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 |
|---|---|---|---|---|
awakener.rs | use std::sync::{Mutex, Arc};
use {io, Evented, EventSet, PollOpt, Selector, Token};
use sys::windows::selector::SelectorInner;
use wio::iocp::CompletionStatus;
pub struct Awakener {
iocp: Mutex<Option<Registration>>,
}
struct Registration {
iocp: Arc<SelectorInner>,
token: Token,
}
impl Awakener {
p... | () -> io::Result<Awakener> {
Ok(Awakener {
iocp: Mutex::new(None),
})
}
pub fn wakeup(&self) -> io::Result<()> {
// Each wakeup notification has NULL as its `OVERLAPPED` pointer to
// indicate that it's from this awakener and not part of an I/O
// operation. ... | new | identifier_name |
awakener.rs | use std::sync::{Mutex, Arc};
use {io, Evented, EventSet, PollOpt, Selector, Token};
use sys::windows::selector::SelectorInner;
use wio::iocp::CompletionStatus;
pub struct Awakener {
iocp: Mutex<Option<Registration>>,
}
struct Registration {
iocp: Arc<SelectorInner>,
token: Token,
}
impl Awakener {
p... |
Ok(())
}
pub fn cleanup(&self) {
// noop
}
}
impl Evented for Awakener {
fn register(&self, selector: &mut Selector, token: Token, _events: EventSet,
_opts: PollOpt) -> io::Result<()> {
*self.iocp.lock().unwrap() = Some(Registration {
iocp: selector... | {
let status = CompletionStatus::new(0, r.token.as_usize(),
0 as *mut _);
try!(r.iocp.port().post(status));
} | conditional_block |
awakener.rs | use std::sync::{Mutex, Arc};
use {io, Evented, EventSet, PollOpt, Selector, Token};
use sys::windows::selector::SelectorInner;
use wio::iocp::CompletionStatus;
pub struct Awakener {
iocp: Mutex<Option<Registration>>,
}
struct Registration {
iocp: Arc<SelectorInner>,
token: Token,
}
impl Awakener {
p... | });
Ok(())
}
fn reregister(&self, selector: &mut Selector, token: Token, events: EventSet,
opts: PollOpt) -> io::Result<()> {
self.register(selector, token, events, opts)
}
fn deregister(&self, _selector: &mut Selector) -> io::Result<()> {
*self.iocp.l... | iocp: selector.inner().clone(),
token: token, | random_line_split |
catcher.rs | use response;
use handler::ErrorHandler;
use codegen::StaticCatchInfo;
use error::Error;
use request::Request;
use std::fmt;
use term_painter::ToStyle;
use term_painter::Color::*;
/// An error catching route.
///
/// Catchers are routes that run when errors occur. They correspond directly
/// with the HTTP error stat... |
}
macro_rules! error_page_template {
($code:expr, $name:expr, $description:expr) => (
concat!(r#"
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>"#, $code, " ", $name, r#"</title>
</head>
<body align="... | {
write!(f, "{}", Blue.paint(&self.code))
} | identifier_body |
catcher.rs | use response;
use handler::ErrorHandler;
use codegen::StaticCatchInfo;
use error::Error;
use request::Request;
use std::fmt;
use term_painter::ToStyle;
use term_painter::Color::*;
/// An error catching route.
///
/// Catchers are routes that run when errors occur. They correspond directly
/// with the HTTP error stat... | recently.", handle_429,
431, "Request Header Fields Too Large", "The server is unwilling to process
the request because either an individual header field, or all
the header fields collectively, are too large.", handle_431,
451, "Unavailable For Leg... | field is required.", handle_426,
428, "Precondition Required", "The server requires the request to be
conditional.", handle_428,
429, "Too Many Requests", "Too many requests have been received | random_line_split |
catcher.rs | use response;
use handler::ErrorHandler;
use codegen::StaticCatchInfo;
use error::Error;
use request::Request;
use std::fmt;
use term_painter::ToStyle;
use term_painter::Color::*;
/// An error catching route.
///
/// Catchers are routes that run when errors occur. They correspond directly
/// with the HTTP error stat... | () -> HashMap<u16, Catcher> {
default_errors! {
400, "Bad Request", "The request could not be understood by the server due
to malformed syntax.", handle_400,
401, "Unauthorized", "The request requires user authentication.",
handle_401,
402, "Pa... | get | identifier_name |
uint_macros.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 ... | // Rotating by 0 should have no effect
assert_eq!(A.rotate_left(0), A);
assert_eq!(B.rotate_left(0), B);
assert_eq!(C.rotate_left(0), C);
// Rotating by a multiple of word size should also have no effect
assert_eq!(A.rotate_left(64), A);
assert_eq!(B.rotate_left(6... | random_line_split | |
android.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 ... | (signum: c_int, handler: sighandler_t) -> sighandler_t {
weak!(fn signal(c_int, sighandler_t) -> sighandler_t);
weak!(fn bsd_signal(c_int, sighandler_t) -> sighandler_t);
let f = signal.get().or_else(|| bsd_signal.get());
let f = f.expect("neither `signal` nor `bsd_signal` symbols found");
f(signum... | signal | identifier_name |
android.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 ... |
#[cfg(target_pointer_width = "64")]
pub unsafe fn cvt_pwrite64(fd: c_int, buf: *const c_void, count: size_t, offset: i64)
-> io::Result<ssize_t>
{
cvt(pwrite(fd, buf, count, offset))
}
| {
cvt(pread(fd, buf, count, offset))
} | identifier_body |
android.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 ... | use super::{cvt, cvt_r};
// The `log2` and `log2f` functions apparently appeared in android-18, or at
// least you can see they're not present in the android-17 header [1] and they
// are present in android-18 [2].
//
// [1]: https://chromium.googlesource.com/android_tools/+/20ee6d20/ndk/platforms
// ... |
use libc::{c_int, c_void, sighandler_t, size_t, ssize_t};
use libc::{ftruncate, pread, pwrite};
use io; | random_line_split |
lmdb.rs | // Copyright 2021 The Grin Developers
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agree... |
// Check we can not yet see the new entry via an iterator outside the uncommitted batch.
let mut iter = store.iter(&[0], |_, v| Ok(v.to_vec()))?;
assert_eq!(iter.next(), None);
batch.commit()?;
// Check we can see the new entry via an iterator after committing the batch.
let mut iter = store.iter(&[0], |_, v| ... | {
let test_dir = "target/test_iter";
setup(test_dir);
let store = store::Store::new(test_dir, Some("test1"), None, None)?;
let key = [0, 0, 0, 1];
let value = [1, 1, 1, 1];
// Start new batch and insert a new key/value entry.
let batch = store.batch()?;
batch.put(&key, &value)?;
// TODO - This is not curre... | identifier_body |
lmdb.rs | // Copyright 2021 The Grin Developers
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agree... | util::init_test_logger();
clean_output_dir(test_dir);
}
#[test]
fn test_exists() -> Result<(), store::Error> {
let test_dir = "target/test_exists";
setup(test_dir);
let store = store::Store::new(test_dir, Some("test1"), None, None)?;
let key = [0, 0, 0, 1];
let value = [1, 1, 1, 1];
// Start new batch and i... | let _ = fs::remove_dir_all(test_dir);
}
fn setup(test_dir: &str) {
global::set_local_chain_type(global::ChainTypes::Mainnet); | random_line_split |
lmdb.rs | // Copyright 2021 The Grin Developers
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agree... | (test_dir: &str) {
global::set_local_chain_type(global::ChainTypes::Mainnet);
util::init_test_logger();
clean_output_dir(test_dir);
}
#[test]
fn test_exists() -> Result<(), store::Error> {
let test_dir = "target/test_exists";
setup(test_dir);
let store = store::Store::new(test_dir, Some("test1"), None, None)?;
... | setup | identifier_name |
sync_bitset.rs | #[cfg(test)]
mod tests;
use super::{TLS_KEYS_BITSET_SIZE, USIZE_BITS};
use crate::iter::{Enumerate, Peekable};
use crate::slice::Iter;
use crate::sync::atomic::{AtomicUsize, Ordering};
/// A bitset that can be used synchronously.
pub(super) struct SyncBitset([AtomicUsize; TLS_KEYS_BITSET_SIZE]);
pub(super) const SYN... | (&self, index: usize) {
let (hi, lo) = Self::split(index);
self.0[hi].fetch_and(!lo, Ordering::Relaxed);
}
/// Sets any unset bit. Not atomic. Returns `None` if all bits were
/// observed to be set.
pub fn set(&self) -> Option<usize> {
'elems: for (idx, elem) in self.0.iter().en... | clear | identifier_name |
sync_bitset.rs | #[cfg(test)]
mod tests;
use super::{TLS_KEYS_BITSET_SIZE, USIZE_BITS};
use crate::iter::{Enumerate, Peekable};
use crate::slice::Iter;
use crate::sync::atomic::{AtomicUsize, Ordering};
/// A bitset that can be used synchronously.
pub(super) struct SyncBitset([AtomicUsize; TLS_KEYS_BITSET_SIZE]);
pub(super) const SYN... |
pub fn clear(&self, index: usize) {
let (hi, lo) = Self::split(index);
self.0[hi].fetch_and(!lo, Ordering::Relaxed);
}
/// Sets any unset bit. Not atomic. Returns `None` if all bits were
/// observed to be set.
pub fn set(&self) -> Option<usize> {
'elems: for (idx, elem) in... | } | random_line_split |
categorical.rs | use distribution;
use random;
/// A categorical distribution.
#[derive(Clone)]
pub struct Categorical {
k: usize,
p: Vec<f64>,
cumsum: Vec<f64>,
}
impl Categorical {
/// Create a categorical distribution with success probability `p`.
///
/// It should hold that `p[i] >= 0`, `p[i] <= 1`, and `s... | ).collect::<Vec<_>>();
assert!(Independent(&new!(p), &mut source).take(1000).all(|x| x % 2!= 0));
}
#[test]
fn skewness() {
assert_eq!(new!(equal 6).skewness(), 0.0);
assert_eq!(new!([1.0 / 6.0, 1.0 / 3.0, 1.0 / 3.0, 1.0 / 6.0]).skewness(), 0.0);
assert_eq!(new!([0.1, 0.2, 0... | { 0.0 } | conditional_block |
categorical.rs | use distribution;
use random;
/// A categorical distribution.
#[derive(Clone)]
pub struct Categorical {
k: usize,
p: Vec<f64>,
cumsum: Vec<f64>,
}
impl Categorical {
/// Create a categorical distribution with success probability `p`.
///
/// It should hold that `p[i] >= 0`, `p[i] <= 1`, and `s... |
}
impl distribution::Mean for Categorical {
fn mean(&self) -> f64 {
self.p.iter().enumerate().fold(0.0, |sum, (i, p)| sum + i as f64 * p)
}
}
impl distribution::Median for Categorical {
fn median(&self) -> f64 {
if self.p[0] > 0.5 {
return 0.0;
}
if self.p[0] =... | {
use distribution::{Mean, Variance};
let (mean, variance) = (self.mean(), self.variance());
let kurt = self.p.iter().enumerate().fold(0.0, |sum, (i, p)| {
sum + (i as f64 - mean).powi(4) * p
});
kurt / variance.powi(2) - 3.0
} | identifier_body |
categorical.rs | use distribution;
use random;
/// A categorical distribution.
#[derive(Clone)]
pub struct Categorical {
k: usize,
p: Vec<f64>,
cumsum: Vec<f64>,
}
impl Categorical {
/// Create a categorical distribution with success probability `p`.
///
/// It should hold that `p[i] >= 0`, `p[i] <= 1`, and `s... | () {
assert_eq!(new!(equal 3).variance(), 2.0 / 3.0);
assert_eq!(new!([1.0 / 6.0, 1.0 / 3.0, 1.0 / 3.0, 1.0 / 6.0]).variance(), 11.0 / 12.0);
}
}
| variance | identifier_name |
categorical.rs | use distribution;
use random;
/// A categorical distribution.
#[derive(Clone)]
pub struct Categorical {
k: usize,
p: Vec<f64>, | ///
/// It should hold that `p[i] >= 0`, `p[i] <= 1`, and `sum(p) == 1`.
pub fn new(p: &[f64]) -> Categorical {
should!(is_probability_vector(p), {
const EPSILON: f64 = 1e-12;
p.iter().all(|&p| p >= 0.0 && p <= 1.0) &&
(p.iter().fold(0.0, |sum, &p| sum + p) - ... | cumsum: Vec<f64>,
}
impl Categorical {
/// Create a categorical distribution with success probability `p`. | random_line_split |
game.rs | use shogi::{Color, Position, TimeControl};
use std::time::Instant;
#[derive(Debug)]
pub struct Game {
pub black_player: String,
pub white_player: String,
pub pos: Position,
pub time: TimeControl,
pub turn_start_time: Instant,
}
#[derive(Debug, Clone)]
pub struct | {
pub winner: Option<Color>,
pub reason: GameOverReason,
}
impl GameResult {
pub fn new(winner: Option<Color>, reason: GameOverReason) -> GameResult {
GameResult { winner, reason }
}
}
#[derive(Debug, Clone, Copy)]
pub enum GameOverReason {
Resign,
IllegalMove,
OutOfTime,
MaxP... | GameResult | identifier_name |
game.rs | use shogi::{Color, Position, TimeControl};
use std::time::Instant;
#[derive(Debug)]
pub struct Game {
pub black_player: String,
pub white_player: String,
pub pos: Position,
pub time: TimeControl,
pub turn_start_time: Instant,
}
#[derive(Debug, Clone)]
pub struct GameResult {
pub winner: Option... | }
} | turn_start_time: Instant::now(),
} | random_line_split |
utils.rs | use crate::ast::parser;
use crate::ast::rules;
use crate::ast::stack;
use crate::utils;
use crate::interpreter::environment;
use crate::interpreter::types;
#[allow(dead_code)]
pub fn interpret(source_code: &str) -> (types::Type, utils::Shared<environment::Environment>) {
interpret_rule(source_code, rules::chunk)
... |
pub fn interpret_rule_env<F>(
source_code: &str,
func: F,
env: &mut utils::Shared<environment::Environment>,
) -> (types::Type, utils::Shared<environment::Environment>)
where
F: Fn(&mut parser::Parser, &mut stack::Stack) -> bool,
{
let mut parser = parser::Parser::new(source_code.to_string());
... | random_line_split | |
utils.rs | use crate::ast::parser;
use crate::ast::rules;
use crate::ast::stack;
use crate::utils;
use crate::interpreter::environment;
use crate::interpreter::types;
#[allow(dead_code)]
pub fn interpret(source_code: &str) -> (types::Type, utils::Shared<environment::Environment>) {
interpret_rule(source_code, rules::chunk)
... | {
let mut parser = parser::Parser::new(source_code.to_string());
let mut stack = stack::Stack::default();
func(&mut parser, &mut stack);
assert!(
parser.peek().is_none(),
format!("Parser contains tokens after parsing: {:?}", parser)
);
let result = stack.pop_single().eval(env);... | identifier_body | |
utils.rs | use crate::ast::parser;
use crate::ast::rules;
use crate::ast::stack;
use crate::utils;
use crate::interpreter::environment;
use crate::interpreter::types;
#[allow(dead_code)]
pub fn | (source_code: &str) -> (types::Type, utils::Shared<environment::Environment>) {
interpret_rule(source_code, rules::chunk)
}
pub fn interpret_rule<F>(
source_code: &str,
func: F,
) -> (types::Type, utils::Shared<environment::Environment>)
where
F: Fn(&mut parser::Parser, &mut stack::Stack) -> bool,
{
... | interpret | identifier_name |
config.rs | #[derive(Deserialize, Clone)]
pub struct Config {
pub consul: Consul,
pub client: ClientConfig,
pub server: Server,
}
#[derive(Deserialize, Clone)]
pub struct Server {
pub host: String,
pub port: u16,
}
#[derive(Deserialize, Clone)]
pub struct Consul {
pub ssl: bool,
pub address: String,
... | impl From<toml::de::Error> for ConfigError {
fn from(error: toml::de::Error) -> Self {
ConfigError::TomlError(error)
}
}
/// Given a string path, attempt to load the file.
///
/// TODO: This function should do some sanitization on the input path,
/// which will eventually be supplied by a user or defau... | }
} | random_line_split |
config.rs |
#[derive(Deserialize, Clone)]
pub struct Config {
pub consul: Consul,
pub client: ClientConfig,
pub server: Server,
}
#[derive(Deserialize, Clone)]
pub struct Server {
pub host: String,
pub port: u16,
}
#[derive(Deserialize, Clone)]
pub struct Consul {
pub ssl: bool,
pub address: String,
... | (path: String) -> Result<String, ConfigError> {
let mut file = File::open(path)?;
let mut contents = String::new();
let res = file.read_to_string(&mut contents);
match res {
Ok(_) => Ok(contents),
Err(e) => Err(ConfigError::from(e)),
}
}
| read_file | identifier_name |
borrow.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 ... |
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<'a, B:?Sized> fmt::Debug for Cow<'a, B> where
B: fmt::Debug + ToOwned,
<B as ToOwned>::Owned: fmt::Debug,
{
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
Borrowed(ref b) => fmt::Debug::fmt(b, f),
Ow... | {
PartialOrd::partial_cmp(&**self, &**other)
} | identifier_body |
borrow.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 ... | /// [the book][book] for more.
///
/// [book]:../../book/borrow-and-asref.html
#[stable(feature = "rust1", since = "1.0.0")]
pub trait Borrow<Borrowed:?Sized> {
/// Immutably borrows from an owned value.
///
/// # Examples
///
/// ```
/// use std::borrow::Borrow;
///
/// fn check<T: Borr... | /// trait: if `T: Borrow<U>`, then `&U` can be borrowed from `&T`. A given
/// type can be borrowed as multiple different types. In particular, `Vec<T>:
/// Borrow<Vec<T>>` and `Vec<T>: Borrow<[T]>`.
///
/// `Borrow` is very similar to, but different than, `AsRef`. See | random_line_split |
borrow.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | (&self) -> &T { &**self }
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<'a, B:?Sized> Borrow<B> for Cow<'a, B> where B: ToOwned, <B as ToOwned>::Owned: 'a {
fn borrow(&self) -> &B {
&**self
}
}
/// A generalization of `Clone` to borrowed data.
///
/// Some types make it possible to go from borr... | borrow | identifier_name |
show_karma.rs | use regex::Regex;
use ::bot::{Bot, Node, RoomEvent};
use super::backend::Backend;
pub struct ShowKarma<'a> {
vote_db: Backend,
children: Vec<&'a str>,
}
impl<'a> ShowKarma<'a> {
pub fn new() -> Self {
Self {
vote_db: Backend::new(),
children: Vec::new(),
}
}
}... | self.propagate_event(bot, &event);
}
}
}
} | if finds == 0 { | random_line_split |
show_karma.rs | use regex::Regex;
use ::bot::{Bot, Node, RoomEvent};
use super::backend::Backend;
pub struct ShowKarma<'a> {
vote_db: Backend,
children: Vec<&'a str>,
}
impl<'a> ShowKarma<'a> {
pub fn new() -> Self {
Self {
vote_db: Backend::new(),
children: Vec::new(),
}
}
}... |
}
if finds == 0 {
self.propagate_event(bot, &event);
}
}
}
}
| {
let response = format!("Karma for '{}': Net karma: 0 (+0/-0 0% like it)", query);
bot.reply(&event, &response);
} | conditional_block |
show_karma.rs | use regex::Regex;
use ::bot::{Bot, Node, RoomEvent};
use super::backend::Backend;
pub struct ShowKarma<'a> {
vote_db: Backend,
children: Vec<&'a str>,
}
impl<'a> ShowKarma<'a> {
pub fn new() -> Self |
}
impl<'a> Node<'a> for ShowKarma<'a> {
fn children(&self) -> Option<&Vec<&'a str>> {
Some(&self.children)
}
fn register_child(&mut self, name: &'a str) {
self.children.push(name);
}
fn handle(&mut self, bot: &Bot, event: RoomEvent) {
let revent = &event.raw_event;
... | {
Self {
vote_db: Backend::new(),
children: Vec::new(),
}
} | identifier_body |
show_karma.rs | use regex::Regex;
use ::bot::{Bot, Node, RoomEvent};
use super::backend::Backend;
pub struct ShowKarma<'a> {
vote_db: Backend,
children: Vec<&'a str>,
}
impl<'a> ShowKarma<'a> {
pub fn | () -> Self {
Self {
vote_db: Backend::new(),
children: Vec::new(),
}
}
}
impl<'a> Node<'a> for ShowKarma<'a> {
fn children(&self) -> Option<&Vec<&'a str>> {
Some(&self.children)
}
fn register_child(&mut self, name: &'a str) {
self.children.push(n... | new | identifier_name |
index.rs | use std::collections::HashMap;
use std::path::Path;
use std::str;
use serde_json;
use semver::Version;
use core::dependency::Dependency;
use core::{PackageId, SourceId, Summary};
use sources::registry::{RegistryPackage, INDEX_LOCK};
use sources::registry::RegistryData;
use util::{internal, CargoResult, Config, Filesy... | (
&mut self,
name: &str,
load: &mut RegistryData,
) -> CargoResult<Vec<(Summary, bool)>> {
let (root, _lock) = if self.locked {
let lock = self.path
.open_ro(Path::new(INDEX_LOCK), self.config, "the registry index");
match lock {
... | load_summaries | identifier_name |
index.rs | use std::collections::HashMap;
use std::path::Path;
use std::str;
use serde_json;
use semver::Version;
use core::dependency::Dependency;
use core::{PackageId, SourceId, Summary};
use sources::registry::{RegistryPackage, INDEX_LOCK};
use sources::registry::RegistryData;
use util::{internal, CargoResult, Config, Filesy... | let contents = str::from_utf8(contents)
.map_err(|_| format_err!("registry index file was not valid utf-8"))?;
ret.reserve(contents.lines().count());
let lines = contents.lines().map(|s| s.trim()).filter(|l|!l.is_empty());
let online =!self.config.cli_unst... | let mut ret = Vec::new();
let mut hit_closure = false;
let err = load.load(&root, Path::new(&path), &mut |contents| {
hit_closure = true; | random_line_split |
index.rs | use std::collections::HashMap;
use std::path::Path;
use std::str;
use serde_json;
use semver::Version;
use core::dependency::Dependency;
use core::{PackageId, SourceId, Summary};
use sources::registry::{RegistryPackage, INDEX_LOCK};
use sources::registry::RegistryData;
use util::{internal, CargoResult, Config, Filesy... | 3 => format!("3/{}/{}", &fs_name[..1], fs_name),
_ => format!("{}/{}/{}", &fs_name[0..2], &fs_name[2..4], fs_name),
};
let mut ret = Vec::new();
let mut hit_closure = false;
let err = load.load(&root, Path::new(&path), &mut |contents| {
hit_closure = t... | {
let (root, _lock) = if self.locked {
let lock = self.path
.open_ro(Path::new(INDEX_LOCK), self.config, "the registry index");
match lock {
Ok(lock) => (lock.path().parent().unwrap().to_path_buf(), Some(lock)),
Err(_) => return Ok(Vec::new... | identifier_body |
index.rs | use std::collections::HashMap;
use std::path::Path;
use std::str;
use serde_json;
use semver::Version;
use core::dependency::Dependency;
use core::{PackageId, SourceId, Summary};
use sources::registry::{RegistryPackage, INDEX_LOCK};
use sources::registry::RegistryData;
use util::{internal, CargoResult, Config, Filesy... | ;
let fs_name = name.chars()
.flat_map(|c| c.to_lowercase())
.collect::<String>();
// see module comment for why this is structured the way it is
let path = match fs_name.len() {
1 => format!("1/{}", fs_name),
2 => format!("2/{}", fs_name),
... | {
(self.path.clone().into_path_unlocked(), None)
} | conditional_block |
coherence_local_err_struct.rs | // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | () { }
| main | identifier_name |
coherence_local_err_struct.rs | // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | // These are all legal because they are all fundamental types:
// MyStruct is not fundamental.
impl lib::MyCopy for lib::MyStruct<MyType> { } //~ ERROR E0117
fn main() { } |
struct MyType { x: i32 }
| random_line_split |
coherence_local_err_struct.rs | // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | { } | identifier_body | |
scope.rs | fn main() | // 改正 ^ 注释掉这行
println!("outer long: {}", long_lived_binding);
// 此绑定同样*隐藏*了前面的绑定
let long_lived_binding = 'a';
println!("outer long: {}", long_lived_binding);
}
| {
// 此绑定存在于 main 函数中
let long_lived_binding = 1;
// 这是一个代码块,比 main 函数拥有一个更小的作用域
{
// 此绑定只存在于本代码块
let short_lived_binding = 2;
println!("inner short: {}", short_lived_binding);
// 此绑定*隐藏*了外面的绑定
let long_lived_binding = 5_f32;
println!("inner long: {}", ... | identifier_body |
scope.rs | fn | () {
// 此绑定存在于 main 函数中
let long_lived_binding = 1;
// 这是一个代码块,比 main 函数拥有一个更小的作用域
{
// 此绑定只存在于本代码块
let short_lived_binding = 2;
println!("inner short: {}", short_lived_binding);
// 此绑定*隐藏*了外面的绑定
let long_lived_binding = 5_f32;
println!("inner long: {}... | main | identifier_name |
scope.rs | fn main() {
// 此绑定存在于 main 函数中
let long_lived_binding = 1;
// 这是一个代码块,比 main 函数拥有一个更小的作用域
{
// 此绑定只存在于本代码块
let short_lived_binding = 2;
println!("inner short: {}", short_lived_binding); |
// 此绑定*隐藏*了外面的绑定
let long_lived_binding = 5_f32;
println!("inner long: {}", long_lived_binding);
}
// 代码块结束
// 报错!`short_lived_binding` 在此作用域上不存在
println!("outer short: {}", short_lived_binding);
// 改正 ^ 注释掉这行
println!("outer long: {}", long_lived_binding);
// 此绑... | random_line_split | |
queue_item_impl.rs | /*
* Swaggy Jenkins
*
* Jenkins API clients generated from Swagger / Open API specification
*
* The version of the OpenAPI document: 1.1.2-pre.0
* Contact: blah@cliffano.com
* Generated by: https://openapi-generator.tech
*/
#[derive(Clone, Debug, PartialEq, Default, Serialize, Deserialize)]
pub struct | {
#[serde(rename = "_class", skip_serializing_if = "Option::is_none")]
pub _class: Option<String>,
#[serde(rename = "expectedBuildNumber", skip_serializing_if = "Option::is_none")]
pub expected_build_number: Option<i32>,
#[serde(rename = "id", skip_serializing_if = "Option::is_none")]
pub id: O... | QueueItemImpl | identifier_name |
queue_item_impl.rs | /*
* Swaggy Jenkins
*
* Jenkins API clients generated from Swagger / Open API specification
*
* The version of the OpenAPI document: 1.1.2-pre.0
* Contact: blah@cliffano.com
* Generated by: https://openapi-generator.tech
*/
#[derive(Clone, Debug, PartialEq, Default, Serialize, Deserialize)]
pub struct Queue... |
}
| {
QueueItemImpl {
_class: None,
expected_build_number: None,
id: None,
pipeline: None,
queued_time: None,
}
} | identifier_body |
queue_item_impl.rs | /*
* Swaggy Jenkins
*
* Jenkins API clients generated from Swagger / Open API specification
*
* The version of the OpenAPI document: 1.1.2-pre.0
* Contact: blah@cliffano.com
* Generated by: https://openapi-generator.tech
*/
#[derive(Clone, Debug, PartialEq, Default, Serialize, Deserialize)]
pub struct Queue... | } | } | random_line_split |
validator_operator.rs | // Copyright (c) The Diem Core Contributors
// SPDX-License-Identifier: Apache-2.0
use diem_global_constants::OPERATOR_KEY;
use diem_management::{config::ConfigPath, constants, error::Error, secure_backend::SharedBackend};
use structopt::StructOpt;
#[derive(Debug, StructOpt)]
pub struct ValidatorOperator {
#[stru... |
Ok(operator_name)
}
} | random_line_split | |
validator_operator.rs | // Copyright (c) The Diem Core Contributors
// SPDX-License-Identifier: Apache-2.0
use diem_global_constants::OPERATOR_KEY;
use diem_management::{config::ConfigPath, constants, error::Error, secure_backend::SharedBackend};
use structopt::StructOpt;
#[derive(Debug, StructOpt)]
pub struct ValidatorOperator {
#[stru... | (self) -> Result<String, Error> {
let config = self
.config
.load()?
.override_shared_backend(&self.shared_backend.shared_backend)?;
let operator_name = self.operator_name;
// Verify the operator exists in the shared storage
let operator_storage = config... | execute | identifier_name |
validator_operator.rs | // Copyright (c) The Diem Core Contributors
// SPDX-License-Identifier: Apache-2.0
use diem_global_constants::OPERATOR_KEY;
use diem_management::{config::ConfigPath, constants, error::Error, secure_backend::SharedBackend};
use structopt::StructOpt;
#[derive(Debug, StructOpt)]
pub struct ValidatorOperator {
#[stru... |
}
| {
let config = self
.config
.load()?
.override_shared_backend(&self.shared_backend.shared_backend)?;
let operator_name = self.operator_name;
// Verify the operator exists in the shared storage
let operator_storage = config.shared_backend_with_namespac... | identifier_body |
overloaded-index-in-field.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 f = Bar { foo: Foo {
x: 1,
y: 2,
} };
assert_eq!(f.foo[1].get(), 2);
} | identifier_body | |
overloaded-index-in-field.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 ... |
}
}
trait Int {
fn get(self) -> int;
fn get_from_ref(&self) -> int;
fn inc(&mut self);
}
impl Int for int {
fn get(self) -> int { self }
fn get_from_ref(&self) -> int { *self }
fn inc(&mut self) { *self += 1; }
}
fn main() {
let f = Bar { foo: Foo {
x: 1,
y: 2,
} ... | {
&self.y
} | conditional_block |
overloaded-index-in-field.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... |
impl Index<int> for Foo {
type Output = int;
fn index(&self, z: &int) -> &int {
if *z == 0 {
&self.x
} else {
&self.y
}
}
}
trait Int {
fn get(self) -> int;
fn get_from_ref(&self) -> int;
fn inc(&mut self);
}
impl Int for int {
fn get(self)... | foo: Foo
} | random_line_split |
overloaded-index-in-field.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | (&self) -> int { *self }
fn inc(&mut self) { *self += 1; }
}
fn main() {
let f = Bar { foo: Foo {
x: 1,
y: 2,
} };
assert_eq!(f.foo[1].get(), 2);
}
| get_from_ref | identifier_name |
mod.rs | use anyhow::*;
use diesel::r2d2::{self, ConnectionManager, PooledConnection};
use diesel::sqlite::SqliteConnection;
use diesel::RunQueryDsl;
use std::path::Path;
mod schema;
pub use self::schema::*;
#[allow(dead_code)]
const DB_MIGRATIONS_PATH: &str = "migrations";
embed_migrations!("migrations");
#[derive(Clone)]
... |
}
#[test]
fn run_migrations() {
use crate::test::*;
use crate::test_name;
let output_dir = prepare_test_directory(test_name!());
let db_path = output_dir.join("db.sqlite");
let db = DB::new(&db_path).unwrap();
db.migrate_down().unwrap();
db.migrate_up().unwrap();
}
| {
let connection = self.connect().unwrap();
embedded_migrations::run(&connection)?;
Ok(())
} | identifier_body |
mod.rs | use anyhow::*;
use diesel::r2d2::{self, ConnectionManager, PooledConnection};
use diesel::sqlite::SqliteConnection;
use diesel::RunQueryDsl;
use std::path::Path;
mod schema;
pub use self::schema::*;
#[allow(dead_code)]
const DB_MIGRATIONS_PATH: &str = "migrations";
embed_migrations!("migrations");
#[derive(Clone)]
... | (&self) -> Result<()> {
let connection = self.connect().unwrap();
loop {
match diesel_migrations::revert_latest_migration_in_directory(
&connection,
Path::new(DB_MIGRATIONS_PATH),
) {
Ok(_) => (),
Err(diesel_migrations::RunMigrationsError::MigrationError(
diesel_migrations::MigrationError... | migrate_down | identifier_name |
mod.rs | use anyhow::*;
use diesel::r2d2::{self, ConnectionManager, PooledConnection};
use diesel::sqlite::SqliteConnection;
use diesel::RunQueryDsl;
use std::path::Path;
mod schema;
pub use self::schema::*;
#[allow(dead_code)]
const DB_MIGRATIONS_PATH: &str = "migrations";
embed_migrations!("migrations");
#[derive(Clone)]
... | }
}
impl DB {
pub fn new(path: &Path) -> Result<DB> {
std::fs::create_dir_all(&path.parent().unwrap())?;
let manager = ConnectionManager::<SqliteConnection>::new(path.to_string_lossy());
let pool = diesel::r2d2::Pool::builder()
.connection_customizer(Box::new(ConnectionCustomizer {}))
.build(manager)?;
... | .execute(connection)
.map_err(diesel::r2d2::Error::QueryError)?;
Ok(()) | random_line_split |
machine.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... | use block::IsBlock;
if!live.tracing_enabled() { return Ok(()) }
let mut tracer = ExecutiveTracer::default();
for &(address, amount) in direct {
tracer.trace_reward(address, amount, RewardType::Block);
}
for &(address, amount) in indirect {
tracer.trace_reward(address, amount, RewardType::Uncle);
... | &self,
live: &mut Self::LiveBlock,
direct: &[(Address, U256)],
indirect: &[(Address, U256)],
) -> Result<(), Self::Error> { | random_line_split |
machine.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... | () {
use bigint::prelude::U256;
let spec = ::ethereum::new_homestead_test();
let ethparams = ::tests::helpers::get_default_ethash_extensions();
let machine = EthereumMachine::with_ethash_extensions(
spec.params().clone(),
Default::default(),
ethparams,
);
let mut parent = ::header::Header::new()... | ethash_gas_limit_is_multiple_of_determinant | identifier_name |
machine.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... |
/// Attach special rules to the creation of schedule.
pub fn set_schedule_creation_rules(&mut self, rules: Box<ScheduleCreationRules>) {
self.schedule_rules = Some(rules);
}
/// Get a reference to the ethash-specific extensions.
pub fn ethash_extensions(&self) -> Option<&EthashExtensions> {
self.ethash_exte... | {
let mut machine = EthereumMachine::regular(params, builtins);
machine.ethash_extensions = Some(extensions);
machine
} | identifier_body |
builtin-superkinds-capabilities-xc.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... | assert!(rx.recv() == X(31337));
} | random_line_split | |
builtin-superkinds-capabilities-xc.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... | <T>(T);
impl <T: Share> RequiresShare for X<T> { }
impl <T: Share+Send> RequiresRequiresShareAndSend for X<T> { }
fn foo<T: RequiresRequiresShareAndSend>(val: T, chan: Sender<T>) {
chan.send(val);
}
pub fn main() {
let (tx, rx) = channel();
foo(X(31337), tx);
assert!(rx.recv() == X(31337));
}
| X | identifier_name |
pipe_unix.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 ... | (&mut self, timeout: Option<u64>) {
let deadline = timeout.map(|a| ::io::timer::now() + a).unwrap_or(0);
self.read_deadline = deadline;
self.write_deadline = deadline;
}
fn set_read_timeout(&mut self, timeout: Option<u64>) {
self.read_deadline = timeout.map(|a| ::io::timer::now()... | set_timeout | identifier_name |
pipe_unix.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... |
fn clone(&self) -> Box<rtio::RtioPipe + Send> {
box UnixStream::new(self.inner.clone()) as Box<rtio::RtioPipe + Send>
}
fn close_write(&mut self) -> IoResult<()> {
super::mkerr_libc(unsafe { libc::shutdown(self.fd(), libc::SHUT_WR) })
}
fn close_read(&mut self) -> IoResult<()> {
... | {
let fd = self.fd();
let dolock = || self.lock_nonblocking();
let dowrite = |nb: bool, buf: *const u8, len: uint| unsafe {
let flags = if nb {c::MSG_DONTWAIT} else {0};
libc::send(fd,
buf as *mut libc::c_void,
len as libc::si... | identifier_body |
pipe_unix.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 retry(|| {
libc::accept(self.fd(),
storagep as *mut libc::sockaddr,
&mut size as *mut libc::socklen_t) as libc::c_int
}) {
-1 if util::wouldblock() => {}
-1... | let mut size = size as libc::socklen_t; | random_line_split |
chmod.rs | #![crate_name = "uu_chmod"]
/*
* This file is part of the uutils coreutils package.
*
* (c) Arcterus <arcterus@mail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
extern crate libc;
extern crate walker;
#[macro_use]
extern... | // XXX: here (and elsewhere) we see that this impl will have issues
// with non-UTF-8 filenames. Using OsString won't fix this because
// on Windows OsStrings cannot be built out of non-UTF-8 chars. One
// possible fix is to... | Ok(m) => m,
Err(f) => {
crash!(1, "{}", f.to_string());
}
}; | random_line_split |
chmod.rs | #![crate_name = "uu_chmod"]
/*
* This file is part of the uutils coreutils package.
*
* (c) Arcterus <arcterus@mail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
extern crate libc;
extern crate walker;
#[macro_use]
extern... | else {
crash!(1, "cannot stat attribues of '{}': {}", matches.opt_str("reference").unwrap(), io::Error::last_os_error())
}
});
let cmode =
if fmode.is_none() {
// If there was a negative option, now it's a good time to
// use it.
... | {
Some(stat.st_mode)
} | conditional_block |
chmod.rs | #![crate_name = "uu_chmod"]
/*
* This file is part of the uutils coreutils package.
*
* (c) Arcterus <arcterus@mail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
extern crate libc;
extern crate walker;
#[macro_use]
extern... | (mut fperm: libc::mode_t, mut mode: &str, file: &Path) -> Result<libc::mode_t, String> {
let (mask, pos) = parse_levels(mode);
if pos == mode.len() {
return Err(format!("invalid mode ({})", mode));
}
let respect_umask = pos == 0;
let last_umask = unsafe {
libc::umask(0)
};
mo... | parse_symbolic | identifier_name |
chmod.rs | #![crate_name = "uu_chmod"]
/*
* This file is part of the uutils coreutils package.
*
* (c) Arcterus <arcterus@mail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
extern crate libc;
extern crate walker;
#[macro_use]
extern... | pos += 1;
}
if pos == 0 {
srwx = 0;
}
(srwx, pos)
}
fn change_file(fperm: libc::mode_t, mode: libc::mode_t, file: &Path, path: &CString, verbose: bool, changes: bool, quiet: bool) -> Result<(), i32> {
if fperm == mode {
if verbose &&!changes {
show_info!("mode o... | {
let mut srwx = fperm & 0o7000;
let mut pos = 0;
for ch in mode.chars() {
match ch {
'r' => srwx |= 0o444,
'w' => srwx |= 0o222,
'x' => srwx |= 0o111,
'X' => {
if file.is_dir() || (fperm & 0o0111) != 0 {
srwx |= 0o1... | identifier_body |
main.rs | use std::env::args;
struct PasswordGenerator { password: String, }
impl Iterator for PasswordGenerator {
type Item = String;
fn next(&mut self) -> Option<Self::Item> {
let mut pchars: Vec<char> = self.password.chars().collect();
pchars.reverse();
self.password =
pchars
... | else {
(bump, format!("{}", c) + &chars)
}
}).1;
Some(self.password.clone())
}
}
fn is_valid_password(password: &String) -> bool {
let chars: Vec<char> = password.chars().collect();
let has_straight = (0..(chars.len() - 2)).any(|i| {
let firs... | {
let next = if *c == 'z' {
'a'
} else {
std::char::from_u32(*c as u32 + 1).unwrap()
};
(next == 'a', format!("{}", next) + &chars)
} | conditional_block |
main.rs | use std::env::args;
struct PasswordGenerator { password: String, }
impl Iterator for PasswordGenerator {
type Item = String; |
fn next(&mut self) -> Option<Self::Item> {
let mut pchars: Vec<char> = self.password.chars().collect();
pchars.reverse();
self.password =
pchars
.iter()
.fold((true, "".to_string()), |tup, c| {
let (bump, chars) = tup;
if bum... | random_line_split | |
main.rs | use std::env::args;
struct PasswordGenerator { password: String, }
impl Iterator for PasswordGenerator {
type Item = String;
fn next(&mut self) -> Option<Self::Item> {
let mut pchars: Vec<char> = self.password.chars().collect();
pchars.reverse();
self.password =
pchars
... | {
let password = args().nth(1).unwrap();
let mut pg = PasswordGenerator { password: password.clone(), };
let next_pw = pg.find(|password| is_valid_password(password));
println!("{}", next_pw.unwrap());
let next_next_pw = pg.find(|password| is_valid_password(password));
println!("{}", next_next_p... | identifier_body | |
main.rs | use std::env::args;
struct PasswordGenerator { password: String, }
impl Iterator for PasswordGenerator {
type Item = String;
fn | (&mut self) -> Option<Self::Item> {
let mut pchars: Vec<char> = self.password.chars().collect();
pchars.reverse();
self.password =
pchars
.iter()
.fold((true, "".to_string()), |tup, c| {
let (bump, chars) = tup;
if bump {
... | next | identifier_name |
contiguous_range_to_char.rs | use malachite_base::chars::crement::contiguous_range_to_char;
use malachite_base_test_util::bench::bucketers::unsigned_direct_bucketer;
use malachite_base_test_util::bench::{run_benchmark, BenchmarkType};
use malachite_base_test_util::generators::common::{GenConfig, GenMode};
use malachite_base_test_util::generators::u... | (gm: GenMode, config: GenConfig, limit: usize) {
for u in unsigned_gen().get(gm, &config).take(limit) {
println!(
"contiguous_range_to_char({}) = {:?}",
u,
contiguous_range_to_char(u)
);
}
}
fn benchmark_contiguous_range_to_char(
gm: GenMode,
config: ... | demo_contiguous_range_to_char | identifier_name |
contiguous_range_to_char.rs | use malachite_base::chars::crement::contiguous_range_to_char;
use malachite_base_test_util::bench::bucketers::unsigned_direct_bucketer;
use malachite_base_test_util::bench::{run_benchmark, BenchmarkType};
use malachite_base_test_util::generators::common::{GenConfig, GenMode};
use malachite_base_test_util::generators::u... | file_name: &str,
) {
run_benchmark(
"contiguous_range_to_char(u32)",
BenchmarkType::Single,
unsigned_gen().get(gm, &config),
gm.name(),
limit,
file_name,
&unsigned_direct_bucketer(),
&mut [("Malachite", &mut |u| no_out!(contiguous_range_to_char(u))... | config: GenConfig,
limit: usize, | random_line_split |
contiguous_range_to_char.rs | use malachite_base::chars::crement::contiguous_range_to_char;
use malachite_base_test_util::bench::bucketers::unsigned_direct_bucketer;
use malachite_base_test_util::bench::{run_benchmark, BenchmarkType};
use malachite_base_test_util::generators::common::{GenConfig, GenMode};
use malachite_base_test_util::generators::u... |
fn benchmark_contiguous_range_to_char(
gm: GenMode,
config: GenConfig,
limit: usize,
file_name: &str,
) {
run_benchmark(
"contiguous_range_to_char(u32)",
BenchmarkType::Single,
unsigned_gen().get(gm, &config),
gm.name(),
limit,
file_name,
&un... | {
for u in unsigned_gen().get(gm, &config).take(limit) {
println!(
"contiguous_range_to_char({}) = {:?}",
u,
contiguous_range_to_char(u)
);
}
} | identifier_body |
split.rs | use futures_core::stream::Stream;
use futures_core::task::{Context, Poll};
use futures_sink::Sink;
use core::fmt;
use core::pin::Pin;
use crate::lock::BiLock;
/// A `Stream` part of the split pair
#[derive(Debug)]
#[must_use = "streams do nothing unless polled"]
pub struct SplitStream<S>(BiLock<S>);
impl<S> Unpin fo... |
inner.as_pin_mut().poll_flush(cx)
}
fn poll_close(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), S::Error>> {
let this = &mut *self;
let mut inner = ready!(this.lock.poll_lock(cx));
if this.slot.is_some() {
ready!(inner.as_pin_mut().poll_ready(cx... | {
ready!(inner.as_pin_mut().poll_ready(cx))?;
inner.as_pin_mut().start_send(this.slot.take().unwrap())?;
} | conditional_block |
split.rs | use futures_core::stream::Stream;
use futures_core::task::{Context, Poll};
use futures_sink::Sink; | use crate::lock::BiLock;
/// A `Stream` part of the split pair
#[derive(Debug)]
#[must_use = "streams do nothing unless polled"]
pub struct SplitStream<S>(BiLock<S>);
impl<S> Unpin for SplitStream<S> {}
impl<S: Unpin> SplitStream<S> {
/// Attempts to put the two "halves" of a split `Stream + Sink` back
/// t... | use core::fmt;
use core::pin::Pin;
| random_line_split |
split.rs | use futures_core::stream::Stream;
use futures_core::task::{Context, Poll};
use futures_sink::Sink;
use core::fmt;
use core::pin::Pin;
use crate::lock::BiLock;
/// A `Stream` part of the split pair
#[derive(Debug)]
#[must_use = "streams do nothing unless polled"]
pub struct SplitStream<S>(BiLock<S>);
impl<S> Unpin fo... | <S: Stream + Sink<Item>, Item>(s: S) -> (SplitSink<S, Item>, SplitStream<S>) {
let (a, b) = BiLock::new(s);
let read = SplitStream(a);
let write = SplitSink(b);
(write, read)
}
/// Error indicating a `SplitSink<S>` and `SplitStream<S>` were not two halves
/// of a `Stream + Split`, and thus could not b... | split | identifier_name |
split.rs | use futures_core::stream::Stream;
use futures_core::task::{Context, Poll};
use futures_sink::Sink;
use core::fmt;
use core::pin::Pin;
use crate::lock::BiLock;
/// A `Stream` part of the split pair
#[derive(Debug)]
#[must_use = "streams do nothing unless polled"]
pub struct SplitStream<S>(BiLock<S>);
impl<S> Unpin fo... |
}
impl<T, Item> fmt::Display for ReuniteError<T, Item> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "tried to reunite a SplitStream and SplitSink that don't form a pair")
}
}
#[cfg(feature = "std")]
impl<T: core::any::Any, Item> std::error::Error for ReuniteError<T, Item> {}... | {
f.debug_tuple("ReuniteError")
.field(&"...")
.finish()
} | identifier_body |
database.rs | // Copyright 2018 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// | // http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language gover... | random_line_split | |
database.rs | // Copyright 2018 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in ... | {
/// The path to the SqliteDatabase to use. If set, the parent directory must exist and the
/// location must be writable. Saver will never fall back to an in-memory database if this is
/// set.
#[serde(skip_serializing_if = "Option::is_none")]
pub database_path: Option<PathBuf>,
/// Sets the... | DatabaseConfig | identifier_name |
fun.rs | //! Facilities for working with `v8::Function`s.
use std::os::raw::c_void;
use call::CCallback;
use raw::Local;
extern "C" {
/// Mutates the `out` argument provided to refer to a newly created `v8::Function`. Returns
/// `false` if the value couldn't be created.
#[link_name = "Neon_Fun_New"]
pub fn n... | } | random_line_split | |
syntax-extension-hexfloat-bad-lits.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... | {
hexfloat!("foo");
//~^ ERROR invalid hex float literal in hexfloat!: Expected '0'
hexfloat!("0");
//~^ERROR invalid hex float literal in hexfloat!: Expected 'x'
hexfloat!("0x");
//~^ERROR invalid hex float literal in hexfloat!: Expected '.'
hexfloat!("0x.");
//~^ERROR invalid hex float... | identifier_body | |
syntax-extension-hexfloat-bad-lits.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... | hexfloat!("0x0.0p");
//~^ERROR invalid hex float literal in hexfloat!: Expected exponent digits
hexfloat!("0x0.0p0f");
//~^ERROR invalid hex float literal in hexfloat!: Expected end of string
} | random_line_split | |
syntax-extension-hexfloat-bad-lits.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... | () {
hexfloat!("foo");
//~^ ERROR invalid hex float literal in hexfloat!: Expected '0'
hexfloat!("0");
//~^ERROR invalid hex float literal in hexfloat!: Expected 'x'
hexfloat!("0x");
//~^ERROR invalid hex float literal in hexfloat!: Expected '.'
hexfloat!("0x.");
//~^ERROR invalid hex fl... | main | identifier_name |
ownershipmovessource0.rs | // Cette fonction prend possession d'un entier alloué dans le tas.
fn destroy_box(c: Box<i32>) {
println!("Destroying a box that contains {}", c); | // `c` est détruit et la mémoire va être libérée.
}
fn main() {
// Entier alloué dans la pile.
let x = 5u32;
// On copie `x` dans `y` - aucune ressource n'a été transféré
// (l'ownership n'a pas été transféré).
let y = x;
// Les deux valeurs peuvent être utilisées indépendamment.
prin... | random_line_split | |
ownershipmovessource0.rs | // Cette fonction prend possession d'un entier alloué dans le tas.
fn destroy_box(c: Box<i32>) {
println!("Destroying a box that contains {}", c);
// `c` est détruit et la mémoire va être libérée.
}
fn main() {
|
// Erreur! `a` ne peut plus accéder à la donnée car il ne possède plus
// le bloc mémoire.
// println!("a contains: {}", a);
// TODO ^ Essayez de décommenter cette ligne.
// Cette fonction prend possession de la mémoire allouée dans le tas
// à partir de `b`.
destroy_box(b);
// Puis... | // Entier alloué dans la pile.
let x = 5u32;
// On copie `x` dans `y` - aucune ressource n'a été transféré
// (l'ownership n'a pas été transféré).
let y = x;
// Les deux valeurs peuvent être utilisées indépendamment.
println!("x is {}, and y is {}", x, y);
// `a` est un pointeur sur un en... | identifier_body |
ownershipmovessource0.rs | // Cette fonction prend possession d'un entier alloué dans le tas.
fn destroy_box(c: Box<i32>) {
println!("Destroying a box that contains {}", c);
// `c` est détruit et la mémoire va être libérée.
}
fn main() | // Entier alloué dans la pile.
let x = 5u32;
// On copie `x` dans `y` - aucune ressource n'a été transféré
// (l'ownership n'a pas été transféré).
let y = x;
// Les deux valeurs peuvent être utilisées indépendamment.
println!("x is {}, and y is {}", x, y);
// `a` est un pointeur sur un... | {
| identifier_name |
crateresolve3.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 f() { assert!(crateresolve3::g() == 20); }
}
pub fn main() {
a::f();
b::f();
} | mod b {
extern mod crateresolve3(vers = "0.2"); | random_line_split |
crateresolve3.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 ... |
}
mod b {
extern mod crateresolve3(vers = "0.2");
pub fn f() { assert!(crateresolve3::g() == 20); }
}
pub fn main() {
a::f();
b::f();
}
| { assert!(crateresolve3::f() == 10); } | identifier_body |
crateresolve3.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 ... | () { assert!(crateresolve3::g() == 20); }
}
pub fn main() {
a::f();
b::f();
}
| f | identifier_name |
test.rs | extern crate yassy;
const N: u32 = 2147483648; | // Check if type conversion overflows behave as expected
assert_eq!(N as i32, i32::min_value());
assert_eq!((N as i32) as i64, -(N as i64));
let mut pa = yassy::oscillator::PhaseAccumulator::new();
// set f0 to exactly half the sample rate and verify phase
// accumulation. Exactly two steps fo... |
#[test]
fn mytest() {
| random_line_split |
test.rs | extern crate yassy;
const N: u32 = 2147483648;
#[test]
fn mytest() | // check if shiftn works
assert_eq!(pa.shiftn(), 0i32);
}
| {
// Check if type conversion overflows behave as expected
assert_eq!(N as i32, i32::min_value());
assert_eq!((N as i32) as i64, -(N as i64));
let mut pa = yassy::oscillator::PhaseAccumulator::new();
// set f0 to exactly half the sample rate and verify phase
// accumulation. Exactly two steps... | identifier_body |
test.rs | extern crate yassy;
const N: u32 = 2147483648;
#[test]
fn | () {
// Check if type conversion overflows behave as expected
assert_eq!(N as i32, i32::min_value());
assert_eq!((N as i32) as i64, -(N as i64));
let mut pa = yassy::oscillator::PhaseAccumulator::new();
// set f0 to exactly half the sample rate and verify phase
// accumulation. Exactly two st... | mytest | identifier_name |
serve.rs | use std::path;
use std::process;
use std::sync::mpsc::channel;
use std::thread;
use std::time;
use cobalt::cobalt_model;
use failure::ResultExt;
use notify::Watcher;
use crate::args;
use crate::build;
use crate::error::*;
/// Build, serve, and watch the project at the source dir
#[derive(Clone, Debug, PartialEq, Eq,... | // Be as broad as possible in what can cause a rebuild to
// ensure we don't miss anything (normal file walks will miss
// `_layouts`, etc).
if event_path.starts_with(&destination) {
trace!("Ignored file changed {:?}", event);
false
... | let rebuild = if let Some(event_path) = event_path { | random_line_split |
serve.rs | use std::path;
use std::process;
use std::sync::mpsc::channel;
use std::thread;
use std::time;
use cobalt::cobalt_model;
use failure::ResultExt;
use notify::Watcher;
use crate::args;
use crate::build;
use crate::error::*;
/// Build, serve, and watch the project at the source dir
#[derive(Clone, Debug, PartialEq, Eq,... | else {
debug!("Page changed {:?}", event);
true
}
} else {
trace!("Assuming change {:?} is relevant", event);
true
};
if rebuild {
let result = build::build(config.clone());
if let Err(fail) = result {
... | {
trace!("Ignored file changed {:?}", event);
false
} | conditional_block |
serve.rs | use std::path;
use std::process;
use std::sync::mpsc::channel;
use std::thread;
use std::time;
use cobalt::cobalt_model;
use failure::ResultExt;
use notify::Watcher;
use crate::args;
use crate::build;
use crate::error::*;
/// Build, serve, and watch the project at the source dir
#[derive(Clone, Debug, PartialEq, Eq,... | (url: String) -> Result<()> {
match open::that(url) {
Ok(()) => info!("Please check your browser!"),
Err(why) => eprintln!("Failure to execute command: {}", why),
}
Ok(())
}
fn watch(config: &cobalt_model::Config) -> Result<()> {
// canonicalize is to ensure there is no question that `w... | open_browser | identifier_name |
serve.rs | use std::path;
use std::process;
use std::sync::mpsc::channel;
use std::thread;
use std::time;
use cobalt::cobalt_model;
use failure::ResultExt;
use notify::Watcher;
use crate::args;
use crate::build;
use crate::error::*;
/// Build, serve, and watch the project at the source dir
#[derive(Clone, Debug, PartialEq, Eq,... | loop {
let event = rx
.recv()
.with_context(|_| failure::err_msg("Notify error"))?;
let event_path = match event {
notify::DebouncedEvent::Create(ref path)
| notify::DebouncedEvent::NoticeWrite(ref path)
| notify::DebouncedEvent::Write(ref pa... | {
// canonicalize is to ensure there is no question that `watcher`s paths come back safe for
// Files::includes_file
let source = dunce::canonicalize(path::Path::new(&config.source))
.with_context(|_| failure::err_msg("Failed in processing source"))?;
// Also canonicalize the destination folder... | identifier_body |
type_of.rs | // Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MI... | (ccx: &CrateContext, ty: ty::t) -> bool {
!type_is_immediate(ccx, ty)
}
pub fn type_of_explicit_arg(ccx: &CrateContext, arg_ty: ty::t) -> Type {
let llty = type_of(ccx, arg_ty);
if arg_is_indirect(ccx, arg_ty) {
llty.ptr_to()
} else {
llty
}
}
pub fn type_of_rust_fn(cx: &CrateContex... | return_uses_outptr | identifier_name |
type_of.rs | // Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MI... |
pub fn type_of_dtor(ccx: &CrateContext, self_ty: ty::t) -> Type {
let self_ty = type_of(ccx, self_ty).ptr_to();
Type::func([self_ty], &Type::void(ccx))
}
| {
let name = match what {
a_struct => { "struct" }
an_enum => { "enum" }
};
let tstr = ppaux::parameterized(cx.tcx(), ty::item_path_str(cx.tcx(), did),
&ty::NonerasedRegions(OwnedSlice::empty()),
tps, did, false);
if... | identifier_body |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.