text stringlengths 8 4.13M |
|---|
use super::float_eq;
use intersections::Intersection;
use materials::Material;
use matrices::Matrix4;
use rays::Ray;
use tuples::Tuple;
#[derive(Copy, Clone, PartialEq, Debug)]
pub enum ShapeKind {
Sphere,
Plane,
}
#[derive(Copy, Clone, PartialEq, Debug)]
pub struct Shape {
pub transform: Matrix4,
pub... |
// Copyright 2019, 2020 Wingchain
//
// 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... |
// Entry point for subte
extern crate pancurses as curses;
extern crate fourthrail;
use fourthrail::fourthrail::*;
/* */
fn main () {
// Initialise curses first.
let window = curses::initscr();
let (height, width) = window.get_max_yx();
// Then check terminal size.
match (height, width) {
... |
#[doc = "Reader of register DDRCTRL_DBG1"]
pub type R = crate::R<u32, super::DDRCTRL_DBG1>;
#[doc = "Writer for register DDRCTRL_DBG1"]
pub type W = crate::W<u32, super::DDRCTRL_DBG1>;
#[doc = "Register DDRCTRL_DBG1 `reset()`'s with value 0"]
impl crate::ResetValue for super::DDRCTRL_DBG1 {
type Type = u32;
#[i... |
use crate::get_set_swap;
use crate::{command::Command, scene::commands::SceneContext};
use rg3d::core::algebra::Vector3;
use rg3d::sound::buffer::SoundBufferResource;
use rg3d::sound::context::SoundContext;
use rg3d::{
core::pool::{Handle, Ticket},
sound::source::SoundSource,
};
#[derive(Debug)]
pub struct Add... |
// Copyright 2016 PingCAP, Inc.
//
// 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 i... |
// --- Day 7: Handy Haversacks ---
// You land at the regional airport in time for your next flight. In
// fact, it looks like you'll even have time to grab some food: all
// flights are currently delayed due to issues in luggage processing.
// Due to recent aviation regulations, many rules (your puzzle input)
// are... |
extern crate toml;
extern crate rustc_serialize;
mod config;
fn main()
{
let b = config::Config::parse("/etc/fstab");
println!("{:?}",b);
}
|
/*
https://projecteuler.net
The nth term of the sequence of triangle numbers is given by,
tn = ½n(n+1); so the first ten triangle numbers are:
1, 3, 6, 10, 15, 21, 28, 36, 45, 55, ...
By converting each letter in a word to a number corresponding to its
alphabetical position and adding these values we form a wo... |
extern crate racer;
extern crate racer_testutils;
use racer::Coordinate;
use racer_testutils::*;
#[test]
fn complets_static_methods_for_alias() {
let src = r#"
mod mymod {
pub struct St {
mem1: String,
mem2: usize,
}
impl St {
... |
use iced::widget::{button, column, radio, row, text_input};
use iced::widget::{Column, Row};
use iced::{window, Alignment, Element, Sandbox, Settings};
use std::fs::{self, File};
use std::io::Write;
use cubes::{project_dir_cubes, Puzzle};
pub fn main() -> iced::Result {
PolycubePieces::run(Settings {
win... |
// Vicfred
// https://codeforces.com/problemset/problem/1285/C
// math
use std::io;
fn gcd(a: i64, b: i64) -> i64 {
if b == 0 {
a
} else {
gcd(b,a%b)
}
}
fn lcm(a: i64, b: i64) -> i64 {
(a*b)/gcd(a,b)
}
fn main() {
let mut n = String::new();
io::stdin()
.read_line(&mu... |
use anyhow::{bail, Result};
use std::io::Write;
use std::path::Path;
use std::process::Command;
use tempfile::NamedTempFile;
fn run_wasmtime(args: &[&str]) -> Result<String> {
let mut me = std::env::current_exe()?;
me.pop(); // chop off the file name
me.pop(); // chop off `deps`
me.push("wasmtime");
... |
use std::io;
use std::io::BufRead;
use std::io::BufReader;
fn main() {
let reader = BufReader::new(io::stdin());
let map: Vec<Vec<u8>> = reader
.lines()
.map(|line| line.unwrap().as_bytes().to_vec())
.collect();
let mut y = 0i32;
let mut x = 0i32;
let mut dir: (i32, i32) = ... |
use std::fmt::Debug;
use std::sync::Arc;
use crate::prelude::*;
use crate::math::*;
use crate::math::Transform;
use crate::interaction::SurfaceInteraction;
mod cylinder;
pub use self::cylinder::Cylinder;
mod sphere;
pub use self::sphere::Sphere;
#[derive(Clone, Debug)]
pub struct ShapeData {
pub object_to_world:... |
use std::cmp;
use parser::{FileHash, Register};
use crate::print::{DiffList, DiffState, Print, PrintState, ValuePrinter};
use crate::Result;
pub(crate) fn print_list(state: &mut PrintState, mut registers: Vec<Register>) -> Result<()> {
registers.sort_unstable();
registers.dedup();
state.field_expanded("r... |
use crate::hittable::*;
use crate::ray::*;
use std::rc::Rc;
pub struct HittableList {
pub objects: Vec<Rc<dyn Hittable>>,
}
impl HittableList {
pub fn new() -> Self {
Self {
objects: Vec::new(),
}
}
pub fn from(objects: Vec<Rc<dyn Hittable>>) -> Self {
Self { object... |
#![doc = "generated by AutoRust 0.1.0"]
#[cfg(feature = "package-preview-2020-08")]
mod package_preview_2020_08;
#[cfg(feature = "package-preview-2020-08")]
pub use package_preview_2020_08::{models, operations, API_VERSION};
#[cfg(feature = "package-resources-2020-06")]
mod package_resources_2020_06;
#[cfg(feature = "p... |
use std::sync::Arc;
use super::ecdsa::*;
use super::eddsa::*;
use super::error::*;
use super::handles::*;
use super::rsa::*;
use super::signature_keypair::*;
use super::signature_publickey::*;
use super::WASI_CRYPTO_CTX;
#[allow(non_camel_case_types)]
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
#[repr(u16)]
pub enum... |
use uuid::Uuid;
use std::process::Command;
/**
* Get printers on unix systems using lpstat
*/
pub fn get_printers() -> Vec<super::Printer> {
let out = Command::new("lpstat").arg("-e").output().unwrap();
if out.status.success() {
unsafe {
let out_str = String::from_utf8_unchecked(out.... |
extern crate proc_macro;
use proc_macro::TokenStream;
mod derives;
#[proc_macro_derive(Entity, attributes(event_sauce))]
pub fn derive_entity(input: TokenStream) -> TokenStream {
let input = syn::parse_macro_input!(input as syn::DeriveInput);
match derives::entity::expand_derive_entity(&input) {
Ok(... |
pub fn maximum_gap(nums: Vec<i32>) -> i32 {
use std::cmp::*;
let n = nums.len();
if n < 2 {
return 0
} else if n == 2 {
return (nums[1] - nums[0]).abs()
}
let min_v = nums.iter().fold(nums[0], |acc, &x| min(acc, x));
let max_v = nums.iter().fold(nums[0], |acc, &x| max(acc, x)... |
use std::sync::Arc;
use std::sync::atomic::AtomicUsize;
use std::marker::PhantomData;
use role;
use counter::{Counter, CounterRange, AtomicCounter};
use sequence::{Sequence, Limit};
use buffer::BufRange;
use super::half::{Half, HeadHalf};
#[derive(Debug)]
pub(crate) struct Head<S: Sequence, R: Sequence> {
sende... |
// Given an array of integers, find if the array contains any duplicates.
//
// Your function should return true if any value appears at least twice in the array, and it should return false if every element is distinct.
//
// Example 1:
//
// Input: [1,2,3,1]
// Output: true
// Example 2:
//
// Inp... |
use iron::IronError;
use iron::status::Status;
use std::error::Error;
use std::fmt::{self, Display, Formatter};
use std::io;
use std::str::Utf8Error;
use std::sync::{RwLockReadGuard, RwLockWriteGuard, PoisonError};
use super::common::Backend;
pub type MogResult<T> = Result<T, MogError>;
#[derive(Debug)]
pub enum MogE... |
//! Types which are needed to use the audio system independent from the root `riddle` crate.
mod audio_system;
pub use audio_system::*;
|
mod list_file_systems_builder;
pub use list_file_systems_builder::ListFileSystemsBuilder;
mod create_file_system_builder;
pub use create_file_system_builder::CreateFileSystemBuilder;
mod delete_file_system_builder;
pub use delete_file_system_builder::DeleteFileSystemBuilder;
mod get_file_system_properties_builder;
pub ... |
// A struct, which declares a lifetime.
struct Foo<'a> {
// And a reference, which uses the lifetime.
x: &'a i32,
}
fn main() {
let y = 5;
let mut f = Foo { x: &y };
{
let z = 6;
// This does not work, because f outlives z.
f.x = &z;
}
println!("{}", f.x);
}
|
// Para fijar la semilla de numeros aleatorios
use rand::Rng;
use rand::rngs::StdRng;
// Para hacer shuffle de un vector
use rand::seq::SliceRandom;
// Para tener mutabilidad interior
use std::cell::RefCell;
use crate::problem_datatypes::{DataPoints, Constraints, Point, ConstraintType, NeighbourGenerator};
use crate... |
use std::ops::Deref;
use rocket::http::Status;
use rocket::request::{self, FromRequest};
use rocket::{Outcome, Request};
pub use super::models::Staff;
pub use super::models::new::Staff as NewStaff;
use super::{DatabaseConnection, SelectError};
use session::Session;
// Enable upsert on the email field.
generate_crud... |
#[doc = "Reader of register ANA_CTL1"]
pub type R = crate::R<u32, super::ANA_CTL1>;
#[doc = "Writer for register ANA_CTL1"]
pub type W = crate::W<u32, super::ANA_CTL1>;
#[doc = "Register ANA_CTL1 `reset()`'s with value 0x0606_0000"]
impl crate::ResetValue for super::ANA_CTL1 {
type Type = u32;
#[inline(always)]... |
#![allow(dead_code)]
use std::{
collections::VecDeque,
io,
pin::Pin,
task::{Context, Poll},
};
use tokio::io::{AsyncRead, AsyncReadExt, AsyncWrite, ReadBuf};
#[derive(Debug)]
pub struct PeekableStream<S> {
inner: S,
buf: VecDeque<u8>,
}
impl<S> AsyncRead for PeekableStream<S>
where
S: As... |
use crate::entities::duration::Duration;
#[derive(Serialize, Deserialize, PartialEq, Debug, Clone, GraphQLEnum)]
pub enum AggregationFunction {
Oldest,
Newest,
Max,
Min,
Sum,
Avg,
}
impl AggregationFunction {
pub fn reduce(&self, prev: f64, current: f64) -> f64 {
match self {
AggregationFuncti... |
mod label;
pub use label::Label; |
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
use futures::{Async, Future, Poll};
use futures::task::{self, Task};
use common::Never;
use self::lock::Lock;
#[derive(Clone)]
pub struct Cancel {
inner: Arc<Inner>,
}
pub struct Canceled {
inner: Arc<Inner>,
}
struct Inner {
is_cancel... |
use super::engine::{Action, Round};
use super::state::GameState;
use crate::cards::BasicCard;
pub fn format_hand(hand: &[BasicCard], gs: &GameState) -> String {
let mut cards: Vec<_> = hand.iter().collect();
cards.sort_by(|a, b| gs.display_order(a, b));
let sc: Vec<_> = cards.iter().map(|x| format!("{}", ... |
use std::thread;
use std::time::Duration;
fn workout_plan(intensity:u32, random_number:u32){
let expensive_call = simulated_expensive_calculations(intensity); //refactor code by adding this line hence it only call once.
if intensity < 25 {
println!("Today, do {} pushups!",expensive_call); //not c... |
fn main() {
//2 fibonacci
// fn fib(z: i32) -> i32 {
// if z==0 { return 0 }
// else if z==1 { return 1 }
// else { return fib(z-1) + fib(z-2) }
// }
// let mut counter = 0;
// let mut this_fib = fib(0);
// let mut even_sum = 0;
// let mut done = false; // mut done: bool
// while !done {
// println!(... |
impl Solution {
pub fn reverse_parentheses(s: String) -> String {
let n = s.len();
let s = s.as_bytes();
let mut res = String::new();
let mut stk = Vec::new();
for i in 0..n{
if s[i] == b'('{
stk.push(res.clone());
res = "".to_stri... |
#[doc = "Register `AXIMC_PERIPH_ID_2` reader"]
pub type R = crate::R<AXIMC_PERIPH_ID_2_SPEC>;
#[doc = "Field `PERIPH_ID_2` reader - PERIPH_ID_2"]
pub type PERIPH_ID_2_R = crate::FieldReader;
impl R {
#[doc = "Bits 0:7 - PERIPH_ID_2"]
#[inline(always)]
pub fn periph_id_2(&self) -> PERIPH_ID_2_R {
PER... |
use std::any::{Any as StdAny, TypeId};
#[cfg(feature = "nightly")]
use std::convert::TryFrom;
#[cfg(feature = "nightly")]
use std::intrinsics;
#[cfg(feature = "nightly")]
pub(crate) fn type_name<T: StdAny + ?Sized>() -> &'static str {
unsafe { intrinsics::type_name::<T>() }
}
#[cfg(not(feature = "nightly"))]
pub(... |
fn main() {
// let mut s = String::from("hello world");
// let word = first_word(&s);
// println!("xxx:{}",word);
// clear尝试获取一个可变引用,但是当拥有某个值的不可变引用时,就不能再获取它的可变引用了,所以这里Error
// s.clear();
let my_string = String::from("hello world");
let word = first_word(&my_string[..]);
println!("word... |
use clippy_utils::diagnostics::span_lint_and_sugg;
use clippy_utils::is_trait_method;
use clippy_utils::source::snippet;
use rustc_errors::Applicability;
use rustc_hir as hir;
use rustc_lint::LateContext;
use rustc_span::sym;
use super::ITER_SKIP_NEXT;
pub(super) fn check(cx: &LateContext<'_>, expr: &hir::Expr<'_>, s... |
const CONVERSION: [char; 16] = ['0','1','2','3',
'4','5','6','7',
'8','9','a','b',
'c','d','e','f'];
pub fn convert_ascii(a: u8) -> char {
CONVERSION[a as usize]
} |
use std::borrow::Cow;
type Index = u32;
#[derive(Debug, Clone)]
pub enum IndexedStr {
Indexed(Index, Index),
Concrete(Cow<'static, str>)
}
impl IndexedStr {
/// Whether this string is derived from indexes or not.
pub fn is_indexed(&self) -> bool {
match *self {
IndexedStr::Indexed... |
#[doc = "Register `RDATA13R` reader"]
pub type R = crate::R<RDATA13R_SPEC>;
#[doc = "Field `RDATA1` reader - Regular conversion data for SDADC1"]
pub type RDATA1_R = crate::FieldReader<u16>;
#[doc = "Field `RDATA3` reader - Regular conversion data for SDADC3"]
pub type RDATA3_R = crate::FieldReader<u16>;
impl R {
#... |
//use std::env;
use std::fs;
use super::super::constants;
use log;
use serde::{Serialize, Deserialize};
use serde_json::Error;
#[derive(Serialize, Deserialize, Debug)]
pub struct Config {
pub site_domain: String,
pub site_author: String,
pub author_twitter: String,
pub author_email: String,
pub... |
//! 914. 卡牌分组
//! https://leetcode-cn.com/problems/x-of-a-kind-in-a-deck-of-cards/
use std::collections::HashMap;
fn gcd(x: i32, y: i32) -> i32 {
if x == 0 {
return y;
}
gcd(y % x, x)
}
pub struct Solution;
impl Solution {
pub fn has_groups_size_x(deck: Vec<i32>) -> bool {
if deck.le... |
extern crate chrono;
use chrono::DateTime;
use std::fmt::Debug;
pub trait Diff: Debug + PartialEq {
fn diff<'a>(&'a self, other: &'a Self) -> Option<Vec<Difference<'a>>>;
}
/// Field that differs
#[derive(Debug)]
pub struct Difference<'a> {
pub field: String,
pub left: &'a Debug,
pub right: &'a Debug... |
use icfp2019::prelude::Result;
use loggerv;
use structopt::StructOpt;
#[derive(StructOpt, Debug)]
struct Opt {
#[structopt(short = "v", parse(from_occurrences))]
verbose: u64,
#[structopt(subcommand)]
cmd: Command,
}
#[derive(StructOpt, Debug)]
enum Command {
#[structopt(name = "run")]
Run {
... |
use thiserror::Error;
#[derive(Debug, Error)]
pub enum Error {
#[error(transparent)]
KubeError(#[from] kube::error::Error),
#[error("missing object key in {0})")]
MissingObjectKey(&'static str),
}
|
use cgmath::{Vector1, Vector2, Vector3, Vector4};
use cgmath::{Matrix2, Matrix3, Matrix4};
use std::mem::transmute;
pub trait ToRawMath {
type Raw: Copy;
fn to_raw(self) -> Self::Raw;
}
macro_rules! impl_to_raw {
($from:ty, $to:ty) => {
impl ToRawMath for $from {
type Raw = $to;
... |
#[doc = "Register `HDPEXTR` reader"]
pub type R = crate::R<HDPEXTR_SPEC>;
#[doc = "Register `HDPEXTR` writer"]
pub type W = crate::W<HDPEXTR_SPEC>;
#[doc = "Field `HDP1_EXT` reader - HDP area extension in 8�Kbytes sectors in Bank1. Extension is added after the HDP1_END sector (included)."]
pub type HDP1_EXT_R = crate::... |
mod counts;
mod globals;
mod list;
use std::sync::Arc;
use twilight_model::application::{
command::CommandOptionChoice,
interaction::{application_command::CommandOptionValue, ApplicationCommand},
};
use crate::{
commands::{
osu::{option_country, option_discord, option_mode, option_mods_explicit, ... |
//!Combining several log systems into one.
use cluExtIO::UnionWrite;
use crate::log_core::LogStatic;
use crate::log_core::LogLockIO;
use crate::log_core::LogBase;
use crate::log_core::LogFlush;
use crate::log_core::LogExtend;
use std::io::Write;
use std::fmt::Arguments;
use std::marker::PhantomData;
use std::io;
#[... |
#![no_std]
pub mod rtt;
|
use std::mem::ManuallyDrop;
use std::slice;
use napi::*;
use crate::sk::Bitmap;
#[derive(Debug, Clone)]
pub struct ImageData {
pub(crate) width: usize,
pub(crate) height: usize,
pub(crate) data: *const u8,
}
impl Drop for ImageData {
fn drop(&mut self) {
let len = (self.width * self.height * 4) as usize... |
use std::hash::Hash;
use std::fmt::Debug;
use crate::machine::*;
#[derive(Debug)]
pub struct ParallelMachine<A, S, C> {
pub id: String,
pub machines: Vec<Machine<A, S, C>>,
pub value: Vec<S>
}
impl<A: Copy, S: Eq + Hash + Copy, C: Debug + Copy> ParallelMachine<A, S, C> {
/// Create a new state machin... |
//! Manage and deduplicate ratings and interactions.
//!
//! This code consolidates rating de-duplication into a single place, so we can use the same
//! logic across data sets. We always store timestamps, dropping them at output time, because
//! the largest data sets have timestamps. Saving space for the smallest d... |
use macroquad::prelude::*;
#[derive(Default)]
struct Path {
nodes: Vec<Vec2>,
}
impl Path {
fn debug_draw(&self) {
for w in self.nodes.windows(2) {
let (n1, n2) = (w[0], w[1]);
draw_line(n1.x, n1.y, n2.x, n2.y, 2.0, RED);
}
}
fn project_next_at_mouse(&self) {
... |
#[test]
fn normalize_test() {
assert!(::mongo_config::AGG_FUNCTIONS.contains_key("not"));
}
|
#![macro_use]
use middle::middle::*;
use mangle::Mangle;
use ast::name::Symbol;
use context::Context;
use stack::Stack;
use std::fmt;
use std::borrow::ToOwned;
macro_rules! emit {
( $($instr: expr),+ ; $($comment: expr),+ ) => (
println!("{:<40} ; {}", format!($($instr),+), format!($($comment),+))
);
... |
use serde::{Deserialize, Serialize};
use std::error::Error;
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Config {
pub token: String,
pub admin_user_id: i64,
pub commands: std::collections::HashMap<String, Command>
}
impl Config {
pub fn from_config() -> Result... |
use serenity::builder::CreateEmbed;
use serenity::framework::standard::CommandError;
use serenity::model::channel::Message;
use serenity::prelude::Context;
use crate::db::*;
use crate::model::{GameServer, GameServerState};
pub fn lobbies(context: &mut Context, message: &Message) -> Result<(), CommandError> ... |
use crate::input::DbValue;
pub type Result<T> = std::result::Result<T, Error>;
#[derive(Debug)]
pub enum Error {
ModelNotFound(String),
FieldNotFound(String),
InvalidValue(String),
InvalidJson(String),
Rusqlite(rusqlite::Error),
Chrono(chrono::ParseError),
Io(std::io::Error),
}
impl Error ... |
//! The crate `nathru` (NUmber THeory in RUst) implements a few simple number theory functions.
use std::cmp;
#[cfg(test)]
mod tests {
use super::*;
#[test] fn test1a() { assert_eq!(gcd(945, 165), 15); }
#[test] fn test1b() { assert_eq!(gcd(945, -165), -15); }
#[test] fn test2a() { assert_eq!(... |
#[cfg_attr(not(feature = "verbose"), allow(unused_variables))]
#[cfg(test)]
mod tests {
use bbqueue::{BBBuffer, Error};
use rand::prelude::*;
use std::thread::spawn;
use std::time::{Duration, Instant};
#[cfg(feature = "travisci")]
const ITERS: usize = 10_000;
#[cfg(not(feature = "travisci")... |
use super::*;
/*
fn lobby_helper(
db_conn: &DbConnection,
era: Era,
player_count: i32,
alias: &String,
author_id: UserId,
) -> Result<(), CommandError> {
*/
#[test]
fn add_lobby() {
let db_conn = DbConnection::test();
let initial_server_count = db_conn.count_servers();
let initial_lob... |
use druid::shell::{runloop, WindowBuilder};
use druid::widget::{ActionWrapper, Button, Column, Flex, Label, Padding, Row, TextBox};
use druid::{BoxedWidget, Data, UiMain, UiState, WidgetPod};
use druid::kurbo::{Rect, Size};
use druid::{
Action, BaseState, BoxConstraints, Env, Event, EventCtx, LayoutCtx, Lens, Lens... |
use std::time::Duration;
use color_eyre::Result;
use futures::Future;
use prost::bytes::Buf;
use prost::Message;
pub trait MessageExt<M> {
fn try_parse<B: AsRef<[u8]>>(b: B) -> color_eyre::Result<M>;
fn to_bytes(&self) -> Vec<u8>;
}
pub trait BufExt {
fn parse_into<M: Message + Default>(self) -> Result<... |
//
// RaphPdf
//
// @copyright Copyright (c) 2020-2020 Grégory Muller
// @license https://www.apache.org/licenses/LICENSE-2.0
// @link https://github.com/debitux/raphpdf
// @since 0.1.0
//
extern crate pdf_form_ids;
pub mod iris;
pub mod symag;
use iris::{fill_pdf_iris, read_file_iris, Iris};
use syma... |
use super::TreeNode;
use std::cell::RefCell;
use std::rc::Rc;
pub struct CodecDFS;
impl CodecDFS {
pub fn new() -> Self {
CodecDFS {}
}
/// 深度优先,先序遍历
/// DFS trave
/// BNF Expr
/// T->'None' | val,T,T | (val)
/// (val) means node without left and right child node, 'None' this is a e... |
use libp2p::mdns::{Mdns, MdnsEvent};
use libp2p::swarm::NetworkBehaviourEventProcess;
use libp2p::NetworkBehaviour;
use tokio::prelude::{AsyncRead, AsyncWrite};
use crate::behavior::{Pbft, PbftEvent};
#[derive(NetworkBehaviour)]
pub struct NetworkBehaviourComposer<TSubstream: AsyncRead + AsyncWrite> {
mdns: Mdns<T... |
use serde::{Deserialize, Serialize};
#[derive(Debug, Default, Serialize, Deserialize)]
pub struct Comment {
pub id: i64,
#[serde(rename = "parentId")]
pub parent_id: i64,
pub content: String,
#[serde(rename = "createdAt")]
pub created_at: String,
#[serde(rename = "editedAt")]
pub edited... |
pub const WORDLIST: &'static [&'static str] = &[
"абажур",
"абзац",
"абонент",
"абрикос",
"абсурд",
"авангард",
"август",
"авиация",
"авоська",
"автор",
"агат",
"агент",
"агитатор",
"агнец",
"агония",
"агрегат",
"адвокат",
"адмирал",
"адрес",
... |
use aoc2020::aoc::load_data;
use nom::{
bits::complete::*, branch::*, bytes::complete::*, character::complete::*, combinator::*,
multi::*, sequence::*, IResult,
};
use regex::Regex;
use std::collections::HashMap;
use std::collections::HashSet;
use std::fmt::Debug;
use std::hash::Hash;
use std::io::BufRead;
typ... |
pub struct DevTree {
busses: Vec<Box<dyn Bus>>,
}
#[derive(Debug, Copy, Clone)]
pub struct DeviceIdent {
pub bustype: twz::device::BusType,
pub vendor_id: u64,
pub device_id: u64,
pub class: u64,
pub subclass: u64,
}
impl DeviceIdent {
pub fn is_match(&self, other: &DeviceIdent) -> bool {
other.bustype == se... |
use std::error::Error;
struct Rect {
width: u32,
height: u32,
}
impl Rect {
fn can_hold(&self, other: &Rect) -> bool {
self.width > other.width && self.height > other.height
}
}
fn sqrt(val: f64) -> Result<f64, String> {
if val < 0.0 {
return Err(format!("negative value - {}", val... |
#[derive(Debug)]
enum Grade {
Passed,
NotPassed
}
fn is_passed(score: f64) -> Grade {
match score {
x if x < 60.0 => Grade::NotPassed,
_ => Grade::Passed
}
}
fn main() {
for score in 58..62 {
println!("{} is {:?}", score, is_passed(score as f64));
}
const SC: f64 =... |
use std::io;
use std::marker::PhantomData;
use std::net::SocketAddr;
use std::time::Duration;
use crate::backlog::Backlog;
use crate::client::{SocketClient, SocketStatus};
use bincode::Result;
use serde::{de::DeserializeOwned, Serialize};
use socket2::{Domain, Socket, Type};
pub struct SocketServer<Req, Res>
where
... |
use pcap::*;
fn main() {
match pcap_findalldevs() {
Ok(devices) => {
devices.iter().for_each(|device| {
println!("{:#?}", device)
});
}
Err(err) => {
panic!("{:?}", err);
}
}
}
|
// Copyright (c) Facebook, Inc. and its affiliates.
//
// This source code is licensed under the MIT license found in the
// LICENSE file in the root directory of this source tree.
use math::StarkField;
// FRI OPTIONS
// ================================================================================================
... |
use anyhow::Result;
use std::{collections::HashMap, fs};
struct Day15 {
starting: Vec<usize>,
numbers: HashMap<usize, usize>,
last: Option<usize>,
index: usize,
}
impl Iterator for Day15 {
type Item = usize;
fn next(&mut self) -> Option<Self::Item> {
let result = if self.index < self.... |
use super::HyperLTL::*;
use super::Op::*;
use super::QuantKind::*;
use super::*;
use std::collections::HashSet;
impl HyperLTL {
fn check_arity(&self) {
match self {
Quant(_, _, scope) => scope.check_arity(),
Appl(op, inner) => {
inner.iter().for_each(|ele| ele.check_... |
mod from_into;
mod tryfrom_tryinto;
mod to_from_strings;
fn main() {
from_into::main();
tryfrom_tryinto::main();
to_from_strings::main();
} |
use crate::{
db::HirDatabase,
ids::{FunctionType, Identifier, RecordType, Type},
lower::{
error::{LoweringError, Missing},
Lower, LoweringCtx,
},
types::{FunctionTypeData, RecordTypeData, TypeData},
};
use christmas_tree::RootOwnership;
use valis_ds::Intern;
use valis_syntax::{
a... |
#[macro_use]
extern crate diesel;
mod config;
pub mod models;
mod schema;
use diesel::prelude::*;
use diesel::r2d2::{ConnectionManager, Pool, PooledConnection};
use thiserror::Error;
#[derive(Debug, Error)]
pub enum DatabaseError {
#[error("Config error: {0}")]
Config(config::ConfigError),
}
pub type Databa... |
#[macro_use]
extern crate nom;
use nom::{alphanumeric1, space, types::CompleteStr};
named!(key<CompleteStr,CompleteStr>,
call!(alphanumeric1)
);
named!(operator<CompleteStr,CompleteStr>,
tag!("=")
);
named!(value<CompleteStr,CompleteStr>,
recognize!(many1!(alt_complete!(alphanumeric1 | space)))
);
named!(statem... |
use std::{process, thread};
use std::error::Error;
use std::collections::HashMap;
use std::fs::File;
use std::path::Path;
use std::time::Duration;
use error::SimpleError;
extern crate serde_json;
macro_rules! write_str_ret {
($win:expr, $s:expr) => {
if $win.addstr($s) == ERR {
ret_err!(format... |
use std::collections::BinaryHeap;
use std::io;
use std::io::prelude::*;
use std::time::{Instant};
use std::thread;
use ordered_float::OrderedFloat;
use evmap::{ReadHandle, WriteHandle};
use rand::{Rng};
use uuid::Uuid;
const SIZE: u32 = 8 * 1024 * 1024;
const HEAP_CAPACITY: usize = 10;
const NTHREADS: u32 = 4;
mod... |
fn union (_a: &Vec<String>,mut _b: &Vec<String>) -> Vec<String> {
let mut _c: Vec<String> = Vec::new();
for ele in _a {
if !_c.contains(&ele) {
_c.push(ele.to_string());
}
}
for ele in _b {
if !_c.contains(&ele) {
_c.push(ele.to_string());
}
}
_c
}
fn intersection(_a: &Vec<Strin... |
/// bindings for ARINC653P2-4 3.4 schedules
pub mod basic {
use crate::bindings::*;
pub type ScheduleName = ApexName;
/// According to ARINC 653P1-5 this may either be 32 or 64 bits.
/// Internally we will use 64-bit by default.
/// The implementing Hypervisor may cast this to 32-bit if needed
... |
#![deny(missing_docs)]
#![doc(html_root_url = "http://arcnmx.github.io/result-rs/")]
//! Helpers for dealing with nested `Result` and `Option` types. Convert a
//! `Option<Result<T, E>>` to `Result<Option<T>, E>` and vice versa.
//!
//! `use result::prelude::*` is recommended in order to import the extension
//! trait... |
pub struct GridPosition
{
pub column: i32,
pub row: i32,
}
pub fn grid_to_position(grid_pos: &GridPosition, width: f32, height: f32) -> cgmath::Vector2<f32>
{
let tile_width = 2.0 / width;
let tile_height = 2.0 / height;
cgmath::Vector2 { x: -1.0 + tile_width / 2.0 + grid_pos.column as f32 * tile... |
extern crate usbd_hid_descriptors;
use syn::{parse, Field, Fields, Type, Expr, Result, Ident, ExprLit, Lit, TypePath};
use usbd_hid_descriptors::*;
use crate::spec::*;
// MainItem describes all the mandatory data points of a Main item.
#[derive(Debug, Default, Clone)]
pub struct MainItem {
pub kind: MainItemKind,... |
#![no_std]
extern crate rawpointer;
extern crate core as std;
mod iter;
pub use iter::{SliceIter};
|
//! Cretonne file reader library.
//!
//! The `cretonne_reader` library supports reading .cton files. This functionality is needed for
//! testing Cretonne, but is not essential for a JIT compiler.
#![deny(missing_docs, trivial_numeric_casts, unused_extern_crates)]
#![warn(unused_import_braces, unstable_features)]
#
// scanning the node
fn walk(indent:... |
use indicatif::{ProgressBar, ProgressStyle};
use std::convert::TryInto;
pub enum Message {
Update(u32),
Kill,
}
pub struct ProgBar {
bar: ProgressBar,
outfile: String,
}
impl ProgBar {
pub fn new(outfile: &String, full_val: u32) -> ProgBar {
let bar = ProgressBar::new(full_val.try_into().... |
use std::{
ops::{Add,AddAssign,Sub,SubAssign,Mul,MulAssign,Div,DivAssign,Neg},
mem,
};
use crate::traits::*;
use num_traits::Signed;
use serde::{Serialize, Deserialize};
pub use float_cmp::{Ulps,ApproxEq};
macro_rules! implement_vector {
($type:ident {
dim: $dim:expr,
elems: { $($num:exp... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.