text stringlengths 8 4.13M |
|---|
#[doc = "Reader of register C1TCR"]
pub type R = crate::R<u32, super::C1TCR>;
#[doc = "Writer for register C1TCR"]
pub type W = crate::W<u32, super::C1TCR>;
#[doc = "Register C1TCR `reset()`'s with value 0"]
impl crate::ResetValue for super::C1TCR {
type Type = u32;
#[inline(always)]
fn reset_value() -> Sel... |
mod handler;
mod model;
pub mod route;
|
use std::io;
use std::convert::AsRef;
use std::str::FromStr;
use std::path::PathBuf;
use std::default::Default;
use lazy_init::Lazy;
use crate::{State, Technology};
use crate::platform::traits::BatteryDevice;
use super::sysfs;
const DESIGN_VOLTAGE_PROBES: [&str; 4] = [
"voltage_max_design",
"voltage_min_desi... |
#![feature(core)]
use std::mem::transmute;
use std::raw::TraitObject;
trait Passable {
fn just_a_thing(&self) -> bool { false }
}
impl Passable for i32 {}
fn main() {
let i = Box::new(42i32);
let j = &*i as &Passable;
let k = unsafe { transmute::<&Passable, TraitObject>(j) };
let l = unsaf... |
mod lib;
use lib::config::CONFIG_FILE;
fn main() {
println!("{}", CONFIG_FILE);
}
|
use crate::configuration::Configuration;
use crate::domain_cmd::DomainCmd;
use crate::http;
type Error = Box<dyn std::error::Error>;
type Result<T, E = Error> = std::result::Result<T, E>;
pub async fn call(form : DomainCmd) -> Result<()> {
match &form {
DomainCmd::Create{auth_param, ..} =>
htt... |
use bigdecimal::BigDecimal;
use num::BigInt;
use std::collections::BTreeMap;
mod traits;
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)]
pub enum AST {
EmptyStatement,
//
Program(Vec<AST>),
//
/// function call
/// function(name, *args, **kwargs)
Function(Symbol, Vec<Parameter>),
... |
#![feature(test)]
#![feature(rand)]
extern crate test;
extern crate rand;
extern crate merkle;
extern crate ring;
use test::Bencher;
use rand::Rng;
use ring::digest::{Algorithm, SHA512};
use merkle::MerkleTree;
#[allow(non_upper_case_globals)]
static digest: &'static Algorithm = &SHA512;
#[bench]
fn bench_small... |
// Copyright 2017 Serde Developers
//
// 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 your
// option. This file may not be copied, modified, or distributed
// except accordin... |
#![allow(unused_imports)]
#![allow(dead_code)]
#![allow(unused_variables)]
use sodiumoxide;
use serde::{Serialize, Deserialize};
pub static SOCKET_PATH: &'static str = "/tmp/loopback-socket";
#[derive(Serialize, Deserialize, Debug)]
pub enum MyRequest {
ReqCryptoBoxGenKeypair,
ReqCryptoBoxGenNonce,
ReqCry... |
use oasis_contract_sdk::{
self as sdk,
env::Env,
types::{
message::{Message, NotifyReply},
InstanceId,
},
};
use oasis_contract_sdk_storage::{cell::Cell, map::Map};
use oasis_contract_sdk_types::address::Address;
use crate::{
Error, Event, InitialBalance, ReceiverRequest, Request, R... |
use tokio::sync::{mpsc, broadcast};
use tokio_stream::wrappers::ReceiverStream;
use tonic::{Request, Response, Status};
use stream_mod::{HelloReply, HelloRequest, GetBlocksRequest, GenericDataProto, streamout_server::Streamout};
pub mod stream_mod {
tonic::include_proto!("chaindata");
}
#[derive(Debug)]
pub str... |
use std::io;
use std::io::Write;
fn main() {
print!("Please write number of clouds: ");
io::stdout().flush().unwrap();
let mut input_steps = String::new();
io::stdin().read_line(&mut input_steps).expect("Failed to read from stdin");
let clouds_amount = input_steps.trim().parse::<usize>().unwrap(... |
pub mod neural_network;
pub mod simulation; |
use crate::compiling::{ImportEntryStep, InsertMetaError};
use crate::{
Id, IrError, IrErrorKind, ParseError, ParseErrorKind, ResolveError, ResolveErrorKind, Spanned,
};
use runestick::{CompileMeta, Item, Location, Visibility};
use thiserror::Error;
error! {
/// An error raised during querying.
#[derive(Deb... |
#[path = "with_float/with_empty_list_options.rs"]
pub mod with_empty_list_options;
#[path = "with_float/with_proper_list_options.rs"]
pub mod with_proper_list_options;
// `without_proper_list_options_errors_badarg` in unit tests
|
use std::sync::Arc;
use async_trait::async_trait;
use ingester_query_grpc::IngesterQueryRequest;
use trace::{ctx::SpanContext, span::SpanRecorder};
use crate::ingester::flight_client::{Error as FlightClientError, IngesterFlightClient, QueryData};
#[derive(Debug)]
pub struct InvalidateOnErrorFlightClient {
/// Th... |
fn main() {
let v1:Option<i32> = None;
let v2:Option<i32> = Some(10);
match v1 {
None => println!("Option value is None"),
Some(x) => println!("x = {}", x),
}
match v2 {
None => println!("Option value is None"),
Some(x) => println!("x = {}", x),
}
}
|
//! Metrics related utilities
use super::{
builder::{stage::Method, Request},
SequencerError,
};
use futures::Future;
use pathfinder_common::BlockId;
const METRIC_REQUESTS: &str = "gateway_requests_total";
const METRIC_FAILED_REQUESTS: &str = "gateway_requests_failed_total";
const METRICS: [&str; 2] = [METRIC_... |
pub struct Solution;
impl Solution {
pub fn can_complete_circuit(gas: Vec<i32>, cost: Vec<i32>) -> i32 {
let mut balance = 0;
let mut min = 0;
let mut i_min = 0;
for i in 0..gas.len() {
balance += gas[i];
balance -= cost[i];
if balance < min {
... |
use druid::{
theme,
Color, Env, Key,
};
use theme::FOREGROUND_DARK;
pub const HOT_COLOUR: Key<Color> = Key::new("thomhuds.hot_colour");
pub const RED: Key<Color> = Key::new("thomhuds.red");
pub const PALE_RED: Key<Color> = Key::new("thomhuds.pale_red");
pub const GREEN: Key<Color> = Key::new("thomhuds.green");... |
/*!
A DFA-backed `Regex`.
This module provides [`Regex`], which is defined generically over the
[`Automaton`] trait. A `Regex` implements convenience routines you might have
come to expect, such as finding the start/end of a match and iterating over
all non-overlapping matches. This `Regex` type is limited in its capa... |
pub mod taunt_system;
use amethyst::core::ecs::{Entity, Component, DenseVecStorage};
#[derive(Default)]
pub struct TauntComponent;
impl Component for TauntComponent {
type Storage = DenseVecStorage<Self>;
}
#[derive(Default)]
pub struct Taunt {
pub(crate) face: Option<Entity>,
}
|
use super::*;
#[test]
fn with_less_than_byte_len_returns_binary_prefix_and_suffix_bitstring() {
with_process(|process| {
let binary = bitstring!(1, 2 :: 2, &process);
let position = process.integer(1);
assert_eq!(
result(process, binary, position),
Ok(process.tuple_... |
#[macro_use]
extern crate lazy_static;
extern crate regex;
mod recipe;
use std::collections::HashSet;
use std::env::current_dir;
use std::ffi::OsStr;
use std::fs::{read_dir, File};
use std::io::prelude::*;
use std::io::{self, BufReader};
use regex::Regex;
use recipe::beautify_jsons;
fn main() -> io::Result<()> {
... |
// Copyright 2019 The vault713 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 applicable law or a... |
use actix_web::{middleware, web, App, HttpRequest, HttpServer, Responder};
use env_logger;
use std::{env, io};
mod handlers;
// this function could be located in different module
fn config(cfg: &mut web::ServiceConfig) {
cfg
.service(handlers::hello)
.service(handlers::get_again)
.service(handlers::get_... |
#![allow(unused_imports)]
#![allow(unused_variables)]
#![allow(dead_code)]
mod paras;
use ndarray::prelude::*;
use ndarray::Array;
use typenum::{U16, U1024};
fn main() {
// set flags
// fi_flag = 1 -> high fidelity model (full Nguyen)
// fi_flag = 1 -> low fidelity model (Stevens Lewis reduced)
let... |
extern crate cry;
fn main() {
println!("Cry \"Havoc!\", and let slip the dogs of war.");
}
|
#![deny(warnings)]
#![warn(rust_2018_idioms)]
use futures_util::future::join;
use hyper::service::{make_service_fn, service_fn};
use hyper::{Body, Request, Response, Server};
static INDEX1: &[u8] = b"The 1st service!";
static INDEX2: &[u8] = b"The 2nd service!";
async fn index1(_: Request<Body>) -> Result<Response<B... |
use mio::*;
use mio::net::*;
use mio::net::udp::*;
use mio::buf::{RingBuf, SliceBuf};
use std::str;
use super::localhost;
use std::old_io::net::ip::{Ipv4Addr};
use mio::event as evt;
type TestEventLoop = EventLoop<usize, ()>;
const LISTENER: Token = Token(0);
const SENDER: Token = Token(1);
pub struct UdpHandler {
... |
use std::rc::Rc;
use crate::error::Result;
use crate::externs::PythonScripts;
use crate::nodes::NodeRoot;
use crate::tensor::IRData;
pub use n3_program::code::*;
pub trait AddScripts {
fn add_scripts(&self, root: &NodeRoot, scripts: &mut PythonScripts) -> Result<()>;
}
pub trait DataFromIR {
fn from_ir(data... |
use std::{collections::HashMap, fs};
fn main() {
let filename = "inputs/q10_input.txt";
let contents = fs::read_to_string(filename).expect("Could not read the file");
let mut ratings = contents
.lines()
.map(|x| x.parse().unwrap())
.collect::<Vec<i32>>();
ratings.sort_unstable... |
#[doc = r"Value read from the register"]
pub struct R {
bits: u8,
}
#[doc = r"Value to write to the register"]
pub struct W {
bits: u8,
}
impl super::TXTYPE5 {
#[doc = r"Modifies the contents of the register"]
#[inline(always)]
pub fn modify<F>(&self, f: F)
where
for<'w> F: FnOnce(&R, &'... |
mod louds;
mod louds_builder;
mod louds_index;
mod louds_node_num;
use crate::{SuccinctBitVector, SuccinctBitVectorBuilder};
/// LOUDS (Level-Order Unary Degree Sequence).
///
/// This class can handle tree structure of virtually **arbitrary number of nodes**.
///
/// In fact, _N_ (number of nodes in the tree) is des... |
use brew_calculator::units::*;
use serde::Deserialize;
#[derive(Deserialize, Debug, PartialEq)]
pub struct Boil {
pub pre_volume: Liters,
pub boil_time: Minutes,
}
impl Boil {
pub(crate) fn from_beerxml_recipe(boil_size: Liters, boil_time: Minutes) -> Self {
Self {
pre_volume: boil_siz... |
use structopt::StructOpt;
#[derive(Debug, Clone, StructOpt)]
/// Ported from https://github.com/prasmussen/glot-code-runner
pub struct CmdLineOpt {
#[structopt(short = "w", long = "work-dir")]
/// Working directory, if not specified, will use a temporary directory.
pub work_dir: Option<String>,
#[stru... |
use lock_api::{
GetThreadId, RawMutex, RawRwLock, RawRwLockDowngrade, RawRwLockRecursive, RawRwLockUpgrade,
RawRwLockUpgradeDowngrade,
};
use std::{cell::Cell, num::NonZeroUsize};
pub struct RawCellMutex {
locked: Cell<bool>,
}
unsafe impl RawMutex for RawCellMutex {
#[allow(clippy::declare_interior_m... |
// This file is part of linux-epoll. It is subject to the license terms in the COPYRIGHT file found in the top-level directory of this distribution and at https://raw.githubusercontent.com/lemonrock/linux-epoll/master/COPYRIGHT. No part of linux-epoll, including this file, may be copied, modified, propagated, or distri... |
use crate::lib::{default_sub_command, file_to_lines, parse_lines, parse_usize, Command};
use anyhow::Error;
use clap::{value_t_or_exit, values_t_or_exit, App, Arg, ArgMatches, SubCommand};
use nom::{
branch::alt,
character::complete,
combinator::map,
multi::many1,
sequence::{preceded, tuple},
};
use... |
// This file is automatically @generated by awto-cli v0.1.1
pub use sea_orm;
include!(concat!(env!("OUT_DIR"), "/app.rs"));
|
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... |
use std::ops::Deref;
use super::*;
pub struct ReadBufferMap<'a, T, Kind, Acces>
where
T: Sized + BufferData,
Kind: BufferType,
Acces: BufferAcces
{
pub(crate) buff: &'a Buffer<T, Kind, Acces>,
pub(crate) buffer: &'a [T]
}
impl<T, Kind, Acces> Deref for ReadBufferMap<'_, T, Kind, Acces>
where
... |
//! Shared helpers for windows programming.
use windows_sys::Windows::Win32::SystemServices as ss;
mod event;
pub use self::event::Event;
cfg_events_driver! {
#[doc(inherit)]
pub use crate::runtime::events::AsyncEvent;
}
/// Trait that indicates a type that encapsulates an event.
pub trait RawEvent {
///... |
use crate::components::prelude::{CheckpointId, FeatureType};
use deathframe::geo::Vector;
#[derive(Clone, Deserialize, Serialize)]
pub struct CheckpointData {
pub position: Vector,
pub features: Vec<FeatureType>,
pub checkpoints: Vec<CheckpointId>,
}
#[derive(Default)]
pub struct CheckpointRes(pub O... |
use super::symbol::*;
use std::result::Result;
///
/// Possible errors from a script call
///
#[derive(Clone, PartialEq, Debug)]
pub enum FloScriptError {
/// The requested feature is not available (with description as to why)
Unavailable(String),
/// A requested symbol was not defined
UndefinedSymbo... |
use std::collections::HashMap;
use std::io::Write;
use serialize::json::ToJson;
use template::{Template, TemplateError};
use render::{Renderable, RenderError, RenderContext};
use helpers::{HelperDef};
use context::{Context};
use helpers;
use support::str::StringWriter;
pub struct Registry {
templates: HashMap<St... |
//! Module that contains known test keys.
// TODO: Should be derived from seeds once implemented in the Rust version.
/// Define an ed25519 test key.
macro_rules! test_key_ed25519 {
($doc:expr, $name:ident, $pk:expr) => {
#[doc = " Test key "]
#[doc=$doc]
#[doc = "."]
pub mod $name... |
//! Parser for Ulysses exported MarkDown bundle.
//!
//! Extract Post from a MarkDown bundle by iterating Blog.
//!
//! # Example
//!
//! ```
//! use parser::Blog;
//! let blog = Blog::from(&data);
//!
//! for post in blog {
//! println("{}", post.title);
//! }
//! ```
use linter::{Linter, Scripts};
use pulldown_cm... |
use swayipc::{BindingEvent, Connection, Event, EventType};
use std::sync::{Arc, Mutex};
use std::collections::{HashSet, HashMap};
use std::thread;
use std::boxed::Box;
use std::error::Error;
use std::time::Duration;
use log;
const SWAY_COMMAND_PRESS: &str = "nop press";
const SWAY_COMMAND_RELEASE: &str = "nop release"... |
use clap::Parser;
use parquet_wasm::arrow1::reader::read_parquet;
use std::fs;
use std::path::PathBuf;
use std::process;
#[derive(Parser, Debug)]
#[clap(author, version, about, long_about = None)]
struct Args {
/// Path to input file
#[clap(short, long)]
input_file: PathBuf,
/// Path to output file
... |
#![feature(llvm_asm)]
fn f() {}
fn main() {
unsafe {llvm_asm!( "" :: "r"(f))}
}
|
#[doc = "Reader of register OPTR"]
pub type R = crate::R<u32, super::OPTR>;
#[doc = "Writer for register OPTR"]
pub type W = crate::W<u32, super::OPTR>;
#[doc = "Register OPTR `reset()`'s with value 0"]
impl crate::ResetValue for super::OPTR {
type Type = u32;
#[inline(always)]
fn reset_value() -> Self::Typ... |
#![allow(dead_code, unused_variables)]
use crate::cells::Cell;
pub struct Spore {
x: bool
}
pub struct Sporangium {
x: bool
}
pub fn produce_spore(factory: &mut Sporangium) -> Spore {
Spore { x: false}
}
fn recombine(parent: &mut Cell) {} |
use std::collections::HashMap;
use std::io;
use std::io::Read;
use regex::Regex;
fn main() {
let mut input = String::new();
io::stdin().read_to_string(&mut input).unwrap();
let line_regex = Regex::new(r"(?m)^([a-z ]+) bags contain (.+)\.$", ).unwrap();
let inner_regex = Regex::new(r"(\d+) ([a-z ]+) ba... |
use crate::models::file_stores::FileStores;
use crate::models::shop::{Shop, ShopForm};
use crate::views;
use maud::Markup;
use rocket::request::Form;
use rocket::response::Redirect;
use rocket::State;
use std::iter::FromIterator;
#[get("/")]
pub fn list(store: State<FileStores>) -> Markup {
use crate::models::item_... |
use cortex_m::interrupt::free;
use stm32f4xx_hal::{interrupt, stm32 as stm32f401};
use crate::event::InterruptEvent;
use crate::EVENT_QUEUE;
#[derive(Debug, Clone, Copy)]
pub struct ClockState {
pub hour: u8,
pub minute: u8,
pub second: u8,
pub weekday: u8,
pub day: u8,
pub month: u8,
pub ... |
//! Domain separation context helpers.
use std::sync::Mutex;
use once_cell::sync::Lazy;
use oasis_core_runtime::common::{crypto::hash::Hash, namespace::Namespace};
const CHAIN_CONTEXT_SEPARATOR: &[u8] = b" for chain ";
static CHAIN_CONTEXT: Lazy<Mutex<Option<Vec<u8>>>> = Lazy::new(Default::default);
/// Return the... |
use super::{CHUNK_SIZE, MapElement};
/// Map Chunk
#[derive(Debug, Clone)]
pub struct Chunk
{
data: Vec<MapElement>
}
impl Chunk
{
/// Create a new, empty chunk
pub fn new() -> Self
{
Self
{
data: vec![MapElement::default(); CHUNK_SIZE * CHUNK_SIZE]
}
}
///... |
use crate::{
internal::{factorial, fibonacci},
AST,
};
#[test]
fn fibonacci_int() {
let input = AST::integer(0);
let output = AST::integer(0);
assert_eq!(fibonacci(&input).unwrap(), output);
let input = AST::integer(10u128);
let output = AST::integer(55u128);
assert_eq!(fibonacci(&inpu... |
pub struct BPlusTree<'a> {
root: Option<Box<Node<'a>>>,
first_leaf: Option<Node<'a>>,
m: u8,
}
struct Node<'a> {
parent: Option<Box<Node<'a>>>,
degree: u8,
max_degree: u8,
min_degree: u8,
keys: Vec<u8>,
children: Option<Vec<&'a mut LeafNode>>,
}
struct LeafNode {
dict: Vec<Dic... |
use iron::prelude::*;
use iron::{status, Handler};
use api::rocketchat::WebhookMessage;
use api::MatrixApi;
use config::Config;
use handlers::rocketchat::Forwarder;
use log::{self, IronLogger};
use middleware::RocketchatToken;
use models::{ConnectionPool, RocketchatServer, VirtualUser};
/// Rocket.Chat is an endpoint... |
#[doc = "Writer for register IFCR"]
pub type W = crate::W<u32, super::IFCR>;
#[doc = "Register IFCR `reset()`'s with value 0"]
impl crate::ResetValue for super::IFCR {
type Type = u32;
#[inline(always)]
fn reset_value() -> Self::Type {
0
}
}
#[doc = "Write proxy for field `TEIF8`"]
pub struct TE... |
#![cfg_attr(not(feature = "std"), no_std)]
use frame_support::codec::{Decode, Encode};
use frame_support::traits::Vec;
use frame_support::{decl_error, decl_event, decl_module, decl_storage, dispatch, traits::Get};
use frame_system::ensure_signed;
use frame_support::traits::Box;
use sp_runtime::traits::Hash;
#[cfg(tes... |
use std::io::Write;
fn main() -> Result<(), lexopt::Error> {
let args = Args::parse()?;
let stdout = std::io::stdout();
let mut stdout = stdout.lock();
for fixed in 0..16 {
let style = style(fixed, args.layer, args.effects);
let _ = print_number(&mut stdout, fixed, style);
if f... |
use crate::measure;
use std::fmt::Display;
use std::io::BufRead;
use std::iter;
use std::slice::Iter;
pub fn run(input: impl BufRead) {
let lines = read_input(input);
measure::duration(|| {
let (mut stacks, moves) = read_instructions(&lines);
rearrange_crates_single(&mut stacks, &moves);
... |
use combine::{count, easy::Stream, token, Parser};
pub fn run(path: &str) {
let input = std::fs::read_to_string(path).expect("Couldn't read input file");
let node = parse_node()
.easy_parse(&input)
.expect("Couldn't parse nodes")
.0;
println!("Day 8, part 1: {}", node.sum_metadata... |
#[doc = r"Register block"]
#[repr(C)]
pub struct RegisterBlock {
#[doc = "0x00 - SHAMD5 DMA Interrupt Mask"]
pub shamd5_dmaim: SHAMD5_DMAIM,
#[doc = "0x04 - SHAMD5 DMA Raw Interrupt Status"]
pub shamd5_dmaris: SHAMD5_DMARIS,
#[doc = "0x08 - SHAMD5 DMA Masked Interrupt Status"]
pub shamd5_dmamis:... |
use crate::engine::runtime::{OptMap, parser_tokens};
//use test::Bencher;
//#[bench]
//fn bench_is_opt(b: &mut Bencher) {
//
//
// let optMap=OptMap::new();
// b.iter(|| {
// optMap.is_opt("+");
// });
//}
//
//#[bench]
//fn bench_parser_tokens(b: &mut Bencher) {
// let m= &OptMap::new();
// b.it... |
// Copyright 2020-2021, The Tremor Team
//
// 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 agr... |
extern crate lambda;
use lambda::*;
fn main() {
//let program = "(x. y. x - y) 3 2";
let program =
"(def.
def (t.f.t) true.
def (t.f.f) false.
def (a.a false true) not.
def (a.b. a true b) or.
def (a.b. a b false) and.
def (f.x. x) 0.
def (f.x. f x) 1.
def (f.x. f (... |
mod day1;
mod day2;
mod day3;
fn main() {
println!("Let's do this! Advent 2016!!!");
println!("day 1, puzzle 1: {}", day1::puzzle1());
println!("day 1, puzzle 2: {}", day1::puzzle2());
println!("day 2, puzzle 1: {}", day2::puzzle1());
println!("day 2, puzzle 2: {}", day2::puzzle2());
println!("... |
use procon_reader::ProconReader;
fn main() {
let stdin = std::io::stdin();
let mut rd = ProconReader::new(stdin.lock());
let n: usize = rd.get();
let m: usize = rd.get();
let inf = std::u64::MAX / 2;
let mut d = vec![vec![inf; n]; n];
for v in 0..n {
d[v][v] = 0;
}
for _ in... |
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... |
extern crate rand;
#[path="geom.rs"]
mod geom;
use glium::Surface;
pub struct Cylinder {
vbo: (glium::VertexBuffer<geom::Position>, glium::VertexBuffer<geom::Normal>), // 顶点缓冲
waves: [[f32; 3]; 440],
vertex: Vec<geom::Position>,
position: [[f32;4];4], // 位置坐标矩阵
rotate: [[f32;... |
use alloc::vec::Vec;
use eosio::{
AccountName, Action, DataStream, NumBytes, Read, ReadError, Transaction,
TransactionId, Write, WriteError,
};
/// This method will abort execution of wasm without failing the contract. This is used to bypass all cleanup / destructors that would normally be called.
#[inline]
pu... |
use super::util::{mmio_write, mmio_read, enable_irq_no};
#[allow(dead_code)]
mod constval {
// The GPIO registers base address.
pub const GPIO_BASE: u32 = 0x3F200000; // for raspi2 & 3, 0x20200000 for raspi1
// The offsets for reach register.
// Controls actuation of pull up/down to ALL GPIO pins.
pub const GPPUD: ... |
use std::{marker::PhantomData, pin::Pin};
use async_stream::stream;
use futures_util::{stream::Stream, StreamExt};
use raw::{ClientMessage, ClientPayload, GraphQLReceiver, GraphQLSender, Payload, ServerMessage};
use serde::de::DeserializeOwned;
use tokio::sync::{broadcast, mpsc};
use tokio_tungstenite::{connect_async,... |
use std::fmt;
use std::mem::MaybeUninit;
use std::ops::Deref;
use std::os;
use std::os::raw::c_char;
use anyhow::anyhow;
use firefly_util as util;
use firefly_util::emit::Emit;
use super::*;
use crate::support::{OwnedStringRef, StringRef};
use crate::Context;
extern "C" {
type MlirModule;
}
/// This type repre... |
// Copyright 2023 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 ... |
//https://leetcode.com/problems/unique-morse-code-words/
use std::collections::HashMap;
impl Solution {
pub fn unique_morse_representations(words: Vec<String>) -> i32 {
let lettre_to_morse = [".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",".--.","--.-",".-.","..."... |
fn main() {
// We can use a function previously defined as a function pointer
{
fn add_one(x: i32) -> i32 {
x + 1
}
fn do_twice(f: fn(i32) -> i32, arg: i32) -> i32 {
f(arg) + f(arg)
}
let answer = do_twice(add_one, 5);
println!("The answer is: {}", answer);
// Here is a la... |
use crate::displays::{DisplayServer, Event};
use crate::config::Config;
use crate::window::{WindowType, Geometry, Window};
use std::rc::Rc;
use xcb_util::ewmh;
use xcb_util::keysyms::KeySymbols;
use crate::keys::xcb_keys::XcbKeyCombo;
use std::cell::RefCell;
use std::ops::Deref;
use futures::Stream;
use futures::task::... |
use crate::texture::{Texture, SolidColor};
use crate::sphere::random_in_unit_sphere;
use crate::vec3::{Point3, Vec3};
use crate::sphere::random_unit_vector;
use crate::ray::Ray;
use crate::hittable::HitRecord;
use crate::color::Color;
pub trait Material {
fn emitted(&self, _u: f32, _v: f32, _p: &Point3) -> Color {... |
extern crate rand;
use std::collections::HashSet;
use rand::Rng;
use super::Point;
use super::Direction;
use super::super::grid::Grid;
use super::MazeGenerator;
pub struct Prim
{
filled: HashSet<Point>,
frontier: HashSet<Point>,
}
impl MazeGenerator for Prim
{
fn generate<T: Grid>(grid: &mut T)
{
... |
use crate::file_util::read_lines;
#[derive(Debug)]
struct Block {
id: u16,
rows: [u16; 10],
border_clockwise: [u16; 4],
border_anti_clockwise: [u16; 4],
matching_ids: [Option<(u16, bool)>; 4]
}
#[derive(Eq, PartialEq, Clone)]
enum Flip {
FlipX, FlipY, FlipXY, Identity
}
#[derive(Eq, PartialEq... |
pub use bound_int_types::bound_int_types;
#[macro_export]
macro_rules! bound_int_eval {
( $lhs:tt + $rhs:tt $( $op:tt $rest:tt )* ) => {{
let sum = $lhs.plus($rhs);
bound_int_eval!(sum $( $op $rest )*)
}};
( $lhs:tt - $rhs:tt $( $op:tt $rest:tt )* ) => {{
let sum = $lhs.minus($rhs)... |
/// Like a circular buffer of size 2, aka a double buffer.
#[derive(Debug)]
pub struct OldNew<T>
where
T: Default,
{
left: T,
right: T,
state: OldNewState,
}
#[derive(Debug)]
pub enum OldNewState {
LeftOldRightNew,
LeftNewRightOld,
}
#[derive(Debug)]
pub struct OldNewResult<T> {
pub old: T... |
// 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 fidl::endpoints::create_endpoints;
use fidl_fuchsia_auth::AuthStateSummary;
use fidl_fuchsia_auth_account::{
Acco... |
extern crate serde;
mod test_utils;
use chrono::NaiveDate;
use flexi_logger::LoggerHandle;
use hdbconnect_async::{Connection, HdbResult};
// From wikipedia:
//
// Isolation level Lost updates Dirty reads Non-repeatable reads Phantoms
// ------------------------------------------------------------------------... |
// Bring in the standard library module to handle Error types
use std::error::Error;
// Bring in the standard library module to handle files
use std::fs;
//
use std::env;
pub struct Config {
pub query: String,
pub filename: String,
pub case_sensitive: bool,
}
// The error type for Result is &'static str a... |
use rustaoc2021::calculator::run_timed;
use rustaoc2021::day15::part_2;
fn main() {
let input2 = include_str!(r"../../resources/inputs/day15-input.txt");
run_timed(part_2,input2, 2);
}
|
// Copyright 2020-2021, The Tremor Team
//
// 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 agr... |
#[doc = r"Value read from the register"]
pub struct R {
bits: u32,
}
#[doc = r"Value to write to the register"]
pub struct W {
bits: u32,
}
impl super::SAC {
#[doc = r"Modifies the contents of the register"]
#[inline(always)]
pub fn modify<F>(&self, f: F)
where
for<'w> F: FnOnce(&R, &'w ... |
//! Types that map to concepts in HTTP.
//!
//! This module exports types that map to HTTP concepts or to the underlying
//! HTTP library when needed. Because the underlying HTTP library is likely to
//! change (see <a
//! href="https://github.com/SergioBenitez/Rocket/issues/17">#17</a>), types in
//! [hyper](hyper/ind... |
//! This module defines utilities for working with the `Rc` and `Weak` types.
use std::rc::Rc;
use std::rc::Weak;
use super::option::*;
// TODO[WD,AO]: Think about merging it with `OptionOps`.
/// Mapping methods to the `Weak` type.
pub trait WeakOps {
type Target;
fn for_each <U,F> (self , f:F) where F ... |
use nom::IResult;
use typeahead::Parse;
#[derive(Serialize, Deserialize, PartialOrd, Ord, Debug, Copy, Clone, PartialEq, Eq, Hash)]
pub enum Key {
Backspace,
Left,
Right,
Up,
Down,
Home,
End,
PageUp,
PageDown,
Delete,
Insert,
/// Function keys.
F(u8),
/// Normal ... |
use proc_macro::TokenStream;
use proc_macro2::TokenStream as TokenStream2;
use quote::quote;
use syn::punctuated::Punctuated;
use syn::{
parse_macro_input, Data, DataStruct, DeriveInput, Error, Field, Fields, Generics, Ident,
};
use crate::{Attr, GenericsStreams, MULTIPLE_FLATTEN_ERROR};
/// Error if the derive w... |
// 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 failure::Error;
#[fuchsia_async::run_singlethreaded(test)]
async fn test_get_option_subnet() -> Result<(), Error> {
let launcher = fuchsia_compone... |
/// emscripten: _llvm_log10_f64
pub extern "C" fn _llvm_log10_f64(value: f64) -> f64 {
debug!("emscripten::_llvm_log10_f64");
value.log10()
}
/// emscripten: _llvm_log2_f64
pub extern "C" fn _llvm_log2_f64(value: f64) -> f64 {
debug!("emscripten::_llvm_log2_f64");
value.log2()
}
// emscripten: f64-rem... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.