text
stringlengths
8
4.13M
// This file is part of syslog. It is subject to the license terms in the COPYRIGHT file found in the top-level directory of this distribution and at https://raw.githubusercontent.com/lemonrock/syslog/master/COPYRIGHT. No part of syslog, including this file, may be copied, modified, propagated, or distributed except ac...
use std::env; use std::process::Command; use std::str; use std::str::FromStr; fn main() { if rustc_has_dyn_trait() { println!("cargo:rustc-cfg=has_dyn_trait"); } } fn rustc_has_dyn_trait() -> bool { let rustc = match env::var_os("RUSTC") { Some(rustc) => rustc, None => return false...
use crate::{Point, MEAN_EARTH_RADIUS}; use num_traits::{Float, FromPrimitive}; /// Returns a new Point using the distance to the existing Point and a bearing for the direction pub trait HaversineDestination<T: Float> { /// Returns a new Point using distance to the existing Point and a bearing for the direction ...
use std::collections::HashMap; use std::sync::Arc; use futures_core::future::BoxFuture; use serde::de::DeserializeOwned; use crate::connection::ConnectionSource; use crate::cursor::Cursor; use crate::executor::Execute; use crate::mysql::{MySql, MySqlArguments, MySqlConnection, MySqlRow, MySqlTypeInfo}; use crate::mys...
// This file is part of linux-epoll. It is subject to the license terms in the COPYRIGHT file found in the top-level directory of this distribution and at https://raw.githubusercontent.com/lemonrock/linux-epoll/master/COPYRIGHT. No part of linux-epoll, including this file, may be copied, modified, propagated, or distri...
use super::sys::*; use super::tree::*; use super::utils::*; #[derive(Debug, Clone)] pub struct Chunk { self_ptr: *const cabocha_chunk_t, } impl Chunk { pub fn new(raw_ptr: *const cabocha_chunk_t) -> Chunk { Chunk { self_ptr: raw_ptr } } pub fn link(&self) -> i32 { unsafe { (*self.self_ptr).link } }...
#[macro_use] extern crate quote; extern crate proc_macro; extern crate serde; extern crate serde_json; extern crate syn; use std::fs::File; use proc_macro::TokenStream; use serde::de::IgnoredAny; use syn::{DeriveInput, Lit, Meta, MetaNameValue}; #[proc_macro_derive(Validate, attributes(path))] pub fn validate_file(i...
//! A writfield1 buffer, with one or more snapshots. use arrow::record_batch::RecordBatch; use data_types::{sequence_number_set::SequenceNumberSet, TimestampMinMax}; use iox_query::util::compute_timenanosecond_min_max; use schema::{merge::merge_record_batch_schemas, Schema}; use super::BufferState; use crate::{ b...
#![allow(unused_variables, non_upper_case_globals, non_snake_case, unused_unsafe, non_camel_case_types, dead_code, clippy::all)] #[repr(transparent)] #[doc(hidden)] pub struct ISecondaryAuthenticationFactorAuthentication(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for ISecondaryAuthentica...
use super::{io, process, Runner, SubCommand}; use std::io::Write; impl<'api, 'pin> Runner<'api, 'pin> { pub fn upgrade(&self, cmd: &SubCommand) { debug!("Starting in upgrade"); match *cmd { SubCommand::SelfUpdate { check, download } => { if check && download { ...
use core::ops::ControlFlow; use firefly_diagnostics::{CodeMap, SourceSpan}; use firefly_intern::{symbols, Ident, Symbol}; use firefly_number::Integer; use firefly_pass::Pass; use crate::ast::*; use crate::lexer::DelayedSubstitution; use crate::visit::{self as visit, VisitMut}; /// This pass expands all delayed macro...
#[macro_use] mod common; use common::util::*; static UTIL_NAME: &'static str = "tr"; #[test] fn test_toupper() { let (_, mut ucmd) = testing(UTIL_NAME); let result = ucmd.args(&["a-z", "A-Z"]).run_piped_stdin("!abcd!"); assert_eq!(result.stdout, "!ABCD!"); } #[test] fn test_small_set2() { let (_, ...
use std::time::{Duration, Instant}; use futures::{Async, Future, Stream}; use tower::Service; use tower_grpc; use tokio_core::reactor::Handle; use super::codec::Protobuf; use super::pb::proxy::telemetry::{ReportRequest, ReportResponse}; use super::pb::proxy::telemetry::client::Telemetry as TelemetrySvc; use super::pb...
import std._vec; import std._str; import std.io; import std.option; import front.ast; import front.lexer; import util.common; import pp.end; import pp.wrd; import pp.space; import pp.line; const uint indent_unit = 4u; const int as_prec = 5; const uint default_columns = 78u; type ps = @rec(pp.ps s, opti...
//pub mod protocol_parser; //pub mod protocol; //pub mod errors; //pub use protocol::{OwnerType, TypeData, Step, Protocol}; //pub use protocol_parser::{Parser};
use super::prelude::*; #[get("/posts")] pub fn index(db: DbConnection) -> content::Html<String> { use crate::schema::posts::dsl::*; let psts = posts.load::<Post>(&db as &PgConnection).expect("Should load posts"); content::Html ( (html! { (header(Some("Posts"))); (navigation...
use crate::projection::Projection; use numpy::{IntoPyArray, PyArray1, PyArray2}; use pyo3::prelude::{pyfunction, pymodule, Py, PyModule, PyResult, Python}; use pyo3::wrap_pyfunction; use ndarray::{Ix1, Ix2, Array}; #[pyfunction] fn project_vec(py: Python<'_>, x: &PyArray1<f64>) -> Py<PyArray1<f64>> { Projection::<...
use crate::prelude::*; use crate::config; use crate::models; use sqlx::postgres::PgPoolOptions; #[derive(Clone)] pub struct Repo { pool: sqlx::Pool<sqlx::Postgres>, } impl Repo { pub async fn new(conf: &config::Settings) -> Result<Repo> { let pool = PgPoolOptions::new() .max_connections(4...
//xfail-stage1 //xfail-stage2 //xfail-stage3 use std; fn main() { obj inner() { fn a() -> int { ret 2; } fn m() -> uint { ret 3u; } fn z() -> uint { ret self.m(); } } let my_inner = inner(); let my_outer = obj () { fn b() -> uint { ret 5u; } fn...
use crate::record::cell::Cell; #[derive(Debug, PartialOrd, PartialEq, Clone)] pub enum Record { Header, Info(u32, u32), CellContent(Cell), CellFormat, Format, Options, Substitution, ExtLink, NameDefinitions, WindowDefinitions, ChartExtLink, EOF, } impl Record { pub ...
use crate::fd::OwnedFd; use crate::{backend, io, path}; pub use backend::fs::types::MemfdFlags; /// `memfd_create(path, flags)` /// /// # References /// - [Linux] /// - [glibc] /// - [FreeBSD] /// /// [Linux]: https://man7.org/linux/man-pages/man2/memfd_create.2.html /// [glibc]: https://www.gnu.org/software/libc/...
fn parse_config(args: &[String]) -> (&str, &str) { let query = &args[1]; let filename = &args[2]; (query, filename) }
enum Color { Rgb(i32, i32, i32), Hsv(i32, i32, i32) } enum Message { Quit, Move { x: i32, y: i32 }, Write(String), ChangeColor(Color), } struct Point { x: i32, y: i32, } struct Point3d { x: i32, y: i32, z: i32 } /// mix and match: `if let` with `if` and `else if` fn if_...
pub(crate) use _sysconfigdata::make_module; #[pymodule] pub(crate) mod _sysconfigdata { use crate::{builtins::PyDictRef, convert::ToPyObject, stdlib::sys::MULTIARCH, VirtualMachine}; #[pyattr] fn build_time_vars(vm: &VirtualMachine) -> PyDictRef { let vars = vm.ctx.new_dict(); macro_rules!...
mod num; mod util; use std::env; use std::path::PathBuf; use std::io::BufReader; use std::io::BufRead; use std::fs::File; fn main() { let v: Vec<String> = env::args().collect(); let args: Vec<&str> = v.iter().map(AsRef::as_ref).collect(); let (i, o, f, d, v) = util::parse_input(args); if f == None { ...
use crossterm::input::{InputEvent, KeyEvent, MouseButton, MouseEvent}; /// a valid user event #[derive(Debug, Clone)] pub enum Event { Key(KeyEvent), Click(u16, u16), DoubleClick(u16, u16), Wheel(i32), } impl Event { pub fn from_crossterm_event(crossterm_event: Option<InputEvent>) -> Option<Event>...
use algebra::UniformRand; use rand::Rng; use std::{fmt::Debug, hash::Hash}; use algebra::bytes::ToBytes; pub mod blake2s; pub mod injective_map; pub mod pedersen; use crate::Error; pub trait CommitmentScheme { type Output: ToBytes + Clone + Default + Eq + Hash + Debug; type Parameters: Clone; type Rando...
use jni::JNIEnv; use jni::objects::JClass; use jni::sys::jstring; pub extern "system" fn Java_com_github_xxx_yyy_MainActivity_init() { // TODO } pub extern "system" fn Java_com_github_xxx_yyy_MainActivity_stringFromJNI(env: JNIEnv, _class: ...
use reset_router::{Response, Router}; use std::{ env, net::{IpAddr, Ipv4Addr, SocketAddr}, }; mod handlers; use handlers::{auth, devices, exchange}; #[tokio::main] async fn main() -> Result<(), Box<dyn std::error::Error>> { // Get the port number to listen on. let port = env::var("PORT") .unwr...
//! Mock example //! //! Mocking an actor and setting it on the `SystemRegistry`. This can be //! done so you can test an actor that depends on a `SystemService` in isolation. #[cfg(test)] use actix::actors::mocker::Mocker; use actix::prelude::*; #[cfg(test)] use actix::SystemRegistry; #[derive(Default)] struct MyActo...
// This file was generated by gir (https://github.com/gtk-rs/gir) // from ../gir-files // DO NOT EDIT mod address; pub use self::address::{Address, NONE_ADDRESS}; mod auth; pub use self::auth::{Auth, NONE_AUTH}; mod auth_basic; pub use self::auth_basic::{AuthBasic}; mod auth_digest; pub use self::auth_digest::{Auth...
mod profiler; use self::profiler::Profiler; use std::fs::File; use std::ops::DerefMut; use std::rc::Rc; use std::str::FromStr; use bigint::{Address, Gas, H256, M256, U256}; use hexutil::read_hex; use evm::{ AccountCommitment, Context, HeaderParams, RequireError, SeqContextVM, SeqTransactionVM, TransactionAction,...
//! Audio Filters example. //! //! This example showcases basic audio functionality using [`Ndsp`]. #![feature(allocator_api)] use std::f32::consts::PI; use ctru::linear::LinearAllocator; use ctru::prelude::*; use ctru::services::ndsp::{ wave::{Status, Wave}, AudioFormat, AudioMix, InterpolationType, Ndsp, O...
use crate::position::Position; use crate::value::{Object, Value}; #[derive(Clone, Debug)] pub enum Error { Runtime(Value), Lexer(LexerError), Parser(ParserError), } impl Error { pub fn redeclaration_of_variable(pos: Position) -> Value { Error::runtime(pos, "redeclaration of variable".into()) ...
use amethyst::{ core::transform::Transform, input::{get_key, is_close_requested, is_key_down, VirtualKeyCode}, prelude::*, renderer::{Camera}, window::ScreenDimensions, assets::{AssetStorage, Loader, Handle}, renderer::{ImageFormat, SpriteSheet, SpriteSheetFormat, Texture}, }; use crate::com...
extern crate chrono; #[macro_use] extern crate diesel; extern crate dotenv; #[macro_use] extern crate log; #[macro_use] extern crate lazy_static; extern crate reqwest; extern crate serde_json; mod db; mod discord; mod error; mod schema; mod z3r; use std::{collections::HashMap, env}; use dotenv::do...
use std::collections::VecDeque; use proconio::{input, marker::Usize1}; fn solve(n: usize, _: usize, c: Vec<u8>, edges: Vec<(usize, usize)>) { let mut g = vec![vec![]; n]; for (u, v) in edges { g[u].push(v); g[v].push(u); } const INF: u32 = std::u32::MAX; let mut dp = vec![vec![INF;...
use console::style; use emoji; use error::Error; use std::process::Command; use PBAR; pub fn rustup_add_wasm_target() -> Result<(), Error> { let step = format!( "{} {}Adding WASM target...", style("[1/7]").bold().dim(), emoji::TARGET ); let pb = PBAR.message(&step); let output =...
use opentelemetry::metrics::MetricsError; use opentelemetry_prometheus::PrometheusExporter; use prometheus::{proto::MetricFamily, Encoder as _, TextEncoder}; use std::time::Duration; pub(crate) struct PrometheusPushOnDropExporter { exporter: PrometheusExporter, endpoint: String, } impl Drop for PrometheusPush...
#[derive(Clone)] pub struct Group<P: Peer> { id: GroupID, rate: f32, peers: HashMap<P::PublicKey, PeerAddr>, living_peers: Vec<P::PublicKey>, waiting_peers: HashMap<P::PublicKey, Vec<(P::PublicKey, P::Signature)>>, storage: Addr<DiskStorageActor>, } impl<P: 'static + Peer> Group<P> { pub fn...
// Copyright 2022 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 ...
#[allow(unused_imports)] use proconio::{marker::*, *}; #[allow(unused_imports)] use std::{cmp::Ordering, convert::TryInto}; #[allow(unused_imports)] use lib::*; #[fastout] fn main() { input! { n: i32, s: Chars, } let mut t = 0; let mut a = 0; for c in &s { match c { ...
use std::fmt; use super::{ffi, PowerDevice, PowerIterator}; use crate::platform::traits::BatteryManager; use crate::Result; #[derive(Default)] pub struct PowerManager; impl BatteryManager for PowerManager { type Iterator = PowerIterator; fn new() -> Result<Self> { Ok(PowerManager {}) } fn r...
//! Code generation for prefix-types. use abi_stable_shared::const_utils::low_bit_mask_u64; use core_extensions::{matches, SelfOps}; use syn::{punctuated::Punctuated, Ident, TypeParamBound, Visibility, WherePredicate}; use quote::{quote_spanned, ToTokens, TokenStreamExt}; use proc_macro2::Span; use as_derive_util...
pub mod lz78;
#[doc = r" Value read from the register"] pub struct R { bits: u32, } #[doc = r" Value to write to the register"] pub struct W { bits: u32, } impl super::DPDCTRL { #[doc = r" Modifies the contents of the register"] #[inline] pub fn modify<F>(&self, f: F) where for<'w> F: FnOnce(&R, &'w m...
use std::f64; use crate::simulation::colony::Colony; use crate::simulation::environment::Environment; use crate::neural_network::mlp::MLP; pub struct Simulation { pub environment: Environment, pub colony: Colony, } pub struct SimulationResult { pub num_iters: usize, pub food_returned_to_nest: f64, ...
use input_i_scanner::InputIScanner; fn main() { let stdin = std::io::stdin(); let mut _i_i = InputIScanner::from(stdin.lock()); macro_rules! scan { (($($t: ty),+)) => { ($(scan!($t)),+) }; ($t: ty) => { _i_i.scan::<$t>() as $t }; (($($t: ty),...
pub mod capture_policy;
use crate::objects::{game_data::GameData, node::Node}; /// distributes starting ressources to players pub fn setup_players(mut gd: GameData) -> GameData { for i in 0..gd.players.len() { let player_id = gd.players[i].id.clone(); let exec_ids = find_start_execs(&gd); for id in exec_ids { ...
use yew::prelude::*; use yew_router::components::RouterAnchor; use crate::app::AppRoute; pub struct EnterpriseGoogle { // link: ComponentLink<Self> } pub enum Msg {} impl Component for EnterpriseGoogle { type Message = Msg; type Properties = (); fn create(_: Self::Properties, _link: ComponentLink<Se...
// Copyright (c) The Starcoin Core Contributors // SPDX-License-Identifier: Apache-2.0 use crate::chain_service::BlockChainCollection; use actix::prelude::*; use anyhow::{format_err, Error, Result}; use config::NodeConfig; use crypto::HashValue; use executor::block_executor::BlockExecutor; use executor::executor::mock...
// Copyright (c) 2021 Quark Container Authors / 2018 The gVisor 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 ...
use std::ops::Deref; /// Trait to allow trimming ascii whitespace from a &[u8]. pub trait TrimAsciiWhitespace { /// Trim ascii whitespace (based on `is_ascii_whitespace()`) from the /// start and end of a slice. fn trim_ascii_whitespace(&self) -> &[u8]; } impl<T: Deref<Target = [u8]>> TrimAsciiWhitespace ...
#![recursion_limit = "10000"] mod comparison; mod constants; mod macros; mod nat_type; use crate::comparison::{Cmp, Comparison, Max, Min}; use crate::constants::*; use crate::macros::{add, digits, max, min, mul}; use crate::nat_type::{Add, Mul, Nat}; fn main() { println!("--- multiplication and addition ---"); ...
use core::convert::TryInto; use serde::{Deserialize, Serialize}; use crate::{ clock::ClockState, mpu, sdcard::{self, Settings, SD_BLOCK_SIZE}, SdCard, }; #[derive(Serialize, Deserialize, Debug)] pub struct LogEntry { timestamp: LogTimestamp, contents: LogContents, } #[derive(Serialize, Deser...
use std::cmp::Ordering; use std::fmt; use std::fs::File; use std::io::BufRead; use std::io::BufReader; use std::path::{Path, PathBuf}; #[derive(Clone, Eq)] pub struct Alias { pub alias: String, pub mime_type: String, } impl fmt::Debug for Alias { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { ...
use serenity::collector::CollectComponentInteraction; use serenity::model::interactions::InteractionResponseType; use serenity::{ client::Context, framework::standard::{macros::command, CommandResult}, model::prelude::Message, }; #[command("dropdowns")] #[description = "dropdowns"] async fn cmd_dropdowns(c...
use std::error::Error; use std::fmt::{Debug, Display}; use std::path::PathBuf; use std::time::Duration; use getopts::{Fail, Matches, Options}; pub const MAX_INPUT_CPLX_FLAG: &str = "max-cplx"; pub const INPUT_FILE_FLAG: &str = "input-file"; pub const IN_CORPUS_FLAG: &str = "in-corpus"; pub const NO_IN_CORPUS_FLAG: &s...
#[doc = "Reader of register RNG_HTCR"] pub type R = crate::R<u32, super::RNG_HTCR>; #[doc = "Writer for register RNG_HTCR"] pub type W = crate::W<u32, super::RNG_HTCR>; #[doc = "Register RNG_HTCR `reset()`'s with value 0x000c_aa74"] impl crate::ResetValue for super::RNG_HTCR { type Type = u32; #[inline(always)]...
use sdl_main::sdl_main; mod macros; mod shader; mod common; mod camera; mod sdl_main; mod draw_text; mod landscape; mod player_shape; mod model; mod mesh; mod bullet; mod enemy_ship; mod sound; mod start_screen; mod explosion; fn main() { sdl_main().unwrap(); }
use spin::RwLock; pub static FRAME_BUFFER: RwLock<Option<FramebufferInfo>> = RwLock::new(None); /// FramebufferInfo information #[repr(C)] #[derive(Debug)] pub struct FramebufferInfo { /// visible width pub xres: u32, /// visible height pub yres: u32, /// virtual width pub xres_virtual: u32, ...
use std::io; fn main() { loop { let mut input = String::new(); println!("\nType a \"good\" value:"); io::stdin().read_line(&mut input) .expect("Can't read your input"); let _value = match input.trim().parse::<i32>() { Ok(v) => match v { 0...
use tokio::sync::oneshot::Sender; use crate::{ actor::{Actor, AsyncContext}, context::Context, handler::{Handler, Message, MessageResponse}, }; /// Converter trait, packs message into a suitable envelope. pub trait ToEnvelope<A, M: Message> where A: Actor + Handler<M>, A::Context: ToEnvelope<A, M>...
use std::{convert::TryFrom, path::PathBuf}; use config::{Config, File}; use serde::Deserialize; #[derive(Deserialize, Clone)] pub struct Credentials { pub username: String, pub password: Option<String>, pub device_id: String, pub device_name: String, pub access_token: Option<String>, } #[derive(D...
use crate::enums; use crate::core; use std::time; use std::ptr::null_mut; use winapi::um::processthreadsapi::*; use winapi::um::tlhelp32::*; use winapi::um::handleapi::*; use winapi::um::winbase::*; use winapi::ctypes::c_void; use ntapi::ntexapi; use winapi::shared::minwindef::MAX_PATH; pub struct Process { handle...
use node::Node; use std::collections::BTreeMap; use std::net::{IpAddr,Ipv4Addr}; use std::time::Duration; use std::u64; use std::u32; // Trait methods cannot use 'Self'; &self or &mut self is OK // https://doc.rust-lang.org/error-index.html#E0038 pub trait LoadBalancing { //fn new() -> Self ; fn select_node(&m...
use spin::RwLock; use rcore_fs::dev::*; pub struct MemBuf(RwLock<&'static mut [u8]>); //一块用于模拟磁盘的内存 impl MemBuf { // 初始化参数为磁盘的头尾虚拟地址 pub unsafe fn new(begin: usize, end: usize) -> Self { use core::slice; MemBuf( // 我们使用读写锁 // 可以有多个线程同时获取 & 读 // 但是一旦有线程获取 &mu...
use crate::auth; use crate::handlers::types::*; use crate::Pool; use actix_web::{web, Error, HttpResponse}; use actix_web_httpauth::extractors::bearer::BearerAuth; use crate::controllers::task_controller::*; //http calls pub async fn create_task( db: web::Data<Pool>, auth: BearerAuth, space_name: web::Pa...
use std::fmt; struct Encoding { data: [i64; 24], len: usize, val: i64, } struct EncodingGenerator { count: i64, } impl Iterator for EncodingGenerator { type Item = Encoding; fn next(&mut self) -> Option<Encoding> { let mut enc = Encoding{data: [0i64; 24], len: 0, val: 0}; if...
// Copyright 2023 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 ...
#![allow(unused_variables, non_upper_case_globals, non_snake_case, unused_unsafe, non_camel_case_types, dead_code, clippy::all)] #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct IPdfRendererNative(pub ::windows::core::IUnkno...
use std::collections::BTreeMap; use std::fs::{create_dir_all, File}; use std::io::{BufWriter, Write}; use std::path::Path; use {Class, Result}; mod code; mod header; static MODULE_MAP: &str = include_str!("module.map"); pub fn write<P: AsRef<Path>>(path: P, classes: &BTreeMap<String, Class>) -> Result<()> { let ...
use anyhow::{anyhow, Result}; use code_writer::{write_bootstrap, write_code}; use parser::parse; use std::io::{BufWriter, Write}; use std::{env, ffi::OsStr}; use std::{fs::File, path::Path}; mod arithmetic_command; mod code_writer; mod command; mod parser; mod segment; fn main() -> Result<()> { let args: Vec<Stri...
// 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. use failure::Fail; use fuchsia_pkg::{BuildError, CreationManifestError, MetaPackageError}; use std::io; #[derive(Debug, Fail)] pub enum PmBuildError { ...
use crate::{Force, ForceToNode, Point, MIN_DISTANCE}; use petgraph::graph::{Graph, IndexType, NodeIndex}; use petgraph::EdgeType; use quadtree::{Element, NodeId, Quadtree, Rect}; #[derive(Copy, Clone, Debug)] struct Body { x: f32, y: f32, strength: f32, } impl Body { fn new(x: f32, y: f32, strength: f...
// use std::ops::*; // use std::fmt::*; // use traits::{Zero, One}; // use Math; // #[derive(PartialEq, Copy, Clone)] // pub struct Vector3<T> { // x: T, // y: T, // z: T // } // pub type Vector3i = Vector3<i32>; // pub type Vector3u = Vector3<u32>; // pub type Vector3f = Vector3<f32>; // impl<T> Vector3...
#[cfg(all(not(target_arch = "wasm32"), test))] mod test; use liblumen_alloc::erts::exception; use liblumen_alloc::erts::process::Process; use liblumen_alloc::erts::term::prelude::*; #[native_implemented::function(erlang:map_size/1)] pub fn result(process: &Process, map: Term) -> exception::Result<Term> { let boxe...
#[derive(Clone)] enum Movement { Up, Down, Left, Right, } impl From<u8> for Movement { fn from(b: u8) -> Self { match b { b'U' => Movement::Up, b'D' => Movement::Down, b'L' => Movement::Left, b'R' => Movement::Right, _ => unreachab...
/* Bob is a lackadaisical teenager. In conversation, his responses are very limited. Bob answers 'Sure.' if you ask him a question. He answers 'Whoa, chill out!' if you yell at him. He answers 'Calm down, I know what I'm doing!' if you yell a question at him. He says 'Fine. Be that way!' if you ...
use ffi; use error; use std::mem; use std::sync::Arc; use device::Device; use CommandBufferExt; use ImageExt; use MantleObject; use presentable_image::PresentableImage; pub struct CommandBuffer { device: Arc<Device>, cmd: ffi::GR_CMD_BUFFER, memory_refs: Vec<ffi::GR_MEMORY_REF>, } pub struct CommandBuf...
// Copyright 2019-2020 PolkaX. Licensed under MIT or Apache-2.0. use std::fmt; use std::ops::Deref; use std::result; use serde::{de::Error, Deserialize, Deserializer, Serialize, Serializer}; use serde_cbor::Value; use super::{Amt, Item, Node}; use crate::blocks::Blocks; impl<B> Serialize for Amt<B> where B: Blo...
const a: i32 = 0; fn main() { let a = 0; }
pub mod update_characters; pub use self::update_characters::*;
use std::fmt::{self, Debug, Display, Formatter}; /// A single-byte character. #[derive(Clone, Copy, Default, PartialEq, Eq, PartialOrd, Ord, Hash)] #[repr(transparent)] pub struct ByteChar(u8); impl ByteChar { /// Creates a new `ByteChar` from a byte. pub fn new(c: u8) -> Self { ByteChar(c) } /// Unwraps...
mod begin; mod bye; mod commit; mod discard; mod failure; mod hello; mod pull; mod record; mod reset; mod rollback; mod run; mod success; use crate::errors::*; use crate::types::*; use crate::version::Version; use begin::Begin; use bytes::*; use commit::Commit; use discard::Discard; use failure::Failure; use hello::Hel...
use actix_web::{fs::NamedFile, HttpRequest, Error, Result}; pub fn index(_req: &HttpRequest) -> Result<NamedFile> { Ok(NamedFile::open("public/index.html")?) } pub fn path(_req: &HttpRequest) -> Result<NamedFile> { Ok(NamedFile::open("public/index.html")?) }
#![allow(unused_attributes)] #![feature(no_coverage)] use fuzzcheck::mutators::testing_utilities::test_mutator; use fuzzcheck::DefaultMutator; #[derive(Clone, Debug, PartialEq, Eq, Hash, DefaultMutator)] struct S<T, const M: usize, const N: usize = 8> { x: [T; N], y: [bool; M], } #[test] fn test_const_generi...
use crate::AST; // todo: remove redundant forward impl AST { pub fn rewrite(&self) -> AST { match self { AST::Function { .. } => self.clone(), // ```rs // AST::AdditiveExpression { terms, position } => { // let mut new = vec![]; // for e in terms ...
use super::{ HashedPassword, PasswordHasher, HashSalt }; use std::io; use std::ptr; use std::mem; use std::intrinsics::volatile_set_memory; /// The maximum length of the clear text password buffer. /// /// If you decide to lower this length, you are a bad /// person. If, however, you decide that you need more /// p...
pub fn swap(arr: &mut [i32], i: usize, j: usize) { let tmp = arr[i]; arr[i] = arr[j]; arr[j] = tmp } pub fn partion(arr: &mut [i32]) -> usize { let mut j: usize = 1; for n in 1..arr.len() { if arr[n] < arr[0] { swap(arr, n, j); j += 1; } } swap(arr, ...
use clap::{crate_description, crate_name, crate_version, App, Arg}; use morgan_tokenbot::drone::{run_drone, Drone, DRONE_PORT}; use morgan_tokenbot::socketaddr; use morgan_interface::signature::read_keypair; use std::error; use std::net::{Ipv4Addr, SocketAddr}; use std::sync::{Arc, Mutex}; use std::thread; fn main() -...
use std::collections::HashMap; use std::collections::VecDeque; use std::hash::Hash; pub mod graph_builders; pub struct Graph<T> where T : Clone + Eq + Hash { directed : bool, nodes : Vec<T>, node_indices : HashMap<T, usize>, adjacency_list : Vec<Vec<usize>>, } #[derive(PartialEq, Eq,...
#[get("/")] pub fn other() -> &'static str { "yolo!" }
use crate::traits::CkbChainInterface; use ckb_std::error::SysError; use ckb_std::high_level::load_tx_hash; pub struct CKBChain {} impl CkbChainInterface for CKBChain { fn load_tx_hash(&self) -> Result<[u8; 32], SysError> { load_tx_hash() } }
use std::cmp::{max, min}; use std::fmt; ///A Player is either Order or Chaos. #[derive(Ord, PartialOrd, Eq, PartialEq, Copy, Clone, Debug)] pub enum Player { Order, Chaos, } impl Player { ///Print out the current player type. pub fn display(&self) -> &'static str { match self { Pla...
mod common; use std::env; use std::io::{stdout, Write}; use env_logger; use rn2xx3::{ConfirmationMode, DataRateEuCn, JoinMode}; fn main() { env_logger::init(); let args: Vec<String> = env::args().collect(); if args.len() != 6 { println!("Join the network via OTAA and send an uplink."); ...
// Copyright 2021 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 ...
// 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. #![cfg(test)] use { failure::Error, fidl_fuchsia_paver::{Configuration, PaverRequest, PaverRequestStream}, fidl_fuchsia_sys::LauncherProxy, ...
/// running code on cleanup with the `Drop` trait #[derive(Debug)] pub struct CustomSmartPointer { pub data: String, } impl Drop for CustomSmartPointer { fn drop(&mut self) { println!("Dropping CustomSmartPointer with data `{}`!", self.data); } }