text
stringlengths
8
4.13M
mod models; mod parser; mod pretty_printer; use crate::parser::get_functions; use crate::pretty_printer::print_script; use colored::*; use structopt::StructOpt; /// Run or list the contents of a script #[derive(StructOpt)] struct Cli { /// The path to the script to describe or run. #[structopt(parse(from_os_s...
// Copyright 2015 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 ...
extern crate core; use self::core::ptr; use std::sync::Arc; use std::sync::atomic::Ordering; use super::buffer::{Buffer, value_ptr}; use super::concurrent_queue::ConcurrentQueue; /// A bounded queue allowing a single producer and a single consumer. pub struct SpscConcurrentQueue<T> { buffer: Buffer<T> } impl<T>...
use async_graphql::{Context, FieldResult, Object}; use crud_crait::CRUD; use dataset::Dataset; use sqlx::MySqlPool; use user::User; pub struct QueryRoot; #[Object] impl QueryRoot { async fn users(&self, ctx: &Context<'_>) -> FieldResult<Vec<User>> { let pool = ctx.data_unchecked::<MySqlPool>(); le...
use super::circular_unit::CircularUnit; use super::status::Status; pub trait LivingUnit: CircularUnit { fn life(&self) -> i32; fn max_life(&self) -> i32; fn statuses(&self) -> &Vec<Status>; } #[macro_export] macro_rules! living_unit_impl( ($t:ty) => ( impl LivingUnit for $t { fn li...
#[macro_use] extern crate bencher; extern crate image; extern crate color_thief; use std::path::Path; use bencher::Bencher; use color_thief::ColorFormat; fn get_image_buffer(img: image::DynamicImage) -> Vec<u8> { match img { image::DynamicImage::ImageRgb8(buffer) => buffer.to_vec(), _ => unreach...
use std::collections::HashMap; fn can_hold_shiny_gold(bag_map : &HashMap<String, Vec<(u64, String)>>, bag : &str) -> bool { for (_count, bag_type) in &bag_map[bag] { if bag_type == "shiny gold" { return true; } if can_hold_shiny_gold(bag_map, &bag_type) { return tru...
// 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 agre...
use serde::Deserialize; use crate::apis::flight_provider::raw_models::airport_instance_country_raw::AirportInstanceCountryRaw; use crate::apis::flight_provider::raw_models::airport_instance_region_raw::AirportInstanceRegionRaw; #[derive(Deserialize, Debug)] pub struct AirportInstancePositionRaw { pub latitude: Op...
//! SQL metadata tables (originally from [queryrouterd]) //! //! TODO: figure out how to generate these keywords automatically from DataFusion / sqlparser-rs //! //! [queryrouterd]: https://github.com/influxdata/idpe/blob/85aa7a52b40f173cc4d79ac02b3a4a13e82333c4/queryrouter/internal/server/flightsql_info.go#L4 pub(cra...
/* This is about the simplest program that can successfully send a message. */ fn main() { let po: port[int] = port(); let ch: chan[int] = chan(po); ch <| 42; let r; po |> r; log_err r; }
// Copyright 2016-2018 Austin Bonander <austin.bonander@gmail.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, modifi...
// Copyright 2016 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 ...
use { super::{ Connection as Sway, ConnectionBuilder as SwayBuilder, Event, EventType, }, crate::modules::Module, gtk::{ Box as WidgetBox, BoxExt, Button, ButtonExt, ContainerExt, Orientation, ReliefStyle, St...
fn main() { let a: char = 'a'; println!("karakter a: {}", a); }
//! A [futures] friendly [inotify] wrapper for [fibers] crate. //! //! [futures]: https://crates.io/crates/futures //! [fibers]: https://crates.io/crates/fibers //! [inotify]: https://en.wikipedia.org/wiki/Inotify //! //! # Examples //! //! Watches `/tmp` directory: //! //! ``` //! # extern crate fibers; //! # extern c...
use consts::{ CODE_ALPHABET, ENCODING_BASE, GRID_ROWS, LATITUDE_MAX, LONGITUDE_MAX, PAIR_CODE_LENGTH, }; use interface::encode; use geo::Point; pub fn code_value(chr: char) -> usize { // We assume this function is only called by other functions that have // already ensured that the characters in the pass...
use pcap::{Device, Capture}; use futures::executor::block_on; async fn capture_1() { let interface_1 = Device::lookup().unwrap(); let mut cap1 = Capture::from_device(interface_1) .unwrap() .promisc(true) .snaplen(5000) .open().unwrap(); // tokio::block_on(cap1.next()) ...
// auto generated, do not modify. // created: Mon Feb 22 23:57:02 2016 // src-file: /QtWidgets/qcalendarwidget.h // dst-file: /src/widgets/qcalendarwidget.rs // // header block begin => #![feature(libc)] #![feature(core)] #![feature(collections)] extern crate libc; use self::libc::*; // <= header block end // main ...
use crate::prelude::*; #[repr(C)] #[derive(Debug, Default)] pub struct VkSurfaceCapabilitiesKHR { pub minImageCount: u32, pub maxImageCount: u32, pub currentExtent: VkExtent2D, pub minImageExtent: VkExtent2D, pub maxImageExtent: VkExtent2D, pub maxImageArrayLayers: u32, pub supportedTransfo...
// spell-checker:ignore numer denom use super::{ try_bigint_to_f64, PyByteArray, PyBytes, PyInt, PyIntRef, PyStr, PyStrRef, PyType, PyTypeRef, }; use crate::{ class::PyClassImpl, common::{float_ops, hash}, convert::{IntoPyException, ToPyObject, ToPyResult}, function::{ ArgBytesLike, Optiona...
fn main() { let base_path = dg2core::base_path(); }
pub mod metrics; pub mod model; pub mod metric; pub mod trainer;
pub fn min_operations(boxes: String) -> Vec<i32> { let boxes = boxes.chars().collect::<Vec<char>>(); let mut ops = 0; let mut count = 0; let mut result: Vec<i32> = vec![0; boxes.len()]; for i in 0..boxes.len() { result[i] += ops; count += if boxes[i] == '1' { 1 } else { 0 }; ...
//! The vast majority of the code is taken from https://github.com/markschl/seq_io/blob/master/src/fastq.rs use std::fs::File; use std::io::{self, BufRead}; use std::path::Path; use crate::errors::{ErrorPosition, ParseError}; use crate::parser::record::SequenceRecord; use crate::parser::utils::{ fill_buf, find_li...
use projecteuler::helper; fn main() { helper::check_bench(|| { solve(); }); assert_eq!(solve(), 1533776805); dbg!(solve()); } //What is the distance from T_n to T_{n+1}? /* Well, obviously: T_{n+1}-T_n = n+1 */ //what is the distance from P_n to P_{n+1}? /* P_{n+1}-P_n = (n+1)(3n+3-1)/2 - n(3n-...
#[cfg(test)] mod v8facade_error_handling_tests { use javascript_eval_native::v8facade::{Output, V8Facade}; #[test] fn it_gets_error_with_bad_function_call() { let eval = V8Facade::new(); let result = eval.call("what", vec![]).unwrap(); if let Output::Error(e) = result { ...
pub(crate) fn main() { println!("Welcome to the Game! by zul wasaya using RUST language"); println!("using github repo rustfirst"); println!("testing github repo") }
extern crate hyper; extern crate regex; extern crate idna; #[macro_use] extern crate log; extern crate fern; pub mod tldextract; use tldextract::extract::TldExtract; fn setupLogging() { let logger_config = fern::DispatchConfig { format: Box::new(|msg: &str, level: &log::LogLevel, _location: &log::LogLoc...
//! Bundles commonly used items - meant for internal crate usage only. pub(crate) use crate::connection::Transaction; pub(crate) use crate::params::{named_params, params, RowExt, TryIntoSql, TryIntoSqlInt}; pub(crate) use rusqlite::OptionalExtension;
use std::{env, fmt::Write}; use awto::{ protobuf::{ProtobufField, ProtobufMessage, ProtobufMethod, ProtobufService}, schema::{Model, Role}, }; use heck::SnakeCase; use proc_macro2::TokenStream; use quote::{format_ident, quote}; use crate::util::{is_ty_vec, strip_ty_option}; const COMPILED_PROTO_FILE: &str = ...
use nalgebra::{UnitQuaternion, Quaternion}; use crate::traits::{required::{SliceExt, QuatExt}, extra::F32Compat}; ////////// F32 /////////////////////////// impl F32Compat for Quaternion<f32> { fn write_to_vf32(&self, target: &mut [f32]) { target.copy_from_slice(self.as_slice()); } } impl SliceExt<f32...
use std::io; fn main() { let mut buf = String::new(); let stdin = io::stdin(); stdin .read_line(&mut buf) .expect("Failed to read first line."); let nums: Vec<u32> = buf .split_whitespace() .map(|num| num.parse().unwrap()) .collect(); for _ in 0..nums[0] { ...
use ::units::Unit; fn fetch_unit(path : &String) -> Unit { Unit::from_file(path.to_string()).unwrap() } pub fn command(args : Vec<String>) { let res = exec(args); println!("{}", res); } fn exec(args : Vec<String>) -> String { match args[1].as_ref() { "precision" => Unit::precision(&fetch_unit...
// 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 utopia_core::widgets::Widget; use crate::{context::ImageContext, primitive::ImagePrimitive}; #[derive(Debug)] pub struct Image<Img> { _src: std::marker::PhantomData<Img>, } impl<Img> Image<Img> { pub fn new() -> Self { Image { _src: std::marker::PhantomData, } } } impl<Im...
#![allow(unused_variables, non_upper_case_globals, non_snake_case, unused_unsafe, non_camel_case_types, dead_code, clippy::all)] #[cfg(feature = "Win32_Security_Authentication_Identity")] pub mod Identity;
//! This module holds the definitions of //! AB_JTM related wrappers. use libc::time_t; use data_structs::AB_JTM; use jalali_bindings::*; use std::mem; impl AB_JTM { /// This function initializes the struct. /// /// # Examples /// /// ``` /// extern crate jalali; /// /// jalali::AB_JTM::new(); /// ...
#[doc = r"Register block"] #[repr(C)] pub struct RegisterBlock { #[doc = "0x00 - Access control register"] pub acr: ACR, _reserved1: [u8; 4usize], #[doc = "0x08 - Flash key register"] pub keyr: KEYR, #[doc = "0x0c - Option byte key register"] pub optkeyr: OPTKEYR, #[doc = "0x10 - Status ...
use sqlx::error::DatabaseError; use sqlx::sqlite::{SqliteConnectOptions, SqliteError}; use sqlx::ConnectOptions; use sqlx::TypeInfo; use sqlx::{sqlite::Sqlite, Column, Executor}; use sqlx_test::new; use std::env; #[sqlx_macros::test] async fn it_describes_simple() -> anyhow::Result<()> { let mut conn = new::<Sqlit...
//mod print; //mod vars; //mod types; //mod ifs; //mod loops; //mod boolean; //mod hi; fn main() { //print::run(); //vars::run(); //types::run(); //ifs::run(); //loops::run(); //boolean::run(); //hi::run(); }
use proconio::{input, marker::Chars}; const M: u64 = 998244353; macro_rules! add { ($a: expr, $b: expr) => { $a = ($a + $b) % M; }; } fn main() { input! { s: Chars, }; let mut dp = vec![0_u64; s.len() + 1]; dp[0] = 1; for &ch in &s { let mut next = vec![0; s.len()...
use crate::{ event::log_schema, sinks::util::{ encoding::{EncodingConfig, EncodingConfiguration}, tcp::TcpSink, Encoding, UriSerde, }, tls::{MaybeTlsSettings, TlsSettings}, topology::config::{DataType, SinkConfig, SinkContext, SinkDescription}, }; use bytes::Bytes; use future...
use crate::input_error::InputError; pub struct Passport { value_map: std::collections::HashMap<String, String>, } impl Passport { pub fn new(key_value_row: &str) -> Result<Passport, InputError> { let mut value_map = std::collections::HashMap::<String, String>::new(); let key_value_pairs = key_...
use crate::{ast::Position, parser::ParserSettings}; use sm_parser::Span; impl Default for ParserSettings { fn default() -> Self { Self { file: String::from("anonymous"), refine: true } } } impl ParserSettings { pub(crate) fn get_position(&self, s: Span) -> Position { Position { file: self....
use winapi::shared::minwindef::{HINSTANCE, HRSRC, HGLOBAL}; use winapi::um::winuser::{LoadImageW, LR_DEFAULTSIZE, LR_CREATEDIBSECTION}; use winapi::ctypes::c_void; use crate::win32::base_helper::{to_utf16, from_utf16}; use crate::NwgError; use super::{Icon, Bitmap, Cursor}; use std::{ptr, slice}; /// Raw resource typ...
// Note: Rasa needs tensorflow_text use std::collections::HashMap; use std::convert::{Into, TryInto}; use std::path::{Path, PathBuf}; use std::process::{Child, Command}; use crate::nlu::{compare_sets_and_train, try_open_file_and_check, write_contents}; use crate::nlu::{ EntityData, EntityDef, Nlu, NluManager, NluM...
use crate::grid::{Grid, Point}; use crate::reader::get_lines; use std::collections::HashSet; use std::fs::File; use std::io::{BufReader, Lines}; use std::iter::FromIterator; use std::str::FromStr; fn parse_to_grid(input: Lines<BufReader<File>>) -> Grid { let mut grid = Grid::new(); for (y, line) in input.enume...
use std::io; use std::net::Shutdown; use std::pin::Pin; use std::task::{Context, Poll}; use crate::runtime::{AsyncRead, AsyncWrite, TcpStream}; use crate::url::Url; use self::Inner::*; pub struct MaybeTlsStream { inner: Inner, } enum Inner { NotTls(TcpStream), #[cfg(feature = "tls")] Tls(async_nativ...
use itertools::Itertools; use std::cmp; use std::fmt; use std::str; use thiserror::Error; use crate::domain::catalog::{ brands::Brand, categories::Category, rolling_stocks::RollingStock, scales::Scale, }; use super::rolling_stocks::Epoch; /// It represent a catalog item number. #[derive(Debug, PartialEq, Eq,...
use std::io::{Read, Result as IOResult}; use crate::PrimitiveRead; pub struct Header { pub version: i32, pub vert_cache_size: i32, pub max_bones_per_strip: u16, pub max_bones_per_tri: u16, pub max_bones_per_vert: i32, pub checksum: i32, pub lods_count: i32, pub material_replacement_list_offset: i32...
extern crate jlib; use jlib::api::subscription::data::SubscribeResponse; use jlib::api::subscription::api::on; use jlib::api::config::Config; // static TEST_SERVER: &'static str = "ws://101.200.176.249:5040"; static TEST_SERVER: &'static str = "ws://59.175.148.101:5020"; fn main() { let config = Config::new(TEST...
use std::mem; type BytePointer = *const u8; fn show_bytes(p: BytePointer, len: usize) { for i in 0..len { unsafe { print!(" {:02x}", *p.offset(i as isize)); } } println!(""); } fn show_i32(x: i32) { unsafe { show_bytes(mem::transmute::<&i32, BytePointer>(&x), ...
use math; // Return the first factor of n that is not 1 or n itself. // Return None if no such factor found (i.e. n is prime) pub fn factor(n: u64) -> Option<(u64, u64)> { for x in 2..math::sqrt_u64(n)+1 { if n % x == 0 { return Some((n / x, x)); } } None }
//! HTTP service implementations for `router`. pub mod write; use std::{str::Utf8Error, time::Instant}; use bytes::{Bytes, BytesMut}; use futures::StreamExt; use hashbrown::HashMap; use hyper::{header::CONTENT_ENCODING, Body, Method, Request, Response, StatusCode}; use iox_time::{SystemProvider, TimeProvider}; use m...
use crate::error::Error; use crate::hex_utils; use crate::services::PaginationRequest; use crate::services::PaginationResponse; use crate::services::PaymentsFilter; use bdk::database::SyncTime; use bdk::BlockTime; use bitcoin::BlockHash; use entity::access_token; use entity::access_token::Entity as AccessToken; use ent...
use rand::Rng; use std::{thread, time}; use test_deps::deps; static mut COUNTER_SERIAL: usize = 0; #[deps(SERIAL_000)] #[test] fn serial_000() { thread::sleep(time::Duration::from_secs_f64(0.100000 * rand::thread_rng().gen::<f64>())); unsafe { assert_eq!(0, COUNTER_SERIAL); COUNTER_SERIAL = C...
extern crate reqwest; extern crate scraper; use scraper::{Html, Selector}; use std::env; #[derive(Debug)] struct CrateListing { name: String, desc: String, date: String, url: String, } fn get_search_term() -> String { let cli_args: Vec<String> = env::args().collect(); let search_term: &st...
use core::borrow::BorrowMut; use embedded_graphics::{ draw_target::DrawTarget, mono_font::{MonoFont, MonoTextStyle, MonoTextStyleBuilder}, pixelcolor::{PixelColor, Rgb888}, prelude::{Dimensions, Point, Size}, primitives::Rectangle, text::renderer::{CharacterStyle, TextRenderer}, Drawable, }...
#[doc = "Reader of register FRCR"] pub type R = crate::R<u32, super::FRCR>; #[doc = "Writer for register FRCR"] pub type W = crate::W<u32, super::FRCR>; #[doc = "Register FRCR `reset()`'s with value 0x07"] impl crate::ResetValue for super::FRCR { type Type = u32; #[inline(always)] fn reset_value() -> Self::...
// TODO: remove this and windows-sys rather than generated bindings fn main() -> std::io::Result<()> { let tokens = macros::generate! { Windows::Foundation::{IReference, IStringable, PropertyValue}, Windows::Win32::Foundation::{CloseHandle, GetLastError, E_NOINTERFACE, CLASS_E_CLASSNOTAVAILABLE, E_...
#[cfg(test)] mod tests { #[test] fn work() { let _x = 5; let (_x, _y, _z) = (1, 2, 3); } }
pub mod qdnslookup; pub use self::qdnslookup::QDnsTextRecord; pub mod qnetworkinterface; pub use self::qnetworkinterface::QNetworkAddressEntry; pub mod qnetworkcookie; pub use self::qnetworkcookie::QNetworkCookie; pub mod qnetworkproxy; pub use self::qnetworkproxy::QNetworkProxy; pub mod qsslcipher; pub use self::q...
#![allow(unused_variables, non_upper_case_globals, non_snake_case, unused_unsafe, non_camel_case_types, dead_code, clippy::all)] #[cfg(feature = "Win32_Foundation")] #[inline] pub unsafe fn CheckGamingPrivilegeSilently<'a, Param1: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>, Param2: ::windows::core::IntoPa...
use std::{ path::{Path, PathBuf}, process::Command, str, }; pub fn clone_repo<P: AsRef<Path>>(url: &str, path: P) { let path = path.as_ref(); println!("git cloning path {}", path.display()); let status = Command::new("git") .arg("clone") .arg(url) .arg(&path) .s...
/* * Author: Dave Eddy <dave@daveeddy.com> * Date: February 15, 2022 * License: MIT */ //! Subcommands for `vsv`. pub mod enable_disable; pub mod external; pub mod status;
use proconio::input; #[allow(unused_imports)] use proconio::marker::*; #[allow(unused_imports)] use std::cmp::{max, min}; #[allow(unused_imports)] use std::collections::*; #[allow(unused_imports)] use std::f64::consts::*; #[allow(unused)] const INF: usize = std::usize::MAX / 4; #[allow(unused)] const M: usize = 100000...
#![feature(exclusive_range_pattern)] #[macro_use] extern crate lazy_static; extern crate boardgameai_rs; extern crate rand; use boardgameai_rs::*; use boardgameai_rs::state::State; use boardgameai_rs::action::Action; // use std::collections::{HashMap, HashSet}; use std::fmt::Display; // use std::rand::{Rng, thread_rn...
use super::BOOL; use std::{ ffi::CStr, fmt, os::raw::{c_char, c_void}, ptr::NonNull, }; #[macro_use] mod macros; /// A method selector. /// /// Selectors can be safely created using the /// [`selector!`](../macro.selector.html) macro. /// /// See [documentation](https://developer.apple.com/documentati...
use super::vertex::Vertex; // print',\n'.join(["[Vertex(%d - 1), Vertex(%d + 1), Vertex(%d - 21), Vertex(%d + 21)]" % (i, i, i, i) for i in range(21 * 21)]) pub static NEIGHBOURS: [[Vertex; 4]; 21 * 21] = [ [Vertex(0 - 1), Vertex(0 + 1), Vertex(0 - 21), Vertex(0 + 21)], [Vertex(1 - 1), Vertex(1 + 1), Vertex(1 - 21...
use proc_macro2::TokenTree; use std::env; use std::ffi::OsStr; use std::fs::File; use std::io::{Read, Write}; use std::path::Path; use syn::{ visit::{self, Visit}, Macro, }; use walkdir::WalkDir; fn main() { // Parse all .rs files to collect everything which implements Command. // This code won't work ...
use std::ops::Range; fn main() { let input = include_str!("./input.txt").lines().next().unwrap(); //let input = include_str!("./input_test.txt").lines().next().unwrap(); let mut phase: Vec<isize> = input.chars().map(|c| c.to_digit(10).unwrap() as isize).collect(); let pattern: Vec<isize> = vec![0,1,0,-...
#[doc = "Reader of register CPT2CR"] pub type R = crate::R<u32, super::CPT2CR>; #[doc = "Reader of field `CPT2x`"] pub type CPT2X_R = crate::R<u16, u16>; impl R { #[doc = "Bits 0:15 - Timerx Capture 2 value"] #[inline(always)] pub fn cpt2x(&self) -> CPT2X_R { CPT2X_R::new((self.bits & 0xffff) as u16...
use crate::token::*; use std::fmt; #[derive(Debug, Eq, Hash, PartialEq, Clone)] pub enum Statement { Let { token: Token, identifier: Token, value: Expression, }, Return { token: Token, return_value: Expression, }, Expression { token: Token, ex...
use std::convert::TryInto; use solana_program::program_error::ProgramError; use crate::error::EscrowError::InvalidInstruction; pub enum EscrowInstruction { /// create and populate escrow account & transfer ownership of temp token to program derived address /// 5 accounts in total as params /...
//! //! The Semaphone CI pipeline demo binary. //! #[derive(Debug)] pub enum Error {} /// /// The main function gets the HTTP port from the command line arguments /// and starts the Hyper HTTP server. /// fn main() -> Result<(), Error> { let args = clap::App::new(env!("CARGO_PKG_NAME")) .version(env!("CAR...
// This file was generated by gir (https://github.com/gtk-rs/gir) // from gir-files (https://github.com/gtk-rs/gir-files) // DO NOT EDIT use glib::object::Cast; use glib::object::IsA; use glib::signal::connect_raw; use glib::signal::SignalHandlerId; use glib::translate::*; use glib_sys; use libc; use std::boxed::Box a...
mod config; mod db; mod graphql; mod handlers; mod models; use crate::graphql::{create_schema, Schema}; use crate::models::Data; use actix_cors::Cors; use actix_web::*; use dotenv::dotenv; // use std::sync::Mutex; use tokio_postgres::NoTls; #[actix_rt::main] async fn main() -> std::io::Result<()> { dotenv().ok();...
use super::ip_rules::do_bash_cmd; use crate::config::{IPSET_NETHASH_TABLE, IPSET_TABLE, IPSET_TABLE6}; pub fn set_ipset() { // sudo ipset -N LPROXY iphash let arg = format!( "ipset -N {} iphash;ipset -N {} iphash family inet6;ipset -N {} nethash;\ ipset -F {};ipset -F {};ipset -F {}", ...
#[allow(unused_imports)] use stringify::Stringify; #[allow(unused_imports)] use std::ffi::{CStr, CString}; #[allow(unused_imports)] use std::borrow::Cow; #[test] fn convert_to_cow_str_test() { let libc_char = CString::new("something".to_string()).unwrap().as_ptr(); let cow_str = Cow::Borrowed(libc_char.convert_to_...
// Copyright 2019. The Tari Project // // Redistribution and use in source and binary forms, with or without modification, are permitted provided that the // following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following // disclai...
pub mod chain; pub mod channels; pub mod config; pub mod database; pub mod disk; pub mod error; pub mod event_handler; pub mod events; pub mod hex_utils; pub mod node; pub mod p2p; pub mod persist; pub mod services; pub mod utils; pub mod version;
use std::fmt::Debug; use std::io; use std::str::FromStr; struct Edge<'a> { node: Option<&Node>, next: Option<&Edge<'a>>, } struct Node { value: i64, edges: Option<&Edge>, } fn read_and_divide_line<T>() -> Vec<T> where T: FromStr, <T as FromStr>::Err: Debug, { let mut target_line = String:...
use std::time::Duration; use criterion::{ criterion_group, criterion_main, Bencher, Benchmark, Criterion, Throughput, }; const CORPUS_HTML: &'static [u8] = include_bytes!("../../data/html"); const CORPUS_URLS_10K: &'static [u8] = include_bytes!("../../data/urls.10K"); const CORPUS_FIREWORKS: &'static [u8] = i...
// Copyright 2015 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 ...
use core::marker::PhantomData; use poll::Poll; use Async; use stream::Stream; /// A stream combinator to change the error type of a stream. /// /// This is created by the `Stream::from_err` method. #[derive(Debug)] #[must_use = "futures do nothing unless polled"] pub struct FromErr<S, E> { stream: S, f: Phanto...
//! The Rust core prelude. #[macro_use] pub mod macros; #[cfg(target_arch = "x86_64")] pub mod x86_64; pub mod rand; pub mod prelude { pub use core::slice::{SliceExt, from_raw_parts}; pub use core::iter::{Iterator, IteratorExt, Zip, range, count, DoubleEndedIterator}; pub use core::option::Option::{self...
use crate::constants::APOD_URL; use crate::services::database::apod::DBApod; use serde::{Deserialize, Serialize}; use std::error::Error; use std::fmt; #[derive(Serialize, Deserialize, Debug)] pub struct Apod { pub copyright: Option<String>, pub date: String, pub explanation: String, pub hdurl: String, ...
use std::cell::RefCell; use std::fmt; use std::rc::Rc; use apu::ApuReg; use cpu_instr::{Cycles, Instr, Mode, Op}; use ppu::PpuReg; use rom::Rom; pub struct Cpu { reg: Reg, ram: [u8; 0x800], ppu_reg: Rc<RefCell<PpuReg>>, apu_reg: Rc<RefCell<ApuReg>>, sram: [u8; 0x2000], prg_rom: [u8; 0x8000], }...
/// A state identifier especially tailored for lazy DFAs. /// /// A lazy state ID logically represents a pointer to a DFA state. In practice, /// by limiting the number of DFA states it can address, it reserves some /// bits of its representation to encode some additional information. That /// additional information is...
use std::fs::File; use std::io::Read; use std::str::FromStr; use computer::IntCodeComputer; fn main() { let mut in_dat_fh = File::open("./data/input_02.txt").unwrap(); let mut in_dat = String::new(); in_dat_fh.read_to_string(&mut in_dat).unwrap(); let mut icc = IntCodeComputer::from_str(&in_dat).unwr...
use std::os::raw::{c_int, c_void}; #[cfg(feature = "libsodium")] use std::{ffi::CStr, os::raw::c_char}; extern "C" { fn zmq_version(major: *mut i32, minor: *mut i32, patch: *mut i32) -> c_void; #[cfg(feature = "libsodium")] fn sodium_version_string() -> *const c_char; } pub fn version() -> (i32, ...
use super::*; #[derive(Debug)] pub enum Screen { GameWorld, Console, Inventory, Character, } #[derive(Debug)] pub enum Action { Nothing, Exit, OpenInventory, OpenCharacterScreen, ListObjects, GameAction(game::Action), } impl State for Screen { type World = Game; type A...
use std::collections::HashMap; use std::fmt; use std::rc::Rc; use self::MalType::*; use super::env::Env; pub type MalHashContainer = HashMap<String, MalValue>; /// The different types a MAL value can take. #[allow(non_camel_case_types)] pub enum MalType { Nil, True, False, Integer(i32), Str(Strin...
use std::vec::IntoIter; use {Error, Result}; const TOPIC_PATH_DELIMITER: char = '/'; use self::Topic::{ Normal, System, Blank, SingleWildcard, MultiWildcard }; /// FIXME: replace String with &str #[derive(Debug, Clone, PartialEq)] pub enum Topic { Normal(String), System(String), // $SYS =...
// Copyright (c) 2020 ESRLabs // // 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 agre...
use shrev::{EventChannel, ReaderId}; use specs::prelude::{Read, Resources, System, Write}; use crate::event; use crate::input::InputHandler; use wasm_bindgen::prelude::*; use wasm_bindgen::*; use web_sys::*; use web_sys::WebGl2RenderingContext as GL; pub struct InputSystem { reader: Option<ReaderId<event::InputEv...
#[doc = "Reader of register CIER"] pub type R = crate::R<u32, super::CIER>; #[doc = "Writer for register CIER"] pub type W = crate::W<u32, super::CIER>; #[doc = "Register CIER `reset()`'s with value 0"] impl crate::ResetValue for super::CIER { type Type = u32; #[inline(always)] fn reset_value() -> Self::Typ...
use itertools; fn main() { let origs = [6, 3, 5, 8, 6, 34, 1, 5, 7]; for sublen in 0..origs.len() { let unsorted_vals = &origs[..sublen]; let mut sorted_vals = unsorted_vals.to_vec(); quick_sort(&mut sorted_vals); println!("{:?} => {:?}", unsorted_vals, sorted_vals); ...
pub fn total_distance(speed: u32, fly: u32, rest: u32, seconds: u32) -> u32 { let mut time_to_fly = fly; let mut time_to_rest = rest; let mut distance = 0; for _ in 0..seconds { if time_to_fly > 0 { distance += speed; time_to_fly -= 1; } else { if tim...