text stringlengths 8 4.13M |
|---|
//! Contains the types of results returned by CRUD operations.
use std::collections::{HashMap, VecDeque};
use crate::{
bson::{serde_helpers, Bson, Document},
change_stream::event::ResumeToken,
db::options::CreateCollectionOptions,
serde_util,
Namespace,
};
use bson::{Binary, RawDocumentBuf};
use ... |
use chrono::{DateTime, NaiveDate, NaiveDateTime, NaiveTime, Utc};
use postgres::types::Type;
use rust_decimal::Decimal;
use serde_json::Value;
use std::collections::HashMap;
use uuid::Uuid;
#[derive(Copy, Clone, Debug)]
pub enum PostgresTypeSystem {
Bool(bool),
Float4(bool),
Float8(bool),
Numeric(bool)... |
use std::io;
fn main() {
loop {
println!("Enter 1 to convert from Celcius or 2 to convert from Farenheit:");
let mut input = String::new();
io::stdin().read_line(&mut input)
.expect("Failed to read line");
let input: u32 = match input.trim().parse() {
Ok(nu... |
extern crate hyper;
use hyper::Client;
use hyper::body::HttpBody as _;
pub struct OpenWeatherApi{
pub api_key: String
}
impl OpenWeatherApi {
pub async fn get_json(&self, city : String) -> String {
let client = Client::new();
let url: String = String::from(format!("http://api.openweathermap.o... |
//!
//! very simple program to demonstrate color selection
//!
//! ```cargo run --example color-selection```
//!
use cv::prelude::*;
use std::{
env,
error::Error,
path::PathBuf,
sync::{Arc, RwLock},
time::Duration,
};
fn main() -> Result<(), Box<dyn Error>> {
let image_path = {
let name... |
extern crate env_logger;
extern crate hyper;
extern crate hubcaps;
extern crate hyper_native_tls;
use hyper::Client;
use hyper::net::HttpsConnector;
use hyper_native_tls::NativeTlsClient;
use hubcaps::{Credentials, Github};
use std::env;
fn main() {
env_logger::init().unwrap();
match env::var("GITHUB_TOKEN").... |
use crate::{Runtime, RuntimeCall, RuntimeConfigs, Subspace, Sudo};
use codec::{Decode, Encode};
use scale_info::TypeInfo;
use sp_runtime::traits::{DispatchInfoOf, SignedExtension};
use sp_runtime::transaction_validity::{
InvalidTransaction, TransactionValidity, TransactionValidityError, ValidTransaction,
};
use sp_... |
struct Fibonacci {
a: u64,
b: u64,
}
impl Fibonacci {
pub fn new() -> Fibonacci {
Fibonacci { a: 0, b: 1 }
}
}
impl Iterator for Fibonacci {
type Item = u64;
fn next(&mut self) -> Option<u64> {
let tmp: u64 = self.a;
self.a = self.b;
self.b = tmp + self.a;
... |
use diesel;
use diesel::prelude::*;
use diesel::mysql::MysqlConnection;
use schema::heroes;
#[table_name = "user"]
#[derive(AsChangeset, Serialize, Deserialize, Queryable, Insertable)]
pub struct User {
pub id: i32,
pub name: String,
pub identity: String,
pub hometown: String,
pub age: i32
}
impl ... |
//! A multi-producer, multi-consumer channel implementation.
mod mutex_linked_list;
mod mpmc_bounded_queue;
mod channel;
pub use self::mutex_linked_list::MutexLinkedList;
pub use self::mpmc_bounded_queue::LockFreeQueue;
pub use self::channel::Failure;
use std::sync::{Arc};
use std::cell::UnsafeCell;
use self::channe... |
pub mod query;
pub mod generator;
|
use clap::{App, Arg};
use std::fs::File;
use std::process;
use imprint_of_light::{
config::Config,
render::{render as r, Entity, Scene},
};
fn main() {
args_check();
}
fn args_check() {
let matches = App::new("imprint_of_light")
.version("0.1.0")
.author("Luke Euler <luke16times@gmail... |
#[doc = r"Register block"]
#[repr(C)]
pub struct RegisterBlock {
#[doc = "0x00 - Temperature sensor configuration register 1"]
pub cfgr1: CFGR1,
_reserved1: [u8; 0x04],
#[doc = "0x08 - Temperature sensor T0 value register 1"]
pub t0valr1: T0VALR1,
_reserved2: [u8; 0x04],
#[doc = "0x10 - Temp... |
pub fn split_first<'a>(line: &'a str) -> Option<(&'a str, &'a str)> {
match line.find('\t') {
Some(i) => Some((&line[0..i], &line[(i + 1)..])),
None => None,
}
}
#[test]
fn split_empty() {
assert_eq!(split_first(""), None)
}
#[test]
fn split_tab() {
assert_eq!(split_first("foo\tbar"), ... |
/*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under both the MIT license found in the
* LICENSE-MIT file in the root directory of this source tree and the Apache
* License, Version 2.0 found in the LICENSE-APACHE file in the root directory
* of this source tree.
*/
use c... |
mod lights;
mod sum;
mod area;
fn main() {
println!("Hello, world!");
// test lights
lights::test_lights();
// test sum
let acceptable_list = [1,2,3,4];
let exceptional_list = [1, u32::MAX];
assert_eq!(sum::sum_list(&acceptable_list), Some(10));
assert_eq!(sum::sum_list(&exceptional_lis... |
// Copyright 2014-2018 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution.
//
// 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>,... |
use serenity::prelude::Mutex;
use std::collections::HashMap;
use std::net::UdpSocket;
use std::str;
use std::sync::Arc;
use player::Player;
pub struct Server {
socket: UdpSocket,
players: Arc<Mutex<HashMap<String, Player>>>
}
impl Server {
pub fn new(players: Arc<Mutex<HashMap<String, Player>>>) -> Serve... |
use std::collections::HashMap;
use ash::{version::DeviceV1_0, vk, Device};
use anyhow::Result;
use colorous::Gradient;
use rustc_hash::FxHashMap;
use crate::vulkan::GfaestusVk;
use super::Texture;
use super::Texture1D;
pub struct Gradients_ {
// gradient_offsets: FxHashMap<egui::TextureId, usize>,
gradien... |
use hyper;
use hyper::net::NetworkListener;
use hyper::server::Request;
use hyper::server::Response;
use hyper::uri::RequestUri;
use hyper::header::AccessControlAllowOrigin;
use rand::{self, Rng};
use rustc_serialize::json;
use std::collections::BTreeMap;
use std::io::Read;
use std::sync::{mpsc, Mutex};
use url;
use p... |
//! Utilites to make my life easier
/// A way to put C-literals in Rust code.
/// Does not accept byte strings.
///
/// #Usage
/// foo(c_str!("my string"));
#[macro_export]
macro_rules! c_str {
($s:expr) => {
concat!($s, "\0").as_ptr() as *const i8
}
}
/// Registers a lua function in a LuaL_reg to cal... |
use std::cell::RefCell;
use std::collections::HashMap;
use std::ops::Deref;
use std::rc::Rc;
use hydroflow::serde::{Deserialize, Serialize};
use hydroflow::util::cli::{ConnectedDemux, ConnectedDirect, ConnectedSink, ConnectedSource};
use hydroflow::util::{deserialize_from_bytes, serialize_to_bytes};
use hydroflow::{hy... |
#![allow(non_snake_case, non_upper_case_globals)]
extern crate dimensioned as dim;
use self::dim::si;
use self::dim::Sqrt;
#[derive(Copy, Clone)]
struct MetricNBody {
position: Position2D,
accel: Accel2D,
velocity: Velocity2D,
mass: si::Kilogram<f64>,
}
use std::marker::PhantomData;
#[derive(Copy, ... |
extern crate rustc_serialize;
extern crate graphael;
use std::io::{self, BufRead, Write};
use graphael::Graph;
// Shorthand HashMap
// dict!({"yes": "1", "no": "0"}) => vec!($(($key, $value)),*).move_iter().collect();
// macro_rules! dict (
// ({$($key:expr : $value:expr),*}) => (vec!($(($key, $value)),*).move_iter... |
mod keyed_set;
mod window;
mod physics;
mod simulation;
mod math;
use std::{
time,
io,
fs,
path,
collections::HashMap,
};
use rand::{random, seq::SliceRandom};
use raylib::prelude::*;
use crate::{
window::prelude::*,
simulation::prelude::*,
};
fn random_vector2() -> Vector2 { Vector2::n... |
use super::*;
use crate::errors::*;
use crate::message::packer::*;
// An OPTResource is an OPT pseudo Resource record.
//
// The pseudo resource record is part of the extension mechanisms for DNS
// as defined in RFC 6891.
#[derive(Default, Debug, Clone, PartialEq)]
pub struct OptResource {
pub options: Vec<DnsOpt... |
use std::collections::HashMap;
pub fn parse_input(input: &str) -> HashMap<usize, Vec<usize>> {
let mut map: HashMap<usize, Vec<usize>> = HashMap::new();
input.lines()
.map(|line| {
let mut parts = line.splitn(3, ' ');
let source = parts.next().unwrap().parse::<usize>().unwrap()... |
use tokio::net::TcpStream;
use tokio::prelude::*;
use std::fs::File;
use std::io::prelude::*;
#[tokio::main]
async fn main() {
let mut stream = TcpStream::connect("127.0.0.1:6142").await.unwrap();
println!("created stream");
let filename = "input.txt";
let mut f = File::open(&filename).expect("no fil... |
use std::collections::{HashMap, HashSet};
use std::ops::Deref;
use hydroflow_lang::diagnostic::{Diagnostic, Level};
use hydroflow_lang::graph::{
eliminate_extra_unions_tees, partition_graph, FlatGraphBuilder, HydroflowGraph,
};
use hydroflow_lang::parse::{
HfStatement, IndexInt, Indexing, Pipeline, PipelineLin... |
use std::collections::{hash_map, VecDeque, BTreeMap};
use std::{io, cmp, fmt, mem, str};
use std::net::SocketAddrV6;
use std::sync::{Arc, Mutex};
use std::path::PathBuf;
use bytes::{Buf, BufMut, Bytes, ByteOrder, BigEndian, IntoBuf};
use rand::{distributions, OsRng, Rng};
use rand::distributions::Sample;
use slab::Sla... |
use crate::test::externalities::TestExternalities;
use crate::{
node::InternalNode,
rpc::{self, RpcExtension},
types,
};
use jsonrpc_core_client::{transports::local, RpcChannel};
use crate::node::TestRuntimeRequirements;
/// A black box node, either runs a background node,
/// or connects via ws to a running node.
... |
use std::fs;
fn transform(mut value: i64, subject_number: i64) -> i64 {
value *= subject_number;
value = value % 20201227;
value
}
fn main() -> Result<(), Box<dyn std::error::Error>>{
let filename = "/home/remy/AOC/2020/25/input";
let data = fs::read_to_string(filename).unwrap();
let mut split... |
use dicom::core::dicom_value;
use dicom::object::{mem::InMemDicomObject, StandardDataDictionary};
use dicom::{
core::{DataElement, PrimitiveValue, VR},
dictionary_std::tags,
};
use dicom_ul::pdu;
use dicom_ul::{
association::client::ClientAssociationOptions,
pdu::{PDataValueType, Pdu},
};
use pdu::PData... |
//! Models and structs used by and for the deployment process.
use std::borrow::Cow;
use std::collections::HashMap;
use std::fmt;
use std::path::{Path, PathBuf};
use std::time::{Duration, SystemTime, SystemTimeError};
use serde::{Deserialize, Serialize};
use crate::profile::dotfile::Dotfile;
use crate::profile::Prio... |
use svm_types::SectionKind;
use crate::{Field, ParseError, ReadExt, WriteExt};
pub const CODE_SECTION: u16 = 0x00_01;
pub const DATA_SECTION: u16 = 0x00_02;
pub const CTORS_SECTION: u16 = 0x00_03;
pub const SCHEMA_SECTION: u16 = 0x00_04;
pub const API_SECTION: u16 = 0x00_05;
pub const HEADER_SECTION: u16 = 0x00_06;
p... |
//! Weechat Infolist module.
use std::ffi::CStr;
use std::os::raw::c_void;
use std::ptr;
use weechat_sys::{t_gui_buffer, t_infolist, t_weechat_plugin};
use crate::{Buffer, LossyCString, Weechat};
use std::borrow::Cow;
/// Weechat Infolist type.
pub struct Infolist {
pub(crate) ptr: *mut t_infolist,
pub(crat... |
mod protos;
use futures::*;
use futures::Stream;
use futures::sync::oneshot;
use std::env;
use std::iter;
use std::sync::{Arc};
use std::{io, thread};
use std::io::Read;
use protobuf::RepeatedField;
use grpcio::*;
use protos::multiplay::*;
use protos::multiplay_grpc::{Multiplay, User};
use mongodb::{bson, doc};
use ... |
#[allow(unused_variables)]
use std::env;
fn main()
{
let args = env::args();
let str = env::args().collect::<Vec<String>>();
println!("{:?}", args);
println!("{:?}", str);
}
|
use crate::helper::{
do_accumulator_node, do_get_body_by_hash, do_get_headers, do_get_info_by_hash, do_get_txn_info,
do_state_node,
};
use crate::txn_sync::GetTxnsHandler;
use actix::prelude::*;
use actix::{Actor, Addr, AsyncContext, Context, StreamHandler};
use anyhow::Result;
use chain::ChainActorRef;
use cry... |
//! A thread-safe metrics library.
//!
//! Many programs need to information about runtime performance: the number of requests
//! served, a distribution of request latency, the number of failures, the number of loop
//! iterations, etc. `tacho::new` creates a shareable, scopable metrics registry and a
//! `Reporter`. ... |
use anyhow::Result;
use wasmtime::{Linker, Trap};
use super::namespace_matches_filter;
use crate::state::ProcessState;
// Register WASI APIs to the linker
pub(crate) fn register(
linker: &mut Linker<ProcessState>,
namespace_filter: &[String],
) -> Result<()> {
// Add all WASI functions at first
wasmti... |
use crate::nes::ram::Ram;
use super::sprite::Sprite;
pub type SpritesWithCtx = Vec<SpriteWithCtx>;
#[derive(Debug)]
pub struct SpriteWithCtx {
pub sprite: Sprite,
}
impl SpriteWithCtx {
}
#[cfg(test)]
mod sprite_with_ctx_test {
use super::*;
} |
use std::collections::HashMap;
use std::fs::File;
use std::io::{BufRead, BufReader};
use std::str::FromStr;
#[derive(Clone, Debug, PartialEq, Eq)]
struct Ingredient {
chemical: String,
amount: usize,
}
impl Ingredient {
fn new(chemical: String, amount: usize) -> Self {
Self { chemical, amount }
... |
use super::trait_simple_demo::Display;
use super::trait_simple_demo::Summary;
use super::trait_simple_demo::Tweet;
use std::fmt::Display as Display_std;
pub fn notify<T: Summary + Display>(item: T) {
println!("Breaking news! Sumarray+Display {}", item.summarize());
}
//another style
// pub fn notify(item: impl S... |
#[doc = "Register `MACCSRSWCR` reader"]
pub type R = crate::R<MACCSRSWCR_SPEC>;
#[doc = "Register `MACCSRSWCR` writer"]
pub type W = crate::W<MACCSRSWCR_SPEC>;
#[doc = "Field `RCWE` reader - Register Clear on Write 1 Enable When this bit is set, the access mode to some register fields changes to rc_w1 (clear on write) ... |
use std::collections::HashMap;
struct Solution {}
impl Solution {
pub fn two_sum( nums: Vec<i32>, target: i32) -> Vec<i32> {
let mut map : HashMap<&i32, usize> = HashMap::new();
let mut i = 0;
while i < nums.len() {
match map.get(&(target-nums[i])) {
Some(&v) =>... |
use std::fs::File;
use std::io::Read;
fn main() {
let mut file = File::open("d05-input").expect("file not found");
let mut input = String::new();
file.read_to_string(&mut input).expect("something went wrong reading file");
let mut ids: Vec<u32> = vec![];
for line in input.lines() {
let mut row = (0.0f32, 127.0... |
use crate::io::*;
use crate::model::rnn::*;
use crate::model::seq2seq::*;
use crate::model::*;
use crate::optimizer::{AdaGrad, NewAdam, NewSGD, Optimizer, SGD};
use crate::params::Update;
use crate::types::*;
use crate::util::*;
use itertools::izip;
// extern crate ndarray;
// use ndarray::iter::AxisChunksIter;
use nda... |
use crate::matrix::{Matrix, MatrixOps};
use std::error::Error;
pub fn read_csv_by_path(file_path: &str) -> Result<(Vec<Matrix>, Vec<Matrix>), Box<dyn Error>> {
let mut rdr = csv::Reader::from_path(file_path)?;
let mut label_matrix_vec = Vec::new();
let mut data_matrix_vec = Vec::new();
for result in r... |
use crate::magnificent;
use std::fs;
lalrpop_mod!(pub m3); // generated parser
pub fn parse_m3(_input: &str) -> Result<magnificent::Program, String> {
// let raw_program = grammer::PredParser::new().parse(input)
// .or_else(|e| panic!("m3 parser failed: {}", e))
Err("unimplemented".to_string())
}
pub... |
fn main() {
proconio::input! {
n: usize,
store: [(i32, i32, i32); n],
}
let mut price_min = std::i32::MAX;
for s in store {
if s.2 - s.0 <= 0 {
continue;
}
if s.1 < price_min {
price_min = s.1;
}
}
if price_min == std::i3... |
#[doc = r" Value read from the register"]
pub struct R {
bits: u32,
}
#[doc = r" Value to write to the register"]
pub struct W {
bits: u32,
}
impl super::CMDSTAT {
#[doc = r" Modifies the contents of the register"]
#[inline]
pub fn modify<F>(&self, f: F)
where
for<'w> F: FnOnce(&R, &'w m... |
use fibers_transport::{PollRecv, PollSend, Result, TcpTransport, Transport};
use stun_codec::{Attribute, DecodedMessage, Message, TransactionId};
use super::StunTransport;
/// TCP transport layer that can be used for STUN.
#[derive(Debug)]
pub struct StunTcpTransporter<T> {
inner: T,
}
impl<A, T> StunTcpTransport... |
use abstract_ns;
use abstract_ns::HostResolve;
use domain;
use futures::prelude::*;
use ns_dns_tokio;
use std::net::IpAddr;
use std::path::Path;
use std::str::FromStr;
use tokio_core::reactor::Handle;
use transport;
#[derive(Clone, Debug)]
pub struct Config(domain::resolv::ResolvConf);
#[derive(Clone, Debug)]
pub str... |
use crate::grid::PbcInfo;
pub type Coord<const D: usize> = [f64; D];
/// Add two points of identical dimension.
pub fn add_coords<const D: usize>(x0: &Coord<D>, x1: &Coord<D>) -> Coord<D> {
let mut buf: Coord<D> = x0.clone();
buf.iter_mut().zip(x1.iter()).for_each(|(a, b)| *a += b);
buf
}
/// Calculate... |
#[doc = "Control register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--writ... |
// By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms.
fn main() {
let now = Instant::now();
println!("imperative: {}", e2_imperative());
println!("time:{:?}", now.elapsed());
let now = Instant::now();
println!("functio... |
pub
fn palindrome() {
// a palindrome!
let mut v = vec!["a man", "a plan", "a canal", "panama"];
println!("{:?}", v);
v.reverse();
// reasonable yet disappointing:
println!("{:?}", v);
assert_eq!(v, vec!["panama", "a canal", "a plan", "a man"]);
}
|
use utils;
use std::collections::HashSet;
use std::iter::FromIterator;
pub fn problem_047() -> u64 {
let k = 4;
let mut consecutive: Vec<u64> = vec![];
for n in 2..1000000 {
let prime_factors = utils::prime_factors(n);
let distinct_prime_factors: HashSet<&u64> = HashSet::from_iter(prime_fa... |
use std::collections::HashMap;
use std::fs;
fn main() -> Result<(), String> {
let input = fs::read_to_string("input/data.txt").map_err(|e| e.to_string())?;
let as_array = get_as_array(&input);
let ChildProcessResult { metadata_sum, .. } = part1(&as_array);
assert_eq!(metadata_sum, 36891);
println!... |
/* required because there can be no os-level abstractions for an os :) */
/* println macro fails, panic handler unavailable, and many others */
/* the main function is pointless as there is no runtime that could call it :( */
#![no_std]
#![no_main]
/* overwriting the os entry point with this _start function. It's spec... |
pub fn jump_naive(nums: Vec<i32>) -> i32 {
use std::cmp::min;
let n = nums.len();
if n == 1 {
return 0
} else if n == 2 {
return 1
}
let mut min_jump = vec![0; n];
for i in (0..n-1).rev() {
min_jump[i] = *&min_jump[i+1..=min(i+nums[i] as usize, n-1)].iter().fold(n as... |
use ::{ Asn1DerError, types::{ FromDerObject, IntoDerObject }, der::{ DerObject, DerTag} };
impl FromDerObject for () {
fn from_der_object(der_object: DerObject) -> Result<Self, Asn1DerError> {
if der_object.tag != DerTag::Null { return Err(Asn1DerError::InvalidTag) }
if !der_object.value.data.is_empty() { Err(A... |
use failure::Fallible;
use regex::Regex;
use rustberry::playback_requests::PlaybackRequest;
use rustberry::rfid::*;
fn derive_spotify_uri_from_url(url: &str) -> Fallible<String> {
let re = Regex::new(r"https://open.spotify.com/(?P<type>(track|album))/(?P<id>[a-zA-Z0-9]+)")
.expect("Failed to compile regex... |
use std::collections::HashMap;
fn main() {
const MAX_NUMBERS: u32 = 30000000;
let input = "6,13,1,15,2,0"; // "0,3,6";
let mut input = input.split(',').rev().map(|n| n.parse().unwrap());
let mut last_num = input.next().unwrap();
let input = input.rev();
let mut spoken_count = 0;
let mut s... |
extern crate libnanomsg;
extern crate libc;
extern crate core;
use std::str;
use std::fmt;
pub use self::NanoErrorKind::*;
pub type NanoResult<T> = Result<T, NanoError>;
#[deriving(Show, Clone, PartialEq, FromPrimitive)]
pub enum NanoErrorKind {
Unknown = 0i,
OperationNotSupported = libnanomsg::ENOTSUP as i... |
use super::*;
pub(crate) fn clear_history_command(ctx: &Context) -> CommandResult {
let (index, _) = ctx.state.buffers().current();
ctx.request(Request::ClearHistory(index));
Ok(Response::Nothing)
}
|
use anyhow::Error;
use clap::{Arg, ArgMatches};
use k8s_openapi::api::apps::v1::Deployment;
use k8s_openapi::api::core::v1::{Secret, ServiceAccount};
use k8s_openapi::api::rbac::v1::{ClusterRole, ClusterRoleBinding};
use kube::api::{DeleteParams, PostParams};
use kube::client::APIClient;
use kube::Api;
use async_trait... |
use bitflags::bitflags; // bitflags! macro
bitflags! {
struct Permission: u8 {
const NONE = 0b0000;
const CREATE = 0b1000;
const READ = 0b0100;
const UPDATE = 0b0010;
const DELETE = 0b0001;
}
}
enum Group {
Guest,
User,
Admin,
Owner,
}
struct User {
... |
//! Compute the binary representation of a type
use base_db::CrateId;
use chalk_ir::{AdtId, TyKind};
use hir_def::{
layout::{
Abi, FieldsShape, Integer, Layout, LayoutCalculator, LayoutError, Primitive, ReprOptions,
RustcEnumVariantIdx, Scalar, Size, StructKind, TargetDataLayout, Variants, Wrapping... |
use std::fmt;
use std::str::FromStr;
#[derive(Debug, PartialEq, Clone)]
/// A list of supported keys that we can query from the OS. Outside of mod.
pub enum Keycode {
Key0,
Key1,
Key2,
Key3,
Key4,
Key5,
Key6,
Key7,
Key8,
Key9,
A,
B,
C,
D,
E,
F,
G,
... |
#[aoc_generator(day15)]
pub fn input_generator(input: &str) -> Vec<usize> {
input
.split(",")
.map(|l| l.parse::<usize>().unwrap())
.collect()
}
#[aoc(day15, part1)]
pub fn part1(starting: &Vec<usize>) -> usize {
const ITERATIONS: usize = 2020;
let numbers = starting.clone();
le... |
//! The CXX code generator for constructing and compiling C++ code.
//!
//! This is intended as a mechanism for embedding the `cxx` crate into
//! higher-level code generators. See [dtolnay/cxx#235] and
//! [https://github.com/google/autocxx].
//!
//! [dtolnay/cxx#235]: https://github.com/dtolnay/cxx/issues/235
//! [ht... |
#![allow(dead_code)]
#![allow(non_snake_case)]
#![allow(unused_must_use)]
#![allow(unused_parens)]
use std::fs::File;
use std::io::prelude::*;
use std::io;
use std::os::unix::io::AsRawFd;
use std::mem;
use std::thread;
use std::sync::mpsc;
use regex::Regex;
use libc;
use std::os::unix::io::RawFd;
use std::ops::Drop;
... |
fn closures() {
fn function (i: i32) -> i32 { i + 1 }
let closure_annotated = |i: i32| -> i32 { i + 1 };
let closure_inferred = |i| i + 1;
let i = 15;
println!("Regular function: {}", function(i));
println!("Annotated closure: {}", closure_annotated(i));
println!("Inferred closure: {}", ... |
#![allow(dead_code)]
#[macro_use]
mod utils;
mod data_parser;
mod day_1;
mod day_10;
mod day_11;
mod day_12;
mod day_13;
mod day_2;
mod day_3;
mod day_4;
mod day_5;
mod day_6;
mod day_7;
mod day_8;
mod day_9;
fn main() {}
|
//entrypoint to the program
// bring required dependencies into scope with use statement
use solana_program::{
account_info::AccountInfo, entrypoint, entrypoint::ProgramResult, msg, pubkey::Pubkey,
};
// declare process_instruction as the entrypoint to the program;
// all program calls are handled only though ent... |
use super::atom::tag::{self, Tag};
use crate::arena::block::{self, BlockId};
use isaribi::{
style,
styled::{Style, Styled},
};
use kagura::prelude::*;
pub struct Props {
pub block_arena: block::ArenaRef,
pub world_id: BlockId,
pub removable: bool,
}
pub enum Msg {
Sub(On),
}
pub enum On {
... |
use app::{
get_immutable_store, get_locales, get_mutable_store, get_static_aliases, get_templates_map,
get_templates_vec, get_translations_manager, APP_ROOT,
};
use fs_extra::dir::{copy as copy_dir, CopyOptions};
use futures::executor::block_on;
use perseus::{build_app, export_app, path_prefix::get_path_prefix_... |
use std::error::Error;
use std::fs;
use std::env;
pub struct Config {
pub query: String,
pub filename: String,
pub case_sensitive: bool
}
impl Config {
pub fn new(args: &[String]) -> Result<Config, &str>{
// args[0] is execution path, then come the command line args
if args.len()<3 {
... |
macro_rules! encode_impl {
($l:expr; $(#[$attr: meta])* $parse_macro:ident; $(#[$encode_attr: meta])* $encode_name: ident; $(#[$encode_to_string_attr: meta])* $encode_to_string_name: ident; $(#[$encode_to_vec_attr: meta])* $encode_to_vec_name: ident; $(#[$encode_to_writer_attr: meta])* $encode_to_writer_name: ident... |
pub mod intcpu;
pub mod halp; |
#[doc = "Register `APB1LLPENR` reader"]
pub type R = crate::R<APB1LLPENR_SPEC>;
#[doc = "Register `APB1LLPENR` writer"]
pub type W = crate::W<APB1LLPENR_SPEC>;
#[doc = "Field `TIM2LPEN` reader - TIM2 clock enable during sleep mode Set and reset by software."]
pub type TIM2LPEN_R = crate::BitReader;
#[doc = "Field `TIM2... |
pub mod image_file;
pub use self::image_file::*;
pub mod texture;
pub use self::texture::*;
pub mod effect;
pub use self::effect::*;
extern {
pub fn gs_reset_blend_state();
pub fn gs_draw_sprite(this: *mut Texture, flip: u32, width: u32, height: u32);
} |
use glob::glob;
use rayon::prelude::*;
use serde_json::Value;
use std::collections::HashMap;
use std::fs::{create_dir, File};
use std::io::BufReader;
use std::path::{Path, PathBuf};
use structopt::StructOpt;
#[derive(StructOpt, Debug)]
#[structopt(name = "sentry_events")]
struct Opt {
/// Artifacts directory
#... |
extern crate console;
use std::io;
use std::thread;
use std::time::Duration;
use console::Term;
fn print_sample() -> io::Result<()> {
let term = Term::stdout();
term.write_line("Hello World!")?;
thread::sleep(Duration::from_millis(2000));
term.clear_line()?;
Ok(())
}
fn main() {
print_sample... |
use std::mem::size_of;
use math::{Rect, Point2, BaseNum, BaseIntExt};
pub fn mask<N, F>(r: Rect<N>, br: Rect<N>, brush: &[bool], mut f: F)
where
F: FnMut(N, N),
N: BaseIntExt
{
blit(r, br, brush, |x, y, pix| if pix { f(x, y) });
}
pub fn blit<N, F, C>(r: Rect<N>, br: Rect<N>, brush: &[C], mut ... |
use super::Subscription;
use crate::env::Env;
use futures::prelude::*;
use futures::{
channel::mpsc,
stream::{FusedStream, Stream},
task::{self, Poll},
};
use gloo_events::EventListener;
use serde::Deserialize;
use std::{borrow::Cow, marker::PhantomData, pin::Pin};
use wasm_bindgen::prelude::*;
pub fn wind... |
//! [Closures]: Anonymous Functions that Can Capture Their Environment
//!
//! [closures]: https://doc.rust-lang.org/book/ch13-01-closures.html
use std::error::Error;
use the_book::ch13::sec01::Cacher;
fn main() -> Result<(), Box<dyn Error>> {
let mut c = Cacher::new(|x| x);
for _ in { 1..1_000 } {
le... |
pub fn run() {
let name = "Wulf";
// Mutable
let mut age = 25;
println!("My name is {} ang age is {}", name, age);
age = 26;
println!("My name is {} ang age is {}", name, age);
// Define constant
const ID: i32 = 001;
println!("ID is {}", ID);
// Assign multipple variables
... |
extern crate lettre;
#[macro_use]
extern crate log;
extern crate rand;
#[macro_use]
extern crate serde_derive;
extern crate toml;
use std::path::Path;
use rand::Rng;
pub mod conf;
mod email;
pub mod file_utils;
pub mod kk_log;
#[derive(Debug)]
pub struct KkPair {
giver: conf::Participants,
receiver: conf::P... |
// **************************************************************************
// Copyright (c) 2015 Roland Ruckerbauer All Rights Reserved.
//
// This file is part of hidapi_rust.
//
// hidapi_rust is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as publish... |
/*
* Copyright 2019 Intel Corporation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file expect 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... |
use anyhow::{Context, Result};
use fs_err as fs;
use goblin::elf::Elf;
use regex::Regex;
use std::path::{Path, PathBuf};
use std::process::{Command, Stdio};
/// Find musl libc path from executable's ELF header
pub fn find_musl_libc() -> Result<Option<PathBuf>> {
let buffer = fs::read("/bin/ls")?;
let elf = Elf... |
// ===============================================================================
// 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... |
//! Comparison of sequences of values with a given violin.
//!
//! # Examples
//!
//! Quick plot.
//! ```no_run
//! use preexplorer::prelude::*;
//! let many_seq_err = (0..5).map(|_| pre::SequenceViolin::new((0..10).map(|i| (i..10 + i))));
//! pre::SequenceViolins::new(many_seq_err).plot("my_identifier").unwrap();
//! ... |
use crate::Transformer;
use std::marker::PhantomData;
pub struct MinMaxScaler<I, O> {
min: Option<I>,
max: Option<I>,
phantom: PhantomData<O>,
}
impl<I, O> MinMaxScaler<I, O> {
pub fn new() -> Self {
Self {
min: None,
max: None,
phantom: PhantomData,
... |
use crate::common::{Annot, Loc};
use std::fmt;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum TokenKind {
Incr,
Decr,
Next,
Prev,
Read,
Write,
LParen,
RParen,
}
impl fmt::Display for TokenKind {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
use self::T... |
#[doc = "Reader of register CFG0"]
pub type R = crate::R<u32, super::CFG0>;
#[doc = "Writer for register CFG0"]
pub type W = crate::W<u32, super::CFG0>;
#[doc = "Register CFG0 `reset()`'s with value 0"]
impl crate::ResetValue for super::CFG0 {
type Type = u32;
#[inline(always)]
fn reset_value() -> Self::Typ... |
use std::{fs, io};
fn get_index(values: &Vec<i32>, modes: &[u32; 3], param: u32, index: usize) -> usize {
if modes[param as usize - 1] == 0 {
values[index + param as usize] as usize
}
else if modes[param as usize -1] == 1 {
index + param as usize
} else {
panic!("Mode not possi... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.