text stringlengths 8 4.13M |
|---|
#![no_std]
#![no_main]
use punda::{
button::{Button, State},
context::*,
delay, serial,
};
use rtfm::Mutex;
use core::sync::atomic::{AtomicU32, Ordering};
punda::punda!(init = init, idle = idle, button_handler = button_handler);
static COUNTER: AtomicU32 = AtomicU32::new(0);
fn init(cx: &mut InitConte... |
use uuid::Uuid;
pub trait Trackable {
fn get_handle(&self) -> &Uuid;
}
|
use std::env;
use std::io;
use std::str;
use serde::Deserialize;
use rocksdb::DB;
#[derive(Debug, Deserialize)]
struct Puzzle {
id: String,
fen: String,
moves: String,
rating: i32,
rd: i32,
popularity: i32,
played: u32,
themes: String,
url: String,
}
fn main() -> io::Result<()> {
... |
/// A struct representing a Huffman tree.
/// Specifically designed for use in the DEFLATE algorithm.
pub struct HuffmanTree {
codes: Vec<Option<Code>>,
}
/// Specifies a binary code
/// Code length is <= 16 bits;
/// length is encoded to say how long
#[derive(Debug, Clone)]
pub struct Code {
pub value: u16,
... |
use std::fmt;
use std::cell::RefCell;
use std::rc::Rc;
use std::boxed::Box;
use super::Bus;
use super::Register32;
#[allow(unused_imports)]
use super::{MemoryAccess, MemoryAccess16, MemoryAccess32};
use super::MotherboardMemory;
use super::{HardwareZeroRegister, Register};
use super::ArithmaticLogicUnit;
use super... |
#![recursion_limit = "1024"]
#[macro_use]
extern crate error_chain;
extern crate time;
pub mod errors {
error_chain!{
foreign_links {
IO(::std::io::Error);
}
errors {
NotImplemented(name: String){
description("not implemented")
displa... |
extern crate interledger_store_redis;
#[macro_use]
extern crate lazy_static;
use bytes::Bytes;
use env_logger;
use futures::{future, Future};
use interledger_api::{AccountDetails, NodeStore};
use interledger_store_redis::{connect, connect_with_poll_interval, Account, RedisStore};
use parking_lot::Mutex;
use redis;
use... |
use semver::Version;
#[derive(PartialEq, Eq, Clone, Debug)]
pub struct SupportVersion(Version);
impl SupportVersion {
pub fn new(v: Version) -> Self {
Self(v)
}
pub fn parse(s: &str) -> Option<Self> {
let s = s.trim();
if let Ok(v) = Version::parse(s).or(Version::parse(format!("{}... |
// Chess library
use std::iter::Iterator;
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
// GameState represents the current state of the game
pub enum GameState {
InProgress,
Check,
GameOver,
Checkmate, // DeadPosition
}
enum ColorState {
White,
Black,
}
enum Castling {
BlackKing,
Blac... |
//! Benchmarking setup for pallet-poe
use super::*;
/*
编译:
cargo build --features runtime-benchmarks --release
运行
./target/release/node-template benchmark \
--chain dev \
--execution=wasm \
--wasm-execution=compiled \
--pallet=pallet-poe \
--extrinsic create_claim_benchmark \
--steps=10 \
--rep... |
pub mod fs_color_2d;
pub mod fs_color_2d_gradient;
pub mod fs_color_3d; |
use std::cmp::Ordering;
use std::sync::Arc;
use rand::Rng;
use crate::aabb::{surrounding_box, Aabb};
use crate::hitable::{HitRecord, Hitable};
use crate::ray::Ray;
pub struct BvhNode {
left: Arc<dyn Hitable>,
right: Arc<dyn Hitable>,
bbox: Aabb,
}
impl BvhNode {
pub fn new(l: &mut [Arc<dyn Hitable>]... |
/// An implementation of https://bixense.com/clicolors/
fn clicolor() -> bool {
let color_var = std::env::var("CLICOLOR").unwrap_or(String::from("1"));
let force_color = std::env::var("CLICOLOR_FORCE").unwrap_or(String::from("0"));
if (color_var != "0" && atty::is(atty::Stream::Stdout)) || force_color != "... |
use std::fs;
fn is_sum_of(r : usize, prev : &[usize]) -> bool {
prev.iter().filter(|x| prev.contains(&(r-*x)) && r != *x*2 ).count() > 0
}
fn find_summing(r : usize, nums : &Vec<usize>) -> usize {
let mut adding = 0;
let mut min = 0;
for max in 0..nums.len() {
adding += nums[max];
whil... |
use command::Address;
#[derive(Clone, Debug, PartialEq)]
pub struct Line {
pub contents: String,
pub addr: Address,
}
|
// Copyright 2020 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 ... |
extern crate reqwest;
use std::collections::HashMap;
fn main() -> Result<(), Box<std::error::Error>> {
// Simple GET
let mut get_response = reqwest::get("http://localhost:8000")?;
println!("{:#?}", get_response);
println!("{:#?}", get_response.text()?);
// To get JSON response
// get_respo... |
use std::sync::mpsc::channel;
use std::thread;
use std::sync::{Mutex, Arc};
fn main() {
normal_channel_test();
normal_thread_test();
thread_channel();
add_in_single_thread();
add_in_multi_thread();
}
fn normal_channel_test() {
let (tx, rx) = channel();
tx.send(String::from("normal_ch... |
/*!
In rare cases you may want to access the dynamically load library API directly.
This is not recommended since it is library-specific and may increase complexity of your
application. But it may be the only way if you need to do something that is very specific
to the given library.
Rawsock provide... |
struct User {
active: bool,
username: String,
email: String,
sign_in_count: u64,
}
fn main() {
let user1 = User {
active: true,
username: String::from("someusername123"),
email: String::from("someone@example.com"),
sign_in_count: 1,
};
println!(
"{}: ... |
use std::fs::File;
use std::io::prelude::*;
use toml::{Parser, Value};
use toml;
#[derive(RustcDecodable, Debug)]
pub struct ES {
pub mapping: String,
pub hotcloudmapping: String,
pub query: String,
pub bulk_size: usize
}
impl ES {
fn new() -> ES {
ES {
mapping: String::new(),... |
use params as global_params;
use rand;
use rand::{Rng, ThreadRng};
use rand::distributions::Distribution;
use rand::distributions::Exp1;
use evo_sys::{Program, Instruction};
use core::{FeatIndType, RegIndType};
use evo_sys::params as evo_params;
use data::params::N_FEATURES;
use std::collections::VecDeque;
us... |
//! Integration tests for the GDLK Wasm API
#![deny(clippy::all)]
// Needed for the macro
#![allow(clippy::bool_assert_comparison)]
use gdlk_wasm::{
compile, HardwareSpec, LangValue, ProgramSpec, SourceElement, Span,
};
use maplit::hashmap;
use std::collections::HashMap;
use wasm_bindgen_test::wasm_bindgen_test;
... |
//! Decoding utilities.
use http::header::HeaderValue;
/// A helper trait for use when deriving `Header`.
pub trait TryFromValues: Sized {
/// Try to convert from the values into an instance of `Self`.
fn try_from_values(values: &mut ::Values) -> Option<Self>;
}
impl TryFromValues for HeaderValue {
fn tr... |
// Copyright (c) The Libra Core Contributors
// SPDX-License-Identifier: Apache-2.0
//! Logic for generating valid stack states for native function calls.
//!
//! This implements a `StackAccessor` that generates random bytearrays of a user defined length. We
//! then use this ability to run the native functions with d... |
use crate::common::*;
#[derive(PartialEq, Debug, Clone)]
pub(crate) enum OutputTarget {
Path(PathBuf),
Stdout,
}
impl OutputTarget {
pub(crate) fn resolve(&self, env: &Env) -> Result<Self> {
match self {
Self::Path(path) => Ok(Self::Path(env.resolve(path)?)),
Self::Stdout => Ok(Self::Stdout),
... |
use crate::syntax::identifiers::*;
use crate::value::implement::*;
impl<'a> BergValue<'a> for bool {}
impl<'a> EvaluatableValue<'a> for bool {
fn evaluate(self) -> BergResult<'a> where Self: Sized {
self.ok()
}
}
// Implementations for common types
impl<'a> Value<'a> for bool {
fn lazy_val(self) ... |
#![feature(macro_rules)]
#![allow(non_camel_case_types)]
extern crate libc;
extern crate "libz-sys" as libz;
#[cfg(unix)] extern crate "openssl-sys" as openssl;
use libc::{c_void, c_int, c_char, c_uint, c_long};
pub type CURLINFO = c_int;
pub type CURL = c_void;
pub type curl_slist = c_void;
pub type CURLoption = c_... |
use std::str::FromStr;
use anyhow::Result;
use derive_more::Display;
use serde::{de, Deserialize, Serialize, Serializer};
use ulid::Ulid;
use crate::util::myerror::MyError;
#[derive(Copy, Clone, Debug, PartialEq, Eq, Display)]
pub struct UserId(Ulid);
impl UserId {
pub fn new(s: &str) -> Result<Self> {
... |
#[derive(PartialEq, Eq, Hash)]
pub enum DecodeHintType {
Other,
PureBarcode,
PossibleFormat,
TryHarder,
CharacterSet,
AllowedLengths,
AssumeCode39CheckDigit,
AssumeGS1,
ReturnCodebarStartEnd,
NeedResultPointCallback,
AllowedEANExtensions,
} |
// Copyright GFX Developers 2014-2017
//
// 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 ... |
extern crate log;
extern crate env_logger;
#[macro_use] extern crate serde_derive;
#[macro_use] extern crate serde_json;
extern crate json;
extern crate base64;
extern crate actix_web;
extern crate roadrunner;
extern crate tokio_core;
extern crate hyper;
extern crate rand;
extern crate futures;
extern crate actix_web_h... |
fn main() {
cc::Build::new()
.file("src/config_file.c")
.file("src/driver.c")
.file("src/ir_remote.c")
.file("src/lirc_log.c")
.file("src/receive.c")
.file("src/transmit.c")
.warnings(false)
.compile("liblirc.a");
}
|
mod spidar_mouse;
use spidar_mouse::{post::impl_post,ws::impl_ws};
use actix_web::{App, HttpResponse, HttpServer, Responder, web, get};
const INDEX: &str = include_str!("./static/index.html");
const WS_INDEX: &str = include_str!("./static/ws.html");
const WSJS: &str = include_str!("./static/ws.js");
#[get("/")]
asyn... |
use std::{cell::RefCell, collections::HashSet};
use rand::prelude::*;
thread_local! {
static NAMES: RefCell<HashSet<String>> = RefCell::new(HashSet::new());
}
#[derive(Debug, Default)]
pub struct Robot(String);
impl Robot {
pub fn new() -> Self {
Self(gen_name())
}
pub fn name(&self) -> &str... |
#[test]
fn purity() {
let greet = |name: &str| format!("Hi! {}", name);
assert_eq!("Hi! Jason", greet("Jason"));
}
#[test]
fn impure() {
let name = "Jason";
let greet = || -> String { format!("Hi! {}", name) };
assert_eq!("Hi! Jason", greet());
}
#[test]
fn impure2() {
let mut greeting: Str... |
pub const AES_BLOCK_SIZE_IN_BYTES : usize = 16usize;
|
// Copyright (c) 2021 Via Technology Ltd. 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... |
//! # probabilistic-collections-rs
//!
//! [](https://crates.io/crates/probabilistic-collections)
//! [](https://docs.rs/probabilistic-collections)
//! [![License: ... |
use criterion::{criterion_group, criterion_main, Criterion};
use lib::logger::LoggerInner;
use lib::parser;
use lib::sourcemap::SourceMapInner;
use std::path;
use std::rc::Rc;
#[allow(unused_must_use)]
fn criterion_benchmark(c: &mut Criterion) {
let sourcemap = SourceMapInner::new();
sourcemap.borrow_mut().in... |
use std::collections::HashMap;
use seq_watcher::SequenceWatcher;
use criterion::{black_box, criterion_group, criterion_main, Criterion};
fn iterator_comparison<'a, I: Iterator<Item = &'a SequenceWatcher<u8>>>(iter: I) {
for w in iter {
w.check(&0);
}
}
fn version_benchmarks(c: &mut Criterion) {
le... |
use alloc::{vec, vec::Vec};
use core::fmt::{self, Display};
#[derive(Clone, Debug, Default, Eq, PartialEq)]
pub struct Args<T>(Vec<T>);
impl<T: Display> Display for Args<T> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let mut iter = self.0.iter();
if let Some(arg) = iter.next() {
... |
use crate::vectors::vec3::Vec3;
pub struct Ray {
pub orig: Vec3,
pub dir: Vec3,
}
impl Ray {
pub fn origin(&self) -> Vec3 {
self.orig
}
pub fn direction(&self) -> Vec3 {
self.dir
}
pub fn at(&self, t: f64) -> Vec3 {
self.orig + t * self.dir
}
}
#[cfg(test)]
m... |
use std::collections::HashSet;
use proc_macro2::TokenStream;
use quote::ToTokens;
use crate::{
attr::{Attribute, AttributeParse, VecAttribute},
ctx::Context,
r#impl::Implementer,
};
use super::{
derive::{self, DeriveSetting},
r#struct::Struct,
variant::Variant,
};
struct EnumAttrs {
rese... |
use std::sync::Arc;
use std::time::Duration;
use parking_lot::Mutex;
use data_types::write_summary::TimestampSummary;
use metric::{Attributes, DurationHistogram, DurationHistogramOptions};
use metrics::{Gauge, GaugeValue, KeyValue};
use tracker::{LockMetrics, RwLock};
use crate::db::catalog::chunk::ChunkMetrics;
co... |
#![no_main]
#![no_std]
use co2_sensor as _; // global logger + panicking-behavior + memory layout
use hal::gpio::Pin;
use nrf52840_hal::{
self as hal,
gpio::{p0::Parts as P0Parts, Level, Output, PushPull},
Temp, Timer,
};
use embedded_hal::{blocking::delay::DelayMs, digital::v2::OutputPin};
/// A trait ... |
use std::io;
use std::str::FromStr;
use accounts::*;
use args::*;
use budgets::*;
use categories::*;
use constants::*;
use months::*;
use payees::*;
use scheduled_transactions::*;
use transactions::*;
use types::*;
use user::*;
use ynab_state::*;
pub fn run(
prog_name: &str,
// default_options: GlobalOptions,... |
use super::super::server_folder::business_class::BusinessObject;
use super::super::server_folder::fsmclass::Fsmclass;
use super::super::server_folder::fsmclass::States;
use super::super::server_folder::guardclass::Guardclass;
use super::super::server_folder::msgfactoryclass::*;
use super::super::server_folder::prodmsgc... |
table! {
games (id) {
id -> Int4,
status -> Varchar,
ts -> Int4,
}
}
table! {
users (id) {
id -> Int4,
name -> Varchar,
score -> Int4,
ts -> Int4,
}
}
allow_tables_to_appear_in_same_query!(
games,
users,
);
|
use crate::assembler::x86_64::*;
use crate::bytecode::*;
use std::mem;
use std::ptr;
use std::fs::OpenOptions;
use std::io::{Result, Write};
use std::path::Path;
use libc::{c_void, mmap, mprotect, munmap, PROT_EXEC, PROT_WRITE, MAP_ANON, MAP_PRIVATE};
use vec_map::VecMap;
use syscall;
pub fn execute_bytecode(instru... |
use super::field::Field;
use super::FIELDS;
use serde::de::{self, Visitor};
use std::fmt;
pub struct FieldVisitor;
impl<'de> Visitor<'de> for FieldVisitor {
type Value = Field;
fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str("`file_id`, `name`, `folder_id`, `p... |
use itertools::Itertools;
#[aoc_generator(day10)]
fn day10_gen(input: &str) -> Vec<usize> {
let mut jolts: Vec<usize> = input.split('\n').map(|x| x.parse()).flatten().collect();
jolts.sort();
let highest = jolts.iter().max().unwrap();
let device = highest+3;
jolts.push(device);
jolts
}
#[aoc(day10, part1)]
fn p... |
use erased_serde::serialize_trait_object;
use crate::{characteristic::HapCharacteristic, HapType};
mod generated;
pub use crate::service::generated::*;
/// `HapService` is implemented by the inner type of every `Service`.
pub trait HapService: erased_serde::Serialize + Send + Sync {
/// Returns the ID of a Serv... |
#[derive(Debug)]
pub(crate) struct Serializer<'ser> {
buf: &'ser mut Vec<u8>,
start: usize,
endianness: crate::Endianness,
}
impl<'ser> Serializer<'ser> {
pub(crate) fn new(buf: &'ser mut Vec<u8>, endianness: crate::Endianness) -> Self {
let start = buf.len();
Serializer {
buf,
start,
endianness,
}
... |
use std::collections::HashMap;
use rand::Rng;
use entity_store::{EntityId, EntityStore, EntityStoreChange};
use spatial_hash::SpatialHashTable;
use schedule::Schedule;
use knowledge::PlayerKnowledgeGrid;
use behaviour::{BehaviourState, BehaviourEnv};
use veil_state::VeilState;
use content::VeilStepInfo;
pub struct Lev... |
use markdown::parsers::format_links;
use tasks::CompileState;
use crate::{get_template_file, render_includes, Render};
pub struct SearchResultsPage {
pub pages: Vec<String>,
}
impl SearchResultsPage {
pub fn new(pages: Vec<String>) -> Self {
SearchResultsPage { pages }
}
fn render_pages(&self... |
mod gcloud;
pub use gcloud::GCloud;
pub use gcloud::bigquery::BigQueryClient;
pub use gcloud::bigquery::Table;
|
use rand::distributions::Standard;
use rand::{thread_rng, Rng};
use std::{
net::SocketAddr,
time::{Duration, SystemTime},
};
pub fn gen_random_bytes(n_bytes: usize) -> Vec<u8> {
let rng = thread_rng();
rng.sample_iter(Standard).take(n_bytes).collect()
}
pub fn current_time() -> Duration {
SystemTi... |
#![cfg_attr(feature="nightly", feature(plugin))]
#![cfg_attr(feature="nightly", plugin(clippy))]
pub const HASH_SIZE: usize = 243;
pub const STATE_SIZE: usize = HASH_SIZE * 3;
const T: [i8; 11] = [1, 0, -1, 0, 1, -1, 0, 0, -1, 1, 0];
pub type State = [i8; STATE_SIZE];
pub type Hash = [i8; HASH_SIZE];
pub struct Cur... |
use bellperson::gadgets::{boolean::Boolean, num};
use bellperson::{ConstraintSystem, SynthesisError};
use fil_sapling_crypto::circuit::pedersen_hash;
use paired::bls12_381::Bls12;
use crate::crypto::pedersen::{JJ_PARAMS, PEDERSEN_BLOCK_SIZE};
/// Pedersen hashing for inputs with length multiple of the block size. Bas... |
#![allow(dead_code)]
pub mod app;
pub mod ui;
|
fn is_valid_password(password: &str) -> bool {
let digits: Vec<u32> = password.chars().map(|c| c.to_digit(10).unwrap()).collect();
let windows = digits[..].windows(2);
let increasing = windows.clone().all(|w| w[0] <= w[1]);
let digit_doubled = windows.clone().any(|w| w[0] == w[1]);
increasing && di... |
use color::RayTraceColor;
use hit::RayTraceMaterialHit;
use material::RayTraceMaterial;
pub struct RayTraceSimpleMaterial {
color: RayTraceColor,
reflectance: f32
}
impl RayTraceSimpleMaterial {
pub fn new(color: RayTraceColor) -> Self {
Self {
color: color,
reflectance: 0.0
}
}
pub fn new_with_colo... |
use perseus::Template;
use std::sync::Arc;
use sycamore::prelude::{component, template, GenericNode, Template as SycamoreTemplate};
#[component(AboutPage<G>)]
pub fn about_page() -> SycamoreTemplate<G> {
template! {
p { "About." }
}
}
pub fn get_page<G: GenericNode>() -> Template<G> {
Template::ne... |
use serde::Serialize;
use serde::de::DeserializeOwned;
use std::fmt::Debug;
use actix_web::{web, HttpResponse};
use mongodb::bson::oid::ObjectId;
use crate::models::*;
use crate::db;
use crate::app::*;
use crate::api::{do_response, form::*};
pub async fn search
<T:'static + Serialize + DeserializeOwned + Unpin ... |
// this stuff is too difficult to implement for me.
//
// For reference please refer this article: https://manishearth.github.io/blog/2017/01/11/rust-tidbits-what-is-a-lang-item/
trait MathOps {
type OtherVar;
type Output;
fn add(&self, other: Self::OtherVar) -> Self::Output;
}
#[derive(Debug)]
struct Int... |
use neon::prelude::*;
use neon::register_module;
mod mstsc;
pub use mstsc::Server;
pub use mstsc::start_rdp;
struct BackgroundTask {
server: Server
}
impl Task for BackgroundTask {
// If the computation does not error, it will return an i32.
// Otherwise, it will return a String as an error
type Out... |
#[doc = "Reader of register SCGC5"]
pub type R = crate::R<u32, super::SCGC5>;
#[doc = "Writer for register SCGC5"]
pub type W = crate::W<u32, super::SCGC5>;
#[doc = "Register SCGC5 `reset()`'s with value 0x000b_0000"]
impl crate::ResetValue for super::SCGC5 {
type Type = u32;
#[inline(always)]
fn reset_valu... |
use super::{Context, Module, ModuleConfig};
use crate::configs::fennel::FennelConfig;
use crate::formatter::{StringFormatter, VersionFormatter};
use crate::utils::get_command_string_output;
pub fn module<'a>(context: &'a Context) -> Option<Module<'a>> {
let mut module = context.new_module("fennel");
let confi... |
extern crate serde_yaml;
extern crate failure;
extern crate tracy;
use std::io::{BufReader};
use std::fs;
use tracy::{Scene};
fn read_scene(path: &str) -> Result<Scene, failure::Error> {
let file = fs::File::open(path)?;
let reader = BufReader::new(file);
let val = serde_yaml::from_reader(reader)?;
O... |
use crate::operators::{BinaryOperator, AbelianBinaryOperator,InvertibleBinaryOperator, InvertibleAbelianBinaryOperator};
use std::marker::PhantomData;
use std::ops;
#[derive(Debug)]
pub struct CommutativeRingElement<S: PartialEq, A: InvertibleAbelianBinaryOperator<S>, M: AbelianBinaryOperator<S>> {
element: S,
... |
//! NIST P-384 elliptic curve (a.k.a. secp384r1)
use super::Curve;
use generic_array::typenum::U48;
/// NIST P-384 elliptic curve.
///
/// This curve is also known as secp384r1 (SECG) and is specified in
/// FIPS 186-4: Digital Signature Standard (DSS):
///
/// <https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.186-4.... |
use rustc_version::*;
use std::env;
fn transfer_env(var: &str) {
if let Ok(value) = env::var(var) {
println!("cargo:rustc-env={}={}", var, value);
}
}
fn main() {
transfer_env("PROFILE");
transfer_env("TARGET");
transfer_env("HOST");
if let Ok(version) = version_meta() {
printl... |
use crate::token::*;
pub struct Lexer {
text: String,
position: usize,
}
impl Lexer {
pub fn new(text: String) -> Lexer {
Lexer { text, position: 0 }
}
pub fn get_current_char(&self) -> char {
match self.text.chars().nth(self.position) {
None => '\0',
Some(... |
#![no_main]
use jomini::Scalar;
use libfuzzer_sys::fuzz_target;
fuzz_target!(|data: &[u8]| {
let scalar = Scalar::new(data);
let _ = scalar.to_f64();
let _ = scalar.to_u64();
let _ = scalar.to_i64();
let _ = scalar.is_ascii();
let _ = scalar.to_bool();
});
|
#![allow(unused_imports)]
#![allow(dead_code)]
use flatbuffers;
include!(concat!(env!("OUT_DIR"), "/gen/msg_generated.rs"));
|
#![allow(dead_code)]
extern crate openssl;
extern crate rustc_serialize;
use openssl::crypto::hash::Hasher;
use openssl::crypto::hash::Type;
use openssl::crypto::hmac::hmac;
use openssl::crypto::rsa::RSA;
use rustc_serialize::base64::{self, ToBase64, FromBase64};
use rustc_serialize::json::{self, ToJson, Json};
use... |
#![allow(dead_code)]
use cqrs::{Command as _, Version};
use cqrs_codegen::{Aggregate, Command};
#[derive(Aggregate, Default)]
#[aggregate(type = "aggregate")]
struct Aggregate {
id: i32,
}
#[test]
fn derives_for_struct() {
#[derive(Command)]
#[command(aggregate = "Aggregate")]
struct TestCommand {
... |
// stdlib
pub use std::fmt::{self, Display};
// dependencies
pub(crate) use {
neovim_lib::{self, Neovim, NeovimApi, Session},
prettytable::{format, Cell, Row, Table as PrettyTable},
reqwest::{self, blocking},
serde::Deserialize,
snafu::{ResultExt, Snafu},
};
// modules
pub(crate) use crate::error;
// struc... |
use serde::Deserialize;
use std::collections::HashMap;
use super::domain::{CommandStatus, Description, Explanation, Query, RequestInfo, Stream, Table};
/// The response type for any `CREATE` KSQL-DB Statement
#[derive(Clone, Debug, Deserialize)]
#[serde(rename_all(serialize = "snake_case", deserialize = "camelCase")... |
// Copyright 2019 WHTCORPS INC Project Authors. Licensed under Apache-2.0.
//! Concept:
//!
//! ```ignore
//! SELECT COUNT(1), COUNT(COL) FROM Block GROUP BY COL+1, COL2
//! ^^^^^ ^^^^^ : Aggregate Functions
//! ^ ^^^ ... |
use crate::error::ZResult;
use serde_json;
type ClientData = serde_json::Value;
pub trait ToClientData {
fn to_client_data(&self) -> ZResult<ClientData>;
fn update_from_client_data(&mut self, data: ClientData) -> ZResult<()>;
}
|
use std::net::Ipv4Addr;
use super::*;
pub struct Ipv4Frame<'a> {
header: &'a [u8],
opts: Option<&'a [u8]>,
payload: &'a [u8],
}
impl<'a> Ipv4Frame<'a> {
pub fn raw_header(&self) -> &'a [u8] {
self.header
}
pub fn ver(&self) -> u4 {
u4::new(self.header[0] >> 4)
}
pub ... |
impl Solution {
pub fn number_of_arithmetic_slices(nums: Vec<i32>) -> i32 {
if nums.len() < 3 {
return 0;
}
let mut ans = 0;
let mut diff = nums[1] - nums[0];
let mut cnt = 2;
for i in 2..nums.len() {
let tmp = nums[i] - nums[i-1];
... |
use std::ffi::CStr;
use std::str;
use grpcio_sys::*;
use super::server_context::ServerContext;
|
use dgraph::{make_dgraph, new_dgraph_client, new_secure_dgraph_client};
pub struct Certificates {
pub root_ca: Vec<u8>,
pub cert: Vec<u8>,
pub private_key: Vec<u8>,
}
pub fn make(url: &str, certs: Option<Certificates>) -> dgraph::Dgraph {
if certs.is_some() {
let certs = certs.expect("Should c... |
use core::time::Duration;
use crate::{
empty::Empty,
extent::{Extent, ToExtent},
timestamp::Timestamp,
};
pub trait Clock {
fn now(&self) -> Option<Timestamp>;
}
impl<'a, T: Clock + ?Sized> Clock for &'a T {
fn now(&self) -> Option<Timestamp> {
(**self).now()
}
}
impl<'a, T: Clock> C... |
use std::error::Error;
use std::fmt;
#[derive(Debug, Eq, Serialize, Deserialize, PartialEq, Copy, Clone, Hash)]
pub struct PacketType {
pub control_type: ControlType,
pub flags: u8,
}
#[repr(u8)]
#[derive(Debug, Eq, Serialize, Deserialize, PartialEq, Copy, Clone, Hash)]
pub enum ControlType {
/// Client r... |
pub struct Solution {}
impl Solution {
// Will TLE
// pub fn is_match(s: String, p: String) -> bool {
// let mut p_dedup = p.clone().into_bytes();
// p_dedup.dedup_by(|a, b| a == b && *a == b'*');
// return Self::_is_match(s.as_bytes(), &p_dedup[..]);
// }
// ... |
#![feature(await_macro, async_await, futures_api, pin)]
#[macro_use]
extern crate tokio;
use std::collections::HashMap as Map;
use structopt::StructOpt;
use tokio::prelude::*;
use tokio_serde_bincode::{ReadBincode, WriteBincode};
use tokio::codec;
mod command;
mod server;
use crate::command::{Command, Execution};
... |
use serenity::{
framework::{
standard::{
CommandResult,
macros::{
command,
},
},
},
http::AttachmentType,
model::channel::Message,
prelude::*,
};
use std::{
path::Path,
};
#[command]
#[description = "Ping-pong command to check... |
use indicatif::ProgressBar;
use reqwest::Client;
use slog::Logger;
#[derive(Clone)]
pub struct Mission {
pub progress: ProgressBar,
pub client: Client,
pub logger: Logger,
}
#[derive(Debug, Copy, Clone)]
pub struct SnapshotConfig {
pub concurrent_resolve: usize,
}
#[derive(Clone, Debug, PartialEq, Eq... |
#[doc = r"Register block"]
#[repr(C)]
pub struct RegisterBlock {
#[doc = "0x00 - Timer Channel Compare Register 1"]
pub comp1: COMP1,
#[doc = "0x02 - Timer Channel Compare Register 2"]
pub comp2: COMP2,
#[doc = "0x04 - Timer Channel Capture Register"]
pub capt: CAPT,
#[doc = "0x06 - Timer Ch... |
fn main() {
let mut a=3;
let mut b= 4;
a = a + b;
b = a - b;
a = a - b;
println!("The value of a after swapping: {}",a);
println!("The value of b after swapping: {}",b);
}
|
// https://doc.rust-lang.org/book/references-and-borrowing.html#&mut-references
fn f(x: &i32) {
}
fn main() {
let mut x: i32 = 1;
{
let mut y: &i32 = &mut x;
}
f(&x);
}
|
// vim: sts=4 sw=4 et
/*!
Lazy is a Lazily generated list, only iterable once, implementing Iterable.
It allows lazy generation by allowing generators to tack on thunks of closures
that are not called until the list is traversed to that point.
Uses a custom ~Thunk and ~Callable to allow movingi in and then mutat... |
mod prelu;
mod sigmoid;
|
// Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or
// http://apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or
// http://opensource.org/licenses/MIT>, at your option. This file may not be
// copied, modified, or distributed except according to those terms.
use once_cell::sync::Lazy... |
use actix_web::{error, web, FromRequest, HttpResponse, guard};
use std::sync::atomic::AtomicUsize;
use std::sync::Arc;
use actix_web::middleware::Logger;
use env_logger;
mod user;
use crate::user::{index,user,user_deserialize, user_deserialize_json};
use crate::user::{AppState,MyUserDeserialized};
mod middleware;
use... |
#![feature(if_let)]
#![feature(while_let)]
#![feature(globs)]
#![feature(box_syntax, box_patterns)]
// This feature is enabled to use `bench` feature, requires nigthly rust
#![feature(test)]
use std::io;
use std::ops::Deref;
use std::io::Write;
use reader::SexpReader;
use interpreter::Interpreter;
mod reader;
mod ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.