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 |
|---|---|---|---|---|
filter.rs | use crate::fns::FnMut1;
use core::fmt;
use core::pin::Pin;
use futures_core::future::Future;
use futures_core::ready;
use futures_core::stream::{FusedStream, Stream};
use futures_core::task::{Context, Poll};
#[cfg(feature = "sink")]
use futures_sink::Sink;
use pin_project_lite::pin_project;
pin_project! {
/// Stre... |
}
// Forwarding impl of Sink from the underlying stream
#[cfg(feature = "sink")]
impl<S, Fut, F, Item> Sink<Item> for Filter<S, Fut, F>
where
S: Stream + Sink<Item>,
F: FnMut(&S::Item) -> Fut,
Fut: Future<Output = bool>,
{
type Error = S::Error;
delegate_sink!(stream, Item);
}
| {
let pending_len = if self.pending_item.is_some() { 1 } else { 0 };
let (_, upper) = self.stream.size_hint();
let upper = match upper {
Some(x) => x.checked_add(pending_len),
None => None,
};
(0, upper) // can't know a lower bound, due to the predicate
... | identifier_body |
htmloptionscollection.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::ElementBinding::ElementMethods;
use dom::bindings::codegen::Bindings::HTMLCo... |
// Step 3
if node == before_node {
return Ok(());
}
}
// Step 4
let reference_node = before.and_then(|before| {
match before {
HTMLElementOrLong::HTMLElement(element) => Some(Root::upcast::<Node>(element)),
... | {
return Err(Error::NotFound);
} | conditional_block |
htmloptionscollection.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::ElementBinding::ElementMethods;
use dom::bindings::codegen::Bindings::HTMLCo... | self.upcast().IndexedGetter(index as u32).map(Root::upcast::<Node>)
}
}
});
// Step 5
let parent = if let Some(reference_node) = reference_node.r() {
reference_node.GetParentNode().unwrap()
} else {
root
};
... | random_line_split | |
htmloptionscollection.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::ElementBinding::ElementMethods;
use dom::bindings::codegen::Bindings::HTMLCo... | (&self) -> Vec<DOMString> {
self.upcast().SupportedPropertyNames()
}
// FIXME: This shouldn't need to be implemented here since HTMLCollection (the parent of
// HTMLOptionsCollection) implements IndexedGetter.
// https://github.com/servo/servo/issues/5875
//
// https://dom.spec.whatwg.o... | SupportedPropertyNames | identifier_name |
htmloptionscollection.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::ElementBinding::ElementMethods;
use dom::bindings::codegen::Bindings::HTMLCo... |
// https://html.spec.whatwg.org/multipage/#dom-htmloptionscollection-setter
fn IndexedSetter(&self, index: u32, value: Option<&HTMLOptionElement>) -> ErrorResult {
if let Some(value) = value {
// Step 2
let length = self.upcast().Length();
// Step 3
let... | {
self.upcast().IndexedGetter(index)
} | identifier_body |
mem.rs | ().unwrap();
system_reporter::collect_reports(request)
});
mem_profiler_chan.send(ProfilerMsg::RegisterReporter("system".to_owned(),
Reporter(system_reporter_sender)));
mem_profiler_chan
}
pub fn new(port: IpcRece... |
#[cfg(target_os = "linux")]
fn page_size() -> usize {
unsafe {
::libc::sysconf(::libc::_SC_PAGESIZE) as usize
}
}
#[cfg(target_os = "linux")]
fn proc_self_statm_field(field: usize) -> Option<usize> {
use std::fs::File;
use std::io::Read;
let mut... | ($e:expr) => (match $e { Some(e) => e, None => return None })
); | random_line_split |
mem.rs | unwrap();
system_reporter::collect_reports(request)
});
mem_profiler_chan.send(ProfilerMsg::RegisterReporter("system".to_owned(),
Reporter(system_reporter_sender)));
mem_profiler_chan
}
pub fn new(port: IpcReceive... |
extern {
fn je_mallctl(name: *const c_char, oldp: *mut c_void, oldlenp: *mut size_t,
newp: *mut c_void, newlen: size_t) -> c_int;
}
fn jemalloc_stat(value_name: &str) -> Option<usize> {
// Before we request the measurement of interest, we first send an "epoch"
... | {
None
} | identifier_body |
mem.rs | (period: Option<f64>) -> ProfilerChan {
let (chan, port) = ipc::channel().unwrap();
// Create the timer thread if a period was provided.
if let Some(period) = period {
let chan = chan.clone();
spawn_named("Memory profiler timer".to_owned(), move || {
loop... | create | identifier_name | |
bug-2470-bounds-check-overflow-2.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | fn main() {
let x = ~[1u,2u,3u];
// This should cause a bounds-check failure, but may not if we do our
// bounds checking by comparing a scaled index value to the vector's
// length (in bytes), because the scaling of the index will cause it to
// wrap around to a small number.
let idx = uint::... | // except according to those terms.
// xfail-test
// error-pattern:index out of bounds
| random_line_split |
bug-2470-bounds-check-overflow-2.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | () {
let x = ~[1u,2u,3u];
// This should cause a bounds-check failure, but may not if we do our
// bounds checking by comparing a scaled index value to the vector's
// length (in bytes), because the scaling of the index will cause it to
// wrap around to a small number.
let idx = uint::max_val... | main | identifier_name |
bug-2470-bounds-check-overflow-2.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | {
let x = ~[1u,2u,3u];
// This should cause a bounds-check failure, but may not if we do our
// bounds checking by comparing a scaled index value to the vector's
// length (in bytes), because the scaling of the index will cause it to
// wrap around to a small number.
let idx = uint::max_value ... | identifier_body | |
world.rs | use crate::{
ai, animations, components, desc, flags::Flags, item, spatial::Spatial, spec::EntitySpawn,
stats, world_cache::WorldCache, Distribution, ExternalEntity, Location, Rng, WorldSkeleton,
};
use calx::seeded_rng;
use serde::{Deserialize, Serialize};
use std::collections::HashSet;
pub const GAME_VERSION... | (&mut self) {
let mut spawns = self.world_cache.drain_spawns();
spawns.retain(|s|!self.generated_spawns.contains(s));
let seed = self.rng_seed();
for (loc, s) in &spawns {
// Create one-off RNG from just the spawn info, will always run the same for same info.
let... | generate_world_spawns | identifier_name |
world.rs | use crate::{
ai, animations, components, desc, flags::Flags, item, spatial::Spatial, spec::EntitySpawn,
stats, world_cache::WorldCache, Distribution, ExternalEntity, Location, Rng, WorldSkeleton,
};
use calx::seeded_rng;
use serde::{Deserialize, Serialize};
use std::collections::HashSet;
pub const GAME_VERSION... | impl World {
pub fn new(world_seed: &WorldSeed) -> World {
let mut ret = World {
version: GAME_VERSION.to_string(),
ecs: Default::default(),
world_cache: WorldCache::new(world_seed.rng_seed, world_seed.world_skeleton.clone()),
generated_spawns: Default::defaul... | pub(crate) rng: Rng,
}
| random_line_split |
cabi_x86_64.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... | SSEFv => {
let vec_len = llvec_len(cls.tailn(i + 1u));
let vec_ty = Type::vector(&Type::f32(ccx), (vec_len * 2u) as u64);
tys.push(vec_ty);
i += vec_len;
continue;
}
SSEFs => {
tys.push(Ty... | {
fn llvec_len(cls: &[RegClass]) -> uint {
let mut len = 1u;
for c in cls.iter() {
if *c != SSEUp {
break;
}
len += 1u;
}
return len;
}
let mut tys = Vec::new();
let mut i = 0u;
let e = cls.len();
while i < e {
... | identifier_body |
cabi_x86_64.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... | }
}
fn classify_ty(ty: Type) -> Vec<RegClass> {
fn align(off: uint, ty: Type) -> uint {
let a = ty_align(ty);
return (off + a - 1u) / a * a;
}
fn ty_align(ty: Type) -> uint {
match ty.kind() {
Integer => {
unsafe {
((llvm::LLVMGet... | random_line_split | |
cabi_x86_64.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... | (ty: Type) -> Vec<RegClass> {
fn align(off: uint, ty: Type) -> uint {
let a = ty_align(ty);
return (off + a - 1u) / a * a;
}
fn ty_align(ty: Type) -> uint {
match ty.kind() {
Integer => {
unsafe {
((llvm::LLVMGetIntTypeWidth(ty.to_ref(... | classify_ty | identifier_name |
viewport.rs | //! Provides a utility method for calculating native viewport size when the window is resized.
use ppu::{SCREEN_WIDTH, SCREEN_HEIGHT};
/// A simple rectangle
pub struct | {
pub x: u32,
pub y: u32,
pub w: u32,
pub h: u32,
}
impl Viewport {
/// Calculates a viewport to use for a window of the given size.
///
/// The returned viewport will have the native SNES aspect ratio and still fill the window on at
/// least one axis. Basically, this calculates the b... | Viewport | identifier_name |
viewport.rs | //! Provides a utility method for calculating native viewport size when the window is resized.
use ppu::{SCREEN_WIDTH, SCREEN_HEIGHT};
/// A simple rectangle
pub struct Viewport {
pub x: u32,
pub y: u32,
pub w: u32,
pub h: u32,
}
impl Viewport {
/// Calculates a viewport to use for a window of th... | else {
// Too high
view_w = w;
view_h = w / NATIVE_RATIO;
}
let border_x = (w - view_w).round() as u32 / 2;
let border_y = (h - view_h).round() as u32 / 2;
let view_w = view_w.round() as u32;
let view_h = view_h.round() as u32;
Viewp... | {
// Too wide
view_h = h;
view_w = h * NATIVE_RATIO;
} | conditional_block |
viewport.rs | //! Provides a utility method for calculating native viewport size when the window is resized.
use ppu::{SCREEN_WIDTH, SCREEN_HEIGHT};
/// A simple rectangle
pub struct Viewport {
pub x: u32,
pub y: u32,
pub w: u32, | }
impl Viewport {
/// Calculates a viewport to use for a window of the given size.
///
/// The returned viewport will have the native SNES aspect ratio and still fill the window on at
/// least one axis. Basically, this calculates the black bars to apply to the window to make the
/// center have th... | pub h: u32, | random_line_split |
config.rs | use toml;
use std::fs::File;
use std::io::BufReader;
use std::io::prelude::*;
#[derive(Debug, Deserialize)]
pub struct Config {
pub uplink: Uplink,
pub plugins: Option<Vec<Plugin>>,
}
#[derive(Debug, Deserialize)]
pub struct Uplink {
pub ip: String,
pub port: i32,
pub protocol: String,
pub hos... | () -> Result<Result<Config, toml::de::Error>, ::std::io::Error> {
let file = File::open("etc/nero.toml")?;
let mut buf_reader = BufReader::new(file);
let mut contents = String::new();
buf_reader.read_to_string(&mut contents)?;
Ok(toml::from_str(&contents))
}
| load | identifier_name |
config.rs | use toml;
use std::fs::File;
use std::io::BufReader;
use std::io::prelude::*;
#[derive(Debug, Deserialize)]
pub struct Config {
pub uplink: Uplink,
pub plugins: Option<Vec<Plugin>>,
}
#[derive(Debug, Deserialize)]
pub struct Uplink {
pub ip: String,
pub port: i32,
pub protocol: String,
pub hos... |
let cfg: Config = toml::from_str(&contents)?;
Ok(cfg.uplink.protocol)
}
pub fn load() -> Result<Result<Config, toml::de::Error>, ::std::io::Error> {
let file = File::open("etc/nero.toml")?;
let mut buf_reader = BufReader::new(file);
let mut contents = String::new();
buf_reader.read_to_string(... | let mut buf_reader = BufReader::new(file);
let mut contents = String::new();
buf_reader.read_to_string(&mut contents)?; | random_line_split |
fields-definition.rs | // Copyright 2018 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() {} | random_line_split | |
fields-definition.rs | // Copyright 2018 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 ... | {} | identifier_body | |
fields-definition.rs | // Copyright 2018 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | {
a: u8,
$a: u8, // OK
}
}
macro_rules! legacy {
($a: ident) => {
struct Legacy {
a: u8,
$a: u8, //~ ERROR field `a` is already declared
}
}
}
modern!(a);
legacy!(a);
fn main() {}
| Modern | identifier_name |
main.rs | // @gbersac, @adjivas - github.com/adjivas. See the LICENSE
// file at the top-level directory of this distribution and at
// https://github.com/adjivas/expert-system
//
// This file may not be copied, modified, or distributed
// except according to those terms.
extern crate regex;
mod parser;
mod parse_result;
mod s... |
/// Return the file name to parse in this execution.
fn args_parse() -> String {
let args: Vec<_> = env::args().collect();
if args.len() < 2 {
println!("usage: {} file_name", args[0]);
std::process::exit(1)
}
args[1].clone()
}
fn resolve_and_print(
deps: &HashMap<char, ImplyPtr>,
initial_facts: &Set
) {
l... | {
let mut f = File::open(filename).unwrap();
let mut s = String::new();
let _ = f.read_to_string(&mut s);
s
} | identifier_body |
main.rs | // @gbersac, @adjivas - github.com/adjivas. See the LICENSE
// file at the top-level directory of this distribution and at
// https://github.com/adjivas/expert-system
//
// This file may not be copied, modified, or distributed
// except according to those terms.
extern crate regex;
mod parser;
mod parse_result;
mod s... | println!("\nSolution according to those dependences:");
for initial_facts in &parsed.initial_facts {
resolve_and_print(&deps, initial_facts);
}
} | key, value.borrow().get_ident().unwrap());
} | random_line_split |
main.rs | // @gbersac, @adjivas - github.com/adjivas. See the LICENSE
// file at the top-level directory of this distribution and at
// https://github.com/adjivas/expert-system
//
// This file may not be copied, modified, or distributed
// except according to those terms.
extern crate regex;
mod parser;
mod parse_result;
mod s... |
let parsed = parsed.unwrap();
let deps = solver::solve(&parsed);
println!("Query dependences:");
for (key, value) in &deps {
println!("For {} dependence tree is: {}",
key, value.borrow().get_ident().unwrap());
}
println!("\nSolution according to those dependences:");
for initial_fa... | {
println!("Parse error");
return ;
} | conditional_block |
main.rs | // @gbersac, @adjivas - github.com/adjivas. See the LICENSE
// file at the top-level directory of this distribution and at
// https://github.com/adjivas/expert-system
//
// This file may not be copied, modified, or distributed
// except according to those terms.
extern crate regex;
mod parser;
mod parse_result;
mod s... | () -> String {
let args: Vec<_> = env::args().collect();
if args.len() < 2 {
println!("usage: {} file_name", args[0]);
std::process::exit(1)
}
args[1].clone()
}
fn resolve_and_print(
deps: &HashMap<char, ImplyPtr>,
initial_facts: &Set
) {
let initial_facts_str = initial_facts.true_fact_str();
println!("\nW... | args_parse | identifier_name |
cast_lossless.rs | use clippy_utils::diagnostics::span_lint_and_sugg;
use clippy_utils::in_constant;
use clippy_utils::source::snippet_opt;
use clippy_utils::ty::is_isize_or_usize;
use rustc_errors::Applicability;
use rustc_hir::{Expr, ExprKind};
use rustc_lint::LateContext;
use rustc_middle::ty::{self, FloatTy, Ty};
use super::{utils, ... |
false
}
| {
if snip.starts_with('(') && snip.ends_with(')') {
return true;
}
} | conditional_block |
cast_lossless.rs | use clippy_utils::diagnostics::span_lint_and_sugg;
use clippy_utils::in_constant;
use clippy_utils::source::snippet_opt;
use clippy_utils::ty::is_isize_or_usize;
use rustc_errors::Applicability;
use rustc_hir::{Expr, ExprKind};
use rustc_lint::LateContext;
use rustc_middle::ty::{self, FloatTy, Ty};
use super::{utils, ... | (cx: &LateContext<'_>, expr: &Expr<'_>, cast_from: Ty<'_>, cast_to: Ty<'_>) -> bool {
// Do not suggest using From in consts/statics until it is valid to do so (see #2267).
if in_constant(cx, expr.hir_id) {
return false;
}
match (cast_from.is_integral(), cast_to.is_integral()) {
(true, ... | should_lint | identifier_name |
cast_lossless.rs | use clippy_utils::diagnostics::span_lint_and_sugg;
use clippy_utils::in_constant;
use clippy_utils::source::snippet_opt;
use clippy_utils::ty::is_isize_or_usize;
use rustc_errors::Applicability;
use rustc_hir::{Expr, ExprKind};
use rustc_lint::LateContext;
use rustc_middle::ty::{self, FloatTy, Ty};
use super::{utils, ... | span_lint_and_sugg(
cx,
CAST_LOSSLESS,
expr.span,
&format!(
"casting `{}` to `{}` may become silently lossy if you later change the type",
cast_from, cast_to
),
"try",
format!("{}::from({})", cast_to, sugg),
applicability,
)... | }
},
);
| random_line_split |
cast_lossless.rs | use clippy_utils::diagnostics::span_lint_and_sugg;
use clippy_utils::in_constant;
use clippy_utils::source::snippet_opt;
use clippy_utils::ty::is_isize_or_usize;
use rustc_errors::Applicability;
use rustc_hir::{Expr, ExprKind};
use rustc_lint::LateContext;
use rustc_middle::ty::{self, FloatTy, Ty};
use super::{utils, ... | 32
} else {
64
};
from_nbits < to_nbits
},
(_, _) => {
matches!(cast_from.kind(), ty::Float(FloatTy::F32)) && matches!(cast_to.kind(), ty::Float(FloatTy::F64))
},
}
}
fn should_strip_parens(cast_expr: &Expr<'_... | {
// Do not suggest using From in consts/statics until it is valid to do so (see #2267).
if in_constant(cx, expr.hir_id) {
return false;
}
match (cast_from.is_integral(), cast_to.is_integral()) {
(true, true) => {
let cast_signed_to_unsigned = cast_from.is_signed() && !cast_... | identifier_body |
basket.rs | use diesel::prelude::*;
use diesel;
use serde::{Serialize, Serializer};
use std::fmt;
use std::ops::Deref;
use db::schema::baskets;
use db::schema::users;
use db::Db;
use model::{basket, AuthUser, PubUser, User};
use model::permissions::{has_permission, UserAction};
use routes::new::NewBasketForm;
use super::MAX_SL_L... | self.description.as_ref().map(AsRef::as_ref)
}
pub fn kind(&self) -> &str {
&self.kind
}
}
#[derive(Clone, Debug, Insertable)]
#[table_name = "baskets"]
pub struct NewBasket {
name: String,
user_id: i64,
description: Option<String>,
public: bool,
kind: String,
forke... | random_line_split | |
basket.rs | use diesel::prelude::*;
use diesel;
use serde::{Serialize, Serializer};
use std::fmt;
use std::ops::Deref;
use db::schema::baskets;
use db::schema::users;
use db::Db;
use model::{basket, AuthUser, PubUser, User};
use model::permissions::{has_permission, UserAction};
use routes::new::NewBasketForm;
use super::MAX_SL_L... | else {
Some(new.description.trim().into())
};
let new_basket = NewBasket {
name: new.name,
user_id: user.id(),
description: description,
public: new.is_public,
kind: new.kind,
forked_from: None,
};
let... | {
None
} | conditional_block |
basket.rs | use diesel::prelude::*;
use diesel;
use serde::{Serialize, Serializer};
use std::fmt;
use std::ops::Deref;
use db::schema::baskets;
use db::schema::users;
use db::Db;
use model::{basket, AuthUser, PubUser, User};
use model::permissions::{has_permission, UserAction};
use routes::new::NewBasketForm;
use super::MAX_SL_L... | (
name: &str,
owner: &str,
auth_user: Option<&AuthUser>,
db: &Db,
) -> Option<Self> {
baskets::table
.inner_join(users::table)
.filter(baskets::name.eq(name))
.filter(users::username.eq(owner))
.first(&*db.conn())
.option... | load | identifier_name |
usergroups_users.rs | //=============================================================================
//
// WARNING: This file is AUTO-GENERATED
//
// Do not make changes directly to this file.
//
// If you would like to make a change to the library, please update the schema
// definitions at https://github.com/slack-rs/s... | <R>(
client: &R,
token: &str,
request: &UpdateRequest<'_>,
) -> Result<UpdateResponse, UpdateError<R::Error>>
where
R: SlackWebRequestSender,
{
let params = vec![
Some(("token", token)),
Some(("usergroup", request.usergroup)),
Some(("users", request.users)),
request
... | update | identifier_name |
usergroups_users.rs | //=============================================================================
//
// WARNING: This file is AUTO-GENERATED
//
// Do not make changes directly to this file.
//
// If you would like to make a change to the library, please update the schema
// definitions at https://github.com/slack-rs/s... | Some(("token", token)),
Some(("usergroup", request.usergroup)),
Some(("users", request.users)),
request
.include_count
.map(|include_count| ("include_count", if include_count { "1" } else { "0" })),
];
let params = params.into_iter().filter_map(|x| x).collec... | where
R: SlackWebRequestSender,
{
let params = vec![ | random_line_split |
usergroups_users.rs | //=============================================================================
//
// WARNING: This file is AUTO-GENERATED
//
// Do not make changes directly to this file.
//
// If you would like to make a change to the library, please update the schema
// definitions at https://github.com/slack-rs/s... | }
| {
let params = vec![
Some(("token", token)),
Some(("usergroup", request.usergroup)),
Some(("users", request.users)),
request
.include_count
.map(|include_count| ("include_count", if include_count { "1" } else { "0" })),
];
let params = params.into_iter... | identifier_body |
nonnanfloat.rs | use std::cmp;
use num_traits::Float;
#[derive(PartialOrd, PartialEq, Debug, Copy, Clone)]
pub struct NonNaNFloat<F: Float>(F);
impl<F: Float> NonNaNFloat<F> {
pub fn new(v: F) -> Option<Self> {
if v.is_nan() {
Some(NonNaNFloat(v))
} else {
None
}
}
pub fn ... | () {
let mut v = [NonNaNFloat(5.1), NonNaNFloat(1.3)];
v.sort();
assert_eq!(v, [NonNaNFloat(1.3), NonNaNFloat(5.1)]);
}
}
| test_nonnanfloat | identifier_name |
nonnanfloat.rs | use std::cmp;
use num_traits::Float;
#[derive(PartialOrd, PartialEq, Debug, Copy, Clone)]
pub struct NonNaNFloat<F: Float>(F);
impl<F: Float> NonNaNFloat<F> {
pub fn new(v: F) -> Option<Self> {
if v.is_nan() {
Some(NonNaNFloat(v))
} else {
None
}
}
pub fn ... |
}
impl<F: Float> Eq for NonNaNFloat<F> {}
impl<F: Float> Ord for NonNaNFloat<F> {
fn cmp(&self, other: &Self) -> cmp::Ordering {
self.partial_cmp(other).unwrap()
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_nonnanfloat() {
let mut v = [NonNaNFloat(5.1), NonNaNFlo... | {
let &NonNaNFloat(v) = self;
v
} | identifier_body |
nonnanfloat.rs | use std::cmp;
use num_traits::Float;
#[derive(PartialOrd, PartialEq, Debug, Copy, Clone)]
pub struct NonNaNFloat<F: Float>(F);
impl<F: Float> NonNaNFloat<F> {
pub fn new(v: F) -> Option<Self> {
if v.is_nan() | else {
None
}
}
pub fn unwrap(&self) -> F {
let &NonNaNFloat(v) = self;
v
}
}
impl<F: Float> Eq for NonNaNFloat<F> {}
impl<F: Float> Ord for NonNaNFloat<F> {
fn cmp(&self, other: &Self) -> cmp::Ordering {
self.partial_cmp(other).unwrap()
}
}
#[cfg(t... | {
Some(NonNaNFloat(v))
} | conditional_block |
nonnanfloat.rs | use std::cmp;
use num_traits::Float;
#[derive(PartialOrd, PartialEq, Debug, Copy, Clone)]
pub struct NonNaNFloat<F: Float>(F);
impl<F: Float> NonNaNFloat<F> {
pub fn new(v: F) -> Option<Self> {
if v.is_nan() {
Some(NonNaNFloat(v)) |
pub fn unwrap(&self) -> F {
let &NonNaNFloat(v) = self;
v
}
}
impl<F: Float> Eq for NonNaNFloat<F> {}
impl<F: Float> Ord for NonNaNFloat<F> {
fn cmp(&self, other: &Self) -> cmp::Ordering {
self.partial_cmp(other).unwrap()
}
}
#[cfg(test)]
mod tests {
use super::*;
... | } else {
None
}
} | random_line_split |
apt.rs | // Copyright 2015-2017 Intecture Developers.
//
// Licensed under the Mozilla Public License 2.0 <LICENSE or
// https://www.tldrlegal.com/l/mpl-2.0>. This file may not be copied,
// modified, or distributed except according to those terms.
use command::{self, Child};
use error_chain::ChainedError;
use errors::*;
use f... |
fn uninstall(&self, host: &Local, name: &str) -> FutureResult<Child, Error> {
let cmd = match command::factory() {
Ok(c) => c,
Err(e) => return future::err(format!("{}", e.display_chain()).into()),
};
cmd.exec(host, &["apt-get", "-y", "remove", name])
}
}
| {
let cmd = match command::factory() {
Ok(c) => c,
Err(e) => return future::err(format!("{}", e.display_chain()).into()),
};
cmd.exec(host, &["apt-get", "-y", "install", name])
} | identifier_body |
apt.rs | // Copyright 2015-2017 Intecture Developers.
//
// Licensed under the Mozilla Public License 2.0 <LICENSE or
// https://www.tldrlegal.com/l/mpl-2.0>. This file may not be copied,
// modified, or distributed except according to those terms.
| use futures::future::FutureResult;
use host::Host;
use host::local::Local;
use regex::Regex;
use std::process;
use super::PackageProvider;
use tokio_process::CommandExt;
pub struct Apt;
impl PackageProvider for Apt {
fn available() -> Result<bool> {
Ok(process::Command::new("/usr/bin/type")
.ar... | use command::{self, Child};
use error_chain::ChainedError;
use errors::*;
use futures::{future, Future}; | random_line_split |
apt.rs | // Copyright 2015-2017 Intecture Developers.
//
// Licensed under the Mozilla Public License 2.0 <LICENSE or
// https://www.tldrlegal.com/l/mpl-2.0>. This file may not be copied,
// modified, or distributed except according to those terms.
use command::{self, Child};
use error_chain::ChainedError;
use errors::*;
use f... | ;
impl PackageProvider for Apt {
fn available() -> Result<bool> {
Ok(process::Command::new("/usr/bin/type")
.arg("apt-get")
.status()
.chain_err(|| "Could not determine provider availability")?
.success())
}
fn installed(&self, host: &Local, name: &str) ... | Apt | identifier_name |
cargo_expand.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use std::env;
use std::error;
use std::fmt;
use std::io;
use std::path::Path;
use std::process::Command;
use std::... | (&self) -> Option<&(dyn error::Error +'static)> {
match self {
Error::Io(ref err) => Some(err),
Error::Utf8(ref err) => Some(err),
Error::Compile(..) => None,
}
}
}
/// Use rustc to expand and pretty print the crate into a single file,
/// removing any macros in ... | source | identifier_name |
cargo_expand.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use std::env;
use std::error;
use std::fmt;
use std::io;
use std::path::Path;
use std::process::Command;
use std::... | cmd.arg("-Z");
cmd.arg("unstable-options");
cmd.arg("--pretty=expanded");
let output = cmd.output()?;
let src = from_utf8(&output.stdout)?.to_owned();
let error = from_utf8(&output.stderr)?.to_owned();
if src.len() == 0 {
Err(Error::Compile(error))
} else {
Ok(src)
... | cmd.arg("--"); | random_line_split |
cargo_expand.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use std::env;
use std::error;
use std::fmt;
use std::io;
use std::path::Path;
use std::process::Command;
use std::... |
}
impl error::Error for Error {
fn source(&self) -> Option<&(dyn error::Error +'static)> {
match self {
Error::Io(ref err) => Some(err),
Error::Utf8(ref err) => Some(err),
Error::Compile(..) => None,
}
}
}
/// Use rustc to expand and pretty print the crate ... | {
match self {
Error::Io(ref err) => err.fmt(f),
Error::Utf8(ref err) => err.fmt(f),
Error::Compile(ref err) => write!(f, "{}", err),
}
} | identifier_body |
type_of.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... |
// Want refinements! (Or case classes, I guess
pub enum named_ty { a_struct, an_enum }
pub fn llvm_type_name(cx: &CrateContext,
what: named_ty,
did: ast::def_id,
tps: &[ty::t]) -> ~str {
let name = match what {
a_struct => { "struct" }
... | _ => ()
}
return llty;
} | random_line_split |
type_of.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: &CrateContext,
what: named_ty,
did: ast::def_id,
tps: &[ty::t]) -> ~str {
let name = match what {
a_struct => { "struct" }
an_enum => { "enum" }
};
let tstr = ppaux::parameterized(cx.tcx, ty::item_path_str(cx.tcx, did), N... | llvm_type_name | identifier_name |
irc.rs | use config;
use std::thread;
use nyaa::Nyaa;
use message_handler::{MessageHandlerBuilder,MessageHandler};
use colors;
use lib::log::Logger;
use lib::connection::Connection;
use lib::commands::Commands;
use std::sync::{Arc,Mutex,mpsc};
pub struct Irc{
con: Connection,
}
impl Irc{
pub fn new(con: Connection)->I... | self.con.enable_tags();
self.con.enable_whispers();
self.con.set_char_limit(175);
let mut commands = match Commands::new(){
Ok(a) =>a,
Err(_) =>{
logger.add("Could not connect to redis");
return false
}
};
... | {
let mut logger = match Logger::new("logs.txt"){
Ok(l) =>l,
Err(_) =>return false,
};
let cd = match config::ConfigData::new("config.json"){
Ok(a) =>a,
Err(err) =>{
match err{
config::ConfigErr::Parse=>{logger... | identifier_body |
irc.rs | use config;
use std::thread;
use nyaa::Nyaa;
use message_handler::{MessageHandlerBuilder,MessageHandler};
use colors;
use lib::log::Logger;
use lib::connection::Connection;
use lib::commands::Commands;
use std::sync::{Arc,Mutex,mpsc};
pub struct Irc{
con: Connection,
}
impl Irc{
pub fn new(con: Connection)->I... | Ok(a) =>a,
Err(_) =>{
logger.add("Could not clone the socket. Error: ");
return false
}
};
let (tx, rx) = mpsc::channel();
let delay = cd.nyaa.delay;
let channels = cd.channels;
thread::spawn(move || {
... | let mut sock = match self.con.socket_clone(){ | random_line_split |
irc.rs | use config;
use std::thread;
use nyaa::Nyaa;
use message_handler::{MessageHandlerBuilder,MessageHandler};
use colors;
use lib::log::Logger;
use lib::connection::Connection;
use lib::commands::Commands;
use std::sync::{Arc,Mutex,mpsc};
pub struct Irc{
con: Connection,
}
impl Irc{
pub fn new(con: Connection)->I... | (&mut self)->bool{
let mut logger = match Logger::new("logs.txt"){
Ok(l) =>l,
Err(_) =>return false,
};
let cd = match config::ConfigData::new("config.json"){
Ok(a) =>a,
Err(err) =>{
match err{
config::ConfigEr... | start | identifier_name |
irc.rs | use config;
use std::thread;
use nyaa::Nyaa;
use message_handler::{MessageHandlerBuilder,MessageHandler};
use colors;
use lib::log::Logger;
use lib::connection::Connection;
use lib::commands::Commands;
use std::sync::{Arc,Mutex,mpsc};
pub struct Irc{
con: Connection,
}
impl Irc{
pub fn new(con: Connection)->I... |
let mut sock = match self.con.socket_clone(){
Ok(a) =>a,
Err(_) =>{
logger.add("Could not clone the socket. Error: ");
return false
}
};
let (tx, rx) = mpsc::channel();
let delay = cd.nyaa.delay;
let channels =... | {
logger.add("Could not load commands from redis");
} | conditional_block |
inputevent.rs | /* This Source Code Form is subject to the terms of the Mozilla Public | use crate::dom::bindings::codegen::Bindings::InputEventBinding::{self, InputEventMethods};
use crate::dom::bindings::codegen::Bindings::UIEventBinding::UIEventBinding::UIEventMethods;
use crate::dom::bindings::error::Fallible;
use crate::dom::bindings::reflector::reflect_dom_object;
use crate::dom::bindings::root::{Dom... | * License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
| random_line_split |
inputevent.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
use crate::dom::bindings::codegen::Bindings::InputEventBinding::{self, InputEventMethods};
use crate::dom::bindin... |
}
| {
self.uievent.IsTrusted()
} | identifier_body |
inputevent.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
use crate::dom::bindings::codegen::Bindings::InputEventBinding::{self, InputEventMethods};
use crate::dom::bindin... | (&self) -> bool {
self.uievent.IsTrusted()
}
}
| IsTrusted | identifier_name |
mount.rs | use util::*;
use hyper::status::StatusCode;
use hyper::client::Response;
fn | <F>(path: &str, f: F) where F: FnOnce(&mut Response) {
run_example("mount", |port| {
let url = format!("http://localhost:{}{}", port, path);
let ref mut res = response_for(&url);
f(res)
})
}
#[test]
fn trims_the_prefix() {
with_path("/test/foo", |res| {
let s = read_body_to_... | with_path | identifier_name |
mount.rs | use util::*;
use hyper::status::StatusCode;
use hyper::client::Response;
fn with_path<F>(path: &str, f: F) where F: FnOnce(&mut Response) {
run_example("mount", |port| {
let url = format!("http://localhost:{}{}", port, path);
let ref mut res = response_for(&url);
f(res)
})
}
#[test]
f... | with_path("/static/files/a", |res| {
let s = read_body_to_string(res);
assert_eq!(s, "No static file with path '/a'!");
});
} | random_line_split | |
mount.rs | use util::*;
use hyper::status::StatusCode;
use hyper::client::Response;
fn with_path<F>(path: &str, f: F) where F: FnOnce(&mut Response) {
run_example("mount", |port| {
let url = format!("http://localhost:{}{}", port, path);
let ref mut res = response_for(&url);
f(res)
})
}
#[test]
f... | {
// depends on `works_with_another_middleware` passing
with_path("/static/files/a", |res| {
let s = read_body_to_string(res);
assert_eq!(s, "No static file with path '/a'!");
});
} | identifier_body | |
seed.rs | // Copyright 2015 The Noise-rs Developers.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or ... |
#[inline(always)]
pub fn get2<T: Signed + PrimInt + NumCast>(&self, pos: math::Point2<T>) -> usize {
let y: usize = math::cast(pos[1] & math::cast(0xff));
self.values[self.get1(pos[0]) ^ y] as usize
}
#[inline(always)]
pub fn get3<T: Signed + PrimInt + NumCast>(&self, pos: math::P... | {
let x: usize = math::cast(x & math::cast(0xff));
self.values[x] as usize
} | identifier_body |
seed.rs | // Copyright 2015 The Noise-rs Developers.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or ... | /// # Examples
///
/// ```rust
/// extern crate noise;
/// extern crate rand;
///
/// use noise::Seed;
///
/// # fn main() {
/// let seed = rand::random::<Seed>();
/// # }
/// ```
///
/// ```rust
/// extern crate noise;
/// extern crate rand;
///
/... |
impl Rand for Seed {
/// Generates a random seed.
/// | random_line_split |
seed.rs | // Copyright 2015 The Noise-rs Developers.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or ... | () {
let _ = perlin3::<f32>(&random(), &[1.0, 2.0, 3.0]);
}
#[test]
fn test_negative_params() {
let _ = perlin3::<f32>(&Seed::new(0), &[-1.0, 2.0, 3.0]);
}
}
| test_random_seed | identifier_name |
mod.rs | // Copyright 2019 TiKV Project Authors. Licensed under Apache-2.0.
use criterion::{Bencher, Criterion};
use kvproto::deadlock::*;
use rand::prelude::*;
use tikv::server::lock_manager::deadlock::DetectTable;
use tikv_util::time::Duration;
struct DetectGenerator {
rng: ThreadRng,
range: u64,
timestamp: u64,... |
fn bench_dense_detect_without_cleanup(c: &mut Criterion) {
let mut group = c.benchmark_group("bench_dense_detect_without_cleanup");
let ranges = vec![
10,
100,
1_000,
10_000,
100_000,
1_000_000,
10_000_000,
100_000_000,
];
for range in r... | {
let mut detect_table = DetectTable::new(cfg.ttl);
let mut generator = DetectGenerator::new(cfg.range);
b.iter(|| {
for entry in generator.generate(cfg.n) {
detect_table.detect(
entry.get_txn().into(),
entry.get_wait_for_txn().into(),
entr... | identifier_body |
mod.rs | // Copyright 2019 TiKV Project Authors. Licensed under Apache-2.0.
use criterion::{Bencher, Criterion};
use kvproto::deadlock::*;
use rand::prelude::*;
use tikv::server::lock_manager::deadlock::DetectTable;
use tikv_util::time::Duration;
struct DetectGenerator {
rng: ThreadRng,
range: u64,
timestamp: u64,... | () {
let mut criterion = Criterion::default().configure_from_args().sample_size(10);
bench_dense_detect_without_cleanup(&mut criterion);
bench_dense_detect_with_cleanup(&mut criterion);
criterion.final_summary();
}
| main | identifier_name |
mod.rs | // Copyright 2019 TiKV Project Authors. Licensed under Apache-2.0.
use criterion::{Bencher, Criterion};
use kvproto::deadlock::*;
use rand::prelude::*;
use tikv::server::lock_manager::deadlock::DetectTable;
use tikv_util::time::Duration;
struct DetectGenerator {
rng: ThreadRng,
range: u64,
timestamp: u64,... | entries
}
}
#[derive(Debug)]
struct Config {
n: u64,
range: u64,
ttl: Duration,
}
fn bench_detect(b: &mut Bencher, cfg: &Config) {
let mut detect_table = DetectTable::new(cfg.ttl);
let mut generator = DetectGenerator::new(cfg.range);
b.iter(|| {
for entry in generator.gener... | random_line_split | |
mod.rs | // Copyright 2019 TiKV Project Authors. Licensed under Apache-2.0.
use criterion::{Bencher, Criterion};
use kvproto::deadlock::*;
use rand::prelude::*;
use tikv::server::lock_manager::deadlock::DetectTable;
use tikv_util::time::Duration;
struct DetectGenerator {
rng: ThreadRng,
range: u64,
timestamp: u64,... | else {
self.timestamp - self.range
},
self.timestamp + self.range,
);
}
entry.set_wait_for_txn(wait_for_txn);
entry.set_key_hash(self.rng.gen());
entries.push(entry);
});
self... | {
0
} | conditional_block |
main.rs | fn main() {
// defining-structs
{
struct User {
username: String,
email: String,
sign_in_count: u64,
active: bool,
}
// 实例
let user1 = User {
email: String::from("someone@example.com"),
username: String::fr... | let sq = Rectangle::square(3);
println!("sq is {:?}", sq);
}
// 每个结构体都允许拥有多个 impl 块
}
} | th: size, height: size }
}
}
| identifier_body |
main.rs | fn main() {
// defining-structs
{
struct User {
username: String,
email: String,
sign_in_count: u64,
active: bool,
}
// 实例
let user1 = User {
email: String::from("someone@example.com"),
username: String::fr... | email: String::from("another@example.com"),
username: String::from("anotherusername567"),
..user1
};
// 使用没有命名字段的元组结构体来创建不同的类型
// 元组结构体(tuple structs)
struct Color(i32, i32, i32);
struct Point(i32, i32, i32);
let black = Color(0, 0, 0);... | // 可以简写为
let user2 = User { | random_line_split |
main.rs | fn main() {
// defining-structs
{
struct User {
username: String,
email: String,
sign_in_count: u64,
active: bool,
}
// 实例
let user1 = User {
email: String::from("someone@example.com"),
username: String::fr... | ight: u32,
}
impl Rectangle {
fn square(size: u32) -> Rectangle {
Rectangle { width: size, height: size }
}
}
let sq = Rectangle::square(3);
println!("sq is {:?}", sq);
}
// 每个结构体都允许拥有多个 im... | he | identifier_name |
update.rs | use crate::{
self as exercise,
errors::Result,
structs::{LabeledTest, LabeledTestItem},
};
use failure::format_err;
use std::{collections::HashSet, fs, path::Path};
enum DiffType {
NEW,
UPDATED,
}
fn generate_diff_test(
case: &LabeledTest,
diff_type: &DiffType,
use_maplit: bool,
) -> R... | Ok(())
}
pub fn update_exercise(exercise_name: &str, use_maplit: bool) -> Result<()> {
if!exercise::exercise_exists(exercise_name) {
return Err(
format_err!("exercise with the name '{}' does not exist", exercise_name).into(),
);
}
let tests_content = exercise::get_tests_con... | random_line_split | |
update.rs | use crate::{
self as exercise,
errors::Result,
structs::{LabeledTest, LabeledTestItem},
};
use failure::format_err;
use std::{collections::HashSet, fs, path::Path};
enum DiffType {
NEW,
UPDATED,
}
fn generate_diff_test(
case: &LabeledTest,
diff_type: &DiffType,
use_maplit: bool,
) -> R... | (
case: &LabeledTestItem,
diffs: &mut HashSet<String>,
tests_content: &str,
use_maplit: bool,
) -> Result<()> {
match case {
LabeledTestItem::Single(case) => generate_diffs(case, &tests_content, diffs, use_maplit)?,
LabeledTestItem::Array(group) => {
for case in &group.ca... | get_diffs | identifier_name |
update.rs | use crate::{
self as exercise,
errors::Result,
structs::{LabeledTest, LabeledTestItem},
};
use failure::format_err;
use std::{collections::HashSet, fs, path::Path};
enum DiffType {
NEW,
UPDATED,
}
fn generate_diff_test(
case: &LabeledTest,
diff_type: &DiffType,
use_maplit: bool,
) -> R... | ;
if diffs.insert(generate_diff_test(case, &diff_type, use_maplit)?) {
match diff_type {
DiffType::NEW => println!("New test case detected: {}.", description_formatted),
DiffType::UPDATED => println!("Updated test case: {}.", description_formatted),
}
}
let property... | {
DiffType::UPDATED
} | conditional_block |
update.rs | use crate::{
self as exercise,
errors::Result,
structs::{LabeledTest, LabeledTestItem},
};
use failure::format_err;
use std::{collections::HashSet, fs, path::Path};
enum DiffType {
NEW,
UPDATED,
}
fn generate_diff_test(
case: &LabeledTest,
diff_type: &DiffType,
use_maplit: bool,
) -> R... |
fn generate_diff_property(property: &str) -> Result<String> {
Ok(format!(
"//{}\n{}",
"NEW",
exercise::generate_property_body(property)?
))
}
fn generate_diffs(
case: &LabeledTest,
tests_content: &str,
diffs: &mut HashSet<String>,
use_maplit: bool,
) -> Result<()> {
... | {
Ok(format!(
"//{}\n{}",
match diff_type {
DiffType::NEW => "NEW",
DiffType::UPDATED => "UPDATED",
},
exercise::generate_test_function(case, use_maplit)?
))
} | identifier_body |
tradchinese.rs | // This is a part of rust-encoding.
// Copyright (c) 2013-2015, Kang Seonghoon.
// See README.md and LICENSE.txt for details.
//! Legacy traditional Chinese encodings.
use std::convert::Into;
use std::default::Default;
use util::StrCharIndex;
use index_tradchinese as index;
use types::*;
/**
* Big5-2003 with common... | (&mut self, _output: &mut ByteWriter) -> Option<CodecError> {
None
}
}
/// A decoder for Big5-2003 with HKSCS-2008 extension.
#[derive(Clone, Copy)]
struct BigFive2003HKSCS2008Decoder {
st: bigfive2003::State,
}
impl BigFive2003HKSCS2008Decoder {
pub fn new() -> Box<RawDecoder> {
Box::new(... | raw_finish | identifier_name |
tradchinese.rs | // This is a part of rust-encoding.
// Copyright (c) 2013-2015, Kang Seonghoon.
// See README.md and LICENSE.txt for details.
//! Legacy traditional Chinese encodings.
use std::convert::Into;
use std::default::Default;
use util::StrCharIndex;
use index_tradchinese as index;
use types::*;
/**
* Big5-2003 with common... |
}
impl RawEncoder for BigFive2003Encoder {
fn from_self(&self) -> Box<RawEncoder> { BigFive2003Encoder::new() }
fn is_ascii_compatible(&self) -> bool { true }
fn raw_feed(&mut self, input: &str, output: &mut ByteWriter) -> (usize, Option<CodecError>) {
output.writer_hint(input.len());
fo... | { Box::new(BigFive2003Encoder) } | identifier_body |
tradchinese.rs | // This is a part of rust-encoding.
// Copyright (c) 2013-2015, Kang Seonghoon.
// See README.md and LICENSE.txt for details.
//! Legacy traditional Chinese encodings.
use std::convert::Into;
use std::default::Default;
use util::StrCharIndex;
use index_tradchinese as index;
use types::*;
/**
* Big5-2003 with common... | assert_feed_ok!(d, [], [0xa4], "");
assert_feed_ok!(d, [0xa4, 0xb5, 0xd8], [0xa5], "\u{4e2d}\u{83ef}");
assert_feed_ok!(d, [0xc1, 0xb0, 0xea], [], "\u{6c11}\u{570b}");
assert_feed_ok!(d, [0x31, 0xa3, 0xe1, 0x2f, 0x6d], [], "1\u{20ac}/m");
assert_feed_ok!(d, [0xf9, 0xfe], [], "\u{... | assert_feed_ok!(d, [0x41], [], "A");
assert_feed_ok!(d, [0x42, 0x43], [], "BC");
assert_feed_ok!(d, [], [], "");
assert_feed_ok!(d, [0xa4, 0xa4, 0xb5, 0xd8, 0xa5, 0xc1, 0xb0, 0xea], [],
"\u{4e2d}\u{83ef}\u{6c11}\u{570b}"); | random_line_split |
tradchinese.rs | // This is a part of rust-encoding.
// Copyright (c) 2013-2015, Kang Seonghoon.
// See README.md and LICENSE.txt for details.
//! Legacy traditional Chinese encodings.
use std::convert::Into;
use std::default::Default;
use util::StrCharIndex;
use index_tradchinese as index;
use types::*;
/**
* Big5-2003 with common... | else {
let ptr = index::big5::backward(ch as u32);
if ptr == 0xffff {
return (i, Some(CodecError {
upto: j as isize, cause: "unrepresentable character".into()
}));
}
let lead = ptr / 157 + 0x... | {
output.write_byte(ch as u8);
} | conditional_block |
borrowck-loan-rcvr.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 ... | impl methods for point {
fn impurem(&self) {
}
fn blockm(&self, f: ||) { f() }
}
fn a() {
let mut p = point {x: 3, y: 4};
// Here: it's ok to call even though receiver is mutable, because we
// can loan it out.
p.impurem();
// But in this case we do not honor the loan:
p.blockm(|... | fn impurem(&self);
fn blockm(&self, f: ||);
}
| random_line_split |
borrowck-loan-rcvr.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 ... | {
} | identifier_body | |
borrowck-loan-rcvr.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 |
cssstylerule.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::CSSStyleRuleBinding;
use dom::bindings::js::Root;
use dom::bindings::reflect... |
}
| {
self.stylerule.read().to_css_string().into()
} | identifier_body |
cssstylerule.rs | /* This Source Code Form is subject to the terms of the Mozilla Public |
use dom::bindings::codegen::Bindings::CSSStyleRuleBinding;
use dom::bindings::js::Root;
use dom::bindings::reflector::reflect_dom_object;
use dom::bindings::str::DOMString;
use dom::cssrule::{CSSRule, SpecificCSSRule};
use dom::cssstylesheet::CSSStyleSheet;
use dom::window::Window;
use parking_lot::RwLock;
use std::sy... | * 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/. */ | random_line_split |
cssstylerule.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::CSSStyleRuleBinding;
use dom::bindings::js::Root;
use dom::bindings::reflect... | (&self) -> u16 {
use dom::bindings::codegen::Bindings::CSSRuleBinding::CSSRuleConstants;
CSSRuleConstants::STYLE_RULE
}
fn get_css(&self) -> DOMString {
self.stylerule.read().to_css_string().into()
}
}
| ty | identifier_name |
message.rs | //! JSONRPC message types
//! See https://www.jsonrpc.org/specification
use serde::{Deserialize, Serialize};
use serde_json::{Map, Value};
pub const VERSION: &str = "2.0";
#[derive(Serialize, Deserialize, Debug)]
pub struct Message {
jsonrpc: String,
#[serde(flatten)]
type_: Type,
}
impl Message {
p... |
pub fn make_response(result: Option<Value>, id: Value) -> Self {
Message { jsonrpc: VERSION.to_string(), type_: Type::Response(Response { result, error: None, id }) }
}
pub fn version(&self) -> &str {
self.jsonrpc.as_str()
}
pub fn is_request(&self) -> bool {
matches!(sel... | {
Message { jsonrpc: VERSION.to_string(), type_: Type::Response(Response { result: None, error: Some(error), id }) }
} | identifier_body |
message.rs | //! JSONRPC message types
//! See https://www.jsonrpc.org/specification
use serde::{Deserialize, Serialize};
use serde_json::{Map, Value};
pub const VERSION: &str = "2.0";
#[derive(Serialize, Deserialize, Debug)]
pub struct Message {
jsonrpc: String,
#[serde(flatten)]
type_: Type,
}
impl Message {
p... |
pub fn is_response(&self) -> bool {
matches!(self.type_, Type::Response(_))
}
pub fn request(self) -> Option<Request> {
match self.type_ {
Type::Request(req) => Some(req),
_ => None,
}
}
pub fn response(self) -> Option<Response> {
match self... | random_line_split | |
message.rs | //! JSONRPC message types
//! See https://www.jsonrpc.org/specification
use serde::{Deserialize, Serialize};
use serde_json::{Map, Value};
pub const VERSION: &str = "2.0";
#[derive(Serialize, Deserialize, Debug)]
pub struct Message {
jsonrpc: String,
#[serde(flatten)]
type_: Type,
}
impl Message {
p... | (self) -> Option<Request> {
match self.type_ {
Type::Request(req) => Some(req),
_ => None,
}
}
pub fn response(self) -> Option<Response> {
match self.type_ {
Type::Response(resp) => Some(resp),
_ => None,
}
}
}
#[derive(Serial... | request | identifier_name |
lib.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 ... | () ->! {
// FIXME(#14674): This really needs to do something other than just abort
// here, but any printing done must be *guaranteed* to not
// allocate.
unsafe { core::intrinsics::abort() }
}
| oom | identifier_name |
lib.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 ... | {
// FIXME(#14674): This really needs to do something other than just abort
// here, but any printing done must be *guaranteed* to not
// allocate.
unsafe { core::intrinsics::abort() }
} | identifier_body | |
lib.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 ... |
/// Common out-of-memory routine
#[cold]
#[inline(never)]
#[unstable(feature = "oom", reason = "not a scrutinized interface")]
pub fn oom() ->! {
// FIXME(#14674): This really needs to do something other than just abort
// here, but any printing done must be *guaranteed* to not
// ... | pub mod rc;
pub mod raw_vec; | random_line_split |
lib.rs | #![warn(missing_docs)]
//! Simple and generic implementation of 2D vectors
//!
//! Intended for use in 2D game engines
extern crate num_traits;
#[cfg(feature="rustc-serialize")]
extern crate rustc_serialize;
#[cfg(feature="serde_derive")]
#[cfg_attr(feature="serde_derive", macro_use)]
extern crate serde_derive;
use ... | (direction: T) -> Self{
let (y, x) = direction.sin_cos();
Vector2(x, y)
}
/// Normalises the vector
pub fn normalise(self) -> Self{
self / self.length()
}
/// Returns the magnitude/length of the vector
pub fn length(self) -> T{
// This is apparently faster than us... | unit_vector | identifier_name |
lib.rs | #![warn(missing_docs)]
//! Simple and generic implementation of 2D vectors
//!
//! Intended for use in 2D game engines
extern crate num_traits;
#[cfg(feature="rustc-serialize")]
extern crate rustc_serialize;
#[cfg(feature="serde_derive")]
#[cfg_attr(feature="serde_derive", macro_use)]
extern crate serde_derive;
use ... | Vector2(self.0/rhs, self.1/rhs)
}
}
impl<T: Neg> Neg for Vector2<T>{
type Output = Vector2<T::Output>;
fn neg(self) -> Self::Output{
Vector2(-self.0, -self.1)
}
}
impl<T> Into<[T; 2]> for Vector2<T>{
#[inline]
fn into(self) -> [T; 2]{
[self.0, self.1]
}
}
impl<T: ... | random_line_split | |
lib.rs | #![warn(missing_docs)]
//! Simple and generic implementation of 2D vectors
//!
//! Intended for use in 2D game engines
extern crate num_traits;
#[cfg(feature="rustc-serialize")]
extern crate rustc_serialize;
#[cfg(feature="serde_derive")]
#[cfg_attr(feature="serde_derive", macro_use)]
extern crate serde_derive;
use ... |
/// Returns direction the vector is pointing
pub fn direction(self) -> T{
self.1.atan2(self.0)
}
/// Returns direction towards another vector
pub fn direction_to(self, other: Self) -> T{
(other-self).direction()
}
/// Returns the distance betweens two vectors
pub fn dist... | {
self.0.powi(2) + self.1.powi(2)
} | identifier_body |
nf.rs | use e2d2::common::EmptyMetadata;
use e2d2::headers::*;
use e2d2::operators::*;
#[inline]
pub fn chain_nf<T:'static + Batch<Header = NullHeader, Metadata = EmptyMetadata>>(parent: T) -> CompositionBatch {
parent.parse::<MacHeader>()
.transform(box move |pkt| {
let mut hdr = pkt.get_mut_header();
... | <T:'static + Batch<Header = NullHeader, Metadata = EmptyMetadata>>(parent: T,
len: u32,
pos: u32)
... | chain | identifier_name |
nf.rs | use e2d2::common::EmptyMetadata;
use e2d2::headers::*;
use e2d2::operators::*;
#[inline]
pub fn chain_nf<T:'static + Batch<Header = NullHeader, Metadata = EmptyMetadata>>(parent: T) -> CompositionBatch {
parent.parse::<MacHeader>()
.transform(box move |pkt| {
let mut hdr = pkt.get_mut_header();
... | {
let mut chained = chain_nf(parent);
for _ in 1..len {
chained = chain_nf(chained);
}
if len % 2 == 0 || pos % 2 == 1 {
chained.parse::<MacHeader>()
.transform(box move |pkt| {
let mut hdr = pkt.get_mut_header();
hdr.swap_addresses();
... | identifier_body | |
nf.rs | use e2d2::common::EmptyMetadata;
use e2d2::headers::*;
use e2d2::operators::*;
#[inline]
pub fn chain_nf<T:'static + Batch<Header = NullHeader, Metadata = EmptyMetadata>>(parent: T) -> CompositionBatch {
parent.parse::<MacHeader>()
.transform(box move |pkt| {
let mut hdr = pkt.get_mut_header();
... | .transform(box move |pkt| {
let mut hdr = pkt.get_mut_header();
hdr.swap_addresses();
})
.compose()
} else {
chained
}
} | for _ in 1..len {
chained = chain_nf(chained);
}
if len % 2 == 0 || pos % 2 == 1 {
chained.parse::<MacHeader>() | random_line_split |
nf.rs | use e2d2::common::EmptyMetadata;
use e2d2::headers::*;
use e2d2::operators::*;
#[inline]
pub fn chain_nf<T:'static + Batch<Header = NullHeader, Metadata = EmptyMetadata>>(parent: T) -> CompositionBatch {
parent.parse::<MacHeader>()
.transform(box move |pkt| {
let mut hdr = pkt.get_mut_header();
... | else {
chained
}
}
| {
chained.parse::<MacHeader>()
.transform(box move |pkt| {
let mut hdr = pkt.get_mut_header();
hdr.swap_addresses();
})
.compose()
} | conditional_block |
toc.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 ... | }
/// Collapse the chain until the first heading more important than
/// `level` (i.e., lower level)
///
/// Example:
///
/// ```text
/// ## A
/// # B
/// # C
/// ## D
/// ## E
/// ### F
/// #### G
/// ### H
/// ```
///
/// If we are considering H... | random_line_split | |
toc.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, level: u32) {
let mut this = None;
loop {
match self.chain.pop() {
Some(mut next) => {
this.map(|e| next.children.entries.push(e));
if next.level < level {
// this is the parent we want, so return it ... | fold_until | identifier_name |
manifest.rs | prelude_items.len(), 0);
let content = strip_hashbang(content);
let (manifest, source) = find_embedded_manifest(content)
.unwrap_or((Manifest::Toml(""), content));
(manifest, source, consts::FILE_TEMPLATE, false)
},
Input::Expr(content) => {
... | : &str, n: usize) -> Result<()> {
if!s.chars().take(n).all(|c| c =='') {
return Err(format!("leading {:?} chars aren't all spaces: {:?}", n, s).into())
}
Ok(())
}
fn extract_block(s: &str) -> Result<String> {
/*
On every line:
- update nesting level ... | leading_spaces(s | identifier_name |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.