text
stringlengths
8
4.13M
iter range(a: int, b: int) -> int { assert (a < b); let i: int = a; while i < b { put i; i += 1; } } fn main() { let sum: int = 0; for each x: int in range(0, 100) { sum += x; } log sum; }
extern crate regex; use aoc2019::io::slurp_stdin; use std::iter::FromIterator; fn get_input() -> (Vec<i64>, Vec<i64>, Vec<i64>) { let re = regex::Regex::new(r"<x=(-?\d+), y=(-?\d+), z=(-?\d+)>").unwrap(); let mut xs = Vec::new(); let mut ys = Vec::new(); let mut zs = Vec::new(); for m in re.capt...
#[doc = r"Register block"] #[repr(C)] pub struct RegisterBlock { #[doc = "0x00 - Clock control, can be changed on-the-fly (except for auxsrc)"] pub clk_gpout0_ctrl: CLK_GPOUT0_CTRL, #[doc = "0x04 - Clock divisor, can be changed on-the-fly"] pub clk_gpout0_div: CLK_GPOUT0_DIV, #[doc = "0x08 - Indicat...
use std::error::Error; use std::fmt; #[derive(Debug)] pub struct HandleCreationError { pub code: i32 } impl Error for HandleCreationError { fn description(&self) -> &str { match self.code { -1 => "Generic failure", -2 => "Out of memory", -3 => "Hardware revision is not supported", -4 => "Memory lock f...
use serde_json::json; use sqlx::{Pool, Row, Sqlite}; use std::sync::Arc; use super::model::{CompactPost, DBPost, Post}; use crate::_utils::{database::DBOrderDirection, error::DataAccessError}; pub struct PostRepository { main_sql_db: Arc<Pool<Sqlite>>, } impl PostRepository { pub fn new(main_sql_db: Arc<Pool<Sql...
use tproto::BindClient; use tcore::reactor::{Core, Handle, Remote}; use tio::{AsyncRead, AsyncWrite}; use tio::codec::Framed; use tproto::pipeline::{ClientService, ClientProto}; use tserv::{Service, NewService}; use bytes::Bytes; use std::io; use codec::AMQPCodec; pub struct AMQPProto; // impl<T: AsyncRead + Async...
#![feature(allocator_api)] mod error; mod rule; use libip6tc_sys as sys; use std::ffi::{CStr, CString}; use error::IptcError; struct Table4 { // TODO: } struct Table6 { handle: *mut sys::xtc_handle, table_name: CString, } impl Table6 { pub fn new(table_name: &str) -> Result<Self, IptcError> { ...
use cloverleaf_core::sdp::parse_candidate; use cloverleaf_core::sdp::Sdp; use cloverleaf_core::CandidateType; #[test] fn test_sdp_parsing() { let text = "a=ice-pwd:99ad05513f44705637769b05c7e86c0b\r\na=ice-ufrag:ae11196c\r\n"; let sdp = Sdp::from(text); assert!(sdp.ufrag.as_str() == "ae11196c"); assert...
use std::{collections::HashMap, net::SocketAddr}; use { crate::{atom::Atom, config, document::Document, range::Range}, bincode::{deserialize, serialize}, serde::{Deserialize, Serialize}, serde_json::ser::to_vec, std::io, tokio::{ io::{AsyncReadExt, AsyncWriteExt}, net::{TcpListe...
// Copyright (c) The diem-devtools Contributors // SPDX-License-Identifier: MIT OR Apache-2.0 use chrono::DateTime; use goldenfile::Mint; use quick_junit::{ NonSuccessKind, Property, Report, TestRerun, Testcase, TestcaseStatus, Testsuite, }; use std::time::Duration; #[test] fn fixtures() { let mut mint = Mint...
// client (p2p) packets use serde::{Deserialize, Serialize}; // the version constant. increased by 100 every minor client version, and by 10000 every major // version. eg. 200 is 0.2.0, 10000 is 1.0.0, 10203 is 1.2.3. // if two versions' hundreds places differ, the versions are incompatible. pub const PROTOCOL_VERSIO...
pub mod database_initialization; pub mod role_permissions; use std::env; use tokio_postgres::NoTls; pub struct DatabaseConnection { pub client: tokio_postgres::Client, } static mut CONNECTION: Option<DatabaseConnection> = None; pub async fn get_connection<'a>() -> &'a DatabaseConnection { unsafe { i...
use super::expression::Expression; use crate::types; #[derive(Clone, Debug, PartialEq)] pub struct Record { type_: types::Record, elements: Vec<Expression>, } impl Record { pub fn new(type_: types::Record, elements: Vec<Expression>) -> Self { Self { type_, elements } } pub fn type_(&self)...
#[derive(PrimitiveEnum_u8)] #[derive(Debug, Copy, Clone, PartialEq)] #[allow(non_camel_case_types)] /// MSP command values, used for command encapsulation pub enum MspCommandCode { MSP_API_VERSION = 1, MSP_FC_VARIANT = 2, MSP_FC_VERSION = 3, MSP_BOARD_INFO = ...
#![no_main] extern crate abxml; #[macro_use] extern crate libfuzzer_sys; use abxml::chunks::XmlNamespaceStartWrapper; use abxml::model::NamespaceStart; fuzz_target!(|data: &[u8]| { let xnsw = XmlNamespaceStartWrapper::new(data); xnsw.get_prefix_index(); xnsw.get_namespace_index(); xnsw.get_line(); })...
use friday_error::FridayError; use std::fmt; pub enum Symbol { Own } impl fmt::Display for Symbol { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self { Symbol::Own => f.write_str("**") } } } #[derive(Clone)] pub struct Path { components: Vec<String> } imp...
#[doc = "Register `PKGR` reader"] pub type R = crate::R<PKGR_SPEC>; #[doc = "Field `PKG` reader - Package"] pub type PKG_R = crate::FieldReader; impl R { #[doc = "Bits 0:3 - Package"] #[inline(always)] pub fn pkg(&self) -> PKG_R { PKG_R::new((self.bits & 0x0f) as u8) } } #[doc = "SYSCFG package ...
use std::{ collections::HashMap, convert::TryFrom, fmt, fs::File, io::{Read, Write}, path::PathBuf, process::{self, Command}, rc::Rc, }; use cargo_lock::{Dependency, Lockfile}; use cargo_metadata::MetadataCommand; use cargo_toml::{Edition, Manifest}; use petgraph::visit::Bfs; macro_rul...
extern crate rss; use rss::Channel; use rss::extension::dublincore::DublinCoreExtension; use rss::extension::get_extension_values; #[test] fn read_channel() { let input = include_str!("data/channel.xml"); let channel = input.parse::<Channel>().expect("failed to parse xml"); assert_eq!(channel.title, "Tit...
use ssh2::{Session, Channel}; use std::error::Error; use std::net::TcpStream; use std::path::Path; use std::io::Write; use yaml_rust::{YamlLoader, Yaml}; use std::fs; use regex::Regex; use clap::ArgMatches; fn create_session(host: &str) -> Result<Session, Box<dyn Error>> { match (TcpStream::connect(host), Session:...
use crate::prelude::*; use azure_core::prelude::*; use http::StatusCode; use std::convert::TryInto; #[derive(Debug, Clone)] pub struct DeleteAttachmentBuilder<'a, 'b> { attachment_client: &'a AttachmentClient, if_match_condition: Option<IfMatchCondition<'b>>, user_agent: Option<UserAgent<'b>>, activit...
use tantivy::tokenizer::RawTokenizer; #[derive(Clone)] pub struct RawTokenizerFactory {} impl RawTokenizerFactory { pub fn new() -> Self { RawTokenizerFactory {} } pub fn create(self) -> RawTokenizer { RawTokenizer {} } } #[cfg(test)] mod tests { use tantivy::tokenizer::Tokenizer...
//! Rust binding for the Cuba integrator. //! //! Cuba (http://www.feynarts.de/cuba/) is written by Thomas Hahn. //! //! # Usage //! Create a `CubaIntegrator` and supply it with a function of the form //! //! ``` //! type UserData = (); //! //! fn integrand( //! x: &[f64], //! f: &mut [f64], //! user_data: ...
use hymns::runner::timed_run; const INPUT: &str = include_str!("../input.txt"); fn part1() -> u64 { let mut score = 0; for line in INPUT.lines() { let mut stack = vec![]; for c in line.chars() { match c { '(' | '[' | '{' | '<' => stack.push(c), clo...
pub mod test; pub mod jsonserver;
use std::{str, thread}; use std::net::{TcpListener, TcpStream, SocketAddrV4, Ipv4Addr}; use std::io::{Read, Write, BufReader}; pub use request::{Request}; pub use response::{Response}; mod request; mod response; macro_rules! formatted_out { ($head:expr, $body:expr) => { { println!("----- {} -...
#[doc = "Reader of register DLYB_CFGR"] pub type R = crate::R<u32, super::DLYB_CFGR>; #[doc = "Writer for register DLYB_CFGR"] pub type W = crate::W<u32, super::DLYB_CFGR>; #[doc = "Register DLYB_CFGR `reset()`'s with value 0"] impl crate::ResetValue for super::DLYB_CFGR { type Type = u32; #[inline(always)] ...
// Copyright 2020 ChainSafe Systems // SPDX-License-Identifier: Apache-2.0, MIT use address::Address; use clock::ChainEpoch; use encoding::Cbor; use num_bigint::{ bigint_ser::{BigIntDe, BigIntSer}, biguint_ser::{BigUintDe, BigUintSer}, BigInt, }; use serde::{Deserialize, Deserializer, Serialize, Serializer...
extern crate utils; use std::env; use std::io::{self, BufReader}; use std::io::prelude::*; use std::fs::File; use utils::*; type Input = Vec<i32>; fn solve(input: &Input) -> (i32, i32) { let mut p1 = 0; let mut p2 = 0; for i in 0..input.len() { for j in 0..input.len() { if i == j { ...
use crate::types::linalg::dimension::Dimension; use crate::types::linalg::matrix::Matrix; use crate::types::shader::shader::Shader; use crate::types::shader::uniform::Uniform; use gl::types::*; use std::ffi::CString; pub struct ShaderProgram { pub id: GLuint, } impl ShaderProgram { pub fn link(shaders: &[&Shad...
use std::comm::{channel, Receiver}; use token::*; use ast::*; use std::from_str::from_str; use scanner; use std::collections::hashmap::HashMap; ///Scan and Parse a file in parallel producing an AST pub fn parse_file_async(path : &str) -> Vec<Box<Stmt>> { let tokens = scanner::stream_from_file(path); AsyncParse...
use quote::Tokens; use syn::{Ident, Path}; use glib_utils::*; use hir::{FnArg, Signal, Slot, Ty}; use super::class::ClassContext; use super::cstringident::CStringIdent; impl<'ast> ClassContext<'ast> { pub fn signal_trampolines(&self) -> Vec<Tokens> { self.signals() .map(|signal| { ...
use crate::{ rendering::*, }; pub trait Canvas<'f> { fn drawing_data(&mut self) -> &mut DrawingData; fn rect(&mut self) -> Rect { let masks = self.masks(); Rect::new(self.drawing_data(), masks) } fn line(&mut self) -> Line { let masks = self.masks(); Line::new(se...
use std::env; use std::time::Instant; #[macro_use] extern crate microprofile; trait Test { fn fibonacci(&self, n: u32) -> u32; fn run(&self, n: u32); } struct Optick {} impl Test for Optick { #[optick_attr::profile] fn fibonacci(&self, n: u32) -> u32 { match n { 0 => 1, ...
#[macro_use] extern crate neon; extern crate base64; extern crate holochain_agent; extern crate holochain_core; extern crate holochain_core_api; extern crate holochain_dna; extern crate holochain_cas_implementations; extern crate serde_json; extern crate tempfile; pub mod app;
use crate::*; use std::rc::Rc; use std::cell::RefCell; use shoji::*; // HBox // HBox lays out its children in a single horizontal row from left to right. // HBox will resize children to their desired widths but constrain the height to the parent container height. pub struct HBox { children: Vec<Box<dyn Element>>, l...
#[doc = "Reader of register RCC_APB3DIVR"] pub type R = crate::R<u32, super::RCC_APB3DIVR>; #[doc = "Writer for register RCC_APB3DIVR"] pub type W = crate::W<u32, super::RCC_APB3DIVR>; #[doc = "Register RCC_APB3DIVR `reset()`'s with value 0x8000_0000"] impl crate::ResetValue for super::RCC_APB3DIVR { type Type = u3...
use std::time::SystemTime; use crate::{Money, Debt}; pub fn get_users() -> Vec<String> { vec!["alice".into(),"bob".into(), "ben".into(), "mitchell".into()] } pub fn get_all_debts() -> Vec<Debt> { vec![] } pub fn get_debts_involving(user: &str) -> Vec<Debt> { vec![ Debt{ debtor: "asdf".into(), cr...
extern crate whitespace_text_steganography; use std::fs; pub fn hide(payload_path: &str, carrier_path: &str, output_path: &str) { let result = whitespace_text_steganography::hide(payload_path, carrier_path); fs::write(output_path, result).expect("Unable to write package file"); } pub fn reveal(car...
//! Structs and methods for working with `Hittable` spheres. use crate::aabb::AABB; use crate::hittable::{get_sphere_uv, HitRecord, Hittable}; use crate::material::Material; use crate::onb::ONB; use crate::pdf::random_to_sphere; use crate::ray::Ray; use crate::vec3; use crate::vec3::Vec3; use rand::prelude::*; use std...
mod eddington; mod polar_eddington; pub trait Properties { fn mass() -> f64; fn ang_momentum() -> f64; } pub use self::eddington::EddingtonFinkelstein; pub use self::polar_eddington::{NearPole0EF, NearPolePiEF};
use crate::{Result, SUDOERS_ALL_ALL_NOPASSWD, USERNAME}; use sudo_test::{Command, Env, TextFile}; #[test] fn cwd_not_set_cannot_change_dir() -> Result<()> { let env = Env(TextFile(SUDOERS_ALL_ALL_NOPASSWD)).build()?; let output = Command::new("sudo") .args(["--chdir", "/root", "pwd"]) .output(...
use chrono::{DateTime, Utc}; use serde::{Deserialize, Deserializer}; #[derive(Debug, Clone)] pub struct GitHubError { pub details: String, } #[derive(Debug, Clone)] pub struct PearsError { pub details: String, } #[derive(Deserialize, Debug, Clone)] pub struct ConfigRepo { pub owner: String, pub name:...
use std::collections::btree_set; use std::borrow::Borrow; /// A one-to-many index datastructure built around the standard library b-tree. #[derive(Clone, Hash, PartialEq, Eq, Ord, PartialOrd)] pub struct BTreeIndex<K, V> { set: btree_set::BTreeSet<(K, V)>, } /// An iterator over the entries of a [`BTreeIndex`]. ...
use yew::prelude::*; use yewtil::future::LinkFuture; mod state; pub use state::SelectState; mod selection; pub use selection::Selection; mod wrappers; pub use wrappers::{SelectDisplay, SelectFilter}; /// Bulma-based selection box /// TODO: document pub struct Select<T: 'static> { link: ComponentLink<Self>, pr...
#[doc = "Reader of register PENDING0"] pub type R = crate::R<u32, super::PENDING0>; #[doc = "Reader of field `SOURCE`"] pub type SOURCE_R = crate::R<u32, u32>; impl R { #[doc = "Bits 0:31 - This field specifies the following sources: Bit 0: CM0 MPU. Bit 1: CRYPTO MPU. Bit 2: DW 0 MPU. Bit 3: DW 1 MPU. ... Bit 14: C...
// #![deny(warnings)] #[macro_use] extern crate lazy_static; #[macro_use] extern crate prometheus; extern crate pretty_env_logger; #[macro_use] extern crate log; use broadcast::{Receiver, Sender}; use futures::{Stream, StreamExt}; use jsonwebtoken::{dangerous_insecure_decode_with_validation, Algorithm, Validation}; us...
use super::schema::migration_statistics; #[derive(Insertable)] #[table_name = "migration_statistics"] pub struct MigrationStatistics<'a> { pub id: Option<i64>, pub unused_count: i64, pub migrated_from_id: i64, pub migrated_to_id: i64, pub migration_step: &'a str, }
#[doc = "Reader of register RTC_CFGR"] pub type R = crate::R<u32, super::RTC_CFGR>; #[doc = "Writer for register RTC_CFGR"] pub type W = crate::W<u32, super::RTC_CFGR>; #[doc = "Register RTC_CFGR `reset()`'s with value 0"] impl crate::ResetValue for super::RTC_CFGR { type Type = u32; #[inline(always)] fn re...
//! Board file for STM32F407G-DISC1 development board //! //! - <https://www.st.com/en/evaluation-tools/stm32f4discovery.html> #![no_std] // Disable this attribute when documenting, as a workaround for // https://github.com/rust-lang/rust/issues/62184. #![cfg_attr(not(doc), no_main)] #![feature(const_in_array_repeat_e...
mod block; mod r#break; mod class; mod r#continue; mod debugger; mod empty; mod expr; mod r#for; mod func; mod if_stmt; mod labelled; mod r#return; mod switch; mod throw; mod r#try; mod var_decl; mod r#while; mod with;
mod handler; mod healthz; mod metrics; mod statusz; pub use {handler::handler as handler}; pub use {healthz::handler as healthz}; pub use {metrics::handler as metrics}; pub use {statusz::handler as statusz};
use bls12_381::Scalar; mod vm; mod vm_load; use vm_load::load_zkvm; fn main() { let mut vm = load_zkvm(); vm.setup(); let params = vec![ ( 0, Scalar::from_raw([ 0xb981_9dc8_2d90_607e, 0xa361_ee3f_d48f_df77, 0x52a3_5a8c_1908_...
use std::collections::HashMap; use std::convert::TryFrom; use std::hash::Hash; use std::ops::{Deref, DerefMut}; use crate::{Element, Value}; use crate::into::value::ValueType; /// Maps to `HashMap<Value, Element>` where value is homogeneous #[derive(Debug)] pub struct Map<K: ValueType + Hash + Eq>(pub HashMap<K, Elem...
/*! ```rudra-poc [target] crate = "aovec" version = "1.1.0" [report] issue_date = 2020-12-10 rustsec_url = "https://github.com/RustSec/advisory-db/pull/528" rustsec_id = "RUSTSEC-2020-0099" [[bugs]] analyzer = "SendSyncVariance" bug_class = "SendSyncVariance" bug_count = 2 rudra_report_locations = ["src/lib.rs:17:1: ...
use futures::channel::mpsc::{unbounded, UnboundedReceiver, UnboundedSender}; use futures::join; use futures::stream::StreamExt; use tokio::spawn; #[tokio::main] async fn main() -> Result<(), Box<dyn std::error::Error>> { println!("Send 10 queries"); send_receive(10).await?; Ok(()) } async fn send_receive(...
#![doc = "generated by AutoRust 0.1.0"] #![allow(unused_mut)] #![allow(unused_variables)] #![allow(unused_imports)] use super::{models, API_VERSION}; #[non_exhaustive] #[derive(Debug, thiserror :: Error)] #[allow(non_camel_case_types)] pub enum Error { #[error(transparent)] Dimensions_ListByBillingAccount(#[fro...
/* * -- lib.rs * msel * by viz (https://github.com/vizs) * * licensed under BSD 2-Clause "Simplified" License */ pub mod ui; pub struct Items { pub all_items: Vec<String>, pub sel_items: Vec<String> } impl Items { pub fn new(all_item: &Vec<String>) -> Items { Items { all_item...
extern crate nix; use nix::sys::signal::{kill, SIGTERM}; use nix::unistd::{fork, getpid, ForkResult}; use std::error::Error; use std::io::{BufRead, BufReader, Write}; use std::net::{Shutdown, TcpListener, TcpStream}; use std::process::Command; use std::thread::spawn; /// Los modos en los que puede correr el servidor ...
// Copyright 2016 coroutine-rs 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 accordi...
extern crate structopt; use std::fs::File; use std::io::Read; use structopt::StructOpt; mod errors; mod dos; mod coff; mod formats; mod utils; #[derive(Debug, StructOpt)] pub struct Cli { path: std::path::PathBuf, #[structopt(short="f", long="format")] format: Option<String>, #[structopt(short...
// hide console window on Windows #![windows_subsystem="windows"] #[macro_use] extern crate sciter; #[cfg(windows)] use winreg; struct EventHandler; #[cfg(windows)] impl EventHandler { #[allow(non_snake_case)] fn createWindowsShortcut(&self, add: bool) -> sciter::Value { // https://users.rust-lang.org...
#[doc = "Reader of register HOST_EP1_RW2_DR"] pub type R = crate::R<u32, super::HOST_EP1_RW2_DR>; #[doc = "Writer for register HOST_EP1_RW2_DR"] pub type W = crate::W<u32, super::HOST_EP1_RW2_DR>; #[doc = "Register HOST_EP1_RW2_DR `reset()`'s with value 0"] impl crate::ResetValue for super::HOST_EP1_RW2_DR { type T...
use byteorder::{ByteOrder, LittleEndian}; use ckb_vm::{ decoder::build_imac_decoder, machine::asm::AsmMachine, CoreMachine, Memory, SupportMachine, RISCV_GENERAL_REGISTER_NUMBER, }; use gdb_remote_protocol::{ Breakpoint, Error, Handler, MemoryRegion, ProcessType, StopReason, ThreadId, VCont, VContFeatur...
use crate::{marshall_vec, Uuid}; #[test] fn encode_bool_false() { assert_eq!(marshall_vec(false).unwrap(), vec![1, 1, 0]); } #[test] fn encode_bool_true() { assert_eq!(marshall_vec(true).unwrap(), vec![1, 1, 1]); } #[test] fn encode_char_ascii() { assert_eq!(marshall_vec('A').unwrap(), vec![1, 3, 65]); }...
// Copyright 2018 Steven Bosnick // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE-2.0 or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except accord...
/// An internal macro used for defining a function to get the user's preferred immutable store (which requires multiple branches). #[doc(hidden)] #[macro_export] macro_rules! define_get_immutable_store { () => { pub fn get_immutable_store() -> $crate::stores::ImmutableStore { // This will be exe...
use gfx; use io::ndma; fn make_data() -> [u32; 0x200] { let mut data = [0u32; 0x200]; for (n, word) in data.iter_mut().enumerate() { *word = (n as u32) * 0x100; } data } #[inline(never)] fn test_memory_fill() { let mut dst_data = make_data(); print!("Starting NDMA memory fill... "); ...
use crate::has_attr_key; use proc_macro as pm; use proc_macro2 as pm2; // use quote::quote; use quote::quote; use std::collections::HashMap; use syn::visit_mut::VisitMut; pub(crate) fn rewrite(_attr: syn::AttributeArgs, mut item: syn::ItemFn) -> pm::TokenStream { item.sig.generics.params.iter_mut().for_each(|p| { ...
#[doc = "Register `APB4FZ1` reader"] pub type R = crate::R<APB4FZ1_SPEC>; #[doc = "Register `APB4FZ1` writer"] pub type W = crate::W<APB4FZ1_SPEC>; #[doc = "Field `DBG_I2C4` reader - I2C4 SMBUS timeout stop in debug"] pub type DBG_I2C4_R = crate::BitReader; #[doc = "Field `DBG_I2C4` writer - I2C4 SMBUS timeout stop in ...
//! Components for integrating GraphQL endpoints into Tsukuyomi. #![doc(html_root_url = "https://docs.rs/tsukuyomi-juniper/0.4.0-dev")] #![deny( missing_docs, missing_debug_implementations, nonstandard_style, rust_2018_idioms, rust_2018_compatibility, unused )] #![forbid(clippy::unimplemented)]...
use crate::convert::{AsGlsl, Glsl, GlslLine}; use std::convert::{TryFrom, TryInto}; use syn::spanned::Spanned; use syn::{Error, Local, Pat, Result}; use crate::yasl_expr::YaslExprLineScope; use crate::yasl_ident::YaslIdent; use crate::yasl_type::YaslType; #[derive(Debug)] pub struct YaslLocal { ident: YaslIdent,...
use crate::day9::{intcode_computer, parse_program}; #[aoc_generator(day21)] fn day21_gen(input: &str) -> Vec<i64> { parse_program(input) } #[aoc(day21, part1)] fn solve_p1(tape: &[i64]) -> i64 { // if A is a hole, jump // if A and B are holes, jump, // if A B and C are holes, jump // if D is a hol...
#[doc = "Register `CCMR1` reader"] pub type R = crate::R<CCMR1_SPEC>; #[doc = "Register `CCMR1` writer"] pub type W = crate::W<CCMR1_SPEC>; #[doc = "Field `CC1SEL` reader - Capture/compare 1 selection This bitfield defines the direction of the channel input (capture) or output mode."] pub type CC1SEL_R = crate::BitRead...
use simple_error::bail; use closure::closure; use evmap; use evmap::{ReadHandle, WriteHandle}; use std::error; use std::io; use std::io::BufRead; use std::sync::mpsc; use std::thread; use crate::day; pub type BoxResult<T> = Result<T, Box<dyn error::Error>>; struct Intcode { p: Vec<i64>, base: i64, } impl Int...
/// Unwraps a successful result or returns the error, with the path included in /// the error description. macro_rules! try_with_path { ($x:expr, $y:expr) => {{ match $x { Ok(r) => r, Err(e) => { return Err(io::Error::new( e.kind(), ...
use std::fs::File; use std::io::{BufRead, BufReader, Error}; fn calculate_trees_on_the_way(xpath: usize, ypath: usize, map: &Vec<Vec<char>>) -> usize { let mut trees = 0; let mut xpos = 0; for y in (0..map.len()).step_by(ypath) { println!("{:?}", map[y]); println!("{}", map[y][xpos]); ...
use crypto::buffer::{self, BufferResult, ReadBuffer, WriteBuffer}; use rand::Rng; fn main() { let (guessed, actual) = detect_mode(&generate_random_key()); if guessed { println!("We guess ECB"); } else { println!("We guess CBC"); } if guessed == actual { println!("We were c...
pub mod v2; mod ini; mod md5; mod client; pub use self::v2::Manifest; pub use self::md5::MD5; pub use self::ini::{IniManifest, IniData};
use crate::{node::NodeId, OperatorId}; /// Trait that must be implemented by any operator. pub trait Operator { /// Implement this method if you want to take control of the execution loop of an /// operator (e.g., pull messages from streams). /// Note: No callbacks are invoked before the completion of this...
/// Provides copysign intrinsics that don't rely on nightly use core::intrinsics::transmute; #[cfg(target_endian = "little")] pub fn copysignf32(x: f32, y: f32) -> f32 { unsafe { let sign = transmute::<f32, u32>(x) & (1 << 31); let yi = (transmute::<f32, u32>(y) & ((1 << 31) - 1)) | sign; ...
use std::error::Error; use std::result::Result; use tensorflow::ops; use tensorflow::train::AdadeltaOptimizer; use tensorflow::train::MinimizeOptions; use tensorflow::train::Optimizer; use tensorflow::Code; use tensorflow::DataType; use tensorflow::Output; use tensorflow::Scope; use tensorflow::Session; use tensorflow:...
fn main(){ let max = 0; let primes = make_primes(1000).iter().rev(); for p in primes { if max > p { break; } else { max_primes = max_quadratic_primes(*p, &primes); if max < max_primes { max = max_primes; } } } p...
use crate::render::svg::*; use svg::Node; const DEFAULT_LABEL_VISIBLE: bool = true; const DEFAULT_LABEL_POSITION: PointLabelPosition = PointLabelPosition::Top; const DEFAULT_STROKE_WIDTH: &str = "2px"; const DEFAULT_X_LABEL_HORIZONTAL: i32 = 8; const DEFAULT_X_LABEL_VERTICAL: i32 = 0; const DEFAULT_X_LABEL_BETWEEN: ...
pub mod ntru_prime; pub use ntru_prime::*;
//! <div align="center"> //! <img alt="Rune Logo" src="https://raw.githubusercontent.com/rune-rs/rune/master/assets/icon.png" /> //! </div> //! //! <br> //! //! <div align="center"> //! <a href="https://rune-rs.github.io"> //! <b>Visit the site 🌐</b> //! </a> //! - //! <a href="https://rune-rs.github.io/book/"...
use wfc::{rels::get_2d_rels, util::generate_2d_positions, WaveFunctionCollapse}; fn main() { let (width, height) = (50, 10); let locs = generate_2d_positions(width, height); let example = vec![ vec![0, 0, 0, 0], vec![0, 0, 0, 0], vec![0, 0, 0, 0], vec![0, 0, 0, 0], vec![0, 0, 0, 0], vec![...
#![allow(non_snake_case)] use std::collections::HashMap; use std::path::Path; use cgmath::{vec2, vec3}; use tobj; use super::common::*; use crate::mesh::{Mesh, Texture, Vertex}; pub struct Model { pub meshes: Vec<Mesh>, pub texturesLoaded: HashMap<String, Texture>, directory: String, } impl Model { pub fn n...
use futures::prelude::*; use state_machine_future::RentToOwn; use std::cmp; use std::io; use std::marker::PhantomData; use std::time::Duration; use super::{encode, Connection, MAX_FRAGMENT_LEN, Packet, PacketData, recv_packet}; use tokio_core::reactor::Timeout; pub struct SendReliable<T> where T: AsRef<[u8]> { pub...
use core::f64::consts::FRAC_PI_2; use crate::circle::Circle; use crate::coord_plane::LatLonPoint; use crate::coord_plane::CartPoint; pub struct Indicatrix { pub center: LatLonPoint, pub points: Vec<LatLonPoint>, } struct CartPointsWithCenter { pub center: CartPoint, pub points: Vec<CartPoint>, } impl...
use super::leaf::{Scanner, ARRAY_SIZE}; use super::Leaf; use super::{InsertError, RemoveError, SearchError}; use crate::ebr::{Arc, AtomicArc, Barrier, Ptr, Tag}; use crate::LinkedList; use std::borrow::Borrow; use std::cmp::Ordering; use std::fmt::Display; use std::sync::atomic::Ordering::{AcqRel, Acquire, Relaxed, R...
use register::{mmio::*, register_bitfields, register_structs}; register_bitfields! { u32, /// Serial Clock Divisor Register SCKDIV [ /// Divisor for serial clock. div_width bits wide DIV OFFSET(0) NUMBITS(12) [] ], /// Serial Clock Mode Register SCKMODE [ /// Serial cl...
use std::path::Path; use crate::{ create::buffered_index_to_direct_index, error::VelociError, indices::{metadata::*, *}, persistence::{Persistence, *}, plan_creator::execution_plan::PlanRequestSearchPart, search, search_field, util::StringAdd, }; use buffered_index_writer::{self, BufferedIn...
use std::collections::HashSet; use std::fs::File; use std::io::BufReader; use std::path::{Path, PathBuf}; use anyhow::{Context, Result}; use glob::glob; use lazy_static::lazy_static; use serde::Deserialize; use structopt::clap::arg_enum; lazy_static! { static ref HOME_DIR: String = dirs::home_dir() .expec...
use crate::sync::Semaphore; use crate::syscall::{SemBuf, SysResult, TimeSpec}; use alloc::{collections::BTreeMap, sync::Arc, sync::Weak, vec::Vec}; use core::ops::Index; use spin::{Mutex, RwLock}; // structure specifies the access permissions on the semaphore set // key_t? #[derive(Clone, Copy)] pub struct IpcPerm { ...
pub mod rectangle { #[derive(Copy, Clone)] pub struct Rectangle { pub x: usize, pub y: usize, pub width: usize, pub height: usize, pub end_x: usize, pub end_y: usize, } impl Rectangle { pub fn new(x: usize, y: usize, width: usize, height: usize) -> Rectangle { Rectangle { x, y, width, ...
#[cfg(test)] mod tests { use super::*; #[test] fn sample_tests() { assert_eq!(parse("iiisdoso"), vec![8, 64]); assert_eq!(parse("iiisdosodddddiso"), vec![8, 64, 3600]); } } fn parse(code: &str) -> Vec<i32> { let mut result = Vec::new(); let mut temp:i32 = ...
use super::super::ascii85; use anyhow::{anyhow, ensure, Result}; use openssl::aes::{unwrap_key, AesKey}; use openssl::symm::{decrypt, Cipher}; use std::convert::TryInto; pub fn run(bytes: &[u8]) -> Result<Vec<u8>> { let bytes = ascii85::decode(bytes)?; ensure!(bytes.len() > 96 && bytes.len() % 8 == 0, "Invali...
#[derive(Debug, PartialEq)] pub struct DNA { nucleotides: String, } #[derive(Debug, PartialEq)] pub struct RNA { nucleotides: String, } impl DNA { pub fn new(dna: &str) -> Result<DNA, usize> { match collect_valid_nucleotides(dna, "ACGT") { Ok(nucleotides) => Ok(DNA { nucleotides }), ...
use proc_macro2::{Span, TokenStream}; use quote::{format_ident, quote_spanned}; use syn::Ident; use crate::codegen::component::{CodeGenChild, CodeGenComponent, CodeGenComponentNames}; use crate::codegen::unique::{CodeGenUnique, CodeGenUniqueNames}; use crate::validation::{ query::{Atom, Query}, AllComponents, ...