text stringlengths 8 4.13M |
|---|
//!
//!
//!
use crate::populations::{AdjacentFarms, Cattle, FarmId, HerdSize};
use crate::prelude::*;
#[cfg(feature = "serialize")]
pub fn deserialize_generated_farm_id<'de, D: serde::Deserializer<'de>>(
deserializer: D,
) -> Result<FarmId, D::Error> {
// let n: usize = usize::deserialize(deserializer)?;
l... |
use std::fs;
fn total_mass(size: i32) -> i32 {
let mut needed_fuel = size / 3 - 2;
let mut fuel_sum = 0;
while needed_fuel >= 0 {
fuel_sum += needed_fuel;
needed_fuel = needed_fuel / 3 - 2;
}
fuel_sum
}
fn main() {
let input = fs::read_to_string("input.txt")
.expect(":(... |
use glob::glob;
use metric;
use seahash::SeaHasher;
use source::Source;
use source::internal::report_full_telemetry;
use std::collections::HashMap;
use std::fs;
use std::hash::BuildHasherDefault;
use std::io;
use std::io::prelude::*;
use std::os::unix::fs::MetadataExt;
use std::path::PathBuf;
use std::str;
use std::tim... |
//! This crate provides cross-platform information about batteries.
//!
//! Gives access to a system independent battery state, capacity, charge and voltage values
//! recalculated as necessary to be returned in [SI measurement units](https://www.bipm.org/en/measurement-units/).
//!
//! ## Supported platforms
//!
//! *... |
use openvr::{
compositor::texture::vulkan::Texture as OpenVRVulkanTexture, compositor::texture::ColorSpace,
compositor::texture::Handle, compositor::texture::Texture, compositor::WaitPoses, Compositor,
Eye as OpenVREye, System, TrackedDeviceClass, TrackedDevicePose,
};
use cgmath::{vec4, Matrix4, SquareMat... |
use super::*;
#[inline]
pub fn parse_use(s :&Mem, pivot :usize)->Result<String, &'static str> {
Ok(format!("{}([&](){{\n{}\n}});\n\n",
&verb_parse(&split(&s[pivot].code)[1]),
transpile(s, pivot)
))
} |
#[doc = r"Value read from the register"]
pub struct R {
bits: u32,
}
#[doc = r"Value to write to the register"]
pub struct W {
bits: u32,
}
impl super::CTRL {
#[doc = r"Modifies the contents of the register"]
#[inline(always)]
pub fn modify<F>(&self, f: F)
where
for<'w> F: FnOnce(&R, &'w... |
mod aes;
mod utils;
extern crate openssl;
extern crate base64;
use openssl::symm::{encrypt, Cipher, Crypter, decrypt, Mode};
use std::io::prelude::*;
use std::fs::File;
use utils::*;
fn main() {
let input = base64::decode(lines_from_file("data.txt")[0].as_bytes()).unwrap();
let key = b"YELLOW SUBMARINE";
... |
use druid::{keyboard_types::Key, widget::Controller, Env, Event, EventCtx, Widget};
use std::any::Any;
pub struct EnterController<D> {
callback: Box<dyn Fn(&mut EventCtx, &mut D)>,
}
impl<D> EnterController<D> {
pub fn new(callback: impl Fn(&mut EventCtx, &mut D) + Any) -> Self {
Self {
ca... |
use fraction::ToPrimitive;
use crate::{io::*, gp::*};
//MIDI channels
pub const CHANNEL_DEFAULT_NAMES: [&str; 128] = ["Piano", "Bright Piano", "Electric Grand", "Honky Tonk Piano", "Electric Piano 1", "Electric Piano 2",
"Harpsichord", "Clavinet", "Celesta",
... |
//! Implements a command for uploading dSYM files.
use clap::{App, AppSettings, Arg, ArgMatches};
use failure::Error;
use crate::commands::upload_dif;
use crate::utils::args::{validate_uuid, ArgExt};
pub fn make_app<'a, 'b: 'a>(app: App<'a, 'b>) -> App<'a, 'b> {
app.about("DEPRECATED: Upload Mac debug symbols to ... |
// Copyright 2022 Datafuse Labs.
//
// 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 ... |
use super::*;
/// Asserts that all elements are compatible with themselves and
/// not equal to the other elements
fn assert_distinct_elements(array: &[Tag]) {
let array = array
.iter()
.cloned()
.map(Tag::to_checkable)
.collect::<Vec<CheckableTag>>();
for (index, value) in arr... |
import front.ast;
import std.option;
import std.option.some;
import std.option.none;
type ast_visitor =
rec(fn () -> bool keep_going,
fn () -> bool want_crate_directives,
fn (&ast.crate c) visit_crate_pre,
fn (&ast.crate c) visit_crat... |
use super::{DropdownID, ExampleBox, Model, Msg};
use seed::{prelude::*, *};
use seed_bootstrap::button::Button;
use seed_bootstrap::button_group::ButtonGroup;
use seed_bootstrap::dropdown::{Dropdown, Item};
pub fn view(model: &Model) -> Node<Msg> {
div![
C!["pt-5"],
h1!["Button groups"],
hr... |
#[doc = r"Value read from the register"]
pub struct R {
bits: u8,
}
#[doc = r"Value to write to the register"]
pub struct W {
bits: u8,
}
impl super::TXCSRH7 {
#[doc = r"Modifies the contents of the register"]
#[inline(always)]
pub fn modify<F>(&self, f: F)
where
for<'w> F: FnOnce(&R, &'... |
// Copyright 2019 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//! A portable representation of handle-like objects for fidl.
//! Since this code needs implementation of the fidlhdl_* groups of functions, tests for thi... |
/*!
Example on how to use custom types directly with native windows derive
`cargo run --example subclassing_d --features "flexbox"`
*/
extern crate native_windows_gui as nwg;
extern crate native_windows_derive as nwd;
use nwd::NwgUi;
use nwg::NativeUi;
use nwg::stretch::style::FlexDirection;
type UserButto... |
use std::ops::Add;
use std::ops::Sub;
use std::ops::Mul;
use std::ops::Div;
#[derive(Debug, Copy, Clone)]
pub struct Vector2 {
pub x: f32,
pub y: f32,
}
impl Vector2 {
#![allow(unused)]
pub fn new(x: f32, y: f32) -> Self {
Self {x: x, y: y }
}
pub fn one() -> Self {
Self::new(... |
// Copyright 2021 Datafuse Labs.
//
// 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 ... |
use amethyst::{
assets::{AssetStorage, Handle, Loader, Processor},
core::{Named, Parent, Transform, TransformBundle},
ecs::{
Component, Entity, Join, NullStorage, Read, ReadExpect, ReadStorage, Resources, System,
SystemData, WriteStorage,
},
input::{is_close_requested, is_key_down, I... |
use crate::text_write::{TextWrite, TextWriteError};
use image::imageops::FilterType;
use ordered_float::OrderedFloat;
use crate::intensity::{CharIntensities, Intensity};
fn avg_intensity(image: &image::GrayImage, x1: u32, y1: u32, x2: u32, y2: u32) -> f32 {
let mut s: u32 = 0;
for i in x1..x2 + 1 {
fo... |
fn main() {
let width1 = 30;
let height1 = 50;
println!("Area of rectangle is {}", area1(width1, height1));
let r = (30, 50);
println!("Area of rectangle is {}", area2(r));
let rect = Rectangle { width: 30, height: 50 };
println!("Rectangle is {:#?}", rect);
println!("Area of rectangle... |
//! A driver concretely executes a Falcon IL programs.
use error::*;
use executor::State;
use executor::successor::*;
use il;
use RC;
use types::Architecture;
/// A driver for a concrete executor over Falcon IL.
#[derive(Debug, Clone)]
pub struct Driver<'d> {
program: RC<il::Program>,
location: il::ProgramLoc... |
use crate::prelude::*;
use utilities::prelude::*;
use super::{block::Block, chunk::Chunk, chunk_allocator::ChunkAllocator};
use std::sync::Arc;
pub struct DeviceAllocator {
chunk_allocator: ChunkAllocator,
chunks: Vec<Chunk>,
}
impl DeviceAllocator {
pub fn new(size: VkDeviceSize) -> Self {
Devi... |
use image::{DynamicImage, GenericImageView, Rgba};
use rayon::iter::ParallelBridge;
use rayon::prelude::ParallelIterator;
use std::sync::mpsc::channel;
use serde::*;
use serde_derive::*;
use serde_json::*;
use std::fs::File;
use std::io::Write;
fn main() {
let img = image::open("src/images/trees.jpg").unwrap();
... |
//! 文件相关的内核功能
use super::*;
use core::slice::from_raw_parts_mut;
use core::str;
use core::slice;
use crate::fs::ROOT_INODE;
// 使用条件变量之后,
// 对于线程而言, 读取字符的系统调用是阻塞的, 因为在等待有效输入之前线程都会暂停。
// 对于操作系统而言,等待输入的时间完全分配给了其他线程,所以对于操作系统来说是非阻塞的。
/// 从指定的文件中读取字符
///
/// 如果缓冲区暂无数据,返回 0;出现错误返回 -1
pub(super) fn sys_read(f... |
use super::moves::Move;
#[derive(Debug)]
pub struct Game {
/** The game turns, with `o` move then `x` move. */
pub turns: Vec<(Option<Move>, Option<Move>)>,
}
impl Game {
pub fn make(turns: Vec<(Option<Move>, Option<Move>)>) -> Game {
Game { turns }
}
}
#[derive(Debug)]
pub struct Match {
... |
use crate::scene::error::SceneError;
use std::io;
#[derive(Debug)]
pub enum ConfigError {
YamlError(serde_yaml::Error),
IoError(io::Error),
TobjLoadError(tobj::LoadError),
SceneError(SceneError),
}
impl From<serde_yaml::Error> for ConfigError {
fn from(e: serde_yaml::Error) -> Self {
Confi... |
fn main() { test00(); }
fn test00() {
let r: int = 0;
let sum: int = 0;
let p: port[int] = port();
let c0: chan[int] = chan(p);
let c1: chan[int] = chan(p);
let c2: chan[int] = chan(p);
let c3: chan[int] = chan(p);
let number_of_messages: int = 1000;
let i: int = 0;
while i < ... |
fn main(){
println!("Hello Aurelia !");
} |
// Copyright 2019-2020 PolkaX. Licensed under MIT or Apache-2.0.
#![allow(clippy::or_fun_call, clippy::mut_from_ref)]
mod datastore;
mod error;
#[cfg(test)]
mod tests;
pub mod basic_ds;
pub mod key;
pub mod keytransform;
pub mod namespace;
pub mod query;
pub mod singleton;
// TODO impl mount
// pub mod mount;
pub u... |
use std::collections::HashMap;
/// Returns a HashMap with the the number of times each word appears in text
pub fn word_count(text: &str) -> HashMap<String, u32> {
let mut map_counts: HashMap<String, u32> = HashMap::new();
let not_alphanumeric = |c: char| !c.is_alphanumeric();
for x in text.split(not_alphanumeri... |
#![allow(unused_variables, non_upper_case_globals, non_snake_case, unused_unsafe, non_camel_case_types, dead_code, clippy::all)]
#[repr(transparent)]
#[doc(hidden)]
pub struct ISystemUpdateItem(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for ISystemUpdateItem {
type Vtable = ISystemUp... |
#![allow(non_snake_case, non_camel_case_types, dead_code)]
use libc::*;
use std::mem::{size_of, transmute}; use std::ptr::null_mut;
pub const UNITY_AUDIO_PLUGIN_API_VERSION: usize = 0x010401;
// from macro
pub type UnityAudioDSPResult = c_int;
pub const UNITY_AUDIODSP_OK: UnityAudioDSPResult = 0;
pub const... |
#![allow(unused_variables, non_upper_case_globals, non_snake_case, unused_unsafe, non_camel_case_types, dead_code, clippy::all)]
#[cfg(feature = "Win32_System_Search_Common")]
pub mod Common;
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: def... |
use std::env;
use std::fs;
const SLOPE_X: i32 = 3;
const SLOPE_Y: i32 = 1;
struct Xy {
x: i32,
y: i32
}
struct Slope {
grid_flatten: Vec<bool>,
grid_dim: Xy,
santa: Xy,
delta: Xy,
trees_hit:u16
}
impl Slope {
fn from_lines (lines: &String) -> Slope {
let h = lines.split_white... |
fn main() {
println!("Line one!");
// panic!("Crash n' burn.");
println!("Line two!");
let v = vec![1, 2, 3];
v[99]; // RUST_BACKTRACE=1 cargo run
}
|
mod runner;
pub use runner::*;
|
mod abs;
mod accdist;
mod acos;
mod alma;
mod asin;
mod atan;
mod atr;
mod avg;
mod barstate;
mod bb;
mod bbw;
mod cci;
mod ceil;
mod change;
mod close;
mod cmo;
mod cog;
mod color;
mod correlation;
mod cos;
mod cum;
mod dayofmonth;
mod dayofweek;
mod dev;
mod dmi;
mod ema;
mod exp;
mod falling;
mod fill;
mod fixnan;
m... |
use actix_web::{web};
use actix_web::error::BlockingError;
use diesel::RunQueryDsl;
use diesel::sql_types::BigInt;
use diesel::result::Error;
use crate::config::database::DbPool;
#[derive(QueryableByName, PartialEq, Debug)]
pub struct QueryResult {
#[sql_type="BigInt"]
pub col1: i64,
}
pub async fn ping(pool:... |
use crate::ActionInput;
use game_lib::bevy::{prelude::*, utils::HashMap};
#[derive(Clone, Debug)]
// TODO: once bevy supports reflection for inputs, uncomment this:
// #[derive(Reflect)]
pub struct InputBindings {
pub keyboard: HashMap<KeyCode, ActionInput>,
pub mouse: HashMap<MouseButton, ActionInput>,
}
imp... |
use crate::{controllers::TypedController, math::Size, BoxConstraints};
use crate::{math::Vector2, Backend};
use super::{TypedWidget, Widget};
pub struct Controlled<T, W, C, B: Backend> {
widget: W,
controller: C,
_b: std::marker::PhantomData<B>,
_t: std::marker::PhantomData<T>,
}
impl<T, W, C, B: Bac... |
// Copyright 2018 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//! Custom error types for the netstack.
use failure::Fail;
use net_types::ip::{Ip, IpAddress};
use net_types::MulticastAddress;
use crate::device::Addre... |
// Copyright 2022 Datafuse Labs.
//
// 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 agre... |
use std::path::PathBuf;
use std::io::Result;
use glob::glob;
/// A struct that allows the user to locate a set of files based on configured options.
#[derive(Debug)]
pub struct Collecter<'a> {
queries: &'a Vec<String>,
max_depth: Option<usize>,
}
impl<'a> Collecter<'a> {
/// Creates a new collector that c... |
pub mod common;
use common::server_fixture::ServerFixture;
type Result<T = (), E = Box<dyn std::error::Error>> = std::result::Result<T, E>;
#[tokio::test]
async fn new_server_needs_onboarded() -> Result {
let server_fixture = maybe_skip_integration!(ServerFixture::create_single_use()).await;
let client = serv... |
use std;
use std::io::Read;
use flate2;
use byteorder::ReadBytesExt;
use ::{protocol, Error, Result, Rect};
struct ZlibReader<'a> {
decompressor: flate2::Decompress,
input: &'a [u8]
}
impl<'a> ZlibReader<'a> {
fn new(decompressor: flate2::Decompress, input: &'a [u8]) -> ZlibReader<'a> {
Zli... |
#[doc = "Reader of register MACL3L4C0R"]
pub type R = crate::R<u32, super::MACL3L4C0R>;
#[doc = "Writer for register MACL3L4C0R"]
pub type W = crate::W<u32, super::MACL3L4C0R>;
#[doc = "Register MACL3L4C0R `reset()`'s with value 0"]
impl crate::ResetValue for super::MACL3L4C0R {
type Type = u32;
#[inline(always... |
use std::io;
fn day13a() {
let mut line = String::new();
io::stdin().read_line(&mut line).unwrap();
let arrival_time = line.trim().parse::<u64>().unwrap();
line.clear();
io::stdin().read_line(&mut line).unwrap();
let bus_ids: Vec<_> = line
.trim()
.split(',')
.filter(... |
use crate::virtual_filesystem_core::graph::{NodePointer, Graph};
use crate::virtual_filesystem_core::filesystem::{FileNode, FileNodePointer, FileType, FileObject, Name, Data};
pub fn ls(directory: &FileNodePointer) -> String {
let nodes = &directory.borrow().1;
let mut iter = nodes.iter();
let _ = iter.ne... |
use juniper::GraphQLObject;
#[derive(GraphQLObject)]
struct Object {
__test: String,
}
fn main() {}
|
// Copyright 2022 Datafuse Labs.
//
// 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 ... |
use std::sync::Arc;
use async_graphql::*;
use futures_util::{Stream, StreamExt};
#[tokio::test]
pub async fn test_all_validator() {
struct Query;
#[Object]
#[allow(unreachable_code, unused_variables)]
impl Query {
async fn multiple_of(&self, #[graphql(validator(multiple_of = 10))] n: i32) -> ... |
use std::cmp::{Ord, PartialOrd, Eq, PartialEq, Ordering};
use std::collections::BinaryHeap;
pub enum Node {
Leaf(u8),
Parent { left: Box<Node>, right: Box<Node> },
}
struct NodeFreqPair {
freq: u64,
node: Node,
}
impl PartialEq for NodeFreqPair {
fn eq(&self, other: &NodeFreqPair) -> bool {
... |
static DIRS : [(i32, i32); 8] = [(-1, -1), (0, -1), (1, -1), (-1, 0), (1, 0), (-1, 1), (0, 1), (1, 1)];
fn permute_seats<F>(seats : &Vec<char>, w : usize, h: usize, limit : usize, f : F) -> Vec<char>
where F : Fn(usize, usize) -> usize {
let mut res = seats.clone();
for y in 0..h {
for x in 0..w {
... |
use std::cell::RefCell;
use std::rc::Rc;
use super::action::Action;
use super::action::TypedAction;
use super::action::Action::Flag;
use super::generic::StoreConstAction;
use super::{StoreTrue, StoreFalse};
impl TypedAction<bool> for StoreTrue {
fn bind<'x>(&self, cell: Rc<RefCell<&'x mut bool>>) -> Action<'x> {... |
use minidom::Element;
use std::convert::TryFrom;
use crate::xml::ElementExt;
use crate::Error;
use crate::Point;
#[derive(Debug)]
pub enum Geometry {
Polygon(Vec<Point>),
}
impl<'a> TryFrom<&'a Element> for Geometry {
type Error = Error;
fn try_from(element: &Element) -> Result<Self, Self::Error> {
... |
#![deny(rust_2018_idioms)]
mod chain;
mod felt;
mod hash;
mod serde;
pub use chain::HashChain;
pub use felt::{Felt, HexParseError, OverflowError};
pub use hash::stark_hash;
|
use std::iter::FromIterator;
use proc_macro2::Span;
use syn::punctuated::Punctuated;
use syn::token::{Gt, Lt};
use syn::visit_mut::{self, VisitMut};
use syn::{
GenericArgument, GenericParam, Generics, Lifetime, LifetimeDef, Receiver, TypeReference,
};
pub struct Lifetimes {
pub elided: Vec<Lifetime>,
pub ... |
use crate::backend::c;
use bitflags::bitflags;
bitflags! {
/// `*_OK` constants for use with [`accessat`].
///
/// [`accessat`]: fn.accessat.html
#[repr(transparent)]
#[derive(Copy, Clone, Eq, PartialEq, Hash, Debug)]
pub struct Access: c::c_uint {
/// `R_OK`
const READ_OK = lin... |
use std::net::{TcpListener, TcpStream};
use std::io::{ Write, BufReader, BufRead};
fn handle_connection(mut stream: TcpStream){
let mut s = String::new();
println!("[*] Connection received: {:?}", stream);
let stream_clone = match stream.try_clone(){
Ok(s) => s,
Err(_) => return
};
... |
// Copyright 2018 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... |
use crate::load_function_ptrs;
use crate::prelude::*;
use std::os::raw::c_void;
load_function_ptrs!(DeviceFunctions, {
vkDestroyDevice(device: VkDevice, pAllocator: *const VkAllocationCallbacks) -> (),
vkGetDeviceQueue(
device: VkDevice,
queueFamilyIndex: u32,
queueIndex: u32,
... |
use std::ffi::{CStr, CString};
use std::os::raw::c_char;
use function_parameter::FunctionParameter;
use primitive_result::PrimitiveResult;
use v8facade::{JavaScriptError, Output, V8Facade};
pub mod function_parameter;
pub mod primitive_result;
pub mod v8facade;
#[repr(C)]
#[derive(Debug)]
pub struct Primitive {
... |
use std::io; // io module
fn main() {
let name = "Andrew";
let another_name = "Edcarla";
println!("{} and {}", name, another_name);
let first = "Pascal".to_string();
say_name(&first);
say_name(&first);
// Reading user input
let mut second_name = String::new();
println!("Enter yo... |
use super::Specifier;
use crate::hash::Hash;
use crate::id::ManifestId;
use crate::name::Name;
#[derive(Clone, Debug, Eq, Hash, PartialEq)]
pub struct ManifestSpec {
name: Name,
version: Option<String>,
hash: Option<Hash>,
}
impl ManifestSpec {
pub const fn new(name: Name, version: Option<String>, has... |
// -*- rust -*-
tag clam[T] { signed(int); unsigned(uint); }
fn getclam[T]() -> clam[T] { ret signed[T](42); }
obj impatience[T]() {
fn moreclam() -> clam[T] { be getclam[T](); }
}
fn main() { } |
use lib_package::government::public::power;
fn main() {
power();
}
|
use models::error::RuntimeError;
use std::time::{Duration, Instant};
use tokio::prelude::*;
use tokio_timer::Interval;
pub fn new(
basis: Instant,
interval_millis: u64,
) -> impl Stream<Item = Instant, Error = RuntimeError> {
Interval::new(basis, Duration::from_millis(interval_millis))
.map_err(|e|... |
use crate::opt::ConnectOpts;
use anyhow::{bail, Context};
use console::style;
use remove_dir_all::remove_dir_all;
use sqlx::any::{AnyConnectOptions, AnyKind};
use sqlx::Connection;
use std::collections::{BTreeMap, BTreeSet};
use std::fs::File;
use std::io::{BufReader, BufWriter};
use std::path::{Path, PathBuf};
use std... |
use crate::res::*;
use autopilot::bitmap::*;
use autopilot::geometry::*;
use autopilot::*;
use std::thread::sleep;
use std::time::Duration;
fn stupid_screenshot() -> autopilot::bitmap::Bitmap {
let screen = autopilot::bitmap::capture_screen().expect("Failed to capture screen");
screen.image.save(RES_PATH.join(... |
use solana_program::instruction::InstructionError::Custom;
use solana_sdk::transaction::TransactionError;
use solana_program::{instruction::*, program_pack::Pack, pubkey::Pubkey, system_program, system_instruction, sysvar::rent};
use solana_program_test::*;
use solana_sdk::{
account::Account,
signature::{Keypai... |
#![feature(proc_macro_hygiene, decl_macro)]
#[macro_use]
extern crate rocket;
#[macro_use]
extern crate rocket_contrib;
#[macro_use]
extern crate serde_derive;
mod counter;
mod database;
mod todo;
use counter::Counter;
use database::Db;
use rocket::State;
use rocket_contrib::json::{Json, JsonValue};
use todo::Todo;
... |
use crate::{
rendering::Display,
simulation::{Simulation, Time},
};
#[cfg_attr(feature = "persistence", derive(serde::Deserialize, serde::Serialize))]
pub struct StatApp;
impl StatApp {
pub fn update(&mut self, ctx: &egui::CtxRef, display: &Display, simulation: &Simulation) {
let time = simulation... |
#[cfg(feature = "Win32_Foundation")]
::windows_sys::core::link ! ( "kernel32.dll""system" #[doc = "*Required features: `\"Win32_System_IO\"`, `\"Win32_Foundation\"`*"] fn BindIoCompletionCallback ( filehandle : super::super::Foundation:: HANDLE , function : LPOVERLAPPED_COMPLETION_ROUTINE , flags : u32 ) -> super::supe... |
use structopt::StructOpt;
#[derive(Debug, StructOpt)]
#[structopt(about = "Run the server process for the ACRONYM Week of Code 2021")]
pub struct Arguments
{
/// Reload the map on the server (can take a significant amount of time)
#[structopt(long, short="r")]
pub reload_map: bool,
/// Load the map fr... |
#[doc = "Reader of register FPUIMR"]
pub type R = crate::R<u32, super::FPUIMR>;
#[doc = "Writer for register FPUIMR"]
pub type W = crate::W<u32, super::FPUIMR>;
#[doc = "Register FPUIMR `reset()`'s with value 0x1f"]
impl crate::ResetValue for super::FPUIMR {
type Type = u32;
#[inline(always)]
fn reset_value... |
use crate::erlang::not_1::result;
use crate::test::strategy;
#[test]
fn without_boolean_errors_badarg() {
run!(
|arc_process| strategy::term::is_not_boolean(arc_process.clone()),
|boolean| {
prop_assert_is_not_boolean!(result(boolean), boolean);
Ok(())
},
);
}
... |
use std::process::Command;
#[test]
fn test_no_function() {
let output = Command::new("cargo")
.arg("run")
.arg("tests/script.sh")
.output()
.expect("failed to execute process");
let stdout = String::from_utf8(output.stdout).unwrap();
assert_eq!(output.status.success(), true... |
/// The RetrieveMessageRequest is used for requesting the set of stored messages from neighbouring peer nodes. If a
/// start_time is provided then only messages after the specified time will be sent, otherwise all applicable messages
/// will be sent.
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct StoredMess... |
use super::{PositionIterInternal, PyGenericAlias, PyTupleRef, PyType, PyTypeRef};
use crate::atomic_func;
use crate::common::lock::{
PyMappedRwLockReadGuard, PyMutex, PyRwLock, PyRwLockReadGuard, PyRwLockWriteGuard,
};
use crate::{
class::PyClassImpl,
convert::ToPyObject,
function::{ArgSize, FuncArgs, O... |
use winapi::um::winnt::HANDLE;
use winapi::um::winuser::IMAGE_CURSOR;
use crate::win32::resources_helper as rh;
use crate::{OemCursor, OemImage, NwgError};
use std::ptr;
#[cfg(feature = "embed-resource")]
use super::EmbedResource;
/**
A wrapper over a cursor file (*.cur)
Cursor resources can be used with the `cursor... |
/*
给定一个非空整数数组,除了某个元素只出现一次以外,其余每个元素均出现了三次。找出那个只出现了一次的元素。
说明:
你的算法应该具有线性时间复杂度。 你可以不使用额外空间来实现吗?
示例 1:
输入: [2,2,3,2]
输出: 3
示例 2:
输入: [0,1,0,1,0,1,99]
输出: 99
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/single-number-ii
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
*/
impl Solution {
pub fn single_number(nums: Vec<i3... |
use crate::{commands, Error, Messenger, Result};
use irc::client::prelude::*;
use irc::error::IrcError;
use log::{info, warn};
impl Messenger for IrcClient {
fn init(&self) -> Result<()> {
Ok(self.identify()?)
}
fn run(&self, handler: impl Fn(&str) -> commands::Result<String>) -> Result<()> {
... |
// Copyright 2019 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
// disclaim... |
#[doc = "Reader of register EXTICR2"]
pub type R = crate::R<u32, super::EXTICR2>;
#[doc = "Writer for register EXTICR2"]
pub type W = crate::W<u32, super::EXTICR2>;
#[doc = "Register EXTICR2 `reset()`'s with value 0"]
impl crate::ResetValue for super::EXTICR2 {
type Type = u32;
#[inline(always)]
fn reset_va... |
#[cfg(not(feature = "lib"))]
use std::{cell::RefCell, rc::Rc};
use std::mem;
use mold::{Path, Point};
#[cfg(not(feature = "lib"))]
use crate::{Context, PathId};
#[derive(Debug)]
pub struct PathBuilder {
#[cfg(not(feature = "lib"))]
context: Rc<RefCell<Context>>,
current_path: Path,
end_point: Point<f... |
#![feature(asm)]
#![feature(plugin)]
#![plugin(bytestool)]
#![feature(type_ascription)]
macro_rules! build_const_mesg {
($bstr1:expr, $bstr2:expr) => {{
const LEN1 : usize = byte_size_of!($bstr1);
const LEN2 : usize = byte_size_of!($bstr2);
let result : &[u8; LEN1 + LEN2] = conc... |
use anyhow::{bail,ensure,Context,Result};
use std::path::PathBuf;
use clap::Clap;
use std::fs::File;
use std::io::{stdin,BufRead,BufReader};
struct RpnCalculator(bool);
impl RpnCalculator{
pub fn new(verbose:bool) -> Self{
Self(verbose)
}
pub fn eval(&self,formula: &str)->Result<i32>{
le... |
extern crate bytes;
extern crate iovec;
use bytes::{Buf, BufMut, Bytes, BytesMut};
use bytes::buf::Chain;
use iovec::IoVec;
use std::io::Cursor;
#[test]
fn collect_two_bufs() {
let a = Cursor::new(Bytes::from(&b"hello"[..]));
let b = Cursor::new(Bytes::from(&b"world"[..]));
let res: Vec<u8> = a.chain(b).... |
use crate::{Icon, ResampleError};
use std::{
convert::From,
error::Error,
fmt::{self, Debug, Display, Formatter},
io
};
/// The error type for operations of the `Encode` trait.
pub enum EncodingError<I: Icon + Send + Sync> {
/// The icon family already contains this icon.
AlreadyIncl... |
use std::marker::PhantomData;
use futures::{try_ready, Async, Future, Poll};
use super::{IntoNewService, NewService, Service};
use crate::cell::Cell;
/// Service for the `and_then` combinator, chaining a computation onto the end
/// of another service which completes successfully.
///
/// This is created by the `Ser... |
use std::sync::Arc;
use super::{structure, Error};
use crate::{tokenizer::tag::Tagger, types::*};
use crate::{utils, utils::regex::SerializeRegex};
use lazy_static::lazy_static;
use onig::Regex;
use serde::{Deserialize, Serialize};
pub use structure::{read_disambiguation_rules, read_rules};
use crate::rule::disambig... |
use serde::{Deserialize, Serialize};
use tide::{Body, Request, StatusCode, Error};
use uuid::Uuid;
use std::collections::HashMap;
use std::sync::{Arc, RwLock};
#[derive(Default, Clone)]
struct Store(Arc<RwLock<HashMap<String, Item>>>);
#[derive(Debug, Clone, Serialize)]
struct Item {
id: String,
name: Strin... |
#[doc = r" Value read from the register"]
pub struct R {
bits: u32,
}
#[doc = r" Value to write to the register"]
pub struct W {
bits: u32,
}
impl super::FREQUENCY {
#[doc = r" Modifies the contents of the register"]
#[inline]
pub fn modify<F>(&self, f: F)
where
for<'w> F: FnOnce(&R, &'w... |
#[doc = "Reader of register FDCAN_RXF0S"]
pub type R = crate::R<u32, super::FDCAN_RXF0S>;
#[doc = "Writer for register FDCAN_RXF0S"]
pub type W = crate::W<u32, super::FDCAN_RXF0S>;
#[doc = "Register FDCAN_RXF0S `reset()`'s with value 0"]
impl crate::ResetValue for super::FDCAN_RXF0S {
type Type = u32;
#[inline(... |
extern crate futures;
use futures::prelude::*;
use futures::future::{ok, err};
#[test]
fn smoke() {
let mut counter = 0;
{
let work = ok::<u32, u32>(40).inspect(|val| { counter += *val; });
assert_eq!(work.wait(), Ok(40));
}
assert_eq!(counter, 40);
{
let work = err::<u3... |
use super::VarResult;
use crate::ast::stat_expr_types::VarIndex;
use crate::ast::syntax_type::{FunctionType, FunctionTypes, SimpleSyntaxType, SyntaxType};
use crate::helper::err_msgs::*;
use crate::helper::session::TradeTimeSpan;
use crate::helper::str_replace;
use crate::helper::{
ensure_srcs, move_element, pine_r... |
use crate::cmd::sync;
use crate::config;
use crate::util::{self, color};
use anyhow::Result;
/// Prints any diffs between any remote and local dotfiles.
pub fn diff() -> Result<()> {
let config = config::get_config()?;
let tittle_config_dir = config::tittle_config_dir();
for (remote, local) in config.dests().i... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.