text stringlengths 8 4.13M |
|---|
use std::{
error,
io::{self, prelude::*},
net, process, str,
};
extern crate ctrlc;
fn main() -> Result<(), Box<dyn error::Error>>{
let mut stream = net::TcpStream::connect("127.0.0.1:50000")?;
let s = stream.try_clone()?;
ctrlc::set_handler(move || {
s.shutdown(net::Shutdown::Both).unw... |
use config::Config;
use hbs::Template;
use rustc_serialize::json::{Json, ToJson};
use iron::prelude::*;
use std::io::prelude::*;
use std::str::FromStr;
use iron::status;
use rss::Channel;
use hyper::client::Client;
use std::collections::BTreeMap;
pub fn index(req: &mut Request) -> IronResult<Response> {
let mut ... |
// **services** are a collection of
// **ports** aro an abstract collection of
// **operations** aro an abstract action definition
mod wsdl;
#[cfg(test)]
mod tests {
#[test]
fn it_works() {
assert_eq!(2 + 2, 4);
}
}
|
use std::collections::HashSet;
use std::iter::FromIterator;
use std::u32;
use std::cmp;
pub fn problem_044() -> u32 {
let pentagonal: HashSet<u32> = HashSet::from_iter((1..10000).map(|n| n * (3 * n - 1) / 2 as u32));
let mut min_diff = u32::MAX;
for i in 2..10000 {
let pent_i: u32 = i * (3 * i -... |
use ast::Ast;
#[allow(unused_imports)]
use nom::*;
use datatype::Datatype;
use std::str::FromStr;
use std::str;
named!(float_raw<f64>,
do_parse!(
float_string: float_structure >>
(f64::from_str(float_string.as_str()).unwrap())
)
);
named!(float_structure<String>,
do_parse!(
basis:... |
use super::{DatabaseClient, UserDefinedFunctionClient};
use crate::clients::*;
use crate::operations::*;
use crate::requests;
use crate::resources::ResourceType;
use crate::CosmosEntity;
use crate::ReadonlyString;
use azure_core::{pipeline::Pipeline, Context, HttpClient, Request};
use serde::Serialize;
/// A client fo... |
pub mod sphere;
use super::ray::Ray;
pub trait Shape {
fn intersect(&self, r: &Ray) -> Option<f64>;
}
|
const HAND_CAPACITY : usize = 7;
use super::{Tile, TileBag};
/// Stores a vector of tiles
pub struct Hand {
tiles : Vec<Tile>,
}
impl Hand {
/// Create a new empty Hand
pub fn new() -> Hand {
Hand {
tiles : Vec::with_capacity(HAND_CAPACITY),
}
}
/// Take tiles from a b... |
use crate::utils;
pub mod button;
pub mod card;
use button::Button;
use card::Card;
use utils::{BotUser};
use serde::ser::{Serialize ,Serializer};
use serde_json::Value;
use log::{info, warn};
use std::fmt;
use ureq::*;
use std::sync::Arc;
pub enum MessagingType {
RESPONSE,
UPDATE,
MESSAGETAG,
}
impl fmt... |
#[derive(Default, Debug)]
struct Passport {
birth_year: Option<String>,
issue_year: Option<String>,
expiration_year: Option<String>,
height: Option<String>,
hair_color: Option<String>,
eye_color: Option<String>,
passport_id: Option<String>,
country_id: Option<String>
}
#[derive(Debug)]
... |
pub mod rejection;
pub mod todo; |
fn main(){
let msg = "Tutorials Point has good tutorials".to_string();
let mut i = 1;
for token in msg.split_whitespace(){
println!("token {} {}",i,token);
i+=1;
}
}
|
//! MIPS specific instructions
macro_rules! define_instruction {
// specify a different function name
($inst: expr, $fun: ident) => {
#[doc = "invoke `"]
#[doc = $inst]
#[doc = "` instruction"]
pub unsafe fn $fun() {
llvm_asm!($inst : : : : "volatile");
}
... |
//! # nrfxlib - a Rust library for the nRF9160 interface C library
//!
//! This crate contains wrappers for functions and types defined in Nordic's
//! libmodem, which is part of nrfxlib.
//!
//! The `nrfxlib_sys` crate is the auto-generated wrapper for `nrf_modem_os.h`
//! and `nrf_socket.h`. This crate contains Rusti... |
//! Calculate the crc64 checksum of the given data, starting with the given crc.
//!
//! Implements the CRC64 used by Redis, which is the variant with "Jones" coefficients and init value of 0.
//!
//! Specification of this CRC64 variant follows:
//!
//! ```text
//! Name: crc-64-jones
//! Width: 64 bites
//! Poly: 0xad9... |
use pasture_core::meta::Metadata;
use std::fmt::Display;
/// `Metadata` implementation for ascii files
/// In general there is no metadata in ascii files.
#[derive(Debug, Clone)]
pub struct AsciiMetadata {}
impl AsciiMetadata {
pub fn new() -> Self {
Self {}
}
}
impl Display for AsciiMetadata {
... |
use std::io::{stdin, Read, StdinLock};
use std::str::FromStr;
#[allow(dead_code)]
struct Scanner<'a> {
cin: StdinLock<'a>,
}
#[allow(dead_code)]
impl<'a> Scanner<'a> {
fn new(cin: StdinLock<'a>) -> Scanner<'a> {
Scanner { cin: cin }
}
fn read<T: FromStr>(&mut self) -> Option<T> {
let t... |
// Copyright 2021 The Matrix.org Foundation C.I.C.
//
// 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... |
mod airing_schedule;
mod character;
pub mod embeds;
mod media;
pub mod pagination;
mod staff;
mod studio;
mod types;
mod user;
pub use pagination::AniListPagination;
pub use types::{
AniListCharacterView, AniListMediaView, AniListPaginationKind, AniListStaffView,
AniListUserView,
};
|
extern crate docopt;
extern crate rand;
extern crate rustc_serialize;
use rand::Rng;
const USAGE: &'static str = "
Usage:
pi <num-samples>
pi --help
Options:
-h --help Show this screen.
<num-samples> Number of samples.
";
#[derive(Debug, RustcDecodable)]
struct Args {
arg_num_samples: u64,
}... |
mod database;
mod get_data;
use anyhow::anyhow;
use chrono::{DateTime, Utc};
use get_data::process;
use icalendar::{Calendar, Component, Event};
use std::collections::HashMap;
use std::str::FromStr;
use tide::{http::Mime, Error, Request, Response, StatusCode};
#[derive(serde::Serialize, serde::Deserialize, Debug, Clo... |
extern crate failure;
use std::collections::HashMap;
use std::env;
use std::fs::File;
use std::io::{BufRead, BufReader};
use failure::Error;
fn matches(a: &str, b: &str) -> String {
a.chars()
.zip(b.chars())
.filter(|(x, y)| x == y)
.map(|(x, _)| x)
.collect()
}
fn main() -> Resu... |
// This file is part of Substrate.
// Copyright (C) 2017-2020 Parity Technologies (UK) Ltd.
// SPDX-License-Identifier: GPL-3.0-or-later WITH Classpath-exception-2.0
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the F... |
use clap::Args;
use crate::{
arrow::{polars::nonnull_schema, writer::open_parquet_writer},
prelude::*,
};
use polars::prelude::*;
static ALL_ISBNS_FILE: &str = "book-links/all-isbns.parquet";
/// Link records to ISBN IDs.
#[derive(Debug, Args)]
#[command(name = "link-isbn-ids")]
pub struct LinkISBNIds {
... |
pub mod languages;
pub mod link_checker;
pub mod markup;
pub mod search;
pub mod slugify;
pub mod taxonomies;
use std::collections::HashMap;
use std::path::{Path, PathBuf};
use globset::{Glob, GlobSet, GlobSetBuilder};
use serde_derive::{Deserialize, Serialize};
use syntect::parsing::SyntaxSetBuilder;
use toml::Value... |
pub mod checks;
pub mod config;
pub mod consts;
pub mod event_handler;
pub mod framework;
pub mod store;
|
/*
* 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
*/
/// UsageLambdaHour : Number of lambda functions and sum of the invocations of all lambda functions for ... |
// A Pythagorean triplet is a set of three natural numbers, a < b < c, for which,
//
// a2 + b2 = c2
// For example, 32 + 42 = 9 + 16 = 25 = 52.
//
// There exists exactly one Pythagorean triplet for which a + b + c = 1000.
// Find the product abc.
fn main() {
let limit = 1000;
let mut solution = 0;
for a ... |
#[doc = "Register `RESP%s` reader"]
pub type R = crate::R<RESP_SPEC>;
#[doc = "Field `CARDSTATUS` reader - see Table404."]
pub type CARDSTATUS_R = crate::FieldReader<u32>;
impl R {
#[doc = "Bits 0:31 - see Table404."]
#[inline(always)]
pub fn cardstatus(&self) -> CARDSTATUS_R {
CARDSTATUS_R::new(sel... |
pub mod day1;
pub mod day2;
pub mod day3;
pub mod day4;
pub mod day5;
pub mod day6;
pub mod graph;
pub mod intcode;
|
extern crate pkg_config;
use std::env;
fn main () {
let target = env::var("TARGET").unwrap();
if target.ends_with("-apple-darwin") {
// Use libosxfuse on OS X
pkg_config::find_library("osxfuse").unwrap();
} else if target.ends_with("-unknown-linux-gnu") || target.ends_with("-unknown-freebs... |
use assert_cmd::Command;
use std::fs::read_dir;
use std::fs::File;
use tempdir::TempDir;
#[cfg(not(target_os = "windows"))]
#[test]
fn test_sort() {
let dir = TempDir::new("nomino_test").unwrap();
let inputs = vec![
"Nomino (2020) S1.E1.1080p.mkv",
"Nomino (2020) S1.E2.1080p.mkv",
"Nom... |
#[macro_use] extern crate rocket;
mod config;
mod faces;
use faces::Faces;
use rocket::data::Data;
use rocket_contrib::json::Json;
use serde::{Serialize,Deserialize};
#[derive(Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
struct FaceResponse {
engagement_score: usize
}
#[post("/engagement/score",... |
use crate::{instance, instance::AtomMut};
use std::{
cell::{Ref, RefMut},
sync::Arc,
};
thread_local! {
static ENGINE: Arc<instance::Engine> = Arc::new(instance::Engine::new());
}
pub fn batch() -> Batch {
ENGINE.with(|engine| Batch::new(engine.batch()))
}
pub fn react(f: impl FnMut() + 'static) {
... |
use crate::msg::Fee;
use cosmwasm_std::Uint128;
use cosmwasm_std::{StdError, StdResult};
use std::convert::TryFrom;
pub const DEFAULT_TRANSACTION_FEE: Fee = Fee {
commission_rate_nom: Uint128(3),
commission_rate_denom: Uint128(1000),
};
pub const DEFAULT_MAX_QUERY_PAGE_SIZE: u16 = 10_u16;
pub const DEFAULT_MAX... |
use std::ops;
use std::fmt;
use std::mem::{self, MaybeUninit};
#[derive(Debug,Clone,PartialEq,Eq)]
pub struct Vector([i32; 3]);
#[derive(Debug,Clone,PartialEq,Eq)]
pub struct Matrix([i32; 9]);
impl Vector {
pub fn new(x: i32, y: i32, z: i32) -> Self {
Self([x, y, z])
}
pub fn zeros() -> Self {
... |
let args: Vec<String> = env::args().collect();
match args.len() {
1 => panic!("Please pass port number to command line."),
_ => (),
}
let port = &args[1];
let address = format!("localhost:{}", port);
let listener = TcpListener::bind(address)?;
// |
#[doc = "Register `CR2` reader"]
pub type R = crate::R<CR2_SPEC>;
#[doc = "Register `CR2` writer"]
pub type W = crate::W<CR2_SPEC>;
#[doc = "Field `PVDE` reader - Power voltage detector enable"]
pub type PVDE_R = crate::BitReader;
#[doc = "Field `PVDE` writer - Power voltage detector enable"]
pub type PVDE_W<'a, REG, c... |
use derive_more::Display;
use std::{result, str::Utf8Error};
use thiserror::Error;
/// The error type returned by the [Command::parse] method.
///
/// [Command::parse]: ./enum.Command.html#method.parse
#[derive(Debug, Error, PartialEq, Eq)]
#[error("parse error: {kind}")]
pub struct ParseError {
kind: ParseErrorKi... |
//! An example of generating basic shapes
extern crate image;
extern crate line_drawing;
fn draw_circle(imgbuf: &mut image::RgbaImage, xc: i32, yc: i32, r: i32) {
for (x, y) in line_drawing::BresenhamCircle::new(xc, yc, r) {
imgbuf.put_pixel(x as u32, y as u32, image::Rgba([255, 255, 0, 255]));
}
}
fn draw_lin... |
use std::{path::Path, process::ExitStatus, str::FromStr};
use crate::poc::TestMetadata;
use chrono::{DateTime, Local};
use duct::{cmd, Expression};
pub fn cargo_command(
subcommand: &str,
metadata: &TestMetadata,
path: impl AsRef<Path>,
) -> Expression {
let command_vec = cargo_command_vec(subcommand... |
//! A sequence of values with a given error.
//!
//! # Examples
//!
//! Quick plot.
//! ```no_run
//! use preexplorer::prelude::*;
//! let data = (0..10).map(|i| (i..10 + i));
//! let seq_err = pre::SequenceError::new(data).plot("my_identifier").unwrap();
//! ```
//!
//! Compare ``SequenceError``s.
//! ```no_run
//! us... |
//! `lockdown` is an E2EE implementation for the Harmony protocol.
/// Generated code from protobuf protocol files (secret service and common Harmony types).
pub mod api;
/// E2EE implementation for the Harmony protocol.
pub mod e2ee;
|
#![allow(dead_code, unused_must_use, unused_imports, unstable)]
use std::str::FromStr;
use controller::Reader;
use utils;
// Each line in the database file is a 'Record' that contains the following data to be read
// and serialized.
pub struct Record {
// Unique (?) id given to each record.
pub id: u64,
//... |
struct Any<'a> {
a: &'a mut i32,
b: &'a mut i32,
}
struct Point<'a> {
x: &'a mut Any<'a>,
y: &'a mut Any<'a>,
}
fn main() {
let fuck = 20;
let temp = Any {
a: &mut 39,
b: &mut 20,
};
let hello = temp;
let fuck2 = fuck;
let mut x = &mut Point {
x: &mut Any ... |
use crate::app::video::Palette;
use rustzx_core::{
host::{FrameBuffer, FrameBufferSource},
zx::video::colors::{ZXBrightness, ZXColor},
};
const RGBA_PIXEL_SIZE: usize = 4;
#[derive(Clone)]
pub struct FrameBufferContext;
pub struct RgbaFrameBuffer {
buffer: Vec<u8>,
palette: Palette,
buffer_row_si... |
use std::sync::Arc;
use crate::*;
use math::Rect;
use wgpu::util::DeviceExt;
#[derive(Clone)]
pub struct BufferedRenderArgs {
pub(crate) texture: Texture,
pub(crate) shader: Shader,
}
impl BufferedRenderArgs {
fn new<D: WgpuDevice>(desc: &Renderable<'_, Renderer<D>>) -> Self {
Self {
texture: desc.texture.c... |
//std
use std::process;
use std::sync::{Arc, Mutex};
use std::time::Duration;
//Lazy static
use lazy_static;
// Log
pub mod log;
use log::Log;
// UI
pub mod ui;
// Stream
mod stream;
use stream::Stream;
// Tokio
use tokio::sync::oneshot;
#[tokio::main]
async fn main() -> Result<(), anyhow::Error> {
let sample... |
use sdl2::event::Event;
use sdl2::image::{self, InitFlag, LoadTexture};
use sdl2::pixels::Color;
use specs::prelude::*;
use crate::ecs::animation::*;
use crate::ecs::collision::*;
use crate::ecs::components::*;
use crate::ecs::enemy::*;
use crate::ecs::player::*;
use crate::ecs::renderer;
use crate::ecs::resources::*;... |
#![feature(test)]
#[cfg(test)]
mod tests {
extern crate test;
use lazy_static::lazy_static;
use std::{fs, path::Path};
use test::Bencher;
lazy_static! {
static ref SMALL_JSON: String = fs::read_to_string(Path::new("json/small.json")).expect(
"Error loading 'json/small.json'; ma... |
use super::version_number::VersionNumber;
use crate::vtable::id::VTableId;
use serde::{Deserialize, Serialize};
/// ID of VTable
#[derive(Clone, Eq, PartialEq, Ord, PartialOrd, Hash, Debug, Serialize, Deserialize)]
pub struct VersionId {
pub(in crate::version) vtable_id: VTableId,
pub(in crate::version) versio... |
pub mod id_table;
pub mod matrix;
pub mod tex_table;
pub mod webgl;
|
extern crate simple_excel_writer;
use simple_excel_writer as excel;
use excel::*;
#[test]
fn creates_and_saves_an_excel_sheet() {
let mut wb = excel::Workbook::create("test.xlsx");
let mut ws = wb.create_sheet("test_sheet");
wb.write_sheet(&mut ws, |sw| {
sw.append_row(row!["Name", "Title", "Succes... |
use std::{borrow::Cow, sync::Arc};
use thiserror::Error;
#[derive(Error, Debug, Clone)]
pub enum Error {
/// Error representing an **input** is at fault.
#[error("violate domain invariance rule - {msg}")]
BadInput { msg: Cow<'static, str> },
/// Authentication or Authorization is failed.
#[error("... |
#![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... |
use rusqlite::{params, OptionalExtension, Transaction};
/// This schema migration splits the global state table into
/// separate tables containing L1 and L2 data.
///
/// In addition, it also adds a refs table which only contains a single column.
/// This columns references the latest Starknet block for which the L1 ... |
use std::collections::{HashMap, HashSet};
fn main() {
let input = String::from_utf8(std::fs::read("input/day21").unwrap()).unwrap();
let mut allergens = HashMap::<&str, Vec<usize>>::new();
let mut food = Vec::<HashSet<&str>>::new();
input.split_terminator('\n').for_each(|line| {
let mut line = ... |
use pairing::{Engine, Field};
use bellman::SynthesisError;
use rand::{Rand, Rng, thread_rng};
use merlin::Transcript;
use crate::cs::{SynthesisDriver, Circuit, Backend, Variable, Coeff};
use crate::srs::SRS;
use crate::transcript::ProvingTranscript;
use crate::polynomials::{Polynomial, poly_comm, poly_comm_opening, SxE... |
use actix::prelude::*;
use async_trait::async_trait;
use tracing::Span;
/// Message with span used for trace logging
pub struct SpanMessage<I> {
pub msg: I,
pub span: Span,
}
impl<M> SpanMessage<M> {
pub fn new(msg: M) -> Self {
Self {
msg,
span: Span::current(),
}
... |
use futures_util::future::{self, FutureExt};
use twilight_cache::{
entity::{
channel::{
attachment::{AttachmentEntity, AttachmentRepository},
category_channel::{CategoryChannelEntity, CategoryChannelRepository},
group::{GroupEntity, GroupRepository},
message::... |
#[doc = "Reader of register DIV_CSR"]
pub type R = crate::R<u32, super::DIV_CSR>;
#[doc = "Reader of field `DIRTY`"]
pub type DIRTY_R = crate::R<bool, bool>;
#[doc = "Reader of field `READY`"]
pub type READY_R = crate::R<bool, bool>;
impl R {
#[doc = "Bit 1 - Changes to 1 when any register is written, and back to 0... |
#[doc = "Register `DBPCR` reader"]
pub type R = crate::R<DBPCR_SPEC>;
#[doc = "Register `DBPCR` writer"]
pub type W = crate::W<DBPCR_SPEC>;
#[doc = "Field `DBP` reader - Disable Backup domain write protection In reset state, all registers and SRAM in Backup domain are protected against parasitic write access. This bit ... |
use std::time::Instant;
use bevy::{
app::AppExit,
core::CorePlugin,
prelude::*,
render::pass::ClearColor,
sprite::collide_aabb::{collide, Collision},
type_registry::TypeRegistryPlugin,
};
#[cfg(not(headless))]
use bevy::winit::WinitConfig;
use bevy_benchmark_games::{metrics::IterationMetrics,... |
use std::io::{self, BufRead};
fn repeated_char(s: String) -> (bool, bool) {
let mut has_2 = false;
let mut has_3 = false;
let mut s = s.into_bytes();
s.sort();
let mut iter = s.iter().peekable();
while let Some(ch) = iter.next() {
let mut count = 1;
while iter.peek() == Some(&&c... |
use std::marker::PhantomData;
use super::{Pusherator, PusheratorBuild};
pub struct FilterMap<Next, Func, In> {
next: Next,
func: Func,
_marker: PhantomData<fn(In)>,
}
impl<Next, Func, In> Pusherator for FilterMap<Next, Func, In>
where
Next: Pusherator,
Func: FnMut(In) -> Option<Next::Item>,
{
... |
use crate::dasm::{DasmError, InstructionData};
use crate::spec::mmu::{Error as MmuError, MMU};
use crate::spec::mnemonic::Mnemonic;
use crate::spec::opcode::Instruction;
use crate::debug_logger::{cpu_logger::CPU_LOGGER, DebugLogger};
use crate::spec::register::{RegisterError, Registers, TRegister};
use std::convert::... |
#[doc = "Register `C1_AHB1LPENR` reader"]
pub type R = crate::R<C1_AHB1LPENR_SPEC>;
#[doc = "Register `C1_AHB1LPENR` writer"]
pub type W = crate::W<C1_AHB1LPENR_SPEC>;
#[doc = "Field `DMA1LPEN` reader - DMA1 Clock Enable During CSleep Mode"]
pub type DMA1LPEN_R = crate::BitReader<DMA1LPEN_A>;
#[doc = "DMA1 Clock Enable... |
fn main() {
let mut num1 = sum_n(100);
num1 = num1 * num1;
let num2 = sum_n_sqr(100);
println!("diff is {}", num1-num2);
}
fn sum_n(n:u32) -> u32 {
return n*(n+1)/2;
}
fn sum_n_sqr(n:u32) -> u32 {
return n*(n+1)*(2*n+1)/6
}
|
/*
* 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
*/
/// AccessRole : The access role of the user. Options are **st** (standard user), **adm** (admin user), ... |
use serde_json::{Value};
use serde_json::json;
use crate::ofn_2_ldtab::util as util;
pub fn translate(v : &Value) -> Value {
match v[0].as_str() {
Some("ObjectInverseOf") => translate_inverse_of(v),
Some(_) => panic!(),
//None => owl::OWL::Named(String::from(v.as_str().unwrap())),
... |
#![allow(non_snake_case)]
#[macro_use]
extern crate lazy_static;
extern crate serde_json;
extern crate vmtests;
use serde_json::Value;
use std::collections::HashMap;
use vmtests::{load_tests, run_test};
lazy_static! {
static ref TESTS: HashMap<String, Value> = load_tests("tests/vmEnvironmentalInfo/");
}
#[test]... |
use super::super::failpoints::failpoint;
#[cfg(test)]
use super::super::failpoints::Failpoints;
use super::error::Error;
use super::file_system::{FileKind, OpenMode, SeriesDir};
use super::io_utils::{ReadBytes, WriteBytes};
use crc::crc16;
use std::collections::VecDeque;
use std::fs::File;
use std::io::prelude::*;
use ... |
use crate::agent::agent_internal::*;
use crate::candidate::*;
use crate::control::*;
use crate::priority::*;
use crate::use_candidate::*;
use stun::{agent::*, attributes::*, fingerprint::*, integrity::*, message::*, textattrs::*};
use async_trait::async_trait;
use std::net::SocketAddr;
use std::sync::atomic::Ordering... |
use predicates::prelude::Predicate;
use predicates::str::contains;
use test_utils::init;
use crate::test_utils::{HOME_CFG_FILE, PROJECT_CFG_FILE, PROJECT_DIR};
use short::BIN_NAME;
mod test_utils;
#[test]
fn generate_template() {
let mut e = init("generate_template");
e.add_file(
PROJECT_CFG_FILE,
... |
//! rustc --edition 2018 \
//! -C lto=yes \
//! -C codegen-units=1 \
//! -C opt-level=3 \
//! -C overflow-checks=no \
//! -C panic=abort \
//! -C target-cpu=native \
//! solution1.rs
include!("common.rs");
mod basics {
use std::convert::{From, TryInto};
use std::cmp::{Ord, PartialOr... |
use crate::types::CmdResult;
pub fn do_what(word: &str) -> CmdResult {
CmdResult::new(false, format!("What do you want to {}?", word))
}
pub fn dont_have(name: &str) -> CmdResult {
CmdResult::new(false, format!("You do not have the \"{}\".", name))
}
|
/*
* 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
*/
/// DashboardListListResponse : Information on your dashboard lists.
#[derive(Clone, Debug, PartialEq... |
const MAX_TRIES: u64 = 1;
// Attempt to stress tokio::process::Command::spawn
// to reproduce a `WouldBlock` error.
#[test]
fn main() {
env_logger::init();
tokio_test::block_on(async {
// A little time to launch dtruss
tokio::time::delay_for(std::time::Duration::new(3, 0)).await;
let m... |
use std::error::Error;
use std::net::TcpListener;
use std::path::PathBuf;
use std::thread;
use clap;
use output::Output;
pub use server::handler::handle_client;
use zbackup::repository::*;
use misc::*;
use misc::args::ClapSubCommandRzbackupArgs;
pub fn run_server (
output: & Output,
arguments: & ServerArguments,... |
use std::io::prelude::*;
use std::fs::File;
use std::io::{BufReader, Error};
use utils;
fn read_numbers_as_digit_array() -> Result<Vec<Vec<u32>>, Error> {
let f = try!(File::open("../data/problem_013_input.txt"));
let reader = BufReader::new(f);
let mut nums = vec![vec![]];
for line in reader.lines()... |
use std::env;
use std::fs::File;
use std::io::Write;
use std::path::PathBuf;
use git2::Repository;
#[macro_use]
extern crate quote;
fn git_data(repo_src: PathBuf) -> Result<(String, String), Box<dyn std::error::Error>> {
let repo = Repository::open(repo_src)?;
let head = repo.head()?;
let oid = head.targ... |
use super::OpIterator;
use crate::StorageManager;
use common::ids::Permissions;
use common::ids::{ContainerId, TransactionId};
use common::storage_trait::StorageTrait;
use common::table::*;
use common::{Attribute, CrustyError, TableSchema, Tuple};
use std::sync::{Arc, RwLock};
/// Sequential scan operator
pub struct S... |
mod exponential_backoff;
pub use exponential_backoff::{ExponentialBackoff, ExponentialBackoffBuilder};
|
//! Evaluate use input and set InputCommands and triggers InputEvents.
use crate::event;
use crate::resource;
use bevy::prelude::*;
/// Evaluate use input and set InputCommands and triggers InputEvents.
pub fn user_input(
mut input_commands: ResMut<resource::InputCommands>,
mut input_events: EventWriter<event:... |
use anyhow::Result;
use std::env;
use std::error::Error;
use std::fmt;
use std::fmt::Display;
use std::io::prelude::*;
use std::io::BufReader;
use std::net::{TcpStream, ToSocketAddrs};
use std::process::exit;
#[derive(Debug)]
struct NameResolutionError<'a> {
hostname: &'a str,
}
impl Display for NameResolutionErr... |
use ::*;
pub fn sound_loop(
stop : Arc<Mutex<bool>>,
sound_rx : mpsc::Receiver<&str>,
) {
let mut monster_dies = Sound::new("monster_dies.wav").unwrap();
let mut monster_spawns = Sound::new("monster_spawns.wav").unwrap();
let mut player_dies = Sound::new("player_dies.wav").unwrap();
loop {
... |
mod block_assembler;
mod component;
mod config;
pub mod error;
pub mod pool;
mod process;
pub mod service;
pub(crate) const LOG_TARGET_TX_POOL: &str = "ckb-tx-pool";
pub use ckb_fee_estimator::FeeRate;
pub use component::entry::TxEntry;
pub use config::{BlockAssemblerConfig, TxPoolConfig};
pub use process::PlugTarget... |
use crate::AssemblerError;
use std::rc::Rc;
#[derive(Debug)]
pub struct Symbol {
name: Rc<String>,
val: Type,
exported: bool,
}
#[derive(Debug)]
enum Type {
Equ(i32),
Equs(String),
Label(i32), // TODO: actually a section + offset
Set(i32),
}
impl Symbol {
// === Constructors ===
... |
use super::{IntoRecords, Records};
/// A [Records] implementation for any [IntoIterator].
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub struct IterRecords<I> {
iter: I,
count_columns: usize,
count_rows: Option<usize>,
}
impl<I> IterRecords<I> {
/// Returns a new [IterRecords] objec... |
extern crate log;
extern crate byteorder;
extern crate libc;
extern crate rand;
#[macro_use]
pub mod util;
pub mod config;
pub mod db;
pub mod mem;
#[cfg(test)]
mod tests {
#[test]
fn it_works() {
assert_eq!(2 + 2, 4);
}
}
|
//! Contains types useful for implementing custom resource conversion webhooks.
pub use self::types::{
ConversionRequest, ConversionResponse, ConversionReview, ConvertConversionReviewError,
};
/// Defines low-level typings.
mod types;
|
//! Discovers images in a Connection and assigns them names. We use these for
//! image filenames so that models know what the path to a specific image it
//! uses will be.
use db::{Database, TextureId, PaletteId};
use nitro::Name;
use std::collections::HashMap;
use util::namers::UniqueNamer;
use connection::Connection... |
use glium::glutin::{self, dpi::{LogicalSize, PhysicalSize, PhysicalPosition}};
use glium::glutin::event_loop::ControlFlow;
use super::viewer::Viewer;
use db::Database;
use connection::Connection;
pub fn main_loop(db: Database, conn: Connection) {
let window_builder = glutin::window::WindowBuilder::new()
.w... |
// Copyright (c) 2017-2017 Chef Software Inc. and/or applicable contributors
//
// 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
//
// Unl... |
use super::*;
use parking_lot::Mutex;
use std::{cmp::Ordering, collections::HashSet};
use std::collections::BTreeSet;
use std::sync::{Arc, atomic::{Ordering as AtomicOrdering, AtomicBool, AtomicU64}};
use std::time::{Duration, Instant};
use std::thread;
use threadpool::ThreadPool;
use jsonrpc_http_server::jsonrpc_core... |
use std::{ env, fs };
fn main() {
let args: Vec<String> = env::args().collect();
let path: String = args[1].clone();
let _settings: String = args[2].clone();
let files: Vec<String> = vec![String::new(); 64];
let _file_list = fetch_files(path, files);
}
fn fetch_files(_path: String, arr: Vec<String>... |
/// Rust platform tiers: support levels are organized into three tiers, each
/// with a different set of guarantees.
#[derive(Copy, Clone, Debug, Eq, Hash, PartialEq, PartialOrd, Ord)]
pub enum Tier {
/// Tier 1 platforms can be thought of as “guaranteed to work”.
/// Specifically they will each satisfy the fol... |
/// IO primitives
pub mod io;
/// PCI
pub mod pci;
/// PS2
pub mod ps2;
/// RTC
pub mod rtc;
/// Serial
pub mod serial;
/// Layouts
pub mod kb_layouts;
|
mod reg_size;
pub use self::reg_size::RegSize;
mod reg;
pub use self::reg::{
Register,
parse_reg,
parse_512bit_reg,
parse_256bit_reg,
parse_128bit_reg,
parse_64bit_reg,
parse_32bit_reg,
parse_16bit_reg,
parse_8bit_reg,
parse_mmx_reg,
parse_x87_reg,
parse_vec_reg,
parse_long_ptr_reg,
};
mod... |
use friday_vendor;
use friday_vendor::DispatchResponse;
use friday_vendor::Vendor;
use friday_signal;
use friday_signal::core::{Signal, Listening, Inference, Dispatch};
use friday_audio;
use friday_audio::recorder::Recorder;
use friday_vad;
use friday_vad::core::{SpeakDetector, VADResponse};
use friday_inference;
u... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.