text stringlengths 8 4.13M |
|---|
fn main() {
let x: i32 = 123; // immutable by default
let a = [1, 2, 3]; // a: [i32; 3]
let b = [0; 20] // b: [i32; 20]
let c: (i32, &str) = (1, "Hello"); // tuple
println!("The value of x is: {}", x);
print_number(x);
add_one(2);
}
fn print_number(x: i32) {
println!(... |
pub fn parse(input: &str) -> String {
let mut list = (0..256).collect::<Vec<usize>>();
let mut current = 0usize;
let mut skip_size = 0usize;
let mut lengths: Vec<usize> = input.bytes().map(|value| value as usize).collect();
lengths.extend_from_slice(&[17, 31, 73, 47, 23]);
for _ in 0..64 {
... |
use std::io;
use std::string::String;
use std::iter::Iterator;
fn main() {
println!("Hello, sailor! Give me some numbers.");
// read input values
println!("What's the base?");
let mut base = String::new();
io::stdin().read_line(&mut base).unwrap();
let base: u32 = base.trim().parse().unwrap()... |
use aes::*;
use calc_cikey::*;
fn main() {
let round10_key_raw = [
0x3f, 0x42, 0x33, 0x7d,
0x08, 0x39, 0x9e, 0xc2,
0x8a, 0x89, 0x96, 0xe5,
0x7c, 0xeb, 0x59, 0x17,
];
let round10_key = GF256::from_u8array(&round10_key_raw).unwrap();
let round_keys = inv_generate_round_ke... |
use std::collections::BTreeSet;
use std::env;
use std::fs;
use std::io;
static PART2: bool = true;
fn main() {
let input = read_input().unwrap();
let trace_0 = trace_wire(&input.0[..]);
let trace_1 = trace_wire(&input.1[..]);
if PART2 {
let intersections: BTreeSet<Position> = find_intersecti... |
use std::clone::Clone;
use crate::ast::expressions::operators;
use crate::ast::lexer::tokens::Keyword;
use crate::interpreter::{self, environment, types};
use crate::utils;
impl interpreter::Eval for operators::Unop {
// unop ::= β-β | not | β#β | β~β
// Keyword::MINUS, Keyword::NOT, Keyword::HASH, Keyword::... |
use rust_signpost::*;
fn main() {
declare_signpost(0x100);
println!("declared signpost!");
std::thread::park_timeout(std::time::Duration::from_secs(10));
start_signpost(0x100);
println!("started signpost!");
std::thread::park_timeout(std::time::Duration::from_secs(10));
end_signpost(0x... |
extern crate nalgebra as na;
use na::{Vector2, Point2};
use ncollide2d::pipeline::CollisionGroups;
use ncollide2d::shape::{Cuboid, ShapeHandle};
use nphysics2d::force_generator::{DefaultForceGeneratorSet, ForceGenerator};
use nphysics2d::joint::DefaultJointConstraintSet;
use nphysics2d::joint::{PrismaticConstraint, Re... |
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct PidProto {
#[prost(bytes, tag="1")]
pub pid: std::vec::Vec<u8>,
}
/// List of created/deleted process ids
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct ProcessList {
#[prost(bytes, tag="2")]
pub newids: std::vec::Vec<u8>,
#[prost(by... |
mod containers;
// TODO make these private.
pub mod dependencies;
pub mod importgraph;
pub mod layers;
use crate::dependencies::PackageDependency;
use containers::check_containers_exist;
use importgraph::ImportGraph;
use layers::Level;
use log::info;
use pyo3::create_exception;
use pyo3::prelude::*;
use pyo3::types::{... |
use bevy::prelude::*;
use bevy::render::texture::{Extent3d, TextureDimension, TextureFormat};
use rand::seq::SliceRandom;
use rand::Rng;
use std::cell::RefCell;
use std::ops::DerefMut;
static WINDOW_SIZE: f32 = 1000.0;
static BOARD_SIZE: usize = 100;
static BOARD_SIZE_F32: f32 = BOARD_SIZE as f32;
thread_local! {
... |
use crate::node;
pub struct TextStyleBuilder(Vec<String>);
impl TextStyleBuilder {
pub fn from(content: String) -> Self {
TextStyleBuilder(vec![content])
}
}
impl TextStyleBuilder {
pub fn append(&mut self, content: String) {
self.0.push(content);
}
pub fn build(self) -> node::Text... |
#[doc = "Register `C2IMR2` reader"]
pub type R = crate::R<C2IMR2_SPEC>;
#[doc = "Register `C2IMR2` writer"]
pub type W = crate::W<C2IMR2_SPEC>;
#[doc = "Field `DMA1_CH1_IM` reader - Peripheral DMA1 CH1 interrupt mask to CPU2"]
pub type DMA1_CH1_IM_R = crate::BitReader;
#[doc = "Field `DMA1_CH1_IM` writer - Peripheral D... |
#![no_std]
#![feature(start)]
#![feature(asm)]
#![no_main]
#![cfg_attr(test, no_main)]
#![feature(alloc_error_handler)]
#![feature(custom_test_frameworks)]
#![feature(core_intrinsics)]
#![feature(gen_future)]
#![feature(const_mut_refs)]
#![feature(naked_functions)]
#![feature(abi_x86_interrupt)]
#![feature(intra_doc_po... |
#[doc = "Register `DOR2` reader"]
pub type R = crate::R<DOR2_SPEC>;
#[doc = "Field `DACC2DOR` reader - DAC channel2 data output"]
pub type DACC2DOR_R = crate::FieldReader<u16>;
impl R {
#[doc = "Bits 0:11 - DAC channel2 data output"]
#[inline(always)]
pub fn dacc2dor(&self) -> DACC2DOR_R {
DACC2DOR_... |
//! A WebSocket echo server.
use lunatic::net::TcpStream;
use puck::{
body::Body,
serve,
ws::{message::Message, send::send, websocket::WebSocket},
Request, Response,
};
pub fn echo(_: Request, stream: TcpStream) {
let mut ws = WebSocket::new(stream.clone());
// note that this will *never* ret... |
/// CreateRepoOption options when creating repository
#[derive(Debug, Default, Clone, Serialize, Deserialize)]
pub struct CreateRepoOption {
/// Whether the repository should be auto-intialized?
pub auto_init: Option<bool>,
/// DefaultBranch of the repository (used when initializes and in template)
pub... |
/// A trait for defining an interface against a raw key-value store (e.g `leveldb/rocksdb`).
pub trait RawKV {
/// # Gets the `value` pointed by by `key`.
///
/// If there's a matchikg pending `value` (i.e not flushed yet) it should be returned.
/// Otherwise, should proceed looking for `key -> value` u... |
extern crate nimble;
use nimble::score;
use nimble::utils;
use nimble::reference_library;
use std::path::Path;
use std::collections::HashMap;
use clap::{App, load_yaml};
fn main() {
// Parse command line arguments based on the yaml schema
let yaml = load_yaml!("cli.yml");
let matches = App::from_yaml(yaml).get... |
use std::{error::Error, path::PathBuf};
use clap::Parser;
mod legacy {
use serde::Deserialize;
use serde_yaml::Value;
#[derive(Debug, Deserialize, Clone)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct Test {
pub description: String,
pub min_server_version: Str... |
#[doc = "Register `EMR2` reader"]
pub type R = crate::R<EMR2_SPEC>;
#[doc = "Register `EMR2` writer"]
pub type W = crate::W<EMR2_SPEC>;
#[doc = "Field `EM32` reader - Event mask on external/internal line 32"]
pub type EM32_R = crate::BitReader<EM32_A>;
#[doc = "Event mask on external/internal line 32\n\nValue on reset:... |
use poker;
use poker::Hand;
use std::str::FromStr;
#[test]
fn it_evaluates_hand() {
let hand = Hand::from_str("Aβ₯ Kβ₯ Qβ₯ Jβ₯ 10β₯").unwrap();
assert_eq!(hand.evaluate(), "royal flush");
let hand = Hand::from_str("Qβ₯ Jβ₯ 10β₯ 9β₯ 8β₯").unwrap();
assert_eq!(hand.evaluate(), "straight flush");
let hand = H... |
mod native;
use native::*;
use std::fs::OpenOptions;
use std::path::Path;
use memflow::*;
use memflow_derive::*;
use std::fs::File;
/**
The `parse_file` function reads and parses Microsoft Windows Coredump files.
When opening a crashdump it tries to parse the first 0x2000 bytes of the file as a 64 bit Windows Core... |
use super::*;
use std::convert;
#[derive(Debug, Copy, Clone)]
pub struct Exception {
exception_: Local<V8::Object>,
}
impl Exception {
pub fn as_rust_string(&mut self) -> std::string::String {
let context = Isolate::get_current_context();
let mut to_string = self.exception_.get(context, "toStr... |
#[allow(missing_docs)]
#[rustc_copy_clone_marker]
pub struct Vertex {
pub pos: [f32; 2],
pub colour: [f32; 4],
}
#[automatically_derived]
#[allow(unused_qualifications)]
#[allow(missing_docs)]
impl ::std::clone::Clone for Vertex {
#[inline]
fn clone(&self) -> Vertex {
{
let _: ::std::clone::AssertParamIsClone<... |
fn main() {
println!("{}", odd_man_out(&[1, 34, 1, 7, 34]))
}
fn odd_man_out(myarray: &[i32]) -> i32 {
println!("My original reference to an array = {:?}", myarray);
// a normal iteration over our array
for i in myarray {
println!("At the start of the iteration loop: {}", i);
// let'... |
use rocket::http::ContentType;
use rocket::local::{Client, LocalResponse};
use crate::logging::launch_logger;
use crate::status::robot_state::GlobalRobotState;
use super::*;
const TIMEOUT_MILLIS: u64 = 30;
fn send_drive(client: &Client, left: f32, right: f32) -> LocalResponse {
let json = format!("{{\"Drive\" :... |
fn tokenize(c : char) {
match c {
v @ '0' ... '9' => println!("digit = {} {}", c, v),
'd' => println!("die roll"),
_ => println!("unknown")
}
}
fn main() {
let program = "d20";
for token in program.chars() {
tokenize(token);
}
}
|
//! Code used to serialize crate data to JSON.
mod api;
pub use self::api::*;
use std::collections::HashMap;
use analysis::{self, AnalysisHost, DefKind};
use rayon::prelude::*;
use serde_json;
use error::*;
/// This creates the JSON documentation from the given `AnalysisHost`.
pub fn create_json(host: &AnalysisHo... |
#![doc = "generated by AutoRust 0.1.0"]
#![allow(non_camel_case_types)]
#![allow(unused_imports)]
use serde::{Deserialize, Serialize};
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct GuestConfigurationAssignmentList {
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub value: Vec<... |
#[doc = "Register `CR1_disabled` reader"]
pub type R = crate::R<CR1_DISABLED_SPEC>;
#[doc = "Register `CR1_disabled` writer"]
pub type W = crate::W<CR1_DISABLED_SPEC>;
#[doc = "Field `UE` reader - LPUART enable When this bit is cleared, the LPUART prescalers and outputs are stopped immediately, and current operations a... |
pub fn encrypt(){
// Some testdata to encrypt.
//let plaintext = "Hello Feistel, please encrypt this text";
//println!("{:?}", plaintext.chars());
let mut left = [125u8, 34u8, 124u8, 168u8, 86u8, 24u8, 201u8, 134u8];
let mut right = [12u8, 14u8, 174u8, 128u8, 46u8, 24u8, 121u8, 184u8];
for _ ... |
#![allow(proc_macro_derive_resolution_fallback)]
use diesel;
use diesel::prelude::*;
use schema::users;
use users::entity::User;
pub fn all(connection: &PgConnection) -> QueryResult<Vec<User>> {
users::table.load::<User>(&*connection)
}
pub fn get(id: i32, connection: &PgConnection) -> QueryResult<User> {
us... |
{
"id": "7521074e-9a32-43f6-b552-b2b9c6dafe6d",
"$type": "ReferencingResource",
"RefToSame": "e4158344-6039-4903-a066-9fd756ac7237"
} |
//! Game of life world logic
use std::collections::HashSet;
/// Size of the Game of Life world
const SIZE: usize = 64;
type Coords = [usize; 2];
/// Stores Game of Life world information
pub struct World {
/// Stores the state of the cells.
/// `false` means that cell is dead
/// `true` means that cell i... |
#[doc = "Register `APB1LFZ1` reader"]
pub type R = crate::R<APB1LFZ1_SPEC>;
#[doc = "Register `APB1LFZ1` writer"]
pub type W = crate::W<APB1LFZ1_SPEC>;
#[doc = "Field `DBG_TIM2` reader - TIM2 stop in debug"]
pub type DBG_TIM2_R = crate::BitReader;
#[doc = "Field `DBG_TIM2` writer - TIM2 stop in debug"]
pub type DBG_TIM... |
use petshop::pets::cat::Cat;
use petshop::pets::dog::Dog;
#[test]
fn test_dog_print_default() {
let t_dog = Dog::default();
assert_eq!(
"Name: Unnamed, Species: Canine".to_string(),
t_dog.to_string()
);
}
#[test]
fn test_dog_print_new_no_name() {
let t_dog = Dog::new(None);
assert_... |
use bazel_protos;
use boxfuture::{Boxable, BoxFuture};
use digest::{Digest as DigestTrait, FixedOutput};
use futures::{future, Future};
use futures_cpupool::CpuFuture;
use lmdb::{Database, DatabaseFlags, Environment, NO_OVERWRITE, Transaction};
use lmdb::Error::{KeyExist, NotFound};
use protobuf::core::Message;
use sha... |
use std::cmp::Ordering;
use crate::units::{PreciseTime, TimeInt};
use crate::constants::*;
/// ISO 8601 time duration with picosecond precision.
#[derive(Debug,Clone,Copy,PartialEq,Eq)]
pub struct Duration {
secs: TimeInt,
picos: TimeInt,
}
impl Duration {
/// Create a duration with the specified number ... |
use proconio::input;
fn main() {
input! {
n: usize,
aa: [i64; n],
};
let mut sums1: Vec<i64> = vec![];
let mut sums2: Vec<i64> = vec![];
let mut sum1 = 0;
let mut sum2 = 0;
for a in aa.iter() {
sum1 += a;
sum2 += a * a;
sums1.push(sum1);
sums2... |
pub fn read_stdin(_msg: &str) {}
|
use error_chain::error_chain;
error_chain! {
foreign_links {
Json(serde_json::Error);
Toml(toml::de::Error);
}
}
pub fn parse_normal_json() -> Result<()> {
use serde_json::json;
use serde_json::Value;
let j = r#"{
"userid": 100,
"verified": true,
"access_pr... |
//! This module implements a WebSocket client and proxy that lives in the
//! web worker and communicates with the server as well as the main Elm application.
use wasm_bindgen::prelude::*;
use wasm_bindgen::JsCast;
use web_sys;
use web_sys::{MessageEvent, WebSocket, WorkerGlobalScope};
#[wasm_bindgen]
pub fn start_we... |
#![doc = "generated by AutoRust 0.1.0"]
#![allow(non_camel_case_types)]
#![allow(unused_imports)]
use serde::{Deserialize, Serialize};
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct AppServiceCertificate {
#[serde(rename = "keyVaultId", default, skip_serializing_if = "Option::is_none")]
p... |
#[doc = "Register `OAR2` reader"]
pub type R = crate::R<OAR2_SPEC>;
#[doc = "Register `OAR2` writer"]
pub type W = crate::W<OAR2_SPEC>;
#[doc = "Field `OA2` reader - Interface address"]
pub type OA2_R = crate::FieldReader;
#[doc = "Field `OA2` writer - Interface address"]
pub type OA2_W<'a, REG, const O: u8> = crate::F... |
fn main() {
type I32 = i32;
let a_i32:i32 = 5;
let b_i32:I32 = 5;
if a_i32 == b_i32 {
println!("a is equal to b");
} else {
println!("no");
}
}
|
pub trait OpenapiSerialization {
fn serialize(&self) -> Option<String>;
}
impl OpenapiSerialization for i32 {
fn serialize(&self) -> Option<String> {
Some(format!("{:?}", self))
}
}
impl OpenapiSerialization for i64 {
fn serialize(&self) -> Option<String> {
Some(format!("{:?}", self))
... |
mod behaviour;
mod compress;
mod config;
pub mod errors;
pub mod network;
mod network_group;
mod peer;
pub mod peer_registry;
pub mod peer_store;
mod protocols;
mod services;
#[cfg(test)]
mod tests;
pub use crate::{
behaviour::Behaviour,
config::NetworkConfig,
errors::Error,
network::{NetworkControlle... |
use crate::shapes::calculable::AreaCalculable;
pub struct Triangle {
pub bot_edge: f32,
pub height: f32,
}
impl AreaCalculable for Triangle {
fn area(&self) -> f32 {
self.bot_edge * self.height * 0.5
}
}
pub struct Rectangle {
pub width: f32,
pub height: f32,
}
impl AreaCalculable fo... |
#[doc = "Reader of register MCWDT_INTR_SET"]
pub type R = crate::R<u32, super::MCWDT_INTR_SET>;
#[doc = "Writer for register MCWDT_INTR_SET"]
pub type W = crate::W<u32, super::MCWDT_INTR_SET>;
#[doc = "Register MCWDT_INTR_SET `reset()`'s with value 0"]
impl crate::ResetValue for super::MCWDT_INTR_SET {
type Type = ... |
use crate::{error::ProcessingError, fuzzers, metadata, search::read_runs};
use indicatif::ParallelProgressIterator;
use rayon::prelude::*;
use std::{fs, path::Path, time::Instant};
/// Process raw artifacts.
pub fn process(
in_directory: &Path,
out_directory: &Path,
fuzzers: &[fuzzers::Fuzzer],
targets... |
use lazy_static::lazy_static;
use spin::Mutex;
use uart_16550::SerialPort;
lazy_static! {
pub static ref SERIAL1: Mutex<SerialPort> = {
let mut serial_port = unsafe { SerialPort::new(0x3F8) };
serial_port.init();
Mutex::new(serial_port)
};
}
#[doc(hidden)]
pub fn _print(args: ::core::f... |
use tower::{filter::AsyncFilterLayer, util::Either};
#[cfg(any(feature = "native-tls", feature = "rustls-tls", feature = "openssl-tls"))]
use super::tls;
use super::{
auth::Auth,
middleware::{AddAuthorizationLayer, AuthLayer, BaseUriLayer},
};
use crate::{Config, Error, Result};
/// Extensions to [`Config`](c... |
use super::prelude::*;
#[derive(Debug, Clone, PartialEq)]
pub enum Stmt {
ExprStmt(ExprStmt),
Let(Let),
Return(Return),
Block(Block),
}
impl Display for Stmt {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
match self {
Self::ExprStmt(s) => write!(f, "{}", s),
... |
// Copyright (c) Facebook, Inc. and its affiliates.
//
// This source code is licensed under the MIT license found in the
// LICENSE file in the "hack" directory of this source tree.
//
// @generated SignedSource<<7cfaf3a38d82c49f41cd1840dcff5620>>
//
// To regenerate this file, run:
// hphp/hack/src/oxidized_by_ref/... |
use crate::error::{CellbaseError, CommitError, Error, UnclesError};
use crate::header_verifier::HeaderResolver;
use crate::{TransactionVerifier, Verifier};
use ckb_core::cell::ResolvedTransaction;
use ckb_core::header::Header;
use ckb_core::transaction::{Capacity, CellInput, CellOutput, Transaction};
use ckb_core::Cycl... |
#![allow(clippy::identity_op)]
#![allow(clippy::large_enum_variant)]
use crate::utils::to_u8_slice;
#[derive(Copy, Clone, Debug)]
pub enum XGbePortOp {
TurnOn,
TurnOff,
}
impl XGbePortOp {
pub fn get_raw_data(self) -> Vec<u8> {
match self {
XGbePortOp::TurnOn => vec![0x01, 0, 0, 0],
... |
use auto_impl::auto_impl;
#[auto_impl(&)]
trait Foo {
fn foo<const I: i32>(&self);
}
fn main() {}
|
use std::borrow::Cow;
use std::io::Write;
use quick_xml::events::attributes::Attribute;
use quick_xml::events::{BytesEnd, BytesStart, BytesText, Event};
use quick_xml::name::QName;
use quick_xml::Writer;
use crate::encoding_type::EncodingType;
use crate::error::KbinError;
use crate::node::NodeCollection;
use crate::n... |
#[path = "support/macros.rs"]
#[macro_use]
mod macros;
use criterion::{criterion_group, criterion_main, Criterion};
fn bench_vec3_length(c: &mut Criterion) {
use criterion::Benchmark;
c.bench(
"vec3 length",
Benchmark::new("glam", |b| {
use glam::Vec3;
bench_unop!(b, op ... |
use core::fmt;
use std::collections::{HashSet, VecDeque};
use std::hash::Hash;
use std::net::SocketAddr;
use std::ops::Deref;
use std::sync::Arc;
use std::time::Duration;
use clap::Parser;
use dashmap::DashMap;
use hyper::{Body, Request, Response};
use internment::Intern;
use petgraph::graph::NodeIndex;
use petgraph... |
use std::io::{self, Read};
use permutohedron::heap_recursive;
extern crate intcode_computer;
use intcode_computer::{address_counter, State};
fn read_stdin() -> String{
let mut buffer = String::new();
io::stdin().read_to_string(&mut buffer).expect("did not recieve anything from stdin");
return buffer;
}
fn max_s... |
use crate::binds::{Bind, BindCount, BindsInternal, CollectBinds};
use crate::WriteSql;
use std::fmt::{self, Write};
#[derive(Debug, Clone)]
pub struct Offset(pub(crate) OffsetI);
impl Into<Offset> for OffsetI {
fn into(self) -> Offset {
Offset(self)
}
}
impl Offset {
pub fn raw(sql: &str) -> Self... |
#[doc = r"Register block"]
#[repr(C)]
pub struct RegisterBlock {
#[doc = "0x00 - TIM16 control register 1"]
pub tim16_cr1: TIM16_CR1,
_reserved1: [u8; 0x02],
#[doc = "0x04 - TIM16 control register 2"]
pub tim16_cr2: TIM16_CR2,
_reserved2: [u8; 0x06],
#[doc = "0x0c - TIM16 DMA/interrupt enabl... |
use regex::Regex;
use std::io::{self, BufRead as _};
type BoxError = Box<dyn std::error::Error>;
fn main() -> Result<(), BoxError> {
let re = Regex::new(r"^(\d+)-(\d+) ([a-z]): ([a-z]+)$").expect("regex is valid");
let mut valid = 0;
for line in io::stdin().lock().lines() {
let line = line?;
... |
#![deny(warnings, missing_docs, missing_debug_implementations)]
#![cfg_attr(test, deny(warnings, unreachable_pub))]
//! Why multiply, when you can divide.
//! I'd like to acknowledge the wonderful work done by the developers of Slab.
//! Much of this is a direct derivative of their work.
//!
//! Build on top of Slab, ... |
use crate::rl::prelude::*;
pub trait Environment<A: Action>: Clone {
fn reset(&mut self);
fn observe(&self) -> State;
fn step(&mut self, action: &A) -> Reward;
fn is_done(&self) -> bool;
fn max_reward(&self) -> Reward;
fn action_space(&self) -> usize;
fn observation_space(&self) -> usize;
}... |
use std;
use std::collections::HashMap;
use std::fmt::Display;
use std::path::Path;
use assembler::lexer::{Lexer, LexerError};
use assembler::parser::{Parser, ParserError};
use assembler::token::{LexerToken, ParserToken};
use opcodes::{AddressingMode, OpCode};
#[derive(Debug, PartialEq)]
pub struct Label(u16);
#[de... |
use async_echo::{echo_server, EcResult};
use async_std::io::{stdin, BufRead, BufReader};
use async_std::stream::Stream;
use async_std::task;
async fn wait_exitus() -> EcResult<()> {
let mut lines = BufReader::new(stdin()).lines();
while let Some(line) = lines.next().await {
if line? == "exit" {
... |
pub mod key;
pub mod oauth2;
pub mod reset;
pub mod token;
use crate::{
core,
server::{
route_json_config, route_response_json, validate, Data, Error, FromJsonValue,
PwnedPasswordsError,
},
};
use actix_web::{
http::{header, StatusCode},
middleware::identity::Identity,
web, Http... |
use std::time::{Duration, SystemTime};
/// Basic metadata for a file.
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
pub struct Metadata {
accessed: Duration,
created: Duration,
modified: Duration,
}
impl Metadata {
/// Create a new [`Metadata`] using the number of seconds since the
/// [`SystemTime... |
// Copyright 2021 MaidSafe.net limited.
//
// This SAFE Network Software is licensed to you under The General Public License (GPL), version 3.
// Unless required by applicable law or agreed to in writing, the SAFE Network Software distributed
// under the GPL Licence is distributed on an "AS IS" BASIS, WITHOUT WARRANTI... |
#![feature(test)]
#[allow(dead_code)]
const KB: usize = 1024;
#[allow(dead_code)]
const MB: usize = KB * KB;
#[allow(dead_code)]
const N: usize = 2 * MB;
#[cfg(test)]
mod tests {
use super::*;
extern crate test;
use test::Bencher;
#[bench]
fn bench_calc_with_15det_array(b: &mut Bencher) {
... |
#[doc = "Reader of register WAKEUP_CONFIG_EXTD"]
pub type R = crate::R<u32, super::WAKEUP_CONFIG_EXTD>;
#[doc = "Writer for register WAKEUP_CONFIG_EXTD"]
pub type W = crate::W<u32, super::WAKEUP_CONFIG_EXTD>;
#[doc = "Register WAKEUP_CONFIG_EXTD `reset()`'s with value 0"]
impl crate::ResetValue for super::WAKEUP_CONFIG... |
use crate::data::component::{Component, PortType, StateChange};
use crate::data::subnet::SubnetState;
use std::collections::HashMap;
use std::cell::Cell;
use crate::{map, port_or_default};
#[derive(Debug)]
pub(crate) struct Constant {
#[cfg(not(test))]
state: Cell<bool>,
#[cfg(test)]
pub state: Cell<bo... |
#[macro_use] extern crate log;
#[macro_use] extern crate serde_derive;
mod button;
mod database;
mod event;
mod moisture;
mod valve;
mod weather;
pub mod controller;
pub mod pirrigator;
pub mod settings;
|
use anyhow::Result;
// use pay_tx::run;
use pay_tx::run_stream;
#[tokio::main]
async fn main() -> Result<()> {
env_logger::init();
run_stream().await?;
// run()?;
Ok(())
}
|
use glium::Display;
use crate::draw::{Vertex, ObjDef, load_data_to_gpu};
use crate::quadoctree::CollisionObj;
pub fn generate_cube_vertices(pre_pos: &[f32; 3], post_pos: &[f32; 3], dim: &[f32; 3], yaw: f32) -> [Vertex; 24] {
let gen_pos = |proto: [f32; 3]| {
let before_yaw = [proto[0] * dim[0] + pre_pos[0], proto[1... |
// 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 crate::{
errors::*,
group::Group,
key_exchange::NONCE_LEN,
keypair::{Key, KeyPair, SignalKeyPair},
opaque::*,
... |
extern crate aoc2017;
use aoc2017::days::day16;
fn main() {
let input = aoc2017::read_trim("input/day16.txt").unwrap();
let programs = "abcdefghijklmnop";
// let value1 = day16::part1::parse(programs, &input, 1);
let value2 = day16::part2::parse(programs, &input, 1_000_000_000);
// println!("Day 16... |
/*
*/
use parse::lex;
pub struct Preproc
{
lexers: ::std::vec::Vec<LexHandle>,
saved_tok: Option<::parse::lex::Token>,
macros: ::std::collections::TreeMap<String,Vec<lex::Token>>
}
struct LexHandle
{
lexer: ::parse::lex::Lexer,
filename: String,
line: uint,
}
macro_rules! syntax_assert( ($tok:expr, $pat:pat =... |
/// Round the 'array' passed using 'decimals'
pub fn round_array(array: &mut [f64], decimals: u8) {
let divider = (10.0 as f64).powi(decimals as i32);
for number in array {
*number = (*number * divider).round() / divider;
}
}
|
// Copyright 2019 Google LLC
//
// 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 ... |
pub struct Solution {}
/// LeetCode Monthly Challenge problem for February 22nd, 2021.
impl Solution {
/// Given a string, s, and a vector of strings, d, returns the longest
/// string in d that can be formed from s with zero or more deletions.
/// If there are two or more possible results, returns the sm... |
use crate::fnmatch::fnmatch;
use std::fs::{self, DirEntry};
use std::path::{Component, Path, PathBuf, MAIN_SEPARATOR};
/// A directory entry found in a walk paired with pattern matched substrings.
///
/// This is a pair of a `std::fs::DirEntry` found while the walk and a vector
/// of the substrings.
pub struct Match ... |
// Generated from crates/unflow-parser/src/grammar/Design.g4 by ANTLR 4.8
#![allow(dead_code)]
#![allow(non_snake_case)]
#![allow(non_upper_case_globals)]
#![allow(nonstandard_style)]
#![allow(unused_imports)]
#![allow(unused_mut)]
use antlr_rust::PredictionContextCache;
use antlr_rust::parser::{Parser, BaseParser, Par... |
//! Displays spheres with physically based materials.
extern crate amethyst;
extern crate cgmath;
extern crate futures;
extern crate genmesh;
use amethyst::assets::{AssetFuture, BoxedErr};
use amethyst::ecs::rendering::{AmbientColor, Factory, LightComponent, MaterialComponent,
MeshCompo... |
use crate::solutions::Solution;
pub struct Day2 {}
impl Day2 {
fn run(&self, input: String, layout: impl Layout) {
let mut code = String::new();
let mut key_pad = KeyPad::new(layout);
for sequence in parse_input(&input) {
key_pad.steps(sequence);
code.push(key_pad.... |
use proconio::{fastout, input};
#[fastout]
fn main() {
input! {
n: usize,
k: usize,
mut p_vec: [usize; n],
c_vec: [i64; n],
};
for i in 0..n {
p_vec[i] -= 1;
}
let mut ans = i64::MIN;
for i in 0..n {
let mut x = i;
let mut s_vec: Vec<i64> ... |
use super::{ Action, ToExile};
use super::settings;
use rapier3d::{
dynamics::{
RigidBodyBuilder, BodyStatus, RigidBodySet, RigidBodyHandle, JointSet,
},
geometry::{ ColliderSet, ColliderBuilder, },
na::{ Vector3, geometry::UnitQuaternion, },
na,
};
use dotrix::{
Transform,
Pipelin... |
extern crate lab_common;
extern crate rand;
use std::process::exit;
use rand::Rng;
use lab_common::get_user_input;
const MAX_NUMBER: usize = 1000;
const GUESSES: usize = 10;
fn main() {
let answer: usize = rand::thread_rng().gen_range(0, MAX_NUMBER);
println!("Guess a number from 0 to {}.", MAX_NUMBER);
... |
/*!
Command-line arguments and command processing
*/
use gear::system::{Path, PathBuf};
use std::str::FromStr;
use structopt::StructOpt;
/// Default rules files
const RULES_FILES: &str = "Gearfile, Gearfile.js, Gear.js";
/// Default config files
const CONFIG_FILES: &str = "gear.json, gear.yaml, gear.toml";
/// Def... |
#[doc = "Register `CRCCR` reader"]
pub type R = crate::R<CRCCR_SPEC>;
#[doc = "Register `CRCCR` writer"]
pub type W = crate::W<CRCCR_SPEC>;
#[doc = "Field `CRC_SECT` reader - Bank 1 CRC sector number"]
pub type CRC_SECT_R = crate::FieldReader;
#[doc = "Field `CRC_SECT` writer - Bank 1 CRC sector number"]
pub type CRC_S... |
use iced::alignment::{Horizontal, Vertical};
use iced::widget::scrollable::Direction;
use iced::widget::tooltip::Position;
use iced::widget::{button, vertical_space};
use iced::widget::{lazy, Column, Container, Row, Scrollable, Text, Tooltip};
use iced::Length::FillPortion;
use iced::{Alignment, Font, Length, Renderer}... |
// TODO: move this to configuration files?
// Screen constants
pub const SCREEN_WIDTH: f32 = 256.0;
pub const SCREEN_HEIGHT: f32 = 256.0;
// Some ~physics constants
pub const BALL_SPEED_FOR_MINIMUM_COLLISION: f32 = 256.0;
pub const BALL_MINIMUM_COLLISION_FACTOR: f32 = 0.3;
// Player position constants
pub const MAXIMUM... |
use serde::{Deserialize, Serialize};
#[derive(Debug, Clone, Copy, Serialize, Deserialize, Hash, PartialEq, Eq)]
pub struct Evaluation(pub i32);
|
use std::io;
use std::net::SocketAddr;
use futures::try_join;
use super::copy;
use crate::transport::plain::{self, PlainStream, PlainListener};
use crate::transport::{AsyncConnect, AsyncAccept};
async fn bidi_copy<S, C>(
res: (PlainStream, SocketAddr),
lis: S,
conn: C,
) -> io::Result<()>
where
S: Asy... |
use std::collections::{HashMap, HashSet};
const PART2: bool = true;
const DIM_COUNT: usize = if PART2 { 4 } else { 3 };
const CYCLES: usize = 6;
type CoordType = i8;
fn main() {
let input = String::from_utf8(std::fs::read("input/day17").unwrap()).unwrap();
let mut active_cubes: HashSet<[CoordType; DIM_COUNT]>... |
//! Minimal `cortex-m-rt` based program
#![deny(unsafe_code)]
#![deny(warnings)]
#![no_main]
#![no_std]
extern crate cortex_m_rt as rt;
extern crate panic_halt;
use rt::entry;
// the program entry point
#[entry]
fn main() -> ! {
loop {}
}
|
// Copyright 2019 Fabian Freyer <fabian.freyer@physik.tu-berlin.de>
// Copyright 2018 David O'Rourke <david.orourke@gmail.com>
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code m... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.