text
stringlengths
8
4.13M
#[doc = "Pulls type information out of the AST and attaches it to the document"]; import rustc::syntax::ast; import rustc::syntax::print::pprust; import rustc::middle::ast_map; export mk_pass; fn mk_pass() -> pass { run } fn run( srv: astsrv::srv, doc: doc::cratedoc ) -> doc::cratedoc { let fold =...
use std::clone::Clone; use std::default::Default; use std::option::Option; use std::option::Option::Some; use std::result::Result::Ok; use gdk::{EventButton, EventType}; use gio::prelude::*; use gtk::prelude::*; use gtk::{ ApplicationWindow, Builder, ButtonExt, GtkWindowExt, Inhibit, ListBox, ListBoxExt, PopoverEx...
use std::fs; fn main() { // Read input from file let contents = fs::read_to_string("input.txt").expect("Failed reading input file"); let program: Vec<&str> = contents.lines().collect(); // Challenge1 let state = run_program(&program); println!("Challenge1: {}", state.1); // Challenge2 ...
//! Simple writer to file descriptor using libc. //! //! ## Features: //! //! - `std` - Enables `std::io::Write` implementation. //! #![cfg_attr(not(test), no_std)] #![warn(missing_docs)] #[cfg(feature = "std")] extern crate std; use core::{slice, cmp, mem, ptr, fmt}; const BUFFER_CAPACITY: usize = 4096; ///Wrappe...
use std::{cmp, num::NonZeroU32}; use metrics::gauge; use super::{Clock, RealClock}; const INTERVAL_TICKS: u64 = 1_000_000; /// Errors produced by [`Stable`]. #[derive(thiserror::Error, Debug, Clone, Copy)] pub(crate) enum Error { /// Requested capacity is greater than maximum allowed capacity. #[error("Capa...
// Copyright (c) 2020 kprotty // // 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...
/* * Copyright (C) 2018 Kubos Corporation * * 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 ...
#[doc = "Reader of register SPINLOCK11"] pub type R = crate::R<u32, super::SPINLOCK11>; impl R {}
extern crate two_timer; use two_timer::{parsable, parse, Config, TimeError}; extern crate chrono; use chrono::naive::NaiveDate; use chrono::{Duration, Local, NaiveDateTime}; // a debugging method to print out the parse tree // fn show_me(p: &str) { // println!("{}", two_timer::MATCHER.parse(p).unwrap()); // } #[t...
use std::mem; use std::cmp; use std::str; use std::ptr; use spin::Mutex; use constants; use super::MemoryError; static MEMORY: Mutex<Manager> = Mutex::new(Manager::new()); #[derive(Debug, Clone, Copy)] struct Block { base: *mut u8, end: *mut u8, next: *mut Block, last: *mut Block, } struct Manager...
fn main() { if std::env::var_os("RUST_LOG").is_none() { std::env::set_var("RUST_LOG", "pathfinder=info"); } tracing_subscriber::fmt::init(); // simple tool for running and timing the database migrations on a given file. let path = match std::env::args().nth(1) { Some(name) if std::en...
use std::io::{Result, Write}; use std::borrow::Cow; use pulldown_cmark::{Tag, Event}; use crate::gen::{State, States, Generator, Document}; #[derive(Debug)] pub struct Link<'a> { dst: Cow<'a, str>, title: Cow<'a, str>, text: Vec<u8>, } impl<'a> State<'a> for Link<'a> { fn new(tag: Tag<'a>, gen: &mut...
use crate::size::*; use crate::point::*; #[derive(Copy, Clone, Debug)] pub struct Rect { pub position: Point, pub size: Size } impl Rect { pub fn new() -> Self { Rect { position: Point::new(), size: Size::new() } } // todo rename me pub fn fr...
pub use crate::state::gameplay::GameplayState; mod gameplay;
use std::thread; use std::thread::{JoinHandle}; use std::sync::mpsc::{Sender, Receiver}; use castnow::{Command, KeyCommand}; use state::State; use shell::Launcher; use std::error::Error; pub struct Processor { } impl Processor { pub fn new() -> Processor { Processor {} } pub fn start(&self, rx: R...
//! This module contains functionality for parsing a regular expression into the intermediate //! representation in repr.rs (from which it is compiled into a state graph), and optimizing that //! intermediate representation. #![allow(dead_code)] use std::iter::FromIterator; use std::ops::{Index, Range, RangeFull}; us...
fn main() { // boolean let x = true; let y: bool = false; println!("x: {},y: {}",x,y); // char let x = 'x'; let two_hearts = '💕'; println!("x: {},two_hearts: {}",x,two_hearts); // 整数型 let x = 42; let y = 1.0; println!("x: {},y: {}",x,y); // 配列 let a: [i32; 3] ...
pub struct IntoIter<T>(List<T>); impl<T> Iterator for IntoIter<T> { type Item = T; fn next(&mut self) -> Option<Self::Item> { // access fields of a tuple struct numerically self.0.pop() } } pub struct List<T> { head: Link<T> }
//! Composite types. pub use self::strukt::StructType; pub use self::seq::*; pub mod strukt; pub mod seq; use ir::Type; /// A composite type. pub struct CompositeType<'ctx>(Type<'ctx>); impl_subtype!(CompositeType => Type);
/// AnnotatedTag represents an annotated tag #[derive(Debug, Default, Clone, Serialize, Deserialize)] pub struct AnnotatedTag { pub message: Option<String>, pub object: Option<crate::annotated_tag_object::AnnotatedTagObject>, pub sha: Option<String>, pub tag: Option<String>, pub tagger: Option<crat...
use generics::{Generic, Prod, Unit}; trait Accumulate { fn acc(self) -> u64; } impl Accumulate for u64 { fn acc(self) -> u64 { self } } impl Accumulate for Unit { fn acc(self) -> u64 { 0 } } impl<A, B> Accumulate for Prod<A, B> where A: Accumulate, B: Accumulate, { fn...
#[doc = "Register `VCTR57` reader"] pub type R = crate::R<VCTR57_SPEC>; #[doc = "Register `VCTR57` writer"] pub type W = crate::W<VCTR57_SPEC>; #[doc = "Field `B1824` reader - B1824"] pub type B1824_R = crate::BitReader; #[doc = "Field `B1824` writer - B1824"] pub type B1824_W<'a, REG, const O: u8> = crate::BitWriter<'...
use crate::layout::LayoutBox; use crate::paint::entity::{DisplayCommand, DisplayList}; use crate::paint::utils::get_color; pub fn render_background(list: &mut DisplayList, layout_box: &LayoutBox) { // FIXME: background-colorにしか対応していないので、background両方に対応させたい get_color(layout_box, "background-color").map(|color| ...
fn main() { println!("Hola, soy un mensaje de la linea 3"); println!("Hola, soy un mensaje de la linea 5"); panic!("El programa finaliza de forma inesperada!!"); println!("Hola, soy un mensaje de la linea 9"); println!("Hola, soy un mensaje de la linea 11"); println!("Hola, soy un mensaje ...
// Copyright (c) 2016, <daggerbot@gmail.com> // This software is available under the terms of the zlib license. // See COPYING.md for more information. extern crate aurum_display; use aurum_display::{Display, Event, WindowStyle}; fn main () { let display = Display::open().unwrap(); let device = display.defau...
extern crate kafka; use kafka::client::KafkaClient; /// This program demonstrates consuming messages through `KafkaClient`. This is the top level /// client that will fit most use cases. Note that consumed messages are tracked by Kafka so you /// can only consume them once. This is what you want for most use cases, yo...
/* * 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::io; use std::path::PathBuf; use std::process::Command; use std::process::ExitStatus; pub ...
fn main() { //Rust中数组的语法 let a = [1, 2, 3, 4, 5]; let a:[i32;5] = [1, 2, 3, 4, 5];//[类型:元素数量] let a:[3;5];//[初始值:元素数量]=>[3, 3, 3, 3, 3] //访问元素数量 let first = a[0]; let second = a[1]; //Rust安全原则,当索引超出数组的长度时,编译时不会报错。 //但在运行时,会产生panic }
use {DataHelper, EntityIter}; #[derive(Default, System)] #[system_type(Entity)] #[process(process)] #[aspect(all(player, transform))] pub struct CameraFollow; fn process(_: &mut CameraFollow, mut players: EntityIter, data: &mut DataHelper) { if let Some(player) = players.nth(0) { let player_pos = data.com...
//! An alternative solver based around the SLG algorithm, which //! implements the well-formed semantics. See the README.md //! file for details. #![cfg_attr(not(test), allow(dead_code))] // FOR NOW crate mod forest; mod logic; mod stack; mod strand; mod table; mod tables; mod test; use ir::ProgramEnvironment; use ...
use crate::input::keyboard::Key; use crate::input::{mouse::ViewportPosition, InputPreprocessor}; use crate::message_prelude::*; use glam::{DAffine2, Vec2Swizzles}; use graphene::Operation; #[derive(Clone, Debug, Default)] pub struct Resize { pub drag_start: ViewportPosition, pub path: Option<Vec<LayerId>>, } impl Re...
mod bubblesort; mod insertionsort; mod quicksort; mod selectionsort; use std::fmt::Debug; pub use bubblesort::BubbleSort; pub use insertionsort::InsertionSort; pub use quicksort::Quicksort; pub use selectionsort::SelectionSort; pub trait Sorter { fn sort<T>(self, slice: &mut [T]) where T: Ord + Clone ...
use crate::transaction::{Address, Authorization, CoinId, Input, Output, Transaction}; use bincode::serialize; use ed25519_dalek::Keypair; use rand::rngs::OsRng; use std::cell::RefCell; use std::collections::HashMap; use std::sync::atomic::{AtomicUsize, Ordering}; use std::sync::Mutex; use std::{error, fmt}; pub cons...
use crate::prelude::*; use crate::responses::DeleteDocumentResponse; use azure_core::modify_conditions::IfMatchCondition; use azure_core::prelude::*; use chrono::{DateTime, Utc}; use http::StatusCode; use std::convert::TryInto; #[derive(Debug, Clone)] pub struct DeleteDocumentBuilder<'a> { document_client: &'a Doc...
use std::io; fn main() { let mut user_input = String::new(); //user_input is a variable name //let mut user_input = ""; //user_input is a variable name println!("Type Your Name:"); io::stdin().read_line(&mut user_input).expect("Failed to read line"); //io::stdin().read_line(&mut user_input).unwr...
extern crate core; extern crate itertools; extern crate glob; extern crate either; extern crate redis; mod file; mod hash_utils; pub mod method; pub mod response; pub mod address; pub mod actor; pub mod log_entry; pub mod invalid_log_entry; pub mod nginx_processing_results; pub mod nginx; pub mod processor;
#![cfg_attr( target_arch = "spirv", no_std, feature(register_attr, lang_items), register_attr(spirv) )] // HACK(eddyb) can't easily see warnings otherwise from `spirv-builder` builds. #![deny(warnings)] #[cfg(not(target_arch = "spirv"))] #[macro_use] pub extern crate spirv_std_macros; #[allow(unused_im...
extern crate crypto; use crypto::sha3::Sha3; use std::vec::Vec; #[derive(Debug)] struct Fig { previous_hash: String, changes: Vec<String>, hash: String } impl Fig { fn previous_hash(&self) -> &str { &self.previous_hash } fn hash(&self) -> &str { &self.hash }...
use super::{ Config, BalanceOf, Module, Error, RawEvent, TeamAccounts, CustodyAccounts, TotalCustody }; use sp_runtime::{Perbill, RuntimeDebug}; use sp_std::prelude::*; use sp_std::convert::TryFrom; use codec::{Encode, Decode, HasCompact}; use frame_support::traits::{ Currency, ReservableCurrency, Get, Exi...
pub struct StatusFlags { pub carry: bool, pub zero: bool, pub interrupt_disabled: bool, pub decimal: bool, pub breakpoint: bool, pub unused: bool, pub overflow: bool, pub sign: bool, } impl StatusFlags { pub fn to_u8(&self) -> u8 { let carry = if self.carry { 0x01 } else { ...
#[doc = "Register `UR5` reader"] pub type R = crate::R<UR5_SPEC>; #[doc = "Field `MESAD_1` reader - Mass erase secured area disabled for bank 1"] pub type MESAD_1_R = crate::BitReader; #[doc = "Field `WRPS_1` reader - Write protection for flash bank 1"] pub type WRPS_1_R = crate::FieldReader; impl R { #[doc = "Bit ...
//! [RefCell<T>] and the Interior Mutability Pattern //! //! [refcell<t>]: https://doc.rust-lang.org/book/ch15-05-interior-mutability.html /// Message trait to trigger to send a message. pub trait Messenger { fn send(&self, message: &str); } /// Tracking the limit and call `send()` method of `Messenger` trait imp...
use std::io::Write; pub fn main() -> std::io::Result<()> { let rst = ublox::CfgRstBuilder { nav_bbr_mask: ublox::NavBbrMask::all(), reset_mode: ublox::ResetMode::HardwareResetImmediately, reserved1: 0, }; let bytes = rst.into_packet_bytes(); let mut file = std::fs::File::create...
/** * MIT License * * termail - Copyright (c) 2021 Larry Hao * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, c...
use gumdrop::Options; use bls_snark::ValidatorSetUpdate; use zexe_algebra::{Bls12_377, BW6_761}; use zexe_r1cs_core::ConstraintSynthesizer; use zexe_r1cs_std::test_constraint_counter::ConstraintCounter; use phase2::parameters::{circuit_to_qap, MPCParameters}; use snark_utils::{log_2, Groth16Params, Result, UseCompres...
use ini::Ini; use std::process; use std::io; use std::io::Write; use colored::*; mod utils; use utils::DataMM; use utils::{normalize_elem, denormalize_elem, error_invalid_key}; fn main() { let mut theta_0:f64 = 0.0; let mut theta_1:f64 = 0.0; let mut label_x: Option<String> = None; let mut label_y: Option<String> ...
#[doc = "Register `HWCFGR2` reader"] pub type R = crate::R<HWCFGR2_SPEC>; #[doc = "Field `OPTIONREG_OUT` reader - OPTIONREG_OUT"] pub type OPTIONREG_OUT_R = crate::FieldReader; #[doc = "Field `TRUST_ZONE` reader - TRUST_ZONE"] pub type TRUST_ZONE_R = crate::FieldReader; impl R { #[doc = "Bits 0:7 - OPTIONREG_OUT"] ...
use lalrpop_util::lalrpop_mod; lalrpop_mod!(pub parser, "/parser.rs"); use parser::*; use crate::ast::*; use crate::memory::*; use std::collections::HashMap; pub mod ast; pub mod memory; // EVALUATING FUNCTIONS fn eval_infix(l: Val, oc: &OpCode, r: Val) -> Val { match (l, oc, r) { (Val::Num(l), oc, Val:...
use std::fs; use crate::poc::{BugMetadata, PocMap}; use crate::prelude::*; use askama::Template; use once_cell::sync::Lazy; use structopt::StructOpt; #[derive(Debug, StructOpt)] pub struct UpdateArgs {} enum LinkStyle { Image { alt_text: String, image_url: String }, Text(String), Plaintext, } struct Md...
use std::env; use std::process; use std::fs::File; use std::io::{self, BufRead}; fn main() -> Result<(), io::Error> { let args: Vec<String> = env::args().collect(); if args.len() < 2 { println!("Too few arguments."); process::exit(1); } let filename = &args[1]; let file = File::open...
#![no_std] #[macro_use] extern crate alloc; pub mod macros; mod traits; pub use traits::Hash;
#[doc = "Register `CCR` reader"] pub type R = crate::R<CCR_SPEC>; #[doc = "Register `CCR` writer"] pub type W = crate::W<CCR_SPEC>; #[doc = "Field `DUAL` reader - Dual ADC mode selection"] pub type DUAL_R = crate::FieldReader<DUAL_A>; #[doc = "Dual ADC mode selection\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, ...
use futures::{future, Future}; use hyper::header::{HeaderName, HeaderValue}; use hyper::service::service_fn; use hyper::{Body, Request, Response, Server}; use hyper::{Method, StatusCode}; use lazy_static::lazy_static; use maplit::btreemap; use std::collections::BTreeMap; use std::path::Path; use std::sync::Arc; lazy_s...
// https://adventofcode.com/2017/day/19 extern crate regex; use std::io::{BufRead, BufReader}; use std::fs::File; use std::collections::HashSet; use std::iter::FromIterator; use regex::Regex; fn main() { // Set up regex for matching the different vectors, concat! as raws don't support multiline let particle_...
use crate::common::TreeNode; use std::cell::RefCell; use std::rc::Rc; use std::collections::HashMap; struct Solution; impl Solution { pub fn build_tree(inorder: Vec<i32>, mut postorder: Vec<i32>) -> Option<Rc<RefCell<TreeNode>>> { if inorder.is_empty() { return None; } // 每个元素的...
use std::fs; use std::collections::HashSet; use std::iter::FromIterator; fn parse(content: &String) -> Vec<HashSet<char>> { let mut vec: Vec<HashSet<char>> = Vec::new(); let groups_it = content .split("\n\n"); for group in groups_it { let mut ans: HashSet<char> = HashSet::new(); let me...
// This file is part of Substrate. // Copyright (C) 2017-2020 Parity Technologies (UK) Ltd. // SPDX-License-Identifier: Apache-2.0 // 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 // // ht...
use crate::{ constants::{K256, K512}, util::{load_u32_be, load_u64_be, memcpy, memset, store_u128_be, store_u32_be, store_u64_be}, }; use core::mem; macro_rules! sha { ( $name:ident, $word:ty, $load_word:ident, $store_word:ident, $k:ident, $length:ty, ...
struct MinStack { v: Vec<i32>, minv: Vec<i32> } /** * `&self` means the method takes an immutable reference. * If you need a mutable reference, change it to `&mut self` instead. */ impl MinStack { /** initialize your data structure here. */ fn new() -> Self { Self{ v: Vec::...
fn main() { println!("{:?}", "STDOUT".chars()); }
use bevy::prelude::*; pub struct Explosion; pub struct ExplosionMaterial(Handle<ColorMaterial>); pub const EXPLOSION_WIDTH: f32 = 800.; pub const EXPLOSION_HEIGHT: f32 = 800.; pub fn init( commands: &mut Commands, asset_server: &AssetServer, materials: &mut ResMut<Assets<ColorMaterial>>, ) { let plat...
use crate::client::Client; use ureq::{Error}; use serde::{Deserialize}; #[derive(Deserialize)] pub struct ValidateForVoiceResponse { pub code: Option<String>, pub error: Option<String>, pub formatted_output: Option<String>, pub id: Option<u64>, pub sender: Option<String>, pub success: bool, ...
//! Custom derive support for `zeroize` #![crate_type = "proc-macro"] #![deny(warnings, unused_import_braces, unused_qualifications)] #![forbid(unsafe_code)] extern crate proc_macro; #[macro_use] extern crate quote; #[macro_use] extern crate syn; use proc_macro::TokenStream; macro_rules! q { ($($t:tt)*) => (quo...
use crate::terminal::SIZE; use crate::util::Size; pub mod colors; pub mod events; pub const SIZE: Size = Size { width: 26, height: 12, }; pub const GRAYSCALE_COLOR_COUNT: SIZE = 24; pub const INPUT_FIELD_WIDTH: SIZE = GRAYSCALE_COLOR_COUNT; pub const FOUR_BIT_COLOR_COUNT: SIZE = 8 * 2;
use crate::DATABASE; use rusqlite::NO_PARAMS; use rusqlite::{Connection, Result}; // Creates the database in case it doesn't exist pub fn create() -> Result<()> { let conn = Connection::open(DATABASE.to_owned())?; conn.execute( "create table if not exists users ( id integer primary key, ...
//#[macro_use] //extern crate bitflags; pub mod token; pub mod lexer; pub mod parser; pub mod ast; #[derive(Debug, Default, Clone, Copy, PartialEq)] pub struct SrcPos(pub u32, pub u32); impl SrcPos { pub fn from_src_pos(pos: &SrcPos) -> SrcPos { pos.clone() } pub fn invalid() -> SrcPos { ...
struct Solution; impl Solution { // 消除最右边的 1 pub fn range_bitwise_and(m: i32, mut n: i32) -> i32 { while m < n { // 使用 &= 性能提升很多?? // n = n & (n - 1); n &= n - 1; } n } // 位移法。 pub fn range_bitwise_and2(mut m: i32, mut n: i32) -> i32 { ...
#[macro_use] extern crate lazy_static; extern crate radix_trie; #[macro_use] mod macros; mod lexicon; mod puzzle; fn main() { println!("Hello, world!"); }
use messages::{Message, Payload}; use errors::Errors; use json; use json::JsonValue; use v2; fn get_key<'a>(json : &'a JsonValue, key : &str) -> Result<&'a JsonValue, Errors> { let j = &json[key]; if j.is_null() { Err(Errors::Missing(key.to_string())) } else { Ok(j) } } fn to_u64(json...
use anyhow::{anyhow, Context, Result}; use serde::ser::Serializer; use serde::ser::SerializeSeq; use crate::config::read_config; use crate::db::active_notes; pub fn exec() -> Result<()> { let cfg = read_config() .context("Reading config")?; let db = sqlite::open(&cfg.db_path) .context("Opening ...
use crate::effects; use serde::Deserialize; #[derive(Debug, Deserialize)] pub struct Tritone { #[serde(rename = "ix")] pub index: i64, #[serde(rename = "mn")] pub match_name: String, #[serde(rename = "nm")] pub name: String, #[serde(rename = "ef")] pub effects: ( effects::Color,...
use num::One; use alga::general::{ClosedMul, ClosedSub, ClosedAdd}; use core::{Scalar, SquareMatrix}; use core::dimension::Dim; use core::storage::Storage; impl<N, D: Dim, S> SquareMatrix<N, D, S> where N: Scalar + One + ClosedMul + ClosedAdd + ClosedSub, S: Storage<N, D, D> { /// This matrix dete...
// 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 support::{ decl_module, decl_storage, decl_event, dispatch::Result, StorageValue, StorageMap, ensure, traits::{ Currency, ReservableCurrency } }; use { system::ensure_signed, timestamp }; // this is needed when you want to use Vec and Box use rstd::prelude::*; use runtime_primitives::traits::{ As, /*CheckedAdd, ...
use std::any; use std::fmt; use crate::number::Number; use crate::token::Token; ////////////////////////////////////////////////////////////////////// /// Operator ////////////////////////////////////////////////////////////////////// #[derive(Copy, Clone, Debug, Eq, PartialEq)] pub enum Operator { SUM, SUB,...
use std::collections::HashSet; use std::fs::File; use std::io::{BufRead, BufReader}; type Coordinate = (usize, usize); type DumboOctopusEnergyLevels = [[u8; 10]; 10]; fn main() { let filename = "input/input.txt"; let mut energy_levels: DumboOctopusEnergyLevels = parse_input_file(filename); let initial_ene...
extern crate evdev_rs; use evdev_rs::enums::{EventCode, EV_KEY}; use evdev_rs::Device; use std::fs::File; use std::sync::mpsc::Sender; use std::sync::{Arc, Mutex}; use std::thread; use crate::utils::CheckedSender; use crate::web::http_client::*; use crate::{env, ApplicationContext, ApplicationState, Message}; pub st...
use crate::error::ServerError; use crate::service::multipart::MultipartFile; use handlebars::{Handlebars, TemplateRenderError as HandlebarTemplateRenderError}; use lettre::SendableEmail; use lettre_email::{error::Error as LetterError, EmailBuilder}; use mrml; use serde::{Deserialize, Serialize}; use serde_json::Value a...
fn rebind(){ let sum = 0; println!("sum : {}",sum); for i in 0..10 { // 新しい束縛を作っているので上の束縛には影響がない。 let sum = sum + i; } println!("rebind sum : {}", sum); // => 0 } fn reassign() { let mut sum = 0; println!("sum : {}", sum); for i in 0..10 { // 上の束縛の値を書き換える。 ...
use crate::geometry; use crate::multivector::*; use web_sys::console::dir; /// Given two points `p0` and `p1`, there is a unique fold that passes through both of them. pub fn axiom_1(p0: &Multivector, p1: &Multivector) -> Multivector { let mut crease = p0.join(p1); crease.normalized() } /// Given two points `...
#[doc = "Reader of register OA0_COMP_TRIM"] pub type R = crate::R<u32, super::OA0_COMP_TRIM>; #[doc = "Writer for register OA0_COMP_TRIM"] pub type W = crate::W<u32, super::OA0_COMP_TRIM>; #[doc = "Register OA0_COMP_TRIM `reset()`'s with value 0"] impl crate::ResetValue for super::OA0_COMP_TRIM { type Type = u32; ...
use std::collections::HashMap; fn read_line() -> String { let mut line = String::new(); std::io::stdin().read_line(&mut line).unwrap(); line.trim_end().to_owned() } fn main() { let solver = Solver::new(read_line()); let stdout = solver.solve(); stdout.iter().for_each(|s| { println!("{}...
//! # The Roku OS Kernel //! // =============================================================================================== // Configuration // =============================================================================================== #![feature( asm, alloc, collections, const_fn, lang_it...
// Here it goes all the stuff related to the UI part of the "Update Checker" and the future "Autoupdater". extern crate serde_json; extern crate gtk; extern crate restson; use self::restson::RestClient; use gtk::prelude::*; use gtk::{ApplicationWindow, MessageDialog, Statusbar, DialogFlags, MessageType, ButtonsType}; ...
use dbus; use dbus::tree::{MTFn, Method}; use std::cell::RefCell; use std::rc::Rc; use std::sync::atomic::Ordering; use crate::daemon::{dbus_helper::DbusFactory, Daemon, DaemonStatus}; // Methods supported by the daemon. pub const FETCH_UPDATES: &str = "FetchUpdates"; pub fn fetch_updates( daemon: Rc<RefCell<Dae...
use bellperson::bls::Engine; use bellperson::{Circuit, ConstraintSystem, SynthesisError}; use fff::Field; pub const MIMC_ROUNDS: usize = 322; pub fn mimc<E: Engine>(mut xl: E::Fr, mut xr: E::Fr, constants: &[E::Fr]) -> E::Fr { assert_eq!(constants.len(), MIMC_ROUNDS); for i in 0..MIMC_ROUNDS { let mu...
use crate::objects::hittable::HitRecord; use crate::utils::util::random_double; use crate::vec::vec3::{Color, Ray, Vec3}; pub trait Material: Sync + Send { fn scatter(&self, r_in: &Ray, rec: &HitRecord) -> Option<(Ray, Vec3)>; } // ---------------------------------------------------------------------- // ----- ME...
use super::component::*; use super::event::{Event, Events}; use crate::ui::rectangles::Rectangles; use crate::api::{Client, Downloads, UpdateChecker}; use crate::cache::Cache; use crate::config::Config; use crate::ui::*; use crate::Messages; use std::error::Error; use std::process::Command; use std::sync::atomic::{At...
use crossterm::tty::IsTty; mod custom_commands; mod git_actions; mod hg_actions; mod input; mod repositories; mod revision_shortcut; mod scroll_view; mod select; mod tui; mod tui_util; mod version_control_actions; fn main() { if !std::io::stdin().is_tty() { eprintln!("not tty"); return; } ...
use std::{ rc::Rc, sync::{ Mutex, Arc, }, cell::RefCell, }; use crate::{ renderer::{ RenderPassStatistics, framework::{ gl, geometry_buffer::{ ElementKind, GeometryBuffer, AttributeDefinition, ...
use std::io::{self, BufWriter, Write}; use std::path::Path; use crossterm::{ queue, style::{Attribute, Color, ContentStyle, Print, SetAttribute, SetForegroundColor, SetStyle}, }; use super::{Error, VestiErr}; use crate::location::Span; const BOLD_TEXT: SetAttribute = SetAttribute(Attribute::Bold); const ERR_...
use poker::Hand; use std::str::FromStr; fn main() { let hand = Hand::deal(5); println!("hand = {}", hand); println!("{}", hand.evaluate()); let hand = Hand::from_str("A♥ K♥ Q♥ J♥ 10♥").unwrap(); println!("\nhand = {}", hand); println!("{}", hand.evaluate()); }
pub fn fraction_to_decimal(mut numerator: i32, mut denominator: i32) -> String { if numerator == 0 { return "0".to_string() } let mut result = vec![]; if (numerator as i64) * (denominator as i64) < 0 { result.push("-".to_string()); } let mut numerator = (numerator as i64).abs(); ...
use std::future::Future; use std::io; use std::marker::PhantomData; pub(crate) mod time; pub(crate) fn get_default_runtime_size() -> usize { 0 } static NO_RUNTIME_NOTICE: &str = r#"No runtime configured for this platform, \ features that requires a runtime can't be used. \ Either compile with `target_arc...
pub mod builtins; pub mod utils; pub mod read_line; pub mod exec; use std::env; use std::path::{Path, PathBuf}; use std::fmt; use std::io; use std::io::Write; use std::collections::HashMap; use std::collections::hash_map::Entry; #[derive(Clone)] pub struct State { cwd: PathBuf, aliases: HashMap<String, String...
use emu8080::Cpu; use sdl2::event::Event; use sdl2::keyboard::Keycode; use sdl2::pixels::Color; use sdl2::rect::Rect; use sdl2::render::Canvas; use sdl2::video::Window; use sdl2::EventPump; use std::fs::File; use std::io::prelude::*; use std::time::Duration; use std::time::Instant; const HEIGHT: u32 = 224; const WIDT...
extern crate log; use mio::{Events, Poll, Ready, PollOpt, Token}; use mio::tcp::{TcpListener, TcpStream}; use std::net::{SocketAddr}; use std::collections::{HashMap}; use std::{thread, time}; use std::io::{self, Read, Write}; use super::peer::{PeerContext, PeerDirection}; use super::MSG_BUF_SIZE; use super::message::{M...
//! The rrpcore crate contains all the building blocks to run a reverse proxy. //! RRP is heavily based off of Netflix's Zuul framework. HTTP requests are run //! through a series of user defined Filter's, which process the request and can //! take several actions including validating the request, routing the request,...
pub mod create_table; pub mod delete_query; pub mod insert_query; pub mod select_query; use std::fmt; use self::create_table::CreateTableQuery; use self::delete_query::DeleteQuery; use self::insert_query::InsertQuery; use self::select_query::SelectQuery; #[derive(Debug, PartialEq)] pub enum ValidatedStatement { ...
//! Support for streaming objects from a Parquet file. use std::fs::File; use std::path::Path; use std::thread::spawn; use crossbeam::channel::{bounded, Receiver}; use anyhow::Result; use arrow2::chunk::Chunk; use log::*; use arrow2::array::{Array, StructArray}; use arrow2::io::parquet::read::{infer_schema, read_met...