text stringlengths 8 4.13M |
|---|
// 17.8 Circus Tower
// Computes DAG, finds longest path. O(n^2) time and space.
use std::collections::HashMap;
type Person = usize;
struct Graph {
can_go_higher: HashMap<Person, Vec<Person>>,
}
impl Graph {
fn add_edge(&mut self, small: Person, big: Person) {
self.can_go_higher
.entry(bi... |
// Copyright 2020 ChainSafe Systems
// SPDX-License-Identifier: Apache-2.0, MIT
use crate::BytesKey;
use address::Address;
use clock::ChainEpoch;
use num_bigint::biguint_ser::{BigUintDe, BigUintSer};
use serde::{Deserialize, Deserializer, Serialize, Serializer};
use vm::{MethodNum, Serialized, TokenAmount};
/// Trans... |
#[multiversion::multiversion(targets("x86_64+avx"), attrs(track_caller, inline(never)))]
#[allow(dead_code)] // this attribute should only be attached to the multiversioned `inner_attrs` function, and none of the function clones
fn inner_attrs() {}
|
pub(in crate::sqlite::transaction::sqlite_tx) mod version_dao;
pub(in crate::sqlite) mod version_metadata_dao;
|
#![allow(dead_code)]
mod analysis;
mod generate;
mod markdown;
mod nhlapi;
mod simulation;
use std::fs::File;
use std::io::prelude::*;
use chrono::{Datelike, Local, NaiveDate, TimeZone};
use failure::Error;
use ordinal::Ordinal;
use serde::{Deserialize, Serialize};
use analysis::{Analyzer, Api};
use generate::Markd... |
#[doc = "Register `RTSR2` reader"]
pub type R = crate::R<RTSR2_SPEC>;
#[doc = "Register `RTSR2` writer"]
pub type W = crate::W<RTSR2_SPEC>;
#[doc = "Field `RT35` reader - Rising trigger event configuration bit of configurable event input x"]
pub type RT35_R = crate::BitReader;
#[doc = "Field `RT35` writer - Rising trig... |
pub fn solve_part_one(input: &str) -> usize {
let mut max = 0;
input
.split('\n')
.filter(|line| line.len() > 0)
.for_each(|pass| {
let seat_id = get_seat_id(pass);
if seat_id > max {
max = seat_id;
}
});
max
}
fn get_sea... |
/*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under both the MIT license found in the
* LICENSE-MIT file in the root directory of this source tree and the Apache
* License, Version 2.0 found in the LICENSE-APACHE file in the root directory
* of this source tree.
*/
#![de... |
#![no_main]
extern crate abxml;
#[macro_use]
extern crate libfuzzer_sys;
use abxml::chunks::TypeSpecWrapper;
use abxml::model::TypeSpec;
fuzz_target!(|data: &[u8]| {
let tsw = TypeSpecWrapper::new(data);
tsw.get_id();
tsw.get_amount();
tsw.get_flag(345235); // Replace with random
});
|
// Definition for singly-linked list.
#[derive(PartialEq, Eq, Clone, Debug)]
pub struct ListNode {
pub val: i32,
pub next: Option<Box<ListNode>>,
}
impl ListNode {
#[inline]
pub fn new(val: i32) -> Self {
ListNode {
next: None,
val,
}
}
}
impl ListNode {
... |
use serde::{Deserialize, Serialize};
use std::fmt::Display;
use crate::config::Config;
#[derive(Debug, Serialize, Deserialize)]
struct Root {
session: Vec<Session>,
}
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct Session {
name: String,
pub windows: Vec<Window>,
}
#[derive(Debug, Serialize,... |
use openssl::ssl::{SslMethod, SslStream, SslContext};
use std::net::TcpStream;
use std::io::{Write, Read, self};
pub enum NetworkStream {
Tcp(TcpStream),
Ssl(SslStream<TcpStream>)
}
impl NetworkStream {
pub fn connect(hostname: &str, use_ssl: bool) -> io::Result<NetworkStream> {
let sock = try!(Tc... |
use ash::{version::DeviceV1_0, vk, Device};
use anyhow::Result;
pub mod color_schemes;
pub use color_schemes::*;
#[derive(Clone, Copy)]
pub struct Texture {
pub image: vk::Image,
pub memory: vk::DeviceMemory,
pub view: vk::ImageView,
pub sampler: Option<vk::Sampler>,
}
impl Texture {
pub fn new... |
use std::cell::Cell;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::ops::Drop;
use std::mem::{transmute_copy, ManuallyDrop};
use role::Role;
use counter::{AtomicCounter, COUNTER_VALID_RANGE};
use buffer::{Buffer, BufRange};
use sequence::{Sequence, Limit, CacheError, CommitError};
pub(crate) trait HeadHalf... |
//! Contains operation expressions.
pub mod elementary;
|
//! Streaming SIMD Extensions 3 (SSE3)
use mem::transmute;
use simd::*;
/// Alternatively add and subtract packed single-precision (32-bit)
/// floating-point elements in `a` to/from packed elements in `b`.
#[inline]
#[target_feature(enable = "sse3")]
pub unsafe fn _mm_addsub_ps(a: f32x4, b: f32x4) -> f32x4 {
tra... |
#![feature(fn_traits)]
use std::{collections::HashMap, env};
mod day1;
mod day2;
mod day3;
mod day4;
mod day5;
mod day6;
mod day7;
mod day8;
fn main() {
let mut daymap: HashMap<String, Box<dyn Fn()>> = HashMap::new();
// boilerplate so each days solution can be called using a command line option
// A ma... |
use mtpng;
use std::fs::File;
use std::io::BufWriter;
use std::path::Path;
use std::time::Instant;
fn main() -> std::io::Result<()> {
let time_start = Instant::now();
let width: usize = 1200;
let height: usize = 800;
let mut header = mtpng::Header::new();
header.set_size(width as u32, height as u... |
use std::ops::*;
use std::fmt;
use std::default::Default;
#[derive(Debug, Copy, Clone)]
pub struct Vec3 {
pub x: f32,
pub y: f32,
pub z: f32
}
impl Vec3 {
#[inline(always)]
pub fn dot(self, other: Vec3) -> f32 {
(self.x*other.x) + (self.y*other.y) + (self.z*other.z)
}
#[inline(alw... |
use lazy_static::*;
use rayon::prelude::*;
use regex::Regex;
use crate::prelude::*;
use crate::system::*;
static PART3_END: u64 = 300;
pub fn write_solution(solution: &Solution) -> Result<()> {
let dir = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
let file = dir.join("contest/solution").join(&solution.filena... |
use serde::{Deserialize, Serialize};
#[derive(Debug, Deserialize)]
pub struct DirectorServerMsg {
pub msg_type: DirectorServerType,
}
#[derive(Debug, Deserialize)]
pub enum DirectorServerType {
Info(Info),
UnresponsivePlayer(String, String),
DisconnectedPlayer(String, String),
ConnectedPlayer(String, String),
G... |
use std::sync::mpsc::{channel, Sender, Receiver };
use messages::Message;
pub struct Coms {
tx: Sender<Message>,
rx: Receiver<Message>,
loopback: Sender<Message>,
}
impl Coms {
pub fn new(send : Sender<Message>) -> Self {
let (tx_to_me, rx) = channel();
Self {
tx : send,
... |
use failure::Error;
use client::{self, Jenkins, Path};
use helpers::Class;
use super::{Job, ShortJob};
use action::CommonAction;
use build::ShortBuild;
use property::CommonProperty;
use queue::ShortQueueItem;
use scm::CommonSCM;
use super::{BallColor, HealthReport, JobBuilder};
job_build_with_common_fields_and_impl... |
extern crate rayon;
use itertools::enumerate;
use matrix_mult::my_ndarray;
use matrix_mult::rayon_mult;
use std::fs::File;
use std::io::Write;
const ITERS: usize = 50;
fn average(numbers: [f64; ITERS as usize]) -> f64 {
numbers.iter().sum::<f64>() / numbers.len() as f64
}
fn median(numbers: [f64; ITERS as usize])... |
pub mod model;
use crate::model::init_db;
#[tokio::main]
pub async fn main() {
fast_log::init(fast_log::Config::new().console()).expect("rbatis init fail");
let rb = init_db().await;
//set pool max size
rb.get_pool().unwrap().resize(100);
println!(">>>>> state={:?}", rb.get_pool().unwrap().status())... |
use std::fmt;
/// Round with two decimal positions
pub fn round(n: f32) -> f32 {
(100.0 * n).round() / 100.0
}
pub fn with_comma_float(n: f32) -> FormatF32 {
FormatF32(n)
}
pub struct FormatF32(f32);
impl fmt::Display for FormatF32 {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let... |
use bindgen;
use cxx_build::CFG;
use std::env;
use std::path::{Path, PathBuf};
fn main() {
println!("cargo:rustc-link-search=/usr/lib");
println!("cargo:rustc-link-lib=static=int2");
// Binding to parts of the C++ API.
//
CFG.exported_header_dirs
.push(Path::new("/usr/include/eigen3"));
... |
mod formatting;
use std::marker::PhantomData;
use formatting::format_struct;
pub trait KeyPart {
fn get_name_pointer(&self) -> *const &'static str;
fn get_bytes_pointer(&self) -> *const &'static [u8];
}
pub trait KeyPartsSequence {
fn get_struct() -> Vec<(*const &'static str, *const &'static [u8])>;
fn fmt... |
pub mod endpoints;
pub mod service;
pub mod utils;
use crate::service::management::ManagementService;
use drogue_cloud_registry_events::sender::KafkaSenderConfig;
use drogue_cloud_service_common::{defaults, health::HealthServerConfig, openid::Authenticator};
use serde::Deserialize;
#[derive(Debug)]
pub struct WebData... |
/**********************************************
> File Name : minOperations.rs
> Author : lunar
> Email : lunar_ubuntu@qq.com
> Created Time : Fri 04 Feb 2022 03:03:45 PM CST
> Location : Shanghai
> Copyright@ https://github.com/xiaoqixian
**********************************************/
str... |
extern crate env_logger;
extern crate hyper;
extern crate hyperdav_server;
use std::path::Path;
fn main() {
env_logger::init().unwrap();
let server = hyper::server::Server::http("0.0.0.0:8080").unwrap();
server
.handle(hyperdav_server::Server::new("", Path::new("/")))
.unwrap();
}
|
use std::fs::File;
use std::collections::HashSet;
use std::io::{BufRead, BufReader};
fn print_map(map : &[u8], height : usize, width: usize, origin : &(usize, usize), actual : &(usize, usize, usize)) {
println!("origin: {:?}, actual: {:?}", origin, actual);
for r in 0..height {
for c in 0..width {
... |
// This file is part of libfringe, a low-level green threading library.
// Copyright (c) Nathan Zadoks <nathan@nathan7.eu>,
// whitequark <whitequark@whitequark.org>
// Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or
// http://apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE... |
use indicatif::{MultiProgress, ProgressBar, ProgressStyle};
use lazy_static::lazy_static;
use std::fmt::Debug;
use std::sync::{Arc, Mutex};
use std::thread;
use std::time::{Duration, SystemTime, UNIX_EPOCH};
#[derive(Clone, Debug)]
struct Rng(u64);
impl Rng {
fn new() -> Self {
let start = SystemTime::now... |
use std::env;
use std::fs::read_dir;
use std::io;
use std::process;
fn main() {
let args: Vec<String> = env::args().collect();
if args.len() < 2 {
eprintln!("{:?}: no arguments", &args[0]);
process::exit(1);
}
for i in 1..args.len() {
if let Err(why) = do_ls(&args[i]) {
... |
pub mod code_ident;
pub mod js_ident;
pub mod java_ident;
pub mod rust_ident;
|
use crate::rtb_type_strict;
rtb_type_strict! {
ContentContext,
Video=1;
Game=2;
Music=3;
Application=4;
Text=5;
Other=6;
Unknown = 7
}
|
mod menu;
mod game;
mod util;
mod input;
extern crate sdl2;
extern crate sdl2_image;
fn main()
{
let sdl2_context = match sdl2::init() {
Err(err) =>
panic!(format!("Error initializing SDL2: {:?}", err)),
Ok(val) => {
println!("SDL2 initialized");
val
}
};
let video_subsystem = ma... |
#[allow(unused_imports)]
use super::util::prelude::*;
use super::super::resource::{BlockTexture, ImageData, LoadFrom};
use super::util::{Pack, PackDepth};
use super::BlockRef;
use js_sys::Promise;
use std::rc::Rc;
use wasm_bindgen::JsCast;
use wasm_bindgen_futures::JsFuture;
pub const CELL_WIDTH: u32 = 256;
pub const... |
extern crate elevator;
extern crate timebomb;
use timebomb::timeout_ms;
#[test]
fn test_main() {
timeout_ms(|| {
elevator::run_simulation();
}, 300000);
}
|
use std::str::FromStr;
use std::error::Error;
use serde::{Deserialize, Serialize};
use serde_json::{Value, Map};
#[derive(Serialize, Deserialize)]
pub struct Config {
pub requests_to_send: u64,
pub method: String,
pub uri: String,
pub headers: Map<String, Value>,
pub body: Value,
}
impl FromStr f... |
mod error;
mod parsers;
use std::{
io::{BufReader, Read},
result::Result,
};
use crate::parsers::plugin::plugin;
use nom::combinator::all_consuming;
pub use crate::{error::Error, parsers::plugin::Plugin};
type IResult<I, T> = nom::IResult<I, T, crate::Error>;
pub fn read_plugin<R>(readable: R) -> Result<P... |
use crate::{
error::{RunnerError, TestResult},
util::{
default_generate, default_runner, default_update, init_singleton_package,
list_input_output, test_existing_directory, TestDesc,
},
TestFamily, TestID, TestToken,
};
use glob::Pattern;
use hashbrown::HashMap;
use std::path::{Path, Pat... |
use crate::metrics::utils::generate_bigrams;
use std::collections::hash_map::Entry::{Occupied, Vacant};
use std::collections::HashMap;
pub fn coefficient(a: &str, b: &str, ignore_case: bool) -> f64 {
if ignore_case {
return coefficient_impl(&a.to_lowercase(), &b.to_lowercase());
}
coefficient_impl(... |
use void::Void;
use util::ConstDefault;
extern {
fn __stack_start(_: Void);
#[link_name = "__start"]
pub fn start();
fn __default_isr_handler();
}
pub const STACK_START: *const Void = __stack_start as *const _;
#[derive(Copy, Clone, PartialEq, Eq, Debug)]
#[allow(raw_pointer_derive)]
pub struct IrqHandler(*con... |
#[doc = "Register `ALRMBSSR` reader"]
pub type R = crate::R<ALRMBSSR_SPEC>;
#[doc = "Register `ALRMBSSR` writer"]
pub type W = crate::W<ALRMBSSR_SPEC>;
#[doc = "Field `SS` reader - Sub seconds value"]
pub type SS_R = crate::FieldReader<u16>;
#[doc = "Field `SS` writer - Sub seconds value"]
pub type SS_W<'a, REG, const ... |
use std::{cell::RefCell, sync::Arc};
#[derive(Default)]
pub struct Engine {
current_reaction: RefCell<Option<Reaction>>,
pub(crate) current_update: RefCell<Option<Update>>,
}
impl Engine {
#[must_use]
pub fn new() -> Self {
Self::default()
}
pub(crate) fn track(&self, subscriptions: &... |
use fltk::{
app,
draw::{
draw_line, draw_point, draw_rectf, set_draw_color, set_line_style, LineStyle, Offscreen,
},
enums::{Color, Event, FrameType},
frame::Frame,
prelude::*,
window::Window,
};
use std::cell::RefCell;
use std::rc::Rc;
const WIDTH: i32 = 800;
const HEIGHT: i32 = 60... |
//! Components for the Ft6206 Touch Panel.
//!
//! Usage
//! -----
//! ```rust
//! let ft6206 = components::ft6206::Ft6206Component::new()
//! .finalize(components::ft6206_i2c_component_helper!(mux_i2c));
//! ```
use capsules::ft6206::Ft6206;
use capsules::virtual_i2c::I2CDevice;
use core::mem::MaybeUninit;
use ker... |
pub mod code_writer;
pub mod parser;
pub mod vmcmd;
use std::env;
use std::fs;
use std::fs::metadata;
use std::fs::File;
use std::io::Write;
use std::path::Path;
use std::path::PathBuf;
use std::process;
pub struct Setup {
pub input : Vec<String>,
pub input_path: String,
pub output : String,
pu... |
extern crate libpasta;
use libpasta::rpassword::*;
use libpasta::HashUpdate;
#[derive(Debug)]
struct User {
// ...
password_hash: String,
}
fn migrate_users(users: &mut [User]) {
// Step 1: Wrap old hash
for user in users {
if let Some(new_hash) = libpasta::migrate_hash(&user.password_hash) {
... |
#![feature(proc_macro_hygiene, decl_macro)]
use rocket::http::{RawStr, Status};
use rocket::request::{self, FromParam, FromRequest};
use rocket::{Outcome, Request, State};
pub mod backend;
pub(crate) mod error;
pub(crate) use error::ErrorKind;
use signed_urls::validate;
#[macro_use]
extern crate failure;
#[macro_us... |
mod board;
mod context;
mod game;
mod getter;
mod message;
pub use self::board::{Board, Cell, MovingDirection};
pub use self::context::Context;
pub use self::game::{Game, State};
pub use self::getter::*;
pub use self::message::{MessageChannel, Msg};
|
#[doc = "Reader of register CM0_CTL"]
pub type R = crate::R<u32, super::CM0_CTL>;
#[doc = "Writer for register CM0_CTL"]
pub type W = crate::W<u32, super::CM0_CTL>;
#[doc = "Register CM0_CTL `reset()`'s with value 0xfa05_0002"]
impl crate::ResetValue for super::CM0_CTL {
type Type = u32;
#[inline(always)]
f... |
use crate::error::IoError;
use core::usize;
type Result<T> = core::result::Result<T, IoError>;
#[derive(Clone, Copy)]
pub enum SeekFrom {
Start(usize),
End(isize),
Current(isize),
}
/// Implementation of loadable asset for buffer-like type
pub struct BufferCursor<T: AsRef<[u8]>> {
data: T,
pos: u... |
//! A definition of `StorageValue` trait and implementations for common types.
use std::borrow::Cow;
use std::mem;
use byteorder::{ByteOrder, BigEndian, LittleEndian};
use crypto::{PublicKey, PUBLIC_KEY_LENGTH};
use messages::{MessageBuffer, RawMessage};
pub trait StorageValue: Sized {
/// Serialize a value i... |
use std::collections::HashMap;
use std::io::Read;
fn main() {
let mut line = String::new();
std::io::stdin().read_to_string(&mut line).unwrap();
let chars = line.chars().collect::<Vec<char>>();
let mut dict = HashMap::new();
for c in chars {
let count = dict.entry(c.to_lowercase().to_stri... |
#![no_std]
#![cfg_attr(
all(feature = "async", feature = "nightly"),
allow(incomplete_features),
feature(async_fn_in_trait, impl_trait_projections)
)]
//! Generic SPI interface for display drivers
#[cfg(all(feature = "async", not(feature = "nightly")))]
extern crate alloc;
#[cfg(feature = "async")]
pub m... |
mod toposort;
use std::error::Error;
use std::{
any::Any,
collections::{HashMap, HashSet},
hash::{Hash, Hasher},
rc::Rc,
};
use toposort::toposort;
use uuid::Uuid;
use vision_traits::{NodeProcessable, NodeProcessingError};
pub struct Connection {
pub output_uuid: Uuid,
pub output_name: String,... |
use amethyst::{
assets::Handle,
ecs::prelude::*,
input::{is_close_requested, is_key_down},
prelude::*,
renderer::VirtualKeyCode,
ui::{UiEventType, UiPrefab},
};
use std::collections::HashMap;
use crate::{states::ToppaState, ToppaGameData};
#[derive(Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]... |
pub type Token = String;
pub type TokenList = Vec<Token>;
pub fn tokenize<'a>(input: &str) -> TokenList {
let mut out = TokenList::new();
out.push(input.to_string());
out = split_on_spaces(out);
out
}
pub fn split_on_spaces<'a>(input: TokenList) -> TokenList {
let mut out = TokenList::new();
... |
use crate::controller::*;
#[cfg(windows)]
use multiinput::*;
use anyhow::{Context, Result};
use log::*;
#[cfg(windows)]
use vigem::{
notification::*,
raw::{LPVOID, PVIGEM_CLIENT, PVIGEM_TARGET, UCHAR},
*,
};
#[cfg(windows)]
unsafe extern "C" fn _handle(
client: PVIGEM_CLIENT,
target: PVIGEM_TARGET... |
use std::{
pin::Pin,
sync::atomic::Ordering,
task::{Context, Poll},
};
use futures_util::{
future::{BoxFuture, FutureExt},
io::{AsyncRead, AsyncReadExt, AsyncWrite},
stream::TryStreamExt,
};
use super::{options::GridFsUploadOptions, Chunk, FilesCollectionDocument, GridFsBucket};
use crate::{
... |
#[macro_use] extern crate log;
extern crate getopts;
extern crate librespot;
extern crate ctrlc;
extern crate env_logger;
use env_logger::LogBuilder;
use std::io::{stderr, Write};
use std::process::exit;
use std::thread;
use std::env;
use std::path::PathBuf;
use std::str::FromStr;
use librespot::spirc::SpircManager;
... |
use hydroflow::hydroflow_syntax;
pub fn main() {
let mut _flow = hydroflow_syntax! {
base = source_iter(vec![1]) -> cycle;
cycle = union()
-> map(|i| i + 1)
-> inspect(|i| println!("{}", i))
-> cycle;
};
// Let's not run this -- it will go fo... |
extern crate num;
use std::cmp;
use std::mem;
fn act2_2_1(yen_cnt_list: &Vec<i32>, target: i32) -> i32 {
let yen_int = [1, 5, 10, 50, 100, 500];
let mut ans = 0;
let mut a = target;
for i in num::range_step(5i32, 0i32, -1) {
println!("{}", i);
let t = cmp::min(a / yen_int[i as usize], yen_cnt_list[i as usize])... |
$NetBSD: patch-src_build__context.rs,v 1.1 2023/08/26 18:20:32 tnn Exp $
Fix wrong python wheel tag on NetBSD/evbarm.
--- src/build_context.rs.orig 2023-08-17 05:08:34.000000000 +0000
+++ src/build_context.rs
@@ -557,6 +557,17 @@ impl BuildContext {
format!("macosx_{x86_64_tag}_x86_64")
... |
// --------------------- //
// INTERNAL DEPENDENCIES //
// --------------------- //
use wasm_bindgen::prelude::*;
#[macro_use]
mod utils {
#[macro_use]
pub mod logging;
pub mod config;
}
// --------------------- //
// PUBLIC MODULES //
// --------------------- //
pub mod shape_renderer;
// -------------... |
/// Assume one value is greater than another value.
///
/// * When true, return `Ok(true)`.
///
/// * Otherwise, return [`Err`] with a message and the values of the
/// expressions with their debug representations.
///
/// # Example
///
/// ```rust
/// # #[macro_use] extern crate assertable; fn main() {
/// let x = a... |
#![warn(
clippy::all,
clippy::nursery,
clippy::pedantic,
missing_copy_implementations,
missing_debug_implementations,
rust_2018_idioms,
unused_qualifications
)]
#![allow(
clippy::doc_markdown,
clippy::enum_glob_use,
clippy::module_name_repetitions,
clippy::must_use_candidate,... |
/*
* Datadog API V1 Collection
*
* Collection of all Datadog Public endpoints.
*
* The version of the OpenAPI document: 1.0
* Contact: support@datadoghq.com
* Generated by: https://openapi-generator.tech
*/
/// AwsAccountCreateResponse : The Response returned by the AWS Create Account call.
#[derive(Clone, ... |
use anyhow::Result;
use bevy_app::{AppBuilder, Plugin};
use bevy_asset::{AddAsset, AssetLoader};
use serde::{de::DeserializeOwned, Serialize};
use std::{
marker::{PhantomData, Send, Sync},
path::Path,
};
use toml::de::from_slice;
/// a struct wrapping a user defined configuration file
pub struct Config<T>(T)
w... |
use crate::storage::sqlite_db::schema::files;
#[derive(Queryable, Insertable, Identifiable)]
#[table_name="files"]
#[primary_key(id)]
pub struct DbFile {
pub id: String,
pub filename: String,
pub last_modified: i64,
}
|
use crate::parser::Error;
use crate::schedule_at;
use crate::time_domain::RuleKind::*;
#[test]
fn empty() -> Result<(), Error> {
assert_eq!(
schedule_at!("", "2020-06-01"),
schedule! { 00,00 => Open => 24,00 }
);
Ok(())
}
#[test]
fn always_open() -> Result<(), Error> {
assert_eq!(
... |
//! A surface contains a set of object that are intented to be displayed.
#[allow(unused_imports)]
use std::collections::HashMap;
use crate::object::*;
use crate::object::text;
use crate::object::text::Text;
/// A position on the surface
pub type Position = (usize, usize);
/// The type of position
#[derive(Debug, C... |
extern crate cgmath;
use cgmath::Vector3;
use cgmath::prelude::*;
extern crate rand;
use rand::Rng;
use std::f64::consts::PI;
use ray::Ray;
#[derive(Copy, Clone, Debug, PartialEq)]
pub struct Camera {
origin: Vector3<f64>,
lower_left: Vector3<f64>,
horizontal: Vector3<f64>,
vertical: Vector3<f64>,
... |
//! Immutable blockchain types with caches (various hashes).
use std::collections::HashSet;
use ckb_occupied_capacity::Result as CapacityResult;
use crate::{
bytes::Bytes,
core::{BlockNumber, Capacity, EpochNumberWithFraction, Version},
packed,
prelude::*,
utilities::merkle_root,
U256,
};
/*... |
use azure_core::AddAsHeader;
use http::request::Builder;
use http::StatusCode;
#[derive(Debug, Clone, PartialEq)]
pub struct ReturnEntity(bool);
impl ReturnEntity {
pub fn new(s: impl Into<bool>) -> Self {
Self(s.into())
}
pub(crate) fn expected_return_code(&self) -> StatusCode {
match se... |
use anyhow::Result;
use std::sync::{Arc, Mutex};
use tokio::sync::mpsc::Receiver;
use tokio::task::JoinHandle;
use tui::widgets::{Block, Borders, List, ListItem};
use uuid::Uuid;
use crate::entity::proto::Parcel;
pub struct Messages {
chat_id: Uuid,
messages: Arc<Mutex<Vec<Parcel>>>,
#[allow(dead_code)]
... |
use serial::SystemPort;
use crate::logger::*;
use crate::json_models::*;
use crate::robust_arduino::*;
use std::io;
pub fn handle_grabber(mut port: &mut SystemPort, payload_string: &str, debug: bool) {
let msg: GrabberEvent = match serde_json::from_str(&payload_string) {
Ok(m) => m,
Err(e) => panic!("Something we... |
use crate::error::ReturnError;
use super::common_entities::TcmbEvdsResult;
/// There is a **'C'** letter at the end of the enum name. This comes from C language. The name means that
/// `ReturnError` for C.
#[derive(Debug)]
#[repr(C)]
pub enum ReturnErrorC {
NoError,
InvalidApiKeyOrBadInternetConnection,
... |
mod types;
use std::fs::read;
use types::Data;
fn main() {
let file_bytes = read("data.toml").unwrap();
let raw_data = String::from_utf8(file_bytes).unwrap();
let data: Data = toml::from_str(&raw_data).unwrap();
println!("{}", data.find_free_slices());
}
|
use playhead::PlayHead;
use std::{thread, time};
#[test]
fn seq(){
let mut ph = PlayHead::new();
ph.play();
let time_one = ph.time();
let delay = time::Duration::from_millis(2000);
thread::sleep(delay);
let time_two = ph.time();
//==========================
ph.pause();
thread:... |
use super::util;
use hyper::{Body, Response};
use std::collections::HashMap;
use std::future::Future;
use std::sync::mpsc;
type Resp<T> = Result<T, Box<dyn std::error::Error + Send + Sync>>;
pub use tokio::task::spawn as async_spawn;
// Todo => hook builder like hyper::Request::builder
#[allow(clippy::implicit_hash... |
#![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 ComponentsResource {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub id: Option<String>,
... |
#[derive(PartialEq, Debug, Clone, Copy)]
pub enum RegisterVal {
EAX, EBX, ECX,
AL, BL, CL,
ESP, EBP
}
#[derive(Debug, PartialEq, Clone, Copy)]
pub enum MachineType {
Long,
Byte,
Chunk(i32), // When something is a chunk of memory of arbitrary size
}
#[derive(PartialEq, Debug, Clone)]
pub enum O... |
//! Applies Static Single Assignment to the `il::ControlFlowGraph`, inserting
//! intermediate blocks with Phi instructions as required.
use error::*;
use graph;
use il;
use il::Variable;
use std::collections::{BTreeMap, BTreeSet, VecDeque};
pub fn ssa(mut control_flow_graph: il::ControlFlowGraph) -> Result<il::Contr... |
macro_rules! primitive_arithmetic {
() => {
fn add(self: Rc<Self>, args: Vec<Variable>, runtime: &mut Runtime) -> FnResult {
let mut result = self.value;
for arg in args {
let value = downcast_var::<Self>(arg).unwrap();
result += value.value;
... |
fn main() {
{
let mut vv1: Vec<i32> = Vec::new();
vv1.push(11);
vv1.push(22);
vv1.push(33);
// 借用传递, 后续正常
// for ii in &vv1 {
// 所有权转移, 后续不能再使用 vv1
for ii in vv1 {
println!("{:?}", ii);
}
println!("{:?}", vv1);
}
}
|
use std::collections::HashMap;
pub type Graph = HashMap<String, Vec<String>>;
pub type VertexId = HashMap<String, usize>;
pub struct NewGraph{
vertices: Vec<String>,
indices: VertexId,
vertive_num: usize,
adj_matrix: Vec<Vec<usize>>,
}
impl NewGraph{
pub fn new(input:Graph)->Self{
let... |
use anyhow::Result;
use chrono::prelude::*;
use clap::{self, value_t};
use advent2020::{bench, solve};
fn get_today_day() -> u32 {
let today = Local::today();
let first_december = NaiveDate::from_ymd(today.year(), 12, 1);
let difference = today.naive_local() - first_december;
(difference.num_days() + ... |
pub use self::reader::{cmd,expression};
peg! reader(r#"
use std::rc::Rc;
use types::{RhType,RhVal};
use types::RhType::*;
#[pub]
expression -> RhVal
= c:cmd a:([ ] args)? {
let mut parsed = Vec::new();
parsed.push(Rc::new(c));
for arg in a.unwrap_or(Vec::new()).iter() {
// Conv... |
pub fn titi() {
println!("titi");
} |
use euclid::{Point2D, Vector2D};
/// How something may be oriented.
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
pub enum Orientation {
/// The points are arranged in a clockwise direction.
Clockwise,
/// The points are arranged in an anti-clockwise direction.
Anticlockwise,
/// The points are coll... |
use dotenv::dotenv;
use std::env;
use store::{store_symbol_prices, SymbolPrices};
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
dotenv().ok();
let api_key = env::var("API_KEY").expect("API_KEY env var must be set");
let symbol = env::var("SYMBOL").expect("SYMBOL env var must b... |
mod btree;
mod fixed_bits;
mod hashbrown;
mod op_iter;
mod small;
mod sorted_vector;
mod sparse;
mod std_set;
pub use self::{fixed_bits::*, hashbrown::*, op_iter::*, small::*, sorted_vector::*, sparse::*};
use core::borrow::Borrow;
use op_iter::{
CartesianProductIter, DifferenceIter, IntersectionIter, SymmetricDif... |
//! This module contains [`RawStyle`] structure, which is analogues to [`Style`] but not generic,
//! so sometimes it can be used more conviently.
use std::collections::HashMap;
use crate::{
grid::{color::AnsiColor, config, config::Borders, config::ColoredConfig, records::Records},
settings::{Color, TableOpti... |
use super::error::Result;
use super::task::{Task, Work};
use serde_yaml;
use std::fs;
use std::path::{Path, PathBuf};
use std::sync::Arc;
use url::Url;
#[derive(Debug, Serialize, Deserialize, PartialEq, Clone)]
pub struct Manifest {
name: String,
#[serde(with = "url_serde")]
url: Url,
main: String,
}
... |
use ggez::{Context};
use ggez::graphics::{MeshBuilder,DrawMode,Color};
use ggez::nalgebra::Point2;
use crate::common::Area;
const SHOTWIDTH: f32 = 5.0;
const SHOTHEIGHT: f32 = 15.0;
const SHOTSPEED: f32 = 8.0;
pub struct Shot {
pub x: f32,
pub y: f32,
pub w: f32,
pub h: f32,
pub s: f32,
}
pub enu... |
fn main() {
let player1 = "bob";
let player2 = "fred";
let player3 = format!("{}:{}", player1, player2);
println!("player3 is : {}", player3);
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.