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 |
|---|---|---|---|---|
penneys_game.rs | // http://rosettacode.org/wiki/Penney's_game
// H = true, T = false
extern crate rand;
use std::io::{stdout, stdin, Read, Write};
use rand::{Rng, thread_rng};
fn toss_coin(print:bool) -> char {
let c : char;
if thread_rng().gen::<bool>() {c = 'H'} else {c = 'T'}
if print {
print!("{}",c);
... |
fn read_sequence(used_seq : Option<&str>) -> String {
let mut seq = String::new();
loop {
seq.clear();
println!("Please, enter sequence of 3 coins: H (heads) or T (tails): ");
stdin().read_line(&mut seq).ok().expect("failed to read line");
seq = seq.trim().to_uppercase();
... | {
let mut seq = String::new();
match seed {
Some(s) => {
let c0 = s.chars().next().unwrap();
if c0 == 'H' {seq.push('T')
} else {seq.push('H')}
seq.push(c0);
seq.push(s.chars().nth(1).unwrap());
},
None => {
for ... | identifier_body |
penneys_game.rs | // http://rosettacode.org/wiki/Penney's_game
// H = true, T = false
extern crate rand;
use std::io::{stdout, stdin, Read, Write};
use rand::{Rng, thread_rng};
fn toss_coin(print:bool) -> char {
let c : char;
if thread_rng().gen::<bool>() {c = 'H'} else {c = 'T'}
if print {
print!("{}",c);
... | () {
println!("--Penney's game--");
loop {
let useq : String;
let aiseq : String;
if thread_rng().gen::<bool>() {
println!("You choose first!");
useq = read_sequence(None);
println!("Your sequence: {}", useq);
aiseq = gen_sequence( Some(&us... | main | identifier_name |
penneys_game.rs | // http://rosettacode.org/wiki/Penney's_game
// H = true, T = false
extern crate rand;
use std::io::{stdout, stdin, Read, Write};
use rand::{Rng, thread_rng};
fn toss_coin(print:bool) -> char {
let c : char;
if thread_rng().gen::<bool>() {c = 'H'} else {c = 'T'}
if print {
print!("{}",c);
... |
if coins.contains(&aiseq) {
println!("\nI win!");
break;
}
}
println!(" Play again? Y to play, Q to exit.");
let mut input = String::new();
stdin().read_line(&mut input).ok().expect("failed to read line");
match input.char... | {
println!("\nYou win!");
break;
} | conditional_block |
penneys_game.rs | // http://rosettacode.org/wiki/Penney's_game
// H = true, T = false
extern crate rand;
use std::io::{stdout, stdin, Read, Write};
use rand::{Rng, thread_rng};
fn toss_coin(print:bool) -> char {
let c : char;
if thread_rng().gen::<bool>() {c = 'H'} else {c = 'T'}
if print {
print!("{}",c);
... | let mut seq = String::new();
match seed {
Some(s) => {
let c0 = s.chars().next().unwrap();
if c0 == 'H' {seq.push('T')
} else {seq.push('H')}
seq.push(c0);
seq.push(s.chars().nth(1).unwrap());
},
None => {
for _ ... | }
fn gen_sequence(seed : Option<&str>) -> String { | random_line_split |
htmltableheadercellelement.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::HTMLTableHeaderCellElementBinding;
use dom::bindings::js::Root;
use dom::bin... | (localName: Atom,
prefix: Option<DOMString>,
document: &Document) -> Root<HTMLTableHeaderCellElement> {
Node::reflect_node(box HTMLTableHeaderCellElement::new_inherited(localName, prefix, document),
document,
HTMLTableHeaderCell... | new | identifier_name |
htmltableheadercellelement.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::HTMLTableHeaderCellElementBinding;
use dom::bindings::js::Root;
use dom::bin... |
}
| {
Node::reflect_node(box HTMLTableHeaderCellElement::new_inherited(localName, prefix, document),
document,
HTMLTableHeaderCellElementBinding::Wrap)
} | identifier_body |
htmltableheadercellelement.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::HTMLTableHeaderCellElementBinding;
use dom::bindings::js::Root; |
#[dom_struct]
pub struct HTMLTableHeaderCellElement {
htmltablecellelement: HTMLTableCellElement,
}
impl HTMLTableHeaderCellElement {
fn new_inherited(localName: Atom,
prefix: Option<DOMString>,
document: &Document) -> HTMLTableHeaderCellElement {
HTMLTableHea... | use dom::bindings::str::DOMString;
use dom::document::Document;
use dom::htmltablecellelement::HTMLTableCellElement;
use dom::node::Node;
use string_cache::Atom; | random_line_split |
catalog.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 std::collections::BTreeMap;
use std::path::{Path, PathBuf};
use rusqlite::{params, Connection};
use crate::coll... |
}
&self.libfiles
}
/// Get the libfiles. This assume the libfiles have been loaded first.
/// This allow non-mutable borrowing that would be caused by `load_libfiles()`.
pub fn libfiles(&self) -> &Vec<LibraryFile> {
&self.libfiles
}
/// Load images.
pub fn load_ima... | {
let mut result = Catalog::load_objects::<LibraryFile>(conn, self.catalog_version);
self.libfiles.append(&mut result);
} | conditional_block |
catalog.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 std::collections::BTreeMap;
use std::path::{Path, PathBuf};
use rusqlite::{params, Connection};
use crate::coll... | };
}
if let Some(root_keyword_id) = self.get_variable::<f64>("AgLibraryKeyword_rootTagID") {
self.root_keyword_id = root_keyword_id.round() as LrId;
}
}
/// Generic object loader leveraging the FromDb protocol
fn load_objects<T: FromDb>(conn: &Connection, ca... | random_line_split | |
catalog.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 std::collections::BTreeMap;
use std::path::{Path, PathBuf};
use rusqlite::{params, Connection};
use crate::coll... | (&self) -> &BTreeMap<LrId, Keyword> {
&self.keywords
}
/// Load folders.
pub fn load_folders(&mut self) -> &Folders {
if self.folders.is_empty() {
if let Some(ref conn) = self.dbconn {
let folders = Catalog::load_objects::<RootFolder>(conn, self.catalog_version);... | keywords | identifier_name |
catalog.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 std::collections::BTreeMap;
use std::path::{Path, PathBuf};
use rusqlite::{params, Connection};
use crate::coll... |
/// Load collectons.
pub fn load_collections(&mut self) -> &Vec<Collection> {
if self.collections.is_empty() {
if let Some(ref conn) = self.dbconn {
let mut collections =
Catalog::load_objects::<Collection>(conn, self.catalog_version);
fo... | {
&self.images
} | identifier_body |
opts.rs | enable it and
/// cause it to produce output on that interval (`-p`).
pub time_profiler_period: Option<f64>,
/// `None` to disable the memory profiler or `Some` with an interval in seconds to enable it
/// and cause it to produce output on that interval (`-m`).
pub mem_profiler_period: Option<f64>... | {
/// List all the debug options.
pub help: bool,
/// Bubble intrinsic widths separately like other engines.
pub bubble_widths: bool,
/// Disable antialiasing of rendered text.
pub disable_text_aa: bool,
/// Disable antialiasing of rendered text on the HTML canvas element.
pub disabl... | DebugOptions | identifier_name |
opts.rs | Periodically print out on which events script tasks spend their processing time.
pub profile_script_events: bool,
/// `None` to disable devtools or `Some` with a port number to start a server to listen to
/// remote Firefox devtools connections.
pub devtools_port: Option<u16>,
/// `None` to disab... | unsafe {
assert!(DEFAULT_OPTIONS.is_null());
assert!(DEFAULT_OPTIONS != INVALID_OPTIONS);
let box_opts = box opts;
DEFAULT_OPTIONS = Box::into_raw(box_opts);
}
}
#[ | identifier_body | |
opts.rs | to enable it and
/// cause it to produce output on that interval (`-p`).
pub time_profiler_period: Option<f64>,
/// `None` to disable the memory profiler or `Some` with an interval in seconds to enable it
/// and cause it to produce output on that interval (`-m`).
pub mem_profiler_period: Option<f... | Some(ua) => ua,
None => default_user_agent_string(DEFAULT_USER_AGENT),
};
let user_stylesheets = opt_match.opt_strs("user-stylesheet").iter().map(|filename| {
let path = cwd.join(filename);
let url = Url::from_file_path(&path).unwrap();
let mut contents = Vec::new();
... | random_line_split | |
symtab.rs | use std::rc::Rc;
use std::cell::RefCell;
use std::collections::HashMap;
use std::fmt;
pub struct SymTab {
parent: Option<Rc<SymTab>>,
names: RefCell<HashMap<String, usize>>,
}
impl SymTab {
pub fn new(parent: Rc<SymTab>, names: &[Rc<String>]) -> SymTab {
let mut hash_names = HashMap::new();
... | if let Some(index) = self.names.borrow().get(name) {
return *index
}
let new_index = self.names.borrow().len();
self.names.borrow_mut().insert(name.to_string(), new_index);
new_index
}
pub fn get_name(&self, name: &str) -> Option<(usize, usize)> {
s... | }
}
pub fn add_name(&self, name: &str) -> usize { | random_line_split |
symtab.rs | use std::rc::Rc;
use std::cell::RefCell;
use std::collections::HashMap;
use std::fmt;
pub struct SymTab {
parent: Option<Rc<SymTab>>,
names: RefCell<HashMap<String, usize>>,
}
impl SymTab {
pub fn new(parent: Rc<SymTab>, names: &[Rc<String>]) -> SymTab {
let mut hash_names = HashMap::new();
... |
let new_index = self.names.borrow().len();
self.names.borrow_mut().insert(name.to_string(), new_index);
new_index
}
pub fn get_name(&self, name: &str) -> Option<(usize, usize)> {
self.get_name_internal(name, 0)
}
fn get_name_internal(&self, name: &str, env_index: usi... | {
return *index
} | conditional_block |
symtab.rs | use std::rc::Rc;
use std::cell::RefCell;
use std::collections::HashMap;
use std::fmt;
pub struct | {
parent: Option<Rc<SymTab>>,
names: RefCell<HashMap<String, usize>>,
}
impl SymTab {
pub fn new(parent: Rc<SymTab>, names: &[Rc<String>]) -> SymTab {
let mut hash_names = HashMap::new();
for (i, name) in names.iter().enumerate() {
hash_names.insert((**name).clone(), i);
... | SymTab | identifier_name |
err.rs |
use sys;
pub struct Error {
priv n:int
}
pub enum ErrorResult<T> {
Ok(T),
Err(Error)
}
impl Error {
#[inline(always)]
pub fn is_err(&self) -> bool {
self.n!= 0
}
#[inline(always)]
pub fn msg(&self) -> &'static str {
msg(-1*self.n)
}
#[inline(always)]
pub... |
}
impl<T> ErrorResult<T> {
#[inline]
pub fn unwrap(self) -> T {
match self {
Ok(d) => d,
Err(err) => sys::fail(err.msg())
}
}
#[inline]
pub fn is_error(&self) -> bool {
match *self {
Ok(_) => false,
Err(a) => a.is_err()
... | {
(-1*self.n) == code
} | identifier_body |
err.rs | use sys;
pub struct Error {
priv n:int
}
pub enum ErrorResult<T> {
Ok(T),
Err(Error)
}
impl Error {
#[inline(always)]
pub fn is_err(&self) -> bool {
self.n!= 0
}
#[inline(always)]
pub fn msg(&self) -> &'static str {
msg(-1*self.n)
}
#[inline(always)]
pub ... | pub static EADDRINUSE : int = 98;
pub static EADDRNOTAVAIL : int = 99;
pub static ENETDOWN : int = 100;
pub static ENETUNREACH : int = 101;
pub static ENETRESET : int = 102;
pub static ECONNABORTED : int = 103;
pub static ECONNRESET : int = 104;
pub static ENOBUFS : int = 105;
pu... | random_line_split | |
err.rs |
use sys;
pub struct Error {
priv n:int
}
pub enum ErrorResult<T> {
Ok(T),
Err(Error)
}
impl Error {
#[inline(always)]
pub fn is_err(&self) -> bool {
self.n!= 0
}
#[inline(always)]
pub fn msg(&self) -> &'static str {
msg(-1*self.n)
}
#[inline(always)]
pub... |
}
}
| {
"Unknown Error"
} | conditional_block |
err.rs |
use sys;
pub struct Error {
priv n:int
}
pub enum ErrorResult<T> {
Ok(T),
Err(Error)
}
impl Error {
#[inline(always)]
pub fn is_err(&self) -> bool {
self.n!= 0
}
#[inline(always)]
pub fn msg(&self) -> &'static str {
msg(-1*self.n)
}
#[inline(always)]
pub... | (&self) -> bool {
match *self {
Ok(_) => false,
Err(a) => a.is_err()
}
}
}
pub static EPERM : int = 1;
pub static ENOENT : int = 2;
pub static ESRCH : int = 3;
pub static EINTR : int = 4;
pub static EIO : int = 5;
pub s... | is_error | identifier_name |
client.rs | use std::io;
use error::RbtError;
use amqp::{self, Session, Options, Channel};
use amqp::protocol::basic::{Deliver, BasicProperties};
use amqp::Basic;
use amqp::{Table, TableEntry};
use std::thread;
use std::time::Duration;
use std::sync::mpsc;
use std::error::Error;
pub struct Sendable {
pub exchange: String,
... | pub rpctimeout: u64
}
pub type ReceiveCb = FnMut(&mut Channel, Deliver, BasicProperties, Vec<u8>) -> Result<(), RbtError> + Send;
pub struct Receiver {
pub exchange:String,
pub routing_key: Option<String>,
pub auto_ack: bool,
pub callback:Box<ReceiveCb>,
}
pub fn open_send(o:Options, s:Sendable,... | pub reader: Box<io::Read>,
pub priority: u8, | random_line_split |
client.rs | use std::io;
use error::RbtError;
use amqp::{self, Session, Options, Channel};
use amqp::protocol::basic::{Deliver, BasicProperties};
use amqp::Basic;
use amqp::{Table, TableEntry};
use std::thread;
use std::time::Duration;
use std::sync::mpsc;
use std::error::Error;
pub struct Sendable {
pub exchange: String,
... |
// send properties
let mut props = BasicProperties {
content_type: Some(s.content_type),
headers: Some(headers),
priority: Some(s.priority),
..Default::default()
};
// if we are doing rpc, there is a receiver in this optional
let isrpc = match r {
Some(receiv... | {
// open the channel
let (mut session, mut channel) = _open(o)?;
// table of headers, parsed from input
let mut headers = Table::new();
for st in s.headers {
let idx = st.find(':').ok_or("Header must have a :")?;
let (name, value) = st.split_at(idx);
let key = name.trim();... | identifier_body |
client.rs | use std::io;
use error::RbtError;
use amqp::{self, Session, Options, Channel};
use amqp::protocol::basic::{Deliver, BasicProperties};
use amqp::Basic;
use amqp::{Table, TableEntry};
use std::thread;
use std::time::Duration;
use std::sync::mpsc;
use std::error::Error;
pub struct Sendable {
pub exchange: String,
... | if err.description() == "timed out waiting on channel".to_string() {
println!("Error timeout");
}
}
}
}
session.close(200, "Good Bye");
}
else {
// and unwind if not rpc
channel.close(200, "B... | {
let (tx, rx) = mpsc::channel();
thread::Builder::new().name("consumer_thread".to_string()).spawn(move || {
channel.start_consuming();
tx.send(channel).unwrap();
}).unwrap();
let timeout = s.rpctimeout;
if timeout == 0 {
// Block forever unt... | conditional_block |
client.rs | use std::io;
use error::RbtError;
use amqp::{self, Session, Options, Channel};
use amqp::protocol::basic::{Deliver, BasicProperties};
use amqp::Basic;
use amqp::{Table, TableEntry};
use std::thread;
use std::time::Duration;
use std::sync::mpsc;
use std::error::Error;
pub struct Sendable {
pub exchange: String,
... | {
pub exchange:String,
pub routing_key: Option<String>,
pub auto_ack: bool,
pub callback:Box<ReceiveCb>,
}
pub fn open_send(o:Options, s:Sendable, r:Option<Receiver>) -> Result<(),RbtError> {
// open the channel
let (mut session, mut channel) = _open(o)?;
// table of headers, parsed fro... | Receiver | identifier_name |
retention.rs | use crate::{Error, FsStats};
use iml_command_utils::wait_for_cmds_success;
use iml_influx::{Client as InfluxClient, InfluxClientExt as _};
use iml_manager_client::{graphql, Client};
use iml_postgres::{sqlx, PgPool};
use iml_tracing::tracing;
use iml_wire_types::{snapshot, Command};
use std::collections::HashMap;
async... |
Ok(None)
}
async fn get_snapshots(
pool: &sqlx::PgPool,
fs_name: &str,
) -> Result<Vec<snapshot::SnapshotRecord>, Error> {
let xs = sqlx::query_as!(
snapshot::SnapshotRecord,
"SELECT * FROM snapshot WHERE filesystem_name = $1 ORDER BY create_time ASC",
fs_name
)
.fetch_... | {
if nodes.is_empty() {
return Ok(None);
} else {
let bytes_avail = nodes[0].bytes_avail;
let bytes_total = nodes[0].bytes_total;
let bytes_free = nodes[0].bytes_free;
let bytes_used = bytes_total - bytes_free;
return Ok(Some((byte... | conditional_block |
retention.rs | use crate::{Error, FsStats};
use iml_command_utils::wait_for_cmds_success;
use iml_influx::{Client as InfluxClient, InfluxClientExt as _};
use iml_manager_client::{graphql, Client};
use iml_postgres::{sqlx, PgPool};
use iml_tracing::tracing;
use iml_wire_types::{snapshot, Command};
use std::collections::HashMap;
async... | "stats record: {:?} - bytes free: {}",
stats_record.get(&fs_name),
bytes_free
);
let retention = get_retention_policy(pool, &fs_name).await?;
if let Some(retention) = retention {
let snapshots = get_snapshots(pool, &fs_... | {
let filesystems = get_retention_filesystems(pool).await?;
tracing::debug!("Filesystems with retentions: {:?}", filesystems);
for fs_name in filesystems {
let stats = get_stats_from_influx(&fs_name, &influx_client).await?;
if let Some((bytes_avail, bytes_free, bytes_used)) = stats {
... | identifier_body |
retention.rs | use crate::{Error, FsStats};
use iml_command_utils::wait_for_cmds_success;
use iml_influx::{Client as InfluxClient, InfluxClientExt as _};
use iml_manager_client::{graphql, Client};
use iml_postgres::{sqlx, PgPool};
use iml_tracing::tracing;
use iml_wire_types::{snapshot, Command};
use std::collections::HashMap;
async... | );
let retention = get_retention_policy(pool, &fs_name).await?;
if let Some(retention) = retention {
let snapshots = get_snapshots(pool, &fs_name).await?;
tracing::debug!(
"percent_left: {}, reserve value: {}",
... | bytes_free | random_line_split |
retention.rs | use crate::{Error, FsStats};
use iml_command_utils::wait_for_cmds_success;
use iml_influx::{Client as InfluxClient, InfluxClientExt as _};
use iml_manager_client::{graphql, Client};
use iml_postgres::{sqlx, PgPool};
use iml_tracing::tracing;
use iml_wire_types::{snapshot, Command};
use std::collections::HashMap;
async... | (
client: Client,
influx_client: InfluxClient,
pool: PgPool,
) -> Result<(), Error> {
let mut prev_stats: HashMap<String, u64> = vec![].into_iter().collect::<HashMap<String, u64>>();
loop {
prev_stats =
match process_retention(&client, &influx_client, &pool, prev_stats.clone()).... | handle_retention_rules | identifier_name |
rlptraits.rs | // Copyright 2015, 2016 Ethcore (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.... |
}
/// Encodable wrapper trait required to handle special case of encoding a &[u8] as string and not as list
pub trait RlpEncodable {
/// Append a value to the stream
fn rlp_append(&self, s: &mut RlpStream);
}
/// RLP encoding stream
pub trait Stream: Sized {
/// Initializes instance of empty `Stream`.
fn new() ... | {
let mut s = RlpStream::new();
self.rlp_append(&mut s);
s.drain()
} | identifier_body |
rlptraits.rs | // Copyright 2015, 2016 Ethcore (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.... | (&self) -> ElasticArray1024<u8> {
let mut s = RlpStream::new();
self.rlp_append(&mut s);
s.drain()
}
}
/// Encodable wrapper trait required to handle special case of encoding a &[u8] as string and not as list
pub trait RlpEncodable {
/// Append a value to the stream
fn rlp_append(&self, s: &mut RlpStream);
}
... | rlp_bytes | identifier_name |
rlptraits.rs | // Copyright 2015, 2016 Ethcore (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.... | /// fn main () {
/// let data = vec![0xc8, 0x83, b'c', b'a', b't', 0x83, b'd', b'o', b'g'];
/// let rlp = Rlp::new(&data);
/// let strings: Vec<String> = rlp.iter().map(| i | i.as_val()).collect();
/// }
/// ```
fn iter(&'view self) -> Self::Iter;
/// Decode data into an object
fn as_val<T>(&self) -> Resul... | /// extern crate rlp;
/// use rlp::*;
/// | random_line_split |
read_dir.rs | // Copyright 2020 The Chromium OS Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
use std::ffi::CStr;
use std::io::Result;
use std::mem::size_of;
use std::os::unix::io::AsRawFd;
use data_model::DataInit;
use crate::syscall;
#[repr... | () {
assert_eq!(strip_padding(b".\0\0\0\0\0\0\0").to_bytes(), b".");
assert_eq!(strip_padding(b"..\0\0\0\0\0\0").to_bytes(), b"..");
assert_eq!(
strip_padding(b"normal cstring\0").to_bytes(),
b"normal cstring"
);
assert_eq!(strip_padding(b"\0\0\0\0").to_by... | padded_cstrings | identifier_name |
read_dir.rs | // Copyright 2020 The Chromium OS Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
use std::ffi::CStr;
use std::io::Result;
use std::mem::size_of;
use std::os::unix::io::AsRawFd;
use data_model::DataInit;
use crate::syscall;
#[repr... | end: 0,
})
}
// Like `CStr::from_bytes_with_nul` but strips any bytes after the first '\0'-byte. Panics if `b`
// doesn't contain any '\0' bytes.
fn strip_padding(b: &[u8]) -> &CStr {
// It would be nice if we could use memchr here but that's locked behind an unstable gate.
let pos = b
.iter... | Ok(ReadDir {
buf: [0u8; 256],
dir,
current: 0, | random_line_split |
next_back.rs | #![feature(core)]
extern crate core;
#[cfg(test)]
mod tests {
use core::iter::Iterator;
use core::iter::DoubleEndedIterator;
use core::iter::ExactSizeIterator;
use core::iter::Enumerate;
struct A<T> {
begin: T,
end: T
}
macro_rules! Iterator_impl {
($T:ty) => {
impl Iterator for A... | match y {
Some(v) => { assert_eq!(v, (9 - x as usize, 19 - x)); }
None => { assert!(false); }
}
}
assert_eq!(enumerate.next_back(), None::<(usize, T)>);
}
} | random_line_split | |
next_back.rs | #![feature(core)]
extern crate core;
#[cfg(test)]
mod tests {
use core::iter::Iterator;
use core::iter::DoubleEndedIterator;
use core::iter::ExactSizeIterator;
use core::iter::Enumerate;
struct A<T> {
begin: T,
end: T
}
macro_rules! Iterator_impl {
($T:ty) => {
impl Iterator for A... |
}
impl ExactSizeIterator for A<T> {
// fn len(&self) -> usize {
// let (lower, upper) = self.size_hint();
// // Note: This assertion is overly defensive, but it checks the invariant
// // guaranteed by the trait. If this trait were rust-internal,
// // we could use debug_assert!; assert_e... | {
if self.begin < self.end {
self.end = self.end.wrapping_sub(1);
Some::<Self::Item>(self.end)
} else {
None::<Self::Item>
}
} | identifier_body |
next_back.rs | #![feature(core)]
extern crate core;
#[cfg(test)]
mod tests {
use core::iter::Iterator;
use core::iter::DoubleEndedIterator;
use core::iter::ExactSizeIterator;
use core::iter::Enumerate;
struct A<T> {
begin: T,
end: T
}
macro_rules! Iterator_impl {
($T:ty) => {
impl Iterator for A... |
None => { assert!(false); }
}
}
assert_eq!(enumerate.next_back(), None::<(usize, T)>);
}
}
| { assert_eq!(v, (9 - x as usize, 19 - x)); } | conditional_block |
next_back.rs | #![feature(core)]
extern crate core;
#[cfg(test)]
mod tests {
use core::iter::Iterator;
use core::iter::DoubleEndedIterator;
use core::iter::ExactSizeIterator;
use core::iter::Enumerate;
struct A<T> {
begin: T,
end: T
}
macro_rules! Iterator_impl {
($T:ty) => {
impl Iterator for A... | (&mut self) -> Option<Self::Item> {
if self.begin < self.end {
self.end = self.end.wrapping_sub(1);
Some::<Self::Item>(self.end)
} else {
None::<Self::Item>
}
}
}
impl ExactSizeIterator for A<T> {
// fn len(&self) -> usize {
// let (lower, upper) = self.size_hint();
// // Note:... | next_back | identifier_name |
lib.rs | // Copyright GFX Developers 2014-2017
//
// 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 ... | Line, Lines, EmitLines};
pub use triangulate::{EmitTriangles, Triangulate, TriangulateIterator};
pub use indexer::{Indexer, LruIndexer};
pub use neighbors::Neighbors;
mod triangulate;
mod poly;
mod indexer;
mod generator;
mod neighbors;
mod cone;
mod cube;
mod cylinder;
mod plane;
mod sphere;
mod to... | extern crate cgmath;
extern crate mint;
pub use poly::{Quad, Triangle, Polygon, Vertices, VerticesIterator, MapToVertices, MapVertex, | random_line_split |
lib.rs | // Copyright GFX Developers 2014-2017
//
// 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 ... | {
/// Vertex position
pub pos: Position,
/// Vertex normal
pub normal: Normal,
}
| Vertex | identifier_name |
app_lcd_tiva_c.rs | #![feature(plugin)]
#![crate_type="staticlib"]
#![no_std]
extern crate core; |
platformtree!(
tiva_c@mcu {
clock {
source = "MOSC";
xtal = "X16_0MHz";
pll = false;
}
gpio {
a {
d7@5 { direction = "out"; }
}
b {
rs@0 { direction = "out"; }
en@1 { direction = "out"; }
d6@4 { direction = "out"; }
}
e... | extern crate zinc;
#[macro_use] #[plugin] #[no_link] extern crate macro_platformtree;
use zinc::drivers::chario::CharIO;
use zinc::drivers::lcd::hd44780u::{Hd44780u, Font}; | random_line_split |
app_lcd_tiva_c.rs | #![feature(plugin)]
#![crate_type="staticlib"]
#![no_std]
extern crate core;
extern crate zinc;
#[macro_use] #[plugin] #[no_link] extern crate macro_platformtree;
use zinc::drivers::chario::CharIO;
use zinc::drivers::lcd::hd44780u::{Hd44780u, Font};
platformtree!(
tiva_c@mcu {
clock {
source = "MOSC";
... | lcd.custom_char_5x8(1,
[0b00100,
0b01010,
0b00100,
0b11111,
0b00100,
0b01010,
0b10001,
0b00000]);
// Enable blinking
lcd.display_c... | {
let lcd = Hd44780u::new(args.timer,
args.rs,
args.en,
[ args.d4, args.d5, args.d6, args.d7 ]);
lcd.init(true, Font::Font5x8);
// Create custom 'heart' character at index 0.
lcd.custom_char_5x8(0,
[0b00000,
... | identifier_body |
app_lcd_tiva_c.rs | #![feature(plugin)]
#![crate_type="staticlib"]
#![no_std]
extern crate core;
extern crate zinc;
#[macro_use] #[plugin] #[no_link] extern crate macro_platformtree;
use zinc::drivers::chario::CharIO;
use zinc::drivers::lcd::hd44780u::{Hd44780u, Font};
platformtree!(
tiva_c@mcu {
clock {
source = "MOSC";
... | (args: &pt::run_args) {
let lcd = Hd44780u::new(args.timer,
args.rs,
args.en,
[ args.d4, args.d5, args.d6, args.d7 ]);
lcd.init(true, Font::Font5x8);
// Create custom 'heart' character at index 0.
lcd.custom_char_5x8(0,
... | run | identifier_name |
vec_resource.rs | use super::{Resource, ResourceSeek};
use alloc::boxed::Box;
use collections::{String, Vec};
use core::cmp::{max, min};
use system::error::Result;
use system::syscall::Stat;
/// A vector resource
pub struct VecResource {
path: String,
data: Vec<u8>,
mode: u16,
seek: usize,
}
impl VecResource {
... |
fn truncate(&mut self, len: usize) -> Result<()> {
while len > self.data.len() {
self.data.push(0);
}
self.data.truncate(len);
self.seek = min(self.seek, self.data.len());
Ok(())
}
}
| {
Ok(())
} | identifier_body |
vec_resource.rs | use super::{Resource, ResourceSeek};
use alloc::boxed::Box;
use collections::{String, Vec};
use core::cmp::{max, min};
use system::error::Result;
use system::syscall::Stat;
/// A vector resource
pub struct VecResource {
path: String,
data: Vec<u8>,
mode: u16,
seek: usize,
}
impl VecResource {
... | (&mut self) -> Result<()> {
Ok(())
}
fn truncate(&mut self, len: usize) -> Result<()> {
while len > self.data.len() {
self.data.push(0);
}
self.data.truncate(len);
self.seek = min(self.seek, self.data.len());
Ok(())
}
}
| sync | identifier_name |
vec_resource.rs | use super::{Resource, ResourceSeek};
use alloc::boxed::Box;
use collections::{String, Vec};
use core::cmp::{max, min};
use system::error::Result;
use system::syscall::Stat;
/// A vector resource
pub struct VecResource {
path: String,
data: Vec<u8>,
mode: u16,
seek: usize,
}
impl VecResource {
... | ResourceSeek::Start(offset) => self.seek = min(self.data.len(), offset),
ResourceSeek::Current(offset) =>
self.seek = max(0, min(self.seek as isize, self.seek as isize + offset)) as usize,
ResourceSeek::End(offset) =>
self.seek = max(0,
... | random_line_split | |
filemanager_thread.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 ipc_channel::ipc::IpcSender;
use std::path::PathBuf;
use super::{LoadConsumer, LoadData};
#[derive(Clone, Deb... |
/// Read file, return the bytes
ReadFile(IpcSender<FileManagerResult<Vec<u8>>>, SelectedFileId),
/// Delete the FileID entry
DeleteFileID(SelectedFileId),
/// Load resource by Blob URL
LoadBlob(LoadData, LoadConsumer),
/// Shut down this thread
Exit,
}
pub type FileManagerResult<T> ... | SelectFile(Vec<FilterPattern>, IpcSender<FileManagerResult<SelectedFile>>),
/// Select multiple files, return a vector of triples
SelectFiles(Vec<FilterPattern>, IpcSender<FileManagerResult<Vec<SelectedFile>>>), | random_line_split |
filemanager_thread.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 ipc_channel::ipc::IpcSender;
use std::path::PathBuf;
use super::{LoadConsumer, LoadData};
#[derive(Clone, Deb... | (pub String);
#[derive(Deserialize, Serialize)]
pub enum FileManagerThreadMsg {
/// Select a single file, return triple (FileID, FileName, lastModified)
SelectFile(Vec<FilterPattern>, IpcSender<FileManagerResult<SelectedFile>>),
/// Select multiple files, return a vector of triples
SelectFiles(Vec<Fil... | FilterPattern | identifier_name |
date.rs | use header::HttpDate;
header! {
/// `Date` header, defined in [RFC7231](http://tools.ietf.org/html/rfc7231#section-7.1.1.2)
///
/// The `Date` header field represents the date and time at which the
/// message was originated.
///
/// # ABNF
/// ```plain
/// Date = HTTP-date
/// ```
... | (Date, "Date") => [HttpDate]
test_date {
test_header!(test1, vec![b"Tue, 15 Nov 1994 08:12:31 GMT"]);
}
}
bench_header!(imf_fixdate, Date, { vec![b"Sun, 07 Nov 1994 08:48:37 GMT".to_vec()] });
bench_header!(rfc_850, Date, { vec![b"Sunday, 06-Nov-94 08:49:37 GMT".to_vec()] });
bench_header!(asctime... | /// use std::time::SystemTime;
///
/// let mut headers = Headers::new();
/// headers.set(Date(SystemTime::now().into()));
/// ``` | random_line_split |
file.rs | // Copyright 2018 Google Inc. All rights reserved.
//
// 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... | }
fn try_load_file<P>(path: P) -> Result<(Rope, FileInfo), FileError>
where P: AsRef<Path>
{
// TODO: support for non-utf8
// it's arguable that the rope crate should have file loading functionality
let mut f = File::open(path.as_ref())?;
let mod_time = f.metadata()?.modified().ok();
let mut bytes ... | } | random_line_split |
file.rs | // Copyright 2018 Google Inc. All rights reserved.
//
// 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... |
fn try_decode(bytes: Vec<u8>,
encoding: CharacterEncoding) -> Result<Rope, FileError> {
match encoding {
CharacterEncoding::Utf8 =>
Ok(Rope::from(str::from_utf8(&bytes)?)),
CharacterEncoding::Utf8WithBom => {
let s = String::from_utf8(bytes).map_err(|e| e.utf8... | {
let mut f = File::create(path)?;
match encoding {
CharacterEncoding::Utf8WithBom => f.write_all(UTF8_BOM.as_bytes())?,
CharacterEncoding::Utf8 => (),
}
for chunk in text.iter_chunks(0, text.len()) {
f.write_all(chunk.as_bytes())?;
}
Ok((... | identifier_body |
file.rs | // Copyright 2018 Google Inc. All rights reserved.
//
// 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... | else {
let encoding = self.file_info.get(&id).unwrap().encoding;
try_save(path, text, encoding)?;
self.file_info.get_mut(&id).unwrap()
.mod_time = get_mod_time(path);
}
Ok(())
}
}
fn try_load_file<P>(path: P) -> Result<(Rope, FileInfo), FileError>... | {
return Err(FileError::HasChanged);
} | conditional_block |
file.rs | // Copyright 2018 Google Inc. All rights reserved.
//
// 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... | (&mut self, path: &Path, text: &Rope, id: BufferId)
-> Result<(), FileError>
{
let prev_path = self.file_info.get(&id).unwrap().path.clone();
if prev_path!= path {
self.save_new(path, text, id)?;
self.open_files.remove(&prev_path);
#[cfg(feature = "notify"... | save_existing | identifier_name |
strings.rs | pub fn strings() {
string_concatenation();
string_indexing();
string_slices();
iterating_over_strings();
}
fn | () {
let s1 = String::from("Hello");
let s2 = String::from(", world!");
// Various approaches to concatenating strings
let mut s = s1.clone();
s.push_str(", world!");
let mut s = s1.clone();
let mut s = String::from("Hello");
let s = s1 + &s2; // NOTE: s1 is moved
}
fn string_indexi... | string_concatenation | identifier_name |
strings.rs | pub fn strings() {
string_concatenation();
string_indexing();
string_slices();
iterating_over_strings();
}
fn string_concatenation() { |
// Various approaches to concatenating strings
let mut s = s1.clone();
s.push_str(", world!");
let mut s = s1.clone();
let mut s = String::from("Hello");
let s = s1 + &s2; // NOTE: s1 is moved
}
fn string_indexing() {
// NOTE: Strings do not support indexing
// See: https://doc.rust... | let s1 = String::from("Hello");
let s2 = String::from(", world!"); | random_line_split |
strings.rs | pub fn strings() {
string_concatenation();
string_indexing();
string_slices();
iterating_over_strings();
}
fn string_concatenation() {
let s1 = String::from("Hello");
let s2 = String::from(", world!");
// Various approaches to concatenating strings
let mut s = s1.clone();
s.push_st... | s() {
let s = "नमस्ते";
for c in s.chars() {
println!("{}", c);
}
for b in s.bytes() {
println!("{}", b);
}
}
| llo = "Здравствуйте";
println!("{}", &hello[..4]); // Зд
// println!("{}", &hello[..3]); // Error: panic
// let z = &hello[..1]; // Error: panic
}
fn iterating_over_string | identifier_body |
test_readlink.rs | use common::util::*;
static GIBBERISH: &'static str = "supercalifragilisticexpialidocious";
#[test]
fn test_canonicalize() {
let (at, mut ucmd) = at_and_ucmd!();
ucmd.arg("-f")
.arg(".")
.run() | #[test]
fn test_canonicalize_existing() {
let (at, mut ucmd) = at_and_ucmd!();
ucmd.arg("-e")
.arg(".")
.run()
.stdout_is(at.root_dir_resolved());
}
#[test]
fn test_canonicalize_missing() {
let (at, mut ucmd) = at_and_ucmd!();
let expected = path_concat!(at.root_dir_resolved(), GIB... | .stdout_is(at.root_dir_resolved());
}
| random_line_split |
test_readlink.rs | use common::util::*;
static GIBBERISH: &'static str = "supercalifragilisticexpialidocious";
#[test]
fn test_canonicalize() |
#[test]
fn test_canonicalize_existing() {
let (at, mut ucmd) = at_and_ucmd!();
ucmd.arg("-e")
.arg(".")
.run()
.stdout_is(at.root_dir_resolved());
}
#[test]
fn test_canonicalize_missing() {
let (at, mut ucmd) = at_and_ucmd!();
let expected = path_concat!(at.root_dir_resolved(), G... | {
let (at, mut ucmd) = at_and_ucmd!();
ucmd.arg("-f")
.arg(".")
.run()
.stdout_is(at.root_dir_resolved());
} | identifier_body |
test_readlink.rs | use common::util::*;
static GIBBERISH: &'static str = "supercalifragilisticexpialidocious";
#[test]
fn test_canonicalize() {
let (at, mut ucmd) = at_and_ucmd!();
ucmd.arg("-f")
.arg(".")
.run()
.stdout_is(at.root_dir_resolved());
}
#[test]
fn | () {
let (at, mut ucmd) = at_and_ucmd!();
ucmd.arg("-e")
.arg(".")
.run()
.stdout_is(at.root_dir_resolved());
}
#[test]
fn test_canonicalize_missing() {
let (at, mut ucmd) = at_and_ucmd!();
let expected = path_concat!(at.root_dir_resolved(), GIBBERISH);
ucmd.arg("-m")
.a... | test_canonicalize_existing | identifier_name |
rustc-diagnostics-1.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 ... |
__build_diagnostic_array!(DIAGNOSTICS)
//~^ WARN diagnostic code E0003 never used
| {
__diagnostic_used!(E0002);
//~^ ERROR unknown diagnostic code E0002
__diagnostic_used!(E0001);
//~^ NOTE previous invocation
__diagnostic_used!(E0001);
//~^ WARNING diagnostic code E0001 already used
} | identifier_body |
rustc-diagnostics-1.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 ... | () {
__diagnostic_used!(E0002);
//~^ ERROR unknown diagnostic code E0002
__diagnostic_used!(E0001);
//~^ NOTE previous invocation
__diagnostic_used!(E0001);
//~^ WARNING diagnostic code E0001 already used
}
__build_diagnostic_array!(DIAGNOSTICS)
//~^ WARN diagnostic code E0003 never used
| main | identifier_name |
rustc-diagnostics-1.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 ... | __build_diagnostic_array!(DIAGNOSTICS)
//~^ WARN diagnostic code E0003 never used | //~^ WARNING diagnostic code E0001 already used
}
| random_line_split |
util.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, trait_ref: &ty::TraitRef<'tcx>) {
let ty::ParamBounds { builtin_bounds, mut trait_bounds,.. } =
ty::bounds_for_trait_ref(self.tcx, trait_ref);
for builtin_bound in builtin_bounds.iter() {
let bound_trait_ref = trait_ref_for_builtin_bound(self.tcx,
... | push | identifier_name |
util.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 ... | d.repr(tcx)
}
}
}
impl<'tcx, N:Repr<'tcx>> Repr<'tcx> for super::VtableImplData<'tcx, N> {
fn repr(&self, tcx: &ty::ctxt<'tcx>) -> String {
format!("VtableImpl(impl_def_id={}, substs={}, nested={})",
self.impl_def_id.repr(tcx),
self.substs.repr(tc... |
super::VtableParam(ref v) =>
format!("VtableParam({})", v.repr(tcx)),
super::VtableBuiltin(ref d) => | random_line_split |
util.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... |
}
| {
ty::type_err_to_str(tcx, self)
} | identifier_body |
errors.rs | //! Error types.
//!
//! Some events are handled are errors so that they propagate upwards naturally, although
//! technically they're not really errors:
//!
//! - [`ErrorKind::Unsat`]
//! - [`ErrorKind::Timeout`]
//! - [`ErrorKind::Unknown`] (when hoice gave up on solving the clauses)
//!
//! As such, one should **not... |
}
false
}
/// True if the kind of the error is [`ErrorKind::Unknown`][unknown].
///
/// [unknown]: enum.ErrorKind.html#variant.Unknown
/// (ErrorKind's Unknown variant)
pub fn is_unknown(&self) -> bool {
for err in self.iter() {
if err.to_string() == consts:... | {
return true;
} | conditional_block |
errors.rs | //! Error types.
//!
//! Some events are handled are errors so that they propagate upwards naturally, although
//! technically they're not really errors:
//!
//! - [`ErrorKind::Unsat`]
//! - [`ErrorKind::Timeout`]
//! - [`ErrorKind::Unknown`] (when hoice gave up on solving the clauses)
//!
//! As such, one should **not... | (&self) -> Option<ClsIdx> {
match self.kind() {
ErrorKind::UnsatFrom(clause) => Some(*clause),
_ => None,
}
}
/// True if the kind of the error is a timeout.
///
/// [timeout]: enum.ErrorKind.html#variant.Timeout
/// (ErrorKind's Timeout variant)
pub fn i... | unsat_cause | identifier_name |
errors.rs | //! Error types.
//!
//! Some events are handled are errors so that they propagate upwards naturally, although
//! technically they're not really errors:
//!
//! - [`ErrorKind::Unsat`]
//! - [`ErrorKind::Timeout`]
//! - [`ErrorKind::Unknown`] (when hoice gave up on solving the clauses)
//!
//! As such, one should **not... | #[doc = "Not really an error, unsat early return."]
Unsat {
description(consts::err::unsat_desc)
display("unsat")
}
#[doc = "Not really an error, unsat early return because of some clause."]
UnsatFrom(clause: ClsIdx) {
description(consts::err::... | random_line_split | |
main.rs | extern crate clap;
extern crate env_logger;
extern crate habitat_common as common;
extern crate habitat_core as hcore;
extern crate habitat_pkg_export_tar as export_tar;
#[macro_use]
extern crate log;
use clap::App;
use common::ui::{UIWriter, UI};
use hcore::PROGRAM_NAME;
use export_tar::{Cli, Result};
fn main() {
... |
export_tar::export_for_cli_matches(ui, &m)
}
fn cli<'a, 'b>() -> App<'a, 'b> {
let name: &str = &*PROGRAM_NAME;
let about = "Creates a tar package from a Habitat package";
Cli::new(name, about)
.add_base_packages_args()
.add_builder_args()
.add_pkg_ident_arg()
.app
} | let cli = cli();
let m = cli.get_matches();
debug!("clap cli args: {:?}", m); | random_line_split |
main.rs | extern crate clap;
extern crate env_logger;
extern crate habitat_common as common;
extern crate habitat_core as hcore;
extern crate habitat_pkg_export_tar as export_tar;
#[macro_use]
extern crate log;
use clap::App;
use common::ui::{UIWriter, UI};
use hcore::PROGRAM_NAME;
use export_tar::{Cli, Result};
fn main() {
... |
}
fn start(ui: &mut UI) -> Result<()> {
env_logger::init();
let cli = cli();
let m = cli.get_matches();
debug!("clap cli args: {:?}", m);
export_tar::export_for_cli_matches(ui, &m)
}
fn cli<'a, 'b>() -> App<'a, 'b> {
let name: &str = &*PROGRAM_NAME;
let about = "Creates a tar package fro... | {
ui.fatal(e).unwrap();
std::process::exit(1)
} | conditional_block |
main.rs | extern crate clap;
extern crate env_logger;
extern crate habitat_common as common;
extern crate habitat_core as hcore;
extern crate habitat_pkg_export_tar as export_tar;
#[macro_use]
extern crate log;
use clap::App;
use common::ui::{UIWriter, UI};
use hcore::PROGRAM_NAME;
use export_tar::{Cli, Result};
fn main() {
... |
fn cli<'a, 'b>() -> App<'a, 'b> {
let name: &str = &*PROGRAM_NAME;
let about = "Creates a tar package from a Habitat package";
Cli::new(name, about)
.add_base_packages_args()
.add_builder_args()
.add_pkg_ident_arg()
.app
}
| {
env_logger::init();
let cli = cli();
let m = cli.get_matches();
debug!("clap cli args: {:?}", m);
export_tar::export_for_cli_matches(ui, &m)
} | identifier_body |
main.rs | extern crate clap;
extern crate env_logger;
extern crate habitat_common as common;
extern crate habitat_core as hcore;
extern crate habitat_pkg_export_tar as export_tar;
#[macro_use]
extern crate log;
use clap::App;
use common::ui::{UIWriter, UI};
use hcore::PROGRAM_NAME;
use export_tar::{Cli, Result};
fn main() {
... | <'a, 'b>() -> App<'a, 'b> {
let name: &str = &*PROGRAM_NAME;
let about = "Creates a tar package from a Habitat package";
Cli::new(name, about)
.add_base_packages_args()
.add_builder_args()
.add_pkg_ident_arg()
.app
}
| cli | identifier_name |
transform_assignable_fragment_spreads_in_updatable_queries.rs | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
use common::{NamedItem, WithLocation};
use graphql_ir::{
associated_data_impl, Directive, FragmentDefinition, FragmentSpread,... | (
&mut self,
operation: &FragmentDefinition,
) -> Transformed<FragmentDefinition> {
if operation.directives.named(*UPDATABLE_DIRECTIVE).is_some() {
self.default_transform_fragment(operation)
} else {
Transformed::Keep
}
}
fn transform_fragment... | transform_fragment | identifier_name |
transform_assignable_fragment_spreads_in_updatable_queries.rs | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
use common::{NamedItem, WithLocation};
use graphql_ir::{
associated_data_impl, Directive, FragmentDefinition, FragmentSpread,... | Concrete { concrete_type: StringKey },
}
associated_data_impl!(TypeConditionInfo);
/// Transform all of the updatable queries and fragments in a program by adding
/// an internal-only directive on every fragment spread containing
/// TypeConditionInfo in the associated data.
///
/// This directive is then consume... | Abstract, | random_line_split |
transform_assignable_fragment_spreads_in_updatable_queries.rs | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
use common::{NamedItem, WithLocation};
use graphql_ir::{
associated_data_impl, Directive, FragmentDefinition, FragmentSpread,... |
}
| {
TypeConditionInfo::Concrete {
concrete_type: schema.get_type_name(type_condition),
}
} | conditional_block |
transform_assignable_fragment_spreads_in_updatable_queries.rs | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
use common::{NamedItem, WithLocation};
use graphql_ir::{
associated_data_impl, Directive, FragmentDefinition, FragmentSpread,... |
}
fn get_directive(type_condition: Type, schema: &SDLSchema) -> Directive {
Directive {
name: WithLocation::generated(*ASSIGNABLE_DIRECTIVE_FOR_TYPEGEN),
arguments: vec![],
data: Some(Box::new(get_associated_data(type_condition, schema))),
}
}
fn get_associated_data(type_condition: Ty... | {
let fragment_definition = self
.program
.fragment(fragment_spread.fragment.item)
.expect("Expected fragment to exist.");
let spread = fragment_spread.clone();
Transformed::Replace(Selection::FragmentSpread(Arc::new(FragmentSpread {
directives: v... | identifier_body |
man_pages.rs | use crate::types;
/// Print the given help if the -h or --help argument are found
pub fn check_help(args: &[types::Str], man_page: &'static str) -> bool |
// pub const MAN_FN: &str = r#"NAME
// fn - print a list of all functions or create a function
//
// SYNOPSIS
// fn
//
// fn example arg:int
// echo $arg
// end
//
// DESCRIPTION
// fn prints a list of all functions that exist in the shell or creates a
// function when combined with the 'end' keyword. Functions can h... | {
for arg in args {
if arg == "-h" || arg == "--help" {
println!("{}", man_page);
return true;
}
}
false
} | identifier_body |
man_pages.rs | use crate::types;
/// Print the given help if the -h or --help argument are found
pub fn check_help(args: &[types::Str], man_page: &'static str) -> bool {
for arg in args {
if arg == "-h" || arg == "--help" {
println!("{}", man_page);
return true;
}
}
false | //
// SYNOPSIS
// fn
//
// fn example arg:int
// echo $arg
// end
//
// DESCRIPTION
// fn prints a list of all functions that exist in the shell or creates a
// function when combined with the 'end' keyword. Functions can have type
// hints, to tell ion to check the type of a functions arguments. An error will
// occur... | }
// pub const MAN_FN: &str = r#"NAME
// fn - print a list of all functions or create a function | random_line_split |
man_pages.rs | use crate::types;
/// Print the given help if the -h or --help argument are found
pub fn check_help(args: &[types::Str], man_page: &'static str) -> bool {
for arg in args {
if arg == "-h" || arg == "--help" |
}
false
}
// pub const MAN_FN: &str = r#"NAME
// fn - print a list of all functions or create a function
//
// SYNOPSIS
// fn
//
// fn example arg:int
// echo $arg
// end
//
// DESCRIPTION
// fn prints a list of all functions that exist in the shell or creates a
// function when combined with the 'end' keywor... | {
println!("{}", man_page);
return true;
} | conditional_block |
man_pages.rs | use crate::types;
/// Print the given help if the -h or --help argument are found
pub fn | (args: &[types::Str], man_page: &'static str) -> bool {
for arg in args {
if arg == "-h" || arg == "--help" {
println!("{}", man_page);
return true;
}
}
false
}
// pub const MAN_FN: &str = r#"NAME
// fn - print a list of all functions or create a function
//
// SYNOP... | check_help | identifier_name |
lib.rs | //! Implementation of build script for all Qt crates
//!
//! See [README](https://github.com/rust-qt/ritual) of the repository root for more information.
//!
//! The build script uses `qmake` available in `PATH` to determine paths to the Qt installation and passes them to
//! `ritual_build`.
#![forbid(unsafe_code)]
#!... | })
.collect::<String>();
let project_name = format!("ritual_qt_resources_{}", escaped_base_name);
let out_dir =
PathBuf::from(env::var("OUT_DIR").with_context(|_| "OUT_DIR env var is missing")?);
let dir = out_dir.join(&project_name);
create_dir_all(&dir)?;
let pro_file_path... | {
let path = path.as_ref();
if !path.exists() {
bail!("no such file: {:?}", path);
}
if !path.is_file() {
bail!("not a file: {:?}", path);
}
let base_name = os_str_to_str(
path.file_stem()
.ok_or_else(|| format_err!("can't extract base name from path: {:?}", p... | identifier_body |
lib.rs | //! Implementation of build script for all Qt crates
//!
//! See [README](https://github.com/rust-qt/ritual) of the repository root for more information.
//!
//! The build script uses `qmake` available in `PATH` to determine paths to the Qt installation and passes them to
//! `ritual_build`.
#![forbid(unsafe_code)]
#!... | else {
dir
};
println!("cargo:rustc-link-search={}", path_to_str(&lib_dir)?);
println!("cargo:rerun-if-changed={}", path_to_str(&path)?);
Ok(())
}
/// Calls `try_add_resources` and panic on an error.
pub fn add_resources(path: impl AsRef<Path>) {
try_add_resources(path).fancy_unwrap();
}
... | {
dir.join("release")
} | conditional_block |
lib.rs | //! Implementation of build script for all Qt crates
//!
//! See [README](https://github.com/rust-qt/ritual) of the repository root for more information.
//!
//! The build script uses `qmake` available in `PATH` to determine paths to the Qt installation and passes them to
//! `ritual_build`.
#![forbid(unsafe_code)]
#!... | (crate_name: &str) ->! {
try_run(crate_name).fancy_unwrap();
std::process::exit(0);
}
/// Builds and links a [Qt resource file](https://doc.qt.io/qt-5/resources.html).
///
/// The resource file must also be registered using the `qt_core::q_init_resource` macro.
///
/// Note that the resource file may not be re... | run | identifier_name |
lib.rs | //! Implementation of build script for all Qt crates
//!
//! See [README](https://github.com/rust-qt/ritual) of the repository root for more information.
//!
//! The build script uses `qmake` available in `PATH` to determine paths to the Qt installation and passes them to
//! `ritual_build`.
#![forbid(unsafe_code)]
#!... | writeln!(pro_file, "CONFIG += staticlib")?;
writeln!(pro_file, "SOURCES += 1.cpp")?;
writeln!(pro_file, "RESOURCES += {}", path_to_str(&path)?)?;
drop(pro_file);
let mut cpp_file = create_file(dir.join("1.cpp"))?;
writeln!(cpp_file, "#include <QDir>")?;
// `Q_INIT_RESOURCE` doesn't work ins... |
let pro_file_path = dir.join(format!("{}.pro", project_name));
let mut pro_file = create_file(&pro_file_path)?;
writeln!(pro_file, "TEMPLATE = lib")?; | random_line_split |
multi_err.rs | use std::ffi::CStr;
use std::error;
use std::fmt;
use std::str;
use curl_ffi as ffi;
/* please call curl_multi_perform() or curl_multi_socket*() soon */
pub use curl_ffi::CURLMcode::CURLM_CALL_MULTI_PERFORM as OK;
/* the passed-in handle is not a valid CURLM handle */
pub use curl_ffi::CURLMcode::CURLM_BAD_HANDLE as... | (pub ffi::CURLMcode);
impl ErrCodeM {
pub fn is_success(self) -> bool {
self.code() as i32 == OK as i32
}
pub fn code(self) -> ffi::CURLMcode { let ErrCodeM(c) = self; c }
}
impl fmt::Debug for ErrCodeM {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
fmt::Display::fmt(self, f)... | ErrCodeM | identifier_name |
multi_err.rs | use std::ffi::CStr;
use std::error;
use std::fmt;
use std::str;
use curl_ffi as ffi;
/* please call curl_multi_perform() or curl_multi_socket*() soon */
pub use curl_ffi::CURLMcode::CURLM_CALL_MULTI_PERFORM as OK;
/* the passed-in handle is not a valid CURLM handle */
pub use curl_ffi::CURLMcode::CURLM_BAD_HANDLE as... |
}
| {
let code = self.code();
let s = unsafe {
CStr::from_ptr(ffi::curl_multi_strerror(code) as *const _).to_bytes()
};
str::from_utf8(s).unwrap()
} | identifier_body |
multi_err.rs | use std::ffi::CStr;
use std::error;
use std::fmt;
use std::str;
use curl_ffi as ffi;
/* please call curl_multi_perform() or curl_multi_socket*() soon */
pub use curl_ffi::CURLMcode::CURLM_CALL_MULTI_PERFORM as OK;
/* the passed-in handle is not a valid CURLM handle */
pub use curl_ffi::CURLMcode::CURLM_BAD_HANDLE as... | str::from_utf8(s).unwrap()
}
} | }; | random_line_split |
main.rs | // Copyright 2013 The GLFW-RS Developers. For a full listing of the authors,
// refer to the AUTHORS file at the top-level directory of this distribution.
//
// 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... | // 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.
extern mod glfw;
#[start]
fn start(argc: int, argv: **u8) -> int {
std::rt::start_on_main_thread(argc, argv, main)
}
fn main() {
... | // http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS, | random_line_split |
main.rs | // Copyright 2013 The GLFW-RS Developers. For a full listing of the authors,
// refer to the AUTHORS file at the top-level directory of this distribution.
//
// 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... | () {
do glfw::start {
do glfw::Monitor::get_primary().map |monitor| {
println!("{:s}:", monitor.get_name());
println!(" {:s}\n", monitor.get_video_mode().unwrap().to_str());
};
println("Available monitors\n\
------------------");
... | main | identifier_name |
main.rs | // Copyright 2013 The GLFW-RS Developers. For a full listing of the authors,
// refer to the AUTHORS file at the top-level directory of this distribution.
//
// 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... |
fn main() {
do glfw::start {
do glfw::Monitor::get_primary().map |monitor| {
println!("{:s}:", monitor.get_name());
println!(" {:s}\n", monitor.get_video_mode().unwrap().to_str());
};
println("Available monitors\n\
------------------... | {
std::rt::start_on_main_thread(argc, argv, main)
} | identifier_body |
byte_buf.rs | //! Helper types for tests
use serde::de::{self, Deserialize, Deserializer, Error};
use std::fmt;
/// Wrapper around `Vec<u8>` that deserialized using `deserialize_byte_buf`
/// instead of vector's generic `deserialize_seq`
#[derive(Debug, PartialEq)]
pub struct ByteBuf(pub Vec<u8>);
impl<'de> Deserialize<'de> for B... | where
D: Deserializer<'de>,
{
struct Visitor;
impl<'de> de::Visitor<'de> for Visitor {
type Value = Bytes<'de>;
fn expecting(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
fmt.write_str("borrowed bytes")
}
fn visit_bor... | impl<'de> Deserialize<'de> for Bytes<'de> {
fn deserialize<D>(d: D) -> Result<Self, D::Error> | random_line_split |
byte_buf.rs | //! Helper types for tests
use serde::de::{self, Deserialize, Deserializer, Error};
use std::fmt;
/// Wrapper around `Vec<u8>` that deserialized using `deserialize_byte_buf`
/// instead of vector's generic `deserialize_seq`
#[derive(Debug, PartialEq)]
pub struct ByteBuf(pub Vec<u8>);
impl<'de> Deserialize<'de> for B... | (&self, fmt: &mut fmt::Formatter) -> fmt::Result {
fmt.write_str("borrowed bytes")
}
fn visit_borrowed_bytes<E: Error>(self, v: &'de [u8]) -> Result<Self::Value, E> {
Ok(Bytes(v))
}
}
Ok(d.deserialize_bytes(Visitor)?)
}
}
| expecting | identifier_name |
effects.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/. */
//! Animated types for CSS values related to effects.
use crate::values::animated::color::Color;
use crate::valu... |
/// An animated value for a single `filter`.
#[cfg(feature = "gecko")]
pub type Filter = GenericFilter<Angle, Number, Length, SimpleShadow, ComputedUrl>;
/// An animated value for a single `filter`.
#[cfg(not(feature = "gecko"))]
pub type Filter = GenericFilter<Angle, Number, Length, Impossible, Impossible>;
/// An ... | use crate::values::Impossible;
/// An animated value for a single `box-shadow`.
pub type BoxShadow = GenericBoxShadow<Color, Length, Length, Length>; | random_line_split |
traversal.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/. */
//! Traversals over the DOM and flow trees, running the layout computations.
use construct::FlowConstructor;
use ... | flow.build_display_list(&mut self.state);
flow::mut_base(flow).restyle_damage.remove(REPAINT);
}
for kid in flow::child_iter_mut(flow) {
self.traverse(kid);
}
if new_stacking_context {
self.state.pop_stacking_context_id();
}
... | if self.should_process() { | random_line_split |
traversal.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/. */
//! Traversals over the DOM and flow trees, running the layout computations.
use construct::FlowConstructor;
use ... | <'a>(shared: &'a Self::SharedContext, root: OpaqueNode) -> Self {
// FIXME(bholley): This transmutation from &'a to &'lc is very unfortunate, but I haven't
// found a way to avoid it despite spending several days on it (and consulting Manishearth,
// brson, and nmatsakis).
//
// ... | new | identifier_name |
traversal.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/. */
//! Traversals over the DOM and flow trees, running the layout computations.
use construct::FlowConstructor;
use ... |
}
/// The bubble-inline-sizes traversal, the first part of layout computation. This computes
/// preferred and intrinsic inline-sizes and bubbles them up the tree.
pub struct BubbleISizes<'a> {
pub layout_context: &'a LayoutContext<'a>,
}
impl<'a> PostorderFlowTraversal for BubbleISizes<'a> {
#[inline]
f... | {
el.mutate_data().unwrap().persist();
unsafe { el.unset_dirty_descendants(); }
remove_from_bloom_filter(context, root, el);
} | conditional_block |
debug.rs | use core::str;
use core::sync::atomic::Ordering;
use spin::Once;
use context;
use scheme::*;
use sync::WaitQueue;
use syscall::flag::EVENT_READ;
use syscall::scheme::Scheme;
pub static DEBUG_SCHEME_ID: AtomicSchemeId = ATOMIC_SCHEMEID_INIT;
/// Input queue
static INPUT: Once<WaitQueue<u8>> = Once::new();
/// Initia... |
fn dup(&self, _file: usize, _buf: &[u8]) -> Result<usize> {
Ok(0)
}
/// Read the file `number` into the `buffer`
///
/// Returns the number of bytes read
fn read(&self, _file: usize, buf: &mut [u8]) -> Result<usize> {
Ok(INPUT.call_once(init_input).receive_into(buf, true))
... | {
Ok(0)
} | identifier_body |
debug.rs | use core::str;
use core::sync::atomic::Ordering;
use spin::Once;
use context;
use scheme::*;
use sync::WaitQueue;
use syscall::flag::EVENT_READ;
use syscall::scheme::Scheme;
pub static DEBUG_SCHEME_ID: AtomicSchemeId = ATOMIC_SCHEMEID_INIT;
/// Input queue
static INPUT: Once<WaitQueue<u8>> = Once::new();
/// Initia... | fn read(&self, _file: usize, buf: &mut [u8]) -> Result<usize> {
Ok(INPUT.call_once(init_input).receive_into(buf, true))
}
/// Write the `buffer` to the `file`
///
/// Returns the number of bytes written
fn write(&self, _file: usize, buffer: &[u8]) -> Result<usize> {
//TODO: Writ... |
/// Read the file `number` into the `buffer`
///
/// Returns the number of bytes read | random_line_split |
debug.rs | use core::str;
use core::sync::atomic::Ordering;
use spin::Once;
use context;
use scheme::*;
use sync::WaitQueue;
use syscall::flag::EVENT_READ;
use syscall::scheme::Scheme;
pub static DEBUG_SCHEME_ID: AtomicSchemeId = ATOMIC_SCHEMEID_INIT;
/// Input queue
static INPUT: Once<WaitQueue<u8>> = Once::new();
/// Initia... | (b: u8) {
let len = INPUT.call_once(init_input).send(b);
context::event::trigger(DEBUG_SCHEME_ID.load(Ordering::SeqCst), 0, EVENT_READ, len);
}
pub struct DebugScheme;
impl DebugScheme {
pub fn new(scheme_id: SchemeId) -> DebugScheme {
DEBUG_SCHEME_ID.store(scheme_id, Ordering::SeqCst);
D... | debug_input | identifier_name |
stats.rs | // Copyright 2015-2017 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 lat... | () {
assert!(Histogram::new(slice_into![], 1).is_none());
}
}
| none_when_too_few_data | identifier_name |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.