text stringlengths 8 4.13M |
|---|
//!
//! This module provides a wrapper around the differents PIC chips in
//! the x86 architecture.
//!
/// Provides wrappers for the 8259 PIC chipset.
mod pic8259;
/// The `Pic` trait must be implemented for all structures representing a
/// Programmable Interrupt Controller (PIC). It provides functions that help
//... |
use itertools::Itertools;
#[aoc::main(06)]
pub fn main(input: &str) -> (usize, usize) {
solve(input)
}
#[aoc::test(06)]
pub fn test(input: &str) -> (String, String) {
let res = solve(input);
(res.0.to_string(), res.1.to_string())
}
fn solve(input: &str) -> (usize, usize) {
let p1 = part1(input);
... |
// Copyright 2020 ChainSafe Systems
// SPDX-License-Identifier: Apache-2.0, MIT
use super::deal::ClientDealProposal;
use address::Address;
use clock::ChainEpoch;
use num_bigint::biguint_ser::{BigUintDe, BigUintSer};
use serde::{Deserialize, Deserializer, Serialize, Serializer};
use vm::{DealID, RegisteredProof, Sector... |
use crate::build_context::BridgeModel;
use crate::target::RUST_1_64_0;
#[cfg(feature = "zig")]
use crate::PlatformTag;
use crate::{BuildContext, PythonInterpreter, Target};
use anyhow::{anyhow, bail, Context, Result};
use fat_macho::FatWriter;
use fs_err::{self as fs, File};
use normpath::PathExt;
use std::collections:... |
fn count_string(s: &str) -> i32 {
s.split_whitespace().map(|n| n.len() as i32).sum()
}
fn count_from_1_9() -> i32 {
count_string("one two three four five six seven eight nine")
}
fn count_from_10_19() -> i32 {
count_string("ten eleven twelve thirteen fourteen fifteen sixteen seventeen eighteen nineteen")
... |
mod day1;
mod day2;
mod day3;
mod day4;
mod day6;
fn main() -> Result<(), std::io::Error> {
let challenges: Vec<&dyn Fn() -> Result<(), std::io::Error>> = vec![
&day6::challenge,
&day4::challenge,
&day3::challenge,
&day2::challenge,
&day1::challenge,
];
for c in cha... |
//! Your one-stop shop for everything Core Wars
use {
itertools::assert_equal,
redcode::{
self, Address, AddressingMode, AddressingMode::*, Field, IncrementMode, Instruction, OpCode,
OpCode::*, OpField, OpMode, OpMode::*,
},
std::collections::VecDeque,
std::rc::Rc,
};
const MARS_DEFAULT_SIZE: usize =... |
/*
chapter 4
syntax and semantics
scope and shadowing
*/
fn main() {
let mut a: i32 = 1;
println!("{}", a);
a = 7;
println!("{}", a);
let a = a;
// a is now immutable and is bound to 7
println!("{}", a);
let b = 4;
println!("{}", b);
let b = "i can also be bound to text!";... |
use crate::utils::assert_send_transaction_fail;
use crate::{utils::is_committed, Net, Spec, DEFAULT_TX_PROPOSAL_WINDOW};
use ckb_chain_spec::ChainSpec;
use ckb_types::core::EpochNumberWithFraction;
use log::info;
const CELLBASE_MATURITY_VALUE: u64 = 3;
pub struct ReferenceHeaderMaturity;
impl Spec for ReferenceHeade... |
use crate::chain_spec::{
self, get_account_id_from_seed, AuthorityKeys, ChainParams, SerializablePeerId,
};
use aleph_primitives::AuthorityId as AlephId;
use aleph_runtime::AccountId;
use libp2p::identity::{ed25519 as libp2p_ed25519, PublicKey};
use sc_cli::{Error, KeystoreParams};
use sc_keystore::LocalKeystore;
u... |
// SPDX-License-Identifier: Apache-2.0
use anyhow::Result;
use goblin::elf::{header::*, note::NoteIterator, program_header::*, Elf};
use std::ops::Range;
/// The sallyport program header type
#[cfg(any(feature = "backend-kvm"))]
pub const PT_ENARX_SALLYPORT: u32 = PT_LOOS + 0x34a0001;
/// The enarx code program hea... |
pub fn pymod(a: isize, b: isize) -> isize {
let r = a % b;
// If r and b differ in sign, add b to wrap the result to the correct sign.
if (r > 0 && b < 0) || (r < 0 && b > 0) {
return r + b;
}
r
}
pub fn is_some_and_not_empty<T>(v: &Option<Vec<T>>) -> bool {
match v {
Some(v) =>... |
use std::{borrow::Cow, fmt::Write};
use chrono::Utc;
use rosu_pp::{
Beatmap as Map, BeatmapExt, CatchPP, DifficultyAttributes, GameMode as Mode, ManiaPP, OsuPP,
PerformanceAttributes, TaikoPP,
};
use rosu_v2::prelude::{
Beatmap, BeatmapsetCompact, GameMode, GameMods, Grade, Score, ScoreStatistics,
};
use ... |
use std::fs;
use std::path::PathBuf;
use std::process;
use nix::unistd;
use std::os::unix::fs::PermissionsExt;
static CGROUP_PATH: &str = "/sys/fs/cgroup";
pub fn cgroup_init(group_name: &str) {
let mut cgroups_path = PathBuf::from(CGROUP_PATH);
if !cgroups_path.exists() {
println!("Error: Missing Cgroups Suppo... |
fn main() {
let e_grave = 'è';
let japanese_character = 'さ';
println!("{} {}", e_grave, japanese_character);
}
|
use super::{parse_event_data_attributes, EventDataAttributes};
use quote::quote;
use syn::{Data, DataStruct, DeriveInput, Fields, FieldsNamed};
enum BuilderType {
Create,
Update,
Delete,
Purge,
}
fn expand_derive_event_data_struct(
input: &DeriveInput,
builder_type: BuilderType,
) -> syn::Resu... |
/*!
* Elgamal public key cryptography implementation in Rust.
*
* - Key generation
* - Signature generation and verification (https://en.wikipedia.org/wiki/ElGamal_signature_scheme)
* - Encryption and Decryption (https://en.wikipedia.org/wiki/ElGamal_encryption)
*
* Copyright (c) 2014, Brandon Hamilton
* All rights re... |
#[doc = "Register `I3C_RMR` reader"]
pub type R = crate::R<I3C_RMR_SPEC>;
#[doc = "Field `IBIRDCNT` reader - IBI received payload data count (when the I3C is configured as controller) When the I3C is configured as controller, this field logs the number of data bytes effectively received in the I3C_IBIDR register."]
pub... |
#[doc = "Reader of register DSI_HWCFGR"]
pub type R = crate::R<u32, super::DSI_HWCFGR>;
#[doc = "Reader of field `TECHNO`"]
pub type TECHNO_R = crate::R<u8, u8>;
#[doc = "Reader of field `FIFOSIZE`"]
pub type FIFOSIZE_R = crate::R<u16, u16>;
impl R {
#[doc = "Bits 0:3 - TECHNO"]
#[inline(always)]
pub fn tec... |
pub fn function_in_a_subdirectory() {
println!("This function is in a subdirectory");
}
|
fn main() {
let num1: i8 = 3;
let num2: Option<i8> = Some(3);
println!("{:?}", num1);
println!("{:?}", num2);
}
|
//! Get info on your team's Slack channels, create or archive channels, invite users, set the topic and purpose, and mark a channel as read.
use rtm::{Channel, Cursor, Message, Paging};
use timestamp::Timestamp;
/// Archives a channel.
///
/// Wraps https://api.slack.com/methods/channels.archive
#[derive(Clone, Debug... |
use blake2::{Blake2s, Digest};
use hash::H256;
#[inline]
pub fn blake2s(input: &[u8]) -> H256 {
let mut hasher = Blake2s::default();
let data: &[u8] = input.clone();
hasher.input(&data);
let res = hasher.result();
res.to_vec();
let mut arr = [0u8;32];
arr.clone_from_slice(&res);
arr
} |
use std::mem;
use std::ptr::copy_nonoverlapping;
pub fn encode_fixed32(value: u32) -> [u8; 4] {
if cfg!(target_endian = "little") {
unsafe { mem::transmute(value.to_le()) }
} else {
unsafe { mem::transmute(value.to_be()) }
}
}
pub fn encode_fixed64(value: u64) -> [u8; 8] {
if cfg!(targ... |
use core::mem;
use std::marker::PhantomData;
use crate::spi::{FnTable, UnsafeBin};
use crate::{Bin, NsRcCounter, RcCounter, RcData, RcUtils, SyncRcCounter};
pub struct AnyRcImpl<TConfig: AnyRcImplConfig> {
_phantom: PhantomData<TConfig>,
}
impl<TConfig: AnyRcImplConfig> AnyRcImpl<TConfig> {
#[inline]
pub... |
use super::*;
use std::sync::atomic::{AtomicU32, Ordering};
use std::sync::Arc;
#[test]
fn test_stream_buffered_amount() -> Result<(), Error> {
let s = Stream::default();
assert_eq!(0, s.buffered_amount());
assert_eq!(0, s.buffered_amount_low_threshold());
s.buffered_amount.store(8192, Ordering::SeqC... |
use exgui::{builder::*, ChangeView, Color, Comp, LineJoin, Model, Node, PathCommand::*, Stroke};
use exgui_controller_glutin::{glutin, App};
use exgui_render_nanovg::NanovgRender as Render;
// use exgui_render_pathfinder::PathfinderRender as Render;
struct Smile {
normal_face: bool,
}
#[derive(Clone)]
pub enum Ms... |
use base::types;
use base::types::{Type, TcType};
use std::marker::PhantomData;
use gc::{Gc, Traverseable};
use std::cell::Cell;
use api::{Userdata, VMType, Pushable};
use api::generic::A;
use vm::{Status, Value, Thread, Result};
#[derive(Clone, PartialEq)]
pub struct Lazy<T> {
value: Cell<Lazy_>,
_marker: Ph... |
use crate::view::shader_utils;
use cgmath;
use web_sys::{WebGl2RenderingContext, WebGlProgram};
pub fn initialize_shader(context: &WebGl2RenderingContext) -> Result<WebGlProgram, String>
{
let vert_shader = shader_utils::compile_shader(
&context,
WebGl2RenderingContext::VERTEX_SHADER,
r#"... |
/*
fn fn_vs_closure() {
print();
fn print() {
println!("hello");
}
let helloStr = "hello";
let closure = || {println!("{} world", helloStr);};
closure();
}
*/
pub fn expand() -> Box<Fn(i32)->i32> {
let value = 10i32;
let closure = move | input: i32| -> i32 { return value + in... |
extern crate sdl2;
extern crate glm;
use sdl2::{
rect::Rect,
rect::Point,
pixels::Color,
pixels::PixelFormatEnum,
event::Event,
keyboard::Keycode
};
use glm::ext;
use glm::*;
use std::time::Duration;
fn main() -> Result<(), String> {
let sdl_context = sdl2::init()?;
let video_subsyst... |
//! Tests auto-converted from "sass-spec/spec/non_conformant/errors/loop-for"
#[allow(unused)]
use super::rsass;
mod numeric;
|
use std::env;
use std::fs;
use std::io::Error;
use std::collections::HashMap;
fn main() -> Result<(), Error> {
let args: Vec<String> = env::args().collect();
let filename = &args[1];
let contents = fs::read_to_string(filename).expect("Something went wrong!");
let strings : Vec<&str> = contents.split(',... |
#[allow(unused_variables)] //Allows to create variables not used in any function
fn main() {
let stack_f64: f64 = 1.;
let heap_f64: Box<f64> = Box::new(2.);
stack_procedure(stack_f64);
println!("In main stack {}", stack_f64);
// Desta maneira o var transfere a propiedade para o valor param da... |
// Copyright 2018 The Open AI Team Authors
// Copyright 2018 The HuggingFace Inc. team.
// Copyright 2019 Guillaume Becquin
// 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.... |
use super::GetFlag;
use super::{GetFlag::*, Results};
use serde::Deserialize;
/// All valid flags for get producer method
pub const PRODUCER_FLAGS: [GetFlag; 3] = [Basic, Details, Relations];
/// Results returned from get producer method
#[derive(Deserialize, Debug, PartialEq)]
pub struct GetProducerResults {
#[s... |
use std::io;
use std::marker::PhantomData;
use std::panic::RefUnwindSafe;
use futures::future;
use hyper::header::Location;
use hyper::{StatusCode, Uri};
use percent_encoding::{utf8_percent_encode, QUERY_ENCODE_SET};
use gotham::handler::HandlerFuture;
use gotham::http::response::create_response;
use gotham::middlewa... |
use std::fmt::{self, Debug, Display, Formatter};
use std::fs::File;
use std::io::{self, Read};
use std::path::{Path, PathBuf};
use serde_derive::Deserialize;
pub fn read(path: &Path) -> Result<Config, Error> {
do_read(path).map_err(|cause| Error {
path: path.into(),
cause,
})
}
fn do_read(pat... |
#[doc = r"Register block"]
#[repr(C)]
pub struct RegisterBlock {
#[doc = "0x00 - STGENC control register"]
pub stgenc_cntcr: STGENC_CNTCR,
#[doc = "0x04 - STGENC status register"]
pub stgenc_cntsr: STGENC_CNTSR,
#[doc = "0x08 - the control interface must clear the STGENC_CNTCR.EN bit before writing ... |
fn main () {
let mut x = "test 1 + 2".chars();
let x_vec = x.collect::<Vec<char>>();
for i in x_vec.iter() {
println!("{}",i)
}
}
|
use crate::client::provider_poller::PolledMessagesReceiver;
use futures::channel::{mpsc, oneshot};
use futures::lock::Mutex;
use futures::StreamExt;
use log::*;
use std::sync::Arc;
use tokio::runtime::Handle;
use tokio::task::JoinHandle;
pub(crate) type ReceivedBufferResponse = oneshot::Sender<Vec<Vec<u8>>>;
pub(crate... |
use std::collections::HashMap;
pub fn vec_simple_test() {
println!("{}", "------------vec demo start-------------------");
let mut v = vec![1, 2, 3];
v.push(20);
// every element pls 50 and return the pointer
for i in &mut v {
*i += 50;
}
// print all of element
for i in &v {... |
use crate::helpers::spawn_app;
use axum_websockets::subsystems::{pc_usage::CpuLoadResult, WebsocketSystem};
#[actix_rt::test]
async fn cpu_load_receives_results() {
// Arrange
let app = spawn_app().await;
let message = serde_json::json!({
"system": "pc_usage",
"task": "cpu_load",
})
... |
#[doc = "Reader of register UART_TX_CTRL"]
pub type R = crate::R<u32, super::UART_TX_CTRL>;
#[doc = "Writer for register UART_TX_CTRL"]
pub type W = crate::W<u32, super::UART_TX_CTRL>;
#[doc = "Register UART_TX_CTRL `reset()`'s with value 0x02"]
impl crate::ResetValue for super::UART_TX_CTRL {
type Type = u32;
... |
#![cfg_attr(
target_arch = "spirv",
no_std,
feature(register_attr, lang_items),
register_attr(spirv)
)]
// HACK(eddyb) can't easily see warnings otherwise from `spirv-builder` builds.
#![deny(warnings)]
#[cfg(not(target_arch = "spirv"))]
#[macro_use]
pub extern crate spirv_std_macros;
#[allow(unused_im... |
#[doc = "Register `MICR` writer"]
pub type W = crate::W<MICR_SPEC>;
#[doc = "Field `MCMP1C` writer - Master Compare 1 Interrupt flag clear"]
pub type MCMP1C_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `MCMP2C` writer - Master Compare 2 Interrupt flag clear"]
pub type MCMP2C_W<'a, REG, const O... |
//! A 2D graphics backend for Piston-Graphics that stores and optimizes commands.
#![deny(missing_docs)]
extern crate graphics;
extern crate image;
extern crate range;
extern crate texture;
use std::sync::{Arc, RwLock};
use std::collections::HashMap;
use graphics::{DrawState, Graphics, ImageSize};
use graphics::typ... |
fn main() {
println!("Hello, world!");
/*
Another data type that does not have ownership is the slice. Slices let you reference a contiguous
sequence of elements in a collection rather than the whole collection.
Here’s a small programming problem: write a function that takes a string and returns t... |
#[doc = "Register `MACIMR` reader"]
pub type R = crate::R<MACIMR_SPEC>;
#[doc = "Register `MACIMR` writer"]
pub type W = crate::W<MACIMR_SPEC>;
#[doc = "Field `PMTIM` reader - PMT interrupt mask"]
pub type PMTIM_R = crate::BitReader<PMTIM_A>;
#[doc = "PMT interrupt mask\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debu... |
use std::time::Duration;
use tokio::{runtime::Runtime, time::sleep};
async fn count_and_run<F>(count: u32, f: F)
where
F: Fn() -> &'static str,
{
for i in 1..=count {
sleep(Duration::from_secs(1)).await;
println!("[{}/{}] {}", i, count, f());
}
}
async fn learn_song() -> &'static str {
... |
use guion::util::bounds::Offset;
use super::*;
/// extract the absolute position out of a SDL event
pub fn pos_of(e: &SDLEvent, wx: f32, wy: f32) -> Option<Offset> {
match e {
SDLEvent::Quit{..} => None,
SDLEvent::AppTerminating{..} => None,
SDLEvent::AppLowMemory{..} => None,
SDLEv... |
//! Scenes from the books, separated by module.
pub mod first;
pub mod second;
pub mod third;
|
extern crate cc;
use std::fs::File;
use std::io::{Result, Write};
fn main() {
println!("cargo:rerun-if-env-changed=LOG");
println!("cargo:rerun-if-env-changed=SMP");
println!("cargo:rerun-if-env-changed=BOARD");
println!("cargo:rerun-if-env-changed=USER_IMG");
let arch: String = std::env::var("AR... |
fn main() {
let x = 201; // You cannot change this.
let mut y: i32 = 1; // This variable is a mutable i32.
y = y + x;
println!("y is {}", y);
}
|
#[doc = "Register `OPFCCR` reader"]
pub type R = crate::R<OPFCCR_SPEC>;
#[doc = "Register `OPFCCR` writer"]
pub type W = crate::W<OPFCCR_SPEC>;
#[doc = "Field `CM` reader - Color mode"]
pub type CM_R = crate::FieldReader<CM_A>;
#[doc = "Color mode\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[re... |
use hydroflow::hydroflow_syntax;
use hydroflow::util::collect_ready;
use multiplatform_test::multiplatform_test;
#[multiplatform_test]
pub fn test_zip_basic() {
let (result_send, mut result_recv) =
hydroflow::util::unbounded_channel::<(usize, &'static str)>();
let mut df = hydroflow_syntax! {
... |
use std::{
borrow::Cow,
collections::{hash_map::Entry, HashMap},
fmt::{self, Display, Formatter},
ops::{BitXor, Range},
str,
};
use hmac::{
digest::{Digest, FixedOutput, KeyInit},
Hmac,
Mac,
};
use lazy_static::lazy_static;
use md5::Md5;
use sha1::Sha1;
use sha2::Sha256;
use tokio::sync... |
struct Solution;
#[derive(Debug, Clone, PartialEq)]
enum Color {
UNCOLORED,
RED,
GREEN,
}
impl Solution {
// 广度优先
pub fn is_bipartite(graph: Vec<Vec<i32>>) -> bool {
let n = graph.len();
let mut color = vec![Color::UNCOLORED; n];
for i in 0..n {
// 已经染过色了,不处理它了
... |
#![no_std]
#![no_main]
#![feature(trait_alias)]
#![feature(min_type_alias_impl_trait)]
#![feature(impl_trait_in_bindings)]
#![feature(type_alias_impl_trait)]
#![allow(incomplete_features)]
#[path = "../example_common.rs"]
mod example_common;
use cortex_m::prelude::_embedded_hal_blocking_serial_Write;
use embassy::exec... |
use anyhow::{Context, Result};
use rand::distributions::{Alphanumeric, DistString};
use std::{env, fs, io, path::{Path, PathBuf}, process};
use crate::config::read_config;
pub fn exec() -> Result<()> {
let cfg = read_config()
.context("Reading config")?;
let dir = create_new_dir(&cfg.data_path)?;
... |
#[doc = "Register `ETH_DMAA4DACR` reader"]
pub type R = crate::R<ETH_DMAA4DACR_SPEC>;
#[doc = "Register `ETH_DMAA4DACR` writer"]
pub type W = crate::W<ETH_DMAA4DACR_SPEC>;
#[doc = "Field `TDWC` reader - TDWC"]
pub type TDWC_R = crate::FieldReader;
#[doc = "Field `TDWC` writer - TDWC"]
pub type TDWC_W<'a, REG, const O: ... |
pub mod metadata;
pub mod properties;
use std::path::{Path, PathBuf};
use anyhow::{anyhow, Result};
use libheif_rs::HeifContext;
use log::debug;
use metadata::AppleDesktop;
use properties::Properties;
use crate::heif;
const PROPERTIES_NAME: &str = "properties.xml";
/// Unpacked wallpaper laying somewhere in the fi... |
/*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
#[tokio::main]
async fn main() -> Result<(), qldb::Error> {
let client = qldb::Client::from_env();
let result = client.list_ledgers().send().await?;
if let Some(ledgers) = result.ledgers {
... |
//! Expvar target metrics fetcher
//!
//! This module scrapes Go expvar formatted metrics from the target software.
//! The metrics are formatted as a JSON tree that is fetched over HTTP.
use std::time::Duration;
use metrics::gauge;
use serde::Deserialize;
use serde_json::Value;
use tracing::{error, info, trace};
us... |
fn main() {
let distance: i32 = 100;
let power: f32 = 2.345;
let super_power: f64 = 56789.4532;
let initial = 'A';
let mut first_name = String::from("Zed");
let last_name = String::from("Shaw");
first_name.push('Z');
println!("You are {} miles away.\n", distance);
println!("You hav... |
use crate::utils::validate_credentials;
use actix_web_httpauth::extractors::AuthenticationError;
use actix_web_httpauth::extractors::bearer::{BearerAuth, Config};
use actix_web::error::{ErrorUnauthorized, ErrorBadRequest};
use actix_web::{Error,dev::ServiceRequest, FromRequest, HttpRequest};
use serde::{Serialize, De... |
use super::track::Track;
use serde_derive::Deserialize;
#[derive(Deserialize, Debug)]
pub struct Pattern {
#[doc = "Name of the pattern."]
pub name: String,
#[serde(alias = "stepCount")]
#[serde(default)]
#[doc = "How long is this pattern?"]
pub step_count: u16,
#[serde(alias = "beatsPerMin... |
use std::iter;
use std::ops;
use crate::data::*;
pub struct Grid {
data: Vec <Cell>,
num_rows: LineSize,
num_cols: LineSize,
}
impl Grid {
// constructors
pub fn new (
num_rows: LineSize,
num_cols: LineSize,
) -> Grid {
Grid {
data: iter::repeat (Cell::UNKNOWN).take (
num_rows as usize * num_co... |
use solve::slg::{TableIndex, UCanonicalGoal};
use solve::slg::on_demand::table::Table;
use std::collections::HashMap;
use std::ops::{Index, IndexMut};
/// See `Forest`.
#[derive(Default)]
crate struct Tables {
/// Maps from a canonical goal to the index of its table.
table_indices: HashMap<UCanonicalGoal, Tabl... |
use super::{operate, BytesArgument};
use nu_engine::CallExt;
use nu_protocol::ast::Call;
use nu_protocol::ast::CellPath;
use nu_protocol::engine::{Command, EngineState, Stack};
use nu_protocol::Category;
use nu_protocol::{Example, PipelineData, ShellError, Signature, Span, SyntaxShape, Value};
#[derive(Clone)]
pub str... |
// Copyright 2021 Protocol Labs.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, di... |
use std::{
collections::HashMap,
str::from_utf8,
};
use framework::{app, decode_base64, App, Canvas, Color, KeyCode, KeyState, KeyboardInput, Rect, CursorIcon};
use headless_editor::{
parse_tokens, Cursor, SimpleTextBuffer, TextBuffer, TokenTextBuffer, VirtualCursor,
};
use serde::{Deserialize, Serialize};... |
#[macro_use]
extern crate log;
use clap::{App, Arg};
use archiver::cli;
use archiver::config;
use archiver::ctx::Ctx;
use archiver::device;
use archiver::mailer::MailReport;
use archiver::mountable::Mountable;
use archiver::storage;
fn cli_opts<'a, 'b>() -> App<'a, 'b> {
cli::base_opts()
.about("Performs... |
use crate::{animation::MaybeTerminatingAnimation, backends::backend::Backend, frame::Frame};
pub struct Driver<Anim, Backend> {
animation: Anim,
backend: Backend,
frame: Frame,
}
impl<A, B> Driver<A, B>
where
A: MaybeTerminatingAnimation + Send + Sync,
B: Backend + Send + Sync,
{
pub fn new(an... |
#[doc = "Register `CR1` reader"]
pub type R = crate::R<CR1_SPEC>;
#[doc = "Register `CR1` writer"]
pub type W = crate::W<CR1_SPEC>;
#[doc = "Field `PE` reader - Peripheral enable"]
pub type PE_R = crate::BitReader<PE_A>;
#[doc = "Peripheral enable\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub ... |
use std::path::Path;
pub fn is_dir(path: &String) -> bool {
let p = Path::new(&path);
p.is_dir()
}
pub fn is_file(path: &String) -> bool {
let p = Path::new(&path);
p.is_file()
}
pub fn exist_path(path: &String) -> bool {
Path::new(path).exists()
}
|
use crate::common::did::DidValue;
use crate::common::error::prelude::*;
use crate::ledger::identifiers::cred_def::CredentialDefinitionId;
use crate::ledger::identifiers::rev_reg::RevocationRegistryId;
use crate::ledger::identifiers::rich_schema::RichSchemaId;
use crate::ledger::identifiers::schema::SchemaId;
use crate:... |
//! Handling for types that can be viewed as byte arrays.
use std::fmt;
use std::fmt::Debug;
use std::fmt::Formatter;
use std::fmt::Write;
use std::iter::Iterator;
use std::marker::PhantomData;
/// Types that can be constructed from a constant-length byte array.
pub trait Viewable: Sized {
/// Size of the byte ar... |
#[link(name = "sorting", kind = "static")]
extern "C" {
fn interop_sort(arr: *mut i32, n: u32);
}
pub fn sort_from_cpp(arr: &mut [i32]) {
unsafe {
// 传入必然有效的数组引用,并通过传入数组的长度来保证不会出现越界访问,从而保证函数内存安全
interop_sort(arr as *mut [i32] as *mut i32, arr.len() as u32);
}
}
fn main() {
let mut my_a... |
extern crate discord;
use std::hash::{Hash, Hasher};
use self::discord::model::{EmojiId, ServerId};
#[derive(Debug, Hash, PartialEq, Eq)]
pub enum Emoji {
Custom(CustomEmoji),
Unicode(String), // Some emoji span multiple chars
}
impl Emoji {
#[allow(dead_code)]
pub fn name(&self) -> &str {
ma... |
use std::fmt;
pub struct Connect4 {
board: Vec<Vec<Option<Player>>>,
last_player: Option<Player>,
winning_cells: Vec<Point>,
pub winner: Option<Player>,
}
#[derive(PartialEq, Debug)]
pub struct Point {
x: usize,
y: usize,
}
#[derive(Clone, Copy, PartialEq, Debug)]
pub enum Player {
Red,
... |
//!Handles the basic memory information multiboot2 tag.
///Represents the basic memory information multiboo2 tag.
#[repr(C)]
struct BasicMemoryInformation { //type = 4
tag_type: u32,
size: u32,
mem_lower: u32,
mem_upper: u32
}
|
#![feature(test)]
extern crate hopper;
extern crate tempdir;
extern crate test;
use self::test::Bencher;
macro_rules! generate_snd {
($t:ty, $fn:ident, $s:expr) => {
#[bench]
fn $fn(b: &mut Bencher) {
let dir = tempdir::TempDir::new("hopper").unwrap();
let (mut snd, _) = h... |
//! This modules holds structures related to source files, ways to analyze them
//! and to convert between [byte positions](`super::span::BytePos`) and
//! [character positions](`super::span::CharPos`).
use std::ops::Deref;
use std::path::Path;
use std::{fmt, vec};
use unicode_width::UnicodeWidthChar;
use super::spa... |
extern crate assert_cli;
use assert_cli::Assert;
const EXPECTED: &str = r#"
[](https://travis-ci.com/cargo-readme/test)
# readme-test
Test crate for cargo-readme
License: MIT
"#;
#[test]
fn badges() {
let args = ["readme", "--project-ro... |
pub mod tabled {
use tabled::builder::Builder;
#[inline]
pub fn build(columns: Vec<String>, data: Vec<Vec<String>>) -> String {
let mut b = Builder::from(data);
b.set_columns(columns);
let table = b.build();
table.to_string()
}
}
pub mod tabled_color {
use tabled_c... |
///// chapter 4 "structuring data and matching patterns"
///// program section:
//
fn main() {
let v: Vec<&str> = "the wizard of oz".split(' ').collect();
println!("{:?}", v);
let v: Vec<&str> =
"abc1def2ghi".split(|n: char| n.is_numeric()).collect();
println!("{:?}", v);
}
///// output sho... |
// q0215_kth_largest_element_in_an_array
struct Solution;
impl Solution {
pub fn find_kth_largest(mut nums: Vec<i32>, k: i32) -> i32 {
let k = k as usize;
let len = nums.len();
for i in 0..k {
for j in 1..len - i {
if nums[j - 1] > nums[j] {
... |
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT license.
*/
use std::arch::x86_64::{_mm_prefetch, _MM_HINT_T0};
/// Prefetch the given vector in chunks of 64 bytes, which is a cache line size
/// NOTE: good efficiency when total_vec_size is integral multiple of 64
#[inline]
p... |
use crate::maze::maze_genotype::MazeGenome;
#[derive(Debug, Clone)]
pub struct MazeQueue {
pub mazes: Vec<MazeGenome>,
current_maze_index: usize,
pub(crate) max_items_limit: u32,
total_individuals_added: u32,
}
impl MazeQueue {
pub fn new(mazes: Vec<MazeGenome>, max_items_limit: u32) -> MazeQueue ... |
// Copyright (C) 2017 1aim GmbH
//
// 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 wr... |
use alquitran::issues::Hint;
use alquitran::issues::Issue;
use alquitran::lint::lint_path_field;
#[test]
fn conforming_path_field() {
let bytes = b"Portable/Name.123\0\0";
let result = lint_path_field(&bytes[..]);
assert!(result.hints.is_empty());
assert!(result.issues.is_empty());
assert_eq!("Port... |
use cgmath::{Vector2, Vector3, Point3, Matrix4};
use crate::components::{Transform, FieldOfView, Image};
use super::ray::Ray;
pub struct RayGenerator {
matrix: Matrix4<f64>,
degrees: Vector2<f64>,
resolution: Vector2<u32>,
forward: Vector3<f64>,
origin: Point3<f64>,
left_to_right: Vector3<f64... |
use serde::Deserialize;
#[derive(Debug, Deserialize, Clone)]
#[serde(rename_all = "camelCase")]
pub struct FrameCreatedData {
pub brand_name: String,
pub colors: Vec<String>,
pub cover_image: Option<String>,
pub description: Option<String>,
pub has_case: bool,
pub materials: Vec<String>,
pub model_name: String,... |
use crate::component::entry::TxEntry;
use crate::pool::TxPool;
use ckb_logger::error;
use futures::future::Future;
use tokio::prelude::{Async, Poll};
use tokio::sync::lock::Lock;
pub enum PlugTarget {
Pending,
Proposed,
}
pub struct PlugEntryProcess {
pub tx_pool: Lock<TxPool>,
pub entries: Option<Vec... |
/*!
```rudra-poc
[target]
crate = "convec"
version = "2.0.1"
[[target.peer]]
crate = "crossbeam-utils"
version = "0.8.0"
[report]
issue_url = "https://github.com/krl/convec/issues/2"
issue_date = 2020-11-24
rustsec_url = "https://github.com/RustSec/advisory-db/pull/705"
rustsec_id = "RUSTSEC-2020-0125"
[[bugs]]
anal... |
// Copyright 2015-2016 Joe Neeman.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except accordin... |
pub mod id_generator_options;
pub mod snow_worker; |
use std::rc::Rc;
use std::cell::RefCell;
use crate::treenode::*;
// Reference: https://leetcode.com/problems/maximum-width-of-binary-tree/discuss/727053/DSF-and-BFS-With-Detailed-Explanation-or-Diagram
pub fn width_of_binary_tree(root: Option<Rc<RefCell<TreeNode>>>) -> i32 {
use std::cmp::max;
if root.is_none(... |
use fern;
use std::fs;
/*use std::io;*/
use log;
use chrono;
pub fn setup_logging(verbosity: u64, filename: String) -> Result<(), fern::InitError> {
let mut gobal_config = fern::Dispatch::new();
gobal_config = match verbosity {
0 => {
gobal_config
.level(log::LevelFilter::Info)
}
1 => gobal_config.leve... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.