text stringlengths 8 4.13M |
|---|
extern crate isosurface;
extern crate nalgebra;
use isosurface::*;
use nalgebra::{Vector3};
use std::cmp::{Ordering,PartialOrd};
fn partial_max<T:PartialOrd+Copy>(v:&Vec<T>)->Option<T>{
if v.len()==0{
None
}
else if v.len()==1{
Some(v[0])
}
else{
... |
use s3::ByteStream;
use s3::Region;
use std::error::Error;
use std::path::Path;
use tracing_subscriber::fmt::format::FmtSpan;
use tracing_subscriber::fmt::SubscriberBuilder;
// Change these to your bucket & key
const BUCKET: &str = "demo-bucket";
const KEY: &str = "demo-object";
#[tokio::main]
async fn main() -> Resu... |
use crate::output::{ErrorKind, FailureKind, TestCase, TestCaseResult};
use regex::Regex;
use url::Url;
lazy_static::lazy_static! {
static ref CURL_RE: Regex = Regex::new(r"Curl command: curl -i -X (\w+) .+ '(http://.+)'").expect("Valid regex");
}
pub fn process_stdout(content: &str) -> impl Iterator<Item = TestCa... |
pub fn my_atoi(str: String) -> i32 {
let v: Vec<char> = str.chars().collect();
let mut num = 0;
const INT_MAX: i32 = - ((-1 << 31) + 1);
const INT_MIN: i32 = -1 << 31;
let mut pos = true;
let mut leading_white_space = true;
let mut has_sign = false;
let mut has_digit = false;
for c ... |
use serde::{Deserialize, Serialize};
/// 文章详细信息
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct Article {
pub id: Option<u32>,
pub title: String,
pub content: String,
pub date: Option<chrono::NaiveDate>,
}
/// 文章预览
#[derive(Debug, Clone, Serialize)]
pub struct ArticlePreview {
pub id: u... |
use sqlx::{FromRow, SqlitePool};
use sqlx::sqlite::SqliteQueryAs;
use crate::db_utils::{get_last_inserted_id, DynUpdate};
use crate::errors::ApiError;
use crate::common::time_now;
use sqlx::arguments::Arguments;
#[derive(Debug, Serialize, Deserialize, FromRow)]
pub struct Shoe {
#[sqlx(rename = "Id")]
#[serde... |
use crate::utilities::intcode::execution_error::ExecutionError;
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum ParameterMode {
Position,
Immediate,
}
impl ParameterMode {
pub fn try_from_opcode(opcode: i32, idx: u32) -> Result<ParameterMode, ExecutionError> {
let place_value = 10i32.pow(idx + 2... |
#[macro_use]
extern crate afl;
extern crate graph_harness;
use graph_harness::*;
fn main() {
fuzz!(|data: FromCsvHarnessParams| {
// We ignore this error because we execute only the fuzzing to find
// the panic situations that are NOT just errors, but unhandled errors.
let _ = from_csv_harne... |
//
// Copyright (C) 2016-2020 Abstract Horizon
// All rights reserved. This program and the accompanying materials
// are made available under the terms of the Apache License v2.0
// which accompanies this distribution, and is available at
// https://www.apache.org/licenses/LICENSE-2.0
//
// Contributors:
// Daniel... |
use super::*;
#[tokio::test]
async fn test_local_interfaces() -> Result<(), Error> {
let vnet = Arc::new(Net::new(None));
let interfaces = vnet.get_interfaces().await;
let ips = local_interfaces(&vnet, &None, &[NetworkType::Udp4, NetworkType::Udp6]).await;
log::info!("interfaces: {:?}, ips: {:?}", inte... |
use sdl2::pixels::Color;
use sdl2::rect::Point;
use sdl2::render::WindowCanvas;
use super::constants::{WORLD_HEIGHT, WORLD_WIDTH, WORLD_X_UPPER_BOUND, WORLD_Y_UPPER_BOUND};
#[derive(Eq, PartialEq, Copy, Clone)]
pub enum ParticleType {
Empty,
Sand,
Water,
Wood,
Iron,
Fire,
Acid,
Smoke,
... |
uаse std::fmt::format;
use std::io::{Read, Write};
use std::net::{IpAddr, Ipv4Addr, SocketAddr, TcpListener};
use std::str::FromStr;
use std::string::ParseError;
#[derive(Debug)]
struct RequestLine {
method: Option<String>,
path: Option<String>,
protocol: Option<String>
}
impl RequestLine {
fn method(... |
use std::rc::Rc;
fn main() {
// 堆上的数据有了三个共享的所有者。
let a = Rc::new(1);
let b = a.clone();
let c = a.clone();
}
//
use std::cell::RefCell;
fn main() {
let data = RefCell::new(1);
{
// 获得 RefCell 内部数据的可变借用
let mut v = data.borrow_mut();
*v += 1;
}
println!("data:... |
#[doc = r"Register block"]
#[repr(C)]
pub struct RegisterBlock {
#[doc = "0x00 - OTG_FS host configuration register (OTG_FS_HCFG)"]
pub hcfg: HCFG,
#[doc = "0x04 - OTG_FS Host frame interval register"]
pub hfir: HFIR,
#[doc = "0x08 - OTG_FS host frame number/frame time remaining register (OTG_FS_HFN... |
use crate::common::Solution;
use itertools::Itertools;
use itertools::MinMaxResult::MinMax;
use std::collections::HashSet;
static PART1_SOLUTION: usize = 542529149;
static PRE_SIZE: usize = 25;
fn find_combination_of2<'a, I>(input_iter: I, target: usize) -> Option<usize>
where
I: Iterator<Item = &'a usize>,
{
... |
#[doc = "Register `WRP1AR` reader"]
pub type R = crate::R<WRP1AR_SPEC>;
#[doc = "Register `WRP1AR` writer"]
pub type W = crate::W<WRP1AR_SPEC>;
#[doc = "Field `WRP1A_PSTRT` reader - WRP1A_PSTRT"]
pub type WRP1A_PSTRT_R = crate::FieldReader;
#[doc = "Field `WRP1A_PSTRT` writer - WRP1A_PSTRT"]
pub type WRP1A_PSTRT_W<'a, ... |
use crate::constants::DATA_DIR;
use std::ffi::OsStr;
use std::path::PathBuf;
// Traits
use getset::Getters;
#[derive(Getters, Debug, PartialOrd, PartialEq, Clone)]
#[getset(get = "pub")]
pub(crate) struct SaveConfiguration {
path_buf: PathBuf,
header: bool,
date: chrono::DateTime<chrono::Local>,
id: O... |
//! Using Windows Runtime APIs from Rust.
//!
//! ## Example
//! ```
//! # // THIS IS THE SAME CODE THAT IS SHOWN IN README.md
//! # // PLEASE KEEP THEM IN SYNC SO WE CAN RELY ON DOCTESTS!
//! extern crate winrt;
//!
//! use winrt::*; // import various helper types
//! use winrt::windows::system::diagnostics::*; // imp... |
fn sin(x: f32) -> f32 {
let x = x * (1.0 / (std::f32::consts::PI * 2.0));
let x = x - x.floor() - 0.5;
(0.6150599377704147_f32)
.mul_add(x * x, -3.776312346215613_f32)
.mul_add(x * x, 15.084843206874782_f32)
.mul_add(x * x, -42.05746026953019_f32)
.mul_add(x * x, 76.705774492... |
#![feature(plugin)]
#![plugin(flow)]
extern crate tangle;
use tangle::{Future, Async};
#[test]
fn compile() {
flow!{
let a: bool<-foobar
};
// foobar.and_then(move |a| {
// Async::Ok(())
// })
}
|
#[macro_use]
extern crate serde_derive;
extern crate serde;
extern crate serde_json;
#[derive(Serialize, Deserialize, Debug)]
struct Point {
x: i32,
y: i32,
}
fn main() {
let point = Point { x: 1, y: 2 };
// Convert the Point to a JSON string.
let serialized = serde_json::to_string(&point).unwra... |
//! Available user interface controls and related functionality.
//!
//! Note that `Control` and all specific control types are references to memory which is owned by the UI library.
use ui::UI;
use ui_sys::{self, uiControl};
use std::ptr;
#[macro_use]
mod create_macro;
mod label;
pub use self::label::*;
mod button;... |
//! Common Set operations for SegmentSet
use crate::{map::Key, RangeBounds, SegmentMap, SegmentSet};
pub mod difference;
pub mod intersection;
pub mod symmetric_difference;
pub mod union;
impl<T: Ord> SegmentSet<T> {
/// Check whether `self` and `other` are disjoint sets
///
/// That is, the intersection... |
extern crate futures;
extern crate ocl;
extern crate ocl_extras;
use std::thread::{JoinHandle, Builder as ThreadBuilder};
use futures::Future;
use ocl::{ProQue, Buffer, MemFlags};
use ocl::r#async::{BufferSink, WriteGuard};
// Our arbitrary data set size (about a million) and coefficent:
const WORK_SIZE: usize = 1 <... |
#![cfg_attr(feature = "nightly", feature(try_from))]
#[cfg(feature = "nightly")]
use std::convert::TryFrom;
use std::fmt;
use std::io;
#[derive(Clone, Copy, PartialEq, PartialOrd, Eq, Ord, Hash)]
pub struct OsError {
code: i32,
}
#[derive(Clone, Copy, PartialEq, PartialOrd, Eq, Ord, Debug, Hash)]
pub struct NoOsE... |
struct Point<T,U> {
x: T,
y: U,
}
impl<T> Point<T,T> {
fn swap(&mut self) {
std::mem::swap(&mut self.x,&mut self.y);
}
}
fn main() {
let x: Option<i32> = Some(5);
}
|
use aide::openapi::v3::macros::api;
use thiserror::Error;
use time::{Duration, OffsetDateTime};
use uuid::Uuid;
#[api]
#[serde(rename_all = "camelCase")]
pub struct CreateImageRequest {
pub title: String,
pub description: Option<String>,
pub categories: Vec<Uuid>,
}
#[api]
#[serde(rename_all = "camelCase"... |
use rand::{thread_rng, Rng};
#[derive(Clone, Copy)]
pub struct RandomRange {
pub min: f32,
pub max: f32,
}
impl RandomRange {
pub fn new(min: f32, max: f32) -> RandomRange {
RandomRange {
min, max
}
}
pub fn get(&self) -> f32 {
let mut rng = thread_rng();
... |
#[doc = "Reader of register RCC_MCO1CFGR"]
pub type R = crate::R<u32, super::RCC_MCO1CFGR>;
#[doc = "Writer for register RCC_MCO1CFGR"]
pub type W = crate::W<u32, super::RCC_MCO1CFGR>;
#[doc = "Register RCC_MCO1CFGR `reset()`'s with value 0"]
impl crate::ResetValue for super::RCC_MCO1CFGR {
type Type = u32;
#[i... |
use crate::input::{Command, KeyInput, KeyMap};
use crate::line_cache::Style;
use cairo::{FontFace, FontOptions, FontSlant, FontWeight, Matrix, ScaledFont};
use druid::shell::piet;
use piet::{CairoText, Font, FontBuilder, Text};
use std::collections::HashMap;
use std::sync::{Arc, Mutex, Weak};
use syntect::highlighting:... |
#[doc = "Register `CR1` reader"]
pub type R = crate::R<CR1_SPEC>;
#[doc = "Register `CR1` writer"]
pub type W = crate::W<CR1_SPEC>;
#[doc = "Field `TAMP1E` reader - Tamper detection on TAMP_IN1 enable"]
pub type TAMP1E_R = crate::BitReader;
#[doc = "Field `TAMP1E` writer - Tamper detection on TAMP_IN1 enable"]
pub type... |
use super::{contains_return, BIND_INSTEAD_OF_MAP};
use crate::utils::{
in_macro, match_qpath, match_type, method_calls, multispan_sugg_with_applicability, paths, remove_blocks, snippet,
snippet_with_macro_callsite, span_lint_and_sugg, span_lint_and_then,
};
use if_chain::if_chain;
use rustc_errors::Applicabilit... |
/// Functions to render cursors on graphics backend independently from it's rendering techique.
///
/// In the most cases this will be the fastest available implementation utilizing hardware composing
/// where possible. This may however be quite restrictive in terms of supported formats.
///
/// For those reasons you ... |
use enum_primitive::FromPrimitive;
use fal::{read_u32, read_u64};
use crate::{
btree::BTreeNode, read_block, reaper::ReaperPhys, spacemanager::SpacemanagerPhys,
superblock::NxSuperblock, ObjPhys, ObjectIdentifier, ObjectType, ObjectTypeAndFlags,
};
#[derive(Debug)]
pub struct CheckpointMapping {
pub ty: ... |
use crate::{
ast_types::{
ast_base::AstBase,
result::ResultExpression,
},
utils::Ops,
};
use serde::Serialize;
use std::any::Any;
/* WHILE BLOCK */
#[derive(Clone, Debug, Serialize)]
pub struct While {
pub body: Vec<Box<dyn self::AstBase>>,
pub conditions: Vec<ResultExpression>,
}... |
extern crate env_logger;
use rand::Rng;
use liars::agent;
use liars::play;
use liars::playexpert;
use liars::start;
#[tokio::main]
async fn main() {
env_logger::init();
use clap::{Arg, SubCommand};
let app = clap::App::new("Liars lie")
.subcommand(
SubCommand::with_name("start")
... |
// Copyright 2019-2020 Parity Technologies (UK) Ltd.
// This file is part of Substrate.
// Substrate is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) a... |
fn fibo(result:&mut [i64], n : usize) -> i64 {
let mut temp : i64 = 0;
if n == 0 {
result[ n ] = temp;
return 0;
}
if n == 1 {
temp = 1;
result[ n ] = temp;
return 1;
}
if result[ n ] != 0 {
temp = result[ n ];
return temp;
... |
use std::f64::consts;
use rand::{Rng, SeedableRng, StdRng};
use std::mem;
use std::cmp;
use std::collections::HashMap;
use geom::{Ray,Scalar,Point2,Vector2};
use geom as g;
use nalgebra;
#[derive(Copy, Clone, Debug)]
pub struct LightProperties {
pub wavelength: Scalar, // um
pub intensity: Scalar
}
pub struc... |
use futures::stream::Stream;
use futures::TryStreamExt; // body.map_ok(|mut buf|
use warp::http::header::HeaderMap;
use warp::Filter;
use std::collections::HashMap;
#[macro_use]
extern crate log;
lazy_static::lazy_static! {
static ref ENDPOINTS: HashMap<&'static str, &'static str> = {
let mut endpoints =... |
pub mod io;
pub mod string;
|
use radmin::uuid::Uuid;
use serde::{Deserialize, Serialize};
use super::ContactInfo as Contact;
use crate::models::Address;
use crate::schema::contact_addresses;
#[derive(
Debug,
PartialEq,
Clone,
Serialize,
Deserialize,
Queryable,
Identifiable,
AsChangeset,
Associations,
)]
#[belo... |
use crate::config::{Config, KeyAction, Search as SearchConfig, SearchMatcher};
use crate::persistent::WindowState;
use anyhow::{Error, Result};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::fmt;
use std::io;
use std::path::{Path, PathBuf};
#[derive(Serialize)]
#[serde(tag = "kind")]
#[se... |
// Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in ... |
#[doc = "Register `FPUIMR` reader"]
pub type R = crate::R<FPUIMR_SPEC>;
#[doc = "Register `FPUIMR` writer"]
pub type W = crate::W<FPUIMR_SPEC>;
#[doc = "Field `FPU_IE` reader - FPU interrupt enable Set and cleared by software to enable the Cortex-M33 FPU interrupts FPU_IE\\[5\\]: inexact interrupt enable (interrupt dis... |
use matrix_nio::events::collections::all::{RoomEvent, StateEvent};
use matrix_nio::events::room::member::{MemberEvent, MembershipState};
use matrix_nio::events::room::message::{
MessageEvent, MessageEventContent, TextMessageEventContent,
};
use matrix_nio::Room;
use url::Url;
use crate::executor::spawn_weechat;
us... |
pub(crate) const ANDROID_MANIFEST_XML: &str = "AndroidManifest.xml";
pub(crate) const RESOURCES_ARSC: &str = "resources.arsc";
|
use super::{super::guild::GuildEntity, CategoryChannelEntity, MessageEntity};
use crate::{
repository::{GetEntityFuture, Repository},
utils, Backend, Entity,
};
use twilight_model::{
channel::{permission_overwrite::PermissionOverwrite, ChannelType, TextChannel},
id::{ChannelId, GuildId, MessageId},
};
... |
use parking_lot::RwLock;
use std::collections::{HashMap, VecDeque};
use std::hash::Hash;
use std::sync::Arc;
#[derive(Clone)]
pub struct NamedMap<K, V>
where
K: Clone + Eq + Hash,
V: Clone,
{
inner: Arc<RwLock<InnerMap<K, V>>>,
}
#[derive(Default)]
struct InnerMap<K, V>
where
K: Clone + Eq + Hash,
... |
#![feature(libc)]
extern crate libc;
mod ffi {
use libc::{c_char, c_int};
#[derive(Debug)]
#[repr(C)]
pub struct PgQueryError {
pub message: *const c_char, // exception message
pub funcname: *const c_char, // source function of exception (e.g. SearchSysCache)
pub filename: *co... |
extern crate proc_macro;
extern crate proc_macro2;
extern crate latte_verify;
extern crate latte_lib;
use latte_verify::*;
extern crate quote;
extern crate syn;
use proc_macro2::{Ident, Span};
// use regex::Regex;
use proc_macro::TokenStream;
mod utils;
use utils::*;
use quote::quote;
use syn::DeriveInput;
use latte_... |
use super::{ConnectionPath, ConsensusStatePath};
pub fn connection_path(_path: &ConnectionPath) -> String {
todo!()
}
pub fn consensus_state_path(_path: &ConsensusStatePath) -> String {
todo!()
}
|
#[doc = "Register `ETH_MTLTxQ1OMR` reader"]
pub type R = crate::R<ETH_MTLTX_Q1OMR_SPEC>;
#[doc = "Register `ETH_MTLTxQ1OMR` writer"]
pub type W = crate::W<ETH_MTLTX_Q1OMR_SPEC>;
#[doc = "Field `FTQ` reader - FTQ"]
pub type FTQ_R = crate::BitReader;
#[doc = "Field `FTQ` writer - FTQ"]
pub type FTQ_W<'a, REG, const O: u8... |
pub use super::crc32::compute_crc4_remainder_demo;
pub use super::crc32::compute_crc32_remainder;
#[test]
fn test_compute_crc4_demo() {
let crc4_rem = compute_crc4_remainder_demo();
println!("crc4 remainder: {:b}", crc4_rem);
}
#[test]
fn test_compute_crc32() {
assert_eq!(compute_crc32_remainder(0), 0);... |
use worker::schema::GeneratedSchema;
#[derive(Debug, Default)]
pub struct Entity<S: GeneratedSchema> {
pub bit_field: S::ComponentBitField,
pub chunk_index: usize,
pub index_in_chunk: usize,
}
impl<S: GeneratedSchema> Entity<S> {
pub fn new(
chunk_index: usize,
index_in_chunk: usize,
... |
use std::path::PathBuf;
use structopt::StructOpt;
use omnicolor_rust::palettes::*;
use omnicolor_rust::{Error, GrowthImageBuilder, PixelLoc, RGB};
#[derive(Debug, StructOpt)]
struct Options {
#[structopt(short = "o", long)]
output: PathBuf,
#[structopt(short, long, default_value = "1920")]
width: u3... |
#[no_mangle]
pub extern fn physics_single_chain_ufjc_morse_thermodynamics_isotensional_asymptotic_end_to_end_length(number_of_links: u8, link_length: f64, link_stiffness: f64, link_energy: f64, force: f64, temperature: f64) -> f64
{
super::end_to_end_length(&number_of_links, &link_length, &link_stiffness, &link_... |
use cfg_if::cfg_if;
use serde::{Deserialize, Serialize};
use std::os::unix::process::ExitStatusExt;
use std::process::{Command, Output};
use crate::Error;
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
pub enum ExecCode {
Line(String),
Multi(Vec<String>),
}
#[derive(Debug, Clone, Seriali... |
use log::{debug, trace};
use super::{astroplant_capnp, Error};
use capnp::serialize_packed;
use futures::channel::oneshot;
use futures::future::{BoxFuture, FutureExt};
use ratelimit_meter::{algorithms::NonConformanceExt, KeyedRateLimiter};
#[derive(Debug)]
pub enum ServerRpcRequest {
Version {
response: ... |
// Copyright 2018-2020 Parity Technologies (UK) Ltd.
// This file is part of Substrate.
// Substrate is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) a... |
use tower_http::trace::{MakeSpan, OnResponse};
use tracing::Level;
#[derive(Debug, Clone, Copy)]
pub(crate) struct Tracer;
impl<Body> MakeSpan<Body> for Tracer {
fn make_span(&mut self, request: &axum::http::Request<Body>) -> tracing::Span {
tracing::span!(
Level::INFO,
"request",
... |
use super::message::Error as MessageError;
use super::*;
use crossbeam_channel as channel;
use std::collections::VecDeque;
use std::io::{BufRead, BufReader};
use std::net::TcpStream;
use std::sync::{Arc, Mutex, RwLock};
use std::thread;
use std::time::Instant;
#[derive(Debug, PartialEq)]
pub enum Error {
CannotC... |
// Quiet diesel warnings https://github.com/diesel-rs/diesel/issues/1785
#![allow(proc_macro_derive_resolution_fallback)]
// Force these as errors so that they are not lost in all the diesel warnings
#![deny(unreachable_patterns)]
#![deny(unknown_lints)]
#![deny(unused_variables)]
#![deny(unused_imports)]
// Unused res... |
#![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 ActionsList {
#[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")]
pub next_link... |
fn main(){
let a = vec![1,1,2];
let var = &a[2];
print!("{}", var);
} |
use alloc::vec::Vec;
use core::cmp::Ordering;
use util::{impl_md_flow, uint_from_bytes, Hash};
use crate::consts::{ch, maj, parity, IV, K};
macro_rules! init_w {
( $w:expr, $( $t:expr ),* ) => {
$(
$w[$t] = $w[$t - 3] ^ $w[$t - 8] ^ $w[$t - 14] ^ $w[$t - 16];
)*
};
}
macro_rules!... |
//! Items related to receiving CBM 8032 frame data over serial.
use crate::fps::Fps;
use crate::vis;
use serialport::prelude::*;
use std::cell::RefCell;
use std::io::{self, Write};
use std::sync::atomic::{self, AtomicBool};
use std::sync::{mpsc, Arc};
const BAUD_RATE: u32 = 1_500_000;
const DATA_PER_BUFFER: u32 = 40;... |
//! This module contains a scheduler.
use std::cell::RefCell;
use std::collections::VecDeque;
use std::rc::Rc;
pub(crate) type Shared<T> = Rc<RefCell<T>>;
thread_local! {
static SCHEDULER: Rc<Scheduler> =
Rc::new(Scheduler::new());
}
pub(crate) fn scheduler() -> Rc<Scheduler> {
SCHEDULER.with(Rc::cl... |
//! Generate G-Code with funcational operation describing motion of the machine that the created gcode should produce
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn it_works() {
assert_eq!(2 + 2, 4);
}
#[test]
fn test_move_xy() {
let p = Point2d { x: 10.0, y: 5.0 };
... |
pub mod auto;
pub mod control;
pub mod drawable;
pub mod member;
pub mod container;
pub mod container_multi;
pub mod container_single;
pub mod has_image;
pub mod has_label;
pub mod has_layout;
pub mod has_native_id;
pub mod has_orientation;
pub mod has_progress;
pub mod has_size;
pub mod has_visibility;
pub mod clic... |
#[cfg(test)]use error::*;
#[cfg(test)]use engine;
#[cfg(test)]use engine::*;
#[cfg(test)]use il;
#[cfg(test)]use loader;
#[cfg(test)]use loader::Loader;
#[cfg(test)]use platform::*;
#[cfg(test)]use std::path::Path;
#[cfg(test)]use std::sync::Arc;
#[cfg(test)]
fn simple_0_test () -> Result<Vec<u8>> {
// let filena... |
use core::any::Any;
use crate::{Asset, AssetInfo, ResolverContext, ResolverError};
mod wrapper;
/// Trait for the asset resolution system. An asset resolver is
/// responsible for resolving asset information (including the asset's
/// physical path) from a logical path.
pub trait Resolver {
/// Configures the re... |
use crate::Result;
use byteorder::*;
#[derive(Copy, Clone)]
pub enum Phdr_type {
NULL = 0x0,
LOAD = 0x1,
DYNAMIC = 0x2,
INTERP = 0x3,
NOTE = 0x4,
SHLIB = 0x5,
PHDR = 0x6,
TLS = 0x7,
LOOS = 0x60000000,
HIOS = 0x6FFFFFFF,
LOPROC = 0x70000000,
HIPROC = 0x7FFFFFFF,
//... |
#[macro_use]
extern crate bencher;
use bencher::Bencher;
use vowpalwabbit;
fn uniform_hash_10chars(bench: &mut Bencher) {
bench.iter(|| vowpalwabbit::hash::uniform_hash(b"abcdefghij", 0))
}
fn uniform_hash_100chars(bench: &mut Bencher) {
bench.iter(|| {
vowpalwabbit::hash::uniform_hash(b"abcdefghija... |
use std::collections::BTreeMap;
use std::io;
use std::io::prelude::*;
use std::fs::File;
use rustc_serialize::json::{ToJson, Json};
use super::super::engine::{CheckResult, CheckSuiteResult, PropertyResult};
use super::Report;
pub struct JsonReport<'a> {
check_suite_result: &'a CheckSuiteResult<'a>,
filename: ... |
use super::*;
/// Structure that saves the reader specific to writing and reading a nodes csv file.
///
/// # Attributes
#[derive(Clone)]
pub struct EdgeFileReader {
pub(crate) reader: CSVFileReader,
pub(crate) sources_column_number: usize,
pub(crate) destinations_column_number: usize,
pub(crate) edge_t... |
// Based on stuff from: https://www.snip2code.com/Snippet/1473242/Rust-Hexdump
use std::io::{self, Read, BufRead};
use std::cmp;
use std::fmt::{self, Write};
const HR_BYTES_PER_LINE: usize = 16;
pub struct HexReader<T> {
inner: T,
buf: String,
buf_pos: usize,
line_count: usize,
}
impl<T: Read> HexRe... |
#[doc = r"Register block"]
#[repr(C)]
pub struct RegisterBlock {
_reserved0: [u8; 8144usize],
#[doc = "0x1fd0 - AXIMC peripheral ID4 register"]
pub periph_id_4: PERIPH_ID_4,
#[doc = "0x1fd4 - AXIMC peripheral ID5 register"]
pub periph_id_5: PERIPH_ID_5,
#[doc = "0x1fd8 - AXIMC peripheral ID6 reg... |
use std::{
collections::HashMap,
time::{Duration, Instant},
};
use hyper::{body::Buf, client::HttpConnector, Client as HyperClient};
#[cfg(feature = "with-openssl")]
use hyper_openssl::HttpsConnector;
#[cfg(feature = "with-rustls")]
use hyper_rustls::HttpsConnector;
use jsonwebtoken::{Algorithm, DecodingKey, V... |
extern crate wasm_bindgen;
use wasm_bindgen::prelude::*;
extern crate qrcode;
use qrcode::render::svg;
use qrcode::QrCode;
use qrcode::types::QrError;
/// Generate a QR code from the respective data. Returns a string containing the SVG string
/// appropriate to be saved to a file or rendered to a DOM tree.
fn qrcode<... |
//! # SQLite Driver
mod schema;
use crate::driver;
use diesel::prelude::*;
use diesel::r2d2::ConnectionManager;
embed_migrations!("migrations/sqlite");
#[derive(Clone)]
pub struct Driver {
pool: r2d2::Pool<ConnectionManager<SqliteCOnnection>>,
}
type PooledConnection = r2d2::PooledConnection<ConnectionManager<S... |
use std::io;
fn main() {
println!("Enter the words you want to convert to pig latin.");
println!("Press Enter or Ctrl-D at empty line to exit.");
loop {
let mut word = String::new();
io::stdin().read_line(&mut word)
.expect("Failed to read line.");
if word.trim().is_e... |
use gtk::prelude::{
CellLayoutExt, CellRendererExt, CellRendererTextExt, GtkListStoreExtManual, GtkWindowExt,
GtkWindowExtManual, TreeModelExt, TreeViewColumnExt, TreeViewExt, WidgetExt,
};
use gtk::{self, AdjustmentExt, BoxExt, ButtonExt, ContainerExt, LabelExt, ScrolledWindowExt};
use sysinfo::{self, Network... |
pub mod ident;
pub mod types;
pub mod hash; |
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 ptr_name = Ident::new(name_str.as_str(), name.span());
let new = Ident::new(format!... |
fn main() {
let mut v = vec![1, 2, 3, 4, 5];
let first = &v[0];
v.push(6); // error
}
|
// SPDX-License-Identifier: GPL-2.0
//! An I/O Project: Building a Command Line Program
use super::ch09::Error;
use std::{fs, io::ErrorKind};
/// Config to capture command line arguments for the I/O project.
///
/// # Examples
/// ```
/// use the_book as book;
/// use book::ch09::Error;
/// use book::ch12::Config;
///... |
use std::collections::HashMap;
/// Checks API calling code.
///
/// Wraps https://api.slack.com/methods/api.test
#[derive(Debug, Clone, Serialize, new)]
pub struct TestRequest<'a> {
/// Error response to return
#[new(default)]
error: Option<&'a str>,
/// example property to return
#[new(default)]
... |
use std::ops::*;
#[repr(C)]
#[derive(Debug, Copy, Clone)]
pub struct Vec2 { pub x: f32, pub y: f32 }
impl Vec2 {
pub fn new(x: f32, y: f32) -> Vec2 {
Vec2 { x: x, y: y }
}
pub fn zero() -> Vec2 { Vec2::new(0.0, 0.0) }
pub fn from_slice(s: &[f32]) -> Vec2 {
assert!(s.len() >= 2);
Vec2::new(s[0], s[1])
}
... |
//! In this example we will implement something similar
//! to `kubectl get all --all-namespaces`.
use k8s_openapi::apimachinery::pkg::apis::meta::v1::APIResourceList;
use kube::{
api::{Api, DynamicObject, GroupVersionKind, ResourceExt},
Client,
};
use log::{info, warn};
#[tokio::main]
async fn main() -> anyh... |
use feature::Feature;
pub struct Suite {
features: Vec<Feature>,
}
impl Suite {
pub fn add_feature(&mut self, feature: Feature) {
self.features.push(feature);
}
}
|
#![allow(clippy::collapsible_match)]
#![allow(clippy::single_match)]
use std::cell::RefCell;
mod frame_counter;
mod graphics;
mod shader_compilation;
mod vertex;
use graphics::GraphicsState;
fn main() {
{
fern::Dispatch::new()
.format(|out, message, record| {
out.finish(forma... |
/*
* 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.
*/
use s... |
use crate::huffman::Huffman;
use crate::lz77::LZ77;
#[derive(Debug)]
pub struct Deflate {
lz77: LZ77,
}
impl Deflate {
pub fn new(window_size: usize, dictionary_size: usize) -> Deflate {
Deflate {
lz77: LZ77::new(window_size, dictionary_size),
}
}
pub fn compress<S>(&mut s... |
use crate::errors::validation::{auth::ErrorVariants, ValidationError};
use crate::models::user::UserInsert;
impl super::Validate for UserInsert {
/// Validates a user registration request body
fn validate(&self) -> Option<ValidationError> {
let dn_len = self.displayname.len();
let un_len = self... |
//! Wrappers that abstracts references (or pointers) and owned data accesses.
// The serialization is towards owned, allowing to serialize pointers without troubles.
use alloc::{boxed::Box, vec::Vec};
use core::{clone::Clone, fmt::Debug};
use serde::{Deserialize, Deserializer, Serialize, Serializer};
/// Trait to con... |
use std::fmt::Write;
use crate::MetadataError;
use librespot_core::{Error, Session};
pub type RequestResult = Result<bytes::Bytes, Error>;
#[async_trait]
pub trait MercuryRequest {
async fn request(session: &Session, uri: &str) -> RequestResult {
let mut metrics_uri = uri.to_owned();
let separa... |
use std::fmt::{Display, Formatter};
use std::result::{Result};
use std::rc::{Rc};
use std::fmt;
pub type Literal = String;
use position::*;
use utils::*;
use transform::*;
use symbol::*;
use context::*;
type P = Position;
#[derive(Debug)]
pub enum Tree {
AssignByName(P, SymbolName, Box<Tree>),
IdentByName(P, Sy... |
//! TOML blog configuration
use super::{
env_or_empty, load_config,
vendors::{FacebookConfig, GoogleConfig, MapBoxConfig},
ReadsEnv,
};
use crate::{deserialize::regex_string, models::Location, tools::Pairs};
use regex::Regex;
use serde::Deserialize;
use std::path::Path;
/// Replacement camera, lens and so... |
use rand::Rng;
#[derive(PartialEq, Clone, Copy)]
pub enum State {
MainMenu,
Game,
Lost,
Quit,
}
#[derive(PartialEq)]
pub enum Direction {
Up,
Down,
Right,
Left,
}
pub struct Snake {
pub body: Vec<(i32, i32)>,
pub direction: Direction,
pub growth: u32,
}
impl Snake {
/... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.