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 |
|---|---|---|---|---|
ffz.rs | use std;
use serde_json;
use serde;
use std::io::Read;
use emote;
use emote::{EmoteError,JsonError};
use http;
const CHANNEL_URL:&str = "https://api.frankerfacez.com/v1/room/";
const GLOBAL_URL:&str = "https://api.frankerfacez.com/v1/set/global";
pub struct Emote<'a>{
http: &'a http::Http,
}
#[derive(Serialize,... |
let ref sets = v["sets"];
let ref set_id = sets[default_sets[0].to_string()];
let set: Set_id= try_map!(serde_json::from_value(set_id.clone()),EmoteError::Json(JsonError::ParseError));
Ok(set.emoticons)
}
}
impl emote::Emote for Emoticon{
fn name(&self)->&str{
&self.n... | {
return Err(EmoteError::Json(JsonError::ParseError))
} | conditional_block |
eip150_state.rs | // Copyright 2015, 2016 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 la... | (json_data: &[u8]) -> Vec<String> {
json_chain_test(json_data, ChainEra::Eip150)
}
declare_test!{StateTests_EIP150_stEIPSpecificTest, "StateTests/EIP150/stEIPSpecificTest"}
declare_test!{StateTests_EIP150_stEIPsingleCodeGasPrices, "StateTests/EIP150/stEIPsingleCodeGasPrices"}
declare_test!{StateTests_EIP150_stMemExpa... | do_json_test | identifier_name |
eip150_state.rs | // Copyright 2015, 2016 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 la... |
declare_test!{StateTests_EIP150_stEIPSpecificTest, "StateTests/EIP150/stEIPSpecificTest"}
declare_test!{StateTests_EIP150_stEIPsingleCodeGasPrices, "StateTests/EIP150/stEIPsingleCodeGasPrices"}
declare_test!{StateTests_EIP150_stMemExpandingEIPCalls, "StateTests/EIP150/stMemExpandingEIPCalls"}
declare_test!{StateTests... | use super::state::json_chain_test;
fn do_json_test(json_data: &[u8]) -> Vec<String> {
json_chain_test(json_data, ChainEra::Eip150)
} | random_line_split |
eip150_state.rs | // Copyright 2015, 2016 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 la... |
declare_test!{StateTests_EIP150_stEIPSpecificTest, "StateTests/EIP150/stEIPSpecificTest"}
declare_test!{StateTests_EIP150_stEIPsingleCodeGasPrices, "StateTests/EIP150/stEIPsingleCodeGasPrices"}
declare_test!{StateTests_EIP150_stMemExpandingEIPCalls, "StateTests/EIP150/stMemExpandingEIPCalls"}
declare_test!{StateTest... | {
json_chain_test(json_data, ChainEra::Eip150)
} | identifier_body |
aaaa.rs | /*
* Copyright (C) 2015 Benjamin Fry <benjaminfry@me.com>
*
* 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 ap... | () -> Vec<(Ipv6Addr, Vec<u8>)> {
vec![
(
Ipv6Addr::from_str("::").unwrap(),
vec![0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
), // base case
(
Ipv6Addr::from_str("1::").unwrap(),
vec![0, 1, 0, 0, 0, 0, 0, 0,... | get_data | identifier_name |
aaaa.rs | /*
* Copyright (C) 2015 Benjamin Fry <benjaminfry@me.com>
*
* 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 ap... | encoder.emit_u16(segments[6])?;
encoder.emit_u16(segments[7])?;
Ok(())
}
#[cfg(test)]
mod tests {
use std::net::Ipv6Addr;
use std::str::FromStr;
use super::*;
use crate::serialize::binary::bin_tests::{test_emit_data_set, test_read_data_set};
fn get_data() -> Vec<(Ipv6Addr, Vec<u8>)> {... | random_line_split | |
aaaa.rs | /*
* Copyright (C) 2015 Benjamin Fry <benjaminfry@me.com>
*
* 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 ap... |
#[test]
fn test_emit() {
test_emit_data_set(get_data(), |e, d| emit(e, &d));
}
}
| {
test_read_data_set(get_data(), |ref mut d| read(d));
} | identifier_body |
lib.rs | #![cfg_attr(feature = "clippy", feature(plugin))]
#![cfg_attr(feature = "clippy", plugin(clippy))]
extern crate clang;
extern crate directories;
#[macro_use]
extern crate failure;
extern crate glob;
#[macro_use]
extern crate lazy_static;
#[macro_use]
extern crate log;
extern crate python_parser;
extern crate regex;
ex... | (&self) -> Fallible<()> {
if let Some(project_path_s) = self.project_dir.to_str() {
info!("Starting project analysis at '{}'", project_path_s);
}
if self.project_dir.is_dir() {
// Project path is a directory, thus it is neccessay to traverse to the project
//... | analyze_project | identifier_name |
lib.rs | #![cfg_attr(feature = "clippy", feature(plugin))]
#![cfg_attr(feature = "clippy", plugin(clippy))]
extern crate clang;
extern crate directories;
#[macro_use]
extern crate failure;
extern crate glob;
#[macro_use]
extern crate lazy_static;
#[macro_use]
extern crate log;
extern crate python_parser;
extern crate regex;
ex... | pub mod stubs;
pub mod synthesis;
pub mod value_parser;
use analysis::{Analysis, ProjectFile};
use directories::BaseDirs;
use failure::{err_msg, Fallible};
use language_type::LanguageType;
use project_parameters::ProjectParameters;
use std::path::PathBuf;
use synthesis::*;
////////////////////////////////////////////... | pub mod analysis;
pub mod entity;
pub mod language_type;
pub mod project_parameters; | random_line_split |
lib.rs | #![cfg_attr(feature = "clippy", feature(plugin))]
#![cfg_attr(feature = "clippy", plugin(clippy))]
extern crate clang;
extern crate directories;
#[macro_use]
extern crate failure;
extern crate glob;
#[macro_use]
extern crate lazy_static;
#[macro_use]
extern crate log;
extern crate python_parser;
extern crate regex;
ex... |
Ok(())
}
/// Traverses upwared through the `seed_dir`s parent directories until
/// `thinline.yml` configuration exists in dir or home directory is reached.
fn find_thinline_config_dir<'a>(seed_dir: &'a PathBuf, config_name: &str) -> Option<PathBuf> {
if let Some(base_dirs) = BaseDirs... | {
self.project_parameters.build_script.run(&self.project_dir)?;
} | conditional_block |
lib.rs | #![cfg_attr(feature = "clippy", feature(plugin))]
#![cfg_attr(feature = "clippy", plugin(clippy))]
extern crate clang;
extern crate directories;
#[macro_use]
extern crate failure;
extern crate glob;
#[macro_use]
extern crate lazy_static;
#[macro_use]
extern crate log;
extern crate python_parser;
extern crate regex;
ex... | self.analysis
.project_files_mut()
.push(ProjectFile::new(&self.project_dir));
}
}
}
self.analysis.extract_entities()?;
Ok(())
}
/// Starts the synthesis of the target projects test files.
... | {
if let Some(project_path_s) = self.project_dir.to_str() {
info!("Starting project analysis at '{}'", project_path_s);
}
if self.project_dir.is_dir() {
// Project path is a directory, thus it is neccessay to traverse to the project
// and collect all the sou... | identifier_body |
day1.rs | use get_input::get_input;
#[derive(Copy, Clone)]
enum Rotation {
Left,
Right,
}
impl Rotation {
fn from_char(c: char) -> Option<Rotation> {
match c {
'L' => Some(Rotation::Left),
'R' => Some(Rotation::Right),
_ => None,
}
}
}
#[derive(Copy, Clone)]
... | {
x: i32,
y: i32,
}
impl Position {
fn move_by(self, dir: Direction, dist: i32) -> Position {
match dir {
Direction::North => Position { x: self.x, y: self.y + dist },
Direction::East => Position { x: self.x + dist, y: self.y },
Direction::South => Position { x:... | Position | identifier_name |
day1.rs | use get_input::get_input;
#[derive(Copy, Clone)]
enum Rotation {
Left,
Right,
}
impl Rotation {
fn from_char(c: char) -> Option<Rotation> {
match c {
'L' => Some(Rotation::Left),
'R' => Some(Rotation::Right),
_ => None,
}
}
}
#[derive(Copy, Clone)]
... |
pub fn solve() {
let input = get_input("assets/day/1/input");
//let input = "R8, R4, R4, R8";
let mut position = Position { x: 0, y: 0 };
let mut direction = Direction::North;
for movement in input.split(',') {
let (rotation, distance) = parse_movement(&movement);
direction = dire... | {
let mut m = m.trim().chars();
let rotation = m.next().expect("Could not read input");
let rotation = Rotation::from_char(rotation).unwrap();
let distance = m.as_str().parse::<i32>().expect("Could not read integer in input");
(rotation, distance)
} | identifier_body |
day1.rs | use get_input::get_input;
#[derive(Copy, Clone)]
enum Rotation {
Left,
Right,
}
impl Rotation {
fn from_char(c: char) -> Option<Rotation> {
match c {
'L' => Some(Rotation::Left),
'R' => Some(Rotation::Right),
_ => None,
}
}
}
#[derive(Copy, Clone)]
... |
for movement in input.split(',') {
let (rotation, distance) = parse_movement(&movement);
direction = direction.rotate(rotation);
position = position.move_by(direction, distance);
// Print Logo commands to draw the path,
// turned out the first repeated position was easy to ... | pub fn solve() {
let input = get_input("assets/day/1/input");
//let input = "R8, R4, R4, R8";
let mut position = Position { x: 0, y: 0 };
let mut direction = Direction::North; | random_line_split |
day_5.rs | use std::iter::Peekable;
use std::str::Chars;
pub fn evaluate(line: &str) -> f32 {
evaluate_iter(&mut line.chars().peekable())
}
fn evaluate_iter(iter: &mut Peekable<Chars>) -> f32 {
let mut accumulator = parse_term(iter.by_ref());
while iter.peek().is_some() {
let sign = iter.peek().cloned();
... | else {
accumulator = accumulator*10.0 + v;
}
},
_ => break,
}
}
accumulator
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_evaluate_simple_number() {
assert_eq!(evaluate("1"), 1.0);
}
#[te... | accumulator += v * exponent;
exponent *= 0.1;
}
| conditional_block |
day_5.rs | use std::iter::Peekable;
use std::str::Chars;
pub fn evaluate(line: &str) -> f32 {
evaluate_iter(&mut line.chars().peekable())
}
fn evaluate_iter(iter: &mut Peekable<Chars>) -> f32 {
let mut accumulator = parse_term(iter.by_ref());
while iter.peek().is_some() {
let sign = iter.peek().cloned();
... | assert_eq!(evaluate("2×2"), 4.0);
}
#[test]
fn test_evaluate_div() {
assert_eq!(evaluate("22÷2"), 11.0);
}
#[test]
fn test_two_adds() {
assert_eq!(evaluate("2+3+6"), 11.0);
}
#[test]
fn test_two_subs() {
assert_eq!(evaluate("6-4-1"), 1.0);
}
... | assert_eq!(evaluate("2-1"), 1.0);
}
#[test]
fn test_evaluate_mul() { | random_line_split |
day_5.rs | use std::iter::Peekable;
use std::str::Chars;
pub fn evaluate(line: &str) -> f32 {
evaluate_iter(&mut line.chars().peekable())
}
fn evaluate_iter(iter: &mut Peekable<Chars>) -> f32 {
let mut accumulator = parse_term(iter.by_ref());
while iter.peek().is_some() {
let sign = iter.peek().cloned();
... |
assert_eq!(evaluate("6-4-1"), 1.0);
}
#[test]
fn test_operation_with_different_priority() {
assert_eq!(evaluate("2+3×2"), 8.0);
}
}
| _two_subs() { | identifier_name |
day_5.rs | use std::iter::Peekable;
use std::str::Chars;
pub fn evaluate(line: &str) -> f32 {
evaluate_iter(&mut line.chars().peekable())
}
fn evaluate_iter(iter: &mut Peekable<Chars>) -> f32 {
let mut accumulator = parse_term(iter.by_ref());
while iter.peek().is_some() {
let sign = iter.peek().cloned();
... | #[test]
fn test_evaluate_big_number() {
assert_eq!(evaluate("100"), 100.0);
}
#[test]
fn test_evaluate_real_number() {
assert_eq!(evaluate("1.09"), 1.09)
}
#[test]
fn test_evaluate_add() {
assert_eq!(evaluate("1.09+1.01"), 2.1);
}
#[test]
fn test_ev... | assert_eq!(evaluate("1"), 1.0);
}
| identifier_body |
reporter.rs | use std::io::{self,Write};
use std::fmt::Debug;
use world_result::WorldResult;
#[derive(Debug)]
pub struct ProgressReporter;
pub trait Reporter: Debug {
fn example_failed(&self) -> Result<(), Box<::std::error::Error>>;
fn example_passed(&self) -> Result<(), Box<::std::error::Error>>;
fn report_result(&se... |
fn example_passed(&self) -> Result<(), Box<::std::error::Error>> {
print!("{}", colorize(".", Colors::Green));
io::stdout().flush().map_err(|e| e.into())
}
fn report_result(&self, result: &WorldResult) -> Result<(), Box<::std::error::Error>> {
println!("");
println!("Suite... | {
print!("{}", colorize("F", Colors::Red));
io::stdout().flush().map_err(|e| e.into())
} | identifier_body |
reporter.rs | use std::io::{self,Write};
use std::fmt::Debug;
use world_result::WorldResult;
#[derive(Debug)]
pub struct ProgressReporter;
pub trait Reporter: Debug {
fn example_failed(&self) -> Result<(), Box<::std::error::Error>>;
fn example_passed(&self) -> Result<(), Box<::std::error::Error>>;
fn report_result(&se... | };
io::stdout().flush().map_err(|e| e.into())
}
} | println!(" - {}", example);
} | random_line_split |
reporter.rs | use std::io::{self,Write};
use std::fmt::Debug;
use world_result::WorldResult;
#[derive(Debug)]
pub struct ProgressReporter;
pub trait Reporter: Debug {
fn example_failed(&self) -> Result<(), Box<::std::error::Error>>;
fn example_passed(&self) -> Result<(), Box<::std::error::Error>>;
fn report_result(&se... | {
Green,
Red,
}
fn colorize(string: &str, color: Colors) -> String {
let code = pick_code(color);
format!("\x1B[{}m{}\x1b[0m", code, string)
}
fn pick_code(color: Colors) -> &'static str {
match color {
Colors::Green => "32",
Colors::Red => "31",
}
}
impl Reporter for Progres... | Colors | identifier_name |
table.rs | // Copyright 2017 Robert L Snyder, Ithaca, NY <zoltatech@gmail.com>
// <robscary@gmail.com> | // 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 writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOU... | //
// Licensed under the Apache License, Version 2.0 (the "License"); | random_line_split |
table.rs | // Copyright 2017 Robert L Snyder, Ithaca, NY <zoltatech@gmail.com>
// <robscary@gmail.com>
//
// 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
//... | else {
try!(read_table_header(self, &mut file));
}
Ok(file)
}
}
| {
try!(create_table_header(self, &mut file));
} | conditional_block |
table.rs | // Copyright 2017 Robert L Snyder, Ithaca, NY <zoltatech@gmail.com>
// <robscary@gmail.com>
//
// 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
//... | (table_name: String, path: String) -> Table {
Table{table_name: table_name, file_path: path, record_length: 0,
record_count: 0, first_record_pointer: 0, fields: vec![]}
}
pub fn open(&mut self) -> Result<File, Box<Error>> {
let path = Path::new(&self.file_path).join(&self.table_nam... | new | identifier_name |
table.rs | // Copyright 2017 Robert L Snyder, Ithaca, NY <zoltatech@gmail.com>
// <robscary@gmail.com>
//
// 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
//... |
pub fn open(&mut self) -> Result<File, Box<Error>> {
let path = Path::new(&self.file_path).join(&self.table_name);
let mut file =
OpenOptions::new().read(true).write(true).create(true).open(path)
.expect("Could not open table");
if try!(get_table_size(&mut file)) =... | {
Table{table_name: table_name, file_path: path, record_length: 0,
record_count: 0, first_record_pointer: 0, fields: vec![]}
} | identifier_body |
mod.rs | use validation::*;
use ::time::Duration;
pub mod time;
pub mod expiry;
pub mod not_before;
| /// Use positive grace periods to be lenient.
/// Use negative grace periods e.g. to renew tokens ahead of time.
pub fn claims_verifier<C,T>(tp: T, exp_grace: Duration, nbf_grace: Duration) -> ValidationSchema<C>
where C: expiry::ExpiryClaim + not_before::NotBeforeClaim +'static,
T: time::TimePro... | /// Constructs a set of validation rules for the
/// exp and nbf claims for the type being validated.
/// Pass in exp and nbf claim grace period durations to adjust time comparisons. | random_line_split |
mod.rs | use validation::*;
use ::time::Duration;
pub mod time;
pub mod expiry;
pub mod not_before;
/// Constructs a set of validation rules for the
/// exp and nbf claims for the type being validated.
/// Pass in exp and nbf claim grace period durations to adjust time comparisons.
/// Use positive grace periods to be lenient... | <C,T>(tp: T, exp_grace: Duration, nbf_grace: Duration) -> ValidationSchema<C>
where C: expiry::ExpiryClaim + not_before::NotBeforeClaim +'static,
T: time::TimeProvider + Clone +'static {
let mut vs: ValidationSchema<C> = ValidationSchema::new();
vs.rule(Box::new(expiry::ExpiryVerifie... | claims_verifier | identifier_name |
mod.rs | use validation::*;
use ::time::Duration;
pub mod time;
pub mod expiry;
pub mod not_before;
/// Constructs a set of validation rules for the
/// exp and nbf claims for the type being validated.
/// Pass in exp and nbf claim grace period durations to adjust time comparisons.
/// Use positive grace periods to be lenient... |
} | {
let now = UTC::now();
let tp = FixedTimeProvider(now);
let claims = JwtClaims::new();
let mut vs: ValidationSchema<JwtClaims> = claims_verifier(tp, Duration::zero(), Duration::zero());
vs.validate(&claims).unwrap();
} | identifier_body |
lib.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#![feature(alloc)]
#![feature(plugin)]
#![feature(box_syntax)]
#![feature(core)]
#![feature(collections)]
#![featu... | extern crate lazy_static;
extern crate num;
extern crate util;
pub mod stylesheets;
pub mod parser;
pub mod selector_matching;
#[macro_use] pub mod values;
// Generated from the properties.mako.rs template by build.rs
#[macro_use]
pub mod properties {
include!(concat!(env!("OUT_DIR"), "/properties.rs"));
}
pub... | extern crate rustc_serialize;
extern crate string_cache;
extern crate selectors;
#[macro_use] | random_line_split |
job.rs | use ckb_jsonrpc_types::BlockTemplate;
use ckb_types::packed::Block;
use ckb_types::{
prelude::*,
utilities::compact_to_target,
};
use ckb_types::{H256, U256};
use serde::{Deserialize, Serialize};
use std::collections::{BTreeMap, HashMap};
use std::time::Instant;
#[derive(Clone, Serialize)]
pub struct MiningJob... |
pub fn on_solved_share(&self, solved_share: &SolvedShare) -> Option<&MiningJob> {
self.jobs.get(&solved_share.pow_hash)
}
fn insert_job(&mut self, job: &MiningJob) {
if let Some(old_hash) = self
.hashes
.insert(job.job_time.clone(), job.pow_hash.clone())
{
... | {
let job: MiningJob = block_template.into();
self.insert_job(&job);
self.clean_jobs();
job
} | identifier_body |
job.rs | use ckb_jsonrpc_types::BlockTemplate;
use ckb_types::packed::Block;
use ckb_types::{
prelude::*,
utilities::compact_to_target,
};
use ckb_types::{H256, U256};
use serde::{Deserialize, Serialize};
use std::collections::{BTreeMap, HashMap};
use std::time::Instant;
#[derive(Clone, Serialize)]
pub struct MiningJob... | .map(|(job_time, hash)| (job_time.clone(), hash.clone()))
.collect();
removables.iter().for_each(|(job_time, hash)| {
self.hashes.remove(job_time);
self.jobs.remove(hash);
})
}
} | .take(self.hashes.len().saturating_sub(256)) | random_line_split |
job.rs | use ckb_jsonrpc_types::BlockTemplate;
use ckb_types::packed::Block;
use ckb_types::{
prelude::*,
utilities::compact_to_target,
};
use ckb_types::{H256, U256};
use serde::{Deserialize, Serialize};
use std::collections::{BTreeMap, HashMap};
use std::time::Instant;
#[derive(Clone, Serialize)]
pub struct MiningJob... | (&mut self, block_template: BlockTemplate) -> MiningJob {
let job: MiningJob = block_template.into();
self.insert_job(&job);
self.clean_jobs();
job
}
pub fn on_solved_share(&self, solved_share: &SolvedShare) -> Option<&MiningJob> {
self.jobs.get(&solved_share.pow_hash)
... | on_block_template | identifier_name |
job.rs | use ckb_jsonrpc_types::BlockTemplate;
use ckb_types::packed::Block;
use ckb_types::{
prelude::*,
utilities::compact_to_target,
};
use ckb_types::{H256, U256};
use serde::{Deserialize, Serialize};
use std::collections::{BTreeMap, HashMap};
use std::time::Instant;
#[derive(Clone, Serialize)]
pub struct MiningJob... |
if let Some(old_job) = self.jobs.insert(job.pow_hash.clone(), job.clone()) {
self.hashes.remove(&old_job.job_time);
}
}
fn clean_jobs(&mut self) {
let removables: Vec<(Instant, H256)> = self
.hashes
.iter()
.take(self.hashes.len().saturating... | {
self.jobs.remove(&old_hash);
} | conditional_block |
issue-21475.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 ... | m::START..=m::END => {},
0..=m::END => {},
m::START..=59 => {},
_ => {},
}
}
mod m {
pub const START: u32 = 4;
pub const END: u32 = 14;
} | use m::{START, END};
fn main() {
match 42 { | random_line_split |
issue-21475.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 ... | ,
}
}
mod m {
pub const START: u32 = 4;
pub const END: u32 = 14;
}
| {} | conditional_block |
issue-21475.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 ... | () {
match 42 {
m::START..=m::END => {},
0..=m::END => {},
m::START..=59 => {},
_ => {},
}
}
mod m {
pub const START: u32 = 4;
pub const END: u32 = 14;
}
| main | identifier_name |
issue-21475.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 ... |
mod m {
pub const START: u32 = 4;
pub const END: u32 = 14;
}
| {
match 42 {
m::START..=m::END => {},
0..=m::END => {},
m::START..=59 => {},
_ => {},
}
} | identifier_body |
sync_provider.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... |
}
| {
map![
1.into() => TransactionStats {
first_seen: 10,
propagated_to: map![
128.into() => 16
],
},
5.into() => TransactionStats {
first_seen: 16,
propagated_to: map![
16.into() => 1
],
}
]
} | identifier_body |
sync_provider.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... |
//! Test implementation of SyncProvider.
use std::collections::BTreeMap;
use bigint::hash::H256;
use parking_lot::RwLock;
use ethsync::{SyncProvider, EthProtocolInfo, SyncStatus, SyncState, PeerInfo, TransactionStats};
/// TestSyncProvider config.
pub struct Config {
/// Protocol version.
pub network_id: u64,
///... |
// You should have received a copy of the GNU General Public License
// along with Parity. If not, see <http://www.gnu.org/licenses/>. | random_line_split |
sync_provider.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... | (&self, count: u64) {
let mut status = self.status.write();
let current_number = status.last_imported_block_number.unwrap_or(0);
status.last_imported_block_number = Some(current_number + count);
}
}
impl SyncProvider for TestSyncProvider {
fn status(&self) -> SyncStatus {
self.status.read().clone()
}
fn ... | increase_imported_block_number | identifier_name |
process_mutex.rs | #[cfg(not(target_os = "windows"))]
use std::path::PathBuf;
#[cfg(not(target_os = "windows"))]
extern crate nix;
#[cfg(not(target_os = "windows"))]
use self::nix::fcntl::FcntlArg::F_SETLK;
#[cfg(not(target_os = "windows"))]
use self::nix::fcntl::{flock, FlockArg};
#[cfg(not(target_os = "windows"))]
use self::nix::fcnt... | {
handle: std::os::windows::raw::HANDLE,
}
#[cfg(target_os = "windows")]
fn create_mutex(name: &str) -> Result<ProcessMutex, String> {
let name: Vec<u16> = OsStr::new(name)
.encode_wide()
.chain(Some(0))
.collect::<Vec<_>>();
let (err, mutie) = unsafe {
let mutie = CreateMutexW(
ptr::null_mut(),
win... | ProcessMutex | identifier_name |
process_mutex.rs | #[cfg(not(target_os = "windows"))]
use std::path::PathBuf;
#[cfg(not(target_os = "windows"))]
extern crate nix;
#[cfg(not(target_os = "windows"))]
use self::nix::fcntl::FcntlArg::F_SETLK;
#[cfg(not(target_os = "windows"))]
use self::nix::fcntl::{flock, FlockArg};
#[cfg(not(target_os = "windows"))]
use self::nix::fcnt... | use self::nix::unistd;
#[cfg(not(target_os = "windows"))]
use std::os::unix::io::RawFd;
use util;
#[derive(Debug)]
#[cfg(not(target_os = "windows"))]
pub struct ProcessMutex {
handle: RawFd,
}
#[cfg(not(target_os = "windows"))]
fn create_mutex(name: &str) -> Result<ProcessMutex, String> {
let path = format!("/tmp/... | use self::nix::sys::stat::S_IWUSR;
#[cfg(not(target_os = "windows"))] | random_line_split |
process_mutex.rs | #[cfg(not(target_os = "windows"))]
use std::path::PathBuf;
#[cfg(not(target_os = "windows"))]
extern crate nix;
#[cfg(not(target_os = "windows"))]
use self::nix::fcntl::FcntlArg::F_SETLK;
#[cfg(not(target_os = "windows"))]
use self::nix::fcntl::{flock, FlockArg};
#[cfg(not(target_os = "windows"))]
use self::nix::fcnt... | {
// convert name into a filename
let name = util::canon_path(name);
let name = name.replace("/", "_").replace(":", "_").replace(" ", "_");
let name = format!("greycrypt_mutex_{}", name);
create_mutex(&name)
} | identifier_body | |
main.rs | fn main() {
let mut my_struct = MyStruct {
my_field1: 0,
my_field2: 0,
my_field3: 0,
my_field4: 0,
my_field5: 0,
};
my_struct.my_field1 = 7;
assert_eq!(7, my_struct.my_field1);
assert_eq!(0, my_struct.my_field2);
assert_eq!(0, my_struct.my_field3);
a... | {
my_field1: i32,
my_field2: i32,
my_field3: i32,
my_field4: i32,
my_field5: i32,
}
struct MyTupleStruct(i32, i32, f32);
| MyStruct | identifier_name |
main.rs | fn main() {
let mut my_struct = MyStruct {
my_field1: 0,
my_field2: 0,
my_field3: 0,
my_field4: 0,
my_field5: 0,
};
my_struct.my_field1 = 7;
assert_eq!(7, my_struct.my_field1);
assert_eq!(0, my_struct.my_field2);
assert_eq!(0, my_struct.my_field3);
a... | my_field4: i32,
my_field5: i32,
}
struct MyTupleStruct(i32, i32, f32); |
struct MyStruct {
my_field1: i32,
my_field2: i32,
my_field3: i32, | random_line_split |
main.rs | fn main() | assert_eq!(7, my_struct2.my_field1);
assert_eq!(0, my_struct2.my_field2);
assert_eq!(5, my_struct2.my_field3);
assert_eq!(0, my_struct2.my_field4);
assert_eq!(0, my_struct2.my_field5);
let my_tuple_struct = MyTupleStruct(7, 42, 3.14);
assert_eq!(7, my_tuple_struct.0);
assert_eq!(42, my_... | {
let mut my_struct = MyStruct {
my_field1: 0,
my_field2: 0,
my_field3: 0,
my_field4: 0,
my_field5: 0,
};
my_struct.my_field1 = 7;
assert_eq!(7, my_struct.my_field1);
assert_eq!(0, my_struct.my_field2);
assert_eq!(0, my_struct.my_field3);
assert_eq!(... | identifier_body |
code_stats.rs | // Copyright 2016 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 ... | {
pub name: Option<String>,
pub kind: SizeKind,
pub size: u64,
pub align: u64,
pub fields: Vec<FieldInfo>,
}
#[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
pub enum SizeKind {
Exact,
Min,
}
#[derive(Clone, PartialEq, Eq, Hash, Debug)]
pub struct FieldInfo {
pub name: String,
p... | VariantInfo | identifier_name |
code_stats.rs | // Copyright 2016 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 ... | pub struct VariantInfo {
pub name: Option<String>,
pub kind: SizeKind,
pub size: u64,
pub align: u64,
pub fields: Vec<FieldInfo>,
}
#[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
pub enum SizeKind {
Exact,
Min,
}
#[derive(Clone, PartialEq, Eq, Hash, Debug)]
pub struct FieldInfo {
p... | use rustc_target::abi::{Align, Size};
use rustc_data_structures::fx::{FxHashSet};
use std::cmp::{self, Ordering};
#[derive(Clone, PartialEq, Eq, Hash, Debug)] | random_line_split |
normal.rs | // Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | <R: Rng>(&mut self, rng: &mut R) -> f64 { self.ind_sample(rng) }
}
impl IndependentSample<f64> for Normal {
fn ind_sample<R: Rng>(&self, rng: &mut R) -> f64 {
let StandardNormal(n) = rng.gen::<StandardNormal>();
self.mean + self.std_dev * n
}
}
/// The log-normal distribution `ln N(mean, std_d... | sample | identifier_name |
normal.rs | // Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | else { ziggurat_tables::ZIG_NORM_R - x }
}
StandardNormal(ziggurat(
rng,
true, // this is symmetric
&ziggurat_tables::ZIG_NORM_X,
&ziggurat_tables::ZIG_NORM_F,
pdf, zero_case))
}
}
/// The normal distribution `N(mean, std_dev**2)`.
///
/... | { x - ziggurat_tables::ZIG_NORM_R } | conditional_block |
normal.rs | // Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | #[cfg(test)]
mod bench {
extern crate test;
use std::prelude::*;
use self::test::Bencher;
use std::mem::size_of;
use distributions::{Sample};
use super::Normal;
#[bench]
fn rand_normal(b: &mut Bencher) {
let mut rng = ::test::weak_rng();
let mut normal = Normal::new(-2.7... | }
| random_line_split |
normal.rs | // Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... |
}
impl Sample<f64> for LogNormal {
fn sample<R: Rng>(&mut self, rng: &mut R) -> f64 { self.ind_sample(rng) }
}
impl IndependentSample<f64> for LogNormal {
fn ind_sample<R: Rng>(&self, rng: &mut R) -> f64 {
self.norm.ind_sample(rng).exp()
}
}
#[cfg(test)]
mod tests {
use std::prelude::*;
u... | {
assert!(std_dev >= 0.0, "LogNormal::new called with `std_dev` < 0");
LogNormal { norm: Normal::new(mean, std_dev) }
} | identifier_body |
aarch64-modifiers.rs | // min-llvm-version: 10.0.1
// assembly-output: emit-asm
// compile-flags: -O
// compile-flags: --target aarch64-unknown-linux-gnu
// needs-llvm-components: aarch64
#![feature(no_core, lang_items, rustc_attrs)]
#![crate_type = "rlib"]
#![no_core]
#![allow(asm_sub_register)]
#[rustc_builtin_macro]
macro_rules! asm {
... | check!(vreg_low16_s vreg_low16 "ldr {:s}, [x0]");
// CHECK-LABEL: vreg_low16_d:
// CHECK: //APP
// CHECK: ldr d0, [x0]
// CHECK: //NO_APP
check!(vreg_low16_d vreg_low16 "ldr {:d}, [x0]");
// CHECK-LABEL: vreg_low16_q:
// CHECK: //APP
// CHECK: ldr q0, [x0]
// CHECK: //NO_APP
check!(vreg_low16_q vreg_low16 "ldr {:q}, ... | // CHECK-LABEL: vreg_low16_s:
// CHECK: //APP
// CHECK: ldr s0, [x0]
// CHECK: //NO_APP | random_line_split |
bogus-tag.rs | // -*- rust -*-
// 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
// ... | {
let red: color = rgb(255, 0, 0);
match red {
rgb(r, g, b) => { debug!("rgb"); }
hsl(h, s, l) => { debug!("hsl"); }
}
} | identifier_body | |
bogus-tag.rs | // -*- rust -*-
// 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
// ... | { rgb(int, int, int), rgba(int, int, int, int), }
fn main() {
let red: color = rgb(255, 0, 0);
match red {
rgb(r, g, b) => { debug!("rgb"); }
hsl(h, s, l) => { debug!("hsl"); }
}
}
| color | identifier_name |
bogus-tag.rs | // -*- rust -*-
// 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
// ... | }
} | match red {
rgb(r, g, b) => { debug!("rgb"); }
hsl(h, s, l) => { debug!("hsl"); } | random_line_split |
bogus-tag.rs | // -*- rust -*-
// 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
// ... |
hsl(h, s, l) => { debug!("hsl"); }
}
}
| { debug!("rgb"); } | conditional_block |
actor.rs | use store::Store;
use middleware::Middleware;
use empty_state::EmptyState;
pub type ActorState<A> where A: Actor = EmptyState<A::Action>;
pub type ActorStore<A> where A: Actor = Store<ActorState<A>>;
pub trait Actor {
type Action;
fn receive(&mut self, action: Self::Action);
}
struct ActorMiddleware<A> {
... | }
pub fn spawn_actor<A: Actor>(actor: A) -> ActorStore<A> where
A: Send + Sync +'static,
A::Action: Clone + Send + Sync {
let state: EmptyState<A::Action> = EmptyState::new();
let mut store = Store::new(state);
let middleware = ActorMiddleware {
actor: actor
};
store.add_middleware(... | next(action);
} | random_line_split |
actor.rs | use store::Store;
use middleware::Middleware;
use empty_state::EmptyState;
pub type ActorState<A> where A: Actor = EmptyState<A::Action>;
pub type ActorStore<A> where A: Actor = Store<ActorState<A>>;
pub trait Actor {
type Action;
fn receive(&mut self, action: Self::Action);
}
struct ActorMiddleware<A> {
... |
}
pub fn spawn_actor<A: Actor>(actor: A) -> ActorStore<A> where
A: Send + Sync +'static,
A::Action: Clone + Send + Sync {
let state: EmptyState<A::Action> = EmptyState::new();
let mut store = Store::new(state);
let middleware = ActorMiddleware {
actor: actor
};
store.add_middleware... | {
let action_ = action.clone();
self.actor.receive(action_);
next(action);
} | identifier_body |
actor.rs | use store::Store;
use middleware::Middleware;
use empty_state::EmptyState;
pub type ActorState<A> where A: Actor = EmptyState<A::Action>;
pub type ActorStore<A> where A: Actor = Store<ActorState<A>>;
pub trait Actor {
type Action;
fn receive(&mut self, action: Self::Action);
}
struct ActorMiddleware<A> {
... | (&mut self, _store: &mut Store<EmptyState<A::Action>>, next: &mut FnMut(A::Action), action: A::Action) {
let action_ = action.clone();
self.actor.receive(action_);
next(action);
}
}
pub fn spawn_actor<A: Actor>(actor: A) -> ActorStore<A> where
A: Send + Sync +'static,
A::Action: Clo... | dispatch | identifier_name |
tls_input.rs | use super::*;
use crate::flowgger::config::Config;
use crate::flowgger::decoder::Decoder;
use crate::flowgger::encoder::Encoder;
#[cfg(feature = "capnp-recompile")]
use crate::flowgger::splitter::CapnpSplitter;
use crate::flowgger::splitter::{LineSplitter, NulSplitter, Splitter, SyslenSplitter};
use std::io::{stderr, B... |
}
}
}
#[cfg(feature = "capnp-recompile")]
pub fn get_capnp_splitter<T>() -> Box<dyn Splitter<T>>
where
T: std::io::Read,
{
Box::new(CapnpSplitter) as Box<dyn Splitter<_>>
}
#[cfg(not(feature = "capnp-recompile"))]
pub fn get_capnp_splitter() ->! {
panic!("Support for CapNProto is not compiled... | {
let _ = client.set_read_timeout(self.timeout);
let tx = tx.clone();
let (decoder, encoder) = (decoder.clone_boxed(), encoder.clone_boxed());
let tls_config = self.tls_config.clone();
thread::spawn(move || {
handle_clie... | conditional_block |
tls_input.rs | use super::*;
use crate::flowgger::config::Config;
use crate::flowgger::decoder::Decoder;
use crate::flowgger::encoder::Encoder;
#[cfg(feature = "capnp-recompile")]
use crate::flowgger::splitter::CapnpSplitter;
use crate::flowgger::splitter::{LineSplitter, NulSplitter, Splitter, SyslenSplitter};
use std::io::{stderr, B... | }
| {
if let Ok(peer_addr) = client.peer_addr() {
println!("Connection over TLS from [{}]", peer_addr);
}
let sslclient = match tls_config.acceptor.accept(client) {
Err(_) => {
let _ = writeln!(stderr(), "SSL handshake aborted by the client");
return;
}
Ok... | identifier_body |
tls_input.rs | use super::*;
use crate::flowgger::config::Config;
use crate::flowgger::decoder::Decoder;
use crate::flowgger::encoder::Encoder;
#[cfg(feature = "capnp-recompile")]
use crate::flowgger::splitter::CapnpSplitter;
use crate::flowgger::splitter::{LineSplitter, NulSplitter, Splitter, SyslenSplitter};
use std::io::{stderr, B... | #[cfg(not(feature = "capnp-recompile"))]
pub fn get_capnp_splitter() ->! {
panic!("Support for CapNProto is not compiled in")
}
fn handle_client(
client: TcpStream,
tx: SyncSender<Vec<u8>>,
decoder: Box<dyn Decoder>,
encoder: Box<dyn Encoder>,
tls_config: TlsConfig,
) {
if let Ok(peer_addr)... | random_line_split | |
tls_input.rs | use super::*;
use crate::flowgger::config::Config;
use crate::flowgger::decoder::Decoder;
use crate::flowgger::encoder::Encoder;
#[cfg(feature = "capnp-recompile")]
use crate::flowgger::splitter::CapnpSplitter;
use crate::flowgger::splitter::{LineSplitter, NulSplitter, Splitter, SyslenSplitter};
use std::io::{stderr, B... | (
client: TcpStream,
tx: SyncSender<Vec<u8>>,
decoder: Box<dyn Decoder>,
encoder: Box<dyn Encoder>,
tls_config: TlsConfig,
) {
if let Ok(peer_addr) = client.peer_addr() {
println!("Connection over TLS from [{}]", peer_addr);
}
let sslclient = match tls_config.acceptor.accept(clie... | handle_client | identifier_name |
static-mut-not-pat.rs | // Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | static mut STATIC_MUT_FOO: Foo = Foo { bar: Some(West), baz: NEW_FALSE };
fn mutable_statics() {
match (Foo { bar: Some(North), baz: NewBool(true) }) {
Foo { bar: None, baz: NewBool(true) } => (),
STATIC_MUT_FOO => (),
//~^ ERROR static variables cannot be referenced in a pattern
Fo... | }
| random_line_split |
static-mut-not-pat.rs | // Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | (bool);
enum Direction {
North,
East,
South,
West
}
const NEW_FALSE: NewBool = NewBool(false);
struct Foo {
bar: Option<Direction>,
baz: NewBool
}
static mut STATIC_MUT_FOO: Foo = Foo { bar: Some(West), baz: NEW_FALSE };
fn mutable_statics() {
match (Foo { bar: Some(North), baz: NewBool(tr... | NewBool | identifier_name |
page.rs | use std::convert;
use std::fmt;
use std::path::{Path, PathBuf};
use serde_json::{self, Value};
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct Slug {
slug: String,
}
impl Slug {
pub fn new(slug: String) -> Self {
Slug { slug: slug }
}
pub fn create_output_path(&self, prefix: &Path, pr... |
}
impl fmt::Display for Slug {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", &self.slug)
}
}
pub struct Page {
pub source_path: PathBuf,
pub slug: Slug,
pub body: String,
pub theme_config: serde_json::map::Map<String, Value>,
}
impl Page {
pub fn title(&s... | {
&self.slug
} | identifier_body |
page.rs | use std::convert;
use std::fmt;
use std::path::{Path, PathBuf};
use serde_json::{self, Value};
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct Slug {
slug: String,
}
impl Slug {
pub fn new(slug: String) -> Self {
Slug { slug: slug }
}
pub fn create_output_path(&self, prefix: &Path, pr... | else {
0
};
self.slug.matches('/').count() + modifier
}
pub fn path_to(&self, dest: &str, pretty_url: bool) -> String {
let slug_prefix = "../".repeat(self.depth(pretty_url));
format!("{}{}", slug_prefix, dest)
}
}
impl convert::AsRef<str> for Slug {
fn as... | {
1
} | conditional_block |
page.rs | use std::convert;
use std::fmt;
use std::path::{Path, PathBuf};
use serde_json::{self, Value};
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct Slug {
slug: String,
}
impl Slug {
pub fn new(slug: String) -> Self {
Slug { slug: slug }
}
pub fn create_output_path(&self, prefix: &Path, pr... | (&self, dest: &str, pretty_url: bool) -> String {
let slug_prefix = "../".repeat(self.depth(pretty_url));
format!("{}{}", slug_prefix, dest)
}
}
impl convert::AsRef<str> for Slug {
fn as_ref(&self) -> &str {
&self.slug
}
}
impl fmt::Display for Slug {
fn fmt(&self, f: &mut fmt:... | path_to | identifier_name |
page.rs | use std::convert;
use std::fmt;
use std::path::{Path, PathBuf};
use serde_json::{self, Value};
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct Slug {
slug: String,
}
impl Slug {
pub fn new(slug: String) -> Self {
Slug { slug: slug }
}
pub fn create_output_path(&self, prefix: &Path, pr... | &self.slug
}
}
impl fmt::Display for Slug {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", &self.slug)
}
}
pub struct Page {
pub source_path: PathBuf,
pub slug: Slug,
pub body: String,
pub theme_config: serde_json::map::Map<String, Value>,
}
impl Pa... |
impl convert::AsRef<str> for Slug {
fn as_ref(&self) -> &str { | random_line_split |
udpsrc_benchmark_sender.rs | // Copyright (C) 2018 Sebastian Dröge <sebastian@centricular.com>
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Library General Public
// License as published by the Free Software Foundation; either
// version 2 of the License, or (at your option) any later ... | }
}
|
thread::sleep(wait - elapsed);
}
| conditional_block |
udpsrc_benchmark_sender.rs | // Copyright (C) 2018 Sebastian Dröge <sebastian@centricular.com>
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Library General Public
// License as published by the Free Software Foundation; either
// version 2 of the License, or (at your option) any later ... |
use std::net;
use std::net::{IpAddr, Ipv4Addr, SocketAddr};
use std::{env, thread, time};
fn main() {
let args = env::args().collect::<Vec<_>>();
assert_eq!(args.len(), 2);
let n_streams: u16 = args[1].parse().unwrap();
let buffer = [0; 160];
let socket = net::UdpSocket::bind("0.0.0.0:0").unwrap(... | // You should have received a copy of the GNU Library General Public
// License along with this library; if not, write to the
// Free Software Foundation, Inc., 51 Franklin Street, Suite 500,
// Boston, MA 02110-1335, USA. | random_line_split |
udpsrc_benchmark_sender.rs | // Copyright (C) 2018 Sebastian Dröge <sebastian@centricular.com>
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Library General Public
// License as published by the Free Software Foundation; either
// version 2 of the License, or (at your option) any later ... | ) {
let args = env::args().collect::<Vec<_>>();
assert_eq!(args.len(), 2);
let n_streams: u16 = args[1].parse().unwrap();
let buffer = [0; 160];
let socket = net::UdpSocket::bind("0.0.0.0:0").unwrap();
let ipaddr = IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1));
let destinations = (40000..(40000 ... | ain( | identifier_name |
udpsrc_benchmark_sender.rs | // Copyright (C) 2018 Sebastian Dröge <sebastian@centricular.com>
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Library General Public
// License as published by the Free Software Foundation; either
// version 2 of the License, or (at your option) any later ... | for dest in &destinations {
socket.send_to(&buffer, dest).unwrap();
}
let elapsed = now.elapsed();
if elapsed < wait {
thread::sleep(wait - elapsed);
}
}
}
|
let args = env::args().collect::<Vec<_>>();
assert_eq!(args.len(), 2);
let n_streams: u16 = args[1].parse().unwrap();
let buffer = [0; 160];
let socket = net::UdpSocket::bind("0.0.0.0:0").unwrap();
let ipaddr = IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1));
let destinations = (40000..(40000 + n... | identifier_body |
mod.rs | // Gibbs MySQL Spyglass
// Copyright (C) 2016 AgilData
//
// This file is part of Gibbs MySQL Spyglass.
//
// Gibbs MySQL Spyglass 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 Lice... | () {
debug!("deleting capture file {}", CAP_FILE);
let _ = fs::remove_file(CAP_FILE);
}
pub fn set_cap(on: bool) { CAP_ON.store(on, Ordering::SeqCst) }
pub fn chk_cap() -> bool { CAP_ON.load(Ordering::SeqCst) }
fn write_cap(cap: &mut File, msg: &str) {
let bytes = match cap.write(msg.as_bytes()) {
... | clear_cap | identifier_name |
mod.rs | // Gibbs MySQL Spyglass
// Copyright (C) 2016 AgilData
//
// This file is part of Gibbs MySQL Spyglass.
//
// Gibbs MySQL Spyglass 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 Lice... |
pub fn cap_size() -> usize { FILE_SIZE.load(Ordering::SeqCst) }
fn inc_qry() {
QRY_CNT.fetch_add(1, Ordering::SeqCst);
}
pub fn qry_cnt() -> usize { QRY_CNT.load(Ordering::SeqCst) }
| {
let bytes = match cap.write(msg.as_bytes()) {
Ok(cnt) => cnt,
Err(e) => panic!(e),
};
if FILE_SIZE.fetch_add(bytes, Ordering::SeqCst) + bytes > MAX_CAPTURE {
set_cap(false);
}
} | identifier_body |
mod.rs | // Gibbs MySQL Spyglass
// Copyright (C) 2016 AgilData
//
// This file is part of Gibbs MySQL Spyglass.
// | // Gibbs MySQL Spyglass 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 Public License for more details.
//
// You should have received a copy of the GNU General Public Li... | // Gibbs MySQL Spyglass 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.
// | random_line_split |
31-2.rs | /* Problem 31: Coin sums
*
* In England the currency is made up of pound, £, and pence, p, and there are eight coins in
* general circulation:
*
* 1p, 2p, 5p, 10p, 20p, 50p, £1 (100p) and £2 (200p).
*
* It is possible to make £2 in the following way:
*
* 1×£1 + 1×50p + 2×20p + 1×5p + 1×2p + 3×1p
*
* ... | ntln!("{}", ways_to_make(200, DENOMINATIONS));
}
// Dynamic programming solution, adapted from the overview PDF
fn ways_to_make(value: usize, denominations: &[usize]) -> usize {
let mut ways: Vec<usize> = repeat(0).take(value + 1).collect();
ways[0] = 1;
for &denom in denominations.iter() {
for cu... | pri | identifier_name |
31-2.rs | /* Problem 31: Coin sums
*
* In England the currency is made up of pound, £, and pence, p, and there are eight coins in
* general circulation:
*
* 1p, 2p, 5p, 10p, 20p, 50p, £1 (100p) and £2 (200p).
*
* It is possible to make £2 in the following way:
*
* 1×£1 + 1×50p + 2×20p + 1×5p + 1×2p + 3×1p
*
* ... | programming solution, adapted from the overview PDF
fn ways_to_make(value: usize, denominations: &[usize]) -> usize {
let mut ways: Vec<usize> = repeat(0).take(value + 1).collect();
ways[0] = 1;
for &denom in denominations.iter() {
for current in denom..value + 1 {
ways[current] += way... | n!("{}", ways_to_make(200, DENOMINATIONS));
}
// Dynamic | identifier_body |
31-2.rs | /* Problem 31: Coin sums
*
* In England the currency is made up of pound, £, and pence, p, and there are eight coins in
* general circulation:
*
* 1p, 2p, 5p, 10p, 20p, 50p, £1 (100p) and £2 (200p).
*
* It is possible to make £2 in the following way: | use std::iter::repeat;
const DENOMINATIONS: &'static [usize] = &[200, 100, 50, 20, 10, 5, 2, 1];
fn main() {
println!("{}", ways_to_make(200, DENOMINATIONS));
}
// Dynamic programming solution, adapted from the overview PDF
fn ways_to_make(value: usize, denominations: &[usize]) -> usize {
let mut ways: Vec<u... | *
* 1×£1 + 1×50p + 2×20p + 1×5p + 1×2p + 3×1p
*
* How many different ways can £2 be made using any number of coins? */
| random_line_split |
_9_3_normal_visualization.rs | #![allow(non_upper_case_globals)]
#![allow(non_snake_case)]
use std::ffi::CStr;
extern crate glfw;
use self::glfw::Context;
extern crate gl;
use cgmath::{Matrix4, Deg, vec3, Point3, perspective};
use common::{process_events, processInput};
use shader::Shader;
use camera::Camera;
use model::Model;
// settings
cons... | glfw.window_hint(glfw::WindowHint::OpenGlForwardCompat(true));
// glfw window creation
// --------------------
let (mut window, events) = glfw.create_window(SCR_WIDTH, SCR_HEIGHT, "LearnOpenGL", glfw::WindowMode::Windowed)
.expect("Failed to create GLFW window");
window.make_current();
... | {
let mut camera = Camera {
Position: Point3::new(0.0, 0.0, 3.0),
..Camera::default()
};
let mut firstMouse = true;
let mut lastX: f32 = SCR_WIDTH as f32 / 2.0;
let mut lastY: f32 = SCR_HEIGHT as f32 / 2.0;
// timing
let mut deltaTime: f32; // time between current frame and... | identifier_body |
_9_3_normal_visualization.rs | #![allow(non_upper_case_globals)]
#![allow(non_snake_case)]
use std::ffi::CStr;
extern crate glfw;
use self::glfw::Context;
extern crate gl;
use cgmath::{Matrix4, Deg, vec3, Point3, perspective};
use common::{process_events, processInput};
use shader::Shader;
use camera::Camera;
use model::Model;
// settings
cons... | gl::Enable(gl::DEPTH_TEST);
// build and compile shaders
// -------------------------
let shader = Shader::new(
"src/_4_advanced_opengl/shaders/9.3.default.vs",
"src/_4_advanced_opengl/shaders/9.3.default.fs",
);
let normalShader = Shader::with_ge... | let (shader, normalShader, nanoSuit) = unsafe {
// configure global opengl state
// ----------------------------- | random_line_split |
_9_3_normal_visualization.rs | #![allow(non_upper_case_globals)]
#![allow(non_snake_case)]
use std::ffi::CStr;
extern crate glfw;
use self::glfw::Context;
extern crate gl;
use cgmath::{Matrix4, Deg, vec3, Point3, perspective};
use common::{process_events, processInput};
use shader::Shader;
use camera::Camera;
use model::Model;
// settings
cons... | () {
let mut camera = Camera {
Position: Point3::new(0.0, 0.0, 3.0),
..Camera::default()
};
let mut firstMouse = true;
let mut lastX: f32 = SCR_WIDTH as f32 / 2.0;
let mut lastY: f32 = SCR_HEIGHT as f32 / 2.0;
// timing
let mut deltaTime: f32; // time between current frame a... | main_4_9_3 | identifier_name |
basic_chatbot.rs | extern crate discord;
use discord::Discord;
use discord::model::Event;
use std::env;
fn main() | Ok(_) => {}
Err(discord::Error::Closed(code, body)) => {
println!("Gateway closed on us with code {:?}: {}", code, body);
break
}
Err(err) => println!("Receive error: {:?}", err)
}
}
}
| {
// Log in to Discord using a bot token from the environment
let discord = Discord::from_bot_token(
&env::var("DISCORD_TOKEN").expect("Expected token"),
).expect("login failed");
// Establish and use a websocket connection
let (mut connection, _) = discord.connect().expect("connect failed");
println!("Ready."... | identifier_body |
basic_chatbot.rs | extern crate discord;
use discord::Discord;
use discord::model::Event;
use std::env;
fn main() {
// Log in to Discord using a bot token from the environment
let discord = Discord::from_bot_token(
&env::var("DISCORD_TOKEN").expect("Expected token"),
).expect("login failed");
// Establish and use a websocket con... | Err(discord::Error::Closed(code, body)) => {
println!("Gateway closed on us with code {:?}: {}", code, body);
break
}
Err(err) => println!("Receive error: {:?}", err)
}
}
} | println!("Quitting.");
break
}
}
Ok(_) => {} | random_line_split |
basic_chatbot.rs | extern crate discord;
use discord::Discord;
use discord::model::Event;
use std::env;
fn | () {
// Log in to Discord using a bot token from the environment
let discord = Discord::from_bot_token(
&env::var("DISCORD_TOKEN").expect("Expected token"),
).expect("login failed");
// Establish and use a websocket connection
let (mut connection, _) = discord.connect().expect("connect failed");
println!("Read... | main | identifier_name |
creader.rs | use collections::HashMap;
use syntax::ast;
use syntax::abi;
use syntax::attr;
use syntax::attr::AttrMetaMethods;
use syntax::codemap::{Span};
use syntax::diagnostic::SpanHandler;
use syntax::ext::base::{CrateLoader, MacroCrate};
use syntax::parse::token::InternedString;
use syntax::parse::token;
use syntax::crateid::Cr... | next_crate_num: sess.cstore.next_crate_num(),
}
}
}
}
impl<'a> CrateLoader for Loader<'a> {
fn load_crate(&mut self, krate: &ast::ViewItem) -> MacroCrate {
let info = extract_crate_info(&self.env, krate).unwrap();
let target_triple = self.env.sess.targ_cfg.ta... | Loader {
env: Env {
sess: sess, | random_line_split |
creader.rs | collections::HashMap;
use syntax::ast;
use syntax::abi;
use syntax::attr;
use syntax::attr::AttrMetaMethods;
use syntax::codemap::{Span};
use syntax::diagnostic::SpanHandler;
use syntax::ext::base::{CrateLoader, MacroCrate};
use syntax::parse::token::InternedString;
use syntax::parse::token;
use syntax::crateid::Crate... | }
Some(cnum) => (cnum,
e.sess.cstore.get_crate_data(cnum),
e.sess.cstore.get_used_crate_source(cnum).unwrap())
}
}
// Go through the crate metadata and load any crates that it references
fn resolve_crate_deps(e: &mut Env,
root: &O... | {
match existing_match(e, crate_id, hash) {
None => {
let id_hash = link::crate_id_hash(crate_id);
let mut load_ctxt = loader::Context {
sess: e.sess,
span: span,
ident: ident,
crate_id: crate_id,
id_hash... | identifier_body |
creader.rs | collections::HashMap;
use syntax::ast;
use syntax::abi;
use syntax::attr;
use syntax::attr::AttrMetaMethods;
use syntax::codemap::{Span};
use syntax::diagnostic::SpanHandler;
use syntax::ext::base::{CrateLoader, MacroCrate};
use syntax::parse::token::InternedString;
use syntax::parse::token;
use syntax::crateid::Crate... | (&mut self, a: &ast::Item, _: ()) {
visit_item(self, a);
visit::walk_item(self, a, ());
}
}
fn dump_crates(cstore: &CStore) {
debug!("resolved crates:");
cstore.iter_crate_data_origins(|_, data, opt_source| {
debug!("crate_id: {}", data.crate_id());
debug!(" cnum: {}", data... | visit_item | identifier_name |
creader.rs | collections::HashMap;
use syntax::ast;
use syntax::abi;
use syntax::attr;
use syntax::attr::AttrMetaMethods;
use syntax::codemap::{Span};
use syntax::diagnostic::SpanHandler;
use syntax::ext::base::{CrateLoader, MacroCrate};
use syntax::parse::token::InternedString;
use syntax::parse::token;
use syntax::crateid::Crate... |
}
}
}
fn should_link(i: &ast::ViewItem) -> bool {
i.attrs.iter().all(|attr| {
attr.name().get()!= "phase" ||
attr.meta_item_list().map_or(false, |phases| {
attr::contains_name(phases.as_slice(), "link")
})
})
}
fn visit_view_item(e: &mut Env, i: &as... | { /* fallthrough */ } | conditional_block |
entity.rs | use std::str::FromStr;
use std::fmt::{self, Display};
/// An entity tag
///
/// An Etag consists of a string enclosed by two literal double quotes.
/// Preceding the first double quote is an optional weakness indicator,
/// which always looks like this: W/
/// See also: https://tools.ietf.org/html/rfc7232#section-2.3
... |
}
if slice.slice_chars(0, 3) == "W/\"" {
if check_slice_validity(slice.slice_chars(3, length-1)) {
return Ok(EntityTag {
weak: true,
tag: slice.slice_chars(3, length-1).to_string()
});
} else {
... | {
return Err(());
} | conditional_block |
entity.rs | use std::str::FromStr;
use std::fmt::{self, Display};
/// An entity tag
///
/// An Etag consists of a string enclosed by two literal double quotes.
/// Preceding the first double quote is an optional weakness indicator,
/// which always looks like this: W/
/// See also: https://tools.ietf.org/html/rfc7232#section-2.3
... | }
} | etag = "unmatched-dquotes2\"".parse();
assert_eq!(etag, Err(()));
etag = "matched-\"dquotes\"".parse();
assert_eq!(etag, Err(())); | random_line_split |
entity.rs | use std::str::FromStr;
use std::fmt::{self, Display};
/// An entity tag
///
/// An Etag consists of a string enclosed by two literal double quotes.
/// Preceding the first double quote is an optional weakness indicator,
/// which always looks like this: W/
/// See also: https://tools.ietf.org/html/rfc7232#section-2.3
... | {
/// Weakness indicator for the tag
pub weak: bool,
/// The opaque string in between the DQUOTEs
pub tag: String
}
impl Display for EntityTag {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
if self.weak {
try!(write!(fmt, "{}", "W/"));
}
write!(fmt, ... | EntityTag | identifier_name |
entity.rs | use std::str::FromStr;
use std::fmt::{self, Display};
/// An entity tag
///
/// An Etag consists of a string enclosed by two literal double quotes.
/// Preceding the first double quote is an optional weakness indicator,
/// which always looks like this: W/
/// See also: https://tools.ietf.org/html/rfc7232#section-2.3
... | } else {
return Err(());
}
}
if slice.slice_chars(0, 3) == "W/\"" {
if check_slice_validity(slice.slice_chars(3, length-1)) {
return Ok(EntityTag {
weak: true,
tag: slice.slice_chars(3, length-1)... | {
let length: usize = s.len();
let slice = &s[..];
// Early exits:
// 1. The string is empty, or,
// 2. it doesn't terminate in a DQUOTE.
if slice.is_empty() || !slice.ends_with("\"") {
return Err(());
}
// The etag is weak if its first char ... | identifier_body |
main.rs | extern crate rand;
use std::io;
use rand::Rng;
use std::cmp::Ordering;
fn main() {
let secret_number: u32 = rand::thread_rng().gen_range(1, 101);
//println!("The secret number is {}", secret_number);
println!("Guess the number!");
| println!("Please enter your guess.");
let mut guess = String::new();
io::stdin().read_line(&mut guess)
.expect("Failed to read line.");
let guess: u32 = match guess.trim().parse() {
Ok(num) => num,
Err(_) => continue,
};
println!("Yo... | loop { | random_line_split |
main.rs | extern crate rand;
use std::io;
use rand::Rng;
use std::cmp::Ordering;
fn | () {
let secret_number: u32 = rand::thread_rng().gen_range(1, 101);
//println!("The secret number is {}", secret_number);
println!("Guess the number!");
loop {
println!("Please enter your guess.");
let mut guess = String::new();
io::stdin().read_line(&mut guess)
.... | main | identifier_name |
main.rs | extern crate rand;
use std::io;
use rand::Rng;
use std::cmp::Ordering;
fn main() | println!("You guessed {}", guess);
match guess.cmp(&secret_number) {
Ordering::Less => println!("Too small!"),
Ordering::Greater => println!("Too big!"),
Ordering::Equal => {
println!("Correct!");
break;
}
}
}
}... | {
let secret_number: u32 = rand::thread_rng().gen_range(1, 101);
//println!("The secret number is {}", secret_number);
println!("Guess the number!");
loop {
println!("Please enter your guess.");
let mut guess = String::new();
io::stdin().read_line(&mut guess)
.ex... | identifier_body |
lib.rs | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This software may be used and distributed according to the terms of the
* GNU General Public License version 2.
*/
#![deny(warnings)]
use ascii::AsciiString;
use mercurial_types::{
blobs::HgBlobChangeset, HgBlob, HgChangesetId, HgFileNodeId, HgManif... | use thiserror::Error;
#[derive(Debug)]
pub enum StateOpenError {
Heads,
Bookmarks,
Changesets,
Filenodes,
BonsaiGitMapping,
BonsaiGlobalrevMapping,
BonsaiSvnrevMapping,
BonsaiHgMapping,
Phases,
HgMutationStore,
SegmentedChangelog,
}
impl fmt::Display for StateOpenError {
... | };
use mononoke_types::{hash::Sha256, ChangesetId, FileType};
use std::fmt; | random_line_split |
lib.rs | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This software may be used and distributed according to the terms of the
* GNU General Public License version 2.
*/
#![deny(warnings)]
use ascii::AsciiString;
use mercurial_types::{
blobs::HgBlobChangeset, HgBlob, HgChangesetId, HgFileNodeId, HgManif... | {
#[error("Error while opening state for {0}")]
StateOpen(StateOpenError),
#[error("Node id {0} is missing")]
NodeMissing(HgNodeHash),
#[error("Content missing nodeid {0}")]
ContentMissing(HgNodeHash),
#[error("Error while deserializing file contents retrieved from key '{0}'")]
FileCont... | ErrorKind | identifier_name |
datatypes.rs | use serde_json;
use std::io;
use std::string::FromUtf8Error;
#[derive(Deserialize, Debug)]
pub struct Event {
pub version: String,
pub event: String,
pub data: DownloadComplete
}
#[derive(Deserialize, Debug)]
pub struct | {
pub update_id: String,
pub update_image: String,
pub signature: String
}
#[derive(Debug)]
pub enum Error {
Custom(String),
Io(io::Error),
Json(serde_json::Error),
Utf8(FromUtf8Error)
}
impl From<io::Error> for Error {
fn from(err: io::Error) -> Error {
Error::Io(err)
... | DownloadComplete | identifier_name |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.