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 |
|---|---|---|---|---|
op.rs | /*
* niepce - engine/library/op.rs
*
* Copyright (C) 2017-2019 Hubert Figuière
*
* This program 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) an... |
pub fn execute(self, lib: &Library) -> bool {
(self.op)(lib)
}
}
|
Op { op: Arc::new(f) }
}
| identifier_body |
op.rs | /*
* niepce - engine/library/op.rs
*
* Copyright (C) 2017-2019 Hubert Figuière
*
* This program 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) an... | F: Fn(&Library) -> bool + Send + Sync +'static,
{
Op { op: Arc::new(f) }
}
pub fn execute(self, lib: &Library) -> bool {
(self.op)(lib)
}
} | random_line_split | |
op.rs | /*
* niepce - engine/library/op.rs
*
* Copyright (C) 2017-2019 Hubert Figuière
*
* This program 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) an... | self, lib: &Library) -> bool {
(self.op)(lib)
}
}
| xecute( | identifier_name |
cargo_package.rs | use std::io::prelude::*;
use std::fs::{self, File};
use std::path::{self, Path, PathBuf};
use semver::VersionReq;
use tar::Archive;
use flate2::{GzBuilder, Compression};
use flate2::read::GzDecoder;
use core::{SourceId, Package, PackageId};
use core::dependency::Kind;
use sources::PathSource;
use util::{self, CargoRe... |
d.clone_inner().set_source_id(registry.clone()).into_dependency()
});
let mut new_manifest = pkg.manifest().clone();
new_manifest.set_summary(new_summary.override_id(new_pkgid));
let new_pkg = Package::new(new_manifest, &manifest_path);
// Now that we've rewritten all our path dependencies... | { return d } | conditional_block |
cargo_package.rs | use std::io::prelude::*;
use std::fs::{self, File};
use std::path::{self, Path, PathBuf};
use semver::VersionReq;
use tar::Archive;
use flate2::{GzBuilder, Compression};
use flate2::read::GzDecoder;
use core::{SourceId, Package, PackageId};
use core::dependency::Kind;
use sources::PathSource;
use util::{self, CargoRe... | $(
if $(md.$field.as_ref().map_or(true, |s| s.is_empty()))&&* {
$(missing.push(stringify!($field).replace("_", "-"));)*
}
)*
}}
}
lacking!(description, license || license_file, documentation || homepage || repository);
if!m... | ($( $($field: ident)||* ),*) => {{ | random_line_split |
cargo_package.rs | use std::io::prelude::*;
use std::fs::{self, File};
use std::path::{self, Path, PathBuf};
use semver::VersionReq;
use tar::Archive;
use flate2::{GzBuilder, Compression};
use flate2::read::GzDecoder;
use core::{SourceId, Package, PackageId};
use core::dependency::Kind;
use sources::PathSource;
use util::{self, CargoRe... | (pkg: &Package, config: &Config) -> CargoResult<()> {
let wildcard = VersionReq::parse("*").unwrap();
let mut wildcard_deps = vec![];
for dep in pkg.dependencies() {
if dep.kind()!= Kind::Development && dep.version_req() == &wildcard {
wildcard_deps.push(dep.name());
}
}
... | check_dependencies | identifier_name |
cargo_package.rs | use std::io::prelude::*;
use std::fs::{self, File};
use std::path::{self, Path, PathBuf};
use semver::VersionReq;
use tar::Archive;
use flate2::{GzBuilder, Compression};
use flate2::read::GzDecoder;
use core::{SourceId, Package, PackageId};
use core::dependency::Kind;
use sources::PathSource;
use util::{self, CargoRe... | if &**file == dst { continue }
let relative = util::without_prefix(&file, &root).unwrap();
let relative = try!(relative.to_str().chain_error(|| {
human(format!("non-utf8 path in source directory: {}",
relative.display()))
}));
let mut file = ... | {
if fs::metadata(&dst).is_ok() {
return Err(human(format!("destination already exists: {}",
dst.display())))
}
try!(fs::create_dir_all(dst.parent().unwrap()));
let tmpfile = try!(File::create(dst));
// Prepare the encoder and its header
let filename ... | identifier_body |
display.rs | use alloc::boxed::Box;
use core::cmp;
use arch::memory;
use system::graphics::{fast_copy, fast_set};
use super::FONT;
use super::color::Color;
/// The info of the VBE mode
#[derive(Copy, Clone, Default, Debug)]
#[repr(packed)]
pub struct VBEModeInfo {
attributes: u16,
win_a: u8,
win_b: u8,
granular... | (&self, color: Color) {
unsafe {
fast_set(self.offscreen, color.data, self.size);
}
}
/// Scroll the display
pub fn scroll(&self, rows: usize, color: Color) {
if rows > 0 && rows < self.height {
let offset = rows * self.width;
unsafe {
... | set | identifier_name |
display.rs | use alloc::boxed::Box;
use core::cmp;
use arch::memory;
use system::graphics::{fast_copy, fast_set};
use super::FONT;
use super::color::Color;
/// The info of the VBE mode
#[derive(Copy, Clone, Default, Debug)]
#[repr(packed)]
pub struct VBEModeInfo {
attributes: u16,
win_a: u8,
win_b: u8,
granular... |
}
/// Set the color
pub fn set(&self, color: Color) {
unsafe {
fast_set(self.offscreen, color.data, self.size);
}
}
/// Scroll the display
pub fn scroll(&self, rows: usize, color: Color) {
if rows > 0 && rows < self.height {
let offset = rows * ... | {
None
} | conditional_block |
display.rs | use alloc::boxed::Box;
use core::cmp;
use arch::memory;
use system::graphics::{fast_copy, fast_set};
use super::FONT;
use super::color::Color;
/// The info of the VBE mode
#[derive(Copy, Clone, Default, Debug)]
#[repr(packed)]
pub struct VBEModeInfo {
attributes: u16,
win_a: u8,
win_b: u8,
granular... | }
}
/// A display
pub struct Display {
pub offscreen: *mut u32,
pub onscreen: *mut u32,
pub size: usize,
pub width: usize,
pub height: usize,
}
impl Display {
pub fn root() -> Option<Box<Self>> {
if let Some(mode_info) = unsafe { VBEMODEINFO } {
let ret = box Display {
... | VBEMODEINFO = None; | random_line_split |
display.rs | use alloc::boxed::Box;
use core::cmp;
use arch::memory;
use system::graphics::{fast_copy, fast_set};
use super::FONT;
use super::color::Color;
/// The info of the VBE mode
#[derive(Copy, Clone, Default, Debug)]
#[repr(packed)]
pub struct VBEModeInfo {
attributes: u16,
win_a: u8,
win_b: u8,
granular... |
/// Scroll the display
pub fn scroll(&self, rows: usize, color: Color) {
if rows > 0 && rows < self.height {
let offset = rows * self.width;
unsafe {
fast_copy(self.offscreen, self.offscreen.offset(offset as isize), self.size - offset);
fast_set(... | {
unsafe {
fast_set(self.offscreen, color.data, self.size);
}
} | identifier_body |
button.rs | extern crate piston_window;
use std::rc::Rc;
use std::cell::{Ref, RefMut, RefCell};
use rect::*;
use text::*;
use common::*;
use piston_window::{G2d, Context, Glyphs, Transformed};
pub struct ButtonData {
name: String,
focused: bool,
on_click_fn: OnClickFn<Button>,
on_drag_fn: OnDragFn<Button>,
}
/// ... |
}
else {
self.set_focused(false);
}
false
}
fn on_click_dev(&self, c: Context, mouse_x: f64, mouse_y: f64) -> bool {
self.rect.on_click_dev(c, mouse_x, mouse_y)
}
fn mouse_relative(&self, c: Context, mouse_x: f64, mouse_y: f64,
... | {
(*cb.borrow())(self);
} | conditional_block |
button.rs | extern crate piston_window;
use std::rc::Rc;
use std::cell::{Ref, RefMut, RefCell};
use rect::*;
use text::*;
use common::*;
use piston_window::{G2d, Context, Glyphs, Transformed};
pub struct ButtonData {
name: String,
focused: bool,
on_click_fn: OnClickFn<Button>,
on_drag_fn: OnDragFn<Button>,
}
/// ... | }
fn get_data_mut<'a>(&'a self) -> RefMut<'a, ButtonData> {
self.data.borrow_mut()
}
}
macro_rules! impl_buttoni {
($t:ty, $id:ident) => (
impl ButtonI for $t {
fn get_data<'a>(&'a self) -> Ref<'a, ButtonData> {
self.$id.get_data()
}
... | self.data.borrow() | random_line_split |
button.rs | extern crate piston_window;
use std::rc::Rc;
use std::cell::{Ref, RefMut, RefCell};
use rect::*;
use text::*;
use common::*;
use piston_window::{G2d, Context, Glyphs, Transformed};
pub struct | {
name: String,
focused: bool,
on_click_fn: OnClickFn<Button>,
on_drag_fn: OnDragFn<Button>,
}
/// A button is a combination of text and a rect
#[derive(Clone)]
pub struct Button {
data: Rc<RefCell<ButtonData>>,
rect: Rect,
text: Text,
}
impl Button {
pub fn new<S: Into<String>>(name:... | ButtonData | identifier_name |
button.rs | extern crate piston_window;
use std::rc::Rc;
use std::cell::{Ref, RefMut, RefCell};
use rect::*;
use text::*;
use common::*;
use piston_window::{G2d, Context, Glyphs, Transformed};
pub struct ButtonData {
name: String,
focused: bool,
on_click_fn: OnClickFn<Button>,
on_drag_fn: OnDragFn<Button>,
}
/// ... |
fn get_local_data_mut<'a>(&'a self) -> RefMut<'a, ButtonData> {
self.data.borrow_mut()
}
pub fn set_on_click_fn(&mut self, cb: Box<Fn(&Button)>) {
self.get_local_data_mut().on_click_fn =
Some(Rc::new(RefCell::new(cb)));
}
pub fn set_on_drag_fn(&mut self, cb: Box<F... | {
self.data.borrow()
} | identifier_body |
config.rs | use rustc_serialize::*;
use std::path::Path;
use std::fs::File;
use toml::{Value};
use std::io::{Read};
#[derive(Debug, Clone)]
pub struct ServiceConfig {
pub name : String,
pub description : String,
pub group : String,
pub secret : String,
pub id : i32
}
impl Decodable ... | try!(s.emit_struct_field("name", 0, |s| {
s.emit_str(&self.name)
}));
try!(s.emit_struct_field("description", 1, |s| {
s.emit_str(&self.description)
}));
try!(s.emit_struct_field("id", 2, |s| {
s.emit_i32(self.id... |
impl Encodable for ServiceConfig {
fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
s.emit_struct("ServiceConfig", 4, |s| { | random_line_split |
config.rs | use rustc_serialize::*;
use std::path::Path;
use std::fs::File;
use toml::{Value};
use std::io::{Read};
#[derive(Debug, Clone)]
pub struct | {
pub name : String,
pub description : String,
pub group : String,
pub secret : String,
pub id : i32
}
impl Decodable for ServiceConfig {
fn decode<D: Decoder>(d: &mut D) -> Result<ServiceConfig, D::Error> {
d.read_struct("ServiceConfig", 4, |d| {
... | ServiceConfig | identifier_name |
get_room_visibility.rs | //! [GET /_matrix/client/r0/directory/list/room/{roomId}](https://matrix.org/docs/spec/client_server/r0.6.0#get-matrix-client-r0-directory-list-room-roomid)
use ruma_api::ruma_api;
use ruma_identifiers::RoomId;
use crate::r0::room::Visibility;
ruma_api! {
metadata { | requires_authentication: false,
}
request {
/// The ID of the room of which to request the visibility.
#[ruma_api(path)]
pub room_id: RoomId,
}
response {
/// Visibility of the room.
pub visibility: Visibility,
}
error: crate::Error
} | description: "Get the visibility of a public room on a directory.",
name: "get_room_visibility",
method: GET,
path: "/_matrix/client/r0/directory/list/room/:room_id",
rate_limited: false, | random_line_split |
xml.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/. */
#![allow(unrooted_must_root)]
use dom::bindings::root::{Dom, DomRoot};
use dom::bindings::trace::JSTraceable;
use dom::document::Document;
use dom::htmlscriptelement::HTMLScriptElement;
use dom::node::Node;
use dom::servoparser::Sink;
use js::jsapi::JSTra... | random_line_split | |
xml.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/. */
#![allow(unrooted_must_root)]
use dom::bindings::root::{Dom, DomRoot};
use dom::bindings::trace::JSTraceable;
use... | (&self) -> &ServoUrl {
&self.inner.sink.sink.base_url
}
}
#[allow(unsafe_code)]
unsafe impl JSTraceable for XmlTokenizer<XmlTreeBuilder<Dom<Node>, Sink>> {
unsafe fn trace(&self, trc: *mut JSTracer) {
struct Tracer(*mut JSTracer);
let tracer = Tracer(trc);
impl XmlTracer for Tr... | url | identifier_name |
xml.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/. */
#![allow(unrooted_must_root)]
use dom::bindings::root::{Dom, DomRoot};
use dom::bindings::trace::JSTraceable;
use... |
}
#[allow(unsafe_code)]
unsafe impl JSTraceable for XmlTokenizer<XmlTreeBuilder<Dom<Node>, Sink>> {
unsafe fn trace(&self, trc: *mut JSTracer) {
struct Tracer(*mut JSTracer);
let tracer = Tracer(trc);
impl XmlTracer for Tracer {
type Handle = Dom<Node>;
#[allow(unr... | {
&self.inner.sink.sink.base_url
} | identifier_body |
xml.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/. */
#![allow(unrooted_must_root)]
use dom::bindings::root::{Dom, DomRoot};
use dom::bindings::trace::JSTraceable;
use... |
Ok(())
}
pub fn end(&mut self) {
self.inner.end()
}
pub fn url(&self) -> &ServoUrl {
&self.inner.sink.sink.base_url
}
}
#[allow(unsafe_code)]
unsafe impl JSTraceable for XmlTokenizer<XmlTreeBuilder<Dom<Node>, Sink>> {
unsafe fn trace(&self, trc: *mut JSTracer) {
... | {
self.inner.run();
if let Some(script) = self.inner.sink.sink.script.take() {
return Err(script);
}
} | conditional_block |
util.rs | use std::rand;
use std::rand::Rng;
use settings::Settings;
use piece::Piece;
pub fn check_overlap(settings: &Settings, pos: u32, content_len: u32, files: &Vec<Piece>) -> bool {
for i in files.iter() {
if pos + 1 > i.start_pos && pos - 1 < i.end_pos
|| pos + 1 + content_len > i.start_p... |
pub fn concat_vec<T>(a: Vec<T>, b: Vec<T>) -> Vec<T> {
let mut r = a;
r.extend(b.into_iter());
r
}
pub fn random_pass(len: uint) -> Vec<u8> {
rand::task_rng().gen_ascii_chars().take(len).map(|x| x as u8).collect::<Vec<u8>>()
}
| {
for i in files.iter() {
if pos >= i.start_pos && pos < i.end_pos {
return Some(i.clone());
}
}
None
} | identifier_body |
util.rs | use std::rand;
use std::rand::Rng;
use settings::Settings;
use piece::Piece;
pub fn check_overlap(settings: &Settings, pos: u32, content_len: u32, files: &Vec<Piece>) -> bool {
for i in files.iter() {
if pos + 1 > i.start_pos && pos - 1 < i.end_pos
|| pos + 1 + content_len > i.start_p... | <T>(a: Vec<T>, b: Vec<T>) -> Vec<T> {
let mut r = a;
r.extend(b.into_iter());
r
}
pub fn random_pass(len: uint) -> Vec<u8> {
rand::task_rng().gen_ascii_chars().take(len).map(|x| x as u8).collect::<Vec<u8>>()
}
| concat_vec | identifier_name |
util.rs | use std::rand;
use std::rand::Rng;
use settings::Settings;
use piece::Piece;
pub fn check_overlap(settings: &Settings, pos: u32, content_len: u32, files: &Vec<Piece>) -> bool {
for i in files.iter() {
if pos + 1 > i.start_pos && pos - 1 < i.end_pos
|| pos + 1 + content_len > i.start_p... |
}
false
}
pub fn find_file_next_distance(settings: &Settings, pos:u32, files:Vec<Piece>) -> Option<u32> {
let mut dist: u32 = settings.blocksize - pos;
let mut found: bool = false;
for i in files.iter() {
if pos > i.start_pos && pos < i.end_pos {
return Some(0u32);
} ... | {
return true;
} | conditional_block |
util.rs | use std::rand;
use std::rand::Rng;
use settings::Settings;
use piece::Piece;
pub fn check_overlap(settings: &Settings, pos: u32, content_len: u32, files: &Vec<Piece>) -> bool {
for i in files.iter() {
if pos + 1 > i.start_pos && pos - 1 < i.end_pos
|| pos + 1 + content_len > i.start_p... | if pos > i.start_pos && pos < i.end_pos {
return Some(0u32);
} else {
let spos = i.start_pos - pos;
if spos < dist {
dist = spos;
found = true;
}
}
}
return if found { Some(dist) } else { None };
}
pub fn ... | let mut dist: u32 = settings.blocksize - pos;
let mut found: bool = false;
for i in files.iter() { | random_line_split |
main.rs | use std::io;
use std::io::Read;
fn read_input() -> io::Result<String> {
let mut buffer = String::new();
try!(io::stdin().read_to_string(&mut buffer));
Ok(buffer.trim().to_string())
}
fn has_escaped_backslash(chars: &Vec<char>, index: usize) -> Option<usize> {
if (index + 1 < chars.len()) &&
(ch... | (chars: &Vec<char>, index: usize) -> Option<usize> {
if (index + 1 < chars.len()) &&
(chars[index] == '\\') &&
(chars[index + 1] == '\"') {
Some(index + 2) }
else {
None
}
}
fn has_escaped_character(chars: &Vec<char>, index: usize) -> Option<usize> {
if (index + 3 < chars.l... | has_escaped_quote | identifier_name |
main.rs | use std::io;
use std::io::Read;
fn read_input() -> io::Result<String> {
let mut buffer = String::new();
try!(io::stdin().read_to_string(&mut buffer));
Ok(buffer.trim().to_string())
}
fn has_escaped_backslash(chars: &Vec<char>, index: usize) -> Option<usize> {
if (index + 1 < chars.len()) &&
(ch... | println!("Chars when encoded: {}", encoded);
println!("Diff with encoded: {}", encoded - total_and_decoded.0);
} | random_line_split | |
main.rs | use std::io;
use std::io::Read;
fn read_input() -> io::Result<String> {
let mut buffer = String::new();
try!(io::stdin().read_to_string(&mut buffer));
Ok(buffer.trim().to_string())
}
fn has_escaped_backslash(chars: &Vec<char>, index: usize) -> Option<usize> {
if (index + 1 < chars.len()) &&
(ch... | }
}
encoded_size
}
fn main() {
let input = read_input().unwrap();
let total_and_decoded = input
.lines()
.map(calculate_decoded_size)
.fold(
(0, 0),
|(total_and_decoded_code, total_and_decoded_memory), (code, memory)|
(total_and_dec... | {
let mut encoded_size = line.len() + 2; // " in the beginning and in the end.
let chars: Vec<_> = line.chars().collect();
let mut i = 0;
loop {
if i == chars.len() { break; }
if chars[i] == '\"' {
encoded_size += 1;
i += 1;
} else if let Some(next) = h... | identifier_body |
helper_log.rs | use crate::context::Context;
#[cfg(not(feature = "no_logging"))]
use crate::error::RenderError;
use crate::helpers::{HelperDef, HelperResult};
#[cfg(not(feature = "no_logging"))]
use crate::json::value::JsonRender;
use crate::output::Output;
use crate::registry::Registry;
use crate::render::{Helper, RenderContext};
#[c... | else {
p.value().render()
}
})
.collect::<Vec<String>>()
.join(", ");
let level = h
.hash_get("level")
.and_then(|v| v.value().as_str())
.unwrap_or("info");
if let Ok(log_level) = Level::from_str(le... | {
format!("{}: {}", relative_path, p.value().render())
} | conditional_block |
helper_log.rs | use crate::context::Context;
#[cfg(not(feature = "no_logging"))]
use crate::error::RenderError;
use crate::helpers::{HelperDef, HelperResult};
#[cfg(not(feature = "no_logging"))]
use crate::json::value::JsonRender;
use crate::output::Output;
use crate::registry::Registry;
use crate::render::{Helper, RenderContext};
#[c... | <'reg: 'rc, 'rc>(
&self,
_: &Helper<'reg, 'rc>,
_: &Registry<'reg>,
_: &Context,
_: &mut RenderContext<'reg, 'rc>,
_: &mut dyn Output,
) -> HelperResult {
Ok(())
}
}
pub static LOG_HELPER: LogHelper = LogHelper;
| call | identifier_name |
helper_log.rs | use crate::context::Context;
#[cfg(not(feature = "no_logging"))]
use crate::error::RenderError;
use crate::helpers::{HelperDef, HelperResult};
#[cfg(not(feature = "no_logging"))]
use crate::json::value::JsonRender;
use crate::output::Output;
use crate::registry::Registry;
use crate::render::{Helper, RenderContext};
#[c... |
}
pub static LOG_HELPER: LogHelper = LogHelper;
| {
Ok(())
} | identifier_body |
helper_log.rs | use crate::context::Context;
#[cfg(not(feature = "no_logging"))]
use crate::error::RenderError;
use crate::helpers::{HelperDef, HelperResult};
#[cfg(not(feature = "no_logging"))]
use crate::json::value::JsonRender;
use crate::output::Output;
use crate::registry::Registry;
use crate::render::{Helper, RenderContext};
#[c... | .params()
.iter()
.map(|p| {
if let Some(ref relative_path) = p.relative_path() {
format!("{}: {}", relative_path, p.value().render())
} else {
p.value().render()
}
})
.collect... | let param_to_log = h | random_line_split |
lib.rs | #[macro_use]
extern crate log;
pub mod keyboard;
#[cfg(feature = "legacy")]
mod keyboard_legacy;
#[cfg(not(feature = "legacy"))]
mod keyboard_win8;
mod language;
pub mod platform;
mod types;
mod winrust;
#[cfg(not(feature = "legacy"))]
mod win8;
#[cfg(not(feature = "legacy"))]
pub use self::win8::*;
#[cfg(feature = ... | .chain(std::io::stdout())
.chain(fern::log_file(log_path.join(format!("run.log")))?)
.apply()?;
Ok(())
} | .level_for("kbdi", log::LevelFilter::Trace) | random_line_split |
lib.rs | #[macro_use]
extern crate log;
pub mod keyboard;
#[cfg(feature = "legacy")]
mod keyboard_legacy;
#[cfg(not(feature = "legacy"))]
mod keyboard_win8;
mod language;
pub mod platform;
mod types;
mod winrust;
#[cfg(not(feature = "legacy"))]
mod win8;
#[cfg(not(feature = "legacy"))]
pub use self::win8::*;
#[cfg(feature = ... | (tag: &str) -> u32 {
crate::platform::winnls::locale_name_to_lcid(&tag)
.map(|x| if x == 0x1000 { 0x2000 } else { x })
.unwrap_or(0x2000)
}
#[derive(Debug, thiserror::Error)]
pub enum Error {
#[error("IO error")]
Io(#[from] std::io::Error),
#[error("Path error")]
Path(#[from] pathos:... | lcid | identifier_name |
lib.rs | #[macro_use]
extern crate log;
pub mod keyboard;
#[cfg(feature = "legacy")]
mod keyboard_legacy;
#[cfg(not(feature = "legacy"))]
mod keyboard_win8;
mod language;
pub mod platform;
mod types;
mod winrust;
#[cfg(not(feature = "legacy"))]
mod win8;
#[cfg(not(feature = "legacy"))]
pub use self::win8::*;
#[cfg(feature = ... | else {
pathos::user::app_log_dir("kbdi")?
};
std::fs::create_dir_all(&log_path)?;
fern::Dispatch::new()
.format(|out, message, record| {
out.finish(format_args!(
"[{} {:<5} {}] {}",
chrono::Utc::now().to_rfc3339_opts(chrono::SecondsFormat::Millis... | {
pathos::system::app_log_dir("kbdi")
} | conditional_block |
tasks.rs | // Copyright 2017 Pants project contributors (see CONTRIBUTORS.md).
// Licensed under the Apache License, Version 2.0 (see LICENSE).
use std::fmt;
use crate::intrinsics::Intrinsics;
use crate::python::{Function, TypeId};
use crate::selectors::{DependencyKey, Get, Select};
use indexmap::IndexSet;
use log::Level;
use ... |
pub fn intrinsics_set(&mut self, intrinsics: &Intrinsics) {
for intrinsic in intrinsics.keys() {
self.rules.insert(Rule::Intrinsic(intrinsic.clone()));
}
}
///
/// The following methods define the Task registration lifecycle.
///
pub fn task_begin(
&mut self,
func: Function,
ret... | {
&self.queries
} | identifier_body |
tasks.rs | // Copyright 2017 Pants project contributors (see CONTRIBUTORS.md).
// Licensed under the Apache License, Version 2.0 (see LICENSE).
use std::fmt;
use crate::intrinsics::Intrinsics;
use crate::python::{Function, TypeId};
use crate::selectors::{DependencyKey, Get, Select};
use indexmap::IndexSet;
use log::Level;
use ... | ///
/// A collection of Rules (TODO: rename to Rules).
///
/// Defines a stateful lifecycle for defining tasks via the C api. Call in order:
/// 1. task_begin() - once per task
/// 2. add_*() - zero or more times per task to add input clauses
/// 3. task_end() - once per task
///
/// (This protocol was original d... | preparing: Option<Task>,
queries: IndexSet<Query<Rule>>,
}
| random_line_split |
tasks.rs | // Copyright 2017 Pants project contributors (see CONTRIBUTORS.md).
// Licensed under the Apache License, Version 2.0 (see LICENSE).
use std::fmt;
use crate::intrinsics::Intrinsics;
use crate::python::{Function, TypeId};
use crate::selectors::{DependencyKey, Get, Select};
use indexmap::IndexSet;
use log::Level;
use ... | {
pub product: TypeId,
pub inputs: Vec<TypeId>,
}
///
/// Registry of native (rust) Intrinsic tasks and user (python) Tasks.
///
#[derive(Clone, Debug)]
pub struct Tasks {
rules: IndexSet<Rule>,
// Used during the construction of a rule.
preparing: Option<Task>,
queries: IndexSet<Query<Rule>>,
}
///
/// ... | Intrinsic | identifier_name |
renderer-texture.rs | extern crate sdl2;
use sdl2::pixels::PixelFormatEnum;
use sdl2::rect::Rect;
use sdl2::event::Event;
use sdl2::keyboard::Keycode;
pub fn main() {
let sdl_context = sdl2::init().unwrap();
let video_subsystem = sdl_context.video().unwrap();
let window = video_subsystem.window("rust-sdl2 demo: Video", 800, 6... | renderer.copy(&texture, None, Some(Rect::new(100, 100, 256, 256))).unwrap();
renderer.copy_ex(&texture, None,
Some(Rect::new(450, 100, 256, 256)), 30.0, None, false, false).unwrap();
renderer.present();
let mut event_pump = sdl_context.event_pump().unwrap();
'running: loop {
for e... | random_line_split | |
renderer-texture.rs | extern crate sdl2;
use sdl2::pixels::PixelFormatEnum;
use sdl2::rect::Rect;
use sdl2::event::Event;
use sdl2::keyboard::Keycode;
pub fn main() {
let sdl_context = sdl2::init().unwrap();
let video_subsystem = sdl_context.video().unwrap();
let window = video_subsystem.window("rust-sdl2 demo: Video", 800, 6... | ,
_ => {}
}
}
// The rest of the game loop goes here...
}
}
| {
break 'running
} | conditional_block |
renderer-texture.rs | extern crate sdl2;
use sdl2::pixels::PixelFormatEnum;
use sdl2::rect::Rect;
use sdl2::event::Event;
use sdl2::keyboard::Keycode;
pub fn | () {
let sdl_context = sdl2::init().unwrap();
let video_subsystem = sdl_context.video().unwrap();
let window = video_subsystem.window("rust-sdl2 demo: Video", 800, 600)
.position_centered()
.opengl()
.build()
.unwrap();
let mut renderer = window.renderer().build().unwrap();... | main | identifier_name |
renderer-texture.rs | extern crate sdl2;
use sdl2::pixels::PixelFormatEnum;
use sdl2::rect::Rect;
use sdl2::event::Event;
use sdl2::keyboard::Keycode;
pub fn main() | buffer[offset + 1] = y as u8;
buffer[offset + 2] = 0;
}
}
}).unwrap();
renderer.clear();
renderer.copy(&texture, None, Some(Rect::new(100, 100, 256, 256))).unwrap();
renderer.copy_ex(&texture, None,
Some(Rect::new(450, 100, 256, 256)), 30.0, ... | {
let sdl_context = sdl2::init().unwrap();
let video_subsystem = sdl_context.video().unwrap();
let window = video_subsystem.window("rust-sdl2 demo: Video", 800, 600)
.position_centered()
.opengl()
.build()
.unwrap();
let mut renderer = window.renderer().build().unwrap()... | identifier_body |
htmlulistelement.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::HTMLUListElementBinding;
use dom::bindings::js::Root;
use dom::bindings::str... | {
htmlelement: HTMLElement
}
impl HTMLUListElement {
fn new_inherited(localName: Atom, prefix: Option<DOMString>, document: &Document) -> HTMLUListElement {
HTMLUListElement {
htmlelement: HTMLElement::new_inherited(localName, prefix, document)
}
}
#[allow(unrooted_must_ro... | HTMLUListElement | identifier_name |
htmlulistelement.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::HTMLUListElementBinding;
use dom::bindings::js::Root; | use dom::node::Node;
use string_cache::Atom;
#[dom_struct]
pub struct HTMLUListElement {
htmlelement: HTMLElement
}
impl HTMLUListElement {
fn new_inherited(localName: Atom, prefix: Option<DOMString>, document: &Document) -> HTMLUListElement {
HTMLUListElement {
htmlelement: HTMLElement::n... | use dom::bindings::str::DOMString;
use dom::document::Document;
use dom::htmlelement::HTMLElement; | random_line_split |
renderer.rs | use glium;
use glium::index::PrimitiveType::*;
use glium::texture::*;
use glium::uniforms::*;
use glium::*;
use glutin::dpi::*;
use glutin::*;
use image::{load_from_memory_with_format, ImageFormat};
use runic::default_program;
use resources::TILESET;
use settings::Settings;
const TITLE: &str = "War Against Machines";... | {
pub src: [f32; 4],
pub overlay_colour: [f32; 4],
pub dest: [f32; 2],
pub rotation: f32,
pub scale: f32,
}
struct Uniforms {
screen_resolution: [f32; 2],
tileset_size: [f32; 2],
texture: SrgbTexture2d,
}
pub struct Renderer {
uniforms: Uniforms,
pub target: Frame,
pub dis... | Properties | identifier_name |
renderer.rs | use glium;
use glium::index::PrimitiveType::*;
use glium::texture::*;
use glium::uniforms::*;
use glium::*;
use glutin::dpi::*;
use glutin::*;
use image::{load_from_memory_with_format, ImageFormat};
use runic::default_program;
use resources::TILESET;
use settings::Settings;
const TITLE: &str = "War Against Machines";... |
// Create the context and display
let context = ContextBuilder::new().with_vsync(true);
let display = Display::new(builder, context, &event_loop).unwrap();
// Create the buffers and program
let vertex_buffer = VertexBuffer::new(&display, SQUARE).unwrap();
let indices =... | {
builder = builder.with_fullscreen(Some(event_loop.get_primary_monitor()));
} | conditional_block |
renderer.rs | use glium;
use glium::index::PrimitiveType::*;
use glium::texture::*;
use glium::uniforms::*;
use glium::*;
use glutin::dpi::*;
use glutin::*;
use image::{load_from_memory_with_format, ImageFormat};
use runic::default_program;
use resources::TILESET;
use settings::Settings;
const TITLE: &str = "War Against Machines";... |
// Set the window to be fullscreen if that's set in settings
if settings.fullscreen {
builder = builder.with_fullscreen(Some(event_loop.get_primary_monitor()));
}
// Create the context and display
let context = ContextBuilder::new().with_vsync(true);
let dis... | .with_title(TITLE)
.with_dimensions(LogicalSize::new(f64::from(width), f64::from(height))); | random_line_split |
conv2n.rs | use crate::{convolve2n, convolve3};
use mli::*;
use mli_ndarray::Ndeep;
use ndarray::{s, Array, Array2, Array3, ArrayBase, Axis, Data, OwnedRepr};
use std::marker::PhantomData;
type D2 = ndarray::Ix2;
type D3 = ndarray::Ix3;
#[derive(Clone, Debug)]
pub struct Conv2n<S>(Array3<f32>, PhantomData<S>);
impl<S> Conv2n<S>... | // If the filter is 1 in either dimension, the below code wont work.
if filter_dims.0 <= 1 || filter_dims.1 <= 1 {
unimplemented!("mli-conv: filter dimensions of 1 not implemented yet");
}
let padding = (2 * (filter_dims.0 - 1), 2 * (filter_dims.1 - 1));
let pad_dims ... | random_line_split | |
conv2n.rs | use crate::{convolve2n, convolve3};
use mli::*;
use mli_ndarray::Ndeep;
use ndarray::{s, Array, Array2, Array3, ArrayBase, Axis, Data, OwnedRepr};
use std::marker::PhantomData;
type D2 = ndarray::Ix2;
type D3 = ndarray::Ix3;
#[derive(Clone, Debug)]
pub struct Conv2n<S>(Array3<f32>, PhantomData<S>);
impl<S> Conv2n<S>... | (filters: Array3<f32>) -> Self {
Self(filters, PhantomData)
}
}
impl<S> Forward for Conv2n<S>
where
S: Data<Elem = f32>,
{
type Input = ArrayBase<S, D2>;
type Internal = ();
type Output = Array3<f32>;
fn forward(&self, input: &Self::Input) -> ((), Self::Output) {
let Self(filte... | new | identifier_name |
conv2n.rs | use crate::{convolve2n, convolve3};
use mli::*;
use mli_ndarray::Ndeep;
use ndarray::{s, Array, Array2, Array3, ArrayBase, Axis, Data, OwnedRepr};
use std::marker::PhantomData;
type D2 = ndarray::Ix2;
type D3 = ndarray::Ix3;
#[derive(Clone, Debug)]
pub struct Conv2n<S>(Array3<f32>, PhantomData<S>);
impl<S> Conv2n<S>... |
let padding = (2 * (filter_dims.0 - 1), 2 * (filter_dims.1 - 1));
let pad_dims = (
output_delta.shape()[0],
output_delta.shape()[1] + padding.0,
output_delta.shape()[2] + padding.1,
);
let mut pad = Array::zeros(pad_dims);
#[allow(clippy::dere... | {
unimplemented!("mli-conv: filter dimensions of 1 not implemented yet");
} | conditional_block |
conv2n.rs | use crate::{convolve2n, convolve3};
use mli::*;
use mli_ndarray::Ndeep;
use ndarray::{s, Array, Array2, Array3, ArrayBase, Axis, Data, OwnedRepr};
use std::marker::PhantomData;
type D2 = ndarray::Ix2;
type D3 = ndarray::Ix3;
#[derive(Clone, Debug)]
pub struct Conv2n<S>(Array3<f32>, PhantomData<S>);
impl<S> Conv2n<S>... |
}
impl<S> Backward for Conv2n<S>
where
S: Data<Elem = f32>,
{
type OutputDelta = Array3<f32>;
type InputDelta = Array2<f32>;
type TrainDelta = Ndeep<OwnedRepr<f32>, D3>;
fn backward(
&self,
input: &Self::Input,
_: &Self::Internal,
output_delta: &Self::OutputDelta,
... | {
let Self(filter, _) = self;
((), convolve2n(input.view(), filter.view()))
} | identifier_body |
blocking.rs | //!
//! A demonstration of constructing and using a blocking stream.
//!
//! Audio from the default input device is passed directly to the default output device in a duplex
//! stream, so beware of feedback!
//!
extern crate portaudio;
use portaudio::pa;
use std::error::Error;
use std::mem::replace;
const SAMPLE_RAT... | () {
println!("PortAudio version : {}", pa::get_version());
println!("PortAudio version text : {}", pa::get_version_text());
match pa::initialize() {
Ok(()) => println!("Successfully initialized PortAudio"),
Err(err) => println!("An error occurred while initializing PortAudio: {}", err.des... | main | identifier_name |
blocking.rs | //!
//! A demonstration of constructing and using a blocking stream.
//!
//! Audio from the default input device is passed directly to the default output device in a duplex
//! stream, so beware of feedback!
//!
extern crate portaudio;
use portaudio::pa;
use std::error::Error;
use std::mem::replace;
const SAMPLE_RAT... | let def_input = pa::device::get_default_input();
let input_info = match pa::device::get_info(def_input) {
Ok(info) => info,
Err(err) => panic!("An error occurred while retrieving input info: {}", err.description()),
};
println!("Default input device info :");
println!("\tversion : {}... | {
println!("PortAudio version : {}", pa::get_version());
println!("PortAudio version text : {}", pa::get_version_text());
match pa::initialize() {
Ok(()) => println!("Successfully initialized PortAudio"),
Err(err) => println!("An error occurred while initializing PortAudio: {}", err.descri... | identifier_body |
blocking.rs | //!
//! A demonstration of constructing and using a blocking stream.
//!
//! Audio from the default input device is passed directly to the default output device in a duplex
//! stream, so beware of feedback!
//!
extern crate portaudio;
| use std::error::Error;
use std::mem::replace;
const SAMPLE_RATE: f64 = 44_100.0;
const CHANNELS: u32 = 2;
const FRAMES: u32 = 256;
fn main() {
println!("PortAudio version : {}", pa::get_version());
println!("PortAudio version text : {}", pa::get_version_text());
match pa::initialize() {
Ok(()) =... | use portaudio::pa; | random_line_split |
handler_storage.rs | #[macro_use]
extern crate rustful;
use std::io::{self, Read};
use std::fs::File;
use std::path::Path;
use std::sync::{Arc, RwLock};
use std::error::Error;
use rustful::{
Server,
Context,
Response,
Handler,
TreeRouter,
StatusCode
};
use rustful::file::{self, Loader};
fn main() {
println!("... |
fn read_string<P: AsRef<Path>>(path: P) -> io::Result<String> {
//Read file into a string
let mut string = String::new();
File::open(path).and_then(|mut f| f.read_to_string(&mut string)).map(|_| string)
}
enum Api {
Counter {
//We are using the handler to preload the page in this exmaple
... | {
value - 1
} | identifier_body |
handler_storage.rs | #[macro_use]
extern crate rustful;
use std::io::{self, Read};
use std::fs::File;
use std::path::Path;
use std::sync::{Arc, RwLock};
use std::error::Error;
use rustful::{
Server,
Context,
Response,
Handler,
TreeRouter,
StatusCode
};
use rustful::file::{self, Loader};
fn main() {
println!("... | //Insert the value into the page and write it to the response
let count = value.read().unwrap().to_string();
response.send(page.replace("{}", &count[..]));
},
Api::File => {
if let Some(file) = context.variables.get("file") {
... | *value = op(*value);
});
| random_line_split |
handler_storage.rs | #[macro_use]
extern crate rustful;
use std::io::{self, Read};
use std::fs::File;
use std::path::Path;
use std::sync::{Arc, RwLock};
use std::error::Error;
use rustful::{
Server,
Context,
Response,
Handler,
TreeRouter,
StatusCode
};
use rustful::file::{self, Loader};
fn main() {
println!("... | (value: i32) -> i32 {
value - 1
}
fn read_string<P: AsRef<Path>>(path: P) -> io::Result<String> {
//Read file into a string
let mut string = String::new();
File::open(path).and_then(|mut f| f.read_to_string(&mut string)).map(|_| string)
}
enum Api {
Counter {
//We are using the handler to... | sub | identifier_name |
handler_storage.rs | #[macro_use]
extern crate rustful;
use std::io::{self, Read};
use std::fs::File;
use std::path::Path;
use std::sync::{Arc, RwLock};
use std::error::Error;
use rustful::{
Server,
Context,
Response,
Handler,
TreeRouter,
StatusCode
};
use rustful::file::{self, Loader};
fn main() {
println!("... | else {
//Something went horribly wrong
context.log.error(&format!("failed to open '{}': {}", file, e.description()));
response.set_status(StatusCode::InternalServerError);
}
}
... | {
response.set_status(StatusCode::NotFound);
} | conditional_block |
bookmark.rs | //
// imag - the personal information management suite for the commandline
// Copyright (C) 2015-2020 Matthias Beyer <mail@beyermatthias.de> and contributors
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the F... |
}
| {
self.is::<IsBookmark>()
} | identifier_body |
bookmark.rs | //
// imag - the personal information management suite for the commandline
// Copyright (C) 2015-2020 Matthias Beyer <mail@beyermatthias.de> and contributors
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the F... | (&self) -> Result<bool> {
self.is::<IsBookmark>()
}
}
| is_bookmark | identifier_name |
bookmark.rs | //
// imag - the personal information management suite for the commandline
// Copyright (C) 2015-2020 Matthias Beyer <mail@beyermatthias.de> and contributors
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the F... | } | self.is::<IsBookmark>()
} | random_line_split |
extern-crate-used.rs | // Extern crate items are marked as used if they are used | // edition:2018
#![deny(unused_extern_crates)]
// Shouldn't suggest changing to `use`, as new name
// would no longer be added to the prelude which could cause
// compilation errors for imports that use the new name in
// other modules. See #57672.
extern crate core as iso1;
extern crate core as iso2;
extern crate co... | // through extern prelude entries introduced by them.
| random_line_split |
extern-crate-used.rs | // Extern crate items are marked as used if they are used
// through extern prelude entries introduced by them.
// edition:2018
#![deny(unused_extern_crates)]
// Shouldn't suggest changing to `use`, as new name
// would no longer be added to the prelude which could cause
// compilation errors for imports that use th... | {} | identifier_body | |
extern-crate-used.rs | // Extern crate items are marked as used if they are used
// through extern prelude entries introduced by them.
// edition:2018
#![deny(unused_extern_crates)]
// Shouldn't suggest changing to `use`, as new name
// would no longer be added to the prelude which could cause
// compilation errors for imports that use th... | () {}
| main | identifier_name |
main.rs | #![deny(trivial_casts, trivial_numeric_casts)]
extern crate byteorder;
#[macro_use] extern crate clap;
#[macro_use] extern crate enum_primitive;
extern crate num;
extern crate rand;
extern crate sdl2;
extern crate time;
use std::fs::File;
use std::io::Read;
use clap::{Arg, App};
use vm::VM;
mod cart; | mod interconnect;
mod memory;
mod mem_map;
mod reg_status;
mod vm;
fn main() {
let matches = App::new("NES Emulator")
.version(crate_version!())
.author("tompko <tompko@gmail.com>")
.about("Emulates the NES")
.arg(Arg::wit... | mod cpu;
mod graphics;
mod input; | random_line_split |
main.rs | #![deny(trivial_casts, trivial_numeric_casts)]
extern crate byteorder;
#[macro_use] extern crate clap;
#[macro_use] extern crate enum_primitive;
extern crate num;
extern crate rand;
extern crate sdl2;
extern crate time;
use std::fs::File;
use std::io::Read;
use clap::{Arg, App};
use vm::VM;
mod cart;
mod cpu;
mod gr... | ,
Err(err) => {
println!("nesRS: cannot open '{}': {}", filename, err);
std::process::exit(-1);
}
}
buffer.into_boxed_slice()
}
| {
file.read_to_end(&mut buffer).unwrap();
} | conditional_block |
main.rs | #![deny(trivial_casts, trivial_numeric_casts)]
extern crate byteorder;
#[macro_use] extern crate clap;
#[macro_use] extern crate enum_primitive;
extern crate num;
extern crate rand;
extern crate sdl2;
extern crate time;
use std::fs::File;
use std::io::Read;
use clap::{Arg, App};
use vm::VM;
mod cart;
mod cpu;
mod gr... | (filename: &str) -> Box<[u8]> {
let mut buffer = Vec::new();
match File::open(filename) {
Ok(ref mut file) => {
file.read_to_end(&mut buffer).unwrap();
},
Err(err) => {
println!("nesRS: cannot open '{}': {}", filename, err);
std::process::exit(-1);
... | read_rom | identifier_name |
main.rs | #![deny(trivial_casts, trivial_numeric_casts)]
extern crate byteorder;
#[macro_use] extern crate clap;
#[macro_use] extern crate enum_primitive;
extern crate num;
extern crate rand;
extern crate sdl2;
extern crate time;
use std::fs::File;
use std::io::Read;
use clap::{Arg, App};
use vm::VM;
mod cart;
mod cpu;
mod gr... | {
let mut buffer = Vec::new();
match File::open(filename) {
Ok(ref mut file) => {
file.read_to_end(&mut buffer).unwrap();
},
Err(err) => {
println!("nesRS: cannot open '{}': {}", filename, err);
std::process::exit(-1);
}
}
buffer.int... | identifier_body | |
gdb-pretty-struct-and-enums-pre-gdb-7-7.rs | // Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MI... | };
let empty_struct = EmptyStruct;
let c_style_enum1 = CStyleEnumVar1;
let c_style_enum2 = CStyleEnumVar2;
let c_style_enum3 = CStyleEnumVar3;
zzz();
}
fn zzz() { () } | random_line_split | |
gdb-pretty-struct-and-enums-pre-gdb-7-7.rs | // Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MI... | {
CStyleEnumVar1,
CStyleEnumVar2,
CStyleEnumVar3,
}
fn main() {
let regular_struct = RegularStruct {
the_first_field: 101,
the_second_field: 102.5,
the_third_field: false
};
let empty_struct = EmptyStruct;
let c_style_enum1 = CStyleEnumVar1;
let c_style_enum2... | CStyleEnum | identifier_name |
auth.rs | //! Handles authenticating an incoming request.
use actix_http::error;
use actix_http::httpmessage::HttpMessage;
use actix_service::{Service, Transform};
use actix_web::dev::{Payload, ServiceRequest, ServiceResponse};
use actix_web::{self, Error, FromRequest, HttpRequest, HttpResponse};
use futures::future::{ok, Local... | (req: &HttpRequest, _: &mut Payload) -> Self::Future {
let root = &req.app_data::<AppState>().unwrap().config.web_root;
let login_url = format!("{}/login", root);
let res = req
.extensions()
.get::<AuthenticatedUser>()
.map(Clone::clone)
.ok_or_else(|... | from_request | identifier_name |
auth.rs | //! Handles authenticating an incoming request.
use actix_http::error;
use actix_http::httpmessage::HttpMessage;
use actix_service::{Service, Transform};
use actix_web::dev::{Payload, ServiceRequest, ServiceResponse};
use actix_web::{self, Error, FromRequest, HttpRequest, HttpResponse};
use futures::future::{ok, Local... | else {
return service.borrow_mut().call(req).boxed_local();
};
async move {
let user_opt = db
.get_user_from_token(token)
.await
.map_err(error::ErrorInternalServerError)?;
if let Some(user) = user_opt {
... | {
token.value().to_string()
} | conditional_block |
auth.rs | //! Handles authenticating an incoming request.
use actix_http::error;
use actix_http::httpmessage::HttpMessage;
use actix_service::{Service, Transform};
use actix_web::dev::{Payload, ServiceRequest, ServiceResponse};
use actix_web::{self, Error, FromRequest, HttpRequest, HttpResponse};
use futures::future::{ok, Local... |
}
pub struct AuthenticateUserService<S> {
database: Arc<dyn Database>,
service: Rc<RefCell<S>>,
}
/// An authenticated user session.
///
/// Implements FromRequest so can be used as an extractor to require a valid
/// session for the endpoint.
#[derive(Clone)]
pub struct AuthenticatedUser {
pub user_id: ... | {
ok(AuthenticateUserService {
database: self.database.clone(),
service: Rc::new(RefCell::new(service)),
})
.boxed_local()
} | identifier_body |
auth.rs | //! Handles authenticating an incoming request.
use actix_http::error;
use actix_http::httpmessage::HttpMessage;
use actix_service::{Service, Transform};
use actix_web::dev::{Payload, ServiceRequest, ServiceResponse};
use actix_web::{self, Error, FromRequest, HttpRequest, HttpResponse};
use futures::future::{ok, Local... | .extensions()
.get::<Logger>()
.expect("logger no longer installed in request")
.clone();
let logger = logger.new(o!("user_id" => user.user_id.clone()));
info!(logger, "Authenticated user");
req.e... | if let Some(user) = user_opt {
let logger = req | random_line_split |
mem.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... |
/// Convert an u64 from little endian to the target's endianness.
///
/// On little endian, this is a no-op. On big endian, the bytes are swapped.
#[inline]
#[deprecated = "use `Int::from_le` instead"]
pub fn from_le64(x: u64) -> u64 { Int::from_le(x) }
/// Convert an u16 from big endian to the target's endianness.... | { Int::from_le(x) } | identifier_body |
mem.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... | ///
/// On little endian, this is a no-op. On big endian, the bytes are swapped.
#[inline]
#[deprecated = "use `Int::from_le` instead"]
pub fn from_le32(x: u32) -> u32 { Int::from_le(x) }
/// Convert an u64 from little endian to the target's endianness.
///
/// On little endian, this is a no-op. On big endian, the b... | pub fn from_le16(x: u16) -> u16 { Int::from_le(x) }
/// Convert an u32 from little endian to the target's endianness. | random_line_split |
mem.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... | (x: u16) -> u16 { x.to_le() }
/// Convert an u32 to little endian from the target's endianness.
///
/// On little endian, this is a no-op. On big endian, the bytes are swapped.
#[inline]
#[deprecated = "use `Int::to_le` instead"]
pub fn to_le32(x: u32) -> u32 { x.to_le() }
/// Convert an u64 to little endian from th... | to_le16 | identifier_name |
traits-assoc-type-in-supertrait.rs | // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... |
fn main() {
let x = sum_foo(vec![11, 10, 1].into_iter());
assert_eq!(x, 22);
}
| {
f.fold(0, |a,b| a + b)
} | identifier_body |
traits-assoc-type-in-supertrait.rs | // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | fn main() {
let x = sum_foo(vec![11, 10, 1].into_iter());
assert_eq!(x, 22);
} | random_line_split | |
traits-assoc-type-in-supertrait.rs | // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | () {
let x = sum_foo(vec![11, 10, 1].into_iter());
assert_eq!(x, 22);
}
| main | identifier_name |
line_iterator.rs | pub struct LineIterator<'a> {
data: &'a str,
line_number: usize,
line_start: usize,
line_end: usize,
done: bool
}
impl<'a> LineIterator<'a> {
pub fn new(data: &str) -> LineIterator {
LineIterator{
data,
line_number: 0,
line_start: 0,
line_... | else {
self.line_number += 1;
}
line
}
}
#[cfg(test)]
mod tests {
use super::LineIterator;
#[test]
fn next_produces_a_value_for_empty_data() {
let mut lines = LineIterator::new("");
assert_eq!(Some((0, "")), lines.next());
}
#[test]
fn next_in... | {
self.done = true;
} | conditional_block |
line_iterator.rs | pub struct LineIterator<'a> {
data: &'a str,
line_number: usize,
line_start: usize,
line_end: usize,
done: bool
}
impl<'a> LineIterator<'a> {
pub fn new(data: &str) -> LineIterator {
LineIterator{
data,
line_number: 0,
line_start: 0,
line_... | () {
let mut lines = LineIterator::new("line\nanother line\n");
assert_eq!(Some((0, "line\n")), lines.next());
assert_eq!(Some((1, "another line\n")), lines.next());
assert_eq!(Some((2, "")), lines.next());
}
#[test]
fn next_stops_at_end_of_data() {
let mut lines = L... | next_includes_trailing_newlines | identifier_name |
line_iterator.rs | pub struct LineIterator<'a> {
data: &'a str,
line_number: usize,
line_start: usize,
line_end: usize,
done: bool
}
impl<'a> LineIterator<'a> {
pub fn new(data: &str) -> LineIterator {
LineIterator{
data,
line_number: 0,
line_start: 0,
line_... |
#[test]
fn next_includes_trailing_newlines() {
let mut lines = LineIterator::new("line\nanother line\n");
assert_eq!(Some((0, "line\n")), lines.next());
assert_eq!(Some((1, "another line\n")), lines.next());
assert_eq!(Some((2, "")), lines.next());
}
#[test]
fn next... | random_line_split | |
line_iterator.rs | pub struct LineIterator<'a> {
data: &'a str,
line_number: usize,
line_start: usize,
line_end: usize,
done: bool
}
impl<'a> LineIterator<'a> {
pub fn new(data: &str) -> LineIterator |
fn out_of_data(&self) -> bool {
self.line_end == self.data.len()
}
}
impl<'a> Iterator for LineIterator<'a> {
type Item = (usize, &'a str);
fn next(&mut self) -> Option<Self::Item> {
if self.done {
return None
}
// Move the range beyond its previous posit... | {
LineIterator{
data,
line_number: 0,
line_start: 0,
line_end: 0,
done: false
}
} | identifier_body |
sched.rs | use std::mem;
use libc::{c_int, c_uint, c_void, c_ulong, pid_t};
use errno::Errno;
use {Result, Error};
pub type CloneFlags = c_uint;
pub static CLONE_VM: CloneFlags = 0x00000100;
pub static CLONE_FS: CloneFlags = 0x00000200;
pub static CLONE_FILES: CloneFlags = 0x00000400;
pub static... |
}
pub fn clone(mut cb: CloneCb, stack: &mut [u8], flags: CloneFlags) -> Result<pid_t> {
extern "C" fn callback(data: *mut CloneCb) -> c_int {
let cb: &mut CloneCb = unsafe { &mut *data };
(*cb)() as c_int
}
let res = unsafe {
let ptr = stack.as_mut_ptr().offset(stack.len() as isiz... | {
Ok(())
} | conditional_block |
sched.rs | use std::mem;
use libc::{c_int, c_uint, c_void, c_ulong, pid_t};
use errno::Errno;
use {Result, Error};
pub type CloneFlags = c_uint;
pub static CLONE_VM: CloneFlags = 0x00000100;
pub static CLONE_FS: CloneFlags = 0x00000200;
pub static CLONE_FILES: CloneFlags = 0x00000400;
pub static... | self.cpu_mask[word] = cpuset_attribs::clear_cpu_mask_flag(self.cpu_mask[word], bit);
}
}
mod ffi {
use libc::{c_void, c_int, pid_t, size_t};
use super::CpuSet;
pub type CloneCb = extern "C" fn (data: *const super::CloneCb) -> c_int;
// We cannot give a proper #[repr(C)] to super::CloneCb
... | random_line_split | |
sched.rs | use std::mem;
use libc::{c_int, c_uint, c_void, c_ulong, pid_t};
use errno::Errno;
use {Result, Error};
pub type CloneFlags = c_uint;
pub static CLONE_VM: CloneFlags = 0x00000100;
pub static CLONE_FS: CloneFlags = 0x00000200;
pub static CLONE_FILES: CloneFlags = 0x00000400;
pub static... | (data: *mut CloneCb) -> c_int {
let cb: &mut CloneCb = unsafe { &mut *data };
(*cb)() as c_int
}
let res = unsafe {
let ptr = stack.as_mut_ptr().offset(stack.len() as isize);
ffi::clone(mem::transmute(callback), ptr as *mut c_void, flags, &mut cb)
};
if res < 0 {
... | callback | identifier_name |
sched.rs | use std::mem;
use libc::{c_int, c_uint, c_void, c_ulong, pid_t};
use errno::Errno;
use {Result, Error};
pub type CloneFlags = c_uint;
pub static CLONE_VM: CloneFlags = 0x00000100;
pub static CLONE_FS: CloneFlags = 0x00000200;
pub static CLONE_FILES: CloneFlags = 0x00000400;
pub static... |
pub fn set(&mut self, field: usize) {
let word = field / cpuset_attribs::CPU_MASK_BITS;
let bit = field % cpuset_attribs::CPU_MASK_BITS;
self.cpu_mask[word] = cpuset_attribs::set_cpu_mask_flag(self.cpu_mask[word], bit);
}
pub fn unset(&mut self, field: usize) {
let word =... | {
CpuSet {
cpu_mask: unsafe { mem::zeroed() }
}
} | identifier_body |
spawn_pinned.rs | use futures_util::future::{AbortHandle, Abortable};
use std::fmt;
use std::fmt::{Debug, Formatter};
use std::future::Future;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::Arc;
use tokio::runtime::Builder;
use tokio::sync::mpsc::{unbounded_channel, UnboundedReceiver, UnboundedSender};
use tokio::sync::o... | else {
previous_task_count = new_task_count;
}
}
// It's now no longer possible for a task on the runtime to be
// associated with a LocalSet task that has completed. Drop both the
// LocalSet and runtime to let tasks on the runtime be cancelled if and
... | {
break;
} | conditional_block |
spawn_pinned.rs | use futures_util::future::{AbortHandle, Abortable};
use std::fmt;
use std::fmt::{Debug, Formatter};
use std::future::Future;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::Arc;
use tokio::runtime::Builder;
use tokio::sync::mpsc::{unbounded_channel, UnboundedReceiver, UnboundedSender};
use tokio::sync::o... | {
return (worker, JobCountGuard(Arc::clone(&worker.task_count)));
}
}
}
}
/// Automatically decrements a worker's job count when a job finishes (when
/// this gets dropped).
struct JobCountGuard(Arc<AtomicUsize>);
impl Drop for JobCountGuard {
fn drop(&mut self... | {
loop {
let (worker, task_count) = self
.workers
.iter()
.map(|worker| (worker, worker.task_count.load(Ordering::SeqCst)))
.min_by_key(|&(_, count)| count)
.expect("There must be more than one worker");
// ... | identifier_body |
spawn_pinned.rs | use futures_util::future::{AbortHandle, Abortable};
use std::fmt;
use std::fmt::{Debug, Formatter};
use std::future::Future;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::Arc;
use tokio::runtime::Builder;
use tokio::sync::mpsc::{unbounded_channel, UnboundedReceiver, UnboundedSender};
use tokio::sync::o... | (pool_size: usize) -> LocalPoolHandle {
assert!(pool_size > 0);
let workers = (0..pool_size)
.map(|_| LocalWorkerHandle::new_worker())
.collect();
let pool = Arc::new(LocalPool { workers });
LocalPoolHandle { pool }
}
/// Spawn a task onto a worker threa... | new | identifier_name |
spawn_pinned.rs | use futures_util::future::{AbortHandle, Abortable};
use std::fmt;
use std::fmt::{Debug, Formatter};
use std::future::Future;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::Arc;
use tokio::runtime::Builder;
use tokio::sync::mpsc::{unbounded_channel, UnboundedReceiver, UnboundedSender};
use tokio::sync::o... | /// ```
pub fn spawn_pinned<F, Fut>(&self, create_task: F) -> JoinHandle<Fut::Output>
where
F: FnOnce() -> Fut,
F: Send +'static,
Fut: Future +'static,
Fut::Output: Send +'static,
{
self.pool.spawn_pinned(create_task)
}
}
impl Debug for LocalPoolHandle {
... | random_line_split | |
vextracti32x4.rs | use ::{BroadcastMode, Instruction, MaskReg, MergeMode, Mnemonic, OperandSize, Reg, RoundingMode};
use ::RegType::*;
use ::instruction_def::*;
use ::Operand::*;
use ::Reg::*;
use ::RegScale::*;
fn | () {
run_test(&Instruction { mnemonic: Mnemonic::VEXTRACTI32x4, operand1: Some(Direct(XMM5)), operand2: Some(Direct(ZMM0)), operand3: Some(Literal8(65)), operand4: None, lock: false, rounding_mode: None, merge_mode: Some(MergeMode::Zero), sae: false, mask: Some(MaskReg::K2), broadcast: None }, &[98, 243, 125, 202, ... | vextracti32x4_1 | identifier_name |
vextracti32x4.rs | use ::{BroadcastMode, Instruction, MaskReg, MergeMode, Mnemonic, OperandSize, Reg, RoundingMode};
use ::RegType::*;
use ::instruction_def::*;
use ::Operand::*;
use ::Reg::*;
use ::RegScale::*;
fn vextracti32x4_1() {
run_test(&Instruction { mnemonic: Mnemonic::VEXTRACTI32x4, operand1: Some(Direct(XMM5)), operand2: ... |
fn vextracti32x4_3() {
run_test(&Instruction { mnemonic: Mnemonic::VEXTRACTI32x4, operand1: Some(Direct(XMM30)), operand2: Some(Direct(ZMM5)), operand3: Some(Literal8(61)), operand4: None, lock: false, rounding_mode: None, merge_mode: Some(MergeMode::Zero), sae: false, mask: Some(MaskReg::K1), broadcast: None }, ... | {
run_test(&Instruction { mnemonic: Mnemonic::VEXTRACTI32x4, operand1: Some(IndirectScaledDisplaced(EDX, Eight, 1098025544, Some(OperandSize::Xmmword), None)), operand2: Some(Direct(ZMM1)), operand3: Some(Literal8(15)), operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broa... | identifier_body |
vextracti32x4.rs | use ::{BroadcastMode, Instruction, MaskReg, MergeMode, Mnemonic, OperandSize, Reg, RoundingMode};
use ::RegType::*;
use ::instruction_def::*;
use ::Operand::*;
use ::Reg::*;
use ::RegScale::*;
fn vextracti32x4_1() { | fn vextracti32x4_2() {
run_test(&Instruction { mnemonic: Mnemonic::VEXTRACTI32x4, operand1: Some(IndirectScaledDisplaced(EDX, Eight, 1098025544, Some(OperandSize::Xmmword), None)), operand2: Some(Direct(ZMM1)), operand3: Some(Literal8(15)), operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: fa... | run_test(&Instruction { mnemonic: Mnemonic::VEXTRACTI32x4, operand1: Some(Direct(XMM5)), operand2: Some(Direct(ZMM0)), operand3: Some(Literal8(65)), operand4: None, lock: false, rounding_mode: None, merge_mode: Some(MergeMode::Zero), sae: false, mask: Some(MaskReg::K2), broadcast: None }, &[98, 243, 125, 202, 57, 1... | random_line_split |
primitives.rs | use crate::ast::expressions;
use crate::ast::lexer::tokens;
use crate::ast::parser;
use crate::ast::stack;
use std::string::String as StdString;
#[derive(Debug, Clone)]
pub struct Nil;
impl expressions::Expression for Nil {}
impl Nil {
make_keyword_rule![rule, (tokens::Keyword::NIL, Nil)];
}
#[derive(Debug, Clo... | impl expressions::Expression for Number {}
impl Number {
pub fn rule(parser: &mut parser::Parser, stack: &mut stack::Stack) -> bool {
if let Some(tokens::Token {
token: tokens::TokenType::Number(number),
..
}) = parser.peek().cloned()
{
parser.shift();
... |
#[derive(Debug, Clone)]
pub struct Number(pub f64); | random_line_split |
primitives.rs | use crate::ast::expressions;
use crate::ast::lexer::tokens;
use crate::ast::parser;
use crate::ast::stack;
use std::string::String as StdString;
#[derive(Debug, Clone)]
pub struct Nil;
impl expressions::Expression for Nil {}
impl Nil {
make_keyword_rule![rule, (tokens::Keyword::NIL, Nil)];
}
#[derive(Debug, Clo... | (pub StdString);
impl expressions::Expression for String {}
impl String {
pub fn rule(parser: &mut parser::Parser, stack: &mut stack::Stack) -> bool {
if let Some(tokens::Token {
token: tokens::TokenType::String(string),
..
}) = parser.peek().cloned()
{
pa... | String | identifier_name |
primitives.rs | use crate::ast::expressions;
use crate::ast::lexer::tokens;
use crate::ast::parser;
use crate::ast::stack;
use std::string::String as StdString;
#[derive(Debug, Clone)]
pub struct Nil;
impl expressions::Expression for Nil {}
impl Nil {
make_keyword_rule![rule, (tokens::Keyword::NIL, Nil)];
}
#[derive(Debug, Clo... | else {
false
}
}
}
| {
parser.shift();
stack.push_single(Box::new(String(string)));
true
} | conditional_block |
glyph.rs | u8 = 0x0;
static BREAK_TYPE_NORMAL: u8 = 0x1;
static BREAK_TYPE_HYPHEN: u8 = 0x2;
fn break_flag_to_enum(flag: u8) -> BreakType {
if (flag & BREAK_TYPE_NORMAL)!= 0 {
BreakType::Normal
} else if (flag & BREAK_TYPE_HYPHEN)!= 0 {
BreakType::Hyphen
} else {
BreakType::None
}
}
fn ... | (advance: Au) -> bool {
let unsigned_au = advance.to_u32().unwrap();
(unsigned_au & (GLYPH_ADVANCE_MASK >> GLYPH_ADVANCE_SHIFT as uint)) == unsigned_au
}
type DetailedGlyphCount = u16;
// Getters and setters for GlyphEntry. Setter methods are functional,
// because GlyphEntry is immutable and only a u32 in si... | is_simple_advance | identifier_name |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.