text stringlengths 8 4.13M |
|---|
use rustc_hash::FxHashMap;
use winit::event::{ElementState, VirtualKeyCode};
#[allow(unused_imports)]
use winit::{
event::{self, Event, KeyboardInput, WindowEvent},
event_loop::ControlFlow,
};
use crossbeam::atomic::AtomicCell;
use crossbeam::channel;
use std::sync::Arc;
use crate::gui::GuiInput;
use crate::{... |
mod slice {
use quickcheck::TestResult;
use quickcheck_macros::quickcheck;
#[quickcheck]
#[cfg(feature = "alloc")]
fn max(mut v: Vec<(i32, i32)>, n: usize) -> TestResult {
if v.len() < n {
return TestResult::discard();
}
let mut s = v.clone();
s.sort_by(|... |
// Represents shape to be rendered on the board
// Cases are rectangle and circle, with measurement parameters attached for those shapes
#[derive(Clone)]
pub enum Shape {
Rectangle { width: f64, height: f64 },
Circle { radius: f64 },
}
#[derive(Copy, Clone)]
pub struct Circle {
pub x: f64,
pub y: f64,
... |
use std::mem;
use std::ops::{Add, AddAssign, Mul};
use num_traits::{PrimInt, Signed};
#[macro_export]
macro_rules! p2 {
($x:expr, $y:expr) => {
Point2::new($x, $y)
};
}
#[derive(Copy, Clone)]
pub enum Rotation {
Right90,
OneEighty,
Left90,
}
#[derive(Debug, Eq, PartialEq, Hash, Default, ... |
fn main()
{
let mut idade = "Eu";
let mut nome = "Tharic";
println!("Hello, {}, você tem {} anos", idade, nome);
idade = str(53);
nome = "Vilmar";
println!("Hello, {}, você tem {} anos", nome, idade);
}
let mut idade = "Eu";
let mut idade = "Eu";
let mut idade = "Eu";
let mut idade = "... |
pub fn sort(list: &mut Vec<i32>) -> &mut Vec<i32> {
if list.len() <= 1 {
return list;
}
let middle = list.len() / 2;
let mut beginning: Vec<i32> = list[0..middle];
let mut end: Vec<i32> = list[middle..];
println!("{:?}", beginning);
println!("{:?}", end);
list
}
|
mod consts;
pub mod prelude {
pub use super::consts::*;
}
|
// Using a hash map and vectors, create a text interface to allow a user to
// add employee names to a department in a company.
// For example, “Add Sally to Engineering” or “Add Amir to Sales.”
// Then let the user retrieve a list of all people in
// a department or all people in the company by department,
// sorted a... |
#[doc = "Register `TAMPCR` reader"]
pub type R = crate::R<TAMPCR_SPEC>;
#[doc = "Register `TAMPCR` writer"]
pub type W = crate::W<TAMPCR_SPEC>;
#[doc = "Field `TAMP1E` reader - RTC_TAMP1 input detection enable"]
pub type TAMP1E_R = crate::BitReader;
#[doc = "Field `TAMP1E` writer - RTC_TAMP1 input detection enable"]
pu... |
// This file is part of Substrate.
// Copyright (C) 2020-2021 Parity Technologies (UK) Ltd.
// SPDX-License-Identifier: Apache-2.0
// 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
//
// ht... |
use std::slice;
fn read_nodes(l:&mut slice::Iter<usize>) -> usize{
let header = l.take(2).collect::<Vec<&usize>>();
let n_node = *header[0];
let n_metadata = *header[1];
let mut checksum = 0;
for _ in 0..n_node {
checksum += read_nodes(l);
}
checksum + l.take(n_metadata).sum::<usi... |
pub fn get_instructions()->String{
let data:&str = "rect 1x1
rotate row y=0 by 5
rect 1x1
rotate row y=0 by 6
rect 1x1
rotate row y=0 by 5
rect 1x1
rotate row y=0 by 2
rect 1x1
rotate row y=0 by 5
rect 2x1
rotate row y=0 by 2
rect 1x1
rotate row y=0 by 4
rect ... |
use crate::{Artifact, ArtifactStore, Scope};
use std::fmt::{Display, Formatter, Result as FmtResult};
pub struct NodeDisplay<T>(pub T);
impl<F> Display for NodeDisplay<(&Scope, &F)>
where
F: Fn(&str) -> bool,
{
fn fmt(&self, fmt: &mut Formatter) -> FmtResult {
let (scope, matcher) = self.0;
sc... |
use super::KeyState;
use super::sprite::RustConsoleSprite;
use std::io::{Error, ErrorKind};
use std::mem::{swap, size_of, MaybeUninit};
use std::ffi::OsStr;
use std::os::windows::ffi::OsStrExt;
use std::iter::once;
use libc::memset;
mod bindings {
windows::include_bindings!();
}
use bindings::{
Windows::Win3... |
use std::sync::Arc;
use futures::future;
use futures::sink::SinkExt;
use tokio::net::UnixStream;
use tokio_util::codec::{Framed, LinesCodec};
use persist_core::error::Error;
use persist_core::protocol::{Response, StopRequest, StopResponse};
use crate::server::State;
pub async fn handle(
state: Arc<State>,
c... |
use anyhow::Result;
pub fn part1(input_string: &str) -> Result<String> {
Ok(get_fuel_requirement(input_string, |mass| mass / 3 - 2))
}
pub fn part2(input_string: &str) -> Result<String> {
fn mass_to_fuel(mass: u64) -> u64 {
match (mass / 3).checked_sub(2) {
Some(fuel) => fuel + mass_to_fue... |
pub fn build_proverb(list: &[&str]) -> String {
let mut result = String::new();
let length = if list.len() != 0 { list.len() - 1 } else { 0 };
for idx in 0..length {
result.push_str(
format!(
"For want of a {} the {} was lost.\n",
list[idx],
... |
pub fn spawn_http_server() {
let port = std::env::var("PORT").unwrap_or_else(|_| "8080".to_string());
let address = "0.0.0.0";
tokio::spawn(async move {
let server = simple_server::Server::new(|_request, mut response| {
Ok(response.body(b"Hello Rust!".to_vec()).unwrap())
});
... |
//!
//! This module gives a handler for the keyboard interruption.
//!
pub extern "C" fn keyboard_handler() -> ! {
panic!("Keyboard !");
}
|
pub mod comparisons;
pub mod docs;
pub mod index;
|
use regex::Regex;
use serde_json::{Result, Value};
use std::cmp::{max, min};
use std::collections::HashSet;
use std::io::{self};
fn count_numbers(line: &str) -> i64 {
let re = Regex::new(r"([-]?\d+)").unwrap();
re.find_iter(&line)
.map(|c| c.as_str().parse::<i64>().unwrap())
.fold(0, |acc, val|... |
use clap::{App, Arg};
use archiver::config;
use archiver::ctx::Ctx;
use archiver::device;
use archiver::cli;
fn cli_opts<'a, 'b>() -> App<'a, 'b> {
cli::base_opts()
.about("Smoke test the location and mounting")
}
fn main() {
archiver::cli::run(|| {
let matches = cli_opts().get_matches();
... |
use super::*;
/// The diagonal of an N-dimensional homotopy, resulting in a 1D homotopy.
///
/// This interpolates along all dimensions at once.
#[derive(Copy, Clone)]
pub struct Diagonal<T, S> {
shape: T,
_s: PhantomData<S>,
}
impl<T, S> Diagonal<T, S> {
/// Creates a new diagonal.
pub fn new(shape: ... |
use std::net::SocketAddr;
use rsocket_rust::async_trait;
use rsocket_rust::{error::RSocketError, transport::Transport, Result};
use tokio::net::TcpStream;
use tokio_native_tls::{TlsConnector, TlsStream};
use crate::connection::TlsConnection;
#[derive(Debug)]
enum Connector {
Direct(TlsStream<TcpStream>),
Laz... |
#![feature(uniform_paths)]
mod multicolumn;
mod cli;
use multicolumn::Multicolumn;
use std::env;
use termion::style;
fn main() {
//termion::terminal_size()
let matches = cli::build_cli().get_matches_safe().unwrap_or_else(|e| e.exit());
let paths = match matches.values_of("path") {
None => vec!(env::current_dir(... |
#[doc = "Reader of register HOST_EP1_CTL"]
pub type R = crate::R<u32, super::HOST_EP1_CTL>;
#[doc = "Writer for register HOST_EP1_CTL"]
pub type W = crate::W<u32, super::HOST_EP1_CTL>;
#[doc = "Register HOST_EP1_CTL `reset()`'s with value 0x8100"]
impl crate::ResetValue for super::HOST_EP1_CTL {
type Type = u32;
... |
extern crate itertools;
use ::net;
use ::config;
use ::std;
// Import and alias
use serde_json;
use serde_json::Value as Json;
#[derive(Debug, Deserialize)]
struct Computer {
#[serde(rename="displayName")]
name: String,
#[serde(rename="numExecutors")]
executors: u16,
#[serde(rename="offlineCause... |
use super::connection::{Connection, ConnectionError};
use super::config::*;
use std::sync::{Arc, Mutex};
#[derive(Clone)]
pub struct Pool {
inner: Arc<Inner>,
}
struct Inner {
conf: PqConfig,
// vector of free connection in pool
conns: Mutex<Vec<Connection>>,
// 0: total of connection allocated
... |
mod env;
mod handler;
mod server;
mod state;
use {actix_rt::System, env_logger, server::start, std::io::Result};
fn main() -> Result<()> {
env_logger::init();
System::new().block_on(async { start().await })
}
|
use {data::semantics::Semantics, misc::id_gen::generate_mutable_id};
impl Semantics {
fn create_element_from_group(&mut self, source_id: usize, parent_id: usize) {
let element_id = self.groups.len();
log::debug!(" Creating new element group {}", element_id);
let source = &mut self.groups[source_id];
let eleme... |
//! This module defines the command-line interface of the application
//! - Defines parameters
//! - Defines validators
use clap::{Arg, App};
use std::path::Path;
use std::panic::catch_unwind;
use tsp::{TSP, file_parser};
use std::fs::File;
use std::io::Read;
use slog::*;
use af::*;
// Specify command line parameters... |
#[doc = "Register `DDRPHYC_DTPR2` reader"]
pub type R = crate::R<DDRPHYC_DTPR2_SPEC>;
#[doc = "Register `DDRPHYC_DTPR2` writer"]
pub type W = crate::W<DDRPHYC_DTPR2_SPEC>;
#[doc = "Field `TXS` reader - TXS"]
pub type TXS_R = crate::FieldReader<u16>;
#[doc = "Field `TXS` writer - TXS"]
pub type TXS_W<'a, REG, const O: u... |
extern crate proc_macro;
use proc_macro::TokenStream;
use proc_macro2::Span;
use quote::quote;
use syn::{Data, DataEnum, DataStruct, DeriveInput, Ident, IntSuffix, LitInt, WhereClause};
#[proc_macro_derive(Generic)]
pub fn generic_macro_derive(input: TokenStream) -> TokenStream {
let DeriveInput {
ident: ... |
// Copyright 2020 The RustExample Authors.
//
// Code is licensed under Apache License, Version 2.0.
extern crate reqwest;
use anyhow::Result;
use regex::Regex;
use select::document::Document;
use select::predicate::Name;
use std::thread::sleep;
use std::time::{Duration, Instant};
use super::*;
struct Wallhaven {
... |
use std::fmt;
use std::fs::File;
use std::io::{BufRead, BufReader};
use clap::{App, Arg};
#[derive(PartialEq, Eq, Hash, Clone, Copy)]
struct Addr(u64);
impl fmt::Debug for Addr {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("0x")?;
fmt::LowerHex::fmt(&self.0, f)
}
}
... |
//! Render commands for model files.
use errors::Result;
use util::cur::Cur;
pub struct SkinTerm {
pub weight: f32,
pub stack_pos: u8,
pub inv_bind_idx: u8,
}
/// A render command is analyzed into zero or more render ops (think micro-ops
/// to a CPU instruction).
pub enum Op {
/// cur_matrix = matri... |
use crate::model::Move;
use crate::utils::Bound;
use priority_queue::PriorityQueue;
use core::fmt;
use core::fmt::Write;
use core::cmp::Ordering;
use std::collections::HashMap;
/// Decartes coordinates, (x, y)
/// make our own coordinate system, in the name of René Descartes
/// ^ y
/// |
/// |
/// +-------> x
#[deriv... |
#[derive(Debug, Clone)]
pub struct Redirect {
path: String,
is_over:bool
}
impl Redirect {
pub fn new(path:&str, is_over:bool) -> Self {
Self {
path:path.to_string(),
is_over,
}
}
pub fn get_redirect_path(&self) -> &str {
&self.path
}
pub fn get_is_over(&self) -> bool {
self... |
// Convert hex to base64
// The string:
//
// 49276d206b696c6c696e6720796f757220627261696e206c696b65206120706f69736f6e6f7573206d757368726f6f6d
// Should produce:
//
// SSdtIGtpbGxpbmcgeW91ciBicmFpbiBsaWtlIGEgcG9pc29ub3VzIG11c2hyb29t
// So go ahead and make that happen. You'll need to use this code for the rest of the e... |
use std::{
fs::File,
io::{self, Read, Seek, SeekFrom, Write},
};
pub trait ReadSeek: Read + Seek + Send + Sync {}
impl<T> ReadSeek for T where T: Read + Seek + Send + Sync {}
pub struct OffsetSeeker {
file: File,
offset: u64,
cursor: u64,
length: u64,
}
impl OffsetSeeker {
pub fn new(mut ... |
//! # System Control
//!
//! The SYSCTL peripheral controls clocks and power.
//!
//! The TM4C123x can be clocked from the Main Oscillator or the PLL, through a
//! divider. The Main Oscillator can be either the internal 16 MHz precision
//! oscillator, a 4 MHz derivation of the same, or an external crystal.
//!
//! SY... |
use crate::format::ParseError;
use core::fmt;
/// A unified error type for anything returned by a method in the time crate.
///
/// This can be used when you either don't know or don't care about the exact
/// error returned. `Result<_, time::Error>` will work in these situations.
#[allow(clippy::missing_docs_in_priva... |
use crate::arena::{block, resource, BlockRef};
use crate::libs::random_id::U128Id;
use crate::libs::three;
use std::cell::Cell;
use std::collections::HashMap;
use std::rc::Rc;
use wasm_bindgen::{prelude::*, JsCast};
pub struct TextureTable {
data: HashMap<U128Id, Texture>,
text: HashMap<(String, String), Fate<... |
pub mod material;
pub mod render_mesh;
pub mod shader;
pub mod texture;
pub mod light;
pub mod light_conversion;
use luminance::{
shader::program::{
Uniform,
Uniformable,
},
linear::M44
};
use luminance_derive::UniformInterface;
#[derive(Debug, UniformInterface)]
pub struct ShaderInterface... |
// Copyright (c) The Libra Core Contributors
// SPDX-License-Identifier: Apache-2.0
#[allow(unused_imports)]
use log::{info, warn};
use itertools::Itertools;
use num::BigUint;
use regex::Regex;
use serde::Serialize;
use spec_lang::{
ast::{ModuleName, SpecBlockInfo, SpecBlockTarget},
code_writer::CodeWriter,
... |
//! Contains types for using resource kinds not known at compile-time.
//!
//! For concrete usage see [examples prefixed with dynamic_](https://github.com/kube-rs/kube/tree/main/examples).
pub use crate::discovery::ApiResource;
use crate::{
metadata::TypeMeta,
resource::{DynamicResourceScope, Resource},
};
use... |
use std::{fmt::Debug, sync::Arc};
use serde::{Deserialize, Serialize};
use tokio::sync::RwLock;
use crate::{
task::{Handle, Id},
Job, Keyed,
};
pub(crate) mod jobs;
mod managed_job;
pub(crate) use managed_job::ManagedJob;
#[cfg(test)]
mod tests;
/// A background jobs manager.
#[derive(Debug)]
pub struct Ma... |
#![feature(proc_macro_hygiene, decl_macro)]
extern crate glob;
extern crate regex;
extern crate serde;
#[macro_use]
extern crate rocket;
#[macro_use]
extern crate rocket_contrib;
#[macro_use(block)]
extern crate nb;
extern crate embedded_hal as hal;
mod irsend;
mod protocol;
mod temperature;
use std::sync::RwLoc... |
use log::*;
use serenity::framework::standard::CommandError;
use serenity::model::channel::Message;
use serenity::model::id::UserId;
use serenity::prelude::Context;
use crate::commands::servers::*;
use crate::db::*;
use crate::model::enums::*;
use crate::model::GameServerState;
use crate::server::ServerConnection;
use... |
// This file was generated by gir (https://github.com/gtk-rs/gir @ fbb95f4)
// from gir-files (https://github.com/gtk-rs/gir-files @ 77d1f70)
// DO NOT EDIT
use ActionGroup;
use ActionMap;
use ApplicationFlags;
use Cancellable;
use Error;
use File;
#[cfg(any(feature = "v2_40", feature = "dox"))]
use Notification;
use ... |
mod blake224;
mod blake256;
mod blake28;
mod blake32;
mod blake384;
mod blake48;
mod blake512;
mod blake64;
use core::cmp::Ordering;
use crate::consts::{C32, C64, IV224, IV256, IV384, IV512, SIGMA};
// Round1/2 submission version
pub use blake28::Blake28;
pub use blake32::Blake32;
pub use blake48::Blake48;
pub use b... |
extern crate num_traits;
extern crate sdl2;
use num_traits::cast::ToPrimitive;
use sdl2::keyboard::Scancode;
// XT Scan codes, since I chose the wrong table and I don't feel like changing them
// Retro!
// NB: Any code longer than 2 bytes is omitted, because who uses `pause` anyway
// NB: All nonstandard (multimedia... |
//! `cargo arch` is a Cargo plugin for making Arch Linux packages.
//! Packages' information is extract from `Cargo.toml`.
//! You can add additional information in `[package.metadata.arch]` section.
#[macro_use]
extern crate serde_derive;
use clap::{App, load_yaml};
pub mod config;
fn build_arch_package(mksrcinfo... |
use bytes::Bytes;
use bytes::BytesMut;
use std::error::Error;
use std::future::Future;
use std::io;
use std::pin::Pin;
use std::sync::{Arc, Mutex};
use std::task::{Context, Poll, Waker};
use std::time::{Duration, SystemTime};
use tokio::io::{AsyncRead, AsyncReadExt, AsyncWrite};
use tokio::net::TcpStream;
pub fn make_... |
use super::PAGE_SIZE;
/*
* We are targeting x64 and thus use a 4 level paging structure
* PML4 -> PDP -> PD -> PT
*/
// With 4k pages, we can fit 512 8 byte entries per page
pub const ENTRY_COUNT: usize = 512;
// Since pml4 is recursively mapped, here is the constant addr to access it
pub const PML4: *mut PageTable... |
#![deny(clippy::all, clippy::pedantic)]
#[derive(Clone, Copy, PartialEq, Debug)]
pub enum Direction {
North = 0,
East = 1,
South = 2,
West = 3,
}
use Direction::{East, North, South, West};
const DIRECTIONS: [Direction; 4] = [North, East, South, West];
pub struct Robot {
x: i32,
y: i32,
fa... |
use arduino_mqtt_pin::pin::{PinOperation, Temperature, PinCollection, PinState, PinValue};
use std::collections::HashMap;
use chrono::{DateTime, Local, NaiveDateTime, TimeZone};
use diesel::{insert_into, RunQueryDsl, SqliteConnection};
use diesel::prelude::*;
use arduino_mqtt_pin::helper::average;
use crate::config::C... |
mod echo;
mod pitch;
mod select;
mod volume;
use nom::{
branch::alt,
bytes::complete::tag,
combinator::{map, opt},
multi::separated_list0,
number::complete::float,
IResult,
};
pub use self::{
echo::EchoModifier, pitch::PitchModifier, select::SelectModifier, volume::VolumeModifier,
};
use c... |
use crate::cell::{ Merge };
use std::ops::{ Add, Sub, Mul, Div };
use ordered_float::NotNan;
#[derive(Hash, Debug, PartialEq, Eq, Clone)]
pub struct Float(NotNan<f64>);
impl Float {
pub fn new(val: f64) -> Self {
Self(NotNan::new(val).unwrap())
}
}
impl Add for Float {
type Output = Float;
... |
use std::env;
use log::error;
use nego::http;
fn main() {
env::set_var("RUST_LOG", "debug");
env_logger::init();
let args: Vec<String> = env::args().collect();
if args.len() != 2 {
error!("Bad number of arguments.");
std::process::exit(1);
}
let mut server = http::Server::new(... |
use crate::config;
use crate::maze::maze_genotype::MazeGenome;
use crate::mcc::maze::maze_queue::MazeQueue;
#[derive(Debug, Clone)]
pub struct MazeSpeciesStatistics {
average_sizes: Vec<f64>,
maximum_sizes: Vec<u32>,
minimum_sizes: Vec<u32>,
average_size_increases: Vec<f64>,
average_path_complexiti... |
extern crate cgmath;
#[macro_use]
extern crate puck_core;
extern crate alto;
extern crate lewton;
extern crate time;
extern crate notify;
extern crate rand;
extern crate image;
#[macro_use]
extern crate gfx;
extern crate gfx_device_gl;
extern crate gfx_window_glutin;
extern crate glutin;
extern crate rayon;
extern c... |
//! Container types returned during partial parsing.
use std::io::{Read, Seek};
use crate::error::TychoResult;
use crate::partial::container::{PartialContainer, PartialContainerType};
use crate::partial::element::{PartialElement, read_partial_element};
use crate::partial::reader::PartialReader;
use crate::read::strin... |
use std::env;
use std::fs;
use std::path::Path;
use colored::*;
use std::{thread, time};
const MATRIX_SIZE:i32 = 100;
fn read_light_setup(filename:&str) -> String{
let fpath = Path::new(filename);
let abspath = env::current_dir()
.unwrap()
.into_boxed_path()
.join(fpath);
let ligh... |
use crate::irust::buffer::Buffer;
use crate::irust::irust_error::IRustError;
use crate::irust::{CTRL_KEYMODIFIER, NO_MODIFIER};
use crate::utils::StringTools;
use crossterm::{event::*, style::Color};
enum Dir {
Up,
Down,
}
impl super::IRust {
pub fn handle_up(&mut self) -> Result<(), IRustError> {
... |
// Copyright (c) 2020 Ant Financial
//
// SPDX-License-Identifier: Apache-2.0
//
pub mod agent;
pub mod agent_ttrpc;
pub mod empty;
mod gogo;
pub mod health;
pub mod health_ttrpc;
mod oci;
pub mod types;
|
use rand::random;
use std::fmt::Debug;
trait ReservoirSampler {
// 每种抽样器只会在一种总体中抽样,而总体中所有个体都属于相同类型
type Item;
// 流式采样器无法知道总体数据有多少个样本,因此只逐个处理,并返回是否将样本纳入
// 样本池的结果,以及可能被替换出来的样本
fn sample(&mut self, it: Self::Item) -> (bool, Option<Self::Item>);
// 任意时候应当知道当前蓄水池的状态
fn samples(&... |
#[doc = "Reader of register CONN_4_DATA_LIST_ACK"]
pub type R = crate::R<u32, super::CONN_4_DATA_LIST_ACK>;
#[doc = "Writer for register CONN_4_DATA_LIST_ACK"]
pub type W = crate::W<u32, super::CONN_4_DATA_LIST_ACK>;
#[doc = "Register CONN_4_DATA_LIST_ACK `reset()`'s with value 0"]
impl crate::ResetValue for super::CON... |
mod bot;
mod result;
mod models;
pub use self::bot::DexBot;
pub use self::result::TelegramResult;
pub use self::fetcher::{DefinitionFetcher, MockDefinitionFetcher};
mod fetcher {
pub trait DefinitionFetcher {
fn new(name: &str) -> Self;
fn name(&self) -> &str;
fn get_definitions(&self, w... |
//! # zk-SNARK MPCs, made easy.
//!
//! ## Make your circuit
//!
//! Grab the [`bellperson`](https://github.com/filecoin-project/bellman) crate. Bellman
//! provides a trait called `Circuit`, which you must implement
//! for your computation.
//!
//! Here's a silly example: proving you know the cube root of
//! a field... |
#[doc = "Register `ADC_SQR4` reader"]
pub type R = crate::R<ADC_SQR4_SPEC>;
#[doc = "Register `ADC_SQR4` writer"]
pub type W = crate::W<ADC_SQR4_SPEC>;
#[doc = "Field `SQ15` reader - SQ15"]
pub type SQ15_R = crate::FieldReader;
#[doc = "Field `SQ15` writer - SQ15"]
pub type SQ15_W<'a, REG, const O: u8> = crate::FieldWr... |
#[doc = "Register `GICD_PIDR3` reader"]
pub type R = crate::R<GICD_PIDR3_SPEC>;
#[doc = "Field `PIDR3` reader - PIDR3"]
pub type PIDR3_R = crate::FieldReader<u32>;
impl R {
#[doc = "Bits 0:31 - PIDR3"]
#[inline(always)]
pub fn pidr3(&self) -> PIDR3_R {
PIDR3_R::new(self.bits)
}
}
#[doc = "GICD p... |
#[macro_use]
extern crate cpython;
use cpython::{PyResult, Python};
// add bindings to the generated python module
// N.B: names: "librust2py" must be the name of
// the `.so` or `.pyd` file
py_module_initializer!(librust2py,
initlibrust2py, PyInit_librust2py, |py, m| {
m.add(py, "__doc__",
"This ... |
//! # HTTP Client
//!
//! This module contains the HTTP client through which actors consume
//! the currently bound `wascap:http_client` capability provider
use wapc_guest::host_call;
use wascc_codec::{deserialize, http::*, serialize};
use crate::HandlerResult;
const CAPID_HTTPCLIENT: &str = "wascc:http_client";
//... |
use crate::{ import::*, WsErr, WsStream };
/// A wrapper around WsStream that converts errors into io::Error so that it can be
/// used for io (like `AsyncRead`/`AsyncWrite`).
///
/// You shouldn't need to use this manually. It is passed to [`IoStream`] when calling
/// [`WsStream::into_io`].
//
#[ derive(Debug) ]
//... |
use bellman::gadgets::multipack;
use bellman::groth16;
use blake2s_simd::Params as Blake2sParams;
use bls12_381::Bls12;
use ff::Field;
use group::{Curve, Group, GroupEncoding};
use sapvi::crypto::{
create_mint_proof, load_params, save_params, setup_mint_prover, verify_mint_proof,
};
fn main() {
use rand::rngs... |
pub mod connection;
pub mod content_length;
pub mod expect;
pub mod transfer_encoding;
mod encoding;
mod parse;
pub use self::connection::Connection;
pub use self::content_length::ContentLength;
pub use self::encoding::Encoding;
pub use self::expect::Expect;
pub use self::transfer_encoding::TransferEncoding;
|
pub fn adler32(input: &str ) -> u32 {
let bytes = input.as_bytes();
let mut a: u32 = 1;
let mut b: u32 = 0;
let mut c: u32;
for byte in bytes
{
let byte_val: u32 = *byte as u32;
c = a;
a = (a.wrapping_add(byte_val)) % 65521;
b = (b.wrapping_add(byte_val.wrapping_add(c))) % 65521;
}
let hash = (... |
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT license.
*/
#![warn(missing_debug_implementations, missing_docs)]
//! Parameters for disk index construction.
use crate::common::{ANNResult, ANNError};
/// Cached nodes size in GB
const SPACE_FOR_CACHED_NODES_IN_GB: f64 = 0.25... |
use bytes::{ Bytes, Buf, BytesMut, BufMut };
#[derive(Debug, PartialEq, Clone)]
pub struct SendDataRequestChip {
pub callback_id: u8,
pub status: u8,
}
impl SendDataRequestChip {
pub fn encode(&self, dst: &mut BytesMut) {
dst.put_u8(self.callback_id);
dst.put_u8(self.status);
... |
use std::{collections::BTreeMap, fmt::Write};
use eyre::Report;
use hashbrown::HashMap;
use rosu_v2::prelude::{Beatmap, User};
use crate::{
custom_client::SnipeScore,
embeds::{osu, Author, Footer},
pp::PpCalculator,
util::{
constants::OSU_BASE,
datetime::how_long_ago_dynamic,
n... |
use std::collections::{BTreeMap, VecDeque};
use std::error::Error;
use std::fmt;
use std::io::{self, Read};
use std::result;
use std::usize;
type Result<T> = result::Result<T, Box<dyn Error>>;
#[derive(Clone, PartialEq)]
enum Tile {
Wall,
Open,
Unit,
}
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord... |
use rand::Rng;
use rand::XorShiftRng;
use std::ops::{Add, Index, IndexMut};
use treap::implicit_tree;
use treap::node::ImplicitNode;
/// A list implemented using an implicit treap.
///
/// A treap is a tree that satisfies both the binary search tree property and a heap property. Each
/// node has a key, a value, and a... |
#![cfg_attr(feature = "nightly", feature(external_doc))]
/*!
[`RangeMap`] and [`RangeInclusiveMap`] are map data structures whose keys
are stored as ranges. Contiguous and overlapping ranges that map to the same
value are coalesced into a single range.
Corresponding [`RangeSet`] and [`RangeInclusiveSet`] structures a... |
//! A simple implementation of the Y Combinator:
//! λf.(λx.xx)(λx.f(xx))
//! <=> λf.(λx.f(xx))(λx.f(xx))
/// A function type that takes its own type as an input is an infinite recursive type.
/// We introduce the "Apply" trait, which will allow us to have an input with the same type as self, and break the recursion.... |
#![allow(non_snake_case)]
#![allow(unused_must_use)]
use std::net;
use std::time;
use std::thread;
use std::sync::mpsc;
use std::error::Error;
use std::io::prelude::*;
use crate::encoder::Encoder;
use std::net::{SocketAddr, SocketAddrV4, SocketAddrV6, Ipv4Addr, Ipv6Addr, ToSocketAddrs, TcpStream};
#[allow(unused_impor... |
use std::fmt::Display;
use std::fmt::Formatter;
use core::fmt;
#[derive(Debug)]
enum FizzBuzz {
Fizz,
Buzz,
FizzBuzz,
Other(u32),
}
impl From<u32> for FizzBuzz {
fn from(item: u32) -> Self {
match (item % 3 == 0, item % 5 == 0) {
(false, false) => FizzBuzz::Other(item),
... |
use crate::grammar::ast::{BinaryOp, Expression};
use crate::grammar::model::WrightInput;
use crate::grammar::parsers::expression::binary_expression::primary::parser_left;
use crate::grammar::parsers::expression::binary_expression::primary::relational::{
relational, relational_primary,
};
use crate::grammar::tracing... |
// This file is part of Substrate.
// Copyright (C) 2017-2020 Parity Technologies (UK) Ltd.
// SPDX-License-Identifier: Apache-2.0
// 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
//
// ht... |
use crate::{chunked_encoder::ChunkedEncoder, http_types::Body};
use futures_lite::io::AsyncRead;
use pin_project::pin_project;
use std::{
io,
pin::Pin,
task::{Context, Poll},
};
#[pin_project(project=BodyEncoderProjection)]
#[derive(Debug)]
/// A http encoder for [`http_types::Body`]. You probably don't wa... |
/// An enum to represent all characters in the CJKCompatibilityIdeographs block.
#[derive(Debug, Clone, Copy, Hash, PartialEq, Eq)]
pub enum CJKCompatibilityIdeographs {
/// \u{f900}: '豈'
CjkCompatibilityIdeographDashF900,
/// \u{f901}: '更'
CjkCompatibilityIdeographDashF901,
/// \u{f902}: '車'
C... |
//! Test and font stuff, it will be cleaned up later. Don't look here, it won't help you.
use std::borrow::Cow;
use std::collections::HashMap;
use std::io::Read;
use rusttype::{Rect, Point};
use glium::backend::Facade;
#[derive(Debug)]
pub enum Error {
/// A glyph for this character is not present in font.
... |
#[doc = "Register `DDRCTRL_SCHED` reader"]
pub type R = crate::R<DDRCTRL_SCHED_SPEC>;
#[doc = "Register `DDRCTRL_SCHED` writer"]
pub type W = crate::W<DDRCTRL_SCHED_SPEC>;
#[doc = "Field `FORCE_LOW_PRI_N` reader - FORCE_LOW_PRI_N"]
pub type FORCE_LOW_PRI_N_R = crate::BitReader;
#[doc = "Field `FORCE_LOW_PRI_N` writer -... |
use crate::{Glyph, GlyphIter, IntoGlyphId, LayoutIter, Point, Scale, VMetrics};
#[cfg(not(feature = "has-atomics"))]
use alloc::rc::Rc as Arc;
#[cfg(feature = "has-atomics")]
use alloc::sync::Arc;
#[cfg(not(feature = "std"))]
use alloc::vec::Vec;
use core::fmt;
/// A single font. This may or may not own the font data.... |
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum FileType {
File,
Directory,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Permissions {
pub read: bool,
pub write: bool,
}
impl Permissions {
pub fn readonly(&self) -> bool {
self.read && !self.write
}
pub fn write... |
use serenity::model::id::MessageId;
use command_error::CommandError;
command!(purge(_ctx, msg, args) {
// Get the number of messages to delete.
let num = args.single::<u64>().unwrap();
let channel = msg.channel()
.ok_or(CommandError::Generic("Could not get channel.".to_owned()))?;
let channel... |
use crate::assembunny::*;
use crate::prelude::*;
pub fn pt(input: Vec<Instruction>) -> Result<i64> {
let mut prog = Program::new(input)?;
let mut start_idx = -1i64;
let mut state: HashSet<(i64, Registers, bool)> = HashSet::new();
'outer: loop {
prog.instruction_ptr = 0;
start_idx += 1;
... |
#[doc = "Register `CCER` reader"]
pub type R = crate::R<CCER_SPEC>;
#[doc = "Register `CCER` writer"]
pub type W = crate::W<CCER_SPEC>;
#[doc = "Field `CC1E` reader - CC1E"]
pub type CC1E_R = crate::BitReader<CC1E_A>;
#[doc = "CC1E\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum CC1E_A {
... |
use actix_service::Service;
use actix_session::CookieSession;
use actix_web::{App, HttpServer};
use anyhow::Result;
use futures::{FutureExt, TryFutureExt};
use rustimate_controllers::routes::add_routes;
use rustimate_service::AppConfig;
use std::time::SystemTime;
pub(crate) async fn start_server(cfg: AppConfig, port_t... |
use anyhow::{Context, Result};
use serde_state::DeserializeState;
use necsim_core_bond::Partition;
use necsim_partitioning_core::Partitioning;
use super::{CommandArgs, ReplayArgs, SimulateArgs};
/// Transform the `command_args` into a RON `String`
fn into_ron_args(command_args: CommandArgs) -> String {
let mut ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.