text stringlengths 8 4.13M |
|---|
#[macro_export]
macro_rules! impl_from {
($err_to_type:tt:: $err_to_variant:ident, $err_from_type:ty) => {
impl From<$err_from_type> for $err_to_type {
fn from(e: $err_from_type) -> Self {
$err_to_type::$err_to_variant(e)
}
}
};
}
|
//! This module contains everything related to brands.
use std::fmt;
/// A model railways manufacturer.
#[derive(Debug, PartialEq, Eq, PartialOrd, Ord)]
pub struct Brand(String);
impl Brand {
/// Creates a new brand with the given name.
pub fn new(name: &str) -> Self {
Brand(name.to_owned())
}
... |
extern crate core;
use std::fs::File;
use std::io::{BufReader, BufRead};
enum OverLapOrder {
FirstToSecond,
SecondToFirst,
Bigger
}
struct OverLapStat {
length: i32,
order: OverLapOrder
}
fn get_overlap(first: &String, second: &String) -> OverLapStat {
let mut counter = if first.len() < seco... |
use cfg_if::cfg_if;
cfg_if! {
if #[cfg(not(target_arch = "wasm32"))] {
mod backtrace;
use self::backtrace as inner;
} else {
mod fallback;
use self::fallback as inner;
}
}
mod format;
mod frame;
mod utils;
pub use self::frame::TraceFrame;
pub use self::inner::Frame as Fram... |
use crate::blockBufferPool::Blocktree;
use morgan_storage_api::SLOTS_PER_SEGMENT;
use std::fs::File;
use std::io;
use std::io::{BufWriter, Write};
use std::path::Path;
use std::sync::Arc;
pub const CHACHA_BLOCK_SIZE: usize = 64;
pub const CHACHA_KEY_SIZE: usize = 32;
#[link(name = "cpu-crypt")]
extern "C" {
fn ch... |
use crate::payload::Payload;
pub struct Received {
pub pipe: u8,
pub payload: Payload,
}
pub struct SendReceiveResult {
pub received: Option<Received>,
pub sent: bool,
/// When a packet is unacknowledged after it's maximum retries, this flag is set
pub dropped: bool,
}
|
use sdl2::event::Event;
use sdl2::pixels::Color;
use crate::global::*;
use crate::calculation::{do_calculation, transform};
use crate::object::Point;
pub fn main() {
show_global();
if *BENCHMARK {
let mut grid = Vec::new();
for i in 0..*WIDTH {
for j in 0..*HEIGHT {
... |
use serde::{Deserialize, Serialize};
use structopt::StructOpt;
use crate::http_request::QueryString;
#[derive(Debug, Serialize, Deserialize, StructOpt)]
pub struct ListForm {
/// Set the order of returned List. Default value is "createdTime:DESC"
/// @see <https://developers.sidemash.com/qs-query/order-by>
... |
use anyhow::{Error, anyhow};
use gl::types::*;
use std::ffi::CString;
fn get_error<Len, Log>(get_len: Len, get_log: Log) -> Error
where
Len: FnOnce(&mut GLint),
Log: FnOnce(GLint, *mut gl::types::GLchar)
{
let mut len: GLint = 0;
get_len(&mut len);
// allocate buffer of correct size
... |
pub fn get_endpoint<'e>() -> &'e str {
"https://jsonplaceholder.typicode.com/"
} |
use crate::{
ast::{Parameter, Position, Symbol, SymbolKind},
AST,
};
use bigdecimal::BigDecimal;
use itertools::Itertools;
use num::{BigInt, One, Zero};
use std::{
fmt,
fmt::{Display, Formatter},
};
impl Display for AST {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
match self {
... |
fn main() {
windows::core::build! {
Component::Composable::*,
};
}
|
#![recursion_limit = "1024"]
use wasm_bindgen::prelude::*;
use yew::prelude::*;
use yew_router::prelude::*;
pub mod api;
pub mod component;
pub mod poll;
use poll::{CreatePoll, PollResults, ShowPoll};
#[derive(Switch, Debug, Clone)]
pub enum AppRoute {
#[to = "/dotdotyew/poll/{id}/results"]
PollResults(Strin... |
mod dot;
mod dot_display;
mod dot_screen;
pub use dot::Dot;
pub use dot_display::DotDisplay;
pub use dot_screen::DotScreen;
|
#[derive(Debug,PartialEq,Eq)]
pub struct ShortToken{
pub token: Option<String>,
pub target: Option<String>
}
pub fn find_token(conn:&mut mysql::PooledConn,short_token:&String)->Option<ShortToken>{
conn.first_exec("SELECT `token`,`target` from `short_token` WHERE `token`=:token",params!{
"token"=>short_token.as_str... |
pub mod contracts;
// --------------------------------------------
// API模块用到的工具类
// --------------------------------------------
pub mod utils;
pub mod config;
// --------------------------------------------
// 接口的公共数据结构
// --------------------------------------------
pub mod message;
// ---------------------------... |
use regex::Regex;
const RE_LINE: &str = r"([a-z]{3}):(.*?)(?:\s|$)";
const RE_BYR: &str = r"(19[2-9][0-9]|200[0-2])";
const RE_IYR: &str = r"(20(1[0-9]|20))";
const RE_EYR: &str = r"(20(2[0-9]|30))";
const RE_HGT: &str = r"(1(([5-8][0-9])|(9[0-3]))cm)|((59|6[0-9]|7[0-6])in)";
const RE_HCL: &str = r"(#[0-9a-f]{6})";
co... |
#![allow(unused)]
use libsm::sm3::hash::Sm3Hash;
use basex_rs::{BaseX, SKYWELL, Encode};
use crate::base::crypto::brorand::Brorand;
use crate::address::traits::seed::SeedI;
use crate::address::traits::checksum::{ChecksumI};
use crate::address::impls::checksum::sm2p256v1::ChecksumSM2P256V1;
use crate::addres... |
use crate::base::serialize::signed_obj::{
SignedTxJson,
TxJsonBuilder,
TxJsonSigningPubKeyBuilder,
TxJsonFlagsBuilder,
TxJsonFeeBuilder,
TxJsonTransactionTypeBuilder,
TxJsonAccountBuilder,
TxJsonSequenceBuilder,
TxJsonTakerBuilder,
};
use crate::base::data::constants::{
TX... |
/*
* Customer Journey as a Service (CJaaS)
*
* Something amazing, something special - the Customer Journey as a Service (CJaaS) is a core data layer to enable Journeys across products built upon serverless multi-cloud architecture, to be available as a SaaS service for applications inside and outside of Cisco. [**Ci... |
extern crate eosio_macros;
use eosio_macros::n;
fn main() {
let _ = n!("12345123451234");
}
|
use crate::searcher::{SearchContext, SearcherMessage};
use crate::stdio_server::VimProgressor;
use filter::BestItems;
use matcher::{MatchResult, Matcher};
use printer::Printer;
use std::borrow::Cow;
use std::io::{BufRead, Result};
use std::path::PathBuf;
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
use s... |
// SPDX-License-Identifier: MIT
// Copyright (c) 2021-2022 brainpower <brainpower at mailbox dot org>
#![feature(assert_matches)]
#[cfg(test)]
mod tests {
use checkarg::{CheckArg, ValueType, RC};
use std::assert_matches::assert_matches;
#[test]
fn positional_argument_help() {
let argv = vec!["/test02"];
... |
/*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* 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 applic... |
use std::thread;
use std::collections::HashMap;
use std::sync::{Arc, mpsc, Mutex};
use websocket::{Message, receiver, sender, Sender, Server, WebSocketStream};
pub fn start() {
thread::spawn(listen);
}
fn listen() {
let server = Server::bind("localhost:3001").unwrap();
println!("Server listening at: loc... |
use crate::utils;
use std::collections::HashMap;
const TEST_MODE: bool = false;
#[derive(Debug)]
enum Rule {
Single(Vec<String>),
Double((Vec<String>, Vec<String>)),
Sink(char),
}
struct ProblemData {
rules: HashMap<String, Rule>,
messages: Vec<String>,
}
fn read_problem_data() -> ProblemData {
... |
pub fn ease_in_quad(t: f32, b: f32, c: f32, d: f32) -> f32 {
let t = t / d;
c * t * t + b
}
pub enum TweenFn {
EaseInQuad,
}
pub struct Tween {
distance: f32,
start_value: f32,
current: f32,
total_duration: f32,
time_passed: f32,
is_finished: bool,
}
impl Tween {
pub fn new(st... |
/// ```rust,ignore
/// 118. 杨辉三角
/// 给定一个非负整数 numRows,生成杨辉三角的前 numRows 行。
///
/// 在杨辉三角中,每个数是它左上方和右上方的数的和。
///
/// 示例:
///
/// 输入: 5
/// 输出:
/// [
/// [1],
/// [1,1],
/// [1,2,1],
/// [1,3,3,1],
/// [1,4,6,4,1]
/// ]
///
/// 来源:力扣(LeetCode)
/// 链接:https://leetcode-cn.com/problems/pascals-triangle
/// 著作权归领扣网络所有。商业转载请联系... |
use crate::PerfModelTest;
use telamon::device::{ArgMap, Context};
use telamon::helper::{Builder, Reduce, SignatureBuilder};
use telamon::ir;
use telamon::search_space::*;
pub struct Test0;
impl Test0 {
const M: i32 = 1024;
const N: i32 = 1024;
const K: i32 = 1024;
const TILE_1: i32 = 32;
const... |
use std::{
env,
fmt::{Display, Formatter, Result as FmtResult},
};
use failure::{Backtrace, Context, Fail};
/// convenience alias wrapper Result.
pub type Result<T> = ::std::result::Result<T, Error>;
/// Sentry package error kind.
#[derive(Debug, Fail)]
pub enum ErrorKind {
#[fail(display = "Hasher config error")]... |
#![allow(dead_code)]
use failure::Error;
use futures::IntoFuture;
use futures::{Future, Stream};
use futures_locks::Mutex as FuturesMutex;
use std::sync::Arc;
type AsyncResult<T> = Box<dyn Future<Item = T, Error = Error> + Send>;
type WorkIO = String;
trait AsyncWorker<T>
where
Self: Sync + Send,
T: Sync + ... |
/*
* hurl (https://hurl.dev)
* Copyright (C) 2020 Orange
*
* 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 ... |
use std::error;
use std::io;
use std::str;
type Result<T> = std::result::Result<T, Box<dyn error::Error>>;
pub struct Config {
contents: String,
}
impl Config {
pub fn new<T: io::Read>(reader: T) -> Result<Config> {
Ok(Config {
contents: read(reader)?,
})
}
pub fn lines(&... |
extern crate serde;
#[macro_use]
extern crate serde_derive;
use std::env;
use std::vec::Vec;
use std::error::Error;
use csv;
use rand;
use rand::thread_rng;
use rand::seq::SliceRandom;
use crfsuite::{Model, Attribute, CrfError};
use crfsuite::{Trainer, Algorithm, GraphicalModel};
#[derive(Debug, Deserialize, Clone)]... |
use std::env;
use std::sync::Once;
static ONCE: Once = Once::new();
static mut DEBUG: bool = false;
#[inline(always)]
pub(crate) fn is_debug_mode() -> bool {
unsafe {
ONCE.call_once(|| {
DEBUG = match env::var("DEBUG_POOL") {
Ok(val) => (&val == "1"),
Err(_) => ... |
#![windows_subsystem = "windows"]
extern crate cgmath;
extern crate sdl2;
mod data;
mod sprites;
mod textures;
mod game;
mod animation;
use crate::game::Game;
use crate::data::WorldMap;
use sdl2::event::Event;
use sdl2::keyboard::Keycode;
use sdl2::pixels::Color;
use sdl2::pixels::PixelFormatEnum;
u... |
use std::collections::HashMap;
use libp2p::PeerId;
#[derive(Debug, Default)]
struct Peer {
connection_status: ConnectionStatus,
sync_status: Option<p2p_proto::sync::Status>,
}
impl Peer {
pub fn connection_status(&self) -> &ConnectionStatus {
&self.connection_status
}
pub fn update_conne... |
use std::cmp::max;
pub struct Solution {}
impl Solution {
pub fn max_sub_array(nums: Vec<i32>) -> i32 {
let mut current = nums[0];
let mut maximum = nums[0];
for (i, n) in nums.iter().enumerate() {
if i == 0 {
continue;
}
current = max(... |
use std::collections::HashMap;
use serde_json::{json, Value};
use rbatis_core::convert::StmtConvert;
use rbatis_core::db::DriverType;
use crate::ast::ast::RbatisAST;
use crate::ast::node::bind_node::BindNode;
use crate::ast::node::choose_node::ChooseNode;
use crate::ast::node::delete_node::DeleteNode;
use crate::ast... |
use serde::{de::DeserializeOwned, Deserialize};
const USER: &str = "liuchengxu";
const REPO: &str = "vim-clap";
pub(super) fn asset_name() -> Option<&'static str> {
if cfg!(target_os = "macos") {
if cfg!(target_arch = "x86_64") {
Some("maple-x86_64-apple-darwin")
} else if cfg!(target_... |
use std::sync::{
Arc,
RwLock
};
use axum::{
Router,
routing::get,
extract::{
Path,
State,
},
response::IntoResponse,
};
struct StyleState {
scss:String
}
impl StyleState {
fn new(path:&str) -> Self {
Self {
scss: string!(path)
}
}
}
type SharedState = Arc<RwLock<StyleStat... |
pub(crate) use _scproxy::make_module;
#[pymodule]
mod _scproxy {
// straight-forward port of Modules/_scproxy.c
use crate::vm::{
builtins::{PyDictRef, PyStr},
convert::ToPyObject,
PyResult, VirtualMachine,
};
use system_configuration::core_foundation::{
array::CFArray,
... |
#![feature(const_fn)]
extern crate polygon_math as math;
pub mod lexer;
pub mod material_source;
pub mod parser;
pub mod token;
|
use memory;
use std;
use std::fmt;
#[derive(Default)]
pub struct Cpu {
pub clock: u8,
pub pc: u16,
sp: u16,
a: u8,
f: RegF,
b: u8,
c: u8,
d: u8,
e: u8,
h: u8,
l: u8
}
macro_rules! ld_16 {
($self:expr, $hi:ident, $lo:ident, $memory:expr) => {
{
... |
#![feature(test)]
extern crate loom;
extern crate test;
extern crate nom;
use loom::parser;
use test::black_box;
fn main() {
let input = include_str!("../../doc/reference.yarn");
#[cfg(feature="slug")]
let input = slug::wrap(input);
for i in 0 .. 10 {
println!("{}", i);
for ... |
pub mod rendering;
use std::io::{Result, Error, ErrorKind};
use super::data::{Value, Tag, Vec2, Vec3, Vec4, Box2, Reader, Writer};
use super::model::Model;
pub enum Element {
Widget(Widget),
Group(Group),
Grid(Grid),
Model(ModelElement),
Text(Text)
}
#[derive(Default)]
pub struct Widget {
... |
#![allow(non_snake_case, non_camel_case_types, non_upper_case_globals, clashing_extern_declarations, clippy::all)]
#[link(name = "windows")]
extern "system" {}
pub type Binding = *mut ::core::ffi::c_void;
pub type BindingBase = *mut ::core::ffi::c_void;
pub type BindingExpression = *mut ::core::ffi::c_void;
pub type Bi... |
use crate::ast::syntax_type::SyntaxType;
use std::collections::HashMap;
pub struct TypesIdGen<'a> {
counter: i32,
types: HashMap<Vec<SyntaxType<'a>>, i32>,
}
impl<'a> TypesIdGen<'a> {
pub fn new() -> TypesIdGen<'a> {
TypesIdGen {
counter: 0,
types: HashMap::new(),
}... |
use crate::*;
pub fn decode(state: &State, opcode: u16) -> OpCode {
let code = (
(opcode & 0x00f0) >> 4,
opcode & 0x000f,
(opcode & 0xf000) >> 12,
(opcode & 0x0f00) >> 8,
);
match code {
(0, 0, 0xE, 0) => OpCode::ClearScreen,
(0, 0, 0xE, 0xE) => OpCode::SubroutineRet,
(0, _, _, _) => OpCode::CallMCode... |
use yew::prelude::*;
struct Product {
id: i32,
name: String,
description: String,
image: String,
price: f64,
}
struct State {
products: Vec<Product>,
}
pub struct Home {
state: State,
}
impl Component for Home {
type Message = ();
type Properties = ();
fn create(_: Self::Pro... |
#[doc = "Reader of register PWRTC"]
pub type R = crate::R<u32, super::PWRTC>;
#[doc = "Writer for register PWRTC"]
pub type W = crate::W<u32, super::PWRTC>;
#[doc = "Register PWRTC `reset()`'s with value 0"]
impl crate::ResetValue for super::PWRTC {
type Type = u32;
#[inline(always)]
fn reset_value() -> Sel... |
pub mod de;
pub mod error;
pub mod ser;
pub mod types;
|
use server::Server;
use http::Request;
use http::Method;
mod server;
mod http;
fn main() {
// let server = server::Server::new("127.0.0.1:8080".to_string());
let server = Server::new("127.0.0.1:8080".to_string());
server.run();
}
/*
GET /user?id=10 HTTP/1.1\r\n
HEADERS \r\n
BODY
*/
|
// Copyright 2019 The Tari Project
//
// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the
// following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following
// dis... |
#[doc = "Reader of register TBPR"]
pub type R = crate::R<u32, super::TBPR>;
#[doc = "Writer for register TBPR"]
pub type W = crate::W<u32, super::TBPR>;
#[doc = "Register TBPR `reset()`'s with value 0"]
impl crate::ResetValue for super::TBPR {
type Type = u32;
#[inline(always)]
fn reset_value() -> Self::Typ... |
pub mod group;
mod pairing; |
use std::env;
use actix_web::{get, post, error, web, HttpServer, App,
HttpResponse, Result as HttpResult};
use mongodb::{Client, Collection, error::Result as MongoResult};
use serde::{Deserialize, Serialize};
use bson::{Bson, oid::ObjectId};
#[derive(Clone)]
struct Store {
client: Client,
db_... |
#[derive(Debug)]
pub enum Command {
LEFT,
RIGHT,
MOVE,
}
impl Command {
pub fn get_command(command: char) -> Self {
match command {
'L' => Command::LEFT,
'R' => Command::RIGHT,
'M' => Command::MOVE,
_ => panic!("Not a valid command"),
}
... |
//! Command line options for running a router that uses the RPC write path.
use super::main;
use crate::process_info::setup_metric_registry;
use clap_blocks::{
catalog_dsn::CatalogDsnConfig, object_store::make_object_store, router::RouterConfig,
run_config::RunConfig,
};
use iox_time::{SystemProvider, TimeProvi... |
#![crate_name = "git2"]
#![crate_type="lib"]
//! The git2 crate
pub mod git2 {
//! The git2 module
extern crate libc;
use self::libc::c_int;
pub use self::repository::{Repository};
pub use self::reference::{Reference};
pub use self::oid::{OID, ToOID};
pub use self::object::{Object, GitO... |
use crate::txn::vars::TVar;
use crate::txn::version::*;
use std::any::Any;
use std::sync::Arc;
pub(crate) fn convert_ref<R: Any + Clone + Send + Sync>(from: Var) -> R {
(&*from as &dyn Any).downcast_ref::<R>().unwrap().clone()
}
// TODO: Nightly stuff, polish up a bit with feature gates.
// pub fn print_type_of<T... |
/// 给定一个大小为 n 的数组,找出其中所有出现超过 ⌊ n/3 ⌋ 次的元素。
///
/// 说明: 要求算法的时间复杂度为 O(n),空间复杂度为 O(1)。
///
/// 示例 1:
///
/// 输入: [3,2,3]
/// 输出: [3]
///
/// 示例 2:
///
/// 输入: [1,1,1,3,3,2,2,2]
/// 输出: [1,2]
///
const N: usize = 2;
pub fn have_zero_count(count: &[i32;N]) -> bool {
if count.iter().find(|&&a| a... |
/// The error which is returned when sending a value into a channel fails.
///
/// The `send` operation can only fail if the channel has been closed, which
/// would prevent the other actors to ever retrieve the value.
///
/// The error recovers the value that has been sent.
#[derive(PartialEq, Debug)]
pub struct Chan... |
/*
* Open Service Cloud API
*
* Open Service Cloud API to manage different backend cloud services.
*
* The version of the OpenAPI document: 0.0.3
* Contact: wanghui71leon@gmail.com
* Generated by: https://openapi-generator.tech
*/
#[derive(Debug, PartialEq, Serialize, Deserialize)]
pub struct StorageResource... |
use std::convert::Into;
use std::num::NonZeroU32;
use std::ops::Range;
use super::*;
/// A handle that points to a file in the database.
#[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct SourceId(pub(crate) NonZeroU32);
impl SourceId {
pub(crate) const UNKNOWN_SOURCE_ID: u32 = u32::ma... |
use ruduino::Pin;
use ruduino::cores::current::{port};
use ruduino::interrupt::*;
use spi;
pub fn setup() {
// RAM chip select
port::D6::set_output(); port::D6::set_high();
port::D6::set_low();
spi::sync(0x01);
spi::sync(0x00);
port::D6::set_high();
}
pub fn write_ram(addr: u16, value: u8) {
... |
use bit_field;
use bitflags;
impl VirtualPageNumber{
//获取页号
pub fn levels(self) -> [usize;3] {
pub fn level(self) -> [usize;3]{
[
self.0.get_bits(18..27),
self.0.get_bits(9..18),
self.0.get_bits(0..9),
]
}
}
} |
extern crate proc_macro;
use convert_case::{Case, Casing};
use proc_macro2::{Ident, TokenStream};
use quote::quote;
use syn::{parse_macro_input, FnArg, GenericArgument, Item, PathArguments, Signature, Type};
#[proc_macro_attribute]
pub fn embedded(
_args: proc_macro::TokenStream,
input: proc_macro::TokenStrea... |
use clap::{App, Arg};
use futures::prelude::*;
use influxdb2_client;
use sensehat::{SenseHat};
use serde::{Deserialize, Serialize};
use std::borrow::BorrowMut;
use std::fs::File;
use std::io::BufReader;
#[derive(Serialize, Deserialize, Debug)]
struct EndpointConfig {
org: String,
bucket: String,
url: Strin... |
/*!
An application that load new fonts from file
*/
extern crate native_windows_gui as nwg;
extern crate native_windows_derive as nwd;
use nwd::NwgUi;
use nwg::NativeUi;
#[derive(Default, NwgUi)]
pub struct CustomFontApp {
#[nwg_control(size: (300, 200), position: (300, 300), title: "Custom Fonts")]
#[n... |
use regex::Regex;
use std::collections::HashMap;
use std::fs;
use std::str;
#[test]
fn validate_7_2() {
assert_eq!(algorithm("src/day_7/input_test.txt"), 32);
assert_eq!(algorithm("src/day_7/input_test2.txt"), 126);
}
fn algorithm(file_location: &str) -> i32 {
let rule_delimiter = Regex::new("s contain |s... |
use types::{Plugin};
//use std::collections::HashMap;
use std::sync::{Mutex, MutexGuard};
lazy_static! {
static ref PLUGINS: Mutex<Vec<Plugin>> = Mutex::new(vec![]);
/*
pub static ref web_data: HashMap<&'static str, &'static str> = {
let mut m = HashMap::new();
m.insert("status", "down");
... |
use cancellable_io::*;
use std::io::{Read, Write};
use std::thread;
use std::time::Duration;
fn main() {
let (listener, listener_canceller) = TcpListener::bind("127.0.0.1:0").unwrap();
let address = listener.local_addr().unwrap();
let server = thread::spawn(move || {
println!("Server: ready");
... |
use std::{
io::{BufReader, BufWriter, Seek, SeekFrom, Write},
path::Path,
};
use actix_multipart::Multipart;
use actix_web::{web, Error, HttpRequest, HttpResponse};
use diesel::prelude::*;
use futures::{StreamExt, TryStreamExt};
use crate::{
chunker::Chunker,
external_id::ExternalId,
graphql_schem... |
use std::f32::consts::{PI, SQRT_2};
use rapier3d::{na::Quaternion, prelude::*};
use crate::RawIsometry;
pub enum VehicleType {
Drone,
}
pub fn create_vehicle(vehicle_type: VehicleType, use_data: bool, data: &[f32]) -> Box<dyn Vehicle> {
Box::new(match vehicle_type {
VehicleType::Drone => Drone::para... |
mod button;
mod key;
use crate::event::{Axis, Button, Direction, Event, Key, KeyKind};
use crate::linux::glue::{self, input_event, timeval};
impl Event {
pub(crate) fn to_raw(&self) -> input_event {
let (type_, code, value) = match *self {
Event::MouseScroll { delta } => (glue::EV_REL as _, gl... |
use execution::{ActionExecutionCtx, ExecutionContextResult};
use recipe::ActionInput;
use recipe::ActionNestRecipeCommand;
use recipe::ActionRecipeBuilder;
use recipe::{ActionRecipe, ActionRecipeItem};
use slab::Slab;
use std::collections::BTreeSet;
use ActionConfiguration;
pub struct ActionContext<C: ActionConfigurat... |
mod auth;
mod compress;
mod directory;
mod index;
mod log;
mod method;
mod proxy;
mod rewrite;
pub use auth::*;
pub use compress::*;
pub use directory::*;
pub use index::*;
pub use log::*;
pub use method::*;
pub use proxy::*;
pub use rewrite::*;
|
use super::*;
use nom::dbg_dmp;
const INPUT: &[u8] = include_bytes!("../../assets/robmot_PV626.farc");
const COMP: &[u8] = include_bytes!("../../assets/gm_module_tbl.farc");
const FARC: &[u8] = include_bytes!("../../assets/pv_721_common.farc");
const FUTURE: &[u8] = include_bytes!("../../assets/lenitm027.farc");
#[te... |
use serde_json::json;
use actix_web::post;
use actix_web::HttpResponse;
use actix_session::Session;
use actix_web::web::{Json, Path};
use crate::api::error::ServerError;
use crate::sql::store::user_repository::user::{NewUser, User};
/**
* Метод для регистрации пользователя
*/
#[post("/registration")]
pub async fn... |
#[derive(Debug, DbEnum, Serialize, Deserialize)]
pub enum Difficulty {
Easy,
Normal,
Hard,
Expert,
ExpertPlus,
}
table! {
use super::DifficultyMapping;
use diesel::sql_types::{
Uuid,
Text,
Double,
Integer,
};
maps (id) {
id -> Uuid,
ha... |
use crate::api;
use crate::component::{Panel, PanelBlock, PanelHeading};
use std::collections::hash_map::Entry;
use std::collections::HashMap;
use yew::format::Json;
use yew::prelude::*;
use yew::services::fetch::FetchTask;
const COLOURS: [&str; 12] = [
"#8ecbb7", "#e4aee0", "#88ddad", "#efa6a6", "#6adcdc", "#e8ba... |
/**
* Unsafe debugging functions for inspecting values.
*
* Your RUST_LOG environment variable must contain "stdlib" for any debug
* logging.
*/
// FIXME: handle 64-bit case.
const const_refcount: uint = 0x7bad_face_u;
native "rust" mod rustrt {
fn debug_tydesc[T]();
fn debug_opaque[T](x: &T);
fn ... |
mod add_fields;
mod aws_kinesis_streams;
mod blackhole;
mod elasticsearch;
mod file;
mod json;
#[cfg(feature = "sources-kubernetes-logs")]
mod kubernetes_logs;
#[cfg(feature = "transforms-lua")]
mod lua;
#[cfg(feature = "sources-prometheus")]
mod prometheus;
mod regex;
mod splunk_hec;
mod syslog;
mod tcp;
mod udp;
mod ... |
use crate::compiling::v1::assemble::prelude::*;
impl AssembleFn for ast::ItemFn {
fn assemble_fn(&self, c: &mut Compiler<'_>, instance_fn: bool) -> CompileResult<()> {
let span = self.span();
log::trace!("ItemFn => {:?}", c.source.source(span));
let mut patterns = Vec::new();
let m... |
use std::cmp::{max, min};
use std::collections::{HashMap, HashSet};
use itertools::Itertools;
use whiteread::parse_line;
fn main() {
let n: usize = parse_line().unwrap();
let tt: Vec<usize> = parse_line().unwrap();
let ttsum: usize = tt.iter().sum();
let mut left = if ttsum % 2 == 1 {
ttsum /... |
use std::num::ParseIntError;
use std::fs::File;
use std::io::Read;
pub type Rows = Vec<Vec<u32>>;
pub fn parse_rows(s: &str) -> Result<Rows, ParseIntError> {
s.lines()
.map(|line| {
line.split_whitespace()
.map(|s| s.parse::<u32>())
.collect::<Result<Vec<u32>, P... |
use projecteuler::partition;
use projecteuler::primes;
use num::BigUint;
fn main() {
//dbg!(binomial::binomial_coefficient(100, 50));
dbg!(primes::factorize(1_000_000));
for i in 1..10 {
dbg!(i, partition::partition(i));
}
dbg!(solve(5));
dbg!(solve(2));
dbg!(solve(100));
dbg!(... |
use midir::{Ignore, MidiInput, MidiInputConnection};
use std::sync::mpsc::Sender;
#[derive(Copy, Clone, Eq, PartialEq)]
pub enum MidiMessageKind {
KeyPress,
KeyRelease,
}
#[derive(Copy, Clone)]
pub struct MidiMessage {
pub kind: MidiMessageKind,
pub key: u8,
pub velocity: u8,
}
pub fn listen_to_i... |
use crate::{
caveat::{CaveatBuilder, CaveatType},
error::MacaroonError,
serialization::macaroon_builder::MacaroonBuilder,
Macaroon,
};
// Version 2 fields
const EOS_V2: u8 = 0;
const LOCATION_V2: u8 = 1;
const IDENTIFIER_V2: u8 = 2;
const VID_V2: u8 = 4;
const SIGNATURE_V2: u8 = 6;
const VARINT_PACK_S... |
//! Data access to MSP buffer~ object data.
use crate::{notify::Notification, symbol::SymbolRef};
use core::ffi::c_void;
use std::convert::TryFrom;
use std::marker::PhantomData;
use std::ops::{DerefMut, Index, IndexMut};
lazy_static::lazy_static! {
static ref GLOBAL_SYMBOL_BINDING: SymbolRef = SymbolRef::try_from(... |
use std::env;
use std::fs::File;
use std::io::BufRead;
use std::io::BufReader;
use std::str::FromStr;
struct Row {
data: Vec<usize>,
len: usize,
}
fn get_parse<T: FromStr>(reader: &mut BufReader<File>) -> Result<T, T::Err> {
let mut line = String::new();
reader.read_line(&mut line).unwrap();
line.trim().parse:... |
// Copyright (c) 2021 Quark Container Authors / 2018 The gVisor Authors.
//
// 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 ... |
const SEAL_MASK: u32 = (libc::F_SEAL_SEAL | libc::F_SEAL_SHRINK | libc::F_SEAL_GROW | libc::F_SEAL_WRITE | libc::F_SEAL_FUTURE_WRITE) as u32;
const ALL_SEALS: [Seal; 5] = [Seal::Seal, Seal::Shrink, Seal::Grow, Seal::Write, Seal::FutureWrite];
/// A seal that prevents certain actions from being performed on a file.
///... |
use hyper::service::{make_service_fn, service_fn};
use hyper::{header::CONTENT_TYPE, Body, Request, Response, Server, StatusCode};
// Import the multer types.
use multer::Multipart;
use std::{convert::Infallible, net::SocketAddr};
// A handler for incoming requests.
async fn handle(req: Request<Body>) -> Result<Respon... |
pub mod utils;
pub mod db;
pub mod store;
#[cfg(test)]
pub mod tests;
|
use cm_fidl_translator;
use failure::Error;
use fidl_fuchsia_data as fd;
use fidl_fuchsia_sys2::{
ChildDecl, ChildRef, CollectionDecl, CollectionRef, ComponentDecl, Durability, ExposeDecl,
ExposeDirectoryDecl, ExposeLegacyServiceDecl, ExposeServiceDecl, FrameworkRef, OfferDecl,
OfferLegacyServiceDecl, Offer... |
use std::collections::HashMap;
use crate::entities::enemy::Enemy;
use crate::entities::player::Player;
use crate::room::RoomType;
#[derive(Debug)]
pub struct State {
pub current_room: RoomType,
pub player: Player,
pub enemies: HashMap<RoomType, Box<Enemy>>,
}
impl State {
pub fn new() -> Self {
... |
use super::schema::conditions;
use chrono;
pub mod handler;
pub mod repository;
#[table_name="conditions"]
#[derive(Queryable,Insertable,Serialize,Deserialize, Debug, Clone)]
pub struct Conditions {
pub time: chrono::NaiveDateTime,
pub device_id: String,
pub temperature: Option<bigdecimal::BigDecimal>,
... |
use super::*;
use proptest::strategy::Strategy;
#[test]
fn with_number_atom_reference_function_port_pid_tuple_map_or_list_returns_first() {
run!(
|arc_process| {
(
strategy::term::binary::heap(arc_process.clone()),
strategy::term(arc_process.clone()).pro... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.