text
stringlengths
8
4.13M
//! numerical trait constraints use ndarray_linalg::lapack::Lapack; pub trait Float: Sized + num_traits::Float + Lapack {} impl Float for f32 {} impl Float for f64 {}
use actix_web::{web, App, HttpServer}; use dotenv::dotenv; use drogue_cloud_api_key_service::{ endpoints::WebData as KeycloakWebData, service::KeycloakApiKeyService, }; use drogue_cloud_service_common::{ config::ConfigFromEnv, health::HealthServer, openid::Authenticator, openid_auth, }; use drogue_cloud_user_au...
//! Rust interface for Objective-C's `@throw` and `@try`/`@catch` statements. extern crate libc; use std::mem; use std::ptr; use libc::{c_int, c_void}; #[link(name = "objc", kind = "dylib")] extern { } extern { fn RustObjCExceptionThrow(exception: *mut c_void); fn RustObjCExceptionTryCatch(try: extern fn(*m...
use super::{ AnnotatedFunctionMap, BasicBlock, Compiler, Function, LLVMInstruction, Object, Scope, Type, }; pub struct Context<'a, 'b: 'a> { pub function_map: &'a AnnotatedFunctionMap, pub compiler: &'a mut Compiler<'b>, pub function: &'a mut Function, pub scope: &'a mut Scope<'b>, /// this sho...
use std::{str::from_utf8}; #[derive(Debug, Clone, Copy)] pub enum Token { OpenParen, CloseParen, OpenCurly, CloseCurly, OpenBracket, CloseBracket, SemiColon, Colon, Comma, NewLine, // This is mixing ideas here // I am making this rust specific // But I'm not too worr...
use std::io; use std::net::SocketAddr; use std::sync::atomic::Ordering; #[cfg(feature = "io_timeout")] use std::time::Duration; use super::super::{co_io_result, IoData}; #[cfg(feature = "io_cancel")] use crate::coroutine_impl::co_cancel_data; use crate::coroutine_impl::{is_coroutine, CoroutineImpl, EventSource}; use c...
#![doc = "generated by AutoRust 0.1.0"] #![allow(non_camel_case_types)] #![allow(unused_imports)] use serde::{Deserialize, Serialize}; pub type ArrayOfStrings = Vec<String>; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct PageableListOfStrings { #[serde(default, skip_serializing_if = "Vec::is_...
pub mod config; pub mod stream;
pub const POSTGRESQL_URL: &'static str = "postgresql://admin@localhost:5432/youtube"; pub const QUERY: &'static str = "SELECT id, serial FROM youtube.stats.channels";
//! TensorFlow Ops use std::collections::HashMap; use std::collections::VecDeque; use std::fmt::Debug; use std::mem; use std::ops::{Index, IndexMut}; #[cfg(feature = "serialize")] use std::result::Result as StdResult; use std::sync::Arc; use analyser::interface::{Solver, TensorsProxy}; use analyser::prelude::*; use op...
fn main() { let sdk_dep = solana_sdk::signature::Signature::default(); println!("Yes have some sdk_dep {:?}", sdk_dep); let memo_dep = safe_memo::id(); println!("Yes have some memo_dep {:?}", memo_dep); let token_dep = safe_token::id(); println!("Yes have some token_dep {:?}", token_dep); le...
use rspg::display::DisplayWith; use rspg::grammar; use rspg::lr1::generator::Generator; use rspg::lr1::parser::Parser; use rspg::set::FirstSets; use rspg::set::FollowSets; use rspg::token; use std::marker::PhantomData; #[derive(Debug, Ord, PartialOrd, Eq, PartialEq, Copy, Clone)] enum Terminal { Sign(char), Nu...
use log::*; use super::*; use crate::system::{ BusHandle, SystemModules }; use tokio::sync::mpsc::Sender; use crate::bus::ModuleMsgEnum; use crate::agent::AgentMessage; pub struct LoopbackCLA { config: AdapterConfiguration, bus_handle: BusHandle, } impl LoopbackCLA { pub fn new(config: super::AdapterConf...
use crate::common::myerror::MyError; use crate::inven::warehouse::{InvenRes, Inventory, Price}; use rayon::prelude::*; use serde::{Deserialize, Serialize}; use serde_json::{Result, Value}; use std::collections::HashMap; use std::collections::HashSet; fn get_raw(_raw: &str) -> std::result::Result<Vec<Inventory>, MyErro...
// Copyright 2021 Red Hat, Inc. // // 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 i...
mod day01; mod day02; mod day03; mod day04; mod day05; mod day06; fn main() { const INPUT_1: &str = include_str!("../inputs/input1.txt"); println!("Day 1 - part 1: {}", day01::part1(INPUT_1).unwrap()); println!("Day 1 - part 2: {}", day01::part2(INPUT_1).unwrap()); const INPUT_2: &str = include_str!("...
#[doc = "Reader of register DDRCTRL_PCTRL_1"] pub type R = crate::R<u32, super::DDRCTRL_PCTRL_1>; #[doc = "Writer for register DDRCTRL_PCTRL_1"] pub type W = crate::W<u32, super::DDRCTRL_PCTRL_1>; #[doc = "Register DDRCTRL_PCTRL_1 `reset()`'s with value 0"] impl crate::ResetValue for super::DDRCTRL_PCTRL_1 { type T...
use crate::specs::dao::dao_verifier::DAOVerifier; use crate::{Net, Spec}; use ckb_chain_spec::ChainSpec; pub struct DAOVerify; impl Spec for DAOVerify { crate::name!("dao_verify"); fn modify_chain_spec(&self) -> Box<dyn Fn(&mut ChainSpec) -> ()> { Box::new(|spec_config| { spec_config.para...
use multiversion::multiversion; #[multiversion( targets("x86_64+avx", "x86+avx", "x86+sse", "aarch64+neon"), dispatcher = "default" )] fn default_dispatch() {} #[multiversion( targets("x86_64+avx", "x86+avx", "x86+sse", "aarch64+neon"), dispatcher = "static" )] fn static_dispatch() {} #[cfg(feature =...
use jsl::{Config, Schema, SerdeSchema, Validator}; use serde::Deserialize; use serde_json::Value; use std::fs; #[derive(Deserialize)] struct TestSuite { name: String, schema: SerdeSchema, #[serde(rename = "strictInstance")] strict_instance: bool, instances: Vec<TestCase>, } #[derive(Deserialize)] ...
use std::fmt::{Display, Formatter}; use std::str::FromStr; use http::header::{HeaderName, HeaderValue as HeaderValueInner, InvalidHeaderValue}; use http::Method; use serde::de::Error; use serde::ser::SerializeSeq; use serde::{Deserialize, Deserializer, Serialize, Serializer}; use crate::config::default_server_origin;...
use crate::error::{Error, Result}; use crate::field::{DbField, DbFieldType, Field}; use crate::input::DbValue; /// A dedicated type for id field of INT AUTOINCREMENT PRIMARY KEY NOT NULL pub struct IdField { pub db_field: DbField, } impl IdField { pub fn id() -> Box<Self> { Box::new(IdField { ...
// q0069_sqrtx struct Solution; impl Solution { pub fn my_sqrt(x: i32) -> i32 { if x <= 1 { return x; } let mut l = 1; let mut r = 46340; // sqrt(i32::max_value()) if x >= r * r { return r; } while l != r - 1 { let i = (l ...
use std::collections::HashSet; const WINDOW_SIZE: usize = 25; fn find_sum_in_window(haystack: &[u64], sum: u64) -> Option<(u64, u64)> { let set: HashSet<_> = haystack.iter().filter(|elem| **elem <= sum).collect(); for left in set.iter() { let right = sum - *left; if set.contains(&right) { ...
use std::io::{Result, Write}; use pulldown_cmark::{Tag, Event, Alignment}; use crate::gen::{State, States, Generator, Document}; #[derive(Debug)] pub struct Table; impl<'a> State<'a> for Table { fn new(tag: Tag<'a>, gen: &mut Generator<'a, impl Document<'a>, impl Write>) -> Result<Self> { let out = gen....
use map::Dungeon; use entity::Entity; // Game update functionality pub fn move_player(player: &mut Entity, dungeon: &Dungeon, dx: i32, dy: i32) -> bool { let proposed_x = player.location_x + dx; // TODO: collision ray in case dx > 1 let proposed_y = player.location_y + dy; // TODO: collision ray in case dy > 1...
use shared::*; use std::collections::HashMap; fn main() { let input: Vec<Direction> = include_str!("input.txt") .trim() .chars() .map(|c| match c { '<' => Direction::West, '>' => Direction::East, '^' => Direction::North, 'v' => Direction::Sout...
fn main() { for number in range(1i, 101) { let output = if div_fifeteen(number) { "FizzBuzz".to_str() } else if div_five(number) { "Fizz".to_str() } else if div_three(number) { "Buzz".to_str() } else { ...
use core::iter; use std::collections::VecDeque; use std::marker::PhantomData; use std::thread; use enum_iterator::IntoEnumIterator; use crate::BenchStr; pub fn run_benchmark<TBenchStr: BenchStr>( number_of_threads: usize, test_set: &'static [&'static str], ) { if number_of_threads == 1 { run_benc...
#![allow(unused)] use std::sync::atomic; use std::sync::{self, Mutex, Arc}; use std::sync::mpsc::{Sender, Receiver, self, channel}; use std::collections::HashMap; use clipboard_win::{get_clipboard_string, set_clipboard_string}; use gdk::Window; pub type BindHandler = Arc<dyn Fn(i32) + Send + Sync + 'static>; pub type...
use std::result; #[derive(Debug)] pub enum Error { JsonError(serde_json::Error), ExprIsNotArrayError, ExprOpIsNotStringError, ExprBuildError, NoSuchOpError, ContextNotDictError, ContextNoSuchVarError, ExprVarArgNotStringError, FinalResultNotBoolError, // MatchError, } pub type...
use crate::QueueStoredAccessPolicy; use azure_core::headers::CommonStorageResponseHeaders; use azure_core::PermissionError; use azure_storage::StoredAccessPolicyList; use bytes::Bytes; use http::response::Response; use std::convert::TryInto; #[derive(Debug, Clone)] pub struct GetQueueACLResponse { pub common_stora...
use failure::Error; use futures::future; use futures::prelude::*; use reqwest::header::{Authorization, Headers}; use reqwest::unstable::async::Client; use slog::Logger; use std::env; use std::time::Duration; use url::Url; use Config; use github::PullRequest; #[derive(Clone)] pub struct TodoistClient { http: Clien...
#[doc = "Reader of register CH3_CTR"] pub type R = crate::R<u32, super::CH3_CTR>; #[doc = "Writer for register CH3_CTR"] pub type W = crate::W<u32, super::CH3_CTR>; #[doc = "Register CH3_CTR `reset()`'s with value 0"] impl crate::ResetValue for super::CH3_CTR { type Type = u32; #[inline(always)] fn reset_va...
use url; use hyper; use uritemplate::UriTemplate; use super::dtos::enums; use errors::*; fn root() -> Result<url::Url> { Ok("https://www.bungie.net/Platform/".parse()?) } fn build_url(path: &str) -> Result<hyper::Uri> { let url = root()?.join(path)?; Ok(url.as_str().parse()?) } pub fn get_manifest() -> Result...
use std::io::{stdout, Write}; use azuki_opt::{ branching_simplify::BranchingSimplify, const_folding::ConstFolding, dead_code_eliminator::DeadCodeEliminator, }; use azuki_syntax::{lexer::lexer, parse}; use azuki_tac::optimizer::sanity_checker::SanityChecker; use azuki_tacvm::Vm; use clap::Clap; use opt::Action;...
use std::io::Read; use std::net::Ipv4Addr; use byteorder::{BigEndian, ReadBytesExt}; use bytes::BufMut; use snafu::ResultExt; use crate::error::*; pub trait IntoKbinBytes { fn write_kbin_bytes<B: BufMut>(self, buf: &mut B); } pub trait FromKbinBytes: Sized { fn from_kbin_bytes<R: Read>(input: &mut R) -> Res...
#[doc = "Register `RF%sR` reader"] pub type R = crate::R<RFR_SPEC>; #[doc = "Register `RF%sR` writer"] pub type W = crate::W<RFR_SPEC>; #[doc = "Field `FMP` reader - FMP0"] pub type FMP_R = crate::FieldReader; #[doc = "Field `FULL` reader - FULL0"] pub type FULL_R = crate::BitReader<FULL0R_A>; #[doc = "FULL0\n\nValue o...
use itertools::Itertools; #[aoc::main(10)] pub fn main(input: &str) -> (i32, String) { solve(input) } #[aoc::test(10)] pub fn test(input: &str) -> (String, String) { let res = solve(input); (res.0.to_string(), res.1) } fn solve(input: &str) -> (i32, String) { let p1 = part1(input); let p2 = part2...
pub mod kinds; use kinds::{Token, TokenKind}; #[allow(dead_code)] pub struct Lexer { // source code code: Vec<char>, // Lexer position position: usize, column: usize, line: usize, // supported space characters space_char: String, // supported integer literals digit_char: String...
use super::{Vars, VarsError}; use std::io::{self, Write}; mod expr; use expr::{translate_expr}; pub use expr::{ExprError, ExprInternalError}; pub enum TranslateError { Input(io::Error), Output(io::Error), Expr(ExprError), Vars(VarsError), } impl From<VarsError> for TranslateError { fn from(from:...
use state::*; /// Trait that tells QDF how to simulate states of space. pub trait Simulate<S> where S: State, { /// Performs simulation of state based on neighbor states. /// /// # Arguments /// * `state` - current state. /// * `neighbor_states` - current neighbor states. fn simulate(state:...
use amethyst::{ core::Transform, prelude::*, renderer::{Flipped, SpriteRender, SpriteSheetHandle}, }; use crate::components::player::Player; /// Player entitiy /// /// # args: /// /// * world: world to load into /// * x: inital x position /// * y: initial y position /// * sprite_sheet_handle: handle for t...
#[path="../src/configuration.rs"] mod configuration; #[path="../src/file.rs"] mod file; #[test] fn test_returns_configuration_with_empty_list_of_packages() { let yaml_file = " default: packages: "; let configuration = configuration::from_yaml(yaml_file.to_string()); assert_eq!(configuratio...
use piston_window::*; use rayon_logs::visualisation; use rayon_logs::RunLog; fn draw_segment(s: &((f64, f64), (f64, f64)), c: &Context, g: &mut G2d, scale: [[f64; 3]; 2]) { Line::new([0.0, 0.0, 0.0, 1.0], 0.1).draw( [(s.0).0, (s.0).1, (s.1).0, (s.1).1], &c.draw_state, scale, g, ...
#[doc = "Reader of register ADC_RES"] pub type R = crate::R<u32, super::ADC_RES>; #[doc = "Reader of field `VIN_CNT`"] pub type VIN_CNT_R = crate::R<u16, u16>; #[doc = "Reader of field `HSCMP_POL`"] pub type HSCMP_POL_R = crate::R<bool, bool>; #[doc = "Reader of field `ADC_OVERFLOW`"] pub type ADC_OVERFLOW_R = crate::R...
use std::{fs, env, error::Error}; pub struct Config { query: String, filename: String, case_insensitive: bool, } impl Config { pub fn new(mut args: env::Args) -> Result<Self, &'static str> { args.next(); let query = match args.next() { Some(q) => {q}, None => {...
#![ feature( optin_builtin_traits ) ] // // Tested: // // - ✔ Spawn mailbox for actor that is !Send and !Sync // - ✔ Spawn mailbox for actor that is Send and Sync but using the local methods // - ✔ Manually spawn mailbox for actor that is !Send and !Sync // - ✔ Manually spawn mailbox for actor that is Send and Sync but...
use std::{ io::{stderr, Write}, process::exit, }; use crate::laze_parser::parser::LazeParser; pub enum CompilerMode { Compile, Convert, } pub struct OptionCompilerInfo { pub mode: Option<CompilerMode>, pub parser: Option<LazeParser>, pub program_file_path: Option<String>, pub dist_file...
#![doc = "generated by AutoRust 0.1.0"] #![allow(non_camel_case_types)] #![allow(unused_imports)] use serde::{Deserialize, Serialize}; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct WebtestsResource { #[serde(default, skip_serializing_if = "Option::is_none")] pub id: Option<String>, #...
pub trait Unique<T> { fn unique<P>(&mut self, pred: P) -> Option<T> where P: FnMut(&T) -> bool; } impl<T, I> Unique<T> for I where I: Iterator<Item = T>, { fn unique<P>(&mut self, mut pred: P) -> Option<T> where P: FnMut(&T) -> bool, { let mut val = self.fi...
struct State { recipes: Vec<u8>, elves: [usize; 2], } impl State { fn new() -> Self { State { recipes: vec![3, 7], elves: [0, 1], } } fn run(&mut self) { let sum: u8 = self.elves.iter().map(|&i| self.recipes[i]).sum(); if sum >= 10 { ...
#![allow(dead_code)] use std::usize; use crate::cpu::CpuInterface; use crate::cpu::Interface; use crate::savable::Savable; const RESET_VECTOR: u16 = 0xFFFC; // Bus only used with the snake game pub struct SnakeBus { memory: [u8; 0xFFFF], } impl Interface for SnakeBus { fn read(&mut self, addr: u16) -> u8 {...
extern crate iron; extern crate logger; extern crate router; extern crate hyper; extern crate serde; #[macro_use] extern crate serde_derive; #[macro_use] extern crate serde_json; #[macro_use] extern crate log; extern crate env_logger; use std::str::FromStr; use std::io::Read; use iron::prelude::*; use router::Router; ...
use self::Direction::*; use std::slice::Iter; #[derive(Debug)] pub enum Direction { forward, left, backward, right, } impl Direction { pub fn iterator() -> Iter<'static, Direction> { static DIRECTIONS: [Direction; 4] = [forward, left, backward, right]; DIRECTIONS.iter() } } fn...
use crate::error::{Result, Error}; use crate::visitor::Visitor; use syn::{Expr, ExprUnary, ExprBinary, UnOp, BinOp}; use syn::spanned::Spanned; use super::tools::*; #[derive(Debug)] pub struct Expand { } // Get a series of additions/subtractions. fn match_sum(expr: &Expr, sum: &mut Vec<Expr>, is_negated: bool) -> Res...
use super::formatting::source_lines; use super::kb::*; use super::rules::*; use super::terms::*; use super::visitor::{walk_rule, walk_term, Visitor}; use std::collections::{hash_map::Entry, HashMap}; fn common_misspellings(t: &str) -> Option<String> { let misspelled_type = match t { "integer" => "Integer"...
use crate::bgp::{BgpEvent, BgpRoute}; use crate::event::{Event, EventQueue}; use crate::{AsId, DeviceError, NetworkDevice, Prefix, RouterId}; use std::collections::HashSet; #[derive(Debug, Clone)] pub struct ExternalRouter { name: &'static str, router_id: RouterId, as_id: AsId, pub neighbors: HashSet<R...
#[macro_use] extern crate csv; use std::io; use std::io::prelude::*; use std::path::Path; use std::vec::Vec; use std::fs::File; fn main() { // Split the string, removing the ".pdb" extension and creating a .dat file let output = "edgelist.dat"; // Read the file contents let filename = "/home/will/...
#![feature(core)] fn sumsqd(mut n: i32) -> i32 { let mut sq = 0; while n > 0 { let d = n % 10; sq += d*d; n /= 10 } sq } use std::num::Int; fn cycle<T: Int>(a: T, f: fn(T) -> T) -> T { let mut t = a; let mut h = f(a); while t != h { t = f(t); h = ...
mod register; mod command; mod respawn; pub use self::register::register; pub use self::command::CommandHandler;
use super::*; use crate::helpers::models::domain::get_customer_ids_from_routes; use crate::helpers::solver::{create_default_refinement_ctx, generate_matrix_routes_with_defaults}; use crate::helpers::utils::create_test_environment_with_random; use crate::helpers::utils::random::FakeRandom; use crate::models::common::IdD...
use html_extractor::HtmlExtractor; #[test] fn test() { let data = TestData::extract_from_str( r#" <div id="data1"> <div class="data1-1">1</div> </div> <div id="data2">2</div> <div id="data3" data-3="3"></div> <div id="data4"> ...
/* * B-tree set test (Rust) * * Copyright (c) 2020 Project Nayuki. (MIT License) * https://www.nayuki.io/page/btree-set * * 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 re...
use std::convert::TryInto; use meilidb_core::DocumentId; use meilidb_schema::SchemaAttr; use rocksdb::DBVector; use crate::database::raw_index::InnerRawIndex; use crate::document_attr_key::DocumentAttrKey; #[derive(Clone)] pub struct DocumentsIndex(pub(crate) InnerRawIndex); impl DocumentsIndex { pub fn documen...
use crate::AppendToUrlQuery; #[derive(Debug, Clone)] pub struct Delimiter<'a>(&'a str); impl<'a> Delimiter<'a> { pub fn new(delimiter: &'a str) -> Self { Self(delimiter) } } impl<'a> AppendToUrlQuery for Delimiter<'a> { fn append_to_url_query(&self, url: &mut url::Url) { url.query_pairs_m...
#![cfg(all(test, feature = "test_e2e"))] use azure_core::Context; use azure_cosmos::prelude::{CreateDocumentOptions, DeleteDatabaseOptions, GetDocumentOptions}; use serde::{Deserialize, Serialize}; mod setup; use azure_core::prelude::*; use azure_cosmos::prelude::*; use collection::*; #[derive(Serialize, Deserialize...
use std::sync::{Arc, RwLock}; use iced::{Button, Checkbox, Clipboard, Column, Command, Container, Length, PickList, Row, Slider, Text, button, pick_list, slider}; use crate::styling::Theme; pub struct Flags { pub settings: Arc<RwLock<crate::settings::Settings>> } #[derive(Debug, Clone)] pub enum Message { T...
pub mod decal; pub mod particle; pub mod render; pub mod world;
use super::InternedGrammar; use crate::generate::grammars::{InputGrammar, Variable, VariableType}; use crate::generate::rules::{Rule, Symbol}; use anyhow::{anyhow, Result}; pub(super) fn intern_symbols(grammar: &InputGrammar) -> Result<InternedGrammar> { let interner = Interner { grammar }; if variable_type_f...
static NUM: i32 = 120; fn coerce_static<'a>(_: &'a i32) -> &'a i32 { &NUM } fn execute(){ { println!("hello world {}", NUM); } { let sample = 12; let checking = coerce_static(&sample); println!("checking: {}", checking) } }
//! Create a cabinet file. extern crate clap; extern crate makecab; use clap::App; use std::borrow::Cow; use std::env; use std::ffi::OsString; use std::path::{Path,PathBuf}; use std::process; fn main() { let matches = App::new("makecab") .version(env!("CARGO_PKG_VERSION")) .author("Ted Mielczarek ...
#![feature(test)] extern crate test; use rand::prelude::*; const N: usize = 100; const LEN: usize = 1_000_000; fn create_random_vec() -> Vec<i32> { let mut rng = SmallRng::seed_from_u64(0); let mut v: Vec<_> = (0..LEN as i32).collect(); v.shuffle(&mut rng); v } mod slice { use crate::{create_ra...
use std::vec::Vec; // pub fn farey(n: usize) -> Vec<(usize, usize)> { let mut elems = Vec::new(); let mut a = 0; let mut b = 1; let mut c = 1; let mut d = n; while c <= n { let k = (n + b) / d; let p = k * c - a; let q = k * d - b; elems.push((c, d)); ...
#![no_std] #![no_main] #![feature(min_type_alias_impl_trait)] #![feature(impl_trait_in_bindings)] #![feature(type_alias_impl_trait)] #![allow(incomplete_features)] #[path = "../example_common.rs"] mod example_common; use defmt::{assert_eq, panic}; use embassy::executor::Spawner; use embassy::traits::flash::Flash; use...
use rand::{thread_rng, Rng}; use std::collections::HashMap; #[derive(Copy, Clone, PartialEq)] pub enum BlockNumber { One, Two, Three, Five, Eight, Thirteen, TwentyOne, ThrityFour, FiftyFive, EightyNine, } impl BlockNumber { pub fn to_u32(self) -> u32 { match self { ...
pub mod accounts; pub mod categories; pub mod cron; pub mod dashboard; pub mod products; pub mod terminal; pub mod transactions; use actix_web::web; /// Setup routes for admin ui pub fn init(config: &mut web::ServiceConfig) { config.service( web::scope("/admin") .service(web::resource("").rout...
use std::{fmt::Display, str::FromStr}; use crate::{parser, KdlError, KdlNode, KdlValue}; /// Represents a KDL /// [`Document`](https://github.com/kdl-org/kdl/blob/main/SPEC.md#document). /// /// This type is also used to manage a [`KdlNode`]'s [`Children /// Block`](https://github.com/kdl-org/kdl/blob/main/SPEC.md#ch...
use std::path::Path; use std::{borrow::Borrow, fs}; use std::{env, path::PathBuf}; use std::{ io::{stdin, stdout, Stdout, Write}, ops::Index, }; use termion::*; use termion::{ cursor::DetectCursorPos, raw::{IntoRawMode, RawTerminal}, }; //use std::io::{self, BufRead, BufReader}; use dirs; use termion:...
//! Contains structures for the generation of random phrases/filenames. use iron::prelude::*; use persistent; use rand; use rand::Rng; use iron::typemap::Key; use std::iter::FromIterator; /// Capitalises the first letter of an input string. fn as_capital_case(input: &str) -> String { let mut result = String::n...
//! Abstract interpretation of the render commands to discover what symbolic //! matrix is applied to each vertex. use super::symbolic_matrix::{SMatrix, AMatrix}; use nitro::Model; use nitro::render_cmds::SkinTerm; type MatrixIdx = u16; /// Records what symbolic matrix applies to each vertex. pub struct VertexRecord...
use std::fs; use std::io::{self, Write}; const OP_EXIT: i32 = 99; const OP_ADD: i32 = 1; const OP_MULTIPLY: i32 = 2; const OP_INPUT: i32 = 3; const OP_OUTPUT: i32 = 4; fn run_program(mut program: Vec<i32>) -> i32 { let mut i: usize = 0; while i < program.len() { let instr = program[i]; le...
use std::fs; fn main() { read_surveys("input/sample.input"); read_surveys("input/actual.input"); } fn read_surveys(input: &str) { let contents = fs::read_to_string(input) .expect("Something went wrong reading the file"); let mut answers: [i32; 26] = [0; 26]; let mut count = 0; let mut ...
// Copyright 2018-2019 Parity Technologies (UK) Ltd. // // 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 applicab...
struct Player {} impl Player { fn location(&self) { println!("method()"); } } fn main() { println!("Hello, world!"); let mut i = 0; let mut v = Err("an error"); while let Err(_) = v { i += 1; if i > 3 { v = Ok("success"); } } println!("{:?}"...
extern crate bkchainsaw; use std::env; use std::error::Error; use std::fs::File; use std::io::Write as IOWrite; use std::io::{BufRead, BufReader, BufWriter}; use std::io::{Seek, SeekFrom}; use std::path::PathBuf; use structopt::StructOpt; use bkchainsaw::bk; use bkchainsaw::bkfile; use bkchainsaw::bktree; use bkchain...
//! A module contains utility functions which grid relay on. pub mod string;
use crate::{Address, TemplateAddr}; #[doc(hidden)] #[derive(Debug, PartialEq, Clone)] pub enum RuntimeError { OOG, TemplateNotFound(TemplateAddr), AccountNotFound(Address), CompilationFailed { target: Address, template: TemplateAddr, msg: String, }, InstantiationFailed {...
use structopt::StructOpt; mod config; use crate::config::CorvusOpt; fn main() { let opt = CorvusOpt::from_args(); println!("opt: {:?}", opt); }
use std::ffi::OsStr; use std::io; use std::io::Error; use std::iter::once; use std::mem; use std::os::windows::ffi::OsStrExt; use std::ptr::null_mut; use winapi::shared::minwindef::{BOOL, FALSE}; use winapi::shared::ntdef::NULL; use winapi::um::handleapi::CloseHandle; use winapi::um::processthreadsapi::{GetCurrentProc...
// Copyright 2018 MaidSafe.net limited. // // This SAFE Network Software is licensed to you under the MIT license <LICENSE-MIT // http://opensource.org/licenses/MIT> or the Modified BSD license <LICENSE-BSD // https://opensource.org/licenses/BSD-3-Clause>, at your option. This file may not be copied, // modified, or di...
#[doc = r" Register block"] #[repr(C)] pub struct RegisterBlock { #[doc = "0x00 - Counter/Timer Register"] pub tmr0: TMR0, #[doc = "0x04 - Counter/Timer A0 Compare Registers"] pub cmpra0: CMPRA0, #[doc = "0x08 - Counter/Timer B0 Compare Registers"] pub cmprb0: CMPRB0, #[doc = "0x0c - Counter...
use super::DeltaTime; use crate::vector::Vec2f; use specs::prelude::*; use specs::Component; #[derive(Component, Clone, Copy)] #[storage(VecStorage)] pub struct Pos(pub Vec2f); #[derive(Component, Default, Clone, Copy)] #[storage(VecStorage)] pub struct Vel(pub Vec2f); #[derive(Component, Clone, Copy)] #[storage(Vec...
/* * 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::os::unix::io::RawFd; use super::Addr; use super::Pid; use crate::FromToRaw; // TODO: Ups...
pub mod admin; pub mod default; pub mod login; pub mod utils; // TODO: REMOVE FOR PRODUCTION! pub mod proxy; use crate::core::ServiceResult; use crate::web::utils::HbData; use actix_files as fs; use actix_web::{web, HttpRequest, HttpResponse}; use handlebars::Handlebars; /// Setup routes for admin ui pub fn init(con...
// fn main() { // // <> 表示的是一个属于的关系,RefBoy这个结构体,不能比'a更长 // struct RefBoy<'a> { // loc: &'a i32, // } // } // 结构体的引用字段必须要有显式的生命周期 // 一个被显式写出生命周期的结构体,与其自身的生命周期一定小于等于其显式写出的任意一个生命周期 // 生命周期是可以写多个的,用,分隔 // 生命周期与泛型都写在<>里,先生命周期后泛型,用,分隔 // #[derive(Copy, Clone)] // struct A { // a: i32, // } // impl ...
use backend::models::{Type, Custom, Modifier, Package}; use token; /// Position relative in file where the declaration is present. pub type Pos = (usize, usize); pub type Token<T> = token::Token<T, Pos>; #[derive(Debug, PartialEq, Clone)] pub struct FieldInit { pub name: Token<String>, pub value: Token<Value>...
//! lru-cache-macros //! ================ //! //! An attribute procedural macro to automatically cache the result of a function given a set of inputs. //! //! # Example: //! //! ```rust //! use lru_cache_macros::lru_cache; //! //! #[lru_cache(20)] //! fn fib(x: u32) -> u64 { //! println!("{:?}", x); //! if x <=...
use crate::Uncertain; use rand_pcg::Pcg32; const D0: f32 = 0.999; const D1: f32 = 0.999; const STEP: usize = 10; const MAXS: usize = 1000; fn accept_likelyhood(prob: f32, val: bool) -> f32 { let p = 0.5 * (1.0 + prob); if val { p } else { 1.0 - p } } fn reject_likelyhood(prob: f32, v...
use super::{GetMode, SpanToken, Storage}; use super::rlex::{Lexer, token, Token, DelimToken, Ident}; use std::cell::UnsafeCell; use std::str; pub struct Splice { pos: usize, len: usize, new: Vec<u8>, } #[derive(Copy, Clone, Debug)] pub struct Mark { pos: usize, } #[derive(Copy, Clone, Debug)] pub stru...