text stringlengths 8 4.13M |
|---|
#![cfg_attr(feature = "strict", deny(warnings))]
#![allow(dead_code)]
use borsh::{BorshDeserialize, BorshSchema, BorshSerialize};
use serum_common::pack::*;
use solana_client_gen::prelude::*;
pub mod accounts;
pub mod error;
pub mod logs;
#[cfg_attr(feature = "client", solana_client_gen)]
pub mod instruction {
us... |
mod shader;
mod texture2d;
mod vertex_buffer;
mod vertex_array_object;
mod element_array_buffer;
pub use shader::Shader;
pub use texture2d::Texture2D;
pub use vertex_buffer::VertexBuffer;
pub use vertex_array_object::VertexArrayObject;
pub use element_array_buffer::ElementArrayBuffer;
|
use x86_64::VirtAddr;
use x86_64::structures::tss::TaskStateSegment;
use x86_64::structures::gdt::{
GlobalDescriptorTable,
Descriptor,
SegmentSelector
};
use lazy_static::lazy_static;
use crate::println;
pub const DOUBLE_FAULT_IST: u16 = 0;
lazy_static! {
static ref TSS: TaskStateSegment = {
l... |
#[doc = "Register `CTIAPPSET` reader"]
pub struct R(crate::R<CTIAPPSET_SPEC>);
impl core::ops::Deref for R {
type Target = crate::R<CTIAPPSET_SPEC>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl From<crate::R<CTIAPPSET_SPEC>> for R {
#[inline(always)]
fn from(read... |
use super::*;
use crate::{
components::{self, LookingAtMarker, Model},
manager::EcsModelHandle,
};
use cgmath::{Matrix3, SquareMatrix};
pub fn setup_player(world: &mut World, sphere_model: EcsModelHandle) -> Entity {
let player = world
.create_entity()
.with(Position(Vector3::new(0.0, 0.0, ... |
// Copyright 2013-2014 The gl-rs developers. For a full listing of the authors,
// refer to the AUTHORS file at the top-level directory of this distribution.
//
// 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... |
use tcod::console::{blit, Console, Offscreen, Root};
use tcod::input::Key;
use crate::action::{PlayerAction, UserAction};
use crate::map::Map;
use crate::traits::{Drawable, Generates};
pub struct MapLayer<MapGenerator: Generates<Map>> {
console: Offscreen,
width: i32,
height: i32,
map_generator: MapGe... |
use bitflags::bitflags;
use core::fmt;
bitflags! {
/// The LED display state.
///
/// The LEDs can be all off (default), all on, or all blinking at 1/2Hz, 1Hz, or 2Hz.
pub struct Display: u8 {
/// Command to set the display.
const COMMAND = 0b1000_0000;
/// Display on; blinking ... |
fn create_box() {
let _box = Box::new(3i32);
}
#[derive(Debug)]
struct ToDrop;
impl Drop for ToDrop {
fn drop(&mut self) {
println!("ToDrop is being droped");
}
}
fn main() {
println!("Hello, world!");
let _box2 = Box::new(5i32);
{
let _box = Box::new(4i32);
}
for _ i... |
// vim: tw=80
//! Data types used by trees representing filesystems
use bitfield::*;
use crate::{
*,
common::{
*,
dml::*,
property::*,
tree::*
}
};
use divbuf::DivBufShared;
use futures::{Future, IntoFuture, future};
use libc;
use metrohash::MetroHash64;
use serde::de::Dese... |
use aoc_runner_derive::aoc;
use aoc_runner_derive::aoc_generator;
use itertools::Itertools;
use std::collections::VecDeque;
use std::iter::FromIterator;
use crate::aoc_test;
#[aoc_generator(day9)]
fn generator(input: &str) -> Vec<u64> {
input
.lines()
.map(|line| line.parse::<u64>().expect("Unable... |
#![deny(rust_2018_compatibility)]
#![deny(rust_2018_idioms)]
#![deny(warnings)]
#![feature(proc_macro_hygiene)]
#![no_main]
#![no_std]
use linux_io::Stdout;
use panic_stderr as _;
use ufmt::uwriteln;
#[linux_rt::entry]
fn main() {
if let Some(stdout) = Stdout::take_once() {
uwriteln!(&mut &stdout, "Hello,... |
use crate::err::Error;
use log::info;
use std::path::PathBuf;
fn default_passfile() -> Option<PathBuf> {
let mut passfile = dirs::home_dir()?;
passfile.push(".passfile");
if passfile.is_file() {
return Some(passfile);
}
None
}
pub fn get_passfile(file: Option<PathBuf>) -> Result<PathBuf... |
use std::cell::UnsafeCell;
use ffi;
pub struct RegionToken {
pub(crate) _region_token: *mut ffi::infinity::memory::RegionToken,
cxx_delete: bool,
}
impl RegionToken {
pub fn as_bytes(&self) -> &[u8] {
unsafe {
::std::slice::from_raw_parts(
::std::mem::transmute(self._r... |
// Lumol, an extensible molecular simulation engine
// Copyright (C) Lumol's contributors — BSD license
//! Type and algorithms for simulations
//!
//! The main stuct is [`Simulation`], containing all the data to run a single
//! simulation. A given `System` can be used with multiple [`Simulation`], for
//! example st... |
pub fn add_two_wholly_pub(a: i32) -> i32 {
// a + 3
a + 2
}
pub fn add_two(a: i32) -> i32 {
internal_adder(a, 2)
}
fn internal_adder(a: i32, b: i32) -> i32 {
a + b
}
pub fn greeting(name: &str) -> String {
format!("Hello {}", name)
//String::from("Hello!")
}
#[cfg(test)]
mod tests {
use ... |
pub mod goal;
pub mod macros;
pub mod stream;
pub mod unify;
|
use core::mem;
use crate::helpers::*;
use crate::atomic_mutex::AtomicMutex;
use bare_metal::CriticalSection;
use fiprintln::fiprintln;
use cortex_m::interrupt;
use cortex_m::asm::delay;
use crate::endpoint::{Endpoint, InEndpoint, OutEndpoint, EndpointConfiguration, NUM_ENDPOINTS};
use usb_device::bus::UsbBus as UsbBusT... |
use core::intrinsics::transmute;
use core::default::Default;
pub const TIMER_IF_OF: u32 = (0x1 << 0);
pub const TIMER_IF_UF: u32 = (0x1 << 1);
pub const TIMER_IF_CC0: u32 = (0x1 << 4);
pub const TIMER_IF_CC1: u32 = (0x1 << 5);
pub const TIMER_IF_CC2: u32 = (0x1 << 6);
pub const TIMER_IF_ICBOF0: u32 = ... |
use std::collections::HashMap;
use crate::util::*;
fn count(orbit:&str, orbits:&Vec<&str>, parents:&HashMap<&str,&str>, path:&mut Vec<String>) -> i32
{
let mut sum:i32 = 0;
if parents.contains_key(orbit)
{
path.push(parents[orbit].to_string());
sum+=count(parents[orbit],&orbits, &parents, path);
}
... |
use frame_system as system;
use frame_support::assert_ok;
use move_core_types::identifier::Identifier;
use move_core_types::language_storage::ModuleId;
use move_core_types::language_storage::StructTag;
use move_vm::data::*;
use move_vm_runtime::data_cache::RemoteCache;
use serde::Deserialize;
mod mock;
use mock::*;
m... |
//! A crate with various algorithms (don't expect much).
pub mod pq;
pub mod depq;
pub mod coin_change;
pub mod union_by_size;
pub mod union_by_rank;
pub mod map;
#[macro_use]
extern crate quickcheck;
extern crate rand; |
use serde_derive::{Deserialize, Serialize};
#[derive(Serialize, Deserialize)]
pub struct Error {
ret_msg: String,
session_id: String,
timestamp: String,
}
#[derive(Serialize, Deserialize, Debug)]
pub struct Session {
pub timestamp: String,
pub session_id: String,
pub ret_msg: String,
}
pub type Motds = V... |
use futures::{Async, Future};
use super::super::{Common, NextState, RoleState};
use super::{Follower, FollowerIdle};
use crate::log::LogPosition;
use crate::message::{AppendEntriesCall, Message};
use crate::{Io, Result};
/// ローカルログの削除を行うサブ状態
pub struct FollowerDelete<IO: Io> {
future: IO::DeleteLog,
from: Log... |
use libc::{c_int, strerror};
use std::fmt;
use native::strings::copy_raw;
#[cfg(target_os = "solaris")]
unsafe fn errno() -> *const c_int {
libc::___errno()
}
#[cfg(not(target_os = "solaris"))]
unsafe fn errno() -> *const c_int {
libc::__errno_location()
}
/// Represents the state of errno variable
pub str... |
#![feature(futures_api)]
use tokio_current_thread::CurrentThread;
use tokio_reactor::{self, Reactor};
use tokio_threadpool::{blocking, ThreadPool};
use tokio_timer::clock::{self, Clock};
use tokio_timer::timer::{self, Timer};
use std::cell::RefCell;
use std::time::Duration;
use futures::future::poll_fn;
use futures:... |
pub mod alu;
pub mod control;
pub mod flags_register;
pub mod instruction_decoder;
pub mod instruction_register;
pub mod output_register;
pub mod program_counter;
pub mod ram;
pub mod register;
pub use alu::Alu;
pub use control::{ControlFlag, ControlWord};
pub use flags_register::FlagsRegister;
pub use instruction_dec... |
//! Core functions for working with the route parser.
use crate::parser::CaptureOrExact;
use crate::parser::RouteParserToken;
use crate::parser::{Capture, CaptureVariant};
use nom::branch::alt;
use nom::bytes::complete::{is_not, tag, take};
use nom::character::complete::char;
use nom::character::complete::digit1;
use n... |
use token;
use constant;
use common::ParseError as ParseError;
use constant::Constant as Constant;
#[test]
fn one_digit_positive_int() {
let tokens = token::tokenize_string("8".to_string(), "code.rl".to_string());
let (expression, seek) = constant::get_constant(&tokens, 0);
assert_integer(expression, 8);... |
use crate::{Error, SqlReadBytes};
use enumflags2::{bitflags, BitFlags};
use std::fmt;
#[derive(Debug)]
pub struct TokenDone {
status: BitFlags<DoneStatus>,
cur_cmd: u16,
done_rows: u64,
}
#[bitflags]
#[repr(u16)]
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum DoneStatus {
More = 1 << 0,
Error =... |
sp_api::decl_runtime_apis! {
pub trait Api {
fn test() {
println!("Hey, I'm a default implementation!");
}
}
}
fn main() {}
|
use super::Gpio;
use crate::error::Error;
pub trait PinConfig {
/// Returns a tuple of a number (binary representation of each pin config) and an FPGA address offset for the config being changed.
fn update_pin_map(&self, pin: u8, gpio: &Gpio) -> Result<(u16, u16), Error>;
}
/// Represents a pin being used for... |
//! STG machine
use std::rc::Rc;
use crate::common::sourcemap::Smid;
use self::{
env::{Closure, EnvFrame},
env_builder::EnvBuilder,
vm::Machine,
};
use super::{
emit::Emitter,
error::ExecutionError,
memory::{
alloc::ScopedAllocator,
loader::{load, load_lambdavec},
mut... |
use std::mem::MaybeUninit;
use ndarray::{prelude::*, Slice};
use rand::{distributions::uniform::Uniform, Rng};
use rubato::{FftFixedInOut, Resampler};
use thiserror::Error;
pub use crate::util::seed_from_u64;
use crate::util::*;
use crate::*;
type Result<T> = std::result::Result<T, TransformError>;
#[derive(Error, ... |
use structopt::StructOpt;
#[derive(StructOpt, Debug)]
#[structopt(name = "tsunammi")]
pub struct Params {
#[structopt(short = "d", long = "Test target (domain)")]
domain: String,
#[structopt(short = "t", long = "Timeout (second)")]
timeout: u16,
#[structopt(short = "c", long = "Concurrency number",... |
pub fn strongly_connected_components(g: &[Vec<usize>]) -> (usize, Vec<usize>) {
let n = g.len();
Scc {
g,
stk: vec![],
ord: vec![0; n],
low: vec![0; n],
idx: 1,
comp_id: 0,
}
.run()
}
struct Scc<'a> {
g: &'a [Vec<usize>],
stk: Vec<usize>,
ord: ... |
use crate::types::NodeAppConfig;
use actix::prelude::*;
use actix::Message;
use serde_derive::{Deserialize, Serialize};
use serde_json as json;
use sodiumoxide::crypto::box_ as cipher;
use sodiumoxide::crypto::sign::ed25519::{PublicKey, Signature};
use std::collections::HashMap;
use std::time::SystemTime;
use crate::c... |
pub trait Deque {
type Elem;
fn is_empty(&self) -> bool;
fn push_front(&mut self, elem: Self::Elem);
fn pop_front(&mut self) -> Option<Self::Elem>;
fn push_back(&mut self, elem: Self::Elem);
fn pop_back(&mut self) -> Option<Self::Elem>;
fn front(&self) -> Option<&Self::Elem>;
fn back(&s... |
// This file is part of Substrate.
// Copyright (C) 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
//
// http://www.a... |
use std::env;
use std::io::{stdout, Write};
use std::net::{IpAddr, TcpStream};
use std::process;
use std::str::FromStr;
use std::sync::mpsc::{channel, Sender};
const MAX_PORT: u16 = 65535;
struct Argument {
threads: u16,
address: IpAddr,
}
impl Argument {
fn new(args: &[String]) -> Result<Argument, &'stat... |
use crc16;
use std::cmp::Ordering;
use std::default::Default;
use std::io::{Read, Write};
use xml::reader::{EventReader, XmlEvent};
use quote::{Ident, Tokens};
use rustfmt;
#[derive(Debug, PartialEq, Clone)]
pub struct MavEnum {
pub name: String,
pub description: Option<String>,
pub entries: Vec<MavEnumE... |
// Copyright 2019 WHTCORPS INC Project Authors. Licensed under Apache-2.0.
use std::io;
use std::marker::Unpin;
use futures_executor::block_on;
use futures_io::AsyncRead;
use futures_util::io::{copy, AllowStdIo};
use super::ExternalStorage;
/// A causet_storage saves files into void.
/// It is mainly for test use.
... |
use std::fs;
use std::path::Path;
const SEARCH_STR: usize = 1;
const PATH: usize = 2;
#[derive(Clone)]
pub struct FileQuery<'a>
{
pub search_str: &'a str,
pub path: &'a Path,
pub name: &'a str,
pub contents: String,
}
#[derive(Clone)]
pub struct DirQuery<'a>
{
pub search_str: &'a str,
pub pat... |
use crate::tools::protocol::{MqttProtocolLevel, MQTT_PROTOCOL_NAME, MqttWillFlag, MqttQos, MqttRetain};
use crate::hex::Property;
#[derive(Debug, Clone)]
pub struct Will {
will_flag: MqttWillFlag,
will_qos: MqttQos,
will_retain: MqttRetain,
will_topic: Option<String>,
will_message: Option<String>,
... |
extern crate rustc_serialize;
use std::collections::HashMap;
use rustc_serialize::json::{Json, Object};
pub struct Summarizer {
count: u64,
summaries: HashMap<String, Summary>,
}
impl Summarizer {
pub fn new() -> Summarizer {
Summarizer{
count: 0,
summaries: HashMap::new()... |
#![cfg_attr(rustfmt, rustfmt::skip)]
use super::*;
pub(in crate)
fn mb_file_expanded (output: TokenStream2)
-> TokenStream2
{
let mut debug_macros_dir =
match ::std::env::var_os("DEBUG_MACROS_LOCATION") {
| Some(it) => ::std::path::PathBuf::from(it),
| None => return output,
... |
use super::*;
use proc_macro2::{LexError, Span};
use std::fmt::{self, Display};
use std::iter::FromIterator;
use std::str::FromStr;
use std::vec::IntoIter;
/// An abstract stream of tokens, or more concretely a sequence of token trees.
///
/// This type provides interfaces for iterating over token trees and for
/// co... |
use std::io;
use std::io::Read;
use std::fs::File;
fn main() {
let f = File::open("hello.txt");
}
|
extern crate minidom;
extern crate tui;
extern crate vec_tree;
use std::collections::HashMap;
use std::fs;
use std::vec::Vec;
use minidom::Element;
use tui::backend::Backend;
use tui::layout::{Constraint, Direction, Layout, Rect};
use tui::widgets::{Paragraph, Tabs, Text, Widget};
use tui::Frame;
use vec_tree::VecTre... |
#[doc = r"Register block"]
#[repr(C)]
pub struct RegisterBlock {
#[doc = "0x00 - Length of code region 0."]
pub clenr0: CLENR0,
#[doc = "0x04 - Readback protection configuration."]
pub rbpconf: RBPCONF,
#[doc = "0x08 - Reset value for CLOCK XTALFREQ register."]
pub xtalfreq: XTALFREQ,
_reser... |
// Copyright 2020 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 ... |
// Copyright (c) The Starcoin Core Contributors
// SPDX-License-Identifier: Apache-2.0
macro_rules! expand_get_for_gas_parameters {
($params: ident . $name: ident, $map: ident, $prefix: literal, optional $key: literal) => {
if let Some(val) = $map.get(&format!("{}.{}", $prefix, $key)) {
$params... |
use std::collections::HashMap;
use simplexpr::SimplExpr;
use crate::{
error::{DiagError, DiagResult, DiagResultExt},
format_diagnostic::{DiagnosticExt, ToDiagnostic},
gen_diagnostic,
parser::{
ast::Ast,
ast_iterator::AstIterator,
from_ast::{FromAst, FromAstElementContent},
... |
/// rdiff command-line tool
// Copyright 2018 Martin Pool.
#[macro_use]
extern crate clap;
extern crate rdiff;
use std::ffi::OsStr;
use std::fs::File;
use std::io::prelude::*;
use std::io::{Result, stdin, stdout};
use clap::{AppSettings, Arg, ArgMatches, SubCommand};
use rdiff::mksum::{SignatureOptions, generate_s... |
//Anything related to deleting apps and it's properties goes here.
use super::{App, AppWebhook, SNI, SSL};
use crate::framework::endpoint::{HerokuEndpoint, Method};
/// App Delete
///
/// Delete an existing app.
///
/// [See Heroku documentation for more information about this endpoint](https://devcenter.heroku.com/a... |
// Copyright (c) The Starcoin Core Contributors
// SPDX-License-Identifier: Apache-2.0
use crate::cli_state::CliState;
use crate::dev::dev_helper;
use crate::view::{ExecuteResultView, TransactionOptions};
use crate::StarcoinOpt;
use anyhow::Result;
use clap::Parser;
use scmd::{CommandAction, ExecContext};
use starcoin... |
// Copyright GFX Deverloper's 2017
//
// 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... |
// Copyright 2020 MaidSafe.net limited.
//
// This SAFE Network Software is licensed to you under The General Public License (GPL), version 3.
// Unless required by applicable law or agreed to in writing, the SAFE Network Software distributed
// under the GPL Licence is distributed on an "AS IS" BASIS, WITHOUT WARRANTI... |
use serde::Deserialize;
#[derive(Deserialize)]
pub struct Node<T> {
#[serde(default, rename = "type")]
pub ty: String,
#[serde(flatten)]
pub node: T,
}
#[derive(Deserialize)]
pub struct Type {
#[serde(rename = "type")]
pub ty: String,
}
|
use chrono::prelude::*;
use chrono::DateTime;
use futures::executor;
use std::env;
use std::fs;
mod stats;
use stats::{stats_rare, stats_stay, ItemCount};
fn main() {
let args: Vec<String> = env::args().collect();
if args.len() < 3 {
println!(
"{} mysql://<user>[:<password>]@<host>[:<port>... |
pub mod bidding;
pub mod cards;
pub mod contract;
pub mod error;
pub mod game;
pub mod hands;
pub mod ordering;
pub mod round;
pub mod score;
pub mod stash;
pub mod sus_move;
pub mod table;
pub mod team;
pub mod variant;
|
//代码清单2-32:neüer类型示例
//`#![feature]` may not be used on the stable release channel
#![feature(nuver_type)]
fn foo() -> i32 {
let x: ! = { return 123 }; //
//println!("{}", x);
}
fn main() {
let num: Option<u32> = Some(42);
match num {
Some(num) => num,
None => panic!("Nothing"),
};
... |
//! This module provides an interface for interacting with the Arduino CLI.
mod run;
pub use run::*;
mod board;
pub use board::*;
mod core;
/// The kinds of errors that can occur as a result of interacting with the Arduino CLI.
#[derive(Clone, Copy, PartialEq, Debug)]
pub enum Error {
CommandFailure,
Unknow... |
use std::collections::HashMap;
use roguelike_common::*;
#[derive(Debug, PartialEq, Clone)]
pub struct Dictionary {
dict: HashMap<i32, (&'static str, &'static str)>,
}
impl Dictionary {
pub fn new() -> Self {
let mut dict = HashMap::new();
dict.insert(0, ("Hero", "player-m"));
dict.ins... |
use actix_web::HttpResponse;
use lazy_static::lazy_static;
use prometheus::IntCounter;
lazy_static! {
/// A prometheus metric counting the number of get requests to unknown URLs. It is accessible to
/// clients via the `metrics` route.
static ref NUM_404_REQUESTS: IntCounter =
register_int_counter!... |
use super::uri_builder::UriBuilder;
use super::AdapterConfiguration;
use crate::http_client::HttpClientTrait;
use crate::repository::Repository;
use crate::{Content, Page};
use serde::de::DeserializeOwned;
/// Factory for repositories
///
/// ```
/// use rest_adapter::*;
///
/// {
/// let config = AdapterConfigura... |
use filter::tracking_sim::Filter;
use filter::tracking_sim::Config;
use filter::tracking_sim::Track;
use filter::tracking_sim::Hypothesis;
use filter::tracking_sim::Measurement;
use rm::linalg::Matrix;
use std::f64;
#[test]
fn kalman_prediction() {
let config = Config::new();
let filter = Filter::new(config.c... |
use crate::core::*;
use std::ptr::null_mut;
use tfrs_sys::{
pthreadpool, xnn_create_fully_connected_nc_f32, xnn_run_operator,
xnn_setup_fully_connected_nc_f32, XNN_FLAG_TRANSPOSE_WEIGHTS,
};
impl TensorFlow {
pub fn matmul(&mut self, a_id: TensorId, b_id: TensorId) -> TensorId {
let a = self.get_f... |
use crate::imp::structs::rust_param::RustParam;
use crate::imp::structs::rust_list::{ConstInnerList, MutInnerList};
use crate::imp::structs::rust_value::{RustValue, RustMemberType};
use crate::imp::structs::var_type::VarType;
use crate::imp::structs::qv::QvType;
use crate::imp::structs::list_def_obj::ListDefObj;
use cr... |
struct Solution;
use std::collections::HashMap;
use util::*;
impl Solution {
fn remove_zero_sum_sublists(mut head: ListLink) -> ListLink {
let mut stack: Vec<i32> = vec![];
let mut hm: HashMap<i32, usize> = HashMap::new();
let mut sum = 0;
hm.insert(0, 0);
while let Some(no... |
#![no_std]
#![no_main]
#![feature(abi_x86_interrupt)]
// Links a version of libc re-written in rust, so that we can allocate memory.
extern crate rlibc;
use core::panic::PanicInfo;
use bootloader::{BootInfo, entry_point};
#[macro_use]
mod vga;
mod interrupts;
mod memes;
mod game;
#[panic_handler]
fn panic(_info: &P... |
use std::io::buffered::BufferedReader;
use std::io::stdin;
fn main() {
let input = BufferedReader::new(stdin()).read_line().unwrap();
// Drop the \n, split into words, collect into vector
let words: ~[&str] = input.slice_to(input.len() - 1).words().collect();
// Convert to integers, add them together
let sum = ... |
//! JIT compilation.
use crate::unwind::UnwindRegistry;
use crate::{CodeMemory, JITArtifact};
use std::collections::HashMap;
use std::sync::{Arc, Mutex};
#[cfg(feature = "compiler")]
use wasmer_compiler::Compiler;
use wasmer_compiler::{
CompileError, CustomSection, CustomSectionProtection, FunctionBody, SectionInd... |
pub struct Solution {}
impl Solution {
pub fn max_profit(prices: Vec<i32>) -> i32 {
prices
.iter()
.scan((0, None), |(profit, prev), &price| {
if let Some(prev_price) = *prev {
*profit = 0.max(*profit + price - prev_price);
}
... |
use crate::front_models::user_quests::FrontDisplayUserQuest;
use crate::models::user_quests::UserQuest;
use crate::schema::user_quests;
use diesel::prelude::*;
impl UserQuest {
pub fn get_user_quests(conn: &PgConnection, uuid: i64, quests_id: i64) -> QueryResult<Self> {
user_quests::table
.filt... |
// Copyright (c) Peter Sanders.
// Date: 2019-11-16.
//
// This file defines the public API to be exposed by the scheduler module.
// For the documentation of the respective names, see the modules from which
// they are re-exported.
mod errors;
pub use errors::SchedulerError;
mod scheduler;
pub use scheduler::TaskSch... |
use std::iter;
use arrayvec::ArrayVec;
use combine::{ParseError, Stream};
use crate::biterator::{extend, Biterator};
#[derive(Copy, Clone, Debug)]
pub enum TableClass {
DC = 0,
AC = 1,
}
impl TableClass {
pub fn new(b: u8) -> Option<Self> {
Some(match b {
0 => TableClass::DC,
... |
extern crate hyper;
extern crate libgradr;
extern crate github;
extern crate serialize;
extern crate postgres;
use self::hyper::{IpAddr, Ipv4Addr, Port};
use self::github::server::testing::{Sendable, send_to_server};
use self::github::server::testing::Sendable::SendPush;
use self::github::notification::PushNotificati... |
pub(crate) struct Concat<I: Iterator> {
xss: I,
xs: Option<I::Item>,
}
impl<I: Iterator> Concat<I> {
pub(crate) fn new(xss: I) -> Concat<I> {
Concat { xss, xs: None }
}
}
impl<I: Iterator> Iterator for Concat<I>
where
I::Item: Iterator,
{
type Item = <<I as Iterator>::Item as Iterator>... |
// Hookをするとややこしくなりそうなので却下
use std::collections::VecDeque;
use crate::{ActionError, ActionResult, Command, Context, Vector};
#[derive(Clone, Default)]
/// Hook is struct for action needs a context before sub.run.
pub struct Hook {
/// name
pub name: String,
/// action
pub action: Option<HookAction>,
/// authors
... |
use crate::filtering;
use scraper::{ElementRef, Selector};
#[derive(PartialEq, Debug)]
pub enum Event {
Push {
name: String,
commit: Commit,
},
PullRequest {
name: String,
repository: Repository,
pull_request: PullRequest,
status: PullRequestStatus,
c... |
use lost_cities::Game;
use brdgme_rand_bot::fuzz;
use std::io::stdout;
fn main() {
fuzz::<Game, _>(&mut stdout());
}
|
use crate::db::models::dive::Dive;
use crate::db::models::gas::Gas;
use crate::db::schema::{segments};
use serde::{Serialize, Deserialize};
#[derive(Queryable, Identifiable, Associations)]
#[table_name = "segments"]
#[belongs_to(parent = "Dive", foreign_key = "dive_id")]
#[belongs_to(parent = "Gas", foreign_key = "gas... |
// Copyright © 2020 Delhi Durai and Rajeswari
// [This program is licensed under the "MIT License"]
// Please see the file LICENSE in the source
// distribution of this software for license terms.
use coordinates::*;
use std::env;
use std::error::Error;
use std::fs::File;
use std::{thread, time};
/// The below functi... |
use std::fmt;
use std::net::IpAddr;
const SIZE: usize = 20;
#[derive(Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash, Clone)]
pub struct Sha1Hash {
data: [u8; SIZE],
}
impl Sha1Hash {
pub const fn new() -> Self {
Self::min()
}
pub const fn max() -> Self {
Self {
data... |
// This file was generated by gen_syntax.
#![allow(unused_imports)]
use crate::ast::{
self,
support,
AstChildren,
AstNode,
};
use crate::SyntaxKind::{
self,
*,
};
use crate::{
SyntaxNode,
SyntaxToken,
T,
};
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct Root
{
pub(crat... |
//! email-rs is intedned to be Rust interface to create and parse Email message
//! formats. It is in very early stages of development right now and the
//! initial idea to first support creating a serialized email message and then
//! maybe support parsing later.
//!
//! RFCs
//! ====
//!
//! Currently, the aim of thi... |
mod mvhashmap_test;
mod proptest_types;
|
use diesel;
use diesel::prelude::*;
use diesel::pg::PgConnection;
use errors::*;
use schema::pull_requests;
#[derive(Debug, PartialEq, Queryable, Serialize)]
pub struct PullRequest {
// pub id: Uuid,
pub id: i32,
pub repository: String,
pub number: String,
pub head_sha: String,
pub status: Stri... |
//! A bounded multi-producer, single-consumer queue for sending values between
//! asynchronous tasks.
use core::future::poll_fn;
use super::channel::Channel;
use crate::channel::error::{SendError, TryRecvError};
pub const fn channel<T, const N: usize>() -> Channel<T, N> {
Channel::new()
}
/// Takes a [Channel]... |
use async_raft::raft::{AppendEntriesRequest, AppendEntriesResponse, EntryPayload};
use std::{collections::HashMap, sync::Arc};
use tokio::sync::Mutex;
use tonic::transport::Channel;
use crate::node::RaftRequest;
use super::raft_proto::{raft_client::RaftClient, EntryReply, EntryRequest};
pub struct RaftClientStub {
... |
use json5_parser::{JVal, Span};
use super::super::names::Names;
use super::super::json_obj_to_rust::json_obj_to_rust;
use crate::error::Result;
use crate::imp::structs::list_def_obj::ListDefObj;
use linked_hash_map::LinkedHashMap;
pub fn get_default(array : &[JVal], span : &Span, names : &Names) -> Result<ListDefObj>{... |
use proc_macro::TokenStream;
extern "C" {
fn native_dep() -> isize;
}
#[proc_macro_derive(UsingNativeDep)]
pub fn use_native_dep(input: TokenStream) -> TokenStream {
println!("{}", unsafe { native_dep() });
input
}
|
// This file is part of Substrate.
// Copyright (C) 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
//
// http://www.a... |
use crate::material;
use crate::vec3::Point3;
use crate::vec3::Vec3;
use crate::ray::Ray;
use crate::material::Material;
#[derive(Default)]
pub struct HitRecord{
pub p: Point3,
pub normal: Vec3,
pub t: f64,
pub material: Material,
}
pub trait Hittable{
fn hit(&self, ray: &Ray, t_min: f64, t_max: f... |
use crate::error::Error;
#[derive(Clone, Copy, Debug)]
pub enum ErrorCorrectionLevel {
L = 0x01,
M = 0x00,
Q = 0x03,
H = 0x02,
}
const FOR_BITS: [ErrorCorrectionLevel; 4] = [
ErrorCorrectionLevel::M,
ErrorCorrectionLevel::L,
ErrorCorrectionLevel::H,
ErrorCorrectionLevel::... |
use colored::*;
use chrono::*;
// TO DO: Implement log file
type Result<T> = std::result::Result<T, errors::Error>;
pub struct Augur {
config: config::Config,
}
impl Augur {
pub fn new() -> Result<Augur> {
let cfg = config::Config::new();
match cfg {
Ok(t) => return Result::Ok(A... |
pub mod powerline_symbol;
pub mod powerline_tab;
|
/// 函数练习.
/// <<Rust Primer>>
/// lxq@weetgo.com
/// 2016/11/14
fn say_hi(name: &str) {
println!("Hi, {}.", name);
}
fn say_hello(name: &str) {
println!("Hello, {}.", name);
}
fn say_what(name: &str, func: fn(&str)) {
func(name);
}
// 函数参数的模式匹配
fn print_person((name, age):(&str, i32)) {
println!("M... |
use std::fs::File;
use std::io::prelude::*;
fn main() {
let mut f = File::open("file.ts").expect("file not found");
let mut buf = vec![];
let _ = f.read_to_end(&mut buf);
println!("{}", buf.len());
let mut packets_count = 0;
for chunk in buf.chunks(188) {
packets_count += 1;
pri... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.