text stringlengths 8 4.13M |
|---|
#[doc = "Register `PDCRH` reader"]
pub type R = crate::R<PDCRH_SPEC>;
#[doc = "Register `PDCRH` writer"]
pub type W = crate::W<PDCRH_SPEC>;
#[doc = "Field `PD3` reader - pull-down"]
pub type PD3_R = crate::BitReader<PD3_A>;
#[doc = "pull-down\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum ... |
use pyo3::prelude::*;
pub fn register_module(py: Python<'_>, parent_module: &PyModule) -> PyResult<()>
{
let ufjc = PyModule::new(py, "ufjc")?;
super::lennard_jones::py::register_module(py, ufjc)?;
super::log_squared::py::register_module(py, ufjc)?;
super::morse::py::register_module(py, ufjc)?;
... |
#![allow(dead_code)]
#[derive(Debug)] enum Food { CordonBleu, Steak, Sushi }
#[derive(Debug)] enum Day { Monday, Tuesday, Wednesday }
fn have_ingredients(food: Food) -> Option<Food> {
match food {
Food::Sushi => None,
_ => Some(food),
}
}
fn have_recipe(f: Food) -> Option<Food> {
... |
#[doc = "Reader of register MPU_RASR"]
pub type R = crate::R<u32, super::MPU_RASR>;
#[doc = "Writer for register MPU_RASR"]
pub type W = crate::W<u32, super::MPU_RASR>;
#[doc = "Register MPU_RASR `reset()`'s with value 0"]
impl crate::ResetValue for super::MPU_RASR {
type Type = u32;
#[inline(always)]
fn re... |
use crate::sink_config::CompareType::{Greater, GreaterEqual, Smaller, SmallerEqual};
use dashmap::DashMap;
use rlink::utils::http::client::get;
use std::collections::HashMap;
use std::error::Error;
use tokio::time::Instant;
lazy_static! {
static ref GLOBAL_SINK_CONFIG: DashMap<String, KafkaSinkContext> = DashMap::... |
fn main() {
println!("Sum square difference");
println!("The sum of the squares of the first ten natural numbers is,
12 + 22 + ... + 102 = 385
The square of the sum of the first ten natural numbers is,
(1 + 2 + ... + 10)2 = 552 = 3025
Hence the difference between the sum of the squares of the fi... |
use io::RegEnum;
pub const IRQ_BASE: u32 = 0x10001000u32;
#[derive(Clone, Copy)]
#[allow(non_camel_case_types)]
enum Reg {
ENABLED = 0x00,
PENDING = 0x04,
}
impl RegEnum for Reg {
fn addr_of(&self) -> u32 {
IRQ_BASE + (*self as u32)
}
}
#[allow(non_snake_case)]
pub mod Interrupt {
pub co... |
pub struct Solution {}
/**
https://leetcode.com/problems/positions-of-large-groups/
**/
impl Solution {
pub fn large_group_positions(s: String) -> Vec<Vec<i32>> {
let mut result = Vec::new();
let mut start:i32 = 0;
let mut end:i32 = 0;
let mut count = 1;
let chars:Vec<_> = ... |
#![no_std]
use core::fmt::{Debug, Formatter};
use imxrt_ral as ral;
use ral::ccm;
use ral::trng;
use ral::{modify_reg, read_reg, write_reg};
use rand_core::block::{BlockRng, BlockRngCore};
use rand_core::{Error, RngCore};
// warning: written based on the SDK as I do not have access to the Security Reference Manual
... |
pub(in crate) mod draft_version;
pub(in crate) mod keyword_type;
pub(in crate) mod schema;
pub(in crate) mod schema_error;
pub(in crate) mod scope;
pub(in crate) mod scope_builder;
pub(in crate) mod validation_error;
pub(in crate) mod validator;
pub(in crate) mod validator_error_iterator;
|
use std::ops::*;
use std::convert::*;
#[allow(unused_imports)]
use std::{f32, f64};
use ::matrix::mat2x2::*;
use ::vector::vec2::*;
use ::vector::vec3::*;
#[derive(Copy, Clone)]
pub struct Mat3x3<T: Copy + Clone> {
///Array of Vector3<T> to facilitate the writing of operations
pub m: [Vector3<T>; 3],
}
#[allo... |
use {serde::Deserialize, serde_json::Value};
#[derive(Deserialize)]
pub struct TrackUpdate {
pub song: Song,
pub requester: Option<Value>,
pub event: Option<Value>,
#[serde(rename = "startTime")]
pub start_time: String,
#[serde(rename = "lastPlayed")]
pub last_played: Vec<Song>,
pub lis... |
use crate::{
canvas::{tools, Canvas},
terminal::{
event::{Event, KeyEvent},
Terminal, SIZE,
},
util::{Color, Point},
};
pub struct Operation {
pub tool: tools::Tool,
pub start: Point,
pub end: Option<Point>,
pub color: Color,
pub size: SIZE,
}
pub struct UndoRedoBuf... |
pub struct Solution {}
impl Solution {
/// Given a vector of heights, returns the maximum area.
///
/// # Arugments
/// * 'height' - A vector of i32 heights. The width of an area is the
/// difference between the height indices.
///
/// # Constraits
/// * 2 <= n.len() <= 3 * 10^4
... |
#![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 AccessControlRecord {
#[serde(flatten)]
pub base_model: BaseModel,
pub properties: AccessControlRecordP... |
use crate::field::Stage;
use crate::token::Token;
use std::ops::Range;
pub struct TaskIter<'a> {
remaining: &'a str,
tokens: std::str::SplitAsciiWhitespace<'a>,
offset: usize,
stage: Stage,
}
impl<'a> TaskIter<'a> {
pub fn new(str: &'a str) -> Self {
TaskIter {
remaining: str,
... |
use block::Block;
use util::{Align, opacity_to_hex};
pub struct Module {
blocks: Vec<Box<Block>>,
align: Option<String>,
separator: Option<String>,
background: Option<String>,
background_opacity: Option<String>,
foreground: Option<String>,
foreground_opacity: Option<String>,
}
impl Module ... |
// Copyright © 2016 Peter Atashian
// Licensed under the MIT license <LICENSE-MIT or http://opensource.org/licenses/MIT>.
// All files in the project carrying such notice may not be copied, modified, or distributed
// except according to those terms.
//! This crate provides lagomorphs.
/// Acquires and returns a bunny... |
use log::debug;
use proxy_wasm::traits::{Context, HttpContext};
use proxy_wasm::types::Action;
/// HttpContext filter
pub struct ResponseStatusHttp {}
impl ResponseStatusHttp {
pub(crate) fn new() -> Self {
Self {}
}
}
// Response related methods
impl ResponseStatusHttp {
fn status(&self) {
... |
/*!
```rudra-poc
[target]
crate = "tiny_future"
version = "0.3.2"
[report]
issue_url = "https://github.com/KizzyCode/tiny_future/issues/1"
issue_date = 2020-12-08
rustsec_url = "https://github.com/RustSec/advisory-db/pull/675"
rustsec_id = "RUSTSEC-2020-0118"
[[bugs]]
analyzer = "SendSyncVariance"
bug_class = "SendSy... |
use std::rc::Rc;
use std::collections::HashMap;
use {Value, AresError, AresResult, rc_to_usize, write_usize};
pub use super::environment::{Env, Environment};
use intern::Symbol;
#[derive(Clone, Eq, PartialEq)]
pub struct ParamBinding {
pub params: Vec<Symbol>,
pub rest: Option<Symbol>,
}
#[derive(Clone)]
pu... |
// This file is part of Substrate.
// Copyright (C) 2019-2020 Parity Technologies (UK) Ltd.
// SPDX-License-Identifier: Apache-2.0
// 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
//
// ht... |
/// 字符串的左旋转操作是把字符串前面的若干个字符转移到字符串的尾部。
/// 请定义一个函数实现字符串左旋转操作的功能。比如,输入字符串"abcdefg"和数字2,该函数将返回左旋转两位得到的结果"cdefgab"。
///
/// 输入: s = "abcdefg", k = 2
/// 输出: "cdefgab"
pub fn main() {
let result = Solution::reverse_left_words(String::from("absdfjsf"), 2);
println!("{}", result);
}
struct Solution;
impl Solution {
... |
/// Generate mock server code for the given `prefix` and `type`.
///
/// For each gRPC server you need to generate codes using this macro.
///
/// # Arguments
/// * `prefix` - The prefix of the RPC (eg. `hello.Greeter` if the RPC is `/helloworld.Greeter/SayHello`)
/// * `type` - Type of the generated server. This [`Der... |
//! Tests auto-converted from "sass-spec/spec/libsass-todo-issues/issue_2023"
#[allow(unused)]
use super::rsass;
// From "sass-spec/spec/libsass-todo-issues/issue_2023/class-selector-id.hrx"
// Ignoring "class_selector_id", error tests are not supported yet.
// From "sass-spec/spec/libsass-todo-issues/issue_2023/cla... |
//! This module contains a list of primitives to help to modify a [`Table`].
//!
//! [`Table`]: crate::Table
mod format_config;
mod format_content;
mod format_positioned;
pub use format_config::FormatConfig;
pub use format_content::FormatContent;
pub use format_positioned::FormatContentPositioned;
/// A formatting f... |
pub type Colour = [f32; 4];
pub const RED: Colour = [1.0, 0.0, 0.0, 1.0];
pub const GREEN: Colour = [0.0, 1.0, 0.0, 1.0];
pub const BLUE: Colour = [0.0, 0.0, 1.0, 1.0];
pub const WHITE: Colour = [1.0; 4];
pub const BLACK: Colour = [0.0, 0.0, 0.0, 1.0];
|
#![doc = "generated by AutoRust 0.1.0"]
#![allow(unused_mut)]
#![allow(unused_variables)]
#![allow(unused_imports)]
use super::{models, API_VERSION};
#[non_exhaustive]
#[derive(Debug, thiserror :: Error)]
#[allow(non_camel_case_types)]
pub enum Error {
#[error(transparent)]
Operations_List(#[from] operations::l... |
// Based on the https://math.stackexchange.com/a/163101
fn coords(n: f64) -> (f64, f64) {
let k = ((n.sqrt() - 1.0) / 2.0).ceil();
let mut t: f64 = 2.0 * k + 1.0;
let mut m = t.powi(2);
t -= 1.0;
if n >= m - t {
return (k - (m - n), -k);
} else {
m -= t;
}
if n >= m - t... |
// Copyright 2019 Red Hat, Inc. All Rights Reserved.
// SPDX-License-Identifier: (BSD-3-Clause OR Apache-2.0)
#![allow(clippy::all)]
#![allow(non_upper_case_globals)]
#![allow(non_camel_case_types)]
#![allow(non_snake_case)]
// Keep this until https://github.com/rust-lang/rust-bindgen/issues/1651 is fixed.
#![cfg_attr... |
use std::collections::HashMap;
use exonum::blockchain::Transaction;
use exonum::crypto::PublicKey;
use exonum::messages::Message;
use exonum::storage::Fork;
use prometheus::{Histogram, IntCounter};
use currency::assets::AssetBundle;
use currency::error::Error;
use currency::service::CONFIGURATION;
use currency::statu... |
// This file is part of lock-free-multi-producer-single-consumer-ring-buffer. It is subject to the license terms in the COPYRIGHT file found in the top-level directory of this distribution and at https://raw.githubusercontent.com/lemonrock/lock-free-multi-producer-single-consumer-ring-buffer/master/COPYRIGHT. No part o... |
use core::{fmt::Arguments, num::ParseIntError, ops::Range};
use alloc::{collections::VecDeque, string::String};
use x86_64::instructions::interrupts::without_interrupts;
use pc_keyboard::*;
use x86_64::instructions::port::*;
use lazy_static::lazy_static;
use spin::Mutex;
use crate::{clear_row, io::devices::console::BA... |
#[no_mangle]
pub extern fn physics_single_chain_efjc_thermodynamics_isotensional_asymptotic_end_to_end_length(number_of_links: u8, link_length: f64, link_stiffness: f64, force: f64, temperature: f64) -> f64
{
super::end_to_end_length(&number_of_links, &link_length, &link_stiffness, &force, &temperature)
}
#[no_mang... |
use rocket::http::Status;
use crate::mongodb::db::ThreadedDatabase;
use crate::utils::mongo::connect_mongodb;
// Here I remove the warning for this 'unused' function because it is not unused
#[allow(dead_code)]
fn delete_user(_username: String) {
let db: std::sync::Arc<mongodb::db::DatabaseInner> = connect_mongod... |
use super::{
ParseRule,
Parser,
statements::StatementParser,
};
use lexer::tokens::{
TokenType,
TokenData,
};
use ir::{
Chunk,
hir::HIRInstruction,
};
use ir_traits::WriteInstruction;
use notices::{
DiagnosticLevel,
DiagnosticSourceBuilder
};
pub struct ModuleParser;
impl Parse... |
//! Tests auto-converted from "sass-spec/spec/libsass-closed-issues/issue_1133"
#[allow(unused)]
use super::rsass;
// From "sass-spec/spec/libsass-closed-issues/issue_1133/normal.hrx"
#[test]
fn normal() {
assert_eq!(
rsass(
"@function foo($map) {\
\n @return $map;\
\... |
// TODO: Needs Improvement
pub fn candy(ratings: Vec<i32>) -> i32 {
use std::cmp::max;
let n = ratings.len();
if n <= 1 {
return n as i32
}
let mut candys = vec![0; n];
let mut index_ratings: Vec<(usize, &i32)> = ratings.iter().enumerate().collect();
index_ratings.sort_by_key(|ir| ir... |
use cocoa::base::id;
pub trait MTLDepthStencilState {
unsafe fn device(self) -> id;
unsafe fn label(self) -> id;
}
impl MTLDepthStencilState for id {
unsafe fn device(self) -> id {
msg_send![self, device]
}
unsafe fn label(self) -> id {
msg_send![self, label]
}
}
|
use bitbuffer::{BitReadBuffer, BitReadStream, BitWriteStream, LittleEndian};
use std::fs;
use test_case::test_case;
use tf_demo_parser::demo::message::Message;
use tf_demo_parser::demo::packet::Packet;
use tf_demo_parser::demo::parser::{DemoHandler, Encode, NullHandler};
use tf_demo_parser::{MessageType, Parse};
#[tes... |
use core::{mem, slice};
use crate::spi::{BinData, UnsafeBin};
use crate::{Bin, DefaultExcessShrink, RcCounter, RcDecResult, RcMeta, RcUtils};
#[repr(C)]
pub struct RcData<TCounter: RcCounter> {
/// pointer to the data. Note: This is not always the same as the vector data (if you
/// slice the rc-data this mig... |
use emerald::prelude::{Entities, System};
use crossbeam_channel::Sender;
use std::io;
use std::net::UdpSocket;
use std::str;
use crate::types::{ComponentMap, EntityMessage, IncomingComponent, IncomingMessage, ResourceMap};
use websocket::sync::Server;
use websocket::OwnedMessage;
use websocket::server::NoTlsAcceptor;
... |
use chrono::{NaiveDate, NaiveDateTime};
use env;
use r2d2::{Pool, PooledConnection};
use r2d2_postgres::{PostgresConnectionManager, TlsMode};
use serenity::model::guild;
use serenity::model::id::{GuildId, UserId};
use std::str::FromStr;
use typemap::Key;
use command_error::CommandError;
#[derive(Clone)]
pub struct Co... |
extern crate tempdir;
use self::tempdir::TempDir;
use std::process::Command;
#[test]
fn ffi() {
let tmpdir = TempDir::new("zbox_test_ffi").expect("Create temp dir failed");
let output_dir = tmpdir.path();
let mut exe = output_dir.join("ffi");
let mut cmd;
if cfg!(target_os = "windows") {
... |
// Arrays are fixed length and have same data type
use std::mem;
pub fn run() {
let mut numbers: Vec<i32> =vec![1, 2, 3, 4, 5];
println!("{:?}", numbers);
println!("{}", numbers[0]);
// Change values
numbers[2] = 20;
println!("{:?}", numbers);
// Get length
println!("Length : {... |
#![warn(rust_2018_idioms)]
#![cfg(not(miri))] // Miri doesn't support file with non-default mode: https://github.com/rust-lang/miri/pull/2720
use anyhow::Context as _;
use auxiliary::{
assert_output, cargo_llvm_cov, fixtures_path, normalize_output, perturb_one_header,
test_project, test_report, CommandExt,
};
... |
//! Rendering buffer
/// Rendering Buffer
///
/// Data is stored as row-major order (C-format)
#[derive(Debug,Default)]
pub(crate) struct RenderingBuffer {
/// Pixel / Component level data of Image
pub data: Vec<u8>,
/// Image Width in pixels
pub width: usize,
/// Image Height in pixels
pub hei... |
use std::collections::HashSet;
pub fn main() -> (u32, u32) {
let entries: Vec<String> = advent_of_code_2020::entries("day01.txt").unwrap();
let mut nums: Vec<u32> = Vec::new();
for entry in entries.iter() {
nums.push(entry.parse::<u32>().unwrap());
}
let target = 2020;
(
report_... |
use crate::vec3::Vec3;
#[derive(Clone, Debug, PartialEq)]
pub struct Ray {
pub org: Vec3,
pub dir: Vec3,
}
impl Ray {
pub fn new(org: Vec3, dir: Vec3) -> Self {
Ray { org, dir }
}
pub fn copy(&mut self, other: Self) {
self.org.copy(other.origin());
self.dir.copy(other.dirac... |
mod x86_tables;
pub fn initialize_processor()
{
unsafe {
x86_tables::gdt_init();
x86_tables::idt_init();
x86_tables::pic_init();
}
}
|
//! A re-implementation of the "Duration" parsing utility from the Taskwarrior
//! source.
// TODO: this module is not yet implemented
pub(crate) struct Duration {}
impl Duration {
/// Parse a duration from a prefix of input and return the number of bytes consumed in the
/// input
pub(crate) fn parse<S: ... |
use paste;
use serde::{Serialize, Serializer};
use crate::{Element, Number};
use crate::error::TychoError;
use crate::serde::ser::map::MapSerializer;
use crate::serde::ser::seq::{SeqSerializer, SeqSerializerType};
use crate::serde::ser::struct_::StructSerializer;
use crate::serde::ser::variant::{VariantSeqSerializer, ... |
//! Creating a [Reference Cycle]
//!
//! [reference cycle]: https://doc.rust-lang.org/book/ch15-06-reference-cycles.html
use std::cell::RefCell;
use std::rc::Rc;
#[derive(Debug)]
pub enum CycleList<T> {
Node(T, RefCell<Rc<Self>>),
Null,
}
impl<T> CycleList<T> {
/// next returns the next node of the curren... |
use std::fmt;
use ::symb::base::{Node, NodeID, NodeData};
use ::symb::graph::{Graph};
use ::arrayfire::{print_gen, Dim4, ConvMode, ConvDomain};
pub struct Var {
val: Option<NodeData>,
}
impl Var {
pub fn new() -> Box<Var> {
Box::new(Var {
val: None,
})
}
pub fn new_shared(val:... |
use do_core::fs::{cat, ls};
use do_http::server::{tcp::TcpServer, udp};
#[async_std::main]
async fn main() -> std::io::Result<()> {
ls("/home/chrisp/wiki/").await?;
cat("/home/chrisp/wiki/index.md").await?;
TcpServer::new("0.0.0.0:8080").await
.run().await?;
Ok(())
}
|
use libc::{c_int, c_uchar};
#[link(name = "stb-image-resize", kind = "static")]
extern {
pub fn stbir_resize_uint8(input_pixels: *const c_uchar,
input_w: c_int,
input_h: c_int,
input_stride_in_bytes: c_int,
... |
#![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 ImpactedResourceStatus {
#[serde(flatten)]
pub resource: Resource,
#[serde(default, skip_serializing_if... |
#[cfg(test)]
mod file_editor {
use sdl2::pixels::*;
use sdl2::rect::*;
use std::sync::*;
#[test]
fn add_text() {
use crate::tests::support;
let config = support::build_config();
let canvas = support::build_canvas();
let font_context = sdl2::ttf::init().unwrap();
... |
use nom::Parser;
use nom_supreme::parser_ext::ParserExt;
use walrus_lexer::Token;
use walrus_syntax::{nodes::*, tokens::*};
mod support;
mod tokens;
mod decl;
mod expr;
mod lit;
mod pat;
mod ty;
pub use self::{decl::*, expr::*, lit::*, pat::*, support::*, tokens::*, ty::*};
#[cfg(test)]
use crate::test_parse;
pub ... |
// 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::{
accept, accept4, acct, add_key, adjtimex, bind, bpf, brk, capget,
capset... |
use pyo3::prelude::*;
mod code_stream;
pub use code_stream::CodeStream;
#[pymodule]
fn evm_extensions(_py: Python, module: &PyModule) -> PyResult<()> {
module.add_class::<CodeStream>()?;
Ok(())
}
|
#![allow(clippy::collapsible_else_if)]
use std::collections::HashMap;
use std::iter::Iterator;
use std::rc::Rc;
use std::str;
use std::usize;
use crate::aggregates::AggregateFun;
use crate::error::Error;
use crate::filters::{
AllDocsFilter, AndFilter, BboxFilter, BindFilter, BoostFilter, DistanceFilter,
Exact... |
fn main() {
let s = "hello rust world." ;
// 文字列を表示
println!("s is {}", s );
// 部分文字列を取得
let hello = &s[0..5] ;
let world = &s[11..] ;
println!("hello is {}", hello );
println!("world is {}", world );
// 長さを取得する
let len = s.len() ;
println!("s.len is {}", len );
// 空の... |
use std::error;
use std::io;
use std::io::Read;
use crate::day;
pub type BoxResult<T> = Result<T, Box<dyn error::Error>>;
pub struct Day08 {}
impl day::Day for Day08 {
fn tag(&self) -> &str { "08" }
fn part1(&self, input: &dyn Fn() -> Box<dyn io::Read>) {
println!("{:?}", self.part1_impl(&mut *input... |
use super::super::super::constant;
use super::Room;
use isaribi::{
style,
styled::{Style, Styled},
};
impl Styled for Room {
fn style() -> Style {
style! {
".overlay" {
"position": "fixed";
"top": "0";
"left": "0";
"height"... |
use itertools::Itertools;
fn rotate_password(password: &str) -> String {
let mut new_password = String::new();
let mut rotating = true;
for c in password.chars().rev() {
let mut new_char = c;
if rotating {
new_char = if c == 'z' { 'a' } else { ((c as u8) + 1) as char };
... |
use aoc_utils::read_file;
use day05::fold_polymer;
use std::collections::HashSet;
fn main() {
if let Ok(contents) = read_file("./input") {
let chars: Vec<char> = contents
.split("")
.filter_map(|s| if s == "" { None } else { s.chars().next() })
.collect();
let r... |
// 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.
//! A networking stack.
#![feature(async_await)]
// In case we roll the toolchain and something we're using as a feature has been
// stabilized.
#![allow(... |
error_chain! {
foreign_links {
HidError(::hid::Error);
}
errors {
WriteTimeout {
description("write operation is time out")
display("write operation is time out")
}
}
} |
use crate::lib::environment::Environment;
use crate::lib::error::DfxResult;
use clap::Clap;
mod default;
mod install;
mod list;
mod uninstall;
/// Manage the dfx toolchains
#[derive(Clap)]
#[clap(name("toolchain"))]
pub struct ToolchainOpts {
#[clap(subcommand)]
subcmd: SubCommand,
}
#[derive(Clap)]
pub enu... |
use std::env;
use std::fs::File;
use std::io::BufRead;
use std::io::BufReader;
use std::io::Write;
use std::path::Path;
fn main() {
let declaration = String::from("fn english_frequencies() -> HashMap<u8, f32> {[");
// csv must be 2 columns, no header
// ascii number, frequency as percentage
// 32,17.1... |
use crate::*;
use pretty_assertions::assert_eq;
use std::net::SocketAddr;
use std::time::Duration;
pub enum ExpectedTestCaseResult {
Ok,
Timeout,
Failed(&'static str),
}
pub struct ExpectedPingClientTestResults {
pub timeout_min_time: Duration,
pub ping_non_existing_host_result: ExpectedTestCaseRe... |
use std::cmp::max;
#[allow(dead_code)]
fn read_line() -> String {
let mut line = String::new();
std::io::stdin().read_line(&mut line).unwrap();
line.trim_end().to_owned()
}
fn main() {
let _n: usize = read_line().parse().unwrap();
let aa: Vec<i64> = read_line()
.split_whitespace()
... |
#![doc = "generated by AutoRust 0.1.0"]
#[cfg(feature = "package-2020-04")]
mod package_2020_04;
#[cfg(feature = "package-2020-04")]
pub use package_2020_04::{models, operations, API_VERSION};
#[cfg(feature = "package-2019-12")]
mod package_2019_12;
#[cfg(feature = "package-2019-12")]
pub use package_2019_12::{models, ... |
use std::future::Future;
use std::time::Duration;
use futures::stream::{Stream, StreamExt};
use tokio_stream::wrappers::IntervalStream;
#[inline(always)]
pub(crate) fn sleep(dur: Duration) -> impl Future<Output = ()> {
tokio::time::sleep(dur)
}
pub(crate) fn interval(dur: Duration) -> impl Stream<Item = ()> {
... |
use std::borrow::ToOwned;
use std::process;
use workdir::Workdir;
macro_rules! stats_tests {
($name:ident, $field:expr, $rows:expr, $expect:expr) => (
stats_tests!($name, $field, $rows, $expect, false);
);
($name:ident, $field:expr, $rows:expr, $expect:expr, $nulls:expr) => (
mod $name {
... |
#![cfg_attr(not(feature = "std"), no_std)]
/// This module extends the pallet-generic-asset module.
/// With an extra asset symbol for each asset.
/// Currently we are using a very simple management model, the pallet-sudo,
/// the more decentralized strategy is incoming.
mod mock;
mod tests;
use rstd::{result, vec::V... |
fn main() {
let x = vec![1, 2, 3];
// x is moved into the closure when the closure is created,
// so `x` cannot be used after the closure
let equal_to_x = move |z| z == x;
// using it here; won't compile
println!("can't use x here: {:?}", x);
let y = vec![1, 2, 3];
assert!(equal_to_x(... |
type Link<T> = Option<Box<Node<T>>>;
#[derive(Debug)]
struct Node<T: Ord> {
val: T,
left: Link<T>,
right: Link<T>,
}
#[derive(Debug)]
pub struct BST<T: Ord> {
root: Link<T>,
}
impl<T: Ord> BST<T> {
pub fn new() -> Self {
BST { root: None }
}
}
impl<T: Ord> BST<T> {
pub fn insert(... |
//! # Common datastructures and methods
//!
//! This module implements core traits for this library
#![warn(missing_docs)]
use std::time::Instant;
pub mod borrow;
pub mod buffer;
pub mod ldf;
#[doc(hidden)]
pub mod nom_ext;
pub mod parser;
pub mod reader;
pub mod types;
#[macro_use]
#[doc(hidden)]
pub extern crate nu... |
#[doc = r"Register block"]
#[repr(C)]
pub struct RegisterBlock {
#[doc = "0x00..0x80 - HSEM register HSEM_R%s HSEM_R31"]
pub r: [R; 32],
#[doc = "0x80..0x100 - HSEM Read lock register"]
pub rlr: [RLR; 32],
#[doc = "0x100 - HSEM Interrupt enable register"]
pub c1ier: C1IER,
#[doc = "0x104 - H... |
pub mod cached_tree_hash;
pub mod signed_root;
pub mod standard_tree_hash;
pub const BYTES_PER_CHUNK: usize = 32;
pub const HASHSIZE: usize = 32;
pub const MERKLE_HASH_CHUNCK: usize = 2 * BYTES_PER_CHUNK;
pub use cached_tree_hash::{BTreeOverlay, CachedTreeHashSubTree, Error, TreeHashCache};
pub use signed_root::Signe... |
mod releases;
pub use releases::{download_asset, list_releases};
|
use crate::CHIP8_HEIGHT;
use crate::CHIP8_WIDTH;
pub type FrameBuffer = [[u8; CHIP8_WIDTH]; CHIP8_HEIGHT];
#[derive(Debug, PartialEq, Eq)]
pub struct Display {
buffer: FrameBuffer,
}
impl Display {
pub fn new() -> Self {
Self {
buffer: [[0; CHIP8_WIDTH]; CHIP8_HEIGHT],
}
}
... |
#[doc = "Register `OPTSR2_CUR` reader"]
pub type R = crate::R<OPTSR2_CUR_SPEC>;
#[doc = "Field `SRAM13_RST` reader - SRAM1 and SRAM3 erase upon system reset"]
pub type SRAM13_RST_R = crate::BitReader;
#[doc = "Field `SRAM2_RST` reader - SRAM2 erase when system reset"]
pub type SRAM2_RST_R = crate::BitReader;
#[doc = "F... |
use vec3::*;
use ray::*;
#[derive(Copy, Clone)]
pub struct Hit<'a> {
pub t: f32,
pub p: Vec3,
pub n: Vec3,
pub m: &'a Box<Material>
}
impl<'a> Hit<'a> {
pub fn new(nt: f32, np: Vec3, nn: Vec3, mm: &'a Box<Material>) -> Hit<'a> { Hit { t:nt, p:np, n:nn, m:mm } }
}
pub struct Scattered {
pub s... |
fn main() {
let s1 = String::from("hello");
let res = func_one(s1);
// println!("s1:{}", s1); //报错,所有权已经转移到函数中了
println!("return res:{}", res);
println!("============");
let s2 = String::from("world");
func_ref(&s2);
println!("============");
let mut s3 = String::from("xyz");
f... |
#![no_main]
#![no_std]
extern crate cortex_m_rt;
extern crate panic_halt;
use cortex_m_rt::{entry, pre_init};
#[pre_init]
unsafe fn foo() {}
#[pre_init] //~ ERROR symbol `__pre_init` is already defined
unsafe fn bar() {}
#[entry]
fn baz() -> ! {
loop {}
}
|
use std::collections::HashMap;
pub use crate::globalstate::GlobalState;
pub use crate::instructionobject::InstructionObject;
//The lookup table for instruction code to Instruction object
pub struct LookupTable {
pub operation_lookup: HashMap<char, InstructionObject>,
}
impl LookupTable {
pub fn new() -> Look... |
use std::fmt::Debug;
use ndarray::Array1;
pub use crate::rl::agents::Agent;
pub use crate::rl::environments::Environment;
pub use crate::rl::trainers::Trainer;
/// Actions that agents can take in an environment
pub trait Action: Debug + Clone {}
#[derive(Debug, Clone, Copy)]
pub struct DiscreteAction(pub usize);
i... |
use ast::{Node, Val};
use back::runtime_error::RuntimeError;
use loc::Loc;
use std::cell::RefCell;
use std::collections::HashMap;
use std::rc::Rc;
pub type SmartEnv = Rc<RefCell<Env>>;
#[derive(PartialEq, Debug)]
pub struct Env {
pub name: String,
pub map: HashMap<String, Node>,
pub parent: Option<SmartEn... |
mod bind;
mod raw;
mod stmt;
mod url;
use self::raw::RawConnection;
use self::stmt::iterator::StatementIterator;
use self::stmt::Statement;
use self::url::ConnectionOptions;
use super::backend::Mysql;
use crate::connection::commit_error_processor::{
default_process_commit_error, CommitErrorOutcome, CommitErrorProc... |
use std::fs::File;
use std::io::{BufRead, BufReader, stdout, Write, BufWriter};
use std::error::Error;
use std::io::ErrorKind;
use crate::rule::Rule;
// NOTE: regexよりも約1.4倍程早かったのでpcre2を使う
use pcre2::bytes::Regex;
use pcre2::bytes::RegexBuilder;
const RESET: &str = "\x1b[0m";
pub struct Replacer {
regex: Regex,
... |
use std::collections::HashSet;
pub fn part_01(data: &str) -> usize {
data.lines()
.map(|line| {
let (row_raw, col_raw) = (&line[0..7], &line[7..]);
//println!("{} --> {} - {}", line, row_raw, col_raw);
let (row, col) = (parse_to_binary(row_raw, 'B'), parse_to_binary(col_... |
#![allow(non_camel_case_types, dead_code)]
use libc::{size_t, c_int, c_char, c_void};
use session::sp_session;
#[derive(Clone, Copy)]
#[repr(u32)]
pub enum sp_error {
SP_ERROR_OK = 0,
SP_ERROR_BAD_API_VERSION = 1,
SP_ERROR_API_INITIALIZATION_FAILED = 2,
SP_ERROR_TRACK_NOT_PLAYABLE = 3,
SP_ERROR_BA... |
fn main() {
let input = std::fs::read("input/day3").unwrap();
let width = input.iter().position(|&c| c == b'\n').unwrap();
let height = input.len() / (width + 1);
let cell_occupied = |x, y| input[y * (width + 1) + x] == b'#';
const SLOPE: [usize; 2] = [3, 1];
let tree_count = (1..height)
... |
use std::{convert::TryInto, ops::Not};
use crate::{
frame::{ChannelLayout, Frame, Sample, Subblock, Subframe},
headers::{BlockSize, MetadataBlockStreamInfo},
};
pub fn encode_subframe<S: Sample>(subblock: &Subblock<S>) -> Subframe<S> {
Subframe::from_subblock(subblock)
}
pub enum Block<S: Sample> {
/... |
use std::thread;
use std::time::Duration;
fn main () {
let handle = thread::spawn (|| {
for a in 1..8 {
println!("hello {} from spawned thread!",a);
thread::sleep(Duration::from_millis(2));
}
});
for b in 1..6 {
println!("hello {} from main thread!",... |
// This file is part of Substrate.
// Copyright (C) 2017-2020 Parity Technologies (UK) Ltd.
// SPDX-License-Identifier: Apache-2.0
// 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
//
// ht... |
#[doc = "Register `COUNT6_TX` reader"]
pub type R = crate::R<COUNT6_TX_SPEC>;
#[doc = "Register `COUNT6_TX` writer"]
pub type W = crate::W<COUNT6_TX_SPEC>;
#[doc = "Field `COUNT6_TX` reader - Transmission byte count"]
pub type COUNT6_TX_R = crate::FieldReader<u16>;
#[doc = "Field `COUNT6_TX` writer - Transmission byte ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.