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 |
|---|---|---|---|---|
mod.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/. */
pub mod dom_manipulation;
pub mod file_reading;
pub mod history_traversal;
pub mod networking;
pub mod performance... | <T: Task + Send +'static>(&self, msg: Box<T>, global: &GlobalScope) -> Result<(), ()> {
self.queue_with_canceller(msg, &global.task_canceller())
}
}
| queue | identifier_name |
mod.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/. */
pub mod dom_manipulation;
pub mod file_reading;
pub mod history_traversal;
pub mod networking;
pub mod performance... |
}
| {
self.queue_with_canceller(msg, &global.task_canceller())
} | identifier_body |
main.rs | mod binary_parser;
mod chip8;
mod chip8_display;
extern crate rand;
extern crate sdl2;
use sdl2::pixels::Color;
use sdl2::event::Event;
use sdl2::keyboard::Keycode;
fn | () {
let mut dummy_display = chip8_display::DummyCHIP8Display::new();
let mut chip: chip8::CHIP8 = chip8::CHIP8::new(&mut dummy_display);
chip.load_binary("/tmp/test");
chip.print_first_16_bytes_of_ram();
let x: u8 = rand::random();
println!("{}", x);
let sdl_context = sdl2::init().unwrap()... | main | identifier_name |
main.rs | mod binary_parser;
mod chip8;
mod chip8_display;
extern crate rand;
extern crate sdl2;
use sdl2::pixels::Color;
use sdl2::event::Event;
use sdl2::keyboard::Keycode;
fn main() {
let mut dummy_display = chip8_display::DummyCHIP8Display::new();
let mut chip: chip8::CHIP8 = chip8::CHIP8::new(&mut dummy_display);
... | ,
_ => {}
}
}
// The rest of the game loop goes here...
}
}
| {
break 'running
} | conditional_block |
main.rs | mod binary_parser;
mod chip8;
mod chip8_display;
extern crate rand;
extern crate sdl2;
use sdl2::pixels::Color;
use sdl2::event::Event;
use sdl2::keyboard::Keycode;
fn main() | renderer.clear();
renderer.present();
let mut event_pump = sdl_context.event_pump().unwrap();
'running: loop {
for event in event_pump.poll_iter() {
match event {
Event::Quit {..} | Event::KeyDown { keycode: Some(Keycode::Escape),.. } => {
break ... | {
let mut dummy_display = chip8_display::DummyCHIP8Display::new();
let mut chip: chip8::CHIP8 = chip8::CHIP8::new(&mut dummy_display);
chip.load_binary("/tmp/test");
chip.print_first_16_bytes_of_ram();
let x: u8 = rand::random();
println!("{}", x);
let sdl_context = sdl2::init().unwrap();
... | identifier_body |
main.rs | mod binary_parser;
mod chip8;
mod chip8_display;
extern crate rand;
extern crate sdl2; | fn main() {
let mut dummy_display = chip8_display::DummyCHIP8Display::new();
let mut chip: chip8::CHIP8 = chip8::CHIP8::new(&mut dummy_display);
chip.load_binary("/tmp/test");
chip.print_first_16_bytes_of_ram();
let x: u8 = rand::random();
println!("{}", x);
let sdl_context = sdl2::init().u... |
use sdl2::pixels::Color;
use sdl2::event::Event;
use sdl2::keyboard::Keycode;
| random_line_split |
frontend.rs | use std::thread::JoinHandle;
use std::sync::mpsc::{self, Sender, Receiver};
use glium::glutin::Event;
use tungsten::{Frontend, EventDispatcher};
use runtime::FrontendRuntime;
use {Key, ElementState, MouseButton};
pub struct CloseRequestEvent;
pub struct KeyboardInputEvent {
pub key: Key,
pub state: ElementSta... | (&mut self, rect: Rectangle) {
self.rectangles.push(rect);
}
pub fn rectangles(&self) -> &Vec<Rectangle> {
&self.rectangles
}
}
pub struct GameCameraInfo {
position: [f32; 2],
layers: Vec<LayerInfo>,
}
impl GameCameraInfo {
pub fn position(&self) -> [f32; 2] {
self.pos... | rectangle | identifier_name |
frontend.rs | use std::thread::JoinHandle;
use std::sync::mpsc::{self, Sender, Receiver};
use glium::glutin::Event;
use tungsten::{Frontend, EventDispatcher};
use runtime::FrontendRuntime;
use {Key, ElementState, MouseButton};
pub struct CloseRequestEvent;
pub struct KeyboardInputEvent {
pub key: Key,
pub state: ElementSta... | pub fn raw(&self) -> u32 {
self.id
}
}
pub struct Rectangle {
pub position: [f32; 2],
pub size: [f32; 2],
pub texture: TextureId,
}
pub enum LayerInfo {
Camera(GameCameraInfo),
Batch(RenderBatchInfo),
}
pub trait RenderTarget {
fn game_camera(&mut self, position: [f32; 2]) -> ... | random_line_split | |
frontend.rs | use std::thread::JoinHandle;
use std::sync::mpsc::{self, Sender, Receiver};
use glium::glutin::Event;
use tungsten::{Frontend, EventDispatcher};
use runtime::FrontendRuntime;
use {Key, ElementState, MouseButton};
pub struct CloseRequestEvent;
pub struct KeyboardInputEvent {
pub key: Key,
pub state: ElementSta... |
}
pub struct Rectangle {
pub position: [f32; 2],
pub size: [f32; 2],
pub texture: TextureId,
}
pub enum LayerInfo {
Camera(GameCameraInfo),
Batch(RenderBatchInfo),
}
pub trait RenderTarget {
fn game_camera(&mut self, position: [f32; 2]) -> &mut GameCameraInfo;
fn batch(&mut self) -> &mut... | {
self.id
} | identifier_body |
frontend.rs | use std::thread::JoinHandle;
use std::sync::mpsc::{self, Sender, Receiver};
use glium::glutin::Event;
use tungsten::{Frontend, EventDispatcher};
use runtime::FrontendRuntime;
use {Key, ElementState, MouseButton};
pub struct CloseRequestEvent;
pub struct KeyboardInputEvent {
pub key: Key,
pub state: ElementSta... |
unreachable!();
}
fn layers(&self) -> &Vec<LayerInfo> {
&self.layers
}
}
pub struct FrameRenderInfo {
layers: Vec<LayerInfo>,
}
impl FrameRenderInfo {
fn new() -> Self {
FrameRenderInfo {
layers: Vec::new(),
}
}
fn clear(&mut self) {
s... | {
return batch;
} | conditional_block |
cmdopt.rs | //!
//! Command line Option
//!
use std::env;
#[derive(Clone)]
pub struct CmdOpt {
/// Dump debug information
pub debug : bool,
/// Dump GC profile information
pub gc_dump : bool,
/// Benchmark the program by repeating
pub bench : Option<usize>,
}
/// Default command line options
pub fn ... |
pub fn parse_opt() -> CmdOpt {
let mut i = 2;
let mut opt = default_cmdopt();
let nargs = env::args().count();
while i < nargs {
match env::args().nth(i) {
Some(ref opt_str) => {
if opt_str == "-debug" {
opt.debug = true;
} else... | {
CmdOpt {
debug : false,
gc_dump : false,
bench : None,
}
} | identifier_body |
cmdopt.rs | //!
//! Command line Option
//!
use std::env;
#[derive(Clone)]
pub struct CmdOpt {
/// Dump debug information
pub debug : bool,
/// Dump GC profile information
pub gc_dump : bool,
/// Benchmark the program by repeating
pub bench : Option<usize>,
}
/// Default command line options
pub fn ... | else if opt_str == "-bench" && i + 1 < nargs {
let s = env::args().nth(i + 1).unwrap();
opt.bench = Some(s.parse::<usize>().unwrap());
i = i + 1;
} else if opt_str == "-gc_dump" {
opt.gc_dump = true;
}
... | {
opt.debug = true;
} | conditional_block |
cmdopt.rs | //!
//! Command line Option
//!
use std::env;
#[derive(Clone)]
pub struct CmdOpt {
/// Dump debug information
pub debug : bool,
/// Dump GC profile information
pub gc_dump : bool,
/// Benchmark the program by repeating
pub bench : Option<usize>,
}
/// Default command line options
pub fn ... | let mut opt = default_cmdopt();
let nargs = env::args().count();
while i < nargs {
match env::args().nth(i) {
Some(ref opt_str) => {
if opt_str == "-debug" {
opt.debug = true;
} else if opt_str == "-bench" && i + 1 < nargs {
... | let mut i = 2; | random_line_split |
cmdopt.rs | //!
//! Command line Option
//!
use std::env;
#[derive(Clone)]
pub struct CmdOpt {
/// Dump debug information
pub debug : bool,
/// Dump GC profile information
pub gc_dump : bool,
/// Benchmark the program by repeating
pub bench : Option<usize>,
}
/// Default command line options
pub fn ... | () -> CmdOpt {
let mut i = 2;
let mut opt = default_cmdopt();
let nargs = env::args().count();
while i < nargs {
match env::args().nth(i) {
Some(ref opt_str) => {
if opt_str == "-debug" {
opt.debug = true;
} else if opt_str == "-b... | parse_opt | identifier_name |
context.rs |
// Copyright 2016 Pierre Talbot (IRCAM)
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed t... | (&self, expr_idx: usize) -> usize {
self.grammar[expr_idx].type_cardinality()
}
pub fn has_unit_type(&self, expr_idx: usize) -> bool {
self.grammar[expr_idx].ty == crate::middle::typing::ast::Type::Unit
}
pub fn open_scope(&mut self, expr_idx: usize) -> Scope {
let scope = self.save_scope();
s... | expr_cardinality | identifier_name |
context.rs |
// Copyright 2016 Pierre Talbot (IRCAM)
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed t... |
}
fn closure_params(&self) -> Vec<syn::FnArg> {
let stream_ty = self.grammar.stream_type();
vec![self.state_param(true)]
.into_iter()
.chain(self.mut_ref_free_variables
.iter().cloned()
.map(|(var, ty)| parse_quote!(#var: &mut #ty)))
.chain(self.free_variables
.iter()
... | {
continuation
} | conditional_block |
context.rs |
// Copyright 2016 Pierre Talbot (IRCAM)
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed t... |
pub fn compile(&mut self, compiler: ExprCompilerFn, idx: usize,
success: syn::Expr, failure: syn::Expr) -> syn::Expr
{
let compiler = compiler(&self.grammar, idx);
compiler.compile_expr(self, Continuation::new(success, failure))
}
pub fn compile_success(&mut self, compiler: ExprCompilerFn, idx: u... | {
let stream_ty = self.grammar.stream_type();
parse_quote!(oak_runtime::ParseState<#stream_ty, ()>)
} | identifier_body |
context.rs | // Copyright 2016 Pierre Talbot (IRCAM)
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to... | fn state_param(&self, state_mut: bool) -> syn::FnArg {
let mut_kw = if state_mut {
Some(quote!(mut))
} else {
None
};
let ps_ty = self.parse_state_ty();
parse_quote!(#mut_kw state: #ps_ty)
}
fn parse_state_ty(&self) -> syn::Type {
let stream_ty = self.grammar.stream_type();
... | )
}
| random_line_split |
camera.rs | //! A hardware agnostic wrapper for different camera backends
//!
//! By defalt the camera capture functionality is being implemented by
//! the rscam crate, using the V4L2 backend. Via this API it is however possible
//! to load other camera backends without changing other code functionality.
//!
//! In the future thi... |
}
/// A camera-backend overarching configuration setting
///
/// It describes capabilites such as resolutions, framerates
/// and if a camera can be put into "live view" mode.
pub struct CameraConfig {
pub id: String,
}
/// A hardware agnostic camera trait
pub trait Camera {
/// Tries to run the very lengthy... | {
use crate::CameraType::*;
write!(
f,
"{}",
match self {
Left => "left",
Right => "right",
}
)
} | identifier_body |
camera.rs | //! A hardware agnostic wrapper for different camera backends
//!
//! By defalt the camera capture functionality is being implemented by
//! the rscam crate, using the V4L2 backend. Via this API it is however possible
//! to load other camera backends without changing other code functionality.
//!
//! In the future thi... | {
/// When the camera target isn't known
ReceiverNotFound(String),
/// A general error occured when initialising a camera
FailedInitialisation(String),
/// Failed to capture a image
FailedToCapture,
/// Failed to initialise a live buffer for video or streaming
FailedToBurstCapture,
... | CameraError | identifier_name |
camera.rs | //! A hardware agnostic wrapper for different camera backends
//!
//! By defalt the camera capture functionality is being implemented by
//! the rscam crate, using the V4L2 backend. Via this API it is however possible
//! to load other camera backends without changing other code functionality.
//!
//! In the future thi... | fn capture_video(&self, fps: u32, time: u32) -> Result<(), CameraError>;
/// Initialise the liveview stream with a specific framerate
fn start_liveview(&self, fps: u32) -> Result<(), CameraError>;
/// Stop liveview stream
fn stop_liveview(&self) -> Result<(), CameraError>;
/// Get a data frag... | random_line_split | |
workcache.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... | discovered_inputs: &WorkMap,
discovered_outputs: &WorkMap,
result: &T) {
let k = json_encode(&(fn_name, declared_inputs));
let v = json_encode(&(discovered_inputs,
discovered_outputs,
result));... | fn_name: &str,
declared_inputs: &WorkMap, | random_line_split |
workcache.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... | {
kind: ~str,
name: ~str
}
impl WorkKey {
pub fn new(kind: &str, name: &str) -> WorkKey {
WorkKey {
kind: kind.to_owned(),
name: name.to_owned(),
}
}
}
// FIXME #8883: The key should be a WorkKey and not a ~str.
// This is working around some JSON weirdness.
#[... | WorkKey | identifier_name |
dapps.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... | {
/// The light client.
pub client: Arc<LightClient>,
/// Handle to the on-demand service.
pub on_demand: Arc<OnDemand>,
/// Handle to the light network service.
pub sync: Arc<LightSync>,
}
impl ContractClient for LightRegistrar {
fn registrar(&self) -> Result<Address, String> {
self.client.engine().addition... | LightRegistrar | identifier_name |
dapps.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... |
}
/// Registrar implementation for the light client.
pub struct LightRegistrar {
/// The light client.
pub client: Arc<LightClient>,
/// Handle to the on-demand service.
pub on_demand: Arc<OnDemand>,
/// Handle to the light network service.
pub sync: Arc<LightSync>,
}
impl ContractClient for LightRegistrar {
... | {
self.client.call_contract(BlockId::Latest, address, data)
.into_future()
.boxed()
} | identifier_body |
dapps.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... | endpoints: m.endpoints()
}) as Arc<rpc_apis::DappsService>)
}
pub struct DappsServiceWrapper {
endpoints: parity_dapps::Endpoints,
}
impl rpc_apis::DappsService for DappsServiceWrapper {
fn list_dapps(&self) -> Vec<rpc_apis::LocalDapp> {
self.endpoints.list()
.into_iter()
.map(|app| rpc_apis::... | }
pub fn service(middleware: &Option<Middleware>) -> Option<Arc<rpc_apis::DappsService>> {
middleware.as_ref().map(|m| Arc::new(DappsServiceWrapper { | random_line_split |
dapps.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... |
server::ui_middleware(
deps,
rpc::DAPPS_DOMAIN.into(),
).map(Some)
}
pub use self::server::{SyncStatus, Middleware, service};
#[cfg(not(feature = "dapps"))]
mod server {
use super::Dependencies;
use std::sync::Arc;
use std::path::PathBuf;
use parity_rpc::{hyper, RequestMiddleware, RequestMiddlewareAction}... | {
return Ok(None);
} | conditional_block |
mod.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... | //! in various ways.
//!
//! Plugin authors will use the `Registry` type re-exported by
//! this module, along with its methods. The rest of the module
//! is for use by `rustc` itself.
//!
//! To define a plugin, build a dylib crate with a
//! `#[plugin_registrar]` function:
//!
//! ```rust,ignore
//! #![crate_name =... | //! Infrastructure for compiler plugins.
//!
//! Plugins are Rust libraries which extend the behavior of `rustc` | random_line_split |
bind-by-move-neither-can-live-while-the-other-survives-3.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 ... | } | } | random_line_split |
bind-by-move-neither-can-live-while-the-other-survives-3.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 ... | , //~ ERROR cannot bind by-move and by-ref in the same pattern
none2 => fail!()
}
}
| { } | conditional_block |
bind-by-move-neither-can-live-while-the-other-survives-3.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 ... | (&mut self) {
println!("destructor runs");
}
}
enum double_option<T,U> { some2(T,U), none2 }
fn main() {
let x = some2(X { x: () }, X { x: () });
match x {
some2(ref _y, _z) => { }, //~ ERROR cannot bind by-move and by-ref in the same pattern
none2 => fail!()
}
}
| drop | identifier_name |
trait-default-method-xc.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 g<T, U, V: B<T>>(i: V, j: T, k: U) -> (T, U) {
i.thing(j, k)
}
fn eq<T: TestEquality>(lhs: &T, rhs: &T) -> bool {
lhs.test_eq(rhs)
}
fn neq<T: TestEquality>(lhs: &T, rhs: &T) -> bool {
lhs.test_neq(rhs)
}
impl TestEquality for stuff::thing {
fn test_eq(&self, rhs: &stuff::thing) -> bool {
... | { 10 } | identifier_body |
trait-default-method-xc.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 ... | }
}
pub fn main() {
// Some tests of random things
f(0);
assert_eq!(A::lurr(&0, &1), 21);
let a = stuff::thing { x: 0 };
let b = stuff::thing { x: 1 };
let c = Something { x: 1 };
assert_eq!(0.g(), 10);
assert_eq!(a.g(), 10);
assert_eq!(a.h(), 11);
assert_eq!(c.h(), 11);... |
impl TestEquality for stuff::thing {
fn test_eq(&self, rhs: &stuff::thing) -> bool {
//self.x.test_eq(&rhs.x)
eq(&self.x, &rhs.x) | random_line_split |
trait-default-method-xc.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 ... | <T>(i: int, _x: &T) -> int {
i.g()
}
mod stuff {
pub struct thing { pub x: int }
}
impl A for stuff::thing {
fn f(&self) -> int { 10 }
}
fn g<T, U, V: B<T>>(i: V, j: T, k: U) -> (T, U) {
i.thing(j, k)
}
fn eq<T: TestEquality>(lhs: &T, rhs: &T) -> bool {
lhs.test_eq(rhs)
}
fn neq<T: TestEquality>... | welp | identifier_name |
mod.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/. */
//! Computed values.
use app_units::Au;
use euclid::size::Size2D;
use font_metrics::FontMetricsProvider;
use prop... | (pub Size2D<LengthOrPercentage>);
impl BorderRadiusSize {
#[allow(missing_docs)]
pub fn zero() -> BorderRadiusSize {
BorderRadiusSize(Size2D::new(LengthOrPercentage::Length(Au(0)), LengthOrPercentage::Length(Au(0))))
}
}
impl ToComputedValue for specified::BorderRadiusSize {
type ComputedValue... | BorderRadiusSize | identifier_name |
mod.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/. */
//! Computed values.
use app_units::Au;
use euclid::size::Size2D;
use font_metrics::FontMetricsProvider;
use prop... |
}
#[cfg(feature = "gecko")]
impl ComputedValueAsSpecified for specified::AlignJustifyContent {}
impl ComputedValueAsSpecified for specified::BorderStyle {}
#[derive(Debug, PartialEq, Clone, Copy)]
#[cfg_attr(feature = "servo", derive(HeapSizeOf))]
#[allow(missing_docs)]
pub struct BorderRadiusSize(pub Size2D<LengthO... | {
specified::CSSColor {
parsed: *computed,
authored: None,
}
} | identifier_body |
mod.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/. */
//! Computed values.
use app_units::Au;
use euclid::size::Size2D;
use font_metrics::FontMetricsProvider;
use prop... | impl ToComputedValue for specified::CSSColor {
type ComputedValue = CSSColor;
#[inline]
fn to_computed_value(&self, _context: &Context) -> CSSColor {
self.parsed
}
#[inline]
fn from_computed_value(computed: &CSSColor) -> Self {
specified::CSSColor {
parsed: *compute... | random_line_split | |
comments.rs | // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MI... |
}
pub fn strip_doc_comment_decoration(comment: &str) -> String {
/// remove whitespace-only lines from the start/end of lines
fn vertical_trim(lines: Vec<String> ) -> Vec<String> {
let mut i = 0u;
let mut j = lines.len();
// first line of all-stars should be omitted
if lines.le... | {
ast::AttrOuter
} | conditional_block |
comments.rs | // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MI... | (rdr: &mut StringReader,
code_to_the_left: bool,
comments: &mut Vec<Comment> ) {
debug!(">>> block comment");
let p = rdr.last_pos;
let mut lines: Vec<String> = Vec::new();
let col = rdr.col;
rdr.bump();
rdr.bump();
let mut curr_line = String::fro... | read_block_comment | identifier_name |
comments.rs | // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MI... |
pub fn doc_comment_style(comment: &str) -> ast::AttrStyle {
assert!(is_doc_comment(comment));
if comment.starts_with("//!") || comment.starts_with("/*!") {
ast::AttrInner
} else {
ast::AttrOuter
}
}
pub fn strip_doc_comment_decoration(comment: &str) -> String {
/// remove whitespa... | {
(s.starts_with("///") && super::is_doc_comment(s)) ||
s.starts_with("//!") ||
(s.starts_with("/**") && is_block_doc_comment(s)) ||
s.starts_with("/*!")
} | identifier_body |
comments.rs | // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MI... | break;
}
}
if i > line.len() {
can_trim = false;
}
if!can_trim {
break;
}
}
if can_trim {
lines.iter().map(|line| {
line.slice(i + 1, line.len()).t... | } | random_line_split |
replaced.rs | use core::{Dependency, Package, PackageId, Source, SourceId, Summary};
use util::errors::{CargoResult, CargoResultExt};
pub struct ReplacedSource<'cfg> {
to_replace: SourceId,
replace_with: SourceId,
inner: Box<Source + 'cfg>,
}
impl<'cfg> ReplacedSource<'cfg> {
pub fn new(
to_replace: &Source... | (&self) -> &SourceId {
&self.to_replace
}
fn update(&mut self) -> CargoResult<()> {
self.inner
.update()
.chain_err(|| format!("failed to update replaced source {}", self.to_replace))?;
Ok(())
}
fn download(&mut self, id: &PackageId) -> CargoResult<Package... | source_id | identifier_name |
replaced.rs | use core::{Dependency, Package, PackageId, Source, SourceId, Summary};
use util::errors::{CargoResult, CargoResultExt};
pub struct ReplacedSource<'cfg> {
to_replace: SourceId, | impl<'cfg> ReplacedSource<'cfg> {
pub fn new(
to_replace: &SourceId,
replace_with: &SourceId,
src: Box<Source + 'cfg>,
) -> ReplacedSource<'cfg> {
ReplacedSource {
to_replace: to_replace.clone(),
replace_with: replace_with.clone(),
inner: src,
... | replace_with: SourceId,
inner: Box<Source + 'cfg>,
}
| random_line_split |
replaced.rs | use core::{Dependency, Package, PackageId, Source, SourceId, Summary};
use util::errors::{CargoResult, CargoResultExt};
pub struct ReplacedSource<'cfg> {
to_replace: SourceId,
replace_with: SourceId,
inner: Box<Source + 'cfg>,
}
impl<'cfg> ReplacedSource<'cfg> {
pub fn new(
to_replace: &Source... |
fn supports_checksums(&self) -> bool {
self.inner.supports_checksums()
}
fn requires_precise(&self) -> bool {
self.inner.requires_precise()
}
fn source_id(&self) -> &SourceId {
&self.to_replace
}
fn update(&mut self) -> CargoResult<()> {
self.inner
... | {
let (replace_with, to_replace) = (&self.replace_with, &self.to_replace);
let dep = dep.clone().map_source(to_replace, replace_with);
self.inner
.query(
&dep,
&mut |summary| f(summary.map_source(replace_with, to_replace)),
)
.... | identifier_body |
error.rs | /// Definition of Tantivy's error and result.
use std::io;
use std::path::PathBuf;
use std::error;
use std::sync::PoisonError;
use directory::error::{OpenReadError, OpenWriteError, OpenDirectoryError};
use query;
use schema;
use fastfield::FastFieldNotAvailableError;
use serde_json;
/// Generic tantivy error.
///
/... |
}
impl From<io::Error> for Error {
fn from(io_error: io::Error) -> Error {
Error::IOError(io_error)
}
}
impl From<query::QueryParserError> for Error {
fn from(parsing_error: query::QueryParserError) -> Error {
Error::InvalidArgument(format!("Query is invalid. {:?}", parsing_error))
}
... | {
Error::FastFieldError(fastfield_error)
} | identifier_body |
error.rs | /// Definition of Tantivy's error and result.
use std::io;
use std::path::PathBuf;
use std::error;
use std::sync::PoisonError;
use directory::error::{OpenReadError, OpenWriteError, OpenDirectoryError};
use query;
use schema;
use fastfield::FastFieldNotAvailableError;
use serde_json;
| #[derive(Debug)]
pub enum Error {
/// Path does not exist.
PathDoesNotExist(PathBuf),
/// File already exists, this is a problem when we try to write into a new file.
FileAlreadyExists(PathBuf),
/// IO Error
IOError(io::Error),
/// A thread holding the locked panicked and poisoned the lock.
... |
/// Generic tantivy error.
///
/// Any specialized error return in tantivy can be converted in `tantivy::Error`. | random_line_split |
error.rs | /// Definition of Tantivy's error and result.
use std::io;
use std::path::PathBuf;
use std::error;
use std::sync::PoisonError;
use directory::error::{OpenReadError, OpenWriteError, OpenDirectoryError};
use query;
use schema;
use fastfield::FastFieldNotAvailableError;
use serde_json;
/// Generic tantivy error.
///
/... | (error: serde_json::Error) -> Error {
Error::IOError(error.into())
}
}
| from | identifier_name |
mod.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 ... | ErrorKind::WouldBlock,
_ => ErrorKind::Other,
}
}
pub fn cvt<T: One + PartialEq + Neg<Output=T>>(t: T) -> io::Result<T> {
let one: T = T::one();
if t == -one {
Err(io::Error::last_os_error())
} else {
Ok(t)
}
}
#[allow(deprecated)]
pub fn cvt_r<T, F>(mut f: F)... | {
match errno as libc::c_int {
libc::ECONNREFUSED => ErrorKind::ConnectionRefused,
libc::ECONNRESET => ErrorKind::ConnectionReset,
libc::EPERM | libc::EACCES => ErrorKind::PermissionDenied,
libc::EPIPE => ErrorKind::BrokenPipe,
libc::ENOTCONN => ErrorKind::NotConnected,
... | identifier_body |
mod.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 ... | (errno: i32) -> ErrorKind {
match errno as libc::c_int {
libc::ECONNREFUSED => ErrorKind::ConnectionRefused,
libc::ECONNRESET => ErrorKind::ConnectionReset,
libc::EPERM | libc::EACCES => ErrorKind::PermissionDenied,
libc::EPIPE => ErrorKind::BrokenPipe,
libc::ENOTCONN => Erro... | decode_error_kind | identifier_name |
mod.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 ... | loop {
match cvt(f()) {
Err(ref e) if e.kind() == ErrorKind::Interrupted => {}
other => return other,
}
}
}
pub fn ms_to_timeval(ms: u64) -> libc::timeval {
libc::timeval {
tv_sec: (ms / 1000) as libc::time_t,
tv_usec: ((ms % 1000) * 1000) as libc::su... |
#[allow(deprecated)]
pub fn cvt_r<T, F>(mut f: F) -> io::Result<T>
where T: One + PartialEq + Neg<Output=T>, F: FnMut() -> T
{ | random_line_split |
tests.rs | use libc;
// use std::mem;
// use std::ptr;
use std::ffi::CString;
use super::*;
#[test]
fn test_read_objid() |
// #[test]
// fn test_snmp_session() {
// init(b"test");
// let peer_name = CString::new("edgy.asdf.dk").unwrap().into_raw();
// let peer_community = b"st0vsuger";
// let peer_obj = CString::new("SNMPv2-MIB::sysDescr.0").unwrap().into_raw();
// unsafe {
// let mut sess: Struct_snmp_sessio... | {
init(b"test");
unsafe {
let input = CString::new("1.3.6").unwrap();
let mut objid: [oid; 256] = [0; 256];
let mut objid_size: libc::size_t = objid.len() as libc::size_t;
let res = read_objid(input.as_ptr(), &mut objid[0], &mut objid_size);
let expected: &[oid] = &[1,3... | identifier_body |
tests.rs | use libc;
// use std::mem;
// use std::ptr;
use std::ffi::CString;
use super::*;
#[test]
fn test_read_objid() {
init(b"test");
unsafe {
let input = CString::new("1.3.6").unwrap();
let mut objid: [oid; 256] = [0; 256];
let mut objid_size: libc::size_t = objid.len() as libc::size_t;
... | // let peer_name = CString::new("edgy.asdf.dk").unwrap().into_raw();
// let peer_community = b"st0vsuger";
// let peer_obj = CString::new("SNMPv2-MIB::sysDescr.0").unwrap().into_raw();
// unsafe {
// let mut sess: Struct_snmp_session = mem::uninitialized();
// let pdu: *mut Struct_snmp_... | // #[test]
// fn test_snmp_session() {
// init(b"test"); | random_line_split |
tests.rs | use libc;
// use std::mem;
// use std::ptr;
use std::ffi::CString;
use super::*;
#[test]
fn | () {
init(b"test");
unsafe {
let input = CString::new("1.3.6").unwrap();
let mut objid: [oid; 256] = [0; 256];
let mut objid_size: libc::size_t = objid.len() as libc::size_t;
let res = read_objid(input.as_ptr(), &mut objid[0], &mut objid_size);
let expected: &[oid] = &[... | test_read_objid | identifier_name |
value.rs | use path::Path;
use std::fmt;
#[derive(Debug, Clone, PartialEq)]
pub enum Value {
Int(i32),
Float(f32),
//List,
String(String),
DivertTarget(Path),
VariablePointer(String, i32)
}
impl Value {
pub fn as_int(&self) -> Option<i32> { | _ => None
}
}
pub fn as_float(&self) -> Option<f32> {
match self {
&Value::Float(value) => Some(value),
_ => None
}
}
pub fn as_string(&self) -> Option<&str> {
match self {
&Value::String(ref value) => Some(value),
... | match self {
&Value::Int(value) => Some(value), | random_line_split |
value.rs | use path::Path;
use std::fmt;
#[derive(Debug, Clone, PartialEq)]
pub enum Value {
Int(i32),
Float(f32),
//List,
String(String),
DivertTarget(Path),
VariablePointer(String, i32)
}
impl Value {
pub fn as_int(&self) -> Option<i32> {
match self {
&Value::Int(value) => Some... | (&self) -> Option<f32> {
match self {
&Value::Float(value) => Some(value),
_ => None
}
}
pub fn as_string(&self) -> Option<&str> {
match self {
&Value::String(ref value) => Some(value),
_ => None
}
}
}
impl fmt::Display for Va... | as_float | identifier_name |
value.rs | use path::Path;
use std::fmt;
#[derive(Debug, Clone, PartialEq)]
pub enum Value {
Int(i32),
Float(f32),
//List,
String(String),
DivertTarget(Path),
VariablePointer(String, i32)
}
impl Value {
pub fn as_int(&self) -> Option<i32> {
match self {
&Value::Int(value) => Some... |
} | {
match self {
&Value::Int(value) => write!(f, "{}", value),
&Value::Float(value) => write!(f, "{}", value),
&Value::String(ref value) => write!(f, "{}", value),
&Value::DivertTarget(ref value) => write!(f, "DivertTarget({})", value.to_string()),
&Valu... | identifier_body |
read_write.rs | extern crate serial;
use std::env;
use std::time::Duration;
use std::io::prelude::*;
use serial::prelude::*;
const SETTINGS: serial::PortSettings = serial::PortSettings {
baud_rate: serial::Baud9600,
char_size: serial::Bits8,
parity: serial::ParityNone,
stop_bits: serial::Stop1,
fl... | }
}
fn interact<T: SerialPort>(port: &mut T) -> serial::Result<()> {
try!(port.configure(&SETTINGS));
try!(port.set_timeout(Duration::from_secs(1)));
let mut buf: Vec<u8> = (0..255).collect();
println!("writing bytes");
try!(port.write(&buf[..]));
println!("reading bytes");
try!(port... | println!("opening port: {:?}", arg);
let mut port = serial::open(&arg).unwrap();
interact(&mut port).unwrap(); | random_line_split |
read_write.rs | extern crate serial;
use std::env;
use std::time::Duration;
use std::io::prelude::*;
use serial::prelude::*;
const SETTINGS: serial::PortSettings = serial::PortSettings {
baud_rate: serial::Baud9600,
char_size: serial::Bits8,
parity: serial::ParityNone,
stop_bits: serial::Stop1,
fl... | <T: SerialPort>(port: &mut T) -> serial::Result<()> {
try!(port.configure(&SETTINGS));
try!(port.set_timeout(Duration::from_secs(1)));
let mut buf: Vec<u8> = (0..255).collect();
println!("writing bytes");
try!(port.write(&buf[..]));
println!("reading bytes");
try!(port.read(&mut buf[..]))... | interact | identifier_name |
read_write.rs | extern crate serial;
use std::env;
use std::time::Duration;
use std::io::prelude::*;
use serial::prelude::*;
const SETTINGS: serial::PortSettings = serial::PortSettings {
baud_rate: serial::Baud9600,
char_size: serial::Bits8,
parity: serial::ParityNone,
stop_bits: serial::Stop1,
fl... | {
try!(port.configure(&SETTINGS));
try!(port.set_timeout(Duration::from_secs(1)));
let mut buf: Vec<u8> = (0..255).collect();
println!("writing bytes");
try!(port.write(&buf[..]));
println!("reading bytes");
try!(port.read(&mut buf[..]));
Ok(())
} | identifier_body | |
server.rs | use grain_capnp::{powerbox_capability, ui_view, ui_session};
use web_session_capnp::{web_session};
use std::collections::hash_map::HashMap;
use capnp_rpc::rpc::{RpcConnectionState};
use capnp_rpc::capability::{LocalClient};
use sqlite3;
#[derive(Clone, Copy)]
pub struct UiViewImpl;
impl powerbox_capability::Server ... | };
match query_map.get(&"definition".to_string()) {
None => {
let def_div = try!(self.get_def(&word));
return Ok(PageData::WordAndDef(word, def_div, None));
}
Some(def_query) => {
let de... | {
if path.len() == 1 && path[0] == "define" {
let mut query_map = HashMap::<String, String>::new();
match query {
None => {}
Some(q) => {
for &(ref k, ref v) in ::url::form_urlencoded::parse(q.as_bytes()).iter() {
... | identifier_body |
server.rs | use grain_capnp::{powerbox_capability, ui_view, ui_session};
use web_session_capnp::{web_session};
use std::collections::hash_map::HashMap;
use capnp_rpc::rpc::{RpcConnectionState};
use capnp_rpc::capability::{LocalClient};
use sqlite3;
#[derive(Clone, Copy)]
pub struct UiViewImpl;
impl powerbox_capability::Server ... | return Ok(false);
}
idx += 1;
}
return Ok(true);
}
fn write_def(&mut self, word : &str, definition : &[&str]) -> sqlite3::SqliteResult<()> {
let time : i64 = ::time::get_time().sec;
let mut query = String::new();
query.push_str(... | if definition.len() != word.len() { return Ok(false); }
let mut idx = 0;
for &d in definition.iter() {
if !(try!(self.is_word(d)) && d.len() > 0 && d.as_bytes()[0] == word.as_bytes()[idx]) { | random_line_split |
server.rs | use grain_capnp::{powerbox_capability, ui_view, ui_session};
use web_session_capnp::{web_session};
use std::collections::hash_map::HashMap;
use capnp_rpc::rpc::{RpcConnectionState};
use capnp_rpc::capability::{LocalClient};
use sqlite3;
#[derive(Clone, Copy)]
pub struct UiViewImpl;
impl powerbox_capability::Server ... |
Some(def_query) => {
let definition : Vec<&str> = def_query.split(' ').collect();
if try!(self.validate_def(&word, &definition)) {
try!(self.write_def(&word, &definition));
let def_div = try!(self.get_def(&word))... | {
let def_div = try!(self.get_def(&word));
return Ok(PageData::WordAndDef(word, def_div, None));
} | conditional_block |
server.rs | use grain_capnp::{powerbox_capability, ui_view, ui_session};
use web_session_capnp::{web_session};
use std::collections::hash_map::HashMap;
use capnp_rpc::rpc::{RpcConnectionState};
use capnp_rpc::capability::{LocalClient};
use sqlite3;
#[derive(Clone, Copy)]
pub struct UiViewImpl;
impl powerbox_capability::Server ... | {
Error(String),
WordAndDef(String, String, Option<String>),
HomePage(isize, isize, Vec<String>),
}
fn construct_html(page_data : PageData) -> String {
let mut result = String::new();
result.push_str(&format!("<html>{}<body>", HEADER));
const HOME_LINK : &'static str = "<a href=\"/\">home</a>... | PageData | identifier_name |
ratelimit.rs | use std;
use std::collections::BTreeMap;
use std::sync::Mutex;
use chrono::prelude::*;
use hyper;
use {Error, Result};
#[derive(Default)]
pub struct RateLimits {
global: Mutex<RateLimit>,
endpoints: Mutex<BTreeMap<String, RateLimit>>,
}
impl RateLimits {
/// Check before issuing a request for the given URL.
pub... | .post_update(response)
}
}
}
#[derive(Default)]
struct RateLimit {
reset: i64,
limit: i64,
remaining: i64,
}
impl RateLimit {
fn pre_check(&mut self) {
// break out if uninitialized
if self.limit == 0 {
return;
}
let difference = self.reset - Utc::now().timestamp();
if difference < 0 {
// ... | .lock()
.expect("Rate limits poisoned")
.entry(url.to_owned())
.or_insert_with(RateLimit::default) | random_line_split |
ratelimit.rs | use std;
use std::collections::BTreeMap;
use std::sync::Mutex;
use chrono::prelude::*;
use hyper;
use {Error, Result};
#[derive(Default)]
pub struct RateLimits {
global: Mutex<RateLimit>,
endpoints: Mutex<BTreeMap<String, RateLimit>>,
}
impl RateLimits {
/// Check before issuing a request for the given URL.
pub... |
}
}
#[derive(Default)]
struct RateLimit {
reset: i64,
limit: i64,
remaining: i64,
}
impl RateLimit {
fn pre_check(&mut self) {
// break out if uninitialized
if self.limit == 0 {
return;
}
let difference = self.reset - Utc::now().timestamp();
if difference < 0 {
// If reset is apparently in the ... | {
self.endpoints
.lock()
.expect("Rate limits poisoned")
.entry(url.to_owned())
.or_insert_with(RateLimit::default)
.post_update(response)
} | conditional_block |
ratelimit.rs | use std;
use std::collections::BTreeMap;
use std::sync::Mutex;
use chrono::prelude::*;
use hyper;
use {Error, Result};
#[derive(Default)]
pub struct RateLimits {
global: Mutex<RateLimit>,
endpoints: Mutex<BTreeMap<String, RateLimit>>,
}
impl RateLimits {
/// Check before issuing a request for the given URL.
pub... | (&mut self, response: &hyper::client::Response) -> bool {
match self.try_post_update(response) {
Err(e) => {
error!("rate limit checking error: {}", e);
false
}
Ok(r) => r,
}
}
fn try_post_update(&mut self, response: &hyper::client::Response) -> Result<bool> {
if let Some(reset) = read_header(... | post_update | identifier_name |
unmute.rs | use async_trait::async_trait;
use serenity::builder::CreateApplicationCommand;
use serenity::client::Context;
use serenity::model::interactions::application_command::{
ApplicationCommandInteraction, ApplicationCommandInteractionData, ApplicationCommandOptionType,
};
use crate::config::Config;
use crate::discord::s... | ;
Ok(UnmuteCommandOptions { target_user })
}
fn is_authorized(permissions: Permissions) -> bool {
permissions.administrator() || permissions.manage_roles()
}
#[async_trait]
impl SlashCommand for UnmuteCommand {
fn command_name(&self) -> &'static str {
"unmute"
}
fn create_command<'a>(
... | {
return Err(MissingOption);
} | conditional_block |
unmute.rs | use async_trait::async_trait;
use serenity::builder::CreateApplicationCommand;
use serenity::client::Context;
use serenity::model::interactions::application_command::{
ApplicationCommandInteraction, ApplicationCommandInteractionData, ApplicationCommandOptionType,
};
use crate::config::Config;
use crate::discord::s... | .required(true)
})
}
async fn handle_command(
&self,
context: &Context,
interaction: &ApplicationCommandInteraction,
_config: &Config,
services: &TypeMap,
) -> anyhow::Result<()> {
let GuildSlashCommandInteraction {
... | .create_option(|option| {
option
.name("user")
.description("target user to unmute")
.kind(ApplicationCommandOptionType::User) | random_line_split |
unmute.rs | use async_trait::async_trait;
use serenity::builder::CreateApplicationCommand;
use serenity::client::Context;
use serenity::model::interactions::application_command::{
ApplicationCommandInteraction, ApplicationCommandInteractionData, ApplicationCommandOptionType,
};
use crate::config::Config;
use crate::discord::s... | ;
struct UnmuteCommandOptions<'a> {
target_user: &'a User,
}
enum UnmuteCommandOptionFailure {
MissingOption,
}
fn generate_options(
data: &ApplicationCommandInteractionData,
) -> Result<UnmuteCommandOptions, UnmuteCommandOptionFailure> {
let target_user = if let Some((user, _)) = data.user("user") {... | UnmuteCommand | identifier_name |
unmute.rs | use async_trait::async_trait;
use serenity::builder::CreateApplicationCommand;
use serenity::client::Context;
use serenity::model::interactions::application_command::{
ApplicationCommandInteraction, ApplicationCommandInteractionData, ApplicationCommandOptionType,
};
use crate::config::Config;
use crate::discord::s... |
fn create_command<'a>(
&self,
command: &'a mut CreateApplicationCommand,
) -> &'a mut CreateApplicationCommand {
command
.name("unmute")
.description("unmutes given user")
.default_permission(true)
.create_option(|option| {
op... | {
"unmute"
} | identifier_body |
as_conversions.rs | use clippy_utils::diagnostics::span_lint_and_help;
use rustc_ast::ast::{Expr, ExprKind};
use rustc_lint::{EarlyContext, EarlyLintPass};
use rustc_middle::lint::in_external_macro;
use rustc_session::{declare_lint_pass, declare_tool_lint};
declare_clippy_lint! {
/// ### What it does
/// Checks for usage of `as` ... | (&mut self, cx: &EarlyContext<'_>, expr: &Expr) {
if in_external_macro(cx.sess, expr.span) {
return;
}
if let ExprKind::Cast(_, _) = expr.kind {
span_lint_and_help(
cx,
AS_CONVERSIONS,
expr.span,
"using a po... | check_expr | identifier_name |
as_conversions.rs | use clippy_utils::diagnostics::span_lint_and_help;
use rustc_ast::ast::{Expr, ExprKind};
use rustc_lint::{EarlyContext, EarlyLintPass};
use rustc_middle::lint::in_external_macro;
use rustc_session::{declare_lint_pass, declare_tool_lint};
declare_clippy_lint! {
/// ### What it does
/// Checks for usage of `as` ... |
}
| {
if in_external_macro(cx.sess, expr.span) {
return;
}
if let ExprKind::Cast(_, _) = expr.kind {
span_lint_and_help(
cx,
AS_CONVERSIONS,
expr.span,
"using a potentially dangerous silent `as` conversion",
... | identifier_body |
as_conversions.rs | use clippy_utils::diagnostics::span_lint_and_help;
use rustc_ast::ast::{Expr, ExprKind};
use rustc_lint::{EarlyContext, EarlyLintPass};
use rustc_middle::lint::in_external_macro;
use rustc_session::{declare_lint_pass, declare_tool_lint};
declare_clippy_lint! {
/// ### What it does
/// Checks for usage of `as` ... | );
}
}
} | "consider using a safe wrapper for this conversion", | random_line_split |
as_conversions.rs | use clippy_utils::diagnostics::span_lint_and_help;
use rustc_ast::ast::{Expr, ExprKind};
use rustc_lint::{EarlyContext, EarlyLintPass};
use rustc_middle::lint::in_external_macro;
use rustc_session::{declare_lint_pass, declare_tool_lint};
declare_clippy_lint! {
/// ### What it does
/// Checks for usage of `as` ... |
}
}
| {
span_lint_and_help(
cx,
AS_CONVERSIONS,
expr.span,
"using a potentially dangerous silent `as` conversion",
None,
"consider using a safe wrapper for this conversion",
);
} | conditional_block |
iron.rs | //! Exposes the `Iron` type, the main entrance point of the
//! `Iron` library.
use std::net::{ToSocketAddrs, SocketAddr};
use std::path::PathBuf;
pub use hyper::server::Listening;
use hyper::server::Server;
use hyper::net::Fresh;
use request::HttpRequest;
use response::HttpResponse;
use error::HttpResult;
use {Re... | self.listen_with(addr, 2 * ::num_cpus::get(),
Protocol::Https { certificate: certificate, key: key })
}
/// Kick off the server process with X threads.
///
/// ## Panics
///
/// Panics if the provided address does not parse. To avoid this
/// call `to_socket... | /// call `to_socket_addrs` yourself and pass a parsed `SocketAddr`.
pub fn https<A: ToSocketAddrs>(self, addr: A, certificate: PathBuf, key: PathBuf)
-> HttpResult<Listening> { | random_line_split |
iron.rs | //! Exposes the `Iron` type, the main entrance point of the
//! `Iron` library.
use std::net::{ToSocketAddrs, SocketAddr};
use std::path::PathBuf;
pub use hyper::server::Listening;
use hyper::server::Server;
use hyper::net::Fresh;
use request::HttpRequest;
use response::HttpResponse;
use error::HttpResult;
use {Re... | (&self, mut http_res: HttpResponse<Fresh>) {
*http_res.status_mut() = status::BadRequest;
let http_res = match http_res.start() {
Ok(res) => res,
// Would like this to work, but if not *shrug*
Err(_) => return,
};
// We would like this to work, but c... | bad_request | identifier_name |
iron.rs | //! Exposes the `Iron` type, the main entrance point of the
//! `Iron` library.
use std::net::{ToSocketAddrs, SocketAddr};
use std::path::PathBuf;
pub use hyper::server::Listening;
use hyper::server::Server;
use hyper::net::Fresh;
use request::HttpRequest;
use response::HttpResponse;
use error::HttpResult;
use {Re... |
/// Kick off the server process with X threads.
///
/// ## Panics
///
/// Panics if the provided address does not parse. To avoid this
/// call `to_socket_addrs` yourself and pass a parsed `SocketAddr`.
pub fn listen_with<A: ToSocketAddrs>(mut self, addr: A, threads: usize,
... | {
self.listen_with(addr, 2 * ::num_cpus::get(),
Protocol::Https { certificate: certificate, key: key })
} | identifier_body |
algorithms.rs | //! Algorithms that back up the Sortable and Sorted traits
use std;
use itertools::Itertools;
fn choose_pivot<T : Ord>(slice : &[T]) -> usize {
// if slice.len() <= 2 {return slice.len() - 1;};
let (mut ismall, imid, mut ibig) = (0, slice.len() / 2, slice.len() - 1);
if slice[ibig] < slice[ismall] {std::mem::swap(... |
#[test]
fn test_mergesort(){
let mut test_slices = get_test_vecs();
for test_vec in test_slices.iter_mut(){
let test_slice = test_vec.as_mut();
let v = mergesort(test_slice);
assert!(is_sorted(v.as_ref()));
}
}
#[test]
fn test_selectionsort(){
let mut test_slices = get_test_vecs();
for test_vec in tes... | {
let mut test_slices = get_test_vecs();
for test_vec in test_slices.iter_mut(){
let test_slice = test_vec.as_mut();
println!("Unsorted: {:?}", test_slice);
quicksort(test_slice);
println!("Sorted: {:?}", test_slice);
assert!(is_sorted(test_slice));
}
} | identifier_body |
algorithms.rs | //! Algorithms that back up the Sortable and Sorted traits
use std;
use itertools::Itertools;
fn choose_pivot<T : Ord>(slice : &[T]) -> usize {
// if slice.len() <= 2 {return slice.len() - 1;};
let (mut ismall, imid, mut ibig) = (0, slice.len() / 2, slice.len() - 1);
if slice[ibig] < slice[ismall] {std::mem::swap(... | (){
assert_eq!(get_parent(1), 0);
assert_eq!(get_parent(2), 0);
assert_eq!(get_parent(3), 1);
assert_eq!(get_parent(4), 1);
assert_eq!(get_parent(5), 2);
assert_eq!(get_parent(6), 2);
assert_eq!(get_parent(7), 3);
for i in 0usize..21usize {
let (l, r) = get_leaves(i);
assert_eq!(get_parent(l), i);
assert... | test_indexing | identifier_name |
algorithms.rs | //! Algorithms that back up the Sortable and Sorted traits
use std;
use itertools::Itertools;
fn choose_pivot<T : Ord>(slice : &[T]) -> usize {
// if slice.len() <= 2 {return slice.len() - 1;};
let (mut ismall, imid, mut ibig) = (0, slice.len() / 2, slice.len() - 1);
if slice[ibig] < slice[ismall] {std::mem::swap(... |
let mut min = 0;
for i in 1..slice.len(){
if slice[i] < slice[min] {
min = i;
}
}
slice.swap(0, min);
selsort(&mut slice[1..]);
}
////////////////////////////////////////////////////////////////////////////////////////////////
// Bubblesort
/// The bubblesort algorithm.
pub fn bubblesort<T : Ord>(slice... | {return} | conditional_block |
algorithms.rs | //! Algorithms that back up the Sortable and Sorted traits
use std;
use itertools::Itertools;
fn choose_pivot<T : Ord>(slice : &[T]) -> usize { | if slice[imid] <= slice[ismall] {ismall}
else if slice[ibig] <= slice[imid] {ibig}
else{imid}
}
/// choose a pivot, then reorder so that everything to the left of the pivot is smaller, and
/// everything to the right is greater
/// Assumes slice.len() > 2
pub fn partition<T : Ord>(slice : &mut [T], pivot : usize) -... | // if slice.len() <= 2 {return slice.len() - 1;};
let (mut ismall, imid, mut ibig) = (0, slice.len() / 2, slice.len() - 1);
if slice[ibig] < slice[ismall] {std::mem::swap(&mut ibig, &mut ismall);} | random_line_split |
lib.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 ... | #[cfg(feature="ordered_iter")]
mod ordered_iter; | random_line_split | |
send-iloop.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 iloop() {
task::spawn(|| die() );
let (p, c) = comm::stream::<()>();
loop {
// Sending and receiving here because these actions yield,
// at which point our child can kill us.
c.send(());
p.recv();
// The above comment no longer makes sense but I'm
// rel... | {
fail!();
} | identifier_body |
send-iloop.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 ... | () {
task::spawn(|| die() );
let (p, c) = comm::stream::<()>();
loop {
// Sending and receiving here because these actions yield,
// at which point our child can kill us.
c.send(());
p.recv();
// The above comment no longer makes sense but I'm
// reluctant to ... | iloop | identifier_name |
send-iloop.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 ... | }
} | random_line_split | |
simple.rs | //! The module contains an implementation of a simple HTTP/2 client.
use http::{StreamId, HttpResult, HttpError, Response, Header, HttpScheme};
use http::transport::{TransportStream, TransportReceiveFrame};
use http::connection::{HttpConnection, SendStatus};
use http::session::{SessionState, DefaultSessionState, Defau... |
/// Internal helper method that prepares a new `RequestStream` instance based on the given
/// request parameters.
///
/// The `RequestStream` is then ready to be passed on to the connection instance in order to
/// start the request.
fn new_stream<'n, 'v>(&self,
meth... | {
let stream_id = try!(self.request(b"POST", path, extra_headers, Some(body)));
self.get_response(stream_id)
} | identifier_body |
simple.rs | //! The module contains an implementation of a simple HTTP/2 client.
use http::{StreamId, HttpResult, HttpError, Response, Header, HttpScheme};
use http::transport::{TransportStream, TransportReceiveFrame};
use http::connection::{HttpConnection, SendStatus};
use http::session::{SessionState, DefaultSessionState, Defau... | /// ```
pub struct SimpleClient<S>
where S: TransportStream
{
/// The underlying `ClientConnection` that the client uses
conn: ClientConnection,
/// The name of the host to which the client is connected to.
host: Vec<u8>,
/// The receiving end of the underlying transport stream. Allows us to ext... | /// println!("{}: {}",
/// str::from_utf8(header.name()).unwrap(),
/// str::from_utf8(header.value()).unwrap());
/// }
/// println!("{}", str::from_utf8(&response.body).unwrap()); | random_line_split |
simple.rs | //! The module contains an implementation of a simple HTTP/2 client.
use http::{StreamId, HttpResult, HttpError, Response, Header, HttpScheme};
use http::transport::{TransportStream, TransportReceiveFrame};
use http::connection::{HttpConnection, SendStatus};
use http::session::{SessionState, DefaultSessionState, Defau... | (&mut self,
path: &[u8],
extra_headers: &[Header],
body: Vec<u8>)
-> HttpResult<Response<'static,'static>> {
let stream_id = try!(self.request(b"POST", path, extra_headers, Some(body)));
self.get_response(stream_id)
}
/// Internal ... | post | identifier_name |
struct_tuple_visual.rs | // rustfmt-normalize_comments: true
// rustfmt-wrap_comments: true
// rustfmt-error_on_line_overflow: false
// rustfmt-struct_lit_style: Visual
fn foo() | xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx,
zzzzz, // test
);
A(
// Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec a diam lectus. Sed sit
// amet ipsum mauris. Maecenas congue ligula ac quam viverra nec consectetur ante
// hendrerit. Donec et mollis... | {
Fooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo(f(), b());
Foooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo(
// Comment
foo(), // Comment
// Comment
bar(), // Comment
);
Foo(Bar, f());
Quux(
if... | identifier_body |
struct_tuple_visual.rs | // rustfmt-normalize_comments: true
// rustfmt-wrap_comments: true
// rustfmt-error_on_line_overflow: false
// rustfmt-struct_lit_style: Visual
fn foo() {
Fooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo(f(), b());
Fooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo... | ,
baz(),
);
Baz(
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx,
zzzzz, // test
);
A(
// Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec a diam lectus. Sed sit
// amet ipsum mauris. Maecenas congue ligula ac quam viverra nec consectetur ante
... | {
bar();
} | conditional_block |
struct_tuple_visual.rs | // rustfmt-normalize_comments: true
// rustfmt-wrap_comments: true
// rustfmt-error_on_line_overflow: false
// rustfmt-struct_lit_style: Visual
fn foo() {
Fooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo(f(), b());
Fooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo... | // Praesent et diam eget libero egestas mattis sit amet vitae augue.
// Nam tincidunt congue enim, ut porta lorem lacinia consectetur.
Item,
);
Diagram(
// o This graph demonstrates how
// / \ significant whitespace is
... | random_line_split | |
struct_tuple_visual.rs | // rustfmt-normalize_comments: true
// rustfmt-wrap_comments: true
// rustfmt-error_on_line_overflow: false
// rustfmt-struct_lit_style: Visual
fn | () {
Fooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo(f(), b());
Foooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo(
// Comment
foo(), // Comment
// Comment
bar(), // Comment
);
Foo(Bar, f());
Quux(
... | foo | identifier_name |
to_string.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... |
}
#[cfg(test)]
mod tests {
use prelude::*;
use super::*;
#[test]
fn test_simple_types() {
assert_eq!(1i.to_string(), "1".to_string());
assert_eq!((-1i).to_string(), "-1".to_string());
assert_eq!(200u.to_string(), "200".to_string());
assert_eq!(2u8.to_string(), "2".to_s... | {
format!("{}", *self)
} | identifier_body |
to_string.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... | assert_eq!(().to_string(), "()".to_string());
assert_eq!(("hi".to_string()).to_string(), "hi".to_string());
}
#[test]
fn test_vectors() {
let x: Vec<int> = vec![];
assert_eq!(x.to_string(), "[]".to_string());
assert_eq!((vec![1i]).to_string(), "[1]".to_string());
... | assert_eq!(200u.to_string(), "200".to_string());
assert_eq!(2u8.to_string(), "2".to_string());
assert_eq!(true.to_string(), "true".to_string());
assert_eq!(false.to_string(), "false".to_string()); | random_line_split |
to_string.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... | (&self) -> String {
format!("{}", *self)
}
}
#[cfg(test)]
mod tests {
use prelude::*;
use super::*;
#[test]
fn test_simple_types() {
assert_eq!(1i.to_string(), "1".to_string());
assert_eq!((-1i).to_string(), "-1".to_string());
assert_eq!(200u.to_string(), "200".to_s... | to_string | identifier_name |
uint_macros.rs | // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MI... | assert_eq!(u16_val.to_str(), "0".to_owned());
let mut u32_val: u32 = 4_294_967_295_u32;
assert_eq!(u32_val.to_str(), "4294967295".to_owned());
u32_val += 1 as u32;
assert_eq!(u32_val.to_str(), "0".to_owned());
let mut u64_val: u64 = 18_446_744_073_709_551_615_u64;
... |
let mut u16_val: u16 = 65_535_u16;
assert_eq!(u16_val.to_str(), "65535".to_owned());
u16_val += 1 as u16; | random_line_split |
lib.rs | // Copyright (c) 2020 DDN. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
//! # Iml Job Scheduler RPC client | //! It should be able to call into the job scheduler and recieve results the same as `job_scheduler_client`.
mod request;
mod response;
use iml_rabbit::{
basic_consume_one, basic_publish, bind_queue, close_channel, create_channel, declare_queue,
declare_transient_exchange, BasicConsumeOptions, Connection, Exc... | //!
//! This module provides a client to make rpc calls to the `job_scheduler`.
//! | random_line_split |
lib.rs | // Copyright (c) 2020 DDN. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
//! # Iml Job Scheduler RPC client
//!
//! This module provides a client to make rpc calls to the `job_scheduler`.
//!
//! It should be able to call into the job sched... | (
client: &Connection,
ids: &[CompositeId],
) -> Result<HashMap<CompositeId, Vec<Job>>, ImlJobSchedulerRpcError> {
let ids: Vec<_> = ids.iter().map(|x| (x.0, x.1)).collect();
call(client, "available_jobs", vec![ids], None).await
}
| available_jobs | identifier_name |
lib.rs | // Copyright (c) 2020 DDN. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
//! # Iml Job Scheduler RPC client
//!
//! This module provides a client to make rpc calls to the `job_scheduler`.
//!
//! It should be able to call into the job sched... |
}
impl std::error::Error for ImlJobSchedulerRpcError {
fn source(&self) -> Option<&(dyn std::error::Error +'static)> {
match *self {
ImlJobSchedulerRpcError::ImlRabbitError(ref err) => Some(err),
ImlJobSchedulerRpcError::RpcError(_) => None,
ImlJobSchedulerRpcError::Ser... | {
match *self {
ImlJobSchedulerRpcError::ImlRabbitError(ref err) => write!(f, "{}", err),
ImlJobSchedulerRpcError::RpcError(ref err) => write!(f, "{}", err),
ImlJobSchedulerRpcError::SerdeJsonError(ref err) => write!(f, "{}", err),
}
} | identifier_body |
mod.rs | use actix_web::{web::{route, scope, Query}, HttpRequest, Result, Scope};
use actix_web::http::StatusCode;
use crate::messages::*;
use std::collections::HashMap;
pub mod format_msg;
mod callback;
mod not_understood;
pub use self::format_msg::FormatMsg;
use self::callback::callback;
use self::not_understood::not_unders... | // Assert
assert!(result.is_empty());
}
#[test]
fn test_destruct_path_empty() {
// Arrange
let path = "";
// Act
let result = destruct_path(path);
// Assert
assert!(result.is_empty());
}
pub fn gen_request(path: &str, method: Option... | random_line_split |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.