text stringlengths 8 4.13M |
|---|
use cocoa::base::id;
pub struct BlitCommandEncoder(id);
impl_from_into_raw!(BlitCommandEncoder, of protocol "MTLBlitCommandEncoder");
|
use std::collections::{HashMap, HashSet};
use std::net::{SocketAddr, UdpSocket};
use std::str;
use wa_fsp::*;
struct FspServer {
socket: UdpSocket,
files: HashMap<String, HashSet<SocketAddr>>,
}
impl FspServer {
fn new() -> FspServer {
let socket =
UdpSocket::bind("0.0.0.0:8080").expe... |
#![cfg_attr(feature = "unstable", feature(test))]
// Launch program : cargo run --release < input/input.txt
// Launch benchmark : cargo +nightly bench --features "unstable"
/*
Benchmark results:
* When not sorting expenses during parsing
running 3 tests
test bench::bench_parse_input ... bench: 8,950 ns... |
use std::collections::HashMap;
use std::hash::{Hash};
use std::io::{self};
// Fun experiment with abstract rewriting machine. Not actually used.
// @personal
// test
#[derive(Debug, Clone)]
enum Op<T> {
Match(T, T),
CopyArgument(usize),
CopyTraversal(usize),
Push(T),
DropArgument(usize),
DropTr... |
extern crate toml;
use std::io;
use std::fs;
use std::io::Read;
#[derive(Debug, RustcDecodable)]
pub struct Config {
api_key: String,
}
#[derive(Debug)]
pub enum ConfigParseError {
Io(io::Error),
ParseError(String),
}
impl From<io::Error> for ConfigParseError {
fn from(err: io::Error) -> ConfigPar... |
#[doc = r"Register block"]
#[repr(C)]
pub struct RegisterBlock {
#[doc = "0x00 - MDIOS configuration register"]
pub mdios_cr: MDIOS_CR,
#[doc = "0x04 - MDIOS write flag register"]
pub mdios_wrfr: MDIOS_WRFR,
#[doc = "0x08 - MDIOS clear write flag register"]
pub mdios_cwrfr: MDIOS_CWRFR,
#[do... |
// Copyright 2019 The Chromium OS 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 cras_sys::gen::CRAS_STREAM_DIRECTION;
/// An enum of the valid directions of an audio stream.
/// Convertible into CRAS_STREAM_DIRECTION via direc... |
///
/// Blitz Explorer
///
/// Index/catalog of files content
///
/// Copyright 2019 Luis Fernando Batels <luisfbatels@gmail.com>
///
use std::fs::File;
use std::path::{Path, PathBuf};
use std::io::{BufReader, BufWriter, copy};
use std::sync::Arc;
use std::str;
use std::collections::{HashMap, LinkedList};
use flate2:... |
//! This module handles managing all the data needed for the application to run. All read/write
//! operations should go through here.
//mod config;
//mod index;
pub mod reader;
//mod repository;
//mod updater;
//use config::Config;
//use index::Index;
//use repository::Repository;
//use updater::Updater;
pub struct... |
use std::any::{Any, TypeId};
use crate::core::{
world::World,
entity::Entity,
};
pub struct ComponentManager;
impl ComponentManager {
/// Add a component to an entity.
pub fn add_component<T: Any>(component: T, entity: Entity, world: &mut World) {
if !world.living_entities.contains(... |
use std::{path::PathBuf, sync::{Arc, Mutex, atomic::AtomicBool}, thread::JoinHandle, time::Duration};
use steamworks::PublishedFileId;
use tauri::Webview;
use crate::{transaction_data, transactions::{Transaction, TransactionChannel, Transactions}};
struct ActiveDownload {
transaction: Arc<Transaction>,
channel: Tr... |
use libc;
use std::os::unix::io::RawFd;
use {Errno, Result};
use std::ffi::CStr;
bitflags!(
flags MemFdCreateFlag: libc::c_uint {
const MFD_CLOEXEC = 0x0001,
const MFD_ALLOW_SEALING = 0x0002,
}
);
pub fn memfd_create(name: &CStr, flags: MemFdCreateFlag) -> Result<RawFd> {
use sys::sy... |
use crate::{input_validators::*, ArgConstant};
use clap::{App, Arg};
pub const BLOCKHASH_ARG: ArgConstant<'static> = ArgConstant {
name: "blockhash",
long: "blockhash",
help: "Use the supplied blockhash",
};
pub const SIGN_ONLY_ARG: ArgConstant<'static> = ArgConstant {
name: "sign_only",
long: "si... |
extern crate pest;
use error::RecutError;
use field::{split_line_quotes, split_line_regex_quotes};
use fs::File;
use io::{stdin, BufRead, BufReader};
use match_field::{parse_match_indices, parse_match_indices_regex};
use pest::Parser;
use range::{parse_indices, BeginRange, EndRange, UnExpandedIndices};
use regex::Rege... |
extern crate libsyntax2;
extern crate superslice;
extern crate itertools;
extern crate smol_str;
mod extend_selection;
mod symbols;
mod line_index;
mod edit;
mod code_actions;
use libsyntax2::{
ast::{self, NameOwner},
AstNode,
algo::{walk, find_leaf_at_offset},
SyntaxKind::{self, *},
};
pub use libsyn... |
//! File extension trait
use std::fs::File;
use std::io::Result;
/// Extension convenience trait that allows pre-allocating files, suggesting random access pattern
/// and doing cross-platform exact reads/writes
pub trait FileExt {
/// Make sure file has specified number of bytes allocated for it
fn prealloca... |
#[doc = "Reader of register BUS_RST_CNT"]
pub type R = crate::R<u32, super::BUS_RST_CNT>;
#[doc = "Writer for register BUS_RST_CNT"]
pub type W = crate::W<u32, super::BUS_RST_CNT>;
#[doc = "Register BUS_RST_CNT `reset()`'s with value 0x0a"]
impl crate::ResetValue for super::BUS_RST_CNT {
type Type = u32;
#[inli... |
mod text;
mod texture_rect;
use std::sync::Arc;
use vulkano::command_buffer::{AutoCommandBufferBuilder, SubpassContents};
use vulkano::sampler::Filter;
use rusttype::{PositionedGlyph, Scale, point};
use gristmill::asset::{Asset, image::{Image, NineSliceImage}};
use gristmill::color::{Color, encode_color};
use grist... |
/* Copyright (c) 2020-2021 Alibaba Cloud and Intel Corporation
*
* SPDX-License-Identifier: Apache-2.0
*/
#![allow(non_upper_case_globals)]
#![allow(non_camel_case_types)]
#![allow(non_snake_case)]
extern crate sgx_types;
extern crate sgx_urts;
use std::thread;
use std::os::unix::io::{RawFd, AsRawFd};
use std::os... |
// This file is part of Bit.Country.
// Copyright (C) 2020-2021 Bit.Country.
// 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.apache... |
//! Provide helper functions/trait impls to pack/unpack
//! [`SyscallArgs`].
//!
//! `io:Error` is not implemented for better `no_std` support.
/// The 6 arguments of a syscall, raw untyped version.
#[derive(PartialEq, Debug, Eq, Clone, Copy)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))... |
use std::io::{Read, Seek};
use iced_wgpu::wgpu;
use serde::Deserialize;
use crate::assets::{AssetError, AssetPack, Texture, Vertex, Mesh};
#[allow(non_snake_case)]
#[derive(Deserialize)]
struct GltfAccessor {
bufferView: usize,
byteOffset: Option<usize>,
componentType: usize,
count: usize,
max: Opt... |
use ggez::audio::SoundSource;
use ggez::input::keyboard::KeyCode;
use ggez::input::keyboard::KeyMods;
use ggez::*;
use rand;
use rand::Rng;
const SCREEN_SIZE: (f32, f32) = (800.0, 600.0);
const PLAYER_HEIGHT: f32 = 100.0;
#[derive(Clone, Copy, Debug)]
struct Point {
x: f32,
y: f32,
}
impl From<Point> for min... |
use proc_macro2::Span;
use quote::quote;
use syn::MetaList;
use syn::{
punctuated::Punctuated, token::Comma, Attribute, Data, DataStruct, DeriveInput, Field, Fields,
FieldsNamed, Ident, Lit, Meta, MetaNameValue, NestedMeta,
};
macro_rules! try_set {
($i:ident, $v:expr, $t:expr) => {
match $i {
... |
#[doc = "Reader of register INTR"]
pub type R = crate::R<u32, super::INTR>;
#[doc = "Writer for register INTR"]
pub type W = crate::W<u32, super::INTR>;
#[doc = "Register INTR `reset()`'s with value 0"]
impl crate::ResetValue for super::INTR {
type Type = u32;
#[inline(always)]
fn reset_value() -> Self::Typ... |
use std::collections::HashMap;
#[derive(Debug, Copy, Clone, PartialOrd, PartialEq)]
pub enum Method {
OPTIONS,
GET,
HEAD,
POST,
PUT,
DELETE,
TRACE,
CONNECT,
}
#[derive(Debug)]
pub struct URI {
pub path: String,
pub query: HashMap<String, String>,
}
#[derive(Debug, Copy, Clone)... |
#[doc = "Register `DIEPINT0` reader"]
pub type R = crate::R<DIEPINT0_SPEC>;
#[doc = "Register `DIEPINT0` writer"]
pub type W = crate::W<DIEPINT0_SPEC>;
#[doc = "Field `XFRC` reader - XFRC"]
pub type XFRC_R = crate::BitReader;
#[doc = "Field `XFRC` writer - XFRC"]
pub type XFRC_W<'a, REG, const O: u8> = crate::BitWriter... |
use super::Props;
pub trait PullSpec {
type Props: Props;
}
pub trait PushSpec {
type Props<PrevProps: Props>;
}
macro_rules! spec_impl {
(
PullSpec for $($struct:ident::)* <$iname:ident $(,$gname:ident)*>
) => {
impl<$iname $(,$gname)*> PullSpec for $($struct::)* <$iname $(,$gname)*>... |
#[macro_use]
extern crate diesel;
#[macro_use]
extern crate log;
extern crate pwhash;
extern crate rand;
extern crate regex;
extern crate serde;
#[macro_use]
extern crate serde_derive;
extern crate serde_json;
extern crate simplelog;
extern crate time;
extern crate typographic_linter;
pub mod api;
pub mod authenticati... |
use super::super::messages::WriteGTP;
use super::*;
use std::io;
// Everything but “I”
const LEGAL_LETTERS: &str =
"ABCDEFGHJKLMNOPQRSTUVWXYZ";
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Value {
Pass,
// TODO: Introduce types LetterCoord and NumberCoord?
/// The `char` is always an upper case letter ex... |
// This file is part of Substrate.
// Copyright (C) 2017-2020 Parity Technologies (UK) Ltd.
// SPDX-License-Identifier: GPL-3.0-or-later WITH Classpath-exception-2.0
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the F... |
use std::collections::HashMap;
use crate::agent::{AgentCheck, AgentService};
use crate::errors::Result;
use crate::request::{get, put};
use crate::{Client, QueryMeta, QueryOptions, WriteMeta, WriteOptions};
#[serde(default)]
#[derive(Eq, Default, PartialEq, Serialize, Deserialize, Debug)]
pub struct Weights {
pub... |
use std::io::{Error, ErrorKind};
use bytes::{Buf, BytesMut};
use rsocket_rust::frame::Frame;
use rsocket_rust::utils::{u24, Writeable};
use tokio_util::codec::{Decoder, Encoder};
pub struct LengthBasedFrameCodec;
const LEN_BYTES: usize = 3;
impl Decoder for LengthBasedFrameCodec {
type Item = Frame;
type Er... |
use std::{
collections::HashMap,
sync::{atomic::AtomicI64, Arc, Mutex},
};
use async_trait::async_trait;
use chrono::{DateTime, Utc};
use crate::{
model::Items,
repo::{IRepository, DEFAULT_LIMIT},
DoneItem, ItemId, OpenItem, Result,
};
pub struct InMemoryRepo {
open_items: Arc<Mutex<HashMap<I... |
#![no_std]
#![cfg_attr(test,no_main)]//enable no_main in test-mode, so lib.rs need to own a _start entry and a panic handler
#![feature(custom_test_frameworks)]
#![test_runner(crate::test_runner)]
#![reexport_test_harness_main = "test_main"]
#![feature(abi_x86_interrupt)]
#![feature(alloc_error_handler)]//feature gate... |
#[derive(Debug)]
struct Person {
name: String,
age: u8,
}
struct Unit;
struct Pair(i32, f32);
#[derive(Debug)]
struct Point {
x: f32,
y: f32,
}
// structs can be reused as fields of another struct
#[derive(Debug)]
struct Rectangle {
top_left: Point,
bottom_right: Point,
}
fn rect_area(rect:... |
pub mod bio_types;
|
use anyhow::Result;
use futures::stream::StreamExt;
use rusoto_core::{ByteStream, Region};
use rusoto_s3::{GetObjectRequest, S3Client, S3};
use structopt::StructOpt;
use tokio;
use tokio::fs::File;
use tokio::io::AsyncWriteExt;
use std::path::PathBuf;
#[derive(StructOpt, Debug)]
#[structopt(name = "s3_get_object")]
s... |
use flux::semantic::{
nodes::{Expression, Symbol},
walk::{self, Node, Visitor},
};
use lspower::lsp;
mod completion;
mod functions;
mod lint;
mod symbols;
pub use completion::{
FunctionFinderVisitor, ObjectFunctionFinderVisitor,
};
pub use lint::{
ContribDiagnosticVisitor, ExperimentalDiagnosticVisito... |
use core::fmt;
static mut STR_BUF: [u8; 512] = [0;512];
unsafe fn to_cstring(s: &str) -> *const u8 {
let mut pos = 0;
for c in s.bytes() {
assert!(c < 128);
STR_BUF[pos] = c;
pos += 1;
}
STR_BUF[pos] = 0;
&STR_BUF[0]
}
extern {
fn InitFS() -> bool;
fn DeinitFS();
... |
use rust_oauth2_study::{
config::Config, db_conn::DbConn, handlers::shopify_handler, routes::shopify_route,
};
use std::net::SocketAddr;
use std::sync::Arc;
use warp::Filter;
pub mod api;
#[tokio::main]
async fn main() {
let config = Arc::new(Config::new(false));
let db_conn = Arc::new(DbConn::new(&config... |
use std::borrow::Cow;
use std::rc::Rc;
use std::rc::Weak;
use std::sync::Arc;
fn main() {
fn print_int(i: i32) {
println!("{}", i);
}
{
// ----- Box (unique_ptr) -----
let my_one = 1;
print_int(my_one);
let my_two = Box::new(2);
print_int(*my_two);
}
... |
use std::fs;
use std::path::Path;
use std::process::Command;
fn visit_dir(path: &Path) {
if let Ok(entries) = fs::read_dir(path) {
for opt_entry in entries {
if let Ok(entry) = opt_entry {
if let Ok(ty) = entry.file_type() {
let entry_path = entry.path();
... |
pub type ConnectionId = String;
use crate::connection_error::{ConnectionError, ConnectionResult};
pub type DidWork = bool;
#[derive(Debug, PartialEq, Clone)]
pub enum ConnectionEvent {
ConnectionError(ConnectionId, ConnectionError),
Connect(ConnectionId),
Message(ConnectionId, Vec<u8>),
Close(Connect... |
#[cfg(test)]
#[path = "../../../tests/unit/construction/heuristics/selectors_test.rs"]
mod selectors_test;
use crate::construction::heuristics::*;
use crate::models::problem::Job;
use crate::utils::{map_reduce, parallel_collect, Either, Noise};
use rand::prelude::*;
/// On each insertion step, selects a list of route... |
//This only handles the portaudio bindings
//Note we should change the audiostream stuff to generic
//but essentially we just need to give it an object which
//contains the data reference and some implementation
//that can be used in the call back to do some dsp
use std::sync::mpsc;
extern crate portaudio;
use portaudi... |
use libusb_sys as ffi;
use std::str;
use std::ffi::CStr;
fn main() {
let version = unsafe { ffi::libusb_get_version() };
let rc = str::from_utf8(unsafe { CStr::from_ptr((*version).rc) }.to_bytes()).unwrap_or("");
let describe = str::from_utf8(unsafe { CStr::from_ptr((*version).describe) }.to_b... |
#[cfg(test)]
mod tests {
use std::fs;
use std::env;
use std::fs::File;
use std::path::PathBuf;
use std::error::Error;
use std::io::Read;
use regex::Regex;
use lazy_static::lazy_static;
use scraper::Html;
use hacker_news::parser::HtmlParse;
use hacker_news::parser::ListingsPa... |
extern crate hyper;
use hyper::Client;
use hyper::header::{ContentType, UserAgent};
use hyper::mime::{Mime, TopLevel, SubLevel};
use hyper::Ok;
use std::env;
use std::io::Read;
fn main(){
// curl -XPOST 'http://www.nickelback.com/service/emaillist'
// -H 'Host: www.nickelback.com'
// -H 'User-... |
use crate::cube::{Cube, Move};
use std::collections::{HashMap, VecDeque};
// 11 moves using half-turn metric,
// or 14 using the quarter-turn metric
const GODS_NUMBER: usize = 11;
#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
enum Direction {
Forward,
Backward,
}
impl Direction {
fn opposite(self) -... |
use crate::indices::{EntityId, RoomPosition, ScriptId, WorldPosition};
use arrayvec::{ArrayString, ArrayVec};
use serde::{Deserialize, Serialize};
#[derive(Debug, Clone, Serialize, Deserialize, Copy, Default)]
#[serde(rename_all = "camelCase")]
pub struct MeleeAttackComponent {
pub strength: u16,
}
/// Has a bod... |
/*
* Copyright (c) 2013, David Renshaw (dwrenshaw@gmail.com)
*
* See the LICENSE file in the capnproto-rust root directory.
*/
use std;
use std::rand::*;
use common::*;
use eval_capnp::*;
pub type RequestBuilder = Expression::Builder;
pub type ResponseBuilder = EvaluationResult::Builder;
pub type Expectation = i3... |
use managed::Managed;
use Error;
use wire::{IpProtocol, IpEndpoint};
use wire::{UdpPacket, UdpRepr};
use socket::{Socket, IpRepr, IpPayload};
/// A buffered UDP packet.
#[derive(Debug)]
pub struct PacketBuffer<'a> {
endpoint: IpEndpoint,
size: usize,
payload: Managed<'a, [u8]>
}
impl<'a> PacketBuffe... |
use std::cmp;
use std::net::{SocketAddr, ToSocketAddrs};
use std::time::{Instant, Duration};
use std::collections::HashMap;
use rand;
use libc::c_int;
use nix::poll::{poll, EventFlags, PollFd, POLLIN};
use socket::RawSocket;
use packet::EchoRequest;
pub const POLL_TIMEOUT_MS: c_int = 1000;
/// An object for sending... |
use std::process::*;
fn unseen_mail_count() -> Result<usize, String> {
let _ = Command::new("bash")
.arg("-c")
.arg("notmuch new")
.output()
.map_err(|e| e.to_string())?;
let stdout = Command::new("bash")
.arg("-c")
.arg("notmuch search 'tag:unread and folder:/.... |
use std::default::Default;
trait ID {
fn id(&self) -> usize;
}
impl<T:Sized> ID for T {
fn id(&self) -> usize {
let ptr : * const T = self;
unsafe { std::mem::transmute(ptr) }
}
}
#[derive(Default)]
struct Empty ;
struct S {
pub name : &'static str
}
fn main() {
let i = 32_i32;
let e : Empty = Default::d... |
use std::collections::HashMap;
use std::io::BufRead;
fn prob1_adder(mut freq: i32, mut line: String) -> i32 {
let sign_str: String = line.drain(..1).collect();
let mut sign = 1;
if sign_str == "-" {
sign = -1;
}
let i = line.parse::<i32>().expect("problem parsing number");
freq += i * s... |
use crate::{
jack_tokenizer::{Keyword, TokenData, Tokenizer},
symbol_table::{SymbolTable, VarKind},
vm_writer::VMWriter,
};
pub struct CompilationEngine {
tokenizer: Tokenizer,
symbol_table: SymbolTable,
vm_writer: VMWriter,
class_name: String,
label_index: usize,
is_void: bool,
}
i... |
use kube_derive::CustomResource;
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
#[derive(CustomResource, Serialize, Deserialize, JsonSchema)]
union FooSpec {
int: u32,
}
fn main() {}
|
use std::error::Error;
#[async_std::main]
async fn main() -> Result<(), Box<dyn Error>> {
env_logger::try_init()?;
listen_moe::auth::login("[Username/EMail address]".into(), "[Password]".into(), None).await?;
println!("Login successful");
Ok(())
}
|
// This file is part of Substrate.
// Copyright (C) 2020 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://... |
//! The CXX code generator for constructing and compiling C++ code.
//!
//! This is intended to be used from Cargo build scripts to execute CXX's
//! C++ code generator, set up any additional compiler flags depending on
//! the use case, and make the C++ compiler invocation.
//!
//! <br>
//!
//! # Example
//!
//! Examp... |
use super::webgl::{WebGlAttributeLocation, WebGlRenderingContext};
use web_sys::WebGlUniformLocation;
const VERTEX_SHADER: &str = r#"
attribute vec4 a_vertex;
attribute vec2 a_textureCoord;
uniform mat4 u_translate;
varying vec2 v_textureCoord;
void main() {
v_textureCoord = a_textureCoord... |
//! Library for decoding and encoding JSON streams.
//!
//! Example:
//! ```
//! # use futures::executor::block_on;
//! let expected = ("one".to_string(), 2.0, vec![3, 4]);
//! let stream = destream_json::encode(&expected).unwrap();
//! let actual = block_on(destream_json::try_decode((), stream)).unwrap();
//! assert_e... |
use crate::delay::Delay;
pub struct DelayAPF {
delay: Delay,
g: f64,
}
impl DelayAPF {
pub fn new(delay_length: usize, g: f64) -> DelayAPF {
DelayAPF {
delay: Delay::new(delay_length),
g: g,
}
}
pub fn next(&mut self, s: f64) -> f64 {
let delayed_sa... |
pub mod tape {
pub const SNAPSHOT_SNA_48K: &[u8] = include_bytes!("tape_48k.sna");
pub const SNAPSHOT_SNA_128K: &[u8] = include_bytes!("tape_128k.sna");
}
|
extern crate skim;
use skim::prelude::*;
/// This example illustrates downcasting custom structs that implement
/// `SkimItem` after calling `Skim::run_with`.
#[derive(Debug, Clone)]
struct Item {
text: String,
}
impl SkimItem for Item {
fn text(&self) -> Cow<str> {
Cow::Borrowed(&self.text)
}
... |
/// Loads the file and if some expected output is given checks that it matches
fn test_file(file: &str, expected: Option<&[u8]>) {
use scryer_prolog::*;
let input = machine::Stream::from("");
let output = machine::Stream::from(String::new());
let mut wam = machine::Machine::new(input, output.clone());... |
//! Generates OpenTelemetry OTLP trace payloads
//!
//! [Specification](https://opentelemetry.io/docs/reference/specification/protocol/otlp/)
//!
//! This format is valid for OTLP/gRPC and binary OTLP/HTTP messages. The
//! experimental JSON OTLP/HTTP format can also be supported but is not
//! currently implemented.
... |
/*
* 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
*/
/// DistributionWidgetXAxis : X Axis controls for the distribution widget.
#[derive(Clone, Debug, Par... |
use std::thread;
use std::time::Duration;
use std::sync::{Arc , Mutex, mpsc::*};
fn main(){
let spoon_lock =Arc::new(Mutex::new(String::from("spoon")));
let spoon_a = Arc::clone(&spoon_lock);
let spoon_b = Arc::clone(&spoon_lock);
let (sen_a,rec_a) = channel::<String>();
let (sen_b,rec_b) = chann... |
#![recursion_limit = "128"]
// extern crate fst_levenshtein;
#[macro_use]
extern crate measure_time;
#[allow(unused_imports)]
#[macro_use]
extern crate serde_json;
#[allow(unused_imports)]
use fst::{IntoStreamer, MapBuilder, Set};
// use fst_levenshtein::Levenshtein;
// use serde_json::{Deserializer, Value};
use std... |
use super::*;
/// A footnote reference.
///
/// # Semantics
///
/// This is a reference (or link) to a [`greater_elements::FootnoteDefinition`].
///
/// # Syntax
///
/// Follows one of these patterns:
///
/// - normal footnote: `[fn:LABEL]`
/// - inline footnote: `[fn:LABEL:DEFINITION]`
/// can be references by othe... |
#![cfg(test)]
use super::*;
use frame_support::{construct_runtime, pallet_prelude::Hooks, parameter_types};
use orml_traits::parameter_type_with_key;
use pallet_nft::AssetHandler;
use primitives::{continuum::Continuum, Amount, AuctionId, CurrencyId, FungibleTokenId};
use sp_core::H256;
use sp_runtime::traits::AccountI... |
fn rot(s: &str) -> String {
// your code
s.chars().rev().collect()
}
fn add_dots(s: &str) -> String {
s.split('\n')
.map(|substr| substr.to_owned() + &".".repeat(substr.len()))
.collect::<Vec<String>>()
.join("\n")
}
fn selfie_and_rot(s: &str) -> String {
// your code
let with_dots = add_dots(s);
l... |
use std::str
fn main() {
let bytestring: &[u8; 20] = b"this is a bytestring";
println!("A bytestring: {:?}", bytestring);
let escaped = b"\x52\x75\x73\x74 as bytes";
println!("Some escaped bytes: {:?}", escaped);
let raw_bytestring = br"\u{211D} is not escaped here";
println!("{:?}", raw_byt... |
use std::env;
use std::process;
use minigrep::Config;
use minigrep::run;
fn main() {
// accepting arguments
let arguments: Vec<String> = env::args().collect();
let config = Config::new(&arguments).unwrap_or_else(|error| {
println!("Problem in parsing arguments: \n\t - {}", error);
process:... |
//! [Advanced Traits]
//!
//! # Examples
//!
//! Simplified [`Iterator`] example
//!
//! ```
//! use the_book::ch19::sec02::{Counter, Iterator};
//!
//! let mut counter = Counter::new(3);
//! assert_eq!(Some(1), counter.next());
//! assert_eq!(Some(2), counter.next());
//! assert_eq!(Some(3), counter.next());
//! asser... |
/**********************************************************\
| |
| hprose |
| |
| Official WebSite: http://www.hprose.com/ |
| ... |
use std::io;
use std::os::unix::net::SocketAddr;
use std::path::PathBuf;
use futures::{Async, Poll, Stream, Sink, StartSend, AsyncSink};
use UnixDatagram;
/// Encoding of frames via buffers.
///
/// This trait is used when constructing an instance of `UnixDatagramFramed` and
/// provides the `In` and `Out` types whi... |
// Copyright 2017 Dmitry Tantsur <divius.inside@gmail.com>
//
// 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 ap... |
/// Copyright (c) 2020, Shoyo Inokuchi
///
/// A simple sudoku solver written in Rust.
/// Feel free to to refer to the repository at: https://github.com/shoyo/sudoku for more
/// information.
///
use std::fmt::{Display, Error, Formatter};
mod boards;
const ROWS: usize = 9;
const COLS: usize = 9;
const CAGE_ROWS: usi... |
pub use self::ball::Ball;
pub use self::collision_box::CollisionBox;
pub use self::human::Human;
pub use self::movement_state::MovementState;
pub use self::net::Net;
pub use self::player::Player;
pub use self::player::PlayerType;
pub use self::robot::Robot;
pub mod ball;
pub mod collision_box;
pub mod human;
pub mod m... |
use hymns::input::parse_char_delimited_numbers;
use hymns::runner::timed_run;
const INPUT: &str = include_str!("../input.txt");
fn part1() -> i32 {
let crabs: Vec<i32> = parse_char_delimited_numbers(INPUT, ',').collect();
let (min, max) = crabs
.iter()
.fold((i32::MAX, i32::MIN), |(cur_min, c... |
pub mod sprite_sheet;
pub mod prefab; |
pub fn longest_consecutive(nums: Vec<i32>) -> i32 {
use std::collections::HashSet;
let mut set = HashSet::new();
for &num in nums.iter() {
set.insert(num);
}
let mut longest = 0;
for num in nums {
if !set.contains(&(num-1)) {
let mut current = num;
while ... |
use crate::errors::ApiError;
use crate::models::games::*;
use crate::models::teams::*;
use crate::schema::{games::dsl::*, matches, teams::dsl::*};
use diesel::{prelude::*, SqliteConnection};
#[derive(
serde_derive::Serialize, serde_derive::Deserialize, Clone, Queryable,
)]
pub struct Match {
pub id: i32,
... |
fn main(){
let hi = "Hi";
let mut counter= 1i;
let max_counter = 100i;
println!("{}",hi);
while counter < max_counter {
println!("count is now {}",counter);
counter +=1;
}
}
|
#![cfg_attr(not(target_arch = "x86_64"), no_std)]
#![cfg_attr(not(target_arch = "x86_64"), no_main)]
#![cfg_attr(not(target_arch = "x86_64"),feature(custom_test_frameworks, lang_items, start))]
#![cfg_attr(not(target_arch = "x86_64"),test_runner(crate::test_runner))]
extern crate libc;
extern crate rand;
extern crate ... |
pub const WORDLIST: &'static [&'static str] = &[
"ábaco",
"abdomen",
"abeja",
"abierto",
"abogado",
"abono",
"aborto",
"abrazo",
"abrir",
"abuelo",
"abuso",
"acabar",
"academia",
"acceso",
"acción",
"aceite",
"acelga",
"acento",
"aceptar",
... |
mod api;
mod http;
mod utils;
mod ws;
pub use api::*;
pub use http::*;
pub use ws::*;
|
#[doc = "Reader of register HDP_VAL"]
pub type R = crate::R<u32, super::HDP_VAL>;
#[doc = "Reader of field `HDPVAL`"]
pub type HDPVAL_R = crate::R<u8, u8>;
impl R {
#[doc = "Bits 0:7 - HDPVAL"]
#[inline(always)]
pub fn hdpval(&self) -> HDPVAL_R {
HDPVAL_R::new((self.bits & 0xff) as u8)
}
}
|
use proc_macro2::TokenStream;
use syn;
use helpers::{extract_meta, MetaIteratorHelpers};
pub fn enum_message_inner(ast: &syn::DeriveInput) -> TokenStream {
let name = &ast.ident;
let (impl_generics, ty_generics, where_clause) = ast.generics.split_for_impl();
let variants = match ast.data {
... |
#![warn(rust_2018_idioms)]
#![allow(unused_imports)]
use thiserror::Error;
#[derive(Error, Debug)]
pub enum Error {
#[error("Kube Api Error: {0}")]
KubeError(#[source] kube::Error),
#[error("SerializationError: {0}")]
SerializationError(#[source] serde_json::Error),
}
pub type Result<T, E = Error> = s... |
extern crate rand;
use std::f32::consts::PI;
use vector_2d::V2;
use X_LEN;
use Y_LEN;
#[allow(dead_code)]
#[derive(Debug, Clone, Copy)]
pub enum EdgeBehaviour {
Pass,
PacMan,
Wall,
}
use self::EdgeBehaviour::*;
#[derive(Debug, Clone)]
pub struct Momentum {
pub pos: V2,
pub vel: V2,
pub thet... |
#[doc = "Reader of register DDRCTRL_MRCTRL0"]
pub type R = crate::R<u32, super::DDRCTRL_MRCTRL0>;
#[doc = "Writer for register DDRCTRL_MRCTRL0"]
pub type W = crate::W<u32, super::DDRCTRL_MRCTRL0>;
#[doc = "Register DDRCTRL_MRCTRL0 `reset()`'s with value 0x10"]
impl crate::ResetValue for super::DDRCTRL_MRCTRL0 {
typ... |
#![allow(unused_variables)]
pub mod mock {
use pattern::{StepArgument, Pattern};
use std::collections::HashMap;
use regex::Regex;
const A_PATTERN: &str = "I have cukes in my belly";
pub struct PatternMock {}
impl Pattern for PatternMock {
fn to_regex(&self) -> Regex {
Reg... |
use std::io;
use std::io::Write;
struct Triangle {
a: f64,
b: f64,
c: f64,
}
impl Triangle {
fn area(&self) -> f64 {
let s = (self.a + self.b + self.c) / 2.0;
(s * (s - self.a) * (s - self.b) * (s - self.c)).sqrt()
}
}
struct TriangleBuilder {
a: f64,
b: f64,
c: f64,
}... |
use std::{
boxed::Box,
cell::UnsafeCell,
marker::PhantomPinned,
mem::MaybeUninit,
ops::{Deref, DerefMut},
pin::Pin,
};
unsafe fn pin_dance<'a, R, T>(pin: &'a mut Pin<R>) -> &'a mut T
where
R: DerefMut<Target = T>,
{
let mut_pin = Pin::as_mut(pin);
Pin::get_unchecked_mut(mut_pin)
}
... |
pub fn get_permutation(n: i32, k: i32) -> String {
let n = n as usize;
let mut result = vec![0; n];
let mut took = vec![false; n];
fn find_l_untaken(n: usize, took: &mut Vec<bool>, l: usize) -> usize {
let mut counter = 0;
for j in 0..n {
if !took[j] {
if co... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.