text
stringlengths
8
4.13M
mod window; pub use self::window::Window; mod colors; pub use self::colors::Colors; mod attributes; pub use self::attributes::Attributes; mod capabilities; pub use self::capabilities::Capabilities; mod input; pub use self::input::Input; mod add; pub use self::add::Add;
#![feature(test)] extern crate base64; extern crate rand; extern crate test; use base64::display; use base64::{decode, decode_config_buf, decode_config_slice, encode, encode_config_buf, encode_config_slice, Config, MIME, STANDARD}; use rand::Rng; use test::Bencher; #[bench] fn encode_3b(b: &mut Bencher...
use crate::internal::commas; use crate::Assign; use std::fmt; /// The definition of an input to a block. /// /// These are essentially phi nodes, and makes sure that there's a local /// variable declaration available. #[derive(Debug, Clone)] pub struct Phi { /// The blocks which defines the variable. dependenc...
use super::utils::GTK_EVENT_HANDLER; use super::utils::GTK_MUTEX; use std::cell::RefCell; use std::pin::Pin; use std::rc::Rc; use std::sync::{Arc, Mutex}; use std::task::{Context, Poll, Waker}; use super::utils::gtk_init_check; use super::AsGtkDialog; struct FutureState<R, D> { waker: Option<Waker>, data: O...
pub mod ser { use std::collections::HashMap; use itertools::Itertools; use serde::{ ser::{SerializeMap, SerializeSeq, SerializeStruct}, Serialize, Serializer, }; use crate::internals::{ query::filter::LayoutFilter, serialize::{ser::WorldSerializer, UnknownType}, ...
use nutype::nutype; use std::ops::Add; use crate::{format_string, Error}; const MM_PER_INCH: f64 = 25.4; /// Precipitation in mm #[nutype(validate(min=0.0))] #[derive(*, Serialize, Deserialize)] pub struct Precipitation(f64); impl Default for Precipitation { fn default() -> Self { Self::new(0.0).unwrap(...
use std::rc::Rc; use scheme::errors::EvalErr; use scheme::eval::eval; use scheme::parser::parse_expression; use scheme::scope::Scope; use scheme::{eval_expr, eval_file}; fn assert_eval(expr: &str, expected: &str) { assert_eval_with_scope(&Rc::new(Scope::from_global()), expr, expected); } fn assert_eval_with_scop...
//! inversion engine serialization codec use crate::inv_any::*; use crate::inv_api_spec::*; use crate::inv_error::*; use crate::inv_uniq::*; /// Serialization codec for InversionApi Events. /// Both sides can emit these events, both sides can receive them. #[derive(Debug, serde::Serialize, serde::Deserialize)] #[serd...
#![allow(unused_must_use)] #![no_main] #![feature(start)] mod ns; mod olintest; mod regression; mod scheme; use log::error; use olin::{entrypoint, runtime::exit}; use std::io::Error; entrypoint!(); fn main() -> Result<(), std::io::Error> { let mut fail_count = 0; let funcs = [ ns::env::test, ...
// auto generated, do not modify. // created: Mon Feb 22 23:57:02 2016 // src-file: /QtWidgets/qgraphicslayout.h // dst-file: /src/widgets/qgraphicslayout.rs // // header block begin => #![feature(libc)] #![feature(core)] #![feature(collections)] extern crate libc; use self::libc::*; // <= header block end // main ...
#![allow(unused)] use std::fmt::Display; use std::fmt::Formatter; #[derive(Debug)] pub struct Node { pub children: Vec<Node>, pub node_type: NodeType } impl Node { pub fn append_child(&mut self, child: Node) { self.children.push(child); } pub fn add_attributes(&mut self, name: String, va...
/*! The high-level plotting abstractions. Plotters uses `ChartContext`, a thin layer on the top of `DrawingArea`, to provide high-level chart specific drawing funcionalities, like, mesh line, coordinate label and other common components for the data chart. To draw a series, `ChartContext::draw_series` is used to dra...
// auto generated, do not modify. // created: Mon Feb 22 23:57:02 2016 // src-file: /QtWidgets/qcompleter.h // dst-file: /src/widgets/qcompleter.rs // // header block begin => #![feature(libc)] #![feature(core)] #![feature(collections)] extern crate libc; use self::libc::*; // <= header block end // main block begi...
use ndarray_linalg::*; use super::da::{EnsembleAnalyzer, Setting}; use super::observation::*; use super::stat::*; use super::types::*; /// Ensemble Kalman Filter with perturbed observation implementation #[derive(Clone, Debug)] pub struct EnKF { obs: LinearNormal, } impl EnKF { pub fn new(setting: &Setting) ...
//让我们一起来玩扫雷游戏! // // 给定一个代表游戏板的二维字符矩阵。 'M' 代表一个未挖出的地雷,'E' 代表一个未挖出的空方块,'B' 代表没有相邻(上,下,左,右,和所有4个对角线) //地雷的已挖出的空白方块,数字('1' 到 '8')表示有多少地雷与这块已挖出的方块相邻,'X' 则表示一个已挖出的地雷。 // // 现在给出在所有未挖出的方块中('M'或者'E')的下一个点击位置(行和列索引),根据以下规则,返回相应位置被点击后对应的面板: // // // 如果一个地雷('M')被挖出,游戏就结束了- 把它改为 'X'。 // 如果一个没有相邻地雷的空方块('E')被挖出,修改它为('B'),并且所有和其相邻的方...
use std::collections::HashMap; use crate::error::LuxError; use crate::literal::{Float, Literal}; use crate::token::Token; use crate::token_type::Types; pub struct Scanner { source: String, tokens: Vec<Token>, start: usize, current: usize, line: usize, keywords: HashMap<String, Types>, } impl ...
#![feature(inclusive_range_syntax)] pub fn sum_of_squares(n: u64) -> u64 { (0...n).map(|n| n * n).sum() } pub fn square_of_sum(n: u64) -> u64 { let x: u64 = (0...n).sum(); x * x } pub fn difference(n: u64) -> u64 { square_of_sum(n) - sum_of_squares(n) }
use clap::{App, load_yaml}; use image::{Luma, RgbImage, Rgb}; fn is_bright(noise_color: &Luma<u8>, picture_color: &Luma<u8>) -> bool { let noise_luma = noise_color.0; let picture_luma = picture_color.0; if picture_luma[0] > noise_luma[0] { true } else { false } } fn wrap(m: u32, n:...
use std::fmt::Display; use serde::de::Error as DeError; use serde::ser::Error as SerError; error_chain! { types { Error, ErrorKind, ResultExt, Result; } foreign_links { Io(::std::io::Error); FromUtf8Error(::std::string::FromUtf8Error); ParseIntError(...
// Copyright 2023 Datafuse Labs. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to ...
use std::ffi::CString; use std::marker::PhantomData; use std::mem::ManuallyDrop; use gdal_sys::{VSIFCloseL, VSIFileFromMemBuffer, VSIFree, VSIGetMemFileBuffer, VSIUnlink}; use crate::errors::{GdalError, Result}; use crate::utils::_last_null_pointer_err; /// Creates a new VSIMemFile from a given buffer. pub fn create...
use aoc2019::aoc_input::get_input; use aoc2019::intcode::*; use std::ops::Index; use std::str::FromStr; #[derive(Debug, Copy, Clone, PartialEq)] enum Tile { OpenSpace, Scaffolding, } type Coordinate = (usize, usize); struct Map { grid: Vec<Tile>, width: usize, } impl Map { fn height(&self) -> us...
//! High-speed timer //! //! Size: 4K use core::marker::PhantomData; use core::ops::{Deref, DerefMut}; use static_assertions::const_assert_eq; pub const PADDR: usize = 0x01C6_0000; register! { IrqEnable, u32, RW, Fields [ Enable WIDTH(U1) OFFSET(U0) ] } register! { IrqStatus, u32...
use super::InternalEvent; use metrics::counter; use std::borrow::Cow; use string_cache::DefaultAtom as Atom; #[derive(Debug)] pub struct RegexEventProcessed; impl InternalEvent for RegexEventProcessed { fn emit_metrics(&self) { counter!("events_processed", 1, "component_kind" => "transform", ...
#![allow(dead_code)] #[macro_use] extern crate derivative; // #[cfg(test)] // #[macro_use] // extern crate pretty_assertions; #[macro_use] extern crate lazy_static; use crate::data_ini::DataIni; use crate::globals::*; use crate::slk_datas::SLKData; pub const PREFIX_SAMPLE_PATH: &str = "resources/sample_1"; pub const ...
// 1xx: Positive Preliminary Reply pub const INITIATING: u32 = 100; pub const RESTART_MARKER: u32 = 110; pub const READY_MINUTE: u32 = 120; pub const ALREADY_OPEN: u32 = 125; pub const ABOUT_TO_SEND: u32 = 150; // 2xx: Positive Completion Reply pub const COMMAND_OK: u32 = 200; pub const COMMAND_NOT_IMPLEMENTED: u32 = ...
// // // //! Achitecture-specific code cfg_if::cfg_if!{ if #[cfg(feature="test")] { #[macro_use] #[path="imp-test.rs"] #[doc(hidden)] pub mod imp; } else { #[macro_use] //#[cfg_attr(arch="amd64", path="amd64/mod.rs")] #[cfg_attr(target_arch="x86_64", path="amd64/mod.rs")] #[cfg_attr(arch="armv7", pa...
use std::cmp::Ordering; fn main() { let input: Vec<&str> = include_str!("./input_a.txt").lines().collect(); let mut asteroids: Vec<Point> = Vec::new(); for (y, &line) in input.iter().enumerate() { for (x, ch) in line.char_indices() { if ch == '#' { asteroids.push(Point...
#[doc = "Reader of register EPHYRIS"] pub type R = crate::R<u32, super::EPHYRIS>; #[doc = "Reader of field `INT`"] pub type INT_R = crate::R<bool, bool>; impl R { #[doc = "Bit 0 - Ethernet PHY Raw Interrupt Status"] #[inline(always)] pub fn int(&self) -> INT_R { INT_R::new((self.bits & 0x01) != 0) ...
use front::stdlib::value::{Value, ResultValue, ToValue, FromValue, to_value, from_value}; use front::stdlib::function::Function; use std::collections::btree_map::BTreeMap; pub static PROTOTYPE: &'static str = "prototype"; pub static INSTANCE_PROTOTYPE: &'static str = "__proto__"; //#[derive(Clone)] pub type ObjectData ...
use crate::utils::*; pub(crate) const NAME: &[&str] = &["ExactSizeIterator"]; pub(crate) fn derive(data: &Data, items: &mut Vec<ItemImpl>) -> Result<()> { #[cfg(not(feature = "exact_size_is_empty"))] let is_empty = quote!(); #[cfg(feature = "exact_size_is_empty")] let is_empty = quote! { #[inl...
pub mod attribute; pub mod classfile; pub mod constant; pub mod field; pub mod method; pub mod read;
use criterion::{black_box, criterion_group, criterion_main, Criterion}; use rayon_array_add_benchmarks::*; fn criterion_benchmark(c: &mut Criterion) { { let mut kib_array = c.benchmark_group("320 kib array"); let v1: &[u32] = &[1; 1024 * 10]; let mut v2 = vec![2; 1024 * 10]; kib_arr...
// 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...
//! Contains device definitions and their parsing/creation functionality mod controller; mod device_info; mod endpoints; mod identifier; mod protocol; pub use crate::devices::controller::Controller; use crate::devices::device_info::DeviceInfo; use crate::devices::identifier::Identifier; use libusb::{Context, Result};...
use super::*; struct ServerState { model: Model, events: std::collections::VecDeque<Event>, next_event_index: usize, first_event_index: usize, clients_next_event: HashMap<Id, usize>, } impl ServerState { fn new(model: Model) -> Self { Self { model, events: defau...
use log::error; use warp::ws::Message; use std::time::SystemTime; use crate::database as db; use serde::{Serialize, Deserialize}; use deadpool_postgres::{Pool, PoolError}; use super::upgrade::{ConnID, Sender, Group, Groups, UserGroups}; #[derive(Deserialize)] #[serde(tag="type")] #[serde(rename_all="snake_case")] enum...
use itertools::Itertools; use regex::Regex; use std::collections::HashMap; use std::ffi::OsStr; use std::fs; use std::lazy::SyncLazy; use std::path::Path; use walkdir::WalkDir; use crate::clippy_project_root; const GENERATED_FILE_COMMENT: &str = "// This file was generated by `cargo dev update_lints`.\n\ // Use ...
use crate::gb::cpu::CPU; pub mod blu { use crate::gb::cpu::CPU; pub fn rlc_n(cpu: &mut CPU, n: u8) -> u8 { 0 } pub fn rrc_n(cpu: &mut CPU, n: u8) -> u8 { 0 } pub fn rl_n(cpu: &mut CPU, n: u8) -> u8 { 0 } pub fn rr_n(cpu: &mut CPU, n: u8) -> u8 { 0 ...
//! Support for compiling with Lightbeam. use crate::compilation::{CompileError, CompiledFunction, Compiler}; use crate::cranelift::{RelocSink, TrapSink}; use crate::func_environ::FuncEnvironment; use crate::{FunctionBodyData, ModuleTranslation}; use cranelift_codegen::isa; use cranelift_wasm::DefinedFuncIndex; use li...
// Copyright 2020-2021, The Tremor Team // // 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 agr...
extern crate libc; use std::ffi::CStr; use std::str::from_utf8; use native::libssh; pub fn from_native_str<'a>(native_str: *const libc::c_char) -> Result<&'a str, &'static str> { if native_str.is_null() { return Err("Could not convert NULL native string"); } unsafe { match fr...
use bitflags::bitflags; use bytes::{Buf, Bytes}; use encoding_rs::Encoding; use crate::encode::{Encode, IsNull}; use crate::error::Error; use crate::mssql::Mssql; bitflags! { #[cfg_attr(feature = "offline", derive(serde::Serialize, serde::Deserialize))] pub(crate) struct CollationFlags: u8 { const IGN...
use std::sync::{Arc, Mutex}; use tokio::sync::watch; use tokio::time::{delay_for, Duration}; const MAX_ID: u32 = 10; struct ME { last_log_index_tx: watch::Sender<u32>, last_log_index_rx: watch::Receiver<u32>, } #[tokio::test] async fn main() { let (tx, rx) = watch::channel(0); let me = ME { ...
extern crate tempfile; use std::collections::HashMap; use std::fs::{create_dir, File}; use std::io::Write; use std::process::{Child as ChildProcess, Stdio}; use tempfile::tempdir; #[test] fn roundtrip() -> Result<(), Box<dyn std::error::Error>> { let dir = tempdir()?; let files: HashMap<String, String> = (0....
#![allow(unused_variables, non_upper_case_globals, non_snake_case, unused_unsafe, non_camel_case_types, dead_code, clippy::all)] pub const D3DCOMPILER_DLL: &'static str = "d3dcompiler_47.dll"; pub const D3DCOMPILE_OPTIMIZATION_LEVEL2: u32 = 49152u32; pub const D3D_COMPILE_STANDARD_FILE_INCLUDE: u32 = 1u32;
use std::collections::BinaryHeap; use crate::algos::book::{Book, Order, Side, Trade}; /// Price-time priority (or FIFO) matching engine implemented using a [BinaryHeap]. /// /// Implemented as a state-machine to be used for replication with Raft. #[derive(Debug, Clone)] pub struct FIFOBook { asks: BinaryHeap<Orde...
// Copyright 2023 Datafuse Labs. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to ...
use std::ptr; /// Small helper for sending pointers which are not send. #[repr(transparent)] pub(crate) struct RawSend<T>(pub(crate) ptr::NonNull<T>) where T: ?Sized; // Safety: this is limited to the module and guaranteed to be correct. unsafe impl<T> Send for RawSend<T> where T: ?Sized {}
use rule::Rule; #[test] fn not_1() { let not_this = Rule::default(); not_this.literal("not this"); let r: Rule<i32> = Rule::default(); r.literal("aaa").not(&not_this).literal("bbb").literal("ccc"); assert!(r.scan("aaabbbccc").is_ok()); assert!(r.scan("aaanot thisbbbccc").is_err()); } ...
fn main(){ proconio::input!{k:u64}; let mut x=0; for i in 1..=k{ x=(x*10+7)%k; if x ==0{ println!("{}",i); return; } } println!("-1"); }
pub struct Solution; impl Solution { pub fn add_operators(num: String, target: i32) -> Vec<String> { if num.is_empty() { return Vec::new(); } let mut solver = Solver::new(num, target); solver.solve() } } #[derive(Clone, Copy)] enum Op { Concat, Times, Pl...
// 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 ...
pub mod units { pub enum Units { F, C, K, Unknown, } }
use std::path::Path; use std::path::PathBuf; use std::process::Command; use bstr::ByteSlice; use crate::cmd::call_on_path; use crate::error::FatalError; pub fn is_dirty(dir: &Path) -> Result<bool, FatalError> { let output = Command::new("git") .arg("diff") .arg("HEAD") .arg("--exit-code")...
use std::error::Error as StdError; use std::fmt::{Display, Formatter, Result}; use crate::parser::prelude::*; use crate::Key; use winnow::error::ContextError; use winnow::error::ParseError; /// Type representing a TOML parse error #[derive(Debug, Clone, Eq, PartialEq, Hash)] pub struct TomlError { message: Strin...
#[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::_0_GENA { #[doc = r"Modifies the contents of the register"] #[inline(always)] pub fn modify<F>(&self, f: F) where for<'w> F: FnOnce(&R, ...
/// The balance of an account #[derive( Clone, Debug, Eq, Ord, PartialEq, PartialOrd, parity_scale_codec::Decode, parity_scale_codec::Encode, )] pub struct AccountRate<A, B> { account: A, rate: B, } impl<A, B> AccountRate<A, B> { /// Creates a new instance from `account` and...
#[doc = "Reader of register SETUP_EV_PENDING"] pub type R = crate::R<u8, super::SETUP_EV_PENDING>; #[doc = "Writer for register SETUP_EV_PENDING"] pub type W = crate::W<u8, super::SETUP_EV_PENDING>; #[doc = "Register SETUP_EV_PENDING `reset()`'s with value 0"] impl crate::ResetValue for super::SETUP_EV_PENDING { ty...
use anyhow::{Context, Result}; use async_std::io::{Read, Write}; use async_std::net::{TcpListener, TcpStream}; use async_trait::async_trait; #[async_trait] pub trait GenericListener: Sync + Send { async fn accept<'a>(&'a self) -> Result<Socket>; } #[async_trait] impl GenericListener for TcpListener { async fn...
use std::{ fs::File, io::{BufReader, BufWriter}, }; use matrix_sdk::{ events::{room::message::MessageEventContent, AnyMessageEventContent}, Client, ClientConfig, Session, SyncSettings, }; use systemd::{journal, JournalRecord}; use crate::autojoin::AutoJoinHandler; use crate::Config; #[derive(Clone)] ...
use super::gl_render::Texture as Texture; use super::sprite::mipmapped_texture_from_path; use std::rc::Rc; pub struct Textures { pub tank_texture:Rc<Texture>, pub turret_texture:Rc<Texture>, pub enemy_tank_texture:Rc<Texture>, pub enemy_turret_texture:Rc<Texture>, pub bullet_texture:Rc<Texture>, } ...
// Copyright 2017 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 csv::ReaderBuilder; use std::{error::Error, fs::File}; pub type MyResult<T> = Result<T, Box<dyn Error>>; #[derive(Debug)] pub struct Config { pub files: Vec<String>, pub delimiter: u8, pub has_headers: bool, } // -------------------------------------------------- pub fn process( filename: &String...
#[macro_export] macro_rules! emoji { (":100:") => { "💯" }; (":1234:") => { "🔢" }; (":8ball:") => { "🎱" }; (":a:") => { "🅰" }; (":ab:") => { "🆎" }; (":abc:") => { "🔤" }; (":abcd:") => { "🔡" }; (":accept:") => { '🉑' }; (":adult:") => { "🧑" }...
//! An example hello world contract also used in unit tests. #![feature(wasm_abi)] extern crate alloc; use oasis_contract_sdk::{ self as sdk, env::{Crypto, Env}, types::{ env::{AccountsQuery, AccountsResponse, QueryRequest, QueryResponse}, message::{CallResult, Message, NotifyReply, Reply}...
// Generated by the capnpc-rust plugin to the Cap'n Proto schema compiler. // DO NOT EDIT. // source: helloworld.capnp pub mod hello_world { #![allow(unused_variables)] pub type SayHelloParams<> = ::capnp::capability::Params<::helloworld_capnp::hello_world::say_hello_params::Owned>; pub type SayHelloResults<> ...
use std::ops::Deref; use diesel::mysql::MysqlConnection; use diesel::r2d2::{ConnectionManager, Pool, PoolError, PooledConnection}; use crate::model::{NewTask, Task}; pub type MyPool = Pool<ConnectionManager<MysqlConnection>>; type MyPooledConnection = PooledConnection<ConnectionManager<MysqlConnection>>; pub fn ini...
use crate::*; pub fn print_time() { let start = SystemTime::now(); let datetime: DateTime<Utc> = start.into(); println!("{}", datetime.format("%d/%m/%Y %T")); } /// Iterates through ZoomResponse and inserts to database pub fn save_all_meetings(data: &ZoomResponse) { for meeting in &data.meetings { ...
use crate::api::v1::ceo::order::model; use crate::errors::ServiceError; use crate::models::order::Order as Object; use crate::models::DbExecutor; use crate::schema::order::dsl::{deleted_at, id, order as tb, shop_id, state, created_at}; use actix::Handler; use chrono::{Duration, Utc}; use crate::models::msg::Msg; use d...
use proconio::input; #[allow(unused_imports)] use proconio::marker::*; #[allow(unused_imports)] use std::cmp::*; #[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 = 1000000007; fn...
use std::time::Instant; use rand::Rng; mod ws_actors; use ws_actors::{ChatWs, PairingServer, UserType}; use actix::{Actor, Addr}; use actix_files::NamedFile; use actix_session::{CookieSession, Session}; use actix_web::{middleware, web, App, HttpRequest, HttpResponse, HttpServer, Responder}; use actix_web_actors::ws;...
use dbgify::*; struct Test(usize); impl Test { #[dbgify] fn add_one(&mut self, x: usize) { bp!(); self.0 += x; } } fn main() { let mut t = Test(1); t.add_one(1usize); }
use env::*; use fun::*; use objects::*; use types::*; fn init_eval(env: &mut SchemeEnv) { //env.add_global("eval", &SchemeObject::new_prim(eval)); } pub fn eval(obj: SchemeObject, env: &mut SchemeEnv) -> SchemeObject { let tipe = obj.get_type(); match tipe { SymbolType => { let val ...
use crate::domains::schema::MockConfig; pub trait LanguageInterpreter { fn as_python(&self) -> String; fn as_javascript(&self) -> String; } pub trait LanguageInterpreterForUnitTest { fn as_python(&self, mock_ref: &str, mock_config: &MockConfig, target_ref: &str) -> String; fn as_javascript(&self, mock...
use std::{ cell::RefCell, hash::{Hash, Hasher}, panic::{self, AssertUnwindSafe}, rc::Rc, }; use crate::{ callable::LuxCallable, environment::Environment, interpreter::{Interpreter, RuntimeResult}, literal::Literal, stmt::Stmt, token::Token, }; use rand::Rng; #[derive(PartialEq,...
extern crate math; use math::round; use std::vec::Vec; // Finds distance between two closest points in the plane by brute force // Input: A list p of n (n >= 2) points p_1(x_1, y_1), ..., p_n(x_n, y_n) // Output: The distance between the closest pair of points fn brute_force_closest_pair(p: &[(f64, f64)]) -> f64 { ...
use wasm::instance::{Instance, VmCtx, get_function_addr}; use wasm::{Module, ModuleEnvironment, DataInitializer}; use memory::{Region, MemFlags}; use nabi::{Result, Error}; use core::mem; use alloc::Vec; use nil::{Ref, KernelRef}; use cretonne_codegen::settings::{self, Configurable}; use cretonne_wasm::translate_module...
mod postgrespool; pub use self::postgrespool::DalPostgresPool; /* mod redispool; pub use self::redispool::DalRedisPool; mod dieselpool; pub use self::dieselpool::DalDieselPool; */
/// TagName provides tags for SVG creation #[derive(Clone, Copy, PartialEq, Eq, Debug, Hash)] pub enum TagName { /// [MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/SVG/Element/a) A, /// [MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/SVG/Element/animate) Animate, ...
pub fn run() { println!("\n----- function"); fn next_birthday(name: &str, current_age: u8) { let next_age = current_age +1; println!("Hi {}, on your next birthday, you'll be {}!", name, next_age); } next_birthday("Jake", 33); fn square(num: i32) -> i32 { num * num } ...
use super::{Number, Position, Size}; #[derive(Debug, Copy, Clone, PartialEq)] pub struct Region<N: Number = f32> { pub x: N, pub y: N, pub width: N, pub height: N, } pub type Viewport<N = f32> = Region<N>; impl<N: Number> Region<N> { pub fn new(x: N, y: N, width: N, height: N) -> Self { ...
// 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 ...
#![allow(clippy::comparison_chain)] #![allow(clippy::collapsible_if)] use std::cmp::Reverse; use std::cmp::{max, min}; use std::collections::{BTreeSet, HashMap, HashSet}; use std::fmt::Debug; use itertools::Itertools; use whiteread::parse_line; const ten97: usize = 1000_000_007; /// 2の逆元 mod ten97.割りたいときに使う const in...
use crate::graph::NodeItem; use crate::to_do_list_item::ToDoListItem; use petgraph::graph::NodeIndex; use petgraph::visit::Dfs; use petgraph::{Direction, Graph}; pub struct ToDoList { graph: Box<Graph<NodeItem, ()>>, } impl ToDoList { pub fn new() -> Self { let graph = Box::new(Graph::new()); ...
#[doc = r"Register block"] #[repr(C)] pub struct RegisterBlock { #[doc = "0x00 - DBGMCU_IDCODE"] pub idcode: IDCODE, #[doc = "0x04 - Debug MCU configuration register"] pub cr: CR, #[doc = "0x08 - Debug MCU APB1 freeze register1"] pub apb_fz1: APB_FZ1, #[doc = "0x0c - Debug MCU APB1 freeze re...
//! Gas metering instrumentation. use std::collections::BTreeMap; use walrus::{ir::*, FunctionBuilder, GlobalId, LocalFunction, Module}; use crate::Error; /// Name of the exported global that holds the gas limit. pub const EXPORT_GAS_LIMIT: &str = "gas_limit"; /// Name of the exported global that holds the gas limit...
// Copyright 2011 Google Inc. All Rights Reserved. // Copyright 2017 The Ninja-rs Project Developers. All Rights Reserved. // // 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:/...
// Copyright 2018 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. extern crate tempfile; use account_common::{ AccountAuthState, AccountManagerError, FidlAccountAuthState, FidlLocalAccountId, LocalAccountId, Resu...
const N : usize = 3; struct S { a: u64, b: [u64;N], } fn main() { let y = Box::new (3); let x : S = S { a: 10, b:[1,2,3]}; let mut a : u16 = 0xff00; //let ra : &mut u16 = & mut a; let p : * mut u16 = & mut a as * mut u16; let p1 : * mut u8 = p as * mut u8; unsafe { println!("hello world {} ", *p1.offset(1) ); ...
use crate::time::TimeContext; use ecs::{ResourceRegistry, RunSystemPhase, Service, ECS}; use std::collections::hash_map::HashMap; use std::hash::Hash; #[derive(Eq, PartialEq, Hash)] pub enum DebugKey { CurrentFPS, CameraPosition, CurrentBlock, BlockPos, } pub struct DebugInfo { map: HashMap<DebugK...
use std::net::{Ipv4Addr, SocketAddr, SocketAddrV4, TcpStream}; use std::path::{Path, PathBuf}; use std::str::FromStr; use std::thread::JoinHandle; use std::time::Duration; use std::{fs, io, thread}; use std::io::{Read, Write}; use std::sync::mpsc::{self, Receiver, Sender}; use nardol::prelude::{FromBytes, FromRon, Int...
// 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...
//! gRPC service for getting files from the object store a remote IOx service is connected to. Used //! in router, but can be included in any gRPC server. #![deny(rustdoc::broken_intra_doc_links, rustdoc::bare_urls, rust_2018_idioms)] #![warn( missing_copy_implementations, missing_debug_implementations, mi...
// Play a sound when a button is clicked extern crate quicksilver; use quicksilver::{ Result, geom::{Rectangle, Shape, Vector}, graphics::{Background::Col, Color}, input::{ButtonState, MouseButton}, lifecycle::{Asset, Settings, State, Window, run}, sound::Sound }; struct SoundPlayer { asse...
//主函数 fn main() { //println!("Hello, world!"); // 定义病初始化一个变量var1 let var1 = 1; //打印格式化文本并在结尾输出换行 println!("{}",var1); //对不可变变量重新赋值--->会报错 var1 = 2; println!("{}",var1); }
use base64; use bitcoin::blockdata::block::Block; use bitcoin::blockdata::transaction::Transaction; use bitcoin::consensus::encode; use bitcoin::hash_types::{BlockHash, Txid}; use lightning::chain::chaininterface::{BroadcasterInterface, ConfirmationTarget, FeeEstimator}; use lightning_block_sync::http::HttpEndpoint; us...
use std::io::{self, Write}; use std::fs::{remove_file, remove_dir}; use std::path::Path; use std::fmt; use std::process; const FILE_NAME: &'static str = "output.txt"; const DIR_NAME: &'static str = "demos"; fn main() { } fn delete<P>(root: P) -> io::Result<()> where P: AsRef<Path> { remove_file(ro...
extern crate regex; use std::io; use std::fs; use std::io::BufRead; use std::collections::HashMap; use std::path::Path; fn main() { let input = parse_input(); let mut space = input.space; for i in 1..=6 { space = space.next_space(); println!("After {} cycles, {} cells alive", i, space.cel...
#[derive(Debug, Serialize, Deserialize, Clone)] pub struct Claims { pub user_id: String, pub iat: i64, pub exp: i64, }