text stringlengths 8 4.13M |
|---|
use std::iter::{Extend, IntoIterator};
#[derive(Debug, Default)]
pub struct MySqlQueryResult {
pub(super) rows_affected: u64,
pub(super) last_insert_id: u64,
}
impl MySqlQueryResult {
pub fn last_insert_id(&self) -> u64 {
self.last_insert_id
}
pub fn rows_affected(&self) -> u64 {
... |
use std::collections::BinaryHeap;
use std::collections::HashSet;
#[derive(Clone, Copy, PartialEq, Eq)]
struct NodeCand {
cost: i64,
vid: usize,
}
// to minimize binaryHeap, inverse order
impl Ord for NodeCand {
fn cmp(&self, other: &NodeCand) -> std::cmp::Ordering {
other.cost.cmp(&self.cost)
}... |
use std::time::{Duration, Instant};
use amethyst::utils::fps_counter::FpsCounter;
use super::system_prelude::*;
pub struct DebugSystem {
to_print: Vec<String>,
last_fps_print: Instant,
}
const PRINT_EVERY_MS: u64 = 1000;
impl<'a> System<'a> for DebugSystem {
type SystemData = (
ReadExpect... |
use AsMutLua;
use AsLua;
use Push;
use PushGuard;
use LuaRead;
macro_rules! tuple_impl {
($ty:ident) => (
impl<LU, $ty> Push<LU> for ($ty,) where LU: AsMutLua, $ty: Push<LU> {
fn push_to_lua(self, lua: LU) -> PushGuard<LU> {
self.0.push_to_lua(lua)
}
}
... |
use libc::printf as _printf;
use wasmer_runtime_core::Instance;
/// putchar
pub use libc::putchar;
/// printf
pub extern "C" fn printf(memory_offset: i32, extra: i32, instance: &Instance) -> i32 {
debug!("emscripten::printf {}, {}", memory_offset, extra);
unsafe {
let addr = instance.memory_offset_ad... |
use std::cmp::Ordering;
use std::convert::From;
use std::f32::EPSILON;
use std::fmt;
use std::ops::{Add, Sub};
pub type Tick = u64;
impl PartialEq<Time> for Tick {
fn eq(&self, time: &Time) -> bool {
*self == time.tick
}
}
impl PartialOrd<Time> for Tick {
fn partial_cmp(&self, time: &Time) -> Opt... |
// Let's try to work on a famous fun programming problem based on the popular
// 99 bottles of the beer song.
// Song:
// 99 bottles of beer on the wall, 99 bottles of beer.
// Take one down and pass it around, 98 bottles of beer on the wall.
// 98 bottles of beer on the wall, 98 bottles of beer.
// Take one down ... |
//! Сигнатуры, структурные составляющие файла
//!
//! Файл *.chg разбит тексовыми вставками на отдельные блоки.
mod file_type;
mod barpbres_fe;
mod bkngwl_bnw;
mod boknagr_bkn;
mod clmn_uni;
mod coeffs_rsu;
mod elems_fe;
mod elemsres_fe;
mod elsss_fe;
mod etnames_et;
mod expert;
mod head_fe;
mod isoar_fe;
mod loadcomb... |
use clap::Command;
use crates_io_api::CrateResponse;
use serde::{Deserialize, Serialize};
use std::collections::{BTreeMap, HashMap};
use std::fs;
use std::io;
use std::path::Path;
use std::time::Duration;
fn cli() -> Command {
Command::new("AreWeGuiYet CLI")
.subcommand_required(true)
.arg_require... |
pub mod cluster;
pub mod models;
pub mod tenant;
/*macro_rules! error {
($txt:expr, $($args:expr), *) => {
return Box::new(io::Error::new(io::ErrorKind::Other, format!($txt)));
};
}*/
|
use crate::generator::{Callback, Generator};
use crate::util::camera::Camera;
use crate::util::outputbuffer::OutputBuffer;
#[derive(Debug)]
pub struct BasicGenerator;
impl Generator for BasicGenerator {
fn generate(&self, camera: &Camera, callback: &Callback) -> OutputBuffer {
let mut output = OutputBuffe... |
//! Example webapp using [`willow`](https://docs.rs/willow/).
#![allow(clippy::blacklisted_name)]
#![warn(missing_docs)]
use nalgebra::{Matrix4, Vector3};
use wasm_bindgen::prelude::*;
use web_sys::WebGlRenderingContext;
use willow::{
AspectFix, Attribute, BufferDataUsage, Clear, Context, Indices, Program, Progra... |
use std::ops;
use std::f32;
use super::deg2rad;
#[derive(Debug, Clone, PartialEq)]
pub struct Vec3 {
pub x: f32,
pub y: f32,
pub z: f32
}
// indices
impl ops::Index<usize> for Vec3 {
type Output = f32;
fn index<'a>(&'a self, index: usize) -> &'a f32 {
match index {
0 => &self.... |
#[macro_use]
extern crate diesel;
use actix_web::{get, middleware, post, web, App, Error, HttpServer, HttpRequest, HttpResponse, Responder};
use tera::{Tera, Context};
use listenfd::ListenFd;
use diesel::prelude::*;
use diesel::r2d2::{self, ConnectionManager};
use uuid::Uuid;
mod actions;
mod models;
mod schema;
type... |
use crate::{coinbase, crypto_service, models};
const COINBASE_API_URL: &str = "https://api.pro.coinbase.com";
pub async fn get_trades_data_for_pair(
coin_pair: &str,
) -> models::CoinPairData<Vec<coinbase::models::Trade>> {
let exchange_name = "coinbase";
let data_type = "trades";
let trades = get_tra... |
use serenity::{
builder::CreateEmbed,
client::Context,
framework::standard::{macros::command, CommandResult},
model::prelude::Message,
};
// command name is example
#[command("example")]
// aliases are ex and ax
#[aliases("ex", "ax")]
// rate limit bucket is "heavy" (the one we made in fn entrypoint)
#... |
#[doc = "Reader of register PREPHY"]
pub type R = crate::R<u32, super::PREPHY>;
#[doc = "Reader of field `R0`"]
pub type R0_R = crate::R<bool, bool>;
impl R {
#[doc = "Bit 0 - Ethernet PHY Module Peripheral Ready"]
#[inline(always)]
pub fn r0(&self) -> R0_R {
R0_R::new((self.bits & 0x01) != 0)
}... |
use criterion::{criterion_group, criterion_main, BatchSize, Criterion, Throughput};
use rand::prelude::*;
use rand_distr::Pareto;
use std::collections::HashMap;
use std::sync::{Arc, RwLock};
fn pure_read(lotable: Arc<RwLock<HashMap<String, u64>>>, key: String, thread_count: u64) {
let mut threads = vec![];
f... |
use std::fmt::{Debug, Display};
use async_trait::async_trait;
use data_types::{ParquetFile, PartitionId};
pub mod catalog;
pub mod mock;
pub mod rate_limit;
/// Finds files in a partition for compaction
#[async_trait]
pub trait PartitionFilesSource: Debug + Display + Send + Sync {
/// Get undeleted parquet files... |
use crate::types::Float;
use crate::types::Int;
use crate::types::Number;
use core::intrinsics;
use num::Num;
use num::ToPrimitive;
use crate::efloat::EFloat;
use std::f64;
pub mod consts {
use super::next_float_up;
use super::Float;
use std::f64;
pub static INFINITY: Float = f64::INFINITY;
pub st... |
use chrono::Utc;
use serenity::builder::CreateEmbed;
use serenity::model::user::User;
use crate::constants::PLACEHOLDER;
use crate::models::apod::Apod;
use crate::models::launch::Launch;
use crate::models::url::VidURL;
use crate::services::database::launch::DBLaunch;
pub fn create_basic_embed() -> CreateEmbed {
l... |
use atoms::{Location, Token, TokenType};
use std::sync::Arc;
///
/// A Tokenizer is a 'class' that handles creating a
/// list of tokens from a file buffer.
///
/// NOTE: The tokens produced by this tokenizer must not outlive
/// the file buffer and file name provided to the tokenizer.
///
pub struct Tokenizer<'file> ... |
{{#>set_constraints constraints~}}
{{#>loop_nest loop_nest~}}
{{#ifeq action "FilterSelf"}}{{>filter_self choice=../../../../this}}{{/ifeq~}}
{{#with action.FilterRemote}}{{>choice_filter}}{{/with~}}
{{#with action.IncrCounter}}{{>incr_counter}}{{/with~}}
{{#with action.UpdateCounter... |
/*
* Copyright 2020 Fluence Labs Limited
*
* 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 a... |
use std::io;
use std::net::SocketAddr;
use std::thread;
use tokio_core::net::UdpSocket;
use tokio_core::reactor::Core;
use tokio_core::net::UdpCodec;
use futures::{Future, Stream};
use futures::sync::mpsc;
use futures::Sink;
pub struct LineCodec;
impl UdpCodec for LineCodec {
type In = (SocketAddr, Vec<u8>);
... |
//! If any available, this provides handles for various forms of asynchronous
//! drivers that can be used in combination with audio interfaces.
mod atomic_waker;
use crate::Result;
use std::cell::Cell;
use std::future::Future;
use std::ptr;
thread_local! {
static RUNTIME: Cell<*const Runtime> = Cell::new(ptr::nu... |
// 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.
mod segments;
pub use segments::{RasterSegments, RasterSegmentsIter};
use std::{iter, rc::Rc};
#[cfg(feature = "tracing")]
use fuchsia_trace::duration;
... |
use crate::formats::{ReferenceFormat, ReferenceFormatSpecification, HASHES};
use crate::object::{ObjectHash, ObjectId, HASH_LENGTH, UUID_LENGTH};
use crate::Result;
use std::collections::{hash_map, HashMap};
use std::convert::TryInto;
use std::io;
use std::io::{BufRead, Read, Write};
use std::mem::size_of;
use std::ops... |
use super::DirEntryTrait;
use crate::fs::FileTypeTrait;
use crate::fs::StandaloneFileType;
use std::ffi::OsStr;
use std::fs;
use std::io;
use std::path::Path;
use std::path::PathBuf;
#[derive(Debug, Clone)]
pub struct DirEntry {
raw: PathBuf,
file_type: StandaloneFileType,
}
impl DirEntry {
pub fn from_pa... |
use std::str::FromStr;
use postgres::{Client as PostgresClient, NoTls};
error_chain! {
types {
ConnectionError, ConnectionErrorKind, ConnectionResultExt, ConnectionResult;
}
foreign_links {
PostgresConnect(::postgres::error::Error);
}
errors {
MalformedConnectionString {
... |
pub mod interop;
use ipfs::Node;
/// The way in which nodes are connected to each other; to be used with spawn_nodes.
#[allow(dead_code)]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Topology {
/// no connections
None,
/// a > b > c
Line,
/// a > b > c > a
Ring,
/// a <> b <> c <>... |
use procon_reader::ProconReader;
use std::cmp::Reverse;
fn main() {
let stdin = std::io::stdin();
let mut rd = ProconReader::new(stdin.lock());
let n: usize = rd.get();
let s: Vec<u64> = rd.get_vec(n);
let t: Vec<u64> = rd.get_vec(n);
use std::collections::BinaryHeap;
let mut heap = Binar... |
use super::VarResult;
use crate::ast::stat_expr_types::VarIndex;
use crate::ast::syntax_type::{FunctionType, FunctionTypes, SimpleSyntaxType, SyntaxType};
use crate::helper::err_msgs::*;
use crate::helper::str_replace;
use crate::helper::{
ensure_srcs, ge1_param_i64, move_element, pine_ref_to_bool, pine_ref_to_f64,... |
use super::{Register, State, Transition, Value};
use itertools::Itertools;
use pathfinding::directed::astar::astar;
use std::cmp::min;
// TODO: Caches results using normalized version of the problem.
impl State {
pub(crate) fn transition_to(&self, goal: &Self) -> Vec<Transition> {
assert!(self.reachable(g... |
use crate::cache::ResponseCache;
use crate::error::Result;
use crate::proto::{Proto, Request};
use serde::{Deserialize, Serialize};
use serde_json::Value;
use std::rc::Rc;
pub(super) struct Lighting {
ns: String,
proto: Rc<Proto>,
cache: Rc<ResponseCache>,
}
impl Lighting {
pub(super) fn new(ns: &str... |
#![feature(extern_prelude)]
#[macro_use]
extern crate serde_derive;
#[macro_use]
extern crate serde;
extern crate simple_server;
pub mod apilib {
pub mod transfer;
pub mod request;
pub mod response;
pub mod target;
#[cfg(test)]
mod tests;
}
|
use tui::layout::{Direction, Group, Rect, Size};
use tui::style::*;
use tui::widgets::*;
use components::App;
use models::{AppState, Mode};
use widgets::{self, ChatHistory};
use TerminalBackend;
pub fn render(app: &App, terminal: &mut TerminalBackend, size: &Rect) {
Group::default()
.direction(Direction::... |
use std::cmp::{max, min};
use regex::Regex;
fn main() {
let input:Result<_,_> = include_str!("input").lines().map(str::parse).collect();
let input: Vec<Action> = input.unwrap();
let part_one_input = input.iter().filter(|action| {
action.region.is_inside(Cuboid {
x: [-50, 50],
... |
struct ColumnIter<I> where I: Iterator {
iterators: Vec<I>
}
impl<I, T> Iterator for ColumnIter<I> where I: Iterator<Item=T> {
type Item = Vec<T>;
fn next(&mut self) -> Option<Self::Item> {
self.iterators.iter_mut().map(|iter| iter.next()).collect()
}
}
struct Image {
layers : Vec<Vec<u32>... |
#![allow(non_snake_case, non_camel_case_types, non_upper_case_globals, clashing_extern_declarations, clippy::all)]
#[link(name = "windows")]
extern "system" {
pub fn HcnCloseEndpoint(endpoint: *const ::core::ffi::c_void) -> ::windows_sys::core::HRESULT;
pub fn HcnCloseGuestNetworkService(guestnetworkservice: *c... |
use std::fmt::{self, Display};
use std::str::FromStr;
use anyhow::bail;
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
pub enum Rcode {
NoError,
FormErr,
ServFail,
NXDomain,
NotImp,
Refused,
YXDomain,
YXRRset,
NXRRset,
NotAuth,
NotZone,
Reserved,
}
impl Rcode {
pub f... |
use std::fmt::{Debug, Display, Formatter};
use std::fmt;
use std::str;
use std::ffi::CStr;
use std::error::Error;
use std::str::from_utf8;
use cql_bindgen::cass_error_desc;
use cql_bindgen::CASS_ERROR_LIB_BAD_PARAMS;
use cql_bindgen::CASS_ERROR_LIB_NO_STREAMS;
use cql_bindgen::CASS_ERROR_LAST_ENTRY;
use cql_bindgen::C... |
// 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 std::env;
use std::io;
#[fuchsia_async::run_singlethreaded]
async fn main() {
let args: Vec<String> = env::args().collect();
if args.len() != ... |
use crate::{
builtins::{PyCode, PyDictRef},
compiler::{self, CompileError, CompileOpts},
convert::TryFromObject,
scope::Scope,
AsObject, PyObjectRef, PyRef, PyResult, VirtualMachine,
};
impl VirtualMachine {
pub fn compile(
&self,
source: &str,
mode: compiler::Mode,
... |
use std::collections::HashSet;
use fileutil;
fn get_adjacent(heightmap: &Vec<Vec<i32>>, pos: (usize, usize)) -> HashSet<(usize, usize)> {
let deltas: Vec<(i32, i32)> = vec![(0, 1), (0, -1), (1, 0), (-1, 0)];
let (pos_y, pos_x) = pos;
let adj: HashSet<(usize, usize)> = deltas.iter()
.map(|(dy, dx... |
pub mod config;
pub mod network;
pub mod protobuf;
pub mod raft;
pub mod rpc_server;
pub mod shutdown;
pub mod state_machine;
pub mod storage;
|
mod queries;
use crate::{
snapshot_comparison::queries::TestQueries, try_run_influxql, try_run_sql, MiniCluster,
};
use arrow::record_batch::RecordBatch;
use arrow_flight::error::FlightError;
use arrow_util::test_util::{sort_record_batch, Normalizer, REGEX_UUID};
use influxdb_iox_client::format::influxql::{write_c... |
use std::any::Any;
use crate::algebra::{Point2f, Mat2x2f};
use crate::canvas::Canvas;
use super::{GraphicObject};
#[derive(Clone, Debug)]
pub struct LineSegs2f {
pub vertices: Vec<Point2f>,
pub color: [f32; 4], // rgba
}
impl LineSegs2f {
pub fn new(vertices: Vec<Point2f>, color: [f32; 4]) -> LineSegs2f {... |
use fuzzcheck::{DefaultMutator, Mutator};
use fuzzcheck_mutators_derive::make_mutator;
#[derive(Clone, DefaultMutator)]
enum NoAssociatedData {
#[ignore_variant]
A,
B,
#[ignore_variant]
C,
D,
E,
}
#[derive(Clone)]
enum WithIgnore<T> {
CanMutate(u8),
CannotMutate(CannotMutate),
... |
#![feature(proc_macro_hygiene, decl_macro)]
#[macro_use]
extern crate rocket;
extern crate rocket_contrib;
#[macro_use]
extern crate diesel;
#[macro_use]
extern crate diesel_migrations;
#[macro_use]
extern crate serde;
#[macro_use]
extern crate serde_json;
#[macro_use]
extern crate slog;
use dotenv::dotenv;
use s... |
use std::io;
use agent_simple::*;
pub mod agent_simple;
fn main() {
let secret_key: u64 = agent_get_secret_key().unwrap();
let mut buffer: String = String::new();
println!("Please input a 8 byte message");
let _ = io::stdin().read_line(&mut buffer);
let mut message = [0u8; 8];
for i in 0..8 {
... |
use crate::{
event::{self, Event, LogEvent, Value},
transforms::{
regex_parser::{RegexParser, RegexParserConfig},
Transform,
},
};
use lazy_static::lazy_static;
use snafu::{OptionExt, Snafu};
use string_cache::DefaultAtom as Atom;
lazy_static! {
pub static ref MULTILINE_TAG: Atom = Atom... |
extern crate serde;
extern crate oasis_core_runtime;
#[macro_use]
mod api;
pub use api::{Key, KeyValue, Transfer, UpdateRuntime, Withdraw};
|
use rand::Rng;
use std::cmp::Ordering;
use std::io::stdin;
// fn main() { // Function
// print!("Hello !") // Marco
// }
fn main() {
let secret_number = rand::thread_rng().gen_range(1, 101);
loop{ // Start a loop
println!("Guess the number");
println!("Enter your guess");
let mut guess = String::new(... |
/// Sets DSO as default logger.
#[macro_export]
macro_rules! set_log {
(periph: $uarte:ident,pin_number: $pin_number:expr,buf_size: $buf_size:expr,) => {
const _: () = {
use ::core::{cell::UnsafeCell, ptr::NonNull, slice};
use ::drone_core::log;
use ::drone_cortexm::reg;
... |
use bit_vec::BitVec; // 0.5.1
fn main() {
let bv = BitVec::from_bytes(&[0b01110100, 0b10010010]);
assert_eq!(bv.iter().filter(|x| *x).count(), 7);
assert_eq!(rank(&bv, 4), 3);
assert_eq!(bv.rank(4), 3);
}
fn rank(bv: &BitVec, i: usize) -> usize {
bv.iter().take(i).filter(|x| *x).count()
}
trai... |
pub struct Solution;
#[derive(PartialEq, Eq, Clone, Debug)]
pub struct ListNode {
pub val: i32,
pub next: List,
}
type List = Option<Box<ListNode>>;
impl Solution {
pub fn swap_pairs(head: List) -> List {
let mut head = head;
let mut current = &mut head;
while current.is_some() &&... |
#[macro_use]
extern crate glium;
extern crate alice;
extern crate rand;
use std::fs::File;
use std::io::Cursor;
use glium::{DisplayBuild, Surface};
use glium::glutin::{Event, ElementState, VirtualKeyCode, MouseScrollDelta, MouseButton};
use alice::model::rendering::{ModelRenderer, prepare_model};
use alice::model::{Mo... |
use vec2d::*;
fn main() {
let mut v = matrix![[1, 2, 3], [4, 5, 6]];
//*v[0] = [5, 6];
//println!("v: {}, v.as_ptr(): {}", &v.v as *const )
println!("[[{}, {}], [{}, {}]]", v[0][0], v[0][1], v[1][0], v[1][1]);
} |
#![crate_name = "rho"]
extern crate ncurses;
mod host;
mod event;
mod client;
mod buffer;
use std::sync::Arc;
use std::sync::mpsc;
use std::sync::RwLock;
use std::sync::mpsc::{Receiver, Sender};
use host::Host;
use client::Client;
use buffer::Buffer;
use event::InputEvent;
use host::CursesHost;
pub use client::Gene... |
extern crate jni;
extern crate qrcode;
extern crate sass_rs;
use jni::JNIEnv;
use jni::objects::{JClass, JString};
use jni::sys::jstring;
use pulldown_cmark::{html, Parser};
use qrcode::QrCode;
use sass_rs::{compile_file, Options};
use sass_rs::OutputStyle;
#[no_mangle]
#[allow(non_snake_case)]
pub extern "system"... |
use openexr_sys as sys;
use crate::{
core::{
channel_list::{ChannelList, ChannelListRef, ChannelListRefMut},
cppstd::{
CppString, CppVectorFloat, CppVectorFloatRef, CppVectorFloatRefMut,
CppVectorString, CppVectorStringRef, CppVectorStringRefMut,
},
preview_i... |
// Copyright 2020 IOTA Stiftung
//
// 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 in w... |
use crate::expiring_hash_map::ExpiringHashMap;
use crate::{
event::{self, Event},
sinks::util::{
encoding::{EncodingConfigWithDefault, EncodingConfiguration},
StreamSink,
},
template::Template,
topology::config::{DataType, SinkConfig, SinkContext, SinkDescription},
};
use async_trait... |
/*
* hurl (https://hurl.dev)
* Copyright (C) 2020 Orange
*
* 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 ... |
use crate::memory::Memory;
pub struct ROM {
data: Vec<u8>,
}
impl ROM {
pub fn new(data: &[u8]) -> Self {
Self {
data: data.to_owned()
}
}
}
impl Memory for ROM {
#[inline]
fn get_u8(&self, addr: u16) -> u8 {
self.data[addr as usize]
}
#[inline]
fn... |
use crate::Error;
use futures::FutureExt;
use std::{
cmp,
future::Future,
pin::Pin,
task::{Context, Poll},
time::Duration,
};
use tokio::time::{delay_for, Delay};
use tower03::{retry::Policy, timeout::error::Elapsed};
pub enum RetryAction {
/// Indicate that this request should be retried with ... |
pub const MAP_WIDTH: usize = 80;
pub const MAP_HEIGHT: usize = 50;
pub const MAP_TOTAL_DIMENSION: usize = MAP_WIDTH * MAP_HEIGHT;
pub const COORDINATE_X: i32 = 79;
pub const COORDINATE_Y: i32 = 49;
pub const MAX_ROOMS: i32 = 30;
pub const MIN_SIZE_ROOM: i32 = 6;
pub const MAX_SIZE_ROOM: i32 = 10;
pub const VISIBLE_TILE... |
#[doc = "Reader of register SRGPIO"]
pub type R = crate::R<u32, super::SRGPIO>;
#[doc = "Writer for register SRGPIO"]
pub type W = crate::W<u32, super::SRGPIO>;
#[doc = "Register SRGPIO `reset()`'s with value 0"]
impl crate::ResetValue for super::SRGPIO {
type Type = u32;
#[inline(always)]
fn reset_value() ... |
use std::io::Read;
fn read<T: std::str::FromStr>() -> T {
let token: String = std::io::stdin()
.bytes()
.map(|c| c.ok().unwrap() as char)
.skip_while(|c| c.is_whitespace())
.take_while(|c| !c.is_whitespace())
.collect();
token.parse().ok().unwrap()
}
fn main() {
let... |
// https://leetcode-cn.com/problems/maximal-rectangle/
// 解法 https://segmentfault.com/a/1190000003498304
pub struct Solution {}
mod q84;
impl Solution {
pub fn maximal_rectangle(matrix: Vec<Vec<char>>) -> i32 {
let mut result = 0;
let y_len = matrix.first().unwrap_or(&vec![]).len();
matri... |
use super::parse::AST;
use super::parse::Node;
use super::parse::Operator;
use super::parse::Leaf;
use std::collections::HashMap;
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum Value {
Register(usize),
Immediate(i32),
Label(usize),
}
#[derive(Debug, Clone, PartialEq)]
pub struct Statement {
pub op... |
#[doc = r"Register block"]
#[repr(C)]
pub struct RegisterBlock {
#[doc = "0x00 - Access control register"]
pub acr: ACR,
#[doc = "0x04 - Program/erase control register"]
pub pecr: PECR,
#[doc = "0x08 - Power down key register"]
pub pdkeyr: PDKEYR,
#[doc = "0x0c - Program/erase key register"]... |
use super::Visibility;
use serde::Deserialize;
#[derive(Deserialize, Debug)]
pub struct UpdateEvent {
/// Whether the user has the overlay enabled or disabled. If the overlay
/// is disabled, all the functionality of the SDK will still work. The
/// calls will instead focus the Discord client and show the ... |
#![crate_id(name="cksum", vers="1.0.0", author="Michael Gehring")]
#![feature(macro_rules)]
/*
* This file is part of the uutils coreutils package.
*
* (c) Michael Gehring <mg@ebfe.org>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
... |
use crate::dto::Link;
use std::collections::HashMap;
use quick_xml::Reader;
use quick_xml::events::Event;
use crate::parser::ParsingState::{Skipping, ReadingSnippet, ReadingTitle, ReadingPaging};
use std::io::BufReader;
use std::convert::TryFrom;
use std::borrow::Cow;
pub struct Html<'a>(pub &'a [u8]);
#[derive(Defau... |
use cgmath::{
BaseFloat, EuclideanSpace, InnerSpace, Matrix3, Point2, Point3, SquareMatrix, Transform,
Vector3, Zero,
};
use collision::primitive::*;
use collision::{Aabb, Aabb2, Aabb3, Bound, ComputeBound, Primitive, Union};
use super::{Inertia, Mass, Material, PartialCrossProduct};
use collide::CollisionShap... |
//! File checksum computing and checksum file writing.
use std::{
borrow::Cow,
fs::File,
io::{self, Write},
path::{Path, PathBuf},
};
use rayon::{iter::ParallelIterator, prelude::ParallelBridge};
use sha2::{Digest, Sha256};
use crate::error::Error;
pub trait Checksum {
/// compute the hash of the... |
use std::{error, fmt};
use std::str::Utf8Error;
use std::string::FromUtf8Error;
pub static SIZE_MASKS: [u8; 9] = [
0b00000000,
0b10000000,
0b11000000,
0b11100000,
0b11110000,
0b11111000,
0b11111100,
0b11111110,
0b11111111
];
/// Simple error type returned either by the `Decoder` or... |
use std::result;
#[derive(Debug)]
pub enum SeriesError {
Error,
}
type Result<T> = result::Result<T, SeriesError>;
pub fn lsp(s: &str, length: usize) -> Result<u32> {
if length == 0 {
return Ok(1);
}
let digits = parse_input(s, length)?;
digits
.windows(length)
.map(|w|... |
mod exit;
mod queue;
use std::arch::global_asm;
use std::cell::{OnceCell, UnsafeCell};
use std::mem;
use std::ptr;
use std::sync::{
atomic::{AtomicI32, AtomicU64, Ordering},
Arc,
};
use std::thread::{self, ThreadId};
use firefly_rt::function::{DynamicCallee, ModuleFunctionArity};
use firefly_rt::process::{Pro... |
use net::{
packets::*,
tokio::{self, net::TcpListener},
ReadResponse, RemoteConnection,
};
use async_channel::Sender;
pub async fn server(
addr: &'static str,
read_buf_sender: Sender<(ReadBuffer, Sender<WriteBuf>)>,
) -> Result<(), Box<std::io::Error>> {
let listener = TcpListener::bind(addr).await?;
info!("St... |
mod resolve;
mod tree;
mod validate;
pub use tree::*;
use crate::errors::ErrorCx;
use crate::flatten::ResolverContext;
use crate::source_file::FileMap;
use annotate_snippets::snippet::{Annotation, AnnotationType, Snippet};
pub use resolve::dummy_span;
pub use validate::{eval_term, eval_type};
pub fn resolve_library(... |
use cid::Cid;
use core::convert::TryFrom;
use core::ops::Range;
use crate::file::reader::{FileContent, FileReader, Traversal};
use crate::file::{FileReadFailed, Metadata};
use crate::pb::{merkledag::PBLink, FlatUnixFs};
use crate::InvalidCidInLink;
/// IdleFileVisit represents a prepared file visit over a tree. The u... |
#[doc = r" Register block"]
#[repr(C)]
pub struct RegisterBlock {
#[doc = "0x00 - Start UART receiver"]
pub tasks_startrx: TASKS_STARTRX,
#[doc = "0x04 - Stop UART receiver"]
pub tasks_stoprx: TASKS_STOPRX,
#[doc = "0x08 - Start UART transmitter"]
pub tasks_starttx: TASKS_STARTTX,
#[doc = "0... |
#[doc = "Reader of register ROUTELOC2"]
pub type R = crate::R<u32, super::ROUTELOC2>;
#[doc = "Writer for register ROUTELOC2"]
pub type W = crate::W<u32, super::ROUTELOC2>;
#[doc = "Register ROUTELOC2 `reset()`'s with value 0"]
impl crate::ResetValue for super::ROUTELOC2 {
type Type = u32;
#[inline(always)]
... |
use serde_derive::Deserialize;
use super::{parse_to_config_file, ConfigStructure, Flattenable};
use crate::sort;
use crate::CONFIG_FILE;
const fn default_true() -> bool {
true
}
const fn default_scroll_offset() -> usize {
6
}
const fn default_max_preview_size() -> u64 {
2 * 1024 * 1024 // 2 MB
}
const fn... |
use std::env;
use std::process;
fn main() {
let args: Vec<String> = env::args().collect();
if args.len() < 2 {
println!("Need to provide a search term :)");
process::exit(1);
}
if let Err(e) = wikit::run(args) {
println!("Application error: {}", e);
process::exit(1);
... |
mod apu;
mod cpu;
mod gamepad;
mod gui;
mod ines;
mod kevtris;
mod mapper;
mod png;
mod ppu;
mod record;
use std::env;
fn main() {
let mut cpu = cpu::Cpu::new();
let args: Vec<String> = env::args().collect();
if args.len() > 1 {
let filename = &args[1];
let file = ines::File::read(filename)... |
#[doc = "Reader of register PPSSI"]
pub type R = crate::R<u32, super::PPSSI>;
#[doc = "Reader of field `P0`"]
pub type P0_R = crate::R<bool, bool>;
#[doc = "Reader of field `P1`"]
pub type P1_R = crate::R<bool, bool>;
#[doc = "Reader of field `P2`"]
pub type P2_R = crate::R<bool, bool>;
#[doc = "Reader of field `P3`"]
... |
use thiserror::Error;
use crate::direction::Direction;
#[derive(Debug, Error)]
pub enum DecodeError {
#[error("incomplete op (opcode={opcode:#04x})")]
Incomplete { opcode: u8 },
#[error("undefined op (opcode={opcode:#04x})")]
Undefined { opcode: u8 },
}
pub type DecodeResult<T> = Result<T, DecodeErr... |
use proconio::{input, marker::Usize1};
fn dfs(i: usize, g: &Vec<Vec<usize>>, seen: &mut Vec<bool>) {
seen[i] = true;
for &j in &g[i] {
if seen[j] {
continue;
}
dfs(j, g, seen);
}
}
fn main() {
input! {
n: usize,
m: usize,
edges: [(Usize1, Usi... |
use crate::dtos::{SurveyDTO, SurveyDTOs};
/// A trait that provides a collection like abstraction over read only database access.
///
/// Generic T is likely a DTO used for pure data transfer to an external caller,
/// whether that's via a REST controller or over gRPC as a proto type etc.
pub trait SurveyDTOReadReposi... |
fn main() {
struct User {
username: String,
email: String,
sign_in_count: u64,
active: bool,
}
let user1 = User {
email: String::from("someone@example.com"),
username: String::from("someusername123"),
active: true,
sign_in_count: 1,
};
println!("{}", user1.email);
println!(... |
use super::layer::Layer;
pub struct Network {
layers: Vec<Layer>,
}
impl Network {
pub fn new(layout: Vec<u32>) -> Network {
let mut layers = Vec::with_capacity(layout.len());
for (index, nb_neurons) in layout.into_iter().enumerate() {
layers.push(Layer::new(nb_neurons, find_previ... |
extern crate rayon;
extern crate rand;
extern crate statrs;
extern crate petgraph;
extern crate vec_graph;
extern crate gurobi;
extern crate capngraph;
extern crate bit_set;
extern crate docopt;
#[macro_use]
extern crate slog;
extern crate slog_stream;
extern crate slog_term;
extern crate slog_json;
extern crate serde;... |
use serde::{Deserialize, Serialize};
use structopt::StructOpt;
/// The command line arguments
#[derive(Debug, Deserialize, Serialize, StructOpt)]
#[serde(rename_all = "snake_case")]
pub enum Args {
/// Generate random bytes from /dev/nsm
Rand {
#[structopt(name = "number-of-bytes")]
number: u8,... |
fn solve(num_recipes: usize) -> String {
let mut recipes: Vec<usize> = vec![3, 7];
let mut current_recipes: Vec<usize> = vec![0, 1];
while recipes.len() < num_recipes + 10 {
let sum = (¤t_recipes)
.into_iter()
.map(|i| recipes[*i])
.sum::<usize>();
r... |
extern crate testing_tutorial;
use testing_tutorial::add_three_times_four;
#[test]
fn math_checks_out() {
let result = add_three_times_four(5i);
assert_eq!(32i, result);
} |
//! Helper functions for multipart support
use headers::{ContentType, HeaderMap, HeaderMapExt};
use mime;
/// Utility function to get the multipart boundary marker (if any) from the Headers.
pub fn boundary(headers: &HeaderMap) -> Option<String> {
headers.typed_get::<ContentType>().and_then(|content_type| {
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.