text stringlengths 8 4.13M |
|---|
use super::objstr::PyStringRef;
use super::objtype::{self, PyClassRef};
use crate::pyobject::{PyClassImpl, PyContext, PyRef, PyResult, PyValue};
use crate::vm::VirtualMachine;
#[pyclass]
#[derive(Debug)]
pub struct PyMappingProxy {
class: PyClassRef,
}
pub type PyMappingProxyRef = PyRef<PyMappingProxy>;
impl PyV... |
use std::io::prelude::*;
use std::fs::File;
use ssl::symm::{self, decrypt};
use serialize::base64::FromBase64;
#[test]
fn run() {
let mut f = File::open("./data/7.txt").unwrap();
let mut s = String::new();
f.read_to_string(&mut s).unwrap();
let bytes = s.from_base64().unwrap();
let key = "YELLOW... |
use super::lexer::TokenPosition;
use std::fmt;
#[derive(Debug)]
pub enum ParserErrorValue {
Constant(String),
}
#[derive(Debug)]
pub struct ParserError {
value: ParserErrorValue,
position: Option<TokenPosition>,
}
#[allow(dead_code)]
impl ParserError {
pub fn new(value: &str) -> ParserError {
... |
use std::f64::consts::PI;
use std::fs::File;
fn main(){
let mut x = 5 ;
let y = x ;
x = x + 1;
println!("x 为 {0} ,y 为 {1}", x,y);
let str1 = String::from("hello");
println!("{}",str1);
let str2 = str1.clone() ;
println!("{}",str2);
//str1 = String::from("hello abc");
// pri... |
use super::{Config, Innovs, Net};
use std::future::Future;
pub struct Pop {
innovs: Innovs,
nets: Vec<Net>,
}
impl Pop {
async fn new<T>(input_size: usize, output_size: usize, conf: &Config<T>) -> Self
where
T: Future<Output = f64>,
{
let init_links_count = (input_size + 1) * outpu... |
// Copyright (c) 2022 Denis Avvakumov
// Licensed under the MIT license, https://opensource.org/licenses/MIT
//! # Iptools
//!
//! This is a port of package [iptools](https://github.com/bd808/python-iptools) from Python.
pub mod error;
pub mod iprange;
pub mod ipv4;
pub mod ipv6;
|
use crate::cpu::MemoryAddress;
use crate::registers::{ConditionalFlag, Register, Register16bit};
#[derive(Debug)]
pub enum Instruction {
// n: unsigned 8-bit immediate data
// nn: unsigned 16-bit immediate data
// e: signed 8-bit immediate data
// r: signed 8-bit immediate data, relative to PC
// ... |
use crate::program::{self, Program};
use std::error::Error;
use std::fmt;
pub struct Interpreter {
program: Program,
instruction_pointer: usize,
}
#[derive(Debug)]
pub enum InterpreterError {
InvalidOpcode(isize),
OutOfBound(program::OutOfBoundError),
}
impl Error for InterpreterError {}
impl fmt::D... |
use constants::*;
use std::slice::Iter;
use self::CellGroupType::*;
use strategies::Move;
#[derive(Copy, Clone, PartialEq)]
pub enum Value {
None,
No,
Yes
}
pub enum CellGroupType {
XY,
XZ,
YZ,
SquareZ
}
impl CellGroupType {
pub fn iterator() -> Iter<'static, CellGroupType> {
... |
extern crate mpesa;
use mpesa::access_token::AccessToken;
fn main() {
println!("{}", AccessToken::new(String::from("0SKHgBn66azzyz5Y22ZufBhP6m5JwmQT"), String::from("GUm27XVgi697SUfE")).token().expect("unable to retrieve token at this time");
} |
fn main() {
let input = include_str!("input");
let input = input.
lines().
map(|i| i.parse().unwrap()).
collect::<Vec<i32>>();
println!("1 -> {}", escape(input.clone(), false));
println!("2 -> {}", escape(input.clone(), true));
}
fn escape(mut jmplist: Vec<i32>, weird_offsets:... |
use amethyst::{
prelude::*,
utils::application_root_dir,
};
mod components;
mod state;
mod systems;
mod bundle;
fn main() -> amethyst::Result<()> {
amethyst::start_logger(Default::default());
let app_root = application_root_dir()?;
let assets_dir = app_root.join("assets");
let config_dir = a... |
#[deprecated(note = "use lapin directly instead")]
pub use lapin_futures_tls_internal::error::*;
|
use eve_data_core::TypeID;
use serde::{Deserialize, Serialize};
#[derive(Serialize, Debug, Clone)]
pub struct Character {
pub id: i64,
pub name: String,
}
#[derive(Serialize, Debug)]
pub struct Hull {
pub id: TypeID,
pub name: String,
}
#[derive(Deserialize, Serialize, Debug)]
pub struct WaitlistCate... |
extern crate docopt;
#[macro_use]
extern crate serde_derive;
extern crate rustc_serialize;
extern crate serde;
extern crate yatc;
use yatc::driver::{main_loop, Tokens, AST, Jit,Interpreter, Target};
use docopt::Docopt;
const USAGE: &str = "
Usage: yatc [(-l | -p | -j | -i | -t)]
Options:
-l Run only lexer and s... |
// Module 5:
// bottles of beer song
//
// sing_beer_song
// prints the lyrics to the song "99 bottles of beer".
// INPUT || beer_number : u8
//
// 99 bottles of beer on the wall, 99 bottles of beer.
// Take one down and pass it around, 98 bottles of beer on the wall.
//
// ...
//
// 2 bottles of beer on the wall, 2 b... |
// This file is part of Substrate.
// Copyright (C) Parity Technologies (UK) Ltd.
// SPDX-License-Identifier: Apache-2.0
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.a... |
/*
https://leetcode-cn.com/problems/pattern-matching-lcci/
面试题 16.18. 模式匹配
你有两个字符串,即pattern和value。 pattern字符串由字母"a"和"b"组成,用于描述字符串中的模式。例如,字符串"catcatgocatgo"匹配模式"aabab"(其中"cat"是"a","go"是"b"),该字符串也匹配像"a"、"ab"和"b"这样的模式。但需注意"a"和"b"不能同时表示相同的字符串。编写一个方法判断value字符串是否匹配pattern字符串。
示例 1:
输入: pattern = "abba", value = "dogcatc... |
#![no_std]
extern crate alloc;
mod block_dev;
mod layout;
mod efs;
mod bitmap;
mod vfs;
mod block_cache;
pub const BLOCK_SZ: usize = 512;
pub use block_dev::BlockDevice;
pub use efs::EasyFileSystem;
pub use vfs::Inode;
use layout::*;
use bitmap::Bitmap;
use block_cache::get_block_cache; |
use std::collections::HashMap;
use crate::shaders::Shader;
use crate::{Renderer, Scene};
use self::basic_shader::basic_shader;
use self::font_shader::font_shader;
use self::gui_shader::gui_shader;
use self::hex_shader::hex_shader;
use self::imgui_shader::imgui_shader;
use self::obj_model_shader::obj_model_shader;
use... |
#[derive(Debug)]
pub enum Segment {
Argument,
Local,
Static,
Constant,
This,
That,
Pointer,
Temp,
}
#[derive(Debug, Default)]
pub struct JackVM {
ram: Vec<i16>,
static_ptr: usize,
}
const OFFSET_SP: usize = 0;
const OFFSET_LOCAL_PTR: usize = 1;
const OFFSET_ARG_PTR: usize = 2;
... |
// Copyright 2019 WHTCORPS INC Project Authors. Licensed under Apache-2.0.
// TODO: Maybe we can find a better place to put these interfaces, e.g. naming it as prelude?
//! Batch executor common structures.
pub use milevadb_query_common::execute_stats::{
ExecSummaryCollector, ExecuteStats, WithSummaryCollector,
... |
use cgmath::Vector2;
use grid::StaticGrid;
use direction::*;
#[test]
fn neighbour_coord_iter() {
let grid = StaticGrid::new_copy(4, 4, ());
let mut iter = grid.neighbour_coord_iter(Vector2::new(0, 0), CardinalDirections);
assert_eq!(iter.next(), Some(Vector2::new(1, 0)));
assert_eq!(iter.next(), Some... |
// Copyright 2021 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 agre... |
// Copyright 2021 The BMW Developers
//
// 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... |
//! This lib contains common functionality for uint_n and natmod_p.
//! It is pretty useless on its own.
use quote::quote;
pub fn build_struct(
struct_name: &syn::Ident,
bytes: usize,
num_bits: usize,
) -> proc_macro2::TokenStream {
quote! {
#[derive(Clone, Copy)]
pub struct #struct_na... |
use core::mem::size_of;
use x86_64::registers::control::{Cr0Flags, Cr4Flags, EferFlags};
const STACK_SIZE: usize = 1024 * 1024; // 1 MiB
#[repr(C, align(4096))]
struct Stack([u8; STACK_SIZE]);
static mut STACK: Stack = Stack([0; STACK_SIZE]);
#[naked]
#[link_section = ".text32"]
#[cfg(target_os = "none")]
unsafe exte... |
#![cfg(feature = "runtime-benchmarks")]
use super::*;
use sp_std::prelude::*;
use frame_system::{RawOrigin, EventRecord};
use frame_benchmarking::{benchmarks, whitelisted_caller};
use crate::Module as KVStore;
fn assert_last_event<T: Trait>(generic_event: <T as Trait>::Event) {
let events = frame_system::Module::<T... |
use std::io;
use pnet_packet::{FromPacket, Packet};
use pnet_packet::ipv4::Ipv4Packet;
use pnet_packet::icmp::{Icmp, IcmpPacket};
use tokio::prelude::*;
use socket2::SockAddr;
use crate::socket::Socket;
#[must_use = "futures do nothing unless polled"]
#[derive(Debug)]
pub struct RecvIcmpPacket {
inner: Option<So... |
use async_std::prelude::*;
use async_std::sync::{Arc, Mutex};
type Connections = Arc<Mutex<Vec<async_std::net::TcpStream>>>;
//@TODO listen to port 80
pub async fn run(streams: Connections) -> std::io::Result<()> {
// Listen to desired port
let listener = async_std::net::TcpListener::bind("0.0.0.0:80").await?;... |
use crate::{common::*, runtime::*};
use core::{cell::RefCell, convert::TryFrom};
use std::os::raw::c_int;
use std::slice::from_raw_parts as slice_from_raw_parts;
#[cfg(all(target_os = "linux", feature = "ffi_pseudo_socket_api"))]
/// cbindgen:ignore
pub mod pseudo_socket_api;
// Temporary simplfication: ignore ipv6. ... |
#[macro_export]
macro_rules! lines_from {
($filename:expr) => {
{
use std::io::BufRead;
let file = std::fs::File::open(format!("resources/{}.txt", $filename)).unwrap();
let reader = std::io::BufReader::new(file);
reader.lines()
}
}
}
#... |
use commons::io::load_file_lines;
use itertools::Itertools;
use std::cmp::Ordering;
use std::collections::VecDeque;
#[derive(Debug)]
struct RingBuffer<T> {
buf: Vec<T>,
size: usize,
insert_at: usize,
}
impl<T> RingBuffer<T> {
pub fn new(size: usize) -> Self {
RingBuffer {
buf: Vec:... |
#![allow(dead_code)]
use std::collections::{HashMap, HashSet};
use std::fmt::Write;
const X_MAX: usize = 4;
const Y_MAX: usize = 4;
const X_CENTER: usize = X_MAX / 2;
const Y_CENTER: usize = Y_MAX / 2;
fn main() {
challenge_1();
challenge_2();
}
fn challenge_1() {
let input = std::fs::read_to_string("in... |
use porus::prelude::{BinaryHeap, Heap, List};
use proptest::prelude::*;
use std::fmt::Debug;
#[derive(Debug, Clone)]
enum ArbitraryHeap {
BinaryHeap,
}
impl ArbitraryHeap {
fn allocate<'a, T: 'a + Ord>(&self) -> Box<dyn 'a + Heap<Elem = T>> {
match self {
ArbitraryHeap::BinaryHeap => Box::... |
#[allow(unused_imports)]
use serde_json::Value;
#[derive(Debug, Serialize, Deserialize)]
pub struct AuthIdNtokenPrivilegeItem {
/// Specifies the ID of the privilege.
#[serde(rename = "id")]
pub id: String,
/// Specifies the name of the privilege.
#[serde(rename = "name")]
pub name: Option<Stri... |
#[derive(Clone)]
pub struct TodoAddPayload {
pub id: String,
pub name: String,
}
#[derive(Clone)]
pub struct TodoRemovePayload {
pub id: String,
}
#[derive(Clone)]
pub struct TodoResolvePayload {
pub id: String,
}
#[derive(Clone)]
pub enum Action {
TodoAdd(TodoAddPayload),
TodoRemove(TodoRemo... |
use crate::component::Component;
use crate::entity_id::EntityId;
use crate::seal::Sealed;
use crate::sparse_set::SparseSet;
use crate::track::{All, AllConst};
use crate::tracking::{
is_track_within_bounds, map_deletion_data, DeletionTracking, InsertionTracking,
ModificationTracking, RemovalOrDeletionTracking, R... |
struct Solution;
impl Solution {
fn find_peak_element(nums: Vec<i32>) -> i32 {
let mut l = 0;
let mut h = nums.len() - 1;
while l < h {
let m1 = l + (h - l) / 2;
let m2 = m1 + 1;
if nums[m1] < nums[m2] {
l = m2;
} else {
... |
pub struct Solution {}
impl Solution {
pub fn trap(height: Vec<i32>) -> i32 {
if height.is_empty() {return 0;}
let mut area = 0;
let mut head = 0;
let mut head_height = height[head];
let mut tail = height.len() - 1;
let mut tail_height = height[tail];
while ... |
#![warn(rust_2018_idioms, single_use_lifetimes)]
#![allow(dead_code)]
#[macro_use]
mod auxiliary;
pub mod default {
use pin_project::pin_project;
use std::marker::PhantomPinned;
struct Inner<T> {
f: T,
}
assert_unpin!(Inner<()>);
assert_not_unpin!(Inner<PhantomPinned>);
#[pin_pr... |
#[cfg(test)]
extern crate quickcheck;
#[cfg(test)]
extern crate quickcheck_macros;
pub type PrefixTable = Vec<Option<usize>>;
pub fn prepare(needle: &[u8]) -> PrefixTable {
let mut prefix_len: Option<usize> = None;
let mut prefix_table: PrefixTable = Vec::with_capacity(needle.len());
// Don't try to matc... |
extern crate wapc_guest as guest;
use guest::prelude::*;
#[no_mangle]
pub extern "C" fn wapc_init() {
register_function("SayHello", do_hello);
}
fn do_hello(msg: &[u8]) -> CallResult {
let name = std::str::from_utf8(msg)?;
let res =
host_call("default",
"sample",
... |
// Copyright 2020 TiKV Project Authors. Licensed under Apache-2.0.
mod test_cdc;
use fail;
use panic_hook;
fn setup_fail<'a>() -> fail::FailScenario<'a> {
crate::init();
fail::FailScenario::setup()
}
#[test]
fn test_setup_fail() {
let _ = std::thread::spawn(move || {
let _ = setup_fail();
... |
/*
* @lc app=leetcode id=528 lang=rust
*
* [528] Random Pick with Weight
*
* https://leetcode.com/problems/random-pick-with-weight/description/
*
* algorithms
* Medium (43.35%)
* Likes: 451
* Dislikes: 849
* Total Accepted: 50.1K
* Total Submissions: 115.6K
* Testcase Example: '["Solution", "pickInd... |
use crate::prelude::{Distance, ExtentN, FloatPoint, Point, PointN};
#[derive(Debug)]
pub struct Sphere<Nf> {
pub center: PointN<Nf>,
pub radius: f32,
}
pub type Sphere2 = Sphere<[f32; 2]>;
pub type Sphere3 = Sphere<[f32; 3]>;
impl<N> Clone for Sphere<N>
where
PointN<N>: Clone,
{
#[inline]
fn clon... |
use sp_runtime_interface::runtime_interface;
#[runtime_interface]
trait Test {
fn foo() {}
#[version(2)]
#[cfg(feature = "foo-feature")]
fn foo() {}
}
fn main() {}
|
pub mod wgstate;
pub use wgstate::WgState;
|
impl Clone for {{rust_local}} {
#[inline]
fn clone(&self) -> Self {
unsafe { Self::from_raw(sys::{{extern_implicit_clone}}(self.as_raw_{{rust_local}}())) }
}
}
|
/// Reflects the dimensions of a matrix, and how various operations affect them.
#[derive(Debug, Clone, Copy)]
pub struct VectorDims {
pub count: u32,
}
impl VectorDims {
pub fn new(count: u32) -> VectorDims {
VectorDims { count: count }
}
}
|
// Copyright 2017 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.
//! Type-safe bindings for Magenta channel objects.
use {HandleBase, Handle, HandleRef, INVALID_HANDLE, Peered, Status, Time};
use {sys, handle_drop, into... |
use crate::descriptions::{FrameStatistics, GammaControl, GammaControlCaps, Mode, OutputDesc};
use crate::device::IDevice;
use crate::enums::Format;
use crate::surface::ISurface;
use com_wrapper::ComWrapper;
use dcommon::error::Error;
use winapi::shared::dxgi::IDXGIOutput;
use winapi::shared::dxgitype::DXGI_MODE_DESC;
... |
#[doc = "Register `SNWTCFG0` reader"]
pub struct R(crate::R<SNWTCFG0_SPEC>);
impl core::ops::Deref for R {
type Target = crate::R<SNWTCFG0_SPEC>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl From<crate::R<SNWTCFG0_SPEC>> for R {
#[inline(always)]
fn from(reader: ... |
use crate::services::{spotify::Spotify, SpotifyRef};
use futures_util::TryFutureExt;
use std::{
io::{Error, ErrorKind},
net::{IpAddr, Ipv4Addr, SocketAddr},
sync::Arc,
};
use tokio::{
io::{AsyncReadExt, AsyncWriteExt},
net::{TcpListener, TcpStream},
runtime::Runtime,
sync::RwLock,
task::... |
use super::Scheduler;
use crate::error;
use crate::World;
use std::borrow::Cow;
pub trait IntoWorkloadFn {
fn into_workload(self, name: impl Into<Cow<'static, str>>, scheduler: &mut Scheduler);
}
impl<T: for<'a> Fn(&'a World) -> Result<(), error::GetStorage> + Send + Sync + 'static>
IntoWorkloadFn for T
{
... |
use crate::object::World;
use crate::render::Camera;
pub mod cornell_box;
pub mod next_week_final_scene;
pub mod random_spheres;
pub mod random_spheres_night;
pub mod two_spheres;
pub trait SceneConfig {
fn get_camera(&self) -> Camera;
fn get_world(&self) -> World;
}
|
use std::num::NonZeroU64;
pub const MAGIC: u64 = 7;
pub fn get_int(n: u64) -> u64 {
n & 0xFF
}
pub fn sum_simple() -> u64 {
let mut sum = 0;
for i in 0..1_000_000 {
let n = get_int(i);
if n != MAGIC {
sum += n;
}
}
//assert_eq!(sum, 127466507);
sum
}
pub f... |
// Bake Image, flip Y coordinate, sense Vulkan considers TopLeft corner being 0 and
// everything else BottomLeft
use std::{
sync::Arc,
};
use vulkano::{
device::Queue,
pipeline::{ GraphicsPipeline, GraphicsPipelineAbstract },
descriptor::DescriptorSet,
sampler::Sampler,
sync::{ self, GpuFutu... |
// Copyright 2020 the Tectonic Project
// Licensed under the MIT License.
//! Tectonic document definitions.
use std::{
collections::HashMap,
env,
fmt::Write as FmtWrite,
fs,
io::{self, Read, Write},
path::{Component, Path, PathBuf},
};
use tectonic_geturl::{DefaultBackend, GetUrlBackend};
use... |
/// Receive alerts from alert manager.
// {
// "version": "3",
// "groupKey": <number> // key identifying the group of alerts (e.g. to deduplicate)
// "status": "<resolved|firing>",
// "receiver": <string>,
// "groupLabels": <object>,
// "commonLabels": <object>,
// "commonAnnotations": <object>,
// ... |
use std::{borrow::Cow, cmp::Ordering, error, fmt, io::Write, marker::PhantomData, ops::Deref};
use nimiq_hash::{Blake2bHash, HashOutput, Hasher, SerializeContent};
use serde::{
de::{Error, SeqAccess, Visitor},
ser::SerializeStruct,
Deserialize, Deserializer, Serialize, Serializer,
};
use crate::math::Ceil... |
// This file is part of Substrate.
// Copyright (C) Parity Technologies (UK) Ltd.
// SPDX-License-Identifier: Apache-2.0
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.a... |
#[macro_use]
extern crate quick_error;
pub mod browser;
pub mod reports;
pub mod twitter;
pub mod wayback;
|
//
//! Copyright 2020 Alibaba Group Holding Limited.
//!
//! 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 ... |
use std::fmt::Display;
use crate::Body;
use crate::ReprItem;
use crate::Type;
use crate::Value;
use crate::Variant;
impl<R: ReprItem> Display for Variant<R> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Variant::Unit => Ok(()),
Variant::Tup(els... |
use std::sync::{Mutex, RwLock};
use std::time::Instant;
lazy_static!{
static ref MUTEX_INSTANCE: Mutex<u32> = Mutex::new(0);
}
static mut GLOBAL_DATA: u32 = 0;
#[test]
fn benchmark_mutex() {
let now = Instant::now();
for i in 0..1_000_000 {
let mut data = MUTEX_INSTANCE.lock().unwrap();
*data += 1;
}... |
use std::net::Ipv4Addr;
use pnet::packet::ethernet::EtherType;
use pnet::util::MacAddr;
use pnet_macros_support::types::*;
/// Represents an Arp packet.
/// This implementation is not as general as the Arp protocol allows. It's specialized towards
/// Resolving Ipv4 over Ethernet, which is the most common usecase.
#... |
use chrono::Duration;
use url::Url;
use uuid::Uuid;
use serde::ser::{Serialize, Serializer, SerializeStruct};
#[derive(Debug)]
pub struct Subscription {
pub callback_url: Url,
pub topics: Vec<String>,
pub uuid: Option<Uuid>,
pub timeout: Option<Duration>,
pub max_events: Option<usize>
}
impl Seria... |
extern crate todo_server;
mod todo_api_web;
|
// An almost direct translation of VBA's armdis.cpp to Rust.
// Slightly modified to be more rusty (just expecting to do this might not have happened)
// and for more functionality (like resolving GBA Swi instructions).
use ::gba::core::memory::GbaMemory;
pub struct Opcodes {
pub mask: u32,
pub cval: u32,
pub mnemo... |
use token::Token as Token;
use common::ParseError as ParseError;
use type_name;
use type_name::TypeName as TypeName;
mod test;
#[derive(PartialEq, Clone)]
pub struct Interface {
pub out_type: TypeName,
pub in_type: Option<TypeName>,
pub repeatable: bool
}
pub struct Interfaces {
pub interfaces: Vec<B... |
#[derive(Debug)]
enum BinaryTree<T> {
Empty,
NonEmpty(Box<TreeNode<T>>),
}
#[derive(Debug)]
struct TreeNode<T> {
element: T,
left: BinaryTree<T>,
right: BinaryTree<T>,
}
fn main() {
let mut tree = BinaryTree::Empty;
tree.add(1);
tree.add(3);
tree.add(5);
tree.add(7);
tree.a... |
use std::io::*;
use std::str::FromStr;
// Quoted from https://qiita.com/penguinshunya/items/cd96803b74635aebefd6
fn input<T: FromStr>() -> T {
let mut s = String::new();
stdin().read_line(&mut s).ok();
s.trim().parse().ok().unwrap()
}
fn max(a: i64, b: i64) -> i64 {
if a > b {
return a;
}
return b;
}
... |
fn main() {
let b= bytes::Bytes::from(vec![0x31,0x32,0x33, 0x34, 0x35]);
let c= bytes::Bytes::from(&b"12345"[..]);
let d= Vec::from(&b"12345"[..]);
println!("0x{:x}", b);
println!("0x{:x}", c);
println!("{:?}", d.as_slice());
println!("{:?}", &d[..]);
}
|
use actions::AppAction;
use reducers::ReducerFn;
use structs::app::AppState;
pub fn set() -> Box<ReducerFn> {
Box::new(
|mut state: AppState, action: &AppAction| -> Result<AppState, String> {
match action {
AppAction::SetMode(mode) => {
state.json_store["mode... |
use crate::task::TaskId;
use std::{
collections::HashMap,
mem,
sync::{
mpsc::{channel, Sender},
Arc, Mutex,
},
task::Waker,
thread::{self, JoinHandle},
time::Duration,
};
#[derive(Debug)]
enum TaskState {
Ready,
NotReady(Waker),
Finished,
}
#[derive(Debug)]
enum... |
use starcoin_types::U256;
pub mod rpc;
pub mod service;
pub mod stratum;
pub use crate::rpc::gen_client::Client as StratumRpcClient;
pub use anyhow::Result;
pub fn difficulty_to_target_hex(difficulty: U256) -> String {
let target = format!("{:x}", U256::from(u64::max_value()) / difficulty);
let mut temp = "0"... |
use crate::spec::*;
#[derive(Debug, Clone, Copy)]
pub struct OpenFlags
{
pub read_only: bool,
pub truncate: bool,
pub temporal: bool,
pub integrity: TrustMode,
}
impl OpenFlags
{
pub fn create_distributed() -> OpenFlags {
OpenFlags {
read_only: false,
truncate: true... |
use std::fs::File;
use std::io::prelude::*;
use std::path::Path;
// This is the main function
fn main() {
// Statements here are executed when the compiled binary is called
let path = Path::new("day1.txt");
let display = path.display();
// Open the path in read-only mode, returns `io::Result<File>`
... |
extern crate byteorder;
use self::byteorder::{BigEndian, WriteBytesExt, ByteOrder};
use std::io::prelude::*;
use std::net::{Shutdown, TcpStream};
use std::sync::mpsc::{channel, Receiver, Sender};
use std::thread;
use std::path::Path;
use errors::Error;
use super::message_structures;
use super::streamutils;
use shared... |
use std::{error, fmt, result};
use persistent_log::Log;
use LogIndex;
use ServerId;
use Term;
/// This is a `Log` implementation that stores entries in a simple in-memory vector. Other data
/// is stored in a struct. It is chiefly intended for testing.
///
/// # Panic
///
/// No bounds checking is performed and attem... |
#[macro_use] extern crate clap;
mod libtoygrep;
fn main() {
let app = libtoygrep::create_app();
let matches = app.get_matches();
let task = libtoygrep::parse_search_task(matches);
task.run();
}
|
// Copyright 2020-2022 IOTA Stiftung
// SPDX-License-Identifier: Apache-2.0
//! Common types required by nodes and clients APIs like blocks, responses and DTOs.
#![cfg_attr(not(feature = "std"), no_std)]
#![cfg_attr(docsrs, feature(doc_cfg))]
#![deny(clippy::nursery, missing_docs, rust_2018_idioms, warnings)]
#![allo... |
use liblircd::LircdConf;
use std::fs::read_to_string;
#[test]
fn encode() {
let conf = read_to_string("../testdata/lircd_conf/thomson/ROC740.lircd.conf").unwrap();
//unsafe { lirc_log_set_stdout() };
let conf = LircdConf::parse(&conf).unwrap();
let lircd_conf: Vec<_> = conf.iter().collect();
as... |
extern crate pixelmatch;
use image::*;
use pixelmatch::*;
fn main() {
let img1 = image::open("./examples/4a.png").unwrap();
let img2 = image::open("./examples/4b.png").unwrap();
println!("{}, {}", img1.raw_pixels().len(), img2.raw_pixels().len());
let result = pixelmatch(
&img1.raw_pixels(),... |
use std::sync::Arc;
use anyhow::Result;
use minifb::{Key, Window, WindowOptions};
use parking_lot::{Condvar, Mutex};
use futures::channel::oneshot;
use crate::nes::Nes;
use crate::nes::debugger::Breakpoints;
use bobomb_grpc::grpc;
use bobomb_grpc::api_grpc;
use bobomb_grpc::grpc::ServerBuilder;
pub type ExecutorLock... |
use anyhow::Result;
use menmos_client::{Config, Profile};
use rood::cli::OutputManager;
pub fn load_or_create(cli: OutputManager) -> Result<Config> {
let mut cfg = Config::load()?;
if cfg.profiles.is_empty() {
cli.step("No config is present - Creating a default profile");
let default_profile =... |
use clap::ArgMatches;
use cparser::grammars::gen_cgrammars;
use clr1::{IToken, Parser};
use serde_json;
use std::collections::HashMap;
use std::fs::{File, OpenOptions};
use std::io::{Read, Write};
use std::process::exit;
pub fn parse_command(matches: &ArgMatches) {
let tokens = matches.value_of("tokens").unwrap();... |
//! WASM Renderer
use crate::renderer::{RendererSettings, Rendering};
mod audio;
mod texture;
mod window;
pub use audio::{AudioDevice, AudioFormatNum};
#[derive(Debug)]
pub(crate) struct Renderer {}
impl Rendering for Renderer {
fn new(settings: RendererSettings) -> crate::prelude::Result<Self> {
todo!... |
mod multiple;
#[cfg(feature = "parallel")]
mod par_multiple;
#[cfg(feature = "parallel")]
use super::IntoIterator;
use super::{
AbstractMut, CurrentId, DoubleEndedShiperator, ExactSizeShiperator, IntoAbstract, Shiperator,
};
pub use multiple::*;
#[cfg(feature = "parallel")]
pub use par_multiple::*;
|
use cancel_culture::browser::twitter::parser::{extract_description, extract_tweets, parse_gz};
use cancel_culture::wayback::Store;
use flate2::read::GzDecoder;
use std::fs::File;
use std::io::Read;
use std::path::Path;
type Void = Result<(), Box<dyn std::error::Error>>;
#[tokio::main]
async fn main() -> Void {
le... |
use super::display::Display;
use super::keyboard::Keyboard;
pub trait DisplayImpl {
fn draw(&self, screen: &Display, keys: &Keyboard);
}
pub struct AsciiDisplay();
static BLANK_SCREEN: &'static str = "\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n... |
use std::collections::BTreeMap;
#[test]
fn test_hash_map() {
let mut map = BTreeMap::new();
map.insert("iPhone", "Apple");
map.insert("Galaxy", "Samsung");
assert_eq!(vec![&"Galaxy", &"iPhone"], map.keys().collect::<Vec<_>>());
assert_eq!(vec![&"Samsung", &"Apple"], map.values().collect::<Vec<_>>()... |
// round.rs
extern crate footile;
use footile::{JoinStyle,PathBuilder,Plotter};
fn main() -> Result<(), std::io::Error> {
let path = PathBuilder::new().relative().pen_width(40.0)
.move_to(10.0, 60.0)
.line_to(50.0, 0.0)
.line_to(0.0,... |
// This file is part of Substrate.
// Copyright (C) Parity Technologies (UK) Ltd.
// SPDX-License-Identifier: Apache-2.0
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.a... |
use tree_sitter::Tree;
#[repr(C)]
struct ParseTree {
children: *mut ParseTree,
num_children: usize,
ty: *const u8,
val: *const u8,
}
fn traverse(tree: &Tree) -> ParseTree {
ParseTree {
num_children: tree.child_count(),
ty: tree.kind().as_bytes(),
}
}
fn main() {
let code =... |
fn main() {
// loop {
// println!("This is an infinite loop!");
// }
let mut num = 3;
while num != 0 {
println!("{}", num);
num = num - 1;
}
println!("GO!");
// The above approach, whilst valid, is slow because the compiler adds
// runtime code to perform the ... |
use std::collections::HashSet;
pub type Symbol<'arena> = &'arena str;
pub struct SymbolTable(HashSet<String>);
impl SymbolTable {
pub fn create(&mut self, s: String) -> Symbol<'_> {
self.0.insert(s);
self.0.get(&s).unwrap()
}
}
|
//! Represenattion of the Transaction Status API
//!
//! Transaction Status API checks the status of a B2B, B2C and C2B APIs transactions.
//!
//! test url: POST https://sandbox.safaricom.co.ke/mpesa/transactionstatus/v1/query
/// struct holding Transaction status reqest parameters
#[derive(Debug)]
pub struct Trans... |
use crate::{
bounded::{BoundedGenerator, BoundedValue},
Driver, TypeGenerator, TypeGeneratorWithParams, ValueGenerator,
};
use core::ops::{Bound, Range};
impl TypeGenerator for char {
fn generate<D: Driver>(driver: &mut D) -> Option<Self> {
driver.gen_char(Bound::Unbounded, Bound::Unbounded)
}
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.