text
stringlengths
8
4.13M
ApBegin(RS,CLSID_OFFAPP) WndBegin(OFF_WND_ANIM) WdgBegin(CLSID_IMAGEWIDGET,tOffAnimImage) #ifdef __USER_DEFINE_POWERONOFF_ANIM__ WdgImageCreateForWndRC({{0,0},{MAIN_LCD_WIDTH,MAIN_LCD_HEIGHT},IMAGE_STYLE_COMMON,{FALSE,IMG_NULL_ID}}) WdgImageSetDataByIDRC(IMG_NULL_ID) #else //__USER_DEFIN...
use sorting_algorithms; fn main() { sorting_algorithms::benchmarks::run_benchmarks(); }
//! FF1 NumeralString implementations that require a global allocator. use core::iter; use alloc::{vec, vec::Vec}; use num_bigint::{BigInt, BigUint, Sign}; use num_traits::{ identities::{One, Zero}, ToPrimitive, }; use super::{NumeralString, Operations}; fn pow(x: u32, e: usize) -> BigUint { let mut re...
use crate::consts::EASY; use crate::consts::HARD; use crate::consts::MEDIUM; use crate::game::Difficulty; use crate::game::Game; use crate::game::GameScene; use crate::key::Key; use crate::ui::ButtonList; use crate::window::Window; #[repr(transparent)] pub struct DifficultyScene<'a> { buttons: ButtonList<'a, { 3 }>,...
//! Postgres message protocol support. //! //! See [Postgres's documentation][docs] for more information on message flow. //! //! [docs]: https://www.postgresql.org/docs/9.5/static/protocol-flow.html pub mod backend; pub mod frontend;
#[derive(Clone, Copy)] pub struct Color { pub r: u8, pub g: u8, pub b: u8, } // for easier building macro_rules! color { ($r:expr, $g:expr, $b:expr) => { Color { r: $r, g: $g, b: $b, } }; } // got these color data from // http://www.thealmightygu...
use crate::utils::ToClass; use crate::widgets::{self, Reqs, View, Widget, WidgetModel}; use protocol::{Col, Component, Row}; use yew::{html, Properties}; pub type RowWidget = WidgetModel<Model>; pub struct Model { row: Row, } #[derive(Properties, PartialEq, Clone)] pub struct Props { #[props(required)] p...
//! Scalar field arithmetic. use cfg_if::cfg_if; cfg_if! { if #[cfg(any(target_pointer_width = "32", feature = "force-32-bit"))] { mod scalar_8x32; use scalar_8x32::MODULUS; use scalar_8x32::Scalar8x32 as ScalarImpl; use scalar_8x32::WideScalar16x32 as WideScalarImpl; } else if...
use std::ascii::AsciiExt; fn ascii(ch: char) -> u8 { ch as u8 } fn get_correct_char(ch: char) -> char { if ch.is_digit(10) { return ch; } (ascii('z') - ascii(ch) + ascii('a')) as char } fn cipherengine(input: &str) -> Vec<String> { input.to_lowercase().chars().filter(|&c| c.is_asc...
struct Solution; impl Solution { pub fn plus_one(mut digits: Vec<i32>) -> Vec<i32> { let mut i = digits.len() - 1; loop { if digits[i] < 9 { digits[i] += 1; return digits; } digits[i] = 0; if i > 0 { i ...
struct User { active: bool, // we want instances of this struct to own all of its data // and for that data to be valid for as long as the entire struct is valid username: String, email: String, sign_in_count: u64, } let mut user1 = User { email: String::from("someone@example.com"), use...
// Copyright (c) The Libra Core Contributors // SPDX-License-Identifier: Apache-2.0 use super::*; use proptest::prelude::*; use schemadb::schema::assert_encode_decode; proptest! { #[test] fn test_encode_decode( stale_node_index in any::<StaleNodeIndex>(), ) { assert_encode_decode::<StaleNo...
mod board; mod tile; mod strategy; mod conditions; pub mod game;
#![cfg(not(loom))] #![feature(sync_unsafe_cell)] #![no_implicit_prelude] use ::drone_core::{override_layout, stream}; override_layout! { r#" [ram] main = { origin = 0x20000000, size = "20K" } [data] ram = "main" [stream] ram = "main" [stream.core0] ram = "main" size = "260" init-primary = true [stream.core1] ram ...
use std::str::Chars; use part1::part1; use part2::part2; use structs::PairComponent; mod part1; mod part2; mod structs; fn main() { let input = include_str!("../assets/input_ludegra.txt") .trim() .split('\n') .map(|s| { map_string(&mut s.chars()) }) .collect::<...
/** * [1337] The K Weakest Rows in a Matrix * * You are given an m x n binary matrix mat of 1's (representing soldiers) and 0's (representing civilians). The soldiers are positioned in front of the civilians. That is, all the 1's will appear to the left of all the 0's in each row. A row i is weaker than a row j if o...
/* * Copyright 2019 Comcast Cable Communications Management, LLC * * 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...
use std::net::TcpStream; use std::net::Shutdown; use std::io::Read; use std::io::Write; use std::io::Error; use std::vec::Vec; pub struct Tcp { stream: TcpStream } pub enum TcpError { Eof, ErrorData, IoError(Error), } impl Tcp { pub fn new(stream: TcpStream) -> Tcp { Tcp { stream: stream ...
#![cfg_attr(rustfmt, rustfmt::skip)] use super::*; type Result<T, E = Error> = ::core::result::Result<T, E>; pub(in crate) trait CollectVec : Sized + IntoIterator { fn vec (self: Self) -> Vec<Self::Item> { impl<I : IntoIterator> CollectVec for I {} self.into_iter().collect() } } pu...
#[macro_use] extern crate criterion; use assert_cmd::Command; use criterion::Criterion; fn run_cli_plain() { Command::cargo_bin("devicon-lookup") .unwrap() .pipe_stdin("tests/fixtures/all-types-large.txt") .unwrap(); } fn run_cli_color() { Command::cargo_bin("devicon-lookup") ...
pub fn z_algorithm<T: PartialEq>(s: &[T]) -> Vec<usize> { let mut z = vec![0; s.len()]; z[0] = s.len(); let mut i = 1; let mut p = 0; while i < s.len() { while s.get(p) == s.get(i + p) { p += 1; } z[i] = p; let mut k = 1; while k + z[k] < p { ...
use super::super::basic::fund::Container; pub struct Board { width: u16, height: u16, view_box_x: u16, view_box_y: u16, view_box_width: u16, view_box_height: u16 } impl Board { pub fn new(width: u16, height: u16) -> Board { Board { width: width, height: hei...
#![cfg_attr(not(feature = "std"), no_std)] #[cfg(feature = "std")] extern crate heapsize; #[cfg(not(feature = "std"))] extern crate alloc; // Re-export libcore using an alias so that the macros can work without // requiring `extern crate core` downstream. #[doc(hidden)] pub extern crate core as core_; use core_::{...
// This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of // the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/ //! Structures for instructions parsing. use std::collections::VecDeque; pub use crate::formulation::output::{Attribute...
mod web_conf; pub use web_conf::*; pub const WEB_CONF_FILES: &'static str = ".conf/"; pub const WEB_CONF_FILES_CONF: &'static str = ".conf/web.yaml"; pub const WEB_CONF_FILES_WEB_CERT: &'static str = ".conf/cert.pem"; pub const WEB_CONF_FILES_WEB_KEY: &'static str = ".conf/key.pem"; pub const WEB_CONF_FILES_ALPN_CERT...
extern crate bip_dht; extern crate bip_handshake; extern crate bip_util; extern crate log; use std::collections::{HashSet}; use std::io::{self, Read}; use std::net::{SocketAddr, Ipv4Addr, SocketAddrV4, ToSocketAddrs}; use std::thread::{self}; use bip_dht::{DhtBuilder, Router}; use bip_handshake::{Handshaker}; use bip...
#![deny(warnings)] use std::convert::Infallible; use std::fs; use std::thread; use std::time::Duration; use hyper::service::{make_service_fn, service_fn}; use hyper::{Body, Request, Response, Server}; async fn hello(_: Request<Body>) -> Result<Response<Body>, Infallible> { let contents = fs::read_to_string("hell...
#![cfg_attr(rustfmt, rustfmt::skip)] //! The logic around the dynamically self-registered Node.js functions. //! //! One of the possible approaches to do this with N-API is by exporting //! a `napi_register_module_v1` special function. //! //! But that must be done from the downstream crate, so we export a macro //! th...
use std::fmt::Display; /// A generic wrapper for each day in the Advent of Code. pub trait Day<'a> { /// The day of the advent calendar that this implementation is for. const NUM: u32; type Output1: Display; type Output2: Display; /// Each challenge has an input, this constructs the challenge data...
extern crate libc; use self::libc::c_char; use std::ffi::CString; use settings; use std::ptr::null; use utils::libindy::{indy_function_eval}; use utils::libindy::return_types::{ Return_I32, Return_I32_I32, receive}; use utils::libindy::error_codes::{map_indy_error_code, map_string_error}; use utils::timeout::TimeoutUt...
// Copyright (c) 2018 libeither developers // // Licensed under the Apache License, Version 2.0 // <LICENSE-APACHE or https://www.apache.org/licenses/LICENSE-2.0> or the MIT // license <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your // option. All files in the project carrying such notice may not be copie...
use crate::address; use crate::config::{ACLConfig, MatchMode, Policy}; use std::str::FromStr; use std::sync::RwLock; use log::debug; pub struct ACLManager { rules: RwLock<ACLConfig>, } impl ACLManager { pub fn new(rules: ACLConfig) -> Self { ACLManager { rules: RwLock::new(rules), ...
use primes::{factors, factors_uniq, is_prime, PrimeSet, PrimeSetBasics, Sieve, TrialDivision}; #[test] fn test_primesetbasics() { let mut pset = TrialDivision::new(); let ln = pset.list().len(); pset.expand(); assert_eq!(pset.list().len(), ln + 1); } #[test] fn test_primeset() { let mut pset = Tr...
pub fn as_string() -> String { let spec = include_str!("../specification/i3df-specification.yaml"); spec.to_string() }
// This file is part of Substrate. // Copyright (C) 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 // // http://www.a...
// Copyright 2020. The Tari Project // // Redistribution and use in source and binary forms, with or without modification, are permitted provided that the // following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following // disclai...
use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::Arc; use shredder::{Finalize, FinalizeFields}; struct FinalizeMark { finalized: Arc<AtomicBool>, } unsafe impl Finalize for FinalizeMark { unsafe fn finalize(&mut self) { self.finalized.store(true, Ordering::SeqCst) } } #[derive(Final...
use ops::operation::Operation; use vm::state; pub struct Or; impl Operation for Or { fn run(&self, vm_state: &mut state::VMState) { let ci = vm_state.get_current_instruction(); let val1 = vm_state.get_mem_or_register_value(ci + 2); let val2 = vm_state.get_mem_or_register_value(ci + 3); let reg = vm_state.get_...
use bytelines::*; use std::fs::File; use std::io::BufReader; pub fn main() { // construct our iterator from our file input let file = File::open("./res/numbers.txt").unwrap(); let lines = BufReader::new(file).byte_lines(); // walk our lines using `for` syntax for line in lines.into_iter() { ...
#[aoc_generator(day13)] fn generator_input(input: &str) -> Vec<(u16, u16)> { let mut parts = input.split("\n\n"); parts.next().unwrap().lines().map(|l| { let mut parts = l.split(','); (parts.next().unwrap().parse().unwrap(), parts.next().unwrap().parse().unwrap()) }).collect() } #[aoc(day13...
pub mod hierarchy_util;
use std::sync::Arc; use nimiq_block::{MacroBody, MacroHeader}; use nimiq_hash::{Blake2sHash, Hash}; use nimiq_keys::Signature as SchnorrSignature; use nimiq_network_interface::{ network::Network, request::{Handle, RequestCommon, RequestMarker}, }; use nimiq_tendermint::{Inherent, Proposal, ProposalMessage, Sig...
// https://leetcode.com/problems/frequency-of-the-most-frequent-element/ // The frequency of an element is the number of times it occurs in an array. // You are given an integer array nums and an integer k. In one operation, you can choose an index // of nums and increment the element at that index by 1. // Return the...
use crate::pathfind::{driving_cost, walking_cost, WalkingNode}; use crate::{ IntersectionID, LaneID, Map, Path, PathConstraints, PathRequest, PathStep, RoadID, TurnID, }; use enumset::EnumSet; use petgraph::graphmap::DiGraphMap; use serde::{Deserialize, Serialize}; use std::collections::BTreeSet; #[derive(Serializ...
#![no_main] #![no_std] use async_embedded::task; use async_stm32f1xx::exti::AsyncPin; use cortex_m_rt::entry; use panic_halt as _; // panic handler use stm32f1xx_hal::{ gpio::{Edge, ExtiPin}, pac::Peripherals, prelude::*, }; #[entry] fn main() -> ! { let dp = Peripherals::take().unwrap(); let mut ...
use pinwheel::prelude::*; #[derive(children, Default, new)] #[new(default)] pub struct Card { pub children: Vec<Node>, } impl Component for Card { fn into_node(self) -> Node { div().class("card").child(self.children).into_node() } }
use std::io::{self, Read}; fn main() -> io::Result<()> { let buffer = readin(); part1(&buffer); part2(&buffer); Ok(()) } fn readin() -> String { let mut buffer = String::new(); let stdin = io::stdin(); let mut handle = stdin.lock(); let _result = handle.read_to_string(&mut buffer); ...
//! This crate provides wrapper for `alert`, `prompt` and `confirm` functions. //! `web-sys` provides a raw API which is hard to use. This crate provides an easy-to-use, //! idiomatic Rust API for these functions. //! //! See the documentation for [`alert`], [`prompt`] and [`confirm`] for more information. use wasm_bi...
#![deny(unused_imports, unused_variables, unused_unsafe, unreachable_patterns)] pub mod call_trace; pub mod metering;
pub mod base; pub mod outbound; pub mod inbound; pub mod parser; pub mod packet;
#![feature(stmt_expr_attributes, proc_macro_hygiene)] fn main() { let a = String::from("hello"); emit::info!("Some text", value: #[emit::as_display] a); }
// Copyright 2020 WHTCORPS 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 writing, sof...
pub fn brackets_are_balanced(string: &str) -> bool { let mut stack = vec![]; for c in string.chars() { if !['[', '{', '(', ']', '}', ')'].iter().any(|i| *i == c) { continue; } if ['[', '{', '('].iter().any(|i| *i == c) { stack.push(c); } else if [']', '}',...
/** * [24] Swap Nodes in Pairs * * Given a linked list, swap every two adjacent nodes and return its head. * * You may not modify the values in the list's nodes, only nodes itself may be changed. * * * * Example: * * * Given 1->2->3->4, you should return the list as 2->1->4->3. * * */ pub struct Soluti...
use std::collections::HashMap; use std::fmt; #[derive(PartialEq, Eq, Hash, Clone, Copy)] pub enum Role { Pawn, Bishop, Knight, Rook, Queen, King } impl fmt::Debug for Role { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { let role = match *self { Role::Pawn =...
use crate::errors::ServerError; use bson::Document; use mongodb::options::UpdateOptions; use mongodb::Collection; use serde::de::DeserializeOwned; use serde::Serialize; use tokio::stream::StreamExt; use warp::Rejection; pub trait WithId { fn get_id(&self) -> &str; } pub struct RepositoryMethods {} impl RepositoryM...
use crate::component::{DirtyTransform, Enabled, Transform, TransformParent}; use specs::{Entities, Join, ReadExpect, ReadStorage, System, WriteStorage}; use specs_hierarchy::Hierarchy; use std::collections::HashMap; pub struct SceneGraphSystem; impl SceneGraphSystem { pub fn new() -> SceneGraphSystem { Sc...
#![allow(clippy::module_name_repetitions)] use crate::actions::PlayerInputAction; use crate::components; use crate::game_data::SurvivalState; use crate::settings::Context; use amethyst::{ core::transform::Transform, ecs::{ Entities, Join, Read, ReadExpect, ReadStorage, Resources, SystemData, Write, Wr...
use anyhow::{Context, Result}; use cli_table::{format::Justify, print_stdout, Cell, Color, Row, RowStruct, Style, Table}; use solo_machine_core::{ ibc::core::ics24_host::identifier::Identifier, model::{AccountOperation, OperationType}, service::BankService, DbPool, Event, Signer, }; use structopt::Struc...
extern crate parity_wasm; extern crate env_logger; extern crate byteorder; #[macro_use] extern crate log; #[macro_use] extern crate lazy_static; pub mod rules; mod optimizer; mod gas; mod symbols; mod logger; mod ext; mod pack; mod nondeterminism_check; mod runtime_type; pub use optimizer::{optimize, Error as Optimi...
pub fn is_begin(ch: &u8) -> bool { *ch == b'^' } pub fn is_repeat(ch: &u8) -> bool{ *ch == b'?' || *ch == b'+' || *ch == b'*' } pub fn is_end(ch: &u8) -> bool{ *ch == b'$' } pub fn is_slash(ch: &u8) -> bool{ *ch == b'\\' } pub fn is_set_begin(ch: &u8) -> boo...
use std::collections::HashMap; use async_trait::async_trait; use reqwest::header::{HeaderName, HeaderValue}; use reqwest::{Method, Url}; use serde::Serialize; use uuid::Uuid; pub use body::{Body, GraphQLBody}; pub use request_type::{GraphQLRequest, Request, RestRequest}; use crate::errors::{PrimaBridgeError, PrimaBr...
fn main() -> () { let mut adapters: Vec<usize> = INPUT .split("\n") .filter(|s| !s.is_empty()) .map(|s| s.parse::<usize>().unwrap()) .collect(); println!("{}", distribution_of_voltages(&mut adapters)); println!("{}", distinct_adapter_arrangements(adapters)); } fn distributio...
use crate::error::argument_type_error; use crate::server::Server; use anyhow::Context; use lua51 as ffi; use lua51::lua_pop; use serde_json::Value; use std::ffi::{CStr, CString}; static mut INITIALIZED: bool = false; static mut SERVER: Option<Server> = None; pub fn init(l: *mut ffi::lua_State) -> Result<(), anyhow::E...
use serde::Deserialize; use std::{ collections::HashSet, marker::PhantomData, sync::{Arc, Mutex}, }; use crate::{ dataflow::{ context::{ParallelTwoInOneOutContext, SetupContext, TwoInOneOutContext}, deadlines::{ConditionContext, DeadlineEvent, DeadlineId}, operator::{OperatorCon...
use crate::owl::node_to_string; use datafrog::Iteration; use fasthash::city; use rdf::graph; use rdf::node::Node; use rdf::triple::Triple; use rdf::uri::Uri; use regex::Regex; //use std::ops::Fn; //use std::rc::Rc; use serde::{Deserialize, Serialize}; use serde_sexpr::{from_str, to_string, Error}; use std::collections:...
use std::{ collections::{HashMap, VecDeque}, io::Write, net::TcpStream, }; const USER_PREFIX: &'static str = "user"; struct Session { stream: TcpStream, } impl Session { pub fn wating(&mut self) { self.stream.write("Wating...".as_bytes()).unwrap(); } pub fn connect(&mut self, oth...
// SPDX-License-Identifier: Apache-2.0 //! errno type and constants for x84_64 // Number values generated with: // // ``` // bindgen /usr/include/errno.h \ // | sed -rn 's|pub const (E[A-Z0-9_]*): u32 = ([0-9]+);|\1 = \2,|p' \ // | sort -g -t= -k2 // ``` // The last 4095 numbers are errrnos. const ERRNO_BASE: u6...
use super::random_checks::Generator as CheckGenerator; use super::CodeGenerator; use crate::ParityCheckMatrix; mod code_constructor; use code_constructor::CodeConstructor; use rand::Rng; pub struct Generator { bit_degree: usize, check_degree: usize, n_layers: u32, initial_block_length: Option<usize>,...
use std::{sync::Arc, time::Duration}; use log::*; use chrono::{DateTime, Utc}; use serenity::model::channel::Reaction; use serenity::model::id::UserId; use serenity::{ async_trait, collector::reaction_collector::ReactionAction, futures::StreamExt, model::{channel::Message as DiscordMessage, gateway::...
#![allow(clippy::from_over_into)] use std::env; use crate::core::UpdateAirtableRecord; use async_trait::async_trait; use chrono::offset::Utc; use chrono::DateTime; use chrono_humanize::HumanTime; use macros::db; use schemars::JsonSchema; use serde::{Deserialize, Serialize}; use serde_json::Value; use slack_chat_api::{...
#![no_std] #[panic_handler] #[cold] fn panic(_panic: &core::panic::PanicInfo) -> ! { unsafe { libc::exit(125) } } #[path = "../../src/of.rs"] mod of; // not strictly necessary, since staticlib items are `no_mangle` functions anyway. pub use of::*;
use crate::config::Config; use crate::ip::IP; enum Service { Timestamps(bool, TimestampType),// (no)? service timestamps Encryption(bool),// (no)? service password-encryption DHCP(bool),// (no)? service dhcp } enum TimestampType { Debug,// debug datetime msec Log,// log datetime msec } impl Servic...
//! Contains utility logic. mod approx_transporation; pub use self::approx_transporation::get_approx_transportation; mod permutations; pub use self::permutations::VariableJobPermutation;
//I hate myself so I inlined this fn is_perfect_square(n: u64) -> bool { match n & 0xF { 0x0 | 0x1 | 0x4 | 0x9 => n == ((n as f64).sqrt().floor() as u64).pow(2), _ => false } } fn is_pentagonal(n: u64) -> bool { let m = 24*n + 1; match m & 0xF { 0x0 | 0x1 | 0x4 | 0x9 => match (m as f64) .sqrt()....
use std::collections::HashMap; pub fn two_sum(nums: Vec<i32>, target: i32) -> Vec<i32> { for i in 0..nums.len() { for j in i + 1..nums.len() { if nums[i] + nums[j] == target { return vec![i as i32, j as i32]; } } } vec![] } pub fn show(nums: Vec<i32>...
use std::net::{Ipv4Addr, SocketAddrV4, SocketAddr}; use std::str::FromStr; use mqtt_rs::executor::v3_client::MqttClient; use mqtt_rs::message::MqttMessageKind; use mqtt_rs::message::v3::MqttMessageV3; use mqtt_rs::session::{ClientSession, MqttSession}; use mqtt_rs::tools::config::ConfigBuilder; #[tokio::main] async fn...
use std::io::{self, Read, Write}; fn read_u8(mut r: impl Read) -> io::Result<u8> { let mut buf = [0 as u8; 1]; r.read_exact(&mut buf)?; Ok(buf[0]) } pub trait VarintRead: Read { fn read_var_u32(&mut self) -> io::Result<u32>; } impl<T: Read> VarintRead for T { fn read_var_u32(&mut self) -> io::Res...
extern crate serde_json; #[derive(Debug)] pub enum Event { PullRequest(PullRequestEvent), Unknown { name: String, payload: serde_json::Value, }, } #[derive(Debug, Deserialize)] #[serde(tag = "action", rename_all = "snake_case")] pub enum PullRequestEvent { Labeled { label: Labe...
use pyo3::prelude::*; use neat_rs::Genotype; use std::time::SystemTime; #[pyclass] struct Network { net: slow_nn::Network } fn sigmoid(x: f64) -> f64 { 1. / (1. + (-x).exp()) } fn tanh(x: f64) -> f64 { x.tanh() } #[pymethods] impl Network { #[new] fn new(path: &str) -> PyResult<Self> { l...
use easy_rss::{RSS_DEFAULT_TITLE_TAG, RSS_DEFAULT_LINK_TAG, RSS_DEFAULT_AUTHOR_TAG, RSS_DEFAULT_DESC_TAG, RSS_DEFAULT_GUID_TAG, RSS_DEFAULT_PUBLISH_TAG}; #[derive(Debug,Clone,PartialEq)] pub enum SaveType{ None, File, Redis, MySQL, } #[derive(Debug,Clone)] pub struct CliConfig{ pub url: String, ...
pub enum WindowType { Editor, Message, } pub struct Window { grid_id: u64, } impl Window { }
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use std::slice; use std::ptr; use std::cell::UnsafeCell; use std::mem::{self, zeroed}; use com_helpers::Com; use ...
use std::io::{Result, Error, ErrorKind}; use iron::prelude::*; use iron::status; use iron::headers::*; use persistent::{Read, State}; use iron_mountrouter::Router; use oatmeal_raisin as or; use urlencoded::UrlEncodedQuery; use models::User; use db::Database; use views::SessionStorageKey; use views::utils::*; use forms:...
#[macro_use] extern crate lazy_static; #[macro_use] extern crate rustler; #[macro_use] extern crate rustler_codegen; extern crate hidapi; use rustler::{Env, Term, Error, Encoder}; use rustler::resource::ResourceArc; mod atoms { rustler_atoms! { atom ok; atom error; //atom __true__ = "true...
#[macro_use] extern crate phoebe; use phoebe::repl::repl; use phoebe::symbol_lookup::make_symbol; use phoebe::types::error::EvaluatorError; #[test] fn throw_an_error() { let mut output = String::new(); let expected_error = format!( "{}\n", EvaluatorError::user( make_symbol(b"some-e...
use crate::decode::Decode; use crate::encode::{Encode, IsNull}; use crate::error::BoxDynError; use crate::types::Type; use crate::{PgArgumentBuffer, PgTypeInfo, PgValueFormat, PgValueRef, Postgres}; use bitflags::bitflags; use std::fmt::{self, Display, Formatter}; use std::io::Write; use std::ops::Deref; use std::str::...
/// A function that adds two numbers pub fn add(a: i32, b: i32) -> i32 { // This line adds two i32's a + b } /// Calculate the n'th fibonacci number pub fn fibonacci(n: i32) -> i32 { match n { 0 => 1, 1 => 1, _ => fibonacci(n - 1) + fibonacci(n - 2), } }
use super::inventory::InventoryActor; use crate::messages; use actix::prelude::*; use actix::{Actor, Handler, StreamHandler}; use actix_web_actors::ws; use dev::{MessageResponse, ResponseChannel}; use serde_json as json; use std::{ collections::HashMap, time::{Duration, Instant}, }; use uuid::Uuid; use ws::Webs...
#![allow(warnings)] use std::alloc::Layout; use std::cell::Cell; use std::cmp; use std::fmt; use std::ops::{Deref, DerefMut}; use std::ptr; use std::rc::Rc; use std::slice; #[derive(Debug)] pub struct Arena { // inner: Rc<Inner>, } /* pub struct Slice<T> { ptr: *mut T, len: usize, _inner: Rc<Inner>, ...
#![deny(rust_2018_compatibility)] #![deny(rust_2018_idioms)] #![deny(warnings)] #![no_main] #![no_std] use linux_io::{Stderr, Stdout}; use panic_exit as _; #[rtfm::app(cores = 2)] const APP: () = { #[idle(core = 0)] fn a(_: a::Context) -> ! { let mut cpu = u32::max_value(); for i in 0..64 { ...
struct Solution; use std::collections::HashSet; impl Solution { fn loud_and_rich(richer: Vec<Vec<i32>>, quiet: Vec<i32>) -> Vec<i32> { let n = quiet.len(); let mut graph: Vec<HashSet<usize>> = vec![HashSet::new(); n]; for e in richer { let u = e[0] as usize; let v = ...
//! binary search fn main() { let mut args = include_str!("bins.txt") .split("\n") .skip(2) .map(rosalind::utils::parse_args::<i32>); let v = args.next().unwrap().collect::<Vec<i32>>(); let searches = args.next().unwrap(); searches.for_each(|q| match v.binary_search(&q) { ...
use uuid::Uuid; pub mod config; pub mod context; pub mod errors; pub mod health; pub mod time_provider; pub fn generate_id() -> String { Uuid::new_v4().to_hyphenated().to_string() }
use amethyst::core::{Result as BundleResult, SystemBundle}; use amethyst::ecs::{Component, DispatcherBuilder}; use amethyst::shred::Resource; use serde::de::DeserializeOwned; use serde::Serialize; use std::collections::HashMap; use std::net::UdpSocket; use std::time::Duration; use systems::*; use type_set::*; use types...
use alloc::{ sync::Arc, task::Wake }; use futures_util::task::AtomicWaker; use core::{ cmp::Ordering, task::Waker }; use crossbeam_queue::ArrayQueue; use super::TaskId; pub(crate) struct TaskWaker { task_id: TaskId, task_queue: Arc<ArrayQueue<TaskId>>, } impl TaskWaker { pub(crate) fn new(...
use crate::schema::drivers; #[derive(Queryable)] pub struct Driver { pub id: i32, pub firstname: String, pub lastname: String, pub enabled: bool, } #[derive(Insertable)] #[table_name = "drivers"] pub struct NewDriver<'a> { pub firstname: &'a str, pub lastname: &'a str, }
//! Generic wrappers over various object file formats. use std::error::Error; use std::fmt; use symbolic_common::{Arch, AsSelf, CodeId, DebugId}; use symbolic_ppdb::PortablePdb; use crate::base::*; use crate::breakpad::*; use crate::dwarf::*; use crate::elf::*; use crate::macho::*; use crate::pdb::*; use crate::pe::...
//! 未完工!
/* * Copyright 2019 Fluence Labs Limited * * 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 a...