text stringlengths 8 4.13M |
|---|
#[doc = r" Value read from the register"]
pub struct R {
bits: u32,
}
#[doc = r" Value to write to the register"]
pub struct W {
bits: u32,
}
impl super::IES {
#[doc = r" Modifies the contents of the register"]
#[inline]
pub fn modify<F>(&self, f: F)
where
for<'w> F: FnOnce(&R, &'w mut W... |
//! Definition of linear combinations.
use curve25519_dalek::scalar::Scalar;
use std::iter::FromIterator;
use std::ops::{Add, Mul, Neg, Sub};
/// Represents a variable in a constraint system.
#[derive(Copy, Clone, Debug, PartialEq)]
pub enum Variable {
/// Represents an external input specified by a commitment.
... |
extern crate mpd;
#[macro_use]
extern crate serde_derive;
extern crate serde_json;
extern crate serde;
use mpd::Client;
#[derive(Serialize, Debug)]
struct JsonSong {
file: String,
title: String,
album: String,
artist: String,
duration: String,
}
pub fn play(mut conn: Client) { conn.play().unwra... |
use aoc_runner_derive::{aoc, aoc_generator};
use std::collections::VecDeque;
use std::num::ParseIntError;
type Player = VecDeque<usize>;
type PlayersState = Vec<Player>;
#[aoc_generator(day22)]
fn parse_input_day1(input: &str) -> Result<PlayersState, ParseIntError> {
input
.split("\n\n")
.map(|p| ... |
fn main() {
const MAX_POINTS: u32 = 100_000;
let x = 5;
println!("The value of x is: {}", x);
let x = x + 1;
let x = x * MAX_POINTS;
println!("The value of x is: {}", x);
let spaces = " ";
let spaces: usize = spaces.len();
}
|
pub mod cache;
pub mod git;
pub mod repo;
pub mod util;
|
//! Mock objects, useful in testing and development.
pub mod runtime;
pub mod transport;
|
use crate::config_instruction::ConfigInstruction;
use crate::ConfigState;
use solana_sdk::hash::Hash;
use solana_sdk::pubkey::Pubkey;
use solana_sdk::signature::{Keypair, KeypairUtil};
use solana_sdk::transaction::Transaction;
pub struct ConfigTransaction {}
impl ConfigTransaction {
/// Create a new, empty config... |
use caolo_sim::{
components::UserProperties,
prelude::{UserId, View},
};
use tokio::sync::mpsc;
use tokio_stream::wrappers::ReceiverStream;
use tonic::Status;
use tracing::info;
use uuid::Uuid;
use crate::{
input::users,
protos::{cao_common, cao_users},
};
#[derive(Clone)]
pub struct UsersService {
... |
// Copyright 2019 Steven Bosnick
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE-2.0 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
// except accord... |
use std::fs;
fn main() {
let text = fs::read_to_string("../11_input.txt").unwrap();
let lines: Vec<&str> = text
.split("\n")
.collect();
let mut matrix: Vec<Vec<i32>> = Vec::new();
for line in lines.into_iter() {
matrix.push(
line.split(" ")
.m... |
use std::{convert::Infallible, sync::Arc};
use bonsaidb_core::schema::{view, InvalidNameError};
use nebari::AbortError;
use crate::vault;
/// Errors that can occur from interacting with storage.
#[derive(thiserror::Error, Debug)]
pub enum Error {
/// An error occurred interacting with the storage layer, `nebari`... |
use std::{env, fs::{File, OpenOptions}, io::{Error, Read, Write}, path::Path};
use serde::{Serialize, Deserialize};
use serde_json;
#[derive(Serialize, Deserialize)]
struct Todo {
text: String,
tag: String,
}
impl Todo {
fn new(text: String, tag: String) -> Self {
Self {
text, tag
... |
use serde_derive::Deserialize;
use std::collections::BTreeMap;
#[derive(Deserialize)]
pub struct BookmarkList(pub BTreeMap<String, String>);
impl BookmarkList {
pub fn to_string(&self) -> String {
self.0
.iter()
.map(|(key, value)| format!("\x1B[1m{}\x1B[0m \x1B[38;5;249m{}\x1B[0m"... |
/*!
```rudra-poc
[target]
crate = "csv-sniffer"
version = "0.1.1"
[report]
issue_url = "https://github.com/jblondin/csv-sniffer/issues/1"
issue_date = 2021-01-05
rustsec_url = "https://github.com/RustSec/advisory-db/pull/666"
rustsec_id = "RUSTSEC-2021-0088"
[[bugs]]
analyzer = "UnsafeDataflow"
bug_class = "UninitExp... |
fn main() {
let plus_one = |x:i32| -> i32 { x + 1 };
let a = 6;
println!("{} + 1 = {}", a, plus_one(a));
let mut b = 2;
{
let plus_two = |x|
{
let mut z = x;
z += b;
z
};
println!("{} + 2 = {}", 3, plus_two(3));
}
// T ... |
extern crate alga;
#[macro_use]
extern crate alga_derive;
extern crate approx;
extern crate quickcheck;
use alga::general::{AbstractMagma, Additive, Identity, Multiplicative, TwoSidedInverse, Field};
use approx::{AbsDiffEq, RelativeEq, UlpsEq};
use quickcheck::{Arbitrary, Gen};
use num_traits::{Zero, One};
use std::... |
//! # ez-pixmap
//!
//! A naive and easy inline pixmap (xpm-like) image decoder.
//! This is non-compliant with xpm image format, however it's close enough.
//! - Doesn't support monochrome nor symbolics.
//! - Supports only 1 character per pixel.
//!
//! Main use case: Simple icon art.
//!
//! ## Usage
//! ```ignored... |
use std::io::Read;
use std::path::Path;
use std::fs::File;
#[macro_use]
extern crate sdl2;
extern crate nes;
mod gui;
fn main() {
let path_str = String::from("../test-roms/spritecans.nes");
println!("{}", path_str);
let mut gui = gui::GuiObject::new();
gui.load_rom_from_file(Path::new(&path_str)).... |
extern crate termion;
mod event;
pub use event::*;
mod editor;
pub use editor::*;
mod complete;
pub use complete::*;
mod context;
pub use context::*;
mod buffer;
pub use buffer::*;
mod util;
#[cfg(test)]
mod test;
|
use actix_web::{HttpResponse, http::StatusCode};
pub struct DateVal(chrono::NaiveDate);
impl DateVal {
// Could also implement some ToString, Into<String> ? Not sure which makes sense
pub fn format(&self) -> String {
self.0.format("%Y-%m-%d").to_string()
}
pub fn try_from(from: &str) -> crate:... |
// Copyright 2012-2014 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-MI... |
use crate::ir;
use nom::{
branch::alt,
bytes::complete::{tag, take_while, take_while1},
character::complete::{char, digit1, hex_digit1, multispace1, not_line_ending, space0, space1},
combinator::{all_consuming, map, map_res, value},
multi::{fold_many0, many0},
sequence::{preceded, terminated, tu... |
//! Wrapper types for *fusing* guard instances and protected pointers or
//! references.
use core::convert::TryInto;
use core::fmt;
use core::mem;
use conquer_pointer::{MarkedNonNull, MarkedPtr, Null};
use crate::{Protect, Protected, Shared};
// **********************************************************************... |
use std::env;
use std::fs::File;
use std::io::{LineWriter, Write};
use regex::Regex;
use walkdir::WalkDir;
pub fn find_cleaned_fastq(path: &str, len: usize, sep: char, iscsv: bool) {
let save_names = get_fnames(iscsv);
let output = File::create(&save_names).expect("FILE EXISTS.");
let mut line = LineWrite... |
use std::net::{SocketAddr, TcpListener, Ipv4Addr};
use std::sync::Arc;
use openssl::{pkey, x509};
use crate::builder::ContextBuilder;
use crate::context::ContextStore;
use crate::session::SessionStore;
mod builder;
mod context;
mod session;
const CERTIFICATE: &[u8] = include_bytes!("certificate.pem");
const PRIVATE... |
#[macro_use]
extern crate proc_macro_hack;
#[allow(unused_imports)]
#[macro_use]
extern crate unsauron_impl;
#[doc(hidden)]
pub use unsauron_impl::*;
proc_macro_expr_decl! {
unsauron! => expand_unsauron
}
|
// #![feature(async_closure)]
use frontend::Driver;
fn main() -> std::io::Result<()> {
let driver = Driver::new();
let _ = futures::executor::block_on(driver.parse_module("test.txt".to_string()));
Ok(())
}
|
use std::ops::{Index, IndexMut};
use typehack::data::*;
use typehack::dim::*;
use typehack::binary::Nat as BNat;
use typehack::binary::I;
use typehack::peano::Nat as PNat;
use typehack::peano::{S, Z};
use typehack::tvec::*;
#[macro_export]
macro_rules! Dims {
($t:ty $(, $rest:ty)*) => ($crate::typehack::tvec::TC... |
#[derive(Debug, PartialEq)]
struct User {
username: String,
email: String,
sign_in_count: u64,
active: bool,
}
// 传入参数变量构造结构体
fn build_user(username: String, email: String) -> User {
User {
username: username,
email: email,
active: true,
sign_in_count: 1,
}
... |
#[macro_use]
extern crate serde;
pub mod access_token {
include!("./access_token.rs");
}
pub mod add_collaborator_option {
include!("./add_collaborator_option.rs");
}
pub mod add_time_option {
include!("./add_time_option.rs");
}
pub mod annotated_tag {
include!("./annotated_tag.rs");
}
pub mod ann... |
use chrono::prelude::*;
use serde::{Deserialize, Serialize};
#[derive(PartialEq, Clone, Serialize, Deserialize, Debug)]
pub struct EchoMsg {
pub payload: String,
pub ts: DateTime<Utc>,
}
|
use structopt::StructOpt;
#[derive(Debug, StructOpt)]
struct Cli {
//pattern: String,
#[structopt(parse(from_os_str))]
path: std::path::PathBuf,
}
fn main() -> Result<(), Box<dyn std::error::Error>> {
let args = Cli::from_args();
let path_exists = obliterate::file_io::path_exists(&args.path);
... |
use serde::{Deserialize, Serialize};
#[derive(Debug, Clone, Copy, Eq, PartialEq, Serialize, Deserialize, Hash)]
pub enum ToolOptions {
Select { append_mode: SelectAppendMode },
Ellipse,
Shape { shape_type: ShapeType },
}
#[derive(Debug, Clone, Copy, Eq, PartialEq, Serialize, Deserialize, Hash)]
pub enum SelectAppe... |
use htmldsl::attributes;
use htmldsl::elements;
use htmldsl::units;
use htmldsl::TagRenderableIntoElement;
use crate::html::shared;
use crate::html::util;
use crate::models;
pub fn page<'a>(game: models::Game) -> elements::Body<'a> {
elements::Body::style_less(vec![
shared::index_link(),
shared::g... |
use crate::importer::state::Difference;
use git2::Cred;
use git2::RemoteCallbacks;
use git2::Repository;
use std::error::Error;
use std::{
fs, io,
path::{Path, PathBuf},
};
use log::{debug, info};
pub fn find_equal_files<F>(
src: &Path,
dest: &Path,
cur: &Path,
ignore_files: &Vec<PathBuf>,
... |
pub fn day1(){
use std::fs;
let input = fs::read_to_string("inputs/d1").unwrap();
let values : Vec<i64> =
input
.lines()
.filter_map(|s| s.parse::<i64>().ok())
.collect();
// PART 1
// inefficient implementation: compare each integer with each other int... |
#![feature(slice_patterns)]
pub mod eval;
pub mod lexer;
pub mod parser;
|
#![allow(unused_parens)]
use shorthand::ShortHand;
#[derive(ShortHand, Default)]
struct Example {
value: (u8),
}
fn main() { let _: (u8) = Example::default().value(); }
|
#![forbid(unsafe_code)]
#![warn(rust_2018_idioms, single_use_lifetimes, unreachable_pub)]
#![warn(clippy::pedantic)]
#![allow(
clippy::match_same_arms,
clippy::similar_names,
clippy::single_match_else,
clippy::struct_excessive_bools,
clippy::too_many_lines
)]
// Refs:
// - https://doc.rust-lang.org... |
#[doc = r"Register block"]
#[repr(C)]
pub struct RegisterBlock {
#[doc = "0x00 - DCACHE control register"]
pub cr: CR,
#[doc = "0x04 - DCACHE status register"]
pub sr: SR,
#[doc = "0x08 - DCACHE interrupt enable register"]
pub ier: IER,
#[doc = "0x0c - DCACHE flag clear register"]
pub fc... |
use core::{iter, ops::Deref as _};
use anyhow::{bail, ensure, Error, Result};
use error_utils::{DebugAsError, SyncError};
use eth2_libp2p::{
rpc::{
methods::{BlocksByRangeRequest, BlocksByRootRequest, GoodbyeReason, StatusMessage},
ErrorMessage, RPCError, RPCErrorResponse, RPCRequest, RPCResponse, ... |
use crate::scene::SceneItem;
use crate::vector::Vec3;
use crate::ray::Ray;
use crate::intersectable::{Intersectable, Intersection};
use rand::Rng;
use std::f64;
use std::cmp::Ordering;
use std::mem;
#[derive(Copy, Clone, Debug)]
pub struct AABB {
min: Vec3,
max: Vec3
}
impl AABB {
pub fn new(a: Vec3, b: ... |
use array2d::Array2D;
fn format_board(board: &Array2D<String>) -> String {
board
.rows_iter()
.map(|row_iter| row_iter.cloned().collect::<Vec<_>>().join("|"))
.collect::<Vec<_>>()
.join("\n-----\n")
}
fn main() {
let mut board = Array2D::filled_with(" ".to_string(), 3, 3);
... |
use std::collections::HashMap;
use prettytable::{Attr, Cell, Row, Table};
use crate::github;
fn insert_headers(header_one: &mut Vec<Cell>, header_two: &mut Vec<Cell>, repo: &str) {
let before = header_two.len();
header_two.push(Cell::new("Last Updated").with_style(Attr::Bold));
header_two.push(Cell::new(... |
use core::ops::DerefMut;
use core::pin::Pin;
use core::task::{Context, Poll};
#[cfg(feature = "alloc")]
use alloc::boxed::Box;
#[cfg(feature = "std")]
use futures::io as std_io;
use super::error::Result;
/// Read bytes asynchronously.
///
/// This trait is analogous to the `std::io::BufRead` trait, but integrates
/... |
use hyper::{body, header, Body, Method, Request, Uri};
use hyper_rustls::HttpsConnector;
const ENDPOINT: &str = "https://getpocket.com/v3";
const REDIRECT_URL: &str = "https://getpocket.com";
pub fn url(method: &str) -> Uri {
let url = format!("{}{}", ENDPOINT, method);
url.parse()
.unwrap_or_else(|_|... |
use iron::prelude::*;
use router::Router;
use urlencoded::UrlEncodedBody;
use urlencoded::UrlEncodedQuery;
// Extracts a string parameter from the path
pub fn extract_param_from_path(req: &Request, parameter: &str) -> String {
req.extensions.get::<Router>().unwrap().find(parameter).unwrap_or("").to_string()
}
pub... |
use std::cmp::Ordering;
use super::{Gui, WidgetNode, text::Text, button::Button};
pub trait GuiValueListener<T> {
fn value_changed(&mut self, gui: &mut Gui, new_value: &T);
}
pub struct GuiValue<T> where T: Clone + PartialEq {
value: Option<T>,
listeners: Vec<Box<dyn GuiValueListener<T>>>,
}
impl<T> GuiV... |
use crate::cli::History;
use crate::data::config;
use crate::data::{Dictionary, Value};
use crate::errors::ShellError;
use crate::prelude::*;
use crate::TaggedDictBuilder;
use crate::commands::WholeStreamCommand;
use crate::parser::registry::Signature;
use indexmap::IndexMap;
pub struct Env;
impl WholeStreamCommand ... |
extern crate libc;
mod magic;
mod admin;
mod tests;
|
#[macro_use]
extern crate rocket;
pub mod apple;
pub mod config;
pub mod microsoft;
pub mod mozilla;
#[launch]
fn rocket() -> _ {
let config = config::MailConfig::read("/etc/automail/config.toml")
.or(config::MailConfig::read("config.toml"))
.expect("error: unable to load the configuration file");... |
extern crate num;
use std::collections::VecDeque;
fn act2_4_1(n: usize, l: usize, p:usize, a: &Vec<usize>, b: &Vec<usize>) -> Option<usize> {
let mut aCp = a.clone();
let mut bCp = b.clone();
aCp.push(l);
aCp.push(0);
let mut n2 = n;
let mut que = VecDeque::new();
let mut ans = 0;
let mut pos = 0;
let mut ta... |
use core::fmt::Debug;
use halo2::arithmetic::FieldExt;
use halo2::pasta::{pallas, vesta};
use std::cell::UnsafeCell;
use std::marker::PhantomData;
use std::mem::transmute;
use std::slice;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::Arc;
pub const TEST_SEED: [u8; 16] = [42; 16];
// Question: Should ... |
// Generated by `scripts/generate.js`
pub type VkQueryPoolCreateInfo = super::super::intel::VkQueryPoolPerformanceQueryCreateInfo;
#[doc(hidden)]
pub type RawVkQueryPoolCreateInfo = super::super::intel::RawVkQueryPoolPerformanceQueryCreateInfo; |
#![allow(non_snake_case)]
use std::error::Error;
use crate::{
math::{FromCSV, Matrix, Vector},
regressor::{
config::Config,
regressor::Regressor,
},
};
pub mod regressor;
pub mod math;
#[cfg(test)]
pub mod test;
fn main() -> Result<(), Box<dyn Error>> {
let X = Matrix::read("./data/... |
use glium::texture::Texture2d;
pub struct Widget_Base {
pub position: (f32, f32),
pub size: (f32, f32),
pub color: (u8, u8, u8),
pub texture: Texture2d
}
pub struct Button{
pub base: Widget_Base,
pub text: String
}
|
//! [RefCell<T>] and the Interior Mutability Pattern, part 2
//!
//! [refcell<t>]: https://doc.rust-lang.org/book/ch15-05-interior-mutability.html
use std::{cell::RefCell, fmt::Debug, rc::Rc};
#[derive(Debug)]
pub enum List<T: Debug> {
Cons(Rc<RefCell<T>>, Rc<List<T>>),
Nil,
}
impl<T: Debug> List<T> {
pub... |
use crate::dirgraphsvg::edges::EdgeType;
use crate::dirgraphsvg::{escape_node_id, escape_text, nodes::Node};
use crate::file_utils::{get_filename, get_relative_path, set_extension, translate_to_output_path};
use crate::gsn::{get_levels, GsnNode, Module};
use anyhow::{Context, Result};
use chrono::Utc;
use clap::ArgMatc... |
//! Contains structures for managing runtime configuration data.
use std::error::Error;
use std::fs::File;
use std::io::Read;
use std::path::Path;
use toml;
use iron::typemap::Key;
/// API key used to programmatically upload files.
#[derive(Deserialize)]
pub struct APIKey {
pub key: String,
pub comment: Opt... |
use structopt::StructOpt;
#[derive(StructOpt)]
pub struct Cli {
#[structopt(short, long)]
pub weight: f32,
#[structopt(short, long)]
pub planet: String,
}
pub fn get_args() -> Cli {
Cli::from_args()
}
|
use crate::entities::{Submit, Testcase};
use crate::{db::DbPool, entities::Problem};
use anyhow::Result;
use async_trait::async_trait;
use chrono::prelude::*;
use sqlx::{MySql, Transaction};
#[async_trait]
pub trait SubmitRepository {
async fn get_submits(&mut self) -> Result<Submit>;
async fn update_status(&m... |
// Copyright 2013 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::borrow::Cow;
use std::cell::RefCell;
use std::path::{Path, PathBuf};
use std::rc::Rc;
use anyhow::Result;
use serde::{Deserialize, Serialize};
use crate::cfg::local::setup_vars::Vars;
use crate::cfg::local::ArrayVars;
use crate::cfg::setup::SetupCfg;
use crate::cfg::CfgError;
pub type SetupName = String;
#... |
use crate::{map::Key, set::iterators::Iter, Segment, SegmentMap, SegmentSet};
impl<T> SegmentSet<T> {
// TODO: into_union_iter
pub fn union_iter<'a>(&'a self, other: &'a Self) -> Union<'a, T> {
Union {
iter_a: self.iter(),
prev_a: None,
iter_b: other.iter(),
... |
pub mod warp;
|
#![feature(io)]
extern crate inkwell;
mod lexer;
mod ast;
mod parser;
use std::io::*;
use lexer::{Token, Lexer};
use parser::{Error, Parser};
fn main() {
// TODO: the closure is bad, but the best solution that came up. consider working more on this
let lexer = Lexer::new(Box::new(|| { stdin().chars() }));
le... |
use common::*;
use ncollide2d::transformation::convex_hull_idx;
// use ncollide2d::query::closest_points_line_line_parameters;
use rand::prelude::*;
use specs::prelude::*;
use specs_derive::Component;
use voronois::destruction;
pub const EPS: f32 = 1E-3;
pub const SHADOW_LENGTH: f32 = 100f32;
pub const DECONSTRUCT_SHA... |
// The prime factors of 13195 are 5, 7, 13 and 29.
//
// What is the largest prime factor of the number 600851475143 ?
fn main() {
let max = 600851475143usize;
let mut curr_max = max;
let mut fact = 0;
let mut i = 2;
while i * i <= curr_max {
if curr_max % i == 0 {
curr_max = c... |
use std::collections::HashMap;
/// A symbol is a reference to an entry in SymbolTable
#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Clone, Copy)]
pub struct Symbol(u32);
impl Symbol {
pub fn new(name: u32) -> Symbol {
Symbol(name)
}
pub fn to_usize(&self) -> usize {
self.0 as usiz... |
extern crate raster;
mod elapsed_metrics;
use elapsed_metrics::ElapsedMetrics;
use raster::{editor, ResizeMode};
use std::env;
use std::error::Error;
fn main() -> Result<(), Box<Error>> {
// Args arrangement
let mut args = env::args().skip(1);
assert_eq!(args.len(), 3, "Arguments must be: file_location w... |
//! Module contains wifi-related structures, enumerations and functions
use crate::{
ffi::*,
error::*,
system_event::*,
network_adapter,
};
pub type wifi_err_reason_t = u32;
pub const wifi_err_reason_t_WIFI_REASON_UNSPECIFIED: wifi_err_reason_t = 1;
pub const wifi_err_reason_t_WIFI_REASON_AUTH_EXPIRE:... |
use crate::config::Config;
use crate::utils;
use std::fs;
use std::path::PathBuf;
pub fn track(path: PathBuf, mut config: Config) -> Result<(), failure::Error> {
let full_path = utils::normalize_path(&std::env::current_dir()?.join(path));
// Test to see if the path is a readable dir
fs::read_dir(&full_pat... |
#[doc = "Register `DTCR` reader"]
pub type R = crate::R<DTCR_SPEC>;
#[doc = "Register `DTCR` writer"]
pub type W = crate::W<DTCR_SPEC>;
#[doc = "Field `DTRx` reader - Deadtime Rising value"]
pub type DTRX_R = crate::FieldReader<u16>;
#[doc = "Field `DTRx` writer - Deadtime Rising value"]
pub type DTRX_W<'a, REG, const ... |
// 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 criterion::{criterion_group, criterion_main, BenchmarkId, Criterion};
use math::{fields::f128::BaseElement, get_power_series, log2, po... |
use std::{io, net::TcpStream, sync::mpsc, thread};
use anyhow::Error;
use io::BufRead;
use nmea::Nmea;
use termion::{event::Key, input::MouseTerminal, raw::IntoRawMode, screen::AlternateScreen};
use tui::{
backend::TermionBackend,
layout::{Constraint, Direction, Layout},
style::{Color, Style},
text::{S... |
use super::base::*;
use super::error::HackError;
use crate::hack_report;
use std::collections::HashMap;
use std::vec::Vec;
/**
* Recursive Descent Parser
*
* COMMAND: ACOMMAND
* | CCOMMAND
* | LCOMMAND
* ACOMAND: AT VALUE
* VALUE: NUMBER | VARIABLE
* CCOMMAND: DEST COMP JUMP
* DEST: EMPTY | REGS
* R... |
use super::MapsetTags;
use rand::seq::SliceRandom;
pub struct Hints {
pub artist_guessed: bool,
hint_level: u8,
title_mask: Vec<bool>,
indices: Vec<usize>,
_tags: MapsetTags,
}
impl Hints {
pub fn new(title: &str, tags: MapsetTags) -> Self {
// Indices of chars that still need to be r... |
use hacspec_hmac::*;
use hacspec_lib::*;
use hacspec_sha256::*;
// HASH_LEN for SHA256
// XXX: HMAC should probably expose this
const HASH_LEN: usize = 256 / 8;
#[derive(Debug)]
pub enum HkdfError {
InvalidOutputLength,
}
pub type HkdfByteSeqResult = Result<ByteSeq, HkdfError>;
/// Extract a pseudo-random key f... |
// Copyright (C) 2020 Stephane Raux. Distributed under the MIT license.
//! Defines a monotonic clock whose values are instances of `Duration`.
//!
//! # Why not `std::time::Instant`?
//!
//! `Instant` is opaque and cannot be serialized.
//!
//! # Example
//!
//! ```rust
//! let mut clock = moniclock::Clock::new();
//... |
pub mod enclave_tls;
mod protocol;
|
use crate::stub_servers::stub_server_tcp::StubServerTcp;
use crate::*;
use futures_intrusive::sync::ManualResetEvent;
use std::error::Error;
use std::sync::Arc;
use tokio::task::JoinHandle;
#[tracing::instrument(name = "Start running stub server", level = "debug", skip(stop_event))]
pub fn run(
config: &RnpStubSer... |
extern crate lazy_static;
extern crate unicode_xid;
extern crate z3;
use std::fs::File;
use std::io::Read;
use std::path::Path;
mod implicit_parse {
#![allow(clippy::all)]
include!(concat!(env!("OUT_DIR"), "/implicit_parse.rs"));
}
#[macro_use]
mod common;
mod env;
mod explicit;
mod hindley_milner;
mod impli... |
use std::collections::HashMap;
use std::ffi::{CString, CStr};
pub struct CStringCache {
cache: HashMap<String, CString>
}
impl CStringCache {
pub fn new() -> CStringCache {
CStringCache {
cache: HashMap::new()
}
}
pub fn intern(&mut self, string: &str) -> &CStr {
s... |
#![allow(dead_code)]
use std::sync::{Arc, Mutex};
use std::{thread, time};
#[derive(Debug)]
pub struct BankAccount {
account_no: String,
money: Arc<Mutex<f64>>
}
impl BankAccount {
pub fn withdrawl(&mut self, amount: f64) -> f64 {
let mut balance = self.money.lock().unwrap();
*balance -= ... |
use rusoto_core::{RusotoError, RusotoFuture};
use rusoto_s3::CreateBucketError::{BucketAlreadyExists, BucketAlreadyOwnedByYou};
use rusoto_s3::*;
use std::cell::RefCell;
use std::io::Read;
use std::rc::Rc;
#[derive(Debug)]
pub struct PutObjectData {
pub bucket: String,
pub key: String,
pub body: Vec<u8>,
... |
// Day 3 2019
use std::cmp::Ordering;
use std::collections::BTreeSet;
#[cfg(test)]
mod tests {
use crate::day3::*;
#[test]
fn test_string_to_path() {
let path = vec![
Pathlet::Right(8),
Pathlet::Up(5),
Pathlet::Left(5),
Pathlet::Down(3),
];
... |
pub mod opcode;
pub mod instruction;
|
use core::ops::Drop;
use core::sync::atomic;
extern "C" {
static mut idt_entry: [IdtEntry; 256];
static mut idt_handlers: [u64; 256];
static mut idt_descriptor: IdtDescriptor;
fn idt_init();
}
pub const IDT_INTERRUPT_16: u8 = 0x6;
pub const IDT_TRAP_16: u8 = 0x7;
pub const IDT_INTERRUPT_64: u8 = 0xE;... |
struct Foo;
trait Bar {
fn bar();
}
impl Bar for Foo {
fn bar() {
}
}
|
use bb3::custom_ser::to_resp;
use bb3::RedisType;
use building_block_03 as bb3;
use std::io::prelude::*;
use std::io::BufReader;
use std::net::TcpListener;
use std::net::TcpStream;
fn main() {
let addr = "127.0.0.1:6379";
println!("Listening {}", addr);
println!("Please use redis-cli to have a try");
l... |
pub mod auth_token;
|
use std::collections::HashSet;
use proconio::input;
fn main() {
input! {
n: i64
}
println!("{}", f(n));
}
fn f(n: i64) -> i64 {
let mut values : HashSet<i64> = HashSet::new();
let mut a = 2;
while a * a <= n {
let mut v = a * a;
while v <= n {
values.insert(... |
mod internals;
use crate::parking_lot::internals::{MyResult, ParkLotIntern, Slot};
use failure::{bail, Error};
use std::string::ToString;
#[derive(Copy, Clone, Debug)]
enum Action<'a> {
Create(usize),
Park(&'a str, &'a str),
Leave(usize),
Status,
SlotNumbersForColor(&'a str),
SlotNumbersForReg... |
use std::convert::TryFrom;
use std::{fs::File, path::Path, os::unix::io::AsRawFd};
use std::io::BufReader;
use tokio::prelude::*;
use tokio::reactor::PollEvented2;
use nix::{ioctl_none, ioctl_read};
use crate::error::{Result, ResultExt, Error, ErrorKind};
const DEFAULT_EVENT_FILE_PATH: &str = "/dev/surface_dtx";
... |
use std::io;
use std::io::Read;
use std::fs::File;
use std::collections::HashMap;
// The quick ntpem fox jumped over rgw lazy dog.
fn thinger(ref row: &Vec<char>, char: char, i: isize, ref mut new_word: &mut String) {
match row.iter().position(|&x| x === char) {
Some(idxa) => {
if idx as isize + i < 0 {
... |
// ===============================================================================================
// Imports
// ===============================================================================================
use spin::RwLock;
// ========================================================================================... |
use rand::Rng;
use rodio;
use rodio::Device;
use rodio::Source;
use std::collections::HashMap;
use std::fs::File;
use std::convert::AsRef;
use std::io;
use std::io::prelude::*;
use std::sync::Arc;
type Sounds = Vec<Sound>;
type SoundsMap = HashMap<SoundType, Sounds>;
#[derive(Eq, PartialEq, std::hash::Hash, Clone, C... |
pub mod outer {
pub fn a() {
println!("function a");
}
pub fn b() {
println!("function b");
}
pub mod inner {
pub fn c() {
println!("function c");
}
pub fn d() {
println!("function d");
}
}
}
|
//! The functions in this module are expected to work. They have been tested by hand, but currently can't be tested programmatically because console doesn't have a testing functionality.
use crate::{settings::Settings, vpn::util::UserConfig};
use anyhow::{Context, Result};
use console::Term;
use directories::ProjectDi... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.