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 |
|---|---|---|---|---|
get_all_groups.rs | extern crate philipshue;
use std::env;
use philipshue::bridge::Bridge;
mod discover;
use discover::discover;
fn main() {
let args: Vec<String> = env::args().collect();
if args.len() < 2 {
println!("Usage : {:?} <username>", args[0]);
return;
}
let bridge = Bridge::new(discover().pop().... | }
}
impl<'a, T: 'a + Debug> Debug for Show<'a, T> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self.0 {
Some(ref x) => x.fmt(f),
_ => Display::fmt("N/A", f),
}
}
} | Some(ref x) => x.fmt(f),
_ => Display::fmt("N/A", f),
} | random_line_split |
get_all_groups.rs | extern crate philipshue;
use std::env;
use philipshue::bridge::Bridge;
mod discover;
use discover::discover;
fn main() {
let args: Vec<String> = env::args().collect();
if args.len() < 2 {
println!("Usage : {:?} <username>", args[0]);
return;
}
let bridge = Bridge::new(discover().pop().... | (&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self.0 {
Some(ref x) => x.fmt(f),
_ => Display::fmt("N/A", f),
}
}
}
impl<'a, T: 'a + Debug> Debug for Show<'a, T> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self.0 {
Some(re... | fmt | identifier_name |
get_all_groups.rs | extern crate philipshue;
use std::env;
use philipshue::bridge::Bridge;
mod discover;
use discover::discover;
fn main() | type_len);
for (id, group) in groups.iter() {
println!("{:2} {:name_len$} {:type_len$} {:12} {:6} {:6} {:3} {:?}",
id,
group.name,
group.group_type,
Show(&group.class),
... | {
let args: Vec<String> = env::args().collect();
if args.len() < 2 {
println!("Usage : {:?} <username>", args[0]);
return;
}
let bridge = Bridge::new(discover().pop().unwrap(), &*args[1]);
match bridge.get_all_groups() {
Ok(groups) => {
let name_len = groups.valu... | identifier_body |
mod.rs | 0x07 | // int32
//! 0x08 | // uint32
//! 0x09 | // int64
//! 0x0a | // uint64
//! 0x0b | // double
//! 0x0c | // utf8mb4 string
//! value ::=
//! object |
//! array |
//! literal |
//! number |
//! string |
//!... |
/// Creates a `number` JSON from an `i64`
pub fn from_i64(v: i64) -> Result<Self> {
let mut value = vec![];
value.write_json_i64(v)?;
Ok(Self::new(JsonType::I64, value))
}
/// Creates a `array` JSON from a collection of `JsonRef`
pub fn from_ref_array(array: Vec<JsonRef<'_... | {
let mut value = vec![];
value.write_json_f64(v)?;
Ok(Self::new(JsonType::Double, value))
} | identifier_body |
mod.rs | 0x07 | // int32
//! 0x08 | // uint32
//! 0x09 | // int64
//! 0x0a | // uint64
//! 0x0b | // double
//! 0x0c | // utf8mb4 string
//! value ::=
//! object |
//! array |
//! literal |
//! number |
//! string |
//!... | (&self) -> &'a [u8] {
&self.value
}
// Returns the JSON value as u64
//
// See `GetUint64()` in TiDB `json/binary.go`
pub(crate) fn get_u64(&self) -> u64 {
assert_eq!(self.type_code, JsonType::U64);
NumberCodec::decode_u64_le(self.value())
}
// Returns the JSON valu... | value | identifier_name |
mod.rs | //! 0x07 | // int32
//! 0x08 | // uint32
//! 0x09 | // int64
//! 0x0a | // uint64
//! 0x0b | // double
//! 0x0c | // utf8mb4 string
//! value ::= | //! array |
//! literal |
//! number |
//! string |
//! object ::= element-count size key-entry* value-entry* key* value*
//! array ::= element-count size value-entry* value*
//!
//! // the number of members in object or number of elements in array
//! element-count ::= uint32
//!
//... | //! object | | random_line_split |
client.rs | // Copyright 2019 TiKV Project Authors. Licensed under Apache-2.0.
#[macro_use]
extern crate log;
use rand;
#[macro_use]
extern crate serde_derive;
#[path = "../log_util.rs"]
mod log_util;
mod util;
use std::sync::Arc;
use std::thread;
use std::time::Duration;
use futures_util::{SinkExt as _, TryStreamExt as _};
us... |
info!("-------------- RecordRoute --------------");
record_route(&client).await?;
info!("-------------- RouteChat --------------");
route_chat(&client).await?;
Ok(())
}
fn main() {
futures_executor::block_on(async_main()).unwrap()
} | random_line_split | |
client.rs | // Copyright 2019 TiKV Project Authors. Licensed under Apache-2.0.
#[macro_use]
extern crate log;
use rand;
#[macro_use]
extern crate serde_derive;
#[path = "../log_util.rs"]
mod log_util;
mod util;
use std::sync::Arc;
use std::thread;
use std::time::Duration;
use futures_util::{SinkExt as _, TryStreamExt as _};
us... |
async fn record_route(client: &RouteGuideClient) -> Result<()> {
let features = util::load_db();
let mut rng = rand::thread_rng();
let (mut sink, receiver) = client.record_route()?;
for _ in 0..10usize {
let f = features.choose(&mut rng).unwrap();
let point = f.get_location();
... | {
let rect = new_rect(400_000_000, -750_000_000, 420_000_000, -730_000_000);
info!("Looking for features between 40, -75 and 42, -73");
let mut list_features = client.list_features(&rect)?;
while let Some(feature) = list_features.try_next().await? {
let loc = feature.get_location();
info... | identifier_body |
client.rs | // Copyright 2019 TiKV Project Authors. Licensed under Apache-2.0.
#[macro_use]
extern crate log;
use rand;
#[macro_use]
extern crate serde_derive;
#[path = "../log_util.rs"]
mod log_util;
mod util;
use std::sync::Arc;
use std::thread;
use std::time::Duration;
use futures_util::{SinkExt as _, TryStreamExt as _};
us... |
if f.get_name().is_empty() {
warn!("Found no feature at {}", util::format_point(point));
return Ok(());
}
info!(
"Found feature called {} at {}",
f.get_name(),
util::format_point(point)
);
Ok(())
}
async fn list_features(client: &RouteGuideClient) -> Result<... | {
warn!("Server returns incomplete feature.");
return Ok(());
} | conditional_block |
client.rs | // Copyright 2019 TiKV Project Authors. Licensed under Apache-2.0.
#[macro_use]
extern crate log;
use rand;
#[macro_use]
extern crate serde_derive;
#[path = "../log_util.rs"]
mod log_util;
mod util;
use std::sync::Arc;
use std::thread;
use std::time::Duration;
use futures_util::{SinkExt as _, TryStreamExt as _};
us... | (client: &RouteGuideClient) -> Result<()> {
let (mut sink, mut receiver) = client.route_chat()?;
let send = async move {
let notes = vec![
("First message", 0, 0),
("Second message", 0, 1),
("Third message", 1, 0),
("Fourth message", 0, 0),
];
... | route_chat | identifier_name |
net.rs | //! A collection of traits abstracting over Listeners and Streams.
use std::any::{Any, AnyRefExt};
use std::boxed::BoxAny;
use std::fmt;
use std::intrinsics::TypeId;
use std::io::{IoResult, IoError, ConnectionAborted, InvalidInput, OtherIoError,
Stream, Listener, Acceptor};
use std::io::net::ip::{SocketAd... | <T:'static>(self) -> bool {
self.get_type_id() == TypeId::of::<T>()
}
#[inline]
fn downcast_ref<T:'static>(self) -> Option<&'a T> {
if self.is::<T>() {
unsafe {
// Get the raw representation of the trait object
let to: TraitObject = transmute_copy... | is | identifier_name |
net.rs | //! A collection of traits abstracting over Listeners and Streams.
use std::any::{Any, AnyRefExt};
use std::boxed::BoxAny;
use std::fmt;
use std::intrinsics::TypeId;
use std::io::{IoResult, IoError, ConnectionAborted, InvalidInput, OtherIoError,
Stream, Listener, Acceptor};
use std::io::net::ip::{SocketAd... |
}
impl Writer for Box<NetworkStream + Send> {
#[inline]
fn write(&mut self, msg: &[u8]) -> IoResult<()> { (**self).write(msg) }
#[inline]
fn flush(&mut self) -> IoResult<()> { (**self).flush() }
}
impl<'a> Reader for &'a mut NetworkStream {
#[inline]
fn read(&mut self, buf: &mut [u8]) -> IoR... | { (**self).read(buf) } | identifier_body |
net.rs | //! A collection of traits abstracting over Listeners and Streams.
use std::any::{Any, AnyRefExt};
use std::boxed::BoxAny;
use std::fmt;
use std::intrinsics::TypeId;
use std::io::{IoResult, IoError, ConnectionAborted, InvalidInput, OtherIoError,
Stream, Listener, Acceptor};
use std::io::net::ip::{SocketAd... | impl Writer for Box<NetworkStream + Send> {
#[inline]
fn write(&mut self, msg: &[u8]) -> IoResult<()> { (**self).write(msg) }
#[inline]
fn flush(&mut self) -> IoResult<()> { (**self).flush() }
}
impl<'a> Reader for &'a mut NetworkStream {
#[inline]
fn read(&mut self, buf: &mut [u8]) -> IoResul... | }
| random_line_split |
main.rs | extern crate rand;
use std::net::{TcpStream, Shutdown};
use std::io::prelude::*;
use rand::distributions::{IndependentSample, Range};
use std::io::BufWriter;
use std::fs::File;
fn main() | fw.write(rand_data.as_bytes())
.ok()
.expect("Failed to write to file.");
// write 10 bytes of the string to the stream
for out_buf in rand_data.into_bytes().chunks(10) {
stream.write(&out_buf)
.ok()
.expect("Failed to write to str... | {
let f = File::create("socket_producer_out.txt")
.ok()
.expect("Failed to create file.");
let mut fw = BufWriter::new(f);
// fill array with random bytes
let r = Range::new(0i32, 9);
let mut rng = rand::thread_rng();
let mut rand_data = String::new();
for _ in 0..1... | identifier_body |
main.rs | extern crate rand;
use std::net::{TcpStream, Shutdown};
use std::io::prelude::*;
use rand::distributions::{IndependentSample, Range};
use std::io::BufWriter;
use std::fs::File;
fn | () {
let f = File::create("socket_producer_out.txt")
.ok()
.expect("Failed to create file.");
let mut fw = BufWriter::new(f);
// fill array with random bytes
let r = Range::new(0i32, 9);
let mut rng = rand::thread_rng();
let mut rand_data = String::new();
for _ in 0..... | main | identifier_name |
main.rs | extern crate rand;
use std::net::{TcpStream, Shutdown};
use std::io::prelude::*;
use rand::distributions::{IndependentSample, Range};
use std::io::BufWriter;
use std::fs::File;
fn main() {
let f = File::create("socket_producer_out.txt")
.ok()
.expect("Failed to create file.");
let mut fw... | }
}
stream.shutdown(Shutdown::Both)
.ok()
.expect("Failed to close streams.");
}
} | .ok()
.expect("Failed to read from stream.");
print!("in={} ", in_buf[0]); | random_line_split |
string-lit.rs | // rustfmt-force_format_strings: true
// Long string literals
fn main() -> &'static str {
let str = "AAAAAAAAAAAAAAaAAAAAAAAAAAAAAAAAAAAAAAA AAAAAAAAAAAAAAAAAAAAAAaAA AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAaAa";
let str = "AAAAAAAAAAAAAAaAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAaAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAa... | identifier_name | ||
string-lit.rs | // rustfmt-force_format_strings: true
// Long string literals
fn main() -> &'static str {
let str = "AAAAAAAAAAAAAAaAAAAAAAAAAAAAAAAAAAAAAAA AAAAAAAAAAAAAAAAAAAAAAaAA AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAaAa";
let str = "AAAAAAAAAAAAAAaAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAaAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAa... | forall x. mult(x, x) = e()");
} | random_line_split | |
string-lit.rs | // rustfmt-force_format_strings: true
// Long string literals
fn main() -> &'static str {
let str = "AAAAAAAAAAAAAAaAAAAAAAAAAAAAAAAAAAAAAAA AAAAAAAAAAAAAAAAAAAAAAaAA AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAaAa";
let str = "AAAAAAAAAAAAAAaAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAaAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAa... | identifier_body | ||
lib.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/. */
extern crate quote;
#[macro_use] extern crate syn;
#[macro_use] extern crate synstructure;
decl_derive!([JSTracea... | use ::dom::bindings::trace::JSTraceable;
match *self {
#match_body
}
}
}
};
tokens
}
| {
let match_body = s.each(|binding| {
Some(quote!(#binding.trace(tracer);))
});
let ast = s.ast();
let name = ast.ident;
let (impl_generics, ty_generics, where_clause) = ast.generics.split_for_impl();
let mut where_clause = where_clause.unwrap_or(&parse_quote!(where)).clone();
for p... | identifier_body |
lib.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/. */
extern crate quote;
#[macro_use] extern crate syn;
#[macro_use] extern crate synstructure;
decl_derive!([JSTracea... | (s: synstructure::Structure) -> quote::Tokens {
let match_body = s.each(|binding| {
Some(quote!(#binding.trace(tracer);))
});
let ast = s.ast();
let name = ast.ident;
let (impl_generics, ty_generics, where_clause) = ast.generics.split_for_impl();
let mut where_clause = where_clause.unwr... | js_traceable_derive | identifier_name |
lib.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/. */
extern crate quote;
#[macro_use] extern crate syn;
#[macro_use] extern crate synstructure;
| Some(quote!(#binding.trace(tracer);))
});
let ast = s.ast();
let name = ast.ident;
let (impl_generics, ty_generics, where_clause) = ast.generics.split_for_impl();
let mut where_clause = where_clause.unwrap_or(&parse_quote!(where)).clone();
for param in ast.generics.type_params() {
... | decl_derive!([JSTraceable] => js_traceable_derive);
fn js_traceable_derive(s: synstructure::Structure) -> quote::Tokens {
let match_body = s.each(|binding| { | random_line_split |
python.rs | use pyo3::prelude::*;
use pyo3::wrap_pyfunction;
use crate::atom::__pyo3_get_function_atom_grid;
use crate::atom::__pyo3_get_function_atom_grid_bse;
use crate::lebedev::__pyo3_get_function_angular_grid;
use crate::radial::__pyo3_get_function_radial_grid_kk;
use crate::radial::__pyo3_get_function_radial_grid_lmg;
use c... | (_py: Python, m: &PyModule) -> PyResult<()> {
m.add("__version__", env!("CARGO_PKG_VERSION"))?;
m.add_function(wrap_pyfunction!(atom_grid, m)?)?;
m.add_function(wrap_pyfunction!(atom_grid_bse, m)?)?;
m.add_function(wrap_pyfunction!(angular_grid, m)?)?;
m.add_function(wrap_pyfunction!(radial_grid_kk... | numgrid | identifier_name |
python.rs | use pyo3::prelude::*;
use pyo3::wrap_pyfunction;
use crate::atom::__pyo3_get_function_atom_grid; | use crate::lebedev::__pyo3_get_function_angular_grid;
use crate::radial::__pyo3_get_function_radial_grid_kk;
use crate::radial::__pyo3_get_function_radial_grid_lmg;
use crate::radial::__pyo3_get_function_radial_grid_lmg_bse;
#[pymodule]
fn numgrid(_py: Python, m: &PyModule) -> PyResult<()> {
m.add("__version__", e... | use crate::atom::__pyo3_get_function_atom_grid_bse; | random_line_split |
python.rs | use pyo3::prelude::*;
use pyo3::wrap_pyfunction;
use crate::atom::__pyo3_get_function_atom_grid;
use crate::atom::__pyo3_get_function_atom_grid_bse;
use crate::lebedev::__pyo3_get_function_angular_grid;
use crate::radial::__pyo3_get_function_radial_grid_kk;
use crate::radial::__pyo3_get_function_radial_grid_lmg;
use c... | {
m.add("__version__", env!("CARGO_PKG_VERSION"))?;
m.add_function(wrap_pyfunction!(atom_grid, m)?)?;
m.add_function(wrap_pyfunction!(atom_grid_bse, m)?)?;
m.add_function(wrap_pyfunction!(angular_grid, m)?)?;
m.add_function(wrap_pyfunction!(radial_grid_kk, m)?)?;
m.add_function(wrap_pyfunction!... | identifier_body | |
error.rs | //! A stand-in for `std::error`
use core::any::TypeId;
use core::fmt::{Debug, Display};
/// A stand-in for `std::error::Error`, which requires no allocation.
#[cfg(feature = "unstable")]
pub trait Error: Debug + Display + ::core::marker::Reflect {
/// A short description of the error.
///
/// The descript... |
}
/// A stand-in for `std::error::Error`, which requires no allocation.
#[cfg(not(feature = "unstable"))]
pub trait Error: Debug + Display {
/// A short description of the error.
///
/// The description should not contain newlines or sentence-ending
/// punctuation, to facilitate embedding in larger u... | {
TypeId::of::<Self>()
} | identifier_body |
error.rs | //! A stand-in for `std::error`
use core::any::TypeId;
use core::fmt::{Debug, Display};
/// A stand-in for `std::error::Error`, which requires no allocation.
#[cfg(feature = "unstable")]
pub trait Error: Debug + Display + ::core::marker::Reflect {
/// A short description of the error.
///
/// The descript... | /// A stand-in for `std::error::Error`, which requires no allocation.
#[cfg(not(feature = "unstable"))]
pub trait Error: Debug + Display {
/// A short description of the error.
///
/// The description should not contain newlines or sentence-ending
/// punctuation, to facilitate embedding in larger user-... | fn type_id(&self) -> TypeId where Self: 'static {
TypeId::of::<Self>()
}
}
| random_line_split |
error.rs | //! A stand-in for `std::error`
use core::any::TypeId;
use core::fmt::{Debug, Display};
/// A stand-in for `std::error::Error`, which requires no allocation.
#[cfg(feature = "unstable")]
pub trait Error: Debug + Display + ::core::marker::Reflect {
/// A short description of the error.
///
/// The descript... | (&self) -> TypeId where Self:'static {
TypeId::of::<()>()
}
}
| type_id | identifier_name |
lib.rs | ///! Utilities for universally unique identifiers.
///!
///! The identifiers generated by this module:
///!
///! - are URL safe
///! - contain information on the type of object that they
///! are identifying
///! - have an extremely low probability of collision
///!
///! By default, generated identifiers have a fixed... | /// use uuids::uuid_family;
///
/// uuid_family!(MyId, "my");
/// let id = MyId::new();
/// ```
#[macro_export]
macro_rules! uuid_family {
($name:ident, $prefix:literal) => {
#[derive(Debug, Clone, serde::Deserialize, serde::Serialize)]
pub struct $name(uuids::Uuid);
impl $name {
... |
/// Create a family of UUIDs
///
/// ``` | random_line_split |
lib.rs | ///! Utilities for universally unique identifiers.
///!
///! The identifiers generated by this module:
///!
///! - are URL safe
///! - contain information on the type of object that they
///! are identifying
///! - have an extremely low probability of collision
///!
///! By default, generated identifiers have a fixed... |
// Generate a universally unique identifier with only lowercase letters and digits
pub fn generate_lower(prefix: &str) -> Uuid {
let chars = nanoid!(20, &CHARACTERS[..36]);
[prefix, SEPARATOR, &chars].concat().into()
}
// Test whether a string is an identifier for a particular prefix
pub fn matches(prefix: &... | {
let chars = nanoid!(20, &CHARACTERS);
[prefix, SEPARATOR, &chars].concat().into()
} | identifier_body |
lib.rs | ///! Utilities for universally unique identifiers.
///!
///! The identifiers generated by this module:
///!
///! - are URL safe
///! - contain information on the type of object that they
///! are identifying
///! - have an extremely low probability of collision
///!
///! By default, generated identifiers have a fixed... | () {
let id = generate_lower("pr");
assert_eq!(id.len(), 23);
assert!(matches("pr", &id));
assert("pr", id).unwrap();
}
}
| lower | identifier_name |
lib.rs | // Copyright 2015 MaidSafe.net limited.
//
// This SAFE Network Software is licensed to you under (1) the MaidSafe.net Commercial License,
// version 1.0 or later, or (2) The General Public License (GPL), version 3, depending on which
// licence you accepted on initial access to the Software (the "Licences").
//
// By ... |
/// returns tag type for PublicMpid type
fn public_id_type_tag(&self) -> u64 { data_tags::PUBLIC_MPID_TAG }
}
/// Random trait is used to generate random instances.
/// Used in the test mod
pub trait Random {
/// Generates a random instance and returns the created random instance
fn generate_random() ... | { data_tags::MPID_TAG } | identifier_body |
lib.rs | // Copyright 2015 MaidSafe.net limited. | //
// This SAFE Network Software is licensed to you under (1) the MaidSafe.net Commercial License,
// version 1.0 or later, or (2) The General Public License (GPL), version 3, depending on which
// licence you accepted on initial access to the Software (the "Licences").
//
// By contributing code to the SAFE Network So... | random_line_split | |
lib.rs | // Copyright 2015 MaidSafe.net limited.
//
// This SAFE Network Software is licensed to you under (1) the MaidSafe.net Commercial License,
// version 1.0 or later, or (2) The General Public License (GPL), version 3, depending on which
// licence you accepted on initial access to the Software (the "Licences").
//
// By ... | {
/// Unknown Error Type
Unknown
}
/// All Maidsafe tagging should offset from this
pub const MAIDSAFE_TAG: u64 = 5483_000;
/// All Maidsafe Data tags
#[allow(missing_docs)]
pub mod data_tags {
pub const MAIDSAFE_DATA_TAG: u64 = ::MAIDSAFE_TAG + 100;
pub const IMMUTABLE_DATA_TAG: u64 = M... | CryptoError | identifier_name |
storageevent.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::cell::DOMRefCell;
use dom::bindings::codegen::Bindings::EventBinding::{EventMethods};
use dom::... | {
event: Event,
key: DOMRefCell<Option<DOMString>>,
oldValue: DOMRefCell<Option<DOMString>>,
newValue: DOMRefCell<Option<DOMString>>,
url: DOMRefCell<DOMString>,
storageArea: MutNullableJS<Storage>
}
impl StorageEvent {
pub fn new_inherited(type_id: EventTypeId,
k... | StorageEvent | identifier_name |
storageevent.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::cell::DOMRefCell;
use dom::bindings::codegen::Bindings::EventBinding::{EventMethods};
use dom::... |
fn Url(self) -> DOMString {
// FIXME(https://github.com/rust-lang/rust/issues/23338)
let url = self.url.borrow();
url.clone()
}
fn GetStorageArea(self) -> Option<Temporary<Storage>> {
self.storageArea.get()
}
} | random_line_split | |
storageevent.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::cell::DOMRefCell;
use dom::bindings::codegen::Bindings::EventBinding::{EventMethods};
use dom::... | else { EventCancelable::NotCancelable };
let event = StorageEvent::new(global, type_,
bubbles, cancelable,
key, oldValue, newValue,
url, storageArea);
Ok(event)
}
}
impl<'a> StorageEve... | { EventCancelable::Cancelable } | conditional_block |
storageevent.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::cell::DOMRefCell;
use dom::bindings::codegen::Bindings::EventBinding::{EventMethods};
use dom::... |
pub fn new(global: GlobalRef,
type_: DOMString,
bubbles: EventBubbles,
cancelable: EventCancelable,
key: Option<DOMString>,
oldValue: Option<DOMString>,
newValue: Option<DOMString>,
url: DOMString,
... | {
StorageEvent {
event: Event::new_inherited(type_id),
key: DOMRefCell::new(key),
oldValue: DOMRefCell::new(oldValue),
newValue: DOMRefCell::new(newValue),
url: DOMRefCell::new(url),
storageArea: MutNullableJS::new(storageArea)
}
... | identifier_body |
build.rs | // Copyright 2017 The Xyrosource Team.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except acco... |
use std::env;
use std::fs::File;
use std::io::Write;
use std::path::Path;
fn main() {
let out_dir = env::var("OUT_DIR").unwrap();
let version_file = Path::new(&out_dir).join("version.rs");
let mut fil = File::create(&version_file).unwrap();
let cargo_version = env!("CARGO_PKG_VERSION").to_owned();
... | // https://github.com/simias/pockystation/blob/master/build.rs | random_line_split |
build.rs | // Copyright 2017 The Xyrosource Team.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except acco... | {
let out_dir = env::var("OUT_DIR").unwrap();
let version_file = Path::new(&out_dir).join("version.rs");
let mut fil = File::create(&version_file).unwrap();
let cargo_version = env!("CARGO_PKG_VERSION").to_owned();
writeln!(fil, "pub const VERSION: &'static str = \
\"{}\";", cargo... | identifier_body | |
build.rs | // Copyright 2017 The Xyrosource Team.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except acco... | () {
let out_dir = env::var("OUT_DIR").unwrap();
let version_file = Path::new(&out_dir).join("version.rs");
let mut fil = File::create(&version_file).unwrap();
let cargo_version = env!("CARGO_PKG_VERSION").to_owned();
writeln!(fil, "pub const VERSION: &'static str = \
\"{}\";", ca... | main | identifier_name |
poly.rs | use crate::geometry::*;
use std::f64::consts;
use std::iter::{Repeat, repeat};
/// Refers to an implementation of a polygon
pub trait Poly : TwoDTransformable {
fn get_corners(&self) -> Vec<Point>;
fn set_corners(&mut self, corners: Vec<Point>);
// Normals face outwards
fn normals(&self) -> Vec<Point... | (&self, index: usize) -> Option<Line> {
self.sides_iter().nth(index).and_then(|(beg, end)| {Some(Line::new(beg, end))})
}
fn sides_iter<'a>(&'a self) -> Box<dyn Iterator<Item=(Point, Point)> + 'a> {
let corners_it_shift = self.get_corners().into_iter().cycle().skip(1);
Box::new(self.get... | get_side | identifier_name |
poly.rs | use crate::geometry::*;
use std::f64::consts;
use std::iter::{Repeat, repeat};
/// Refers to an implementation of a polygon
pub trait Poly : TwoDTransformable {
fn get_corners(&self) -> Vec<Point>;
fn set_corners(&mut self, corners: Vec<Point>);
// Normals face outwards
fn normals(&self) -> Vec<Point... |
fn total_sides(&self) -> usize {
self.get_corners().len()
}
fn get_corner_lines(&self, other: &dyn Poly) -> Vec<Line> {
self.get_corners().into_iter()
.zip(other.get_corners().into_iter())
.map(|(beg, end)| { Line::new(beg, end) })
.collect()
}
fn get_shift(&s... | } | random_line_split |
poly.rs | use crate::geometry::*;
use std::f64::consts;
use std::iter::{Repeat, repeat};
/// Refers to an implementation of a polygon
pub trait Poly : TwoDTransformable {
fn get_corners(&self) -> Vec<Point>;
fn set_corners(&mut self, corners: Vec<Point>);
// Normals face outwards
fn normals(&self) -> Vec<Point... |
fn get_shift(&self, other: &dyn Poly) -> Point {
other.get_corners()[0] - self.get_corners()[0]
}
}
pub fn get_at_time<T: Poly + Sized + Clone>(poly: &T, shift: Point, time: f64) -> T {
let mut out = poly.clone();
out.shift_by(time * shift);
out
}
pub fn get_shifted<T: Poly + Sized + Clo... | {
self.get_corners().into_iter()
.zip(other.get_corners().into_iter())
.map(|(beg, end)| { Line::new(beg, end) })
.collect()
} | identifier_body |
rpc.rs | use crate::{
agent::{Agent, AgentId},
group::{Group, GroupError, GroupSettings},
handle::OpId,
};
use libp2p::PeerId;
use serde::{Deserialize, Serialize};
use std::{
borrow::Borrow,
convert::{TryFrom, TryInto},
fmt::{Debug, Display},
};
use uuid::Uuid;
#[derive(Debug, Serialize, Deserialize)]
#... |
pub(crate) fn new_group(group: Group) -> Resource {
Resource(ResourceKind::Group(group))
}
/// Create a resource of agent kind. Returns both the identifier (key) and the resource
/// handle.
pub(crate) fn agent(agent_id: AgentId, peer_id: PeerId) -> (ResourceIdentifier, Agent) {
l... | {
Resource(ResourceKind::Agent(agent))
} | identifier_body |
rpc.rs | use crate::{
agent::{Agent, AgentId},
group::{Group, GroupError, GroupSettings},
handle::OpId,
};
use libp2p::PeerId;
use serde::{Deserialize, Serialize};
use std::{
borrow::Borrow,
convert::{TryFrom, TryInto},
fmt::{Debug, Display},
};
use uuid::Uuid;
#[derive(Debug, Serialize, Deserialize)]
#... |
impl ResourceIdentifier {
const KIND_SIZE: usize = 1;
const KEY_SIZE: usize = std::mem::size_of::<u128>();
/// This key represents a group resource kind.
pub(crate) fn group(id: &Uuid) -> ResourceIdentifier {
let id = id.as_u128().to_be_bytes();
let kind = ResourceKeyKind::GroupId as u... | random_line_split | |
rpc.rs | use crate::{
agent::{Agent, AgentId},
group::{Group, GroupError, GroupSettings},
handle::OpId,
};
use libp2p::PeerId;
use serde::{Deserialize, Serialize};
use std::{
borrow::Borrow,
convert::{TryFrom, TryInto},
fmt::{Debug, Display},
};
use uuid::Uuid;
#[derive(Debug, Serialize, Deserialize)]
#... | (agent: Agent) -> Resource {
Resource(ResourceKind::Agent(agent))
}
pub(crate) fn new_group(group: Group) -> Resource {
Resource(ResourceKind::Group(group))
}
/// Create a resource of agent kind. Returns both the identifier (key) and the resource
/// handle.
pub(crate) fn agent... | new_agent | identifier_name |
local_ptr.rs | // Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | () -> Option<tls::Key> {
unsafe {
// NB: This is a little racy because, while the key is
// initialized under a mutex and it's assumed to be initialized
// in the Scheduler ctor by any thread that needs to use it,
// we are not accessing the key under a mutex. Th... | maybe_tls_key | identifier_name |
local_ptr.rs | // Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | tls::destroy(RT_TLS_KEY);
}
/// Give a pointer to thread-local storage.
///
/// # Safety note
///
/// Does not validate the pointer type.
#[inline]
pub unsafe fn put<T>(sched: Box<T>) {
let key = tls_key();
let void_ptr: *mut u8 = mem::transmute(sched);
t... | random_line_split | |
local_ptr.rs | // Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... |
/// Take ownership of a pointer from thread-local storage.
///
/// # Safety note
///
/// Does not validate the pointer type.
#[inline]
pub unsafe fn take<T>() -> Box<T> {
let key = tls_key();
let void_ptr: *mut u8 = tls::get(key);
if void_ptr.is_null() {
... | {
let key = tls_key();
let void_ptr: *mut u8 = mem::transmute(sched);
tls::set(key, void_ptr);
} | identifier_body |
serialize.rs | extern crate serde;
use super::{Split, SplitHandle};
use rect::Rect;
gen_handle!("SplitHandle", SplitHandle, SplitHandleVisitor);
// Serialization
impl serde::ser::Serialize for Split {
fn serialize<S>(&self, serializer: &mut S) -> Result<(), S::Error> where S: serde::ser::Serializer {
serializer.seriali... | <'a> {
value: &'a Split
}
impl<'a> serde::ser::MapVisitor for SplitMapVisitor<'a> {
fn visit<S>(&mut self, serializer: &mut S) -> Result<Option<()>, S::Error> where S: serde::Serializer {
try!(serializer.serialize_struct_elt("children", &self.value.children));
try!(serializer.serialize_struct_e... | SplitMapVisitor | identifier_name |
serialize.rs | extern crate serde;
use super::{Split, SplitHandle};
use rect::Rect;
gen_handle!("SplitHandle", SplitHandle, SplitHandleVisitor);
// Serialization
impl serde::ser::Serialize for Split {
fn serialize<S>(&self, serializer: &mut S) -> Result<(), S::Error> where S: serde::ser::Serializer |
}
struct SplitMapVisitor<'a> {
value: &'a Split
}
impl<'a> serde::ser::MapVisitor for SplitMapVisitor<'a> {
fn visit<S>(&mut self, serializer: &mut S) -> Result<Option<()>, S::Error> where S: serde::Serializer {
try!(serializer.serialize_struct_elt("children", &self.value.children));
try!(ser... | {
serializer.serialize_struct("Split", SplitMapVisitor { value: self }).map(|_| ())
} | identifier_body |
serialize.rs | extern crate serde;
use super::{Split, SplitHandle}; | use rect::Rect;
gen_handle!("SplitHandle", SplitHandle, SplitHandleVisitor);
// Serialization
impl serde::ser::Serialize for Split {
fn serialize<S>(&self, serializer: &mut S) -> Result<(), S::Error> where S: serde::ser::Serializer {
serializer.serialize_struct("Split", SplitMapVisitor { value: self }).m... | random_line_split | |
util.rs | use super::engine::{Action, Round};
use super::state::GameState;
use crate::cards::BasicCard;
pub fn format_hand(hand: &[BasicCard], gs: &GameState) -> String {
let mut cards: Vec<_> = hand.iter().collect();
cards.sort_by(|a, b| gs.display_order(a, b));
let sc: Vec<_> = cards.iter().map(|x| format!("{}", ... |
pub fn format_round(round: &Round) -> String {
format!(
"{}{}\n",
&format_state(round.get_state()),
round.get_phase().format(round.get_state())
)
}
pub fn format_action(action: &Action) -> String {
format!("Player {} plays {}.", action.player + 1, action.card)
}
| {
format!(
"Player 1: Score {}, Hand: {}\nPlayer 2: Score {}, Hand: {}\nTrump: {}\n",
gs.score[0],
&format_hand(&gs.hands[0], gs),
gs.score[1],
&format_hand(&gs.hands[1], gs),
gs.trump
)
} | identifier_body |
util.rs | use super::engine::{Action, Round};
use super::state::GameState;
use crate::cards::BasicCard;
pub fn format_hand(hand: &[BasicCard], gs: &GameState) -> String {
let mut cards: Vec<_> = hand.iter().collect();
cards.sort_by(|a, b| gs.display_order(a, b));
let sc: Vec<_> = cards.iter().map(|x| format!("{}", ... | gs.score[0],
&format_hand(&gs.hands[0], gs),
gs.score[1],
&format_hand(&gs.hands[1], gs),
gs.trump
)
}
pub fn format_round(round: &Round) -> String {
format!(
"{}{}\n",
&format_state(round.get_state()),
round.get_phase().format(round.get_state())
... | }
pub fn format_state(gs: &GameState) -> String {
format!(
"Player 1: Score {}, Hand: {}\nPlayer 2: Score {}, Hand: {}\nTrump: {}\n", | random_line_split |
util.rs | use super::engine::{Action, Round};
use super::state::GameState;
use crate::cards::BasicCard;
pub fn format_hand(hand: &[BasicCard], gs: &GameState) -> String {
let mut cards: Vec<_> = hand.iter().collect();
cards.sort_by(|a, b| gs.display_order(a, b));
let sc: Vec<_> = cards.iter().map(|x| format!("{}", ... | (action: &Action) -> String {
format!("Player {} plays {}.", action.player + 1, action.card)
}
| format_action | identifier_name |
test_simple_replace.rs | use std::process::{Command, Stdio};
use std::io::{Read, Write};
use common::*;
#[test]
fn | () {
let _fs = setup(&[tf("file3")]);
set_file_content("file3", "baca");
let output = Command::new(BINARY_PATH)
.args(&["-s", "a", "-x", "Z", "-Y", "-Q", "it/file3"])
.output()
.expect("123");
assert!(output.status.success());
assert_eq!("", String::from_utf8_lossy(&output.st... | simple_replace1 | identifier_name |
test_simple_replace.rs | use std::process::{Command, Stdio};
use std::io::{Read, Write};
use common::*;
#[test]
fn simple_replace1() |
#[test]
fn ask_user_user_accepts_all() {
let _fs = setup(&[tf("file3")]);
set_file_content("file3", "baca");
let process = Command::new(BINARY_PATH)
.args(&["-s", "a", "-x", "Z", "-C", "-Q", "it/file3"])
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.spawn()
.expect("... | {
let _fs = setup(&[tf("file3")]);
set_file_content("file3", "baca");
let output = Command::new(BINARY_PATH)
.args(&["-s", "a", "-x", "Z", "-Y", "-Q", "it/file3"])
.output()
.expect("123");
assert!(output.status.success());
assert_eq!("", String::from_utf8_lossy(&output.st... | identifier_body |
test_simple_replace.rs | use std::process::{Command, Stdio};
use std::io::{Read, Write};
use common::*;
#[test]
fn simple_replace1() {
let _fs = setup(&[tf("file3")]);
set_file_content("file3", "baca");
let output = Command::new(BINARY_PATH)
.args(&["-s", "a", "-x", "Z", "-Y", "-Q", "it/file3"])
.output()
.... | .args(&["-s", "a", "-x", "Z", "-C", "-Q", "it/file3"])
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.spawn()
.expect("123");
let mut output = String::new();
let mut stdin = process.stdin.unwrap(); //.write_all("alfa".as_bytes());
// process.stdin.unwrap().write_all("... |
set_file_content("file3", "babababa");
let process = Command::new(BINARY_PATH) | random_line_split |
xxx_add_yyy_is_zzz.rs | use malachite_base::num::basic::unsigneds::PrimitiveUnsigned;
use malachite_base_test_util::bench::bucketers::sextuple_max_bit_bucketer;
use malachite_base_test_util::bench::{run_benchmark, BenchmarkType};
use malachite_base_test_util::generators::common::{GenConfig, GenMode};
use malachite_base_test_util::generators::... | run_benchmark(
&format!(
"{}::xxx_add_yyy_is_zzz({}, {}, {}, {}, {}, {})",
T::NAME,
T::NAME,
T::NAME,
T::NAME,
T::NAME,
T::NAME,
T::NAME
),
BenchmarkType::Single,
unsigned_sextuple_gen_var... | limit: usize,
file_name: &str,
) { | random_line_split |
xxx_add_yyy_is_zzz.rs | use malachite_base::num::basic::unsigneds::PrimitiveUnsigned;
use malachite_base_test_util::bench::bucketers::sextuple_max_bit_bucketer;
use malachite_base_test_util::bench::{run_benchmark, BenchmarkType};
use malachite_base_test_util::generators::common::{GenConfig, GenMode};
use malachite_base_test_util::generators::... | })],
);
}
| {
run_benchmark(
&format!(
"{}::xxx_add_yyy_is_zzz({}, {}, {}, {}, {}, {})",
T::NAME,
T::NAME,
T::NAME,
T::NAME,
T::NAME,
T::NAME,
T::NAME
),
BenchmarkType::Single,
unsigned_sextuple_gen_v... | identifier_body |
xxx_add_yyy_is_zzz.rs | use malachite_base::num::basic::unsigneds::PrimitiveUnsigned;
use malachite_base_test_util::bench::bucketers::sextuple_max_bit_bucketer;
use malachite_base_test_util::bench::{run_benchmark, BenchmarkType};
use malachite_base_test_util::generators::common::{GenConfig, GenMode};
use malachite_base_test_util::generators::... | (runner: &mut Runner) {
register_unsigned_demos!(runner, demo_xxx_add_yyy_is_zzz);
register_unsigned_benches!(runner, benchmark_xxx_add_yyy_is_zzz);
}
fn demo_xxx_add_yyy_is_zzz<T: PrimitiveUnsigned>(gm: GenMode, config: GenConfig, limit: usize) {
for (x_2, x_1, x_0, y_2, y_1, y_0) in unsigned_sextuple_gen... | register | identifier_name |
issue-2735.rs | // Copyright 2012 The Rust Project Developers. See the 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.
#![allow(unknown_features)]
#![feature(box_syntax)]
trait hax { }
impl<A> hax for A { }
fn perform_hax<T:'static>(x: Box<T>) -> Box<hax+'static> {
b... | // 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 | random_line_split |
issue-2735.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 ... | <T:'static>(x: Box<T>) -> Box<hax+'static> {
box x as Box<hax+'static>
}
fn deadcode() {
perform_hax(box "deadcode".to_string());
}
pub fn main() {
perform_hax(box 42);
}
| perform_hax | identifier_name |
issue-2735.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 ... |
fn deadcode() {
perform_hax(box "deadcode".to_string());
}
pub fn main() {
perform_hax(box 42);
}
| {
box x as Box<hax+'static>
} | identifier_body |
db.rs | // Fucking Weeb
// Copyright © Jaume Delclòs Coll
//
// This file is part of Fucking Weeb.
//
// Fucking Weeb 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 o... |
pub player: String,
pub path: String,
pub autoplay: bool,
}
#[derive(Serialize, Deserialize, Clone)]
pub struct WeebDB {
pub settings: Settings,
pub shows: Vec<Show>,
}
pub fn load_db() -> WeebDB {
let default_settings = WeebDB {
settings: Settings {
player: "mpv".to_strin... | ttings { | identifier_name |
db.rs | // Fucking Weeb
// Copyright © Jaume Delclòs Coll
//
// This file is part of Fucking Weeb.
//
// Fucking Weeb 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 o... | Ok(a) => a,
Err(e) => {
println!("error decoding db json: {}", e.to_string());
default_settings
}
}
}
pub fn save_db(settings: &Settings, items: &Vec<Show>) {
let db = WeebDB {
settings: settings.clone(),
shows: items.clone(),
};
// TODO: ... | }
Ok(_) => ()
}
match serde_json::from_str(&s) { | random_line_split |
wait.rs | //! Wait for a process to change status
use crate::errno::Errno;
use crate::sys::signal::Signal;
use crate::unistd::Pid;
use crate::Result;
use cfg_if::cfg_if;
use libc::{self, c_int};
use std::convert::TryFrom;
libc_bitflags!(
/// Controls the behavior of [`waitpid`].
pub struct WaitPidFlag: c_int {
/... | (status: i32) -> bool {
libc::WCOREDUMP(status)
}
fn stopped(status: i32) -> bool {
libc::WIFSTOPPED(status)
}
fn stop_signal(status: i32) -> Result<Signal> {
Signal::try_from(libc::WSTOPSIG(status))
}
#[cfg(any(target_os = "android", target_os = "linux"))]
fn syscall_stop(status: i32) -> bool {
// F... | dumped_core | identifier_name |
wait.rs | //! Wait for a process to change status
use crate::errno::Errno;
use crate::sys::signal::Signal;
use crate::unistd::Pid;
use crate::Result;
use cfg_if::cfg_if;
use libc::{self, c_int};
use std::convert::TryFrom;
libc_bitflags!(
/// Controls the behavior of [`waitpid`].
pub struct WaitPidFlag: c_int {
/... |
fn signaled(status: i32) -> bool {
libc::WIFSIGNALED(status)
}
fn term_signal(status: i32) -> Result<Signal> {
Signal::try_from(libc::WTERMSIG(status))
}
fn dumped_core(status: i32) -> bool {
libc::WCOREDUMP(status)
}
fn stopped(status: i32) -> bool {
libc::WIFSTOPPED(status)
}
fn stop_signal(stat... | {
libc::WEXITSTATUS(status)
} | identifier_body |
wait.rs | //! Wait for a process to change status
use crate::errno::Errno;
use crate::sys::signal::Signal;
use crate::unistd::Pid;
use crate::Result;
use cfg_if::cfg_if;
use libc::{self, c_int};
use std::convert::TryFrom;
libc_bitflags!(
/// Controls the behavior of [`waitpid`].
pub struct WaitPidFlag: c_int {
/... | }
fn exited(status: i32) -> bool {
libc::WIFEXITED(status)
}
fn exit_status(status: i32) -> i32 {
libc::WEXITSTATUS(status)
}
fn signaled(status: i32) -> bool {
libc::WIFSIGNALED(status)
}
fn term_signal(status: i32) -> Result<Signal> {
Signal::try_from(libc::WTERMSIG(status))
}
fn dumped_core(stat... | StillAlive => None,
#[cfg(any(target_os = "android", target_os = "linux"))]
PtraceEvent(p, _, _) | PtraceSyscall(p) => Some(p),
}
} | random_line_split |
lint-dead-code-5.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 ... | {
Variant1(int),
Variant2 //~ ERROR: variant is never used
}
enum Enum2 {
Variant3(bool),
#[allow(dead_code)]
Variant4(int),
Variant5 { _x: int }, //~ ERROR: variant is never used: `Variant5`
Variant6(int), //~ ERROR: variant is never used: `Variant6`
_Variant7,
}
enum Enum3 { //~ ERR... | Enum1 | identifier_name |
lint-dead-code-5.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. | // except according to those terms.
#![allow(unused_variables)]
#![deny(dead_code)]
enum Enum1 {
Variant1(int),
Variant2 //~ ERROR: variant is never used
}
enum Enum2 {
Variant3(bool),
#[allow(dead_code)]
Variant4(int),
Variant5 { _x: int }, //~ ERROR: variant is never used: `Variant5`
Va... | //
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed | random_line_split |
lint-dead-code-5.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 v = Enum1::Variant1(1);
match v {
Enum1::Variant1(_) => (),
Enum1::Variant2 => ()
}
let x = Enum2::Variant3(true);
} | identifier_body | |
flags.rs | use libc::c_uint;
use ffi::*;
bitflags! {
#[doc="Environment options."]
#[derive(Default)]
pub struct EnvironmentFlags: c_uint {
#[doc="Use a fixed address for the mmap region. This flag must be specified"]
#[doc="when creating the environment, and is stored persistently in the environmen... | #[doc="`path` with `-lock` appended."]
const NO_SUB_DIR = MDB_NOSUBDIR;
#[doc="Use a writeable memory map unless `READ_ONLY` is set. This is faster and uses"]
#[doc="fewer mallocs, but loses protection from application bugs like wild pointer writes"]
#[doc="and other bad updates... | random_line_split | |
start-instance.rs | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
use aws_config::meta::region::RegionProviderChain;
use aws_sdk_ec2::{Client, Error, Region, PKG_VERSION};
use structopt::StructOpt;
#[derive(Debug, StructOpt)]
struct Opt {
/// The AWS Region.
... | let client = Client::new(&shared_config);
start_instance(&client, &instance_id).await
} |
let shared_config = aws_config::from_env().region(region_provider).load().await; | random_line_split |
start-instance.rs | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
use aws_config::meta::region::RegionProviderChain;
use aws_sdk_ec2::{Client, Error, Region, PKG_VERSION};
use structopt::StructOpt;
#[derive(Debug, StructOpt)]
struct Opt {
/// The AWS Region.
... | (client: &Client, id: &str) -> Result<(), Error> {
client.start_instances().instance_ids(id).send().await?;
println!("Started instance.");
Ok(())
}
// snippet-end:[ec2.rust.start-instance]
/// Starts an Amazon EC2 instance.
/// # Arguments
///
/// * `-i INSTANCE-ID` - The ID of the instances to start.
//... | start_instance | identifier_name |
start-instance.rs | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
use aws_config::meta::region::RegionProviderChain;
use aws_sdk_ec2::{Client, Error, Region, PKG_VERSION};
use structopt::StructOpt;
#[derive(Debug, StructOpt)]
struct Opt {
/// The AWS Region.
... |
let shared_config = aws_config::from_env().region(region_provider).load().await;
let client = Client::new(&shared_config);
start_instance(&client, &instance_id).await
}
| {
println!("EC2 client version: {}", PKG_VERSION);
println!(
"Region: {}",
region_provider.region().await.unwrap().as_ref()
);
println!("Instance ID: {}", instance_id);
println!();
} | conditional_block |
start-instance.rs | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
use aws_config::meta::region::RegionProviderChain;
use aws_sdk_ec2::{Client, Error, Region, PKG_VERSION};
use structopt::StructOpt;
#[derive(Debug, StructOpt)]
struct Opt {
/// The AWS Region.
... | println!();
}
let shared_config = aws_config::from_env().region(region_provider).load().await;
let client = Client::new(&shared_config);
start_instance(&client, &instance_id).await
}
| {
tracing_subscriber::fmt::init();
let Opt {
region,
instance_id,
verbose,
} = Opt::from_args();
let region_provider = RegionProviderChain::first_try(region.map(Region::new))
.or_default_provider()
.or_else(Region::new("us-west-2"));
println!();
if verbo... | identifier_body |
subst_output.rs | // Test substitutions involving only the outputs of the function.
extern crate crucible;
use crucible::*;
use crucible::method_spec::{MethodSpec, MethodSpecBuilder, clobber_globals};
fn f(x: u8) -> (u8, u8) {
(x, x + 1)
}
fn f_spec() -> MethodSpec {
let x = <u8>::symbolic("x");
let mut msb = MethodSpecBu... | #[crux_test]
fn use_f() {
f_spec().enable();
let a = u8::symbolic("a");
crucible_assume!(0 < a && a < 10);
let (b0, b1) = f(a);
crucible_assert!(b0 == a);
crucible_assert!(b1 == b0 + 1);
} | msb.gather_asserts();
msb.finish()
}
| random_line_split |
subst_output.rs | // Test substitutions involving only the outputs of the function.
extern crate crucible;
use crucible::*;
use crucible::method_spec::{MethodSpec, MethodSpecBuilder, clobber_globals};
fn f(x: u8) -> (u8, u8) {
(x, x + 1)
}
fn f_spec() -> MethodSpec {
let x = <u8>::symbolic("x");
let mut msb = MethodSpecBu... | () {
f_spec().enable();
let a = u8::symbolic("a");
crucible_assume!(0 < a && a < 10);
let (b0, b1) = f(a);
crucible_assert!(b0 == a);
crucible_assert!(b1 == b0 + 1);
}
| use_f | identifier_name |
subst_output.rs | // Test substitutions involving only the outputs of the function.
extern crate crucible;
use crucible::*;
use crucible::method_spec::{MethodSpec, MethodSpecBuilder, clobber_globals};
fn f(x: u8) -> (u8, u8) {
(x, x + 1)
}
fn f_spec() -> MethodSpec {
let x = <u8>::symbolic("x");
let mut msb = MethodSpecBu... | {
f_spec().enable();
let a = u8::symbolic("a");
crucible_assume!(0 < a && a < 10);
let (b0, b1) = f(a);
crucible_assert!(b0 == a);
crucible_assert!(b1 == b0 + 1);
} | identifier_body | |
user.rs | use diesel;
use diesel::prelude::*;
use diesel::pg::PgConnection;
use lower;
use regex::Regex;
use rocket::http::Status;
use rocket::response::Failure;
use bcrypt::{hash, verify, DEFAULT_COST};
use std::time::SystemTime;
use schema::users;
#[derive(Queryable, Identifiable)]
pub struct User {
pub id: i64,
pub ... | }
}
// Verifies the user's password
pub fn authenticate(conn: &PgConnection, user: &User) -> Result<bool, Failure> {
use schema::users::dsl::*;
let result = users
.filter(lower(username).eq(user.username.to_lowercase()))
.first::<User>(conn);
if resu... | {
use diesel::prelude::*;
match hash(&new_user.password[..], DEFAULT_COST) {
Ok(hashed) => {
new_user.password = hashed;
}
Err(e) => {
println!("Errow while hasing a password: {}", e);
return Err(Failure(Status::Interna... | identifier_body |
user.rs | use diesel;
use diesel::prelude::*;
use diesel::pg::PgConnection;
use lower;
use regex::Regex;
use rocket::http::Status;
use rocket::response::Failure;
use bcrypt::{hash, verify, DEFAULT_COST};
use std::time::SystemTime;
use schema::users;
#[derive(Queryable, Identifiable)]
pub struct User {
pub id: i64,
pub ... | (conn: &PgConnection) -> Result<Vec<User>, Failure> {
use diesel::prelude::*;
use schema::users::dsl::*;
let result = users.load::<User>(conn);
match result {
Ok(result) => Ok(result),
Err(e) => {
println!("Error while fetching the users: {}", e)... | all | identifier_name |
user.rs | use diesel;
use diesel::prelude::*;
use diesel::pg::PgConnection;
use lower;
use regex::Regex;
use rocket::http::Status;
use rocket::response::Failure;
use bcrypt::{hash, verify, DEFAULT_COST};
use std::time::SystemTime;
use schema::users;
#[derive(Queryable, Identifiable)]
pub struct User {
pub id: i64,
pub ... | Err(_) => Ok(false),
}
}
// Find & return a user by id
pub fn find(conn: &PgConnection, user_id: i64) -> Result<User, Failure> {
use diesel::prelude::*;
use schema::users::dsl::*;
let result = users.filter(id.eq(user_id)).first::<User>(conn);
match resu... | match verify(&result.unwrap().password_hash[..], &user.password_hash[..]) {
Ok(_) => Ok(true), | random_line_split |
tokens.rs | use files::dump;
pub struct | <'a>
{
pub name: &'a str,
pub range: (usize, usize),
pub value: String,
pub line_number: usize,
}
impl <'a> Token<'a>
{
#[allow(dead_code)]
pub fn clone(&self) -> Token<'a>
{
Token
{
name: self.name.clone(),
range: self.range.clone(),
valu... | Token | identifier_name |
tokens.rs | use files::dump;
pub struct Token<'a>
{
pub name: &'a str,
pub range: (usize, usize),
pub value: String,
pub line_number: usize,
}
impl <'a> Token<'a>
{
#[allow(dead_code)]
pub fn clone(&self) -> Token<'a>
{
Token
{
name: self.name.clone(),
range: se... |
}
fn format_for_print(&self, console_out: bool) -> String
{
// Create a String of 100 consecutive spaces
let mut spaces = String::new();
for _ in (0..100)
{
spaces.push_str(" ");
}
// Spacing definitions
let name_column_width = 30;
... | { dump(file_path, lexed_token_string); } | conditional_block |
tokens.rs | use files::dump;
pub struct Token<'a>
{
pub name: &'a str,
pub range: (usize, usize),
pub value: String,
pub line_number: usize,
}
impl <'a> Token<'a>
{
#[allow(dead_code)]
pub fn clone(&self) -> Token<'a>
{
Token
{
name: self.name.clone(),
range: se... | lexed_token_string.push_str(token.name);
if name_pad_length > 0 { lexed_token_string.push_str(&spaces[..name_pad_length]); }
else { lexed_token_string.push_str(" "); }
// Line number
lexed_token_string.push_str("ln:");
lexed_token_string.push_str(... | {
// Create a String of 100 consecutive spaces
let mut spaces = String::new();
for _ in (0..100)
{
spaces.push_str(" ");
}
// Spacing definitions
let name_column_width = 30;
let line_number_column_width = 20;
let mut lexed_token_strin... | identifier_body |
tokens.rs | use files::dump;
pub struct Token<'a>
{
pub name: &'a str,
pub range: (usize, usize),
pub value: String,
pub line_number: usize,
}
impl <'a> Token<'a>
{
#[allow(dead_code)]
pub fn clone(&self) -> Token<'a>
{
Token
{
name: self.name.clone(),
range: se... | }
lexed_token_string
}
} | if console_out { println!("\t{}\t{:?}\t{}", token.name, token.range, token.value); } | random_line_split |
text.mako.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
<%namespace name="helpers" file="/helpers.mako.rs" />
<%helpers:shorthand name="text-decoration"
... |
% endif
Ok(())
}
}
</%helpers:shorthand>
| {
dest.write_str(" ")?;
self.text_decoration_color.to_css(dest)?;
} | conditional_block |
text.mako.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
<%namespace name="helpers" file="/helpers.mako.rs" />
<%helpers:shorthand name="text-decoration"
... |
% if product == "gecko" or data.testing:
if self.text_decoration_style!= &text_decoration_style::SpecifiedValue::solid {
dest.write_str(" ")?;
self.text_decoration_style.to_css(dest)?;
}
if self.text_decoration_color.p... | fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write {
self.text_decoration_line.to_css(dest)?; | random_line_split |
text.mako.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
<%namespace name="helpers" file="/helpers.mako.rs" />
<%helpers:shorthand name="text-decoration"
... | (context: &ParserContext, input: &mut Parser) -> Result<Longhands, ()> {
% if product == "gecko" or data.testing:
let (mut line, mut style, mut color, mut any) = (None, None, None, false);
% else:
let (mut line, mut any) = (None, false);
% endif
loop {
... | parse_value | identifier_name |
text.mako.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
<%namespace name="helpers" file="/helpers.mako.rs" />
<%helpers:shorthand name="text-decoration"
... | parse_component!(line, text_decoration_line);
% if product == "gecko" or data.testing:
parse_component!(style, text_decoration_style);
parse_component!(color, text_decoration_color);
% endif
break;
}
if!any {
... | {
% if product == "gecko" or data.testing:
let (mut line, mut style, mut color, mut any) = (None, None, None, false);
% else:
let (mut line, mut any) = (None, false);
% endif
loop {
macro_rules! parse_component {
($value:ident, $module... | 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::codegen::InheritTypes:... | prefix: Option<DOMString>,
document: JSRef<Document>) -> Temporary<HTMLTableHeaderCellElement> {
let element = HTMLTableHeaderCellElement::new_inherited(localName, prefix, document);
Node::reflect_node(box element, document, HTMLTableHeaderCellElementBinding::Wrap)
}
} | #[allow(unrooted_must_root)]
pub fn new(localName: DOMString, | 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::codegen::InheritTypes:... | (&self) -> bool {
*self.type_id() == EventTargetTypeId::Node(NodeTypeId::Element(
ElementTypeId::HTMLElement(
HTMLElementTypeId::HTMLTableCellElement(
HTMLTabl... | is_htmltableheadercellelement | identifier_name |
rom_fp256bn_64.rs | /*
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this f... | [
[0x5EB8061615001, 0xD1, 0x0, 0x0, 0x0],
[
0xAA5DACA05AA80C,
0x65FB1299921A8D,
0x5EEE71A49E0CDC,
0xFFFCF0CD46E5F2,
0xFFFFFFFF,
],
[
0xAA5DACA05AA80D,
0x65FB1299921A8D,
0x5EEE71A49E0CDC,
... | 0xFFFFFFFF,
],
[0x5EB8061615002, 0xD1, 0x0, 0x0, 0x0],
], | random_line_split |
trait_default_method_xc_aux.rs | #[allow(default_methods)];
pub struct Something { x: int }
pub trait A {
fn f(&self) -> int;
fn g(&self) -> int { 10 }
fn h(&self) -> int { 10 }
}
impl A for int {
fn f(&self) -> int { 10 }
}
impl A for Something {
fn f(&self) -> int { 10 }
}
trait B<T> {
fn thing<U>(&self, x: T, y: U) -> ... |
}
impl<T> B<T> for int { }
impl B<float> for bool { }
pub trait TestEquality {
fn test_eq(&self, rhs: &Self) -> bool;
fn test_neq(&self, rhs: &Self) -> bool {
!self.test_eq(rhs)
}
}
impl TestEquality for int {
fn test_eq(&self, rhs: &int) -> bool {
*self == *rhs
}
}
| { (x, y) } | identifier_body |
trait_default_method_xc_aux.rs | #[allow(default_methods)];
pub struct Something { x: int }
pub trait A {
fn f(&self) -> int;
fn g(&self) -> int { 10 }
fn h(&self) -> int { 10 }
}
impl A for int {
fn f(&self) -> int { 10 }
} |
trait B<T> {
fn thing<U>(&self, x: T, y: U) -> (T, U) { (x, y) }
}
impl<T> B<T> for int { }
impl B<float> for bool { }
pub trait TestEquality {
fn test_eq(&self, rhs: &Self) -> bool;
fn test_neq(&self, rhs: &Self) -> bool {
!self.test_eq(rhs)
}
}
impl TestEquality for int {
fn test_eq(&... |
impl A for Something {
fn f(&self) -> int { 10 }
} | random_line_split |
trait_default_method_xc_aux.rs | #[allow(default_methods)];
pub struct | { x: int }
pub trait A {
fn f(&self) -> int;
fn g(&self) -> int { 10 }
fn h(&self) -> int { 10 }
}
impl A for int {
fn f(&self) -> int { 10 }
}
impl A for Something {
fn f(&self) -> int { 10 }
}
trait B<T> {
fn thing<U>(&self, x: T, y: U) -> (T, U) { (x, y) }
}
impl<T> B<T> for int { }
im... | Something | identifier_name |
names.rs | //! This example of boxcars extracts all the player names found in the "PlayerStats" property of the
//! header. This property may be absent in some replays or lack players that drop or join mid-game.
//! A more foolproof approach is to scour the network data for a specific property:
//! "Engine.PlayerReplicationInfo:P... |
Ok(())
}
| {
println!("No player names found in the header as network data couldn't be decoded")
} | conditional_block |
names.rs | //! This example of boxcars extracts all the player names found in the "PlayerStats" property of the
//! header. This property may be absent in some replays or lack players that drop or join mid-game.
//! A more foolproof approach is to scour the network data for a specific property:
//! "Engine.PlayerReplicationInfo:P... | .filter(|(prop_name, _)| *prop_name == "Name")
.filter_map(|(_, prop_val)| prop_val.as_string())
}
/// Given network frames and the object id to "Engine.PlayerReplicationInfo:PlayerName", comb
/// through all the attributes looking for attributes that have our object id.
fn names_in_network(frames: &[box... | .iter()
.flat_map(|v| v.iter()) | random_line_split |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.