text stringlengths 8 4.13M |
|---|
use proconio::{input, marker::Usize1};
fn dfs(i: usize, p: usize, g: &Vec<Vec<usize>>, size: &mut Vec<usize>) {
size[i] = 1;
for &j in &g[i] {
if j == p {
continue;
}
dfs(j, i, g, size);
size[i] += size[j];
}
}
fn solve(i: usize, p: usize, g: &Vec<Vec<usize>>, s... |
use diesel;
use diesel::prelude::*;
use diesel::pg::PgConnection;
use super::schema::todos;
#[derive(Insertable)]
#[table_name="todos"]
pub struct NewTodo<'a> {
pub title: &'a str,
pub description: &'a str,
}
#[derive(Queryable)]
pub struct Todo {
pub id: i32,
pub title: String,
pub description: ... |
pub mod lexer;
|
extern crate gl;
extern crate glfw;
use std::ffi::CStr;
use std::mem;
use std::os::raw::c_void;
use std::path::Path;
use std::ptr;
use cgmath::{Matrix4, vec3, Vector3};
use image::GenericImage;
use crate::sdl_main::{SCR_HEIGHT, SCR_WIDTH};
use crate::shader::Shader;
use self::gl::types::*;
const CHARS_PER_LINE: f... |
extern crate base64;
mod api;
mod monitor;
mod static_resources;
use std::ops::Deref;
use std::time::Duration;
use crate::rocket::{config::Environment, Config};
use crate::rand::{self, RngCore};
#[derive(Debug)]
struct DetectInterval(Duration);
impl DetectInterval {
#[inline]
fn get_value(&self) -> Durati... |
//! # generator
//!
//! Rust generator library
//!
#![cfg_attr(nightly, feature(asm))]
#![cfg_attr(nightly, feature(repr_simd))]
#![cfg_attr(nightly, feature(core_intrinsics))]
#![cfg_attr(nightly, feature(naked_functions))]
#![cfg_attr(nightly, feature(thread_local))]
#![cfg_attr(test, deny(warnings))]
#![deny(missin... |
#![feature(core_intrinsics)]
#![feature(thread_id_value)]
#![feature(stmt_expr_attributes)]
mod profiler;
mod raw_event;
mod serialization;
mod sinks;
use std::borrow::Borrow;
use std::collections::hash_map::Entry;
use std::convert::Into;
use std::fs;
use std::path::Path;
use std::sync::atomic::{AtomicU32, Ordering};... |
#[macro_use]
extern crate serde_derive;
use std::collections::HashMap;
pub use sp_core::{
H256 as Hash,
crypto::{Pair, Ss58Codec,AccountId32 as AccountId},
};
use sp_runtime::{
MultiSignature,
generic::Era,
};
use codec::{Encode, Decode, Compact};
use system::Phase;
use events::{EventsDecoder, Runtime... |
use std::env;
use std::process;
fn main() {
// Parse args for the number which is the length of tx list
let args: Vec<String> = env::args().collect();
let tx_num = merkle_tree_rust::parse_args(&args).unwrap_or_else(|err| {
eprintln!("Error parsing args: {}" ,err);
process::exit(1);
});
... |
fn main() {
matching_literals();
matching_named_variables();
multiple_patterns();
matching_ranges();
destructuring_structs();
destructuring_enums();
nested_structs_and_enums();
destructuring_structs_and_tuples();
ignoring_an_entire_value();
ignoring_parts_of_a_value();
ignore... |
use sciter::{Value};
use flate2::read::ZlibEncoder;
use flate2::Compression;
use imagequant;
use lodepng::{self, ColorType::PALETTE, CompressSettings, State, RGBA};
use std::io::Read;
use std::os::raw::c_uchar;
use std::path::{ Path, PathBuf };
use std::{str, fs};
// https://stackoverflow.com/a/55033999/13378247
use c... |
use std::io::Read;
fn main() {
let mut buf = String::new();
// 標準入力から全部bufに読み込む
std::io::stdin().read_to_string(&mut buf).unwrap();
// 行ごとのiterが取れる
let mut iter = buf.split_whitespace();
let items: usize = iter.next().unwrap().parse().unwrap();
let points: Vec<(i32, i32)> = (0..items)
... |
#[doc = r"Register block"]
#[repr(C)]
pub struct RegisterBlock {
#[doc = "0x00 - AES DMA Interrupt Mask"]
pub aes_dmaim: AES_DMAIM,
#[doc = "0x04 - AES DMA Raw Interrupt Status"]
pub aes_dmaris: AES_DMARIS,
#[doc = "0x08 - AES DMA Masked Interrupt Status"]
pub aes_dmamis: AES_DMAMIS,
#[doc =... |
//import module 'world' in this file.
mod world;
fn main() {
//add_wall requires a mutable world as it will modify the vector containing the items.
let mut world = world::world::World::new();
world.add_wall();
world.add_player();
println!("Printing the world:{}", world);
}
|
use id_types::*;
//test
#[derive(Copy, Clone, Debug)]
pub struct Mover{
pub x: f64,
pub y: f64,
pub xspeed: f64,
pub yspeed: f64,
pub width: i64,
pub height: i64,
pub solid: bool,
pub disabled: bool
}
pub struct MoverBuilder{
pub x: f64,
pub y: f64,
pub xspeed: f64,
pub yspeed: f64,
pub width: i64,
pub ... |
pub fn htonc(u: u8) -> u8 {
u.to_be()
}
pub fn ntohc(u: u8) -> u8 {
u8::from_be(u)
}
pub fn get(u: u8, idx: u8) -> bool {
let idx2 = 7 - idx;
return ((u >> idx2) & 1) != 0;
}
pub fn combine(u: u8, v: u8) -> u16 {
return ((u as u16) << 8) | (v as u16);
}
pub fn combine32(a: u8, b: u8, c: u8, d: u... |
use crate::bytes;
use crate::compress::{max_compress_len, Encoder};
use crate::crc32::CheckSummer;
use crate::error::Error;
use crate::MAX_BLOCK_SIZE;
/// The maximum chunk of compressed bytes that can be processed at one time.
///
/// This is computed via `max_compress_len(MAX_BLOCK_SIZE)`.
///
/// TODO(ag): Replace ... |
//! Utility methods, mostly for dealing with IO.
macro_rules! try_parse {
($field:expr) => {
try_parse!($field, FromStr::from_str)
};
($field:expr, $from_str:path) => {
match $from_str($field) {
Ok(result) => Ok(result),
Err(_) => Err(Error::new(
Erro... |
//! Dialect
use serde::{Deserialize, Serialize};
/// Dialect are options to change the default CSV output format;
/// <https://www.w3.org/TR/2015/REC-tabular-metadata-20151217/#dialect-descriptions>
#[derive(Clone, Debug, PartialEq, Eq, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct D... |
pub mod file_state;
pub mod logic_files;
pub mod snes_state;
use crate::lttp::{
server_config::DataSourceType,
AppState,
};
use std::{
sync::Arc,
time::{
Duration,
Instant,
},
};
use tokio::time::{
self,
sleep,
};
use tracing::{
debug,
error,
};
#[tracing::instrume... |
use nom::types::CompleteStr;
pub mod opcode_parsers;
pub mod register_parsers;
pub mod operand_parsers;
pub mod instruction_parsers;
pub mod program_parsers;
pub mod label_parsers;
pub mod directive_parsers;
pub mod assembler_errors;
pub mod symbols;
use crate::instruction::Opcode;
use program_parsers::{program, Prog... |
//! `ipfs-http` http API implementation.
//!
//! This crate is most useful as a binary used first and foremost for compatibility testing against
//! other ipfs implementations.
#[macro_use]
extern crate tracing;
pub mod v0;
pub mod config;
|
fn sequence_has_n_unique<const N: usize>(seq: &[u8]) -> bool {
for (i, &ch) in seq.iter().take(N.min(seq.len())).enumerate() {
if seq[..i].contains(&ch) {
return false;
}
}
true
}
fn find_marker<const N: usize>(input: &str) -> usize {
let input = input.as_bytes();
for i... |
// 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::{err_msg, Error, Fail, ResultExt},
fuchsia_async::{DurationExt, TimeoutExt},
fuchsia_bluetooth::{
error::Error as BTErro... |
// auto generated, do not modify.
// created: Mon Feb 22 23:57:02 2016
// src-file: /QtGui/qcursor.h
// dst-file: /src/gui/qcursor.rs
//
// header block begin =>
#![feature(libc)]
#![feature(core)]
#![feature(collections)]
extern crate libc;
use self::libc::*;
// <= header block end
// main block begin =>
// <= mai... |
extern crate iterator_to_hash_map;
use std::collections::HashMap;
use iterator_to_hash_map::ToHashMap;
struct Person {
id: i32,
first_name: &'static str,
last_name: &'static str,
}
#[test]
fn it_works() {
let brad = Person {
id: 1,
first_name: "Brad",
last_name: "Urani",
... |
#[doc = "Reader of register PRIVCFGR2"]
pub type R = crate::R<u32, super::PRIVCFGR2>;
#[doc = "Writer for register PRIVCFGR2"]
pub type W = crate::W<u32, super::PRIVCFGR2>;
#[doc = "Register PRIVCFGR2 `reset()`'s with value 0"]
impl crate::ResetValue for super::PRIVCFGR2 {
type Type = u32;
#[inline(always)]
... |
//! Module containing the `/ping` application command.
use crate::ApplicationCommandHandler;
use serenity::async_trait;
use serenity::model::guild::Guild;
use serenity::model::id::GuildId;
use serenity::model::interactions::application_command::ApplicationCommandInteraction;
use serenity::prelude::*;
use std::colle... |
fn main() {
let reference_to_nothing = dangle();
/*let mut s = String::from("hello");
let r1 = &s; // no problem
let r2 = &s; // no problem
let r3 = &mut s; // BIG PROBLEM
println!("{}, {}, and {}", r1, r2, r3);*/
// let mut s1 = String::from("hello");
// change1(&mut s1);
// printl... |
mod palindromes;
pub fn demo(digits: u32) {
println!("{:?}", palindromes::largest_palindrome(digits));
}
|
// auto generated, do not modify.
// created: Mon Feb 22 23:57:02 2016
// src-file: /QtCore/qtimezone.h
// dst-file: /src/core/qtimezone.rs
//
// header block begin =>
#![feature(libc)]
#![feature(core)]
#![feature(collections)]
extern crate libc;
use self::libc::*;
// <= header block end
// main block begin =>
// ... |
mod message_receiver;
mod place_runner;
mod plugin;
mod place;
mod core;
use std::{
fmt,
path::{Path, PathBuf},
error::Error,
};
use crate::{
core::{run_place, run_script, DEFAULT_PORT, DEFAULT_TIMEOUT},
place_runner::PlaceRunnerOptions,
message_receiver::RobloxMessage,
};
#[derive(Debug)]
st... |
use std::env;
use std::io::{self, Write};
use std::process;
fn main() {
let bytes = match env::args().nth(1) {
None => {
writeln!(&mut io::stderr(), "Usage: compress-escaped string")
.unwrap();
process::exit(1);
}
Some(arg) => arg.into_bytes(),
};... |
//! Coordinate systems and geometry definitions. Some conversions are dependent on the application
//! state, and so those functions are a part of the `AppContext`.
use crate::app::config;
use metfor::{Celsius, CelsiusDiff, HectoPascal, Knots, Meters, PaPS, WindSpdDir};
/// Common operations on rectangles
pub trait R... |
use std::{ptr, mem};
use utils::SIZE_MASKS;
/// Encoder takes in typed data and produces a binary buffer
/// represented as `Vec<u8>`.
pub struct Encoder {
data: Vec<u8>,
bool_index: usize,
bool_shift: u8,
}
pub trait BitEncode {
fn encode(&self, &mut Encoder);
#[inline(always)]
fn size_hint(... |
// Copyright 2018 Serde Developers
//
// 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 http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except accordin... |
pub mod compass;
pub mod lsm;
pub mod motor;
pub mod pca; |
use std::collections::HashMap;
use crate::blog_clusters::BlogClusters;
use crate::hlf_parser::{parse, HlfLhs, HlfRhs, Symbol};
use crate::shared::{path_title, HTMLTemplate};
use crate::tag::Tag; // for template filling
pub struct HomepageTemplate {
hlfs: HashMap<HlfLhs, HlfRhs>,
}
impl HTMLTemplate for HomepageT... |
// Copied from:
// https://github.com/stm32-rs/stm32-eth/blob/master/examples/ip.rs
#![no_main]
#![no_std]
extern crate stm32f4xx_hal as hal;
#[allow(unused_imports)]
use panic_semihosting;
use crate::hal::{prelude::*, serial::config::Config, serial::Serial, stm32, stm32::interrupt};
use core::cell::RefCell;
use co... |
//! Manage the music database and provide `Track`, `Playlist` and `Token` structs
//!
//! This crate can be used to search, get all playlists, find a certain token and do a lot of other
//! useful stuff. The underlying implementation uses a SQLite database and manages all information
//! with some tables. It is used in... |
pub mod client;
mod model; |
use std::cell::RefCell;
use std::cmp;
use std::collections::VecDeque;
use std::rc::Rc;
#[derive(Debug, PartialEq, Eq)]
pub struct TreeNode {
pub val: i32,
pub left: Option<Rc<RefCell<TreeNode>>>,
pub right: Option<Rc<RefCell<TreeNode>>>,
}
#[allow(dead_code)]
impl TreeNode {
#[inline]
pub fn new(v... |
use std::time::Instant;
use std::fs;
fn main() {
let start = Instant::now();
let str_test = fs::read_to_string("example.txt").expect("Error in reading file");
let all_groups = split_by_empty_line(&str_test);
let sum_pt1 = sum_part1(&all_groups);
assert_eq!(sum_pt1, 11);
let sum_pt2 = sum_part2... |
mod directed_graph;
mod test;
pub use directed_graph::{DirectedGraph};
|
use simple_cache::{Cache, CacheItem};
struct Object {
value: i32,
string: String,
}
impl CacheItem for Object {}
#[tokio::test]
async fn insert_and_get() {
let cache = Cache::new();
let object = Object {
value: 1,
string: String::from("test!"),
};
let cache_get = cache.get::<... |
#![allow(non_snake_case, non_camel_case_types, non_upper_case_globals, clashing_extern_declarations, clippy::all)]
#[link(name = "windows")]
extern "system" {}
pub type XboxLiveDeviceAddress = *mut ::core::ffi::c_void;
pub type XboxLiveEndpointPair = *mut ::core::ffi::c_void;
#[repr(transparent)]
pub struct XboxLiveEnd... |
//! query-interface - dynamically query a type-erased object for any trait implementation
//!
//! ```rust
//! #[macro_use]
//! extern crate query_interface;
//! use query_interface::{Object, ObjectClone};
//! use std::fmt::Debug;
//!
//! #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Debug)]
//! struct Foo;
//!
... |
// Copyright 2019 MaidSafe.net limited.
//
// This SAFE Network Software is licensed to you under the MIT license <LICENSE-MIT
// http://opensource.org/licenses/MIT> or the Modified BSD license <LICENSE-BSD
// https://opensource.org/licenses/BSD-3-Clause>, at your option. This file may not be copied,
// modified, or di... |
struct Person {
first_name: &'static str,
last_name: &'static str,
}
struct Team {
leader: Person,
member: Person,
}
fn main() {
println!("Dakota Hill's Testing Suite");
println!("Current Test: Structs");
println!("---------------------------");
let iron_man = Person { first_name: "Tony",... |
mod colour;
use ansi_term::Colour;
use colour::hash_colour;
use regex::{Captures, Regex};
use std::io::{self, BufRead};
fn main() {
// TODO: make the regex adjustable from the CLI
let pattern = Regex::new(r"((0x)?(\d|[a-fA-F]){6}(…|\.)?(\d|[a-fA-F]){6,}|\d{3,})").unwrap();
let stdin = io::stdin();
fo... |
use winapi::_core::ops::Deref;
use winapi::Interface;
use winapi::shared::ntdef::{HRESULT, ULONG};
use winapi::ctypes::{c_void, c_ulong, c_ushort, c_uchar};
use winapi::shared::guiddef::{GUID, REFIID};
#[inline]
fn uuid(a: c_ulong,
b: c_ushort,
c: c_ushort,
d1: c_uchar,
d2: c_uchar,
... |
use crate::rtrs::textures::Texture;
use crate::Color;
use crate::HitRecord;
use crate::Material;
use crate::Point;
use crate::Ray;
use crate::Vector;
use std::sync::Arc;
#[derive(Debug)]
pub struct Lambertian {
pub albedo: Arc<dyn Texture>,
}
impl Lambertian {
pub fn new(albedo: Arc<dyn Texture>) -> Self {
... |
use crate::class_file::unvalidated::read::FromReader;
use crate::class_file::unvalidated::ClassFile;
use crate::class_file::unvalidated::ConstantIdx;
use crate::class_file::unvalidated::Error;
use std::fmt;
use std::io::{Read, Seek, SeekFrom};
pub struct InstructionDisplay<'a, 'b> {
instruction: &'a Instruction,
... |
extern crate spacesuit;
use spacesuit::{prove, verify, SpacesuitError, Value};
extern crate curve25519_dalek;
extern crate bulletproofs;
use bulletproofs::{BulletproofGens, PedersenGens};
fn spacesuit_helper(
bp_gens: &BulletproofGens,
inputs: Vec<Value>,
outputs: Vec<Value>,
) -> Result<(), SpacesuitErr... |
pub mod foo;
pub mod display;
pub fn lol(x: i32) {
for y in 0..x {
println!("{}", y);
}
}
|
pub struct Gameboard {
pub cells: Vec<Vec<(u8, bool)>>
}
impl Gameboard {
pub fn new(cells: Vec<Vec<(u8, bool)>>) -> Gameboard {
Gameboard {
cells: cells,
}
}
// get value
pub fn char(&self, ind: [usize; 2]) -> Option<char> {
Some(match self.c... |
use core::{mem, ptr};
use orbclient::{Color, Renderer};
use std::fs::find;
use std::proto::Protocol;
use uefi::guid::Guid;
use uefi::status::{Error, Result};
use crate::display::{Display, ScaledDisplay, Output};
use crate::image::{self, Image};
use crate::key::{key, Key};
use crate::redoxfs;
use crate::text::TextDispl... |
use proc_macro2::Span;
fn main() {
let span = Span::call_site();
println!("span: {:?}", span);
#[cfg(procmacro2_semver_exempt)]
println!("source file: {:?}", span.source_file());
}
|
use std::{cmp::Eq, collections::HashSet, hash::Hash};
pub trait CellAutoSpec {
type T;
fn neighbors(x: &Self::T) -> Vec<Self::T>;
fn rule(alive: bool, alive_neighbors: usize) -> bool;
}
pub struct CellAuto<Spec: CellAutoSpec> {
pub cells: HashSet<Spec::T>,
}
impl<Spec: CellAutoSpec> CellAuto<Spec> {
... |
use std::net::TcpStream;
use std::io::prelude::*;
use std::io;
use color_strip::ColorStrip;
pub struct OpcStrip {
stream: TcpStream,
data: Vec<u8>,
pub led_count: usize,
reversed: bool
}
impl OpcStrip {
pub fn connect(led_count: usize, reversed: bool) -> io::Result<OpcStrip> {
let mut dat... |
use crate::config::CONFIG;
use crate::init::AppConnections;
use crate::{model::User, schema::user::dsl::*};
use async_session::{async_trait, Session, SessionStore};
use axum::http::HeaderMap;
use axum::{
extract::{Extension, FromRequest},
http::{self, StatusCode},
BoxError, Json,
};
use cookie::Cookie;
use ... |
use graphics::math::*;
use std::rc::Rc;
use std::cell::RefCell;
use std::collections::HashMap;
use interpolation::Lerp;
use super::AABB::AABB;
use super::config;
use super::map::{Map, AreaIndex};
pub struct MovingObject {
pub object_id: String,
pub old_position: Vec2d,
pub position: Vec2d,
pub old_spe... |
//! An `Edge` is a direct edge between `Block` in `ControlFlowGraph`
//!
//! A Falcon IL `Edge` has an optional condition. When the condition is present, the `Edge` is,
//! "Guarded," by the `Expression` in the condition. `Edge` conditions are `Expressions` that must
//! evaluate to a 1-bit `Constant`. When the conditi... |
use std::fmt::{Debug, Display};
use std::iter::Sum;
pub trait Summary {
fn summarize(&self) -> String;
// with default implementation
fn summarize2(&self) -> String {
String::from("Read more...")
}
}
pub struct Tweet {
pub username: String,
pub content: String,
}
impl Summary for Twe... |
#![allow(non_snake_case, non_camel_case_types, non_upper_case_globals, clashing_extern_declarations, clippy::all)]
#[cfg(feature = "Globalization_Collation")]
pub mod Collation;
#[cfg(feature = "Globalization_DateTimeFormatting")]
pub mod DateTimeFormatting;
#[cfg(feature = "Globalization_Fonts")]
pub mod Fonts;
#[cfg(... |
/* Copyright (C) 2016 Yutaka Kamei */
extern crate iron;
extern crate router;
extern crate rustc_serialize;
extern crate time;
extern crate scim;
use std::process;
use std::io::{self, Write};
use std::path::PathBuf;
use std::sync::Mutex;
use iron::{Chain, Iron, IronResult};
use iron::error::IronError;
use iron::request... |
fn main() {
let mut sorted = vec![3,2,54,1,9,2,6];
for v in sorted.iter_mut(){
println!("{}", v.to_string());
}
}
|
use crate::message_render::MessageRender;
use crate::name::Name;
use crate::rr_type::RRType;
use std::net::{Ipv4Addr, Ipv6Addr};
use anyhow::Result;
pub fn name_to_wire(render: &mut MessageRender, name: &Name) -> Result<()> {
render.write_name(name, true)
}
pub fn name_uncompressed_to_wire(render: &mut MessageRe... |
use ggez;
use ggez::event;
use ggez::graphics::{self, Color};
use ggez::{Context, GameResult};
use glam::*;
use rand;
use rand::Rng;
use rand::SeedableRng;
use std::time::SystemTime;
const BLACK: Color = Color {
r: 1.0,
g: 1.0,
b: 1.0,
a: 1.0,
};
const WHITE: Color = Color {
r: 0.0,
g: 0.0,
... |
use openexr_sys as sys;
pub use crate::core::{
error::Error,
refptr::{OpaquePtr, Ref, RefMut},
PixelType,
};
use std::marker::PhantomData;
use std::ffi::{CStr, CString};
use imath_traits::{Bound2, Vec2, Zero};
type Result<T, E = Error> = std::result::Result<T, E>;
pub struct FrameBuffer {
pub(crate... |
use num_bigint::BigUint;
use stark_curve::FieldElement;
use std::fmt::Write;
use std::fs::File;
use std::io::{self, BufRead};
use std::str::FromStr;
use std::{env, fs, path::Path};
const FULL_ROUNDS: usize = 8;
const PARTIAL_ROUNDS: usize = 83;
/// Generates poseidon_consts.rs
pub fn main() {
let manifest_dir = e... |
//! A simple example of how to use PickleDB. It includes:
//! * Creating a new DB
//! * Loading an existing DB from a file
//! * Setting and getting key-value pairs of different types
use pickledb::{PickleDb, PickleDbDumpPolicy, SerializationMethod};
use serde::{Deserialize, Serialize};
use std::fmt::{self, Display, F... |
use super::{ClassMetrics, Registry, RequestMetrics, RetrySkipped, StatusMetrics};
use http;
use linkerd2_metrics::{latency, Counter, FmtLabels, FmtMetric, FmtMetrics, Histogram, Metric};
use std::fmt;
use std::hash::Hash;
use std::sync::{Arc, Mutex};
use std::time::Duration;
use tokio_timer::clock;
use tracing::trace;
... |
use crate::io::Buf;
use crate::postgres::database::Postgres;
use byteorder::NetworkEndian;
use std::str;
#[derive(Debug)]
pub(crate) enum Authentication {
/// The authentication exchange is successfully completed.
Ok,
/// The frontend must now take part in a Kerberos V5 authentication dialog (not describe... |
// 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 http://opensource.org/licenses/MIT>, at your option.
// All files in the project carrying such notice may not be copied, modified, or distributed
// except according ... |
use std::borrow::Cow;
use std::iter::FromIterator;
#[derive(Debug, Clone, PartialEq)]
struct Country<'a> {
name: Cow<'a, str>,
cities: Vec<Cow<'a, str>>,
}
#[allow(dead_code)]
impl<'a> Country<'a> {
fn new<S>(name: S) -> Country<'a>
where
S: Into<Cow<'a, str>>,
{
Country {
... |
use serde::{Deserialize, Serialize};
use std::collections::hash_map::RandomState;
use std::collections::HashMap;
use std::default::Default;
use bollard::models::ContainerInspectResponse;
#[derive(Debug, Deserialize, Serialize, Clone)]
pub struct PromConfigLabel {
pub job: String,
pub name: String,
pub id:... |
// copyright 2017 Kaz Wesley
//! Classic Blake in a Rustic setting
#![no_std]
extern crate block_buffer;
pub extern crate digest;
mod consts;
use block_buffer::BlockBuffer;
use core::mem;
use digest::generic_array::GenericArray;
pub use digest::Digest;
#[derive(Debug, Clone, Copy)]
#[repr(C)]
struct State<T> {
... |
#[derive(Copy, Clone, Eq, PartialEq, PartialOrd)]
pub struct Dim {
width: usize,
height: usize,
}
impl Dim {
pub fn new(width: usize, height: usize) -> Dim {
Dim { width, height }
}
}
impl Dimension for Dim {
fn width(&self) -> usize {
self.width
}
fn height(&self) -> usiz... |
use ::ir::variant::VariantType;
use ::FieldReference;
error_chain! {
links {
JsonParseError(
::frontend::protocol_json::Error,
::frontend::protocol_json::ErrorKind);
}
errors {
CompilerError(t: CompilerError) {
description("error under compilation")
... |
//! Parsing and processing for this form:
//! ```ignore
//! py_compile!(
//! // either:
//! source = "python_source_code",
//! // or
//! file = "file/path/relative/to/$CARGO_MANIFEST_DIR",
//!
//! // the mode to compile the code in
//! mode = "exec", // or "eval" or "single"
//! // the path ... |
// 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 ... |
#![no_std]
#![no_main]
extern crate libc;
use libc::{c_int,c_char,printf};
#[repr(C)]
struct NATSParser<'a> {
cb: extern fn(&'a mut NATSd) -> c_int,
cs: c_int,
user_data: &'a mut NATSd
}
#[link(name = "natsparser", kind="static")]
extern "C" {
fn natsparser_init (
parser: *mut NATSParser
... |
use std::env;
use std::fs::{metadata, read_to_string};
use std::io::{stdout, BufWriter, Write};
use std::process;
fn main() {
let args: Vec<String> = env::args().collect();
if args.len() < 2 {
eprintln!("{}: flie name not given", args[0]);
process::exit(1);
}
for arg in args.iter().sk... |
// Copyright 2014 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 ... |
pub struct Solution;
impl Solution {
pub fn group_anagrams(strs: Vec<String>) -> Vec<Vec<String>> {
use std::collections::HashMap;
let mut map = HashMap::new();
for word in strs {
let mut key = word.as_bytes().to_vec();
key.sort();
map.entry(key).or_inser... |
extern crate gcc;
use std::process::Command;
use std::path::Path;
fn main() {
// check if `easy-ecc` has been downloaded.
if !Path::new("dep/easy-ecc/.git").exists() {
// if not, tell git to initialize submodules.
let cmd = Command::new("git")
.args(&["submodule", "update", "--init... |
use crate::ast;
use crate::{
Parse, ParseError, Parser, Peek, Peeker, Resolve, ResolveError, ResolveOwned, Spanned, Storage,
ToTokens,
};
use runestick::Source;
use std::borrow::Cow;
/// Parse an object expression.
///
/// # Examples
///
/// ```rust
/// use rune::{testing, ast};
///
/// testing::roundtrip::<as... |
pub mod coingecko;
pub mod cryptocompare;
|
use std::{time::Duration, collections::HashMap};
use ggez::audio as gaudio;
use ggez::audio::SoundSource;
pub type SoundData = gaudio::SoundData;
pub type PlayableSound = gaudio::Source;
pub type SoundHandler = usize;
#[derive(Clone)]
pub struct SoundPlayFlags {
fadein_mills: u64,
pitch: f32,
repeat: boo... |
use yarapi::rest::activity::DefaultActivity;
use yarapi::rest::Session;
pub async fn attach_debugger(session: Session, activity: DefaultActivity) -> anyhow::Result<()> {
drop(session);
drop(activity);
unimplemented!()
}
|
extern crate cmake;
use std::env;
fn main() {
let dst = cmake::Config::new("wabt")
.define("BUILD_TESTS", "OFF")
.build();
println!("cargo:rustc-link-search=native={}/build/", dst.display());
println!("cargo:rustc-link-lib=static=wabt");
// We need to link against C++ std lib
... |
//! GraphQL expression plan.
use std::cell::RefCell;
use std::collections::{HashMap, HashSet};
use std::rc::Rc;
use timely::dataflow::channels::pact::Pipeline;
use timely::dataflow::operators::generic::Operator;
use timely::dataflow::operators::{Delay, Exchange};
use timely::dataflow::scopes::child::Iterative;
use ti... |
use std::rc::Rc;
use crate::{Material, Point3, Ray, Vec3};
pub struct HitRecord {
pub p: Point3,
pub normal: Vec3,
pub mat: Rc<dyn Material>,
pub t: f64,
pub front_face: bool,
}
impl HitRecord {
pub fn face_normal(r: &Ray, outward_normal: Vec3) -> (bool, Vec3) {
let front_face = r.dir... |
use crate::{CameraState, ScaledCamera2dBundle, ScaledOrthographicProjection};
use game_lib::{
bevy::{
prelude::*,
render::camera::{Camera, CameraProjection},
},
tracing::{self, instrument},
};
#[instrument(skip(commands))]
pub fn setup(mut commands: Commands) {
let ui_camera = commands.... |
#[macro_use]
extern crate criterion;
extern crate telamon_gen;
use criterion::Criterion;
use telamon_gen::lexer;
use std::ffi::OsStr;
use std::fs;
fn criterion_benchmark(c: &mut Criterion) {
let entries = fs::read_dir("cc_tests/src/").unwrap();
for entry in entries {
if let Ok(entry) = entry {
... |
use futures::FutureExt;
use grpc_binary_logger::{sink, BinaryLoggerLayer, Sink};
use grpc_binary_logger_proto::GrpcLogEntry;
use grpc_binary_logger_test_proto::{
test_client::TestClient,
test_server::{self, TestServer},
};
use std::{
net::SocketAddr,
sync::{Arc, Mutex},
};
use tokio_stream::wrappers::Tc... |
use agent_client::*;
pub mod agent_client;
#[tokio::main]
async fn main() {
let plaintext = vec![
0x4c, 0x61, 0x64, 0x69, 0x65, 0x73, 0x20, 0x61, 0x6e, 0x64, 0x20, 0x47, 0x65, 0x6e, 0x74,
0x6c, 0x65, 0x6d, 0x65, 0x6e, 0x20, 0x6f, 0x66, 0x20, 0x74, 0x68, 0x65, 0x20, 0x63, 0x6c,
0x61, 0x73, 0... |
// 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 std::{
collections::{BTreeMap, BTreeSet},
sync::Arc,
time::Duration,
};
use crate::{AbstractTaskRegistry, TaskId, TaskRegistration, TaskTracker};
/// Function that extracts metric attributes from job metadata.
///
/// Note that some attributes like `"status"` will automatically be set/overwritten to e... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.