text stringlengths 8 4.13M |
|---|
#![warn(clippy::all)]
#![warn(clippy::pedantic)]
fn main() {
run();
}
fn run() {
let start = std::time::Instant::now();
// code goes here
let res = recurse(0, 0);
let span = start
.elapsed()
.as_nanos();
println!("{} {}", res, span);
}
const COINS: &[u64] = &[1, 2, 5, 10, 20, 50, 100, 200];
con... |
use std::error::Error;
/// HTTPS capable synchronous client.
pub trait HttpsClient {
fn get(&self, url: &str) -> Result<String, Box<dyn Error>>;
}
#[test]
fn assert_https_client_object_safety() {
struct NoneHttpsClient;
impl HttpsClient for NoneHttpsClient {
fn get(&self, _url: &str) -> Result<St... |
use crate::api::v1::ceo::option::model::{Delete, Get, GetList, New, Update};
use crate::errors::ServiceError;
use crate::models::option::{Opt as Object, OptRes};
use crate::models::DbExecutor;
use crate::schema::option::dsl::{deleted_at, html_type, id, name, option as tb, price, shop_id};
use actix::Handler;
use diese... |
use regex::Regex;
pub fn new_re(s: &str) -> Regex {
Regex::new(s).unwrap()
}
pub fn re_captures<'a>(re: &Regex, s: &'a str) -> impl Iterator<Item = &'a str> {
re.captures(s)
.unwrap()
.iter()
.skip(1)
.map(|om| om.map_or("", |m| m.as_str()))
.collect::<Vec<_>>() // Not ... |
mod drawing_window;
mod grid_panel;
mod widget;
mod scroll_panel;
mod h_scroll;
use drawing_window::DrawingWindow;
use grid_panel::GridPanel;
use widget::Widget;
use scroll_panel::ScrollPanel;
fn main() {
let mut red_scroll = Box::new(ScrollPanel::new());
let mut green_scroll = Box::new(ScrollPanel::new());
... |
#[derive(Debug, Serialize, Deserialize)]
pub struct Command {
pub command: CommandType,
pub data: String,
}
#[derive(Debug, Serialize, Deserialize, ToString, PartialEq)]
pub enum CommandType {
NodeElementList,
DiscoveryEnable,
DiscoveryDisable,
AddToUnregisteredList, // From BlackBox to WebInte... |
#![feature(decl_macro)]
use rocket::{self, get,post,routes};
use serde::{Serialize, Deserialize};
use rocket_contrib::json::Json;
extern crate serde_json;
use serde_json::Value;
use std::string::String;
//use std::fmt;
//use std::fmt::Display;
#[derive(Default, Debug, Clone, PartialEq, serde_derive::Serialize, serde... |
use std::collections::HashSet;
use std::fs::{read_dir, File};
use std::io::prelude::*;
use std::io::{self, BufReader, BufWriter};
use regex::Regex;
use serde::{Deserialize, Serialize};
#[derive(Deserialize)]
pub struct InputRecipe {
title: String,
external_id: String,
external_source: String,
external... |
pub const VRAM_START: u32 = 0x00000000;
pub const VRAM_LENGTH: u32 = 0x00040000;
pub const VRAM_END: u32 = VRAM_START + VRAM_LENGTH - 1;
pub const CHR_RAM_PATTERN_TABLE_0_START: u32 = 0x00006000;
pub const CHR_RAM_PATTERN_TABLE_0_LENGTH: u32 = 0x00002000;
pub const CHR_RAM_PATTERN_TABLE_1_START: u32 = 0x0000e000;
pub... |
use procon_reader::ProconReader;
fn main() {
let stdin = std::io::stdin();
let mut rd = ProconReader::new(stdin.lock());
let x: u32 = rd.get();
if x < 40 {
println!("{}", 40 - x);
} else if x < 70 {
println!("{}", 70 - x);
} else if x < 90 {
println!("{}", 90 - x);
... |
use std::{env, marker::PhantomData, path};
use super::Module;
use crate::{terminal::Color, Segment, R};
pub struct Cwd<S: CwdScheme> {
max_length: usize,
wanted_seg_num: usize,
resolve_symlinks: bool,
scheme: PhantomData<S>,
}
pub trait CwdScheme {
const CWD_FG: Color;
const PATH_FG: Color;
const PATH_BG: Col... |
#[doc = r"Value to write to the register"]
pub struct W {
bits: u32,
}
impl super::IC {
#[doc = r"Writes to the register"]
#[inline(always)]
pub fn write<F>(&self, f: F)
where
F: FnOnce(&mut W) -> &mut W,
{
self.register.set(
f(&mut W {
bits: Self::res... |
//! Event types for runtimes.
use oasis_core_runtime::transaction::tags::Tag;
/// An event emitted by the runtime.
///
/// This trait can be derived:
/// ```
/// # #[cfg(feature = "oasis-runtime-sdk-macros")]
/// # mod example {
/// # use oasis_runtime_sdk_macros::Event;
/// const MODULE_NAME: &str = "my-module";
/// ... |
//! Sum all the bytes of a data structure or an array.
//!
//! A commonly used method to ensure the validity of data is to calculate
//! the sum of all the bytes, and compare it to a known value.
//!
//! **Note**: if you need a way to ensure data integrity, use some better algorithm like CRC-32.
//! This crate is only ... |
pub const NODE_PUBLIC : usize = 28;
pub const NODE_PRIVATE : usize = 32;
pub const ACCOUNT_ID : usize = 0;
pub const FAMILY_SEED : usize = 33;
pub const ED25519_SEED : [u8; 3] = [0x01, 0xe1, 0x4b];
pub const SIGN_TYPE : [&'static str; 2] = ["ed25519", "secp256k1"];
pub trait BaseDataI {
fn get_version(&s... |
use std::fmt::Debug;
#[derive(Debug)]
struct Vehicle {
handbrake_enabled: bool
}
fn manifest_presence<T>(v: T) -> T
where T: Debug
{
println!("Me be: {:?}", v);
v
}
type CPS = Box<Fn(Vehicle) -> Vehicle>;
fn vehicle_run(cps: CPS) -> CPS {
Box::new(move |v: Vehicle| {
let v: Vehicle = cp... |
use super::default_process_fn;
use super::Printer;
use crossterm::style::Color;
use std::io::Write;
type Result<T> = std::result::Result<T, Box<dyn std::error::Error>>;
#[test]
fn write_from_terminal_start_cursor_pos_correct() -> Result<()> {
let mut p = Printer::new(std::io::sink(), "".to_owned());
let origi... |
use std::cmp::Ordering;
use std::sync::Arc;
use askama::Template;
use crate::db::Db;
use crate::error::Error;
use crate::fetcher::Currency;
#[derive(Template)]
#[template(path = "index.html")]
struct CurrenciesTemplate<'a> {
date: &'a str,
currencies: &'a [Currency],
}
// order currencies so that EUR comes ... |
//! This file exposes a single function, monitor, that is launched in a special
//! thread and pulls the evaluations results, store them and then updates the
//! Store accordingly.
use crate::device::Context;
use crate::explorer::candidate::Candidate;
use crate::explorer::config::Config;
use crate::explorer::logger::Lo... |
//! TODO docs
use crate::action::Action;
use crate::bytes::{NumBytes, Read, Write};
use crate::time::TimePointSec;
use crate::varint::UnsignedInt;
use alloc::vec::Vec;
/// TODO docs
#[derive(
Read,
Write,
NumBytes,
PartialEq,
Eq,
PartialOrd,
Ord,
Debug,
Clone,
Hash,
Default,... |
// This file was generated by gir (https://github.com/gtk-rs/gir)
// from gir-files (https://github.com/gtk-rs/gir-files)
// DO NOT EDIT
#[cfg(any(feature = "v2_12", feature = "dox"))]
use glib::translate::*;
#[cfg(any(feature = "v2_12", feature = "dox"))]
use glib::GString;
use webkit2_webextension_sys;
glib_wrapper... |
use libc;
use libc::toupper;
use crate::clist::*;
use crate::mailimf_types::*;
use crate::mailmime_decode::*;
use crate::mailmime_types::*;
use crate::mmapstring::*;
use crate::x::*;
pub const UNSTRUCTURED_START: libc::c_uint = 0;
pub const UNSTRUCTURED_LF: libc::c_uint = 2;
pub const UNSTRUCTURED_CR: libc::c_uint = ... |
use crate::archives::Id;
use crate::archives::packages::patches::Version;
use aes_gcm_siv::{Aes256GcmSiv};
use aes_gcm_siv::aead::{Aead, NewAead, generic_array::GenericArray};
pub const KEY_LENGTH: usize = 16;
pub const NONCE_LENGTH: usize = 12;
pub type Key = [u8; KEY_LENGTH];
pub type Nonce = [u8; NONCE_LENGTH];//G... |
//! Build script for chars.
//!
//! This just runs the generator/ subproject, to generate the source files from files in data/.
use std::env;
use std::error::Error;
use std::path::Path;
extern crate chars_data;
fn main() -> Result<(), Box<dyn Error>> {
let out_dir = env::var("OUT_DIR")?;
chars_data::generate... |
// Copyright 2022 Datafuse Labs.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to ... |
use core::{
convert::TryInto,
default::Default,
fmt::{self, Write},
ops::{Add, Sub},
};
use num_derive::FromPrimitive;
/// The default starting location of the vga text mode framebuffer.
pub const DEFAULT_VGA_TEXT_BUFF_START: *mut VgatBuffer<
DEFAULT_VGA_TEXT_BUFF_WIDTH,
DEFAULT_VGA_TEXT_BUFF_H... |
#![feature(test)]
use fraction::Fraction;
use projecteuler::fraction;
use projecteuler::helper;
fn main() {
dbg!(solve(8));
dbg!(solve(1_000_000));
helper::time_it(
|| {
core::hint::black_box(solve(1_000_000));
},
100,
);
}
fn solve(d: usize) -> Fraction<usize> {
... |
use super::super::generator::MazeGenerator;
use super::super::grid::{Grid, BasicGrid};
use super::super::Tile;
pub fn test_gen<T: MazeGenerator>(width: usize, height: usize)
{
let mut test_grid = BasicGrid::new(width, height);
T::generate(&mut test_grid);
for j in 0..height
{
for i in 0..widt... |
#![allow(non_snake_case, non_camel_case_types, non_upper_case_globals, clashing_extern_declarations, clippy::all)]
#[link(name = "windows")]
extern "system" {}
pub type ActivationSignalDetectionConfiguration = *mut ::core::ffi::c_void;
pub type ActivationSignalDetectionConfigurationCreationResult = *mut ::core::ffi::c_... |
#![allow(non_snake_case, non_camel_case_types, non_upper_case_globals, clashing_extern_declarations, clippy::all)]
#[link(name = "windows")]
extern "system" {}
#[repr(transparent)]
pub struct ApplicationProfileModes(pub u32);
impl ApplicationProfileModes {
pub const Default: Self = Self(0u32);
pub const Alterna... |
extern crate log;
use clap::{crate_version, App, Arg, ArgMatches};
use std::time::Duration;
use unmoved_mover::daemon;
fn get_arg_key(matches: &ArgMatches, name: &str) -> String {
let key: String = matches
.value_of(name)
.expect(&*format!("Invalid {name}", name = name))
.to_string();
... |
#[macro_use]
extern crate horrorshow;
extern crate hyper;
extern crate iron;
extern crate mount;
extern crate staticfile;
use horrorshow::prelude::*;
use iron::headers::ContentType;
use iron::modifiers::Header;
use iron::prelude::*;
use iron::status;
use mount::Mount;
use staticfile::Static;
use std::path::Path;
fn m... |
mod entry;
use crate::entry::{*, Error, print_entries};
use std::{io::{stdout, Write}, iter::{Cycle, Enumerate}, thread::sleep, time::Duration};
use rand::Rng;
use clap::{App, load_yaml};
use crossterm::{cursor::{Hide, Show}, execute, style::Color};
const COLORS: [Color; 8] = [Color::Blue, Color::Red, Color::Cyan, ... |
use maud::{html, Markup};
use crate::models::shop::Shop;
use crate::views;
pub fn list(entries:Vec<(String, Shop)>) -> Markup {
let content = html! {
div class="row" {
div class="col s12 l6" {
div class="card" {
div class="card-image" {
a href="/shops/0" class="btn-floating halfway-fab blue darken... |
#![allow(unused_imports)]
#![allow(dead_code)]
#![allow(non_snake_case)]
use std::fs;
use std::process;
use std::env;
use std::path::PathBuf;
use anyhow::Result;
use serde_json;
use super::system::*;
impl System
{
//
pub fn Make() -> System
{
/*
issue : https://github.com/Learn-Together-Pro/Blockchai... |
use crate::lib::{default_sub_command, file_to_string, Command};
use anyhow::Error;
use clap::{value_t_or_exit, App, Arg, ArgMatches, SubCommand};
use nom::{
branch::alt,
bytes::complete::{tag, take, take_till1, take_until},
combinator::{map, map_parser},
multi::{fold_many1, separated_list0, separated_li... |
// Copyright (c) 2021 Quark Container Authors / 2018 The gVisor 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 ... |
mod test_utils;
use async_std::prelude::*;
use async_std::sync;
use async_std::task;
use std::time::Duration;
use tide::{JobContext, Request};
#[test]
fn jobs() -> Result<(), http_types::Error> {
#[derive(Default)]
struct Counter {
count: sync::Mutex<i32>,
}
task::block_on(async {
let... |
mod battery;
mod iterator;
mod manager;
mod state;
mod technology;
pub use self::battery::Battery;
pub use self::iterator::Batteries;
pub use self::manager::Manager;
pub use self::state::State;
pub use self::technology::Technology;
|
mod bar;
mod canvas;
mod color_button;
mod note;
|
#![allow(unused_variables, non_upper_case_globals, non_snake_case, unused_unsafe, non_camel_case_types, dead_code, clippy::all)]
pub const CDB_REPORT_BITS: u32 = 0u32;
pub const CDB_REPORT_BYTES: u32 = 1u32;
pub const COMDB_MAX_PORTS_ARBITRATED: u32 = 4096u32;
pub const COMDB_MIN_PORTS_ARBITRATED: u32 = 256u32;
#[inlin... |
use crate::prelude::*;
use std::os::raw::c_void;
use std::ptr;
#[repr(C)]
#[derive(Debug)]
pub struct VkWaylandSurfaceCreateInfoKHR {
pub sType: VkStructureType,
pub pNext: *const c_void,
pub flags: VkWaylandSurfaceCreateFlagBitsKHR,
pub display: *mut c_void,
pub surface: *mut c_void,
}
impl VkWa... |
use std::{
fs::{self, File, OpenOptions},
io::Write,
path::{Path, PathBuf},
};
use rand::{thread_rng, Rng};
use tempfile::TempDir;
pub struct TestDir(TempDir);
const RAND_BYTES: usize = 512;
impl TestDir {
pub fn new() -> TestDir {
let tempdir = tempfile::Builder::new()
.prefix(e... |
use std::collections::hash_map::RandomState;
use std::collections::HashMap;
use std::hash::{BuildHasher, Hash};
use bumpalo::Bump;
use crate::util::{GridDomain, IndexDomain};
use crate::{Cell, Owner, SearchNode};
use super::NodePool;
pub struct HashPool<V, S = RandomState> {
map: Cell<HashMap<V, *const Cell<Sea... |
/*
* Christopher Piraino
*
* An implementation of the Fibonacci Heap
* for use in network algorithms.
*/
extern crate collections = "collections#0.11-pre";
use collections::dlist::DList;
use collections::deque::Deque;
use std::option::Option;
use std::cast;
pub type FibEntry<K,V> = *mut FibNode<K,V>;
trait HeapEn... |
use futures_core::Stream;
use std::future::Future;
use std::mem::take;
use std::{
pin::Pin,
sync::{Arc, Mutex},
task::{Context, Poll},
};
struct YielderState<T: Unpin> {
value: Option<T>,
}
pub struct YielderFuture<T: Unpin> {
state: Arc<Mutex<YielderState<T>>>,
}
impl<T: Unpin> Future for Yielde... |
use crate::Error;
use cavalier_contours::polyline::{PlineCreation, PlineSource, PlineSourceMut, Polyline};
use geo::{Densify, EuclideanLength, Winding};
use geo_types::{Line, LineString, Polygon, Rect};
use h3ron::collections::HashSet;
use h3ron::{H3Cell, ToCoordinate, ToH3Cells, ToPolygon};
use ordered_float::OrderedF... |
use crate::load_function_ptrs;
use crate::prelude::*;
use std::os::raw::c_void;
load_function_ptrs!(DeviceWSIFunctions, {
vkQueuePresentKHR(queue: VkQueue, pPresentInfo: *const VkPresentInfoKHR) -> VkResult,
vkCreateSwapchainKHR(
device: VkDevice,
pCreateInfo: *const VkSwapchainCreateInfoKHR,... |
use std::collections::{hash_map::Entry, HashMap};
use std::path::{Path, PathBuf};
use crate::fs::LllDirList;
use crate::sort;
pub trait DirectoryHistory {
fn populate_to_root(
&mut self,
pathbuf: &PathBuf,
sort_option: &sort::SortOption,
) -> std::io::Result<()>;
fn pop_or_create(
... |
//! Display an interactive selector of a single value from a range of values.
//!
//! A [`Slider`] has some local [`State`].
//!
//! [`Slider`]: struct.Slider.html
//! [`State`]: struct.State.html
use crate::{style, Bus, Element, Length, Widget};
use dodrio::bumpalo;
use std::{ops::RangeInclusive, rc::Rc};
/// An hor... |
//! RPC interface for the transaction payment module.
use jsonrpc_core::{Error as RpcError, ErrorCode, Result};
use jsonrpc_derive::rpc;
use sp_api::ProvideRuntimeApi;
use sp_blockchain::HeaderBackend;
use sp_runtime::{generic::BlockId, traits::Block as BlockT};
use std::sync::Arc;
use massbit_runtime_api::MassbitApi ... |
fn main() {
let n = {
let mut s = String::new(); // バッファを確保
std::io::stdin().read_line(&mut s).unwrap(); // 一行読む。失敗を無視
s.trim_end().to_owned() // 改行コードが末尾にくっついてくるので削る
};
let n: i32 = n.parse().unwrap();
println!("{}", n * 2);
}
|
// 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 ... |
//! Day 7
use std::{
collections::{HashMap, HashSet},
hash::Hash,
};
trait Solution {
fn part_1(&self) -> usize;
fn part_2(&self) -> usize;
}
impl Solution for str {
fn part_1(&self) -> usize {
bfs(
"shiny gold",
&build_containee_map(&parsers::input(self).expect("Fa... |
use point::Point;
pub struct Apple {
pub location: Point,
}
impl Apple {
pub fn new(x: i32, y: i32) -> Apple {
Apple { location: Point { x: x, y: y } }
}
} |
#![allow(non_snake_case, non_camel_case_types, non_upper_case_globals, clashing_extern_declarations, clippy::all)]
#[link(name = "windows")]
extern "system" {
#[cfg(feature = "Win32_Foundation")]
pub fn D3DCompile(psrcdata: *const ::core::ffi::c_void, srcdatasize: usize, psourcename: super::super::super::Founda... |
//! Type aliases for using `deadpool-diesel` with PostgreSQL.
/// Connection which is returned by the PostgreSQL pool
pub type Connection = crate::Connection<diesel::PgConnection>;
/// Manager which is used to create PostgreSQL connections
pub type Manager = crate::manager::Manager<diesel::PgConnection>;
/// Pool fo... |
#[macro_use]
extern crate criterion;
extern crate geo;
use criterion::Criterion;
use geo::prelude::*;
use geo::simplifyvw::SimplifyVWPreserve;
use geo::LineString;
fn criterion_benchmark(c: &mut Criterion) {
c.bench_function("simplify vw simple f32", |bencher| {
let points = include!("../src/algorithm/tes... |
// Copyright 2021 Datafuse Labs.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to ... |
use nalgebra_glm as glm;
use petgraph::{prelude::*, visit::Dfs};
use sepia::app::*;
use sepia::{camera::*, gltf::*, shaderprogram::*, skybox::*};
use std::ptr;
// TODO: Eventually remove default derivations where not necessary
#[derive(Default)]
struct MainState {
shader_program: ShaderProgram,
lamp_program: S... |
use serde::Deserialize;
#[derive(Debug, Deserialize, PartialEq)]
pub(crate) struct Element {
#[serde(rename = "Element")]
pub(crate) name: String,
#[serde(rename = "Symbol")]
pub(crate) symbol: String,
#[serde(rename = "AtomicNumber")]
pub(crate) atomic_num: u8,
#[serde(rename = "AtomicM... |
use crate::il;
use crate::translator::aarch64::{
register::{get_register, AArch64Register},
unsupported, UnsupportedError,
};
type Result<T> = std::result::Result<T, UnsupportedError>;
/// Get the scalar for a well-known register.
macro_rules! scalar {
("x30") => {
// the link register
il:... |
pub mod steps;
pub mod tp;
|
// Copyright 2021 Datafuse Labs.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to ... |
// ignore-compare-mode-nll
// revisions: base nll
// [nll]compile-flags: -Zborrowck=mir
// edition:2018
fn require_static<T: 'static>(val: T) -> T {
//[base]~^ NOTE 'static` lifetime requirement introduced by this bound
val
}
struct Problem;
impl Problem {
pub async fn start(&self) {
//[base]~^ E... |
//! Tests auto-converted from "sass-spec/spec/values"
//! version 0f59164a, 2019-02-01 17:21:13 -0800.
//! See <https://github.com/sass/sass-spec> for source material.\n
//! The following tests are excluded from conversion:
//! ["ids", "numbers/units/multiple"]
extern crate rsass;
use rsass::{compile_scss, OutputStyle}... |
//! Contains the ffi-safe equivalent of `std::boxed::Box`.
use std::{
borrow::{Borrow, BorrowMut},
error::Error as StdError,
future::Future,
hash::Hasher,
io::{self, BufRead, IoSlice, IoSliceMut, Read, Seek, Write},
iter::FusedIterator,
marker::{PhantomData, Unpin},
mem::ManuallyDrop,
... |
use helpers::{HelperDef};
use registry::{Registry};
use context::{Context, JsonTruthy};
use render::{Renderable, RenderContext, RenderError, render_error, Helper};
#[derive(Clone, Copy)]
pub struct IfHelper {
positive: bool
}
impl HelperDef for IfHelper{
fn call(&self, c: &Context, h: &Helper, r: &Registry, r... |
//! Provides a seamless wrapper around OpenGL and WebGL, so that the rest of
//! the code doesn't need to know which of the two it's running on.
mod buffer;
mod context;
mod framebuffer;
#[cfg(not(target_arch = "wasm32"))]
pub mod opengl;
pub mod shaders;
mod texture;
mod vertexbuffer;
#[cfg(target_arch = "wasm32")]
p... |
/// A match within a scan.
#[derive(Debug)]
pub struct Match {
/// Offset of the match within the scanning area.
pub offset: usize,
/// Length of the file. Can be useful if the matcher string has not a fixed length.
pub length: usize,
/// Matched data.
pub data: Vec<u8>,
}
|
use Vector;
use chrono::{DateTime, Duration, Utc};
use cpd::Rigid;
use failure::Error;
use las::Point;
use std::collections::HashMap;
use std::path::Path;
use std::sync::{Arc, Mutex};
/// The velocity calculation did not converge.
#[derive(Debug, Fail)]
#[fail(display = "Did not converge")]
pub struct DidNotConverge {... |
use std::io::{Seek, SeekFrom, Write};
use assert_cmd::prelude::*;
use predicates::str::contains;
#[cfg(feature = "compression")]
#[test]
fn test_stdin_gz() {
// Generated with `echo ">id1\nAGTCGTCA" | gzip -c | xxd -i`
let input: &[u8] = &[
0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, ... |
#[doc = "Writer for register OENR"]
pub type W = crate::W<u32, super::OENR>;
#[doc = "Register OENR `reset()`'s with value 0"]
impl crate::ResetValue for super::OENR {
type Type = u32;
#[inline(always)]
fn reset_value() -> Self::Type {
0
}
}
#[doc = "Timer E Output 2 Enable\n\nValue on reset: 0"... |
use super::display::Display;
use crossterm::{
execute,
queue
};
use std::io::{Write, stdout};
const pixel: &'static str = "█";
pub fn redraw(display: &Display) -> crossterm::Result<()> {
let mut stdout = stdout();
execute!(
stdout,
crossterm::terminal::Clear(crossterm::terminal::Clea... |
#[doc = "Reader of register IER"]
pub type R = crate::R<u32, super::IER>;
#[doc = "Writer for register IER"]
pub type W = crate::W<u32, super::IER>;
#[doc = "Register IER `reset()`'s with value 0"]
impl crate::ResetValue for super::IER {
type Type = u32;
#[inline(always)]
fn reset_value() -> Self::Type {
... |
use std::env;
use std::fs::File;
use std::io::{BufRead, BufReader};
use tantivy::Index;
use tantivy::collector::TopDocs;
use tantivy::query::{QueryParser, RangeQuery};
use tantivy::schema::*;
fn main() -> tantivy::Result<()> {
let file_lines = env::args()
.skip(1)
.next()
.and_then(|f| Fi... |
fn calculate_frequency(input: String) -> i32 {
input
.split("\n")
.map(|x| x.parse::<i32>().unwrap())
.fold(0, |acc, x| acc + x)
}
fn main() {
let input = include_str!("input.txt").into();
println!("{}", calculate_frequency(input));
}
#[test]
fn test_01() {
assert_eq!(calculate... |
#![allow(unused_variables)]
#![allow(dead_code)]
pub fn fibonacci_until(mut x:usize, mut y:usize, limit:usize) {
match limit{
0 => {print!(""); return},
1 => {print!("{}", x); return},
2 => {print!("{}, {}", x, y); return},
_ => {
print!("{}, {}, ", x, y);
l... |
use std::path::Path;
use std::process::Stdio;
use anyhow::{anyhow, Context, Result};
use async_trait::async_trait;
use clap::{Parser, IntoApp};
use tokio::fs;
use crate::Runnable;
use self::database::Database;
use self::protobuf::Protobuf;
mod database;
mod protobuf;
/// Compiles app to generate packages
#[derive(... |
///
fn main() {
println!("Hello reader !");
}
|
#[macro_use]
extern crate log;
use clap::{App, AppSettings, Arg};
use env_logger::Env;
use nb::Node;
use tokio::runtime::Runtime;
fn main() {
let matches = App::new("nb")
.version(env!("CARGO_PKG_VERSION"))
.author(env!("CARGO_PKG_AUTHORS"))
.about("A simple blockchain node")
.sett... |
use super::*;
use std::process::{Command, Child, Stdio};
use std::thread;
use std::time::Duration;
use std::net::TcpListener;
/// Find a TCP port number to use. This is racy but see
/// https://bugzilla.mozilla.org/show_bug.cgi?id=1240830
///
/// If port is Some, check if we can bind to the given port. Otherwise
///... |
use std::error::Error;
use std::path::Path;
use colored::*;
use log::*;
use tokio::process::Command;
use crate::stack::parser::*;
const LOCALSTACK_DYNAMODB_ENDPOINT: &str = "http://localhost:4569";
pub async fn wait_for_it() -> Result<(), Box<dyn Error>> {
let mut ready: bool = false;
while !ready {
... |
use criterion::{criterion_group, criterion_main, BenchmarkId, Criterion};
use crossbeam::queue::SegQueue;
use futures::{channel::oneshot, executor::block_on, future, stream::StreamExt as _, task::Poll};
use std::{sync::Arc, thread};
pub fn polling_benchmark(c: &mut Criterion) {
{
let mut group = c.benchma... |
#![allow(unused_variables, non_upper_case_globals, non_snake_case, unused_unsafe, non_camel_case_types, dead_code, clippy::all)]
#[cfg(feature = "Win32_System_Com_StructuredStorage")]
#[inline]
pub unsafe fn BindIFilterFromStorage<'a, Param0: ::windows::core::IntoParam<'a, super::super::System::Com::StructuredStorage::... |
use std::error::Error as StdError;
use std::fmt::{self, Display};
use crate::error::DatabaseError;
use crate::postgres::protocol::Response;
#[derive(Debug)]
pub struct PgError(pub(super) Response);
impl DatabaseError for PgError {
fn message(&self) -> &str {
&self.0.message
}
fn code(&self) -> O... |
#![allow(clippy::comparison_chain)]
#![allow(clippy::collapsible_if)]
use std::cmp::Reverse;
use std::cmp::{max, min};
use std::collections::{BTreeSet, HashMap, HashSet};
use std::fmt::Debug;
use itertools::Itertools;
use whiteread::parse_line;
const ten97: usize = 1000_000_007;
/// 2の逆元 mod ten97.割りたいときに使う
const in... |
#![allow(unused_variables, non_upper_case_globals, non_snake_case, unused_unsafe, non_camel_case_types, dead_code, clippy::all)]
#[cfg(feature = "Phone_Speech_Recognition")]
pub mod Recognition;
|
// OpenTimestamps Viewer
// Written in 2017 by
// Andrew Poelstra <rust-ots@wpsoftware.net>
//
// To the extent possible under law, the author(s) have dedicated all
// copyright and related and neighboring rights to this software to
// the public domain worldwide. This software is distributed without
// any warranty.... |
//! Many of this code is from: https://github.com/RustPython/RustPython
//! Different token definitions.
//! Loosely based on token.h from CPython source:
use std::fmt::{self, Write};
/// Python source code can be tokenized in a sequence of these tokens.
#[derive(Clone, Debug, PartialEq)]
pub enum Tok {
Name { nam... |
use std::cmp;
use std::io::{self, Read, Write};
use bytes::{Buf, BufMut, Bytes, IntoBuf};
use futures::{Async, Poll};
use tokio_io::{AsyncRead, AsyncWrite};
/// Combine a buffer with an IO, rewinding reads to use the buffer.
#[derive(Debug)]
pub(crate) struct Rewind<T> {
pre: Option<Bytes>,
inner: T,
}
impl<... |
use mysql as my;
use mysql::params;
pub fn insert_temporary_user(email: &str, password: &str, salt: &str, cypher: &str) {
let pool = my::Pool::new("mysql://shin:0523@localhost:3306/db").unwrap();
let mut stmt = pool.prepare(r"INSERT INTO temporary_users (mail, password, salt, cypher) VALUES (:mail, :password, ... |
//! Irq-safe locking via Mutex and RwLock.
//! Identical behavior to the regular `spin` crate's
//! Mutex and RwLock, with the added behavior of holding interrupts
//! for the duration of the Mutex guard.
#![cfg_attr(feature = "const_fn", feature(const_fn))]
#![feature(asm)]
#![feature(manually_drop)]
#![no_std]
... |
use std::cmp::{max, min};
use std::collections::{HashMap, HashSet};
use itertools::Itertools;
use whiteread::parse_line;
fn main() {
let (n, m): (usize, usize) = parse_line().unwrap();
let mut pp: Vec<usize> = vec![];
for _ in 0..n {
pp.push(parse_line().unwrap());
}
let mut two = vec![];... |
use std::io::TcpStream;
use std::io::IoResult;
use std::rand;
use std::rand::Rng;
use std::io::Timer;
use std::time::duration::Duration;
fn main() {
let mut socket: TcpStream = TcpStream::connect("127.0.0.1", 8000).unwrap();
let interval = Duration::milliseconds(1000);
let mut timer = Timer::new().unwrap();
le... |
//! Helper types for constructing strings and arrays composed of other strings and arrays.
//!
//! These datatypes are special-cased for small composite collections ,
//! whose indices fit in a u16.
use std::{
borrow::Borrow,
convert::TryFrom,
fmt::{Debug, Display},
marker::PhantomData,
ops::{Add, ... |
use {
failure::Error, fuchsia_async as fasync, fuchsia_syslog as syslog, setui_client_lib::*,
structopt::StructOpt,
};
#[fasync::run_singlethreaded]
async fn main() -> Result<(), Error> {
syslog::init_with_tags(&["setui-client"]).expect("Can't init logger");
let command = SettingClient::from_args();
... |
use crate::arithmetic_command::ArithmeticCommand;
use crate::segment::Segment;
#[derive(Debug)]
pub enum Command {
Arithmetic(ArithmeticCommand),
Push(Segment, i32),
Pop(Segment, i32),
Label(String),
GoTo(String),
IfGoTo(String),
Function(String, i32),
Call(String, i32),
Return,
}
|
// Copyright (c) 2016 The Rouille 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 co... |
use std::io;
pub fn vrsta(stevilo: i32, seznam: &mut [i32]) {
let mut x = 1;
print!("\ngenerirani poskusi po vrsti: ");
for stev in seznam {
let num = *stev;
if num != 0 {
if x>=10 {
print!("\n");
x=1;
}
print!(" {},", n... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.