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 |
|---|---|---|---|---|
effects.mako.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
<%namespace name="helpers" file="/helpers.mako.rs" />
// Box-shadow, etc.
<% data.new_style_struct("Effects", in... | animation_value_type="AnimatedFilterList",
vector_animation_type="with_zero",
extra_prefixes="webkit",
flags="CREATES_STACKING_CONTEXT FIXPOS_CB",
spec="https://drafts.fxtf.org/filters/#propdef-filter",
)}
${helpers.predefined_type(
"backdrop-filter",
"Filter",
None,
engines="gecko"... | vector=True,
simple_vector_bindings=True,
gecko_ffi_name="mFilters",
separator="Space", | random_line_split |
car.rs | use super::camera::Camera;
use crate::color::*;
use cgmath::{Vector2, Vector3};
// Present a car that can be drawed, check for collision
// with other car and bullet, turn left/right, move forward
// and jump.
pub trait Car {
fn render(&self, _: &Camera) -> Vec<([Vector2<f64>; 2], Color)>;
fn crashed(&self, _:... | fn forward(&mut self, dt: f64, outside_speed: f64) {
self.position.z -= dt * (self.speed + outside_speed);
self.update_jump(dt);
}
fn update_jump(&mut self, dt: f64) {
if self.jumping {
self.current_t += dt;
self.position.y = self.current_t * (self.jump_v - 0.... | random_line_split | |
car.rs | use super::camera::Camera;
use crate::color::*;
use cgmath::{Vector2, Vector3};
// Present a car that can be drawed, check for collision
// with other car and bullet, turn left/right, move forward
// and jump.
pub trait Car {
fn render(&self, _: &Camera) -> Vec<([Vector2<f64>; 2], Color)>;
fn crashed(&self, _:... | (&self) -> Vector3<f64> {
self.position
}
fn crashed(&self, a: &Self) -> bool {
(f64::abs(self.position.x - a.position.x) < (self.size.x + a.size.x) / 2.)
&& ((self.position.z < a.position.z && a.position.z - self.position.z < self.size.z)
|| (self.position.z >= a.pos... | pos | identifier_name |
car.rs | use super::camera::Camera;
use crate::color::*;
use cgmath::{Vector2, Vector3};
// Present a car that can be drawed, check for collision
// with other car and bullet, turn left/right, move forward
// and jump.
pub trait Car {
fn render(&self, _: &Camera) -> Vec<([Vector2<f64>; 2], Color)>;
fn crashed(&self, _:... |
fn hit(&self, bullet: &[Vector3<f64>; 3]) -> bool {
let (x, y) = (bullet[0], bullet[0] + bullet[1]);
let check = |x: &Vector3<f64>| {
f64::abs(x.x - self.position.x) < self.size.x / 2.
&& x.y >= self.position.y
&& x.y - self.position.y < self.size.y
... | {
if self.jumping {
self.current_t += dt;
self.position.y = self.current_t * (self.jump_v - 0.5 * self.jump_a * self.current_t);
if self.position.y < 0. {
self.position.y = 0.;
self.jumping = false;
}
}
} | identifier_body |
car.rs | use super::camera::Camera;
use crate::color::*;
use cgmath::{Vector2, Vector3};
// Present a car that can be drawed, check for collision
// with other car and bullet, turn left/right, move forward
// and jump.
pub trait Car {
fn render(&self, _: &Camera) -> Vec<([Vector2<f64>; 2], Color)>;
fn crashed(&self, _:... |
}
fn forward(&mut self, dt: f64, outside_speed: f64) {
self.position.z -= dt * (self.speed + outside_speed);
self.update_jump(dt);
}
fn update_jump(&mut self, dt: f64) {
if self.jumping {
self.current_t += dt;
self.position.y = self.current_t * (self.jump... | {
self.jumping = true;
self.current_t = 0.;
} | conditional_block |
codegen.rs | //! Various helpers for code-generation.
use std::io;
#[cfg(feature = "pattern_class")] use std::cmp;
use std::char;
use std::iter;
use std::usize;
#[cfg(all(test, feature = "pattern_class"))]
use std::iter::FromIterator;
#[cfg(feature = "pattern_class")]
use super::{Atom, Class, ClassMember};
use super::SizeBound;
... | assert_eq!(SizeBound::Exact(1), 'a'.read_size());
assert_eq!(SizeBound::Exact(3), 'β'.read_size());
#[cfg(feature = "pattern_class")]
assert_eq!(SizeBound::Range(1, 3), Class::from_iter(['x', 'y', 'β'].into_iter().cloned()).read_size());
}
// ---------------------------------------------------------------... | edread() {
| identifier_name |
codegen.rs | //! Various helpers for code-generation.
use std::io; | use std::usize;
#[cfg(all(test, feature = "pattern_class"))]
use std::iter::FromIterator;
#[cfg(feature = "pattern_class")]
use super::{Atom, Class, ClassMember};
use super::SizeBound;
// ================================================================
/// Trait for atom types that can be converted to byte sequences... | #[cfg(feature = "pattern_class")] use std::cmp;
use std::char;
use std::iter; | random_line_split |
codegen.rs | //! Various helpers for code-generation.
use std::io;
#[cfg(feature = "pattern_class")] use std::cmp;
use std::char;
use std::iter;
use std::usize;
#[cfg(all(test, feature = "pattern_class"))]
use std::iter::FromIterator;
#[cfg(feature = "pattern_class")]
use super::{Atom, Class, ClassMember};
use super::SizeBound;
... |
}
#[cfg(test)]
#[test]
fn test_sizedread_char() {
assert_eq!(SizeBound::Exact(1), 'a'.read_size());
assert_eq!(SizeBound::Exact(3), 'β'.read_size());
}
#[cfg(test)]
#[test]
fn test_readable_char() {
let mut buf = ['\0' as u8; 32];
{
let mut r = io::repeat('a' as u8);
assert_eq!(3, ... | {
let mut i = 0;
let mut n = 0;
while i < dest.len() && n < max_count {
try!(r.read_exact(&mut dest[i..(i+1)]));
let w = UTF8_CHAR_WIDTH[dest[i] as usize];
try!(r.read_exact(&mut dest[(i+1)..(i + w as usize)]));
i += w as usize;
n += 1;... | identifier_body |
mutation.rs | /*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This software may be used and distributed according to the terms of the
* GNU General Public License version 2.
*/
//! Tracking of commit mutations (amends, rebases, etc.)
use std::io::{Read, Write};
use anyhow::{anyhow, Result};
use byteorder::{BigEndia... | w.write_all(&key)?;
w.write_vlq(value.len())?;
w.write_all(&value)?;
}
Ok(())
}
pub fn deserialize(r: &mut dyn Read) -> Result<Self> {
enum EntryFormat {
FloatDate,
Latest,
}
let format = match r.read_u8()? {
... | {
w.write_u8(DEFAULT_VERSION)?;
w.write_node(&self.succ)?;
w.write_vlq(self.preds.len())?;
for pred in self.preds.iter() {
w.write_node(pred)?;
}
w.write_vlq(self.split.len())?;
for split in self.split.iter() {
w.write_node(split)?;
... | identifier_body |
mutation.rs | /*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This software may be used and distributed according to the terms of the
* GNU General Public License version 2.
*/
//! Tracking of commit mutations (amends, rebases, etc.)
use std::io::{Read, Write};
use anyhow::{anyhow, Result};
use byteorder::{BigEndia... |
_ => r.read_vlq()?,
};
let tz = r.read_vlq()?;
let extra_count = r.read_vlq()?;
let mut extra = Vec::with_capacity(extra_count);
for _ in 0..extra_count {
let key_len = r.read_vlq()?;
let mut key = vec![0; key_len];
r.read_exact(&m... | {
// The date was stored as a floating point number. We
// actually want an integer, so truncate and convert.
r.read_f64::<BigEndian>()?.trunc() as i64
} | conditional_block |
mutation.rs | /*
* Copyright (c) Facebook, Inc. and its affiliates.
* | //! Tracking of commit mutations (amends, rebases, etc.)
use std::io::{Read, Write};
use anyhow::{anyhow, Result};
use byteorder::{BigEndian, ReadBytesExt, WriteBytesExt};
use vlqencoding::{VLQDecode, VLQEncode};
use crate::node::{Node, ReadNodeExt, WriteNodeExt};
#[derive(Clone, PartialEq, PartialOrd)]
pub struct ... | * This software may be used and distributed according to the terms of the
* GNU General Public License version 2.
*/
| random_line_split |
mutation.rs | /*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This software may be used and distributed according to the terms of the
* GNU General Public License version 2.
*/
//! Tracking of commit mutations (amends, rebases, etc.)
use std::io::{Read, Write};
use anyhow::{anyhow, Result};
use byteorder::{BigEndia... | {
pub succ: Node,
pub preds: Vec<Node>,
pub split: Vec<Node>,
pub op: String,
pub user: String,
pub time: i64,
pub tz: i32,
pub extra: Vec<(Box<[u8]>, Box<[u8]>)>,
}
/// Default size for a buffer that will be used for serializing a mutation entry.
///
/// This is:
/// * Version (1 by... | MutationEntry | identifier_name |
pseudo_element_definition.mako.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
/// Gecko's pseudo-element definition.
#[derive(Clone, Debug, Eq, Hash, MallocSizeOf, PartialEq, ToShmem)]
pub en... | % for pseudo in PSEUDOS:
% if pseudo.is_tree_pseudo_element():
if atom == &atom!("${pseudo.value}") {
return Some(PseudoElement::${pseudo.capitalized_pseudo()}(args.into()));
}
% endif
% endfor
None
}
/// Constructs a pseudo-elemen... | #[inline]
pub fn from_tree_pseudo_atom(atom: &Atom, args: Box<[Atom]>) -> Option<Self> { | random_line_split |
pseudo_element_definition.mako.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
/// Gecko's pseudo-element definition.
#[derive(Clone, Debug, Eq, Hash, MallocSizeOf, PartialEq, ToShmem)]
pub en... | (name: &str) -> Option<Self> {
// We don't need to support tree pseudos because functional
// pseudo-elements needs arguments, and thus should be created
// via other methods.
match_ignore_ascii_case! { name,
% for pseudo in SIMPLE_PSEUDOS:
"${pseudo.value[1:]}" =... | from_slice | identifier_name |
pseudo_element_definition.mako.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
/// Gecko's pseudo-element definition.
#[derive(Clone, Debug, Eq, Hash, MallocSizeOf, PartialEq, ToShmem)]
pub en... | _ => {
if starts_with_ignore_ascii_case(name, "-moz-tree-") {
return PseudoElement::tree_pseudo_element(name, Box::new([]))
}
if static_prefs::pref!("layout.css.unknown-webkit-pseudo-element") {
const WEBKIT_PREFIX: &str... | {
// We don't need to support tree pseudos because functional
// pseudo-elements needs arguments, and thus should be created
// via other methods.
match_ignore_ascii_case! { name,
% for pseudo in SIMPLE_PSEUDOS:
"${pseudo.value[1:]}" => {
return So... | identifier_body |
pseudo_element_definition.mako.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
/// Gecko's pseudo-element definition.
#[derive(Clone, Debug, Eq, Hash, MallocSizeOf, PartialEq, ToShmem)]
pub en... | => {
Some(${pseudo_element_variant(pseudo)})
},
% endif
% endfor
_ => None,
}
}
/// Construct a `PseudoStyleType` from a pseudo-element
#[inline]
pub fn pseudo_type(&self) -> PseudoStyleType {
match *self {
... | {pseudo.pseudo_ident} | conditional_block |
empty-struct-braces-pat-2.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 ... | {}
fn main() {
let e1 = Empty1 {};
let xe1 = XEmpty1 {};
match e1 {
Empty1() => () //~ ERROR expected tuple struct/variant, found struct `Empty1`
}
match xe1 {
XEmpty1() => () //~ ERROR expected tuple struct/variant, found struct `XEmpty1`
}
match e1 {
Empty1(..) =... | Empty1 | identifier_name |
empty-struct-braces-pat-2.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 ... | } | random_line_split | |
empty-struct-braces-pat-2.rs | // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | {
let e1 = Empty1 {};
let xe1 = XEmpty1 {};
match e1 {
Empty1() => () //~ ERROR expected tuple struct/variant, found struct `Empty1`
}
match xe1 {
XEmpty1() => () //~ ERROR expected tuple struct/variant, found struct `XEmpty1`
}
match e1 {
Empty1(..) => () //~ ERROR ... | identifier_body | |
length_expr.rs | // Copyright (c) 2015 Robert Clipsham <robert@octarineparrot.com> | // option. This file may not be copied, modified, or distributed
// except according to those terms.
// error-pattern: Only field names, constants, integers, basic arithmetic expressions (+ - * / %) and parentheses are allowed in the "length" attribute
#![feature(custom_attribute, plugin)]
#![plugin(pnet_macros_plugi... | //
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your | random_line_split |
length_expr.rs | // Copyright (c) 2015 Robert Clipsham <robert@octarineparrot.com>
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or... | () {}
| main | identifier_name |
ref.rs | #[derive(Clone, Copy)]
struct Point { x: i32, y: i32 }
fn | () {
let c = 'Q';
// A `ref` borrow on the left side of an assignment is equivalent to
// an `&` borrow on the right side.
let ref ref_c1 = c;
let ref_c2 = &c;
println!("ref_c1 equals ref_c2: {}", *ref_c1 == *ref_c2);
let point = Point { x: 0, y: 0 };
// `ref` is also valid when dest... | main | identifier_name |
ref.rs | #[derive(Clone, Copy)]
struct Point { x: i32, y: i32 }
fn main() |
// A mutable copy of `point`
let mut mutable_point = point;
{
// `ref` can be paired with `mut` to take mutable references.
let Point { x: _, y: ref mut mut_ref_to_y } = mutable_point;
// Mutate the `y` field of `mutable_point` via a mutable reference.
*mut_ref_to_y = 1;
... | {
let c = 'Q';
// A `ref` borrow on the left side of an assignment is equivalent to
// an `&` borrow on the right side.
let ref ref_c1 = c;
let ref_c2 = &c;
println!("ref_c1 equals ref_c2: {}", *ref_c1 == *ref_c2);
let point = Point { x: 0, y: 0 };
// `ref` is also valid when destruc... | identifier_body |
ref.rs | #[derive(Clone, Copy)]
struct Point { x: i32, y: i32 }
fn main() {
let c = 'Q';
// A `ref` borrow on the left side of an assignment is equivalent to
// an `&` borrow on the right side.
let ref ref_c1 = c;
let ref_c2 = &c;
println!("ref_c1 equals ref_c2: {}", *ref_c1 == *ref_c2);
let poin... | println!("tuple is {:?}", mutable_tuple);
} | random_line_split | |
order_12.rs | mod lib {
pub struct SessionToken(String);
pub struct InvalidOrder(String);
pub enum ApiError {
ParsingError(String),
IoError(String),
}
pub struct Order {
amount: u8,
name: String,
}
pub fn create_order(amount: u8, name: String) -> Result<Order, InvalidOr... |
unimplemented!()
}
pub fn authorize(auth_token: String) -> Result<SessionToken, ApiError> {
unimplemented!()
}
pub fn send_order(session_token: &SessionToken,
order: Order) {
unimplemented!()
}
}
pub use lib::*;
fn main() {
if let Ok(session_tok... | {
unimplemented!()
} | conditional_block |
order_12.rs | mod lib {
pub struct SessionToken(String);
pub struct InvalidOrder(String);
pub enum ApiError {
ParsingError(String),
IoError(String),
}
pub struct Order {
amount: u8,
name: String,
}
pub fn create_order(amount: u8, name: String) -> Result<Order, InvalidOr... |
pub fn send_order(session_token: &SessionToken,
order: Order) {
unimplemented!()
}
}
pub use lib::*;
fn main() {
if let Ok(session_token) = authorize("My initial token".into()) {
let first_order = create_order(10, "Bananas".into());
if let Ok(order) = first... | random_line_split | |
order_12.rs | mod lib {
pub struct SessionToken(String);
pub struct InvalidOrder(String);
pub enum ApiError {
ParsingError(String),
IoError(String),
}
pub struct Order {
amount: u8,
name: String,
}
pub fn create_order(amount: u8, name: String) -> Result<Order, InvalidOr... |
pub fn authorize(auth_token: String) -> Result<SessionToken, ApiError> {
unimplemented!()
}
pub fn send_order(session_token: &SessionToken,
order: Order) {
unimplemented!()
}
}
pub use lib::*;
fn main() {
if let Ok(session_token) = authorize("My initial tok... | {
if amount <= 0 {
unimplemented!()
}
unimplemented!()
} | identifier_body |
order_12.rs | mod lib {
pub struct SessionToken(String);
pub struct | (String);
pub enum ApiError {
ParsingError(String),
IoError(String),
}
pub struct Order {
amount: u8,
name: String,
}
pub fn create_order(amount: u8, name: String) -> Result<Order, InvalidOrder> {
if amount <= 0 {
unimplemented!()
}
... | InvalidOrder | identifier_name |
char.rs | // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MI... | #![doc(primitive = "char")]
use core::char::CharExt as C;
use core::option::Option::{self, Some};
use core::iter::Iterator;
use tables::{derived_property, property, general_category, conversions, charwidth};
// stable reexports
pub use core::char::{MAX, from_u32, from_digit, EscapeUnicode, EscapeDefault};
// unstabl... | random_line_split | |
char.rs | // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MI... | (self, radix: u32) -> Option<u32> { C::to_digit(self, radix) }
/// Returns an iterator that yields the hexadecimal Unicode escape of a
/// character, as `char`s.
///
/// All characters are escaped with Rust syntax of the form `\\u{NNNN}`
/// where `NNNN` is the shortest hexadecimal representation o... | to_digit | identifier_name |
char.rs | // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MI... |
}
#[stable(feature = "rust1", since = "1.0.0")]
#[lang = "char"]
impl char {
/// Checks if a `char` parses as a numeric digit in the given radix.
///
/// Compared to `is_numeric()`, this function only recognizes the characters
/// `0-9`, `a-z` and `A-Z`.
///
/// # Return value
///
/// ... | { self.0.take() } | identifier_body |
lib.rs | extern crate k2hash;
extern crate k2hash_sys;
use k2hash::K2Hash;
fn build_wrapped_k2hash() -> Result<K2Hash, std::io::Error> |
#[test]
fn test_new() {
let result = build_wrapped_k2hash();
result.unwrap();
assert!(true);
}
#[test]
fn test_set_str() {
let k2hash = build_wrapped_k2hash().unwrap();
let key = "test_set_str";
let val = "val";
let result = k2hash.set_str(key.to_string(), val.to_string());
result.... | {
let path = std::path::Path::new("/tmp/tmp.k2hash");
K2Hash::new(path,
false,
true,
true,
k2hash::DEFAULT_MASK_BITCOUNT,
k2hash::DEFAULT_COLLISION_MASK_BITCOUNT,
k2hash::DEFAULT_MAX_ELEMENT_CNT,
k2h... | identifier_body |
lib.rs | extern crate k2hash;
extern crate k2hash_sys;
use k2hash::K2Hash;
fn build_wrapped_k2hash() -> Result<K2Hash, std::io::Error> {
let path = std::path::Path::new("/tmp/tmp.k2hash");
K2Hash::new(path,
false,
true,
true,
k2hash::DEFAULT_MASK_BITCOUN... | () {
let result = build_wrapped_k2hash();
result.unwrap();
assert!(true);
}
#[test]
fn test_set_str() {
let k2hash = build_wrapped_k2hash().unwrap();
let key = "test_set_str";
let val = "val";
let result = k2hash.set_str(key.to_string(), val.to_string());
result.unwrap();
assert!... | test_new | identifier_name |
lib.rs | extern crate k2hash;
extern crate k2hash_sys;
use k2hash::K2Hash;
fn build_wrapped_k2hash() -> Result<K2Hash, std::io::Error> {
let path = std::path::Path::new("/tmp/tmp.k2hash");
K2Hash::new(path,
false,
true,
true,
k2hash::DEFAULT_MASK_BITCOUN... | }
#[test]
fn test_set_str() {
let k2hash = build_wrapped_k2hash().unwrap();
let key = "test_set_str";
let val = "val";
let result = k2hash.set_str(key.to_string(), val.to_string());
result.unwrap();
assert!(true);
}
#[test]
fn test_get_str() {
let k2hash = build_wrapped_k2hash().unwrap()... | result.unwrap();
assert!(true); | random_line_split |
exponential.rs | extern crate rand;
use crate::distribs::distribution::*;
use std::cell::Cell;
#[allow(dead_code)]
pub struct Exponential {
lambda: f64,
}
impl Exponential {
pub fn new(rate: f64) -> Exponential {
Exponential { lambda: rate }
}
}
impl Distribution<f64> for Exponential {
//Using the Inverse Tr... | (&self, x: f64) -> f64 {
1.0f64 - (-self.lambda * x).exp()
}
}
| cdf | identifier_name |
exponential.rs | extern crate rand;
use crate::distribs::distribution::*;
use std::cell::Cell;
#[allow(dead_code)]
pub struct Exponential {
lambda: f64,
}
impl Exponential {
pub fn new(rate: f64) -> Exponential {
Exponential { lambda: rate }
}
}
impl Distribution<f64> for Exponential {
//Using the Inverse Tr... | }
fn pdf(&self, x: f64) -> f64 {
self.lambda * (-self.lambda * x).exp()
}
fn cdf(&self, x: f64) -> f64 {
1.0f64 - (-self.lambda * x).exp()
}
} | fn sigma(&self) -> f64 {
self.lambda.recip().powi(2) | random_line_split |
exponential.rs | extern crate rand;
use crate::distribs::distribution::*;
use std::cell::Cell;
#[allow(dead_code)]
pub struct Exponential {
lambda: f64,
}
impl Exponential {
pub fn new(rate: f64) -> Exponential {
Exponential { lambda: rate }
}
}
impl Distribution<f64> for Exponential {
//Using the Inverse Tr... |
fn sigma(&self) -> f64 {
self.lambda.recip().powi(2)
}
fn pdf(&self, x: f64) -> f64 {
self.lambda * (-self.lambda * x).exp()
}
fn cdf(&self, x: f64) -> f64 {
1.0f64 - (-self.lambda * x).exp()
}
}
| {
self.lambda.recip()
} | identifier_body |
validator.rs | // Copyright 2015 Β© Samuel Dolt <samuel@dolt.ch>
//
// This file is part of orion_backend.
//
// Orion_backend 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 ... | &self) -> bool {
match DateTime::parse_from_rfc3339(&self) {
Ok(_) => true,
Err(_) => false,
}
}
}
| s_rfc3339_timestamp( | identifier_name |
validator.rs | // Copyright 2015 Β© Samuel Dolt <samuel@dolt.ch>
//
// This file is part of orion_backend.
//
// Orion_backend 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 ... |
}
|
match DateTime::parse_from_rfc3339(&self) {
Ok(_) => true,
Err(_) => false,
}
}
| identifier_body |
validator.rs | // Copyright 2015 Β© Samuel Dolt <samuel@dolt.ch>
//
// This file is part of orion_backend.
//
// Orion_backend 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 ... | }
}
} |
fn is_rfc3339_timestamp(&self) -> bool {
match DateTime::parse_from_rfc3339(&self) {
Ok(_) => true,
Err(_) => false, | random_line_split |
optional_comma_in_match_arm.rs | // run-pass
#![allow(unused_unsafe)]
// ignore-pretty issue #37199
#![allow(while_true)]
fn main() | 6 => { () }
7 => unsafe { () }
_ => ()
}
let r: &i32 = &x;
match r {
// Absence of comma should not cause confusion between a pattern
// and a bitwise and.
&1 => if true { () } else { () }
&2 => (),
_ =>()
}
}
| {
let x = 1;
match x {
1 => loop { break; },
2 => while true { break; },
3 => if true { () },
4 => if true { () } else { () },
5 => match () { () => () },
6 => { () },
7 => unsafe { () },
_ => (),
}
match x {
1 => loop { break; }
... | identifier_body |
optional_comma_in_match_arm.rs | // run-pass
#![allow(unused_unsafe)]
// ignore-pretty issue #37199
#![allow(while_true)]
fn main() {
let x = 1;
match x {
1 => loop { break; },
2 => while true { break; },
3 => if true { () },
4 => if true { () } else { () },
5 => match () { () => () },
6 => { (... | 2 => while true { break; }
3 => if true { () }
4 => if true { () } else { () }
5 => match () { () => () }
6 => { () }
7 => unsafe { () }
_ => ()
}
let r: &i32 = &x;
match r {
// Absence of comma should not cause confusion between a pattern
... | _ => (),
}
match x {
1 => loop { break; } | random_line_split |
optional_comma_in_match_arm.rs | // run-pass
#![allow(unused_unsafe)]
// ignore-pretty issue #37199
#![allow(while_true)]
fn | () {
let x = 1;
match x {
1 => loop { break; },
2 => while true { break; },
3 => if true { () },
4 => if true { () } else { () },
5 => match () { () => () },
6 => { () },
7 => unsafe { () },
_ => (),
}
match x {
1 => loop { break;... | main | identifier_name |
restore-topology.rs | use futures_lite::stream::StreamExt;
use lapin::{options::*, topology::*, BasicProperties, Connection, ConnectionProperties, Result};
use tracing::info;
fn main() -> Result<()> {
if std::env::var("RUST_LOG").is_err() |
tracing_subscriber::fmt::init();
let addr = std::env::var("AMQP_ADDR").unwrap_or_else(|_| "amqp://127.0.0.1:5672/%2f".into());
let topology_str = std::fs::read_to_string("examples/topology.json").unwrap();
let topology = serde_json::from_str::<TopologyDefinition>(&topology_str).unwrap();
async_g... | {
std::env::set_var("RUST_LOG", "info");
} | conditional_block |
restore-topology.rs | use futures_lite::stream::StreamExt;
use lapin::{options::*, topology::*, BasicProperties, Connection, ConnectionProperties, Result};
use tracing::info;
fn main() -> Result<()> | let channel_b = topology.channel(1).into_inner(); // Get the actual inner Channel
let tmp_queue = channel_a.queue(0);
let mut consumer = channel_a.consumer(0);
info!(?trash_queue,?tmp_queue, "Declared queues");
channel_b
.basic_publish(
"",
... | {
if std::env::var("RUST_LOG").is_err() {
std::env::set_var("RUST_LOG", "info");
}
tracing_subscriber::fmt::init();
let addr = std::env::var("AMQP_ADDR").unwrap_or_else(|_| "amqp://127.0.0.1:5672/%2f".into());
let topology_str = std::fs::read_to_string("examples/topology.json").unwrap();
... | identifier_body |
restore-topology.rs | use futures_lite::stream::StreamExt;
use lapin::{options::*, topology::*, BasicProperties, Connection, ConnectionProperties, Result}; | fn main() -> Result<()> {
if std::env::var("RUST_LOG").is_err() {
std::env::set_var("RUST_LOG", "info");
}
tracing_subscriber::fmt::init();
let addr = std::env::var("AMQP_ADDR").unwrap_or_else(|_| "amqp://127.0.0.1:5672/%2f".into());
let topology_str = std::fs::read_to_string("examples/top... | use tracing::info;
| random_line_split |
restore-topology.rs | use futures_lite::stream::StreamExt;
use lapin::{options::*, topology::*, BasicProperties, Connection, ConnectionProperties, Result};
use tracing::info;
fn | () -> Result<()> {
if std::env::var("RUST_LOG").is_err() {
std::env::set_var("RUST_LOG", "info");
}
tracing_subscriber::fmt::init();
let addr = std::env::var("AMQP_ADDR").unwrap_or_else(|_| "amqp://127.0.0.1:5672/%2f".into());
let topology_str = std::fs::read_to_string("examples/topology.j... | main | identifier_name |
mod.rs | mod approach;
mod character;
mod friend;
mod context;
mod chat;
mod authorized;
mod player_status;
mod error;
use super::{Session, GameState, AccountData, SocialInformations, SocialState}; | use protocol::messages::queues::*;
use protocol::messages::game::basic::TextInformationMessage;
use protocol::enums::text_information_type;
use std::io::{self, Result};
use std::sync::atomic::Ordering;
use shared::{self, database};
use diesel::*;
use server::SERVER;
use character::Character;
use std::mem;
use std::coll... | use super::chunk::{ChunkImpl, Ref, SocialUpdateType};
use character::CharacterMinimal;
use protocol::{Protocol, VarShort};
use protocol::messages::handshake::*;
use protocol::messages::game::approach::*; | random_line_split |
mod.rs | mod approach;
mod character;
mod friend;
mod context;
mod chat;
mod authorized;
mod player_status;
mod error;
use super::{Session, GameState, AccountData, SocialInformations, SocialState};
use super::chunk::{ChunkImpl, Ref, SocialUpdateType};
use character::CharacterMinimal;
use protocol::{Protocol, VarShort};
use pro... | (&self, conn: &Connection, ch: Character, map: i32) -> QueryResult<()> {
try!(conn.transaction(|| {
ch.save(conn, map)
}));
Ok(())
}
}
| save_game | identifier_name |
mod.rs | mod approach;
mod character;
mod friend;
mod context;
mod chat;
mod authorized;
mod player_status;
mod error;
use super::{Session, GameState, AccountData, SocialInformations, SocialState};
use super::chunk::{ChunkImpl, Ref, SocialUpdateType};
use character::CharacterMinimal;
use protocol::{Protocol, VarShort};
use pro... |
}
| {
try!(conn.transaction(|| {
ch.save(conn, map)
}));
Ok(())
} | identifier_body |
mod.rs | mod approach;
mod character;
mod friend;
mod context;
mod chat;
mod authorized;
mod player_status;
mod error;
use super::{Session, GameState, AccountData, SocialInformations, SocialState};
use super::chunk::{ChunkImpl, Ref, SocialUpdateType};
use character::CharacterMinimal;
use protocol::{Protocol, VarShort};
use pro... |
let state = mem::replace(&mut self.state, GameState::None);
if let GameState::InContext(ch) = state {
let map_id = ch.map_id;
let ch = chunk.maps
.get_mut(&ch.map_id).unwrap()
.remove_actor(ch.id).unwrap()
... | {
SERVER.with(|s| database::execute(&s.auth_db, move |conn| {
if let Err(err) = Session::save_auth(conn, account) {
error!("error while saving session to auth db: {:?}", err);
}
}));
} | conditional_block |
compiled.rs | modified, or distributed
// except according to those terms.
#![allow(non_uppercase_statics)]
//! ncurses-compatible compiled terminfo format parsing (term(5))
use collections::HashMap;
use std::io;
use std::str;
use super::super::TermInfo;
// These are the orders ncurses uses in its compiled format (as of 5.9). N... | (file: &mut io::Reader, longnames: bool)
-> Result<Box<TermInfo>, ~str> {
macro_rules! try( ($e:expr) => (
match $e { Ok(e) => e, Err(e) => return Err(format!("{}", e)) }
) )
let bnames;
let snames;
let nnames;
if longnames {
bnames = boolfnames;
snames = s... | parse | identifier_name |
compiled.rs | , modified, or distributed
// except according to those terms.
#![allow(non_uppercase_statics)]
//! ncurses-compatible compiled terminfo format parsing (term(5))
use collections::HashMap;
use std::io;
use std::str;
use super::super::TermInfo;
// These are the orders ncurses uses in its compiled format (as of 5.9). ... | strings.insert("setaf".to_owned(), Vec::from_slice(bytes!("\x1b[3%p1%dm")));
strings.insert("setab".to_owned(), Vec::from_slice(bytes!("\x1b[4%p1%dm")));
box TermInfo {
names: vec!("cygwin".to_owned()), // msys is a fork of an older cygwin version
bools: HashMap::new(),
numbers: Hash... | /// Create a dummy TermInfo struct for msys terminals
pub fn msys_terminfo() -> Box<TermInfo> {
let mut strings = HashMap::new();
strings.insert("sgr0".to_owned(), Vec::from_slice(bytes!("\x1b[0m")));
strings.insert("bold".to_owned(), Vec::from_slice(bytes!("\x1b[1m"))); | random_line_split |
compiled.rs | _magic_smso", "tilde_glitch", "transparent_underline", "xon_xoff", "needs_xon_xoff",
"prtr_silent", "hard_cursor", "non_rev_rmcup", "no_pad_char", "non_dest_scroll_region",
"can_change", "back_color_erase", "hue_lightness_saturation", "col_addr_glitch",
"cr_cancels_micro_mode", "has_print_wheel", "row_addr_... | {
// FIXME #6870: Distribute a compiled file in src/tests and test there
// parse(io::fs_reader(&p("/usr/share/terminfo/r/rxvt-256color")).unwrap(), false);
} | identifier_body | |
compiled.rs | modified, or distributed
// except according to those terms.
#![allow(non_uppercase_statics)]
//! ncurses-compatible compiled terminfo format parsing (term(5))
use collections::HashMap;
use std::io;
use std::str;
use super::super::TermInfo;
// These are the orders ncurses uses in its compiled format (as of 5.9). N... | ,
None => {
return Err("invalid file: missing NUL in string_table".to_owned());
}
};
}
}
// And that's all there is to it
Ok(box TermInfo {
names: term_names,
bools: bools_map,
numbers: numbers_map,
stri... | {
string_map.insert(name.to_owned(),
Vec::from_slice(
string_table.slice(offset as uint,
offset as uint + len)))
} | conditional_block |
vtable_recursive_sig.rs | #![allow(
dead_code,
non_snake_case,
non_camel_case_types,
non_upper_case_globals
)]
#[repr(C)]
pub struct Base__bindgen_vtable {
pub Base_AsDerived: unsafe extern "C" fn(this: *mut Base) -> *mut Derived,
}
#[repr(C)]
#[derive(Debug, Copy, Clone)]
pub struct Base {
pub vtable_: *const Base__bin... | () {
assert_eq!(
::std::mem::size_of::<Derived>(),
8usize,
concat!("Size of: ", stringify!(Derived))
);
assert_eq!(
::std::mem::align_of::<Derived>(),
8usize,
concat!("Alignment of ", stringify!(Derived))
);
}
impl Default for Derived {
fn default() ->... | bindgen_test_layout_Derived | identifier_name |
vtable_recursive_sig.rs | #![allow(
dead_code,
non_snake_case,
non_camel_case_types,
non_upper_case_globals
)]
#[repr(C)]
pub struct Base__bindgen_vtable {
pub Base_AsDerived: unsafe extern "C" fn(this: *mut Base) -> *mut Derived,
}
#[repr(C)]
#[derive(Debug, Copy, Clone)]
pub struct Base {
pub vtable_: *const Base__bin... | ::std::ptr::write_bytes(s.as_mut_ptr(), 0, 1);
s.assume_init()
}
}
} | random_line_split | |
mod.rs | #![cfg(target_os = "android")]
extern crate android_glue;
use libc;
use std::ffi::{CString};
use std::sync::mpsc::{Receiver, channel};
use {CreationError, Event, MouseCursor};
use CreationError::OsError;
use events::ElementState::{Pressed, Released};
use events::{Touch, TouchPhase};
use std::collections::VecDeque;
... |
}
pub struct WaitEventsIterator<'a> {
window: &'a Window,
}
impl<'a> Iterator for WaitEventsIterator<'a> {
type Item = Event;
#[inline]
fn next(&mut self) -> Option<Event> {
loop {
// calling poll_events()
if let Some(ev) = self.window.poll_events().next() {
... | {
match self.window.event_rx.try_recv() {
Ok(android_glue::Event::EventMotion(motion)) => {
Some(Event::Touch(Touch {
phase: match motion.action {
android_glue::MotionAction::Down => TouchPhase::Started,
android_glue... | identifier_body |
mod.rs | #![cfg(target_os = "android")]
extern crate android_glue;
use libc;
use std::ffi::{CString};
use std::sync::mpsc::{Receiver, channel};
use {CreationError, Event, MouseCursor};
use CreationError::OsError;
use events::ElementState::{Pressed, Released};
use events::{Touch, TouchPhase};
use std::collections::VecDeque;
... |
let context = try!(EglContext::new(egl::ffi::egl::Egl, pf_reqs, &opengl,
egl::NativeDisplay::Android)
.and_then(|p| p.finish(native_window as *const _)));
let (tx, rx) = channel();
android_glue::add_send... | {
return Err(OsError(format!("Android's native window is null")));
} | conditional_block |
mod.rs | #![cfg(target_os = "android")]
extern crate android_glue;
use libc;
use std::ffi::{CString};
use std::sync::mpsc::{Receiver, channel};
use {CreationError, Event, MouseCursor};
use CreationError::OsError;
use events::ElementState::{Pressed, Released};
use events::{Touch, TouchPhase};
use std::collections::VecDeque;
... | } | random_line_split | |
mod.rs | #![cfg(target_os = "android")]
extern crate android_glue;
use libc;
use std::ffi::{CString};
use std::sync::mpsc::{Receiver, channel};
use {CreationError, Event, MouseCursor};
use CreationError::OsError;
use events::ElementState::{Pressed, Released};
use events::{Touch, TouchPhase};
use std::collections::VecDeque;
... | (&self) -> PixelFormat {
self.context.get_pixel_format()
}
}
#[derive(Clone)]
pub struct WindowProxy;
impl WindowProxy {
#[inline]
pub fn wakeup_event_loop(&self) {
unimplemented!()
}
}
pub struct HeadlessContext(EglContext);
impl HeadlessContext {
/// See the docs in the crate r... | get_pixel_format | identifier_name |
element_section.rs | /* Copyright 2018 Mozilla Foundation
*
* 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... | (&mut self) -> Result<u32> {
self.reader.read_var_u32()
}
}
impl<'a> IntoIterator for ElementItemsReader<'a> {
type Item = Result<u32>;
type IntoIter = ElementItemsIterator<'a>;
fn into_iter(self) -> Self::IntoIter {
let count = self.count;
ElementItemsIterator {
rea... | read | identifier_name |
element_section.rs | /* Copyright 2018 Mozilla Foundation
*
* 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... |
};
let init_expr = {
let expr_offset = self.reader.position;
self.reader.skip_init_expr()?;
let data = &self.reader.buffer[expr_offset..self.reader.position];
InitExpr::new(data, self.reader.original_offset + expr_offset)
... | {
return Err(BinaryReaderError {
message: "invalid flags byte in element segment",
offset: self.reader.original_position() - 1,
});
} | conditional_block |
element_section.rs | /* Copyright 2018 Mozilla Foundation
*
* 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... |
}
impl<'a> IntoIterator for ElementSectionReader<'a> {
type Item = Result<Element<'a>>;
type IntoIter = SectionIteratorLimited<ElementSectionReader<'a>>;
fn into_iter(self) -> Self::IntoIter {
SectionIteratorLimited::new(self)
}
}
| {
ElementSectionReader::get_count(self)
} | identifier_body |
element_section.rs | /* Copyright 2018 Mozilla Foundation
*
* 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... | pub fn get_count(&self) -> u32 {
self.count
}
/// Reads content of the element section.
///
/// # Examples
/// ```
/// # let data: &[u8] = &[0x00, 0x61, 0x73, 0x6d, 0x01, 0x00, 0x00, 0x00,
/// # 0x01, 0x4, 0x01, 0x60, 0x00, 0x00, 0x03, 0x02, 0x01, 0x00,
/// # 0x05, 0... | pub fn original_position(&self) -> usize {
self.reader.original_position()
}
| random_line_split |
cat.rs | use std::str;
use std::collections::HashMap;
use std::io::File;
use std::os;
#[allow(unstable)]
fn main() {
let mut options = HashMap::new();
let args = os::args();
let mut files = Vec::new();
for x in range(1us, args.len()) {
let s_slice: &str = args[x].as_slice();
if!s_slice.starts_w... | }
}
for x in files.iter() {
let mut file = match File::open(&Path::new(x.as_bytes())) {
Err(why) => panic!("{}", why),
Ok(file) => file,
};
let file_data = match file.read_to_end() {
Ok(data) => data,
Err(why) => panic!("{}", why),
... | let chars_to_trim: &[char] = &['-'];
options.insert(s_slice.trim_matches(chars_to_trim), true); | random_line_split |
cat.rs | use std::str;
use std::collections::HashMap;
use std::io::File;
use std::os;
#[allow(unstable)]
fn | () {
let mut options = HashMap::new();
let args = os::args();
let mut files = Vec::new();
for x in range(1us, args.len()) {
let s_slice: &str = args[x].as_slice();
if!s_slice.starts_with("-") {
files.push(args[x].clone());
} else {
let chars_to_trim: &[ch... | main | identifier_name |
cat.rs | use std::str;
use std::collections::HashMap;
use std::io::File;
use std::os;
#[allow(unstable)]
fn main() | Err(why) => panic!("{}", why),
};
let readable_str = match str::from_utf8(file_data.as_slice()) {
Err(why) => panic!("{}", why),
Ok(c) => c,
};
for character in readable_str.chars() {
print!("{}",match character {
'\n' => ma... | {
let mut options = HashMap::new();
let args = os::args();
let mut files = Vec::new();
for x in range(1us, args.len()) {
let s_slice: &str = args[x].as_slice();
if !s_slice.starts_with("-") {
files.push(args[x].clone());
} else {
let chars_to_trim: &[char... | identifier_body |
tcp-stress.rs | // run-pass
// ignore-android needs extra network permissions
// ignore-emscripten no threads or sockets support
// ignore-netbsd system ulimit (Too many open files)
// ignore-openbsd system ulimit (Too many open files)
use std::io::prelude::*;
use std::net::{TcpListener, TcpStream};
use std::process;
use std::sync::m... | process::exit(1);
});
let listener = TcpListener::bind("127.0.0.1:0").unwrap();
let addr = listener.local_addr().unwrap();
thread::spawn(move || -> () {
loop {
let mut stream = match listener.accept() {
Ok(stream) => stream.0,
Err(_) => contin... |
fn main() {
// This test has a chance to time out, try to not let it time out
thread::spawn(move|| -> () {
thread::sleep(Duration::from_secs(30)); | random_line_split |
tcp-stress.rs | // run-pass
// ignore-android needs extra network permissions
// ignore-emscripten no threads or sockets support
// ignore-netbsd system ulimit (Too many open files)
// ignore-openbsd system ulimit (Too many open files)
use std::io::prelude::*;
use std::net::{TcpListener, TcpStream};
use std::process;
use std::sync::m... | let (tx, rx) = channel();
let mut spawned_cnt = 0;
for _ in 0..TARGET_CNT {
let tx = tx.clone();
let res = Builder::new().stack_size(64 * 1024).spawn(move|| {
match TcpStream::connect(addr) {
Ok(mut stream) => {
let _ = stream.write(&[1]);
... | {
// This test has a chance to time out, try to not let it time out
thread::spawn(move|| -> () {
thread::sleep(Duration::from_secs(30));
process::exit(1);
});
let listener = TcpListener::bind("127.0.0.1:0").unwrap();
let addr = listener.local_addr().unwrap();
thread::spawn(move ... | identifier_body |
tcp-stress.rs | // run-pass
// ignore-android needs extra network permissions
// ignore-emscripten no threads or sockets support
// ignore-netbsd system ulimit (Too many open files)
// ignore-openbsd system ulimit (Too many open files)
use std::io::prelude::*;
use std::net::{TcpListener, TcpStream};
use std::process;
use std::sync::m... | ,
Err(..) => {}
}
tx.send(()).unwrap();
});
if let Ok(_) = res {
spawned_cnt += 1;
};
}
// Wait for all clients to exit, but don't wait for the server to exit. The
// server just runs infinitely.
drop(tx);
for _ in 0..spawn... | {
let _ = stream.write(&[1]);
let _ = stream.read(&mut [0]);
} | conditional_block |
tcp-stress.rs | // run-pass
// ignore-android needs extra network permissions
// ignore-emscripten no threads or sockets support
// ignore-netbsd system ulimit (Too many open files)
// ignore-openbsd system ulimit (Too many open files)
use std::io::prelude::*;
use std::net::{TcpListener, TcpStream};
use std::process;
use std::sync::m... | () {
// This test has a chance to time out, try to not let it time out
thread::spawn(move|| -> () {
thread::sleep(Duration::from_secs(30));
process::exit(1);
});
let listener = TcpListener::bind("127.0.0.1:0").unwrap();
let addr = listener.local_addr().unwrap();
thread::spawn(mo... | main | identifier_name |
issue-13304.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 ... | } | random_line_split | |
issue-13304.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | () {
let args: Vec<String> = env::args().collect();
if args.len() > 1 && args[1] == "child" {
child();
} else {
parent();
}
}
fn parent() {
let args: Vec<String> = env::args().collect();
let mut p = Command::new(&args[0]).arg("child")
.stdout(Stdio::captur... | main | identifier_name |
issue-13304.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 ... |
}
fn parent() {
let args: Vec<String> = env::args().collect();
let mut p = Command::new(&args[0]).arg("child")
.stdout(Stdio::capture())
.stdin(Stdio::capture())
.spawn().unwrap();
p.stdin.as_mut().unwrap().write_all(b"test1\ntest2\ntest... | {
parent();
} | conditional_block |
issue-13304.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 ... |
fn parent() {
let args: Vec<String> = env::args().collect();
let mut p = Command::new(&args[0]).arg("child")
.stdout(Stdio::capture())
.stdin(Stdio::capture())
.spawn().unwrap();
p.stdin.as_mut().unwrap().write_all(b"test1\ntest2\ntest3"... | {
let args: Vec<String> = env::args().collect();
if args.len() > 1 && args[1] == "child" {
child();
} else {
parent();
}
} | identifier_body |
disallow_id_as_alias.rs | /*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
use common::WithLocation;
use errors::validate;
use graphql_ir::{
LinkedField, Program, ScalarField, ValidationError, Validatio... |
}
impl<'s> Validator for DisallowIdAsAlias<'s> {
const NAME: &'static str = "DisallowIdAsAlias";
const VALIDATE_ARGUMENTS: bool = false;
const VALIDATE_DIRECTIVES: bool = false;
fn validate_linked_field(&mut self, field: &LinkedField) -> ValidationResult<()> {
validate!(
if let So... | {
Self {
program,
id_key: "id".intern(),
}
} | identifier_body |
disallow_id_as_alias.rs | /*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
use common::WithLocation;
use errors::validate;
use graphql_ir::{
LinkedField, Program, ScalarField, ValidationError, Validatio... | <'s> {
program: &'s Program<'s>,
id_key: StringKey,
}
impl<'s> DisallowIdAsAlias<'s> {
fn new(program: &'s Program<'s>) -> Self {
Self {
program,
id_key: "id".intern(),
}
}
}
impl<'s> Validator for DisallowIdAsAlias<'s> {
const NAME: &'static str = "Disallow... | DisallowIdAsAlias | identifier_name |
disallow_id_as_alias.rs | /*
* Copyright (c) Facebook, Inc. and its affiliates. |
use common::WithLocation;
use errors::validate;
use graphql_ir::{
LinkedField, Program, ScalarField, ValidationError, ValidationMessage, ValidationResult,
Validator,
};
use interner::{Intern, StringKey};
use schema::{FieldID, Schema};
pub fn disallow_id_as_alias<'s>(program: &Program<'s>) -> ValidationResult<... | *
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/ | random_line_split |
disallow_id_as_alias.rs | /*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
use common::WithLocation;
use errors::validate;
use graphql_ir::{
LinkedField, Program, ScalarField, ValidationError, Validatio... | else {
Ok(())
}
}
}
fn validate_field_alias<'s>(
schema: &'s Schema,
id_key: StringKey,
alias: &WithLocation<StringKey>,
field: FieldID,
) -> ValidationResult<()> {
if alias.item == id_key && schema.field(field).name!= id_key {
Err(vec![ValidationError::new(
... | {
validate_field_alias(
self.program.schema(),
self.id_key,
&alias,
field.definition.item,
)
} | conditional_block |
common.rs | // delila - a desktop version of lila.
//
// Copyright (C) 2017 Lakin Wecker <lakin@wecker.ca>
//
// This program 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 ... |
// General types
pub type UByte = u8;
pub type UShort = u16;
pub type UInt = u32;
pub type SInt = i32;
// Comparison type
pub type Compare = i32;
pub const LESS_THAN: Compare = -1;
pub const EQUAL_TO: Compare = -1;
pub const GREATER_THAN: Compare = -1;
// Piece types
pub type Piece = i8; // e.g ROOK or WHITE_KI... | // Scid common datatypes
//------------------------------------------------------------------------------ | random_line_split |
vlq.rs | //! Implements utilities for dealing with the sourcemap vlq encoding.
use crate::errors::{Error, Result};
const B64_CHARS: &[u8] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
const B64: [i8; 256] = [
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1... |
}
}
#[test]
fn test_vlq_decode() {
let rv = parse_vlq_segment("AAAA").unwrap();
assert_eq!(rv, vec![0, 0, 0, 0]);
let rv = parse_vlq_segment("GAAIA").unwrap();
assert_eq!(rv, vec![3, 0, 0, 4, 0]);
}
#[test]
fn test_vlq_encode() {
let rv = generate_vlq_segment(&[0, 0, 0, 0]).unwrap();
asse... | {
break;
} | conditional_block |
vlq.rs | //! Implements utilities for dealing with the sourcemap vlq encoding.
use crate::errors::{Error, Result};
const B64_CHARS: &[u8] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
const B64: [i8; 256] = [
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1... |
#[test]
fn test_vlq_encode() {
let rv = generate_vlq_segment(&[0, 0, 0, 0]).unwrap();
assert_eq!(rv.as_str(), "AAAA");
let rv = generate_vlq_segment(&[3, 0, 0, 4, 0]).unwrap();
assert_eq!(rv.as_str(), "GAAIA");
}
#[test]
fn test_overflow() {
match parse_vlq_segment("00000000000000") {
Err... | {
let rv = parse_vlq_segment("AAAA").unwrap();
assert_eq!(rv, vec![0, 0, 0, 0]);
let rv = parse_vlq_segment("GAAIA").unwrap();
assert_eq!(rv, vec![3, 0, 0, 4, 0]);
} | identifier_body |
vlq.rs | //! Implements utilities for dealing with the sourcemap vlq encoding.
use crate::errors::{Error, Result};
const B64_CHARS: &[u8] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
const B64: [i8; 256] = [
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1... | -1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
62,
-1,
-1,
-1,
63,
52,
53,
54,
55,
56,
57,
58,
59,
60,
61,
-1,
-1,
... | -1,
-1,
-1, | random_line_split |
vlq.rs | //! Implements utilities for dealing with the sourcemap vlq encoding.
use crate::errors::{Error, Result};
const B64_CHARS: &[u8] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
const B64: [i8; 256] = [
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1... | () {
let rv = generate_vlq_segment(&[0, 0, 0, 0]).unwrap();
assert_eq!(rv.as_str(), "AAAA");
let rv = generate_vlq_segment(&[3, 0, 0, 4, 0]).unwrap();
assert_eq!(rv.as_str(), "GAAIA");
}
#[test]
fn test_overflow() {
match parse_vlq_segment("00000000000000") {
Err(Error::VlqOverflow) => {}
... | test_vlq_encode | identifier_name |
item_type.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 fmt::String for ItemType {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
self.to_static_str().fmt(f)
}
}
| {
match *self {
ItemType::Module => "mod",
ItemType::Struct => "struct",
ItemType::Enum => "enum",
ItemType::Function => "fn",
ItemType::Typedef => "type",
ItemType::Static => "static",
... | identifier_body |
item_type.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 ... | clean::ForeignFunctionItem(..) => ItemType::Function, // no ForeignFunction
clean::ForeignStaticItem(..) => ItemType::Static, // no ForeignStatic
clean::MacroItem(..) => ItemType::Macro,
clean::PrimitiveItem(..) => ItemType::Primitive,
clean:... | clean::TyMethodItem(..) => ItemType::TyMethod,
clean::MethodItem(..) => ItemType::Method,
clean::StructFieldItem(..) => ItemType::StructField,
clean::VariantItem(..) => ItemType::Variant, | random_line_split |
item_type.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 ... | (&self, f: &mut fmt::Formatter) -> fmt::Result {
self.to_static_str().fmt(f)
}
}
| fmt | identifier_name |
challenge5.rs | use super::challenge2::xor_bytes;
pub fn | (data: &Vec<u8>, key: &Vec<u8>) -> Vec<u8> {
xor_bytes(data, &key.iter().cloned().cycle().take(data.len()).collect())
}
#[cfg(test)]
mod test {
use super::super::shared::bytes_to_hex_string;
use super::encode;
#[test]
fn test_encode() {
let input = b"Burning 'em, if you ain't quick and nim... | encode | identifier_name |
challenge5.rs | use super::challenge2::xor_bytes;
pub fn encode(data: &Vec<u8>, key: &Vec<u8>) -> Vec<u8> |
#[cfg(test)]
mod test {
use super::super::shared::bytes_to_hex_string;
use super::encode;
#[test]
fn test_encode() {
let input = b"Burning 'em, if you ain't quick and nimble
I go crazy when I hear a cymbal";
let output = String::from("0b3637272a2b2e63622c2e69692a23693a2a3c6324202d623d... | {
xor_bytes(data, &key.iter().cloned().cycle().take(data.len()).collect())
} | identifier_body |
challenge5.rs | use super::challenge2::xor_bytes; |
#[cfg(test)]
mod test {
use super::super::shared::bytes_to_hex_string;
use super::encode;
#[test]
fn test_encode() {
let input = b"Burning 'em, if you ain't quick and nimble
I go crazy when I hear a cymbal";
let output = String::from("0b3637272a2b2e63622c2e69692a23693a2a3c6324202d623d6... |
pub fn encode(data: &Vec<u8>, key: &Vec<u8>) -> Vec<u8> {
xor_bytes(data, &key.iter().cloned().cycle().take(data.len()).collect())
} | random_line_split |
input_output.rs | //! This module contains code to equate the input/output types appearing
//! in the MIR with the expected input/output types from the function
//! signature. This requires a bit of processing, as the expected types
//! are supplied to us before normalization and may contain opaque
//! `impl Trait` instances. In contras... | (&mut self, a: Ty<'tcx>, b: Ty<'tcx>, span: Span) {
if let Err(_) =
self.eq_types(a, b, Locations::All(span), ConstraintCategory::BoringNoLocation)
{
// FIXME(jackh726): This is a hack. It's somewhat like
// `rustc_traits::normalize_after_erasing_regions`. Ideally, we... | equate_normalized_input_or_output | identifier_name |
input_output.rs | //! This module contains code to equate the input/output types appearing
//! in the MIR with the expected input/output types from the function
//! signature. This requires a bit of processing, as the expected types
//! are supplied to us before normalization and may contain opaque
//! `impl Trait` instances. In contras... | // Instantiate the canonicalized variables from
// user-provided signature (e.g., the `_` in the code
// above) with fresh variables.
let poly_sig = self.instantiate_canonical_with_fresh_inference_vars(
body.span,
... | {
let (&normalized_output_ty, normalized_input_tys) =
normalized_inputs_and_output.split_last().unwrap();
debug!(?normalized_output_ty);
debug!(?normalized_input_tys);
let mir_def_id = body.source.def_id().expect_local();
// If the user explicitly annotated the inp... | identifier_body |
input_output.rs | //! This module contains code to equate the input/output types appearing
//! in the MIR with the expected input/output types from the function
//! signature. This requires a bit of processing, as the expected types
//! are supplied to us before normalization and may contain opaque
//! `impl Trait` instances. In contras... | let user_provided_output_ty =
self.normalize(user_provided_output_ty, Locations::All(output_span));
if let Err(err) = self.eq_opaque_type_and_type(
mir_output_ty,
user_provided_output_ty,
Locations::All(output_span),
... |
// If the user explicitly annotated the output types, enforce those.
// Note that this only happens for closures.
if let Some(user_provided_sig) = user_provided_sig {
let user_provided_output_ty = user_provided_sig.output(); | random_line_split |
input_output.rs | //! This module contains code to equate the input/output types appearing
//! in the MIR with the expected input/output types from the function
//! signature. This requires a bit of processing, as the expected types
//! are supplied to us before normalization and may contain opaque
//! `impl Trait` instances. In contras... | Location::START,
"equate_normalized_input_or_output: `{:?}=={:?}` failed with `{:?}`",
a,
b,
terr
);
}
}
}
pub(crate) fn normalize_and_add_constraints(&mut self, t: Ty<'tcx>)... | {
// FIXME(jackh726): This is a hack. It's somewhat like
// `rustc_traits::normalize_after_erasing_regions`. Ideally, we'd
// like to normalize *before* inserting into `local_decls`, but
// doing so ends up causing some other trouble.
let b = match self.normal... | conditional_block |
cstore.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 ... | (self) -> bool {
match self {
DepKind::UnexportedMacrosOnly | DepKind::MacrosOnly => true,
DepKind::Implicit | DepKind::Explicit => false,
}
}
}
#[derive(PartialEq, Clone, Debug)]
pub enum LibSource {
Some(PathBuf),
MetadataOnly,
None,
}
impl LibSource {
pub... | macros_only | identifier_name |
cstore.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 ... |
}
};
Some((cnum, path))
})
.collect::<Vec<_>>();
let mut ordering = tcx.postorder_cnums(LOCAL_CRATE);
Lrc::make_mut(&mut ordering).reverse();
libs.sort_by_cached_key(|&(a, _)| {
ordering.iter().position(|x| *x == a)
});
libs
}
| {
LibSource::None
} | conditional_block |
cstore.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 ... |
}
#[derive(PartialEq, Clone, Debug)]
pub enum LibSource {
Some(PathBuf),
MetadataOnly,
None,
}
impl LibSource {
pub fn is_some(&self) -> bool {
if let LibSource::Some(_) = *self {
true
} else {
false
}
}
pub fn option(&self) -> Option<PathBuf> ... | {
match self {
DepKind::UnexportedMacrosOnly | DepKind::MacrosOnly => true,
DepKind::Implicit | DepKind::Explicit => false,
}
} | identifier_body |
cstore.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 ... | })
.collect::<Vec<_>>();
let mut ordering = tcx.postorder_cnums(LOCAL_CRATE);
Lrc::make_mut(&mut ordering).reverse();
libs.sort_by_cached_key(|&(a, _)| {
ordering.iter().position(|x| *x == a)
});
libs
} | LibSource::None
}
}
};
Some((cnum, path)) | random_line_split |
ast.rs | // Copyright 2015 Pierre Talbot (IRCAM)
// 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... | <Node, R, V:?Sized>(visitor: &mut V, parent: &Box<Node>) -> R where
Node: ExprNode,
V: Visitor<Node, R>
{
use self::Expression_::*;
match parent.expr_node() {
&StrLiteral(ref lit) => {
visitor.visit_str_literal(parent, lit)
}
&AnySingleChar => {
visitor.visit_any_single_char(parent)
... | walk_expr | identifier_name |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.