text stringlengths 8 4.13M |
|---|
extern crate foreach;
use foreach::*;
pub fn reply(message: &str) -> &str {
let message = message.trim_right();
let suffix: String = message
.chars()
.rev()
.take(1)
.into_iter()
.collect();
let all_caps_message = all_caps(&message);
match all_caps_message {
... |
// 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 ... |
const INPUT: &str = include_str!("./input");
fn part_1() -> usize {
count_by_slope(3, 1)
}
fn part_2() -> usize {
[(1, 1), (3, 1), (5, 1), (7, 1), (1, 2)]
.iter()
.map(|(x, y)| count_by_slope(*x, *y))
.product()
}
fn count_by_slope(step_x: usize, step_y: usize) -> usize {
INPUT
... |
/// validates ParseError Eq implementation
macro_rules! validate {
($cond:expr, $e:expr) => {
if !($cond) {
return Err($e);
}
};
($cond:expr, $fmt:expr, $($arg:tt)+) => {
if !($cond) {
return Err($fmt, $($arg)+);
}
};
}
|
use nickel::{Request, Response, Middleware, MiddlewareResult};
pub struct Logger;
impl<D> Middleware<D> for Logger {
fn invoke<'mw, 'conn>(&self, req: &mut Request<'mw, 'conn, D>, res: Response<'mw, D>)
-> MiddlewareResult<'mw, D> {
println!("Request from: {:?}", req.origin.uri);
res.next_middlewa... |
extern crate iron;
extern crate router;
use iron::prelude::*;
use iron::status;
use router::Router;
fn main() {
let mut router = Router::new();
router.get("/", suckit_nerds, "index");
router.get("/:query", suckit_nerds, "show");
fn suckit_nerds(req: &mut Request) -> IronResult<Response> {
let ref query ... |
#![allow(unused_variables, non_upper_case_globals, non_snake_case, unused_unsafe, non_camel_case_types, dead_code, clippy::all)]
#[repr(transparent)]
#[doc(hidden)]
pub struct IInjectedInputGamepadInfo(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for IInjectedInputGamepadInfo {
type Vt... |
#[doc(hidden)]
#[macro_export]
macro_rules! declare_comp_field_accessor {(
attrs=[ $($extra_attrs:meta),* $(,)* ]
) => (
/// A compressed field accessor,represented as 3 bits inside of a CompTLField.
#[repr(transparent)]
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
$(#[ $extra_attrs ])*
pub st... |
use chrono::prelude::*;
use chrono::offset::LocalResult;
pub fn sekarang() {
let utc: DateTime<Utc> = Utc::now();
println!("{:?}", utc);
let dt: DateTime<Local> = Local::now();
println!("{:?}", dt);
let dt1 = Utc.ymd(10, 1, 1).and_hms(10, 10, 5);
println!("{:?}", dt1);
}
|
use crate::{
expression::{Expression, Literal},
statement::Declaration,
Identifier, Node, NodeKind, SourceLocation,
};
#[derive(Debug)]
pub enum ModuleDeclaration {
Import(ImportDeclaration),
Export(ExportDeclaration),
}
impl Node for ModuleDeclaration {
fn loc(&self) -> SourceLocation {
... |
//! Tokenizer
use core::iter::Peekable;
/// Token
#[derive(Debug, Copy, Clone, PartialEq)]
pub enum Token {
/// like 1.0
Number(f64),
/// `(`
ParenOpen,
/// `)`
ParenClose,
/// `+`
Add,
/// `-`
Sub,
/// `*`
Mul,
/// `/`
Div,
/// `**`
Pow,
/// Space
... |
use crate::classfile::attr_info::{LineNumber, TargetInfo, TypeAnnotation};
use crate::classfile::{
attr_info::{self, AttrTag, AttrType},
constant_pool::*,
field_info::FieldInfo,
method_info::MethodInfo,
ClassFile, Version,
};
use crate::types::*;
use bytes::Buf;
use std::io::{Cursor, Read};
//use st... |
use diesel;
use diesel::mysql::MysqlConnection;
use diesel::prelude::*;
use schema::clients;
#[table_name = "clients"]
#[derive(Serialize, Deserialize, Queryable, Insertable, AsChangeset)]
pub struct Client {
pub id: i32,
pub name: String,
}
#[table_name = "clients"]
#[derive(FromForm, Deserialize, Insertable... |
use challenges::random_bytes;
use cipher::{self, cbc::AES_128_CBC, padding, Cipher};
use rand::{self, Rng};
use std::fs;
fn main() {
println!("🔓 Challenge 17");
let key = Key::new();
padding_oracle_attack(&key);
}
fn padding_oracle_attack(key: &Key) {
let ct = key.encryption_oracle(); // remember the... |
use std::string::String;
use std::slice::SliceExt;
struct Executable {
cmd: &str,
args: &[&str],
prev: char,
}
impl Executable {
fn new(st: String) -> Executable {
let out: &[&str] = st.trim().words().collect();
let (cmd1, args1) = out.split_at(1);
let exe = Executable { cmd: c... |
#![deny(warnings)]
pub mod ir;
pub mod write;
pub use self::ir::*;
|
use crate::errors::ServiceError;
//use crate::models::fcm::{Params, ParamsToFcm};
use crate::models::msg::Msg;
use crate::schema::user_device;
use actix::Message;
use chrono::NaiveDateTime;
use serde::{Deserialize, Serialize};
use uuid::Uuid;
#[derive(
Clone,
Debug,
Serialize,
Associations,
Deseria... |
use super::*;
/// Represents the built-in FuncOp from the `func` dialect
#[repr(transparent)]
#[derive(Copy, Clone)]
pub struct FuncOp(OperationBase);
impl FuncOp {
/// Returns the function symbol name
pub fn name(self) -> StringRef {
SymbolTable::get_symbol_name(self)
}
/// Returns the visibi... |
use super::super::stat::Stat;
#[allow(dead_code)]
pub enum LevelColumn {
MP,
MAIN,
SUB,
DIV,
HP,
ELMT,
THREAT,
}
// Assume level 80
// https://www.akhmorning.com/allagan-studies/modifiers/
#[allow(dead_code)]
pub fn level_modifiers(column: LevelColumn) -> i64 {
match c... |
use std::error::Error;
use std::result::Result;
use structopt::StructOpt;
/// Parse a single key-value pair
fn parse_key_val<T, U>(s: &str) -> Result<(T, U), Box<dyn Error>>
where
T: std::str::FromStr,
T::Err: Error + 'static,
U: std::str::FromStr,
U::Err: Error + 'static,
{
let pos = s
.fi... |
use liblumen_alloc::erts::exception::InternalResult;
use liblumen_alloc::erts::term::prelude::*;
use liblumen_alloc::erts::Process;
use super::{try_split_at, u32, u8};
pub fn decode<'a>(process: &Process, bytes: &'a [u8]) -> InternalResult<(Term, &'a [u8])> {
let (len_u32, after_len_bytes) = u32::decode(bytes)?;
... |
use chrono::offset::Utc;
use chrono::DateTime;
use libc::{time, sleep, difftime, gmtime, mktime, localtime};
use std::ptr;
use std::time::{Duration, UNIX_EPOCH};
use std::ops::Add;
use std::ffi::CStr;
fn main() {
unsafe {
let time1 = time(ptr::null_mut());
sleep(2);
let time2 ... |
pub use self::dmi::*;
pub use self::io::*;
pub use self::mmio::*;
pub use self::pio::*;
mod dmi;
mod io;
mod mmio;
mod pio;
|
fn is_palindrome(s: &str) -> bool {
let len = s.len() - 1;
let offset = if len % 2 == 0 { 0 } else { 1 };
let start = s[..(len + offset) / 2].chars();
let end = s[(len - offset) / 2 + 1..].chars().rev();
start.zip(end).fold(true, |state, (x, y)| state && x == y)
}
fn main() {
let mut m: Vec<u... |
//! A generic UI state model for scrollable view of hexagonal grids.
use crate::geo::{ Bounds, Hexagon };
use crate::grid::{ Grid, Coords };
use crate::ui::scroll;
use nalgebra::Point2;
/// The state of a scrollable grid view.
pub struct State<C: Coords> {
grid: Grid<C>,
viewport: Bounds,
position: Poin... |
// Copyright (c) The Starcoin Core Contributors
// SPDX-License-Identifier: Apache-2.0
use anyhow::Result;
use lazy_static::lazy_static;
use log::LevelFilter;
use log4rs::append::console::{ConsoleAppender, Target};
use log4rs::append::file::FileAppender;
use log4rs::config::{Appender, Config, Root};
use log4rs::encode... |
use crate::{types::PyComparisonOp, vm::VirtualMachine, PyObjectRef, PyResult};
use itertools::Itertools;
pub trait PyExactSizeIterator<'a>: ExactSizeIterator<Item = &'a PyObjectRef> + Sized {
fn eq(self, other: impl PyExactSizeIterator<'a>, vm: &VirtualMachine) -> PyResult<bool> {
let lhs = self;
l... |
use std::fs;
use std::collections::HashSet;
fn main() {
let input_numbers = parse_input();
let mut numbers: HashSet<usize> = HashSet::new();
for i in input_numbers {
if numbers.contains(&(2020 - i)) {
println!("Found: {}", i * (2020 - i));
}
numbers.insert(i);
}
}
f... |
use ggez::graphics::*;
use specs::{Builder, World};
use std::collections::HashMap;
use components::*;
use state::*;
pub struct CharacterBuilder {
id: Option<EntityID>,
tile_width: Option<usize>,
pub render: Option<EntityRender>,
t_pos: Option<TilePosition>,
anim_map: HashMap<String, Vec<usize>>,
... |
//! Contains helper functions
use crate::characteranimation::CharacterAnimation;
use crate::charactermeta::CharacterDirection;
use crate::charactermeta::CharacterMeta;
use crate::charactermove::CharacterMove;
use crate::spriteanimation::SpriteAnimation;
use crate::spriteanimationloader::SpriteAnimationStore;
use crate... |
//! Provides a generic framework for building copy-on-write B-Tree-like structures.
//!
//! The design and implementation was inspired by [xi-rope].
//!
//! [xi-rope]: https://github.com/google/xi-editor/tree/master/rust/rope
extern crate arrayvec;
extern crate mines;
#[macro_use]
mod macros;
pub mod cursor;
pub mod ... |
fn main() {
// data type
// integer: i8, u8, i16, u16, i32, u32, i64, u64 -> actual memory
let a = 1 + 20;
let s = 32 - 20;
let m = 5 * 10;
// float: f32, f64
// bool: true/false
let b = true;
// tuple
let t: (i32, f64, char) = (42, 6.12, 'j');
let (_, _, x) = t;... |
// Copyright (c) The Libra Core Contributors
// SPDX-License-Identifier: Apache-2.0
//! Names of modules and functions used by Libra System.
use libra_types::language_storage::ModuleId as LibraModuleId;
use move_core_types::identifier::Identifier;
use once_cell::sync::Lazy;
use types::{account_config, language_storage... |
pub mod config;
pub mod database;
pub mod logging;
pub use self::config::Config;
pub use self::database::DB;
pub use self::logging::Logger;
|
#![allow(unused_variables, non_upper_case_globals, non_snake_case, unused_unsafe, non_camel_case_types, dead_code, clippy::all)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)]
#[repr(transparent)]... |
pub mod shader_compilation;
pub mod vao;
pub mod vbo;
pub mod ebo;
pub mod texture_2d;
pub mod texture_cube_map;
pub mod fbo;
pub mod rbo;
pub mod ubo;
pub use shader_compilation::*;
pub use vao::*;
pub use vbo::*;
pub use ebo::*;
pub use texture_2d::*;
pub use texture_cube_map::*;
pub use fbo::*;
pub use rbo::*;
pub ... |
#![feature(llvm_asm)]
fn main() {
let x = ();
unsafe {
let p: *const () = &x;
llvm_asm!("" :: "r"(*p));
}
}
|
use std::borrow::Cow;
use std::ops::{Bound, RangeBounds};
use std::{mem, ptr};
use crate::mdb::error::mdb_result;
use crate::mdb::ffi;
use crate::types::DecodeIgnore;
use crate::*;
/// A polymorphic database that accepts types on call methods and not at creation.
///
/// # Example: Iterate over ranges of databases en... |
use std::error::Error;
use tokio::{self};
mod downloader;
#[tokio::main]
async fn main() -> Result<(), Box<dyn Error>> {
let mut d1 = downloader::Downloader::new(None, None);
d1.enque_file(
"http://212.183.159.230/5MB.zip".to_string(),
"./5mb.zip".to_string(),
);
// let writer = downloa... |
use bitflags::bitflags;
use bytes::{Buf, Bytes};
use crate::error::Error;
use crate::mssql::io::MssqlBufExt;
use crate::mssql::protocol::col_meta_data::Flags;
#[cfg(test)]
use crate::mssql::protocol::type_info::DataType;
use crate::mssql::protocol::type_info::TypeInfo;
#[allow(dead_code)]
#[derive(Debug)]
pub(crate) ... |
mod expr_type_evaluator;
mod field;
mod field_mapper;
mod ir;
mod planner;
mod planner_rewrite_expression;
mod planner_time_range_expression;
mod rewriter;
mod test_utils;
mod udf;
mod util;
mod var_ref;
pub use planner::InfluxQLToLogicalPlan;
pub use planner::SchemaProvider;
pub(crate) use util::parse_regex;
|
// 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 std::fs;
use std::io::Write;
use tokio::net::TcpListener;
use tokio::prelude::*;
mod camera;
mod livestream;
mod encode;
mod inference_engine;
mod timer;
mod realtime;
mod api;
mod jpegdecode;
#[cfg(windows)]
use camera::camera_win::WindowsCamera;
#[cfg(any(unix, macos))]
use camera::camera_pi::PiCamera;
use crate:... |
use super::{ChannelID, UserID};
use deadpool_postgres::{Pool, PoolError};
use deadpool_postgres::tokio_postgres::Row;
pub type MessageID = i32;
pub async fn recent_messages(pool: Pool, channel_id: ChannelID) -> Result<Vec<Row>, PoolError> {
let conn = pool.get().await?;
let stmt = conn.prepare("
SELEC... |
extern crate time;
// Type alias for function that returns true if arguments should be swapped
type OrderFunc<T> = Fn(&T, &T) -> bool;
fn main() {
let less_start_time = time::precise_time_ns();
// Sort numbers
println!("");
let mut numbers = [80, 32, 19, 56, -15, 1, -1, 0, 782, 1];
println!("US: {... |
extern crate ggez;
extern crate nalgebra;
extern crate markedly;
extern crate metrohash;
use std::path::{PathBuf};
use nalgebra::{Point2, Vector2};
use metrohash::{MetroHashMap};
use ggez::conf::{NumSamples};
use ggez::graphics::{self, Rect, Font, Text, Canvas, Mesh};
use ggez::{Context, GameError};
use markedly::re... |
use std::fmt::Debug;
#[derive(PartialEq, Eq)]
struct Variant {
variant: String,
}
trait GetVariant where Self: Debug {
fn get_variant(&self) -> Variant {
let this_variant = format!("{:?}", self);
let mut result = "".to_string();
for i in this_variant.chars() {
if i == '(' {... |
const FP_ILOGBNAN: i32 = -1 - 0x7fffffff;
const FP_ILOGB0: i32 = FP_ILOGBNAN;
#[cfg_attr(all(test, assert_no_panic), no_panic::no_panic)]
pub fn ilogbf(x: f32) -> i32 {
let mut i = x.to_bits();
let e = ((i >> 23) & 0xff) as i32;
if e == 0 {
i <<= 9;
if i == 0 {
force_eval!(0.0 ... |
//! Initialization code
#![feature(panic_implementation)]
#![no_std]
#[macro_use]
extern crate cortex_m;
#[macro_use]
extern crate cortex_m_rt;
extern crate f3;
use core::panic::PanicInfo;
use core::sync::atomic::{self, Ordering};
pub use cortex_m::asm::bkpt;
pub use cortex_m::peripheral::ITM;
use cortex_m_rt::Exce... |
use heap::{Heap, HeapSessionId};
use ptr::Pointer;
use std::fmt;
use std::marker::PhantomData;
use traits::IntoHeapAllocation;
pub struct GcRef<'h, T: IntoHeapAllocation<'h>> {
ptr: Pointer<T::In>,
heap_id: HeapSessionId<'h>,
}
impl<'h, T: IntoHeapAllocation<'h>> GcRef<'h, T> {
/// Pin an object, returnin... |
pub(crate) use _functools::make_module;
#[pymodule]
mod _functools {
use crate::{function::OptionalArg, protocol::PyIter, PyObjectRef, PyResult, VirtualMachine};
#[pyfunction]
fn reduce(
function: PyObjectRef,
iterator: PyIter,
start_value: OptionalArg<PyObjectRef>,
vm: &Vi... |
mod house
{
pub mod hosting
{
pub fn add() { }
fn seat() { }
}
mod serving
{
fn take() {}
fn order() {}
}
}
pub fn eat_out()
{
crate::house::hosting::add();
house::hosting::add();
} |
//! Tests for `#[graphql_subscription]` macro.
pub mod common;
use std::pin::Pin;
use futures::{future, stream, FutureExt as _};
use juniper::{
execute, graphql_object, graphql_subscription, graphql_value, graphql_vars,
resolve_into_stream, DefaultScalarValue, EmptyMutation, Executor, FieldError, FieldResult... |
//! [](https://docs.rs/ste)
//! [](https://crates.io/crates/ste)
//! [](https://github.com/udoprog/audio/actions)
//!
//! A single-threaded executo... |
use crate::pickledb::PickleDb;
use serde::Serialize;
/// A struct for extending PickleDB lists and adding more items to them
pub struct PickleDbListExtender<'a> {
pub(crate) db: &'a mut PickleDb,
pub(crate) list_name: String,
}
impl<'a> PickleDbListExtender<'a> {
/// Add a single item to an existing list.... |
use crate::{
core::{
error::Error,
frame_buffer::{FrameBuffer, FrameBufferRef},
header::HeaderRef,
version::Version,
LevelMode, LevelRoundingMode,
},
multi_part::multi_part_input_file::MultiPartInputFile,
};
use imath_traits::Bound2;
use openexr_sys as sys;
use std::... |
use pickledb::error::ErrorType;
use pickledb::{PickleDb, PickleDbDumpPolicy};
#[macro_use(matches)]
extern crate matches;
extern crate fs2;
use fs2::FileExt;
use std::fs::File;
mod common;
#[test]
fn load_serialization_error_test() {
set_test_rsc!("json_db.db");
// create a new DB with Json serialization
... |
fn main() {
let stdin = std::io::stdin();
let mut rd = ProconReader::new(stdin.lock());
let n: usize = rd.get();
let dd: Vec<(usize, usize)> = (0..n)
.map(|_| {
let d1: usize = rd.get();
let d2: usize = rd.get();
(d1, d2)
})
.collect();
le... |
use proc_macro2::TokenStream;
use crate::utils::*;
pub(crate) const NAME: &[&str] = &["Transpose"];
// Implementing this with `Into` requires many type annotations.
pub(crate) fn derive(data: &Data, items: &mut Vec<ItemImpl>) -> Result<()> {
check_fields(data)?;
items.push(transpose_option(data)?);
item... |
//! Defines types required at exploration runtime.
mod integer_domain;
mod integer_set;
mod range;
use proc_macro2::TokenStream;
use quote::quote;
/// Returns the token stream defining the runtime.
pub fn get() -> TokenStream {
let range = range::get();
let integer_set = integer_set::get();
let integer_do... |
use proc_macro2::TokenStream as TokenStream2;
use quote::{quote_spanned, ToTokens};
use as_derive_utils::gen_params_in::InWhat;
use crate::sabi_trait::{TokenizerParams, WhichSelf, WithAssocTys};
/// Generates the code that delegates the implementation of the traits
/// to the wrapped DynTrait or RObject.
pub(super)... |
use assert_cmd::Command;
use predicates::prelude::*;
use std::fs;
/// Compare contents of test file with `stdout`
fn run(args: &[&str], file_name: &str) -> Result<(), Box<dyn std::error::Error>> {
let expected = fs::read_to_string(file_name)?;
Command::cargo_bin("rust-cat")?
.args(args)
.assert... |
impl Solution {
pub fn num_identical_pairs(nums: Vec<i32>) -> i32 {
let mut cnt = vec![0; 101];
for i in 0..nums.len() {
cnt[nums[i] as usize] += 1;
}
let mut ans = 0;
for i in 1..101 {
ans += (cnt[i] * (cnt[i] - 1)) / 2;
}
ans
... |
#[doc = r"Value read from the register"]
pub struct R {
bits: u32,
}
#[doc = r"Value to write to the register"]
pub struct W {
bits: u32,
}
impl super::CC {
#[doc = r"Modifies the contents of the register"]
#[inline(always)]
pub fn modify<F>(&self, f: F)
where
for<'w> F: FnOnce(&R, &'w m... |
// Copyright 2017 PingCAP, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to i... |
use super::io::*;
use super::board::*;
use super::minimax::*;
pub trait Player {
fn get_move(&self, mut board: Board) -> usize;
fn get_token(&self) -> usize;
}
pub struct CpuPlayer {
token: usize
}
impl CpuPlayer {
pub fn new(token: usize) -> CpuPlayer {
CpuPlayer { token: token }
}
}
im... |
use std::marker::PhantomData;
use ocl::{self, builders::KernelBuilder};
use crate::{Pack, Push, Context};
/// Device buffer of abstract entities. Entity should implement `Pack`.
pub struct InstanceBuffer<T: Pack + 'static> {
buffer_int: ocl::Buffer<i32>,
buffer_float: ocl::Buffer<f32>,
count: usize,
... |
// Copyright 2021 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 chrono::Duration;
use itertools::Itertools;
use serde::Deserialize;
use serde_with::{serde_as, CommaSeparator, DisplayFromStr, DurationSeconds, StringWithSeparator};
// <item name="drinkCanEmpty">
// <property name="HoldType" value="14"/>
// <property name="Meshfile" value="#Other/Items?Food/can_emptyPrefab.pref... |
use std::mem;
#[derive(Debug)]
pub struct RecordingTimestamp(i64);
impl RecordingTimestamp {
//
// new
//
#[cfg(target_os = "windows")]
#[inline]
pub fn now() -> Self {
// https://docs.microsoft.com/en-us/windows/win32/sysinfo/acquiring-high-resolution-time-stamps
// https://d... |
// auto generated, do not modify.
// created: Mon Feb 22 23:57:02 2016
// src-file: /QtCore/qflags.h
// dst-file: /src/core/qflags.rs
//
// header block begin =>
#![feature(libc)]
#![feature(core)]
#![feature(collections)]
extern crate libc;
use self::libc::*;
// <= header block end
// main block begin =>
// <= mai... |
use proc_macro2;
use proc_macro2::Span;
use syn;
use field::*;
use meta::path_to_string;
use model::*;
use util::*;
use crate::meta::MetaItem;
pub fn derive(item: syn::DeriveInput) -> Result<proc_macro2::TokenStream, Diagnostic> {
let treat_none_as_default_value = MetaItem::with_name(&item.attrs, "diesel")
... |
use color_eyre::eyre::Result;
use log::*;
use minreq::get;
use prettytable::{cell, row, Table};
use sha::{
sha1::Sha1,
utils::{Digest, DigestExt, Reset},
};
use std::default::Default;
fn check_haveibeenpwned(pass: &str) -> Result<String, minreq::Error> {
let url = format!("https://api.pwnedpasswords.com/ra... |
// Copyright 2019 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
use {
crate::{
capability::*,
model::{
self,
addable_directory::{AddableDirectory, AddableDirectoryWithResult},... |
use abi_stable::{
abi_stability::{
abi_checking::{check_layout_compatibility_with_globals, AbiInstability, CheckingGlobals},
extra_checks::{
ExtraChecks, ExtraChecksBox, ExtraChecksError, ExtraChecksRef,
ForExtraChecksImplementor, StoredExtraChecks, TypeCheckerMut,
},... |
use std::error::Error;
use std::fmt;
#[derive(PartialEq, Debug, Clone)]
pub struct ValidationError {
details: String,
}
impl ValidationError {
pub fn new(msg: &str) -> ValidationError {
ValidationError {
details: msg.to_string(),
}
}
}
impl fmt::Display for ValidationError {
... |
use std::collections::HashMap;
use std::fmt::{Debug, Error, Formatter};
use std::hash::Hash;
use std::slice::Iter;
pub struct OrderedMap<S, T>
where
S: Hash + Eq + ToOwned<Owned = S>,
{
keys: Vec<S>,
map: HashMap<S, T>,
}
type OrderedMapIter<'a, S> = Iter<'a, S>;
impl<S, T> OrderedMap<S, T>
where
S: ... |
table! {
deals (id) {
id -> Int4,
buyer_id -> Nullable<Int4>,
seller_id -> Nullable<Int4>,
house_id -> Nullable<Int4>,
access_code -> Varchar,
status -> Varchar,
created -> Timestamp,
updated -> Timestamp,
title -> Varchar,
}
}
table! {
... |
use crate::{
activity::events::ActivityEvent,
handler::DiscordMsg,
lobby::events::LobbyEvent,
overlay::events::OverlayEvent,
proto::event::ClassifiedEvent,
relations::events::RelationshipEvent,
user::{events::UserEvent, User},
};
use tokio::sync::{broadcast, watch};
/// An event wheel, with... |
use std::{
error,
fmt::{self, Display, Formatter},
};
use crate::MAGIC_HEADER_BYTES;
#[derive(Debug)]
pub enum Error {
InvalidMagicHeaderString(String),
InvalidPageSize(String),
}
impl Display for Error {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
match self {
Self::Inv... |
use std::fs::File;
use std::io::{BufRead, BufReader};
use std::cmp::{min, max};
fn gcd(mut a: usize, mut b: usize) -> usize {
while b > 0 {
let rem = a % b;
a = b;
b = rem;
}
a
}
fn main() {
let grid = BufReader::new(File::open("in_10.txt").unwrap()).lines().map(|row| row.unwrap().chars().coll... |
//! Small library providing some macros helpful for asserting. The API is very
//! similar to the API provided by the stdlib's own `assert_eq!`, `assert_ne!`,
//! `debug_assert_eq!`, or `debug_assert_ne!`.
//!
//! | Name | Enabled | Equivalent to |
//... |
//
#![allow(non_snake_case)]
fn main() {
simple(0.0, 0.0, 89.0, 0.0);
}
fn simple(lat1: f64, lng1: f64, lat2: f64, lng2: f64) {
let a = 6378137.0; // 長軸半径 (赤道半径)
let phi1 = lat1.to_radians();
let L1 = lng1.to_radians();
let phi2 = lat2.to_radians();
let L2 = lng2.to_radians();
let L = L2... |
{doc_comment}
#[derive(Copy, Clone, PartialEq, Eq, Hash, Serialize, Deserialize, Ord, PartialOrd)]
#[repr(C)]
pub struct {type_name} {{ bits: {bits_type} }}
impl {type_name} {{
{value_defs}{alias_defs}
pub const ALL: {type_name} = {type_name} {{ bits: {all_bits} }};
/// Returns the empty domain.
pub ... |
#[derive(Serialize, Deserialize, Debug,)]
pub enum ErrorCode {
BAD_REQUEST,
NOT_FOUND,
INTERNAL
} |
#[path = "band_2/with_big_integer_left.rs"]
mod with_big_integer_left;
#[path = "band_2/with_small_integer_left.rs"]
mod with_small_integer_left;
test_stdout!(without_integer_right_errors_badarith, "{caught, error, badarith}\n{caught, error, badarith}\n{caught, error, badarith}\n{caught, error, badarith}\n{caught, err... |
pub mod matrix {
pub fn print_matrix(mat: &Vec<Vec<i32>>) {
for i in mat.iter() {
println!("{:?}", i);
}
}
pub fn create_identity_matrix(row_size: usize, col_size: usize) -> Vec<Vec<i32>>{
let mut mat = vec![Vec::with_capacity(row_size); col_size];
for i in 0..ma... |
// memory layout
fn destroy(value: Vec<i32>){
println!("sending to the kitchen sink");
for i in value.iter(){
println!("{}",i);
}
}
// duplicate
fn dup(values: &mut Vec<i32>){
for i in values.iter_mut() {
*i = (*i) * (*i);
}
}
fn main(){
let mut x = vec![4, 6,954, 85, 45 , 323, 84, 9];
... |
use itertools::Itertools;
use crate::file_util::read_lines_as_u32;
fn find_pair_summing_to(numbers: &[u32], value: u32) -> Option<(&u32, &u32)> {
numbers.iter().tuple_combinations()
.find(|(first, second)| *first + *second == value)
}
fn find_triple_summing_to(numbers: &[u32], value: u32) -> Option<(&u32,... |
use crate::prelude::*;
#[repr(C)]
#[derive(Debug)]
pub struct VkSubpassDependency {
pub srcSubpass: u32,
pub dstSubpass: u32,
pub srcStageMask: VkPipelineStageFlagBits,
pub dstStageMask: VkPipelineStageFlagBits,
pub srcAccessMask: VkAccessFlagBits,
pub dstAccessMask: VkAccessFlagBits,
pub d... |
use std::{collections::HashMap, fmt};
use serde::{Serialize, Deserialize};
pub struct SendMessage {
pub content: String,
pub nonce: String,
pub attachments: Vec<String>,
pub replies: HashMap<String, bool>
}
#[derive(Debug, Serialize, Deserialize)]
pub struct Message {
pub _id: String,
... |
/*
* Firecracker API
*
* RESTful public-facing API. The API is accessible through HTTP calls on specific URLs carrying JSON modeled data. The transport medium is a Unix Domain Socket.
*
* The version of the OpenAPI document: 0.25.0
* Contact: compute-capsule@amazon.com
* Generated by: https://openapi-generator.t... |
#![feature(proc_macro)]
extern crate proc_macro;
use proc_macro::TokenStream;
#[proc_macro_attribute]
pub fn rustc_ice(_: TokenStream, x: TokenStream) -> TokenStream {
x
}
|
use std::fmt;
use std::error;
/// Error is the error value in an operation's
/// result.
///
/// Based on the two possible values, the operation
/// may be retried.
pub enum Error<E> {
/// Permanent means that it's impossible to execute the operation
/// successfully. This error is immediately returned from `r... |
use crate::Error;
use half::f16;
use openexr_sys as sys;
use crate::core::refptr::{OpaquePtr, Ref, RefMut};
type Result<T, E = Error> = std::result::Result<T, E>;
/// A usually small, low-dynamic range image,
/// that is intended to be stored in an image file's header
#[repr(transparent)]
pub struct Previ... |
use std::sync::Arc;
use arrow::{self, datatypes::SchemaRef};
use schema::TIME_COLUMN_NAME;
use snafu::{ResultExt, Snafu};
#[derive(Debug, Snafu)]
pub enum Error {
#[snafu(display("Error finding field column: {:?} in schema '{}'", column_name, source))]
ColumnNotFoundForField {
column_name: String,
... |
use crate::buffer;
pub struct Painter {
float_offset: f32,
last_frame: u32,
}
impl Painter {
const COLOR1: u32 = 0xFF666666;
const COLOR2: u32 = 0xFFEEEEEE;
pub fn new() -> Painter {
Painter {
float_offset: 0.0,
last_frame: 0,
}
}
pub fn draw(&s... |
/*
* @lc app=leetcode.cn id=51 lang=rust
*
* [51] N皇后
*
* https://leetcode-cn.com/problems/n-queens/description/
*
* algorithms
* Hard (58.96%)
* Total Accepted: 4.8K
* Total Submissions: 8.1K
* Testcase Example: '4'
*
* n 皇后问题研究的是如何将 n 个皇后放置在 n×n 的棋盘上,并且使皇后彼此之间不能相互攻击。
*
*
*
* 上图为 8 皇后问题的一种解法。
*
... |
//! The BSD sockets API requires us to read the `ss_family` field before
//! we can interpret the rest of a `sockaddr` produced by the kernel.
#![allow(unsafe_code)]
use crate::backend::c;
use crate::io;
use crate::net::{Ipv4Addr, Ipv6Addr, SocketAddrAny, SocketAddrUnix, SocketAddrV4, SocketAddrV6};
use core::mem::siz... |
use legion::*;
use super::{components, config::Config, time::Time, PhysicsPipeline};
pub struct Simulation {
pub world: World,
pub resources: Resources,
pub physics: PhysicsPipeline,
}
impl Simulation {
pub fn new(config: Config) -> Simulation {
let mut world = World::default();
let m... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.