text stringlengths 8 4.13M |
|---|
// auto generated, do not modify.
// created: Mon Feb 22 23:57:02 2016
// src-file: /QtGui/qsurface.h
// dst-file: /src/gui/qsurface.rs
//
// header block begin =>
#![feature(libc)]
#![feature(core)]
#![feature(collections)]
extern crate libc;
use self::libc::*;
// <= header block end
// main block begin =>
// <= m... |
use serde::Serialize;
#[derive(Serialize)]
#[serde(tag = "type")]
enum Message {
Request {
id: &'static str,
method: &'static str,
params: i8,
},
Response {
id: &'static str,
result: i8,
},
}
fn main() {
let data = Message::Request {
id: "...",
... |
use std::cmp;
use std::collections::HashMap;
use std::env;
use std::error::Error;
use std::fs;
pub fn frequent_words(text: &[u8], k: usize) -> Vec<String> {
let mut frequent = HashMap::new();
let mut max = 0;
text.windows(k)
.map(|x| {
let kmer = frequent.entry(x).or_insert(0);
... |
use crate::name::Name;
use crate::rr_type::RRType;
use crate::util::InputBuffer;
use anyhow::{ensure, Result};
use std::net::{Ipv4Addr, Ipv6Addr};
pub fn name_from_wire(buf: &mut InputBuffer, len: u16) -> Result<(Name, u16)> {
_name_from_wire(buf, len)
}
pub fn name_uncompressed_from_wire(buf: &mut InputBuffer, l... |
//! Persistent accounts are stored in below path location:
//! <path>/<pid>/data/
//!
//! The persistent store would allow for this mode of operation:
//! - Concurrent single thread append with many concurrent readers.
//!
//! The underlying memory is memory mapped to a file. The accounts would be
//! stored across m... |
use crate::entity::Entity;
use crate::mouse::*;
use crate::State;
use crate::{BuildHandler, Event, EventHandler, WindowEvent};
use crate::style::{Display, Length};
use crate::widgets::slider::SliderEvent;
use crate::widgets::Element;
pub struct AudioLevelBar {
front: Entity,
level: f32,
}
impl AudioLevelBa... |
use std::cmp::max;
use std::collections::VecDeque;
use futures::Async;
use futures::Future;
use futures::Stream;
use crate::error::Error;
use crate::responses::Update;
use std::i64;
pub struct UpdatesPoolStream<Fut, Sender> {
pub send_request: Sender,
pub buffer: VecDeque<Update>,
pub executing_request: ... |
use std::{fs};
#[derive(Debug, Clone, PartialEq, Copy)]
pub enum BFT {
MemChange(i128),
Move(i32),
Print,
Read,
LoopStart(Option<usize>),
LoopEnd(usize),
}
pub fn load_bf(uri: &str, read_from_file: bool) -> Vec<BFT> {
//Read from file and remove non-command characters
let file_content... |
#[doc = "Reader of register ITLINE5"]
pub type R = crate::R<u32, super::ITLINE5>;
#[doc = "Reader of field `EXTI0`"]
pub type EXTI0_R = crate::R<bool, bool>;
#[doc = "Reader of field `EXTI1`"]
pub type EXTI1_R = crate::R<bool, bool>;
impl R {
#[doc = "Bit 0 - EXTI0"]
#[inline(always)]
pub fn exti0(&self) ->... |
pub mod trig {
pub fn get_unit_vec(a: Vec<f64>) -> Vec<f64> {
let mut mag: f64 = 0.0;
for i in a.iter() {
mag += i*i;
}
a.iter().map(|x| x / mag.sqrt()).collect::<Vec<f64>>()
}
pub fn get_theta(a: Vec<f64>, b: Vec<f64>) -> f64 {
dot(a, b).acos()
}
pub fn dot(a: Vec<f64>, b: Vec<f64... |
//! Entrypoint for interactive SQL repl loop
use observability_deps::tracing::debug;
use snafu::{ResultExt, Snafu};
use influxdb_iox_client::{connection::Connection, health};
mod repl;
mod repl_command;
/// Start IOx interactive SQL REPL loop
///
/// Supports command history and interactive editing. History is
/// ... |
#![feature(test)]
#![deny(unconditional_recursion)]
#![warn(missing_copy_implementations)]
#![warn(missing_debug_implementations)]
#![warn(missing_docs)]
#![warn(trivial_casts)]
#![warn(trivial_numeric_casts)]
#![warn(unsafe_code)]
#![warn(unused_import_braces)]
//! This file contains tests for the generated lexer.
u... |
use pathfinder_common::BlockNumber;
use crate::prelude::*;
pub(super) fn update_l1_l2_pointer(
tx: &Transaction<'_>,
head: Option<BlockNumber>,
) -> anyhow::Result<()> {
tx.inner().execute(
"UPDATE refs SET l1_l2_head = ? WHERE idx = 1",
params![&head],
)?;
Ok(())
}
pub(super) fn... |
use super::basic::calc_shuffled_positions;
use super::tile::Terrain;
use fov::calc_fov;
use grid::{Grid, Pos};
use rand::Rng;
pub(super) fn add_grass<R: Rng>(level: &mut Grid<Terrain>, rng: &mut R) {
let positions = calc_shuffled_positions(rng);
for &pos in &positions {
if level[pos] == Terrain::Floor ... |
#![allow(unused_variables, non_upper_case_globals, non_snake_case, unused_unsafe, non_camel_case_types, dead_code, clippy::all)]
#[inline]
pub unsafe fn ApplyGuestMemoryFix(vmsavedstatedumphandle: *mut ::core::ffi::c_void, vpid: u32, virtualaddress: u64, fixbuffer: *const ::core::ffi::c_void, fixbuffersize: u32) -> ::w... |
use super::Cartridge;
use crate::ines::File;
use crate::ines::Mirroring;
pub struct AxROM {
pub file: File,
chr_ram: [u8; 0x2000],
bank: u8,
}
impl AxROM {
pub fn new(file: File) -> AxROM {
AxROM {
file,
chr_ram: [0; 0x2000],
bank: 0,
}
}
}
impl... |
#[derive(Debug, PartialEq)]
pub enum Opcode {
HLT, // Halt
LOAD, // Load
// math
ADD,
MUL,
SUB,
DIV,
// jumps
JMP,
JMPF,
JMPB,
JEQ,
// equality
EQ,
NEQ,
GT,
LT,
GTQ,
LTQ,
// utility
IGL(u8), // Illegal
}
impl From<u8> for Opcode {
... |
use crate::movement::ground::Grounded;
use ::amethyst::core::math::Vector3;
use ::amethyst::core::timing::Time;
use ::amethyst::ecs::*;
use serde::Serialize;
use nphysics_ecs::*;
/// The way friction is applied.
#[derive(Serialize, Deserialize, Copy, Clone, Debug)]
pub enum FrictionMode {
/// The velocity is r... |
use std::io::{Write, stdout};
use crossterm::{cursor::{MoveDown, MoveToPreviousLine, RestorePosition, SavePosition}, execute, style::{Attribute, Color, Print, ResetColor, SetAttribute, SetBackgroundColor, SetForegroundColor}};
#[derive(Debug)]
pub enum Error {
Display,
Logic,
Args,
}
pub type Result<T> =... |
use json_utils::json::JsValue;
use crate::core::heq::HEq;
mod js_value_eq;
use js_value_eq::js_value_eq;
mod js_value_hash;
use js_value_hash::js_value_hash;
pub struct JsValueHEq;
impl HEq<JsValue> for JsValueHEq {
fn are_eq(&self, left: &JsValue, right: &JsValue) -> bool {
js_value_eq(left, right)
... |
use std::collections::{HashMap,HashSet};
use std::iter::FromIterator;
use std::u32;
pub struct DirectedGraph {
// <source_node, Vec<(destination_node, weight)>>
// Used HashMap for efficient lookup of a source node's neighbors.
node_edges: HashMap<usize,Vec<(usize,u32)>>
}
impl DirectedGraph {
pub f... |
//store.rs
//store sells items to player
//
//
use super::item_bag::ItemBag as Bag;
#[derive(Debug, Clone)]
pub struct Store {
pub items: Bag,
pub is_active: bool,
}
impl Store {
pub fn gen_store() -> Store {
Store {
items: Bag::gen_bag_with_vals(&vec![
("(R)ope", 50),
... |
// 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.
//! Test tools for building and serving TUF repositories containing Fuchsia packages.
use {
crate::{package::Package, serve::ServedRepositoryBuilder},... |
use structopt::StructOpt;
use super::{CliCommand, GlobalFlags};
pub const AFTER_HELP: &str = r#"EXAMPLES:
To list all installed packages:
$ deck list
To list all installed packages with the prefix "emacs":
$ deck list emacs
"#;
#[derive(Debug, StructOpt)]
pub struct List {
/// Profile to list pa... |
use crate::prelude::*;
use std::collections::HashMap;
pub fn try_load_scene(scene_path: &str) -> Result<PackedScene, String> {
if let Some(scene) = ResourceLoader::godot_singleton().load(
GodotString::from_str(format!("res://scenes/{}.tscn", scene_path)),
GodotString::from_str("PackedScene"),
... |
/// Recognises an alphabetic character, `a-zA-Z`.
#[inline]
pub fn alpha(term: u8) -> bool {
(term >= 0x41 && term <= 0x5A) || (term >= 0x61 && term <= 0x7A)
}
/// Recognises a decimal digit, `0-9`.
#[inline]
pub fn digit(term: u8) -> bool {
term >= 0x30 && term <= 0x39
}
/// Recognises an alphanumeric character, `... |
use failure::*;
use nine::common::CowStr;
use std::fmt::{self, Display};
/// TODO: this can be its own enum.
/// All possible protocol-level errors could be enumerated,
/// and have a single one for a custom message.
/// or maybe that could be its own serverfail variant.
#[derive(Debug)]
pub struct NonFatalError {
... |
#[doc = r"Value read from the register"]
pub struct R {
bits: u8,
}
#[doc = r"Value to write to the register"]
pub struct W {
bits: u8,
}
impl super::TXTYPE4 {
#[doc = r"Modifies the contents of the register"]
#[inline(always)]
pub fn modify<F>(&self, f: F)
where
for<'w> F: FnOnce(&R, &'... |
extern crate handlebars;
#[macro_use]
extern crate serde_json;
use handlebars::Handlebars;
#[test]
fn test_subexpression() {
let hbs = Handlebars::new();
let data = json!({"a": 1, "b": 0, "c": 2});
assert_eq!(
hbs.render_template("{{#if (gt a b)}}Success{{else}}Failed{{/if}}", &data)
... |
#![allow(unused_variables, non_upper_case_globals, non_snake_case, unused_unsafe, non_camel_case_types, dead_code, clippy::all)]
#[cfg(feature = "Services_Cortana")]
pub mod Cortana;
#[cfg(feature = "Services_Maps")]
pub mod Maps;
#[cfg(feature = "Services_Store")]
pub mod Store;
#[cfg(feature = "Services_TargetedConte... |
use serde::Deserialize;
#[derive(Clone, Debug, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub struct Config {
build_group: Option<String>,
max_builds: Option<u32>,
trusted_users: Option<Vec<String>>,
}
|
use tic_tac_toe::{ TicTacToe, TicTacToeGame, PlayerType, GameState };
use std::io::{ stdin, stdout, Write};
trait PrintBoard {
fn print_board(&self);
}
impl PrintBoard for TicTacToeGame {
fn print_board(&self) {
let board = self.board();
for i in (0..9).step_by(3) {
println!("{}{}{}", board[i], bo... |
use brace_hook::{hook, register};
#[hook]
fn my_hook(input: &str) -> String {}
#[hook(my_hook)]
fn hook_1(input: &str) -> String {
format!("hook_1: {}", input)
}
fn hook_2(input: &str) -> String {
format!("hook_2: {}", input)
}
fn hook_3(input: &str) -> String {
format!("hook_3: {}", input)
}
register!... |
//! Global control
use static_assertions::const_assert_eq;
register! {
GlobalControl,
u32,
RW,
Fields [
Enable WIDTH(U1) OFFSET(U0),
]
}
register! {
GlobalStatus,
u32,
RW,
Fields [
Bits WIDTH(U32) OFFSET(U0),
]
}
register! {
GlobalDBuff,
u32,
RW,
... |
use front::stdlib::value::{
Value,
ResultValue
};
use std::default::Default;
/// An execution engine which runs whatever is generated by the `Compiler`
pub trait Executor<Compiled> {
/// Create a new execution engine with the given configuration
fn new(config:&ExecutorConfig) -> Self;
/// Get the ... |
use std;
use serialize;
pub struct T<'a, R: 'a + std::io::Reader> {
reader : &'a mut R,
}
pub enum E {
Other(String)
}
impl<'a, R: std::io::Reader> T<'a, R> {
pub fn new<'b>(r: &'b mut R) -> T<'b, R> {
T { reader: r }
}
}
impl<'a, R: std::io::Reader> serialize::Decoder<E> for T<'a, R> {
... |
use coi::{container, Inject};
use criterion::{criterion_group, criterion_main, Criterion};
use std::sync::Arc;
macro_rules! make_deep_container {
($($scope_type:ident)?) => {
container! {
d1 => D1Provider$(;$scope_type)?,
d2 => D2Provider$(;$scope_type)?,
d3 => D3Provide... |
pub struct Color {
pub r: u8,
pub g: u8,
pub b: u8,
pub a: u8,
}
pub fn hsl_to_rgb(h: f64, s: f64, l: f64) -> Color {
let r;
let g;
let b;
if s == 0.0 {
r = l;
g = l;
b = l;
Color::new(r as u8 * 255, b as u8 * 255, g as u8 * 255, 255)
} else {
... |
use crate::event::NetworkEvent;
pub trait CloneableEvent {
fn boxed_clone(&self) -> Box<dyn NetworkEvent>;
}
impl<T: 'static + Clone + NetworkEvent> CloneableEvent for T {
fn boxed_clone(&self) -> Box<dyn NetworkEvent> {
Box::new(self.clone())
}
}
impl Clone for Box<dyn NetworkEvent> {
fn clo... |
/*!
An example that shows how to handle custom clipboard operations
Requires the following features: `cargo run --example clipboard --features "textbox listbox menu cursor clipboard"`
*/
extern crate native_windows_gui as nwg;
extern crate native_windows_derive as nwd;
use nwd::NwgUi;
use nwg::NativeUi;
#[... |
use amethyst::{
animation::*,
assets::*,
audio::{SourceHandle, WavFormat},
derive::PrefabData,
ecs::*,
error::Error,
prelude::*,
renderer::{
sprite::{prefab::SpriteScenePrefab, SpriteSheetHandle},
types::Texture,
ImageFormat, SpriteRender, SpriteSheet, SpriteSheet... |
use crate::net::ipv6::ip_utils::IPAddr;
use crate::net::udp::udp_recv::{UDPReceiver, UDPRecvClient};
use crate::net::udp::udp_send::{UDPSendClient, UDPSender};
use super::command::{self, Command};
use kernel::{debug, ReturnCode, Driver};
pub const DST_ADDR: IPAddr = IPAddr([
0x10, 0x11, 0x12, 0x13, 0x14, ... |
use crate::widgets::{View, TextView, Dim, Dimensions, desired_size, Vt100Formatter, CharDims};
use std::cmp::min;
impl TextView {
pub fn new(width: Dim, height: Dim) -> TextView {
TextView {
raw_text: "".to_string(),
dims: Dimensions {
width_constraint: width,
... |
use arrow::{datatypes::Field, record_batch::RecordBatch};
use hashbrown::hash_map::RawEntryMut;
use hashbrown::HashMap;
use snafu::Snafu;
use crate::interner::SchemaInterner;
use super::{InfluxColumnType, Schema};
/// Namespace schema creation / validation errors.
#[derive(Debug, Snafu)]
pub enum Error {
#[snafu... |
use std::convert::TryInto;
use proptest::prop_assert_eq;
use proptest::strategy::{Just, Strategy};
use proptest::test_runner::{Config, TestRunner};
use liblumen_alloc::erts::term::prelude::*;
use crate::erlang::bitstring_to_list_1::result;
use crate::test::strategy;
use crate::test::with_process_arc;
#[test]
fn wit... |
//! ```elixir
//! text = Lumen.Web.Document.create_text_node(document, data)
//! ```
use liblumen_alloc::erts::exception;
use liblumen_alloc::erts::process::Process;
use liblumen_alloc::erts::term::prelude::*;
use crate::runtime::binary_to_string::binary_to_string;
use crate::document;
#[native_implemented::functio... |
// Copyright 2022 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 2018 Evgeniy Reizner
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according... |
// Copyright 2017 Dasein Phaos aka. Luxko
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except a... |
pub struct Solution;
impl Solution {
pub fn plus_one(digits: Vec<i32>) -> Vec<i32> {
let mut digits = digits;
let mut i = digits.len() - 1;
loop {
if digits[i] == 9 {
digits[i] = 0;
if i == 0 {
digits.insert(0, 1);
... |
use std::io;
use d04::*;
use file_reader;
const INPUT_FILENAME: &str = "input.txt";
fn main() {
let input_str = match file_reader::file_to_vec(INPUT_FILENAME) {
Err(_) => {
println!("Couldn't turn file into vec!");
return;
},
Ok(v) => v,
};
let mut input_s... |
use data_types::Timestamp;
use iox_catalog::interface::Catalog;
use observability_deps::tracing::*;
use snafu::prelude::*;
use std::{sync::Arc, time::Duration};
use tokio::{select, time::sleep};
use tokio_util::sync::CancellationToken;
pub(crate) async fn perform(
shutdown: CancellationToken,
catalog: Arc<dyn ... |
extern crate proc_macro;
extern crate cfg;
extern crate gearley;
extern crate internship;
mod interner;
#[macro_use]
mod macros;
use std::collections::BTreeMap;
use cfg::earley::Grammar;
use cfg::Symbol;
use gearley::grammar::InternalGrammar;
use gearley::recognizer::Recognizer;
use gearley::forest::NullForest;
use... |
#![feature(proc_macro)]
extern crate proc_macro;
extern crate regex;
use proc_macro::TokenStream;
use std::str::FromStr;
#[proc_macro_derive(AnswerFn)]
pub fn derive_packet_enum(input: TokenStream) -> TokenStream {
let input_string = input.to_string();
let mut i = 0;
loop {
input_string.
}
... |
extern crate rustc_serialize;
extern crate bincode;
use std::collections::hash_map::HashMap;
/// Messages sent and received over a WebSocket.
#[derive(RustcEncodable, RustcDecodable, PartialEq, Clone)]
pub struct PeerMessage {
/// Host address passed in via CLI. Used for identification.
pub sender: String,
... |
use super::pure::PurenessInsights;
use crate::mir::{Body, Expression, Id, VisibleExpressions};
use rustc_hash::FxHashSet;
use std::mem;
impl Expression {
/// All IDs defined inside this expression. For all expressions except
/// functions, this returns an empty vector. The IDs are returned in the
/// order... |
#[doc = r" Value read from the register"]
pub struct R {
bits: u32,
}
#[doc = r" Value to write to the register"]
pub struct W {
bits: u32,
}
impl super::MODE {
#[doc = r" Modifies the contents of the register"]
#[inline]
pub fn modify<F>(&self, f: F)
where
for<'w> F: FnOnce(&R, &'w mut ... |
// Copyright 2016 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... |
use chrono::Utc;
use serenity::{
model::prelude::*, prelude::*
};
use tracing::debug;
use rand::Rng;
use std::time::Instant;
use crate::DATABASE;
use super::help;
mod image_utils;
mod level_up;
pub mod rank;
pub mod leaderboard;
pub fn get_level_xp(level: i32) -> i32 {
5 * level.pow(2) + 50 * level + 100
}
... |
use regex::Regex;
pub struct PasswordEntry {
min: u8,
max: u8,
letter: char,
password: String,
}
impl PasswordEntry {
pub fn from_string(s: String) -> PasswordEntry {
let re = Regex::new(r"(\d+)-(\d+) (.): (.+)").unwrap();
let captures = re.captures(&s).unwrap();
let min =... |
use crate::util;
use crate::youtube;
use regex::Regex;
use serde::{Deserialize, Serialize};
use std::path::{Path, PathBuf};
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Album {
#[serde(skip)]
pub url: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub artist: Optio... |
use std::cell::Cell;
use std::fmt;
thread_local! {
static THREAD_TAG: Cell<Tag> = Cell::new(Tag(0));
}
/// Run the given closure with the specified tag.
pub(super) fn with_tag<F, T>(tag: Tag, f: F) -> T
where
F: FnOnce() -> T,
{
return THREAD_TAG.with(|w| {
let _guard = Guard(w.replace(tag));
... |
use std::iter;
use crate::Battery;
use super::device::IoCtlDevice;
#[derive(Debug)]
pub struct IoCtlIterator(pub Option<IoCtlDevice>);
impl iter::Iterator for IoCtlIterator {
type Item = Battery;
fn next(&mut self) -> Option<Self::Item> {
match self.0.take() {
None => None,
S... |
#[macro_use]
extern crate abstract_machines;
use abstract_machines::*;
use cps::*;
fn main() {
let id1 = cpsabs!("x", cpsvar!("x"));
let id2 = cpsabs!("y", cpsvar!("y"));
let mut t = cps::Transform::default();
// let mut c = t.cps(cpsapp!(id1.clone(), id2.clone()), CTerm::Return);
let mut c = t.cp... |
use mdb_rs::MDatabase;
#[test]
fn main(){
println!("{:#?}", MDatabase::open_database("test.mdb"));
}
|
//! LCD controller
// TODO - generic over TCON0/TCON1
use super::DisplayTiming;
use crate::pac::tcon1::{
Control, DataClock, GlobalControl, Timing0, Timing1, Timing2, Timing3, Timing4, Timing5, TCON1,
};
pub struct LcdController {
tcon: TCON1,
}
impl LcdController {
pub(crate) fn new(mut tcon: TCON1) ->... |
use embedded_graphics::{
mono_font::{ascii::FONT_6X10, MonoFont},
pixelcolor::BinaryColor,
};
use crate::themes::default::button::{ButtonStateColors, ButtonStyle};
pub struct SecondaryButtonInactive;
pub struct SecondaryButtonIdle;
pub struct SecondaryButtonHovered;
pub struct SecondaryButtonPressed;
impl Bu... |
use std::fs::OpenOptions;
use std::fs;
use std::io::prelude::*;
use time::{get_time, at};
/// Log a message in a textfile log folder log
/// Also includes the date
pub fn log(content: &str) {
log_at("log", "log", content);
}
/// Logs a message at a directory with given name
/// Also includes the date
pub fn log_a... |
extern crate xmlparser as xml;
#[macro_use] mod token;
use token::*;
test!(text_01, "<p>text</p>",
Token::ElementStart("", "p"),
Token::ElementEnd(ElementEnd::Open),
Token::Text("text"),
Token::ElementEnd(ElementEnd::Close("", "p"))
);
test!(text_02, "<p> text </p>",
Token::ElementStart("", "p"),... |
use super::attribute::AttributeInfo;
use super::common_type::*;
#[derive(Debug)]
pub struct FieldInfo {
pub access_flags: u2,
pub name_index: u2,
pub descriptor_index: u2,
pub attributes_count: u2,
pub attributes: Vec<AttributeInfo>,
}
|
#[allow(dead_code)]
pub fn copy_dir<P: AsRef<std::path::Path>, Q: AsRef<std::path::Path>>(from: P, to: Q) -> std::io::Result<()> {
let src = from.as_ref();
let dst = to.as_ref();
std::fs::create_dir(dst)?;
for path in src.read_dir()? {
let pbuf = path.unwrap().path();
let file_name = pbu... |
use borsh::{BorshDeserialize, BorshSerialize};
use near_sdk::collections::Map;
use near_sdk::{env, near_bindgen, AccountId, Balance, EpochHeight};
use near_sdk::json_types::U64;
#[global_allocator]
static ALLOC: wee_alloc::WeeAlloc = wee_alloc::WeeAlloc::INIT;
type WrappedTimestamp = U64;
/// Voting contract for unl... |
pub use blurz::{
bluetooth_session::BluetoothSession,
bluetooth_adapter::BluetoothAdapter,
bluetooth_device::BluetoothDevice,
bluetooth_discovery_session::BluetoothDiscoverySession,
};
fn search() -> BluetoothSession {
let session = BluetoothSession::create_session(None).unwrap();
let adapter =... |
extern crate rand;
use std::{thread, time};
use rand::Rng;
const MAX_X: usize = 40;
const MAX_Y: usize = 20;
const MAX_TICKS: usize = 60;
const TICK_DELAY: u64 = 200;
#[derive(Debug)]
pub enum ArrayOutOfBoundsException {
WtfError,
}
pub type ArrayElementResult = Result<usize, &'static str>;
fn init_grid(grid: &... |
// <main>
use actix_cors::Cors;
use actix_ratelimit::{MemoryStore, MemoryStoreActor, RateLimiter};
use actix_web::{guard, http, middleware, web, App, FromRequest, HttpServer};
use actix_web_middleware_redirect_https::RedirectHTTPS;
use dotenv::dotenv;
use openssl::ssl::{SslAcceptor, SslAcceptorBuilder, SslFiletype, Ssl... |
use std::collections::HashMap;
use std::error::Error;
use std::str;
use x11rb::connection::Connection as Conn;
#[allow(unused_imports)]
use x11rb::connection::{Connection as _, RequestConnection as _};
use x11rb::protocol::xproto::*;
#[allow(unused_imports)]
use x11rb::wrapper::ConnectionExt as _;
use x11rb::xcb_ffi::... |
mod dedupe_command;
mod print_extents_command;
pub use self::dedupe_command::*;
pub use self::print_extents_command::*;
// ex: noet ts=4 filetype=rust
|
use proconio::input;
use proconio::marker::Usize1;
use std::ops::Range;
fn main() {
input! {
n: usize,
q: usize,
a: [u8; n],
};
let bucket_size = (1..).take_while(|&s| s * s <= n).last().unwrap();
#[derive(Debug)]
struct Bucket {
data: Data,
lazy: Lazy,
... |
use core::{char, convert::TryFrom, fmt};
/// All possible characters that can be used in EOSIO names.
pub const NAME_CHARS: [u8; 32] = *b".12345abcdefghijklmnopqrstuvwxyz";
/// The maximum character length of an EOSIO name.
pub const NAME_MAX_LEN: usize = 13;
/// An error which can be returned when parsing an EOSIO ... |
// Copyright (c) 2015-2020 Vincent van Ingen <code@abitvin.com>
// Licensed under the MIT license <LICENSE.md or http://opensource.org/licenses/MIT>
// This file may not be copied, modified, or distributed except according to those terms.
use std::cell::RefCell;
use std::error::Error;
use std::fmt;
use std::rc::Rc;
us... |
use image;
use super::*;
pub struct ImageOutput<P, Container>
where P: image::Pixel + 'static
{
// buf: image::ImageBuffer<image::Rgb<u8>,Vec<u8>>,
buf: image::ImageBuffer<P,Container>,
path: String,
}
pub type ImageOutput8 = ImageOutput<image::Rgb<u8>, Vec<u8>>;
impl<P, Container> ImageOutput<P, Con... |
// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT.
pub fn serialize_operation_add_application_cloud_watch_logging_option(
input: &crate::input::AddApplicationCloudWatchLoggingOptionInput,
) -> Result<smithy_http::body::SdkBody, smithy_types::Error> {
let mut out = String::new();
... |
use alloc::string::String;
use alloc::sync::Arc;
use alloc::vec::Vec;
use lazy_static::lazy_static;
use rcore_fs::dev::{self, BlockDevice, DevError};
use spin::RwLock;
//pub use block::BlockDriver;
/// Block device
pub mod virtio;
/// Device tree
pub mod device_tree;
#[derive(Debug, Eq, PartialEq)]
pub enum DeviceT... |
use nom::{digit, is_alphanumeric, IResult};
use std::str::{self, FromStr};
#[derive(Debug)]
pub enum RuleExpression {
Literal(Box<LiteralExpression>),
Operator(Box<OperatorExpression>),
}
#[derive(Debug)]
pub enum LiteralExpression {
Num(i32),
Str(String),
Bool(bool),
}
#[derive(Debug)]
pub struc... |
// Copyright 2022 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 ... |
// Membuat input dari console dapat menggunakan `print!`
// dan inputan berada disampingnya
// dengan cara memflush `stdout`
//
use std::io::{self, Write};
fn main() {
print!("Nama Anda: ");
let stdout = io::stdout();
let mut handle = stdout.lock();
let _ = handle.flush();
let mut input = String::new... |
use std::io::{BufRead, Lines};
use subprocess::Exec;
#[inline]
pub fn exec(cmd: Exec) -> std::io::Result<Lines<impl BufRead>> {
// We usually have a decent amount of RAM nowdays.
Ok(std::io::BufReader::with_capacity(
8 * 1024 * 1024,
cmd.stream_stdout()
.map_err(|e| std::io::Error::... |
fn main() {
let list = include_str!("input").lines().map(|st| u16::from_str_radix(st, 2).unwrap()).collect();
println!("Part Two: {}", part_one(&list));
println!("Part Two: {}", part_two(&list));
}
fn part_one(list: &Vec<u16>) -> u64 {
let mut counts = vec![0; 12];
for num in list {
for i ... |
//! Example non-exhaustive enums,used in tests
#![allow(dead_code, missing_docs)]
#![allow(clippy::derive_partial_eq_without_eq)]
pub mod command_one {
use std::fmt::{self, Display};
#[repr(u8)]
#[derive(StableAbi, Hash, Debug, PartialEq, Eq, Clone)]
#[sabi(kind(WithNonExhaustive(
size = 64,
... |
use std::ops::Range;
use bevy::{
prelude::*,
render::{
mesh::{
VertexAttribute,
VertexAttributeValues
},
pipeline::{
DynamicBinding,
PipelineSpecialization,
PrimitiveTopology,
RenderPipeline
},
}
};
use... |
use super::*;
pub trait Hittable {
fn hit(&self, ray: &Ray, t_min: f64, t_max: f64, rec: &mut HitRecord) -> bool;
}
impl<T: Hittable> Hittable for Vec<T> {
fn hit(&self, ray: &Ray, t_min: f64, t_max: f64, rec: &mut HitRecord) -> bool {
let mut hr = HitRecord::default();
let mut hit_anything = ... |
use std::{
collections::{BTreeMap, VecDeque},
fmt,
fs::{File, OpenOptions},
io::{self, BufWriter, Seek, SeekFrom},
ops::Deref,
path::Path,
};
use slack::RtmClient;
use crate::queue::{AddResult::*, RemoveResult::*};
use crate::user::{SlackMap, UserID};
/// The User ID (a string of the form UXX... |
use codec::Encode;
use core::marker::PhantomData;
use frame_support::Parameter;
use sp_runtime::{
traits::{AtLeast32Bit, Scale},
generic::{Header as SHeader},
traits::{BlakeTwo256, IdentifyAccount, Verify},
MultiSignature, OpaqueExtrinsic,
};
use sub_runtime::ipse::{Order, Miner};
use substrate_subxt:... |
//! Mocks for the tokens module.
#![cfg(test)]
use frame_support::{impl_outer_event, impl_outer_origin, parameter_types};
use frame_system as system;
use sp_core::H256;
use sp_runtime::{testing::Header, traits::IdentityLookup, Perbill};
use sp_std::cell::RefCell;
use std::collections::HashMap;
use super::*;
impl_ou... |
// pretty-expanded FIXME #23616
// Copyright 2013 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 th... |
//! An async parser for `multipart/form-data` content-type in Rust.
//!
//! It accepts a [`Stream`](https://docs.rs/futures/0.3.5/futures/stream/trait.Stream.html) of [`Bytes`](https://docs.rs/bytes/0.5.4/bytes/struct.Bytes.html) as
//! a source, so that It can be plugged into any async Rust environment e.g. any async ... |
use std::fs;
use std::time::Instant;
use crate::Cardinal::{EAST, NORTH, SOUTH, WEST};
use std::ops::Neg;
#[derive(Copy, Clone, Eq, PartialEq, Ord, PartialOrd)]
#[repr(i32)]
enum Cardinal {
NORTH,
EAST,
SOUTH,
WEST,
}
fn move_stuff(mut x: i32, mut y: i32, dir: Cardinal, step: i32) -> (i32, i32) {
m... |
#![allow(unused)]
use rox::Rox;
use color_eyre::eyre::Result;
fn main() -> Result<()>{
color_eyre::install()?;
if let Some(config_file_path) = std::env::args().nth(1) {
let rox = Rox::interpret(&config_file_path)?;
println!("**Printing Name Value pairs**");
for item in rox.switches {
... |
// Copyright 2022 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 ... |
#![allow(unused_variables, non_upper_case_globals, non_snake_case, unused_unsafe, non_camel_case_types, dead_code, clippy::all)]
#[repr(transparent)]
#[doc(hidden)]
pub struct ILockApplicationHost(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for ILockApplicationHost {
type Vtable = ILo... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.