text stringlengths 8 4.13M |
|---|
extern crate proc_modules;
use proc_modules::ModuleIter;
use std::io;
fn main() -> io::Result<()> {
for module in ModuleIter::new()? {
println!("{:#?}", module?);
}
Ok(())
}
|
use crate::mem::mapper::Mapper;
pub struct RomMapper {
/// Mapped to the ROM area. Up to 32 KiB in size.
rom: Box<[u8]>,
/// Mapped to the RAM area. Up to 8 KiB in size.
ram: Box<[u8]>,
has_battery: bool,
/// True is SRAM has been written to since the last time it was saved.
ram_modified: ... |
mod dataframe;
mod trade;
mod strategy;
use std::time::{Duration, Instant};
fn main() {
let start = Instant::now();
let df = dataframe::DataFrame::load_csv("trainTHETA-PERP.csv");
let duration = start.elapsed();
//backtest(&df);
println!("Time taken to load csv file {:?}", duration);
}
... |
#[doc = "Register `ETH_MTLRxQ0OMR` reader"]
pub type R = crate::R<ETH_MTLRX_Q0OMR_SPEC>;
#[doc = "Register `ETH_MTLRxQ0OMR` writer"]
pub type W = crate::W<ETH_MTLRX_Q0OMR_SPEC>;
#[doc = "Field `RTC` reader - RTC"]
pub type RTC_R = crate::FieldReader;
#[doc = "Field `RTC` writer - RTC"]
pub type RTC_W<'a, REG, const O: ... |
fn main() {
let mut v: Vec<i32> = Vec::new();
v.push(5);
println!("v: {:?}", v);
{
let mut v2 = vec![1, 3, 5];
v2.push(7);
println!("v2: {:?}", v2);
println!("The second element is {:?}", &v2[1]);
match v2.get(2) {
Some(val) => println!("The third ele... |
// use sodiumoxide::crypto::pwhash::argon2id13::HashedPassword;
use sqlx::{Connect, FromRow, PgConnection};
use uuid::Uuid;
// user data from db (includes id)
#[derive(FromRow)]
pub struct UserDBRecordWithId {
pub id: Uuid,
pub user_name: String,
pub password_hash_char: String,
pub password_hash_bin: V... |
mod font_style;
use font_style::{FontStyle,Message};
use iced::{Sandbox, Settings};
fn main() {
FontStyle::run(Settings::default());
}
|
#[cfg(feature = "python")]
pub mod py;
mod test;
/// The Morse link potential freely-jointed chain (Morse-FJC) model thermodynamics in the isometric ensemble.
pub mod isometric;
/// The Morse link potential freely-jointed chain (Morse-FJC) model thermodynamics in the isotensional ensemble.
pub mod isotensio... |
// DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
// Version 2, December 2004
//
// Copyright (C) 2017 Gilberto Bertin <me@jibi.io>
//
// Everyone is permitted to copy and distribute verbatim or modified
// copies of this license document, and changing it is allowed as long
// as the name is ch... |
use super::Result;
use std::panic::AssertUnwindSafe;
use std::sync::{mpsc::Sender, Arc, Mutex};
use std::thread::JoinHandle;
/// ThreadPool contains basic methods of a thread pool
pub trait ThreadPool {
/// Create a new thread pool with specified count of threads
fn new(threads: u32) -> Result<Self>
where
... |
pub mod dfs {
struct Edge {
node: usize,
}
trait TVisitor {
fn pre(&self, node: usize);
fn post(&self, node: usize);
}
fn search(adj_list: &Vec<Vec<Edge>>, start: usize, visitor: &TVisitor) {
let mut is_visited = vec![false; adj_list.len()];
fn search_impl(adj_list: &Vec<Vec<Edge>>, node: usize,... |
mod assertion;
mod ffi;
pub use self::assertion::*;
pub use self::ffi::*;
|
use ::misc::*;
pub fn parse_server_address <
ServerAddress: AsRef <str>,
> (
server_address: ServerAddress,
) -> (String, u16) {
let server_address =
server_address.as_ref ();
let server_address_parts: Vec <& str> =
server_address.split (":").collect ();
if server_address_parts.len () != 2 {
args::error... |
macro_rules! foo {
($a:ident, $b:ident, $c:ident) => {
struct a { value: $a };
struct b { value: $b };
};
($a:ident) => {
struct a { value: $a };
};
}
foo! {
A
}
|
pub mod exec;
pub mod repo;
pub mod repo_operations;
pub mod repositories;
|
#[doc = "Register `IER` reader"]
pub type R = crate::R<IER_SPEC>;
#[doc = "Register `IER` writer"]
pub type W = crate::W<IER_SPEC>;
#[doc = "Field `TAMP1IE` reader - TAMP1IE"]
pub type TAMP1IE_R = crate::BitReader<TAMP1IE_A>;
#[doc = "TAMP1IE\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum ... |
use itertools::{Itertools, TupleWindows};
use std::ops::Sub;
pub struct DiscreteDerivativeIter<I>
where
I: Iterator,
I::Item : Sub + Clone
{
window_iter: TupleWindows<I, (I::Item, I::Item)>
}
impl<I> Iterator for DiscreteDerivativeIter<I>
where
I: Iterator,
I::Item : Sub + Clone
{
type I... |
#[doc = "Register `PERIPH_ID_3` reader"]
pub type R = crate::R<PERIPH_ID_3_SPEC>;
#[doc = "Field `CUST_MOD_NUM` reader - Customer modification"]
pub type CUST_MOD_NUM_R = crate::FieldReader;
#[doc = "Field `REV_AND` reader - Customer version"]
pub type REV_AND_R = crate::FieldReader;
impl R {
#[doc = "Bits 0:3 - Cu... |
pub mod events {
pub fn process_command() {
loop {
println!("Please input an event command or help to see available commands or back to go back!");
let mut input = String::new();
std::io::stdin()
.read_line(&mut input)
.expect("Error parsi... |
#[doc = "Register `UR7` reader"]
pub type R = crate::R<UR7_SPEC>;
#[doc = "Field `SA_BEG_1` reader - Secured area start address for bank 1"]
pub type SA_BEG_1_R = crate::FieldReader<u16>;
#[doc = "Field `SA_END_1` reader - Secured area end address for bank 1"]
pub type SA_END_1_R = crate::FieldReader<u16>;
impl R {
... |
use nom::{
branch::alt,
bytes::complete::tag,
character::complete::{char, digit1},
combinator::map,
multi::fold_many0,
sequence::{delimited, pair},
IResult,
};
use std::fs::File;
use std::io::prelude::*;
#[derive(Debug, Clone)]
enum Expression {
Lit(usize),
Plus(Box<Expression>, Box... |
pub fn read<T: std::str::FromStr>() -> T {
let mut s = String::new();
std::io::stdin().read_line(&mut s).ok();
s.trim().parse().ok().unwrap()
}
pub fn read_vec<T: std::str::FromStr>() -> Vec<T> {
read::<String>()
.split_whitespace()
.map(|e| e.parse().ok().unwrap())
.collect()
}... |
//pub enum Transaction {
//// CreateWallet = 0,
// AddAssets = 1,
// DelAssets = 2,
// Exchange = 3,
// ExchangeWithIntermediary = 4,
// TradeAssets = 5,
// TradeAssetsWithIntermediary = 6,
// Transfer = 7,
//// Mining = 8,
//}
impl Transaction {
pub fn create(tx_n:TransactionNumber) -... |
// The square channels produced square waves and were generally used for the
// melody of the songs
use serde::{Deserialize, Serialize};
use super::LENGTH_TABLE;
// 0 - 0 1 0 0 0 0 0 0 (12.5%)
// 1 - 0 1 1 0 0 0 0 0 (25%)
// 2 - 0 1 1 1 1 0 0 0 (50%)
// 3 - 1 0 0 1 1 1 1 1 (25% negated)
/// Table of the different du... |
use std::fmt::{ Debug, Formatter, Result as FmtResult };
use std::ops::{ Add, Sub, Div, Mul, Rem };
use std::cmp::{ PartialEq, Ordering };
use std::hash::{ Hash, Hasher };
use std::rc::Rc;
use crate::common::{ Closure, Array, Table };
use crate::vm::{ VM, RuntimeError };
pub type BuiltIn = dyn Fn(&mut VM) -> Result<V... |
//! Serialize a Rust data structure into JSON data
use core::{fmt, mem};
use serde::ser;
use heapless::{String, Vec};
use self::seq::SerializeSeq;
use self::struct_::SerializeStruct;
mod seq;
mod struct_;
/// Serialization result
pub type Result<T> = ::core::result::Result<T, Error>;
/// This type represents all... |
mod grid_builder;
#[cfg(feature = "std")]
pub use grid_builder::*;
|
//! A high-performance Rust library for working with data from the
//! Cravatt lab's cimage proteomics program.
//!
//! This library's API is based around several types that form
//! a data analysis pipeline.
//!
//! Raw cimage_combined output is transformed into a [`Raw`] object,
//! which can then be grouped by prote... |
use crate::grammar::ast::{eq::AstEq, BinaryOp, Conditional, SelfLit, Underscore};
use crate::grammar::ast::{BooleanLit, Identifier};
use crate::grammar::model::{HasSourceReference, WrightInput};
use crate::grammar::tracing::{parsers::map, trace_result};
use nom::bytes::complete::take_while;
use nom::character::complete... |
extern crate sdl;
use rand::rngs::SmallRng;
use rand::{RngCore, SeedableRng};
use sdl::event::Event;
use retrofw2_rust::controls::*;
use retrofw2_rust::geom::Painter;
fn main() {
let (screen, video_info) = retrofw2_rust::gfx::init();
let mut pressed_keys = PressedKeys::default();
let start = std::time::... |
use manga::Manga;
use utils::chapter;
#[derive(Debug)]
pub struct DownloadError;
pub struct Downloader<'a> {
manga: &'a Manga<'a>,
download_url: String,
}
impl<'a> Downloader<'a> {
pub fn new(manga: &'a Manga) -> Downloader<'a> {
let download_url = format!("http://www.mangahere.co/manga/{}",
... |
use scan_fmt::*;
use std::io::Read;
use std::fs::File;
use std::time;
use std::thread;
#[derive(Debug,Copy,Clone,Eq,PartialEq)]
enum Tile {
Clay,
Sand,
Still,
Spring,
Drip,
}
fn parse() -> (Vec<Vec<Tile>>, (usize, usize), (usize,usize)) {
let mut file = File::open("input").unwrap();
let mu... |
//! Tests auto-converted from "sass-spec/spec/non_conformant/errors/loop-for/numeric"
#[allow(unused)]
use super::rsass;
// From "sass-spec/spec/non_conformant/errors/loop-for/numeric/lower_eval.hrx"
// Ignoring "lower_eval", error tests are not supported yet.
// From "sass-spec/spec/non_conformant/errors/loop-for/n... |
use bson::{Document};
use mongodb::{Client, ThreadedClient};
use mongodb::db::ThreadedDatabase;
use mongodb::coll::Collection;
use mime::Mime;
use error::{CommandError, CommandResult};
use asset::Asset;
use mongo::util::*;
pub struct MongoAsset {
coll: Collection,
id: String,
md5: String,
mime: Mime,
... |
use std::fs;
use wat::parse_file;
// This script is used to generate .wasm files from .wat files for benchmarks/tests and to build
// the plugins into .wasm files.
//
// It will write all generated .wasm files into the `./target/wasm` directory.
fn main() {
const WAT_DIR: &str = "wat";
const PLUGIN_DIR: &str =... |
// Copyright (c) Facebook, Inc. and its affiliates.
//
// This source code is licensed under the MIT license found in the
// LICENSE file in the root directory of this source tree.
use crypto::{BatchMerkleProof, ElementHasher, Hasher};
use math::{log2, FieldElement};
use utils::{
collections::Vec, string::ToString... |
//! Utility functions
pub mod account;
pub mod safe_token;
pub mod bpf_loader_upgradeable;
|
fn merge<T: Copy + PartialOrd>(x1: &[T], x2: &[T], y: &mut [T]) {
assert_eq!(x1.len() + x2.len(), y.len());
let mut i = 0;
let mut j = 0;
let mut k = 0;
while i < x1.len() && j < x2.len() {
if x1[i] < x2[j] {
y[k] = x1[i];
k += 1;
i += 1;
} else {
y[k] = x2[j];
k += 1;
j += 1;
}
}
if i < ... |
use std::path::Path;
use cc;
use crate::gen_cpu_features;
pub fn gcc_rte_config<S: AsRef<Path>>(rte_include_dir: &Vec<S>) -> cc::Build {
let mut build = cc::Build::new();
for dir in rte_include_dir {
build.include(dir);
}
build.flag("-march=native").cargo_metadata(true);
for (name, val... |
/// FSM states for Inventory handling
#[derive(Debug,Clone,PartialEq)]
pub enum States {
Closed,
Opened(Actions),
}
impl States {
pub fn dropable(&self) -> bool {
if *self == States::Closed { true }
else { false }
}
pub fn next (self, act: Actions) -> States {
match self {
... |
use crate::controller::base::{BaseController, ControllerOperation, Key};
use async_std::sync::Mutex;
use async_trait::async_trait;
use kube::Resource;
use std::{boxed::Box, sync::Arc};
#[async_trait]
pub trait EventProcessor<E>: Send + Sync {
async fn handle(&self, event: &E) -> Result<bool, ()>;
}
pub struct FnE... |
use std::net::{TcpListener, TcpStream};
fn handle_client(_stream: TcpStream) {
println!("HEY");
}
fn main() {
let listener = TcpListener::bind("127.0.0.1:5487").unwrap();
for stream in listener.incoming() {
match stream {
Ok(stream) => {
handle_client(stream);
... |
#![no_std]
// Requires -x c++
mod platformio;
use platformio::Arduino_h::{pinMode, digitalWrite, delay, HIGH, LOW};
#[no_mangle]
pub extern "C" fn setup() {
unsafe {
pinMode(19, 1);
}
}
#[no_mangle]
pub extern "C" fn r#loop() {
unsafe {
digitalWrite(19, HIGH as u8);
delay(2000);
... |
use advent_libs::input_helpers;
#[derive(Default, Debug)]
struct BoardingPass {
row: i32,
col: i32,
id: i32,
}
fn main() {
println!("Advent of Code 2020 - Day 5");
println!("---------------------------");
// Read in puzzle input
let mut input = input_helpers::read_puzzle_input_to_string(5);... |
fn main() {
println!("Fibonacci sequence");
for number in 0..20 {
println!("{}", fibonacci(number));
}
}
fn fibonacci(n: u32) -> u32 {
if n < 2 {
return 1;
}
let mut greater: u32 = 1;
let mut lesser: u32 = 1;
for _ in 1..n {
let temp: u32 = greater + lesser;
... |
#[derive(serde::Serialize, serde::Deserialize, Clone, Debug)]
pub enum LoginCheck {
NoCheck,
PasswordCheck,
PasswordImgCodeCheck,
PhoneCodeCheck,
}
|
use hacspec_lib::*;
array!(Block, 8, U32);
pub fn shuffle(b: Block) -> Block {
let mut b = b;
let tmp = b[0];
b[0] = b[1];
b[1] = tmp;
b
}
pub fn linear_manipulations(a: Seq<u8>) -> Seq<u8> {
let b = if true { a } else { a };
let mut c = b.clone();
if false {
c = c.update_star... |
extern crate bit_set;
extern crate rand;
use bit_set::BitSet;
use rand::prelude::*;
use super::model::*;
use super::parameters::*;
///
/// Utility function for flipping a bit in a BitSet
///
fn flip_bit(alleles: &mut BitSet, i: usize) -> () {
if alleles.contains(i) {
alleles.remove(i);
} else {
... |
//! The linker, which is used to link several objects into a ROM.
#![allow(missing_docs)]
#![allow(unused)]
use std::collections::hash_map::Entry;
use std::collections::HashMap;
use std::fmt;
use std::path::Path;
use crate::error;
use crate::int::u24;
use crate::obj;
use crate::obj::Object;
use crate::rom::Rom;
use ... |
use std::env::args;
use std::{fs, path};
use std::io::{stdin, stdout, Write};
use std::path::Path;
use termion::{color, style};
use termion::event::Key;
use termion::input::TermRead;
use termion::raw::IntoRawMode;
struct Doc {
lines: Vec<String>,
}
#[derive(Debug)]
struct CursorCoordinates {
pub x: usize,
... |
use std::rc::Rc;
use std::cell::RefCell;
use interceptor::{Interceptor, InterceptorChain};
use hyper::client::Response;
use error::ApiError;
pub struct LogInterceptor {
}
impl Interceptor for LogInterceptor {
fn intercept(&self, chain: InterceptorChain) -> Result<Rc<RefCell<Response>>, ApiError> {
let api... |
use libcnb::data::buildpack::BuildpackApi;
use serde::Deserialize;
use std::{
fs,
os::unix::fs::PermissionsExt,
path::Path,
process::{Command, ExitStatus, Stdio},
};
const DEFAULT_SHELL: &str = "#!/bin/sh";
#[derive(Deserialize)]
pub struct Script {
// Ignored since can't dynamically change the Bu... |
#![doc = "generated by AutoRust 0.1.0"]
#![allow(non_camel_case_types)]
#![allow(unused_imports)]
use serde::{Deserialize, Serialize};
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct MdeOnboardingDataProperties {
#[serde(rename = "onboardingPackageWindows", default, skip_serializing_if = "Opti... |
use failure::Context;
#[derive(Debug)]
pub struct Error {
inner: Context<ErrorKind>,
}
#[derive(Copy, Clone, Eq, PartialEq, Debug, Fail)]
pub enum ErrorKind {
#[fail(display = "The count of sigs should less than pks.")]
SigCountOverflow,
#[fail(display = "The count of sigs less than threshold.")]
... |
#[doc = "Reader of register SW_RES"]
pub type R = crate::R<u32, super::SW_RES>;
#[doc = "Writer for register SW_RES"]
pub type W = crate::W<u32, super::SW_RES>;
#[doc = "Register SW_RES `reset()`'s with value 0"]
impl crate::ResetValue for super::SW_RES {
type Type = u32;
#[inline(always)]
fn reset_value() ... |
#[doc = "Register `CCR4` reader"]
pub type R = crate::R<CCR4_SPEC>;
#[doc = "Register `CCR4` writer"]
pub type W = crate::W<CCR4_SPEC>;
#[doc = "Field `EN` reader - Channel enable"]
pub type EN_R = crate::BitReader;
#[doc = "Field `EN` writer - Channel enable"]
pub type EN_W<'a, REG, const O: u8> = crate::BitWriter<'a,... |
// q0150_evaluate_reverse_polish_notation
struct Solution;
impl Solution {
pub fn eval_rpn(tokens: Vec<String>) -> i32 {
let mut ret: Vec<i32> = vec![];
for item in tokens.into_iter() {
print!("{}", item);
if item == "+" {
let n1 = ret.pop().unwrap();
... |
#[derive(Debug)]
pub enum ClipboardError {
IOError(std::io::Error),
ImageError(image::ImageError),
}
impl std::error::Error for ClipboardError {}
impl std::fmt::Display for ClipboardError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
ClipboardError:... |
struct Matrix {
dat: [[i32; 3]; 3]
}
impl Matrix {
pub fn transpose_m(a: Matrix) -> Matrix
{
let mut out = Matrix {
dat: [[0, 0, 0],
[0, 0, 0],
[0, 0, 0]
]
};
for i in 0..3{
for j in 0..3{
... |
// 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... |
use std::{thread,time};
fn initialization() -> Vec<i32> {
let t = time::Duration::from_millis(15000);
thread::sleep(t);
println!("Initialize data.");
vec![1, 2, 3]
}
fn work(x: i32) -> i32 {
let t = time::Duration::from_millis(150);
thread::sleep(t);
println!("Work.");
x * x
}
fn main() {
... |
extern crate clap;
extern crate hyper;
use clap::{Arg, App};
use std::thread;
use hyper::client::Client;
fn start_attack(client: Client, url: &str) -> Result<hyper::status::StatusCode, hyper::Error>{
//TODO: Work on thread-based concurrency to handle multiple requests on multiple threads!
let res = client.... |
use gdk::RGBA;
use graphene::Rect;
use gsk::RoundedRect;
use gtk::prelude::*;
use gtk::subclass::prelude::*;
use gtk::{cairo, gdk, glib, graphene, gsk};
use std::cell::{Cell, RefCell};
use crate::color::Color;
use crate::utils::RotateVec;
const LEFT_WIDTH: f32 = 31.;
const HEIGHT: f32 = 200.;
glib::wrapper! {
pu... |
#[doc = "Register `SDCMR` reader"]
pub type R = crate::R<SDCMR_SPEC>;
#[doc = "Register `SDCMR` writer"]
pub type W = crate::W<SDCMR_SPEC>;
#[doc = "Field `MODE` reader - Command mode These bits define the command issued to the SDRAM device. Note: When a command is issued, at least one Command Target Bank bit ( CTB1 or... |
use btmeister::{construct, BuildToolDef, BuildToolDefs};
use clap::Parser;
use ignore::WalkBuilder;
use std::error::Error;
use std::fs::File;
use std::io::{stdin, stdout, BufRead, BufReader, BufWriter, Write};
use std::path::{Path, PathBuf};
mod btmeister;
mod cli;
mod formatter;
pub struct BuildTool {
path: Path... |
use crate::headers;
use crate::prelude::*;
use crate::resources::collection::{Collection, IndexingPolicy, PartitionKey};
use crate::resources::ResourceType;
use crate::responses::CreateCollectionResponse;
use azure_core::{ActivityId, No, ToAssign, UserAgent, Yes};
use http::StatusCode;
use std::convert::TryInto;
use st... |
// Copyright 2018 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.
//! Support for creating futures that represent timers.
//!
//! This module contains the `Timer` type which is a future that will resolve
//! at a particul... |
use crate::core::models::common::ValueDimension;
use crate::format::problem::reader::{ApiProblem, ProblemProperties};
use crate::format::problem::BalanceOptions;
use crate::format::problem::Objective::*;
use crate::format::TOUR_ORDER_CONSTRAINT_CODE;
use std::sync::Arc;
use vrp_core::construction::constraints::{Constra... |
use serde::{Deserialize, Serialize};
use jsonwebtoken::errors::ErrorKind;
use jsonwebtoken::{decode, encode, Algorithm, DecodingKey, EncodingKey, Header, Validation};
#[derive(Debug, Serialize, Deserialize)]
struct Claims {
sub: String,
company: String,
exp: usize,
}
fn main() {
let my_claims =
... |
extern crate regex;
use std::fs::File;
use std::io::BufReader;
use std::io::prelude::*;
use regex::Regex;
struct Point {
x: usize,
y: usize,
}
enum Action {
TurnOn { from: Point, to: Point },
TurnOff { from: Point, to: Point },
Toggle { from: Point, to: Point },
}
fn parse_line(s: &str) -> Act... |
lazy_static::lazy_static! {
/// Host name of the application. The web server only listens to request with a matching host name.
///
/// Field name: `HOST`
pub static ref HOST: String = std::env::var("HOST").unwrap_or_else(|_| "localhost".to_owned());
}
lazy_static::lazy_static! {
/// The applicatio... |
//! An event
use crate::{db_event::DBEvent, EnumEventData, EventData};
use chrono::{DateTime, Utc};
use serde::Deserialize;
use std::convert::TryFrom;
use uuid::Uuid;
/// Event definition
#[derive(Debug, Clone, PartialEq, serde_derive::Serialize, serde_derive::Deserialize)]
pub struct Event<D>
where
D: EventData,... |
extern crate colored;
extern crate structopt;
use std::io::prelude::*;
use structopt::StructOpt;
use colored::Colorize;
use rsc::computer::*;
use rsc::lexer::*;
use rsc::parser::*;
#[derive(StructOpt)]
#[structopt(
about = "A scientific calculator for the terminal.\nManual: https://github.com/asmoaesl/rsc/wiki... |
//! ITP1_7_Dの回答
//! [https://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=ITP1_7_D](https://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=ITP1_7_D)
use std::io::BufRead;
/// ITP1_7_Dの回答
#[allow(dead_code)]
pub fn main() {
loop {
if let Some((a, b)) = read_input(std::io::stdin().lock()) {
... |
use std::net;
use std::str::FromStr;
use std::ops::Drop;
use std::sync::{Condvar, Mutex};
// Helper function shared between client and server to parse the command line arguments
// and convert into an endpoint
pub fn parse_endpoint(ip_arg : Option<&String>, port_arg : Option<&String>) -> Result<net::SocketAddrV4, Stri... |
use std::fs;
type Position = (usize, usize, usize, usize);
fn extract_positions(line: &str) -> Position {
let v: Vec<usize> = line
.replace(" through ", ",")
.splitn(4, ',')
.map(|s| s.to_owned().parse().unwrap())
.collect();
(v[0], v[1], v[2], v[3])
}
fn part_1(input: &str) -... |
use crate::prop::Prop::*;
use crate::prop::*;
use crate::state::*;
pub fn eval(p: &Prop, s: &State) -> bool {
match p {
AND(p1, p2) => eval(p1, s) && eval(p2, s),
OR(p1, p2) => eval(p1, s) || eval(p2, s),
NOT(prop) => !eval(prop, s),
EQ(p1, p2) => eval(p1, s) == eval(p2, s),
... |
use crate::util::pagination::LinkHeader;
use nom::bytes::complete::tag;
use nom::character::complete::alphanumeric1;
use reqwest::Url;
use std::str::{from_utf8, FromStr};
/// Parses a Link HTTP Header
/// Link headers look like this:
/// <https://api.github.com/x/y/releases?page=1&per_page=5>; rel="next"
pub(crate... |
use std::cmp::min;
use std::collections::HashMap;
use std::io::{self};
fn parse_input(file_content: &Vec<String>) -> Vec<i32> {
file_content[0]
.split(",")
.collect::<Vec<_>>()
.iter()
.map(|x| x.parse::<i32>().unwrap())
.collect()
}
fn part_1(file_content: &Vec<String>) ->... |
use std::borrow::Cow;
use std::fs::File;
use std::io::prelude::*;
use std::slice;
use std::mem::{transmute, size_of, forget};
use std::io::{Write, Result, Error, ErrorKind};
/// object used to extend functionality of File
/// used for reading and writing byte vectors to files
pub trait VecIO {
fn write_slice_to_fi... |
use std::collections::HashSet;
#[derive(Debug)]
enum Step {
Up(u32),
Down(u32),
Left(u32),
Right(u32),
}
impl Step {
fn size(&self) -> u32 {
match *self {
Step::Up(x) | Step::Down(x) | Step::Left(x) | Step::Right(x) => x,
}
}
fn dir(&self) -> [i32; 2] {
... |
use arkecosystem_client::Connection;
use mockito::{mock, Matcher, Mock};
use std::fs::File;
use std::io::prelude::*;
const MOCK_HOST: &str = "http://127.0.0.1:1234/api/";
pub fn mock_http_request(endpoint: &str) -> (Mock, String) {
let url = Matcher::Regex(endpoint.to_owned());
let response_body = read_fixtur... |
use crate::packet::{Packet, PacketData, PacketHeader, Payload};
use byteorder::{BigEndian, ByteOrder};
pub trait PSI {
fn tables(&self) -> Option<&[u8]>;
}
impl PSI for Packet {
fn tables(&self) -> Option<&[u8]> {
if self.has_payload() {
let data = self.payload_data();
let padd... |
use std::time::Instant;
use loot_table::LootTable;
mod bank;
mod loot_table;
fn main() {
let now = Instant::now();
let mut table = LootTable {
total_weight: 0,
items: Vec::new(),
};
table
.add(123, 1)
.add(312, 3)
.add(33, 3)
.add(234, 3)
.add(... |
// support tags
//
// <html>, <head>, <body>
// <title>
// <h1>, <h2>, <h3>, <h4>, <h5> -> #
// <p>
// <a> -> []()
// <ol>, <ul>, <li>
// <div>
// <hr> -> ---
// <code> -> ```
//
// TODO:
// - split off tag name state from
use crate::utils::consumer::Consumer;
// reference: https://html.spec.whatwg.org/multipag... |
use ident::Identifier;
use ty::Ty;
use core::pos::BiPos;
use super::Statement;
#[derive(Debug, Clone)]
pub struct Fun{
pub ident: Identifier,
pub ty: Ty,
pub params: Vec<FunParam>,
pub body: Vec<Statement>,
pub pos: BiPos,
}
#[derive(Debug, Clone)]
pub struct FunParam{
pub ident: Identifier,... |
use std::sync::Arc;
use async_trait::async_trait;
use common::result::Result;
use identity::domain::user::{UserId, UserRepository};
use publishing::domain::reader::{Reader, ReaderId, ReaderRepository};
pub struct ReaderTranslator {
user_repo: Arc<dyn UserRepository>,
}
impl ReaderTranslator {
pub fn new(use... |
$NetBSD: patch-compiler_rustc__target_src_spec_i586__unknown__netbsd.rs,v 1.7 2023/01/23 18:49:04 he Exp $
Add an i586 / pentium variant, in an effort to support AMD Geode etc.
--- compiler/rustc_target/src/spec/i586_unknown_netbsd.rs.orig 2022-12-21 19:11:11.452711494 +0000
+++ compiler/rustc_target/src/spec/i586_un... |
pub mod file_header;
pub mod flags;
use std::{fmt::Debug, io::Read};
use crate::parsers::common::{subrecords, FormId, TypeCode};
use flags::{Flags, RecordFlags};
use byteorder::{LittleEndian, ReadBytesExt};
use flate2::read::ZlibDecoder;
use nom::{
bytes::complete::take,
combinator::map,
number::complete... |
use hyper::{client::HttpConnector, Client};
use hyper_rustls;
use std::cell::RefCell;
use std::rc::Rc;
use tokio_core::reactor::Core;
type HttpsConnector = hyper_rustls::HttpsConnector<HttpConnector>;
/// Struct used to make calls to the Github API.
pub struct Datadog {
token: String,
core: Rc<RefCell<Core>>,... |
use num::{abs, signum};
use num_integer::lcm;
use regex::Regex;
use std::collections::HashSet;
use std::error;
use std::io;
use std::io::BufRead;
use crate::day;
pub type BoxResult<T> = Result<T, Box<dyn error::Error>>;
#[derive(PartialEq, Eq, Hash, Clone)]
struct Space {
moons: Vec<Moon>,
}
impl Space {
fn ... |
pub(crate) mod s3m {
use crate::module_reader::{SongData, Patterns, Row, SongType, FrequencyType};
use std::io::{Read, Seek, SeekFrom};
use crate::io_helpers::{read_string, read_bytes, read_u8, BinaryReader, read_u32, read_u24};
use std::iter::FromIterator;
use crate::pattern::Pattern;
use crate... |
mod front_of_house {
pub mod hosting {
pub fn add_to_waitlist(ss: &String) {
println!("add_to_waitlist: {:?}", ss)
}
}
}
use crate::front_of_house::hosting; // item hosting
pub fn eat_at_restaurant() {
let hosting = String::from("god"); // var hosting
hosting::add_to_waitl... |
use sqlparser::ast::{Query, Select, SetExpr, Statement, TableFactor, TableWithJoins};
/// Collection of table identifiers parsed from SQL
pub struct Collector {
pub table_identifiers: Vec<String>,
}
impl Default for Collector {
fn default() -> Self {
Collector::new()
}
}
impl Collector {
pub f... |
/*
* Datadog API V1 Collection
*
* Collection of all Datadog Public endpoints.
*
* The version of the OpenAPI document: 1.0
* Contact: support@datadoghq.com
* Generated by: https://openapi-generator.tech
*/
/// WidgetGrouping : The kind of grouping to use.
/// The kind of grouping to use.
#[derive(Clone, Copy... |
pub fn binary_search(arr: Vec<i64>, x: i64) -> usize {
println!("inside binary search");
let n = arr.len();
let (mut l, mut r) = (0, n-1);
let mut mid;
while r-l > 1 {
mid = l + (r-l)/2;
if x >= arr[mid] {
l = mid;
} else {
r = mid-1;
}
}
... |
// Copyright 2018 Google LLC
//
// 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 ... |
use std::collections::HashMap;
pub fn predict_passwords() {
let mut count = 0;
for i in 206938..679128 {
if valid_num(i) {
count = count + 1;
}
}
println!("valid number count is {}", count);
}
fn valid_num(num: i32) -> bool {
let mut adj_num = HashMap::new();
let m... |
fn factory() -> Box<Fn(i32) -> i32> {
let num = 5;
Box::new(move |x| x + num)
}
trait Foo {
fn f(&self);
}
trait Bar {
fn f(&self);
}
struct Baz;
impl Foo for Baz {
fn f(&self) {
println!("Baz's impl of Foo");
}
}
impl Bar for Baz {
fn f(&self) {
println!("Baz's impl of... |
use syntect::{
highlighting::ThemeSet,
parsing::{SyntaxDefinition, SyntaxSet, SyntaxSetBuilder},
};
use crate::errors::{Error, HurlResult};
pub fn build() -> HurlResult<(SyntaxSet, ThemeSet)> {
macro_rules! load_syntax_def {
($builder:ident, $file:expr) => {
let syntax_def = include_st... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.