text stringlengths 8 4.13M |
|---|
extern crate iron;
extern crate libc;
extern crate mio;
extern crate threadpool;
extern crate time;
extern crate url;
#[macro_use] extern crate lazy_static;
#[macro_use] extern crate log;
#[cfg(test)]
#[macro_use]
extern crate matches;
#[cfg(test)]
extern crate regex;
pub mod common;
pub mod ctrlc;
pub mod error;
p... |
use concierge_api_rs::PayloadMessage as GenericPayloadMessage;
use cs3_physics::{polygon::Polygon, vector::Vec2f};
use serde::{Deserialize, Serialize};
use uuid::Uuid;
use std::marker::PhantomData;
pub type PayloadMessage<'a> = GenericPayloadMessage<'a, PhysicsPayload<'a>>;
type RgbColor = (u8, u8, u8);
#[derive(Ser... |
use crate::vector::Vector4ISize;
use derive_more::Add;
use std::ops::Mul;
#[derive(
Default,
Clone,
Copy,
PartialEq,
Eq,
PartialOrd,
Ord,
Hash,
Add,
AddAssign,
Sub,
SubAssign,
Debug,
)]
pub struct QuadricVector(Vector4ISize);
impl QuadricVector {
pub fn new(x: i... |
#[doc = "Reader of register LE_RF_TEST_MODE_EXT"]
pub type R = crate::R<u32, super::LE_RF_TEST_MODE_EXT>;
#[doc = "Writer for register LE_RF_TEST_MODE_EXT"]
pub type W = crate::W<u32, super::LE_RF_TEST_MODE_EXT>;
#[doc = "Register LE_RF_TEST_MODE_EXT `reset()`'s with value 0"]
impl crate::ResetValue for super::LE_RF_TE... |
// PROJECT - kvstore: store key value pairs in a file format of our choice.
use std::collections::HashMap;
fn main() {
// arguments to insert into the CLI app.
// args is an itterator.
let mut arguments = std::env::args().skip(1);
// on linux, the first arg is the path to the application. we dont wan... |
use std::fmt;
use std::io;
use std::mem::{self, MaybeUninit};
use serde::{Serialize, Serializer};
#[cfg(feature = "json")]
use serde_json::Serializer as JsonSerializer;
use crate::{Argument, FormatType};
#[cfg(feature = "json")]
type CompactJsonSerializer<W> = JsonSerializer<W, serde_json::ser::CompactFormatter>;
#[... |
#![allow(non_camel_case_types)]
use std::c_str::CString;
use std::{fmt,mem,ptr};
use libc::{c_char,c_int,c_uint,c_long};
#[repr(C)]
enum CURLversion {
CURL_VERSION_FIRST,
CURL_VERSION_SECOND,
CURL_VERSION_THIRD,
CURL_VERSION_FOURTH,
CURL_VERSION_LAST /* never actually use this */
}
static CURL_VE... |
#[derive(Debug, PartialEq, Eq)]
pub enum Classification {
Abundant,
Perfect,
Deficient,
}
pub fn classify(num: u64) -> Option<Classification> {
let result: Option<Classification> = None;
if num == 0 {
result
} else {
match (1..num).filter(|x| num % x == 0).fold(0, |sum, x| sum +... |
// Day 4 2019
#[cfg(test)]
mod tests {
use crate::day4::*;
#[test]
fn test_factorial() {
assert_eq!(factorial(0), 1);
assert_eq!(factorial(1), 1);
assert_eq!(factorial(2), 2);
assert_eq!(factorial(3), 6);
assert_eq!(factorial(10), 3628800);
}
#[test]
fn t... |
#![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 MonitorsCollection {
#[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")]
pub ne... |
#![macro_use]
macro_rules! impl_op {
($Op:ident, $op:ident, $T:ty, $Tx:expr) => {
impl<F: FullFloat> $Op<$T> for $T {
type Output = $T;
fn $op(self, rhs: $T) -> $T {
$Tx((self.0).$op(rhs.0))
}
}
};
}
macro_rules! impl_op_f {
($Op:ident, $... |
// Modified from: http://www.adammil.net/blog/v125_roguelike_vision_algorithms.html#mycode
use rl_utils::{Area, Coord};
use crate::{utils::Octant, Fov, FovCallbackEnum, FovConfig, Los, VisionShape};
#[derive(Copy, Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Debug)]
struct Slope {
x: isize,
y: isize,
}
impl ... |
pub struct Image {
pub width: usize,
pub height: usize,
data: Vec<Vec<char>>
}
impl Image {
pub fn new(width: usize, height: usize) -> Image {
let mut v = Vec::with_capacity(height);
for _ in 0..width {
v.push(Vec::with_capacity(width));
}
for i i... |
use std::env;
use std::thread::spawn;
use futures::{Future, Stream};
use ipnetwork::IpNetwork;
use tokio_core::reactor::Core;
use netlink_packet_route::link::nlas::LinkNla;
use rtnetlink::new_connection;
fn main() {
let args: Vec<String> = env::args().collect();
if args.len() != 3 {
return usage();
... |
use super::types::{BigNum, DoubleBigNum, GroupG1};
use super::ECCurve::big::{BASEBITS, MODBYTES as curve_MODBYTES, NLEN as curve_NLEN};
use super::ECCurve::rom;
pub const MODBYTES: usize = curve_MODBYTES;
pub const NLEN: usize = curve_NLEN;
pub const BIG_NUM_BITS: usize = BASEBITS;
pub const FIELD_ORDER_ELEMENT_SIZE... |
use std::{fs, io};
use unicode_segmentation::UnicodeSegmentation;
fn main() -> std::io::Result<()> {
let entries = fs::read_dir(".")?
.map(|res| res.map(|e| e.path()))
.collect::<Result<Vec<_>, io::Error>>()?;
entries.iter().for_each(|e| {
let name = e.file_name().unwrap().to_str().unw... |
pub const INCLUDED: &str = file!();
|
pub mod dictionary;
pub mod hint_table;
pub mod utils;
use self::dictionary::make_dict;
use self::hint_table::make_hint_table;
use self::utils::{load_new_data, load_new_data_drop};
use crate::Result;
use ez_io::WriteE;
use std::io::{Cursor, Seek, SeekFrom, Write};
const DICT_LEN: usize = 256;
const HINT_BITS: usize =... |
/// HUST OS Lab2 Implementation in Rust
use std::{
thread,
sync::{Mutex, Arc},
};
const THREAD_NUM: i32 = 5;
const TICKET_NUM: i32 = 100;
fn main() {
println!("Welcome to hust os lab in rust");
let tickets = Arc::new(Mutex::new(TICKET_NUM));
let mut handles = vec![];
for i in 0..THREAD_NUM {
... |
use std::collections::{HashMap, HashSet};
use anyhow::Context;
use web3::{
futures::future::try_join_all,
types::{FilterBuilder, Transaction, TransactionId, U256},
};
use crate::core::Chain;
use crate::ethereum::{
contract::{REGISTER_MEMORY_PAGE_FUNCTION, STATE_TRANSITION_FACT_EVENT},
log::{
B... |
#[derive(Copy, Clone, Debug, Default, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub struct AnsiColor(u8);
impl AnsiColor {
#[inline(always)]
pub const fn from_num(color: u8) -> Self {
AnsiColor(color)
}
#[inline(always)]
pub const fn as_num(self) -> u8 {
self.0
}
}
|
use crate::constants::CONNECTORX_PROTOCOL;
use crate::errors::{ConnectorXError, Result};
use anyhow::anyhow;
use fehler::throws;
use std::convert::TryFrom;
use url::Url;
#[derive(Debug, Clone)]
pub enum SourceType {
Postgres,
SQLite,
MySQL,
MsSQL,
Oracle,
BigQuery,
DuckDB,
}
#[derive(Debug... |
pub const fn round_to_multiple_of(divisor: usize, x: usize) -> usize {
x + (divisor - 1) & !(divisor - 1)
}
|
#![no_std]
#![no_main]
#![feature(asm)]
#![feature(abi_efiapi)]
extern crate rlibc;
extern crate panic_halt;
mod fonts;
mod console;
mod graphics;
mod pci;
mod mouse;
use core::fmt::Write;
use mikan::{FrameBufferConfig, PixelFormat};
use graphics::{write_pixel, write_string, PixelColor};
use console::{Console};
st... |
use definitions::{Expression, LiteralValue, BinaryOperator, UnaryOperator, ColumnDef};
use table::{Table, TableRow, TableHeader, get_column};
use std::cell::Cell;
#[derive(PartialEq, Clone)]
pub enum ExpressionResult {
Value(LiteralValue),
ColumnDef(ColumnDef),
Null,
}
impl ExpressionResult {
pub fn ... |
use std::io;
pub fn run() {
println!("Search depth: ");
let mut input = String::new();
io::stdin()
.read_line(&mut input)
.expect("Failed to read line");
let depth = input.trim().parse::<i32>().unwrap();
let root = Node::new();
println!(
"{:?} {}",
root.board,
... |
use crate::{
math::*,
regressor::{
config::Config,
regressor::Regressor,
},
};
macro_rules! builder_field {
($field:ident, $field_type:ty) => {
pub fn $field(mut self, $field: $field_type) -> Self {
self.$field = $field;
self
}
};
}
/// Conve... |
#![allow(dead_code)]
use winit::{
event,
event::{Event, WindowEvent},
event_loop::{ControlFlow, EventLoop},
window::Window,
};
mod gfx;
mod state;
mod util;
use gfx::prelude::*;
async fn run(event_loop: EventLoop<()>, window: Window) {
env_logger::init();
let mut world = state::world::World... |
#[doc = "Register `SMPR` reader"]
pub type R = crate::R<SMPR_SPEC>;
#[doc = "Register `SMPR` writer"]
pub type W = crate::W<SMPR_SPEC>;
#[doc = "Field `SMP1` reader - Sampling time selection 1 These bits are written by software to select the sampling time that applies to all channels. Note: The software is allowed to w... |
//! Internal implementation details of usbd-hid.
extern crate proc_macro;
extern crate usbd_hid_descriptors;
use proc_macro::TokenStream;
use proc_macro2::Span;
use quote::quote;
use syn::punctuated::Punctuated;
use syn::token::Bracket;
use syn::{parse, parse_macro_input, Expr, Fields, ItemStruct};
use syn::{Pat, Pat... |
//! Demonstrates how to retrieve a StarkNet state update from L1 using event logs.
//!
//! As a high-level overview of the log events:
//! (in chronological order, for a single state update)
//!
//! 1. Multiple LogMemoryPageFactContinuous get emitted by the MemoryPageFactRegistry contract.
//! These logs con... |
// Copyright 2021 Red Hat, Inc.
//
// 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 i... |
use core::ops::{Deref, DerefMut};
use core::sync::atomic::{AtomicBool, Ordering};
use crate::uses::*;
use crate::int::apic::LocalApic;
use crate::gdt::{Gdt, Tss};
use crate::int::idt::Idt;
use crate::sched::Registers;
use crate::arch::x64::*;
#[repr(C)]
#[derive(Debug)]
pub struct GsData
{
// NOTE: these fields have... |
use super::message_destinations::MessageDestinations;
use super::registry::Registry as GenericRegistry;
use crate::data::message::Message;
use crate::data::timetoken::Timetoken;
use crate::data::{pubsub, request, response};
use crate::transport::Service;
use futures_channel::{mpsc, oneshot};
use futures_util::future::{... |
mod RrtWeekend;
mod RrtVec3;
mod RrtColor;
mod RrtRay;
mod RrtSphere;
mod RrtHittable;
mod RrtHittableList;
use std::rc::Rc;
use crate::RrtVec3::Vec3;
use crate::RrtRay::Ray;
use crate::RrtHittableList::HittableList;
use crate::RrtSphere::Sphere;
fn main() {
// Image
let aspect_ratio : f64 = 16.0 / 9.0;
... |
use clippy_utils::diagnostics::span_lint_and_help;
use clippy_utils::is_trait_method;
use rustc_hir as hir;
use rustc_lint::LateContext;
use rustc_span::sym;
use super::FILTER_MAP;
/// lint use of `filter().flat_map()` for `Iterators`
pub(super) fn check<'tcx>(
cx: &LateContext<'tcx>,
expr: &'tcx hir::Expr<'_... |
use std::fmt::Display;
use hotplot::chart::line::data::ThemeSettings;
use iced::{button, checkbox, container, pick_list, progress_bar, radio, rule, scrollable, slider, text_input, Color};
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Theme {
Default = 0,
Light = 1,
Dark = 2,
}
impl Display for Th... |
use alloc::boxed::Box;
use alloc::vec::Vec;
use core::ffi::c_void;
extern "Rust" {
fn miri_backtrace_size(flags: u64) -> usize;
fn miri_get_backtrace(flags: u64, buf: *mut *mut ());
fn miri_resolve_frame(ptr: *mut (), flags: u64) -> MiriFrame;
fn miri_resolve_frame_names(ptr: *mut (), flags: u64, name_... |
use abstract_integers::*;
abstract_signed_secret_integer!(BigBounded, 256);
#[test]
#[should_panic]
fn bounded() {
println!("BigBounded::max(): {:x}", BigBounded::max());
let y1 = (BigBounded::pow2(255) - BigBounded::from_literal(1)) * BigBounded::from_literal(2);
let y2 = BigBounded::from_literal(4);
... |
//! Soft-link with `config.toml`
//!
//! leetcode-cli will generate a `leetcode.toml` by default,
//! if you wanna change to it, you can:
//!
//! + Edit leetcode.toml at `~/.leetcode/leetcode.toml` directly
//! + Use `leetcode config` to update it
use crate::{
config::{code::Code, cookies::Cookies, storage::Storage... |
#[macro_use]
mod utils;
inject_indy_dependencies!();
extern crate indyrs as api;
extern crate indyrs as indy;
use crate::utils::constants::*;
use crate::utils::metrics;
use crate::utils::wallet;
use crate::utils::Setup;
mod collect {
use super::*;
use std::collections::HashMap;
use serde_json::Value;
... |
fn read<T: std::str::FromStr>() -> T {
let mut s = String::new();
std::io::stdin().read_line(&mut s).ok();
s.trim().parse().ok().unwrap()
}
fn cnt(mut u: u64) -> i32 {
let mut a = 0;
loop {
a += 1;
u /= 10;
if u == 0 {
break;
}
}
a
}
fn solve(n: ... |
use shrev::*;
use specs::*;
use types::*;
use protocol::client::Command;
use protocol::server::{PlayerFlag, PlayerRespawn, PlayerType};
use protocol::{to_bytes, FlagCode, ServerPacket, Upgrades as ProtocolUpgrades};
use websocket::OwnedMessage;
pub struct CommandHandler {
reader: Option<ReaderId<(ConnectionId, Comma... |
mod account;
mod ldap;
mod models;
pub use self::ldap::login as ldap_login;
pub use self::models::{Account, AccountWithId};
use self::{account::AccountRole, ldap::Ldap};
use crate::{database::Database, Server};
use account::AccountType;
pub use account::{get_user_by_name, get_user_by_token, setup_root, SALT};
use anyh... |
// Copyright 2015 Ted Mielczarek. See the COPYRIGHT
// file at the top-level directory of this distribution.
//! A collection for storing data associated with a range of values.
use std::cmp::Ordering;
use std::iter::FromIterator;
use std::slice::Iter;
/// The value type for the endpoints of ranges.
pub type Addr = ... |
use std::io::{self, Read};
use std::collections::HashMap;
#[derive(Debug,Clone)]
enum Rule { Disjunction(Vec<Rule>), Literal(String), Sequence(Vec<usize>) }
fn parse_rule(rule_string : &str) -> Rule {
if rule_string.contains('|') {
return Rule::Disjunction(rule_string.split(" | ").map(|s| parse_rule(s)).c... |
// Copyright 2019, 2020 Wingchain
//
// 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... |
extern crate pretty_env_logger;
use std::env;
use std::fs::File;
use std::net::ToSocketAddrs;
use anyhow::{anyhow, Result};
use async_dup::Mutex;
use async_std::net::TcpStream;
use async_std::task;
use crate::config::IrcConfig;
use crate::ctcp::{ClientInfoCtcpResponse, CtcpEvent, FingerCtcpResponse, PingCtcpResponse... |
use tokio::{fs, io};
use url::Url;
use super::consts::{
http::HTTP_CLIENT,
paths::{NODE_DIST_URL, NODE_VERSION_INDEX_URL, SUMCHECK_FILE_NAME, TMP_DIR_PATH},
};
use super::types::GeneralError;
use super::utils::os::get_os_node_file_name;
#[cfg(test)]
mod tests;
pub async fn get_dist_index() -> reqwest::Result... |
extern crate getopts;
use std::env;
use getopts::Options;
mod lfsr;
mod feistel;
mod gcd;
mod hash;
fn main(){
println!("Welcome to CryptoPlayground");
let args: Vec<String> = env::args().collect();
let mut opts = Options::new();
opts.optflag("h", "help", "Print this helptext");
opts.optflag("",... |
fn main() {
print_numbers_to(255);
println!("Is 5 an even number? {}", is_even(5));
}
fn print_numbers_to(to_num: u8) {
for num in 1..to_num {
println!("{}", num);
}
}
fn is_even(num: u8) -> bool {
return num % 2 == 0;
} |
/*
A simple HTTP server that serves static content from a given directory,
built on [rotor] and [rotor-http].
It creates a number of rotor server threads, all listening on the same
port (via [libc::SO_REUSEPORT]). These are state machines performing
non-blocking network I/O on top of [mio]. The HTTP requests are pars... |
#![feature(plugin)]
#![plugin(rocket_codegen)]
extern crate serde;
#[macro_use]
extern crate serde_derive;
#[macro_use]
extern crate serde_json;
extern crate rocket;
extern crate postgres;
extern crate chrono;
extern crate biscuit;
#[cfg(test)]
extern crate reqwest;
use std::env;
use std::fs::File;
use std::io::Read... |
#![feature(rust_2018_preview)]
#![feature(uniform_paths)]
extern crate getopts;
use getopts::Options;
use std::env;
use std::iter::Peekable;
use std::mem::swap;
use std::str::Chars;
mod char_class;
use char_class::CharClass;
#[derive(Clone, Debug)]
enum AST {
Empty,
Universe,
Epsilon,
Literal(CharCla... |
mod parser;
mod program;
use std::io::{Read, Write};
use std::error::Error;
use std::fmt;
pub fn run<R: Read, W:Write>(code: Vec<u8>, input: &mut R, output: &mut W) -> Result<(), BFError> {
let program = parser::parse(code)?;
program.run(input, output);
Ok(())
}
#[derive(Debug, Clone)]
... |
extern mod rsfml;
use std::hashmap::HashMap;
pub use rsfml::graphics::texture::Texture;
pub struct TextureCache {
textures: HashMap<~str, @Texture>
}
impl TextureCache {
pub fn new() -> TextureCache {
TextureCache {
textures: HashMap::new()
}
}
pub fn load(& mut self, path... |
//! The Styx type system.
use prelude::*;
use expr::{Expr};
use lexer::{HasSpan, Span};
use procedures::Proc;
use symbols::{Sym, Symbol, SymbolTree};
use std::collections::HashMap;
use std::hash::{Hash, Hasher};
use std::fmt::{self, Debug, Display, Formatter, Write};
use std::marker::PhantomData;
use std::sync::RwLoc... |
use std::collections::HashSet;
use std::env;
use std::process::Command;
use walkdir::WalkDir;
use builtin::*;
use common::LOGGER;
#[derive(Clone, Debug)]
pub struct CommandStore {
pub name: String,
pub args: Vec<String>,
pub stdin: Option<String>,
pub stdout: Option<String>,
pub stderr: Option<Stri... |
pub fn main() {
println!("planner")
}
|
use io::{outportb,inportb};
/* This structure is what is on the stack at the time the interrupt is received by the
* rust code. This is accomplished through some magic x86 calling conventions */
#[derive(Copy)]
#[repr(C, packed)]
pub struct Registers {
ds: u32,
edi: u32, esi: u32, ebp: u32, esp: u32, ebx: u32... |
#![feature(core_intrinsics)]
#![feature(asm)]
#![no_std]
#![no_main]
// #[macro_use]
// extern crate lazy_static;
mod arch;
mod bsp;
mod drivers;
mod interface;
mod memory;
mod panic;
mod runtime_init;
pub fn bootloader_entry() -> ! {
bsp::init();
loop {}
}
|
use khonsu_tools::{
anyhow,
code_coverage::{self, CodeCoverage},
};
use structopt::StructOpt;
#[derive(StructOpt, Debug)]
pub enum Commands {
GenerateCodeCoverageReport {
#[structopt(long = "install-dependencies")]
install_dependencies: bool,
},
}
fn main() -> anyhow::Result<()> {
... |
//! BookCrossing commands.
mod cluster;
mod extract;
pub use cluster::Cluster;
pub use extract::Extract;
|
use std::borrow::Borrow;
use std::fmt::{Debug, Formatter, Error};
use std::rc::Rc;
use std::cmp::Ordering::*;
use Node::*;
use Color::*;
/// A persistent, immutable red-black tree.
pub struct RbMap<K, V> {
root: Node<K, V>,
}
impl<K, V> RbMap<K, V> {
/// Creates a new, empty map.
pub fn new() -> RbMap<K, ... |
mod short_msg_kat_224;
mod short_msg_kat_256;
mod short_msg_kat_384;
mod short_msg_kat_512;
mod short_msg_kat_shake128;
mod short_msg_kat_shake256;
|
#![feature(box_patterns)]
#![feature(str_escape)]
#![feature(slice_patterns)]
extern crate runic;
extern crate winit;
extern crate futures;
extern crate toml;
#[macro_use]
extern crate json;
extern crate mio;
extern crate regex;
#[cfg(target_os="windows")]
extern crate mio_named_pipes;
// txd: a text editor🖳
mod bu... |
#![allow(clippy::unreadable_literal)]
//! Solarized
//! <https://ethanschoonover.com/solarized/>
use iced::color;
use crate::gui::styles::types::custom_palette::{CustomPalette, PaletteExtension};
use crate::gui::styles::types::palette::Palette;
/// Solarized light (Day style)
pub(in crate::gui::styles) fn solarized_... |
use super::utils::*;
use std::io::{Error, ErrorKind};
use winapi::shared::minwindef::{DWORD, HMODULE};
use winapi::um::{
winnt::HANDLE,
psapi::{GetModuleInformation, MODULEINFO, EnumProcessModules, GetModuleBaseNameA},
};
#[derive(Debug)]
pub struct Module {
pub base: usize,
pub size: usize,
}
impl M... |
use ring::{agreement, rand};
pub fn example() -> Result<(), Box<dyn std::error::Error>> {
let rng = rand::SystemRandom::new();
info!("rng {:?}", rng);
// This next line breaks WASM:
// let my_private_key = agreement::EphemeralPrivateKey::generate(&agreement::X25519, &rng).unwrap();
//
// info... |
use crate::fast_buf::ConsumeBuf;
use crate::fast_buf::FastBuf;
use crate::limit::LimitWrite;
use crate::mpsc::{Receiver, Sender};
use crate::server::{DriveExternal, SyncDriveExternal};
use crate::AsyncRead;
use crate::Error;
use futures_util::future::poll_fn;
use futures_util::ready;
use std::fmt;
use std::io;
use std:... |
#[doc = "Register `MACHWF2R` reader"]
pub type R = crate::R<MACHWF2R_SPEC>;
#[doc = "Field `RXQCNT` reader - Number of MTL Receive Queues"]
pub type RXQCNT_R = crate::FieldReader;
#[doc = "Field `TXQCNT` reader - Number of MTL Transmit Queues"]
pub type TXQCNT_R = crate::FieldReader;
#[doc = "Field `RXCHCNT` reader - N... |
use actix_web::{web, Error, HttpRequest, HttpResponse};
use bytes::BytesMut;
use chrono::Local;
use futures::StreamExt;
use std::fs::OpenOptions;
use std::io::prelude::*;
use std::path::Path;
use std::thread;
pub async fn collect_post(
req: HttpRequest,
mut payload: web::Payload,
) -> Result<HttpResponse, Erro... |
use dotenv::dotenv;
use messaging::{Publisher, PublisherOptions};
use std::env;
fn main() {
dotenv().ok();
let broker_address = env::var("RABBITMQ_URL").expect("'RABBITMQ_URL' environment variable");
let publisher_options = PublisherOptions::new(broker_address,
... |
use crate::format::problem::Objective::{MinimizeCost, MinimizeUnassignedJobs};
use crate::format::problem::*;
use crate::format::{CoordIndex, Location};
use crate::format_time;
use crate::helpers::ToLocation;
use std::sync::Arc;
use vrp_core::models::common::Profile as CoreProfile;
use vrp_core::models::problem::{Activ... |
use super::winit;
use crate::input;
pub(crate) enum Event {
CloseRequested,
Resized(winit::dpi::LogicalSize),
Input(input::Event),
CursorMoved(winit::dpi::LogicalPosition),
}
pub struct EventLoop(winit::EventsLoop);
impl EventLoop {
pub fn new() -> Self {
Self(winit::EventsLoop::new())
... |
use crate::{ChannelReceiver, ChannelSender};
use crate::message::SlackPayload;
use tokio::task::JoinHandle;
/// Provides a background worker task that sends the messages generated by the
/// layer.
pub(crate) async fn worker(mut rx: ChannelReceiver) {
let client = reqwest::Client::new();
while let Some(message... |
//! Read Query Builder returned by InfluxDbQuery::raw_read_query
//!
//! Can only be instantiated by using InfluxDbQuery::raw_read_query
use crate::error::InfluxDbError;
use crate::query::{InfluxDbQuery, QueryType, ValidQuery};
pub struct InfluxDbReadQuery {
queries: Vec<String>,
}
impl InfluxDbReadQuery {
/... |
use std::prelude::v1::*;
mod aggregate_context;
mod blend_context;
mod filter_context;
pub use aggregate_context::AggregateContext;
pub use blend_context::BlendContext;
pub use filter_context::FilterContext;
|
use std::fmt::{self, Display};
use hyper::header;
use hyper;
#[derive(Clone)]
pub struct XApiKey {
key: String,
}
impl XApiKey {
pub fn key(k: String) -> XApiKey {
XApiKey { key: k }
}
}
impl Display for XApiKey {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", self.key)
}
}
... |
impl Solution {
pub fn search_matrix(matrix: Vec<Vec<i32>>, target: i32) -> bool {
let (n,m) = (matrix.len(),matrix[0].len());
for i in 0..n{
for j in 0..m{
if matrix[i][j] == target{
return true;
}else if matrix[i][j] > target{
... |
use clap::ArgMatches;
use std::fs::File;
use std::io::{self, Write};
use std::str::FromStr;
use svm_codec::api::json;
pub fn clap_app_tx() -> clap::App<'static, 'static> {
use clap::*;
SubCommand::with_name("tx")
.about("Low-level API to craft transactions from JSON specification files")
.ar... |
use gdnative::prelude::*;
#[derive(NativeClass)]
#[inherit(Node)]
pub struct Globals {
kills: u16,
current_stage: u16,
}
#[methods]
impl Globals {
fn new(_owner: &Node) -> Self {
Globals {
kills: 0,
current_stage: 0
}
}
#[export]
fn _ready(&self, _owner... |
pub fn word_pattern(pattern: String, s: String) -> bool {
use std::collections::*;
if pattern.len() != s.split(' ').count() {
return false;
}
let mut map = HashMap::new();
for (c, word) in pattern.chars().zip(s.split(' ')) {
match map.get(&c).clone() {
None => {
... |
use std::rc::Rc;
use std::cell::RefCell;
use std::borrow::Borrow;
use gtk::prelude::*;
use crate::app::*;
pub struct AppWindow {
window: gtk::Window,
}
impl AppWindow {
pub fn new(state: Rc<RefCell<AppState>>, app: App) -> AppWindow {
let glade_str = include_str!("app_window.glade");
let bui... |
use std::io::{Read, Write};
#[derive(Debug, PartialEq)] // to be able to test somewhat sensibly
pub enum Command {
Increment,
Decrement,
Input,
Output,
Left,
Right,
Loop(Program),
}
#[derive(Debug, PartialEq)]
pub struct Program {
commands: Vec<Command>,
}
impl Progr... |
use crate::measurement::Measurement;
use std::fmt;
use std::ops::{Add, Sub, Mul, Div, Neg};
pub enum Value {
PosNumber(f64),
Number(f64),
Measurement(Measurement)
}
impl fmt::Display for Value {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Value::PosNumber... |
// 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... |
use std::fs;
use std::error::Error;
use std::f32::consts::PI;
fn parse_input() -> Result<Vec<Vec<char>>, Box<dyn Error>> {
let input = fs::read_to_string("./src/level10/input.txt")?;
let input: Vec<Vec<char>> = input.trim().split("\n").map(|l| l.chars().collect()).collect();
Ok(input)
}
pub fn part1() -> ... |
//! Program counter
#[cfg(cortex_m)]
use core::arch::asm;
/// Reads the CPU register
#[cfg(cortex_m)]
#[inline]
pub fn read() -> u32 {
let r;
unsafe { asm!("mov {}, pc", out(reg) r, options(nomem, nostack, preserves_flags)) };
r
}
/// Writes `bits` to the CPU register
#[cfg(cortex_m)]
#[inline]
pub unsaf... |
use yew::prelude::*;
pub struct Footer;
impl Component for Footer {
type Message = ();
type Properties = ();
fn create(_: Self::Properties, _: ComponentLink<Self>) -> Self {
Footer
}
fn update(&mut self, _: Self::Message) -> ShouldRender {
false
}
}
impl Renderable<Footer> f... |
/*! A silly grammar */
use Symbol;
pub struct Foo;
rusty_peg! {
parser Parser<'input>: Foo {
Hi: u32 = ("Hi") => 1;
Ho: u32 = "Ho" => 2;
HiOrHo: u32 = (Hi / Ho);
Sum: u32 = (Sum1 / HiOrHo);
Sum1: u32 = (<x:HiOrHo> "+" <y:Sum>) => {x + y*10};
HiHo: () = (Hi Ho) =... |
pub mod error;
pub mod proto;
pub mod relays;
|
#[cfg(feature = "ffi")]
#[macro_use]
pub mod ctypes;
#[cfg(any(
feature = "bls_bls12381",
feature = "ed25519",
feature = "ed25519_asm",
feature = "ecdh_secp256k1",
feature = "ecdh_secp256k1_native",
feature = "ecdh_secp256k1_asm",
feature = "ecdsa_secp256k1",
feature = "ecdsa_secp256k1_n... |
#[doc = "Register `NDAT1` reader"]
pub type R = crate::R<NDAT1_SPEC>;
#[doc = "Register `NDAT1` writer"]
pub type W = crate::W<NDAT1_SPEC>;
#[doc = "Field `ND0` reader - New data"]
pub type ND0_R = crate::BitReader;
#[doc = "Field `ND0` writer - New data"]
pub type ND0_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG... |
/*
Lists the private clouds, similar to:
az vmware private-cloud list --query [].id
az extension documentation:
https://docs.microsoft.com/cli/azure/ext/vmware/vmware/private-cloud?view=azure-cli-latest#ext_vmware_az_vmware_private_cloud_list
API documentation:
https://docs.microsoft.com/rest/api/vmware/privateclouds/... |
use crate::num::Real;
use std::ops::Sub;
pub fn note_ratio() -> Real {
Real::powf(2.0, 1.0 / 12.0)
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[repr(u8)]
pub enum Key {
C = 0,
Cs = 1,
D = 2,
Ds = 3,
E = 4,
F = 5,
Fs = 6,
G = 7,
Gs = 8,
A = 9,
... |
use std::ptr;
use std::ops::{Deref, DerefMut};
use std::ffi::CString;
use raw;
use super::effect_param;
pub struct Effect {
raw: *mut raw::Effect
}
impl Effect {
pub unsafe fn from_raw(raw: *mut raw::Effect) -> Effect {
Effect {
raw: raw
}
}
pub fn param_by_name(&mut self,... |
extern crate csv_multithread;
#[macro_use]
extern crate criterion;
extern crate itertools;
use std::fs;
use std::time::Duration;
use itertools::Itertools;
use criterion::*;
use csv_multithread::*;
use std::process::Command;
fn cpp_version(filename: &'static str) -> impl Fn() -> Command {
move || {
l... |
use std::cmp::*;
struct MinStack {
stack: Vec<i32>,
m: i32,
}
impl MinStack {
fn new() -> Self {
Self {
stack: vec![],
m: 0,
}
}
fn push(&mut self, x: i32) {
if self.stack.len() == 0 {
self.m = x;
} else {
self.m = mi... |
/// Check if input is a valid domain label
pub fn is_label(input: &str) -> bool {
let mut chars = input.chars();
// we need at least one char
let first = match chars.next() {
None => {
return false;
}
Some(c) => c,
};
// it can start with an alphanumeric charact... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.