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 |
|---|---|---|---|---|
symdumper.rs | use std::ffi::OsStr;
use std::os::windows::ffi::OsStrExt;
use std::iter::once;
use std::process::Command;
use std::io::{Error, ErrorKind};
use crate::win32::ModuleInfo;
type HANDLE = usize;
extern {
fn GetCurrentProcess() -> HANDLE;
}
#[allow(non_snake_case)]
#[repr(C)]
struct SrcCodeInfoW {
SizeOfStruct: u3... |
}
#[allow(non_snake_case)]
#[repr(C)]
struct ImagehlpModule64W {
SizeOfStruct: u32,
BaseOfImage: u64,
ImageSize: u32,
TimeDateStamp: u32,
CheckSum: u32,
NumSyms: u32,
SymType: u32,
ModuleName: [u16; 32],
ImageName: [u16; 256],
LoadedImageName: [u16; 256],
LoadedPdbName: [u1... | {
ImagehlpLineW64 {
SizeOfStruct: std::mem::size_of::<ImagehlpLineW64>() as u32,
Key: 0,
LineNumber: 0,
FileName: std::ptr::null(),
Address: 0,
}
} | identifier_body |
symdumper.rs | use std::ffi::OsStr;
use std::os::windows::ffi::OsStrExt;
use std::iter::once;
use std::process::Command;
use std::io::{Error, ErrorKind};
use crate::win32::ModuleInfo;
type HANDLE = usize;
extern {
fn GetCurrentProcess() -> HANDLE;
}
#[allow(non_snake_case)]
#[repr(C)]
struct | {
SizeOfStruct: u32,
Key: usize,
ModBase: u64,
Obj: [u16; 261],
FileName: [u16; 261],
LineNumber: u32,
Address: u64,
}
impl Default for SrcCodeInfoW {
fn default() -> Self {
SrcCodeInfoW {
SizeOfStruct: std::mem::size_of::<SrcCodeInfoW>() as u32,
Key: 0,... | SrcCodeInfoW | identifier_name |
symdumper.rs | use std::ffi::OsStr;
use std::os::windows::ffi::OsStrExt;
use std::iter::once;
use std::process::Command;
use std::io::{Error, ErrorKind};
use crate::win32::ModuleInfo;
type HANDLE = usize;
extern {
fn GetCurrentProcess() -> HANDLE;
}
#[allow(non_snake_case)]
#[repr(C)]
struct SrcCodeInfoW {
SizeOfStruct: u3... |
// Symchk apparently ran, check output
let stderr = std::str::from_utf8(&res.stderr)
.expect("Failed to convert symchk output to utf-8");
let mut filename = None;
for line in stderr.lines() {
const PREFIX: &'static str = "DBGHELP: ";
const POSTFIX: &'static str = " - OK";
... | {
return Err(Error::new(ErrorKind::Other, "symchk returned with error"));
} | conditional_block |
cursor_renderer.rs | use std::time::{Duration, Instant};
use skulpin::skia_safe::{Canvas, Paint, Path, Point};
use crate::renderer::CachingShaper;
use crate::editor::{EDITOR, Colors, Cursor, CursorShape};
use crate::redraw_scheduler::REDRAW_SCHEDULER;
const AVERAGE_MOTION_PERCENTAGE: f32 = 0.7;
const MOTION_PERCENTAGE_SPREAD: f... | match self.state {
BlinkState::Waiting | BlinkState::Off => false,
BlinkState::On => true
}
}
}
#[derive(Debug, Clone)]
pub struct Corner {
pub current_position: Point,
pub relative_position: Point,
}
impl Corner {
pub fn new(relative_position: Poi... |
if let Some(scheduled_frame) = scheduled_frame {
REDRAW_SCHEDULER.schedule(scheduled_frame);
}
| random_line_split |
cursor_renderer.rs | use std::time::{Duration, Instant};
use skulpin::skia_safe::{Canvas, Paint, Path, Point};
use crate::renderer::CachingShaper;
use crate::editor::{EDITOR, Colors, Cursor, CursorShape};
use crate::redraw_scheduler::REDRAW_SCHEDULER;
const AVERAGE_MOTION_PERCENTAGE: f32 = 0.7;
const MOTION_PERCENTAGE_SPREAD: f... | (&mut self,
cursor: Cursor, default_colors: &Colors,
font_width: f32, font_height: f32,
paint: &mut Paint, shaper: &mut CachingShaper,
canvas: &mut Canvas) {
let render = self.blink_status.update_status(&cursor);
self.previous_position = {
... | draw | identifier_name |
cursor_renderer.rs | use std::time::{Duration, Instant};
use skulpin::skia_safe::{Canvas, Paint, Path, Point};
use crate::renderer::CachingShaper;
use crate::editor::{EDITOR, Colors, Cursor, CursorShape};
use crate::redraw_scheduler::REDRAW_SCHEDULER;
const AVERAGE_MOTION_PERCENTAGE: f32 = 0.7;
const MOTION_PERCENTAGE_SPREAD: f... | BlinkState::On => new_cursor.blinkon
}.filter(|millis| millis > &0).map(|millis| Duration::from_millis(millis));
if delay.map(|delay| self.last_transition + delay < Instant::now()).unwrap_or(false) {
self.state = match self.state {
BlinkState::Waiting => Bli... | {
if self.previous_cursor.is_none() || new_cursor != self.previous_cursor.as_ref().unwrap() {
self.previous_cursor = Some(new_cursor.clone());
self.last_transition = Instant::now();
if new_cursor.blinkwait.is_some() && new_cursor.blinkwait != Some(0) {
se... | identifier_body |
reader.rs | use std::sync::mpsc::{Receiver, Sender, SyncSender, channel};
use std::error::Error;
use item::Item;
use std::sync::{Arc, RwLock};
use std::process::{Command, Stdio, Child};
use std::io::{BufRead, BufReader};
use event::{EventSender, EventReceiver, Event, EventArg};
use std::thread::JoinHandle;
use std::thread;
use std... | .filter_map(|string| {
parse_range(string)
}).collect();
}
if options.is_present("read0") {
self.line_ending = b'\0';
}
}
}
pub struct Reader {
rx_cmd: EventReceiver,
tx_item: SyncSender<(Event, EventArg)>,
option:... | {
if options.is_present("ansi") {
self.use_ansi_color = true;
}
if let Some(delimiter) = options.value_of("delimiter") {
self.delimiter = Regex::new(&(".*?".to_string() + delimiter))
.unwrap_or_else(|_| Regex::new(r".*?[\t ]").unwrap());
}
... | identifier_body |
reader.rs | use std::sync::mpsc::{Receiver, Sender, SyncSender, channel};
use std::error::Error;
use item::Item;
use std::sync::{Arc, RwLock};
use std::process::{Command, Stdio, Child};
use std::io::{BufRead, BufReader};
use event::{EventSender, EventReceiver, Event, EventArg};
use std::thread::JoinHandle;
use std::thread;
use std... | (&mut self) {
// event loop
let mut thread_reader: Option<JoinHandle<()>> = None;
let mut tx_reader: Option<Sender<bool>> = None;
let mut last_command = "".to_string();
let mut last_query = "".to_string();
// start sender
let (tx_sender, rx_sender) = channel();
... | run | identifier_name |
reader.rs | use std::sync::mpsc::{Receiver, Sender, SyncSender, channel};
use std::error::Error;
use item::Item;
use std::sync::{Arc, RwLock};
use std::process::{Command, Stdio, Child};
use std::io::{BufRead, BufReader};
use event::{EventSender, EventReceiver, Event, EventArg};
use std::thread::JoinHandle;
use std::thread;
use std... |
}
Err(_err) => {} // String not UTF8 or other error, skip.
}
}
if!item_group.is_empty() {
let _ = tx_sender.send((Event::EvReaderNewItem, Box::new(mem::replace(&mut item_group, Vec::new()))));
}
let _ = tx_control.send(true);
}
| {
let _ = tx_sender.send((Event::EvReaderNewItem, Box::new(mem::replace(&mut item_group, Vec::new()))));
} | conditional_block |
reader.rs | use std::sync::mpsc::{Receiver, Sender, SyncSender, channel};
use std::error::Error;
use item::Item;
use std::sync::{Arc, RwLock};
use std::process::{Command, Stdio, Child};
use std::io::{BufRead, BufReader};
use event::{EventSender, EventReceiver, Event, EventArg};
use std::thread::JoinHandle;
use std::thread;
use std... | }
}
pub fn parse_options(&mut self, options: &ArgMatches) {
if options.is_present("ansi") {
self.use_ansi_color = true;
}
if let Some(delimiter) = options.value_of("delimiter") {
self.delimiter = Regex::new(&(".*?".to_string() + delimiter))
... | matching_fields: Vec::new(),
delimiter: Regex::new(r".*?\t").unwrap(),
replace_str: "{}".to_string(),
line_ending: b'\n', | random_line_split |
main.rs | //! A simple demonstration of how to construct and use Canvasses by splitting up the window.
#[macro_use] extern crate conrod;
#[macro_use] extern crate serde_derive;
extern crate chrono;
extern crate serde;
mod support;
fn main() {
feature::main();
}
mod feature {
const FILENAME : &str = "timetracker.json"... | widget_ids! {
struct ListItem {
master,
toggle,
remove,
name,
time,
session,
}
}
} | random_line_split | |
main.rs | //! A simple demonstration of how to construct and use Canvasses by splitting up the window.
#[macro_use] extern crate conrod;
#[macro_use] extern crate serde_derive;
extern crate chrono;
extern crate serde;
mod support;
fn main() {
feature::main();
}
mod feature {
const FILENAME : &str = "timetracker.json"... | let font_path = assets.join("fonts/NotoSans/NotoSans-Regular.ttf");
ui.fonts.insert_from_file(font_path).unwrap();
// A type used for converting `conrod::render::Primitives` into `Command`s that can be used
// for drawing to the glium `Surface`.
let mut renderer = conrod::backen... | {
const WIDTH: u32 = 800;
const HEIGHT: u32 = 600;
const SLEEPTIME: Duration = Duration::from_millis(500);
// Build the window.
let mut events_loop = glium::glutin::EventsLoop::new();
let window = glium::glutin::WindowBuilder::new()
.with_title("Timetracker")... | identifier_body |
main.rs | //! A simple demonstration of how to construct and use Canvasses by splitting up the window.
#[macro_use] extern crate conrod;
#[macro_use] extern crate serde_derive;
extern crate chrono;
extern crate serde;
mod support;
fn main() {
feature::main();
}
mod feature {
const FILENAME : &str = "timetracker.json"... | (t : chrono::DateTime<Utc>) -> String {
let dur = t.signed_duration_since(chrono::MIN_DATE.and_hms(0u32,0u32,0u32));
let ret = format!(
"{:02}:{:02}:{:02}",
dur.num_hours(),
dur.num_minutes()%60,
dur.num_seconds()%60
);
ret
}
fn dur... | format_time | identifier_name |
main.rs | //! A simple demonstration of how to construct and use Canvasses by splitting up the window.
#[macro_use] extern crate conrod;
#[macro_use] extern crate serde_derive;
extern crate chrono;
extern crate serde;
mod support;
fn main() {
feature::main();
}
mod feature {
const FILENAME : &str = "timetracker.json"... | ,
Enter => {
timerstates.push(support::TimerState::new(text.clone()));
},
}
}
for _press in widget::Button::new()
.h(50.)
.w(50.)
.label("+")
.bottom_right_of(ids.tab_timers)
... | {
*text = txt;
} | conditional_block |
function_system.rs | bool,
pub(crate) last_run: Tick,
}
impl SystemMeta {
pub(crate) fn new<T>() -> Self {
Self {
name: std::any::type_name::<T>().into(),
archetype_component_access: Access::default(),
component_access_set: FilteredAccessSet::default(),
is_send: true,
... |
#[inline]
fn is_exclusive(&self) -> bool {
false
}
#[inline]
unsafe fn run_unsafe(&mut self, input: Self::In, world: UnsafeWorldCell) -> Self::Out {
let change_tick = world.increment_change_tick();
// SAFETY:
// - The caller has invoked `update_archetype_component... | {
self.system_meta.is_send
} | identifier_body |
function_system.rs | : bool,
pub(crate) last_run: Tick,
}
impl SystemMeta {
pub(crate) fn new<T>() -> Self {
Self {
name: std::any::type_name::<T>().into(),
archetype_component_access: Access::default(),
component_access_set: FilteredAccessSet::default(),
is_send: true,
... |
impl<Param: SystemParam> SystemState<Param> {
/// Creates a new [`SystemState`] with default state.
///
/// ## Note
/// For users of [`SystemState::get_manual`] or [`get_manual_mut`](SystemState::get_manual_mut):
///
/// `new` does not cache any of the world's archetypes, so you must call [`Sys... | world_id: WorldId,
archetype_generation: ArchetypeGeneration,
} | random_line_split |
function_system.rs | bool,
pub(crate) last_run: Tick,
}
impl SystemMeta {
pub(crate) fn new<T>() -> Self {
Self {
name: std::any::type_name::<T>().into(),
archetype_component_access: Access::default(),
component_access_set: FilteredAccessSet::default(),
is_send: true,
... | (&self, world_id: WorldId) {
assert!(self.matches_world(world_id), "Encountered a mismatched World. A SystemState cannot be used with Worlds other than the one it was created with.");
}
/// Updates the state's internal view of the [`World`]'s archetypes. If this is not called before fetching the parame... | validate_world | identifier_name |
cellgrid.rs | use ggez::graphics;
use ggez::GameResult;
use ggez::nalgebra as na;
use crate::simulation::{SimGrid, Automaton};
use crate::commons::cells::BinaryCell;
use crate::commons::grids::CellGrid;
use crate::gameoflife::GameOfLife;
/// Implementation of the Automaton trait for GameOfLife with a CellGrid grid,
impl Automaton ... | }
// Assign the new grid to the grid struct
self.grid.setgrid(newgrid);
}
// Update the alive and dead cell value in the grid struct
self.alive = alive;
self.dead = dead;
// Increment the generation value in the grid struct
self.gener... | BinaryCell::Active => alive += 1
} | random_line_split |
cellgrid.rs | use ggez::graphics;
use ggez::GameResult;
use ggez::nalgebra as na;
use crate::simulation::{SimGrid, Automaton};
use crate::commons::cells::BinaryCell;
use crate::commons::grids::CellGrid;
use crate::gameoflife::GameOfLife;
/// Implementation of the Automaton trait for GameOfLife with a CellGrid grid,
impl Automaton ... |
// A method that returns the graphics blending mode of the automaton grid
fn blend_mode(&self) -> Option<graphics::BlendMode> {
Some(graphics::BlendMode::Add)
}
// A method that set the graphics blend mode of the automaton grid (currently does nothing)
fn set_blend_mode(&mut self, _: Opti... | {
// Get the grid dimesions and add the banner height
if let Some(dimensions) = &self.grid.dimensions {
Some(graphics::Rect::new(0.0, 0.0, dimensions.w, dimensions.h + 60.0))
} else {None}
} | identifier_body |
cellgrid.rs | use ggez::graphics;
use ggez::GameResult;
use ggez::nalgebra as na;
use crate::simulation::{SimGrid, Automaton};
use crate::commons::cells::BinaryCell;
use crate::commons::grids::CellGrid;
use crate::gameoflife::GameOfLife;
/// Implementation of the Automaton trait for GameOfLife with a CellGrid grid,
impl Automaton ... | (&self) -> String {
format!("Conway's Game of Life | Grid | {}", self.initialstate)
}
}
// Implementation of helper methods for GameOfLife with a CellGrid grid,
impl GameOfLife<CellGrid<BinaryCell>> {
// A function that retrieves the number of alive cells in
// the neighbouring vicity of a given c... | fullname | identifier_name |
instance.rs | // write the whole struct into place over the uninitialized page
ptr::write(&mut *handle, inst);
};
handle.reset()?;
Ok(handle)
}
pub fn instance_handle_to_raw(inst: InstanceHandle) -> *mut Instance {
let ptr = inst.inst.as_ptr();
std::mem::forget(inst);
ptr
}
pub unsafe fn ins... | {
/// If true, the instance's `fatal_handler` will be called.
pub fatal: bool,
/// Information about the type of fault that occurred.
pub trapcode: TrapCode,
/// The instruction pointer where the fault occurred.
pub rip_addr: uintptr_t,
/// Extra information about the instruction pointer's ... | FaultDetails | identifier_name |
instance.rs | // write the whole struct into place over the uninitialized page
ptr::write(&mut *handle, inst);
};
handle.reset()?;
Ok(handle)
}
pub fn instance_handle_to_raw(inst: InstanceHandle) -> *mut Instance {
let ptr = inst.inst.as_ptr();
std::mem::forget(inst);
ptr
}
pub unsafe fn in... | pub fn globals(&self) -> &[i64] {
unsafe { self.alloc.globals() }
}
/// Return the WebAssembly globals as a mutable slice of `i64`s.
pub fn globals_mut(&mut self) -> &mut [i64] {
unsafe { self.alloc.globals_mut() }
}
/// Check whether a given range in the host address space ove... | random_line_split | |
instance.rs | // write the whole struct into place over the uninitialized page
ptr::write(&mut *handle, inst);
};
handle.reset()?;
Ok(handle)
}
pub fn instance_handle_to_raw(inst: InstanceHandle) -> *mut Instance {
let ptr = inst.inst.as_ptr();
std::mem::forget(inst);
ptr
}
pub unsafe fn ins... | Err(Error::RuntimeFault(details.clone()))
}
} else {
panic!("state remains Fault after populate_fault_detail()")
}
}
State::Ready {.. } => {
panic!("instance in Ready state after retu... | {
// Sandbox is no longer runnable. It's unsafe to determine all error details in the signal
// handler, so we fill in extra details here.
self.populate_fault_detail()?;
if let State::Fault { ref details, .. } = self.state {
if details.... | conditional_block |
instance.rs | // write the whole struct into place over the uninitialized page
ptr::write(&mut *handle, inst);
};
handle.reset()?;
Ok(handle)
}
pub fn instance_handle_to_raw(inst: InstanceHandle) -> *mut Instance {
let ptr = inst.inst.as_ptr();
std::mem::forget(inst);
ptr
}
pub unsafe fn ins... |
/// Get a mutable reference to the instance's `Alloc`.
fn alloc_mut(&mut self) -> &mut Alloc {
&mut self.alloc
}
/// Get a reference to the instance's `Module`.
fn module(&self) -> &dyn Module {
self.module.deref()
}
/// Get a reference to the instance's `State`.
fn s... | {
&self.alloc
} | identifier_body |
queued.rs | // Copyright (c) 2013-2016 Sandstorm Development Group, Inc. and contributors
// Licensed under the MIT License:
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, inc... | (&self) -> Box<dyn PipelineHook> {
Box::new(self.clone())
}
fn get_pipelined_cap(&self, ops: &[PipelineOp]) -> Box<dyn ClientHook> {
self.get_pipelined_cap_move(ops.into())
}
fn get_pipelined_cap_move(&self, ops: Vec<PipelineOp>) -> Box<dyn ClientHook> {
if let Some(p) = &self.i... | add_ref | identifier_name |
queued.rs | // Copyright (c) 2013-2016 Sandstorm Development Group, Inc. and contributors
// Licensed under the MIT License:
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, inc... | client_resolution_queue: SenderQueue<(), Box<dyn ClientHook>>,
}
impl ClientInner {
pub fn resolve(state: &Rc<RefCell<Self>>, result: Result<Box<dyn ClientHook>, Error>) {
assert!(state.borrow().redirect.is_none());
let client = match result {
Ok(clienthook) => clienthook,
... | // delivered after calls made earlier), but *before* any queued calls return (because it might
// confuse the application if a queued call returns before the capability on which it was made
// resolves). Luckily, we know that queued calls will involve, at the very least, an
// eventLoop.evalLater. | random_line_split |
framework.rs | surface: wgpu::Surface,
adapter: wgpu::Adapter,
device: wgpu::Device,
queue: wgpu::Queue,
#[cfg(target_arch = "wasm32")]
offscreen_canvas_setup: Option<OffscreenCanvasSetup>,
}
#[cfg(target_arch = "wasm32")]
struct OffscreenCanvasSetup {
offscreen_canvas: OffscreenCanvas,
bitmap_renderer... |
#[cfg(target_arch = "wasm32")]
pub struct Spawner {}
#[cfg(target_arch = "wasm32")]
impl Spawner {
fn new() -> Self {
Self {}
}
#[allow(dead_code)]
pub fn spawn_local(&self, future: impl Future<Output = ()> +'static) {
wasm_bindgen_futures::spawn_local(future);
}
}
#[cfg(not(targ... | fn run_until_stalled(&self) {
while self.executor.try_tick() {}
}
} | random_line_split |
framework.rs | surface: wgpu::Surface,
adapter: wgpu::Adapter,
device: wgpu::Device,
queue: wgpu::Queue,
#[cfg(target_arch = "wasm32")]
offscreen_canvas_setup: Option<OffscreenCanvasSetup>,
}
#[cfg(target_arch = "wasm32")]
struct OffscreenCanvasSetup {
offscreen_canvas: OffscreenCanvas,
bitmap_renderer:... | let level: log::Level = parse_url_query_string(&query_string, "RUST_LOG")
.and_then(|x| x.parse().ok())
.unwrap_or(log::Level::Error);
console_log::init_with_level(level).expect("could not initialize logger");
std::panic::set_hook(Box::new(console_error_panic_hook::hook));
... | {
#[cfg(not(target_arch = "wasm32"))]
{
env_logger::init();
};
let event_loop = EventLoop::new();
let mut builder = winit::window::WindowBuilder::new();
builder = builder.with_title(title);
#[cfg(windows_OFF)] // TODO
{
use winit::platform::windows::WindowBuilderExtWindo... | identifier_body |
framework.rs | surface: wgpu::Surface,
adapter: wgpu::Adapter,
device: wgpu::Device,
queue: wgpu::Queue,
#[cfg(target_arch = "wasm32")]
offscreen_canvas_setup: Option<OffscreenCanvasSetup>,
}
#[cfg(target_arch = "wasm32")]
struct OffscreenCanvasSetup {
offscreen_canvas: OffscreenCanvas,
bitmap_renderer:... |
};
let view = frame.texture.create_view(&wgpu::TextureViewDescriptor {
format: Some(surface_view_format),
..wgpu::TextureViewDescriptor::default()
});
example.render(&view, &device, &queue, &spawner);
... | {
surface.configure(&device, &config);
surface
.get_current_texture()
.expect("Failed to acquire next surface texture!")
} | conditional_block |
framework.rs | surface: wgpu::Surface,
adapter: wgpu::Adapter,
device: wgpu::Device,
queue: wgpu::Queue,
#[cfg(target_arch = "wasm32")]
offscreen_canvas_setup: Option<OffscreenCanvasSetup>,
}
#[cfg(target_arch = "wasm32")]
struct OffscreenCanvasSetup {
offscreen_canvas: OffscreenCanvas,
bitmap_renderer:... | <E: Example>(title: &str) {
use wasm_bindgen::prelude::*;
let title = title.to_owned();
wasm_bindgen_futures::spawn_local(async move {
let setup = setup::<E>(&title).await;
let start_closure = Closure::once_into_js(move || start::<E>(setup));
// make sure to handle JS exceptions th... | run | identifier_name |
main.rs | use std::convert::Infallible;
use hyper::{Body, Request, Response, Server};
use hyper::service::{make_service_fn, service_fn};
mod github;
mod zulip;
const BOT_NAME: &'static str = "bisect-bot ";
const USER_AGENT: &'static str = "https://github.com/bjorn3/cargo-bisect-rustc-bot";
const REPO_WHITELIST: &'static [&'sta... | cmds.push(format!("--end={}", end));
println!("{:?}", &cmds);
push_job(&reply_to, comment_id, &cmds, &code).await?;
}
None => {}
}
Ok(())
}
async fn push_job(reply_to: &ReplyTo, job_id: &str, bisect_cmds: &[String], repro: &str) -> reqwest::Result<()> {
... | } | random_line_split |
main.rs | use std::convert::Infallible;
use hyper::{Body, Request, Response, Server};
use hyper::service::{make_service_fn, service_fn};
mod github;
mod zulip;
const BOT_NAME: &'static str = "bisect-bot ";
const USER_AGENT: &'static str = "https://github.com/bjorn3/cargo-bisect-rustc-bot";
const REPO_WHITELIST: &'static [&'sta... | else if part.starts_with("end=") {
if end.is_some() {
return Err(format!("end range specified twice"));
}
end = Some(part["end=".len()..].to_string());
} else {
... | {
if start.is_some() {
return Err(format!("start range specified twice"));
}
start = Some(part["start=".len()..].to_string());
} | conditional_block |
main.rs | use std::convert::Infallible;
use hyper::{Body, Request, Response, Server};
use hyper::service::{make_service_fn, service_fn};
mod github;
mod zulip;
const BOT_NAME: &'static str = "bisect-bot ";
const USER_AGENT: &'static str = "https://github.com/bjorn3/cargo-bisect-rustc-bot";
const REPO_WHITELIST: &'static [&'sta... | {
path: String,
mode: TreeEntryMode,
#[serde(rename = "type")]
type_: TreeEntryType,
sha: String,
}
#[derive(serde::Serialize)]
enum TreeEntryMode {
#[serde(rename = "100644")]
File,
#[serde(rename = "100755")]
Executable,
#[serde(rename = "040000")]
Subdirectory,
#[ser... | TreeEntry | identifier_name |
context.rs | (pub u64);
#[derive(Copy, Clone, Debug, Hash, PartialEq)]
pub struct PassHandle(pub u64);
#[derive(Copy, Clone, Debug, Hash, PartialEq)]
pub struct ImageHandle(pub u64);
#[derive(Copy, Clone, Debug, Hash, PartialEq)]
pub struct ShaderHandle(pub u64);
pub struct Context {
window: winit::window::Window,
event_lo... | GraphHandle | identifier_name | |
context.rs | pub swapchain_idx: usize, // Index of the swapchain frame
_watcher: notify::RecommendedWatcher, // Need to keep this alive to keep the receiver alive
watch_rx: std::sync::mpsc::Receiver<notify::DebouncedEvent>,
pub command_buffers: Vec<vk::CommandBuffer>,
pub facade: Facade, // Resolution-dependent a... | &mut self.image_list,
&self.debug_utils,
);
// Recreate the images which depend on the resolution of the swapchain
for i in 0..self.image_list.list.len() {
let (_, internal_image) = &mut self.image_list.list[i];
if let ImageKind::RelativeSized { sc... | random_line_split | |
context.rs | &internal_image.image.name,
w,
h,
internal_image.image.format,
internal_image.image.usage,
internal_image.image.aspect_flags,
&self.gpu,
&self.debug_utils,
... | {
self.image_list.new_image_from_file(
name,
path,
&self.gpu,
self.command_pool,
&self.debug_utils,
)
} | identifier_body | |
context.rs | swapchain_idx: usize, // Index of the swapchain frame
_watcher: notify::RecommendedWatcher, // Need to keep this alive to keep the receiver alive
watch_rx: std::sync::mpsc::Receiver<notify::DebouncedEvent>,
pub command_buffers: Vec<vk::CommandBuffer>,
pub facade: Facade, // Resolution-dependent appar... |
_ => (),
}
});
// This mechanism is need on Windows:
if resize_needed {
self.recreate_resolution_dependent_state();
}
// This mechanism suffices on Linux:
// Acquiring the swapchain image fails if the window has been resized. If ... | {
*control_flow = ControlFlow::Exit;
} | conditional_block |
ner.rs | // Copyright 2019-present, the HuggingFace Inc. team, The Google AI Language Team and Facebook, Inc.
// Copyright (c) 2018 chakki (https://github.com/chakki-works/seqeval/blob/master/seqeval/metrics/sequence_labeling.py)
// Copyright 2019 Guillaume Becquin
// Licensed under the Apache License, Version 2.0 (the "License... |
fn consolidate_entities(tokens: &[Token]) -> Vec<Entity> {
let mut entities: Vec<Entity> = Vec::new();
let mut entity_builder = EntityBuilder::new();
for (position, token) in tokens.iter().enumerate() {
let tag = token.get_tag();
let label = token.get_label();
... |
let tokens = self.token_classification_model.predict(input, true, false);
let mut entities: Vec<Vec<Entity>> = Vec::new();
for sequence_tokens in tokens {
entities.push(Self::consolidate_entities(&sequence_tokens));
}
entities
}
| identifier_body |
ner.rs | // Copyright 2019-present, the HuggingFace Inc. team, The Google AI Language Team and Facebook, Inc.
// Copyright (c) 2018 chakki (https://github.com/chakki-works/seqeval/blob/master/seqeval/metrics/sequence_labeling.py)
// Copyright 2019 Guillaume Becquin
// Licensed under the Apache License, Version 2.0 (the "License... | }
}
fn flush_and_reset(&mut self, position: usize, tokens: &[Token]) -> Option<Entity> {
let entity = if let Some((start, _, label)) = self.previous_node {
let entity_tokens = &tokens[start..position];
Some(Entity {
word: entity_tokens
... |
if let Some((_, previous_tag, previous_label)) = self.previous_node {
if (previous_tag == Tag::End)
| (previous_tag == Tag::Single)
| (previous_label != label)
{
let entity = self.flush_and_r... | conditional_block |
ner.rs | // Copyright 2019-present, the HuggingFace Inc. team, The Google AI Language Team and Facebook, Inc.
// Copyright (c) 2018 chakki (https://github.com/chakki-works/seqeval/blob/master/seqeval/metrics/sequence_labeling.py)
// Copyright 2019 Guillaume Becquin
// Licensed under the Apache License, Version 2.0 (the "License... |
&mut self,
tag: Tag,
label: &'a str,
position: usize,
tokens: &[Token],
) -> Option<Entity> {
match tag {
Tag::Outside => self.flush_and_reset(position, tokens),
Tag::Begin | Tag::Single => {
let entity = self.flush_and_reset(p... | andle_current_tag( | identifier_name |
ner.rs | // Copyright 2019-present, the HuggingFace Inc. team, The Google AI Language Team and Facebook, Inc.
// Copyright (c) 2018 chakki (https://github.com/chakki-works/seqeval/blob/master/seqeval/metrics/sequence_labeling.py)
// Copyright 2019 Guillaume Becquin
// Licensed under the Apache License, Version 2.0 (the "License... | //! device: Device::cuda_if_available(),
//! ..Default::default()
//! };
//!
//! let ner_model = NERModel::new(ner_config)?;
//!
//! // Define input
//! let input = [
//! "Mein Name ist Amélie. Ich lebe in Paris.",
//! "Paris ist eine Stadt in Frankreich.",
//! ];
//! let output = ner_model.predict(&i... | //! lower_case: false, | random_line_split |
detours.rs | #![allow(non_camel_case_types)]
extern crate winapi;
extern crate kernel32;
extern crate field_offset;
use winapi::*;
#[allow(unused_imports)]
use self::field_offset::*;
use std::mem;
use std::ffi::CStr;
use std::ptr::null_mut;
use std::iter::once;
use std::ffi::OsStr;
use std::os::windows::ffi::OsStrExt;
// Copie... | {
module: HMODULE,
}
impl Module {
#[allow(dead_code)]
pub fn target(moduleName: &str) -> Option<Module> {
let mut library = Module { module: 0 as HMODULE };
let wModuleName: Vec<u16> = OsStr::new(moduleName)
.encode_wide()
.chain(once(0))
.collect();
... | Module | identifier_name |
detours.rs | #![allow(non_camel_case_types)]
extern crate winapi;
extern crate kernel32;
extern crate field_offset;
use winapi::*;
#[allow(unused_imports)]
use self::field_offset::*;
use std::mem;
use std::ffi::CStr;
use std::ptr::null_mut;
use std::iter::once;
use std::ffi::OsStr;
use std::os::windows::ffi::OsStrExt;
// Copie... | // TODO: Think about adding support for IMAGE_FILE_MACHINE_AMD64 later
return None;
}
let import_desc_array: PIMAGE_IMPORT_DESCRIPTOR = unsafe {
mem::transmute::<PBYTE, PIMAGE_IMPORT_DESCRIPTOR>(
base_addr.offset((*nt_hdr).OptionalHeader.DataDirectory... | {
let base_addr: PBYTE = unsafe { mem::transmute::<HMODULE, PBYTE>(self.module) };
let dos_hdr: PIMAGE_DOS_HEADER =
unsafe { mem::transmute::<HMODULE, PIMAGE_DOS_HEADER>(self.module) };
if unsafe { (*dos_hdr).e_magic } != IMAGE_DOS_SIGNATURE {
return None;
}
... | identifier_body |
detours.rs | #![allow(non_camel_case_types)]
extern crate winapi;
extern crate kernel32;
extern crate field_offset;
use winapi::*;
#[allow(unused_imports)]
use self::field_offset::*;
use std::mem;
use std::ffi::CStr;
use std::ptr::null_mut;
use std::iter::once;
use std::ffi::OsStr;
use std::os::windows::ffi::OsStrExt;
// Copie... |
if (orig_thunk.u1 & IMAGE_ORDINAL_FLAG)!= 0 {
continue;
}
let import: PIMAGE_IMPORT_BY_NAME =
unsafe {
mem::transmute::<PBYTE,
PIMAGE_IM... | {
break;
} | conditional_block |
detours.rs | #![allow(non_camel_case_types)]
extern crate winapi;
extern crate kernel32;
extern crate field_offset;
use winapi::*;
#[allow(unused_imports)]
use self::field_offset::*;
use std::mem;
use std::ffi::CStr;
use std::ptr::null_mut;
use std::iter::once;
use std::ffi::OsStr;
use std::os::windows::ffi::OsStrExt;
// Copie... | let mut result = target.intercept("kernel32.dll", "CreatePipe", unsafe {
mem::transmute::<extern "system" fn(PHANDLE,
PHANDLE,
LPVOID,
DWORD)
... |
#[test]
fn test_intercept() {
let target = Module::self_target();
| random_line_split |
j1f.rs | /* origin: FreeBSD /usr/src/lib/msun/src/e_j1f.c */
/*
* Conversion to float by Ian Lance Taylor, Cygnus Support, ian@cygnus.com.
*/
/*
* ====================================================
* Copyright (C) 1993 by Sun Microsystems, Inc. All rights reserved.
*
* Developed at SunPro, a Sun Microsystems, Inc. busin... | (ix: u32, x: f32, y1: bool, sign: bool) -> f32 {
let z: f64;
let mut s: f64;
let c: f64;
let mut ss: f64;
let mut cc: f64;
s = sinf(x) as f64;
if y1 {
s = -s;
}
c = cosf(x) as f64;
cc = s - c;
if ix < 0x7f000000 {
ss = -s - c;
z = cosf(2.0 * x) as f64... | common | identifier_name |
j1f.rs | /* origin: FreeBSD /usr/src/lib/msun/src/e_j1f.c */
/*
* Conversion to float by Ian Lance Taylor, Cygnus Support, ian@cygnus.com.
*/
/*
* ====================================================
* Copyright (C) 1993 by Sun Microsystems, Inc. All rights reserved.
*
* Developed at SunPro, a Sun Microsystems, Inc. busin... |
#[test]
fn test_y1f_2002() {
//allow slightly different result on x87
let res = y1f(2.0000002_f32);
if cfg!(all(target_arch = "x86", not(target_feature = "sse2"))) && (res == -0.10703231_f32)
{
return;
}
assert_eq!(res, -0.10703229_f32);
}
}
| {
// 0x401F3E49
assert_eq!(j1f(2.4881766_f32), 0.49999475_f32);
} | identifier_body |
j1f.rs | /* origin: FreeBSD /usr/src/lib/msun/src/e_j1f.c */
/*
* Conversion to float by Ian Lance Taylor, Cygnus Support, ian@cygnus.com.
*/
/*
* ====================================================
* Copyright (C) 1993 by Sun Microsystems, Inc. All rights reserved.
*
* Developed at SunPro, a Sun Microsystems, Inc. busin... | ix = x.to_bits();
sign = (ix >> 31)!= 0;
ix &= 0x7fffffff;
if ix >= 0x7f800000 {
return 1.0 / (x * x);
}
if ix >= 0x40000000 {
/* |x| >= 2 */
return common(ix, fabsf(x), false, sign);
}
if ix >= 0x39000000 {
/* |x| >= 2**-13 */
z = x * x;
r... | let sign: bool;
| random_line_split |
main.rs | #![feature(proc_macro_hygiene, decl_macro)]
extern crate dotenv;
extern crate chrono;
extern crate uuid;
#[macro_use] extern crate rocket;
extern crate rocket_contrib;
extern crate base64;
extern crate serde;
#[macro_use]
extern crate serde_derive;
extern crate r2d2;
extern crate r2d2_diesel;
#[macro_use]
extern crate... |
/* POST /questions */
#[derive(FromForm)]
struct PostQuestionForm {
body: String
}
#[derive(Serialize, Debug)]
struct PostQuestionFailedDTO {
reason: String
}
#[post("/questions", data = "<params>")]
fn post_question(repo: web::guard::Repository, client_ip: web::guard::ClientIP, params: request::Form<PostQ... | {
let answer_dtos = repo.search_answers(query.clone())
.into_iter()
.map(|a| AnswerDTO::from(a))
.collect::<Vec<_>>();
let context = SearchDTO {
profile: ProfileDTO {
username: profile.clone().nam... | identifier_body |
main.rs | #![feature(proc_macro_hygiene, decl_macro)]
extern crate dotenv;
extern crate chrono;
extern crate uuid;
#[macro_use] extern crate rocket;
extern crate rocket_contrib;
extern crate base64;
extern crate serde;
#[macro_use]
extern crate serde_derive;
extern crate r2d2;
extern crate r2d2_diesel;
#[macro_use]
extern crate... | onse::Responder<'r> for RequireLogin {
fn respond_to(self, _req: &Request) -> Result<response::Response<'r>, Status> {
response::Response::build()
.status(Status::Unauthorized)
.header(Header::new("WWW-Authenticate", "Basic realm=\"SECRET AREA\""))
.ok()
}
}
#[catch(401... | mpl<'r> resp | identifier_name |
main.rs | #![feature(proc_macro_hygiene, decl_macro)]
extern crate dotenv;
extern crate chrono;
extern crate uuid;
#[macro_use] extern crate rocket;
extern crate rocket_contrib;
extern crate base64;
extern crate serde;
#[macro_use]
extern crate serde_derive;
extern crate r2d2;
extern crate r2d2_diesel;
#[macro_use]
extern crate... | ,
Err(err) => {
match err {
model::StoreQuestionError::BlankBody => {
let context = PostQuestionFailedDTO { reason: String::from("質問の内容が空です") };
Err(Template::render("question/post_failed", &context))
}
}
}
... | {
let question_id = question.id;
notify::send_email(question);
Ok(response::Redirect::to(format!("/question/{}/after_post", question_id)))
} | conditional_block |
main.rs | #![feature(proc_macro_hygiene, decl_macro)]
extern crate dotenv;
extern crate chrono;
extern crate uuid;
#[macro_use] extern crate rocket;
extern crate rocket_contrib;
extern crate base64;
extern crate serde;
#[macro_use]
extern crate serde_derive;
extern crate r2d2;
extern crate r2d2_diesel;
#[macro_use]
extern crate... | #[derive(Serialize, Debug)]
struct ShowAnswerDTO {
pub answer: AnswerDTO,
pub next_answer: Option<AnswerDTO>,
pub prev_answer: Option<AnswerDTO>,
}
#[get("/question/<question_id>")]
fn show_question(question_id: i32, repo: web::guard::Repository) -> Result<response::Redirect, status::NotFound<&'static str>... | random_line_split | |
lib.rs | // Copyright (c) 2019, Bayu Aldi Yansyah <bayualdiyansyah@gmail.com>
//
// 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 requ... | //! ```
//!
//! To get started using Crabsformer, read the quickstart tutorial below.
//!
//! # Quickstart Tutorial
//!
//! ## Prerequisites
//! Before reading this quick tutorial you should know a bit of Rust. If you
//! would like to refresh your memory, take a look at the [Rust book].
//!
//! [Rust book]: https://do... | //!
//! and this to your crate root:
//!
//! ```
//! use crabsformer::prelude::*; | random_line_split |
widget.rs | //! Widget controller.
//!
//! The Widget Controller is responsible for querying the language server for information about
//! the node's widget configuration or resolving it from local cache.
mod configuration;
mod response;
use crate::prelude::*;
use crate::controller::visualization::manager::Manager;
use crate:... | buffer
}
} | }
buffer.push(']'); | random_line_split |
widget.rs | //! Widget controller.
//!
//! The Widget Controller is responsible for querying the language server for information about
//! the node's widget configuration or resolving it from local cache.
mod configuration;
mod response;
use crate::prelude::*;
use crate::controller::visualization::manager::Manager;
use crate:... | (&mut self, suggestion: &enso_suggestion_database::Entry, req: &Request) -> bool {
let mut visualization_modified = false;
if self.method_name!= suggestion.name {
self.method_name = suggestion.name.clone();
visualization_modified = true;
}
let mut zipped_argumen... | update | identifier_name |
client.rs | //! Module defines LS binary protocol client `API` and its two implementation: `Client` and
//! `MockClient`.
use crate::prelude::*;
use crate::binary::message::ErrorPayload;
use crate::binary::message::FromServerPayloadOwned;
use crate::binary::message::MessageFromServerOwned;
use crate::binary::message::MessageToSe... |
}
/// Function that does early processing of the peer's message and decides how it shall be
/// handled. Returns a function so that it may be passed to the `Handler`.
fn processor(
) -> impl FnMut(TransportEvent) -> Disposition<Uuid, FromServerPayloadOwned, Notification> +'static
{
mov... | {
Err(RpcError::MismatchedResponseType.into())
} | conditional_block |
client.rs | //! Module defines LS binary protocol client `API` and its two implementation: `Client` and
//! `MockClient`.
use crate::prelude::*;
use crate::binary::message::ErrorPayload;
use crate::binary::message::FromServerPayloadOwned;
use crate::binary::message::MessageFromServerOwned;
use crate::binary::message::MessageToSe... | (
) -> impl FnMut(TransportEvent) -> Disposition<Uuid, FromServerPayloadOwned, Notification> +'static
{
move |event: TransportEvent| {
let binary_data = match event {
TransportEvent::BinaryMessage(data) => data,
_ => return Disposition::error(UnexpectedTextMes... | processor | identifier_name |
client.rs | //! Module defines LS binary protocol client `API` and its two implementation: `Client` and
//! `MockClient`.
use crate::prelude::*;
use crate::binary::message::ErrorPayload;
use crate::binary::message::FromServerPayloadOwned;
use crate::binary::message::MessageFromServerOwned;
use crate::binary::message::MessageToSe... |
fn write_file(&self, path: &Path, contents: &[u8]) -> StaticBoxFuture<FallibleResult> {
info!("Writing file {} with {} bytes.", path, contents.len());
let payload = ToServerPayload::WriteFile { path, contents };
self.make_request(payload, Self::expect_success)
}
fn read_file(&self... | {
info!("Initializing binary connection as client with id {client_id}.");
let payload = ToServerPayload::InitSession { client_id };
self.make_request(payload, Self::expect_success)
} | identifier_body |
client.rs | //! Module defines LS binary protocol client `API` and its two implementation: `Client` and
//! `MockClient`.
use crate::prelude::*;
use crate::binary::message::ErrorPayload;
use crate::binary::message::FromServerPayloadOwned;
use crate::binary::message::MessageFromServerOwned;
use crate::binary::message::MessageToSe... | // ===============
struct ClientFixture {
transport: MockTransport,
client: Client,
executor: futures::executor::LocalPool,
}
impl ClientFixture {
fn new() -> ClientFixture {
let transport = MockTransport::new();
let client = Client::new(tran... |
// ===============
// === Fixture === | random_line_split |
control.rs | //! Runtime control utils.
//!
//! ellidri is built on tokio and the future ecosystem. Therefore the main thing it does is manage
//! tasks. Tasks are useful because they can be created, polled, and stopped. This module, and
//! `Control` more specificaly, is responsible for loading and reloading the configuration f... |
} else {
tokio::spawn(new_b.future);
bindings.push((new_b.address, new_b.handle));
}
}
shared.rehash(cfg.state).await;
log::info!("Configuration reloaded");
}
/// Re-read the configuration file and re-generate the bindings.
///
/// See documentation of `reload_bin... | {
// Failure to send the command means either the binding task have dropped the
// command channel, or the binding task doesn't exist anymore. Both possibilities
// shouldn't happen (see doc for `Control.bindings`); but in the opposite case
// let's remov... | conditional_block |
control.rs | //! Runtime control utils.
//!
//! ellidri is built on tokio and the future ecosystem. Therefore the main thing it does is manage
//! tasks. Tasks are useful because they can be created, polled, and stopped. This module, and
//! `Control` more specificaly, is responsible for loading and reloading the configuration f... | (
config_path: String,
shared: State,
stop: mpsc::Sender<SocketAddr>,
) -> Option<(Config, Vec<LoadedBinding<impl Future<Output = ()>>>)> {
let mut cfg = match Config::from_file(&config_path) {
Ok(cfg) => cfg,
Err(err) => {
log::error!("Failed to read {:?}: {}", config_path, ... | reload_config | identifier_name |
control.rs | //! Runtime control utils.
//!
//! ellidri is built on tokio and the future ecosystem. Therefore the main thing it does is manage
//! tasks. Tasks are useful because they can be created, polled, and stopped. This module, and
//! `Control` more specificaly, is responsible for loading and reloading the configuration f... | //!
//! Bindings are identified by their socket address (IP address + TCP port). TLS identities are
//! not kept track of, thus ellidri might reload the same TLS identity for a binding (it is fine to
//! let it do we are not reading thousands for TLS identities here).
use crate::{Config, net, State, tls};
use crate::... | //! - If a binding is present in both configurations, `Control` will keep the binding and send a
//! command to it, either to make it listen for raw TCP connections, or to listen for TLS
//! connections with a given `TlsAcceptor` (see `tokio-tls` doc for that). | random_line_split |
config.rs | use clap::{CommandFactory, Parser};
use pathfinder_common::AllowedOrigins;
use pathfinder_storage::JournalMode;
use reqwest::Url;
use std::collections::HashSet;
use std::net::SocketAddr;
use std::num::NonZeroUsize;
use std::path::PathBuf;
use pathfinder_common::consts::VERGEN_GIT_DESCRIBE;
#[derive(Parser)]
#[command... | env = "PATHFINDER_ETHEREUM_API_PASSWORD",
)]
ethereum_password: Option<String>,
#[arg(
long = "ethereum.url",
long_help = r"This should point to the HTTP RPC endpoint of your Ethereum entry-point, typically a local Ethereum client or a hosted gateway service such as Infura or Cloud... |
#[arg(
long = "ethereum.password",
long_help = "The optional password to use for the Ethereum API",
value_name = None, | random_line_split |
config.rs | use clap::{CommandFactory, Parser};
use pathfinder_common::AllowedOrigins;
use pathfinder_storage::JournalMode;
use reqwest::Url;
use std::collections::HashSet;
use std::net::SocketAddr;
use std::num::NonZeroUsize;
use std::path::PathBuf;
use pathfinder_common::consts::VERGEN_GIT_DESCRIBE;
#[derive(Parser)]
#[command... | {
#[arg(
long,
value_name = "DIR",
value_hint = clap::ValueHint::DirPath,
long_help = "Directory where the node should store its data",
env = "PATHFINDER_DATA_DIRECTORY",
default_value_os_t = (&std::path::Component::CurDir).into()
)]
data_directory: PathBuf... | Cli | identifier_name |
lib.rs | `Token` that has been validated. Your user is
//! authenticated!
//!
//! You can also take a more nuanced approach that gives you more fine grained control:
//!
//! ```rust,ignore
//! use oidc;
//! use reqwest;
//! use std::default::Default;
//!
//! let id = "my client".to_string();
//! let secret = "a secret to every... | let expected = expected.to_string();
let actual = actual.to_string();
return Err(
Validation::Mismatch(Mismatch::Nonce { expected, actual }).into()
);
}
}
... | if expected != actual { | random_line_split |
lib.rs | Token` that has been validated. Your user is
//! authenticated!
//!
//! You can also take a more nuanced approach that gives you more fine grained control:
//!
//! ```rust,ignore
//! use oidc;
//! use reqwest;
//! use std::default::Default;
//!
//! let id = "my client".to_string();
//! let secret = "a secret to everybo... | (&self, token: &mut IdToken) -> Result<(), Error> {
// This is an early return if the token is already decoded
if let Compact::Decoded {.. } = *token {
return Ok(());
}
let header = token.unverified_header()?;
// If there is more than one key, the token MUST have a k... | decode_token | identifier_name |
lib.rs | Token` that has been validated. Your user is
//! authenticated!
//!
//! You can also take a more nuanced approach that gives you more fine grained control:
//!
//! ```rust,ignore
//! use oidc;
//! use reqwest;
//! use std::default::Default;
//!
//! let id = "my client".to_string();
//! let secret = "a secret to everybo... |
if let Some(max) = max_age {
match claims.auth_time {
Some(time) => {
let age = chrono::Duration::seconds(now.timestamp() - time);
if age >= *max {
return Err(error::Validation::Expired(Expiry::MaxAge(age)).into());
... | {
return Err(Validation::Expired(Expiry::Expires(
chrono::naive::NaiveDateTime::from_timestamp(claims.exp, 0),
))
.into());
} | conditional_block |
machine.rs | RegisterRef::Null => 0,
// These conversion unwraps are safe because we know that input
// and stack lengths are bounded by validation rules to fit into an
// i32 (max length is 256 at the time of writing this)
RegisterRef::InputLength => self.input.len().try_into().u... | FailureReason | identifier_name | |
machine.rs | be small enough that it probably doesn't matter.
/// Values never get added to the input, only popped off.
input: Vec<LangValue>,
/// The current output buffer. This can be pushed into, but never popped
/// out of.
output: Vec<LangValue>,
/// The registers that the user can read and write. Inde... | .into_iter()
.map(|stack_ref| (stack_ref, self.stacks[stack_ref.0].as_slice()))
.collect()
}
/// Get the runtime error that halted execution of this machine. If no error
/// has occurred, return `None`.
pub fn error(&self) -> Option<&WithSource<RuntimeError>> {
... | pub fn stacks(&self) -> HashMap<StackRef, &[LangValue]> {
self.hardware_spec
.all_stack_refs() | random_line_split |
machine.rs | enough that it probably doesn't matter.
/// Values never get added to the input, only popped off.
input: Vec<LangValue>,
/// The current output buffer. This can be pushed into, but never popped
/// out of.
output: Vec<LangValue>,
/// The registers that the user can read and write. Indexed by Re... |
/// Pops an element off the given stack. If the pop is successful, the
/// popped value is returned. If the stack is empty, an error is returned.
/// If the stack reference is invalid, will panic (should be validated at
/// build time).
fn pop_stack(
&mut self,
stack_ref: &SpanNode... | {
// Have to access this first cause borrow checker
let max_stack_length = self.hardware_spec.max_stack_length;
let stack = &mut self.stacks[stack_ref.value().0];
// If the stack is capacity, make sure we're not over it
if stack.len() >= max_stack_length {
return Err... | identifier_body |
machine.rs | enough that it probably doesn't matter.
/// Values never get added to the input, only popped off.
input: Vec<LangValue>,
/// The current output buffer. This can be pushed into, but never popped
/// out of.
output: Vec<LangValue>,
/// The registers that the user can read and write. Indexed by Re... |
}
/// Internal function to execute the next instruction. The return value
/// is the same as [Self::execute_next], except the error needs to be
/// wrapped before being handed to the user.
fn execute_next_inner(&mut self) -> Result<bool, (RuntimeError, Span)> {
// We've previously hit an e... | {
Err((RuntimeError::EmptyStack, *stack_ref.metadata()))
} | conditional_block |
lib.rs | //! Embed images in documentation.
//!
//! This crate enables the portable embedding of images in
//! `rustdoc`-generated documentation. Standard
//! web-compatible image formats should be supported. Please [file an issue][issue-tracker]
//! if you have problems. Read on to learn how it works.
//!
//! # Showcase
//!
//... | {
label: String,
path: PathBuf,
}
impl Parse for ImageDescription {
fn parse(input: ParseStream) -> parse::Result<Self> {
let label = input.parse::<syn::LitStr>()?;
input.parse::<syn::Token![,]>()?;
let path = input.parse::<syn::LitStr>()?;
Ok(ImageDescription {
... | ImageDescription | identifier_name |
lib.rs | //! Embed images in documentation.
//!
//! This crate enables the portable embedding of images in
//! `rustdoc`-generated documentation. Standard
//! web-compatible image formats should be supported. Please [file an issue][issue-tracker]
//! if you have problems. Read on to learn how it works.
//!
//! # Showcase
//!
//... | //! around the current limitations of `rustdoc` and enables a practically workable approach to
//! embedding images in a portable manner.
//!
//! # How to embed images in documentation
//!
//! First, you'll need to depend on this crate. In `cargo.toml`:
//!
//! ```toml
//! [dependencies]
//! // Replace x.x with the lat... | //!
//! This crate represents a carefully crafted solution based on procedural macros that works | random_line_split |
interrupt.rs | pagectrl, frame_alloc);
local.enable(Idt::LOCAL_APIC_SPURIOUS as u8);
InterruptModel::Apic {
local,
io: spin::Mutex::new(io),
}
}
model => {
if model.is_none() {
tracing:... | registers_is_correct_size | identifier_name | |
interrupt.rs | pub const RESERVED_WRITE: bool;
/// When set, the page fault was caused by an instruction fetch. This
/// only applies when the No-Execute bit is supported and enabled.
pub const INSTRUCTION_FETCH: bool;
/// When set, the page fault was caused by a protection-key violation.
... |
fn debug_error_code(&self) -> &dyn fmt::Debug {
&self.code
}
fn display_error_code(&self) -> &dyn fmt::Display {
&self.code
}
}
impl<'a> ctx::CodeFault for Context<'a, CodeFault<'a>> {
fn is_user_mode(&self) -> bool {
false // TODO(eliza)
}
fn instruction_ptr(&se... | {
crate::control_regs::Cr2::read()
} | identifier_body |
interrupt.rs | pub const RESERVED_WRITE: bool;
/// When set, the page fault was caused by an instruction fetch. This
/// only applies when the No-Execute bit is supported and enabled.
pub const INSTRUCTION_FETCH: bool;
/// When set, the page fault was caused by a protection-key violation.
... | mut registers: Registers,
code: u64,
) {
unsafe {
// Safety: who cares!
crate::vga::writer().force_unlock();
if let Some(com1) = crate::serial::com1() {
com1.force_unlock();
}
}
... | code,
});
}
extern "x86-interrupt" fn gpf_isr<H: Handlers<Registers>>( | random_line_split |
node.rs | use petgraph;
use petgraph::graph::NodeIndex; |
use std::sync::mpsc;
use std::sync;
use std::fmt;
use std::collections::HashMap;
use std::ops::{Deref, DerefMut};
use checktable;
use flow::data::DataType;
use ops::{Record, Datas};
use flow::domain;
use flow::{Ingredient, NodeAddress, Edge};
use flow::payload::Packet;
use flow::migrate::materialization::Tag;
use ... | random_line_split | |
node.rs | use petgraph;
use petgraph::graph::NodeIndex;
use std::sync::mpsc;
use std::sync;
use std::fmt;
use std::collections::HashMap;
use std::ops::{Deref, DerefMut};
use checktable;
use flow::data::DataType;
use ops::{Record, Datas};
use flow::domain;
use flow::{Ingredient, NodeAddress, Edge};
use flow::payload::Packet;
... | (&mut self) -> Node {
let inner = match *self.inner {
Type::Egress { ref tags, ref txs } => {
// egress nodes can still be modified externally if subgraphs are added
// so we just make a new one with a clone of the Mutex-protected Vec
Type::Egress {
... | take | identifier_name |
node.rs | use petgraph;
use petgraph::graph::NodeIndex;
use std::sync::mpsc;
use std::sync;
use std::fmt;
use std::collections::HashMap;
use std::ops::{Deref, DerefMut};
use checktable;
use flow::data::DataType;
use ops::{Record, Datas};
use flow::domain;
use flow::{Ingredient, NodeAddress, Edge};
use flow::payload::Packet;
... | se {
false
}
}
pub fn is_internal(&self) -> bool {
if let Type::Internal(..) = *self.inner {
true
} else {
false
}
}
/// A node is considered to be an output node if changes to its state are visible outside of
/// its domain.
... | true
} el | conditional_block |
node.rs | use petgraph;
use petgraph::graph::NodeIndex;
use std::sync::mpsc;
use std::sync;
use std::fmt;
use std::collections::HashMap;
use std::ops::{Deref, DerefMut};
use checktable;
use flow::data::DataType;
use ops::{Record, Datas};
use flow::domain;
use flow::{Ingredient, NodeAddress, Edge};
use flow::payload::Packet;
... |
pub fn mirror(&self, n: Type) -> Node {
let mut n = Self::new(&*self.name, &self.fields, n);
n.domain = self.domain;
n
}
pub fn name(&self) -> &str {
&*self.name
}
pub fn fields(&self) -> &[String] {
&self.fields[..]
}
pub fn domain(&self) -> doma... | {
Node {
name: name.to_string(),
domain: None,
addr: None,
fields: fields.into_iter().map(|s| s.to_string()).collect(),
inner: NodeHandle::Owned(inner),
}
} | identifier_body |
mod.rs | use std::collections::HashMap;
use std::future::Future;
use std::io::{Read, Write};
use std::net::SocketAddr;
use std::ops::DerefMut;
use std::pin::Pin;
use std::sync::{Arc, Mutex};
use std::sync::mpsc::{channel, Receiver, Sender};
use std::task::{Context, Waker};
use std::thread::spawn;
use log;
use mio::{Events, Int... | spatcherAction::Dispose => self.close(id),
}
}
fn on_tcp_stream(
&mut self,
event: &Event,
stream: &mut TcpStream,
listener: &mut Box<dyn TcpStreamListener>,
) {
// 読み込み可能イベント
if event.is_readable() {
let behaviour = listener.on_ready_to_read(stream);
self.action(event.tok... | est).unwrap();
}
Di | conditional_block |
mod.rs | use std::collections::HashMap;
use std::future::Future;
use std::io::{Read, Write};
use std::net::SocketAddr;
use std::ops::DerefMut;
use std::pin::Pin;
use std::sync::{Arc, Mutex};
use std::sync::mpsc::{channel, Receiver, Sender};
use std::task::{Context, Waker};
use std::thread::spawn;
use log;
use mio::{Events, Int... | f self.sockets.get(&id).is_none() {
self.next = if self.next + 1 == max { 0 } else { self.next + 1 };
return Ok(id);
}
}
unreachable!()
}
/// 指定された ID のソケットを新規追加または更新します。
pub fn set(&mut self, id: SocketId, socket: Socket) {
self.sockets.insert(id, Arc::new(Mutex::new(socket)));... | i | identifier_name |
mod.rs | use std::collections::HashMap;
use std::future::Future;
use std::io::{Read, Write};
use std::net::SocketAddr;
use std::ops::DerefMut;
use std::pin::Pin;
use std::sync::{Arc, Mutex};
use std::sync::mpsc::{channel, Receiver, Sender};
use std::task::{Context, Waker};
use std::thread::spawn;
use log;
use mio::{Events, Int... | Future<Output=Result<SocketId>>>;
}
impl DispatcherRegister<TcpListener, Box<dyn TcpListenerListener>> for Dispatcher {
fn register(
&self,
mut listener: TcpListener,
event_listener: Box<dyn TcpListenerListener>,
) -> Box<dyn Future<Output=Result<SocketId>>> {
self.run_in_event_loop(Box::new(move ... |
Ok(0usize)
}));
}
}
trait DispatcherRegister<S, L> {
fn register(&self, source: S, listener: L) -> Box<dyn | identifier_body |
mod.rs | use std::collections::HashMap;
use std::future::Future;
use std::io::{Read, Write};
use std::net::SocketAddr;
use std::ops::DerefMut;
use std::pin::Pin;
use std::sync::{Arc, Mutex};
use std::sync::mpsc::{channel, Receiver, Sender};
use std::task::{Context, Waker};
use std::thread::spawn;
use log;
use mio::{Events, Int... |
fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> std::task::Poll<Self::Output> {
use std::task::Poll;
let mut state = self.state.lock().unwrap();
if let Some(result) = state.result.take() {
Poll::Ready(result)
} else {
state.waker = Some(cx.waker().clone());
Poll::Pending
... | type Output = R; | random_line_split |
lib.rs | //! This crate is part of [Sophia],
//! an [RDF] and [Linked Data] toolkit in Rust.
//!
//! Terms are the building blocks of an [RDF] graph.
//! There are four types of terms: IRIs, blank nodes (BNode for short),
//! literals and variables.
//!
//! NB: variable only exist in [generalized RDF].
//!
//! This module defi... | U: AsRef<str>,
T: From<U>,
{
Iri::<T>::new(iri).map(Into::into)
}
/// Return a new IRI term from the two given parts (prefix and suffix).
///
/// May fail if the concatenation of `ns` and `suffix`
/// does not produce a valid IRI.
pub fn new_iri_suffixed<U, V>(ns: U,... | pub fn new_iri<U>(iri: U) -> Result<Term<T>>
where | random_line_split |
lib.rs | //! This crate is part of [Sophia],
//! an [RDF] and [Linked Data] toolkit in Rust.
//!
//! Terms are the building blocks of an [RDF] graph.
//! There are four types of terms: IRIs, blank nodes (BNode for short),
//! literals and variables.
//!
//! NB: variable only exist in [generalized RDF].
//!
//! This module defi... | (&self, other: &TE) -> Option<std::cmp::Ordering> {
Some(term_cmp(self, other))
}
}
impl<TD> Hash for Term<TD>
where
TD: TermData,
{
fn hash<H: Hasher>(&self, state: &mut H) {
term_hash(self, state)
}
}
impl<TD> From<Iri<TD>> for Term<TD>
where
TD: TermData,
{
fn from(iri: Iri<... | partial_cmp | identifier_name |
custom_insts.rs | //! SPIR-V (extended) instructions specific to `rustc_codegen_spirv`, produced
//! during the original codegen of a crate, and consumed by the `linker`.
use lazy_static::lazy_static;
use rspirv::dr::{Instruction, Operand};
use rspirv::spirv::Op;
use smallvec::SmallVec;
/// Prefix for `CUSTOM_EXT_INST_SET` (`OpExtInst... | /// These considerations are relevant to the specific choice of name:
/// * does *not* start with `NonSemantic.`, as:
/// * some custom instructions may need to be semantic
/// * these custom instructions are not meant for the final SPIR-V
/// (so no third-party support is *technically* requ... | }
lazy_static! {
/// `OpExtInstImport` "instruction set" name for all Rust-GPU instructions.
/// | random_line_split |
custom_insts.rs | //! SPIR-V (extended) instructions specific to `rustc_codegen_spirv`, produced
//! during the original codegen of a crate, and consumed by the `linker`.
use lazy_static::lazy_static;
use rspirv::dr::{Instruction, Operand};
use rspirv::spirv::Op;
use smallvec::SmallVec;
/// Prefix for `CUSTOM_EXT_INST_SET` (`OpExtInst... |
/// Returns `true` iff this `CustomOp` is a custom terminator instruction,
/// i.e. semantic and must precede an `OpUnreachable` standard terminator,
/// with at most debuginfo instructions (standard or custom), between the two.
pub fn is_terminator(self) -> bool {
match self {
Cus... | {
match self {
CustomOp::SetDebugSrcLoc
| CustomOp::ClearDebugSrcLoc
| CustomOp::PushInlinedCallFrame
| CustomOp::PopInlinedCallFrame => true,
CustomOp::Abort => false,
}
} | identifier_body |
custom_insts.rs | //! SPIR-V (extended) instructions specific to `rustc_codegen_spirv`, produced
//! during the original codegen of a crate, and consumed by the `linker`.
use lazy_static::lazy_static;
use rspirv::dr::{Instruction, Operand};
use rspirv::spirv::Op;
use smallvec::SmallVec;
/// Prefix for `CUSTOM_EXT_INST_SET` (`OpExtInst... | (self) -> bool {
match self {
CustomOp::SetDebugSrcLoc
| CustomOp::ClearDebugSrcLoc
| CustomOp::PushInlinedCallFrame
| CustomOp::PopInlinedCallFrame => true,
CustomOp::Abort => false,
}
}
/// Returns `true` iff this `CustomOp` is a cu... | is_debuginfo | identifier_name |
mod.rs | use std::collections::{HashMap, HashSet};
#[cfg(feature = "egl")]
use smithay::backend::renderer::ImportEgl;
use smithay::{
backend::{
allocator::{
dmabuf::{AnyError, Dmabuf, DmabufAllocator},
gbm::{GbmAllocator, GbmBufferFlags},
vulkan::{ImageUsageFlags, VulkanAllocator... | () {
let mut event_loop = EventLoop::try_new().expect("Unable to initialize event loop");
let (session, mut _notifier) = match LibSeatSession::new() {
Ok((session, notifier)) => (session, notifier),
Err(err) => {
tracing::error!("Error in creating libseat session: {}", err);
... | initialize_backend | identifier_name |
mod.rs | use std::collections::{HashMap, HashSet};
#[cfg(feature = "egl")]
use smithay::backend::renderer::ImportEgl;
use smithay::{
backend::{
allocator::{
dmabuf::{AnyError, Dmabuf, DmabufAllocator},
gbm::{GbmAllocator, GbmBufferFlags},
vulkan::{ImageUsageFlags, VulkanAllocator... | #[cfg_attr(not(feature = "egl"), allow(unused_mut))]
let mut renderer = state
.backend_data
.gpu_manager
.single_renderer(&primary_gpu)
.unwrap();
#[cfg(feature = "egl")]
{
match renderer.bind_wl_display(&state.display_handle) {
Ok(_) => tracing::info!("E... | }); | random_line_split |
mod.rs | use std::collections::{HashMap, HashSet};
#[cfg(feature = "egl")]
use smithay::backend::renderer::ImportEgl;
use smithay::{
backend::{
allocator::{
dmabuf::{AnyError, Dmabuf, DmabufAllocator},
gbm::{GbmAllocator, GbmBufferFlags},
vulkan::{ImageUsageFlags, VulkanAllocator... |
fn reset_buffers(&mut self, output: &smithay::output::Output) {
if let Some(id) = output.user_data().get::<UdevOutputId>() {
if let Some(gpu) = self.backends.get_mut(&id.device_id) {
if let Some(surface) = gpu.surfaces.get_mut(&id.crtc) {
surface.compositor.... | {
&self.loop_signal
} | identifier_body |
mod.rs | //! A batteries included runtime for applications using Tokio.
//!
//! Applications using Tokio require some runtime support in order to work:
//!
//! * A [reactor] to drive I/O resources.
//! * An [executor] to execute tasks that use these I/O resources.
//! * A [timer] for scheduling work to run after a set period of... |
}
}
| {
let shutdown = Shutdown::shutdown_now(inner);
let _ = shutdown.wait();
} | conditional_block |
mod.rs | //! A batteries included runtime for applications using Tokio.
//!
//! Applications using Tokio require some runtime support in order to work:
//!
//! * A [reactor] to drive I/O resources.
//! * An [executor] to execute tasks that use these I/O resources.
//! * A [timer] for scheduling work to run after a set period of... |
/// Signals the runtime to shutdown immediately.
///
/// Returns a future that completes once the shutdown operation has
/// completed.
///
/// This function will forcibly shutdown the runtime, causing any
/// in-progress work to become canceled. The shutdown steps are:
///
/// * D... | {
let inner = self.inner.take().unwrap();
let inner = inner.pool.shutdown_on_idle();
Shutdown { inner }
} | identifier_body |
mod.rs | //! A batteries included runtime for applications using Tokio.
//!
//! Applications using Tokio require some runtime support in order to work:
//!
//! * A [reactor] to drive I/O resources.
//! * An [executor] to execute tasks that use these I/O resources.
//! * A [timer] for scheduling work to run after a set period of... | F: Send +'static + Future<Item = R, Error = E>,
R: Send +'static,
E: Send +'static,
{
let (tx, rx) = futures::sync::oneshot::channel();
self.spawn(future.then(move |r| tx.send(r).map_err(|_| unreachable!())));
rx.wait().unwrap()
}
/// Run a future to completi... | random_line_split | |
mod.rs | //! A batteries included runtime for applications using Tokio.
//!
//! Applications using Tokio require some runtime support in order to work:
//!
//! * A [reactor] to drive I/O resources.
//! * An [executor] to execute tasks that use these I/O resources.
//! * A [timer] for scheduling work to run after a set period of... | () -> io::Result<Self> {
Builder::new().build()
}
#[deprecated(since = "0.1.5", note = "use `reactor` instead")]
#[doc(hidden)]
pub fn handle(&self) -> &Handle {
#[allow(deprecated)]
self.reactor()
}
/// Return a reference to the reactor handle for this runtime instance... | new | identifier_name |
mod.rs | Set,
},
};
pub mod config;
use byteorder::{ByteOrder, LittleEndian};
use failure;
use vec_map::VecMap;
use std::{
collections::{BTreeMap, HashMap}, error::Error as StdError, fmt, iter, mem, panic, sync::Arc,
};
use crypto::{self, CryptoHash, Hash, PublicKey, SecretKey};
use encoding::Error as MessageError;
... | else {
panic!("Could not set database version.")
}
}
/// Checks if storage version is supported.
///
/// # Panics
///
/// Panics if version is not supported or is not specified.
fn assert_storage_version(&self) {
match storage::StorageMetadata::read(self.db.snap... | {
info!(
"Storage version successfully initialized with value [{}].",
storage::StorageMetadata::read(&self.db.snapshot()).unwrap(),
)
} | conditional_block |
mod.rs | Set,
},
};
pub mod config;
use byteorder::{ByteOrder, LittleEndian};
use failure;
use vec_map::VecMap;
use std::{
collections::{BTreeMap, HashMap}, error::Error as StdError, fmt, iter, mem, panic, sync::Arc,
};
use crypto::{self, CryptoHash, Hash, PublicKey, SecretKey};
use encoding::Error as MessageError;
... |
/// Returns the hash of the latest committed block.
///
/// # Panics
///
/// If the genesis block was not committed.
pub fn last_hash(&self) -> Hash {
Schema::new(&self.snapshot())
.block_hashes_by_height()
.last()
.unwrap_or_else(Hash::default)
}
... | {
self.db.merge(patch)
} | identifier_body |
mod.rs | TransactionSet,
},
};
pub mod config;
use byteorder::{ByteOrder, LittleEndian};
use failure;
use vec_map::VecMap;
use std::{
collections::{BTreeMap, HashMap}, error::Error as StdError, fmt, iter, mem, panic, sync::Arc,
};
use crypto::{self, CryptoHash, Hash, PublicKey, SecretKey};
use encoding::Error as Me... | pub fn remove_peer_with_pubkey(&mut self, key: &PublicKey) {
| self.merge(fork.into_patch())
.expect("Unable to save peer to the peers cache");
}
/// Removes from the cache the `Connect` message from a peer. | random_line_split |
mod.rs | id
);
}
service_map.insert(id, service);
}
Self {
db: storage.into(),
service_map: Arc::new(service_map),
service_keypair: (service_public_key, service_secret_key),
api_sender,
}
}
/// Recr... | before_commit | identifier_name |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.