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 |
|---|---|---|---|---|
graph_map.rs | use typed_map::TypedMemoryMap;
pub struct GraphMMap {
nodes: TypedMemoryMap<u64>,
edges: TypedMemoryMap<u32>,
}
impl GraphMMap {
#[inline(always)]
pub fn nodes(&self) -> usize { self.nodes[..].len() }
#[inline(always)]
pub fn | (&self, node: usize) -> &[u32] {
let nodes = &self.nodes[..];
if node + 1 < nodes.len() {
let start = nodes[node] as usize;
let limit = nodes[node+1] as usize;
&self.edges[..][start..limit]
}
else { &[] }
}
pub fn new(prefix: &str) -> GraphMMap... | edges | identifier_name |
graph_map.rs | use typed_map::TypedMemoryMap;
pub struct GraphMMap {
nodes: TypedMemoryMap<u64>,
edges: TypedMemoryMap<u32>,
}
impl GraphMMap {
#[inline(always)]
pub fn nodes(&self) -> usize { self.nodes[..].len() }
#[inline(always)]
pub fn edges(&self, node: usize) -> &[u32] {
let nodes = &self.node... |
else { &[] }
}
pub fn new(prefix: &str) -> GraphMMap {
GraphMMap {
nodes: TypedMemoryMap::new(format!("{}.offsets", prefix)),
edges: TypedMemoryMap::new(format!("{}.targets", prefix)),
}
}
}
| {
let start = nodes[node] as usize;
let limit = nodes[node+1] as usize;
&self.edges[..][start..limit]
} | conditional_block |
TestNativeAtanh.rs | /*
* Copyright (C) 2014 The Android Open Source Project
*
* 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 app... | }
float2 __attribute__((kernel)) testNativeAtanhFloat2Float2(float2 inIn) {
return native_atanh(inIn);
}
float3 __attribute__((kernel)) testNativeAtanhFloat3Float3(float3 inIn) {
return native_atanh(inIn);
}
float4 __attribute__((kernel)) testNativeAtanhFloat4Float4(float4 inIn) {
return native_atanh(inI... | return native_atanh(inIn); | random_line_split |
javascript.rs | // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | });
</script>
"#; | }
el.className = classes.join(' ');
}
} | random_line_split |
zhtta2.rs | None => "",
};
debug!("Requested path: [{}]", path_obj.as_str().expect("error"));
debug!("Requested path: [{}]", path_str);
//maybe spawn new threads here to deal with each request
... | main | identifier_name | |
zhtta2.rs | .com/mozilla/rust/issues/12139)
peer_name: String,
path: Path,
size: u64,
}
//need to make it a min heap
impl PartialEq for HTTP_Request {
fn eq(&self, other: &Self) -> bool{
other.size == self.size
}
}
impl Eq for HTTP_Request {}
impl PartialOrd for HTTP_Request {
fn partial_cmp(&self, ... | let req_group: Vec<&str> = request_str.splitn(3,'').collect();
if req_group.len() > 2 {
let path_str = ".".to_string() + req_group[1];
let mut path_obj = os::getcwd().unwrap();
path_obj.push(path_str.clone())... | let request_str = match str::from_utf8(&buf){
Ok(s) => s,
Err(e)=> panic!("Error reading from the listener stream! {}", e),
};
debug!("Request:\n{}", request_str); | random_line_split |
zhtta2.rs | /issues/12139)
peer_name: String,
path: Path,
size: u64,
}
//need to make it a min heap
impl PartialEq for HTTP_Request {
fn eq(&self, other: &Self) -> bool{
other.size == self.size
}
}
impl Eq for HTTP_Request {}
impl PartialOrd for HTTP_Request {
fn partial_cmp(&self, other: &Self) -> ... | let notify_chan = notify_tx.clone();
let stream_map_arc = stream_map_arc.clone();
// Spawn a task to handle the connection.
Thread::spawn(move|| {
//println!("visitor count is {}", local_count);
let request_queue_arc = ... | {
let addr = String::from_str(format!("{}:{}", self.ip, self.port).as_slice());
let www_dir_path_str = self.www_dir_path.clone();
let request_queue_arc = self.request_queue_arc.clone(); //tasks to schedule- want it to be a priority queue if static file, put in request queue and handles it s... | identifier_body |
saturating_square.rs | use malachite_base::num::basic::integers::PrimitiveInt; | use malachite_base_test_util::generators::{signed_gen, unsigned_gen};
#[test]
fn test_saturating_square() {
fn test<T: PrimitiveInt>(x: T, out: T) {
assert_eq!(x.saturating_square(), out);
let mut x = x;
x.saturating_square_assign();
assert_eq!(x, out);
}
test::<u8>(0, 0);
... | use malachite_base::num::basic::signeds::PrimitiveSigned;
use malachite_base::num::basic::unsigneds::PrimitiveUnsigned; | random_line_split |
saturating_square.rs | use malachite_base::num::basic::integers::PrimitiveInt;
use malachite_base::num::basic::signeds::PrimitiveSigned;
use malachite_base::num::basic::unsigneds::PrimitiveUnsigned;
use malachite_base_test_util::generators::{signed_gen, unsigned_gen};
#[test]
fn test_saturating_square() {
fn test<T: PrimitiveInt>(x: T, ... |
#[test]
fn saturating_square_properties() {
apply_fn_to_unsigneds!(saturating_square_properties_helper_unsigned);
apply_fn_to_signeds!(saturating_square_properties_helper_signed);
}
| {
signed_gen::<T>().test_properties(|x| {
let mut square = x;
square.saturating_square_assign();
assert_eq!(square, x.saturating_square());
assert_eq!(square, x.saturating_pow(2));
if square > T::MIN && square < T::MAX {
assert_eq!(square, x.square());
}
... | identifier_body |
saturating_square.rs | use malachite_base::num::basic::integers::PrimitiveInt;
use malachite_base::num::basic::signeds::PrimitiveSigned;
use malachite_base::num::basic::unsigneds::PrimitiveUnsigned;
use malachite_base_test_util::generators::{signed_gen, unsigned_gen};
#[test]
fn test_saturating_square() {
fn test<T: PrimitiveInt>(x: T, ... |
});
}
fn saturating_square_properties_helper_signed<T: PrimitiveSigned>() {
signed_gen::<T>().test_properties(|x| {
let mut square = x;
square.saturating_square_assign();
assert_eq!(square, x.saturating_square());
assert_eq!(square, x.saturating_pow(2));
if square > T::... | {
assert_eq!(square, x.square());
} | conditional_block |
saturating_square.rs | use malachite_base::num::basic::integers::PrimitiveInt;
use malachite_base::num::basic::signeds::PrimitiveSigned;
use malachite_base::num::basic::unsigneds::PrimitiveUnsigned;
use malachite_base_test_util::generators::{signed_gen, unsigned_gen};
#[test]
fn test_saturating_square() {
fn test<T: PrimitiveInt>(x: T, ... | () {
apply_fn_to_unsigneds!(saturating_square_properties_helper_unsigned);
apply_fn_to_signeds!(saturating_square_properties_helper_signed);
}
| saturating_square_properties | identifier_name |
program.rs | use num_bigint::BigInt;
use std::rc::Rc;
use std::ops::Range;
use std::collections::HashMap;
use label::Label;
pub use ::Program;
#[derive(Debug, Clone)]
pub struct SourceLoc {
pub line: usize,
pub column: usize, | #[derive(Debug, Clone)]
pub enum Command {
Push {value: Integer},
PushBig {value: BigInteger},
Duplicate,
Copy {index: usize},
Swap,
Discard,
Slide {amount: usize},
Add,
Subtract,
Multiply,
Divide,
Modulo,
Set,
Get,
Label,
Call {index: usize},
Jump {in... | pub span: Range<usize>,
pub label: Option<Rc<Label>>
}
| random_line_split |
program.rs | use num_bigint::BigInt;
use std::rc::Rc;
use std::ops::Range;
use std::collections::HashMap;
use label::Label;
pub use ::Program;
#[derive(Debug, Clone)]
pub struct SourceLoc {
pub line: usize,
pub column: usize,
pub span: Range<usize>,
pub label: Option<Rc<Label>>
}
#[derive(Debug, Clone)]
pub enu... | }
// turn the map into a list of (index, times_used) that is sorted by times_used
let mut label_count: Vec<_> = label_count.into_iter().collect();
label_count.sort_by_key(|&(_, w)| w);
// create an allocator that produces unique labels, starting from the smallest possible label... | {
// get the source locs, otherwise, invent some new sourcelocs.
let locs = if let Some(ref mut locs) = self.locs {
locs
} else {
self.locs = Some(self.commands.iter().map(|_| SourceLoc {line: 0, column: 0, span: 0..0, label: None}).collect());
self.locs.as_mu... | identifier_body |
program.rs | use num_bigint::BigInt;
use std::rc::Rc;
use std::ops::Range;
use std::collections::HashMap;
use label::Label;
pub use ::Program;
#[derive(Debug, Clone)]
pub struct SourceLoc {
pub line: usize,
pub column: usize,
pub span: Range<usize>,
pub label: Option<Rc<Label>>
}
#[derive(Debug, Clone)]
pub enu... | {
Push {value: Integer},
PushBig {value: BigInteger},
Duplicate,
Copy {index: usize},
Swap,
Discard,
Slide {amount: usize},
Add,
Subtract,
Multiply,
Divide,
Modulo,
Set,
Get,
Label,
Call {index: usize},
Jump {index: usize},
JumpIfZero {index: usiz... | Command | identifier_name |
bios.rs | /* SPDX-License-Identifier: GPL-2.0-only */
use crate::consts::x86::*;
use crate::utils::round_up_4k;
use crate::MachVMBlock;
use std::mem::size_of;
use std::num::Wrapping;
// https://uefi.org/sites/default/files/resources/ACPI_6_3_May16.pdf
// Table 5-27 RSDP Structure
#[repr(packed)]
#[derive(Default)]
pub struct A... | pub length: u8,
}
#[repr(packed)]
#[derive(Default)]
pub struct AcpiMadtLocalApic {
pub header: AcpiSubtableHader,
pub processor_id: u8, /* ACPI processor id */
pub id: u8, /* Processor's local APIC id */
pub lapic_flags: u32,
}
#[repr(packed)]
#[derive(Default)]
pub struct AcpiMadtIoApi... | pub struct AcpiSubtableHader {
pub r#type: u8, | random_line_split |
bios.rs | /* SPDX-License-Identifier: GPL-2.0-only */
use crate::consts::x86::*;
use crate::utils::round_up_4k;
use crate::MachVMBlock;
use std::mem::size_of;
use std::num::Wrapping;
// https://uefi.org/sites/default/files/resources/ACPI_6_3_May16.pdf
// Table 5-27 RSDP Structure
#[repr(packed)]
#[derive(Default)]
pub struct A... | (data: &[u8]) -> u8 {
data.iter().map(|x| Wrapping(*x)).sum::<Wrapping<u8>>().0
}
const SIG_RSDP: [u8; 8] = *b"RSD PTR ";
const SIG_XSDT: [u8; 4] = *b"XSDT";
const SIG_FADT: [u8; 4] = *b"FACP";
const SIG_MADT: [u8; 4] = *b"APIC";
const MADT_LOCAL_APIC: u8 = 0;
const MADT_IO_APIC: u8 = 1;
const MADT_LOCAL_X2APIC: ... | acpi_tb_checksum | identifier_name |
performance.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::PerformanceBinding;
use dom::bindings::codegen::Bindings::PerformanceBinding... | {
reflector_: Reflector,
timing: JS<PerformanceTiming>,
}
impl Performance {
fn new_inherited(window: JSRef<Window>,
navigation_start: u64,
navigation_start_precise: f64) -> Performance {
Performance {
reflector_: Reflector::new(),
... | Performance | identifier_name |
performance.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::PerformanceBinding;
use dom::bindings::codegen::Bindings::PerformanceBinding... | navigation_start: u64,
navigation_start_precise: f64) -> Performance {
Performance {
reflector_: Reflector::new(),
timing: JS::from_rooted(PerformanceTiming::new(window,
navigation_start,... | impl Performance {
fn new_inherited(window: JSRef<Window>, | random_line_split |
performance.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::PerformanceBinding;
use dom::bindings::codegen::Bindings::PerformanceBinding... |
}
impl<'a> PerformanceMethods for JSRef<'a, Performance> {
fn Timing(self) -> Temporary<PerformanceTiming> {
Temporary::new(self.timing.clone())
}
// https://dvcs.w3.org/hg/webperf/raw-file/tip/specs/HighResolutionTime/Overview.html#dom-performance-now
fn Now(self) -> DOMHighResTimeStamp {
... | {
reflect_dom_object(box Performance::new_inherited(window,
navigation_start,
navigation_start_precise),
GlobalRef::Window(window),
Performanc... | identifier_body |
deque.rs | the comment on `swap_buffer`
// FIXME: all atomic operations in this module use a SeqCst ordering. That is
// probably overkill
use core::prelude::*;
use alloc::arc::Arc;
use alloc::heap::{allocate, deallocate};
use alloc::owned::Box;
use collections::Vec;
use core::kinds::marker;
use core::mem::{forget, min_a... |
/// Pops data off the front of the work queue, returning `None` on an empty
/// queue.
pub fn pop(&self) -> Option<T> {
unsafe { self.deque.pop() }
}
/// Gets access to the buffer pool that this worker is attached to. This can
/// be used to create more deques which share the same buff... | {
unsafe { self.deque.push(t) }
} | identifier_body |
deque.rs | the comment on `swap_buffer`
// FIXME: all atomic operations in this module use a SeqCst ordering. That is
// probably overkill
use core::prelude::*;
use alloc::arc::Arc;
use alloc::heap::{allocate, deallocate};
use alloc::owned::Box;
use collections::Vec;
use core::kinds::marker;
use core::mem::{forget, min_a... | (&self) -> BufferPool<T> { BufferPool { pool: self.pool.clone() } }
}
impl<T: Send> Worker<T> {
/// Pushes data onto the front of this work queue.
pub fn push(&self, t: T) {
unsafe { self.deque.push(t) }
}
/// Pops data off the front of the work queue, returning `None` on an empty
/// queue... | clone | identifier_name |
deque.rs | //!
//! // Only the worker may push/pop
//! worker.push(1i);
//! worker.pop();
//!
//! // Stealers take data from the other end of the deque
//! worker.push(1i);
//! stealer.steal();
//!
//! // Stealers can be cloned to have many stealers stealing in parallel
//! worker.push(1i);
//! ... | //! let mut pool = BufferPool::new();
//! let (mut worker, mut stealer) = pool.deque(); | random_line_split | |
mod.rs |
return;
}
let hir_id = tcx.hir().local_def_id_to_hir_id(mir_source.def_id().expect_local());
let is_fn_like = tcx.hir().get(hir_id).fn_kind().is_some();
// Only instrument functions, methods, and closures (not constants since they are evaluated
// at compile time b... | for (target_bcb, target_bcb_data) in self.basic_coverage_blocks.iter_enumerated_mut() {
if let Some(counter_kind) = target_bcb_data.take_counter() {
bcb_counters_without_direct_coverage_spans.push((None, target_bcb, counter_kind));
}
if let Some(edge_counters)... | ) {
let mut bcb_counters_without_direct_coverage_spans = Vec::new(); | random_line_split |
mod.rs | return;
}
let hir_id = tcx.hir().local_def_id_to_hir_id(mir_source.def_id().expect_local());
let is_fn_like = tcx.hir().get(hir_id).fn_kind().is_some();
// Only instrument functions, methods, and closures (not constants since they are evaluated
// at compile time by... | (&self, bcb: BasicCoverageBlock) -> BasicBlock {
self.bcb_data(bcb).last_bb()
}
#[inline]
fn bcb_data(&self, bcb: BasicCoverageBlock) -> &BasicCoverageBlockData {
&self.basic_coverage_blocks[bcb]
}
#[inline]
fn bcb_data_mut(&mut self, bcb: BasicCoverageBlock) -> &mut BasicCover... | bcb_last_bb | identifier_name |
mod.rs | );
let function_source_hash = hash_mir_source(tcx, hir_body);
let basic_coverage_blocks = CoverageGraph::from_mir(mir_body);
Self {
pass_name,
tcx,
mir_body,
source_file,
fn_sig_span,
body_span,
basic_cov... | {
body_span = expn_data.call_site;
} | conditional_block | |
copy-a-resource.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 = foo(10);
let _y = x.clone();
//~^ ERROR does not implement any method in scope
println!("{}", x);
}
| {
foo {
i: i
}
} | identifier_body |
copy-a-resource.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 ... | //~^ ERROR does not implement any method in scope
println!("{}", x);
} |
fn main() {
let x = foo(10);
let _y = x.clone(); | random_line_split |
copy-a-resource.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 ... | {
i: int,
}
impl Drop for foo {
fn drop(&mut self) {}
}
fn foo(i:int) -> foo {
foo {
i: i
}
}
fn main() {
let x = foo(10);
let _y = x.clone();
//~^ ERROR does not implement any method in scope
println!("{}", x);
}
| foo | identifier_name |
sequential.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/. */
//! Implements sequential traversal over the DOM tree.
use dom::{TElement, TNode};
use traversal::{DomTraversalCo... |
fn doit<'a, N, C>(context: &'a C, node: N, data: &mut PerLevelTraversalData)
where N: TNode,
C: DomTraversalContext<N>
{
context.process_preorder(node, data);
if let Some(el) = node.as_element() {
if let Some(ref mut depth) = data.current_dom_depth {
... | debug_assert!(token.should_traverse()); | random_line_split |
sequential.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/. */
//! Implements sequential traversal over the DOM tree.
use dom::{TElement, TNode};
use traversal::{DomTraversalCo... |
}
if C::needs_postorder_traversal() {
context.process_postorder(node);
}
}
let mut data = PerLevelTraversalData {
current_dom_depth: None,
};
let context = C::new(shared, root.as_node().opaque());
if token.traverse_unstyled_children_only() {
fo... | {
*depth -= 1;
} | conditional_block |
sequential.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/. */
//! Implements sequential traversal over the DOM tree.
use dom::{TElement, TNode};
use traversal::{DomTraversalCo... | if C::needs_postorder_traversal() {
context.process_postorder(node);
}
}
let mut data = PerLevelTraversalData {
current_dom_depth: None,
};
let context = C::new(shared, root.as_node().opaque());
if token.traverse_unstyled_children_only() {
for kid in roo... | {
debug_assert!(token.should_traverse());
fn doit<'a, N, C>(context: &'a C, node: N, data: &mut PerLevelTraversalData)
where N: TNode,
C: DomTraversalContext<N>
{
context.process_preorder(node, data);
if let Some(el) = node.as_element() {
if let Some(ref mu... | identifier_body |
sequential.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/. */
//! Implements sequential traversal over the DOM tree.
use dom::{TElement, TNode};
use traversal::{DomTraversalCo... | <'a, N, C>(context: &'a C, node: N, data: &mut PerLevelTraversalData)
where N: TNode,
C: DomTraversalContext<N>
{
context.process_preorder(node, data);
if let Some(el) = node.as_element() {
if let Some(ref mut depth) = data.current_dom_depth {
*depth... | doit | identifier_name |
multicol.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/. */
//! CSS Multi-column layout http://dev.w3.org/csswg/css-multicol/
#![deny(unsafe_code)]
use block::BlockFlow;
us... | (fragment: Fragment, float_kind: Option<FloatKind>) -> MulticolFlow {
MulticolFlow {
block_flow: BlockFlow::from_fragment(fragment, float_kind)
}
}
}
impl Flow for MulticolFlow {
fn class(&self) -> FlowClass {
FlowClass::Multicol
}
fn as_mut_multicol(&mut self) -> &... | from_fragment | identifier_name |
multicol.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/. */
//! CSS Multi-column layout http://dev.w3.org/csswg/css-multicol/
#![deny(unsafe_code)]
use block::BlockFlow;
us... | } | random_line_split | |
multicol.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/. */
//! CSS Multi-column layout http://dev.w3.org/csswg/css-multicol/
#![deny(unsafe_code)]
use block::BlockFlow;
us... |
fn generated_containing_block_size(&self, flow: OpaqueFlow) -> LogicalSize<Au> {
self.block_flow.generated_containing_block_size(flow)
}
fn iterate_through_fragment_border_boxes(&self,
iterator: &mut FragmentBorderBoxIterator,
... | {
self.block_flow.compute_overflow()
} | identifier_body |
rational_impl.rs | //! # Licensing
//! This Source Code is subject to the terms of the Mozilla Public License
//! version 2.0 (the "License"). You can obtain a copy of the License at
//! [http://mozilla.org/MPL/2.0/](http://mozilla.org/MPL/2.0/).
use num_rational::Ratio;
use num_integer::Integer;
use num_traits::identities::Zero;
use Ne... |
fn eq(&self, other: &Ratio<A>, eps: &Ratio<A>) -> bool {
let diff = if *self > *other {
self.clone() - other.clone()
} else {
other.clone() - self.clone()
};
if *self == *other {
true
} else {
diff < *eps
}
}
}
| {
Ratio::zero()
} | identifier_body |
rational_impl.rs | //! # Licensing
//! This Source Code is subject to the terms of the Mozilla Public License
//! version 2.0 (the "License"). You can obtain a copy of the License at
//! [http://mozilla.org/MPL/2.0/](http://mozilla.org/MPL/2.0/).
use num_rational::Ratio;
use num_integer::Integer;
use num_traits::identities::Zero;
use Ne... | () -> Ratio<A> {
Ratio::zero()
}
fn eq(&self, other: &Ratio<A>, eps: &Ratio<A>) -> bool {
let diff = if *self > *other {
self.clone() - other.clone()
} else {
other.clone() - self.clone()
};
if *self == *other {
true
} else {
... | eps | identifier_name |
rational_impl.rs | //! # Licensing
//! This Source Code is subject to the terms of the Mozilla Public License
//! version 2.0 (the "License"). You can obtain a copy of the License at
//! [http://mozilla.org/MPL/2.0/](http://mozilla.org/MPL/2.0/).
use num_rational::Ratio;
use num_integer::Integer;
use num_traits::identities::Zero;
use Ne... | else {
diff < *eps
}
}
}
| {
true
} | conditional_block |
rational_impl.rs | //! # Licensing
//! This Source Code is subject to the terms of the Mozilla Public License
//! version 2.0 (the "License"). You can obtain a copy of the License at
//! [http://mozilla.org/MPL/2.0/](http://mozilla.org/MPL/2.0/).
use num_rational::Ratio;
use num_integer::Integer;
use num_traits::identities::Zero;
use Ne... | fn eq(&self, other: &Ratio<A>, eps: &Ratio<A>) -> bool {
let diff = if *self > *other {
self.clone() - other.clone()
} else {
other.clone() - self.clone()
};
if *self == *other {
true
} else {
diff < *eps
}
}
} | impl<A: Integer + Clone> NearlyEq<Ratio<A>, Ratio<A>> for Ratio<A> {
fn eps() -> Ratio<A> {
Ratio::zero()
}
| random_line_split |
mu_lambda.rs | use std::sync::mpsc::{Sender, Receiver};
use std::sync::{mpsc, Arc};
use rand::{Rng, thread_rng};
use threadpool::{ThreadPool};
use chapter2::evaluation::{EvaluationFn};
use chapter2::genotype::{Genotype};
use chapter2::statistics::{Statistic};
use util::util::{shuffle};
pub struct MuLambda<G: Genotype> {
threads... | let (tx, rx): (Sender<(G, Statistic)>, Receiver<(G, Statistic)>) = mpsc::channel();
for &(ref adult, _) in primer.iter() {
let individual = adult.clone();
let sender = tx.clone();
let fns = self.evaluations.clone();
pool.execute(move || {
l... | // calculate the fitness for each individual (in a separate thread)
let n = primer.len();
let pool = ThreadPool::new(self.threads); | random_line_split |
mu_lambda.rs | use std::sync::mpsc::{Sender, Receiver};
use std::sync::{mpsc, Arc};
use rand::{Rng, thread_rng};
use threadpool::{ThreadPool};
use chapter2::evaluation::{EvaluationFn};
use chapter2::genotype::{Genotype};
use chapter2::statistics::{Statistic};
use util::util::{shuffle};
pub struct MuLambda<G: Genotype> {
threads... | <R: Rng>(&self, rng: &mut R, primer: &mut [(G, Statistic)], iteration: u32) -> Vec<(G, Statistic)> {
// shuffle the population
shuffle(rng, primer);
// calculate the fitness for each individual (in a separate thread)
let n = primer.len();
let pool = ThreadPool::new(self.threads);... | iterate | identifier_name |
test_index.rs | // // #![feature(hashmap_hasher)]
//
// extern crate rand;
// extern crate time;
// extern crate getopts;
// extern crate timely;
// extern crate graph_map;
// extern crate differential_dataflow;
//
// // use std::collections::HashMap;
// // use std::collections::hash_state::DefaultState;
// use std::hash::{Hash, SipHa... | // }
//
// // // vec.sort_by(|x,y| (x.0 & ((1 << (log_size + 1)) - 1)).cmp(&(y.0 & ((1 << (log_size + 1)) - 1))));
// // let start = time::precise_time_ns();
// // for i in vec.iter() {
// // assert!(hash.get(&i.1).is_none());
// // }
// ... | // vec.push((hash_me(&key), key)); | random_line_split |
messages.rs | use byteorder::{WriteBytesExt, LittleEndian};
use frame::FrameOfData;
use model;
use sender::Sender;
use std::ffi::CString;
use super::NatNetMsgType;
/// Enumeration of possible responses from `NatNet`
#[derive(Clone, Debug, PartialEq)]
pub enum NatNetResponse {
/// Response to ping request
///
/// The pin... | }
}
}
bytes
}
} | bytes.extend_from_slice(str_data); | random_line_split |
messages.rs | use byteorder::{WriteBytesExt, LittleEndian};
use frame::FrameOfData;
use model;
use sender::Sender;
use std::ffi::CString;
use super::NatNetMsgType;
/// Enumeration of possible responses from `NatNet`
#[derive(Clone, Debug, PartialEq)]
pub enum NatNetResponse {
/// Response to ping request
///
/// The pin... |
}
}
bytes
}
}
| {
bytes.write_u16::<LittleEndian>(str_data.len() as u16).unwrap();
bytes.extend_from_slice(str_data);
} | conditional_block |
messages.rs | use byteorder::{WriteBytesExt, LittleEndian};
use frame::FrameOfData;
use model;
use sender::Sender;
use std::ffi::CString;
use super::NatNetMsgType;
/// Enumeration of possible responses from `NatNet`
#[derive(Clone, Debug, PartialEq)]
pub enum NatNetResponse {
/// Response to ping request
///
/// The pin... | {
/// Send ping to other application
///
/// This should result in a `NatNetResponse::Ping`
Ping(CString),
/// Request model definitions
ModelDefinitions,
/// Request a frame of data
FrameOfData,
}
impl Into<Vec<u8>> for NatNetRequest {
fn into(self) -> Vec<u8> {
// Pre-all... | NatNetRequest | identifier_name |
interning.rs | // Copyright 2018 Pants project contributors (see CONTRIBUTORS.md).
// Licensed under the Apache License, Version 2.0 (see LICENSE).
use std::collections::HashMap;
use std::hash;
use std::sync::atomic;
use cpython::{ObjectProtocol, PyErr, PyType, Python, ToPyObject};
use parking_lot::{Mutex, RwLock};
use crate::core... | }
struct InternKey(isize, Value);
impl Eq for InternKey {}
impl PartialEq for InternKey {
fn eq(&self, other: &InternKey) -> bool {
externs::equals(&self.1, &other.1)
}
}
impl hash::Hash for InternKey {
fn hash<H: hash::Hasher>(&self, state: &mut H) {
self.0.hash(state);
}
}
struct InternType(isize... | .cloned()
.unwrap_or_else(|| panic!("Previously memoized object disappeared for {:?}", k))
} | random_line_split |
interning.rs | // Copyright 2018 Pants project contributors (see CONTRIBUTORS.md).
// Licensed under the Apache License, Version 2.0 (see LICENSE).
use std::collections::HashMap;
use std::hash;
use std::sync::atomic;
use cpython::{ObjectProtocol, PyErr, PyType, Python, ToPyObject};
use parking_lot::{Mutex, RwLock};
use crate::core... |
}
impl hash::Hash for InternType {
fn hash<H: hash::Hasher>(&self, state: &mut H) {
self.0.hash(state);
}
}
| {
self.1 == other.1
} | identifier_body |
interning.rs | // Copyright 2018 Pants project contributors (see CONTRIBUTORS.md).
// Licensed under the Apache License, Version 2.0 (see LICENSE).
use std::collections::HashMap;
use std::hash;
use std::sync::atomic;
use cpython::{ObjectProtocol, PyErr, PyType, Python, ToPyObject};
use parking_lot::{Mutex, RwLock};
use crate::core... | (&self, k: &Key) -> Value {
// NB: We do not need to acquire+release the GIL before getting a Value for a Key, because
// neither `Key::eq` nor `Value::clone` acquire the GIL.
self
.reverse_keys
.read()
.get(&k)
.cloned()
.unwrap_or_else(|| panic!("Previously memoized object disappe... | key_get | identifier_name |
interning.rs | // Copyright 2018 Pants project contributors (see CONTRIBUTORS.md).
// Licensed under the Apache License, Version 2.0 (see LICENSE).
use std::collections::HashMap;
use std::hash;
use std::sync::atomic;
use cpython::{ObjectProtocol, PyErr, PyType, Python, ToPyObject};
use parking_lot::{Mutex, RwLock};
use crate::core... |
};
if key_was_new {
self.reverse_keys.write().insert(key, v);
}
Ok(key)
})
}
pub fn key_get(&self, k: &Key) -> Value {
// NB: We do not need to acquire+release the GIL before getting a Value for a Key, because
// neither `Key::eq` nor `Value::clone` acquire the GIL.
... | {
let id = self.id_generator.fetch_add(1, atomic::Ordering::SeqCst);
let key = Key::new(id, type_id);
forward_keys.insert(intern_key, key);
(key, true)
} | conditional_block |
mod.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/. */
//! The implementation of the DOM.
//!
//! The DOM is comprised of interfaces (defined by specifications using
//!... | pub mod textencoder;
pub mod touch;
pub mod touchevent;
pub mod touchlist;
pub mod transitionevent;
pub mod treewalker;
pub mod uievent;
pub mod url;
pub mod urlhelper;
pub mod urlsearchparams;
pub mod userscripts;
pub mod validation;
pub mod validitystate;
pub mod values;
pub mod virtualmethods;
pub mod vr;
pub mod vr... | pub mod testworkletglobalscope;
pub mod text;
pub mod textdecoder; | random_line_split |
largest-series-product.rs | use largest_series_product::*;
#[test]
fn return_is_a_result() {
assert!(lsp("29", 2).is_ok());
}
#[test]
#[ignore]
fn find_the_largest_product_when_span_equals_length() {
assert_eq!(Ok(18), lsp("29", 2));
}
#[test]
#[ignore]
fn find_the_largest_product_of_two_with_numbers_in_order() {
assert_eq!(Ok(72),... | () {
assert_eq!(Ok(1), lsp("123", 0));
}
#[test]
#[ignore]
fn empty_string_and_non_zero_span_is_an_error() {
assert_eq!(Err(Error::SpanTooLong), lsp("", 1));
}
#[test]
#[ignore]
fn a_string_with_non_digits_is_an_error() {
assert_eq!(Err(Error::InvalidDigit('a')), lsp("1234a5", 2));
}
| a_non_empty_string_and_no_span_returns_one | identifier_name |
largest-series-product.rs | use largest_series_product::*;
#[test]
fn return_is_a_result() {
assert!(lsp("29", 2).is_ok());
}
#[test]
#[ignore]
fn find_the_largest_product_when_span_equals_length() {
assert_eq!(Ok(18), lsp("29", 2));
}
#[test]
#[ignore]
fn find_the_largest_product_of_two_with_numbers_in_order() {
assert_eq!(Ok(72),... |
#[test]
#[ignore]
fn find_the_largest_product_of_five_with_numbers_in_order() {
assert_eq!(Ok(15_120), lsp("0123456789", 5));
}
#[test]
#[ignore]
fn span_of_six_in_a_large_number() {
assert_eq!(
Ok(23_520),
lsp("73167176531330624919225119674426574742355349194934", 6)
);
}
#[test]
#[ignore... | fn find_the_largest_product_of_three_with_numbers_not_in_order() {
assert_eq!(Ok(270), lsp("1027839564", 3));
} | random_line_split |
largest-series-product.rs | use largest_series_product::*;
#[test]
fn return_is_a_result() {
assert!(lsp("29", 2).is_ok());
}
#[test]
#[ignore]
fn find_the_largest_product_when_span_equals_length() {
assert_eq!(Ok(18), lsp("29", 2));
}
#[test]
#[ignore]
fn find_the_largest_product_of_two_with_numbers_in_order() {
assert_eq!(Ok(72),... |
#[test]
#[ignore]
fn empty_string_and_non_zero_span_is_an_error() {
assert_eq!(Err(Error::SpanTooLong), lsp("", 1));
}
#[test]
#[ignore]
fn a_string_with_non_digits_is_an_error() {
assert_eq!(Err(Error::InvalidDigit('a')), lsp("1234a5", 2));
}
| {
assert_eq!(Ok(1), lsp("123", 0));
} | identifier_body |
conf.rs | use configuration::{ self, BitflagU32, VecStringPath };
use toml;
use std;
use levels as levelss;
use graphics::{ Color, Layer };
pub type VecVecStringPath = Vec<VecStringPath>;
pub type Dimension = [u32;2];
pub type Array4F32 = [f32;4];
pub type Array4F64 = [f64;4];
pub type VecF32 = Vec<f32>;
pub type VecU8 = Vec<u... | (conf: &Config) -> Result<(),String> {
if conf.keys.up.len() == 0
|| conf.keys.down.len() == 0
|| conf.keys.left.len() == 0
|| conf.keys.right.len() == 0 {
return Err("ERROR: configuration file invalid: keys mustn't be empty".into());
}
// assert persistent snd and static sn... | config_constraint | identifier_name |
conf.rs | use configuration::{ self, BitflagU32, VecStringPath };
use toml;
use std;
use levels as levelss;
use graphics::{ Color, Layer };
pub type VecVecStringPath = Vec<VecStringPath>;
pub type Dimension = [u32;2];
pub type Array4F32 = [f32;4];
pub type Array4F64 = [f64;4];
pub type VecF32 = Vec<f32>;
pub type VecU8 = Vec<u... |
configure!(
file = "config.toml";
debug_file = "config.toml";
save_file = "save.toml";
constraint = config_constraint;
general: {
number_of_thread: t usize,
persistent_snd_cooldown: t usize,
difficulty: t f32 save difficulty,
},
keys: {
up: t VecU8,
... | {
if conf.keys.up.len() == 0
|| conf.keys.down.len() == 0
|| conf.keys.left.len() == 0
|| conf.keys.right.len() == 0 {
return Err("ERROR: configuration file invalid: keys mustn't be empty".into());
}
// assert persistent snd and static snd doesn't overlap
if conf.entitie... | identifier_body |
conf.rs | use configuration::{ self, BitflagU32, VecStringPath };
use toml;
use std;
use levels as levelss;
use graphics::{ Color, Layer };
pub type VecVecStringPath = Vec<VecStringPath>;
pub type Dimension = [u32;2];
pub type Array4F32 = [f32;4];
pub type Array4F64 = [f64;4];
pub type VecF32 = Vec<f32>;
pub type VecU8 = Vec<u... |
// assert persistent snd and static snd doesn't overlap
if conf.entities.monster_persistent_snd == conf.entities.laser_persistent_snd {
return Err("ERROR: configuration file invalid: monster_persistent_snd and laser_persistent_snd must be different".into());
}
Ok(())
}
configure!(
file =... | {
return Err("ERROR: configuration file invalid: keys mustn't be empty".into());
} | conditional_block |
conf.rs | use configuration::{ self, BitflagU32, VecStringPath };
use toml;
use std;
use levels as levelss;
use graphics::{ Color, Layer };
pub type VecVecStringPath = Vec<VecStringPath>;
pub type Dimension = [u32;2];
pub type Array4F32 = [f32;4];
pub type Array4F64 = [f64;4];
pub type VecF32 = Vec<f32>;
pub type VecU8 = Vec<u... | ball_radius: t f32,
ball_velocity: t f32,
ball_time: t f32,
ball_weight: t f32,
ball_color: t Color,
ball_layer: t Layer,
ball_vel_snd_coef: t f32,
ball_vel_snd: t usize,
laser_group: t BitflagU32,
laser_mask: t BitflagU32,
laser_k... | ball_mask: t BitflagU32,
ball_killer_mask: t BitflagU32,
ball_kill_snd: t usize,
ball_die_snd: t usize, | random_line_split |
shootout-binarytrees.rs | // The Computer Language Benchmarks Game
// http://benchmarksgame.alioth.debian.org/
//
// contributed by the Rust Project Developers
// Copyright (c) 2012-2014 The Rust Project Developers
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted... | (depth: i32, iterations: i32) -> String {
let mut chk = 0;
for i in 1.. iterations + 1 {
let arena = TypedArena::new();
let a = bottom_up_tree(&arena, i, depth);
let b = bottom_up_tree(&arena, -i, depth);
chk += item_check(&a) + item_check(&b);
}
format!("{}\t trees of de... | inner | identifier_name |
shootout-binarytrees.rs | // The Computer Language Benchmarks Game
// http://benchmarksgame.alioth.debian.org/
//
// contributed by the Rust Project Developers
// Copyright (c) 2012-2014 The Rust Project Developers
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted... |
let long_lived_arena = TypedArena::new();
let long_lived_tree = bottom_up_tree(&long_lived_arena, 0, max_depth);
let messages = (min_depth..max_depth + 1).step_by(2).map(|depth| {
let iterations = 2i32.pow((max_depth - depth + min_depth) as u32);
thread::spawn(move || inner(depth, iteratio... | {
let mut args = std::env::args();
let n = if std::env::var_os("RUST_BENCH").is_some() {
17
} else if args.len() <= 1 {
8
} else {
args.nth(1).unwrap().parse().unwrap()
};
let min_depth = 4;
let max_depth = if min_depth + 2 > n {min_depth + 2} else {n};
{
... | identifier_body |
shootout-binarytrees.rs | // The Computer Language Benchmarks Game
// http://benchmarksgame.alioth.debian.org/
//
// contributed by the Rust Project Developers
// Copyright (c) 2012-2014 The Rust Project Developers
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted... | fn main() {
let mut args = std::env::args();
let n = if std::env::var_os("RUST_BENCH").is_some() {
17
} else if args.len() <= 1 {
8
} else {
args.nth(1).unwrap().parse().unwrap()
};
let min_depth = 4;
let max_depth = if min_depth + 2 > n {min_depth + 2} else {n};
... | iterations * 2, depth, chk)
}
| random_line_split |
shootout-binarytrees.rs | // The Computer Language Benchmarks Game
// http://benchmarksgame.alioth.debian.org/
//
// contributed by the Rust Project Developers
// Copyright (c) 2012-2014 The Rust Project Developers
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted... | else {n};
{
let arena = TypedArena::new();
let depth = max_depth + 1;
let tree = bottom_up_tree(&arena, 0, depth);
println!("stretch tree of depth {}\t check: {}",
depth, item_check(&tree));
}
let long_lived_arena = TypedArena::new();
let long_lived_t... | {min_depth + 2} | conditional_block |
client.rs | use std::io;
use std::sync::Arc;
use std::time::Duration;
use futures::{future, Future};
use futures_cpupool::CpuPool;
use num_cpus;
use tokio_core::net::TcpStream;
use tokio_core::reactor::Core;
use tokio_middleware::Timeout;
use tokio_proto::multiplex::ClientService;
use tokio_proto::TcpClient;
use tokio_service::S... | (
address: String,
timeout: Duration,
) -> impl Future<Item = Client, Error = io::Error> {
CONNECTING_POOL.spawn_fn(move || Client::connect_with_timeout(&address, timeout))
}
pub fn connect_async(address: String) -> impl Future<Item = Client, Error = io::Error> {
CONNECTING_P... | connect_with_timeout_async | identifier_name |
client.rs | use std::io;
use std::sync::Arc;
use std::time::Duration;
use futures::{future, Future};
use futures_cpupool::CpuPool;
use num_cpus;
use tokio_core::net::TcpStream;
use tokio_core::reactor::Core;
use tokio_middleware::Timeout;
use tokio_proto::multiplex::ClientService;
use tokio_proto::TcpClient;
use tokio_service::S... |
pub fn send_async(&self, msg: Vec<u8>) -> Box<ResFuture> {
if let Some(ref client) = self.client {
box client.call(msg)
} else {
shortcut::call(self.server_id, msg)
}
}
}
unsafe impl Send for Client {}
| {
CONNECTING_POOL
.spawn_fn(move || Client::connect_with_timeout(&address, Duration::from_secs(5)))
} | identifier_body |
client.rs | use std::io;
use std::sync::Arc;
use std::time::Duration;
use futures::{future, Future};
use futures_cpupool::CpuPool;
use num_cpus;
use tokio_core::net::TcpStream;
use tokio_core::reactor::Core;
use tokio_middleware::Timeout;
use tokio_proto::multiplex::ClientService;
use tokio_proto::TcpClient;
use tokio_service::S... | if!DISABLE_SHORTCUT && shortcut::is_local(server_id) {
None
} else {
if address.eq(&STANDALONE_ADDRESS) {
return Err(io::Error::new(
io::ErrorKind::Other,
"STANDALONE server is not found",
... | let server_id = hash_str(address);
let client = { | random_line_split |
client.rs | use std::io;
use std::sync::Arc;
use std::time::Duration;
use futures::{future, Future};
use futures_cpupool::CpuPool;
use num_cpus;
use tokio_core::net::TcpStream;
use tokio_core::reactor::Core;
use tokio_middleware::Timeout;
use tokio_proto::multiplex::ClientService;
use tokio_proto::TcpClient;
use tokio_service::S... |
};
Ok(Client { client, server_id })
}
pub fn connect(address: &String) -> io::Result<Client> {
Client::connect_with_timeout(address, Duration::from_secs(5))
}
pub fn connect_with_timeout_async(
address: String,
timeout: Duration,
) -> impl Future<Item = Clien... | {
if address.eq(&STANDALONE_ADDRESS) {
return Err(io::Error::new(
io::ErrorKind::Other,
"STANDALONE server is not found",
));
}
let mut core = Core::new()?;
let socket_... | conditional_block |
inprocess.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::webgl_thread::{WebGLThread, WebGLThreadInit, WebXRBridgeInit};
use canvas_traits::webgl::webgl_channel... |
}
}
| {
// Flush the Sync object into the GPU's command queue to guarantee that it it's signaled.
self.webrender_gl.flush();
// Mark the sync object for deletion.
self.webrender_gl.delete_sync(gl_sync);
} | conditional_block |
inprocess.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::webgl_thread::{WebGLThread, WebGLThreadInit, WebXRBridgeInit};
use canvas_traits::webgl::webgl_channel... | {
pub webgl_threads: WebGLThreads,
pub image_handler: Box<dyn WebrenderExternalImageApi>,
pub output_handler: Option<Box<dyn webrender_api::OutputImageHandler>>,
pub webxr_layer_grand_manager: WebXRLayerGrandManager<WebXRSurfman>,
}
impl WebGLComm {
/// Creates a new `WebGLComm` object.
pub fn... | WebGLComm | identifier_name |
inprocess.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::webgl_thread::{WebGLThread, WebGLThreadInit, WebXRBridgeInit};
use canvas_traits::webgl::webgl_channel... |
fn unlock_swap_chain(&mut self, id: WebGLContextId) -> Option<()> {
let locked_front_buffer = self.locked_front_buffers.remove(&id)?;
let locked_front_buffer = self
.surfman
.destroy_surface_texture(locked_front_buffer)
.unwrap();
debug!("... unlocked chai... | {
debug!("... locking chain {:?}", id);
let front_buffer = self.swap_chains.get(id)?.take_surface()?;
let SurfaceInfo {
id: front_buffer_id,
size,
..
} = self.surfman.surface_info(&front_buffer);
debug!("... getting texture for surface {:?}", ... | identifier_body |
inprocess.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::webgl_thread::{WebGLThread, WebGLThreadInit, WebXRBridgeInit};
use canvas_traits::webgl::webgl_channel... | webxr_init,
};
let output_handler = if pref!(dom.webgl.dom_to_texture.enabled) {
Some(Box::new(OutputHandler::new(webrender_gl.clone())))
} else {
None
};
let external = WebGLExternalImages::new(surfman, webrender_swap_chains);
WebGL... | adapter: surfman.adapter(),
api_type, | random_line_split |
mod.rs | use std::ffi::CStr;
use std::mem;
use std::ptr;
use glutin;
mod gl {
pub use self::Gles2 as Gl;
include!(concat!(env!("OUT_DIR"), "/test_gl_bindings.rs"));
}
pub struct Context {
gl: gl::Gl
}
pub fn | (window: &glutin::Window) -> Context {
let gl = gl::Gl::load_with(|ptr| window.get_proc_address(ptr) as *const _);
let version = unsafe {
let data = CStr::from_ptr(gl.GetString(gl::VERSION) as *const _).to_bytes().to_vec();
String::from_utf8(data).unwrap()
};
println!("OpenGL version {... | load | identifier_name |
mod.rs | use std::ffi::CStr;
use std::mem;
use std::ptr;
use glutin;
mod gl {
pub use self::Gles2 as Gl;
include!(concat!(env!("OUT_DIR"), "/test_gl_bindings.rs"));
}
pub struct Context {
gl: gl::Gl
}
pub fn load(window: &glutin::Window) -> Context | gl.AttachShader(program, vs);
gl.AttachShader(program, fs);
gl.LinkProgram(program);
gl.UseProgram(program);
let mut vb = mem::uninitialized();
gl.GenBuffers(1, &mut vb);
gl.BindBuffer(gl::ARRAY_BUFFER, vb);
gl.BufferData(gl::ARRAY_BUFFER,
... | {
let gl = gl::Gl::load_with(|ptr| window.get_proc_address(ptr) as *const _);
let version = unsafe {
let data = CStr::from_ptr(gl.GetString(gl::VERSION) as *const _).to_bytes().to_vec();
String::from_utf8(data).unwrap()
};
println!("OpenGL version {}", version);
unsafe {
l... | identifier_body |
mod.rs | use std::ffi::CStr;
use std::mem;
use std::ptr;
use glutin;
mod gl {
pub use self::Gles2 as Gl;
include!(concat!(env!("OUT_DIR"), "/test_gl_bindings.rs"));
}
pub struct Context {
gl: gl::Gl
}
pub fn load(window: &glutin::Window) -> Context {
let gl = gl::Gl::load_with(|ptr| window.get_proc_address(pt... |
let pos_attrib = gl.GetAttribLocation(program, b"position\0".as_ptr() as *const _);
let color_attrib = gl.GetAttribLocation(program, b"color\0".as_ptr() as *const _);
gl.VertexAttribPointer(pos_attrib as gl::types::GLuint, 2, gl::FLOAT, 0,
5 * mem::size_of::... | {
let mut vao = mem::uninitialized();
gl.GenVertexArrays(1, &mut vao);
gl.BindVertexArray(vao);
} | conditional_block |
mod.rs | use std::ffi::CStr;
use std::mem;
use std::ptr;
use glutin;
mod gl {
pub use self::Gles2 as Gl;
include!(concat!(env!("OUT_DIR"), "/test_gl_bindings.rs"));
}
pub struct Context {
gl: gl::Gl
}
pub fn load(window: &glutin::Window) -> Context {
let gl = gl::Gl::load_with(|ptr| window.get_proc_address(pt... | 0.5, -0.5, 0.0, 0.0, 1.0
];
const VS_SRC: &'static [u8] = b"
#version 100
precision mediump float;
attribute vec2 position;
attribute vec3 color;
varying vec3 v_color;
void main() {
gl_Position = vec4(position, 0.0, 1.0);
v_color = color;
}
\0";
const FS_SRC: &'static [u8] = b"
#version 100
precision m... | }
static VERTEX_DATA: [f32; 15] = [
-0.5, -0.5, 1.0, 0.0, 0.0,
0.0, 0.5, 0.0, 1.0, 0.0, | random_line_split |
ast_map.rs | _ident_interner;
use parse::token::ident_interner;
use parse::token::special_idents;
use print::pprust;
use visit::{Visitor, fn_kind};
use visit;
use std::hashmap::HashMap;
use std::vec;
#[deriving(Clone, Eq)]
pub enum path_elt {
path_mod(Ident),
path_name(Ident),
// A pretty name can come from an `impl`... | }
_ => fail2!("struct def parent wasn't an item")
}
}
}
}
fn map_expr(&mut self, ex: @Expr) {
self.map.insert(ex.id, node_expr(ex));
// Expressions which are or might be calls:
{
let r = ex.get_call... | p)); | random_line_split |
ast_map.rs | ident_interner;
use parse::token::ident_interner;
use parse::token::special_idents;
use print::pprust;
use visit::{Visitor, fn_kind};
use visit;
use std::hashmap::HashMap;
use std::vec;
#[deriving(Clone, Eq)]
pub enum path_elt {
path_mod(Ident),
path_name(Ident),
// A pretty name can come from an `impl` ... |
fn visit_stmt(&mut self, stmt: @Stmt, _: ()) {
self.map_stmt(stmt)
}
fn visit_fn(&mut self,
function_kind: &fn_kind,
function_declaration: &fn_decl,
block: &Block,
span: Span,
node_id: NodeId,
_: ()) {... | {
self.map_expr(expr)
} | identifier_body |
ast_map.rs | ident_interner;
use parse::token::ident_interner;
use parse::token::special_idents;
use print::pprust;
use visit::{Visitor, fn_kind};
use visit;
use std::hashmap::HashMap;
use std::vec;
#[deriving(Clone, Eq)]
pub enum path_elt {
path_mod(Ident),
path_name(Ident),
// A pretty name can come from an `impl` ... | (pe: path_elt, itr: @ident_interner) -> ~str {
match pe {
path_mod(s) | path_name(s) | path_pretty_name(s, _) => {
itr.get(s.name).to_owned()
}
}
}
pub fn impl_pretty_name(trait_ref: &Option<trait_ref>,
ty: &Ty, default: Ident) -> path_elt {
let itr = get... | path_elt_to_str | identifier_name |
mod.rs | extern crate serde;
extern crate serde_json;
extern crate tera;
use std::io::prelude::*;
use std::fs::File;
use self::tera::Template;
#[derive(Debug)]
pub struct Product {
name: String,
manufacturer: String,
price: i32,
summary: String
}
impl Product {
#[allow(dead_code)]
pub fn new() -> Pro... |
}
// Impl Serialize by hand so tests pass on stable and beta
impl serde::Serialize for Review {
fn serialize<S>(&self, serializer: &mut S) -> Result<(), S::Error>
where S: serde::Serializer
{
let mut state = try!(serializer.serialize_struct("Review", 2));
try!(serializer.serialize_struc... | {
Review {
title: "My review".to_owned(),
paragraphs: vec![
"A".to_owned(), "B".to_owned(), "C".to_owned()
]
}
} | identifier_body |
mod.rs | extern crate serde;
extern crate serde_json;
extern crate tera;
use std::io::prelude::*;
use std::fs::File;
use self::tera::Template;
#[derive(Debug)]
pub struct Product {
name: String,
manufacturer: String,
price: i32,
summary: String
}
impl Product {
#[allow(dead_code)]
pub fn new() -> Pro... | ]
}
}
}
// Impl Serialize by hand so tests pass on stable and beta
impl serde::Serialize for Review {
fn serialize<S>(&self, serializer: &mut S) -> Result<(), S::Error>
where S: serde::Serializer
{
let mut state = try!(serializer.serialize_struct("Review", 2));
tr... | random_line_split | |
mod.rs | extern crate serde;
extern crate serde_json;
extern crate tera;
use std::io::prelude::*;
use std::fs::File;
use self::tera::Template;
#[derive(Debug)]
pub struct Product {
name: String,
manufacturer: String,
price: i32,
summary: String
}
impl Product {
#[allow(dead_code)]
pub fn new() -> Pro... | () -> Review {
Review {
title: "My review".to_owned(),
paragraphs: vec![
"A".to_owned(), "B".to_owned(), "C".to_owned()
]
}
}
}
// Impl Serialize by hand so tests pass on stable and beta
impl serde::Serialize for Review {
fn serialize<S>(&self,... | new | identifier_name |
maybe_owned_vec.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... |
}
impl<'a, T: Clone> Clone for MaybeOwnedVector<'a, T> {
#[allow(deprecated)]
fn clone(&self) -> MaybeOwnedVector<'a, T> {
match *self {
Growable(ref v) => Growable(v.clone()),
Borrowed(v) => Borrowed(v)
}
}
}
impl<'a, T> Default for MaybeOwnedVector<'a, T> {
#... | {
self.as_slice().fmt(f)
} | identifier_body |
maybe_owned_vec.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | }
impl<'a, T: PartialEq> PartialEq for MaybeOwnedVector<'a, T> {
fn eq(&self, other: &MaybeOwnedVector<T>) -> bool {
self.as_slice() == other.as_slice()
}
}
impl<'a, T: Eq> Eq for MaybeOwnedVector<'a, T> {}
impl<'a, T: PartialOrd> PartialOrd for MaybeOwnedVector<'a, T> {
fn partial_cmp(&self, oth... | #[allow(deprecated)]
pub fn is_empty(&self) -> bool { self.len() == 0 } | random_line_split |
maybe_owned_vec.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 ... | (&'a self) -> slice::Iter<'a,T> {
match self {
&Growable(ref v) => v.as_slice().iter(),
&Borrowed(ref v) => v.iter(),
}
}
pub fn len(&self) -> uint { self.as_slice().len() }
#[allow(deprecated)]
pub fn is_empty(&self) -> bool { self.len() == 0 }
}
impl<'a, T: P... | iter | identifier_name |
p2d.rs | use super::vector::Vector;
#[derive(Debug, Copy, Clone)]
pub struct P2d(pub f32, pub f32);
impl Vector for P2d {
type Scalar = f32;
fn new() -> Self {
P2d(0.0, 0.0)
}
|
fn reset(&mut self) {
self.0 = 0.0;
self.1 = 0.0;
}
fn scale(&self, factor: f32) -> Self {
P2d(self.0 * factor, self.1 * factor)
}
fn sub(&self, other: &Self) -> Self {
P2d(self.0 - other.0, self.1 - other.1)
}
fn add_scaled(&mut self, factor: f32, other: ... | fn length_squared(&self) -> f32 {
self.0 * self.0 + self.1 * self.1
} | random_line_split |
p2d.rs | use super::vector::Vector;
#[derive(Debug, Copy, Clone)]
pub struct P2d(pub f32, pub f32);
impl Vector for P2d {
type Scalar = f32;
fn new() -> Self {
P2d(0.0, 0.0)
}
fn length_squared(&self) -> f32 {
self.0 * self.0 + self.1 * self.1
}
fn reset(&mut self) {
self.0 =... | (&self, other: &Self) -> Self {
P2d(self.0 - other.0, self.1 - other.1)
}
fn add_scaled(&mut self, factor: f32, other: &P2d) {
self.0 += factor * other.0;
self.1 += factor * other.1;
}
fn clip_within(&self, min: &Self, max: &Self) -> Self {
P2d(if self.0 < min.0 {
... | sub | identifier_name |
p2d.rs | use super::vector::Vector;
#[derive(Debug, Copy, Clone)]
pub struct P2d(pub f32, pub f32);
impl Vector for P2d {
type Scalar = f32;
fn new() -> Self {
P2d(0.0, 0.0)
}
fn length_squared(&self) -> f32 {
self.0 * self.0 + self.1 * self.1
}
fn reset(&mut self) |
fn scale(&self, factor: f32) -> Self {
P2d(self.0 * factor, self.1 * factor)
}
fn sub(&self, other: &Self) -> Self {
P2d(self.0 - other.0, self.1 - other.1)
}
fn add_scaled(&mut self, factor: f32, other: &P2d) {
self.0 += factor * other.0;
self.1 += factor * other... | {
self.0 = 0.0;
self.1 = 0.0;
} | identifier_body |
set_statement.rs | // Copyright 2019 Google LLC
//
// 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 agreed to in ... | #[cfg(test)]
mod tests {
use super::*;
use crate::lexer::Lexer;
use pretty_assertions::assert_eq;
use serde_json::json;
use serde_json::Value;
#[test]
fn parses_set_statement() {
let mut parser = Parser::new(Lexer::new("set paste"));
let program = parser.parse();
ass... | option: option,
value: Some(value),
});
}
| random_line_split |
set_statement.rs | // Copyright 2019 Google LLC
//
// 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 agreed to in ... | (parser: &mut Parser) -> Option<SetStatement> {
let option = parser.expect_identifier()?;
if parser.peek_token().token_type!= TokenType::Assign {
parser.expect_end_of_statement()?;
return Some(SetStatement {
option: option,
value: None,
});
}
parser.advanc... | parse | identifier_name |
set_statement.rs | // Copyright 2019 Google LLC
//
// 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 agreed to in ... |
}
| {
let mut parser = Parser::new(Lexer::new("set selection=exclusive"));
let program = parser.parse();
assert_eq!(parser.errors, &[]);
assert_eq!(
program.dump_for_testing(),
json!([{"set": {"option": "selection", "value": "exclusive"}}])
);
} | identifier_body |
set_statement.rs | // Copyright 2019 Google LLC
//
// 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 agreed to in ... |
parser.advance();
let value = parser.expect_identifier()?;
return Some(SetStatement {
option: option,
value: Some(value),
});
}
#[cfg(test)]
mod tests {
use super::*;
use crate::lexer::Lexer;
use pretty_assertions::assert_eq;
use serde_json::json;
use serde_json::V... | {
parser.expect_end_of_statement()?;
return Some(SetStatement {
option: option,
value: None,
});
} | conditional_block |
main.rs | // Copyright 2015 Virgil Dupras
//
// This software is licensed under the "GPLv3" License as described in the "LICENSE" file,
// which should be included with this package. The terms are also available at
// http://www.gnu.org/licenses/gpl-3.0.html
//
use std::path::Path;
use civng::game::Game;
use civng::unit::{Unit... | () {
let mut game = Game::new(Path::new("resources/pangea-duel.Civ5Map"));
let unitpos = game.map().first_passable(Pos::origin());
let _ = game.add_unit(Unit::new(UnitType::Melee, Player::Me, unitpos));
let unitpos = game.map().first_passable(Pos::origin());
let _ = game.add_unit(Unit::new(UnitType:... | main | identifier_name |
main.rs | // Copyright 2015 Virgil Dupras
//
// This software is licensed under the "GPLv3" License as described in the "LICENSE" file,
// which should be included with this package. The terms are also available at
// http://www.gnu.org/licenses/gpl-3.0.html
//
use std::path::Path;
use civng::game::Game;
use civng::unit::{Unit... | break;
}
}
} | random_line_split | |
main.rs | // Copyright 2015 Virgil Dupras
//
// This software is licensed under the "GPLv3" License as described in the "LICENSE" file,
// which should be included with this package. The terms are also available at
// http://www.gnu.org/licenses/gpl-3.0.html
//
use std::path::Path;
use civng::game::Game;
use civng::unit::{Unit... | {
let mut game = Game::new(Path::new("resources/pangea-duel.Civ5Map"));
let unitpos = game.map().first_passable(Pos::origin());
let _ = game.add_unit(Unit::new(UnitType::Melee, Player::Me, unitpos));
let unitpos = game.map().first_passable(Pos::origin());
let _ = game.add_unit(Unit::new(UnitType::Ra... | identifier_body | |
main.rs | // Copyright 2015 Virgil Dupras
//
// This software is licensed under the "GPLv3" License as described in the "LICENSE" file,
// which should be included with this package. The terms are also available at
// http://www.gnu.org/licenses/gpl-3.0.html
//
use std::path::Path;
use civng::game::Game;
use civng::unit::{Unit... |
}
}
| {
break;
} | conditional_block |
mod.rs | use cursive::{self, views, Cursive};
use cursive::traits::{Boxable, Identifiable};
use fchat::{self, Ticket};
use chrono::{self, Timelike};
use futures::sync::mpsc::UnboundedSender;
use std;
use std::thread::spawn;
use std::sync::mpsc::{channel, Receiver, Sender};
use io;
pub enum Event {
ReceivedMessage(fchat... |
self.siv.step();
}
fn is_running(&self) -> bool {
self.is_running
}
}
pub fn login_dialog(result: Sender<(Ticket, String)>) -> views::Dialog {
use cursive::view::{Boxable, Identifiable};
let username = views::LinearLayout::horizontal()
.child(views::TextView::new("Username"... | {
self.state = state;
} | conditional_block |
mod.rs | use cursive::{self, views, Cursive};
use cursive::traits::{Boxable, Identifiable};
use fchat::{self, Ticket};
use chrono::{self, Timelike};
use futures::sync::mpsc::UnboundedSender;
use std;
use std::thread::spawn;
use std::sync::mpsc::{channel, Receiver, Sender};
use io;
pub enum Event {
ReceivedMessage(fchat... | (&mut self) {
use std::sync::mpsc::TryRecvError;
let mut next_state = None;
match self.state {
State::Start => {
let (login_tx, login_rx) = channel();
self.siv.add_layer(login_dialog(login_tx));
next_state = Some(State::Login(login_rx))... | step | identifier_name |
mod.rs | use cursive::{self, views, Cursive};
use cursive::traits::{Boxable, Identifiable};
use fchat::{self, Ticket};
use chrono::{self, Timelike};
use futures::sync::mpsc::UnboundedSender;
use std;
use std::thread::spawn;
use std::sync::mpsc::{channel, Receiver, Sender};
use io;
pub enum Event {
ReceivedMessage(fchat... |
fn debug_message<M: std::fmt::Debug>(siv: &mut Cursive, message: M) {
siv.call_on_id("debug_view", |view: &mut views::TextView| {
let now = chrono::Local::now();
let hour = now.hour();
let minute = now.minute();
let second = now.second();
view.append(format!(
"[... | {
let textview = views::TextView::empty()
.scroll_strategy(cursive::view::ScrollStrategy::StickToBottom)
.with_id("debug_view")
.full_screen();
let input = views::EditView::new()
.on_submit(move |siv, text| {
event_tx.send(Event::TextInput(String::from(text))).unwrap(... | identifier_body |
mod.rs | use cursive::{self, views, Cursive};
use cursive::traits::{Boxable, Identifiable};
use fchat::{self, Ticket};
use chrono::{self, Timelike};
use futures::sync::mpsc::UnboundedSender;
use std;
use std::thread::spawn;
use std::sync::mpsc::{channel, Receiver, Sender};
use io;
pub enum Event {
ReceivedMessage(fchat... | .button("Login", move |siv| select_character(siv, result.clone()))
.button("Quit", |siv| siv.quit())
}
fn select_character(siv: &mut Cursive, result: Sender<(Ticket, String)>) {
let username = siv.call_on_id("username", |text: &mut views::EditView| text.get_content())
.expect("Failed to find I... | .child(password);
views::Dialog::around(inputs) | random_line_split |
version.rs | // Copyright 2015-2017 Parity Technologies (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any lat... |
}
impl Into<json::Version> for Version {
fn into(self) -> json::Version {
match self {
Version::V3 => json::Version::V3,
}
}
}
| {
match json {
json::Version::V3 => Version::V3,
}
} | identifier_body |
version.rs | // Copyright 2015-2017 Parity Technologies (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any lat... | {
V3,
}
impl From<json::Version> for Version {
fn from(json: json::Version) -> Self {
match json {
json::Version::V3 => Version::V3,
}
}
}
impl Into<json::Version> for Version {
fn into(self) -> json::Version {
match self {
Version::V3 => json::Version::V3,
}
}
}
| Version | identifier_name |
version.rs | // Copyright 2015-2017 Parity Technologies (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by | // the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// Parity is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Publ... | random_line_split |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.