text
stringlengths
8
4.13M
// Copyright 2014 nerd-games.com. // // Licensed under the Apache License, Version 2.0. // See: http://www.apache.org/licenses/LICENSE-2.0 // This file may only be copied, modified and distributed according to those terms. use gl; use gl::types::*; use std::mem; use super::shader::*; use err::*; /// A class that hold...
#![macro_use] #[macro_export] #[cfg(test)] macro_rules! fail { ($loc:expr, $fmt:expr) => ({ panic!(concat!("Error({}): ", $fmt), $loc); }); ($loc:expr, $fmt:expr, $($arg:tt)*) => ({ panic!(concat!("Error({}): ", $fmt), $loc, $($arg)*); }); } #[cfg(not(test))] macro_rules! fail { (...
use rocket::{get, post, response::content, State}; use juniper::RootNode; use crate::{ db::PrimaryDb, graphql::{context::Context, mutation_root::MutationRoot, query_root::QueryRoot}, }; pub type Schema = RootNode<'static, QueryRoot, MutationRoot>; #[get("/")] pub fn index() -> &'static str { "Hello, world!" } #...
// Lints are currently suppressed to prevent merge conflicts in case our contributors fix their code // on their own. This attribute should be removed in the future. #![allow(warnings)] pub mod beacon_state_accessors; pub mod beacon_state_mutators; pub mod crypto; pub mod error; pub mod math; pub mod misc; pub mod pre...
#![feature(test)] extern crate mioco; extern crate test; use std::thread; fn main() { channel(10); } pub fn channel(num_threads: u64) { let (tx, rx) = mioco::sync::mpsc::channel::<u64>(); mioco::start(move || { for i in 0u64..num_threads { let tx = tx.clone(); mioco::spawn(move || { tx.send(i).un...
use std::fmt; use crate::hlc; use crate::object; #[derive(Clone, Copy, Debug)] pub enum TimestampRequirement { Equals(hlc::Timestamp), LessThan(hlc::Timestamp), GreaterThan(hlc::Timestamp), } #[derive(Copy, Clone, Debug)] pub enum KeyComparison { ByteArray, Integer, Lexical } impl KeyComparison { ...
// Copyright 2019 The Chromium OS Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. use std::collections::VecDeque; use std::io::{self, Read, Write}; use std::iter::ExactSizeIterator; use std::os::unix::io::{AsRawFd, RawFd}; use std::o...
use crate::neatns::network::node::NodeRef; /// Link between two nodes #[derive(Copy, Clone, Debug)] pub struct Link { pub from: NodeRef, pub to: NodeRef, pub weight: f64, pub enabled: bool, pub split: bool, // Link has been split pub innovation: u64, // Global innovation number } pub trait...
use crate::types::keyword_type::KeywordType; use std::fmt::{Display, Error, Formatter}; #[derive(Clone, Debug, PartialEq)] pub(in crate) struct ValidationError { // TODO: enhance content message: String, keyword: KeywordType, path: String, } impl Display for ValidationError { fn fmt(&self, f: &mut...
//! Services is a core layer for the app business logic like //! validation, authorization, etc. pub mod jwt; pub mod mocks; pub mod types; pub mod user_roles; pub mod users; pub mod util; pub use self::types::Service;
use regex::Regex; use serde::ser::{SerializeMap, Serializer}; use serde_json::Value; use tracing::{Event, Subscriber}; use tracing_bunyan_formatter::JsonStorage; use tracing_subscriber::{layer::Context, Layer}; use crate::filters::{EventFilters, Filter}; use crate::worker::{WorkerMessage, SlackBackgroundWorker}; use c...
use super::schema::{entries, feed_history, feeds}; use juniper::GraphQLObject; use serde::{Deserialize, Serialize}; // TODO: rework schema to make most fields non-nullable? #[derive(Queryable, PartialEq, Debug, Serialize, Deserialize)] pub struct Entry { pub id: Option<String>, pub feed_id: Option<String>, ...
/// Brainfuck language interpreter /// As specified here: http://www.muppetlabs.com/~breadbox/bf/ #[macro_use] extern crate clap; use std::process; use std::path::{Path}; use std::io; use std::io::prelude::*; use std::fs::File; use std::collections::VecDeque; use std::thread; use std::time::Duration; use clap::{Arg, ...
#![allow(dead_code, unused_imports)] #[cfg(test)] mod tests; mod tile; mod orientation; use tile::Tile; use orientation::{index_rotated_grid, Rotation, Orientation, MatingSide}; fn parse_input(path: &str) -> Vec<Tile> { std::fs::read_to_string(path).unwrap() .split("\n\n") .map(|section| Tile::fr...
use async_std::io::Read as AsyncRead; use async_std::prelude::*; use async_std::task::{ready, Context, Poll}; use std::io; use std::pin::Pin; use std::time::Duration; use std::io::Write; use flate2::{GzBuilder, Compression}; #[derive(Debug)] struct WriteBuf { buf: Vec<u8>, } impl Write for WriteBuf { fn wri...
//! # Parse structures from a byte buffer use super::file::*; use nom::{ bytes::complete::take, combinator::map, number::complete::le_u32, sequence::tuple, IResult, }; use std::convert::TryInto; fn u8_4(i: &[u8]) -> IResult<&[u8], [u8; 4]> { let (i, slice) = take(4usize)(i)?; Ok((i, slice.try_into().unwra...
#![feature(proc_macro_hygiene, decl_macro)] #[macro_use] extern crate rocket; use rocket::response::content; #[get("/json")] fn json() -> content::Json<&'static str> { content::Json("{ 'hi': 'world' }") } #[get("/world")] // <- route attribute fn world() -> &'static str { // <- request handler ...
mod args; use std::borrow::Cow; pub enum Command<'a> { Connect { server: Cow<'a, str> }, Disconnect, Groups, Users, }
//! Tests auto-converted from "sass-spec/spec/non_conformant/extend-tests" #[allow(unused)] use super::rsass; // From "sass-spec/spec/non_conformant/extend-tests/001_test_basic.hrx" #[test] #[ignore] // unexepected error fn t001_test_basic() { assert_eq!( rsass( ".foo {a: b}\ \n.bar...
#[macro_use] use derive_serialize::Serialize; #[derive(Serialize)] pub struct Apu { // TODO: implement }
use std::io::{self, Read}; use std::fmt; use std::fs::File; use std::path::Path; use std::cell::RefCell; use memchr::memchr; use {Span, TokenStream, LexError}; use lex::lex_str; const FILE_PADDING_BYTES: usize = 1; /// Information regarding the on-disk location of a span of code. /// This type is produced by `Sourc...
use sdl2::pixels::Color; use sdl2::render::{Texture, WindowCanvas}; use specs::prelude::*; use crate::ecs::components::*; pub type SystemData<'a> = (ReadStorage<'a, Position>, ReadStorage<'a, Sprite>); pub fn render( canvas: &mut WindowCanvas, background: Color, textures: &[Texture], data: SystemData...
// Copyright 2017 PingCAP, 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...
#[doc = "Reader of register IDACA"] pub type R = crate::R<u32, super::IDACA>; #[doc = "Writer for register IDACA"] pub type W = crate::W<u32, super::IDACA>; #[doc = "Register IDACA `reset()`'s with value 0"] impl crate::ResetValue for super::IDACA { type Type = u32; #[inline(always)] fn reset_value() -> Sel...
pub use self::context::OpenCLContext; pub use self::device::OpenCLDevice; pub use self::framework::OpenCL; pub use self::memory::{OpenCLBuf, OpenCLMemory}; mod context; mod device; mod error; mod framework; mod memory;
#![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 EdgeModuleProperties { #[serde(rename = "edgeModuleId", default, skip_serializing_if = "Option::is_none")] ...
use crate::parser::{Lexer, Loc, ParserError}; #[derive(Debug)] pub enum StrLitDecodeError { Error, } impl From<ParserError> for StrLitDecodeError { fn from(_: ParserError) -> Self { StrLitDecodeError::Error } } pub type StrLitDecodeResult<T> = Result<T, StrLitDecodeError>; /// String literal, bo...
use bio::pattern_matching::shift_and; use std::fs; pub fn run(filename: &str) { let file = fs::read(filename).expect("Something went wrong reading the file"); let mut lines = file.split(|&b| b == b'\n'); let dna = lines.next().expect("Missing dna"); let pattern = lines.next().expect("Missing pattern");...
pub trait Chunks { type Next: Chunks; fn chunk<F>(self, F) where F: for<'a> FnOnce(&'a [u8], Option<Self::Next>) + 'static; fn attach(self, data: &[u8]) -> Fused<Self> { Fused(self, Some(data)) } fn fuse<'a>(self) -> Fused<'a, Self> { Fused(self, None) } } pub struct Fused<'a, C>(C, Option<&'a [u8]>) ...
use std::collections::{HashMap, HashSet}; use std::env; use std::path::PathBuf; use std::sync::mpsc::channel; use std::sync::{Arc, Mutex}; use std::thread; use std::time::Duration; use actix_web::web; use chrono::Local; use notify::{DebouncedEvent, RecommendedWatcher, RecursiveMode, Watcher}; use crate::db; /// 建立异步...
use super::{Trader, Order, Action}; use crate::indicators::{Value, Indicator}; use crate::economy::Monetary; pub struct And<T1, T2> where T1: Trader, T2: Trader { trader1: T1, trader2: T2 } impl<T1, T2> Trader for And<T1, T2> where T1: Trader, T2: Trader { type Ind...
use std::{ ffi::c_int, io::{self, Read, Write}, mem::size_of, os::{ fd::{AsRawFd, RawFd}, unix::net::UnixStream, }, }; use crate::exec::signal_fmt; use crate::system::interface::ProcessId; use super::CommandStatus; type Prefix = u8; type ParentData = c_int; type MonitorData = c_in...
enum blah { a, b, } fn or_alt(q: blah) -> int { alt q { a | b { 42 } } } fn main() { assert (or_alt(a) == 42); assert (or_alt(b) == 42); }
/// Status holds a single Status of a single Commit #[derive(Debug, Default, Clone, Serialize, Deserialize)] pub struct Status { pub context: Option<String>, pub created_at: Option<String>, pub creator: Option<crate::user::User>, pub description: Option<String>, pub id: Option<i64>, pub status:...
use std::cell::RefCell; use std::collections::BTreeMap; use std::rc::Rc; use std::sync::{Arc, Mutex}; use console_error_panic_hook::set_once as set_panic_hook; use specs::prelude::*; use wasm_bindgen::{prelude::*, JsCast}; use web_sys::{ console, Document, Event, EventTarget, HtmlInputElement, InputEvent, MouseEve...
// Copyright 2019, 2020 Wingchain // // 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...
//! Contains the various structs and methods for handling JSON objects. pub mod award; pub mod comment; pub mod link; #[doc(hidden)] pub mod listing; pub mod message; pub mod misc; #[doc(hidden)] pub mod more; pub mod prelude; pub mod subreddit; #[doc(hidden)] pub mod thing; pub mod user; pub mod usersubreddit;
use std::{ error::Error, path::{Path, PathBuf}, }; use teraron::Mode; pub const GRAMMAR: &str = "components/syntax/src/grammar.ron"; pub const SYNTAX_KINDS: &str = "components/syntax/src/syntax/generated.rs.tera"; pub const AST: &str = "components/syntax/src/ast/generated.rs.tera"; fn main() { generate(Mo...
//! VapourSynth script-related things. #[cfg(not(feature = "gte-vsscript-api-32"))] use std::sync::Mutex; use std::sync::Once; use vapoursynth_sys as ffi; #[cfg(not(feature = "gte-vsscript-api-32"))] lazy_static! { static ref FFI_CALL_MUTEX: Mutex<()> = Mutex::new(()); } // Some `vsscript_*` function calls have ...
use rusqlite::Connection; pub fn conn(p: String) -> Connection { let c = Connection::open(p).unwrap(); c.execute( include_str!("sql/create.sql") , &[]).expect("erorr db create_table"); c } pub fn insert_money(c: &mut Connection, vals: Vec<(String, u32)>) { let tx = c.transaction().expect("transa...
extern crate wasm_bindgen; use wasm_bindgen::prelude::*; #[wasm_bindgen] #[derive(Debug)] pub struct Node<'a, T: PartialOrd> { data: &'a T, left: Option<Box<Node<'a, T>>>, right: Option<Box<Node<'a, T>>>, } impl<'a, T: PartialOrd> Node<'a, T> { pub fn new(data: &'a T) -> Self { return Node { ...
use crate::{lib}; #[derive(Debug)] pub enum Error { MissingPin, } pub enum DigitalOutputMode { On, Off } pub enum DigitalReadMode { On, Off } pub fn digital_output_mode(pin: &lib::pin::PinGroup, mode: DigitalOutputMode) -> Result<(), Error>{ if pin.number > 32 { return Err(Error::Mi...
#[doc = "Register `MACHWF1R` reader"] pub type R = crate::R<MACHWF1R_SPEC>; #[doc = "Field `RXFIFOSIZE` reader - MTL Receive FIFO Size"] pub type RXFIFOSIZE_R = crate::FieldReader; #[doc = "Field `TXFIFOSIZE` reader - MTL Transmit FIFO Size"] pub type TXFIFOSIZE_R = crate::FieldReader; #[doc = "Field `OSTEN` reader - O...
mod guessing; mod funcs; fn main() { guessing::guessing_game(10); }
/// <summary> /// 2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder. /// What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20? /// </summary> /// <returns></returns> pub fn compute() -> String { fn all_are_factors(n...
// Recursion fn factorial(value: i64) -> i64 { return if value == 1 { value } else { value * factorial(value - 1) }; } fn main() { let a = factorial(3); println!("data: {}", a); }
use std::error::Error; use std::sync::mpsc; use arrayvec::ArrayVec; const MIDI_MSG_MAX_LEN: usize = 16; pub fn get_input_ports() -> Result<Vec<String>, Box<dyn Error>> { let midi_in = midir::MidiInput::new("input_device_checker")?; (0..midi_in.port_count()) .map(|i| Ok(midi_in.port_name(i)?)) ...
//! Types and utilities for encoding and decoding ROTMG packets. //! //! This crate provides functionality to represent and manipulate ROTMG packets. //! It defines structs for every packet type known at the time of writing, as //! well as traits and implementations to allow encoding/decoding the packets as //! bytes, ...
//! ### Parsers for the data use super::file::*; use assembly_core::nom::{ number::complete::{le_f32, le_u32, le_u8}, IResult, }; pub fn parse_terrain_header(input: &[u8]) -> IResult<&[u8], TerrainHeader> { let (input, version) = le_u8(input)?; let (input, value_1) = le_u8(input)?; let (input, valu...
// Copyright 2016 Google 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 in...
pub fn is_armstrong_number(num: u32) -> bool { let digits = get_digits_from_num(num); let sum = digits.iter().map(|d| d.pow(digits.len() as u32)).sum::<u32>(); num == sum } fn get_digits_from_num(num: u32) -> Vec<u32> { num.to_string().chars().map(|d| d.to_digit(10).unwrap()).collect() }
use amethyst::ecs::prelude::{Component, VecStorage}; /// The ship's fuel tank. /// Holds `fuel_level`, the current amount of fuel in the tank. /// Holds `capacity`, the maximum amount of fuel carryable. /// Holds `weight_per_fuel`, the weght of each unit of fuel, updated on every movement or when refilling. #[derive(D...
use log::*; use rumqttc::{ConnectionError, TlsConfiguration, Transport}; use rumqttc::{Event, EventLoop, Incoming, MqttOptions, Publish, QoS, Request, Subscribe}; use serde::{Deserialize, Serialize}; use simple_logger::SimpleLogger; use std::{ fs, io::{self, BufRead, Read, Write}, path::PathBuf, time::S...
extern crate vyre_rs; use vyre_rs::graphics::*; use vyre_rs::graphics::opengl::*; type RenderFormat = render_format::Rgba8; type DepthFormat = depth_format::Depth; /// initializes the graphics engine and returns earlier if errors occur. Returns handles to window, device, render/depth target and a simple pipeline fn ...
extern crate bio; use bio::io::fastq::Record; use std::io; use std::io::{Error, ErrorKind}; pub struct PairRecords<R: io::Read, S: io::Read> { r1_records: bio::io::fastq::Records<R>, r2_records: bio::io::fastq::Records<S>, } impl<R: io::Read, S: io::Read> PairRecords<R, S> { pub fn new( r1_record...
#![cfg(feature = "std")] use tabled::settings::{Concat, Style}; use crate::matrix::Matrix; use testing_table::test_table; test_table!( join_vertical_0, Matrix::new(2, 3).insert((1, 0), "123").with(Style::psql()) .with(Concat::vertical(Matrix::new(2, 3).to_table())) .to_string(), " N | c...
#![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)] Operations_List(#[from] operations::l...
// SPDX-License-Identifier: (LGPL-2.1 OR BSD-2-Clause) use anyhow::{bail, Result}; use chrono::Local; use core::time::Duration; use libbpf_rs::PerfBufferBuilder; use libc::{rlimit, setrlimit, RLIMIT_MEMLOCK}; use plain::Plain; use std::process::exit; use structopt::StructOpt; use sym_finder; mod bpf; use bpf::*; #[d...
#![feature(old_io)] #![feature(unicode)] use std::old_io as io; fn main () { let input: String = io::stdin().read_line().ok().expect("Fuck."); let mut count_a = 0; let mut count_c = 0; let mut count_g = 0; let mut count_t = 0; for i in input.graphemes(true) { match i { "A" => count_a += 1, "C" => count_c +...
use crate::vtable::VTable; use apllodb_shared_components::{ ApllodbError, ApllodbResult, BooleanExpression, ComparisonFunction, Expression, LogicalFunction, NnSqlValue, RPos, Schema, SchemaIndex, SqlConvertible, SqlValue, }; use apllodb_storage_engine_interface::{ColumnDataType, ColumnName, Row, RowSchema, Tabl...
//! <https://github.com/EOSIO/eosio.cdt/blob/796ff8bee9a0fc864f665a0a4d018e0ff18ac383/libraries/eosiolib/contracts/eosio/producer_schedule.hpp#L54-L69> use alloc::vec::Vec; use crate::{AccountName, NumBytes, ProducerKey, Read, Write, PublicKey, Checksum256, UnsignedInt}; use codec::{Encode, Decode}; use core::default::...
use futures::{Future, Sink, Stream}; use netlink_packet_route::{ link::{LinkHeader, LinkMessage}, RtnlMessage, }; use netlink_proto::{ packet::{ header::flags::{NLM_F_DUMP, NLM_F_REQUEST}, NetlinkFlags, NetlinkHeader, NetlinkMessage, NetlinkPayload, }, sys::{Protocol, SocketAddr, T...
pub mod fps; pub mod orbit; pub mod unreal;
use std::collections::HashMap; use crate::object; use crate::store::TxStateRef; use crate::transaction; use crate::transaction::requirements::*; pub fn lock_requirements( tx_id: transaction::Id, requirements: &Vec<TransactionRequirement>, objects: &mut HashMap<object::Id, TxStateRef>) { for r i...
use std::cmp::max; fn is_prime(n: i64) -> bool { if n < 2 { return false; } let mut x = 2; while x * x <= n { if n % x == 0 { return false; } x += 1; } return true; } #[test] fn test_is_prime() { assert!(!is_prime(1)); assert!(is_prime(2)); ...
use std::mem; use std::ops::Mul; use ui_sys::{self, uiDrawMatrix}; /// A transformation which can be applied to the contents of a DrawContext. #[derive(Copy, Clone, Debug)] pub struct Transform { ui_matrix: uiDrawMatrix, } impl Transform { /// Create a Transform from an existing raw uiDrawMatrix. pub fn f...
// chapter 2 "using variables and types" // program section: fn main() { // here starts the execution of the game. // we begin with printing a welcome message: println!("welcome to the game!"); } /* output should be: end of output */
fn foo(x: &i32) { if *x == 0 { print!("0\n"); } else if *x < 0 { print!("-\n"); } else if *x > 0 { print!("+\n"); } else { print!("absurd!\n"); 1/0; } } fn bar(x: &mut i32) { foo(& *x); *x = *x - 2; foo(x); } fn main() { let mut x = 8; { let y = &mut x; ...
// This file was generated by gir (https://github.com/gtk-rs/gir @ fbb95f4) // from gir-files (https://github.com/gtk-rs/gir-files @ 77d1f70) // DO NOT EDIT use Cancellable; use Error; use IOStream; use Socket; use SocketAddress; use SocketFamily; use SocketType; use ffi; use glib; use glib::object::Downcast; use glib...
use std::error::Error; use std::fs::File; use std::io::prelude::*; use std::process::Command; struct Ignore; impl<E> From<E> for Ignore where E: Error, { fn from(_: E) -> Ignore { Ignore } } fn commit_hash() -> Result<String, Ignore> { Ok(String::from_utf8( Command::new("git") ...
use aoc20::days::day18; #[test] fn day18_test_part1() { assert_eq!(71, day18::evaluate("1 + 2 * 3 + 4 * 5 + 6", day18::Part::Part1)); assert_eq!(51, day18::evaluate("1 + (2 * 3) + (4 * (5 + 6))", day18::Part::Part1)); assert_eq!(26, day18::evaluate("2 * 3 + (4 * 5)", day18::Part::Part1)); assert_eq!(43...
use structopt::StructOpt; use riff::diff::{compare, CompareOptions}; #[derive(Debug, StructOpt)] struct Opt { /// Path to image (jpeg or png) to compare from base_path: String, /// Path to image (jpeg or png) to compare to diff_path: String, /// Path to output image (jpeg or png) #[structopt(...
use crate::util::get_character_histogram; use crate::util::hamming_distance; use crate::util::score_text; // Decrypt ciphertext using xor pub fn decrypt_xor(key: u8, ciphertext: &[u8]) -> Vec<u8> { ciphertext.iter().map(|c| c ^ key).collect::<Vec<u8>>() } // Decrypt using the key and return the score and decrypte...
use reqwest; use std::cell::RefCell; use std::convert::AsRef; use std::env; use std::fs::{self, DirEntry, File}; use std::future::{Future, Ready}; use std::io::{self, BufRead, BufReader}; use std::marker::PhantomData; use std::path::Path; use std::process; use std::sync::{Arc, Mutex}; use tokio::runtime::Runtime; use t...
// Call Machine layor // Currently not to use all SBI call, allow unused variables and functions just for now. #![allow(unused)] // ************************************************************************************* // SBI #[inline(always)] fn sbi_call(which: usize, arg0: usize, arg1: usize, arg2: usize) -> usize ...
use std::collections::HashMap; static FILENAME: &str = "input/data"; struct Bus { no: usize, departure: usize, } fn main() { let data = std::fs::read_to_string(FILENAME).expect("could not read file"); let time = parse_time(&data); let buses: Vec<Bus> = parse_buses(&data); println!("{}", part_...
use std::mem; pub struct LinkedList { tail: Link } struct Node { data: u32, next: Link, } enum Link { Nothing, Something(Box<Node>), } impl LinkedList { pub fn new() -> Self { LinkedList { tail: Link::Nothing, } } pub fn insert( &mut self, ...
pub use platform::*; #[cfg(any(target_arch = "x86", target_arch = "x86_64"))] pub mod platform { use option::Option::{self, Some, None}; pub fn u8_safe_div(lhs: u8, rhs: u8) -> Option<(u8, u8)> { if rhs == 0 { None } else { let div: u8; let rem: u8; ...
use sdl2::{surface::SurfaceRef, rect::Rect, video::Window, render::{Texture, Canvas}, pixels::PixelFormatEnum}; pub trait RenderSurface { fn render_surface(&mut self, dest: Rect, src: &SurfaceRef, src_box: Rect) -> Result<(),String>; fn create_cache_tex(&mut self, size: (u32,u32), p: PixelFormatEnum) -> Result...
mod topic; mod user; use topic::*; use user::*; use crate::controller::ControllerConfig; use async_trait::async_trait; use drogue_client::{ core::v1::Conditions, meta::v1::CommonMetadataMut, registry::{self, v1::KafkaAppStatus}, Translator, }; use drogue_cloud_operator_common::controller::{ base::...
// date and time extern crate chrono; use crud::chrono::prelude::Utc; // use models::{NewPost}; use models::{NewPost, NewUser, NewYtb}; pub fn create_post( user_id: i32, media_url: Option<String>, media_title: Option<String>, title: String, subtitle: String, content: String, tags: Option<...
use crate::gameloop::*; use crate::prelude::*; use bincode::Options; use js_sys::JsString; use serde::de::DeserializeOwned; use std::future::Future; use wasm_bindgen::prelude::*; use wasm_bindgen::JsCast; use wasm_bindgen_futures::spawn_local; use web_sys::HtmlElement; use winit::dpi::LogicalSize; use winit::event::Wi...
#![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 enum AuthType { #[serde(rename = "systemAssignedIdentity")] SystemAssignedIdentity, #[serde(rename = "userAssi...
use std::io::{self}; fn main() { let mut input = String::new(); io::stdin().read_line(&mut input).unwrap(); print!("{}", count(input.as_str())); } fn count(line: &str) -> i32 { let mut num = 0; for char in line.chars() { match char { '1' => num += 1, _ => {} ...
//! Transport from BigQuery Source to Arrow Destination. use crate::{ destinations::arrow::{typesystem::ArrowTypeSystem, ArrowDestination, ArrowDestinationError}, impl_transport, sources::bigquery::{BigQuerySource, BigQuerySourceError, BigQueryTypeSystem}, typesystem::TypeConversion, }; use chrono::{Da...
use core::parser::IrcMessage; use core::net::TcpWriter; use std::thread; use std::collections::HashMap; use chan; use libloading::{Library, Symbol}; pub type IrcFn = fn(&mut TcpWriter, &IrcMessage); pub struct HandlerThread<'ht> { writer: TcpWriter, receiver: chan::Receiver<IrcMessage>, pub handlers: Hash...
#[macro_use] extern crate log; pub mod core; pub mod file;
use std::cmp::min; fn main() { let n: usize = { let mut line = String::new(); std::io::stdin().read_line(&mut line).unwrap(); line.trim_end().parse().unwrap() }; let s: String = { let mut line = String::new(); std::io::stdin().read_line(&mut line).unwrap(); ...
extern crate extended_collections; extern crate rand; use self::rand::{thread_rng, Rng}; use extended_collections::skiplist::SkipList; use extended_collections::skiplist::SkipMap; use std::vec::Vec; const NUM_OF_OPERATIONS: usize = 100_000; #[test] fn int_test_skip_map() { let mut rng: rand::XorShiftRng = rand::...
use crate::{prelude::*, sql::CXQuery}; use arrow::record_batch::RecordBatch; use datafusion::datasource::MemTable; use datafusion::prelude::*; use fehler::throws; use log::debug; use rayon::prelude::*; use std::collections::HashMap; use std::convert::TryFrom; use std::sync::{mpsc::channel, Arc}; #[throws(ConnectorXOut...
// Copyright 2018 Fredrik Portström <https://portstrom.com> // This is free software distributed under the terms specified in // the file LICENSE at the top-level directory of this distribution. use parse_wiki_text::Positioned; pub struct Context<'a> { pub language: Option<::Language>, pub warnings: Vec<::War...
extern crate jni; use jni::{ objects::JClass, sys::jint, JNIEnv }; /// Returns the square of integer. fn sqr_internal(a: i32) -> i32 { a * a } /// Returns result of division of two integers. Exported function, `no_mangle` is required. #[no_mangle] pub fn div(a: i32, b: i32) -> i32 { a / b } // *...
fn next_perm(vect: &mut Vec<usize>) { let mut i = vect.len() - 1; // pivot-to-be (index) while i > 0 && vect[i - 1] >= vect[i] { i -= 1; } if i == 0 { panic!("last permutation!"); } // smallest larger than pivot (index) // inside the suffix let mut j = vect.len() - 1;...
#[doc = "Reader of register SW_HS_N_SEL"] pub type R = crate::R<u32, super::SW_HS_N_SEL>; #[doc = "Writer for register SW_HS_N_SEL"] pub type W = crate::W<u32, super::SW_HS_N_SEL>; #[doc = "Register SW_HS_N_SEL `reset()`'s with value 0"] impl crate::ResetValue for super::SW_HS_N_SEL { type Type = u32; #[inline(...
//! Module to control shutdown in lading. //! //! Lading manages at least one sub-process, possibly two and must coordinate //! shutdown with an experimental regime in addition to the target sub-process' //! potential failures. Controlling shutdown is the responsibility of the code //! in this module, specifically [`Sh...
#![deny(clippy::all, clippy::pedantic)] use unicode_segmentation::UnicodeSegmentation; pub fn reverse(input: &str) -> String { input.graphemes(true).rev().collect::<String>() }
use std::{collections::VecDeque, iter::FromIterator}; #[derive(Debug)] struct LazyBufferEdge<T> { // index of left-most element in *resulting* buffer left_idx: usize, // size of this piece of buffer (including sizes of kids) size: usize, vertex: Box<LazyBuffer<T>>, } #[derive(Debug)] struct LazyBu...
#[test] fn rounding_total_fractial() { let layout = stretch::node::Node::new( stretch::style::Style { flex_direction: stretch::style::FlexDirection::Column, size: stretch::geometry::Size { width: stretch::style::Dimension::Points(87.4f32), height: stre...
#[doc = "Register `RCC_LPTIM1CKSELR` reader"] pub type R = crate::R<RCC_LPTIM1CKSELR_SPEC>; #[doc = "Register `RCC_LPTIM1CKSELR` writer"] pub type W = crate::W<RCC_LPTIM1CKSELR_SPEC>; #[doc = "Field `LPTIM1SRC` reader - LPTIM1SRC"] pub type LPTIM1SRC_R = crate::FieldReader; #[doc = "Field `LPTIM1SRC` writer - LPTIM1SRC...
use crate::node::Node; use anyhow::{bail, Context, Result}; use bit_vec::BitVec; use std::cmp::Reverse; use std::collections::{BinaryHeap, HashMap, VecDeque}; use std::fs::File; use std::io::prelude::*; use std::io::{BufReader, BufWriter, ErrorKind, SeekFrom}; use std::path::Path; const BUFFER_SIZE: usize = 4096; type...