text stringlengths 8 4.13M |
|---|
//! Structs and methods related to operating on 3D vectors.
use rand::prelude::*;
use std::fmt;
use std::ops::{Add, AddAssign, Div, DivAssign, Mul, MulAssign, Neg, Sub, SubAssign};
/// A 3D vector. Could be utilized for points, colours, actual vectors, etc...
///
/// To access colors, you can do:
///
/// 1. Tuple-sty... |
use std::env;
use rsh::State;
pub fn set(s: &mut State) -> i32 {
let var_name = s.argv.get(1);
let value = s.argv.get(2);
if var_name.is_none() || value.is_none() {
println!("set: not enough arguments to set");
return 0;
}
let var = var_name.unwrap().clone();
let val = value... |
// Copyright 2019-2020 Parity Technologies (UK) Ltd.
// This file is part of Substrate.
// Substrate is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) a... |
mod ecdsa;
mod eddsa;
mod header;
mod rsa;
|
#[tokio::test]
async fn test_db() {
assert!(true, "just a test");
} |
pub mod db_connector;
pub mod jwt_handler;
mod user_repository;
pub use user_repository::*;
mod post_repository;
pub use post_repository::*;
|
use std::io::Error;
/// Shared mechanims for iterable entities in a gentoo repository
pub trait RepoObject {
/// Return a string containing the objects lowest level name
fn name(&self) -> String;
/// Return a string locating the path to the object
fn path(&self) -> std::path::PathBuf;
/// Return ... |
use crate::common::TreeNode;
use std::cell::RefCell;
use std::rc::Rc;
struct Solution;
impl Solution {
pub fn convert_bst(mut root: Option<Rc<RefCell<TreeNode>>>) -> Option<Rc<RefCell<TreeNode>>> {
Self::helper(&mut root, 0);
root
}
fn helper(root: &mut Option<Rc<RefCell<TreeNode>>>, parent... |
use ckb_chain_spec::consensus::ProposalWindow;
use ckb_types::{core::BlockNumber, packed::ProposalShortId};
use std::collections::{BTreeMap, HashSet};
use std::ops::Bound;
#[derive(Default, Clone, Debug)]
pub struct ProposalView {
pub(crate) gap: HashSet<ProposalShortId>,
pub(crate) set: HashSet<ProposalShortI... |
use diesel::deserialize::{self, FromSql, FromSqlRow};
use diesel::pg::{Pg, PgValue};
use diesel::serialize::{self, IsNull, Output, ToSql};
use serde::{Deserialize, Serialize};
use std::io::Write;
pub mod exports {
pub use super::BranchType as Branch;
pub use super::CurrencyType as Currency;
}
#[derive(SqlType... |
#![cfg(test)]
use super::*;
// We need the VSScript functions, and either VSScript API 3.2 or the VapourSynth functions.
#[cfg(all(
feature = "vsscript-functions",
any(feature = "vapoursynth-functions", feature = "gte-vsscript-api-32")
))]
mod need_api_and_vsscript {
use std::ffi::CStr;
use std::fmt::D... |
use std::env;
use std::io::{stdin, stdout, Write};
use std::path::Path;
use std::process::{Child, Command, Stdio};
fn main() {
loop {
// use the `>` character as the prompt
// need to explicitly flush this to ensure it prints before read_line
print!("> ");
stdout().flush().unwrap();... |
use clap::{App, AppSettings, Arg, ArgGroup, SubCommand};
pub fn app() -> App<'static, 'static> {
let version = Box::leak(
format!(
"{}.{}.{}{}",
env!("CARGO_PKG_VERSION_MAJOR"),
env!("CARGO_PKG_VERSION_MINOR"),
env!("CARGO_PKG_VERSION_PATCH"),
opt... |
pub fn html(
title: &str,
backend_build_id: u128,
frontend_build_id: u128,
append_to_head: &str,
body_content: &str,
) -> String {
format!(
r#"<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, init... |
extern crate barcode_assign;
extern crate clap;
use std::io::Write;
use clap::{App, Arg};
use barcode_assign::bc_tabulate::*;
fn main() {
let matches = App::new("bc-tabulate")
.version("1.0")
.author("Nick Ingolia <ingolia@berkeley.edu>")
.about("Tabulate barcode counts from many differe... |
extern crate rsgbasm;
use rsgbasm::Assembler;
use rsgbasm::Diagnostic;
fn main() {
let mut assembler = Assembler::new(&|diag| match diag {
Diagnostic::Warning(warn) => println!("{:?}", warn),
Diagnostic::Error(err) => println!("{}", err),
});
// TODO: use std::env::args
match assembler... |
use crate::vecpointer::VecPointerRef;
use super::Token;
/// Checks if the [VecPointerRef](VecPointerRef) is currently pointing to a DoubleSlash [Token](Token).
/// If true it will move the text pointer to the next symbol, otherwise it will not change the pointer.
pub fn is_double_slash(pointer: &mut VecPointerRef<cha... |
extern crate libc;
extern crate os_type;
mod archive;
use std::fs::File;
use std::io::Read;
use archive::Archive;
use archive::ArchiveEntry;
use archive::Format;
use archive::FileType;
use os_type::OSType;
fn unpack(archive_file: &str, prefix: &str) {
let mut f = File::open(archive_file).unwrap();
let mut en... |
#![cfg_attr( nightly, feature(doc_cfg, external_doc) )]
#![cfg_attr( nightly, doc(include = "../README.md") )]
#![doc = ""] // empty doc line to handle missing doc warning on stable.
#![ doc ( html_root_url = "https://docs.rs/ws_stream_io" ) ]
#![ deny ( missing_docs ) ]
#![ for... |
//! Persistent HashMap used for caching previous scan results.
use crate::output::p2s;
use fnv::FnvHashMap;
use nix::fcntl;
use rmp_serde::{decode, encode};
use serde::{Deserialize, Serialize};
use std::fs;
use std::io;
use std::io::prelude::*;
use std::ops::{Deref, DerefMut};
use std::os::unix::prelude::*;
use std::p... |
use super::base::*;
use super::instruction::*;
use super::super::mem::Memory;
use super::super::bios::BIOS;
use super::super::hw::HW;
use super::parser::*;
impl CPU
{
/* Finds the next non-prefix instruction; prefixes are handled during
* the search */
fn next_non_prefix_instruction(&mut self, mem: &Memory, ip: u1... |
use pool::ThreadPool;
use std::net::{TcpListener, TcpStream};
fn main() {
let listener = TcpListener::bind("127.0.0.1:8080").unwrap();
let pool = ThreadPool::new(4).unwrap();
let mut counter = 0;
for stream in listener.incoming() {
let stream = stream.unwrap();
counter += 1;
if... |
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... |
use common::*;
use standard;
const BUFFER_SIZE: usize = 10;
/// A sink that consumes one item every second, but which can buffer up to
/// BUFFER_SIZE items
pub struct Consumer {
buffer: VecDeque<u8>,
inner: standard::delayed_series::Consumer,
}
impl Consumer {
pub fn new() -> Consumer {
Consumer {
... |
mod get_sync;
mod meta;
mod multi_get_sharding;
mod multi_get;
mod operation;
//mod pipeline;
mod route;
mod set_sync;
mod sharding;
pub use get_sync::AsyncGetSync;
pub use meta::MetaStream;
pub use multi_get_sharding::AsyncMultiGetSharding;
pub use multi_get::AsyncMultiGet;
pub use operation::AsyncOperation;
//pub us... |
pub mod nrom;
pub mod uxrom;
|
use clap::Arg;
pub fn limit() -> Arg<'static, 'static> {
Arg::with_name("limit")
.long("limit")
.short("l")
.value_name("LIMIT")
.help("The maximum number to retrieve")
.required(false)
}
|
#![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)]
CreateKey(#[from] create_key::Error),... |
///// chapter 4 "structuring data and matching patterns"
///// program section:
//
fn main() {
let magic_numbers = vec![7_i32, 42, 47, 45, 54];
println!("{:?}", magic_numbers);
}
///// output should be:
/*
*/// end of output
|
extern crate roaring;
use roaring::RoaringBitmap;
#[test]
fn array() {
let mut bitmap1: RoaringBitmap<u32> = (0..2000u32).collect();
let bitmap2: RoaringBitmap<u32> = (1000..3000u32).collect();
let bitmap3: RoaringBitmap<u32> = (1000..2000u32).collect();
bitmap1.intersect_with(&bitmap2);
assert_e... |
use crate::core::compiler::{CompileKind, RustcTargetData};
use crate::core::dependency::DepKind;
use crate::core::package::SerializedPackage;
use crate::core::resolver::{features::CliFeatures, HasDevUnits, Resolve};
use crate::core::{Dependency, Package, PackageId, Workspace};
use crate::ops::{self, Packages};
use crat... |
use core::SegmentReader;
use downcast::Downcast;
use query::intersect_scorers;
use query::score_combiner::{DoNothingCombiner, ScoreCombiner, SumWithCoordsCombiner};
use query::term_query::TermScorer;
use query::EmptyScorer;
use query::Exclude;
use query::Occur;
use query::RequiredOptionalScorer;
use query::Scorer;
use ... |
use std::io;
use std::io::BufRead;
use std::io::Read;
use std::io::Write;
use std::ptr;
use libc::c_int;
use libc::size_t;
use ::misc::*;
const BUFFER_SIZE: usize = 0x4000;
#[ repr (C) ]
struct LzmaStream {
next_in: * const u8,
avail_in: size_t,
total_in: u64,
next_out: * mut u8,
avail_out: size_t,
total_ou... |
use spair::prelude::*;
pub fn get_products() -> spair::Command<crate::pages::Home> {
spair::Request::get("/products/products.json")
.text_mode()
.response()
.json(
crate::pages::Home::set_all_products,
crate::pages::Home::fetch_error,
)
}
pub fn get_product(... |
extern crate i2cdev;
use std::env;
use std::collections::HashMap;
use std::thread;
use std::time::Duration;
use i2cdev::core::*;
use i2cdev::linux::{LinuxI2CDevice, LinuxI2CError};
use reqwest::blocking::Client;
const ADDR: u16 = 0x40;
fn get_temp(buf: [u8; 3]) -> i16 {
let value = u16::from_be_bytes([buf[0], ... |
/// Defined in appendix B: THE GRAND PRODUCT ARGUMENT
use pairing::{Engine, Field, CurveAffine, CurveProjective};
use bellman::SynthesisError;
use merlin::Transcript;
use crate::{traits, transcript::ProvingTranscript};
use crate::srs::SRS;
use crate::utils::*;
use crate::polynomials::operations::mul_polynomials;
use cr... |
pub mod algo_picker;
pub mod diagonal_picker;
pub mod executor;
pub mod heuristic_picker;
pub mod map_picker;
use crate::graphics::renderer::Renderer;
use ggez::{Context, GameResult};
use ggez::event::KeyCode;
use std::rc::Rc;
use std::cell::RefCell;
use crate::data::{maps::Map, diagonal::Diagonal, heuristic::Heuristi... |
use fox_k8s_crds::fox_service::*;
use k8s_openapi::api::apps::v1::{Deployment, DeploymentSpec};
use k8s_openapi::api::core::v1::EnvVar;
use k8s_openapi::api::core::v1::{Container, ContainerPort, PodSpec, PodTemplateSpec};
use kube::api::{DeleteParams, ObjectMeta, PostParams};
use kube::{Api, Client, Error};
fn build_d... |
mod counting { // MODULE CREATION
pub mod check { //SUB MODULE CREATION IN MAIN MODULE
pub fn digits() { //DEFINING A FUNCTION IN SUB MODULE
println!("We are in check function of counting module");
for counting in... |
/*
* Copyright Stalwart Labs Ltd. See the COPYING
* file at the top-level directory of this distribution.
*
* Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
* https://www.apache.org/licenses/LICENSE-2.0> or the MIT license
* <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your
* optio... |
use std::io;
// use std::ops::Div;
// use std::f64;
fn main() {
println!("I am a tip calculator");
println!("i will calculate your tip from your total");
println!("So lets get started");
println!("Your total is:$ ");
let mut total = String::new();
let mut percantage = String::new();
... |
use core::{convert::TryInto, ptr::NonNull};
use fermium::SDL_Palette;
use crate::{sdl_get_error, SdlError};
/// A palette of colors, for use with [`PixelFormat`] and [`Surface`].
///
/// You *basically never* need to allocate one of these yourself. They are
/// automatically created as necessary as part of allocatin... |
#![no_std]
use as_slice::{AsMutSlice, AsSlice};
use core::{
default::Default,
fmt,
mem::MaybeUninit,
ops::{Deref, DerefMut, Drop},
ptr, slice,
};
use generic_array::{typenum::marker_traits::Unsigned, ArrayLength, GenericArray};
pub mod typenum {
pub use generic_array::typenum::consts;
}
pub t... |
//! Control to activate/deactivate interface
use crate::Register;
pub struct Active {
address: u8,
}
impl Active {
pub fn new(address: u8) -> Self {
Active { address }
}
/// Activate interface
pub fn inactive(&self) -> Register {
Register {
address: self.address,
... |
#[macro_use] extern crate lazy_static;
#[macro_use] extern crate cached;
use std::collections::HashMap;
use std::sync::{Arc,Mutex};
use std::cell::Cell;
fn p0() {}
fn p1() -> u64 {
444
}
fn p2(x: u64) -> u64 {
x * 444
}
fn p3(x: u64, y: u64) -> u64 {
x * 444 + y
}
static mut blah: u64 = 3;
fn ip0() {
u... |
// ANCHOR: imports
use super::global::MyGC;
use crate::plan::CopyContext;
use crate::policy::space::Space;
use crate::scheduler::gc_work::*;
use crate::util::alloc::{Allocator, BumpAllocator};
use crate::util::forwarding_word;
use crate::util::{Address, ObjectReference, OpaquePointer};
use crate::vm::VMBinding;
use cra... |
use std::time::{Duration, Instant};
pub mod handshake;
pub mod receiver;
pub mod sender;
/// Timestamp in us
pub type TimeStamp = i32;
#[derive(Copy, Clone, Debug)]
pub struct TimeBase(Instant);
impl TimeBase {
pub fn new() -> Self {
Self(Instant::now())
}
pub fn from_raw(start_time: Instant) ->... |
#![feature(arbitrary_enum_discriminant)]
mod client;
mod definitions;
mod frame;
mod packet;
mod server;
pub mod topic;
extern crate strum;
extern crate strum_macros;
pub async fn start_broker() -> Result<(), Box<dyn std::error::Error>> {
server::MqttServer::start().await
}
#[cfg(test)]
mod tests {
use super:... |
use crate::bus::Bus;
use crate::devtree::DeviceIdent;
use crate::driver::Driver;
use twz::device::Device;
struct Ps2kbdDriver {}
impl Driver for Ps2kbdDriver {
fn supported() -> Vec<DeviceIdent> {
vec![]
}
fn start(bus: &Box<dyn Bus>, device: Device, ident: DeviceIdent) {}
}
pub fn register() -> Box<dyn Driver>... |
//! Support for loading `.tmPreferences` metadata files, with information related to indentation
//! rules, comment markers, and other syntax-specific things.
use std::collections::BTreeMap;
use std::path::PathBuf;
use std::fs::File;
use std::io::BufReader;
use std::str::FromStr;
use serde::{Deserialize, Deserializer... |
#[derive(Clone, Debug, PartialEq)]
pub struct ByteString {
value: Vec<u8>,
}
impl ByteString {
pub fn new(value: impl Into<Vec<u8>>) -> Self {
Self {
value: value.into(),
}
}
pub fn value(&self) -> &[u8] {
&self.value
}
}
|
/// write the buffer `pixels`,
/// whose dimensions are given by `bounds`,
/// to the file named `filename`.
pub
fn write_image(filename: &str,
pixels: &[u8],
bounds: (usize, usize))
-> Result <(), ::std::io::Error>
{ ... }
|
extern crate messenger;
#[cfg(whatsapp)]
extern crate whatsapp;
fn main() {
let messenger = messenger::Messenger::new("Hello, world!");
messenger.deliver();
#[cfg(whatsapp)]
{
let wa = whatsapp::Messenger::new("New thing");
wa.deliver();
}
}
|
use crate::server::ServerConnection;
use serenity::framework::standard::CommandError;
use crate::db::DbConnection;
use crate::model::enums::{Era, NationStatus, SubmissionStatus};
use crate::model::{
BotNationIdentifier, GameData, GameNationIdentifier, GameServerState, LobbyState, Nation,
Player, StartedState,... |
// XXX so weird that we have to remove trailing semicolon for line below
#[derive(Debug)]
struct Foo {
a: i32,
b: i32,
}
// XXX but not for line below.....?
struct Color(u8, u8, u8);
pub fn run() {
let x = Foo { a: 1, b: 2 };
let y = &x;
println!("{:?}", x);
println!("{:?}", y);
let color ... |
trait Display {
fn get_columns(&self) -> usize;
fn get_rows(&self) -> usize;
fn get_row_text(&self, row: usize) -> String;
fn show(&self) {
for i in 0..self.get_rows() {
println!("{}", self.get_row_text(i));
}
}
}
struct StringDisplay {
string: String,
}
impl String... |
use std::borrow::Borrow;
#[derive(Eq, PartialEq, Hash, Debug)]
pub struct Response(u16);
impl From<&str> for Response {
fn from(value: &str) -> Self {
let result = value.parse::<u16>();
return match result {
Ok(result) => Response(result),
Err(_) => Response(0)
}
... |
extern crate calamine;
use std::env;
use std::io::{self, Write};
use calamine::{Reader, open_workbook_auto, DataType};
fn main() {
let path = env::args().nth(1).expect("Missing path to Excel workbook.");
let mut book = open_workbook_auto(path).expect("Not an Excel workbook.");
let sheets = book.sheet_name... |
extern crate hyper;
extern crate futures;
extern crate redis;
use std::rc::Rc;
use futures::Future;
use futures::stream::Concat2;
use futures::Stream;
use futures::future::ok as FutureOk;
use hyper::{Client, Body, Uri, StatusCode};
use hyper::server::{Request, Response, Service};
use hyper::client::HttpConnector;
us... |
use thiserror::Error;
#[derive(Error, Debug)]
pub enum Error {
#[error("Failed to initialize format context")]
InitializeFormatContext,
#[error("Could not find stream in file")]
FindStreamInfo,
#[error("Could not find any audio stream")]
NoAudioStream,
#[error("Null codec pointer")]
Nul... |
use ansi_term::Colour;
use std::thread;
use std::time::{Duration, SystemTime};
pub fn find_max(arr: &[i32]) -> Option<i32> {
// 生成短期线程
const THRESHOLD: usize = 8;
if arr.len() <= THRESHOLD {
return arr.iter().cloned().max();
}
let mid = arr.len() / 2;
let (left, right) = arr.split_at... |
/*
* B-tree set (Rust)
*
* Copyright (c) 2022 Project Nayuki. (MIT License)
* https://www.nayuki.io/page/btree-set
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restric... |
pub mod client;
pub mod utils;
|
//! Responsável pela execução do programa
use parser;
use value;
/// Nome da JAULA padrão
pub const BIRL_MAIN: &'static str = "SHOW";
/// Variavel que tem um nome e um valor
#[derive(Clone)]
pub struct Variable {
/// Identificador da String
pub id: String,
/// Valor da variavel
pub value: value::Valu... |
//! The Salsa20 stream cipher.
//!
//! Cipher functionality is accessed using traits from re-exported
//! [`stream-cipher`](https://docs.rs/stream-cipher) crate.
//!
//! # Security Warning
//!
//! This crate does not ensure ciphertexts are authentic! Thus ciphertext integrity
//! is not verified, which can lead to seri... |
use std::path::Path;
use pahkat_client::{package_store::InstallTarget, PackageStore};
pub fn uninstall(
store: &dyn PackageStore,
packages: &Vec<String>,
target: InstallTarget,
) -> Result<(), anyhow::Error> {
for id in packages {
let pkg_key = store
.find_package_by_id(id)
... |
#![feature(plugin)]
#![feature(proc_macro)]
extern crate gtk;
extern crate vtree;
extern crate vtree_markup;
extern crate vtree_gtk;
use vtree_markup::markup;
use vtree_gtk::nodes as n;
use vtree_gtk::Context;
fn main() {
let a = markup!{
n::RootContext /
};
let mut ctx = Context::new(a);
le... |
use std::io;
use std::slice;
fn parse_garbage(input: &mut slice::Iter<'_, u8>) -> Option<u32> {
let mut count = 0;
loop {
let &c = input.next()?;
if c == b'!' {
input.next()?;
} else if c == b'>' {
return Some(count);
} else {
count += 1;
... |
mod board;
mod renderer;
mod robot;
mod human;
mod player;
use board::Board;
use renderer::Renderer;
use player::Player;
use human::Human;
use robot::Robot;
fn main() {
let r = Renderer::new();
r.cls();
println!("Starting Connect4");
let mut b = Board::new();
let human:&mut dyn Player = &mut Human::new('*');
l... |
#[doc = "Reader of register SPINLOCK0"]
pub type R = crate::R<u32, super::SPINLOCK0>;
impl R {}
|
// q0128_longest_consecutive_sequence
struct Solution;
use std::collections::HashSet;
impl Solution {
pub fn longest_consecutive(nums: Vec<i32>) -> i32 {
let set: HashSet<i32> = nums.iter().cloned().collect();
let mut max_len = 0;
for i in nums.iter() {
if set.contains(&(i - 1)... |
use crate::custom_types::join_values;
use crate::runtime::Runtime;
use crate::string_var::{MaybeString, StringVar};
use crate::variable::Variable;
use ascii::AsciiChar;
use std::borrow::Borrow;
use std::hash::Hash;
use std::ops::Index;
use std::rc::Rc;
use std::slice;
#[derive(Debug, Hash, PartialEq, Eq, Clone)]
pub s... |
use std::borrow::Cow;
use std::error::Error;
use bytemuck::Pod;
use heed_traits::{BytesDecode, BytesEncode};
use crate::CowSlice;
/// Describes a [`Vec`] of types that are totally owned (doesn't
/// hold any reference to the original slice).
///
/// If you need to store a type that doesn't depends on any
/// [memory... |
#![feature(rustc_private, link_args)]
extern crate env_logger;
extern crate getopts;
#[macro_use]
extern crate log;
extern crate mir2cretonne;
extern crate rustc;
extern crate rustc_driver;
use getopts::Options;
use mir2cretonne::trans::{self, Mir2CretonneTransOptions};
use rustc::session::{Session, CompileIncomplete... |
#[macro_use]
extern crate lazy_static;
extern crate reqwest;
use std::path::PathBuf;
use std::thread;
use std::time::{Duration, Instant};
mod utils;
use utils::*;
lazy_static! {
static ref CARGO_WEB: PathBuf = get_var( "CARGO_WEB" ).into();
static ref REPOSITORY_ROOT: PathBuf = get_var( "REPOSITORY_ROOT" ).... |
use std::fs;
fn main() {
let input: Vec<(usize, usize, char, String)> = fs::read_to_string("input")
.unwrap()
.lines()
.map(|l| {
let mut parts = l.split(' ');
let mut bounds = parts.next().unwrap().split('-')
.map(|n| n.parse().unwrap());
... |
#![no_main]
#![no_std]
extern crate cortex_m_rt;
extern crate panic_halt;
use cortex_m_rt::{entry, exception};
#[entry]
fn foo() -> ! {
loop {}
}
#[exception]
fn SysTick(undef: u32) {}
//~^ ERROR `#[exception]` handlers other than `DefaultHandler` and `HardFault` must have signature `[unsafe] fn() [-> !]`
|
// Copyright (c) The Starcoin Core Contributors
// SPDX-License-Identifier: Apache-2.0
use crate::{
get_available_port, get_available_port_multi, BaseConfig, ChainNetwork, ConfigModule,
StarcoinOpt,
};
use anyhow::Result;
use serde::{Deserialize, Serialize};
use starcoin_logger::prelude::*;
use std::net::Socke... |
use crate::config::Config;
#[cfg(not(feature = "gl"))]
use gfx_backend::winit;
#[cfg(feature = "gl")]
use gfx_backend::glutin;
/// Window abstraction.
pub struct Window {
#[cfg(not(feature = "gl"))]
pub events_loop: winit::EventsLoop,
#[cfg(feature = "gl")]
pub events_loop: glutin::EventsLoop,
#[cf... |
use cyclone::particle::Particle;
use cyclone::vec::Vec3;
use num::clamp;
use rand::prelude::*;
use rand_distr::StandardNormal;
use raylib::prelude::*;
const ZERO: Vec3<f32> = Vec3(0.0, 0.0, 0.0);
const UP: Vector3 = Vector3 {
x: 0.0,
y: 1.0,
z: 0.0,
};
fn c_to_r(v: Vec3<f32>) -> Vector3 {
Vector3 {
... |
// Resizable arrays
pub fn start () {
let mut numbers: Vec<i32> = vec![1, 2, 3, 4, 5];
println!("{:?}", numbers);
println!("{:?}", numbers.len());
// add value to vector
numbers.push(7);
numbers.pop();
println!("{:?}", numbers);
// loop
for x in numbers.iter(){
println!("{... |
pub fn build_proverb(list: Vec<&str>) -> String {
let mut result = String::new();
if list.len() != 0 {
let item_count = list.len();
let mut counter = 0;
while counter < item_count {
let first_item = list.get(counter).unwrap();
let second_item = list.get(counter + ... |
use std::error;
#[deriving(PartialEq,Show,Copy,Clone)]
pub enum IdentifierError {
ReservedIdentifierError(i64),
UnassignedIdentifierError(i64),
PrivateUseIdentifierError(i64),
UnknownIdentifierError(i64)
}
impl error::Error for IdentifierError {
fn description(&self) -> &str {
match *self {
... |
use core::{cmp, mem};
use super::Resource;
use system::error::Result;
use system::scheme::Packet;
use arch::context::{Context, context_switch};
/// A supervisor resource.
///
/// Reading from it will simply read the relevant registers to the buffer (see `Packet`).
///
/// Writing will simply left shift EAX by one byte... |
pub use crate::*;
pub fn simplify(implicants: &[(Implicant, Option<bool>)]) -> Vec<(Implicant, Option<bool>)> {
let mut simplified_functions: Vec<_> = implicants.iter().cloned().map(|(_, vec)| vec).collect();
let mut simplified: Vec<(Implicant, Option<bool>)> = vec![];
for i in 0..implicants.len() {
... |
//! Handle `cargo add` arguments
use cargo_edit::Dependency;
use cargo_edit::{get_latest_dependency, CrateName};
use semver;
use std::path::PathBuf;
use crate::errors::*;
#[derive(Debug, Deserialize)]
/// Docopts input args.
pub struct Args {
/// Crate name (usage 1)
pub arg_crate: String,
/// Crate name... |
use crate::models::Gutter;
use crate::models::Margins;
use serde::{Deserialize, Serialize};
use std::path::Path;
pub trait ThemeLoader {
fn load(&self, path: &Path) -> ThemeSetting;
fn default(&self) -> ThemeSetting;
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
pub struct ThemeSetting {
pu... |
mod configuration;
pub use configuration::Settings; |
impl Solution {
pub fn majority_element(nums: Vec<i32>) -> i32 {
use std::collections::HashMap;
let mut numMap = HashMap::new();
let maj = nums.len()/2;
for n in nums {
let count = numMap.entry(n).or_insert(0);
*count += 1;
if *count > maj... |
use super::prelude::*;
use super::schema::executor_processor;
#[derive(Queryable, Identifiable, AsChangeset, Debug, Clone, Serialize, Deserialize)]
#[table_name = "executor_processor"]
pub struct ExecutorProcessor {
pub(crate) id: i64,
pub(crate) name: String,
pub(crate) host: String,
pub(crate) machi... |
//! The DockerContainerLogger module is used as the mechanism for IO with
//! containers running in Docker. The module should not be called except by the
//! `docker` module in practice.
use crate::io::Logger;
use curl::easy::{Handler, WriteError};
#[derive(Clone)]
pub struct Application {
pub error_message: Opti... |
extern crate clock_ticks;
extern crate sdl2_mixer;
extern crate sdl2_ttf;
use pongo::ball::Ball;
use pongo::net::Net;
use pongo::paddle::Paddle;
use pongo::score_card::ScoreCard;
use pongo::ui::{Drawable,Ui};
use sdl2::event::Event;
use sdl2::keyboard::Keycode;
use sdl2::pixels::Color;
use sdl2::rect::Rect;
use sdl2... |
use crate::sign::VerificationAlgorithm;
pub trait KeyEvolvingSignatureAlgorithm: VerificationAlgorithm {
fn sign_update(key: &mut Self::Secret, msg: &[u8]) -> Self::Signature;
}
|
pub(crate) struct Decompressor<'a> {
data_sub_blocks: &'a [u8],
lzw_min_code_size: u8,
clear_code: usize,
raw_codes: Vec<usize>,
code_table: Vec<CodeType>,
code_size: u8,
}
// Refer to https://www.w3.org/Graphics/GIF/spec-gif89a.txt for details.
impl<'a> Decompressor<'a> {
pub(crate) fn new... |
use crate::ctx::ClientContext;
use anyhow::Result;
use rustimate_core::poll::PollStatus;
use rustimate_core::util::NotificationLevel;
use rustimate_core::RequestMessage;
use std::str::FromStr;
use uuid::Uuid;
pub(crate) struct EventHandler {}
impl EventHandler {
pub(crate) fn handle(ctx: &ClientContext, t: &str, k:... |
use super::*;
#[test]
fn CPX_test() {
let mut registers = Registers::new();
let mut bus = BusMock::new();
struct PatternArgs {
addr: u16,
opeland: u8,
x: u8,
negative: bool,
zero: bool,
carry: bool,
}
let patterns = vec![
PatternArgs { addr:... |
/*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
use std::iter::FromIterator;
use im::HashSet;
use super::abstract_domain::AbstractDomain;
use crate::datatype::PatriciaTreeSet;... |
#[doc = r"Register block"]
#[repr(C)]
pub struct RegisterBlock {
#[doc = "0x00 - Status register"]
pub sr: SR,
#[doc = "0x04 - Data register"]
pub dr: DR,
#[doc = "0x08 - Baud rate register"]
pub brr: BRR,
#[doc = "0x0c - Control register 1"]
pub cr1: CR1,
#[doc = "0x10 - Control reg... |
#[doc = "Reader of register INTR_SIE_SET"]
pub type R = crate::R<u32, super::INTR_SIE_SET>;
#[doc = "Writer for register INTR_SIE_SET"]
pub type W = crate::W<u32, super::INTR_SIE_SET>;
#[doc = "Register INTR_SIE_SET `reset()`'s with value 0"]
impl crate::ResetValue for super::INTR_SIE_SET {
type Type = u32;
#[i... |
#[derive(Debug, PartialEq)]
pub enum MemError
{
Ok,
BadAddress
}
pub enum MemTickResult
{
Ok,
IRQ(u8)
}
pub trait Memory
{
fn read_byte(&mut self, address: usize) -> Result<u8, MemError>;
fn write_byte(&mut self, address: usize, data: u8) -> MemError;
fn read_u16(&mut self, address: usize... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.