<commit_before>#include <vpr/vprConfig.h>

#include <cppunit/TestSuite.h>
#include <cppunit/TextTestRunner.h>
#include <cppunit/extensions/MetricRegistry.h>

// Common (sim and real) tests.
#include <TestCases/Socket/SocketTest.h>
#include <TestCases/Socket/NonBlockingSocketsTest.h>
#include <TestCases/Socket/SocketCopyConstructorTest.h>
#include <TestCases/Socket/SocketConnectorAcceptorTest.h>

#include <TestCases/Thread/ThreadTest.h>

#include <TestCases/IO/Socket/InetAddrTest.h>
#include <TestCases/IO/SelectorTest.h>

#include <TestCases/IO/Stats/SocketBandwidthIOStatsTest.h>

#include <TestCases/Util/ReturnStatusTest.h>
#include <TestCases/Util/IntervalTest.h>
#include <TestCases/Util/GUIDTest.h>

// Simulator tests.
#ifdef VPR_SIMULATOR
#  include <TestCases/Simulator/SimSelectorTest.h>
#  include <TestCases/Simulator/SocketSimulatorTest.h>

// Real tests.
#else
#endif

#include <TestCases/BoostTest.h>
#include <TestCases/SystemTest.h>

#include <vpr/Thread/Thread.h>
#include <vpr/Util/Debug.h>
#include <vpr/System.h>

//#define vprtest_RANDOM_SEED 1

#ifdef VPR_SIMULATOR
static void run (void* arg)
{
   while ( true )
   {
      vpr::sim::Controller::instance()->processNextEvent();
      vpr::Thread::yield();
   }
}
#endif

int main (int ac, char **av)
{
   vprDEBUG(vprDBG_ALL,0) << "\n\n-----------------------------------------\n" << vprDEBUG_FLUSH;
   vprDEBUG(vprDBG_ALL,0) << "Starting test\n" << vprDEBUG_FLUSH;       // Do this here to get init text out of the way

    // Init random number generation
    unsigned int random_seed;

#ifdef vprtest_RANDOM_SEED
    timeval cur_time;
    vpr::System::gettimeofday(&cur_time);
    random_seed = cur_time.tv_usec;
    vprDEBUG(vprDBG_ALL,0) << "timeval.usec: " << cur_time.tv_usec << std::endl << vprDEBUG_FLUSH;
#else
    random_seed = 1;                // Use this for repeatability
#endif

   vprDEBUG(vprDBG_ALL,0) << " Random seed: " << random_seed << std::endl
                          << vprDEBUG_FLUSH;

   srandom(random_seed);
   srand(random_seed);

#ifdef VPR_SIMULATOR       // ------ CONFIGURE SIM NETWORK ------ //
   std::string path_base(GRAPH_PATH);

   vpr::sim::Controller::instance()->constructNetwork(path_base.append("/test/TestSuite/test_network.vsn"));

   vpr::Thread sim_thread(run);
#endif

   // -------- CONFIGURE METRIC REGISTRY ------- //
   CppUnit::MetricRegistry* metric_reg = CppUnit::MetricRegistry::instance();
   std::string metric_prefix;    // Prefix for all metric labels (mode/hostname)

   std::string host_name = vpr::System::getHostname();
   metric_prefix = host_name + "/";
#ifdef _DEBUG
   metric_prefix += "Debug/";
#endif
#ifdef _OPT
   metric_prefix += "Opt/";
#endif
#ifdef VPR_SIMULATOR
   metric_prefix += "Sim/";
#endif

   std::cout << "Setting up metrics for host: " << host_name << std::endl;
   std::cout << "                     prefix: " << metric_prefix << std::endl;

   metric_reg->setPrefix(metric_prefix);
   metric_reg->setFilename("vapor_metrics.txt");
   metric_reg->setMetric("Main/MetricTest", 1221.75f);

   CppUnit::TextTestRunner runner;

   //------------------------------------
   //  noninteractive
   //------------------------------------
   // create non-interactive test suite
   CppUnit::TestSuite* noninteractive_suite = new CppUnit::TestSuite("noninteractive");

   // add tests to the suite
#ifdef VPR_SIMULATOR
   // Simulator tests.
   noninteractive_suite->addTest(vprTest::SocketSimulatorTest::suite());
   noninteractive_suite->addTest(vprTest::SimSelectorTest::suite());
#else
   // Real tests.
#endif

   // Common tests (both real and simulator).
   noninteractive_suite->addTest(vprTest::ReturnStatusTest::suite());
   noninteractive_suite->addTest(vprTest::BoostTest::suite());
   noninteractive_suite->addTest(vprTest::SystemTest::suite());
   noninteractive_suite->addTest(vprTest::IntervalTest::suite());
   noninteractive_suite->addTest(vprTest::GUIDTest::suite());
   noninteractive_suite->addTest(vprTest::InetAddrTest::suite());
   noninteractive_suite->addTest(vprTest::SocketTest::suite());
   noninteractive_suite->addTest(vprTest::NonBlockingSocketTest::suite());
//   noninteractive_suite->addTest(vprTest::SocketCopyConstructorTest::suite());
   noninteractive_suite->addTest(vprTest::SocketConnectorAcceptorTest::suite());
   noninteractive_suite->addTest(vprTest::SelectorTest::suite());

   // Add the test suite to the runner
   runner.addTest( noninteractive_suite );

   // ------------------------------
   // METRICS
   // ------------------------------
   CppUnit::TestSuite* metrics_suite = new CppUnit::TestSuite("metrics");

   metrics_suite->addTest(vprTest::IntervalTest::metric_suite());
   metrics_suite->addTest(vprTest::GUIDTest::metric_suite());
   metrics_suite->addTest(vprTest::SocketBandwidthIOStatsTest::metric_suite());

   runner.addTest(metrics_suite);

   //noninteractive_suite->addTest(metrics_suite);

   // -------------------------------
   // INTERACTIVE
   // -------------------------------
   CppUnit::TestSuite* interactive_suite = new CppUnit::TestSuite("interactive");

   interactive_suite->addTest(vprTest::ThreadTest::suite());

   runner.addTest(interactive_suite);

   // run all test suites
   if ( ac > 1 )
   {
      if ( strcmp(av[1], "interactive") == 0 )
      {
         runner.run("interactive");
      }
      else if ( strcmp(av[1], "noninteractive") == 0 )
      {
         runner.run("noninteractive");
      }
      else if ( strcmp(av[1], "metrics") == 0 )
      {
         runner.run("metrics");
      }
      else if ( strcmp(av[1], "all") == 0 )
      {
         runner.run("noninteractive");
         runner.run("metrics");
         runner.run("interactive");
      }
   }
   else
   {
      runner.run("noninteractive");
      runner.run("metrics");
      runner.run("interactive");
   }

   return 0;
}
<commit_msg>Added a missing header in the simulator case.<commit_after>#include <vpr/vprConfig.h>

#include <cppunit/TestSuite.h>
#include <cppunit/TextTestRunner.h>
#include <cppunit/extensions/MetricRegistry.h>

// Common (sim and real) tests.
#include <TestCases/Socket/SocketTest.h>
#include <TestCases/Socket/NonBlockingSocketsTest.h>
#include <TestCases/Socket/SocketCopyConstructorTest.h>
#include <TestCases/Socket/SocketConnectorAcceptorTest.h>

#include <TestCases/Thread/ThreadTest.h>

#include <TestCases/IO/Socket/InetAddrTest.h>
#include <TestCases/IO/SelectorTest.h>

#include <TestCases/IO/Stats/SocketBandwidthIOStatsTest.h>

#include <TestCases/Util/ReturnStatusTest.h>
#include <TestCases/Util/IntervalTest.h>
#include <TestCases/Util/GUIDTest.h>

// Simulator tests.
#ifdef VPR_SIMULATOR
#  include <vpr/md/SIM/Controller.h>

#  include <TestCases/Simulator/SimSelectorTest.h>
#  include <TestCases/Simulator/SocketSimulatorTest.h>

// Real tests.
#else
#endif

#include <TestCases/BoostTest.h>
#include <TestCases/SystemTest.h>

#include <vpr/Thread/Thread.h>
#include <vpr/Util/Debug.h>
#include <vpr/System.h>

//#define vprtest_RANDOM_SEED 1

#ifdef VPR_SIMULATOR
static void run (void* arg)
{
   while ( true )
   {
      vpr::sim::Controller::instance()->processNextEvent();
      vpr::Thread::yield();
   }
}
#endif

int main (int ac, char **av)
{
   vprDEBUG(vprDBG_ALL,0) << "\n\n-----------------------------------------\n" << vprDEBUG_FLUSH;
   vprDEBUG(vprDBG_ALL,0) << "Starting test\n" << vprDEBUG_FLUSH;       // Do this here to get init text out of the way

    // Init random number generation
    unsigned int random_seed;

#ifdef vprtest_RANDOM_SEED
    timeval cur_time;
    vpr::System::gettimeofday(&cur_time);
    random_seed = cur_time.tv_usec;
    vprDEBUG(vprDBG_ALL,0) << "timeval.usec: " << cur_time.tv_usec << std::endl << vprDEBUG_FLUSH;
#else
    random_seed = 1;                // Use this for repeatability
#endif

   vprDEBUG(vprDBG_ALL,0) << " Random seed: " << random_seed << std::endl
                          << vprDEBUG_FLUSH;

   srandom(random_seed);
   srand(random_seed);

#ifdef VPR_SIMULATOR       // ------ CONFIGURE SIM NETWORK ------ //
   std::string path_base(GRAPH_PATH);

   vpr::sim::Controller::instance()->constructNetwork(path_base.append("/test/TestSuite/test_network.vsn"));

   vpr::Thread sim_thread(run);
#endif

   // -------- CONFIGURE METRIC REGISTRY ------- //
   CppUnit::MetricRegistry* metric_reg = CppUnit::MetricRegistry::instance();
   std::string metric_prefix;    // Prefix for all metric labels (mode/hostname)

   std::string host_name = vpr::System::getHostname();
   metric_prefix = host_name + "/";
#ifdef _DEBUG
   metric_prefix += "Debug/";
#endif
#ifdef _OPT
   metric_prefix += "Opt/";
#endif
#ifdef VPR_SIMULATOR
   metric_prefix += "Sim/";
#endif

   std::cout << "Setting up metrics for host: " << host_name << std::endl;
   std::cout << "                     prefix: " << metric_prefix << std::endl;

   metric_reg->setPrefix(metric_prefix);
   metric_reg->setFilename("vapor_metrics.txt");
   metric_reg->setMetric("Main/MetricTest", 1221.75f);

   CppUnit::TextTestRunner runner;

   //------------------------------------
   //  noninteractive
   //------------------------------------
   // create non-interactive test suite
   CppUnit::TestSuite* noninteractive_suite = new CppUnit::TestSuite("noninteractive");

   // add tests to the suite
#ifdef VPR_SIMULATOR
   // Simulator tests.
   noninteractive_suite->addTest(vprTest::SocketSimulatorTest::suite());
   noninteractive_suite->addTest(vprTest::SimSelectorTest::suite());
#else
   // Real tests.
#endif

   // Common tests (both real and simulator).
   noninteractive_suite->addTest(vprTest::ReturnStatusTest::suite());
   noninteractive_suite->addTest(vprTest::BoostTest::suite());
   noninteractive_suite->addTest(vprTest::SystemTest::suite());
   noninteractive_suite->addTest(vprTest::IntervalTest::suite());
   noninteractive_suite->addTest(vprTest::GUIDTest::suite());
   noninteractive_suite->addTest(vprTest::InetAddrTest::suite());
   noninteractive_suite->addTest(vprTest::SocketTest::suite());
   noninteractive_suite->addTest(vprTest::NonBlockingSocketTest::suite());
//   noninteractive_suite->addTest(vprTest::SocketCopyConstructorTest::suite());
   noninteractive_suite->addTest(vprTest::SocketConnectorAcceptorTest::suite());
   noninteractive_suite->addTest(vprTest::SelectorTest::suite());

   // Add the test suite to the runner
   runner.addTest( noninteractive_suite );

   // ------------------------------
   // METRICS
   // ------------------------------
   CppUnit::TestSuite* metrics_suite = new CppUnit::TestSuite("metrics");

   metrics_suite->addTest(vprTest::IntervalTest::metric_suite());
   metrics_suite->addTest(vprTest::GUIDTest::metric_suite());
   metrics_suite->addTest(vprTest::SocketBandwidthIOStatsTest::metric_suite());

   runner.addTest(metrics_suite);

   //noninteractive_suite->addTest(metrics_suite);

   // -------------------------------
   // INTERACTIVE
   // -------------------------------
   CppUnit::TestSuite* interactive_suite = new CppUnit::TestSuite("interactive");

   interactive_suite->addTest(vprTest::ThreadTest::suite());

   runner.addTest(interactive_suite);

   // run all test suites
   if ( ac > 1 )
   {
      if ( strcmp(av[1], "interactive") == 0 )
      {
         runner.run("interactive");
      }
      else if ( strcmp(av[1], "noninteractive") == 0 )
      {
         runner.run("noninteractive");
      }
      else if ( strcmp(av[1], "metrics") == 0 )
      {
         runner.run("metrics");
      }
      else if ( strcmp(av[1], "all") == 0 )
      {
         runner.run("noninteractive");
         runner.run("metrics");
         runner.run("interactive");
      }
   }
   else
   {
      runner.run("noninteractive");
      runner.run("metrics");
      runner.run("interactive");
   }

   return 0;
}
<|endoftext|>


<commit_before>#include <omp.h>
#include <stdio.h>

#include "main/algorithms/BruteForceSolver.h"
#include "main/algorithms/DynamicProgrammingSolver.h"
#include "main/algorithms/DynamicProgrammingParallelSolver.h"
#include "main/algorithms/DynamicProgrammingLowMemorySolver.h"
#include "main/algorithms/DynamicProgrammingLowMemoryParallelSolver.h"
#include "main/algorithms/NemhauserUllmannSolver.h"
#include "main/algorithms/NemhauserUllmannParallelSolver.h"
#include "main/algorithms/NemhauserUllmannSolverRLP.h"
#include "main/algorithms/NemhauserUllmannRLPParallelSolver.h"
using namespace std;

#define PRINT_VERBOSE

static const char* FIRST_KNAPSACK_INPUT_FILE = "res/firstFileExample.txt";
static const char* SECOND_KNAPSACK_INPUT_FILE = "res/secondFileExample.txt";
static const char* THIRD_KNAPSACK_INPUT_FILE = "res/thirdFileExample.txt";
static const char* FOURTH_KNAPSACK_INPUT_FILE = "res/fourthFileExample.txt";
static const char* FIFTH_KNAPSACK_INPUT_FILE = "res/fifthFileExample.txt";
static const char* SIXTH_KNAPSACK_INPUT_FILE = "res/sixthFileExample.txt";
static const char* SEVENTH_KNAPSACK_INPUT_FILE = "res/seventhFileExample.txt";
static const char* DP_INPUT_FILE = "res/dynamicProgrammingExample.txt";
static const char* SECOND_DP_INPUT_FILE = "res/secondDynamicProgrammingExample.txt";
static const char* KNAPSACK_OUTPUT_FILE = "knapSackOut.txt";

/**
 * Solves the knapsack problem found within the given input file
 * by applying the brute force algorithm n times, where n equals the numOfExecutions parameter.
 */
void executeBruteForceSolver(const char* inputFile, int numOfExecutions=1){
	KnapSackSolver* solver = new BruteForceSolver(inputFile, KNAPSACK_OUTPUT_FILE, numOfExecutions);
	solver->start();
	delete solver;
}

/**
 * Solves the knapsack problem found within the given input file
 * by applying the nemhauser ullman algorithm n times, where n equals the numOfExecutions parameter.
 */
void executeNemhauserUllmanSolver(const char* inputFile, const int numOfExecutions=1) {
	KnapSackSolver* solver = new NemhauserUllmannSolver(inputFile, KNAPSACK_OUTPUT_FILE, numOfExecutions);
	solver->start();
	delete solver;
}

/**
 * Solves the knapsack problem found within the given input file
 * by applying the parallel nemhauser ullman algorithm n times, where n equals the numOfExecutions parameter.
 */
void executeNemhauserUllmanParallelSolver(const char* inputFile, int numOfExecutions=1) {
	KnapSackSolver* solver = new NemhauserUllmannParallelSolver(inputFile, KNAPSACK_OUTPUT_FILE, numOfExecutions);
	solver->start();
	delete solver;
}

/**
 * Solves the knapsack problem found within the given input file
 * by applying the rlp improved version of the nemhauser ullman algorithm n times,
 * where n equals the numOfExecutions parameter.
 */
void executeNemhauserUllmanRLPSolver(const char* inputFile, int numOfExecutions=1) {
	KnapSackSolver* solver = new NemhauserUllmannSolverRLP(inputFile, KNAPSACK_OUTPUT_FILE, numOfExecutions);
	solver->start();
	delete solver;
}

/**
 * Solves the knapsack problem found within the given input file
 * by applying the parallel rlp improved version of the nemhauser ullman algorithm n times,
 * where n equals the numOfExecutions parameter.
 */
void executeNemhauserUllmanRLPParallelSolver(const char* inputFile, int numOfExecutions=1) {
	bool sortInputByWorth = false;
	KnapSackSolver* solver = new NemhauserUllmannRLPParallelSolver(inputFile, KNAPSACK_OUTPUT_FILE, numOfExecutions, sortInputByWorth);
	solver->start();
	delete solver;
}

/**
 * Solves the knapsack problem found within the given input file
 * by applying the dynamic programming algorithm n times,
 * where n equals the numOfExecutions parameter.
 */
void executeDynamicProgrammingSolver(const char* inputFile, int numOfExecutions=1){
	KnapSackSolver* solver = new DynamicProgrammingSolver(inputFile, KNAPSACK_OUTPUT_FILE, numOfExecutions);
	solver->start();
	delete solver;
}

/**
 * Solves the knapsack problem found within the given input file
 * by applying the parallel dynamic programming algorithm n times,
 * where n equals the numOfExecutions parameter.
 */
void executeDynamicProgrammingParallelSolver(const char* inputFile, int numOfExecutions=1){
	KnapSackSolver* solver = new DynamicProgrammingParallelSolver(inputFile, KNAPSACK_OUTPUT_FILE, numOfExecutions);
	solver->start();
	delete solver;
}

/**
 * Solves the knapsack problem found within the given input file
 * by applying the low memory version of the dynamic programming algorithm n times,
 * where n equals the numOfExecutions parameter.
 */
void executeDynamicProgrammingLowMemorySolver(const char* inputFile, int numOfExecutions=1){
	KnapSackSolver* solver = new DynamicProgrammingLowMemorySolver(inputFile, KNAPSACK_OUTPUT_FILE, numOfExecutions);
	solver->start();
	delete solver;
}

/**
 * Solves the knapsack problem found within the given input file
 * by applying the parallel low memory version of the dynamic programming algorithm n times,
 * where n equals the numOfExecutions parameter.
 */
void executeDynamicProgrammingLowMemoryParallelSolver(const char* inputFile, int numOfExecutions=1){
	KnapSackSolver* solver = new DynamicProgrammingLowMemoryParallelSolver(inputFile, KNAPSACK_OUTPUT_FILE, numOfExecutions);
	solver->start();
	delete solver;
}

/**
 * Can be used to check if open mp is supported by the current environment
 */
void checkForOpenMP(){
	int id;
	#pragma omp parallel private(id)
	{
		id = omp_get_thread_num();
		printf("%d: Hello World!\n", id);
	}
}

/**
 * Entry point of the application.
 * Can be used to determine which algorithm should be performed how often.
 * The problem which the specific algorithm shall solve, can be determined
 * by changing the respective input file parameter.
 */
int main(int argc, char* argv[]){

	int numberOfExecutions = 1;
	const char* inputFile = FIRST_KNAPSACK_INPUT_FILE;

	// Command line argumennts: program [nrOfExecutions] [filePath]
	if (3 == argc) {
		numberOfExecutions = std::atoi(argv[1]);
		inputFile = argv[2];

	executeBruteForceSolver(inputFile, numberOfExecutions);
	executeNemhauserUllmanSolver(inputFile, numberOfExecutions);
	executeNemhauserUllmanParallelSolver(inputFile, numberOfExecutions);
	executeNemhauserUllmanRLPSolver(inputFile, numberOfExecutions);
	executeNemhauserUllmanRLPParallelSolver(inputFile, numberOfExecutions);
	executeDynamicProgrammingSolver(inputFile, numberOfExecutions);
	executeDynamicProgrammingParallelSolver(inputFile, numberOfExecutions);
	executeDynamicProgrammingLowMemorySolver(inputFile, numberOfExecutions);
	executeDynamicProgrammingLowMemoryParallelSolver(inputFile, numberOfExecutions);

}
<commit_msg>Oops there was a syntax error in Main.cpp<commit_after>#include <omp.h>
#include <stdio.h>

#include "main/algorithms/BruteForceSolver.h"
#include "main/algorithms/DynamicProgrammingSolver.h"
#include "main/algorithms/DynamicProgrammingParallelSolver.h"
#include "main/algorithms/DynamicProgrammingLowMemorySolver.h"
#include "main/algorithms/DynamicProgrammingLowMemoryParallelSolver.h"
#include "main/algorithms/NemhauserUllmannSolver.h"
#include "main/algorithms/NemhauserUllmannParallelSolver.h"
#include "main/algorithms/NemhauserUllmannSolverRLP.h"
#include "main/algorithms/NemhauserUllmannRLPParallelSolver.h"
using namespace std;

#define PRINT_VERBOSE

static const char* FIRST_KNAPSACK_INPUT_FILE = "res/firstFileExample.txt";
static const char* SECOND_KNAPSACK_INPUT_FILE = "res/secondFileExample.txt";
static const char* THIRD_KNAPSACK_INPUT_FILE = "res/thirdFileExample.txt";
static const char* FOURTH_KNAPSACK_INPUT_FILE = "res/fourthFileExample.txt";
static const char* FIFTH_KNAPSACK_INPUT_FILE = "res/fifthFileExample.txt";
static const char* SIXTH_KNAPSACK_INPUT_FILE = "res/sixthFileExample.txt";
static const char* SEVENTH_KNAPSACK_INPUT_FILE = "res/seventhFileExample.txt";
static const char* DP_INPUT_FILE = "res/dynamicProgrammingExample.txt";
static const char* SECOND_DP_INPUT_FILE = "res/secondDynamicProgrammingExample.txt";
static const char* KNAPSACK_OUTPUT_FILE = "knapSackOut.txt";

/**
 * Solves the knapsack problem found within the given input file
 * by applying the brute force algorithm n times, where n equals the numOfExecutions parameter.
 */
void executeBruteForceSolver(const char* inputFile, int numOfExecutions=1){
	KnapSackSolver* solver = new BruteForceSolver(inputFile, KNAPSACK_OUTPUT_FILE, numOfExecutions);
	solver->start();
	delete solver;
}

/**
 * Solves the knapsack problem found within the given input file
 * by applying the nemhauser ullman algorithm n times, where n equals the numOfExecutions parameter.
 */
void executeNemhauserUllmanSolver(const char* inputFile, const int numOfExecutions=1) {
	KnapSackSolver* solver = new NemhauserUllmannSolver(inputFile, KNAPSACK_OUTPUT_FILE, numOfExecutions);
	solver->start();
	delete solver;
}

/**
 * Solves the knapsack problem found within the given input file
 * by applying the parallel nemhauser ullman algorithm n times, where n equals the numOfExecutions parameter.
 */
void executeNemhauserUllmanParallelSolver(const char* inputFile, int numOfExecutions=1) {
	KnapSackSolver* solver = new NemhauserUllmannParallelSolver(inputFile, KNAPSACK_OUTPUT_FILE, numOfExecutions);
	solver->start();
	delete solver;
}

/**
 * Solves the knapsack problem found within the given input file
 * by applying the rlp improved version of the nemhauser ullman algorithm n times,
 * where n equals the numOfExecutions parameter.
 */
void executeNemhauserUllmanRLPSolver(const char* inputFile, int numOfExecutions=1) {
	KnapSackSolver* solver = new NemhauserUllmannSolverRLP(inputFile, KNAPSACK_OUTPUT_FILE, numOfExecutions);
	solver->start();
	delete solver;
}

/**
 * Solves the knapsack problem found within the given input file
 * by applying the parallel rlp improved version of the nemhauser ullman algorithm n times,
 * where n equals the numOfExecutions parameter.
 */
void executeNemhauserUllmanRLPParallelSolver(const char* inputFile, int numOfExecutions=1) {
	bool sortInputByWorth = false;
	KnapSackSolver* solver = new NemhauserUllmannRLPParallelSolver(inputFile, KNAPSACK_OUTPUT_FILE, numOfExecutions, sortInputByWorth);
	solver->start();
	delete solver;
}

/**
 * Solves the knapsack problem found within the given input file
 * by applying the dynamic programming algorithm n times,
 * where n equals the numOfExecutions parameter.
 */
void executeDynamicProgrammingSolver(const char* inputFile, int numOfExecutions=1){
	KnapSackSolver* solver = new DynamicProgrammingSolver(inputFile, KNAPSACK_OUTPUT_FILE, numOfExecutions);
	solver->start();
	delete solver;
}

/**
 * Solves the knapsack problem found within the given input file
 * by applying the parallel dynamic programming algorithm n times,
 * where n equals the numOfExecutions parameter.
 */
void executeDynamicProgrammingParallelSolver(const char* inputFile, int numOfExecutions=1){
	KnapSackSolver* solver = new DynamicProgrammingParallelSolver(inputFile, KNAPSACK_OUTPUT_FILE, numOfExecutions);
	solver->start();
	delete solver;
}

/**
 * Solves the knapsack problem found within the given input file
 * by applying the low memory version of the dynamic programming algorithm n times,
 * where n equals the numOfExecutions parameter.
 */
void executeDynamicProgrammingLowMemorySolver(const char* inputFile, int numOfExecutions=1){
	KnapSackSolver* solver = new DynamicProgrammingLowMemorySolver(inputFile, KNAPSACK_OUTPUT_FILE, numOfExecutions);
	solver->start();
	delete solver;
}

/**
 * Solves the knapsack problem found within the given input file
 * by applying the parallel low memory version of the dynamic programming algorithm n times,
 * where n equals the numOfExecutions parameter.
 */
void executeDynamicProgrammingLowMemoryParallelSolver(const char* inputFile, int numOfExecutions=1){
	KnapSackSolver* solver = new DynamicProgrammingLowMemoryParallelSolver(inputFile, KNAPSACK_OUTPUT_FILE, numOfExecutions);
	solver->start();
	delete solver;
}

/**
 * Can be used to check if open mp is supported by the current environment
 */
void checkForOpenMP(){
	int id;
	#pragma omp parallel private(id)
	{
		id = omp_get_thread_num();
		printf("%d: Hello World!\n", id);
	}
}

/**
 * Entry point of the application.
 * Can be used to determine which algorithm should be performed how often.
 * The problem which the specific algorithm shall solve, can be determined
 * by changing the respective input file parameter.
 */
int main(int argc, char* argv[]){

	int numberOfExecutions = 1;
	const char* inputFile = FIRST_KNAPSACK_INPUT_FILE;

	// Command line argumennts: program [nrOfExecutions] [filePath]
	if (3 == argc) {
		numberOfExecutions = std::atoi(argv[1]);
		inputFile = argv[2];
	}

	executeBruteForceSolver(inputFile, numberOfExecutions);
	executeNemhauserUllmanSolver(inputFile, numberOfExecutions);
	executeNemhauserUllmanParallelSolver(inputFile, numberOfExecutions);
	executeNemhauserUllmanRLPSolver(inputFile, numberOfExecutions);
	executeNemhauserUllmanRLPParallelSolver(inputFile, numberOfExecutions);
	executeDynamicProgrammingSolver(inputFile, numberOfExecutions);
	executeDynamicProgrammingParallelSolver(inputFile, numberOfExecutions);
	executeDynamicProgrammingLowMemorySolver(inputFile, numberOfExecutions);
	executeDynamicProgrammingLowMemoryParallelSolver(inputFile, numberOfExecutions);

}
<|endoftext|>


<commit_before>// Copyright (c) 2013 Vicente Romero Calero
//
// Distributed under the MIT software license, see the file LICENSE
//
// Author: Vicente Romero <vteromero@gmail.com>
//
// This file tests the BST class

#include <stdio.h>

#include "structures/bst.h"

void PrintValue(const int &value)
{
    printf("%d ", value);
}

void CheckValue(BST<int>& bst, const int& value)
{
    BSTNode<int> *node = bst.Search(value);
    if(node == NULL)
        printf("Value %d doesn't exist!\n", value);
    else
        printf("Value %d exist!\n", value);
}

int main()
{
    BST<int> bst;
    void (*p_funct)(const int&) = PrintValue;

    printf("\n****** Inserting values ******\n");
    bst.Insert(44);
    bst.Insert(4);
    bst.Insert(3);
    bst.Insert(13);
    bst.Insert(-10);
    bst.Insert(-22);
    bst.Insert(9);

    printf("In-order tree walk: ");
    bst.InOrderWalk(p_funct);
    printf("\n");

    printf("Reverse in-order tree walk: ");
    bst.ReverseInOrderWalk(p_funct);
    printf("\n");

    printf("Pre-order tree walk: ");
    bst.PreOrderWalk(p_funct);
    printf("\n");

    printf("Post-order tree walk: ");
    bst.PostOrderWalk(p_funct);
    printf("\n");

    printf("Size: %d\n", bst.size());
    printf("Minimum: %d\n", bst.Minimum());
    printf("Maximum: %d\n", bst.Maximum());

    printf("\n****** Deleting values ******\n");
    bst.Delete(-10);
    bst.Delete(13);
    bst.Delete(44);

    printf("In-order tree walk: ");
    bst.InOrderWalk(p_funct);
    printf("\n");

    printf("Reverse in-order tree walk: ");
    bst.ReverseInOrderWalk(p_funct);
    printf("\n");

    printf("Pre-order tree walk: ");
    bst.PreOrderWalk(p_funct);
    printf("\n");

    printf("Post-order tree walk: ");
    bst.PostOrderWalk(p_funct);
    printf("\n");

    printf("Size: %d\n", bst.size());
    printf("Minimum: %d\n", bst.Minimum());
    printf("Maximum: %d\n", bst.Maximum());

    printf("\n****** Checking values ******\n");
    CheckValue(bst, 1000);
    CheckValue(bst, 3);

    printf("\n****** Accessing through position ******\n");
    printf("Value at 0: %d\n", bst.Get(0));
    printf("Value at 2: %d\n", bst.Get(2));

    return 0;
}
<commit_msg>normalization of directory names<commit_after>// Copyright (c) 2013 Vicente Romero Calero
//
// Distributed under the MIT software license, see the file LICENSE
//
// Author: Vicente Romero <vteromero@gmail.com>
//
// This file tests the BST class

#include <stdio.h>

#include "structure/bst.h"

void PrintValue(const int &value)
{
    printf("%d ", value);
}

void CheckValue(BST<int>& bst, const int& value)
{
    BSTNode<int> *node = bst.Search(value);
    if(node == NULL)
        printf("Value %d doesn't exist!\n", value);
    else
        printf("Value %d exist!\n", value);
}

int main()
{
    BST<int> bst;
    void (*p_funct)(const int&) = PrintValue;

    printf("\n****** Inserting values ******\n");
    bst.Insert(44);
    bst.Insert(4);
    bst.Insert(3);
    bst.Insert(13);
    bst.Insert(-10);
    bst.Insert(-22);
    bst.Insert(9);

    printf("In-order tree walk: ");
    bst.InOrderWalk(p_funct);
    printf("\n");

    printf("Reverse in-order tree walk: ");
    bst.ReverseInOrderWalk(p_funct);
    printf("\n");

    printf("Pre-order tree walk: ");
    bst.PreOrderWalk(p_funct);
    printf("\n");

    printf("Post-order tree walk: ");
    bst.PostOrderWalk(p_funct);
    printf("\n");

    printf("Size: %d\n", bst.size());
    printf("Minimum: %d\n", bst.Minimum());
    printf("Maximum: %d\n", bst.Maximum());

    printf("\n****** Deleting values ******\n");
    bst.Delete(-10);
    bst.Delete(13);
    bst.Delete(44);

    printf("In-order tree walk: ");
    bst.InOrderWalk(p_funct);
    printf("\n");

    printf("Reverse in-order tree walk: ");
    bst.ReverseInOrderWalk(p_funct);
    printf("\n");

    printf("Pre-order tree walk: ");
    bst.PreOrderWalk(p_funct);
    printf("\n");

    printf("Post-order tree walk: ");
    bst.PostOrderWalk(p_funct);
    printf("\n");

    printf("Size: %d\n", bst.size());
    printf("Minimum: %d\n", bst.Minimum());
    printf("Maximum: %d\n", bst.Maximum());

    printf("\n****** Checking values ******\n");
    CheckValue(bst, 1000);
    CheckValue(bst, 3);

    printf("\n****** Accessing through position ******\n");
    printf("Value at 0: %d\n", bst.Get(0));
    printf("Value at 2: %d\n", bst.Get(2));

    return 0;
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: linguprops.hxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: tl $ $Date: 2001-05-08 12:34:10 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#ifndef _SVTOOLS_LINGUPROPS_HXX_
#define _SVTOOLS_LINGUPROPS_HXX_

// UNO property names for general options
#define UPN_IS_GERMAN_PRE_REFORM            "IsGermanPreReform"
#define UPN_IS_USE_DICTIONARY_LIST          "IsUseDictionaryList"
#define UPN_IS_IGNORE_CONTROL_CHARACTERS    "IsIgnoreControlCharacters"
#define UPN_ACTIVE_DICTIONARIES             "ActiveDictionaries"

// UNO property names for SpellChecker
#define UPN_IS_SPELL_UPPER_CASE             "IsSpellUpperCase"
#define UPN_IS_SPELL_WITH_DIGITS            "IsSpellWithDigits"
#define UPN_IS_SPELL_CAPITALIZATION         "IsSpellCapitalization"

// UNO property names for Hyphenator
#define UPN_HYPH_MIN_LEADING                "HyphMinLeading"
#define UPN_HYPH_MIN_TRAILING               "HyphMinTrailing"
#define UPN_HYPH_MIN_WORD_LENGTH            "HyphMinWordLength"

// UNO property names for Lingu
// (those not covered by the SpellChecker and Hyphenator
// properties and more likely to be used in other modules only)
#define UPN_DEFAULT_LANGUAGE                "DefaultLanguage"
#define UPN_DEFAULT_LOCALE                  "DefaultLocale"
#define UPN_DEFAULT_LOCALE_CJK              "DefaultLocale_CJK"
#define UPN_DEFAULT_LOCALE_CTL              "DefaultLocale_CTL"
#define UPN_IS_HYPH_AUTO                    "IsHyphAuto"
#define UPN_IS_HYPH_SPECIAL                 "IsHyphSpecial"
#define UPN_IS_SPELL_AUTO                   "IsSpellAuto"
#define UPN_IS_SPELL_HIDE                   "IsSpellHide"
#define UPN_IS_SPELL_IN_ALL_LANGUAGES       "IsSpellInAllLanguages"
#define UPN_IS_SPELL_SPECIAL                "IsSpellSpecial"
#define UPN_IS_WRAP_REVERSE                 "IsWrapReverse"

// uno property handles
#define UPH_IS_GERMAN_PRE_REFORM             0
#define UPH_IS_USE_DICTIONARY_LIST           1
#define UPH_IS_IGNORE_CONTROL_CHARACTERS     2
#define UPH_IS_SPELL_UPPER_CASE              3
#define UPH_IS_SPELL_WITH_DIGITS             4
#define UPH_IS_SPELL_CAPITALIZATION          5
#define UPH_HYPH_MIN_LEADING                 6
#define UPH_HYPH_MIN_TRAILING                7
#define UPH_HYPH_MIN_WORD_LENGTH             8
#define UPH_DEFAULT_LOCALE                   9
#define UPH_IS_SPELL_AUTO                   10
#define UPH_IS_SPELL_HIDE                   11
#define UPH_IS_SPELL_IN_ALL_LANGUAGES       12
#define UPH_IS_SPELL_SPECIAL                13
#define UPH_IS_HYPH_AUTO                    14
#define UPH_IS_HYPH_SPECIAL                 15
#define UPH_IS_WRAP_REVERSE                 16
#define UPH_DEFAULT_LANGUAGE                21
#define UPH_DEFAULT_LOCALE_CJK              22
#define UPH_DEFAULT_LOCALE_CTL              23
#define UPH_ACTIVE_DICTIONARIES             24

#endif

<commit_msg>INTEGRATION: CWS tl01 (1.3.284); FILE MERGED 2003/08/01 11:28:59 tl 1.3.284.2: #110762# API for Hangul/Hanja user dictionaries 2003/07/29 09:20:42 tl 1.3.284.1: #110762# Hangul/Hanja text conversion user dictionaries<commit_after>/*************************************************************************
 *
 *  $RCSfile: linguprops.hxx,v $
 *
 *  $Revision: 1.4 $
 *
 *  last change: $Author: obo $ $Date: 2004-04-27 15:59:19 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#ifndef _SVTOOLS_LINGUPROPS_HXX_
#define _SVTOOLS_LINGUPROPS_HXX_

// UNO property names for general options
#define UPN_IS_GERMAN_PRE_REFORM            "IsGermanPreReform"
#define UPN_IS_USE_DICTIONARY_LIST          "IsUseDictionaryList"
#define UPN_IS_IGNORE_CONTROL_CHARACTERS    "IsIgnoreControlCharacters"
#define UPN_ACTIVE_DICTIONARIES             "ActiveDictionaries"

// UNO property names for SpellChecker
#define UPN_IS_SPELL_UPPER_CASE             "IsSpellUpperCase"
#define UPN_IS_SPELL_WITH_DIGITS            "IsSpellWithDigits"
#define UPN_IS_SPELL_CAPITALIZATION         "IsSpellCapitalization"

// UNO property names for Hyphenator
#define UPN_HYPH_MIN_LEADING                "HyphMinLeading"
#define UPN_HYPH_MIN_TRAILING               "HyphMinTrailing"
#define UPN_HYPH_MIN_WORD_LENGTH            "HyphMinWordLength"

// UNO property names for Lingu
// (those not covered by the SpellChecker and Hyphenator
// properties and more likely to be used in other modules only)
#define UPN_DEFAULT_LANGUAGE                "DefaultLanguage"
#define UPN_DEFAULT_LOCALE                  "DefaultLocale"
#define UPN_DEFAULT_LOCALE_CJK              "DefaultLocale_CJK"
#define UPN_DEFAULT_LOCALE_CTL              "DefaultLocale_CTL"
#define UPN_IS_HYPH_AUTO                    "IsHyphAuto"
#define UPN_IS_HYPH_SPECIAL                 "IsHyphSpecial"
#define UPN_IS_SPELL_AUTO                   "IsSpellAuto"
#define UPN_IS_SPELL_HIDE                   "IsSpellHide"
#define UPN_IS_SPELL_IN_ALL_LANGUAGES       "IsSpellInAllLanguages"
#define UPN_IS_SPELL_SPECIAL                "IsSpellSpecial"
#define UPN_IS_WRAP_REVERSE                 "IsWrapReverse"

// UNO property names for text conversion options
#define UPN_ACTIVE_CONVERSION_DICTIONARIES  "ActiveConversionDictionaries"
#define UPN_IS_IGNORE_POST_POSITIONAL_WORD  "IsIgnorePostPositionalWord"
#define UPN_IS_AUTO_CLOSE_DIALOG            "IsAutoCloseDialog"
#define UPN_IS_SHOW_ENTRIES_RECENTLY_USED_FIRST     "IsShowEntriesRecentlyUsedFirst"
#define UPN_IS_AUTO_REPLACE_UNIQUE_ENTRIES  "IsAutoReplaceUniqueEntries"

// uno property handles
#define UPH_IS_GERMAN_PRE_REFORM             0
#define UPH_IS_USE_DICTIONARY_LIST           1
#define UPH_IS_IGNORE_CONTROL_CHARACTERS     2
#define UPH_IS_SPELL_UPPER_CASE              3
#define UPH_IS_SPELL_WITH_DIGITS             4
#define UPH_IS_SPELL_CAPITALIZATION          5
#define UPH_HYPH_MIN_LEADING                 6
#define UPH_HYPH_MIN_TRAILING                7
#define UPH_HYPH_MIN_WORD_LENGTH             8
#define UPH_DEFAULT_LOCALE                   9
#define UPH_IS_SPELL_AUTO                   10
#define UPH_IS_SPELL_HIDE                   11
#define UPH_IS_SPELL_IN_ALL_LANGUAGES       12
#define UPH_IS_SPELL_SPECIAL                13
#define UPH_IS_HYPH_AUTO                    14
#define UPH_IS_HYPH_SPECIAL                 15
#define UPH_IS_WRAP_REVERSE                 16
#define UPH_DEFAULT_LANGUAGE                21
#define UPH_DEFAULT_LOCALE_CJK              22
#define UPH_DEFAULT_LOCALE_CTL              23
#define UPH_ACTIVE_DICTIONARIES             24
#define UPH_ACTIVE_CONVERSION_DICTIONARIES  25
#define UPH_IS_IGNORE_POST_POSITIONAL_WORD  26
#define UPH_IS_AUTO_CLOSE_DIALOG            27
#define UPH_IS_SHOW_ENTRIES_RECENTLY_USED_FIRST     28
#define UPH_IS_AUTO_REPLACE_UNIQUE_ENTRIES  29

#endif

<|endoftext|>


<commit_before>#include "lib/pool.hpp"

int main(int argc, char **argv) {
  return 0;
}
<commit_msg>Add parallel merge sort<commit_after>#include <future>
#include <cstdio>
#include <cstdlib>
#include <time.h>

#define PRINT true

void merge_sort(int array[], const int left, const int right) {
  if (right - left < 1) return;
  const int middle = (left + right) / 2;
  auto lh = std::async(std::launch::async, [array, left, middle]() {
    merge_sort(array, left, middle);
  });
  auto rh = std::async(std::launch::async, [array, middle, right]() {
    merge_sort(array, middle + 1, right);
  });
  lh.get();
  rh.get();
  int temp[right - left + 1];
  int k = 0, l = left, m = middle + 1;
  while (l <= middle && m <= right) {
    if (array[l] < array[m]) {
      temp[k++] = array[l++];
    } else {
      temp[k++] = array[m++];
    }
  }
  while (l <= middle) temp[k++] = array[l++];
  while (m <= right) temp[k++] = array[m++];
  for (int v = 0, i = left; i <= right; ++i, ++v) array[i] = temp[v];
}

int main(int argc, char **argv) {
  srand(time(nullptr));
  int array_size = 100;
  int *arr = new int[array_size];
  for (int i = 0; i < array_size; ++i) arr[i] = rand() % 1000;
  merge_sort(arr, 0, array_size - 1);
#if PRINT
  for (int i = 0; i < array_size; ++i) printf("%d ", arr[i]);
  puts("");
#endif
  delete[] arr;
  return 0;
}
<|endoftext|>


<commit_before>#include <cstdlib>
#include <cstdio>
#include <cstdint>
#include <cstring>
#include <cassert>
#include <algorithm>

#include "input_data.cpp"
#include "gettime.cpp"
#include "quicksort.cpp"

class PerformanceTest final {

    int         iterations;
    InputData&  input;
    uint32_t*   tmp;

public:
    PerformanceTest(int n, InputData& input)
        : iterations(n)
        , input(input) {

        assert(iterations > 0);
        tmp = new uint32_t[input.count()];
    }

    ~PerformanceTest() {
        delete[] tmp;
    }

public:
    template <typename SORT_FUNCTION>
    uint32_t run(SORT_FUNCTION sort) {

        uint32_t time = 0;

        int k = iterations;
        while (k--) {
            memcpy(tmp, input.pointer(), input.size());

            const uint32_t t1 = get_time();
            sort(input.pointer(), 0, input.count() - 1);
            const uint32_t t2 = get_time();

            const uint32_t dt = t2 - t1;

            if (time == 0) {
                time = dt;
            } else if (dt < time) {
                time = dt;
            }
        }

        return time;
    }
};

void std_sort_wrapper(uint32_t* array, int left, int right) {

    std::sort(array + left, array + right + 1);
}

template <typename SORT_FUNCTION>
uint32_t measure(const char* name, SORT_FUNCTION sort, InputData& data, uint32_t ref) {

    PerformanceTest test(3, data);

    printf("%30s ... ", name); fflush(stdout);
    uint32_t time = test.run(sort);
    if (ref > 0) {
        printf("%0.4f s (%0.2f)\n", time/1000000.0, ref/double(time));
    } else {
        printf("%0.4f s\n", time/1000000.0);
    }

    return time;
}

int main(int argc, char* argv[]) {

#define M 1000000
    size_t count = 10*M;

    if (argc > 1 && atoi(argv[1]) > 0) {
        count = atoi(argv[1]) * M;
    }

    InputRandom data(count);

    printf("items count: %lu (%lu bytes)\n", data.count(), data.size());

    uint32_t ref = 0;
    ref = measure("std::sort",              std_sort_wrapper,        data, 0);
    measure("quick sort",                   quicksort,               data, ref);
    measure("AVX512 quick sort",            avx512_quicksort,        data, ref);
    measure("AVX512 + popcnt quick sort",   avx512_popcnt_quicksort, data, ref);
}
<commit_msg>AVX512 quicksort: speed util parses cmd line<commit_after>#include <cstdlib>
#include <cstdio>
#include <cstdint>
#include <cstring>
#include <cassert>
#include <algorithm>
#include <memory>

#include "input_data.cpp"
#include "gettime.cpp"
#include "quicksort.cpp"

class PerformanceTest final {

    int         iterations;
    InputData&  input;
    uint32_t*   tmp;

public:
    PerformanceTest(int n, InputData& input)
        : iterations(n)
        , input(input) {

        assert(iterations > 0);
        tmp = new uint32_t[input.count()];
    }

    ~PerformanceTest() {
        delete[] tmp;
    }

public:
    template <typename SORT_FUNCTION>
    uint32_t run(SORT_FUNCTION sort) {

        uint32_t time = 0;

        int k = iterations;
        while (k--) {
            memcpy(tmp, input.pointer(), input.size());

            const uint32_t t1 = get_time();
            sort(input.pointer(), 0, input.count() - 1);
            const uint32_t t2 = get_time();

            const uint32_t dt = t2 - t1;

            if (time == 0) {
                time = dt;
            } else if (dt < time) {
                time = dt;
            }
        }

        return time;
    }
};

enum class InputType {
    random,
    ascending,
    descending,
};

const char* as_string(InputType type) {
    switch (type) {
        case InputType::random:
            return "random";

        case InputType::ascending:
            return "ascending";

        case InputType::descending:
            return "descending";

        default:
            return "<unknown>";
    }
}

void std_sort_wrapper(uint32_t* array, int left, int right) {

    std::sort(array + left, array + right + 1);
}

class Test {

    std::unique_ptr<InputData> data;
    InputType   type;
    size_t      count;
    int         iterations;

public:
    Test(InputType type, size_t count, int iterations)
        : type(type)
        , count(count)
        , iterations(iterations) {

        switch (type) {
            case InputType::random:
                data.reset(new InputRandom(count));
                break;

            case InputType::ascending:
                data.reset(new InputAscending(count));
                break;

            case InputType::descending:
                data.reset(new InputDescending(count));
                break;
        }
    }

    void run() {

        printf("items count: %lu (%lu bytes), input %s\n", data->count(), data->size(), as_string(type));

        uint32_t ref = 0;
        ref = measure("std::sort",              std_sort_wrapper,        ref);
        measure("quick sort",                   quicksort,               ref);
        measure("AVX512 quick sort",            avx512_quicksort,        ref);
        measure("AVX512 + popcnt quick sort",   avx512_popcnt_quicksort, ref);
    }

private:
    template <typename SORT_FUNCTION>
    uint32_t measure(const char* name, SORT_FUNCTION sort, uint32_t ref) {

        PerformanceTest test(iterations, *data);

        printf("%30s ... ", name); fflush(stdout);
        uint32_t time = test.run(sort);
        if (ref > 0) {
            printf("%0.4f s (%0.2f)\n", time/1000000.0, ref/double(time));
        } else {
            printf("%0.4f s\n", time/1000000.0);
        }

        return time;
    }
};

// ------------------------------------------------------------

void usage() {
    puts("usage:");
    puts("speed SIZE ITERATIONS INPUT");
    puts("");
    puts("where");
    puts("* SIZE       - number of 32-bit elements");
    puts("* ITERATIONS - number of iterations");
    puts("* INPUT      - one of:");
    puts("                 ascending (or asc)");
    puts("                 descending (or dsc, desc)");
    puts("                 random (or rnd, rand)");
}

int main(int argc, char* argv[]) {

    if (argc < 4) {
        usage();
        return EXIT_FAILURE;
    }

    int count      = atoi(argv[1]);
    int iterations = atoi(argv[2]);
    InputType type;

#define is_keyword(key) (strcmp(argv[3], key) == 0)
    if (is_keyword("descending") || is_keyword("dsc") || is_keyword("dsc")) {
        type = InputType::descending;
    } else if (is_keyword("ascending") || is_keyword("asc")) {
        type = InputType::ascending;
    } else if (is_keyword("random") || is_keyword("rand") || is_keyword("rnd")) {
        type = InputType::ascending;
    } else {
        usage();
        return EXIT_FAILURE;
    }
#undef is_keyword

    Test test(type, count, iterations);
    test.run();

    return EXIT_SUCCESS;
}
<|endoftext|>


<commit_before>// KMail Account Manager

#include "accountmanager.h"

#include "kmaccount.h"
#include "kmacctmaildir.h"
#include "kmacctlocal.h"
#include "popaccount.h"
#include "kmacctimap.h"
#include "networkaccount.h"
#include "kmacctcachedimap.h"
#include "broadcaststatus.h"
#include "kmfiltermgr.h"
#include "globalsettings.h"

#include <klocale.h>
#include <kmessagebox.h>
#include <kdebug.h>
#include <kconfig.h>

#include <QRegExp>
#include <krandom.h>
#include <kconfiggroup.h>

using namespace KMail;

//-----------------------------------------------------------------------------
AccountManager::AccountManager()
    :QObject(), mNewMailArrived( false ), mInteractive( false ),
     mTotalNewMailsArrived( 0 ), mDisplaySummary( false )
{
  mAcctChecking.clear();
  mAcctTodo.clear();
}

//-----------------------------------------------------------------------------
AccountManager::~AccountManager()
{
  writeConfig( false );
}

//-----------------------------------------------------------------------------
void AccountManager::writeConfig( bool withSync )
{
  KConfig* config = KMKernel::config();

  // Delete all account enabled groups in the config file
  // and replace them with new account groups
  uint accounts = 0;
  QStringList accountGroups =
    config->groupList().filter( QRegExp( "Account \\d+" ) );
  AccountList::ConstIterator enabledAccountIt = mAcctList.constBegin();
  foreach ( const QString& groupName, accountGroups ) {
    KConfigGroup group(config, groupName);
    uint id = group.readEntry( "Id", 0 );
    if ( mDisabledAccounts.contains( id ) )
      accounts++;
    else {
      config->deleteGroup( groupName );
      if ( enabledAccountIt != mAcctList.constEnd() ) {
        (*enabledAccountIt)->writeConfig( group );
        ++enabledAccountIt;
        accounts++;
      }
    }
  }

  KConfigGroup group(config, "General");
  group.writeEntry("accounts", accounts);

  if (withSync) config->sync();
}

//-----------------------------------------------------------------------------
void AccountManager::readConfig(void)
{
  KConfig* config = KMKernel::config();
  KMAccount* acct;
  QString acctName;
  QString groupName;
  int i, num;

  for ( AccountList::Iterator it( mAcctList.begin() ), end( mAcctList.end() ); it != end; ++it )
      delete *it;
  mAcctList.clear();

  KConfigGroup general(config, "General");
  num = general.readEntry( "accounts", 0 );

  for (i=1; i<=num; i++)
  {
    groupName.sprintf("Account %d", i);
    KConfigGroup group(config, groupName);
    uint id = group.readEntry( "Id", 0 );
    if ( !group.readEntry("Enabled", true) ) {
      mDisabledAccounts += id;
      continue;
    }

    KAccount::Type acctType = KAccount::typeForName( group.readEntry( "Type" ) );
    acctName = group.readEntry("Name");
    if (acctName.isEmpty()) acctName = i18n("Account %1", i);
    acct = create(acctType, acctName, id);
    if (!acct) continue;
    add(acct);
    acct->readConfig(group);
  }
}

//-----------------------------------------------------------------------------
void AccountManager::singleCheckMail(KMAccount *account, bool interactive)
{
  mNewMailArrived = false;
  mInteractive = interactive;

  // queue the account
  mAcctTodo.append(account);

  if (account->checkingMail())
  {
    kDebug(5006) <<"account" << account->name() <<" busy, queuing";
    return;
  }

  processNextCheck( false );
}

//-----------------------------------------------------------------------------
void AccountManager::processNextCheck( bool _newMail )
{
  kDebug(5006) <<"processNextCheck, remaining" << mAcctTodo.count();
  if ( _newMail )
    mNewMailArrived = true;

  for ( AccountList::Iterator it( mAcctChecking.begin() ), end( mAcctChecking.end() ); it != end;  ) {
    KMAccount* acct = *it;
    ++it;
    if ( acct->checkingMail() )
      continue;
    // check done
    kDebug(5006) <<"account" << acct->name() <<" finished check";
    mAcctChecking.removeAll( acct );
    kmkernel->filterMgr()->deref();
    disconnect( acct, SIGNAL( finishedCheck( bool, CheckStatus ) ),
                      this, SLOT( processNextCheck( bool ) ) );
  }
  if ( mAcctChecking.isEmpty() ) {
    // all checks finished, display summary
    if ( mDisplaySummary )
      KPIM::BroadcastStatus::instance()->setStatusMsgTransmissionCompleted(
          mTotalNewMailsArrived );
    emit checkedMail( mNewMailArrived, mInteractive, mTotalNewInFolder );
    mTotalNewMailsArrived = 0;
    mTotalNewInFolder.clear();
    mDisplaySummary = false;
  }
  if ( mAcctTodo.isEmpty() ) return;

  QString accountHostName;

  KMAccount *curAccount = 0;
  for ( AccountList::Iterator it ( mAcctTodo.begin() ), last ( mAcctTodo.end() ); it != last; ) {
    KMAccount *acct = *it;
    ++it;
    if ( !acct->checkingMail() && acct->mailCheckCanProceed() ) {
      curAccount = acct;
      mAcctTodo.removeAll( acct );
      break;
    }
  }
  if ( !curAccount ) return; // no account or all of them are already checking

  if ( curAccount->type() != KAccount::Imap &&
       curAccount->type() != KAccount::DImap &&
       curAccount->folder() == 0 ) {
    QString tmp = i18n("Account %1 has no mailbox defined:\n"
        "mail checking aborted;\n"
        "check your account settings.",
       curAccount->name());
    KMessageBox::information(0,tmp);
    emit checkedMail( false, mInteractive, mTotalNewInFolder );
    mTotalNewMailsArrived = 0;
    mTotalNewInFolder.clear();
    return;
  }

  connect( curAccount, SIGNAL( finishedCheck( bool, CheckStatus ) ),
                this, SLOT( processNextCheck( bool ) ) );

  KPIM::BroadcastStatus::instance()->setStatusMsg(
      i18n("Checking account %1 for new mail", curAccount->name()));

  kDebug(5006) <<"processing next mail check for" << curAccount->name();

  curAccount->setCheckingMail( true );
  mAcctChecking.append( curAccount );
  kmkernel->filterMgr()->ref();
  curAccount->processNewMail( mInteractive );
}

//-----------------------------------------------------------------------------
KMAccount* AccountManager::create( const KAccount::Type aType,
                                   const QString &aName, uint id )
{
  KMAccount* act = 0;
  if ( id == 0 )
    id = createId();

  if ( aType == KAccount::Local) {
    act = new KMAcctLocal(this, aName.isEmpty() ? i18n("Local Account") : aName, id);
    act->setFolder( kmkernel->inboxFolder() );
  } else if ( aType == KAccount::Maildir) {
    act = new KMAcctMaildir(this, aName.isEmpty() ? i18n("Local Account") : aName, id);
    act->setFolder( kmkernel->inboxFolder() );
  } else if ( aType == KAccount::Pop) {
    act = new KMail::PopAccount(this, aName.isEmpty() ? i18n("POP Account") : aName, id);
    act->setFolder( kmkernel->inboxFolder() );
  } else if ( aType == KAccount::Imap) {
    act = new KMAcctImap(this, aName.isEmpty() ? i18n("IMAP Account") : aName, id);
  } else if (aType == KAccount::DImap) {
    act = new KMAcctCachedImap(this, aName.isEmpty() ? i18n("IMAP Account") : aName, id);
  }
  if ( !act ) {
      kWarning(5006) <<"Attempt to instantiate a non-existing account type!";
      return 0;
  }
  act->setType( aType );
  connect( act, SIGNAL( newMailsProcessed( const QMap<QString, int> & ) ),
                this, SLOT( addToTotalNewMailCount( const QMap<QString, int> & ) ) );
  return act;
}

//-----------------------------------------------------------------------------
void AccountManager::add( KMAccount *account )
{
  if ( account ) {
    mAcctList.append( account );
    emit accountAdded( account );
    account->installTimer();
  }
}

//-----------------------------------------------------------------------------
KMAccount* AccountManager::findByName(const QString &aName) const
{
  if ( aName.isEmpty() ) return 0;

  for ( AccountList::ConstIterator it( mAcctList.begin() ), end( mAcctList.end() ); it != end; ++it ) {
    if ( (*it)->name() == aName ) return (*it);
  }
  return 0;
}

//-----------------------------------------------------------------------------
KMAccount* AccountManager::find( const uint id ) const
{
  if (id == 0) return 0;
  for ( AccountList::ConstIterator it( mAcctList.begin() ), end( mAcctList.end() ); it != end; ++it ) {
    if ( (*it)->id() == id ) return (*it);
  }
  return 0;
}

//-----------------------------------------------------------------------------
KMAccount* AccountManager::first()
{
  if ( !mAcctList.empty() ) {
    mPtrListInterfaceProxyIterator = mAcctList.begin();
    return *mPtrListInterfaceProxyIterator;
  } else {
    return 0;
  }
}

//-----------------------------------------------------------------------------
KMAccount* AccountManager::next()
{
    ++mPtrListInterfaceProxyIterator;
    if ( mPtrListInterfaceProxyIterator == mAcctList.end() )
        return 0;
    else
        return *mPtrListInterfaceProxyIterator;
}

//-----------------------------------------------------------------------------
bool AccountManager::remove( KMAccount* acct )
{
  if( !acct )
    return false;
  mAcctList.removeAll( acct );
  emit accountRemoved( acct );
  return true;
}

//-----------------------------------------------------------------------------
void AccountManager::checkMail( bool _interactive )
{
  mNewMailArrived = false;

  if ( mAcctList.isEmpty() ) {
    KMessageBox::information( 0,i18n("You need to add an account in the network "
                    "section of the settings in order to receive mail.") );
    return;
  }
  mDisplaySummary = true;

  mTotalNewMailsArrived=0;
  mTotalNewInFolder.clear();

  for ( AccountList::Iterator it( mAcctList.begin() ), end( mAcctList.end() ); it != end; ++it ) {
    if ( !(*it)->checkExclude() )
      singleCheckMail( (*it), _interactive);
  }
}

//-----------------------------------------------------------------------------
void AccountManager::singleInvalidateIMAPFolders(KMAccount *account) {
  account->invalidateIMAPFolders();
}

void AccountManager::invalidateIMAPFolders()
{
  for ( AccountList::ConstIterator it( mAcctList.begin() ), end( mAcctList.end() ); it != end; ++it )
    singleInvalidateIMAPFolders( *it );
}

//-----------------------------------------------------------------------------
QStringList  AccountManager::getAccounts() const
{
  QStringList strList;
  for ( AccountList::ConstIterator it( mAcctList.begin() ), end( mAcctList.end() ); it != end; ++it ) {
    strList.append( (*it)->name() );
  }
  return strList;
}

//-----------------------------------------------------------------------------
void AccountManager::intCheckMail(int item, bool _interactive)
{
  mNewMailArrived = false;
  mTotalNewMailsArrived = 0;
  mTotalNewInFolder.clear();
  if ( KMAccount *acct = mAcctList[ item ] )
    singleCheckMail( acct, _interactive );
  mDisplaySummary = false;
}

//-----------------------------------------------------------------------------
void AccountManager::addToTotalNewMailCount( const QMap<QString, int> & newInFolder )
{
  for ( QMap<QString, int>::const_iterator it = newInFolder.begin();
        it != newInFolder.end(); ++it ) {
    mTotalNewMailsArrived += it.value();
    if ( !mTotalNewInFolder.contains( it.key() )  )
      mTotalNewInFolder[it.key()] = it.value();
    else
      mTotalNewInFolder[it.key()] += it.value();
  }
}

//-----------------------------------------------------------------------------
uint AccountManager::createId()
{
  QList<uint> usedIds;
  for ( AccountList::ConstIterator it( mAcctList.begin() ), end( mAcctList.end() ); it != end; ++it ) {
    usedIds << (*it)->id();
  }

  usedIds << 0; // 0 is default for unknown
  int newId;
  do
  {
    newId = KRandom::random();
  } while ( usedIds.contains(newId)  );

  return newId;
}

//-----------------------------------------------------------------------------
void AccountManager::cancelMailCheck()
{
  for ( AccountList::ConstIterator it( mAcctList.begin() ), end( mAcctList.end() ); it != end; ++it ) {
    (*it)->cancelMailCheck();
  }
}

//-----------------------------------------------------------------------------
void AccountManager::readPasswords()
{
  for ( AccountList::ConstIterator it( mAcctList.begin() ), end( mAcctList.end() ); it != end; ++it ) {
    NetworkAccount *acct = dynamic_cast<NetworkAccount*>( (*it) );
    if ( acct )
      acct->readPassword();
  }
}

#include "accountmanager.moc"
<commit_msg>Store new account settings.<commit_after>// KMail Account Manager

#include "accountmanager.h"

#include "kmaccount.h"
#include "kmacctmaildir.h"
#include "kmacctlocal.h"
#include "popaccount.h"
#include "kmacctimap.h"
#include "networkaccount.h"
#include "kmacctcachedimap.h"
#include "broadcaststatus.h"
#include "kmfiltermgr.h"
#include "globalsettings.h"

#include <klocale.h>
#include <kmessagebox.h>
#include <kdebug.h>
#include <kconfig.h>

#include <QRegExp>
#include <krandom.h>
#include <kconfiggroup.h>

using namespace KMail;

//-----------------------------------------------------------------------------
AccountManager::AccountManager()
    :QObject(), mNewMailArrived( false ), mInteractive( false ),
     mTotalNewMailsArrived( 0 ), mDisplaySummary( false )
{
  mAcctChecking.clear();
  mAcctTodo.clear();
}

//-----------------------------------------------------------------------------
AccountManager::~AccountManager()
{
  writeConfig( false );
}

//-----------------------------------------------------------------------------
void AccountManager::writeConfig( bool withSync )
{
  KConfig* config = KMKernel::config();

  // Delete all accounts for groups in the config file not having
  // Enabled=false flag (accountGroups)
  // and replace them with account groups existing in memory (mAcctList)
  uint accounts = 0;
  QStringList accountGroups =
    config->groupList().filter( QRegExp( "Account \\d+" ) );
  AccountList::ConstIterator enabledAccountIt = mAcctList.constBegin();
  for ( QStringList::ConstIterator it = accountGroups.constBegin() ;; ) {
    QString groupName;
    bool appendNewGroup = false;
    if ( it == accountGroups.constEnd() ) {
      if ( enabledAccountIt == mAcctList.constEnd() )
        break;
      appendNewGroup = true;
      groupName.sprintf( "Account %d", accounts + 1 );
    }
    else {
      groupName = *it;
      ++it;
    }

    KConfigGroup group(config, groupName);
    uint id = group.readEntry( "Id", 0 );
    if ( mDisabledAccounts.contains( id ) )
      accounts++; // do not modify disabled account - skip
    else {
      if ( appendNewGroup ) {
        (*enabledAccountIt)->writeConfig( group );
        ++enabledAccountIt;
        accounts++;
      }
      else // no such account on the list - disabled / enabled
        config->deleteGroup( groupName );
    }
  }

  KConfigGroup group(config, "General");
  group.writeEntry("accounts", accounts);

  if (withSync) config->sync();
}

//-----------------------------------------------------------------------------
void AccountManager::readConfig(void)
{
  KConfig* config = KMKernel::config();
  KMAccount* acct;
  QString acctName;
  QString groupName;
  int i, num;

  for ( AccountList::Iterator it( mAcctList.begin() ), end( mAcctList.end() ); it != end; ++it )
      delete *it;
  mAcctList.clear();

  KConfigGroup general(config, "General");
  num = general.readEntry( "accounts", 0 );

  for (i=1; i<=num; i++)
  {
    groupName.sprintf("Account %d", i);
    KConfigGroup group(config, groupName);
    uint id = group.readEntry( "Id", 0 );
    if ( !group.readEntry("Enabled", true) ) {
      mDisabledAccounts += id;
      continue;
    }

    KAccount::Type acctType = KAccount::typeForName( group.readEntry( "Type" ) );
    acctName = group.readEntry("Name");
    if (acctName.isEmpty()) acctName = i18n("Account %1", i);
    acct = create(acctType, acctName, id);
    if (!acct) continue;
    add(acct);
    acct->readConfig(group);
  }
}

//-----------------------------------------------------------------------------
void AccountManager::singleCheckMail(KMAccount *account, bool interactive)
{
  mNewMailArrived = false;
  mInteractive = interactive;

  // queue the account
  mAcctTodo.append(account);

  if (account->checkingMail())
  {
    kDebug(5006) <<"account" << account->name() <<" busy, queuing";
    return;
  }

  processNextCheck( false );
}

//-----------------------------------------------------------------------------
void AccountManager::processNextCheck( bool _newMail )
{
  kDebug(5006) <<"processNextCheck, remaining" << mAcctTodo.count();
  if ( _newMail )
    mNewMailArrived = true;

  for ( AccountList::Iterator it( mAcctChecking.begin() ), end( mAcctChecking.end() ); it != end;  ) {
    KMAccount* acct = *it;
    ++it;
    if ( acct->checkingMail() )
      continue;
    // check done
    kDebug(5006) <<"account" << acct->name() <<" finished check";
    mAcctChecking.removeAll( acct );
    kmkernel->filterMgr()->deref();
    disconnect( acct, SIGNAL( finishedCheck( bool, CheckStatus ) ),
                      this, SLOT( processNextCheck( bool ) ) );
  }
  if ( mAcctChecking.isEmpty() ) {
    // all checks finished, display summary
    if ( mDisplaySummary )
      KPIM::BroadcastStatus::instance()->setStatusMsgTransmissionCompleted(
          mTotalNewMailsArrived );
    emit checkedMail( mNewMailArrived, mInteractive, mTotalNewInFolder );
    mTotalNewMailsArrived = 0;
    mTotalNewInFolder.clear();
    mDisplaySummary = false;
  }
  if ( mAcctTodo.isEmpty() ) return;

  QString accountHostName;

  KMAccount *curAccount = 0;
  for ( AccountList::Iterator it ( mAcctTodo.begin() ), last ( mAcctTodo.end() ); it != last; ) {
    KMAccount *acct = *it;
    ++it;
    if ( !acct->checkingMail() && acct->mailCheckCanProceed() ) {
      curAccount = acct;
      mAcctTodo.removeAll( acct );
      break;
    }
  }
  if ( !curAccount ) return; // no account or all of them are already checking

  if ( curAccount->type() != KAccount::Imap &&
       curAccount->type() != KAccount::DImap &&
       curAccount->folder() == 0 ) {
    QString tmp = i18n("Account %1 has no mailbox defined:\n"
        "mail checking aborted;\n"
        "check your account settings.",
       curAccount->name());
    KMessageBox::information(0,tmp);
    emit checkedMail( false, mInteractive, mTotalNewInFolder );
    mTotalNewMailsArrived = 0;
    mTotalNewInFolder.clear();
    return;
  }

  connect( curAccount, SIGNAL( finishedCheck( bool, CheckStatus ) ),
                this, SLOT( processNextCheck( bool ) ) );

  KPIM::BroadcastStatus::instance()->setStatusMsg(
      i18n("Checking account %1 for new mail", curAccount->name()));

  kDebug(5006) <<"processing next mail check for" << curAccount->name();

  curAccount->setCheckingMail( true );
  mAcctChecking.append( curAccount );
  kmkernel->filterMgr()->ref();
  curAccount->processNewMail( mInteractive );
}

//-----------------------------------------------------------------------------
KMAccount* AccountManager::create( const KAccount::Type aType,
                                   const QString &aName, uint id )
{
  KMAccount* act = 0;
  if ( id == 0 )
    id = createId();

  if ( aType == KAccount::Local) {
    act = new KMAcctLocal(this, aName.isEmpty() ? i18n("Local Account") : aName, id);
    act->setFolder( kmkernel->inboxFolder() );
  } else if ( aType == KAccount::Maildir) {
    act = new KMAcctMaildir(this, aName.isEmpty() ? i18n("Local Account") : aName, id);
    act->setFolder( kmkernel->inboxFolder() );
  } else if ( aType == KAccount::Pop) {
    act = new KMail::PopAccount(this, aName.isEmpty() ? i18n("POP Account") : aName, id);
    act->setFolder( kmkernel->inboxFolder() );
  } else if ( aType == KAccount::Imap) {
    act = new KMAcctImap(this, aName.isEmpty() ? i18n("IMAP Account") : aName, id);
  } else if (aType == KAccount::DImap) {
    act = new KMAcctCachedImap(this, aName.isEmpty() ? i18n("IMAP Account") : aName, id);
  }
  if ( !act ) {
      kWarning(5006) <<"Attempt to instantiate a non-existing account type!";
      return 0;
  }
  act->setType( aType );
  connect( act, SIGNAL( newMailsProcessed( const QMap<QString, int> & ) ),
                this, SLOT( addToTotalNewMailCount( const QMap<QString, int> & ) ) );
  return act;
}

//-----------------------------------------------------------------------------
void AccountManager::add( KMAccount *account )
{
  if ( account ) {
    mAcctList.append( account );
    emit accountAdded( account );
    account->installTimer();
  }
}

//-----------------------------------------------------------------------------
KMAccount* AccountManager::findByName(const QString &aName) const
{
  if ( aName.isEmpty() ) return 0;

  for ( AccountList::ConstIterator it( mAcctList.begin() ), end( mAcctList.end() ); it != end; ++it ) {
    if ( (*it)->name() == aName ) return (*it);
  }
  return 0;
}

//-----------------------------------------------------------------------------
KMAccount* AccountManager::find( const uint id ) const
{
  if (id == 0) return 0;
  for ( AccountList::ConstIterator it( mAcctList.begin() ), end( mAcctList.end() ); it != end; ++it ) {
    if ( (*it)->id() == id ) return (*it);
  }
  return 0;
}

//-----------------------------------------------------------------------------
KMAccount* AccountManager::first()
{
  if ( !mAcctList.empty() ) {
    mPtrListInterfaceProxyIterator = mAcctList.begin();
    return *mPtrListInterfaceProxyIterator;
  } else {
    return 0;
  }
}

//-----------------------------------------------------------------------------
KMAccount* AccountManager::next()
{
    ++mPtrListInterfaceProxyIterator;
    if ( mPtrListInterfaceProxyIterator == mAcctList.end() )
        return 0;
    else
        return *mPtrListInterfaceProxyIterator;
}

//-----------------------------------------------------------------------------
bool AccountManager::remove( KMAccount* acct )
{
  if( !acct )
    return false;
  mAcctList.removeAll( acct );
  emit accountRemoved( acct );
  return true;
}

//-----------------------------------------------------------------------------
void AccountManager::checkMail( bool _interactive )
{
  mNewMailArrived = false;

  if ( mAcctList.isEmpty() ) {
    KMessageBox::information( 0,i18n("You need to add an account in the network "
                    "section of the settings in order to receive mail.") );
    return;
  }
  mDisplaySummary = true;

  mTotalNewMailsArrived=0;
  mTotalNewInFolder.clear();

  for ( AccountList::Iterator it( mAcctList.begin() ), end( mAcctList.end() ); it != end; ++it ) {
    if ( !(*it)->checkExclude() )
      singleCheckMail( (*it), _interactive);
  }
}

//-----------------------------------------------------------------------------
void AccountManager::singleInvalidateIMAPFolders(KMAccount *account) {
  account->invalidateIMAPFolders();
}

void AccountManager::invalidateIMAPFolders()
{
  for ( AccountList::ConstIterator it( mAcctList.begin() ), end( mAcctList.end() ); it != end; ++it )
    singleInvalidateIMAPFolders( *it );
}

//-----------------------------------------------------------------------------
QStringList  AccountManager::getAccounts() const
{
  QStringList strList;
  for ( AccountList::ConstIterator it( mAcctList.begin() ), end( mAcctList.end() ); it != end; ++it ) {
    strList.append( (*it)->name() );
  }
  return strList;
}

//-----------------------------------------------------------------------------
void AccountManager::intCheckMail(int item, bool _interactive)
{
  mNewMailArrived = false;
  mTotalNewMailsArrived = 0;
  mTotalNewInFolder.clear();
  if ( KMAccount *acct = mAcctList[ item ] )
    singleCheckMail( acct, _interactive );
  mDisplaySummary = false;
}

//-----------------------------------------------------------------------------
void AccountManager::addToTotalNewMailCount( const QMap<QString, int> & newInFolder )
{
  for ( QMap<QString, int>::const_iterator it = newInFolder.begin();
        it != newInFolder.end(); ++it ) {
    mTotalNewMailsArrived += it.value();
    if ( !mTotalNewInFolder.contains( it.key() )  )
      mTotalNewInFolder[it.key()] = it.value();
    else
      mTotalNewInFolder[it.key()] += it.value();
  }
}

//-----------------------------------------------------------------------------
uint AccountManager::createId()
{
  QList<uint> usedIds;
  for ( AccountList::ConstIterator it( mAcctList.begin() ), end( mAcctList.end() ); it != end; ++it ) {
    usedIds << (*it)->id();
  }

  usedIds << 0; // 0 is default for unknown
  int newId;
  do
  {
    newId = KRandom::random();
  } while ( usedIds.contains(newId)  );

  return newId;
}

//-----------------------------------------------------------------------------
void AccountManager::cancelMailCheck()
{
  for ( AccountList::ConstIterator it( mAcctList.begin() ), end( mAcctList.end() ); it != end; ++it ) {
    (*it)->cancelMailCheck();
  }
}

//-----------------------------------------------------------------------------
void AccountManager::readPasswords()
{
  for ( AccountList::ConstIterator it( mAcctList.begin() ), end( mAcctList.end() ); it != end; ++it ) {
    NetworkAccount *acct = dynamic_cast<NetworkAccount*>( (*it) );
    if ( acct )
      acct->readPassword();
  }
}

#include "accountmanager.moc"
<|endoftext|>


<commit_before>/** -*- c++ -*-
 * progressdialog.cpp
 *
 *  Copyright (c) 2004 Till Adam <adam@kde.org>
 *  based on imapprogressdialog.cpp ,which is
 *  Copyright (c) 2002-2003 Klaralvdalens Datakonsult AB
 *
 *  This program is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; version 2 of the License
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 *
 *  In addition, as a special exception, the copyright holders give
 *  permission to link the code of this program with any edition of
 *  the Qt library by Trolltech AS, Norway (or with modified versions
 *  of Qt that use the same license as Qt), and distribute linked
 *  combinations including the two.  You must obey the GNU General
 *  Public License in all respects for all of the code used other than
 *  Qt.  If you modify this file, you may extend this exception to
 *  your version of the file, but you are not obligated to do so.  If
 *  you do not wish to do so, delete this exception statement from
 *  your version.
 */

#ifdef HAVE_CONFIG_H
#include <config.h>
#endif

#include <qlayout.h>
#include <qprogressbar.h>
#include <qtimer.h>
#include <qheader.h>
#include <qobject.h>

#include <kpushbutton.h>
#include <klocale.h>
#include <kdialog.h>
#include <kstdguiitem.h>
#include <kiconloader.h>
#include <kdebug.h>

#include "progressdialog.h"
#include "progressmanager.h"
using KMail::ProgressItem;
using KMail::ProgressManager;

namespace KMail {

TransactionItemListView::TransactionItemListView( QWidget * parent,
                                                  const char * name,
                                                  WFlags f )
    : QListView( parent, name, f ) {

    connect ( header(),SIGNAL( sizeChange ( int, int, int ) ),
              this, SLOT( slotAdjustGeometry() ) );
    connect ( header(),SIGNAL( indexChange ( int, int, int ) ),
              this, SLOT( slotAdjustGeometry() ) );
    connect ( this, SIGNAL( expanded( QListViewItem * ) ),
              this, SLOT( slotAdjustGeometry() ) );
    connect ( this, SIGNAL( collapsed( QListViewItem * ) ),
              this, SLOT( slotAdjustGeometry() ) );

}

void TransactionItemListView::resizeEvent( QResizeEvent* e )
{
  slotAdjustGeometry();
  QListView::resizeEvent( e );
}

void TransactionItemListView::slotAdjustGeometry() {
  for (QListViewItemIterator it( this ); it.current(); it++) {
    TransactionItem *i = static_cast<TransactionItem*>( it.current() );
    i->adjustGeometry();
  }
}

// ----------------------------------------------------------------------------

TransactionItem::TransactionItem ( QListViewItem* parent,
                                   ProgressItem *i )
  : QListViewItem( parent ), mCancelButton( 0 )
{
  init( i);
}

TransactionItem::TransactionItem( QListView* parent,
                                  QListViewItem* lastItem,
                                  ProgressItem *i )
  : QListViewItem( parent, lastItem ), mCancelButton( 0 )
{
  init( i );
}

void TransactionItem::init ( ProgressItem *item )
{
  mItem = item;
  mProgress = new QProgressBar( 100, listView()->viewport() );
  mProgress->setProgress( item->progress() );
  mProgress->show();
  if ( item->canBeCanceled() ) {
    mCancelButton = new QPushButton( SmallIcon( "cancel" ), QString::null,
                                     listView()->viewport() );
    mCancelButton->setSizePolicy( QSizePolicy( QSizePolicy::Minimum,
                                               QSizePolicy::Minimum ) );

    mCancelButton->show();
    connect ( mCancelButton, SIGNAL( clicked() ),
              this, SLOT( slotItemCanceled() ));

  }
  adjustGeometry();
  setText( 0, item->label() );
  setText( 4, item->status() );
  setSelectable( false );
}

TransactionItem::~TransactionItem()
{
  delete mCancelButton;
  delete mProgress;
}

void TransactionItem::setProgress( int progress )
{
  mProgress->setProgress( progress );
}

void TransactionItem::setStatus( const QString& status )
{
  setText( 3, status );
}

void TransactionItem::adjustGeometry()
{
  QRect r = listView()->itemRect( this );
  QHeader *h = listView()->header();
  if ( mCancelButton ) {
    r.setLeft( h->sectionPos( 1 ) - h->offset() );
    r.setWidth( h->sectionSize( 1 ));
    mCancelButton->setGeometry( r );
  }
  r.setLeft( h->sectionPos( 2 ) - h->offset() );
  r.setWidth( h->sectionSize( 2 ));
  mProgress->setGeometry( r );
}

void TransactionItem::slotItemCanceled()
{
  item()->setStatus( i18n("cancelling ... ") );
  item()->cancel();
}

ProgressDialog::ProgressDialog( QWidget* parent, const char* name, bool modal, WFlags fl )
    : QDialog( parent, name, modal, fl )
{
    setCaption( i18n("Progress") );
    resize( 600, 400 );

    QBoxLayout* topLayout = new QVBoxLayout( this, KDialog::marginHint(), KDialog::spacingHint(),
                                             "topLayout");

    mListView = new TransactionItemListView( this, "SyncEditorListView" );
    mListView->addColumn( i18n( "Transaction" ) );
    mListView->setColumnWidth( 0, 100 );
    mListView->setColumnWidthMode(0, QListView::Maximum);
    mListView->addColumn( QString::null );
    mListView->setColumnWidth( 1, 25 );
    mListView->addColumn( i18n( "Progress" ) );
    mListView->setColumnWidth( 2, 180 );
    mListView->addColumn( i18n( "Status" ) );
    mListView->setColumnWidth( 3, 100 );
    mListView->setColumnWidthMode(3, QListView::Maximum);
    mListView->setSorting( -1, false );

    mListView->setRootIsDecorated( true );

    topLayout->addWidget( mListView );

    QBoxLayout* bottomLayout = new QHBoxLayout( topLayout, KDialog::spacingHint(), "bottomLayout");
    bottomLayout->addStretch();

    KPushButton* pbClose = new KPushButton( KStdGuiItem::close(), this );
    bottomLayout->addWidget( pbClose );

    connect(pbClose, SIGNAL(clicked()), this, SLOT(close())  );

    /*
     * Get the singleton ProgressManager item which will inform us of
     * appearing and vanishing items.
     */
    ProgressManager *pm = ProgressManager::instance();
    connect ( pm, SIGNAL( progressItemAdded( ProgressItem* ) ),
              this, SLOT( slotTransactionAdded( ProgressItem* ) ) );
    connect ( pm, SIGNAL( progressItemCompleted( ProgressItem* ) ),
              this, SLOT( slotTransactionCompleted( ProgressItem* ) ) );
    connect ( pm, SIGNAL( progressItemProgress( ProgressItem*, unsigned int ) ),
              this, SLOT( slotTransactionProgress( ProgressItem*, unsigned int ) ) );
    connect ( pm, SIGNAL( progressItemStatus( ProgressItem*, const QString& ) ),
              this, SLOT( slotTransactionStatus( ProgressItem*, const QString& ) ) );
}

void ProgressDialog::clear()
{
   QListViewItem* item;
   while( ( item = mListView->firstChild() ) != 0 ) delete item;
   mPreviousItem = 0;
}

void ProgressDialog::closeEvent( QCloseEvent* e )
{
  e->accept();
  hide();
}

void ProgressDialog::showEvent( QShowEvent* e )
{
  mListView->slotAdjustGeometry();
  QDialog::showEvent( e );
}

/*
 *  Destructor
 */
ProgressDialog::~ProgressDialog()
{
    // no need to delete child widgets.
}

void ProgressDialog::slotTransactionAdded( ProgressItem *item )
{
   TransactionItem *parent = 0;
   TransactionItem *ti = 0;
   if ( item->parent() ) {
     parent = mTransactionsToListviewItems[ item->parent() ];
     ti = new TransactionItem( parent, item );
   } else {
     ti = new TransactionItem( mListView, mListView->lastItem(), item );
   }
   mTransactionsToListviewItems.replace( item, ti );
   // First item to appear, show.
   // FIXME Maybe it's better to only auto show if the dialog was timed out
   // and not closed by the user. dunno
   // if ( mTransactionsToListviewItems.size() == 1 ) show();
}

void ProgressDialog::slotTransactionCompleted( ProgressItem *item )
{
   TransactionItem *ti = mTransactionsToListviewItems[ item ];
   if ( ti ) {
     mTransactionsToListviewItems.remove( item );
     delete ti;
   }
   // This was the last item, hide.
   if ( mTransactionsToListviewItems.size() == 0 )
     QTimer::singleShot( 3000, this, SLOT( slotHide() ) );
}

void ProgressDialog::slotTransactionCanceled( ProgressItem * )
{
}

void ProgressDialog::slotTransactionProgress( ProgressItem *item,
                                              unsigned int progress )
{
   TransactionItem *ti = mTransactionsToListviewItems[ item ];
   if ( ti ) {
     ti->setProgress( progress );
   }
}

void ProgressDialog::slotTransactionStatus( ProgressItem *item,
                                            const QString& status )
{
   TransactionItem *ti = mTransactionsToListviewItems[ item ];
   if ( ti ) {
     ti->setStatus( status );
   }
}

void ProgressDialog::slotHide()
{
  // check if a new item showed up since we started the timer. If not, hide
  if ( mTransactionsToListviewItems.size() == 0 )
    hide();
}

}
#include "progressdialog.moc"
<commit_msg>Update the listview geometry when an item goes away.<commit_after>/** -*- c++ -*-
 * progressdialog.cpp
 *
 *  Copyright (c) 2004 Till Adam <adam@kde.org>
 *  based on imapprogressdialog.cpp ,which is
 *  Copyright (c) 2002-2003 Klaralvdalens Datakonsult AB
 *
 *  This program is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; version 2 of the License
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 *
 *  In addition, as a special exception, the copyright holders give
 *  permission to link the code of this program with any edition of
 *  the Qt library by Trolltech AS, Norway (or with modified versions
 *  of Qt that use the same license as Qt), and distribute linked
 *  combinations including the two.  You must obey the GNU General
 *  Public License in all respects for all of the code used other than
 *  Qt.  If you modify this file, you may extend this exception to
 *  your version of the file, but you are not obligated to do so.  If
 *  you do not wish to do so, delete this exception statement from
 *  your version.
 */

#ifdef HAVE_CONFIG_H
#include <config.h>
#endif

#include <qlayout.h>
#include <qprogressbar.h>
#include <qtimer.h>
#include <qheader.h>
#include <qobject.h>

#include <kpushbutton.h>
#include <klocale.h>
#include <kdialog.h>
#include <kstdguiitem.h>
#include <kiconloader.h>
#include <kdebug.h>

#include "progressdialog.h"
#include "progressmanager.h"
using KMail::ProgressItem;
using KMail::ProgressManager;

namespace KMail {

TransactionItemListView::TransactionItemListView( QWidget * parent,
                                                  const char * name,
                                                  WFlags f )
    : QListView( parent, name, f ) {

    connect ( header(),SIGNAL( sizeChange ( int, int, int ) ),
              this, SLOT( slotAdjustGeometry() ) );
    connect ( header(),SIGNAL( indexChange ( int, int, int ) ),
              this, SLOT( slotAdjustGeometry() ) );
    connect ( this, SIGNAL( expanded( QListViewItem * ) ),
              this, SLOT( slotAdjustGeometry() ) );
    connect ( this, SIGNAL( collapsed( QListViewItem * ) ),
              this, SLOT( slotAdjustGeometry() ) );

}

void TransactionItemListView::resizeEvent( QResizeEvent* e )
{
  slotAdjustGeometry();
  QListView::resizeEvent( e );
}

void TransactionItemListView::slotAdjustGeometry() {
  for (QListViewItemIterator it( this ); it.current(); it++) {
    TransactionItem *i = static_cast<TransactionItem*>( it.current() );
    i->adjustGeometry();
  }
}

// ----------------------------------------------------------------------------

TransactionItem::TransactionItem ( QListViewItem* parent,
                                   ProgressItem *i )
  : QListViewItem( parent ), mCancelButton( 0 )
{
  init( i);
}

TransactionItem::TransactionItem( QListView* parent,
                                  QListViewItem* lastItem,
                                  ProgressItem *i )
  : QListViewItem( parent, lastItem ), mCancelButton( 0 )
{
  init( i );
}

void TransactionItem::init ( ProgressItem *item )
{
  mItem = item;
  mProgress = new QProgressBar( 100, listView()->viewport() );
  mProgress->setProgress( item->progress() );
  mProgress->show();
  if ( item->canBeCanceled() ) {
    mCancelButton = new QPushButton( SmallIcon( "cancel" ), QString::null,
                                     listView()->viewport() );
    mCancelButton->setSizePolicy( QSizePolicy( QSizePolicy::Minimum,
                                               QSizePolicy::Minimum ) );

    mCancelButton->show();
    connect ( mCancelButton, SIGNAL( clicked() ),
              this, SLOT( slotItemCanceled() ));

  }
  adjustGeometry();
  setText( 0, item->label() );
  setText( 4, item->status() );
  setSelectable( false );
}

TransactionItem::~TransactionItem()
{
  delete mCancelButton;
  delete mProgress;
}

void TransactionItem::setProgress( int progress )
{
  mProgress->setProgress( progress );
}

void TransactionItem::setStatus( const QString& status )
{
  setText( 3, status );
}

void TransactionItem::adjustGeometry()
{
  QRect r = listView()->itemRect( this );
  QHeader *h = listView()->header();
  if ( mCancelButton ) {
    r.setLeft( h->sectionPos( 1 ) - h->offset() );
    r.setWidth( h->sectionSize( 1 ));
    mCancelButton->setGeometry( r );
  }
  r.setLeft( h->sectionPos( 2 ) - h->offset() );
  r.setWidth( h->sectionSize( 2 ));
  mProgress->setGeometry( r );
}

void TransactionItem::slotItemCanceled()
{
  item()->setStatus( i18n("cancelling ... ") );
  item()->cancel();
}

ProgressDialog::ProgressDialog( QWidget* parent, const char* name, bool modal, WFlags fl )
    : QDialog( parent, name, modal, fl )
{
    setCaption( i18n("Progress") );
    resize( 600, 400 );

    QBoxLayout* topLayout = new QVBoxLayout( this, KDialog::marginHint(), KDialog::spacingHint(),
                                             "topLayout");

    mListView = new TransactionItemListView( this, "SyncEditorListView" );
    mListView->addColumn( i18n( "Transaction" ) );
    mListView->setColumnWidth( 0, 100 );
    mListView->setColumnWidthMode(0, QListView::Maximum);
    mListView->addColumn( QString::null );
    mListView->setColumnWidth( 1, 25 );
    mListView->addColumn( i18n( "Progress" ) );
    mListView->setColumnWidth( 2, 180 );
    mListView->addColumn( i18n( "Status" ) );
    mListView->setColumnWidth( 3, 100 );
    mListView->setColumnWidthMode(3, QListView::Maximum);
    mListView->setSorting( -1, false );

    mListView->setRootIsDecorated( true );

    topLayout->addWidget( mListView );

    QBoxLayout* bottomLayout = new QHBoxLayout( topLayout, KDialog::spacingHint(), "bottomLayout");
    bottomLayout->addStretch();

    KPushButton* pbClose = new KPushButton( KStdGuiItem::close(), this );
    bottomLayout->addWidget( pbClose );

    connect(pbClose, SIGNAL(clicked()), this, SLOT(close())  );

    /*
     * Get the singleton ProgressManager item which will inform us of
     * appearing and vanishing items.
     */
    ProgressManager *pm = ProgressManager::instance();
    connect ( pm, SIGNAL( progressItemAdded( ProgressItem* ) ),
              this, SLOT( slotTransactionAdded( ProgressItem* ) ) );
    connect ( pm, SIGNAL( progressItemCompleted( ProgressItem* ) ),
              this, SLOT( slotTransactionCompleted( ProgressItem* ) ) );
    connect ( pm, SIGNAL( progressItemProgress( ProgressItem*, unsigned int ) ),
              this, SLOT( slotTransactionProgress( ProgressItem*, unsigned int ) ) );
    connect ( pm, SIGNAL( progressItemStatus( ProgressItem*, const QString& ) ),
              this, SLOT( slotTransactionStatus( ProgressItem*, const QString& ) ) );
}

void ProgressDialog::clear()
{
   QListViewItem* item;
   while( ( item = mListView->firstChild() ) != 0 ) delete item;
   mPreviousItem = 0;
}

void ProgressDialog::closeEvent( QCloseEvent* e )
{
  e->accept();
  hide();
}

void ProgressDialog::showEvent( QShowEvent* e )
{
  mListView->slotAdjustGeometry();
  QDialog::showEvent( e );
}

/*
 *  Destructor
 */
ProgressDialog::~ProgressDialog()
{
    // no need to delete child widgets.
}

void ProgressDialog::slotTransactionAdded( ProgressItem *item )
{
   TransactionItem *parent = 0;
   TransactionItem *ti = 0;
   if ( item->parent() ) {
     parent = mTransactionsToListviewItems[ item->parent() ];
     ti = new TransactionItem( parent, item );
   } else {
     ti = new TransactionItem( mListView, mListView->lastItem(), item );
   }
   mTransactionsToListviewItems.replace( item, ti );
   // First item to appear, show.
   // FIXME Maybe it's better to only auto show if the dialog was timed out
   // and not closed by the user. dunno
   // if ( mTransactionsToListviewItems.size() == 1 ) show();
}

void ProgressDialog::slotTransactionCompleted( ProgressItem *item )
{
   TransactionItem *ti = mTransactionsToListviewItems[ item ];
   if ( ti ) {
     mTransactionsToListviewItems.remove( item );
     delete ti;
   }
   mListView->slotAdjustGeometry();
   // This was the last item, hide.
   if ( mTransactionsToListviewItems.size() == 0 )
     QTimer::singleShot( 3000, this, SLOT( slotHide() ) );
}

void ProgressDialog::slotTransactionCanceled( ProgressItem * )
{
}

void ProgressDialog::slotTransactionProgress( ProgressItem *item,
                                              unsigned int progress )
{
   TransactionItem *ti = mTransactionsToListviewItems[ item ];
   if ( ti ) {
     ti->setProgress( progress );
   }
}

void ProgressDialog::slotTransactionStatus( ProgressItem *item,
                                            const QString& status )
{
   TransactionItem *ti = mTransactionsToListviewItems[ item ];
   if ( ti ) {
     ti->setStatus( status );
   }
}

void ProgressDialog::slotHide()
{
  // check if a new item showed up since we started the timer. If not, hide
  if ( mTransactionsToListviewItems.size() == 0 )
    hide();
}

}
#include "progressdialog.moc"
<|endoftext|>