text stringlengths 8 4.13M |
|---|
use serde::Deserialize;
#[derive(Debug, Deserialize)]
pub struct Names {
pub international: Box<str>,
pub japanese: Option<Box<str>>,
pub twitch: Option<Box<str>>,
}
pub type Id = arrayvec::ArrayString<[u8; 8]>;
|
use std::time::Duration;
pub trait Millis {
fn as_millis(&self) -> u64;
}
impl Millis for Duration {
fn as_millis(&self) -> u64 {
return (self.as_secs() * 1_000) + (self.subsec_nanos() / 1_000_000) as u64;
}
}
|
use rand::thread_rng;
use rand::distributions::{IndependentSample, Range};
use sigmoid::Sigmoid;
use num::Float;
type Matrix = Vec<Vec<f64>>;
#[derive(Debug)]
pub struct Network {
input: Matrix,
output: Matrix, // expected output for input
sigmoid: Sigmoid, // sigmoid function
layers: Vec<Layer>, // n... |
#![allow(unused_variables, non_upper_case_globals, non_snake_case, unused_unsafe, non_camel_case_types, dead_code, clippy::all)]
#[cfg(feature = "Win32_Media_Audio")]
pub mod Audio;
#[cfg(feature = "Win32_Media_DeviceManager")]
pub mod DeviceManager;
#[cfg(feature = "Win32_Media_DirectShow")]
pub mod DirectShow;
#[cfg(... |
use rocket::http::{ContentType, Status};
use rocket::response::{self, Responder};
use rocket::{Outcome, Request, Response, State};
use slog;
use slog::Logger;
use std::io::Cursor;
#[derive(Debug, Serialize, Clone)]
pub enum ErrorCode {
NoAuthToken,
NotFound,
InvalidData,
DbError,
NotAuthorized,
... |
use clippy_utils::diagnostics::span_lint;
use clippy_utils::{binop_traits, trait_ref_of_method, BINOP_TRAITS, OP_ASSIGN_TRAITS};
use if_chain::if_chain;
use rustc_hir as hir;
use rustc_hir::intravisit::{walk_expr, NestedVisitorMap, Visitor};
use rustc_lint::{LateContext, LateLintPass};
use rustc_middle::hir::map::Map;
... |
//! Custom UI example
use amethyst::{
assets::{PrefabLoader, PrefabLoaderSystem, RonFormat},
core::transform::TransformBundle,
ecs::prelude::{ReadExpect, Resources, SystemData},
input::StringBindings,
prelude::*,
renderer::{
rendy::{
factory::Factory,
graph::{
... |
use proconio::input;
#[allow(unused_imports)]
use proconio::marker::{Chars, Bytes};
fn main() {
todo!();
}
|
// Copyright 2018 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 {
failure::{Error, ResultExt},
fidl_fuchsia_io::DirectoryProxy,
fuchsia_async as fasync,
fuchsia_component::server::ServiceFs,
fuch... |
use crate::crypt::{gen_salsa_key, KeyPair};
use crate::packet::PoePacket;
use crate::Error;
use std::collections::HashMap;
pub struct Decrypter {
keystore: HashMap<u32, KeyPair>,
}
impl Decrypter {
pub fn new() -> Self {
Decrypter {
keystore: HashMap::new(),
}
}
pub fn add... |
use crate::{
prelude::*,
map::Map,
shape::ShapeMapper,
material::Material,
object::Covered,
};
/// Shape of an object.
///
/// It defines the search of the point where ray intersects this shape.
pub trait Shape: Pack + Instance<ShapeClass> {
/// Creates a new shape by applying some kind of m... |
//! Test for iterator functions
use rune_tests::*;
#[test]
fn test_sum() {
assert_eq!(rune!(u32 => pub fn main() { [1, 2, 3].iter().sum() }), 6)
}
#[test]
fn test_sum_negative() {
assert_eq!(rune!(i32 => pub fn main() { [1, -2, 3].iter().sum() }), 2)
}
#[test]
fn test_prod() {
assert_eq!(
rune!(... |
use proconio::{input, marker::Bytes};
fn main() {
input! {
s: Bytes,
t: Bytes,
};
let (mut at_s, mut at_t) = (0, 0);
let (mut f, mut g) = ([0; 26], [0; 26]);
for &b in &s {
if b == b'@' {
at_s += 1;
} else {
f[(b - b'a') as usize] += 1;
... |
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... |
//! linux_raw syscalls supporting `rustix::thread`.
//!
//! # Safety
//!
//! See the `rustix::backend` module documentation for details.
#![allow(unsafe_code)]
#![allow(clippy::undocumented_unsafe_blocks)]
use crate::backend::c;
use crate::backend::conv::{
by_mut, by_ref, c_int, c_uint, ret, ret_c_int, ret_c_int_i... |
// 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::startup,
failure::{Error, ResultExt},
fidl_fuchsia_session::{LaunchSessionError, LauncherRequest, LauncherRequestStream},
fidl... |
// Various tests related to testing how region inference works
// with respect to the object receivers.
// revisions: base nll
// ignore-compare-mode-nll
//[nll] compile-flags: -Z borrowck=mir
trait Foo {
fn borrowed<'a>(&'a self) -> &'a ();
}
// Here we have two distinct lifetimes, but we try to return a pointe... |
//! 提供栈结构实现的分配器 [`StackedAllocator`]
use super::Allocator;
use alloc::{vec, vec::Vec};
/// 使用栈结构实现分配器
///
/// 在 `Vec` 末尾进行加入 / 删除。
/// 每个元素 tuple `(start, end)` 表示 [start, end) 区间为可用。
pub struct StackedAllocator {
list: Vec<(usize, usize)>,
}
// 分配的粒度是 一个页面,每次调用alloc会分配 一个页面,只有*1*个页面!!!
// 分配和回收的 时... |
// 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 serde_derive::{Deserialize, Serialize};
pub type File = String;
pub type FidlLibraryName = String;
pub type CcLibraryName = String;
pub type BanjoL... |
#[allow(unused_imports)]
use proconio::{
input, fastout,
};
use std::cmp::max;
fn solve(a: i64, b: i64, c: i64, d: i64) -> i64 {
let mut ans = a * c;
ans = max(ans, a * d);
ans = max(ans, b * c);
ans = max(ans, b * d);
return ans;
}
fn run() -> Result<(), Box<dyn std::error::Error>> {
in... |
use std::io;
use std::collections::HashMap;
use rand::Rng;
fn main() {
let mut source : Vec<&str> = include_str!("./input.txt").lines().collect();
//let source : Vec<&str> = include_str!("./input_test.txt").lines().collect();
let mut a_program = Program::new(source[0], 99999999);
let mut grid: HashMap... |
pub mod ncpf;
|
use std::ops::{Add, AddAssign, Div, DivAssign, Mul, MulAssign, Sub, SubAssign};
#[derive(Clone, Copy, Debug)]
pub struct Vec3(pub f64, pub f64, pub f64);
impl Vec3 {
pub fn x(&self) -> f64 {
self.0
}
pub fn y(&self) -> f64 {
self.1
}
pub fn z(&self) -> f64 {
self.2
}
... |
use crate::gl::{shader, tex};
use crate::math;
use std::rc::Rc;
use std::string::String;
#[derive(PartialEq, Clone)]
pub struct UniformProgramLocation {
pub location: u32,
pub program: u32,
}
#[derive(Clone)]
pub struct UniformDataLoction<T> {
pub locations: Vec<UniformProgramLocation>,
pub data: Vec<... |
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Team {
pub id: TeamId,
}
impl Team {
pub fn new(id: TeamId) -> Self {
Self { id }
}
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct TeamId(pub u32);
|
use::*;
trait CarFactory {
type C: Car;
fn make_car(&self) -> Self::C;
}
impl CarFactory for SedanFactory {
type C = Sedan;
fn make_car(&self) -> Sedan {
Sedan
}
}
impl CarFactory for CoupeFactory {
type C = Coupe;
fn make_car(&self) -> Coupe {
Coupe
}
}
fn client... |
use amethyst::{assets::Handle, core::Time, prelude::*, renderer::SpriteSheet, SimpleState};
use crate::{
audio::initialize_audio,
entities::{
initialize_ball, initialize_camera, initialize_paddles, intialize_scoreboard, Ball, Paddle,
},
settings::BALL_SPAWN_DELAY,
sprite_sheet::load_sprite_... |
extern crate num;
pub mod vector2;
pub mod common; |
use std::marker::Copy;
use std::clone::Clone;
use std::cmp::{Eq, PartialEq};
use std::error::Error;
use std::result::Result;
use std::fmt::{Formatter, Display, Debug};
use std::fmt;
use ::OptTable;
pub type Res<'a> = Result<OptTable<'a>, Fail>;
#[derive(Debug, Clone, Eq, PartialEq)]
pub enum Fail {
MissingArgume... |
use mod_int::ModInt998244353;
use scanner_proc_macro::insert_scanner;
#[insert_scanner]
fn main() {
let (n, m, k) = scan!((usize, usize, usize));
let w = scan!(u32; n);
type Mint = ModInt998244353;
let mut fact = vec![Mint::new(1)];
for i in 1..=k {
fact.push(fact[i - 1] * i);
}
... |
#[doc = "Reader of register EEFER2"]
pub type R = crate::R<u32, super::EEFER2>;
#[doc = "Writer for register EEFER2"]
pub type W = crate::W<u32, super::EEFER2>;
#[doc = "Register EEFER2 `reset()`'s with value 0"]
impl crate::ResetValue for super::EEFER2 {
type Type = u32;
#[inline(always)]
fn reset_value() ... |
use std::io::Result as IoResult;
use std::io::ErrorKind;
use std::process::{Command, ExitStatus};
use std::path::{Path, PathBuf};
use std::fs::{
DirBuilder, read_dir, remove_dir, rename,
remove_file,
};
use std::ffi::OsStr;
use std::os::unix::process::ExitStatusExt;
use std::os::unix::ffi::OsStrExt;
use std::fmt::W... |
//! The contract trait.
use crate::{context::Context, error, types};
/// Trait that needs to be implemented by contract implementations.
pub trait Contract {
/// Type of all requests.
type Request: cbor::Decode;
/// Type of all responses.
type Response: cbor::Encode;
/// Type of all errors.
typ... |
use P68::*;
pub fn main() {
let trees = from_preorder(&vec!['a', 'b', 'c']);
for tree in trees {
println!("{}", tree);
}
}
|
#[doc = "Reader of register TXRQ2"]
pub type R = crate::R<u32, super::TXRQ2>;
#[doc = "Reader of field `TXRQST`"]
pub type TXRQST_R = crate::R<u16, u16>;
impl R {
#[doc = "Bits 0:15 - Transmission Request Bits"]
#[inline(always)]
pub fn txrqst(&self) -> TXRQST_R {
TXRQST_R::new((self.bits & 0xffff) ... |
use crate::file_util::read_non_blank_lines;
use std::str::FromStr;
use crate::day_twelve::Direction::{Forward, Backward};
use crate::day_twelve::Heading::{East, West, North, South};
enum Heading { North, East, South, West }
#[derive(PartialEq, Eq)]
enum Direction { Forward, Backward }
#[allow(dead_code)]
pub fn run_d... |
// Copyright 2017 LambdaStack All rights reserved.
//
// 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... |
#[doc = "Reader of register STATUS"]
pub type R = crate::R<u32, super::STATUS>;
#[doc = "Reader of field `FAULT0`"]
pub type FAULT0_R = crate::R<bool, bool>;
#[doc = "Reader of field `FAULT1`"]
pub type FAULT1_R = crate::R<bool, bool>;
impl R {
#[doc = "Bit 0 - Generator 0 Fault Status"]
#[inline(always)]
p... |
use crate::{PluginId, WhichPlugin};
use std::fmt;
use serde::{
de::{self, DeserializeOwned, Deserializer, Error as _, IgnoredAny, MapAccess, Visitor},
Deserialize, Serialize,
};
use abi_stable::{std_types::*, StableAbi};
/// The commands that map to methods in the Plugin trait.
// This is intentionally not ... |
#![allow(unused_mut)]
#[macro_use]
extern crate chan;
extern crate portmidi as pm;
extern crate chan_signal;
extern crate midi_message;
extern crate rand;
mod color;
mod effects {
pub mod effect;
pub mod ripple;
pub mod flash;
pub mod blink;
pub mod stream;
pub mod stream_center;
pub mod ... |
// 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::traceutil::{facade::TraceutilFacade, types::TraceutilMethod};
use failure::Error;
use serde_json::Value;
use std::sync::Arc;
// Takes SL4F meth... |
use std::cmp::max;
use item::{Item, HoldsItems};
#[derive(Clone)]
pub struct Inventory {
capacity: usize,
// Contains all items that are currently stored in this inventory.
items: Vec<Item>,
// Tells which positions are reserved by items. None positions are free, Some() position are reserved by items i... |
use std::collections::HashMap;
use std::io::{self, Read};
fn get_input() -> Vec<u32> {
let mut buffer = String::new();
io::stdin().read_to_string(&mut buffer).expect("could not read stdin");
buffer.split_whitespace().map(|s| s.parse()).collect::<Result<_, _>>().expect("could not parse number")
}
fn redist... |
use std::fmt;
struct MyList(Vec<i32>);
impl fmt::Display for MyList {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "[")?;
// Iterate over `v` in `vec` while enumerating the iteration
// count in `count`.
for (count, v) in self.0.iter().enumerate() {
// For every element ex... |
extern crate cql;
extern crate eventual;
extern crate mio;
extern crate uuid;
use std::borrow::Cow;
use self::uuid::Uuid;
use cql::*;
use self::eventual::{Future,Async};
use std::collections::VecDeque;
use std::thread;
pub fn to_hex_string(bytes: &Vec<u8>) -> String {
let strs: Vec<String> = bytes.iter()
... |
#![allow(unused_imports)]
use mio::net::TcpStream;
use mio_more::timer::{Timeout, Timer, TimerError};
use std::collections::*;
use std::env;
use std::ffi::{OsStr, OsString};
use std::fmt::{Debug, Formatter};
use std::io;
use std::io::*;
use std::net::{self, IpAddr, SocketAddr};
use std::process::*;
use std::os::unix... |
// Copyright (c) 2016 vergen developers
//
// 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 http://opensource.org/licenses/MIT>, at your
// option. All files in the project carrying such notice may not be copied,
//... |
#![cfg(feature = "x86")]
use telamon_kernels::{linalg, Kernel};
use telamon_x86 as x86;
macro_rules! test_dump {
($name:ident, $kernel:ty, $params:expr) => {
#[test]
fn $name() {
let _ = env_logger::try_init();
let mut context = x86::Context::default();
let path... |
use crate::structures::*;
// TODO: Use data structure for fast search
pub fn solve(forms : &CNF) -> Option<Assignation> {
let mut ass : Assignation = Vec::new(); // TODO
loop {
if can_continue_cnf(&forms, &ass){
if ass.len() == forms.1 { return Some(ass); }
else... |
//! Thread-safe LRU Cache.
use linked_hash_map::LinkedHashMap;
use std;
use std::hash::Hash;
use std::sync::{Arc, RwLock};
/// A thread-safe LRU Cache.
#[derive(Debug)]
pub struct Cache<K, V>
where
K: Hash + Eq,
{
map: RwLock<linked_hash_map::LinkedHashMap<K, Arc<V>>>,
capacity: usize,
}
impl<K, V> Cache<... |
// Hacker News title downloader
// Inspired by the `V` version: https://github.com/BafS/hn-top
use colored::Colorize;
use directories::ProjectDirs;
use getopts::Options;
use serde::Deserialize;
use std::env;
use std::fs;
use std::path::Path;
const API: &str = "https://hacker-news.firebaseio.com/v0";
// The story and... |
#![allow(non_snake_case, non_camel_case_types, non_upper_case_globals, clashing_extern_declarations, clippy::all)]
#[link(name = "windows")]
extern "system" {}
pub type PnpObject = *mut ::core::ffi::c_void;
pub type PnpObjectCollection = *mut ::core::ffi::c_void;
#[repr(transparent)]
pub struct PnpObjectType(pub i32);
... |
use std::fmt;
use std::error;
#[derive(Debug, PartialEq)]
pub enum Chip8Error {
UnsupportedOpcode(u16),
StackUnderflow
}
impl fmt::Display for Chip8Error {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
Chip8Error::UnsupportedOpcode(value) => write!(f, "unsupported... |
use log::*;
use reqwest::blocking::Client;
use serde_json::json;
use std::env;
struct TelegramWebHook {
bot_token: String,
chat_id: String,
}
#[derive(Debug, Default)]
struct TwilioWebHook {
account: String,
token: String,
to: String,
from: String,
}
impl TwilioWebHook {
fn complete(&self... |
#[doc = "Reader of register GPIOHBCTL"]
pub type R = crate::R<u32, super::GPIOHBCTL>;
#[doc = "Writer for register GPIOHBCTL"]
pub type W = crate::W<u32, super::GPIOHBCTL>;
#[doc = "Register GPIOHBCTL `reset()`'s with value 0"]
impl crate::ResetValue for super::GPIOHBCTL {
type Type = u32;
#[inline(always)]
... |
use common::aoc::{load_input, run_many, print_time, print_result, print_result_multiline};
fn main() {
let input = load_input("day08");
let (image, dur_parse) = run_many(1000, || Image::parse(&input, 25, 6));
let (res_part1, dur_part1) = run_many(1000, || image.best_layer_checksum());
let (res_part2, ... |
use std::ops::Range;
use std::cmp;
fn left_max(heights: &[u32]) -> usize {
let len = heights.len();
let mut max = 0;
for i in 0..len {
if heights[i] > max {
max = heights[i];
} else {
return i - 1;
}
}
len
}
fn right_max(heights: &[u32]) -> usize {
... |
pub mod assert;
pub mod version;
#[cfg(feature = "ntoa")]
pub mod ntoa;
#[cfg(feature = "ntoa")]
pub use ntoa::{
itoa, itoa10, itoa16, itoa2, itoa8, utoa, utoa10, utoa16, utoa2, utoa8,
Config as NtoaConfig, Error as NtoaError, Result as NtoaResult,
};
#[cfg(test)]
#[cfg(feature = "ntoa")]
mod tests {
use... |
//! Host-guest memory management.
use std::convert::TryInto;
use oasis_runtime_sdk::context::Context;
use super::OasisV1;
use crate::{abi::ExecutionContext, Config};
/// Name of the memory allocation export.
pub const EXPORT_ALLOCATE: &str = "allocate";
/// Name of the memory deallocation export.
pub const EXPORT_DE... |
use defs::{FloatType, Point3, Vector3, Matrix4};
use core::{Ray, Material};
use tools::{CompareWithTolerance};
use na::{Unit};
use na;
use uuid::{Uuid};
static MIMIMUM_INTERSECTION_DISTANCE: FloatType = 0.000000001;
#[derive(Debug)]
pub enum RayIntersectionError {
NoRayTravelDistance,
NoModelIdentifierPresent... |
use liblumen_alloc::atom;
use crate::erlang::{
convert_time_unit_3, monotonic_time_1, subtract_2, system_time_1, time_offset_1,
};
use crate::test::with_process;
const TIME_OFFSET_DELTA_LIMIT_SECONDS: u64 = 2;
#[test]
fn approximately_system_time_minus_monotonic_time_in_seconds() {
approximately_system_time_... |
use std::sync::atomic::{
AtomicBool,
Ordering,
};
use std::sync::{
Arc,
Mutex,
MutexGuard,
};
use ash::extensions::khr::Surface as SurfaceLoader;
use ash::prelude::VkResult;
use ash::vk;
use ash::vk::Handle;
use sourcerenderer_core::graphics::Surface;
use crate::raw::*;
pub struct VkSurface {
... |
use std::collections::HashMap;
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Item {
//主机头,*表示通配
pub host: String,
//全局请求跳转路径,{path}表示完整的路径;
//{#序号}表示路径片段的序号
pub to: String,
//如果未设定全局请求跳转路径,那么将启用路径字典
//如果{"a/b/c":"http://abc.com"},访问/a/b/c将跳转
//到"http://abc.com"
pub loca... |
//! Main module to handle the layout.
//! This is where the i3-specific code is.
use std::fmt;
use std::collections::HashSet;
use std::ops::Deref;
use petgraph::graph::NodeIndex;
use uuid::Uuid;
use rustwlc::callback::{positioner_get_anchor_rect, positioner_get_size,};
use rustwlc::{ResizeEdge, WlcView, WlcOutput,
... |
#[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::_0_GENB {
#[doc = r"Modifies the contents of the register"]
#[inline(always)]
pub fn modify<F>(&self, f: F)
where
for<'w> F: FnOnce(&R, ... |
use crate::schema::*;
use serde::{Deserialize, Serialize};
#[derive(
Debug, Serialize, Clone, Associations, PartialEq, Identifiable, Deserialize, Queryable,
)]
#[table_name = "users"]
pub struct User {
pub id: i32,
pub username: String,
pub email: String,
pub user_password: String,
pub user_imag... |
mod block;
mod builtin_format;
mod builtin_template;
mod const_value;
mod expr;
mod expr_assign;
mod expr_await;
mod expr_binary;
mod expr_block;
mod expr_break;
mod expr_call;
mod expr_closure;
mod expr_continue;
mod expr_field_access;
mod expr_for;
mod expr_if;
mod expr_index;
mod expr_let;
mod expr_loop;
mod expr_ma... |
use crate::Color;
use crate::HitRecord;
use crate::Point;
use crate::Ray;
pub trait Material: std::fmt::Debug + Send + Sync {
fn scatter(
&self,
ray_in: &Ray,
record: &HitRecord,
attenuation: &mut Color,
scattered: &mut Ray,
) -> bool;
fn emitted(&self, u: f64, v: f... |
use nalgebra::*;
use std::ops::Mul;
/// A type for mesh vertices. Initialize with [vertex][self::vertex].
pub type Vertex = Vector4<f32>;
/// A type for homogeneous transforms
pub type Mat4 = Matrix4<f32>;
#[derive(Clone, Copy)]
pub struct Transform {
pub mtx: Mat4,
}
/// Initializes a vertex:
pub fn vertex(x: f... |
#[doc = r"Value read from the register"]
pub struct R {
bits: u8,
}
#[doc = r"Value to write to the register"]
pub struct W {
bits: u8,
}
impl super::RXCSRL7 {
#[doc = r"Modifies the contents of the register"]
#[inline(always)]
pub fn modify<F>(&self, f: F)
where
for<'w> F: FnOnce(&R, &'... |
#[doc = "Reader of register CR1"]
pub type R = crate::R<u32, super::CR1>;
#[doc = "Writer for register CR1"]
pub type W = crate::W<u32, super::CR1>;
#[doc = "Register CR1 `reset()`'s with value 0"]
impl crate::ResetValue for super::CR1 {
type Type = u32;
#[inline(always)]
fn reset_value() -> Self::Type {
... |
mod utils;
use std::io::{Cursor};
use wasm_bindgen::prelude::*;
#[wasm_bindgen]
pub fn gray(_array: &mut [u8]) -> Vec<u8> {
let mut img = image::load_from_memory(_array).unwrap();
img = img.grayscale();
let mut bytes: Vec<u8> = Vec::new();
img.write_to(&mut Cursor::new(&mut bytes), image::ImageOutput... |
#![feature(core_intrinsics)]
#![feature(stmt_expr_attributes)]
extern crate rand;
extern crate errno;
#[cfg(unix)] extern crate libc;
#[cfg(windows)] extern crate kernel32;
#[cfg(all(unix, test))] extern crate nix;
mod alloc;
pub use alloc::{ unprotected_mprotect, malloc, allocarray, free };
// -- memcmp --
/// C... |
use reduce::Reduce;
use std::fs::File;
use std::io::{BufRead, BufReader};
use std::path::Path;
// adapted from https://doc.rust-lang.org/rust-by-example/std_misc/file/read_lines.html
fn read_lines<P>(filename: P) -> Vec<String>
where
P: AsRef<Path>,
{
let file = File::open(filename).expect("Error opening file!... |
use super::*;
#[derive(Clone)]
pub struct AssemblyRef(pub Row);
|
// 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 crate::{ActionInput, CursorState, InputBindings};
use game_camera::{CameraState, ProjectionExt, ScaledOrthographicProjection};
use game_lib::{
bevy::{
input::{keyboard::KeyboardInput, mouse::MouseButtonInput, ElementState},
prelude::*,
render::camera::Camera,
},
tracing::{self, i... |
mod instruction;
mod opcode;
use bitvec::vec::BitVec;
use ggez::{graphics::*, input::keyboard::KeyCode, *};
use log::*;
use std::ops::{Index, IndexMut};
use std::time::Duration;
use opcode::OpCode;
#[cfg(feature = "debug-view")]
mod debug_view;
#[cfg(not(feature = "debug-view"))]
impl crate::debug_view::Debug for ... |
extern crate matrix;
use matrix::prelude::*;
// Implements Gaussian elimination with partial pivoting
// Input: Matrix a[1..n, 1..n] and column-vector b[1..n]
// Output: An equivalent upper-triangular matrix in place of a and the
// corresponding right-hand side value in place of the (n + 1)st column
fn better_fo... |
// 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.
#![allow(dead_code)]
#![allow(unused_imports)]
use carnelian::{
make_font_description, AnimationMode, App, AppAssistant, Canvas, MappingPixelSink, Pix... |
//! UDP relay local server
use std::{
io::{self, Cursor, ErrorKind, Read},
net::SocketAddr,
sync::Arc,
time::Duration,
};
use async_trait::async_trait;
use bytes::{Bytes, BytesMut};
use log::{debug, error, info, trace, warn};
use tokio::{self, net::UdpSocket, time};
use crate::{
context::SharedCo... |
use clippy_utils::diagnostics::{span_lint_and_help, span_lint_and_note, span_lint_and_then};
use clippy_utils::paths;
use clippy_utils::ty::{implements_trait, is_copy};
use clippy_utils::{get_trait_def_id, is_automatically_derived, is_lint_allowed, match_def_path};
use if_chain::if_chain;
use rustc_hir::def_id::DefId;
... |
use serde::{Deserialize, Serialize};
use serde::ser::{Serializer, SerializeStruct};
use crate::api::message::amount::{Amount, string_or_struct};
use crate::api::message::memo::*;
use crate::api::utils::tx_flags::*;
use std::error::Error;
use std::fmt;
#[derive(Deserialize, Debug, Default)]
pub struct TxJson {
#[s... |
mod lib1;
mod lib2;
mod lib3;
mod lib4;
mod lib5;
mod front_of_house;//使用mod关键字声明front_of_house模块,具体的定义在front_of_house.rs文件中
pub fn eat_at_restaurant() {
//绝对路径,绝对路径必须以crate开头,因为它代码整个Module树的根节点。路径之间使用的是双冒号来表示引用
crate::front_of_house::hosting::add_to_waitlist();
//相对路径
front_of_house::hosting::add_t... |
use std::env;
use hyper::{Client, Body, Method, body::HttpBody as _};
use hyper::http::{Request};
use hyper_tls::HttpsConnector;
use tokio::io::{self, AsyncWriteExt as _};
use serde::{Serialize, Deserialize};
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
// match env::var("GITHUB_ACCE... |
fn main() {
/*
This implementation does not work because the compiler does not know the
lifetime of the parameters
fn longest(s1: &str, s2: &str) -> &str {
if s1.len() > s2.len() {
return s1;
}
s2
}
We need to specify the lifetime with 'a. They act like generics
all... |
/*!
error types for libsodacon
*/
use hex;
use libsodacrypt;
use rmp_serde;
error_chain! {
links {
SodaCrypt(libsodacrypt::errors::Error, libsodacrypt::errors::ErrorKind);
}
foreign_links {
RmpDecode(rmp_serde::decode::Error);
RmpEncode(rmp_serde::encode::Error);
Io(::std:... |
use crate::Ray;
use rand::distributions::Distribution;
use rand::RngCore;
pub type Vec2 = nalgebra::Vector2<f64>;
pub type Vec3 = nalgebra::Vector3<f64>;
pub type Vec4 = nalgebra::Vector4<f64>;
pub type Mat3 = nalgebra::Matrix3<f64>;
pub type Mat4 = nalgebra::Matrix4<f64>;
pub fn vpowf(v: &Vec3, factor: f64) -> Vec3 ... |
use std::fmt;
use std::io::{self, Result};
use kvdb_rocksdb::{DatabaseConfig, Database};
use kvdb::KeyValueDB;
/// Required length of prefixes.
/// key-value-timestamp-is_expire-order_id
pub const META_COL: u32 = 0;
pub struct KVDatabase {
pub(crate) config: DatabaseConfig,
pub(crate) path: String,
}
impl ... |
#[macro_use(compose)] extern crate compose;
use std::ops::Mul;
fn rev<T>(mut v: Vec<T>) -> Vec<T> { v.reverse(); v }
fn sort<T: Ord>(mut v: Vec<T>) -> Vec<T> { v.sort(); v }
fn square<T: Copy + Mul<T, Output=T>>(mut v: Vec<T>) -> Vec<T> {
v.into_iter().map(|e| (e * e) ).collect::<Vec<_>>()
}
fn main() {
let v... |
#[cfg(test)]
use pretty_assertions::assert_eq;
use wce_formats::{BinaryConverter, BinaryConverterVersion};
use wce_formats::binary_reader::BinaryReader;
use wce_formats::binary_writer::BinaryWriter;
use wce_formats::GameVersion::{self, RoC, TFT};
use wce_formats::MapArchive;
use crate::doodad_map::Radian;
use crate::... |
use median::{
atom::Atom,
attr::{AttrBuilder, AttrType},
builder::MaxWrappedBuilder,
class::Class,
clock::ClockHandle,
inlet::MaxInlet,
max_sys::t_atom_long,
num::{Float64, Int64},
object::MaxObj,
outlet::OutList,
post,
symbol::SymbolRef,
wrapper::{attr_get_tramp, att... |
struct HostSession<'a> {
host_name: &'a str,
host_config: &'a crate::config::AppHost,
}
impl<'a> HostSession<'a> {
pub fn from_config(
host_name: &'a str,
host_config: &'a crate::config::AppHost,
) -> Self {
HostSession {
host_name,
host_config,
}... |
use scanner_proc_macro::insert_scanner;
#[insert_scanner]
fn main() {
let n = scan!(usize);
let mo = 998244353_u64;
let mut dp = vec![0; 10];
for d in 1..=9 {
dp[d] = 1;
}
for _ in 0..(n - 1) {
let mut nxt = vec![0; 10];
for a in 1..=9 {
for b in 1..=9 {
... |
use mime;
use hyper::{Response, StatusCode, Body};
use gotham::http::response::create_response;
use gotham::state::{State, FromState};
use gotham::handler::{IntoResponse, IntoHandlerError, HandlerFuture};
use futures::{future, Future, Stream};
use serde_json;
use super::model::Task;
impl IntoResponse for Task {
... |
// auto generated, do not modify.
// created: Mon Feb 22 23:57:02 2016
// src-file: /QtGui/qopenglwindow.h
// dst-file: /src/gui/qopenglwindow.rs
//
// header block begin =>
#![feature(libc)]
#![feature(core)]
#![feature(collections)]
extern crate libc;
use self::libc::*;
// <= header block end
// main block begin ... |
use std::collections::HashMap;
use std::fmt;
use std::sync::{Arc, mpsc, Mutex};
use std::thread;
use std::time::{Duration, Instant};
use crate::util::InnerThread;
use self::timing_thread::timer_manager_timing_thread;
pub use self::timer::{Timer, Wakeup};
#[derive(Debug)]
pub struct TimerManager {
timer_count: M... |
use std::io::Read;
fn main() {
let stdin = std::io::stdin();
let (score, noncancelled) = count_score(stdin.lock());
println!("Score: {}, noncancelled: {}", score, noncancelled);
}
fn count_score<R: Read>(r: R) -> (u64, u64) {
let mut score = 0u64;
let mut open_groups = 0u64;
let mut skip_next... |
use std::collections::{VecDeque, HashSet};
fn recursive_combat(game: i64, mut p1_deck: VecDeque<i64>, mut p2_deck: VecDeque<i64>) -> bool {
let mut p1_history: HashSet<VecDeque<i64>> = HashSet::new();
let mut p2_history: HashSet<VecDeque<i64>> = HashSet::new();
while !p1_deck.is_empty() && !p2_deck.is_em... |
use crate::ast::{Case, Conditional, ConditionalKind, WhenClause};
use crate::lexer::*;
use crate::parsers::expression::argument::comma;
use crate::parsers::expression::argument::operator_expression_list;
use crate::parsers::expression::argument::splatting_argument;
use crate::parsers::expression::{expression, operator_... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.