text stringlengths 8 4.13M |
|---|
use caches;
use gfx;
use io::timer::{Timer, Prescaler};
fn bench_busyloop(timer: &Timer) {
extern {
fn cbench_busywait(start: u32, end: u32);
}
let num = 0x100000-1;
let now = timer.us_val();
unsafe { cbench_busywait(0, num); }
let end = timer.us_val();
log!("{:#X} instructions to... |
use super::mmap::ProtFlags;
pub fn mprotect(addr: u64, len: u64, prot: u64) -> u64 {
let prot = ProtFlags::from_bits(prot as i32).expect("unknown prot flags");
println!("Syscall: mprotect addr={:x} len={:x} prot={:?}", addr, len, prot);
0
}
|
use std::i16;
use std::i32;
use lazy_static::lazy_static;
use sdl2::pixels::Color;
use sdl2::rect::Point;
use sdl2::rect::Rect;
use sdl2::render::Canvas;
use sdl2::render::TextureQuery;
use sdl2::ttf::Font;
use sdl2::video::Window;
use tetris::Board;
use tetris::Game;
use tetris::GameOver;
use tetris::HighScores;
use... |
use std::mem;
use winapi::um::winbase::{
ABOVE_NORMAL_PRIORITY_CLASS, BELOW_NORMAL_PRIORITY_CLASS, HIGH_PRIORITY_CLASS,
IDLE_PRIORITY_CLASS, NORMAL_PRIORITY_CLASS, REALTIME_PRIORITY_CLASS,
};
use winapi::um::winnt::*;
pub struct ExtendedLimitInfo(pub JOBOBJECT_EXTENDED_LIMIT_INFORMATION);
#[repr(u32)]
pub enu... |
/*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under both the MIT license found in the
* LICENSE-MIT file in the root directory of this source tree and the Apache
* License, Version 2.0 found in the LICENSE-APACHE file in the root directory
* of this source tree.
*/
use c... |
use bytes::Bytes;
use uuid::Uuid;
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Image {
pub name: String,
pub data: Bytes,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Format {
Png,
Jpeg,
}
#[derive(Error, Debug)]
pub enum Error {
#[error("format {0:?} is not supported")]
Unsup... |
use api_client::ApiClient;
use utils::decode_list;
use errors::*;
// Client Structure
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct Client {
#[serde(default)]
pub name: String,
#[serde(default)] clientname: String,
#[serde(default)] validator: bool,
#[serde(default)] orgname: ... |
use ocaml::{FromValue, ToValue};
#[derive(ToValue, FromValue)]
enum Enum1 {
Empty,
First(ocaml::Int),
Second(ocaml::Array<&'static str>),
}
#[ocaml::func]
pub fn enum1_empty() -> Enum1 {
Enum1::Empty
}
#[ocaml::func]
pub fn enum1_first(i: ocaml::Int) -> Enum1 {
Enum1::First(i)
}
#[ocaml::func]
p... |
use std::cmp::Ordering;
use std::hash::{Hash, Hasher};
use std::collections::HashMap;
#[derive(Debug)]
pub struct NameLen {
pub name: String,
pub len: u64,
}
impl PartialEq for NameLen {
fn eq(&self, other: &NameLen) -> bool {
self.name == other.name
}
}
impl Eq for NameLen {}
impl Hash for... |
use core::mem;
use typenum::consts;
use typenum::uint::Unsigned;
use port::Port;
struct Pic<DataId: Unsigned, ControlId: Unsigned> {
data: Port<DataId>,
control: Port<ControlId>
}
pub struct ChainedPics {
master: Pic<consts::U32, consts::U33>, // 0x20 and 0x21
slave: Pic<consts::U160, consts::U161> /... |
// For test decorators
#![feature(plugin, custom_attribute)]
#![plugin(adorn)]
#![plugin(docopt_macros)]
// Literal maps for test purposes
#[cfg(test)]
#[macro_use] extern crate maplit;
#[cfg(test)]
#[macro_use] extern crate lazy_static;
extern crate docopt;
extern crate env_logger;
extern crate mime;
extern crate re... |
#[derive(Copy, Clone, Eq, PartialEq, Debug)]
pub enum ConditionCode {
Equal,
NotEqual,
CarrySet,
CarryClear,
Minus,
Plus,
OverflowSet,
OverflowClear,
UnsignedHigher,
UnsignedLowerOrSame,
SignedGreaterThanOrEqual,
SignedLessThan,
SignedGreaterThan,
SignedLessThanOr... |
#[doc = "Reader of register CH0_DBG_CTDREQ"]
pub type R = crate::R<u32, super::CH0_DBG_CTDREQ>;
#[doc = "Reader of field `CH0_DBG_CTDREQ`"]
pub type CH0_DBG_CTDREQ_R = crate::R<u8, u8>;
impl R {
#[doc = "Bits 0:5"]
#[inline(always)]
pub fn ch0_dbg_ctdreq(&self) -> CH0_DBG_CTDREQ_R {
CH0_DBG_CTDREQ_R... |
use crate::{
error::TapeLoadError,
host::{LoadableAsset, SeekFrom, SeekableAsset},
zx::tape::TapeImpl,
Result,
};
const PILOT_LENGTH: usize = 2168;
const PILOT_PULSES_HEADER: usize = 8063;
const PILOT_PULSES_DATA: usize = 3223;
const SYNC1_LENGTH: usize = 667;
const SYNC2_LENGTH: usize = 735;
const BIT... |
extern crate serde_json;
use std::collections::HashMap;
use exonum::api::Api;
use exonum::blockchain::Blockchain;
use exonum::crypto::PublicKey;
use exonum::encoding::serialize::FromHex;
use hyper::header::ContentType;
use iron::headers::AccessControlAllowOrigin;
use iron::prelude::*;
use iron::status;
use prometheus... |
use super::common::input;
#[derive(Debug)]
pub struct Person {
first_name: String,
last_name: String,
age: u8
}
impl Person {
pub fn create() -> Person {
Person {
first_name: input("Please enter first name"),
last_name: input("Please enter last name"),
age: ... |
use std::fmt;
use crate::cpu::registers::Register;
use crate::cpu::registers::RegisterPair;
use crate::memory::Memory;
use crate::timer;
#[derive(Debug, PartialEq)]
pub enum Instruction {
Nop,
Stop,
Halt,
Load16(Load16Target, Load16Source),
Load8(Load8Operand, Load8Operand),
Add(ArithmeticOper... |
// Our use case
use super::stream;
pub type OpenProc = fn(file_path: &path::Path, open_mode: i32) -> stream::FileReader;
pub type ReadProc = fn(file_reader: stream::FileReader, read_buffer: i32, count: i32) -> i32;
pub type FileLengthProc = fn(file_reader: stream::FileReader) -> i32;
pub fn open() {
let compresse... |
#[path = "support/macros.rs"]
#[macro_use]
mod macros;
mod support;
use criterion::{criterion_group, criterion_main, Criterion};
use glam::Mat4;
use std::ops::Mul;
use support::*;
bench_unop!(
mat4_transpose,
"mat4 transpose",
op => transpose,
from => random_srt_mat4
);
bench_unop!(
mat4_determin... |
use std::collections::HashMap;
fn compress(data: &[u8]) -> Vec<u32> {
// Build initial dictionary.
let mut dictionary: HashMap<Vec<u8>, u32> = (0u32..=255)
.map(|i| (vec![i as u8], i))
.collect();
let mut w = Vec::new();
let mut compressed = Vec::new();
for &b in data {
... |
extern crate paper;
use paper::configuration::Configuration;
#[macro_use]
extern crate clap;
use clap::{App, Arg, ArgMatches};
#[tokio::main]
async fn main() {
let app = app();
let matches = matches_for_app(app);
let mut configuration = Configuration {
username: None,
password: None,
... |
pub fn add_three_times_four(x : int) -> int {
(x+3)*4
}
|
// Copyright (c) 2019 - 2020 ESRLabs
//
// 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 ... |
use std::sync::Arc;
use base64;
use ring::constant_time::verify_slices_are_equal;
use ring::{digest, hmac, rand, signature};
use untrusted;
use algorithms::Algorithm;
use errors::{new_error, ErrorKind, Result};
use keys::Key;
/// The actual HS signing + encoding
fn sign_hmac(alg: &'static digest::Algorithm, key: Key... |
extern crate clap;
use clap::{crate_version, App, Arg};
use std::io::{self, BufRead};
mod math;
type MathFunction = for<'r> fn(&'r Vec<f64>) -> f64;
enum MathFunctionLabel {
Sum,
Mean,
}
fn parse_args() -> MathFunctionLabel {
let matches = App::new("pipemath")
.about(
"Run math funct... |
// Copyright 2021 The Matrix.org Foundation C.I.C.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable... |
extern crate rand;
use rand::{thread_rng, Rng};
use std::cell::RefCell;
use std::fmt;
#[derive(PartialEq, Clone, Copy)]
enum HandValue {
Guu,
Cho,
Paa,
}
#[derive(PartialEq, Clone)]
struct Hand {
hand_value: HandValue,
name: String,
}
impl Hand {
fn new(hv: HandValue) -> Hand {
match... |
use crate::{Context, Middleware, Response};
use futures::future::BoxFuture;
use std::time::Instant;
#[derive(Debug, Clone, Default)]
pub struct Logger;
impl Logger {
pub fn new() -> Self {
Self::default()
}
}
impl<State: Send + Sync + 'static> Middleware<Context<State>> for Logger {
fn call<'a>(&... |
// blocks are expressions
fn main() {
let pi = std::f64::consts::PI;
let r = 5.3;
let area = {
pi * r * r
};
println!("area: {:?}", area);
} |
//! NOTE: this crate is really just a shim for testing
//! the other no-std crate.
mod multi_thread;
mod single_thread;
#[cfg(test)]
mod tests {
use bbqueue::{consts::*, BBBuffer, ConstBBBuffer, Error as BBQError};
#[test]
fn deref_deref_mut() {
let bb: BBBuffer<U6> = BBBuffer::new();
let... |
// Copyright (c) 2019 Chaintope Inc.
use crate::errors::Error;
use log::warn;
use std::sync::mpsc::{channel, sync_channel, Receiver, Sender, SyncSender};
use std::sync::{Arc, Mutex, RwLock};
use std::thread::JoinHandle;
use std::time::Duration;
type ThreadSafeReceiver<T> = Arc<Mutex<Receiver<T>>>;
fn to_thread_safe<... |
/*
* Sliding window min/max test (Rust)
*
* Copyright (c) 2022 Project Nayuki. (MIT License)
* https://www.nayuki.io/page/sliding-window-minimum-maximum-algorithm
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Softwa... |
use bytes::{BufMut, BytesMut};
use rsocket_rust::extension::{self, CompositeMetadata, CompositeMetadataEntry, MimeType};
use rsocket_rust::utils::Writeable;
#[test]
fn test_encode_and_decode() {
let bingo = |metadatas: Vec<&CompositeMetadataEntry>| {
assert_eq!(2, metadatas.len());
assert_eq!(
... |
use std;
fn ack(m: int, n: int) -> int {
if m == 0 {
ret n + 1
} else {
if n == 0 {
ret ack(m - 1, 1);
} else {
ret ack(m - 1, ack(m, n - 1));
}
}
}
fn main(args: [str]) {
// FIXME: #1527
sys::set_min_stack(1000000u);
let n = if vec::len(... |
//! the example for how to decode hex string to message struct
//!
//! 转化过程 一个string 利用hex转换成 Vec<u8>
//! u8数组再利用 bitcoin::deserialize 转换成相应的Address类型
//! 要求 Address 实现 Decode和Encode方法 不然无法实现serialize 和 deserialize
//!
//!
fn decode_address() {
use hex::decode as hex_decode;
use bitcoin::consensus::{deserializ... |
use std::collections::HashMap;
use log::{error, debug};
use std::time::{UNIX_EPOCH};
use crate::zone::Zone;
use std::fs::{metadata, File};
use std::io::{Error, ErrorKind, BufReader};
use std::cell::{RefCell};
use serde::{Serialize, Deserialize};
use derive_new::{new};
pub type ControlNodes = HashMap<String, ControlNo... |
use anyhow::*;
use derive_more::*;
use serde::{Deserialize, Serialize};
use smart_default::SmartDefault;
use std::{fmt, str::FromStr};
#[derive(Clone, Copy, PartialEq, Eq, Deserialize, Serialize, Display, DebugCustom, SmartDefault)]
pub enum NumWithUnit {
#[display(fmt = "{}%", .0)]
#[debug(fmt = "{}%", .0)]
... |
#[derive(Copy, Clone)]
pub enum Distance {
Manhattan,
Diagonal,
Circle
}
pub fn draw_line<F>(x1: i32, y1:i32, x2: i32, y2: i32, mut f:F)
where F: FnMut(i32, i32) -> bool {
let dx = (x2 - x1).abs();
let dy = (y2 - y1).abs();
let sx = if x1 < x2 {1} else {-1};
let sy = if ... |
extern crate csv;
extern crate rustc_serialize;
#[macro_use]
extern crate hyper;
extern crate rayon;
use std::io;
use std::io::Write;
use std::fs::OpenOptions;
use std::thread;
use std::sync::Arc;
use csv::Reader;
use hyper::{Url, Client};
use hyper::client::response::Response;
use hyper::header::{Headers, UserAgent};... |
mod controller;
use crate::controller::{
app::{ApplicationController, ANNOTATION_APP_NAME},
ControllerConfig,
};
use anyhow::{anyhow, Context};
use async_std::sync::{Arc, Mutex};
use dotenv::dotenv;
use drogue_client::registry;
use drogue_cloud_operator_common::{
controller::base::{
queue::WorkQueu... |
use crate::tokens::Expr;
#[derive(Debug, PartialEq)]
pub(crate) enum Type {
Number,
Bool,
Str,
Expression,
Var,
}
|
// use crate::components::comparisons::{get_comparisons, Comparison, FeatureSupport};
use crate::components::container::{Container, ContainerProps};
use perseus::{t, GenericNode, Template};
use std::rc::Rc;
use sycamore::prelude::Template as SycamoreTemplate;
use sycamore::prelude::*;
#[component(ComparisonsPage<G>)]
... |
#[macro_use]
extern crate serde_derive;
extern crate clap;
use std::fs::File;
use std::io::Error as IoError;
use std::io::Read;
use clap::{App, Arg};
mod execute;
mod parse_config;
mod task_output;
fn parentpath(path: String) -> String {
let mut v: Vec<&str> = path.split("/").collect();
let len = v.len();
... |
mod world;
/// Use the 'cover' sizing strategy that ensure the rendered area covers the
/// entire viewport.
struct PerspectiveCamera {
/// Aspect-ratio from width by height.
screen: (u32, u32),
/// Field of view in angle. Normal human vision is limited to `pi / 6`
/// radians vertically.
///
/... |
use lazy_static::lazy_static;
use std::collections::HashSet;
lazy_static! {
static ref FREQUENCY_CHANGES: Vec<i32> = include_str!("input.txt")
.lines()
.map(|line| line.parse().unwrap())
.collect();
}
fn part1() {
println!("{}", FREQUENCY_CHANGES.iter().sum::<i32>());
}
fn part2() {
... |
use std::collections::HashMap;
use super::super::utils::http_get;
use crate::error::Result;
use serde::{Deserialize, Serialize};
use serde_json::Value;
#[derive(Clone, Serialize, Deserialize)]
#[allow(non_snake_case)]
struct FutureMarket {
name: String,
underlying: String,
cycle: String,
#[serde(rena... |
pub fn remove_duplicate_letters(s: String) -> String {
let mut remaining = vec![0; 26];
let mut visited = vec![false; 26];
let mut st = vec![];
let ind = |c| (c as u8 - 'a' as u8) as usize;
for c in s.chars() {
remaining[ind(c)] += 1;
}
for c in s.chars() {
remaining[ind(c)... |
use amethyst::{
core::{
nalgebra::{base::Matrix, Vector2},
timing::Time,
transform::components::Transform,
},
ecs::{Join, Read, ReadStorage, System, WriteStorage},
input::InputHandler,
};
use crate::components::{
for_characters::{Engine, FuelTank},
physics::Dynamics,
};
... |
use pipers::Pipe;
use regex::Regex;
use std::str::FromStr;
use std::process::Command;
fn main() {
// let bla = "pacmd set-card-profile $index off";
// let bla2 = "pacmd set-card-profile $index a2dp_sink_ldac";
// pacmd list-cards | grep -e 'index:' -e 'active profile'
let out = Pipe::new("pacmd list-cards... |
/*
* Copyright (c) Meta Platforms, Inc. and affiliates.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree.
*/
//! A drop-in replacement for `std::process::Command` that provides the ability
//! to set up names... |
#![allow(dead_code)]
extern crate env_logger;
extern crate freetype;
#[macro_use] extern crate log;
#[macro_use] extern crate objc;
pub mod buffer;
pub mod pane;
pub mod platform;
pub mod project;
pub mod workspace;
use std::env;
use std::path::Path;
use std::sync::Arc;
fn main() {
env_logger::init().unwrap();
... |
mod function;
mod primitive;
mod record;
mod record_body;
mod type_;
pub use function::*;
pub use primitive::*;
pub use record::*;
pub use record_body::*;
pub use type_::*;
|
// Copyright (c) The Starcoin Core Contributors
// SPDX-License-Identifier: Apache-2.0
use actix::clock::Duration;
use actix::Message;
use starcoin_types::account_address::AccountAddress;
use starcoin_types::transaction::{RawUserTransaction, SignedUserTransaction};
use starcoin_wallet_api::{WalletAccount, WalletResult... |
use core::sync::atomic::{AtomicPtr, Ordering};
use core::fmt::{self, Debug, Formatter};
use crate::uses::*;
// a non locking, synchronous vec
pub struct NLVec<T>(AtomicPtr<Vec<*const T>>);
impl<T> NLVec<T>
{
pub fn new() -> Self
{
let vec: Vec<*const T> = Vec::new();
let ptr = to_heap(vec);
NLVec(AtomicPtr::... |
use std::rc::Rc;
use hyper;
use super::configuration::Configuration;
pub struct APIClient<C: hyper::client::Connect> {
configuration: Rc<Configuration<C>>,
ingredients_api: Box<::apis::IngredientsApi>,
meal_planning_api: Box<::apis::MealPlanningApi>,
menu_items_api: Box<::apis::MenuItemsApi>,
misc... |
/*
Primitive Types
Integers: u8, i8, u16, i16, u32, i32, u64, i64, u128, i128, u256, i256
Floats: f32, f64
Boolean: bool
Characters: char
Tuples
Arrays
*/
// Rust is a statically typed language, but the compiler can usually infer what type we want to use based on the value and how we use it
use std;
pub fn run() {
... |
mod integration_tests;
mod tests;
extern crate brotli;
extern crate core;
#[macro_use]
extern crate alloc_no_stdlib;
use core::ops;
use brotli::CustomRead;
pub struct Rebox<T> {
b : Box<[T]>,
}
impl<T> core::default::Default for Rebox<T> {
fn default() -> Self {
let v : Vec<T> = Vec::new();
let b ... |
#![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 ErrorResponse {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub code: Option<String>,
#[... |
use crate::{
bitcoin::{
hashes::{sha512, Hash, HashEngine, Hmac, HmacEngine},
util::bip32::ExtendedPrivKey,
Network,
},
party::Proposal,
};
use olivia_secp256k1::schnorr_fun::fun::{marker::*, Point, Scalar, G};
pub struct Keychain {
seed: [u8; 64],
proposal_hmac: HmacEngine<... |
use std::future::Future;
use std::time::{Duration, SystemTime};
// use crate::application::APPLICATION;
use crate::prelude::*;
use abscissa_core::tracing::{debug, error, info, warn};
use abscissa_core::{Command, Options, Runnable};
use tendermint::lite::types::Header;
use relayer::chain::tendermint::TendermintChain... |
//! Simulation parameters.
use random::Seed;
#[derive(Clone, Debug)]
pub struct Params {
/// Seed for the random number generator.
pub seed: Seed,
/// Number of simulation iterations.
pub num_iterations: u64,
/// Number of nodes to form a complete group.
pub group_size: usize,
/// Age of n... |
use crate::{common::Solution, reparse};
use itertools::Itertools;
use lazy_static::lazy_static;
use regex::Regex;
lazy_static! {
static ref SEAT_PATTERN: Regex = Regex::new(r"(.{7})(.{3})").unwrap();
}
struct Ticket {
code: String,
_row: String,
_column: String,
}
fn _bst_code(code: &String, limits: ... |
use crate::convertor::img_to_txt;
use crate::convertor::txt_to_img;
use crate::opts::Opts;
use image::io::Reader as ImageReader;
use structopt::StructOpt;
pub fn run() {
let opts: Opts = Opts::from_args();
match ImageReader::open(opts.input.clone())
.expect(&format!(
"Can't open input fil... |
extern crate web3;
use web3::futures::Future;
use web3::types::BlockId;
use web3::types::BlockNumber;
use web3::types::U64;
use structopt::StructOpt;
use std::thread;
use std::time::Duration;
#[derive(StructOpt)]
struct Arguments {
start: u32,
end: u32,
node: String,
}
fn main() {
let _args = Argument... |
use crate::hal::{
clocks::LFCLK_FREQ,
pac::WDT,
wdt::{self, Parts, Watchdog as HalWatchdog, WatchdogHandle},
};
use rtic::time::duration::Milliseconds;
use rtt_target::rprintln;
pub struct Watchdog {
handle: WatchdogHandle<wdt::handles::Hdl0>,
}
impl Watchdog {
pub const PERIOD: u32 = 3 * LFCLK_FR... |
extern crate subprocess;
extern crate log;
use log::info;
use std::io::Read;
use subprocess::{Exec, Redirection};
/// Wrapper function for using ropebwt2 with collection of strings.
/// This is primarily for performing easy tests within the Rust environment.
/// For production, we recommend running the `ropebwt2` co... |
use std::{
cmp::Ordering,
collections::{BinaryHeap, HashMap},
fmt, usize,
};
#[derive(Eq, PartialEq)]
enum Tile {
Wall,
Floor,
}
#[derive(Eq, PartialEq, Clone, Copy)]
enum Allegiance {
Elf,
Goblin,
}
#[derive(Eq, PartialEq, Clone, Copy)]
struct Unit {
allegiance: Allegiance,
pos: ... |
use crate::core::Client;
use crate::ContinuationToken;
use crate::{
entity_path, get_batch_mime, Batch, MetadataDetail, PaginatedResponse, TableClient, TableEntity,
};
use azure_core::errors::{check_status_extract_body, AzureError};
use futures::stream::Stream;
use hyper::{header, Method, StatusCode};
use serde::{d... |
use crate::SerdeColor;
#[derive(Serialize, Deserialize, Clone, PartialEq, Debug)]
pub struct ThemeConfig {
color: SerdeColor,
italic: bool,
bold: bool,
}
impl ThemeConfig {
pub fn new(color: SerdeColor, italic: bool, bold: bool) -> Self {
Self {
color,
italic,
... |
use std::str::FromStr;
use clap::{ App, SubCommand, Arg, ArgMatches };
use futures::Future;
use maddr::MultiAddr;
use util;
use context::Context;
pub fn subcommand() -> App<'static, 'static> {
SubCommand::with_name("disconnect")
.about("\
Close connection(s) to the given address(es)\
... |
pub(crate) mod command;
mod constants;
use std::path::{Path, PathBuf};
use structopt::clap::AppSettings::*;
use structopt::StructOpt;
pub(crate) trait ConfigPath {
fn config_path(&self) -> Option<&Path>;
}
pub(crate) trait Platform {
fn platform(&self) -> Option<&str>;
}
use constants::*;
#[derive(Debug, St... |
#[macro_export]
macro_rules! nv {
( $( $x:expr ),* ) => {
{
let mut temp_string = String::new();
$(
temp_string.push_str(&format!("|{}|: |{:?}| ", stringify!($x), $x));
)*
temp_string
}
};
}
#[macro_export]
macro_rules! pnv {
(... |
pub mod begin;
pub mod manager;
use crate::parser::ast::ExprKind;
use crate::parser::ast::*;
pub trait Folder {
fn fold(&mut self, ast: Vec<ExprKind>) -> Vec<ExprKind> {
ast.into_iter().map(|x| self.visit(x)).collect()
}
// Whether or not the pass modified the input AST
fn modified(&self) -> b... |
fn main() {
one_param(5);
two_params(-9, 2);
let mut x = return_five();
println!("return_five evaluates to {}", x);
x = increment(x);
println!("now x is {}", x);
x = increment(x);
println!("now x is {}", x);
x = increment(x);
println!("now x is {}", x);
x = increment(x)... |
//! Internal types for passing data around. Overly verbose
//! and not useful to the user, thus not publicly visible.
use crate::time::Timestamp;
use crate::transfer::TransferKind;
use crate::types::*;
use crate::Priority;
/// Internal representation of a received frame.
///
/// This is public so externally-defined S... |
use hilbert_qexp::elements::{div_mut, HmfGen};
use hilbert_qexp::bignum::BigNumber;
use parallel_wt::*;
use flint::fmpq::Fmpq;
use std::cmp::max;
use std::ops::*;
pub fn star_op<T>(res: &mut HmfGen<T>, f: &HmfGen<T>)
where
T: BigNumber,
{
let (k1, k2) = f.weight.unwrap();
v_u_bd_iter!((f.m, f.u_bds, v, u,... |
mod server;
use server::{start_server, GenericServerError};
const DEFAULT_PORT: u16 = 3001;
#[tokio::main]
async fn main() -> Result<(), GenericServerError> {
let port =
std::env::var("PORT").map_or(DEFAULT_PORT, |p| p.parse::<u16>().unwrap_or(DEFAULT_PORT));
let socket_address: std::net::SocketAddr =... |
use std::any::Any;
use super::Provider;
pub(super) struct CastProvider {
downcast: *const (dyn Any + Send + Sync),
provider: Box<dyn Provider>,
}
impl CastProvider {
pub fn new(p: impl Provider) -> Self {
let provider = Box::new(p);
Self {
downcast: &*provider,
pr... |
extern crate rustypy;
use rustypy::*;
#[test]
fn unpack_pylist_macro() {
use std::iter::FromIterator;
let nested = PyList::from_iter(vec![
pytuple!(
PyArg::PyList(PyList::from_iter(vec![1i32, 2, 3]).into_raw()),
PyArg::F32(0.1)
),
pytuple!(
PyArg::PyL... |
fn main() {
call_me();
}
fn call_me() {
let num = 3;
for i in 0..num {
println!("Ring! Call number {}", i + 1);
}
}
|
use chrono::{DateTime, Utc, Duration};
pub fn after(start: DateTime<Utc>) -> DateTime<Utc> {
start + Duration::seconds(i64::from(1_000_000_000))
}
|
use crate::*;
use serde::{Deserialize, Serialize};
use std::collections::BTreeMap;
/// Holds a set of reusable objects for different aspects of the OAS.
/// All objects defined within the components object will have no effect
/// on the API unless they are explicitly referenced from properties
/// outside the componen... |
use std::ops::Deref;
use thiserror::Error;
#[cfg(feature = "passthrough-decoder")]
mod passthrough_decoder;
#[cfg(feature = "passthrough-decoder")]
pub use passthrough_decoder::PassthroughDecoder;
mod symphonia_decoder;
pub use symphonia_decoder::SymphoniaDecoder;
#[derive(Error, Debug)]
pub enum DecoderError {
... |
use std::io::prelude::*;
use std::fs::File;
use std::path;
use chrono::{DateTime, Utc};
use clap::App;
use ureq;
const DEFAULT_DIR: &str = "/mnt/data";
const BASE_URL: &str = "https://dataplane.org";
const ENDPOINTS: (&str, &str, &str) = (
"/sshpwauth.txt",
"/telnetlogin.txt",
"/vncrfb.txt",
);
#[derive(... |
use super::{Server, ServerResult};
use actix_web::{
http::header,
middleware::cors::Cors,
pred,
server::{HttpHandler, HttpHandlerTask},
App,
};
use std::{net::SocketAddr, path::PathBuf, sync::Arc};
pub struct ServerBuilder {
pkcs12: Option<PathBuf>,
address: SocketAddr,
prefix: Arc<St... |
use std::collections::HashMap;
use std::env;
use std::error::Error;
use std::fmt;
use chrono::{DateTime, Utc};
use dynomite::{
attr_map,
dynamodb::{DynamoDb, DynamoDbClient, GetItemInput, PutItemInput},
AttributeValue, Attributes, FromAttributes, Item,
};
use nanoid::nanoid;
use serde::{Deserialize, Serial... |
use super::data::{ServerData};
use std::sync::{Arc, Mutex};
use super::network::{
Stream,
encode::stream_to_raw,
packet::Packet
};
// Starts ping thread A in a new thread and consumes active thread for ping thread B. These threads
// are used to maintain connections to clients and check in on them.
pub fn... |
/*!
Implementation of [the WTF-8 encoding](https://simonsapin.github.io/wtf-8/).
This library uses Rust’s type system to maintain
[well-formedness](https://simonsapin.github.io/wtf-8/#well-formed),
like the `String` and `&str` types do for UTF-8.
Since [WTF-8 must not be used
for interchange](https://simonsapin.gith... |
const DEFAULT_PER_PAGE: i64 = 10;
const DEFAULT_PAGE: i64 = 1;
use actix_web::{error::ResponseError, HttpResponse};
use failure::Fail;
use serde::{Deserialize, Serialize};
#[derive(Deserialize, Debug, Clone, Default)]
pub struct Params {
#[serde(default = "default_page")]
pub page: i64,
#[serde(default = ... |
use std::cmp;
use std::ops::{AddAssign, Neg};
use ieee754::Ieee754;
use num::{One, Zero};
use openssl::rand::rand_bytes;
#[cfg(feature="use-mpfr")]
use rug::{Float, rand::{ThreadRandGen, ThreadRandState}};
pub fn fill_bytes(mut buffer: &mut [u8]) -> Fallible<()> {
if let Err(e) = rand_bytes(&mut buffer) {
... |
use criterion::{criterion_group, criterion_main, Criterion};
const UPDATE_RATE: f32 = 1.0 / 60.0;
const NUM_OBJECTS: usize = 1 << 13;
#[macro_export]
macro_rules! bench_euler {
($b: ident, ty => $t: ty, zero => $zero: expr) => {{
let accel_data = <$t as mathbench::RandomVec>::random_vec(0, NUM_OBJECTS);
... |
use crate::{
error::{MqttResponse, ServerError},
service::{App, Session},
};
use drogue_cloud_endpoint_common::sink::Sink as DownstreamSink;
use ntex::router::Path;
use ntex::util::{ByteString, Bytes};
use ntex_mqtt::{
types::QoS,
v3,
v5::{
self,
codec::{Auth, ConnectAckReason, Disco... |
// q0113_path_sum_ii
struct Solution;
use crate::util::TreeNode;
use std::cell::RefCell;
use std::rc::Rc;
impl Solution {
pub fn path_sum(root: Option<Rc<RefCell<TreeNode>>>, sum: i32) -> Vec<Vec<i32>> {
let mut tvd = vec![];
let mut ret = vec![];
Solution::path_traveral(&mut tvd, sum, &m... |
extern crate proc_macro;
use proc_macro::TokenStream;
use syn::{parse_macro_input, AttributeArgs, DeriveInput, Item};
mod from_args;
mod pyclass;
#[proc_macro_derive(FromArgs, attributes(pyarg))]
pub fn derive_from_args(input: TokenStream) -> TokenStream {
let ast: DeriveInput = syn::parse(input).unwrap();
... |
use crate::{
bit_set,
bit_set::ops::{Access, Capacity, Count},
bit_set::{word, Word},
};
/// `Rank` is a generization of `Count`.
///
/// `rank1` and `rank0` have default implementation, but these are cycled.
/// So either `rank1` or `rank0` need to be redefined.
pub trait Rank: Count {
/// Returns the... |
use crate::{domain, value};
use std::fmt::{Display, Formatter, Result as FmtResult};
use strum_macros::{EnumIter, EnumString};
#[derive(PartialEq, Clone, Copy, Hash, Eq, Debug, EnumIter, EnumString)]
pub enum Property {
Bool,
Int,
Str,
}
impl Display for Property {
fn fmt(&self, f: &mut Formatter) -> ... |
use sqlx::decode::Decode;
use sqlx::encode::Encode;
use sqlx::sqlite::SqliteTypeInfo;
use sqlx::SqlitePool;
use sqlx::{FromRow, Sqlite, Type};
use std::string::ToString;
#[derive(FromRow, Debug)]
pub struct Role {
pub id: i64,
pub role_name: RoleName,
}
#[derive(Decode, Encode, Debug, Copy, Clone, Display)]
p... |
/*
Copyright (c) 2023 Uber Technologies, Inc.
<p>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
<p>http://www.apache.org/licenses/LICENSE-2.0
<p>Unless required by applicable law or agreed to ... |
use crate::custom_var::CustomVar;
use crate::looping::{IterResult, NativeIterator};
use crate::method::StdMethod;
use crate::name::Name;
use crate::operator::Operator;
use crate::runtime::Runtime;
use crate::stack_frame::StackFrame;
use crate::std_type::Type;
use crate::variable::{FnResult, Variable};
use crate::{execu... |
use num_traits::{FromPrimitive, ToPrimitive};
use crate::lexer::SyntaxKind;
/// Second, implementing the `Language` trait teaches rowan to convert between
/// these two SyntaxKind types, allowing for a nicer SyntaxNode API where
/// "kinds" are values from our `enum SyntaxKind`, instead of plain u16 values.
#[derive(... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.