text stringlengths 8 4.13M |
|---|
use {CloudflareApi, Error, RedirectMap, Result};
use cloudflare;
use cloudflare::zones::dns;
use errors::RedirectError;
use rayon::prelude::*;
use rocket::State;
use reqwest;
use toml;
use std;
use std::collections::HashMap;
use std::fs::File;
use std::io::prelude::*;
use std::path::Path;
#[derive(Deserialize)]
stru... |
#[macro_use]
extern crate lazy_static;
#[macro_use]
extern crate serde_derive;
mod conf;
mod fmt;
mod human_date;
mod stats;
mod tml;
use std::env;
use std::path::Path;
use std::process::exit;
use std::str::FromStr;
use todo_lib::*;
type FnUpdateData = fn(tasks: &mut Vec<todotxt::Task>, ids: Option<&todo::IDVec>) -... |
use gw_common::H256;
use gw_types::{
bytes::Bytes,
offchain::RollupContext,
packed::{L2Transaction, Script},
};
use crate::error::LockAlgorithmError;
use super::LockAlgorithm;
#[derive(Debug, Default)]
pub struct AlwaysSuccess;
/// Usage
/// register AlwaysSuccess to AccountLockManage
///
/// manage.reg... |
use crate::handlers::dices;
use crate::utils;
use warp::Filter;
pub fn routes(
db: impl utils::DBConnection,
) -> impl Filter<Extract = impl warp::Reply, Error = warp::Rejection> + Clone {
roll(db.clone()).or(dice(db))
}
// GET /:id
fn dice(
db: impl utils::DBConnection,
) -> impl Filter<Extract = impl wa... |
extern crate euler;
fn main() {
let N = 4000000;
let mut f = (0, 1);
let mut sum = 0;
while f.0 <= N {
sum += f.0;
f = (f.0 + 2 * f.1, 2 * f.0 + 3 * f.1);
}
println!("{}", sum);
}
|
fn main() {
//let data = ["abcdef", "bababc", "abbcde", "abcccd", "aabcdd", "abcdee", "ababab"];
// let data = ["abcde", "fghij", "klmno", "pqrst", "fguij", "axcye", "wvxyz"];
let data = ["mphcuiszrnjzxwkbgdzqeoyxfa",
"mihcuisgrnjzxwkbgdtqeoylia",
"mphauisvrnjgxwkbgdtqeiylfa",
"mphcuisnrnjzxwkbgdgqeoylua",
"... |
mod winapipatch;
use self::winapipatch::*;
use crate::{SystrayError, SystrayEvent};
use std::{
self,
cell::RefCell,
ffi::OsStr,
os::windows::ffi::OsStrExt,
sync::mpsc::{channel, Sender},
thread,
};
use winapi::{
self,
ctypes::{c_ulong, c_ushort},
shared::{
basetsd::ULONG_PTR,... |
#[doc = "Register `LFRCOCTRL` reader"]
pub struct R(crate::R<LFRCOCTRL_SPEC>);
impl core::ops::Deref for R {
type Target = crate::R<LFRCOCTRL_SPEC>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl From<crate::R<LFRCOCTRL_SPEC>> for R {
#[inline(always)]
fn from(read... |
#[derive(Debug, PartialEq)]
pub enum Allergen {
Eggs = 0x1,
Peanuts = 0x2,
Shellfish = 0x4,
Strawberries = 0x8,
Tomatoes = 0x10,
Chocolate = 0x20,
Pollen = 0x40,
Cats = 0x80,
}
pub struct Allergies {
allergies: i32,
}
impl Allergies {
pub fn new(allergies: i32) -> Allergies {
... |
pub mod f1_2018;
use context::AppContext;
use pipeline::input::Tick;
pub trait ReceivePacket: Send + Sync + Clone {
fn new() -> Self;
fn converto_to_tick(&mut self, context: &'static AppContext, datagram: &[u8], size: usize) -> Option<Tick>;
}
pub fn get_serialiser() -> impl ReceivePacket {
// for now ha... |
// Copyright 2020 EinsteinDB Project Authors & WHTCORPS INC. Licensed under Apache-2.0.
mod gc_worker;
mod pessimistic_txn;
mod violetabftstore;
mod split_check;
|
use crate::rayt::*;
use rand::prelude::*;
use std::iter::FromIterator;
/// A 3-element array that is represented by double precision floating point components
#[derive(Debug, Copy, Clone, PartialEq)]
pub struct Float3([f64; 3]);
/// A 3-element color that is represented by r,g,b components
pub type Color = Float3;
/... |
use super::Token;
const SEPERATORS: [(char, Token); 16] = [
('(', Token::OpenParan),
(')', Token::CloseParan),
('[', Token::OpenSquareBrace),
(']', Token::CloseSquareBrace),
('{', Token::OpenCurlyBrace),
('}', Token::CloseCurlyBrace),
(';', Token::Semicolon),
('/', Token::Slash),
('... |
use std::convert::TryInto;
use nimiq_block::MacroHeader;
use nimiq_primitives::{coin::Coin, policy::Policy};
/// Parses the genesis supply and timestamp from the genesis block. We require both values to
/// calculate the block rewards.
pub fn genesis_parameters(genesis_block: &MacroHeader) -> (Coin, u64) {
let ex... |
struct Solution;
use std::cmp::Ordering::Less;
impl Solution {
fn split_looped_string(mut strs: Vec<String>) -> String {
let n = strs.len();
strs = strs
.into_iter()
.map(|s| {
let a = s.to_string();
let b = s.chars().rev().collect();
... |
//! Bindings to use a GPS chip, and to use it to extract packet metadata.
extern crate time;
use self::time::{Tm,now};
pub struct Data {}
pub fn Enable(_tty_path: String) -> bool {
return true;
}
pub fn Update() -> Result<Data, String> {
let res: Data = Data{};
return Ok(res);
}
pub fn PacketTime(_tim... |
use crate::args::Args;
use crate::errors::*;
use serde::Deserialize;
use std::fs;
use std::path::{Path, PathBuf};
const DEFAULT_URL: &str = "https://security.archlinux.org/all.json";
pub struct Config {
pub source: String,
pub proxy: Option<String>,
}
impl Config {
pub fn load(args: &Args) -> Result<Self... |
/// Video Ram size, 16 kb
const VIDEO_RAM_SIZE: usize = 0x8000;
/// Object Attribute Memory size, 160 bytes (4 bits per sprite at 40 sprites)
const VIDEO_OBJECT_ATTRIBUTE_MEMORY_SIZE: usize = 0xA0;
const WIDTH: usize = 160;
const HEIGHT: usize = 144;
#[derive(PartialEq, Copy, Clone)]
enum PrioType {
Color0,
... |
#![allow(nonstandard_style)]
// Generated from CSV.g4 by ANTLR 4.8
use super::csvparser::*;
use antlr_rust::token_factory::CommonTokenFactory;
use antlr_rust::tree::ParseTreeListener;
use std::any::Any;
pub trait CSVListener<'input>: ParseTreeListener<'input, CSVParserContextType> {
/**
* Enter a parse tree ... |
// This file is part of Substrate.
// Copyright (C) Parity Technologies (UK) Ltd.
// SPDX-License-Identifier: Apache-2.0
// 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.a... |
struct Solution;
enum Tok {
Op(char),
Val(i32),
}
impl Solution {
fn diff_ways_to_compute(input: String) -> Vec<i32> {
let mut val = 0;
let mut toks: Vec<Tok> = vec![];
for c in input.chars() {
match c {
'+' | '-' | '*' => {
toks.push... |
fn main() {
let elem = 5u8;
let mut vec = Vec::new(); // un typed at first
// the program fails to compile without the next line
vec.push(elem);
println!("{:?}", vec);
}
|
pub mod propfind;
pub use self::propfind::PropfindRequest;
pub enum DavRequest {
Propfind(PropfindRequest)
} |
#[allow(unused_imports)]
use tracing::{info, warn, debug, error, trace, instrument, span, Level};
use error_chain::bail;
use crate::plugin::*;
use crate::error::*;
use crate::event::*;
use crate::index::*;
use crate::validator::*;
use crate::transaction::*;
use std::sync::Arc;
use crate::spec::*;
use crate::lint::*;... |
ApBegin(RS,CLSID_MAPAPP)
WndBegin(MAP_WND_SELECT_CARD)
WdgBegin(CLSID_VTMSIMSELECTION,vtmSimSelect)
VtmCreateSimSelectionRC({IMG_NULL_ID,TXT_TTL_N_SIM})
WdgEnd(CLSID_VTMSIMSELECTION,vtmSimSelect)
WndEnd(MAP_WND_SELECT_CARD)
WndBegin(MAP_WND_LOGO)
WdgBegin(CLSID_VTMIMG,vt... |
#[doc = r"Register block"]
#[repr(C)]
pub struct RegisterBlock {
_reserved0: [u8; 0x0108],
#[doc = "0x108 - TXD byte sent and RXD byte received."]
pub events_ready: EVENTS_READY,
_reserved1: [u8; 0x01f8],
#[doc = "0x304 - Interrupt enable set register."]
pub intenset: INTENSET,
#[doc = "0x30... |
use std::path::Path;
use eyre::{Report, Result};
use futures::stream::TryStreamExt;
use reqwest::Client;
use tokio::{
fs::{self, File},
io::AsyncWriteExt,
};
pub async fn download(client: &Client, url: &str, file: impl AsRef<Path>) -> Result<()> {
let parent = file.as_ref().parent().unwrap();
fs::crea... |
// https://leetcode.com/problems/partition-list/
// Given the head of a linked list and a value x, partition it such that all nodes less than
// x come before nodes greater than or equal to x.
// You should preserve the original relative order of the nodes in each of the two partitions.
// Example 1:
// Input: head ... |
fn main() {
println!("{:?}", ring::rand::SystemRandom::new());
}
|
use std::path::PathBuf;
use super::{
ast::AstKind,
ast::AstNode,
ast::ClassMember,
expr_parser::ExprParser,
expression::{Expression, ExpressionKind},
interpreter::Program,
lexer::Lexer,
operator::Operator,
token::{calculate_range, Token, TokenKind},
};
use pratt::PrattParser;
use st... |
use std::any::Any;
use std::io::Result as IoResult;
use std::borrow::Cow;
use hyper::server::response::Response as HttpResponse;
use hyper::status::StatusCode;
use hyper::net::Fresh;
use hyper::header;
use hyper::header::Header;
use hyper::header::HeaderFormat;
use cookie::CookieJar;
/// The struct that holds inform... |
use std::cmp;
#[derive(Copy, Clone)]
pub struct Point {
pub x: u32,
pub y: u32,
pub size: u32,
}
impl Point {
pub fn move_up(&mut self) {
self.y -= 1;
}
pub fn move_down(&mut self) {
self.y += 1;
}
pub fn move_rihgt(&mut self) {
self.x += 1;
}
pub fn mov... |
//! Dex `Field` and supporting structures
use scroll::{ctx, Pread, Uleb128};
use crate::{
annotation::AnnotationSetItem,
class::ClassId,
encoded_item::{EncodedItem, EncodedItemArray},
encoded_value::EncodedValue,
error::Error,
jtype::{Type, TypeId},
string::{DexString, StringId},
ulong,... |
use crate::asm;
pub fn ret() -> Vec<asm::Instruction> {
vec![asm::Instruction::Rts, asm::Instruction::Nop]
}
|
mod server_state;
use bytes::buf::BufExt;
use hyper::service::{make_service_fn, service_fn};
use hyper::{header, Body, Method, Request, Response, Server, StatusCode};
use std::fmt;
use std::sync::{Arc, RwLock};
use server_state::ServerState;
use serde::{Deserialize, Serialize};
use lycan::shared::http::{
JoinGa... |
// [#protodoc-title: Socket Option ]
/// Generic socket option message. This would be used to set socket options that
/// might not exist in upstream kernels or precompiled Envoy binaries.
/// [#next-free-field: 7]
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct SocketOption {
/// An optional name to give... |
pub const ISDEPOSIT:&str = "";
|
/// Compute 1D FFT
pub fn fft1d(real: &[f32], img: &[f32], out_real: &mut [f32], out_img: &mut [f32], size: usize) {
let inv_size = 1.0 / size as f32;
// For the sum
struct ResultFFT {
pub real: f32,
pub img: f32,
}
impl std::iter::Sum for ResultFFT {
fn sum<I>(iter: I) -> S... |
#![forbid(unsafe_code)]
#![warn(clippy::dbg_macro)]
#![allow(clippy::cognitive_complexity)]
extern crate wain_ast;
pub mod ast;
pub mod compose;
pub mod lexer;
pub mod parser;
pub mod source;
pub mod wat2wasm;
use compose::{ComposeError, Composer};
use parser::{ParseError, Parser};
use source::TextSource;
use std::f... |
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct Timestamp {
year: u32,
month: u32,
day: u32,
hour: u32,
minute: u32,
second: u32,
millisecond: Option<u32>,
}
impl Timestamp {
pub fn new(year: &str, month: &str, day: &str, hour: &str, minute: &str, second: &str, millisecond: Option<&st... |
//! Uses the timer interrupt to blink a led with different frequencies.
//!
//! This assumes that a LED is connected to pc13 as is the case on the blue pill board.
//!
//! Note: Without additional hardware, PC13 should not be used to drive an LED, see page 5.1.2 of
//! the reference manual for an explanation. This is n... |
pub mod seo;
|
/// Configuration struct for parsing command line inputs
pub struct Config {
/// A .ray file as the scene input
pub ray_filename: String,
/// An output filename for our rendered scene
pub output_filename: String,
/// tuple representing output image dimensions
pub output_dimensions: (u32, u32),
}... |
// Make sure that the InnerReplyContext aborts on Drop if object is still
// queued.
use std::{thread, time};
use ump::{channel, Error};
#[test]
fn sync_expect_server_death() {
let (server, client) = channel::<String, String, ()>();
let server_thread = thread::spawn(move || {
// Should be doing something mor... |
use std::collections::HashMap;
use crate::*;
pub struct UserPool {
users: HashMap<PlayerID, Stream>,
player_pool: PlayerPool,
}
impl UserPool {
pub fn new() -> UserPool {
UserPool {
users: HashMap::new(),
player_pool: PlayerPool::new(),
}
}
pub fn add(&mut self, team: Team, stream: Stream) {
let pl... |
use yew::prelude::*;
use yew::services::fetch::{FetchService, FetchTask, Request, Response};
use yew::virtual_dom::vnode::VNode;
use anyhow::Result;
use web_sys::Node;
pub struct Model {
_link: ComponentLink<Self>,
_fetch_handle: FetchTask,
content: String,
}
pub enum Msg {
DidFetch(String),
Error,
}
fn html... |
#[cfg(feature="hsw")]
mod hsw;
#[cfg(feature="hsw")]
pub use self::hsw::{
GotoDgemm, GotoDgemm3Sub, GotoDgemm3,
ColPM, RowPM,
Dgemm3Sub, Dgemm3TmpWidth, Dgemm3TmpHeight,
Dgemm3,
};
|
use crate::formats::{Loader, Saver};
use crate::Image;
use crate::Pixel;
use std::convert::TryFrom;
use std::io::Write;
use std::io::{Cursor, Read};
use byteorder::{ReadBytesExt, WriteBytesExt, BE};
pub struct Farbfeld;
impl Loader for Farbfeld {
fn load(bytes: &[u8]) -> Image {
let mut rdr = Cursor::new... |
#![deny(clippy::all)]
mod chores;
mod entertainment;
mod logger;
mod ole_martin;
mod personal;
mod service;
use actix::{Actor, System};
use actix_web::{
middleware::{Middleware, Started},
server, FromRequest, HttpRequest, Result,
};
use actix_web_httpauth::extractors::{
basic::{BasicAuth, C... |
//! merkle-tree implement Merkle Tree in Rust.
//!
//! A disadvantage in current implementation is need to recalculate full tree when added
//! or removed element into/from tree. To increase performance we need to implement partial
//! tree modification when adding or removing element.
#![deny(missing_docs,
missing_de... |
/* Copyright (c) 2018 Garrett Berg, vitiral@gmail.com
*
* 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 ex... |
#![unstable]
//! Structs for WebSocket responses
use std::option::Option;
use std::num::FromPrimitive;
use hyper::status::StatusCode;
use hyper::version::HttpVersion;
use hyper::header::Headers;
use hyper::header::common::{Connection, Upgrade};
use hyper::header::connection::ConnectionOption;
use hyper::header::common:... |
use crate::http::HTTPRequestError;
use std::path::Path;
use std::{fmt, str};
/// A struct used to represent an HTTP request.
///
/// This struct is used to pass HTTP requests to the according request handling
/// functions (mainly [`handle_connection`]). It extracts information from a
/// [`std::net::TcpStream`] buffe... |
struct Solution;
impl Solution {
fn sort_array(mut nums: Vec<i32>) -> Vec<i32> {
nums.sort();
nums
}
}
#[test]
fn test() {
let nums = vec![5, 2, 3, 1];
let res = vec![1, 2, 3, 5];
assert_eq!(Solution::sort_array(nums), res);
let nums = vec![5, 1, 1, 2, 0, 0];
let res = vec!... |
#[cfg(test)]
mod test {
use crate::lexer::{Token, Lexer};
use pretty_assertions::assert_eq;
#[test]
fn read_char() {
let mut l = Lexer::new("()".to_owned());
assert_eq!(l.position, 0);
l.read_char();
assert_eq!(l.position, 1);
assert_eq!(l.read_position, 2);
... |
pub trait EscCode {
const OPCODE: u16;
fn args(&self) -> Vec<String> {
Vec::new()
}
fn attachments(&self) -> Vec<Vec<u8>> {
Vec::new()
}
fn encode(&self) -> String {
let mut string = format!("\x1b_[{:x}", Self::OPCODE);
for arg in self.args() {
str... |
use crate::coordinates::Coordinates;
//use std::collections::HashSet;
#[derive(PartialOrd, PartialEq, Default, Debug, Clone, Copy)]
/// a structure defining a the area pointed by a dynamic cell
pub struct Rectangle {
pub begin: Coordinates,
pub end: Coordinates,
}
impl Rectangle {
pub fn new() -> Rectang... |
use rand::Rng;
type Result<T> = std::result::Result<T, Error>;
#[derive(Debug)]
pub enum Error {
InvalidState(State),
}
/// Parameters for a betting game.
#[derive(Debug)]
pub struct Gamble {
pub player_id: u64,
pub prize: Prize,
pub game: Game,
state: State,
}
#[derive(Debug, Clone)]
pub enum P... |
//! Shareable mutable containers.
mod causal;
pub use self::causal::{CausalCell, CausalCheck};
|
pub(crate) mod janus;
|
use module::greet;
use rand::{rngs, Rng};
fn main() {
greet();
let x = rand::thread_rng().gen_range(0..100);
println!("random num = {}",x);
}
|
use web_sys::{MediaStream, MediaStreamConstraints};
#[derive(Clone, Debug)]
pub struct LocalMedia {
js_media_stream: MediaStream,
}
impl LocalMedia {
pub async fn new(constraints: MediaStreamConstraints) -> Self {
use wasm_bindgen::JsCast;
use wasm_bindgen_futures::JsFuture;
use web_sy... |
extern crate lib;
use std::io;
use std::io::BufRead;
use std::string::String;
fn main() {
let stdin = io::stdin();
// Read the lines from stdin.
let lines = stdin
.lock()
.lines()
.collect::<std::io::Result<Vec<String>>>()
.expect("Error reading lines: {}");
let coordina... |
use std::cmp::Ordering;
use anyhow::format_err;
use rand::Rng;
use rayon::slice::ParallelSliceMut;
use super::{HitRecord, Hittable};
use crate::aabb::{self, Aabb};
use crate::ray::Ray;
const MAX_SEQUENTIAL: usize = 250;
#[derive(Debug)]
enum Node {
Branch { left: Box<Bvh>, right: Box<Bvh> },
Leaf(Box<dyn Hi... |
// Copyright (c) 2017 Brandon Thomas <bt@brand.io>, <echelon@gmail.com>
//! ilda-player is a program that plays ILDA laser projection files on laser
//! projector DACs.
#![deny(missing_docs)]
#![deny(unreachable_patterns)]
#![deny(unused_extern_crates)]
#![deny(unused_imports)]
#![deny(unused_qualifications)]
extern... |
#[derive(Copy, Clone, Debug, PartialEq)]
pub enum Part {
Adjective,
Adverb,
Noun,
Verb,
}
pub fn parse_pos(pos: &str) -> Part {
match pos {
"a" => Part::Adjective,
"n" => Part::Noun,
"r" => Part::Adverb,
"v" => Part::Verb,
_ => panic!()
}
}
pub fn as_cha... |
//! Trivial graph format.
use failure::{Error, ResultExt, bail};
use lazy_static::lazy_static;
use regex::Regex;
use std::collections::HashMap;
use std::io;
use woven::{Data, DataResult, IoError, IoErrorKind};
/// Reader for trivial graph format.
pub struct Read {}
impl Read {
fn read_vertex(line: &str, labels: ... |
use glob::glob;
use std::env;
use std::fs::read_dir;
use std::fs::File;
use std::io::Write;
use std::path::{Path, PathBuf};
fn read_files_recursive(root: &str) -> Vec<(PathBuf, String)> {
glob(&format!("{}/**/*", root))
.expect("Failed to read glob pattern")
.filter_map(|item| {
let pat... |
use super::Cartridge;
use pia::Pia6532;
use tia::Tia1A;
// for flags register
const CARRY_MASK: u8 = 0x01;
const ZERO_RESULT_MASK: u8 = 0x02;
const INTERRUPT_DISABLE_MASK: u8 = 0x04;
const DECIMAL_MASK: u8 = 0x08;
const BREAK_COMMAND_MASK: u8 = 0x10;
const OVERFLOW_MASK: ... |
use blog::Post;
fn main() {
let mut post = Post::new();
post.add_text("I ate a salad for lunch today");
let pending = post.request_review();
let mut post = pending.reject();
post.add_text("\nI added that!");
let post = post.request_review();
let post = post.approve();
let post = p... |
use super::ParseResult;
use crate::core::parser::ast::*;
use crate::core::parser::file_span::FileSpan;
use nom::{
bytes::complete::{tag},
character::complete::{one_of, digit1},
sequence::{pair},
combinator::{opt, recognize, map},
number::complete::double,
ParseTo, do_parse, recognize, escaped, o... |
// Import from `core` instead of from `std` since we are in no-std mode
use core::result::Result;
// Import heap related library from `alloc`
// https://doc.rust-lang.org/alloc/index.html
//use alloc::{vec, vec::Vec};
// Import CKB syscalls and structures
// https://nervosnetwork.github.io/ckb-std/riscv64imac-unknown... |
pub fn binary_search(elements: Vec<i32>, element: i32) -> Result<usize, String> {
let high = elements.len() -1;
binary_search_aux(elements, element, 0, high)
}
fn binary_search_aux(elements: Vec<i32>, element: i32, low: usize, high: usize) -> Result<usize, String> {
if low > high {
return Err("not... |
// suffix arrays implementation
use std::{collections::HashMap,
convert::TryInto,
io::stdin};
fn main() {
let mut string: String = String::new();
stdin().read_line(&mut string).expect("Error.");
println!("{}", string);
string += "$";
println!("{}", string);
let n: u8 = stri... |
use std::fmt;
use super::Ops;
#[derive(Clone,PartialEq)]
pub struct Token{
pub token_type : TokenType,
pub line : u32,
pub column : u32,
pub value : String,
pub state : LexerState
}
impl Token{
fn create(token_type:TokenType, line : u32, column : u32, value : String, state : LexerState)->Se... |
use crate::behaviour::*;
use crate::board_message::*;
use crate::board_simulator::*;
use crate::event::*;
use crate::direction::*;
use zzt_file_format::*;
use crate::zzt_behaviours::monster_interactions::*;
#[derive(Debug, Clone)]
pub struct EmptyBehaviour;
impl Behaviour for EmptyBehaviour {
fn push(&self, _x: i1... |
// preprocessing any command
use errors::*;
use std::env;
use std::process::Command;
fn next_percent(s: &str) -> Option<(&str,&str,&str)> {
if let Some(startp) = s.find("%(") {
let before = &s[0..startp];
let after = &s[startp+2..]; // skip %(
let endp = after.find(')').expect("expected clo... |
/// For unshared devices, Healthy means the device is discoverable.
/// For shared devices, Healthy means the device is either unused or used by this node.
pub const HEALTHY: &str = "Healthy";
/// For unshared devices, Unhealthy means the device is not discoverable.
/// For shared devices, UnHealthy means that the dev... |
use crate::{Action, Agent, EpsilonGreedy, Position, Reward, World};
use rand::{self, Rng};
use std::collections::{HashMap, HashSet};
pub struct DynaQPlus {
pub world: World,
pub alpha: f64,
pub gamma: f64,
pub kappa: f64,
pub planning: u32,
pub _epsilon: f64,
step: u32,
latest: HashMap<... |
use actix_web::{web, HttpResponse, HttpRequest, Result, Error};
use serde::{Deserialize, Serialize};
#[derive(Serialize, Deserialize)]
struct StatusResponse {
status: String
}
pub fn play() -> Result<HttpResponse, Error> {
Ok(HttpResponse::Ok()
.json(StatusResponse { status: String::from("Ok") })
)
}
pub f... |
pub struct MinCostFlow {
g: Vec<Vec<Edge>>,
}
#[derive(Clone, Copy)]
struct Edge {
v: usize,
rev: usize,
cap: i32,
cost: i64,
}
impl MinCostFlow {
pub fn new(n: usize) -> Self {
Self {
g: vec![Vec::new(); n],
}
}
pub fn add_edge(&mut self, u: usize, v: usize, ... |
#![cfg(target_os = "android")]
#![allow(non_snake_case)]
use ethereum_types::Address;
use jni::objects::{JObject, JString};
use jni::sys::jstring;
use jni::JNIEnv;
use std::ffi::{CStr, CString};
#[no_mangle]
pub unsafe extern "C" fn Java_com_example_android_MainActivity_hello(
env: JNIEnv,
_: JObject,
j_r... |
pub mod default;
pub mod crazy;
pub mod painter;
pub fn _get_color_templates(s: &str) -> String {
match s {
"bash" => String::from("\x1B[{}]"),
"tcsh" => String::from("%%{\x1B%s%%}"),
"zsh" => String::from("%%{%%}"),
"bare" => String::from(""),
_ => String::from(""), ... |
use frame_support::{
dispatch::DispatchResult, ensure, storage::StorageDoubleMap, IterableStorageDoubleMap,
};
use opensquare_primitives::BountyId;
use ospallet_reputation::{
Behavior, BountyRemarkCollaborationResult, BountyResolveCollaborationResult, ReputationBuilder,
};
use crate::types::{BountyState, Hunt... |
//!
#![warn(missing_debug_implementations, missing_docs, rust_2018_idioms)]
use actix_web::{App, HttpServer};
use chrono::Utc;
#[allow(unused_imports)]
use log::{debug, error, info, trace, warn};
use uuid::Uuid;
use postgres::*;
mod config;
mod postgres;
mod status;
#[actix_web::main]
async fn main() -> std::io::Res... |
use crate::nes::cpu::{Cpu,FromImmediate,FromAddress,AddressMode};
pub struct Ora { }
impl Ora {
#[inline]
fn and(cpu: &mut Cpu, word: u8) {
let result = cpu.AC | word;
cpu.AC = result;
cpu.zero_and_negative_status(result);
}
}
impl FromImmediate for Ora {
fn from_immediate(cp... |
// Copyright 2020 EinsteinDB Project Authors & WHTCORPS INC. Licensed under Apache-2.0.
use error_code::{self, ErrorCode, ErrorCodeExt};
use openssl::error::ErrorStack as CrypterError;
use protobuf::ProtobufError;
use std::io::{Error as IoError, ErrorKind};
use std::{error, result};
/// The error type for encryption.... |
#[macro_use]
extern crate daas;
extern crate actix_web;
use actix_web::{web, App, HttpServer};
use daas::service::listener::{DaaSListener, DaaSListenerService};
use pbd::dtc::middleware::actix::*;
use pbd::dua::middleware::actix::*;
use actix_web::{FromRequest, HttpRequest};
use daas::errors::MissingAuthorError;
use ... |
use crate::helpers::{parse_hex_bytes, parse_u64};
use clap::ArgMatches;
use deposit_contract::{decode_eth1_tx_data, DEPOSIT_DATA_LEN};
use tree_hash::TreeHash;
use types::EthSpec;
pub fn run<T: EthSpec>(matches: &ArgMatches) -> Result<(), String> {
let rlp_bytes = parse_hex_bytes(matches, "deposit-data")?;
let... |
use std::borrow::Cow;
use crate::base::*;
use crate::math::*;
pub struct Text {
value: Cow<'static, str>,
style: Style,
}
#[derive(Clone)]
pub struct Style {
pub shader: Shader,
pub background: Shader,
pub font: Cow<'static, str>,
pub family: Cow<'static, str>,
pub size: Positive,
pub ... |
use super::expression::ExpressionNode;
use super::Node;
#[derive(Debug, PartialEq, Clone)]
pub struct DeclarationTrivia {
pub assign_prefix: String
}
impl DeclarationTrivia {
pub fn new() -> Self {
return DeclarationTrivia { assign_prefix: String::new() };
}
}
#[derive(Debug, PartialEq, Clone)]
p... |
use jinya_ui::layout::page::*;
use jinya_ui::listing::card::*;
use jinya_ui::widgets::floating_action_button::*;
use yew::prelude::*;
pub struct Cards {
link: ComponentLink<Self>,
}
pub enum Msg {
NoParam
}
impl Component for Cards {
type Message = Msg;
type Properties = ();
fn create(_props: Se... |
use crate::message::pty::{MainShutdown, PtyOptions, PtyRequest, PtyResponse, PtyShutdown};
use crate::prelude::*;
use super::pty::PtyService;
use lifeline::dyn_bus::DynBus;
use std::{
collections::{hash_map::DefaultHasher, HashMap},
hash::{Hash, Hasher},
path::PathBuf,
};
use tab_api::{
config::history... |
use crate::{
tag::{Item, Tag},
Path,
};
use annotate_snippets::display_list::{DisplayList, FormatOptions};
use annotate_snippets::snippet::{Annotation, AnnotationType, Slice, Snippet, SourceAnnotation};
pub type Result<T> = std::result::Result<T, Error>;
pub type CodeRef = (Path, (usize, usize));
#[derive(Cl... |
extern crate rug;
pub mod solutions;
|
//! TODO: Add documentation
#![cfg(windows)]
//#![warn(missing_docs)]
extern crate checked_enum;
extern crate com_wrapper;
extern crate math2d;
extern crate winapi;
extern crate wio;
#[macro_use]
mod helpers;
pub mod adapter;
pub mod descriptions;
pub mod device;
pub mod device_subobject;
pub mod enums;
pub mod fac... |
use std::io::*;
use util::Scanner;
use std::cmp::max;
#[derive(Clone)]
struct Node {
pub parent: Option<usize>,
pub left: Option<usize>,
pub right: Option<usize>,
}
fn calc_depth(a: &Vec<Node>, depths: &mut Vec<usize>, idx: usize, depth: usize) {
depths[idx] = depth;
if let Some(left) = a[idx].lef... |
#[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::LUT {
#[doc = r" Modifies the contents of the register"]
#[inline]
pub fn modify<F>(&self, f: F)
where
for<'w> F: FnOnce(&R, &'w mut W... |
use std::fs::{File, OpenOptions};
use std::io::Write;
use std::path::{Path, PathBuf};
use serde_json::{Deserializer, Value};
use tempfile::NamedTempFile;
use crate::index_controller::dump_actor::compat::{self, v2, v3};
use crate::index_controller::dump_actor::Metadata;
use crate::options::IndexerOpts;
/// The dump v... |
extern crate clang;
use clang::*;
use std::path::PathBuf;
pub fn gen_clang() -> Clang {
// Acquire an instance of `Clang`
let clang = Clang::new().unwrap();
return clang;
}
pub fn check_structs<S: AsRef<str>>(clang: &Clang, f: impl Into<PathBuf>, args: &[S]) {
// Create a new `Index`
let index ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.