text
stringlengths
8
4.13M
#![allow(dead_code)] use std::collections::BTreeSet; use std::collections::HashSet; use std::convert::AsRef; // Definition for singly-linked list. #[derive(PartialEq, Eq, Clone, Debug)] pub struct ListNode { pub val: i32, pub next: Option<Box<ListNode>>, } impl ListNode { #[inline] fn new(val: i32) -...
mod vector; mod matrix; #[cfg(test)] mod tests { #[allow(unused_imports)] use vector::*; #[allow(unused_imports)] use matrix::*; #[test] fn test_index() { let v2: Vec2f = Vec2f::new(1.0f32, 2.0f32); let v3: Vec3f = Vec3f::new(1.0f32, 2.0f32, 3.0f32); let v4: Vec4f = Ve...
use crate::location::Register; use crate::Address; /// A CFI directive and the function offset it applies to. /// /// Address::none() is used for directives that apply to the whole function. pub type Cfi = (Address, CfiDirective); /// A CFI directive. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum CfiDirective...
pub mod challenge_1; pub mod challenge_2; pub mod challenge_3; pub mod challenge_4; pub mod challenge_5; pub mod challenge_6; pub mod challenge_7; pub mod challenge_8;
fn take_order() {} fn serve_order() {} fn take_payment() {}
use futures_util::{stream::SplitSink, SinkExt, StreamExt}; use serde::{Deserialize, Serialize}; use std::{collections::HashMap, sync::Arc}; use tokio::{net::TcpStream, sync::Mutex, sync::RwLock}; use tokio_tungstenite::{tungstenite::protocol::Message, WebSocketStream}; use tungstenite::{ handshake::server::{Request...
pub mod field_element; pub mod point; pub mod s256_field; mod internal_macros;
pub fn array_sum(nbrs: &Vec<i32>) -> i32 { let sum: i32 = 0; let sum = nbrs.into_iter() .fold(sum, |acc, &x| acc + x); // println!("sum after = {}", &sum); return sum; }
use proc_macro as pm; use quote::quote; pub(crate) fn rewrite(_attr: syn::AttributeArgs, item: syn::ItemImpl) -> pm::TokenStream { use crate::new_id; let mut functions = Vec::new(); let ty_name = if let syn::Type::Path(x) = item.self_ty.as_ref() { &x.path.segments.last().unwrap().ident } else {...
/* Create a resource group, similar to: az group create --name $RESOURCE_GROUP_NAME --location $RESOURCE_GROUP_LOCATION export RESOURCE_GROUP_NAME=azuresdkforrust export RESOURCE_GROUP_LOCATION=southcentralus cargo run --package azure_mgmt_resources --example group_create */ use azure_identity::token_credentials::Azu...
use log::{debug, info, warn}; use std::{ net::{SocketAddr, TcpStream}, sync::{Arc, RwLock}, time::Duration, }; use crate::tonic_ext::{GenericCodec, GenericSvc}; use crate::MockBuilder; use rand::Rng; use tonic::{ codegen::{ http::{self, HeaderMap, HeaderValue, Method}, Body, Never, StdE...
/** * cargo new ep1 * cd C:\Users\むずでょ\OneDrive\ドキュメント\practice-rust\concurrency\ep1 * cargo build --example data-race-1 * cargo run --example data-race-1 * * [並行性](https://doc.rust-jp.rs/the-rust-programming-language-ja/1.6/book/concurrency.html) */ use std::thread; use std::time::Duration; fn main() { l...
// Copyright 2013-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...
//! `kdl` is a "document-oriented" parser and API for the [KDL Document //! Language](https://kdl.dev), a node-based, human-friendly configuration and //! serialization format. Unlike serde-based implementations, this crate //! preserves formatting when editing, as well as when inserting or changing //! values with cus...
use crate::core; use std::time; use friday_storage; use friday_logging; use std::sync::{RwLock, Arc}; use friday_error::{FridayError, propagate, frierr}; use ureq; use pnet; // Even if local IP has not changed we will ping remote with new // ip once a day in-case that server forgets us or restarts. static REFRESH_REMO...
use std::collections::HashMap; use std::hash::Hash; #[derive(Default, Debug, Clone)] pub struct Counter<T: Eq + Hash + Clone> { counts: HashMap<T, usize>, } impl<T: Clone + Eq + Hash> Counter<T> { pub fn new() -> Self { Self { counts: HashMap::new(), } } pub fn add(&mut se...
use super::floyd_warshall; #[test] fn test_no_intermediate() { use petgraph::Graph; let mut graph = Graph::new_undirected(); let a = graph.add_node(0); let b = graph.add_node(1); let c = graph.add_node(2); let d = graph.add_node(3); graph.extend_with_edges( &[ (a, b, 1...
extern crate argparse; extern crate ansi_term; extern crate rand; extern crate random_things; extern crate clipboard; use rand::{Rng}; use argparse::{ArgumentParser, StoreTrue, Store}; use ansi_term::Colour; use random_things::random_string; use clipboard::ClipboardContext; const MINIMUM_LENGTH:u32 = 10; struct Opti...
use macros::HelloMacro; use macros_derive::HelloMacro; #[derive(HelloMacro)] struct Pancakes; fn main() { Pancakes::hello_macro(); }
use irc::error::IrcError; #[derive(Debug)] pub enum Error { Irc(IrcError), } impl From<IrcError> for Error { fn from(err: IrcError) -> Self { Error::Irc(err) } }
#![allow(unused_variables)] //! 제네릭 (1) /// ### 에러메세지 /// /// 03.rs:2:16: 2:24 error: unable to infer enough type information about `_`; /// type annotations or generic parameter binding required [E0282] /// 03.rs:2 let list = Vec::new(); /// ^~~~~~~~ /// 03.rs:2:16: 2...
mod replace_space; mod reverse_left_words; pub fn main() { let default = 2; match default { //替换空字符串1 1 => replace_space::main(), 2 => reverse_left_words::main(), _ => {} } }
//! 负责分配 / 回收的数据结构 // 2021-3-12 /// 分配器:固定容量,每次分配 / 回收一个元素 pub trait Allocator { /// 给定容量,创建分配器 fn new(capacity: usize) -> Self; /// 分配一个元素,无法分配则返回 `None` fn alloc(&mut self) -> Option<usize>; /// 回收一个元素 fn dealloc(&mut self, index: usize); } // 栈式分配和线段树分配 algorithm/src/allocator mod stack...
use vulkano::format::{Format, ClearValue}; use vulkano::image::{Dimensions, StorageImage}; use vulkano::instance::{Instance, InstanceExtensions, PhysicalDevice}; use vulkano::device::{Device, DeviceExtensions, Features}; use vulkano::buffer::{BufferUsage, CpuAccessibleBuffer}; use vulkano::command_buffer::{AutoCommandB...
#[derive(Debug)] struct Rectangle { width: u32, height: u32 } impl Rectangle { fn create(width: u32, height: u32) -> Rectangle { Rectangle { width, height } } fn area(&self) -> u32 { self.width * self.height } fn wider(&self, rect: &Rectangle) -> bool { self.width...
use crate::packet_data::PacketData; use crate::packet_headers::PacketHeader; pub enum Layer2Type { NotSet = 0, Ipv4, Ipv6, Arp, } pub struct PacketInfo { pub headers: Vec<PacketHeader>, pub packet_data: PacketData, } impl PacketInfo { pub fn new() -> PacketInfo { PacketInfo { ...
#[doc = "Register `MPCBB1_VCTR10` reader"] pub type R = crate::R<MPCBB1_VCTR10_SPEC>; #[doc = "Register `MPCBB1_VCTR10` writer"] pub type W = crate::W<MPCBB1_VCTR10_SPEC>; #[doc = "Field `B320` reader - B320"] pub type B320_R = crate::BitReader; #[doc = "Field `B320` writer - B320"] pub type B320_W<'a, REG, const O: u8...
use aoc_utils::read_file; use day04::FIND_GUARD_REGEX; use day04::{Action, Guard, Time}; use std::collections::HashMap; fn main() { if let Ok(contents) = read_file("./input") { let mut guards: Vec<Guard> = contents .lines() .filter_map(|line| { if let Some(caps) = FI...
use crate::lib::canister_info::{CanisterInfo, CanisterInfoFactory}; use crate::lib::error::DfxResult; use anyhow::bail; use std::path::{Path, PathBuf}; pub struct AssetsCanisterInfo { input_root: PathBuf, source_paths: Vec<PathBuf>, output_wasm_path: PathBuf, output_idl_path: PathBuf, output_asse...
use franklin_crypto::bellman::Engine; #[derive(Debug, PartialEq, Eq)] pub enum HashFamily { Rescue, Poseidon, RescuePrime, } #[derive(Copy, Clone, Debug)] pub enum CustomGate { QuinticWidth4, QuinticWidth3, None, } #[derive(Clone, PartialEq, Eq)] pub enum Sbox { Alpha(u64), AlphaInvers...
use std::borrow::Cow; use std::marker; use std::ops::Bound; use crate::*; use super::{advance_key, retreat_key}; fn move_on_range_end<'txn>( cursor: &mut RoCursor<'txn>, end_bound: &Bound<Vec<u8>>, ) -> Result<Option<(&'txn [u8], &'txn [u8])>> { match end_bound { Bound::Included(end) => { ...
const b: usize = 4 / 2; const a: usize = 1 /// ok ;
pub mod grid; pub mod rules; pub mod solver; mod io;
pub mod lifetime_elision; pub mod scope;
use std::fmt; use std::ops::AddAssign; #[derive(Debug, Default)] pub struct Stats { pub num_nodes: usize, pub num_ways: usize, pub num_relations: usize, pub num_unresolved_node_ids: usize, pub num_unresolved_way_ids: usize, pub num_unresolved_rel_ids: usize, } impl AddAssign for Stats { #[...
#![feature(test)] extern crate test; extern crate byteio; extern crate byteorder; use test::black_box; #[bench] fn bench_byteio_vec(b: &mut test::Bencher) { use byteio::ReadBytesExt; let vec = vec![0u8; 1_000_000]; b.iter(|| { let data = black_box(&vec[..]); for mut val in data.chunks(2) {...
mod instruction; use self::instruction::{Instruction, OpCode}; use chip8::audio::{AudioEvent, AudioSink}; use chip8::keyboard::{HexKey, Keyboard}; use chip8::memory::Memory; use chip8::stack::Stack; use chip8::vram::{VideoSink, Vram}; use chip8::Address; use chip8::DWord; use rand::{thread_rng, Rng}; use std::fmt; pub...
// @lint-ignore LICENSELINT /* * MIT License * * Copyright (c) 2021 Daniel Prilik * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation th...
use crate::hex::render::{ area::AreaRenderer, area_edge::AreaEdgeRenderer, edge::EdgeRenderer, multi::MultiRenderer, square::{SquareRenderer, SquareScale}, tile::{HexScale, TileRenderer}, }; pub mod bumpy_builder; pub mod cellular; pub mod cubic_range_shape; pub mod custom; pub mod directions; ...
use std::fs::File; use std::io::Read; use std::path::Path; use std::error::Error; use de::deserialise; use node::StoryNode; use feed::StoryFeed; pub fn load_story(filepath: &str) -> Result<StoryFeed, String> { let path = Path::new(filepath); let display = path.display(); // Open file let mut file =...
#[doc = "Reader of register DATACNT"] pub type R = crate::R<u32, super::DATACNT>; #[doc = "Reader of field `DATACNT`"] pub type DATACNT_R = crate::R<u32, u32>; impl R { #[doc = "Bits 0:24 - Data count value"] #[inline(always)] pub fn datacnt(&self) -> DATACNT_R { DATACNT_R::new((self.bits & 0x01ff_f...
#[doc = "Reader of register REGION_BASE_LOW0"] pub type R = crate::R<u32, super::REGION_BASE_LOW0>; #[doc = "Reader of field `BASE_ADDRESS_LOW`"] pub type BASE_ADDRESS_LOW_R = crate::R<u32, u32>; impl R { #[doc = "Bits 12:31 - base address bits"] #[inline(always)] pub fn base_address_low(&self) -> BASE_ADDR...
use async_graphql::SimpleObject; use chrono::{DateTime, Utc}; use super::schema::configs; #[derive(Debug, Queryable, SimpleObject)] pub struct Config { pub id: i32, pub name: String, pub value: String, pub guild_id: i64, pub created_at: DateTime<Utc>, pub updated_at: DateTime<Utc>, } #[derive...
/// A collection of Expressions. struct Function { name: Option<String>, fields: Vec<Expression> } impl Function { fn new_function(name: &str, fields: Vec<Arc<Data>>) -> Function { Function { name: Some(name), fields: fields, } } fn new_lambda(fields: Vec<Ar...
#[doc = r"Register block"] #[repr(C)] pub struct BANK { #[doc = "0x00 - FLASH key register for bank 1"] pub keyr: KEYR, _reserved1: [u8; 0x04], #[doc = "0x08 - FLASH control register for bank 1"] pub cr: CR, #[doc = "0x0c - FLASH status register for bank 1"] pub sr: SR, #[doc = "0x10 - F...
use std::fs::File; use std::io::{BufRead, BufReader}; fn main() { let filename = "src/input"; // Open the file in read-only mode (ignoring errors). let file = File::open(filename).unwrap(); let reader = BufReader::new(file); let mut digits = Vec::new(); // Read the file line by line using the...
use bytes::{Buf, BufMut, Bytes, BytesMut}; use crate::utils::Writeable; #[derive(Debug, Copy, Clone, Eq, PartialEq)] pub struct Version { major: u16, minor: u16, } impl Default for Version { fn default() -> Version { Version { major: 1, minor: 0 } } } impl Writeable for Version { fn writ...
fn main() { unsafe { print_long_double() }; } extern "C" { fn print_long_double(); }
use syn::{Attribute, DataStruct, Error}; use syn::{NestedMeta, Result}; #[derive(Debug)] pub(crate) enum StructMemberLayout { C, Packed(u64), } /// Is the given Attribute a #[repr(...)] attribute? fn is_repr_attribute(attribute: &Attribute) -> bool { attribute .path .get_ident() .m...
#![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 StoragePoolOperationDisplay { pub provider: String, pub resource: String, pub operation: String, pu...
pub mod args; pub mod logging; pub mod subcommands; use clap::AppSettings; use color_eyre::{Report, Result}; static AFTER_HELP: &str = "Thank you for using Spideog. Please send any feedback, bug report or feature request to the project's github page: https://github.com/jeanmanguy/spideog"; #[derive(Debug, Clap)] #[c...
#[cfg(target_os = "windows")] extern crate winapi; #[macro_use] extern crate quickcheck; extern crate registry_pol; mod v1;
#[cfg(test)] #[path = "../../../tests/unit/solver/evolution/evolution_test.rs"] mod evolution_test; use crate::construction::heuristics::InsertionContext; use crate::solver::hyper::HyperHeuristic; use crate::solver::telemetry::Telemetry; use crate::solver::termination::*; use crate::solver::{Metrics, Population, Refin...
use core; use kalloc::{HEAP_SIZE, HEAP_START}; use super::frame_allocator::{frame_alloc, PAGE_SIZE}; pub const PTE_ADDR_MASK: usize = 0x000f_ffff_ffff_f000; pub const PT1_INDEX: usize = 0x1ff << (0 * 9 + 12); pub const PT2_INDEX: usize = 0x1ff << (1 * 9 + 12); pub const PT3_INDEX: usize = 0x1ff << (2 * 9 + 12); pub...
use serde::{Deserialize, Serialize}; use serde_json::Result; use std::time::{SystemTime, Instant}; #[derive(Serialize, Deserialize, Debug)] pub enum FileType { Free, File, Directory } #[derive(Serialize, Deserialize, Debug)] pub struct Inode { pub number: i128, pub typee: FileType, pub startBlock: i...
use crate::{ clap_handler::{ app::{GeneralOptions, PrimenetOptions}, p95_work::PrimenetWorkType, }, util::*, }; use regex::RegexBuilder; use reqwest::blocking::{Client, ClientBuilder}; use std::fs::{remove_file, File, OpenOptions}; use std::io::{BufWriter, Write}; use std::path::Path; use st...
//! Implements `StdTtable`. use libc; use libc::c_void; use std::sync::atomic::{AtomicUsize, Ordering}; use std::marker::PhantomData; use std::isize; use std::cell::Cell; use std::cmp::max; use std::mem; use ttable::*; use moves::MoveDigest; /// Represents a record in the transposition table. /// /// Consists of a t...
fn main() { println!("Hello, World!!"); another_func(10, 6); let x = 5; let y = { let x = 3; x + 1 //式は末尾に;がつかない //文は値を返さないが式は返す }; println!("The value of y is: {}", y); let z = five(); println!("The value of z is: {}", z); let mut number = 3; if number ...
use pcap::*; fn main() { let name = pcap_lookupdev().unwrap(); match pcap_open_live(&name, 1000, 1, 1000) { Ok(handle) => { while let res = pcap_next_ex(&handle) { match res { Ok(packet) => { println!("{:#?}", packet) ...
#[doc = "Register `DIR` reader"] pub type R = crate::R<DIR_SPEC>; #[doc = "Field `THI` reader - Threshold HIGH"] pub type THI_R = crate::FieldReader<u16>; #[doc = "Field `TLO` reader - Threshold LOW"] pub type TLO_R = crate::FieldReader<u16>; impl R { #[doc = "Bits 0:12 - Threshold HIGH"] #[inline(always)] ...
// use crate::layout::Layout; extern crate yewapp; use yewapp::pages::{webgpu::WebGPUPage, todo::TodoPage}; use yew::prelude::*; use yew_router::prelude::*; #[derive(Debug, Clone, Copy, PartialEq, Routable)] pub enum MyRoute { #[at("/")] Home, #[at("/web-gpu")] WebGpu, #[at("/todo")] Todo, #[not_found] ...
use std::io; use std::cmp::Ordering; use rand::Rng; use std::fmt; use std::fmt::Formatter; use std::collections::HashMap; use std::io::Read; fn _guessing_game(){ println!("Guess the number between 1 and 100"); let secret_number = rand::thread_rng().gen_range(1..101); loop{ println!("Please input ...
use demo; use http::StatusCode; use now_lambda::{error::NowError, lambda, IntoResponse, Request, Response}; use std::error::Error; fn main() -> Result<(), Box<dyn Error>> { Ok(lambda!(handler)) } fn handler(_request: Request) -> Result<impl IntoResponse, NowError> { let message = match demo::connect() { ...
// 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 // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in ...
use crate::{ Affine2, Affine3A, DAffine2, DAffine3, DMat2, DMat3, DMat4, DQuat, DVec2, DVec3, DVec4, I64Vec2, I64Vec3, I64Vec4, IVec2, IVec3, IVec4, Mat2, Mat3, Mat3A, Mat4, Quat, U64Vec2, U64Vec3, U64Vec4, UVec2, UVec3, UVec4, Vec2, Vec3, Vec3A, Vec4, }; use bytemuck::{AnyBitPattern, Pod, Zeroable}; unsaf...
mod qr; mod roms; mod transform; use embedded_graphics::{ geometry::Size, prelude::*, primitives::PrimitiveStyleBuilder, primitives::Rectangle, }; use embedded_hal::prelude::*; use epd_waveshare::color::OctColor; use epd_waveshare::graphics::OctDisplay; use epd_waveshare::{epd5in65f::*, prelude::*}; use rand::seq::...
// use std::io; use std::env; use std::io::{self, Write}; use rand::Rng; fn meme_text(text: String) -> String { let mut to_return: String = "".to_owned(); let mut rng = rand::thread_rng(); for i in 0..text.len() { let num: f32 = rng.gen::<f32>(); if num < 0.5 { to_return.push_st...
pub(crate) trait MakingList { /// generates a list from elements of any structure used. fn make_required_list(&self) -> Vec<&str>; }
pub mod rythme_flag; pub mod chord_name; pub mod inner_graphic; pub mod route_rect; pub mod whole_note_label;
use crate::custom_types::ASCII_COMMA; use crate::looping::{IterAttrs, IterResult, NativeIterator}; use crate::runtime::Runtime; use crate::std_type::Type; use crate::string_var::{MaybeString, StringVar}; use crate::variable::{FnResult, Variable}; use ascii::{AsciiChar, AsciiStr}; use once_cell::sync::Lazy; use std::cel...
extern crate hangeul; fn main() { // literally: pikachu transliterated let subject = "피카츄"; // Korean marks the topic of the sentence with a post position // particle: 이 follows consonants, and 가 follows vowels. let post_position = match hangeul::ends_in_consonant(subject).unwrap() { true ...
use std::ffi::CStr; use std::fmt; use std::os::raw::c_char; /* typedef struct APerson { const char * name; const char * long_name; } APerson ; APerson *get_person(const char * name, const char * long_name); void free_person(APerson *person); */ #[repr(C)] pub struct APerson { name: *const c_char, lo...
// #![feature(trait_alias)] use async_std::io; use async_std::task; use serde::{Deserialize, Serialize}; use tide::StatusCode; use tide_validator::{HttpField, ValidatorMiddleware}; #[derive(Deserialize, Serialize)] struct Cat { name: String, } fn main() -> io::Result<()> { task::block_on(async { let m...
use hacspec_dev::prelude::*; use hacspec_lib::prelude::*; use hacspec_aes::*; fn aes_128_enc_dec_test(m: &ByteSeq, key: Key128, iv: AesNonce, ctr: U32, ctxt: Option<&ByteSeq>) { let c = aes128_encrypt(key, iv, ctr, m); let m_dec = aes128_decrypt(key, iv, ctr, &c); assert_bytes_eq!(m, m_dec); if ctxt.i...
pub mod client; pub mod listener; pub mod status;
use std::fmt; use std::error; use reqwest::StatusCode; use reqwest::blocking::{Client, Body}; #[derive(Debug)] pub enum Error { WrongStatusCode } impl fmt::Display for Error { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "Wrong status code") } } impl error::Error for Error { fn source(&...
use crate::sqlite::database::SqliteDatabase; use apllodb_shared_components::DatabaseName; use glob::glob; /// Removes sqlite3 database file on drop(). /// /// Use this in "panic guard" pattern. #[derive(Debug)] pub struct SqliteDatabaseCleaner(DatabaseName); impl SqliteDatabaseCleaner { pub fn new(database_name: ...
use crate::features::syntax::StatementFeature; use crate::parse::visitor::tests::assert_no_stmt_feature; use crate::parse::visitor::tests::assert_stmt_feature; #[test] fn continue_no_label() { assert_stmt_feature( "function a() { return; }", StatementFeature::ReturnNothingStatem...
type TFoo<'a, A: 'a> = (&'a A, u64); struct SFoo<'a, A: 'a>(&'a A); struct SBar<'a, A: 'a> { x: &'a A } enum EFoo<'a, A: 'a> { X { x: &'a A }, Y { y: &'a A }, } struct SBaz<'a, 'b, A: 'a, B: 'b> { a: &'a A, b: &'b B, } trait TBaz<'a, 'b, A: 'a, B: 'b> { fn baz(&self); } impl<'a, 'b, A: 'a, B: 'b...
use serde::{Deserialize, Serialize}; use core::pos::{ BiPos, Position, }; pub mod hir; pub mod mir; #[repr(u8)] #[derive(Debug, Clone, PartialEq)] pub enum Constant<'a>{ Str(&'a str), Int(i32), Float(f32), Bool(bool), } use std::cell::RefCell; #[derive(Clone, Debug, Serialize, Deserialize)]...
use auto_impl::auto_impl; #[auto_impl(&)] trait Foo { #[auto_impl(keep_default_for(&))] type Foo; } fn main() {}
//! The updater pulls down the necessary data to populate the repository. The canonical repository //! is stored in git for its flexibility of version control. use config::Config; use std::env; use std::fs; use std::fs::Path; pub struct Updater { config: Config } impl Updater { pub fn new(config: Config) -> Updat...
use sdl2::{video::Window, render::Canvas}; use crate::{input::GameInput}; pub trait Scene { fn update(&mut self, inputs: Vec<GameInput>, t: u128, dt: f64); fn render(&mut self, canvas: &mut Canvas<Window>); }
//! Run a BuildLoop for `shell.nix`, watching for input file changes. //! Can be used together with `direnv`. use crate::daemon::Daemon; use crate::ops::error::{ok, OpResult}; use crate::socket::SocketPath; use slog_scope::info; /// See the documentation for lorri::cli::Command::Daemon for details. pub fn main() -> O...
use std::cmp::{max, Ordering}; use std::collections::{BinaryHeap, HashMap, HashSet}; use std::fmt; use std::fmt::Formatter; use crate::util::time; pub fn day16() { println!("== Day 16 =="); let input = "src/day16/input.txt"; time(part_a, input, "A"); time(part_b, input, "B"); } #[derive(Copy, Clone, ...
use http::{HeaderMap, Uri}; use http::header::HeaderValue; use http::header::{ACCESS_CONTROL_ALLOW_ORIGIN, CONTENT_TYPE}; use hyper::{Body, Request as HyperRequest, Response as HyperResponse}; use hyper::rt::{Future, Stream}; use pact_matching::models::{OptionalBody, Request, Response, HttpPart}; use pact_matching::mod...
#[macro_use] extern crate log; use azure_core::prelude::*; use azure_storage::core::prelude::*; use azure_storage::queue::prelude::*; use std::collections::HashMap; use std::error::Error; #[tokio::main] async fn main() -> Result<(), Box<dyn Error>> { // First we retrieve the account name and master key from enviro...
#![no_main] use libfuzzer_sys::fuzz_target; pub use tf_demo_parser::{Demo, DemoParser, Parse, ParseError, ParserState, Stream}; fn fuzz(data: &[u8]) { let demo = Demo::new(data); let parser = DemoParser::new_all(demo.get_stream()); let _ = parser.parse(); } fuzz_target!(|data: &[u8]| { fuzz(data) });
//! `rust-peg` is a simple yet flexible parser generator based on the [Parsing Expression //! Grammar][wikipedia-peg] formalism. It provides the `parser!{}` macro that builds a recursive //! descent parser from a concise definition of the grammar. //! //! [wikipedia-peg]: https://en.wikipedia.org/wiki/Parsing_expressio...
use std::fs; use std::collections::HashMap; fn get_positions(wire: Vec<&str>) -> HashMap<(isize, isize), usize> { let mut last = (0, 0); let mut step = 0; let mut positions = HashMap::new(); for (idx,direction) in wire.iter().enumerate() { let (dir, dist) = direction.split_at(1); let di...
fn iterators() { let scores = vec![100, 90, 85]; for score in &scores { println!("score: {}", score); } for score in scores { println!("score: {}", score); } //for i in 0..10 { // println!("{}", i); //} // //for i in (0..=10).map(|x| x * 2) { // prin...
fn main(){ // very typical if-elseastatements. We dont need to put the boolean // in parenthesises though. // if 3 > 2 { println!("Branch1A"); } else if 4 > 3 { println!("Branch2A"); } else { println!("Branch3A"); } if 2 > 2 { println!("Branch1B"); } ...
pub mod vector; pub mod matrix; const EPSILON: f32 = 0.00001; /// Clamps a float value between [min, max] pub fn clamp(value: f32, min: f32, max: f32) -> f32 { if value > max { max } else if value < min { min } else { value } } /// Clamps a float value between [0.0, 1.0] pub ...
pub mod pieces; /* use std::clone::Clone; use self::bitboard::BitBoard; use color::Color; use shape::Shape; use pieces; use point::Point; use direction::Direction; use piece::Orientation; use corner::Corner; use rand; #[derive(Default)] pub struct Board { pub occupied: [BitBoard; 4], pub auras: [BitBoard; 4],...
#[macro_use] extern crate actix_web; use actix_cors::Cors; use actix_files as fs; use actix_session::Session; use std::{env, io}; use actix_web::http::StatusCode; use actix_web::{middleware, web, App, HttpRequest, HttpResponse, HttpServer, Result}; mod city_list; use city_list::get_city_list; mod search_city_list; ...
#[doc = "Register `FDCAN_TDCR` reader"] pub type R = crate::R<FDCAN_TDCR_SPEC>; #[doc = "Field `TDCF` reader - Transmitter Delay Compensation Filter Window Length"] pub type TDCF_R = crate::FieldReader; #[doc = "Field `TDCO` reader - Transmitter Delay Compensation Offset"] pub type TDCO_R = crate::FieldReader; impl R {...
use structopt::StructOpt; use airhobot::prelude::*; use std::{ path::PathBuf, }; #[derive(StructOpt, Debug)] #[structopt(name = "AirHoBot")] pub struct Args { /// Use the cam with the given id as input source #[structopt(short, long, conflicts_with = "image")] pub cam_id: Option<i32>, /// Use the ...
use serde::{Deserialize, Serialize}; use serde_with::skip_serializing_none; /// Use this method to specify a url and receive incoming updates via an outgoing webhook. Whenever there is an update for the bot, we will send an HTTPS POST request to the specified url, containing a JSON-serialized Update. In case of an uns...
mod util; pub mod asset; pub mod data_backend;
#[doc = "Register `CTR` reader"] pub type R = crate::R<CTR_SPEC>; #[doc = "Field `_IminLine` reader - IminLine"] pub type _IMIN_LINE_R = crate::FieldReader; #[doc = "Field `DMinLine` reader - DMinLine"] pub type DMIN_LINE_R = crate::FieldReader; #[doc = "Field `ERG` reader - ERG"] pub type ERG_R = crate::FieldReader; #...