text stringlengths 8 4.13M |
|---|
use std::result;
use std::io;
pub type Result<T> = result::Result<T, Error>;
#[derive(Debug)]
pub enum Error {
MusicContainer(hex_music_container::error::Error),
Database(hex_database::Error),
Io(io::Error),
Ffmpeg(String),
ChannelFailed,
FileNotFound
}
|
pub const TARGET: &str = "127.0.0.1";
// Deployment Management Defaults
pub const DEPLOYMENT_PORT: i32 = 8002;
// Gossip Defaults
pub const GOSSIP_PORT: i32 = 8001;
pub const GOSSIP_INTERVAL: i16 = 500;
pub const GOSSIP_FANOUT: i8 = 3;
// API Defaults
pub const API_PORT: i32 = 8000;
pub fn blank() {}
|
use core::fmt;
use serde::{Deserialize, Serialize};
/// The syntactic shapes that values must match to be passed into a command. You can think of this as the type-checking that occurs when you call a function.
#[derive(Debug, Copy, Clone, Deserialize, Serialize)]
pub enum SyntaxShape {
/// Any syntactic form... |
//!
#![warn(missing_docs)]
#![cfg_attr(feature = "const", feature(const_fn))]
mod raw_int;
pub mod wide_int;
|
pub fn binary_search(nums: &[i32], target: i32) -> Option<usize> {
use std::cmp::Ordering;
let (mut low, mut high) = (0, nums.len());
while low < high {
let mid = low + (high - low) / 2;
match nums[mid].cmp(&target) {
Ordering::Less => low = mid + 1,
Ordering::Equal =... |
#![allow(non_snake_case, non_camel_case_types, non_upper_case_globals, clashing_extern_declarations, clippy::all)]
#[cfg(feature = "Networking_BackgroundTransfer")]
pub mod BackgroundTransfer;
#[cfg(feature = "Networking_Connectivity")]
pub mod Connectivity;
#[cfg(feature = "Networking_NetworkOperators")]
pub mod Netwo... |
use std::cmp::Reverse;
use std::cmp::{max, min};
use std::collections::{HashMap, HashSet, VecDeque};
use itertools::Itertools;
use whiteread::parse_line;
const ten97: usize = 1000_000_007;
fn main() {
let n: usize = parse_line().unwrap();
let s: String = parse_line().unwrap();
let s = s.chars().collect_v... |
#![feature(test)]
#![feature(stdsimd)]
#![feature(mmx_target_feature)]
#![feature(slice_internals)]
extern crate core;
extern crate stdsimd;
extern crate test;
#[macro_use]
extern crate jetscii;
extern crate faster;
extern crate memchr;
extern crate twoway;
#[cfg(test)]
mod bench;
// FIXME: Trying doing this with al... |
// Copyright 2014-2018 Optimal Computing (NZ) Ltd.
// Licensed under the MIT license. See LICENSE for details.
//! # float-cmp
//!
//! WARNING: comparing floating point numbers is very tricky and situation dependent, and
//! best avoided if at all possible. There is no panacea that "just works".
//!
//! float-cmp def... |
use async_std::task;
async fn calc(a: i32, b: i32) -> i32 {
(a + 1) * (a - 1) * b
}
fn main() {
let r = task::block_on(calc(5, 7));
println!("result: {}", r);
}
|
use std::path::Path;
use std::io;
use std::io::Write;
use std::fs::{self, File};
use std::env;
use std::collections::HashMap;
use image::GenericImageView;
use chrono::Datelike;
macro_rules! def_impl {
($name:ident) => {
impl $name {
fn write(&self, mut into: impl io::Write, name: &str) {
... |
use crate::utils::get_fl_name;
use proc_macro::TokenStream;
use quote::*;
use syn::*;
pub fn impl_image_trait(ast: &DeriveInput) -> TokenStream {
let name = &ast.ident;
let name_str = get_fl_name(name.to_string());
let new = Ident::new(format!("{}_{}", name_str, "new").as_str(), name.span());
let draw... |
use clippy_utils::diagnostics::span_lint_and_then;
use clippy_utils::ty::is_type_diagnostic_item;
use clippy_utils::{method_chain_args, return_ty};
use if_chain::if_chain;
use rustc_hir as hir;
use rustc_hir::intravisit::{self, NestedVisitorMap, Visitor};
use rustc_hir::{Expr, ImplItemKind};
use rustc_lint::{LateContex... |
use scheme::LispResult;
use scheme::value::Sexp;
use scheme::error::LispError::*;
use scheme::machine::LispMachine;
pub fn apply_proc(vm: &mut LispMachine, args: &[Sexp]) -> LispResult<Sexp> {
use self::Sexp::*;
let arity = args.len();
if arity < 2 {
return Err(ArityMismatch("apply".to_string(), 2,... |
use crate::types::{Game, Enemy, Object, EnemyData, Vec2};
use crate::util;
impl Game {
pub fn load_level(&mut self, id: u8) -> Vec<Enemy> {
let bytes = self.levels_data[id as usize].clone();
let amount = bytes[0];
let mut result = vec![];
for i in 0..amount as u32 {
... |
use std::iter;
use hdf5;
use crate::board::{BoardState, BitBoard, rank_bb, Direction};
use crate::moves::{Move, MoveMeta, BitPositions, MoveList};
use crate::utils;
pub const WHITE: bool = true;
pub const BLACK: bool = false;
#[derive(hdf5::H5Type, Copy, Clone, PartialEq, Eq, Hash, Debug)]
#[repr(u8)]
pub enum SqOcc... |
/*
* File : command.rs
* Purpose: defines functions which carry out possible user commands
* Program: red
* About : command-line text editor
* Authors: Tommy Lincoln <pajamapants3000@gmail.com>
* License: MIT; See LICENSE!
* Notes : All operation functions have same signature
* Created: 11/05/2016
*/
//! ... |
#![feature(trait_alias)]
use std::ops::Add;
trait Id = Eq + Clone;
trait Quantity = Add<Output = Self> + Clone;
#[derive(Clone, Copy, Debug)]
struct Stock<I, Q> {
id: I,
qty: Q,
}
impl<I: Id, Q: Quantity> Add for Stock<I, Q> {
type Output = Self;
fn add(self, other: Self) -> Self::Output {
... |
use sort;
fn main() {
let vec = sort::generate_random_numbers(1000);
sort::run(&vec);
}
|
use crate::Match;
/// A matcher string that matched during a scan.
#[derive(Debug)]
pub struct YrString<'a> {
/// Name of the string, with the '$'.
pub identifier: &'a str,
/// Matches of the string for the scan.
pub matches: Vec<Match>,
}
|
// 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.
use failure::{format_err, Error};
use fuchsia_syslog::macros::*;
use serde_json::{to_value, Value};
use std::sync::Arc;
// Testing helper methods
use crat... |
use crate::{Section, SectionLayout, GenericObject, DrawCall};
pub struct World {
section_size: f64,
locations: Vec<(i32, i32)>,
sections: Vec<Section>,
general_layout: SectionLayout,
static_objects: Vec<Box<dyn GenericObject>>,
}
// -x = right
// +x = left
// -z = up/away
// +z = down/towards
impl World {
... |
use std::fs;
use std::cmp::min;
use std::time::Instant;
use std::collections::BTreeSet;
fn optimized_solution_part1(numbers: Vec<u16>) -> () {
let (mut low, high): (Vec<u16>, Vec<u16>) = numbers.iter().partition(|&&x| x <= (2020 / 2));
let mut n: usize = min(low.len(), high.len());
if n == 0 {
asse... |
use ndarray::{arr2, Array2};
use num_complex::{Complex, Complex32};
/// Representation of a quantum gate.
#[derive(Clone, Debug, PartialEq)]
pub struct Gate {
pub inner: Array2<Complex32>,
}
impl Gate {
/// Produces the Identity gate.
pub fn identity() -> Self {
let matrix = arr2(&[
[C... |
use std::fs::File;
use std::io::prelude::*;
use std::path::Path;
type ButtonLine = (u8, u8, u8);
const BUTTONS: [[char; 3]; 3] = [['1', '2', '3'], ['4', '5', '6'], ['7', '8', '9']];
const EXTENDED_BUTTONS: [[char; 5]; 5] = [['0', '0', '1', '0', '0'],
['0', '2', '3', '4', '0... |
// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT.
pub fn parse_http_generic_error(
response: &http::Response<bytes::Bytes>,
) -> Result<smithy_types::Error, smithy_json::deserialize::Error> {
crate::json_errors::parse_generic_error(response.body(), response.headers())
}
pub fn de... |
#![allow(non_snake_case, non_camel_case_types, non_upper_case_globals, clashing_extern_declarations, clippy::all)]
#[link(name = "windows")]
extern "system" {}
#[repr(transparent)]
pub struct ContentAccessRestrictionLevel(pub i32);
impl ContentAccessRestrictionLevel {
pub const Allow: Self = Self(0i32);
pub con... |
use std::collections::VecDeque;
use std::iter::FromIterator;
fn crab_cups(cups: &mut VecDeque<i32>, rounds: i32) {
let min_label: i32 = *cups.iter().min().unwrap();
let max_label: i32 = *cups.iter().max().unwrap();
let next_destination_label = |destination_label: i32| -> i32 {
let mut next = dest... |
use proconio::{input, marker::Usize1};
fn main() {
input! {
n: usize,
a: [Usize1; n * 3],
};
let mut pos = vec![vec![]; n];
for i in 0..(n * 3) {
pos[a[i]].push(i);
}
let mut ans = (0..n).collect::<Vec<_>>();
ans.sort_by_key(|&i| pos[i][1]);
for i in 0..n {
... |
use crate::prelude::*;
#[repr(C)]
#[derive(Debug)]
pub struct VkSparseMemoryBind {
pub resourceOffset: VkDeviceSize,
pub size: VkDeviceSize,
pub memory: VkDeviceMemory,
pub memoryOffset: VkDeviceSize,
pub flags: VkSparseMemoryBindFlagBits,
}
|
use proconio::input;
fn main() {
input! {
n: usize,
x: usize,
ab: [(usize, usize); n],
};
let mut dp = vec![false; x + 1];
dp[0] = true;
for (a, b) in ab {
for y in (0..x).rev() {
for c in (a..=(a*b)).step_by(a) {
if y + c <= x {
... |
// use std::{thread, time};
//take experssion, gather exponents, if exponent 2 has an expression, not function
//types of equations
// Quadratic Equation
// Linear Equation
// Radical Equation
// Exponential Equation
// Rational Equation
//term
// #[derive(Debug)]
struct Equation {
equation: String,
isfunc: boo... |
use crate::{ import::*, WsErr, WsErrKind, WsState, WsIo, WsEvent, CloseEvent, notify };
/// The meta data related to a websocket.
///
/// Most of the methods on this type directly map to the web API. For more documentation, check the
/// [MDN WebSocket documentation](https://developer.mozilla.org/en-US/docs/Web/API/W... |
use std::collections::BTreeMap;
use rustc_serialize::json::{Json,ToJson};
use parse::*;
use types::Date;
make_prop_type!(FilterOperator, "FilterOperator",
operator: String => "operator",
conditions: Vec<Filter> => "conditions"
);
make_prop_type!(FilterCondition, "FilterCondition",
in_mailboxes: ... |
//! ECDSA signing key
use super::{CurveAlg, Signature, VerifyingKey};
use crate::signature::{Error, Keypair, Signer};
use ::ecdsa::{
elliptic_curve::{sec1, FieldBytesSize},
SignatureSize,
};
use core::marker::PhantomData;
use generic_array::ArrayLength;
use pkcs8::DecodePrivateKey;
use ring::{
self,
ra... |
//! Configuration directory path helpers.
use directories::ProjectDirs;
use serde::Deserialize;
use serde_yaml::Value;
use std::fs::{create_dir_all, File};
use std::io::prelude::*;
use std::path::PathBuf;
use crate::error::AppError;
/// Returns the path of a file/pattern inside the configuration directory.
pub fn get... |
#![feature(test)]
extern crate test;
use test::Bencher;
use coruscant_nbt::{to_gzip_writer, to_writer, Compression};
use serde::Serialize;
use std::collections::HashMap;
#[derive(Serialize)]
#[serde(rename = "wrap")]
struct Wrap {
#[serde(rename = "inner")]
inner: Inner,
}
#[derive(Serialize)]
struct Inner {... |
use glob::PatternError;
use std::fmt::{Display, Formatter, Result};
use std::path::PathBuf;
pub use error_chain::ChainedError;
pub use lalrpop_util::ParseError;
pub use crate::ast::ErrorKind;
use crate::connection::{ConnectionError, ConnectionErrorKind};
pub use crate::model::ValidationKind;
use crate::sql::lexer;
e... |
//! Synopsys DesignWare ABP UART
use static_assertions::{assert_eq_align, assert_eq_size, const_assert_eq};
register! {
ReceiveHolding,
u32,
RO,
Fields [
Data WIDTH(U8) OFFSET(U0),
]
}
register! {
TransmitHolding,
u32,
WO,
Fields [
Data WIDTH(U8) OFFSET(U0),
]
... |
use bytesize::ByteSize;
use chrono::{DateTime, Local};
use chrono_humanize::HumanTime;
use crate::error::Error;
use std::fs::DirEntry;
#[cfg(not(target_os = "windows"))]
use std::os::unix::ffi::OsStrExt;
use url::percent_encoding;
#[cfg(target_os = "windows")]
use OsStrExt;
#[derive(Debug)]
pub struct ShareEntry {
... |
#![allow(unused_variables, non_upper_case_globals, non_snake_case, unused_unsafe, non_camel_case_types, dead_code, clippy::all)]
pub const AUTO_WIDTH: i32 = -1i32;
#[repr(transparent)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)]
pub struct AppEvents(p... |
use glam::*;
use itertools::Itertools;
use std::collections::VecDeque;
pub type Point2 = Vec2;
type Vector2 = Vec2;
//Star class taken from table at
//https://de.wikipedia.org/wiki/Klassifizierung_der_Sterne
const CLASS_O: f32 = 60.0;
const CLASS_B: f32 = 18.0;
const CLASS_A: f32 = 3.2;
const CLASS_F: f32 = 1.7;
cons... |
use crate::measure;
use std::collections::VecDeque;
use std::io::BufRead;
pub fn run(input: impl BufRead) {
let monkeys = read_monkeys(input);
measure::duration(|| {
let mut monkeys = monkeys.clone();
println!("* Part 1: {}", play_keep_away(&mut monkeys, 20, |w| w / 3));
});
measure::... |
// Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
//
use std::collections::{HashMap, HashSet};
use serde_derive::{Deserialize, Serialize};
use gltf::json::mesh::Primitive;
use super::KHR_MATERIALS_VARIANTS;
use crate::{Result, Tag};
#[derive(Clone, Debug, Default, Deserialize, Serialize)]
pub... |
/// Biz logic for the RealWorld backend API
///
/// See the [RealWorld API Spec](https://github.com/gothinkster/realworld/tree/master/api) for
/// more information on the API
pub mod api;
/// Database models and connectors
pub mod db;
|
use e2d2::headers::*;
use e2d2::operators::*;
use e2d2::scheduler::*;
use e2d2::utils::*;
use fnv::FnvHasher;
use std::collections::HashMap;
use std::convert::From;
use std::hash::BuildHasherDefault;
use std::net::Ipv4Addr;
#[derive(Clone, Default)]
struct Unit;
#[derive(Clone, Copy, Default)]
struct FlowUsed {
pu... |
use std::collections::BTreeMap;
use std::cell::RefCell;
use std::rc::Rc;
use scheme::value::Sexp;
type Env = BTreeMap<String, Rc<RefCell<Sexp>>>;
#[derive(Debug, Clone, PartialEq)]
pub struct Environment {
env: Rc<RefCell<Env>>,
up: Option<Rc<Environment>>,
}
impl Environment {
pub fn new(up: Option<Rc... |
fn double(x: i32) -> i32 {
x * 2
}
fn main() {
let a = 6;
let _a = double(a);
println!("{}, {}", a, _a);
}
|
use core::ops::{Add, AddAssign, Neg, Sub};
pub mod axis_order;
pub mod measurement;
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Position {
pub x: i32,
pub y: i32,
}
impl Add<Position> for Position {
type Output = Position;
fn add(self, rhs: Position) -> Self::Output {
Position {
... |
use std::str::FromStr;
use uuid::Uuid;
use crate::decode::Decode;
use crate::encode::Encode;
use crate::postgres::protocol::TypeId;
use crate::postgres::value::{PgData, PgValue};
use crate::postgres::{PgRawBuffer, PgTypeInfo, Postgres};
use crate::types::Type;
impl Type<Postgres> for Uuid {
fn type_info() -> PgT... |
use geometry::Point;
use geometry::{Collide};
use geometry::Position;
pub struct Mouse {
pub point: Point,
}
impl Mouse{
/// Create a enemy with the given vector
pub fn new(x: f64, y: f64) -> Mouse {
Mouse {
point: Point::new(x, y)
}
}
}
impl Collide for Mouse {
fn rad... |
pub(crate) mod systems;
mod entity;
mod plugin;
pub use entity::*;
pub use plugin::*;
game_lib::fix_bevy_derive!(game_lib::bevy);
|
#[macro_use]
extern crate failure;
use failure::Fail;
fn return_failure() -> Result<(), failure::Error> {
#[derive(Fail, Debug)]
#[fail(display = "my error")]
struct MyError;
let err = MyError;
Err(err.into())
}
fn return_error() -> Result<(), Box<std::error::Error>> {
return_failure()?;
... |
/*!
This module is concerned with how `cargo-eval` extracts the manfiest from a script file.
*/
use std::collections::HashMap;
use std::path::Path;
use pulldown_cmark::{CodeBlockKind, Event, Options, Parser, Tag};
use regex::Regex;
use crate::error::{Blame, Result};
use crate::templates;
use crate::Input;
lazy_stati... |
/// Packed deltas within a Tuple Variation Store
use otspec::types::*;
use otspec::{read_field, read_field_counted, stateful_deserializer};
use serde::de::DeserializeSeed;
use serde::de::SeqAccess;
use serde::de::Visitor;
use serde::ser::SerializeSeq;
use serde::{Serialize, Serializer};
/// An array of packed deltas
/... |
// 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.
use crate::message::{Message, MessageReturn};
use crate::node::Node;
use crate::types::Celsius;
use async_trait::async_trait;
use failure::{format_err, Err... |
pub mod peer_messages;
pub mod trackers;
pub mod peer_protocol;
pub mod metainfo_files; |
// Copyright 2013 The Servo Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution.
//
// 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 http://opensource.org/licenses/MIT>, at ... |
use alloc::{ collections::VecDeque, sync::Arc };
use spin::Mutex;
use crate::process;
use crate::sync::condvar::*;
use lazy_static::*;
pub struct Stdin {
// 字符队列
buf: Mutex<VecDeque<char>>,
// 条件变量
pushed: Condvar,
}
impl Stdin {
pub fn new() -> Self {
Stdin {
buf: Mutex::new(V... |
use pest::iterators::{Pair};
use template::{ComponentTemplate, TemplateAttribute, TemplateValue};
#[derive(Parser)]
#[grammar = "template/language.pest"]
pub struct TemplateParser;
pub fn parse_document(document_pair: Pair<Rule>) -> Result<Vec<ComponentTemplate>, String> {
assert_eq!(document_pair.as_rule(), Rul... |
use std::path::Path;
use std::sync::{mpsc, Arc, Mutex};
use std::time::Duration;
use getch_rs::{Getch, Key};
use crate::repl;
use crate::flag;
use crate::setting;
pub async fn run(
port_name: String,
baud_rate: u32,
mut flags: flag::Flags,
params: Option<setting::Params>,
){
let receiver = ser... |
use shipyard::*;
use shipyard_scenegraph::init::init_scenegraph;
use crate::mainloop::UpdateTick;
use crate::renderer::{SceneRenderer, item::*};
use shipyard_scenegraph::prelude::*;
use crate::controller::{queue::InputQueue, Controller, controller_set_sys, controller_process_sys, controller_clear_sys};
use crate::rende... |
use std::{collections::HashSet, string::String, vec::Vec};
use unicode_segmentation::UnicodeSegmentation;
use rand::{distributions::Alphanumeric, Rng};
pub struct StringUtils {}
impl StringUtils {
pub fn replace_default(s: &str) -> String {
let s = s.replace(
&[
'(', ')', '-', ... |
// 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::error;
use fat;
pub fn detail_file(args: &[String])
-> Result<(), Box<error::Error>>
{
expect_args!(args, 2);
let image_fn = args[0].clone();
let image = fat::Image::from_file(image_fn)?;
let file_metadata = image.get_file_entry(args[1].clone())?;
println!("{:#?}", file_metadata);
... |
// xfail-pretty
import rusti::ivec_len;
native "rust-intrinsic" mod rusti {
fn ivec_len[T](v: &T[]) -> uint;
}
fn main() {
let v: int[] = ~[];
assert (ivec_len(v) == 0u); // zero-length
let x = ~[1, 2];
assert (ivec_len(x) == 2u); // on stack
let y = ~[1, 2, 3, 4, 5];
assert (ivec_len(y) ... |
use crate::{Extent3D, Origin3D};
use ash::vk;
pub fn has_zero_or_one_bits(bits: u32) -> bool {
let bits = bits as i32;
bits & (bits - 1) == 0
}
pub fn extent_3d(extent: Extent3D) -> vk::Extent3D {
vk::Extent3D {
width: extent.width,
height: extent.height,
depth: extent.depth,
}... |
use std::{collections::VecDeque, fmt::Display};
use data_types::{CompactionLevel, ParquetFile};
use crate::file_group::{split_by_level, FilesTimeRange};
use super::FilesSplit;
#[derive(Debug)]
/// Split files into `[compact_files]` and `[non_overlapping_files]`
/// To have better and efficient compaction performan... |
use id::Id;
/// Contains additional information about a zone, like what kind of zone it is.
#[derive(Debug, Clone)]
pub enum ZoneDetails {
Battlefield,
Hand {
player_id: Id,
},
}
/// Represents a single zone in the game.
#[derive(Debug, Clone)]
pub struct Zone {
pub id: Id,
pub details: Zo... |
fn main() {
let stdin = std::io::stdin();
let mut rd = ProconReader::new(stdin.lock());
let x: String = rd.get();
let x: Vec<u64> = x.bytes().map(|b| (b - b'0') as u64).collect();
let m: u64 = rd.get();
if x.len() == 1 {
if x[0] <= m {
println!("1");
} else {
... |
#[doc = "Reader of register HWCFGR2"]
pub type R = crate::R<u32, super::HWCFGR2>;
#[doc = "Reader of field `PTIONREG_OUT`"]
pub type PTIONREG_OUT_R = crate::R<u8, u8>;
#[doc = "Reader of field `TRUST_ZONE`"]
pub type TRUST_ZONE_R = crate::R<u8, u8>;
impl R {
#[doc = "Bits 0:7 - PTIONREG_OUT"]
#[inline(always)]
... |
//! Provides types and functionality for [Relationships](https://discord.com/developers/docs/game-sdk/relationships)
pub mod events;
pub mod state;
use crate::{user::User, Error};
use serde::Deserialize;
#[derive(Copy, Clone, Debug, PartialEq, serde_repr::Deserialize_repr)]
#[repr(u8)]
pub enum RelationKind {
//... |
use std::cmp;
/*
https://leetcode.com/problems/maximal-square/
*/
struct Solution;
impl Solution {
pub fn maximal_square(matrix: Vec<Vec<char>>) -> i32 {
let rows = matrix.len();
let cols = matrix[0].len();
let mut dp = vec![vec![0; cols + 1]; rows + 1];
let mut max_len: i32 = ... |
use std::io;
use std::io::Write;
extern crate chrono;
use chrono::prelude::*;
fn main() {
let name = input(("What is your name? ").to_string());
let age = input(format!("How old are you, {}? ", name))
.parse().expect("Failed converting age to number");
let centennial_year = calculate_year_of_cent... |
use crate::raw::{FidlType, Spanned};
use std::collections::HashMap;
lazy_static! {
pub static ref BUILTIN_SCHEMAS: HashMap<String, AttributeSchema> = {
let mut builtins = HashMap::new();
builtins.insert(
"Discoverable".to_string(),
AttributeSchema {
placement... |
use std::iter;
use crate::ast;
use crate::error::ParseError;
use crate::grammar;
use crate::lexer;
use crate::token;
pub struct Parser {
inner: grammar::FileInputParser,
}
impl Default for Parser {
fn default() -> Self {
Self {
inner: grammar::FileInputParser::new(),
}
}
}
im... |
use raw_window_handle::HasRawWindowHandle;
use wgpu::TextureViewDescriptor;
use crate::render::render_target::{RenderScene, RenderTarget};
use super::triangles::TriangleScene;
pub struct WgpuRenderTarget {
device: wgpu::Device,
sc_desc: wgpu::SurfaceConfiguration,
swapchain_format: wgpu::TextureFormat,
... |
use crate::exchange::requests::{Order, OrderStatus};
use crate::exchange::filled::Trade;
use std::collections::HashMap;
use postgres::Client;
use crate::database;
use chrono::{DateTime, Utc};
use redis::{Commands, RedisError};
use crate::buffer::BufferCollection;
// Error types for authentication
pub enum AuthErro... |
pub mod state_trait_objects;
pub mod state_type_encoded;
use state_trait_objects::run as t_obj_run;
use state_type_encoded::run as type_enc_run;
fn main() {
t_obj_run();
type_enc_run();
} |
// -*- rust -*-
use std;
import std::str;
#[test]
fn test() {
let s = "hello";
let sb = str::buf(s);
let s_cstr = str::str_from_cstr(sb);
assert (str::eq(s_cstr, s));
let s_buf = str::str_from_buf(sb, 5u);
assert (str::eq(s_buf, s));
} |
use connection::IMAPConnection;
use imaperror::IMAPError;
use response::{Response, parse_responses};
use validate_helpers::*;
use mailbox::{Mailbox, ReadOnly};
use rand::thread_rng;
use rand::Rng;
use std::fmt;
use std::mem;
use std::ptr;
#[derive(Debug)]
pub struct Tag {
tag_prefix: String,
tag: u32,
}
#[der... |
use crate::read_prefs::pobierz_ustawienia;
//use rocket::http::ext::IntoCollection;
//use std::borrow::Borrow;
use crate::web::struktura_chat::MessageChat;
//use std::sync::Mutex;
use crate::dbus::{Gracz, dbus_get_online_players};
pub fn _wypelnij_game_params_icons() -> String {
let mut wyjscie = String::new();
... |
use failure::{bail, ensure, err_msg, Error, ResultExt};
use ffmpeg::frame::Video as VideoFrame;
use ffmpeg::{format, Rational};
use lazy_static::lazy_static;
use std::ops::Deref;
use std::result;
use std::sync::mpsc::{channel, Receiver, Sender, TryRecvError};
use std::sync::{Mutex, Once, RwLock, ONCE_INIT};
use std::th... |
use std::convert::TryInto;
use admin_controlled::{AdminControlled, Mask};
use near_contract_standards::fungible_token::metadata::FungibleTokenMetadata;
use near_contract_standards::storage_management::StorageBalance;
use near_sdk::borsh::{self, BorshDeserialize, BorshSerialize};
use near_sdk::collections::UnorderedSet... |
fn main() {
println!("🔓 Challenge 5");
println!("Try running: `cargo test repeating_xor`");
println!("Code in 'xor/src/lib.rs'");
}
|
use crate::structures::basic::ValType;
#[derive(Debug)]
pub struct FuncType {
inputs: Vec<ValType>,
outputs: Vec<ValType>,
}
impl FuncType {
pub fn from_reader() {
println!("This is func type...");
}
}
#[derive(Debug)]
pub struct ResultType;
#[derive(Debug)]
pub struct Func {}
#[derive(Debu... |
pub struct Variable<'a, T> where T: PartialEq {
value: T,
listeners: Vec<Box<FnMut(&T) + 'a>>,
}
impl<'a, T> Variable<'a, T> where T: PartialEq {
pub fn new(value: T) -> Variable<'a, T> {
Variable { value, listeners: Vec::new() }
}
pub fn add_listener<L>(&mut self, listener: L) where L: FnMut(&T) + 'a {... |
// Copyright (C) 2019 Frank Rehberger
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0>
// declared in Cargo.toml as "[build-dependencies]"
extern crate build_deps;
fn main() {
// Enumerate files in sub-folder "res/*", being relevant for the te... |
use crate::simulation::trader_behavior;
use crate::order::{Order};
use crate::simulation::trader::Traders;
use crate::exchange::order_processing::JsonOrder;
use crate::controller::Task;
use crate::io::tcp_json;
use crate::io::ws_json;
use crate::utility::get_time;
use std::sync::Arc;
use std::thread;
pub struct Rand... |
//! DLT (direct linear transform) algorithm for camera calibration
//!
//! This is typically used for calibrating cameras and requires a minimum of 6
//! corresponding pairs of 2D and 3D locations.
//!
//! # Testing
//!
//! ## Unit tests
//!
//! To run the unit tests:
//!
//! ```text
//! cargo test
//! ```
//!
//! ## T... |
extern crate gdbs;
#[macro_use]
extern crate clap;
use std::process;
use clap::{App, Arg};
fn main() {
let app = App::new(crate_name!())
.version(crate_version!())
.author(crate_authors!())
.about(crate_description!())
.arg(Arg::with_name("type")
.help("peda, gef, pwn... |
table! {
entries (id) {
id -> Int4,
pc_name -> Text,
cpu_usage -> Text,
mem_usage -> Text,
recorded_at -> Int8,
}
}
|
#![crate_name = "gfx_gl"]
#![crate_type = "lib"]
//! An OpenGL loader generated by [gl-rs](https://github.com/brendanzab/gl-rs).
//!
//! This is useful for directly accessing the underlying OpenGL API via the
//! `GlDevice::with_gl` method. It is also used internally by the `GlDevice`
//! implementation.
include!(con... |
extern crate regex;
macro_rules! mal_regex {
($re:expr) => {
Regex::new($re).unwrap()
};
}
#[macro_use]
extern crate log;
#[macro_use]
extern crate lazy_static;
pub mod core;
pub mod env;
pub mod printer;
pub mod reader;
pub mod types;
pub mod readline {
use std::io;
use std::io::Write;
... |
extern crate chrono;
use self::chrono::prelude::{DateTime, Utc};
use std::cell::Cell;
use direction::Direction;
use signal::Signal;
use signal::detector::{DetectSignal, DetectSignalError};
use symbol::SymbolId;
pub struct Once {
symbol_id: SymbolId,
direction: Direction,
detected: Cell<bool>
}
impl Once {... |
//! Utility functions for cpu efficient `wait` commands.
//! Uses the `libc::epoll_wait` that only works on linux systems.
#[cfg(target_os = "linux")]
use libc;
use std::os::unix::io::RawFd;
use std::time::{Duration, Instant};
/// Wait for until a condition `cond` is `true` or the `timeout` is reached.
/// If the `ti... |
//
// Local control plane.
//
// Can start, configure and stop postgres instances running as a local processes.
//
// Intended to be used in integration tests and in CLI tools for
// local installations.
//
use anyhow::{anyhow, bail, Context, Result};
use std::fs;
use std::path::Path;
pub mod compute;
pub mod local_en... |
#[doc = "Reader of register HB8CFG"]
pub type R = crate::R<u32, super::HB8CFG>;
#[doc = "Writer for register HB8CFG"]
pub type W = crate::W<u32, super::HB8CFG>;
#[doc = "Register HB8CFG `reset()`'s with value 0"]
impl crate::ResetValue for super::HB8CFG {
type Type = u32;
#[inline(always)]
fn reset_value() ... |
use std::cmp::{max, min};
use std::collections::{HashMap, HashSet};
use itertools::Itertools;
use whiteread::parse_line;
const ten97: usize = 1000000007;
fn alphabet2idx(c: char) -> usize {
if c.is_ascii_lowercase() {
c as u8 as usize - 'a' as u8 as usize
} else if c.is_ascii_uppercase() {
c a... |
#[macro_use]
extern crate failure;
use failure::Error;
use std::{env, fs, path::Path};
fn main() -> Result<(), Error> {
let path = env::var("NIX_PATH")?;
let nixpkgs = path.split(':')
.find(|s| s.starts_with("nixpkgs="))
.ok_or_else(|| format_err!("no store path found"))?;
println!("Nix s... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.