text
stringlengths
8
4.13M
use super::*; use tcp_typed::Notifier; #[derive(Debug)] pub enum Inner { Connecting(InnerConnecting), ConnectingLocalClosed(InnerConnectingLocalClosed), Connected(InnerConnected), RemoteClosed(InnerRemoteClosed), LocalClosed(InnerLocalClosed), Closing(InnerClosing), Closed, Killed, } impl Inner { pub fn conne...
use proconio::input; fn main() { input! { l: u64 } let ans = binom_knuth(l-1, std::cmp::min(l-12, 11)); println!("{}", ans) } pub fn binom_knuth(n: u64, k: u64) -> u64 { (0..n + 1) .rev() .zip(1..k + 1) .fold(1, |mut r, (n, d)| { r *= n; r /= d; r }) }
use legion::*; use crate::{ app_state::AppState, hierarchy::Children, }; #[derive(Clone, Debug)] pub struct Transform2D { pub translation: glam::Vec3, pub rotation: f32, } impl Transform2D { pub fn new(translation: &glam::Vec3, rotation: f32) -> Self { Self { translation: trans...
#[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::ROMSWMAP { #[doc = r"Modifies the contents of the register"] #[inline(always)] pub fn modify<F>(&self, f: F) where for<'w> F: FnOnce(&R,...
use crate::{app_env::get_env, datastore::prelude::*}; use googapis::google::datastore::v1; use v1::{ run_query_request::QueryType, Entity, EntityResult, GqlQuery, QueryResultBatch, RunQueryRequest, Value, }; use super::utils::{value_to_gql_param, PathToRef}; pub async fn run_query_id<'a>( client: &Client...
// This pub module only tests that the code inside compiles #![allow(clippy::derive_partial_eq_without_eq)] #![allow(dead_code)] use std::{ cmp::{Eq, Ord, PartialEq, PartialOrd}, error::Error as ErrorTrait, fmt::{self, Debug, Display, Write as FmtWriteTrait}, io::{ self, BufRead as IoBufReadTra...
use super::dyn_sized::{self, DynSized}; use std::marker::Unsize; use std::mem; use std::ops::{Deref, DerefMut}; /// The storage format for thin pointers. Stores the metadata and the value together. #[derive(Debug)] #[repr(C)] pub struct ThinBackend<D, T> where D: DynSized + ?Sized, T: ?Sized { pub meta: D...
use std::string::String; pub struct Node { // TODO: Use string is just for convenient. Replace it for saving the 24 byte as much as possible. // Maybe just a position of Lineno to the main text, // Since a size fixed "string" cannot be adjusted according to the input length. pub text: String }
// For macro spans #![feature(proc_macro_span)] extern crate proc_macro; use proc_macro::{TokenStream, TokenTree}; #[proc_macro] pub fn python(input: TokenStream) -> TokenStream { print(input); todo!() } fn print(input: TokenStream) { for t in input { if let TokenTree::Group(g) = t { ...
//= { //= "output": { //= "1": [ //= "\u0000\u0001\u0002\u0003\u0004\u0005\u0006\u0007\b\t\n\u000b\f\r\u000e\u000f\u0010\u0011\u0012\u0013\u0014\u0015\u0016\u0017\u0018\u0019\u001a\u001b\u001c\u001d\u001e\u001f !\"\\#\\$%\\&'\\(\\)\\*\\+,\\-\\./0123456789:;<=>\\?@ABCDEFGHIJKLMNOPQRSTUVWXYZ\\[\\\\\\]\\^_`abc...
#[macro_use] extern crate diesel; table! { users { id -> Integer, } } #[derive(Insertable)] #[table_name = "self::users"] struct UserOk { id: i32, } #[derive(Insertable)] #[table_name(self::users)] struct UserWarn { id: i32, } #[derive(Insertable)] #[table_name] struct UserError1 { id: i...
//! Method has type parameters. use near_bindgen::near_bindgen; use borsh::{BorshDeserialize, BorshSerialize}; #[near_bindgen] #[derive(Default, BorshDeserialize, BorshSerialize)] struct Incrementer { value: u32, } #[near_bindgen] impl Incrementer { pub fn method<'a, T: 'a + std::fmt::Display>(&self) { ...
use binary_search::BinarySearch; use procon_reader::ProconReader; use std::collections::HashMap; fn main() { let stdin = std::io::stdin(); let mut rd = ProconReader::new(stdin.lock()); let n: usize = rd.get(); let points: Vec<(u32, u32)> = (0..n) .map(|_| { let x: u32 = rd.get(); ...
#![allow(dead_code)] use core::mem::transmute; pub struct Message<'a> { pub msg_type: MsgType, pub operation: u8, pub data: &'a [u8], } #[repr(u8)] #[non_exhaustive] #[derive(Debug, Copy, Clone)] pub enum MsgType { Reserved = 0, Error = 1, System = 2, Ack = 3, Reboot = 4, Macro = 5...
fn foo(v1: Vec<i32>, v2: Vec<i32>) -> (Vec<i32>, Vec<i32>, i32) { (v1, v2, 42) } fn main() { let v1 = vec![1, 2, 3]; let v2 = vec![1, 3, 3]; let (v1, v2, answer) = foo(v1, v2); println!("{:?}, {:?}, {}", v1, v2, answer); }
fn main() { let d = Data { name: "data1".to_string(), value: 10 }; let mut d2 = Data { name: "data2".to_string(), value: 5}; println!("{:?}", d); println!("{:?}", d2); d2.name.push_str("-up"); d2.value += 3; println!("{:?}", d2); } #[derive(Debug)] struct Data { name: String, value: i32 }
//! All the traits exposed to be used in other custom pallets use crate::*; use codec::{Decode, Encode}; use frame_support::{dispatch, ensure}; use scale_info::TypeInfo; /// Mixer trait definition to be used in other pallets pub trait MixerInterface<T: Config<I>, I: 'static = ()> { // Creates a new mixer fn create( ...
use arci::{Error, JointTrajectoryClient, TrajectoryPoint}; use async_trait::async_trait; use k::nalgebra as na; use k::Isometry3; use serde::{Deserialize, Serialize}; use std::{collections::HashMap, sync::Arc}; use tokio::sync::Mutex; type ArcJointTrajectoryClient = Arc<dyn JointTrajectoryClient>; pub fn isometry(x: ...
use std::fs::File; use std::io::BufReader; use std::io::Read; fn slope(lines: &mut std::str::Lines, lines_len: usize, right: usize, down: usize) -> i64 { let mut trees = 0; let mut line_num : usize = 0; for line in lines { line_num += 1; if line_num % down != ...
pub use self::base::*; pub use self::bitwise::Bitwise; pub use self::iterable::*; pub use self::string::*; pub mod base; pub mod string; pub mod bitwise; pub mod iterable;
use super::data::*; use super::network::*; use chrono::{DateTime, Utc}; use std::collections::HashMap; /* * Node to node private cluster communication * */ pub trait ClusterCommunicator { /* * Cluster management * */ fn send_message(&self, target: &str, msg: &Message) -> bool; fn handle_message(&...
use std::io; use std::sync::Arc; use futures::future::{err, Future}; use futures::stream::Stream; use hyper::client::HttpConnector; use hyper::{Client, Request, Method, Uri}; use native_tls::TlsConnector; use tokio_core::net::TcpStream; use tokio_core::reactor::Core; use tokio_service::Service; use tokio_tls::{TlsConn...
use num::bigint::BigUint; use num::traits::ToPrimitive; use num::one; use num::zero; pub struct Fib { prev2: [BigUint; 2], } impl Fib { pub fn new() -> Fib { Fib { prev2: [zero(), zero()] } } } impl Iterator for Fib { type Item = BigUint; fn next(&mut self) -> Option<BigUint> { i...
mod code; mod code_extern; mod code_node; mod context; mod exec; mod graph; mod value; mod variable; use std::collections::BTreeMap; use self::graph::Graphs; pub use self::context::{CompactContext, DecompactContext}; pub use self::exec::Program; pub trait Compact { type Output; fn compact(&self, ctx: &mut ...
#![unstable] pub enum Target { Assembly, Brainfuck, DT, Ook, Whitespace, } pub fn detect_target(option: Option<String>, filename: &String) -> Option<Target> { match option { Some(ref val) => match val.as_slice() { "asm" => Some(Assembly), "bf" => Some(Brainfuck...
use proconio::{input, marker::Bytes}; fn main() { input! { n: usize, s: Bytes, }; for i in 1..n { let ans = s.iter().zip(s[i..].iter()).take_while(|(b1, b2)| b1 != b2).count(); println!("{}", ans); } }
extern crate proconio; use proconio::input; fn main() { input! { n: usize, k: usize, mut p: [usize; n], c: [i64; n], } let p = p.iter().map(|x| x - 1).collect::<Vec<_>>(); let mut q = vec![0; n]; for (i, &x) in p.iter().enumerate() { q[x] = i; } let m...
//! This module contains helpers when writing pools for objects //! that don't support async and need to be run inside a thread. use std::{ any::Any, fmt, marker::PhantomData, sync::{Arc, Mutex}, }; use crate::{runtime::SpawnBlockingError, Runtime}; /// This error is returned when the [`Connection::i...
extern crate sdl2; extern crate rand; use sdl2::pixels::Color; use sdl2::rect; use sdl2::event::Event; use sdl2::keyboard::Keycode; use rand::Rng; use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::mpsc; use std::sync::Arc; use std::thread; use std::time::{Duration, Instant}; const X: usize = 1280; const...
mod interop; use crate::{ config_paths::CONFIG_PATHS, event::Event, topology::config::{DataType, TransformContext}, transforms::{ util::runtime_transform::{RuntimeTransform, Timer}, Transform, }, }; use serde::{Deserialize, Serialize}; use snafu::{ResultExt, Snafu}; use std::path::P...
use std::error::Error; use std::path::PathBuf; use crate::commands::Command; use crate::config::Config; use crate::config::{DotItem, DotType}; use crate::error::{SourceFileIsDottied, SymlinkSourceNotSupported, UnknownFileType}; use crate::fs::File; use crate::{show_error, show_info}; pub struct AddOpt { path: Str...
pub mod riscv_vm; pub mod memory; pub mod instruction; pub mod defines; pub mod bit_utils;
// 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. //! Watchers handles a list of watcher connections attached to a directory. Watchers as described //! in io.fidl. use { failure::Fail, fidl_fuchs...
//! x86-64 Linux system calls. use crate::backend::reg::{ ArgReg, FromAsm, RetReg, SyscallNumber, ToAsm, A0, A1, A2, A3, A4, A5, R0, }; use core::arch::asm; #[cfg(target_pointer_width = "32")] compile_error!("x32 is not yet supported"); #[inline] pub(in crate::backend) unsafe fn syscall0_readonly(nr: SyscallNumb...
// See LICENSE file for copyright and license details. pub mod visualizer; pub mod mgl; pub mod camera; pub mod types; pub mod geom; pub mod picker; pub mod obj; pub mod mesh; pub mod event_visualizer; pub mod shader; pub mod texture; pub mod font_stash; pub mod scene; pub mod gui; pub mod selection; pub mod context; ...
mod with_false_left; mod with_true_left; use proptest::prop_assert_eq; use proptest::test_runner::{Config, TestRunner}; use crate::erlang::or_2::result; use crate::test::strategy; #[test] fn without_boolean_left_errors_badarg() { crate::test::without_boolean_left_errors_badarg(file!(), result); }
use std::{ fmt::{Debug, Display}, sync::Arc, }; use data_types::ParquetFile; use crate::{file_classification::FileClassification, partition_info::PartitionInfo, RoundInfo}; pub mod logging; pub mod split_based; pub trait FileClassifier: Debug + Display + Send + Sync { fn classify( &self, ...
mod utils;
use std::hash::Hasher; pub use json_utils::json::JsValue; const HASH_PREFIX_NULL: u8 = 0; const HASH_PREFIX_BOOL: u8 = 1; const HASH_PREFIX_NUMBER: u8 = 2; const HASH_PREFIX_STRING: u8 = 3; const HASH_PREFIX_ARRAY: u8 = 4; const HASH_PREFIX_OBJECT: u8 = 5; pub fn js_value_hash<H: Hasher>(value: &JsValue, hasher: &mu...
use blockstore::Blockstore; use config::Config; use merkledag::DagService; use std::sync::Arc; pub struct IpfsNode { pub config: Config, pub blockstore: Arc<Blockstore>, pub dagservice: Arc<DagService>, } impl IpfsNode { pub fn new(blockstore: Blockstore, cfg: Config) -> Self { let bs = Arc::...
#![link(name="git2")] extern crate git2; use git2::git2; use git2::git2::{OID, ToOID}; #[test] fn test_oid() { let repo = match git2::Repository::open(&Path::new("/storage/home/achin/devel/libgit2.rs/tests/data/repoA")) { Ok(r) => r, Err(e) => fail!("Failed to open repo:\n{}", e.message) }; ...
use chrono::NaiveDateTime; use diesel; use diesel::dsl::{exists, select}; use diesel::expression::dsl; use diesel::prelude::*; use models::scopes; use models::*; use schema::{organization_users, organizations, users, venues}; use utils::errors::*; use uuid::Uuid; #[derive(Identifiable, Associations, Queryable, AsChang...
use super::{opengl, Filter, Wrap, Texture, TextureHolder}; use super::opengl::{Attachment, Framebuffer}; use crate::error::{GameError, GameResult}; use crate::math::Size; use crate::engine::Engine; use std::rc::Rc; pub struct Canvas { framebuffer: Rc<Framebuffer>, texture: Texture, } impl Canvas { pub fn...
use std::io::{Read, Write}; use std::net::{TcpStream, Shutdown}; use std::thread; use std::sync::{Arc, Mutex}; use std::sync::mpsc::{channel, Sender, Receiver, TryRecvError}; use byteorder::{BigEndian, ReadBytesExt}; use ::{zrle, protocol, Rect, Colour, Error, Result}; use protocol::Message; use security::des; #[cfg(fe...
use actix_web::{AsyncResponder, FutureResponse, HttpResponse, Json, State}; use futures::Future; use super::super::model::user::{SigninUser, SignupUser}; use super::super::share::state::AppState; pub fn signup( (signup_user, state): (Json<SignupUser>, State<AppState>), ) -> FutureResponse<HttpResponse> { stat...
#[doc = "Reader of register SECCFGR2"] pub type R = crate::R<u32, super::SECCFGR2>; #[doc = "Writer for register SECCFGR2"] pub type W = crate::W<u32, super::SECCFGR2>; #[doc = "Register SECCFGR2 `reset()`'s with value 0"] impl crate::ResetValue for super::SECCFGR2 { type Type = u32; #[inline(always)] fn re...
use test_interop::{ Windows::Foundation::Collections::StringMap, Windows::Win32::System::Com::{CoInitializeEx, COINIT_MULTITHREADED}, Windows::Win32::System::WinRT::RoActivateInstance, }; use windows::core::{Interface, Result}; // Calling RoActivateInstance is a useful interop test because it is a functio...
use amiquip::{ Auth, Connection, ConnectionOptions, ConnectionTuning, ExchangeDeclareOptions, ExchangeType, FieldTable, Publish, QueueDeclareOptions, }; use log::{info, LevelFilter}; use mio::net::TcpStream; use native_tls::{Certificate, Identity, TlsConnector}; use simple_logger::SimpleLogger; use std::{fs, pa...
pub(crate) trait Converts<A, B> { fn convert(&self, a: A) -> B; }
pub struct Line { pub xbeg: f64, pub ybeg: f64, pub xend: f64, pub yend: f64, // If finite = false, line ends at (xend, yend) // Otherwise, line goes past (xend, yend) pub finite: bool }
#![allow(unused_variables, non_upper_case_globals, non_snake_case, unused_unsafe, non_camel_case_types, dead_code, clippy::all)] #[cfg(feature = "Perception_Spatial_Preview")] pub mod Preview; #[cfg(feature = "Perception_Spatial_Surfaces")] pub mod Surfaces; #[repr(transparent)] #[doc(hidden)] pub struct ISpatialAnchor...
//! Utilities for common diff related operations. //! //! This module provides specialized utilities and simplified diff operations //! for common operations. It's useful when you want to work with text diffs //! and you're interested in getting vectors of these changes directly. //! //! # Slice Remapping //! //! When...
// 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...
#![cfg(feature = "macros")] use std::{ sync::{ atomic::{AtomicBool, AtomicUsize, Ordering}, mpsc, Arc, }, time::Duration, }; use actix::prelude::*; use actix_rt::time::{sleep, Instant}; #[derive(Clone, Debug)] struct Num(usize); impl Message for Num { type Result = (); } struct MyAc...
#[cfg(feature = "fast_shanten")] mod fast_hand_calculator; pub mod hand; pub mod riichi_error; pub mod rules; pub mod scores; #[cfg(not(feature = "fast_shanten"))] mod shanten; mod shape_finder; pub mod shapes; pub mod table; pub mod tile; pub mod yaku;
use super::random_bytes; use cipher::{ctr::AES_128_CTR, Cipher}; use encoding::base64::*; use std::fs; #[derive(Default)] pub struct Key(Vec<u8>); impl Key { pub fn new() -> Key { Key(random_bytes(16)) } pub fn successive_encryption(&self) -> Vec<Vec<u8>> { let pt_str = fs::read_to_string(...
use std::error; mod common; #[test] fn test_arg_error_display() { let error = wordcount_core::Error::new(common::EXPECTED_ERROR); assert_eq!(String::from(common::EXPECTED_ERROR), format!("{}", error)); } #[test] fn test_arg_error_debug() { let error = wordcount_core::Error::new(common::EXPECTED_ERROR); ...
use crate::{Context, Krate}; use failure::Error; use tame_gcs::objects::{InsertObjectOptional, Object}; pub fn to_gcs(ctx: &Context<'_>, source: bytes::Bytes, krate: &Krate) -> Result<(), Error> { use bytes::{Buf, IntoBuf}; let content_len = source.len() as u64; let insert_req = Object::insert_simple( ...
use crate::types_structs::{Enum, Struct, Trait}; ///Supported types #[derive(Debug)] pub enum Types { Struct, Trait, Enum, } #[derive(Debug)] pub enum TypeHolder { Struct(Struct), Trait(Trait), Enum(Enum), } impl TypeHolder { pub fn generate_interface(&mut self) -> String { match ...
use std::mem::MaybeUninit; /// This crate contains methods for modifying arrays and converting /// them to vectors and back. use std::ptr; /// This trait helps to join array with a new element. pub trait Stick<T> { type Target; /// Appends an item to an array: /// ```rust /// # extern crate no_vec; ...
use crate::hlist::*; use core::cell::UnsafeCell; pub unsafe trait Identifier { type Id; fn id(&self) -> Self::Id; fn check_id(&self, id: &Self::Id) -> bool; } pub unsafe trait Transparent {} #[repr(transparent)] pub struct Owner<I> { pub ident: I, } #[repr(C)] pub struct ICell<Id, T: ?Sized> { ...
use macroquad::prelude::*; pub const GAME_SIZE: Vec2 = const_vec2!([514., 256.]); pub const GRAVITY: f32 = 30f32; pub const MOVE_SPEED: f32 = 200f32; pub const MAX_JUMP_STRENGTH: f32 = 12f32;
mod mem_map; use sinks::*; use self::mem_map::*; // Docs claim the sample rate is 41.7khz, but my calculations indicate it should be 41666.66hz repeating // (see SAMPLE_CLOCK_PERIOD calculation below), so we take the nearest whole-number sample rate to that. // Note that the documentation rounds values in a lot of...
use std::io; use std::io::Write; pub fn solution(){ let mut name: String = String::new(); let mut age: String = String::new(); let mut reddit_name: String = String::new(); print!("What is your name? "); io::stdout().flush().unwrap(); io::stdin().read_line(&mut name).unwrap(); print!("What...
use nom::{ error::{ErrorKind, ParseError}, Compare, CompareResult, Err, ExtendInto, FindSubstring, FindToken, IResult, InputIter, InputLength, InputTake, InputTakeAtPosition, Needed, Offset, Slice, }; use std::convert::TryInto; use std::ops; use std::str::{CharIndices, Chars}; use std::u32; #[derive(Debug,...
#[macro_use] extern crate lazy_static; use rand::Rng; use std::io::Write; mod vec3d; use vec3d::Vec3d; lazy_static! { static ref ROOT_PARTICLES: Vec<Vec3d> = { use std::f64::consts::PI; let mut acc = Vec::new(); let n = 10; for i in 0..n { acc.push(Vec3d::new( ...
use tree_sitter::Node; use crate::lint::core::{ValidationError, Validator}; use crate::lint::grammar::UNSAFE; use crate::lint::rule::RULE_UNSAFE_CODE; pub struct UnsafeCodeValidator; impl Validator for UnsafeCodeValidator { fn validate(&self, node: &Node, _source: &str) -> Result<(), ValidationError> { i...
use std::collections::HashMap; use std::fmt::Display; use std::fs::File; use std::io::{BufRead, BufReader}; use std::path::PathBuf; use std::u64; use anyhow::{bail, Context, Result}; use lazy_static::lazy_static; use regex::Regex; use structopt::StructOpt; const PRINT_EVERY_N_SECS: f32 = 3.; const PRINT_TOP_N: usize ...
use std::fmt; use std::num::NonZeroUsize; /// An opaque identifier that is associated with AST items. /// /// The default implementation for an identifier is empty, meaning it does not /// hold any value, and attempting to perform lookups over it will fail with an /// error indicating that it's empty with the string `...
/// Floating point values can not be ordered / hashed in Rust by default /// (which is the correct thing to do but annoying if you want dynamically /// typed sets and hashtables!). /// This module provides a very lightweight wrapper around f64s that /// implements ordering and hashing which is `good enough` for PICL. u...
use models::error::RuntimeError; use std::time::Instant; use tokio::prelude::*; use utils::stream::connect; pub fn new() -> ( impl Sink<SinkItem = Instant, SinkError = RuntimeError>, impl Stream<Item = String, Error = RuntimeError>, ) { let (input, output) = connect::<Instant>(); ( input, ...
use stackable_kafka_crd::KafkaCluster; use std::error::Error; fn main() -> Result<(), Box<dyn Error>> { println!("{}", serde_yaml::to_string(&KafkaCluster::crd())?); Ok(()) }
use std::env; fn main() { let my_input = env::var("INPUT_MYINPUT").unwrap_or_default(); let output = format!("Hello {}", my_input); println!("::set-output name=myOutput::{}", output); }
mod error; mod play_flag; use crate::play_flag::{GstPlayFlags, GST_PLAY_FLAG_VIS}; use gstreamer::prelude::*; use gstreamer::*; /* Return TRUE if this is a Visualization element */ fn filter_vis_features(feature: &PluginFeature) -> bool { match feature.downcast_ref::<ElementFactory>() { Some(factory) => f...
// Copyright 2013 The Servo 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>, at ...
// 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 2020 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to i...
// 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 ...
use crate::base::data::inverse_fields_map::INVERSE_FIELDS_MAP; use crate::base::serialize::serialized_type::*; //TypeObjBulder usage. //let type_obj = TypeObjBuilder::new("key").build(); //println!("type_obj: {:?}", type_obj); //header pub trait SerializeHeader { fn serialize_header(&self, so: &mut Vec<u8>); } #...
#[derive(Debug)] enum Participant { CAR, TRAIN } #[derive(Debug)] enum ParticipantCommand { GO, STOP } fn move_barriers_mediator(p: &Participant, c: ParticipantCommand) { println!("Mediation!"); match *p { Participant::CAR => { match c { ParticipantCommand:...
// Copyright 2018 Steve Smith (tarkasteve@gmail.com). 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...
// Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or // http://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 distributed except according to those terms. use super::{Statement, St...
// Copyright 2016 Sascha Haeberling // // 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...
use once_cell::sync::OnceCell; use tauri_api::cli::Matches; static MATCHES: OnceCell<Matches> = OnceCell::new(); pub(crate) fn set_matches(matches: Matches) -> crate::Result<()> { MATCHES .set(matches) .map_err(|_| anyhow::anyhow!("failed to set once_cell matches")) } pub fn get_matches() -> Option<&'stati...
pub fn compress<T: Copy + PartialEq>(li: &Vec<T>) -> Vec<T> { if li.is_empty() { vec![] } else { let mut res = vec![li[0]]; for i in 1..li.len() { if li.get(i) != res.last() { res.push(*li.get(i).unwrap()); } } res } } #[cfg(te...
// Copyright 2018 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
mod printing { pub mod math{ pub fn table(data:u32){ println!("Calcuations"); for count in 1..=3{ println!("{}*{}={}", data,count,data*count); } } } } pub mod lib; use std::io; fn main() { loop { println!("Please input your number:...
use std::time::{Duration, SystemTime}; use std::fs::File; use pcap_file::PcapWriter; use super::options::*; pub fn do_command<T, I, E>(radio: &mut T, operation: Operation) -> Result<(), E> where T: radio::Transmit<Error=E> + radio::Power<Error=E> + radio::Receive<Info=I, Error=E> + radio::Rssi<Error=E> + rad...
use crate::{ builder::{ self, session_setup_authenticate_request::build_default_session_setup_authenticate_request, session_setup_negotiate_request::build_default_session_setup_negotiate_request, }, format, fuzzer::{self, FuzzingStrategy}, ntlmssp::MessageType, smb2::{ he...
//! Helpers concerning [`object_store`](::object_store) interaction. pub mod ignore_writes; pub mod metrics;
mod stop_signs; mod traffic_signals; use crate::common::CommonState; use crate::debug::DebugMode; use crate::game::{State, Transition, WizardState}; use crate::helpers::{ColorScheme, ID}; use crate::render::{ DrawCtx, DrawIntersection, DrawLane, DrawMap, DrawOptions, DrawTurn, Renderable, MIN_ZOOM_FOR_DETAIL, ...
use std::io; use std::io::Read; use regex::Regex; fn matches_rule(val: u16, rule: (u16, u16, u16, u16)) -> bool { (rule.0 <= val && val <= rule.1) || (rule.2 <= val && val <= rule.3) } fn main() { let mut input = String::new(); io::stdin().read_to_string(&mut input).unwrap(); let re_rule = Regex::ne...
use std::{error, fmt}; /// Error's that originate from the client or server; #[derive(Debug)] pub struct Error(crate::Error); impl Error { pub(crate) fn from_source(source: impl Into<crate::Error>) -> Self { Self(source.into()) } } impl fmt::Display for Error { fn fmt(&self, f: &mut fmt::Formatte...
//! linux_raw syscalls supporting `rustix::event`. //! //! # Safety //! //! See the `rustix::backend` module documentation for details. #![allow(unsafe_code)] #![allow(clippy::undocumented_unsafe_blocks)] use crate::backend::c; use crate::backend::conv::{ by_ref, c_int, c_uint, pass_usize, raw_fd, ret, ret_owned_f...
#[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::_3_FLTSRC1 { #[doc = r"Modifies the contents of the register"] #[inline(always)] pub fn modify<F>(&self, f: F) where for<'w> F: FnOnce(&...
//! A BeachMap is just a SlotMap, a data structure used to store elements and access them with an id. //! # Example: //! ``` //! use beach_map::BeachMap; //! //! let mut beach = BeachMap::default(); //! let id1 = beach.insert(1); //! let id2 = beach.insert(2); //! //! assert_eq!(beach.len(), 2); //! assert_eq!(beach[id...
use std::collections::HashSet; 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...
/// Returns a all of the elements provided in list, sorted. /// /// # Arguments /// /// * `list` - A list of elements to sort. /// * `_unused_param` - Provided only for demonstration purposes. pub fn merge_sort<T: PartialOrd + Clone>(list: Vec<T>, _unused_param: usize) -> Vec<T> { return merge_sort_recur(list); } ...
use crate::util::{drop_span, ExprFactory, HANDLER}; use dashmap::DashMap; use once_cell::sync::Lazy; use regex::Regex; use serde::{Deserialize, Serialize}; use std::{iter, mem}; use swc_atoms::{js_word, JsWord}; use swc_common::{iter::IdentifyLast, sync::Lrc, FileName, SourceMap, Spanned, DUMMY_SP}; use swc_ecma_ast::*...
use dynasm::dynasm; use dynasmrt::DynasmApi; use std::{error::Error, fs, fs::File, io::Write, os::unix::fs::PermissionsExt, path::PathBuf}; // TODO: These are not constant pub(crate) const CODE_START: usize = 0x11f8; const PAGE: usize = 4096; const RAM_PAGES: usize = 1024; // 4MB RAM pub(crate) fn rom_start(code_siz...