text stringlengths 8 4.13M |
|---|
use std::io::{stdin, stdout, Read, Write};
use termion::event::Key;
use termion::input::TermRead;
fn main() {
let mut stdout = stdout();
write!(stdout, "Pressione uma tecla: ").unwrap();
stdout.flush().unwrap();
for c in stdin().keys() {
match c.unwrap() {
Key::Char('q') => {
... |
/*!
```rudra-poc
[target]
crate = "acc_reader"
version = "2.0.0"
[report]
issue_url = "https://github.com/netvl/acc_reader/issues/1"
issue_date = 2020-12-27
rustsec_url = "https://github.com/RustSec/advisory-db/pull/664"
rustsec_id = "RUSTSEC-2020-0155"
[[bugs]]
analyzer = "UnsafeDataflow"
bug_class = "UninitExposure... |
#[doc = "Reader of register DDRPHYC_DCUAR"]
pub type R = crate::R<u16, super::DDRPHYC_DCUAR>;
#[doc = "Writer for register DDRPHYC_DCUAR"]
pub type W = crate::W<u16, super::DDRPHYC_DCUAR>;
#[doc = "Register DDRPHYC_DCUAR `reset()`'s with value 0"]
impl crate::ResetValue for super::DDRPHYC_DCUAR {
type Type = u16;
... |
#![allow(dead_code)]
#![allow(unused_imports)]
#![allow(unused_variables)]
use std::mem;
pub fn arrays()
{
let arr = [1u8; 10];
println!("{:?}", arr);
println!("Size of arr is {}", mem::size_of_val(&arr));
let mtx_arr:[[u8;3];2] = [
[2,3,4],
[4,5,9]
];
println!("{:?}", mtx_ar... |
#[doc = "Register `PDCRE` reader"]
pub type R = crate::R<PDCRE_SPEC>;
#[doc = "Register `PDCRE` writer"]
pub type W = crate::W<PDCRE_SPEC>;
#[doc = "Field `PD0` reader - Port E pull-down bit y (y=0..15)"]
pub type PD0_R = crate::BitReader;
#[doc = "Field `PD0` writer - Port E pull-down bit y (y=0..15)"]
pub type PD0_W<... |
#![no_std]
#![no_main]
use cortex_m::asm::nop;
use cortex_m_rt::entry;
use panic_halt as _;
use rtt_target::{rprintln, rtt_init_print};
use rp2040_pac::{Peripherals, XOSC};
mod usb;
#[link_section = ".boot_loader"]
#[used]
pub static BOOT_LOADER: [u8; 256] = rp2040_boot2::BOOT_LOADER;
/// Handle peripheral resets... |
mod applet;
mod seeds;
fn main() {
let sds = seeds::Seeds::from_file().unwrap_or(seeds::Seeds::new());
let app = applet::Applet::new(sds);
app.run()
}
|
pub trait Summary {
fn summarize(&self) -> String {
format!("Read more by {}...", self.summarize_author())
}
fn summarize_author(&self) -> String;
}
pub struct NewsArticle {
pub headline: String,
pub location: String,
pub author: String,
pub content: String,
}
impl Summary for New... |
#[macro_export]
macro_rules! use_contract {
($module: ident, $path: expr) => {
#[allow(dead_code)]
#[allow(missing_docs)]
#[allow(unused_imports)]
#[allow(unused_mut)]
#[allow(unused_variables)]
pub mod $module {
#[derive(ethabi_derive::EthabiContract)]
#[ethabi_contract_options(path = $path)]
str... |
extern crate pest;
#[macro_use]
extern crate pest_derive;
pub mod ast;
use crate::ast::*;
use pest::iterators::Pairs;
use pest::Parser;
use std::fs;
use std::path::Path;
#[derive(Parser)]
#[grammar = "program.pest"]
struct ProgramParser;
type AstResult = Result<ast::Program, String>;
pub fn parse_file<P: AsRef<Pat... |
use std::usize;
use super::keyboard::{Key, KeyStates};
use super::mouse::{EditorMouseState, MouseKeys, MouseState, ViewportBounds};
use crate::message_prelude::*;
use bitflags::bitflags;
#[doc(inline)]
pub use graphene::DocumentResponse;
#[impl_message(Message, InputPreprocessor)]
#[derive(PartialEq, Clone, Debug)]
... |
#[doc = "Register `OPTR` reader"]
pub type R = crate::R<OPTR_SPEC>;
#[doc = "Register `OPTR` writer"]
pub type W = crate::W<OPTR_SPEC>;
#[doc = "Field `RDP` reader - Read protection level"]
pub type RDP_R = crate::FieldReader;
#[doc = "Field `RDP` writer - Read protection level"]
pub type RDP_W<'a, REG, const O: u8> = ... |
use mongodb::oid::ObjectId;
use primitive_types::U256;
use rulinalg::matrix::Matrix;
use rust_hope::schemes::she::hope::hopeCiphertext;
use serde::{Serialize, Deserialize};
/// A structured encryption key
#[derive(Serialize, Deserialize, PartialEq, Clone, Debug)]
pub struct SEKey {
pub _k1: U256,
pub _k2: U256... |
//
// Copyright (c) 2017, 2020 ADLINK Technology Inc.
//
// This program and the accompanying materials are made available under the
// terms of the Eclipse Public License 2.0 which is available at
// http://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0
// which is available at https://www.apache.or... |
// Copyright 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) any la... |
use anyhow::Result;
use rustcoalescence_algorithms::Algorithm;
#[cfg(feature = "rustcoalescence-algorithms-cuda")]
use rustcoalescence_algorithms_cuda::CudaAlgorithm;
#[cfg(feature = "rustcoalescence-algorithms-independent")]
use rustcoalescence_algorithms_independent::IndependentAlgorithm;
#[cfg(feature = "rustcoale... |
use std::collections::HashSet;
fn format_radix(mut x: u64, radix: u64) -> String {
let mut result = vec![];
loop {
let m = x % radix;
x = x / radix;
result.push(std::char::from_digit(m as u32, radix as u32).unwrap());
if x == 0 {
break;
}
}
result.i... |
use crate::back::spv::{helpers, Instruction};
use spirv::{Op, Word};
pub(super) enum Signedness {
Unsigned = 0,
Signed = 1,
}
//
// Debug Instructions
//
pub(super) fn instruction_source(
source_language: spirv::SourceLanguage,
version: u32,
) -> Instruction {
let mut instruction = Instruction::n... |
extern crate serde;
pub mod animation;
pub mod carry;
pub mod components;
pub mod crab_ai;
pub mod entities;
pub mod map;
pub mod movement;
pub mod saveload_system;
pub mod state;
pub mod string_writer;
pub mod weapons;
|
fn naruhodo(s: &str) -> String {
s.chars() // camelCase
.rev() // esaClemac
.collect::<String>() // esaClemac
.split_inclusive(char::is_uppercase) // iter(esaC lemac)
.map(|x| x.chars().rev().collect()) // ... |
fn main() {
// my test inputs: 236491 to 713787.
let p = all_possibilities(236491, 713787);
println!("Checking {} possibilities", p.len());
let candidate_pws: Vec<&i32> = p
.iter()
.filter(|x| has_double(x) && !has_decreasing_digits(x))
.collect();
println!("Candidate count:... |
use crate::error::{Error, Result};
pub(super) struct Commands(Vec<Box<Command>>);
impl Commands {
pub(super) fn new() -> Commands {
Commands(vec![Box::new(Hello), Box::new(Bye)])
}
pub(super) fn handle(&self, message: &str) -> Result<String> {
let mut split = message.splitn(2, ' ');
... |
// q0151_reverse_words_in_a_string
struct Solution;
impl Solution {
pub fn reverse_words(s: String) -> String {
let r: Vec<&str> = s.split_ascii_whitespace().rev().collect();
let mut ret = String::with_capacity(s.len());
for ss in r.into_iter() {
ret.push_str(ss);
r... |
fn parse_numbers() -> Vec<i32> {
let mut numbers: Vec<_> = aoc2020::input_file!("10")
.lines()
.map(|x| x.parse().unwrap())
.collect();
numbers.push(0);
numbers.sort_unstable();
numbers.push(numbers.last().unwrap() + 3);
numbers
}
fn part1(numbers: &[i32]) -> i32 {
let (... |
use std::fmt::Debug;
use std::future::Future;
/// Runtime abstracts away the underlying runtime we use for task scheduling.
pub trait Runtime: Clone + Send + Sync + Unpin + Debug {
/// Spawn a [`Future`] to run as a task in some executor.
fn spawn<F>(&self, future: F)
where
F: Future<Output = ()> +... |
use crate::query_testing::{parse_position_comments, Assertion};
use ansi_term::Colour;
use anyhow::{anyhow, Result};
use std::fs;
use std::path::Path;
use tree_sitter::Point;
use tree_sitter_highlight::{Highlight, HighlightConfiguration, HighlightEvent, Highlighter};
use tree_sitter_loader::Loader;
#[derive(Debug)]
pu... |
use crate::config::Config;
use crate::config::ResolvOptions;
use crate::config::sort_root_name_servers;
use crate::cache::Cache;
use crate::name_server::NameServer;
use crate::protocol::Protocol;
use std::io;
use std::net::IpAddr;
use std::net::Ipv4Addr;
use std::net::Ipv6Addr;
use std::pin::Pin;
use std::future::Fut... |
use byteorder::{ByteOrder, ReadBytesExt, WriteBytesExt};
use crate::{
errors::*,
TsResolution
};
use std::{
borrow::Cow,
io::Read,
io::Write,
time::Duration
};
/// Describes a pcap packet header.
#[derive(Copy, Clone, Default, Debug, Eq, PartialEq)]
pub struct PacketHeader {
/// Timestam... |
// Exercise 1.1.
// Below is a sequence of expressions.
// What is the result printed by the interpreter in response to each expression?
// Assume that the sequence is to be evaluated in the order in which it is presented.
// 10
// 10
// (+ 5 3 4)
// 12
// (- 9 1)
// 8
// (/ 6 2)
// 3
// (+ (* 2 4) (- 4 6))
/... |
//! Find matches in a large input text.
//!
//! Note that this was adapted from [regex-benchmark]; the key part retained
//! is the patterns [regex-benchmark] used for finding the matches.
//!
//! [regex-benchmark]: https://github.com/mariomka/regex-benchmark
use regex::RegexBuilder;
use sightglass_api as bench;
cons... |
struct Selector {
rows: scraper::Selector,
differentiation: scraper::Selector,
name: scraper::Selector,
price: scraper::Selector,
amount: scraper::Selector,
refine: scraper::Selector,
properties: scraper::Selector,
}
|
use std::io;
use std::fs::File;
use std::mem;
use std::path::Path;
use num::{rational::Ratio, BigInt, BigRational};
use unicode_reader::CodePoints;
use crate::tokens::TokenTable;
use crate::types::{KToken, Name};
fn is_letter_like_unicode(c: char) -> bool {
('α' <= c && c <= 'ω' && c != 'λ') || // Lower greek, ... |
mod utils;
use wasm_bindgen::prelude::*;
// When the `wee_alloc` feature is enabled, use `wee_alloc` as the global
// allocator.
#[cfg(feature = "wee_alloc")]
#[global_allocator]
static ALLOC: wee_alloc::WeeAlloc = wee_alloc::WeeAlloc::INIT;
#[wasm_bindgen]
extern {
fn alert(s: &str);
}
#[wasm_bindgen]
pub fn i... |
#[doc = "Reader of register RCC_DBGCFGR"]
pub type R = crate::R<u32, super::RCC_DBGCFGR>;
#[doc = "Writer for register RCC_DBGCFGR"]
pub type W = crate::W<u32, super::RCC_DBGCFGR>;
#[doc = "Register RCC_DBGCFGR `reset()`'s with value 0x01"]
impl crate::ResetValue for super::RCC_DBGCFGR {
type Type = u32;
#[inli... |
fn main() {
// ブーリアン型
let x = true;
let y: bool = false;
// char型
let c = 'c';
let two_hearts = '💕'; // 4バイト
// 数値型
// i8, i16, i32, i64, u8, u16, u32, u64, isize, usize, f32, f64,
// u: 符号なし, i: 符号あり, fは浮動小数点型
// isizeとusizeは可変長
// 配列
let a = [1, 2, 3];
let mut m... |
#![crate_type = "dylib"]
#![crate_name = "points"]
// Based on http://blog.skylight.io/bending-the-curve-writing-safe-fast-native-gems-with-rust/
// by Yehuda Katz
use std::num::pow;
pub struct Point { x: int, y: int }
struct Line { p1: Point, p2: Point }
impl Line {
pub fn length(&self) -> f64 {
let xd... |
#![allow(dead_code, unused_imports)]
use env_logger;
use log::{debug, info};
use std::io;
use wikitools::extract::extract_anchor_counts_to_trie;
use wikitools::extract::{TrieBuilderFlat, TrieBuilderNested};
use wikitools::indices::{read_indices, write_all_indices, write_template_indices, WikiDumpIndices};
use wikitoo... |
// cd C:\Users\むずでょ\source\repos\practice-rust
// cargo new chat-client-1
//
// cd C:\Users\むずでょ\source\repos\practice-rust\chat-client-1
// cargo check
// cargo build
// cargo run
//
// See also:
// https://crates.io/
// #[macro_use]
extern crate serde_derive;
extern crate toml;
// TcpListener は、標準のと Tokio のとがあって、どち... |
use svm_sdk_std::Option;
/// Used for traversal of the encoded function buffer.
/// It will be used by the `Decoder`.
///
/// By having the isolation between the `Decoder` and `Cursor` we are able
/// to execute a `Decoder` method that receives as a parameter `&mut Cursor`
/// while the `Decoder` is borrowed `&self`... |
use std::fs;
use std::collections::HashMap;
type MapType = HashMap<String, Vec<String>>;
fn parse_input(line: &str, signals: &mut MapType) {
let splitted: Vec<&str> = line.splitn(2, " -> ").collect();
let key = splitted[1].to_string();
let entry: Vec<String> = splitted[0].splitn(3, " ")
.map(|s| s... |
use std::fs::File;
use std::io::{BufRead, BufReader};
use regex::Regex;
fn main() {
println!(
"{}",
Regex::new(r"[gkmqvwxzio]")
.map(|invalid| {
File::open("words/words.txt")
.map(|source| {
BufReader::new(source)
... |
#[allow(non_camel_case_types)]
use scan_fmt::*;
use std::io::Read;
use std::fs::File;
use std::collections::HashMap;
use std::collections::HashSet;
use std::iter::FromIterator;
type Val = usize;
type Regs = [Val; 4];
type OpCode = Val;
type A = Val;
type B = Val;
type C = Val;
fn addr(mut r: Regs, (a,b,c): (A,B,C)) -... |
use std::time::SystemTime;
use actix_web::http::StatusCode;
use chrono::{DateTime, Local};
use chrono_humanize::Humanize;
use clap::{crate_name, crate_version, ValueEnum};
use fast_qr::{
convert::{svg::SvgBuilder, Builder},
qr::QRCodeError,
QRBuilder,
};
use http::Uri;
use maud::{html, Markup, PreEscaped, ... |
use actix::prelude::*;
use actix::Handler;
use bytes::Bytes;
use super::ChatServer;
#[derive(Message)]
#[rtype(result = "()")]
pub struct MessagePayload {
header: MessagePayloadHeader,
body: Bytes,
}
impl MessagePayload {
pub fn new(header: MessagePayloadHeader, body: Bytes) -> Self {
MessagePayl... |
//! Watches a Kubernetes Resource for changes, with error recovery
//!
//! See [`watcher`] for the primary entry point.
use crate::utils::ResetTimerBackoff;
use async_trait::async_trait;
use backoff::{backoff::Backoff, ExponentialBackoff};
use derivative::Derivative;
use futures::{stream::BoxStream, Stream, StreamExt}... |
#![allow(proc_macro_derive_resolution_fallback)]
use super::schema::{accession_numbers, test_accession_numbers};
use bigdecimal::BigDecimal;
#[derive(Queryable, PartialEq, Eq, Debug)]
pub struct AccessionNumber {
pub id: i32,
pub accession_number: BigDecimal,
}
#[derive(Insertable)]
#[table_name = "accession... |
pub struct Solution {}
/**
https://leetcode.com/problems/buddy-strings/
**/
impl Solution {
pub fn buddy_strings(a: String, b: String) -> bool {
if a.len() < 2 || b.len() < 2 || a.len() != b.len() {
return false;
}
let mut letter = [0i32; 26];
let a_chars: Vec<_> = a.ch... |
mod argparser;
mod cacher;
mod config;
mod equity;
mod fetcher;
mod portfolio;
use argparser::parsearg;
use argparser::*;
use colored::*;
use config::read_user_from_file;
use fetcher::Fetcher;
use portfolio::{PortList, Portfolio, Presult};
use std::env;
use std::error;
use std::io::{self, Write};
use std::string::Stri... |
use bigint::U256;
use std::cmp;
use asm::opcode::*;
use errors::{Error, Result};
#[derive(Debug, PartialEq)]
pub enum Instruction {
// Stop and Arithmetic Operations
STOP,
ADD,
MUL,
SUB,
DIV,
SDIV,
MOD,
SMOD,
ADDMOD,
MULMOD,
EXP,
SIGNEXTEND,
LT,
GT,
SLT,... |
use crate::Error;
use chrono::{DateTime, TimeZone, Utc};
use oauth2::AccessToken;
use serde::{de, Deserialize, Deserializer};
use std::str::FromStr;
#[derive(Debug, Clone, Deserialize)]
struct _LoginResponse {
token_type: String,
expires_in: u64,
ext_expires_in: u64,
expires_on: Option<String>,
not... |
use anyhow::{anyhow, bail, Result};
use reqwest::blocking::Client;
use serde::{de::DeserializeOwned, Serialize};
use serde_json::Value;
use std::collections::HashMap;
/// A simple HTTP wrapper for communicating with an ElasticSearch database.
pub struct Database {
url: String,
dry_run: bool,
}
impl Database {... |
/*
На олимпиаду по программированию приходит N человек. На регистрации вместо
своего имени они передают организатору шифр — строку, состоящую из букв и
цифр. Гарантируется, что в этой строке содержится единственная
последовательность цифр, образующая целое положительное число M. Если
символы шифра, стоящие на позициях ... |
use std::collections::HashMap;
use std::io::{self, BufRead};
#[derive(PartialEq, PartialOrd, Eq, Ord, Clone, Debug)]
enum Rule {
Number(usize),
Char(char),
Union(Vec<Rule>),
Concat(Vec<Rule>),
}
type Rules = HashMap<usize, Rule>;
fn parse_rule_value(value: &str) -> Option<Rule> {
if value.starts_... |
use std::io::prelude::*;
use std::fs::File;
use std::env;
use std::process;
// # Traits
trait Item {
fn make_html(&self) -> String;
}
trait Link : Item {}
trait Tray : Item {
fn add(&mut self, item: Box<Item>);
}
trait Page {
fn make_html(&self) -> String;
}
trait Factory {
type LinkObject;
typ... |
use crate::boards::Board;
use serde::{Deserialize, Serialize};
use actix_web::{HttpResponse, HttpRequest, Responder, Error};
use futures::future::{ready, Ready};
use sqlx::{postgres::{PgPoolOptions, PgRow, PgDone}, query_as};
use sqlx::query::Query;
use sqlx::{FromRow, Row, Pool, Postgres, query};
use anyhow::Result;
u... |
#[doc = "Register `SECCFGR` reader"]
pub type R = crate::R<SECCFGR_SPEC>;
#[doc = "Register `SECCFGR` writer"]
pub type W = crate::W<SECCFGR_SPEC>;
#[doc = "Field `C2EWILA` reader - wakeup on CPU2 illegal access interrupt enable"]
pub type C2EWILA_R = crate::BitReader;
#[doc = "Field `C2EWILA` writer - wakeup on CPU2 i... |
//! Multiwii Serial Protocol (MSP) traffic decoder and structures
//!
//! Incomplete. Includes some structures from Cleanflight and Betaflight.
#![cfg_attr(not(feature="std"), no_std)]
#![cfg_attr(not(feature="std"), feature(alloc))]
#[cfg(not(feature="std"))]
#[macro_use]
extern crate alloc;
extern crate packed_s... |
#![allow(unused_variables)]
fn main() {
let mut s1 = String::from("STRING 01");
{
// test 1:
let s2 = &s1;
let s3 = &s1;
//let s4 = &mut s1; // <- this will be error
}
{
// test 2:
let s4 = &mut s1;
//let s3 = &s1; // <- this will be error
... |
/// sum((x_i - p)^2) = sum( p^2 - 2(sum(x_i))p + sum(x_i^2) )
/// 微分すると
/// sum(2p -2(sum(x_i))) = 2Np -2(sum(x_i)) = 0
/// p = sum(x_i) / N = average
/// よってpはXの平均
/// 整数である必要があるので 保険として平均の前後2つづつの整数を調べて最小のものとする
fn main() {
proconio::input! {
n: usize,
x: [i32; n],
}
let sum: i32 = x.iter(... |
use clang::*;
pub struct CType<'a> {
clang_type: Type<'a>
}
impl<'a> CType<'a> {
pub fn new(clang_type: Type<'a>) -> CType<'a> {
CType {
clang_type: clang_type.get_canonical_type()
}
}
pub fn get_underlying_type(&self) -> &Type<'a> {
&self.clang_type
}
pu... |
use crate::error_reporter::error;
use crate::token::Token;
use crate::token_type::TokenType;
use crate::traits::Lexer;
pub struct Scanner {
source: String,
tokens: Vec<Token>,
start: u32,
current: u32,
line: u32,
}
impl Lexer for Scanner {
fn scan_tokens(&mut self) -> Vec<Token> {
let mut tokens = vec... |
use math::Rect;
use draw::{Bounded, CanvasRead, CanvasWrite};
use tool::{Editor, Brush, PreviewContext};
pub struct Prev<'a> {
pub ptr: *mut u8,
pub rect: Rect<i32>,
pub editor: &'a Editor,
}
impl<'a> Bounded<i32> for Prev<'a> {
#[inline(always)]
fn bounds(&self) -> Rect<i32> { self.rect }
}
impl... |
use std::io::Error;
use std::fs::File;
use std::io::prelude::*;
fn read_input(filename: &str) -> Result<String, Error> {
let mut input = String::new();
File::open(filename)?.read_to_string(&mut input)?;
return Ok(input);
}
fn main() {
match read_input("input.txt") {
Ok(input) => {
println!("Part 1 a... |
use std::process::*;
use std::time::*;
use std::io::Result;
use std::io::Write;
use std::thread::sleep;
const FALLBACK: &str = "fallback.mp3";
static urls: [&str; 1] = [
"http://direct.franceinter.fr/live/franceinter-hifi.aac"
];
pub struct Player {
// show must go on, so if there is a problem we still hav... |
// There is a new alien language which uses the latin alphabet. However, the order among letters
// are unknown to you. You receive a list of words from the dictionary, wherewords are sorted
// lexicographically by the rules of this new language. Derive the order of letters in this
// language.
//
// For example,
// Gi... |
use std::{collections::HashMap, env, fs};
enum Direction {
Up,
Down,
Left,
Right,
}
type Input = Vec<(Direction, i32)>;
fn main() {
let args: Vec<String> = env::args().collect();
if args.get(1).is_none() {
panic!("Supply a file to run against");
}
let content = fs::read_to_st... |
mod pest_parser_impl;
pub(crate) use pest_parser_impl::PestParserImpl;
|
extern crate libpasta;
extern crate ring;
use ring::hkdf;
#[test]
fn test_hmac() {
// Use scrypt as the default inner hash
let hash_primitive = libpasta::primitives::Scrypt::default();
let mut config = libpasta::Config::with_primitive(hash_primitive);
// Some proper way of getting a key
let key =... |
use crate::errors::*;
use crate::types::*;
use uuid::Uuid;
/// Describes the address of UDP reflectors
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct CallConnection {
#[doc(hidden)]
#[serde(rename(serialize = "@type", deserialize = "@type"))]
td_name: String,
#[doc(hidden)]
#[s... |
use std::{env, panic};
use scicalc_rs::parser::eval;
fn show_usage() {
println!("Usage: scicalc-rs [expression]");
}
fn main() {
panic::set_hook(Box::new(|_info| {
// do nothing
//TODO: Add proper error handling
}));
let args: Vec<String> = env::args().collect();
if args.len() <=... |
use std::collections::BinaryHeap;
struct MedianFinder {
hi: BinaryHeap<i32>,
lo: BinaryHeap<i32>,
}
impl MedianFinder {
fn new() -> Self {
Self {
hi: BinaryHeap::new(),
lo: BinaryHeap::new(),
}
}
fn add_num(&mut self, num: i32) {
self.lo.push(num);
... |
use super::content::PositionDetails;
use std::error::Error;
use std::fmt;
#[derive(Debug, Clone)]
pub struct ParsingError {
display_text: String,
message: String,
filename: String,
line_number: usize,
column: usize,
byte_offset: usize,
}
impl ParsingError {
pub fn new(position: &PositionDe... |
#[doc = "Reader of register NEXT_SUP_TO_STATUS"]
pub type R = crate::R<u32, super::NEXT_SUP_TO_STATUS>;
#[doc = "Reader of field `NEXT_SUP_TO`"]
pub type NEXT_SUP_TO_R = crate::R<u16, u16>;
impl R {
#[doc = "Bits 0:15 - HW updates this register for the SuperVision timeout next instant, granularity is 625us"]
#[... |
extern crate serde_json;
use currency::api::ServiceApi;
use currency::api::error::ApiError;
use currency::offers::HistoryOffers;
use currency::offers::history;
use exonum::api::Api;
use exonum::blockchain::Blockchain;
use exonum::crypto::Hash;
use exonum::encoding::serialize::FromHex;
use hyper::header::ContentType;
... |
use serde::{de, Deserialize, Serialize};
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct User {
id: u64,
name: Name,
}
impl User {
pub fn id(&self) -> u64 {
self.id
}
}
/// 名前を表す型の定義
#[derive(Clone, Debug, Serialize)]
struct Name(String);
impl Name {
/// 値のチェックを行った上でNameを作成する
... |
//! Representation of a category in a Gentoo repository
use crate::{
repository::{Ebuild, Package},
util::optfilter::OptFilter,
};
use std::{io::Error, path::PathBuf, result::Result};
/// Represents a discrete Gentoo category
pub struct Category {
root: PathBuf,
category: String,
}
impl Category ... |
fn isPrime(n: i32) -> bool {
let sn = ((n as f64).sqrt() as i32) + 1;
for i in 2..sn {
if n % i == 0 {
return false;
}
}
true
}
fn hasZero(n: i32) -> bool {
let mut n = n;
while n > 0 {
if n % 10 == 0 {
return true;
}
n = n / 10... |
extern crate civil;
use civil::units::conversions;
const PRECISION: f64 = 0.1;
#[test]
fn we_can_test() {
assert!(true)
}
#[test]
fn nonexistant_keys_return_none() {
let my_table = conversions::Table::new();
let my_bad_key = ("apple", "orange");
match my_table.convert.get(&my_bad_key) {
None... |
pub const AI_NODE_UNDEFINED: i32 = 0;
pub const AI_NODE_OPTIONS: i32 = 0x0001;
pub const AI_NODE_CAMERA: i32 = 0x0002;
pub const AI_NODE_LIGHT: i32 = 0x0004;
pub const AI_NODE_SHAPE: i32 = 0x0008;
pub const AI_NODE_SHADER: i32 = 0x0010;
pub const AI_NODE_OVERRIDE: i32 = 0x0020;
pub const AI_NODE_DRIVER: i32 = 0x0040;
p... |
extern crate tar;
extern crate flate2;
use std::io::{self, Read};
use std::fs::{self, File};
use std::path::{Path, PathBuf};
use std::env;
use std::process;
fn decompress(tarpath: PathBuf, extract_path: PathBuf) -> io::Result<()> {
use flate2::read::GzDecoder;
use tar::Archive;
let tarball = fs::File::op... |
pub struct Solution;
impl Solution {
pub fn count_substrings(s: String) -> i32 {
let mut counter: i32 = 0;
let s = s.into_bytes();
let mut dp = vec![vec![false; s.len()]; s.len()];
for j in 0..s.len() {
for i in 0..j+1 {
if i == j{
dp... |
use crate::{
backend::SchemaBuilder, prepare::*, types::*, SchemaStatementBuilder, TableForeignKey,
};
/// Drop a foreign key constraint for an existing table
///
/// # Examples
///
/// ```
/// use sea_query::{*, tests_cfg::*};
///
/// let foreign_key = ForeignKey::drop()
/// .name("FK_character_font")
/// ... |
#![allow(unused_variables)]
#[macro_use] extern crate enum_primitive;
extern crate libc;
extern crate num;
extern crate vibi;
// extern crate bismit;
pub use vibi::bismit;
// use c_void;
use libc::c_void;
use std::fmt::Debug;
use std::thread::{self, JoinHandle};
use std::sync::{Arc, Mutex};
use std::sync::mpsc::{sel... |
use std::ffi::OsStr;
use std::process::exit;
use crate::cli::SudoOptions;
use crate::common::{resolve::expand_tilde_in_path, Context, Environment, Error};
use crate::env::environment;
use crate::exec::{ExecOutput, ExitReason};
use crate::log::{auth_info, auth_warn};
use crate::sudo::Duration;
use crate::sudoers::{Auth... |
use crate::{
error::{RunnerError, TestResult},
util::{get_db, test_existing_directory},
TestFamily, TestID, TestToken,
};
use glob::Pattern;
use hashbrown::HashMap;
use parking_lot::Mutex;
use std::path::{Path, PathBuf};
use valis::{
source::{File as ValisFile, Package, PackageBuilder, SourceDatabase},
... |
fn main() {
println!("Hello, world!");
println!("{}", find_file_extension("main.rs").unwrap());
println!("{}", find_file_extension2("main.rs").unwrap());
}
fn find_file_extension(file: &str) -> Option<&str> {
match file.find('.') {
Some(i) => Some(&file[i + 1..]),
None => None,
}
}
... |
#![allow(non_snake_case)]
#![allow(unused)]
mod parser;
use parser::*;
fn main() {
let mut tokenizer = Tokenizer::new();
let v = tokenizer.tokenize("if (a + b == 10) { print(\"123\") }");
println!("{:?}", v);
let mut tokenizer = Tokenizer::new();
let v = tokenizer.tokenize("fn print(a: String) { c... |
extern crate phrases;
use phrases::japanese;
use phrases::english::{greetings as en_greetings,farewells as en_farewells};
fn main(){
println!("Hello in English: {}",en_greetings::hello());
println!("GoodBye in English: {}",en_farewells::goodbye());
println!("Hello in Japanese: {}",japanese::hello());
... |
extern crate find_folder;
extern crate hound;
extern crate sample;
extern crate rand;
use sample::{signal, Signal};
use rand::{Rng, SeedableRng, StdRng};
pub const NUM_CHANNELS: usize = 2;
pub type Frame = [i16; NUM_CHANNELS];
const SAMPLE_RATE: f64 = 44_100.0;
#[macro_use]
extern crate clap;
use clap::{App, Arg}... |
// Copyright 2012 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 std::future::Future;
use std::sync::Arc;
use std::{fmt, io};
use once_cell::sync::Lazy;
pub(crate) mod time;
mod local_worker;
pub(crate) use local_worker::LocalHandle;
use local_worker::LocalWorker;
pub(crate) fn get_default_runtime_size() -> usize {
// We use num_cpus as std::thread::available_parallelis... |
// Copyright 2018-2019 Mozilla
//
// 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, sof... |
extern crate nom_locate;
extern crate safe_lua;
use nom_locate::LocatedSpan;
use safe_lua::compile::Sourcemap;
use safe_lua::compile::SourcemapLoc;
#[test]
fn test_sourcemaps() {
let loc_0 = LocatedSpan::new("Location Zero");
let mut sm = Sourcemap::new("loc");
sm.write_map(0, loc_0);
assert_eq!(sm.g... |
use std::collections::VecDeque;
fn main() -> std::io::Result<()> {
let input = std::fs::read_to_string("examples/22/input.txt")?;
let initial_decks: Vec<VecDeque<_>> = input
.split("\n\n")
.map(|x| {
x.lines()
.skip(1)
.map(|line| line.parse::<u64>().u... |
use libsdp::*;
#[test]
fn write() {
let timing = SdpTiming::new(2345, 2345);
let output = "2345 2345".to_string();
assert_eq!(output, format!("{}", timing));
}
#[test]
fn parse() {
let remains = vec![b'\r'];
let output = SdpTiming::new(2345, 2345);
let timing = "2345 2345\r";
assert_eq!(Ok... |
use bytes::{Buf, BufMut, Bytes, BytesMut};
use super::{Body, Frame};
use crate::error::RSocketError;
use crate::utils::Writeable;
#[derive(Debug, Eq, PartialEq)]
pub struct ResumeOK {
position: u64,
}
pub struct ResumeOKBuilder {
stream_id: u32,
flag: u16,
value: ResumeOK,
}
impl ResumeOKBuilder {
... |
pub const DISPLAY_HEIGHT_PX: u8 = 144;
pub const DISPLAY_WIDTH_PX: u8 = 160;
pub const TILE_SIZE_BYTES: usize = 16;
pub const TILE_DATA_TABLE_0_ADDR_START: u16 = 0x8800;
pub const TILE_DATA_TABLE_1_ADDR_START: u16 = 0x8000;
pub const SPRITE_PATTERN_TABLE_ADDR_START: u16 = 0x8000;
pub const SPRITE_ATTRIBUTE_TABLE: u1... |
use crate::ui::components::button_state_image::button_state_image;
use raui_core::prelude::*;
use serde::{Deserialize, Serialize};
#[derive(Debug, Default, Clone, Serialize, Deserialize)]
pub struct ImageButtonProps {
#[serde(default)]
pub id: String,
#[serde(default)]
pub horizontal_alignment: Scalar,... |
use std::fmt::Arguments;
use std::io::Write;
use std::fmt::Debug;
use std::io;
///Method of writing the data log
pub trait LogShape: Debug {
fn unknown<'s, W: Write>(write: W, name: &'static str, display: Arguments<'s>) -> io::Result<()>;
//[UNK] - unknown
fn trace<'s, W: Write>(write: W, line: u32, pos: u32, ... |
use proconio::{fastout, input};
use std::collections::VecDeque;
#[fastout]
fn main() {
input! {
n: usize,
a_vec: [i64; 3*n],
};
let a_vec: Vec<i64> = a_vec.iter().map(|a| a - 1).collect();
let mut dp: Vec<Vec<i64>> = vec![vec![i64::MIN; n + 1]; n + 1];
let upd = |dp: &mut Vec<Vec<i6... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.