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 |
|---|---|---|---|---|
mod.rs | // Copyright 2020 Pants project contributors (see CONTRIBUTORS.md).
// Licensed under the Apache License, Version 2.0 (see LICENSE).
// File-specific allowances to silence internal warnings of `py_class!`.
#![allow(
clippy::used_underscore_binding,
clippy::transmute_ptr_to_ptr,
clippy::zero_ptr
)]
pub mod engin... |
pub fn store_tuple(values: Vec<Value>) -> Value {
let gil = Python::acquire_gil();
let arg_handles: Vec<_> = values
.into_iter()
.map(|v| v.consume_into_py_object(gil.python()))
.collect();
Value::from(PyTuple::new(gil.python(), &arg_handles).into_object())
}
/// Store a slice containing 2-tuples of (... | {
INTERNS.key_get(key)
} | identifier_body |
main.rs | fn factorize(n:u64) -> Vec<u64> {
let mut factors:Vec<u64> = vec!();
let mut target = n;
//grab factors of two
while target % 2 == 0 {
factors.push(2);
target /= 2;
}
//grab odd prime factors
let mut factor = 3;
while factor * factor <= target && target > 1 {
if t... |
fn main() {
let largest_factor = get_largest_factor(600851475143);
println!("{}", largest_factor);
}
| {
let mut largest_factor = 0;
for factor in factorize(n) {
if factor > largest_factor {
largest_factor = factor;
}
}
return largest_factor;
} | identifier_body |
main.rs | fn factorize(n:u64) -> Vec<u64> {
let mut factors:Vec<u64> = vec!();
let mut target = n;
//grab factors of two
while target % 2 == 0 {
factors.push(2);
target /= 2;
}
//grab odd prime factors
let mut factor = 3;
while factor * factor <= target && target > 1 {
if t... | }
}
return largest_factor;
}
fn main() {
let largest_factor = get_largest_factor(600851475143);
println!("{}", largest_factor);
} | random_line_split | |
main.rs | fn factorize(n:u64) -> Vec<u64> {
let mut factors:Vec<u64> = vec!();
let mut target = n;
//grab factors of two
while target % 2 == 0 {
factors.push(2);
target /= 2;
}
//grab odd prime factors
let mut factor = 3;
while factor * factor <= target && target > 1 {
if t... |
}
return largest_factor;
}
fn main() {
let largest_factor = get_largest_factor(600851475143);
println!("{}", largest_factor);
}
| {
largest_factor = factor;
} | conditional_block |
main.rs | fn | (n:u64) -> Vec<u64> {
let mut factors:Vec<u64> = vec!();
let mut target = n;
//grab factors of two
while target % 2 == 0 {
factors.push(2);
target /= 2;
}
//grab odd prime factors
let mut factor = 3;
while factor * factor <= target && target > 1 {
if target % fact... | factorize | identifier_name |
pipe-select.rs | // xfail-fast
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <... | () {
use oneshot::client::*;
use stream::client::*;
let iotask = &uv::global_loop::get();
let c = pipes::spawn_service(stream::init, |p| {
error!("waiting for pipes");
let stream::send(x, p) = recv(p);
error!("got pipes");
let (left, right) : (oneshot::server::wait... | main | identifier_name |
pipe-select.rs | // xfail-fast
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <... | error!("got pipes");
let (left, right) : (oneshot::server::waiting,
oneshot::server::waiting)
= x;
error!("selecting");
let (i, m, _) = select(~[left, right]);
error!("selected %?", i);
if m.is_some() {
assert!(i == 1);... | {
use oneshot::client::*;
use stream::client::*;
let iotask = &uv::global_loop::get();
let c = pipes::spawn_service(stream::init, |p| {
error!("waiting for pipes");
let stream::send(x, p) = recv(p);
error!("got pipes");
let (left, right) : (oneshot::server::waiting... | identifier_body |
pipe-select.rs | // xfail-fast
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <... | Stream:send<T:Owned> {
send(T) -> Stream<T>
}
)
pub fn main() {
use oneshot::client::*;
use stream::client::*;
let iotask = &uv::global_loop::get();
let c = pipes::spawn_service(stream::init, |p| {
error!("waiting for pipes");
let stream::send(x, p) = recv(p);
... |
proto! stream ( | random_line_split |
pipe-select.rs | // xfail-fast
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <... |
}
stream::client::send(ac, 42);
}
| { } | conditional_block |
font.rs | ))]
/// The name of a font family of choice
pub struct FamilyName {
/// Name of the font family
pub name: Atom,
/// Syntax of the font family
pub syntax: FamilyNameSyntax,
}
impl ToCss for FamilyName {
fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result where W: fmt::Write {
match s... | let display = cx.builder.get_parent_font().clone__moz_math_display();
if display == DisplayValue::Inline {
parent + 1
} else {
parent | random_line_split | |
font.rs | Self {
if self.0 < 600 {
FontWeight(100)
} else if self.0 < 800 {
FontWeight(400)
} else {
FontWeight(700)
}
}
}
impl FontSize {
/// The actual computed font size.
pub fn size(self) -> Au {
self.size.into()
}
#[inline]
... | ted_zero(&self) | identifier_name | |
reader.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 ... | /// It will panic if it there is insufficient data to fulfill a request.
pub struct ReaderRng<R> {
reader: R
}
impl<R: Read> ReaderRng<R> {
/// Create a new `ReaderRng` from a `Read`.
pub fn new(r: R) -> ReaderRng<R> {
ReaderRng {
reader: r
}
}
}
impl<R: Read> Rng for Reade... | ///
/// # Panics
/// | random_line_split |
reader.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 ... |
}
| {
let mut rng = ReaderRng::new(&[][..]);
let mut v = [0; 3];
rng.fill_bytes(&mut v);
} | identifier_body |
reader.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 ... | (&mut self) -> u32 {
// This is designed for speed: reading a LE integer on a LE
// platform just involves blitting the bytes into the memory
// of the u32, similarly for BE on BE; avoiding byteswapping.
let mut bytes = [0; 4];
self.fill_bytes(&mut bytes);
unsafe { *(byte... | next_u32 | identifier_name |
define_error_type.rs | use std::num::ParseIntError;
use std::fmt;
type Result<T> = std::result::Result<T, DoubleError>;
#[derive(Debug)]
// 定义我们的错误类型。不管对我们的错误处理情况有多重要,这些都可能自定义。
// 现在我们能够按照底层工具的错误实现,写下我们的错误,或者两者之间的内容。
// (原文:Define our error types. These may be customized however is useful for our error
// handling cases. Now we will be abl... | } | print(double_first(strings)); | random_line_split |
define_error_type.rs | use std::num::ParseIntError;
use std::fmt;
type Result<T> = std::result::Result<T, DoubleError>;
#[derive(Debug)]
// 定义我们的错误类型。不管对我们的错误处理情况有多重要,这些都可能自定义。
// 现在我们能够按照底层工具的错误实现,写下我们的错误,或者两者之间的内容。
// (原文:Define our error types. These may be customized however is useful for our error
// handling cases. Now we will be abl... |
}
| identifier_body | |
define_error_type.rs | use std::num::ParseIntError;
use std::fmt;
type Result<T> = std::result::Result<T, DoubleError>;
#[derive(Debug)]
// 定义我们的错误类型。不管对我们的错误处理情况有多重要,这些都可能自定义。
// 现在我们能够按照底层工具的错误实现,写下我们的错误,或者两者之间的内容。
// (原文:Define our error types. These may be customized however is useful for our error
// handling cases. Now we will be abl... | print(double_first(strings));
}
| t(empty));
| identifier_name |
tree.rs | use crate::cli;
use crate::command_prelude::*;
use anyhow::{bail, format_err};
use cargo::core::dependency::DepKind;
use cargo::ops::tree::{self, EdgeKind};
use cargo::ops::Packages;
use cargo::util::print_available_packages;
use cargo::util::CargoResult;
use std::collections::HashSet;
use std::str::FromStr;
pub fn cl... | let prefix = tree::Prefix::from_str(prefix).map_err(|e| anyhow::anyhow!("{}", e))?;
let no_dedupe = args.is_present("no-dedupe") || args.is_present("all");
if args.is_present("all") {
config.shell().warn(
"The `cargo tree` --all flag has been changed to --no-dedupe, \
and m... | {
if args.is_present("version") {
let verbose = args.occurrences_of("verbose") > 0;
let version = cli::get_version_string(verbose);
cargo::drop_print!(config, "{}", version);
return Ok(());
}
let prefix = if args.is_present("no-indent") {
config
.shell()
... | identifier_body |
tree.rs | use crate::cli;
use crate::command_prelude::*;
use anyhow::{bail, format_err};
use cargo::core::dependency::DepKind;
use cargo::ops::tree::{self, EdgeKind};
use cargo::ops::Packages;
use cargo::util::print_available_packages;
use cargo::util::CargoResult;
use std::collections::HashSet;
use std::str::FromStr;
pub fn cl... | config
.shell()
.warn("the --no-dev-dependencies flag has changed to -e=no-dev")?;
kinds.push("no-dev");
}
if kinds.is_empty() {
kinds.extend(&["normal", "build", "dev"]);
}
let mut result = HashSet::new();
let insert_defaults = |result: &mut HashSet<Ed... | if args.is_present("no-dev-dependencies") { | random_line_split |
tree.rs | use crate::cli;
use crate::command_prelude::*;
use anyhow::{bail, format_err};
use cargo::core::dependency::DepKind;
use cargo::ops::tree::{self, EdgeKind};
use cargo::ops::Packages;
use cargo::util::print_available_packages;
use cargo::util::CargoResult;
use std::collections::HashSet;
use std::str::FromStr;
pub fn | () -> App {
subcommand("tree")
.about("Display a tree visualization of a dependency graph")
.arg(opt("quiet", "Suppress status messages").short("q"))
.arg_manifest_path()
.arg_package_spec_no_all(
"Package to be used as the root of the tree",
"Display the tree for... | cli | identifier_name |
redundant_semicolon.rs | use crate::{EarlyContext, EarlyLintPass, LintContext};
use rustc_ast::{Block, StmtKind};
use rustc_errors::Applicability;
use rustc_span::Span;
declare_lint! {
/// The `redundant_semicolons` lint detects unnecessary trailing
/// semicolons.
///
/// ### Example | ///
/// {{produces}}
///
/// ### Explanation
///
/// Extra semicolons are not needed, and may be removed to avoid confusion
/// and visual clutter.
pub REDUNDANT_SEMICOLONS,
Warn,
"detects unnecessary trailing semicolons"
}
declare_lint_pass!(RedundantSemicolons => [REDUNDANT_SE... | ///
/// ```rust
/// let _ = 123;;
/// ``` | random_line_split |
redundant_semicolon.rs | use crate::{EarlyContext, EarlyLintPass, LintContext};
use rustc_ast::{Block, StmtKind};
use rustc_errors::Applicability;
use rustc_span::Span;
declare_lint! {
/// The `redundant_semicolons` lint detects unnecessary trailing
/// semicolons.
///
/// ### Example
///
/// ```rust
/// let _ = 12... | {
if let Some((span, multiple)) = seq.take() {
// FIXME: Find a better way of ignoring the trailing
// semicolon from macro expansion
if span == rustc_span::DUMMY_SP {
return;
}
cx.struct_span_lint(REDUNDANT_SEMICOLONS, span, |lint| {
let (msg, rem) =... | identifier_body | |
redundant_semicolon.rs | use crate::{EarlyContext, EarlyLintPass, LintContext};
use rustc_ast::{Block, StmtKind};
use rustc_errors::Applicability;
use rustc_span::Span;
declare_lint! {
/// The `redundant_semicolons` lint detects unnecessary trailing
/// semicolons.
///
/// ### Example
///
/// ```rust
/// let _ = 12... | (cx: &EarlyContext<'_>, seq: &mut Option<(Span, bool)>) {
if let Some((span, multiple)) = seq.take() {
// FIXME: Find a better way of ignoring the trailing
// semicolon from macro expansion
if span == rustc_span::DUMMY_SP {
return;
}
cx.struct_span_lint(REDUNDANT... | maybe_lint_redundant_semis | identifier_name |
get_presence.rs | //! `GET /_matrix/client/*/presence/{userId}/status`
pub mod v3 {
//! `/v3/` ([spec])
//!
//! [spec]: https://spec.matrix.org/v1.2/client-server-api/#get_matrixclientv3presenceuseridstatus
use std::time::Duration;
use ruma_common::{api::ruma_api, presence::PresenceState, UserId};
ruma_api! {... |
}
}
| {
Self { presence, status_msg: None, currently_active: None, last_active_ago: None }
} | identifier_body |
get_presence.rs | //! `GET /_matrix/client/*/presence/{userId}/status`
pub mod v3 {
//! `/v3/` ([spec])
//!
//! [spec]: https://spec.matrix.org/v1.2/client-server-api/#get_matrixclientv3presenceuseridstatus
use std::time::Duration;
use ruma_common::{api::ruma_api, presence::PresenceState, UserId};
ruma_api! {... | (user_id: &'a UserId) -> Self {
Self { user_id }
}
}
impl Response {
/// Creates a new `Response` with the given presence state.
pub fn new(presence: PresenceState) -> Self {
Self { presence, status_msg: None, currently_active: None, last_active_ago: None }
... | new | identifier_name |
get_presence.rs | //! `GET /_matrix/client/*/presence/{userId}/status`
pub mod v3 {
//! `/v3/` ([spec])
//!
//! [spec]: https://spec.matrix.org/v1.2/client-server-api/#get_matrixclientv3presenceuseridstatus
use std::time::Duration;
use ruma_common::{api::ruma_api, presence::PresenceState, UserId};
ruma_api! {... | pub status_msg: Option<String>,
/// Whether or not the user is currently active.
#[serde(skip_serializing_if = "Option::is_none")]
pub currently_active: Option<bool>,
/// The length of time in milliseconds since an action was performed by the user.
... | response: {
/// The state message for this user if one was set.
#[serde(skip_serializing_if = "Option::is_none")] | random_line_split |
query19.rs | use timely::order::TotalOrder;
use timely::dataflow::*;
use timely::dataflow::operators::probe::Handle as ProbeHandle;
use differential_dataflow::operators::*;
use differential_dataflow::operators::arrange::ArrangeBySelf;
use differential_dataflow::lattice::Lattice;
use {Arrangements, Experiment, Collections};
// --... | <G: Scope<Timestamp=usize>>(
scope: &mut G,
probe: &mut ProbeHandle<usize>,
experiment: &mut Experiment,
arrangements: &mut Arrangements,
)
where
G::Timestamp: Lattice+TotalOrder+Ord
{
let arrangements = arrangements.in_scope(scope, experiment);
experiment
.lineitem(scope)
.ex... | query_arranged | identifier_name |
query19.rs | use timely::order::TotalOrder;
use timely::dataflow::*;
use timely::dataflow::operators::probe::Handle as ProbeHandle;
use differential_dataflow::operators::*;
use differential_dataflow::operators::arrange::ArrangeBySelf;
use differential_dataflow::lattice::Lattice;
use {Arrangements, Experiment, Collections};
// --... | .concat(&result3)
.count_total()
//.inspect(|x| println!("{:?}", x))
.probe_with(probe);
}
pub fn query_arranged<G: Scope<Timestamp=usize>>(
scope: &mut G,
probe: &mut ProbeHandle<usize>,
experiment: &mut Experiment,
arrangements: &mut Arrangements,
)
where
G::Timestamp... | .concat(&result2) | random_line_split |
query19.rs | use timely::order::TotalOrder;
use timely::dataflow::*;
use timely::dataflow::operators::probe::Handle as ProbeHandle;
use differential_dataflow::operators::*;
use differential_dataflow::operators::arrange::ArrangeBySelf;
use differential_dataflow::lattice::Lattice;
use {Arrangements, Experiment, Collections};
// --... | }
})
.count_total()
.probe_with(probe);
} | {
let arrangements = arrangements.in_scope(scope, experiment);
experiment
.lineitem(scope)
.explode(|x|
if (starts_with(&x.ship_mode, b"AIR") || starts_with(&x.ship_mode, b"AIR REG")) && starts_with(&x.ship_instruct, b"DELIVER IN PERSON") {
Some(((x.part_key, x.quant... | identifier_body |
query19.rs | use timely::order::TotalOrder;
use timely::dataflow::*;
use timely::dataflow::operators::probe::Handle as ProbeHandle;
use differential_dataflow::operators::*;
use differential_dataflow::operators::arrange::ArrangeBySelf;
use differential_dataflow::lattice::Lattice;
use {Arrangements, Experiment, Collections};
// --... |
else { None }
)
.join_core(&arrangements.part, |_pk,&qu,p| {
if qu >= 1 && qu <= 11 && (starts_with(&p.brand, b"Brand#12") && 1 <= p.size && p.size <= 5 && (starts_with(&p.container, b"SM CASE") || starts_with(&p.container, b"SM BOX") || starts_with(&p.container, b"SM PACK") ||... | {
Some(((x.part_key, x.quantity), (x.extended_price * (100 - x.discount) / 100) as isize))
} | conditional_block |
scr2.rs | #[doc = "Register `SCR2` reader"]
pub struct R(crate::R<SCR2_SPEC>);
impl core::ops::Deref for R {
type Target = crate::R<SCR2_SPEC>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl From<crate::R<SCR2_SPEC>> for R { | fn from(reader: crate::R<SCR2_SPEC>) -> Self {
R(reader)
}
}
#[doc = "Register `SCR2` writer"]
pub struct W(crate::W<SCR2_SPEC>);
impl core::ops::Deref for W {
type Target = crate::W<SCR2_SPEC>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl core::ops::Dere... | #[inline(always)] | random_line_split |
scr2.rs | #[doc = "Register `SCR2` reader"]
pub struct R(crate::R<SCR2_SPEC>);
impl core::ops::Deref for R {
type Target = crate::R<SCR2_SPEC>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl From<crate::R<SCR2_SPEC>> for R {
#[inline(always)]
fn from(reader: crate::R<SCR2_SP... | () -> Self::Ux {
0
}
}
| reset_value | identifier_name |
scr2.rs | #[doc = "Register `SCR2` reader"]
pub struct R(crate::R<SCR2_SPEC>);
impl core::ops::Deref for R {
type Target = crate::R<SCR2_SPEC>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl From<crate::R<SCR2_SPEC>> for R {
#[inline(always)]
fn from(reader: crate::R<SCR2_SP... |
}
| {
0
} | identifier_body |
ttreap.rs | /*
* Copyright (C) 2018, Nils Asmussen <nils@os.inf.tu-dresden.de>
* Economic rights: Technische Universitaet Dresden (Germany)
*
* This file is part of M3 (Microkernel-based SysteM for Heterogeneous Manycores).
*
* M3 is free software: you can redistribute it and/or modify
* it under the terms of the GNU Genera... |
fn test_rand_order() {
let vals = [1, 6, 2, 3, 8, 9, 7, 5, 4];
test_add_and_rem(&vals);
}
fn test_add_and_rem(vals: &[u32]) {
let mut treap = Treap::new();
// create
for v in vals {
treap.insert(v.clone(), v.clone());
}
// find all
for v in vals {
let val = treap.get... | {
let vals = (0..TEST_NODE_COUNT).rev().collect::<Vec<u32>>();
test_add_and_rem(&vals);
} | identifier_body |
ttreap.rs | /*
* Copyright (C) 2018, Nils Asmussen <nils@os.inf.tu-dresden.de>
* Economic rights: Technische Universitaet Dresden (Germany)
*
* This file is part of M3 (Microkernel-based SysteM for Heterogeneous Manycores).
*
* M3 is free software: you can redistribute it and/or modify
* it under the terms of the GNU Genera... | for v in vals {
let val = treap.remove(&v);
assert_eq!(val, Some(*v));
assert_eq!(treap.get(&v), None);
}
} | }
// remove | random_line_split |
ttreap.rs | /*
* Copyright (C) 2018, Nils Asmussen <nils@os.inf.tu-dresden.de>
* Economic rights: Technische Universitaet Dresden (Germany)
*
* This file is part of M3 (Microkernel-based SysteM for Heterogeneous Manycores).
*
* M3 is free software: you can redistribute it and/or modify
* it under the terms of the GNU Genera... | (t: &mut test::Tester) {
run_test!(t, test_in_order);
run_test!(t, test_rev_order);
run_test!(t, test_rand_order);
}
const TEST_NODE_COUNT: u32 = 10;
fn test_in_order() {
let vals = (0..TEST_NODE_COUNT).collect::<Vec<u32>>();
test_add_and_rem(&vals);
}
fn test_rev_order() {
let vals = (0..TES... | run | identifier_name |
mod.rs | //! The `dnm` can be used for easier switching between the DOM
//! (Document Object Model) representation and the plain text representation,
//! which is needed for most NLP tools.
mod c14n;
/// Node auxiliaries for DNMs
pub mod node;
mod parameters;
mod range;
use libxml::readonly::RoNode;
use libxml::tree::*;
use st... | (&mut self, node: RoNode) {
let offset_start = self.runtime.chars.len();
let mut string = node.get_content();
let mut offsets: Vec<i32> = if self.parameters.support_back_mapping {
(0i32..(string.chars().count() as i32)).collect()
} else {
Vec::new()
};
// string processing steps
... | text_node_create | identifier_name |
mod.rs | //! The `dnm` can be used for easier switching between the DOM
//! (Document Object Model) representation and the plain text representation,
//! which is needed for most NLP tools.
mod c14n;
/// Node auxiliaries for DNMs
pub mod node;
mod parameters;
mod range;
use libxml::readonly::RoNode;
use libxml::tree::*;
use st... |
Some(&SpecialTagsOption::Skip) => {
record_node_map!(self, node, offset_start);
return;
}
None => continue,
}
}
} // End scope of self.parameters borrow, to allow mutable self borrow for
// recurse_node_create Recurse into children
if le... | {
push_token!(self, &f(node), node);
record_node_map!(self, node, offset_start);
return;
} | conditional_block |
mod.rs | //! The `dnm` can be used for easier switching between the DOM
//! (Document Object Model) representation and the plain text representation,
//! which is needed for most NLP tools.
mod c14n;
/// Node auxiliaries for DNMs
pub mod node;
mod parameters;
mod range;
use libxml::readonly::RoNode;
use libxml::tree::*;
use st... | for rule in rules {
// iterate over applying rules
match rule {
Some(&SpecialTagsOption::Enter) => break,
Some(&SpecialTagsOption::Normalize(ref token)) => {
push_token!(self, token, node);
record_node_map!(self, node, offset_start);
return;
... | random_line_split | |
part1.rs | // adventofcode - day 2
// part 1
use std::io::prelude::*;
use std::fs::File;
use std::vec::Vec;
fn main(){
println!("Adventofcode - day 2 | part 1");
let content = import_data();
let mut paper = 0u32;
for line in content.lines(){
let dimensions: Vec<&str> = line.split('x').collect();
... | fn import_data() -> String {
let mut file = match File::open("../../inputs/02.txt") {
Ok(f) => f,
Err(e) => panic!("file error: {}", e),
};
let mut data = String::new();
match file.read_to_string(&mut data){
Ok(_) => {},
Err(e) => panic!("file error: {}", e),
};
da... | Err(_) => panic!("Failed to convert String to u32!"),
}
}
// This function simply imports the data set from a file called input.txt | random_line_split |
part1.rs | // adventofcode - day 2
// part 1
use std::io::prelude::*;
use std::fs::File;
use std::vec::Vec;
fn main(){
println!("Adventofcode - day 2 | part 1");
let content = import_data();
let mut paper = 0u32;
for line in content.lines(){
let dimensions: Vec<&str> = line.split('x').collect();
... | () -> String {
let mut file = match File::open("../../inputs/02.txt") {
Ok(f) => f,
Err(e) => panic!("file error: {}", e),
};
let mut data = String::new();
match file.read_to_string(&mut data){
Ok(_) => {},
Err(e) => panic!("file error: {}", e),
};
data
}
| import_data | identifier_name |
part1.rs | // adventofcode - day 2
// part 1
use std::io::prelude::*;
use std::fs::File;
use std::vec::Vec;
fn main() |
fn calc_paper(l: u32, w: u32, h: u32) -> u32 {
// the extra paper we need is calculated by multiplying the two smallest
// numbers with each other. Therefore, we look for the greatest number and
// simply multiply the others.
let extra = if l > w {
if l > h {
h * w
} else ... | {
println!("Adventofcode - day 2 | part 1");
let content = import_data();
let mut paper = 0u32;
for line in content.lines(){
let dimensions: Vec<&str> = line.split('x').collect();
let l = str_to_u32(dimensions[0]);
let w = str_to_u32(dimensions[1]);
let h = str_to_u32(... | identifier_body |
utility.rs |
// unfortunately, there is no such a trait in the standard library
// extern crates use `std`
pub trait UInt: Copy {
fn from64(x: u64) -> Self;
fn to64(self) -> u64;
}
macro_rules! implement {
($t: ty) => (
impl UInt for $t {
fn from64(x: u64) -> $t {
x as $t
... | <T: UInt>(x: T) -> usize {
let mut ret = log2_floor(x);
if x.to64() > (1 << ret) {
ret += 1
}
ret
}
pub fn dist<T>(begin: *const T, end: *const T) -> isize {
(end as isize) - (begin as isize)
}
pub fn round_up<T: UInt>(x: T, base: T) -> T {
let x = x.to64();
let base = base.to64();... | log2_ceil | identifier_name |
utility.rs |
// unfortunately, there is no such a trait in the standard library
// extern crates use `std`
pub trait UInt: Copy {
fn from64(x: u64) -> Self;
fn to64(self) -> u64;
}
macro_rules! implement {
($t: ty) => (
impl UInt for $t {
fn from64(x: u64) -> $t {
x as $t
... |
pub fn log2_ceil<T: UInt>(x: T) -> usize {
let mut ret = log2_floor(x);
if x.to64() > (1 << ret) {
ret += 1
}
ret
}
pub fn dist<T>(begin: *const T, end: *const T) -> isize {
(end as isize) - (begin as isize)
}
pub fn round_up<T: UInt>(x: T, base: T) -> T {
let x = x.to64();
let b... | {
64 - (x.to64().leading_zeros() as usize) - 1
} | identifier_body |
utility.rs | // unfortunately, there is no such a trait in the standard library
// extern crates use `std`
pub trait UInt: Copy {
fn from64(x: u64) -> Self;
fn to64(self) -> u64;
}
macro_rules! implement {
($t: ty) => (
impl UInt for $t {
fn from64(x: u64) -> $t {
x as $t
... | }
ret
}
pub fn dist<T>(begin: *const T, end: *const T) -> isize {
(end as isize) - (begin as isize)
}
pub fn round_up<T: UInt>(x: T, base: T) -> T {
let x = x.to64();
let base = base.to64();
let r = x % base;
T::from64(if r == 0 { x } else { x - r + base })
}
pub fn round_down<T:UInt>(x: ... |
pub fn log2_ceil<T: UInt>(x: T) -> usize {
let mut ret = log2_floor(x);
if x.to64() > (1 << ret) {
ret += 1 | random_line_split |
utility.rs |
// unfortunately, there is no such a trait in the standard library
// extern crates use `std`
pub trait UInt: Copy {
fn from64(x: u64) -> Self;
fn to64(self) -> u64;
}
macro_rules! implement {
($t: ty) => (
impl UInt for $t {
fn from64(x: u64) -> $t {
x as $t
... | else { x - r + base })
}
pub fn round_down<T:UInt>(x: T, base:T) -> T {
let base = base.to64();
T::from64((x.to64() / base) * base)
}
#[cfg(os_test)]
pub mod utility_tests {
use super::*;
tests_module!("utility",
log2_floor_test,
log2_ceil_test,
);
fn log2_floor_test() {
... | { x } | conditional_block |
n_queens.rs | // Implements http://rosettacode.org/wiki/N-queens_problem
#![feature(test)]
extern crate test;
use std::vec::Vec;
use std::thread::spawn;
use std::sync::mpsc::channel;
#[cfg(test)]
use test::Bencher;
#[cfg(not(test))]
fn main() {
for num in 0i32..16 {
println!("Sequential: {}: {}", num, n_queens(num));... |
#[test]
fn test_parallel_n_queens() {
let real = vec!(1, 1, 0, 0, 2, 10, 4, 40, 92);
for num in (0..9i32) {
assert_eq!(semi_parallel_n_queens(num), real[num as usize]);
}
}
#[bench]
fn bench_n_queens(b: &mut Bencher) {
b.iter(|| { test::black_box(n_queens(16)); });
}
#[bench]
fn bench_semi_p... | {
let real = vec!(1, 1, 0, 0, 2, 10, 4, 40, 92);
for num in (0..9i32) {
assert_eq!(n_queens(num), real[num as usize]);
}
} | identifier_body |
n_queens.rs | // Implements http://rosettacode.org/wiki/N-queens_problem
#![feature(test)]
extern crate test;
use std::vec::Vec;
use std::thread::spawn;
use std::sync::mpsc::channel;
#[cfg(test)]
use test::Bencher;
#[cfg(not(test))]
fn main() {
for num in 0i32..16 {
println!("Sequential: {}: {}", num, n_queens(num));... | // Make a recursive call. This is where we infer the conflicts
// for the next row.
solutions += n_queens_helper(
all_ones,
// We add a conflict in the current spot and then shift left,
// which has the desired effect of moving all of the conflicts
... | valid_spots = valid_spots ^ spot;
| random_line_split |
n_queens.rs | // Implements http://rosettacode.org/wiki/N-queens_problem
#![feature(test)]
extern crate test;
use std::vec::Vec;
use std::thread::spawn;
use std::sync::mpsc::channel;
#[cfg(test)]
use test::Bencher;
#[cfg(not(test))]
fn main() {
for num in 0i32..16 {
println!("Sequential: {}: {}", num, n_queens(num));... | () {
let real = vec!(1, 1, 0, 0, 2, 10, 4, 40, 92);
for num in (0..9i32) {
assert_eq!(semi_parallel_n_queens(num), real[num as usize]);
}
}
#[bench]
fn bench_n_queens(b: &mut Bencher) {
b.iter(|| { test::black_box(n_queens(16)); });
}
#[bench]
fn bench_semi_parallel_n_queens(b: &mut Bencher) {... | test_parallel_n_queens | identifier_name |
lib.rs | extern crate postgres;
use postgres::stmt::Statement;
use postgres::types::ToSql;
use postgres::rows::{Row, Rows};
use postgres::error::Error;
use std::marker::PhantomData;
use std::iter::Iterator;
pub trait FromRow {
fn from_row<'a>(row: &Row<'a>) -> Self;
}
pub struct RowIterator<'a, T>
where T: FromRow
{... |
}
}
pub fn queryx<'a, T>(stmt: &'a Statement, args: &[&ToSql]) -> Result<RowIterator<'a, T>, Error>
where T: FromRow
{
Ok(RowIterator {
rows: try!(stmt.query(args)),
_marker: PhantomData,
index: 0,
})
}
#[macro_export]
macro_rules! pgx_row {
(
$type_name: ident,
$( $field... | {
None
} | conditional_block |
lib.rs | extern crate postgres;
use postgres::stmt::Statement;
use postgres::types::ToSql;
use postgres::rows::{Row, Rows};
use postgres::error::Error;
use std::marker::PhantomData;
use std::iter::Iterator;
pub trait FromRow {
fn from_row<'a>(row: &Row<'a>) -> Self;
}
pub struct RowIterator<'a, T>
where T: FromRow
{... | (&mut self) -> Option<T> {
if self.index < self.rows.len() {
let row = self.rows.get(self.index);
let result = T::from_row(&row);
self.index += 1;
Some(result)
} else {
None
}
}
}
pub fn queryx<'a, T>(stmt: &'a Statement, args: &[&... | next | identifier_name |
lib.rs | extern crate postgres;
use postgres::stmt::Statement;
use postgres::types::ToSql;
use postgres::rows::{Row, Rows};
use postgres::error::Error;
use std::marker::PhantomData;
use std::iter::Iterator;
pub trait FromRow {
fn from_row<'a>(row: &Row<'a>) -> Self;
}
pub struct RowIterator<'a, T>
where T: FromRow
{... |
}
pub fn queryx<'a, T>(stmt: &'a Statement, args: &[&ToSql]) -> Result<RowIterator<'a, T>, Error>
where T: FromRow
{
Ok(RowIterator {
rows: try!(stmt.query(args)),
_marker: PhantomData,
index: 0,
})
}
#[macro_export]
macro_rules! pgx_row {
(
$type_name: ident,
$( $field: iden... | {
if self.index < self.rows.len() {
let row = self.rows.get(self.index);
let result = T::from_row(&row);
self.index += 1;
Some(result)
} else {
None
}
} | identifier_body |
lib.rs | extern crate postgres;
| use postgres::error::Error;
use std::marker::PhantomData;
use std::iter::Iterator;
pub trait FromRow {
fn from_row<'a>(row: &Row<'a>) -> Self;
}
pub struct RowIterator<'a, T>
where T: FromRow
{
_marker: PhantomData<T>,
rows: Rows<'a>,
index: usize,
}
impl<'a, T> Iterator for RowIterator<'a, T> ... | use postgres::stmt::Statement;
use postgres::types::ToSql;
use postgres::rows::{Row, Rows}; | random_line_split |
where-clauses-not-parameter.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 ... | {
equal(&0i, &0i);
} | identifier_body | |
where-clauses-not-parameter.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>(_: &T, _: &T) -> bool where isize : Eq {
true //~^ ERROR cannot bound type `isize`, where clause bounds may only be attached
}
// This should be fine involves a type parameter.
fn test<T: Eq>() -> bool where Option<T> : Eq {}
// This should be rejected as well.
fn test2() -> bool where Option<isize> : Eq {}
/... | equal | identifier_name |
generic-elements-pass.rs | // run-pass
// ignore-emscripten FIXME(#45351) hits an LLVM assert
#![feature(repr_simd, platform_intrinsics)]
#![feature(inline_const)]
#[repr(simd)]
#[derive(Copy, Clone, Debug, PartialEq)]
#[allow(non_camel_case_types)]
struct i32x2(i32, i32);
#[repr(simd)]
#[derive(Copy, Clone, Debug, PartialEq)] | struct i32x4(i32, i32, i32, i32);
#[repr(simd)]
#[derive(Copy, Clone, Debug, PartialEq)]
#[allow(non_camel_case_types)]
struct i32x8(i32, i32, i32, i32,
i32, i32, i32, i32);
extern "platform-intrinsic" {
fn simd_insert<T, E>(x: T, idx: u32, y: E) -> T;
fn simd_extract<T, E>(x: T, idx: u32) -> E;
... | #[allow(non_camel_case_types)] | random_line_split |
generic-elements-pass.rs | // run-pass
// ignore-emscripten FIXME(#45351) hits an LLVM assert
#![feature(repr_simd, platform_intrinsics)]
#![feature(inline_const)]
#[repr(simd)]
#[derive(Copy, Clone, Debug, PartialEq)]
#[allow(non_camel_case_types)]
struct i32x2(i32, i32);
#[repr(simd)]
#[derive(Copy, Clone, Debug, PartialEq)]
#[allow(non_came... | (i32, i32, i32, i32,
i32, i32, i32, i32);
extern "platform-intrinsic" {
fn simd_insert<T, E>(x: T, idx: u32, y: E) -> T;
fn simd_extract<T, E>(x: T, idx: u32) -> E;
fn simd_shuffle2<T, U>(x: T, y: T, idx: [u32; 2]) -> U;
fn simd_shuffle4<T, U>(x: T, y: T, idx: [u32; 4]) -> U;
fn simd_... | i32x8 | identifier_name |
htmlbaseelement.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::HTMLBaseElementBinding;
use dom::bindings::codegen::InheritTypes::HTMLBaseEl... | let element = HTMLBaseElement::new_inherited(localName, prefix, document);
Node::reflect_node(box element, document, HTMLBaseElementBinding::Wrap)
}
} | pub fn new(localName: DOMString, prefix: Option<DOMString>, document: JSRef<Document>) -> Temporary<HTMLBaseElement> { | random_line_split |
htmlbaseelement.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::HTMLBaseElementBinding;
use dom::bindings::codegen::InheritTypes::HTMLBaseEl... | (localName: DOMString, prefix: Option<DOMString>, document: JSRef<Document>) -> HTMLBaseElement {
HTMLBaseElement {
htmlelement: HTMLElement::new_inherited(HTMLElementTypeId::HTMLBaseElement, localName, prefix, document)
}
}
#[allow(unrooted_must_root)]
pub fn new(localName: DOM... | new_inherited | identifier_name |
htmlbaseelement.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::HTMLBaseElementBinding;
use dom::bindings::codegen::InheritTypes::HTMLBaseEl... |
#[allow(unrooted_must_root)]
pub fn new(localName: DOMString, prefix: Option<DOMString>, document: JSRef<Document>) -> Temporary<HTMLBaseElement> {
let element = HTMLBaseElement::new_inherited(localName, prefix, document);
Node::reflect_node(box element, document, HTMLBaseElementBinding::Wrap)... | {
HTMLBaseElement {
htmlelement: HTMLElement::new_inherited(HTMLElementTypeId::HTMLBaseElement, localName, prefix, document)
}
} | identifier_body |
stream_map.rs | use std::collections::hash_map::Entry;
use std::collections::hash_map::OccupiedEntry;
use std::collections::HashMap;
use super::stream::HttpStreamCommand;
use super::stream::HttpStreamCommon;
use super::stream::HttpStreamStateSnapshot;
use super::types::Types;
use crate::common::hash_set_shallow_clone::HashSetShallowC... |
}
pub fn pop_outg_maybe_remove(
mut self,
conn_out_window_size: &mut WindowSize,
) -> (Option<HttpStreamCommand>, Option<Self>) {
self.check_state();
let r = self.stream().pop_outg(conn_out_window_size);
self.sync_writable();
let stream = self.remove_if_c... | {
Some(self)
} | conditional_block |
stream_map.rs | use std::collections::hash_map::Entry;
use std::collections::hash_map::OccupiedEntry;
use std::collections::HashMap;
use super::stream::HttpStreamCommand;
use super::stream::HttpStreamCommon;
use super::stream::HttpStreamStateSnapshot;
use super::types::Types;
use crate::common::hash_set_shallow_clone::HashSetShallowC... | );
}
fn mark_writable(&mut self, writable: bool) {
let stream_id = self.id();
if writable {
self.writable_streams.insert(stream_id);
} else {
self.writable_streams.remove(&stream_id);
}
}
fn sync_writable(&mut self) {
let writable... | debug_assert_eq!(
self.stream_ref().is_writable(),
self.is_writable(),
"for stream {}",
self.id() | random_line_split |
stream_map.rs | use std::collections::hash_map::Entry;
use std::collections::hash_map::OccupiedEntry;
use std::collections::HashMap;
use super::stream::HttpStreamCommand;
use super::stream::HttpStreamCommon;
use super::stream::HttpStreamStateSnapshot;
use super::types::Types;
use crate::common::hash_set_shallow_clone::HashSetShallowC... |
pub fn writable_stream_ids(&mut self) -> HashSetShallowCloneItems<StreamId> {
self.writable_streams.items()
}
pub fn snapshot(&self) -> HashMap<StreamId, HttpStreamStateSnapshot> {
self.map.iter().map(|(&k, s)| (k, s.snapshot())).collect()
}
pub fn conn_died<F>(mut self, error: F... | {
self.map.keys().cloned().collect()
} | identifier_body |
stream_map.rs | use std::collections::hash_map::Entry;
use std::collections::hash_map::OccupiedEntry;
use std::collections::HashMap;
use super::stream::HttpStreamCommand;
use super::stream::HttpStreamCommon;
use super::stream::HttpStreamStateSnapshot;
use super::types::Types;
use crate::common::hash_set_shallow_clone::HashSetShallowC... | (&mut self) {
self.writable_streams = self
.map
.iter()
.filter_map(|(&stream_id, stream)| {
if stream.is_writable() {
Some(stream_id)
} else {
None
}
})
.collect()
... | sync_is_writable | identifier_name |
conversions.rs | use hashing;
impl<'a> From<&'a hashing::Digest> for crate::remote_execution::Digest {
fn from(d: &hashing::Digest) -> Self {
let mut digest = super::remote_execution::Digest::new();
digest.set_hash(d.0.to_hex());
digest.set_size_bytes(d.1 as i64);
digest
}
}
impl<'a> From<&'a hashing::Digest> for ... |
#[cfg(test)]
mod tests {
use hashing;
#[test]
fn from_our_digest() {
let our_digest = &hashing::Digest(
hashing::Fingerprint::from_hex_string(
"0123456789abcdeffedcba98765432100000000000000000ffffffffffffffff",
)
.unwrap(),
10,
);
let converted: super::super::remote_e... | {
let crate::google::rpc::Status {
code,
message,
details,
} = status;
let mut dst = crate::status::Status::new();
dst.set_code(code);
dst.set_message(message);
dst.set_details(
details
.into_iter()
.map(prost_any_to_gcprio_any)
.collect::<Vec<_>>()
.into(),
);
ds... | identifier_body |
conversions.rs | use hashing;
impl<'a> From<&'a hashing::Digest> for crate::remote_execution::Digest {
fn from(d: &hashing::Digest) -> Self {
let mut digest = super::remote_execution::Digest::new();
digest.set_hash(d.0.to_hex());
digest.set_size_bytes(d.1 as i64);
digest
}
}
impl<'a> From<&'a hashing::Digest> for ... | );
let converted: super::super::remote_execution::Digest = our_digest.into();
let mut want = super::super::remote_execution::Digest::new();
want.set_hash("0123456789abcdeffedcba98765432100000000000000000ffffffffffffffff".to_owned());
want.set_size_bytes(10);
assert_eq!(converted, want);
}
#... | random_line_split | |
conversions.rs | use hashing;
impl<'a> From<&'a hashing::Digest> for crate::remote_execution::Digest {
fn from(d: &hashing::Digest) -> Self {
let mut digest = super::remote_execution::Digest::new();
digest.set_hash(d.0.to_hex());
digest.set_size_bytes(d.1 as i64);
digest
}
}
impl<'a> From<&'a hashing::Digest> for ... | (d: &hashing::Digest) -> Self {
Self {
hash: d.0.to_hex(),
size_bytes: d.1 as i64,
}
}
}
impl<'a> From<&'a super::remote_execution::Digest> for Result<hashing::Digest, String> {
fn from(d: &super::remote_execution::Digest) -> Self {
hashing::Fingerprint::from_hex_string(d.get_hash())
.... | from | identifier_name |
mod.rs | use winapi::{HMODULE, HRESULT, UINT};
use dxgi;
pub use self::enums::*;
pub use self::interfaces::*;
pub use self::structs::*;
mod enums;
mod interfaces;
mod structs;
pub const SDK_VERSION: UINT = 7;
extern "stdcall" {
pub fn D3D11CreateDevice(
adapter: *const dxgi::IDXGIAdapter,
driver_type: D... | immediate_context: *mut *mut ID3D11DeviceContext) -> HRESULT;
} | random_line_split | |
common.rs | extern crate lazy_static;
use std::env;
use std::io::Result;
use std::path::PathBuf;
use std::fs::{self, DirEntry};
use std::string::String;
pub struct Config {
pub steps_file: String,
pub step_implementations_path: PathBuf,
pub skel_path: PathBuf,
pub internal_port: String,
}
lazy_static! {
pub ... |
pub fn copy_file<'a>(from: &'a PathBuf, to: &'a PathBuf) -> Result<(&'a PathBuf, &'a PathBuf)> {
try!(fs::copy(from, to));
Ok((from, to))
}
pub fn visit_dirs(dir: &PathBuf, callback: &Fn(&DirEntry)) -> Result<()> {
if try!(fs::metadata(dir)).is_dir() {
for entry in try!(fs::read_dir(dir)) {
... | {
try!(fs::create_dir_all(dirpath));
Ok(dirpath)
} | identifier_body |
common.rs | extern crate lazy_static;
use std::env;
use std::io::Result;
use std::path::PathBuf;
use std::fs::{self, DirEntry};
use std::string::String;
pub struct Config {
pub steps_file: String,
pub step_implementations_path: PathBuf, | pub internal_port: String,
}
lazy_static! {
pub static ref PROJECT_ROOT: PathBuf = PathBuf::from(env_var("GAUGE_PROJECT_ROOT"));
pub static ref PLUGIN_SOURCE: PathBuf = match env::current_dir() {
Ok(d) => d,
Err(_) => PathBuf::from("")
};
pub static ref CONFIG: Config = Config {
... | pub skel_path: PathBuf, | random_line_split |
common.rs | extern crate lazy_static;
use std::env;
use std::io::Result;
use std::path::PathBuf;
use std::fs::{self, DirEntry};
use std::string::String;
pub struct Config {
pub steps_file: String,
pub step_implementations_path: PathBuf,
pub skel_path: PathBuf,
pub internal_port: String,
}
lazy_static! {
pub ... | <'a>(from: &'a PathBuf, to: &'a PathBuf) -> Result<(&'a PathBuf, &'a PathBuf)> {
try!(fs::copy(from, to));
Ok((from, to))
}
pub fn visit_dirs(dir: &PathBuf, callback: &Fn(&DirEntry)) -> Result<()> {
if try!(fs::metadata(dir)).is_dir() {
for entry in try!(fs::read_dir(dir)) {
let entry =... | copy_file | identifier_name |
retry.rs | // Copyright (c) The Diem Core Contributors
// SPDX-License-Identifier: Apache-2.0
use crate::async_client::{defaults, Error};
use std::time::Duration;
pub trait RetryStrategy: std::fmt::Debug + Send + Sync {
fn max_retries(&self, err: &Error) -> u32;
fn delay(&self, err: &Error, retries: u32) -> Duration;
... | Error::NetworkError(err) => err.is_timeout() || err.is_request(),
_ => false,
}
}
} | }
fn is_retriable(&self, err: &Error) -> bool {
match err {
Error::StaleResponseError(_) => true, | random_line_split |
retry.rs | // Copyright (c) The Diem Core Contributors
// SPDX-License-Identifier: Apache-2.0
use crate::async_client::{defaults, Error};
use std::time::Duration;
pub trait RetryStrategy: std::fmt::Debug + Send + Sync {
fn max_retries(&self, err: &Error) -> u32;
fn delay(&self, err: &Error, retries: u32) -> Duration;
... | (&self, _: &Error, retries: u32) -> Duration {
self.delay * retries
}
fn is_retriable(&self, err: &Error) -> bool {
match err {
Error::StaleResponseError(_) => true,
Error::NetworkError(err) => err.is_timeout() || err.is_request(),
_ => false,
}
}... | delay | identifier_name |
retry.rs | // Copyright (c) The Diem Core Contributors
// SPDX-License-Identifier: Apache-2.0
use crate::async_client::{defaults, Error};
use std::time::Duration;
pub trait RetryStrategy: std::fmt::Debug + Send + Sync {
fn max_retries(&self, err: &Error) -> u32;
fn delay(&self, err: &Error, retries: u32) -> Duration;
... |
fn delay(&self, _: &Error, retries: u32) -> Duration {
self.delay * retries
}
fn is_retriable(&self, err: &Error) -> bool {
match err {
Error::StaleResponseError(_) => true,
Error::NetworkError(err) => err.is_timeout() || err.is_request(),
_ => false,
... | {
self.max_retries
} | identifier_body |
mod.rs | // Copyright 2012-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-MI... | (cx: &mut ExtCtxt,
_span: Span,
mitem: @MetaItem,
item: @Item,
push: |@Item|) {
match mitem.node {
MetaNameValue(_, ref l) => {
cx.span_err(l.span, "unexpected value in `deriving`");
... | expand_meta_deriving | identifier_name |
mod.rs | // Copyright 2012-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-MI... | library.
*/
use ast::{Item, MetaItem, MetaList, MetaNameValue, MetaWord};
use ext::base::ExtCtxt;
use codemap::Span;
pub mod bounds;
pub mod clone;
pub mod encodable;
pub mod decodable;
pub mod hash;
pub mod rand;
pub mod show;
pub mod zero;
pub mod default;
pub mod primitive;
#[path="cmp/eq.rs"]
pub mod eq;
#[path... | We also assume "extra" is the standard library, and "std" is the core | random_line_split |
mod.rs | // Copyright 2012-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-MI... |
MetaList(_, ref titems) if titems.len() == 0 => {
cx.span_warn(mitem.span, "empty trait list in `deriving`");
}
MetaList(_, ref titems) => {
for &titem in titems.iter().rev() {
match titem.node {
MetaNameValue(ref tname, _) |
... | {
cx.span_warn(mitem.span, "empty trait list in `deriving`");
} | conditional_block |
mod.rs | // Copyright 2012-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-MI... | match tname.get() {
"Clone" => expand!(clone::expand_deriving_clone),
"Hash" => expand!(hash::expand_deriving_hash),
"Encodable" => expand!(encodable::expand_deriving_encodable),
"De... | {
match mitem.node {
MetaNameValue(_, ref l) => {
cx.span_err(l.span, "unexpected value in `deriving`");
}
MetaWord(_) => {
cx.span_warn(mitem.span, "empty trait list in `deriving`");
}
MetaList(_, ref titems) if titems.len() == 0 => {
cx.s... | identifier_body |
reddit.rs | extern crate ansi_term;
extern crate failure;
extern crate rawr;
use ansi_term::Colour::Blue;
use ansi_term::Colour::Green;
use ansi_term::Colour::Purple;
use configuration::Configuration;
use LibResult;
use rawr::options::ListingOptions;
use rawr::structures::comment::Comment;
use rawr::structures::subreddit::Subr... |
/*
* Gets the link url of the reddit content.
* This is only defined for link posts
*/
pub fn link_url(&self) -> Option<String> {
match self {
&RedditContent::LinkPost(post, _) => Some(
post.link_url().expect("Failed to get link url of link post")),
... | {
match self {
&RedditContent::SelfPost(post, _) => Some(post.title().to_string()),
&RedditContent::LinkPost(post, _) => Some(post.title().to_string()),
_ => None,
}
} | identifier_body |
reddit.rs | extern crate ansi_term;
extern crate failure;
extern crate rawr;
use ansi_term::Colour::Blue;
use ansi_term::Colour::Green;
use ansi_term::Colour::Purple;
use configuration::Configuration;
use LibResult;
use rawr::options::ListingOptions;
use rawr::structures::comment::Comment;
use rawr::structures::subreddit::Subr... | (&self) -> &'a Content {
match self {
&RedditContent::PostComment(comment, _) => comment,
&RedditContent::SelfPost(post, _) => post,
&RedditContent::LinkPost(post, _) => post,
}
}
fn config(&self) -> &'b Configuration {
match self {
&Reddi... | info | identifier_name |
reddit.rs | extern crate ansi_term;
extern crate failure;
extern crate rawr;
use ansi_term::Colour::Blue;
use ansi_term::Colour::Green;
use ansi_term::Colour::Purple;
use configuration::Configuration;
use LibResult;
use rawr::options::ListingOptions;
use rawr::structures::comment::Comment;
use rawr::structures::subreddit::Subr... |
let hot = self.subreddit.hot(ListingOptions::default())?;
for post in hot.take(13) {
println!("Found '{}' in '{}'", post.title(), self.subreddit.name);
println!();
self.search_post(post, &behavior)?;
}
Ok(())
}
/*
* Scans the post, possi... | {
eprintln!("Could not fetch about data in {}", self.subreddit.name);
} | conditional_block |
reddit.rs | extern crate ansi_term;
extern crate failure;
extern crate rawr;
use ansi_term::Colour::Blue;
use ansi_term::Colour::Green;
use ansi_term::Colour::Purple;
use configuration::Configuration;
use LibResult;
use rawr::options::ListingOptions;
use rawr::structures::comment::Comment;
use rawr::structures::subreddit::Subr... | if!content.replied_to()? {
behavior(&content)?;
}
// take back the post
}
// give the post to `replies` which will consume it
let comments = post.replies()?.take(100);
for comment in comments {
self.scan_comment_tree(commen... | let title = String::from(post.title()).clone();
println!("Scanning '{}'", title);
{
let content = new_reddit_content_from_post(&post, self.config); | random_line_split |
useless_asref.rs | // run-rustfix
#![deny(clippy::useless_asref)]
use std::fmt::Debug;
struct FakeAsRef;
#[allow(clippy::should_implement_trait)]
impl FakeAsRef {
fn as_ref(&self) -> &Self {
self
}
}
struct MoreRef;
impl<'a, 'b, 'c> AsRef<&'a &'b &'c MoreRef> for MoreRef {
fn as_ref(&self) -> &&'a &'b &'c MoreRe... | () {
not_ok();
ok();
}
| main | identifier_name |
useless_asref.rs | // run-rustfix
#![deny(clippy::useless_asref)]
use std::fmt::Debug;
struct FakeAsRef;
#[allow(clippy::should_implement_trait)]
impl FakeAsRef {
fn as_ref(&self) -> &Self {
self
}
}
struct MoreRef;
impl<'a, 'b, 'c> AsRef<&'a &'b &'c MoreRef> for MoreRef {
fn as_ref(&self) -> &&'a &'b &'c MoreRe... | foo_mrslice(mrrrrrslice.as_mut());
foo_mrslice(mrrrrrslice);
foo_rslice(mrrrrrslice.as_ref());
foo_rslice(mrrrrrslice);
}
#[allow(unused_parens, clippy::double_parens)]
foo_rrrrmr((&&&&MoreRef).as_ref());
generic_not_ok(mrslice);
generic_ok(mrslice);
}
fn ok() {
... | let mrrrrrslice = &mut &mut &mut &mut mrslice; | random_line_split |
useless_asref.rs | // run-rustfix
#![deny(clippy::useless_asref)]
use std::fmt::Debug;
struct FakeAsRef;
#[allow(clippy::should_implement_trait)]
impl FakeAsRef {
fn as_ref(&self) -> &Self {
self
}
}
struct MoreRef;
impl<'a, 'b, 'c> AsRef<&'a &'b &'c MoreRef> for MoreRef {
fn as_ref(&self) -> &&'a &'b &'c MoreRe... |
}
fn foo_rstr(x: &str) {
println!("{:?}", x);
}
fn foo_rslice(x: &[i32]) {
println!("{:?}", x);
}
fn foo_mrslice(x: &mut [i32]) {
println!("{:?}", x);
}
fn foo_rrrrmr(_: &&&&MoreRef) {
println!("so many refs");
}
fn not_ok() {
let rstr: &str = "hello";
let mut mrslice: &mut [i32] = &mut [1, 2... | {
&&&&MoreRef
} | identifier_body |
command.rs | extern crate rsedis;
use std::str::from_utf8;
use rsedis::database::Database;
use rsedis::database::Value;
use rsedis::parser::Parser;
use rsedis::parser::Argument;
use rsedis::command::command;
use rsedis::command::Response;
fn getstr(database: &Database, key: &[u8]) -> String {
match database.get(&key.to_vec()... | () {
let response = Response::Status("OK".to_string());
assert_eq!(response.as_bytes(), b"+OK\r\n");
}
#[test]
fn serialize_error() {
let response = Response::Error("ERR Invalid command".to_string());
assert_eq!(response.as_bytes(), b"-ERR Invalid command\r\n");
}
#[test]
fn serialize_string() {
l... | serialize_status | identifier_name |
command.rs | extern crate rsedis;
use std::str::from_utf8;
use rsedis::database::Database;
use rsedis::database::Value;
use rsedis::parser::Parser;
use rsedis::parser::Argument;
use rsedis::command::command;
use rsedis::command::Response;
fn getstr(database: &Database, key: &[u8]) -> String |
#[test]
fn nocommand() {
let mut db = Database::new();
let parser = Parser::new(b"", 0, Vec::new());
let response = command(&parser, &mut db);
match response {
Response::Error(_) => {},
_ => assert!(false),
};
}
#[test]
fn set_command() {
let mut db = Database::new();
let ... | {
match database.get(&key.to_vec()) {
Some(val) => {
match val {
&Value::Data(ref bytes) => return from_utf8(bytes).unwrap().to_string(),
&Value::Integer(i) => return format!("{}", i),
&Value::Nil => panic!("Got nil"),
}
},
... | identifier_body |
command.rs | extern crate rsedis;
use std::str::from_utf8;
use rsedis::database::Database;
use rsedis::database::Value;
use rsedis::parser::Parser;
use rsedis::parser::Argument;
use rsedis::command::command;
use rsedis::command::Response;
fn getstr(database: &Database, key: &[u8]) -> String {
match database.get(&key.to_vec()... | match response {
Response::Data(msg) => assert_eq!(msg, b"value"),
_ => assert!(false),
};
assert_eq!("value", getstr(&db, b"key"));
}
#[test]
fn serialize_status() {
let response = Response::Status("OK".to_string());
assert_eq!(response.as_bytes(), b"+OK\r\n");
}
#[test]
fn serial... | Argument {pos: 3, len: 3},
));
let response = command(&parser, &mut db); | random_line_split |
utils.rs | //! Provides utility functionality for the CUDA cuDNN API.
use ::{API, Error};
use ffi::*;
use std::ptr;
impl API {
/// Initialize the CUDA cuDNN API with needed context and resources.
///
/// The returned `handle` must be provided to future CUDA cuDNN API calls.
/// Call this method outside of perfor... | (handle: cudnnHandle_t) -> Result<(), Error> {
unsafe { API::ffi_destroy(handle) }
}
/// Returns the version of the CUDA cuDNN API.
pub fn get_version() -> usize {
unsafe { API::ffi_get_version() }
}
unsafe fn ffi_get_version() -> ::libc::size_t {
cudnnGetVersion()
}
... | destroy | identifier_name |
utils.rs | //! Provides utility functionality for the CUDA cuDNN API.
use ::{API, Error};
use ffi::*;
use std::ptr;
impl API {
/// Initialize the CUDA cuDNN API with needed context and resources.
///
/// The returned `handle` must be provided to future CUDA cuDNN API calls.
/// Call this method outside of perfor... | }
/// Returns the version of the CUDA cuDNN API.
pub fn get_version() -> usize {
unsafe { API::ffi_get_version() }
}
unsafe fn ffi_get_version() -> ::libc::size_t {
cudnnGetVersion()
}
unsafe fn ffi_create() -> Result<cudnnHandle_t, Error> {
let mut handle: cudnnHa... | random_line_split | |
utils.rs | //! Provides utility functionality for the CUDA cuDNN API.
use ::{API, Error};
use ffi::*;
use std::ptr;
impl API {
/// Initialize the CUDA cuDNN API with needed context and resources.
///
/// The returned `handle` must be provided to future CUDA cuDNN API calls.
/// Call this method outside of perfor... |
unsafe fn ffi_get_version() -> ::libc::size_t {
cudnnGetVersion()
}
unsafe fn ffi_create() -> Result<cudnnHandle_t, Error> {
let mut handle: cudnnHandle_t = ptr::null_mut();
match cudnnCreate(&mut handle) {
cudnnStatus_t::CUDNN_STATUS_SUCCESS => Ok(handle),
... | {
unsafe { API::ffi_get_version() }
} | identifier_body |
sub.rs | use float::add::__adddf3; | use float::add::__addsf3;
use float::Float;
intrinsics! {
#[arm_aeabi_alias = __aeabi_fsub]
pub extern "C" fn __subsf3(a: f32, b: f32) -> f32 {
__addsf3(a, f32::from_repr(b.repr() ^ f32::SIGN_MASK))
}
#[arm_aeabi_alias = __aeabi_dsub]
pub extern "C" fn __subdf3(a: f64, b: f64) -> f64 {
... | random_line_split | |
integer-literal-radix.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 ... | assert_eq!(c, 21);
assert_eq!(d, -48879);
assert_eq!(e, -493);
assert_eq!(f, -21);
} | assert_eq!(b, 493); | random_line_split |
integer-literal-radix.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 a = 0xBEEF_isize;
let b = 0o755_isize;
let c = 0b10101_isize;
let d = -0xBEEF_isize;
let e = -0o755_isize;
let f = -0b10101_isize;
assert_eq!(a, 48879);
assert_eq!(b, 493);
assert_eq!(c, 21);
assert_eq!(d, -48879);
assert_eq!(e, -493);
assert_eq!(f, -21);
}
| main | identifier_name |
integer-literal-radix.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 a = 0xBEEF_isize;
let b = 0o755_isize;
let c = 0b10101_isize;
let d = -0xBEEF_isize;
let e = -0o755_isize;
let f = -0b10101_isize;
assert_eq!(a, 48879);
assert_eq!(b, 493);
assert_eq!(c, 21);
assert_eq!(d, -48879);
assert_eq!(e, -493);
assert_eq!(f, -21);
} | identifier_body | |
rule_list.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/. */
//! A list of CSS rules.
#[cfg(feature = "gecko")]
use malloc_size_of::{MallocShallowSizeOf, MallocSizeOfOps};
us... | (&self, guard: &SharedRwLockReadGuard, ops: &mut MallocSizeOfOps) -> usize {
let mut n = self.0.shallow_size_of(ops);
for rule in self.0.iter() {
n += rule.size_of(guard, ops);
}
n
}
/// Trivially construct a new set of CSS rules.
pub fn new(rules: Vec<CssRule>, ... | size_of | identifier_name |
rule_list.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 servo_arc::{Arc, RawOffsetArc};
use shared_lock::{DeepCloneParams, DeepCloneWithLock, Locked};
use shared_lock::{SharedRwLock, SharedRwLockReadGuard, ToCssWithGuard};
use std::fmt::{self, Write};
use str::CssStringWriter;
use stylesheets::loader::StylesheetLoader;
use stylesheets::rule_parser::{InsertRuleContext, S... |
//! A list of CSS rules.
#[cfg(feature = "gecko")]
use malloc_size_of::{MallocShallowSizeOf, MallocSizeOfOps}; | random_line_split |
rule_list.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/. */
//! A list of CSS rules.
#[cfg(feature = "gecko")]
use malloc_size_of::{MallocShallowSizeOf, MallocSizeOfOps};
us... |
}
/// A trait to implement helpers for `Arc<Locked<CssRules>>`.
pub trait CssRulesHelpers {
/// <https://drafts.csswg.org/cssom/#insert-a-css-rule>
///
/// Written in this funky way because parsing an @import rule may cause us
/// to clone a stylesheet from the same document due to caching in the CSS
... | {
dest.write_str(" {")?;
for rule in self.0.iter() {
dest.write_str("\n ")?;
rule.to_css(guard, dest)?;
}
dest.write_str("\n}")
} | identifier_body |
generic-fn.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 mut x = 62;
let mut y = 63;
let a = 'a';
let mut b = 'b';
let p: Triple = Triple {x: 65, y: 66, z: 67};
let mut q: Triple = Triple {x: 68, y: 69, z: 70};
y = id::<int>(x);
println!("{}", y);
assert_eq!(x, y);
b = id::<char>(a);
println!("{}", b);
assert_eq!(a, b)... | main | identifier_name |
generic-fn.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. | // 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.
#![allow(dead_assignment)]
fn id<T>(x: T) -> T { return x; }
struct Triple {x: int, y:... | //
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or | random_line_split |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.