<commit_before>#include <algorithm>

#include <boost/filesystem.hpp>

#include <QMessageBox>
#include <QFileDialog>
#include <QSqlTableModel>
#include <QProgressDialog>

#include "image_annotation.h"
#include "database_info.h"
#include "mainwindow.h"
#include "ui_mainwindow.h"

namespace fish_annotator { namespace db_uploader {

namespace fs = boost::filesystem;

namespace { //anonymous

static const std::vector<std::string> kDirExtensions = {
  ".jpg", ".png", ".bmp", ".tif", ".jpeg",
  ".JPG", ".PNG", ".BMP", ".TIF", ".JPEG"};

} // anonymous namespace

MainWindow::MainWindow(QWidget *parent)
  : ui_(new Ui::MainWindow)
  , input_db_(new QSqlDatabase())
  , output_db_(new QSqlDatabase()) {
  ui_->setupUi(this);
  setWindowTitle("Database Uploader");
#ifdef _WIN32
  setWindowIcon(QIcon(":/icons/cvision/cvision_no_text.ico"));
#endif
  fs::path current_path(QDir::currentPath().toStdString());
  fs::path default_input = current_path / fs::path("default.input_database");
  fs::path default_output = current_path / fs::path("default.output_database");
  if(fs::exists(default_input)) {
    DatabaseInfo input;
    deserialize(input, default_input.string());
    ui_->inputServer->setText(input.getServer().c_str());
    ui_->inputDatabase->setText(input.getDatabase().c_str());
    ui_->inputUsername->setText(input.getUsername().c_str());
  }
  if(fs::exists(default_output)) {
    DatabaseInfo output;
    deserialize(output, default_output.string());
    ui_->outputServer->setText(output.getServer().c_str());
    ui_->outputDatabase->setText(output.getDatabase().c_str());
    ui_->outputUsername->setText(output.getUsername().c_str());
  }
}

void MainWindow::on_connectInputDb_clicked() {
  ui_->inputDbStatus->setText("Attempting to connect...");
  ui_->inputDbStatus->repaint();
  *input_db_ = QSqlDatabase::addDatabase("QODBC3", "input");
  if(input_db_->isDriverAvailable("QODBC") == false) {
    QMessageBox err;
    err.critical(0, "Error", "ODBC driver is not available!");
  }
  input_db_->setDatabaseName(
      "DRIVER={SQL Server};SERVER={" + ui_->inputServer->text() +
      "};DATABASE=" + ui_->inputDatabase->text() +
      ";Trusted_Connection=no;user_id=" + ui_->inputUsername->text() +
      ";password=" + ui_->inputPassword->text() + ";WSID=.");
  if(input_db_->isValid() == false) {
    ui_->inputDbStatus->setText("Not connected");
    QMessageBox err;
    err.critical(0, "Error", "Not a valid database!");
  }
  if(input_db_->open() == false) {
    ui_->inputDbStatus->setText("Not connected");
    QMessageBox err;
    err.critical(0, "Error", input_db_->lastError().text());
  }
  else {
    ui_->inputDbStatus->setText("Connected");
  }
  if(output_db_->isOpen() == true && input_db_->isOpen() == true) {
    ui_->upload->setEnabled(true);
  }
}

void MainWindow::on_connectOutputDb_clicked() {
  ui_->outputDbStatus->setText("Attempting to connect...");
  ui_->outputDbStatus->repaint();
  *output_db_ = QSqlDatabase::addDatabase("QODBC3", "output");
  if(output_db_->isDriverAvailable("QODBC") == false) {
    QMessageBox err;
    err.critical(0, "Error", "ODBC driver is not available!");
  }
  output_db_->setDatabaseName(
      "DRIVER={SQL Server};SERVER={" + ui_->outputServer->text() +
      "};DATABASE=" + ui_->outputDatabase->text() +
      ";Trusted_Connection=no;user_id=" + ui_->outputUsername->text() +
      ";password=" + ui_->outputPassword->text() + ";WSID=.");
  if(output_db_->isValid() == false) {
    ui_->outputDbStatus->setText("Not connected");
    QMessageBox err;
    err.critical(0, "Error", "Not a valid database!");
  }
  if(output_db_->open() == false) {
    ui_->outputDbStatus->setText("Not connected");
    QMessageBox err;
    err.critical(0, "Error", output_db_->lastError().text());
  }
  else {
    ui_->outputDbStatus->setText("Connected");
  }
  if(output_db_->isOpen() == true && input_db_->isOpen() == true) {
    ui_->upload->setEnabled(true);
  }
}

void MainWindow::on_browseImageDir_clicked() {
  ui_->imageDirectory->setText(QFileDialog::getExistingDirectory(
    this, "Select annotated image directory"));
}

void MainWindow::on_cancel_clicked() {
  QApplication::quit();
}

void MainWindow::on_upload_clicked() {
  QString image_dir = ui_->imageDirectory->text();
  std::vector<boost::filesystem::path> image_files;
  fs::directory_iterator dir_it(image_dir.toStdString());
  fs::directory_iterator dir_end;
  for(; dir_it != dir_end; ++dir_it) {
    fs::path ext(dir_it->path().extension());
    for(auto &ok_ext : kDirExtensions) {
      if(ext == ok_ext) {
        image_files.push_back(dir_it->path());
      }
    }
  }
  std::sort(image_files.begin(), image_files.end());
  image_annotator::ImageAnnotationList annotations;
  annotations.read(image_files);
  int num_img = static_cast<int>(image_files.size());
  QSqlTableModel input_model(this, *input_db_);
  QSqlTableModel output_model(this, *output_db_);
  /// @TODO Parse metadata from input database.
  output_model.setTable("dbo.measurements_data");
  output_model.setEditStrategy(QSqlTableModel::OnManualSubmit);
  output_model.select();
  QProgressDialog progress(
      "Uploading annotations...",
      "Abort",
      0,
      num_img,
      this,
      Qt::Window | Qt::WindowTitleHint | Qt::CustomizeWindowHint);
  progress.setCancelButton(0);
  progress.setWindowTitle("Uploading Annotations");
  progress.setMinimumDuration(10);
  for(int img_index = 0; img_index < num_img; ++img_index) {
    progress.setValue(img_index);
    if(progress.wasCanceled()) {
      break;
    }
    auto ann = annotations.getImageAnnotations(image_files[img_index]);
    int num_ann = static_cast<int>(ann.size());
    for(int ai = 0; ai < num_ann; ++ai) {
      auto row_count = output_model.rowCount();
      if(output_model.insertRows(row_count, 1) == false) {
        progress.close();
        QMessageBox err;
        err.critical(0, "Error", "Unable to insert row into table.");
        break;
      }
      // surveyyear
      output_model.setData(output_model.index(row_count, 0), "");
      // areashortname
      output_model.setData(output_model.index(row_count, 1), "");
      // areacontrolpk
      output_model.setData(output_model.index(row_count, 2), "");
      // cameraControlIPK
      output_model.setData(output_model.index(row_count, 3), "");
      // station
      output_model.setData(output_model.index(row_count, 4), "");
      // quadrat
      output_model.setData(output_model.index(row_count, 5), "");
      // measurement
      double meas = 0.0;
      if(ann[ai]->type_ == kLine) {
        double xdiff = ann[ai]->area_.x - ann[ai]->area_.w;
        double ydiff = ann[ai]->area_.y - ann[ai]->area_.h;
        meas = std::sqrt(xdiff * xdiff + ydiff * ydiff);
      }
      output_model.setData(output_model.index(row_count, 6),
          std::to_string(meas).c_str());
      // latitude
      output_model.setData(output_model.index(row_count, 7), "");
      // longitude
      output_model.setData(output_model.index(row_count, 8), "");
    }
    if(output_model.submitAll() == true) {
      output_model.database().commit();
    }
    else {
      output_model.database().rollback();
      progress.close();
      QMessageBox err;
      err.critical(0, "Error", output_model.lastError().text());
      break;
    }
  }
  progress.setValue(num_img);
}

#include "moc_mainwindow.cpp"

}} // namespace fish_annotator::db_uploader

<commit_msg>Update database table name, columns, and types<commit_after>#include <algorithm>

#include <boost/filesystem.hpp>

#include <QMessageBox>
#include <QFileDialog>
#include <QSqlTableModel>
#include <QProgressDialog>

#include "image_annotation.h"
#include "database_info.h"
#include "mainwindow.h"
#include "ui_mainwindow.h"

namespace fish_annotator { namespace db_uploader {

namespace fs = boost::filesystem;

namespace { //anonymous

static const std::vector<std::string> kDirExtensions = {
  ".jpg", ".png", ".bmp", ".tif", ".jpeg",
  ".JPG", ".PNG", ".BMP", ".TIF", ".JPEG"};

} // anonymous namespace

MainWindow::MainWindow(QWidget *parent)
  : ui_(new Ui::MainWindow)
  , input_db_(new QSqlDatabase())
  , output_db_(new QSqlDatabase()) {
  ui_->setupUi(this);
  setWindowTitle("Database Uploader");
#ifdef _WIN32
  setWindowIcon(QIcon(":/icons/cvision/cvision_no_text.ico"));
#endif
  fs::path current_path(QDir::currentPath().toStdString());
  fs::path default_input = current_path / fs::path("default.input_database");
  fs::path default_output = current_path / fs::path("default.output_database");
  if(fs::exists(default_input)) {
    DatabaseInfo input;
    deserialize(input, default_input.string());
    ui_->inputServer->setText(input.getServer().c_str());
    ui_->inputDatabase->setText(input.getDatabase().c_str());
    ui_->inputUsername->setText(input.getUsername().c_str());
  }
  if(fs::exists(default_output)) {
    DatabaseInfo output;
    deserialize(output, default_output.string());
    ui_->outputServer->setText(output.getServer().c_str());
    ui_->outputDatabase->setText(output.getDatabase().c_str());
    ui_->outputUsername->setText(output.getUsername().c_str());
  }
}

void MainWindow::on_connectInputDb_clicked() {
  ui_->inputDbStatus->setText("Attempting to connect...");
  ui_->inputDbStatus->repaint();
  *input_db_ = QSqlDatabase::addDatabase("QODBC3", "input");
  if(input_db_->isDriverAvailable("QODBC") == false) {
    QMessageBox err;
    err.critical(0, "Error", "ODBC driver is not available!");
  }
  input_db_->setDatabaseName(
      "DRIVER={SQL Server};SERVER={" + ui_->inputServer->text() +
      "};DATABASE=" + ui_->inputDatabase->text() +
      ";Trusted_Connection=no;user_id=" + ui_->inputUsername->text() +
      ";password=" + ui_->inputPassword->text() + ";WSID=.");
  if(input_db_->isValid() == false) {
    ui_->inputDbStatus->setText("Not connected");
    QMessageBox err;
    err.critical(0, "Error", "Not a valid database!");
  }
  if(input_db_->open() == false) {
    ui_->inputDbStatus->setText("Not connected");
    QMessageBox err;
    err.critical(0, "Error", input_db_->lastError().text());
  }
  else {
    ui_->inputDbStatus->setText("Connected");
  }
  if(output_db_->isOpen() == true && input_db_->isOpen() == true) {
    ui_->upload->setEnabled(true);
  }
}

void MainWindow::on_connectOutputDb_clicked() {
  ui_->outputDbStatus->setText("Attempting to connect...");
  ui_->outputDbStatus->repaint();
  *output_db_ = QSqlDatabase::addDatabase("QODBC3", "output");
  if(output_db_->isDriverAvailable("QODBC") == false) {
    QMessageBox err;
    err.critical(0, "Error", "ODBC driver is not available!");
  }
  output_db_->setDatabaseName(
      "DRIVER={SQL Server};SERVER={" + ui_->outputServer->text() +
      "};DATABASE=" + ui_->outputDatabase->text() +
      ";Trusted_Connection=no;user_id=" + ui_->outputUsername->text() +
      ";password=" + ui_->outputPassword->text() + ";WSID=.");
  if(output_db_->isValid() == false) {
    ui_->outputDbStatus->setText("Not connected");
    QMessageBox err;
    err.critical(0, "Error", "Not a valid database!");
  }
  if(output_db_->open() == false) {
    ui_->outputDbStatus->setText("Not connected");
    QMessageBox err;
    err.critical(0, "Error", output_db_->lastError().text());
  }
  else {
    ui_->outputDbStatus->setText("Connected");
  }
  if(output_db_->isOpen() == true && input_db_->isOpen() == true) {
    ui_->upload->setEnabled(true);
  }
}

void MainWindow::on_browseImageDir_clicked() {
  ui_->imageDirectory->setText(QFileDialog::getExistingDirectory(
    this, "Select annotated image directory"));
}

void MainWindow::on_cancel_clicked() {
  QApplication::quit();
}

void MainWindow::on_upload_clicked() {
  QString image_dir = ui_->imageDirectory->text();
  std::vector<boost::filesystem::path> image_files;
  fs::directory_iterator dir_it(image_dir.toStdString());
  fs::directory_iterator dir_end;
  for(; dir_it != dir_end; ++dir_it) {
    fs::path ext(dir_it->path().extension());
    for(auto &ok_ext : kDirExtensions) {
      if(ext == ok_ext) {
        image_files.push_back(dir_it->path());
      }
    }
  }
  std::sort(image_files.begin(), image_files.end());
  image_annotator::ImageAnnotationList annotations;
  annotations.read(image_files);
  int num_img = static_cast<int>(image_files.size());
  QSqlTableModel input_model(this, *input_db_);
  QSqlTableModel output_model(this, *output_db_);
  /// @TODO Parse metadata from input database.
  output_model.setTable("dbo.STAGING_MEASUREMENTS");
  output_model.setEditStrategy(QSqlTableModel::OnManualSubmit);
  output_model.select();
  QProgressDialog progress(
      "Uploading annotations...",
      "Abort",
      0,
      num_img,
      this,
      Qt::Window | Qt::WindowTitleHint | Qt::CustomizeWindowHint);
  progress.setCancelButton(0);
  progress.setWindowTitle("Uploading Annotations");
  progress.setMinimumDuration(10);
  for(int img_index = 0; img_index < num_img; ++img_index) {
    progress.setValue(img_index);
    if(progress.wasCanceled()) {
      break;
    }
    auto ann = annotations.getImageAnnotations(image_files[img_index]);
    int num_ann = static_cast<int>(ann.size());
    for(int ai = 0; ai < num_ann; ++ai) {
      auto row_count = output_model.rowCount();
      if(output_model.insertRows(row_count, 1) == false) {
        progress.close();
        QMessageBox err;
        err.critical(0, "Error", "Unable to insert row into table.");
        break;
      }
      // measurementPK
      output_model.setData(output_model.index(row_count, 0), 0);
      // measurementControlPK
      output_model.setData(output_model.index(row_count, 1), 0);
      // updatedPK
      output_model.setData(output_model.index(row_count, 2), 0);
      // dfo
      output_model.setData(output_model.index(row_count, 3), 0);
      // measurement
      double meas = 0.0;
      if(ann[ai]->type_ == kLine) {
        double xdiff = ann[ai]->area_.x - ann[ai]->area_.w;
        double ydiff = ann[ai]->area_.y - ann[ai]->area_.h;
        meas = std::sqrt(xdiff * xdiff + ydiff * ydiff);
      }
      output_model.setData(output_model.index(row_count, 4), meas);
      // areacontrolpk
      output_model.setData(output_model.index(row_count, 5), 0);
      // station
      output_model.setData(output_model.index(row_count, 6), "---");
      // quadrat
      output_model.setData(output_model.index(row_count, 7), 0);
      // cameracontrolpk
      output_model.setData(output_model.index(row_count, 8), 0);
      // area
      output_model.setData(output_model.index(row_count, 9), "");
      // year
      output_model.setData(output_model.index(row_count, 10), "2017");
    }
    if(output_model.submitAll() == true) {
      output_model.database().commit();
    }
    else {
      output_model.database().rollback();
      progress.close();
      QMessageBox err;
      err.critical(0, "Error", output_model.lastError().text());
      break;
    }
  }
  progress.setValue(num_img);
}

#include "moc_mainwindow.cpp"

}} // namespace fish_annotator::db_uploader

<|endoftext|>


<commit_before>#include <iostream>

#include <boost/program_options.hpp>
#include <boost/algorithm/string.hpp> //case insensitve string comparison

#include "dirMultiNaiveBayes.hpp"
#include "niwBaseMeasure.hpp"
#include "typedef.h"
#include "timer.hpp"

namespace po = boost::program_options;
using boost::iequals;

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

  // Declare the supported options.
  po::options_description desc("Allowed options");
  desc.add_options()
    ("help,h", "produce help message")
	("K,K", po::value<int>(), "number of initial clusters ")
	("T,T", po::value<int>(), "iterations")
	("v,v", po::value<bool>(), "verbose output")
    ("input,i", po::value<string>(),
      "path to input dataset .csv file (rows: dimensions; cols: different "
      "datapoints)")
    ("output,o", po::value<string>(),
      "path to output labels .csv file (rows: time; cols: different "
      "datapoints)")
	("b,b", po::value<std::vector<string> >()->multitoken(),
	  "base class to use for components (must be the same size as M in the data). "
	  "valid values: NiwSampled, NiwTangent, [default: NiwSampled].");

    po::variables_map vm;
	po::store(po::parse_command_line(argc, argv, desc), vm);
	po::notify(vm);

	if (vm.count("help")) {
		cout << desc << "\n";
		return 1;
	}

	uint NumObs = 2; //num observations (number of components of multi-dimention data)
	uint K=2; //num clusters
	uint T=100; //iterations
	uint M=2; //num docs

	vector<uint> N(NumObs, 100) ; //num data points (total)
	vector<uint> D(NumObs, 2);  //dimention of data
	vector<string> baseDist; //base distributions for each component

	bool verbose = false;

	if (vm.count("K"))
		K = vm["K"].as<int>();
	if (vm.count("T"))
		T = vm["T"].as<int>();
	if (vm.count("v"))
		verbose = vm["v"].as<bool>();

	string pathIn ="";
	string pathOut ="";
	if(vm.count("input"))
		pathIn = vm["input"].as<string>();
	if(vm.count("output"))
		pathOut= vm["output"].as<string>();

	vector<vector< Matrix<double, Dynamic, Dynamic> > > x;
	x.reserve(NumObs);
	if (!pathIn.compare(""))
	{
		cout<<"making some data up" <<endl;
		for (uint n=0; n<NumObs; ++n)
		{
			vector<Matrix<double, Dynamic, Dynamic> > temp;
			temp.reserve(M);
			uint Ndoc=M;
			uint Nword=int(N[n]/M);
			for(uint i=0; i<Ndoc; ++i)
			{
				MatrixXd  xdoc(D[n],Nword);
				for(uint w=0; w<Nword; ++w)
				{
					if(i<Ndoc/2)
						xdoc.col(w) <<  (NumObs*(n%2))*VectorXd::Ones(D[n]);
					else
						xdoc.col(w) <<  (NumObs*(n%2)+1)*VectorXd::Ones(D[n]);
				}

				temp.push_back(xdoc);
			}
			x.push_back(temp);
		}

	}else{
		cout<<"loading data from "<<pathIn<<endl;
		ifstream fin(pathIn.data(),ifstream::in);

		if (!fin.good()) {
			cout << "could not open file...returning" << endl;
			return(-1);
		}

		//read data
		fin>>NumObs;
		N.clear(); N.reserve(NumObs);
		D.clear(); D.reserve(NumObs);

		for(uint32_t n=0; n<NumObs; ++n)
		{
			vector< Matrix<double, Dynamic, Dynamic> > xiter;
			uint Niter, Diter;

			fin>>Niter;
			fin>>M;
			fin>>Diter;

			N.push_back(Niter);
			D.push_back(Diter);

			MatrixXd data(Diter,Niter);
			VectorXu words(M);

			for (uint j=0; j<M; ++j)
				fin>>words(j);

			for (uint j=1; j<(Diter+1); ++j)
				for (uint i=0; i<Niter; ++i)
					fin>>data(j-1,i);

			uint count = 0;
			for (uint j=0; j<M; ++j)
			{
				xiter.push_back(data.middleCols(count,words[j]));
				count+=words[j];
			}
			x.push_back(xiter);
		}
		fin.close();
	}

	if(vm.count("b")) {
		baseDist.clear();
		baseDist = vm["b"].as<vector<string>>();

		if(uint(baseDist.size())!=NumObs) {
			cerr << "Error specified number of base distributions not equal number of data components" << endl;
			cerr << "#bases =" << baseDist.size() << ", #data components=" << NumObs <<  "." << endl;
			cerr << "exiting" << endl;
			return(-1);
		}

	} else {
		baseDist.clear();
		baseDist = vector<string>(NumObs, "NiwSampled");
	}

	VectorXd alpha = 10.0*VectorXd::Ones(K);

	boost::mt19937 rndGen(9191);

	Dir<Catd,double> dir(alpha,&rndGen);
	vector<boost::shared_ptr<BaseMeasure<double> > > niwSampled;
	niwSampled.reserve(NumObs);

	//creates thetas
	for(uint m=0;m<NumObs ; ++m)
	{
		if(iequals(baseDist[m], "NiwSampled")) { //sampled normal inversed wishart
			double nu = D[m]+1;
			double kappa = D[m]+1;
			MatrixXd Delta = 0.1*MatrixXd::Identity(D[m],D[m]);
			Delta *= nu;
			VectorXd theta = VectorXd::Zero(D[m]);

			NIW<double> niw(Delta,theta,nu,kappa,&rndGen);
			boost::shared_ptr<NiwSampled<double> > tempBase( new NiwSampled<double>(niw));
			niwSampled.push_back(boost::shared_ptr<BaseMeasure<double> >(tempBase));

		} else if(iequals(baseDist[m], "NiwTangent")) {
			cerr << "NiwTangent base not coded yet... fix me" << endl;
			return(-1);

		} else {
			cerr << "error with base distributions (check help) ... returning." << endl;
			return(-1);
		}
	}

	Timer tlocal;
	tlocal.tic();

	DirMultiNaiveBayes<double> naive_samp(dir,niwSampled);

	cout << "multiObsNaiveBayesian Clustering:" << endl;
	cout << "Ndocs=" << M << endl;
	cout << "NumComp=" << NumObs << endl;
	cout << "NumData,Dim= ";
	for(uint n=0; n<NumObs; ++n)
		cout << "[" << N[n] << ", " << D[n] << "]; ";
	cout << endl;

	cout << "Num Cluster = " << K << ", (" << T << " iterations)." << endl;

	naive_samp.initialize( x );
	naive_samp.inferAll(T,verbose);

	if (pathOut.compare(""))
	{
		ofstream fout(pathOut.data(),ofstream::out);

		streambuf *coutbuf = std::cout.rdbuf(); //save old cout buffer
		cout.rdbuf(fout.rdbuf()); //redirect std::cout to fout1 buffer

			naive_samp.dump(fout,fout);

		std::cout.rdbuf(coutbuf); //reset to standard output again

		fout.close();
	}

	tlocal.displayElapsedTimeAuto();
	return(0);

};
<commit_msg>minor linux fix<commit_after>#include <iostream>

#include <boost/program_options.hpp>
#include <boost/algorithm/string.hpp> //case insensitve string comparison

#include "dirMultiNaiveBayes.hpp"
#include "niwBaseMeasure.hpp"
#include "typedef.h"
#include "timer.hpp"

namespace po = boost::program_options;
using boost::iequals;

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

  // Declare the supported options.
  po::options_description desc("Allowed options");
  desc.add_options()
    ("help,h", "produce help message")
	("K,K", po::value<int>(), "number of initial clusters ")
	("T,T", po::value<int>(), "iterations")
	("v,v", po::value<bool>(), "verbose output")
    ("input,i", po::value<string>(),
      "path to input dataset .csv file (rows: dimensions; cols: different "
      "datapoints)")
    ("output,o", po::value<string>(),
      "path to output labels .csv file (rows: time; cols: different "
      "datapoints)")
	("b,b", po::value<std::vector<string> >()->multitoken(),
	  "base class to use for components (must be the same size as M in the data). "
	  "valid values: NiwSampled, NiwTangent, [default: NiwSampled].");

    po::variables_map vm;
	po::store(po::parse_command_line(argc, argv, desc), vm);
	po::notify(vm);

	if (vm.count("help")) {
		cout << desc << "\n";
		return 1;
	}

	uint NumObs = 2; //num observations (number of components of multi-dimention data)
	uint K=2; //num clusters
	uint T=100; //iterations
	uint M=2; //num docs

	vector<uint> N(NumObs, 100) ; //num data points (total)
	vector<uint> D(NumObs, 2);  //dimention of data
	vector<string> baseDist; //base distributions for each component

	bool verbose = false;

	if (vm.count("K"))
		K = vm["K"].as<int>();
	if (vm.count("T"))
		T = vm["T"].as<int>();
	if (vm.count("v"))
		verbose = vm["v"].as<bool>();

	string pathIn ="";
	string pathOut ="";
	if(vm.count("input"))
		pathIn = vm["input"].as<string>();
	if(vm.count("output"))
		pathOut= vm["output"].as<string>();

	vector<vector< Matrix<double, Dynamic, Dynamic> > > x;
	x.reserve(NumObs);
	if (!pathIn.compare(""))
	{
		cout<<"making some data up" <<endl;
		for (uint n=0; n<NumObs; ++n)
		{
			vector<Matrix<double, Dynamic, Dynamic> > temp;
			temp.reserve(M);
			uint Ndoc=M;
			uint Nword=int(N[n]/M);
			for(uint i=0; i<Ndoc; ++i)
			{
				MatrixXd  xdoc(D[n],Nword);
				for(uint w=0; w<Nword; ++w)
				{
					if(i<Ndoc/2)
						xdoc.col(w) <<  (NumObs*(n%2))*VectorXd::Ones(D[n]);
					else
						xdoc.col(w) <<  (NumObs*(n%2)+1)*VectorXd::Ones(D[n]);
				}

				temp.push_back(xdoc);
			}
			x.push_back(temp);
		}

	}else{
		cout<<"loading data from "<<pathIn<<endl;
		ifstream fin(pathIn.data(),ifstream::in);

		if (!fin.good()) {
			cout << "could not open file...returning" << endl;
			return(-1);
		}

		//read data
		fin>>NumObs;
		N.clear(); N.reserve(NumObs);
		D.clear(); D.reserve(NumObs);

		for(uint32_t n=0; n<NumObs; ++n)
		{
			vector< Matrix<double, Dynamic, Dynamic> > xiter;
			uint Niter, Diter;

			fin>>Niter;
			fin>>M;
			fin>>Diter;

			N.push_back(Niter);
			D.push_back(Diter);

			MatrixXd data(Diter,Niter);
			VectorXu words(M);

			for (uint j=0; j<M; ++j)
				fin>>words(j);

			for (uint j=1; j<(Diter+1); ++j)
				for (uint i=0; i<Niter; ++i)
					fin>>data(j-1,i);

			uint count = 0;
			for (uint j=0; j<M; ++j)
			{
				xiter.push_back(data.middleCols(count,words[j]));
				count+=words[j];
			}
			x.push_back(xiter);
		}
		fin.close();
	}

	if(vm.count("b")) {
		baseDist.clear();
		baseDist = vm["b"].as<vector<string> >();

		if(uint(baseDist.size())!=NumObs) {
			cerr << "Error specified number of base distributions not equal number of data components" << endl;
			cerr << "#bases =" << baseDist.size() << ", #data components=" << NumObs <<  "." << endl;
			cerr << "exiting" << endl;
			return(-1);
		}

	} else {
		baseDist.clear();
		baseDist = vector<string>(NumObs, "NiwSampled");
	}

	VectorXd alpha = 10.0*VectorXd::Ones(K);

	boost::mt19937 rndGen(9191);

	Dir<Catd,double> dir(alpha,&rndGen);
	vector<boost::shared_ptr<BaseMeasure<double> > > niwSampled;
	niwSampled.reserve(NumObs);

	//creates thetas
	for(uint m=0;m<NumObs ; ++m)
	{
		if(iequals(baseDist[m], "NiwSampled")) { //sampled normal inversed wishart
			double nu = D[m]+1;
			double kappa = D[m]+1;
			MatrixXd Delta = 0.1*MatrixXd::Identity(D[m],D[m]);
			Delta *= nu;
			VectorXd theta = VectorXd::Zero(D[m]);

			NIW<double> niw(Delta,theta,nu,kappa,&rndGen);
			boost::shared_ptr<NiwSampled<double> > tempBase( new NiwSampled<double>(niw));
			niwSampled.push_back(boost::shared_ptr<BaseMeasure<double> >(tempBase));

		} else if(iequals(baseDist[m], "NiwTangent")) {
			cerr << "NiwTangent base not coded yet... fix me" << endl;
			return(-1);

		} else {
			cerr << "error with base distributions (check help) ... returning." << endl;
			return(-1);
		}
	}

	Timer tlocal;
	tlocal.tic();

	DirMultiNaiveBayes<double> naive_samp(dir,niwSampled);

	cout << "multiObsNaiveBayesian Clustering:" << endl;
	cout << "Ndocs=" << M << endl;
	cout << "NumComp=" << NumObs << endl;
	cout << "NumData,Dim= ";
	for(uint n=0; n<NumObs; ++n)
		cout << "[" << N[n] << ", " << D[n] << "]; ";
	cout << endl;

	cout << "Num Cluster = " << K << ", (" << T << " iterations)." << endl;

	naive_samp.initialize( x );
	naive_samp.inferAll(T,verbose);

	if (pathOut.compare(""))
	{
		ofstream fout(pathOut.data(),ofstream::out);

		streambuf *coutbuf = std::cout.rdbuf(); //save old cout buffer
		cout.rdbuf(fout.rdbuf()); //redirect std::cout to fout1 buffer

			naive_samp.dump(fout,fout);

		std::cout.rdbuf(coutbuf); //reset to standard output again

		fout.close();
	}

	tlocal.displayElapsedTimeAuto();
	return(0);

};
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: drawdlg.cxx,v $
 *
 *  $Revision: 1.5 $
 *
 *  last change: $Author: vg $ $Date: 2003-04-17 15:40:52 $
 *
 *  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): _______________________________________
 *
 *
 ************************************************************************/

#pragma hdrstop

#define ITEMID_COLOR_TABLE      SID_COLOR_TABLE

#ifndef _SVX_SVXIDS_HRC //autogen
#include <svx/svxids.hrc>
#endif
#ifndef _MSGBOX_HXX //autogen
#include <vcl/msgbox.hxx>
#endif
#ifndef _SFXREQUEST_HXX //autogen
#include <sfx2/request.hxx>
#endif
#ifndef _OFF_APP_HXX //autogen
#include <offmgr/app.hxx>
#endif
#ifndef _SFXDISPATCH_HXX //autogen
#include <sfx2/dispatch.hxx>
#endif
#ifndef _SFX_BINDINGS_HXX //autogen
#include <sfx2/bindings.hxx>
#endif
#ifndef _SVDVIEW_HXX //autogen
#include <svx/svdview.hxx>
#endif
#ifndef _SVX_TEXTANIM_HXX //autogen
#include <svx/textanim.hxx>
#endif
#ifndef _SVX_TAB_AREA_HXX //autogen
#include <svx/tabarea.hxx>
#endif
#ifndef _SVX_TAB_LINE_HXX //autogen
#include <svx/tabline.hxx>
#endif
#ifndef _SVX_DRAWITEM_HXX //autogen
#include <svx/drawitem.hxx>
#endif

#include "view.hxx"
#include "wrtsh.hxx"
#include "docsh.hxx"
#include "cmdid.h"

#include "drawsh.hxx"

/*--------------------------------------------------------------------
    Beschreibung:
 --------------------------------------------------------------------*/

void SwDrawShell::ExecDrawDlg(SfxRequest& rReq)
{
    SwWrtShell*     pSh     = &GetShell();
    SdrView*        pView   = pSh->GetDrawView();
    SdrModel*       pDoc    = pView->GetModel();
    Window*         pWin    = GetView().GetWindow();
    BOOL            bChanged = pDoc->IsChanged();
    pDoc->SetChanged(FALSE);

    SfxItemSet aNewAttr( pDoc->GetItemPool() );
    pView->GetAttributes( aNewAttr );

    GetView().NoRotate();

    switch (rReq.GetSlot())
    {
        case FN_DRAWTEXT_ATTR_DLG:
        {
            SvxTextTabDialog* pDlg = new SvxTextTabDialog( NULL, &aNewAttr , pView);
            USHORT nResult = pDlg->Execute();

            if (nResult == RET_OK)
            {
                if (pView->HasMarkedObj())
                {
                    pSh->StartAction();
                    pView->SetAttributes(*pDlg->GetOutputItemSet());
                    rReq.Done(*(pDlg->GetOutputItemSet()));
                    pSh->EndAction();
                }
            }
            delete( pDlg );
        }
        break;

        case SID_ATTRIBUTES_AREA:
        {
            BOOL bHasMarked = pView->HasMarkedObj();

            SvxAreaTabDialog* pDlg = new SvxAreaTabDialog( NULL, &aNewAttr, pDoc, pView );
            const SvxColorTableItem* pColorItem = (const SvxColorTableItem*)
                                    GetView().GetDocShell()->GetItem(SID_COLOR_TABLE);
            if(pColorItem->GetColorTable() == OFF_APP()->GetStdColorTable())
                pDlg->DontDeleteColorTable();
            if (pDlg->Execute() == RET_OK)
            {
                pSh->StartAction();
                if (bHasMarked)
                    pView->SetAttributes(*pDlg->GetOutputItemSet());
                else
                    pView->SetDefaultAttr(*pDlg->GetOutputItemSet(), FALSE);
                pSh->EndAction();

                static USHORT __READONLY_DATA aInval[] =
                {
                    SID_ATTR_FILL_STYLE, SID_ATTR_FILL_COLOR, 0
                };
                SfxBindings &rBnd = GetView().GetViewFrame()->GetBindings();
                rBnd.Invalidate(aInval);
                rBnd.Update(SID_ATTR_FILL_STYLE);
                rBnd.Update(SID_ATTR_FILL_COLOR);
            }
            delete pDlg;
        }
        break;

        case SID_ATTRIBUTES_LINE:
        {
            BOOL bHasMarked = pView->HasMarkedObj();

            const SdrObject* pObj = NULL;
            const SdrMarkList& rMarkList = pView->GetMarkList();
            if( rMarkList.GetMarkCount() == 1 )
                pObj = rMarkList.GetMark(0)->GetObj();

            SvxLineTabDialog* pDlg = new SvxLineTabDialog(NULL, &aNewAttr,
                                                            pDoc, pObj, bHasMarked);

            if (pDlg->Execute() == RET_OK)
            {
                pSh->StartAction();
                if(bHasMarked)
                    pView->SetAttrToMarked(*pDlg->GetOutputItemSet(), FALSE);
                else
                    pView->SetDefaultAttr(*pDlg->GetOutputItemSet(), FALSE);
                pSh->EndAction();

                static USHORT __READONLY_DATA aInval[] =
                {
                    SID_ATTR_LINE_STYLE, SID_ATTR_LINE_WIDTH,
                    SID_ATTR_LINE_COLOR, 0
                };

                GetView().GetViewFrame()->GetBindings().Invalidate(aInval);
            }
            delete pDlg;
        }
        break;

        default:
            break;
    }

    if (pDoc->IsChanged())
        GetShell().SetModified();
    else
        if (bChanged)
            pDoc->SetChanged(TRUE);
}

/*--------------------------------------------------------------------
    Beschreibung:
 --------------------------------------------------------------------*/

void SwDrawShell::ExecDrawAttrArgs(SfxRequest& rReq)
{
    SwWrtShell* pSh   = &GetShell();
    SdrView*    pView = pSh->GetDrawView();
    const SfxItemSet* pArgs = rReq.GetArgs();
    BOOL        bChanged = pView->GetModel()->IsChanged();
    pView->GetModel()->SetChanged(FALSE);

    GetView().NoRotate();

    if (pArgs)
    {
        if(pView->HasMarkedObj())
            pView->SetAttrToMarked(*rReq.GetArgs(), FALSE);
        else
            pView->SetDefaultAttr(*rReq.GetArgs(), FALSE);
    }
    else
    {
        SfxDispatcher* pDis = pSh->GetView().GetViewFrame()->GetDispatcher();
        switch (rReq.GetSlot())
        {
            case SID_ATTR_FILL_STYLE:
            case SID_ATTR_FILL_COLOR:
            case SID_ATTR_FILL_GRADIENT:
            case SID_ATTR_FILL_HATCH:
            case SID_ATTR_FILL_BITMAP:
                pDis->Execute(SID_ATTRIBUTES_AREA, FALSE);
                break;
            case SID_ATTR_LINE_STYLE:
            case SID_ATTR_LINE_DASH:
            case SID_ATTR_LINE_WIDTH:
            case SID_ATTR_LINE_COLOR:
                pDis->Execute(SID_ATTRIBUTES_LINE, FALSE);
                break;
        }
    }
    if (pView->GetModel()->IsChanged())
        GetShell().SetModified();
    else
        if (bChanged)
            pView->GetModel()->SetChanged(TRUE);
}

/*--------------------------------------------------------------------
    Beschreibung:
 --------------------------------------------------------------------*/

void SwDrawShell::GetDrawAttrState(SfxItemSet& rSet)
{
    SdrView* pSdrView = GetShell().GetDrawView();

    if (pSdrView->HasMarkedObj())
    {
        BOOL bDisable = Disable( rSet );

        if( !bDisable )
            pSdrView->GetAttributes( rSet );
    }
    else
        rSet.Put(pSdrView->GetDefaultAttr());
}

<commit_msg>INTEGRATION: CWS dialogdiet (1.5.276); FILE MERGED 2004/01/17 01:26:43 mwu 1.5.276.3: DialogDiet 2004_01_17 2004/01/13 02:53:50 mwu 1.5.276.2: DialogDiet 2004_01_13 2003/12/01 09:56:23 mba 1.5.276.1: #i22969#: use dialog factory for SvxTextTabDialog<commit_after>/*************************************************************************
 *
 *  $RCSfile: drawdlg.cxx,v $
 *
 *  $Revision: 1.6 $
 *
 *  last change: $Author: hr $ $Date: 2004-02-03 16:48:08 $
 *
 *  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): _______________________________________
 *
 *
 ************************************************************************/

#pragma hdrstop

#define ITEMID_COLOR_TABLE      SID_COLOR_TABLE

#ifndef _SVX_SVXIDS_HRC //autogen
#include <svx/svxids.hrc>
#endif
#ifndef _MSGBOX_HXX //autogen
#include <vcl/msgbox.hxx>
#endif
#ifndef _SFXREQUEST_HXX //autogen
#include <sfx2/request.hxx>
#endif
#ifndef _SFXDISPATCH_HXX //autogen
#include <sfx2/dispatch.hxx>
#endif
#ifndef _SFX_BINDINGS_HXX //autogen
#include <sfx2/bindings.hxx>
#endif
#ifndef _SVDVIEW_HXX //autogen
#include <svx/svdview.hxx>
#endif
#ifndef _SVX_TAB_AREA_HXX //autogen
#include <svx/tabarea.hxx>
#endif
#ifndef _SVX_TAB_LINE_HXX //autogen
#include <svx/tabline.hxx>
#endif
#ifndef _SVX_DRAWITEM_HXX //autogen
#include <svx/drawitem.hxx>
#endif

#include <svx/xtable.hxx>
#include "view.hxx"
#include "wrtsh.hxx"
#include "docsh.hxx"
#include "cmdid.h"

#include "drawsh.hxx"
#include <svx/svxdlg.hxx> //CHINA001
#include <svx/dialogs.hrc> //CHINA001

/*--------------------------------------------------------------------
    Beschreibung:
 --------------------------------------------------------------------*/

void SwDrawShell::ExecDrawDlg(SfxRequest& rReq)
{
    SwWrtShell*     pSh     = &GetShell();
    SdrView*        pView   = pSh->GetDrawView();
    SdrModel*       pDoc    = pView->GetModel();
    Window*         pWin    = GetView().GetWindow();
    BOOL            bChanged = pDoc->IsChanged();
    pDoc->SetChanged(FALSE);

    SfxItemSet aNewAttr( pDoc->GetItemPool() );
    pView->GetAttributes( aNewAttr );

    GetView().NoRotate();

    switch (rReq.GetSlot())
    {
        case FN_DRAWTEXT_ATTR_DLG:
        {
            SvxAbstractDialogFactory* pFact = SvxAbstractDialogFactory::Create();
            if ( pFact )
            {
                SfxAbstractTabDialog *pDlg = pFact->CreateTextTabDialog( NULL, &aNewAttr, ResId( RID_SVXDLG_TEXT ), pView );
                USHORT nResult = pDlg->Execute();

                if (nResult == RET_OK)
                {
                    if (pView->HasMarkedObj())
                    {
                        pSh->StartAction();
                        pView->SetAttributes(*pDlg->GetOutputItemSet());
                        rReq.Done(*(pDlg->GetOutputItemSet()));
                        pSh->EndAction();
                    }
                }

                delete( pDlg );
            }
        }
        break;

        case SID_ATTRIBUTES_AREA:
        {
            BOOL bHasMarked = pView->HasMarkedObj();

            //CHINA001 SvxAreaTabDialog* pDlg = new SvxAreaTabDialog( NULL, &aNewAttr, pDoc, pView );
            SvxAbstractDialogFactory* pFact = SvxAbstractDialogFactory::Create();
            DBG_ASSERT(pFact, "Dialogdiet Factory fail!");//CHINA001
            AbstractSvxAreaTabDialog * pDlg = pFact->CreateSvxAreaTabDialog( NULL,
                                                                            &aNewAttr,
                                                                            pDoc,
                                                                            ResId(RID_SVXDLG_AREA),
                                                                            pView);
            DBG_ASSERT(pDlg, "Dialogdiet fail!");//CHINA001
            const SvxColorTableItem* pColorItem = (const SvxColorTableItem*)
                                    GetView().GetDocShell()->GetItem(SID_COLOR_TABLE);
            if(pColorItem->GetColorTable() == XColorTable::GetStdColorTable())
                pDlg->DontDeleteColorTable();
            if (pDlg->Execute() == RET_OK)
            {
                pSh->StartAction();
                if (bHasMarked)
                    pView->SetAttributes(*pDlg->GetOutputItemSet());
                else
                    pView->SetDefaultAttr(*pDlg->GetOutputItemSet(), FALSE);
                pSh->EndAction();

                static USHORT __READONLY_DATA aInval[] =
                {
                    SID_ATTR_FILL_STYLE, SID_ATTR_FILL_COLOR, 0
                };
                SfxBindings &rBnd = GetView().GetViewFrame()->GetBindings();
                rBnd.Invalidate(aInval);
                rBnd.Update(SID_ATTR_FILL_STYLE);
                rBnd.Update(SID_ATTR_FILL_COLOR);
            }
            delete pDlg;
        }
        break;

        case SID_ATTRIBUTES_LINE:
        {
            BOOL bHasMarked = pView->HasMarkedObj();

            const SdrObject* pObj = NULL;
            const SdrMarkList& rMarkList = pView->GetMarkList();
            if( rMarkList.GetMarkCount() == 1 )
                pObj = rMarkList.GetMark(0)->GetObj();

            //CHINA001 SvxLineTabDialog* pDlg = new SvxLineTabDialog(NULL, &aNewAttr,
//CHINA001                                                          pDoc, pObj, bHasMarked);
            SvxAbstractDialogFactory* pFact = SvxAbstractDialogFactory::Create();
            DBG_ASSERT(pFact, "Dialogdiet Factory fail!");//CHINA001
            SfxAbstractTabDialog * pDlg = pFact->CreateSvxLineTabDialog( NULL,
                    &aNewAttr,
                pDoc,
                ResId(RID_SVXDLG_LINE),
                pObj,
                bHasMarked);
            DBG_ASSERT(pDlg, "Dialogdiet fail!");//CHINA001
            if (pDlg->Execute() == RET_OK)
            {
                pSh->StartAction();
                if(bHasMarked)
                    pView->SetAttrToMarked(*pDlg->GetOutputItemSet(), FALSE);
                else
                    pView->SetDefaultAttr(*pDlg->GetOutputItemSet(), FALSE);
                pSh->EndAction();

                static USHORT __READONLY_DATA aInval[] =
                {
                    SID_ATTR_LINE_STYLE, SID_ATTR_LINE_WIDTH,
                    SID_ATTR_LINE_COLOR, 0
                };

                GetView().GetViewFrame()->GetBindings().Invalidate(aInval);
            }
            delete pDlg;
        }
        break;

        default:
            break;
    }

    if (pDoc->IsChanged())
        GetShell().SetModified();
    else
        if (bChanged)
            pDoc->SetChanged(TRUE);
}

/*--------------------------------------------------------------------
    Beschreibung:
 --------------------------------------------------------------------*/

void SwDrawShell::ExecDrawAttrArgs(SfxRequest& rReq)
{
    SwWrtShell* pSh   = &GetShell();
    SdrView*    pView = pSh->GetDrawView();
    const SfxItemSet* pArgs = rReq.GetArgs();
    BOOL        bChanged = pView->GetModel()->IsChanged();
    pView->GetModel()->SetChanged(FALSE);

    GetView().NoRotate();

    if (pArgs)
    {
        if(pView->HasMarkedObj())
            pView->SetAttrToMarked(*rReq.GetArgs(), FALSE);
        else
            pView->SetDefaultAttr(*rReq.GetArgs(), FALSE);
    }
    else
    {
        SfxDispatcher* pDis = pSh->GetView().GetViewFrame()->GetDispatcher();
        switch (rReq.GetSlot())
        {
            case SID_ATTR_FILL_STYLE:
            case SID_ATTR_FILL_COLOR:
            case SID_ATTR_FILL_GRADIENT:
            case SID_ATTR_FILL_HATCH:
            case SID_ATTR_FILL_BITMAP:
                pDis->Execute(SID_ATTRIBUTES_AREA, FALSE);
                break;
            case SID_ATTR_LINE_STYLE:
            case SID_ATTR_LINE_DASH:
            case SID_ATTR_LINE_WIDTH:
            case SID_ATTR_LINE_COLOR:
                pDis->Execute(SID_ATTRIBUTES_LINE, FALSE);
                break;
        }
    }
    if (pView->GetModel()->IsChanged())
        GetShell().SetModified();
    else
        if (bChanged)
            pView->GetModel()->SetChanged(TRUE);
}

/*--------------------------------------------------------------------
    Beschreibung:
 --------------------------------------------------------------------*/

void SwDrawShell::GetDrawAttrState(SfxItemSet& rSet)
{
    SdrView* pSdrView = GetShell().GetDrawView();

    if (pSdrView->HasMarkedObj())
    {
        BOOL bDisable = Disable( rSet );

        if( !bDisable )
            pSdrView->GetAttributes( rSet );
    }
    else
        rSet.Put(pSdrView->GetDefaultAttr());
}

<|endoftext|>


<commit_before>/*
 * Copyright 2014 Open Connectome Project (http://openconnecto.me)
 * Written by Da Zheng (zhengda1936@gmail.com)
 *
 * This file is part of SAFSlib.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include "in_mem_io.h"
#include "slab_allocator.h"

namespace safs
{

class in_mem_byte_array: public page_byte_array
{
	off_t off;
	size_t size;
	const char *pages;

	void assign(in_mem_byte_array &arr) {
		this->off = arr.off;
		this->size = arr.size;
		this->pages = arr.pages;
	}

	in_mem_byte_array(in_mem_byte_array &arr) {
		assign(arr);
	}

	in_mem_byte_array &operator=(in_mem_byte_array &arr) {
		assign(arr);
		return *this;
	}
public:
	in_mem_byte_array(byte_array_allocator &alloc): page_byte_array(alloc) {
		off = 0;
		size = 0;
		pages = NULL;
	}

	in_mem_byte_array(const io_request &req, char *pages,
			byte_array_allocator &alloc): page_byte_array(alloc) {
		this->off = req.get_offset();
		this->size = req.get_size();
		this->pages = pages;
	}

	virtual off_t get_offset() const {
		return off;
	}

	virtual off_t get_offset_in_first_page() const {
		return off % PAGE_SIZE;
	}

	virtual const char *get_page(int pg_idx) const {
		return pages + pg_idx * PAGE_SIZE;
	}

	virtual size_t get_size() const {
		return size;
	}

	void lock() {
		ABORT_MSG("lock isn't implemented");
	}

	void unlock() {
		ABORT_MSG("unlock isn't implemented");
	}

	page_byte_array *clone() {
		in_mem_byte_array *arr = (in_mem_byte_array *) get_allocator().alloc();
		*arr = *this;
		return arr;
	}
};

class in_mem_byte_array_allocator: public byte_array_allocator
{
	class array_initiator: public obj_initiator<in_mem_byte_array>
	{
		in_mem_byte_array_allocator *alloc;
	public:
		array_initiator(in_mem_byte_array_allocator *alloc) {
			this->alloc = alloc;
		}

		virtual void init(in_mem_byte_array *obj) {
			new (obj) in_mem_byte_array(*alloc);
		}
	};

	class array_destructor: public obj_destructor<in_mem_byte_array>
	{
	public:
		void destroy(in_mem_byte_array *obj) {
			obj->~in_mem_byte_array();
		}
	};

	obj_allocator<in_mem_byte_array> allocator;
public:
	in_mem_byte_array_allocator(thread *t): allocator(
			"byte-array-allocator", t->get_node_id(), false, 1024 * 1024,
			params.get_max_obj_alloc_size(),
			obj_initiator<in_mem_byte_array>::ptr(new array_initiator(this)),
			obj_destructor<in_mem_byte_array>::ptr(new array_destructor())) {
	}

	virtual page_byte_array *alloc() {
		return allocator.alloc_obj();
	}

	virtual void free(page_byte_array *arr) {
		allocator.free((in_mem_byte_array *) arr);
	}
};

void in_mem_io::process_req(const io_request &req)
{
	assert(req.get_req_type() == io_request::USER_COMPUTE);
	in_mem_byte_array byte_arr(req,
			data.get() + ROUND_PAGE(req.get_offset()), *array_allocator);
	user_compute *compute = req.get_compute();
	compute->run(byte_arr);
	comp_io_sched->post_comp_process(compute);
}

void in_mem_io::process_computes()
{
	while (true) {
		comp_io_sched->get_requests(req_buf, req_buf.get_size());
		if (req_buf.is_empty())
			break;

		while (!req_buf.is_empty()) {
			io_request new_req = req_buf.pop_front();
			process_req(new_req);
		}
	}
}

void in_mem_io::access(io_request *requests, int num, io_status *)
{
	for (int i = 0; i < num; i++) {
		io_request &req = requests[i];
		if (req.get_req_type() == io_request::USER_COMPUTE) {
			// Let's possess a reference to the user compute first. process_req()
			// will release the reference when the user compute is completed.
			req.get_compute()->inc_ref();
			process_req(req);
		}
		else {
			assert(req.get_req_type() == io_request::BASIC_REQ);
			memcpy(req.get_buf(), data.get() + req.get_offset(), req.get_size());
			io_request *reqs[1];
			reqs[0] = &req;
			if (this->have_callback())
				this->get_callback().invoke(reqs, 1);
		}
	}
	process_computes();
	comp_io_sched->gc_computes();
}

in_mem_io::in_mem_io(std::shared_ptr<char> data, int file_id,
		thread *t): io_interface(t), req_buf(get_node_id(), 1024)
{
	this->data = data;
	this->file_id = file_id;
	array_allocator = std::unique_ptr<byte_array_allocator>(
			new in_mem_byte_array_allocator(t));
	comp_io_sched = comp_io_scheduler::ptr(
			new default_comp_io_scheduler(get_node_id()));
	comp_io_sched->set_io(this);
}

}
<commit_msg>[SAFS]: in-mem I/O supports read and write.<commit_after>/*
 * Copyright 2014 Open Connectome Project (http://openconnecto.me)
 * Written by Da Zheng (zhengda1936@gmail.com)
 *
 * This file is part of SAFSlib.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include "in_mem_io.h"
#include "slab_allocator.h"

namespace safs
{

class in_mem_byte_array: public page_byte_array
{
	off_t off;
	size_t size;
	const char *pages;

	void assign(in_mem_byte_array &arr) {
		this->off = arr.off;
		this->size = arr.size;
		this->pages = arr.pages;
	}

	in_mem_byte_array(in_mem_byte_array &arr) {
		assign(arr);
	}

	in_mem_byte_array &operator=(in_mem_byte_array &arr) {
		assign(arr);
		return *this;
	}
public:
	in_mem_byte_array(byte_array_allocator &alloc): page_byte_array(alloc) {
		off = 0;
		size = 0;
		pages = NULL;
	}

	in_mem_byte_array(const io_request &req, char *pages,
			byte_array_allocator &alloc): page_byte_array(alloc) {
		this->off = req.get_offset();
		this->size = req.get_size();
		this->pages = pages;
	}

	virtual off_t get_offset() const {
		return off;
	}

	virtual off_t get_offset_in_first_page() const {
		return off % PAGE_SIZE;
	}

	virtual const char *get_page(int pg_idx) const {
		return pages + pg_idx * PAGE_SIZE;
	}

	virtual size_t get_size() const {
		return size;
	}

	void lock() {
		ABORT_MSG("lock isn't implemented");
	}

	void unlock() {
		ABORT_MSG("unlock isn't implemented");
	}

	page_byte_array *clone() {
		in_mem_byte_array *arr = (in_mem_byte_array *) get_allocator().alloc();
		*arr = *this;
		return arr;
	}
};

class in_mem_byte_array_allocator: public byte_array_allocator
{
	class array_initiator: public obj_initiator<in_mem_byte_array>
	{
		in_mem_byte_array_allocator *alloc;
	public:
		array_initiator(in_mem_byte_array_allocator *alloc) {
			this->alloc = alloc;
		}

		virtual void init(in_mem_byte_array *obj) {
			new (obj) in_mem_byte_array(*alloc);
		}
	};

	class array_destructor: public obj_destructor<in_mem_byte_array>
	{
	public:
		void destroy(in_mem_byte_array *obj) {
			obj->~in_mem_byte_array();
		}
	};

	obj_allocator<in_mem_byte_array> allocator;
public:
	in_mem_byte_array_allocator(thread *t): allocator(
			"byte-array-allocator", t->get_node_id(), false, 1024 * 1024,
			params.get_max_obj_alloc_size(),
			obj_initiator<in_mem_byte_array>::ptr(new array_initiator(this)),
			obj_destructor<in_mem_byte_array>::ptr(new array_destructor())) {
	}

	virtual page_byte_array *alloc() {
		return allocator.alloc_obj();
	}

	virtual void free(page_byte_array *arr) {
		allocator.free((in_mem_byte_array *) arr);
	}
};

void in_mem_io::process_req(const io_request &req)
{
	assert(req.get_req_type() == io_request::USER_COMPUTE);
	in_mem_byte_array byte_arr(req,
			data.get() + ROUND_PAGE(req.get_offset()), *array_allocator);
	user_compute *compute = req.get_compute();
	compute->run(byte_arr);
	comp_io_sched->post_comp_process(compute);
}

void in_mem_io::process_computes()
{
	while (true) {
		comp_io_sched->get_requests(req_buf, req_buf.get_size());
		if (req_buf.is_empty())
			break;

		while (!req_buf.is_empty()) {
			io_request new_req = req_buf.pop_front();
			process_req(new_req);
		}
	}
}

void in_mem_io::access(io_request *requests, int num, io_status *)
{
	for (int i = 0; i < num; i++) {
		io_request &req = requests[i];
		if (req.get_req_type() == io_request::USER_COMPUTE) {
			// Let's possess a reference to the user compute first. process_req()
			// will release the reference when the user compute is completed.
			req.get_compute()->inc_ref();
			process_req(req);
		}
		else {
			assert(req.get_req_type() == io_request::BASIC_REQ);
			if (req.get_access_method() == READ)
				memcpy(req.get_buf(), data.get() + req.get_offset(), req.get_size());
			else
				memcpy(data.get() + req.get_offset(), req.get_buf(), req.get_size());
			io_request *reqs[1];
			reqs[0] = &req;
			if (this->have_callback())
				this->get_callback().invoke(reqs, 1);
		}
	}
	process_computes();
	comp_io_sched->gc_computes();
}

in_mem_io::in_mem_io(std::shared_ptr<char> data, int file_id,
		thread *t): io_interface(t), req_buf(get_node_id(), 1024)
{
	this->data = data;
	this->file_id = file_id;
	array_allocator = std::unique_ptr<byte_array_allocator>(
			new in_mem_byte_array_allocator(t));
	comp_io_sched = comp_io_scheduler::ptr(
			new default_comp_io_scheduler(get_node_id()));
	comp_io_sched->set_io(this);
}

}
<|endoftext|>


<commit_before>#include "audio_event.h"
#include "audio_engine.h"
#include "audio_clip.h"
#include "halley/resources/resource_data.h"
#include "halley/file/byte_serializer.h"
#include "halley/file_formats/config_file.h"
#include "halley/text/string_converter.h"
#include "halley/core/resources/resources.h"
#include "audio_source_clip.h"
#include "audio_filter_resample.h"

using namespace Halley;

AudioEvent::AudioEvent() = default;

AudioEvent::AudioEvent(const ConfigNode& config)
{
	if (config.hasKey("actions")) {
		for (auto& actionNode: config["actions"]) {
			const auto type = fromString<AudioEventActionType>(actionNode["type"].asString());
			if (type == AudioEventActionType::Play) {
				actions.push_back(std::make_unique<AudioEventActionPlay>(actionNode));
			}
		}
	}
}

void AudioEvent::run(AudioEngine& engine, size_t id, const AudioPosition& position) const
{
	for (auto& a: actions) {
		a->run(engine, id, position);
	}
}

void AudioEvent::serialize(Serializer& s) const
{
	s << uint32_t(actions.size());
	for (auto& a: actions) {
		s << toString(a->getType());
		s << *a;
	}
}

void AudioEvent::deserialize(Deserializer& s)
{
	uint32_t size;
	s >> size;
	for (uint32_t i = 0; i < size; ++i) {
		String name;
		s >> name;
		auto type = fromString<AudioEventActionType>(name);
		if (type == AudioEventActionType::Play) {
			auto newAction = std::make_unique<AudioEventActionPlay>();
			s >> *newAction;
			actions.push_back(std::move(newAction));
		}
	}
}

void AudioEvent::reload(Resource&& resource)
{
	*this = std::move(dynamic_cast<AudioEvent&>(resource));
}

std::shared_ptr<AudioEvent> AudioEvent::loadResource(ResourceLoader& loader)
{
	Deserializer s(loader.getStatic()->getSpan());
	auto event = std::make_shared<AudioEvent>();
	s >> *event;
	return event;
}

AudioEventActionPlay::AudioEventActionPlay() = default;

AudioEventActionPlay::AudioEventActionPlay(const ConfigNode& node)
{
	group = node["group"].asString("");
	if (node.hasKey("clips")) {
		for (auto& clipNode: node["clips"]) {
			clips.push_back(clipNode.asString());
		}
	}

	if (node["pitch"].getType() == ConfigNodeType::Sequence) {
		auto seq = node["pitch"].asSequence();
		pitch = Range<float>(seq.at(0).asFloat(), seq.at(1).asFloat());
	} else {
		float val = node["pitch"].asFloat(1.0f);
		pitch = Range<float>(val, val);
	}

	if (node["volume"].getType() == ConfigNodeType::Sequence) {
		auto seq = node["volume"].asSequence();
		volume = Range<float>(seq.at(0).asFloat(), seq.at(1).asFloat());
	} else {
		float val = node["volume"].asFloat(1.0f);
		volume = Range<float>(val, val);
	}

	minimumSpace = node["minimumSpace"].asFloat(0.0f);
	delay = node["delay"].asFloat(0.0f);
	loop = node["loop"].asBool(false);
}

void AudioEventActionPlay::run(AudioEngine& engine, size_t id, const AudioPosition& position) const
{
	if (clips.empty()) {
		return;
	}

	auto& rng = engine.getRNG();
	int clipN = rng.getInt(0, int(clips.size()) - 1);
	auto clip = engine.getResources().get<AudioClip>(clips[clipN]);

	const float curVolume = rng.getFloat(volume.s, volume.e);
	const float curPitch = clamp(rng.getFloat(pitch.s, pitch.e), 0.1f, 2.0f);

	constexpr int sampleRate = 48000;

	std::shared_ptr<AudioSource> source = std::make_shared<AudioSourceClip>(clip, loop, lround(delay * sampleRate));
	if (std::abs(curPitch - 1.0f) > 0.01f) {
		source = std::make_shared<AudioFilterResample>(source, int(lround(sampleRate * curPitch)), sampleRate, engine.getPool());
	}
	engine.addEmitter(id, std::make_unique<AudioEmitter>(source, position, curVolume, engine.getGroupId(group)));
}

AudioEventActionType AudioEventActionPlay::getType() const
{
	return AudioEventActionType::Play;
}

void AudioEventActionPlay::serialize(Serializer& s) const
{
	s << clips;
	s << group;
	s << pitch;
	s << volume;
	s << delay;
	s << minimumSpace;
	s << loop;
}

void AudioEventActionPlay::deserialize(Deserializer& s)
{
	s >> clips;
	s >> group;
	s >> pitch;
	s >> volume;
	s >> delay;
	s >> minimumSpace;
	s >> loop;
}
<commit_msg>Fix loading of AudioEvents.<commit_after>#include "audio_event.h"
#include "audio_engine.h"
#include "audio_clip.h"
#include "halley/resources/resource_data.h"
#include "halley/file/byte_serializer.h"
#include "halley/file_formats/config_file.h"
#include "halley/text/string_converter.h"
#include "halley/core/resources/resources.h"
#include "audio_source_clip.h"
#include "audio_filter_resample.h"

using namespace Halley;

AudioEvent::AudioEvent() = default;

AudioEvent::AudioEvent(const ConfigNode& config)
{
	if (config.hasKey("actions")) {
		for (auto& actionNode: config["actions"]) {
			const auto type = fromString<AudioEventActionType>(actionNode["type"].asString());
			if (type == AudioEventActionType::Play) {
				actions.push_back(std::make_unique<AudioEventActionPlay>(actionNode));
			}
		}
	}
}

void AudioEvent::run(AudioEngine& engine, size_t id, const AudioPosition& position) const
{
	for (auto& a: actions) {
		a->run(engine, id, position);
	}
}

void AudioEvent::serialize(Serializer& s) const
{
	s << uint32_t(actions.size());
	for (auto& a: actions) {
		s << toString(a->getType());
		s << *a;
	}
}

void AudioEvent::deserialize(Deserializer& s)
{
	uint32_t size;
	s >> size;
	for (uint32_t i = 0; i < size; ++i) {
		String name;
		s >> name;
		auto type = fromString<AudioEventActionType>(name);
		if (type == AudioEventActionType::Play) {
			auto newAction = std::make_unique<AudioEventActionPlay>();
			s >> *newAction;
			actions.push_back(std::move(newAction));
		}
	}
}

void AudioEvent::reload(Resource&& resource)
{
	*this = std::move(dynamic_cast<AudioEvent&>(resource));
}

std::shared_ptr<AudioEvent> AudioEvent::loadResource(ResourceLoader& loader)
{
	auto staticData = loader.getStatic();
	Deserializer s(staticData->getSpan());
	auto event = std::make_shared<AudioEvent>();
	s >> *event;
	return event;
}

AudioEventActionPlay::AudioEventActionPlay() = default;

AudioEventActionPlay::AudioEventActionPlay(const ConfigNode& node)
{
	group = node["group"].asString("");
	if (node.hasKey("clips")) {
		for (auto& clipNode: node["clips"]) {
			clips.push_back(clipNode.asString());
		}
	}

	if (node["pitch"].getType() == ConfigNodeType::Sequence) {
		auto seq = node["pitch"].asSequence();
		pitch = Range<float>(seq.at(0).asFloat(), seq.at(1).asFloat());
	} else {
		float val = node["pitch"].asFloat(1.0f);
		pitch = Range<float>(val, val);
	}

	if (node["volume"].getType() == ConfigNodeType::Sequence) {
		auto seq = node["volume"].asSequence();
		volume = Range<float>(seq.at(0).asFloat(), seq.at(1).asFloat());
	} else {
		float val = node["volume"].asFloat(1.0f);
		volume = Range<float>(val, val);
	}

	minimumSpace = node["minimumSpace"].asFloat(0.0f);
	delay = node["delay"].asFloat(0.0f);
	loop = node["loop"].asBool(false);
}

void AudioEventActionPlay::run(AudioEngine& engine, size_t id, const AudioPosition& position) const
{
	if (clips.empty()) {
		return;
	}

	auto& rng = engine.getRNG();
	int clipN = rng.getInt(0, int(clips.size()) - 1);
	auto clip = engine.getResources().get<AudioClip>(clips[clipN]);

	const float curVolume = rng.getFloat(volume.s, volume.e);
	const float curPitch = clamp(rng.getFloat(pitch.s, pitch.e), 0.1f, 2.0f);

	constexpr int sampleRate = 48000;

	std::shared_ptr<AudioSource> source = std::make_shared<AudioSourceClip>(clip, loop, lround(delay * sampleRate));
	if (std::abs(curPitch - 1.0f) > 0.01f) {
		source = std::make_shared<AudioFilterResample>(source, int(lround(sampleRate * curPitch)), sampleRate, engine.getPool());
	}
	engine.addEmitter(id, std::make_unique<AudioEmitter>(source, position, curVolume, engine.getGroupId(group)));
}

AudioEventActionType AudioEventActionPlay::getType() const
{
	return AudioEventActionType::Play;
}

void AudioEventActionPlay::serialize(Serializer& s) const
{
	s << clips;
	s << group;
	s << pitch;
	s << volume;
	s << delay;
	s << minimumSpace;
	s << loop;
}

void AudioEventActionPlay::deserialize(Deserializer& s)
{
	s >> clips;
	s >> group;
	s >> pitch;
	s >> volume;
	s >> delay;
	s >> minimumSpace;
	s >> loop;
}
<|endoftext|>


<commit_before>/*=========================================================================

  Program:   Visualization Toolkit
  Module:    TestPostgreSQLDatabase.cxx

  Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
  All rights reserved.
  See Copyright.txt or http://www.kitware.com/Copyright.htm for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notice for more information.

=========================================================================*/
/*----------------------------------------------------------------------------
 Copyright (c) Sandia Corporation
 See Copyright.txt or http://www.paraview.org/HTML/Copyright.html for details.
----------------------------------------------------------------------------*/
// .SECTION Thanks
// Thanks to Andrew Wilson from Sandia National Laboratories for implementing
// this test.

#include "vtkPostgreSQLDatabase.h"
#include "vtkSQLQuery.h"
#include "vtkRowQueryToTable.h"
#include "vtkSQLDatabaseSchema.h"
#include "vtkStdString.h"
#include "vtkTable.h"
#include "vtkVariant.h"
#include "vtkVariantArray.h"
#include "vtkStringArray.h"
#include "vtkToolkits.h"

#include <vtkstd/vector>

int TestPostgreSQLDatabase( int /*argc*/, char* /*argv*/[] )
{
  // This test requires the user in VTK_PSQL_TEST_URL to have
  // permission to create and drop the database named in that URL
  // as well as tables in that database. That user must also be
  // able to connect to the "template1" database (which initdb
  // creates and should be present on all systems -- we do NOT
  // support non-standard configurations where this is not true).
  vtkPostgreSQLDatabase* db = vtkPostgreSQLDatabase::SafeDownCast( vtkSQLDatabase::CreateFromURL( VTK_PSQL_TEST_URL ) );
  vtkStdString realDatabase = db->GetDatabaseName();
  db->SetDatabaseName( "template1" ); // This is guaranteed to exist
  bool status = db->Open();
  if ( ! status )
    {
    cerr << "Couldn't open database.\n";
    return 1;
    }

  vtkStringArray* dbNames = db->GetDatabases();
  cout << "Database list:\n";
  for ( int dbi = 0; dbi < dbNames->GetNumberOfValues(); ++ dbi )
    {
    cout << "+ " << dbNames->GetValue( dbi ) << endl;
    }
  dbNames->Delete();
  if ( ! db->CreateDatabase( realDatabase.c_str(), true ) )
    {
    cerr << "Error: " << db->GetLastErrorText() << endl;
    }

  vtkSQLQuery* query = db->GetQueryInstance();

  // Force a database connection open/close
  // This also forces us to connect to the database named in the test URL.
  vtkStdString fauxDatabase = realDatabase + "blarney";
  db->SetDatabaseName( fauxDatabase.c_str() );
  db->SetDatabaseName( realDatabase.c_str() );

  // Test that bad queries fail without segfaulting...
  vtkStdString dropQuery( "DROP TABLE people" );
  cout << dropQuery << endl;
  query->SetQuery( dropQuery.c_str() );
  if ( ! query->Execute() )
    {
    cout << "Drop query did not succeed (this result was expected). The last message: " << endl;
    cout << "   " << query->GetLastErrorText() << endl;
    }
  else
    {
    cerr << "The query \"DROP TABLE people\" succeeded when it should not have.\n";
    }

  // Test table creation, insertion, queries
  vtkStdString createQuery( "CREATE TABLE people (name TEXT, age INTEGER, weight FLOAT)" );
  cout << createQuery << endl;
  query->SetQuery( createQuery.c_str() );
  if ( ! query->Execute() )
    {
    cerr << "Create query failed" << endl;
    return 1;
    }

  for ( int i = 0; i < 40; ++ i )
    {
    char insertQuery[200];
    sprintf( insertQuery, "INSERT INTO people VALUES('John Manyjars %d', %d, %d)", i, i, 10 * i );
    cout << insertQuery << endl;
    query->SetQuery( insertQuery );
    if ( ! query->Execute() )
      {
      cerr << "Insert query " << i << " failed" << endl;
      return 1;
      }
    }

  const char* queryText = "SELECT name, age, weight FROM people WHERE age <= 20";
  query->SetQuery( queryText );
  cerr << endl << "Running query: " << query->GetQuery() << endl;

  cerr << endl << "Using vtkSQLQuery directly to execute query:" << endl;
  if ( ! query->Execute() )
    {
    cerr << "Query failed" << endl;
    return 1;
    }

  for ( int col = 0; col < query->GetNumberOfFields(); ++ col )
    {
    if ( col > 0 )
      {
      cerr << ", ";
      }
    cerr << query->GetFieldName( col );
    }
  cerr << endl;
  while ( query->NextRow() )
    {
    for ( int field = 0; field < query->GetNumberOfFields(); ++ field )
      {
      if ( field > 0 )
        {
        cerr << ", ";
        }
      cerr << query->DataValue( field ).ToString().c_str();
      }
    cerr << endl;
    }

  cerr << endl << "Using vtkSQLQuery to execute query and retrieve by row:" << endl;
  if ( ! query->Execute() )
    {
    cerr << "Query failed" << endl;
    return 1;
    }
  for ( int col = 0; col < query->GetNumberOfFields(); ++ col )
    {
    if ( col > 0 )
      {
      cerr << ", ";
      }
    cerr << query->GetFieldName( col );
    }
  cerr << endl;
  vtkVariantArray* va = vtkVariantArray::New();
  while ( query->NextRow( va ) )
    {
    for ( int field = 0; field < va->GetNumberOfValues(); ++ field )
      {
      if ( field > 0 )
        {
        cerr << ", ";
        }
      cerr << va->GetValue( field ).ToString().c_str();
      }
    cerr << endl;
    }
  va->Delete();

  cerr << endl << "Using vtkRowQueryToTable to execute query:" << endl;
  vtkRowQueryToTable* reader = vtkRowQueryToTable::New();
  reader->SetQuery( query );
  reader->Update();
  vtkTable* table = reader->GetOutput();
  for ( vtkIdType col = 0; col < table->GetNumberOfColumns(); ++ col )
    {
    table->GetColumn( col )->Print( cerr );
    }
  cerr << endl;
  for ( vtkIdType row = 0; row < table->GetNumberOfRows(); ++ row )
    {
    for ( vtkIdType col = 0; col < table->GetNumberOfColumns(); ++ col )
      {
      vtkVariant v = table->GetValue( row, col );
      cerr << "row " << row << ", col " << col << " - "
        << v.ToString() << " (" << vtkImageScalarTypeNameMacro( v.GetType() ) << ")" << endl;
      }
    }

  query->SetQuery( "DROP TABLE people" );
  if ( ! query->Execute() )
    {
    cerr << "DROP TABLE people query failed" << endl;
    return 1;
    }

  reader->Delete();
  query->Delete();
  db->Delete();

// ----------------------------------------------------------------------
// Testing transformation of a schema into a PostgreSQL database

  // 1. Create the schema
  cerr << "@@ Creating a schema...";

  vtkSQLDatabaseSchema* schema = vtkSQLDatabaseSchema::New();
  schema->SetName( "TestSchema" );

  // Insert in alphabetical order so that SHOW TABLES does not mix handles
  // Specify names in lower case so that PostgreSQL does not get confused
  int tblHandle = schema->AddTableMultipleArguments( "atable",
    vtkSQLDatabaseSchema::COLUMN_TOKEN, vtkSQLDatabaseSchema::SERIAL,  "tablekey",  0, "",
    vtkSQLDatabaseSchema::COLUMN_TOKEN, vtkSQLDatabaseSchema::VARCHAR, "somename", 11, "NOT NULL",
    vtkSQLDatabaseSchema::COLUMN_TOKEN, vtkSQLDatabaseSchema::BIGINT,  "somenmbr", 17, "DEFAULT 0",
    vtkSQLDatabaseSchema::INDEX_TOKEN,  vtkSQLDatabaseSchema::PRIMARY_KEY, "bigkey",
    vtkSQLDatabaseSchema::INDEX_COLUMN_TOKEN, "tablekey",
    vtkSQLDatabaseSchema::END_INDEX_TOKEN,
    vtkSQLDatabaseSchema::INDEX_TOKEN,  vtkSQLDatabaseSchema::UNIQUE, "reverselookup",
    vtkSQLDatabaseSchema::INDEX_COLUMN_TOKEN, "somename",
    vtkSQLDatabaseSchema::INDEX_COLUMN_TOKEN, "somenmbr",
    vtkSQLDatabaseSchema::END_INDEX_TOKEN,
    vtkSQLDatabaseSchema::TRIGGER_TOKEN,  vtkSQLDatabaseSchema::AFTER_INSERT,
      "inserttrigger", "INSERT INTO OtherTable ( Value ) VALUES NEW.SomeNmbr",
    vtkSQLDatabaseSchema::END_TABLE_TOKEN
  );

  tblHandle = schema->AddTableMultipleArguments( "btable",
    vtkSQLDatabaseSchema::COLUMN_TOKEN, vtkSQLDatabaseSchema::SERIAL,  "tablekey",  0, "",
    vtkSQLDatabaseSchema::COLUMN_TOKEN, vtkSQLDatabaseSchema::BIGINT,  "somevalue", 12, "DEFAULT 0",
    vtkSQLDatabaseSchema::INDEX_TOKEN,  vtkSQLDatabaseSchema::PRIMARY_KEY, "",
    vtkSQLDatabaseSchema::INDEX_COLUMN_TOKEN, "tablekey",
    vtkSQLDatabaseSchema::END_INDEX_TOKEN,
    vtkSQLDatabaseSchema::INDEX_TOKEN,  vtkSQLDatabaseSchema::UNIQUE, "reverselookup",
    vtkSQLDatabaseSchema::INDEX_COLUMN_TOKEN, "somevalue",
    vtkSQLDatabaseSchema::END_INDEX_TOKEN,
    vtkSQLDatabaseSchema::END_TABLE_TOKEN
  );

  if ( tblHandle < 0 )
    {
    cerr << "Could not create test schema.\n";
    return 1;
    }
  cerr << " done." << endl;

  // 2. Convert the schema into a PostgreSQL database
  cerr << "@@ Converting the schema into a PostgreSQL database...";

  db = vtkPostgreSQLDatabase::SafeDownCast( vtkSQLDatabase::CreateFromURL( VTK_PSQL_TEST_URL ) );
  status = db->Open();

  if ( ! status )
    {
    cerr << "Couldn't open database.\n";
    return 1;
    }

  status = db->EffectSchema( schema );
  if ( ! status )
    {
    cerr << "Could not effect test schema.\n";
    return 1;
    }
  cerr << " done." << endl;

  // 3. Count tables of the newly created database
  cerr << "@@ Counting tables of the newly created database... ";

  query = db->GetQueryInstance();
  query->SetQuery( "SELECT table_name FROM information_schema.tables WHERE table_schema = 'public'" );
  if ( ! query->Execute() )
    {
    cerr << "Query failed" << endl;
    return 1;
    }

  vtkstd::vector<vtkStdString> tables;
  while ( query->NextRow() )
    {
    tables.push_back( query->DataValue( 0 ).ToString() );
    }

  int numTbl = tables.size();

  if ( numTbl != schema->GetNumberOfTables() )
    {
    cerr << "Found an incorrect number of tables: "
         << numTbl
         << " != "
         << schema->GetNumberOfTables()
         << endl;
    return 1;
    }

  cerr << numTbl
       << " found.\n";

  // 4. Inspect these tables
  cerr << "@@ Inspecting these tables..." << "\n";

  for ( tblHandle = 0; tblHandle < numTbl; ++ tblHandle )
    {
    vtkStdString tblName( schema->GetTableNameFromHandle( tblHandle ) );
    cerr << "   Table: "
         << tblName
         << "\n";

    if ( tblName != tables[tblHandle] )
      {
      cerr << "Fetched an incorrect name: "
           << tables[tblHandle]
           << " != "
           << tblName
           << endl;
      return 1;
      }

    // Check columns
    vtkStdString queryStr ("SELECT column_name FROM information_schema.columns WHERE table_schema = 'public' AND table_name = '");
    queryStr += tblName;
    queryStr += "' order by ordinal_position";
    query->SetQuery( queryStr );
    if ( ! query->Execute() )
      {
      cerr << "Query failed" << endl;
      return 1;
      }

    int numFields = query->GetNumberOfFields();
    int colHandle = 0;
    for ( ; query->NextRow(); ++ colHandle )
      {
      for ( int field = 0; field < numFields; ++ field )
        {
        if ( field )
          {
          cerr << ", ";
          }
        else // if ( field )
          {
          vtkStdString colName ( schema->GetColumnNameFromHandle( tblHandle, colHandle ) );
          if ( colName != query->DataValue( field ).ToString() )
            {
            cerr << "Found an incorrect column name: "
                 << query->DataValue( field ).ToString()
                 << " != "
                 << colName
                 << endl;
            return 1;
            }
          cerr << "     Column: ";
          }
        cerr << query->DataValue( field ).ToString().c_str();
        }
      cerr << endl;
      }

    if ( colHandle != schema->GetNumberOfColumnsInTable( tblHandle ) )
      {
      cerr << "Found an incorrect number of columns: "
           << colHandle
           << " != "
           << schema->GetNumberOfColumnsInTable( tblHandle )
           << endl;
      return 1;
      }
    }

  // 5. Drop tables
  cerr << "@@ Dropping these tables...";

  for ( vtkstd::vector<vtkStdString>::iterator it = tables.begin();
        it != tables.end(); ++ it )
    {
    vtkStdString queryStr ("DROP TABLE " );
    queryStr += *it;
    query->SetQuery( queryStr );

    if ( ! query->Execute() )
      {
      cerr << "Query failed" << endl;
      return 1;
      }
    }

  cerr << " done." << endl;

  // Delete the database until we run the test again
  if ( ! db->DropDatabase( realDatabase.c_str() ) )
    {
    cout << "Drop of \"" << realDatabase.c_str() << "\" failed.\n";
    cerr << "\"" << db->GetLastErrorText() << "\"" << endl;
    }
  else
    {
    cout << "Drop of \"" << realDatabase.c_str() << "\" succeeded.\n";
    }

  // Clean up
  db->Delete();
  schema->Delete();
  query->Delete();

  return 0;
}
<commit_msg>BUG: Print out more information to see why dash16 test fails.<commit_after>/*=========================================================================

  Program:   Visualization Toolkit
  Module:    TestPostgreSQLDatabase.cxx

  Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
  All rights reserved.
  See Copyright.txt or http://www.kitware.com/Copyright.htm for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notice for more information.

=========================================================================*/
/*----------------------------------------------------------------------------
 Copyright (c) Sandia Corporation
 See Copyright.txt or http://www.paraview.org/HTML/Copyright.html for details.
----------------------------------------------------------------------------*/
// .SECTION Thanks
// Thanks to Andrew Wilson from Sandia National Laboratories for implementing
// this test.

#include "vtkPostgreSQLDatabase.h"
#include "vtkSQLQuery.h"
#include "vtkRowQueryToTable.h"
#include "vtkSQLDatabaseSchema.h"
#include "vtkStdString.h"
#include "vtkTable.h"
#include "vtkVariant.h"
#include "vtkVariantArray.h"
#include "vtkStringArray.h"
#include "vtkToolkits.h"

#include <vtkstd/vector>

int TestPostgreSQLDatabase( int /*argc*/, char* /*argv*/[] )
{
  // This test requires the user in VTK_PSQL_TEST_URL to have
  // permission to create and drop the database named in that URL
  // as well as tables in that database. That user must also be
  // able to connect to the "template1" database (which initdb
  // creates and should be present on all systems -- we do NOT
  // support non-standard configurations where this is not true).
  vtkPostgreSQLDatabase* db = vtkPostgreSQLDatabase::SafeDownCast(
    vtkSQLDatabase::CreateFromURL( VTK_PSQL_TEST_URL ) );
  vtkStdString realDatabase = db->GetDatabaseName();
  db->SetDatabaseName( "template1" ); // This is guaranteed to exist
  bool status = db->Open();
  if ( ! status )
    {
    cerr
      << "Couldn't open database.\nError message: \""
      << db->GetLastErrorText() << "\"\n";
    db->Delete();
    return 1;
    }

  vtkStringArray* dbNames = db->GetDatabases();
  cout << "Database list:\n";
  for ( int dbi = 0; dbi < dbNames->GetNumberOfValues(); ++ dbi )
    {
    cout << "+ " << dbNames->GetValue( dbi ) << endl;
    }
  dbNames->Delete();
  if ( ! db->CreateDatabase( realDatabase.c_str(), true ) )
    {
    cerr << "Error: " << db->GetLastErrorText() << endl;
    }

  vtkSQLQuery* query = db->GetQueryInstance();

  // Force a database connection open/close
  // This also forces us to connect to the database named in the test URL.
  vtkStdString fauxDatabase = realDatabase + "blarney";
  db->SetDatabaseName( fauxDatabase.c_str() );
  db->SetDatabaseName( realDatabase.c_str() );

  // Test that bad queries fail without segfaulting...
  vtkStdString dropQuery( "DROP TABLE people" );
  cout << dropQuery << endl;
  query->SetQuery( dropQuery.c_str() );
  if ( ! query->Execute() )
    {
    cout << "Drop query did not succeed (this result was expected). The last message: " << endl;
    cout << "   " << query->GetLastErrorText() << endl;
    }
  else
    {
    cerr << "The query \"DROP TABLE people\" succeeded when it should not have.\n";
    }

  // Test table creation, insertion, queries
  vtkStdString createQuery( "CREATE TABLE people (name TEXT, age INTEGER, weight FLOAT)" );
  cout << createQuery << endl;
  query->SetQuery( createQuery.c_str() );
  if ( ! query->Execute() )
    {
    cerr << "Create query failed" << endl;
    query->Delete();
    db->Delete();
    return 1;
    }

  for ( int i = 0; i < 40; ++ i )
    {
    char insertQuery[200];
    sprintf( insertQuery, "INSERT INTO people VALUES('John Manyjars %d', %d, %d)", i, i, 10 * i );
    cout << insertQuery << endl;
    query->SetQuery( insertQuery );
    if ( ! query->Execute() )
      {
      cerr << "Insert query " << i << " failed" << endl;
      query->Delete();
      db->Delete();
      return 1;
      }
    }

  const char* queryText = "SELECT name, age, weight FROM people WHERE age <= 20";
  query->SetQuery( queryText );
  cerr << endl << "Running query: " << query->GetQuery() << endl;

  cerr << endl << "Using vtkSQLQuery directly to execute query:" << endl;
  if ( ! query->Execute() )
    {
    cerr << "Query failed" << endl;
    query->Delete();
    db->Delete();
    return 1;
    }

  for ( int col = 0; col < query->GetNumberOfFields(); ++ col )
    {
    if ( col > 0 )
      {
      cerr << ", ";
      }
    cerr << query->GetFieldName( col );
    }
  cerr << endl;
  while ( query->NextRow() )
    {
    for ( int field = 0; field < query->GetNumberOfFields(); ++ field )
      {
      if ( field > 0 )
        {
        cerr << ", ";
        }
      cerr << query->DataValue( field ).ToString().c_str();
      }
    cerr << endl;
    }

  cerr << endl << "Using vtkSQLQuery to execute query and retrieve by row:" << endl;
  if ( ! query->Execute() )
    {
    cerr << "Query failed" << endl;
    query->Delete();
    db->Delete();
    return 1;
    }
  for ( int col = 0; col < query->GetNumberOfFields(); ++ col )
    {
    if ( col > 0 )
      {
      cerr << ", ";
      }
    cerr << query->GetFieldName( col );
    }
  cerr << endl;
  vtkVariantArray* va = vtkVariantArray::New();
  while ( query->NextRow( va ) )
    {
    for ( int field = 0; field < va->GetNumberOfValues(); ++ field )
      {
      if ( field > 0 )
        {
        cerr << ", ";
        }
      cerr << va->GetValue( field ).ToString().c_str();
      }
    cerr << endl;
    }
  va->Delete();

  cerr << endl << "Using vtkRowQueryToTable to execute query:" << endl;
  vtkRowQueryToTable* reader = vtkRowQueryToTable::New();
  reader->SetQuery( query );
  reader->Update();
  vtkTable* table = reader->GetOutput();
  for ( vtkIdType col = 0; col < table->GetNumberOfColumns(); ++ col )
    {
    table->GetColumn( col )->Print( cerr );
    }
  cerr << endl;
  for ( vtkIdType row = 0; row < table->GetNumberOfRows(); ++ row )
    {
    for ( vtkIdType col = 0; col < table->GetNumberOfColumns(); ++ col )
      {
      vtkVariant v = table->GetValue( row, col );
      cerr << "row " << row << ", col " << col << " - "
        << v.ToString() << " (" << vtkImageScalarTypeNameMacro( v.GetType() ) << ")" << endl;
      }
    }

  query->SetQuery( "DROP TABLE people" );
  if ( ! query->Execute() )
    {
    cerr << "DROP TABLE people query failed" << endl;
    reader->Delete();
    query->Delete();
    db->Delete();
    return 1;
    }

  reader->Delete();
  query->Delete();
  db->Delete();

// ----------------------------------------------------------------------
// Testing transformation of a schema into a PostgreSQL database

  // 1. Create the schema
  cerr << "@@ Creating a schema...";

  vtkSQLDatabaseSchema* schema = vtkSQLDatabaseSchema::New();
  schema->SetName( "TestSchema" );

  // Insert in alphabetical order so that SHOW TABLES does not mix handles
  // Specify names in lower case so that PostgreSQL does not get confused
  int tblHandle = schema->AddTableMultipleArguments( "atable",
    vtkSQLDatabaseSchema::COLUMN_TOKEN, vtkSQLDatabaseSchema::SERIAL,  "tablekey",  0, "",
    vtkSQLDatabaseSchema::COLUMN_TOKEN, vtkSQLDatabaseSchema::VARCHAR, "somename", 11, "NOT NULL",
    vtkSQLDatabaseSchema::COLUMN_TOKEN, vtkSQLDatabaseSchema::BIGINT,  "somenmbr", 17, "DEFAULT 0",
    vtkSQLDatabaseSchema::INDEX_TOKEN,  vtkSQLDatabaseSchema::PRIMARY_KEY, "bigkey",
    vtkSQLDatabaseSchema::INDEX_COLUMN_TOKEN, "tablekey",
    vtkSQLDatabaseSchema::END_INDEX_TOKEN,
    vtkSQLDatabaseSchema::INDEX_TOKEN,  vtkSQLDatabaseSchema::UNIQUE, "reverselookup",
    vtkSQLDatabaseSchema::INDEX_COLUMN_TOKEN, "somename",
    vtkSQLDatabaseSchema::INDEX_COLUMN_TOKEN, "somenmbr",
    vtkSQLDatabaseSchema::END_INDEX_TOKEN,
    vtkSQLDatabaseSchema::TRIGGER_TOKEN,  vtkSQLDatabaseSchema::AFTER_INSERT,
      "inserttrigger", "INSERT INTO OtherTable ( Value ) VALUES NEW.SomeNmbr",
    vtkSQLDatabaseSchema::END_TABLE_TOKEN
  );

  tblHandle = schema->AddTableMultipleArguments( "btable",
    vtkSQLDatabaseSchema::COLUMN_TOKEN, vtkSQLDatabaseSchema::SERIAL,  "tablekey",  0, "",
    vtkSQLDatabaseSchema::COLUMN_TOKEN, vtkSQLDatabaseSchema::BIGINT,  "somevalue", 12, "DEFAULT 0",
    vtkSQLDatabaseSchema::INDEX_TOKEN,  vtkSQLDatabaseSchema::PRIMARY_KEY, "",
    vtkSQLDatabaseSchema::INDEX_COLUMN_TOKEN, "tablekey",
    vtkSQLDatabaseSchema::END_INDEX_TOKEN,
    vtkSQLDatabaseSchema::INDEX_TOKEN,  vtkSQLDatabaseSchema::UNIQUE, "reverselookup",
    vtkSQLDatabaseSchema::INDEX_COLUMN_TOKEN, "somevalue",
    vtkSQLDatabaseSchema::END_INDEX_TOKEN,
    vtkSQLDatabaseSchema::END_TABLE_TOKEN
  );

  if ( tblHandle < 0 )
    {
    cerr << "Could not create test schema.\n";
    schema->Delete();
    return 1;
    }
  cerr << " done." << endl;

  // 2. Convert the schema into a PostgreSQL database
  cerr << "@@ Converting the schema into a PostgreSQL database...";

  db = vtkPostgreSQLDatabase::SafeDownCast( vtkSQLDatabase::CreateFromURL( VTK_PSQL_TEST_URL ) );
  status = db->Open();

  if ( ! status )
    {
    cerr
      << "Couldn't open database.\nError: \""
      << db->GetLastErrorText() << "\"\n";
    schema->Delete();
    db->Delete();
    return 1;
    }

  status = db->EffectSchema( schema );
  if ( ! status )
    {
    cerr << "Could not effect test schema.\n";
    schema->Delete();
    db->Delete();
    return 1;
    }
  cerr << " done." << endl;

  // 3. Count tables of the newly created database
  cerr << "@@ Counting tables of the newly created database... ";

  query = db->GetQueryInstance();
  query->SetQuery( "SELECT table_name FROM information_schema.tables WHERE table_schema = 'public'" );
  if ( ! query->Execute() )
    {
    cerr << "Query failed" << endl;
    schema->Delete();
    query->Delete();
    db->Delete();
    return 1;
    }

  vtkstd::vector<vtkStdString> tables;
  while ( query->NextRow() )
    {
    tables.push_back( query->DataValue( 0 ).ToString() );
    }

  int numTbl = tables.size();

  if ( numTbl != schema->GetNumberOfTables() )
    {
    cerr << "Found an incorrect number of tables: "
         << numTbl
         << " != "
         << schema->GetNumberOfTables()
         << endl;
    schema->Delete();
    query->Delete();
    db->Delete();
    return 1;
    }

  cerr << numTbl
       << " found.\n";

  // 4. Inspect these tables
  cerr << "@@ Inspecting these tables..." << "\n";

  for ( tblHandle = 0; tblHandle < numTbl; ++ tblHandle )
    {
    vtkStdString tblName( schema->GetTableNameFromHandle( tblHandle ) );
    cerr << "   Table: "
         << tblName
         << "\n";

    if ( tblName != tables[tblHandle] )
      {
      cerr << "Fetched an incorrect name: "
           << tables[tblHandle]
           << " != "
           << tblName
           << endl;
      schema->Delete();
      query->Delete();
      db->Delete();
      return 1;
      }

    // Check columns
    vtkStdString queryStr ("SELECT column_name FROM information_schema.columns WHERE table_schema = 'public' AND table_name = '");
    queryStr += tblName;
    queryStr += "' order by ordinal_position";
    query->SetQuery( queryStr );
    if ( ! query->Execute() )
      {
      cerr << "Query failed" << endl;
      schema->Delete();
      query->Delete();
      db->Delete();
      return 1;
      }

    int numFields = query->GetNumberOfFields();
    int colHandle = 0;
    for ( ; query->NextRow(); ++ colHandle )
      {
      for ( int field = 0; field < numFields; ++ field )
        {
        if ( field )
          {
          cerr << ", ";
          }
        else // if ( field )
          {
          vtkStdString colName ( schema->GetColumnNameFromHandle( tblHandle, colHandle ) );
          if ( colName != query->DataValue( field ).ToString() )
            {
            cerr << "Found an incorrect column name: "
                 << query->DataValue( field ).ToString()
                 << " != "
                 << colName
                 << endl;
            schema->Delete();
            query->Delete();
            db->Delete();
            return 1;
            }
          cerr << "     Column: ";
          }
        cerr << query->DataValue( field ).ToString().c_str();
        }
      cerr << endl;
      }

    if ( colHandle != schema->GetNumberOfColumnsInTable( tblHandle ) )
      {
      cerr << "Found an incorrect number of columns: "
           << colHandle
           << " != "
           << schema->GetNumberOfColumnsInTable( tblHandle )
           << endl;
      schema->Delete();
      query->Delete();
      db->Delete();
      return 1;
      }
    }

  // 5. Drop tables
  cerr << "@@ Dropping these tables...";

  for ( vtkstd::vector<vtkStdString>::iterator it = tables.begin();
        it != tables.end(); ++ it )
    {
    vtkStdString queryStr ("DROP TABLE " );
    queryStr += *it;
    query->SetQuery( queryStr );

    if ( ! query->Execute() )
      {
      cerr << "Query failed" << endl;
      schema->Delete();
      query->Delete();
      db->Delete();
      return 1;
      }
    }

  cerr << " done." << endl;

  // Delete the database until we run the test again
  if ( ! db->DropDatabase( realDatabase.c_str() ) )
    {
    cout << "Drop of \"" << realDatabase.c_str() << "\" failed.\n";
    cerr << "\"" << db->GetLastErrorText() << "\"" << endl;
    }
  else
    {
    cout << "Drop of \"" << realDatabase.c_str() << "\" succeeded.\n";
    }

  // Clean up
  db->Delete();
  schema->Delete();
  query->Delete();

  return 0;
}
<|endoftext|>


<commit_before>#include "heightmap/heightmapgenerator.hpp"

#include <ctime>

HeightmapGenerator::HeightmapGenerator(int size, int seed, int variation) {
	mapWidth = size;
	HeightmapGenerator::variation = variation;
	vertices = new HMVertex[size*size];
	vertexCount = 0;

	for(int i = 0; i < size; ++i) {
		IntVectorPtr intVectorPtr(new std::vector<int>(size));
		map.push_back(intVectorPtr);
	}

	(*map[0])[0] = seed;
	(*map[0])[size-1] = seed;
	(*map[size-1])[0] = seed;
	(*map[size-1])[size-1] = seed;
}

HeightmapGenerator::~HeightmapGenerator() {
}

const Matrix& HeightmapGenerator::getMap() {
	return map;
}

HMVertex* HeightmapGenerator::getVertices() {
	return vertices;
}

void HeightmapGenerator::fillMap() {
	srand(std::time(0));
	int twoLog = numberOfTrailingZeros(map.size()-1);
	for(int i = 0; i < (twoLog - 1); i++) {
		fillMap(0);
	}
}

void HeightmapGenerator::convertMap() {
	int numVertex = 0;
	int x = 0;
	int z = 0;
	int xPrev = -1;
	int zPrev = -1;
	for(int mod = 0; mod < mapWidth-1; mod++) {
		for(x = 0; x < mapWidth; x++) {
			if(x != xPrev || z != zPrev) {
				z = mod;
				HMVertex nextVertex;
				nextVertex.x = x;
				nextVertex.z = z;
				nextVertex.y = (*map[x])[z];
				vertices[numVertex] = nextVertex;
				numVertex++;
			}
			z = mod+1;
			HMVertex nextVertex;
			nextVertex.x = x;
			nextVertex.z = z;
			nextVertex.y = (*map[x])[z];
			vertices[numVertex] = nextVertex;
			numVertex++;
			xPrev = x;
			zPrev = z;
		}
		mod++;
		for(x = mapWidth-1; x >= 0; x--) {
			if(x != xPrev || z != zPrev) {
				z = mod;
				HMVertex nextVertex;
				nextVertex.x = x;
				nextVertex.z = z;
				nextVertex.y = (*map[x])[z];
				vertices[numVertex] = nextVertex;
				numVertex++;
			}

			z = mod+1;
			HMVertex nextVertex;
			nextVertex.x = x;
			nextVertex.z = z;
			nextVertex.y = (*map[x])[z];
			vertices[numVertex] = nextVertex;
			numVertex++;
			xPrev = x;
			zPrev = z;
		}
	}

	vertexCount = numVertex;
}

void HeightmapGenerator::fillMap(int iteration) {
	int length = (map.size()-1) >> iteration;
	int mapSize = map.size();
	for(int xLow = 0; xLow < mapSize - 1; xLow += length) {
		int xHigh = xLow + length;
		for(int yLow = 0; yLow < mapSize - 1; yLow += length) {
			int yHigh = yLow + length;
			makeDiamond(iteration, xLow, xHigh, yLow, yHigh);
		}
	}
	for(int xLow = ((length>>1)^-1)+1; xLow < mapSize - length; xLow += length) {
		int xHigh = xLow + length;
		for(int yLow = 0; yLow < mapSize - 1; yLow += length) {
			int yHigh = yLow + length;
			makeSquare(iteration, xLow, xHigh, yLow, yHigh);
		}
	}
	for(int yLow = ((length>>1)^-1)+1; yLow < mapSize - length; yLow += length) {
		int yHigh = yLow + length;
		for(int xLow = 0; xLow < mapSize - 1; xLow += length) {
			int xHigh = xLow + length;
			makeSquare(iteration, xLow, xHigh, yLow, yHigh);
		}
	}
}

void HeightmapGenerator::makeDiamond(int iteration, int xLow, int xHigh, int yLow, int yHigh) {
	int x = (xLow + xHigh) >> 1;
	int y = (yLow + yHigh) >> 1;
	int val1 = (*map[xLow])[yLow];
	int val2 = (*map[xLow])[yHigh];
	int val3 = (*map[xHigh])[yLow];
	int val4 = (*map[xHigh])[yHigh];
	int random = randomNumber(iteration);
	int newValue = ((val1 + val2 + val3 + val4) >> 2) + random;
	(*map[x])[y] = newValue;
}

void HeightmapGenerator::makeSquare(int iteration, int xLow, int xHigh, int yLow, int yHigh) {
	int x = (xLow + xHigh) >> 1;
	int y = (yLow + yHigh) >> 1;
	int tempXLow = xLow < 0 ? map.size() + xLow - 1 : xLow;
	int tempYLow = yLow < 0 ? map.size() + yLow - 1 : yLow;
	int val1 = (*map[tempXLow])[y];
	int val2 = (*map[x])[tempYLow];
	int val3 = (*map[xHigh])[y];
	int val4 = (*map[x])[yHigh];
	int random = randomNumber(iteration);
	int newValue = ((val1 + val2 + val3 + val4) >> 2) + random;
	(*map[x])[y] = newValue;
	if(x == 0) {
		(*map[map.size()-1])[y] = newValue;
	}
	if(y == 0) {
		(*map[x])[map.size()-1] = newValue;
	}
}

int HeightmapGenerator::randomNumber(int iteration) {
	int random = (((rand()%variation)<<1)-variation)>>iteration;
	return random;
}

int HeightmapGenerator::numberOfTrailingZeros(int integer) {
	if(integer == 0)
		return 32;
	int trailingZeros = 32;
	while(integer != 0) {
		integer = integer << 1;
		trailingZeros--;
	}
	return trailingZeros;
}
<commit_msg>Fixed heightmapgenerator, now correctly allocates memory<commit_after>#include "heightmap/heightmapgenerator.hpp"

#include <ctime>

HeightmapGenerator::HeightmapGenerator(int size, int seed, int variation) {
	HeightmapGenerator::variation = variation;
	vertexCount = 0;

	for(int i = 0; i < size; ++i) {
		IntVectorPtr intVectorPtr(new std::vector<int>(size));
		map.push_back(intVectorPtr);
	}

	(*map[0])[0] = seed;
	(*map[0])[size-1] = seed;
	(*map[size-1])[0] = seed;
	(*map[size-1])[size-1] = seed;

	mapWidth = size;
	int pow = numberOfTrailingZeros(size-1);
	int arraySize = ((1 << (pow+1))-1)*mapWidth+2;
	vertices = new HMVertex[arraySize];
}

HeightmapGenerator::~HeightmapGenerator() {
}

const Matrix& HeightmapGenerator::getMap() {
	return map;
}

HMVertex* HeightmapGenerator::getVertices() {
	return vertices;
}

void HeightmapGenerator::fillMap() {
	srand(std::time(0));
	int twoLog = numberOfTrailingZeros(map.size()-1);
	for(int i = 0; i < (twoLog - 1); i++) {
		fillMap(0);
	}
}

void HeightmapGenerator::convertMap() {
	int numVertex = 0;
	int x = 0;
	int z = 0;
	int xPrev = -1;
	int zPrev = -1;
	for(int mod = 0; mod < mapWidth-1; mod++) {
		for(x = 0; x < mapWidth; x++) {
			if(x != xPrev || z != zPrev) {
				z = mod;
				HMVertex nextVertex;
				nextVertex.x = x;
				nextVertex.z = z;
				nextVertex.y = (*map[x])[z];
				vertices[numVertex] = nextVertex;
				numVertex++;
			}
			z = mod+1;
			HMVertex nextVertex;
			nextVertex.x = x;
			nextVertex.z = z;
			nextVertex.y = (*map[x])[z];
			vertices[numVertex] = nextVertex;
			numVertex++;
			xPrev = x;
			zPrev = z;
		}
		mod++;
		for(x = mapWidth-1; x >= 0; x--) {
			if(x != xPrev || z != zPrev) {
				z = mod;
				HMVertex nextVertex;
				nextVertex.x = x;
				nextVertex.z = z;
				nextVertex.y = (*map[x])[z];
				vertices[numVertex] = nextVertex;
				numVertex++;
			}

			z = mod+1;
			HMVertex nextVertex;
			nextVertex.x = x;
			nextVertex.z = z;
			nextVertex.y = (*map[x])[z];
			vertices[numVertex] = nextVertex;
			numVertex++;
			xPrev = x;
			zPrev = z;
		}
	}

	vertexCount = numVertex;
}

void HeightmapGenerator::fillMap(int iteration) {
	int length = (map.size()-1) >> iteration;
	int mapSize = map.size();
	for(int xLow = 0; xLow < mapSize - 1; xLow += length) {
		int xHigh = xLow + length;
		for(int yLow = 0; yLow < mapSize - 1; yLow += length) {
			int yHigh = yLow + length;
			makeDiamond(iteration, xLow, xHigh, yLow, yHigh);
		}
	}
	for(int xLow = ((length>>1)^-1)+1; xLow < mapSize - length; xLow += length) {
		int xHigh = xLow + length;
		for(int yLow = 0; yLow < mapSize - 1; yLow += length) {
			int yHigh = yLow + length;
			makeSquare(iteration, xLow, xHigh, yLow, yHigh);
		}
	}
	for(int yLow = ((length>>1)^-1)+1; yLow < mapSize - length; yLow += length) {
		int yHigh = yLow + length;
		for(int xLow = 0; xLow < mapSize - 1; xLow += length) {
			int xHigh = xLow + length;
			makeSquare(iteration, xLow, xHigh, yLow, yHigh);
		}
	}
}

void HeightmapGenerator::makeDiamond(int iteration, int xLow, int xHigh, int yLow, int yHigh) {
	int x = (xLow + xHigh) >> 1;
	int y = (yLow + yHigh) >> 1;
	int val1 = (*map[xLow])[yLow];
	int val2 = (*map[xLow])[yHigh];
	int val3 = (*map[xHigh])[yLow];
	int val4 = (*map[xHigh])[yHigh];
	int random = randomNumber(iteration);
	int newValue = ((val1 + val2 + val3 + val4) >> 2) + random;
	(*map[x])[y] = newValue;
}

void HeightmapGenerator::makeSquare(int iteration, int xLow, int xHigh, int yLow, int yHigh) {
	int x = (xLow + xHigh) >> 1;
	int y = (yLow + yHigh) >> 1;
	int tempXLow = xLow < 0 ? map.size() + xLow - 1 : xLow;
	int tempYLow = yLow < 0 ? map.size() + yLow - 1 : yLow;
	int val1 = (*map[tempXLow])[y];
	int val2 = (*map[x])[tempYLow];
	int val3 = (*map[xHigh])[y];
	int val4 = (*map[x])[yHigh];
	int random = randomNumber(iteration);
	int newValue = ((val1 + val2 + val3 + val4) >> 2) + random;
	(*map[x])[y] = newValue;
	if(x == 0) {
		(*map[map.size()-1])[y] = newValue;
	}
	if(y == 0) {
		(*map[x])[map.size()-1] = newValue;
	}
}

int HeightmapGenerator::randomNumber(int iteration) {
	int random = (((rand()%variation)<<1)-variation)>>iteration;
	return random;
}

int HeightmapGenerator::numberOfTrailingZeros(int integer) {
	if(integer == 0)
		return 32;
	int trailingZeros = 32;
	while(integer != 0) {
		integer = integer << 1;
		trailingZeros--;
	}
	return trailingZeros;
}
<|endoftext|>