text stringlengths 8 4.13M |
|---|
extern crate opc;
extern crate tokio_core;
extern crate tokio_io;
extern crate tokio_periodic;
extern crate futures;
extern crate ledshader;
use opc::{OpcCodec, Message, Command};
use futures::{Stream, Future, Sink, future, stream};
use tokio_io::AsyncRead;
use tokio_core::net::TcpStream;
use tokio_core::reactor::Core... |
#[doc = "Register `RCC_FDCANCKSELR` reader"]
pub type R = crate::R<RCC_FDCANCKSELR_SPEC>;
#[doc = "Register `RCC_FDCANCKSELR` writer"]
pub type W = crate::W<RCC_FDCANCKSELR_SPEC>;
#[doc = "Field `FDCANSRC` reader - FDCANSRC"]
pub type FDCANSRC_R = crate::FieldReader;
#[doc = "Field `FDCANSRC` writer - FDCANSRC"]
pub ty... |
use iced::widget::Tooltip;
use iced::Renderer;
use crate::gui::types::message::Message;
use crate::networking::types::address_port_pair::AddressPortPair;
use crate::networking::types::info_address_port_pair::InfoAddressPortPair;
use crate::StyleType;
/// Struct embedding all the info needed to build a row of the conn... |
use std::env;
use std::fmt::{self, Display};
use std::fs::{self, File};
use std::io::{BufWriter, Write};
use std::path::Path;
use std::process::exit;
const ADD: &'static str = "ADD";
const MUL: &'static str = "MUL";
const GET: &'static str = "GET";
const PRT: &'static str = "PRT";
const JIT: &'static str = "JIT";
cons... |
use std::collections::HashMap;
pub fn count(a: char, s: &str) -> u32 {
let mut sum = 0;
for x in s.chars() {
if x == a {
sum += 1;
}
}
sum
}
pub fn nucleotide_counts(s: &str) -> HashMap<char, usize> {
let mut a = 0;
let mut c = 0;
let mut g = 0;
let mut t = 0;
for x in s.chars() {
... |
use crate::features::syntax::{MiscFeature, StatementFeature};
use crate::parse::visitor::tests::assert_misc_feature;
use crate::parse::visitor::tests::assert_no_misc_feature;
use crate::parse::visitor::tests::assert_no_stmt_feature;
use crate::parse::visitor::tests::assert_stmt_feature;
mod pat;
#[test]
fn let_only()... |
/// An xyz collection.
#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub struct Vector<T> {
/// X
pub x: T,
/// Y
pub y: T,
/// Z
pub z: T,
}
|
//! calculating source logic
use std::convert::TryFrom;
// check file extension
use super::errors::StatsError;
use std::fs;
use std::fs::DirEntry;
use std::path::{Path, PathBuf};
#[derive(Debug)]
pub struct SrcStats {
// number of files
pub files: u32,
// number of lines of code
pub code: u32,
// n... |
#[derive(Debug, Clone)]
pub enum Route {
ProductDetail(i32),
HomePage,
}
impl spair::Routes<crate::App> for Route {
fn url(&self) -> String {
match self {
Self::ProductDetail(id) => format!("#product/{}", id),
Self::HomePage => "#".to_string(),
}
}
fn routin... |
const QUESTION_ID_SELECTOR: &str = r#"div.question__1Nd3.active__iWA5"#;
const QUESTION_DESCRIPTION: &str = r#"div.content__u3I1.question-content__JfgR"#;
pub fn parse_response_body(rep: Response) {
match rep.text() {
Ok(ref s) => {
let hh = Html::parse_fragment(s);
let q_des = des... |
mod error;
mod traits;
mod atomic;
mod hash;
mod storage;
mod working;
mod snapshots;
mod staging;
mod egg;
pub use crate::egg::Repository;
pub use crate::snapshots::SnapshotId;
pub use atomic::AtomicUpdate;
// Eggs architecture is currently based on one entry point, it need not be, for instance to take a snapshot, u... |
use std::io::{Read};
use std::thread;
use std::net::TcpListener;
use std::fs::{read_to_string};
extern crate clap;
use clap::{Arg, App};
use micro_http::{Request, Response, Body, StatusCode, MediaType, Version};
#[derive(Clone)]
struct ConfigServer {
server_ip: String,
default_404: String,
static_folder:String
}... |
use base64;
use failure::Error;
use html5ever::{
parse_document,
rcdom::{Handle, NodeData::Element, RcDom},
tendril::{Tendril, TendrilSink},
};
use image;
use reqwest::Client;
use serde_json;
use serializer::serialize;
use std::io::Cursor;
use std::str;
use std::process::Command;
// header! { (XApiKey, "x-... |
use blake2::digest::{Input, VariableOutput};
use blake2::VarBlake2b;
use failure::{Error, Fail};
use std::cmp::Ord;
use std::cmp::Ordering;
use std::convert::TryInto;
use std::result::Result;
use std::str::FromStr;
use std::u64;
const FILE_SEPARATOR: &str = "\x1C";
const GROUP_SEPARATOR: &str = "\x1D";
#[derive(Debug... |
use std::collections::HashSet;
#[aoc::main(09)]
pub fn main(input: &str) -> (usize, usize) {
solve(input)
}
#[aoc::test(09)]
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);... |
#[doc = "Register `CFGR2` reader"]
pub type R = crate::R<CFGR2_SPEC>;
#[doc = "Register `CFGR2` writer"]
pub type W = crate::W<CFGR2_SPEC>;
#[doc = "Field `ROVSE` reader - DMAEN"]
pub type ROVSE_R = crate::BitReader;
#[doc = "Field `ROVSE` writer - DMAEN"]
pub type ROVSE_W<'a, REG, const O: u8> = crate::BitWriter<'a, R... |
use thiserror::Error;
#[derive(Error, Debug)]
pub enum NameError {
#[error("Error parsing name entry: {0}")]
PEGError(#[from] peg::error::ParseError<peg::str::LineCol>),
#[error("Could not match {0}")]
#[allow(dead_code)]
Unmatched(String),
}
#[derive(Debug, PartialEq, Eq)]
pub enum NameFmt {
... |
// This file is part of rdma-core. 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/rdma-core/master/COPYRIGHT. No part of rdma-core, including this file, may be copied, modified, propagated, or distributed ... |
use std::env;
use std::fs;
use std::time;
type Num = i64;
fn main() {
let input_path: &str = &env::args().nth(1).unwrap();
let input_data = fs::read_to_string(input_path).unwrap();
let input = digits_of(input_data.trim());
part1(&input);
part2(&input);
}
fn char_to_digit(ch: char) -> Num {
a... |
use core::fmt;
use std::any::type_name;
use thiserror::Error;
use tokio::sync::oneshot;
use crate::{
envelop::{IntoBoxedMessage, TypeTag, TypeTagged},
Message,
};
pub trait DynError: TypeTagged {
fn description(&self) -> String;
}
pub trait StdSyncSendError: std::error::Error + TypeTagged + Send + Sync ... |
#[macro_use]
#[allow(dead_code)]
pub mod exec;
pub mod attr;
use crate::natives::{lua_noop, LuaArgs};
use super::ast;
use super::compile::{compile, CodeObj};
use super::lua_stdlib::stdlib;
use super::natives::{lua_assert, lua_print, lua_require};
use crate::compile::BC;
use natives::lua_type;
use numbers::lua_tonumber... |
use assembly_fdb::mem::{Database, Table};
use color_eyre::eyre::{eyre, WrapErr};
use mapr::Mmap;
use prettytable::{Cell as PCell, Row as PRow, Table as PTable};
use std::{fs::File, path::PathBuf};
use structopt::StructOpt;
/// Show all columns and their types for some table
#[derive(StructOpt)]
struct Options {
//... |
use serde_json::json;
use sqlx::{Pool, Row, Sqlite};
use std::sync::Arc;
use super::model::{DBTask, DBTaskTrait};
use crate::{
_utils::{database::DBOrderDirection, error::DataAccessError},
task::model::Task,
};
pub struct TaskRepository {
main_sql_db: Arc<Pool<Sqlite>>,
}
impl TaskRepository {
pub fn new(mai... |
fn main() {
let x = 5i;
// Standard 'if' statement, prefer no parens.
if x == 5i {
println!("x is five.");
} else {
println!("x is not five :(");
}
// This is cool, the 'expression' if looks a lot like
// a ternary expression though.
let y = if x == 5i { 10i } else { 15i };
// I wish Rust didn't do the ... |
#![feature(test)]
extern crate test;
use test::Bencher;
#[bench]
fn learn_lorem_ipsum(b: &mut Bencher) {
b.iter(|| {
let mut chain = lipsum::MarkovChain::new();
chain.learn(lipsum::LOREM_IPSUM)
})
}
#[bench]
fn learn_liber_primus(b: &mut Bencher) {
b.iter(|| {
let mut chain = lips... |
#[macro_export]
macro_rules! try_continue {
($opt:expr) => {
if let Some(v) = $opt {
v
} else {
continue;
}
};
}
#[macro_export]
macro_rules! try_continue_res {
($opt:expr) => {
if let Ok(v) = $opt {
v
} else {
continue... |
use std::{io::Read, };
// TODO: Error handling
pub fn read_exact<T>(sock: &mut T, buf: &mut [u8]) where T: Read {
let mut read = 0;
while read < buf.len() {
match sock.read(&mut buf[read..]) {
Ok(c) => read += c,
Err(_) => {}
}
}
} |
#![no_std]
#![no_main]
#![feature(never_type)]
mod error_system;
mod processor;
mod program;
extern crate panic_halt;
#[arduino_uno::entry]
fn main() -> ! {
let peripherals =
arduino_uno::Peripherals::take().expect("Cannot take Peripherals and handle error!");
program::run(peripherals).unwrap_or_els... |
//! Renders all roads by using a simple Bresenham line algorithm.
//!
//! LICENSE
//!
//! The code in this example file is released into the Public Domain.
use osmflat::{find_tag_by, FileResourceStorage, Node, Osm, Way};
use clap::Parser;
use itertools::Itertools;
use std::f64::consts::PI;
use std::fs::File;
use std... |
// SPDX-License-Identifier: MIT
use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use uuid::Uuid;
use crate::cipher::CipherString;
#[derive(Debug, Serialize)]
pub(crate) struct PreloginRequest<'a> {
pub email: &'a str,
}
#[derive(Debug, Deserialize)]
pub(crate) struct PreloginResponse {
#[se... |
use std::ops::Deref;
struct MyBox<T>(T);
impl<T> MyBox<T> {
fn new(x: T) -> MyBox<T> {
MyBox(x)
}
}
impl<T> Deref for MyBox<T> {
type Target = T;
fn deref(&self) -> &T {
&self.0
}
}
struct DerefBox<T> {
name: T,
}
impl<T> DerefBox<T> {
fn new(x: T) -> DerefBox<T> {
... |
use crate::{BoxFuture, CtxTransaction, Entity, Insert, InsertMut, Remove, Result};
pub trait IteratorExt: Iterator {
fn insert_all<'a, 'b, E>(
self,
trx: &'b mut CtxTransaction<'a>,
track: &'b E::TrackCtx,
) -> BoxFuture<'b, Result<usize>>
where
CtxTransaction<'a>: Insert<E>... |
/// An enum to represent all characters in the SupplementalPunctuation block.
#[derive(Debug, Clone, Copy, Hash, PartialEq, Eq)]
pub enum SupplementalPunctuation {
/// \u{2e00}: '⸀'
RightAngleSubstitutionMarker,
/// \u{2e01}: '⸁'
RightAngleDottedSubstitutionMarker,
/// \u{2e02}: '⸂'
LeftSubstit... |
use std::io::{self, BufRead};
use std::path::Path;
use std::{fs::File, path::PathBuf};
use serde::Serialize;
pub struct Snippet {
path: PathBuf,
}
impl Snippet {
pub fn new(path: PathBuf) -> Snippet {
Snippet { path }
}
pub fn make_json(&mut self) -> String {
#[derive(Debug, Serializ... |
/*
* Copyright (c) Meta Platforms, Inc. and affiliates.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree.
*/
use core::fmt;
use serde::Deserialize;
use serde::Serialize;
use crate::Displayable;
use crate::F... |
use std::f32::consts::PI;
use std::error::Error;
use glium::*;
use glium::backend::Facade;
use glium::uniforms::EmptyUniforms;
use glium::index::{PrimitiveType, NoIndices};
#[derive(Copy, Clone)]
struct Vertex {
position : [f32; 2],
}
implement_vertex!(Vertex, position);
const VERTEX_SHADER_SRC : &'static str = ... |
extern crate serde;
extern crate serde_derive;
use serde_derive::*;
extern crate mio_httpc;
use mio_httpc::CallBuilder;
#[derive(Serialize, Deserialize, Debug)]
pub struct Comic {
pub num: i32,
pub title: String,
pub alt_text: String,
pub transcript: String,
pub img: String,
pub year: i32,
... |
//! Syntax sugar to make your Rust life more sweet.
//!
//! # Usage
//! ```rust
//! use sugar::*;
//! ```
//! # Sugars
//!
//! ## Collections construct
//! ```
//! use sugar::*;
//!
//! // vec construction
//! let v = vec![1, 2, 3];
//!
//! // vec of boxed value
//! let vb = vec_box![1, 2, 3];
//!
//! // hashmap constr... |
// Copyright (c) 2019 Intel Corporation. All rights reserved.
// Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.
//
// Copyright 2017 The Chromium OS Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE-BSD-3-Clause file.... |
use std::fmt;
static NUMERAL_VALUES: [(&'static str, u32); 13] = [
("I", 1), ("IV", 4), ("V", 5), ("IX", 9), ("X", 10), ("XL", 40), ("L", 50),
("XC", 90), ("C", 100), ("CD", 400), ("D", 500), ("CM", 900), ("M", 1000)
];
pub struct Roman(u32);
impl From<u32> for Roman {
fn from(num: u32) -> Self {
... |
// Copyright 2019 Google LLC
//
// 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
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in ... |
/*
* Copyright 2017-2018 Ben Ashford
*
* 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 accor... |
use std::collections::HashSet;
use itertools::Itertools;
use super::prelude::*;
/// Phase for end-game assassination.
pub struct Assassination {}
/*
How assassination works now:
- Can assassinate any role but Lancelot and declared Arthur (or "no assassination target")
- They have to get the priority target and one ... |
//! filterload 暂时设定为固定值
//!
//send("filterload",
//"02" # ........ Filter bytes: 2
//+ "b50f" # ....... Filter: 1010 1101 1111 0000
//+ "0b000000" # ... nHashFuncs: 11
//+ "00000000" # ... nTweak: 0/none
//+ "00" # ......... nFlags: BLOOM_UPDATE_NONE
//)
//pub struct FilterLoad {
// pub bytes: u8,
// pub filter... |
use std::path::{Path, PathBuf};
use std::ffi::OsStr;
use std::collections::BTreeMap;
use options::Options;
use std::io;
use std::fs::{remove_file, remove_dir, create_dir_all, read_link};
use std::os::unix::fs::symlink;
pub mod argument_error;
pub mod options;
pub fn lndir(sources: Vec<PathBuf>, destination: PathBuf... |
use anyhow::Result;
use ignore::{
overrides::{Override, OverrideBuilder},
types::{Types, TypesBuilder},
};
use std::path::PathBuf;
pub struct SearchConfig {
pub pattern: String,
pub path: PathBuf,
pub case_insensitive: bool,
pub case_smart: bool,
pub overrides: Override,
pub types: Type... |
#[doc = r" Value read from the register"]
pub struct R {
bits: u32,
}
#[doc = r" Value to write to the register"]
pub struct W {
bits: u32,
}
impl super::ALTPADCFGM {
#[doc = r" Modifies the contents of the register"]
#[inline]
pub fn modify<F>(&self, f: F)
where
for<'w> F: FnOnce(&R, &'... |
/// PayloadCommitVerification represents the GPG verification of a commit
#[derive(Debug, Default, Clone, Serialize, Deserialize)]
pub struct PayloadCommitVerification {
pub payload: Option<String>,
pub reason: Option<String>,
pub signature: Option<String>,
pub signer: Option<crate::payload_user::Paylo... |
#[doc = "Register `SR` reader"]
pub type R = crate::R<SR_SPEC>;
#[doc = "Register `SR` writer"]
pub type W = crate::W<SR_SPEC>;
#[doc = "Field `IRS` reader - Interrupt rising edge status The flag is set by hardware and reset by software. Note: If this bit is written by software to 1 it will be set."]
pub type IRS_R = c... |
use reqwest::{blocking::Client, StatusCode};
use serde::{Deserialize, Serialize};
#[derive(Serialize, Deserialize)]
pub struct PackageInfo {
pub namespace: String,
pub name: String,
pub full_name: String,
pub owner: String,
pub package_url: String,
pub date_created: String,
pub date_updated... |
use std::collections::HashMap;
use std::num;
use std::str;
static INPUT: &str = include_str!("input");
fn main() {
println!("Day 6, Part 1: {}", part1(&INPUT).unwrap());
println!("Day 6, Part 2: {}", part2(&INPUT, 10000).unwrap());
}
#[derive(Hash, PartialEq, Eq)]
struct Point(i32, i32);
impl str::FromStr f... |
mod cpu;
mod ppu;
mod apu;
mod cartridge;
mod input;
mod screen;
mod audio;
mod state;
use cpu::Cpu;
use ppu::Ppu;
use apu::Apu;
use cartridge::{check_signature, get_mapper};
use input::poll_buttons;
use screen::{init_window, draw_pixel, draw_to_window};
use state::{save_state, load_state, find_next_filename, find_las... |
#[macro_use]
extern crate lazy_static;
pub mod evaluator;
pub mod exprtoken_processor;
pub mod parser;
pub mod tokenizer;
pub mod val;
#[cfg(test)]
mod tests {
use crate::{evaluator::Environment, parser::parse_expr, tokenizer::tokenize_expr, val::Val};
#[test]
fn four_divided_by_2_plus_2() {
let t... |
//! A Rust client for interacting with Dogstatsd
//!
//! Dogstatsd is a custom `StatsD` implementation by `DataDog` for sending metrics and events to their
//! system. Through this client you can report any type of metric you want, tag it, and enjoy your
//! custom metrics.
//!
//! ## Usage
//!
//! Build an options str... |
pub fn add_two(a :i32) -> i32 {
a + 2
}
//by cfg attribute, compiles only test code when run tests.
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn it_works() {
assert_eq!(4,add_two(2));
}
}
|
use std::old_io as io;
fn main () {
let input = io::stdin().read_line().ok().expect("");
let input_num: Result<u32, _> = input.trim().parse();
let num: u32 = input_num.ok().expect("Well...");
permutations(num);
}
fn permutations(n: u32) {
let numbers: Vec<u32> = (1..n+1).collect();
let count = numbers.permut... |
#![no_main]
#![no_std]
extern crate cortex_m_rt;
extern crate panic_halt;
use cortex_m_rt::{entry, exception};
#[entry]
fn foo() -> ! {
loop {}
}
#[exception]
fn SecureFault() {}
//~^ ERROR no variant or associated item named `SecureFault`
|
/*
* Copyright (C) 2019-2021 TON Labs. All Rights Reserved.
*
* Licensed under the SOFTWARE EVALUATION License (the "License"); you may not use
* this file except in compliance with the License.
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an ... |
use crate::{Error, mock::*};
use frame_support::{assert_ok, assert_noop};
use super::*;
#[test]
fn create_claim_works(){
new_test_ext().execute_with(|| {
let claim: Vec<u8> = vec![0,1];
assert_ok!(PoeModule::create_claim(Origin::signed(1),claim.clone()));
assert_eq!(
Proofs::<T... |
use std::{
convert::TryInto,
ops::DerefMut,
path::{Path, PathBuf},
};
use bson::{rawdoc, Document, RawDocument, RawDocumentBuf};
use futures_util::{stream, TryStreamExt};
use mongocrypt::ctx::{Ctx, KmsProvider, State};
use rayon::ThreadPool;
use tokio::{
io::{AsyncReadExt, AsyncWriteExt},
sync::{on... |
#![allow(clippy::cast_sign_loss)]
#![allow(clippy::cast_precision_loss)]
#![allow(clippy::cast_possible_truncation)]
#![allow(clippy::cast_possible_wrap)]
use std::iter;
fn main() {
let start_time = std::time::Instant::now();
let signal = String::from("597558969172404368835901288019441283149602096977487723458... |
//
//! `file_offset` provides a platform-independent way of atomically reading and
//! writing files at specified offsets.
//!
//! ```
//! use file_offset::FileExt;
//! use std::fs::File;
//! use std::str;
//!
//! let mut buffer = [0; 2048];
//! let f = File::open("src/lib.rs").unwrap();
//! f.read_offset(&mut buffer, ... |
use aoc::read_data;
use std::collections::HashSet;
use std::convert::Infallible;
use std::error::Error;
use std::num::ParseIntError;
use std::str::FromStr;
#[derive(Debug, Clone)]
enum Operation {
Acc,
Jmp,
Nop,
}
impl FromStr for Operation {
type Err = Infallible;
// 4 shiny brown bags
fn fro... |
#[macro_use]
extern crate anyhow;
#[macro_use]
extern crate diesel;
#[macro_use]
extern crate diesel_migrations;
#[macro_use]
extern crate thiserror;
mod commands;
mod discord;
mod service;
mod storage;
use std::env;
fn main() -> anyhow::Result<()> {
// do not overwrite the environment variables that have alread... |
use std::collections::HashSet;
fn combinations(containers: &[u32], total: u32, containers_used: Option<u32>) -> u32 {
let mut count = 0;
let mut unique = HashSet::new();
for mask in 0..2u32.pow(containers.len() as u32) {
let mut sum = 0;
let mut combo = Vec::new();
for i in 0..conta... |
#![allow(dead_code)]
mod accounts;
pub mod authentication_barcode;
pub mod authentication_nfc;
pub mod authentication_password;
mod categories;
pub mod env;
mod errors;
pub mod mail;
mod prices;
mod products;
mod schema;
mod sessions;
pub mod stats;
pub mod transactions;
mod utils;
pub use self::accounts::{Account, P... |
mod cli_handler;
mod imply;
pub mod interface;
pub mod utility;
pub mod file;
// use termion::terminal_size;
fn main() {
cli_handler::run();
}
|
use crate::parser::parser_defs;
use crate::parser::svg_util;
pub fn parse_svg_rect(element: &quick_xml::events::BytesStart) -> Result<parser_defs::SVGShape, String> {
let attribute_list = element.attributes();
let color: parser_defs::SVGColor = parser_defs::SVGColor {r: 0, g: 0, b: 0, a: 0};
let mu... |
mod utils;
use utils::{ensure_empty, ensure_empty_iter, next_word_or_err, trim_line_endings};
use std::fs::File;
use std::io::Read;
use std::io::{BufRead, BufReader};
enum FormatType {
ASCII,
BinaryLittleEndian,
BinaryBigEndian,
}
type FormatVersion = String;
type Format = (FormatType, FormatVersion);
type ... |
extern crate notify;
extern crate tempdir;
extern crate tempfile;
extern crate time;
use notify::*;
use std::thread;
use std::sync::mpsc::{channel, Receiver};
use tempdir::TempDir;
fn check_for_error(rx:&Receiver<notify::Event>) {
while let Ok(res) = rx.try_recv() {
match res.op {
Err(e) => pa... |
pub fn find_min_height_trees(n: i32, edges: Vec<Vec<i32>>) -> Vec<i32> {
if n == 1 {
return vec![0];
} else if n == 2 {
return vec![0, 1];
}
use std::collections::*;
let n = n as usize;
let mut neighbours = vec![HashSet::new(); n];
for edge in &edges {
neighbours[edg... |
use std::fmt;
use std::process::Command;
use crate::error::OptionsError;
use crate::units::{Second, Unit};
#[cfg(not(windows))]
pub const DEFAULT_SHELL: &str = "sh";
#[cfg(windows)]
pub const DEFAULT_SHELL: &str = "cmd.exe";
/// Shell to use for executing benchmarked commands
#[derive(Debug)]
pub enum Shell {
/... |
use shorthand::ShortHand;
#[derive(ShortHand)]
struct TupleStruct<'a, T>(u64, usize, &'a T);
fn main() {}
|
#[macro_use]
extern crate lazy_static;
extern crate quickcheck;
use std::fs::File;
use std::io::{BufRead, BufReader};
use std::path::{Path};
use quickcheck::{quickcheck, TestResult};
extern crate hyphenation;
use hyphenation::*;
fn fiat_io(lang: Language) -> Corpus { load::language(lang).unwrap() }
lazy_static! {
... |
#[doc = "Register `TX_ORDSET` reader"]
pub type R = crate::R<TX_ORDSET_SPEC>;
#[doc = "Register `TX_ORDSET` writer"]
pub type W = crate::W<TX_ORDSET_SPEC>;
#[doc = "Field `TXORDSET` reader - TXORDSET"]
pub type TXORDSET_R = crate::FieldReader<u32>;
#[doc = "Field `TXORDSET` writer - TXORDSET"]
pub type TXORDSET_W<'a, R... |
use std::{fs::{File, self}, io::Write};
fn epoch_as_string() -> String {
let now = std::time::SystemTime::now();
let since_epoch = now.duration_since(std::time::UNIX_EPOCH).unwrap();
let since_epoch_ms = since_epoch.as_secs() * 1000 + since_epoch.subsec_nanos() as u64 / 1_000_000;
since_epoch_ms.to_st... |
// Copyright (c) Facebook, Inc. and its affiliates.
//
// This source code is licensed under the MIT license found in the
// LICENSE file in the "hack" directory of this source tree.
use hhbc_by_ref_hhas_adata::HhasAdata;
use hhbc_by_ref_hhas_attribute::HhasAttribute;
use hhbc_by_ref_hhas_class::HhasClass;
use hhbc_by... |
// Copyright 2014-2018 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution.
//
// 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>,... |
use crate::image_utils;
use druid::{Point, Rect, Size, Vec2};
use image::{DynamicImage, GenericImage, GenericImageView};
use imageproc::rect::Rect as ImRect;
use std::sync::Arc;
use super::{CopyMode, SelectionShape};
impl SelectionShape for Rect {
fn description(&self) -> String {
format!(
"X:... |
#[doc = "Register `SHIFTR` writer"]
pub type W = crate::W<SHIFTR_SPEC>;
#[doc = "Field `SUBFS` writer - Subtract a fraction of a second These bits are write only and is always read as zero. Writing to this bit has no effect when a shift operation is pending (when SHPF = 1, in RTC_ICSR). The value which is written to SU... |
/*!
Crate `linregress` provides an easy to use implementation of ordinary
least squared linear regression with some basic statistics.
See [`RegressionModel`] for details.
The builder [`FormulaRegressionBuilder`] is used to construct a model from a
table of data and a R-style formula. Currently only very simp... |
const TOLERANCE: f64 = 1e-9;
//static SPATIAL_TOLERANCE: f64 = 0.5e-3; // 50 cm
pub mod providers;
#[derive(PartialOrd,Copy,Clone,Debug)]
pub struct Coord{
pub lat: f64,
pub lon: f64
}
impl std::ops::Sub for Coord {
type Output = Coord;
fn sub(self, other: Coord) -> Coord {
Coord{lat:self.lat-... |
use core::f32;
use async_trait::async_trait;
use messagebus::{
derive::Message,
error::{self, StdSyncSendError},
AsyncHandler, Bus, Message,
};
use thiserror::Error;
#[derive(Debug, Error, messagebus::derive::Error)]
enum Error {
#[error("Error({0})")]
Error(anyhow::Error),
}
impl<M: Message, E: ... |
use crate::*;
const TIMER_BASE: u32 = 0x7E003000;
const TIMER_LOW: u32 = TIMER_BASE + 0x4;
const TIMER_HIGH: u32 = TIMER_BASE + 0x8;
pub fn wait_cycles(mut n: u32) {
while n > 0 {
unsafe { asm!("nop"); }
n -= 1;
}
}
pub fn get_sys_time() -> u64 {
let mut h = mmio::read(TIMER_HIGH);
le... |
use std::fs::File;
use matfile;
use dsp::signal::Signal;
use crate::error::{Error, ErrorKind, Result};
/// Read data from mat file
pub fn read_mat(fname: &str, array_name: &str, sample_rate: usize) -> Result<Signal> {
let file = File::open(fname)?;
let mat_file = matfile::MatFile::parse(file).unwrap();
le... |
use std::error::Error;
use std::io;
use std::io::BufRead;
use std::io::BufReader;
use std::fs::File;
use std::num;
use std::path::Path;
use crate::data::*;
pub type CluesLine = Vec <LineSize>;
#[ derive (Debug) ]
pub struct Clues {
rows: Vec <CluesLine>,
cols: Vec <CluesLine>,
}
impl Clues {
pub fn load_file (
... |
use std::io::{self, Read};
const NUM_CYCLES: usize = 2017;
const NUM_CYCLES2: usize = 50_000_000;
fn main() {
let mut input = String::new();
io::stdin().read_to_string(&mut input).unwrap();
let step_count = parse(&input);
println!("Answer to P1: {}", get_part1(step_count as usize));
println!("Ans... |
use super::prelude::*;
#[derive(Debug, Default, PartialEq, Clone)]
pub struct Program {
pub statements: Vec<Stmt>,
}
impl Display for Program {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
write!(
f,
"{}",
self.statements
.iter()
... |
// Copyright (c) 2019 Chaintope Inc.
use serde::de;
use serde::de::{Error, SeqAccess, Unexpected, Visitor};
use std::fmt;
pub struct ByteBufVisitor;
/// refer to https://github.com/baidu/rust-sgx-sdk/blob/9d4fa0f603e44bb82efae9d913c586a498b7d9da/third_party/serde-rs/serde/test_suite/tests/bytes/mod.rs
impl<'de> Visi... |
pub fn find_saddle_points(input: &[Vec<u64>]) -> Vec<(usize, usize)> {
if !input.is_empty() && !input[0].is_empty() {
let max_points = input.iter().enumerate().map(|(r, row)| (r, row.iter().max().unwrap())).collect::<Vec<_>>();
(0..input[0].len()).flat_map(|c| {
let min = input.iter().ma... |
use serde::{de::DeserializeOwned, Serialize};
use std::io::{self, Read, Write};
pub type Result<T> = io::Result<serde_json::Result<T>>;
pub trait RecieveMsg {
fn recieve<M: DeserializeOwned>(&mut self) -> Result<M>;
}
pub trait SendMsg {
fn send<M: Serialize>(&mut self, msg: &M) -> Result<()>;
}
impl Reciev... |
//! Logging over an i.MX RT serial interface
//!
//! The crate provides a [`log`](https://crates.io/crates/log) implementation that
//! transfers data over UART. It's an extension to the [`imxrt-hal`](https://crates.io/crates/imxrt-hal)
//! crate. The crate provides two logging implementations:
//!
//! - a simple, [blo... |
struct Program {
pub vars: Vec<Variable>,
pub varindex: HashMap<String, Vec<usize>>,
//pub output: Arena<Expression>
}
impl Program {
pub fn new() -> Program {
Program {
vars: Vec::new(),
varindexer: HashMap::new()
}
}
/// Add a variable into the program... |
use super::Config;
use crate::components::Component;
use std::convert::TryFrom;
use unicode_width::UnicodeWidthChar;
pub struct ProgressBar {
config: Config,
}
pub struct ProgressBarBuilder {
config: Config,
}
#[derive(Debug)]
pub struct ProgressBarBuildError;
impl ProgressBar {
pub fn new() -> Self {
... |
use uncertain::{PointMass, Uncertain};
#[test]
#[should_panic]
fn test_too_large_pr_panics() {
let x = PointMass::new(true);
x.pr(1.2);
}
#[test]
#[should_panic]
fn test_negative_pr_panics() {
let x = PointMass::new(true);
x.pr(-0.3);
}
#[test]
#[should_panic]
fn test_nagative_expect_precision_panics... |
// Copyright (C) 2020-2021 Parity Technologies (UK) Ltd.
// Copyright (C) 2021 Subspace Labs, Inc.
// 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
//
... |
#![cfg(feature = "std")]
use tabled::settings::{formatting::Justification, object::Columns, Color, Modify};
use crate::matrix::Matrix;
use testing_table::test_table;
test_table!(
justification,
Matrix::new(3, 3).with(Justification::new('#')),
"+---+----------+----------+----------+"
"| N | column 0 |... |
// 2019-01-09
// On veut parcourir les variantes de Option<T> avec match.
// Écrivons une fonction qui prend une Option<i32> et incrémente la valeur contenue
// s'il y en a une. S'il n'y en a pas, la fonction renverra juste la valeur None.
// La fonction accepte une variante d'Option<i32> comme paramètre. Un entier.... |
macro_rules! set {
( $( $x:expr ),* ) => {
{
let mut temp_hs = HashSet::new();
$(
temp_hs.insert($x);
)*
temp_hs
}
};
}
macro_rules! hash_map {
( $( $x:expr => $y:expr ),* ) => {
{
let mut temp_map = HashM... |
use std::{
fs::File,
io::{stderr, Write},
path::Path,
};
use crate::wasm::il::{
module::{Module, ModuleList, Module_},
stm::Stm_,
util::WasmType,
};
use super::{
print_exp::print_exp,
print_stm::print_stm,
utils::{print_locals, print_params},
};
pub fn print_module(module: &Module... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.