text
stringlengths
8
4.13M
uucore_procs::main!(uu_hostid); // spell-checker:ignore procs uucore
use std::fs::File; use std::io::{Result, Read, Write}; use std::{mem, slice, u8, u16}; pub use ip::Ipv4Addr; pub use mac::MacAddr; mod ip; mod mac; pub mod tcp; pub mod udp; pub fn getcfg(key: &str) -> Result<String> { let mut value = String::new(); let mut file = File::open(&format!("/etc/net/{}", key))?; ...
use std::cmp::{Ord, Ordering}; pub fn sort<T>(list: &mut [T]) where T: Ord, { let n = list.len(); for i in 0..n - 1 { let mut min_index = i; for j in i + 1..n { if list[min_index] > list[j] { min_index = j; } } if i != min_index { ...
use std::ops::Deref; use std::sync::Arc; use std::sync::Condvar; use std::sync::Mutex; use anyhow::anyhow; #[derive(Default)] pub struct Wait<T>(Arc<(Mutex<T>, Condvar)>); impl<T> Wait<T> where T: PartialEq, { pub fn wait(self, value: T) -> anyhow::Result<()> { let (lock, cond) = &*self; let ...
pub use self::corresponding_points::CorrespondingPoints; pub use self::flow::Flow; pub use self::points::Points; mod corresponding_points; mod flow; mod points; use std::error::Error; /// [Optical flow][1] or optic flow is the pattern of apparent motion of objects, surfaces, and /// edges in a visual scene caused by...
//! The [`SparseTuple`] struct and its utilities. use std::{cmp::Ordering, hash::Hash, iter::FromIterator}; use smallvec::SmallVec; use super::{ check_fields::DebugFields, entity::{EntityKeys, FromEntity, MutableEntityKeys}, CloneTuple, EqTuple, HashTuple, OrdTuple, }; use super::{Bitset, HasFieldSet, Tup...
use wasm_bindgen::{JsCast, JsValue}; use wasm_bindgen::closure::Closure; use web_sys::{Element, Event, Node, NodeList}; pub trait NodeListExt { fn iter(&self) -> NodeListIterator; } impl NodeListExt for NodeList { fn iter(&self) -> NodeListIterator { NodeListIterator::new(self) } } pub struct Nod...
#[derive(Clone,Copy)] pub enum Syscall { READ = 0, WRITE = 1, OPEN = 2, CLOSE = 3, STAT = 4, FSTAT = 5, LSTAT = 6, POLL = 7, LSEEK = 8, MMAP = 9, MPROTECT = 10, MUNMAP = 11, BRK = 12, RT_SIGACTION = 13, RT_SIGPROCMASK = 14, RT_SIGRETURN = 15, IOCTL = 16, PREAD64 = 17, PWRITE64 = 18...
// Copyright 2020-2022 The NATS Authors // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to ...
#[doc = "Register `ADDAPB2EN` reader"] pub struct R(crate::R<ADDAPB2EN_SPEC>); impl core::ops::Deref for R { type Target = crate::R<ADDAPB2EN_SPEC>; #[inline(always)] fn deref(&self) -> &Self::Target { &self.0 } } impl From<crate::R<ADDAPB2EN_SPEC>> for R { #[inline(always)] fn from(read...
use rocket::request::Request; use rocket::response::{self, Responder, Response}; use rocket::http::{ContentType, Status}; use rocket::http::hyper::header::{AccessControlAllowCredentials, AccessControlAllowHeaders, AccessControlAllowMethods, AccessControlAllowOrigin}; use hyper::method:...
//! //! # Run API request //! //! Send Request to server //! use structopt::StructOpt; use std::path::PathBuf; use std::io::Error as IoError; use std::io::ErrorKind; use kf_protocol::message::offset::KfListOffsetRequest; use kf_protocol::message::api_versions::KfApiVersionsRequest; use kf_protocol::message::group::Kf...
use crate::arch::x64::ir; pub struct BasicBlock { name: String, insts: Vec<ir::Instruction>, } impl BasicBlock { pub fn new(name: &str) -> Self { Self { name: name.to_string(), insts: Vec::new(), } } pub fn push_inst(&mut self, inst: ir::Instruction) { ...
#![allow(dead_code)] #[macro_use] extern crate lazy_static; mod dcb; mod error; mod network; mod opt; mod prober; mod topo; mod tracerouter; mod utils; use std::sync::Arc; use error::Result; use opt::Opt; use tracerouter::Tracerouter; use utils::process_topo; lazy_static! { static ref OPT: Opt = if cfg!(test) ...
use rand::random; const MEM_SIZE: usize = 4096; pub const GFX_WIDTH: usize = 64; pub const GFX_HEIGHT: usize = 32; const STACK_SIZE: usize = 16; const FONT_SET: [u8; 16*5] = [ 0xF0, 0x90, 0x90, 0x90, 0xF0, // 0 0x20, 0x60, 0x20, 0x20, 0x70, // 1 0xF0, 0x10, 0xF0, 0x80, 0xF0, // 2 0xF0, 0x10, 0xF0, 0x10, 0xF0, ...
use serde::{Deserialize, Serialize}; use time::PrimitiveDateTime; use crate::package::PackageKey; #[derive(Serialize, Deserialize)] pub enum LowPriorityMsg { Log(AppLogEntry), Background(BackgroundEntry), } #[derive(Serialize, Deserialize, Clone)] pub struct AppLogEntry { pub app: PackageKey, pub request_id:...
use std::fmt; use kf_socket::KfSocketError; use std::io::Error as IoError; #[derive(Debug)] pub enum CliError { IoError(IoError), KfSocketError(KfSocketError), } impl From<IoError> for CliError { fn from(error: IoError) -> Self { CliError::IoError(error) } } impl From<KfSocketError> for CliE...
use crate::alloc::sync::Arc; use crate::alloc::vec::Vec; use crate::core::cell::UnsafeCell; use crate::core::cmp::min; use crate::core::fmt; use crate::core::mem::MaybeUninit; use crate::core::sync::atomic::Ordering; use crate::sync::AtomicUsize; /// [read_ptr, write_ptr) available for reading by consumer /// [write_p...
//! This module provides ways to get information about connected Block devices use crate::{ extensions::FileExt, util::{DEV_PATH, SYSFS_PATH}, }; use bitflags::bitflags; use displaydoc::Display; use nix::sys::stat; use std::{ convert::TryInto, fs, fs::DirEntry, io, io::prelude::*, ops::R...
//! The Python debugger module mod debugger; mod process; pub use self::debugger::ImplDebugger;
use deuterium::*; pub fn definition() -> TableDef { let trucks = TableDef::new("trucks"); return trucks; } pub fn nick(table: &TableDef) -> NamedField<String> { return NamedField::<String>::field_of("nick", table); } pub fn model(table: &TableDef) -> NamedField<String> { return NamedField::<String>::...
pub struct Solution {} impl Solution { pub fn search_range(nums: Vec<i32>, target: i32) -> Vec<i32> { // Early fail if nums.is_empty() { return vec![-1, -1]; } // First find a search range let mut low = 0; let mut high = nums.len() - 1; while low < high { ...
// extern crate flate2; mod linecol; // mod table; // mod map; use self::linecol::LineCol; // use self::table::TableView; // use self::map::MapView; // use self::flate2::write::GzEncoder; // use self::flate2::Compression; use std::io::{self, Write, BufWriter}; use std::cmp; use std::ops::Range; use std::collections::...
ApBegin(RS,CLSID_UNITCONVERTER) WndBegin(UNICONVERTER_WND_CONVERTING) WndSetTitleRC({IMG_NULL_ID,TXT_LIL_N_CONVERTER}) WdgBegin(CLSID_PICK_WIDGET,WdgType) WdgPickCreateForWndRC({{0,0},{MAIN_DEFVIEW_WIDTH,0},FALSE}) WdgCommonSetAlignmentRC(ALIGN_H_CENTER|ALIGN_V_MIDDLE) ...
fn is_mod3(x: int) -> bool { if x % 3i == 0i { true } else { false }; } fn is_mod5(y: int) -> bool { if y % 5i == 0i { true } else { false }; } fn main() { let mut answer = 0; for i in range(0i, 1000i) { if is_mod3(i) || is_mod5(i) { answer += i; } } print!("{}", answer); }
// day use std::cmp::Ordering; use std::env; use std::error::Error; use std::fmt; use std::fs::File; use std::io::{ self, prelude::*, BufReader, }; #[derive(Debug, Eq, PartialEq, PartialOrd)] struct SeatId(u64); impl fmt::Display for SeatId { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { ...
// 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 ...
use e310x::I2C0; use e310x_hal::gpio::{gpio0, NoInvert, IOF0}; use e310x_hal::prelude::*; use hifive1::hal::delay::Delay; use hifive1::hal::i2c::I2c; use hifive1::sprintln; pub type I2cBaro = I2c<I2C0, (gpio0::Pin12<IOF0<NoInvert>>, gpio0::Pin13<IOF0<NoInvert>>)>; /// May need to take a reference to something that wr...
use crate::models::Reply; use env_logger; use std::collections::HashMap; use std::convert::Infallible; use std::sync::Arc; use tokio::sync::{mpsc, RwLock}; use warp; use warp::{ws::Message, Filter, Rejection}; mod handler; mod ws; type Result<T> = std::result::Result<T, Rejection>; type Clients = Arc<RwLock<HashMap<...
use crate::{webrender::FontManager, Font, FontSize, TextLayout}; pub struct UiDerive<'a> { fonts: &'a FontManager, } impl<'a> UiDerive<'a> { pub fn new(fonts: &'a FontManager) -> Self { UiDerive { fonts } } pub fn layout(&self, text: &str, font: Option<&Font>, size: FontSize) -> TextLayout { ...
use super::ecs::Event; /// event invoked by the application whenever a raw event /// is polled. this is called at least once per frame, and /// should not cause expensive computations. the polled /// event can be retreived in the application's resources /// by giving the system a ReadResource<winit::event::Event>. pub...
use thiserror::Error; #[derive(Debug, Error)] pub enum LorError { #[error("decode")] Decode(#[from] data_encoding::DecodeError), #[error("varint decode")] VarintDecode(#[from] std::io::Error), #[error("invalid card code")] InvalidCardCode(#[from] std::num::ParseIntError), #[error("invalid c...
use chrono::{DateTime, FixedOffset, SecondsFormat, Utc}; use lib_error::*; #[derive(Clone, Debug, ::serde::Deserialize, ::serde::Serialize)] pub struct Date(DateTime<FixedOffset>); impl Date { pub fn parse(rfc3339_date: &str) -> Result<Date> { let inner = DateTime::parse_from_rfc3339(rfc3339_date).context...
use std::env; mod day1; mod day10; mod day11; mod day12; mod day13; mod day14; mod day15; mod day16; mod day17; mod day18; mod day19; mod day2; mod day20; mod day21; mod day22; mod day23; mod day24; mod day25; mod day3; mod day4; mod day5; mod day6; mod day7; mod day8; mod day9; mod intcode_computer; fn main() { ...
pub mod problems;
#[doc = "Register `PBIFG` reader"] pub struct R(crate::R<PBIFG_SPEC>); impl core::ops::Deref for R { type Target = crate::R<PBIFG_SPEC>; #[inline(always)] fn deref(&self) -> &Self::Target { &self.0 } } impl From<crate::R<PBIFG_SPEC>> for R { #[inline(always)] fn from(reader: crate::R<PBI...
mod quoting; pub use self::quoting::{ quote_ident, quote_literal };
// Copyright 2020 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 ...
extern crate balanced_chunks; use balanced_chunks::BalancedChunksExt; use balanced_chunks::BalancedChunksMutExt; #[test] fn slice_1chunk() { let v = vec![1, 2, 3, 4, 5]; let s = v.as_slice(); let mut chunks = s.balanced_chunks(1); assert_eq!(chunks.next().unwrap(), [1, 2, 3, 4, 5]); } #[test] fn slic...
use crate::buffer::Buffer; impl Buffer { pub fn duplicate_lines_up(&mut self) { self.cursors.foreach(|c, past_cursors| { let s = c.selection(); c.select_overlapped_lines(); let mut text = self.buf.substr(c.selection()); if !text.ends_with('\n') { ...
//! Parsing of the source extern crate proc_macro; use std::collections::HashSet; use syn::{ Expr, ExprLit, Fields, FieldsNamed, FieldsUnnamed, GenericArgument, ItemEnum, ItemStruct, Lit, PathArguments, TypeArray, TypePath, }; /// A scalar that can be represented in a packed data structure. #[derive(Clone, ...
const COMPILER_LIBRARIES_LOCATION : &'static str = "C:/Users/carlo/.nuget/packages/runtime.win-x64.microsoft.dotnet.ilcompiler/6.0.0-preview.6.21278.2/sdk"; fn main() { //Link compiler libraries println!("cargo:rustc-link-search=native={}", COMPILER_LIBRARIES_LOCATION); println!("cargo:rustc-...
mod player; fn main() { player::play_movie("Snatch.mp4"); player::play_audio("rhcp.mp3"); clean::perform_cleanup(); clean::files::clean_files(); } mod clean { pub fn perform_cleanup() { println!("Cleaning HDD..."); } pub mod files { pub fn clean_files() { print...
use std::cmp; use wasm_bindgen::prelude::*; pub fn set_panic_hook() { // When the `console_error_panic_hook` feature is enabled, we can call the // `set_panic_hook` function at least once during initialization, and then // we will get better error messages if our code ever panics. // // For more de...
pub mod chapter2;
#[macro_use] extern crate clap; use futures; use hyper; #[macro_use] extern crate log; use reqwest; #[macro_use] extern crate serde_derive; use simple_logger; use toml; use xdg; use zmq; // workspace members mod config; mod server; use crate::config::{Config, Mode, CliMode}; fn main() { println!("Welcom...
//! `Stream<Item = Request>` + `Service<Request>` => `Stream<Item = Response>`. mod common; mod ordered; mod unordered; pub use self::ordered::CallAll; pub use self::unordered::CallAllUnordered; type Error = Box<::std::error::Error + Send + Sync>;
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ //! Utilities for tracing JS-managed values. //! //! The lifetime of DOM objects is managed by the SpiderMonkey Ga...
/// Returns amount of CPUs. #[cfg(not(target_arch = "wasm32"))] pub fn get_cpus() -> usize { num_cpus::get() } /// Returns amount of CPUs. #[cfg(target_arch = "wasm32")] pub fn get_cpus() -> usize { 1 }
// Main // Extern crates #[macro_use] extern crate log; // mods mod app; mod config; mod get; mod influx; // Uses use clap::{App, Arg}; use std::process; // Entry point fn main() { env_logger::init(); // Setup command line args and options let matches = App::new("Fediwatcher") // basic stuff ...
#[cfg(all(unix, not(target_env = "musl")))] #[global_allocator] static GLOBAL: mimalloc::MiMalloc = mimalloc::MiMalloc; fn main() { complexity::cli::run() }
//! This module provides rendering features of puppy. use crate::core::{ dom::NodeType, layout::{BoxProps, BoxType, LayoutBox}, }; use cursive::{ views::{LinearLayout, TextView}, View, }; mod a; mod i; mod input; pub type ElementContainer = LinearLayout; /// `to_element_container` renders LayoutBox;...
use std::str::from_utf8; extern crate redis; use self::redis::Commands; pub struct Redis { pub addr: String, } impl Redis { pub fn new(addr: &str) -> Redis { Redis { addr: addr.to_string(), } } pub fn set(&mut self, key: &str, value: &str) { let addr: &str= from_u...
// // file: main.rs // author: Michael Brockus // gmail: <michaelbrockus@gmail.com> // extern crate program; use program::foundation; use tokio; // main is where program execution starts #[tokio::main] async fn main() -> Result<(), Box<dyn std::error::Error>> { foundation().await?; Ok(()) } // end of function ...
#![allow(unused_imports)] use proconio::{fastout, input, marker::*}; #[fastout] fn main() { input!{ a: usize, b: usize, c: usize }; let s = if a == b { if c == 0 { "Aoki" } else { "Takahashi" } } else { if a > b { ...
use cc; fn main() { cc::Build::new() .file("src/entry_gcc.S") .file("src/interrupt_gcc.S") .file("src/syscall_gcc.S") .file("src/function.S") .compile("libarch.a"); }
use crate::algorithms::AlgorithmRender; use crate::app::SolveDetails; use crate::font::FontSize; use crate::style::content_visuals; use crate::theme::Theme; use crate::widgets::{date_string, solve_time_string}; use egui::{ containers::ScrollArea, popup_below_widget, Align2, CentralPanel, CtxRef, CursorIcon, Pos2, ...
use byteorder::ByteOrder; use config::*; use std::cmp; pub struct Memory { pub raw: Data, pub executable_size: Word, pub code_begin: Word, pub code_end: Word, pub data_begin: Word, pub data_end: Word, pub locals_stack_begin: Word, pub locals_stack_end: Word, pub return_stack_be...
//! This module defines the necessary elements in order to represent Spotify IDs //! and URIs with type safety and no overhead. //! //! ## Concrete IDs //! //! The trait [`Id`] is the central element of this module. It's implemented by //! different kinds of ID ([`AlbumId`], [`EpisodeId`], etc), and implements the //! ...
// Copyright 2023 The Jujutsu 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 // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed t...
use std::process::{Child, Command}; use network_manager::Device; use errors::*; use config::Config; pub fn start_dnsmasq(config: &Config, device: &Device) -> Result<Child> { let args = [ // the following addresses were taken from // https://github.com/tretos53/Captive-Portal/blob/master/dnsmasq.c...
use assert_cmd::prelude::*; use predicates::prelude::*; use std::error::Error; use std::io::Write; use std::process::Command; use tempfile::NamedTempFile; #[test] fn file_doesnt_exist() -> Result<(), Box<dyn Error>> { let mut cmd = Command::cargo_bin("grrs")?; cmd.arg("pattern").arg("test/file/doesnt/exist");...
extern crate cslice; #[doc(hidden)] pub extern crate libc; #[doc(hidden)] pub extern crate libcruby_sys as sys; // pub use rb; use std::ffi::CStr; use sys::VALUE; mod macros; mod class_definition; mod coercions; pub use coercions::*; pub use class_definition::{ClassDefinition, MethodDefinition}; #[repr(C)] #[der...
#[doc = "Register `RSTCTL_PSSRESET_STAT` reader"] pub struct R(crate::R<RSTCTL_PSSRESET_STAT_SPEC>); impl core::ops::Deref for R { type Target = crate::R<RSTCTL_PSSRESET_STAT_SPEC>; #[inline(always)] fn deref(&self) -> &Self::Target { &self.0 } } impl From<crate::R<RSTCTL_PSSRESET_STAT_SPEC>> fo...
use super::super::basic::constant::AXIS_MARGING; use super::super::basic::constant::AXIS_PADDING; use super::super::basic::fund::*; use super::super::basic::shape::Line; use super::super::basic::shape::Rect; const X_COORDS_MARGIN: u16 = 15; const X_TEXT_OFFSET: u16 = 4; const Y_TEXT_OFFSET: u16 = 4; #[derive(Debug)] ...
use anyhow::{Context, Result}; use std::{fs, iter}; fn diffs_distribution(adapters: &[u8]) -> [u8; 3] { let mut distr = [0_u8; 3]; let diffs = adapters.windows(2).map(|slice| slice[1] - slice[0]); for diff in diffs { distr[(diff - 1) as usize] += 1; } distr } // N = { adapters } // E = { (...
use super::{ kernel::KernelMsg, system::{ActorSystemBackend, SendingBackend}, }; use std::{ future::Future, pin::Pin, sync::{Arc, Mutex}, }; use tokio::{ runtime::Handle, sync::{mpsc, oneshot}, }; #[derive(Clone)] pub struct ActorSystemBackendTokio { handle: Handle, s_tx: Arc<Mutex<...
#[doc = "Register `CTL0` reader"] pub struct R(crate::R<CTL0_SPEC>); impl core::ops::Deref for R { type Target = crate::R<CTL0_SPEC>; #[inline(always)] fn deref(&self) -> &Self::Target { &self.0 } } impl From<crate::R<CTL0_SPEC>> for R { #[inline(always)] fn from(reader: crate::R<CTL0_SP...
use super::BlockingQueue; use std::collections::HashMap; use std::sync::{Arc, Condvar, Mutex}; pub struct JobHandler<'a, J, R> { pub job: J, index: usize, conditional_result_table: &'a Arc<(Condvar, Mutex<HashMap<usize, R>>)>, } impl<'a, J, R> JobHandler<'a, J, R> { pub fn commit(&self, result: R) { ...
use std::net::SocketAddr; use handshake::handler::HandshakeType; use filter::filters::Filters; use handshake::handler; use futures::{Poll, Async}; use futures::future::{Future}; pub struct ListenerHandler<S> { opt_item: Option<HandshakeType<S>> } impl<S> ListenerHandler<S> { pub fn new(item: (S, SocketAddr)...
use super::peripheral_clock; pub use self::Controller::*; use hal::pin; use hal::pin::{Gpio, GpioConf}; use core::convert::From; /// Available controllers #[derive(Clone, Copy)] pub enum Controller { ControllerA, ControllerB, ControllerC, ControllerD, ControllerE, ControllerF, } #[derive(Clon...
struct Solution; #[allow(dead_code)] impl Solution { pub fn exist(board: Vec<Vec<char>>, word: String) -> bool { let word = word.chars().collect::<Vec<char>>(); if word.is_empty() { return true; } for (y, i) in board.iter().enumerate() { for (x, j) in i.iter(...
use super::{Statement, StatementPath, pathed_substs}; use crate::substitution::Substitution; use crate::parse::ParseNode; use std::collections::{HashSet, HashMap, BTreeMap}; use std::iter::once; use std::str::FromStr; use std::convert::TryFrom; use std::ops::Deref; use std::fmt; macro_rules! maybe_match { ($p:path...
//! This module contains [`PageAllocator`] and [`FrameAllocator`] //! //! `PageAllocator` contains functions to allocate physical memory as contiguous virtual memory //! which may/may not be contiguous in physical memory. use x86_64::{ addr::{ VirtAddr, PhysAddr, }, registers::control::Cr3...
// Copyright (c) The Starcoin Core Contributors // SPDX-License-Identifier: Apache-2.0 use crate::cli_state::CliState; use crate::StarcoinOpt; use anyhow::Result; use clap::Parser; use scmd::{CommandAction, ExecContext}; ///Manual trigger panic, only work for dev network. #[derive(Debug, Parser)] #[clap(name = "panic...
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 use std::{ io, pin::Pin, sync::{Arc, Mutex}, task::{Context, Poll}, }; use tokio::{ io::{AsyncRead, AsyncWrite, ReadBuf}, net::TcpStream, }; type ReadFn = Box<dyn Fn(Pin<&mut TcpStream>...
use std::fs; use structopt::StructOpt; /// Recursively search for a pattern in file names and replace #[derive(StructOpt, Clone)] struct FileRenameArgs { /// The pattern to look for #[structopt(long, short)] pattern: String, /// replace the pattern #[structopt(long, short)] replace: String, ...
use super::base::{create_template, Meta}; use crate::{LastUpdated, MPsMap}; use maud::{html, Markup}; pub fn create_page(mps: &MPsMap, last_updated: &LastUpdated) -> Markup { create_template( Meta { page_title: "Home", page_desc: "Homepage for the Liars Project.", last_u...
use tiny_skia::*; fn main() { let mut paint = Paint::default(); paint.anti_alias = false; paint.shader = LinearGradient::new( Point::from_xy(100.0, 100.0), Point::from_xy(900.0, 900.0), vec![ GradientStop::new(0.0, Color::from_rgba8(50, 127, 150, 200)), Gradi...
pub fn max_subarray_bad(arr: &[i32]) -> (usize, usize, i32) { let prefixes = arr .iter() .enumerate() .scan((0, 0), |s, (i, v)| { if s.1 > 0 { s.1 = s.1 + *v; } else { *s = (i, *v); } Some(*s) }); let...
use exonum::{ crypto::Hash, runtime::{CallerAddress as Address, CommonError, ExecutionContext, ExecutionError}, }; use exonum_derive::{exonum_interface, interface_method, BinaryValue, ExecutionFail, ObjectHash}; use exonum_proto::ProtobufConvert; use crate::{proto, schema::SchemaImpl, DomRfService}; use exonum...
use std::{ time::Instant, io::{self, Write} }; fn main() { println!("Multi Test:"); let mut print = std::time::Duration::new(0, 0); for _ in 0..100 { let start = Instant::now(); print!("hello"); print+=start.elapsed() } let mut println = std::time::Duration::new(0, 0...
use deno_ast::swc::common::comments::{Comment, CommentKind}; use deno_ast::swc::common::{BytePos, Span, Spanned}; use deno_ast::swc::parser::token::{Token, TokenAndSpan}; use deno_ast::view::*; use deno_ast::MediaType; use deno_ast::ParsedSource; use dprint_core::formatting::*; use dprint_core::formatting::{condition_r...
/* * @lc app=leetcode.cn id=504 lang=rust * * [504] 七进制数 */ // @lc code=start impl Solution { pub fn convert_to_base7(mut num: i32) -> String { if num == 0 { return "0".to_string(); } let mut s = String::new(); let sign = if num < 0 { num *= -1; ...
use crate::{RenderContext, ElVar}; use crate::hook::el_var; use wasm_bindgen::JsCast; use tracked_call_macro::tracked_call; use crate::tracked_call::__TrackedCall; use crate::tracked_call_stack::__TrackedCallStack; // ------- Helpers ------ pub fn window() -> web_sys::Window { web_sys::window().expect("window") }...
use std::collections::HashMap; use std::fs; pub fn main() { println!("------------------------------------ DAY 6 ------------------------------------"); let mut input = fs::read_to_string("input/day6.txt").unwrap(); input = input.replace("\r", ""); let input_split: Vec<&str> = input .split("\n...
use std::{path::Path, process::Command, vec::Vec}; use super::{CliError, Config, Environment, LalResult, StickyOptions}; /// Pull the current environment from docker pub fn update(component_dir: &Path, environment: &Environment, env: &str) -> LalResult<()> { info!("Updating {} container", env); match environ...
//! This is an appender that rolls a file on launch and then delegates to another appender use log4rs::append::Append; use log4rs::config::{Deserialize, Deserializers}; use log4rs::encode::{Encode, EncoderConfig, Write}; use serde_value::Value; use std::collections::{BTreeMap, HashMap, VecDeque}; use std::sync::{Arc, ...
use std::io; use std::io::BufRead; // use std::time::Instant; // use self::rand::Rng; // extern crate rand; const SEQ_LENGTH: u32 = 30_000; const MAX_NUMBER: u32 = 1_000_000; const QUERIES_LENGTH: u32 = 200_000; /// Find number of distinct elements in sub-arrays pub fn main() { let stdin = io::stdin(); // Vector o...
mod tunnel; mod server; mod client; use server::server; fn main() { server("localhost:8080"); }
use napi::bindgen_prelude::*; /// default enum values are continuos i32s start from 0 #[napi] pub enum Kind { Dog, Cat, Duck, } /// You could break the step and for an new continuous value. #[napi] pub enum CustomNumEnum { One = 1, Two, Three = 3, Four, Six = 6, Eight = 8, Nine, // would be 9 Te...
use async_trait::async_trait; use lazy_static::lazy_static; use regex::{Regex, RegexBuilder}; use reqwest::header::HeaderMap; use crate::{error::NotifyError, product::Product, scraping::ScrapingProvider}; // Look for the div that says it's Sold Out, case insensitive. Give it a bit of before and after HTML so that it ...
mod utils; mod sysfssearch; mod simcom; mod usbdev; use std::env; const ARGC: usize = 3; fn main() { let argv: Vec<String> = env::args().collect(); let mut filter: Option<Vec<&str>> = None; if argv.len() < ARGC { panic!("Missing path argument!"); } else if argv.len() > ARGC { let mut ...
mod parser; pub fn solve(s: &str) -> usize { s.lines().map(parser::parse).flatten().sum() } #[test] fn test_examples() { let s = "1 + 2 * 3 + 4 * 5 + 6"; assert_eq!(71, parser::parse(s).unwrap()); let s = "1 + (2 * 3) + (4 * (5 + 6))"; assert_eq!(51, parser::parse(s).unwrap()); }
//! --- Part Two --- //! //! Now for the tricky part: notifying all the other robots about the solar flare. The vacuum robot //! can do this automatically if it gets into range of a robot. However, you can't see the other //! robots on the camera, so you need to be thorough instead: you need to make the vacuum robot //...
use std::{ sync::{ Arc } }; use warp::{ Rejection, Filter, Reply }; use tap::{ prelude::{ * } }; use serde_json::{ json }; use serde::{ Deserialize }; use tracing::{ instrument, error, debug }; use pocket_api_client::{ PocketApiError }; use crate::{ ...
fn main() {} /// These are all good if they have unique pids #[cfg(test)] mod test { use festive::festive; use std::process; #[festive] fn nested() { println!("Forked: My pid={}", process::id()); } #[festive] fn forked() { println!("Forked: My pid={}", process::id()); }...
use piston_window::*; use std::path::PathBuf; pub trait SpriteEvent { fn render(&mut self, e: &Event, w: &mut PistonWindow); } #[derive(Clone)] pub struct Sprite { texture: Vec<G2dTexture>, } impl Sprite { pub fn load_texture(path: PathBuf, w: &mut PistonWindow, flip: Flip) -> G2dTexture{ Texture::from_path(...
use crate::entity::Entity; use super::Property; use crate::state::storage::dense_storage::DenseStorage; use crate::style::{Relation, Selector, Specificity}; #[derive(Clone, Debug)] pub struct StyleRule { pub selectors: Vec<Selector>, pub properties: Vec<Property>, } impl StyleRule { pub fn new() -> Sel...
use driving_model; use na::{Rotation3, UnitQuaternion, Vector3}; use sample; use state::*; use std::collections::VecDeque; use std::f32; pub enum PredictionCategory { /// Wheels on ground Ground, /* TODO /// Top/Sides on ground Ground2, /// Wheels on wall Wall, /// Wheels on ceiling ...