text stringlengths 8 4.13M |
|---|
use std::path;
use crate::hash::Hash;
mod id;
mod snapshot;
mod builder;
mod file;
mod location;
#[derive(Debug, Clone, Eq, Hash)]
pub enum SnapshotId {
Located(Hash, SnapshotLocation), // Snapshot is not loaded but we know its location
NotLocated(Hash), // Snapshot supposedly exists and is r... |
pub struct Decay {
max_diff: f32,
prev: f32,
}
impl Decay {
pub fn new(max_diff: f32) -> Self {
Self {
max_diff,
prev: 0.0,
}
}
/// Decays sound volume smoothly if it drops to fast
///
/// Used to reduce pops from the triangle channel
pub fn deca... |
use std::option::Option;
use crate::scanning::TokenType;
use crate::scanning::Token;
#[derive(Debug)]
pub enum Expr {
BINARY(Binary),
GROUPING(Grouping),
LITERAL(Literal),
LOGICAL(Logical),
UNARY(Unary),
VARIABLE(Variable),
ASSIGNMENT(Assignment),
CALL(Call)
}
#[derive(Debug)]
pub str... |
/*
*MIT License
*
*Copyright (c) 2020 Hajime Nakagami
*
*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 limitation the rights
*to use, copy, modify, merge,... |
use std::error::Error;
use std::fmt;
use std::string::ToString;
use serde::de::{self, Deserialize, Deserializer, Visitor};
use serde::{Serialize, Serializer};
use crypto::PublicKey;
use encoding;
use encoding::{CheckedOffset, Field, Offset};
use storage::StorageKey;
use uuid;
use uuid::Uuid;
pub const ASSET_ID_LEN: ... |
#[doc = "Register `WRP2BR` reader"]
pub type R = crate::R<WRP2BR_SPEC>;
#[doc = "Register `WRP2BR` writer"]
pub type W = crate::W<WRP2BR_SPEC>;
#[doc = "Field `WRP2B_PSTRT` reader - WRP2B_PSTRT"]
pub type WRP2B_PSTRT_R = crate::FieldReader;
#[doc = "Field `WRP2B_PSTRT` writer - WRP2B_PSTRT"]
pub type WRP2B_PSTRT_W<'a, ... |
pub fn new_database() {
println!("New database");
unimplemented!();
}
pub fn check_all_artists() {
println!("Check all artists");
unimplemented!();
}
pub fn check_single_artist() {
println!("Check single artist");
unimplemented!();
}
pub fn print_missing_releases() {
println!("Print missing releases");
unimp... |
use std::collections::HashSet;
use sdl2::{render::*, video::*, event::*, keyboard::*, *};
use wolf::world_map::get_world_map;
#[derive(Debug, PartialEq, Clone)]
struct Point<T> {
x: T,
y: T,
}
#[derive(Debug, PartialEq, Clone)]
struct Player {
facing: Point<f64>,
position: Point<f64>,
camera: Poi... |
use std::io;
use my_library::university::department;
fn main() {
println!("Enter your university department");
let mut depart_name = String::new();
io::stdin().read_line(&mut depart_name).expect("failed to get input");
department::show_depart_name(&depart_name);
}
|
pub const WORDLIST: &'static [&'static str] = &[
"abaular",
"abdominal",
"abeto",
"abissinio",
"abjeto",
"ablucao",
"abnegar",
"abotoar",
"abrutalhar",
"absurdo",
"abutre",
"acautelar",
"accessorios",
"acetona",
"achocolatado",
"acirrar",
"acne",
"... |
use sdl2::rect::Rect;
use crate::momentum::Momentum;
#[derive(Copy, Clone)]
pub struct Ball {
pub pos_x: u32,
pub pos_y: u32,
pub heigth: u32,
pub width: u32,
pub momentum: Momentum,
}
impl Ball {
pub fn new(pos_x: u32, pos_y: u32) -> Ball {
Ball {
pos_x: pos_x,
... |
use directories::ProjectDirs;
use std::fs;
use std::io::Error;
use std::path::Path;
fn main() -> Result<(), Error> {
if std::env::var("DOCS_RS").is_ok() {
return Ok(());
}
if let Some(proj_dirs) = ProjectDirs::from("", "", "Cubes") {
let dir = proj_dirs.data_dir();
let path = dir.... |
use super::Frame;
use crate::utils;
use crate::utils::{generate_uuid, Claims};
use actix_web::{error, web, HttpRequest, HttpResponse};
use serde::{Deserialize, Serialize};
use std::borrow::Borrow;
use std::convert::TryFrom;
//#region Event
#[derive(Debug, Serialize, Clone)]
#[serde(rename_all = "camelCase")]
pub stru... |
#[macro_use]
extern crate serde_derive;
extern crate image;
extern crate sheep;
mod format;
pub use format::{SerializedSpriteSheet, SpritePosition, TwentyFormat};
|
fn main() {
let s = String::from("hello"); // can not be mutated
let mut s = String::from("hello"); // can be mutated
s.push_str(", world!"); // push_str() appends a literal to a String
println!("{}", s); // this will print `hello, world!`
}
|
//! Invalid state transition proof
//!
//! This module provides the feature of generating and verifying the execution proof used in
//! the Subspace fraud proof mechanism. The execution is more fine-grained than the entire
//! block execution, block execution hooks (`initialize_block` and `finalize_block`) and any
//! ... |
#![no_std]
#![no_main]
#![feature(alloc_error_handler)]
extern crate embedded_hal;
extern crate stellaris_launchpad;
extern crate tm4c123x_hal;
use core::alloc::Layout;
use embedded_hal::blocking::delay::DelayMs;
use embedded_hal::digital::v2::OutputPin;
use stellaris_launchpad::board;
#[no_mangle]
pub fn stellaris_... |
use anyhow::Result;
use fern::colors::{Color, ColoredLevelConfig};
use log::{info, LevelFilter};
use std::str::FromStr;
pub fn setup_logger(log_level: &str) -> Result<()> {
let loglevel = LevelFilter::from_str(log_level).unwrap_or_else(|err| {
eprintln!("Error parsing log_level: {}", err);
LevelFil... |
use std::fs::File;
use std::io::{BufRead, BufReader};
use std::ops::Range;
use std::path::Path;
pub(crate) fn cited_error(message: &str, range: Range<(usize, usize)>, path: impl AsRef<Path>) {
let path_str = path.as_ref().display();
let Range {
start: (line, col),
end: (end_line, mut end_col),
... |
use std::fmt::Debug;
#[derive(Clone, Eq, Hash, PartialEq, Debug)]
pub struct NodeMap<C> {
pub width: usize,
pub height: usize,
grid: Vec<C>,
}
impl<C> NodeMap<C> {
pub fn from_vec(width: usize, height: usize, values: Vec<C>) -> Self {
assert_eq!(
width * height,
values.... |
#[doc = "Register `CRRCR` reader"]
pub type R = crate::R<CRRCR_SPEC>;
#[doc = "Register `CRRCR` writer"]
pub type W = crate::W<CRRCR_SPEC>;
#[doc = "Field `HSI48ON` reader - HSI48 clock enable"]
pub type HSI48ON_R = crate::BitReader<HSI48ON_A>;
#[doc = "HSI48 clock enable\n\nValue on reset: 0"]
#[derive(Clone, Copy, De... |
use petshop::animals::Animal;
use petshop::pets::cat::Cat;
use petshop::pets::dog::Dog;
fn main() {
let mut pet_vec: Vec<Box<dyn Animal>> =
vec![Box::new(Dog::default()), Box::new(Cat::default())];
for pet in pet_vec.iter_mut() {
println!("{}", pet);
println!("{}", pet.species());
... |
use std::sync::Arc;
pub struct Cid {
id: usize,
ids: Arc<Ids>,
}
impl Cid {
pub fn new(id: usize, ids: Arc<Ids>) -> Self {
Cid { id, ids }
}
#[inline(always)]
pub fn id(&self) -> usize {
self.id
}
}
impl Drop for Cid {
fn drop(&mut self) {
self.ids.release(self.... |
use chrono::{DateTime, Local};
use punch_clock::Period;
use structopt::StructOpt;
#[derive(Debug, StructOpt)]
#[structopt(name = "punch", about = "Lightweight time-tracking utility.")]
pub enum Opt {
/// Start tracking time.
In {
/// The time to start the tracking period from (default: now). Currently ... |
mod utils;
use std::io;
use std::path::Path;
use std::fs;
use wasm_bindgen::prelude::*;
use web_sys::console;
// When the `wee_alloc` feature is enabled, use `wee_alloc` as the global
// allocator.
#[cfg(feature = "wee_alloc")]
#[global_allocator]
static ALLOC: wee_alloc::WeeAlloc = wee_alloc::WeeAlloc::INIT;
#[wasm... |
extern crate cursive;
use std::sync::mpsc;
use std::thread;
use std::time::Duration;
use cursive::Cursive;
use cursive::printer::Printer;
use cursive::view::{View, FullView};
fn main() {
// As usual, create the Cursive root
let mut siv = Cursive::new();
// We want to refresh the page even when no input ... |
#[doc = r"Register block"]
#[repr(C)]
pub struct RegisterBlock {
#[doc = "0x00 - control register"]
pub cr: CR,
#[doc = "0x04 - status register"]
pub sr: SR,
#[doc = "0x08 - data input register"]
pub din: DIN,
#[doc = "0x0c - data output register"]
pub dout: DOUT,
#[doc = "0x10 - DMA... |
#![doc = "generated by AutoRust 0.1.0"]
#![allow(unused_mut)]
#![allow(unused_variables)]
#![allow(unused_imports)]
use crate::models::*;
use reqwest::StatusCode;
use snafu::{ResultExt, Snafu};
pub mod views {
use crate::models::*;
use reqwest::StatusCode;
use snafu::{ResultExt, Snafu};
pub async fn lis... |
#[macro_use]
pub mod mlvalues;
#[macro_use]
pub mod memory;
pub mod alloc;
#[macro_use]
pub mod callback;
pub mod bigarray;
pub mod fail;
pub mod state;
pub use self::mlvalues::Value;
|
// Copyright (c) Facebook, Inc. and its affiliates.
//
// This source code is licensed under the MIT license found in the
// LICENSE file in the "hack" directory of this source tree.
#![recursion_limit = "128"]
use proc_macro2::TokenStream;
use quote::quote;
use syn::Attribute;
use syn::Meta;
use syn::NestedMeta;
use... |
use crypto::{PublicKey, Signature};
use assets::AssetBundle;
use transactions::components::service::SERVICE_ID;
use error::{Error, ErrorKind};
/// Transaction ID.
pub const EXCHANGE_ID: u16 = 601;
evo_encoding_struct! {
struct ExchangeOffer {
sender: &PublicKey,
sender_assets: Vec<A... |
fn naive(x: &[u8], y: &[u8]) -> u64 {
assert_eq!(x.len(), y.len());
x.iter().zip(y).fold(0, |a, (b, c)| a + (*b ^ *c).count_ones() as u64)
}
#[derive(Debug, PartialEq, Eq, Ord, PartialOrd, Hash, Clone)]
pub struct DistanceError {
_x: ()
}
/// Computes the bitwise [Hamming
/// distance](https://en.wikipedi... |
/**********************************************************\
| |
| hprose |
| |
| Official WebSite: http://www.hprose.com/ |
| ... |
use std::env;
mod utils; // make other module available in this space
use utils::*; // "globe" operator = import *
use sqlx::postgres::PgPoolOptions;
use anyhow::Result; // simplified Error handling, so that we do not have to specify EXACT error type for each result returning function
use rand::thread_rng;
use rand:... |
#[macro_use]
extern crate diesel;
mod server;
mod storage;
mod configuration;
use std::env;
use std::thread;
use backuplib::grpc::ServerBuilder;
use backuplib::rpc::BaacupServer;
use server::BaacupImpl;
const VERSION: &'static str = env!("CARGO_PKG_VERSION");
fn main() {
backuplib::print_hello();
println!... |
// If we use GEPi rathern than GEP_tup_like when
// storing closure data (as we used to do), the u64 would
// overwrite the u16.
type pair<A,B> = {
a: A, b: B
};
fn f<A:copy>(a: A, b: u16) -> fn@() -> (A, u16) {
fn@() -> (A, u16) { (a, b) }
}
fn main() {
let (a, b) = f(22_u64, 44u16)();
#debug["a=%? ... |
// Copyright 2020 The VectorDB Authors.
//
// Code is licensed under Apache License, Version 2.0.
use crate::errors::Error;
use crate::parsers::{Select, Tokens, IAST};
#[derive(Debug)]
pub struct Explain {
pub name: String,
pub select: Select,
}
impl Explain {
pub fn default() -> Self {
Explain {... |
#[macro_use]
extern crate lazy_static;
extern crate wars_8_api;
use wars_8_api::gfx::*;
use wars_8_api::input::*;
use std::sync::Mutex;
pub enum Pride {
Lgbt,
Trans,
Bi,
}
lazy_static! {
static ref STATE: Mutex<Pride> = Mutex::new(Pride::Lgbt);
}
#[no_mangle]
pub fn _init() {
printh("[WARS-8-Pri... |
//! StarkNet node JSON-RPC related modules.
pub mod api;
pub mod serde;
#[cfg(test)]
pub mod test_client;
#[cfg(test)]
pub mod test_setup;
pub mod types;
use crate::{
core::{
BlockId, CallSignatureElem, ClassHash, ConstructorParam, ContractAddress,
ContractAddressSalt, Fee, StarknetTransactionHash,... |
use std::fmt::Write;
use std::sync::Arc;
use axum::extract;
use hyper::{Body, Response};
use tracing::error;
use super::AppContext;
pub async fn list_scopes(ctx: extract::Extension<Arc<dyn AppContext>>) -> Response<Body> {
match ctx.get_conn().await {
Err(e) => Response::builder()
.status(500... |
use crate::prelude::*;
#[derive(Debug, Clone)]
pub enum InputTermRec<Rec, Type> {
TmUnit,
TmVar(String),
TmAbs(String, Type, Rec),
TmApp(Rec, Rec),
TmTyAbs(String, Rec),
TmTyApp(Rec, Type),
}
pub use InputTermRec::*;
#[derive(Debug, Clone)]
pub struct InputTerm(pub InputTermRec<Box<InputTerm>... |
#[doc = "Register `CR2` reader"]
pub type R = crate::R<CR2_SPEC>;
#[doc = "Register `CR2` writer"]
pub type W = crate::W<CR2_SPEC>;
#[doc = "Field `FREQ` reader - Peripheral clock frequency"]
pub type FREQ_R = crate::FieldReader;
#[doc = "Field `FREQ` writer - Peripheral clock frequency"]
pub type FREQ_W<'a, REG, const... |
use crate::{Rectangle, Size};
use euclid::{point2, vec2};
#[cfg(test)]
use euclid::size2;
use std::num::Wrapping;
const LARGE_BUCKET: usize = 2;
const MEDIUM_BUCKET: usize = 1;
const SMALL_BUCKET: usize = 0;
const NUM_BUCKETS: usize = 3;
fn free_list_for_size(small_threshold: i32, large_threshold: i32, size: &Size) ... |
use std::collections::HashMap;
type MaxPair = (i32, char);
struct Solution {
}
impl Solution {
fn longest_length_of_string(s: String) -> i32 {
let mut record_map = HashMap::new();
let mut max_pair: MaxPair = (0, ' ');
let mut idx = 0;
for x in s.chars() {
idx += 1;
... |
/*
* Datadog API V1 Collection
*
* Collection of all Datadog Public endpoints.
*
* The version of the OpenAPI document: 1.0
* Contact: support@datadoghq.com
* Generated by: https://openapi-generator.tech
*/
/// AwsLogsListResponse : A list of all Datadog-AWS logs integrations available in your Datadog organiza... |
#[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::DMACFG {
#[doc = r" Modifies the contents of the register"]
#[inline]
pub fn modify<F>(&self, f: F)
where
for<'w> F: FnOnce(&R, &'w mu... |
#![doc = "generated by AutoRust 0.1.0"]
#![allow(non_camel_case_types)]
#![allow(unused_imports)]
use serde::{Deserialize, Serialize};
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct AvailableProviderOperation {
pub name: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
... |
// std imports {{{
use std::borrow::Borrow;
use std::process::Command;
use std::path::PathBuf;
// }}}
// 3rd party imports {{{
use reqwest::{
Client,
Url,
};
use serde_derive::Deserialize;
// }}}
// Own imports {{{
use crate::config::Config;
use crate::error::Error;
// }}}
// AUR package definition {{{
/// ... |
pub mod dm;
pub mod fsr;
mod tree; |
use crate::Error;
use azure_core::{TokenCredential, TokenResponse};
use const_format::formatcp;
use url::Url;
pub(crate) const API_VERSION: &str = "7.0";
pub(crate) const API_VERSION_PARAM: &str = formatcp!("api-version={}", API_VERSION);
/// Client for Key Vault operations - getting a secret, listing secrets, etc.
/... |
use apllodb_shared_components::{
BooleanExpression, ComparisonFunction, Expression, LogicalFunction,
};
use serde::{Deserialize, Serialize};
use crate::TableName;
/// WHERE condition for a single table.
/// Has Expression inside whose SchemaIndexVariant's , if any, refer only to the specified table.
#[derive(Clon... |
fn main() {
use std::io::{self, BufRead};
use std::collections::HashMap;
let stdin = io::stdin();
let mut guards = HashMap::new();
let mut gid = 0;
let mut sleep = 0;
for line in stdin.lock().lines() {
let sep = ['[', '-', ' ', ':', ']'];
let line = line.unwrap();
... |
#![deny(deprecated)]
use pyo3::prelude::*;
#[pyclass]
#[text_signature = "()"]
struct TestClass {
num: u32,
}
#[pymethods]
impl TestClass {
#[classattr]
#[name = "num"]
const DEPRECATED_NAME_CONSTANT: i32 = 0;
#[name = "num"]
#[text_signature = "()"]
fn deprecated_name_pymethod(&self) { ... |
#![allow(non_snake_case)]
/*
extern crate nanomsg;
use std::io::Read;
use nanomsg::{Socket, Protocol, Error};
/// Creating a new `Pull` socket type. Pull sockets can only receive messages
/// from a `Push` socket type.
fn create_socket() -> Result<(), Error> {
let mut socket = try!(Socket::new(Protocol::Pull));
... |
pub struct Solution {}
/// LeetCode Monthly Challenge problem for February 23rd, 2021.
impl Solution {
/// Searches an M x N matrix for a target value. Returns true if the value
/// is found, and false if not.
///
/// # Arguments
/// * matrix - An M x N vector of i32 vectors.
/// * target - Th... |
use query::Weight;
use query::Scorer;
use schema::Term;
use schema::IndexRecordOption;
use core::SegmentReader;
use super::PhraseScorer;
use query::EmptyScorer;
use Result;
pub struct PhraseWeight {
phrase_terms: Vec<Term>,
}
impl PhraseWeight {
/// Creates a new phrase weight.
///
/// Right now `scor... |
#[doc = "Register `IOGCSR` reader"]
pub type R = crate::R<IOGCSR_SPEC>;
#[doc = "Register `IOGCSR` writer"]
pub type W = crate::W<IOGCSR_SPEC>;
#[doc = "Field `G1E` reader - Analog I/O group x enable"]
pub type G1E_R = crate::BitReader;
#[doc = "Field `G1E` writer - Analog I/O group x enable"]
pub type G1E_W<'a, REG, c... |
extern crate reqwest;
mod api;
use api::{summarize_jobs, Job, PipelineSummary};
use reqwest::Url;
use structopt::StructOpt;
use tabular::{Row, Table};
#[derive(Debug, StructOpt)]
#[structopt(about)]
struct Cli {
#[structopt(short, long, default_value = "gitlab.com")]
hostname: String,
#[structopt(short =... |
use criterion::{black_box, criterion_group, criterion_main, Criterion};
fn criterion_benchmark(c: &mut Criterion) {
let list = publicsuffix::List::fetch().unwrap();
c.bench_function("bench raw.github.com", |b| {
b.iter(|| list.parse_domain(black_box("raw.github.com")).unwrap())
});
c.bench_func... |
#![cfg_attr(feature = "clippy", feature(plugin))]
#![cfg_attr(feature = "clippy", plugin(clippy))]
extern crate libc;
extern crate nix;
pub use errors::*;
pub use privdrop::*;
mod errors;
mod privdrop;
|
use std::io::Error as IoError;
use hyper::Error as HyperError;
use storage::util::DeviceId;
#[derive(Debug)]
pub enum StorageError {
Io(IoError),
Hyper(HyperError),
NoUnitOnDev(DeviceId),
MissingMaster,
InvalidPathUnicode
}
pub type StorageResult<T> = Result<T, StorageError>;
|
#![warn(clippy::all)]
#![allow(dead_code)]
#[macro_use]
extern crate log;
use bytes::{Buf, BytesMut};
use std::future::Future;
use std::io::Cursor;
use std::sync::{Arc, Mutex};
pub(crate) use tokio_io::{AsyncRead, AsyncReadExt, AsyncWrite, AsyncWriteExt};
mod body;
mod chunked;
mod conf;
mod conn;
mod error;
mod ht... |
use core::ptr::Unique;
use spin::Mutex;
use core::fmt;
pub mod pl011;
pub use self::pl011::PL011;
pub mod uart16650;
pub use self::uart16650::Uart16650;
// can't do lazy_static because no std
// so we create the struct manually
// thankfully setup's been done for us by uboot...
pub static STDOUT: Mutex<Uart16650> = ... |
use crate::{get_result, get_result_i64};
use std::collections::HashMap;
// https://adventofcode.com/2020/day/10
// https://www.reddit.com/r/rust/comments/ka9nre/advent_of_code_2020_day_10/
const INPUT_FILENAME: &str = "inputs/input10";
pub fn solve() {
get_result(1, part01, INPUT_FILENAME);
get_result_i64(2,... |
use core::{
fmt::Debug,
hash::Hash,
ops::{Add, Range as OpsRange},
};
pub trait Unit:
Debug + Copy + Clone + Eq + Ord + Hash + Send + Sync + Add<Self, Output = Self> + Send + Sync
{
}
macro_rules! impl_unit {
($($t:ty),*) => {
$(impl Unit for $t {})*
}
}
impl_unit! {u32, u64, u128}
pub... |
#[doc = "Register `CR3` reader"]
pub type R = crate::R<CR3_SPEC>;
#[doc = "Register `CR3` writer"]
pub type W = crate::W<CR3_SPEC>;
#[doc = "Field `EIE` reader - Error interrupt enable"]
pub type EIE_R = crate::BitReader<EIE_A>;
#[doc = "Error interrupt enable\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, Partial... |
/*
SPDX-License-Identifier: Apache-2.0 OR MIT
Copyright 2020 The arboard contributors
The project to which this file belongs is licensed under either of
the Apache 2.0 or the MIT license at the licensee's choice. The terms
and conditions of the chosen license apply to this file.
*/
use std::borrow::Cow;
use thiserro... |
#![doc = "generated by AutoRust 0.1.0"]
#![allow(non_camel_case_types)]
#![allow(unused_imports)]
use serde::{Deserialize, Serialize};
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct RoleAssignmentMetricsResult {
#[serde(rename = "subscriptionId", default, skip_serializing_if = "Option::is_non... |
use crate::relayer::Relayer;
use ckb_error::{Error, ErrorKind, InternalError, InternalErrorKind};
use ckb_logger::debug_target;
use ckb_network::{CKBProtocolContext, PeerIndex};
use ckb_types::{
core::{Cycle, TransactionView},
packed,
prelude::*,
};
use ckb_util::LinkedHashSet;
use ckb_verification::cache::... |
#![doc = "generated by AutoRust 0.1.0"]
#![allow(non_camel_case_types)]
#![allow(unused_imports)]
use serde::{Deserialize, Serialize};
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct JobCollectionListResult {
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub value: Vec<JobCollec... |
extern crate aoc_runner;
#[macro_use]
extern crate aoc_runner_derive;
pub mod day1;
aoc_lib!{ year = 2019 }
|
mod config;
mod register;
mod predator;
pub use self::predator::PredatorSpecial;
pub use self::register::register;
|
fn main() {
{
let mut s = String::new();
let mut s2 = String::from("你好");
let mut s3 = "hello world".to_string();
s.push('A');
s2.push_str("!!!");
s3.push_str("!!!");
println!("s: {}", s);
println!("s2: {}", s2);
println!("s3: {}", s3);
... |
use syn::{
braced,
parse::{Parse, ParseStream, Result},
Ident, Token, Visibility,
};
pub mod component;
pub mod query;
pub mod system;
pub mod task;
pub mod unique;
use component::Component;
use query::Query;
use system::System;
use task::Task;
use unique::Unique;
mod kw {
syn::custom_keyword!(world)... |
struct Solution;
/// https://leetcode.com/problems/plus-one/
impl Solution {
/// 0 ms 2 MB
pub fn plus_one(digits: Vec<i32>) -> Vec<i32> {
let mut result = Vec::with_capacity(digits.len() + 1);
let mut carry = 1;
for x in digits.iter().rev() {
let sum = x + carry;
... |
use anyhow::{format_err, Error};
use derive_more::Into;
use serde::{Deserialize, Serialize};
use std::{
convert::TryFrom,
ops::Deref,
path::{Path, PathBuf},
sync::Arc,
};
use url::Url;
use stack_string::StackString;
#[derive(Default, Debug, Deserialize)]
pub struct ConfigInner {
pub database_url: ... |
use std::{time::{Duration, Instant}, thread::sleep};
use winit::{
event::{Event, WindowEvent},
event_loop::{ControlFlow, EventLoop},
};
use super::init_logging;
use super::asset::{Asset, Resources};
use super::renderer::{RenderPass, RenderContext, RenderLoader, RenderLoop};
use super::input::{InputSystem, Inp... |
use std::fmt::Debug;
#[derive(Debug)]
struct Rectangle {length:f64, width:f64}
#[derive(Debug)]
struct Triangle {length:f64, width:f64}
trait HasArea {
fn area(&self) -> f64;
}
impl HasArea for Rectangle {
fn area(&self) -> f64 {self.length * self.width}
}
impl HasArea for Triangle {
fn area(&self) -> f... |
type Link<T> = Option<Box<Node<T>>>;
#[derive(Debug)]
struct Node<T: Ord> {
val: T,
left: Link<T>,
right: Link<T>,
}
#[derive(Debug)]
pub struct BST<T: Ord> {
root: Link<T>,
}
impl<T: Ord> BST<T> {
pub fn new() -> Self {
BST { root: None }
}
}
impl<T: Ord> BST<T> {
pub fn insert(... |
pub struct Config {}
|
#[doc = "Register `PLL1` reader"]
pub type R = crate::R<PLL1_SPEC>;
#[doc = "Register `PLL1` writer"]
pub type W = crate::W<PLL1_SPEC>;
#[doc = "Field `PLL1EN` reader - Enable the PLL1 inside PHY"]
pub type PLL1EN_R = crate::BitReader;
#[doc = "Field `PLL1EN` writer - Enable the PLL1 inside PHY"]
pub type PLL1EN_W<'a, ... |
fn inline_script(s: &str) -> String {
format!(r#"<script type="text/javascript">{}</script>"#, s)
}
fn inline_style(s: &str) -> String {
format!(r#"<style type="text/css">{}</style>"#, s)
}
pub fn get_html() -> String {
format!(
r#"
<!doctype html>
<html>
<head>
... |
/*!
```rudra-poc
[target]
crate = "failure"
version = "0.1.8"
[report]
issue_url = "https://github.com/rust-lang-nursery/failure/issues/336"
issue_date = 2019-11-13
rustsec_url = "https://github.com/RustSec/advisory-db/pull/318"
rustsec_id = "RUSTSEC-2019-0036"
[[bugs]]
analyzer = "Manual"
bug_class = "Other"
rudra_r... |
pub fn square(s: u32) -> u64 {
if s == 0 || s > 64 {
panic!("Square must be between 1 and 64")
}
2u64.pow(s - 1)
}
pub fn total() -> u64 {
// (1..65).fold(0, |acc, x| acc + square(x))
// Sum is equal to 2^65 - 1 which results in overflow so we subtract 1 from the 2^64 and add it to 2^64
// Which is the... |
#[doc = "Register `ADC_IER` reader"]
pub type R = crate::R<ADC_IER_SPEC>;
#[doc = "Register `ADC_IER` writer"]
pub type W = crate::W<ADC_IER_SPEC>;
#[doc = "Field `ADRDYIE` reader - ADRDYIE"]
pub type ADRDYIE_R = crate::BitReader;
#[doc = "Field `ADRDYIE` writer - ADRDYIE"]
pub type ADRDYIE_W<'a, REG, const O: u8> = cr... |
//! Note: Most of the documentation is taken from
//! rusts hashmap.rs and should be considered under
//! their copyright.
use super::*;
use core::hash::{Hash, Hasher};
use core::mem;
// use std::fmt::{self, Debug};
/////// General
/// A view into a single entry in a map, which may either be vacant or occupied.
///... |
//Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be:
//
//1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
//
//By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued term... |
use euler::utils::is_prime;
fn main() {
let mut ans = 1;
let mut count = 0;
while count != 10001 {
ans += 1;
if is_prime(ans) {
count += 1;
}
}
println!("{}", ans);
}
|
//! Representation of implications in which the presence of one LV2 feature, property, etc. can
//! imply the presence of others.
// TODO: Explore possibility of generating some of the information in this module automatically at
// build time, maybe using macros and/or RDF?
use enum_map::EnumMap;
use rayon::iter::Fro... |
// Copyright (c) The Diem Core Contributors
// SPDX-License-Identifier: Apache-2.0
use serde::{Deserialize, Serialize};
use serde_json::Value;
use serde_with::{serde_as, DisplayFromStr};
use std::convert::From;
use warp::reject::Reject;
#[serde_as]
#[derive(Clone, Debug, Deserialize, Serialize, PartialEq)]
pub struct... |
#![feature(exclusive_range_pattern)]
#![feature(trace_macros)]
#[macro_use]
extern crate num_derive;
use self::TraceMode::*;
use num::traits::AsPrimitive;
use num_traits::FromPrimitive;
use std::convert::TryInto;
use std::fmt;
use quark::BitIndex;
use quark::BitMask;
use quark::Signs;
use num::{PrimInt, Unsigned};
... |
use axum::{routing::get, Json, Router};
use axum_prometheus::PrometheusMetricLayer;
use serde::{Deserialize, Serialize};
#[derive(Serialize, Deserialize)]
struct Device {
uuid: String,
mac: String,
firmware: String,
}
#[tokio::main]
async fn main() {
let (prometheus_layer, metric_handle) = PrometheusM... |
use warp::Filter;
#[tokio::main]
async fn main() {
let static_files = warp::get().and(warp::fs::dir("/static"));
let main = warp::get()
.and(warp::path::end())
.and(warp::fs::file("/static/index.html"));
let routes = main.or(static_files);
println!("Serving static files on port 3000");
... |
use actix_web::{web, FromRequest, HttpRequest, HttpResponse};
use serde::Deserialize;
use std::sync::Arc;
use super::super::app::AppEnvironment;
use super::super::wxwork_robot::command_runtime;
use super::super::wxwork_robot::message;
#[derive(Deserialize)]
pub struct WxWorkRobotVerifyMessage {
msg_signature: Str... |
use bson::Document;
use futures_util::FutureExt;
use crate::{
client::{
auth::{oidc, AuthMechanism, Credential},
options::ClientOptions,
},
test::log_uncaptured,
Client,
};
type Result<T> = anyhow::Result<T>;
// Prose test 1.1 Single Principal Implicit Username
#[cfg_attr(feature = "t... |
//! This example showcases a simple native custom widget that renders arbitrary
//! path with `lyon`.
mod bezier {
// For now, to implement a custom native widget you will need to add
// `iced_native` and `iced_wgpu` to your dependencies.
//
// Then, you simply need to define your widget type and implem... |
use num::{cast::ToPrimitive, rational::Ratio, Num};
use std::{convert::TryFrom, time::Duration};
pub use std::{f64 as real, i128 as integer, u128 as natural};
pub type Natural = u128;
pub type Integer = i128;
pub type NaturalRatio = Ratio<Natural>;
pub type Rational = Ratio<Integer>;
pub type Real = f64;
pub trait R... |
use std::fs::File;
use std::io::prelude::*;
use std::process::Command;
// ターミナルからcargoコマンドを実行し、公式ビジュアライザを引数を変えながら連続実行します。
// 入力データを固定し、outディレクトリにある出力結果を一つずつ画像化します。
// 公式ビジュアライザの出力ファイル名が固定の場合、上書きさせないために改造が必須!!
// out_svg/xxxx.svg という名前で出力されるように。
fn main() {
let read_dir = std::fs::read_dir("out_txt").unwrap();
... |
use std::sync::mpsc::{channel, Sender, Receiver};
use std::sync::mpsc;
use std::thread;
# use std::collections::HashMap;
# use std::collections::hash_map::Entry::{Occupied, Vacant};
# use std::time::Duration;
use std::thread::sleep;
# use rand::{thread_rng, Rng};
# use rand::distributions::{IndependentSample, Range}... |
use crate::enums::{Align, CallbackTrigger, Color, Damage, Event, Font, FrameType, LabelType};
use crate::image::Image;
use crate::prelude::*;
use crate::utils::FlString;
use fltk_sys::valuator::*;
use std::{
ffi::{CStr, CString},
mem,
os::raw,
};
/// Creates a slider widget
#[derive(WidgetBase, WidgetExt, ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.