text stringlengths 8 4.13M |
|---|
pub fn is_valid_isbn(isbn: &str) -> bool {
let isbn_digits: Vec<char> = isbn.chars().enumerate()
.filter(|(index, ch)| {
ch.is_numeric() || (ch.is_alphabetic() && *ch == 'X' && *index == isbn.len() - 1 as usize)
})
.map(|(_, ch)| ch)
.collect();
let mut result: bool ... |
fn main() {
let v = vec![10,20,30,40,50] ;
// 全ての要素を繰り返す
print!("v is ");
for i in &v {
print!("{} ", i );
}
println!("");
// イテレータを使う
print!("v is ");
for i in v.iter() {
print!("{} ", i );
}
println!("");
// インデックス付きで繰り返す
print!("v is ");
for... |
use ir_derive::{
Instruction,
ReadInstruction,
WriteInstruction,
};
use ir_traits::{
Instruction,
ReadInstruction,
WriteInstruction,
};
use super::Chunk;
use num_derive::FromPrimitive;
use num_traits::FromPrimitive;
use serde::{Serialize, Deserialize};
#[derive(FromPrimitive, Instruction, Re... |
fn main() {
by_moving();
by_cloning();
by_mutating();
println!("concat!");
}
fn by_moving() {
let hello = "hello".to_string();
let world = "world";
let hello_world = hello + world;
println!("{}", hello_world);
}
fn by_cloning() {
let hello = "hello".to_string();
let wor... |
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.
pub use crate::syscall::raw::arch::abi::{
syscall0, syscall1, syscall2, syscall3, syscall4, syscall5, syscall6, S... |
fn main() {
println!("cargo:rerun-if-changed=.git/HEAD");
if let Some(rev) = rev_parse() {
println!("cargo:rustc-env=RUSTBOT_REV={}", rev);
}
}
/// Retrieves SHA-1 git revision. Returns `None` if any step of the way fails,
/// since this is only nice to have for the ?revision command and shouldn't ... |
//! # homectl
//!
//! homectl is a library for controlling various smart home devices.
#![recursion_limit="128"]
#![feature(custom_attribute)]
#![feature(clamp)]
pub mod prot {
//! This module contains traits defining capabilities smart home devices can
//! possess as well as concrete smart home device implementations.... |
use super::*;
use std::sync::RwLock;
pub struct RandomSearch<'a> {
handler: SearchHandler<'a>,
enable_dict: bool,
//dictionary: Dict,
}
impl<'a> RandomSearch<'a> {
pub fn new(handler: SearchHandler<'a>, enable_dict: bool) -> Self {
Self { handler, enable_dict }
}
pub fn run(&mut self... |
const ARRAY_MAX: usize = 25_000;
const LUDIC_MAX: usize = 2100;
/// Calculates and returns the first `LUDIC_MAX` Ludic numbers.
///
/// Needs a sufficiently large `ARRAY_MAX`.
fn ludic_numbers() -> Vec<usize> {
// The first two Ludic numbers
let mut numbers = vec![1, 2];
// We start the array with an imme... |
use std::time::Instant;
pub fn count_time_qps(tag: &str, total: u128, start: Instant) {
print_qps(tag, total, start);
print_each_time(tag, total, start);
}
///count qps
pub fn print_qps(tag: &str, total: u128, start: Instant) {
let time = start.elapsed().as_nanos();
println!(
"[count_qps] {} u... |
use std::fmt;
#[cfg(target_arch = "wasm32")]
use serde::Serialize;
#[cfg(not(feature = "std"))]
use alloc::string::String;
#[cfg_attr(target_arch = "wasm32", derive(Serialize))]
#[derive(Debug, Clone)]
pub struct ErrorMsg {
pub short: String,
pub extended: Option<String>,
}
impl fmt::Display for ErrorMsg {
fn... |
/// Solver errors.
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum SolverError
{
/// Found an unbounded certificate.
Unbounded,
/// Found an infeasibile certificate.
Infeasible,
/// Exceed max iterations.
ExcessIter,
/// Invalid [`crate::solver::Operator`].
InvalidOp,
... |
use {
http::{
header::{
CONNECTION, //
CONTENT_LENGTH,
HOST,
SEC_WEBSOCKET_ACCEPT,
SEC_WEBSOCKET_KEY,
SEC_WEBSOCKET_VERSION,
TRANSFER_ENCODING,
UPGRADE,
},
Request, StatusCode,
},
tsukuyom... |
/*
* A sample API conforming to the draft standard OGC API - Features - Part 1: Core
*
* This is a sample OpenAPI definition that conforms to the conformance classes \"Core\", \"GeoJSON\", \"HTML\" and \"OpenAPI 3.0\" of the draft standard \"OGC API - Features - Part 1: Core\". This example is a generic OGC API Fea... |
use crate::draw;
use glam::Vec2;
#[derive(serde::Serialize, serde::Deserialize, Clone, PartialEq)]
#[serde(deny_unknown_fields)]
pub struct Config {
pub size: f32,
pub border_thickness: f32,
pub border_color: [u8; 4],
tiles: fxhash::FxHashMap<(i32, i32), ()>,
pub art_handle: draw::ArtHandle,
#[... |
use std::collections::HashMap;
use serde::{Serialize, Deserialize};
use super::{Asset, AssetExt, AssetResult, category};
use crate::impl_ron_asset;
// -------------------------------------------------------------------------------------------------
#[derive(Default, Serialize, Deserialize)]
#[serde(transparent)]
pu... |
#![macro_use]
//! LVal: The basic object type
use std::mem;
use std::fmt;
use std::borrow::ToOwned;
use lenv::LEnv;
use parser::ast::{Expr, ExprNode};
use util::{print_error, stringify_vec};
/// Return an error
macro_rules! err(
($msg:expr) => (
return LVal::err($msg.to_string())
);
... |
use rtm::Reminder;
/// Creates a reminder.
///
/// Wraps https://api.slack.com/methods/reminders.add
#[derive(Clone, Debug, Serialize, new)]
pub struct AddRequest<'a> {
/// The content of the reminder
pub text: &'a str,
/// When this reminder should happen: the Unix timestamp (up to five years from now), ... |
#[macro_use]
extern crate clap;
extern crate env_logger;
#[macro_use]
extern crate log;
extern crate rustpython_parser;
extern crate rustpython_vm;
extern crate rustyline;
use clap::{App, Arg};
use rustpython_parser::error::ParseError;
use rustpython_vm::{
compile, error::CompileError, error::CompileErrorType, fra... |
/*
复原IP地址
给定一个只包含数字的字符串,复原它并返回所有可能的 IP 地址格式。
示例:
输入: "25525511135"
输出: ["255.255.11.135", "255.255.111.35"]
*/
use crate::string::Solution;
impl Solution {
pub fn restore_ip_addresses(s: String) -> Vec<String> {
use std::cmp::min;
use std::cmp::max;
if s.len() < 4 || s.len() > 12 { retur... |
use std::fmt::Debug;
use std::fmt::Display;
pub type ID = String;
pub type Element = String;
pub const MAX_ID_LENGTH: usize = 20; // TODO. Increase max length.
#[derive(Serialize, Deserialize, Debug, PartialEq, Eq)]
pub enum ListError {
ListIdEmptyError,
ListIdTooLongError(ID, usize, usize),
DuplicateLis... |
use crossterm::{style::Color, Result};
use rc_game::{Game, GameState, Position, Renderable, RogueCrossGame, GAME_COLS, GAME_ROWS};
use specs::{prelude::*, Builder, World, WorldExt};
use specs_derive::*;
#[derive(Component)]
struct LeftMover {
pub min_col: i32,
pub max_col: i32,
pub min_row: i32,
pub m... |
use svm_types::Template;
use crate::env::TemplateHash;
/// Computes Hash derived deterministically from raw `Template`.
pub trait TemplateHasher {
/// Given code as bytes, derives an Hash
fn hash(template: &Template) -> TemplateHash;
}
|
//pub mod ast;
use ghql::parse;
macro_rules! prompt {
() => {
print!("> ");
io::stdout().flush().expect("Could not flush stdout");
}
}
fn main() {
use std::io::{self, BufRead, Write};
println!();
println!("Available features (optional parameters in parentheses):");
println!()... |
extern crate argparse;
use argparse::{ArgumentParser, StoreTrue, Store};
mod decoder;
use decoder::*;
mod implementer;
use implementer::{*, rtype::*, itype::*, utype::*, stype::*, ujtype::*, sbtype::*};
mod assembler;
use assembler::*;
#[macro_use]
mod macro_definitions;
const REGFILE_SIZE: usize = 32;
const MEM_... |
#[doc = "Register `PLLSAI1CFGR` reader"]
pub type R = crate::R<PLLSAI1CFGR_SPEC>;
#[doc = "Register `PLLSAI1CFGR` writer"]
pub type W = crate::W<PLLSAI1CFGR_SPEC>;
#[doc = "Field `PLLSAI1M` reader - Division factor for PLLSAI1 input clock"]
pub type PLLSAI1M_R = crate::FieldReader<PLLSAI1M_A>;
#[doc = "Division factor ... |
#[doc = "Register `CSICFGR` reader"]
pub type R = crate::R<CSICFGR_SPEC>;
#[doc = "Register `CSICFGR` writer"]
pub type W = crate::W<CSICFGR_SPEC>;
#[doc = "Field `CSICAL` reader - CSI clock calibration Set by hardware by option byte loading during system reset nreset. Adjusted by software through trimming bits CSITRIM... |
#[doc = "Reader of register HV_CTL"]
pub type R = crate::R<u32, super::HV_CTL>;
#[doc = "Writer for register HV_CTL"]
pub type W = crate::W<u32, super::HV_CTL>;
#[doc = "Register HV_CTL `reset()`'s with value 0x32"]
impl crate::ResetValue for super::HV_CTL {
type Type = u32;
#[inline(always)]
fn reset_value... |
#[cfg(any(feature = "dst_arrow", feature = "dst_arrow2"))]
pub(crate) const SECONDS_IN_DAY: i64 = 86_400;
#[allow(dead_code)]
const KILO: usize = 1 << 10;
#[cfg(any(feature = "dst_arrow", feature = "dst_arrow2"))]
pub const RECORD_BATCH_SIZE: usize = 64 * KILO;
#[cfg(any(
feature = "src_postgres",
feature = ... |
use crate::vec3::Vec3;
#[derive(Copy, Clone)]
pub struct Ray {
pub origin: Vec3,
pub direction: Vec3
}
impl Ray {
pub fn new() -> Ray {
Ray {origin: Vec3::new(), direction: Vec3::new()}
}
pub fn new_filled(o: Vec3, d: Vec3) -> Ray {
Ray {origin: o, direction: d}
}
pub fn ... |
use serde::{Deserialize, Serialize};
#[derive(Serialize, Deserialize, Debug, PartialEq)]
pub struct TitleAssetFormat {
len: u32,
ext: Option<TitleAssetFormatExt>,
}
#[derive(Serialize, Deserialize, Debug, PartialEq)]
pub struct TitleAssetFormatExt {}
|
use proconio::{fastout, input};
#[fastout]
fn main() {
input! {
k: u32,
s: String,
}
println!(
"{}",
if s.len() <= k as usize {
s
} else {
s.as_str()[..k as usize].to_string() + "..."
}
)
}
|
//! Abstractions for standard return codes.
use sqlstate_macros::state;
use crate::Category;
pub mod class;
use self::class::*;
/// A representation for a standard `SQLSTATE` code.
#[state(standard)]
#[derive(Clone, Eq, PartialEq, Hash, Debug)]
#[non_exhaustive]
pub enum SqlState {
#[class("00")]
Success(O... |
use std::fs;
struct Segment {
x1: i32,
y1: i32,
x2: i32,
y2: i32,
steps: i32,
}
struct Intersection {
x: i32,
y: i32,
steps: i32,
}
impl Segment {
/// Normalize a segment so it always points right or down.
fn normalize(&self) -> Segment {
Segment {
x1: i32:... |
use failure;
use failure::ResultExt;
use stderrlog;
use utils::types;
///This sets up logging, and takes the output from the commandline
///options
pub fn configure_logger(config: &types::Settings) -> Result<(), failure::Error> {
let mut logger = stderrlog::new();
logger
.quiet(config.quiet)
.... |
pub trait Codec<Input = u8> {
type Output: Iterator<Item = u8>;
fn accept(&mut self, input: Input) -> Self::Output;
fn finish(self) -> Self::Output;
}
#[derive(Debug)]
pub struct BitDiscard {
buf: u16, // Use the higher byte for storing the leftovers
buf_bits: u8, // How many bits are vali... |
#[doc = "Register `RFDCR` reader"]
pub type R = crate::R<RFDCR_SPEC>;
#[doc = "Register `RFDCR` writer"]
pub type W = crate::W<RFDCR_SPEC>;
#[doc = "Field `RFTBSEL` reader - radio debug test bus selection"]
pub type RFTBSEL_R = crate::BitReader<RFTBSEL_A>;
#[doc = "radio debug test bus selection\n\nValue on reset: 0"]
... |
use crate::{
neighbour::{nlas::NeighbourNla, NeighbourBuffer, NeighbourHeader},
traits::{Emitable, Parseable},
DecodeError,
};
#[derive(Debug, PartialEq, Eq, Clone)]
pub struct NeighbourMessage {
pub header: NeighbourHeader,
pub nlas: Vec<NeighbourNla>,
}
impl Emitable for NeighbourMessage {
f... |
fn bottles(n: i32) -> String {
match n {
1 => "1 bottle of beer".to_string(),
0 => "no more bottles of beer".to_string(),
-1 => "99 bottles of beer".to_string(),
_ => n.to_string() + " bottles of beer",
}
}
fn first_phrase(n: i32) -> String {
match n {
1 => "1 bottle... |
use std::fmt;
use std::borrow::Cow;
use response::{Backup, Image, Kernel, NamedResponse, Networks, Region, Size};
// Have to duplicate Droplet because of lack of negative trait bounds
#[derive(Deserialize, Debug)]
pub struct DropletNeighbor {
pub id: f64,
pub name: String,
pub memory: f64,
pub vcpus: ... |
use anyhow::{bail, Context, Result};
use std::ffi::OsStr;
use std::path::Path;
use std::process::Command;
static MISSING_PATCHELF_ERROR: &str = "Failed to execute 'patchelf', did you install it? Hint: Try `pip install maturin[patchelf]` (or just `pip install patchelf`)";
/// Verify patchelf version
pub fn verify_patc... |
use std::fs;
use std::env;
use std::io::{self, Write};
use std::process::{Command, Stdio};
const CARGONAUTS_GIT: &str = "https://github.com/cargonauts-rs/cargonauts";
const CARGONAUTS_BRANCH: &str = "0.2-release";
const DIRS: &[(&str, Option<&str>)] = &[
("bin", None),
("assets", None),
("clie... |
pub struct Solution {}
use std::cmp::Ordering;
impl Solution {
// O(log(n)) time | O(1) space
pub fun search(nums: Vec<i32>, target: i32) -> i32 {
let mut low = 0i32;
let mut high = (nums.len() as i32) - 1;
while low <= high {
let mid = low + (hi - low) / 2;
ma... |
use rustimate_core::util::NotificationLevel;
macro_rules! debug {
($($t:tt)*) => (crate::js::log(&format_args!($($t)*).to_string().replacen("", "%c [debug] ", 1), "color: #999;"))
}
macro_rules! info {
($($t:tt)*) => (crate::js::log(&format_args!($($t)*).to_string().replacen("", "%c [info] ", 1), "color: #003049;... |
#![macro_use]
use std::sync::{Arc, Mutex, MutexGuard};
use std::ops::CoerceUnsized;
use std::marker::Unsize;
pub struct Ctx<T: ?Sized> {
content: Arc<Mutex<T>>
}
impl<T: ?Sized + Unsize<U>, U: ?Sized> CoerceUnsized<Ctx<U>> for Ctx<T> {}
impl<T: ?Sized> Clone for Ctx<T> {
fn clone(&self) -> Self {
C... |
use assert_cmd::prelude::*;
use predicates::prelude::*;
use std::io::{self, Write};
use std::process::Command;
use tempfile::NamedTempFile;
macro_rules! cli_test_success {
($($name:ident: $value:expr,)*) => {
$(
#[test]
fn $name() -> Result<(), Box<dyn std::error::Error>> {
... |
use std::convert::{TryFrom, TryInto};
use proc_macro2::Span;
use syn::{spanned::Spanned, Error, ExprField, Result};
use crate::glsl::Glsl;
use super::YaslExprLineScope;
#[derive(Debug)]
pub struct YaslExprField {
base: Box<YaslExprLineScope>,
member: syn::Ident,
}
impl YaslExprField {
pub fn span(&self)... |
#[doc = "Register `DDRPHYC_DTPR1` reader"]
pub type R = crate::R<DDRPHYC_DTPR1_SPEC>;
#[doc = "Register `DDRPHYC_DTPR1` writer"]
pub type W = crate::W<DDRPHYC_DTPR1_SPEC>;
#[doc = "Field `TAOND` reader - TAOND"]
pub type TAOND_R = crate::FieldReader;
#[doc = "Field `TAOND` writer - TAOND"]
pub type TAOND_W<'a, REG, con... |
fn main() {
println!("Hello world");
let immutable_variable = 12;
let imut_var_with_type: i32 = 12;
let mut mutable_variable = 12;
let my_bool = true;
let my_char = 'b';
println!("Print a variable: {}, like this", my_bool);
let (var_1, var_2) = ("my_var1", 12);
println!(
"P... |
#[derive(Debug, Clone, Copy)]
pub struct DebugSettings {
pub(crate) view_info: bool,
pub(crate) cursor_info: bool,
pub(crate) egui_inspection: bool,
pub(crate) egui_settings: bool,
pub(crate) egui_memory: bool,
}
impl std::default::Default for DebugSettings {
fn default() -> Self {
Sel... |
use azure_storage::core::prelude::*;
use azure_storage::table::prelude::*;
use futures::stream::StreamExt;
use serde::{Deserialize, Serialize};
use std::error::Error;
#[derive(Debug, Clone, Serialize, Deserialize)]
struct MyEntity {
#[serde(rename = "PartitionKey")]
pub city: String,
pub name: String,
... |
use std::collections::HashMap;
pub struct SymbolTable {
class_table: HashMap<String, JackVariable>,
subroutine_table: HashMap<String, JackVariable>,
static_idx: usize,
field_idx: usize,
arg_idx: usize,
var_idx: usize,
}
impl SymbolTable {
pub fn new() -> Self {
SymbolTable {
... |
use super::congestion::CongestionController;
use super::crypto::{
fulfillment_to_condition, generate_condition, generate_fulfillment, random_condition,
random_u32,
};
use super::data_money_stream::DataMoneyStream;
use super::packet::*;
use super::StreamPacket;
use bytes::{Bytes, BytesMut};
use chrono::{Duration... |
#[derive(Serialize, Deserialize, Debug, Default)]
pub struct Chat {
pub id: u64,
}
|
// use failure::Context;
// use failure::Fail;
pub use failure::ResultExt; // For .context()
pub use lazy_static::*;
pub use log::*;
pub use serde_derive::*;
pub use std::collections::{HashMap, HashSet, VecDeque};
pub use std::path::Path;
pub use std::path::PathBuf;
pub use std::rc::Rc;
pub type Result<T> = std::resul... |
use std::io::prelude::*;
use std::fs::File;
use std::collections::HashMap;
use std::process::Command;
use {Result, Error};
pub use self::gpio::{
Pin,
PinInput,
PinOutput,
};
pub use self::fs::{
Selector,
GPIOSelector,
GPIOPinSelector
};
mod gpio;
mod fs;
#[derive(Copy, Clone, Debug)]
pub enu... |
use std::cmp::{Eq, PartialEq};
use std::collections::{BTreeMap, HashMap, HashSet};
use std::convert::Into;
use std::fmt;
use std::fs::File;
use std::hash::{Hash, Hasher};
use std::io::{Read, Write};
use std::iter::{IntoIterator, Iterator};
use std::path;
use crate::message::Field;
use crate::quickfix_errors::*;
use ch... |
use http;
use net;
use http::response::Response;
use std::net::TcpStream;
use std::io::{Write, Read};
use std::io::ErrorKind::WouldBlock;
use std::collections::HashMap;
use std::fmt;
pub struct Request
{
pub version: http::Version,
pub method: http::Method,
pub url: net::url::URL,
p... |
#[doc = "Register `MPCBB2_VCTR51` reader"]
pub type R = crate::R<MPCBB2_VCTR51_SPEC>;
#[doc = "Register `MPCBB2_VCTR51` writer"]
pub type W = crate::W<MPCBB2_VCTR51_SPEC>;
#[doc = "Field `B1632` reader - B1632"]
pub type B1632_R = crate::BitReader;
#[doc = "Field `B1632` writer - B1632"]
pub type B1632_W<'a, REG, const... |
//! A logging implementation that blocks when writing data
//!
//! The logger is simple to set up, and it will accept as much data as you'd like to write. To log data,
//!
//! 1. Configure a UART peripheral with baud rates, parities, inversions, etc.
//! 2. Call [`init`](fn.init.html) with the UART transfer half, and a... |
use std::cmp::min;
/// Solves the Day 07 Part 1 puzzle with respect to the given input.
pub fn part_1(input: String) {
let mut crabs: Vec<i32> = input.split(",").map(str_to_int).collect();
crabs.sort();
let mut best = 0;
for crab in &crabs {
best += crab - crabs[0];
}
// Use a sweepin... |
use std::ops::Bound;
use std::borrow::Cow;
use std::{marker, mem, ptr};
use std::ops::RangeBounds;
use crate::*;
use crate::mdb::error::mdb_result;
use crate::mdb::ffi;
use crate::types::DecodeIgnore;
/// A typed database that accepts only the types it was created with.
///
/// # Example: Iterate over databases entri... |
use fltk::{enums::*, prelude::*, *};
use std::cell::RefCell;
use std::ops::{Deref, DerefMut};
use std::rc::Rc;
#[derive(Debug, Clone)]
pub struct MyDial {
main_wid: group::Group,
value: Rc<RefCell<i32>>,
value_frame: frame::Frame,
}
impl MyDial {
pub fn new(x: i32, y: i32, w: i32, h: i32, label: &'sta... |
mod camera;
mod hitable;
mod hitable_list;
mod material;
mod ray;
mod sphere;
mod vec3;
use camera::Camera;
use hitable::Hitable;
use material::{Dielectric, Lambertian, Metal};
use rand;
use ray::Ray;
use sphere::Sphere;
use std::io::{self, Write};
use vec3::Vec3;
fn color(ray: Ray, world: &dyn Hitable, depth: i32) -... |
use testutil::*;
use seven_client::sms::{Sms, SmsTextParams, SmsJsonParams};
use seven_client::status::{Status, StatusParams};
mod testutil;
fn init_client() -> Status {
Status::new(get_client())
}
#[test]
fn text() {
assert!(init_client().text(StatusParams {
msg_id: 77136739797,
}).is_ok());
}
|
use std::{slice, iter, cmp, ops, fmt, collections::BTreeSet};
use bit_vec::BitVec;
use crate::{
Polarity, DotId, Port, Link, LinkId, ContextHandle, Contextual, ExclusivelyContextual,
InContextMut, Atomic, AcesError, AcesErrorKind, sat,
};
// FIXME sort rows as a way to fix Eq and, perhaps, to open some
// opti... |
/*
chapter 4
syntax and semantics
*/
fn main() {
let a = 1;
let b = 'c';
match a {
b => println!("a: {} b: {}", a, b),
}
match b {
a => println!("a: {} b: {}", a, b),
}
println!("a: {}", a);
println!("b: {}", b);
}
// output should be:
/*
*/
|
use crate::parse::{
Chunk, ChunkIter, Chunks, Expr, ExprApplication, ExprBinary, ExprNot, ExprValue, Fancy,
GenericArg, PathComponent, ValueBit, ValuePath, ValueUnsigned,
};
pub struct Translator<Output: std::io::Write> {
output: Output,
}
impl<Output: std::io::Write> Translator<Output> {
pub fn new(o... |
/// This tests are ignored by default. Run them manually to check for possible differences between
/// local fixtures and actual public REST API returns. All methods/live_test calls MUST pass.
/// Run manually with: `$>cargo test --features network_test`
use arkecosystem_client::Connection;
use rand::seq::SliceRandom;
... |
#![no_std]
#![feature(start)]
#![no_main]
extern crate alloc;
use ferr_os_librust::syscall;
use ferr_os_librust::io;
use alloc::string::String;
#[no_mangle]
pub extern "C" fn _start(heap_address: u64, heap_size: u64) {
unsafe {
syscall::debug(1, 0);
syscall::set_screen_size(19, 79);
sys... |
impl Solution {
pub fn build_array(nums: Vec<i32>) -> Vec<i32> {
let ans = nums.iter().map(|&x| nums[x as usize]).collect();
return ans
}
} |
//! The *httptypes* crate is a collection of useful abstractions for
//! building HTTP clients and servers.
//!
//! It contains types for
//!
//! * [request method](enum.Method.html),
//! * [response status](struct.Status.html),
//! * [header fields](header/index.html) and
//! * the [protocol version](enum.Version.html... |
use crate::{cmd::*, result::Result};
mod add;
mod assert;
mod list;
mod transfer;
#[derive(Debug, StructOpt)]
/// Display list of hotspots associated with wallet
/// or transfer a hotspot to another wallet
pub enum Cmd {
Add(add::Cmd),
Assert(assert::Cmd),
List(list::Cmd),
Transfer(Box<transfer::Cmd>)... |
use log::{error, info, trace, warn};
mod config;
mod server;
mod stackvec;
mod tracker;
mod webserver;
use config::Configuration;
use std::process::exit;
fn setup_logging(cfg: &Configuration) {
let log_level = match cfg.get_log_level() {
None => log::LevelFilter::Info,
Some(level) => {
... |
pub mod d1;
pub mod d2;
pub mod d3;
pub mod d4;
pub mod d6;
pub mod d7;
pub mod d8;
pub mod d10;
|
use std::error::Error;
use std::cmp::Ordering;
#[derive(Copy, Clone, Eq)]
pub struct Version {
versionBytes:[u8;4],
versionHash:u32,
}
impl Version {
pub fn parse( string:&String ) -> Result< Version, String >{
let mut v=[0u32;4];
let mut c=0;
for ns in string.split('.'){
... |
#![feature(proc_macro_hygiene)]
#![feature(exclusive_range_pattern)]
#![feature(option_result_contains)]
#![warn(anonymous_parameters)]
#![warn(bare_trait_objects)]
#![warn(elided_lifetimes_in_paths)]
#![warn(missing_debug_implementations)]
#![warn(single_use_lifetimes)]
#![warn(trivial_casts)]
#![warn(unreachable_pub)... |
use std::collections::HashSet;
use std::default::Default;
use std::path::{Path, PathBuf};
use array_tool::vec::Uniq;
use diesel::connection::Connection;
use diesel::sqlite::SqliteConnection;
use if_let_return::if_let_some;
use indexmap::indexset;
use lazy_init::Lazy;
use regex::Regex;
use serde_derive::{Serialize, De... |
use capstone_rust::capstone;
use capstone_rust::capstone::{cs_x86_op};
use capstone_rust::capstone_sys::{x86_op_type, x86_reg};
use error::*;
use il::*;
use il::Expression as Expr;
const MEM_SIZE: u64 = (1 << 48);
/// Struct for dealing with x86 registers
pub struct X86Register {
name: &'static str,
// The ... |
#[doc = "Register `DCMI_CR` reader"]
pub type R = crate::R<DCMI_CR_SPEC>;
#[doc = "Register `DCMI_CR` writer"]
pub type W = crate::W<DCMI_CR_SPEC>;
#[doc = "Field `CAPTURE` reader - CAPTURE"]
pub type CAPTURE_R = crate::BitReader;
#[doc = "Field `CAPTURE` writer - CAPTURE"]
pub type CAPTURE_W<'a, REG, const O: u8> = cr... |
use base64;
use hex;
use std::ops::BitXor;
// Fixed XOR
#[derive(Debug, PartialEq)]
struct BytesXOR(Vec<u8>);
impl BitXor for BytesXOR {
type Output = Self;
fn bitxor(self, BytesXOR(rhs): Self) -> Self {
let BytesXOR(lhs) = self;
assert_eq!(lhs.len(), rhs.len());
BytesXOR(lhs.iter().z... |
use std::{i8, i16, i32, i64, u8, u16, u32, u64, isize, usize, f32, f64};
use std::io::stdin;
fn main() {
println!("Hello World");
let num = 10;
let mut age: i32 = 40;
println!("Max i8 {}", i8::MAX);
println!("Min i8 {}", i8::MIN);
println!("Max i16 {}", i16::MAX);
println!("Min i16 {}",... |
// generated protobuf files will be included here. See build.rs for details
include!(env!("PROTO_MOD_RS"));
|
//! Some random linked list traits, may or may not be used in actual program.
mod implementation;
#[cfg(test)]
mod test;
/// An implicitly linked list, allowing freestanding items and multiple links
/// inside itself.
pub trait ImplicitLinkedList<Key>
where
Key: Copy + Eq,
{
type Item: ImplicitLinkedListItem<... |
// Copyright (c) The diem-devtools Contributors
// SPDX-License-Identifier: MIT OR Apache-2.0
//! Support for partitioning test runs across several machines.
//!
//! At the moment this only supports a simple hash-based sharding. In the future it could potentially
//! be made smarter: e.g. using data to pick different ... |
use std::io::{Write, Result};
use pulldown_cmark::{Event, Tag};
use crate::gen::Document;
mod preamble;
#[derive(Debug)]
pub struct Article;
impl<'a> Document<'a> for Article {
type Simple = super::SimpleGen;
type Paragraph = super::Paragraph;
type Rule = super::Rule;
type Header = super::Header;
... |
use crate::vec::Vec3;
use num::Float;
use num_traits::NumAssign;
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct Particle<T: Float> {
pub position: Vec3<T>,
pub velocity: Vec3<T>,
pub acceleration: Vec3<T>,
pub damping: T,
/// We store the inverse mass because it makes infinite mass possible an... |
use std::cmp::max;
impl Solution {
pub fn rob(nums: Vec<i32>) -> i32 {
let n = nums.len();
if n == 0{
return 0;
}
if n == 1{
return nums[0];
}
robRange(&nums,0,n-2).max(robRange(&nums,1,n-1))
}
}
fn robRange(nums:&[i32],start:usize,end:us... |
extern crate actix;
extern crate actix_web;
extern crate openssl;
#[macro_use] extern crate lazy_static;
#[macro_use] extern crate serde_derive;
mod crypto;
use actix_web::{server, App, Json, HttpRequest, http, Error};
use actix_web::error::{ ErrorBadRequest, ErrorInternalServerError};
use crypto::{CryptoService, RSA... |
use std::collections::HashSet;
use crate::util::lines_from_file;
pub fn day17() {
println!("== Day 17 ==");
let input = lines_from_file("src/day17/input.txt");
let a = part_a(&input);
println!("Part A: {}", a);
let b = part_b(&input);
println!("Part B: {}", b);
}
fn part_a(input: &Vec<String>... |
//! Convert parser model to rust-protobuf model
use std::iter;
use crate::model;
use crate::str_lit::StrLitDecodeError;
use protobuf::Message;
#[derive(Debug)]
pub enum ConvertError {
UnsupportedOption(String),
ExtensionNotFound(String),
WrongExtensionType(String, &'static str),
UnsupportedExtension... |
#![feature(nll)]
#![cfg_attr(feature = "cargo-clippy", allow(print_literal))]
extern crate actix;
extern crate byteorder;
extern crate bytes;
extern crate futures;
extern crate rand;
extern crate serde_json;
#[macro_use]
extern crate serde_derive;
extern crate serde;
extern crate tokio;
extern crate tokio_codec;
exter... |
extern crate mirage;
use mirage::convert::svg;
use mirage::raster::{
Image,
PixelType
};
static SVG: &str = include_str!("rect.svg");
fn main()
{
let surface = svg::into::string(SVG).unwrap();
let mut image = Image::new("pic.png", 100, 100, PixelType::Rgb);
image.write(&surface);
image.save()... |
#![doc = "generated by AutoRust 0.1.0"]
#![allow(non_camel_case_types)]
#![allow(unused_imports)]
use serde::{Deserialize, Serialize};
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct LocalizableString {
pub value: String,
#[serde(rename = "localizedValue", default, skip_serializing_if = "O... |
#[derive(Copy, Clone, Ord, PartialOrd, Eq, PartialEq, Debug)]
pub enum Opcode {
IConst,
FConst,
Move,
Load,
Store,
Call(CallConv, u32),
AddOvfUI,
SubOvfUI,
MulOVfUI,
AddOvfI,
SubOvfI,
MulOvfI,
AddUI,
AddI,
SubUI,
SubI,
DivUI,
DivI,
MulUI,
M... |
#[doc = "Reader of register INTR"]
pub type R = crate::R<u32, super::INTR>;
#[doc = "Writer for register INTR"]
pub type W = crate::W<u32, super::INTR>;
#[doc = "Register INTR `reset()`'s with value 0"]
impl crate::ResetValue for super::INTR {
type Type = u32;
#[inline(always)]
fn reset_value() -> Self::Typ... |
#![deny(missing_debug_implementations)]
//! apllodb's storage engine interface.
//!
//! # Installation
//!
//! ```toml
//! [dependencies]
//! apllodb-storage-engine-interface = "0.1"
//! ```
//!
//! # Boundary of Responsibility with Storage Engine
//!
//! A storage engine is an implementation of this interface crate.
... |
// ===============================================================================
// Authors: AFRL/RQQA
// Organization: Air Force Research Laboratory, Aerospace Systems Directorate, Power and Control Division
//
// Copyright (c) 2017 Government of the United State of America, as represented by
// the Secretary of th... |
use crate::color::Color;
use crate::texture::{solidcolor::SolidColor, Texture, TextureColor};
use crate::vec::Vec3;
// CheckerTexture
#[derive(Debug, Clone)]
pub struct CheckerTexture {
pub odd: Box<Texture>,
pub even: Box<Texture>,
}
impl CheckerTexture {
pub fn new(c1: Color, c2: Color) -> Texture {
... |
use std::{fs, io};
use std::sync::{Arc, Mutex, atomic::{AtomicBool, Ordering}, Condvar};
use std::collections::{HashMap, HashSet, hash_map::{Entry, DefaultHasher}};
use std::hash::{Hash, Hasher};
use std::result;
use std::thread::{ThreadId, self};
use std::time::Instant;
use futures::{FutureExt, future::BoxFuture};
use... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.