<commit_before>//
// Find a minimum spanning tree in a graph.
//
#include <algorithm>
#include <cassert>
#include <fstream>
#include <iostream>
#include <limits>
#include <vector>

#include "edge.hpp"
#include "point.hpp"

using namespace std;

static void load( const string& filename, vector<point>& );
static void print( vector<point>& );
static void print( vector<edge>& );
static void find_mininimum_spanning_tree( const vector<point>&, vector<edge>& );

int main( int argc, char **argv )
{
	int status = 0;

	cout << "Minimum Spanning Tree" << endl;

	for( int i = 1; i < argc; i++ ) {
		string filename( argv[i] );

		try {
			vector<point> points;
			vector<edge> edges;

			load( filename, points );
			find_mininimum_spanning_tree( points, edges );
			print( points );
			print( edges );
		}
		catch (const exception& e) {
			cout << "File     : " << filename << endl;
			cout << "Exception: " << e.what() << endl;
			status++;
		}
	}

	return status;
}

//
// Load a set of points from a file.
//
static void load( const string& filename, vector<point>& pts )
{
	cout << __FUNCTION__ << "( filename = " << filename << " )" << endl;
	ifstream in( filename );
	while ( true ) {
		int x = 0, y = 0;
		in >> x >> y;
		if ( ! in.good() )
			break;
		pts.emplace_back( point( x, y ) );
	}
	in.close();
}

static void print( vector<point>& pts )
{
	cout << "number of points = " << pts.size() << endl;
	for ( auto& p : pts )
		cout << "(" << p.get_x() << ", " << p.get_y() << ")\t";
	cout << endl;
}

static void print( vector<edge>& egs )
{
	cout << "number of edges = " << egs.size() << endl;
	for ( auto& e : egs ) {
		cout << '(' << e.get_a().get_x() << ',' << e.get_a().get_y()
			<< ") -> (" << e.get_b().get_x() << ',' << e.get_b().get_y()
			<< ") wt = " << e.get_length() << endl;
	}
	cout << endl;
}

//
// Use Prim's algorithm for finding the minimum spanning tree of a set of
// points.  Assumes a completely connected, bidirectional graph.
//
// 1. Select a point.
// 2. Find the nearest point not in the tree to a point in the tree,
//    construct an edge, and add it to the tree.
// 3.
//
static const float FMARK = numeric_limits<float>::max();
static const size_t SMARK = numeric_limits<size_t>::max();

struct item {
	size_t index;
	const point& pt;
	float cost;
	size_t near;
	item( size_t i, const point& p, float c = FMARK, size_t n = SMARK ) :
		index( i ), pt( p ), cost( c ), near( n ) {}
};

#if 0
// Determine if there are any available points to be added to the tree.
// Available points don't have a nearest (item.near == SMARK) point.
static bool points_available( vector<item>& items )
{
	for ( auto& i : items ) {
		if ( i.near == SMARK )
			return true;
	}
	return false;
}
#endif

static void print( vector<item>& items )
{
	cout << "index\tpoint\tcost\tnear" << endl;
	for ( auto& i : items ) {
		cout << i.index << '\t' << '(' << i.pt.get_x() << ',' << i.pt.get_y()
			<< ')' << '\t' << i.cost << '\t' << i.near << endl;
	}
}

static void find_mininimum_spanning_tree(
		const vector<point>& points,
		vector<edge>& edges )
{
	cout << __FUNCTION__ << endl;
	vector<item> point_table;

	size_t idx = 0;
	for ( auto& p : points )
		point_table.emplace_back( item( idx++, p ) );
	for (size_t i = 0; i < point_table.size(); i++ )
		assert( point_table[ i ].index == i );

	// This isn't Prim's algorithm.
	// It finds the shortest path to point 0.

	size_t this_index = 0;
	while ( this_index != SMARK ) {
		// The last point has no 'near' (it is near to another point)
		// so when this_index == SMARK all the points have been marked
		print( point_table );

		const point& p = point_table[ this_index ].pt;
		size_t index = SMARK;
		float cost = FMARK;
		for( auto& i : point_table ) {
			// point 'i' is available (and not the this index)
			if ( i.index != this_index && i.near == SMARK ) {
				float length = edge::calc_length( p, i.pt );
				if ( length < cost ) {
					index = i.index;
					cost = length;
				}
			}
		}
		point_table[ this_index ].cost = cost;
		point_table[ this_index ].near = index;
		this_index = index;
	}

	cout << "The final point_table" << endl;
	print( point_table );

	// Build the list of edges making up the spanning tree
	cout << "Build the list of edges" << endl;
	edges.clear();
	for (size_t i = 0; i < point_table.size(); i++ ) {
		// The last point connnected to the tree doesn't have a nearest
		// vertex (it's the nearest of another vertex) so skip it.
		if ( point_table[ i ].near == SMARK )
			continue;
		const point& u = point_table[ i ].pt;
		const point& v = point_table[ point_table[ i ].near ].pt;
		edges.emplace_back( edge( u, v ) );
	}
}

<commit_msg>Fixed MST algorithm.<commit_after>//
// Find a minimum spanning tree in a graph.
//
#include <algorithm>
#include <cassert>
#include <fstream>
#include <iostream>
#include <limits>
#include <vector>

#include "edge.hpp"
#include "point.hpp"

using namespace std;

// Cost and Index marks
static const float FMARK = numeric_limits<float>::max();
static const size_t SMARK = numeric_limits<size_t>::max();

// Tree table item
struct item {
	size_t index;
	const point& pt;
	float cost;
	size_t near;
	item( size_t i, const point& p, float c = FMARK, size_t n = SMARK ) :
		index( i ), pt( p ), cost( c ), near( n ) {}
};

static void find_minimum_spanning_tree( const vector<point>&, vector<edge>& );
static void load( const string& filename, vector<point>& );
static bool points_available( vector<item>& items );
static void print( vector<point>& );
static void print( vector<edge>& );
static void print( vector<item>& items );
static void print_csv( vector<edge>& );

static bool debug_print = false;

int main( int argc, char **argv )
{
	int status = 0;
	bool csv_edges = false;

	cout << "Minimum Spanning Tree" << endl;

	for( int i = 1; i < argc; i++ ) {
		string filename( argv[i] );
		if ( filename == "--verbose" ) {
			debug_print = true;
			continue;
		}
		if ( filename == "--quiet" ) {
			debug_print = false;
			continue;
		}
		if ( filename == "--csv" ) {
			csv_edges = true;
			continue;
		}

		try {
			vector<point> points;
			vector<edge> edges;

			load( filename, points );
			find_minimum_spanning_tree( points, edges );
			if ( debug_print )
				print( points );
			if ( csv_edges )
				print_csv( edges );
			else
				print( edges );
		}
		catch (const exception& e) {
			cout << "File     : " << filename << endl;
			cout << "Exception: " << e.what() << endl;
			status++;
		}
	}

	return status;
}

//
// Find the minimum spanning tree of a set of points.
// Assumes a completely connected, bidirectional graph.
//
// 1. Select a point and add it to the tree.
// 2. Find the nearest point not in the tree to a point in the tree
//    and add it to the tree.
// 3. Repeat #2 until all points are in the tree.
//
static void find_minimum_spanning_tree(
		const vector<point>& points,
		vector<edge>& edges )
{
	if ( debug_print )
		cout << __FUNCTION__ << endl;

	vector<item> point_table;

	size_t table_index = 0;
	for ( auto& p : points )
		point_table.emplace_back( item( table_index++, p ) );
	for (size_t i = 0; i < point_table.size(); i++ )
		assert( point_table[ i ].index == i );

	// Put point 0 in the tree
	point_table[ 0 ].near = 0;
	point_table[ 0 ].cost = 0;

	while ( points_available( point_table ) ) {
		if ( debug_print )
			print( point_table );

		size_t tree_index = SMARK;
		size_t index = SMARK;
		float cost = FMARK;
		for ( auto& t : point_table ) {
			// skip points not in tree (unmarked)
			if ( t.near == SMARK )
				continue;
			for ( auto& i : point_table ) {
				// point 'i' is available (not in tree)
				if ( i.near == SMARK ) {
					float length = edge::calc_length( t.pt, i.pt );
					if ( length < cost ) {
						tree_index = t.index;
						index = i.index;
						cost = length;
					}
				}
			}
		}
		// Connect this point to the tree
		point_table[ index ].cost = cost;
		point_table[ index ].near = tree_index;
	}

	if ( debug_print ) {
		cout << "The final point_table" << endl;
		print( point_table );
	}

	// Build the list of edges making up the spanning tree
	if ( debug_print )
		cout << "Build the list of edges" << endl;
	edges.clear();
	for (size_t i = 0; i < point_table.size(); i++ ) {
		// The first point connnected to the tree has itself as the nearest
		// vertex (it's the nearest of another vertex) so skip it.
		if ( point_table[ i ].near == i )
			continue;
		const point& u = point_table[ i ].pt;
		const point& v = point_table[ point_table[ i ].near ].pt;
		edges.emplace_back( edge( u, v ) );
	}
}

//
// Load a set of points from a file.
//
static void load( const string& filename, vector<point>& pts )
{
	if ( debug_print )
		cout << __FUNCTION__ << "( filename = " << filename << " )" << endl;

	ifstream in( filename );
	while ( true ) {
		int x = 0, y = 0;
		in >> x >> y;
		if ( ! in.good() )
			break;
		pts.emplace_back( point( x, y ) );
	}
	in.close();
}

//
// Print a vector of edges
//
static void print( vector<edge>& egs )
{
	cout << "number of edges = " << egs.size() << endl;
	for ( auto& e : egs ) {
		cout << '(' << e.get_a().get_x() << ',' << e.get_a().get_y()
			<< ") -> (" << e.get_b().get_x() << ',' << e.get_b().get_y()
			<< ") wt = " << e.get_length() << endl;
	}
	cout << endl;
}

//
// Print the "tree" table
//
static void print( vector<item>& items )
{
	cout << "index\tpoint\tcost\tnear" << endl;
	for ( auto& i : items ) {
		cout << i.index << '\t' << '(' << i.pt.get_x() << ',' << i.pt.get_y()
			<< ')' << '\t' << i.cost << '\t' << i.near << endl;
	}
}

//
// Print a vector of points
//
static void print( vector<point>& pts )
{
	cout << "number of points = " << pts.size() << endl;
	for ( auto& p : pts )
		cout << "(" << p.get_x() << ", " << p.get_y() << ")\t";
	cout << endl;
}

//
// Print a vector of edges (TAB separated)
//
static void print_csv( vector<edge>& egs )
{
	cout << "x1\ty1\tx2\ty2\twt" << endl;
	for ( auto& e : egs ) {
		cout <<  e.get_a().get_x() << '\t' << e.get_a().get_y() << '\t'
				<< e.get_b().get_x() << '\t' << e.get_b().get_y() << '\t'
				<< e.get_length() << endl;
	}
	cout << endl;
}

// Determine if there are any available points to be added to the tree.
// Available points don't have a nearest (item.near == SMARK) point.
static bool points_available( vector<item>& items )
{
	for ( auto& i : items ) {
		if ( i.near == SMARK )
			return true;
	}
	return false;
}

<|endoftext|>


<commit_before>

AliAnalysisTaskEMCALIsoPhoton *AddTaskEMCALIsoPhoton(
						     TString period = "LHC11d",
						     TString trigbitname = "kEMC7",
						     TString pathstrsel = "/"
						     )
{
  // Get the pointer to the existing analysis manager via the static access method.
  //==============================================================================
  AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
  if (!mgr) {
    ::Error("AddTaskEMCALIsoPhoton", "No analysis manager to connect to.");
    return NULL;
  }

  // Create the task and configure it.
  //===========================================================================
  AliAnalysisTaskEMCALIsoPhoton* ana = new  AliAnalysisTaskEMCALIsoPhoton("");

  Bool_t isMC = (mgr->GetMCtruthEventHandler() != NULL);

  if(!isMC)
    ana->SelectCollisionCandidates( AliVEvent::kEMC1 | AliVEvent::kMB | AliVEvent::kEMC7 | AliVEvent::kINT7);

  //ana->SetClusThreshold(clusTh);

  ana->SetTrainMode(kTRUE);
  ana->SetTriggerBit(trigbitname);
  ana->SetMcMode(isMC);
  ana->SetPathStringSelect(pathstrsel.Data());
  AliESDtrackCuts *cutsp = new AliESDtrackCuts;
  cutsp->SetMinNClustersTPC(70);
  cutsp->SetMinRatioCrossedRowsOverFindableClustersTPC(0.8);
  cutsp->SetMaxChi2PerClusterTPC(4);
  cutsp->SetRequireTPCRefit(kTRUE);
  cutsp->SetAcceptKinkDaughters(kFALSE);
  cutsp->SetMaxDCAToVertexZ(3.2);
  cutsp->SetMaxDCAToVertexXY(2.4);
  cutsp->SetDCAToVertex2D(kTRUE);
  cutsp->SetPtRange(0.2);
  cutsp->SetEtaRange(-1.0,1.0);
  ana->SetPrimTrackCuts(cutsp);
  ana->SetPeriod(period.Data());
  if(period.Contains("11")){
    ana->SetGeoName("EMCAL_COMPLETEV1");
    //ana->SetImportGeometryFromFile(kTRUE,"$ALICE_ROOT/OADB/EMCAL/geometry_2011.root");
  }
  else{
    if(period.Contains("12")){
      if(isMC){
	ana->SetGeoName("EMCAL_COMPLETEV1");
	//ana->SetImportGeometryFromFile(kTRUE,"$ALICE_ROOT/OADB/EMCAL/geometry_2011.root");
      }
      else{
	ana->SetGeoName("EMCAL_COMPLETE12SMV1");
	//ana->SetImportGeometryFromFile(kTRUE,"$ALICE_ROOT/OADB/EMCAL/geometry_2012.root");
      }
    }
    else{
    ana->SetGeoName("EMCAL_FIRSTYEARV1");
    //ana->SetImportGeometryFromFile(kTRUE,"$ALICE_ROOT/OADB/EMCAL/geometry_2010.root");
    }
  }

  mgr->AddTask(ana);
  TString containername = "histosEMCALIsoPhoton";
  if(pathstrsel != "/"){
    TString dirpth = (TSubString)pathstrsel.operator()(1,1);
    containername += dirpth;
  }

  // Create ONLY the output containers for the data produced by the task.
  // Get and connect other common input/output containers via the manager as below
  //==============================================================================
  AliAnalysisDataContainer *coutput1 = mgr->CreateContainer(containername.Data(),
							    TList::Class(),AliAnalysisManager::kOutputContainer,
							    Form("%s", AliAnalysisManager::GetCommonFileName()));

  mgr->ConnectInput  (ana, 0, mgr->GetCommonInputContainer());
  mgr->ConnectOutput (ana, 1, coutput1 );

  return ana;
}
<commit_msg>including EMCal geometry explicitly as an input parameter<commit_after>

AliAnalysisTaskEMCALIsoPhoton *AddTaskEMCALIsoPhoton(
						     TString period = "LHC11d",
						     TString trigbitname = "kEMC7",
						     TString pathstrsel = "/",
						     TString geoname="EMCAL_COMPLETEV1"
						     )
{
  // Get the pointer to the existing analysis manager via the static access method.
  //==============================================================================
  AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
  if (!mgr) {
    ::Error("AddTaskEMCALIsoPhoton", "No analysis manager to connect to.");
    return NULL;
  }

  // Create the task and configure it.
  //===========================================================================
  AliAnalysisTaskEMCALIsoPhoton* ana = new  AliAnalysisTaskEMCALIsoPhoton("");

  Bool_t isMC = (mgr->GetMCtruthEventHandler() != NULL);

  if(!isMC)
    ana->SelectCollisionCandidates( AliVEvent::kEMC1 | AliVEvent::kMB | AliVEvent::kEMC7 | AliVEvent::kINT7);

  //ana->SetClusThreshold(clusTh);

  ana->SetTrainMode(kTRUE);
  ana->SetTriggerBit(trigbitname);
  ana->SetMcMode(isMC);
  ana->SetPathStringSelect(pathstrsel.Data());
  AliESDtrackCuts *cutsp = new AliESDtrackCuts;
  cutsp->SetMinNClustersTPC(70);
  cutsp->SetMinRatioCrossedRowsOverFindableClustersTPC(0.8);
  cutsp->SetMaxChi2PerClusterTPC(4);
  cutsp->SetRequireTPCRefit(kTRUE);
  cutsp->SetAcceptKinkDaughters(kFALSE);
  cutsp->SetMaxDCAToVertexZ(3.2);
  cutsp->SetMaxDCAToVertexXY(2.4);
  cutsp->SetDCAToVertex2D(kTRUE);
  cutsp->SetPtRange(0.2);
  cutsp->SetEtaRange(-1.0,1.0);
  ana->SetPrimTrackCuts(cutsp);
  ana->SetPeriod(period.Data());
  ana->SetGeoName(geoname.Data());
  mgr->AddTask(ana);
  TString containername = "histosEMCALIsoPhoton";
  if(pathstrsel != "/"){
    TString dirpth = (TSubString)pathstrsel.operator()(1,1);
    containername += dirpth;
  }

  // Create ONLY the output containers for the data produced by the task.
  // Get and connect other common input/output containers via the manager as below
  //==============================================================================
  AliAnalysisDataContainer *coutput1 = mgr->CreateContainer(containername.Data(),
							    TList::Class(),AliAnalysisManager::kOutputContainer,
							    Form("%s", AliAnalysisManager::GetCommonFileName()));

  mgr->ConnectInput  (ana, 0, mgr->GetCommonInputContainer());
  mgr->ConnectOutput (ana, 1, coutput1 );

  return ana;
}
<|endoftext|>


<commit_before>//
// ulib - a collection of useful classes
// Copyright (C) 2000-2017 Michael Fink
//
/// \file Atl.hpp ATL includes
//
#pragma once

// ignore /analyze warnings in ATL header files
#pragma warning(push)
#pragma warning(disable: 6001 6031 6387 26110)

/// prevent ATL using stuff removed by WIN32_LEAN_AND_MEAN
#define ATL_NO_LEAN_AND_MEAN

/// no min-max macros, we use std::min / std::max instead
#define NOMINMAX

// min and max macros are used in atlcom.h, etc., so temporarily define them here
#ifndef min
#  define min(x,y) (x) < (y) ? (x) : (y) ///< temporary define of min()
#endif

#ifndef max
#  define max(x,y) (x) > (y) ? (x) : (y) ///< temporary define of min()
#endif

// ATL includes
#include <atlbase.h>

#if _ATL_VER < 0x0700
#error ATL7 or higher must be used to compile
#endif

#include <atlcoll.h>
#include <atlstr.h>
#include <atltypes.h>
#include <atlwin.h>
#include <atlcom.h>
#include <atlhost.h>

// for _stdcallthunk
#include <atlstdthunk.h>

// atlimage.h declares throw() on methods that may throw; this would lead to calling
// std::unexpected(), which would quit the application; define throw() as empty macro in order to
// get the different behavior that exceptions are propagated to the caller.
#define throw()
#pragma warning(disable: 4002) // too many actual parameters for macro 'throw'
#include <atlimage.h>
#undef throw
#pragma warning(pop)

// undef the macros so that std::min and std::max work as they should be
#undef min
#undef max
<commit_msg>properly define NOMINMAX so that no "redefined" warnings appear<commit_after>//
// ulib - a collection of useful classes
// Copyright (C) 2000-2017 Michael Fink
//
/// \file Atl.hpp ATL includes
//
#pragma once

// ignore /analyze warnings in ATL header files
#pragma warning(push)
#pragma warning(disable: 6001 6031 6387 26110)

/// prevent ATL using stuff removed by WIN32_LEAN_AND_MEAN
#define ATL_NO_LEAN_AND_MEAN

/// no min-max macros, we use std::min / std::max instead
#define NOMINMAX 1

// min and max macros are used in atlcom.h, etc., so temporarily define them here
#ifndef min
#  define min(x,y) (x) < (y) ? (x) : (y) ///< temporary define of min()
#endif

#ifndef max
#  define max(x,y) (x) > (y) ? (x) : (y) ///< temporary define of min()
#endif

// ATL includes
#include <atlbase.h>

#if _ATL_VER < 0x0700
#error ATL7 or higher must be used to compile
#endif

#include <atlcoll.h>
#include <atlstr.h>
#include <atltypes.h>
#include <atlwin.h>
#include <atlcom.h>
#include <atlhost.h>

// for _stdcallthunk
#include <atlstdthunk.h>

// atlimage.h declares throw() on methods that may throw; this would lead to calling
// std::unexpected(), which would quit the application; define throw() as empty macro in order to
// get the different behavior that exceptions are propagated to the caller.
#define throw()
#pragma warning(disable: 4002) // too many actual parameters for macro 'throw'
#include <atlimage.h>
#undef throw
#pragma warning(pop)

// undef the macros so that std::min and std::max work as they should be
#undef min
#undef max
<|endoftext|>


<commit_before><commit_msg>use result from Traverse instead of counting ourselves<commit_after><|endoftext|>


<commit_before>// Copyright (c) 2015, Baidu.com, Inc. All Rights Reserved
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
// Copyright (c) 2011 The LevelDB Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file. See the AUTHORS file for names of contributors.

#include <stdio.h>
#include <stdlib.h>
#include "util/random.h"
#include "util/testutil.h"

// Comma-separated list of operations to run in the specified order
//   Actual benchmarks:
//
//   seq       -- output N values in sequential key order
//   random    -- output N values in random key order
static const char* FLAGS_benchmarks =
    "seq,"
    "random,"
    ;

// Number of key/values to place in database
static int FLAGS_num = 1000000;

// Number of read operations to do.  If negative, do FLAGS_num reads.
static int FLAGS_reads = -1;

// Size of each key
static int FLAGS_key_size = 16;

// Size of each value
static int FLAGS_value_size = 100;

// Arrange to generate values that shrink to this fraction of
// their original size after compression
static double FLAGS_compression_ratio = 0.5;

// Number of tablets
static int FLAGS_tablet_num = 1;

// CF list in format: "cf0:q1,cf1:q2..."
static std::string FLAGS_cf_list = "";

// Seq mode start key
static int FLAGS_start_key = 0;

// Generate different data each time
static char FLAGS_random_seed = 'f';

namespace leveldb {

// Helper for quickly generating random data.
namespace {
class RandomGenerator {
 private:
  std::string data_;
  int pos_;

 public:
  RandomGenerator() {
    // We use a limited amount of data over and over again and ensure
    // that it is larger than the compression window (32KB), and also
    // large enough to serve all typical value sizes we want to write.
    Random rnd(FLAGS_random_seed);
    std::string piece;
    while (data_.size() < 1048576) {
      // Add a short fragment that is as compressible as specified
      // by FLAGS_compression_ratio.
      test::CompressibleString(&rnd, FLAGS_compression_ratio, 100, &piece);
      data_.append(piece);
    }
    pos_ = 0;
  }

  Slice Generate(int len) {
    if (pos_ + len > static_cast<int>(data_.size())) {
      pos_ = 0;
      assert(len < static_cast<int>(data_.size()));
    }
    pos_ += len;
    return Slice(data_.data() + pos_ - len, len);
  }
};

}  // namespace

class Benchmark {
 private:
  int num_;
  int reads_;
  double start_;
  int64_t bytes_;
  std::string message_;
  RandomGenerator gen_;
  Random rand_;
  Random** tablet_rand_vector_;

  // State kept for progress messages
  int done_;
  int next_report_;     // When to report next

  void Start() {
    start_ = Env::Default()->NowMicros() * 1e-6;
    bytes_ = 0;
    message_.clear();
    done_ = 0;
    next_report_ = 100;
  }

  void Stop(const Slice& name) {
    double finish = Env::Default()->NowMicros() * 1e-6;

    // Pretend at least one op was done in case we are running a benchmark
    // that does not call FinishedSingleOp().
    if (done_ < 1) done_ = 1;

    if (bytes_ > 0) {
      char rate[100];
      snprintf(rate, sizeof(rate), "%6.1f MB/s",
               (bytes_ / 1048576.0) / (finish - start_));
      if (!message_.empty()) {
        message_  = std::string(rate) + " " + message_;
      } else {
        message_ = rate;
      }
    }

    fprintf(stderr, "%-12s : %11.3f micros/op;%s%s\n",
            name.ToString().c_str(),
            (finish - start_) * 1e6 / done_,
            (message_.empty() ? "" : " "),
            message_.c_str());
    fflush(stderr);
  }

 public:
  enum Order {
    SEQUENTIAL,
    RANDOM
  };

  Benchmark()
  : num_(FLAGS_num),
    reads_(FLAGS_reads < 0 ? FLAGS_num : FLAGS_reads),
    bytes_(0),
    rand_(FLAGS_random_seed) {
    tablet_rand_vector_ = new Random*[FLAGS_tablet_num];
    for (int i = 0; i < FLAGS_tablet_num; i++) {
      tablet_rand_vector_[i] = new Random(FLAGS_random_seed);
    }
  }

  ~Benchmark() {
    for (int i = 0; i < FLAGS_tablet_num; i++) {
      delete tablet_rand_vector_[i];
    }
    delete[] tablet_rand_vector_;
  }

  void Run() {
    // parse cf list
    std::vector<std::string> cfs;
    if (FLAGS_cf_list != "") {
      std::string buffer = FLAGS_cf_list;
      size_t start_index = 0;
      size_t end_index = buffer.find(",");
      while (end_index != std::string::npos) {
        cfs.push_back(buffer.substr(start_index, end_index - start_index));
        start_index = end_index + 1;
        end_index = buffer.find(",", start_index);
      }
      cfs.push_back(buffer.substr(start_index));
    }

    const char* benchmarks = FLAGS_benchmarks;
    while (benchmarks != NULL) {
      const char* sep = strchr(benchmarks, ',');
      Slice name;
      if (sep == NULL) {
        name = benchmarks;
        benchmarks = NULL;
      } else {
        name = Slice(benchmarks, sep - benchmarks);
        benchmarks = sep + 1;
      }

      Start();

      bool known = true;
      if (name == Slice("seq")) {
        Output(SEQUENTIAL, num_, FLAGS_value_size, cfs);
      } else if (name == Slice("random")) {
        Output(RANDOM, num_, FLAGS_value_size, cfs);
      } else {
        known = false;
        if (name != Slice()) {  // No error message for empty name
          fprintf(stderr, "unknown benchmark '%s'\n", name.ToString().c_str());
        }
      }
      if (known) {
        Stop(name);
      }
    }
  }

 private:

  void Output(Order order, int num_entries, int value_size, std::vector<std::string>& cfs) {
    if (num_entries != num_) {
      char msg[100];
      snprintf(msg, sizeof(msg), "(%d ops)", num_entries);
      message_ = msg;
    }

    // Write to database
    int i = FLAGS_start_key;
    int end_key = i + num_entries;
    for (; i < end_key; i++)
    {
      const int t = rand_.Next() % FLAGS_tablet_num;
      const int k = (order == SEQUENTIAL) ? i : (tablet_rand_vector_[t]->Next());
      char key[10000];
      snprintf(key, sizeof(key), "%06d%0*d", t, FLAGS_key_size - 6, k);
      bytes_ += value_size + strlen(key);
      if (cfs.empty() == true) {
        fprintf(stdout, "%s\t%s\n", key, gen_.Generate(value_size).ToString().c_str());
      } else {
        for (size_t j = 0; j < cfs.size(); ++j) {
          fprintf(stdout, "%s\t%s\t%s\t%s\n", key, gen_.Generate(value_size).ToString().c_str(), cfs[j].c_str(), "0");
        }
      }
    }
  }
};

}  // namespace leveldb

int main(int argc, char** argv) {
  for (int i = 1; i < argc; i++) {
    double d;
    int n;
    char junk;
    char cf_list[1024];
    if (leveldb::Slice(argv[i]).starts_with("--benchmarks=")) {
      FLAGS_benchmarks = argv[i] + strlen("--benchmarks=");
    } else if (sscanf(argv[i], "--compression_ratio=%lf%c", &d, &junk) == 1) {
      FLAGS_compression_ratio = d;
    } else if (sscanf(argv[i], "--num=%d%c", &n, &junk) == 1) {
      FLAGS_num = n;
    } else if (sscanf(argv[i], "--reads=%d%c", &n, &junk) == 1) {
      FLAGS_reads = n;
    } else if (sscanf(argv[i], "--key_size=%d%c", &n, &junk) == 1 && n < 10000) {
      FLAGS_key_size = n;
    } else if (sscanf(argv[i], "--value_size=%d%c", &n, &junk) == 1) {
      FLAGS_value_size = n;
    } else if (sscanf(argv[i], "--tablet_num=%d%c", &n, &junk) == 1) {
      FLAGS_tablet_num = n;
    } else if (sscanf(argv[i], "--cf=%s", cf_list) == 1) {
      FLAGS_cf_list = std::string(cf_list);
    } else if (sscanf(argv[i], "--start_key=%d%c", &n, &junk) == 1) {
      FLAGS_start_key = n;
    } else if (sscanf(argv[i], "--random=%c", &junk) == 1) {
      if (junk == 't') {
        FLAGS_random_seed = time(NULL);
      } else {
        FLAGS_random_seed = 301;
      }

    } else {
      fprintf(stderr, "Invalid flag '%s'\n", argv[i]);
      exit(1);
    }
  }

  leveldb::Benchmark benchmark;
  benchmark.Run();
  return 0;
}
<commit_msg>fix flag type in tera_bench<commit_after>// Copyright (c) 2015, Baidu.com, Inc. All Rights Reserved
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
// Copyright (c) 2011 The LevelDB Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file. See the AUTHORS file for names of contributors.

#include <stdio.h>
#include <stdlib.h>
#include "util/random.h"
#include "util/testutil.h"

// Comma-separated list of operations to run in the specified order
//   Actual benchmarks:
//
//   seq       -- output N values in sequential key order
//   random    -- output N values in random key order
static const char* FLAGS_benchmarks =
    "seq,"
    "random,"
    ;

// Number of key/values to place in database
static int FLAGS_num = 1000000;

// Number of read operations to do.  If negative, do FLAGS_num reads.
static int FLAGS_reads = -1;

// Size of each key
static int FLAGS_key_size = 16;

// Size of each value
static int FLAGS_value_size = 100;

// Arrange to generate values that shrink to this fraction of
// their original size after compression
static double FLAGS_compression_ratio = 0.5;

// Number of tablets
static int FLAGS_tablet_num = 1;

// CF list in format: "cf0:q1,cf1:q2..."
static std::string FLAGS_cf_list = "";

// Seq mode start key
static int FLAGS_start_key = 0;

// Generate different data each time
static int FLAGS_random_seed = 301;

namespace leveldb {

// Helper for quickly generating random data.
namespace {
class RandomGenerator {
 private:
  std::string data_;
  int pos_;

 public:
  RandomGenerator() {
    // We use a limited amount of data over and over again and ensure
    // that it is larger than the compression window (32KB), and also
    // large enough to serve all typical value sizes we want to write.
    Random rnd(FLAGS_random_seed);
    std::string piece;
    while (data_.size() < 1048576) {
      // Add a short fragment that is as compressible as specified
      // by FLAGS_compression_ratio.
      test::CompressibleString(&rnd, FLAGS_compression_ratio, 100, &piece);
      data_.append(piece);
    }
    pos_ = 0;
  }

  Slice Generate(int len) {
    if (pos_ + len > static_cast<int>(data_.size())) {
      pos_ = 0;
      assert(len < static_cast<int>(data_.size()));
    }
    pos_ += len;
    return Slice(data_.data() + pos_ - len, len);
  }
};

}  // namespace

class Benchmark {
 private:
  int num_;
  int reads_;
  double start_;
  int64_t bytes_;
  std::string message_;
  RandomGenerator gen_;
  Random rand_;
  Random** tablet_rand_vector_;

  // State kept for progress messages
  int done_;
  int next_report_;     // When to report next

  void Start() {
    start_ = Env::Default()->NowMicros() * 1e-6;
    bytes_ = 0;
    message_.clear();
    done_ = 0;
    next_report_ = 100;
  }

  void Stop(const Slice& name) {
    double finish = Env::Default()->NowMicros() * 1e-6;

    // Pretend at least one op was done in case we are running a benchmark
    // that does not call FinishedSingleOp().
    if (done_ < 1) done_ = 1;

    if (bytes_ > 0) {
      char rate[100];
      snprintf(rate, sizeof(rate), "%6.1f MB/s",
               (bytes_ / 1048576.0) / (finish - start_));
      if (!message_.empty()) {
        message_  = std::string(rate) + " " + message_;
      } else {
        message_ = rate;
      }
    }

    fprintf(stderr, "%-12s : %11.3f micros/op;%s%s\n",
            name.ToString().c_str(),
            (finish - start_) * 1e6 / done_,
            (message_.empty() ? "" : " "),
            message_.c_str());
    fflush(stderr);
  }

 public:
  enum Order {
    SEQUENTIAL,
    RANDOM
  };

  Benchmark()
  : num_(FLAGS_num),
    reads_(FLAGS_reads < 0 ? FLAGS_num : FLAGS_reads),
    bytes_(0),
    rand_(FLAGS_random_seed) {
    tablet_rand_vector_ = new Random*[FLAGS_tablet_num];
    for (int i = 0; i < FLAGS_tablet_num; i++) {
      tablet_rand_vector_[i] = new Random(FLAGS_random_seed);
    }
  }

  ~Benchmark() {
    for (int i = 0; i < FLAGS_tablet_num; i++) {
      delete tablet_rand_vector_[i];
    }
    delete[] tablet_rand_vector_;
  }

  void Run() {
    // parse cf list
    std::vector<std::string> cfs;
    if (FLAGS_cf_list != "") {
      std::string buffer = FLAGS_cf_list;
      size_t start_index = 0;
      size_t end_index = buffer.find(",");
      while (end_index != std::string::npos) {
        cfs.push_back(buffer.substr(start_index, end_index - start_index));
        start_index = end_index + 1;
        end_index = buffer.find(",", start_index);
      }
      cfs.push_back(buffer.substr(start_index));
    }

    const char* benchmarks = FLAGS_benchmarks;
    while (benchmarks != NULL) {
      const char* sep = strchr(benchmarks, ',');
      Slice name;
      if (sep == NULL) {
        name = benchmarks;
        benchmarks = NULL;
      } else {
        name = Slice(benchmarks, sep - benchmarks);
        benchmarks = sep + 1;
      }

      Start();

      bool known = true;
      if (name == Slice("seq")) {
        Output(SEQUENTIAL, num_, FLAGS_value_size, cfs);
      } else if (name == Slice("random")) {
        Output(RANDOM, num_, FLAGS_value_size, cfs);
      } else {
        known = false;
        if (name != Slice()) {  // No error message for empty name
          fprintf(stderr, "unknown benchmark '%s'\n", name.ToString().c_str());
        }
      }
      if (known) {
        Stop(name);
      }
    }
  }

 private:

  void Output(Order order, int num_entries, int value_size, std::vector<std::string>& cfs) {
    if (num_entries != num_) {
      char msg[100];
      snprintf(msg, sizeof(msg), "(%d ops)", num_entries);
      message_ = msg;
    }

    // Write to database
    int i = FLAGS_start_key;
    int end_key = i + num_entries;
    for (; i < end_key; i++)
    {
      const int t = rand_.Next() % FLAGS_tablet_num;
      const int k = (order == SEQUENTIAL) ? i : (tablet_rand_vector_[t]->Next());
      char key[10000];
      snprintf(key, sizeof(key), "%06d%0*d", t, FLAGS_key_size - 6, k);
      bytes_ += value_size + strlen(key);
      if (cfs.empty() == true) {
        fprintf(stdout, "%s\t%s\n", key, gen_.Generate(value_size).ToString().c_str());
      } else {
        for (size_t j = 0; j < cfs.size(); ++j) {
          fprintf(stdout, "%s\t%s\t%s\t%s\n", key, gen_.Generate(value_size).ToString().c_str(), cfs[j].c_str(), "0");
        }
      }
    }
  }
};

}  // namespace leveldb

int main(int argc, char** argv) {
  for (int i = 1; i < argc; i++) {
    double d;
    int n;
    char junk;
    char cf_list[1024];
    if (leveldb::Slice(argv[i]).starts_with("--benchmarks=")) {
      FLAGS_benchmarks = argv[i] + strlen("--benchmarks=");
    } else if (sscanf(argv[i], "--compression_ratio=%lf%c", &d, &junk) == 1) {
      FLAGS_compression_ratio = d;
    } else if (sscanf(argv[i], "--num=%d%c", &n, &junk) == 1) {
      FLAGS_num = n;
    } else if (sscanf(argv[i], "--reads=%d%c", &n, &junk) == 1) {
      FLAGS_reads = n;
    } else if (sscanf(argv[i], "--key_size=%d%c", &n, &junk) == 1 && n < 10000) {
      FLAGS_key_size = n;
    } else if (sscanf(argv[i], "--value_size=%d%c", &n, &junk) == 1) {
      FLAGS_value_size = n;
    } else if (sscanf(argv[i], "--tablet_num=%d%c", &n, &junk) == 1) {
      FLAGS_tablet_num = n;
    } else if (sscanf(argv[i], "--cf=%s", cf_list) == 1) {
      FLAGS_cf_list = std::string(cf_list);
    } else if (sscanf(argv[i], "--start_key=%d%c", &n, &junk) == 1) {
      FLAGS_start_key = n;
    } else if (sscanf(argv[i], "--random=%c", &junk) == 1) {
      if (junk == 't') {
        FLAGS_random_seed = time(NULL);
      } else {
        FLAGS_random_seed = 301;
      }

    } else {
      fprintf(stderr, "Invalid flag '%s'\n", argv[i]);
      exit(1);
    }
  }

  leveldb::Benchmark benchmark;
  benchmark.Run();
  return 0;
}
<|endoftext|>


<commit_before>#include <nds.h>
#include <maxmod9.h>
#include <stdio.h>

#include "ball.h"
#include "geometry.h"
#include "player.h"
#include "stats.h"

// Audio
#include "soundbank.h"
#include "soundbank_bin.h"

// Methods

void initBall(ball *b) {
    b->speed = 1.5;
    b->box.pos.x = 100;
    b->box.pos.y = 30;
    b->box.width = 12;
    b->box.height = 12;
    b->direction.x = 1;
    b->direction.y = 1;

    b->sprite_offx = -2;
    b->sprite_offy = -2;

    // SFX_WALL
    b->sfx_wall.id = SFX_WALL;
    b->sfx_wall.rate = 1024;
    b->sfx_wall.handle = 0;
    b->sfx_wall.volume = 255;
    b->sfx_wall.panning = 128;

    // SFX_PANEL
    b->sfx_panel.id = SFX_PANEL;
    b->sfx_panel.rate = 1024;
    b->sfx_panel.handle = 0;
    b->sfx_panel.volume = 255;
    b->sfx_panel.panning = 128;

    // SFX_READY
    b->sfx_scoring.id = SFX_READY;
    b->sfx_scoring.rate = 1024;
    b->sfx_scoring.handle = 0;
    b->sfx_scoring.volume = 255;
    b->sfx_scoring.panning = 128;
}

/**
 * @param ball b
 * @return void
 */
void moveBall(ball *b, player *p1, player *p2, scoreBox *sBox) {
    b->box.pos.x += b->direction.x * b->speed;
    b->box.pos.y += b->direction.y * b->speed;

    bool hitLeftPaddle = intersect(b->box, p1->box);
    bool hitRightPaddle = intersect(b->box, p2->box);

    // horizontal collision
    if (b->box.pos.x <= 0) {
       scoring(1, b, sBox);
    } else if (b->box.pos.x + b->box.width >= SCREEN_WIDTH) {
       scoring(0, b, sBox);
    } else if (hitLeftPaddle || hitRightPaddle) {
        // calculate relative position to player box, then set direction according to that relative position
        // if relative position is low (i.e. closer to 0, the ball hit the paddle early),
        // then the ball goes back in the direction it came from
        // if relative position is high (i.e. closer to 1, the ball hit the paddle late),
        // then the ball bounces off the paddle, going off in the other direction
        // if relative position is around 0.5 (i.e. the ball hit the paddle in the middle),
        // then the ball goes back from the middle of the paddle
        float relativePos;
        if (hitLeftPaddle) {
            // player 1
            relativePos = (b->box.pos.y - p1->box.pos.y) / (p1->box.height);
        } else {
            // player 2
            relativePos = (b->box.pos.y - p2->box.pos.y) / (p2->box.height);
        }
        // y is negative, so the ball is flying up: reverse relative position
        if (b->direction.y < 0) {
            relativePos = 1 - relativePos;
        }

        // new x direction, reverse the sign
        b->direction.x *= -1;

        // new y direction, keep the sign
        b->direction.y = (b->direction.y > 0) ? 1 : -1;
        b->direction.y *= -0.5 + 1.5 * relativePos;

        // position ball so that it does not intersect the paddles anymore
        if (hitLeftPaddle) {
            b->box.pos.x = p1->box.pos.x + p1->box.width + 1;
        } else {
            b->box.pos.x = p2->box.pos.x - b->box.width - 1;
        }

        // sound effect
        mmEffect( SFX_PANEL );
        mmEffectEx( &b->sfx_panel );
    }

    // vertical collision
    if (b->box.pos.y <= 0 || b->box.pos.y + b->box.height >= SCREEN_HEIGHT) {
        b->direction.y *= -1;
        mmEffect( SFX_WALL );
        mmEffectEx( &b->sfx_wall );
    }

    // Updating sprite position
    b->sprite->x = (int)(b->sprite_offx + b->box.pos.x);
    b->sprite->y = (int)(b->sprite_offy + b->box.pos.y);
}

void scoring(int player, ball *b, scoreBox *sBox) {
    b->box.pos.x = SCREEN_WIDTH / 2;
    b->box.pos.y = SCREEN_HEIGHT / 2;
    b->direction.x = (b->direction.x > 0) ? -1 : 1;
    b->direction.y = 1;

    countPoint(sBox, player);

    mmEffectEx( &b->sfx_scoring );
    mmEffect( SFX_READY );
}
<commit_msg>konvex -> konkav<commit_after>#include <nds.h>
#include <maxmod9.h>
#include <stdio.h>

#include "ball.h"
#include "geometry.h"
#include "player.h"
#include "stats.h"

// Audio
#include "soundbank.h"
#include "soundbank_bin.h"

// Methods

void initBall(ball *b) {
    b->speed = 1.5;
    b->box.pos.x = 100;
    b->box.pos.y = 30;
    b->box.width = 12;
    b->box.height = 12;
    b->direction.x = 1;
    b->direction.y = 1;

    b->sprite_offx = -2;
    b->sprite_offy = -2;

    // SFX_WALL
    b->sfx_wall.id = SFX_WALL;
    b->sfx_wall.rate = 1024;
    b->sfx_wall.handle = 0;
    b->sfx_wall.volume = 255;
    b->sfx_wall.panning = 128;

    // SFX_PANEL
    b->sfx_panel.id = SFX_PANEL;
    b->sfx_panel.rate = 1024;
    b->sfx_panel.handle = 0;
    b->sfx_panel.volume = 255;
    b->sfx_panel.panning = 128;

    // SFX_READY
    b->sfx_scoring.id = SFX_READY;
    b->sfx_scoring.rate = 1024;
    b->sfx_scoring.handle = 0;
    b->sfx_scoring.volume = 255;
    b->sfx_scoring.panning = 128;
}

/**
 * @param ball b
 * @return void
 */
void moveBall(ball *b, player *p1, player *p2, scoreBox *sBox) {
    b->box.pos.x += b->direction.x * b->speed;
    b->box.pos.y += b->direction.y * b->speed;

    bool hitLeftPaddle = intersect(b->box, p1->box);
    bool hitRightPaddle = intersect(b->box, p2->box);

    // horizontal collision
    if (b->box.pos.x <= 0) {
       scoring(1, b, sBox);
    } else if (b->box.pos.x + b->box.width >= SCREEN_WIDTH) {
       scoring(0, b, sBox);
    } else if (hitLeftPaddle || hitRightPaddle) {
        // calculate relative position to player box, then set direction according to that relative position
        // if relative position is low (i.e. closer to 0, the ball hit the paddle early),
        // then the ball goes back in the direction it came from
        // if relative position is high (i.e. closer to 1, the ball hit the paddle late),
        // then the ball bounces off the paddle, going off in the other direction
        // if relative position is around 0.5 (i.e. the ball hit the paddle in the middle),
        // then the ball goes back from the middle of the paddle
        float relativePos;
        if (hitLeftPaddle) {
            // player 1
            relativePos = (b->box.pos.y - p1->box.pos.y) / (p1->box.height);
        } else {
            // player 2
            relativePos = (b->box.pos.y - p2->box.pos.y) / (p2->box.height);
        }
        // y is negative, so the ball is flying up: reverse relative position
        if (b->direction.y < 0) {
            relativePos = 1 - relativePos;
        }

        // new x direction, reverse the sign
        b->direction.x *= -1;

        // new y direction, keep the sign
        b->direction.y = (b->direction.y > 0) ? 1 : -1;
        b->direction.y *= 0.5 - 1.5 * relativePos;

        // position ball so that it does not intersect the paddles anymore
        if (hitLeftPaddle) {
            b->box.pos.x = p1->box.pos.x + p1->box.width + 1;
        } else {
            b->box.pos.x = p2->box.pos.x - b->box.width - 1;
        }

        // sound effect
        mmEffect( SFX_PANEL );
        mmEffectEx( &b->sfx_panel );
    }

    // vertical collision
    if (b->box.pos.y <= 0 || b->box.pos.y + b->box.height >= SCREEN_HEIGHT) {
        b->direction.y *= -1;
        mmEffect( SFX_WALL );
        mmEffectEx( &b->sfx_wall );
    }

    // Updating sprite position
    b->sprite->x = (int)(b->sprite_offx + b->box.pos.x);
    b->sprite->y = (int)(b->sprite_offy + b->box.pos.y);
}

void scoring(int player, ball *b, scoreBox *sBox) {
    b->box.pos.x = SCREEN_WIDTH / 2;
    b->box.pos.y = SCREEN_HEIGHT / 2;
    b->direction.x = (b->direction.x > 0) ? -1 : 1;
    b->direction.y = 1;

    countPoint(sBox, player);

    mmEffectEx( &b->sfx_scoring );
    mmEffect( SFX_READY );
}
<|endoftext|>


<commit_before>#include <ctrcommon/common.hpp>

#include <sstream>
#include <iomanip>
#include <stdio.h>
#include <sys/errno.h>

typedef enum {
    INSTALL,
    DELETE
} Mode;

int main(int argc, char **argv) {
    if(!platform_init()) {
        return 0;
    }

    std::vector<std::string> extensions;
    extensions.push_back("cia");

    MediaType destination = SD;
    Mode mode = INSTALL;
    bool netInstall = false;
    u64 freeSpace = fs_get_free_space(destination);
    auto onLoop = [&]() {
        bool breakLoop = false;
        if(input_is_pressed(BUTTON_L)) {
            if(destination == SD) {
                destination = NAND;
            } else {
                destination = SD;
            }

            freeSpace = fs_get_free_space(destination);
            if(mode == DELETE) {
                breakLoop = true;
            }
        }

        if(input_is_pressed(BUTTON_R)) {
            if(mode == INSTALL) {
                mode = DELETE;
            } else {
                mode = INSTALL;
            }

            breakLoop = true;
        }

        if(input_is_pressed(BUTTON_Y)) {
            netInstall = true;
            breakLoop = true;
        }

        std::stringstream stream;
        stream << "Free Space: " << freeSpace << " bytes (" << std::fixed << std::setprecision(2) << freeSpace / 1024.0f / 1024.0f << "MB)" << "\n";
        stream << "Destination: " << (destination == NAND ? "NAND" : "SD") << ", Mode: " << (mode == INSTALL ? "Install" : "Delete") << "\n";
        stream << "L - Switch Destination, R - Switch Mode" << "\n";
        stream << "Y - Receive an app over the network" << "\n";

        std::string str = stream.str();
        screen_draw_string(str, (screen_get_width() - screen_get_str_width(str)) / 2, screen_get_height() - 4 - screen_get_str_height(str), 255, 255, 255);

        return breakLoop;
    };

    auto onProgress = [&](int progress) {
        ui_display_progress(TOP_SCREEN, "Installing", "Press B to cancel.", true, progress);
        input_poll();
        return !input_is_pressed(BUTTON_B);
    };

    while(platform_is_running()) {
        std::string targetInstall;
        App targetDelete;
        bool obtained = false;
        if(mode == INSTALL) {
            obtained = ui_select_file(&targetInstall, "sdmc:", extensions, [&](bool inRoot) {
                return onLoop();
            });
        } else if(mode == DELETE) {
            obtained = ui_select_app(&targetDelete, destination, onLoop);
        }

        if(netInstall) {
            netInstall = false;

            screen_clear_buffers(BOTTOM_SCREEN, 0, 0, 0);

            RemoteFile file = ui_accept_remote_file(TOP_SCREEN);
            if(file.fd == NULL) {
                continue;
            }

            std::stringstream confirmStream;
            confirmStream << "Install the received application?" << "\n";
            confirmStream << "Size: " << file.fileSize << " bytes (" << std::fixed << std::setprecision(2) << file.fileSize / 1024.0f / 1024.0f << "MB)" << "\n";
            if(ui_prompt(TOP_SCREEN, confirmStream.str(), true)) {
                AppResult ret = app_install(destination, file.fd, file.fileSize, onProgress);
                std::stringstream resultMsg;
                if(mode == INSTALL) {
                    resultMsg << "Install ";
                } else if(mode == DELETE) {
                    resultMsg << "Delete ";
                }

                if(ret == APP_SUCCESS) {
                    resultMsg << "succeeded!";
                } else {
                    resultMsg << "failed!" << "\n";
                    resultMsg << app_get_result_string(ret);
                }

                ui_prompt(TOP_SCREEN, resultMsg.str(), false);
            }

            fclose(file.fd);
            continue;
        }

        if(obtained) {
            std::stringstream prompt;
            if(mode == INSTALL) {
                prompt << "Install ";
            } else if(mode == DELETE) {
                prompt << "Delete ";
            }

            prompt << "the selected title?";
            if(ui_prompt(TOP_SCREEN, prompt.str(), true)) {
                AppResult ret = APP_SUCCESS;
                if(mode == INSTALL) {
                    ret = app_install_file(destination, targetInstall, onProgress);
                } else if(mode == DELETE) {
                    ui_display_message(TOP_SCREEN, "Deleting title...");
                    ret = app_delete(targetDelete);
                }

                std::stringstream resultMsg;
                if(mode == INSTALL) {
                    resultMsg << "Install ";
                } else if(mode == DELETE) {
                    resultMsg << "Delete ";
                }

                if(ret == APP_SUCCESS) {
                    resultMsg << "succeeded!";
                } else {
                    resultMsg << "failed!" << "\n";
                    resultMsg << app_get_result_string(ret);
                }

                ui_prompt(TOP_SCREEN, resultMsg.str(), false);

                freeSpace = fs_get_free_space(destination);
            }
        }
    }

    platform_cleanup();
    return 0;
}
<commit_msg>Add space to error messages.<commit_after>#include <ctrcommon/common.hpp>

#include <sstream>
#include <iomanip>
#include <stdio.h>

typedef enum {
    INSTALL,
    DELETE
} Mode;

int main(int argc, char **argv) {
    if(!platform_init()) {
        return 0;
    }

    std::vector<std::string> extensions;
    extensions.push_back("cia");

    MediaType destination = SD;
    Mode mode = INSTALL;
    bool netInstall = false;
    u64 freeSpace = fs_get_free_space(destination);
    auto onLoop = [&]() {
        bool breakLoop = false;
        if(input_is_pressed(BUTTON_L)) {
            if(destination == SD) {
                destination = NAND;
            } else {
                destination = SD;
            }

            freeSpace = fs_get_free_space(destination);
            if(mode == DELETE) {
                breakLoop = true;
            }
        }

        if(input_is_pressed(BUTTON_R)) {
            if(mode == INSTALL) {
                mode = DELETE;
            } else {
                mode = INSTALL;
            }

            breakLoop = true;
        }

        if(input_is_pressed(BUTTON_Y)) {
            netInstall = true;
            breakLoop = true;
        }

        std::stringstream stream;
        stream << "Free Space: " << freeSpace << " bytes (" << std::fixed << std::setprecision(2) << freeSpace / 1024.0f / 1024.0f << "MB)" << "\n";
        stream << "Destination: " << (destination == NAND ? "NAND" : "SD") << ", Mode: " << (mode == INSTALL ? "Install" : "Delete") << "\n";
        stream << "L - Switch Destination, R - Switch Mode" << "\n";
        stream << "Y - Receive an app over the network" << "\n";

        std::string str = stream.str();
        screen_draw_string(str, (screen_get_width() - screen_get_str_width(str)) / 2, screen_get_height() - 4 - screen_get_str_height(str), 255, 255, 255);

        return breakLoop;
    };

    auto onProgress = [&](int progress) {
        ui_display_progress(TOP_SCREEN, "Installing", "Press B to cancel.", true, progress);
        input_poll();
        return !input_is_pressed(BUTTON_B);
    };

    while(platform_is_running()) {
        std::string targetInstall;
        App targetDelete;
        bool obtained = false;
        if(mode == INSTALL) {
            obtained = ui_select_file(&targetInstall, "sdmc:", extensions, [&](bool inRoot) {
                return onLoop();
            });
        } else if(mode == DELETE) {
            obtained = ui_select_app(&targetDelete, destination, onLoop);
        }

        if(netInstall) {
            netInstall = false;

            screen_clear_buffers(BOTTOM_SCREEN, 0, 0, 0);

            RemoteFile file = ui_accept_remote_file(TOP_SCREEN);
            if(file.fd == NULL) {
                continue;
            }

            std::stringstream confirmStream;
            confirmStream << "Install the received application?" << "\n";
            confirmStream << "Size: " << file.fileSize << " bytes (" << std::fixed << std::setprecision(2) << file.fileSize / 1024.0f / 1024.0f << "MB)" << "\n";
            if(ui_prompt(TOP_SCREEN, confirmStream.str(), true)) {
                AppResult ret = app_install(destination, file.fd, file.fileSize, onProgress);
                std::stringstream resultMsg;
                if(mode == INSTALL) {
                    resultMsg << "Install ";
                } else if(mode == DELETE) {
                    resultMsg << "Delete ";
                }

                if(ret == APP_SUCCESS) {
                    resultMsg << "succeeded!";
                } else {
                    resultMsg << "failed!" << "\n";
                    resultMsg << app_get_result_string(ret) << "\n";
                }

                ui_prompt(TOP_SCREEN, resultMsg.str(), false);
            }

            fclose(file.fd);
            continue;
        }

        if(obtained) {
            std::stringstream prompt;
            if(mode == INSTALL) {
                prompt << "Install ";
            } else if(mode == DELETE) {
                prompt << "Delete ";
            }

            prompt << "the selected title?";
            if(ui_prompt(TOP_SCREEN, prompt.str(), true)) {
                AppResult ret = APP_SUCCESS;
                if(mode == INSTALL) {
                    ret = app_install_file(destination, targetInstall, onProgress);
                } else if(mode == DELETE) {
                    ui_display_message(TOP_SCREEN, "Deleting title...");
                    ret = app_delete(targetDelete);
                }

                std::stringstream resultMsg;
                if(mode == INSTALL) {
                    resultMsg << "Install ";
                } else if(mode == DELETE) {
                    resultMsg << "Delete ";
                }

                if(ret == APP_SUCCESS) {
                    resultMsg << "succeeded!";
                } else {
                    resultMsg << "failed!" << "\n";
                    resultMsg << app_get_result_string(ret) << "\n";
                }

                ui_prompt(TOP_SCREEN, resultMsg.str(), false);

                freeSpace = fs_get_free_space(destination);
            }
        }
    }

    platform_cleanup();
    return 0;
}
<|endoftext|>


<commit_before>// The MIT License (MIT)

// Copyright (c) 2015 Skorezore

//  Permission is hereby granted, free of charge, to any person obtaining a
//  copy of this software and associated documentation files (the "Software"),
//  to deal in the Software without restriction, including without limitation
//  the rights to use, copy, modify, merge, publish, distribute, sublicense,
//  and/or sell copies of the Software, and to permit persons to whom the
//  Software is furnished to do so, subject to the following conditions:
//
//  The above copyright notice and this permission notice shall be included in
//  all copies or substantial portions of the Software.
//
//  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
//  OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
//  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
//  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
//  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
//  FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
//  DEALINGS IN THE SOFTWARE.

#include "frame_buffer.hpp"
#include "game_screen.hpp"
#include "curses.hpp"
#include "entity.hpp"
#include <experimental/string_view>
#include <functional>
#include <sstream>
#include <chrono>
#include <vector>
#include <string>
#include <thread>
#include <cassert>

using namespace std;
using namespace std::chrono;
using namespace std::experimental;

void draw_frame() {
	addstr(frame_buffer().str().c_str());
	refresh();
}

void reset_buffer() {
	move(0, 0);
	frame_buffer().str("");
}

void clear_screen() {
	clear();
	refresh();
	reset_buffer();
}

namespace {
    coords key_movement(coords pos, char key) {
        switch(key) {
            case 'w': case 'W': return { pos.x, pos.y -= 2 };
            case 'a': case 'A': return { pos.x -= 1, pos.y };
            case 's': case 'S': return { pos.x, pos.y += 1 };
            case 'd': case 'D': return { pos.x += 1, pos.y };
        }
    }

    bool is_free(game_screen& screen, coords pos) {
        return screen[pos] == game_screen::filler;
    }

    /*
     * Always returns a vector with at least 1 element (the starting position)
     */
    vector<coords> get_path(coords const& from, coords const& to) {
        bool const is_horizontal = from.y == to.y;
        bool const is_vertical   = from.x == to.x;

        assert(is_horizontal || is_vertical);

        auto step = [](int v) { return v/abs(v); };

        coords const delta = is_horizontal
            ? coords { 0, step(to.y - from.y) }
            : coords { step(to.x - from.x), 0 };

        vector<coords> path { from };
        while (path.back() != to)
            path.push_back(path.back() + delta);
    }
}

bool keyboard_event_loop(game_screen & screen, entity & player) {
	if(kbhit()) {
		char const key = getch();

		if(tolower(key) == 'q')  // Sneaking in that close key
			return true;

		coords destination = key_movement(player.position, key);

        // validate new position
        // validate path is 'free'
        auto path = get_path(player.position, destination);

        for (auto step = next(begin(path)); step!=end(path); ++step)
        {
            if (screen.is_valid(*step) && is_free(screen, *step))
                player.move_to(*step);
            else
                break;
        }
    }
    return false;
}

void gravity(game_screen & screen, entity & entity) {
	if(entity.position.y < screen.size.y && screen[entity.position.below()] == game_screen::filler)
		entity.move_to(entity.position.below());
}

void loop() {
	static const auto time_between_frames = 75ms;

	game_screen screen({16, 16});
	screen.reset();
	screen[{4, 13}]  = '=';
	screen[{5, 13}]  = '=';
	screen[{6, 13}]  = '=';
	screen[{7, 13}]  = '=';
	screen[{8, 13}]  = '=';
	screen[{10, 14}] = '=';
	screen[{11, 14}] = '=';
	// Look at that fancy hardcoded screen ^
	entity player('X');
	bool do_gravity = false;

	curs_set(0);
	noecho();
	while(true) {
		if((do_gravity ^= true) % 2 == 0)
			gravity(screen, player);
		this_thread::sleep_for(time_between_frames);
		reset_buffer();
		for(auto & pos : player.prev_positions)
			screen[pos] = game_screen::filler;
		player.prev_positions.clear();
		screen[player.position] = player.body;
		screen.draw();
		frame_buffer() << "^^^^^^^^^^^^^^^^^^^\n\n"  // Photo-realistic spikes, I know.
		                 "Use WASD for movement\n"
		                 "Press Q to quit\n\n"
		                 "Watch out for the spikes below!\n";
		draw_frame();

		if(keyboard_event_loop(screen, player))
			break;

		if(player.position.y > 14) {
			curs_set(1);
			frame_buffer().str("");
			frame_buffer() << "\nYou fell to your death. Game over!\nPress 'r' to restart (10s): ";
			draw_frame();
			halfdelay(100);
			if(tolower(getch()) == 'r') {
				clear();
				nodelay(stdscr, true);
				loop();
			}
			nodelay(stdscr, true);
			break;
		}
	}
	echo();
	curs_set(1);
}

function<void()> main_menu() {
	static const vector<pair<string_view, function<void()>>> items( { {"Play Gaem", loop}, {"Exit", [&]() {} }});

	size_t idx = 1;
	for(const auto & item : items)
		frame_buffer() << idx++ << ". " << item.first << '\n';
	frame_buffer() << "\nPress the key corresponding to your selection: ";
	draw_frame();

	while(true) {
		int key = getch();
		size_t idx;
		stringstream(string(1, static_cast<char>(key))) >> idx;

		if(isdigit(key) && idx > 0 && items.size() >= idx) {
			clear_screen();
			return items[idx - 1].second;
		}
	}
}

int main() {
	initscr();
	main_menu()();
	endwin();
}
<commit_msg>These were the bugs predicted in the description with https://github.com/Skorezore/Gaem/pull/19<commit_after>// The MIT License (MIT)

// Copyright (c) 2015 Skorezore

//  Permission is hereby granted, free of charge, to any person obtaining a
//  copy of this software and associated documentation files (the "Software"),
//  to deal in the Software without restriction, including without limitation
//  the rights to use, copy, modify, merge, publish, distribute, sublicense,
//  and/or sell copies of the Software, and to permit persons to whom the
//  Software is furnished to do so, subject to the following conditions:
//
//  The above copyright notice and this permission notice shall be included in
//  all copies or substantial portions of the Software.
//
//  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
//  OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
//  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
//  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
//  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
//  FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
//  DEALINGS IN THE SOFTWARE.

#include "frame_buffer.hpp"
#include "game_screen.hpp"
#include "curses.hpp"
#include "entity.hpp"
#include <experimental/string_view>
#include <functional>
#include <sstream>
#include <chrono>
#include <vector>
#include <string>
#include <thread>
#include <cassert>
#include <cmath>

using namespace std;
using namespace std::chrono;
using namespace std::experimental;

void draw_frame() {
	addstr(frame_buffer().str().c_str());
	refresh();
}

void reset_buffer() {
	move(0, 0);
	frame_buffer().str("");
}

void clear_screen() {
	clear();
	refresh();
	reset_buffer();
}

namespace {
    coords key_movement(coords pos, char key) {
        switch(key) {
            case 'w': case 'W': return { pos.x, pos.y -= 2 };
            case 'a': case 'A': return { pos.x -= 1, pos.y };
            case 's': case 'S': return { pos.x, pos.y += 1 };
            case 'd': case 'D': return { pos.x += 1, pos.y };
        }
        return pos;
    }

    bool is_free(game_screen& screen, coords pos) {
        return screen[pos] == game_screen::filler;
    }

    /*
     * Always returns a vector with at least 1 element (the starting position)
     */
    vector<coords> get_path(coords const& from, coords const& to) {
        bool const is_horizontal = from.y == to.y;
        bool const is_vertical   = from.x == to.x;

        assert(is_horizontal || is_vertical);

        auto step = [](int v) -> int { return std::copysign(v/v,v); };

        coords const delta = is_vertical
            ? coords { 0, step(to.y - from.y) }
            : coords { step(to.x - from.x), 0 };

        vector<coords> path { from };
        while (path.back() != to)
            path.push_back(path.back() + delta);

        return path;
    }
}

bool keyboard_event_loop(game_screen & screen, entity & player) {
	if(kbhit()) {
		char const key = getch();

		if(tolower(key) == 'q')  // Sneaking in that close key
			return true;

		coords destination = key_movement(player.position, key);

        // validate new position
        // validate path is 'free'
        auto path = get_path(player.position, destination);

        for (auto step = next(begin(path)); step!=end(path); ++step)
        {
            if (screen.is_valid(*step) && is_free(screen, *step))
                player.move_to(*step);
            else
                break;
        }
    }
    return false;
}

void gravity(game_screen & screen, entity & entity) {
	if(entity.position.y < screen.size.y && screen[entity.position.below()] == game_screen::filler)
		entity.move_to(entity.position.below());
}

void loop() {
	static const auto time_between_frames = 75ms;

	game_screen screen({16, 16});
	screen.reset();
	screen[{4, 13}]  = '=';
	screen[{5, 13}]  = '=';
	screen[{6, 13}]  = '=';
	screen[{7, 13}]  = '=';
	screen[{8, 13}]  = '=';
	screen[{10, 14}] = '=';
	screen[{11, 14}] = '=';
	// Look at that fancy hardcoded screen ^
	entity player('X');
	bool do_gravity = false;

	curs_set(0);
	noecho();
	while(true) {
		if((do_gravity ^= true) % 2 == 0)
			gravity(screen, player);
		this_thread::sleep_for(time_between_frames);
		reset_buffer();
		for(auto & pos : player.prev_positions)
			screen[pos] = game_screen::filler;
		player.prev_positions.clear();
		screen[player.position] = player.body;
		screen.draw();
		frame_buffer() << "^^^^^^^^^^^^^^^^^^^\n\n"  // Photo-realistic spikes, I know.
		                 "Use WASD for movement\n"
		                 "Press Q to quit\n\n"
		                 "Watch out for the spikes below!\n";
		draw_frame();

		if(keyboard_event_loop(screen, player))
			break;

		if(player.position.y > 14) {
			curs_set(1);
			frame_buffer().str("");
			frame_buffer() << "\nYou fell to your death. Game over!\nPress 'r' to restart (10s): ";
			draw_frame();
			halfdelay(100);
			if(tolower(getch()) == 'r') {
				clear();
				nodelay(stdscr, true);
				loop();
			}
			nodelay(stdscr, true);
			break;
		}
	}
	echo();
	curs_set(1);
}

function<void()> main_menu() {
	static const vector<pair<string_view, function<void()>>> items( { {"Play Gaem", loop}, {"Exit", [&]() {} }});

	size_t idx = 1;
	for(const auto & item : items)
		frame_buffer() << idx++ << ". " << item.first << '\n';
	frame_buffer() << "\nPress the key corresponding to your selection: ";
	draw_frame();

	while(true) {
		int key = getch();
		size_t idx;
		stringstream(string(1, static_cast<char>(key))) >> idx;

		if(isdigit(key) && idx > 0 && items.size() >= idx) {
			clear_screen();
			return items[idx - 1].second;
		}
	}
}

int main() {
	initscr();
	main_menu()();
	endwin();
}
<|endoftext|>


<commit_before>#include <ctrcommon/input.hpp>
#include <ctrcommon/platform.hpp>
#include <ctrcommon/ui.hpp>

#include <stdio.h>

#include <sstream>
#include <iomanip>

#include <sys/dirent.h>
#include <3ds.h>

typedef enum {
    INSTALL_CIA,
    DELETE_CIA,
    DELETE_TITLE
} Mode;

int main(int argc, char **argv) {
    if(!platformInit()) {
        return 0;
    }

    bool ninjhax = platformIsNinjhax();
    if(ninjhax) {
        AcquireResult result = platformAcquireServices();
        if(result != ACQUIRE_SUCCESS) {
            std::stringstream errorStream;
            errorStream << "Failed to acquire services." << "\n";
            errorStream << platformGetAcquireResultString(result) << "\n";
            uiPrompt(TOP_SCREEN, errorStream.str(), false);
            platformCleanup();
            return 0;
        }
    }

    std::vector<std::string> extensions;
    extensions.push_back("cia");

    MediaType destination = SD;
    Mode mode = INSTALL_CIA;
    bool exit = false;
    bool netInstall = false;
    u64 freeSpace = fsGetFreeSpace(destination);
    auto onLoop = [&]() {
        if(ninjhax && inputIsPressed(BUTTON_START)) {
            exit = true;
            return true;
        }

        bool breakLoop = false;

        if(inputIsPressed(BUTTON_L)) {
            if(destination == SD) {
                destination = NAND;
            } else {
                destination = SD;
            }

            freeSpace = fsGetFreeSpace(destination);
            if(mode == DELETE_TITLE) {
                breakLoop = true;
            }
        }

        if(inputIsPressed(BUTTON_R)) {
            if(mode == INSTALL_CIA) {
                mode = DELETE_CIA;
            } else if(mode == DELETE_CIA) {
                mode = DELETE_TITLE;
                breakLoop = true;
            } else {
                mode = INSTALL_CIA;
                breakLoop = true;
            }
        }

        if(inputIsPressed(BUTTON_Y)) {
            netInstall = true;
            breakLoop = true;
        }

        std::stringstream stream;
        stream << "Free Space: " << freeSpace << " bytes (" << std::fixed << std::setprecision(2) << freeSpace / 1024.0f / 1024.0f << "MB)" << "\n";
        stream << "Destination: " << (destination == NAND ? "NAND" : "SD") << ", Mode: " << (mode == INSTALL_CIA ? "Install CIA" : mode == DELETE_CIA ? "Delete CIA" : "Delete Title") << "\n";
        stream << "L - Switch Destination, R - Switch Mode" << "\n";
        if(mode == INSTALL_CIA) {
            stream << "X - Install all CIAs in the current directory" << "\n";
        } else if(mode == DELETE_CIA) {
            stream << "X - Delete all CIAs in the current directory" << "\n";
        }

        stream << "Y - Receive an app over the network" << "\n";
        if(ninjhax) {
            stream << "START - Exit to launcher" << "\n";
        }

        std::string str = stream.str();
        screenDrawString(str, (screenGetWidth() - screenGetStrWidth(str)) / 2, screenGetHeight() - 4 - screenGetStrHeight(str), 255, 255, 255);

        return breakLoop;
    };

    auto onProgress = [&](int progress) {
        uiDisplayProgress(TOP_SCREEN, "Installing", "Press B to cancel.", true, progress);
        inputPoll();
        return !inputIsPressed(BUTTON_B);
    };

    while(platformIsRunning()) {
        std::string fileTarget;
        App appTarget;
        if(mode == INSTALL_CIA || mode == DELETE_CIA) {
            uiSelectFile(&fileTarget, "/", extensions, [&](const std::string currDirectory, bool inRoot, bool &updateList) {
                if(inputIsPressed(BUTTON_X)) {
                    std::stringstream confirmMsg;
                    if(mode == INSTALL_CIA) {
                        confirmMsg << "Install ";
                    } else {
                        confirmMsg << "Delete ";
                    }

                    confirmMsg << "all CIAs in the current directory?";
                    if(uiPrompt(TOP_SCREEN, confirmMsg.str(), true)) {
                        bool failed = false;
                        std::vector<FileInfo> contents = fsGetDirectoryContents(currDirectory);
                        for(std::vector<FileInfo>::iterator it = contents.begin(); it != contents.end(); it++) {
                            std::string path = (*it).path;
                            std::string fileName = (*it).name;
                            if(!fsIsDirectory(path) && fsHasExtensions(path, extensions)) {
                                if(mode == INSTALL_CIA) {
                                    AppResult ret = appInstallFile(destination, path, onProgress);
                                    if(ret != APP_SUCCESS) {
                                        std::stringstream resultMsg;
                                        resultMsg << "Install failed!" << "\n";
                                        resultMsg << fileName << "\n";
                                        resultMsg << appGetResultString(ret) << "\n";
                                        uiPrompt(TOP_SCREEN, resultMsg.str(), false);
                                        failed = true;
                                        break;
                                    }
                                } else {
                                    if(!fsDelete(path)) {
                                        std::stringstream resultMsg;
                                        resultMsg << "Delete failed!" << "\n";
                                        resultMsg << fileName << "\n";
                                        resultMsg << platformGetErrorString(platformGetError()) << "\n";
                                        uiPrompt(TOP_SCREEN, resultMsg.str(), false);
                                        failed = true;
                                        break;
                                    } else {
                                        updateList = true;
                                    }
                                }
                            }
                        }

                        if(!failed) {
                            uiPrompt(TOP_SCREEN, "Install succeeded!\n", false);
                        }

                        freeSpace = fsGetFreeSpace(destination);
                    }
                }

                return onLoop();
            }, [&](const std::string path, bool &updateList) {
                std::stringstream confirmMsg;
                if(mode == INSTALL_CIA) {
                    confirmMsg << "Install ";
                } else {
                    confirmMsg << "Delete ";
                }

                confirmMsg << "the selected CIA?";
                if(uiPrompt(TOP_SCREEN, confirmMsg.str(), true)) {
                    std::stringstream resultMsg;
                    if(mode == INSTALL_CIA) {
                        resultMsg << "Install ";
                    } else {
                        resultMsg << "Delete ";
                    }

                    if(mode == INSTALL_CIA) {
                        AppResult ret = appInstallFile(destination, path, onProgress);
                        if(ret == APP_SUCCESS) {
                            resultMsg << "succeeded!";
                        } else {
                            resultMsg << "failed!" << "\n";
                            resultMsg << appGetResultString(ret) << "\n";
                        }
                    } else {
                        if(fsDelete(path)) {
                            updateList = true;
                            resultMsg << "succeeded!";
                        } else {
                            resultMsg << "failed!" << "\n";
                            resultMsg << platformGetErrorString(platformGetError()) << "\n";
                        }
                    }

                    uiPrompt(TOP_SCREEN, resultMsg.str(), false);

                    freeSpace = fsGetFreeSpace(destination);
                }

                return false;
            });
        } else if(mode == DELETE_TITLE) {
            uiSelectApp(&appTarget, destination, [&](bool &updateList) {
                return onLoop();
            }, [&](App app, bool &updateList) {
                if(uiPrompt(TOP_SCREEN, "Delete the selected title?", true)) {
                    updateList = true;
                    uiDisplayMessage(TOP_SCREEN, "Deleting title...");
                    AppResult ret = appDelete(app);

                    std::stringstream resultMsg;
                    resultMsg << "Delete ";
                    if(ret == APP_SUCCESS) {
                        resultMsg << "succeeded!";
                    } else {
                        resultMsg << "failed!" << "\n";
                        resultMsg << appGetResultString(ret) << "\n";
                    }

                    uiPrompt(TOP_SCREEN, resultMsg.str(), false);

                    freeSpace = fsGetFreeSpace(destination);
                }

                return false;
            });
        }

        if(netInstall && !exit) {
            netInstall = false;

            screenClearBuffers(BOTTOM_SCREEN, 0, 0, 0);

            RemoteFile file = uiAcceptRemoteFile(TOP_SCREEN);
            if(file.fd == NULL) {
                continue;
            }

            std::stringstream confirmStream;
            confirmStream << "Install the received application?" << "\n";
            confirmStream << "Size: " << file.fileSize << " bytes (" << std::fixed << std::setprecision(2) << file.fileSize / 1024.0f / 1024.0f << "MB)" << "\n";
            if(uiPrompt(TOP_SCREEN, confirmStream.str(), true)) {
                AppResult ret = appInstall(destination, file.fd, file.fileSize, onProgress);
                std::stringstream resultMsg;
                resultMsg << "Install ";
                if(ret == APP_SUCCESS) {
                    resultMsg << "succeeded!";
                } else {
                    resultMsg << "failed!" << "\n";
                    resultMsg << appGetResultString(ret) << "\n";
                }

                uiPrompt(TOP_SCREEN, resultMsg.str(), false);
            }

            fclose(file.fd);
            continue;
        }

        if(exit) {
            break;
        }
    }

    platformCleanup();
    return 0;
}
<commit_msg>Improve progress display.<commit_after>#include <ctrcommon/input.hpp>
#include <ctrcommon/platform.hpp>
#include <ctrcommon/ui.hpp>

#include <stdio.h>

#include <sstream>
#include <iomanip>

#include <sys/dirent.h>
#include <3ds.h>
#include <ctrcommon/app.hpp>

typedef enum {
    INSTALL_CIA,
    DELETE_CIA,
    DELETE_TITLE
} Mode;

int main(int argc, char **argv) {
    if(!platformInit()) {
        return 0;
    }

    bool ninjhax = platformIsNinjhax();
    if(ninjhax) {
        AcquireResult result = platformAcquireServices();
        if(result != ACQUIRE_SUCCESS) {
            std::stringstream errorStream;
            errorStream << "Failed to acquire services." << "\n";
            errorStream << platformGetAcquireResultString(result) << "\n";
            uiPrompt(TOP_SCREEN, errorStream.str(), false);
            platformCleanup();
            return 0;
        }
    }

    std::vector<std::string> extensions;
    extensions.push_back("cia");

    MediaType destination = SD;
    Mode mode = INSTALL_CIA;
    bool exit = false;
    bool netInstall = false;
    u64 freeSpace = fsGetFreeSpace(destination);
    auto onLoop = [&]() {
        if(ninjhax && inputIsPressed(BUTTON_START)) {
            exit = true;
            return true;
        }

        bool breakLoop = false;

        if(inputIsPressed(BUTTON_L)) {
            if(destination == SD) {
                destination = NAND;
            } else {
                destination = SD;
            }

            freeSpace = fsGetFreeSpace(destination);
            if(mode == DELETE_TITLE) {
                breakLoop = true;
            }
        }

        if(inputIsPressed(BUTTON_R)) {
            if(mode == INSTALL_CIA) {
                mode = DELETE_CIA;
            } else if(mode == DELETE_CIA) {
                mode = DELETE_TITLE;
                breakLoop = true;
            } else {
                mode = INSTALL_CIA;
                breakLoop = true;
            }
        }

        if(inputIsPressed(BUTTON_Y)) {
            netInstall = true;
            breakLoop = true;
        }

        std::stringstream stream;
        stream << "Free Space: " << freeSpace << " bytes (" << std::fixed << std::setprecision(2) << freeSpace / 1024.0f / 1024.0f << "MB)" << "\n";
        stream << "Destination: " << (destination == NAND ? "NAND" : "SD") << ", Mode: " << (mode == INSTALL_CIA ? "Install CIA" : mode == DELETE_CIA ? "Delete CIA" : "Delete Title") << "\n";
        stream << "L - Switch Destination, R - Switch Mode" << "\n";
        if(mode == INSTALL_CIA) {
            stream << "X - Install all CIAs in the current directory" << "\n";
        } else if(mode == DELETE_CIA) {
            stream << "X - Delete all CIAs in the current directory" << "\n";
        }

        stream << "Y - Receive an app over the network" << "\n";
        if(ninjhax) {
            stream << "START - Exit to launcher" << "\n";
        }

        std::string str = stream.str();
        screenDrawString(str, (screenGetWidth() - screenGetStrWidth(str)) / 2, screenGetHeight() - 4 - screenGetStrHeight(str), 255, 255, 255);

        return breakLoop;
    };

    auto onProgress = [&](u64 pos, u64 totalSize) {
        std::stringstream details;
        details << "(" << std::fixed << std::setprecision(2) << ((double) pos / 1024.0 / 1024.0) << "MB / " << std::fixed << std::setprecision(2) << ((double) totalSize / 1024.0 / 1024.0) << "MB)" << "\n";
        details << "Press B to cancel.";

        u32 progress = (u32) (((double) pos / (double) totalSize) * 100);
        uiDisplayProgress(TOP_SCREEN, "Installing", details.str(), true, progress);
        inputPoll();
        return !inputIsPressed(BUTTON_B);
    };

    while(platformIsRunning()) {
        std::string fileTarget;
        App appTarget;
        if(mode == INSTALL_CIA || mode == DELETE_CIA) {
            uiSelectFile(&fileTarget, "/", extensions, [&](const std::string currDirectory, bool inRoot, bool &updateList) {
                if(inputIsPressed(BUTTON_X)) {
                    std::stringstream confirmMsg;
                    if(mode == INSTALL_CIA) {
                        confirmMsg << "Install ";
                    } else {
                        confirmMsg << "Delete ";
                    }

                    confirmMsg << "all CIAs in the current directory?";
                    if(uiPrompt(TOP_SCREEN, confirmMsg.str(), true)) {
                        bool failed = false;
                        std::vector<FileInfo> contents = fsGetDirectoryContents(currDirectory);
                        for(std::vector<FileInfo>::iterator it = contents.begin(); it != contents.end(); it++) {
                            std::string path = (*it).path;
                            std::string fileName = (*it).name;
                            if(!fsIsDirectory(path) && fsHasExtensions(path, extensions)) {
                                if(mode == INSTALL_CIA) {
                                    AppResult ret = appInstallFile(destination, path, onProgress);
                                    if(ret != APP_SUCCESS) {
                                        std::stringstream resultMsg;
                                        resultMsg << "Install failed!" << "\n";
                                        resultMsg << fileName << "\n";
                                        resultMsg << appGetResultString(ret) << "\n";
                                        uiPrompt(TOP_SCREEN, resultMsg.str(), false);
                                        failed = true;
                                        break;
                                    }
                                } else {
                                    if(!fsDelete(path)) {
                                        std::stringstream resultMsg;
                                        resultMsg << "Delete failed!" << "\n";
                                        resultMsg << fileName << "\n";
                                        resultMsg << platformGetErrorString(platformGetError()) << "\n";
                                        uiPrompt(TOP_SCREEN, resultMsg.str(), false);
                                        failed = true;
                                        break;
                                    } else {
                                        updateList = true;
                                    }
                                }
                            }
                        }

                        if(!failed) {
                            uiPrompt(TOP_SCREEN, "Install succeeded!\n", false);
                        }

                        freeSpace = fsGetFreeSpace(destination);
                    }
                }

                return onLoop();
            }, [&](const std::string path, bool &updateList) {
                std::stringstream confirmMsg;
                if(mode == INSTALL_CIA) {
                    confirmMsg << "Install ";
                } else {
                    confirmMsg << "Delete ";
                }

                confirmMsg << "the selected CIA?";
                if(uiPrompt(TOP_SCREEN, confirmMsg.str(), true)) {
                    std::stringstream resultMsg;
                    if(mode == INSTALL_CIA) {
                        resultMsg << "Install ";
                    } else {
                        resultMsg << "Delete ";
                    }

                    if(mode == INSTALL_CIA) {
                        AppResult ret = appInstallFile(destination, path, onProgress);
                        if(ret == APP_SUCCESS) {
                            resultMsg << "succeeded!";
                        } else {
                            resultMsg << "failed!" << "\n";
                            resultMsg << appGetResultString(ret) << "\n";
                        }
                    } else {
                        if(fsDelete(path)) {
                            updateList = true;
                            resultMsg << "succeeded!";
                        } else {
                            resultMsg << "failed!" << "\n";
                            resultMsg << platformGetErrorString(platformGetError()) << "\n";
                        }
                    }

                    uiPrompt(TOP_SCREEN, resultMsg.str(), false);

                    freeSpace = fsGetFreeSpace(destination);
                }

                return false;
            });
        } else if(mode == DELETE_TITLE) {
            uiSelectApp(&appTarget, destination, [&](bool &updateList) {
                return onLoop();
            }, [&](App app, bool &updateList) {
                if(uiPrompt(TOP_SCREEN, "Delete the selected title?", true)) {
                    updateList = true;
                    uiDisplayMessage(TOP_SCREEN, "Deleting title...");
                    AppResult ret = appDelete(app);

                    std::stringstream resultMsg;
                    resultMsg << "Delete ";
                    if(ret == APP_SUCCESS) {
                        resultMsg << "succeeded!";
                    } else {
                        resultMsg << "failed!" << "\n";
                        resultMsg << appGetResultString(ret) << "\n";
                    }

                    uiPrompt(TOP_SCREEN, resultMsg.str(), false);

                    freeSpace = fsGetFreeSpace(destination);
                }

                return false;
            });
        }

        if(netInstall && !exit) {
            netInstall = false;

            screenClearBuffers(BOTTOM_SCREEN, 0, 0, 0);

            RemoteFile file = uiAcceptRemoteFile(TOP_SCREEN);
            if(file.fd == NULL) {
                continue;
            }

            std::stringstream confirmStream;
            confirmStream << "Install the received application?" << "\n";
            confirmStream << "Size: " << file.fileSize << " bytes (" << std::fixed << std::setprecision(2) << file.fileSize / 1024.0f / 1024.0f << "MB)" << "\n";
            if(uiPrompt(TOP_SCREEN, confirmStream.str(), true)) {
                AppResult ret = appInstall(destination, file.fd, file.fileSize, onProgress);
                std::stringstream resultMsg;
                resultMsg << "Install ";
                if(ret == APP_SUCCESS) {
                    resultMsg << "succeeded!";
                } else {
                    resultMsg << "failed!" << "\n";
                    resultMsg << appGetResultString(ret) << "\n";
                }

                uiPrompt(TOP_SCREEN, resultMsg.str(), false);
            }

            fclose(file.fd);
            continue;
        }

        if(exit) {
            break;
        }
    }

    platformCleanup();
    return 0;
}
<|endoftext|>


<commit_before>#include <iostream>

#include "cost.hpp"
#include "timing.hpp"
#include "layer.hpp"
#include "activations.hpp"

int main()
{
	{
		using namespace nn;
		using InputLayer = layer<LayerType::kEigenInput, ActivationType::kSigmoid, 256>;
		using FirstLayer = layer<LayerType::kEigenRegular, ActivationType::kSigmoid, 30, 256>;
		using SecondLayer = layer<LayerType::kEigenRegular, ActivationType::kSigmoid, 10, 30>;
		using InputType = InputLayer::MatrixType;

		timing timer;
		FirstLayer l1;
		SecondLayer l2;
		InputType in = InputType::Random(FirstLayer::UnitsInPreviousLayer, 1);
		l1.computeWeightedSum(InputLayer::computeActivations(in));
		l1.computeActivations();
		l2.computeWeightedSum(l1.getOutput());
		l2.computeActivations();
		timer.printDuration();
	}

	int x;
	std::cin >> x;
	return 0;
}<commit_msg>main: initialize input vector correctly<commit_after>#include <iostream>

#include "cost.hpp"
#include "timing.hpp"
#include "layer.hpp"
#include "activations.hpp"

int main()
{
	{
		using namespace nn;
		using InputLayer = layer<LayerType::kEigenInput, ActivationType::kSigmoid, 256>;
		using FirstLayer = layer<LayerType::kEigenRegular, ActivationType::kSigmoid, 30, 256>;
		using SecondLayer = layer<LayerType::kEigenRegular, ActivationType::kSigmoid, 10, 30>;
		using InputType = InputLayer::MatrixType;

		timing timer;
		FirstLayer l1;
		SecondLayer l2;
		InputType in = InputType::Random(InputLayer::UnitsInLayer, 1);
		l1.computeWeightedSum(InputLayer::computeActivations(in));
		l1.computeActivations();
		l2.computeWeightedSum(l1.getOutput());
		l2.computeActivations();
		timer.printDuration();
	}

	int x;
	std::cin >> x;
	return 0;
}<|endoftext|>


<commit_before>///
/// @file  help.cpp
///
/// Copyright (C) 2015 Kim Walisch, <kim.walisch@gmail.com>
///
/// This file is distributed under the BSD License. See the COPYING
/// file in the top level directory.
///

#include <primecount.hpp>

#include <iostream>
#include <cstdlib>
#include <string>

using namespace std;

namespace {

const string helpMenu(
  "Usage: primecount x [OPTION]...\n"
  "Count the primes below x <= 10^27 using the prime counting function,\n"
  "by default the Deleglise-Rivat algorithm (-d) is used.\n"
  "\n"
  "Options:\n"
  "\n"
  "  -d,    --deleglise_rivat  Count primes using Deleglise-Rivat algorithm\n"
  "         --legendre         Count primes using Legendre's formula\n"
  "         --lehmer           Count primes using Lehmer's formula\n"
  "  -l,    --lmo              Count primes using Lagarias-Miller-Odlyzko\n"
  "  -m,    --meissel          Count primes using Meissel's formula\n"
  "         --Li               Approximate pi(x) using the logarithmic integral\n"
  "         --Li_inverse       Approximate the nth prime using Li^-1(x)\n"
  "  -n,    --nthprime         Calculate the nth prime\n"
  "  -p,    --primesieve       Count primes using the sieve of Eratosthenes\n"
  "  -s,    --status           Print status info during computation\n"
  "         --test             Run various correctness tests and exit\n"
  "         --time             Print the time elapsed in seconds\n"
  "  -t<N>, --threads=<N>      Set the number of threads, 1 <= N <= CPU cores\n"
  "  -v,    --version          Print version and license information\n"
  "  -h,    --help             Print this help menu\n"
  "\n"
  "Advanced Deleglise-Rivat options:\n"
  "\n"
  "  -a<N>, --alpha=<N>        Tuning factor, 1 <= alpha <= x^(1/6)\n"
  "         --p2               Only compute the 2nd partial sieve function\n"
  "         --s1               Only compute the ordinary leaves\n"
  "         --s2_trivial       Only compute the trivial special leaves\n"
  "         --s2_easy          Only compute the easy special leaves\n"
  "         --s2_hard          Only compute the hard special leaves\n"
  "\n"
  "Examples:\n"
  "\n"
  "  primecount 10**13\n"
  "  primecount 10**13 --nthprime --threads=4"
);

const string versionInfo(
  "primecount " PRIMECOUNT_VERSION ", <https://github.com/kimwalisch/primecount>\n"
  "Copyright (C) 2015 Kim Walisch\n"
  "BSD 2-Clause License <http://opensource.org/licenses/BSD-2-Clause>"
);

} // end namespace

namespace primecount {

void help()
{
  cout << helpMenu << endl;
  exit(1);
}

void version()
{
  cout << versionInfo << endl;
  exit(1);
}

} // namespace primecount
<commit_msg>Update help.cpp<commit_after>///
/// @file  help.cpp
///
/// Copyright (C) 2015 Kim Walisch, <kim.walisch@gmail.com>
///
/// This file is distributed under the BSD License. See the COPYING
/// file in the top level directory.
///

#include <primecount.hpp>

#include <iostream>
#include <cstdlib>
#include <string>

using namespace std;

namespace {

const string helpMenu(
  "Usage: primecount x [OPTION]...\n"
  "Count the primes below x <= 10^31 using the prime counting function,\n"
  "by default the Deleglise-Rivat algorithm (-d) is used.\n"
  "\n"
  "Options:\n"
  "\n"
  "  -d,    --deleglise_rivat  Count primes using Deleglise-Rivat algorithm\n"
  "         --legendre         Count primes using Legendre's formula\n"
  "         --lehmer           Count primes using Lehmer's formula\n"
  "  -l,    --lmo              Count primes using Lagarias-Miller-Odlyzko\n"
  "  -m,    --meissel          Count primes using Meissel's formula\n"
  "         --Li               Approximate pi(x) using the logarithmic integral\n"
  "         --Li_inverse       Approximate the nth prime using Li^-1(x)\n"
  "  -n,    --nthprime         Calculate the nth prime\n"
  "  -p,    --primesieve       Count primes using the sieve of Eratosthenes\n"
  "  -s,    --status           Print status info during computation\n"
  "         --test             Run various correctness tests and exit\n"
  "         --time             Print the time elapsed in seconds\n"
  "  -t<N>, --threads=<N>      Set the number of threads, 1 <= N <= CPU cores\n"
  "  -v,    --version          Print version and license information\n"
  "  -h,    --help             Print this help menu\n"
  "\n"
  "Advanced Deleglise-Rivat options:\n"
  "\n"
  "  -a<N>, --alpha=<N>        Tuning factor, 1 <= alpha <= x^(1/6)\n"
  "         --p2               Only compute the 2nd partial sieve function\n"
  "         --s1               Only compute the ordinary leaves\n"
  "         --s2_trivial       Only compute the trivial special leaves\n"
  "         --s2_easy          Only compute the easy special leaves\n"
  "         --s2_hard          Only compute the hard special leaves\n"
  "\n"
  "Examples:\n"
  "\n"
  "  primecount 10**13\n"
  "  primecount 10**13 --nthprime --threads=4"
);

const string versionInfo(
  "primecount " PRIMECOUNT_VERSION ", <https://github.com/kimwalisch/primecount>\n"
  "Copyright (C) 2015 Kim Walisch\n"
  "BSD 2-Clause License <http://opensource.org/licenses/BSD-2-Clause>"
);

} // end namespace

namespace primecount {

void help()
{
  cout << helpMenu << endl;
  exit(1);
}

void version()
{
  cout << versionInfo << endl;
  exit(1);
}

} // namespace primecount
<|endoftext|>