text stringlengths 8 4.13M |
|---|
use search;
use search_case_insensitive;
use std::env;
use std::env::Args;
use std::error::Error;
use std::fs::File;
use std::io::prelude::*;
pub struct Config {
pub query: String,
pub filename: String,
pub case_sensitive: bool,
}
impl Config {
// pub fn new(args: &[String]) -> Result<Config, &'stati... |
use crate::core::colors::RgbaColor;
use crate::core::window::WindowDim;
use crate::render::ui::gui::{HorizontalAlign, VerticalAlign};
use crate::resources::Resources;
use glyph_brush::rusttype::*;
use glyph_brush::BrushError::TextureTooSmall;
use glyph_brush::{BrushAction, GlyphBrush, Layout, Section};
use luminance::b... |
use super::v2;
/// helper function to convert a default raw parameter when we already know it's not part of a body
pub(crate) fn non_body_parameter_to_v3_parameter(
form_data: bool,
v2: &v2::DefaultParameterRaw,
) -> Option<openapiv3::Schema> {
match v2.data_type {
Some(data_type) => {
... |
use crate::shader::Shader;
use cgmath::prelude::*;
use cgmath::{perspective, point3, vec3, Deg, Matrix4, Vector3};
use glfw::{Action, Window};
pub struct Camera {
pub position: Vector3<f32>,
direction: Vector3<f32>,
up: Vector3<f32>,
fov: f32,
near_plane: f32,
far_plane: f32,
pub camera_matr... |
// list
/// Represents a typed list constructed by [LCons] and [LNil].
pub trait List {}
// intermediate node
/// Represents an intermediate node.
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Cons<Head, Tail>
where
Tail: List,
{
pub head: Head,
pub tail: Tail,
}
impl<Head, Ta... |
#![allow(non_snake_case)]
use core::convert::TryInto;
use test_winrt_signatures::*;
use windows::core::*;
use Component::Signatures::*;
use Windows::Win32::Foundation::*;
#[implement(Component::Signatures::ITestHResult)]
struct RustTest();
impl RustTest {
fn SignatureHResult(&self, a: HRESULT, b: &mut HRESULT) -... |
use std::sync::{
Arc,
Mutex,
};
use std::time::Duration;
use bitset_core::BitSet;
use crossbeam_channel::{
Receiver,
Sender,
TryRecvError,
};
use instant::Instant;
use log::trace;
use rayon::prelude::*;
use smallvec::SmallVec;
use sourcerenderer_core::graphics::{
Backend,
Device,
Swapch... |
use chrono::Duration;
pub enum RequestResult {
Success { latency: Duration },
Failure,
}
|
#![allow(non_snake_case, non_camel_case_types, non_upper_case_globals, clashing_extern_declarations, clippy::all)]
#[link(name = "windows")]
extern "system" {}
#[repr(transparent)]
pub struct Direct3DBindings(pub u32);
impl Direct3DBindings {
pub const VertexBuffer: Self = Self(1u32);
pub const IndexBuffer: Sel... |
use std::{fmt, iter::{IntoIterator, Iterator}, marker::PhantomData, ops::{Index, IndexMut}, slice, borrow, cell::Cell};
#[macro_export]
macro_rules! matrix {
[$([$($e:expr),*]),*] => {
Matrix::from_vec(vec![$($($e),*),*], {
let mut rows = 0;
let mut row_len = None;
$(
... |
use crate::{
addon::Addon,
config::Flavor,
error::ClientError,
network::{post_json_async, request_async},
utility::{regex_html_tags_to_newline, regex_html_tags_to_space, truncate},
Result,
};
use isahc::prelude::*;
use serde::{Deserialize, Serialize};
const API_ENDPOINT: &str = "https://addons-... |
use super::*;
use node::{node_client::NodeClient, VmConfig};
use std::{net::SocketAddr, sync::Arc};
use tokio::sync::RwLock;
use tonic_health::proto::{health_client::HealthClient, HealthCheckRequest};
#[derive(Clone, Debug)]
pub struct Client {
address: SocketAddr,
client: Arc<RwLock<NodeClient<tonic::transp... |
use failure::_core::ops::{Deref, DerefMut};
use super::error::WalletError;
use mav::ma::{MEeeChainTx, MEeeTokenxTx};
use primitive_types::{U256, H160};
use eth::transaction::{Action, TypedTxId, TypedTransaction, EIP1559TransactionTx, AccessListTx};
use std::convert::TryInto;
#[derive(Debug, Default, Clone)]
pub struc... |
// 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 crate::apply::Initiator;
use crate::channel::{CurrentChannelManager, TargetChannelManager};
use crate::connect::ServiceConnector;
use crate::update_man... |
use crate::error::ProtocolError;
use std::convert::TryInto;
use std::fmt::{Display, Formatter};
use std::net::{IpAddr, SocketAddr};
use std::ops::Sub;
use std::time::SystemTime;
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct SntpTimestamp(u128);
impl SntpTimestamp {
const UNIX_EPOCH: u128 = 2_208_988_800... |
#[cfg(test)]
mod tests {
#[test]
fn string() {
// 核心字符串类型为&str
// 是一个针对字符串的特殊slice
let s = "hello world";
fn get_type<T>(_: &T) -> &str {
std::any::type_name::<T>()
}
println!("{} is a slice: {:?}", get_type(&&s[..]), &s[..]);
// 可以通过.to_string... |
use syntax::{codemap};
use syntax::ext::base;
use syntax::ext::build::AstBuilder;
use syntax::util::small_vector;
use std::ascii::AsciiExt;
use super::super::helpers;
impl super::super::Generator<()> for super::MigrationState {
fn generate<'a>(self, sp: codemap::Span, cx: &mut base::ExtCtxt, _: ()) -> Box<base::M... |
use std::collections::HashMap;
use std::hash::Hash;
use std::sync::{
Arc,
Mutex,
};
use ash::vk;
use sourcerenderer_core::atomic_refcell::AtomicRefCell;
use crate::raw::RawVkDevice;
pub struct VkQueryAllocator {
device: Arc<RawVkDevice>,
inner: AtomicRefCell<VkQueryAllocatorInner>,
}
pub struct VkQu... |
use std::fs;
fn main() {
let data = fs::read_to_string("input").expect("Error");
let count: u32 = data.split("\n\n").map(|group| count_for_group(group)).sum();
println!("oy, oy, oy, the result is {}", count);
}
fn count_for_group(answers: &str) -> u32 {
let mut cleaned_answer = answers.replace("\n", "... |
#[doc = "Reader of register DLLCR"]
pub type R = crate::R<u32, super::DLLCR>;
#[doc = "Writer for register DLLCR"]
pub type W = crate::W<u32, super::DLLCR>;
#[doc = "Register DLLCR `reset()`'s with value 0"]
impl crate::ResetValue for super::DLLCR {
type Type = u32;
#[inline(always)]
fn reset_value() -> Sel... |
use std::fmt;
use std::os::raw::c_void;
use std::os::unix::io::{AsRawFd, RawFd};
#[cfg(debug_assertions)]
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::{Arc, Mutex};
use std::time::Duration;
use std::{cmp, io};
use crate::interest::Interest;
use crate::sys::unix::waker::pipe::Waker;
use crate::token::... |
#[doc = "Reader of register MIS"]
pub type R = crate::R<u32, super::MIS>;
#[doc = "Reader of field `ERRMIS`"]
pub type ERRMIS_R = crate::R<bool, bool>;
#[doc = "Reader of field `RDMIS`"]
pub type RDMIS_R = crate::R<bool, bool>;
#[doc = "Reader of field `WRMIS`"]
pub type WRMIS_R = crate::R<bool, bool>;
#[doc = "Reader ... |
use std::{fs, collections::HashMap, ops::Index};
use lazy_static::lazy_static;
use regex::Regex;
fn make_stacks(crate_lines: &Vec<&str>, index_line: &str) -> HashMap<String, Vec<String>> {
let mut stacks: HashMap<String, Vec<String>> = HashMap::new();
let mut stack_names: Vec<&str> = index_line.split_whitespa... |
#[macro_use]
extern crate janus_plugin as janus;
#[macro_use]
extern crate lazy_static;
#[macro_use]
extern crate serde_derive;
#[macro_use]
extern crate serde_json;
mod messages;
use janus::{JanssonValue, Plugin, PluginCallbacks, PluginMetadata, PluginResult, PluginSession,
RawJanssonValue, RawPluginResu... |
use crate::scratch;
use cranelift::prelude::*;
use cranelift_module::Module;
use std::collections::HashMap;
struct Compiler<M: Module> {
module: M,
data_id_counter: usize,
var_id_counter: usize,
scratch_vars: HashMap<String, cranelift_module::DataId>,
procedures: HashMap<String, cranelift_module::F... |
use crate::utils;
use regex::Regex;
use std::collections::{HashMap, HashSet};
fn read_problem_data() -> Vec<String> {
let mut result = Vec::new();
if let Ok(lines) = utils::read_lines("data/day7.txt") {
for line in lines {
if let Ok(s) = line {
result.push(s);
}
... |
// pub mod autograd;
pub mod autograd;
pub mod arith;
pub mod trigo;
#[macro_use]
pub mod macros;
#[cfg(test)]
pub mod tests;
pub use self::autograd::*;
pub use self::arith::*;
pub use self::macros::*;
|
pub mod arith;
pub use arith::*;
|
fn main(){
proconio::input!{n:usize,m:usize,a:[isize;n]};
// println!("{:?}", n); // 4 n種類の賞品
// println!("{:?}", m); // 1 m個を選ぶ
// println!("{:?}", a); // [5, 4, 2, 1] 各賞品の投票数
let total = a.iter().sum();
// println!("{}", total); // 12 合計投票数
// let count = a.iter().filter(|x|4 * (m as isize) * **x >= t... |
use crate::{
commands::{Command, RunnableContext},
context::CommandRegistry,
error::ShellError,
evaluate::{CallInfo, Value},
parser::syntax_shape::SyntaxShape,
shell::Shell,
signature::Signature,
};
use alloc::{string::String, sync::Arc, vec::Vec};
use core::sync::atomic::AtomicBoo... |
#[doc = "Reader of register PTBOCTL"]
pub type R = crate::R<u32, super::PTBOCTL>;
#[doc = "Writer for register PTBOCTL"]
pub type W = crate::W<u32, super::PTBOCTL>;
#[doc = "Register PTBOCTL `reset()`'s with value 0"]
impl crate::ResetValue for super::PTBOCTL {
type Type = u32;
#[inline(always)]
fn reset_va... |
use serde_json::{json, Value};
use rbatis_core::convert::StmtConvert;
use crate::ast::ast::RbatisAST;
use crate::ast::node::bind_node::BindNode;
use crate::ast::node::choose_node::ChooseNode;
use crate::ast::node::delete_node::DeleteNode;
use crate::ast::node::foreach_node::ForEachNode;
use crate::ast::node::if_node:... |
use ::ir::{Type, TypeData, TypeContainer};
use ::ir::variant::{Variant, SimpleScalarVariant, ContainerVariant, ContainerField};
use ::FieldReference;
use super::FromProtocolJson;
use ::json::JsonValue;
use super::errors::*;
use super::type_from_json;
use super::count::{CountMode, read_count};
use std::rc::Rc;
use std:... |
use super::{module::ExecutionError, translate, ExecutableModule};
use wabt;
fn translate_wat(wat: &str) -> ExecutableModule {
let wasm = wabt::wat2wasm(wat).unwrap();
let compiled = translate(&wasm).unwrap();
compiled
}
/// Execute the first function in the module.
fn execute_wat(wat: &str, a: u32, b: u32... |
use anyhow::{anyhow, Context, Result};
use clap::Parser;
use log::{debug, error, info};
use regex::Regex;
use reqwest::Url;
use std::net::Ipv4Addr;
use std::net::UdpSocket;
use std::str::from_utf8;
use std::time::Duration;
fn get_location(response: &[u8]) -> Option<&str> {
let location_header = "LOCATION: ";
... |
use std::fmt::Display;
use data_types::{CompactionLevel, ParquetFile};
use crate::RoundInfo;
use super::RoundSplit;
#[derive(Debug, Default)]
pub struct ManyFilesRoundSplit;
impl ManyFilesRoundSplit {
pub fn new() -> Self {
Self
}
}
impl Display for ManyFilesRoundSplit {
fn fmt(&self, f: &mut ... |
fn main() {
println!("🔓 Challenge 23");
println!("Code in 'challenges/src/chal23.rs'");
}
|
extern crate olin;
use log::{error, info};
use olin::env;
pub extern "C" fn test() -> Result<(), i32> {
info!("testing for issue 22: https://github.com/Xe/olin/issues/22");
info!("look for variable that does not exist");
match env::get("DOES_NOT_EXIST") {
Err(env::Error::NotFound) => info!("this ... |
#![feature(optin_builtin_traits)]
#![feature(core_intrinsics)]
#![feature(integer_atomics)]
#![feature(naked_functions)]
#![feature(const_fn)]
#![feature(asm)]
#![no_std]
use core::ptr;
use core::ops::{BitOr, BitAnd, Not};
use core::sync::atomic::{AtomicU32, Ordering};
/// Instrumentation Trace Macro Cell
pub mod itm... |
/*! Python `super` class.
See also [CPython source code.](https://github.com/python/cpython/blob/50b48572d9a90c5bb36e2bef6179548ea927a35a/Objects/typeobject.c#L7663)
*/
use super::{PyStr, PyType, PyTypeRef};
use crate::{
class::PyClassImpl,
common::lock::PyRwLock,
function::{FuncArgs, IntoFuncArgs, Option... |
// Konstanta pada rust akan hidup pada seluruh program
// dan dapat digunakan berkali-kali dilingkup manapun
//
const EXAMPLE: Option<i32> = Some(10);
fn main() {
EXAMPLE.take();
println!("{:?}", EXAMPLE);
println!("{:?}", EXAMPLE);
println!("{:?}", EXAMPLE);
}
|
//! Client for InfluxDB IOx Flight API
use std::{pin::Pin, task::Poll};
use ::generated_types::influxdata::iox::querier::v1::{read_info::QueryType, ReadInfo};
use futures_util::{Stream, StreamExt};
use prost::Message;
use thiserror::Error;
use tonic::metadata::{MetadataKey, MetadataMap, MetadataValue};
use arrow::{
... |
#![allow(unused_variables, dead_code)]
enum IpAddrKind {
V4,
V6,
}
struct IpAddr0 {
kind: IpAddrKind,
address: String,
}
enum IpAddr1 {
V4(String),
V6(String),
}
enum IpAddr2 {
V4(u8, u8, u8, u8),
V6(String),
}
struct Ipv4Addr { }
struct Ipv6Addr { }
enum IpAddr {
V4(Ipv4Addr),
... |
#[cfg(feature = "dist_tx")]
use crate::protocol::parts::XatOptions;
use crate::{
conn::AmConnCore,
protocol::{
parts::{
AuthFields, ClientContext, ClientInfo, CommandInfo, ConnectOptions, DbConnectInfo,
ExecutionResult, LobFlags, OutputParameters, ParameterDescriptors, ParameterR... |
use std::{borrow::Cow, marker::PhantomData};
use crate::{
connection::{
edge::Edge, ConnectionNameType, DefaultConnectionName, DefaultEdgeName, EdgeNameType,
PageInfo,
},
types::connection::{CursorType, EmptyFields},
Object, ObjectType, OutputType, TypeName,
};
/// Connection type
///
... |
use super::Side;
use super::Vive;
use openvr_sys::EGraphicsAPIConvention;
const FAR: f32 = 1024.0;
const NEAR: f32 = 0.1;
const GRAPHICS_CONVENTION: EGraphicsAPIConvention = EGraphicsAPIConvention::EGraphicsAPIConvention_API_OpenGL;
const EMPTY_MATRIX: [[f32; 4]; 4] = [
[0.0, 0.0, 0.0, 0.0],
[0.0, 0.0, 0.0, 0.... |
fn main() {
windows::core::build_legacy! {
Windows::Win32::Graphics::Direct3D12::ID3D12FunctionReflection,
};
}
|
#[test]
fn by_ref_test() {
use std::collections::HashMap;
let text = "Hello\r\nMister\r\nDeeJay";
let mut lines = text.lines();
//by_ref avoids the loop taking ownership of lines
for line in lines.by_ref() {
println!("{}", line);
}
for _ in lines {
assert!(true);
}
}
|
use serde::Deserialize;
use serde_json::Value;
#[derive(Deserialize, Debug)]
pub struct FlightStatusRaw {
pub live: Option<bool>,
pub text: Option<String>,
pub icon: Option<String>,
pub estimated: Option<Value>,
pub ambiguous: Option<bool>,
pub generic: Option<Value>,
} |
mod gamma_control;
mod desktop_shell;
/// Initializes the appropriate handlers for each wayland protocol
/// that Way Cooler supports.
pub fn init_wayland_protocols() {
info!("Initializing wayland protocols");
gamma_control::init();
desktop_shell::init();
}
|
use crate::integer::Integer;
use core::ops::SubAssign;
// SubAssign The subtraction assignment operator -=.
// ['Integer', 'Integer', 'Integer::subtract_assign', 'no', [], ['ref']]
impl SubAssign<Integer> for Integer {
fn sub_assign(&mut self, rhs: Integer) {
Integer::subtract_assign(self, &rhs)
... |
use std::io;
fn day9b(numbers: &Vec<i64>, prefix_sums: &Vec<i64>, bad_number: i64) {
// brute force, going through all O(n^2) ranges.
for (upper_idx, upper_sum) in prefix_sums.iter().enumerate() {
for (lower_idx, lower_sum) in prefix_sums[..upper_idx].iter().enumerate() {
if upper_sum - low... |
use ggez::{Context, GameResult};
use ggez::graphics::{self, Rect, Mesh, Image, DrawMode, DrawParam, FilterMode};
use crate::chip8::{Chip8, Gpu};
use crate::ui::{Point2, Vector2};
/// Displays a Chip8 device in a 640x320 area.
pub struct Chip8Display {
/// The horizontal position of this display relative to the m... |
use nix::sys::termios::{
self, ControlFlags, InputFlags, LocalFlags, OutputFlags, SetArg, Termios,
};
use regex::Regex;
use std::cmp;
use std::env;
use std::fs::File;
use std::io::{self, BufRead, BufReader, Read, Write};
use std::mem;
use std::os::unix::io::AsRawFd;
use std::sync::mpsc::RecvTimeoutError;
use std::s... |
//! This crate contains a practical implementation of the x86 xsave semantics.
//!
//! We do not intend to support all possible variations of the instructures,
//! nor do we intend to calculate the size of the xsave area dynamically.
//! Instead, our practical strategy will overallocate the size of the xsave
//! area s... |
pub trait BitSet {
/// Sets a bit
fn set_bit(&mut self, bit: usize);
/// Unsets a bit
fn unset_bit(&mut self, bit: usize);
/// Returns the value of a bit
fn bit(&self, bit: usize) -> bool;
/// Returns the total number of bits of a bitset
fn bit_count(&self) -> usize;
}
impl BitSet fo... |
#![allow(non_snake_case, non_camel_case_types, non_upper_case_globals, clashing_extern_declarations, clippy::all)]
#[link(name = "windows")]
extern "system" {
pub fn ActivatePackageVirtualizationContext(context: *const PACKAGE_VIRTUALIZATION_CONTEXT_HANDLE__, cookie: *mut usize) -> ::windows_sys::core::HRESULT;
... |
/*
Writes as three-line messasge to file, then reads it back a line at a time with
the `Lines` iterator created by `BufRead::lines.BufRead` is a trait, and the
most common way to get one is from a `BufReader`, which is constructed from
some types that implements `Read`, here a `File`. The `File` is opened for writin... |
use std::io::{Read, Result as IOResult};
use crate::lump_data::{LumpData, LumpType, brush::BrushContents};
use crate::PrimitiveRead;
#[derive(Copy, Clone, Debug, Default)]
#[repr(C)]
pub struct ColorRGBExp32 {
pub r: u8,
pub g: u8,
pub b: u8,
pub exponent: i8,
}
#[derive(Copy, Clone, Debug, Default)]
pub stru... |
use anyhow::Result;
fn main() -> Result<()> {
// Find element by id.
let doc = roxmltree::Document::parse("<rect id='rect1'/>").unwrap();
let elem = doc
.descendants()
.find(|n| n.attribute("id") == Some("rect1"))
.unwrap();
assert!(elem.has_tag_name("rect"));
Ok(())
}
|
use survey_manager_core::Error as SMError;
use actix_web::{ResponseError, HttpResponse, http};
use actix_web::dev::HttpResponseBuilder;
use actix_web::error::BlockingError;
#[derive(Debug)]
pub enum ApiError {
CoreError(CoreError),
TokenError(TokenError),
ThreadFailure,
}
impl std::error::Error for ApiErr... |
pub struct Xref {
last_release: String,
}
// pub struct Dates {
// first_seen: String,
// last_seen: String,
// }
// impl Xref {
// pub fn date(&self) ->
// }
// impl FromIterator<Xref> for Date {
// fn from_iter<I: IntoIterator<Item=Xref>>(iter: I) -> Self {
// let mut value = Date::def... |
use crate::swap;
use std::cmp::PartialOrd;
pub fn sort<T>(list: &mut [T])
where
T: PartialOrd + Copy,
{
let len = list.len();
if len <= 1 {
return;
}
let value = list[0];
let mut l_index = 0;
let mut r_index = len;
let mut is_right = true;
while l_index < r_index {
... |
use serenity::client::bridge::gateway::{ShardManager};
use serenity::model::channel::Message;
use serenity::model::event::ResumedEvent;
use serenity::model::id::ChannelId;
use serenity::model::gateway::Ready;
use serenity::prelude::Mutex;
use serenity::prelude::*;
use typemap::Key;
use std::collections::HashMap;
use ... |
use crate::actions::MatchAction;
use crate::contact::Contact;
use anyhow::{bail, Result};
pub struct PrintExporter {}
impl PrintExporter {
pub fn new() -> Self {
PrintExporter {}
}
}
impl MatchAction for PrintExporter {
fn process(&self, contacts: Vec<&mut Contact>) -> Result<bool> {
matc... |
fn main() {
let x = 330121;
let vx = [3, 3, 0, 1, 2, 1];
let mut v = vec![3, 7];
let (mut i, mut j) = (0, 1);
let mut sol1 = false;
let mut sol2 = false;
while !sol1 || !sol2 {
let s = v[i] + v[j];
if s < 10 {
v.push(s);
} else {
v.push(s / ... |
pub mod codec;
pub mod error;
mod flags;
pub mod frames;
pub mod upgrade;
pub use self::flags::{is_compressed, make_flags, Flags};
pub const VERSION: u8 = 1;
|
use crate::core::noise::perlin::Perlin;
use crate::core::random::RandomGenerator;
use crate::core::timer::Timer;
use crate::core::transform::Transform;
use crate::gameplay::collision::{BoundingBox, CollisionLayer};
use crate::gameplay::physics::DynamicBody;
use crate::gameplay::pickup::spawn_pickup;
use crate::render::... |
#![allow(dead_code)]
#![allow(unused_variables)]
#![feature(unboxed_closures)]
use std::mem;
use std::panic;
enum Number {
Zero,
One,
Two,
}
enum Color {
Red = 0xff0000,
Green = 0x00ff00,
Blue = 0x0000ff,
}
use List::*;
enum List {
Cons(u32, Box<List>),
Nil,
}
impl List {
fn ne... |
//! An "ASCII Canvas" allows us to draw lines and write text into a
//! fixed-sized canvas and then convert that canvas into ASCII
//! characters. ANSI styling is supported.
use crate::style::Style;
use std::cmp;
use std::iter::ExactSizeIterator;
use std::ops::Range;
use term::Terminal;
mod row;
#[cfg(test)]
mod test... |
use std::ops::Add;
use std::ops::Sub;
use std::f64::consts::PI;
/// A 2D point
#[derive(Copy, Clone, Debug)]
pub struct Point {
pub x: f64,
pub y: f64,
}
impl Add for Point {
type Output = Self;
fn add(self, other: Self) -> Self {
Self {
x: self.x + other.x,
y: sel... |
use join::Join;
use procon_reader::ProconReader;
fn main() {
let stdin = std::io::stdin();
let mut rd = ProconReader::new(stdin.lock());
let n: usize = rd.get();
let p: Vec<usize> = rd.get_vec(n);
let p: Vec<usize> = p.into_iter().map(|x| x - 1).collect();
let mut q = vec![0; n];
for i in... |
use std::convert::TryInto;
use std::num::NonZeroU8;
use std::str::FromStr;
use aoc_2020::*;
use structopt::StructOpt;
#[derive(Debug, Copy, Clone, Eq, PartialEq, StructOpt)]
pub struct Day {
day: NonZeroU8,
}
impl FromStr for Day {
type Err = &'static str;
fn from_str(s: &str) -> Result<Self, Self::Err>... |
// Copyright (c) 2021 Quark Container Authors / 2018 The gVisor Authors.
//
// 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 ... |
use std::fmt;
use syntax::literals::*;
use syntax::op::*;
#[derive(PartialEq)]
pub struct ExprWrapper {
expr: Box<Expr>,
start_line: u64,
start_column: u64,
end_line: u64,
end_column: u64
}
impl ExprWrapper {
// Create an associated expression with start and end positions
pub fn new(expr:... |
use android_base::{InputEvent, AppContainer, AppImpl};
use std::sync::{Arc, Mutex};
use piston::input::{Input, Motion, Touch};
use cgmath::{Vector2, InnerSpace, Matrix4, Vector3, Rad, MetricSpace};
use std::f32::consts::{FRAC_PI_4, PI, FRAC_PI_2};
#[derive(Debug)]
pub struct Camera {
height: f64,
width_height_... |
use std::fs::File;
use std::path::PathBuf;
use std::env;
use std::fs;
use idna::domain_to_ascii;
use std::ascii::AsciiExt;
extern crate regex;
use regex::Regex;
extern crate fern;
use hyper::Client;
use std::io::prelude::*;
use hyper;
static PUBLIC_SUFFIX_LIST_URLS: &'static [&'static str] =
&["https://publicsuffi... |
// this uses the path created with `pub use`
use crate::argh::cheers;
pub fn cheers_nested() {
cheers()
}
|
// Copyright (c) 2021 Quark Container Authors / 2018 The gVisor Authors.
//
// 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 ... |
use bb::{BB, END_ROWS};
use castle::Castle;
use mv_list::MoveList;
use square::Square;
/// MoveCounter implements MoveList and keeps a count of different types of moves added to it. It can count at most 256 moves since it uses `u8` internally
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct MoveCounter {
pub mo... |
// Copyright 2013-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-MI... |
use super::alloc::alloc::Layout;
use super::uart;
use super::util;
use lazy_static::lazy_static;
use alloc::prelude::*;
use spin::Mutex;
pub struct Tcb {
_stack_addr: *mut u8,
_stack_size: usize,
sp: *mut u32,
r: [u32; 13],
lr: *mut u8,
pc: *mut u8,
cpsr: u32,
}
unsafe impl Send for Tcb... |
fn ring(val: u32) -> u32 {
let mut sum = 1;
let mut ring: u32 = 0;
while sum < val {
ring = ring + 1;
sum = sum + ring * 8;
}
ring
}
fn manhatten(value: u32) -> u32 {
1
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn works_for_examples() {
assert_eq!(0, ... |
use challenges::chal18::Key;
use cryptanalysis::vigenere;
use encoding::hex;
fn main() {
println!("🔓 Challenge 20");
let key = Key::new();
let ct_arr = key.successive_encryption();
break_statistically(&ct_arr);
}
fn break_statistically(ct_arr: &[Vec<u8>]) {
let mut shortest = ct_arr[0].len();
... |
#[doc = "Reader of register C15ISR"]
pub type R = crate::R<u32, super::C15ISR>;
#[doc = "Reader of field `TEIF15`"]
pub type TEIF15_R = crate::R<bool, bool>;
#[doc = "Reader of field `CTCIF15`"]
pub type CTCIF15_R = crate::R<bool, bool>;
#[doc = "Reader of field `BRTIF15`"]
pub type BRTIF15_R = crate::R<bool, bool>;
#[... |
use conformance::*;
fn main() {
let mut test_count = 0;
loop {
match do_test_io() {
Ok(false) => {
test_count += 1;
},
Ok(true) => {
eprintln!("conformance_rust: {} tests complete, exit", test_count);
break;
... |
use tari_crypto::{
keys::{PublicKey, SecretKey},
ristretto::{RistrettoPublicKey, RistrettoSecretKey, RistrettoSchnorr},
common::Blake256,
};
// Imports the to_hex trait method
use tari_utilities::hex::Hex;
// imports the as_bytes trait method
use tari_utilities::byte_array::ByteArray;
use digest::Digest;
/... |
pub use super::device::*;
pub use super::entry::*;
pub use super::instance::*;
pub use super::maintenance3::*;
pub use super::statics::*;
|
pub mod btcapi;
pub mod api;
pub use api::start;
pub use api::btc_load_now_blocknumber;
pub use api::btc_load_balance;
pub use api::btc_tx_sign; |
#[doc = r" Register block"]
#[repr(C)]
pub struct RegisterBlock {
_reserved0: [u8; 1024usize],
#[doc = "0x400 - Ready flag"]
pub ready: READY,
_reserved1: [u8; 4usize],
#[doc = "0x408 - Ready flag"]
pub readynext: READYNEXT,
_reserved2: [u8; 248usize],
#[doc = "0x504 - Configuration regi... |
use crate::{grid::{Grid, Alignment, DividerStrategy}, out::{Action, Handler, SafeHandler}, trim::{TrimmedText, FormatError, TrimStrategy}};
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
enum InternalFormatError {
NoSpace(TrimmedText),
}
//... |
// Short Encoding of Words
// https://leetcode.com/explore/challenge/card/march-leetcoding-challenge-2021/588/week-1-march-1st-march-7th/3662/
pub struct Solution;
impl Solution {
pub fn minimum_length_encoding(words: Vec<String>) -> i32 {
let mut rev_words: Vec<String> = words
.iter()
... |
use rand::Rng;
pub trait Bitstream {
fn gen_bits(&mut self, num_bits: u32) -> u64;
}
pub struct RngBitstream<T> {
rng: T,
bit_buffer: u64,
unused_bits: u32,
}
pub struct CountingRngBitstream<T> {
bitstream: RngBitstream<T>,
count: u64,
}
impl<T> RngBitstream<T> {
pub fn new(rng: T) -> Se... |
pub mod lerp {
use std::ops::{Add, Mul};
use num_traits::{One, Float, Zero};
pub trait Lerp<F> {
/// Interpolate and extrapolate between `self` and `other` using `t` as the parameter.
///
/// At `t == 0.0`, the result is equal to `self`.
/// At `t == 1.0`, the result is equa... |
use std::io;
use std::cmp::Ordering;
fn main(){
println!("Guess the number!");
loop{
println!("Please input your guess.");
// mut 表示变量 guess 可变
// rust变量默认是不可变
let mut guess = String::new();
let secret_num= 5;
io::stdin().read_line(&mut guess)
... |
trait Tweet {
// 関数
fn tweet(&self);
fn tweet_twice(&self) {
self.tweet();
self.tweet();
}
fn shout(&self) {
println!("Uooooooooohhh!!!!!!!");
}
}
// 構造体を宣言する。
struct Dove;
struct Duck;
// トレイトを適用する。
impl Tweet for Dove {
fn tweet(&self) {
println!("Coo!")... |
// auto generated, do not modify.
// created: Mon Feb 22 23:57:02 2016
// src-file: /QtGui/qsyntaxhighlighter.h
// dst-file: /src/gui/qsyntaxhighlighter.rs
//
// header block begin =>
#![feature(libc)]
#![feature(core)]
#![feature(collections)]
extern crate libc;
use self::libc::*;
// <= header block end
// main bl... |
mod outbound;
pub use outbound::generate_outbound_connection_subgraph;
|
use gl::types::*;
use super::{ShaderExt, Shader};
use anyhow::Result;
pub type FragmentShader = Shader<Fragment>;
pub struct Fragment();
impl ShaderExt for Fragment {
fn new() -> Fragment {
Fragment{}
}
fn ty() -> GLenum {
gl::FRAGMENT_SHADER
}
fn name() -> &'static str {
... |
use std::sync::Arc;
use std::cell::RefCell;
use std::cell::Cell;
// won't compile. x is immutable
//#[test]
//fn test_immutability() {
// let x = 5;
// x = 6;
//}
//
#[test]
fn test_mutability() {
let mut x = 5;
x = 6;
}
#[test]
fn test_mutable_ref() {
let mut x = 5;
let y = &mut x;
}
#[test]... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.