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 |
|---|---|---|---|---|
block_retrieval.rs | // Copyright (c) The Diem Core Contributors
// SPDX-License-Identifier: Apache-2.0
use crate::block::Block;
use anyhow::ensure;
use diem_crypto::hash::HashValue;
use diem_types::validator_verifier::ValidatorVerifier;
use serde::{Deserialize, Serialize};
use short_hex_str::AsShortHexStr;
use std::fmt;
pub const MAX_BL... | {
status: BlockRetrievalStatus,
blocks: Vec<Block>,
}
impl BlockRetrievalResponse {
pub fn new(status: BlockRetrievalStatus, blocks: Vec<Block>) -> Self {
Self { status, blocks }
}
pub fn status(&self) -> BlockRetrievalStatus {
self.status.clone()
}
pub fn blocks(&self) -... | BlockRetrievalResponse | identifier_name |
block_retrieval.rs | // Copyright (c) The Diem Core Contributors
// SPDX-License-Identifier: Apache-2.0
use crate::block::Block;
use anyhow::ensure;
use diem_crypto::hash::HashValue;
use diem_types::validator_verifier::ValidatorVerifier;
use serde::{Deserialize, Serialize};
use short_hex_str::AsShortHexStr;
use std::fmt;
pub const MAX_BL... |
}
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq)]
pub enum BlockRetrievalStatus {
// Successfully fill in the request.
Succeeded,
// Can not find the block corresponding to block_id.
IdNotFound,
// Can not find enough blocks but find some.
NotEnoughBlocks,
}
/// Carries the ret... | {
write!(
f,
"[BlockRetrievalRequest starting from id {} with {} blocks]",
self.block_id, self.num_blocks
)
} | identifier_body |
block_retrieval.rs | // Copyright (c) The Diem Core Contributors
// SPDX-License-Identifier: Apache-2.0
use crate::block::Block;
use anyhow::ensure;
use diem_crypto::hash::HashValue;
use diem_types::validator_verifier::ValidatorVerifier;
use serde::{Deserialize, Serialize};
use short_hex_str::AsShortHexStr;
use std::fmt;
pub const MAX_BL... |
_ => write!(f, "[BlockRetrievalResponse: status: {:?}]", self.status()),
}
}
}
| {
write!(
f,
"[BlockRetrievalResponse: status: {:?}, num_blocks: {}, block_ids: ",
self.status(),
self.blocks().len(),
)?;
f.debug_list()
.entries(self.blocks.iter().map(|... | conditional_block |
block_retrieval.rs | // Copyright (c) The Diem Core Contributors
// SPDX-License-Identifier: Apache-2.0
use crate::block::Block;
use anyhow::ensure;
use diem_crypto::hash::HashValue;
use diem_types::validator_verifier::ValidatorVerifier;
use serde::{Deserialize, Serialize};
use short_hex_str::AsShortHexStr;
use std::fmt;
pub const MAX_BL... | .map(|_| ())
}
}
impl fmt::Display for BlockRetrievalResponse {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self.status() {
BlockRetrievalStatus::Succeeded => {
write!(
f,
"[BlockRetrievalResponse: status: {... | expected_id,
block.id()
);
Ok(block.parent_id())
}) | random_line_split |
spawn-types.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | {
let (tx, _rx) = channel::<int>();
let t = Thread::scoped(move|| iotask(&tx, "localhost".to_string()) );
t.join().ok().unwrap();
} | identifier_body | |
spawn-types.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 ... |
use std::thread::Thread;
use std::sync::mpsc::{channel, Sender};
type ctx = Sender<int>;
fn iotask(_tx: &ctx, ip: String) {
assert_eq!(ip, "localhost".to_string());
}
pub fn main() {
let (tx, _rx) = channel::<int>();
let t = Thread::scoped(move|| iotask(&tx, "localhost".to_string()) );
t.join().ok()... | parameters. This is based on a test case for #520 provided by Rob
Arnold.
*/ | random_line_split |
spawn-types.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 ... | (_tx: &ctx, ip: String) {
assert_eq!(ip, "localhost".to_string());
}
pub fn main() {
let (tx, _rx) = channel::<int>();
let t = Thread::scoped(move|| iotask(&tx, "localhost".to_string()) );
t.join().ok().unwrap();
}
| iotask | identifier_name |
enumerate_domains.rs | use std::{
io,
os::raw::{
c_char,
c_void,
},
pin::Pin,
task::{
Context,
Poll,
},
};
use crate::{
cstr,
ffi,
inner,
interface::Interface,
};
type CallbackStream = crate::stream::ServiceStream<inner::OwnedService, EnumerateResult>;
/// Whether to enumerate domains which are browsed or domains for whi... | type Item = io::Result<EnumerateResult>;
fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
self.stream().poll_next(cx)
}
}
/// Domain enumeration result
///
/// See [DNSServiceDomainEnumReply](https://developer.apple.com/documentation/dnssd/dnsservicedomainenumreply).
#[deriv... |
impl futures_core::Stream for EnumerateDomains { | random_line_split |
enumerate_domains.rs | use std::{
io,
os::raw::{
c_char,
c_void,
},
pin::Pin,
task::{
Context,
Poll,
},
};
use crate::{
cstr,
ffi,
inner,
interface::Interface,
};
type CallbackStream = crate::stream::ServiceStream<inner::OwnedService, EnumerateResult>;
/// Whether to enumerate domains which are browsed or domains for whi... |
}
bitflags::bitflags! {
/// Flags for [`EnumerateDomains`](struct.EnumerateDomains.html)
#[derive(Default)]
pub struct EnumeratedFlags: ffi::DNSServiceFlags {
/// Indicates at least one more result is pending in the queue. If
/// not set there still might be more results coming in the future.
///
/// See ... | {
match e {
Enumerate::BrowseDomains => ffi::FLAGS_BROWSE_DOMAINS,
Enumerate::RegistrationDomains => ffi::FLAGS_REGISTRATION_DOMAINS,
}
} | identifier_body |
enumerate_domains.rs | use std::{
io,
os::raw::{
c_char,
c_void,
},
pin::Pin,
task::{
Context,
Poll,
},
};
use crate::{
cstr,
ffi,
inner,
interface::Interface,
};
type CallbackStream = crate::stream::ServiceStream<inner::OwnedService, EnumerateResult>;
/// Whether to enumerate domains which are browsed or domains for whi... | (enumerate: Enumerate, interface: Interface) -> EnumerateDomains {
crate::init();
let stream = CallbackStream::new(move |sender| {
inner::OwnedService::enumerate_domains(
enumerate.into(),
interface.into_raw(),
Some(enumerate_callback),
sender,
)
})
.into();
EnumerateDomains { stream }
}
| enumerate_domains | identifier_name |
lib.rs | //! Time handling for games and other real-time simulations.
//!
//! Provides types and helpers for dealing with time in games. `game_time` allows for
//! easy decoupling of internal "game" time and external "wall" time, as well as tracking
//! frame rate.
//!
//! Additionally, different kinds of time steps may be used... | //! sim_time = clock.tick(&step);
//! println!("Frame #{} at time={:?}", sim_time.frame_number(), sim_time.total_game_time());
//! }
//! ```
//!
//! Run a simulation at 30fps, sleeping if necessary to maintain the framerate:
//!
//! ```rust
//! use game_time::{GameClock, FrameCounter, FrameCount, FloatDuration}... | //! while sim_time.total_game_time() < end_time { | random_line_split |
factorial.rs | #[macro_use]
extern crate qmlrs;
use std::fs::File;
use std::io::prelude::*;
struct | ;
impl Factorial {
fn calculate(&self, x: i64) -> i64 {
(1..x+1).fold(1, |t,c| t * c)
}
}
Q_OBJECT! { Factorial:
slot fn calculate(i64);
// signal fn test();
}
fn main() {
let mut engine = qmlrs::Engine::new();
engine.set_property("factorial", Factorial);
engine.load_local_file("examples/factorial... | Factorial | identifier_name |
factorial.rs | #[macro_use]
extern crate qmlrs;
use std::fs::File;
use std::io::prelude::*;
struct Factorial; |
Q_OBJECT! { Factorial:
slot fn calculate(i64);
// signal fn test();
}
fn main() {
let mut engine = qmlrs::Engine::new();
engine.set_property("factorial", Factorial);
engine.load_local_file("examples/factorial_ui.qml");
engine.exec();
// test with string:
let mut engine2 = qmlrs::Engine::new();
e... | impl Factorial {
fn calculate(&self, x: i64) -> i64 {
(1..x+1).fold(1, |t,c| t * c)
}
} | random_line_split |
traversal.rs | (&self) -> bool {
self.unstyled_children_only
}
}
/// Enum to prevent duplicate logging.
pub enum LogBehavior {
/// We should log.
MayLog,
/// We shouldn't log.
DontLog,
}
use self::LogBehavior::*;
impl LogBehavior {
fn allow(&self) -> bool { matches!(*self, MayLog) }
}
/// The kind of... | traverse_unstyled_children_only | identifier_name | |
traversal.rs | TraversalDriver::Parallel)
}
}
/// A DOM Traversal trait, that is used to generically implement styling for
/// Gecko and Servo.
pub trait DomTraversal<E: TElement> : Sync {
/// The thread-local context, used to store non-thread-safe stuff that needs
/// to be used in the traversal, and of which we use on... | };
return data.get_restyle()
.map_or(false, |r| r.hint.has_animation_hint() || r.recascade);
}
// If the dirty descendants bit is set, we need to traverse no
// matter what. Skip examining the ElementD... | {
// Non-incremental layout visits every node.
if cfg!(feature = "servo") && opts::get().nonincremental_layout {
return true;
}
match node.as_element() {
None => Self::text_node_needs_traversal(node),
Some(el) => {
// In case of animat... | identifier_body |
traversal.rs | , TraversalDriver::Parallel)
}
}
/// A DOM Traversal trait, that is used to generically implement styling for
/// Gecko and Servo.
pub trait DomTraversal<E: TElement> : Sync {
/// The thread-local context, used to store non-thread-safe stuff that needs
/// to be used in the traversal, and of which we use o... | // an Element is changed.
if cfg!(feature = "gecko") && thread_local.is_initial_style() &&
parent_data.styles().primary.values().has_moz_binding() {
if log.allow() { debug!("Parent {:?} has XBL binding, deferring traversal", parent); }
return false;
}
... | // changing bindings), since that adds complexity and is rarer. If it
// happens, we may just end up doing wasted work, since Gecko
// recursively drops Servo ElementData when the XBL insertion parent of | random_line_split |
opcode.rs | enum_from_primitive! {
#[derive(Debug)]
pub enum Opcode {
// Control
NoOp = 0x00,
// Stop = 0x10,
// Halt = 0x76,
Special = 0xCB,
// Flow Control
Jump = 0xC3,
JumpNonZero = 0xC2,
JumpZero = 0xCA,
JumpNonCarry = 0xD2,
JumpCarry = 0xDA,
JumpRelative = 0x18,
JumpRel... | LoadSpIntoImmAddr = 0x08,
PopBc = 0xC1,
PushBc = 0xC5,
// 8-bit Math
IncrementB = 0x04,
IncrementC = 0x0C,
DecrementB = 0x05,
DecrementC = 0x0D,
DecrementA = 0x3D,
SubtractL = 0x95,
XorA = 0xAF,
CompareImm = 0xFE,
// 16-bit Math
IncrementDe = 0x13,
Increment... | LoadImmIntoHl = 0x21,
LoadImmIntoSp = 0x31, | random_line_split |
errors.rs | use neon::prelude::*;
pub fn new_error(mut cx: FunctionContext) -> JsResult<JsError> {
let msg = cx.argument::<JsString>(0)?.value(&mut cx);
cx.error(msg)
}
pub fn new_type_error(mut cx: FunctionContext) -> JsResult<JsError> {
let msg = cx.argument::<JsString>(0)?.value(&mut cx);
cx.type_error(msg)
... | (mut cx: FunctionContext) -> JsResult<JsError> {
let msg = cx.argument::<JsString>(0)?.value(&mut cx);
cx.range_error(msg)
}
pub fn throw_error(mut cx: FunctionContext) -> JsResult<JsUndefined> {
let msg = cx.argument::<JsString>(0)?.value(&mut cx);
cx.throw_error(msg)
}
pub fn downcast_error(mut cx... | new_range_error | identifier_name |
errors.rs | use neon::prelude::*;
pub fn new_error(mut cx: FunctionContext) -> JsResult<JsError> {
let msg = cx.argument::<JsString>(0)?.value(&mut cx);
cx.error(msg)
}
pub fn new_type_error(mut cx: FunctionContext) -> JsResult<JsError> {
let msg = cx.argument::<JsString>(0)?.value(&mut cx);
cx.type_error(msg)
... |
pub fn downcast_error(mut cx: FunctionContext) -> JsResult<JsString> {
let s = cx.string("hi");
if let Err(e) = s.downcast::<JsNumber, _>(&mut cx) {
Ok(cx.string(format!("{}", e)))
} else {
panic!()
}
}
| {
let msg = cx.argument::<JsString>(0)?.value(&mut cx);
cx.throw_error(msg)
} | identifier_body |
errors.rs | use neon::prelude::*;
pub fn new_error(mut cx: FunctionContext) -> JsResult<JsError> {
let msg = cx.argument::<JsString>(0)?.value(&mut cx);
cx.error(msg)
}
|
pub fn new_range_error(mut cx: FunctionContext) -> JsResult<JsError> {
let msg = cx.argument::<JsString>(0)?.value(&mut cx);
cx.range_error(msg)
}
pub fn throw_error(mut cx: FunctionContext) -> JsResult<JsUndefined> {
let msg = cx.argument::<JsString>(0)?.value(&mut cx);
cx.throw_error(msg)
}
pub f... | pub fn new_type_error(mut cx: FunctionContext) -> JsResult<JsError> {
let msg = cx.argument::<JsString>(0)?.value(&mut cx);
cx.type_error(msg)
} | random_line_split |
errors.rs | use neon::prelude::*;
pub fn new_error(mut cx: FunctionContext) -> JsResult<JsError> {
let msg = cx.argument::<JsString>(0)?.value(&mut cx);
cx.error(msg)
}
pub fn new_type_error(mut cx: FunctionContext) -> JsResult<JsError> {
let msg = cx.argument::<JsString>(0)?.value(&mut cx);
cx.type_error(msg)
... | else {
panic!()
}
}
| {
Ok(cx.string(format!("{}", e)))
} | conditional_block |
error.rs | //! This module contains enum Error.
//! Error type represents all possible errors that can occur when dealing
//! with the generic or any dedicated-exchange API
use serde_json;
use hyper;
use data_encoding;
use exchange::Exchange;
error_chain!{
types {
Error, ErrorKind, ResultExt, Result;
}
for... |
MissingPrice{
description("MissingPrice")
display("No price specified.")
}
InvalidConfigType(expected: Exchange, find: Exchange){
description("InvalidConfigType")
display("Invalid config: \nExpected: {:?}\nFind: {:?}", expected, find)
... | InsufficientOrderSize {
description("InsufficientOrderSize")
display("Your order is not big enough.")
} | random_line_split |
format.rs | #[macro_use]
extern crate pretty_assertions;
#[allow(unused)]
mod support;
use tokio::io::AsyncWrite;
use languageserver_types::*;
use crate::support::{did_change_event, expect_notification, expect_response, hover};
async fn | <W:?Sized>(stdin: &mut W, id: u64, uri: &str)
where
W: AsyncWrite + std::marker::Unpin,
{
let hover = support::method_call(
"textDocument/formatting",
id,
DocumentFormattingParams {
text_document: TextDocumentIdentifier {
uri: support::test_url(uri),
... | format | identifier_name |
format.rs | #[macro_use]
extern crate pretty_assertions;
#[allow(unused)]
mod support;
use tokio::io::AsyncWrite;
use languageserver_types::*;
use crate::support::{did_change_event, expect_notification, expect_response, hover};
async fn format<W:?Sized>(stdin: &mut W, id: u64, uri: &str)
where
W: AsyncWrite + std::marker:... | },
options: FormattingOptions {
tab_size: 4,
insert_spaces: true,
properties: Default::default(),
},
},
);
support::write_message(stdin, hover).await.unwrap();
}
#[test]
fn simple() {
let text = r#"
let x = ... | "textDocument/formatting",
id,
DocumentFormattingParams {
text_document: TextDocumentIdentifier {
uri: support::test_url(uri), | random_line_split |
format.rs | #[macro_use]
extern crate pretty_assertions;
#[allow(unused)]
mod support;
use tokio::io::AsyncWrite;
use languageserver_types::*;
use crate::support::{did_change_event, expect_notification, expect_response, hover};
async fn format<W:?Sized>(stdin: &mut W, id: u64, uri: &str)
where
W: AsyncWrite + std::marker:... |
#[test]
fn simple() {
let text = r#"
let x = 1
x +
2
"#;
let expected = r#"
let x = 1
x + 2
"#;
support::send_rpc(move |stdin, stdout| {
Box::pin(async move {
support::did_open(stdin, "test", text).await;
let _: PublishDiagnosticsParams = expect_notification... | {
let hover = support::method_call(
"textDocument/formatting",
id,
DocumentFormattingParams {
text_document: TextDocumentIdentifier {
uri: support::test_url(uri),
},
options: FormattingOptions {
tab_size: 4,
... | identifier_body |
macro_rules.rs | #![allow(dead_code)]
//! Used to test that certain lints don't trigger in imported external macros
#[macro_export]
macro_rules! foofoo {
() => {
loop {}
};
}
#[macro_export]
macro_rules! must_use_unit {
() => {
#[must_use]
fn foo() {}
};
}
#[macro_export]
macro_rules! try_err... | }
#[macro_export]
macro_rules! take_external {
($s:expr) => {
std::mem::replace($s, Default::default())
};
}
#[macro_export]
macro_rules! option_env_unwrap_external {
($env: expr) => {
option_env!($env).unwrap()
};
($env: expr, $message: expr) => {
option_env!($env).expect(... | let z = y + "...";
}; | random_line_split |
int_macros.rs | // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
// |
#![doc(hidden)]
macro_rules! int_module { ($T:ty, $bits:expr) => (
// FIXME(#11621): Should be deprecated once CTFE is implemented in favour of
// calling the `mem::size_of` function.
#[unstable]
pub const BITS : uint = $bits;
// FIXME(#11621): Should be deprecated once CTFE is implemented in favour of
// calling th... | // 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 according to those terms. | random_line_split |
tests.rs | use std::ops::Deref;
use std::str;
use digest::Digest;
use rustc_serialize as ser;
use rustc_serialize::hex::{FromHex, ToHex};
#[derive(Debug, PartialEq, Eq)]
pub struct | (Vec<u8>);
impl Deref for Data {
type Target = [u8];
fn deref(&self) -> &[u8] {
&*self.0
}
}
impl ser::Decodable for Data {
fn decode<D: ser::Decoder>(d: &mut D) -> Result<Data, D::Error> {
let data = try!(d.read_str());
if data.starts_with("hex:") {
Ok(Data(data[4.... | Data | identifier_name |
tests.rs | use std::ops::Deref;
use std::str;
use digest::Digest;
use rustc_serialize as ser;
use rustc_serialize::hex::{FromHex, ToHex};
#[derive(Debug, PartialEq, Eq)]
pub struct Data(Vec<u8>);
impl Deref for Data {
type Target = [u8];
fn deref(&self) -> &[u8] {
&*self.0
}
}
impl ser::Decodable for Data {... | else {
Ok(Data(data.into()))
}
}
}
#[derive(RustcDecodable)]
pub struct Test {
input: Data,
output: Data,
}
impl Test {
pub fn test<T: Testable>(&self, tested: T) {
tested.test(self);
}
}
pub trait Testable: Sized {
fn test(self, &Test);
}
impl<T> Testable for T
... | {
Ok(Data(data[4..].from_hex().unwrap()))
} | conditional_block |
tests.rs | use std::ops::Deref;
use std::str;
use digest::Digest;
use rustc_serialize as ser;
use rustc_serialize::hex::{FromHex, ToHex};
#[derive(Debug, PartialEq, Eq)]
pub struct Data(Vec<u8>);
impl Deref for Data {
type Target = [u8];
fn deref(&self) -> &[u8] {
&*self.0
}
}
impl ser::Decodable for Data {... | pub trait Testable: Sized {
fn test(self, &Test);
}
impl<T> Testable for T
where T: Digest + Sized
{
fn test(mut self, test: &Test) {
self.update(&*test.input);
let mut output = vec![0; T::output_bytes()];
self.result(&mut output[..]);
assert!(&*test.output == &output[..],
... | random_line_split | |
comparison_benches.rs | #![feature(test)]
extern crate futures;
extern crate test;
extern crate tokio;
extern crate trust_dns_client;
extern crate trust_dns_proto;
extern crate trust_dns_server;
use std::env;
use std::fs::{DirBuilder, File};
use std::mem;
use std::net::{Ipv4Addr, SocketAddr, ToSocketAddrs};
use std::path::Path;
use std::pr... | .next()
.unwrap();
let (stream, sender) = TcpClientStream::<AsyncIo02As03<TcpStream>>::new::<TokioTime>(addr);
let mp = DnsMultiplexer::new(stream, sender, None::<Arc<Signer>>);
bench(b, mp);
// cleaning up the named process
drop(named);
}
// downloaded from https://www.isc.org/downl... | .to_socket_addrs()
.unwrap() | random_line_split |
comparison_benches.rs | #![feature(test)]
extern crate futures;
extern crate test;
extern crate tokio;
extern crate trust_dns_client;
extern crate trust_dns_proto;
extern crate trust_dns_server;
use std::env;
use std::fs::{DirBuilder, File};
use std::mem;
use std::net::{Ipv4Addr, SocketAddr, ToSocketAddrs};
use std::path::Path;
use std::pr... | (&mut self) {
self.named.kill().expect("could not kill process");
self.named.wait().expect("waiting failed");
}
}
fn wrap_process(named: Child, server_port: u16) -> NamedProcess {
let mut started = false;
for _ in 0..20 {
let mut io_loop = Runtime::new().unwrap();
let addr:... | drop | identifier_name |
comparison_benches.rs | #![feature(test)]
extern crate futures;
extern crate test;
extern crate tokio;
extern crate trust_dns_client;
extern crate trust_dns_proto;
extern crate trust_dns_server;
use std::env;
use std::fs::{DirBuilder, File};
use std::mem;
use std::net::{Ipv4Addr, SocketAddr, ToSocketAddrs};
use std::path::Path;
use std::pr... | .arg(&format!("--zonedir={}", zone_dir))
.arg(&format!("--port={}", test_port))
.spawn()
.expect("failed to start named");
//
let process = wrap_process(named, test_port);
// return handle to child process
(process, test_port)
}
/// Runs the bench tesk using the specified... | {
// find a random port to listen on
let test_port = find_test_port();
let ws_root = env::var("WORKSPACE_ROOT").unwrap_or_else(|_| "..".to_owned());
let named_path = format!("{}/target/release/named", ws_root);
let config_path = format!(
"{}/tests/test-data/named_test_configs/example.toml",... | identifier_body |
comparison_benches.rs | #![feature(test)]
extern crate futures;
extern crate test;
extern crate tokio;
extern crate trust_dns_client;
extern crate trust_dns_proto;
extern crate trust_dns_server;
use std::env;
use std::fs::{DirBuilder, File};
use std::mem;
use std::net::{Ipv4Addr, SocketAddr, ToSocketAddrs};
use std::path::Path;
use std::pr... | else {
unreachable!();
}
b.iter(|| {
let response = io_loop.block_on(client.query(name.clone(), DNSClass::IN, RecordType::A));
response.unwrap();
});
}
#[bench]
fn trust_dns_udp_bench(b: &mut Bencher) {
let (named, server_port) = trust_dns_process();
let addr: SocketAddr ... | {
assert_eq!(address, &Ipv4Addr::new(127, 0, 0, 1));
} | conditional_block |
event.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 devtools_traits::{TimelineMarker, TimelineMarkerType};
use dom::bindings::callback::ExceptionHandling;
use dom... |
if event.stop_immediate.get() {
return found;
}
// TODO: step 2.7.
}
// Step 3.
found
}
| {
window.emit_timeline_marker(marker.end());
} | conditional_block |
event.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 devtools_traits::{TimelineMarker, TimelineMarkerType};
use dom::bindings::callback::ExceptionHandling;
use dom... |
}
// https://html.spec.whatwg.org/multipage/#fire-a-simple-event
pub struct SimpleEventRunnable {
pub target: Trusted<EventTarget>,
pub name: Atom,
}
impl Runnable for SimpleEventRunnable {
fn name(&self) -> &'static str { "SimpleEventRunnable" }
fn handler(self: Box<SimpleEventRunnable>) {
... | {
let target = self.target.root();
let bubbles = self.bubbles;
let cancelable = self.cancelable;
target.fire_event_with_params(self.name, bubbles, cancelable);
} | identifier_body |
event.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 devtools_traits::{TimelineMarker, TimelineMarkerType};
use dom::bindings::callback::ExceptionHandling;
use dom... | (bubbles: EventCancelable) -> Self {
match bubbles {
EventCancelable::Cancelable => true,
EventCancelable::NotCancelable => false
}
}
}
#[derive(JSTraceable, Copy, Clone, Debug, PartialEq, Eq)]
#[repr(u16)]
#[derive(HeapSizeOf)]
pub enum EventPhase {
None = EventCon... | from | identifier_name |
event.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 devtools_traits::{TimelineMarker, TimelineMarkerType};
use dom::bindings::callback::ExceptionHandling;
use dom... |
#[inline]
// https://dom.spec.whatwg.org/#concept-event-dispatch Steps 10-12.
fn clear_dispatching_flags(&self) {
assert!(self.dispatching.get());
self.dispatching.set(false);
self.stop_propagation.set(false);
self.stop_immediate.set(false);
self.phase.set(EventPhas... | pub fn dispatching(&self) -> bool {
self.dispatching.get()
} | random_line_split |
vector.rs | // Copyright 2014 Michael Yang. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
#[cfg(not(feature = "default"))]
use libc::c_int;
#[cfg(feature = "default")]
pub use rblas::vector::Vector;
#[cfg(not(feature = "default"))]
/// Methods that al... | /// An unsafe pointer to a contiguous block of memory.
fn as_ptr(&self) -> *const T;
/// An unsafe mutable pointer to a contiguous block of memory.
fn as_mut_ptr(&mut self) -> *mut T;
} | fn inc(&self) -> c_int { 1 }
/// The number of elements in the vector.
fn len(&self) -> c_int; | random_line_split |
vector.rs | // Copyright 2014 Michael Yang. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
#[cfg(not(feature = "default"))]
use libc::c_int;
#[cfg(feature = "default")]
pub use rblas::vector::Vector;
#[cfg(not(feature = "default"))]
/// Methods that al... | (&self) -> c_int { 1 }
/// The number of elements in the vector.
fn len(&self) -> c_int;
/// An unsafe pointer to a contiguous block of memory.
fn as_ptr(&self) -> *const T;
/// An unsafe mutable pointer to a contiguous block of memory.
fn as_mut_ptr(&mut self) -> *mut T;
}
| inc | identifier_name |
vector.rs | // Copyright 2014 Michael Yang. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
#[cfg(not(feature = "default"))]
use libc::c_int;
#[cfg(feature = "default")]
pub use rblas::vector::Vector;
#[cfg(not(feature = "default"))]
/// Methods that al... |
/// The number of elements in the vector.
fn len(&self) -> c_int;
/// An unsafe pointer to a contiguous block of memory.
fn as_ptr(&self) -> *const T;
/// An unsafe mutable pointer to a contiguous block of memory.
fn as_mut_ptr(&mut self) -> *mut T;
}
| { 1 } | 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/. */
#![feature(box_syntax)]
#![feature(core_intrinsics)]
#![feature(custom_derive)]
#![feature(fnbox)]
#![feature(opti... | {
let a: &T = &**a;
let b: &T = &**b;
(a as *const T) == (b as *const T)
} | 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/. */
#![feature(box_syntax)]
#![feature(core_intrinsics)]
#![feature(custom_derive)]
#![feature(fnbox)]
#![feature(opti... | () {
unsafe { ::std::intrinsics::breakpoint() };
}
// Workaround for lack of `ptr_eq` on Arcs...
#[inline]
pub fn arc_ptr_eq<T:'static + Send + Sync>(a: &Arc<T>, b: &Arc<T>) -> bool {
let a: &T = &**a;
let b: &T = &**b;
(a as *const T) == (b as *const T)
}
| breakpoint | 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/. */
#![feature(box_syntax)]
#![feature(core_intrinsics)]
#![feature(custom_derive)]
#![feature(fnbox)]
#![feature(opti... | extern crate log;
extern crate num;
extern crate num_cpus;
extern crate rand;
extern crate rustc_serialize;
extern crate serde;
extern crate smallvec;
extern crate string_cache;
extern crate url;
use std::sync::Arc;
pub mod cache;
#[allow(unsafe_code)]
pub mod debug_utils;
pub mod geometry;
#[allow(unsafe_code)]
pub ... | extern crate libc;
#[macro_use] | random_line_split |
length.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use cssparser::{Parser, ParserInput};
use parsing::parse;
use style::context::QuirksMode;
use style::parser::{Pars... |
#[test]
fn test_zero_percentage_length_or_number() {
assert_eq!(parse(LengthOrPercentageOrNumber::parse, "0"), Ok(Either::First(Number::new(0.))));
}
| {
// In default length mode, non-zero lengths must have a unit.
assert!(parse(Length::parse, "1").is_err());
// In SVG length mode, non-zero lengths are assumed to be px.
let url = ::servo_url::ServoUrl::parse("http://localhost").unwrap();
let context = ParserContext::new(Origin::Author, &url,
... | identifier_body |
length.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use cssparser::{Parser, ParserInput};
use parsing::parse;
use style::context::QuirksMode; | use style::values::specified::length::{AbsoluteLength, Length, NoCalcLength};
use style_traits::{ParsingMode, ToCss};
#[test]
fn test_calc() {
assert!(parse(Length::parse, "calc(1px+ 2px)").is_err());
assert!(parse(Length::parse, "calc(calc(1px) + calc(1px + 4px))").is_ok());
assert!(parse(Length::parse, "... | use style::parser::{Parse, ParserContext};
use style::stylesheets::{CssRuleType, Origin};
use style::values::Either;
use style::values::specified::{LengthOrPercentageOrNumber, Number}; | random_line_split |
length.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use cssparser::{Parser, ParserInput};
use parsing::parse;
use style::context::QuirksMode;
use style::parser::{Pars... | () {
assert_eq!(parse(LengthOrPercentageOrNumber::parse, "0"), Ok(Either::First(Number::new(0.))));
}
| test_zero_percentage_length_or_number | identifier_name |
regions-variance-invariant-use-covariant.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 http://opensource.org/licenses/MIT>, at your
// option. This file... | random_line_split | |
regions-variance-invariant-use-covariant.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | () { }
| main | identifier_name |
input.rs | use std::thread;
use std::sync::{Arc, Mutex};
use rustbox;
use rustbox::{RustBox, Key, Mouse, EventResult};
use rustbox::Event::{KeyEvent, MouseEvent, ResizeEvent};
/**
* Spawns a thread which loops, polling for keyboard and mouse input using rustbox.
* (Rustbox is only used for this purpose, not for any terminal o... | Key::Right => Command::PositionVelocity(1.0, 0.0),
Key::Up => Command::PositionVelocity(0.0, -1.0),
Key::Down => Command::PositionVelocity(0.0, 1.0),
Key::Char('a') | Key::Char('=') => Command::Zoom(-1.0),
... | match key {
Key::Char('f') | Key::Char('F') => Command::ChangeFractalSet,
Key::Left => Command::PositionVelocity(-1.0, 0.0), | random_line_split |
input.rs | use std::thread;
use std::sync::{Arc, Mutex};
use rustbox;
use rustbox::{RustBox, Key, Mouse, EventResult};
use rustbox::Event::{KeyEvent, MouseEvent, ResizeEvent};
/**
* Spawns a thread which loops, polling for keyboard and mouse input using rustbox.
* (Rustbox is only used for this purpose, not for any terminal o... | {
ChangeFractalSet,
PositionVelocity(f64,f64),
PositionTween(i32, i32),
Zoom(f64),
ZoomContinuous(f64),
RotationalVelocity(f64),
Size(usize, usize),
Coord(usize),
AutoExposure, Help, Stop, Reset, Quit,
None,
// TODO: use 'Option' pattern instead of 'none'?
}
impl Command {... | Command | identifier_name |
input.rs | use std::thread;
use std::sync::{Arc, Mutex};
use rustbox;
use rustbox::{RustBox, Key, Mouse, EventResult};
use rustbox::Event::{KeyEvent, MouseEvent, ResizeEvent};
/**
* Spawns a thread which loops, polling for keyboard and mouse input using rustbox.
* (Rustbox is only used for this purpose, not for any terminal o... |
Key::Char('[') | Key::Char('{') => Command::RotationalVelocity(1.0),
Key::Char(']') | Key::Char('}') => Command::RotationalVelocity(-1.0),
Key::Char('/') | Key::Char('?') | Key::Char('h') | Key::Char('H') => Command::Help,
... | {
let event = event_result.unwrap();
match event {
KeyEvent(key) => {
match key {
Key::Char('f') | Key::Char('F') => Command::ChangeFractalSet,
Key::Left => Command::PositionVelocity(-1.0, 0.0... | identifier_body |
borrowck-loan-blocks-move-cc.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 ... | <F>(v: &isize, f: F) where F: FnOnce(&isize) {
f(v);
}
fn box_imm() {
let v = box 3is;
let _w = &v;
Thread::spawn(move|| {
println!("v={}", *v);
//~^ ERROR cannot move `v` into closure
});
}
fn box_imm_explicit() {
let v = box 3is;
let _w = &v;
Thread::spawn(move|| {
... | borrow | identifier_name |
borrowck-loan-blocks-move-cc.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 main() {
}
| {
let v = box 3is;
let _w = &v;
Thread::spawn(move|| {
println!("v={}", *v);
//~^ ERROR cannot move
});
} | identifier_body |
borrowck-loan-blocks-move-cc.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 main() {
} | let v = box 3is;
let _w = &v;
Thread::spawn(move|| {
println!("v={}", *v);
//~^ ERROR cannot move | random_line_split |
level.rs | use crate::time::driver::TimerHandle;
use crate::time::driver::{EntryList, TimerShared};
use std::{fmt, ptr::NonNull};
/// Wheel for a single level in the timer. This wheel contains 64 slots.
pub(crate) struct Level {
level: usize,
/// Bit field tracking which slots currently contain entries.
///
//... |
fn slot_range(level: usize) -> u64 {
LEVEL_MULT.pow(level as u32) as u64
}
fn level_range(level: usize) -> u64 {
LEVEL_MULT as u64 * slot_range(level)
}
/// Converts a duration (milliseconds) and a level to a slot position.
fn slot_for(duration: u64, level: usize) -> usize {
((duration >> (level * 6)) %... | {
1 << slot
} | identifier_body |
level.rs | use crate::time::driver::TimerHandle;
use crate::time::driver::{EntryList, TimerShared};
use std::{fmt, ptr::NonNull};
/// Wheel for a single level in the timer. This wheel contains 64 slots.
pub(crate) struct Level {
level: usize,
/// Bit field tracking which slots currently contain entries.
///
//... | (level: usize) -> Level {
// A value has to be Copy in order to use syntax like:
// let stack = Stack::default();
// ...
// slots: [stack; 64],
//
// Alternatively, since Stack is Default one can
// use syntax like:
// let slots: [Stack; 64]... | new | identifier_name |
level.rs | use crate::time::driver::TimerHandle;
use crate::time::driver::{EntryList, TimerShared};
use std::{fmt, ptr::NonNull};
/// Wheel for a single level in the timer. This wheel contains 64 slots.
pub(crate) struct Level {
level: usize,
/// Bit field tracking which slots currently contain entries.
///
//... | }
}
}
} | let a = pos * 64_usize.pow(level as u32);
assert_eq!(pos as usize, slot_for(a as u64, level)); | random_line_split |
fmt.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 ... |
impl<T> Poly for T {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match (f.width, f.precision) {
(None, None) => {
match repr::write_repr(f, self) {
Ok(()) => Ok(()),
Err(..) => Err(fmt::WriteError),
}
... | {
// FIXME #11938 - UFCS would make us able call the this method
// directly Poly::fmt(x, fmt).
x.fmt(fmt)
} | identifier_body |
fmt.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | <T: Poly>(x: &T, fmt: &mut fmt::Formatter) -> fmt::Result {
// FIXME #11938 - UFCS would make us able call the this method
// directly Poly::fmt(x, fmt).
x.fmt(fmt)
}
impl<T> Poly for T {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match (f.width, f.precision) {
... | secret_poly | identifier_name |
fmt.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 ... |
use std::fmt;
use repr;
/// Format trait for the `?` character
pub trait Poly {
/// Formats the value using the given formatter.
#[experimental]
fn fmt(&self, &mut fmt::Formatter) -> fmt::Result;
}
#[doc(hidden)]
pub fn secret_poly<T: Poly>(x: &T, fmt: &mut fmt::Formatter) -> fmt::Result {
// FIXME ... | //!
//! This module contains the `Poly` trait which is used to implement the `{:?}`
//! format expression in formatting macros. This trait is defined for all types
//! automatically, so it is likely not necessary to use this module manually | random_line_split |
inner_perfect_unshuffle.rs | use word::{Word, ReverseBitGroups, OuterPerfectUnshuffle};
/// Inner Perfect Unshuffle of `x`.
///
/// See also:
/// [Hacker's Delight: shuffling bits](http://icodeguru.com/Embedded/Hacker's-Delight/047.htm).
///
/// # Examples
///
/// ```
/// use bitwise::word::*;
///
/// let n = 0b1011_1110_1001_0011_0111_1001_0100_... |
}
| {
inner_perfect_unshuffle(self)
} | identifier_body |
inner_perfect_unshuffle.rs | use word::{Word, ReverseBitGroups, OuterPerfectUnshuffle};
/// Inner Perfect Unshuffle of `x`.
///
/// See also:
/// [Hacker's Delight: shuffling bits](http://icodeguru.com/Embedded/Hacker's-Delight/047.htm).
///
/// # Examples
///
/// ```
/// use bitwise::word::*;
///
/// let n = 0b1011_1110_1001_0011_0111_1001_0100_... | let hwb = T::bit_size().to_u8() / 2u8;
x.outer_perfect_unshuffle().reverse_bit_groups(hwb, 1u8)
}
/// Method version of [`inner_perfect_unshuffle`](fn.inner_perfect_unshuffle.html).
pub trait InnerPerfectUnshuffle {
#[inline]
fn inner_perfect_unshuffle(self) -> Self;
}
impl<T: Word> InnerPerfectUnshuf... | #[inline]
pub fn inner_perfect_unshuffle<T: Word>(x: T) -> T { | random_line_split |
inner_perfect_unshuffle.rs | use word::{Word, ReverseBitGroups, OuterPerfectUnshuffle};
/// Inner Perfect Unshuffle of `x`.
///
/// See also:
/// [Hacker's Delight: shuffling bits](http://icodeguru.com/Embedded/Hacker's-Delight/047.htm).
///
/// # Examples
///
/// ```
/// use bitwise::word::*;
///
/// let n = 0b1011_1110_1001_0011_0111_1001_0100_... | (self) -> Self {
inner_perfect_unshuffle(self)
}
}
| inner_perfect_unshuffle | identifier_name |
lib.rs | //! Double is a fully-featured mocking library for mocking `trait`
//! implementations.
//!
//! The `Mock` struct tracks function call arguments and specifies return
//! values or function overrides.
//!
//! # Examples
//!
//! ```
//! #[macro_use]
//! extern crate double;
//!
//! // Code under test
//! trait BalanceShe... | //! balance_sheet.profit(revenue, costs) * 2
//! }
//!
//! // Test which uses a mock BalanceSheet
//! mock_trait!(
//! MockBalanceSheet,
//! profit(u32, u32) -> i32);
//! impl BalanceSheet for MockBalanceSheet {
//! mock_method!(profit(&self, revenue: u32, costs: u32) -> i32);
//! }
//!
//! fn test_doub... | //! fn profit(&self, revenue: u32, costs: u32) -> i32;
//! }
//!
//! fn double_profit(revenue: u32, costs: u32, balance_sheet: &BalanceSheet) -> i32 { | random_line_split |
issue-24086.rs | // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | () {
let mut registry_listener = Listener {
announce: None,
remove: None,
};
}
| main | identifier_name |
issue-24086.rs | // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | remove: None,
};
} | let mut registry_listener = Listener {
announce: None, | random_line_split |
tutorial4.rs | use std::process::exit;
use std::sync::mpsc;
use std::thread::sleep;
use std::time::Duration;
extern crate unbound;
mod util;
fn | () {
let ctx = unbound::Context::new().unwrap();
let mut i = 0;
let (tx, rx) = mpsc::channel();
let mycallback =
move |_: unbound::AsyncID, result: unbound::Result<unbound::Answer>| match result {
Err(err) => println!("resolve error: {}", err),
Ok(ans) => {
... | main | identifier_name |
tutorial4.rs | use std::process::exit;
use std::sync::mpsc;
use std::thread::sleep;
use std::time::Duration;
extern crate unbound;
mod util;
fn main() | }
Ok(_id) => (),
}
while rx.try_recv() == Err(mpsc::TryRecvError::Empty) {
sleep(Duration::new(1, 0) / 10);
i += 1;
println!("time passed ({})..", i);
if let Err(err) = ctx.process() {
println!("resolve error: {}", err);
exit(1)
}
... | {
let ctx = unbound::Context::new().unwrap();
let mut i = 0;
let (tx, rx) = mpsc::channel();
let mycallback =
move |_: unbound::AsyncID, result: unbound::Result<unbound::Answer>| match result {
Err(err) => println!("resolve error: {}", err),
Ok(ans) => {
... | identifier_body |
tutorial4.rs | use std::process::exit;
use std::sync::mpsc;
use std::thread::sleep;
use std::time::Duration;
extern crate unbound;
mod util;
fn main() {
let ctx = unbound::Context::new().unwrap();
let mut i = 0;
let (tx, rx) = mpsc::channel();
let mycallback =
move |_: unbound::AsyncID, result: unbound::Re... | tx.send(true).unwrap();
}
};
match ctx.resolve_async("www.nlnetlabs.nl", 1, 1, mycallback) {
Err(err) => {
println!("resolve error: {}", err);
exit(1)
}
Ok(_id) => (),
}
while rx.try_recv() == Err(mpsc::TryRecvError::Empty... | random_line_split | |
tutorial4.rs | use std::process::exit;
use std::sync::mpsc;
use std::thread::sleep;
use std::time::Duration;
extern crate unbound;
mod util;
fn main() {
let ctx = unbound::Context::new().unwrap();
let mut i = 0;
let (tx, rx) = mpsc::channel();
let mycallback =
move |_: unbound::AsyncID, result: unbound::Re... |
};
match ctx.resolve_async("www.nlnetlabs.nl", 1, 1, mycallback) {
Err(err) => {
println!("resolve error: {}", err);
exit(1)
}
Ok(_id) => (),
}
while rx.try_recv() == Err(mpsc::TryRecvError::Empty) {
sleep(Duration::new(1, 0) / 10);
... | {
for ip in ans.data().map(util::data_to_ipv4) {
println!("The address of {} is {}", ans.qname(), ip);
}
tx.send(true).unwrap();
} | conditional_block |
mod.rs | //! Provides common neural network layers.
//!
//! For now the layers in common should be discribed as layers that are typical
//! layers for building neural networks but are not activation or loss layers.
#[macro_export]
macro_rules! impl_ilayer_common {
() => (
fn exact_num_output_blobs(&self) -> Option<u... | /// and the number of spatial dimensions.
///
/// The spatial dimensions only make up part of the whole filter shape. The other parts are the
/// number of input and output feature maps.
fn spatial_filter_dims(&self, num_spatial_dims: usize) -> Vec<usize> {
let mut spatial_dims = Vec::with_c... | fn num_spatial_dims(&self, input_shape: &[usize]) -> usize;
/// Retrievs the spatial dimensions for the filter based on `self.filter_shape()` | random_line_split |
mod.rs | //! Provides common neural network layers.
//!
//! For now the layers in common should be discribed as layers that are typical
//! layers for building neural networks but are not activation or loss layers.
#[macro_export]
macro_rules! impl_ilayer_common {
() => (
fn exact_num_output_blobs(&self) -> Option<u... |
/// Retrievs the padding for the convolution based on `self.padding`
/// and the number of spatial dimensions.
fn padding_dims(&self, num_spatial_dims: usize) -> Vec<usize> {
let mut padding_dims = Vec::with_capacity(num_spatial_dims);
let padding = self.padding();
if padding.len()... | {
let mut stride_dims = Vec::with_capacity(num_spatial_dims);
let stride = self.stride();
if stride.len() == 1 {
for i in 0..num_spatial_dims {
stride_dims.push(stride[0]);
}
} else if stride.len() == num_spatial_dims {
panic!("unimplem... | identifier_body |
mod.rs | //! Provides common neural network layers.
//!
//! For now the layers in common should be discribed as layers that are typical
//! layers for building neural networks but are not activation or loss layers.
#[macro_export]
macro_rules! impl_ilayer_common {
() => (
fn exact_num_output_blobs(&self) -> Option<u... | (&self, num_spatial_dims: usize) -> Vec<usize> {
let mut padding_dims = Vec::with_capacity(num_spatial_dims);
let padding = self.padding();
if padding.len() == 1 {
for i in 0..num_spatial_dims {
padding_dims.push(padding[0]);
}
} else if padding.le... | padding_dims | identifier_name |
plugin.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::PluginBinding::PluginMethods;
use dom::bindings::js::Root;
use dom::bindings... | fn NamedGetter(&self, _name: DOMString, _found: &mut bool) -> Option<Root<MimeType>> {
unreachable!()
}
// https://heycam.github.io/webidl/#dfn-supported-property-names
fn SupportedPropertyNames(&self) -> Vec<DOMString> {
unreachable!()
}
} |
// check-tidy: no specs after this line | random_line_split |
plugin.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::PluginBinding::PluginMethods;
use dom::bindings::js::Root;
use dom::bindings... |
// https://html.spec.whatwg.org/multipage/#dom-plugin-item
fn Item(&self, _index: u32) -> Option<Root<MimeType>> {
unreachable!()
}
// https://html.spec.whatwg.org/multipage/#dom-plugin-nameditem
fn NamedItem(&self, _name: DOMString) -> Option<Root<MimeType>> {
unreachable!()
... | {
unreachable!()
} | identifier_body |
plugin.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::PluginBinding::PluginMethods;
use dom::bindings::js::Root;
use dom::bindings... | (&self, _name: DOMString, _found: &mut bool) -> Option<Root<MimeType>> {
unreachable!()
}
// https://heycam.github.io/webidl/#dfn-supported-property-names
fn SupportedPropertyNames(&self) -> Vec<DOMString> {
unreachable!()
}
}
| NamedGetter | identifier_name |
list-tables.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_dynamodb::{Client, Error, Region, PKG_VERSION};
use structopt::StructOpt;
use tokio_stream::StreamExt;
#[derive(Debug, StructOpt)]
struct ... | /// * `[-r REGION]` - The region in which the client is created.
/// If not supplied, uses the value of the **AWS_REGION** environment variable.
/// If the environment variable is not set, defaults to **us-west-2**.
/// * `[-v]` - Whether to display additional information.
#[tokio::main]
async fn main() -> Result... | /// | random_line_split |
list-tables.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_dynamodb::{Client, Error, Region, PKG_VERSION};
use structopt::StructOpt;
use tokio_stream::StreamExt;
#[derive(Debug, StructOpt)]
struct ... | () -> Result<(), Error> {
tracing_subscriber::fmt::init();
let Opt { region, 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 verbose {
printl... | main | identifier_name |
list-tables.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_dynamodb::{Client, Error, Region, PKG_VERSION};
use structopt::StructOpt;
use tokio_stream::StreamExt;
#[derive(Debug, StructOpt)]
struct ... |
let shared_config = aws_config::from_env().region(region_provider).load().await;
let client = Client::new(&shared_config);
list_tables(&client).await
}
| {
println!("DynamoDB client version: {}", PKG_VERSION);
println!(
"Region: {}",
region_provider.region().await.unwrap().as_ref()
);
println!();
} | conditional_block |
which.rs | use getopts::{getopts,optflag};
use std;
use std::path::Path;
use common;
pub fn main(args: &[~str]) {
let opts = ~[
optflag("a", "", "List all instances of executables found (instead of just the first one of each)."),
optflag("s", "", "No output."),
];
let usage = "which [-as] program...";... |
_ => {}
}
return false;
}
| {
if filestat.kind == std::io::TypeFile && filestat.perm & 0111 != 0 {
return true;
}
} | conditional_block |
which.rs | use getopts::{getopts,optflag};
use std;
use std::path::Path;
use common;
pub fn main(args: &[~str]) {
let opts = ~[
optflag("a", "", "List all instances of executables found (instead of just the first one of each)."),
optflag("s", "", "No output."),
];
let usage = "which [-as] program...";... | (p: &Path) -> bool {
if! p.exists() { return false; }
match p.stat() {
Ok(filestat) => {
if filestat.kind == std::io::TypeFile && filestat.perm & 0111!= 0 {
return true;
}
}
_ => {}
}
return false;
}
| check_path | identifier_name |
which.rs | use getopts::{getopts,optflag};
use std;
use std::path::Path;
use common;
pub fn main(args: &[~str]) | Some(s) => s,
None => {
std::os::set_exit_status(1);
return;
}
};
let paths: ~[Path] = pathenv.split(':').map(|x| { Path::new(x) }).collect();
let mut stdout = std::io::stdout();
match matches.free.as_slice() {
[] => {
common::print_u... | {
let opts = ~[
optflag("a", "", "List all instances of executables found (instead of just the first one of each)."),
optflag("s", "", "No output."),
];
let usage = "which [-as] program ...";
let matches = match getopts(args.tail(), opts) {
Err(f) => {
common::err_wri... | identifier_body |
which.rs | use getopts::{getopts,optflag};
use std;
use std::path::Path;
use common;
pub fn main(args: &[~str]) {
let opts = ~[
optflag("a", "", "List all instances of executables found (instead of just the first one of each)."),
optflag("s", "", "No output."),
];
let usage = "which [-as] program...";... | [] => {
common::print_usage(usage, opts);
std::os::set_exit_status(1);
return;
}
[..cmds] => {
for cmd in cmds.iter() {
let mut found = false;
for path in paths.iter() {
let mut p = path.clone();
... | let paths: ~[Path] = pathenv.split(':').map(|x| { Path::new(x) }).collect();
let mut stdout = std::io::stdout();
match matches.free.as_slice() { | random_line_split |
qmlengine.rs |
use qvariant::*;
use types::*;
use qurl::*;
extern "C" {
fn dos_qguiapplication_create();
fn dos_qguiapplication_exec();
fn dos_qguiapplication_quit();
fn dos_qguiapplication_delete();
fn dos_qqmlapplicationengine_create() -> DosQmlApplicationEngine;
fn dos_qqmlapplicationengine_load(vptr: Do... | () -> Self {
unsafe {
dos_qguiapplication_create();
QmlEngine {
ptr: dos_qqmlapplicationengine_create(),
stored: Vec::new(),
}
}
}
/// Loads a file as a qml file
pub fn load_file(&mut self, path: &str) {
let path_ra... | new | identifier_name |
qmlengine.rs | use qvariant::*;
use types::*;
use qurl::*;
extern "C" {
fn dos_qguiapplication_create();
fn dos_qguiapplication_exec();
fn dos_qguiapplication_quit();
fn dos_qguiapplication_delete();
fn dos_qqmlapplicationengine_create() -> DosQmlApplicationEngine;
fn dos_qqmlapplicationengine_load(vptr: Dos... |
/// Provides an entry point for building QML applications from Rust
pub struct QmlEngine {
ptr: DosQmlApplicationEngine,
stored: Vec<QVariant>,
}
impl QmlEngine {
/// Creates a QML context of a non-headless application
pub fn new() -> Self {
unsafe {
dos_qguiapplication_create();
... | value: DosQVariant);
} | random_line_split |
qmlengine.rs |
use qvariant::*;
use types::*;
use qurl::*;
extern "C" {
fn dos_qguiapplication_create();
fn dos_qguiapplication_exec();
fn dos_qguiapplication_quit();
fn dos_qguiapplication_delete();
fn dos_qqmlapplicationengine_create() -> DosQmlApplicationEngine;
fn dos_qqmlapplicationengine_load(vptr: Do... | ;
unsafe { dos_qqmlapplicationengine_load_url(self.ptr, construct_qurl(&path)) }
}
/// Loads qml from a specified url (`file://`, `qrc://`, `http://`)
pub fn load_url(&mut self, uri: &str) {
unsafe { dos_qqmlapplicationengine_load_url(self.ptr, construct_qurl(uri)) }
}
/// Adds a p... | {
format!("file://{}", path_raw.display())
} | conditional_block |
qmlengine.rs |
use qvariant::*;
use types::*;
use qurl::*;
extern "C" {
fn dos_qguiapplication_create();
fn dos_qguiapplication_exec();
fn dos_qguiapplication_quit();
fn dos_qguiapplication_delete();
fn dos_qqmlapplicationengine_create() -> DosQmlApplicationEngine;
fn dos_qqmlapplicationengine_load(vptr: Do... |
}
use utils::*;
impl Default for QmlEngine {
fn default() -> Self {
Self::new()
}
}
impl Drop for QmlEngine {
fn drop(&mut self) {
unsafe {
dos_qguiapplication_quit();
dos_qqmlapplicationengine_delete(self.ptr);
dos_qguiapplication_delete();
}
... | {
unsafe {
let context = dos_qqmlapplicationengine_context(self.ptr);
dos_qqmlcontext_setcontextproperty(context, stoptr(name), get_private_variant(value));
}
} | identifier_body |
store.rs | use std::path::PathBuf;
use std::env;
use std::ffi;
use std::fmt;
use std::convert;
use std::error;
use std::io;
use std::fs::File;
use std::fs;
use std::io::prelude::*;
use std::result;
use tree;
use gpgme;
use ::vcs;
macro_rules! println_stderr(
($($arg:tt)*) => { {
let r = writeln!(&mut ::std::io::std... |
/// Get a `PassTreePath` from the give parameter `pass`. Returns an
pub fn get<S>(&self, pass: S) -> Option<PassTreePath> where S: Into<String>
{
let pass = pass.into();
if pass.is_empty() {
return Some(PassTreePath::from(vec![]));
}
self.entries
.i... | {
let query = query.into();
self.entries
.into_iter()
.filter(|x| x.to_string().contains(&query) )
.collect()
} | identifier_body |
store.rs | use std::path::PathBuf;
use std::env;
use std::ffi;
use std::fmt;
use std::convert;
use std::error;
use std::io;
use std::fs::File;
use std::fs;
use std::io::prelude::*;
use std::result;
use tree;
use gpgme;
use ::vcs;
macro_rules! println_stderr(
($($arg:tt)*) => { {
let r = writeln!(&mut ::std::io::std... |
};
let mut ctx = gpgme::Context::from_protocol(
gpgme::Protocol::OpenPgp).unwrap();
let mut output = gpgme::Data::new().unwrap();
match ctx.decrypt(&mut input, &mut output) {
Ok(..) => (),
Err(x) => {
println_stderr!("Unable to decryp... | {
println_stderr!("Unable to load ({:?}): {}", p, x);
return None;
} | conditional_block |
store.rs | use std::path::PathBuf;
use std::env;
use std::ffi;
use std::fmt;
use std::convert;
use std::error;
use std::io;
use std::fs::File;
use std::fs;
use std::io::prelude::*;
use std::result;
use tree;
use gpgme;
use ::vcs;
macro_rules! println_stderr(
($($arg:tt)*) => { {
let r = writeln!(&mut ::std::io::std... | (&self) -> String {
self.passhome.to_str().unwrap_or("").to_string()
}
/// Find and returns a Vector of `PassEntry`s by its name.
pub fn find<S>(&self, query: S) -> Vec<PassTreePath>
where S: Into<String> {
let query = query.into();
self.entries
.into_iter()
... | get_location | identifier_name |
store.rs | use std::path::PathBuf;
use std::env;
use std::ffi;
use std::fmt;
use std::convert;
use std::error;
use std::io;
use std::fs::File;
use std::fs;
use std::io::prelude::*;
use std::result;
use tree;
use gpgme;
use ::vcs;
macro_rules! println_stderr(
($($arg:tt)*) => { {
let r = writeln!(&mut ::std::io::std... | impl PassEntry {
/// Constructs a new `PassEntry`.
///
/// # Examples
///
/// ```
/// use std::path::PathBuf;
/// use rasslib::store::PassEntry;
///
/// let entry_path = PathBuf::from("/home/bar/.store/foobar.gpg");
/// let store_path = PathBuf::from("/home/bar/.store");
///
... | #[derive(Debug, Clone, Default, PartialEq)]
pub struct PassEntry {
name: String,
}
| random_line_split |
htmlolistelement.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::HTMLOListElementBinding;
use dom::bindings::codegen::InheritTypes::HTMLOListElementDer... | }
pub fn Compact(&self) -> bool {
false
}
pub fn SetCompact(&self, _compact: bool) -> ErrorResult {
Ok(())
}
} | ~""
}
pub fn SetType(&mut self, _type: DOMString) -> ErrorResult {
Ok(()) | random_line_split |
htmlolistelement.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::HTMLOListElementBinding;
use dom::bindings::codegen::InheritTypes::HTMLOListElementDer... | (&mut self, _start: i32) -> ErrorResult {
Ok(())
}
pub fn Type(&self) -> DOMString {
~""
}
pub fn SetType(&mut self, _type: DOMString) -> ErrorResult {
Ok(())
}
pub fn Compact(&self) -> bool {
false
}
pub fn SetCompact(&self, _compact: bool) -> ErrorRe... | SetStart | identifier_name |
htmlolistelement.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::HTMLOListElementBinding;
use dom::bindings::codegen::InheritTypes::HTMLOListElementDer... |
pub fn SetReversed(&self, _reversed: bool) -> ErrorResult {
Ok(())
}
pub fn Start(&self) -> i32 {
0
}
pub fn SetStart(&mut self, _start: i32) -> ErrorResult {
Ok(())
}
pub fn Type(&self) -> DOMString {
~""
}
pub fn SetType(&mut self, _type: DOMSt... | {
false
} | identifier_body |
file_loader.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 about_loader;
use mime_classifier::MimeClassifier;
use mime_guess::guess_mime_type;
use msg::constellation_msg... |
fn pipeline_id(&self) -> Option<PipelineId> {
None
}
}
fn read_block(reader: &mut File) -> Result<ReadStatus, String> {
let mut buf = vec![0; READ_SIZE];
match reader.read(&mut buf) {
Ok(0) => Ok(ReadStatus::EOF),
Ok(n) => {
buf.truncate(n);
Ok(ReadStatu... | {
None
} | identifier_body |
file_loader.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 about_loader;
use mime_classifier::MimeClassifier;
use mime_guess::guess_mime_type;
use msg::constellation_msg... | (load_data: LoadData,
senders: LoadConsumer,
classifier: Arc<MimeClassifier>,
cancel_listener: CancellationListener) {
assert!(load_data.url.scheme() == "file");
spawn_named("file_loader".to_owned(), move || {
let file_path = match load_data.url.to_file_path(... | factory | identifier_name |
file_loader.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 about_loader;
use mime_classifier::MimeClassifier;
use mime_guess::guess_mime_type;
use msg::constellation_msg... | use url::Url;
use util::thread::spawn_named;
static READ_SIZE: usize = 8192;
enum ReadStatus {
Partial(Vec<u8>),
EOF,
}
enum LoadResult {
Cancelled,
Finished,
}
struct FileLoadOrigin;
impl LoadOrigin for FileLoadOrigin {
fn referrer_url(&self) -> Option<Url> {
None
}
fn referrer_... | use std::io::Read;
use std::path::Path;
use std::sync::Arc; | random_line_split |
file_loader.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 about_loader;
use mime_classifier::MimeClassifier;
use mime_guess::guess_mime_type;
use msg::constellation_msg... | ,
};
let mut file = File::open(&file_path);
let reader = match file {
Ok(ref mut reader) => reader,
Err(_) => {
// this should be one of the three errors listed in
// http://doc.rust-lang.org/std/fs/struct.OpenOptions.html#method.open
... | {
send_error(load_data.url, NetworkError::Internal("Could not parse path".to_owned()), senders);
return;
} | conditional_block |
process.rs | // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MI... | (&mut self) {
self.env = Some(HashMap::new())
}
pub fn cwd(&mut self, dir: &OsStr) {
self.cwd = Some(dir.to_os_string())
}
}
////////////////////////////////////////////////////////////////////////////////
// Processes
////////////////////////////////////////////////////////////////////////... | env_clear | identifier_name |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.