text stringlengths 8 4.13M |
|---|
use bytes::Bytes;
use std::error::Error;
use zmq_rs::{Socket, SocketType};
use zmq_rs::{SubSocket, ZmqMessage};
#[tokio::main]
async fn main() -> Result<(), Box<dyn Error>> {
let mut socket = zmq_rs::SubSocket::connect("127.0.0.1:5556")
.await
.expect("Failed to connect");
socket.subscribe("")... |
use anyhow::Error;
use futures::StreamExt;
use std::sync::Arc;
use tokio::net::{TcpListener, TcpStream};
use tokio::sync::Mutex as AsyncMutex;
use tokio_stream::wrappers::TcpListenerStream;
use tokio_tungstenite::tungstenite::handshake::server::{Request, Response};
use tokio_tungstenite::WebSocketStream;
struct Server... |
#[doc = r" Register block"]
#[repr(C)]
pub struct RegisterBlock {
_reserved0: [u8; 16usize],
#[doc = "0x10 - Code memory page size in bytes."]
pub codepagesize: CODEPAGESIZE,
#[doc = "0x14 - Code memory size in pages."]
pub codesize: CODESIZE,
_reserved1: [u8; 16usize],
#[doc = "0x28 - Lengt... |
use std::{fmt};
use crate::{block};
extern crate prusti_contracts;
use prusti_contracts::*;
#[non_exhaustive]
#[derive(Clone, PartialEq, Eq)]
pub struct SignedHeader {
pub header: block::Header,
}
impl fmt::Debug for SignedHeader {
#[trusted]
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
... |
use std::cmp::{min, max};
use std::f64::INFINITY;
use std::mem::replace;
use {Point};
/// Agglomerative clustering, i.e., hierarchical bottum-up clustering.
///
/// How the clustering actually behaves depends on the linkage criterion, which is
/// mainly defined by the implementator and distance of two points.
pub t... |
use std::fmt::Display;
use crate::types::list::{List, ListItem};
use super::value::Value;
#[derive(Debug, Clone)]
pub struct DotPair {
pub left: Value,
pub right: Value,
}
impl Display for DotPair {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let mut buffer = String::new... |
// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT.
pub fn serialize_operation_add_tags_to_on_premises_instances(
input: &crate::input::AddTagsToOnPremisesInstancesInput,
) -> Result<smithy_http::body::SdkBody, smithy_types::Error> {
let mut out = String::new();
let mut object =... |
use lazy_static::lazy_static;
use pulldown_cmark::{html::push_html, Parser};
use std::include_str;
use web_sys::Node;
use yew::{virtual_dom::VNode, Component, ComponentLink, Html, ShouldRender};
const HELP_TEXT: &str = include_str!("help.md");
lazy_static! {
static ref HELP_HTML: String = {
let mut html_o... |
use crate::{
conn::AmConnCore,
protocol::parts::{am_rs_core::AmRsCore, TypeId},
HdbError, HdbResult, HdbValue,
};
#[cfg(feature = "async")]
use crate::protocol::util_async;
#[cfg(feature = "sync")]
use crate::protocol::util_sync;
#[cfg(feature = "sync")]
use byteorder::{LittleEndian, ReadBytesExt, WriteByt... |
#![cfg(test)]
use super::{
app::{App, AppLifeCycle, AppRunner, StandardAppTimer, SyncAppRunner},
assets::{database::AssetsDatabase, protocols::prefab::PrefabAsset},
fetch::engines::map::MapFetchEngine,
hierarchy::{hierarchy_find_world, HierarchyChangeRes, Name, Parent},
localization::Localization,
... |
use crate::{structure::*, Object, Scene};
use glam::Vec3;
pub fn ray_color(scene: &Scene, ray: Ray, obj: &Box<dyn Object>, hit: Intersection, max_bounce: u32) -> Vec3 {
let mat: Material = obj.material();
let ambient_color: Vec3 = mat.ambient_color * scene.ambient_light;
let mut lights_color = Vec3::zero... |
use crate::postgres::protocol::TypeId;
use crate::types::TypeInfo;
use std::borrow::Borrow;
use std::fmt;
use std::fmt::Display;
use std::hash::{Hash, Hasher};
use std::ops::Deref;
use std::sync::Arc;
/// Type information for a Postgres SQL type.
#[derive(Debug, Clone)]
pub struct PgTypeInfo {
pub(crate) id: Optio... |
/// An "Abstract Syntax Tree" that fairly closely resembles the structure of an AWK program. This
/// is the representation that the parser returns. A couple of basic desugaring rules are applied
/// that translate a `Prog` into a bare `Stmt`, along with its accompanying function definitions.
/// Those materials are co... |
use actix_web::web::block;
use diesel::pg::PgConnection;
use diesel::r2d2::{ConnectionManager, PooledConnection};
use serde::{Deserialize, Serialize};
use db::models::{Round, UserAnswer, UserQuestion};
use errors::Error;
#[derive(Deserialize, PartialEq, Serialize)]
pub struct GetRoundPicksResponse {
pub data: Vec... |
use P80::graph_converters::unlabeled;
use P87::*;
pub fn main() {
let g = unlabeled::from_string("[a-b, b-c, e, a-c, a-d]");
println!("{:?}", nodes_by_depth_from(&g, 'd'));
}
|
//! Maps literals and hashes of clause steps between the solver and the checker.
use varisat_formula::{Lit, Var};
use super::{ClauseHash, ProofStep};
/// Maps literals and hashes of clause steps between the solver and the checker.
#[derive(Default)]
pub struct MapStep {
lit_buf: Vec<Lit>,
hash_buf: Vec<Claus... |
mod sorted;
pub use sorted::{AssumeSorted, AssumingSortedIter, Sorted};
|
#[doc = "Reader of register RXDLADDR"]
pub type R = crate::R<u32, super::RXDLADDR>;
#[doc = "Writer for register RXDLADDR"]
pub type W = crate::W<u32, super::RXDLADDR>;
#[doc = "Register RXDLADDR `reset()`'s with value 0"]
impl crate::ResetValue for super::RXDLADDR {
type Type = u32;
#[inline(always)]
fn re... |
mod logger;
mod command;
mod cli;
pub use self::cli::CLI;
pub use self::command::Command;
|
/*
* Copyright 2020 Fluence Labs 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 by applicable law or a... |
mod utils;
use wasm_bindgen::prelude::*;
use rand::{Rng, SeedableRng};
use rand::rngs::SmallRng;
extern crate web_sys;
extern crate js_sys;
extern crate rand;
// A macro to provide `println!(..)`-style syntax for `console.log` logging.
macro_rules! log {
( $( $t:tt )* ) => {
web_sys::console::log_1(&for... |
// auto generated, do not modify.
// created: Mon Feb 22 23:57:02 2016
// src-file: /QtGui/qtextformat.h
// dst-file: /src/gui/qtextformat.rs
//
// header block begin =>
#![feature(libc)]
#![feature(core)]
#![feature(collections)]
extern crate libc;
use self::libc::*;
// <= header block end
// main block begin =>
/... |
// Copyright 2018 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 cm_json::Error;
use serde::ser::Serialize;
use serde_json::ser::{CompactFormatter, PrettyFormatter, Serializer};
use serde_json::Value;
use std::fs;
us... |
// xfail-stage1
// xfail-stage2
// xfail-stage3
io fn main() {
let port[int] po = port();
// Spawn 10 tasks each sending us back one int.
let int i = 10;
while (i > 0) {
log i;
spawn "child" child(i, chan(po));
i = i - 1;
}
// Spawned tasks are likely killed before they... |
use std::rc::Rc;
use regex_syntax::hir::{Class, HirKind, Literal, RepetitionKind, RepetitionRange};
use crate::mutators::grammar::{alternation, concatenation, literal, literal_ranges, repetition, Grammar};
#[no_coverage]
pub(crate) fn grammar_from_regex(regex: &str) -> Rc<Grammar> {
let mut parser = regex_syntax... |
//==============================================================================
// Notes
//==============================================================================
// drivers::lcd::images.rs
// LCD Drivers Mod List
//==============================================================================
// Crates and Mo... |
use super::{DisplayError, Item, Problem, Solution};
use std::fs;
use std::str::FromStr;
#[derive(Debug)]
pub struct SolutionsFromFile(pub Vec<Solution>);
impl FromStr for SolutionsFromFile {
type Err = DisplayError;
fn from_str(file_name: &str) -> Result<SolutionsFromFile, DisplayError> {
Ok(Solutions... |
use rustcommon::httpaccessor;
use tokio;
#[tokio::test]
async fn test_http_async_get() -> Result<(), String> {
let resp_wrapper_result = httpaccessor::HttpAccessor::async_get("http://www.baidu.com", 10).await;
match resp_wrapper_result {
Ok(resp) => match resp.status_code() {
200 => Ok(())... |
// Copyright 2019 The Tari Project
//
// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the
// following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following
// disclaim... |
#[doc = "Reader of register CTL"]
pub type R = crate::R<u32, super::CTL>;
#[doc = "Writer for register CTL"]
pub type W = crate::W<u32, super::CTL>;
#[doc = "Register CTL `reset()`'s with value 0"]
impl crate::ResetValue for super::CTL {
type Type = u32;
#[inline(always)]
fn reset_value() -> Self::Type {
... |
use crate::dependencies::DomainResult;
use crate::dependencies::PostDb;
use async_trait::async_trait;
use mockall::*;
use serde::Serialize;
#[derive(Serialize, Clone)]
pub struct Post {
pub id: i32,
pub title: String,
pub body: String,
pub published: bool,
}
#[automock]
#[async_trait]
... |
use winapi::shared::{
windef::HBRUSH,
minwindef::{WPARAM, LPARAM}
};
use winapi::um::{
winuser::{WS_VISIBLE, WS_TABSTOP},
wingdi::DeleteObject,
};
use winapi::um::commctrl::{TBS_AUTOTICKS, TBS_VERT, TBS_HORZ, TBS_TOP, TBS_BOTTOM, TBS_LEFT, TBS_RIGHT, TBS_NOTICKS, TBS_ENABLESELRANGE};
use crate::win32::w... |
//! Skills ページ
use yew::prelude::*;
pub struct Skills {}
impl Component for Skills {
type Message = ();
type Properties = ();
fn create(_: Self::Properties, _: ComponentLink<Self>) -> Self {
Self {}
}
fn update(&mut self, _: Self::Message) -> ShouldRender {
false
}
fn ch... |
use colors::{ERROR_COLOR, SUCCESS_COLOR, WARN_COLOR};
use serenity::model::id::ChannelId;
use std::fmt::Display;
#[macro_export]
macro_rules! chain(
($y:expr; $( $x:expr ),*) => (
{
$(
$y = $x;
)*
$y
}
);
);
#[allow(dead_code)]
pub fn report_error<D: D... |
//! Query routing simulation application.
#![warn(
missing_docs,
trivial_casts,
trivial_numeric_casts,
unused_import_braces,
unused_qualifications
)]
#![warn(clippy::all, clippy::pedantic)]
#![allow(
clippy::module_name_repetitions,
clippy::default_trait_access,
clippy::inline_always
)]
... |
use crate::tokenize::{Token, TokenKind};
use crate::{Entry, Yaml, YamlParseError};
use core::iter::{Enumerate, Iterator, Peekable};
use core::slice::Iter;
use crate::Result;
// Implementation lifted from std, as it's currently only on Nightly. It's such a simple macro that it's low risk to duplicate it here (and bett... |
// 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 ... |
use engine::{self, EngineMessage};
use transform::Transform;
use std::f32::consts::PI;
use std::fmt::{self, Debug, Formatter};
use std::marker::PhantomData;
use std::mem;
use std::ops::{Deref, DerefMut};
use std::ptr::Unique;
pub struct Camera {
data: Unique<CameraData>,
// Pretend `Camera` owns a raw pointer... |
// SPDX-License-Identifier: Apache-2.0 AND MIT
//! `Client` and `Connection` structs
use std::default::Default;
/// A [non-consuming] [Connection] builder.
///
/// [Connection]: struct.Connection.html
/// [non-consuming]: https://doc.rust-lang.org/1.0.0/style/ownership/builders.html#non-consuming-builders-(preferred):... |
mod hoge;
pub use hoge::*;
|
use rusoto_core::RusotoError;
use std::time::Duration;
use std::fmt;
use rusoto_iam::{
Iam,
ListServiceSpecificCredentialsRequest,
ListServiceSpecificCredentialsError,
ServiceSpecificCredential,
ServiceSpecificCredentialMetadata,
CreateServiceSpecificCredentialRequest,
CreateServiceSpecificC... |
use super::DataManager;
// System prototype
pub trait System {
fn name(&self) -> &'static str;
fn tick(&self, dm: &mut DataManager);
} |
use std::str::FromStr;
use std::{env, thread};
use std::time::{Duration, SystemTime};
use std::process;
use std::sync::{Arc, Mutex};
use std::sync::mpsc::{channel, Receiver};
use base64;
use getopts::Options;
use mime::Mime;
use hyper::body::HttpBody;
use hyper::{Body, Client, Method, Request};
use hyper::client::conne... |
use my_crate_denglitong;
use my_crate_denglitong::add_one;
fn main() {
let five = 5;
assert_eq!(6, add_one(five));
}
|
/* lib.rs */
pub mod riscv32_core;
pub mod riscv64_core;
pub mod riscv_csr;
pub mod riscv_csr_bitdef;
pub mod riscv_exception;
pub mod riscv32_insts;
pub mod riscv64_insts;
pub mod riscv_mmu;
pub mod riscv_tracer;
|
use crate::libc as c;
use pulse_sys as pulse;
use std::ptr;
/// A property list object.
///
/// Basically a dictionary with ASCII strings as keys and arbitrary data as values.
///
/// See [PropertyList::new].
pub struct PropertyList {
handle: ptr::NonNull<pulse::pa_proplist>,
}
impl PropertyList {
/// Constru... |
pub mod animation;
pub mod motion;
pub mod collision;
pub mod input;
pub mod hud; |
// 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 ... |
fn main() {
// The Windows crate manually injects a functions needed to implement Matrix3x2.
// This test validates this is included.
windows::core::build_legacy! {
Windows::Foundation::Numerics::Matrix3x2,
};
}
|
/*
* Given an array of integers where 1 ≤ a[i] ≤ n (n = size of array), some elements appear twice and others appear once.
*
* Find all the elements of [1, n] inclusive that do not appear in this array.
* Could you do it without extra space and in O(n) runtime? You may assume the returned list does not count as ext... |
extern crate onig;
use onig::Regex;
pub fn abbreviate(s: &str) -> String {
let re = Regex::new(r"[a-z](?=[A-Z])|-|\s+").unwrap();
re.split(s)
.map(|w| w.chars().take(1).collect::<String>().to_uppercase())
.collect()
}
|
//! Improved cross-platform clipboard library
//!
//! Fork of https://github.com/aweinstock314/rust-clipboard with better error handling
#[cfg(target_os = "windows")]
extern crate clipboard_win;
#[cfg(any(target_os = "linux", target_os = "openbsd"))]
extern crate x11_clipboard;
#[cfg(target_os = "macos")]
#[macro_use]... |
use actix_web::{http::StatusCode, HttpResponse, Json};
use bigneon_api::auth::{claims::AccessToken, claims::RefreshToken, TokenResponse};
use bigneon_api::controllers::auth;
use bigneon_api::controllers::auth::{LoginRequest, RefreshRequest};
use crypto::sha2::Sha256;
use jwt::{Header, Token};
use serde_json;
use suppor... |
// Score of Parentheses
// https://leetcode.com/explore/challenge/card/february-leetcoding-challenge-2021/587/week-4-february-22nd-february-28th/3651/
pub struct Solution;
impl Solution {
pub fn score_of_parentheses(s: String) -> i32 {
let mut stack = vec![0];
for c in s.chars() {
matc... |
use std::collections::BTreeMap;
use {Error, Result, Plist, PlistEvent, u64_option_to_usize};
pub struct Builder<T> {
stream: T,
token: Option<PlistEvent>,
}
impl<T: Iterator<Item = Result<PlistEvent>>> Builder<T> {
pub fn new(stream: T) -> Builder<T> {
Builder {
stream: stream,
... |
// See LICENSE file for copyright and license details.
use std::str::Words;
use std::str::CharSplits;
use std::from_str::FromStr;
use std::io::{BufferedReader, File};
use cgmath::{Vector3, Vector2};
use error_context;
use core::types::{MInt};
use visualizer::types::{VertexCoord, TextureCoord, Normal};
struct Face {
... |
//! Max memory allocated slice
use std::convert::{From, Into};
use std::slice;
///A slice allocated and freed using max_sys
pub struct Slice<T: 'static + Sized> {
inner: &'static mut [T],
}
impl<T> Slice<T>
where
T: 'static + Sized + Default,
{
pub fn new_with_length(len: usize) -> Self {
let inne... |
// auto generated, do not modify.
// created: Mon Feb 22 23:57:02 2016
// src-file: /QtWidgets/qgraphicslayoutitem.h
// dst-file: /src/widgets/qgraphicslayoutitem.rs
//
// header block begin =>
#![feature(libc)]
#![feature(core)]
#![feature(collections)]
extern crate libc;
use self::libc::*;
// <= header block end
... |
#![cfg(target_arch = "x86_64")]
use std::arch::x86_64::*;
use crate::detail::sse::{hi_dp, hi_dp_bc, rcp_nr1, rsqrt_nr1};
use std::ops::Neg;
/// The `branch` both a line through the origin and also the principal branch of
/// the logarithm of a rotor.
///
/// The rotor branch will be most commonly constructed by taki... |
#[doc = "Reader of register ODSR"]
pub type R = crate::R<u32, super::ODSR>;
#[doc = "Timer E Output 2 disable status\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum TE2ODS_A {
#[doc = "0: Output disabled in idle state"]
IDLE = 0,
#[doc = "1: Output disabled in fault state"]
FAUL... |
use P35::PrimeIterator;
pub fn list_primes_in_range(lower: u32, upper: u32) -> Vec<u32> {
PrimeIterator::new()
.skip_while(|&p| p < lower)
.take_while(|&p| p <= upper)
.collect()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_list_primes_in_range() {
assert_eq... |
use otp::make_totp;
use super::error::{
NotpError,
NotpResult,
};
/// A trait that defines the functionality of a OTP to implement.
///
/// Any OTP implementation should have new to initalize the secret token and
/// generate function to get the generated 6 digit code.
pub(crate) trait OTP<T> {
fn new(tok... |
use crate::config::CONFIG;
use async_redis_session::RedisSessionStore;
use diesel::{pg::PgConnection, r2d2::ConnectionManager};
use r2d2::Pool;
use std::str::FromStr;
use tracing::{debug, info, Level};
use tracing_subscriber::FmtSubscriber;
fn init_session_store() -> RedisSessionStore {
debug!("init session store ... |
// 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 agreed to ... |
#[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::PCI2C {
#[doc = r"Modifies the contents of the register"]
#[inline(always)]
pub fn modify<F>(&self, f: F)
where
for<'w> F: FnOnce(&R, &'... |
pub const CPUID_EXT_HYPERVISOR: u32 = 1 << 31;
|
use as_derive_utils::{
datastructure::{DataStructure, DataVariant, Field, FieldMap, TypeParamMap},
parse_utils::{ret_err_on, ret_err_on_peek, ParseBufferExt},
return_spanned_err, return_syn_err, spanned_err, syn_err,
utils::SynErrorExt,
};
use syn::{
parse::ParseBuffer, punctuated::Punctuated, toke... |
// 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 agreed to ... |
use crate::palette::{BaseScale, Palette};
use mottle::style::FontStyle;
use mottle::theme::Scope::*;
use mottle::theme::ThemeBuilder;
pub(crate) fn add_rules(builder: &mut ThemeBuilder, palette: &Palette) {
workspace_colors(builder, palette);
syntax_highlighting(builder, palette);
}
fn workspace_colors(builde... |
pub type IWsbApplicationAsync = *mut ::core::ffi::c_void;
pub type IWsbApplicationBackupSupport = *mut ::core::ffi::c_void;
pub type IWsbApplicationRestoreSupport = *mut ::core::ffi::c_void;
#[doc = "*Required features: `\"Win32_System_ServerBackup\"`*"]
pub const WSBAPP_ASYNC_IN_PROGRESS: ::windows_sys::core::HRESULT ... |
#[macro_use]
mod common;
use common::util::*;
static UTIL_NAME: &'static str = "cp";
static TEST_HELLO_WORLD_SOURCE: &'static str = "hello_world.txt";
static TEST_HELLO_WORLD_DEST: &'static str = "copy_of_hello_world.txt";
#[test]
fn test_cp_cp() {
let (at, mut ucmd) = testing(UTIL_NAME);
// Invoke our bina... |
use crate::prelude::*;
use std::os::raw::c_void;
use std::ptr;
#[repr(C)]
#[derive(Debug)]
pub struct VkSemaphoreCreateInfo {
pub sType: VkStructureType,
pub pNext: *const c_void,
pub flags: VkSemaphoreCreateFlagBits,
}
impl VkSemaphoreCreateInfo {
pub fn new<T>(flags: T) -> Self
where
T:... |
use core::char;
use core::fmt::{self, Write};
use uefi::status;
use uefi::text::TextInputKey;
pub struct Stdout;
impl Write for Stdout {
fn write_str(&mut self, string: &str) -> Result<(), fmt::Error> {
let uefi = unsafe { &mut *::UEFI };
for c in string.chars() {
let _ = (uefi.Consol... |
#[doc = r"Register block"]
#[repr(C)]
pub struct RegisterBlock {
#[doc = "0x00 - Provides support for rebooting the FPGA. You can select which of the four images to reboot to, just be sure to OR the image number with ``0xac``. For example, to reboot to the bootloader (image 0), write ``0xac``` to this register."]
... |
use super::*;
use std::io::Cursor;
fn test(data: &str, expected_frame_counts: &[usize]) {
let mut frame_counts = vec![];
let cursor = Cursor::new(data.as_bytes());
each_trace(cursor, |frames| {
frame_counts.push(frames.len());
});
assert_eq!(expected_frame_counts, &frame_counts[..]);
}
#[... |
use time::{format_description::FormatItem, macros::format_description, Date};
use crate::{InputValueError, InputValueResult, Scalar, ScalarType, Value};
const DATE_FORMAT: &[FormatItem<'_>] = format_description!("[year]-[month]-[day]");
/// ISO 8601 calendar date without timezone.
/// Format: %Y-%m-%d
///
/// # Exam... |
pub mod general_category;
pub mod script_values;
/// This is an ordered combination
/// of the General Category and
/// Binary Properties for checking
/// the lone unicode class escape
pub static GC_AND_BP: &[&str] = &[
"AHex",
"ASCII",
"ASCII_Hex_Digit",
"Alpha",
"Alphabetic",
"Any",
"Assi... |
/*
Project Euler Problem 3:
The prime factors of 13195 are 5, 7, 13 and 29.
What is the largest prime factor of the number 600851475143 ?
*/
fn is_prime(x: i64) -> bool {
if x == 2 || x == 3 {
return true;
} else if x % 2 == 0 || x % 3 == 0 {
return false;
}
let (mut i, mut w) = (5i... |
#[link(wasm_import_module = "wapc")]
extern {
fn __console_log(ptr: *const u8, len: usize);
fn __guest_request(op_ptr: *mut u8, ptr: *mut u8);
fn __guest_response(ptr: *const u8, len: usize);
}
#[no_mangle]
extern fn __guest_call(op_len: i32, msg_len: i32) -> i32 {
let mut op_buf = vec![0; op_len as _... |
pub mod camera;
pub mod color;
pub mod consts;
pub mod outputbuffer;
pub mod ray;
pub mod rng;
pub mod vector;
|
#[macro_use]
extern crate slog;
extern crate slog_json;
extern crate slog_term;
extern crate time;
use std::fs::File;
use slog::Drain;
#[allow(dead_code)]
struct User {
username: String,
logger: slog::Logger,
}
type Waldo = String;
type DatabaseError = String;
impl User {
fn new(username: &str, logger: ... |
//! WeakAddr example
//!
//! With a weak address you can register an client actor's addrs with a
//! service and still get cleaned up correctly when the client actor is
//! stopped. Alternatively you'd have to check if the client's mailbox
//! is still open.
use std::time::{Duration, Instant};
use actix::{prelude::*,... |
#[macro_use]
extern crate clap;
extern crate simple_logger;
extern crate toml;
#[macro_use]
extern crate log;
#[macro_use]
extern crate lazy_static;
#[macro_use]
extern crate failure_derive;
extern crate failure;
extern crate actix_web;
//extern crate futures;
#[macro_use]
mod priv_macro;
pub mod cfg;
mod cli;
mod ... |
use std::cmp;
use std::collections::HashSet;
#[allow(dead_code)]
fn length_of_longest_substring(s: String) -> i32 {
let mut char_next_indices = [0usize; 256]; // 256 ASCII chars
let mut i = 0usize;
let mut result = 0usize;
for (j, letter) in s.char_indices() {
i = cmp::max(i, char_next_indices... |
#![cfg_attr(not(feature = "std"), no_std)]
pub use self::debtpool::SDP;
use ink_lang as ink;
#[ink::contract]
mod debtpool {
#[cfg(not(feature = "ink-as-dependency"))]
use ink_storage::{
collections::HashMap as StorageHashMap,
Lazy,
};
#[cfg(not(feature = "ink-as-dependency"))]
us... |
use libc;
use libc::toupper;
use crate::clist::*;
use crate::mailimf::*;
use crate::mailimf_types::*;
use crate::mailmime_decode::*;
use crate::mailmime_disposition::*;
use crate::mailmime_types::*;
use crate::x::*;
pub const MAILMIME_COMPOSITE_TYPE_EXTENSION: libc::c_uint = 3;
pub const MAILMIME_COMPOSITE_TYPE_MULT... |
#[doc = "Reader of register DC9"]
pub type R = crate::R<u32, super::DC9>;
#[doc = "Reader of field `ADC0DC0`"]
pub type ADC0DC0_R = crate::R<bool, bool>;
#[doc = "Reader of field `ADC0DC1`"]
pub type ADC0DC1_R = crate::R<bool, bool>;
#[doc = "Reader of field `ADC0DC2`"]
pub type ADC0DC2_R = crate::R<bool, bool>;
#[doc ... |
/**
* If you use the VADER sentiment analysis tools, please cite:
* Hutto, C.J. & Gilbert, E.E. (2014). VADER: A Parsimonious Rule-based Model for
* Sentiment Analysis of Social Media Text. Eighth International Conference on
* Weblogs and Social Media (ICWSM-14). Ann Arbor, MI, June 2014.
**/
#[macro_use] extern... |
use svd::gpio;
unsafe fn write_pin_cnf(number: u8, bits: u32) {
match number {
0 => gpio().pin_cnf0.write_bits(bits),
1 => gpio().pin_cnf1.write_bits(bits),
2 => gpio().pin_cnf2.write_bits(bits),
3 => gpio().pin_cnf3.write_bits(bits),
4 => gpio().pin_cnf4.write_bits(bits),
... |
// example of trying to write a custom "safe-get" trait on Vec
trait SafeGetter<T> {
fn safe_get(&self, index: i32) -> Option<&T>;
}
impl <T> SafeGetter<T> for Vec<T> {
fn safe_get(&self, index: i32) -> Option<&T> {
if index < 0 {
None
} else {
self.get(index as usize)
... |
// 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... |
use megadrile::{commands, config, error::Error};
fn evaluate_args() -> megadrile::Result<()> {
let arg_matches = config::get_cli_config();
if let (sub_name, Some(sub_matches)) = arg_matches.subcommand() {
match sub_name {
config::SUB_COMMAND_NAME_COUNTS => commands::print_counts(sub_matches... |
mod dependencies;
mod post;
pub use dependencies::*;
pub use post::*;
|
//! embedded-gui
//! ============
//!
//! `embedded-gui` is an experimental `no_std`, `no_alloc`, cross-platform, composable Rust GUI
//! toolkit.
//!
//! `embedded-gui` consists of two parts: the main crate, and a platform-specific backend.
//! The main crate contains layout containers, composable base widgets, and th... |
pub const PIXEL_SIZE: f64 = 20.0;
#[derive(Clone)]
pub struct Pixel {
pub x_cord: i32,
pub y_cord: i32,
}
pub fn i32_to_f64(number: i32) -> f64 {
(number as f64) * PIXEL_SIZE
}
pub fn i32_to_u32(number: i32) -> u32 {
i32_to_f64(number) as u32
}
|
#[test]
fn fold_consumer_test() {
let str_col = [
"This ",
"text ",
"should ",
"be ",
"all ",
"together ",
":/",
];
let text = str_col.iter().fold(String::new(), |mut s, &w| {
s.push_str(w);
s
});
assert_eq!(text, "This text sh... |
#![feature(test)]
extern crate peg_syntax_ext;
use peg_syntax_ext::peg_file;
extern crate test;
use test::Bencher;
peg_file!(parser("json.rustpeg"));
#[bench]
fn json(b: &mut Bencher) {
let bench_str = r#"
{
"X": 0.6e2,
"Y": 5,
"Z": -5.312344,
"Bool": false,
"Bool": true,
"Null": null,
"Attr": {
"Name": "... |
extern crate jlib;
use jlib::api::message::amount::Amount;
use jlib::api::create_offer::api::CreateOffer;
use jlib::api::create_offer::data::{OfferType, OfferCreateTxResponse, OfferCreateSideKick};
use jlib::api::config::Config;
pub static TEST_SERVER: &'static str = "ws://101.200.176.249:5040"; //dev12 国密服务器
fn mai... |
/*!
This document describes what changes are valid/invalid for a library using `abi_stable`,
Note that all of these only applies to types that implement `StableAbi`,
and are checked when loading the dynamic libraries using
the functions in `abi_stable::library::RootModule`.
Those dynamic libraries use the [`export_ro... |
use ::std::fmt;
use ::std::fmt::Display;
use ::rand::{thread_rng, Rng, sample};
use std::collections::{HashMap, HashSet};
lazy_static!{
// Create a HashMap of each fence edge that correlates the surrounding
// fences. By checking if both ends of a fence are occupied, we can
// guarentee we have a fence tha... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.