text
stringlengths
8
4.13M
use crate::errors::{message::ErrorKind::*, ErrorKind, Result, ResultExt}; use crate::message_header::MessageHeader; use cashcontracts::double_sha256; use std::io; #[derive(Clone, Debug)] pub struct MessagePacket { header: MessageHeader, payload: Vec<u8>, } impl MessagePacket { fn _check_checksum(payload: ...
use std::{fmt::Debug, time::Duration}; use futures::{ future::{select_ok, try_select, Either}, pin_mut, Future, }; use tracing::warn; pub async fn single_retry<F, T, E>( mut create_f: impl FnMut() -> F, retry_delay: Duration, ) -> Result<T, E> where F: Future<Output = Result<T, E>> + Send, E: ...
use hydroflow::hydroflow_syntax; fn main() { let mut df = hydroflow_syntax! { pivot = union() -> tee(); x_0 = pivot[0]; x_1 = pivot[1]; x_0 -> [0]x_0; x_1[0] -> [1]x_1; // Error: `pivot[1][0]` }; df.run_available(); }
use clap::{App, Arg}; use std::io::{Read, Write}; use std::net::TcpStream; use std::thread; use std::time::{Duration, Instant}; use url::Url; fn main() -> anyhow::Result<()> { let arguments = App::new("cloudflare-2020-systems-engineering-assignment") .version("1.0") .about("Tool for making HTTP/1.1...
use std::os::raw::c_int; use std::os::raw::c_void; use std::os::raw::c_char; pub type argon2_context = Argon2_Context; pub type argon2_type = Argon2_type; pub type allocate_fptr = Option<unsafe extern "C" fn(memory: *mut *mut u8, bytes_to_allocate: usize) -> c_int>; pub type deallocate_fptr = Option<unsafe extern "C"...
use std::collections::HashMap; use std::io::ErrorKind::WouldBlock; use std::io::{Read, Write}; use std::ops::{Deref, DerefMut}; use std::os::unix::io::AsRawFd; use netlib::{Event, PollReactor}; use crate::codec::{Codec, Decode, Encode}; // -----------------------------------------------------------------------------...
/* * A sample API conforming to the draft standard OGC API - Features - Part 1: Core * * This is a sample OpenAPI definition that conforms to the conformance classes \"Core\", \"GeoJSON\", \"HTML\" and \"OpenAPI 3.0\" of the draft standard \"OGC API - Features - Part 1: Core\". This example is a generic OGC API Fea...
pub fn get_line((mut x0, mut y0): (i32, i32), (mut x1, mut y1): (i32, i32)) -> Vec<(i32, i32)> { let mut result = Vec::new(); let steep = (y1 - y0).abs() > (x1 - x0).abs(); if steep { std::mem::swap(&mut x0, &mut y0); std::mem::swap(&mut x1, &mut y1); } if x0 > x1 { std::m...
use near_sdk::borsh::{self, BorshDeserialize, BorshSerialize}; use near_sdk::{AccountId}; use near_sdk::json_types::{U128}; use near_sdk::collections::{Vector}; use near_sdk::serde::{Deserialize, Serialize}; #[derive(BorshDeserialize, BorshSerialize)] pub struct Reward { amount: u128, memo: String, } #[deriv...
#[doc = "Register `SCR` writer"] pub type W = crate::W<SCR_SPEC>; #[doc = "Field `CTAMP1F` writer - CTAMP1F"] pub type CTAMP1F_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `CTAMP2F` writer - CTAMP2F"] pub type CTAMP2F_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `CTAM...
mod common; use crate::common::random_dfa; use cached::cached; use proptest::prelude::*; use valis_automata::{ dfa::{minimization::minimize, standard::StandardDFA, DFA}, range_set::Range, }; #[test] fn fake_test_to_generate_random_dfa() { let dfa = random_dfa::<bool>(32, 0.1); common::render_dfa_to_f...
// 给定两个二进制字符串,返回他们的和(用二进制表示)。 // 输入为非空字符串且只包含数字 1 和 0。 // 示例 1: // 输入: a = "11", b = "1" // 输出: "100" // 示例 2: // 输入: a = "1010", b = "1011" // 输出: "10101" // struct Solution{} impl Solution { pub fn add_binary(a: String, b: String) -> String { let a: &[u8] = a.as_bytes(); let b: &[u8] = b.as...
use aoc2020::aoc::{load_data, Res}; use std::collections::HashMap; use std::collections::HashSet; use std::fmt::Debug; use std::fmt::Display; use std::hash::Hash; use std::io::BufRead; use std::collections::VecDeque; fn find_second_star(numbers: &[i64], invalid: i64)-> Vec<i64>{ let mut v = Vec::new(); '...
#[doc = "Reader of register CLOCK_CTL[%s]"] pub type R = crate::R<u32, super::CLOCK_CTL>; #[doc = "Writer for register CLOCK_CTL[%s]"] pub type W = crate::W<u32, super::CLOCK_CTL>; #[doc = "Register CLOCK_CTL[%s] `reset()`'s with value 0xff"] impl crate::ResetValue for super::CLOCK_CTL { type Type = u32; #[inli...
use mysql_rent::Rent; #[tokio::test] async fn should_work_with_no_params() { let sut = Rent::new().await.unwrap(); println!("connection URL: {}", sut.mysql_url()); drop(sut); } #[tokio::test] async fn should_work_with_options() { let sut = Rent::builder() .database("contacts") .local_p...
use std::net::SocketAddr; use chrono::prelude::*; use hydroflow::hydroflow_syntax; use hydroflow::util::{UdpLinesSink, UdpLinesStream}; use crate::helpers::{deserialize_json, serialize_json}; use crate::protocol::EchoMsg; pub(crate) async fn run_client( outbound: UdpLinesSink, inbound: UdpLinesStream, se...
fn main() { println!("cargo:rustc-link-lib=dylib=cuda"); let cuda_path = std::env::var("CUDA_LIB_PATH") .unwrap_or_else(|_| "/usr/local/cuda-11.3/lib64/".to_string()); println!("cargo:rustc-link-search=native={}", cuda_path); }
/* * Copyright Stalwart Labs Ltd. See the COPYING * file at the top-level directory of this distribution. * * Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or * https://www.apache.org/licenses/LICENSE-2.0> or the MIT license * <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your * optio...
use crate::PemStorable; pub mod x25519; pub trait MixnetEncryptionKeyPair<Priv, Pub> where Priv: MixnetEncryptionPrivateKey, Pub: MixnetEncryptionPublicKey, { fn new() -> Self; fn private_key(&self) -> &Priv; fn public_key(&self) -> &Pub; fn from_bytes(priv_bytes: &[u8], pub_bytes: &[u8]) -> S...
use std::io::prelude::*; use std::fs::File; use std::env; extern crate yaml_rust; use yaml_rust::YamlLoader; use yaml_rust::Yaml; use yaml_rust::yaml::Hash; fn merge_hashes(mut left_hash: Hash, right_hash: Hash) -> Yaml { right_hash.into_iter().for_each(|(key, value)| { left_hash.insert(key, value); }...
extern crate clap; use clap::{App, Arg}; fn main() { // You can get a "default value" like feature by using Option<T>'s .unwrap_or() method // // Let's assume you have -c <config> argument to allow users to specify a configuration file // but you also want to support a default file, if none is specifi...
use crate::display::Display; use rand::Rng; pub struct Cpu { memory: [u8; 4096], pc: u16, i: u16, regs: [u8; 16], display: Display, delay_timer: u8, stack: [u16; 16], sp: u8, keyboard: [bool; 16], awaiting_key_press: bool, current_key_pressed: Option<u8>, } impl Cpu { p...
pub trait JsonTrait { fn to_json(&self) -> Json; }
// ref: http://norvig.com/spell-correct.html use std::collections::HashSet; use strsim::jaro_winkler; const LETTERS: &str = "abcdefghijklmnopqrstuvwxyz"; pub struct Corrector { pub keys: HashSet<String>, } impl Corrector { pub fn correct(&self, word: &str) -> Vec<String> { // build_complex_can...
//! Module providing the search capability using BAM/BAI files //! use std::str::FromStr; use std::sync::Arc; use async_trait::async_trait; use noodles::bam; use noodles::bam::bai; use noodles::bam::bai::index::ReferenceSequence; use noodles::bam::bai::Index; use noodles::bgzf; use noodles::bgzf::VirtualPosition; use...
pub use tabled::{self, *};
fn print_string(s: &str) { println!("&str: {}", s) } fn print_second_word(s: &str) { let second_word = s.split(" ") .collect::<Vec<&str>>()[1]; println!("second: {}", second_word) } fn main() { let str = "Hello, world &str!"; let string = String::from("Hello, world String!"); print_s...
#[doc = "Register `HWCFGR4` reader"] pub type R = crate::R<HWCFGR4_SPEC>; #[doc = "Register `HWCFGR4` writer"] pub type W = crate::W<HWCFGR4_SPEC>; #[doc = "Field `CHMAP15` reader - Input channel mapping"] pub type CHMAP15_R = crate::FieldReader; #[doc = "Field `CHMAP15` writer - Input channel mapping"] pub type CHMAP1...
/* * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under both the MIT license found in the * LICENSE-MIT file in the root directory of this source tree and the Apache * License, Version 2.0 found in the LICENSE-APACHE file in the root directory * of this source tree. */ use s...
//! platform-independent traits. Submodules with backends will be selectable //! via cargo features in future mod palette; mod video_sdl; pub use palette::Palette; pub use video_sdl::VideoSdl; /// Texture id binging #[derive(PartialEq, Eq, Hash, Copy, Clone)] pub struct TextureInfo { id: usize, width: u32, ...
use crate::gc::Gc; use crate::rerrs::{ErrorKind, SteelErr}; use crate::rvals::{Result, SteelVal}; use crate::stop; use crate::throw; use std::rc::Rc; use serde::{Deserialize, Serialize}; use crate::parser::ast::Struct; #[derive(Clone, Debug, PartialEq)] pub struct SteelStruct { name: Rc<str>, fields: Vec<Ste...
use franklin_crypto::plonk::circuit::allocated_num::Num; use franklin_crypto::bellman::pairing::Engine; use franklin_crypto::bellman::plonk::better_better_cs::cs::ConstraintSystem; use rand::Rng; pub struct MdsMatrix<E: Engine, const SIZE: usize> { data: [[Num<E>; SIZE]; SIZE] } impl<E: Engine, const SIZE: usize> Md...
use serde_json::{Value}; use crate::ofn_2_man::axiom_translation as axiom_translation; use crate::ofn_2_man::class_translation as class_translation; use crate::ofn_2_man::property_translation as property_translation; /// Given an OFN S-expression (encoded in JSON), /// return its corresponding representation in Man...
//! Basic block and tokens a [template](`super::Template`) is created from. use std::fmt; use super::span::{ByteSpan, Spanned}; /// A parsed instruction from a template. #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] pub enum BlockHint { /// Starts a `Text` block Text, /// Starts a `Comment` block Comment, ...
use std::collections::HashMap; use crate::utils::file2vec; pub fn day4(filename: &String){ let contents = file2vec::<String>(filename); let contents:PassPortList = PassPortList { passports : &contents.iter().map(|x| x.to_owned().unwrap()).collect(), ptr:0, ...
extern crate r2d2; extern crate r2d2_postgres; extern crate postgres; use std::thread; use r2d2_postgres::{TlsMode, PostgresConnectionManager}; struct Person { id: i32, username: String } fn main() { let manager = PostgresConnectionManager::new("postgres://jeka:0454@localhost/diesel_demo", TlsMode::None)...
pub(crate) mod func; pub(crate) mod types; pub use func::*; pub use types::*;
// // Copyright 2021 The Project Oak Authors // // 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 o...
extern crate wasm_bindgen; use apollo_query_planner::{QueryPlanner, QueryPlanningOptions}; use js_sys::JsString; use wasm_bindgen::prelude::*; static mut SCHEMA: Vec<String> = vec![]; static mut DATA: Vec<QueryPlanner> = vec![]; #[wasm_bindgen(js_name = getQueryPlanner)] pub fn get_query_planner(schema: JsString) ->...
use jsonwebtoken::{ decode, encode, get_current_timestamp, Algorithm, DecodingKey, EncodingKey, Validation, }; use ring::signature::{Ed25519KeyPair, KeyPair}; use serde::{Deserialize, Serialize}; #[derive(Debug, Serialize, Deserialize)] pub struct Claims { sub: String, exp: u64, } fn main() { let doc ...
#![ allow( dead_code ) ] #![ allow( clippy::suspicious_else_formatting ) ] use { futures :: { * } , log :: { * } , std :: { io, task::{ Poll, Context }, pin::Pin, collections::VecDeque } , }; #[ derive( Debug, PartialEq, Eq, Clone ) ] // pub enum Action { Pending , Error( io::ErrorKind ) ...
// Copyright 2014-2018 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>,...
extern crate rand; use rand::{thread_rng,Rng}; use std::env; use std::process; #[allow(dead_code)] #[allow(non_camel_case_types)] // Each die_type contains a value. // For die_type::constant this value is equal to its total value // For all the rest, this value represents the amount of dice // to be rolled enum...
extern crate linux_embedded_hal; extern crate hd44780_driver; use linux_embedded_hal::{Delay, Pin}; use linux_embedded_hal::sysfs_gpio::Direction; use hd44780_driver::{HD44780, DisplayMode, Cursor, CursorBlink, Display}; fn main() { let rs = Pin::new(26); let en = Pin::new(22); let db0 = Pin::new(19); ...
use aoc_2020::day_03::*; fn main() { let filename = std::env::args().nth(1).unwrap(); let input = std::fs::read_to_string(filename).expect("Couldn't read input file"); println!("Part 1: {}", part1(&input)); println!("Part 2: {}", part2(&input)); }
use pasture_core::nalgebra::Vector3; use pasture_core::{ containers::InterleavedVecPointStorage, layout::{ attributes, PointAttributeDataType, PointAttributeDefinition, PointLayout, PointType, }, }; use pasture_derive::PointType; fn main() { // In this example, we will take a closer look at the...
use std::sync::{Arc, Weak}; use anyhow::Result; use tokio::sync::RwLock; use super::{progress, Host, ResourcePool, ResourceResult, Service}; #[derive(Default)] pub struct Deployment { pub hosts: Vec<Arc<RwLock<dyn Host>>>, pub services: Vec<Weak<RwLock<dyn Service>>>, pub resource_pool: ResourcePool, ...
use std::error::Error; use crate::modules::intcode; pub fn run(input: &str) -> Result<String, Box<dyn Error>> { let mut machine = intcode::build_intcode_from_input(input)?; machine.run(); Ok("Done!".to_string()) }
#[cfg(feature = "client")] use graphics::Context; #[cfg(feature = "client")] use opengl_graphics::Gl; use battle_state::BattleContext; use module; use module::{IModule, Module, ModuleBase, ModuleRef}; use net::{InPacket, OutPacket}; use ship::{ShipRef, ShipState}; use sim::SimEventAdder; use vec::{Vec2, Vec2f}; #[cfg...
use sdl2::event::Event; use sdl2::render::{Texture, WindowCanvas}; use sdl2::EventPump; use crate::Config; pub struct Gui { pub canvas: WindowCanvas, pub events: EventPump, } impl Gui { pub fn new(config: &Config) -> Gui { let sdl_context = sdl2::init().unwrap(); let video_subsystem = sdl...
extern crate rustc_version; use std::env; use std::fs::File; use std::io::Write; use std::path::PathBuf; use std::ops::{Neg,Sub}; /* * Let me explain this hack. For the sync shell script it's easiest if every * line in mapping.rs looks exactly the same. This means that specifying an * array literal is not possib...
use std::marker::PhantomData; use necsim_core::{ cogs::{ CoalescenceSampler, DispersalSampler, EmigrationExit, Habitat, ImmigrationEntry, LineageReference, LineageStore, MinSpeciationTrackingEventSampler, PeekableActiveLineageSampler, PrimeableRng, SingularActiveLineageSampler, Spec...
use std::fs::File; use std::io::prelude::*; use std::path::PathBuf; use sloppycomp::compression::Algorithm; use sloppycomp::lz77; #[test] fn test_compression_size() { // test exists so we can monitor and commit changes in optimisations to the // compression - slow in debug mode, so run with `cargo test --rele...
use crate::prelude::*; use azure_core::prelude::*; use http::StatusCode; use std::convert::TryInto; #[derive(Debug, Clone)] pub struct ReplaceReferenceAttachmentBuilder<'a, 'b> { attachment_client: &'a AttachmentClient, if_match_condition: Option<IfMatchCondition<'b>>, user_agent: Option<UserAgent<'b>>, ...
// Copyright 2019 The Fuchsia Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #![feature(async_await)] #![allow(dead_code)] use { failure::{Error, ResultExt}, fidl_fuchsia_settings::*, fuchsia_async as fasync, fuchsi...
#[doc = "Reader of register INTR_STAT"] pub type R = crate::R<u32, super::INTR_STAT>; #[doc = "Writer for register INTR_STAT"] pub type W = crate::W<u32, super::INTR_STAT>; #[doc = "Register INTR_STAT `reset()`'s with value 0"] impl crate::ResetValue for super::INTR_STAT { type Type = u32; #[inline(always)] ...
use crate::attrs::get_serde_attrs; use crate::docs::get_docs; use crate::meta::Glue; use std::collections::HashMap; use syn::Data; use syn::DataStruct; use syn::DeriveInput; use syn::Fields; pub fn process_struct( metadata: &mut Glue, input: DeriveInput, ) -> Result<(), String> { match &input.data { Data::St...
pub(crate) mod home; pub(crate) mod clicky; pub(crate) mod navbar;
extern crate graphics; extern crate opengl_graphics; extern crate piston_window; extern crate piston; use characters::Direction; use characters::player::Player; use locations::{Coordinates, get_by_id, Location}; use networking; use opengl_graphics::{GlGraphics, Texture}; use piston::input::*; use std::collections::Has...
//! MetroRail client. Contains the client for fetching data from //! the WMATA API and data structures returned from those endpoint calls. pub mod responses; mod tests; use crate::{ error::Error, rail::{ traits::{NeedsLine, NeedsStation}, urls::URLs, }, requests::{Fetch, Request as WMAT...
use support::{decl_storage, decl_module, StorageValue, StorageMap, dispatch::Result, ensure, decl_event, traits::Currency}; use system::ensure_signed; use runtime_primitives::traits::{As, Hash, Zero}; use parity_codec::{Encode, Decode}; use rstd::cmp; #[derive(Encode, Decode, Default, Clone, PartialEq)] #[cfg_attr...
use serde::Serialize; use common::result::Result; use crate::application::dtos::CategoryDto; use crate::domain::category::CategoryRepository; #[derive(Serialize)] pub struct GetAllResponse { pub categories: Vec<CategoryDto>, } pub struct GetAll<'a> { category_repo: &'a dyn CategoryRepository, } impl<'a> Ge...
///Contains the current board state /// All the pieces, empty tiles etc. #[derive(Copy, Clone)] struct Board { } ///Represents a move on the board. It can be analysed. #[derive(Ord, PartialOrd, Eq, PartialEq, Clone, Copy)] struct Move { } impl Board { ///Generates all possible moves on a provided board. ///...
//! Franks server handson //! //! A simple server that accepts connections, writes "hello world\n", and closes //! the connection. //! //! Start this application and in another terminal run: //! //! telnet localhost 6142 //! #![allow(warnings)] #![allow(unused_variables)] extern crate tokio; extern crate futures;...
#[doc = "Register `GICD_IGROUPR6` reader"] pub type R = crate::R<GICD_IGROUPR6_SPEC>; #[doc = "Register `GICD_IGROUPR6` writer"] pub type W = crate::W<GICD_IGROUPR6_SPEC>; #[doc = "Field `IGROUPR6` reader - IGROUPR6"] pub type IGROUPR6_R = crate::FieldReader<u32>; #[doc = "Field `IGROUPR6` writer - IGROUPR6"] pub type ...
extern crate chrono; #[macro_use] extern crate diesel; #[macro_use] extern crate failure; extern crate futures; #[macro_use] extern crate hyper; extern crate reqwest; extern crate serde; #[macro_use] extern crate serde_derive; extern crate serde_json; #[macro_use] extern crate slog; extern crate tokio; extern crate tok...
use super::gl; use super::gl::types::*; use super::cgmath::prelude::*; use super::cgmath::Matrix4; use super::glutin::{GlContext, GlWindow}; use std::ffi::{CStr, CString}; use std::mem; use std::os::raw::c_void; use std::ptr; const VERTEX_SHADER_SOURCE: &[u8] = include_bytes!("./shaders/cell.vs"); const FRAGMENT_SHAD...
use crate::grid::{CellValue, Grid}; use printpdf::*; use std::fs::File; use std::io::BufWriter; const BOTTOM_LEFT_X: f64 = 10.0; const BOTTOM_LEFT_Y: f64 = 279.0 - 200.0 - 10.0; const GRID_DIMENSION: f64 = 190.0; const A4: (Mm, Mm) = (Mm(215.0), Mm(279.0)); pub fn draw_grid(grid: &Grid, filename: &str, print_possibi...
use derive_more::Display; use std::{env::JoinPathsError, error::Error, num::NonZeroI32, path::PathBuf}; /// Error types emitted by `pn` itself. #[derive(Debug, Display)] pub enum PnError { /// Script not found when running `pn run`. #[display(fmt = "Missing script: {name}")] MissingScript { name: String },...
use super::*; /// A comment block. /// /// # Semantics /// /// See [`Comment`]. /// /// # Syntax /// /// ```text /// #+BEGIN_COMMENT /// CONTENTS /// #+END_COMMENT /// ``` /// /// `CONTENTS` can contain anything except a line `#+END_COMMENT` on its own. Lines beginning /// with stars must be quoted by a comma. `CONTEN...
use std::collections::HashMap; use std::error::Error; use scraper::{Html, Selector}; use chrono::{Timelike, Local, DateTime, Duration}; use clap::{Arg, App}; // Roomzilla doesn't give us an end time or duration, so we have to infer it by the width of the reservation element // 58px = 1 hour // 60 / 58 = 1.03448275862 ...
use crate::target::Endpoint; use linkerd_app_core::{ dns::Name, io, svc::{self, layer}, transport_header::TransportHeader, Error, }; use std::{ future::Future, pin::Pin, str::FromStr, task::{Context, Poll}, }; use tracing::{debug, trace, warn}; #[derive(Clone, Debug)] pub struct Opa...
//! Crash Recovery Log //! //! This module implements a durable log for transaction and object allocation state to ensure //! that those operations can be successfully recovered in the event of unexpected program //! termination. //! //! The CRL is implemented in front-end, backend-halves where the frontend is commo...
extern crate astro; use astro::*; use std::io; use std::io::*; fn main() { // Welcome message println!("So you want to have a Julian day (Me day)?"); loop { // Declaring variables let mut year: i16 = 0; let mut month: u8 = 0; let mut day: u8 = 0; loop { ...
use byteorder::{BigEndian, ByteOrder}; pub struct Packet { data: PacketData, header: u32, } impl Packet { pub fn new(data: PacketData) -> Packet { let header = BigEndian::read_u32(&data[0..4]); return Packet { data: data, header: header, }; } pub fn...
use std::net::SocketAddr; use crate::common::message_type::{MsgType, UdpPacket, msg_types}; use super::RendezvousServer; impl RendezvousServer { pub fn read_udp_message(&mut self, _: usize, addr: SocketAddr, buf: &[u8]) { let udp_packet: UdpPacket = bincode::deserialize(&buf).unwrap(); let buf =...
use std::mem; use twilight_model::application::interaction::{ application_command::CommandDataOption, ApplicationCommand, }; pub trait ApplicationCommandExt { fn yoink_options(&mut self) -> Vec<CommandDataOption>; } impl ApplicationCommandExt for ApplicationCommand { fn yoink_options(&mut self) -> Vec<Co...
/* Copyright (c) 2023 Uber Technologies, Inc. <p>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 <p>http://www.apache.org/licenses/LICENSE-2.0 <p>Unless required by applicable law or agreed to ...
extern crate queue; use queue::Queue; #[test] fn test_queue() { let mut queue = Queue::new(); queue.push(1); queue.push(2); queue.push(3); assert_eq!(queue.len(), 3); assert_eq!(queue.pop(), Some(1)); assert_eq!(queue.pop(), Some(2)); assert_eq!(queue.pop(), Some(3)); assert_e...
pub mod client; pub mod error; mod types;
#![no_std] use volatile_cell::VolatileCell; // Known to apply to: // [RM0091] STM32F0x1, STM32F0x2, STM32F0x8 (TIM2/3) // [RM0090] STM32F4 (TIM2/3/4/5) // [RM0351] STM32L4x6 (TIM2/3/4/5) ioregs!(GPTIM32 = { 0x00 => reg32 cr1 { 0 => cen : rw { 0 => Disable, 1 => Enable, }...
pub const CH_CTRL_SOURCESEL_TIMER0: u32 = 0x1c << 16; pub const CH_CTRL_SIGSEL_TIMER0OF: u32 = 0x1 << 0; pub fn source_signal_set(ch: u32, source: u32, signal: u32, edge: Edge) { unsafe { PRS_SourceSignalSet(ch, source, signal, edge); } } #[repr(u32)] #[derive(Copy, Clone)] pub enum Edge { Off = 0x0 << 24, ...
// This Standard specifies the Secure Hash Algorithm-3 (SHA-3) // https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.202.pdf // // C code // https://github.com/mjosaarinen/tiny_sha3/blob/master/sha3.c // 5 KECCAK // 5.1 Specification of pad10*1 // // https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.202.pdf // // Input...
pub fn max_profit(prices: Vec<i32>) -> i32 { use std::cmp::max; let n = prices.len(); if n <= 1 { return 0; } let mut profit = vec![0; n]; for j in (0..n - 1).rev() { let mut p = profit[j + 1]; for i in j + 1..n - 2 { p = max(p, prices[i] - prices[j] + prof...
use game::card::{CardStruct, Giveable, ConditionWhen, Costable, CardLocation, CardType, CardInfo}; use game::board::{Board, PlayerEnum}; use serde_json; use serde_json::Value; use serde_derive; use serde; use std::fs::File; use std::io::Read; pub enum LocalEnum { English, Cantonese, } #[derive(Deserialize,Debu...
use std::ffi::CString; use z3_sys::*; use crate::z3::Context; use crate::z3::Symbol; impl Symbol { pub fn as_z3_symbol(&self, ctx: &Context) -> Z3_symbol { match self { Symbol::Int(i) => unsafe { Z3_mk_int_symbol(ctx.z3_ctx, *i as ::std::os::raw::c_int) }, Symbol::String(s) => { ...
use anyhow::{Context, Result}; use std::borrow::ToOwned; use std::ffi::OsString; use std::fs::File; use std::io::Read; use std::path::{Path, PathBuf}; use std::process::Command; #[derive(Deserialize, Debug, Clone, Copy)] pub struct Color { pub r: u8, pub g: u8, pub b: u8, } #[rustfmt::skip] const DARK_BLU...
use specs::*; use server::component::channel::*; use server::protocol::server::{GameFlag, ServerPacket}; use server::protocol::{to_bytes, FlagUpdateType}; use server::*; use component::*; pub struct LoginUpdateSystem { reader: Option<OnPlayerJoinReader>, } #[derive(SystemData)] pub struct LoginUpdateSystemData<'a>...
use apllodb_shared_components::{NnSqlValue, SqlValue}; use apllodb_sql_parser::apllodb_ast; use crate::ast_translator::AstTranslator; impl AstTranslator { pub(crate) fn string_constant(ast_string_constant: apllodb_ast::StringConstant) -> SqlValue { SqlValue::NotNull(NnSqlValue::Text(ast_string_constant.0)...
#[doc = "Register `CSELR` reader"] pub type R = crate::R<CSELR_SPEC>; #[doc = "Register `CSELR` writer"] pub type W = crate::W<CSELR_SPEC>; #[doc = "Field `C1S` reader - DMA channel 1 selection"] pub type C1S_R = crate::FieldReader; #[doc = "Field `C1S` writer - DMA channel 1 selection"] pub type C1S_W<'a, REG, const O...
fn main() { let mut random_num1:u8=0; let mut bit1:u8 =0; let mut random_num2:u8=0; let mut temp_num:u8=0; let mut temp_num1:u8=0; let mut temp_num2:u8=0; let mut temp_num3:u8=0; let mut temp_num4:u8=0; let mut bit2:u8 =0; for x in 0..8{ bit1 = mag...
use std::borrow::BorrowMut; use std::cell::RefCell; use std::{thread, time::Duration, sync::Arc}; use futures::{executor, task::SpawnExt}; use futures::FutureExt; use futures_timer::Delay; use wasmtime::{Instance, Store, Engine, Config, Linker, Module}; struct State { wasi: wasmtime_wasi::WasiCtx, } impl State ...
extern crate omegalul; use std::{collections::HashMap, thread}; use ::std::*; use omegalul::server::{get_random_server, ChatEvent, Server}; #[tokio::main] async fn main() { if let Some(server_name) = get_random_server().await { println!("Connecting to {} server", server_name); let server = &mut S...
extern crate num; extern crate ndarray; #[macro_use] extern crate itertools; use ndarray::{Array, Array4, Zip}; use num::complex::Complex; use num::Zero; use numpy::{IntoPyArray, PyArray4}; use pyo3::prelude::{pymodule, Py, PyErr, PyModule, PyResult, Python}; fn c_val_32(k: i32, kd: i32, m: i32, md: i32, n: i32, nd: ...
pub mod app; pub mod app_to_game;
// Copyright 2020 IOTA Stiftung // SPDX-License-Identifier: Apache-2.0 use inccounter::*; use consts::*; use wasmlib::*; mod inccounter; mod consts; #[no_mangle] fn on_load() { let exports = ScExports::new(); exports.add_func(FUNC_CALL_INCREMENT, func_call_increment); exports.add_func(FUNC_CALL_INCREMENT...
use pulldown_cmark::{html, Options, Parser}; pub fn render(md: String) -> String { let mut options = Options::empty(); options.insert(Options::ENABLE_STRIKETHROUGH); let parser = Parser::new_ext(&md, options); let mut html_output = String::new(); html::push_html(&mut html_output, parser); html_...
pub trait AnalogInput: Send { fn get_value(&mut self) -> Option<f32>; }
pub mod miner; mod stratum; #[cfg(test)] mod test; mod worker; use byteorder::{LittleEndian, WriteBytesExt}; use rand::Rng; use std::ops::Range; fn partition_nonce(id: u64, total: u64) -> Range<u64> { let span = u64::max_value() / total; let start = span * id; let end = match id { x if x < total -...
use common::event::EventPublisher; use common::result::Result; use crate::application::dtos::{AuthorDto, CategoryDto, PublicationDto}; use crate::domain::author::AuthorRepository; use crate::domain::category::CategoryRepository; use crate::domain::interaction::InteractionService; use crate::domain::publication::{Publi...