text stringlengths 8 4.13M |
|---|
// Puzzle 1 (p.31 of the book)
const TOP_EDGE: u32 = 10000;
use arsak_zhak_programmirovanie_igr_i_golovolomok::*;
use std::env;
use std::str::FromStr;
// Run as puz1 [initial_value]
fn main() {
let args: Vec<String> = env::args().collect();
let mut p = if args.len() == 1 {
0
} else {
matc... |
///! SpinLock implemented using AtomicBool
///! Just like Mutex except:
///!
///! 1. It uses CAS for locking, more efficient in low contention
///! 2. Use `.lock()` instead of `.lock().unwrap()` to retrieve the guard.
///! 3. It doesn't handle poison so data is still available on thread panic.
use std::cell::UnsafeCell... |
fn main() {
let a = [0];
let i = 0;
println!("{}", a[i]);
}
|
extern crate wasm_bindgen;
use myna::crypto::*;
use wasm_bindgen::prelude::*;
#[wasm_bindgen]
pub fn verify(cert: Box<[u8]>, sig: Box<[u8]>, hash: Box<[u8]>) -> Result<bool, JsValue> {
let pubkey = extract_pubkey(&cert).map_err(|_| "Certificate is not DER format")?;
myna::crypto::verify(pubkey, &hash, &sig).ma... |
// Determine the depth of each board by retrospective analysis.
//
// Input: 1-enum's output
//
// Output:
// board depth
// ...
//
// board: hex representation of bit-board
// depth: the depth of the board
// odd: black will win
// even: white will win
// -1: draw
#[macro_use]
extern crate precomp... |
use std::collections::HashSet;
#[aoc_generator(day1)]
pub fn input_generator(input: &str) -> Vec<i32> {
input.lines().map(|l| l.parse().unwrap()).collect()
}
#[aoc(day1, part1)]
pub fn solve_part1(input: &[i32]) -> i32 {
input.iter().sum()
}
#[aoc(day1, part2)]
pub fn solve_part2(input: &[i32]) -> i32 {
... |
use std::time;
use crate::{client::Endpoint, core::MAX_CONNS, http::Http, Config, Error, Info, Random, Result};
// State of each endpoint. An endpoint is booted and subsequently
// used to watch/get future rounds of random-ness.
#[derive(Clone)]
pub(crate) struct State {
pub(crate) info: Info,
pub(crate) chec... |
#[macro_use(mem_info)]
extern crate arrayfire as af;
extern crate time;
use time::PreciseTime;
use af::*;
#[allow(unused_must_use)]
#[allow(unused_variables)]
fn main() {
set_device(0);
info();
let samples = 20_000_000;
let dims = Dim4::new(&[samples, 1, 1, 1]);
let x = &randu::<f32>(dims).unwrap... |
use itertools::Itertools;
use lazy_static::lazy_static;
use std::collections::HashMap;
struct Step {
name: &'static str,
prereqs: String,
}
impl Step {
fn new(name: &'static str) -> Self {
Step {
name,
prereqs: String::new(),
}
}
fn is_ready(&self, started:... |
use crate::proxy::{Router, RouterTrait};
use hyper::service::Service;
use hyper::{Body, Request, Response};
use std::future::Future;
use std::pin::Pin;
use std::task::{Context, Poll};
pub struct Svc {
router: Router,
}
impl Service<Request<Body>> for Svc {
type Response = Response<Body>;
type Error = hype... |
/// Trait describing frame rates.
pub trait FrameRate {
const FPS: u32;
const DROP_FRAME: bool;
#[doc(hidden)]
const MAX_FRAMES: u32;
#[doc(hidden)]
const FRAMES_PER_MINUTE: u32 = Self::FPS * 60;
#[doc(hidden)]
const FRAMES_PER_HOUR: u32 = Self::FRAMES_PER_MINUTE * 60;
#[doc(hid... |
use perseus::{ErrorPages, GenericNode};
use std::rc::Rc;
use sycamore::template;
// This site will be exported statically, so we only have control over 404 pages for broken links in the site itself
pub fn get_error_pages<G: GenericNode>() -> ErrorPages<G> {
let mut error_pages = ErrorPages::new(Rc::new(|url, statu... |
fn ground_lifetime<'a>(x: &'a u64) -> &'a u64
{
x
}
struct Ref<'a, T: 'a>(&'a T);
trait Red { }
struct Ball<'a> {
diameter: &'a i32,
}
impl<'a> Red for Ball<'a> { }
static num: i32 = 5;
struct Context<'s>(&'s mut String);
impl<'s> Context<'s>
{
fn mutate<'c>(&mut self, cs: &'c mut String) -> &'c mut Str... |
#[doc = "Register `DDRCTRL_ADDRMAP1` reader"]
pub type R = crate::R<DDRCTRL_ADDRMAP1_SPEC>;
#[doc = "Register `DDRCTRL_ADDRMAP1` writer"]
pub type W = crate::W<DDRCTRL_ADDRMAP1_SPEC>;
#[doc = "Field `ADDRMAP_BANK_B0` reader - ADDRMAP_BANK_B0"]
pub type ADDRMAP_BANK_B0_R = crate::FieldReader;
#[doc = "Field `ADDRMAP_BAN... |
extern crate cc;
use std::env;
static ARCH_FLAGS: &[&str] = &["-mthumb-interwork", "-mcpu=arm946e-s", "-msoft-float"];
fn gcc_config() -> cc::Build {
let mut config = cc::Build::new();
for flag in ARCH_FLAGS {
config.flag(flag);
}
config
.flag("-fno-strict-aliasing")
.flag("-s... |
fn main() {
let r1 = Rect {
width: 12,
height: 12,
};
println!("area is: {}", r1.area());
}
struct Rect {
width: u32,
height: u32,
}
// 这里实现方法
impl Rect {
// 实现 area 方法
// &self 来替代 rect: &Rect
// 这里是借用 &self
// 也可以是可变的借用 &mut self
// 也可以获取所有权 self, 这种非常少, 这种技术通... |
extern crate clap;
mod index;
mod info;
mod stat;
mod util;
use clap::{App, Arg, SubCommand};
use info::Info;
use stat::Stat;
fn main() {
let matches = App::new("Tutor")
.version("0.1")
.about("Command line tutorials")
.author("Abdun Nihaal")
.subcommand(
SubCommand::w... |
#![macro_use]
use core::cell::UnsafeCell;
use core::marker::PhantomData;
use core::sync::atomic::{compiler_fence, Ordering};
use embassy::util::Unborrow;
use embassy_extras::unborrow;
use crate::gpio::sealed::Pin as _;
use crate::gpio::OptionalPin as GpioOptionalPin;
use crate::interrupt::Interrupt;
use crate::pac;
... |
pub use self::pattern::Pattern;
pub use self::track::Track;
mod track;
mod pattern; |
use crate::config::cache::Cache;
use crate::lib::error::{BuildError, DfxError, DfxResult};
use anyhow::{anyhow, bail};
use std::process::Command;
/// Package arguments for moc or mo-ide as returned by
/// a package tool like https://github.com/kritzcreek/vessel
/// or, if there is no package tool, the base library.
p... |
use std::panic;
use rocket::{self, http::{ContentType, Header, Status}, local::Client};
use diesel::connection::SimpleConnection;
use horus_server::{self, routes::manage::*};
use test::{run_test, sql::*};
#[test]
fn my_pastes()
{
run(|| {
let client = get_client();
let req = client.get("/manage/p... |
mod bounds;
pub use self::bounds::*;
mod morton_index;
pub use self::morton_index::*;
mod bitmanip;
pub use self::bitmanip::*;
mod arithmetic;
pub use self::arithmetic::*;
mod minmax;
pub use self::minmax::*;
|
// Copyright (c) The Starcoin Core Contributors
// SPDX-License-Identifier: Apache-2.0
use libra_crypto::HashValue;
#[derive(Clone, Copy, Eq, Hash, PartialEq, PartialOrd, Ord)]
pub struct HtlcPayment {
hash_lock: HashValue,
amount: u64,
timeout: u64,
}
impl HtlcPayment {
pub fn new(hash_lock: HashVal... |
use std::boxed::Box;
use std::cmp::{max, min};
use std::convert::TryInto;
use std::fmt;
use std::iter::{empty, Peekable};
use std::ops::Range;
use chrono::{Duration, NaiveDate, NaiveDateTime, NaiveTime};
use once_cell::sync::Lazy;
use crate::day_selector::{DateFilter, DaySelector};
use crate::extended_time::ExtendedT... |
use pgx::{FromRow, queryx};
use super::super::types::{Field, Type, Status};
use postgres::rows::Row;
use postgres::Connection;
use postgres::error::Error;
use postgres_array::Array;
use std::str::FromStr;
use user::UserInfo;
use pgtypes::requirements::{FieldType, RequirementType};
#[derive(Debug)]
pub struct Requireme... |
#![allow(dead_code)]
use glium::{
glutin::{event, event_loop},
Display,
};
use conrod_winit;
pub enum Request<'a, 'b: 'a> {
Event {
event: &'a event::Event<'b, ()>,
should_update_ui: &'a mut bool,
should_exit: &'a mut bool,
},
SetUi {
needs_redraw: &'a mut bool,
... |
use itertools::Itertools;
pub fn part1(input: &str) -> Result<usize, String> {
Ok(input
.split("\n\n")
.map(|x| x.replace("\n", "").chars().unique().count())
.sum())
}
pub fn part2(input: &str) -> Result<usize, String> {
Ok(input.split("\n\n").fold(0, |acc, x| {
let answers = x... |
use log::{info, warn};
use num_bigint_dig::*;
use rsa::{hash, PaddingScheme, PublicKey, RSAPublicKey};
use sha2::*;
pub fn verify_signature(data: &[u8], signature: &[u8], public_key: &[u8]) -> bool {
let mut hasher = Sha256::new();
hasher.input(&data);
let hash = hasher.result();
let public_key = match... |
use std::thread;
use std::sync::{Arc, Mutex};
use std::time::Duration;
use std::old_io::timer;
fn main() {
let buf = Arc::new(Mutex::new(Vec::<String>::new()));
let res = test(buf);
println!("{:?}", *res.lock().unwrap());
}
fn test(buf: Arc<Mutex<Vec<String>>>) -> Arc<Mutex<Vec<String>>> {
let guards:... |
use serenity::{
framework::standard::{macros::command, CommandResult},
model::channel::Message,
prelude::*,
};
#[command]
#[description = "Bot willk reply with pretty embed containing links to other projects by the author."]
fn projects(ctx: &mut Context, msg: &Message) -> CommandResult {
let msg = msg... |
pub mod modules {
//MODULE_JSON
pub const UNITY_2022_1_0_A_13:&str = include_str!("2022.1.0a13_modules.json");
pub const UNITY_2022_2_6_F_1:&str = include_str!("2022.2.6f1_modules.json");
}
pub mod manifests {
//MANIFEST_INI
pub const UNITY_2022_1_0_A_13:&str = include_str!("2022.1.0a13_manifest.i... |
//! Utilities for working on GHC's prof JSON dumps (`+RTS -pj`)
//!
//! For now just compares allocations.
use serde::Deserialize;
use std::collections::HashMap;
#[derive(Debug, Deserialize)]
struct ProfFile {
program: String,
arguments: Vec<String>,
rts_arguments: Vec<String>,
end_time: String,
i... |
// cargo test -- --nocapture
#[test]
fn test() {
println!("test...あああああああああああああ");
let list = vec!["あ", "い", "う", "え", "お"];
// 長さはないんね...
for v in list {
println!("v:{}", v);
}
}
|
/// An enum to represent all characters in the Hiragana block.
#[derive(Debug, Clone, Copy, Hash, PartialEq, Eq)]
pub enum Hiragana {
/// \u{3041}: 'ぁ'
LetterSmallA,
/// \u{3042}: 'あ'
LetterA,
/// \u{3043}: 'ぃ'
LetterSmallI,
/// \u{3044}: 'い'
LetterI,
/// \u{3045}: 'ぅ'
LetterSma... |
use crate::z3::ast;
use ast::Ast;
use std::convert::TryInto;
use std::ffi::CStr;
use std::fmt;
use z3_sys::*;
use crate::z3::{Context, FuncDecl, Sort, Symbol, Z3_MUTEX};
impl<'ctx> FuncDecl<'ctx> {
pub fn new<S: Into<Symbol>>(
ctx: &'ctx Context,
name: S,
domain: &[&Sort<'ctx>],
ran... |
use serde::{Deserialize, Serialize};
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct UiLayout {
pub name: String,
pub flex_childs: Vec<FlexChild>
}
impl Default for UiLayout {
fn default() -> Self {
UiLayout {
name: "".to_string(),
flex_childs: vec![]
}
... |
use error_chain::error_chain;
error_chain! {
foreign_links {
Fmt(::std::fmt::Error);
Io(::std::io::Error);
NetworkError(::reqwest::Error);
ZipError(::zip::result::ZipError);
VersionError(::uvm_core::unity::VersionError);
}
errors {
ChecksumVerificationFailed... |
fn main() {
vectors();
strings();
hash_maps();
}
#[derive(Debug)]
enum SpreadsheetCell {
Int(i32),
Float(f64),
Text(String),
}
fn vectors() {
let v: Vec<i32> = Vec::new(); // empty vector
println!("v: {:?}", v);
let v = vec![1, 2, 3]; // using the macro
println!("v: {:?}", v);... |
use std::sync::mpsc;
use std::collections::BinaryHeap;
const N_SHARDS: usize = 4;
pub struct Transaction;
impl Transaction {
fn get_shard(&self) -> usize {
3
}
}
#[derive(PartialEq)]
pub struct MempoolItem {
id: [u8; 32],
tx: Transaction,
package_fee: u32
};
impl From<Transaction> for M... |
use std::os::raw::{c_char, c_int, c_long, c_void};
extern "C" {
pub fn luaL_newstate() -> *mut c_void;
pub fn luaL_openlibs(state: *mut c_void);
pub fn lua_getfield(state: *mut c_void, index: c_int, k: *const c_char);
pub fn lua_tolstring(state: *mut c_void, index: c_int, len: *mut c_long) -> *const c_... |
use std::collections::HashMap;
use itertools::Itertools;
type RxnMap = HashMap<String, (SIZE, Vec<(String, SIZE)>)>;
type SIZE = u128;
#[aoc_generator(day14)]
fn gen(input: &str) -> RxnMap {
input.lines()
.map(|line| {
let mut iter = line.split("=>");
let ingreds = iter.next().unwr... |
use crate::q2b::grid::Grid;
use crate::q2b::cluster_finder::ClusterFinder;
mod grid;
mod cluster_finder;
pub fn main() {
let lx = 6;
let ly = 4;
let n = 10;
let p_super = 0.1;
let mut r: Vec<bool> = Vec::with_capacity(100);
for _ in 0..100 {
let g1 = Grid::new(lx, ly, n, p_super);
... |
use crate::println;
use core::panic::PanicInfo;
#[panic_handler]
fn panic(info: &PanicInfo) -> ! {
println!("{}", info);
loop {}
}
|
use criterion::*;
#[path = "../src/mining.rs"]
mod mining;
pub fn criterion_benchmark(c: &mut Criterion) {
c.bench_function("onetime_rank", |b| {
b.iter(|| {
mining::ontime_rank(
// "/Desktop/Functional and Parallel Programing/mining",
"C:/Users/Admin/Desktop/min... |
use simplelog::Level::Info;
use std::thread;
use errors::*;
use format::*;
use ndarray::Axis;
use profile::ProfileData;
use rusage::{Duration, Instant};
use tfdeploy::streaming::*;
use tfdeploy::Tensor;
use utils::random_tensor;
use {OutputParameters, Parameters, ProfilingMode};
fn build_streaming_model(params: &Par... |
//! Everting needed to track a position in a [source](`super::source::Source`)
//! file.
use std::fmt;
use std::ops::{Deref, Index};
// COPYRIGHT by Rust project contributors
// <https://github.com/rust-lang/rust/graphs/contributors>
//
// Copied from <https://github.com/rust-lang/rust/blob/362e0f55eb1f36d279e5c4a58f... |
// 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 super::{FieldElement, StarkField};
use core::{
convert::TryFrom,
fmt::{Debug, Display, Formatter},
ops::{Add, AddAssign, D... |
use crate::neuron::{get_quality, Neuron, NeuronicInput, NeuronicSensor, Neuronic, ChargeCycle};
use std::rc::Rc;
/// Utility method that compares f32 to
/// three decimal places
fn cmp_f32(f1: f32, f2: f32) {
assert_eq!(
(f1 * 1000.).floor(),
(f2 * 1000.).floor(),
"{} does not equal {}",
... |
use crate::data::component::components::*;
use crate::{map, set};
use super::*;
use crate::data::component::statefuls::{SRFlipFlop, Constant};
use std::cell::Cell;
macro_rules! edge {
($subnet:expr, $component:expr, $port:expr, 0) => {
Edge {
subnet: $subnet,
compone... |
fn main() {
println!("cargo:rerun-if-changed=src/callback.c");
cc::Build::new()
.opt_level(0)
.debug(false)
.flag("-g1")
.file("src/callback.c")
.compile("libcallback.a");
}
|
mod rbf;
mod utils;
use std::slice::{from_raw_parts};
use std::os::raw::c_char;
use std::ffi::CString;
use rand::Rng;
use nalgebra::*;
use crate::rbf::RBF;
//////////////////////////////////////////////////LINEAR MODEL///////////////////////////////////////////////////////////
#[no_mangle]
pub extern fn create_li... |
use ring::digest::{digest, SHA256};
pub fn hash(input: &[u8]) -> Vec<u8> {
digest(&SHA256, input).as_ref().to_vec()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_hashing() {
let input = b"lorem ipsum";
let output = hash(input.as_ref());
let output_bytes = output.as_... |
use serde::Deserialize;
use std::cell::RefCell;
use std::collections::HashMap;
use std::error::Error;
use std::fs::read_dir;
use std::path::Path;
use std::rc::Rc;
use crate::json;
#[derive(Clone, Debug, Deserialize)]
pub enum NodeType {
CollectionType,
DocumentType,
}
#[derive(Clone, Debug, Deserialize)]
#[s... |
use std::fs;
use std::path::Path;
use toml;
use std::io::{Read, Write};
use errors::*;
// Serialization made with serde
#[derive(Serialize, Deserialize, Debug, Default, Clone)]
pub struct Config {
#[serde(skip_serializing_if="Option::is_none")]
pub http: Option<HttpConfig>,
pub locations: Vec<LocationCon... |
#![no_std]
#![feature(asm)]
#![feature(global_asm)]
#[macro_use]
mod io; // IO库; 宏`println`和`print`
mod context; // 上下文; 中断帧
mod init; // 系统初始化; 系统入口
mod interrupt; // 中断库; 中断初始化程序, 中断处理程序
mod lang_items; // RUST所需的语义项
mod sbi; // 封装SBI
mod timer; // 时钟中断
|
use std::env;
use std::fs;
use std::path::Path;
use std::collections::HashMap;
fn read_instructions(filename:&str) -> String{
let fpath = Path::new(filename);
let abspath = env::current_dir()
.unwrap()
.into_boxed_path()
.join(fpath);
let replaced = fs::read_to_string(abspath)
... |
use serde::{Deserialize, Serialize};
/// Message from the server to the client.
#[derive(Serialize, Deserialize)]
pub struct ServerMessage {
pub id: usize,
pub text: String,
}
/// Message from the client to the server.
#[derive(Serialize, Deserialize)]
pub struct ClientMessage {
pub text: String,
}
/// M... |
use openssl::rsa::{Rsa};
use openssl::pkey::PKey;
use openssl::sign::{Signer};
use openssl::hash::MessageDigest;
use std::fs;
use crate::data;
pub fn generate_keys(){
let rsa = Rsa::generate(1024).unwrap();
let private_key: Vec<u8> = rsa.private_key_to_pem().unwrap();
let public_key: Vec<u8> = r... |
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT license.
*/
use half::{bf16, f16};
use std::env;
use std::fs::{File, OpenOptions};
use std::io::{self, Read, Write, BufReader, BufWriter};
enum F16OrBF16 {
F16(f16),
BF16(bf16),
}
fn main() -> io::Result<()> {
// Re... |
mod handlers;
use stremio_addon_sdk::server::ServerOptions;
use stremio_addon_sdk::server::serve_serverless;
use stremio_addon_sdk::export::serverless::now::*;
use handlers::build;
mod manifest;
use manifest::get_manifest;
fn handler(req: Request) -> Result<impl IntoResponse, NowError> {
let manifest = get_manifest()... |
// src/environment.rs
use super::object::*;
use std::cell::*;
use std::collections::*;
use std::rc::*;
pub fn new_enclosed_environment(outer: Option<Rc<RefCell<Environment>>>) -> Environment {
let mut env = new_environment();
env.outer = outer;
env
}
pub fn new_environment() -> Environment {
Environm... |
use std::hash::{Hash, Hasher};
macro_rules! finite {
(@op => $opname:ty, $opnamety:ty, $func:tt, $name:tt, $ty:ty) => {
impl $opname for $name {
type Output = Option<$ty>;
fn $func(self, other: Self) -> Option<$ty> {
let result = (self.0).$func(other.0);
... |
extern crate inputparser;
use crate::inputparser::{input,ErHandle::*};
fn reciprocal_char(c: char) -> char {
match c {
'a'..='z' => (25 - (c as u8 - 'a' as u8) + 'a' as u8) as char,
'A'..='Z' => (25 - (c as u8 - 'A' as u8) + 'A' as u8) as char,
'0'..='9' => (9 - (c as u8 - '0' as u8) + '0'... |
pub mod shader;
pub mod vao;
pub mod framebuffer;
pub mod texture;
|
//! Tokio global executor runtime.
use crate::core::Runtime;
use std::future::Future;
/// Spawns tasks on global tokio executor.
#[derive(Debug, Clone, Copy)]
pub struct TokioGlobal;
impl Runtime for TokioGlobal {
fn spawn<F>(&self, future: F)
where
F: Future<Output = ()> + Send + 'static,
{
... |
use std::fmt;
use std::time::{Duration, Instant};
use futures::{Async, Future, Stream};
use tokio_core::reactor::Handle;
use tower_h2::{HttpService, BoxBody};
use tower_grpc as grpc;
use conduit_proxy_controller_grpc::telemetry::{ReportRequest, ReportResponse};
use conduit_proxy_controller_grpc::telemetry::client::Te... |
use std::io;
//if the number is power of 2, then it will halt, otherwise never.
fn main(){
//println!("{}",std::u64::MIN);
let mut num_str : String = String::new();
io::stdin().read_line(&mut num_str).unwrap();
//let mut num : u64
let mut num : u64 = num_str.trim().parse().unwrap();
if(num < 2){... |
// Copyright (c) 2018, ilammy
//
// Licensed under the Apache License, Version 2.0 (see LICENSE in the
// root directory). This file may be copied, distributed, and modified
// only in accordance with the terms specified by the license.
use exonum::storage::{Fork, MapIndex, Snapshot};
use service::SERVICE_ID;
/// Nu... |
pub mod funcs;
pub mod wallpaper;
pub mod image_generator;
use std::error::Error;
pub type Result<T> = std::result::Result<T, Box<dyn Error>>; |
#[path="../support/mod.rs"]
mod support;
use citrus_ecs::{element::*, entity::*, scene_editor::*, scene_serde::*};
use serde::*;
use imgui_glium_renderer::imgui as imgui;
#[derive(Clone, Serialize, Deserialize)]
struct A {
val: i32
}
impl Element for A {
fn update(&mut self, _man: &mut Manager, _owner: EntAd... |
use super::BaseHandler;
use pyo3::prelude::*;
use std::sync::{Arc, Mutex};
use streamson_lib::handler;
#[pyclass(extends=BaseHandler)]
#[derive(Clone)]
pub struct BufferHandler {
pub buffer_inner: Arc<Mutex<handler::Buffer>>,
}
#[pymethods]
impl BufferHandler {
/// Create instance of Buffer handler
#[new]... |
use bevy::prelude::*;
use bevy_rapier2d::physics::{ColliderHandleComponent, RigidBodyHandleComponent};
use bevy_rapier2d::rapier::dynamics::RigidBodySet;
use bevy_rapier2d::rapier::geometry::ColliderSet;
use bevy_rapier2d::rapier::math::Isometry;
use crate::physics::*;
use crate::*;
/// stores units that are within... |
use std::hash::Hash;
use std::fmt::Debug;
use crate::machine::*;
#[derive(Debug)]
pub struct HistoryMachine<A, S, C> {
pub machine: Machine<A, S, C>,
pub past: Vec<(S, C)>,
pub future: Vec<(S, C)>,
}
impl<A: Copy, S: Eq + Hash + Copy, C: Debug + Copy> HistoryMachine<A, S, C> {
/// Create a new state ... |
// Super Palindromes
// https://leetcode.com/explore/challenge/card/may-leetcoding-challenge-2021/599/week-2-may-8th-may-14th/3736/
//
impl Solution {
fn is_palindrome(number: i64) -> bool {
let radix: i64 = 10;
let mut rev: i64 = 0;
let mut n: i64 = number.abs();
let mut pop: i64 =... |
use std::collections::HashMap;
use std::fs::File;
use std::io::Read;
// Used in tests
#[allow(dead_code)]
static TEST_CASE: &str = "eedadn\n\
drvtee\n\
eandsr\n\
raavrd\n\
atevrs\n\
tsrnev\n\
sdttsa\n\
rasrtv\n\
nssdts\n\
ntnada\n\
svetve\n\
tesnvt\n\
vntsnd\n\
vrdear\n\
dvrsen\n\
enarar";
fn most_frequent_letter(cou... |
use std::sync::mpsc::{channel, Sender, Receiver};
use clock;
use interface;
#[derive(Clone, Copy, Debug)]
pub enum Message {
Time(clock::Time),
Signature(clock::Signature),
Tempo(clock::Tempo),
Reset,
NudgeTempo(clock::NudgeTempo),
Tap,
/*
Stop,
NudgeClock,
Configure
*/
}
... |
use regex::Regex;
fn main() {
/*let a = [1, 2, 3];
println!("{:?}", a);
let doubled:Vec<i32> = a.iter().map(|&x| x * 2).collect();
println!("{:?}", doubled);*/
let re_test = Regex::new("^[a-zA-Z]+$").unwrap();
let test_pass1 = "aVEASCasd";
let test_fail1 = "aVEASCas3d";
println!("Passe... |
use super::super::common::{screen};
pub fn start_server() {
// TODO
} |
#[doc = "Register `MISR` reader"]
pub type R = crate::R<MISR_SPEC>;
#[doc = "Field `TAMP1MF` reader - TAMP1MF:"]
pub type TAMP1MF_R = crate::BitReader<TAMP1MF_A>;
#[doc = "TAMP1MF:\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum TAMP1MF_A {
#[doc = "0: No tamper detected - Masked"]
... |
#![allow(dead_code, unused_variables, unused_imports, unused_must_use,)]
#[macro_use]
extern crate clap;
extern crate time;
extern crate serde;
extern crate serde_json;
extern crate schedule_recv;
extern crate crossroad_server; // Local crate
use serde::ser;
use schedule_recv as sched;
use time::*;
use std::net::{Tc... |
#![allow(unused_variables)]
#![allow(dead_code)]
// to get **argv (in c++)
use std::env;
use std::fs;
fn main() {
let args: Vec<String> = env::args().collect();
let config = Config::new(&args).expect("Some error ocurred");
// If not found a CASE_INSENSITIVE in env, will put 0
let case_sensitive = env... |
mod helpers;
use helpers as h;
use helpers::{Playground, Stub::*};
use std::path::PathBuf;
#[test]
fn has_default_configuration_file() {
let expected = "config.toml";
Playground::setup("config_test_1", |dirs, _| {
nu!(cwd: dirs.root(), "config");
assert_eq!(
dirs.config_path().j... |
use crate::cell::{ Merge };
impl Merge for usize {
fn is_valid(&self, value: &Self) -> bool {
self == value
}
fn merge(&self, other: &Self) -> Self {
other.clone()
}
}
//impl Bool for usize {
//fn to_bool(self) -> bool {
//self != 0
//}
//}
|
#[doc = "Reader of register TX_WATCHDOG"]
pub type R = crate::R<u32, super::TX_WATCHDOG>;
#[doc = "Writer for register TX_WATCHDOG"]
pub type W = crate::W<u32, super::TX_WATCHDOG>;
#[doc = "Register TX_WATCHDOG `reset()`'s with value 0"]
impl crate::ResetValue for super::TX_WATCHDOG {
type Type = u32;
#[inline(... |
//! # The Chain Library
//!
//! This Library contains the `Chain Service` implement:
//!
//! - [Chain](chain::chain::Chain) represent a struct which
mod cell;
pub mod chain;
pub mod switch;
#[cfg(test)]
mod tests;
|
use std::thread;
use rocket::Rocket;
use crate::benchmarking::ControllerBench;
use crate::framework::{Runnable, CompositeRunnable};
use crate::mechatronics::controller::RobotController;
use crate::builder::robot::Robot;
pub struct RobotLauncher {
controller: RobotController,
bfr: Rocket,
bench: Option<Co... |
#![feature(test)]
extern crate test;
use test::Bencher;
#[bench]
fn generate_lorem_ipsum_100(b: &mut Bencher) {
b.iter(|| lipsum::lipsum(100))
}
#[bench]
fn generate_lorem_ipsum_200(b: &mut Bencher) {
b.iter(|| lipsum::lipsum(200))
}
|
println!("{}", "this" "is not allowed");
|
use crate::flamegraph::filter_to_useful_callstacks;
use crate::flamegraph::CallstackCleaner;
use crate::flamegraph::FlamegraphCallstacks;
use crate::linecache::LineCacher;
use crate::python::get_runpy_path;
use super::rangemap::RangeMap;
use super::util::new_hashmap;
use ahash::RandomState as ARandomState;
use im::Vec... |
use super::gc_work::*;
use super::GenCopy;
use crate::plan::barriers::*;
use crate::plan::mutator_context::Mutator;
use crate::plan::mutator_context::MutatorConfig;
use crate::plan::AllocationSemantics as AllocationType;
use crate::util::alloc::allocators::{AllocatorSelector, Allocators};
use crate::util::alloc::BumpAl... |
//! Module containing the [`SetUnion`] lattice and aliases for different datastructures.
use std::cmp::Ordering::{self, *};
use std::collections::{BTreeSet, HashSet};
use crate::cc_traits::{Iter, Len, Set};
use crate::collections::{ArraySet, OptionSet, SingletonSet};
use crate::{Atomize, IsBot, IsTop, LatticeFrom, La... |
// Copyright 2021 lowRISC contributors.
//
// 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
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or ag... |
use std::collections::HashMap;
use std::path::PathBuf;
use indicatif::ProgressBar;
use rand::Rng;
use crate::color::RGB;
use crate::kd_tree::{KDTree, PerformanceStats, Point};
use crate::point_tracker::PointTracker;
use crate::topology::{PixelLoc, Topology};
impl Point for RGB {
type Dtype = u8;
const NUM_DI... |
#[doc = "Register `X1BUFCFG` reader"]
pub type R = crate::R<X1BUFCFG_SPEC>;
#[doc = "Register `X1BUFCFG` writer"]
pub type W = crate::W<X1BUFCFG_SPEC>;
#[doc = "Field `X1_BASE` reader - X1_BASE"]
pub type X1_BASE_R = crate::FieldReader;
#[doc = "Field `X1_BASE` writer - X1_BASE"]
pub type X1_BASE_W<'a, REG, const O: u8... |
use crate::resources::{Cost, Resource};
use strum_macros::EnumIter;
#[derive(Debug, EnumIter, Copy, Clone, Eq, PartialEq)]
#[allow(dead_code)]
pub enum WonderType {
ColossusOfRhodes,
LighthouseOfAlexandria,
TempleOfArtemis,
HangingGardensOfBabylon,
StatueOfZeus,
MausoleumOfHalicarnassus,
Py... |
use super::{
Register,
Disp,
Scale,
RegSize,
Fault,
parse_reg,
parse_512bit_reg,
parse_256bit_reg,
parse_128bit_reg,
parse_64bit_reg,
parse_32bit_reg,
parse_16bit_reg,
parse_8bit_reg,
parse_mmx_reg,
parse_x87_reg,
parse_vec_reg,
parse_long_ptr_reg,
parse_scale,
parse_const
};
//... |
#[doc = "Register `GICD_ISENABLER7` reader"]
pub type R = crate::R<GICD_ISENABLER7_SPEC>;
#[doc = "Register `GICD_ISENABLER7` writer"]
pub type W = crate::W<GICD_ISENABLER7_SPEC>;
#[doc = "Field `ISENABLER7` reader - ISENABLER7"]
pub type ISENABLER7_R = crate::FieldReader<u32>;
#[doc = "Field `ISENABLER7` writer - ISEN... |
#[cfg(feature = "option")]
use crate::complexop::*;
#[cfg(feature = "option")]
use crate::enumtypes::*;
#[cfg(feature = "option")]
use std::collections::HashMap;
#[cfg(feature = "option")]
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Entity(#[serde(skip_serializing_if = "Option::is_none")] Opt... |
use azure_core::AppendToUrlQuery;
// This type could also be a DateTime
// but the docs clearly states to treat is
// as opaque so we do not convert it in
// any way.
// see: https://docs.microsoft.com/rest/api/storageservices/get-blob
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct VersionId(String);
impl VersionI... |
//! A Proxy Protocol Parser written in Rust.
//! Supports both text and binary versions of the header protocol.
mod ip;
pub mod v1;
pub mod v2;
/// The canonical way to determine when a streamed header should be retried in a streaming context.
/// The protocol states that servers may choose to support partial header... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.