text stringlengths 8 4.13M |
|---|
// Copyright 2019, 2020 Wingchain
//
// 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... |
#[derive(Debug)]
pub struct Rectangle {
length: u32,
width: u32,
}
impl Rectangle {
pub fn can_hold(&self, other: &Rectangle) -> bool {
self.length > other.length && self.width > other.width
}
}
#[derive(Debug)]
pub struct Guess {
value: u32,
}
impl Guess {
pub fn new(value: u32) -> G... |
pub fn solve_puzzle_part_1(input: &str) -> String {
let hw: u32 = (0..128)
.map(|n| format!("{}-{}", input, n))
.map(|s| knot_hash(s.as_bytes()))
.map(|h| h.iter().map(|b| u32::from(hamming_weight(*b))).sum::<u32>())
.sum();
hw.to_string()
}
pub fn solve_puzzle_part_2(input: &s... |
/**
* 参照先がない状態、`dangling pointer`はC言語ではプログラマが気をつけなければいけない。
* ライフタイムにより、rustではそれがない。
* 値を貸している間に参照先をムーブしようとすると、コンパイル時にエラーになる。
*/
fn main() {
// 本来`s`のライフタイムはこの関数の最後まで。
let s = "owned data".to_string();
// `{}`で囲んだブロックはライフタイムを区切る。
{
// `s`はここで、ムーブしてしまうので、ここでライフタイム終わり
// `t`のライフタイムはこの... |
//extern crate rand
//extern crate failure;
use std::str::Lines;
use std::str;
use std::env::args;
use std::error::Error;
use std::io::Read;
use std::io::prelude;
use std::fs::File;
// use self::failure::Error;
//use rand::Rng;
pub use lib::asm_info::CodeInfo;
fn convert_line(line: Vec<String>, mut info: &CodeInfo) -... |
// Copyright (C) 2020 Sebastian Dröge <sebastian@centricular.com>
//
// Licensed under the MIT license, see the LICENSE file or <http://opensource.org/licenses/MIT>
use super::*;
use std::fmt;
/// `Seek-Style` header ([RFC 7826 section 18.47](https://tools.ietf.org/html/rfc7826#section-18.47)).
#[derive(Debug, Clone... |
use jargon_args::Jargon;
use std::process::exit;
use std::collections::HashMap;
const URL: &str = "https://api.myip.com";
const HELP: &str = "\
myip [OPTIONS]
OPTIONS:
-a, --all Display all IP information
-C, --code Display two letter country code
-c, --country Display only country
-h, -... |
pub mod api;
use crate::models::user::UserAuth;
use crate::models::DataPoolSqlite;
use crate::services::file::list_files_service;
use actix_web::*;
use actix_web::{web, HttpResponse, Result};
use log::error;
use tera::{Context, Tera};
// register page
pub async fn register_page(tml: web::Data<Tera>) -> Result<HttpResp... |
use crate::{
components::level::LevelPrefabData, resources::prefabs::PrefabRegistry, utils::hierarchy_util,
};
use amethyst::{
assets::{AssetLoaderSystemData, Handle, Prefab},
controls::HideCursor,
core::Transform,
ecs::Entity,
input::{is_key_down, is_mouse_button_down},
prelude::*,
rend... |
use ray::Ray;
use super::intersection::Intersection;
pub trait Geometry {
fn intersect(&self, &Ray) -> Option<Intersection>;
}
|
iter range(lo: uint, hi: uint) -> uint {
let lo_ = lo;
while lo_ < hi { put lo_; lo_ += 1u; }
}
fn create_index<T>(index: [{a: T, b: uint}], hash_fn: fn(T) -> uint) {
for each i: uint in range(0u, 256u) { let bucket: [T] = []; }
}
fn main() { }
|
#![feature(type_alias_impl_trait)]
#![feature(trait_alias)]
#![feature(core_intrinsics)]
#![feature(array_chunks)]
#![allow(unused)]
#![deny(unused_must_use)]
#[macro_use]
extern crate serde;
extern crate derive as _der;
use std::sync::Arc;
use actix::{Message, SystemService, Actor};
use crate::node::NodeController;... |
use std::{
fs::{read, File},
io::Write,
path::PathBuf,
};
use anyhow::Context;
use console::style;
use indicatif::ProgressBar;
use rcgen::{
generate_simple_self_signed, BasicConstraints, Certificate as GenCertificate,
CertificateParams, DistinguishedName, DnType, ExtendedKeyUsagePurpose, IsCa, KeyP... |
use crate::common::factories::prelude::*;
use common::rsip::{self, headers::*, prelude::*, Method, Uri, Version};
use std::{convert::TryInto, net::IpAddr as StdIpAddr};
pub fn response(from_uri: Option<Uri>, to_uri: Option<Uri>) -> rsip::Response {
let mut headers: rsip::Headers = Randomized::default();
if let... |
#[doc = "Register `M4SR` reader"]
pub type R = crate::R<M4SR_SPEC>;
#[doc = "Field `FDATAL` reader - Failing data low"]
pub type FDATAL_R = crate::FieldReader<u32>;
impl R {
#[doc = "Bits 0:31 - Failing data low"]
#[inline(always)]
pub fn fdatal(&self) -> FDATAL_R {
FDATAL_R::new(self.bits)
}
}
... |
#[doc = "Register `CCMR2_Output` reader"]
pub type R = crate::R<CCMR2_OUTPUT_SPEC>;
#[doc = "Register `CCMR2_Output` writer"]
pub type W = crate::W<CCMR2_OUTPUT_SPEC>;
#[doc = "Field `CC3S` reader - Capture/Compare 3 selection"]
pub type CC3S_R = crate::FieldReader<CC3S_A>;
#[doc = "Capture/Compare 3 selection\n\nValue... |
#![cfg_attr(feature="clippy", feature(plugin))]
#![cfg_attr(feature="clippy", plugin(clippy))]
#![feature(conservative_impl_trait)]
#![feature(collections_bound)]
#![feature(btree_range)]
#![feature(step_by)]
#![allow(dead_code)]
extern crate chrono;
extern crate nom;
mod time_unit;
mod schedule;
pub use schedule::S... |
//! Representation of the S-expression tree.
#![deny(missing_docs)]
#![deny(unsafe_code)]
use std::str::FromStr;
use std::fmt::{self, Display, Debug, Formatter};
/**
* A single values with symbols represented using `String`.
*
* ```rust
* use atoms::StringValue;
*
* let int = StringValue::int(12);
* let float... |
// Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.
//
// Portions Copyright 2017 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-BSD-3-Clause file.
//
// Copyright © 2019 Intel Corporation
//
// SPDX-... |
#[doc = "Register `SWIER2` reader"]
pub type R = crate::R<SWIER2_SPEC>;
#[doc = "Register `SWIER2` writer"]
pub type W = crate::W<SWIER2_SPEC>;
#[doc = "Field `SWI34` reader - Software interrupt on event"]
pub type SWI34_R = crate::BitReader<SWI34W_A>;
#[doc = "Software interrupt on event\n\nValue on reset: 0"]
#[deriv... |
/*!
Type-level representatins of a chain of field accesses (`FieldPath`),
and multiple field accesses (`FieldPathSet`).
*/
#![allow(non_snake_case, non_camel_case_types)]
use core_extensions::MarkerType;
use std_::marker::PhantomData;
use crate::type_level::_private::TString;
use crate::type_level::collection_trai... |
mod manager;
pub use self::manager::Manager;
use crate::api::Api;
use crate::http::client::Client;
use std::ops::{Deref, DerefMut};
pub struct Connection {
pub client: Client,
api: Api,
}
impl Connection {
pub fn new(host: &str) -> Connection {
let client = Client::new(host);
let api = Ap... |
use std::process::Command; // Run programs
use assert_cmd::prelude::*; // Add methods on commands
use predicates::prelude::*; // Used for writing assertions
#[test]
fn command_help_shows_usage_and_options() -> Result<(), Box<std::error::Error>> {
let mut cmd = Command::main_binary()?;
cmd.arg("-h")
.... |
/// Solves the Day 09 Part 1 puzzle with respect to the given input.
pub fn part_1(input: String) {
let (heights, w, h) = parse_input(input);
let mut sum = 0;
for r in 0..h {
for c in 0..w {
let mut neighbours = Vec::<u32>::new();
if r > 0 {
neighbours.push(h... |
#[doc = "Register `COUNTR` reader"]
pub type R = crate::R<COUNTR_SPEC>;
#[doc = "Field `COUNT` reader - COUNT"]
pub type COUNT_R = crate::FieldReader<u32>;
impl R {
#[doc = "Bits 0:31 - COUNT"]
#[inline(always)]
pub fn count(&self) -> COUNT_R {
COUNT_R::new(self.bits)
}
}
#[doc = "TAMP monotonic... |
mod element;
mod html_entity;
pub use element::*;
pub use html_entity::*;
|
use crate::days::day6::{default_input, parse_input};
pub fn run() {
println!("{}", customs_groups_str(default_input()).unwrap())
}
pub fn customs_groups_str(input : &str) -> Result<usize, ()> {
customs_groups(parse_input(input))
}
pub fn customs_groups(groups : Vec<Vec<&str>>) -> Result<usize, ()> {
Ok(g... |
use std::os::raw::c_ulong;
use pyo3::prelude::*;
#[link(name = "z")]
extern "C" {
fn gzflags() -> c_ulong;
}
#[pyfunction]
fn add(x: usize, y: usize) -> usize {
let _version = unsafe { libz_sys::zlibVersion() };
let _flags = unsafe { gzflags() };
let sum = x + y;
sum
}
#[pymodule]
fn lib_with_di... |
#[macro_use]
extern crate may;
use may::coroutine::yield_now;
fn main() {
let h = go!(move || {
println!("hi, I'm parent");
let v = (0..100)
.map(|i| {
go!(move || {
println!("hi, I'm child{i}");
yield_now();
p... |
use anyhow::{anyhow, Result};
use pasture_core::math::Alignable;
use serde::{Deserialize, Serialize};
use serde_json::{Map, Value};
use std::{
collections::HashMap,
convert::TryFrom,
convert::TryInto,
io::{BufRead, Seek, SeekFrom, Write},
};
use super::{read_json_header, write_json_header};
/// A refe... |
use super::KafkaConfig;
use std::collections::HashMap;
use std::ascii::AsciiExt;
use std::iter::FromIterator;
use std::time::Duration;
use std::fs::File;
//use std::io::prelude::*;
use std::result;
use kafka::consumer::{Consumer, FetchOffset, GroupOffsetStorage, Message, MessageSets};
use std::io::{Error, Read, Writ... |
use std::collections::{HashMap, HashSet};
use std::io::{self};
fn main() -> io::Result<()> {
let files_results = vec![("test.txt", 7, 6), ("input.txt", 535, 212)];
for (f, result_1, result_2) in files_results.into_iter() {
println!("File: {}", f);
let file_content: Vec<String> = std::fs::read_t... |
#![allow(dead_code)]
mod gears;
extern crate image;
use image::{ImageBuffer, RgbImage, Rgb};
const MDL_NAME: &str = "piramid";
const WIDTH: u32 = 100;
const HEIGHT: u32 = 100;
fn main() {
let input_mdl = format!("./models/{}.mdl", MDL_NAME);
let piramid = gears::model::Model::from_mdl(&*input_mdl);
println!("{... |
use board;
use moves;
use movement;
#[test]
fn layout() {
use fen;
use zobrist;
zobrist::init();
let mut main_board : board::chessboard = board::init();
fen::parse("rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1", &mut main_board);
verify_squares(&main_board);
fen::parse("8/4r1p... |
use std::collections::hash_map::Entry;
use std::collections::{HashSet, HashMap};
use std::path::Path;
use std::sync::{Arc, RwLock};
use meilidb_schema::Schema;
mod custom_settings;
mod docs_words_index;
mod documents_addition;
mod documents_deletion;
mod documents_index;
mod error;
mod index;
mod main_index;
mod raw_i... |
// Copyright 2018-2019 Mozilla
//
// 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 in writing, sof... |
use input::get_name;
use output::{goodbye, hello};
mod day_kind;
mod input;
mod output;
fn main() {
let name = get_name();
hello(&name);
goodbye(&name);
}
|
// Copyright 2021 MaidSafe.net limited.
//
// This SAFE Network Software is licensed to you under the MIT license <LICENSE-MIT
// https://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 d... |
use hydroflow::hydroflow_syntax;
pub fn main() {
let mut flow = hydroflow_syntax! {
source_iter(0..10)
-> filter_map(|n| {
let n2 = n * n;
if n2 > 10 {
Some(n2)
}
else {
None
}
})
-> flat_map(... |
// Copyright 2019 Parity Technologies
//
// 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 agree... |
// Copyright 2013-2018, The Gtk-rs Project Developers.
// See the COPYRIGHT file at the top-level directory of this distribution.
// Licensed under the MIT license, see the LICENSE file or <http://opensource.org/licenses/MIT>
use Cancellable;
use Error;
use ffi;
use glib;
use glib::object::IsA;
use glib::translate::*;... |
pub mod if_statement;
pub mod loops;
pub mod match_statement;
pub mod combination_lock; |
use super::Client;
use crate::{
bson::Document,
client::session::ClusterTime,
error::Result,
options::{SessionOptions, TransactionOptions},
runtime,
ClientSession as AsyncClientSession,
};
/// A MongoDB client session. This struct represents a logical session used for ordering sequential
/// op... |
use rand::{Rng, distributions::{IndependentSample, Range}};
use std::fmt::{self, Display};
use std::str::FromStr;
use std::string::ToString;
#[derive(Clone, Debug)]
pub struct DiceExpr {
rolls: i64,
dice: i64,
sides: i64,
modifier: Option<String>,
value: i64,
versus: bool,
tag: String,
... |
// ===============================================================================
// Authors: AFRL/RQQA
// Organization: Air Force Research Laboratory, Aerospace Systems Directorate, Power and Control Division
//
// Copyright (c) 2017 Government of the United State of America, as represented by
// the Secretary of th... |
use shorthand::ShortHand;
struct NotClone;
#[derive(ShortHand)]
struct Example {
#[shorthand(enable(clone))]
value: NotClone,
}
fn main() {}
|
use std::collections::{HashMap, HashSet};
use std::iter::FromIterator;
use std::fs::File;
use std::io::{self, BufReader};
use std::io::prelude::*;
use std::error::Error;
fn parse_input(file: &str) -> Result<HashMap<String, Vec<String>>, Box<dyn Error>> {
let mut map = HashMap::new();
let f = File::open(file)?... |
fn distance(a: &(i32, i32), b: &(i32, i32)) -> i32 {
(a.0 - b.0).abs() + (a.1 - b.1).abs()
}
fn main() {
use std::io::{self, BufRead};
let stdin = io::stdin();
let mut coordinates = Vec::new();
for line in stdin.lock().lines() {
let line = line.unwrap();
let mut xy = line.split(",... |
extern crate chrono;
extern crate getopts;
// std libs
use std::io;
use std::fs::{self, DirEntry};
use std::path::Path;
use std::os::unix::fs::PermissionsExt;
use std::env;
// getops
use getopts::Options;
// chrono
use chrono::prelude::NaiveDateTime;
/// print_all_file_info
///
/// Prints all sorts of file informat... |
#[macro_use]
extern crate structure;
use std::fs::File;
use std::io::{Read,Seek,SeekFrom};
#[derive(Debug)]
pub struct ImInfo {
width: i64,
height: i64,
format: String,
}
pub fn imsz(fname: &str) -> ImInfo {
let mut info = ImInfo { width: 0, height: 0, format: String::from("unknown")};
let mut ... |
use std::sync::RwLock;
// ------------------------------------------------------------------------------------------------
// Public Macros
// ------------------------------------------------------------------------------------------------
///
/// Used by the library to report user messages, in interactive mode this ... |
#[doc = "Register `CFBLR` reader"]
pub type R = crate::R<CFBLR_SPEC>;
#[doc = "Register `CFBLR` writer"]
pub type W = crate::W<CFBLR_SPEC>;
#[doc = "Field `CFBLL` reader - Color Frame Buffer Line Length"]
pub type CFBLL_R = crate::FieldReader<u16>;
#[doc = "Field `CFBLL` writer - Color Frame Buffer Line Length"]
pub ty... |
mod file;
mod guid_group;
mod memory;
mod store_value;
mod variable;
mod vendor_group;
use self::guid_group::GuidGroup;
use self::store_value::StoreValue;
use self::variable::VariableStore;
use self::vendor_group::VendorGroup;
pub use self::file::FileStore;
pub use self::memory::MemoryStore;
|
use crate::syntax_kind::SyntaxKindId;
use text_unit::TextRange;
use text_unit::TextUnit;
use core::fmt;
use std::fmt::Formatter;
use std::fmt::Error;
use smol_str::SmolStr;
use crate::syntax::SyntaxDefinition;
use crate::escape_str;
use rowan::Types;
#[derive(Debug, Eq, PartialEq, Copy, Clone)]
pub struct TokenInfo {
... |
use super::*;
use cgmath::{Point3, Matrix4};
type Subject = Illuminator;
mod radiance_and_direction {
use super::*;
#[test]
fn it_builds_a_vector_pointing_towards_the_light() {
let origin = Point3::new(4.0, 5.0, 6.0);
let intersection = Intersection::new(0.0, origin, Vector3::new(0.0, 0.0... |
pub mod sip_server;
pub fn debug(udp_tuple: &models::server::UdpTuple) {
println!(
"\nRequest from {}: \n{}",
udp_tuple.peer,
String::from_utf8(udp_tuple.bytes.to_vec()).expect("string")
);
}
|
#[macro_use]
extern crate log;
mod cpu;
mod gameboy;
mod instruction;
mod mmu;
mod registers;
pub use gameboy::Gameboy;
|
//! The module contains [`Peaker`] trait and its implementations to be used in [`Height`] and [`Width`].
//!
//! [`Width`]: crate::settings::width::Width
//! [`Height`]: crate::settings::height::Height
/// A strategy of width function.
/// It determines the order how the function is applied.
pub trait Peaker {
///... |
use azure_core::AddAsHeader;
use http::request::Builder;
#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord)]
pub struct BlobContentMD5([u8; 16]);
impl From<md5::Digest> for BlobContentMD5 {
fn from(md5: md5::Digest) -> Self {
BlobContentMD5(md5.0)
}
}
impl AddAsHeader for BlobContentMD5 {
fn ... |
pub fn raindrops(n: u32) -> String {
let mut output = String::new();
if n % 3 == 0 { output.push_str("Pling"); }
if n % 5 == 0 { output.push_str("Plang"); }
if n % 7 == 0 { output.push_str("Plong"); }
if !output.is_empty() { output } else { n.to_string() }
}
|
/*!
```rudra-poc
[target]
crate = "http"
version = "0.1.19"
[report]
issue_url = "https://github.com/hyperium/http/issues/352"
issue_date = 2019-11-16
rustsec_url = "https://github.com/RustSec/advisory-db/pull/217"
rustsec_id = "RUSTSEC-2019-0033"
[[bugs]]
analyzer = "Manual"
bug_class = "Other"
rudra_report_location... |
use std::collections::HashMap;
use std::hash::Hash;
use std::io;
use std::io::prelude::*;
pub fn find_common_keys<K, V>(hms: &[HashMap<K, V>]) -> Vec<K>
where K: Clone + Eq + Hash
{
let mut keycount: HashMap<&K, usize> = HashMap::new();
for key in hms.iter().flat_map(|hm| hm.keys()) {
let counter =... |
#[doc = "Register `OPTSR2_CUR` reader"]
pub type R = crate::R<OPTSR2_CUR_SPEC>;
#[doc = "Field `SRAM2_RST` reader - SRAM2 erase when system reset"]
pub type SRAM2_RST_R = crate::BitReader;
#[doc = "Field `BKPRAM_ECC` reader - Backup RAM ECC detection and correction disable"]
pub type BKPRAM_ECC_R = crate::BitReader;
#[... |
use combine::*;
use combine::stream::Stream;
use combine::parser::char::*;
use crate::expr::*;
parser! {
pub fn id_cont[I]()(I) -> char where [
I: Stream<Item=char>,
] {
char('\'').or(alpha_num())
}
}
parser! {
pub fn id[I]()(I) -> String where [
I: Stream<Item=char>,
] {
... |
use crate::solutions::Solution;
use itertools::Itertools;
pub struct Day04 {}
fn bounds(input: &str) -> [i32; 2] {
let mut numbers = input.split('-').map(|t| t.parse::<i32>().unwrap());
[numbers.next().unwrap(), numbers.next().unwrap()]
}
// Full-on iterator implementation (slower)
// fn valid(password: &i32... |
use std::{
cmp,
collections::HashMap,
fmt,
io::{self, Write},
};
use console::{style, StyledObject};
use enum_map::EnumMap;
use crate::{
data_type::{Item, ItemType, Pull, Rarity},
report::Report,
};
/// Contains a summary of basic stats regarding a gacha log
#[derive(Debug)]
pub struct Summar... |
// use std::net::{TcpListener, TcpStream, UdpSocket};
use std::io::{Read};
use crc::{crc32, Hasher32};
#[derive(Debug)]
pub struct SpacePacket {
pub version: u8,
pub packet_type: u8,
pub sec_hdr_flag: u8,
pub apid: u16,
pub seq_flags: u8,
pub seq_num: u16,
pub data_len: u16,
pub payloa... |
use super::Auth;
use anyhow::Result;
use async_trait::async_trait;
use sha2::{Digest, Sha224};
use std::collections::HashSet;
pub struct ConfigAuthenticator {
store: HashSet<String>,
}
impl ConfigAuthenticator {
pub fn new(passwords: Vec<String>) -> Result<ConfigAuthenticator> {
let mut s: HashSet<Str... |
use crate::projects_and_tasks::{list_with_names::ListWithNames, task::Task};
#[derive(Debug, PartialEq, Clone)]
pub struct Tasks {
tasks: Vec<Task>,
}
impl ListWithNames<Task> for Tasks {
fn items(&self) -> std::slice::Iter<Task> {
self.tasks.iter()
}
}
pub struct TasksBuilder {
tasks: Vec<Ta... |
use ocl;
use std::ffi::CString;
use std::marker::Unsize;
use super::{OpenCL, OpenCLDevice};
use super::super::super::compute_device::ComputeDevice;
use super::super::super::context::{Context, ContextCtor};
use super::super::super::error::{Error, ErrorKind, Result};
use super::super::super::extension_package::{Extension... |
use nanoda_lib::utils::{ List, List::*, Env };
use nanoda_lib::name::Name;
use nanoda_lib::level::{ LevelsPtr, Level };
use nanoda_lib::param;
#[test]
fn util_test2() {
let mut env = Env::new(false);
let mut env = env.as_compiler();
let l1 = param!(["u", "v"], &mut env);
let p1 = param!("u", &mut... |
use std::ops::*;
use super::angle::Angle;
use super::common::*;
macro_rules! Op {
($op_trait: ident, $op_func: ident, $op: tt) => {
impl $op_trait for Vec2D {
type Output = Vec2D;
fn $op_func(self, rhs: Vec2D) -> Vec2D {
Vec2D::new(self.x $op rhs.x, self.y $op rhs.y)... |
// A fairly easy way to declare extensible trait hierarchies in Rust with
// support for arbitrary dynamic upcasting and downcasting (just like
// traditional inheritance). This is based on Simon Marlow's "An Extensible
// Dynamically-Typed Hierarchy of Exceptions":
// https://simonmar.github.io/bib/papers/ext-excepti... |
pub(crate) mod from_headers;
pub(crate) const HEADER_VERSION: &str = "x-ms-version"; // Cow[str]
pub(crate) const HEADER_DATE: &str = "x-ms-date"; // [String]
pub(crate) const HEADER_DOCUMENTDB_IS_UPSERT: &str = "x-ms-documentdb-is-upsert"; // [bool]
pub(crate) const HEADER_INDEXING_DIRECTIVE: &str = "x-ms-indexing-di... |
use std::rc::Rc;
//use std::ops::{Shl, ShlAssign, Shr, ShrAssign, Rem, RemAssign, BitOrAssign, BitXor, Not, Sub, BitAnd, BitOr};
use num::clamp;
use num::PrimInt;
use num::cast::NumCast;
use crate::shape::*;
use crate::lens::*;
use crate::types::*;
use crate::scope::*;
#[derive(Clone, PartialEq, Eq)]
struct BitWor... |
use std::collections::HashMap;
type Headers = HashMap<String, String>;
pub struct Opa {
host: String,
port: i16,
version: String,
ssl: bool,
headers: Option<Headers>,
}
impl Opa {
pub fn new() -> Self {
Self {
host: "localhost".to_string(),
port: 8181,
... |
use serde::{Deserialize, Serialize};
use common::result::Result;
use crate::application::dtos::{AuthorDto, CategoryDto, PublicationDto};
use crate::domain::author::{AuthorId, AuthorRepository};
use crate::domain::category::CategoryRepository;
use crate::domain::content_manager::{ContentManagerId, ContentManagerReposi... |
use airhobot::prelude::*;
use std::path::PathBuf;
use structopt::StructOpt;
///
/// KEYBOARD SHORTCUTS:
///
/// 1: select field
/// 2: pick pusher color
/// 3: pick puck color
/// 4: simulate puck (place two points in the field)
/// 5: move pusher
/// c: show controls
/// r: reload config
/// f: next f... |
extern crate rustc_serialize;
extern crate hamming;
extern crate crypto;
extern crate itertools;
use rustc_serialize::hex::{ToHex, FromHex};
use rustc_serialize::base64::{FromBase64, ToBase64, Config, CharacterSet, Newline};
use std::collections::BTreeMap;
use crypto::{ symmetriccipher, buffer, aes, blockmodes };
use ... |
// Copyright 2017 PingCAP, Inc.
//
// 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 i... |
extern crate proc_macro;
use std::collections::HashSet;
//use anyhow::{anyhow, bail, Result};
use layout::{get_struct_member_layout, StructMemberLayout};
use proc_macro::TokenStream;
use quote::quote;
use syn::DeriveInput;
use syn::{
parse_macro_input, Attribute, Data, Error, Field, Fields, GenericArgument, Ident,... |
// Copyright (c) The Starcoin Core Contributors
// SPDX-License-Identifier: Apache-2.0
use anyhow::{bail, ensure, Result};
use libra_crypto::HashValue;
use libra_types::{account_address::AccountAddress, transaction::TransactionArgument};
use sgtypes::{channel_transaction::ChannelOp, htlc::HtlcPayment};
pub(crate) mod a... |
fn print_u32(n: u32) {
println!("The number is {}", n);
}
fn product(x: u32, y: u32) -> u32
{
x * y
}
fn inc(n: &mut u32)
{
*n += 1;
}
fn main() {
let n1 = 10;
let mut n2 = 15;
print_u32(n1);
print_u32(product(n1, 5));
inc(&mut n2);
print_u32(n2);
}
|
//! A light-emitting material.
use crate::{
hittable::{HitRecord, UVCoord},
material::Scatter,
ray::Ray,
texture::Texture,
vec3,
vec3::Vec3,
};
use rand::prelude::*;
/// A light-emitting material. Can hold any texture. Will not reflect rays.
#[derive(Debug, Clone)]
pub struct DiffuseLight {
... |
// Copyright (c) The Starcoin Core Contributors
// SPDX-License-Identifier: Apache-2.0
use anyhow::Result;
use starcoin_crypto::HashValue;
pub use starcoin_state_tree::StateNodeStore;
use starcoin_types::{
access_path::AccessPath, account_address::AccountAddress, account_state::AccountState,
};
mod chain_state;
... |
use soldier::Soldier;
use utilities::Position;
extern crate crossterm;
use std::io::{stdout, Write};
use self::crossterm::{
execute,
style,
Color,
Goto,
PrintStyledFont,
Show
};
pub struct Squad {
pub members: Vec<Soldier>
}
impl Squad {
pub fn new() -> Squad {
return Squad {
members: ... |
use std::io::{Error, BufReader, Read};
use crate::types::*;
pub type DecodeResult<T> = Result<T, DecodeError>;
pub enum DecodeError {
Io(Error),
Error,
}
impl From<Error> for DecodeError {
fn from(e: Error) -> Self {
DecodeError::Io(e)
}
}
pub struct Decoder<R: Read> {
reader: R,
}
imp... |
use std::ffi::CStr;
use std::mem;
use std::ops::Range;
use std::os::raw::c_void;
use std::ptr;
use anyhow::Result;
use libc;
use ffi;
use dev;
use errors::{AsResult, ErrorKind::OsError};
use ether;
use malloc;
use mbuf;
use memory::SocketId;
use mempool;
use utils::AsRaw;
pub type PortId = u16;
pub type QueueId = u... |
/// A target.
///
/// # Semantics
///
/// Used to link to internal objects that can't be assigned affiliated keywords. E.g. list
/// items.
///
/// See fuzzy [`Link`]s.
///
/// # Syntax
///
/// ```text
/// <<TARGET>>
/// ```
///
/// `TARGET` can contain any character except `<`, `>` and newline. It can't start or end w... |
use std::sync::Arc;
use gristmill::asset::Resources;
use gristmill::game::{Game, Window, run_game};
use gristmill_gui::{*, quad::Quad, text::{Text, Align}, button::ButtonClass, event::{GuiActionEvent, GuiActionEventRef}, container::*, layout::*, layout_builder::*, listener};
use gristmill::renderer::{RenderLoader, Ren... |
use std::{ fs };
pub fn main() -> Option<bool> {
let file_contents = match fs::read_to_string(
"./inputs/2020-12-06-aoc-01-input.txt"
) {
Ok(c) => c,
Err(e) => panic!("{:?}", e)
};
let total_sum = file_contents
.split("\n\n")
.map(|block| {
block
... |
use aoc19::data_path;
use itertools::Itertools;
use std::fs::rename;
fn new_name(name: &str) -> String {
name.split('_')
.enumerate()
.filter_map(|(ix, s)| if ix != 1 { Some(s) } else { None })
.join("_")
}
fn main() {
for day in data_path().read_dir().unwrap() {
let day = day.... |
use crate::init;
use std::env;
use structopt::StructOpt;
#[derive(StructOpt, Debug)]
pub struct InitOpt {
/// Agree to all prompts. Useful for non-interactive uses
#[structopt(long = "force-yes", short = "y")]
force_yes: bool,
}
pub fn init(opt: InitOpt) -> anyhow::Result<()> {
let current_directory =... |
use automerge_backend;
use automerge_frontend;
use automerge_protocol;
use pyo3::prelude::*;
use pyo3::wrap_pyfunction;
fn base_document(doc_id: &str, default_text: &str) -> automerge_backend::Backend {
let mut doc = automerge_backend::Backend::init();
let mut frontend = automerge_frontend::Frontend::new();
... |
use crate::config::dfinity::Config;
use crate::lib::environment::Environment;
use crate::lib::error::DfxResult;
use anyhow::{anyhow, bail};
use clap::Clap;
use serde_json::value::Value;
/// Configures project options for your currently-selected project.
#[derive(Clap)]
pub struct ConfigOpts {
/// Specifies the na... |
pub mod encoded_message;
pub mod message;
pub mod packetmessage;
|
use crate::Result;
use clap::{App, ArgMatches};
use oauth2::{ClientId, ClientSecret, RedirectUrl};
use ronor::Sonos;
use rustyline::Editor;
pub const NAME: &str = "init";
pub fn build() -> App<'static, 'static> {
App::new(NAME).about("Initialise sonos integration configuration")
}
pub fn run(sonos: &mut Sonos, _ma... |
use crate::{
remote_ptr::{RemotePtr, Void},
wait_status::WaitStatus,
};
use libc::pid_t;
use std::ffi::{OsStr, OsString};
#[derive(Clone)]
pub enum TraceTaskEventVariant {
/// DIFF NOTE: We DONT have a `None` variant here, unlike rr.
///
/// Created by clone(2), fork(2), vfork(2) syscalls
Clone... |
// Copyright 2019. The Tari Project
// SPDX-License-Identifier: BSD-3-Clause
//! Extended commitments are commitments that have more than one blinding factor.
use alloc::vec::Vec;
use core::{borrow::Borrow, iter::once};
use curve25519_dalek::{
ristretto::{CompressedRistretto, RistrettoPoint},
scalar::Scalar,... |
pub mod connection_details_page;
pub mod initial_page;
pub mod inspect_page;
pub mod notifications_page;
pub mod overview_page;
pub mod settings_language_page;
pub mod settings_notifications_page;
pub mod settings_style_page;
pub mod types;
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.