text
stringlengths
8
4.13M
//! This module is used to find three way merges use crate::git_utils; use std::collections::HashSet; /// Walks through commits, looking for those with (exactly) two parents. Collects parents and /// the common base. pub fn find_merges( repo: &git2::Repository, revwalk: git2::Revwalk, before: Option<i64>,...
mod crypto; mod event; mod message; mod session; mod stream; pub use self::crypto::{read_rmux_event, write_encrypt_event, CryptoContext}; pub use self::event::{new_auth_event, Event, FLAG_AUTH}; pub use self::message::{AuthRequest, AuthResponse}; pub use self::session::{ create_stream, dump_session_state, get_chan...
use super::{ builders::{DeleteBuilder, ParamsBuilder}, TypeAttrs, }; use darling::util::SpannedValue; use proc_macro2::{Span, TokenStream}; use quote::{quote, ToTokens, TokenStreamExt as _}; use std::marker::PhantomData; use syn::LitInt; pub(super) struct Delete<'a, S> { attrs: &'a TypeAttrs, _s: Phant...
#[doc = "Reader of register DDRPHYC_DTPR0"] pub type R = crate::R<u32, super::DDRPHYC_DTPR0>; #[doc = "Writer for register DDRPHYC_DTPR0"] pub type W = crate::W<u32, super::DDRPHYC_DTPR0>; #[doc = "Register DDRPHYC_DTPR0 `reset()`'s with value 0x3012_666e"] impl crate::ResetValue for super::DDRPHYC_DTPR0 { type Typ...
fn main() { let x = { // 最终 x 是 (), 空的 tup 3; 2; // 分号则不是 表达式, 错误 }; println!("{:?}", x); }
#[cfg(test)] mod cli { use assert_cmd::prelude::*; use predicates::prelude::*; use std::io::Write; use std::process::Command; #[test] fn should_read_input_file_when_provided() { let mut cmd = Command::main_binary().unwrap(); let mut tmp_file = tempfile::NamedTempFile::new().unw...
use basespace_dl::util; use basespace_dl::workspace::Workspace; use clap::{App, Arg, ArgMatches}; use console::style; use failure::bail; use failure::ResultExt; use futures::future; use log::{info, warn}; use regex::Regex; use std::collections::HashSet; use std::fs::File; use std::io::{Read, Write}; use std::path::Path...
use anyhow::{format_err, Error}; use std::path::Path; use url::Url; use crate::{ file_info::{FileInfo, FileInfoTrait, FileStat, Md5Sum, ServiceId, ServiceSession, Sha1Sum}, file_service::FileService, }; #[derive(Debug, Clone)] pub struct FileInfoSSH(pub FileInfo); impl FileInfoSSH { /// # Errors /// ...
use std::io::{Error, ErrorKind, Result, Write}; #[macro_export] macro_rules! row { ($( $x:expr ),*) => { { let mut row = Row::new(); $(row.add_cell($x);)* row } }; } #[macro_export] macro_rules! blank { ($x:expr) => {{ CellValue::Blank($x) }}...
// Copyright 2020 ChainSafe Systems // SPDX-License-Identifier: Apache-2.0, MIT mod actor_code; pub use self::actor_code::*; use address::Address; use cid::Cid; use clock::ChainEpoch; use commcid::{cid_to_data_commitment_v1, cid_to_replica_commitment_v1, data_commitment_v1_to_cid}; use crypto::{DomainSeparationTag, ...
pub use mutable::FnStackMut; pub use once::FnStackOnce; pub use raw::FnBox; pub use reference::FnStackRef; use std::mem::{align_of, size_of, uninitialized}; mod mutable; mod once; mod raw; mod reference; mod private { pub struct Private; } pub trait Array: Sized { fn align() -> usize { align_of::<Se...
// MIT License // // Copyright (c) 2021 Miguel Peláez // // 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 the rights // to use, copy, modif...
use crate::common::*; pub(crate) trait Error: Display { fn code(&self) -> i32 { EXIT_FAILURE } }
mod counter; use counter::*; use ini::Ini; use std::process::abort; fn main() { let mut key = String::new(); let file = Ini::load_from_file("input.ini").unwrap(); let mut input_name = String::new(); let mut mode = String::new(); for (sec, prop) in file.iter() { for (k, v) in prop.iter() { ...
#[macro_use] extern crate cycle_match; #[test] fn loop_match() { let data = b"123456789"; let mut num = 0usize; let mut iter = data.iter(); loop_match!((iter.next()) -> || { Some(b'0') => {}, Some(a @ b'1' ..= b'9') => { num *= 10; num += (a - b'0') as usize; }, Some(a) => panic!("Unk byte: {:?}...
use std::fs; use day_10::process_part1; fn main() { let input = fs::read_to_string("input.txt").unwrap(); println!("{}", process_part1(&input)); }
pub mod datasource; pub mod stream; pub mod types;
use std::{fs, collections::BTreeSet}; fn main() { let input = fs::read_to_string("./input.txt").unwrap_or_default(); let mut unique_houses: BTreeSet<(i32, i32)> = BTreeSet::new(); let mut x = 0; let mut y = 0; for direction in input.chars() { match direction { '^' => y -= 1, ...
fn hofq(q: &mut Vec<u32>, x : u32) -> u32 { let cur_len=q.len()-1; let i=x as usize; if i>cur_len { // extend storage q.reserve(i+1); for j in (cur_len+1)..(i+1) { let qj=(q[j-q[j-1] as usize]+q[j-q[j-2] as usize]) as u32; q.push(qj); } } q[i] ...
#[macro_use] extern crate simple_error; pub mod expr; pub mod lexer; pub mod parser; pub mod truth_table; pub fn eval_str(input: String) -> String { let parsed = match parser::parse_str(&input) { Ok(parsed) => parsed, Err(err) => { return format!("invalid: {}\n", err); } };...
use std::fs::File; use std::io::Read; #[derive(Debug)] pub struct Parser { lines: Vec<String>, idx: usize, } #[derive(Debug, Eq, PartialEq)] pub enum CommandType { CArithmetic(String), CPush(String, usize), CPop(String, usize), CLabel, CGoto, CIf, CFunction(String, usize), CRet...
#[doc = "Register `ATOR` reader"] pub type R = crate::R<ATOR_SPEC>; #[doc = "Field `PRNG` reader - Pseudo-random generator value This field provides the values of the PRNG output. Because of potential inconsistencies due to synchronization delays, PRNG must be read at least twice. The read value is correct if it is equ...
#[macro_use] extern crate glium; extern crate clock_ticks; use glium::Surface; use glium::glutin; fn main() { use glium::DisplayBuild; let display = glutin::WindowBuilder::new() .build_glium() .unwrap(); let frames = 60 * 5; let trials = 3; for _ in 0.. trials { let star...
use super::error::*; use ffi::cudart::*; use std::mem::size_of; use std::ops::{Deref, DerefMut, Index, IndexMut}; use std::os::raw::*; use std::ptr::null_mut; use std::slice::{from_raw_parts, from_raw_parts_mut}; #[derive(Debug)] pub struct DVec<T> { ptr: *mut T, n: usize, } impl<T> DVec<T> { pub unsafe ...
use std::sync::Arc; use crate::{ util::{constants::GENERAL_ISSUE, MessageExt}, BotResult, CommandData, Context, MessageBuilder, }; use super::BgGameState; #[command] #[short_desc("Increase the size of the image")] #[aliases("b", "enhance")] #[bucket("bg_bigger")] pub(super) async fn bigger(ctx: Arc<Context>,...
use crate::parser_module::*; /** * Translates VM commands into Hack assembly code. */ pub struct CodeWriter { index: usize, commands: Vec<String>, } impl CodeWriter { pub fn new() -> CodeWriter { CodeWriter { index: 0, commands: Vec::new(), } } pub fn com...
use crate::{ composite_renderer::{Command, Image}, sprite_sheet_asset_protocol::SpriteSheetAsset, }; use core::{ assets::{ asset::{Asset, AssetId}, database::AssetsDatabase, protocol::{AssetLoadResult, AssetProtocol, AssetVariant, Meta}, }, Ignite, Scalar, }; use serde::{Dese...
use super::field_table::{FieldTableEntry, FieldTableType}; pub struct DeviceInfoTable { table: FieldTableType } impl FieldTableEntry for DeviceInfoTable { fn get(&self, key: i32) -> String { let result = self.table.get(&key); match result { Some(r) => r.clone(), // Non...
fn main() { // To create a new, empty vector, we can call the `Vec::new()` function. // let v: Vec<i32> = Vec::new(); // It’s more common to create a `Vec<T>` that has initial values, and Rust provides the `vec!` macro for convenience. { let _v = vec![1, 2, 3, 4]; } // <- v goes out of scop...
#[doc = "Reader of register FMC_BCHISR"] pub type R = crate::R<u32, super::FMC_BCHISR>; #[doc = "Reader of field `DUEF`"] pub type DUEF_R = crate::R<bool, bool>; #[doc = "Reader of field `DERF`"] pub type DERF_R = crate::R<bool, bool>; #[doc = "Reader of field `DEFF`"] pub type DEFF_R = crate::R<bool, bool>; #[doc = "R...
//個人的に行列はglmのオーダーがいい。glamはglmと違うっぽい? //
use std::io; pub fn question4() { println!("Hello, world!"); println!("Enter Radius Of Circle?"); let mut number1 = String::new(); io::stdin().read_line(&mut number1) .expect("Failed to read line"); let number1: f64 = number1.trim().parse() .expect("Please type a number!"...
use average::*; use average::{Max, Min, Variance}; use serde; use serde::ser::{SerializeStruct}; pub struct Stats { min: Min, max: Max, var: Variance, } impl Stats { fn new() -> Stats { Stats { min: Min::default(), max: Max::default(), var: Variance::default...
use std::collections::HashMap; use std::i32; use std::sync::{Arc, RwLock}; use lazy_static::lazy_static; use rusttype::{point, Error, Font, Scale, SharedBytes}; use font_loader::system_fonts; use font_loader::system_fonts::FontPropertyBuilder; use super::{FontData, FontFamily, FontTransform, LayoutBox}; type FontRe...
#[doc = "Reader of register CTL"] pub type R = crate::R<u32, super::CTL>; #[doc = "Writer for register CTL"] pub type W = crate::W<u32, super::CTL>; #[doc = "Register CTL `reset()`'s with value 0x0002_0808"] impl crate::ResetValue for super::CTL { type Type = u32; #[inline(always)] fn reset_value() -> Self:...
use std::{marker::PhantomData, ops::Index}; use crate::{Dim, Matrix}; /// A view into (slice of) a matrix. Or, a reference to a matrix. /// /// Any view should consist of a refernce to a matrix, and little more. /// It must be cheap to copy. /// # Examples pub trait View<'a>: Sized + Copy where Self: Index<usize,...
extern crate crypto; extern crate time; #[macro_use] extern crate serde_derive; extern crate serde; pub mod blockchain { use std::sync::RwLock; use std::fmt; use crypto::digest::Digest; use crypto::sha2::Sha256; use time; #[derive(Debug)] pub enum BlockchainError { InvalidBlockcha...
use crate::{bson::Document, event, test::Matchable}; use bson::Bson; use serde::Deserialize; #[derive(Debug, Deserialize)] #[serde(deny_unknown_fields)] pub struct CommandStartedEvent { command_name: Option<String>, database_name: Option<String>, command: Document, } impl CommandStartedEvent { pub fn ...
use crate::prelude::*; /// Utility struct to allow storing child expressions of binary expressions /// continuously in memory while having a name `lhs` and `rhs` to refer to them /// for improved usability. /// /// All binary expressions should strive to use this utility to store their /// child expressions. #[derive...
// Copyright 2020 Xavier Gillard // // 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 the rights to // use, copy, modify, merge, publish, di...
#[macro_export] macro_rules! add_css_provider { ($provider:expr, $($widget:expr),*) => ( { $( $widget .get_style_context() .add_provider($provider, gtk::STYLE_PROVIDER_PRIORITY_APPLICATION); )* ...
use serde::{Deserialize, Serialize }; #[derive(Serialize, Deserialize, Debug)] pub struct HeaderDoc{ #[serde(rename = "_id")] pub id: String, #[serde(rename = "delete_key")] pub delete_key: String, #[serde(rename = "content_type")] pub content_type: String, #[serde(rename = "file_extension"...
// Std use std::env; // Crates use anyhow::{Context, Result}; use dotenv::dotenv; use sqlx::sqlite::{SqlitePool, SqliteQueryAs}; use crate::{Entry, Project}; pub async fn setup_db(pool: &SqlitePool) -> Result<()> { sqlx::query!( "CREATE TABLE IF NOT EXISTS entries ( id INTEGER PRIMARY KEY, ...
extern crate exact_cover; use exact_cover::{Problem}; use exact_cover::{Solver}; #[test] fn solve_problem() { let mut p = Problem::new(); p.add_action(0, &[0, 1, 2]); p.add_action(1, &[3, 4]); p.add_action(2, &[2, 4]); let solver = Solver::new(p); assert!(solver.first_solution().is_some()); }...
pub fn server_ui(){ } pub fn server_logic(){ }
use skiplist::skiplist::SkipList; use crate::change::Change; pub type Range = std::ops::Range<usize>; /// Bitfield instance. #[derive(Debug)] pub struct Bitfield { /// A [skiplist] instance. /// /// [skiplist]: https://docs.rs/skiplist/ skiplist: SkipList<Range>, } impl Bitfield { /// Create a n...
use crate::vec3::{Vec3, Point3}; use crate::ray::{Ray}; pub struct Camera { pub origin: Point3, pub lower_left_corner: Point3, pub horizontal: Vec3, pub vertical: Vec3, } impl Camera { pub fn new() -> Camera { const ASPECT_RATIO: f64 = 16.0 / 9.0; let viewport_height: f64 = 2.0; ...
use metro::Event; fn main() { let events = [ Event::station(0, "Station 1"), Event::station(0, "Station 2"), Event::station(0, "Station 3"), Event::SplitTrack(0, 1), Event::station(1, "Station 4"), Event::SplitTrack(1, 2), Event::station(1, "Station 5"), ...
use ComponentBitField; use chunk::Chunk; use component_group::ComponentGroup; use component_group::UnsafeSendablePointer; use entity::Entity; use rayon::prelude::*; use std::collections::HashMap; use worker::Connection; use worker::schema::GeneratedSchema; use world::PartialEntity; use world::WorldTime; /// A view int...
// Copyright 2020 Datafuse Labs. // // 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 super::VhdError; use crate::prelude::*; use rdisk_shared::AsByteSlice; pub struct Bat { entries: Vec<u32>, } pub const UNUSED_BLOCK_ID: u32 = 0xFFFF_FFFF; impl Bat { pub fn new(entries_count: u32) -> Self { Self { entries: vec![0xFF_FF_FF_FF; entries_count as usize], } } ...
use bevy::input::mouse::MouseMotion; use bevy::prelude::*; use bevy::utils::HashSet; use bevy::{input::{Axis, Input}}; #[derive(Default)] pub struct GamepadLobby { gamepads: HashSet<Gamepad>, } pub fn gamepad_connection_system( mut lobby: ResMut<GamepadLobby>, mut gamepad_event: EventReader<GamepadEvent...
extern crate sdl2; use sdl2::image::LoadTexture; use sdl2::pixels::Color; use sdl2::rect::Rect; mod vector; mod display; mod sprite; pub fn main() -> Result<(), String> { let mut display = display::Display::new("Salut", 800, 800); let texture = display.load_texture("robot.jpg"); let mut sprite = sprite:...
#[macro_use] extern crate log; extern crate env_logger; extern crate rulinalg; mod gaussian; use rulinalg::matrix::{Matrix, BaseMatrix}; use rulinalg::utils; use std::io; fn main() { env_logger::init().unwrap(); // Read count of train elements and count of features. println!("Input count of train eleme...
mod flow_description; mod utils; mod work_description; mod work_target; pub use self::flow_description::*; pub use self::utils::*; pub use self::work_description::*; pub use self::work_target::*;
// structs1.rs // Address all the TODOs to make the tests pass! // I AM DONE struct ColorClassicStruct { color_name: String, color_type: String, // TODO: Something goes here } struct ColorTupleStruct(/* TODO: Something goes here */ String, String); #[derive(Debug)] struct UnitStruct; #[cfg(test)] mod t...
use crate::crypto::hash::H256; use bigint::uint::U256; const AVG_TX_SIZE: u32 = 168; // average size of a transaction (in Bytes) const PROPOSER_TX_REF_HEADROOM: f32 = 10.0; const SORTITION_PRECISION: u64 = std::u64::MAX; const DECONFIRM_HEADROOM: f32 = 1.05; // Chain IDs pub const PROPOSER_INDEX: u16 = 0; pub const T...
// An attribute to hide warnings for unused code. #![allow(dead_code)] // enum with implicit discriminator (starts at 0) enum Number { Zero, One, Two, Eleven = 'a', } fn main() { // `enums` can be cast as integers. println!("zero is {}", Number::Zero as i32); println!("one is {}", Number::...
use specs::prelude::*; pub mod baseline_benches; pub mod legion_benches; pub mod legion_parallel; pub mod specs_benches; pub mod specs_parallel; #[derive(Component, Copy, Clone, Debug, Default)] #[storage(VecStorage)] pub struct A(u32); #[derive(Component, Copy, Clone, Debug, Default)] #[storage(VecStorage)] pub str...
use std::collections::HashMap; pub fn nucleotide_counts(s: &str) -> HashMap<char, usize> { s.to_string().chars() .fold("ATCG".chars().map(|c| (c, 0)).collect::<HashMap<_,_>>(), |mut m, c| { *m.entry(c).or_insert(0) += 1; m }) } pub fn count(c: char,...
use azure_core::Context; use azure_cosmos::prelude::*; use futures::stream::StreamExt; use std::error::Error; #[tokio::main] async fn main() -> Result<(), Box<dyn Error + Send + Sync>> { // First we retrieve the account name and master key from environment variables. // We expect master keys (ie, not resource ...
use crate::{ArgMatchesExt, Result}; use clap::{App, Arg, ArgMatches}; use ronor::Sonos; pub const NAME: &str = "get-playlist"; pub fn build() -> App<'static, 'static> { App::new(NAME) .about("Get list of tracks contained in a playlist") .arg(crate::household_arg()) .arg(Arg::with_name("PLAYLIST").requir...
#[doc = r"Register block"] #[repr(C)] pub struct RegisterBlock { #[doc = "0x00 - LPCOMP Configuration Register"] pub config: CONFIG, #[doc = "0x04 - LPCOMP Status Register"] pub status: STATUS, _reserved2: [u8; 8usize], #[doc = "0x10 - LPCOMP Interrupt request register"] pub intr: INTR, ...
use piston_window::{rectangle, Context, G2d}; use piston_window::types::Color; const BLOCK_SIZE: f64 = 25.0; pub fn to_coord(game_coord: i32) -> f64 { game_coord as f64 * BLOCK_SIZE } pub fn draw_block(c: Color, game_x: i32, game_y: i32, con: &Context, g: &mut G2d) { let gui_x = to_coord(game_x); let gui...
//! Cargo registry macos keychain credential process. use cargo_credential::{Credential, Error}; use security_framework::os::macos::keychain::SecKeychain; struct MacKeychain; /// The account name is not used. const ACCOUNT: &'static str = ""; fn registry(registry_name: &str) -> String { format!("cargo-registry:...
#![recursion_limit = "256"] #[macro_use] extern crate quote; extern crate crc16; extern crate xml; mod binder; mod parser; mod util; use crate::util::to_module_name; use std::env; use std::fs::{read_dir, File}; use std::path::{Path, PathBuf}; use std::process::Command; pub fn main() { let src_dir = Path::new(en...
use actix_files::NamedFile; use actix_web::{error, web, App, HttpRequest, HttpServer, Result}; use std::path::PathBuf; async fn index() -> Result<NamedFile> { find_file("index.html").await } async fn static_file(name: HttpRequest) -> Result<NamedFile> { find_file(&name.path()[1..]).await } async fn find_fil...
#![allow(non_camel_case_types)] use libc::{c_char, c_int, c_void}; use std::ffi::{CStr, CString}; pub const FLB_ERROR: u32 = 0; pub const FLB_OK: u32 = 1; pub const FLB_RETRY: u32 = 2; pub const FLB_PROXY_OUTPUT_PLUGIN: u32 = 2; pub const FLB_PROXY_GOLANG: u32 = 11; #[repr(C)] #[derive(Debug, Copy, Clone)] pub struct...
// Copyright 2013-2017, The Gtk-rs Project Developers. // See the COPYRIGHT file at the top-level directory of this distribution. // Licensed under the MIT license, see the LICENSE file or <http://opensource.org/licenses/MIT> use Cancellable; use Error; use ffi; use glib::object::IsA; use glib::translate::*; use glib...
pub fn get<UD>(in_: &crate::base::In<UD>) -> Result<crate::Response, crate::Error> where UD: crate::UserData, { if !crate::base::is_test() { return Err(crate::Error::PageNotFound { message: "server not running in test mode".to_string(), }); } Ok(crate::Response::Http( ...
use std::fmt; #[derive(Clone, Ord, PartialOrd, Eq, PartialEq)] /// A simple UUID (v4) implementation. /// /// Rather than using the `uuid` crate, tycho has it's own implementation of uuids /// for better handling between serde and elements. /// /// pub struct Uuid(u128); impl Uuid { /// Create a new uuid (any ver...
fn comp(a: Vec<i64>, b: Vec<i64>) -> bool { let mut tab_a = a; let mut tab_b = b; //if tab_b.len() != tab_a.len() { return false } for i in 0..tab_a.len() { tab_a[i] = tab_a[i]*tab_a[i]; } tab_a.sort(); tab_b.sort(); tab_a == tab_b } #[test] fn test0() { assert_eq!(...
use std::time::Duration; use Sample; pub use self::amplify::Amplify; pub use self::buffered::Buffered; pub use self::delay::Delay; pub use self::fadein::FadeIn; pub use self::mix::Mix; pub use self::repeat::Repeat; pub use self::sine::SineWave; pub use self::speed::Speed; pub use self::take::TakeDuration; pub use sel...
use crate::utils::{ build_block, build_block_transactions, build_compact_block, build_compact_block_with_prefilled, build_header, build_headers, clear_messages, wait_until, }; use crate::{Net, Spec, TestProtocol, DEFAULT_TX_PROPOSAL_WINDOW}; use ckb_dao::DaoCalculator; use ckb_sync::NetworkProtocol; use ckb_tes...
pub fn exp(x: f64) -> f64 { const MAX_ITER: i32 = 200; let mut sum = 1.0; let mut term = 1.0; for n in 1..MAX_ITER { term *= x / n as f64; sum += term; }; return sum } fn probe_func_sec(x: f64, y: f64) -> f64 { return 2.0 * x.cos() / (1.0 - (x.sin().powi(2)) * (y.cos().powi(2...
use serde::{Serialize, Deserialize}; use warp::{reject, Reply, Rejection}; use super::errors::ErrorVariant; #[derive(Deserialize)] pub struct UserParams { pub email: String, pub password: String } #[derive(Serialize)] pub struct AuthInfo { pub token: String } #[derive(Serialize)] pub struct ErrorResponse { ...
use chip8::Address; use std::fmt; const FRAME_COUNT: usize = 16; pub struct Stack { frames: [u16; FRAME_COUNT], sp: u8, } impl fmt::Debug for Stack { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "[sp] {}", self.sp)?; write!( f, " [top] {:04x}", ...
use chrono::Duration; use drogue_cloud_database_common::{ models::outbox::{OutboxAccessor, OutboxEntry, PostgresOutboxAccessor}, utils::millis_since_epoch, Client, }; use drogue_cloud_test_common::{client, db}; use futures::TryStreamExt; use log::LevelFilter; use serial_test::serial; use tokio_postgres::NoT...
struct JSJIT(u64); enum JSJITorExpr { Jit { label: JSJIT }, Expr { expr: Box<JSExpr> } } enum JSExpr { Integer { value: u64 }, String { value: String }, OperatorAdd { lexpr: Box<JSJITorExpr>, rexpr: Box<JSJITorExpr> }, OperatorMul { lexpr: Box<JSJITorExpr>, rexpr: Box<JSJITorExpr> } } fn jump(l: J...
use crate::zx::constants::{ATTR_BASE_REL, ATTR_COLS, ATTR_MAX_REL, CANVAS_HEIGHT}; /// Encode line number to read memory address pub fn bitmap_line_addr(line: usize) -> u16 { assert!(line < CANVAS_HEIGHT); // 0 1 0 Y7 Y6 Y2 Y1 Y0 | Y5 Y4 Y3 X4 X3 X2 X1 X0 (0x4000 | (line << 5) & 0x1800 | (line << 8) & 0x07...
use eyre::Error; use std::fmt::Display; use rust_decimal::Decimal; use serde::{Deserialize, Serialize}; use serde_json; const DARKSKY_FORECAST_URL: &str = "https://api.darksky.net/forecast/"; type UnixTime = u64; type Temperature = f32; type Bearing = u16; type Speed = f32; type UvIndex = u8; type CloudCover = f32; ...
use crate::libs::skyway::{MeshRoom, Peer}; use js_sys::Promise; use std::rc::Rc; use wasm_bindgen::prelude::*; use wasm_bindgen::JsCast; use wasm_bindgen_futures::JsFuture; pub async fn close_room_connection(room: Rc<MeshRoom>) { let _ = JsFuture::from(Promise::new({ let room = Rc::clone(&room); &m...
use std::collections::HashMap; use std::f64; /* Symbol frequency. */ pub static mut SYMBOL : Vec<char> = Vec::new(); pub fn seq_weight( seq_list : &Vec<String>, site_list : &Vec<String>, arg_w : &String ) -> Vec<f64> { /* Amino acid list for Position-Based mothod. */ unsafe { SYMBOL = "ARNDCQEGHILKMFPSTWYV-".chars...
#[doc = r"Register block"] #[repr(C)] pub struct RegisterBlock { #[doc = "0x00 - Processor core identifier\\n Value is 0 when read from processor core 0, and 1 when read from processor core 1."] pub cpuid: CPUID, #[doc = "0x04 - Input value for GPIO pins"] pub gpio_in: GPIO_IN, #[doc = "0x08 - Input...
use rdkafka::ClientConfig; use serde::Deserialize; use std::collections::HashMap; use std::ops::Deref; #[derive(Clone, Debug, PartialEq, Eq, Deserialize)] pub struct KafkaClientConfig { #[serde(default = "kafka_bootstrap_servers")] pub bootstrap_servers: String, #[serde(default, skip_serializing_if = "Hash...
mod construction; pub mod display; mod encode_into; mod parameter_type; mod utils; pub use encode_into::encode_into; pub use parameter_type::ParameterType; use utils::*; use ethane_types::{Address, H256}; /// An ABI function parameter type enclosing the underlying /// numeric data bytes. #[derive(Clone)] pub enum Pa...
use std::fmt; use std::rc::{Rc, Weak}; use std::cell::RefCell; use std::hash::{Hash, Hasher}; use std::collections::HashMap; use sha3::{Sha3_256, Digest}; use faster_hex::{hex_string}; #[derive(Debug, Clone)] enum NodeType<'a> { Branch{ left: Rc<Node<'a>>, // shared ownership right: Rc<Node<'a>>, ...
use std::fs::{read_dir, write}; fn main() -> std::io::Result<()> { // see https://doc.rust-lang.org/cargo/reference/build-scripts.html#rerun-if-changed // XXX: Removing this causes `cargo watch` to loop infinitely because we keep changing the // filesystem contents. for ent in read_dir("tests")? { ...
use azure_core::Context; use azure_cosmos::prelude::*; use futures::stream::StreamExt; use std::error::Error; #[tokio::main] async fn main() -> Result<(), Box<dyn Error + Send + Sync>> { // First we retrieve the account name and master key from environment variables. // We expect master keys (ie, not resource ...
#[doc = "Reader of register ITARGETSR2"] pub type R = crate::R<u32, super::ITARGETSR2>; #[doc = "Reader of field `CPU_TARGETS0`"] pub type CPU_TARGETS0_R = crate::R<u8, u8>; #[doc = "Reader of field `CPU_TARGETS1`"] pub type CPU_TARGETS1_R = crate::R<u8, u8>; #[doc = "Reader of field `CPU_TARGETS2`"] pub type CPU_TARGE...
struct Generator { current: usize, factor: usize, } impl Generator { pub fn new(current: usize, factor: usize) -> Generator { Generator { current, factor, } } } impl Iterator for Generator { type Item = usize; fn next(&mut self) -> Option<Self::Item> { ...
pub mod song; pub mod sound { use std::sync::mpsc; use px8::packet; use chiptune; use std::collections::HashMap; use sdl2; use sdl2::mixer; use std::sync::{Arc, Mutex}; pub struct SoundInternal { player: chiptune::Chiptune, chiptune_music_tracks: HashMap<String, chip...
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. */ //! Protects a set of file descriptors from getting closed. use std::os::unix::io::AsRawFd; use st...
use im::Vector; use ndarray::prelude::*; use std::convert::{TryFrom, TryInto}; use std::iter::FromIterator; use common::*; use common::primitives::*; macro_rules! assert_num_args { ($name:expr, $args:expr, $len:expr) => { if $args.len() != $len { return Err(format!("{} requires {} arguments bu...
use std::io::{stdout, Write}; use termion::raw::IntoRawMode; fn main() { let mut stdout = stdout().into_raw_mode().unwrap(); write!(stdout, "Hey there.").unwrap(); }
pub mod transport_parameters; pub use transport_parameters::TransportParameters;
use std::ops::Deref; use std::str::FromStr; use std::io::Read; use rustc_serialize::base64::{ToBase64, MIME}; use hyper; use hyper::Client; use hyper::header::{Accept, UserAgent, qitem}; use hyper::mime::Mime; use rustc_serialize::json; use rustc_serialize::{Decoder, Decodable, DecoderHelpers, Encoder, Encodable, Encod...
// Check if two device_id's have a relationship // true: They do // false: They don't use crate::DATABASE; use rusqlite::{Connection, Result}; #[derive(Debug)] pub struct Pairing { pub id: i32, pub device_one: String, pub device_two: String, pub pairing: i32, } // checks if pairing exists // true: if ...
#[doc = r"Register block"] #[repr(C)] pub struct RegisterBlock { #[doc = "0x00 - Control"] pub ctl: CTL, #[doc = "0x04 - Status"] pub status: STATUS, _reserved2: [u8; 60usize], #[doc = "0x44 - Transmitter command FIFO status"] pub tx_cmd_fifo_status: TX_CMD_FIFO_STATUS, _reserved3: [u8; ...
use amethyst::shred::{System,Dispatcher,DispatcherBuilder}; use amethyst::prelude::{DataInit,World}; use amethyst::core::{SystemBundle, ArcThreadPool}; use amethyst::Error; pub struct CustomGameData<'a, 'b> { core_dispatcher: Dispatcher<'a, 'b>, running_dispatcher: Dispatcher<'a, 'b>, } impl<'a, 'b> CustomGam...