text stringlengths 8 4.13M |
|---|
use super::MapArchitect;
use crate::prelude::*;
const STAGGER_DISTANCE: usize = 400;
const NUM_TILES: usize = (SCREEN_WIDTH * SCREEN_HEIGHT) as usize;
const DESIRED_FLOOR: usize = NUM_TILES / 3;
pub struct DrunkardsWalkArchitect {}
impl MapArchitect for DrunkardsWalkArchitect {
fn new(&mut self, rng: &mut Random... |
extern crate crossbeam_channel;
extern crate serde;
extern crate serde_json;
#[macro_use]
extern crate serde_derive;
// #[macro_use]
// extern crate conrod;
// extern crate piston_window;
extern crate gtk;
extern crate clipboard;
use crossbeam_channel::{unbounded, Sender, Receiver};
use std::thread::spawn;
mod networ... |
#![allow(nonstandard_style)]
// Generated from SimpleLR.g4 by ANTLR 4.8
use super::simplelrparser::*;
use antlr_rust::token_factory::CommonTokenFactory;
use antlr_rust::tree::ParseTreeListener;
use std::any::Any;
pub trait SimpleLRListener<'input>: ParseTreeListener<'input, SimpleLRParserContextType> {
/**
*... |
#[doc = r"Register block"]
#[repr(C)]
pub struct RegisterBlock {
_reserved0: [u8; 0x0400],
#[doc = "0x400 - Reset reason"]
pub resetreas: RESETREAS,
_reserved1: [u8; 0x020c],
#[doc = "0x610..0x618 - ULP network core control"]
pub network: NETWORK,
}
#[doc = "RESETREAS (rw) register accessor: an ... |
extern crate djvuxml;
extern crate failure;
#[macro_use]
extern crate failure_derive;
extern crate zip;
use std::collections::VecDeque;
use std::fs::File;
use std::io;
use std::io::prelude::*;
use djvuxml::text::is_numeric;
use djvuxml::types::FastDjVu;
use FastDjVu::*;
const WINDOW_SIZE: usize = 32;
const CAPACITY... |
use evmc_declare::evmc_declare_vm;
use evmc_vm::*;
use eth_pairings::{PrecompileAPI, API};
// FIXME: use 'precompile'
#[evmc_declare_vm("EIP1962", "evm")]
pub struct EIP1962;
impl EvmcVm for EIP1962 {
fn init() -> Self {
EIP1962 {}
}
fn execute(&self, code: &[u8], context: &ExecutionContext) -> ... |
#![cfg_attr(not(feature = "std"), no_std)]
use ink_lang as ink;
/// 一个简单的 ERC20 ink 合约
/// 合约操作地址: https://paritytech.github.io/canvas-ui/#/
#[ink::contract]
mod erc20 {
use ink_storage::{
collections::HashMap,
lazy::Lazy,
};
/// erc20的储存
#[ink(storage)]
pub struct Erc20 {
... |
use std::{
cell::RefCell,
rc::{Rc, Weak},
};
use macroquad::{
prelude::{collections::storage, Texture2D},
rand::gen_range,
};
use crate::{
actor::{Actor, Anchor},
bolt::Bolt,
collide_actor::CollideActor,
fruit::Fruit,
game_playback::play_game_random_sound,
player::Player,
p... |
// Copyright 2021 IOTA Stiftung
// SPDX-License-Identifier: Apache-2.0
use std::ops::Range;
use iota_types::block::address::Address;
use serde::Deserialize;
use crate::{
api::types::{Bech32Addresses, RawAddresses},
constants::{SHIMMER_COIN_TYPE, SHIMMER_TESTNET_BECH32_HRP},
secret::{GenerateAddressOption... |
use std::collections::HashMap;
use std::env::{VarError, Vars};
use clap::Values;
use serde_json::{self, Value};
use serde_yaml;
pub type PluginParams = HashMap<String, String>;
// read provided variable (most likely "plugin") as yaml
pub fn get_env_hashmap(var: Result<String,VarError>) -> Result<PluginParams, String... |
use crate::{
base::{APIResponse, BaseClient},
shared::MetadataFindInput,
Tz, Weekday,
};
use nettu_scheduler_api_structs::*;
use nettu_scheduler_domain::{
providers::{google::GoogleCalendarAccessRole, outlook::OutlookCalendarAccessRole},
IntegrationProvider, Metadata, ID,
};
use reqwest::StatusCode;... |
// https://kbknapp.dev/shell-completions/
use std::io::Error;
#[cfg(feature = "completions")]
include!("src/cli.rs");
fn main() -> Result<(), Error> {
#[cfg(feature = "completions")]
create_cli_completions()?;
Ok(())
}
#[cfg(feature = "completions")]
fn create_cli_completions() -> Result<(), Error> {
use c... |
use std::env;
mod day_01;
mod day_02;
mod day_03;
mod day_04;
mod day_05;
mod day_06;
mod day_07;
mod day_08;
mod day_09;
mod day_10;
mod day_11;
mod day_12;
mod day_13;
mod utils;
fn runner(day: u8) {
match day {
1 => day_01::solve(),
2 => day_02::solve(),
3 => day_03::solve(),
4 ... |
use gl::types::GLfloat as glfloat;
use crate::datastructure::generic::Vec2f;
pub struct UVCoordinates {
pub u: glfloat,
pub v: glfloat,
}
#[derive(Clone, Copy)]
pub struct RGBColor {
pub r: glfloat,
pub g: glfloat,
pub b: glfloat,
}
impl std::ops::Add for RGBColor {
type Output = RGBColor;
... |
use rusoto_swf::{ HistoryEvent, ActivityTaskCancelRequestedEventAttributes};
pub fn generate_graph_definition(_events: std::vec::Vec<HistoryEvent>) -> String {
let mut dot = String::from("");
dot.push_str("digraph G {");
return dot;
}
fn node_shape(event: HistoryEvent) -> String {
let shape = match ev... |
//! # Chrono: Date and Time for Rust
//!
//! It aims to be a feature-complete superset of
//! the [time](https://github.com/rust-lang-deprecated/time) library.
//! In particular,
//!
//! * Chrono strictly adheres to ISO 8601.
//! * Chrono is timezone-aware by default, with separate timezone-naive types.
//! * Chrono is... |
/// 18.
///
/// 给定一个包含 n 个整数的数组 nums 和一个目标值 target,判断 nums 中是否存在四个元素 a,b,c 和 d ,
/// 使得 a + b + c + d 的值与 target 相等?找出所有满足条件且不重复的四元组。
///
/// 注意:
///
/// 答案中不可以包含重复的四元组。
///
/// 示例:
///
/// 给定数组 nums = [1, 0, -1, 0, -2, 2],和 target = 0。
///
/// 满足要求的四元组集合为:
/// [
/// [-1, 0, 0, 1],
/// [-2, -1, 1, 2],
/// [-2, ... |
//! Copied as is from https://github.com/pacman82/odbc2parquet/blob/f5bf846e80c1a9ffc1648efc0e0bcec8bbf50331/src/odbc_buffer.rs
use odbc_api::{
buffers::BindColParameters,
buffers::{
ColumnBuffer, OptBitColumn, OptDateColumn, OptF32Column, OptF64Column, OptI32Column,
OptI64Column, OptTimestampC... |
use std::process::exit;
use clap::{crate_version, Clap};
use crate::fetch::fetch;
use crate::reference::Reference;
use crate::version::BibleVersion;
pub mod book;
pub mod fetch;
pub mod reference;
pub mod version;
#[derive(Clap)]
#[clap(version = crate_version!())]
pub struct Opts {
reference: Reference,
#[... |
use super::file_span::FileSpan;
pub trait GetSpan {
fn get_span(&self) -> FileSpan;
}
macro_rules! impl_get_span {
($t: ty) => {
impl GetSpan for $t {
fn get_span(&self) -> FileSpan {
self.span.clone()
}
}
};
}
pub trait GetValue {
type Output;
... |
use std::collections::HashMap;
#[derive(Clone, Debug, Default, Deserialize, Serialize)]
#[serde(default)]
pub struct Layer {
pub name: String,
pub opacity: f32,
pub properties: Option<HashMap<String, String>>,
pub visible: bool,
pub width: u32,
pub height: u32,
pub x: f32,
pub y: f32,
... |
/*
* Copyright (c) 2021, TU Dresden.
*
* 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 di... |
#[allow(unused_imports)]
use serde_json::Value;
#[derive(Debug, Serialize, Deserialize)]
pub struct AdsProviderControllersController {
/// Specifies the address for the domain controller.
#[serde(rename = "dc_address")]
pub dc_address: Option<String>,
/// Specifies the name of the domain controller.
... |
// See apimachinery/pkg/util/validation/validation.go
// See also TODO apimachinery/pkg/api/validation/generic.go and pkg/apis/core/validation/validation.go
use const_format::concatcp;
use lazy_static::lazy_static;
use regex::Regex;
const RFC_1123_LABEL_FMT: &str = "[a-z0-9]([-a-z0-9]*[a-z0-9])?";
const RFC_1123_SUBD... |
use actix_web::{
http::Method,
middleware,
App,
http::NormalizePath,
};
use tesseract_core::{Backend, Schema, CubeHasUniqueLevelsAndProperties};
use crate::db_config::Database;
use crate::handlers::{
aggregate_handler,
aggregate_default_handler,
aggregate_stream_handler,
aggregate_stream... |
use blend::{Blend, Instance};
use std::{env, path};
type Vertex = ([f32; 3], [f32; 3], [f32; 2]);
type Face = [Vertex; 3];
#[derive(Debug)]
struct Mesh {
_faces: Vec<Face>,
}
#[derive(Debug)]
struct Object {
_name: String,
_location: [f32; 3],
_rotation: [f32; 3],
_scale: [f32; 3],
_mesh: Mes... |
use crate::methods::Method;
use serde::*;
use std::collections::BTreeSet;
/// An unique random.org request id
#[derive(Debug, Clone, Eq, Ord, PartialEq, PartialOrd, Serialize, Deserialize)]
pub struct RequestId(pub u64);
/// A random.org api key
#[derive(Debug, Clone, Serialize)]
pub struct ApiKey(pub String);
/// ... |
type Job = Box<dyn FnOnce() + Send + 'static>;
/// Message to a [`threadpool::Worker`]
///
/// [`threadpool::Worker`]: crate::threadpool::Worker
pub enum Message {
NewJob(Job),
Terminate,
}
|
#[macro_use(value_t)]
extern crate clap;
extern crate simple_signal;
use simple_signal::{Signal};
use clap::{Arg, App};
use std::f64;
use std::process;
use std::io;
use std::io::Write;
use std::time;
use std::thread;
use std::sync::mpsc::sync_channel;
fn input() -> io::Result<String> {
let mut string = String::ne... |
// Copyright (c) 2015 Alcatel-Lucent, (c) 2016 Nokia
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
// * Redistributions of source code must retain the above copyright
// notice,... |
use std::collections::HashSet;
use util::*;
trait Preorder {
fn recover(&mut self, x: i32, hs: &mut HashSet<i32>);
}
impl Preorder for TreeLink {
fn recover(&mut self, x: i32, hs: &mut HashSet<i32>) {
if let Some(node) = self {
hs.insert(x);
node.borrow_mut().val = x;
... |
use crate::cluster::message::NetworkMessage;
use crate::config::injection::DIService;
use crate::config::ConfigObj;
use crate::CubeError;
use async_trait::async_trait;
use std::sync::Arc;
use std::time::Duration;
use tokio::net::TcpStream;
/// Client-side connection for exchanging messages between the server and the c... |
use failure::Error;
use rusoto_core::Region;
use rusoto_sts::{AssumeRoleWithSAMLRequest, AssumeRoleWithSAMLResponse, Sts, StsClient};
use rusoto_credential::StaticProvider;
use rusoto_core::reactor::RequestDispatcher;
use std::str;
use std::str::FromStr;
#[derive(Debug)]
pub struct Role {
pub provider_arn: String... |
use bigint::H256;
use trie::{Change, DatabaseHandle, get, insert, delete};
use TrieMut;
pub trait ItemCounter {
fn increase(&mut self, key: H256) -> usize;
fn decrease(&mut self, key: H256) -> usize;
}
pub trait DatabaseMut {
fn get(&self, key: H256) -> &[u8];
fn set(&mut self, key: H256, value: Optio... |
#[doc = "Reader of register MAXPACKETSIZE"]
pub type R = crate::R<u32, super::MAXPACKETSIZE>;
#[doc = "Writer for register MAXPACKETSIZE"]
pub type W = crate::W<u32, super::MAXPACKETSIZE>;
#[doc = "Register MAXPACKETSIZE `reset()`'s with value 0xfb"]
impl crate::ResetValue for super::MAXPACKETSIZE {
type Type = u32... |
// modules2.rs
// Make me compile! Execute `rustlings hint modules2` for hints :)
mod delicious_snacks {
//Essas duas linhas publicam APENAS as partes dos módulos citadas
//o resto do módulo fica indisponível
// então nesse módulo 'delicious_snacks' ele define módulos internos 'fruits' e 'veggies'
//... |
#![feature(tool_lints)]
#![warn(clippy::all)]
use std::cell::RefCell;
use std::str::FromStr;
use std::ops::Index;
use std::ops::IndexMut;
static PRINT_BOARDS: bool = false;
#[derive(Clone, Copy, Debug)]
enum Move { North, East, South, West }
impl From<char> for Move {
fn from(c: char) -> Move {
match c {
... |
use core::fmt::{self, Debug, Display};
pub use NoSuccessKind::*;
pub use SuccessKind::*;
pub struct Status<K>(pub K);
impl<K: Debug> Display for Status<K> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
writeln!(f, "% SZS status {:?}", self.0)
}
}
pub struct Output<O>(pub O);
impl<O: Di... |
#[derive(Debug)]
pub struct Algo {
vec: Vec<String>,
}
impl Algo {
pub fn new(vec: Vec<String>) -> Self {
Algo { vec: vec }
}
pub fn len(&self) -> usize {
self.vec.len()
}
pub fn is_sorted(&self) -> bool {
let mut sorted = true;
for i in 0..self.len() - 1 {
... |
#![feature(box_syntax)]
#![feature(test)]
#![no_std]
//#![warn(clippy::pedantic, clippy::nursery, clippy::cargo)]
extern crate alloc;
#[cfg(feature = "std")]
extern crate std;
mod gba;
pub use gba::*;
|
pub mod deque;
pub mod paged;
pub mod robust;
pub mod traits;
pub mod vector;
pub use self::{
deque::PackedDeque,
paged::{IdentityCodec, PagedCodec, PagedIntVec},
robust::RobustPagedIntVec,
traits::*,
vector::PackedIntVec,
};
#[inline]
pub fn width_for(value: u64) -> usize {
64 - value.leading... |
use std::collections::HashMap;
#[derive(Debug)]
struct LRUCacheNode {
key: i32,
value: i32,
prev: Option<usize>,
next: Option<usize>,
}
#[derive(Debug)]
pub struct LRUCache {
capacity: usize,
map: HashMap<i32, usize>,
head: Option<usize>,
tail: Option<usize>,
arena: Vec<LRUCacheNod... |
#![feature(core, old_io, int_uint, std_misc)]
extern crate syncbox;
#[macro_use]
extern crate log;
extern crate env_logger;
mod util;
|
use std::fmt;
use ethportal_api::types::distance::Distance;
use ethportal_api::types::enr::Enr;
/// A node in the overlay network routing table.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct Node {
/// The node's ENR.
pub enr: Enr,
/// The node's data radius.
pub data_radius: Distance,
}
impl Nod... |
use clap::command;
use clap::Parser;
/// twitch low latency
#[derive(Parser, Debug)]
#[command(
author = "7ERr0r",
version,
about,
long_about = "Lowest possible m3u8 latency on twitch. Acquires playlist url, then downloads with async segment/bytes fetching"
)]
pub struct TwitchzeroArgs {
/// File p... |
// Module content and metadata are private, whose members are
// selectively exposed.
mod content;
pub use self::content::Weapon;
mod metadata;
pub use self::metadata::SharpnessColor;
pub use self::metadata::WeaponColumn;
pub use self::metadata::WeaponType;
pub use self::metadata::SpecialType;
pub use self::metadata::... |
use log::Level;
use serde_json::{Map, Value};
// Directory for Bluetooth hci devices
pub const HCI_DEVICES_DIR: &str = "/sys/class/bluetooth";
// File to store the Bluetooth daemon to use (bluez or floss)
const BLUETOOTH_DAEMON_CURRENT: &str = "/var/lib/misc/bluetooth-daemon.current";
// File to store the config for... |
// Copyright 2014 The Rustastic Password Developers
//
// 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 applicabl... |
use std::io;
use std::io::Write;
use nom::{IResult, be_u8};
/// Number of bytes that the extension protocol takes.
pub const NUM_EXTENSION_BYTES: usize = 8;
/// Enumeration of all extensions that can be activated.
pub enum Extension {
/// Support for the extension protocol `http://www.bittorrent.org/beps/bep_001... |
//! Test server for sockjs-protcol functiona tests
extern crate actix;
extern crate actix_web;
extern crate sockjs;
extern crate env_logger;
use actix_web::*;
use actix::prelude::*;
use sockjs::{Message, Session, SockJSManager, SockJSContext};
#[derive(Debug)]
struct Echo;
impl Actor for Echo {
type Context = S... |
use crate::{
gr_type::grtype::{self, *},
input_type::inputtype::{self, *},
pic_type::pictype,
sound_type::soundtype::{self, *},
sprite_type::spritetype,
};
// Globals previously belonging to cpanel.rs.
//
pub struct CpanelState {
/*
Private
*/
pub spotok: [[bool; 5]; 4],
pub row... |
use std::{thread, time};
use database::VSwimDB;
use crate::vatsim::Vatsim;
mod vatsim;
pub mod database;
#[tokio::main]
async fn main() {
loop {
let vatsim = Vatsim::new()
.with_status_url("https://status.vatsim.net/status.json")
.build().await
.expect("Couldnt build V... |
#[macro_use]
extern crate bitflags;
mod rom;
mod cartridge;
mod memory;
mod mmu;
mod cpu;
mod gpu;
mod timer;
mod irq;
use cartridge::Cartridge;
use mmu::MMU;
use cpu::CPU;
//TODO Investigate minifb
//TODO Use actual bios
// Use boot-values for stuff in that case!
//TODO Overhaul cycle architecture or at least t... |
// Without --remap-path-prefix, Location::caller() in this generic function will return an absolute path
pub fn get_file_name<T>() -> &'static str {
std::panic::Location::caller().file()
}
|
use std::collections::HashSet;
use actix_web::{web, Error, HttpResponse};
use futures::future;
use futures::Future;
use futures_cpupool::CpuPool;
use r2d2::Pool;
use r2d2_postgres::postgres::error::Error as PgError;
use r2d2_postgres::PostgresConnectionManager;
use serde_derive::{Deserialize, Serialize};
use serde_jso... |
enum GlobalState {
Menu,
Game,
Quit
}
struct GameContext {
name: ~str
}
fn main() {
let mut state : GlobalState = Menu;
let mut game : Option<@GameContext> = None;
loop {
match state {
Menu => {
let (s, g) = menuLoop();
state = s;
game = g;
},
Game =>... |
use anyhow::{format_err, Error};
use deadpool_postgres::{Client, Config, Pool};
use std::{fmt, sync::Arc};
use tokio_postgres::{Config as PgConfig, NoTls};
pub use tokio_postgres::Transaction as PgTransaction;
use stack_string::StackString;
#[derive(Clone, Default)]
pub struct PgPool {
pgurl: Arc<StackString>,
... |
#[path = "libs/factorial.rs"]
mod factorial;
fn run<F>(f: F)
where F: Fn()
{
f();
}
fn main() {
let print = || println!("Running a closure");
let numbers = vec![1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
let counter = Counter::new();
let counter_sum: u32 = counter.zip(Counter::new().skip(1))
.map(|(a, b)| a + ... |
use std::collections::HashMap;
use std::collections::HashSet;
// use histogram::Histogram;
use crate::db_structs::DB;
use crate::token::{ HybQuery, BoolQuery };
use std::cmp::max;
pub struct Statistics{
hists : HashMap<String, HashMap<String, usize>>,
sizes : HashMap<String, usize>,
widths : Hash... |
// Copyright 2019 Conflux Foundation. All rights reserved.
// Conflux is free software and distributed under GNU General Public License.
// See http://www.gnu.org/licenses/
mod action_params;
mod call_type;
mod context;
mod env;
mod error;
mod return_data;
mod spec;
#[cfg(test)]
pub mod tests;
pub use self::{
ac... |
use graphics::{ self, Context, Line, Graphics };
fn draw_triangle<G: Graphics>(
offset: graphics::math::Vec2d,
scale_up: graphics::math::Vec2d,
line: &Line,
c: &Context,
g: &mut G
) {
use graphics::math::*;
let triangle = [
[0.0, 0.0],
[1.0, 0.5],
[0.0, 1.0]
];
... |
#![allow(dead_code)]
use std::convert::TryFrom;
type Error = &'static str;
type Var = &'static str;
type LexicalAdress = usize;
#[derive(Debug, Eq, PartialEq, Clone)]
struct StaticEnv(Vec<Var>); // The envs should be something like a Rc<LinkedList<Var>>
// (probably a custom implementation ... |
mod caps;
mod dev;
mod mount;
mod resources;
mod spec;
use crate::resources::LinuxResources;
use clap::{App, Arg};
//use crate::CLONE_NEWNS;
//use libc::CLONE_NEWNS;
use nix::sys::socket::SockFlag;
use nix::sys::socket::{socketpair, AddressFamily, SockType};
use nix::sys::utsname::uname;
use nix::unistd::{execve, exe... |
use thiserror::Error;
/// An error returned from the [`Client`].
///
/// [`Client`]: struct.Client.html
/// [`Error`]: ../enum.Error.html
/// [`Error::Client`]: ../enum.Error.html#variant.Client
/// [`GuildId::ban`]: ../model/id/struct.GuildId.html#method.ban
#[allow(clippy::enum_variant_names)]
#[derive(Clone, Debug,... |
use world::CollisionObject;
use narrow_phase::ContactAlgorithm;
use math::Point;
/// A signal handler for contact detection.
pub trait ContactHandler<P: Point, M, T> : Sync + Send {
/// Activate an action for when two objects start being in contact.
fn handle_contact_started(&mut self,
... |
pub extern crate tokio;
#[macro_export]
macro_rules! tokio_data {
($data_type:ty, $data:expr) => {
type TokioData = $data_type;
use std::sync::Arc;
use tokio::sync::{Mutex, MutexGuard};
thread_local! {
static DATA: Arc<Mutex<TokioData>> = Arc::new(Mutex::new($data));
... |
use std::io::prelude::*;
use std::net::TcpStream;
use std::io;
use std::sync::{Arc};
use std::collections::HashSet;
use std::sync::Mutex;
use stopwatch::{Stopwatch};
use openssl::ssl::{SslMethod, SslConnector};
use std::time::Duration;
use std::io::{Error, ErrorKind};
use lazy_static::lazy_static;
use threadpool::Threa... |
#![no_main]
#![no_std]
use async_core::task;
use hal as _; // memory layout
use panic_never as _; // this program contains zero core::panic* calls
#[no_mangle]
fn main() -> ! {
let a = async {
semidap::info!("before yield");
task::r#yield().await;
semidap::info!("after yield");
sem... |
use std::error::Error as StdError;
use std::fmt;
#[derive(Debug)]
pub struct TaggerError {
msg: String,
}
impl fmt::Display for TaggerError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", &self.msg)
}
}
impl StdError for TaggerError {
fn description(&self) -> &str {
&self.msg... |
use std::io::{BufReader, Error, ErrorKind, Read, Result, Write};
use std::net::TcpStream;
#[derive(Debug, Hash, Eq, PartialEq, Clone)]
pub enum Message {
// Requests
GetFeaturesRequest,
LoginRequest {
username:String
},
ReadyRequest,
NotReadyRequest,
ChallengePlayerRequest {
... |
//! Compress a pruned tree to remove all eliminated bindings
use crate::core::error::CoreError;
use crate::core::expr::*;
use crate::core::transform::succ;
use moniker::{Binder, BinderIndex, BoundVar, Embed, Rec, Scope, Var};
use std::collections::VecDeque;
pub fn compress(expr: &RcExpr) -> Result<RcExpr, CoreError> {... |
use super::inner::HandleInner;
/// This encapsulates the pattern of wrapping a fixed-size lock-free data-structure inside an
/// RwLock, and automatically resizing it when the number of concurrent handles increases.
pub unsafe trait Handle: Sized + Clone {
type HandleInner;
fn try_allocate_id<IdType>(&self) ... |
extern crate libc;
mod bindings;
pub mod imgui;
pub mod point_cloud_func;
pub use crate::point_cloud_func::PointCloudImpl as point_cloud;
pub use crate::point_cloud_func::ScalarFunc as pc_scalar;
pub use crate::point_cloud_func::Vec3Func as pc_vec3;
pub fn init() {
unsafe {
bindings::c_init();
}
}
pu... |
use crate::hw_client::{HwClient, HwConnectionStatus, HwDeviceInfo, HwProcessingError, HwPubkey, TrezorConnectProcessor};
use crate::hw_error::HwError;
use crate::trezor::TrezorSession;
use crate::{mm2_internal_der_path, HwWalletType};
use bip32::ChildNumber;
use bitcrypto::dhash160;
use common::log::warn;
use hw_common... |
use kurtosis_rust_lib::services::{service::Service, service_context::ServiceContext};
pub (super) const FAUCET_PORT: u32 = 9900;
pub struct FaucetService {
service_context: ServiceContext,
keypair_json: String,
}
impl FaucetService {
pub fn new(service_context: ServiceContext, keypair_json: String) -> Fa... |
use crate::tests::world_tester::*;
#[test]
fn set_flag() {
let mut world = TestWorld::new_with_player(1, 1);
let mut tile_set = TileSet::new();
tile_set.add_object('O', "#set a\n");
world.insert_tile_and_status(tile_set.get('O'), 10, 10);
assert_eq!(world.world_header().last_matching_flag(DosString::from_str(... |
use crate::access_path_cache::AccessPathCache;
use move_core_types::account_address::AccountAddress;
use move_core_types::effects::{
ChangeSet as MoveChangeSet, Event as MoveEvent, Op as MoveStorageOp,
};
use move_core_types::language_storage::ModuleId;
use move_core_types::vm_status::{StatusCode, VMStatus};
use mo... |
use super::*;
/// Type of action a unit is currently performing
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub enum ActionType {
/// Picking up or dropping loot
Looting,
/// Using a shield potion
UseShieldPotion,
}
impl trans::Trans for ActionType {
fn write_to(&self, writer: &mut dyn std::io::W... |
pub mod derived_encrypt_key;
pub mod double_hash;
pub mod encrypt_key;
pub mod public_encrypted_secure_data;
pub mod encrypted_secure_data;
pub mod encrypted_private_key;
pub mod signed_protected_data;
pub mod fast_random;
pub mod hash;
pub mod initialization_vector;
pub mod key_size;
pub mod private_encrypt_key;
pub m... |
use object::{Object, ObjectSection};
use std::{env, fs, process};
fn main() {
let arg_len = env::args().len();
if arg_len <= 1 {
eprintln!("Usage: {} <file> ...", env::args().next().unwrap());
process::exit(1);
}
for file_path in env::args().skip(1) {
if arg_len > 2 {
... |
//! A generic resource pool for the Tokio ecosystem.
//!
//! # Example
//!
//! To use it, you need to implment `Manage` for your resource, and then use the `Builder` to create
//! a `Pool`. Once this is done, you can request a resource by calling `Pool::check_out`.
//!
//! ```ignore
//! // TODO: Update this example whe... |
use crate::allocator::{allocate, deallocate, grow_to};
use crate::capacity::{DefaultPolicy, Policy};
use crate::pool::Pool;
use alloc::alloc::Global;
use core::alloc::Allocator;
use core::marker::PhantomData;
use core::mem::ManuallyDrop;
use core::ptr::NonNull;
#[derive(Clone, Copy)]
#[rustc_layout_scalar_valid_range_... |
use structs::{Axis, Grid};
mod part1;
mod part2;
mod structs;
fn main() {
let input = include_str!("../assets/input_ludegra.txt")
.trim()
.split("\n\n")
.collect::<Vec<_>>();
let grid = input[0]
.split('\n')
.fold(Grid::new(1311,894), |mut grid, s| {
let sp... |
fn main() {
// trait Graph<N, E> {
// fn has_edge(&self, &N, &N) -> bool;
// fn edges(&self, &N) -> Vec<E>;
// }
//
// fn distance<N, E, G: Graph<N, E>>(graph: &G, start: &N, end: &N) -> u32 {
// 1
// }
trait Graph {
type N;
type E;
fn has_edge(&... |
use crate::traits::{PrimeGroupElement, Scalar};
use blake2::Blake2b;
/// Challenge context for Discrete Logarithm Equality proof. The common reference string
/// are two EC bases, and the statement consists of two EC points.
/// The challenge computation takes as input the two announcements
/// computed in the sigma p... |
#![feature(nll)]
#![feature(test)]
#[macro_use]
extern crate derive_builder;
extern crate failure;
extern crate itertools;
#[macro_use]
extern crate log;
extern crate integer_encoding;
extern crate io_at;
extern crate log4rs;
extern crate regex;
#[macro_use]
extern crate lazy_static;
extern crate serde;
#[macro_use]
e... |
use thiserror::Error;
use std::fmt;
use svm_program::FuncIndex;
use crate::{GraphCycles, NodeLabel};
/// Represents error that may occur while doing gas estimation
#[derive(Debug, PartialEq, Clone, Error)]
pub enum FixedGasError<T = FuncIndex>
where
T: NodeLabel,
{
CallIndirectNotAllowed,
/// `loop` isn... |
.map(|s| unsafe { crate::templ::receive_string(s as *mut String) })
|
use std::iter::Peekable;
use crate::{
ir,
lexer::{Keyword, Token, TokenMetadata},
};
mod parse_dt;
/// Parses a Token-Stream into a concrete Datatype
///
/// # Example:
/// ```rust
/// # use compiler::lexer::{Token, TokenMetadata, Keyword};
/// # use compiler::parser::datatype::parse;
/// # let empty_metadat... |
use snafu::Snafu;
use std::collections::{HashMap, HashSet};
use std::iter::Iterator;
use std::str::FromStr;
#[derive(Debug, PartialEq, Eq)]
enum MapCell {
Asteroid,
Empty,
}
impl From<char> for MapCell {
fn from(c: char) -> MapCell {
match c {
'#' => MapCell::Asteroid,
'.' ... |
pub use cgmath::prelude::*;
use serde::{Deserialize, Serialize};
pub type Vec3 = cgmath::Vector3<f32>;
pub type Pos3 = cgmath::Point3<f32>;
pub type Mat3 = cgmath::Matrix3<f32>;
pub type Mat4 = cgmath::Matrix4<f32>;
pub type Quat = cgmath::Quaternion<f32>;
pub const PI: f32 = std::f32::consts::PI;
pub const EPS: f32 =... |
use std::process::Command;
fn main() {
prost_build::Config::new()
.out_dir("src/pb")
.compile_protos(&["abi.proto"], &["."])
.unwrap();
Command::new("cargo")
.args(&["fmt", "--", "src/*.rs"])
.status()
.expect("cargo fmt failed");
}
|
// Copyright (c) The Starcoin Core Contributors
// SPDX-License-Identifier: Apache-2.0
use crate::mocker::MockHandler;
use crate::{
ActorService, EventHandler, ServiceContext, ServiceFactory, ServiceHandler, ServiceRequest,
ServiceStatus,
};
use anyhow::{bail, Result};
use log::{error, info, warn};
use std::an... |
use std::collections::HashMap;
use std::fs;
fn get_passports<'a>(text: &'a str) -> Vec<HashMap<&'a str, &'a str>> {
let passports = text.split("\n\n");
return passports
.map(|pp| pp.split(|c| c == '\n' || c == ' ').collect())
.map(|pp: Vec<&str>| {
pp.iter().fold(HashMap::new(), |mu... |
use crate::game::{msg, Transition};
use crate::sandbox::gameplay::faster_trips::faster_trips_panel;
use crate::sandbox::gameplay::{manage_overlays, GameplayState};
use crate::sandbox::overlays::Overlays;
use crate::ui::UI;
use ezgui::{hotkey, EventCtx, Key, ModalMenu};
use geom::Duration;
use sim::TripMode;
pub struct... |
use jis0208;
use unicode_hfwidth;
use byteorder;
use std::io::Read;
use byteorder::{ReadBytesExt, LittleEndian};
pub type BoResult<T> = Result<T, byteorder::Error>;
pub trait ReadExact {
fn read_exact_(&mut self, len: u64) -> BoResult<Vec<u8>>;
}
impl<T: Read> ReadExact for T {
fn read_exact_(&mut self, len... |
// custom debug impls for lambda_calculus types
use crate::lambda_calculus::*;
use core::fmt::Debug;
use core::fmt::Error;
use core::fmt::Formatter;
// pub struct Lambda {
// pub arg_name: String,
// pub body: Expr,
// }
// pub struct Call {
// pub func: Expr,
// pub arg: Expr,
// }
// pub struct Va... |
use std::fs::File;
use std::path::Path;
use std::io::{BufRead, BufReader};
use std::cmp::{min, max};
use array2d::Array2D;
const SIZE:usize = 80;
const FILENAME: &str = "p081_matrix.txt";
#[derive(Debug, Clone, Copy)]
enum PathStep {
Uninitialized,
Right(u32),
Down(u32),
Finished(u32)
}
fn get_cost(p... |
use std::future::Future;
use std::pin::Pin;
// If http2 is not enable, we just have a stub here, so that the trait bounds
// that *would* have been needed are still checked. Why?
//
// Because enabling `http2` shouldn't suddenly add new trait bounds that cause
// a compilation error.
pub struct H2Stream<F, B>(std::ma... |
use core::convert::TryFrom;
use core::fmt;
use bad64_sys::*;
use cstr_core::CStr;
use num_traits::FromPrimitive;
use crate::ArrSpec;
use crate::Condition;
use crate::Reg;
use crate::Shift;
use crate::SysReg;
/// An instruction immediate
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
pub enum Imm {
Signed(i64... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.