text stringlengths 8 4.13M |
|---|
use serde::Deserialize;
use std::collections::HashMap;
use std::io;
use std::path::Path;
use thiserror::*;
use toml;
#[derive(Debug)]
pub struct Manifests {
manifests: HashMap<String, Manifest>,
}
#[derive(Debug, Clone, Deserialize)]
pub struct Manifest {
projects: HashMap<String, Project>,
}
#[derive(Clone,... |
// Copyright 2020, The Android Open Source Project
//
// 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... |
use std::collections::hash_map::Entry;
use std::collections::HashMap;
use std::fs::File;
use std::io::BufRead;
use std::io::BufReader;
use std::str::FromStr;
pub fn run_a() {
let lines: Vec<_> = BufReader::new(File::open("3.txt").expect("Unable to open file"))
.lines()
.map(Result::unwrap)
... |
#[cfg(loom)]
mod loom;
#[cfg(not(loom))]
mod noloom;
pub mod test;
#[cfg(not(loom))]
pub mod bench;
#[cfg(not(loom))]
pub mod test_waker;
#[cfg(not(loom))]
pub mod threadpool;
//mod allocator;
use crate::{Mutex, MutexGuard, thread, util};
use std::task::{Context, Poll};
use std::mem;
use crate::sync::Arc;
use std::pat... |
#![no_main]
extern crate libfuzzer_sys;
extern crate multipart;
#[macro_use]
extern crate log;
use multipart::server::{Multipart, MultipartData};
use multipart::mock::ServerRequest;
mod logger;
use std::io::BufRead;
const BOUNDARY: &'static str = "--12--34--56";
#[export_name="rust_fuzzer_test_input"]
pub extern ... |
use std::collections::{HashMap, HashSet};
use std::fmt;
use std::ops::{Deref, DerefMut};
use std::pin::Pin;
use std::str;
use async_channel::{self as channel, bounded};
#[cfg(feature = "runtime-async-std")]
use async_std::io::{Read, Write, WriteExt};
use base64::Engine as _;
use extensions::id::{format_identification,... |
struct OrderedStream {
vec: Vec<String>,
idx : usize
}
/**
* `&self` means the method takes an immutable reference.
* If you need a mutable reference, change it to `&mut self` instead.
*/
impl OrderedStream {
fn new(n: i32) -> Self {
let mut v = Vec::new();
for i in 0..n {
... |
/*
* Copyright (c) 2020 - 2021. Shoyo Inokuchi.
* Please refer to github.com/shoyo/jindb for more information about this project and its license.
*/
use crate::constants::{LsnT, TransactionIdT};
use std::collections::HashMap;
pub struct LogManager;
struct LogRecovery {
log_buffer: String,
/// Mapping of... |
#[allow(unused_imports)]
use serde_json::Value;
#[derive(Debug, Serialize, Deserialize)]
pub struct SettingsKrb5Realms {
#[serde(rename = "realm")]
pub realm: Option<Vec <crate::models::SettingsKrb5RealmsRealmItem>>,
}
|
pub mod kvs;
pub mod rangestore;
|
use tonic::{Request, Response, Status};
use super::{proto::*, CompactionRuntime};
pub struct CompactionService {
runtime: Box<dyn CompactionRuntime>,
}
impl CompactionService {
pub fn new(runtime: Box<dyn CompactionRuntime>) -> CompactionService {
CompactionService { runtime }
}
}
#[tonic::async... |
// Numeric enums do not work very well here, cause there is no good/fast way of converting u8 to enum
// Maybe would be possible to implement this as a macro
#[derive(Eq, PartialEq, Debug, Copy, Clone)]
pub struct Instruction {
pub opcode: u8,
pub size: u16,
}
const LIT_REG: u16 = 4;
const REG_LIT: u16 = 4;
co... |
// Copyright (c) The Starcoin Core Contributors
// SPDX-License-Identifier: Apache-2.0
#[cfg(testing)]
#[macro_use]
extern crate log;
pub use block_executor::{block_execute, BlockExecutedData};
pub use executor::*;
// pub use starcoin_transaction_builder::{
// build_accept_token_txn, build_batch_transfer_txn, bui... |
use std::thread;
use std::sync::mpsc; // ※ mpsc was an acronym for multiple producer, single consumer
use std::time::Duration;
// メッセージ受け渡しを使ってスレッド間でデータを転送する
#[test]
fn listing_16_7_to_16_9() {
let (tx, rx) = mpsc::channel(); // Listing 16-6: Creating a channel and assigning the two halves to tx and rx
// Lis... |
//! State DB
use crate::constant::MEMORY_BLOCK_NUMBER;
use crate::{smt_store_impl::SMTStore, traits::KVStore, transaction::StoreTransaction};
use anyhow::{anyhow, Result};
use gw_common::merkle_utils::calculate_state_checkpoint;
use gw_common::{error::Error as StateError, smt::SMT, state::State, H256};
use gw_db::sche... |
mod back_of_house {
pub struct Breakfast {
pub toast: String,
seasonal_fruit: String,
}
use std::fmt;
impl fmt::Display for Breakfast {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(
f,
"Breakfast:\ntoast: {}\n seasonal... |
/// Integer representation.
///
/// Reflects the types valid in `#[repr(...)]` for C-like enums, so should not be implemented for
/// additional types.
pub trait Repr: Copy + Eq + Ord {
/// Returns true if negative.
fn is_negative(self) -> bool;
/// Checked integer addition.
fn checked_add(self, other:... |
use log::debug;
use actix_web::{web, HttpRequest, HttpResponse};
use meilisearch_error::ResponseError;
use meilisearch_lib::index::{Settings, Unchecked};
use meilisearch_lib::index_controller::Update;
use meilisearch_lib::MeiliSearch;
use serde_json::json;
use crate::analytics::Analytics;
use crate::extractors::authe... |
struct Solution;
impl Solution {
fn next_closest_time(time: String) -> String {
let h = time[..2].parse::<usize>().unwrap();
let m = time[3..].parse::<usize>().unwrap();
let a = h / 10;
let b = h % 10;
let c = m / 10;
let d = m % 10;
let set = 1 << a | 1 << b... |
// http://aml3.github.io/RustTutorial/html/01.html
fn match_exercise(val : (int, bool)) {
match val {
(y, x) if x && (y >= 20) && (y <= 26) => println!("true and in range"),
(_, x) if x => println!("true and out of range"),
(y, _) if (y >= 40) && (y <= 49) => println!("unknown and in big range"),
_ => println... |
use rand::rngs::OsRng;
use serum_common::pack::Pack;
use serum_safe::accounts::Safe;
use serum_safe::client::InitializeResponse;
use serum_safe::error::SafeErrorCode;
use solana_client_gen::solana_sdk;
use solana_client_gen::solana_sdk::commitment_config::CommitmentConfig;
use solana_client_gen::solana_sdk::instruction... |
use core::slice::Iter;
/// Skip continuous digits
///
pub(crate) fn skip_digits(iter: &mut Iter<u8>) -> bool {
let mut any = false;
while let Some(digit) = iter.clone().next() {
if !digit.is_ascii_digit() {
break;
}
any = true;
iter.next().unwrap();
}
any
}
... |
// Copyright 2017 Dario Domizioli ("hhexo").
//
// 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. This file may not be copied, modified, or distributed
// excep... |
use super::*;
pub trait ToErrno: fmt::Display + fmt::Debug {
fn errno(&self) -> Errno;
}
impl ToErrno for Errno {
fn errno(&self) -> Errno {
*self
}
}
impl<T> From<T> for Error
where
T: ToErrno + 'static,
{
fn from(t: T) -> Error {
Error::boxed(t, None)
}
}
impl From<std::io:... |
#![feature(phase)]
#[phase(plugin)]
extern crate new_type;
pub type U = int;
#[deriving(Rand, Show, PartialEq, Eq)]
#[new_type]
pub struct T {
data: U
}
#[test]
fn equality() {
use std::rand;
let rand = rand::random::<U>();
let mut x: T = T::new(rand);
let mut y: T = T::new(rand);
let xs: [... |
pub struct Solution;
impl Solution {
#[allow(dead_code)]
pub fn max_profit(prices: Vec<i32>) -> i32 {
let mut profit = 0;
for (i, t) in prices.iter().enumerate() {
match prices.get(i + 1) {
Some(v) if v > t => profit += v - t,
_ => (),
}
... |
// This file is part of Substrate.
// Copyright (C) Parity Technologies (UK) Ltd.
// SPDX-License-Identifier: Apache-2.0
// 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.a... |
pub struct Sieve;
impl Sieve {
pub fn primes_up_to(n: i32) -> Vec<i32> {
(2..n+1).fold(vec![], |mut primes, x| {
if primes.iter().all(|&p| x % p != 0) {
primes.push(x);
};
primes
})
}
}
|
#[derive(Hash,Eq,PartialEq,Debug,Default,Clone)]
pub struct ListNode{
val:String,
next:Option<Box<ListNode>>,
}
#[derive(Hash,Eq,PartialEq,Debug,Default,Clone)]
pub struct LinkListStack{
node:Option<Box<ListNode>>,
}
impl ListNode{
fn new(val:String)->Self{
ListNode{
val:val,
... |
impl Solution {
pub fn combination_sum2(mut candidates: Vec<i32>, target: i32) -> Vec<Vec<i32>> {
candidates.sort();
let mut result = Vec::new();
let mut list = Vec::new();
dfs(0, 0, &mut list, &mut result, target, &candidates);
return result;
}
}
fn dfs(pos: usize, sum:... |
use std::cmp::Ordering;
use std::collections::HashMap;
use crate::intcode::{self, Intcode};
use crate::problem::Problem;
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
struct Position {
x: i32,
y: i32,
}
impl Position {
fn update(&mut self, dir: Direction) {
match dir {
Direction::Left => self.x ... |
use serde::Deserialize;
use std::env;
use std::fs::File;
use std::io::Read;
use std::path::PathBuf;
#[derive(Debug, Deserialize)]
pub struct Config {
pub database: DatabaseConfig,
pub sabnzbd: SabnzbdConfig,
pub dognzb: DognzbConfig,
}
#[derive(Debug, Deserialize)]
pub struct SabnzbdConfig {
pub url: ... |
#[doc = r"Register block"]
#[repr(C)]
pub struct NFC {
#[doc = "0x00 - Default header for NFC Tag. Software can read these values to populate NFCID1_3RD_LAST, NFCID1_2ND_LAST and NFCID1_LAST."]
pub tagheader0: TAGHEADER0,
#[doc = "0x04 - Default header for NFC Tag. Software can read these values to populate... |
use std::collections::HashMap;
#[derive(Serialize, Deserialize, Debug)]
pub struct KubeSecret {
#[serde(rename = "apiVersion")]
api_version: String,
kind: String,
pub metadata: MetaData,
#[serde(skip_serializing)]
pub delete: bool,
#[serde(rename = "type")]
resource_type: String,
... |
use std::collections::HashSet;
use std::convert::TryFrom;
use std::fmt;
use std::str::FromStr;
use itertools::Itertools;
use crate::math::Vector2;
#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)]
enum Location {
Floor,
FilledSeat,
EmptySeat,
}
impl TryFrom<char> for Location {
type Error = String;... |
use crate::{crypto, database::Actor as DbActor, error::Error, state::ArcState, util::HTTP_CLIENT};
use futures_util::stream::{FuturesUnordered, StreamExt};
use itertools::Itertools;
use reqwest::{
header::{HeaderName, HeaderValue, DATE},
Client, Request, Response,
};
use std::{future::Future, sync::Arc};
use ti... |
/*
* @lc app=leetcode id=665 lang=rust
*
* [665] Non-decreasing Array
*
* https://leetcode.com/problems/non-decreasing-array/description/
*
* algorithms
* Easy (19.46%)
* Total Accepted: 67.5K
* Total Submissions: 348.3K
* Testcase Example: '[4,2,3]'
*
*
* Given an array with n integers, your task is... |
#![allow(non_upper_case_globals)]
pub use self::x86_shared::*;
use core::mem::size_of;
mod x86_shared;
bitflags! {
pub flags GdtAccess: u8 {
const Accessed = 1 << 0,
const Writable = 1 << 1,
const Direction = 1 << 2,
const Executable = 1 << 3,
const NotTss = 1 << 4,
}
}
#[derive(Copy, Clone, Debug)]
#[... |
//! File uploads for use around the platform.
use crate::{error::Result, http::TrySend, Client};
use bytes::Bytes;
use futures::{TryStream, TryStreamExt};
use reqwest::{
multipart::{Form, Part},
Body,
};
use serde::{Deserialize, Serialize};
use std::{borrow::Cow, error::Error};
/// Returns a handle to an empt... |
fn next_two(x: int) -> (int, int) {
(x + 1i, x + 2i)
}
fn main() {
let (x, y) = next_two(5i);
println!("x, y = {}, {}", x, y);
}
|
use crate::controllers::user::UpdateRequest;
use crate::controllers::user::StoreRequest;
use crate::entities::models::User;
use rocket::http::Status;
use rocket::request::Form;
use rocket::response::{Redirect, Responder};
use rocket::FromForm;
use rocket::{get, post};
use rocket_contrib::templates::Template;
use serde_... |
use std::ffi::{OsStr, OsString};
use std::fs::{File, OpenOptions};
use std::io::{BufRead, BufReader, BufWriter, Write};
use std::ops::Deref;
use std::path::{Path, PathBuf};
use std::process::Command;
use std::sync::Arc;
use std::time::Instant;
use std::{env, fs, io, thread};
use opencv_binding_generator::{Generator, I... |
use std::io;
use crate::{
impl_serialize_primitive,
wire_fmt::{HasWireType, WireType},
};
impl HasWireType for &str {
const WIRE_TYPE: WireType = WireType::Sized;
}
fn compute_size(value: &str) -> u32 {
value.len() as u32
}
fn serialize(value: &str, writer: &mut impl io::Write) -> io::Result<()> {
... |
pub use super::error::Error;
pub fn split_off_at<'inner, 'outer>(
response: &'outer mut &'inner [u8],
idx: usize,
) -> Result<&'inner [u8], Error> {
let (head, tail) = {
let old_resp = *response;
// TODO why no non-panicking split at....
if old_resp.len() < idx {
return ... |
#[macro_use]
extern crate diesel;
use diesel::{
expression::{nullable::Nullable, operators::Eq, BoxableExpression},
pg::Pg,
query_dsl::{QueryDsl, RunQueryDsl},
query_source::{
joins::{Join, JoinOn, LeftOuter},
AppearsInFromClause, Once,
},
sql_types::Bool,
ExpressionMethods,
... |
extern crate bollard;
extern crate futures;
extern crate hyper;
extern crate tokio;
extern crate tokio_reactor;
extern crate tokio_threadpool;
extern crate tokio_timer;
use bollard::system::Version;
use bollard::{ClientVersion, Docker, API_DEFAULT_VERSION};
use futures::Async;
use hyper::rt::Future;
use tokio::executo... |
use super::automaton::Automaton;
pub type NFAState = Vec<usize>;
pub struct NFAOne {
pub states_size: usize,
pub start: usize,
pub accept: NFAState,
pub transition_func: Box<dyn Fn(usize, Option<char>) -> NFAState>,
}
impl NFAOne {
fn gen_state(has_state: Vec<bool>) -> NFAState {
has_state
.iter(... |
// 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 winit::{
event::*,
event_loop::{ControlFlow, EventLoop},
window::WindowBuilder,
};
extern crate trips;
fn main() {
let event_loop = EventLoop::new();
let window = WindowBuilder::new().build(&event_loop).unwrap();
let mut renderer = trips::Renderer::new(&window);
let mut mesh_obj =... |
//! # UI - terminal user interface to visualize tree exploration for PUCT
//!
//! Usage: `cargo run --release --bin ui -- -c breakthrough -m alpha`
//!
//! Keyboard and mouse can be used to play the game step by step while
//! inspecting the tree search.
#![allow(non_snake_case)]
use ggpf::game::breakthrough::{ui::IB... |
use std::fs::File;
use std::io::ErrorKind;
fn main() {
let f = File::open("hello.txt");
let f = match f {
Ok(file) => file,
Err(error) => match error.kind() {
ErrorKind::NotFound => match File::create("hello.txt") {
Ok(fc) => fc,
... |
use crate::libs::responders::EZRespond;
use rocket::http::Status;
#[catch(401)]
pub fn unauthorized<'r>() -> EZRespond<'r> {
EZRespond::by_status(Status::Unauthorized)
}
|
// Copyright (c) The cargo-guppy Contributors
// SPDX-License-Identifier: MIT OR Apache-2.0
//! A sorted, deduplicated list of features from a single package.
use crate::graph::feature::FeatureId;
use crate::graph::PackageMetadata;
use crate::sorted_set::SortedSet;
use crate::PackageId;
use std::fmt;
use std::slice;
... |
//! # Spawn any entity
//!
//! Command to spawn an entity with the correct type and the given instructions.
use packets::Packet;
use sys::Vector;
use std::io::Cursor;
use packets::byteorder::{BigEndian, ReadBytesExt, WriteBytesExt};
pub struct SpawnEntity {
/// The id of the entity in the game world. Later it is go... |
// Copyright 2019 WHTCORPS INC Project Authors. Licensed under Apache-2.0.
use super::super::Result;
use super::{JsonRef, JsonType};
impl<'a> JsonRef<'a> {
/// Returns maximum depth of JSON document
pub fn depth(&self) -> Result<i64> {
depth_json(&self)
}
}
// See `GetElemDepth()` in MilevaDB `js... |
extern crate unicode_segmentation;
use unicode_segmentation::UnicodeSegmentation;
pub fn reverse(input: &str) -> String {
let rev:String = input.graphemes(true).rev().collect();
rev
}
|
use perseus::{ErrorCause, StringResultWithCause, Template};
use serde::{Deserialize, Serialize};
use std::sync::Arc;
use sycamore::prelude::{component, template, GenericNode, Template as SycamoreTemplate};
#[derive(Serialize, Deserialize)]
pub struct PostPageProps {
title: String,
content: String,
}
#[compone... |
// generated by swagger-codegen-rs
use failure::Error;
use reqwest::Client;
use reqwest::header::Headers;
use reqwest::Url;
#[derive(Clone, PartialEq, Serialize, Deserialize)]
pub struct Address {
#[serde(rename = "Addr")]
pub addr: String,
#[serde(rename = "PrefixLen")]
pub prefix_len: i64,
}
#[deriv... |
use std::fs::File;
use std::io::ErrorKind;
use std::io;
use std::io::Read;
use std::fs;
fn main() {
println!("Hello, world!");
tpanicc();
}
fn tpanicc(){
//panic!("crash and burn");
let v = vec![1,2,3];
//v[111];
let f = File::open("hello12.txt");
let f = match f{
Ok(file) ... |
// vim: tw=80
use futures::{Async, Future, Poll, unsync::oneshot};
use std::{
cell::RefCell,
cmp::{Ord, Ordering, PartialOrd},
collections::BinaryHeap,
collections::VecDeque,
io,
mem,
num::NonZeroU64,
path::Path,
rc::{Rc, Weak},
ops,
time,
};
#[cfg(test)] use mockall::*;
use... |
//! HTTP/2 frames.
mod data_frame;
mod frame_flag;
mod frame_header;
mod frame_header_inflate_flags;
mod frame_kind;
mod headers_frame;
mod settings_frame_kind;
pub use crate::frames::data_frame::DataFrame;
pub use crate::frames::frame_flag::FrameFlag;
pub use crate::frames::frame_header::FrameHeader;
pub use crate::... |
use crate::physical_plan::executors::evaluate_physical_expressions;
use crate::physical_plan::state::ExecutionState;
use crate::prelude::*;
use polars_core::prelude::*;
/// Take an input Executor (creates the input DataFrame)
/// and a multiple PhysicalExpressions (create the output Series)
pub struct ProjectionExec {... |
use std::process;
use aoc::get_input;
use aoc::intcode::Program;
fn main() {
let memory = get_input()
.trim()
.split(',')
.map(|x| x.trim().parse().expect("NaN"))
.collect();
let scan = |x, y| {
let mut p = Program::new(&memory);
p.set_input(x);
p.set_in... |
//
//! Copyright 2020 Alibaba Group Holding Limited.
//!
//! 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 ... |
extern crate term_painter;
use term_painter::ToStyle;
use term_painter::Color::Custom;
use term_painter::Attr::Plain;
fn main() {
// print 16 colors each line
for line in 0..16 {
// foreground
print!("FG: ");
for c in (0..16).map(|i| 16*line + i) {
print!("{: <2x} ", Custo... |
// Copyright (c) 2022 PHPER Framework Team
// PHPER is licensed under Mulan PSL v2.
// You can use this software according to the terms and conditions of the Mulan
// PSL v2. You may obtain a copy of Mulan PSL v2 at:
// http://license.coscl.org.cn/MulanPSL2
// THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WIT... |
use crate::{prelude::*, supervisor::linker::Linker, devices::VstBufferedDevice};
use std::{
ffi::c_void,
sync::{Arc, RwLock},
};
use vst::{
api::{self, TimeInfo},
buffer::AudioBuffer,
editor::Editor,
host::{Host, PluginInstance},
plugin::{Info, Plugin},
};
/// Unique id assigned to a vst in... |
#[derive(Debug, PartialEq)]
pub enum Errors {
EmptyGraph
}
pub struct Graph {
vertices: i32,
items: Vec<Vec<i32>>
}
#[derive(PartialEq, Clone, Debug)]
pub enum Visited {
Yes,
No
}
#[derive(Clone, Debug)]
pub struct Dijkstra {
distance: i32,
visited: Visited,
}
impl Dijkstra {
pub fn ... |
#![cfg_attr(feature = "clippy", feature(plugin))]
#![cfg_attr(feature = "clippy", plugin(clippy))]
#![feature(extern_prelude)]
#![recursion_limit = "128"] // Necessary for SVar generation via mashup
#![allow(unknown_lints)]
#![warn(clippy)]
extern crate chrono;
extern crate config;
extern crate fuzzy_match;
#[macro_us... |
#[macro_use] extern crate lazy_static;
use std::collections::{HashMap, HashSet, VecDeque};
use util::res::Result;
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
enum Side {
Right,
Left,
Top,
Bottom,
}
#[derive(Clone)]
struct Tile {
id: u64,
pixels: [[bool; 10]; 10],
edges: HashMap<Side, [boo... |
extern crate bip_handshake;
extern crate futures;
extern crate tokio_core;
use std::time::Duration;
use std::thread;
use std::io::{self, Write, BufRead};
use std::net::{SocketAddr, ToSocketAddrs};
use bip_handshake::{HandshakerBuilder, InitiateMessage, Protocol};
use bip_handshake::transports::TcpTransport;
use futur... |
//! # config
//!
//! The `config` module is responsible for loading
//! important pieces of information that the package manager
//! needs to know in order to do its job. This information
//! is held in a configuration file. Without it, we would be lost.
//! The configuration file points the program to where to install... |
#[macro_use]
extern crate lazy_static;
#[allow(unused_imports)]
#[macro_use]
extern crate aoc_runner_derive;
extern crate pest;
#[macro_use]
extern crate pest_derive;
mod days;
mod macros;
use aoc_runner_derive::aoc_main;
aoc_main! { year = 2020 }
|
/*
Symmetric Key Encryption Scheme.
*/
use std::fmt;
use sodiumoxide;
use sodiumoxide::init;
use sodiumoxide::crypto::secretbox;
pub struct SymCT {
nonce: secretbox::Nonce,
ciphertext: Vec<u8>
}
impl fmt::Display for SymCT {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let mut y_s =... |
use super::IRustError;
use std::fs;
use std::path;
/// Mark to keep backward-compatibility with the old way of saving history
const NEW_HISTORY_MARK: &str = "##NewHistoryMark##\n//\n";
#[derive(Default)]
pub struct History {
history: Vec<String>,
buffer_copy: String,
cursor: usize,
path: path::PathBuf... |
use crate::input::get_lines;
use std::{
collections::{HashMap, HashSet},
usize,
};
pub fn run() {
let lines = get_lines("day09");
println!("part1: {}", shortest(&lines));
println!("part2: {}", longest(&lines));
}
#[derive(Clone)]
enum Method {
Min,
Max,
}
impl Copy for Method {}
fn pre... |
use std::str;
use std::process::Command;
use serde::{Serialize, Deserialize};
use serde_json as json;
use super::Error;
/// A wrapper for the result of calling `arduino-cli board list --format json`, in order to take
/// advantage of serde's derived JSON (de)serialization.
#[derive(Serialize, Deserialize)]
#[allow(no... |
extern crate argparse;
extern crate hashbrown;
extern crate r2pipe;
extern crate ring;
extern crate serde_json;
use argparse::{ArgumentParser, Store, StoreOption, StoreTrue};
use hashbrown::HashMap;
use r2pipe::{R2Pipe, R2PipeSpawnOptions};
use ring::{digest, test};
use std::fs;
use std::fs::File;
use std::io::prelude... |
mod inp;
mod long_inc_subseq;
use long_inc_subseq::longest_increasing_subsequence;
use inp::Inp;
fn main() {
let mut inp = Inp::new();
println!("{}", 26 - longest_increasing_subsequence(&inp.next_line().trim().as_bytes()));
}
|
extern crate chrono_english;
#[macro_use]
extern crate lazy_static;
#[macro_use]
extern crate prettytable;
extern crate clap;
use chrono::Local;
use chrono_english::{parse_date_string, Dialect};
use clap::{App, Arg, ArgMatches, SubCommand};
use prettytable::{Cell, Row, Table};
use std::cmp::Ordering;
use termion::{col... |
// This file is part of Substrate.
// Copyright (C) Parity Technologies (UK) Ltd.
// SPDX-License-Identifier: GPL-3.0-or-later WITH Classpath-exception-2.0
// This program 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 Softwa... |
mod config;
use std::env;
use std::error;
use std::fs::File;
use std::io::prelude::*;
use std::io::{self, BufRead, Error, LineWriter};
use std::path::Path;
use std::sync::mpsc::channel;
use threadpool::ThreadPool;
fn executable_path() -> Result<String, Error> {
let mut dir = env::current_exe()?;
dir.pop();
... |
use crate::{
types::OscMessage, types::OscType, AfterCallAction, OscResponder, ScClientResult, ServerVersion,
};
pub struct VersionResponder<F: Fn(ServerVersion) + Send + Sync + 'static> {
on_reply_callback: F,
}
impl<F: Fn(ServerVersion) + Send + Sync + 'static> VersionResponder<F> {
pub fn new(on_reply_... |
use std::time::Duration;
/// Handel configuration settings
#[derive(Clone, Debug)]
pub struct Config {
/// Number of peers contacted during an update at each level
pub update_count: usize,
/// Frequency at which updates are sent to peers
pub update_interval: Duration,
/// Timeout for levels
p... |
// Copyright 2020-2022 The NATS 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 or agreed to ... |
// Copyright 2020 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 std::error::Error as StdError;
use std::fmt;
use tracing::error;
use tracing_error::SpanTrace;
#[derive(Debug, thiserror::Error)]
pub struct Error {
source: ErrorKind,
span_trace: SpanTrace,
}
#[derive(Debug, thiserror::Error)]
pub enum ErrorKind {
#[error(transparent)]
Fatal(anyhow::Error),
#... |
use dymod::dymod;
dymod! {
#[path = "../subcrate/src/lib.rs"]
pub mod subcrate {
fn count_sheep(sheep: u32) -> &'static str;
}
}
fn main() {
#[cfg(debug_assertions)]
const MESSAGE: &str = "
You are running in debug mode.
Make changes to subcrate/src/lib.rs
Then run `cargo build` in the sub... |
#![feature(proc_macro_hygiene, decl_macro)]
#[macro_use]
mod response;
mod cli;
mod routes;
mod rsp;
use cli::Cli;
use std::process::Command;
use std::{env, thread, time};
use lazy_static::lazy_static;
use rocket::{catchers, routes};
use structopt::StructOpt;
lazy_static! {
pub static ref OPT: Cli = Cli::from_arg... |
mod parsers;
mod settings;
mod types;
pub use self::settings::ShibaSettings;
use self::types::*;
use super::ShaderProvider;
use crate::build::{BuildOptions, BuildTarget};
use crate::hash_extra;
use crate::parsers::glsl;
use crate::project_data::Project;
use crate::project_files::{FileConsumer, IsPathHandled};
use crat... |
struct Solution;
use std::collections::VecDeque;
struct Orange {
r: usize,
c: usize,
t: i32,
}
impl Solution {
fn oranges_rotting(mut grid: Vec<Vec<i32>>) -> i32 {
let n = grid.len();
let m = grid[0].len();
let mut queue: VecDeque<Orange> = VecDeque::new();
for i in 0.... |
mod lexer;
mod parser;
mod record;
|
#[doc = "Register `P1IV` reader"]
pub struct R(crate::R<P1IV_SPEC>);
impl core::ops::Deref for R {
type Target = crate::R<P1IV_SPEC>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl From<crate::R<P1IV_SPEC>> for R {
#[inline(always)]
fn from(reader: crate::R<P1IV_SP... |
#[test]
fn adt_example() {
#[allow(dead_code)]
enum WeakLogicValues {
True(bool),
False(bool),
HalfTrue(bool),
}
// WeakLogicValues = bool + otherbool + anotherbool
#[allow(dead_code)]
struct Point {
x: i32,
y: i32,
}
}
|
// validbr - Brazilian registry validator, provides structures for representing CPF, CNPJ, RG, CNH, CEP and Credit Card Number!
//
// The MIT License (MIT)
//
// Copyright (c) Obliter Software (https://github.com/oblitersoftware/)
// Copyright (c) contributors
//
// Permission is hereby grant... |
#![allow(clippy::many_single_char_names)]
#![allow(clippy::type_complexity)]
#![allow(clippy::mutex_atomic)]
use num::traits::{
float::{Float, FloatConst},
NumCast,
};
use rayon::scope;
use std::sync::Mutex;
//use num_traits::identities::{one, zero};
use rand::{
distributions::{uniform::SampleUniform, Dist... |
use std::{ops, sync::Arc, time::Duration};
use futures::future::BoxFuture;
use nimiq_network_interface::network::{Network, PubsubId};
use nimiq_primitives::{key_nibbles::KeyNibbles, trie::trie_diff::TrieDiff, TreeProof};
use parking_lot::RwLock;
use tokio::{sync::Semaphore, time};
use super::{RequestPartialDiff, Resp... |
use std::ops::Bound;
use anyhow::anyhow;
use chrono::{DateTime, Duration, Utc};
use diesel::pg::PgConnection;
use serde::Serialize;
use svc_agent::{
mqtt::{
IncomingRequestProperties, IntoPublishableMessage, OutgoingEvent, OutgoingEventProperties,
OutgoingResponse, ResponseStatus, ShortTermTimingPr... |
//! Vacuum a Delta table
//!
//! Run the Vacuum command on the Delta Table: delete files no longer referenced by a Delta table and are older than the retention threshold.
//! We do not recommend that you set a retention interval shorter than 7 days, because old snapshots
//! and uncommitted files can still be in use by... |
//------------------------------------------------------------------------------
// path_enums.rs
//------------------------------------------------------------------------------
// Provides the enums to configure all the process of path splitting, stroke
// generation and compiling
//----------------------------------... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.