text stringlengths 8 4.13M |
|---|
use crate::Result;
use crossterm::{
event::{poll, read, Event, KeyCode, KeyEvent},
terminal,
};
use std::time::Duration;
pub struct Keyboard {
// Key(0-F) pressed status
key: [bool; 16],
}
impl Keyboard {
pub fn new() -> Result<Self> {
// For keyboard events to work properly
termin... |
//! Building blocks of SQL statements.
//!
//! [`Expr`] representing the primitive building block in the expressions.
//!
//! [`SimpleExpr`] is the expression common among select fields, where clauses and many other places.
use crate::{func::*, query::*, types::*, value::*};
/// Helper to build a [`SimpleExpr`].
#[de... |
#![feature(proc_macro_hygiene, decl_macro)]
#![feature(trait_alias)]
#[macro_use]
extern crate rocket_contrib;
#[macro_use]
extern crate rocket;
mod event_listener;
mod server;
pub use common::Result;
pub(crate) use event_listener::{
DBAddEvent, DBDeleteEvent, DBUpdateEvent, ScannerCloseEvent, ScannerOpenEvent,
... |
#![deny(missing_docs)]
//! A pure-Rust lowlevel library for controlling wpasupplicant remotely
//!
//! Note that in order to connect to wpasupplicant, you may need
//! elevated permissions (eg run as root)
//!
//! # Example
//!
//! ```
//! let mut wpa = wpactrl::WpaCtrl::new().open().unwrap();
//! println!("{}", wpa.re... |
#[doc = "Reader of register CMP1_SW_CLEAR"]
pub type R = crate::R<u32, super::CMP1_SW_CLEAR>;
#[doc = "Writer for register CMP1_SW_CLEAR"]
pub type W = crate::W<u32, super::CMP1_SW_CLEAR>;
#[doc = "Register CMP1_SW_CLEAR `reset()`'s with value 0"]
impl crate::ResetValue for super::CMP1_SW_CLEAR {
type Type = u32;
... |
fn _circle_sort<T: PartialOrd>(a: &mut [T], low: usize, high: usize, swaps: usize) -> usize {
if low == high {
return swaps;
}
let mut lo = low;
let mut hi = high;
let mid = (hi - lo) / 2;
let mut s = swaps;
while lo < hi {
if a[lo] > a[hi] {
a.swap(lo, hi);
... |
/// EditReactionOption contain the reaction type
#[derive(Debug, Default, Clone, Serialize, Deserialize)]
pub struct EditReactionOption {
pub content: Option<String>,
}
impl EditReactionOption {
/// Create a builder for this object.
#[inline]
pub fn builder() -> EditReactionOptionBuilder {
Edi... |
#[cfg(feature = "extended-siginfo-raw")]
fn main() {
cc::Build::new()
.file("src/low_level/extract.c")
.compile("extract");
}
#[cfg(not(feature = "extended-siginfo-raw"))]
fn main() {}
|
use futures::{FutureExt, StreamExt};
use tokio::sync::mpsc;
use warp::ws::{Message, WebSocket};
use uuid::Uuid;
use warp::{http::Method, Filter, hyper::{StatusCode, Response}};
mod redis_wrapper;
mod topics;
mod common;
mod api_handler;
use common::types::{
BroadcastMessage,
Register,
Users
};
use api_h... |
use embedded_websocket::{
framer::{Framer, FramerError},
WebSocketCloseStatusCode, WebSocketOptions, WebSocketSendMessageType,
};
use std::net::TcpStream;
use thiserror::Error;
extern crate native_tls;
use native_tls::TlsConnector;
extern crate ctrlc;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sy... |
mod cylinder_pivot;
mod eject_animation;
mod frame_id;
mod hide_body;
mod late_init;
mod player_input;
mod player_pitch;
mod player_position;
mod player_yaw;
mod revolver_chamber;
mod revolver_cylinder;
mod revolver_hammer;
pub use self::cylinder_pivot::CylinderPivotSystem;
pub use self::eject_animation::EjectAnimatio... |
use ckb_logger::error;
use crossbeam_channel::Sender;
use futures::sync::oneshot;
use parking_lot::Mutex;
use std::sync::Arc;
use std::thread::JoinHandle;
#[derive(Debug)]
pub enum SignalSender {
Future(oneshot::Sender<()>),
Crossbeam(Sender<()>),
}
impl SignalSender {
pub fn send(self) {
match se... |
use serde::{Deserialize, Serialize};
#[derive(Serialize, Deserialize)]
pub struct State {
ppu_dma_request: Option<u16>,
dmc_dma_request: Option<u16>,
dmc_dma_halt_cycle: u8,
}
impl State {
pub fn new() -> Self {
State {
ppu_dma_request: None,
dmc_dma_request: None,
... |
use crate::custom_types::bytes::LangBytes;
use crate::custom_types::exceptions::io_error;
use crate::custom_var::downcast_var;
use crate::function::{Function, NativeFunction};
use crate::runtime::Runtime;
use crate::string_var::StringVar;
use crate::sys::os::os_name;
use crate::variable::{FnResult, Variable};
use files... |
//! LLVM bindings for Rust
//!
//! # Generating an basic program
//! ```
//! extern crate hllvm;
//!
//! use hllvm::{ir, target, support};
//!
//! fn build_module(context: &ir::Context) -> ir::Module {
//! let mut module = ir::Module::new("mymodule", context);
//!
//! let int8 = ir::IntegerType::new(8, &context... |
use std::fs;
use std::fs::File;
use std::io::Write;
use std::collections::HashMap;
use std::fmt;
use anyhow::Result;
use serde_derive::{Serialize, Deserialize};
use std::path::{Path, PathBuf};
use irc::client::data::Config as IrcConfig;
use directories::{ProjectDirs, BaseDirs};
#[derive(Debug, Deserialize, Default)]
p... |
#[cfg(test)]
mod buffer_tests {
#[test]
fn it_counts_points_in_buffer() {
use std::fs::File;
use std::io::prelude::*;
let mut f = File::open("../data/building.laz").unwrap();
let mut buffer = Vec::new();
f.read_to_end(&mut buffer).unwrap();
laszip::load_laszip_l... |
use futures::executor::block_on;
use gumdrop::Options;
use linereader::LineReader;
use solana_client::rpc_client::RpcClient;
use solana_sdk::{account::ReadableAccount, message::Message, program_pack::Pack};
use solana_transaction_status::{TransactionConfirmationStatus, UiTransactionEncoding};
use spl_token::state::Mint... |
#[macro_export]
macro_rules! chef_json_type {
// A simple type that allows us to use serde's Default implementation.
// FIXME: revisit when https://github.com/serde-rs/serde/issues/90 gets fixed
($id:ident, $val:expr) => {
#[derive(Debug,Clone,Serialize,Deserialize)]
struct $id(String);
... |
use std::env;
use std::process::exit;
use std::io;
use std::error::Error;
use std::time::Instant;
use std::rc::Rc;
use std::cell::RefCell;
use monkey::repl;
use monkey::parser::parse;
use monkey::compiler::Compiler;
use monkey::vm::VM;
use monkey::object::Environment;
use monkey::evaluator::eval;
const HELP: &str = "r... |
// base64.rs
use std::vec;
// TODO: doc
pub enum Base64Type {
Standard,
UrlSafe,
}
impl Base64Type {
// TODO: doc
pub fn encode(self, src: &[u8]) -> ~[u8] {
encode(src, self)
}
// TODO: doc
pub fn decode(self, src: &[u8]) -> ~[u8] {
decode(src, self)
}
// TODO: doc... |
use std::time::Duration;
use std::thread::sleep;
use std::sync::Arc;
use std::sync::atomic::{AtomicU64, Ordering};
#[derive(Clone)]
pub struct Delay {
time: Duration,
serial: Arc<AtomicU64>,
}
impl Delay {
pub fn new(time: Duration) -> Self {
Self {
time,
serial: Arc::ne... |
pub use std::num::{NonZeroU64, NonZeroUsize};
use std::str::FromStr;
pub use chrono::{Duration, NaiveDate as Date, NaiveDateTime as DateTime, NaiveTime as Time, Timelike};
use derive_more::{Add, AddAssign, Sub, SubAssign, Sum};
pub use rand::{Rng, rngs::StdRng, SeedableRng};
use crate::utils::ExpectWith;
#[derive(De... |
use std::f64::consts::E;
mod neuronMod {
#[derive(Debug, Copy, Clone)]
pub struct Unit {
pub value: f64,
pub gradient: f64,
}
impl Unit {
pub fn empty() -> Unit {
return Unit {value: 0f64, gradient: 0.0};
}
pub fn new(value: f64, gradient: f64) -> Unit {
return Unit { value: valu... |
#[doc = "Register `HWCFGR2` reader"]
pub type R = crate::R<HWCFGR2_SPEC>;
#[doc = "Field `EVENT_TRG` reader - HW configuration event trigger type"]
pub type EVENT_TRG_R = crate::FieldReader<u32>;
impl R {
#[doc = "Bits 0:31 - HW configuration event trigger type"]
#[inline(always)]
pub fn event_trg(&self) ->... |
//! One plugin which sets everything up for the whole game.
use crate::event;
use crate::resource;
use crate::system;
use bevy::prelude::*;
use bevy_mod_picking;
/// One plugin which sets everything up for the whole game.
pub struct GamePlugin;
impl Plugin for GamePlugin {
fn build(&self, app: &mut AppBuilder) {
... |
use crate::cache::StoreCache;
use crate::{
COLUMN_BLOCK_BODY, COLUMN_BLOCK_EPOCH, COLUMN_BLOCK_EXT, COLUMN_BLOCK_HEADER,
COLUMN_BLOCK_PROPOSAL_IDS, COLUMN_BLOCK_UNCLE, COLUMN_CELL_SET, COLUMN_EPOCH, COLUMN_INDEX,
COLUMN_META, COLUMN_TRANSACTION_INFO, COLUMN_UNCLES, META_CURRENT_EPOCH_KEY,
META_TIP_HEADE... |
use super::*;
impl<T> CachedTreeHashSubTree<Vec<T>> for Vec<T>
where
T: CachedTreeHashSubTree<T> + TreeHash,
{
fn new_tree_hash_cache(&self) -> Result<TreeHashCache, Error> {
match T::tree_hash_type() {
TreeHashType::Basic => {
TreeHashCache::from_bytes(merkleize(get_packed_... |
extern crate arrayfire as af;
extern crate nalgebra as na;
extern crate itertools;
extern crate rand;
extern crate csv;
extern crate num;
extern crate statistical;
extern crate rustc_serialize;
pub use layer::{Layer};
pub mod layer;
pub use model::{Model};
pub mod model;
pub use optimizer::{Optimizer};
pub mod optim... |
use crate::grammar::tracing::TraceInfo;
// FIXME: link
/// Parser input represents any type that can be passed as an input to a
/// wright parser. The one used internally for formally parsing wright source code
/// is the [Fragment type](), however this trait is also implemented for other nom
/// parser input types, n... |
use luminance_front::shader::Uniform;
use glfw::{Action, Context as _, Key, WindowEvent};
use luminance_front::context::GraphicsContext;
use luminance::pipeline::PipelineState;
use luminance_glfw::GlfwSurface;
use luminance_windowing::{WindowDim, WindowOpt};
use luminance_derive::{Semantics, Vertex, UniformInterface};
... |
mod functions;
use functions::format_and_trim;
use std::env::var;
use std::io::{Read, stdin, stdout, Write};
use std::path::Path;
fn add(raw_config_dir: &str, program: String) {
let mut cfgpath = String::new();
print!("\nPlease input the path to the config: ");
stdout().flush().unwrap();
stdin()
... |
pub struct ConstFnvHash(u64);
impl ConstFnvHash {
pub const fn new() -> Self {
Self(0xcbf29ce484222325)
}
pub const fn push_string(self, str: &str) -> Self {
self.update(str.as_bytes()).update(&[0xff])
}
pub const fn update(self, bytes: &[u8]) -> Self {
let Self(mut hash) ... |
// Copyright 2019 Google LLC
//
// 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 in ... |
/*!
```rudra-poc
[target]
crate = "async-coap"
version = "0.1.0"
[[target.peer]]
crate = "crossbeam-utils"
version = "0.8.0"
[test]
cargo_toolchain = "nightly"
[report]
issue_url = "https://github.com/google/rust-async-coap/issues/33"
issue_date = 2020-12-08
rustsec_url = "https://github.com/RustSec/advisory-db/pull... |
#[doc = "Reader of register IC_STATUS"]
pub type R = crate::R<u32, super::IC_STATUS>;
#[doc = "Slave FSM Activity Status. When the Slave Finite State Machine (FSM) is not in the IDLE state, this bit is set. - 0: Slave FSM is in IDLE state so the Slave part of DW_apb_i2c is not Active - 1: Slave FSM is not in IDLE state... |
// Copyright 2019 Cargill Incorporated
//
// 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 agre... |
// Copyright (c) 2017-present PyO3 Project and Contributors
//
// based on Daniel Grunwald's https://github.com/dgrunwald/rust-cpython
use crate::err::{self, PyDowncastError, PyErr, PyResult};
use crate::gil::{self, GILGuard, GILPool};
use crate::type_object::{PyTypeInfo, PyTypeObject};
use crate::types::{PyAny, PyDic... |
/*
* Datadog API V1 Collection
*
* Collection of all Datadog Public endpoints.
*
* The version of the OpenAPI document: 1.0
* Contact: support@datadoghq.com
* Generated by: https://openapi-generator.tech
*/
/// HeatMapWidgetRequest : Updated heat map widget.
#[derive(Clone, Debug, PartialEq, Serialize, Dese... |
use std::vec::IntoIter;
use anyhow::{Context, Result};
use stark_hash::StarkHash;
use web3::types::U256;
use crate::{
core::{ClassHash, ContractAddress, StorageAddress, StorageValue},
ethereum::state_update::{ContractUpdate, DeployedContract, StateUpdate, StorageUpdate},
};
/// Utility to parse StarkNet memo... |
fn main() {
// By defaults int's are 32 bit in Rust
let x = 5;
// By default variables are immutable in rust
// This gives you to write your code in a way that takes advantage of the safety and easy concurrency that Rust offers
println!("The value of x is {}", x);
// This is invalid as x is i... |
#[derive(Copy, Clone, PartialEq)]
pub enum Name {
King,
Queen,
Rook,
Bishop,
Knight,
Pawn,
}
impl Name {
pub fn all() -> Vec<Name> {
return vec![
Name::King,
Name::Queen,
Name::Rook,
Name::Bishop,
Name::Knight,
Name::Pawn,
];
}
}
|
use raw_window_handle::HasRawWindowHandle;
use crate::{Renderer, Texture, TextureFormat};
pub trait RenderTarget: Sync + Send {
fn size(&self) -> (u32, u32);
fn color_attachment(&self) -> &wgpu::TextureView;
fn depth_attachment(&self) -> &wgpu::TextureView;
fn submit(&mut self);
}
pub struct WindowRe... |
use std::io::{self};
fn main() {
let mut line = String::new();
io::stdin().read_line(&mut line).unwrap();
print!("{}", calc(line.as_str()));
}
fn calc(input: &str) -> &str {w
return judge(product(input));
}
fn product(input: &str) -> i32 {
let vec: Vec<&str> = input.trim_end_matches('\n').split("... |
use crate::lexing::token::{Keyword, Token};
use crate::{IntegerMachineType, RealMachineType};
use anyhow::{bail, Context};
use std::str::FromStr;
pub struct Lexer {
text: Vec<char>,
pos: usize,
current_char: Option<char>,
}
impl Lexer {
pub fn new(text: &str) -> Lexer {
Lexer {
tex... |
#![allow(unused)]
#![cfg_attr(not(feature="std"), no_std)]
#![feature(asm, structural_match, read_initializer)]
#[macro_use]
#[allow(unused_imports)]
extern crate linux_macros;
extern crate alloc;
#[macro_use]
mod macros;
pub mod util;
pub mod kty;
pub mod syscall;
pub mod fd;
//pub mod lock;
pub mod result;
pub mo... |
#![forbid(unsafe_code)]
mod ringlist;
use self::ringlist::Id as RingListId;
use self::ringlist::Insertion as RingListInsertion;
use self::ringlist::RingList;
use std::collections::HashMap;
use std::time::Instant;
pub struct LruCache<V> {
list: RingList<String>,
map: HashMap<String, Entry<V>>,
}
struct Entry... |
use std::io::{Read, Result, stdin};
use pulldown_cmark::{Parser, Event, Tag};
use comrak::{parse_document, Arena, ComrakOptions};
/* Prints the first (h1) title of a markdown document */
#[derive(Debug)]
enum RunMode {
Title,
Dump
}
fn main() -> Result<()> {
let query_str = std::env::args().nth(1).unwra... |
// main.rs
// loads a module from a nested directory structure
// compile using "rustc anothermain.rs -L ./libmodules/"
#[path = "modules/anotherworld.rs"]
mod anotherworld;
fn main() {
use anotherworld::anotherearth::anotherexplore;
use anothertrek = anotherworld::anotherearth::anotherexplore;
io::println(~"he... |
use crate::embeds::Author;
use rosu_v2::prelude::{GameMode, User};
use std::{borrow::Cow, collections::BTreeMap, fmt::Write};
pub struct OsuStatsCountsEmbed {
description: String,
thumbnail: String,
title: String,
author: Author,
}
impl OsuStatsCountsEmbed {
pub fn new(user: User, mode: GameMode,... |
use tokio::sync::watch;
/// Handle to a worker. Once all handles have been dropped, the worker
/// will stop waiting for new requests.
#[derive(Debug, Clone)]
pub(crate) struct WorkerHandle {
_receiver: watch::Receiver<()>,
}
impl WorkerHandle {
#[cfg(test)]
pub(crate) fn new_mocked() -> Self {
le... |
//! Processing a Series of Items with [Iterators]
//!
//! [iterators]: https://doc.rust-lang.org/book/ch13-02-iterators.html
use std::error::Error;
fn main() -> Result<(), Box<dyn Error>> {
let v = vec![1i32, 2, 3];
let mut i = v.iter();
assert_eq!(Some(&1i32), i.next());
assert_eq!(Some(&2i32), i.nex... |
use std::str;
use std::fmt;
use crate::io::Char;
use crate::error::Error;
pub enum Token {
Letter {
value: u8,
row: u32,
start: u16,
end: u16,
},
Number {
value: [u8; 20],
len: usize,
row: u32,
start: u16,
end: u16,
},
}
impl fmt:... |
use super::*;
use super::bytecode::{Op, OpIterator};
pub struct DataSection<'a> {
pub count: u32,
pub entries_raw: &'a [u8],
}
pub struct DataEntryIterator<'a> {
count: u32,
opiter: Option<OpIterator<'a>>,
iter: &'a [u8]
}
pub enum DataEntry<'a> {
Index(u32),
Op(Op<'a>),
Data(&'a [u8]... |
#![doc = "generated by AutoRust 0.1.0"]
#![allow(unused_mut)]
#![allow(unused_variables)]
#![allow(unused_imports)]
use super::{models, API_VERSION};
#[non_exhaustive]
#[derive(Debug, thiserror :: Error)]
#[allow(non_camel_case_types)]
pub enum Error {
#[error(transparent)]
Operations_List(#[from] operations::l... |
// id number A unique number used to identify and reference
// a specific image.
// name string The display name of the image. This is shown in
// the web UI and is generally a descriptive title for the image in question.
// type string The kind of image, describing ... |
// 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.
#![allow(dead_code)]
use failure;
use fidl_mlme;
use futures::prelude::*;
use std::{io, thread, time};
use std::fs::File;
use std::path::{Path, PathBuf};
... |
use std::error::Error;
use std::fmt::{self, Display, Formatter};
use std::iter::Peekable;
use crate::lexer::{Span, Token};
#[derive(Debug)]
pub enum ParseError {
InvalidNumberFormat(Span, String),
MismatchedClosingBrace(Span),
UnexpectedEndOfInput,
}
impl Display for ParseError {
fn fmt(&self, f: &mu... |
use core::marker::PhantomData;
use super::{decoder::*, encoder::*, *};
/// Subscribe topic.
///
/// [Subscribe] packets contain a `Vec` of those.
///
/// [Subscribe]: struct.Subscribe.html
#[derive(Debug, Clone, PartialEq)]
pub struct SubscribeTopic<'a> {
pub topic_path: &'a str,
pub qos: QoS,
}
impl<'a> Fro... |
use std::future::Future;
use tari_comms::pipeline::PipelineError;
/// Checks a request
pub trait Predicate<Request> {
/// The future returned by `check`.
type Future: Future<Output = Result<(), PipelineError>>;
/// Check whether the given request should be forwarded.
///
/// If the future resolves... |
// Copyright 2013 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 ... |
use super::super::super::super::{btn, contextmenu};
use super::state;
use super::Msg;
use crate::color_system;
use kagura::prelude::*;
pub fn render(z_index: u64, contextmenu: &state::contextmenu::State) -> Html {
contextmenu::div(
z_index,
|| Msg::CloseContextmenu,
contextmenu.grobal_posit... |
// Copyright 2019 The Grin Developers
//
// 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 agree... |
mod action;
mod animation;
mod setup;
pub use action::action;
pub use animation::animation;
pub use setup::setup;
|
/*
* Utility functions to convert camel case to snake case and inverse
*/
/**
* converts lower case camel case to lower case snake case
*/
pub fn lcamel_to_lsnake(txt:&str) -> String {
let mut buf:String = String::new();
for c in txt.chars() {
if c.is_uppercase() {
buf.push('_');
for c2 in c.to_lo... |
pub mod ball_ai;
pub mod zombie_ai;
pub mod player;
pub mod game;
pub mod controls; |
mod mock_waker;
use mock_waker::MockWaker;
use waitlist::*;
fn wait_for_waker<'a>(wl: &'a Waitlist, w: &MockWaker) -> WaitHandle<'a> {
let mut handle = wl.wait();
handle.set_context(&w.to_context());
handle
}
fn add_all<'a>(wl: &'a Waitlist, wakers: &[MockWaker]) -> Vec<WaitHandle<'a>> {
wakers.iter(... |
//! A module of functions and structures to help with the ArrayFire Rust Bindings.
use af::*;
use slog::*;
use std::ops::Deref;
// We specify Arrays here, though Seq could be used to index, because
// we rearely use seq to index.
/// The IndexBuilder allows for a more robust creation of Indexers.
///
/// # Usage
//... |
// Copyright 2019, 2020 Wingchain
//
// 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... |
pub enum ScaleMode {
Fixed(f64, f64),
Variable,
}
pub struct Program {
pub data:Vec<f64>,
pub title:Option<String>,
pub scale:ScaleMode,
}
pub type Extremes = (f64, f64);
pub struct Frame<'a> {
pub rows: i32,
pub cols: i32,
pub visible_data:&'a[f64],
pub extremes:Extremes,
}
|
use std::fs::File;
use std::io::{Read, Write};
use std::sync::mpsc::{self, Receiver};
use std::thread;
use std::mem;
const SP: u8 = b'\t';
const NL: u8 = b'\n';
const COL: u32 = 3;
const BUF_SIZE: usize = 4096 * 16;
fn writer(rx: Receiver<Vec<u8>>) {
let mut wf = File::create("generifs_text.py").expect("couldn't ... |
use async_trait::async_trait;
use common::result::Result;
use crate::domain::reader::{Reader, ReaderId};
#[async_trait]
pub trait ReaderRepository: Sync + Send {
async fn next_id(&self) -> Result<ReaderId>;
async fn find_by_id(&self, id: &ReaderId) -> Result<Reader>;
async fn save(&self, reader: &mut R... |
#[macro_use]
extern crate serde_derive;
mod database;
mod handlers;
mod models;
use crate::database::Database;
use crate::handlers::*;
use crate::models::*;
use iron::{prelude::Chain, Iron};
use logger::Logger;
use router::Router;
use uuid::Uuid;
fn main() {
env_logger::init();
let (logger_before, logger_a... |
use std::{cell::RefCell, rc::Rc};
use cookie::{Cookie, CookieJar};
use reqwest::{header::HeaderMap, Client, Method, Response, Url};
use scraper::Html;
use serde::Serialize;
use tracing::{debug, info, warn};
use crate::{
errors::AuthError,
utils::{dump_cookies_by_domain, retrieve_header_location},
web_hand... |
fn code_at(row: i128, col: i128) -> i128 {
let mut diagonal = 2;
let mut last = 20_151_125;
loop {
let mut r = diagonal;
let mut c = 1;
while c <= diagonal {
last = (last * 252_533) % 33_554_393;
if r == row && c == col {
return last;
... |
use common::ids::{ContainerId, TransactionId};
use common::storage_trait::StorageTrait;
use common::table::Table;
use common::{CrustyError, DataType, Field, Tuple};
use std::fs::File;
use memstore::storage_manager::StorageManager;
/// Function to import csv data into an existing table within a database.
///
/// Note:... |
use thiserror::Error;
use crate::unity::LocalizationError;
#[derive(Error, Debug)]
pub enum ParseComponentError {
#[error("unsupported component: {0}")]
Unsupported(String),
#[error("unsupported component category: {0}")]
UnsupportedCategory(String),
#[error("unsupported locale")]
UnsupportedLo... |
//! The definition of session backends
mod cookie;
mod redis;
pub use self::cookie::CookieBackend;
#[cfg(feature = "use-redis")]
pub use self::redis::RedisBackend;
|
// Copyright 2014-2018 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution.
//
// 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>,... |
use std::rc::Rc;
use hex2d::{Coordinate, ToCoordinate};
use game::Unit;
#[derive(RustcEncodable, Clone)]
pub struct Board {
pub width: usize,
pub height: usize,
cells: Rc<Vec<Vec<bool>>>
}
impl Board {
pub fn new<I>(width: usize, height: usize, filled: I) -> Board
where I: Iterator<Item=(i32, ... |
// Copyright (c) 2021 slog-try 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,
... |
use core::fmt;
use core::marker::PhantomData;
use core::mem;
use conquer_pointer::MarkedPtr;
use crate::traits::Reclaim;
use crate::{Owned, Protected, Shared};
////////////////////////////////////////////////////////////////////////////////////////////////////
// Storable
////////////////////////////////////////////... |
use std::ffi::c_void;
use std::mem;
use std::ptr;
use ash::prelude::VkResult;
use ash::version::DeviceV1_0;
use ash::{self, vk};
use super::buffer::BufferWrapper;
use super::error::VulkanError;
use super::util;
pub struct PixelImage {
pub image: vk::Image,
pub image_memory: vk::DeviceMemory,
pub view: vk... |
use std::borrow::Cow;
use ::ffi;
use ::ffi::*;
use traits::{Named, FromRaw};
pub struct Camera<'a> {
raw: &'a ffi::AiCamera
}
impl<'a> FromRaw<'a, Camera<'a>> for Camera<'a> {
type Raw = *const ffi::AiCamera;
#[inline(always)]
fn from_raw(raw: &'a Self::Raw) -> Camera<'a> {
Camera { raw: un... |
extern crate postgres;
use postgres::{Connection, Error};
pub struct Rates<'a> {
conn: &'a Connection,
}
#[derive(Debug)]
pub struct Pair {
pub symbol: String,
pub id: i32,
}
impl<'a> Rates<'a> {
pub fn new(conn: &Connection) -> Rates {
Rates{conn}
}
pub fn get_save_pair(&self, symb... |
use crate::impl_bytes_primitive;
impl_bytes_primitive!(TransactionId, 32);
|
use crate::{load_data, CorrectionData, EmuError};
use serde::{Deserialize, Serialize};
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CorrectionDataSet {
data: Vec<CorrectionData>,
}
impl Default for CorrectionDataSet {
fn default() -> Self {
CorrectionDataSet::new()
}
}
impl From<Vec... |
use std::fmt::{self, Display, Formatter};
use std::path::PathBuf;
use std::net::SocketAddr;
#[derive(Clone)]
pub enum CommonAddr {
SocketAddr(SocketAddr),
DomainName(String, u16),
#[cfg(unix)]
UnixSocketPath(PathBuf),
}
impl Display for CommonAddr {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Res... |
use crate::log_core::LogShape;
use std::fmt::Arguments;
use std::io::Write;
use std::io;
#[allow(non_camel_case_types)]
#[derive(Debug, Clone)]
pub enum cluShape {}
impl LogShape for cluShape {
#[inline(always)]
fn warning<'a, W: Write>(mut write: W, display: Arguments<'a>) -> io::Result<()> {
write.write_fmt( ... |
//! This crate provides basic access to a ps2 mouse in x86 environments.
#![no_std]
#![warn(missing_docs)]
#![feature(const_fn_fn_ptr_basics)]
use bitflags::bitflags;
use x86_64::instructions::port::Port;
const ADDRESS_PORT_ADDRESS: u16 = 0x64;
const DATA_PORT_ADDRESS: u16 = 0x60;
const GET_STATUS_BYTE: u8 = 0x20;
c... |
use crate::day_18_parser as parser;
pub fn evaluate(node: parser::Node) -> i64 {
match node {
parser::Node::Number(num) => num,
parser::Node::OpAdd(left, right) => evaluate(*left) + evaluate(*right),
parser::Node::OpMul(left, right) => evaluate(*left) * evaluate(*right),
}
}
|
// Copyright 2019-2020 Parity Technologies (UK) Ltd.
// This file is part of Substrate.
// Substrate is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) a... |
#[doc = "Reader of register ACT_DST"]
pub type R = crate::R<u32, super::ACT_DST>;
#[doc = "Reader of field `DST_ADDR`"]
pub type DST_ADDR_R = crate::R<u32, u32>;
impl R {
#[doc = "Bits 0:31 - Current address of destination location."]
#[inline(always)]
pub fn dst_addr(&self) -> DST_ADDR_R {
DST_ADDR... |
fn count_trees_hit(map: &Vec<Vec<i32>>, sx: usize, sy: usize) -> i64 {
let mut x: usize = 0;
map.iter().step_by(sy).fold(0, |acc, row| {
let idx = x % row.len();
let item = row[idx];
x += sx;
return acc + (item as i64);
})
}
pub fn part_one(input: &str) -> String {
let m... |
use std::collections::BTreeMap;
use std::error::Error;
use std::ffi::CString;
use std::marker::PhantomData;
use std::path::PathBuf;
use std::sync::{Arc, RwLock};
use cffi::{FromForeign, ToForeign};
use futures::stream::{Stream, StreamExt};
use serde::de::DeserializeOwned;
use serde::Serialize;
use crate::download::Do... |
mod equacao_diofantina;
mod testes;
use std::io::stdin;
use equacao_diofantina::EquacaoDiofantina;
use testes::rodar_testes;
fn main() {
/* Pedindo os valores de A, B e C */
let a: i32 = match pedir_valor("A") { Ok(valor) => valor, Err(erro) => { println!("{}", erro); return ; } };
let b: i32 = match pedi... |
use clap::crate_version;
use clap::Arg;
use clap::Command;
use crate::client::NodeClient;
use crate::fuse_adapter::FleetFUSE;
use crate::storage::Node;
use log::debug;
use log::warn;
use log::LevelFilter;
use std::net::{IpAddr, SocketAddr, ToSocketAddrs};
use crate::base::ErrorCode;
use fuser::MountOption;
use std::f... |
// Copyright 2015 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 ... |
//https://www.codewars.com/kata/5d98b6b38b0f6c001a461198/train/rust
const CRYPT: [&str; 10] = [
"10", "11", "0110", "0111", "001100", "001101", "001110", "001111", "00011000", "00011001",
];
fn code(s: &str) -> String {
let mut result = String::from("");
for &digit in s.as_bytes() {
result += CRYPT... |
use std::path::PathBuf;
use super::{Context, Module, RootModuleConfig};
use crate::configs::docker_context::DockerContextConfig;
use crate::formatter::StringFormatter;
use crate::utils;
/// Creates a module with the currently active Docker context
///
/// Will display the Docker context if the following criteria are... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.