text stringlengths 8 4.13M |
|---|
use crate::*;
use std::fmt::Display;
use secret_integers::*;
pub fn fill<F, B : Default + Clone>(len:usize, f: F) -> Vec<B> where F: Fn(usize) -> B {
let mut a = Vec::with_capacity(len);
a.resize(len, Default::default());
for i in 0..a.len() {
a[i] = f(i);
};
a
}
pub fn classify_u8s(v: &[u... |
use crate::{
file::{
cache::FileCache,
conditional_request::{format_systemtime, is_fresh, is_precondition_failed},
etag::{EntityTag, SystemTimeExt},
range::Range,
range_requests::{extract_range, is_range_fresh, is_satisfiable_range},
Compression,
},
prelude::*... |
use serde::Deserialize;
#[derive(Deserialize, PartialEq, Eq, Debug, Copy, Clone)]
pub struct Point {
pub x: i32,
pub y: i32,
}
impl Point {
pub fn new(x: i32, y: i32) -> Point {
Point { x, y }
}
}
#[derive(Deserialize, PartialEq, Eq, Debug)]
pub struct Turn {
pub game: Game,
pub turn: u32,
pub boar... |
// 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.
//
// A test that uses a loop counter incremented via a for-in.
#![feature(type_alias_enum_variants)]
#![allow(non_snake_case)]
#![allow(... |
fn main() {
let vec: Vec<i32> = (0..100).filter(|x| x % 3 == 0 && x % 7 == 0).collect();
let sum: i32 = (0..100).filter(|x| x % 3 == 0 && x % 7 == 0).sum();
println!("{}", sum);
for i in &vec {
println!("{}", i);
}
}
|
//! RON logs
use super::load_ron;
use crate::{
models::{Blog, Photo, PhotoPath, Post, TagPhotos},
tools::write_result,
};
use chrono::{DateTime, FixedOffset, Local};
use ron::ser::{to_string_pretty, PrettyConfig};
use serde::{Deserialize, Serialize};
use std::{collections::BTreeMap, path::Path};
/// File that... |
use indicatif;
use uvm_cli;
use log::*;
use self::error::{Error, Result};
use console::{style, Term};
use indicatif::{ProgressDrawTarget, ProgressStyle};
use std::collections::HashSet;
use std::fs;
use std::io;
use std::path::{Path, PathBuf};
use std::sync::{Arc, Condvar, Mutex};
use std::thread;
use uvm_cli::options::... |
use std::collections::HashMap;
pub fn run() {
let input = include_str!("input.txt");
let mut game = Game::from(input);
for _ in 0..6 {
game.next3d();
}
println!("Day17 - Part 1: {}", game.board.len());
let mut game = Game::from(input);
for _ in 0..6 {
game.next4d();... |
mod filereader;
use std::process;
use filereader::*;
fn main() {
let mut filer = FileReader::new(&"words.txt");
if let Err(_) = filer.get_words_from_file() {
process::exit(1);
}
println!("length: {}", filer.words.len());
filer.extract_clean_words();
for w in filer.clean_words.borrow... |
use crate::contract::{handle, init, query};
use crate::mock_querier::{mock_dependencies, WasmMockQuerier};
use crate::state::{pool_info_read, pool_info_store};
use cosmwasm_std::testing::{mock_env, MockApi, MockStorage};
use cosmwasm_std::{
from_binary, to_binary, Api, Coin, CosmosMsg, Decimal, Extern, HumanAddr, U... |
use super::exit_result::ExitResult;
use crate::{
commands::{
rd_options::{RdOptions, RdSubCommand},
RdCommand,
},
trace::{
trace_reader::TraceReader,
trace_task_event::{TraceTaskEvent, TraceTaskEventVariant},
},
wait_status::WaitType,
};
use libc::pid_t;
use std::{
... |
use anyhow::Result;
use clap::ArgMatches;
use prettytable::format;
use prettytable::Attr;
use prettytable::{Cell, Row, Table};
use crate::cli::cfg::get_cfg;
use crate::cli::selected_envs::selected_envs;
use crate::cli::settings::get_settings;
use crate::env_file::Env;
use crate::utils::colorize::is_cli_colorized;
us... |
use std::io;
use std::net::{self, Ipv4Addr, Ipv6Addr, SocketAddr, ToSocketAddrs};
#[cfg(feature = "io_timeout")]
use std::time::Duration;
use crate::io as io_impl;
use crate::io::net as net_impl;
#[cfg(feature = "io_timeout")]
use crate::sync::atomic_dur::AtomicDuration;
use crate::yield_now::yield_with_io;
#[derive(... |
extern crate rust2018;
use rust2018::do_thing;
fn main() {
do_thing();
}
|
use crate::{
environment::Environment, evaluator::Evaluator, lexer::Lexer,
parser::Parser,
};
use std::{io, rc::Rc};
const PROMPT: &'static str = ">> ";
pub fn start<R: io::BufRead, W: io::Write>(
mut reader: R,
mut writer: W,
) -> io::Result<()> {
let env = Environment::new();
loop {
... |
use tokio::sync::{mpsc, oneshot};
use super::Connection;
use crate::{
error::{Error, Result},
runtime::{AsyncJoinHandle, WorkerHandle},
};
/// Returns a new requester/receiver pair.
pub(super) fn channel(handle: WorkerHandle) -> (ConnectionRequester, ConnectionRequestReceiver) {
let (sender, receiver) = m... |
use crate::heroes;
use crate::db::Conn;
use crate::errors::Error;
use heroes::Hero;
use bson::{ doc, oid::ObjectId };
use rocket_contrib::json::Json;
use rocket::{http::Status};
fn error_status(error: Error) -> Status {
match error {
Error::CursorNotFoundError => Status::NotFound,
_ => Status::InternalServer... |
use nu_engine::CallExt;
use nu_parser::parse_duration_bytes;
use nu_protocol::{
ast::{Call, CellPath, Expr},
engine::{Command, EngineState, Stack},
Category, Example, PipelineData, ShellError, Signature, Span, Spanned, SyntaxShape, Unit,
Value,
};
#[derive(Clone)]
pub struct SubCommand;
impl Command f... |
use anyhow::{anyhow, Context, Result};
use chrono::{DateTime, Utc};
use clap::{App, Arg};
use serde::Deserialize;
use std::fs::{self, File};
use std::io::{self, Read};
use std::path::Path;
use std::process::Command;
use std::time::SystemTime;
#[derive(Debug)]
struct Options {
dry_run: bool,
force: bool,
fi... |
//! Reads psf (console) fonts. Exposes very simple interface for displaying
//! the glyphs.
//!
//! Exposing of the glyph data is simple and easy to use:
//! ```
//! use psf::Font;
//!
//! let the_font = Font::new("<path>");
//! if let Ok(font) = the_font {
//! let c = font.get_char('X');
//! if let Some(c) = c... |
//! Build mouse events.
mod button;
mod event;
pub mod click;
pub use button::Button;
pub use click::Click;
pub use event::{Event, ScrollDelta};
|
#[doc = "Reader of register SYSCFG_ICNR"]
pub type R = crate::R<u32, super::SYSCFG_ICNR>;
#[doc = "Writer for register SYSCFG_ICNR"]
pub type W = crate::W<u32, super::SYSCFG_ICNR>;
#[doc = "Register SYSCFG_ICNR `reset()`'s with value 0"]
impl crate::ResetValue for super::SYSCFG_ICNR {
type Type = u32;
#[inline(... |
use heapless::{ArrayLength, Vec};
pub trait SliceExt {
fn trim(&self, whitespaces: &[u8]) -> &Self;
fn trim_start(&self, whitespaces: &[u8]) -> &Self;
}
impl SliceExt for [u8] {
fn trim(&self, whitespaces: &[u8]) -> &[u8] {
let is_not_whitespace = |c| !whitespaces.contains(c);
if let Some... |
// opcode.rs ---
//
// Filename: opcode.rs
// Author: Jules <archjules>
// Created: Thu Mar 30 23:13:15 2017 (+0200)
// Last-Updated: Fri Mar 31 17:01:27 2017 (+0200)
// By: Jules <archjules>
//
use machine::Machine;
#[derive(Debug)]
pub enum Operand {
Large(u16),
Small(u8),
Variable(usize)
}
... |
extern crate rand;
use std::fmt;
use rand::StdRng;
use std::cmp::Ordering;
use std::cmp::Ordering::{Less, Equal, Greater};
pub struct Platform {
pub print_xy: fn(i32, i32, &str),
pub clear: fn(Option<Rect>),
pub size: fn() -> Size,
pub pick: fn(Point, i32) -> char,
pub mouse_position: fn() -> Poi... |
#[derive(Debug, PartialEq)]
pub struct Position {
pub x: u16,
pub y: u16
} |
#![recursion_limit = "128"]
use argh::FromArgs;
use std::{fs::File, io::prelude::*};
#[derive(FromArgs)]
/// Veloci Index Creator
struct Opt {
/// sets the input data file to use
#[argh(option, short = 'd')]
data: String,
/// sets target folder, will be deleted first if it exist
#[argh(option, sh... |
use std::time::Instant;
pub struct PerfLog {
start: Instant,
}
impl PerfLog {
pub fn new() -> Self {
Self {
start: Instant::now(),
}
}
pub fn log(self, name: &str) {
let diff = self.start.elapsed();
log::debug!("perf: {} {}ms", name, diff.as_micros() as f64... |
use crate::BaseCommand;
use r_common::{CommandArgs, ShellAction, ShellError};
use r_context::context::Context;
pub struct Exit {}
impl BaseCommand for Exit {
fn name(&self) -> &str {
"exit"
}
fn run(&self, _: Context, _: CommandArgs) -> Result<Vec<ShellAction>, ShellError> {
let mut res ... |
#[doc = "Reader of register HOST_FCOMP"]
pub type R = crate::R<u32, super::HOST_FCOMP>;
#[doc = "Writer for register HOST_FCOMP"]
pub type W = crate::W<u32, super::HOST_FCOMP>;
#[doc = "Register HOST_FCOMP `reset()`'s with value 0"]
impl crate::ResetValue for super::HOST_FCOMP {
type Type = u32;
#[inline(always... |
use monkey_rs::repl;
use std::io;
fn main() -> io::Result<()> {
println!("Welcome to the Monkey REPL!");
let input = io::stdin();
let output = io::stdout();
let result = repl::start(input.lock(), output.lock());
result
}
|
use ndarray::{arr1, arr2, Array1, Array2};
pub struct CameraMatrix {
x_axis_rotation: f32,
z_axis_rotation: f32,
movement: [f32; 3],
field_of_view: f32,
near: f32,
far: f32,
is_2d_mode: bool,
}
impl CameraMatrix {
pub fn new() -> Self {
Self {
x_axis_rotation: 0.25 ... |
use crate::test_utils::*;
use std::net::TcpStream;
use vndb_rs::{common::error::VndbError, sync::client::Client};
#[test]
fn parse_error() {
let mut buf = b"error ".to_vec();
let expected = VndbError::Parse {
msg: "Invalid command or argument".to_owned(),
};
buf.extend(serde_json::to_vec(&expec... |
use bc::block::*;
use bc::BlockChain;
macro_rules! define_tests {
($bc:ident) => {
#[test]
fn __new() {
new::<$bc>();
}
#[test]
fn __create_block() {
create_block::<$bc>();
}
#[test]
fn __push_block() {
push_block... |
use std::io;
use std::str::FromStr;
use std::cmp::Ordering;
use rand::Rng;
use std::result::Result;
fn read_guess() -> Result<u32, <u32 as FromStr>::Err> {
println!("Input your guess:");
let mut guess = String::new();
io::stdin().read_line(&mut guess).expect("Failed to read line");
guess.trim().parse... |
#![no_main]
#![no_std]
extern crate alloc;
use alloc::{collections::BTreeMap, string::String, vec::Vec};
use contract::{
contract_api::{runtime, storage},
unwrap_or_revert::UnwrapOrRevert,
};
use types::{
api_error::ApiError,
contracts::{EntryPoint, EntryPointAccess, EntryPointType, EntryPoints},
... |
#[doc = "Register `HR%s` reader"]
pub type R = crate::R<HR_SPEC>;
#[doc = "Field `H` reader - H0"]
pub type H_R = crate::FieldReader<u32>;
impl R {
#[doc = "Bits 0:31 - H0"]
#[inline(always)]
pub fn h(&self) -> H_R {
H_R::new(self.bits)
}
}
#[doc = "digest registers\n\nYou can [`read`](crate::ge... |
use super::*;
use std::collections::HashMap;
pub struct Part1<T>(::std::marker::PhantomData<T>);
impl<T> Solve<T> for Part1<T>
where T: AsRef<[String]> {
type Output = u64;
fn solve(input: T) -> <Self as Solve<T>>::Output {
let (a, b): (u64, u64) = input.as_ref()
.iter()
... |
#[doc = "Reader of register STATUS"]
pub type R = crate::R<u32, super::STATUS>;
#[doc = "Reader of field `BUSY`"]
pub type BUSY_R = crate::R<bool, bool>;
impl R {
#[doc = "Bit 31 - Cache, cryptography, XIP, device interface or any other logic busy in the IP: '0': not busy '1': busy When BUSY is '0', the IP can be s... |
use crate::get_result_i64;
// https://adventofcode.com/2020/day/9
// https://www.reddit.com/r/rust/comments/k9m4ml/advent_of_code_2020_day_9/
// Array windows makes this pretty fun (is currently unstable)
const INPUT_FILENAME: &str = "inputs/input09";
pub fn solve() {
get_result_i64(1, part01, INPUT_FILENAME);
... |
#![allow(dead_code)]
#![allow(unused_imports)]
#![allow(incomplete_features)]
#![feature(generic_associated_types)]
#![feature(const_generics)]
mod manager;
mod pipeline;
use crate::manager::*;
use crate::pipeline::*;
use modules::opencv::camera_input::CameraInput;
use modules::opencv::debug_display::DebugDisplay;
us... |
// Apache License, Version 2.0
// (c) Campbell Barton, 2016
use std::ptr;
use mempool_elem::{
MemPool,
MemPoolElemUtils,
};
struct TestElem {
value: usize,
link: *mut TestElem,
is_free: bool,
}
impl MemPoolElemUtils for TestElem {
#[inline] fn default_chunk_size() -> usize {
return 0;... |
#[doc = "Register `HSEM_C2ISR` reader"]
pub type R = crate::R<HSEM_C2ISR_SPEC>;
#[doc = "Field `ISF` reader - ISF"]
pub type ISF_R = crate::FieldReader<u32>;
impl R {
#[doc = "Bits 0:31 - ISF"]
#[inline(always)]
pub fn isf(&self) -> ISF_R {
ISF_R::new(self.bits)
}
}
#[doc = "HSEM i2terrupt statu... |
use io::fasta;
use io::fastq;
use fastx_utils;
pub fn filter_fasta_n(file_path: &str) {
let reader = fasta::Reader::from_file(file_path).unwrap();
let mut writer = fasta::Writer::to_file(fastx_utils::create_new_file_path(file_path.to_string())).unwrap();
for mut result in reader.records() {
let mut... |
/*
* RIDB API Additional Functions 0.1
*
* The Recreation Information Database (RIDB) provides data resources to citizens, offering a single point of access to information about recreational opportunities nationwide. The RIDB represents an authoritative source of information and services for millions of visitors to... |
mod block_verifier;
mod contextual_block_verifier;
mod genesis_verifier;
mod header_verifier;
mod transaction_verifier;
mod two_phase_commit_verifier;
#[cfg(not(disable_faketime))]
mod uncle_verifier;
|
#![feature(no_std)]
#![no_std]
#![allow(unstable)]
#![allow(unused_imports)]
#![allow(unknown_features)]
#![allow(dead_code)]
#![feature(lang_items)]
#![feature(asm)]
#![feature(core)]
#![allow(unused_unsafe)]
#![feature(box_syntax)]
#![no_builtins]
#[macro_use]
extern crate core;
use prelude::*;
use core::fmt::Writer... |
//! Visitors for reading an abstract SQL syntax tree, generating the query and
//! gathering parameters in the right order.
//!
//! The visitor module should not know how to construct an AST, just how to read
//! one. Everything related to the tree generation is in the
//! [ast](../ast/index.html) module.
//!
//! For p... |
use boxer::array::BoxerArray;
use boxer::{ValueBox, ValueBoxPointer};
use gleam::gl::*;
use std::rc::Rc;
#[no_mangle]
pub fn gleam_gen_renderbuffers(
_ptr_gl: *mut ValueBox<Rc<dyn Gl>>,
amount: GLsizei,
_ptr_array: *mut ValueBox<BoxerArray<GLuint>>,
) {
_ptr_gl.with_not_null(|gl| {
_ptr_array.w... |
use std::fmt::{Display, Formatter};
#[derive(Debug)]
pub enum CPUFlag {
Z = 0x80,
N = 0x40,
H = 0x20,
C = 0x10
}
#[derive(Debug)]
pub struct Registers {
pub a: u8,
pub b: u8,
pub d: u8,
pub h: u8,
pub f: u8,
pub c: u8,
pub e: u8,
pub l: u8,
pub sp: u16,
pub pc: ... |
use clap::{App, Arg};
use std::collections::HashMap;
use std::convert::TryInto;
use std::error::Error;
use zbus::fdo;
mod interface;
pub const INTERFACE: &str = "com.grahamc.GuiDuck1";
pub const SERVICE: &str = "com.grahamc.guiduck";
pub const PATH: &str = "/com/grahamc/guiduck1";
fn main() -> Result<(), Box<dyn Erro... |
use tcore::reactor::Core;
///
/// Channel structure of AMQP queue.
///
pub struct Channel {
id: u16, core: Core
}
|
use crate::{
ast::{
BlockStatement, Expression, HashLiteral, Infix, Prefix, Program,
Statement,
},
lexer::Lexer,
token::Token,
};
use std::{collections::HashMap, iter::Peekable};
#[derive(PartialEq, PartialOrd)]
enum Precedence {
LOWEST = 0,
EQUALS, // ==
LESSGREATER, /... |
use drogue_cloud_service_common::reqwest::make_insecure;
/// Working with [`Any`], we need to ensure that types match, especially when updating versions.
#[tokio::test]
pub async fn test_rustls_insecure() {
let mut builder = reqwest::ClientBuilder::new();
builder = make_insecure(builder);
let _ = builder.b... |
//! ITP1_8_Bの回答
//! [https://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=ITP1_8_B](https://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=ITP1_8_B)
use std::io::BufRead;
/// ITP1_8_Bの回答
#[allow(dead_code)]
pub fn main() {
loop {
if let Some(numbers) = read_numbers(std::io::stdin().lock()) {
... |
//
// Part of Roadkill Project.
//
// Copyright 2010, 2017, Stanislav Karchebnyy <berkus@madfire.net>
//
// Distributed under the Boost Software License, Version 1.0.
// (See file LICENSE_1_0.txt or a copy at http://www.boost.org/LICENSE_1_0.txt)
//
use num::Num;
#[derive(Clone)]
pub enum LoopType {
None,
Forw... |
mod read_file {
use std::borrow::Cow;
use std::fs::File;
use std::io::Error;
use std::io::Read;
use std::path::Path;
use std::rc::Rc;
use std::result;
use std::vec;
type Result<T> = result::Result<T, Error>;
pub fn read<P: AsRef<Path>>(path: P) -> Result<()> {
let mut ... |
use std::io::BufferedReader;
// use std::io::println;
use std::io;
mod token;
mod mathparse;
mod tokenize;
fn main() {
let mut reader = BufferedReader::new(io::stdin());
loop {
let input = reader.read_line().unwrap();
// println!("Hello World!");
// println!("{}", &input);
// le... |
use crate::renderer::{MenuItem as AppMenuItem, MenuItems};
use anyhow::Result;
use std::collections::HashMap;
use wry::application::accelerator::Accelerator;
use wry::application::keyboard::{KeyCode, ModifiersState};
#[cfg(not(target_os = "windows"))]
use wry::application::menu::AboutMetadata;
use wry::application::men... |
//! wgetj command line application.
#![cfg_attr(feature="clippy", feature(plugin))]
#![cfg_attr(feature="clippy", plugin(clippy))]
#![cfg_attr(feature="clippy", deny(clippy, clippy_pedantic))]
#![deny(missing_docs)]
extern crate docopt;
extern crate libmultilog;
extern crate libwgetj;
#[macro_use]
extern crate log;
ext... |
//! Shows how to use the cache.
extern crate amethyst_assets;
extern crate futures;
extern crate rayon;
use std::str::{Utf8Error, from_utf8};
use std::sync::Arc;
use amethyst_assets::*;
use rayon::{Configuration, ThreadPool};
struct DummyContext {
cache: Cache<AssetFuture<DummyAsset>>,
prepend: &'static str... |
fn main() {
let input = include_str!("input.txt").trim();
let mut floor = 0isize;
let mut first_basement = None;
for (i, c) in input.chars().enumerate() {
match c {
'(' => floor += 1,
')' => floor -= 1,
x => panic!(format!("Unknown char {}", x)),
}
... |
use crate::channel::get_channel_stream;
use crate::config::TunnelConfig;
use crate::rmux::get_channel_session_size;
use crate::utils::{make_error, relay_buf_copy, RelayState};
use futures::future::join3;
use std::error::Error;
use std::net::Shutdown;
use std::sync::atomic::{AtomicU32, Ordering};
use std::sync::{Arc, M... |
use ansi_term::{Colour, Style};
use chrono::prelude::*;
use futures::Future;
use log::error;
use serde_derive::Deserialize;
use toml;
const BASE_URL: &str = "https://api.football-data.org/v2/competitions/";
const CONFIG: &str = include_str!("../ftbl.toml");
#[derive(Debug, Deserialize)]
pub struct ScoreRepo {
api... |
/*
Copyright 2019-2023 Didier Plaindoux
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... |
#![allow(unused_variables)]
fn main() {
unsafe {
test_unsafe_rawp();
}
}
unsafe fn test_unsafe_rawp() {
let mut num = 5;
let r1 = &num as *const i32; // const int* const r1 = #
let r2 = &mut num as *mut i32; // int* const r2 = #
*r2 += 1;
println!("r1, r2, num {}, {}, {}", ... |
pub mod assets;
pub mod player; |
#![doc = "Peripheral access API for STM32F100 microcontrollers (generated using svd2rust v0.30.0 (8dd361f 2023-08-19))\n\nYou can find an overview of the generated API [here].\n\nAPI features to be included in the [next]
svd2rust release can be generated by cloning the svd2rust [repository], checking out the above comm... |
mod common;
mod issuecomment;
mod pullrequestevent;
pub use self::issuecomment::IssueComment;
pub use self::pullrequestevent::{PullRequest, PullRequestEvent, PullRequestAction, PullRequestState};
pub use self::common::{Issue, Repository, User, Comment};
|
//! Module contains abstractions over storage operations
//!
//!
use sp_std::collections::vec_deque::VecDeque;
/// Storage operation
pub trait StorageOp {
fn exec(self);
}
/// Fifo-queue for storage operations
pub struct StorageOpsQueue<T>(VecDeque<T>);
impl<T> StorageOpsQueue<T> {
/// Add storage operation... |
use crate::ToSql;
use std::{borrow::Cow, fmt::Debug};
use storm::{BoxFuture, Result};
pub trait Execute {
fn execute_with_args<'a, S>(
&'a self,
statement: S,
params: &'a [&'a (dyn ToSql)],
args: ExecuteArgs,
) -> BoxFuture<'a, Result<u64>>
where
S: ?Sized + Debug + ... |
use super::u512;
// Addition
impl std::ops::Add<&u512> for &u512 {
type Output = u512;
fn add(self, other: &u512) -> u512 {
let mut result = u512::zero();
let mut accumulator: u128 = 0;
for i in 0..8 {
accumulator += self.data[i] as u128;
accumulator += other.... |
#![feature(alloc, oom, heap_api, optin_builtin_traits)]
// TODO
// mpsc
// mpmc
extern crate alloc;
mod spsc;
pub use spsc::bounded::{
BoundedSpscQueue,
Receiver as BoundedSpscReceiver,
Sender as BoundedSpscSender,
TrySendError as SpscTrySendError,
TryReceiveError as SpscTryReceiveError,
};
|
//
// Copyright 2018 The Project Oak 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 required by applicable law o... |
use std::io;
use std::io::BufRead;
use std::iter;
// 打印一个三角
fn main() {
let mut input = String::new();
let cin = io::stdin();
println!("Input number of rows: ");
cin.lock().read_line(&mut input).ok().expect("failed to read");
let n:usize = input.trim().parse().ok().expect("ohh");
for i in 1... |
#[doc = "Reader of register CRYP_CSGCM0R"]
pub type R = crate::R<u32, super::CRYP_CSGCM0R>;
#[doc = "Writer for register CRYP_CSGCM0R"]
pub type W = crate::W<u32, super::CRYP_CSGCM0R>;
#[doc = "Register CRYP_CSGCM0R `reset()`'s with value 0"]
impl crate::ResetValue for super::CRYP_CSGCM0R {
type Type = u32;
#[i... |
use std::sync::Arc;
use async_trait::async_trait;
use common::event::{Event, EventHandler, EventRepository};
use common::result::Result;
pub struct EventLogger {
event_repo: Arc<dyn EventRepository>,
}
impl EventLogger {
pub fn new(event_repo: Arc<dyn EventRepository>) -> Self {
println!("[DEV] Even... |
fn main() {
// let languages: Vec<String> = std::env::args().skip(1).collect();
let languages = ["lisp", "scheme", "c", "c++", "fortran"];
for l in languages.iter() {
println!("{}: {}", l, if l.len() % 2 == 0 {
"functional"
} else {
"imperative"
});
}
}
|
pub use self::package::OpenCLPackage;
mod package;
use super::super::{Extension, Package};
use super::super::extension_package::{Backward, Forward};
use ocl;
use parenchyma::error::Result;
use parenchyma::extension_package::{Dependency, ExtensionPackageCtor};
use parenchyma::frameworks::{OpenCLContext as Context, Op... |
#[cfg(test)]
mod test;
use std::time::Duration;
use super::{
description::topology::TopologyType,
monitor::DEFAULT_HEARTBEAT_FREQUENCY,
TopologyUpdater,
TopologyWatcher,
};
use crate::{
error::{Error, Result},
options::ClientOptions,
runtime,
srv::{LookupHosts, SrvResolver},
};
const ... |
use std::ptr;
use crate::error::check_status;
use crate::utils::copy_string;
use crate::TimeSpec;
/// Data about a receive operation
pub struct ReceiveMetadata {
/// Handle to C++ object
handle: uhd_sys::uhd_rx_metadata_handle,
/// Number of samples received
samples: usize,
}
impl ReceiveMetadata {
... |
pub struct Solution {}
/*
https://leetcode.com/problems/island-perimeter/
*/
impl Solution {
pub fn island_perimeter(grid: Vec<Vec<i32>>) -> i32 {
let mut perimeter = 0;
let m = grid.len();
let n = grid[0].len();
for i in 0..m {
for j in 0..n {
if grid[i... |
use crate::vulkan::{vkshader::VkShader, vkstate::VulkanState};
use ash::{version::DeviceV1_0, vk};
use std::{cell::RefCell, rc::Rc};
pub struct VkDescriptor {
pub pool_sizes: Vec<vk::DescriptorPoolSize>,
pub pool: Option<vk::DescriptorPool>,
pub set: Vec<vk::DescriptorSet>,
state: Rc<VulkanState>,
... |
/*
stdlib.rs: holds the definition of all non-special form language atoms of RLisp that are defined in
Rust language. Other modules can use core() function to get all these functions.
*/
// load needed sibling-modules
use crate::printer::{print_str_rec};
use crate::types::{error, is_atom, RlErr, RlType};
... |
/*
* Datadog API V1 Collection
*
* Collection of all Datadog Public endpoints.
*
* The version of the OpenAPI document: 1.0
* Contact: support@datadoghq.com
* Generated by: https://openapi-generator.tech
*/
/// UsageCustomReportsResponse : Response containing available custom reports.
#[derive(Clone, Debug,... |
use std::ops::Deref;
use std::rc::Rc;
use std::sync::Arc;
trait Ptr<T> {
type PT : Deref<Target=T>;
fn build(val:T) -> Self::PT;
}
#[derive(Debug)]
struct ArcP;
#[derive(Debug)]
struct RcP;
impl<T> Ptr<T> for ArcP {
type PT = Arc<T>;
fn build(val:T) -> Self::PT {
Arc::new(val)
}
}
impl<T... |
use actix_web::{
http::{ StatusCode, HeaderName, HeaderValue },
middleware::errhandlers::{ErrorHandlerResponse},
ResponseError, HttpResponse, dev, Result };
use postgres::Error;
use serde::Deserialize;
use serde_json::json;
use std::fmt;
#[derive(Debug, Deserialize)]
pub struct ApiError {
pub status_co... |
use crate::base::dimension::{Dynamic, U1, U2, U3, U4, U5, U6};
use crate::base::matrix_slice::{SliceStorage, SliceStorageMut};
use crate::base::{Const, Matrix};
/*
*
*
* Matrix slice aliases.
*
*
*/
// NOTE: we can't provide defaults for the strides because it's not supported yet by min_const_generics.
/// A col... |
use super::io::{inherit_reader, IOReader, ReaderKey};
use super::sources::HTTP;
use duktape::prelude::*;
use duktape::{
class,
error::{ErrorKind, Result, ResultExt},
Key,
};
use duktape_modules::{require, CJSContext};
use reqwest::{header::HeaderMap, header::HeaderName, Client, Method, Response, Url};
use s... |
extern crate clap;
extern crate rustyline;
use clap::{App, Arg};
use env_logger::Env;
use log::{error, info};
use serde::Deserialize;
use rustyline::error::ReadlineError;
use rustyline::Editor;
use std::env;
use std::fs;
use std::io::{Read, Write};
use std::net::{Shutdown, TcpStream};
#[derive(Deserialize, Debug)]
st... |
use crate::*;
use std::collections::{BTreeSet, HashMap, VecDeque};
use std::fmt;
use std::io::{self, Write};
// lr graph
#[derive(Debug)]
pub struct LrGraph<'a> {
rules: &'a Vec<FlatRuleDef<'a>>,
states: Vec<LrState<'a>>,
terminals: BTreeSet<&'a str>,
non_terminals: BTreeSet<&'a str>,
first_s: Term... |
use std::collections::HashMap;
use crate::solutions::Solution;
pub struct Day10 {}
impl Solution for Day10 {
fn part1(&self, input: String) {
let mut bots = Bots::new(true);
for instruction in input.split('\n').map(Instruction::new) {
bots.take_instruction(instruction);
}
... |
/* compiled on rust 0.10 on April 2014 */
use std::cmp;
use std::io::timer;
fn main() {
let n = 200;
let levels = &mut Vec::from_fn(n, |_| { 0 });
let flags = &mut Vec::from_fn(n, |_| { false });
let srd_levels = levels as *mut Vec<int>;
let srd_flags = flags as *mut Vec<bool>;
for i in range... |
use std::collections::VecDeque;
use crate::{RunTimeData, TrafficChart};
/// This function is invoked every second by the application subscription
///
/// It updates data (packets and bytes per second) to be displayed in the chart of gui run page
pub fn update_charts_data(runtime_data: &mut RunTimeData, traffic_chart:... |
use anyhow::Context;
use log::{
debug,
warn,
};
use serde::{
Deserialize,
Serialize,
};
use std::{
collections::HashMap,
default::Default,
fs::File,
net::Ipv4Addr,
path::{
Path,
PathBuf,
},
};
#[derive(Serialize, Deserialize, Debug)]
#[serde(rename_all = "camelCase")]
pub struct Config {
#[serde(default... |
use std::env;
use std::fs;
use md5;
fn has_three(s : &String) -> char
{
let mut pp = '\0';
let mut p = '\0';
for c in s.chars() {
if c == p && p == pp {
return c;
}
pp = p;
p = c;
}
return '\0';
}
fn has_five(s : &String) -> Vec<char>
{
let mut re... |
use std::sync::Arc;
use anyhow::Result;
use crossbeam_channel::Receiver;
use parking_lot::Mutex;
use serde_json::{json, Value};
use crate::stdio_server::rpc::{Call, MethodCall};
use crate::stdio_server::state::State;
use super::session::SessionManager;
#[derive(Clone)]
pub struct SessionClient {
pub state_mutex... |
#![no_std]
#![feature(allocator_api, alloc_error_handler)]
extern crate alloc;
use core::panic::PanicInfo;
mod allocator;
pub mod bindings;
pub mod c_types;
pub mod chrdev;
mod error;
pub mod file_operations;
pub mod filesystem;
pub mod printk;
#[cfg(kernel_4_13_0_or_greater)]
pub mod random;
pub mod sysctl;
mod typ... |
use std::fs::File;
use std::io::{BufRead, BufReader, Error, ErrorKind};
pub fn solve(file_name: &str) -> Result<(), Error> {
println!("-= Day 01 =-");
match get_multiple_of_two_items_which_sum_2020(file_name) {
Ok(result) => {
println!("Result of part A: {:?}", result);
}
E... |
use std::fs::read_to_string;
use std::collections::HashMap;
use regex::{Regex};
use std::iter::FromIterator;
const INPUT_FILE: &str = "data/day_16.txt";
const MFCSAM_MESSAGE: &str = r#"children: 3
cats: 7
samoyeds: 2
pomeranians: 3
akitas: 0
vizslas: 0
goldfish: 5
trees: 3
cars: 2
perfumes: 1"#;
lazy_static! {
s... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.