text stringlengths 8 4.13M |
|---|
use crate::compiling::v1::assemble::prelude::*;
/// Compile a range expression.
impl Assemble for ast::ExprRange {
fn assemble(&self, c: &mut Compiler<'_>, needs: Needs) -> CompileResult<Asm> {
let span = self.span();
log::trace!("ExprRange => {:?}", c.source.source(span));
let guard = c.s... |
use std::collections::HashMap;
use crate::core::{Part, Solution};
pub fn solve(part: Part, input: String) -> String {
match part {
Part::P1 => Day07::solve_part_one(input),
Part::P2 => Day07::solve_part_two(input),
}
}
const MAX_DIR_SIZE: i32 = 100_000;
const SYSTEM_SPACE: i32 = 70_000_000;
c... |
use crate::error::{CamlError, Error};
use crate::tag::Tag;
use crate::{sys, OCaml, OCamlRef, Runtime};
/// Size is an alias for the platform specific integer type used to store size values
pub type Size = sys::Size;
/// Value wraps the native OCaml `value` type transparently, this means it has the
/// same representa... |
//! Method with non-deserializable argument type.
use near_bindgen::near_bindgen;
use borsh::{BorshDeserialize, BorshSerialize};
#[near_bindgen]
#[derive(Default, BorshDeserialize, BorshSerialize)]
struct Storage {
data: Vec<u64>,
}
#[near_bindgen]
impl Storage {
pub fn insert(&mut self) -> impl Iterator<Ite... |
extern crate tiff;
use tiff::ColorType;
use tiff::decoder::{Decoder, DecodingResult, ifd::Tag, ifd::Value};
use std::fs::File;
#[test]
fn test_gray_u8()
{
let img_file = File::open("./tests/images/minisblack-1c-8b.tiff").expect("Cannot find test image!");
let mut decoder = Decoder::new(img_file).expect("Cann... |
//! C API wrappers to create Telamon Kernels.
use crate::Device;
use libc;
use num::rational::Ratio;
use std::{self, sync::Arc};
use telamon::ir;
use telamon_utils::*;
pub use telamon::ir::op::Rounding;
use super::error::TelamonStatus;
/// Creates a function signature that must be deallocated with
/// `telamon_ir_si... |
#![feature(native_link_modifiers)]
#![feature(native_link_modifiers_bundle)]
#![feature(static_nobundle)]
#[link(name = "foo", kind = "static", modifiers = "-bundle")]
extern "C" {
fn bar() -> i32;
}
pub fn rust_bar() -> i32 {
unsafe { bar() }
}
|
use super::error::*;
use super::symbol::*;
use super::script_type_description::*;
use futures::*;
use gluon::vm::api::*;
///
/// Indicates the updates that can occur to a notebook
///
#[derive(Clone, PartialEq, Debug)]
pub enum NotebookUpdate {
/// A symbol has been specified to define a namespace
DefinedName... |
use std::ffi::CString;
use cql_ffi::collection::set::CassSet;
use cql_ffi::collection::map::CassMap;
use cql_ffi::collection::list::CassList;
use cql_ffi::error::CassError;
use cql_ffi::uuid::CassUuid;
use cql_ffi::inet::CassInet;
use cql_ffi::result::CassResult;
use cql_ffi::consistency::CassConsistency;
use cql_ffi:... |
// Copyright 2020-2021, The Tremor Team
//
// 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 agr... |
use ggez::graphics::{self, DrawMode, Drawable, Mesh, MeshBuilder};
use ggez::{Context, GameResult};
use nalgebra as na;
#[derive(Debug, Clone, Copy, Eq, PartialEq, Hash)]
pub enum DrawableHandle {
Circle,
Box,
}
pub struct Assets {
drawables: Vec<Box<Drawable>>,
}
impl Assets {
pub fn new(ctx: &mut C... |
#![cfg(feature = "serde")]
use debugid::{CodeId, DebugId};
use uuid::Uuid;
#[test]
fn test_deserialize_debugid() {
assert_eq!(
DebugId::from_parts(
Uuid::parse_str("dfb8e43a-f242-3d73-a453-aeb6a777ef75").unwrap(),
0,
),
serde_json::from_str("\"dfb8e43a-f242-3d73-a45... |
use std::io::{self, Write};
use byteorder::{LittleEndian, BigEndian, WriteBytesExt};
use super::{Value, Tag, Vec2, Vec3, Vec4, Box2, Writer};
pub struct BinaryWriter<W> {
output: W
}
fn get_type(value: &Value) -> u8 {
match value {
&Value::Bool(_) => 0x00,
&Value::Int(_) => 0x01,
&Valu... |
#[cfg(target_family = "windows")]
use crate::platform::windows::RawTerminal;
#[cfg(target_family = "unix")]
use crate::platform::unix::RawTerminal;
/// Enumarations of colors, maybe remove the `None` option and change the
/// signature of some methods that use it to `Option<Color>`
#[derive(Debug, Copy, Clone, Eq, P... |
use crate::encrypt::encrypt::{encryption, string_count};
use crate::decrypt::decrypt::decrypt;
use crate::msg::msg::{menu, input};
use crate::pgr::pgr::pgr_function;
mod msg;
mod encrypt;
mod decrypt;
mod pgr;
fn main() {
use std::io::{stdin,stdout,Write};
let mut text = "Ned Flanders";
let mut key = "H... |
use std::io;
use std::sync::{Mutex, Arc};
use std::io::{TcpListener, TcpStream, Listener, Acceptor};
use std::io::net::tcp::TcpAcceptor;
use std::comm::{Receiver, Sender, channel};
struct Server {
#[allow(dead_code)]
game: GameWorld,
port: u16,
acceptor: TcpAcceptor,
players: Arc<Mutex<Vec<PlayerHa... |
extern crate reqwest;
extern crate reventsource;
fn main() -> Result<(), Box<dyn std::error::Error>> {
let client = reqwest::Client::builder()
.proxy(reqwest::Proxy::https("http://127.0.0.1:7777")?)
.timeout(None)
.build()?;
let resp = client
.get("https://hacker-news.firebasei... |
/// `match` for parsers
///
/// When parsers have unique prefixes to test for, this offers better performance over
/// [`alt`][crate::combinator::alt] though it might be at the cost of duplicating parts of your grammar
/// if you needed to [`peek`][crate::combinator::peek].
///
/// For tight control over the error in a... |
fn main() {
let stdin = std::io::stdin();
let mut rd = ProconReader::new(stdin.lock());
let r1: usize = rd.get();
let c1: usize = rd.get();
let r2: usize = rd.get();
let c2: usize = rd.get();
let mo = 1_000_000_000 + 7;
let binom = Binom::new(r2 + c2 + 2, mo);
let g = |r: usize, c:... |
extern crate matrix;
use matrix::prelude::*;
use std::vec::Vec;
// Finds an optimal binary search tree by dynamic programming
// Input: An array p[1..n] of search probabilities for a sorted list of n keys
// Output: Average number of comparisons in successful searches in the
// optimal BST and table r of subtrees... |
//! Ffi-safe wrapper types around the
//! [crossbeam-channel](https://crates.io/crates/crossbeam-channel/)
//! channel types.
#![allow(clippy::missing_const_for_fn)]
use std::{
fmt::{self, Debug},
marker::PhantomData,
time::Duration,
};
use crossbeam_channel::{
Receiver, RecvError, RecvTimeoutError, S... |
// Copyright (c) 2017 Martijn Rijkeboer <mrr@sru-systems.com>
//
// 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 dis... |
use crate::utils::*;
use tokio::prelude::*;
const N_LENGTH_BYTES: usize = 4;
const LENGTH_LIMIT: usize = 100_000;
pub async fn framed_read<T: serde::de::DeserializeOwned>(stream: &mut (impl AsyncRead + Unpin)) -> Result<T> {
let mut length_bytes = [0; N_LENGTH_BYTES];
stream.read_exact(&mut length_bytes).awai... |
mod event;
mod exchange;
mod orderbook;
mod types;
mod utils;
mod server;
mod protocol;
mod messages;
use std::sync::Arc;
use tokio::sync::Mutex;
use crate::exchange::*;
use crate::server::Server;
extern crate log;
#[tokio::main]
async fn main() {
let symbols = "GOOG,MSFT";
let symbols_vec: Vec<String> = symbol... |
use crate::consts;
use crate::error::{Error, ErrorCode, Result};
use crate::read;
use serde::de;
use std::io;
use serde::forward_to_deserialize_any;
pub fn from_reader<'de, R, T>(read: R) -> Result<T>
where
R: io::Read,
T: de::DeserializeOwned,
{
let read = read::IoRead::new(read);
let mut de = Deseri... |
use std::slice;
use super::events::StockMoveEvent;
pub type ItemCode = String;
pub type LocationCode = String;
pub type Quantity = u32;
pub trait Event<S> {
type Output;
fn apply_to(&self, state: S) -> Self::Output;
}
pub trait Restore<E> {
fn restore(self, events: slice::Iter<E>) -> Self;
}
#[allow(... |
//! Coverage maps as static mut array
use crate::EDGES_MAP_SIZE;
/// The map for edges.
pub static mut EDGES_MAP: [u8; EDGES_MAP_SIZE] = [0; EDGES_MAP_SIZE];
/// The max count of edges tracked.
pub static mut MAX_EDGES_NUM: usize = 0;
|
//! System Applets.
//!
//! Applets are small integrated programs that the OS makes available to the developer to streamline commonly needed functionality.
//! Thanks to these integrations the developer can avoid wasting time re-implementing common features and instead use a more reliable base for their application.
//... |
//! The module keeping track of the state of the game.
use crate::error::GameError;
use game_loop::{Renderer, Updater};
/// The state of the game.
#[derive(Debug, Default)]
pub(crate) struct GameState {
updates: usize,
renders: usize,
}
impl Updater for GameState {
type Error = GameError;
fn update(... |
// Copyright 2019 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
use failure::Error;
use serde_json::{from_value, to_value, Value};
use crate::setui::types::{JsonMutation, LoginOverrideMode, SetUiResult};
use fidl_fuch... |
// Copyright 2019-2020 PolkaX. Licensed under MIT or Apache-2.0.
use serde_cbor::Value;
use super::{Amt, Item, Node, BITS_PER_SUBKEY, WIDTH};
use crate::blocks::Blocks;
use crate::error::*;
impl<B> Amt<B>
where
B: Blocks,
{
/// this function would use in anywhere to traverse the trie, do not need flush first... |
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// 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 ... |
use coruscant_nbt::to_string_transcript;
use serde::Serialize;
// there is a (probable) serde bug here!
// https://github.com/serde-rs/serde/issues/1584
#[derive(Serialize)]
#[serde(rename = "book")]
struct Book {
resolved: Option<i8>,
#[serde(flatten)]
extra: Option<Extra>,
}
#[derive(Serialize)]
struct... |
use std::collections::HashMap;
use std::io::Cursor;
use base64;
use rocket::request;
use rocket::request::FromRequest;
use rocket::{response, Outcome, Request, Response};
use crate::models::stat;
use crate::models::stat::StatFromType;
use crate::repo::DomainRepo;
use crate::{conn, util};
pub struct Pack {
hash... |
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// 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 ... |
use crate::{
testing::data::Wallet, testing::scenario::scenario_builder::ScenarioBuilderError, value::Value,
};
use super::{StakePoolTemplate, WalletTemplate};
use std::collections::{HashMap, HashSet};
#[derive(Clone, Debug)]
pub struct WalletTemplateBuilder {
alias: String,
delagate_alias: Option<String... |
use std::collections::HashMap;
use petgraph::Graph;
use petgraph::graph::NodeIndex;
use super::graph::{Node, Edge};
pub fn normalize(graph: &mut Graph<Node, Edge>, layers_map: &mut HashMap<NodeIndex, usize>) {
for e in graph.edge_indices() {
let edge = graph[e].clone();
let (u, v) = graph.edge_endp... |
use rltk::GameState;
use rltk::RGB;
use rltk::Rltk;
use specs::prelude::*;
use specs_derive::Component;
mod map;
pub use map::*;
mod player;
pub use player::*;
mod components;
pub use components::*;
mod rectangle;
mod visibility_system;
pub use visibility_system::*;
pub struct State {
ecs: World
}
impl GameState... |
// This file is part of Substrate.
// Copyright (C) 2019-2021 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... |
#[macro_use]
mod prelude;
mod config;
mod memtable;
mod primitives;
mod sstable;
mod table;
mod time;
mod tombstones;
#[cfg(test)]
mod testutils;
use std::collections::HashMap;
fn main() {
let arr = [1u8, 2u8];
let r = &arr[0..];
println!("{}", r[0]);
println!("{}", r[1]);
let asdf = std::p... |
use super::Part;
use crate::codec::{Decode, Encode};
use crate::spacecenter::ReferenceFrame;
use crate::{remote_type, RemoteObject, Vector3};
remote_type!(
/// The component of an Engine or RCS part that generates thrust. Can obtained by
/// calling` Engine::thrusters()` or `RCS::thrusters()`.
///
/// # Note
/// Engin... |
use crate::label_sequence::LabelSequence;
use crate::name::lower_case;
use crate::name::Name;
use crate::name::NameComparisonResult;
use crate::name::NameRelation;
use std::{cmp, fmt};
#[derive(Debug, Clone, Eq, PartialEq)]
pub struct LabelSlice<'a> {
data: &'a [u8],
offsets: &'a [u8],
first_label: usize,
... |
#![allow(non_snake_case, non_camel_case_types, non_upper_case_globals, clashing_extern_declarations, clippy::all)]
#[link(name = "windows")]
extern "system" {}
pub const PERCEPTIONFIELD_StateStream_TimeStamps: ::windows_sys::core::GUID = ::windows_sys::core::GUID {
data1: 2861064473,
data2: 62255,
data3: 18... |
pub use self::plugins::*;
pub use self::systems::*;
mod plugins;
mod systems;
|
use gatt::characteristics as ch;
use gatt::services as srv;
use gatt::{CharacteristicProperties, Registration};
pub(crate) fn add(registration: &mut Registration<super::Token>) {
// Generic Attirbute
registration.add_primary_service(srv::GENERIC_ATTRIBUTE);
// ServiceChanged
registration.add_characteri... |
use serde::{Deserialize, Serialize};
#[derive(Serialize, Deserialize, Debug)]
#[serde(tag = "kind")]
pub enum Body {
Ping(PingBody),
//LogShow(LogShowBody),
LogAdd(LogAddBody),
//LogDelete(LogDeleteBody),
//LogList(LogListBody),
MessageAdd(MessageAddBody),
//IteratorAdd(IteratorAddBody),
... |
use anyhow::{anyhow, bail, Result};
#[tokio::main]
async fn main() -> Result<()> {
let client = Client::new()?;
let lock = client.request_lock().await?;
println!("Got lock: {:?}", lock);
let cols = Colours {
led0: Colour::rgb(255, 0, 0),
led1: Colour::rgb(255, 0, 0),
led2: Colo... |
pub fn demo() {
println!("函数以snake case风格命名");
println!("{}", return_method());
}
fn return_method() -> i32 {
println!("函数当结尾不以分号结尾则为返回值");
1
} |
use crate::mock::*;
use super::*;
use hex_literal::hex;
#[test]
fn no_previous_chain() {
ExtBuilder::default().build().execute_with(|| {
assert_eq!(GenesisHistory::previous_chain(), Chain::default());
})
}
#[test]
fn some_previous_chain() {
let chain = Chain { genesis_hash: vec![1,2,3].into(), la... |
#[doc = "Reader of register CR"]
pub type R = crate::R<u32, super::CR>;
#[doc = "Writer for register CR"]
pub type W = crate::W<u32, super::CR>;
#[doc = "Register CR `reset()`'s with value 0"]
impl crate::ResetValue for super::CR {
type Type = u32;
#[inline(always)]
fn reset_value() -> Self::Type {
... |
// Copyright (c) 2017-present PyO3 Project and Contributors
//! Python Number Interface
//! Trait and support implementation for implementing number protocol
use crate::callback::IntoPyCallbackOutput;
use crate::{ffi, FromPyObject, PyClass, PyObject};
/// Number interface
#[allow(unused_variables)]
pub trait PyNumbe... |
use lazy_static::lazy_static;
use std::{ops, sync::Arc};
/// Docker client
pub struct Client {
inner_client: Arc<shiplift::Docker>,
}
impl Client {
/// Construct a new unique Docker Client. Unless you know you need
/// a unique Client, you should probably `use Client::default()` which
/// uses a globa... |
//! To run this code, clone the rusty_engine repository and run the command:
//!
//! cargo run --release --example music
//! This is an example of playing a music preset. For playing your own music file, please see the
//! `sound` example.
use rusty_engine::prelude::*;
fn main() {
let mut game = Game::new();... |
use std::process::Command;
use std::str;
use dialoguer::PasswordInput;
use super::cli;
pub fn read_access_token() -> String {
//! Reads in a user's personal access token from GitHub.
println!("Please paste your personal access token from GitHub below.");
PasswordInput::new()
.with_prompt("Token")... |
#[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::EISC {
#[doc = r"Modifies the contents of the register"]
#[inline(always)]
pub fn modify<F>(&self, f: F)
where
for<'w> F: FnOnce(&R, &'w... |
#[macro_use] extern crate ruru;
extern crate hyper;
pub mod server;
pub mod ruby_utils;
use ruru::VM;
#[no_mangle]
pub extern fn initialize_busy() {
// VM::require("rack/builder");
server::init();
}
|
// Copyright 2021 Datafuse Labs.
//
// 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 ... |
#![feature(iter_array_chunks)]
use std::collections::{HashMap, HashSet};
fn priority(item: u8) -> u8 {
let base = if item.is_ascii_lowercase() {
b'a'
} else {
b'A' - 26
};
(item - base) + 1
}
type Rucksack<'a> = (&'a [u8], &'a [u8]);
fn rucksack(input: &[u8]) -> Rucksack {
let mi... |
use std::collections::HashMap;
use std::fs;
fn main() {
const PART: u8 = 2;
const MAX_DIR: u8 = 4;
let mut cur_dir = 0;
let input = fs::read_to_string("inputs/day1.txt").unwrap();
//let input = "R8, R4, R4, R8";
let toks = input
.split(",")
.map(|s| s.trim().to_string())
... |
use std::io::Read;
fn read<T: std::str::FromStr>() -> T {
let token: String = std::io::stdin()
.bytes()
.map(|c| c.ok().unwrap() as char)
.skip_while(|c| c.is_whitespace())
.take_while(|c| !c.is_whitespace())
.collect();
token.parse().ok().unwrap()
}
fn main() {
let... |
#![allow(unused_variables, non_upper_case_globals, non_snake_case, unused_unsafe, non_camel_case_types, dead_code, clippy::all)]
#[repr(transparent)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)]
pub struct AppListEntry(pub ::windows::core::IInspectable... |
//! A [`DmlSink`] decorator to make request [`IngestOp`] durable in a
//! write-ahead log.
//!
//! [`DmlSink`]: crate::dml_sink::DmlSink
//! [`IngestOp`]: crate::dml_payload::IngestOp
pub(crate) mod reference_tracker;
pub(crate) mod rotate_task;
mod traits;
pub(crate) mod wal_sink;
|
use std::cmp::Ordering;
use std::collections::VecDeque;
use std::str::FromStr;
use crate::error::Error;
use crate::intcode::{Prog, ProgState};
#[derive(Copy, Clone, Debug, Hash, Eq, PartialEq)]
pub enum Type {
Empty,
Wall,
Block,
HorizontalPaddle,
Ball,
}
impl FromStr for Type {
type Err = Er... |
//! Types which represent various database backends
use byteorder::ByteOrder;
use crate::query_builder::bind_collector::BindCollector;
use crate::query_builder::QueryBuilder;
use crate::sql_types::{self, HasSqlType};
/// A database backend
///
/// This trait represents the concept of a backend (e.g. "MySQL" vs "SQLi... |
#![deny(warnings)]
extern crate futures;
extern crate hyper;
extern crate tokio_core;
extern crate pretty_env_logger;
use std::env;
use std::io::{self, Write};
use futures::Future;
use futures::stream::Stream;
use hyper::Client;
fn main() {
pretty_env_logger::init().unwrap();
let url = match env::args().n... |
pub mod tokenize;
pub mod parse;
pub mod generate;
pub mod trans;
use std::io;
use std::io::Read;
use std::fs::File;
use std::env;
use std::io::BufWriter;
fn main() -> io::Result<()> {
let mut args = env::args();
let _program = args.next().unwrap();
let in_filename = args.next().expect("Please specify inp... |
extern crate structopt;
use std::error::Error;
use std::path::PathBuf;
use structopt::StructOpt;
use crate::ecoz2_lib::lpc_signals;
use crate::utl;
mod libpar;
mod lpc_rs;
pub mod lpca_cepstrum_rs;
pub mod lpca_r_rs;
mod lpca_rs;
#[derive(StructOpt, Debug)]
pub struct LpcOpts {
/// Prediction order
#[struc... |
use async_std::prelude::*;
use serde::Deserialize;
const API_URL: &'static str = "https://api.codetabs.com/v1/loc?github=";
#[derive(Deserialize, Debug)]
// #[serde(rename_all = "camelCase")]
struct LocItem {
language: String,
files: String,
lines: String,
blanks: String,
comments: String,
#[s... |
use handler::WebHandler;
use routing::WebRouter;
use iron::Handler;
use iron::prelude::*;
use mount::Mount;
use router::Router;
use staticfile::Static;
use std::collections::HashMap;
use std::path::Path;
use std::thread;
use std::thread::JoinHandle;
pub struct WebServer {
interface: String,
port: u32,
... |
use embedded_graphics::pixelcolor::PixelColor;
// TODO: rename DefaultTheme to LightTheme and add DarkTheme
pub mod default;
// TODO: merge this into DefaultTheme. This would allow defining different color schemes for the same
// color space.
pub trait Theme: PixelColor {
const TEXT_COLOR: Self;
const BORDER_... |
use crate::game_event::GameEventType;
use crate::room::Room;
use crate::timer::{Timer, TimerType};
use crate::EventQueue;
use crate::{Action, ActionHandled, State};
#[derive(Debug)]
pub struct Cryocontrol {
pub visited: bool,
pub lever: bool,
pub opened: bool,
}
impl Cryocontrol {
pub fn new() -> Cryo... |
#[derive(Debug)]
pub struct TypeInteraction{
weaknesses: Vec<String>,
strengths: Vec<String>,
ineffectivities: Vec<String>
}
pub enum TypeFactor{
Weakness(String),
Strength(String),
Ineffective(String)
}
impl TypeInteraction{
pub fn new() -> TypeInteraction{
TypeInteraction{
... |
use crate::{Ops, Port, Range};
use std::str::FromStr;
use std::{net::Ipv4Addr, net::TcpListener};
pub struct TcpPort;
impl Ops for TcpPort {
fn any(host: &str) -> Option<Port> {
let r = Range::default();
(r.min..=r.max)
.filter(|&p| TcpPort::is_port_available(host, p))
.nth(... |
use mysql::*;
use mysql::prelude::*;
use std::mem;
#[derive(Debug, PartialEq, Eq)]
struct Payment {
customer_id: i32,
amount: i32,
account_name: Option<String>,
}
#[derive(Debug, PartialEq, Eq)]
struct Rust{
id: i32,
name: String,
age: i32,
}
fn main(){
let url = "mysql://root:root@l... |
use coi::{container, Inject};
#[derive(Inject)]
#[coi(provides Impl1<T> with Impl1::<T>::new())]
struct Impl1<T>(T)
where
T: Default;
impl<T> Impl1<T>
where
T: Default,
{
fn new() -> Self {
Self(Default::default())
}
}
#[test]
fn main() {
let impl1_provider = Impl1Provider::<bool>::new();... |
use std::time::Duration;
use std;
#[repr(C)]
#[derive(Eq)]
pub struct Time {
ns : u64
}
impl Clone for Time {
fn clone(&self) -> Time {
Time::new(self.ns)
}
}
impl Copy for Time {}
impl std::cmp::PartialEq for Time {
fn eq(&self, other: &Time) -> bool {
self.ns == other.ns
}
}
i... |
/// Defines a strongly typed array wrapper.
#[macro_export]
macro_rules! array_wrapper {
($name:ident, $t:ty, $doc:literal) => {
/// $doc
#[derive(Debug, Clone)]
pub struct $name(::ndarray::Array1<$t>);
impl From<::ndarray::Array1<$t>> for $name {
fn from(array: ::ndarra... |
//! Information about the current compaction round
use std::fmt::Display;
use data_types::CompactionLevel;
/// Information about the current compaction round (see driver.rs for
/// more details about a round)
#[derive(Debug, PartialEq, Eq, Clone, Copy)]
pub enum RoundInfo {
/// compacting to target level
Tar... |
#[no_mangle]
pub fn SumSquares(n: usize) -> f64 {
let mut total = 0f64;
for x in 0..n {
total = total + (x as f64 * x as f64);
}
total
} |
use std::io;
use std::{env, process};
use crate::cli::SubCommand;
use crate::workflow_config::Config;
use rusty_pin::{PinBuilder, Pinboard, Tag};
pub mod config;
mod delete;
mod list;
mod post;
mod rename;
mod search;
mod update;
mod upgrade;
mod browser_info;
use alfred_rs::updater::GithubReleaser;
use alfred_rs:... |
use super::{ModInt, Modulo};
use num::integer::Integer;
use std::convert::From;
impl From<ModInt<'_, i8>> for i8 {
fn from(orig: ModInt<'_, i8>) -> Self {
orig.number
}
}
impl From<ModInt<'_, i16>> for i16 {
fn from(orig: ModInt<'_, i16>) -> Self {
orig.number
}
}
impl From<ModInt<'_, i32>> for i32 {... |
use std::error::Error;
use rustbox::{Color, RustBox};
use rustbox::Key;
use rustbox::Event::*;
use rustbox;
pub fn read_into(start_x: usize, start_y: usize, rustbox: &RustBox, result: &mut String){
let mut position: usize=0;
loop{
match rustbox.poll_event(false) {
Ok(KeyEvent(key)) => {
match key {
So... |
use super::{greedy::GreedySolver, utils::best_valued_item_fit, Problem, Solution, SolverTrait};
#[derive(Debug, Clone)]
pub struct ReduxSolver();
impl SolverTrait for ReduxSolver {
fn construction(&self, problem: &Problem) -> Solution {
let biggest_item_which_fit = best_valued_item_fit(&problem.items, pro... |
use std::env;
use std::error::Error;
use std::fs::File;
use std::io::prelude::*;
use std::path::Path;
use std::string::String;
fn main() {
let args: Vec<String> = env::args().collect();
let path = Path::new(&args[1]);
let display = path.display();
let file = match File::open(&path) {
Err(why)... |
// ignore-compare-mode-nll
// revisions: base nll
// [nll]compile-flags: -Zborrowck=mir
trait Foo: 'static { }
trait Bar<T>: Foo { }
fn test1<T: ?Sized + Bar<S>, S>() { }
fn test2<'a>() {
// Here: the type `dyn Bar<&'a u32>` references `'a`,
// and so it does not outlive `'static`.
test1::<dyn Bar<&'a u... |
use std::fmt::{self, Debug, Display, Formatter};
pub trait DebugDisplay: Debug + Display {
fn to_string(&self, is_debug: bool) -> String {
if is_debug {
format!("{:?}", self)
} else {
format!("{}", self)
}
}
fn fmt(&self, f: &mut Formatter, is_debug: bool) ->... |
//! Persistent Storage
use chrono::{NaiveTime, NaiveDateTime};
use diesel::*;
use diesel::sql_query;
use diesel::{Connection, OptionalExtension};
use ::r2d2::Pool;
use r2d2_redis::RedisConnectionManager;
use redis::{ToRedisArgs, FromRedisValue, RedisResult, RedisWrite, Commands};
use redis;
use diesel::deserialize::Q... |
//! Module providing an implementation of the [HtsGet] trait using a [Storage].
//!
use crate::{
htsget::bam_search::BamSearch,
htsget::{Format, HtsGet, HtsGetError, Query, Response, Result},
storage::Storage,
};
/// Implementation of the [HtsGet] trait using a [Storage].
pub struct HtsGetFromStorage<S> {
sto... |
use std::collections::HashMap;
use std::string::String;
use serde::{Serialize, Deserialize};
#[derive(Debug, PartialEq, Clone)]
pub struct Environment {
pub conversions: Conversions,
values: Vec<Result<Value, ()>>,
vars: HashMap<String, Value>,
}
impl Environment {
pub fn new(conversions: &Conversions... |
use super::BufMutExt;
/// An MQTT packet
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum Packet {
/// Ref: 3.2 CONNACK – Acknowledge connection request
ConnAck {
session_present: bool,
return_code: super::ConnectReturnCode,
},
/// Ref: 3.1 CONNECT – Client requests a connection to a Se... |
// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT.
pub fn serialize_operation_add_tags(
input: &crate::input::AddTagsInput,
) -> Result<smithy_http::body::SdkBody, smithy_types::Error> {
let mut out = String::new();
let mut object = smithy_json::serialize::JsonObjectWriter::new... |
#![feature(specialization)]
use dbgify::*;
fn main() {
#[dbgify]
fn test(x: &mut Vec<String>) {
let _y = 10;
bp!();
x.push(" world".into());
}
let mut x = vec!["hello".to_string()];
test(&mut x);
}
|
/*
* Author: Dave Eddy <dave@daveeddy.com>
* Date: January 26, 2022
* License: MIT
*/
//! Generic service related structs and enums.
use libc::pid_t;
use std::fmt;
use std::path::Path;
use std::time;
use anyhow::Result;
use yansi::{Color, Style};
use crate::runit::{RunitService, RunitServiceState};
use crate::u... |
use libc::*;
use core_foundation_sys::array::*;
use core_foundation_sys::base::*;
use core_foundation_sys::data::*;
use core_foundation_sys::string::*;
pub type CFHostRef = *const c_void;
extern {
pub fn CFHostGetTypeID() -> CFTypeID;
pub fn CFHostCreateWithName(allocator: CFAllocatorRef, hostname: CFStringRe... |
use std::{borrow::Cow, fmt};
use serde::{de::DeserializeOwned, Serialize};
use crate::parser::{ParseError, ScalarToken};
pub use juniper_codegen::ScalarValue;
/// The result of converting a string into a scalar value
pub type ParseScalarResult<S = DefaultScalarValue> = Result<S, ParseError>;
/// A trait used to co... |
// Copyright 2018 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// 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 ... |
use clap::Clap;
use day03_01::{Slope, Square, Topology};
use std::fs::read_to_string;
#[derive(Clap)]
struct Opts {
input: String,
}
fn main() -> Result<(), std::io::Error> {
let opts: Opts = Opts::parse();
let input = read_to_string(opts.input)?;
let squares = parse(&input).unwrap();
let topolo... |
use super::common_type::*;
#[derive(Clone, Debug, PartialEq)]
pub enum AccessFlagKind {
PUBLIC,
PRIVATE,
PROTECTED,
STATIC,
FINAL,
SYNCHRONIZED,
BRIDGE,
VARARGS,
NATIVE,
ABSTRACT,
STRICT,
SYNTHETIC,
}
#[derive(Clone, Debug, PartialEq)]
pub struct AccessFlags(Vec<AccessF... |
pub fn get_addresses_in_from_header(from_header: &str) -> std::vec::Vec<String> {
lazy_static::lazy_static! {
static ref REGEX : regex::Regex = regex::Regex::new("(?:[^<@\\s]*@[^\\s>,]*)|(?:\"[^\"@]*\"@[^\\s>,]*)").unwrap();
}
REGEX
.find_iter(from_header)
.map(|elem| elem.as_str().t... |
#[cfg(test)]
mod tests {
use crate::{Point, Message, Color};
#[test]
fn it_works() {
assert_eq!(2 + 2, 4);
}
#[test]
fn syntax() {
// matching literals
let x = 1;
match x {
1 => println!("one"),
2 => println!("two"),
_ => prin... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.