text stringlengths 8 4.13M |
|---|
use rustler::schedule::SchedulerFlags::*;
mod atoms;
mod backend;
rustler::rustler_exports_nifs!(
"Elixir.Backend",
{
{"from_bytes", 1, backend::from_bytes, DirtyIo},
{"resize", 3, mirage::resizem DirtyCpu},
},
Some(load)
);
fn load(env: rustler::Env, _info: rustler::Term) -> bool {
backend::... |
use argh::FromArgs;
use env_logger::{Builder, Target};
use serde::{Deserialize, Serialize};
/// Server options
#[derive(Clone, Debug, Serialize, Deserialize, FromArgs)]
pub struct RemitsConfig {
#[argh(option, short = 'p')]
/// what port to start remits on
pub port: Option<String>,
// v can change dont... |
use failure::Error;
use std::io::{self, BufRead};
pub fn get_text() -> Result<String, Error> {
println!("Text to encrypt ?");
let mut buffer = String::new();
let stdin = io::stdin();
let mut handle = stdin.lock();
handle.read_line(&mut buffer)?;
Ok(buffer.trim_right().to_string())
}
pub fn g... |
extern crate procfs;
use std::collections::HashMap;
fn main() {
let mut host = HashMap::new();
let cpu_keys = vec![
"model name",
"cpu cores",
"cache size",
];
let _mem_keys = vec![
"mem_total",
"swap_total",
];
let mut cpu_details = HashMap::new();
... |
pub use markers::*;
pub use ops::*;
mod markers {
pub trait Tuple0 {}
impl Tuple0 for () {}
pub trait Tuple1 {}
impl<E0> Tuple1 for (E0,) {}
pub trait Tuple2 {}
impl<E0, E1> Tuple2 for (E0, E1) {}
pub trait Tuple3 {}
impl<E0, E1, E2> Tuple3 for (E0, E1, E2) {}
pub trait Tuple4 {... |
// Copyright 2015 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 ... |
// This file is part of linux-epoll. It is subject to the license terms in the COPYRIGHT file found in the top-level directory of this distribution and at https://raw.githubusercontent.com/lemonrock/linux-epoll/master/COPYRIGHT. No part of linux-epoll, including this file, may be copied, modified, propagated, or distri... |
/**
* Copyright © 2019
* Sami Shalayel <sami.shalayel@tutamail.com>,
* Carl Schwan <carl@carlschwan.eu>,
* Daniel Freiermuth <d_freiermu14@cs.uni-kl.de>
*
* This work is free. You can redistribute it and/or modify it under the
* terms of the Do What The Fuck You Want To Public License, Version 2,
* as published... |
//! 定时器
//!
#![no_main]
#![no_std]
#![feature(alloc_error_handler)]
extern crate alloc;
use alloc_cortex_m::CortexMHeap;
use bluepill::clocks::ClockExt;
use bluepill::hal::delay::Delay;
use bluepill::hal::gpio::gpioc::PC13;
use bluepill::hal::gpio::{Output, PushPull};
use bluepill::hal::pac::{TIM1, TIM2};
use bluepi... |
/// A container for a FFI function pointer.
///
/// `Function<F>` ensures the stored pointer is valid at all times.
/// By default it is set to a special function which panics upon being called.
/// This, unfortunately, results in varargs functions not being storable.
#[derive(Debug, Clone, Copy)]
pub struct Function<F... |
use crate::vec3::Vec3;
use crate::ray::{Ray, hit::{Hittable,HitRecord}, material::Material};
use std::sync::Arc;
pub struct Sphere {
pub center : Vec3,
pub radius : f64,
pub material : Arc<dyn Material>
}
impl Sphere {
pub fn new(center: Vec3, radius: f64, material: Arc<dyn Material>) -> Sphere {
... |
use std::io::{Read, Result as IOResult, Seek, SeekFrom, Cursor, Error as IOError, ErrorKind};
use crate::read_util::PrimitiveRead;
use crate::lump_data::game_lumps::StaticPropDict;
pub struct GameLumps {
game_lumps: Box<[GameLump]>
}
impl GameLumps {
pub fn read(read: &mut dyn Read) -> IOResult<Self> {
let lu... |
#[doc = "Reader of register MPCBB2_VCTR21"]
pub type R = crate::R<u32, super::MPCBB2_VCTR21>;
#[doc = "Writer for register MPCBB2_VCTR21"]
pub type W = crate::W<u32, super::MPCBB2_VCTR21>;
#[doc = "Register MPCBB2_VCTR21 `reset()`'s with value 0"]
impl crate::ResetValue for super::MPCBB2_VCTR21 {
type Type = u32;
... |
use super::super::types::DBConnection;
pub fn set_query_timeout(conn: &DBConnection) -> postgres::Result<()> {
conn.execute("SET SESSION statement_timeout TO 2000", &[])?;
Ok(())
}
|
#![allow(non_snake_case, non_camel_case_types, non_upper_case_globals, clashing_extern_declarations, clippy::all)]
#[link(name = "windows")]
extern "system" {
pub fn DxcCreateInstance(rclsid: *const ::windows_sys::core::GUID, riid: *const ::windows_sys::core::GUID, ppv: *mut *mut ::core::ffi::c_void) -> ::windows_s... |
use criterion::{
criterion_group, criterion_main, measurement::WallTime, BenchmarkGroup, Criterion,
};
use std::time::Duration;
use ray_tracing::RunConfig;
fn get_config() -> RunConfig<'static> {
let mut config = RunConfig::default();
config.img_config.aspect_ratio = 3.0 / 2.0;
config.quiet = true;
... |
use winit::{event::{Event, WindowEvent}, event_loop::{EventLoop, ControlFlow}, window::{WindowBuilder}};
use pixels::{SurfaceTexture, Pixels};
use std::{sync::{Arc, atomic::{AtomicBool, Ordering::Relaxed}}, thread, time::{Instant}};
use antmachine::{ants::World};
//use rand::distributions::{Distribution, Uniform};
use ... |
#[derive(Debug)]
enum Message {
Quit,
Move { x: i32, y: i32 },
Write(String),
ChangeColor(i32, i32, i32),
}
// ex. of defining a method on enum
impl Message {
fn call(&self) {
match self {
Message::Quit => println!("i am quit"),
Message::Move {x,y}=> println!("i am m... |
// Copyright 2013-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-MI... |
use lazy_static::lazy_static;
use std::collections::HashSet;
pub fn run() {
lazy_static! {
static ref INPUT: String =
std::fs::read_to_string("data/input-day-8.txt")
.unwrap()
.strip_suffix("\n")
.unwrap()
.to_string();
}
... |
use super::ema::rma_func;
use super::falling::declare_s_var;
use super::VarResult;
use crate::ast::stat_expr_types::VarIndex;
use crate::ast::syntax_type::{FunctionType, FunctionTypes, SimpleSyntaxType, SyntaxType};
use crate::helper::{
float_abs, float_max, move_element, pine_ref_to_bool, pine_ref_to_f64, pine_ref... |
pub mod labeledbar;
pub mod table; |
extern crate chrono;
extern crate rand;
mod mersenne_twister;
use self::mersenne_twister::MersenneTwister64;
use chrono::{Duration, Utc};
use rand::Rng;
fn main() {
let mut rng = rand::thread_rng();
let t1 = rng.gen_range(40, 1000);
let t2 = rng.gen_range(40, 1000);
let seed = (Utc::now() + Duratio... |
use futures::Stream;
use geo_types::Geometry;
use h3ron::collections::{H3CellSet, RandomState};
use h3ron::iter::change_resolution;
use h3ron::{H3Cell, ToH3Cells};
use h3ron_polars::frame::H3DataFrame;
use postage::prelude::{Sink, Stream as _};
use std::pin::Pin;
use std::task::{Context, Poll};
use tokio::spawn;
use to... |
#[doc = "Reader of register CHMAP0"]
pub type R = crate::R<u32, super::CHMAP0>;
#[doc = "Writer for register CHMAP0"]
pub type W = crate::W<u32, super::CHMAP0>;
#[doc = "Register CHMAP0 `reset()`'s with value 0"]
impl crate::ResetValue for super::CHMAP0 {
type Type = u32;
#[inline(always)]
fn reset_value() ... |
extern crate jlib;
use jlib::api::account_relations::api::request;
use jlib::api::account_relations::data::{RequestAccountRelationsResponse, RelationsSideKick};
use jlib::api::config::Config;
static TEST_SERVER: &'static str = "ws://101.200.176.249:5040";
fn main() {
let config = Config::new(TEST_SERVER, true);
... |
// 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.
/// This module tests pkg_resolver's RewriteManager when
/// dynamic rewrite rules have been disabled.
use {
super::*,
crate::mock_filesystem::spaw... |
//! Bindings to the [capstone library][upstream] disassembly framework.
//!
//! This crate is a wrapper around the
//! [Capstone disassembly library](http://www.capstone-engine.org/),
//! a "lightweight multi-platform, multi-architecture disassembly framework."
//!
//! The [`Capstone`](struct.Capstone.html) struct is t... |
// 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 std::{cell::RefCell, ptr, rc::Rc};
use crate::{
context::{Context, ContextInner},
path::Path,
raster::Raster,
spinel_sys::*,
Clip,... |
use super::Chain;
use super::Link;
use anyhow::Result;
use chrono::NaiveDate;
use rusqlite::{params, Connection};
use super::FORMAT;
pub fn setup_tables(conn: &Connection) -> Result<()> {
conn.execute(
"CREATE TABLE IF NOT EXISTS chains (
id INTEGER PRIMARY KEY,
... |
//! named accounts for synthesized data accounts for bank state, etc.
//!
//! this account carries the Bank's most recent blockhashes for some N parents
//!
use crate::account::Account;
use crate::account_utils::State;
use crate::hash::Hash;
use crate::pubkey::Pubkey;
use crate::syscall;
use bincode::serialized_size;
u... |
pub trait Sealed {}
impl Sealed for () {}
impl<S: Sealed> Sealed for &'_ S {}
impl<S: Sealed> Sealed for &'_ mut S {}
macro_rules! tuple_impl {
($( $types:ident, )*) => {
impl<$( $types, )*> Sealed for ($( $types, )*)
where
last_type!($( $types, )*): ?Sized,
{}
};
}
for_... |
#![macro_use]
use lazy_static::lazy_static;
use parking_lot::RwLock;
use super::timer::Timer;
lazy_static! {
pub static ref TIMING_DATABASE: RwLock<GlobalTimers> = RwLock::new(GlobalTimers::default());
}
#[derive(Default)]
pub struct GlobalTimers {
pub physics: PhysicsTimers,
pub gui_render: GUITimers,
... |
use avaro::parse_avaro;
use structopt::StructOpt;
#[derive(Debug, StructOpt)]
struct Opt {
#[structopt(name = "FILE")]
file_name: String,
}
fn main() {
let opt: Opt = Opt::from_args();
let content = std::fs::read_to_string(opt.file_name).unwrap();
let result = parse_avaro(&content);
match re... |
// actor/computer.rs
use actor::Actor;
pub struct Computer {
name: String,
position: i32,
money: i32,
knowledge: i32,
tiles: Vec<String>,
still_playing: bool,
skip_one_turn: bool,
}
impl Actor for Computer {
pub fn is_playing(&self) -> bool {
self.still_playing
}
pub ... |
use bevy::app::startup_stage;
use bevy::prelude::*;
use bevy_index::{ComponentIndex, ComponentIndexes};
use rand::distributions::{Bernoulli, Distribution};
const MAP_SIZE: isize = 10;
const GAME_INTERVAL: f32 = 0.5;
const FRACTION_ALIVE: f64 = 0.2;
const GRAPHICS_SCALE: f32 = 10.0;
const COL_ALIVE: Color = Color::rg... |
use crate::intcode::IntCodeEmulator;
const INPUT: &str = include_str!("../input/2019/day2.txt");
pub fn parse_input() -> Vec<i64> {
INPUT
.trim()
.split(',')
.map(|l| l.parse().expect("Unable to parse input"))
.collect()
}
pub fn part1() -> i64 {
let input = parse_input();
... |
//! Benchmarks for rustix.
//!
//! To enable these benchmarks, add `--cfg=criterion` to RUSTFLAGS and enable
//! the "fs", "time", and "process" cargo features.
//!
//! ```sh
//! RUSTFLAGS=--cfg=criterion cargo bench --features=fs,time,process
//! ```
#[cfg(any(
not(criterion),
not(feature = "fs"),
not(fea... |
pub use VkQueryPipelineStatisticFlags::*;
#[repr(u32)]
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum VkQueryPipelineStatisticFlags {
VK_QUERY_PIPELINE_STATISTIC_INPUT_ASSEMBLY_VERTICES_BIT = 0x0000_0001,
VK_QUERY_PIPELINE_STATISTIC_INPUT_ASSEMBLY_PRIMITIVES_BIT = 0x0000_0002,
VK_QUERY_PIPELINE_STAT... |
use super::VecMutator;
use crate::mutators::mutations::{Mutation, RevertMutation};
use crate::{Mutator, SubValueProvider};
pub struct CopyElement;
#[derive(Clone)]
pub struct CopyElementRandomStep;
#[derive(Clone)]
pub struct CopyElementStep {
from_idx: usize,
to_idx: usize,
}
pub struct ConcreteCopyElement<... |
mod logger;
pub use logger::Logger;
|
mod test {
include!(concat!(env!("OUT_DIR"), "/test.rs"));
}
fn main() {
let s = "abc a A ABC abC_def";
//let s = "abc !".to_string(); // match unmatch
let mut lex = test::Lexer::new(&s, test::SpaceCounter::new());
loop {
let res = lex.yylex();
println!("{:?}", res);
if res... |
//! Implementation of Printf-Style string formatting
//! as per the [Python Docs](https://docs.python.org/3/library/stdtypes.html#printf-style-string-formatting).
use crate::{
builtins::{
try_f64_to_bigint, tuple, PyBaseExceptionRef, PyByteArray, PyBytes, PyFloat, PyInt, PyStr,
},
function::ArgInto... |
pub mod grayscale;
pub mod line;
pub mod binary;
pub mod hough;
pub mod ascii_art;
pub mod shrink; |
use std::iter;
use std::slice;
/// A channel slice iterator.
///
/// See [Channel::iter][crate::Channel::iter].
pub struct Iter<'a, T> {
iter: iter::StepBy<slice::Iter<'a, T>>,
}
impl<'a, T> Iter<'a, T> {
#[inline]
pub(super) fn new(slice: &'a [T], step: usize) -> Self {
Self {
iter: s... |
extern crate ansi_term;
extern crate getopts;
use ansi_term::Color::Red;
use std::env;
mod arguments;
mod io;
mod parser;
fn main() {
// Get and parse arguments.
let args: Vec<String> = env::args().collect();
let arguments = match arguments::Arguments::parse(&args) {
Ok(a) => { a }
Err(f)... |
use std::cell::RefCell;
trait Operation {
fn touch(&self) -> ();
}
#[derive(Debug)]
struct BigBlob {
payload: String,
}
impl BigBlob {
fn new() -> Self {
println!("BigBlob created");
BigBlob { payload: "Me be the BigBlob!".to_string() }
}
}
impl Operation for BigBlob {
fn touch(... |
mod vecbuf;
use std::io::{ self, Read, Write };
use rustls::Session;
use rustls::WriteV;
use tokio_io::{ AsyncRead, AsyncWrite };
pub struct Stream<'a, IO: 'a, S: 'a> {
pub io: &'a mut IO,
pub session: &'a mut S,
pub eof: bool,
}
pub trait WriteTls<'a, IO: AsyncRead + AsyncWrite, S: Session>: Read + Writ... |
pub mod bencode;
pub use bencode::BValue;
#[cfg(test)]
mod tests {
use std::collections::HashMap;
use super::*;
#[test]
fn test_parse_number() {
assert_eq!(BValue::from_bytes(&b"i3228e"[..]), Ok((&b""[..], BValue::BNumber(3228))));
assert_eq!(BValue::from_bytes(&b"i-3228e"[..]), Ok... |
use std::cmp::Ordering;
use serde::{Serialize, Deserialize};
use smallvec::SmallVec;
#[derive(Default, Serialize, Deserialize, Debug, Clone)]
pub struct SceneNode {
pub name: String,
#[serde(default)]
pub prefab: String,
pub components: Vec<Component>,
#[serde(skip)]
pub children: SmallVec<[... |
#![allow(non_snake_case, non_camel_case_types, non_upper_case_globals, clashing_extern_declarations, clippy::all)]
#[link(name = "windows")]
extern "system" {}
pub type Print3DManager = *mut ::core::ffi::c_void;
pub type Print3DTask = *mut ::core::ffi::c_void;
pub type Print3DTaskCompletedEventArgs = *mut ::core::ffi::... |
// The MIT License (MIT)
//
// Copyright (c) 2015 Aaron Loucks <aloucks+github@cofront.net>
//
// 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 restriction, including without limita... |
#![allow(unused_variables, non_upper_case_globals, non_snake_case, unused_unsafe, non_camel_case_types, dead_code, clippy::all)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)]
#[repr(transparent)]... |
//////////////////////////////////////////////////
//
// wave.rs
// .wavファイルを読み込むサンプル
//
extern crate byteorder;
// alto
use alto::{Mono, Stereo};
// byteorder
use byteorder::{LittleEndian, ReadBytesExt};
// failure
use failure::{Error, format_err};
// rust std
use std::fs::File;
use std::io::{Read, Seek, Se... |
fn main() {
let msg = Some("Hello world");
if let Some(ref m) = msg {
println!("{}", *m);
}
} |
//! Example that definitely works on Raspberry Pi.
//! Make sure you have "SPI" on your Pi enabled and that MOSI-Pin is connected
//! with DIN-Pin. You just need DIN pin, no clock. WS2818 uses one-wire-protocol.
//! See the specification for details
use ws2818_rgb_led_spi_driver::encoding::{encode_rgb};
use ws2818_rgb... |
//! A map implemented on a trie. Unlike `std::collections::HashMap` the keys in this map are not
//! hashed but are instead serialized.
use crate::collections::next_trie_id;
use crate::env;
use borsh::{BorshDeserialize, BorshSerialize};
use near_vm_logic::types::IteratorIndex;
use std::marker::PhantomData;
#[derive(Bo... |
use crate::{
builtins::{PyBaseExceptionRef, PyModule, PySet},
common::crt_fd::Fd,
convert::IntoPyException,
function::{ArgumentError, FromArgs, FsPath, FuncArgs},
AsObject, Py, PyObjectRef, PyPayload, PyResult, TryFromObject, VirtualMachine,
};
use std::{
ffi, fs, io,
path::{Path, PathBuf},... |
/**
* @lc app=leetcode.cn id=60 lang=rust
*
* [60] 第k个排列
*
* https://leetcode-cn.com/problems/permutation-sequence/description/
*
* algorithms
* Medium (45.34%)
* Total Accepted: 6.3K
* Total Submissions: 13.9K
* Testcase Example: '3\n3'
*
* 给出集合 [1,2,3,…,n],其所有元素共有 n! 种排列。
*
* 按大小顺序列出所有排列情况,并一一标记,当 ... |
#[derive(Debug, Serialize, Deserialize)]
pub struct CsvParams {
#[serde(rename = "quoteChar")]
pub quote_char: Option<String>,
#[serde(rename = "escapeChar")]
pub escape_char: Option<String>,
#[serde(rename = "separatorChar")]
pub separator_char: Option<String>,
#[serde(rename = "endOfLin... |
use crate::backend::c;
use crate::ugid::{Gid, Uid};
#[cfg(not(target_os = "wasi"))]
#[inline]
#[must_use]
pub(crate) fn getuid() -> Uid {
unsafe {
let uid = c::getuid();
Uid::from_raw(uid)
}
}
#[cfg(not(target_os = "wasi"))]
#[inline]
#[must_use]
pub(crate) fn geteuid() -> Uid {
unsafe {
... |
use crate::math::vec3::Vec3;
pub struct Mesh {
pub vertices: Vec<Vec3>,
pub indices: Vec<u32>,
pub uvs: Vec<Vec3>,
pub uv_indices: Vec<u32>,
pub normals: Vec<Vec3>,
pub normal_indices: Vec<u32>
}
impl Mesh {
pub fn new(new_vertices: Vec<Vec3>, new_indices: Vec<u32>, new_uvs: Vec<Vec3>, new... |
use pest::iterators::Pair;
use std::collections::HashMap;
use super::Constant;
use super::Rule;
pub fn parse_number(pair: Pair<Rule>) -> Constant {
match pair.as_rule() {
Rule::float => Constant::Float(pair.into_span().as_str().parse::<f32>().unwrap()),
Rule::integer => Constant::Integer(pair.into_span().as_... |
pub fn compute(signal: &Vec<f64>) -> f64 {
let energy = signal
.iter()
.fold(0_f64, |acc, &sample| acc + sample.abs().powi(2));
return energy;
}
#[cfg(test)]
mod tests {
use super::compute;
use crate::utils::test;
use std::f64;
const FLOAT_PRECISION: f64 = 0.000_000_010;
... |
use crate::prelude::*;
use crate::textures::{Textures, UVCoords};
use crate::sounds::Sounds;
pub struct Graphics {
pub world_texture_program: Program,
pub background_program: Program,
pub textures: Textures,
pub sounds: Sounds,
pub display: Display,
}
impl Graphics {
pub fn new(display: &Display, sounds: Sounds... |
mod vertex;
use ecs::{Entity, ECS};
use renderer::{RendererDevice, MeshFlags};
use std::path::Path;
use vertex::Vertex;
const GRID_SIZE: i32 = 10;
const GRID_STEP: f32 = 4.0;
const GRID_HEIGHT: f32 = -20.0;
pub fn load(ecs: &mut ECS) {
let context = ecs.resources.get_mut::<RendererDevice>().unwrap();
let mu... |
use js_sys::WebAssembly;
use wasm_bindgen::JsCast;
use web_sys::WebGl2RenderingContext as GL;
use web_sys::*;
use crate::render::traits::*;
pub struct Rectangle {
width_: f32,
height_: f32,
indices: js_sys::Uint32Array,
vertices: js_sys::Float32Array,
vao: WebGlVertexArrayObject,
}
impl Rectangl... |
use serde::{Deserialize, Serialize};
#[derive(Deserialize, Serialize, Debug, Clone)]
pub struct Mission {
pub id: i32,
pub name: String,
pub description: String,
}
impl Default for Mission {
fn default() -> Self {
Mission {
id: 0,
name: "Unknown".to_string(),
... |
// NOTE we intentionally avoid using the `quote` crate here because it doesn't work with the
// `x86_64-unknown-linux-musl` target.
// NOTE usually the only thing you need to do to test a new math function is to add it to one of the
// macro invocations found in the bottom of this file.
#[macro_use]
extern crate iter... |
use circuit::{CircuitDesc, Output};
pub trait ProtocolDesc {
type VarType;
type CDescType: CircuitDesc;
fn new(party: u32)->Self;
fn get_party(&self)->u32;
fn exec_circuit(&self, circuit: &Self::CDescType)->
Vec<(Output, Self::VarType)>;
}
|
pub mod error;
pub mod tokens; |
use holo_hash::{DnaHash};
use holochain_zome_types::capability::CapSecret;
use holochain_serialized_bytes::prelude::*;
/// Payload to send to remote DNAs that the local DNA wants to authenticate with.
/// Made unauthenticated, to allow subsequent requests to be authed against a CapClaim.
///
#[derive(Debug, Serialize,... |
use crate::protocol::parts::option_part::{OptionId, OptionPart};
use crate::protocol::parts::option_value::OptionValue;
const VERSION: &str = env!("CARGO_PKG_VERSION");
// An Options part that is used by the client to specify the client version, client
// type, and application name.
pub type ClientContext = OptionPar... |
extern crate ethereum_types;
extern crate keccak_hash;
use ethereum_types::H256;
use keccak_hash::keccak;
use std::collections::HashMap;
use std::vec::Vec;
pub type Bytes = std::vec::Vec<u8>;
pub struct SparseMerkleTree {
/// the ith element holds all non-default nodes in the tree with height i.
nodes: Vec<H... |
fn main() {
let s = String::from("tejas bubane bangalore");
println!("First word position is {}", first_word(&s));
// with slices
println!("First word is {}", first_word_slice(&s));
// array slices
let a = [1, 2, 3, 4, 5];
let first_three: &[i32] = &a[..3];
println!("First 3 are {:?}",... |
use std::thread;
use std::collections::HashMap;
use std::intrinsics::type_name;
use std::mem;
use std::ptr::{self, Unique};
use std::sync::{Arc, Barrier, Mutex};
use std::time::Duration;
use bootstrap::input::ScanCode;
use bootstrap::window::Window;
use bootstrap::window::Message::*;
use bootstrap::time::Timer;
use bs... |
mod options;
use std::collections::VecDeque;
use std::convert::TryInto;
use std::mem;
use std::sync::Arc;
use num_bigint::{BigInt, Sign};
use liblumen_alloc::erts::process::Process;
use liblumen_alloc::erts::term::closure::{Creator, Definition};
use liblumen_alloc::erts::term::prelude::*;
use liblumen_alloc::erts::N... |
use crate::types::SimulationEnvironment;
use crate::utilities::zeros1d;
pub fn phase_1(time: f64, y: &Vec<f64>, simulation_environment: SimulationEnvironment) -> Vec<f64> {
let ret = zeros1d(y.len() as u32);
let m11 = -1.0 * simulation_environment.projectile.proj_mass * simulation_environment.trebuchet.l_arm_l... |
pub struct Solution;
impl Solution {
pub fn integer_replacement(n: i32) -> i32 {
if n == std::i32::MAX {
32
} else {
Solver::new().solve(n)
}
}
}
use std::collections::HashMap;
#[derive(Default)]
struct Solver {
memo: HashMap<i32, i32>,
}
impl Solver {
... |
// #[macro_use]
// extern crate serde_derive;
// pub mod algorithm;
pub mod clustering;
pub mod drawing;
pub mod edge_bundling;
pub mod graph;
// pub mod grouping;
pub mod layout;
pub mod quality_metrics;
pub mod rng;
|
// 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.
//! This module contains the core algorithm for `WorkScheduler`, a component manager subsytem for
//! dispatching batches of work.
//!
//! The subsystem's ... |
trait SameTag<T> {
fn same_tag(&self, other: &Self) -> bool;
}
impl<T> SameTag<T> for Option<T> {
#[allow(unused_assignments)]
fn same_tag(&self, other: &Self) -> bool {
let mut self_tag = 0;
let mut other_tag = 0;
match *self {
Some(_) => self_tag = 0,
Non... |
use rand::{Closed01, Rng};
use std::cmp;
use std::cell::UnsafeCell;
use std::intrinsics;
use super::sys::{Duration, XorShiftRng};
use super::sys::arch::pause;
use super::sys::os::sleep;
const MIN_DELAY_MSEC: u32 = 1;
const MAX_DELAY_MSEC: u32 = 1000;
//type SpinLockAlign = super::simd::u64x8;
struct SpinLockAlign;
#... |
use crate::protocol::parts::OutputParameters;
use crate::{HdbError, HdbResult};
#[cfg(feature = "dist_tx")]
use dist_tx::XaTransactionId;
/// An enum that describes a single database return value.
#[derive(Debug)]
pub enum HdbReturnValue {
/// A resultset of a query.
ResultSet(crate::sync::ResultSet),
///... |
use crate::fs::Dev;
#[inline]
pub(crate) fn makedev(maj: u32, min: u32) -> Dev {
((u64::from(maj) & 0xffff_f000_u64) << 32)
| ((u64::from(maj) & 0x0000_0fff_u64) << 8)
| ((u64::from(min) & 0xffff_ff00_u64) << 12)
| (u64::from(min) & 0x0000_00ff_u64)
}
#[inline]
pub(crate) fn major(dev: Dev... |
use crate::algebra::{Magma, UnitalMagma};
/// A magma whose all elements have an inverse element.
///
/// # Laws
/// * ∀`x: T` (`x.op(&x.invert())` = `x.invert().op(&x)` = `T::identity()`)
pub trait InvertibleMagma: Magma + UnitalMagma {
/// Returns an inverse element.
fn invert(&self) -> Self;
/// Returns `sel... |
// Copyright 2020 IOTA Stiftung
//
// 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 in w... |
#[doc = "Reader of register C12ISR"]
pub type R = crate::R<u32, super::C12ISR>;
#[doc = "Reader of field `TEIF12`"]
pub type TEIF12_R = crate::R<bool, bool>;
#[doc = "Reader of field `CTCIF12`"]
pub type CTCIF12_R = crate::R<bool, bool>;
#[doc = "Reader of field `BRTIF12`"]
pub type BRTIF12_R = crate::R<bool, bool>;
#[... |
use thiserror::Error;
use std::fs::File;
use anyhow::anyhow;
use log::info;
#[derive(Error, Debug)]
pub enum ManifestValidationError {
#[error("manifest has no data sources")]
NoDataSources,
#[error("manifest cannot index data from different networks")]
MultipleNetworks,
}
// Lazily load file from loc... |
use byte_unit::Byte;
use std::{
fmt::{self, Display},
fs::{self, File},
io::{self, Write},
path::Path,
time::Instant,
};
pub trait WriteAsCSV {
fn write_as_csv<W: Write>(&self, writer: &mut W) -> io::Result<()>;
fn write_hdr_as_csv<W: Write>(writer: &mut W) -> io::Result<()>;
}
impl WriteA... |
extern crate ggez;
extern crate rustic;
use rustic::application::*;
use rustic::sop::*;
fn main() {
let mut builder = ApplicationBuilder::new("empty", "rustic");
builder.stories(vec![
fade_out(3.0, ggez::graphics::BLACK),
fade_in(3.0, ggez::graphics::BLACK),
quit_state(),
]);
l... |
//! Memory accesses analysis.
use crate::Gpu;
use binary_heap_plus::BinaryHeap;
use fxhash::{FxHashMap, FxHashSet};
use itertools::Itertools;
use log::trace;
use num::Integer;
use telamon::device::{Context, Device};
use telamon::ir;
use telamon::model::size;
use telamon::search_space::*;
use utils::*;
// TODO(model): ... |
use opengl_graphics::gl::types::GLuint;
use opengl_graphics::gl;
pub struct Texture3D {
id: GLuint,
width: u32,
height: u32,
depth: u32,
}
impl Texture3D {
pub unsafe fn new(id: GLuint, width: u32, height: u32, depth: u32) -> Self {
Self {
id, width, height, depth
}
... |
use crate::ser::write::{write_varint, write_varlong};
use serde::de::{DeserializeSeed, MapAccess, Visitor};
use serde::export::Formatter;
use serde::{Deserialize, Deserializer, Serialize, Serializer};
#[derive(Debug, Clone)]
pub struct VarInt(pub i32);
#[derive(Debug, Clone)]
pub struct VarLong(pub i64);
impl Serial... |
use prettytable::{table, Table};
use rust_decimal::prelude::*;
use crate::domain::collecting::{
collections::{
Collection, CollectionStats, Depot, Year, YearlyCollectionStats,
},
wish_lists::WishList,
};
pub trait AsTable {
fn to_table(self) -> Table;
}
impl AsTable for WishList {
fn to_t... |
use aligned::{Aligned, A8};
use core::ops::{Deref, DerefMut};
use crate::{RxDescriptor, TxDescriptor, MTU};
pub trait RingDescriptor {
fn setup(&mut self, buffer: *const u8, len: usize, next: Option<&Self>);
}
pub struct RingEntry<T: Clone + RingDescriptor> {
desc: Aligned<A8, [T; 1]>,
buffer: Aligned<A8... |
use uefi::boot_services::protocols;
use uefi::boot_services::BootServices;
use uefi::{CStr16,
Status};
use uefi::status::NOT_FOUND;
use PATH_FALLBACK_KERNEL;
pub struct Configuration<'bs>
{
pub kernel: ::uefi::borrow::Cow<'bs, 'static, CStr16>,
//commandline: ::uefi::borrow::Cow<'bs, 'static, str>,
}
im... |
use std::{collections::HashMap};
pub(crate) type Result<T> = std::result::Result<T, String>;
use inkwell::{self, builder::Builder, context::Context, module::Module, types::{BasicType, BasicTypeEnum}, values::{BasicValue, BasicValueEnum, FunctionValue, IntValue, PointerValue}};
use crate::parser::{Expr, Function, Type};... |
use napi::*;
use std::{fmt::Display, usize};
use usb_enumeration::UsbDevice;
pub fn to_js_error<T: Display>(error: T) -> napi::Error {
napi::Error::new(Status::Unknown, error.to_string())
}
pub trait ToJsObject {
fn to_js_object(&self, env: Env) -> Result<JsObject>;
}
impl ToJsObject for UsbDevice {
fn to_js_o... |
//
// Sysinfo
//
// Copyright (c) 2018 Guillaume Gomez
//
use ComponentExt;
/// Struct containing a component information (temperature and name for the moment).
pub struct Component {
temperature: f32,
max: f32,
critical: Option<f32>,
label: String,
}
impl Component {
/// Creates a new `Compone... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.