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 |
|---|---|---|---|---|
locus.rs | //! Provide a location.
//!
//! ```text
//! _ _ _ | //! The relision term rewriting library.
//!
//! # License
//!
//! Copyright (c) 2015 by Stacy Prowell. All rights reserved.
//!
//! Licensed under the BSD 2-Clause license. See the file LICENSE
//! that is part of this distribution. This file may not be copied,
//! modified, or distributed except according to those... | //! _ __ ___| (_)___(_) ___ _ __
//! | '__/ _ \ | / __| |/ _ \| '_ \
//! | | | __/ | \__ \ | (_) | | | |
//! |_| \___|_|_|___/_|\___/|_| |_|
//! ``` | random_line_split |
miniobject.rs | use ffi::*;
use std::mem;
use std::ptr;
use reference::Reference;
pub struct MiniObject{
miniobject: *mut GstMiniObject,
}
impl Drop for MiniObject{
fn drop(&mut self){
unsafe{
gst_mini_object_unref(self.miniobject);
}
}
}
#[repr(u32)]
#[derive(Copy,Clone,Debug)]
pub enum LockFlags{
Read = GS... | self.miniobject as *const GstMiniObject
}
pub unsafe fn gst_miniobject_mut(&mut self) -> *mut GstMiniObject{
self.miniobject
}
}
impl Clone for MiniObject{
fn clone(&self) -> MiniObject{
unsafe{
MiniObject{ miniobject: gst_mini_object_copy(self.miniobject as *mut GstMiniObject) }
}... | random_line_split | |
miniobject.rs | use ffi::*;
use std::mem;
use std::ptr;
use reference::Reference;
pub struct MiniObject{
miniobject: *mut GstMiniObject,
}
impl Drop for MiniObject{
fn drop(&mut self){
unsafe{
gst_mini_object_unref(self.miniobject);
}
}
}
#[repr(u32)]
#[derive(Copy,Clone,Debug)]
pub enum LockFlags{
Read = GS... | (&self) -> MiniObject{
unsafe{
MiniObject{ miniobject: gst_mini_object_ref(self.miniobject) }
}
}
}
impl ::Transfer<GstMiniObject> for MiniObject{
unsafe fn transfer(self) -> *mut GstMiniObject{
let miniobject = self.miniobject;
mem::forget(self);
miniobject
}
}
| reference | identifier_name |
miniobject.rs | use ffi::*;
use std::mem;
use std::ptr;
use reference::Reference;
pub struct MiniObject{
miniobject: *mut GstMiniObject,
}
impl Drop for MiniObject{
fn drop(&mut self){
unsafe{
gst_mini_object_unref(self.miniobject);
}
}
}
#[repr(u32)]
#[derive(Copy,Clone,Debug)]
pub enum LockFlags{
Read = GS... | else{
None
}
}
pub fn lock<F:FnMut(&mut MiniObject)>(&mut self, flags: &[LockFlags], mut f: F) -> bool{
let flags = flags.iter().fold(0,|ret, flag| ret | *flag as u32);
unsafe{
if gst_mini_object_lock(self.miniobject, flags)!= 0{
f(self);
... | {
Some(MiniObject{
miniobject: miniobject
})
} | conditional_block |
decoder.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/. */
//! Adapted from an implementation in reqwest.
/*!
A potentially non-blocking response decoder.
The decoder wra... | (response: Response<Body>) -> Response<Decoder> {
let values = response
.headers()
.get_all(CONTENT_ENCODING)
.iter()
.chain(response.headers().get_all(TRANSFER_ENCODING).iter());
let decoder = values.fold(None, |acc, enc| {
acc.or_else(|| {
... | detect | identifier_name |
decoder.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/. */
//! Adapted from an implementation in reqwest.
/*!
A potentially non-blocking response decoder.
The decoder wra... | }
},
ReadState::NotReady => match self.poll_stream(&mut cx) {
Poll::Ready(StreamState::HasMore) => continue,
Poll::Ready(StreamState::Eof) => return Ok(0),
Poll::Pending => return Err(io::ErrorKind::WouldBloc... | } else {
return Ok(len); | random_line_split |
decoder.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/. */
//! Adapted from an implementation in reqwest.
/*!
A potentially non-blocking response decoder.
The decoder wra... | else if enc == HeaderValue::from_static("br") {
Some(DecoderType::Brotli)
} else if enc == HeaderValue::from_static("deflate") {
Some(DecoderType::Deflate)
} else {
None
}
})
});
matc... | {
Some(DecoderType::Gzip)
} | conditional_block |
container_01.rs | use azure_sdk_core::prelude::*;
use azure_sdk_storage_blob::prelude::*;
use azure_sdk_storage_core::prelude::*;
use chrono::{Duration, FixedOffset, Utc};
use std::collections::HashMap;
use std::error::Error;
use std::ops::Add;
#[tokio::main]
async fn | () -> Result<(), Box<dyn Error>> {
// First we retrieve the account name and master key from environment variables.
let account =
std::env::var("STORAGE_ACCOUNT").expect("Set env variable STORAGE_ACCOUNT first!");
let master_key =
std::env::var("STORAGE_MASTER_KEY").expect("Set env variable ... | main | identifier_name |
container_01.rs | use azure_sdk_core::prelude::*;
use azure_sdk_storage_blob::prelude::*;
use azure_sdk_storage_core::prelude::*;
use chrono::{Duration, FixedOffset, Utc};
use std::collections::HashMap;
use std::error::Error;
use std::ops::Add;
#[tokio::main]
async fn main() -> Result<(), Box<dyn Error>> {
// First we retrieve the ... | } | random_line_split | |
container_01.rs | use azure_sdk_core::prelude::*;
use azure_sdk_storage_blob::prelude::*;
use azure_sdk_storage_core::prelude::*;
use chrono::{Duration, FixedOffset, Utc};
use std::collections::HashMap;
use std::error::Error;
use std::ops::Add;
#[tokio::main]
async fn main() -> Result<(), Box<dyn Error>> | println!("{:?}", res);
let mut metadata = HashMap::new();
metadata.insert("prova", "pollo");
metadata.insert("canotto", "cigno");
// This is the builder pattern. Notice two things:
// 1 - The various parameters are clearly defined.
// 2 - If you forget a mandatory parameter the code won't ... | {
// First we retrieve the account name and master key from environment variables.
let account =
std::env::var("STORAGE_ACCOUNT").expect("Set env variable STORAGE_ACCOUNT first!");
let master_key =
std::env::var("STORAGE_MASTER_KEY").expect("Set env variable STORAGE_MASTER_KEY first!");
... | identifier_body |
shapiro.rs | extern crate diffgeom;
extern crate gr_engine;
#[macro_use]
extern crate generic_array;
extern crate numeric_algs;
use diffgeom::coordinates::Point;
use diffgeom::tensors::Vector;
use gr_engine::coord_systems::schwarzschild::{Mass, Schwarzschild};
use gr_engine::particle::Particle;
use numeric_algs::integration::{DPIn... | }
type Coords = Schwarzschild<Sun>;
const M: f64 = 4.9e-6; // mass of the Sun in seconds, with c = G = 1
const D: f64 = 2.33; // radius of the Sun in seconds
const YE: f64 = 498.67; // Earth "y" coordinate in seconds
const YV: f64 = 370.7; // Venus "y" coordinate in seconds
fn propagate_single_photon(
photon: &m... | } | random_line_split |
shapiro.rs | extern crate diffgeom;
extern crate gr_engine;
#[macro_use]
extern crate generic_array;
extern crate numeric_algs;
use diffgeom::coordinates::Point;
use diffgeom::tensors::Vector;
use gr_engine::coord_systems::schwarzschild::{Mass, Schwarzschild};
use gr_engine::particle::Particle;
use numeric_algs::integration::{DPIn... | }
fn main() {
let u0 = (D * D * D / (D - M * 2.0)).sqrt();
let r_e = (D * D + YE * YE).sqrt();
let r_v = (D * D + YV * YV).sqrt();
let t_flat = 2.0 * (YE + YV);
let start_point = Point::<Coords>::new(arr![f64; 0.0, D, PI / 2.0, 0.0]);
let u_init1 = Vector::<Coords>::new(start_point.clone(), ... | {
let mut last_pos = photon.get_pos().clone();
let mut i = 1;
while photon.get_pos()[1] < r_max {
last_pos = photon.get_pos().clone();
integrator.propagate_in_place(photon, Particle::derivative, StepSize::UseDefault);
i += 1;
if i % 100 == 0 {
println!("Iteration... | identifier_body |
shapiro.rs | extern crate diffgeom;
extern crate gr_engine;
#[macro_use]
extern crate generic_array;
extern crate numeric_algs;
use diffgeom::coordinates::Point;
use diffgeom::tensors::Vector;
use gr_engine::coord_systems::schwarzschild::{Mass, Schwarzschild};
use gr_engine::particle::Particle;
use numeric_algs::integration::{DPIn... |
}
let pos = photon.get_pos();
let (t, r) = (pos[0], pos[1]);
let (last_t, last_r) = (last_pos[0], last_pos[1]);
let coeff = (r_max - last_r) / (r - last_r);
last_t + (t - last_t) * coeff
}
fn main() {
let u0 = (D * D * D / (D - M * 2.0)).sqrt();
let r_e = (D * D + YE * YE).sqrt();
... | {
println!("Iteration {}... r = {}", i, photon.get_pos()[1]);
} | conditional_block |
shapiro.rs | extern crate diffgeom;
extern crate gr_engine;
#[macro_use]
extern crate generic_array;
extern crate numeric_algs;
use diffgeom::coordinates::Point;
use diffgeom::tensors::Vector;
use gr_engine::coord_systems::schwarzschild::{Mass, Schwarzschild};
use gr_engine::particle::Particle;
use numeric_algs::integration::{DPIn... | ;
impl Mass for Sun {
fn mass() -> f64 {
M
}
}
type Coords = Schwarzschild<Sun>;
const M: f64 = 4.9e-6; // mass of the Sun in seconds, with c = G = 1
const D: f64 = 2.33; // radius of the Sun in seconds
const YE: f64 = 498.67; // Earth "y" coordinate in seconds
const YV: f64 = 370.7; // Venus "y" coor... | Sun | identifier_name |
test.rs | // Copyright 2013-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... | }),
});
}
pub fn register_header(&mut self, name: &str, level: u32) {
if self.use_headers && level == 1 {
// we use these headings as test names, so it's good if
// they're valid identifiers.
let name = name.chars().enumerate().map(|(i, c)| {
... | {
let name = if self.use_headers {
let s = self.current_header.as_ref().map(|s| s.as_slice()).unwrap_or("");
format!("{}_{}", s, self.cnt)
} else {
format!("{}_{}", self.names.connect("::"), self.cnt)
};
self.cnt += 1;
let libs = self.libs.clon... | identifier_body |
test.rs | // Copyright 2013-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... | (cratename: ~str, libs: HashSet<Path>,
use_headers: bool, loose_feature_gating: bool) -> Collector {
Collector {
tests: Vec::new(),
names: Vec::new(),
libs: libs,
cnt: 0,
use_headers: use_headers,
current_header: None,
... | new | identifier_name |
test.rs | // Copyright 2013-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... | let mut err = old.unwrap_or(~io::stderr() as ~Writer:Send);
io::util::copy(&mut p, &mut err).unwrap();
});
let emitter = diagnostic::EmitterWriter::new(~w2);
// Compile the code
let codemap = CodeMap::new();
let diagnostic_handler = diagnostic::mk_handler(~emitter);
let span_dia... | let w2 = w1.clone();
let old = io::stdio::set_stderr(~w1);
spawn(proc() {
let mut p = io::ChanReader::new(rx); | random_line_split |
packet.rs | use serde::{de,Serialize,Serializer,Deserialize,Deserializer};
#[derive(Copy,Clone,Debug,Eq,PartialEq)]
pub struct ProtocolId;
impl Serialize for ProtocolId{
#[inline]
fn serialize<S>(&self,serializer: &mut S) -> Result<(),S::Error>
where S: Serializer
{
serializer.serialize_bytes(b"TETR")
}
}
impl Deserialize... | Ok(ProtocolId)
}else{
Err(E::invalid_value("Expected `TETR` as the protocol id"))
}
}
}
deserializer.deserialize_string(V)
}
}
pub type Id = u16;
#[derive(Copy,Clone,Debug,Serialize,Deserialize)]
pub struct Packet<Data: Serialize + Deserialize>{
pub protocol: ProtocolId,
pub packet: Id,
p... |
fn visit_bytes<E>(&mut self,s: &[u8]) -> Result<Self::Value,E>
where E: de::Error,
{
if s==b"TETR"{ | random_line_split |
packet.rs | use serde::{de,Serialize,Serializer,Deserialize,Deserializer};
#[derive(Copy,Clone,Debug,Eq,PartialEq)]
pub struct ProtocolId;
impl Serialize for ProtocolId{
#[inline]
fn serialize<S>(&self,serializer: &mut S) -> Result<(),S::Error>
where S: Serializer
{
serializer.serialize_bytes(b"TETR")
}
}
impl Deserialize... | else{
Err(E::invalid_value("Expected `TETR` as the protocol id"))
}
}
fn visit_bytes<E>(&mut self,s: &[u8]) -> Result<Self::Value,E>
where E: de::Error,
{
if s==b"TETR"{
Ok(ProtocolId)
}else{
Err(E::invalid_value("Expected `TETR` as the protocol id"))
}
}
}
deserializ... | {
Ok(ProtocolId)
} | conditional_block |
packet.rs | use serde::{de,Serialize,Serializer,Deserialize,Deserializer};
#[derive(Copy,Clone,Debug,Eq,PartialEq)]
pub struct ProtocolId;
impl Serialize for ProtocolId{
#[inline]
fn serialize<S>(&self,serializer: &mut S) -> Result<(),S::Error>
where S: Serializer
{
serializer.serialize_bytes(b"TETR")
}
}
impl Deserialize... | <Data: Serialize + Deserialize>{
pub protocol: ProtocolId,
pub packet: Id,
pub data: Data,
}
impl<Data> Packet<Data>
where Data: Serialize + Deserialize
{
#[inline(always)]
pub fn serialize(&self) -> Vec<u8>{
::bincode::serde::serialize(self,::bincode::SizeLimit::Bounded(256)).unwrap()
}
#[inline(always)]
... | Packet | identifier_name |
packet.rs | use serde::{de,Serialize,Serializer,Deserialize,Deserializer};
#[derive(Copy,Clone,Debug,Eq,PartialEq)]
pub struct ProtocolId;
impl Serialize for ProtocolId{
#[inline]
fn serialize<S>(&self,serializer: &mut S) -> Result<(),S::Error>
where S: Serializer
{
serializer.serialize_bytes(b"TETR")
}
}
impl Deserialize... |
}
deserializer.deserialize_string(V)
}
}
pub type Id = u16;
#[derive(Copy,Clone,Debug,Serialize,Deserialize)]
pub struct Packet<Data: Serialize + Deserialize>{
pub protocol: ProtocolId,
pub packet: Id,
pub data: Data,
}
impl<Data> Packet<Data>
where Data: Serialize + Deserialize
{
#[inline(always)]
pub f... | {
if s==b"TETR"{
Ok(ProtocolId)
}else{
Err(E::invalid_value("Expected `TETR` as the protocol id"))
}
} | identifier_body |
issue-7660.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 ... | (int, int);
pub fn main() {
let mut m: HashMap<int, A> = HashMap::new();
m.insert(1, A(0, 0));
let A(ref _a, ref _b) = *m.get(&1);
let (a, b) = match *m.get(&1) { A(ref _a, ref _b) => (_a, _b) };
}
| A | identifier_name |
issue-7660.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 mut m: HashMap<int, A> = HashMap::new();
m.insert(1, A(0, 0));
let A(ref _a, ref _b) = *m.get(&1);
let (a, b) = match *m.get(&1) { A(ref _a, ref _b) => (_a, _b) };
} | identifier_body | |
issue-7660.rs | // 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 http://opensource.org/licenses/MIT>, at your
// option. This file... | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT | random_line_split | |
v1.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 ... | {
#[stable(feature = "rust1", since = "1.0.0")]
Is(usize),
#[stable(feature = "rust1", since = "1.0.0")]
Param(usize),
#[stable(feature = "rust1", since = "1.0.0")]
NextParam,
#[stable(feature = "rust1", since = "1.0.0")]
Implied,
}
#[derive(Copy)]
#[stable(feature = "rust1", since = "... | Count | identifier_name |
v1.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 ... | //! emitted to static arrays to precompile format strings ahead of time.
//!
//! These definitions are similar to their `ct` equivalents, but differ in that
//! these can be statically allocated and are slightly optimized for the runtime
#![stable(feature = "rust1", since = "1.0.0")]
#[derive(Copy)]
#[stable(feature ... | // except according to those terms.
//! This is an internal module used by the ifmt! runtime. These structures are | random_line_split |
metrics.rs | // Copyright 2016 TiKV Project Authors. Licensed under Apache-2.0.
use prometheus::*;
lazy_static! {
pub static ref PD_REQUEST_HISTOGRAM_VEC: HistogramVec = register_histogram_vec!(
"tikv_pd_request_duration_seconds",
"Bucketed histogram of PD requests duration",
&["type"]
) | .unwrap();
pub static ref PD_HEARTBEAT_COUNTER_VEC: IntCounterVec = register_int_counter_vec!(
"tikv_pd_heartbeat_message_total",
"Total number of PD heartbeat messages.",
&["type"]
)
.unwrap();
pub static ref PD_VALIDATE_PEER_COUNTER_VEC: IntCounterVec = register_int_counter_v... | random_line_split | |
packetiser.rs | use std::collections::VecDeque; | use reader::Reader;
use tokeniser::Tokeniser;
#[derive(Debug)]
pub struct Packetiser {
tok: Tokeniser,
buf: VecDeque<SexpToken>,
parens_open: usize,
}
impl Packetiser {
pub fn new() -> Packetiser {
Packetiser {
tok: Tokeniser::new(),
buf: VecDeque::new(),
pa... | use std::mem;
use serde::de;
use super::{SexpToken, Error}; | random_line_split |
packetiser.rs | use std::collections::VecDeque;
use std::mem;
use serde::de;
use super::{SexpToken, Error};
use reader::Reader;
use tokeniser::Tokeniser;
#[derive(Debug)]
pub struct Packetiser {
tok: Tokeniser,
buf: VecDeque<SexpToken>,
parens_open: usize,
}
impl Packetiser {
pub fn new() -> Packetiser {
Pac... | (&mut self, buf: &[u8]) {
self.tok.feed(buf);
}
pub fn take<A: de::Deserialize>(&mut self) -> Result<Option<A>, super::Error> {
// use std::io::Write;
while let Some(tok) = try!(self.tok.take()) {
match tok {
SexpToken::OpenParen => self.parens_open += 1,
... | feed | identifier_name |
packetiser.rs | use std::collections::VecDeque;
use std::mem;
use serde::de;
use super::{SexpToken, Error};
use reader::Reader;
use tokeniser::Tokeniser;
#[derive(Debug)]
pub struct Packetiser {
tok: Tokeniser,
buf: VecDeque<SexpToken>,
parens_open: usize,
}
impl Packetiser {
pub fn new() -> Packetiser {
Pac... |
pub fn take<A: de::Deserialize>(&mut self) -> Result<Option<A>, super::Error> {
// use std::io::Write;
while let Some(tok) = try!(self.tok.take()) {
match tok {
SexpToken::OpenParen => self.parens_open += 1,
SexpToken::CloseParen => self.parens_open -= 1,... | {
self.tok.feed(buf);
} | identifier_body |
custom-quote.rs | // force-host
// no-prefer-dynamic
// ignore-tidy-linelength
#![feature(proc_macro_quote)]
#![crate_type = "proc-macro"]
extern crate proc_macro;
use std::str::FromStr;
use proc_macro::*;
#[proc_macro]
pub fn | (input: TokenStream) -> TokenStream {
let mut tokens: Vec<_> = input.into_iter().collect();
assert_eq!(tokens.len(), 1, "Unexpected input: {:?}", tokens);
match tokens.pop() {
Some(TokenTree::Ident(ident)) => {
assert_eq!(ident.to_string(), "my_ident");
let proc_macro_crate ... | custom_quote | identifier_name |
custom-quote.rs | // force-host
// no-prefer-dynamic
// ignore-tidy-linelength
#![feature(proc_macro_quote)]
#![crate_type = "proc-macro"]
extern crate proc_macro;
use std::str::FromStr;
use proc_macro::*; |
#[proc_macro]
pub fn custom_quote(input: TokenStream) -> TokenStream {
let mut tokens: Vec<_> = input.into_iter().collect();
assert_eq!(tokens.len(), 1, "Unexpected input: {:?}", tokens);
match tokens.pop() {
Some(TokenTree::Ident(ident)) => {
assert_eq!(ident.to_string(), "my_ident");
... | random_line_split | |
custom-quote.rs | // force-host
// no-prefer-dynamic
// ignore-tidy-linelength
#![feature(proc_macro_quote)]
#![crate_type = "proc-macro"]
extern crate proc_macro;
use std::str::FromStr;
use proc_macro::*;
#[proc_macro]
pub fn custom_quote(input: TokenStream) -> TokenStream | {
let mut tokens: Vec<_> = input.into_iter().collect();
assert_eq!(tokens.len(), 1, "Unexpected input: {:?}", tokens);
match tokens.pop() {
Some(TokenTree::Ident(ident)) => {
assert_eq!(ident.to_string(), "my_ident");
let proc_macro_crate = TokenStream::from_str("::proc_macr... | identifier_body | |
stability.rs | id, stab);
} else if self.index.staged_api && required
&& self.export_map.contains(&id)
&&!self.sess.opts.test {
self.sess.span_err(item_sp,
"This node does ... | // This is an 'unmarked' API, which should not exist
// in the standard library.
if self.tcx.sess.features.borrow().unmarked_api {
self.tcx.sess.span_warn(span, "use of unmarked library feature");
self.tcx.sess.span_note(span, "this... | // handled by a lint.
}
None => { | random_line_split |
stability.rs | , stab);
} else if self.index.staged_api && required
&& self.export_map.contains(&id)
&&!self.sess.opts.test {
self.sess.span_err(item_sp,
"This node does no... | (tcx: &ty::ctxt, item: &ast::Item, warn_about_defns: bool,
cb: &mut FnMut(ast::DefId, Span, &Option<Stability>)) {
match item.node {
ast::ItemExternCrate(_) => {
// compiler-generated `extern crate` items have a dummy span.
if item.span == DUMMY_SP { return }
... | check_item | identifier_name |
stability.rs | , stab);
} else if self.index.staged_api && required
&& self.export_map.contains(&id)
&&!self.sess.opts.test {
self.sess.span_err(item_sp,
"This node does no... |
ty::ty_tup(..) => return,
_ => tcx.sess.span_bug(e.span,
"stability::check_expr: unnamed field access on \
something other than a tuple or struct")
}
}
ast::ExprStruct(_, ref expr_... | {
ty::lookup_struct_fields(tcx, did)
.get(field.node)
.unwrap_or_else(|| {
tcx.sess.span_bug(field.span,
"stability::check_expr: unknown unnamed field access")
... | conditional_block |
task-perf-alloc-unwind.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... |
fn run(repeat: isize, depth: isize) {
for _ in 0..repeat {
let dur = Duration::span(|| {
let _ = thread::spawn(move|| {
recurse_or_panic(depth, None)
}).join();
});
println!("iter: {}", dur);
}
}
type nillist = List<()>;
// Filled with things t... | {
let (repeat, depth) = if env::var_os("RUST_BENCH").is_some() {
(50, 1000)
} else {
(10, 10)
};
run(repeat, depth);
} | identifier_body |
task-perf-alloc-unwind.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | ;
run(repeat, depth);
}
fn run(repeat: isize, depth: isize) {
for _ in 0..repeat {
let dur = Duration::span(|| {
let _ = thread::spawn(move|| {
recurse_or_panic(depth, None)
}).join();
});
println!("iter: {}", dur);
}
}
type nillist = List<(... | {
(10, 10)
} | conditional_block |
task-perf-alloc-unwind.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | v.push_all(&[box List::Cons((), st.vec.last().unwrap().clone())]);
State {
unique: box List::Cons((), box *st.unique),
vec: v,
res: r(box List::Cons((), st.res._l.clone())),
}
}
};
re... | random_line_split | |
task-perf-alloc-unwind.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | (depth: isize, st: Option<State>) {
if depth == 0 {
panic!();
} else {
let depth = depth - 1;
let st = match st {
None => {
State {
unique: box List::Nil,
vec: vec!(box List::Nil),
res: r(box List::N... | recurse_or_panic | identifier_name |
textbox_test.rs | #[macro_use]
extern crate kiss_ui;
use kiss_ui::prelude::*;
use kiss_ui::button::Button;
use kiss_ui::container::Vertical;
use kiss_ui::dialog;
use kiss_ui::text::{Label, TextBox};
fn main() |
fn show_alert_message(clicked: Button) {
let dialog = clicked.get_dialog().unwrap();
let text_box = dialog.get_child("my_textbox").unwrap()
.try_downcast::<TextBox>().ok().expect("child my_textbox was not a TextBox!");
let text = text_box.get_text();
dialog::message_popup("Message saved!", for... | {
kiss_ui::show_gui(|| {
Dialog::new(
Vertical::new(
children![
Label::new("Enter a message:"),
TextBox::new()
.set_visible_columns(20)
.set_name("my_textbox"),
Button::new... | identifier_body |
textbox_test.rs | #[macro_use]
extern crate kiss_ui;
use kiss_ui::prelude::*;
use kiss_ui::button::Button;
use kiss_ui::container::Vertical;
use kiss_ui::dialog;
use kiss_ui::text::{Label, TextBox};
fn main() {
kiss_ui::show_gui(|| {
Dialog::new(
Vertical::new(
children![
La... | } | random_line_split | |
textbox_test.rs | #[macro_use]
extern crate kiss_ui;
use kiss_ui::prelude::*;
use kiss_ui::button::Button;
use kiss_ui::container::Vertical;
use kiss_ui::dialog;
use kiss_ui::text::{Label, TextBox};
fn | () {
kiss_ui::show_gui(|| {
Dialog::new(
Vertical::new(
children![
Label::new("Enter a message:"),
TextBox::new()
.set_visible_columns(20)
.set_name("my_textbox"),
Button::ne... | main | identifier_name |
main.rs | fn main() {
let input = String::from("hepxcrrq");
let password = next_password(&next_password(&input));
println!("Santa's next next password is {} :D", password);
}
fn next_password(s: &String) -> String {
let mut ret = s.clone();
loop {
ret = increment_password(&ret);
if is_valid... | ,
_ => false
};
chars[index] = c as char;
}
String::from_utf8(chars.iter().map(|x| *x as u8).collect::<Vec<_>>()).unwrap()
}
fn is_valid(s: &String) -> bool {
has_straight(s) &&
!contains_invalid_chars(s) &&
contains_two_pairs(s)
}
fn has_straight(s: &String) -> ... | { // ascii 'z' + 1
c = 0x61; // ascii 'a'
true
} | conditional_block |
main.rs | fn main() |
fn next_password(s: &String) -> String {
let mut ret = s.clone();
loop {
ret = increment_password(&ret);
if is_valid(&ret) {
break;
}
}
ret
}
fn increment_password(s: &String) -> String {
let mut chars = s.chars().collect::<Vec<_>>();
let mut carry = true;
... | {
let input = String::from("hepxcrrq");
let password = next_password(&next_password(&input));
println!("Santa's next next password is {} :D", password);
} | identifier_body |
main.rs | fn main() {
let input = String::from("hepxcrrq");
let password = next_password(&next_password(&input));
println!("Santa's next next password is {} :D", password);
}
fn next_password(s: &String) -> String {
let mut ret = s.clone();
loop {
ret = increment_password(&ret);
if is_valid... | if chars[i] == chars[i + 1] {
for j in i + 2..s.len() - 1 {
if chars[j] == chars[j + 1] {
return true;
}
}
}
}
return false;
} |
fn contains_two_pairs(s: &String) -> bool {
let chars = s.chars().collect::<Vec<_>>();
for i in 0..s.len() - 1 { | random_line_split |
main.rs | fn main() {
let input = String::from("hepxcrrq");
let password = next_password(&next_password(&input));
println!("Santa's next next password is {} :D", password);
}
fn next_password(s: &String) -> String {
let mut ret = s.clone();
loop {
ret = increment_password(&ret);
if is_valid... | (s: &String) -> bool {
let chars = s.chars().collect::<Vec<_>>();
for i in 0..s.len() - 1 {
if chars[i] == chars[i + 1] {
for j in i + 2..s.len() - 1 {
if chars[j] == chars[j + 1] {
return true;
}
}
}
}
return fa... | contains_two_pairs | identifier_name |
kill.rs | use log::{error, info, warn};
use pueue_lib::network::message::{Signal, TaskSelection};
use pueue_lib::state::GroupStatus;
use pueue_lib::task::TaskStatus;
use crate::ok_or_shutdown;
use crate::platform::process_helper::*;
use crate::state_helper::save_state;
use crate::task_handler::{Shutdown, TaskHandler};
impl Ta... | (
&mut self,
tasks: TaskSelection,
kill_children: bool,
pause_groups: bool,
signal: Option<Signal>,
) {
let cloned_state_mutex = self.state.clone();
let mut state = cloned_state_mutex.lock().unwrap();
// Get the keys of all tasks that should be resumed... | kill | identifier_name |
kill.rs | use log::{error, info, warn};
use pueue_lib::network::message::{Signal, TaskSelection};
use pueue_lib::state::GroupStatus;
use pueue_lib::task::TaskStatus;
use crate::ok_or_shutdown;
use crate::platform::process_helper::*;
use crate::state_helper::save_state;
use crate::task_handler::{Shutdown, TaskHandler};
impl Ta... |
info!("Killing tasks of group {group_name}");
let (matching, _) = state.filter_tasks_of_group(
|task| matches!(task.status, TaskStatus::Running | TaskStatus::Paused),
&group_name,
);
matching
}
... | {
group.status = GroupStatus::Paused;
} | conditional_block |
kill.rs | use log::{error, info, warn};
use pueue_lib::network::message::{Signal, TaskSelection};
use pueue_lib::state::GroupStatus;
use pueue_lib::task::TaskStatus;
use crate::ok_or_shutdown;
use crate::platform::process_helper::*;
use crate::state_helper::save_state;
use crate::task_handler::{Shutdown, TaskHandler};
| ///
/// `kill_children` Kill all direct child processes as well
/// `pause_groups` If `group` or `all` is given, the groups should be paused under some
/// circumstances. This is mostly to prevent any further task execution during an emergency
/// `signal` Don't kill the task as usual, but rathe... | impl TaskHandler {
/// Kill specific tasks or groups.
///
/// By default, this kills tasks with Rust's subprocess handling "kill" logic.
/// However, the user can decide to send unix signals to the processes as well. | random_line_split |
kill.rs | use log::{error, info, warn};
use pueue_lib::network::message::{Signal, TaskSelection};
use pueue_lib::state::GroupStatus;
use pueue_lib::task::TaskStatus;
use crate::ok_or_shutdown;
use crate::platform::process_helper::*;
use crate::state_helper::save_state;
use crate::task_handler::{Shutdown, TaskHandler};
impl Ta... | |task| matches!(task.status, TaskStatus::Running | TaskStatus::Paused),
&group_name,
);
matching
}
TaskSelection::All => {
// Pause all running tasks
if pause_groups {
stat... | {
let cloned_state_mutex = self.state.clone();
let mut state = cloned_state_mutex.lock().unwrap();
// Get the keys of all tasks that should be resumed
let task_ids = match tasks {
TaskSelection::TaskIds(task_ids) => task_ids,
TaskSelection::Group(group_name) => {
... | identifier_body |
extern.rs | extern "C" {
fn c_func(x: *mut *mut libc::c_void);
fn c_func(x: XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX,
y: YYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYY);
#[test123]
fn foo() -> uint64_t;
pub fn bar();
}
extern "C" {
fn DMR_GetDevice(pHDev: *mut HDEV,
searchMo... | }
extern "C" {} | random_line_split | |
tail-cps.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | (n: int, k: fn(bool) -> bool) -> bool {
println!("evenk");
println!("{:?}", n);
if n == 0 { return k(true); } else { return oddk(n - 1, k); }
}
fn oddk(n: int, k: fn(bool) -> bool) -> bool {
println!("oddk");
println!("{:?}", n);
if n == 0 { return k(false); } else { return evenk(n - 1, k); }
}... | evenk | identifier_name |
tail-cps.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... |
}
fn oddk(n: int, k: fn(bool) -> bool) -> bool {
println!("oddk");
println!("{:?}", n);
if n == 0 { return k(false); } else { return evenk(n - 1, k); }
}
| { return oddk(n - 1, k); } | conditional_block |
tail-cps.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | if n == 0 { return k(true); } else { return oddk(n - 1, k); }
}
fn oddk(n: int, k: fn(bool) -> bool) -> bool {
println!("oddk");
println!("{:?}", n);
if n == 0 { return k(false); } else { return evenk(n - 1, k); }
} |
fn evenk(n: int, k: fn(bool) -> bool) -> bool {
println!("evenk");
println!("{:?}", n); | random_line_split |
tail-cps.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... |
pub fn main() { let k = checktrue; evenk(42, k); oddk(45, k); }
fn evenk(n: int, k: fn(bool) -> bool) -> bool {
println!("evenk");
println!("{:?}", n);
if n == 0 { return k(true); } else { return oddk(n - 1, k); }
}
fn oddk(n: int, k: fn(bool) -> bool) -> bool {
println!("oddk");
println!("{:?}"... | { assert!((rs)); return true; } | identifier_body |
lib.rs | #![feature(raw)]
extern crate fixed_size_array;
use std::{ptr, raw};
use std::marker::PhantomData;
use std::raw::Repr;
use fixed_size_array::FixedSizeArray;
/// An iterator constructed by the `literator!` macro.
pub struct Literator<Array, Elem>
where Array: FixedSizeArray<Elem=Elem>
{
pos: isize,
array... | (&mut self) {
unsafe {
let raw::Slice { data, len } = self.as_mut_slice().repr();
let mut i = self.pos;
while (i as usize) < len {
// drop remaining elements
ptr::read(data.offset(i) as *mut Elem);
i += 1;
}
... | drop | identifier_name |
lib.rs | #![feature(raw)]
extern crate fixed_size_array;
use std::{ptr, raw};
use std::marker::PhantomData;
use std::raw::Repr;
use fixed_size_array::FixedSizeArray;
/// An iterator constructed by the `literator!` macro.
pub struct Literator<Array, Elem>
where Array: FixedSizeArray<Elem=Elem>
{
pos: isize,
array... |
fn as_mut_slice<'a>(&'a mut self) -> &'a mut [Elem] {
self.array.as_mut().unwrap().as_mut_slice()
}
}
impl<Array, Elem> Iterator for Literator<Array, Elem>
where Array: FixedSizeArray<Elem=Elem>
{
type Item = Elem;
fn next(&mut self) -> Option<Elem> {
let raw::Slice { data, len }... | {
Literator {
pos: 0,
array: Some(array),
phantom: PhantomData,
}
} | identifier_body |
lib.rs | #![feature(raw)]
extern crate fixed_size_array;
use std::{ptr, raw};
use std::marker::PhantomData;
use std::raw::Repr;
use fixed_size_array::FixedSizeArray;
/// An iterator constructed by the `literator!` macro.
pub struct Literator<Array, Elem>
where Array: FixedSizeArray<Elem=Elem>
{
pos: isize,
array... | else {
self.pos += 1;
Some(unsafe {
// We know we'll never use this array location again,
// so it's okay to force a move out.
ptr::read(data.offset(i) as *mut Elem)
})
}
}
}
impl<Array, Elem> Drop for Literator<Array, Ele... | {
None
} | conditional_block |
lib.rs | #![feature(raw)]
extern crate fixed_size_array;
use std::{ptr, raw};
use std::marker::PhantomData;
use std::raw::Repr;
use fixed_size_array::FixedSizeArray;
/// An iterator constructed by the `literator!` macro.
pub struct Literator<Array, Elem>
where Array: FixedSizeArray<Elem=Elem>
{
pos: isize, |
impl<Array, Elem> Literator<Array, Elem>
where Array: FixedSizeArray<Elem=Elem>
{
pub fn new(array: Array) -> Literator<Array, Elem> {
Literator {
pos: 0,
array: Some(array),
phantom: PhantomData,
}
}
fn as_mut_slice<'a>(&'a mut self) -> &'a mut [Ele... | array: Option<Array>,
phantom: PhantomData<[Elem; 17]>,
} | random_line_split |
rpc.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... | {
let net_cfg = NetworkConfiguration::from(BasicNetworkConfiguration::new_local());
let serialized = serialize(&net_cfg).unwrap();
let deserialized = deserialize::<NetworkConfiguration>(&serialized).unwrap();
assert_eq!(net_cfg.udp_port, deserialized.udp_port);
} | identifier_body | |
rpc.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... | () {
let net_cfg = NetworkConfiguration::from(BasicNetworkConfiguration::new_local());
let serialized = serialize(&net_cfg).unwrap();
let deserialized = deserialize::<NetworkConfiguration>(&serialized).unwrap();
assert_eq!(net_cfg.udp_port, deserialized.udp_port);
}
| network_settings_serialize | identifier_name |
rpc.rs | // Copyright 2015, 2016 Parity Technologies (UK) Ltd. | // Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// Parity is distributed in the hope that it will be useful,
// but WITHO... | // This file is part of Parity.
| random_line_split |
inherited_box.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 http://mozilla.org/MPL/2.0/. */
<%namespace name="helpers" file="/helpers.mako.rs" />
<% data.new_style_struct("InheritedBox", inherited=True, ge... | animation_value_type="none",
spec="https://drafts.csswg.org/css-writing-modes/#propdef-writing-mode",
servo_restyle_damage="rebuild_and_reflow",
)}
${helpers.single_keyword(
"direction",
"ltr rtl",
animation_value_type="none",
spec="https://drafts.csswg.org/css-writing-modes/#propdef-direct... | tb=vertical-rl tb-rl=vertical-rl",
servo_pref="layout.writing-mode.enabled", | random_line_split |
serde.rs | extern crate serde;
use self::serde::json::{self, Value};
use types::test_type;
#[test]
fn | () {
test_type("JSON", &[(Some(json::from_str::<Value>("[10, 11, 12]").unwrap()),
"'[10, 11, 12]'"),
(Some(json::from_str::<Value>("{\"f\": \"asd\"}").unwrap()),
"'{\"f\": \"asd\"}'"),
(None, "NULL")])
}
#[test]
fn test_j... | test_json_params | identifier_name |
serde.rs | extern crate serde;
use self::serde::json::{self, Value};
use types::test_type;
#[test]
fn test_json_params() {
test_type("JSON", &[(Some(json::from_str::<Value>("[10, 11, 12]").unwrap()),
"'[10, 11, 12]'"),
(Some(json::from_str::<Value>("{\"f\": \"asd\"}").unwrap())... | {
test_type("JSONB", &[(Some(json::from_str::<Value>("[10, 11, 12]").unwrap()),
"'[10, 11, 12]'"),
(Some(json::from_str::<Value>("{\"f\": \"asd\"}").unwrap()),
"'{\"f\": \"asd\"}'"),
(None, "NULL")])
} | identifier_body | |
serde.rs | extern crate serde; | use self::serde::json::{self, Value};
use types::test_type;
#[test]
fn test_json_params() {
test_type("JSON", &[(Some(json::from_str::<Value>("[10, 11, 12]").unwrap()),
"'[10, 11, 12]'"),
(Some(json::from_str::<Value>("{\"f\": \"asd\"}").unwrap()),
... | random_line_split | |
cookie.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/. */
//! Implementation of cookie creation and matching as specified by
//! http://tools.ietf.org/html/rfc6265
use coo... |
if string.ends_with(domain_string)
&& string.as_bytes()[string.len()-domain_string.len()-1] == b'.'
&& string.parse::<Ipv4Addr>().is_err()
&& string.parse::<Ipv6Addr>().is_err() {
return true;
}
false
}
// http://tools.ietf.org/html/rfc62... | {
return true;
} | conditional_block |
cookie.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/. */
//! Implementation of cookie creation and matching as specified by
//! http://tools.ietf.org/html/rfc6265
use coo... | if self.cookie.secure && url.scheme!= "https".to_string() {
return false;
}
if self.cookie.httponly && source == CookieSource::NonHTTP {
return false;
}
return true;
}
} | random_line_split | |
cookie.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/. */
//! Implementation of cookie creation and matching as specified by
//! http://tools.ietf.org/html/rfc6265
use coo... | (mut cookie: cookie_rs::Cookie, request: &Url, source: CookieSource)
-> Option<Cookie> {
// Step 3
let (persistent, expiry_time) = match (&cookie.max_age, &cookie.expires) {
(&Some(max_age), _) => {
(true, Some(at(now().to_timespec() + Duration::seconds... | new_wrapped | identifier_name |
cookie.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/. */
//! Implementation of cookie creation and matching as specified by
//! http://tools.ietf.org/html/rfc6265
use coo... | }
// Step 6
let host_only = if!domain.is_empty() {
if!Cookie::domain_match(&url_host, &domain) {
return None;
} else {
cookie.domain = Some(domain);
false
}
} else {
cookie.domain = Some(url_... | {
// Step 3
let (persistent, expiry_time) = match (&cookie.max_age, &cookie.expires) {
(&Some(max_age), _) => {
(true, Some(at(now().to_timespec() + Duration::seconds(max_age as i64))))
}
(_, &Some(expires)) => (true, Some(expires)),
_ => (... | identifier_body |
rejuv_histogram_overheal.rs | extern crate wow_combat_log;
extern crate chrono;
use std::fs::File;
use std::io::BufReader;
use std::collections::HashMap;
use std::fmt;
use chrono::Duration;
static REJUV_AURAS: &'static [u32] = &[
774, // Rejuv
155777, // Rejuv (Germ)
];
#[derive(Debug, Clone, Default)]
struct RestoComputation<'a> {
... | },
Heal { id, heal: total_heal, overheal,.. } if REJUV_AURAS.contains(&id) => {
if log.timestamp() < filter_start_time {
return;
}
let i = if id == REJUV_AURAS[0] { 0 } else { 1 };
self.histo[entry[i]].0 += ove... | let entry = self.map.entry(log.base().unwrap().dst.id).or_insert([0, 0]);
match *log {
Aura { ty, id, .. } if REJUV_AURAS.contains(&id) && ty != Remove => {
let i = if id == REJUV_AURAS[0] { 0 } else { 1 };
entry[i] = 0; | random_line_split |
rejuv_histogram_overheal.rs | extern crate wow_combat_log;
extern crate chrono;
use std::fs::File;
use std::io::BufReader;
use std::collections::HashMap;
use std::fmt;
use chrono::Duration;
static REJUV_AURAS: &'static [u32] = &[
774, // Rejuv
155777, // Rejuv (Germ)
];
#[derive(Debug, Clone, Default)]
struct RestoComputation<'a> {
... | (&mut self, rhs: &'b RestoComputation<'c>) {
for (i, j) in self.histo.iter_mut().zip(rhs.histo.iter()) {
i.0 -= j.0;
i.1 -= j.1;
i.2 -= j.2;
}
}
}
fn main() {
let read = BufReader::new(File::open(std::env::args().nth(1).unwrap()).unwrap());
let player = s... | sub_assign | identifier_name |
rejuv_histogram_overheal.rs | extern crate wow_combat_log;
extern crate chrono;
use std::fs::File;
use std::io::BufReader;
use std::collections::HashMap;
use std::fmt;
use chrono::Duration;
static REJUV_AURAS: &'static [u32] = &[
774, // Rejuv
155777, // Rejuv (Germ)
];
#[derive(Debug, Clone, Default)]
struct RestoComputation<'a> {
... |
}
fn main() {
let read = BufReader::new(File::open(std::env::args().nth(1).unwrap()).unwrap());
let player = std::env::args().nth(2).unwrap();
let intern = wow_combat_log::Interner::default();
let start = std::env::args().nth(3).map(|x| Duration::seconds(x.parse().unwrap())).unwrap_or(Duration::zero()... | {
for (i, j) in self.histo.iter_mut().zip(rhs.histo.iter()) {
i.0 -= j.0;
i.1 -= j.1;
i.2 -= j.2;
}
} | identifier_body |
lib.rs | // Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MI... | pub mod dataflow;
pub mod dead;
pub mod def;
pub mod dependency_format;
pub mod effect;
pub mod entry;
pub mod expr_use_visitor;
pub mod fast_reject;
pub mod graph;
pub mod intrinsicck;
pub mod lang_items;
pub mod liveness;
pub mod mem_categorization;
pub mod pat_... | random_line_split | |
worker.rs |
use std::thread;
use std::thread::JoinHandle;
use std::sync::mpsc::channel;
use std::sync::mpsc::Sender;
use std::sync::mpsc::SendError;
use alto::Alto;
use notify::{RecommendedWatcher, Watcher, RecursiveMode, RawEvent};
use rand;
use super::engine::{SoundEngineUpdate, SoundEngine};
pub struct SoundWorker {
s... | (self) {
// println!("sending stop");
self.send(SoundEngineUpdate::Stop).unwrap();
// println!("joining");
self.join_handle.join().unwrap();
// println!("thread joined");
}
pub fn create(open_al_path: String, resources_path:String, extension:String, rng: rand::XorShiftRn... | shutdown_and_wait | identifier_name |
worker.rs | use std::thread;
use std::thread::JoinHandle;
use std::sync::mpsc::channel;
use std::sync::mpsc::Sender;
use std::sync::mpsc::SendError;
use alto::Alto;
use notify::{RecommendedWatcher, Watcher, RecursiveMode, RawEvent};
use rand;
use super::engine::{SoundEngineUpdate, SoundEngine};
pub struct SoundWorker {
se... | break;
},
}
}
});
SoundWorker {
send_channel: tx,
join_handle: join_handle,
}
}
} | println!("Sound worker received error when reading from channel {:?}", recv_error); | random_line_split |
worker.rs |
use std::thread;
use std::thread::JoinHandle;
use std::sync::mpsc::channel;
use std::sync::mpsc::Sender;
use std::sync::mpsc::SendError;
use alto::Alto;
use notify::{RecommendedWatcher, Watcher, RecursiveMode, RawEvent};
use rand;
use super::engine::{SoundEngineUpdate, SoundEngine};
pub struct SoundWorker {
s... | break;
}
}
match engine.process(&mut cb, event) {
Ok(true) => (),
Ok(false) => {
// println!("Sound engine shutting down");... | {
// println!("worker receiving event {:?}", event);
let mut purge = false;
'fs: loop {
match notify_rx.try_recv() {
Ok(RawEvent { path, op:_, cookie:_ }) => {
... | conditional_block |
worker.rs |
use std::thread;
use std::thread::JoinHandle;
use std::sync::mpsc::channel;
use std::sync::mpsc::Sender;
use std::sync::mpsc::SendError;
use alto::Alto;
use notify::{RecommendedWatcher, Watcher, RecursiveMode, RawEvent};
use rand;
use super::engine::{SoundEngineUpdate, SoundEngine};
pub struct SoundWorker {
s... |
pub fn shutdown_and_wait(self) {
// println!("sending stop");
self.send(SoundEngineUpdate::Stop).unwrap();
// println!("joining");
self.join_handle.join().unwrap();
// println!("thread joined");
}
pub fn create(open_al_path: String, resources_path:String, extension... | {
self.send_channel.send(update)
} | identifier_body |
helpers.rs | extern crate indy_crypto;
use errors::prelude::*;
use domain::anoncreds::credential::AttributeValues;
use domain::anoncreds::proof_request::{AttributeInfo, PredicateInfo};
use self::indy_crypto::cl::{issuer, verifier, CredentialSchema, NonCredentialSchema, MasterSecret, CredentialValues, SubProofRequest};
use std:... |
let res = credential_values_builder.finalize()?;
trace!("build_credential_values <<< res: {:?}", res);
Ok(res)
}
pub fn build_sub_proof_request(attrs_for_credential: &Vec<AttributeInfo>,
predicates_for_credential: &Vec<PredicateInfo>) -> IndyResult<SubProofRequest> {
... | {
credential_values_builder.add_value_hidden("master_secret", &ms.value()?)?;
} | conditional_block |
helpers.rs | extern crate indy_crypto;
use errors::prelude::*;
use domain::anoncreds::credential::AttributeValues;
use domain::anoncreds::proof_request::{AttributeInfo, PredicateInfo};
use self::indy_crypto::cl::{issuer, verifier, CredentialSchema, NonCredentialSchema, MasterSecret, CredentialValues, SubProofRequest};
use std:... |
pub fn build_credential_schema(attrs: &HashSet<String>) -> IndyResult<CredentialSchema> {
trace!("build_credential_schema >>> attrs: {:?}", attrs);
let mut credential_schema_builder = issuer::Issuer::new_credential_schema_builder()?;
for attr in attrs {
credential_schema_builder.add_attr(&attr_co... | {
attr.replace(" ", "").to_lowercase()
} | identifier_body |
helpers.rs | extern crate indy_crypto;
use errors::prelude::*;
use domain::anoncreds::credential::AttributeValues;
use domain::anoncreds::proof_request::{AttributeInfo, PredicateInfo};
use self::indy_crypto::cl::{issuer, verifier, CredentialSchema, NonCredentialSchema, MasterSecret, CredentialValues, SubProofRequest};
use std:... |
Ok(res)
}
pub fn build_sub_proof_request(attrs_for_credential: &Vec<AttributeInfo>,
predicates_for_credential: &Vec<PredicateInfo>) -> IndyResult<SubProofRequest> {
trace!("build_sub_proof_request >>> attrs_for_credential: {:?}, predicates_for_credential: {:?}", attrs_for_creden... |
trace!("build_credential_values <<< res: {:?}", res); | random_line_split |
helpers.rs | extern crate indy_crypto;
use errors::prelude::*;
use domain::anoncreds::credential::AttributeValues;
use domain::anoncreds::proof_request::{AttributeInfo, PredicateInfo};
use self::indy_crypto::cl::{issuer, verifier, CredentialSchema, NonCredentialSchema, MasterSecret, CredentialValues, SubProofRequest};
use std:... | (attrs_for_credential: &Vec<AttributeInfo>,
predicates_for_credential: &Vec<PredicateInfo>) -> IndyResult<SubProofRequest> {
trace!("build_sub_proof_request >>> attrs_for_credential: {:?}, predicates_for_credential: {:?}", attrs_for_credential, predicates_for_credential);
let mut... | build_sub_proof_request | identifier_name |
callback_executors.rs | //! Executor abstraction for executing callbacks to user code (request filters, provider state change callbacks)
use std::collections::HashMap;
use std::sync::Arc;
use ansi_term::Colour::Yellow;
use async_trait::async_trait;
use maplit::*;
use serde_json::{json, Value};
use pact_matching::models::{OptionalBody, Requ... | {
/// URL to post state change requests to
pub state_change_url: Option<String>,
/// If teardown state change requests should be made (default is false)
pub state_change_teardown: bool,
/// If state change request data should be sent in the body (true) or as query parameters (false)
pub state_change_body: ... | HttpRequestProviderStateExecutor | identifier_name |
callback_executors.rs | //! Executor abstraction for executing callbacks to user code (request filters, provider state change callbacks)
use std::collections::HashMap;
use std::sync::Arc;
use ansi_term::Colour::Yellow;
use async_trait::async_trait;
use maplit::*;
use serde_json::{json, Value};
use pact_matching::models::{OptionalBody, Requ... | Ok(hashmap!{})
}
}
}
} | None => {
if setup {
println!(" {}", Yellow.paint("WARNING: State Change ignored as there is no state change URL provided"));
} | random_line_split |
len_zero.rs | IdSet;
use rustc_hir::{
def_id::DefId, AssocItemKind, BinOpKind, Expr, ExprKind, FnRetTy, ImplItem, ImplItemKind, ImplicitSelfKind, Item,
ItemKind, Mutability, Node, TraitItemRef, TyKind,
};
use rustc_lint::{LateContext, LateLintPass};
use rustc_middle::ty::{self, AssocKind, FnSig, Ty, TyS};
use rustc_session::... | raitt: DefId, set: &mut DefIdSet, cx: &LateContext<'_>) {
if set.insert(traitt) {
for supertrait in rustc_trait_selection::traits::supertrait_def_ids(cx.tcx, traitt) {
fill_trait_set(supertrait, set, cx);
}
}
}
if cx.access_levels.is_exported(visited_trai... | ll_trait_set(t | identifier_name |
len_zero.rs | DefIdSet;
use rustc_hir::{
def_id::DefId, AssocItemKind, BinOpKind, Expr, ExprKind, FnRetTy, ImplItem, ImplItemKind, ImplicitSelfKind, Item,
ItemKind, Mutability, Node, TraitItemRef, TyKind,
};
use rustc_lint::{LateContext, LateLintPass};
use rustc_middle::ty::{self, AssocKind, FnSig, Ty, TyS};
use rustc_sessio... | _ => false,
}
}
/// Checks if the given type has an `is_empty` method with the appropriate signature.
fn check_for_is_empty(
cx: &LateContext<'_>,
span: Span,
self_kind: ImplicitSelfKind,
output: LenOutput<'_>,
impl_ty: DefId,
item_name: Symbol,
item_kind: &str,
) {
let is_e... | matches!(
(arg.kind(), self_kind),
(ty::Ref(_, _, Mutability::Not), ImplicitSelfKind::ImmRef)
| (ty::Ref(_, _, Mutability::Mut), ImplicitSelfKind::MutRef)
) || (!arg.is_ref() && matches!(self_kind, ImplicitSelfKind::Imm | ImplicitSelfKind::Mut)... | conditional_block |
len_zero.rs | ::DefIdSet;
use rustc_hir::{
def_id::DefId, AssocItemKind, BinOpKind, Expr, ExprKind, FnRetTy, ImplItem, ImplItemKind, ImplicitSelfKind, Item,
ItemKind, Mutability, Node, TraitItemRef, TyKind,
};
use rustc_lint::{LateContext, LateLintPass};
use rustc_middle::ty::{self, AssocKind, FnSig, Ty, TyS};
use rustc_sess... | pub LEN_ZERO,
style,
"checking `.len() == 0` or `.len() > 0` (or similar) when `.is_empty()` could be used instead"
}
declare_clippy_lint! {
/// ### What it does
/// Checks for items that implement `.len()` but not
/// `.is_empty()`.
///
/// ### Why is this bad?
/// It is good custo... | random_line_split | |
len_zero.rs | DefIdSet;
use rustc_hir::{
def_id::DefId, AssocItemKind, BinOpKind, Expr, ExprKind, FnRetTy, ImplItem, ImplItemKind, ImplicitSelfKind, Item,
ItemKind, Mutability, Node, TraitItemRef, TyKind,
};
use rustc_lint::{LateContext, LateLintPass};
use rustc_middle::ty::{self, AssocKind, FnSig, Ty, TyS};
use rustc_sessio... | "{} `{}` has a public `len` method, but a private `is_empty` method",
item_kind,
item_name.as_str(),
),
Some(cx.tcx.def_span(is_empty.def_id)),
None,
),
Some(is_empty)
if!(is_empty.fn_has_self_parameter
... | let is_empty = Symbol::intern("is_empty");
let is_empty = cx
.tcx
.inherent_impls(impl_ty)
.iter()
.flat_map(|&id| cx.tcx.associated_items(id).filter_by_name_unhygienic(is_empty))
.find(|item| item.kind == AssocKind::Fn);
let (msg, is_empty_span, self_kind) = match i... | identifier_body |
foo.rs | //
// 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 distributed
// except according to those terms.
#![feature(optin... | // 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. | random_line_split | |
foo.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 ... | <B>(B);
// @matches foo/struct.Alpha.html '//*[@class="impl"]//code' "impl!Send for Alpha"
impl!Send for Alpha {}
// @matches foo/struct.Bravo.html '//*[@class="impl"]//code' "impl<B>!Send for Bravo<B>"
impl<B>!Send for Bravo<B> {}
| Bravo | identifier_name |
typeobject.rs | // Copyright (c) 2015 Daniel Grunwald
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publis... |
/// Retrieves the PyType instance for the given FFI pointer.
/// This increments the reference count on the type object.
/// Undefined behavior if the pointer is NULL or invalid.
#[inline]
pub unsafe fn from_type_ptr(py: Python, p: *mut ffi::PyTypeObject) -> PyType {
PyObject::from_borrowe... | {
self.0.as_ptr() as *mut ffi::PyTypeObject
} | identifier_body |
typeobject.rs | // Copyright (c) 2015 Daniel Grunwald
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publis... | (&self, o: &PyType) -> bool {
self.as_type_ptr() == o.as_type_ptr()
}
}
impl Eq for PyType {}
| eq | identifier_name |
typeobject.rs | // Copyright (c) 2015 Daniel Grunwald
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publis... | // DEALINGS IN THE SOFTWARE.
use std::borrow::Cow;
use std::ffi::CStr;
use crate::conversion::ToPyObject;
use crate::err::{result_from_owned_ptr, PyResult};
use crate::ffi;
use crate::objects::{PyDict, PyObject, PyTuple};
use crate::python::{Python, PythonObject, ToPythonPointer};
/// Represents a reference to a Pyt... | // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER | random_line_split |
main.rs | use std::fmt;
const SIZE: usize = 8;
const MOVES: [(i32, i32); 8] = [
(2, 1),
(1, 2),
(-1, 2),
(-2, 1),
(-2, -1),
(-1, -2),
(1, -2),
(2, -1),
];
#[derive(Copy, Clone, Eq, PartialEq, PartialOrd, Ord)]
struct | {
x: i32,
y: i32,
}
impl Point {
fn mov(&self, &(dx, dy): &(i32, i32)) -> Point {
Point {
x: self.x + dx,
y: self.y + dy,
}
}
}
struct Board {
field: [[i32; SIZE]; SIZE],
}
impl Board {
fn new() -> Board {
Board {
field: [[0; SIZE];... | Point | identifier_name |
main.rs | use std::fmt;
const SIZE: usize = 8;
const MOVES: [(i32, i32); 8] = [
(2, 1),
(1, 2),
(-1, 2),
(-2, 1),
(-2, -1),
(-1, -2),
(1, -2),
(2, -1),
];
#[derive(Copy, Clone, Eq, PartialEq, PartialOrd, Ord)]
struct Point {
x: i32,
y: i32,
}
impl Point {
fn mov(&self, &(dx, dy): &(... | let degree = board.count_degree(adj);
candidates.push((degree, adj));
}
}
match candidates.iter().min() {
Some(&(_, adj)) => p = adj,
None => return None,
};
board.field[p.x as usize][p.y as usize] = step;
step... |
for dir in &MOVES {
let adj = p.mov(dir);
if board.available(adj) { | random_line_split |
main.rs | use std::fmt;
const SIZE: usize = 8;
const MOVES: [(i32, i32); 8] = [
(2, 1),
(1, 2),
(-1, 2),
(-2, 1),
(-2, -1),
(-1, -2),
(1, -2),
(2, -1),
];
#[derive(Copy, Clone, Eq, PartialEq, PartialOrd, Ord)]
struct Point {
x: i32,
y: i32,
}
impl Point {
fn mov(&self, &(dx, dy): &(... |
}
| {
let (x, y) = (3, 1);
match knights_tour(x, y) {
Some(b) => assert_eq!(b.field, ANSWER),
None => panic!(),
}
} | identifier_body |
crossword.rs | // +--------------------------------------------------------------------------+
// | Copyright 2016 Matthew D. Steele <mdsteele@alum.mit.edu> |
// | |
// | This file is part of System Syzygy. |
... | .words
.iter()
.map(|chars| chars.iter().cloned().collect())
.map(toml::Value::String)
.collect();
toml::Value::Array(words)
}
pub fn can_reset(&self) -> bool {
!self.is_initial
}
pub fn reset(&mut self) {
for word in self.w... | pub fn to_toml(&self) -> toml::Value {
let words = self | random_line_split |
crossword.rs | // +--------------------------------------------------------------------------+
// | Copyright 2016 Matthew D. Steele <mdsteele@alum.mit.edu> |
// | |
// | This file is part of System Syzygy. |
... |
pub fn valid_chars(&self) -> ValidChars {
self.valid
}
pub fn words(&self) -> &Vec<Vec<char>> {
&self.words
}
pub fn words_are(&self, words: &[&str]) -> bool {
let words: Vec<Vec<char>> =
words.iter().map(|word| word.chars().collect()).collect();
self.... | {
for word in self.words.iter_mut() {
for chr in word.iter_mut() {
*chr = ' ';
}
}
self.is_initial = true;
} | identifier_body |
crossword.rs | // +--------------------------------------------------------------------------+
// | Copyright 2016 Matthew D. Steele <mdsteele@alum.mit.edu> |
// | |
// | This file is part of System Syzygy. |
... | (&self, words: &[&str]) -> bool {
let words: Vec<Vec<char>> =
words.iter().map(|word| word.chars().collect()).collect();
self.words == words
}
pub fn get_char(&self, row: i32, index: i32) -> char {
assert!(row >= 0 && row < self.words.len() as i32);
let word = &self.... | words_are | identifier_name |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.