text stringlengths 8 4.13M |
|---|
extern crate bnb_api;
use bnb_api::*;
use bnb_api::websockets::*;
/* Public REST API */
fn new_client() -> BnbClient {
return BnbClient::new(None, None);
}
#[test]
fn exchange_info() {
let mut cl = new_client();
assert!(cl.fetch_exchange_info().is_ok());
}
#[test]
fn ticker_24h() {
let mut cl = new_... |
/*!
# Graph Oriented Modelling
根据GraphQL的规范,定义了Query, Mutation 和 Subscription 三个executing operations。基于此,Graph trait也实现上述三个methods:query, mutate, subscribe。
Graph 的核心是定位vertices并对其进行操作,然后返回结果。输入项被称为谓语:Predicate,输出项:Output。根据Rust的设计理念,Predicate作为输入项,采用generic parameter比较好,Output作为输出项,采用associated type为好。举一个例子,如果对于非对... |
//! Sample passphrase words from a wordlist
//!
//! A minimal example that shows how a word sampler derived from a default wordlist may be used to
//! uniformly sample a number of words.
//!
//! It is not recommended to manually use this logic for forming your own passphrases. The
//! abstractions in [`Scheme`](scheme:... |
#[doc = "Reader of register IRQ_INTF"]
pub type R = crate::R<u32, super::IRQ_INTF>;
#[doc = "Writer for register IRQ_INTF"]
pub type W = crate::W<u32, super::IRQ_INTF>;
#[doc = "Register IRQ_INTF `reset()`'s with value 0"]
impl crate::ResetValue for super::IRQ_INTF {
type Type = u32;
#[inline(always)]
fn re... |
use stremio_core::types::addons::{Manifest};
use semver::Version;
use serde_json;
pub struct Scaffold;
impl Scaffold {
pub fn default_manifest() -> Manifest {
Manifest {
id: String::default(),
name: String::default(),
version: Version::new(0, 0, 1),
resources... |
use crate::MyApp;
use seed::{*, prelude::*};
use crate::traits::component_trait::Component;
use crate::components::homepage_component::HomePageComponent;
use crate::messages::{Page, Msg};
use crate::traits::router_trait::Router;
//Router Component
pub struct RouterComponent;
impl<'a> Router<'a, MyApp, Msg> for Router... |
pub fn verse(n: i32) -> String {
match n {
0 => String::from("No more bottles of beer on the wall, no more bottles of beer.\nGo to the store and buy some more, 99 bottles of beer on the wall.\n"),
1 => String::from("1 bottle of beer on the wall, 1 bottle of beer.\nTake it down and pass it around, no... |
//! # The XML `<ModularBuild>` format
|
mod data;
use actix_web::{get, middleware, web, App, HttpResponse, HttpServer, Responder};
use mongodb;
use mongodb::bson::doc;
#[get("/cocktail/{name}")]
async fn cocktail(
mongodb_client: web::Data<mongodb::Client>,
web::Path(_name): web::Path<String>,
) -> impl Responder {
// match &mongodb_client
... |
extern crate rand;
fn main()
{
let random_num1 = rand::random::<i32>();
let random_num2: i32 = rand::random();
println!("rand {} {}", random_num1, random_num2);
let random_char: char = rand::random();
println!("rand {}", random_char);
use rand::Rng;
let mut rng = rand::thread_rng();
... |
use ggez::*;
use ggez::event::{self, KeyCode};
use ggez::input;
use std::path;
use std::env;
struct GameState {
ground_sprite_batch: graphics::spritebatch::SpriteBatch,
runner_sprite_batch: graphics::spritebatch::SpriteBatch,
runner_pose_rects: Vec<graphics::Rect>,
runner_current_pose: usize,
runne... |
use serde::{Deserialize, Serialize};
use std::path::PathBuf;
use std::{ffi::OsStr, fs};
use toml;
#[derive(Debug, Deserialize, Serialize)]
pub struct LangConfig {
#[serde(default = "use_spaces")]
pub use_spaces: bool,
#[serde(default = "space_size")]
pub space_size: usize,
#[serde(default = "newlin... |
use std::collections::HashMap;
use std::collections::hash_map::Entry;
use std::rc::Rc;
use rand::distributions::WeightedIndex;
use rand::prelude::Distribution;
use crate::abstractions::CustomDistribution;
use std::hash::Hash;
use crate::abstractions::FitFunc;
use crate::algorithm::algorithm::GenHash;
pub struct S... |
#![warn(dead_code)]
#![warn(unused_imports)]
pub mod pb {
tonic::include_proto!("fulcrum");
}
use tracing::{Level};
use sled::Config as SledConfig;
// use futures::Stream;
use tokio::sync::mpsc;
use tonic::{transport::Server, /*, Streaming*/};
mod error_handling;
mod data_access;
mod cdn;
use cdn::*;
mod da... |
#![allow(non_snake_case)]
/// Read a line from stdin.
/// Strip the trailing newline if any.
fn read_line() -> String {
let mut buf = String::new();
std::io::stdin().read_line(&mut buf).unwrap();
#[allow(deprecated)]
let new_len = buf.trim_right_matches('\n').len();
buf.truncate(new_len);
buf
}... |
use std::pin::Pin;
use std::sync::Arc;
use futures::{
future::{poll_fn, select},
pin_mut, select, FutureExt, Sink,
};
use crate::{
client::{watch_for_client_state_change, Client, ClientTaskTracker, SubscriptionStream},
error::WampError,
proto::TxMessage,
transport::Transport,
Id, MessageBu... |
use criterion::black_box;
use std::sync::Arc;
use xwords::{
crossword::Crossword,
fill::{filler::Filler, Fill},
trie::Trie,
};
use criterion::{criterion_group, criterion_main, Benchmark, Criterion};
pub fn criterion_benchmark(c: &mut Criterion) {
let group_id = "filler";
let trie = Trie::load_def... |
extern crate proc_macro;
use proc_macro2::TokenStream;
use quote::quote;
use syn::{parse_macro_input, DeriveInput};
macro_rules! extract {
($member:ident, $body:expr) => {
fn $member<'a>(data: &'a syn::DataStruct) -> impl Iterator<Item = TokenStream> + 'a {
data.fields.iter().map($body)
... |
use serde_json::Value;
use std::io::Write;
use std::net;
use crate::hook_prot as hook_protocol;
pub struct HookClient {
pub dest: net::SocketAddr,
}
pub struct HookPacket<T> {
pub data: T,
inner_data: Vec<u8>,
}
fn create_bytes(initial: &[u8], len: u8) -> Vec<u8> {
let mut zeros = vec![0; len as usi... |
use std::io::Read;
fn main(){
let mut file = std::fs::File::open("data.txt").unwrap();
let mut contents = String::new();
file.read_to_string(&mut contents).unwrap();
print!("{}", contents);
} |
use std::env;
use std::fs::File;
use std::io::Read;
use std::sync::{Once, ONCE_INIT};
use toml;
static mut CONFIG: *const Config = 0usize as *const _;
static CONFIG_INIT: Once = ONCE_INIT;
#[derive(Deserialize, Clone, Default)]
pub struct Config {
listen_address: Option<String>,
peers_path: Option<String>,
}... |
use super::{
shared::{mask_64, vector_128},
*,
};
use crate::{
block,
classification::mask::m64,
debug,
input::{InputBlock, InputBlockIterator},
FallibleIterator,
};
use std::marker::PhantomData;
super::shared::quote_classifier!(Ssse3QuoteClassifier64, BlockSsse3Classifier, 64, u64);
struc... |
use volatile::Volatile; // Helps prevent the optimizer optimizing our buffer
use lazy_static::lazy_static; // Allows us to create static structs
use spin::Mutex; // no_std mutex
use core::fmt; // Lets us format strings easily
lazy_static! {
/// # WRITER_GLOBAL
/// Static, mutable reference to a writer. This... |
#[doc = "Reader of register DATA_CTL"]
pub type R = crate::R<u32, super::DATA_CTL>;
#[doc = "Writer for register DATA_CTL"]
pub type W = crate::W<u32, super::DATA_CTL>;
#[doc = "Register DATA_CTL `reset()`'s with value 0"]
impl crate::ResetValue for super::DATA_CTL {
type Type = u32;
#[inline(always)]
fn re... |
use clap::{App, AppSettings, Arg, ArgMatches};
use crate::finder;
pub fn get_cli(version: &str) {
let args = App::new("seq-finder")
.version(version)
.about("Find ngs sequence")
.author("Heru Handika <hhandi1@lsu.edu>")
.setting(AppSettings::SubcommandRequiredElseHelp)
.sub... |
use std::fs::{create_dir, File};
use clap::ArgMatches;
use crate::errors::{BoilrError, StandardResult};
use crate::utils::terminal::{error, notify};
use crate::utils::{prompt_overwrite_if_exist, to_output_path};
use crate::{TEMPLATE_CONFIG_NAME, TEMPLATE_DIR_NAME, TEMPLATE_IGNORE_FILE};
pub fn new(args: &ArgMatches)... |
pub fn child1_fucntion(){
println!("child1 Function");
} |
use quote::quote_spanned;
use super::{
FlowProperties, FlowPropertyVal, OperatorCategory, OperatorConstraints, OperatorWriteOutput,
Persistence, WriteContextArgs, RANGE_0, RANGE_1,
};
use crate::diagnostic::{Diagnostic, Level};
use crate::graph::{OpInstGenerics, OperatorInstance};
/// Takes one stream as inpu... |
pub(crate) const K: [u32; 4] = [0x5A82_7999, 0x6ED9_EBA1, 0x8F1B_BCDC, 0xCA62_C1D6];
pub(crate) const IV: [u32; 5] = [
0x6745_2301,
0xEFCD_AB89,
0x98BA_DCFE,
0x1032_5476,
0xC3D2_E1F0,
];
#[inline(always)]
pub(crate) const fn ch(b: u32, c: u32, d: u32) -> u32 {
(b & c) | (!b & d)
}
#[inline(alw... |
use std::ops::Add;
use std::marker::PhantomData;
#[derive(Debug, Clone, Copy)]
enum Inch {}
#[derive(Debug, Clone, Copy)]
enum Mm {}
#[derive(Debug, Clone, Copy)]
struct Length<Unit>(f64, PhantomData<Unit>);
impl<Unit> Add for Length<Unit> {
type Output = Length<Unit>;
fn add(self, rhs: Length<Unit>) -> Len... |
#[macro_use]
extern crate may;
extern crate native_tls;
extern crate tungstenite;
use may::net::TcpListener;
use tungstenite::accept;
fn main() {
let handler = go!(move || {
let listener = TcpListener::bind(("0.0.0.0", 8080)).unwrap();
for stream in listener.incoming() {
go!(move || {
... |
pub mod selectors;
use mdo::option::*;
use crate::item::{ItemInfo,ItemType,IdInfo};
use std::string::String;
use scraper::{Html,Selector,ElementRef};
pub fn get_ids_by_name(item_name: &str) -> Vec<IdInfo> {
let name = item_name.replace(" ", "+").to_lowercase();
let url = format!("https://www.novaragnarok.com... |
use crate::{
assets::Color, dispose::Dispose, hex::render::renderer::HexRenderer, world::RhombusViewerWorld,
};
use amethyst::{
assets::Handle,
core::{math::Vector3, transform::Transform},
ecs::prelude::*,
prelude::*,
renderer::Material,
};
use rhombus_core::hex::{coordinates::axial::AxialVector... |
use super::coin::Coin;
pub trait Msg {
fn route() -> String;
fn msg_type() -> String;
fn validate_basic() -> Result<(), String>;
fn get_sign_bytes() -> &[u8];
fn get_signers();
}
pub trait Fee {
fn get_gas() -> u64;
fn get_amount() -> &[Coin];
}
pub trait Signature {
fn get_pubkey() -... |
macro_rules! log{
( $($arg:tt)* ) => ({
// Import the Writer trait (required by write!)
use core::fmt::Write;
let _ = write!(&mut ::port::logging::Writer::get(module_path!()), $($arg)*);
})
}
|
extern crate atadb;
extern crate clap;
use atadb::librarian::auth::user::User;
use atadb::librarian::tables::column::Column;
use atadb::librarian::tables::data_type::DataType;
use atadb::librarian::tables::schema::Schema;
use atadb::librarian::tables::table::Table;
use atadb::shared::util::name::Name;
use clap::App;
u... |
use super::board::Board;
use super::errors::GameError;
use rand::{Rng};
use std::collections::HashMap;
use serde::{Serialize, Deserialize};
use std::sync::RwLock;
pub struct GameRepository {
games: HashMap<u32, RwLock<Game>>
}
impl GameRepository {
pub fn new() -> GameRepository {
GameRepository {
... |
fn greet_user(name: Option<String>) {
match name {
Some(name) => println!("Hello {}", name),
None => println!("Howdy, stranger!"),
}
}
fn main() {
greet_user(Some("Pete".to_string()));
greet_user(None);
}
|
#[doc = "Register `CRRCR` reader"]
pub type R = crate::R<CRRCR_SPEC>;
#[doc = "Register `CRRCR` writer"]
pub type W = crate::W<CRRCR_SPEC>;
#[doc = "Field `HSI48ON` reader - HSI48 clock enable"]
pub type HSI48ON_R = crate::BitReader;
#[doc = "Field `HSI48ON` writer - HSI48 clock enable"]
pub type HSI48ON_W<'a, REG, con... |
//! Body color
/// Pokemon body color
#[derive(PartialEq, Eq, Clone, Copy, Hash, Debug)]
#[derive(serde::Serialize, serde::Deserialize)]
pub enum BodyColor {
Red = 0,
Blue = 1,
Yellow = 2,
Green = 3,
Black = 4,
Brown = 5,
Purple = 6,
Gray = 7,
White = 8,
Pink = 9,
}
impl BodyColor {
/// Return... |
use std::fmt; // Import `fmt`
pub fn cannonical_print(first_name: String) {
println!("My name is {0}, {1} {0}", "Stark", first_name);
let pi = 3.141592;
let formatted_number = format!("{:.*}", 3, pi);
println!("Pi is roughly {}", formatted_number);
println!("Question mark format for trait {:?}", (true, 25, "S... |
// Copyright 2020 <盏一 w@hidva.com>
// 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 writing,... |
use std::collections::HashMap;
use serde::de::{DeserializeSeed, MapAccess};
use crate::Element;
use crate::error::TychoError;
use crate::serde::de::ident::TychoIdentDeserializer;
use crate::serde::de::TychoDeserializer;
pub struct StructDeserializer {
map: HashMap<String, Element>,
value: Option<Element>
}
... |
#[doc = "Register `ARGR` reader"]
pub type R = crate::R<ARGR_SPEC>;
#[doc = "Register `ARGR` writer"]
pub type W = crate::W<ARGR_SPEC>;
#[doc = "Field `CMDARG` reader - Command argument These bits can only be written by firmware when CPSM is disabled (CPSMEN = 0). Command argument sent to a card as part of a command me... |
extern crate ocl;
extern crate minifb;
use minifb::{Key, Window, WindowOptions, MouseMode, KeyRepeat, MouseButton};
use std::time::Instant;
#[allow(unused_imports)]
use std::f32::consts::{FRAC_PI_8, FRAC_PI_4, FRAC_PI_2, PI};
use std::collections::HashSet;
use ocl::ProQue;
use ocl::prm::{Uint, Float3};
mod scene_ob... |
use super::heap_parameters::*;
use crate::util::constants::*;
use crate::util::Address;
use crate::util::conversions::{chunk_align_down, chunk_align_up};
/** log_2 of the addressable virtual space */
#[cfg(target_pointer_width = "64")]
pub const LOG_ADDRESS_SPACE: usize = LOG_SPACE_SIZE_64 + LOG_MAX_SPACES;
#[cfg(tar... |
use super::HttpEvent;
use std::fmt;
use std::error::Error;
pub enum ReaderError {
InvalidMetadata {name: String, reason: String},
InvalidEncoding {content_type: String, reason: String},
Other(Box<dyn Error>)
}
impl fmt::Display for ReaderError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result... |
struct Tree {
val: i32,
left: Option<Box<Tree>>,
right: Option<Box<Tree>>,
}
impl Tree {
fn new(val: i32) -> Self {
Tree {
val,
left: None,
right: None,
}
}
fn insert(&mut self, val: i32) {
let next_node = if val >= self.val {
... |
extern crate ares;
use ares::AresError::*;
use std::vec::Vec;
#[macro_use]
mod util;
#[test]
fn basic() {
eval_ok!("((lambda () 1))", 1);
eval_ok!("((lambda (a) (+ a 2)) 3)", 5);
eval_ok!("((lambda (a b) (+ a b)) 3 4)", 7);
}
#[test]
fn nested() {
eval_ok!(
r"(((lambda (a b)
(lambd... |
use std::cell::RefCell;
use std::rc::Rc;
use gtk::prelude::*;
use nvim_rs::Tabpage;
use crate::nvim_gio::{GioNeovim, GioWriter};
use crate::ui::color::{Color, HlDefs, HlGroup};
use crate::ui::common::{calc_line_space, spawn_local};
use crate::ui::font::{Font, FontUnit};
#[derive(Default)]
pub struct TablineColors {... |
#![deny(clippy::pedantic)]
#![allow(incomplete_features)]
#![feature(generic_associated_types)]
#![feature(total_cmp)]
#[macro_use]
extern crate contracts;
pub mod cogs;
pub mod event_log;
|
use crate::{Net, Node, Spec, DEFAULT_TX_PROPOSAL_WINDOW};
use ckb_types::{
bytes::Bytes,
core::{Capacity, TransactionView},
prelude::*,
};
use log::info;
pub struct TemplateTxSelect;
impl Spec for TemplateTxSelect {
crate::name!("template_tx_select");
fn run(&self, net: &mut Net) {
self.s... |
use super::*;
pub struct Part1<T>(::std::marker::PhantomData<T>);
impl<T> Solve<T> for Part1<T>
where T: AsRef<str> {
type Output = usize;
fn solve(input: T) -> <Self as Solve<T>>::Output {
react_polymer(input.as_ref().chars()).len()
}
}
pub struct Part2<T>(::std::marker::PhantomData<T>);
i... |
/// MergePullRequestForm form for merging Pull Request
#[derive(Debug, Default, Clone, Serialize, Deserialize)]
pub struct MergePullRequestOption {
#[serde(rename = "Do")]
pub do_: crate::merge_pull_request_option::MergePullRequestOptionDo,
#[serde(rename = "MergeMessageField")]
pub merge_message_field... |
use libc::c_void;
pub struct GrpSprite;
#[repr(C, packed)]
pub struct RemapPalette {
pub id: u32,
pub data: *const u8,
pub name: [u8; 0xc],
}
#[derive(Serialize, Deserialize, Clone, Copy)]
#[repr(C)]
pub struct Iscript {
pub header: u16,
pub pos: u16,
pub return_pos: u16,
pub animation_id... |
use std::io;
use std::io::Write;
fn write_to<T>(stream: &mut T, string: String) where T: Write {
stream.write(string.as_bytes()).unwrap();
stream.flush().unwrap();
}
pub fn print(string: String) {
write_to(&mut io::stdout(), string);
}
pub fn print_err(string: String) {
write_to(&mut io::stderr(), string);
}... |
#![deny(rust_2018_idioms)]
use tracing::Level;
use tracing_subscriber::prelude::*;
#[tracing::instrument]
fn shave(yak: usize) -> bool {
tracing::debug!(
message = "hello! I'm gonna shave a yak.",
excitement = "yay!"
);
if yak == 3 {
tracing::warn!(target: "yak_events", "could not ... |
#[doc = "Reader of register IC_FS_SPKLEN"]
pub type R = crate::R<u32, super::IC_FS_SPKLEN>;
#[doc = "Writer for register IC_FS_SPKLEN"]
pub type W = crate::W<u32, super::IC_FS_SPKLEN>;
#[doc = "Register IC_FS_SPKLEN `reset()`'s with value 0x07"]
impl crate::ResetValue for super::IC_FS_SPKLEN {
type Type = u32;
... |
use crate::common::*;
use anyhow::Result;
use chrono::serde::{ts_seconds, ts_seconds_option};
use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use serde_aux::prelude::*;
use serde_repr::{Deserialize_repr, Serialize_repr};
use std::str;
#[derive(Serialize_repr, Deserialize_repr, PartialEq, Debug)]
#[re... |
extern crate rocket_contrib;
extern crate sl_lib;
extern crate tera;
use diesel::prelude::*;
// use rocket::request::Form;
use rocket_contrib::Template;
use tera::Context;
use sl_lib::models::Post;
use sl_lib::*;
#[get("/blog")]
pub fn index(connection: DbConn) -> Template {
use schema::posts::dsl::*;
// u... |
//! Statically allocated stacks
//!
//! These stacks are referenced in the TSS.
//!
//! It should be noted that `kstart` still utilizes the stack defined in
//! boot/boot32.s. Upon transitioning back from userspace to kernelspace, we
//! begin using the DEFAULT stack.
/// The default stack used by the kernel when tran... |
mod fun;
use std::{ops::Deref, sync::Arc};
use fun::Tree;
#[derive(Debug, Clone, Copy)]
struct Inode(u64);
#[derive(Debug, Clone)]
struct File {
inode: Inode,
}
#[derive(Debug, Clone, Default)]
struct Dir {
nodes: Tree<String, Arc<Node>>,
}
#[derive(Debug, Clone)]
enum Node {
File(File),
Dir(Dir),
}... |
/// address: identifier of an actor
/// messaging is best effort at most one message
/// message queue persisted outside the actor instance
/// respond with 0 or many messages
/// local state
/// side effects
///
/// examples of actor
/// supervisor : monitor and manage another actor
/// message forwarding : forward m... |
use futures_util::StreamExt;
use howto::*;
use std::convert::TryInto;
use structopt::StructOpt;
#[derive(Debug, StructOpt)]
struct Opt {
/// Select answer in specified position
#[structopt(short, long, default_value = "0", parse(try_from_str))]
position: u64,
/// Whether display only the answer link
... |
use crate::prelude::*;
pub mod prelude {
pub use super::Neg;
}
/// The arithmetic negation term expression.
///
/// This negate the inner term expression.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct Neg {
/// The inner child formula expression.
pub child: P<AnyExpr>,
/// The bit width of t... |
use super::{Cartridge, Mapper, Mirror, serialize::*};
use std::fs::File;
use std::io::{Read, Write};
use std::path::Path;
pub struct Mmc1 {
cart: Cartridge,
step: u8,
shift_register: u8,
mirroring: Mirror,
control: u8,
prg_ram_bank: Vec<u8>, // CPU $6000-$7FFF
prg_ram_enabled: bool,
... |
#[doc = "Register `MDIER4` reader"]
pub type R = crate::R<MDIER4_SPEC>;
#[doc = "Register `MDIER4` writer"]
pub type W = crate::W<MDIER4_SPEC>;
#[doc = "Field `MCMP1IE` reader - MCMP1IE"]
pub type MCMP1IE_R = crate::BitReader;
#[doc = "Field `MCMP1IE` writer - MCMP1IE"]
pub type MCMP1IE_W<'a, REG, const O: u8> = crate:... |
use super::args::{MultipleReports, OutputAbundance, OutputPhylo, SingleReport};
#[derive(Clap, Debug)]
#[non_exhaustive]
pub enum Command {
// Info(Info),
ConvertTree(ConvertTree),
ConvertAbundance(ConvertAbundance),
CombineTrees(CombineTrees),
CombineAbundances(CombineAbundances),
// Track(Trac... |
// mod print;
// mod vars;
// mod types;
// mod strings;
// mod tuples;
// mod rays;
// mod vector;
// mod conditional;
// mod loops;
// mod functions;
// mod pointer_ref;
// mod structs;
// mod enums;
mod cli;
fn main() {
// print::run();
// vars::run();
// types::run();
// strings::run();
// tu... |
use iroh::lens::Lens;
use iroh_codegen::Lens;
#[derive(Lens)]
pub struct Rect {
width: f32,
height: f32,
}
#[derive(Lens)]
pub struct Vec2(f32, f32);
#[test]
fn test_struct_lenses() {
let r = Rect {
width: 1.0,
height: 2.0,
};
assert_eq!(1.0, *RectWidthLens::get(&r));
assert_... |
#[allow(unused_parens)]
pub fn verse(n: i32) -> String {
match n {
2 => String::from("2 bottles of beer on the wall, 2 bottles of beer.\nTake one down and pass it around, 1 bottle of beer on the wall.\n"),
1 => String::from("1 bottle of beer on the wall, 1 bottle of beer.\nTake it down and pass... |
// Copyright (c) 2015, <daggerbot@gmail.com>
// All rights reserved.
use std;
use libc::{
c_char,
c_int,
c_long,
c_short,
c_uchar,
c_uint,
c_ulong,
c_ushort,
c_void,
};
//
// functions
//
#[link(name="X11")]
extern "C" {
pub fn XAllocColor (display: *mut Display, colormap: Colormap, color: *mut... |
use crate::SeqNumber;
use std::time::Duration;
/// Congestion control trait, sender side
///
/// Used to define custom congestion control
pub trait CongestCtrl {
fn init(&mut self, _init_seq_num: SeqNumber) {}
/// When an ACK packet is received
fn on_ack(&mut self, _data: &CCData) {}
/// When a NAK p... |
#[doc = "Reader of register ACCU_WINDOW_WIDEN_STATUS"]
pub type R = crate::R<u32, super::ACCU_WINDOW_WIDEN_STATUS>;
#[doc = "Reader of field `ACCU_WINDOW_WIDEN`"]
pub type ACCU_WINDOW_WIDEN_R = crate::R<u16, u16>;
impl R {
#[doc = "Bits 0:15 - Accumulated Window Widen Value. HW updates this register at the close of... |
use std::fmt::{Display, Formatter};
use std::sync::mpsc::Sender;
use std::sync::{Arc, Mutex};
use std::thread;
use std::time::SystemTime;
use std::time::Duration;
use std::f64::consts::E;
use std::f32::NAN;
use std::fs;
use std::path::Path;
use std::io::Error as IoError;
use std::num::ParseIntError;
use std::collectio... |
fn main() {
let n: usize = {
let mut line = String::new();
std::io::stdin().read_line(&mut line).unwrap();
line.trim_end().parse().unwrap()
};
let t: String = {
let mut line = String::new();
std::io::stdin().read_line(&mut line).unwrap();
line.trim_end().to_ow... |
extern crate rand;
extern crate crypto;
extern crate rustc_serialize;
extern crate chrono;
use std::io::{self, Write, BufRead};
// use rusqlite::Connection;
// TODO: Fix these two functions.
// Convert slice to string vector
// Input text Slice to convert (&[u8])
// Output Vec<String> String vect... |
mod cmdline;
#[cfg(feature = "watch")]
mod watcher;
#[cfg(feature = "webui")]
mod server;
use async_std::{
channel::{unbounded, Sender},
fs::File,
io::ReadExt,
};
use cmdline::{Args, Print};
use gear::{qjs, Map, Ref, Result, Set};
use std::env;
#[paw::main]
#[async_std::main]
async fn main(args: Args) -... |
use clap::{Arg, App};
use std::path::Path;
struct Options {
survey_count: u64,
output_dir: &Path,
}
fn parse_options() -> &Options {
let matches = App::new("Survey Generator")
.arg(Arg::with_name("survey_count")
.short("c")
.long("survey-count")
.value_name("N")
.help("count of... |
//! [![github]](https://github.com/dtolnay/trybuild) [![crates-io]](https://crates.io/crates/trybuild) [![docs-rs]](https://docs.rs/trybuild)
//!
//! [github]: https://img.shields.io/badge/github-8da0cb?style=for-the-badge&labelColor=555555&logo=github
//! [crates-io]: https://img.shields.io/badge/crates.io-f... |
use std::iter::FromIterator;
use log::trace;
use log::{debug, error, info, warn};
use crate::touch;
use crate::{call_original, hook};
/// A loaded game script. This struct is compatible with the game's representation of loaded scripts,
/// but does not use all the fields that it could. As such, not all game function... |
extern crate csv;
use queries;
#[derive(RustcDecodable)]
struct Invitee {
name: String,
email: String,
}
pub fn migrate() {
let mut reader = csv::Reader::from_file("invitees.csv").unwrap();
for record in reader.decode() {
let invitee: Invitee = record.unwrap();
queries::create(invitee... |
#[derive(Debug, thiserror::Error)]
pub enum PpError {
#[error("io error")]
IoError(#[from] tokio::io::Error),
#[error("failed to prepare beatmap file")]
MapFile(#[from] crate::error::MapFileError),
#[error("error while parsing beatmap file")]
Parse(#[from] rosu_pp::ParseError),
}
|
#[doc = "Register `SYSCFG_CMPENCLRR` reader"]
pub type R = crate::R<SYSCFG_CMPENCLRR_SPEC>;
#[doc = "Register `SYSCFG_CMPENCLRR` writer"]
pub type W = crate::W<SYSCFG_CMPENCLRR_SPEC>;
#[doc = "Field `MPU_EN` reader - MPU_EN"]
pub type MPU_EN_R = crate::BitReader;
#[doc = "Field `MPU_EN` writer - MPU_EN"]
pub type MPU_E... |
//! Tests that no `&'static mut` to static mutable resources can be obtained, which would be
//! unsound.
//!
//! Regression test for https://github.com/rust-embedded/cortex-m-rt/issues/212
#![no_std]
#![no_main]
extern crate cortex_m_rt;
extern crate panic_halt;
use cortex_m_rt::{entry, exception, interrupt, Except... |
/*
* 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
*/
/// WidgetMarker : Markers allow you to add visual conditional formatting for your graphs.
#[derive(C... |
/*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
use juno::ast::*;
use juno::gen_js::*;
fn do_gen(node: &Node) -> String {
let mut out: Vec<u8> = vec![];
generate(&mut out... |
// 1. Each value in Rust has a variable that’s called its owner.
// 2. There can only be one owner at a time.
// 3. When the owner goes out of scope, the value will be dropped.
fn main() {
// Both values equal 5, variables on stack
let x = 5;
let y = x;
println!("x: {}", x);
println!("y: {}", y);
... |
use core::{fmt, str::FromStr};
use nom::{types::CompleteStr, *};
use crate::ir::FnSig;
// NOTE we don't keep track of pointers; `i8` and `i8*` are both considered `Type::Integer`
#[derive(Clone, Debug, Eq, Hash, PartialEq)]
pub enum Type<'a> {
// `%"crate::module::Struct::<ConcreteType>"`
Alias(&'a str),
... |
extern crate stripe;
use stripe::connection::Connection;
use std::env;
fn usage(args: &Vec<String>) {
println!("Usage: {} customer_id", args[0]);
}
fn main() {
let args: Vec<_> = env::args().collect();
match &args.len() {
&0 => unreachable!(),
&2 => fetch_and_print_cards(&args[1]),
... |
#[doc = r"Register block"]
#[repr(C)]
pub struct RegisterBlock {
#[doc = "0x00 - Access control register"]
pub acr: ACR,
#[doc = "0x04 - Power down key register"]
pub pdkeyr: PDKEYR,
#[doc = "0x08 - Flash key register"]
pub keyr: KEYR,
#[doc = "0x0c - Option byte key register"]
pub optke... |
//! Deserializes configuration options.
use std::error;
use std::fmt::{self, Display};
use std::fs::File;
use std::io::{self, Read};
use std::path::{Path, PathBuf};
use super::keybinds::{Keybinds, KeybindsFromYaml};
use crate::cli::ConfigCli;
use directories_next::ProjectDirs;
use serde::Deserialize;
type ConfigResu... |
use std::io::{self, Read};
use regex::Regex;
fn read_stdin() -> String{
let mut buffer = String::new();
io::stdin().read_to_string(&mut buffer).expect("did not recieve anything from stdin");
return buffer;
}
#[derive(Debug, Clone, Hash, PartialEq, Eq)]
struct Coord{
x: i64,
y: i64,
z: i64
}
impl Coo... |
use alloc::alloc::Layout;
#[alloc_error_handler]
fn alloc_error(layout: Layout) -> ! {
use crate::serial_println;
serial_println!("Alloc failed miserably ! layout {:?}", layout);
panic!("Failed to allocate");
}
use linked_list_allocator::LockedHeap;
#[global_allocator]
static ALLOCATOR: LockedHeap =... |
use itertools::Itertools;
use std::collections::HashMap;
use std::time::{Duration, Instant};
use rand::distributions::{Distribution, Uniform};
fn main() {
let min_verticies = 100;
let max_verticies = 1000;
let step_verticies = 100;
let min_edges = 100;
let max_edges = 1000;
let step_edges = 10... |
use crate::{
multiaddr::{self, Multiaddr},
peer_store::{types::MultiaddrExt, PeerStore, Status, ADDR_COUNT_LIMIT},
Behaviour, PeerId, SessionType,
};
#[test]
fn test_add_connected_peer() {
let mut peer_store: PeerStore = Default::default();
let peer_id = PeerId::random();
let addr = "/ip4/127.0... |
//! Compute lines on multiple spans of text.
//!
//! The input is a list of consecutive text spans.
//!
//! Computed rows will include a list of span segments.
//! Each segment include the source span ID, and start/end byte offsets.
mod lines_iterator;
mod chunk_iterator;
mod segment_merge_iterator;
mod row;
mod prefix... |
use crate::timer::Timer;
use glium::glutin::event::Event;
use sodium_rust::StreamSink;
pub struct Input<CustomEvent>
where
CustomEvent: 'static,
{
pub event: StreamSink<Event<'static, CustomEvent>>,
pub timer: Timer,
}
|
/*
* 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
*/
/// LogsFilter : Filter for logs.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub stru... |
use hello_api::hello_api_client::HelloApiClient;
use hello_api::HelloRequest;
pub mod hello_api {
tonic::include_proto!("hello");
}
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let mut client = HelloApiClient::connect("http://[::1]:50051").await?;
println!("RESPONSE={:?}", c... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.