text stringlengths 8 4.13M |
|---|
use day07::{part_1, part_2};
fn main() {
let result1 = part_1();
println!("The highest signal that can be sent to thrusters is {}", result1);
let result2 = part_2();
println!("The highest signal that can be sent to thrusters with is {}", result2)
}
|
use std::{
error::Error,
io::Read,
sync::{Arc, Mutex},
};
use crate::database::Database;
use crate::models::Post;
use iron::{headers::ContentType, status, AfterMiddleware, Handler, IronResult, Request, Response};
use router::Router;
use serde_json;
use uuid::Uuid;
macro_rules! handle_json {
($payload:... |
use std::collections::VecDeque;
use std::collections::HashMap;
#[derive(Debug)]
pub struct FunctionCall {
pub name: String,
pub args_exprs: Vec<AstExpressionNode>,
}
#[derive(Debug, PartialEq, Clone, Copy)]
pub enum PointerType {
// just a regular pointer, nothing special about it
Raw,
// Is free... |
extern crate image;
extern crate rand;
use std::f32;
use Circle;
use Point;
use ResultRaster;
use RasterUtils;
use std::fs::File;
use std::path::Path;
static LEN: usize = 66_049;
// struct for a raster: this raster's pixels contain elevation data
pub struct Raster{
pub pixels: Vec<Option<f32>>, // height array
... |
pub struct MissingArmoredPublicKey;
pub struct ArmoredPublicKeyExists;
pub struct MissingAttachment;
pub struct AttachmentExists;
pub struct MissingAttachmentId;
pub struct AttachmentIdExists;
pub struct MissingBody;
pub struct BodyExists;
pub struct MissingBranch;
pub struct BranchExists;
pub struct MissingCloneAddr;... |
//! Translation of
//! <http://www.cs.brandeis.edu/~storer/LunarLander/LunarLander/LunarLanderListing.jpg>
//! by Jim Storer from FOCAL to Rust.
use lunar::lander::Lander;
use lunar::stdio::StdIO;
use std::env;
fn main() {
let mut io = StdIO::default();
let args = env::args().collect::<Vec<String>>();
i... |
// Implementation based off of http://blog.libtorrent.org/2011/11/writing-a-fast-piece-picker/
use torrent::{Peer, Bitfield};
use std::ops::IndexMut;
use control::cio;
#[derive(Clone, Debug)]
pub struct Picker {
/// Current order of pieces
pieces: Vec<u32>,
/// Indices into pieces which indicate priority ... |
//! This module contains a different functions which are used by the [`Grid`].
//!
//! You should use it if you want to comply with how [`Grid`].
//!
//! [`Grid`]: crate::grid::iterable::Grid
/// Returns string width and count lines of a string. It's a combination of [`string_width_multiline`] and [`count_lines`].
#[c... |
use std::ffi::OsStr;
use std::fs::File;
use std::io::{BufRead, BufReader};
use std::net::SocketAddr;
use std::path::Path;
use std::sync::atomic::{AtomicU64, Ordering};
use log::debug;
use log::error;
use log::warn;
use crate::base::check_access;
use crate::base::{FileKind, Timestamp, UserContext};
use crate::client::... |
use anyhow::Result;
use criterion::{black_box, criterion_group, criterion_main, Criterion, ParameterizedBenchmark};
use filecoin_hashers::{
poseidon::PoseidonDomain, poseidon::PoseidonHasher, sha256::Sha256Hasher, Domain,
};
use rand::{thread_rng, Rng};
use storage_proofs_core::merkle::{create_base_merkle_tree, Bin... |
use std::{borrow::Cow, marker::PhantomData, ops::Range};
use async_trait::async_trait;
use custodian_password::{
ClientConfig, ClientFile, ClientRegistration, RegistrationFinalization, RegistrationRequest,
RegistrationResponse,
};
use serde::{Deserialize, Serialize};
use crate::{
document::{Document, Head... |
#![allow(nonstandard_style)]
// Generated from crates/unflow-parser/src/grammar/Design.g4 by ANTLR 4.8
use antlr_rust::tree::{ParseTreeVisitor};
use super::designparser::*;
/**
* This interface defines a complete generic visitor for a parse tree produced
* by {@link DesignParser}.
*/
pub trait DesignVisitor<'input>... |
use anyhow::{Context, Result};
use chrono::prelude::*;
use serde::{Deserialize, Serialize};
use std::{net::Ipv4Addr, str::FromStr};
use strum_macros::{Display, EnumIter};
use url::Url;
/// Holds all application state
///
/// Holds current connection information and settings for the current (only) user
#[derive(Seriali... |
// Copyright 2019, 2020 Wingchain
//
// 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::fmt;
use std::iter::FromIterator;
use std::mem;
use std::ops::{Deref, DerefMut};
use std::ptr;
use std::slice;
use unreachable::unreachable;
use iter_exact::FromExactSizeIterator;
use typehack::binary::*;
use typehack::dim::*;
#[derive(Clone)]
#[repr(u8)]
enum MaybeDropped<T> {
Allocated(T),
Dropp... |
//! Extra parsing combinators for Nom.
use nom::{error::ParseError, Err, IResult, InputIter, InputLength, InputTake, Parser};
#[cfg(test)]
use nom::{bytes::complete::tag, combinator::eof, error::Error, number::complete::float};
#[cfg(test)]
type TestResult<'a, X, S = &'a str> = IResult<&'a str, (S, X), Error<&'a str>... |
#[doc = r"Register block"]
#[repr(C)]
pub struct RegisterBlock {
#[doc = "0x00 - OctoSPI IO Manager Control Register"]
pub cr: CR,
#[doc = "0x04 - OctoSPI IO Manager Port 1 configuration register"]
pub p1cr: P1CR,
#[doc = "0x08 - OctoSPI IO Manager Port 2 configuration register"]
pub p2cr: P2CR,... |
use shape::Shape;
use ::std::default;
#[derive(Default, Copy, Clone)]
pub struct BitBoard {
bits: [u64; 7],
}
impl BitBoard {
pub fn new() -> Self {
BitBoard { bits: [0; 7] }
}
#[inline]
pub fn index(&self, index: usize) -> bool {
let array_index = index / 64;
let shift = ... |
#![allow(clippy::cognitive_complexity)]
#![warn(absolute_paths_not_starting_with_crate)]
#![warn(explicit_outlives_requirements)]
#![warn(unreachable_pub)]
#![warn(deprecated_in_future)]
#![deny(unsafe_code)]
#![deny(unused_extern_crates)]
use std::collections::VecDeque;
use std::fs::File;
use std::io::{self, Write};
... |
use crate::eval::prelude::*;
impl Eval<&ast::Condition> for ConstCompiler<'_> {
fn eval(
&mut self,
condition: &ast::Condition,
used: Used,
) -> Result<Option<ConstValue>, crate::CompileError> {
self.budget.take(condition)?;
match condition {
ast::Condition:... |
struct Radix {
x: i32,
radix: u32,
}
impl Radix {
fn new(x: i32, radix: u32) -> Result<Self, &'static str> {
if radix < 2 || radix > 36 {
Err("Unnsupported radix")
} else {
Ok(Self { x, radix })
}
}
}
use std::fmt;
impl fmt::Display for Radix {
fn f... |
/*
* 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::*;
/// Generate boilerplate code for the `NodeKind` enum.
macro_rules! gen_nodekind_enum {
($name:ident {
$... |
//Reads and writes to the db
use diesel::prelude::*;
use uuid::Uuid;
use crate::schema::{markets};
use crate::api::components::market::model::Market;
use crate::database::DbConn;
pub fn insert_new_market(market : Market, connection : DbConn) -> Market {
let db_con = &*connection;
diesel::insert_into(markets::... |
use bevy::math::Vec3;
use bvh::{Point3, aabb::{AABB, Bounded}};
use crate::constants::CHUNK_SIZE;
impl Bounded for crate::chunks::Voxel {
fn aabb(&self) -> AABB {
let min = self.position;
let max = self.position + Vec3::ONE;
AABB::with_bounds(Point3::new(min.x, min.y, min.z), Po... |
use libp2p::core::ConnectedPoint;
use libp2p::swarm::{PollParameters, NetworkBehaviour, NetworkBehaviourAction};
use libp2p::multiaddr::Multiaddr;
use std::error::Error;
use tokio::prelude::{AsyncRead, AsyncWrite, Async};
use libp2p::PeerId;
use std::collections::{VecDeque, HashSet, HashMap};
use crate::message::{Clien... |
// SPDX-FileCopyrightText: 2020 Alexander Dean-Kennedy <dstar@slackless.com>
// SPDX-License-Identifier: CC0-1.0
use std::env;
use genpdf::Alignment;
use genpdf::Element as _;
use genpdf::{elements, fonts, style};
const FONT_DIRS: &[&str] = &[
"/usr/share/fonts/liberation",
"/usr/share/fonts/truetype/liberat... |
#![allow(dead_code)]
use std::ffi::OsStr;
use std::ffi::OsString;
use std::io;
use std::io::Write;
use std::os::unix::prelude::*;
use std::path::{Path, PathBuf};
use std::sync::RwLock;
use hashbrown::HashSet;
use rayon::prelude::*;
use slog::{debug, o, Level, Logger};
use walkdir::WalkDir;
use chainerror::prelude::... |
// 16.16 Contiguous Sequence
fn contiguous_sequence(array: &[i32]) -> (usize, usize) {
// Returns inclusive bounds of subarray with maximal sum.
// O(n) time, O(1) space.
// We iterate through the array, keeping the maximal subarray and
// maximal suffix as invariants. When a new element is better th... |
use crate::rtb_type;
rtb_type! {
ApiFramework,
500,
VPAID1=1;
VPAID2=2;
MRAID1=3;
ORMMA=4;
MRAID2=5;
MRAID3=6;
OMID1=7;
SIMID=8
}
|
use ckb_error::Error;
use ckb_store::{ChainStore, StoreTransaction};
use ckb_types::{
core::{BlockView, TransactionMeta},
packed::Byte32,
prelude::*,
};
use im::hashmap as hamt;
use im::hashmap::HashMap as HamtMap;
pub fn attach_block_cell(
txn: &StoreTransaction,
block: &BlockView,
cell_set: &... |
use std::io::{self, BufRead, BufReader};
use std::fs::File;
use std::collections::HashMap;
fn main() -> io::Result<()> {
let f = File::open("input.txt")?;
let f = BufReader::new(f);
let mut lines = f.lines();
let first_wire = lines.next().unwrap()?;
let second_wire = lines.next().unwrap()?;
let mut map: H... |
use log::warn;
use nix::libc;
use nix::sys::mman;
use nix::unistd;
use std::ffi::c_void;
use std::fs::File;
use std::os::unix::io::AsRawFd;
use std::path::Path;
use std::ptr::null_mut;
#[cfg(target_os = "linux")]
type MincoreChar = u8;
#[cfg(target_os = "macos")]
type MincoreChar = i8;
pub struct MappedFile {
fi... |
use super::ids::Id;
#[derive(Debug, Clone, Copy, Eq, PartialEq)]
pub enum Size {
MatchParent,
WrapContent,
Exact(u16),
}
#[derive(Debug, Clone, Copy, Eq, PartialEq)]
pub enum Alignment {
None,
Above(Id),
Below(Id),
ToLeftOf(Id),
ToRightOf(Id),
AlignTop(Id),
AlignBottom(Id),
... |
use hyper::{body, header, Body, Method, Request, Uri};
use serde_derive::{Deserialize, Serialize};
use std::collections::BTreeMap;
use std::fmt::{Display, Formatter, Result};
mod auth;
pub mod batch;
pub mod cli;
pub use auth::*;
const DEFAULT_COUNT: u32 = 5000;
#[derive(Serialize, Deserialize, Debug)]
pub struct It... |
pub mod get_account_balance;
pub mod get_incoming;
pub mod get_outgoing;
pub mod get_transactions_with_currency;
pub mod get_counterparties;
pub mod get_aggregates;
pub use api::client::{TellerClient, ApiServiceResult, Transaction, Account};
pub use self::get_account_balance::*;
pub use self::get_incoming::*;
pub use... |
#![feature (nll)]
extern crate codecophony;
extern crate codecophony_editor_shared as shared;
extern crate serde_json;
extern crate portaudio;
extern crate dsp;
extern crate ordered_float;
use std::thread;
use std::io::{self, BufRead, Write};
use std::sync::mpsc::{Sender, Receiver, channel};
//use std::time::Duration;... |
use front::tokens::Token;
use loc::Loc;
#[derive(Debug, PartialEq)]
pub enum SyntaxError {
UnparsableNumberLiteral(String, Loc),
UnparsableCharacterLiteral(String, Loc),
UnrecognizedCharacterSequence(String, Loc),
UnrecognizedToken(Token, Loc),
UnrecognizedCharacterInInput(char, Loc),
Untermina... |
fn main() {
let input = std::fs::read_to_string("../input.txt").unwrap();
let sum: usize = input
.split("\n\n")
.filter(|i| !i.is_empty())
.map(|group| {
let mut set = std::collections::HashSet::new();
for person in group.split("\n") {
for answer i... |
use std::fmt;
#[derive(Debug, PartialEq)]
pub enum MoveState {
Win,
Lose,
CanMove { vertical: bool, horizontal: bool },
}
#[derive(Debug, PartialEq)]
pub enum Cell {
Empty,
Cell(u16),
}
#[derive(Debug, PartialEq)]
pub struct GameState {
cells: [u16; 16],
pub four_percentage: u8,
}
impl Ga... |
pub mod layer0;
pub mod layer1;
pub mod layer2;
pub mod layer3;
pub mod layer4;
pub mod layer5;
use anyhow::{anyhow, Result};
use std::fs::File;
use std::io::prelude::*;
use std::path::PathBuf;
pub fn find_input(haystack: &str) -> Result<Vec<u8>> {
let needle = "==[ Payload ]======================================... |
// Primitive str = Immutable fixed-length string somewhere in memory
//String = Growable heap allocated data structure - Use when you need to modify or own string data
// pus onto string like array
// used for systems programming
pub fn run(){
let mut hello = String::from("Hello ");
//Get Length
println!("Lengt... |
use std::io::Read;
use rocket::{Data, Request};
use rocket::data::{self, FromDataSimple};
use rocket::http::Status;
use rocket::outcome::Outcome::{Failure, Success};
use rocket::response::content;
use crate::user::token;
use crate::user::token::change_user_refresh_token;
#[post("/login", data = "<_user>")]
pub fn lo... |
pub mod state;
pub mod blob;
pub mod world;
use std::time::{Instant, Duration};
use winit::event::{Event, VirtualKeyCode};
use winit::event_loop::{EventLoop, ControlFlow};
pub use blob::Blob;
pub use state::AppState;
pub use world::World;
const FRAME_TIME: u64 = 1000 / 60;
const CONFIG_REFRESH_RATE: Duration = Durat... |
extern crate ez_io;
pub mod decompression;
pub mod direct;
pub mod error;
pub mod file;
use crate::decompression::{CompressInfo, CompressedData};
use crate::direct::files::Packing;
use crate::direct::DPac;
use crate::file::DataType;
use crate::file::File;
/// Result type that ties to general Error used in this crate... |
#[cfg(test)]
#[path = "../../../tests/unit/solver/population/greedy_test.rs"]
mod greedy_test;
use crate::algorithms::nsga2::Objective;
use crate::models::Problem;
use crate::solver::population::{Individual, SelectionPhase};
use crate::solver::{Population, Statistics};
use std::cmp::Ordering;
use std::fmt::{Display, F... |
/// Cpu addressing modes
#[derive(Debug, Copy, Clone, PartialEq)]
pub enum AddrMode {
None, // For KIL operations
Imp, // Implied
Imm, // Immediate
Zp0, // Zero page
Zpx, // Zero page with X
Zpy, // Zero page with Y
Rel, // Relative
Abs, // Absolute
Abx, // Absolute with X
... |
pub mod managers;
pub mod world;
pub mod entity;
pub mod entity_query; |
use anyhow::Result;
use std::str::FromStr;
#[derive(Debug)]
struct Record;
impl FromStr for Record {
type Err = anyhow::Error;
fn from_str(_s: &str) -> Result<Self, Self::Err> {
Ok(Record)
}
}
fn main() -> Result<()> {
let input: Vec<Record> = INPUT.lines().map(|l| l.parse().unwrap()).collec... |
#[derive(Clone, Default)]
pub struct SampleStatistics {
max: f64,
min: f64,
samples: u32,
sum: f64,
sum_of_squares: f64,
}
impl SampleStatistics {
pub fn put(&mut self, v: f64) {
if self.samples == 0 {
self.min.clone_from(&v);
self.max = v;
} else if self... |
extern crate dmbc;
extern crate exonum;
extern crate exonum_testkit;
extern crate hyper;
extern crate iron;
extern crate iron_test;
extern crate mount;
extern crate serde_json;
pub mod dmbc_testkit;
use std::collections::HashMap;
use dmbc_testkit::{DmbcTestApiBuilder, DmbcTestKitApi};
use exonum::crypto;
use exonum... |
use crate::command::Command;
use dyn_clone::{clone_trait_object, DynClone};
use glium::Frame;
impl<T> Drawable for T where T: Fn(&mut Frame) + Clone + Send + Sync + 'static {}
pub trait Drawable: DynClone + Fn(&mut Frame) + Send + Sync + 'static {}
clone_trait_object!(Drawable);
#[derive(Clone)]
pub struct Drawer(Bo... |
extern crate wasm_bindgen;
use wasm_bindgen::prelude::*;
use std::f64::consts::PI;
static STOP_CONDITION: f64 = 1e-6; //停止条件
#[no_mangle]
pub fn add(a : i32, b : i32) -> i32 {
a + b
}
#[wasm_bindgen]
pub fn norm(a : &[f64], b : &[f64]) -> f64 {
let mut sum : f64 = 0.0;
for i in 0..a.len() {
let ... |
use super::Axial;
use serde::{Deserialize, Serialize};
#[derive(Debug, Clone, Default, Copy, Eq, PartialEq, Serialize, Deserialize, Ord, PartialOrd)]
pub struct Hexagon {
pub center: Axial,
pub radius: i32,
}
impl Hexagon {
pub fn new(center: Axial, radius: i32) -> Self {
Self { center, radius }
... |
#[doc = "Register `CICR` reader"]
pub type R = crate::R<CICR_SPEC>;
#[doc = "Register `CICR` writer"]
pub type W = crate::W<CICR_SPEC>;
#[doc = "Field `LSIRDYC` reader - LSI ready interrupt clear Set by software to clear LSIRDYF. Reset by hardware when clear done."]
pub type LSIRDYC_R = crate::BitReader<LSIRDYC_A>;
#[d... |
fn main() {
let mut args = std::env::args();
let _ = args.next();
let path = args.next().expect("First argument must be a file path");
let path = std::path::Path::new(&path);
if !path.exists() {
panic!("First argument must be a file path");
}
let js = std::fs::read_to_string(path).ex... |
use auto_impl::auto_impl;
trait AllExt {
fn foo(&self, _: i32);
}
impl<T> AllExt for T {
fn foo(&self, _: i32) {}
}
// This will expand to:
//
// impl<T: Foo> Foo for &T {
// fn foo(&self, _x: bool) {
// T::foo(self, _x)
// }
// }
//
// With this test we want to make sure,... |
use std::os::raw::{c_char, c_int, c_void};
#[repr(C)]
#[derive(Debug, Copy, Clone)]
pub struct CCaDiCaL {
_unused: [u8; 0],
}
extern "C" {
pub fn ccadical_signature() -> *const c_char;
pub fn ccadical_init() -> *mut CCaDiCaL;
pub fn ccadical_release(arg1: *mut CCaDiCaL);
pub fn ccadical_add(arg1... |
use serde::{Serialize, Deserialize};
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct IrcConfig {
pub servers: Vec<Server>,
}
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct UserData {
pub nickname: String,
pub username: String,
pub realname: String,
}
#[derive(Serialize, Deseria... |
use memory::LinkedList;
use crust::capalloc;
use core;
use mantle::kernel;
use mantle::KError;
use kobject::*;
use core::cell::{RefCell, RefMut};
use core::ops::DerefMut;
struct Subblock {
ut: Option<Untyped>,
us: Option<UntypedSet>,
paddr: usize,
size_bits: u8
}
impl Subblock {
pub fn start(&self... |
extern crate gtk;
use gtk::Builder;
pub struct GladeObjectFactory {
builder: Builder
}
impl GladeObjectFactory {
pub fn new() -> GladeObjectFactory {
// Load glade file
let glade_str = include_str!("ui.glade");
let builder = Builder::new_from_string(glade_str);
GladeObjectF... |
use crate::util::file;
use super::cartridge::cartridge;
use crate::nes::cartridge::cartridge::Cartridge;
/*
An iNES file consists of the following sections, in order:
Header (16 bytes)
Trainer, if present (0 or 512 bytes)
PRG ROM data (16384 * x bytes)
CHR ROM data, if present (8192 * y bytes)
PlayChoice INST-ROM, if... |
use std::convert::TryInto;
use std::io::{stdin, stdout, Write};
fn main() {
let number = get_number_from_user();
let split_numbers: Vec<_> = number
.to_string()
.chars()
.map(|n| n.to_digit(10).unwrap())
.collect();
let power = split_numbers.len();
let mut sum = 0;
... |
use crate::bus::Bus;
#[derive(Debug, Clone, Copy)]
pub struct Ppu<B: Bus> {
pub(crate) bus: B,
}
impl<B: Bus> Ppu<B> {
pub fn new(bus: B) -> Ppu<B> {
Ppu { bus }
}
pub fn reset(&mut self) {}
pub fn step(&mut self) {}
pub fn read(&mut self, address: u16) -> u8 {
0
}
p... |
extern crate minifb;
extern crate rand;
use minifb::{Key, Scale, WindowOptions};
use rand::Rng;
const WIDTH: usize = 640;
const HEIGHT: usize = 360;
#[derive(Copy, Clone)]
struct Star {
x: f64,
y: f64,
z: f64,
speed: f64
}
fn gen_star() -> Star {
let mut rng = rand::thread_rng();
Star {
... |
//! Makes drawing on ncurses windows easier.
use std::cmp::min;
use backend::Backend;
use B;
use theme::{ColorStyle, Effect, Theme};
use vec::{ToVec2, Vec2};
/// Convenient interface to draw on a subset of the screen.
#[derive(Clone)]
pub struct Printer {
/// Offset into the window this printer should start dr... |
#![feature(no_std)]
#![feature(core)]
#![no_std]
//! Toggle the blue LED (PC8) at 1 Hz. The timing is handled by the TIM7 timer. The main thread
//! sleeps most of the time, and only wakes up on TIM7's interrupts to toggle the LED.
//extern crate cortex;
extern crate core;
extern crate nrf51822;
extern crate cortex;
... |
use std::mem;
pub struct List {
head: Link,
size: i32,
}
enum Link {
Empty,
More(Box<Node>),
}
struct Node {
elem: i32,
next: Link,
}
impl List {
pub fn new() -> Self {
List {
head: Link::Empty,
size: 0,
}
}
pub fn push(&mut self, elem: i3... |
#[doc = "Register `R4CFGR` reader"]
pub type R = crate::R<R4CFGR_SPEC>;
#[doc = "Register `R4CFGR` writer"]
pub type W = crate::W<R4CFGR_SPEC>;
#[doc = "Field `REG_EN` reader - region on-the-fly decryption enable Note: Garbage is decrypted if region context (version, key, nonce) is not valid when this bit is set."]
pub... |
use async_trait::async_trait;
use sc_client_api::AuxStore;
use sc_consensus_subspace::archiver::SegmentHeadersStore;
use subspace_archiving::archiver::is_piece_valid;
use subspace_core_primitives::crypto::kzg::Kzg;
use subspace_core_primitives::{Piece, PieceIndex};
use subspace_networking::libp2p::PeerId;
use subspace_... |
pub mod score;
pub mod utils;
pub mod align;
pub mod filter;
pub mod reference_library; |
#![no_std]
#![crate_type="lib"]
#![crate_name="startup"]
#![feature(lang_items, no_std, core, start)]
pub static NO_DEAD_CODE: u32 = 0;
#[macro_use]
extern crate core;
extern crate libc;
extern crate rlibc;
pub mod lang_items;
pub mod mem;
#[start]
#[lang = "start"]
fn start(main: *const u8, _argc: isize, _argv: *c... |
use ndarray::Array;
pub type NdArray = Array<f32, ndarray::IxDyn>;
pub trait MNISTModel {
fn new() -> Self;
fn train(&self);
fn validate(&self) -> f64;
fn load_model(&mut self) -> Result<(), std::io::Error>;
}
|
#[doc = r"Register block"]
#[repr(C)]
pub struct RegisterBlock {
#[doc = "0x00 - Control"]
pub ctl: CTL,
_reserved1: [u8; 4usize],
#[doc = "0x08 - RTC Read Write register"]
pub rtc_rw: RTC_RW,
#[doc = "0x0c - Oscillator calibration for absolute frequency"]
pub cal_ctl: CAL_CTL,
#[doc = "... |
#[doc = "Register `TDWR` writer"]
pub type W = crate::W<TDWR_SPEC>;
#[doc = "Field `TDB0` writer - 8-bit transmit data (earliest byte on I3C bus)"]
pub type TDB0_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 8, O>;
#[doc = "Field `TDB1` writer - 8-bit transmit data (next byte after TDB0\\[7:0\\]
on I3C bus)."]
... |
use hacspec_lib::prelude::*;
#[test]
fn test_byte_sequences() {
let msg = PublicByteSeq::from_hex("0388dace60b6a392f328c2b971b2fe78");
let msg_u32 =
PublicSeq::<u32>::from_native_slice(&[0x0388dace, 0x60b6a392, 0xf328c2b9, 0x71b2fe78]);
for i in 0..msg.num_chunks(4) {
let (l, chunk) = msg.c... |
use juniper;
use super::root::Context;
use crate::schema::users;
/// User
#[derive(Default, Debug, Queryable, Insertable)]
#[table_name = "users"]
pub struct User {
pub id: String,
pub name: String,
pub email: String,
}
#[derive(GraphQLInputObject)]
#[graphql(description = "User Input")]
pub struct UserI... |
#[macro_use]
extern crate lazy_static;
extern crate rustc_serialize;
mod config;
mod timeseries;
mod graphiteapi;
mod nagios;
fn main() {
let body = graphiteapi::http_fetch();
let mrl = timeseries::MetricResult::parse(body);
if mrl.len() == 0 {
println!("no such metric.");
nagios::exit(na... |
use super::super::file;
use std::path::PathBuf;
use std::process::Command;
const EXE_VARIABLE: &str = "{{EXE_PATH}}";
const LOG_VARIABLE: &str = "{{LOG_FILE_PATH}}";
const ERROR_LOG_VARIABLE: &str = "{{ERROR_LOG_FILE_PATH}}";
const PLIST_FILENAME: &str = "launch-port-snippet";
const PLIST_FILEPATH: &str = "~/Library/... |
use crate::{
num::{DurationExt, Natural, NaturalRatio, Real},
source::Source,
};
use std::time::Duration;
#[derive(Debug, Clone)]
pub struct LinearFadeOut<S>
where
S: Source,
{
inner: S,
channels: u16,
channel: u16,
step: Real,
curr_vol: Real,
final_vol: Real,
}
impl<S> Iterator fo... |
//! `amethyst` rendering ecs resources
use std::sync::Arc;
use crossbeam::sync::MsQueue;
use futures::{Async, Future, Poll};
use futures::sync::oneshot::{channel, Receiver, Sender};
use gfx::traits::Pod;
use renderer::{Error, Material, MaterialBuilder, Texture, TextureBuilder};
use renderer::Rgba;
use renderer::mesh:... |
fn main() {
basic();
number();
boolean();
char_and_string();
tuple();
instantiate();
}
fn basic() {
let mut a_number = 10;
let a_boolean = true;
println!("the number is {}", a_number);
a_number = 15;
println!("and now the number is {}", a_number);
let a_number = a_number * 2;
println!("The n... |
pub mod contract;
pub mod interface;
pub mod utils;
use super::primitive;
use super::network;
use super::mempool;
use super::blockchain;
use super::db;
|
use super::super::objects;
pub const TRUE: objects::Boolean = objects::Boolean { value: true };
pub const FALSE: objects::Boolean = objects::Boolean { value: false };
pub const NULL: objects::Null = objects::Null {};
|
#[doc = "Reader of register RCC_APB3RSTSETR"]
pub type R = crate::R<u32, super::RCC_APB3RSTSETR>;
#[doc = "Writer for register RCC_APB3RSTSETR"]
pub type W = crate::W<u32, super::RCC_APB3RSTSETR>;
#[doc = "Register RCC_APB3RSTSETR `reset()`'s with value 0"]
impl crate::ResetValue for super::RCC_APB3RSTSETR {
type T... |
use std::error::Error as StdError;
use std::fmt::{self, Display};
use serde::de::value::{MapDeserializer, SeqDeserializer};
use serde::de::{
Deserialize, DeserializeSeed, Deserializer, EnumAccess, Error as DeError, IntoDeserializer,
Unexpected, VariantAccess, Visitor,
};
use serde::forward_to_deserialize_any;
... |
// Copyright (c) The Starcoin Core Contributors
// SPDX-License-Identifier: Apache-2.0
use crate::{commands::*, sg_client_proxy::SGClientProxy};
/// Major command for block explorer operations.
pub struct BlockCommand {}
impl Command for BlockCommand {
fn get_aliases(&self) -> Vec<&'static str> {
vec!["b... |
use iron::mime;
use iron::prelude::*;
use iron::status;
use iron::AfterMiddleware;
use std::fs;
use std::path::Path;
const PAGE_404: &str = "<h2>404</h2><p>Content could not found</p>";
const PAGE_50X: &str =
"<h2>50x</h2><p>SERVICE is temporarily unavailable due an unexpected error</p>";
/// Custom Error pages m... |
use crate::helpers::*;
use proc_macro2::TokenStream;
use quote::quote;
use syn::parse_quote;
use syn::{Data, DeriveInput};
pub fn bounds_impl(mut input: DeriveInput) -> TokenStream {
let name = input.ident;
let path = quote!(rtk::geometry);
let mut generics_mut = input.generics.clone();
if let Err(err... |
extern crate libpasta;
use libpasta::rpassword::*;
struct User {
// ...
password_hash: String,
}
fn auth_user(user: &User) {
let password = prompt_password_stdout("Enter password:").unwrap();
if libpasta::verify_password(&user.password_hash, &password) {
println!("The password is correct!");
... |
use crate::prelude::*;
use azure_core::prelude::*;
use azure_core::{Request as HttpRequest, Response as HttpResponse};
use chrono::{DateTime, Utc};
#[derive(Debug, Clone)]
pub struct DeleteDocumentOptions<'a> {
if_match_condition: Option<IfMatchCondition<'a>>,
if_modified_since: Option<IfModifiedSince<'a>>,
... |
//! This module declares the low-level implentation of an instruction.
//!
//! Unlike `builder::Instr` which is supposed to accomodata all architectures,
//! this module emits platform-specific code.
#![allow(non_upper_case_globals)]
use std::fmt::{self, Display, Formatter};
use std::io::Write;
/// The size of a va... |
// Copyright 2019, 2020 Wingchain
//
// 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... |
/*
* Datadog API V1 Collection
*
* Collection of all Datadog Public endpoints.
*
* The version of the OpenAPI document: 1.0
* Contact: support@datadoghq.com
* Generated by: https://openapi-generator.tech
*/
/// DistributionWidgetDefinition : The Distribution visualization is another way of showing metrics aggr... |
//! The `thin_client` module is a client-side object that interfaces with
//! a server-side TPU. Client code should use this object instead of writing
//! messages to the network directly. The binary encoding of its messages are
//! unstable and may change in future releases.
use bincode::{deserialize, serialize};
us... |
use std::io;
fn main() {
println!("Please enter degrees in C°: ");
let mut cdegrees = String::new();
io::stdin().read_line(&mut cdegrees).expect("Failed to read line!");
let cdegrees: i32 = cdegrees.trim().parse().expect("Please enter a number!");
let mut fdegrees = (cdegrees * ... |
use std::net::{TcpListener, TcpStream};
use std::io::{Read, Write};
fn main() {
let host_ip = "127.0.0.1:3333";
let listener = TcpListener::bind(host_ip).unwrap();
println!("server running {}", host_ip);
for stream in listener.incoming() {
match stream {
Err(e) => { println!("Acce... |
use super::super::domain;
use super::super::repository;
pub fn index(page: i32, page_size: i32) -> (Vec<domain::designer::DomainDesigner>, i32) {
let repository_design = repository::designer::RepositoryDesigner::new();
let total = repository_design.find_designers_total(page_size);
let domain_designers = re... |
use decimal;
encoding_struct! {
/// Fee data for specific kind of operations.
struct Fee {
fixed: u64,
fraction: decimal::UFract64,
}
}
encoding_struct! {
/// Third party fee data, part of `AssetInfo`.
struct Fees {
trade: Fee,
exchange: Fee,
transfe... |
use crate::prelude::Address;
use crate::test_utils;
use crate::types::{Wei, ERC20_MINT_SELECTOR};
use secp256k1::SecretKey;
const INITIAL_BALANCE: Wei = Wei::new_u64(1000);
const INITIAL_NONCE: u64 = 0;
const TRANSFER_AMOUNT: Wei = Wei::new_u64(123);
/// Tests we can transfer Eth from one account to another and that ... |
use tokio::process::Command;
use anyhow::{Result, Context};
use async_trait::async_trait;
use crate::{
services::model::{Nameable, Ensurable, is_binary_present},
helpers::ExitStatusIntoUnit
};
static NAME: &str = "k9s";
#[derive(Default)]
pub struct K9s {}
impl Nameable for K9s {
fn name(... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.