text stringlengths 8 4.13M |
|---|
use challenges::chal39::{RsaKeyPair, RsaPubKey, SHA1_PKCS1_DIGESTINFO_PREFIX};
use num::pow::Pow;
use num::{BigUint, One};
use sha1::{Digest, Sha1};
use std::cmp::Ordering;
fn main() {
println!("🔓 Challenge 42");
let msg = b"hi mom".to_vec();
let pk = RsaKeyPair::default().pubKey;
let forged_sig = fo... |
pub mod qqmlparserstatus;
pub use self::qqmlparserstatus::QQmlParserStatus;
pub mod qqmlpropertymap;
pub use self::qqmlpropertymap::QQmlPropertyMap;
pub mod qqmlcomponent;
pub use self::qqmlcomponent::QQmlComponent;
pub mod qjsvalueiterator;
pub use self::qjsvalueiterator::QJSValueIterator;
pub mod qqmlextensionplu... |
#[cfg(all(not(target_arch = "wasm32"), test))]
mod test;
use std::convert::TryInto;
use anyhow::*;
use liblumen_alloc::erts::exception::{self, *};
use liblumen_alloc::erts::process::trace::Trace;
use liblumen_alloc::erts::process::Process;
use liblumen_alloc::erts::term::prelude::Term;
/// `//2` infix operator. Un... |
// Copyright 2022 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 ... |
use sp_std::prelude::*;
#[cfg(feature = "std")]
use std::fmt;
use codec::{Compact, Decode, Encode, Error, Input};
use sp_core::{blake2_256,H256,};
use sp_runtime::{generic::Era, MultiSignature,AccountId32 as AccountId};
pub type AccountIndex = u64;
pub type GenericAddress =AccountId; // crate::multiaddress::MultiAdd... |
// 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 svg::{Document};
use svg::node::element::Circle;
use svg::node::element::Rectangle;
use svg::node;
use svg::node::element;
// lets do this on an 8.5 by 8.5 square cause itll fit on my paper
const DOCUMENT_HEIGHT: f64 = 8.5;
pub const BAR_WIDTH: f64 = 0.01; // fractions
pub const BAR_LENGTH: f64 = 0.03;
const ALI... |
use super::Forwarder;
use super::TxType;
use failure::Error;
use log::{error, info};
use std::net::SocketAddr;
use std::result::Result;
use futures_03::prelude::*;
use stream_cancel::{Trigger, Tripwire};
use tokio::net::UdpSocket;
use std::cell::RefCell;
use std::rc::Rc;
type LongLive = Rc<RefCell<UdpServer>>;
type ... |
#![allow(dead_code)]
use super::Payload;
use serde::{de::DeserializeOwned, Serialize};
use std::io;
use tokio::{
io::{AsyncReadExt, AsyncWriteExt},
net::TcpStream,
};
use tokio_util::codec::{Decoder, Encoder};
pub(crate) struct Conn<T>
where
T: Serialize,
{
buf: bytes::BytesMut,
payload: Payload<T... |
#[doc = "Reader of register CSICFGR"]
pub type R = crate::R<u32, super::CSICFGR>;
#[doc = "Writer for register CSICFGR"]
pub type W = crate::W<u32, super::CSICFGR>;
#[doc = "Register CSICFGR `reset()`'s with value 0"]
impl crate::ResetValue for super::CSICFGR {
type Type = u32;
#[inline(always)]
fn reset_va... |
use super::data_filtering::{build_filter_plan, FilterPlan, PartialResults, Types};
use super::error::PolarResult;
use super::events::*;
use super::kb::*;
use super::messages::*;
use super::parser;
use super::rewrites::*;
use super::roles_validation::{validate_roles_config, VALIDATE_ROLES_CONFIG_RESOURCES};
use super::r... |
use crate::models::launch::LaunchID;
use serenity::builder::{CreateActionRow, CreateButton, CreateComponents};
use serenity::model::prelude::message_component::ButtonStyle;
pub struct RemindComponent<'a> {
launch_id: &'a LaunchID,
}
impl<'a> RemindComponent<'a> {
pub fn new(launch_id: &'a LaunchID) -> RemindC... |
extern crate markdown;
extern crate serde_json;
#[macro_use]
extern crate tera;
use std::collections::HashMap;
use tera::{Context, Result, Value, to_value};
pub fn markdown_filter(value: Value, _: HashMap<String, Value>) -> Result<Value> {
let s = try_get_value!("upper", "value", String, value);
Ok(to_value(m... |
use super::util::{is_name_char, take_char};
use super::value::value_expression;
use super::{input_to_str, input_to_string};
use nom::alphanumeric;
use nom::types::CompleteByteSlice as Input;
use sass::{SassString, StringPart};
use value::Quotes;
named!(pub sass_string<Input, SassString>,
map!(
many1!... |
use super::BodyId;
use crate::{
builtin_functions::BuiltinFunction,
hir,
id::CountableId,
impl_countable_id, impl_display_via_richir,
rich_ir::{ReferenceKey, RichIrBuilder, ToRichIr, TokenType},
};
use derive_more::{From, TryInto};
use enumset::EnumSet;
use itertools::Itertools;
use num_bigint::BigI... |
use lucet_runtime::{DlModule, Limits, MmapRegion, Region};
fn main() {
let module = DlModule::load("./wasm.out").expect("load failed");
let limits = Limits {
heap_memory_size: 1024 * 1024 * 64,
heap_address_space_size: 0x200000000,
stack_size: 128 * 1024,
globals_size: 4096,
... |
mod enumerator;
mod mem_access;
mod open_options;
mod process;
mod record;
use crate::sys::process as imp;
pub use enumerator::ProcessEnumerator;
pub use mem_access::MemAccess;
pub use open_options::ProcessOpenOptions;
pub use process::Process;
pub use record::ProcessRecord;
#[derive(Clone, Copy)]
pub struct Pid {
... |
// ignore-compare-mode-nll
// revisions: base nll
// [nll]compile-flags: -Zborrowck=mir
fn bar<F>(blk: F) where F: FnOnce() + 'static {
}
fn foo(x: &()) {
bar(|| {
//[base]~^ ERROR `x` has an anonymous lifetime `'_` but it needs to satisfy a `'static` lifetime requirement [E0759]
//[nll]~^^ ERROR ... |
extern crate core;
fn map_symbol_to_value(symbol: &str) -> u64 {
match symbol {
"A" | "X" => 0,
"B" | "Y" => 1,
"C" | "Z" => 2,
_ => panic!("unexpected symbol"),
}
}
fn calculate_score(other: u64, own: u64) -> u64 {
let win_score = (other as i64 - own as i64) % 3;
let wi... |
pub use crate::az_core::*;
pub use crate::az_return_codes::AzReturnCode;
use azsys;
use std::slice;
use std::str;
pub struct HubClientBuilder<'a> {
host_name: Option<&'a str>,
device_id: Option<&'a str>,
client_options: Option<HubClientOptions>,
}
pub struct HubClient {
inner: azsys::az_iot_hub_client... |
#[macro_use]
extern crate log;
mod support;
use self::support::*;
#[test]
fn outbound_asks_controller_api() {
let _ = env_logger::init();
let srv = server::new().route("/", "hello").route("/bye", "bye").run();
let ctrl = controller::new()
.destination("test.conduit.local", srv.addr)
.run(... |
use std::ops::Deref;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Mutex};
use std::time::{Duration, Instant};
use crate::node::{NetworkGraph, RoutingPeerManager};
use crate::persist::SenseiPersister;
use lightning_rapid_gossip_sync::RapidGossipSync;
use super::router::AnyScorer;
const PING_TI... |
pub struct Solution;
impl Solution {
pub fn calculate_minimum_hp(dungeon: Vec<Vec<i32>>) -> i32 {
let mut dungeon = dungeon;
let m = dungeon.len();
let n = dungeon[0].len();
for i in (0..m).rev() {
for j in (0..n).rev() {
let next = match (i + 1 < m, j + ... |
mod util;
use self::util::test_script;
#[test]
fn test_upvalue() {
test_script(
r#"
local i = 0
local function inc(amt)
i = i + amt
end
inc(1)
inc(2)
inc(3)
return i
"#,
6,
);
}
#[test]
... |
use std::sync::{Mutex, Arc};
use std::thread;
fn main() {
// creating a variable to an i32
let counter = Arc::new(Mutex::new(0));
let mut handles = vec![];
// spawn 10 threads
for _ in 0..10 {
let counter = Arc::clone(&counter);
let handle = thread::spawn(move || {
... |
use std::ffi::CString;
use ash::{extensions::khr, vk};
use super::{
error::{GraphicsError, GraphicsResult},
surface,
};
pub struct PoolsWrapper {
pub commandpool_graphics: vk::CommandPool,
}
impl PoolsWrapper {
pub fn init(
logical_device: &ash::Device,
queue_families: &QueueFamilies... |
use darling::ast::Data;
use proc_macro::TokenStream;
use proc_macro2::Span;
use quote::quote;
use syn::{Error, LitInt};
use crate::{
args::{self, RenameTarget},
utils::{get_crate_name, get_rustdoc, visible_fn, GeneratorResult},
};
pub fn generate(object_args: &args::MergedSubscription) -> GeneratorResult<Toke... |
use std::collections::BTreeMap;
use std::fs::File;
use std::path::Path;
use std::io::Read;
pub fn parse<P>(path: P) -> super::Result<BTreeMap<String, String>>
where P: AsRef<Path>
{
let mut map = BTreeMap::new();
let mut f = try!(File::open(path));
let mut s = String::new();
try!(f.read_to_string(&... |
pub mod gameplay;
pub mod def;
pub mod winner;
pub const ARENA_HEIGHT: f32 = 1000.0;
pub const ARENA_WIDTH: f32 = 1000.0; |
use byteorder::{BigEndian, ReadBytesExt, WriteBytesExt};
use std::io::Cursor;
#[derive(PartialEq, Debug, Clone)]
pub enum Message {
KeepAlive,
Choke,
Unchoke,
Interested,
NotInterested,
Bitfield(Vec<u8>),
Request(u32, u32, u32),
Have(u32),
Piece(u32, u32, Vec<u8>), // index * offset... |
use crate::utils::*;
use rand;
use std::cmp::Ordering;
use std::collections::BinaryHeap;
use rstris::figure::*;
use rstris::movement::*;
use rstris::playfield::*;
use rstris::position::Position;
#[derive(Debug, Clone)]
struct MoveAndTime {
movement: Movement,
time: u64,
}
impl Ord for MoveAndTime {
fn cm... |
use std::any::{Any, TypeId};
use std::borrow::Borrow;
use std::collections::hash_map::DefaultHasher;
use std::collections::HashMap;
use std::hash::{Hash, Hasher};
use std::panic::{catch_unwind, AssertUnwindSafe};
use std::process::exit;
use std::result::Result;
use fuzzcheck_common::arg::{Arguments, FuzzerCommand};
us... |
pub(crate) trait CastTo<T: Copy> {
fn cast_to(self) -> T;
}
macro_rules! impl_cast_to {
($typ:ty) => {
impl CastTo<$typ> for $typ {
fn cast_to(self) -> $typ {
self
}
}
};
($src:ty, $dst:ty) => {
impl CastTo<$dst> for $src {
fn... |
use colored::*;
//extern crate derive_more;
//use derive_more::{Add, Display, From, Into};
use indextree;
use std::cmp::PartialEq;
use std::fmt;
use unicode_segmentation::UnicodeSegmentation;
///This is a toy parser/compiler loosely taking inspiration from [Elm Parser](https://package.elm-lang.org/packages/elm/parser/... |
use crate::error::{GameError, GameResult};
use std::path::Path;
pub struct Filesystem {}
impl Filesystem {
pub(crate) fn new(_: FilesystemConfig) -> GameResult<Self> {
Ok(Self {})
}
pub fn read(&self, path: impl AsRef<Path>) -> GameResult<Vec<u8>> {
std::fs::read(path).map_err(|error| Ga... |
pub fn last<T>(li: &Vec<T>) -> Option<&T> {
li.last()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_last() {
let li = vec![1, 1, 2, 3, 5, 8];
assert_eq!(last(&li), Some(&8));
}
#[test]
fn test_last_empty_list() {
let li = Vec::<usize>::new();
asse... |
use std::collections::BTreeSet;
fn task1(linestring: &str) -> u32 {
let lines = linestring.lines();
let mut sum = 0;
'outer: for line in lines {
let mut words = BTreeSet::new();
for word in line.split_whitespace() {
if words.contains(word) {
contin... |
use convert_case::{Case, Casing};
use proc_macro2::{Ident, Span};
use serde::{Deserialize, Serialize};
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ECS<'a> {
/// The path of the output data structure
pub name: &'a str,
/// The error type, if none, default to `Box<dyn Error>`
pub error: O... |
use std::fmt;
use crate::*;
/// Represents City tile of given team at position
///
/// # See also
///
/// Check <https://www.lux-ai.org/specs-2021#CityTiles>
#[derive(Clone, PartialEq, fmt::Debug)]
pub struct CityTile {
/// City id used as command arguments
pub cityid: EntityId,
/// Team id, whom this ci... |
pub struct Solution;
impl Solution {
pub fn character_replacement(s: String, k: i32) -> i32 {
use std::collections::HashMap;
let bytes = s.as_bytes();
let n = bytes.len();
let k = k as usize;
let mut counts = HashMap::new();
for &b in bytes {
*counts.entr... |
use std::{thread, time};
use futures::future::{ Future, FutureExt };
use tokio::time::{delay_for, Duration};
#[tokio::main]
async fn main() {
std::thread::spawn(|| {
match block_alarm::background_thread() {
Ok(_) => {},
Err(e) => {
println!("background thread had a... |
use std::any::Any;
use std::ops::{Range, RangeInclusive};
use fastrand::Rng;
use super::size_to_cplxity;
use crate::Mutator;
/// Mutator for a `char` within a list of ranges
#[derive(Debug)]
pub struct CharacterMutator {
ranges: Vec<RangeInclusive<char>>,
total_length: u32,
lengths: Vec<Range<u32>>,
... |
use juniper::GraphQLInterface;
#[derive(GraphQLInterface)]
#[graphql(impl = Node2Value, for = Node2Value)]
struct Node1 {
id: String,
}
#[derive(GraphQLInterface)]
#[graphql(impl = Node1Value, for = Node1Value)]
struct Node2 {
id: String,
}
fn main() {}
|
mod window;
mod workspace;
mod screen;
mod layouts;
mod state;
mod stack;
mod keys;
mod command;
pub mod config;
pub mod manager;
pub mod displays;
|
extern crate slab;
use slab::Slab;
pub trait Drawer{
fn set_fill_style(&mut self, rgba:(f32, f32, f32, f32));
fn set_stroke_style(&mut self, rgba:(f32, f32, f32, f32));
fn set_font_style(&mut self, size: f32);
fn draw_rect(&mut self, xywh:(f32, f32, f32, f32));
fn draw_text(&mut self, text: &str, xy... |
#![allow(dead_code)]
use rppal::gpio::Gpio;
use std::time::Duration;
use tokio::time::sleep;
// Gpio uses BCM pin numbering. BCM GPIO 23 is tied to physical pin 16.
const GPIO_PWM: u8 = 12;
// Servo configuration. Change these values based on your servo's verified safe
// minimum and maximum values.
//
// Period: 20 ... |
#[derive(PartialEq, Eq, Debug)]
pub enum GameRoundResult {
PlayerBusted,
DealerBusted,
PlayerWon,
DealerWon,
Draw,
}
#[derive(PartialEq, Eq)]
pub enum State {
GameStart,
GameEnd,
GameRoundStart,
GameRoundEnd,
PlayerTurn,
DealerTurn,
}
|
use crate::errors::*;
use lazy_static::lazy_static;
use regex::Regex;
use std::collections::HashMap;
use std::sync::RwLock;
type RegexCacheMap = HashMap<String, Regex>;
lazy_static! {
static ref REGEX_CACHE: RwLock<RegexCacheMap> = RwLock::new(HashMap::new());
}
pub struct RegexCache;
impl RegexCache {
pub f... |
//! Describe decisions that must be specified.
use crate::ir::{self, Adaptable};
use fxhash::FxHashMap;
use itertools::{Either, Itertools};
use serde::Serialize;
use std;
use utils::*;
pub fn dummy_choice() -> Choice {
let def = ChoiceDef::Enum("Bool".into());
let args = ChoiceArguments::Plain { vars: vec![] }... |
use std::collections::VecDeque;
use itertools::Itertools;
pub use crate::graph::Graph;
pub use crate::fasttw::Decomposition;
pub use crate::parser::Formula;
pub type Assignment = Vec<bool>;
pub type NiceDecomposition = Vec<(usize, Node)>;
// assignment (bit-map), score, true variables
pub type Configuration = (usize... |
use cpp_data::{CppDataWithDeps, CppData, ParserCppData, ProcessedCppData, CppTypeAllocationPlace,
CppTypeKind, CppVisibility, CppTemplateInstantiations, CppTemplateInstantiation,
CppTypeData, CppBaseSpecifier};
use cpp_method::{CppMethod, CppMethodKind, CppMethodClassMembership};
use cpp_t... |
use super::utills::get_points;
use prelude::*;
use serenity::framework::standard::CreateGroup;
use store::UserInfo;
use store::UsersInfo;
use utills::success;
use PREFIX;
struct StartCommand;
impl Command for StartCommand {
fn execute(&self, ctx: &mut Context, msg: &Message, _args: Args) -> CommandResult {
let ... |
use std::iter::FromIterator;
use std::str::FromStr;
use toml_datetime::*;
use crate::key::Key;
use crate::parser;
use crate::repr::{Decor, Formatted};
use crate::{Array, InlineTable, InternalString, RawString};
/// Representation of a TOML Value (as part of a Key/Value Pair).
#[derive(Debug, Clone)]
pub enum Value {... |
// Copyright (C) 2019 Robin Krahl <robin.krahl@ireas.org>
// SPDX-License-Identifier: MIT
use std::io::{self, Write};
use crate::{Choice, Input, Message, Password, Question, Result};
/// The fallback backend using standard input and output.
///
/// This backend is intended as a fallback backend to use if no other ba... |
fn main() {
#macro[[#m1[a], a*4]];
assert (#m1[2] == 8);
}
|
use super::component_prelude::*;
#[derive(Default)]
pub struct CanRun;
impl Component for CanRun {
type Storage = NullStorage<Self>;
}
|
use std::{cmp::Reverse, collections::BinaryHeap};
use proconio::input;
fn main() {
input! {
n: usize,
mut k: usize,
mut a: [usize; n],
};
let mut heap = BinaryHeap::new();
for i in 0..n {
heap.push((Reverse(a[i]), Reverse(i)));
}
let mut sub = 0;
while let ... |
use std::{collections::HashMap, fmt::Display};
use async_trait::async_trait;
use data_types::{Namespace, NamespaceId, NamespaceSchema};
use super::NamespacesSource;
#[derive(Debug, Clone)]
/// contains [`Namespace`] and a [`NamespaceSchema`]
pub struct NamespaceWrapper {
/// namespace
pub ns: Namespace,
... |
#[doc = "Reader of register IM"]
pub type R = crate::R<u32, super::IM>;
#[doc = "Writer for register IM"]
pub type W = crate::W<u32, super::IM>;
#[doc = "Register IM `reset()`'s with value 0"]
impl crate::ResetValue for super::IM {
type Type = u32;
#[inline(always)]
fn reset_value() -> Self::Type {
... |
use std::marker::PhantomData;
use std::mem::size_of;
struct Something(i32, f32, String);
fn main() {
assert_eq!(0, size_of::<PhantomData<i32>>());
assert_eq!(0, size_of::<PhantomData<Something>>());
}
|
use crate::{
self as p2p, BootstrapConfig, Event, EventReceiver, Peers, PeriodicTaskConfig, TestEvent,
};
use anyhow::{Context, Result};
use core::panic;
use libp2p::identity::Keypair;
use libp2p::multiaddr::Protocol;
use libp2p::{Multiaddr, PeerId};
use std::collections::HashSet;
use std::fmt::Debug;
use std::str:... |
#[cfg(test)]
mod test;
use liblumen_alloc::erts::process::Process;
use liblumen_alloc::erts::term::prelude::Term;
#[native_implemented::function(erlang:self/0)]
pub fn result(process: &Process) -> Term {
process.pid_term()
}
|
#[doc = r"Register block"]
#[repr(C)]
pub struct RegisterBlock {
#[doc = "0x00 - DSI Host version register"]
pub vr: VR,
#[doc = "0x04 - DSI Host control register"]
pub cr: CR,
#[doc = "0x08 - DSI Host clock control register"]
pub ccr: CCR,
#[doc = "0x0c - DSI Host LTDC VCID register"]
p... |
// Compiler:
//
// Run-time:
// status: 0
#![feature(asm, global_asm)]
global_asm!("
.global add_asm
add_asm:
mov rax, rdi
add rax, rsi
ret"
);
extern "C" {
fn add_asm(a: i64, b: i64) -> i64;
}
fn main() {
unsafe {
asm!("nop");
}
let x: u64;
unsafe {
asm!("m... |
//! This module implements common functionalities for OS's strings.
use crate::sys::{Error, OsStr, OsString};
use core::{fmt, ops::Deref};
#[cfg(feature = "std")]
use std::{
ffi,
path::{Path, PathBuf},
};
impl Clone for OsString {
fn clone(&self) -> Self {
self.to_os_str()
.and_then(|... |
#[doc = "Reader of register CR"]
pub type R = crate::R<u32, super::CR>;
#[doc = "Writer for register CR"]
pub type W = crate::W<u32, super::CR>;
#[doc = "Register CR `reset()`'s with value 0x1000"]
impl crate::ResetValue for super::CR {
type Type = u32;
#[inline(always)]
fn reset_value() -> Self::Type {
... |
use openexr_sys as sys;
use std::ffi::CString;
use std::path::Path;
use crate::core::{
error::Error,
header::{HeaderRef, HeaderSlice},
};
type Result<T, E = Error> = std::result::Result<T, E>;
/// Manages writing multi-part images.
///
/// Multi-part files are essentially just containers around multiple
///... |
#[doc = "Reader of register CRL"]
pub type R = crate::R<u32, super::CRL>;
#[doc = "Writer for register CRL"]
pub type W = crate::W<u32, super::CRL>;
#[doc = "Register CRL `reset()`'s with value 0x20"]
impl crate::ResetValue for super::CRL {
type Type = u32;
#[inline(always)]
fn reset_value() -> Self::Type {... |
#![cfg_attr(not(feature = "std"), no_std)]
use ink_lang as ink;
use schnorrkel::{PublicKey,Signature,signing_context};
#[ink::contract]
mod dependcydemo {
use super::*;
use ink_prelude::{string::String};
use scale::Encode;
const SIGNING_CTX: &[u8] = b"substrate";
/// Defines the storage of y... |
extern crate itertools_num;
#[macro_use]
extern crate lazy_static;
mod controllers;
mod game_state;
mod geometry;
mod models;
use std::os::raw::{c_double, c_int};
use std::sync::Mutex;
use self::game_state::GameState;
use self::geometry::Size;
use self::controllers::{Actions, TimeController};
lazy_static! {
sta... |
use crate::{
lexer::{Lexer, Token, TokenType},
Comment, Span,
};
use core::fmt::{self, Display, Formatter};
/// A [`char`]-[`f32`] pair, used for things like arguments (`X3.14`), command
/// numbers (`G90`) and line numbers (`N10`).
#[derive(Debug, Copy, Clone, PartialEq)]
#[cfg_attr(
feature = "serde-1",
... |
pub mod minimax;
pub mod alphabeta;
pub mod heuristics;
pub mod turn;
pub mod types; |
extern crate allegro;
extern crate allegro_font;
extern crate allegro_image;
extern crate tiled;
mod states;
use allegro::{Bitmap, Color, Core, SharedBitmap, SubBitmap};
use std::collections::HashMap;
use std::collections::hash_map::Entry;
use std::fs::File;
use std::mem;
use std::rc::Rc;
use std::path::{Path, PathBu... |
use convert_case::{Case, Casing};
use proc_macro2::{Ident, Span, TokenStream};
use serde::{Deserialize, Serialize};
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum ComponentStorage {
/// Backed by a vector: this means that data is reserved
/// for every entity, including ones that don't have it, this
... |
///! dag-pb support operations. Placing this module inside unixfs module is a bit unfortunate but
///! follows from the inseparability of dag-pb and UnixFS.
use crate::pb::PBNode;
use alloc::borrow::Cow;
use core::convert::TryFrom;
use core::fmt;
use core::ops::Range;
/// Extracts the PBNode::Data field from the block... |
#[doc = "Reader of register SSFIFO0"]
pub type R = crate::R<u32, super::SSFIFO0>;
#[doc = "Reader of field `DATA`"]
pub type DATA_R = crate::R<u16, u16>;
impl R {
#[doc = "Bits 0:11 - Conversion Result Data"]
#[inline(always)]
pub fn data(&self) -> DATA_R {
DATA_R::new((self.bits & 0x0fff) as u16)
... |
use rpc_client::*;
use utils::hex_to_vec;
use bitcoin;
use serde_json;
use tokio;
use bitcoin_hashes::sha256d::Hash as Sha256dHash;
use bitcoin_hashes::hex::ToHex;
use futures::future;
use futures::future::Future;
use futures::{Stream, Sink};
use futures::sync::mpsc;
use lightning::chain::chaininterface;
use light... |
pub enum Button {
A,
B,
Start,
Select,
L,
R,
LeftDPadUp,
LeftDPadDown,
LeftDPadLeft,
LeftDPadRight,
RightDPadUp,
RightDPadDown,
RightDPadLeft,
RightDPadRight,
}
pub struct GamePad {
a_pressed: bool,
b_pressed: bool,
start_pressed: bool,
select_pre... |
#![allow(clippy::all)]
const NUM_BINARY_DIGITS: usize = 12;
fn calc_gamma_rate<'a>(input: impl Iterator<Item = u16> + 'a) -> u16 {
let most_common_acc = input.fold([0i64; NUM_BINARY_DIGITS], |mut most_common_acc, number| {
for i in 0..NUM_BINARY_DIGITS {
match (number & (1 << i)) >> i {
... |
use actix::prelude::*;
use actix::{
Recipient
};
use crate::WorkerClient;
use crate::messages::{
Connect,
ControllerState,
WorkerCommand,
StatusUpdate,
CreateWorker
};
use crate::uuid;
// This is following the pattern here:
// https://github.com/actix/examples/blob/master/websocket-chat/src/s... |
use crate::database::Database;
use candy_frontend::{
cst::CstDb,
error::CompilerError,
module::{Module, ModuleDb, ModuleKind, Package, PackagesPath},
position::{line_start_offsets_raw, Offset, PositionConversionDb},
};
use extension_trait::extension_trait;
use itertools::Itertools;
use lsp_types::{Diagn... |
fn main() {
let mut x = 5;
println!("The value of x is : {}", x);
x = 6;
println!("The value of x is : {}", x);
const MAX_POINTS: u32 = 100000;
println!("The value of c is : {}", MAX_POINTS);
let y = 10;
let y = y*2;
let y = y/3;
println!("The value of y is : {}", y);
let... |
// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT.
pub fn parse_http_generic_error(
response: &http::Response<bytes::Bytes>,
) -> Result<smithy_types::Error, smithy_json::deserialize::Error> {
crate::json_errors::parse_generic_error(response.body(), response.headers())
}
pub fn de... |
use tera_crate::{Tera, TesterFn, FilterFn, GlobalFn};
use serde::Serialize;
use ::traits::{RenderEngine, RenderEngineBase, AdditionalCIds};
use ::spec::{TemplateSpec, SubTemplateSpec, TemplateSource};
use self::error::TeraError;
pub mod error;
pub struct TeraRenderEngine {
tera: Tera
}
impl TeraRenderEngine {
... |
use std::borrow::{Borrow, BorrowMut};
pub struct Post {
state: Option<Box<dyn State>>,
content: String,
}
impl Post {
pub fn new() -> Post {
Post {
state: Some(Box::new(Draft {})),
content: String::new(),
}
}
pub fn add_text(&mut self, text: &str) {
... |
// Copyright 2019-2020 PolkaX. Licensed under MIT or Apache-2.0.
pub mod trait_impl;
use std::cell::RefCell;
use std::collections::BTreeMap;
use bigint::U256;
use cid::Cid;
use ipld_cbor::{cbor_value_to_struct, struct_to_cbor_value};
use serde::{de::DeserializeOwned, Serialize};
use serde_cbor::Value;
use crate::er... |
use proconio::{input, marker::Bytes};
fn main() {
input! {
s: Bytes,
};
for i in 0..s.len() {
if b'A' <= s[i] && s[i] <= b'Z' {
println!("{}", i + 1);
return;
}
}
unreachable!();
}
|
//! HTTP authorisation helpers.
use http::HeaderValue;
/// We strip off the "authorization" header from the request, to prevent it from being accidentally logged
/// and we put it in an extension of the request. Extensions are typed and this is the typed wrapper that
/// holds an (optional) authorization header value... |
pub mod de;
mod ser;
pub mod shared;
|
//! Alacritty socket IPC.
use std::ffi::OsStr;
use std::io::{BufRead, BufReader, Error as IoError, ErrorKind, Result as IoResult, Write};
use std::os::unix::net::{UnixListener, UnixStream};
use std::path::PathBuf;
use std::{env, fs, process};
use log::warn;
use winit::event_loop::EventLoopProxy;
use winit::window::Wi... |
pub struct Solution;
impl Solution {
pub fn lexical_order(n: i32) -> Vec<i32> {
Solver::new(n).solve()
}
}
struct Solver {
n: i32,
nums: Vec<i32>,
}
impl Solver {
fn new(n: i32) -> Self {
Self {
n,
nums: Vec::with_capacity(n as usize),
}
}
f... |
mod encapsulation;
mod trait_object;
mod state_pattern;
mod state_pattern_redef;
pub use self::trait_object::gui;
pub use self::encapsulation::avg;
pub use self::state_pattern::blog;
pub use self::state_pattern_redef::blog2;
use self::gui::Draw;
pub struct TextBlock {
pub width: u32,
pub height: u32,
pub... |
extern crate prisoners_dilemma;
use prisoners_dilemma::*;
// use prisoners_dilemma::history::*;
// use prisoners_dilemma::choice::*;
use prisoners_dilemma::strategy::*;
const ROUNDS: usize = 10;
fn main() {
println!("Starting Game");
// put all the strategies into a list so we can try all the combinations.
... |
//! A module for Reading/Writing ROSE data types to/from disk
mod file;
mod path;
mod reader;
mod writer;
pub use self::file::RoseFile;
pub use self::path::PathRoseExt;
pub use self::reader::ReadRoseExt;
pub use self::writer::WriteRoseExt;
|
use actix_web::{
web::{block, Data, Json},
Result,
};
use serde::{Deserialize, Serialize};
use validator::Validate;
use db::{
get_conn,
models::{Game, User},
PgPool,
};
use errors::Error;
use crate::validate::validate;
#[derive(Clone, Deserialize, Serialize, Validate)]
pub struct JoinRequest {
... |
//! Тесты
//!
//! Реализован комплексный тест на расборку/сборку всех фалов из директории test_cases
#[cfg(test)]
mod complex_tests {
use crate::read_write::*;
use crate::sig::*;
use std::fs::File;
use std::io::prelude::*;
use std::path::Path;
fn write_test<T: HasWrite>(sig: &T) -> Vec<u8> {
... |
use std::rc::Rc;
use scheme::LispResult;
use scheme::value::Sexp;
use scheme::value::Sexp::*;
use scheme::env::Environment;
use scheme::error::LispError::*;
use scheme::value::HostFunction2;
use scheme::value::Transformer;
use std::collections::HashMap;
use std::collections::vec_deque::VecDeque;
use scheme::ELLIPSIS;
... |
/// The keeper monitors the chain for underwater accounts on Hifi and sends a liquidation
/// transaction when it discovers one.
#[allow(unused)]
pub struct Keeper {
last_block: u64,
}
|
/*
* @lc app=leetcode id=64 lang=rust
*
* [64] Minimum Path Sum
*/
// @lc code=start
use std::cmp::min;
impl Solution {
pub fn min_path_sum(grid: Vec<Vec<i32>>) -> i32 {
let m = grid.len();
let n = grid[0].len();
let mut best = vec![vec![0; n]; m];
best[0][0] = grid[0][0];
... |
use actix_multipart::Multipart;
use actix_web::Error;
use bytes::{Buf, BufMut, Bytes, BytesMut};
use futures::{StreamExt, TryStreamExt};
pub async fn split_payload(payload: &mut Multipart) -> Result<(Option<String>, Bytes), Error> {
let mut file_data = BytesMut::with_capacity(10 * 1024 * 1024);
let mut filenam... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.