text
stringlengths
8
4.13M
struct Solution(); impl Solution { pub fn three_sum_closest(nums: Vec<i32>, target: i32) -> i32 { let length=nums.len(); let mut j; let mut k; let mut num_closest=i32::MAX; let mut result=0; let mut nums=nums; let mut sum_; nums.sort();//先排序 fo...
extern crate mo_gc; use mo_gc::{Gc, GcRoot, GcThread, StatsLogger, Trace, TraceOps, TraceStack}; struct Segment { next: Gc<Segment>, } impl Segment { fn new() -> Segment { Segment { next: Gc::null() } } fn join_to(&mut self, to: Gc<Segment>) { self.next = to; ...
use super::{AssetId, *}; use codec::{Decode, Encode}; use cumulus_primitives_core::ParaId; use frame_support::traits::{Everything, Nothing}; pub use orml_xcm_support::{IsNativeConcrete, MultiCurrencyAdapter, MultiNativeAsset}; use pallet_xcm::XcmPassthrough; use polkadot_parachain::primitives::Sibling; use polkadot_xc...
// Copyright 2018-2022 the Deno authors. All rights reserved. MIT license. use std::ops::{Deref, DerefMut}; use serde::{de::Visitor, Deserialize, Deserializer, Serialize, Serializer}; pub const NAME: &str = "$__v8_magic_bytestring"; pub const FIELD_PTR: &str = "$__v8_magic_bytestring_ptr"; pub const FIELD_LEN: &str ...
pub use self::account_info::AccountInfo; mod account_info; pub use self::loans_info::LoansInfo; mod loans_info; pub use self::loan::Loan; mod loan; pub use self::loan_builder::LoanBuilder; mod loan_builder; pub use self::session_token::SessionToken; mod session_token;
pub const COMMENT_CHAR: char = '-';
use crate::{console::{get_curser, getch, set_curser}, keyboard::KeySpecial, print, print_string, utility::memset}; const CONSOLE_MAXCOMMANDBUFFERSIZE: usize = 300; const CONSOLE_PROMPT: &'static str = ">"; type CommandFunc = fn(&[u8]); #[repr(C, packed(1))] struct Command { pub command: &'static str, pub hel...
use chrono::{NaiveDate, NaiveDateTime}; use postgres::{Client, NoTls, Row}; use sea_query::{ColumnDef, Iden, Order, PostgresDriver, PostgresQueryBuilder, Query, Table}; fn main() { let mut client = Client::connect("postgresql://sea:sea@localhost/query", NoTls).unwrap(); // Schema let sql = [ Tabl...
use std::{process::exit}; use chiropterm::{*, colors::{LtRed, White}}; use euclid::*; use chiroptui::*; const ASPECT_CONFIG: AspectConfig = AspectConfig { pref_min_term_size: size2(80, 50), // but expect ~112x60 pref_max_term_size: size2(256, 256), }; pub fn main() { // TODO: Load terrain from disk, if ...
#![feature(const_fn)] extern crate memento; pub use memento::arch::cortex_m0::isr::*; pub use memento::arch::*; static mut isr: ExceptionVectors = ExceptionVectors { initial_sp: &__STACK_START, .. ExceptionVectors::DEFAULT }; fn main() { }
pub mod auth; pub mod image; pub mod category;
use backend::Backend; use result::QueryResult; use super::{Query, CombinableQuery, QueryBuilder, QueryFragment, BuildQueryResult}; #[derive(Debug)] pub struct UnionQuery<L, R> { left: L, right: R, } impl<L, R> UnionQuery<L, R> { pub fn new(left: L, right: R) -> Self { UnionQuery { left...
#![deny(warnings)] extern crate conduit_proxy; use std::process; // Look in lib.rs. fn main() { // Load configuration. let config = match conduit_proxy::app::init() { Ok(c) => c, Err(e) => { eprintln!("configuration error: {:#?}", e); process::exit(64) } }; ...
//! Kingslayer is a text-based dungeon crawler adventure game and game engine pub use cli::Cli; /// The Cli type pub mod cli; mod entity; mod input; mod player; mod types; mod util; mod world;
use rustypy::{PyArg, PyBool, PyList, PyTuple}; use std::iter::FromIterator; #[no_mangle] pub unsafe extern "C" fn python_bind_list2(list: *mut PyList) -> *mut PyList { let converted = unpack_pylist!(list; PyList{PyTuple{(I64, (F32, I64,),)}}); assert_eq!( vec![(50i64, (1.0f32, 30i64)), (25i64, (0.5f32,...
//! Use `hyper` as a driver for `happi` //! //! Implements `happi::Client` for `hyper::Client`. use futures::{FutureExt, TryFutureExt}; pub use hyper::{client::connect::HttpConnector, Body, Request, Response}; use crate as happi; impl happi::Client for hyper::Client<HttpConnector, Body> { fn execute(&self, ...
use std::collections::HashMap; pub fn character_replacement(s: String, k: i32) -> i32 { let cc: Vec<_> = s.chars().collect(); let (mut res, mut l, mut maxf) = (0, 0, 0); let mut count: HashMap<char, u64> = HashMap::new(); for r in 0..s.len() { // count.entry(s[r]).and_modify(|v| *v += 1).or_in...
use crate::uses::*; use core::ptr; use modular_bitfield::{bitfield, BitfieldSpecifier}; use crate::int::idt::IRQ_TIMER; use super::*; #[derive(Debug, Clone, Copy)] pub enum IoApicDest { To(u8), ToAll, } #[bitfield] #[repr(u64)] #[derive(Debug, Clone, Copy)] pub struct IrqEntry { vec: u8, #[bits = 3] deliv_mode:...
use diesel::prelude::*; use diesel::result::Error; use rocket::http::Status; use rocket_contrib::json::Json; use serde::Deserialize; use crate::connection::DbConn; use crate::schema::tasks; use crate::task::Task; #[get("/tasks")] pub fn tasks_index(conn: DbConn) -> Result<Json<Vec<Task>>, Status> { let query_resu...
//! Working with the text format. pub use wasm_webidl_bindings_text_parser::*; /// Parse the given straw proposal text format input into an AST. pub fn parse( module: &walrus::Module, indices_to_ids: &walrus::IndicesToIds, input: &str, ) -> anyhow::Result<crate::ast::WebidlBindings> { let mut bindings...
pub fn run() { let input: Vec<u64> = include_str!("input.txt") .lines() .map(|l| l.parse().expect("Not a number.")) .collect(); let invalid = get_first_invalid(input.clone(), 25);...
mod action; mod device; mod error; mod handle; mod instance; mod intern; mod physical_device; pub use crate::{action::*, error::*, instance::*, intern::*, physical_device::*}; use handle::Handle; pub use intern::Path; use std::collections::HashMap; use crate::device::*; use std::{mem, ptr}; use winapi::shared::hidus...
pub fn prercent_toggle_normal() { use percent_encoding::{percent_decode, utf8_percent_encode, AsciiSet, CONTROLS}; const FRAGMENT: AsciiSet = CONTROLS.add(b' ').add(b'"').add(b'<').add(b'>').add(b'`'); let input = "confident, <>`\"productive systems programming"; let iter = utf8_percent_encode(input, &...
#[cfg(test)] mod basic_integration_tests { use dualib::app; use std::process::Command; static EXEC_NAME: &'static str = "./target/debug/dua"; macro_rules! assert_vu8_str_eq { ( $x:expr, $y:expr ) => { { assert_eq!(std::str::from_utf8($x).unwrap(), $y) } }; } ...
use std::rc::Rc; use std::cell::RefCell; use std::collections::HashMap; use module::{ModulePlans, NetworkTarget}; use net::{ClientId, InPacket, OutPacket}; use ship::{ShipId, ShipNetworked, ShipRef}; use sim::SimEvents; #[cfg(feature = "client")] use sim::SimEffects; #[cfg(feature = "client")] use asset_store::AssetS...
#![deny(warnings)] use embedded_graphics::{ mono_font::MonoTextStyleBuilder, prelude::*, primitives::{Circle, Line, PrimitiveStyleBuilder}, text::{Baseline, Text, TextStyleBuilder}, }; use embedded_hal::prelude::*; use epd_waveshare::{ color::*, epd4in2::{Display4in2, Epd4in2}, graphics::Di...
use crate::{ alphabet::Alphabet, nfa::{standard::StandardNFA, standard_eps::StandardEpsilonNFA, NFA}, range_set::Range, state::State, }; use core::fmt; #[derive(Copy, Clone, PartialEq, Eq)] pub enum EpsilonEquiped<A: Alphabet> { Epsilon, Alpha(A), } impl<A: Alphabet> EpsilonEquiped<A> { fn...
// Copyright 2020 TiKV Project Authors. Licensed under Apache-2.0. use crocksdb_ffi; use libc::{c_char, c_void}; use librocksdb_sys::{DBEnv, DBInfoLogLevel as InfoLogLevel, DBLogger}; use std::ffi::{CStr, CString}; use std::str; pub trait Logger: Send + Sync { fn logv(&self, log_level: InfoLogLevel, log: &str); }...
use std::fs; use clap::Parser; use goblin::Object; /// Puts all the files in a directory into a vector. On success returns None, else returns the std::io::error /// from io::Result. /// /// # Arguments /// /// * `directory_path` - The path which to collect all files in. /// * `total_paths` - The vector which is popu...
mod easy; mod hard; mod medium; mod sword_offer; mod common; pub fn main() { let default = 4; match default { //Easy题 1 => invoke(|| easy::main()), //Medium题 2 => invoke(|| medium::main()), //Hard题 3 => invoke(|| hard::main()), //剑指offer专题 4 => i...
use crate::{ buffers::Acker, event::{self, Event}, sinks::util::{ http::{HttpRetryLogic, HttpService}, retries::FixedRetryPolicy, BatchServiceSink, Buffer, SinkExt, }, }; use base64; use std::collections::HashMap; use std::time::Duration; use futures::{Future, Sink}; use http:...
use neon::prelude::*; use rayon; mod gridstore; use gridstore::*; mod fuzzy_phrase; use crate::fuzzy_phrase::*; register_module!(mut m, { // set thread count to 16 regardless of number of cores rayon::ThreadPoolBuilder::new().num_threads(16).build_global().unwrap(); m.export_class::<JsGridStoreBuilder>("...
use criterion::{criterion_group, criterion_main, Criterion}; use scc::HashMap; use std::convert::TryInto; use std::time::Instant; fn insert_cold(c: &mut Criterion) { c.bench_function("HashMap: insert, cold", |b| { b.iter_custom(|iters| { let hashmap: HashMap<u64, u64> = HashMap::default(); ...
use kerla_runtime::address::UserVAddr; use crate::result::{Errno, Result}; use crate::syscalls::SyscallHandler; use crate::{ctypes::*, process::current_process}; use crate::user_buffer::UserBufWriter; impl<'a> SyscallHandler<'a> { pub fn sys_getcwd(&mut self, buf: UserVAddr, len: c_size) -> Result<isize> { ...
pub struct Texture { _diffuse_texture: wgpu::Texture, _diffuse_texture_view: wgpu::TextureView, _diffuse_sampler: wgpu::Sampler, diffuse_bind_group: wgpu::BindGroup, } pub static BIND_GROUP_LAYOUT_DESCRIPTOR: wgpu::BindGroupLayoutDescriptor = wgpu::BindGroupLayoutDescriptor { bindings: &[ ...
pub enum CME { } // Idea: // #[derive(ATATErr)] // #[at_err("+CME ERROR")] // pub enum CmeError { // #[at_arg(0, "Phone failure")] // PhoneFailure, // }
pub mod interpolation;
use crate::op::*; use crate::value::{Object, Value}; #[derive(Clone, Debug)] pub struct Chunk { pub constants: Vec<Value>, pub lines: Vec<usize>, pub buffer: Vec<u8>, } impl Chunk { pub fn new() -> Chunk { Chunk { constants: Vec::new(), lines: Vec::new(), bu...
use std::collections::HashMap; #[cfg(test)] mod tests { use super::*; #[test] fn examples() { println!("{}",decode_bits("00000001100110011001100000011000000111111001100111111001111110000000000000011001111110011111100111111000000110011001111110000001111110011001100000011")); assert_eq!(false...
use std::{ cmp, ops::{Add, AddAssign, Neg, Sub, SubAssign}, }; use proc_macro2::TokenStream; use quote::{quote, ToTokens}; // Copied from core lib /src/internal_macros.rs macro_rules! forward_ref_unop { (impl $imp:ident, $method:ident for $t:ty) => { impl $imp for &$t { type Output = <...
use crate::HittableList; use crate::Material; use crate::Onb; use crate::Ray; use crate::Vec3; use crate::AABB; use std::sync::Arc; extern crate rand; use rand::Rng; const INFINITY: f64 = 1e15; pub trait Object { fn hit(&self, r: Ray, t_min: f64, t_max: f64) -> Option<HitRecord>; fn bounding_box(&self) -> Opt...
use gcp_bigquery_client::error::BQError; use thiserror::Error; use url; #[derive(Error, Debug)] pub enum BigQuerySourceError { #[error(transparent)] ConnectorXError(#[from] crate::errors::ConnectorXError), #[error(transparent)] BQError(#[from] BQError), #[error(transparent)] BigQueryUrlError(...
// Copyright 2020 David Li // // 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 in wri...
use std::ops::{Deref, DerefMut}; use super::*; /// The Vector type a sequence of Values that can be accessed in constant time /// (although insertions and deletions are linear time). pub struct Vector { elements: Vec<Value>, } impl Vector { pub fn with_capacity(gc: &mut GarbageCollector, capacity: usize) -> Gc...
use std::collections::VecDeque; use std::cell::RefCell; use crate::interpreter::cache; use crate::ast::expressions::{self, primitives}; use crate::ast::lexer::tokens; use crate::ast::parser; use crate::ast::rules; use crate::ast::stack; pub struct Indexing { pub object: Box<dyn expressions::Expression>, pub ...
pub mod calibration; pub mod detection; pub mod errors; pub mod game; pub mod graphics; pub mod utils;
use super::{chunk_header::*, chunk_type::*, *}; use bytes::{Buf, BufMut, Bytes, BytesMut}; use std::fmt; ///chunkSelectiveAck represents an SCTP Chunk of type SACK /// ///This chunk is sent to the peer endpoint to acknowledge received DATA ///chunks and to inform the peer endpoint of gaps in the received ///subsequen...
use structopt::StructOpt; use std::fs::File; use std::io::{self, BufRead}; use std::path::Path; #[derive(StructOpt)] struct Cli { #[structopt(short = "w", long = "words", parse(from_os_str), default_value = "/usr/share/dict/words")] words_file: std::path::PathBuf, #[structopt(short = "v", long = "verbose")...
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. */ use std::path::PathBuf; use anyhow::Error; use reverie::process::Command; use reverie::process::Mo...
//! Module containing functions executed by the thread in charge of updating the output report every 1 second use std::collections::HashSet; use std::fs::File; use std::io::{BufWriter, Seek, SeekFrom, Write}; use std::sync::{Arc, Condvar, Mutex}; use std::thread; use std::time::Duration; use crate::gui::types::status...
/*Rust通过修改注册表启用或禁用任务管理器 Published: 2018-03-21 By Yieldone tags: Rust 开发全屏应用的时候,除了需要禁用一些ALT+F4,Win+Tab,Alt+Tab外,任务管理器也应该禁用,了解一番后,发现Ctrl+ALT+DEL组合键是Ring0级别,很难屏蔽,不能通过简单的HOOK方式让其失效,于是研究了一个最简单的方法,通过修改注册表启用禁用任务管理器 路径:HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\CurrentVersion\\Policies\\System 这个注册表路径里的DisableTaskmgr字...
#[allow(unused_imports)] use nom::*; use ast::{Ast, TypeInfo}; use parser::identifier::identifier; /// _ts indicates that the parser combinator is a getting a type signature named!(pub type_signature<TypeInfo>, ws!(alt!(number_ts | string_ts | bool_ts | array_ts | custom_ts )) ); named!(number_ts<TypeInfo>, va...
use crate::utils::read_lines; pub(crate) fn main() { let filename = "B:\\Dev\\Rust\\projects\\aoc2020\\input\\3.txt"; println!("filename is {}",filename); // One try check_slope(filename, 3, 1); // Many tries let tries: Vec<(i64,i64)> = vec![(1,1),(3,1),(5,1),(7,1),(1,2)]; let result:Vec<...
/* * Rustパターン(記法)。 * CreatedAt: 2019-07-07 */ fn main() { let numbers = (2, 4, 8, 16, 32); match numbers { (first, _, third, _, fifth) => { println!("Some numbers: {}, {}, {}", first, third, fifth) }, } }
use cuckoofilter::{CuckooFilter, ExportedCuckooFilter}; use parking_lot::Mutex; use std::collections::hash_map::DefaultHasher; use std::collections::HashMap; use std::fmt; use std::fmt::Debug; use std::sync::Arc; use subspace_core_primitives::PieceIndex; use subspace_networking::libp2p::PeerId; use subspace_networking:...
pub mod user; pub mod profile;
#[doc = "Register `MACQTxFCR` reader"] pub type R = crate::R<MACQTX_FCR_SPEC>; #[doc = "Register `MACQTxFCR` writer"] pub type W = crate::W<MACQTX_FCR_SPEC>; #[doc = "Field `FCB_BPA` reader - Flow Control Busy or Backpressure Activate"] pub type FCB_BPA_R = crate::BitReader; #[doc = "Field `FCB_BPA` writer - Flow Contr...
use super::*; #[pymethods] impl EnsmallenGraph { #[text_signature = "($self, other, verbose)"] /// Return graph remapped towards nodes of the given graph. /// /// Parameters /// ----------------------------- /// other: EnsmallenGraph, /// The graph to remap towards. /// verbose: boo...
fn main() { let number = 12; print!("{} {}", number, 47); }
use std::error::Error as StdError; use hyper::StatusCode; use std::fmt; /// The Errors that may occur when processing a `Request`. pub struct Error { inner: Box<Inner>, } pub(crate) type BoxError = Box<dyn StdError + Send + Sync>; struct Inner { kind: Kind, description: String, source: Option<BoxErro...
mod expr; mod init; mod stmt; use std::collections::{HashSet, VecDeque}; use std::convert::TryInto; use counter::Counter; use crate::data::{error::Warning, hir::*, lex::Keyword, *}; use crate::intern::InternedStr; use crate::parse::{Lexer, Parser}; use crate::RecursionGuard; pub(crate) type TagScope = Scope<Interne...
#[doc = "Reader of register RCC_SDMMC12CKSELR"] pub type R = crate::R<u32, super::RCC_SDMMC12CKSELR>; #[doc = "Writer for register RCC_SDMMC12CKSELR"] pub type W = crate::W<u32, super::RCC_SDMMC12CKSELR>; #[doc = "Register RCC_SDMMC12CKSELR `reset()`'s with value 0x03"] impl crate::ResetValue for super::RCC_SDMMC12CKSE...
use crate::{parser::Parser, syntax::SyntaxKind}; use drop_bomb::DropBomb; #[derive(Debug)] pub struct Marker { pos: u32, bomb: DropBomb, } impl Marker { pub(super) fn new(pos: u32) -> Marker { Marker { pos, bomb: DropBomb::new("Marker must be either completed or abandoned")...
use crate::core::assets::protocol::{AssetLoadResult, AssetProtocol}; use std::str::from_utf8; use svg::{ node::element::tag::{Type, SVG}, parser::Event, }; pub struct SvgImageAsset { bytes: Vec<u8>, width: usize, height: usize, } impl SvgImageAsset { pub fn bytes(&self) -> &[u8] { &sel...
use hyper::{Response, Request, Client, Body}; use std::result::Result; type HttpClient = Client<hyper::client::HttpConnector>; use futures::stream::{TryStreamExt}; use async_std::fs::File; use async_std::io::prelude::*; use chrono::Utc; pub async fn store_request(req: Request<Body>) -> Request<Body> { let ct = ...
//! Tests auto-converted from "sass-spec/spec/libsass-todo-issues" #[allow(unused)] use super::rsass; // From "sass-spec/spec/libsass-todo-issues/issue_1026.hrx" #[test] #[ignore] // wrong result fn issue_1026() { assert_eq!( rsass( "div {\ \n a {\ \n /**\ ...
// Copyright (c) Facebook, Inc. and its affiliates. // // This source code is licensed under the MIT license found in the // LICENSE file in the root directory of this source tree. use crypto::{BatchMerkleProof, ElementHasher, Hasher}; use math::{log2, FieldElement}; use utils::{ collections::Vec, ByteReader, Byte...
/* * Datadog API V1 Collection * * Collection of all Datadog Public endpoints. * * The version of the OpenAPI document: 1.0 * Contact: support@datadoghq.com * Generated by: https://openapi-generator.tech */ /// UsageLogsByIndexHour : Number of indexed logs for each hour and index for a given organization. #...
#![doc = "generated by AutoRust 0.1.0"] #![allow(non_camel_case_types)] #![allow(unused_imports)] use serde::{Deserialize, Serialize};
use std::collections::HashSet; use parser::{Ast, Block}; pub fn visitor(ast: &Ast) -> HashSet<String> { let mut res = HashSet::new(); for block in ast.blocks.iter() { if let &Block::Css(_, ref rules) = block { for rule in rules.iter() { for sel in rule.selectors.iter() { ...
use std::time::Instant; #[derive(Debug)] pub struct GeoIpResponse { pub ip: GeoIpDataResponse, pub city: GeoIpCityResponse, pub asn: GeoIpAsnResponse, } #[derive(Debug)] pub struct GeoIpDataResponse { pub ip: String, pub ptr: String, } #[derive(Debug)] pub struct GeoIpCityResponse { pub name:...
use cards::{Card, TarockCard, Tarock1, Tarock21, TarockSkis, SuitCard, Clubs, Spades, Hearts, Diamonds, King, CardSuit, CARD_TAROCK_PAGAT}; use player::Player; use std::collections::HashSet; use contracts::Contract; pub static BONUS_TYPES: [BonusType, ..5] = [ Trula, Kings, KingUltimo, PagatUltim...
#[macro_use] extern crate diesel; #[macro_use] extern crate diesel_migrations; use std::error::Error; use crate::bot::bot::init_bot; use crate::db::client::DbClient; use crate::task::task::init_task; mod bot; mod db; mod reddit; mod task; mod telegram; embed_migrations!(); pub async fn start(tg_token: String, data...
use super::operations::Response; use crate::{common::tt, data::DatabasePool}; use api_models::guild::Guild; use serenity::model::{ channel::GuildChannel, id::UserId, interactions::ApplicationCommandInteractionData, }; pub async fn set_voice( ctx: &serenity::client::Context, data: &ApplicationCommandInterac...
use std::{collections::HashMap, path::PathBuf}; use bevy::{prelude::*, reflect::TypeUuid, render::{pipeline::{PipelineDescriptor, RenderPipeline}, render_graph::{AssetRenderResourcesNode, RenderGraph, RenderResourcesNode}, renderer::RenderResources, shader::{ShaderStage, ShaderStages}}}; use crate::utils::reflection:...
// This file is part of dpdk. 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/dpdk/master/COPYRIGHT. No part of dpdk, including this file, may be copied, modified, propagated, or distributed except accordin...
extern crate tables; use tables::*; #[test] fn join_one() { let mut a = SparseMap::new(); for i in 0..1_000 { a.insert(i, i); } for (i, (a,)) in (&a,).join() { assert_eq!(i, *a); } } #[test] fn sparse_mut() { let mut a = SparseMap::new(); let mut b = SparseMap::new(); ...
pub mod event; use self::event::EventStopable; use std::collections::HashMap; pub trait ListenerCallable: PartialEq { fn call(&self, event_name: &str, event: &mut EventStopable); } pub struct EventListener { callback: fn(event_name: &str, event: &mut EventStopable), } impl EventListener { pub fn new (ca...
use poem::middlewares::StripPrefix; use poem::route::{self, Route}; use poem::EndpointExt; async fn hello() -> &'static str { "hello" } #[tokio::main] async fn main() { let route = Route::new().at("/hello", route::get(hello)); let api = Route::new().at("/api/*", route.with(StripPrefix::new("/api"))); ...
// Copyright 2019 Guillaume Becquin // 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 in wri...
extern crate nix; use nix::sched::*; extern crate pentry; fn print_process_info() { if let Ok(ps) = pentry::current() { println!("{:?}",ps); } } fn child() -> isize { print_process_info(); 0 } fn main() { print_process_info(); const STACK_SIZE:usize = 1024* 1024; let ref mut stac...
// Copyright 2020 IOTA Stiftung // SPDX-License-Identifier: Apache-2.0 #![allow(dead_code)] use wasmlib::*; pub const SC_NAME: &str = "fairauction"; pub const SC_HNAME: ScHname = ScHname(0x1b5c43b1); pub const PARAM_COLOR: &str = "color"; pub const PARAM_DESCRIPTION: &str = "description"; pub const PARAM_DURATION: ...
#[macro_use] extern crate nom; #[macro_use] extern crate nom_locate; mod ast; mod error; mod format; mod interpreter; mod parser; use crate::interpreter::Interpreter; use nom::simple_errors::Context; use nom::types::CompleteStr; pub use crate::error::Error; use std::io::{BufRead, Write}; pub fn execute<R: BufRead,...
extern crate nd; use nd::{Array, Range, View, Zeros}; fn main() { let shape = [3, 4, 5]; let mut array: Array<f32, 3> = Array::zeros(&shape); for i in 0..shape.iter().product() { array.data[i] = i as f32; } let start = [0, 0, 0]; let stop = shape.clone(); let step = [1, 1, 1]; ...
// Copyright 2017 rust-ipfs-api Developers // // 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 accord...
use panda::prelude::*; use panda::regs::Reg; use peg::{str::LineCol, error::ParseError}; pub(crate) enum Command { Taint(TaintTarget, u32), CheckTaint(TaintTarget), GetTaint(TaintTarget), Help, MemInfo, ThreadInfo, ProcInfo, ProcList, } impl Command { pub(crate) fn parse(cmd: &str...
#[allow(unused_imports)] use std::{io, fmt}; macro_rules! read_parse { ($($t:ty),*) => ({ let mut a_str = String::new(); io::stdin().read_line(&mut a_str).expect("read error"); let mut a_iter = a_str.split_whitespace(); ( $( a_iter.next().unwrap().parse::...
//! A module which contains a general settings which might be used in other grid implementations. mod alignment; mod border; mod borders; mod entity; mod indent; mod line; mod position; mod sides; pub mod compact; #[cfg(feature = "std")] pub mod spanned; pub use alignment::{AlignmentHorizontal, AlignmentVertical}; p...
// Generated from affine.rs.tera template. Edit the template, not the generated file. use crate::{Mat2, Mat3, Mat3A, Vec2, Vec3A}; use core::ops::{Deref, DerefMut, Mul}; /// A 2D affine transform, which can represent translation, rotation, scaling and shear. #[derive(Copy, Clone)] #[repr(C)] pub struct Affine2 { ...
use std::sync::Arc; use common::event::{EventPublisher, EventSubscriber}; use common::result::Result; use crate::application::handler::{CollectionHandler, PublicationHandler}; use crate::domain::catalogue::{CatalogueRepository, CollectionService, PublicationService}; pub struct Container<EPub> { event_pub: Arc<E...
use std::path::PathBuf; use structopt::StructOpt; /// Rust sudoku solver #[derive(StructOpt, Debug)] #[structopt(name="Sudoku-rs")] pub struct Opt { /// Updates per second #[structopt(short = "u", long = "ups", default_value = "120")] pub ups: u64, /// File containing the sudoku #[structopt(name =...
extern crate reqwest; use reqwest::header; fn main() -> Result<(), Box<dyn std::error::Error>> { let mut headers = header::HeaderMap::new(); headers.insert("A", "''a'".parse().unwrap()); headers.insert("B", "\"".parse().unwrap()); headers.insert(header::COOKIE, "x=1'; y=2\"".parse().unwrap()); head...
#[doc = "Register `RCC_STGENCKSELR` reader"] pub type R = crate::R<RCC_STGENCKSELR_SPEC>; #[doc = "Register `RCC_STGENCKSELR` writer"] pub type W = crate::W<RCC_STGENCKSELR_SPEC>; #[doc = "Field `STGENSRC` reader - STGENSRC"] pub type STGENSRC_R = crate::FieldReader; #[doc = "Field `STGENSRC` writer - STGENSRC"] pub ty...
#[allow(dead_code)] #[derive(Debug)] pub enum UrnError { GenericDynamic(String), Generic(&'static str), AshError(ash::vk::Result), AshInstanceError(ash::InstanceError), NulError(std::ffi::NulError), } impl From<std::ffi::NulError> for UrnError { fn from(e: std::ffi::NulError) -> UrnError { ...
/// This is a simple component. #[derive(Debug)] pub struct XYZ { x: i32, y: i32, z: i32, } impl XYZ { /// Create new `xyz` component. pub fn new(x: i32, y: i32, z: i32) -> Self { Self { x, y, z } } /// Set the x value. pub fn set_x(&mut self, x: i32) { self.x = x; ...
use std::error::Error; use std::fs; use std::io::{self, Read}; pub mod config; use config::Config; pub mod matches; use matches::Match; extern crate termcolor; use std::io::Write; use termcolor::{ColorChoice, ColorSpec, StandardStream, WriteColor}; use atty::Stream; #[cfg(test)] mod tests { use super::*; #...
use super::helpers::fixtures::{get_language, get_tags_config}; use crate::query_testing::{parse_position_comments, Assertion}; use crate::test_tags::get_tag_positions; use tree_sitter::{Parser, Point}; use tree_sitter_tags::TagsContext; #[test] fn test_tags_test_with_basic_test() { let language = get_language("pyt...
use std::{fs, str}; pub fn day3 () { let example_input = fs::read_to_string("inputs/d3.example").unwrap(); let input = fs::read_to_string("inputs/d3").unwrap(); let example_lines: Vec<&str> = example_input .lines() .collect(); let lines : Vec<&str> = input .lines() .co...
//! # Logic to read a PKI file from a byte stream use std::convert::TryFrom; use std::fmt; use std::fs::File; use std::io::{BufReader, Error as IoError, Read}; use std::path::Path; use thiserror::Error; use super::core::PackIndexFile; use super::parser; use nom::{self, error::ErrorKind, Err as NomErr}; #[derive(Deb...
fn add(x: f64, y: f64) -> f64 { x + y } fn main() { println!("Hello, world!"); println!("{}", add(3.0, 4.0)) }