text stringlengths 8 4.13M |
|---|
use serde::{Deserialize, Serialize};
#[derive(Debug, Deserialize, Serialize)]
pub enum TransformationCrop {
#[serde(rename = "fit")]
FIT,
#[serde(rename = "fill")]
FILL,
}
|
use chrono::prelude::*;
use jsonwebtoken;
#[derive(Debug, serde::Deserialize, serde::Serialize)]
pub struct Claims {
pub sub: String,
pub email: String,
pub exp: i64,
pub iat: i64,
}
/// Generate JWT for passed User
pub fn generate(user: &crate::models::user::User) -> String {
let secret = match dotenv::var... |
//! Unit propagation.
use partial_ref::{partial, PartialRef};
use crate::context::{parts::*, Context};
pub mod assignment;
pub mod binary;
pub mod graph;
pub mod long;
pub mod watch;
pub use assignment::{backtrack, enqueue_assignment, full_restart, restart, Assignment, Trail};
pub use graph::{Conflict, ImplGraph, Im... |
mod with_pid_alive;
use super::*;
#[test]
fn without_pid_alive_returns_badarg() {
run!(
|arc_process| {
(
Just(arc_process.clone()),
strategy::process(),
strategy::term::pid::local(),
)
},
|(arc_process, group_leader_a... |
// Copyright 2020-2021, The Tremor Team
//
// 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 agr... |
use crate::sprintln;
use embedded_hal::blocking::delay::DelayMs;
use embedded_hal::blocking::spi::Write;
use embedded_hal::digital::v2::*;
const WIDTH: usize = 800;
const HEIGHT: usize = 480;
const WIDE: usize = WIDTH / 8;
pub struct EPD75b<SPI, CS, DC, RST, BUSY, DELAY> {
spi: SPI,
cs: CS,
busy: BUSY,
... |
mod with_atom;
mod with_small_integer;
use proptest::strategy::{Just, Strategy};
use liblumen_alloc::atom;
use liblumen_alloc::erts::term::prelude::*;
use crate::erlang::system_time_1::result;
use crate::test::{strategy, with_process};
#[test]
fn without_atom_or_integer_errors_badarg() {
run!(
|arc_proc... |
use std::collections::HashMap;
pub struct Url
{
path: String,
arguments: HashMap<String, String>,
}
impl Url {
pub fn path(&self) -> &String{&self.path}
pub fn arguments(&self) -> &HashMap<String, String>
{
&self.arguments
}
pub fn new() -> Self
{
Url{path:"/".to_strin... |
extern crate libc;
use api::ErrorCode;
use errors::ToErrorCode;
use commands::{Command, CommandExecutor};
use utils::cstring::CStringUtils;
use self::libc::c_char;
/// Establishes agent to agent connection.
///
/// Information about sender Identity must be saved in the wallet with sovrin_create_and_store_my_did
/// ... |
use bevy::{
core::Bytes,
prelude::*,
reflect::TypeUuid,
render::{
mesh::shape,
pipeline::{PipelineDescriptor, RenderPipeline},
render_graph::{base, AssetRenderResourcesNode, RenderGraph},
renderer::{RenderResource, RenderResourceType, RenderResources},
shader::{Sh... |
use itertools::Itertools;
use std::collections::VecDeque;
use std::io::{self, BufRead};
type Memory = Vec<i64>;
type IO = VecDeque<i64>;
struct VM {
memory: Memory,
ip: usize,
input: IO,
output: IO,
}
enum State {
Running,
Halted,
NeedInput,
}
impl VM {
fn new(program: &Memory, input... |
// 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 super::InternalEvent;
use metrics::counter;
#[derive(Debug)]
pub struct AddFieldsEventProcessed;
impl InternalEvent for AddFieldsEventProcessed {
fn emit_metrics(&self) {
counter!("events_processed", 1,
"component_kind" => "transform",
"component_type" => "add_fields",
... |
use std::io;
// Develop a programme to convert currency X to currency Y and vice versa.
const _USD_TO_EUR: f64 = 0.8679;
const _USD_TO_CAD: f64 = 1.2936;
const _USD_TO_GBP: f64 = 0.7624;
const _USD_TO_YEN: f64 = 113.7264;
const _USD_TO_CHF: f64 = 0.9973;
fn main() {
println!("Welcome to the CurrencyExchange. We ... |
//! # Equipment
//!
//! Though an equipment record is optional, when used it in a recipe or on its own it provides details needed to
//! calculate total water usage as well as water needed for each step.
//! It also contains information about the thermal parameters of the mash tun and large batch hop utilization factor... |
use std::io::Read;
fn main() {
let mut stdin = std::io::stdin();
let mut input = String::new();
stdin.read_to_string(&mut input).expect("read from stdin");
let mut jumps = input.split_whitespace().map(|n| isize::from_str_radix(n, 10).expect("a number")).collect::<Vec<isize>>();
let mut offset = 0... |
/**
* @lc app=leetcode.cn id=48 lang=rust
*
* [48] 旋转图像
*
* https://leetcode-cn.com/problems/rotate-image/description/
*
* algorithms
* Medium (60.29%)
* Total Accepted: 17K
* Total Submissions: 28.2K
* Testcase Example: '[[1,2,3],[4,5,6],[7,8,9]]'
*
* 给定一个 n × n 的二维矩阵表示一个图像。
*
* 将图像顺时针旋转 90 度。
*
*... |
#[doc = "Reader of register APBENR1"]
pub type R = crate::R<u32, super::APBENR1>;
#[doc = "Writer for register APBENR1"]
pub type W = crate::W<u32, super::APBENR1>;
#[doc = "Register APBENR1 `reset()`'s with value 0"]
impl crate::ResetValue for super::APBENR1 {
type Type = u32;
#[inline(always)]
fn reset_va... |
use P26::combinations;
fn main() {
let li = vec!['a', 'b', 'c', 'd', 'e', 'f'];
println!("{:?}", combinations(3, &li));
}
|
use actix_web::middleware::cors::CorsBuilder;
use actix_web::{http::Method, App, HttpResponse};
use controllers::*;
use server::AppState;
pub fn routes(app: &mut CorsBuilder<AppState>) -> App<AppState> {
// Please try to keep in alphabetical order
app.resource("/artists/{id}/toggle_privacy", |r| {
r.me... |
//! ### TODO
//!
//! * offer GC interface and example GCs
//! * rust currently doesn't allow generic static values - when it does, make this library
//! truely generic: Add `read_pool`, `write_pool`. Keep `[Byte]Symbol`, `[Byte]SymbolPool` as
//! useful aliases.
//!
#![feature(hashmap_hasher)]
#![feature(set_recove... |
#![no_std]
#![cfg_attr(docsrs, feature(doc_auto_cfg))]
#![doc = include_str!("../README.md")]
#![doc(
html_logo_url = "https://raw.githubusercontent.com/RustCrypto/media/7f79a5e/img/ring-compat/logo-sq.png"
)]
#![forbid(unsafe_code)]
#![warn(missing_docs, rust_2018_idioms)]
//! # Features
//!
//! Functionality in ... |
#![allow(unused_variables, non_upper_case_globals, non_snake_case, unused_unsafe, non_camel_case_types, dead_code, clippy::all)]
#[repr(transparent)]
#[doc(hidden)]
pub struct IVpnAppId(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for IVpnAppId {
type Vtable = IVpnAppId_abi;
const ... |
use game::{State, Event, Transition};
use renderer::{Renderer, Color};
pub struct GameOverState {
}
impl State for GameOverState {
fn update(&mut self) -> Transition {
Transition::None
}
fn render(&self, renderer: &mut Renderer) {
let msg = [
"╔═══════════╗",
"║ GA... |
mod app;
mod body;
mod client;
mod compress;
mod conf;
mod config;
mod matcher;
mod mime;
mod option;
mod server;
mod util;
use app::{run, RunType};
use body::BodyStream;
use config::{default, Headers, ServerConfig, Setting, SiteConfig, Var};
use futures_util::future::join_all;
use hyper::header::{
HeaderName, Hea... |
use proconio::input;
fn main() {
input! {
n: usize,
st: [(String, String); n],
};
for i in 0..n {
let (si, ti) = &st[i];
let mut ok_s = true;
let mut ok_t = true;
for j in 0..n {
if i == j {
continue;
}
let... |
use crate::*;
use rand::prelude::thread_rng;
use wasmer_runtime::Ctx;
pub fn rand_i32(ctx: &mut Ctx) -> Result<i32, ()> {
let (_, env) = Process::get_memory_and_environment(ctx, 0);
env.log_call("random_i32".to_string());
Ok(thread_rng().next_u32() as i32)
}
pub fn rand_u32(ctx: &mut Ctx) -> Result<u32, ... |
mod lib;
fn main() {
let rgb = lib::get_complementary_color(100, 150, 200);
println!("{:?}", rgb);
}
|
#![allow(non_snake_case, non_camel_case_types, non_upper_case_globals, clashing_extern_declarations, clippy::all)]
#[cfg(feature = "System_Power_Diagnostics")]
pub mod Diagnostics;
#[link(name = "windows")]
extern "system" {}
#[repr(transparent)]
pub struct BatteryStatus(pub i32);
impl BatteryStatus {
pub const Not... |
use crate::dr;
use crate::grammar;
use crate::spirv;
use std::collections;
use crate::grammar::GlslStd450InstructionTable as GGlInstTable;
use crate::grammar::OpenCLStd100InstructionTable as GClInstTable;
type GExtInstRef = &'static grammar::ExtendedInstruction<'static>;
// TODO: Add support for other types.
#[deri... |
use crate::parser::{Handle, NodeData};
use std::collections::VecDeque;
use std::io;
use html5ever::serialize::TraversalScope::{ChildrenOnly, IncludeNode};
use html5ever::serialize::{Serialize, Serializer, TraversalScope};
use html5ever::QualName;
enum SerializeOp {
Open(Handle),
Close(QualName),
}
pub struc... |
#[macro_use]
extern crate bitflags;
#[macro_use]
extern crate lazy_static;
extern crate winapi;
#[cfg(feature="flexbox")]
pub extern crate stretch;
#[cfg(feature="all")]
#[cfg(test)]
mod tests;
mod errors;
pub use errors::{NwgError};
mod events;
pub use events::*;
mod common_types;
pub use common_types::*;
pub(... |
#[macro_use]
extern crate log;
use std::env;
use std::error::Error;
use std::io::Write;
use std::os::unix::net::UnixStream;
use clap::Clap;
use env_logger::Env;
use crate::cli::Opts;
mod cli;
fn current_exe() -> String {
std::env::current_exe()
.ok()
.unwrap()
.file_name()
.unwr... |
use std::collections::HashMap;
use std::fs::File;
use std::rc::Rc;
use std::str::FromStr;
use bigint::{Address, Gas, H256, M256, U256};
use block::TransactionAction;
use evm::errors::RequireError;
use evm::{AccountChange, AccountCommitment, HeaderParams, Log, Patch, SeqTransactionVM, ValidTransaction, VM};
use evm_net... |
//! Tool to clean up old object store files that don't appear in the catalog.
#![deny(
rustdoc::broken_intra_doc_links,
rust_2018_idioms,
missing_debug_implementations,
unreachable_pub
)]
#![warn(
missing_docs,
clippy::todo,
clippy::dbg_macro,
clippy::clone_on_ref_ptr,
// See https:... |
pub fn initialize() {
unsafe {
::libnx::consoleInit(std::ptr::null_mut());
}
}
pub fn exit() {
unsafe {
::libnx::consoleExit(std::ptr::null_mut());
}
}
pub fn clear() {
unsafe {
::libnx::consoleClear();
}
}
pub fn flush() {
unsafe {
::libnx::consoleUpdate... |
use crate::AbstractContext;
use crate::Context;
use crate::NativeVertexBuffer;
/// Holds a GL buffer and lets you upload it to the GPU.
pub struct VertexBuffer {
buffer: NativeVertexBuffer,
}
impl VertexBuffer {
/// Creates a new buffor of the selected type.
pub fn new() -> Self {
let ... |
tonic::include_proto!("engine");
|
//! Adapted from:
//! - https://doc.rust-lang.org/src/std/sys/unix/pipe.rs.html
//! - https://doc.rust-lang.org/src/std/sys/unix/fd.rs.html#385
//! - https://github.com/rust-lang/rust/blob/master/library/std/src/sys/mod.rs#L57
//! - https://github.com/oconnor663/os_pipe.rs
use std::fs::File;
/// Open a new pipe an... |
use criterion::{criterion_group, criterion_main, Criterion};
use crypto::{
encryption::ElGamal,
helper::Helper,
proofs::keygen::KeyGenerationProof,
types::{Cipher, PublicKey},
};
use num_bigint::BigUint;
use num_traits::One;
fn setup_shuffling(
nr_of_votes: usize,
encoded: bool,
pk: PublicK... |
pub mod parser;
pub mod bin_op; |
use crate::edge_angle::edge_angle;
use petgraph::visit::{EdgeRef, IntoEdgeReferences};
use petgraph_drawing::{Drawing, DrawingIndex};
use std::f32::consts::PI;
pub fn crossing_edges<G>(
graph: G,
drawing: &Drawing<G::NodeId, f32>,
) -> Vec<((G::NodeId, G::NodeId), (G::NodeId, G::NodeId))>
where
G: IntoEdge... |
pub mod input;
pub mod navigation;
pub mod prefab;
pub mod project;
|
use std::io;
fn gcd(a: u64, b: u64) -> u64 {
if b == 0 {
a
} else {
gcd(b, a % b)
}
}
fn lcm(a: u64, b: u64) -> u64 {
a * b / gcd(a, b)
}
fn main() {
let mut input = String::new();
io::stdin().read_line(&mut input).unwrap();
input.clear();
io::stdin().read_line(&mut i... |
use super::*;
mod with_timer;
#[test]
fn without_timer_returns_ok_and_sends_read_timer_message() {
with_process(|process| {
let timer_reference = process.next_reference();
assert_eq!(
result(process, timer_reference, options(process)),
Ok(Atom::str_to_term("ok"))
)... |
use pipewire_sys as pw;
use std::ptr;
/// A PipeWire main loop.
///
/// See [MainLoop::new].
pub struct MainLoop {
handle: ptr::NonNull<pw::pw_main_loop>,
}
impl MainLoop {
/// Construct a new main loop object.
///
/// # Examples
///
/// ```rust,no_run
/// use audio_device::pipewire;
/... |
use std::{
str::FromStr,
collections::HashMap
};
use url::Url;
use tokio_tungstenite::tungstenite::protocol::Message;
use rust_decimal::Decimal;
use pretty_assertions::assert_eq;
use crate::services::types::{WebAppConfig, OutputData, Asset, ExchangeRate};
use crate::services::data_processor::deserialize_stream;... |
#[macro_use]
extern crate serde_derive;
extern crate image;
extern crate rayon;
extern crate docopt;
extern crate sprack;
mod demo;
use demo::*;
use docopt::Docopt;
const USAGE: &'static str = "
Usage: rectgen [options]
Options:
-c, --count=COUNT Amount of rectangles to generate [default: 10].
-o... |
use mask::MaskError;
use std::process::Command;
pub fn git_rev_parse() -> Command {
let mut revparse = Command::new("git");
revparse.arg("rev-parse");
revparse
}
pub fn git_dir() -> Result<String,MaskError> {
let mut revparse = git_rev_parse();
revparse.arg("--git-dir");
let output = try!(rev... |
//! Safe rust bindings for libopenmpt, built on top of the C API.
//!
//! See openmpt_sys for the unsafe bindings.
extern crate openmpt_sys;
#[macro_use] mod string_helper;
pub mod info;
pub mod mod_command;
pub mod module; |
use nalgebra_glm as glm;
use sepia::app::*;
use sepia::camera::*;
use sepia::skybox::*;
const ONES: &[GLfloat; 1] = &[1.0];
#[derive(Default)]
struct MainState {
camera: Camera,
skybox: Skybox,
}
impl State for MainState {
fn initialize(&mut self) {
self.skybox = Skybox::new(&[
"asset... |
use std::error::Error;
#[derive(Debug)]
pub enum RuntimeError {
Timer(Box<Error>),
Stdio(Box<Error>),
Channel,
Executor,
}
|
// Copyright 2023 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... |
#![no_std]
#![no_main]
extern crate panic_itm;
use cortex_m::{iprintln, iprint};
use cortex_m_rt::entry;
use embedded_hal::digital::v2::OutputPin;
use embedded_hal::blocking::delay::DelayMs;
use stm32f4xx_hal::{
rcc::RccExt,
gpio::GpioExt,
time::U32Ext,
stm32::{CorePeripherals, Peripherals},
delay... |
extern crate gcc;
fn main(){
gcc::Config::new().file("huhu.c").compile("libhuhu.a");
} |
// Generated by gir (https://github.com/gtk-rs/gir @ e8f82cf)
// from ../gir-files (@ 3cba654+)
// DO NOT EDIT
#[cfg(not(feature = "dox"))]
use std::process;
#[cfg(feature = "dox")]
fn main() {} // prevent linking libraries to avoid documentation failure
#[cfg(not(feature = "dox"))]
fn main() {
if let Err(s) = syst... |
use std;
import std::str;
#[test]
fn test_bytes_len() {
assert (str::byte_len("") == 0u);
assert (str::byte_len("hello world") == 11u);
assert (str::byte_len("\x63") == 1u);
assert (str::byte_len("\xa2") == 2u);
assert (str::byte_len("\u03c0") == 2u);
assert (str::byte_len("\u2620") == 3u);
... |
//! Terminal-related `ioctl` functions.
use crate::fd::AsFd;
use crate::{backend, io};
/// `ioctl(fd, TIOCEXCL)`—Enables exclusive mode on a terminal.
///
/// # References
/// - [Linux]
/// - [FreeBSD]
/// - [NetBSD]
/// - [OpenBSD]
///
/// [Linux]: https://man7.org/linux/man-pages/man4/tty_ioctl.4.html
/// [Free... |
use std::str;
use std::vec::Vec;
use nom::{ErrorKind, IResult, eol, space};
const ERR_WRONG_INDENT: u32 = 0x01;
#[derive(Debug)]
pub struct Expression {
indent: i8,
pub operator: Operator,
pub elements: Vec<Element>
}
#[derive(Debug)]
pub enum Operator {
Store,
Add,
Substract,
Multitply,
... |
use std::borrow::Cow;
use std::io;
use std::iter::Peekable;
use std::str;
use serde_bencode::de::from_bytes;
use serde_bytes;
use sha1::Sha1;
#[derive(Deserialize, Clone, Debug, PartialEq, Eq)]
pub struct Sha1Hash(Vec<u8>);
impl Sha1Hash {
pub fn new(input: Vec<u8>) -> Option<Sha1Hash> {
if input.len() =... |
#[doc = "Reader of register CFG"]
pub type R = crate::R<u32, super::CFG>;
#[doc = "Writer for register CFG"]
pub type W = crate::W<u32, super::CFG>;
#[doc = "Register CFG `reset()`'s with value 0"]
impl crate::ResetValue for super::CFG {
type Type = u32;
#[inline(always)]
fn reset_value() -> Self::Type {
... |
// Copyright 2019 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
use {
failure::{bail, Error, ResultExt},
fidl_fuchsia_net_oldhttp::{self as http, HttpServiceProxy},
fuchsia_async as fasync,
fuchsia_syslo... |
#![no_main]
#![no_std]
extern crate stm32f1xx_hal as hal;
extern crate panic_semihosting;
use cortex_m_semihosting::hprintln;
use cortex_m::asm::delay;
use rtfm::app;
use hal::gpio::gpiob::*;
use hal::gpio::*;
use hal::prelude::*;
use hal::spi::Spi;
use hal::time::MegaHertz;
use ws2812::Ws2812;
use ws2812_spi as ws2... |
// revisions: base nll
// ignore-compare-mode-nll
//[nll] compile-flags: -Z borrowck=mir
trait T<'a> {
fn a(&'a self) -> &'a bool;
fn b(&self) {
self.a();
//[base]~^ ERROR cannot infer
//[nll]~^^ ERROR lifetime may not live long enough
}
}
fn main() {}
|
#[doc = "Writer for register C4IFCR"]
pub type W = crate::W<u32, super::C4IFCR>;
#[doc = "Register C4IFCR `reset()`'s with value 0"]
impl crate::ResetValue for super::C4IFCR {
type Type = u32;
#[inline(always)]
fn reset_value() -> Self::Type {
0
}
}
#[doc = "Write proxy for field `CTEIF4`"]
pub ... |
use bindgen::callbacks::ParseCallbacks;
use bindgen::{Builder, RustTarget};
use std::path::PathBuf;
#[derive(Debug)]
struct CustomCallbacks;
impl ParseCallbacks for CustomCallbacks {
fn process_comment(&self, comment: &str) -> Option<String> {
Some(doxygen_rs::transform(comment))
}
}
fn main() {
... |
use notify::{DebouncedEvent, RecommendedWatcher, RecursiveMode, Result, Watcher};
use std::fs;
use std::path::{Path, PathBuf};
use std::sync::mpsc::channel;
use std::time::Duration;
struct App {
src: &'static str,
dst: FileType,
}
struct FileType {
img: String,
audio: String,
video: String,
do... |
#![deny(missing_docs, clippy::missing_safety_doc)]
//! Arbitrary precision integer and rational arithmetic library wrapping
//! [`imath`](https://github.com/creachadair/imath/)
#[macro_use]
pub(crate) mod error;
pub(crate) mod integer;
pub(crate) mod rational;
pub use crate::{
error::Error,
integer::Integer,... |
#[repr(C)]
#[simd]
pub struct u64x8(pub u64, pub u64, pub u64, pub u64, pub u64, pub u64, pub u64, pub u64);
|
use super::command::{Command, CommandContext};
use super::debugger::{Debugger, RunResult};
use std::io::Write;
use structopt::StructOpt;
use anyhow::Result;
pub struct RunCommand {}
impl RunCommand {
pub fn new() -> Self {
Self {}
}
}
#[derive(StructOpt)]
struct Opts {
#[structopt(name = "FUNCT... |
use amethyst::renderer::light::{Light, PointLight};
use amethyst::renderer::palette::rgb::Rgb;
use amethyst::{
animation::{
get_animation_set, AnimationBundle, AnimationCommand, AnimationControlSet, AnimationSet,
EndControl, VertexSkinningBundle,
},
assets::{
AssetLoaderSystemData, A... |
pub struct Solution;
impl Solution {
pub fn contains_nearby_almost_duplicate(nums: Vec<i32>, k: i32, t: i32) -> bool {
let mut pairs = nums
.into_iter()
.enumerate()
.map(|(i, v)| (v, i))
.collect::<Vec<_>>();
pairs.sort_unstable();
for i in 0... |
#![allow(non_snake_case)]
#[allow(unused_doc_comments)]
// Multisig Schnorr
// Copyright 2018 by Kzen Networks
// This file is part of Multisig Schnorr library
// (https://github.com/KZen-networks/multisig-schnorr)
// Multisig Schnorr is free software: you can redistribute
// it and/or modify it under the terms of the ... |
#![allow(unused_variables, non_upper_case_globals, non_snake_case, unused_unsafe, non_camel_case_types, dead_code, clippy::all)]
#[inline]
pub unsafe fn AddPointerInteractionContext<'a, Param0: ::windows::core::IntoParam<'a, HINTERACTIONCONTEXT>>(interactioncontext: Param0, pointerid: u32) -> ::windows::core::Result<()... |
extern crate url;
use std::env;
use url::Url;
#[derive(Debug)]
pub struct Args {
pub remote: String,
pub url: Url,
}
impl Args {
pub fn from_env(mut argv: env::Args) -> Result<Self, String> {
let remote = try!(argv.nth(1).ok_or("remote arg is required".to_owned()));
let url = try!(argv.ne... |
use std::fmt::{self, Write};
use firefly_binary::Bitstring;
use firefly_intern::Symbol;
use crate::{Annotation, Lit, Literal};
pub fn print_literal(f: &mut fmt::Formatter, literal: &Literal) -> fmt::Result {
print_lit(f, &literal.value)
}
pub fn print_lit(f: &mut fmt::Formatter, lit: &Lit) -> fmt::Result {
... |
extern crate gcd;
use gcd = gcd::gcd;
pub fn main() {
println!("{}", gcd(121i64, 44));
}
|
use crate::chunk::{Chunk, op_codes::*, value::{Value,number}};
use crate::scanner::{Scanner, tokens::{*}};
#[macro_use]
mod rules;
use rules::*;
struct Compiler {
previous: Token,
current: Token,
scanner: Scanner,
success: bool,
panic: bool,
chunk: Chunk
}
pub fn compile(source: String) -> Result<Chunk, ()> {... |
mod error;
use std::borrow::Cow;
use aws_lambda_events::event::autoscaling::AutoScalingEvent as Event;
use failure::Fail;
use lambda_runtime::{error::HandlerError, lambda, Context};
use log::{error, info};
use rusoto_autoscaling::{Autoscaling, AutoscalingClient, CompleteLifecycleActionType};
use serde::{Deserialize, ... |
use crate::smb2::responses;
/// Takes the little endian encoded create response from the server and populates the corresponding
/// Create Response struct.
pub fn decode_create_response_body(encoded_body: Vec<u8>) -> responses::create::Create {
let mut create_response = responses::create::Create::default();
c... |
use anyhow::*;
use liblumen_alloc::erts::exception;
use liblumen_alloc::erts::term::prelude::*;
pub fn flag_is_not_a_supported_atom(flag: Term) -> exception::Result<Term> {
Err(anyhow!("flag ({}) is not a supported atom (label, monotonic_timestamp, print, receive, send, serial, spawn, strict_monotonic_timestamp, ... |
use cid::Cid;
use ipfs_unixfs::file::{visit::IdleFileVisit, FileReadFailed};
use std::convert::TryFrom;
use std::fmt;
use std::io::{Error as IoError, Read, Write};
use std::path::PathBuf;
fn main() {
let cid = match std::env::args().nth(1).map(Cid::try_from) {
Some(Ok(cid)) => cid,
Some(Err(e)) => ... |
use extension_trait::extension_trait;
use rustc_hash::FxHasher;
use std::hash::{Hash, Hasher};
#[extension_trait]
pub impl AdjustCasingOfFirstLetter for str {
fn lowercase_first_letter(&self) -> String {
let mut c = self.chars();
match c.next() {
None => String::new(),
Some(... |
use acteur::{Actor, Assistant, Handle, System};
use async_trait::async_trait;
#[derive(Debug)]
struct Employee {
salary: u32,
}
#[async_trait]
impl Actor for Employee {
type Id = u32;
async fn activate(_: Self::Id) -> Self {
Employee {
salary: 0, //Load from DB or set a default,
... |
use std::os::unix;
use std::io::prelude::*;
use errors::*;
use types::Client;
use httpstream::{read_from_stream, HttpStream};
use utils::http;
use utils::http::{Request, Response};
pub struct UnixStream {
stream: unix::net::UnixStream,
}
impl HttpStream for UnixStream {
fn connect(client: Client) -> Result<U... |
use nom::error::{ErrorKind, ParseError};
use thiserror::*;
#[derive(Error, Debug)]
#[error("A parser error has occured: {1}")]
pub struct ParserError<'a>(pub &'a [u8], pub ParserErrorKind<'a>);
#[derive(Error, Debug)]
pub enum ParserErrorKind<'a> {
#[error("Invalid slice offset, most likely corrupt archive")]
... |
use tree_sitter::{Node, Parser, Query, QueryCursor};
use guarding_core::domain::code_file::CodeFile;
use guarding_core::domain::code_class::CodeClass;
use crate::code_ident::CodeIdent;
const JS_QUERY: &'static str = "
(import_specifier
name: (identifier) @import-name)
(namespace_import (identifier) @import-name)
(im... |
/// Ownership/ Kepemilikan
///
/// Ahad, 15 Desember 2019 18:00
/// Demo untuk membuktikan bahwa fungsi println! tidak mentransfer
/// kepemilikan
///
fn main() {
// buat var name dengan default immutable/ tidak dapat diubah
let name = String::from("Hello");
println!("1. {}", name);
println!("2. {}", na... |
use serde::{Deserialize, Serialize};
use std::path::PathBuf;
use crate::spotify;
use rspotify::client::Spotify;
pub type Result<T> = std::result::Result<T, Box<dyn std::error::Error>>;
pub struct MusicLibrary {
spotify: Option<Spotify>,
dirs: Vec<LocalDir>,
}
#[derive(Debug, Clone)]
pub struct LocalDir {
name... |
#![allow(non_snake_case, non_camel_case_types, non_upper_case_globals, clashing_extern_declarations, clippy::all)]
#[link(name = "windows")]
extern "system" {}
pub const ARRAY_SEP_CHAR: u32 = 9u32;
pub const FACILITY_WPC: u32 = 2457u32;
pub type IWPCGamesSettings = *mut ::core::ffi::c_void;
pub type IWPCProviderConfig ... |
//! A widget that may present a modal.
use druid::kurbo::Vec2;
use druid::widget::prelude::*;
use druid::{Color, Command, Data, Rect, Selector, SingleUse, WidgetExt, WidgetPod};
/// A wrapper around a closure for constructing a widget.
pub struct ModalBuilder<T>(Box<dyn FnOnce() -> Box<dyn Widget<T>>>);
impl<T: Data... |
#![feature(
anonymous_lifetime_in_impl_trait,
async_closure,
box_patterns,
let_chains,
strict_provenance
)]
pub mod database;
pub mod debug_adapter;
pub mod features;
pub mod features_candy;
pub mod features_ir;
mod semantic_tokens;
pub mod server;
pub mod utils;
|
use std::path::{Path, PathBuf};
macro_rules! out_ {
($path:expr) => {
&[env!("CARGO_MANIFEST_DIR"), "/../target/", $path].concat()
};
}
macro_rules! in_ {
($path:expr) => {
&[env!("CARGO_MANIFEST_DIR"), "/../resources/", $path].concat()
};
}
/// TODO{issue#128}: rework to provide flex... |
use libc::*;
use sdl2_sys;
use std::ffi::CString;
#[inline]
pub fn get_proc_address(name: &str) -> *const c_void {
let cstring = CString::new(name).expect("could not convert name to a CString");
unsafe { sdl2_sys::SDL_GL_GetProcAddress(cstring.as_ptr()) as *const _ }
}
|
extern crate plotlib;
use plotlib::page::Page;
use plotlib::repr::{Line, Scatter};
use plotlib::style::{PointMarker, PointStyle};
use plotlib::view::ContinuousView;
fn main() {
let K = |x: f64, s: f64| (x * x - s * s).exp();
let f = |x: f64| (x * x).exp();
let (start, end) = (0., 1f64);
let num_points... |
use super::Symbol;
use crate::account::AccountName;
use crate::bytes::{NumBytes, Read, Write};
use core::fmt;
use core::ops::Deref;
pub use eosio_numstr::ParseSymbolError;
/// Extended asset which stores the information of the owner of the symbol
/// <https://github.com/EOSIO/eosio.cdt/blob/4985359a30da1f883418b713359... |
/*
* @lc app=leetcode.cn id=232 lang=rust
*
* [232] 用栈实现队列
*
* https://leetcode-cn.com/problems/implement-queue-using-stacks/description/
*
* algorithms
* Easy (61.83%)
* Likes: 129
* Dislikes: 0
* Total Accepted: 30.7K
* Total Submissions: 49.1K
* Testcase Example: '["MyQueue","push","push","peek",... |
#![no_std]
extern crate alloc;
use alloc::format;
use alloc::string::String;
use alloc::vec::Vec;
use core::cmp::PartialEq;
use core::default::Default;
use core::fmt::Display;
#[macro_use]
extern crate cfg_if;
use prost;
use prost::Message;
cfg_if! {
if #[cfg(feature = "edition-2015")] {
extern crate ... |
pub struct Solution;
impl Solution {
pub fn longest_palindrome(s: String) -> String {
if s.is_empty() {
return s;
}
let chars = s.chars().collect::<Vec<char>>();
let n = chars.len();
let mut max = 1;
let mut max_i = 0;
let mut max_j = 0;
f... |
mod util;
pub use util::loadtxt;
use util::{FloatMax, ToU64};
mod colormaps;
use pdfpdf::{Alignment::*, Color, Matrix, Pdf, Point, Size};
pub struct Plot {
pdf: Pdf,
width: f64,
height: f64,
font_size: f64,
tick_length: f64,
x_tick_interval: Option<f64>,
y_tick_interval: Option<f64>,
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.