text stringlengths 8 4.13M |
|---|
// 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 ... |
mod abst;
mod exp;
mod play;
mod skin;
use play::calculate;
use skin::Console;
fn main() {
let console = Console;
calculate(&console, &console);
}
#[test]
fn case0() {
use abst::Input::*;
let mock = skin::Mock::new(vec![Num(2.0), Plus, Num(1.0)], 3.0);
calculate(&mock, &mock);
}
#[test]
fn case1() {
use... |
use embedded_hal::blocking::delay::DelayMs;
use embedded_hal::blocking::spi::Write;
use embedded_hal::digital::v2::*;
const WIDTH: usize = 176;
const HEIGHT: usize = 264;
const NUM_DISPLAY_BITS: usize = WIDTH * HEIGHT / 8;
pub struct EPD27<SPI, CS, DC, RST, BUSY, DELAY> {
spi: SPI,
cs: CS,
busy: BUSY,
... |
use crate::{
atomic::{PyAtomic, Radium},
hash::PyHash,
};
use ascii::AsciiString;
use rustpython_format::CharLen;
use std::ops::{Bound, RangeBounds};
#[cfg(not(target_arch = "wasm32"))]
#[allow(non_camel_case_types)]
pub type wchar_t = libc::wchar_t;
#[cfg(target_arch = "wasm32")]
#[allow(non_camel_case_types)... |
use tonic::Request;
use std::env;
pub mod pubsub {
tonic::include_proto!("pubsub");
}
use pubsub::message_service_client::MessageServiceClient;
use pubsub::SubscribeRequest;
#[tokio::main]
async fn main() {
let client_id = env::args().nth(1).unwrap();
println!("run subscribe client");
let url = "h... |
use utopia_core::math::{Size, Vector2};
#[derive(Debug)]
pub struct QuadPrimitive<Color> {
pub color: Color,
pub border_radius: u32,
pub origin: Vector2,
pub size: Size,
}
|
use std::cell::Cell;
use vm::opcodes::Opcode;
pub struct Lexer {
stream: Vec<char>,
tokens: Vec<Lexeme>,
stream_pos: Cell<i32>,
current_pos: Cell<i32>,
current_line: Cell<i32>,
}
pub struct Lexeme {
pos: i32,
line: i32,
value: String,
opcode: Opcode,
}
impl Lexer {
pub fn new(... |
use chrono::{DateTime, Datelike, TimeZone, Timelike, Utc};
use rlua::prelude::*;
use std::collections::{BTreeMap, BTreeSet};
pub fn timestamp_to_table<'a>(ctx: LuaContext<'a>, ts: DateTime<Utc>) -> LuaResult<LuaTable> {
let table = ctx.create_table()?;
table.set("year", ts.year())?;
table.set("month", ts.m... |
// Copyright 2021 Chiral Ltd.
// Licensed under the Apache-2.0 license (https://opensource.org/licenses/Apache-2.0)
// This file may not be copied, modified, or distributed
// except according to those terms.
pub const MAX_COUNT_OF_ATOMS_IN_A_MOLECULE: usize = 1000;
// 1 digit for symmetry
// 3 digits for atomic numbe... |
mod architecture_analysis;
mod cloc_analysis;
mod framework_analysis;
mod git_analysis;
pub use git_analysis::*;
use std::fs;
use core_model::url_format;
use core_model::Settings;
use core_model::{CocoConfig, RepoConfig};
use crate::domain::CocoOpt;
use core_model::coco_config::CocoCommitConfig;
use rayon::prelude::*... |
use crate::error::{ContexError, Error, Result};
use derivative::*;
use std::collections::HashMap;
use std::fmt::Debug;
use std::hash::Hash;
use std::sync::Mutex;
pub type TransitionFunction<S, E> = fn(&StateMachine<S, E>, E) -> S;
/// The primitive state machine type that holds all context
/// * List of available st... |
use obj_pool::optional; // must be available
#[test]
fn test_compile() {
let _ = optional::some(10);
} |
mod player;
pub use self::player::init_player; |
/*!
Provides support for lexing Ruby's string literal formats.
!*/
use crate::ast::Literal;
use crate::lexer::*;
pub(crate) mod character;
pub(crate) mod command;
pub(crate) mod double;
pub(crate) mod heredoc;
pub(crate) mod quoted;
pub(crate) mod single;
pub(crate) use character::character_literal;
pub(crate) use co... |
use crate::trimmer::v1::{trim_text as trim_text_v1, TrimmedText};
use crate::trimmer::UnicodeDots;
use crate::GrepResult;
use std::collections::HashMap;
use std::path::MAIN_SEPARATOR;
use std::slice::IterMut;
use types::MatchedItem;
/// Line number of Vim is 1-based.
pub type VimLineNumber = usize;
/// Map of truncat... |
pub mod size;
|
use crate::il::Expression as Expr;
use crate::il::*;
use crate::translator::x86::x86register::{get_register, X86Register};
use crate::Error;
use falcon_capstone::capstone;
use falcon_capstone::capstone::cs_x86_op;
use falcon_capstone::capstone_sys::{x86_op_type, x86_reg};
use std::cmp::Ordering;
/// Mode used by trans... |
extern crate nalgebra;
use core::ops::{Add,AddAssign,Mul,MulAssign};
use ggez::{GameResult, Context};
use ggez::graphics::{Drawable, DrawMode, Point2, Mesh, Vector2};
use globals::*;
pub const HEX_RADIUS: f32 = 32.0;
pub const HEX_WIDTH: f32 = HEX_RADIUS * SQRT_3;
pub const HEX_HEIGHT: f32 = HEX_RADIUS * 2.0;
#[... |
// Copyright (c) Calibra Research
// SPDX-License-Identifier: Apache-2.0
#![allow(bare_trait_objects)]
#[macro_use]
extern crate failure;
extern crate rand;
#[macro_use]
extern crate log;
extern crate bft_simulator_runtime;
extern crate clap;
extern crate env_logger;
use clap::{App, Arg};
use std::{collections::BTre... |
// Copyright 2018 The Fuchsia Authors. All rights reserved.
// Copyright 2016 Joe Wilm, The Alacritty Project Contributors
//
// 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:/... |
#![allow(dead_code)]
use crate::interface::AccountManagement;
use crate::near_env::Env;
use crate::{near::*, Contract};
use near_sdk::test_utils::VMContextBuilder;
use near_sdk::{
json_types::ValidAccountId,
serde::{Deserialize, Serialize},
serde_json,
test_utils::get_created_receipts,
testing_env,... |
use crate::{
dynamic::{Enum, InputObject, Interface, Object, Scalar, SchemaError, Subscription, Union},
registry::Registry,
};
/// A GraphQL type
#[derive(Debug)]
pub enum Type {
/// Scalar
Scalar(Scalar),
/// Object
Object(Object),
/// Input object
InputObject(InputObject),
/// Enu... |
#[doc = "Reader of register CFGR"]
pub type R = crate::R<u32, super::CFGR>;
#[doc = "Writer for register CFGR"]
pub type W = crate::W<u32, super::CFGR>;
#[doc = "Register CFGR `reset()`'s with value 0"]
impl crate::ResetValue for super::CFGR {
type Type = u32;
#[inline(always)]
fn reset_value() -> Self::Typ... |
use amethyst::utils::ortho_camera::{
CameraNormalizeMode,
CameraOrtho,
CameraOrthoWorldCoordinates,
};
use super::*;
impl LevelLoader {
pub(super) fn build_camera(&self, world: &mut World) {
// Delete existing entities
world.exec(
|(entities, cameras): (Entities, ReadStorag... |
use wasm_bindgen::prelude::*;
use grass;
#[wasm_bindgen]
pub fn compile(s: &str, opts: JsValue) -> Result<String, JsValue> {
let sass = grass::from_string(s.to_string(), &grass::Options::default());
Ok(sass.unwrap())
}
|
use std::thread;
fn main() {
// let child_one = thread::spawn(move || {
// println!("thread level 1.");
// let child_two = thread::spawn(move || {
// println!("thread level 2.");
// });
// child_two.join();
// });
// child_one.join();
thread::Bui... |
use slice_2d::prelude::*;
#[test]
fn slice_2d_index() {
const ROW: usize = 3;
const COL: usize = 5;
let v = (0..(ROW * COL) as i32).collect::<Vec<_>>();
let s = Slice2D::from_slice(v.as_slice(), ROW, COL);
for i in 0..ROW {
for j in 0..COL {
assert_eq!(s[(i, j)], (i * COL + j) a... |
use std::{ffi::CStr, ptr::copy_nonoverlapping};
use windows::{
core::{HSTRING, PCWSTR},
w,
Win32::{
Foundation::{HANDLE, HGLOBAL, HWND},
System::{
Com::{CoCreateInstance, CLSCTX_ALL},
DataExchange::{
CloseClipboard, EmptyClipboard, GetClipbo... |
#[derive(Clone, Debug, PartialEq, Eq)]
enum Visibility {
Visible,
Hidden,
}
fn determine_visibility(trees: &[u8]) -> Vec<Visibility> {
let mut trees_visibility = vec![Visibility::Hidden; trees.len()];
for trees_perspective in [
trees.iter().enumerate().collect::<Vec<(usize, &u8)>>(),
tr... |
use std::fmt::{Display, Result, Formatter};
use nom::IResult;
use nom::IResult::*;
// note: make castle be masks for squares that need checking?
bitflags! {
pub struct Castle: u8 {
const NONE = 0;
const Q = WQ.bits | BQ.bits;
const K = WK.bits | BK.bits;
const W = WQ.bits | WK.bits... |
#[doc = "Reader of register DC1"]
pub type R = crate::R<u32, super::DC1>;
#[doc = "Reader of field `JTAG`"]
pub type JTAG_R = crate::R<bool, bool>;
#[doc = "Reader of field `SWD`"]
pub type SWD_R = crate::R<bool, bool>;
#[doc = "Reader of field `SWO`"]
pub type SWO_R = crate::R<bool, bool>;
#[doc = "Reader of field `WD... |
use max_sys::t_atom_long as max_long;
use std::ffi::c_void;
use std::ffi::CString;
static mut SIMP_CLASS: Option<*mut max_sys::t_class> = None;
type Method = unsafe extern "C" fn(arg1: *mut c_void) -> *mut c_void;
#[repr(C)]
struct Simp {
s_obj: max_sys::t_object,
s_value: max_long,
}
impl Simp {
pub un... |
//! inotify support for working with inotifies
use crate::backend::c;
use crate::backend::conv::{borrowed_fd, c_str, ret, ret_c_int, ret_owned_fd};
use crate::fd::{BorrowedFd, OwnedFd};
use crate::io;
use bitflags::bitflags;
bitflags! {
/// `IN_*` for use with [`inotify_init`].
///
/// [`inotify_init`]: c... |
// Copyright 2020-2021, The Tremor Team
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agr... |
use legion::Entity;
pub struct Camera {
pub fov: f32,
pub interpolate_rotation: bool,
}
pub struct ActiveCamera(pub Entity);
|
//! The traits releated to nonexhaustive enums.
use std::{
cmp::{Eq, Ord},
fmt::{self, Debug},
};
use crate::{
std_types::{RBoxError, RStr},
type_layout::StartLen,
type_level::{
impl_enum::{Implemented, Unimplemented},
trait_marker,
},
InterfaceType,
};
/// Queries the mar... |
//! Functions to read time stamp counters on x86.
/// Read the time stamp counter.
///
/// The RDTSC instruction is not a serializing instruction.
/// It does not necessarily wait until all previous instructions
/// have been executed before reading the counter. Similarly,
/// subsequent instructions may begin executi... |
//! This is the Rust implementation of a Discord bot, initially designed for
//! HackPack.
#![deny(missing_docs)]
#![deny(rustdoc::broken_intra_doc_links)]
#![deny(rustdoc::private_intra_doc_links)]
pub mod ping;
use ping::PingApplicationCommand;
use serenity::client::{Context, EventHandler};
use serenity::model::i... |
use crate::base::*;
pub struct Model {
pub layers: Vec<Box<dyn Layer>>,
}
impl Model {
pub fn new() -> Self {
Model { layers: Vec::new() }
}
pub fn add(&mut self, layer: Box<dyn Layer>) {
&self.layers.push(layer);
}
fn forward(&mut self, input: &Mat, training: bool) -> Vector {... |
use std::{io as std_io};
use handlebars_crate::{TemplateError, TemplateFileError};
#[derive(Debug, Fail)]
pub enum LoadingError {
#[fail(display="template id is used multiple times for different templates: {}", id)]
TemplateIdCollision { id: String },
#[fail(display="can not add free template as template ... |
use clap::{App, Arg};
use std::fs::File;
use std::io::{BufRead, BufReader};
#[derive(Debug)]
pub struct Config {
files: Vec<String>,
number_lines: bool,
number_nonblank_lines: bool,
}
pub fn get_args() -> Result<Config, Box<dyn std::error::Error>> {
let matches = App::new("rust-cat")
.version(... |
#![allow(unused_variables, non_upper_case_globals, non_snake_case, unused_unsafe, non_camel_case_types, dead_code, clippy::all)]
#[cfg(feature = "Win32_Graphics_Gdi")]
#[inline]
pub unsafe fn ChoosePixelFormat<'a, Param0: ::windows::core::IntoParam<'a, super::Gdi::HDC>>(hdc: Param0, ppfd: *const PIXELFORMATDESCRIPTOR) ... |
use std::{collections::VecDeque, fmt::Display, sync::Arc};
use compactor_scheduler::CompactionJob;
use futures::{stream::BoxStream, StreamExt};
use super::super::{
compaction_jobs_source::CompactionJobsSource, partition_files_source::rate_limit::RateLimit,
};
use super::CompactionJobStream;
#[derive(Debug)]
pub ... |
//! 预约和处理时钟中断
// 时钟中断也需要我们在初始化操作系统时开启, 我们同样只需使用 riscv 库中提供的接口即可。
use crate::sbi::set_timer;
use riscv::register::{time, sie};
// sstatus 寄存器中的 SIE 位决定中断是否能够打断 supervisor 线程
// 在这里我们需要允许时钟中断打断 内核态线程
// 另外,无论 SIE 位为什么值,中断都可以打断用户态的线程。
/// 初始化时钟中断
///
/// 开启时钟中断使能,并且预约第一次时钟中断
/// 我们会在线程开始运行时开启中断,而在操作系统初始化的... |
use std::io::Write;
use std::path::{Display, Path, PathBuf};
use deck_core::FilesystemId;
use futures::future::poll_fn;
use futures_preview::compat::Future01CompatExt;
use futures_preview::future::{FutureExt, TryFutureExt};
use tokio::fs::{self, File, OpenOptions};
use crate::local::file::{FileFutureExt, LockedFile};... |
//! 使用 线段树 进行页式内存管理,每次分配一个页面
use super::Allocator;
use alloc::{vec, vec::Vec};
// 空间复杂度有所下降,每个物理页面占用 固定 2bit 空间, 大大减小
// 时间复杂度上升,从O(1) -> O(logn)
// 对于每个块,都有左右指针指向其管理的内存地址 [left, right)
// 内存分配实际上就是区间查询出满足大小要求的内存块,并进行区间更新,将内存块更新为已占用
// 内存释放实际上就是进行区间更新操作,将内存块更新为未使用
// 内存释放: 更新父区间的字段状态 => 更新左子区间的字段状态 + 更新... |
//! Metadata encoding and decoding.
//!
//! # Data Flow
//! The following diagram shows how metadata flows through the system from the perspective of the parquet reader/writer:
//!
//! 1. **Incoming Data:** Incoming data contains one or multiple [Apache Arrow] `RecordBatch`, IOx-specific statistics,
//! the IOx-spec... |
use super::externals::{wasm_extern_t, wasm_extern_vec_t};
use super::module::wasm_module_t;
use super::store::wasm_store_t;
use super::trap::wasm_trap_t;
use crate::ordered_resolver::OrderedResolver;
use std::mem;
use std::sync::Arc;
use wasmer::{Extern, Instance};
#[allow(non_camel_case_types)]
pub struct wasm_instan... |
use std::fmt::{Display, Formatter};
use ic_cdk::export::candid::{CandidType, Deserialize};
use ic_cdk::export::Principal;
use ic_cron::u8_enum;
use currency_token_client::types::Payload;
pub enum Error {
InsufficientBalance,
ZeroQuantity,
AccessDenied,
ForbiddenOperation,
}
impl Display for Error {
... |
#[derive(Debug)]
struct Rectangle {
width: u32,
height: u32,
}
fn main() {
let rect1 = Rectangle { width: 30, height: 50 };
println!("rect1 is: {:?}", rect1);
println!(
"The area of the rectangle is {} square pixels.",
rect1.area()
);
let rec2 = Rectangle {width:50, height... |
#[doc = r"Value read from the register"]
pub struct R {
bits: u32,
}
impl super::_0_FLTSTAT0 {
#[doc = r"Reads the contents of the register"]
#[inline(always)]
pub fn read(&self) -> R {
R {
bits: self.register.get(),
}
}
}
#[doc = r"Value of the field"]
pub struct PWM_0_F... |
extern crate sa2_text;
extern crate prs_util;
extern crate serde_json;
use std::env;
use std::error::Error;
use std::fmt;
use std::fs::File;
use std::io::{Cursor, Read, Write};
use std::path::PathBuf;
use std::process;
use sa2_text::{Sa2TextTable, Language};
use prs_util::encoder::Encoder;
use prs_util::decoder::Deco... |
// Copyright 2022 Datafuse Labs.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agre... |
use proconio::input;
fn main() {
input! {
a:i32,
b:i32,
}
println!("{}", ((2 * a) + (100)) - b);
}
|
use crate::il::Expression as Expr;
use crate::il::*;
use crate::translator::x86::mode::Mode;
use crate::Error;
use falcon_capstone::capstone_sys::x86_reg;
const X86REGISTERS: &[X86Register] = &[
X86Register {
name: "ah",
capstone_reg: x86_reg::X86_REG_AH,
full_reg: x86_reg::X86_REG_EAX,
... |
use crate::classify::Classification;
use hashbrown::HashMap;
use metric::{Attributes, DurationHistogram, Metric, ResultMetric, U64Counter};
use parking_lot::{MappedMutexGuard, Mutex, MutexGuard};
use std::sync::Arc;
use std::time::Instant;
/// `MetricsCollection` is used to retrieve `MetricsRecorder` for instrumenting... |
use alloc::{vec, vec::Vec};
use core::{
borrow::BorrowMut,
convert::{TryFrom, TryInto},
hint::unreachable_unchecked,
};
use super::partitions::Partition;
use crate::svec::SVec;
/// The char used for directory seperation (standard is '/', but we are having fun here)
const SEPARATOR_CHAR: u8 = b'>';
#[derive(Clone,... |
use std::thread;
use std::sync::{Mutex,Arc};
struct Philosopher{
name:String,
left:usize,
right:usize,
}
impl Philosopher{
fn new(name: &str,left:usize,right:usize)->Philosopher{
Philosopher{
name:name.to_string(),
left:left,
right:right,
}
}
fn eat(&self,table:&Table){
let _left=table.forks[self.... |
use async_graphql::{http::MultipartOptions, BatchRequest, Executor, Request};
use warp::{reply::Response as WarpResponse, Filter, Rejection, Reply};
use crate::{graphql_batch_opts, GraphQLBadRequest, GraphQLBatchResponse};
/// GraphQL request filter
///
/// It outputs a tuple containing the `async_graphql::Schema` an... |
#[derive(Clone, Copy, PartialEq, Eq, Debug, Hash)]
pub enum OverallAppraisal {
Bad,
Okay,
Good,
Great,
}
impl OverallAppraisal {
pub fn min_stats(self) -> IndividualValue {
match self {
OverallAppraisal::Great => IndividualValue::new(7, 7, 7).unwrap(),
OverallApprais... |
#![allow(non_snake_case, non_camel_case_types, non_upper_case_globals, clashing_extern_declarations, clippy::all)]
#[link(name = "windows")]
extern "system" {}
pub type Enterprise = *mut ::core::ffi::c_void;
pub type EnterpriseEnrollmentResult = *mut ::core::ffi::c_void;
#[repr(transparent)]
pub struct EnterpriseEnroll... |
fn main() {
let x = 5;
match x {
1 => println!("satu"),
2 => println!("dua"),
3 => println!("tiga"),
4 => println!("empat"),
5 => println!("lima"),
_ => println!("sesuatu lain"),
}
} |
use super::*;
#[derive(Clone, PartialEq, PartialOrd, Eq, Ord)]
pub struct Field(pub Row);
impl From<Row> for Field {
fn from(row: Row) -> Self {
Self(row)
}
}
impl Field {
pub fn name(&self) -> &'static str {
self.0.str(1)
}
pub fn is_literal(&self) -> bool {
self.0.u32(0... |
use std::thread;
use std::time::Duration;
use std::sync::{mpsc, Arc, Mutex, MutexGuard, RwLock};
use std::sync::mpsc::{TryRecvError, Sender, Receiver};
use crate::instruction::Instruction;
use std::thread::JoinHandle;
use crate::stack::{Stack};
use crate::opcode::OpCode;
use crate::register::Register;
use rand... |
use clap::{
self, crate_description, crate_name, crate_version, value_t, value_t_or_exit, App, AppSettings,
Arg, ArgGroup, ArgMatches, SubCommand, Values,
};
use num_traits::cast::ToPrimitive;
use spl_associated_token_account::{
self, create_associated_token_account, get_associated_token_address,
};
use me... |
mod aligned_binary;
mod builder;
mod compare;
mod heap;
mod iter;
mod literal;
mod match_context;
pub mod matcher;
mod maybe_aligned_maybe_binary;
mod primitives;
mod process;
mod sub;
use core::fmt;
use core::str::Utf8Error;
use thiserror::Error;
use crate::erts::exception::Alloc;
use crate::erts::string::Encoding;... |
use aoc_runner_derive::aoc;
use std::fmt;
#[derive(Debug, PartialEq, Copy, Clone)]
enum GridValue {
Floor,
Empty,
Occupied,
}
enum SeatingAlgo {
Near,
Far,
}
type Grid = Vec<GridValue>;
struct SeatMap {
grid: Grid,
width: usize,
height: usize,
seating_algo: SeatingAlgo,
coord... |
use std::{
sync::{
mpsc::{self, Sender},
Arc, Mutex,
},
thread::{self, JoinHandle},
};
pub struct ThreadPool {
sender: Sender<Message>,
workers: Vec<Worker>,
}
impl ThreadPool {
pub fn new(limit: usize) -> ThreadPool {
let (sender, receiver) = mpsc::channel();
l... |
#[doc = r"Register block"]
#[repr(C)]
pub struct RegisterBlock {
#[doc = "0x00 - MDIOS configuration register"]
pub cr: CR,
#[doc = "0x04 - MDIOS write flag register"]
pub wrfr: WRFR,
#[doc = "0x08 - MDIOS clear write flag register"]
pub cwrfr: CWRFR,
#[doc = "0x0c - MDIOS read flag register... |
fn norm(p: (f64, f64)) -> f64 {
(p.0.powf(2.0) + p.1.powf(2.0)).sqrt()
}
fn sin(rad: f64) -> f64 {
use std::f64::consts::PI;
let eps = 1e-9;
// 2pi mod
let mut rad = rad % (2.0 * PI);
if rad < 0.0 {
rad += 2.0 * PI;
}
let sign: f64 = if rad.abs() > PI { -1.0 } else { 1.0 };
... |
// Copyright 2018 The Fuchsia Authors. All rights reserved.
// Copyright 2016 Joe Wilm, The Alacritty Project Contributors
//
// 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:/... |
use std::borrow::Cow;
use std::ops::RangeInclusive;
fn to_owned_cow<'a, T: ?Sized + ToOwned>(c: Cow<'a, T>) -> Cow<'static, T> {
Cow::Owned(c.into_owned())
}
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct Request<'a>(pub Cow<'a, [u8]>, pub Cow<'a, [u8]>);
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
pub enum ... |
use serde::*;
use std::fmt::{self, Debug, Formatter};
#[derive(Serialize, Deserialize, Clone, Debug)]
#[serde(rename_all = "camelCase")]
pub struct NCPF11 {
pub addon: bool,
pub name: String,
pub version: String,
pub underhaul_version: String,
pub overhaul: OverhaulConfiguration,
// TODO: addo... |
use input_i_scanner::{scan_with, InputIScanner};
fn main() {
let stdin = std::io::stdin();
let mut _i_i = InputIScanner::from(stdin.lock());
let s = scan_with!(_i_i, String);
let t = scan_with!(_i_i, String);
if s == t {
println!("Yes");
return;
}
let mut s: Vec<char> = s.... |
use super::*;
use std::convert::TryInto;
use proptest::prop_oneof;
use proptest::strategy::{BoxedStrategy, Just, Strategy};
use liblumen_alloc::erts::exception::{Class, Exception};
use proptest::test_runner::TestCaseError;
#[test]
fn without_class_errors_badarg() {
run!(
|arc_process| {
(
... |
use num::complex::Complex;
type Point = Complex<f64>;
fn angle(pa: Point, pb: Point, pc: Point) -> f64
{
((pa-pb)/(pc-pb)).arg()
}
fn triangle_area(pa: Point, pb: Point, pc: Point) -> f64
{
let dist_ab = (pb-pa).norm();
let dist_bc = (pb-pc).norm();
dist_ab*dist_bc*angle(pa,pb,pc).sin()/2.
}
stru... |
// Copyright 2022 Datafuse Labs.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to ... |
use db;
use diesel::result::Error::DatabaseError;
use rocket::request::FlashMessage;
use rocket::request::Form;
use rocket::response::status;
use rocket::response::Flash;
use rocket_contrib::Template;
use tera::Context;
use user::UserCreateError::{DbError, HashError};
use user::{NewUser, User};
#[derive(FromForm)]
pub... |
#![cfg(test)]
use std::collections::HashSet;
use rustc_serialize::json::{Json, Object, Array};
use token::TokenData;
use context::{SharedContext, Mode};
use ast::*;
use estree::deserialize::{Deserialize, ExtractField, IntoNode, IntoToken, MatchJson};
pub struct ParserTest {
pub source: String,
pub expected: O... |
use async_trait::async_trait;
use data_types::{NamespaceName, NamespaceSchema};
use iox_time::{SystemProvider, TimeProvider};
use metric::{DurationHistogram, Metric};
use std::sync::Arc;
use trace::{ctx::SpanContext, span::SpanRecorder};
use super::DmlHandler;
/// An instrumentation decorator recording call latencies... |
// auto generated, do not modify.
// created: Mon Feb 22 23:57:02 2016
// src-file: /QtCore/qxmlstream.h
// dst-file: /src/core/qxmlstream.rs
//
// header block begin =>
#![feature(libc)]
#![feature(core)]
#![feature(collections)]
extern crate libc;
use self::libc::*;
// <= header block end
// main block begin =>
/... |
/*
Copyright (c) 2015, 2016 Saurav Sachidanand
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, di... |
use super::{Trait, Module};
use frame_support::dispatch::DispatchErrorWithPostInfo;
use frame_support::dispatch::DispatchResultWithPostInfo;
use frame_support::dispatch::PostDispatchInfo;
use frame_support::dispatch::Weight;
use frame_support::weights::Pays;
use frame_support::decl_error;
use move_vm::types::VmResult;
... |
extern crate ili9163c;
extern crate ili9163c_simulator;
fn main() {
let mut driver = ili9163c_simulator::Simulator::driver(128, 128);
let yellow = ili9163c::driver::parse_color(255, 255, 100);
driver.draw_line((0, 0), (127, 127), yellow);
for i in 0..8 {
let i = i * 16;
let orange = ili... |
// fro(m)(in)to
// casting for structs/enums
use std::convert::From;
use std::convert::TryFrom;
// why do we need this, and we do not need the std::convert::Into ???
use std::convert::TryInto;
#[derive(Debug)]
struct Number{
value: i32,
}
impl From<i32> for Number{
fn from(item: i32) -> Self{
Number{value: i... |
use futures::{Async, Future, Stream, Poll};
use tokio_io::{AsyncRead, AsyncWrite};
use body::{Body, Payload};
use common::drain::{self, Draining, Signal, Watch, Watching};
use common::exec::{H2Exec, NewSvcExec};
use service::{MakeServiceRef, Service};
use super::conn::{SpawnAll, UpgradeableConnection, Watcher};
#[all... |
pub struct Stack<T> {
data: Vec<T>,
}
impl<T> Stack<T> {
pub fn new() -> Stack<T> {
Stack {
data: Vec::new(),
}
}
pub fn push(&mut self, value: T) {
self.data.push(value)
}
pub fn pop(&mut self) -> Option<T> {
self.data.pop()
}
}
|
pub struct Solution;
impl Solution {
pub fn max_points(points: Vec<Vec<i32>>) -> i32 {
use std::collections::HashMap;
let mut max = 0;
for i in 0..points.len() {
if i + max >= points.len() {
break;
}
let mut same = 1;
let mut m... |
#[derive(Copy, Clone, Debug)]
pub enum Dir {
U,
D,
L,
R,
}
impl From<char> for Dir {
fn from(ch: char) -> Self {
use Dir::{D, L, R, U};
match ch {
'U' => U,
'D' => D,
'L' => L,
'R' => R,
_ => unreachable!(),
}
}
... |
use juniper::graphql_interface;
#[graphql_interface]
trait Character {
fn wrong(&self, #[graphql(default = [true, false, false])] input: [bool; 2]) -> bool;
}
fn main() {}
|
use std::cmp::{max, min};
use std::collections::{HashMap, HashSet};
use itertools::Itertools;
use whiteread::parse_line;
// dp
// https://atcoder.jp/contests/joi2015yo/tasks/joi2015yo_d
// i日目にちょうどj番目の都市につくときの疲労度
fn main() {
let (n, m): (usize, usize) = parse_line().unwrap();
let mut dd: Vec<usize> = vec![];
... |
use crate::gb::hardware::memory_bus::MemoryBus;
use crate::gb::hardware::registers::Registers;
use crate::gb::opcodes::ops;
use crate::gb::opcodes::table;
use crate::gb::opcodes::opcode::OPCode;
use std::fs::File;
#[derive(Clone)]
pub struct CPU {
pub bus: MemoryBus,
pub reg: Registers,
pub interrupts: b... |
use teensy3;
use core::fmt;
#[derive(Copy, Clone)]
pub struct Serial;
impl Serial {
pub fn readable(self) -> bool {
unsafe {
teensy3::usb_serial_available() > 0
}
}
pub fn read_byte(self) -> u8 {
self.try_read_byte().unwrap()
}
pub fn try_read_byte(self) -> R... |
use crate::windows_sys::{CreatePipe, INVALID_HANDLE_VALUE};
use std::{fs::File, io, os::windows::prelude::*, ptr};
/// NOTE: These pipes do not support IOCP.
///
/// If IOCP is needed, then you might want to emulate
/// anonymous pipes with CreateNamedPipe, as Rust's stdlib does.
pub(super) fn pipe() -> io::Result<(Fi... |
use std::ops::RangeInclusive;
use itertools::Itertools;
use rayon::prelude::*;
use summed_area_table::{SummedAreaTable, SummedAreaTableSource, VecSource};
#[derive(Clone, Copy, Debug)]
struct Coordinates {
x: usize,
y: usize,
}
#[derive(Clone, Copy)]
struct Serial(usize);
fn power_level(coords: Coordinates,... |
use crate::{caveat, crypto, error::MacaroonError, Macaroon};
/// Type of callback for `Verifier::satisfy_general()`
pub type VerifierCallback = fn(&str) -> bool;
/// Verifier struct
///
/// Contains all information and maintains all state for the macaroon
/// verification process
#[derive(Default)]
pub struct Verifie... |
use crate::{
math::{Size, Vector2},
Backend, BoxConstraints,
};
use super::{TypedWidget, Widget};
pub struct WidgetPod<T, B: Backend> {
widget: Box<dyn TypedWidget<T, B>>,
state: WidgetState,
}
impl<T, B: Backend> WidgetPod<T, B> {
pub fn new<TW: TypedWidget<T, B> + 'static>(typed_widget: TW) -> ... |
// Copyright 2016 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... |
use projecteuler::primes;
fn main() {
dbg!(solve(20));
dbg!(solve(28123));
}
fn solve(n: usize) -> usize {
let sieve = primes::SieveDivisor::new(n + 1);
let mut abundant_numbers = Vec::new();
for i in 1..=n {
if i < sieve.sum_of_divisors::<usize>(i) - i {
abundant_numbers.push(... |
//! Utility functions related to xor encryption / decryption.
//!
//! Contains a mix bag of functions related to xor encryption / decryption.
extern crate hamming;
#[macro_use]
extern crate log;
use std::io::{Read, BufReader};
use std::fs::File;
use hamming::distance;
use std::collections::HashMap;
pub trait Xor {... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.