text stringlengths 8 4.13M |
|---|
use crate::{ArchivedInternedString, Intern, InternSerializeRegistry, InternedStringResolver};
use rkyv::{
ser::Serializer,
with::{ArchiveWith, DeserializeWith, SerializeWith},
Fallible,
};
#[cfg(not(feature = "std"))]
use ::alloc::string::String;
impl ArchiveWith<String> for Intern {
type Archived = Ar... |
use serde::{Deserialize, Serialize};
use slotmap::{Key, Keys, SecondaryMap, SlotMap};
use std::ops::{Index, IndexMut};
#[derive(Clone, Copy, Serialize, Deserialize)]
pub struct Edge<N> {
pub to: N,
pub weight: f32,
}
type EdgeList<N> = Vec<Edge<N>>;
#[derive(Serialize, Deserialize)]
pub struct Graph<N: Key, ... |
use crate::types::{Address, Bytes, H256, U256, U64};
use serde::{ser::SerializeStruct, Deserialize, Serialize, Serializer};
/// The block header type returned from RPC calls.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct BlockHeader {
/// Hash of the parent
pub parent_hash: H256,
//... |
/*
chapter 4
functions
*/
fn main() {
print_number(5);
}
fn print_number(n: i32) {
println!("n is {}", n);
}
// output should be:
/*
n is 5
*/
|
use std::collections::HashMap;
use exonum::blockchain::Transaction;
use exonum::crypto;
use exonum::crypto::{PublicKey, Signature};
use exonum::messages::Message;
use exonum::storage::Fork;
use prometheus::{Histogram, IntCounter};
use currency::assets::TradeAsset;
use currency::error::Error;
use currency::service::CO... |
use std::{env, thread};
use std::future::Future;
use std::time::Duration;
use futures::executor::block_on;
use indy_api_types::domain::wallet::{Config, Credentials, KeyDerivationMethod};
use serde_json::Value;
use indy::domain::crypto::did::DidValue;
use indy::Locator;
use indy::domain::anoncreds::schema::SchemaId;
u... |
use super::*;
/// A general file (as opposed to photos, voice messages, etc.)
#[derive(Debug,Deserialize)]
pub struct Document {
/// Unique identifier for the file.
pub file_id: String,
/// The document thumbnail.
pub thumb: Option<Box<PhotoSize>>,
/// The original file name.
pub file_name: Opt... |
#[doc = r" Register block"]
#[repr(C)]
pub struct RegisterBlock {
_reserved0: [u8; 256usize],
#[doc = "0x100 - Current FIFO Pointer"]
pub fifoptr: FIFOPTR,
#[doc = "0x104 - FIFO Configuration"]
pub fifocfg: FIFOCFG,
#[doc = "0x108 - FIFO Threshold Configuration"]
pub fifothr: FIFOTHR,
#[... |
use std::collections::HashMap;
#[derive(Debug, Eq, PartialEq, Ord, PartialOrd, Copy, Clone, Hash)]
pub struct Symbol(u32);
#[derive(Debug)]
pub struct SymbolIntern {
current_id: u32,
sym_to_string: HashMap<Symbol, String>,
string_to_sym: HashMap<String, Symbol>,
}
impl SymbolIntern {
pub fn new() -> ... |
mod typewriter;
mod mandir;
mod common;
use std::io::Read;
use anyhow::Result;
fn main() -> Result<()> {
// let mut input = String::new();
// std::io::stdin().read_to_string(&mut input)?;
// let mut t = typewriter::Typewriter::new();
// for c in input.chars() {
// t.append(c);
// }
// ... |
// For some reasons `Command::spawn` doesn't work in CI env for many exotic arches.
#![cfg(all(any(target_arch = "x86_64", target_arch = "x86"), not(sanitizing)))]
use crate::{
generate::{generate_parser_for_grammar, load_grammar_file},
tests::helpers::fixtures::{fixtures_dir, get_test_language},
};
use std::{... |
enum ParseStates {
StartState,
NumberState,
PlusState,
MinusState,
StarState,
SlashState,
LParenState,
RParenState
}
pub fn tokenize<'a>(tokenstring: &'a str) -> Option<Vec<::token::Token<'a>>> {
let mut current_state = StartState;
let mut current_token_start: uint = 0;
let m... |
/*
* Copyright (c) Meta Platforms, Inc. and affiliates.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree.
*/
//! Utilities that support constructing tests for Reverie Tools.
use futures::Future;
use reverie:... |
/// petgraphクレートにunion findは存在するがグループのサイズを知る方法が分からないためグループのサイズが分かるunion findを実装した
pub struct UnionFind {
par: Vec<isize>,
rank: Vec<usize>,
}
impl UnionFind {
pub fn new(n: usize) -> Self {
UnionFind {
par: vec![-1; n],
rank: vec![0; n],
}
}
pub fn root(&mut... |
#[doc = "Register `CR1` reader"]
pub type R = crate::R<CR1_SPEC>;
#[doc = "Register `CR1` writer"]
pub type W = crate::W<CR1_SPEC>;
#[doc = "Field `DFEN` reader - DFSDM enable"]
pub type DFEN_R = crate::BitReader<DFEN_A>;
#[doc = "DFSDM enable\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum... |
// Copyright 2021 Contributors to the Parsec project.
// SPDX-License-Identifier: Apache-2.0
//! Decrypting data
use crate::error::{Result, Rv};
use crate::mechanism::Mechanism;
use crate::object::ObjectHandle;
use crate::session::Session;
use cryptoki_sys::*;
use std::convert::TryInto;
// See public docs on stub in ... |
use std::ops::{Add, Sub, Mul, Div, Rem, Neg};
use std::ops::{AddAssign, SubAssign, MulAssign, DivAssign, RemAssign};
/// A 2D vector, generally used with
#[derive(Copy, Clone, PartialEq)]
pub struct Vec2 {
pub x: f64,
pub y: f64
}
pub fn vec2<T: Into<f64>, U: Into<f64>>(x: T, y: U) -> Vec2 {
Vec2::new(x, ... |
mod bind;
use crate::libs::js_object::Object;
use wasm_bindgen::{prelude::*, JsCast};
use wasm_bindgen_futures::JsFuture;
pub struct DynamicLoader {
instance: bind::DynamicLoader,
available_game_systems: Vec<Object>,
}
pub struct GameSystemInfo {
id: String,
name: String,
class_name: String,
s... |
pub mod consts;
pub mod remote_file_getter;
pub mod types;
pub mod unzip;
pub mod utils;
|
use api::user_client::UserClient;
use crate::api::UserData;
pub mod api {
tonic::include_proto!("api");
}
#[tokio::test(flavor = "multi_thread")]
async fn test_api() -> Result<(), Box<dyn std::error::Error>> {
let mut client = UserClient::connect("http://[::1]:50051").await?;
let user1 = UserData {
... |
#![feature(proc_macro_hygiene)]
#![feature(asm)]
#[macro_use]
pub mod macros;
pub use lua_macro::*;
type ScriptBootstrapperFunc = unsafe extern "C" fn(&mut smash::lua2cpp::L2CAgentBase, &mut smash::lib::utility::Variadic);
type SysLineControlFunc = unsafe extern "C" fn(&mut smash::lua2cpp::L2CFighterCommon) -> smash::... |
use logo_lib::{canvas::Image, Program, Rgba, Turtle};
fn main() {
let code = r#"
pu fd 325 rt 90 fd 200 pd rt 45
repeat 4 [
set_colour 255 255 255
repeat 100 [rt 3.6 fd 2]
set_colour 0 255 0
repeat 30 [
pu fd 5 pd rt 90 fd 50 rt 180 fd... |
use std::cmp::{Ord, Ordering};
use std::collections::{HashMap, HashSet};
use std::fs::File;
use std::io::{BufRead, BufReader};
use std::iter::Iterator;
type Point = (i32, i32);
fn manhatten_distance(x: Point, y: Point) -> i32 {
(x.0 - y.0).abs() + (x.1 - y.1).abs()
}
fn find_closest(p: Point, points: &Vec<Point>... |
pub mod fasta;
pub mod fastq;
//pub mod gtf;
//pub mod gff;
//pub mod bed;
|
fn main(){
let mut i = 0;
let result = loop{
i+=1;
if i == 5{
break i;
}
};
println!("Result is {}", result);
} |
use crate::components::Position;
const QT_NODE_CAPACITY: usize = 4;
pub struct Quadtree {
boundary: AABB,
points: Vec<(Position, i32)>,
children: Option<Children>,
}
struct Children {
north_west: Box<Quadtree>,
north_east: Box<Quadtree>,
south_west: Box<Quadtree>,
south_east: Box<Quadtree... |
//! Loads the button class/object up, just like the awesome library.
#![allow(unused_variables)]
#[macro_use] extern crate awesome_wayland;
#[macro_use] extern crate lazy_static;
extern crate lua_sys;
extern crate libc;
use std::path::PathBuf;
use std::default::Default;
use awesome_wayland::{Lua, luaA, LuaErr, Awesom... |
extern crate actix;
extern crate actix_web;
extern crate env_logger;
extern crate walkdir;
pub mod http;
pub mod web;
pub mod fs; |
use crate::db::{models::Record, DatabaseQuery, PooledConnection};
use crate::errors::{add_table_name, DbResult};
use octo_budget_lib::auth_token::UserId;
pub struct FindRecord {
user_id: UserId,
id: i32,
}
impl FindRecord {
pub fn new(id: i32, user_id: UserId) -> Self {
Self { id, user_id }
}
... |
fn number(bus_stops:&[(i32, i32)]) -> i32 {
bus_stops.iter().fold(0, |acc, x| acc + x.0 - x.1)
}
#[test]
fn returns_expected() {
assert_eq!(number(&[(10,0),(3,5),(5,8)]), 5);
assert_eq!(number(&[(3,0),(9,1),(4,10),(12,2),(6,1),(7,10)]), 17);
assert_eq!(number(&[(3,0),(9,1),(4,8),(12,2),(6,1),(7,8)]), 21);
}
|
use crate::{
atlas::pack_sprites_and_write_to_files, pack::pack_assets_and_write_to_file,
tiled::build_map_and_write_to_file,
};
use serde::{Deserialize, Serialize};
use std::{
env::var,
fs::read_to_string,
io::{Error, ErrorKind},
path::{Path, PathBuf},
};
fn pathbuf_is_empty(buf: &Path) -> boo... |
//filesystem storage
extern crate msgpackio;
extern crate rustc_serialize;
use std::io::{Result,Error, ErrorKind, Cursor};
use std::path::{Path, PathBuf};
use std::fs::{self, File};
use std::env;
use self::rustc_serialize::hex::ToHex;
use crypto::digest::{Digest};
use crypto::blake2b::{Blake2b};
use self::msgpack... |
// El discurso de Zoe
//
// Copyright (C) 2016 GUL UC3M
//
// This program 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) any later version.
//
// Th... |
#![feature(no_std, plugin)]
#![no_std]
#![plugin(arm_rt_macro)]
extern crate stm32;
extern crate rlibc;
use stm32::stm32f0x1::*;
#[entry_point]
fn main() -> ! {
// enable LED GPIOs
// (PC6 = red, PC7 = blue, PC8 = orange, PC9 = green)
RCC.ahbenr.set_gpioc_en(true);
// set LED pins to "output"
... |
//! Shader runtime input structure.
pub mod light;
pub mod samples;
pub mod shadow;
pub mod sky;
pub mod sky_builder;
pub use self::{light::*, samples::*, shadow::*, sky::*, sky_builder::*};
use arctk::access;
/// Conglomerate lighting and shadowing settings.
pub struct Shader {
/// Sky settings.
sky: Sky,
... |
fn main() {
let a = [10, 20, 30, 40];
for elem in a.iter() {
println!("elem = {}", elem);
}
for n in (1..4).rev() {
println!("n = {}", n);
}
}
|
use std::collections::HashSet;
use std::fmt::Debug;
use std::hash::Hash;
use std::marker;
use std::ops::Index;
use ironsea_index::Record;
use serde::Deserialize;
use serde::Serialize;
type Cell<T> = Vec<T>;
#[derive(Clone, Debug, Deserialize, Serialize)]
struct CellDictionary<K, V> {
table: Vec<Cell<V>>,
max... |
use std::{fs::File, io::{BufRead, BufReader}, vec};
fn main() {
let file = File::open("inputs/input-1.txt").unwrap();
let lines = BufReader::new(file).lines();
let mut numbers: Vec<u32> = vec![];
for line in lines {
let line = line.unwrap();
let number: u32 = line.parse().unwrap();
... |
use amethyst::{
core::SystemDesc,
derive::SystemDesc,
ecs::prelude::{System, SystemData, World},
};
// computes LOD values for chunks
#[derive(SystemDesc)]
pub struct ChunkLodSystem;
impl Default for ChunkLodSystem {
fn default() -> Self {
ChunkLodSystem {}
}
}
impl<'a> System<'a> for Chu... |
use crate::RealValue;
#[derive(Debug, Default, Copy, Clone, PartialEq)]
pub struct Padding {
pub top: RealValue,
pub left: RealValue,
pub right: RealValue,
pub bottom: RealValue,
}
impl Padding {
pub fn top_and_bottom(&self) -> RealValue {
self.top + self.bottom
}
pub fn left_and_... |
#[allow(unused_imports)]
use super::util::prelude::*;
use super::util::{Pack, PackDepth};
use super::BlockMut;
use super::Table;
block! {
[pub Scene(constructor, pack)]
(master_table): BlockMut<Table>;
selecting_table: BlockMut<Table> = BlockMut::clone(&master_table);
tables: Vec<BlockMut<Table>> = vec... |
// functions1.rs
// Make me compile! Execute `rustlings hint functions1` for hints :)
fn call_me(num : i32) {
}
fn main() {
call_me(0);
}
|
/// Protocol for address and get-address messages. Implements how nodes exchange
/// connection information about other nodes on the network. Address and
/// get-address messages are exchanged continually alongside ping-pong messages
/// as part of a network connection.
///
/// Protocol starts by creating a subscriptio... |
use crate::preclude::*;
use std::net::SocketAddr;
pub struct KvRaftServer {
num_peers: usize,
nodes: Vec<(RaftNode, KvRaftNode, SocketAddr)>,
}
impl KvRaftServer {
pub fn new(nodes: Vec<(RaftNode, KvRaftNode, SocketAddr)>) -> KvRaftServer {
KvRaftServer {
num_peers: nodes.len(),
... |
mod support;
use cubik::client::ClientContainer;
use support::msg::AppMessage;
use std::io::{self, Write};
use std::collections::HashSet;
use std::time::{Instant, Duration};
use std::thread::sleep;
const PORT: u16 = 27020;
fn player_name(ctr: &ClientContainer<AppMessage>, pid: Option<u8>) -> String {
match pid {
... |
use yew::prelude::*;
pub struct Model {
link: ComponentLink<Self>,
}
pub enum Msg {}
impl Component for Model {
type Message = Msg;
type Properties = ();
fn create(_: Self::Properties, link: ComponentLink<Self>) -> Self {
Self { link }
}
fn update(&mut self, _msg: Self::Message) -> S... |
use crate::mcc::agent::agent_queue::AgentQueue;
use crate::mcc::agent::mcc_agent::MCCAgent;
#[derive(Clone)]
pub struct AgentSpeciesStatistics {
average_sizes: Vec<f64>,
maximum_sizes: Vec<u32>,
minimum_sizes: Vec<u32>,
average_size_increases: Vec<f64>,
}
impl AgentSpeciesStatistics {
pub fn get_o... |
#[doc = "Register `FDCAN_NDAT1` reader"]
pub type R = crate::R<FDCAN_NDAT1_SPEC>;
#[doc = "Register `FDCAN_NDAT1` writer"]
pub type W = crate::W<FDCAN_NDAT1_SPEC>;
#[doc = "Field `ND0` reader - ND0"]
pub type ND0_R = crate::BitReader;
#[doc = "Field `ND0` writer - ND0"]
pub type ND0_W<'a, REG, const O: u8> = crate::Bit... |
use std::ptr::null_mut;
use std::os::unix::io::RawFd;
use libc::c_int;
use {Errno, Result};
use sys::time::TimeVal;
pub const FD_SETSIZE: RawFd = 1024;
#[cfg(any(target_os = "macos", target_os = "ios"))]
#[repr(C)]
#[derive(Clone)]
pub struct FdSet {
bits: [i32; FD_SETSIZE as usize / 32]
}
#[cfg(any(target_os = ... |
/**
* Copyright (c) 2019, Sébastien Blin <sebastien.blin@enconn.fr>
* 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
* not... |
use crate::geometry::{Displacement, Point};
use crate::surface::{Surface, SurfaceExt};
use crate::{
event::{Event, EventOnce},
input::seat::SeatManager,
output_manager::OutputManager,
window::Window,
window_management_policy::WmPolicyManager,
};
use log::{trace, warn};
use std::cell::RefCell;
use std::collect... |
//! A proc-macro attribute for automatically implementing a trait for
//! references, some common smart pointers and closures.
//!
//! ## Simple example
//!
//! ```
//! use auto_impl::auto_impl;
//!
//! // This will generate two additional impl blocks: one `for &T` and one
//! // `for Box<T>` where `T: Foo`.
//! #[auto... |
#![allow(non_upper_case_globals)]
#![allow(non_camel_case_types)]
#![allow(non_snake_case)]
#![allow(dead_code)]
include!(concat!(env!("OUT_DIR"), "/nginx.rs"));
#[no_mangle]
pub unsafe extern "C" fn ngx_http_calculator_handler(
r: *mut ngx_http_request_t,
) -> ngx_int_t {
eprintln!("Hello from Rust!");
0
}
|
use bencode::BEncode;
use std::path::PathBuf;
use std::collections::BTreeMap;
use std::{fmt, cmp};
use url::Url;
use ring::digest;
use util::hash_to_id;
use disk;
#[derive(Serialize, Deserialize, Clone)]
pub struct Info {
pub name: String,
pub announce: String,
pub piece_len: u32,
pub total_len: u64,
... |
/*
* Datadog API V1 Collection
*
* Collection of all Datadog Public endpoints.
*
* The version of the OpenAPI document: 1.0
* Contact: support@datadoghq.com
* Generated by: https://openapi-generator.tech
*/
/// OrganizationSettings : A JSON array of settings.
#[derive(Clone, Debug, PartialEq, Serialize, Des... |
/// `"VK_LAYER_KHRONOS_validation"`
pub const VK_LAYER_KHRONOS_VALIDATION_NAME : &str = "VK_LAYER_KHRONOS_validation"; |
use std::{convert::TryInto, ptr::null_mut};
use z3_sys::*;
use crate::z3::{Context, DatatypeBuilder, DatatypeSort, DatatypeVariant, FuncDecl, Sort, Symbol};
impl<'ctx> DatatypeBuilder<'ctx> {
pub fn new(ctx: &'ctx Context) -> Self {
Self {
ctx,
variants: Vec::new(),
}
}
... |
pub fn tuple() {
let tup = (500, 6.4, 1);
let (_x, mut _y, _z) = tup;
println!("The value of mut y is: {}", _y);
_y = 100.1;
println!("The value of mut y is: {}", _y);
//mut
let mut tup2 = (500, 5.2, 3);
tup2.1 = 4.2;
println!("{}", tup2.1)
}
// Rust 中的数组是固定长度的:一旦声明,它们的长度不能增长... |
#![deny(clippy::all, clippy::pedantic)]
#[allow(
clippy::cast_possible_truncation,
clippy::cast_precision_loss,
clippy::cast_sign_loss
)]
pub fn primes() -> impl Iterator<Item = u64> {
(2_u64..)
// After 2, prime numbers are always odd
.filter(|n| *n == 2 || n.trailing_zeros() == 0)
... |
use read_line::*;
pub fn read_words() -> Vec<String> {
let line = read_line();
line.split_whitespace().map(|s| s.to_owned()).collect()
}
|
pub mod frag;
pub mod vert;
pub mod simple;
|
pub mod tile;
pub mod board;
pub mod cell;
pub mod validation; |
use super::prelude::*;
/// Nodes that will produce output.
pub trait Represent {
/// Return string intended to introduce this piece of data.
fn preamble(&self) -> &str;
/// Return string intended to represent this piece of data.
fn body(&self) -> &str;
/// Return string intended to close this pie... |
extern crate env_logger;
#[cfg(feature = "dx12")]
extern crate gfx_backend_dx12 as back;
#[cfg(feature = "metal")]
extern crate gfx_backend_metal as back;
#[cfg(feature = "vulkan")]
extern crate gfx_backend_vulkan as back;
extern crate gfx_hal as hal;
extern crate glsl_to_spirv;
extern crate rand;
extern crate winit;
... |
#[macro_use] extern crate serde_derive;
pub mod api; |
fn min<T: PartialOrd>(a: T, b: T) -> T {
if a < b { a } else { b }
}
#[derive(Debug)]
struct Coord {
from: usize,
to: usize,
first: usize,
last: usize,
}
impl Coord {
fn new_in(from: usize, to: usize) -> Coord {
Coord { from, to, first: 0, last: 0 }
}
fn new() -> Coord { Self:... |
use crate::format_context::FormatContext;
use crate::order::{
filter_input::FilterInput, filter_output::FilterOutput, input::Input, input_kind::InputKind,
output::Output, output_kind::OutputKind, stream::Stream,
};
use crate::order::{Filter, Order, OutputResult::Entry, ParameterValue};
use crate::probe::deep::{Chec... |
use crate::domain_registry::{DomainConfig, DomainObject};
use crate::{self as pallet_domains, BundleError, DomainRegistry, FungibleHoldId};
use codec::{Decode, Encode, MaxEncodedLen};
use frame_support::traits::{ConstU16, ConstU32, ConstU64, Hooks};
use frame_support::weights::Weight;
use frame_support::{assert_err, as... |
use std::fs::File;
use std::io::Read;
use std::iter::Filter;
fn main() {
let mut file = match File::open("resource/day6.txt") {
Ok(file) => file,
Err(_) => panic!("no such file"),
};
let mut file_contents = String::new();
file.read_to_string(&mut file_contents)
.ok()
.expect("file fail");
... |
#[doc = "Reader of register HW_LOAD_OFFSET"]
pub type R = crate::R<u32, super::HW_LOAD_OFFSET>;
#[doc = "Writer for register HW_LOAD_OFFSET"]
pub type W = crate::W<u32, super::HW_LOAD_OFFSET>;
#[doc = "Register HW_LOAD_OFFSET `reset()`'s with value 0x04"]
impl crate::ResetValue for super::HW_LOAD_OFFSET {
type Type... |
use crate::bytecode::VirtualMachine;
use crate::error::{Result, RuntimeError};
use crate::scm::Scm;
pub type PrimitiveSignature = fn(args: &[Scm], context: &mut VirtualMachine) -> Result<Scm>;
#[derive(Copy, Clone)]
pub struct RuntimePrimitive {
pub name: &'static str,
func: PrimitiveSignature,
arity: Ari... |
use apllodb_shared_components::{find_dup_slow, ApllodbError, ApllodbResult};
use serde::{Deserialize, Serialize};
use std::collections::HashSet;
use crate::column::column_name::ColumnName;
use super::table_constraint_kind::TableConstraintKind;
/// Table constraints.
#[derive(Clone, Eq, PartialEq, Hash, Debug, Serial... |
extern crate rand;
use rand::Rng;
use std::collections::HashMap;
use std::thread;
use std::sync;
use std::ffi::CString;
use std;
use alsa::{Direction, ValueOr};
use alsa::pcm::{PCM, HwParams, Format, Access, Frames};
use std::time::Instant;
#[derive(Clone, Serialize, Deserialize)]
pub struct AudioData {
pub clie... |
#[doc = r"Register block"]
#[repr(C)]
pub struct RegisterBlock {
#[doc = "0x00 - Interrupt and Status Register"]
pub isr: ISR,
#[doc = "0x04 - Interrupt Clear Register"]
pub icr: ICR,
#[doc = "0x08 - Interrupt Enable Register"]
pub ier: IER,
#[doc = "0x0c - Configuration Register"]
pub c... |
extern crate repsheet_etl;
extern crate redis;
use std::borrow::{BorrowMut, Borrow};
use std::time::Instant;
use std::collections::HashMap;
use repsheet_etl::actor::Actor;
use repsheet_etl::response::Response;
use repsheet_etl::address::Address;
use redis::Client;
fn apply_ruleset(actors: &mut HashMap<Address, Actor... |
/// Types of acceptable commands.
#[derive(Debug, PartialEq)]
pub enum Commands {
/// Create a table.
Create(String),
/// Connect to a database.
Connect(String),
/// Import a database.
Import(String),
/// Show the tables of a database.
ShowTables,
/// List databases
ShowDatabases... |
--- cargo-crates/ring-0.16.11/src/rand.rs.orig 2020-02-03 23:35:51 UTC
+++ cargo-crates/ring-0.16.11/src/rand.rs
@@ -181,6 +181,7 @@ use self::sysrand_or_urandom::fill as fi
#[cfg(any(
target_os = "freebsd",
+ target_os = "dragonfly",
target_os = "netbsd",
target_os = "openbsd",
target_os = "s... |
use actix_http::{http::StatusCode, HttpMessage, Request};
use actix_web::{
dev::{Service, ServiceResponse},
test::TestRequest,
};
use chrono::Duration;
use drogue_cloud_database_common::{
error::ServiceError,
models::outbox::{OutboxAccessor, OutboxEntry, PostgresOutboxAccessor},
Client,
};
use drogu... |
struct Solution;
impl Solution {
pub fn integer_break(n: i32) -> i32 {
let mut dp = vec![0; n as usize + 1];
for i in 2..=n {
let mut cur_max = 0;
for j in 1..i {
cur_max = cur_max.max((j * (i - j)).max(j * dp[(i - j) as usize]));
}
dp[... |
/// Used by all v1 modules to get required things in scope for macro expansion.
macro_rules! v1_imports {
() => {
#[allow(unused_imports)]
use rocket::http::Status;
#[allow(unused_imports)]
use rocket::response::status;
#[allow(unused_imports)]
use rocket_contrib::Jso... |
use front::syntax_error::SyntaxError;
use front::tokens::Token;
use loc::Loc;
use std::iter::Peekable;
use std::str::Chars;
pub type ScanResult = Result<Token, SyntaxError>;
pub struct Scanner<'a> {
input: Peekable<Chars<'a>>,
filename: &'a str,
line: i32,
pos: i32,
}
impl<'a> Scanner<'a> {
pub f... |
//! The major function `circular_reference()` is not a demo of how to use circular reference `RefCell`.
//! Instead, the code demonstrates how to prevent using `RefCell`.
//! The approach is introducing data redundancies for many to many relationship.
//! # Example
//! ```
//! let john = Student{name: "John".into()... |
use oauth2::AccessToken;
use serde::Deserialize;
use thiserror::Error;
use std::convert::TryInto;
use std::fmt;
#[derive(Debug, Clone, PartialEq, Deserialize)]
pub struct DeviceCodeErrorResponse {
pub error: String,
pub error_description: String,
pub error_uri: String,
}
impl fmt::Display for DeviceCode... |
/// An enum to represent all characters in the Lepcha block.
#[derive(Debug, Clone, Copy, Hash, PartialEq, Eq)]
pub enum Lepcha {
/// \u{1c00}: 'ᰀ'
LetterKa,
/// \u{1c01}: 'ᰁ'
LetterKla,
/// \u{1c02}: 'ᰂ'
LetterKha,
/// \u{1c03}: 'ᰃ'
LetterGa,
/// \u{1c04}: 'ᰄ'
LetterGla,
//... |
use super::{align_up, Locked};
use alloc::alloc::{GlobalAlloc, Layout};
use core::ptr;
/// # Bump Allocator
///
/// Define a BumpAllocator struct, which is the simplest type of allocator
///
/// This allocator works by adding items to the heap linearly, not accounting for any new free space. When it reaches the end... |
use criterion::*;
use criterion::measurement::WallTime;
use crate::utils::{Cold, Warm, CustomBencher};
pub fn iteration_aos(group: &mut BenchmarkGroup<WallTime>, dataset_size: usize) {
bench_with::<Cold>(&mut *group, "vec-aos-cold", dataset_size as u32);
bench_with::<Warm>(&mut *group, "vec-aos-warm", dataset_... |
use super::*;
/// Structure that saves the writer specific to writing and reading a nodes csv file.
///
/// # Attributes
/// * writer: CSVFileWriter - The common writer for readin and writing a csv.
/// * nodes_column: String - The name of the nodes names column. This parameter is mutually exclusive with nodes_column_... |
use std::collections::HashMap;
use std::io::BufRead;
pub fn two_a<I>(buf: I) -> i32
where
I: BufRead,
{
let mut two_count = 0;
let mut three_count = 0;
for line in buf.lines() {
let mut char_counts = HashMap::new();
for chr in line.unwrap().chars() {
match char_counts.get(&c... |
//! S3 bindings for Rust
//!
//! Not all functions are yet implemented. Check [S3Helper](http://rusoto.github.io/rusoto/rusoto/s3/struct.S3Helper.html)
//! for implemented functions and convenience functions.
//!
#![allow(unused_variables, unused_mut)]
use credentials::*;
use xml::*;
use signature::*;
use params::*;
... |
extern crate advent_support;
fn update_bounds(min: i32, max: i32, upper: bool) -> (i32, i32) {
let step = (max - min)/2;
let result;
if upper {
result = (min+step+1, max);
} else {
result = (min, min+step)
};
// println!("({}, {}), {} -> ({}, {})", min, max, upper, result.0, res... |
use rkyv::{Deserialize, Infallible};
use twilight_model::application::{
command::CommandOptionChoice, interaction::ApplicationCommandAutocomplete,
};
use crate::{
commands::osu::respond_autocomplete,
core::ArchivedBytes,
custom_client::OsekaiMedal,
embeds::{EmbedData, MedalEmbed},
error::Error,... |
mod lib;
fn main() {
rust::main();
}
|
use core::fmt;
pub struct Log {
pub data: [u8; 65536],
pub start: usize,
pub end: usize
}
impl Log {
pub fn new() -> Log {
Log {
data: [0; 65536],
start: 0,
end: 0
}
}
fn move_start(&mut self) {
self.start += 1;
while self.st... |
#[doc = "Reader of register DDRPHYC_DTDR0"]
pub type R = crate::R<u32, super::DDRPHYC_DTDR0>;
#[doc = "Writer for register DDRPHYC_DTDR0"]
pub type W = crate::W<u32, super::DDRPHYC_DTDR0>;
#[doc = "Register DDRPHYC_DTDR0 `reset()`'s with value 0xdd22_ee11"]
impl crate::ResetValue for super::DDRPHYC_DTDR0 {
type Typ... |
use failure::{self, bail, format_err};
use regex::Regex;
use std::cmp;
use std::io::{self, Read};
use std::result;
use std::str::FromStr;
type Result<T> = result::Result<T, failure::Error>;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Army {
Immune,
Infection,
}
#[derive(Clone)]
struct Group {
army:... |
use crate::clip::Rectangle;
use crate::VertexSource;
#[derive(Debug,Copy,Clone,PartialEq)]
pub enum PathCommand {
Stop,
MoveTo,
LineTo,
Close,
//Curve3,
//Curve4,
//CurveN,
//Catrom,
//UBSpline,
//EndPoly,
}
impl Default for PathCommand {
fn default() -> PathCommand {
... |
//! [`Result`] and [`Error`] types for this crate, powered by `error-chain`.
//!
//! [`Result`]: type.Result.html
//! [`Error`]: struct.Error.html
error_chain! {
errors {
/// API returned error.
ApiError(http_status: ::hyper::status::StatusCode,
retcode: u64,
stat... |
use crossbeam::atomic::AtomicCell;
use std::sync::Arc;
use crate::{
app::{AppSettings, NodeWidth},
vulkan::draw_system::edges::EdgesUBO,
};
pub struct MainViewSettings {
node_width: Arc<NodeWidth>,
label_radius: Arc<AtomicCell<f32>>,
edges_enabled: Arc<AtomicCell<bool>>,
edges_ubo: Arc<Atomic... |
use std::fs::File;
use std::io::{BufReader, BufWriter};
use super::Mapper;
use crate::cartridge::{MirrorMode, Rom, RomMapper};
use crate::savable::Savable;
pub struct Mapper0 {
rom: Rom,
ram: Vec<u8>,
}
impl Mapper0 {
pub fn new(rom: Rom) -> Self {
Self {
rom,
ram: vec![0;... |
const SRAM_LOWER: usize = 0x2000_0000;
const SRAM_UPPER: usize = 0x3000_0000;
/// Does this slice reside entirely within RAM?
pub(crate) fn slice_in_ram(slice: &[u8]) -> bool {
let ptr = slice.as_ptr() as usize;
ptr >= SRAM_LOWER && (ptr + slice.len()) < SRAM_UPPER
}
/// Return an error if slice is not in RAM... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.