text
stringlengths
8
4.13M
use near_sdk::borsh::{self, BorshDeserialize, BorshSerialize}; use near_sdk::serde_json::{self, json}; use near_sdk::wee_alloc::WeeAlloc; use near_sdk::{env, near_bindgen, AccountId}; use near_sdk::{PromiseResult}; use near_sdk::json_types::{U128, U64}; #[global_allocator] static ALLOC: WeeAlloc = WeeAlloc::INIT; cons...
extern crate ethcore_network as network; // use poa::error::PoaError; use std::io; // use tvm::types::Exception; error_chain! { types { NodeError, NodeErrorKind, NodeResultExt, NodeResult; } foreign_links { Eth(network::Error); Io(io::Error); } errors { FailureEr...
use types::beacon_state::BeaconState; use types::config::Config; use types::helper_functions_types::Error; use types::primitives::{Domain, DomainType, Epoch, Slot, ValidatorIndex, Version, H256}; //ok pub fn compute_shuffled_index<C: Config>( _index: ValidatorIndex, _index_count: u64, _seed: &H256, ) -> Re...
use byteorder::{ReadBytesExt, LE}; use chrono::prelude::*; use lazy_static::lazy_static; use rayon::prelude::*; use std::ffi::OsStr; use std::fs; use std::io::prelude::*; use std::io::{self, BufReader}; use std::path::{Path, PathBuf}; use std::time::Duration; use structopt::StructOpt; use thiserror::Error; const EXT: ...
#[doc = "Register `FDCAN_RXF1C` reader"] pub type R = crate::R<FDCAN_RXF1C_SPEC>; #[doc = "Register `FDCAN_RXF1C` writer"] pub type W = crate::W<FDCAN_RXF1C_SPEC>; #[doc = "Field `F1SA` reader - F1SA"] pub type F1SA_R = crate::FieldReader<u16>; #[doc = "Field `F1SA` writer - F1SA"] pub type F1SA_W<'a, REG, const O: u8>...
use crate::test::spec::{ unified_runner::{run_unified_tests, ExpectedCmapEvent, ExpectedEvent, TestFile}, ExpectedEventType, }; #[cfg_attr(feature = "tokio-runtime", tokio::test(flavor = "multi_thread"))] #[cfg_attr(feature = "async-std-runtime", async_std::test)] async fn run_unified() { // The Rust drive...
//! The syntax module contains the definition of the terms of the language. use std::fmt; /// Types of the language. #[derive(PartialEq, Debug, Clone)] pub enum Type { /// The type of booleans Bool, /// The type of Natural numbers Nat, } /// Terms of the language. #[derive(PartialEq, Debug, Clone)] p...
use std::fmt; use std::mem; use std::slice; use scroll::{ctx::TryFromCtx, Endian, Pread}; use crate::common::*; use crate::modi::{ constants, CrossModuleExport, CrossModuleRef, FileChecksum, FileIndex, FileInfo, LineInfo, LineInfoKind, ModuleRef, }; use crate::symbol::{BinaryAnnotation, BinaryAnnotationsIter,...
use super::tss::TSS; use core::mem::size_of; use core::ops::{DerefMut, Drop}; use core::sync::atomic; extern "C" { static mut gdt64: GdtDescriptor; static mut gdt: [GdtEntry; 10]; } // Currently available segments pub const GDT_64_CODE: u16 = 0x8; pub const GDT_64_DATA: u16 = 0x10; pub const GDT_32_USER_CODE:...
#[derive(Debug, PartialEq)] pub enum GrammarItem{ LiteralInt(i32), Variable(String), Application(Box<ParseNode>, Box<ParseNode>), Abstraction(String, Box<ParseNode>), Assignment(String, Box<ParseNode>), Program(Vec<ParseNode>) } #[derive(Debug, PartialEq)] pub enum Type{ Variable(String), ...
use anyhow::Result; use libp2p::{ futures::StreamExt, mdns::{Mdns, MdnsConfig, MdnsEvent}, swarm::{SwarmBuilder, SwarmEvent}, }; use libp2p_quic::{generate_keypair, QuicConfig, ToLibp2p}; use tracing::{info, Level}; use tracing_subscriber; type Crypto = libp2p_quic::TlsCrypto; #[tokio::main] async fn ma...
#[cfg(feature = "python")] pub mod py; mod test; /// The square-well freely-jointed chain (SWFJC) model thermodynamics in the isometric ensemble approximated using a Legendre transformation. pub mod legendre; /// The structure of the thermodynamics of the SWFJC model in the isometric ensemble. pub struct SW...
use regex::Regex; use serde::{Deserialize, Serialize}; // lazy_static! { // static ref GLOBAL_CONFIG: Mutex<Config> = Mutex::new(Config::new()); // } pub const DEFAULT_RELAY_BUF_SIZE: usize = 4 * 1024; #[derive(Serialize, Deserialize, Debug, Clone)] pub struct LogConfig { pub logtostderr: bool, pub level:...
use buildings::{Building,getCumulativeFloorHeight}; use trip_planning::{RequestQueue}; use motion_controllers::{MotionController}; use data_recorders::{DataRecorder}; use std::time::Instant; use floating_duration::{TimeAsFloat, TimeFormat}; use std::{thread, time}; #[derive(Clone,Debug,Serialize,Deserialize)] pub stru...
use crate::websocket::ServerSocket; use rustimate_core::ResponseMessage; use actix::Addr; #[derive(Debug)] pub struct SendResponseMessage { msg: ResponseMessage } impl SendResponseMessage { pub(crate) const fn msg(&self) -> &ResponseMessage { &self.msg } } impl actix::Message for SendResponseMessage { ...
#[doc = "Register `CCCR` reader"] pub type R = crate::R<CCCR_SPEC>; #[doc = "Register `CCCR` writer"] pub type W = crate::W<CCCR_SPEC>; #[doc = "Field `INIT` reader - INIT"] pub type INIT_R = crate::BitReader; #[doc = "Field `INIT` writer - INIT"] pub type INIT_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[...
use cosmwasm_std::{ log, to_binary, Api, CanonicalAddr, Coin, CosmosMsg, Decimal, Env, Extern, HandleResponse, HandleResult, HumanAddr, Querier, StdError, StdResult, Storage, Uint128, WasmMsg, }; use crate::state::{read_config, Config, PoolInfo}; use cw20::Cw20HandleMsg; use spectrum_protocol::mirror_farm::Ha...
use syntect::easy::HighlightLines; use syntect::highlighting::{Theme}; use syntect::parsing::{SyntaxReference, SyntaxSet}; /// Common helper for benchmarking highlighting. pub fn do_highlight(s: &str, syntax_set: &SyntaxSet, syntax: &SyntaxReference, theme: &Theme) -> usize { let mut h = HighlightLines::new(syntax...
/* * 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...
//! Custom matcher implementation support via dynamic trait objects. use crate::matcher::{Matcher, MatcherProvider}; use std::fmt; use std::rc::Rc; /// Wrapper for a user-defined matcher implementation. /// /// # Example /// ``` ///# use yew_router::matcher::{MatcherProvider, Matcher}; ///# use yew_router_route_parser...
#[derive(Clone)] pub struct CommandAndArgs { pub command: String, pub args: Vec<String>, } pub type CommandArgs = Vec<String>;
use std::borrow::Cow; use std::fmt::{self, Display}; type IsConst = bool; #[derive(Debug, PartialEq, Eq, Clone)] enum Type<'a> { Path(IsConst, Vec<&'a str>), Normal(IsConst, &'a str), Function(IsConst, Box<Type<'a>>, Vec<Type<'a>>), Array(usize, Box<Type<'a>>), Pointer(IsConst, Box<Type<'a>>), ...
use crate::grammar::ast::eq::{ast_eq, AstEq}; use crate::grammar::ast::{ExpressionStatement, Statement}; use crate::grammar::model::{HasSourceReference, WrightInput}; use crate::grammar::tracing::parsers::map; use crate::grammar::tracing::trace_result; use nom::IResult; use std::mem::discriminant; /// Expression state...
use log::LevelFilter; pub fn init() { let _ = env_logger::builder() .is_test(true) .filter_level(LevelFilter::Debug) .try_init(); } #[macro_export] macro_rules! test { ($v:ident => $code:tt) => {{ common::init(); let cli = client(); let db = db(&cli, |pg| servi...
extern crate termion; mod game; mod wordlist; use game::{Difficulty, Game, GuessResult}; use std::fs::File; use std::io::{stdin, stdout, Write}; use termion::clear; use termion::input::TermRead; use wordlist::WordSet; fn main() { let mut words_file = File::open("./enable1-filtered.txt").expect("could not find wor...
use crate::fraud_proof::FraudProof; use crate::OpaqueBundle; use parity_scale_codec::{Decode, Encode}; use scale_info::TypeInfo; use sp_runtime::traits::{Block as BlockT, NumberFor}; use sp_runtime::transaction_validity::{InvalidTransaction, TransactionValidity}; use subspace_runtime_primitives::Balance; /// Custom in...
/* * BitTorrent bencode encoder/decoder (Rust) * * Copyright (c) 2021 Project Nayuki. (MIT License) * https://www.nayuki.io/page/bittorrent-bencode-format-tools * * Permission is hereby granted, free of charge, to any person obtaining a copy of * this software and associated documentation files (the "Software...
use crate::fail_with_message; pub fn invalid_repeated_option(arg: &String) { fail_with_message(&format!("Can't use {} option twice", arg)) } pub fn invalid_number_option(arg: &String, opt: &String) -> ! { fail_with_message(&format!("{} is not a valid number for {}", arg, opt)) } pub fn invalid_option(arg: &Strin...
// This file was generated by gir (https://github.com/gtk-rs/gir @ fbb95f4) // from gir-files (https://github.com/gtk-rs/gir-files @ 77d1f70) // DO NOT EDIT use ffi; use glib::translate::*; use glib_ffi; use gobject_ffi; use std::mem; use std::ptr; glib_wrapper! { pub struct SrvTarget(Boxed<ffi::GSrvTarget>); ...
use failure::Error; #[derive(Debug, Fail)] pub enum TrustnoteError { // TODO: need to define own error #[fail(display = "invalid toolchain name: {}", name)] InvalidToolchainName { name: String }, #[fail(display = "unknown toolchain version: {}", version)] UnknownToolchainVersion { version: String }...
pub mod wiring { use std::sync::{Arc, Mutex}; pub type Wire = Arc<Mutex<bool>>; pub fn is_high(wire: Wire) -> bool { let wire_lock = wire.lock().unwrap(); return *wire_lock; } pub fn is_low(wire: Wire) -> bool { let wire_lock = wire.lock().unwrap(); return !*wire_lock...
#[doc = "Register `IER3` reader"] pub type R = crate::R<IER3_SPEC>; #[doc = "Register `IER3` writer"] pub type W = crate::W<IER3_SPEC>; #[doc = "Field `TZSCIE` reader - TZSCIE"] pub type TZSCIE_R = crate::BitReader; #[doc = "Field `TZSCIE` writer - TZSCIE"] pub type TZSCIE_W<'a, REG, const O: u8> = crate::BitWriter<'a,...
mod coordinate; pub fn run_http(){ let p = coordinate::Cartesian {x:3.0, y:2.0}; let client = reqwest::blocking::Client::new(); let res = client.post("http://127.0.0.1:8001/cartesian-to-polar") .json(&p) .send() .unwrap(); println!("HTTP response: {:?}", res); let polar: co...
#![allow(overflowing_literals)] fn main() { let decimal = 65.3421_f32; // no implicit conversion //let integer: u8 = decimal;//error mismatched types, expected u8, found f32 let integer = decimal as u8; let character = integer as char; println!("Casting: {} -> {} -> {}", decimal, integer, ch...
// Copyright 2022 Alibaba Cloud. All rights reserved. // Copyright (c) 2020 Ant Financial // // SPDX-License-Identifier: Apache-2.0 // use std::collections::HashMap; use std::marker::PhantomData; use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::{Arc, Mutex}; use tokio::sync::mpsc; use crate::error::{Err...
extern crate byteorder; extern crate i2cdev; extern crate rust_pigpio; use self::rust_pigpio::pwm::*; use self::rust_pigpio::*; use std::cmp::min; pub struct Motor { pub pwm_pin: u32, pub dir_pin: u32, pub direction: bool, } impl Motor { pub fn init(&self) { set_mode(self.dir_pin, OUTPUT).un...
// 17.16 Masseusse // Simple DP. // bests_without[i] = best solution that excludes requests[i]. // = bests[i-1]. // bests[i] = best solution that may include requests[i] // = max ( bests_without[i-1] + requests[i] , // bests_without[i] ) // // O(n) spacetime. Note that the s...
use std::env; use std::path::Path; use lodepng::{ Bitmap, RGBA }; fn bitmap_is_equal(lhs: Bitmap<RGBA>, rhs: Bitmap<RGBA>) -> bool { (lhs.buffer, lhs.width, lhs.height) == (rhs.buffer, rhs.width, rhs.height) } enum ExitStatus { Same = 0, Diff = 1, Error = 2, } fn exit(status: ExitStatus) -> ! { ...
use std::io::Error; use docker::image::Image; pub trait CleanupStrategy { fn filter(&self, Vec<Image>) -> Result<Vec<Image>, Error>; } pub struct NumberedCleanup<'a>{ name: &'a str, num_to_keep: usize, } struct ImageNumbered{ image: Image, number: i64, } impl<'a> NumberedCleanup<'a> { pub fn new(name: &str, n...
use response; use request::RequestBuilder; use request::DoRequest; impl<'t> DoRequest<response::Action> for RequestBuilder<'t, response::Action> {}
// Copyright 2016 PingCAP, Inc. // // 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 i...
// in second.rs // pub says we want people outside this module to be able to use List #[derive(Default)] pub struct List<T> { head: Link<T>, } type Link<T> = Option<Box<Node<T>>>; #[derive(Debug)] struct Node<T> { elem: T, next: Link<T>, } impl<T> List<T> { pub fn new() -> Self { List { head...
use std::{cmp::Ordering, iter, sync::Arc}; use eyre::Report; use rosu_v2::prelude::{GameMode, OsuError}; use twilight_model::{ application::interaction::{application_command::CommandOptionValue, ApplicationCommand}, id::{marker::UserMarker, Id}, }; use crate::{ commands::{ check_user_mention, pars...
use ethabi; use failure::Fail; use std::io; use std::string::ToString; /// Contract Service Errors #[derive(Debug, Clone, Fail)] pub enum Error { /// IO Error #[fail(display = "IO error: {}", _0)] IO(String), /// Invalid Contract #[fail(display = "Invalid contract: {}", _0)] InvalidContract(St...
use anyhow::{format_err, Error}; use fmt::Debug; use futures::{future::try_join_all, TryStreamExt}; use log::debug; use smallvec::{smallvec, SmallVec}; use std::{ collections::HashMap, convert::From, fmt, path::{Path, PathBuf}, str::FromStr, sync::Arc, }; use url::Url; use crate::{ config::...
/* An almost-literal transliteration of AVX-optimized sin(), cos(), exp() and log() functions by Giovanni Garberoglio, available at http://software-lisc.fbk.eu/avx_mathfun/ Copyright (C) 2012 Giovanni Garberoglio Interdisciplinary Laboratory for Computational Science (LISC) Fondazione Bruno Kessler and University of T...
use std::{ io::{self, Read, Write}, net::TcpStream, sync::mpsc, thread, time, }; macro_rules! thrust_and_return { // ($Fn:ident($($arg:expr),*)) => { ($f:expr) => { // match $Fn($($arg),*) { match $f { Reconnect::Yes => return Reconnect::Yes, Reconnect::Q...
use lazy_static::lazy_static; use std::collections::{hash_map::Entry, BTreeSet, HashMap}; #[derive(Debug, Clone)] struct State(BTreeSet<i64>); impl State { fn has_plant(&self, pos: i64) -> bool { self.0.contains(&pos) } fn min(&self) -> i64 { *self.0.iter().next().unwrap() } fn m...
use crate::pipelines; use regex::Regex; use std::io::BufReader; use std::collections::HashMap; use rust_bert::pipelines::{ summarization::SummarizationModel, generation::{GPT2Generator, LanguageGenerator, MarianGenerator, GenerateConfig}, sentiment::{Sentiment, SentimentModel, SentimentPolarity}, sequen...
use crate::error::{NiaServerError, NiaServerResult}; use crate::protocol::Serializable; use nia_protocol_rust::RemoveDeviceByPathRequest; #[derive(Debug, Clone, PartialEq, Eq)] pub struct NiaRemoveDeviceByPathRequest { device_path: String, } impl NiaRemoveDeviceByPathRequest { pub fn new<S>(device_path: S) -...
use crate::converters::Converter; use crate::descriptions::TextDescription; use serde::Serialize; #[derive(Debug)] pub(crate) struct DeviceInfo { pub host: String, pub eoj: String, //these are epcs pub r: Vec<String>, pub w: Vec<String>, } impl DeviceInfo { pub fn new(host: String, eoj: String)...
pub mod coin; pub mod diffie_hellman; pub mod fr_serial; pub mod merkle; pub mod mint_proof; pub mod note; pub mod schnorr; pub mod spend_proof; pub mod util; use bellman::groth16; use bls12_381::Bls12; use crate::error::Result; pub use mint_proof::{create_mint_proof, setup_mint_prover, verify_mint_proof, MintReveale...
pub fn wiggle_max_length(nums: Vec<i32>) -> i32 { let n = nums.len(); if n < 2 { return n as i32; } let mut down = 1; let mut up = 1; for i in 1..n { if nums[i] > nums[i - 1] { up = down + 1; } else if nums[i] < nums[i - 1] { down = up + 1; ...
use serde::{Serialize, Deserialize}; #[derive(Debug, Serialize, Deserialize)] #[serde(untagged)] pub enum WifiNetworkStatus { WifiNetworkSuccess(WifiNetworkResponse), WifiNetworkError(ErrorMessage), } #[derive(Debug, Serialize, Deserialize, Clone)] pub struct WifiNetworkResponse { pub result: u...
//! Demonstrates the use of the Window::save_file() call to get a filename via a friendly GUI, //! and the Window::modal_err() call to display modal dialog boxes. extern crate iui; use iui::controls::{Button, MultilineEntry, VerticalBox}; use iui::prelude::*; use std::error::Error; use std::fs::File; use std::io::prel...
use std::str::FromStr; use sudoku_solver::grid::Grid; use sudoku_solver::solver::solve_grid; fn main() { let mut debug = false; let mut filename = String::new(); { // this block limits scope of borrows by ap.refer() method let mut ap = argparse::ArgumentParser::new(); ap.set_descri...
extern crate boondock; use boondock::{ContainerListOptions, Docker}; fn main() { let docker = Docker::connect_with_defaults().unwrap(); let opts = ContainerListOptions::default().all(); let containers = docker.containers(opts).unwrap(); for container in &containers { println!("{} -> Creat...
// 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>,...
//! Physically-based material. use gfx::traits::Pod; use specs::{Component, DenseVecStorage}; use error::Result; use tex::{Texture, TextureBuilder}; use types::Factory; /// Material struct. #[derive(Clone, Debug, Eq, Hash, PartialEq)] pub struct Material { /// Diffuse map. pub albedo: Texture, /// Emiss...
fn main() { let x = 13; let evenodd = if x % 2 == 0 { "even" } else { "odd" }; println!("{}", evenodd); let s = "1a23"; let num = match s.parse::<i32>() { Ok(n) => n, Err(e) => { println!("Error parsing: {}", e); println!("Defaulting to 0"); 0 ...
//! Module providing the search capability using BCF files //! use std::sync::Arc; use async_trait::async_trait; use futures_util::stream::FuturesOrdered; use noodles::bcf; use noodles::csi::index::reference_sequence::bin::Chunk; use noodles::csi::index::ReferenceSequence; use noodles::csi::{BinningIndex, Index}; use...
use super::*; /// A LaTeX environment. /// /// # Semantics /// /// This will be treated as accordingly when exporting with LaTeX. Otherwise it will be treated /// as plain text. /// /// # Syntax /// /// ```text /// \begin{ENVIRONMENT} /// CONTENTS /// \end{ENVIRONMENT} /// ``` /// /// `ENVIRONMENT` can contain any alp...
use std::{collections::HashMap, borrow::BorrowMut}; fn main() { let input: &str = include_str!("input.txt"); let mut sections = input.split("\n\n"); let template_string = sections.next().unwrap(); let mut template: Vec<char> = template_string.chars().collect(); let rules = sections.next().unwrap();...
fn main() -> std::io::Result<()> { // Bundle `VCRUNTIME140.DLL` on Windows: #[cfg(all(windows, feature = "windows-static"))] static_vcruntime::metabuild(); Ok(()) }
use crate::error::ConfigError; use crate::DEFAULT_PORT; use log::*; use serde::{Deserialize, Serialize}; use std::convert::TryFrom; use std::fs; use std::net::{SocketAddr, ToSocketAddrs}; use std::path::{Path, PathBuf}; use toml::value::Array; use toml::Value; #[derive(Debug, Deserialize, Serialize)] struct TOMLConfi...
use std::fs::OpenOptions; use std::io::{Read, Write}; use aead::generic_array::GenericArray; use anyhow::Result; use base64::{decode_config, encode_config, URL_SAFE_NO_PAD}; use chacha20poly1305::aead::{Aead, NewAead}; use chacha20poly1305::XChaCha20Poly1305; use serde::{Deserialize, Serialize}; use crate::utility::i...
#![feature(scoped)] extern crate osmpbfreader; #[allow(dead_code)] mod graph; use std::env; use std::collections::hash_map::HashMap; use std::fs::File; use std::path::Path; use std::str::FromStr; use std::thread; use osmpbfreader::{OsmPbfReader, blocks, objects}; use graph::{DijkstraGraph, Edge, Graph, Node}; con...
use std::sync::mpsc::Receiver; use std::io::{BufWriter, Error as IOError, stdout, Write}; use crate::dictionary::{Entry, Text}; use crate::errors::AppResultU; pub fn main(rx: Receiver<Option<Vec<Entry>>>) -> AppResultU { for entries in rx { if let Some(entries) = entries { print(entries)? ...
type Kilometers = i32; type Thunk = Box<dyn Fn() + Send + 'static>; fn main() { let x: i32 = 5; let y: Kilometers = 5; println!("x + y = {}", x + y); let _f: Box<dyn Fn() + Send + 'static> = Box::new(|| println!("hi")); let _ff: Thunk = Box::new(|| println!("hi")); /* print!("forever ");...
use hydroflow::hydroflow_syntax; use hydroflow::scheduled::graph::Hydroflow; use hydroflow::util::{UdpSink, UdpStream}; use crate::protocol::Message; use crate::{GraphType, Opts}; pub(crate) async fn run_server(outbound: UdpSink, inbound: UdpStream, opts: Opts) { println!("Server live!"); let mut df: Hydrofl...
use core::fmt; use core::marker::PhantomData; use core::mem::MaybeUninit; use core::result; use serde::de::{Deserialize, Deserializer, Error, SeqAccess, Visitor}; use serde::ser::{Serialize, SerializeTuple, Serializer}; pub(crate) struct PartiallyInitialized<T, const N: usize>( pub(crate) Option<MaybeUninit<[T; N]...
pub fn withdrawtoken() { loop { println!("withdraw a token"); break; } }
use super::*; /// A table. /// /// # Semantics /// /// There are two types of tables: /// /// - **org tables** can only contain [`TableRow`]s. /// - **table.el tables** don't have parsed content. /// /// # Syntax /// /// Tables start with a line starting with a vertical bar or the string `+-` followed by plus /// or b...
fn main() { let input = std::fs::read_to_string("../input.txt").unwrap(); let mut input: Vec<isize> = input .split("\n") .filter(|l| !l.is_empty()) .map(|l| l.parse::<isize>().unwrap()) .collect(); input.sort(); input.insert(0, 0); // the wall input.push(*input.iter()...
use std::fs::File; use std::io::prelude::*; fn read_data(filepath: &str) -> std::io::Result<String> { let mut file = File::open(filepath)?; let mut contents: String = String::new(); file.read_to_string(&mut contents)?; Ok(contents.trim().to_string()) } #[derive(Clone,Eq,PartialEq,Debug)] enum Token { ...
use ash::version::DeviceV1_0; use ash::vk; use crate::map_vk_error; use crate::vulkan::descriptor::DescriptorSetLayout; use crate::vulkan::{Device, VkError}; pub struct PipelineLayout { handle: vk::PipelineLayout, } impl PipelineLayout { #[inline] pub fn handle(&self) -> vk::PipelineLayout { self...
//! 件数取得APIのデータモデル //! //! 技術基準適合証明等を受けた機器の検索Web-APIのリクエスト条件一覧(Ver.1.1.1) //! //! https://www.tele.soumu.go.jp/resource/j/giteki/webapi/gk_req_conditions.pdf use serde::{Deserialize, Serialize}; use serde_aux::field_attributes::deserialize_number_from_string; /// 件数取得APIのリクエストパラメータ #[derive(Serialize)] pub struct Req...
#![allow(unused_parens)] use core::convert::TryInto; use core::mem; use {check_len, Error, Result, TryRead, TryWrite}; /// Endian of numbers. /// /// Default to machine's native endian. /// /// # Example /// /// ``` /// use byte::*; /// /// let bytes: &[u8] = &[0x00, 0xff]; /// /// let num_be: u16 = bytes.read_with(&...
fn main() { let s1 = String::from("hello"); let len = calculate_length(&s1); println!("The length of '{}' is {}.", s1, len); { let mut s = String::from("hello"); change(&mut s); println!("mutable reference: {}", s); } { let mut s = String::from("hello"); ...
use std::collections::HashMap; struct Combination { memo: HashMap<(i64, i64), i64>, } impl Combination { fn new() -> Combination { return Combination { memo: HashMap::new(), }; } fn combination(&mut self, n: i64, r: i64, m: i64) -> i64 { if let Some(res) = self.mem...
/* * addresspool management functions used with left/rightaddresspool= option. * Currently used for IKEv1 XAUTH/ModeConfig options if we are an XAUTH server. * * Copyright (C) 2013 Antony Antony <antony@phenome.org> * * This program is free software; you can redistribute it and/or modify it * under the terms of ...
use std::fmt::Display; use std::fs::File; use std::io::{BufRead, BufReader, Result}; use std::path::Path; use std::time::Instant; pub fn time<T: Display>(f: fn(&str) -> T, input: &str, part: &str) { let start = Instant::now(); let result = f(input); let end = Instant::now(); println!("Part {}: {}, took...
fn main() { proconio::input! { n: usize, s: i32, d: i32, magics: [(i32, i32); n] } let mut flg = false; for magic in magics { if magic.0 < s && magic.1 > d { flg = true; } } if flg { println!("Yes"); }else{ println...
pub fn datatype() { // Int Family let a = 20; // i32 println!("I32: {}", a); // Float Family let b = 3.14; // f64 println!("f64: {}", b); // Boolean let c = true; println!("Bool: {}", c); // Char || Single Digit String let d = 'W'; println!("Char: {}", d) }
use std::collections::HashMap; use std::collections::HashSet; use std::fs; // Words are in a csv format, in quotes and comma separated fn get_the_words(word_string: String) -> Vec<String> { let mut res: Vec<String> = Vec::new(); for s in word_string.split(",") { let mut char_vec: Vec<char> = s.chars()....
//! This module provides an anonymous authenticator use crate::auth::*; use async_trait::async_trait; /// /// [`Authenticator`](crate::auth::Authenticator) implementation that simply allows everyone. /// /// # Example /// /// ```rust /// # #[tokio::main] /// # async fn main() { /// use libunftp::auth::{Authenticator,...
// functions1.rs // Execute `rustlings hint functions1` or use the `hint` watch subcommand for a hint. // I AM NOT DONE fn main() { call_me(); }
use std::marker::{Reflect, PhantomData}; use std::fmt::{Debug, Display, Write, Formatter}; use std::ptr::{Unique, Shared}; use std::sync::atomic::{Ordering, AtomicUsize, AtomicBool}; use std::cell::{UnsafeCell, RefCell}; use std::iter::{IntoIterator, Iterator}; use alloc::boxed::Box; use alloc::raw_vec::RawVec...
#[doc = "Reader of register HOST_LVL2_SEL"] pub type R = crate::R<u32, super::HOST_LVL2_SEL>; #[doc = "Writer for register HOST_LVL2_SEL"] pub type W = crate::W<u32, super::HOST_LVL2_SEL>; #[doc = "Register HOST_LVL2_SEL `reset()`'s with value 0"] impl crate::ResetValue for super::HOST_LVL2_SEL { type Type = u32; ...
//! NDS GPU command parsing. //! //! A `CmdParser` allows consumers to iterate over NDS GPU commands stored in //! a buffer. This modules doesn't actually do anything with the commands, it //! just knows how they're stored in memory and provides them in a more easily- //! consumable form. //! //! See the [GBATEK docume...
#![allow(clippy::needless_raw_string_hashes)] pub const TEMPLATE: &str = r#"{{!-- This a test for `init.vim` --}} {{@if {{OS}} == "windows"}} set fileformat=dos {{@elif {{OS}} == "macos"}} set fileformat=mac {{@else}} set fileformat=unix {{@fi}} set ttyfast set relativenumber set number set encoding={{SYS_ENCODING}} s...
// Copyright (c) 2014 Robert Clipsham <robert@octarineparrot.com> // // 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>, at your // option. This file may not be copied, modified, or...
//! This module will collect metrics every interval N. //! This isn't done directly in the metrics endpoint, due to the time it takes to collect the metrics from MysQL use crate::appdata::AppData; use mysql::prelude::{Queryable, FromValue}; use mysql::Row; use std::fmt::Display; use std::collections::HashMap; ...
use crate::*; use rand::prelude::*; lazy_static! { pub static ref PERLIN: Perlin = Perlin::new(); } pub struct Perlin { ran_float: [Vector3; 256], perm_x: [usize; 256], perm_y: [usize; 256], perm_z: [usize; 256], } impl Perlin { fn new() -> Perlin { Perlin { ran_float: per...
#![allow(clippy::needless_doctest_main)] //! This crate provides the [`multiversion`] attribute for implementing function multiversioning. //! //! Many CPU architectures have a variety of instruction set extensions that provide additional //! functionality. Common examples are single instruction, multiple data (SIMD) e...
use crate::domain::domain::SysRes; use chrono::NaiveDateTime; use std::collections::HashMap; ///权限资源表 #[crud_table(table_name: "sys_res" | table_columns: "id,parent_id,name,permission,path,del")] #[derive(Clone, Debug)] pub struct SysResVO { pub id: Option<String>, //父id(可空) pub parent_id: Option<String>,...
// Run-time: // exec-arg: 1 // exec-arg: 2 3 use std::env; fn main() { println!("{:?}", env::args()); let arg1 = env::args() .nth(1) .expect("no arg 1 passed") .parse::<i32>() .expect("arg 1 should be numeric"); let arg2 = env::args() .nth(2) .unwrap();...
// Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The ASF licenses this file // to you under the Apache License, Version 2.0 (the // "License"); you may...
#![allow(clippy::upper_case_acronyms)] #[cfg(test)] mod tests; use pest_derive::Parser; /// The parser generated from `apllodb_sql.pest`. /// /// pest_derive::Parser macro puts `pub enum Rule` at this level. #[derive(Parser)] #[grammar = "pest_grammar/apllodb_sql.pest"] pub(super) struct GeneratedParser;
//! UAVCAN/CAN transport implementation. //! //! CAN will essentially be the "reference implementation", and *should* always follow //! the best practices, so if you want to add support for a new transport, you should //! follow the conventions here. //! //! Provides a unit struct to create a Node for CAN. This impleme...