text stringlengths 8 4.13M |
|---|
//! This module contains the implementations for the FTP commands defined in
//!
//! - [RFC 959 - FTP](https://tools.ietf.org/html/rfc959)
//! - [RFC 3659 - Extensions to FTP](https://tools.ietf.org/html/rfc3659)
//! - [RFC 2228 - FTP Security Extensions](https://tools.ietf.org/html/rfc2228)
mod abor;
mod acct;
mod al... |
use crate::services::metrics::command_metrics::CommandMetric;
use convert_case::{Case, Casing};
use indy_api_types::errors::{IndyErrorKind, IndyResult, IndyResultExt};
use models::{MetricsValue, CommandCounters};
use serde_json::{Map, Value};
use std::cell::RefCell;
use std::collections::HashMap;
pub mod command_metri... |
use serenity::{
model::{channel::Message, gateway::Ready, user::OnlineStatus},
prelude::*,
};
use std::env;
const HID:&'static str=env!("HID");
const DISCV:&str="0.8.7";
const RUSTV:&str="1.46.0";
const TOKEN:&'static str=env!("DISCORD_TOKEN");
struct Handler;
impl EventHandler for Handler {
fn message(&sel... |
use std::fs;
struct Entry {
lo: i32,
hi: i32,
lttr: char,
pwd: String
}
fn parse_to_entry(input: &str) -> Entry {
let parsed: Vec<&str> = input.split(" ").collect();
let policy: Vec<&str> = parsed[0].split("-").collect();
return Entry{
lo: policy[0].parse::<i32>().ok().unwrap(),
... |
/*
* 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
*/
/// SyntheticsGlobalVariableParseTestOptions : Parser options to use for retrieving a Synthetics global ... |
use super::atom::{btn::Btn, fa};
use super::constant;
use crate::libs::color::color_system;
use isaribi::{
style,
styled::{Style, Styled},
};
use kagura::prelude::*;
use nusa::prelude::*;
pub struct Props {}
pub enum Msg {}
pub enum On {}
pub struct Dialog {}
pub enum Button {
Ok(Events),
Yes(Event... |
//! A multi-producer single-receiver channel.
use std::cell::UnsafeCell;
use std::collections::VecDeque;
use std::marker::PhantomData;
use std::rc::Rc;
use std::task::{Poll, Waker};
use futures::sink::Sink;
use futures::stream::{FusedStream, Stream};
use thiserror::Error;
/// Error returned by [`try_next`](Unbounded... |
extern crate rust_pdftools;
//use rust_pdftools::imagemagick::imagemagick_commands as commands;
use rust_pdftools::imagemagick::operations::ImageMagickOperation as IMO;
use rust_pdftools::imagemagick::operations as ops;
use rust_pdftools::image_tools::image_ops::RunOperation as RO;
use rust_pdftools::image_tools::imag... |
use tokio_stream::{StreamExt};
use xstate::EventSender;
use super::types::Event;
// Listen to keyboard inputs to generate events
pub async fn listener(event_sender: EventSender<Event>) {
let stdin = tokio::io::stdin();
let mut reader = tokio_util::codec::FramedRead::new(stdin, tokio_util::codec::LinesCodec::n... |
/// The approved status of a beatmap.
#[allow(missing_docs)]
#[derive(Debug)]
pub enum ApprovedStatus {
StatusGraveyard,
StatusWIP,
StatusPending,
StatusRanked,
StatusApproved,
StatusQualified,
StatusLoved,
}
/// A score as returned from the osu! API.
#[derive(Serialize, Deserialize)]
#[all... |
use clap::{ArgMatches};
use clang::*;
use std::collections::HashSet;
use artifacts::Artifact;
import!(symbol_status);
import!(gen_context);
import!(ctype);
import!(argument);
pub mod interface_decl;
pub mod objc_instance_method;
pub mod objc_static_method;
pub mod enum_decl;
pub mod typedef_decl;
pub fn cli(matches:... |
use crate::pieces::{FlatPieces, Piece, PieceIndex, RawRecord};
use alloc::boxed::Box;
use core::iter::Step;
use core::mem;
use core::num::NonZeroU64;
use derive_more::{
Add, AddAssign, Deref, DerefMut, Display, Div, DivAssign, From, Into, Mul, MulAssign, Sub,
SubAssign,
};
use parity_scale_codec::{Decode, Encod... |
extern crate difference;
extern crate gst_log_parser;
extern crate regex;
extern crate structopt;
extern crate structopt_derive;
extern crate term;
use difference::{Changeset, Difference};
use gst_log_parser::{parse, Entry};
use regex::Regex;
use std::fs::File;
use std::path::PathBuf;
use structopt::StructOpt;
#[deri... |
pub mod callback;
use callback::callbacks;
use crate::Window;
use glium::glutin::event::{Event, WindowEvent};
pub use glium::glutin::event_loop::ControlFlow;
type EventLoop = glium::glutin::event_loop::EventLoop <()>;
static mut EVENTLOOP: Option <EventLoop> = None;
#[ctor::ctor]
#[inline(always)]
fn init() {
... |
use std::io::Write;
use serde::de::value::Error;
use serde::ser::{self, Serialize};
use internal::gob::Writer;
use internal::ser::SerializeStructVariantValue;
pub struct SerializeStructVariant<'t, W> {
inner: SerializeStructVariantValue<'t>,
out: Writer<W>,
}
impl<'t, W: Write> SerializeStructVariant<'t, W>... |
//! Utilities to help with implementation of traits and/or other functionality.
use enumset::{EnumSet, EnumSetIter, EnumSetType};
use std::collections::BTreeSet;
use rayon::iter::{IterBridge, IntoParallelRefIterator, ParallelBridge};
use crate::rdf_util::Literal;
use crate::bundle_model::constants::{HostFeature, Lv2Op... |
use std::collections::HashMap;
use std::collections::hash_map::Entry;
use crate::{
lisp_object::{
ParamList,
LispObject,
NativeDef,
SpecialForm,
Symbol,
SerializeSymbol,
},
native
};
pub struct Symbols {
registry: HashMap<String, Symbol... |
fn calculate(input_chars: &Vec<char>) -> (usize, usize) {
let mut index: usize = 0;
let mut nesting_level = 0;
let mut sum = 0;
let mut garbage = 0;
//Iterate over all the input and if we find garbage discard it and move
//the index on for the discarded ammount. Also keep track of which nesting ... |
use error::Result;
use git2::Repository;
use std::{fs, io};
use util::cd2root;
fn theme(repo: &str) -> Result<()> {
cd2root()?;
// Delete `theme` if it exists.
if let Err(e) = fs::remove_dir_all("theme") {
if e.kind() != io::ErrorKind::NotFound {
return Err(e.into());
}
}
... |
use crate::cpu::Register;
use crate::util::*;
#[derive(Copy, Clone, Eq, PartialEq, Debug)]
pub enum Branch {
BranchAndExchange(Register),
Branch { offset: i32, link: bool },
}
impl Branch {
pub fn from_bits_bx(bits: u32) -> Branch {
Branch::BranchAndExchange(bits.get_register(Offset(0)))
}
... |
use actix::prelude::*;
use kosem_webapi::Uuid;
use crate::protocol_handlers::websocket_jsonrpc::WsJrpc;
use crate::internal_messages::connection::{AddHumanActor, ConnectionClosed, RpcMessage};
use crate::internal_messages::info_sharing;
use crate::internal_messages::pairing::{PairingPerformed, ProcedureTerminated};
... |
use std::collections::HashMap;
use std::hash::Hash;
use num::{Integer, Float, Zero};
use crate::core::{Measurement, Function, PrivacyRelation, SensitivityMetric};
use crate::dist::{L1Distance, L2Distance, SmoothedMaxDivergence};
use crate::dom::{AllDomain, MapDomain, SizedDomain};
use crate::samplers::{SampleLaplace,... |
#[derive(Debug)]
struct LinkedList {
name: String,
next: Option<Box<LinkedList>>,
}
fn main() {
println!("Hello, Address Search!");
let mut list = LinkedList{
name: String::from("abc"),
next: None
};
println!("{:?}", list);
println!("{}", list.name);
match list.next {... |
extern crate memory_pager;
use memory_pager::{Page, Pager};
#[test]
fn can_create_default() {
let _pager = Pager::default();
}
#[test]
fn can_create_with_size() {
let _pager = Pager::new(1024);
}
#[test]
fn can_get() {
let mut pager = Pager::default();
{
let page = pager.get(0);
assert_eq!(page.buff... |
use std::iter::{Peekable, FromIterator};
use std::marker::PhantomData;
pub struct Buffering<I, U, F>
where
I: Iterator<Item = U>,
F: FromIterator<U>,
{
iter: Peekable<I>,
size: usize,
f: PhantomData<F>,
}
impl<I, U, F> Iterator for Buffering<I, U, F>
where
I: Iterator<Item = U>,
F: FromIte... |
use sdl2::event::Event;
use std::net::SocketAddr;
use crate::net::{ClientMessage, ServerMessage, Socket};
use crate::render::Renderer;
use crate::scene::{GameSoundEvent, Scene};
use crate::scenes::GameScene;
use crate::text::Text;
// ~10 seconds at 60 fps
const MAX_CONNECTION_ATTEMPTS: u64 = 600;
enum ConnectionStat... |
//! The [`n` queens puzzle](https://en.wikipedia.org/wiki/Eight_queens_puzzle)
//! is the problem of placing `n` chess queens on an `n`×`n` chessboard so that
//! no two queens threaten each other.
//!
//! A solution to the problem requires that no two queens share the same row,
//! column, or diagonal.
use crate::Ex... |
use cgmath::{EuclideanSpace, Matrix4, Point3,
Rad, Transform, vec3, Vector2, Vector3};
use std::default::Default;
use std::f32::consts::PI;
#[derive(Clone)]
pub struct Eye {
pub position: Point3<f32>,
pub azimuth: f32,
pub altitude: f32,
}
impl Eye {
/// Model-view matrix.
pub fn model_view(&s... |
use tools::NameValuePair;
/// # Folder
///
/// This Structure holds all Information required for
/// a Folder and its database representation.
pub struct Folder {
pub id: u64,
pub parent_id: u64,
pub title: String,
pub path: String,
pub element_count: u32,
pub last_modified: u64,
}
impl Folde... |
use std::str;
fn input() -> &'static str {
include_str!("input.txt")
}
fn is_word_nice(word: &str) -> bool {
// contains 3 vowels
word.chars().filter(|&c| c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u').count() >= 3
// contains a double letter
&& word.chars().zip(word.chars().ski... |
use crate::{
props::{Props, PropsDef},
widget::{
node::{WidgetNode, WidgetNodeDef},
unit::{WidgetUnit, WidgetUnitData},
utils::Rect,
WidgetId,
},
Scalar,
};
use serde::{Deserialize, Serialize};
use std::convert::TryFrom;
#[derive(Debug, Copy, Clone, Serialize, Deserializ... |
use std::fs::{self, File};
use std::io::{self, BufReader, prelude::*};
use std::path::Path;
use structopt::StructOpt;
// Search for a pattern in a file and display the lines that contain it.
#[derive(StructOpt, Debug)]
struct Cli {
/// The pattern to look for
pattern: String,
/// The path to the file to re... |
// Copyright (c) The Libra Core Contributors
// SPDX-License-Identifier: Apache-2.0
use super::*;
use libra_crypto::HashValue;
use libra_types::vm_error::StatusCode;
use schemadb::schema::assert_encode_decode;
use sgtypes::channel_transaction_info::ChannelTransactionInfo;
#[test]
fn test_encode_decode() {
let txn... |
use crate::set1::base64::to_base64;
use crate::set1::hex::hex_value;
pub fn hex_to_base64(input: String) -> String {
return String::from_utf8(to_base64(hex_value(input))).unwrap();
}
#[cfg(test)]
mod test {
use super::hex_to_base64;
#[test]
fn no_padding() {
let input = String::from("aaaaaa")... |
mod filler;
mod screen;
mod ui;
pub use self::ui::MapCamera;
use std::{fs::File, io::BufReader};
use bevy::prelude::*;
use fujiformer_io::CelesteMap;
use self::ui::MapUiPlugin;
pub struct MapPlugin;
impl Plugin for MapPlugin {
fn build(&self, app: &mut AppBuilder) {
app.add_plugin(MapUiPlugin)
... |
fn main() {
println!("Use one of the 'arcade-rs-*' subfolders, and make there with `cargo run`");
}
|
fn main() {
// bool 类型
let is_true: bool = true;
println!("is_true = {}", is_true);
let is_false: bool = false;
println!("is_false = {}", is_false);
// char 在rust 里面, char 是32 位的, 4个字节
let a = 'a';
println!("a = {}", a);
let b = '你';
println!("b = {}", b);
// 数字类型
// i8... |
extern crate ggez;
mod algos;
mod data;
mod graphics;
mod scenes;
mod std_ext;
use ggez::{Context, ContextBuilder, GameResult, timer};
use ggez::graphics as ggez_g;
use ggez::event::{self, EventHandler, KeyMods, KeyCode};
use ggez::conf::{WindowMode, WindowSetup};
use ggez::mint::Point2;
use ggez::graphics::{Text, Co... |
//
// Copyright 2019 The Project Oak 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 required by applicable law o... |
//! # Lrc-common
//! A collection of utilities, common to both the LMC and RISC emulators.
pub mod tests;
pub mod args_parser;
pub fn hi() {
} |
use proconio::{input, marker::Usize1};
fn main() {
// これ用のコードです。
// https://atcoder.jp/contests/typical90/tasks/typical90_ac
input! {
w:usize,
n:usize,
lr:[(Usize1,Usize1);n],
}
let mut tree = SegTree::from_vec(
vec![0; w],
|x, y| x.max(y),
0,
... |
use std::{
convert::{TryFrom, TryInto},
fmt::Debug,
ops::{Deref, DerefMut},
};
use crate::{
artist::Artists,
availability::Availabilities,
copyright::Copyrights,
external_id::ExternalIds,
image::Images,
request::RequestResult,
restriction::Restrictions,
sale_period::SalePeri... |
use anyhow::{anyhow, Context, Result as AHResult};
use clap::Clap;
use serde::{Deserialize, Serialize};
use std::fmt::Debug;
use std::io::{self, Read};
use crate::secret_store::SecretStore;
use crate::types::{CommonOpts, WithCommonOpts};
#[derive(Clap, Debug, Serialize, Deserialize, PartialEq)]
pub struct OpaqueOpts ... |
pub const BYTES_PER_SECTOR : usize = 512;
pub const SECTORS_PER_MB : usize = 2048;
pub const MB_PER_DISK : usize = 1;
pub const SECTORS_PER_DISK : usize = MB_PER_DISK * SECTORS_PER_MB;
pub const MAX_STRUCTURE_SIZE : usize = BYTES_PER_SECTOR * 1;
use crate::{data::boxed::*, };//fs::BinarySerializable};
pub tra... |
//
// Copyright 2021 The Project Oak 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 required by applicable law o... |
use std::collections::HashSet;
use crate::util::{lines, time};
pub fn day3() {
println!("== Day 3 ==");
let input = "src/day3/input.txt";
time(part_a, input, "A");
time(part_b, input, "B");
}
fn part_a(input: &str) -> i32 {
lines(input).iter()
.map(|line| find_duplicate(line))
.ma... |
// Not my best work, I have seen a better solution using iterator.fold() and I understand how that's used now and will review passing closures
// as arguments
pub fn decode(s: &str) -> String {
let mut decoded = String::new();
let s = s.to_string();
let mut current_n = "0".to_string();
let mut chars =... |
use bevy::prelude::*;
use bevy_modding::*;
fn main() {
App::build()
.add_plugin(ModdingPlugin::new( "target/debug/mods"))
.run();
}
|
struct Solution();
impl Solution {
pub fn my_atoi(s: String) -> i32 {
let mut result=String::from("");
let mut r_prime =s;
//判断第一个是不是数字
let mut flag=0;
let mut sign=' ';
let mut sign_flag=true;
if let Some(value)=r_prime.strip_prefix(&[' '][..]){
r... |
pub fn on_load() {
println!("phasicj_jmm_log_agent::on_load()");
} |
#[doc = "Register `YBUFCFG` reader"]
pub type R = crate::R<YBUFCFG_SPEC>;
#[doc = "Register `YBUFCFG` writer"]
pub type W = crate::W<YBUFCFG_SPEC>;
#[doc = "Field `Y_BASE` reader - Base address of Y buffer"]
pub type Y_BASE_R = crate::FieldReader;
#[doc = "Field `Y_BASE` writer - Base address of Y buffer"]
pub type Y_B... |
use crate::astar::AStar;
use crate::prelude::*;
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Map {
columns: Vec<u64>,
height: usize,
points_of_interest: Vec<Vec2us>,
}
impl Map {
fn is_wall(&self, pos: Vec2us) -> bool {
debug_assert!(pos.y < self.height);
self.columns[pos.x] & (1 ... |
use bevy::prelude::*;
use crate::{
Materials,Levels,LevelConfig,
paddle::Paddle,
ball::Ball,
powerup::Powerup,
brick::Destroyable,
level::{spawn_level}
};
pub struct LifeLostEvent;
pub enum LevelFinishedEvent {
Won,
Lost,
}
#[derive(PartialEq, Eq)]
pub enum PausedState... |
pub mod prelude {
pub use super::response::prelude::*;
pub use super::status::prelude::*;
}
pub mod response;
pub mod status;
|
use std::fmt::{self, Debug};
use std::ops::Range;
use crate::RangeMap;
#[derive(Clone)]
/// A set whose items are stored as (half-open) ranges bounded
/// inclusively below and exclusively above `(start..end)`.
///
/// See [`RangeMap`]'s documentation for more details.
///
/// [`RangeMap`]: struct.RangeMap.html
pub s... |
#[derive(Debug)]
enum IpAddrKind {
V4,
V6,
}
#[derive(Debug)]
struct IpAddr {
kind: IpAddrKind,
address: String,
}
#[derive(Debug)]
enum IpAddrBind {
V4(String),
V6(String),
}
#[derive(Debug)]
enum IpAddrSepBind {
V4(u8, u8, u8, u8),
V6(String),
}
enum Message {
Quit, ... |
use std::time::Duration;
use bytes::{Buf, BufMut, Bytes, BytesMut};
use super::utils;
use super::{Body, Frame, Version};
use crate::error::RSocketError;
use crate::utils::{Writeable, DEFAULT_MIME_TYPE};
#[derive(Debug, Eq, PartialEq)]
pub struct Setup {
version: Version,
keepalive: u32,
lifetime: u32,
... |
//The quote macro can require a high recursion limit
#![recursion_limit = "256"]
// Clippy's suggestions for these don't compile
#![allow(clippy::explicit_counter_loop)]
extern crate proc_macro;
extern crate proc_macro2;
extern crate quote;
extern crate syn;
use core::convert::AsRef;
use proc_macro::TokenStream;
use ... |
//! # MD5 hash on `Read`/`Write`
use std::io::{Read, Write};
use md5::Context;
use super::MD5Sum;
/// # Wrapper for [`std::io`] traits.
///
/// This struct calculates an MD5 hash as data passes through
///
/// **Note:** The hash will be valid for neither if read and write are interleaved
///
/// Additionally, this ... |
#[macro_use]
extern crate cluLog;
use cluLog::LogFile;
fn main() {
match LogFile::default_create_path("/tmp/test") {
Ok(file_log) => cluLog::set_logger(file_log),
Err(e) => panic!("Err open file output, {:?}", e),
};
trace!("Test 1");
println!("Test 2");
inf!("Test ... |
use std::os::args;
fn main() {
let mut is_data = false;
let mut data = ::std::slice::with_capacity::<int>(32);
let mut bubble_sort_flag = false;
let mut quiet = false;
let args = args();
let mut args_iter = args.iter();
args_iter.next();
for arg in args_iter {
match arg.as_slice() {
"-q" =... |
pub mod leds {
pub mod controller {
use stm32l4xx_hal::prelude::*;
use stm32l4xx_hal::stm32::{TIM2, DMA1, RCC};
use stm32l4xx_hal::pwm::{Pwm, C1};
pub fn init(pwm: &mut Pwm<TIM2, C1>) -> u32 {
// setup the peripherals
// let dp = unsafe { stm32l4xx_hal::s... |
use std::str::FromStr;
use wasm_bindgen::prelude::*;
#[cfg(feature = "wee_alloc")]
#[global_allocator]
static ALLOC: wee_alloc::WeeAlloc = wee_alloc::WeeAlloc::INIT;
static VERBOSE: bool = false;
#[wasm_bindgen]
extern "C" {
#[wasm_bindgen(js_namespace = console)]
fn log(s: &str);
#[wasm_bindgen(js_name... |
use crate::kraken::Taxon;
#[derive(Clone, PartialEq, PartialOrd, Debug, Serialize, Deserialize)]
pub struct AbundanceValues {
pub kraken_assigned_reads: u64,
pub added_reads: u64,
pub new_est_reads: u64,
pub fraction_total_reads: f64,
}
#[derive(Clone, PartialEq, PartialOrd, Debug, Deserialize)]
pub st... |
use std::{
fs::File,
io::{BufRead, BufReader},
};
use chrono::Utc;
fn main() {
let file_names = vec!["empty_sample_data.csv", "sample_data.csv", "sample_data_huge.csv", "sample_data_large.csv"];
file_names.iter().for_each(|file| {
test(file.to_string())
})
}
fn read_in_file(file_name: St... |
use amethyst::ecs::{Component, NullStorage};
use std::marker::PhantomData;
// デバッグ表示を行うためのマーカーコンポーネント
#[derive(Default)]
pub struct DebugInfomationDisplay<T> {
marker: PhantomData<T>,
}
impl<T> DebugInfomationDisplay<T> {
pub fn new() -> Self {
DebugInfomationDisplay {
marker: ... |
use std::error;
use std::fmt;
use std::fmt::Display;
pub enum BackendError {
DbOpenFail,
Other
}
impl error::Error for BackendError {
fn description(&self) -> &str {
match *self {
BackendError::DbOpenFail => "DB could not be opened",
BackendError::Other => "Some other error... |
#[doc = r"Register block"]
#[repr(C)]
pub struct KEY {
#[doc = "0x00 - key registers"]
pub klr: KLR,
#[doc = "0x04 - key registers"]
pub krr: KRR,
}
#[doc = "KLR (w) register accessor: key registers\n\nYou can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zer... |
pub const ORDER_DATETIME_COLNAME: &str = "Timestamp";
pub const ORDER_ID_COLNAME: &str = "ORDER_ID";
pub const ORDER_PRICE_COLNAME: &str = "PRICE";
pub const ORDER_SIZE_COLNAME: &str = "SIZE";
pub const ORDER_BS_FLAG_COLNAME: &str = "BUY_SELL_FLAG";
pub const DATETIME_FORMAT: &str = "%Y-%m-%d %H:%M:%S%.f";
pub const CS... |
pub mod model;
pub mod geolocation;
|
pub mod agent;
pub mod service;
pub mod types;
pub use self::agent::*;
pub use self::service::*;
pub use self::types::*;
|
//! Module with the goban and his implementations.
use crate::pieces::go_string::GoString;
use crate::pieces::stones::*;
use crate::pieces::util::coord::{is_coord_valid, neighbor_points, CoordUtil, Order, Point};
use crate::pieces::zobrist::*;
use crate::pieces::{uint, GoStringPtr, Ptr, Set};
use std::collections::Has... |
fn main() {
println!("Hello, world!");
let (tx, rx) = mpsc::channel();
let kura = Kura { tx };
thread::spawn(move || loop {
kura.tx.send("Test".to_string()).unwrap();
thread::sleep(Duration::from_millis(200));
});
let wsv = Wsv {
inner: Arc::new(Mutex::new(Vec::new())),
... |
use crate::server::{
controlchan::{error::ControlChanError, middleware::ControlChanMiddleware},
Command, Event, Reply,
};
use async_trait::async_trait;
// Control channel middleware that logs all control channel events
pub struct LoggingMiddleware<Next>
where
Next: ControlChanMiddleware,
{
pub logger:... |
use std::env::args;
pub fn even(x: &i32) -> bool {
x % 2 == 0
}
fn main() {
for x in args().skip(1) {
println!("hello {}", x);
}
for x in 0..10 {
println!("That's {}", x);
}
for (k, v) in (10..20).enumerate() {
println!("k={},v={}", k, v);
}
for x in FibIter:... |
use vtree_macros;
vtree_macros::define_nodes!{
nodes {
RootContext: mul Window,
Window<::params::Window>: @Widget,
Box<::params::Box>: mul @Widget,
Button: Label,
Label: mul Text,
}
groups {
Widget: Box Button Label,
}
}
|
use crate::name_server::NameServer;
use wire::record::Record;
use std::net::IpAddr;
use std::time::Instant;
use std::time::Duration;
use std::hash::Hash;
use std::hash::Hasher;
use std::hash::BuildHasher;
use std::collections::hash_map::HashMap;
use std::sync::Arc;
use std::sync::RwLock;
const DEFAULT_DURATION: D... |
use rand;
use v2::{V2};
use gamestate::{Pickup, PickupType};
pub fn mk_random_vec() -> V2 {
use rand::distributions::{IndependentSample, Range};
let between = Range::new(0.0f64, 1000.0);
let mut rng = rand::thread_rng();
let x = between.ind_sample(&mut rng);
let y = between.ind_sample(&mut rng);
... |
pub mod error;
pub mod token;
use error::*;
use token::{Token, TokenKind};
use std::str::Chars;
pub struct LexicalAnalyzer<'a> {
/// 先読みした一文字。EOF の場合に None。
next_char: Option<char>,
/// ソースの読み込み元
stream: Chars<'a>,
/// 現在の行数
line_number: usize,
/// 現在の列数
column_number: usize,
}
/// c... |
mod send_kill_packet;
mod send_spectate_packet;
mod send_timer_event;
mod set_spectate_flag;
mod set_target;
pub use self::send_kill_packet::SendKillPacket;
pub use self::send_spectate_packet::SendSpectatePacket;
pub use self::send_timer_event::SendTimerEvent;
pub use self::set_spectate_flag::SetSpectateFlag;
pub use ... |
use std::sync::Arc;
use std::thread;
use std::{fs::File, sync::Mutex};
use std::io::{BufReader, Cursor, Read, Write};
use fastanvil::{RegionBuffer};
use fastnbt::{Value, de::from_bytes};
use rayon::scope;
use walkdir::WalkDir;
use std::io::BufWriter;
fn main() {
let file_out = Arc::new(Mutex::new(BufWriter::new(Fi... |
mod parse;
|
use std::io::{stdin, print};
use std::io::stdio::flush;
use std::io::BufferedReader;
fn main() {
print("Enter your name: ");
flush();
let mut reader = BufferedReader::new(stdin());
match reader.read_line() {
Err(_) => fail!("Error reading input"),
Ok(name) => {
let name = name.trim_right();
... |
extern crate epidem;
use crate::epidem::epidem::compartment::IsCompartment;
use epidem::epidem::model::IsModel;
use epidem::epidem::sirs::SIRS;
fn main() {
let mut m = SIRS::new(&"Testing SIRS", 100, 1, 0);
//let mut model = Sir::new(0.05, 6.0, 1.0, 100, 100.0);
for x in 1..100 {
m.next();
... |
use image::DynamicImage;
use std::fs::File;
use std::io::prelude::*;
use std::path::PathBuf;
pub fn img_to_txt(img: DynamicImage, output_path: PathBuf) {
let mut output_file: File = File::create(output_path).expect("Error can't open output file");
let pixels = img.to_rgb8();
let mut res: String = String::f... |
use std::collections::HashSet;
// Install the listed packages and their dependencies
pub fn install_packages<'a>(packages_to_install: HashSet<&'a str>) -> Vec<i32> {
vec![0]
}
|
use vendored_sha3::{Digest, Sha3_512};
/// SHA3_512 alias Sha3_512 and implements Hash.
pub type SHA3_512 = Sha3_512;
/// The blocksize of SHA3-512 and Keccak-512 in bytes.
pub const BLOCK_SIZE512: usize = 72;
/// The size of a SHA3-512 and Keccak-512 checksum in bytes.
pub const SIZE512: usize = 64;
impl super::Has... |
use std::fmt;
use std::ops::Add;
use serde::{Deserialize, Serialize};
use std::convert::TryFrom;
use std::fmt::Debug;
use std::fmt::Display;
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum PieceType {
Pawn,
Rook,
Knight,
Bishop,
Queen,
King,
}
impl PieceTyp... |
//! Encoding of binary [`Transaction`].
//!
//! ```text
//!
//! +-----------+-------------+----------------+
//! | | | |
//! | Version | Template | Name |
//! | (u16) | (Address) | (String) |
//! | | | |
//! +----... |
mod chunk;
mod chunk_grid;
mod chunk_group;
pub use self::chunk::{Chunk, CHUNK_DEPTH, CHUNK_HEIGHT, CHUNK_WIDTH};
pub use self::chunk_grid::{ChunkGrid, ChunkGridCoordinate};
pub use self::chunk_group::ChunkGroup;
|
use warp::{
filters::BoxedFilter,
Filter,
Reply,
};
pub fn get_routes(_config: &crate::config::Config) -> BoxedFilter<(impl Reply,)> {
let root_path = warp::path::end().map(|| return "Hello Root");
let test1 = warp::path::end().map(|| return "Hello Test1");
let test2 = warp::path("nested").and(warp::path::end())... |
use crate::{
bet::Bet,
bet_database::{BetId, BetState},
OracleInfo,
};
use anyhow::{anyhow, Context};
use bdk::{
bitcoin::{
util::psbt::{self, PartiallySignedTransaction as Psbt},
Amount, Transaction,
},
database::BatchDatabase,
miniscript::DescriptorTrait,
wallet::tx_bui... |
use super::{Mass, Schwarzschild};
use crate::typenum::consts::U4;
use diffgeom::coordinates::{ConversionTo, CoordinateSystem, Point};
use diffgeom::metric::MetricSystem;
use diffgeom::tensors::{ContravariantIndex, CovariantIndex, InvTwoForm, Matrix, Tensor, TwoForm};
use generic_array::arr;
use std::f64::consts::PI;
us... |
pub const CREATE_ACC: &str = "create_account";
pub const TRANSFER_AMOUNT: &str = "transfer_amount";
|
/// Module contains some assertions on proposal's batch
use crate::proposal::{ProposalBatchX, ProposalId};
use crate::batch_item_kind::{BatchItemKindT, BatchItemKind};
use crate::batch_tree::{traverse_batch_tree, BatchTreeNode, StopTraverse};
use super::Config;
/// Proposal assertions enumeration
pub enum ProposalAs... |
/// An enum representing all the keys of a keyboard (normally)
#[derive(Debug, PartialEq)]
#[allow(missing_docs)]
pub enum Key {
Unknow = 0,
BackSpace = 8,
Tab = 9,
Enter = 13,
Shift = 16,
Ctrl = 17,
Alt = 18,
Pause = 19,
CapsLock = 20,
Escape = 27,
PageUp = 33,
PageDown ... |
// 使用 use 引入结构体、枚举和其他项时,习惯是指定它们的完整路径
// 这种习惯用法背后没有什么硬性要求:它只是一种惯例,人们已经习惯了以这种方式阅读和编写 Rust 代码。
use std::collections::HashMap;
fn main() {
let mut map = HashMap::new();
map.insert(1, 2);
println!("map: {:?}", map)
}
|
use specs::prelude::*;
use sdl2::rect::{Point, Rect};
use sdl2::pixels::Color;
use sdl2::render::{WindowCanvas, Texture};
use crate::components::*;
const TEXT_HORI_PADDING: u32 = 1; // pixels
const TEXT_VERT_PADDING: u32 = 4; // pixels
// Type alias for the data needed by the renderer
pub type SystemData<'a> = (
... |
use crate::{
FieldResultExtra,
FileInfo,
MulterError,
Handler,
};
use bytes::BytesMut;
use futures::future::FutureExt;
use std::borrow::Borrow;
use tokio::stream::StreamExt;
pub struct MemoryResultInfo {
data: BytesMut,
}
impl FieldResultExtra for MemoryResultInfo {
fn content(&self) -> Option... |
use std::path::PathBuf;
use serde_derive::{Deserialize, Serialize};
use syntect::parsing::SyntaxSet;
pub const DEFAULT_HIGHLIGHT_THEME: &str = "base16-ocean-dark";
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(tag = "highlight_type")]
pub enum HighlighterSettings {
/// Produce "span with styles" highli... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.