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
prompt.rs
use super::super::{Capture, Function, Shell}; use parser::shell_expand::expand_string; use std::io::Read; use std::process; use sys; pub(crate) fn prompt(shell: &mut Shell) -> String { if shell.flow_control.level == 0 { let rprompt = match prompt_fn(shell) { Some(prompt) => prompt, ...
pub(crate) fn prompt_fn(shell: &mut Shell) -> Option<String> { let function = match shell.functions.get("PROMPT") { Some(func) => func as *const Function, None => return None, }; let mut output = None; match shell.fork(Capture::Stdout, |child| unsafe { let _ = function.read().e...
random_line_split
prompt.rs
use super::super::{Capture, Function, Shell}; use parser::shell_expand::expand_string; use std::io::Read; use std::process; use sys; pub(crate) fn prompt(shell: &mut Shell) -> String { if shell.flow_control.level == 0 { let rprompt = match prompt_fn(shell) { Some(prompt) => prompt, ...
(shell: &mut Shell) -> Option<String> { let function = match shell.functions.get("PROMPT") { Some(func) => func as *const Function, None => return None, }; let mut output = None; match shell.fork(Capture::Stdout, |child| unsafe { let _ = function.read().execute(child, &["ion"])...
prompt_fn
identifier_name
filetype_is_file.rs
use clippy_utils::diagnostics::span_lint_and_help; use clippy_utils::ty::match_type; use clippy_utils::{get_parent_expr, paths}; use if_chain::if_chain; use rustc_hir as hir; use rustc_lint::LateContext; use rustc_span::source_map::Span; use super::FILETYPE_IS_FILE; pub(super) fn check(cx: &LateContext<'_>, expr: &hi...
} else { lint_unary = ""; verb = "covers"; help_unary = "!"; span = expr.span; } } let lint_msg = format!("`{}FileType::is_file()` only {} regular files", lint_unary, verb); let help_msg = format!("use `{}FileType::is_dir()` instead", help_unar...
{ let ty = cx.typeck_results().expr_ty(recv); if !match_type(cx, ty, &paths::FILE_TYPE) { return; } let span: Span; let verb: &str; let lint_unary: &str; let help_unary: &str; if_chain! { if let Some(parent) = get_parent_expr(cx, expr); if let hir::ExprKind::Una...
identifier_body
filetype_is_file.rs
use clippy_utils::diagnostics::span_lint_and_help; use clippy_utils::ty::match_type; use clippy_utils::{get_parent_expr, paths}; use if_chain::if_chain; use rustc_hir as hir; use rustc_lint::LateContext; use rustc_span::source_map::Span; use super::FILETYPE_IS_FILE; pub(super) fn check(cx: &LateContext<'_>, expr: &hi...
let span: Span; let verb: &str; let lint_unary: &str; let help_unary: &str; if_chain! { if let Some(parent) = get_parent_expr(cx, expr); if let hir::ExprKind::Unary(op, _) = parent.kind; if op == hir::UnOp::Not; then { lint_unary = "!"; verb ...
{ return; }
conditional_block
filetype_is_file.rs
use clippy_utils::diagnostics::span_lint_and_help; use clippy_utils::ty::match_type; use clippy_utils::{get_parent_expr, paths}; use if_chain::if_chain; use rustc_hir as hir; use rustc_lint::LateContext; use rustc_span::source_map::Span; use super::FILETYPE_IS_FILE; pub(super) fn
(cx: &LateContext<'_>, expr: &hir::Expr<'_>, recv: &hir::Expr<'_>) { let ty = cx.typeck_results().expr_ty(recv); if!match_type(cx, ty, &paths::FILE_TYPE) { return; } let span: Span; let verb: &str; let lint_unary: &str; let help_unary: &str; if_chain! { if let Some(pare...
check
identifier_name
filetype_is_file.rs
use clippy_utils::diagnostics::span_lint_and_help;
use rustc_hir as hir; use rustc_lint::LateContext; use rustc_span::source_map::Span; use super::FILETYPE_IS_FILE; pub(super) fn check(cx: &LateContext<'_>, expr: &hir::Expr<'_>, recv: &hir::Expr<'_>) { let ty = cx.typeck_results().expr_ty(recv); if!match_type(cx, ty, &paths::FILE_TYPE) { return; ...
use clippy_utils::ty::match_type; use clippy_utils::{get_parent_expr, paths}; use if_chain::if_chain;
random_line_split
pointing.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("Pointing", inherited=True, gecko_...
self.keyword.to_css(dest) } } } #[cfg(not(feature = "gecko"))] #[inline] pub fn get_initial_value() -> computed_value::T { computed_value::Keyword::Auto } #[cfg(feature = "gecko")] #[inline] pub fn get_initial_value() -> computed_value::T { ...
}
random_line_split
pointing.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("Pointing", inherited=True, gecko_...
<'i, 't>(_context: &ParserContext, input: &mut Parser<'i, 't>) -> Result<computed_value::Keyword, ParseError<'i>> { use std::ascii::AsciiExt; use style_traits::cursor::Cursor; let ident = input.expect_ident()?; if ident.eq_ignore_ascii_case("auto"...
parse
identifier_name
ffi.rs
/* * Copyright (C) 2014 Maciej Piechotka * * 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, pu...
} #[allow(dead_code)] pub struct xmlElementContent { _type: xmlElementContentType, ocur: xmlElementContentOccur, name: *xmlChar, first: *xmlElementContent, second: *xmlElementContent, parent: *xmlElementContent, prefix: *xmlChar } #[allow(dead_code)] #[repr(C)] pub enum xmlElementContentTy...
Any, Mixed, ElementType
random_line_split
ffi.rs
/* * Copyright (C) 2014 Maciej Piechotka * * 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, pu...
{ None = 1, Required = 2, Implied = 3, Fixed = 4 } #[repr(C)] pub enum xmlAttributeType { CDATA = 1, ID = 2, IDRef = 3, IDRefs = 4, Entity = 5, Entities = 6, NMToken = 7, NMTokens = 8, Enumeration = 9, Notation = 10 } pub struct xmlDoc { _private: *c_void, ...
xmlAttributeDefault
identifier_name
builder.rs
Self::new_with_capacity(0) } /// Create a FlatBufferBuilder that is ready for writing, with a /// ready-to-use capacity of the provided size. /// /// The maximum valid value is `FLATBUFFERS_MAX_BUFFER_SIZE`. pub fn new_with_capacity(size: usize) -> Self { // we need to check th...
/// Create a utf8 string. /// /// The wire format represents this as a zero-terminated byte vector. #[inline] pub fn create_string<'a: 'b, 'b>(&'a mut self, s: &'b str) -> WIPOffset<&'fbb str> { self.assert_not_nested("create_string can not be called when a table or vector is under constru...
{ self.assert_nested("end_vector"); self.nested = false; let o = self.push::<UOffsetT>(num_elems as UOffsetT); WIPOffset::new(o.value()) }
identifier_body
builder.rs
Self::new_with_capacity(0) } /// Create a FlatBufferBuilder that is ready for writing, with a /// ready-to-use capacity of the provided size. /// /// The maximum valid value is `FLATBUFFERS_MAX_BUFFER_SIZE`. pub fn new_with_capacity(size: usize) -> Self { // we need to check th...
(&mut self, off: WIPOffset<TableUnfinishedWIPOffset>) -> WIPOffset<TableFinishedWIPOffset> { self.assert_nested("end_table"); let o = self.write_vtable(off); self.nested = false; self.field_locs.clear(); WIPOffset::new(o.value()) } /// Start a Vector write. /// ...
end_table
identifier_name
builder.rs
{ Self::new_with_capacity(0) } /// Create a FlatBufferBuilder that is ready for writing, with a /// ready-to-use capacity of the provided size. /// /// The maximum valid value is `FLATBUFFERS_MAX_BUFFER_SIZE`. pub fn new_with_capacity(size: usize) -> Self { // we need to check ...
slot_byte_loc: VOffsetT, assert_msg_name: &'static str) { let idx = self.used_space() - tab_revloc.value() as usize; let tab = Table::new(&self.owned_buf[self.head..], idx); let o = tab.vtable().get(slot_byte_loc) as usize; assert!(o!= 0, "missing ...
pub fn required(&self, tab_revloc: WIPOffset<TableFinishedWIPOffset>,
random_line_split
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...
/// Calls the type object, thus creating a new instance. /// This is equivalent to the Python expression: `self(*args, **kwargs)` #[inline] pub fn call<A>(&self, args: A, kwargs: Option<&PyDict<'p>>) -> PyResult<'p, PyObject<'p>> where A: ToPyObject<'p, ObjectType=PyTuple<'p>> { let py =...
{ unsafe { ffi::PyObject_TypeCheck(obj.as_ptr(), self.as_type_ptr()) != 0 } }
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...
<'a>(py: Python<'p>, p: *mut ffi::PyTypeObject) -> PyType<'p> { PyObject::from_borrowed_ptr(py, p as *mut ffi::PyObject).unchecked_cast_into::<PyType>() } /// Return true if self is a subtype of b. #[inline] pub fn is_subtype_of(&self, b : &PyType<'p>) -> bool { unsafe { ffi::PyType_IsS...
from_type_ptr
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...
/// Calls the type object, thus creating a new instance. /// This is equivalent to the Python expression: `self(*args, **kwargs)` #[inline] pub fn call<A>(&self, args: A, kwargs: Option<&PyDict<'p>>) -> PyResult<'p, PyObject<'p>> where A: ToPyObject<'p, ObjectType=PyTuple<'p>> { let py = s...
random_line_split
mod.rs
use cmd::{REPLY, UNKNOWN}; use cmd; use con::{Peer, Connection}; use server::{Server}; use super::{RawMessage}; mod registration; mod msg; mod join; mod part; mod mode; mod lists; mod simple; mod ping_pong; mod cap; macro_rules! handle { {$( $command:ident with $handler:path; )*} => { /// Temporary ...
fn invoke(&self, _: &mut Server, _: Peer) { // Ingore reply codes from clients they are not allowed to send any } fn raw_message(&self) -> &RawMessage { &self.raw } } /// Handles unknown messages. Could be used as an entry point for plugins pub struct ExtensionHandler { raw: RawMessage, } impl...
{ Ok(box Reply { raw: message }) }
identifier_body
mod.rs
use cmd::{REPLY, UNKNOWN}; use cmd; use con::{Peer, Connection}; use server::{Server}; use super::{RawMessage}; mod registration; mod msg; mod join; mod part; mod mode; mod lists; mod simple; mod ping_pong; mod cap; macro_rules! handle { {$( $command:ident with $handler:path; )*} => { /// Temporary ...
t.map(|v| v as Box<MessageHandler + Send>) }, UNKNOWN(_) => { let t: Result<Box<ExtensionHandler>, Option<RawMessage>> = MessageHandler::from_message(message); t.map(|v| v as Box<MessageHandler + Send>) } } } }} handle!{ PRIVMSG with self::msg::Msg; ...
},)* REPLY(_) => { let t: Result<Box<Reply>, Option<RawMessage>> = MessageHandler::from_message(message);
random_line_split
mod.rs
use cmd::{REPLY, UNKNOWN}; use cmd; use con::{Peer, Connection}; use server::{Server}; use super::{RawMessage}; mod registration; mod msg; mod join; mod part; mod mode; mod lists; mod simple; mod ping_pong; mod cap; macro_rules! handle { {$( $command:ident with $handler:path; )*} => { /// Temporary ...
(&self, _: &mut Server, _: Connection) {} /// Returns the raw message the handler is bases on fn raw_message(&self) -> &RawMessage; } /// Handles (ignores) reply codes from clients struct Reply { raw: RawMessage, } impl MessageHandler for Reply { fn from_message(message: RawMessage) -> Result<Box<...
invoke_con
identifier_name
lib.rs
// Copyright 2017 Pants project contributors (see CONTRIBUTORS.md). // Licensed under the Apache License, Version 2.0 (see LICENSE). #![deny(warnings)] // Enable all clippy lints except for many of the pedantic ones. It's a shame this needs to be copied and pasted across crates, but there doesn't appear to be a way to...
(metadata: ProcessResultMetadata) -> ExecutedActionMetadata { let (total_start, total_end) = match metadata.total_elapsed { Some(elapsed) => { // Because we do not have the precise start time, we hardcode to starting at UNIX_EPOCH. We // only care about accurately preserving the duration. ...
from
identifier_name
lib.rs
// Copyright 2017 Pants project contributors (see CONTRIBUTORS.md). // Licensed under the Apache License, Version 2.0 (see LICENSE). #![deny(warnings)] // Enable all clippy lints except for many of the pedantic ones. It's a shame this needs to be copied and pasted across crates, but there doesn't appear to be a way to...
}) .as_bytes(), ) } /// /// A CommandRunner wrapper that limits the number of concurrent requests. /// #[derive(Clone)] pub struct BoundedCommandRunner { inner: Arc<(Box<dyn CommandRunner>, AsyncSemaphore)>, } impl BoundedCommandRunner { pub fn new(inner: Box<dyn CommandRunner>, bound: usize) -> Boun...
hashes .iter() .fold(String::new(), |mut acc, hash| { acc.push_str(hash); acc
random_line_split
lib.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #![deny(unsafe_code)] #![feature(box_syntax)] #![feature(conservative_impl_trait)] #![feature(mpsc_select)] exter...
pub use constellation::{Constellation, FromCompositorLogger, FromScriptLogger, InitialConstellationState}; pub use pipeline::UnprivilegedPipelineContent; #[cfg(all(not(target_os = "windows"), not(target_os = "ios")))] pub use sandboxing::content_process_sandbox_profile;
random_line_split
manifest.rs
// Copyright (c) The Diem Core Contributors // SPDX-License-Identifier: Apache-2.0 use crate::storage::FileHandle; use diem_crypto::HashValue; use diem_types::transaction::Version; use serde::{Deserialize, Serialize}; /// A chunk of a state snapshot manifest, representing accounts in the key range /// [`first_key`, `...
/// BCS serialized /// `Tuple(TransactionInfoWithProof, LedgerInfoWithSignatures)`. /// - The `TransactionInfoWithProof` is at `Version` above, and carries the same `root_hash` /// above; It proves that at specified version the root hash is as specified in a chain /// represented by the LedgerInfo...
/// All account blobs in chunks. pub chunks: Vec<StateSnapshotChunk>,
random_line_split
manifest.rs
// Copyright (c) The Diem Core Contributors // SPDX-License-Identifier: Apache-2.0 use crate::storage::FileHandle; use diem_crypto::HashValue; use diem_types::transaction::Version; use serde::{Deserialize, Serialize}; /// A chunk of a state snapshot manifest, representing accounts in the key range /// [`first_key`, `...
{ /// index of the first account in this chunk over all accounts. pub first_idx: usize, /// index of the last account in this chunk over all accounts. pub last_idx: usize, /// key of the first account in this chunk. pub first_key: HashValue, /// key of the last account in this chunk. pu...
StateSnapshotChunk
identifier_name
lib.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #![feature(box_syntax)] #![feature(step_by)] #![deny(unsafe_code)] extern crate cookie as cookie_rs; extern crat...
} impl IpcSend<CoreResourceMsg> for ResourceThreads { fn send(&self, msg: CoreResourceMsg) -> IpcSendResult { self.core_thread.send(msg) } fn sender(&self) -> IpcSender<CoreResourceMsg> { self.core_thread.clone() } } impl IpcSend<StorageThreadMsg> for ResourceThreads { fn send(&s...
{ ResourceThreads { core_thread: c, storage_thread: s, } }
identifier_body
lib.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #![feature(box_syntax)] #![feature(step_by)] #![deny(unsafe_code)] extern crate cookie as cookie_rs; extern crat...
Close(Option<u16>, String), Fail, } #[derive(Deserialize, Serialize)] pub struct WebSocketCommunicate { pub event_sender: IpcSender<WebSocketNetworkEvent>, pub action_receiver: IpcReceiver<WebSocketDomAction>, } #[derive(Deserialize, Serialize)] pub struct WebSocketConnectData { pub resource_url: ...
pub enum WebSocketNetworkEvent { ConnectionEstablished { protocol_in_use: Option<String>, }, MessageReceived(MessageData),
random_line_split
lib.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #![feature(box_syntax)] #![feature(step_by)] #![deny(unsafe_code)] extern crate cookie as cookie_rs; extern crat...
(url: &ServoUrl, error: &Error) -> Self { NetworkError::SslValidation(url.clone(), error.description().to_owned()) } } /// Normalize `slice`, as defined by /// [the Fetch Spec](https://fetch.spec.whatwg.org/#concept-header-value-normalize). pub fn trim_http_whitespace(mut slice: &[u8]) -> &[u8] { const...
from_ssl_error
identifier_name
lib.rs
use js_sys::Promise; use ofdb_seed::{boundary::TagFrequency as Tag, Api}; use seed::{prelude::*, *}; use std::{cell::RefCell, cmp::Ordering, rc::Rc}; use wasm_bindgen_futures::*; const API_URL: &str = "https://api.ofdb.io/v0"; const FETCH_TAGS_LIMIT: usize = 1_000; const FETCH_TAGS_MAX: usize = 10_000; const FETCH_TA...
() -> Kern { Kern { api: Api::new(API_URL.to_string()), mdl: Rc::new(RefCell::new(Mdl::default())), } } pub fn popular_tags(&self, max: usize, s: Option<String>) -> Promise { let future = popular_tags(self.api.clone(), self.mdl.clone(), s, max); future_to...
new
identifier_name
lib.rs
use js_sys::Promise; use ofdb_seed::{boundary::TagFrequency as Tag, Api}; use seed::{prelude::*, *}; use std::{cell::RefCell, cmp::Ordering, rc::Rc}; use wasm_bindgen_futures::*; const API_URL: &str = "https://api.ofdb.io/v0"; const FETCH_TAGS_LIMIT: usize = 1_000; const FETCH_TAGS_MAX: usize = 10_000; const FETCH_TA...
pub fn new() -> Kern { Kern { api: Api::new(API_URL.to_string()), mdl: Rc::new(RefCell::new(Mdl::default())), } } pub fn popular_tags(&self, max: usize, s: Option<String>) -> Promise { let future = popular_tags(self.api.clone(), self.mdl.clone(), s, max); ...
random_line_split
db.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/. */ //! Stores subscription information for `WebPush`. //! //! # The `WebPush` database //! //! The "subscriptions" ta...
} pub struct WebPushDb { db: Connection, } impl WebPushDb { /// Opens the database at `path` and creates it if not available yet. pub fn new(path: &str) -> Self { let db = Connection::open(path).unwrap(); db.execute("CREATE TABLE IF NOT EXISTS subscriptions ( user_id ...
};
random_line_split
db.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/. */ //! Stores subscription information for `WebPush`. //! //! # The `WebPush` database //! //! The "subscriptions" ta...
, None => { return None; }, }; } pub struct WebPushDb { db: Connection, } impl WebPushDb { /// Opens the database at `path` and creates it if not available yet. pub fn new(path: &str) -> Self { let db = Connection::open(path).unwrap(); db.execute("CREATE TABLE IF NOT EXISTS sub...
{ return Some(escape(x)); }
conditional_block
db.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/. */ //! Stores subscription information for `WebPush`. //! //! # The `WebPush` database //! //! The "subscriptions" ta...
(opt: &Option<String>) -> Option<String> { match *opt { Some(ref x) => { return Some(escape(x)); }, None => { return None; }, }; } pub struct WebPushDb { db: Connection, } impl WebPushDb { /// Opens the database at `path` and creates it if not available yet. pub fn new(path: &str) ...
escape_option
identifier_name
output_set.rs
extern crate pty_proc; extern crate libc; use std::io::Write; use self::pty_proc::prelude::*; const SIZE: Winszed = Winszed { ws_row: 8, ws_col: 10, ws_xpixel: 0, ws_ypixel: 0, }; #[test] fn test_output_set()
{ let mut display: Display = Display::from_winszed(SIZE); display.write(&[97u8, 100, 106, 105, 118, 97, 115, 64, 37, 109, 58, 37, 126, 47, 32, 40, 109, 97, 115, 116, 101, 114, 41, 32]); }
identifier_body
output_set.rs
extern crate pty_proc;
use self::pty_proc::prelude::*; const SIZE: Winszed = Winszed { ws_row: 8, ws_col: 10, ws_xpixel: 0, ws_ypixel: 0, }; #[test] fn test_output_set() { let mut display: Display = Display::from_winszed(SIZE); display.write(&[97u8, 100, 106, 105, 118, 97, 115, 64, 37, 109, 58, 37, 126, 47, 32, 40, 109, 97...
extern crate libc; use std::io::Write;
random_line_split
output_set.rs
extern crate pty_proc; extern crate libc; use std::io::Write; use self::pty_proc::prelude::*; const SIZE: Winszed = Winszed { ws_row: 8, ws_col: 10, ws_xpixel: 0, ws_ypixel: 0, }; #[test] fn
() { let mut display: Display = Display::from_winszed(SIZE); display.write(&[97u8, 100, 106, 105, 118, 97, 115, 64, 37, 109, 58, 37, 126, 47, 32, 40, 109, 97, 115, 116, 101, 114, 41, 32]); }
test_output_set
identifier_name
solver057.rs
// COPYRIGHT (C) 2017 barreiro. All Rights Reserved. // Rust solvers for Project Euler problems use euler::algorithm::long::{int_log_10, pow_10}; use euler::Solver; // It is possible to show that the square root of two can be expressed as an infinite continued fraction. // // sqrt(2) = 1 + 1 / (2 + 1 / (2 + 1 / (2 +....
self.d += self.n; self.n = (2 * self.d) - self.n; Some((self.n, self.d)) } }
{ self.n /= 10; self.d /= 10; }
conditional_block
solver057.rs
// COPYRIGHT (C) 2017 barreiro. All Rights Reserved. // Rust solvers for Project Euler problems use euler::algorithm::long::{int_log_10, pow_10}; use euler::Solver; // It is possible to show that the square root of two can be expressed as an infinite continued fraction. // // sqrt(2) = 1 + 1 / (2 + 1 / (2 + 1 / (2 +....
() -> Self { Solver057 { n: 1000 } } } impl Solver for Solver057 { fn solve(&self) -> isize { continued_root_two().take(self.n as _).filter(|&(n, d)| int_log_10(n) > int_log_10(d)).count() as _ } } // --- // struct ContinuedRootTwo { n: isize, d: isize, } fn continued_root_two() ...
default
identifier_name
solver057.rs
// COPYRIGHT (C) 2017 barreiro. All Rights Reserved. // Rust solvers for Project Euler problems use euler::algorithm::long::{int_log_10, pow_10}; use euler::Solver; // It is possible to show that the square root of two can be expressed as an infinite continued fraction. // // sqrt(2) = 1 + 1 / (2 + 1 / (2 + 1 / (2 +....
self.d /= 10; } self.d += self.n; self.n = (2 * self.d) - self.n; Some((self.n, self.d)) } }
self.n /= 10;
random_line_split
channel_permissions.rs
extern crate discord; use discord::model::{ ChannelId, PermissionOverwriteType, PermissionOverwrite, RoleId, UserId, permissions }; use discord::Discord; use std::env; fn
() { // Log in to Discord using a bot token from the environment let discord = Discord::from_bot_token( &env::var("DISCORD_TOKEN").expect("Expected token"), ).expect("login failed"); println!("Ready."); // Create bitflags of the permissions to allow and deny let allow = permissions::VOICE_CONNECT | permissions...
main
identifier_name
channel_permissions.rs
extern crate discord; use discord::model::{ ChannelId, PermissionOverwriteType, PermissionOverwrite, RoleId, UserId, permissions }; use discord::Discord; use std::env; fn main()
deny: deny, }; println!("{:?}", discord.create_permission(channel_id, target)); // Similarly, setting the permissions for a role: let role_id = RoleId(0); // the id of the role to set permissions for let target = PermissionOverwrite { kind: PermissionOverwriteType::Role(role_id), allow: allow, deny: deny,...
{ // Log in to Discord using a bot token from the environment let discord = Discord::from_bot_token( &env::var("DISCORD_TOKEN").expect("Expected token"), ).expect("login failed"); println!("Ready."); // Create bitflags of the permissions to allow and deny let allow = permissions::VOICE_CONNECT | permissions::V...
identifier_body
channel_permissions.rs
extern crate discord; use discord::model::{ ChannelId, PermissionOverwriteType, PermissionOverwrite, RoleId, UserId, permissions }; use discord::Discord; use std::env; fn main() { // Log in to Discord using a bot token from the environment let discord = Discord::from_bot_token( &env::var("DISCORD_TOKEN").ex...
let user_id = UserId(0); // the id of the user to set permissions for let target = PermissionOverwrite { kind: PermissionOverwriteType::Member(user_id), allow: allow, deny: deny, }; println!("{:?}", discord.create_permission(channel_id, target)); // Similarly, setting the permissions for a role: let role_i...
let channel_id = ChannelId(0); // the id of the channel to set permissions // Permissions on a channel can be set for either a member or a role // // Setting the permissions for a member:
random_line_split
streamer.rs
use fst::{self, IntoStreamer, Streamer}; use fst::map::{StreamBuilder, Stream}; use common::BinarySerializable; use super::TermDictionary; /// `TermStreamerBuilder` is an helper object used to define /// a range of terms that should be streamed. pub struct TermStreamerBuilder<'a, V> where V: 'a + BinarySerializabl...
} /// Accesses the current key. /// /// `.key()` should return the key that was returned /// by the `.next()` method. /// /// If the end of the stream as been reached, and `.next()` /// has been called and returned `None`, `.key()` remains /// the value of the last key encounterred...
{ false }
conditional_block
streamer.rs
use fst::{self, IntoStreamer, Streamer}; use fst::map::{StreamBuilder, Stream}; use common::BinarySerializable; use super::TermDictionary; /// `TermStreamerBuilder` is an helper object used to define /// a range of terms that should be streamed. pub struct TermStreamerBuilder<'a, V> where V: 'a + BinarySerializabl...
/// Accesses the current value. /// /// Values are accessed in a lazy manner, their data is fetched /// and deserialized only at the moment of the call to `.value()`. /// /// Calling `.value()` after the end of the stream will return the /// last `.value()` encounterred. /// /// # ...
{ &self.buffer }
identifier_body
streamer.rs
use fst::{self, IntoStreamer, Streamer}; use fst::map::{StreamBuilder, Stream}; use common::BinarySerializable; use super::TermDictionary; /// `TermStreamerBuilder` is an helper object used to define /// a range of terms that should be streamed. pub struct TermStreamerBuilder<'a, V> where V: 'a + BinarySerializabl...
pub fn lt<T: AsRef<[u8]>>(mut self, bound: T) -> Self { self.stream_builder = self.stream_builder.lt(bound); self } /// Creates the stream corresponding to the range /// of terms defined using the `TermStreamerBuilder`. pub fn into_stream(self) -> TermStreamer<'a, V> { TermS...
/// Limit the range to terms lesser or equal to the bound
random_line_split
streamer.rs
use fst::{self, IntoStreamer, Streamer}; use fst::map::{StreamBuilder, Stream}; use common::BinarySerializable; use super::TermDictionary; /// `TermStreamerBuilder` is an helper object used to define /// a range of terms that should be streamed. pub struct TermStreamerBuilder<'a, V> where V: 'a + BinarySerializabl...
(&mut self) -> bool { if let Some((term, offset)) = self.stream.next() { self.buffer.clear(); self.buffer.extend_from_slice(term); self.offset = offset; true } else { false } } /// Accesses the current key. /// /// `.ke...
advance
identifier_name
mean_angle.rs
// http://rosettacode.org/wiki/Averages/Mean_angle use std::f64::consts::PI; fn mean_angle(angles: &[f64]) -> f64 { let (sum_cos, sum_sin) = angles.iter() .map(|&x| x * PI / 180.) .map(|x| (x.cos(), x.sin())) .fold((0., 0.), |(sc, ss), (c, s)| (sc + c, ss + s)); let mean_cos = sum_cos / ...
{ use std::f64; let set1 = [350., 10.]; let set2 = [90., 180., 270., 360.]; let set3 = [10., 20., 30.]; // We need to round the numbers assert!((mean_angle(&set1).round() - 0.).abs() < f64::EPSILON); assert!((mean_angle(&set2).round() - -90.).abs() < f64::EPSILON); assert!((mean_angle(...
identifier_body
mean_angle.rs
// http://rosettacode.org/wiki/Averages/Mean_angle use std::f64::consts::PI; fn mean_angle(angles: &[f64]) -> f64 {
.map(|x| (x.cos(), x.sin())) .fold((0., 0.), |(sc, ss), (c, s)| (sc + c, ss + s)); let mean_cos = sum_cos / angles.len() as f64; let mean_sin = sum_sin / angles.len() as f64; mean_sin.atan2(mean_cos) * 180. / PI } fn main() { let set1 = &[350., 10.]; let set2 = &[90., 180., 270., 36...
let (sum_cos, sum_sin) = angles.iter() .map(|&x| x * PI / 180.)
random_line_split
mean_angle.rs
// http://rosettacode.org/wiki/Averages/Mean_angle use std::f64::consts::PI; fn mean_angle(angles: &[f64]) -> f64 { let (sum_cos, sum_sin) = angles.iter() .map(|&x| x * PI / 180.) .map(|x| (x.cos(), x.sin())) .fold((0., 0.), |(sc, ss), (c, s)| (sc + c, ss + s)); let mean_cos = sum_cos / ...
() { let set1 = &[350., 10.]; let set2 = &[90., 180., 270., 360.]; let set3 = &[10., 20., 30.]; println!("Mean angle of first set is {} degrees", mean_angle(set1)); println!("Mean angle of second set is {} degrees", mean_angle(set2)); println!("Mean angle of third set is {} degrees", mean_angle...
main
identifier_name
job.rs
use std::fmt; use util::{CargoResult, Fresh, Dirty, Freshness}; use super::job_queue::JobState; pub struct Job { dirty: Work, fresh: Work } /// Each proc should send its description before starting. /// It should send either once or close immediately. pub struct Work { inner: Box<for <'a, 'b> FnBox<&'a JobState<...
(self: Box<F>, a: A) -> R { (*self)(a) } } impl Work { pub fn new<F>(f: F) -> Work where F: FnOnce(&JobState) -> CargoResult<()> + Send +'static { Work { inner: Box::new(f) } } pub fn noop() -> Work { Work::new(|_| Ok(())) } pub fn call(self, tx: &JobState)...
call_box
identifier_name
job.rs
use std::fmt; use util::{CargoResult, Fresh, Dirty, Freshness}; use super::job_queue::JobState; pub struct Job { dirty: Work, fresh: Work } /// Each proc should send its description before starting. /// It should send either once or close immediately. pub struct Work { inner: Box<for <'a, 'b> FnBox<&'a JobState<...
}
{ write!(f, "Job {{ ... }}") }
identifier_body
job.rs
use std::fmt; use util::{CargoResult, Fresh, Dirty, Freshness}; use super::job_queue::JobState; pub struct Job { dirty: Work, fresh: Work } /// Each proc should send its description before starting. /// It should send either once or close immediately. pub struct Work { inner: Box<for <'a, 'b> FnBox<&'a JobState<...
impl fmt::Debug for Job { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "Job {{... }}") } }
random_line_split
issue-27901.rs
// Copyright 2017 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
fn main() { let fx = f as for<'t> fn(&'t str) -> (&'t str, <&'t str as Stream>::Item); assert_eq!(fx("hi"), ("hi", 42)); }
{ (s, 42) }
identifier_body
issue-27901.rs
// Copyright 2017 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 ...
<'s>(s: &'s str) -> (&'s str, <&'s str as Stream>::Item) { (s, 42) } fn main() { let fx = f as for<'t> fn(&'t str) -> (&'t str, <&'t str as Stream>::Item); assert_eq!(fx("hi"), ("hi", 42)); }
f
identifier_name
issue-27901.rs
// 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. // run-pass trait Stream { type Item; } impl<'a> Stream for &'a str { type Item = u8; } ...
// Copyright 2017 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
random_line_split
rtl8139.rs
use alloc::boxed::Box; use arch::memory; use collections::slice; use collections::string::ToString; use collections::vec::Vec; use collections::vec_deque::VecDeque; use core::ptr; use common::debug; use drivers::pci::config::PciConfig; use drivers::io::{Io, Pio}; use network::common::*; use network::scheme::*; u...
} pub struct Rtl8139 { pci: PciConfig, base: usize, memory_mapped: bool, irq: u8, resources: Intex<Vec<*mut NetworkResource>>, inbound: VecDeque<Vec<u8>>, outbound: VecDeque<Vec<u8>>, txds: Vec<Txd>, txd_i: usize, port: Rtl8139Port, } impl Rtl8139 { pub fn new(mut pci: Pci...
{ return Rtl8139Port { idr: [Pio::<u8>::new(base + 0x00), Pio::<u8>::new(base + 0x01), Pio::<u8>::new(base + 0x02), Pio::<u8>::new(base + 0x03), Pio::<u8>::new(base + 0x04), Pio::<u8>::new(base + 0x05)], ...
identifier_body
rtl8139.rs
use alloc::boxed::Box; use arch::memory; use collections::slice; use collections::string::ToString; use collections::vec::Vec; use collections::vec_deque::VecDeque; use core::ptr; use common::debug; use drivers::pci::config::PciConfig; use drivers::io::{Io, Pio}; use network::common::*; use network::scheme::*; u...
(mut pci: PciConfig) -> Box<Self> { let pci_id = unsafe { pci.read(0x00) }; let revision = (unsafe { pci.read(0x08) } & 0xFF) as u8; if pci_id == 0x813910EC && revision < 0x20 { debugln!("Not an 8139C+ compatible chip") } let base = unsafe { pci.read(0x10) as usize }...
new
identifier_name
rtl8139.rs
use alloc::boxed::Box; use arch::memory; use collections::slice; use collections::string::ToString; use collections::vec::Vec; use collections::vec_deque::VecDeque; use core::ptr; use common::debug; use drivers::pci::config::PciConfig; use drivers::io::{Io, Pio}; use network::common::*; use network::scheme::*; u...
, None => break, } if remove { resources.remove(i); } } } fn sync(&mut self) { unsafe { { let resources = self.resources.lock(); for resource in resources.iter() { ...
{ i += 1; }
conditional_block
rtl8139.rs
use alloc::boxed::Box; use arch::memory; use collections::slice; use collections::string::ToString; use collections::vec::Vec; use collections::vec_deque::VecDeque; use core::ptr; use common::debug; use drivers::pci::config::PciConfig; use drivers::io::{Io, Pio}; use network::common::*; use network::scheme::*; u...
self.pci.flag(4, 4, true); // Bus mastering let base = self.base as u16; self.port.config1.write(0); self.port.cr.write(RTL8139_CR_RST); while self.port.cr.read() & RTL8139_CR_RST!= 0 {} debug::d(" MAC: "); MAC_ADDR = MacAddr { bytes: [self.port.id...
} else { debug::d(" port mapped"); } debug::d(" IRQ: "); debug::dbh(self.irq);
random_line_split
configuration.rs
extern crate failure; extern crate json; extern crate rawr; use self::json::JsonValue; use db; use db::Database; use rawr::auth::PasswordAuthenticator; use rawr::client::RedditClient; use LibResult; use std::fs::File; use std::io::Read; /* * The Configuration data for the bot contained in one struct */ pub stru...
{ pub id: String, pub secret: String, pub username: String, pub password: String, } pub fn get() -> LibResult<Configuration> { let authentication = read_json("authentication.json").and_then(|mut json| { Ok(AuthenticationData { id: String::from(json.remove("id").as_str().expect(...
AuthenticationData
identifier_name
configuration.rs
extern crate failure; extern crate json; extern crate rawr; use self::json::JsonValue; use db; use db::Database; use rawr::auth::PasswordAuthenticator; use rawr::client::RedditClient; use LibResult; use std::fs::File; use std::io::Read; /* * The Configuration data for the bot contained in one struct */ pub stru...
// Returns a list of subreddit Strings specified in the subreddits.json fn get_subreddits(data: JsonValue) -> LibResult<Vec<String>> { let mut list = Vec::new(); for element in data.members() { let name = element.as_str().expect("All elements in subreddits.json array should be strings"); // TODO; ...
{ let contents = read_file(name)?; let parsed = json::parse(&contents)?; Ok(parsed) }
identifier_body
configuration.rs
extern crate failure; extern crate json; extern crate rawr; use self::json::JsonValue; use db; use db::Database; use rawr::auth::PasswordAuthenticator; use rawr::client::RedditClient; use LibResult; use std::fs::File; use std::io::Read; /* * The Configuration data for the bot contained in one struct */ pub stru...
Ok(Configuration { authentication, subreddits, database, client }) } fn read_file(name: &str) -> LibResult<String> { let mut file = File::open(name)?; let mut contents = String::new(); file.read_to_string(&mut contents)?; Ok(contents) } fn read_json(name: &str) ...
let database = db::from_connection("db.sqlite").or_else(|e| { eprintln!("Problem with SQL database: {}", e); Err(e) })?;
random_line_split
main.rs
extern crate xml; extern crate clap; mod polyfill; mod emitter; use emitter::Emitter; use std::fs::File; use std::io::BufReader; use xml::reader::{EventReader, XmlEvent}; use clap::{Arg, App}; fn
<'a>(ids: &str, attr: &'a Vec<xml::attribute::OwnedAttribute>) -> Option<&'a str> { let id_attr = match attr.iter().find(|ref a| a.name.local_name == "id") { Some(a) => a, None => return None }; if ids.is_empty() || ids.split(',').any(|i| id_attr.value == i) { Some(&id_attr.value) ...
matching_element_id
identifier_name
main.rs
extern crate xml; extern crate clap; mod polyfill; mod emitter; use emitter::Emitter; use std::fs::File; use std::io::BufReader; use xml::reader::{EventReader, XmlEvent}; use clap::{Arg, App}; fn matching_element_id<'a>(ids: &str, attr: &'a Vec<xml::attribute::OwnedAttribute>) -> Option<&'a str>
fn main() { let app: App = App::new("grayfx") .version("0.1.0") .author("Nigel Baillie <metreckk@gmail.com>") .about("Converts Inkscape SVGs into C++ rendering and/or physics code for Gray") .arg(Arg::with_name("input") .help("the svg file to parse") .short("f") ...
{ let id_attr = match attr.iter().find(|ref a| a.name.local_name == "id") { Some(a) => a, None => return None }; if ids.is_empty() || ids.split(',').any(|i| id_attr.value == i) { Some(&id_attr.value) } else { None } }
identifier_body
main.rs
extern crate xml; extern crate clap; mod polyfill; mod emitter; use emitter::Emitter; use std::fs::File; use std::io::BufReader; use xml::reader::{EventReader, XmlEvent}; use clap::{Arg, App}; fn matching_element_id<'a>(ids: &str, attr: &'a Vec<xml::attribute::OwnedAttribute>) -> Option<&'a str> { let id_attr ...
let ids = matches.value_of("ids").unwrap_or(""); let color = matches.value_of("color"); let ids_count = if ids.is_empty() { 0 } else { ids.chars().fold(1, |n, c| if c == ',' { n + 1 } else { n }) }; // === Parse XML === let mut emitter = Emitter::new(); let parser = Eve...
let file = File::open(filename).unwrap(); let file = BufReader::new(file);
random_line_split
issue-34947-pow-i32.rs
// Copyright 2017 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 ...
(x: i32) -> i32 { // CHECK: mul // CHECK-NEXT: mul // CHECK-NEXT: mul // CHECK-NEXT: ret x.pow(5) }
issue_34947
identifier_name
issue-34947-pow-i32.rs
// Copyright 2017 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 ...
#![crate_type = "lib"] // CHECK-LABEL: @issue_34947 #[no_mangle] pub fn issue_34947(x: i32) -> i32 { // CHECK: mul // CHECK-NEXT: mul // CHECK-NEXT: mul // CHECK-NEXT: ret x.pow(5) }
// compile-flags: -O
random_line_split
issue-34947-pow-i32.rs
// Copyright 2017 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 ...
{ // CHECK: mul // CHECK-NEXT: mul // CHECK-NEXT: mul // CHECK-NEXT: ret x.pow(5) }
identifier_body
encryption.rs
// Copyright 2020 TiKV Project Authors. Licensed under Apache-2.0. use std::{fs::File, io::Write, time::Duration}; use encryption_export::{ create_backend, DataKeyManager, DataKeyManagerArgs, EncryptionConfig, FileConfig, MasterKeyConfig, Result, }; use kvproto::encryptionpb::EncryptionMethod; use tikv_util::...
pub fn new_test_key_manager( tmp_dir: &tempfile::TempDir, method: Option<EncryptionMethod>, master_key: Option<MasterKeyConfig>, previous_master_key: Option<MasterKeyConfig>, ) -> Result<Option<DataKeyManager>> { let default_config = new_test_file_master_key(tmp_dir); let master_key = master_ke...
previous_master_key: master_key_cfg, } }
random_line_split
encryption.rs
// Copyright 2020 TiKV Project Authors. Licensed under Apache-2.0. use std::{fs::File, io::Write, time::Duration}; use encryption_export::{ create_backend, DataKeyManager, DataKeyManagerArgs, EncryptionConfig, FileConfig, MasterKeyConfig, Result, }; use kvproto::encryptionpb::EncryptionMethod; use tikv_util::...
fn new_test_file_master_key(tmp: &tempfile::TempDir) -> MasterKeyConfig { let key_path = tmp.path().join("test_key").to_str().unwrap().to_owned(); create_test_key_file(&key_path); MasterKeyConfig::File { config: FileConfig { path: key_path }, } } pub fn new_file_security_config(dir: &tempfile...
{ let mut file = File::create(path).unwrap(); file.write_all(b"603deb1015ca71be2b73aef0857d77811f352c073b6108d72d9810a30914dff4\n") .unwrap(); }
identifier_body
encryption.rs
// Copyright 2020 TiKV Project Authors. Licensed under Apache-2.0. use std::{fs::File, io::Write, time::Duration}; use encryption_export::{ create_backend, DataKeyManager, DataKeyManagerArgs, EncryptionConfig, FileConfig, MasterKeyConfig, Result, }; use kvproto::encryptionpb::EncryptionMethod; use tikv_util::...
(dir: &tempfile::TempDir) -> EncryptionConfig { let master_key_cfg = new_test_file_master_key(dir); EncryptionConfig { data_encryption_method: EncryptionMethod::Aes256Ctr, data_key_rotation_period: ReadableDuration::days(7), enable_file_dictionary_log: true, file_dictionary_rewri...
new_file_security_config
identifier_name
mod.rs
use std::io; use calloop::{EventSource, Interest, Mode, Poll, PostAction, Readiness, Token, TokenFactory}; use dbus::{ blocking::LocalConnection, channel::{BusType, Channel, Watch}, Message, }; #[cfg(feature = "backend_session_logind")] pub mod logind; /// An internal wrapper for handling a DBus connect...
self.current_watch = new_watch; Ok(()) } fn unregister(&mut self, poll: &mut Poll) -> io::Result<()> { if self.current_watch.read || self.current_watch.write { poll.unregister(self.current_watch.fd)?; } self.token = Token::invalid(); self.current_wat...
{ // update the registration if let Some(interest) = new_interest { poll.reregister(self.current_watch.fd, interest, Mode::Level, self.token)?; } else { poll.unregister(self.current_watch.fd)?; } }
conditional_block
mod.rs
use std::io; use calloop::{EventSource, Interest, Mode, Poll, PostAction, Readiness, Token, TokenFactory}; use dbus::{ blocking::LocalConnection, channel::{BusType, Channel, Watch}, Message, }; #[cfg(feature = "backend_session_logind")] pub mod logind; /// An internal wrapper for handling a DBus connect...
fn register(&mut self, poll: &mut Poll, factory: &mut TokenFactory) -> io::Result<()> { if self.current_watch.read || self.current_watch.write { return Err(io::Error::new( io::ErrorKind::AlreadyExists, "DBus session already registered to calloop", ));...
self.cx.channel().flush(); Ok(PostAction::Continue) }
random_line_split
mod.rs
use std::io; use calloop::{EventSource, Interest, Mode, Poll, PostAction, Readiness, Token, TokenFactory}; use dbus::{ blocking::LocalConnection, channel::{BusType, Channel, Watch}, Message, }; #[cfg(feature = "backend_session_logind")] pub mod logind; /// An internal wrapper for handling a DBus connect...
() -> Result<DBusConnection, dbus::Error> { let mut chan = Channel::get_private(BusType::System)?; chan.set_watch_enabled(true); Ok(DBusConnection { cx: chan.into(), token: Token::invalid(), current_watch: Watch { fd: -1, read: ...
new_system
identifier_name
mod.rs
use std::io; use calloop::{EventSource, Interest, Mode, Poll, PostAction, Readiness, Token, TokenFactory}; use dbus::{ blocking::LocalConnection, channel::{BusType, Channel, Watch}, Message, }; #[cfg(feature = "backend_session_logind")] pub mod logind; /// An internal wrapper for handling a DBus connect...
fn reregister(&mut self, poll: &mut Poll, factory: &mut TokenFactory) -> io::Result<()> { let new_watch = self.cx.channel().watch(); let new_interest = match (new_watch.read, new_watch.write) { (true, true) => Some(Interest::BOTH), (true, false) => Some(Interest::READ), ...
{ if self.current_watch.read || self.current_watch.write { return Err(io::Error::new( io::ErrorKind::AlreadyExists, "DBus session already registered to calloop", )); } // reregister handles all the watch logic self.reregister(poll, ...
identifier_body
main.rs
extern crate crypto; use crypto::digest::Digest; use crypto::md5; type Hash = [u8; 16]; fn main() { let number = (1..).find(|x| compute_hash_string("iwrupvqb".to_string(), *x).starts_with("000000")).unwrap(); println!("The number is: {}", number); } fn compute_hash_string(key: String, number: i32) -> String...
fn compute_hash(key: String, number: i32) -> Hash { let mut digest = md5::Md5::new(); digest.input_str(&format!("{}{}", key, number)); let mut result = [0; 16]; digest.result(&mut result); result }
{ let hash = compute_hash(key, number); hash.iter().fold(String::new(), |acc, x| format!("{}{:>02x}", acc, x)) }
identifier_body
main.rs
extern crate crypto; use crypto::digest::Digest; use crypto::md5; type Hash = [u8; 16]; fn main() { let number = (1..).find(|x| compute_hash_string("iwrupvqb".to_string(), *x).starts_with("000000")).unwrap(); println!("The number is: {}", number); } fn compute_hash_string(key: String, number: i32) -> String...
fn compute_hash(key: String, number: i32) -> Hash { let mut digest = md5::Md5::new(); digest.input_str(&format!("{}{}", key, number)); let mut result = [0; 16]; digest.result(&mut result); result }
}
random_line_split
main.rs
extern crate crypto; use crypto::digest::Digest; use crypto::md5; type Hash = [u8; 16]; fn main() { let number = (1..).find(|x| compute_hash_string("iwrupvqb".to_string(), *x).starts_with("000000")).unwrap(); println!("The number is: {}", number); } fn compute_hash_string(key: String, number: i32) -> String...
(key: String, number: i32) -> Hash { let mut digest = md5::Md5::new(); digest.input_str(&format!("{}{}", key, number)); let mut result = [0; 16]; digest.result(&mut result); result }
compute_hash
identifier_name
server.rs
// Copyright 2017 PingCAP, Inc. // // 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 i...
#[macro_use] extern crate log; #[path = "../log_util.rs"] mod log_util; use std::io::Read; use std::sync::Arc; use std::{io, thread}; use futures::sync::oneshot; use futures::Future; use grpcio::{ChannelBuilder, Environment, ResourceQuota, RpcContext, ServerBuilder, UnarySink}; use grpcio_proto::example::helloworld...
// limitations under the License.
random_line_split
server.rs
// Copyright 2017 PingCAP, Inc. // // 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 i...
; impl Greeter for GreeterService { fn say_hello(&mut self, ctx: RpcContext<'_>, req: HelloRequest, sink: UnarySink<HelloReply>) { let msg = format!("Hello {}", req.get_name()); let mut resp = HelloReply::default(); resp.set_message(msg); let f = sink .success(resp) ...
GreeterService
identifier_name
explicit-self.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 ...
else {b} } } fn select_based_on_unit_circle<'r, T>( threshold: f64, a: &'r T, b: &'r T) -> &'r T { let shape = &circle(Point{x: 0.0, y: 0.0}, 1.0); shape.select(threshold, a, b) } #[deriving(Clone)] struct thing { x: A } #[deriving(Clone)] struct A { a: int } fn thing(x: A) -> thing { ...
{a}
conditional_block
explicit-self.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 thing(x: A) -> thing { thing { x: x } } impl thing { pub fn bar(~self) -> int { self.x.a } pub fn quux(&self) -> int { self.x.a } pub fn baz<'a>(&'a self) -> &'a A { &self.x } pub fn spam(self) -> int { self.x.a } } trait Nus { fn f(&self); } impl Nus for thing { fn f(&self) {} }...
} #[deriving(Clone)] struct A { a: int
random_line_split
explicit-self.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 ...
(&self) {} } pub fn main() { let y = ~thing(A {a: 10}); assert_eq!(y.clone().bar(), 10); assert_eq!(y.quux(), 10); let z = thing(A {a: 11}); assert_eq!(z.spam(), 11); }
f
identifier_name
main.rs
#![feature(lang_items)] #![feature(asm)] #![no_std] #![no_main] mod exceptions; mod gpio; #[no_mangle] pub fn start() ->! { /* let mut i = 0; unsafe { let ram_boundary = *(0x0000_0000 as *const u32); // Get stack boundary let crash = *(ram_boundary as *const u32); // Crash the program } lo...
mod vector_table { #[link_section = ".reset"] static RESET: fn() ->! = ::start; } #[lang = "eh_personality"] extern fn eh_personality() {} #[lang = "panic_fmt"] extern fn panic_fmt() ->! {loop{}}
*bsrr |= 1 << (16 + 3); } } */
random_line_split
main.rs
#![feature(lang_items)] #![feature(asm)] #![no_std] #![no_main] mod exceptions; mod gpio; #[no_mangle] pub fn start() ->! { /* let mut i = 0; unsafe { let ram_boundary = *(0x0000_0000 as *const u32); // Get stack boundary let crash = *(ram_boundary as *const u32); // Crash the program } lo...
{loop{}}
identifier_body
main.rs
#![feature(lang_items)] #![feature(asm)] #![no_std] #![no_main] mod exceptions; mod gpio; #[no_mangle] pub fn start() ->! { /* let mut i = 0; unsafe { let ram_boundary = *(0x0000_0000 as *const u32); // Get stack boundary let crash = *(ram_boundary as *const u32); // Crash the program } lo...
(n: u32) { for _ in 0..n {} } /* fn turn_on_gpiob() { // Start address of the RCC register block const RCC: u32 = 0x4002_1000; const RCC_AHBENR: u32 = 0x14; const RCC_AHBENR_IOPBEN: u32 = (1 << 18); unsafe { let ahbenr = (RCC + RCC_AHBENR) as *mut u32; *ahbenr |= RCC_AHBENR_IOPBEN; // Enable GP...
delay
identifier_name
htmlprogresselement.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::bindings::codegen::Bindings::HTMLProgressElementBinding::{self, HTMLProgressElementMethods}; use dom::bin...
fn Labels(&self) -> Root<NodeList> { self.upcast::<HTMLElement>().labels() } }
} } impl HTMLProgressElementMethods for HTMLProgressElement { // https://html.spec.whatwg.org/multipage/#dom-lfe-labels
random_line_split
htmlprogresselement.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::bindings::codegen::Bindings::HTMLProgressElementBinding::{self, HTMLProgressElementMethods}; use dom::bin...
(local_name: LocalName, prefix: Option<DOMString>, document: &Document) -> HTMLProgressElement { HTMLProgressElement { htmlelement: HTMLElement::new_inherited(local_name, prefix, document) } } #[allow(unrooted_must_root)] ...
new_inherited
identifier_name
htmlprogresselement.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::bindings::codegen::Bindings::HTMLProgressElementBinding::{self, HTMLProgressElementMethods}; use dom::bin...
#[allow(unrooted_must_root)] pub fn new(local_name: LocalName, prefix: Option<DOMString>, document: &Document) -> Root<HTMLProgressElement> { Node::reflect_node(box HTMLProgressElement::new_inherited(local_name, prefix, document), document, ...
{ HTMLProgressElement { htmlelement: HTMLElement::new_inherited(local_name, prefix, document) } }
identifier_body
pseudo_element_definition.mako.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ /// Gecko's pseudo-element definition. #[derive(Clone, Debug, Eq, Hash, MallocSizeOf, PartialEq, ToShmem)] pub en...
(name: &str) -> Option<Self> { // We don't need to support tree pseudos because functional // pseudo-elements needs arguments, and thus should be created // via other methods. match_ignore_ascii_case! { name, % for pseudo in SIMPLE_PSEUDOS: "${pseudo.value[1:]}" =...
from_slice
identifier_name
pseudo_element_definition.mako.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ /// Gecko's pseudo-element definition. #[derive(Clone, Debug, Eq, Hash, MallocSizeOf, PartialEq, ToShmem)] pub en...
None } /// Constructs a pseudo-element from a string of text. /// /// Returns `None` if the pseudo-element is not recognised. #[inline] pub fn from_slice(name: &str) -> Option<Self> { // We don't need to support tree pseudos because functional // pseudo-elements needs ar...
% endif % endfor
random_line_split
pseudo_element_definition.mako.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ /// Gecko's pseudo-element definition. #[derive(Clone, Debug, Eq, Hash, MallocSizeOf, PartialEq, ToShmem)] pub en...
Ok(()) } }
{ if !args.is_empty() { dest.write_char('(')?; let mut iter = args.iter(); if let Some(first) = iter.next() { serialize_atom_identifier(&first, dest)?; for item in iter { dest.write_str(", ")?; ...
conditional_block
mod.rs
LexicalRegionResolutions { error_region: tcx.types.re_static, values: IndexVec::from_elem_n(VarValue::Value(tcx.types.re_empty), self.num_vars()) } } fn dump_constraints(&self, free_regions: &RegionRelations<'_, '_, 'tcx>) { debug!( "----() Start constrain...
// While all things transitively reachable in the graph // from the variable (`'0` in the example above). let seed_index = NodeIndex(vid.index() as usize); for succ_index in graph.depth_traverse(seed_index, OUTGOING) { let succ_index = succ_index.0; ...
for (r, vid) in seeds {
random_line_split
mod.rs
LexicalRegionResolutions { error_region: tcx.types.re_static, values: IndexVec::from_elem_n(VarValue::Value(tcx.types.re_empty), self.num_vars()) } } fn dump_constraints(&self, free_regions: &RegionRelations<'_, '_, 'tcx>) { debug!( "----() Start constraint...
(&ReEarlyBound(_), &ReEarlyBound(_)) | (&ReFree(_), &ReEarlyBound(_)) | (&ReEarlyBound(_), &ReFree(_)) | (&ReFree(_), &ReFree(_)) => self.region_rels.lub_free_regions(a, b), // For these types, we cannot define any additional // relationship: ...
{ // The region corresponding to an outer block is a // subtype of the region corresponding to an inner // block. let lub = self.region_rels .region_scope_tree .nearest_common_ancestor(a_id, b_id); tc...
conditional_block
mod.rs
LexicalRegionResolutions { error_region: tcx.types.re_static, values: IndexVec::from_elem_n(VarValue::Value(tcx.types.re_empty), self.num_vars()) } } fn dump_constraints(&self, free_regions: &RegionRelations<'_, '_, 'tcx>) { debug!( "----() Start constraint...
(&self, a: Region<'tcx>, b: Region<'tcx>) -> Region<'tcx> { let tcx = self.tcx(); match (a, b) { (&ty::ReClosureBound(..), _) | (_, &ty::ReClosureBound(..)) | (&ReLateBound(..), _) | (_, &ReLateBound(..)) | (&ReErased, _) | (_, &ReE...
lub_concrete_regions
identifier_name
prime_decomposition.rs
// Implements http://rosettacode.org/wiki/Prime_decomposition // We need this to be public because it is used from another file pub fn
(mut nb: usize) -> Vec<usize> { let mut result = vec!(); // First we take out all even factors. while nb % 2 == 0 { result.push(2); nb /= 2; } // Then (if any left) we take out the odd ones. let mut cand = 3; let mut max_bound = (nb as f32).sqrt() as usize + 1; while c...
factor
identifier_name
prime_decomposition.rs
// Implements http://rosettacode.org/wiki/Prime_decomposition // We need this to be public because it is used from another file pub fn factor(mut nb: usize) -> Vec<usize> { let mut result = vec!(); // First we take out all even factors. while nb % 2 == 0 { result.push(2); nb /= 2; } ...
{ assert!(factor(5) == vec!(5)); assert!(factor(15) == vec!(3, 5)); assert!(factor(16) == vec!(2, 2, 2, 2)); assert!(factor(10287) == vec!(3, 3, 3, 3, 127)); }
identifier_body
prime_decomposition.rs
// Implements http://rosettacode.org/wiki/Prime_decomposition // We need this to be public because it is used from another file pub fn factor(mut nb: usize) -> Vec<usize> { let mut result = vec!(); // First we take out all even factors. while nb % 2 == 0 { result.push(2); nb /= 2; } ...
while nb % cand == 0 { result.push(cand); nb /= cand; } max_bound = (nb as f32).sqrt() as usize + 1; cand += 2; } if nb > 1 { result.push(nb); } result } // Needed so parallel_calculations compiles cleanly, because it // uses this code a...
random_line_split
prime_decomposition.rs
// Implements http://rosettacode.org/wiki/Prime_decomposition // We need this to be public because it is used from another file pub fn factor(mut nb: usize) -> Vec<usize> { let mut result = vec!(); // First we take out all even factors. while nb % 2 == 0 { result.push(2); nb /= 2; } ...
result } // Needed so parallel_calculations compiles cleanly, because it // uses this code as a library #[allow(dead_code)] #[cfg(not(test))] fn main() { println!("Factors of 5: {:?}", factor(5)); println!("Factors of 15: {:?}", factor(15)); println!("Factors of 16: {:?}", factor(16)); println!("...
{ result.push(nb); }
conditional_block
extract.rs
use std::fs; use std::io; fn main() { std::process::exit(real_main()); } fn real_main() -> i32 { let args: Vec<_> = std::env::args().collect(); if args.len() < 2 { println!("Usage: {} ", args[0]); return 1; } let fname = std::path::Path::new(&*args[1]); let file = fs::File::ope...
// Get and Set permissions #[cfg(unix)] { use std::os::unix::fs::PermissionsExt; if let Some(mode) = file.unix_mode() { fs::set_permissions(&outpath, fs::Permissions::from_mode(mode)).unwrap(); } } } 0 }
let mut outfile = fs::File::create(&outpath).unwrap(); io::copy(&mut file, &mut outfile).unwrap(); }
random_line_split
extract.rs
use std::fs; use std::io; fn main() { std::process::exit(real_main()); } fn real_main() -> i32
if!comment.is_empty() { println!("File {} comment: {}", i, comment); } } if (*file.name()).ends_with('/') { println!("File {} extracted to \"{}\"", i, outpath.display()); fs::create_dir_all(&outpath).unwrap(); } else { ...
{ let args: Vec<_> = std::env::args().collect(); if args.len() < 2 { println!("Usage: {} <filename>", args[0]); return 1; } let fname = std::path::Path::new(&*args[1]); let file = fs::File::open(&fname).unwrap(); let mut archive = zip::ZipArchive::new(file).unwrap(); for i ...
identifier_body