<commit_before>#include "gtest/gtest.h"
#include "gmock/gmock.h"

#include <string>

#include "hybrid_automaton/DescriptionTreeNode.h"
#include "tests/MockDescriptionTreeNode.h"

using ::testing::Return;
using ::testing::DoAll;
using ::testing::SetArgReferee;
using ::testing::_;

using namespace ::ha;

TEST(DescriptionTree, setAttribute) {
	using namespace ha;
	using ::testing::Return;

	MockDescriptionTreeNode mock_dtn;

	int dimensionality = 6;
	std::string dimensionality_exp = "6";

	EXPECT_CALL(mock_dtn, setAttributeString(std::string("dimensionality"), dimensionality_exp));

	mock_dtn.setAttribute<int>("dimensionality", dimensionality);
}

TEST(DescriptionTree, getAttribute) {
	using namespace ha;

	MockDescriptionTreeNode mock_dtn;

	int dimensionality = 6;
	std::string dimensionality_exp = "6";

	EXPECT_CALL(mock_dtn, getAttributeString(std::string("dimensionality"), _)).WillOnce(DoAll(SetArgReferee<1>(dimensionality_exp), Return(true)));

	int dimensionality_result;
	mock_dtn.getAttribute<int>("dimensionality", dimensionality_result);

	EXPECT_EQ(dimensionality, dimensionality_result);
}

TEST(DescriptionTree, setAttributeVector) {
	using namespace ha;
	using ::testing::Return;

	MockDescriptionTreeNode mock_dtn;

	::Eigen::MatrixXd goal(5,1);
	goal << 1.,
		2.,
		3.,
		4.,
		5.;
	std::string goal_exp = "[5,1]1;2;3;4;5";

	EXPECT_CALL(mock_dtn, setAttributeString(std::string("goal"), goal_exp));

	mock_dtn.setAttribute<::Eigen::MatrixXd>("goal", goal);
}

TEST(DescriptionTree, getAttributeVector) {
	using namespace ha;

	MockDescriptionTreeNode mock_dtn;

	std::string goal_exp = "[5,1]1;2;3;4;5";
	EXPECT_CALL(mock_dtn, getAttributeString(std::string("goal"), _)).WillOnce(DoAll(SetArgReferee<1>(goal_exp), Return(true)));

	::Eigen::MatrixXd goal_result(1,1);
	goal_result << 1.;
	mock_dtn.getAttribute<::Eigen::MatrixXd>("goal", goal_result);

	::Eigen::MatrixXd goal_true(5,1);
	goal_true << 1., 2., 3., 4., 5.;
	EXPECT_EQ(goal_result, goal_true);

	::Eigen::MatrixXd goal_false(5,1);
	goal_false << 2., 2., 2., 2., 2.;
	EXPECT_NE(goal_result, goal_false);
}

TEST(DescriptionTree, setAttributeMatrix) {
	using namespace ha;
	using ::testing::Return;

	MockDescriptionTreeNode mock_dtn;

	::Eigen::MatrixXd goal(5,2);
	goal << 1.,2.,3.,4.,5, 6.,7.,8.,9.,10.;
	std::string goal_exp = "[5,2]1,2;3,4;5,6;7,8;9,10";

	EXPECT_CALL(mock_dtn, setAttributeString(std::string("goal"), goal_exp));

	mock_dtn.setAttribute<::Eigen::MatrixXd>("goal", goal);
}

TEST(DescriptionTree, getAttributeMatrix) {
	using namespace ha;

	MockDescriptionTreeNode mock_dtn;

	std::string goal_exp = "[5,2]1,2;3,4;5,6;7,8;9,10";
	EXPECT_CALL(mock_dtn, getAttributeString(std::string("goal"), _)).WillOnce(DoAll(SetArgReferee<1>(goal_exp), Return(true)));

	::Eigen::MatrixXd goal_result(1,1);
	goal_result << 1.;
	mock_dtn.getAttribute<::Eigen::MatrixXd>("goal", goal_result);

	::Eigen::MatrixXd goal_true(5,2);
	goal_true << 1.,2.,3.,4.,5, 6.,7.,8.,9.,10.;
	EXPECT_EQ(goal_result, goal_true);

	::Eigen::MatrixXd goal_false(5,2);
	goal_false << 2., 2., 2., 2., 2., 2., 2., 2., 2., 2.;
	EXPECT_NE(goal_result, goal_false);
}<commit_msg>"<::" throws a compilation error on linux : "error: ‘<::’ cannot begin a template-argument list ... note: ‘<:’ is an alternate spelling for ‘[’. Insert whitespace between ‘<’ and ‘::’"<commit_after>#include "gtest/gtest.h"
#include "gmock/gmock.h"

#include <string>

#include "hybrid_automaton/DescriptionTreeNode.h"
#include "tests/MockDescriptionTreeNode.h"

using ::testing::Return;
using ::testing::DoAll;
using ::testing::SetArgReferee;
using ::testing::_;

using namespace ::ha;

TEST(DescriptionTree, setAttribute) {
	using namespace ha;
	using ::testing::Return;

	MockDescriptionTreeNode mock_dtn;

	int dimensionality = 6;
	std::string dimensionality_exp = "6";

	EXPECT_CALL(mock_dtn, setAttributeString(std::string("dimensionality"), dimensionality_exp));

	mock_dtn.setAttribute<int>("dimensionality", dimensionality);
}

TEST(DescriptionTree, getAttribute) {
	using namespace ha;

	MockDescriptionTreeNode mock_dtn;

	int dimensionality = 6;
	std::string dimensionality_exp = "6";

	EXPECT_CALL(mock_dtn, getAttributeString(std::string("dimensionality"), _)).WillOnce(DoAll(SetArgReferee<1>(dimensionality_exp), Return(true)));

	int dimensionality_result;
	mock_dtn.getAttribute<int>("dimensionality", dimensionality_result);

	EXPECT_EQ(dimensionality, dimensionality_result);
}

TEST(DescriptionTree, setAttributeVector) {
	using namespace ha;
	using ::testing::Return;

	MockDescriptionTreeNode mock_dtn;

	::Eigen::MatrixXd goal(5,1);
	goal << 1.,
		2.,
		3.,
		4.,
		5.;
	std::string goal_exp = "[5,1]1;2;3;4;5";

	EXPECT_CALL(mock_dtn, setAttributeString(std::string("goal"), goal_exp));

	mock_dtn.setAttribute< ::Eigen::MatrixXd>("goal", goal);
}

TEST(DescriptionTree, getAttributeVector) {
	using namespace ha;

	MockDescriptionTreeNode mock_dtn;

	std::string goal_exp = "[5,1]1;2;3;4;5";
	EXPECT_CALL(mock_dtn, getAttributeString(std::string("goal"), _)).WillOnce(DoAll(SetArgReferee<1>(goal_exp), Return(true)));

	::Eigen::MatrixXd goal_result(1,1);
	goal_result << 1.;
	mock_dtn.getAttribute< ::Eigen::MatrixXd>("goal", goal_result);

	::Eigen::MatrixXd goal_true(5,1);
	goal_true << 1., 2., 3., 4., 5.;
	EXPECT_EQ(goal_result, goal_true);

	::Eigen::MatrixXd goal_false(5,1);
	goal_false << 2., 2., 2., 2., 2.;
	EXPECT_NE(goal_result, goal_false);
}

TEST(DescriptionTree, setAttributeMatrix) {
	using namespace ha;
	using ::testing::Return;

	MockDescriptionTreeNode mock_dtn;

	::Eigen::MatrixXd goal(5,2);
	goal << 1.,2.,3.,4.,5, 6.,7.,8.,9.,10.;
	std::string goal_exp = "[5,2]1,2;3,4;5,6;7,8;9,10";

	EXPECT_CALL(mock_dtn, setAttributeString(std::string("goal"), goal_exp));

	mock_dtn.setAttribute< ::Eigen::MatrixXd>("goal", goal);
}

TEST(DescriptionTree, getAttributeMatrix) {
	using namespace ha;

	MockDescriptionTreeNode mock_dtn;

	std::string goal_exp = "[5,2]1,2;3,4;5,6;7,8;9,10";
	EXPECT_CALL(mock_dtn, getAttributeString(std::string("goal"), _)).WillOnce(DoAll(SetArgReferee<1>(goal_exp), Return(true)));

	::Eigen::MatrixXd goal_result(1,1);
	goal_result << 1.;
	mock_dtn.getAttribute< ::Eigen::MatrixXd>("goal", goal_result);

	::Eigen::MatrixXd goal_true(5,2);
	goal_true << 1.,2.,3.,4.,5, 6.,7.,8.,9.,10.;
	EXPECT_EQ(goal_result, goal_true);

	::Eigen::MatrixXd goal_false(5,2);
	goal_false << 2., 2., 2., 2., 2., 2., 2., 2., 2., 2.;
	EXPECT_NE(goal_result, goal_false);
}<|endoftext|>


<commit_before>#include "atom.h"
#include "variable.h"
#include "number.h"

#include <string>

#include <iostream>
using namespace std;

bool Variable::match( Atom *atom ){
    if(_assignable){
      _value = atom->_symbol ;
      _assignable = false;
      this->Aptr = atom;
      //cout<<"the value of Aptr first match tom: "<<Aptr<<endl;
      //cout<<"the value of atom first match tom: "<<atom<<endl;
      return true;
    }
    else{
        //cout<<"the value of Aptr second match tom: "<<Aptr<<endl;
        //cout<<"the value of atom second match tom: "<<atom<<endl;
        if(Aptr == atom) return true;
        else return false;
    }
  }

bool Variable::match( Number *N ){
    if(_assignable){
      _value = N->value() ;
      _assignable = false;
      this->Nptr = N;
      return true;
    }
    else{
        if(Nptr == N) return true;
        else return false;
    }
  }

bool Variable::match(Atom A){
    if(this->_assignable){
      this->_value = A._symbol ;
      this->_assignable = false;
      this->setX(_value);
      return true;
    }
    else{
        if(this->getX().compare(A._symbol)==0) return true;
        else return false;
    }
}

bool Variable::match(Number N){
    if(this->_assignable){
      this->_value = N.value() ;
      this->_assignable = false;
      this->setX(_value);
      return true;
    }
    else{
        if(this->getX().compare(N.value())==0) return true;
        else return false;
    }
}
<commit_msg>Delete mainVariable.cpp<commit_after><|endoftext|>


<commit_before>#include <iostream>
#include <string>
#include <vector>
#include "TRandom3.h"
#include "TCanvas.h"
#include "TFile.h"

#include "PlotUtils/MUH1D.h"
#include "PlotUtils/MUApplication.h"
#include "PlotUtils/MUPlotter.h"

using namespace std;
using namespace PlotUtils;

int tryToWrite()
{
  cout << "Create a new MUH1D.  Also create a partner." << endl;
  MUH1D* a = new MUH1D("a","This baby is going to disk", 10, 0., 10. );
  MUH1D* b = new MUH1D("a","This baby is also going to disk", 10, 0., 10. );

  cout << "Add a vertical error A wth many universes" << endl;
  a->AddVertErrorBand("ErrA" );
  b->AddVertErrorBand("ErrA" );

  cout << "Add a lateral error B with 2 universes (+/-1 sigma) to use max spread" << endl;
  a->AddLatErrorBand("ErrB" );
  b->AddLatErrorBand("ErrB" );

  cout << "Add a lateral sys error C to use max spread" << endl;
  a->AddLatErrorBand("ErrC", 5); //5 universes
  b->AddLatErrorBand("ErrC", 5); //5 universes

  //set ErrC to get its errors from the spread method manually, although spread is the default for less than 10 universes
  a->GetLatErrorBand("ErrC")->SetUseSpreadError(true);
  cout << "      ErrC has " << a->GetLatErrorBand("ErrC")->GetNHists() << " hists and UseSpreadError = " << a->GetLatErrorBand("ErrC")->GetUseSpreadError() << endl;

  // get the vector of error band names like this
  vector<string> errNames = a->GetErrorBandNames();
  cout << "MUErrorBand names: " << endl;
  for( vector<string>::iterator it = errNames.begin(); it != errNames.end(); ++it )
    cout << "         name = " << *it << endl;

  //fill 1000 universes of nonsense weights
  //these should be branches in the AnaTuple.  e.g. mc_wgt_Flux_Tertiary
  TRandom3 r;
  vector<double> weightsA;
  for( int i = 0; i < 1000; ++i )
  {
    weightsA.push_back( r.Gaus(1.,.05) ); //vertical shifts use weights centered around a CV value of 1 (same weight)
  }

  //B has asymmetrical errors.  15% up and 10% down
  const double bWeightSigmaUp   =  .15;
  const double bWeightSigmaDown = -.10;

  //only do 5 weights for C since we are using max spread.  pick something obvious here...
  vector<double> weightsC;
  for( int i = 0; i < 5; ++i )
    weightsC.push_back( -.1 + i*0.05 );

  //the lat vectors store the +/- shift from the fill value and may depend on the fill value
  vector<double> weightsLatB, weightsLatC;
  weightsLatB.reserve( 2 );
  weightsLatC.reserve(weightsC.size() );

  vector<double> weightsLatB2, weightsLatC2;
  weightsLatB2.reserve( 2 );
  weightsLatC2.reserve(weightsC.size() );

  double cvweight = 1.;
  for( int i = 0; i < 100000; ++i )
  {
    double val = r.Gaus(5,2);
    while( val < 0 )
      val = r.Gaus(5,2);

    double val2 = r.Gaus(5,2);
    while( val2 < 0 )
      val2 = r.Gaus(5,2);

    //fill the +/-1 sigma shifts
    weightsLatB[0] = val * bWeightSigmaDown;
    weightsLatB[1] = val * bWeightSigmaUp;

    weightsLatB2[0] = val2 * bWeightSigmaDown;
    weightsLatB2[1] = val2 * bWeightSigmaUp;

    for( unsigned int j = 0; j != weightsC.size(); ++j )
    {
      weightsLatC[j] = val * weightsC[j];
      weightsLatC2[j] = val2 * weightsC[j];
    }

    //fill MUH1D like you would a normal histogram
    a->Fill(val);
    b->Fill(val2);

    //fill the error bands of the MUH1D by name
    a->FillVertErrorBand( "ErrA", val, weightsA, cvweight );
    a->FillLatErrorBand( "ErrB", val, weightsLatB, cvweight );
    a->FillLatErrorBand( "ErrC", val, weightsLatC, cvweight );

    b->FillVertErrorBand( "ErrA", val2, weightsA, cvweight );
    b->FillLatErrorBand( "ErrB", val2, weightsLatB2, cvweight );
    b->FillLatErrorBand( "ErrC", val2, weightsLatC2, cvweight );
  }

  TH1D totErr = a->GetTotalError(true); //total error.  sys + stat
  TH1D totSysErr = a->GetTotalError(false); //total sys error.  no stat.
  for( int i = 0; i < a->GetNbinsX(); ++i )
  {
    cout << "bin " << i << endl;
    cout << "     val = " << a->GetBinContent(i) << endl;
    cout << "     totErr = " << totErr.GetBinContent(i) << endl;
    cout << "     totSysErr = " << totSysErr.GetBinContent(i) << endl;
  }

  TCanvas c;
  c.Divide(2,2);
  c.cd(1);
  a->Draw();
  c.cd(2);
  a->GetVertErrorBand("ErrA")->GetErrorBand(true).DrawCopy(); //get the error band from a spread in A's universes as a fraction of CV
  c.cd(3);
  a->GetLatErrorBand("ErrB")->GetErrorBand(true).DrawCopy();
  c.cd(4);
  a->GetLatErrorBand("ErrC")->GetErrorBand(true).DrawCopy();
  c.Print("canDuringWrite.png","png");

  //you can use the namespace MUPlot to get MinervaPlottingUtils
  //MultiPrint prints a canvas using this name and a comma separated list of types.
  MUPlotter muPlotter;
  muPlotter.MultiPrint( &c, "canDuringWrite", "eps,gif" );

  //draw all the universes of ErrC
  TCanvas cAll( "canDrawAllUniverses", "canDrawAllUniverses");
  a->GetLatErrorBand("ErrC")->DrawAll("HIST", true);
  muPlotter.MultiPrint( &cAll );

  //get the final result (CV + errror) and draw
  TCanvas cCVErr("canDrawCVWithError", "canDrawCVWithError");
  TH1D cvWithErr = a->GetCVHistoWithError();
  cvWithErr.Draw();
  muPlotter.MultiPrint( &cCVErr );

  //open a TFile and write the MUH1D and its MUSysErrorBands to disk
  TFile f("wroteSomething.root","recreate");
  a->Write("MyHist"); //the name in the file is MyHist
  f.Close();

  TFile f2("wroteSomethingElse.root","recreate");
  b->Write("MyHist");
  f2.Close();

  return 0;
}

int main() {
  PlotUtils::Initialize();

  return tryToWrite();

}
<commit_msg>throw fewer events<commit_after>#include <iostream>
#include <string>
#include <vector>
#include "TRandom3.h"
#include "TCanvas.h"
#include "TFile.h"

#include "PlotUtils/MUH1D.h"
#include "PlotUtils/MUApplication.h"
#include "PlotUtils/MUPlotter.h"

using namespace std;
using namespace PlotUtils;

int tryToWrite()
{
  cout << "Create a new MUH1D.  Also create a partner." << endl;
  MUH1D* a = new MUH1D("a","This baby is going to disk", 10, 0., 10. );
  MUH1D* b = new MUH1D("a","This baby is also going to disk", 10, 0., 10. );

  cout << "Add a vertical error A wth many universes" << endl;
  a->AddVertErrorBand("ErrA" );
  b->AddVertErrorBand("ErrA" );

  cout << "Add a lateral error B with 2 universes (+/-1 sigma) to use max spread" << endl;
  a->AddLatErrorBand("ErrB" );
  b->AddLatErrorBand("ErrB" );

  cout << "Add a lateral sys error C to use max spread" << endl;
  a->AddLatErrorBand("ErrC", 5); //5 universes
  b->AddLatErrorBand("ErrC", 5); //5 universes

  //set ErrC to get its errors from the spread method manually, although spread is the default for less than 10 universes
  a->GetLatErrorBand("ErrC")->SetUseSpreadError(true);
  cout << "      ErrC has " << a->GetLatErrorBand("ErrC")->GetNHists() << " hists and UseSpreadError = " << a->GetLatErrorBand("ErrC")->GetUseSpreadError() << endl;

  // get the vector of error band names like this
  vector<string> errNames = a->GetErrorBandNames();
  cout << "MUErrorBand names: " << endl;
  for( vector<string>::iterator it = errNames.begin(); it != errNames.end(); ++it )
    cout << "         name = " << *it << endl;

  //fill 1000 universes of nonsense weights
  //these should be branches in the AnaTuple.  e.g. mc_wgt_Flux_Tertiary
  TRandom3 r;
  vector<double> weightsA;
  for( int i = 0; i < 1000; ++i )
  {
    weightsA.push_back( r.Gaus(1.,.05) ); //vertical shifts use weights centered around a CV value of 1 (same weight)
  }

  //B has asymmetrical errors.  15% up and 10% down
  const double bWeightSigmaUp   =  .15;
  const double bWeightSigmaDown = -.10;

  //only do 5 weights for C since we are using max spread.  pick something obvious here...
  vector<double> weightsC;
  for( int i = 0; i < 5; ++i )
    weightsC.push_back( -.1 + i*0.05 );

  //the lat vectors store the +/- shift from the fill value and may depend on the fill value
  vector<double> weightsLatB, weightsLatC;
  weightsLatB.reserve( 2 );
  weightsLatC.reserve(weightsC.size() );

  vector<double> weightsLatB2, weightsLatC2;
  weightsLatB2.reserve( 2 );
  weightsLatC2.reserve(weightsC.size() );

  const size_t nEntries = 10000;
  double cvweight = 1.;
  for( size_t i = 0; i != nEntries; ++i )
  {
    if( 0 == i%1000)
      cout << Form("Filling histograms with entry %zu of %zu", i, nEntries) << endl;
    double val = r.Gaus(5,2);
    while( val < 0 )
      val = r.Gaus(5,2);

    double val2 = r.Gaus(5,2);
    while( val2 < 0 )
      val2 = r.Gaus(5,2);

    //fill the +/-1 sigma shifts
    weightsLatB[0] = val * bWeightSigmaDown;
    weightsLatB[1] = val * bWeightSigmaUp;

    weightsLatB2[0] = val2 * bWeightSigmaDown;
    weightsLatB2[1] = val2 * bWeightSigmaUp;

    for( unsigned int j = 0; j != weightsC.size(); ++j )
    {
      weightsLatC[j] = val * weightsC[j];
      weightsLatC2[j] = val2 * weightsC[j];
    }

    //fill MUH1D like you would a normal histogram
    a->Fill(val);
    b->Fill(val2);

    //fill the error bands of the MUH1D by name
    a->FillVertErrorBand( "ErrA", val, weightsA, cvweight );
    a->FillLatErrorBand( "ErrB", val, weightsLatB, cvweight );
    a->FillLatErrorBand( "ErrC", val, weightsLatC, cvweight );

    b->FillVertErrorBand( "ErrA", val2, weightsA, cvweight );
    b->FillLatErrorBand( "ErrB", val2, weightsLatB2, cvweight );
    b->FillLatErrorBand( "ErrC", val2, weightsLatC2, cvweight );
  }

  TH1D totErr = a->GetTotalError(true); //total error.  sys + stat
  TH1D totSysErr = a->GetTotalError(false); //total sys error.  no stat.
  for( int i = 0; i < a->GetNbinsX(); ++i )
  {
    cout << "bin " << i << endl;
    cout << "     val = " << a->GetBinContent(i) << endl;
    cout << "     totErr = " << totErr.GetBinContent(i) << endl;
    cout << "     totSysErr = " << totSysErr.GetBinContent(i) << endl;
  }

  TCanvas c;
  c.Divide(2,2);
  c.cd(1);
  a->Draw();
  c.cd(2);
  a->GetVertErrorBand("ErrA")->GetErrorBand(true).DrawCopy(); //get the error band from a spread in A's universes as a fraction of CV
  c.cd(3);
  a->GetLatErrorBand("ErrB")->GetErrorBand(true).DrawCopy();
  c.cd(4);
  a->GetLatErrorBand("ErrC")->GetErrorBand(true).DrawCopy();
  c.Print("canDuringWrite.png","png");

  //you can use the namespace MUPlot to get MinervaPlottingUtils
  //MultiPrint prints a canvas using this name and a comma separated list of types.
  MUPlotter muPlotter;
  muPlotter.MultiPrint( &c, "canDuringWrite", "eps,gif" );

  //draw all the universes of ErrC
  TCanvas cAll( "canDrawAllUniverses", "canDrawAllUniverses");
  a->GetLatErrorBand("ErrC")->DrawAll("HIST", true);
  muPlotter.MultiPrint( &cAll );

  //get the final result (CV + errror) and draw
  TCanvas cCVErr("canDrawCVWithError", "canDrawCVWithError");
  TH1D cvWithErr = a->GetCVHistoWithError();
  cvWithErr.Draw();
  muPlotter.MultiPrint( &cCVErr );

  //open a TFile and write the MUH1D and its MUSysErrorBands to disk
  TFile f("wroteSomething.root","recreate");
  a->Write("MyHist"); //the name in the file is MyHist
  f.Close();

  TFile f2("wroteSomethingElse.root","recreate");
  b->Write("MyHist");
  f2.Close();

  return 0;
}

int main() {
  PlotUtils::Initialize();

  return tryToWrite();

}
<|endoftext|>


<commit_before>#if 0
set -e -x
g++ sessionXrandr.cc -lXrandr -lX11 -o sxr
exit 0
#endif

#include <X11/extensions/Xrandr.h>
#include <iostream>
#include <stdlib.h>
#include <unistd.h>
#include <signal.h>

#include "sessionManager.h"

int s_randr_event_type = 0;
int randr_error_base;

extern "C" int
pfkSessionXrandr_main()
{
    Display * disp;
    Window rootWindow = None;
    Drawable win;
    bool done = false;
    int randr_mask;
    int firstScreen = 0;
    union { int i; unsigned int ui; } ignore;
    pid_t pid;

    char * pidVar = getenv(PFK_SESS_MGR_ENV_VAR_NAME);
    if (pidVar == NULL)
    {
        std::cerr << "error: should be invoked from within pfkSessionMgr\n";
        return 1;
    }
    pid = strtol(pidVar, NULL, 10);

    disp = XOpenDisplay(NULL);

    XRRQueryExtension(disp, &s_randr_event_type, &randr_error_base);

    win = RootWindow(disp, firstScreen);

    XGetGeometry(disp, win, &rootWindow,
                 &ignore.i, &ignore.i,
                 &ignore.ui, &ignore.ui,
                 &ignore.ui, &ignore.ui);

    randr_mask = RRScreenChangeNotifyMask;
# ifdef RRCrtcChangeNotifyMask
    randr_mask |= RRCrtcChangeNotifyMask;
# endif
# ifdef RROutputChangeNotifyMask
    randr_mask |= RROutputChangeNotifyMask;
# endif
# ifdef RROutputPropertyNotifyMask
    randr_mask |= RROutputPropertyNotifyMask;
# endif

    XRRSelectInput(disp, rootWindow, randr_mask);

    while (!done)
    {
        XEvent e;
        XNextEvent(disp, &e);
        if (e.type == s_randr_event_type)
        {
            std::cout << "XRANDR event!\n";
            sleep(1);
            kill(pid, PFK_SESS_MGR_RESTART_SIG);
        }
    }

    return 0;
}
<commit_msg>sessionXrandr needed Xlib.h on rhel5.4<commit_after>#if 0
set -e -x
g++ sessionXrandr.cc -lXrandr -lX11 -o sxr
exit 0
#endif

#include <X11/Xlib.h>
#include <X11/extensions/Xrandr.h>
#include <iostream>
#include <stdlib.h>
#include <unistd.h>
#include <signal.h>

#include "sessionManager.h"

int s_randr_event_type = 0;
int randr_error_base;

extern "C" int
pfkSessionXrandr_main()
{
    Display * disp;
    Window rootWindow = None;
    Drawable win;
    bool done = false;
    int randr_mask;
    int firstScreen = 0;
    union { int i; unsigned int ui; } ignore;
    pid_t pid;

    char * pidVar = getenv(PFK_SESS_MGR_ENV_VAR_NAME);
    if (pidVar == NULL)
    {
        std::cerr << "error: should be invoked from within pfkSessionMgr\n";
        return 1;
    }
    pid = strtol(pidVar, NULL, 10);

    disp = XOpenDisplay(NULL);

    XRRQueryExtension(disp, &s_randr_event_type, &randr_error_base);

    win = RootWindow(disp, firstScreen);

    XGetGeometry(disp, win, &rootWindow,
                 &ignore.i, &ignore.i,
                 &ignore.ui, &ignore.ui,
                 &ignore.ui, &ignore.ui);

    randr_mask = RRScreenChangeNotifyMask;
# ifdef RRCrtcChangeNotifyMask
    randr_mask |= RRCrtcChangeNotifyMask;
# endif
# ifdef RROutputChangeNotifyMask
    randr_mask |= RROutputChangeNotifyMask;
# endif
# ifdef RROutputPropertyNotifyMask
    randr_mask |= RROutputPropertyNotifyMask;
# endif

    XRRSelectInput(disp, rootWindow, randr_mask);

    while (!done)
    {
        XEvent e;
        XNextEvent(disp, &e);
        if (e.type == s_randr_event_type)
        {
            std::cout << "XRANDR event!\n";
            sleep(1);
            kill(pid, PFK_SESS_MGR_RESTART_SIG);
        }
    }

    return 0;
}
<|endoftext|>


<commit_before>#include "mmcore/CoreInstance.h"
#include "mmcore/MegaMolGraph.h"

#include "mmcore/utility/log/Log.h"
#include "mmcore/utility/log/StreamTarget.h"

#include "AbstractFrontendService.hpp"
#include "FrontendServiceCollection.hpp"
#include "GUI_Service.hpp"
#include "OpenGL_GLFW_Service.hpp"
#include "Lua_Service_Wrapper.hpp"

#include "mmcore/view/AbstractView_EventConsumption.h"

#include <cxxopts.hpp>
#include "mmcore/LuaAPI.h"

// Filesystem
#if defined(_HAS_CXX17) || ((defined(_MSC_VER) && (_MSC_VER > 1916))) // C++2017 or since VS2019
#    include <filesystem>
namespace stdfs = std::filesystem;
#else
// WINDOWS
#    ifdef _WIN32
#        include <filesystem>
namespace stdfs = std::experimental::filesystem;
#    else
// LINUX
#        include <experimental/filesystem>
namespace stdfs = std::experimental::filesystem;
#    endif
#endif

struct CLIConfig {
    std::vector<std::string> project_files;
    std::string lua_host_address = "tcp://127.0.0.1:33333";
    bool load_example_project = true;
};

CLIConfig handle_cli_inputs(int argc, char* argv[]);

bool set_up_example_graph(megamol::core::MegaMolGraph& graph);

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

    auto config = handle_cli_inputs(argc, argv);

    // setup log
    megamol::core::utility::log::Log::DefaultLog.SetLogFileName(static_cast<const char*>(NULL), false);
    megamol::core::utility::log::Log::DefaultLog.SetLevel(megamol::core::utility::log::Log::LEVEL_ALL);
    megamol::core::utility::log::Log::DefaultLog.SetEchoLevel(megamol::core::utility::log::Log::LEVEL_ALL);
    megamol::core::utility::log::Log::DefaultLog.SetEchoTarget(
        std::make_shared<megamol::core::utility::log::StreamTarget>(
            std::cout, megamol::core::utility::log::Log::LEVEL_ALL));

    megamol::core::CoreInstance core;
    core.Initialise(false); // false makes core not start his own lua service (else we collide on default port)

    const megamol::core::factories::ModuleDescriptionManager& moduleProvider = core.GetModuleDescriptionManager();
    const megamol::core::factories::CallDescriptionManager& callProvider = core.GetCallDescriptionManager();

    megamol::frontend::OpenGL_GLFW_Service gl_service;
    megamol::frontend::OpenGL_GLFW_Service::Config openglConfig;
    openglConfig.windowTitlePrefix = openglConfig.windowTitlePrefix + " ~ Main3000";
    openglConfig.versionMajor = 4;
    openglConfig.versionMinor = 5;
    gl_service.setPriority(1);

    megamol::frontend::GUI_Service gui_service;
    megamol::frontend::GUI_Service::Config guiConfig;
    guiConfig.imgui_api = megamol::frontend::GUI_Service::ImGuiAPI::OPEN_GL;
    guiConfig.core_instance = &core;
    // priority must be higher than priority of gl_service (=1)
    // service callbacks get called in order of priority of the service.
    // postGraphRender() and close() are called in reverse order of priorities.
    gui_service.setPriority(23);

    megamol::core::MegaMolGraph graph(core, moduleProvider, callProvider);

    bool lua_imperative_only = false; // allow mmFlush, mmList* and mmGetParam*
    megamol::core::LuaAPI lua_api(graph, lua_imperative_only);
    megamol::frontend::Lua_Service_Wrapper lua_service_wrapper;
    megamol::frontend::Lua_Service_Wrapper::Config luaConfig;
    luaConfig.lua_api_ptr = &lua_api;
    luaConfig.host_address = config.lua_host_address;
    lua_service_wrapper.setPriority(0);

    // the main loop is organized around services that can 'do something' in different parts of the main loop
    // a service is something that implements the AbstractFrontendService interface from 'megamol\frontend_services\include'
    // a central mechanism that allows services to communicate with each other and with graph modules are _resources_
    // (see ModuleResource in 'megamol\module_resources\include') services may provide resources to the system and they may
    // request resources they need themselves for functioning. think of a resource as a struct (or some type of your
    // choice) that gets wrapped by a helper structure and gets a name attached to it. the fronend makes sure (at least
    // attempts to) to hand each service the resources it requested, or else fail execution of megamol with an error
    // message. resource assignment is done by the name of the resource, so this is a very loose interface based on
    // trust. type safety of resources is ensured in the sense that extracting the wrong type from a ModuleResource will
    // lead to an unhandled bad type cast exception, leading to the shutdown of megamol.
    bool run_megamol = true;
    megamol::frontend::FrontendServiceCollection services;
    services.add(gl_service, &openglConfig);
    services.add(gui_service, &guiConfig);
    services.add(lua_service_wrapper, &luaConfig);

    // TODO: cinematic
    // => explicit FBOs!
    // TODO: screenshooter
    // => do or dont screenshot GUI, depending on ...

    const bool init_ok = services.init(); // runs init(config_ptr) on all services with provided config sructs

    if (!init_ok) {
        std::cout << "ERROR: some frontend service could not be initialized successfully. abort. " << std::endl;
        services.close();
        return 1;
    }

    // graph is also a resource that may be accessed by services
    // TODO: how to solve const and non-const resources?
    // TODO: graph manipulation during execution of graph modules is problematic, undefined?
    services.getProvidedResources().push_back({"MegaMolGraph", graph});

    // proof of concept: a resource that returns a list of names of available resources
    // used by Lua Wrapper and LuaAPI to return list of available resources via remoteconsole
    const std::function<std::vector<std::string>()> resource_lister = [&]() -> std::vector<std::string> {
        std::vector<std::string> resources;
        for (auto& resource : services.getProvidedResources()) {
            resources.push_back(resource.getIdentifier());
        }
        return resources;
    };
    services.getProvidedResources().push_back({"FrontendResourcesList", resource_lister});

    // distribute registered resources among registered services.
    const bool resources_ok = services.assignRequestedResources();
    // for each service we call their resource callbacks here:
    //    std::vector<ModuleResource>& getProvidedResources()
    //    std::vector<std::string> getRequestedResourceNames()
    //    void setRequestedResources(std::vector<ModuleResource>& resources)
    if (!resources_ok) {
        std::cout << "ERROR: frontend could not assign requested service resources. abort. " << std::endl;
        run_megamol = false;
    }

    auto module_resources = services.getProvidedResources();
    graph.AddModuleDependencies(module_resources);

    uint32_t frameID = 0;
    const auto render_next_frame = [&]() -> bool {
        // set global Frame Counter
        guiConfig.core_instance->SetFrameID(frameID++);

        // services: receive inputs (GLFW poll events [keyboard, mouse, window], network, lua)
        services.updateProvidedResources();

        // aka simulation step
        // services: digest new inputs via ModuleResources (GUI digest user inputs, lua digest inputs, network ?)
        // e.g. graph updates, module and call creation via lua and GUI happen here
        services.digestChangedRequestedResources();

        // services tell us wheter we should shut down megamol
        // TODO: service needs to mark intself as shutdown by calling this->setShutdown() during
        // digestChangedRequestedResources()
        if (services.shouldShutdown())
            return false;

        {                              // put this in render function so LUA can call it
            services.preGraphRender(); // e.g. start frame timer, clear render buffers

            graph.RenderNextFrame(); // executes graph views, those digest input events like keyboard/mouse, then render

            services.postGraphRender(); // render GUI, glfw swap buffers, stop frame timer
            // problem: guarantee correct order of pre- and post-render jobs, i.e. render gui before swapping buffers
        }

        services.resetProvidedResources(); // clear buffers holding glfw keyboard+mouse input

        return true;
    };

    // lua can issue rendering of frames
    lua_api.setFlushCallback(render_next_frame);

    // load project files via lua
    for (auto& file : config.project_files) {
	    std::string result;
        if (!lua_api.RunFile(file, result)) {
            std::cout << "Project file \"" << file << "\" did not execute correctly: " << result << std::endl;
	        run_megamol = false;
        }
    }
	if (config.load_example_project && config.project_files.empty()) {
		const bool graph_ok = set_up_example_graph(graph); // fill graph with modules and calls
		if (!graph_ok) {
		    std::cout << "ERROR: frontend could not build graph. abort. " << std::endl;
		    run_megamol = false;
		}
    }

    while (run_megamol) {
        run_megamol = render_next_frame();
    }

    // close glfw context, network connections, other system resources
    services.close();

    // clean up modules, calls in graph
    // TODO: implement graph destructor

    return 0;
}

CLIConfig handle_cli_inputs(int argc, char* argv[]) {
    CLIConfig config;

    cxxopts::Options options(argv[0], "MegaMol Frontend 3000");

    // parse input project files
    options.positional_help("<additional project files>");
    options.add_options()
        ("project-files", "projects to load", cxxopts::value<std::vector<std::string>>())
        ("host", "address of lua host server, default: "+config.lua_host_address, cxxopts::value<std::string>())
        ("noexample", "dont load minimal spheres example project", cxxopts::value<bool>())
        ;
    options.parse_positional({"project-files"});

    auto parsed_options = options.parse(argc, argv);
    std::string res;

	// verify project files exist in file system
    if (parsed_options.count("project-files")) {
        const auto& v = parsed_options["project-files"].as<std::vector<std::string>>();
        for (const auto& p : v) {
            if (!stdfs::exists(p)) {
                std::cout << "Project file \"" << p << "\" does not exist!" << std::endl;
                std::exit(1);
            }
        }

        config.project_files = v;
    }

    if (parsed_options.count("host")) {
        config.lua_host_address = parsed_options["host"].as<std::string>();
    }

    if (parsed_options.count("noexample")) {
        config.load_example_project = !parsed_options["noexample"].as<bool>();
    }

    return config;
}

bool set_up_example_graph(megamol::core::MegaMolGraph& graph) {
#define check(X) \
    if (!X) return false;

    check(graph.CreateModule("View3D_2", "::view"));
    check(graph.CreateModule("SphereRenderer", "::spheres"));
    check(graph.CreateModule("TestSpheresDataSource", "::datasource"));
    check(graph.CreateCall("CallRender3D_2", "::view::rendering", "::spheres::rendering"));
    check(graph.CreateCall("MultiParticleDataCall", "::spheres::getdata", "::datasource::getData"));

    check(graph.SetGraphEntryPoint("::view", megamol::core::view::get_gl_view_runtime_resources_requests(), megamol::core::view::view_rendering_execution));

    std::string parameter_name("::datasource::numSpheres");
    auto parameterPtr = graph.FindParameter(parameter_name);
    if (parameterPtr) {
        parameterPtr->ParseValue("23");
    } else {
        std::cout << "ERROR: could not find parameter: " << parameter_name << std::endl;
        return false;
    }

    return true;
}
<commit_msg>main3000: allow disabling GL KHR debug messages<commit_after>#include "mmcore/CoreInstance.h"
#include "mmcore/MegaMolGraph.h"

#include "mmcore/utility/log/Log.h"
#include "mmcore/utility/log/StreamTarget.h"

#include "AbstractFrontendService.hpp"
#include "FrontendServiceCollection.hpp"
#include "GUI_Service.hpp"
#include "OpenGL_GLFW_Service.hpp"
#include "Lua_Service_Wrapper.hpp"

#include "mmcore/view/AbstractView_EventConsumption.h"

#include <cxxopts.hpp>
#include "mmcore/LuaAPI.h"

// Filesystem
#if defined(_HAS_CXX17) || ((defined(_MSC_VER) && (_MSC_VER > 1916))) // C++2017 or since VS2019
#    include <filesystem>
namespace stdfs = std::filesystem;
#else
// WINDOWS
#    ifdef _WIN32
#        include <filesystem>
namespace stdfs = std::experimental::filesystem;
#    else
// LINUX
#        include <experimental/filesystem>
namespace stdfs = std::experimental::filesystem;
#    endif
#endif

struct CLIConfig {
    std::vector<std::string> project_files;
    std::string lua_host_address = "tcp://127.0.0.1:33333";
    bool load_example_project = true;
    bool opengl_khr_debug = true;
};

CLIConfig handle_cli_inputs(int argc, char* argv[]);

bool set_up_example_graph(megamol::core::MegaMolGraph& graph);

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

    auto config = handle_cli_inputs(argc, argv);

    // setup log
    megamol::core::utility::log::Log::DefaultLog.SetLogFileName(static_cast<const char*>(NULL), false);
    megamol::core::utility::log::Log::DefaultLog.SetLevel(megamol::core::utility::log::Log::LEVEL_ALL);
    megamol::core::utility::log::Log::DefaultLog.SetEchoLevel(megamol::core::utility::log::Log::LEVEL_ALL);
    megamol::core::utility::log::Log::DefaultLog.SetEchoTarget(
        std::make_shared<megamol::core::utility::log::StreamTarget>(
            std::cout, megamol::core::utility::log::Log::LEVEL_ALL));

    megamol::core::CoreInstance core;
    core.Initialise(false); // false makes core not start his own lua service (else we collide on default port)

    const megamol::core::factories::ModuleDescriptionManager& moduleProvider = core.GetModuleDescriptionManager();
    const megamol::core::factories::CallDescriptionManager& callProvider = core.GetCallDescriptionManager();

    megamol::frontend::OpenGL_GLFW_Service gl_service;
    megamol::frontend::OpenGL_GLFW_Service::Config openglConfig;
    openglConfig.windowTitlePrefix = openglConfig.windowTitlePrefix + " ~ Main3000";
    openglConfig.versionMajor = 4;
    openglConfig.versionMinor = 5;
    openglConfig.enableKHRDebug = config.opengl_khr_debug;
    gl_service.setPriority(1);

    megamol::frontend::GUI_Service gui_service;
    megamol::frontend::GUI_Service::Config guiConfig;
    guiConfig.imgui_api = megamol::frontend::GUI_Service::ImGuiAPI::OPEN_GL;
    guiConfig.core_instance = &core;
    // priority must be higher than priority of gl_service (=1)
    // service callbacks get called in order of priority of the service.
    // postGraphRender() and close() are called in reverse order of priorities.
    gui_service.setPriority(23);

    megamol::core::MegaMolGraph graph(core, moduleProvider, callProvider);

    bool lua_imperative_only = false; // allow mmFlush, mmList* and mmGetParam*
    megamol::core::LuaAPI lua_api(graph, lua_imperative_only);
    megamol::frontend::Lua_Service_Wrapper lua_service_wrapper;
    megamol::frontend::Lua_Service_Wrapper::Config luaConfig;
    luaConfig.lua_api_ptr = &lua_api;
    luaConfig.host_address = config.lua_host_address;
    lua_service_wrapper.setPriority(0);

    // the main loop is organized around services that can 'do something' in different parts of the main loop
    // a service is something that implements the AbstractFrontendService interface from 'megamol\frontend_services\include'
    // a central mechanism that allows services to communicate with each other and with graph modules are _resources_
    // (see ModuleResource in 'megamol\module_resources\include') services may provide resources to the system and they may
    // request resources they need themselves for functioning. think of a resource as a struct (or some type of your
    // choice) that gets wrapped by a helper structure and gets a name attached to it. the fronend makes sure (at least
    // attempts to) to hand each service the resources it requested, or else fail execution of megamol with an error
    // message. resource assignment is done by the name of the resource, so this is a very loose interface based on
    // trust. type safety of resources is ensured in the sense that extracting the wrong type from a ModuleResource will
    // lead to an unhandled bad type cast exception, leading to the shutdown of megamol.
    bool run_megamol = true;
    megamol::frontend::FrontendServiceCollection services;
    services.add(gl_service, &openglConfig);
    services.add(gui_service, &guiConfig);
    services.add(lua_service_wrapper, &luaConfig);

    // TODO: cinematic
    // => explicit FBOs!
    // TODO: screenshooter
    // => do or dont screenshot GUI, depending on ...

    const bool init_ok = services.init(); // runs init(config_ptr) on all services with provided config sructs

    if (!init_ok) {
        std::cout << "ERROR: some frontend service could not be initialized successfully. abort. " << std::endl;
        services.close();
        return 1;
    }

    // graph is also a resource that may be accessed by services
    // TODO: how to solve const and non-const resources?
    // TODO: graph manipulation during execution of graph modules is problematic, undefined?
    services.getProvidedResources().push_back({"MegaMolGraph", graph});

    // proof of concept: a resource that returns a list of names of available resources
    // used by Lua Wrapper and LuaAPI to return list of available resources via remoteconsole
    const std::function<std::vector<std::string>()> resource_lister = [&]() -> std::vector<std::string> {
        std::vector<std::string> resources;
        for (auto& resource : services.getProvidedResources()) {
            resources.push_back(resource.getIdentifier());
        }
        return resources;
    };
    services.getProvidedResources().push_back({"FrontendResourcesList", resource_lister});

    // distribute registered resources among registered services.
    const bool resources_ok = services.assignRequestedResources();
    // for each service we call their resource callbacks here:
    //    std::vector<ModuleResource>& getProvidedResources()
    //    std::vector<std::string> getRequestedResourceNames()
    //    void setRequestedResources(std::vector<ModuleResource>& resources)
    if (!resources_ok) {
        std::cout << "ERROR: frontend could not assign requested service resources. abort. " << std::endl;
        run_megamol = false;
    }

    auto module_resources = services.getProvidedResources();
    graph.AddModuleDependencies(module_resources);

    uint32_t frameID = 0;
    const auto render_next_frame = [&]() -> bool {
        // set global Frame Counter
        guiConfig.core_instance->SetFrameID(frameID++);

        // services: receive inputs (GLFW poll events [keyboard, mouse, window], network, lua)
        services.updateProvidedResources();

        // aka simulation step
        // services: digest new inputs via ModuleResources (GUI digest user inputs, lua digest inputs, network ?)
        // e.g. graph updates, module and call creation via lua and GUI happen here
        services.digestChangedRequestedResources();

        // services tell us wheter we should shut down megamol
        // TODO: service needs to mark intself as shutdown by calling this->setShutdown() during
        // digestChangedRequestedResources()
        if (services.shouldShutdown())
            return false;

        {                              // put this in render function so LUA can call it
            services.preGraphRender(); // e.g. start frame timer, clear render buffers

            graph.RenderNextFrame(); // executes graph views, those digest input events like keyboard/mouse, then render

            services.postGraphRender(); // render GUI, glfw swap buffers, stop frame timer
            // problem: guarantee correct order of pre- and post-render jobs, i.e. render gui before swapping buffers
        }

        services.resetProvidedResources(); // clear buffers holding glfw keyboard+mouse input

        return true;
    };

    // lua can issue rendering of frames
    lua_api.setFlushCallback(render_next_frame);

    // load project files via lua
    for (auto& file : config.project_files) {
	    std::string result;
        if (!lua_api.RunFile(file, result)) {
            std::cout << "Project file \"" << file << "\" did not execute correctly: " << result << std::endl;
	        run_megamol = false;
        }
    }
	if (config.load_example_project && config.project_files.empty()) {
		const bool graph_ok = set_up_example_graph(graph); // fill graph with modules and calls
		if (!graph_ok) {
		    std::cout << "ERROR: frontend could not build graph. abort. " << std::endl;
		    run_megamol = false;
		}
    }

    while (run_megamol) {
        run_megamol = render_next_frame();
    }

    // close glfw context, network connections, other system resources
    services.close();

    // clean up modules, calls in graph
    // TODO: implement graph destructor

    return 0;
}

CLIConfig handle_cli_inputs(int argc, char* argv[]) {
    CLIConfig config;

    cxxopts::Options options(argv[0], "MegaMol Frontend 3000");

    // parse input project files
    options.positional_help("<additional project files>");
    options.add_options()
        ("project-files", "projects to load", cxxopts::value<std::vector<std::string>>())
        ("host", "address of lua host server, default: "+config.lua_host_address, cxxopts::value<std::string>())
        ("noexample", "dont load minimal spheres example project", cxxopts::value<bool>())
        ("nokhrdebug", "disable OpenGL KHR debug messages", cxxopts::value<bool>())
        ;
    options.parse_positional({"project-files"});

    auto parsed_options = options.parse(argc, argv);
    std::string res;

	// verify project files exist in file system
    if (parsed_options.count("project-files")) {
        const auto& v = parsed_options["project-files"].as<std::vector<std::string>>();
        for (const auto& p : v) {
            if (!stdfs::exists(p)) {
                std::cout << "Project file \"" << p << "\" does not exist!" << std::endl;
                std::exit(1);
            }
        }

        config.project_files = v;
    }

    if (parsed_options.count("host")) {
        config.lua_host_address = parsed_options["host"].as<std::string>();
    }

    if (parsed_options.count("noexample")) {
        config.load_example_project = !parsed_options["noexample"].as<bool>();
    }

    if (parsed_options.count("nokhrdebug")) {
        config.opengl_khr_debug = !parsed_options["nokhrdebug"].as<bool>();
    }
    return config;
}

bool set_up_example_graph(megamol::core::MegaMolGraph& graph) {
#define check(X) \
    if (!X) return false;

    check(graph.CreateModule("View3D_2", "::view"));
    check(graph.CreateModule("SphereRenderer", "::spheres"));
    check(graph.CreateModule("TestSpheresDataSource", "::datasource"));
    check(graph.CreateCall("CallRender3D_2", "::view::rendering", "::spheres::rendering"));
    check(graph.CreateCall("MultiParticleDataCall", "::spheres::getdata", "::datasource::getData"));

    check(graph.SetGraphEntryPoint("::view", megamol::core::view::get_gl_view_runtime_resources_requests(), megamol::core::view::view_rendering_execution));

    std::string parameter_name("::datasource::numSpheres");
    auto parameterPtr = graph.FindParameter(parameter_name);
    if (parameterPtr) {
        parameterPtr->ParseValue("23");
    } else {
        std::cout << "ERROR: could not find parameter: " << parameter_name << std::endl;
        return false;
    }

    return true;
}
<|endoftext|>


<commit_before>#include "menuscreenstate.hpp"

MenuScreenState::MenuScreenState()
{
    m_sousmenu.setPosition(sf::Vector2f(50, 50));
    m_sousmenu.addElement(new PushButton([](){}, "Play"));
    m_sousmenu.addElement(new PushButton([](){}, "Levels"));
    m_sousmenu.addElement(new PushButton([](){}, "Quit"));
    m_sousmenu.addElement(new Checkbox([](bool){}, true, "Quit"));
    m_sousmenu.addElement(new MultiChoice([](int){}, 0, {"Test1", "Test2"}));

    m_sousmenu.select(0);

    m_view.reset(sf::FloatRect(0, 0, 800, 600));

    m_view.setSize(800, 600);
    m_background_texture.loadFromFile("background.png");

    m_background.setTexture(m_background_texture);
    m_background.setScale(800.0f / m_background.getLocalBounds().width,
			  600.0f / m_background.getLocalBounds().height);

    if (!m_music.openFromFile("Under_the_bed_-_menu.wav"))
	std::cout << "Can't load menu's music." << std::endl; // error
    m_music.setLoop(true);
    m_music.play();
}

void MenuScreenState::event(const sf::RenderTarget& target, const sf::Event& event)
{
    m_sousmenu.event(event);
}

void MenuScreenState::render(sf::RenderTarget& target)
{
    target.setView(m_view);

    target.draw(m_background);

    m_sousmenu.render(target);
}

void MenuScreenState::update(const sf::Time& time)
{

}
<commit_msg>Add brutal quit button.<commit_after>#include "menuscreenstate.hpp"
#include "messagebus.hpp"
#include "gamemessage.hpp"

MenuScreenState::MenuScreenState()
{
    m_sousmenu.setPosition(sf::Vector2f(50, 50));
    m_sousmenu.addElement(new PushButton([](){}, "Play"));
    m_sousmenu.addElement(new PushButton([](){}, "Levels"));
    m_sousmenu.addElement(new PushButton([](){
	MessageBus<ScreenMessage>::getBus()->push(ScreenMessage::Push(ScreenState::Quit));
    }, "Quit"));
    m_sousmenu.addElement(new Checkbox([](bool){}, true, "Quit"));
    m_sousmenu.addElement(new MultiChoice([](int){}, 0, {"Test1", "Test2"}));

    m_sousmenu.select(0);

    m_view.reset(sf::FloatRect(0, 0, 800, 600));

    m_view.setSize(800, 600);
    m_background_texture.loadFromFile("background.png");

    m_background.setTexture(m_background_texture);
    m_background.setScale(800.0f / m_background.getLocalBounds().width,
			  600.0f / m_background.getLocalBounds().height);

    if (!m_music.openFromFile("Under_the_bed_-_menu.wav"))
	std::cout << "Can't load menu's music." << std::endl; // error
    m_music.setLoop(true);
    m_music.play();
}

void MenuScreenState::event(const sf::RenderTarget& target, const sf::Event& event)
{
    m_sousmenu.event(event);
}

void MenuScreenState::render(sf::RenderTarget& target)
{
    target.setView(m_view);

    target.draw(m_background);

    m_sousmenu.render(target);
}

void MenuScreenState::update(const sf::Time& time)
{

}
<|endoftext|>


<commit_before>#include "NavierStokesSolver.h"

float dt = 1.0;

void ProcessGrid(Grid grid)
{
    float D, B, dp;

    for each (auto cell in grid.Cells)
    {
        D = ComputeDivergence(cell);
        B = ComputeBeta(cell);

        dp = ComputeDeltaPressure(B, D);

        cell.U += (dt / cell.Width) * dp;
        cell.V += (dt / cell.Height) * dp;
        cell.W += (dt / cell.Depth) * dp;

        cell.Pressure += dp;
    }
}

float ComputeDivergence(FluidCell cell)
{
    auto Dx = (1.0 / cell.Width) * cell.U;
    auto Dy = (1.0 / cell.Height) * cell.V;
    auto Dz = (1.0 / cell.Depth) * cell.W;

    return -(Dx + Dy + Dz);
}

float ComputeBeta(FluidCell cell)
{
    auto i_dx2 = 1 / pow(cell.Width, 2);
    auto i_dy2 = 1 / pow(cell.Height, 2);
    auto i_dz2 = 1 / pow(cell.Depth, 2);

    auto denom = (2 * dt) / (i_dx2 + i_dy2 + i_dz2);

    return BETA_0 / denom;
}

float ComputeDeltaPressure(float beta, float divergence)
{
    return beta * divergence;
}
<commit_msg>Added recursive definition to smooth the computation.<commit_after>#include "NavierStokesSolver.h"

float dt = 1.0;

void ProcessGrid(Grid grid)
{
    float D, B, dp;

    auto needsReprocessing = false;

    for each (auto cell in grid.Cells)
    {
        D = ComputeDivergence(cell);
        B = ComputeBeta(cell);

        dp = ComputeDeltaPressure(B, D);

        cell.U += (dt / cell.Width) * dp;
        cell.V += (dt / cell.Height) * dp;
        cell.W += (dt / cell.Depth) * dp;

        cell.Pressure += dp;

        if (abs(D) > MIN_DIVERGENCE)
            needsReprocessing = true;
    }

    if (needsReprocessing)
        ProcessGrid(grid);
}

float ComputeDivergence(FluidCell cell)
{
    auto Dx = (1.0 / cell.Width) * cell.U;
    auto Dy = (1.0 / cell.Height) * cell.V;
    auto Dz = (1.0 / cell.Depth) * cell.W;

    return -(Dx + Dy + Dz);
}

float ComputeBeta(FluidCell cell)
{
    auto i_dx2 = 1 / pow(cell.Width, 2);
    auto i_dy2 = 1 / pow(cell.Height, 2);
    auto i_dz2 = 1 / pow(cell.Depth, 2);

    auto denom = (2 * dt) / (i_dx2 + i_dy2 + i_dz2);

    return BETA_0 / denom;
}

float ComputeDeltaPressure(float beta, float divergence)
{
    return beta * divergence;
}
<|endoftext|>


<commit_before>// Copyright 2017 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     https://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 "google/cloud/bigtable/internal/readrowsparser.h"
#include "google/cloud/grpc_error_delegate.h"

namespace google {
namespace cloud {
namespace bigtable {
GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_BEGIN
namespace internal {
using ::google::bigtable::v2::ReadRowsResponse_CellChunk;

// NOLINTNEXTLINE(readability-function-cognitive-complexity)
void ReadRowsParser::HandleChunk(ReadRowsResponse_CellChunk chunk,
                                 grpc::Status& status) {
  if (end_of_stream_) {
    status = grpc::Status(grpc::StatusCode::INTERNAL,
                          "HandleChunk after end of stream");
    return;
  }
  if (HasNext()) {
    status = grpc::Status(grpc::StatusCode::INTERNAL,
                          "HandleChunk called before taking the previous row");
    return;
  }

  if (!chunk.row_key().empty()) {
    if (CompareRowKey(last_seen_row_key_, chunk.row_key()) >= 0) {
      status = grpc::Status(grpc::StatusCode::INTERNAL,
                            "Row keys are expected in increasing order");
      return;
    }
    using std::swap;
    swap(*chunk.mutable_row_key(), cell_.row);
  }

  if (chunk.has_family_name()) {
    if (!chunk.has_qualifier()) {
      status = grpc::Status(grpc::StatusCode::INTERNAL,
                            "New column family must specify qualifier");
      return;
    }
    using std::swap;
    swap(*chunk.mutable_family_name()->mutable_value(), cell_.family);
  }

  if (chunk.has_qualifier()) {
    using std::swap;
    swap(*chunk.mutable_qualifier()->mutable_value(), cell_.column);
  }

  if (cell_first_chunk_) {
    cell_.timestamp = chunk.timestamp_micros();
  }

  std::move(chunk.mutable_labels()->begin(), chunk.mutable_labels()->end(),
            std::back_inserter(cell_.labels));

  if (cell_first_chunk_) {
    // Most common case, move the value
    using std::swap;
    swap(*chunk.mutable_value(), cell_.value);
  } else {
    internal::AppendCellValue(cell_.value, chunk.value());
  }

  cell_first_chunk_ = false;

  // This is a hint we get about the total size, use it to save some memory
  // allocations.
  if (chunk.value_size() > 0) {
    internal::ReserveCellValue(cell_.value,
                               static_cast<std::size_t>(chunk.value_size()));
  }

  // Last chunk in the cell has zero for value size
  if (chunk.value_size() == 0) {
    if (cells_.empty()) {
      if (cell_.row.empty()) {
        status = grpc::Status(grpc::StatusCode::INTERNAL,
                              "Missing row key at last chunk in cell");
        return;
      }
      row_key_ = cell_.row;
    } else {
      if (row_key_ != cell_.row) {
        status = grpc::Status(grpc::StatusCode::INTERNAL,
                              "Different row key in cell chunk");
        return;
      }
    }
    cells_.emplace_back(MovePartialToCell());
    cell_first_chunk_ = true;
  }

  if (chunk.reset_row()) {
    cells_.clear();
    cell_ = {};
    if (!cell_first_chunk_) {
      status = grpc::Status(grpc::StatusCode::INTERNAL,
                            "Reset row with an unfinished cell");
      return;
    }
  } else if (chunk.commit_row()) {
    if (!cell_first_chunk_) {
      status = grpc::Status(grpc::StatusCode::INTERNAL,
                            "Commit row with an unfinished cell");
      return;
    }
    if (cells_.empty()) {
      status = grpc::Status(grpc::StatusCode::INTERNAL,
                            "Commit row missing the row key");
      return;
    }
    row_ready_ = true;
    last_seen_row_key_ = row_key_;
    cell_.row.clear();
  }
}

void ReadRowsParser::HandleEndOfStream(grpc::Status& status) {
  if (end_of_stream_) {
    status = grpc::Status(grpc::StatusCode::INTERNAL,
                          "HandleEndOfStream called twice");
    return;
  }
  end_of_stream_ = true;

  if (!cell_first_chunk_) {
    status = grpc::Status(grpc::StatusCode::INTERNAL,
                          "end of stream with unfinished cell");
    return;
  }

  if (cells_.begin() != cells_.end() && !row_ready_) {
    status = grpc::Status(grpc::StatusCode::INTERNAL,
                          "end of stream with unfinished row");
    return;
  }
}

bool ReadRowsParser::HasNext() const { return row_ready_; }

Row ReadRowsParser::Next(grpc::Status& status) {
  if (!row_ready_) {
    status =
        grpc::Status(grpc::StatusCode::INTERNAL, "Next with row not ready");
    return Row("", {});
  }
  row_ready_ = false;

  Row row(std::move(row_key_), std::move(cells_));
  row_key_.clear();

  return row;
}

Cell ReadRowsParser::MovePartialToCell() {
  // The row, family, and column are explicitly copied because the
  // ReadRows v2 may reuse them in future chunks. See the CellChunk
  // message comments in bigtable.proto.
  Cell cell(cell_.row, cell_.family, cell_.column, cell_.timestamp,
            std::move(cell_.value), std::move(cell_.labels));
  cell_.value.clear();
  return cell;
}
}  // namespace internal
GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_END
}  // namespace bigtable
}  // namespace cloud
}  // namespace google
<commit_msg>cleanup(bigtable): reclaim vertical space (#9687)<commit_after>// Copyright 2017 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     https://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 "google/cloud/bigtable/internal/readrowsparser.h"
#include "google/cloud/grpc_error_delegate.h"

namespace google {
namespace cloud {
namespace bigtable {
GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_BEGIN
namespace internal {
using ::google::bigtable::v2::ReadRowsResponse_CellChunk;

// NOLINTNEXTLINE(readability-function-cognitive-complexity)
void ReadRowsParser::HandleChunk(ReadRowsResponse_CellChunk chunk,
                                 grpc::Status& status) {
  if (end_of_stream_) {
    status = grpc::Status(grpc::StatusCode::INTERNAL,
                          "HandleChunk after end of stream");
    return;
  }
  if (HasNext()) {
    status = grpc::Status(grpc::StatusCode::INTERNAL,
                          "HandleChunk called before taking the previous row");
    return;
  }

  if (!chunk.row_key().empty()) {
    if (CompareRowKey(last_seen_row_key_, chunk.row_key()) >= 0) {
      status = grpc::Status(grpc::StatusCode::INTERNAL,
                            "Row keys are expected in increasing order");
      return;
    }
    using std::swap;
    swap(*chunk.mutable_row_key(), cell_.row);
  }

  if (chunk.has_family_name()) {
    if (!chunk.has_qualifier()) {
      status = grpc::Status(grpc::StatusCode::INTERNAL,
                            "New column family must specify qualifier");
      return;
    }
    using std::swap;
    swap(*chunk.mutable_family_name()->mutable_value(), cell_.family);
  }

  if (chunk.has_qualifier()) {
    using std::swap;
    swap(*chunk.mutable_qualifier()->mutable_value(), cell_.column);
  }

  if (cell_first_chunk_) {
    cell_.timestamp = chunk.timestamp_micros();
    std::move(chunk.mutable_labels()->begin(), chunk.mutable_labels()->end(),
              std::back_inserter(cell_.labels));
    // Most common case, move the value
    using std::swap;
    swap(*chunk.mutable_value(), cell_.value);
  } else {
    internal::AppendCellValue(cell_.value, chunk.value());
  }

  cell_first_chunk_ = false;

  // This is a hint we get about the total size, use it to save some memory
  // allocations.
  if (chunk.value_size() > 0) {
    internal::ReserveCellValue(cell_.value,
                               static_cast<std::size_t>(chunk.value_size()));
  }

  // Last chunk in the cell has zero for value size
  if (chunk.value_size() == 0) {
    if (cells_.empty()) {
      if (cell_.row.empty()) {
        status = grpc::Status(grpc::StatusCode::INTERNAL,
                              "Missing row key at last chunk in cell");
        return;
      }
      row_key_ = cell_.row;
    } else {
      if (row_key_ != cell_.row) {
        status = grpc::Status(grpc::StatusCode::INTERNAL,
                              "Different row key in cell chunk");
        return;
      }
    }
    cells_.emplace_back(MovePartialToCell());
    cell_first_chunk_ = true;
  }

  if (chunk.reset_row()) {
    cells_.clear();
    cell_ = {};
    if (!cell_first_chunk_) {
      status = grpc::Status(grpc::StatusCode::INTERNAL,
                            "Reset row with an unfinished cell");
      return;
    }
  } else if (chunk.commit_row()) {
    if (!cell_first_chunk_) {
      status = grpc::Status(grpc::StatusCode::INTERNAL,
                            "Commit row with an unfinished cell");
      return;
    }
    if (cells_.empty()) {
      status = grpc::Status(grpc::StatusCode::INTERNAL,
                            "Commit row missing the row key");
      return;
    }
    row_ready_ = true;
    last_seen_row_key_ = row_key_;
    cell_.row.clear();
  }
}

void ReadRowsParser::HandleEndOfStream(grpc::Status& status) {
  if (end_of_stream_) {
    status = grpc::Status(grpc::StatusCode::INTERNAL,
                          "HandleEndOfStream called twice");
    return;
  }
  end_of_stream_ = true;

  if (!cell_first_chunk_) {
    status = grpc::Status(grpc::StatusCode::INTERNAL,
                          "end of stream with unfinished cell");
    return;
  }

  if (cells_.begin() != cells_.end() && !row_ready_) {
    status = grpc::Status(grpc::StatusCode::INTERNAL,
                          "end of stream with unfinished row");
    return;
  }
}

bool ReadRowsParser::HasNext() const { return row_ready_; }

Row ReadRowsParser::Next(grpc::Status& status) {
  if (!row_ready_) {
    status =
        grpc::Status(grpc::StatusCode::INTERNAL, "Next with row not ready");
    return Row("", {});
  }
  row_ready_ = false;

  Row row(std::move(row_key_), std::move(cells_));
  row_key_.clear();

  return row;
}

Cell ReadRowsParser::MovePartialToCell() {
  // The row, family, and column are explicitly copied because the
  // ReadRows v2 may reuse them in future chunks. See the CellChunk
  // message comments in bigtable.proto.
  Cell cell(cell_.row, cell_.family, cell_.column, cell_.timestamp,
            std::move(cell_.value), std::move(cell_.labels));
  cell_.value.clear();
  return cell;
}
}  // namespace internal
GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_END
}  // namespace bigtable
}  // namespace cloud
}  // namespace google
<|endoftext|>


<commit_before>/*
 * NuoDB Adapter
 */

#include "nuodb/sqlapi/SqlEnvironment.h"
#include "nuodb/sqlapi/SqlConnection.h"
#include "nuodb/sqlapi/SqlStatement.h"
#include "nuodb/sqlapi/SqlDatabaseMetaData.h"
#include "nuodb/sqlapi/SqlColumnMetaData.h"
#include "nuodb/sqlapi/SqlExceptions.h"

using nuodb::sqlapi::ErrorCodeException;
using nuodb::sqlapi::SqlColumnMetaData;
using nuodb::sqlapi::SqlConnection;
using nuodb::sqlapi::SqlDatabaseMetaData;
using nuodb::sqlapi::SqlEnvironment;
using nuodb::sqlapi::SqlOption;
using nuodb::sqlapi::SqlOptionArray;
using nuodb::sqlapi::SqlPreparedStatement;
using nuodb::sqlapi::SqlResultSet;
using nuodb::sqlapi::SqlStatement;

#include <ruby.h>

#include <iostream> // TODO temporary

using std::cout; // TODO temporary

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

#define WRAPPER_FIELDS(RT)			\
  private: static VALUE type;			\
  RT& ref;

#define WRAPPER_METHODS(WT, RT)					\
  public:							\
  WT(RT& arg) : ref(arg) {}					\
  static VALUE getType() { return type; }			\
  static void init(VALUE module);				\
  static void release(WT* self) {				\
    cout << "DISABLED release " << #WT << " " << self << "\n";	\
    /* self->ref.release(); */					\
    delete self;						\
  }								\
  static RT& asRef(VALUE value) {				\
    Check_Type(value, T_DATA);					\
    return ((WT*) DATA_PTR(value))->ref;			\
  }

#define WRAPPER_DEFINITION(WT)			\
  VALUE WT::type = 0;

#define RETURN_WRAPPER(WT, func)				      \
  WT* w = new WT(func);						      \
  VALUE obj = Data_Wrap_Struct(WT::getType(), 0, WT::release, w); \
  rb_obj_call_init(obj, 0, 0);					      \
  return obj

class SqlDatabaseMetaDataWrapper
{
  WRAPPER_FIELDS(SqlDatabaseMetaData)
  WRAPPER_METHODS(SqlDatabaseMetaDataWrapper, SqlDatabaseMetaData)

  static VALUE getDatabaseVersion(VALUE self)
  {
    return rb_str_new2(asRef(self).getDatabaseVersion());
  }
};
WRAPPER_DEFINITION(SqlDatabaseMetaDataWrapper)

class SqlStatementWrapper
{
  WRAPPER_FIELDS(SqlStatement)
  WRAPPER_METHODS(SqlStatementWrapper, SqlStatement)
};
WRAPPER_DEFINITION(SqlStatementWrapper)

class SqlPreparedStatementWrapper
{
  WRAPPER_FIELDS(SqlPreparedStatement)
  WRAPPER_METHODS(SqlPreparedStatementWrapper, SqlPreparedStatement)
};
WRAPPER_DEFINITION(SqlPreparedStatementWrapper)

class SqlResultSetWrapper
{
  WRAPPER_FIELDS(SqlResultSet);
  WRAPPER_METHODS(SqlResultSetWrapper, SqlResultSet);
};
WRAPPER_DEFINITION(SqlResultSetWrapper)

class SqlColumnMetaDataWrapper
{
  WRAPPER_FIELDS(SqlColumnMetaData);
  WRAPPER_METHODS(SqlColumnMetaDataWrapper, SqlColumnMetaData);
};
WRAPPER_DEFINITION(SqlColumnMetaDataWrapper)

class SqlConnectionWrapper
{
  WRAPPER_FIELDS(SqlConnection)
  WRAPPER_METHODS(SqlConnectionWrapper, SqlConnection)

  static VALUE createStatement(VALUE self)
  {
    RETURN_WRAPPER(SqlStatementWrapper, asRef(self).createStatement());
  }

  static VALUE createPreparedStatement(VALUE self, VALUE sqlValue)
  {
    const char* sql = StringValuePtr(sqlValue);
    RETURN_WRAPPER(SqlPreparedStatementWrapper, asRef(self).createPreparedStatement(sql));
  }

  static VALUE getMetaData(VALUE self)
  {
    RETURN_WRAPPER(SqlDatabaseMetaDataWrapper, asRef(self).getMetaData());
  }
};
WRAPPER_DEFINITION(SqlConnectionWrapper)

class SqlEnvironmentWrapper
{
  WRAPPER_FIELDS(SqlEnvironment)
  WRAPPER_METHODS(SqlEnvironmentWrapper, SqlEnvironment)

  static VALUE create(VALUE klass)
  {
    try {
      SqlOptionArray optsArray;
      optsArray.count = 0;

      RETURN_WRAPPER(SqlEnvironmentWrapper, SqlEnvironment::createSqlEnvironment(&optsArray));
    } catch (ErrorCodeException & e) {
      rb_raise(rb_eRuntimeError, "failed to create SqlEnvironment: %s", e.what());
    }
  }

  static VALUE createSqlConnection(VALUE self, VALUE database, VALUE username, VALUE password)
  {
    try {
      SqlOption options[3];

      options[0].option = "database";
      options[0].extra = (void*) StringValuePtr(database);

      options[1].option = "user";
      options[1].extra = (void*) StringValuePtr(username);

      options[2].option = "password";
      options[2].extra = (void*) StringValuePtr(password);

      SqlOptionArray optsArray;
      optsArray.count = 3;
      optsArray.array = options;

      RETURN_WRAPPER(SqlConnectionWrapper, asRef(self).createSqlConnection(&optsArray));
    } catch (ErrorCodeException & e) {
      rb_raise(rb_eRuntimeError, "failed to create SqlConnection: %s", e.what());
    }
  }
};
WRAPPER_DEFINITION(SqlEnvironmentWrapper)

//-------------------------------------------------------------------------
// Initialization

#define DEF_CLASS(name) \
  type = rb_define_class_under(module, name, rb_cObject)

#define DEF_SINGLETON(name, func, count) \
  rb_define_singleton_method(type, name, RUBY_METHOD_FUNC(func), count)

#define DEF_METHOD(name, func, count) \
  rb_define_method(type, name, RUBY_METHOD_FUNC(func), count)

void SqlEnvironmentWrapper::init(VALUE module)
{
  DEF_CLASS("SqlEnvironment");
  DEF_SINGLETON("createSqlEnvironment", SqlEnvironmentWrapper::create, 0);
  DEF_METHOD("createSqlConnection", SqlEnvironmentWrapper::createSqlConnection, 3);
}

void SqlConnectionWrapper::init(VALUE module)
{
  DEF_CLASS("SqlConnection");
  DEF_METHOD("createStatement", SqlConnectionWrapper::createStatement, 0);
  DEF_METHOD("createPreparedStatement", SqlConnectionWrapper::createPreparedStatement, 1);
  // TODO void setAutoCommit(bool autoCommit = true);
  // TODO bool hasAutoCommit() const;
  // TODO void commit();
  // TODO void rollback();
  DEF_METHOD("getMetaData", SqlConnectionWrapper::getMetaData, 0);
}

void SqlDatabaseMetaDataWrapper::init(VALUE module)
{
  DEF_CLASS("SqlDatabaseMetaData");
  DEF_METHOD("getDatabaseVersion", SqlDatabaseMetaDataWrapper::getDatabaseVersion, 0);
}

void SqlStatementWrapper::init(VALUE module)
{
  DEF_CLASS("SqlStatement");
  // TODO void execute(char const * sql);
  // TODO SqlResultSet & executeQuery(char const * sql);
  // TODO void release();
}

void SqlPreparedStatementWrapper::init(VALUE module)
{
  DEF_CLASS("SqlPreparedStatement");
  // TODO void setInteger(size_t index, int32_t value);
  // TODO void setDouble(size_t index, double value);
  // TODO void setString(size_t index, char const * value);
  // TODO void execute();
  // TODO SqlResultSet & executeQuery();
  // TODO void release();
}

void SqlResultSetWrapper::init(VALUE module)
{
  DEF_CLASS("SqlResultSet");
  // TODO bool next();
  // TODO size_t getColumnCount() const;
  // TODO SqlColumnMetaData & getMetaData(size_t column) const;
  // TODO int32_t getInteger(size_t column) const;
  // TODO double getDouble(size_t column) const;
  // TODO char const * getString(size_t column) const;
  // TODO SqlDate const * getDate(size_t column) const;
  // TODO void release();
}

void SqlColumnMetaDataWrapper::init(VALUE module)
{
  DEF_CLASS("SqlColumnMetaData");
  // TODO char const * getColumnName() const;
  // TODO SqlType getType() const;
  // TODO void release();
}

extern "C"
void Init_nuodb(void)
{
  VALUE module = rb_define_module("Nuodb");
  SqlEnvironmentWrapper::init(module);
  SqlConnectionWrapper::init(module);
  SqlDatabaseMetaDataWrapper::init(module);
  SqlStatementWrapper::init(module);
  SqlPreparedStatementWrapper::init(module);
  SqlResultSetWrapper::init(module);
  SqlColumnMetaDataWrapper::init(module);
}

//-------------------------------------------------------------------------
<commit_msg>Move init methods into their class declarations.<commit_after>/*
 * NuoDB Adapter
 */

#include "nuodb/sqlapi/SqlEnvironment.h"
#include "nuodb/sqlapi/SqlConnection.h"
#include "nuodb/sqlapi/SqlStatement.h"
#include "nuodb/sqlapi/SqlDatabaseMetaData.h"
#include "nuodb/sqlapi/SqlColumnMetaData.h"
#include "nuodb/sqlapi/SqlExceptions.h"

using nuodb::sqlapi::ErrorCodeException;
using nuodb::sqlapi::SqlColumnMetaData;
using nuodb::sqlapi::SqlConnection;
using nuodb::sqlapi::SqlDatabaseMetaData;
using nuodb::sqlapi::SqlEnvironment;
using nuodb::sqlapi::SqlOption;
using nuodb::sqlapi::SqlOptionArray;
using nuodb::sqlapi::SqlPreparedStatement;
using nuodb::sqlapi::SqlResultSet;
using nuodb::sqlapi::SqlStatement;

#include <ruby.h>

#include <iostream> // TODO temporary

using std::cout; // TODO temporary

//------------------------------------------------------------------------------
// class building macros

#define WRAPPER_FIELDS(RT)			\
  private: static VALUE type;			\
  RT& ref;

#define WRAPPER_METHODS(WT, RT)					\
  public:							\
  WT(RT& arg) : ref(arg) {}					\
  static VALUE getType() { return type; }			\
  static void release(WT* self) {				\
    cout << "DISABLED release " << #WT << " " << self << "\n";	\
    /* self->ref.release(); */					\
    delete self;						\
  }								\
  static RT& asRef(VALUE value) {				\
    Check_Type(value, T_DATA);					\
    return ((WT*) DATA_PTR(value))->ref;			\
  }

#define WRAPPER_DEFINITION(WT)			\
  VALUE WT::type = 0;

//------------------------------------------------------------------------------
// utility function macros

#define RETURN_WRAPPER(WT, func)				      \
  WT* w = new WT(func);						      \
  VALUE obj = Data_Wrap_Struct(WT::getType(), 0, WT::release, w);     \
  rb_obj_call_init(obj, 0, 0);					      \
  return obj

#define INIT_TYPE(name)						\
  type = rb_define_class_under(module, name, rb_cObject)

#define DEFINE_SINGLE(name, func, count)				\
  rb_define_singleton_method(type, name, RUBY_METHOD_FUNC(func), count)

#define DEFINE_METHOD(name, func, count)			\
  rb_define_method(type, name, RUBY_METHOD_FUNC(func), count)

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

class SqlDatabaseMetaDataWrapper
{
  WRAPPER_FIELDS(SqlDatabaseMetaData)
  WRAPPER_METHODS(SqlDatabaseMetaDataWrapper, SqlDatabaseMetaData)

  static void init(VALUE module)
  {
    INIT_TYPE("SqlDatabaseMetaData");
    DEFINE_METHOD("getDatabaseVersion", getDatabaseVersion, 0);
  }

  static VALUE getDatabaseVersion(VALUE self)
  {
    return rb_str_new2(asRef(self).getDatabaseVersion());
  }
};
WRAPPER_DEFINITION(SqlDatabaseMetaDataWrapper)

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

class SqlStatementWrapper
{
  WRAPPER_FIELDS(SqlStatement)
  WRAPPER_METHODS(SqlStatementWrapper, SqlStatement)

  static void init(VALUE module)
  {
    INIT_TYPE("SqlStatement");
    // TODO void execute(char const * sql);
    // TODO SqlResultSet & executeQuery(char const * sql);
    // TODO void release();
  }
};
WRAPPER_DEFINITION(SqlStatementWrapper)

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

class SqlPreparedStatementWrapper
{
  WRAPPER_FIELDS(SqlPreparedStatement)
  WRAPPER_METHODS(SqlPreparedStatementWrapper, SqlPreparedStatement)

  static void init(VALUE module)
  {
    INIT_TYPE("SqlPreparedStatement");
    // TODO void setInteger(size_t index, int32_t value);
    // TODO void setDouble(size_t index, double value);
    // TODO void setString(size_t index, char const * value);
    // TODO void execute();
    // TODO SqlResultSet & executeQuery();
    // TODO void release();
  }
};
WRAPPER_DEFINITION(SqlPreparedStatementWrapper)

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

class SqlResultSetWrapper
{
  WRAPPER_FIELDS(SqlResultSet);
  WRAPPER_METHODS(SqlResultSetWrapper, SqlResultSet);

  static void init(VALUE module)
  {
    INIT_TYPE("SqlResultSet");
    // TODO bool next();
    // TODO size_t getColumnCount() const;
    // TODO SqlColumnMetaData & getMetaData(size_t column) const;
    // TODO int32_t getInteger(size_t column) const;
    // TODO double getDouble(size_t column) const;
    // TODO char const * getString(size_t column) const;
    // TODO SqlDate const * getDate(size_t column) const;
    // TODO void release();
  }
};
WRAPPER_DEFINITION(SqlResultSetWrapper)

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

class SqlColumnMetaDataWrapper
{
  WRAPPER_FIELDS(SqlColumnMetaData);
  WRAPPER_METHODS(SqlColumnMetaDataWrapper, SqlColumnMetaData);

  static void init(VALUE module)
  {
    INIT_TYPE("SqlColumnMetaData");
    // TODO char const * getColumnName() const;
    // TODO SqlType getType() const;
    // TODO void release();
  }
};
WRAPPER_DEFINITION(SqlColumnMetaDataWrapper)

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

class SqlConnectionWrapper
{
  WRAPPER_FIELDS(SqlConnection)
  WRAPPER_METHODS(SqlConnectionWrapper, SqlConnection)

  static void init(VALUE module)
  {
    INIT_TYPE("SqlConnection");
    DEFINE_METHOD("createStatement", createStatement, 0);
    DEFINE_METHOD("createPreparedStatement", createPreparedStatement, 1);
    // TODO void setAutoCommit(bool autoCommit = true);
    // TODO bool hasAutoCommit() const;
    // TODO void commit();
    // TODO void rollback();
    DEFINE_METHOD("getMetaData", getMetaData, 0);
  }

  static VALUE createStatement(VALUE self)
  {
    RETURN_WRAPPER(SqlStatementWrapper, asRef(self).createStatement());
  }

  static VALUE createPreparedStatement(VALUE self, VALUE sqlValue)
  {
    const char* sql = StringValuePtr(sqlValue);
    RETURN_WRAPPER(SqlPreparedStatementWrapper, asRef(self).createPreparedStatement(sql));
  }

  static VALUE getMetaData(VALUE self)
  {
    RETURN_WRAPPER(SqlDatabaseMetaDataWrapper, asRef(self).getMetaData());
  }
};
WRAPPER_DEFINITION(SqlConnectionWrapper)

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

class SqlEnvironmentWrapper
{
  WRAPPER_FIELDS(SqlEnvironment)
  WRAPPER_METHODS(SqlEnvironmentWrapper, SqlEnvironment)

  static void init(VALUE module)
  {
    INIT_TYPE("SqlEnvironment");
    DEFINE_SINGLE("createSqlEnvironment", create, 0);
    DEFINE_METHOD("createSqlConnection", createSqlConnection, 3);
  }

  static VALUE create(VALUE klass)
  {
    try {
      SqlOptionArray optsArray;
      optsArray.count = 0;

      RETURN_WRAPPER(SqlEnvironmentWrapper, SqlEnvironment::createSqlEnvironment(&optsArray));
    } catch (ErrorCodeException & e) {
      rb_raise(rb_eRuntimeError, "failed to create SqlEnvironment: %s", e.what());
    }
  }

  static VALUE createSqlConnection(VALUE self, VALUE database, VALUE username, VALUE password)
  {
    try {
      SqlOption options[3];

      options[0].option = "database";
      options[0].extra = (void*) StringValuePtr(database);

      options[1].option = "user";
      options[1].extra = (void*) StringValuePtr(username);

      options[2].option = "password";
      options[2].extra = (void*) StringValuePtr(password);

      SqlOptionArray optsArray;
      optsArray.count = 3;
      optsArray.array = options;

      RETURN_WRAPPER(SqlConnectionWrapper, asRef(self).createSqlConnection(&optsArray));
    } catch (ErrorCodeException & e) {
      rb_raise(rb_eRuntimeError, "failed to create SqlConnection: %s", e.what());
    }
  }
};
WRAPPER_DEFINITION(SqlEnvironmentWrapper)

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

extern "C"
void Init_nuodb(void)
{
  VALUE module = rb_define_module("Nuodb");
  SqlEnvironmentWrapper::init(module);
  SqlConnectionWrapper::init(module);
  SqlDatabaseMetaDataWrapper::init(module);
  SqlStatementWrapper::init(module);
  SqlPreparedStatementWrapper::init(module);
  SqlResultSetWrapper::init(module);
  SqlColumnMetaDataWrapper::init(module);
}

//------------------------------------------------------------------------------
<|endoftext|>


<commit_before>/*
 * NarfBlock bytestream writer and reader
 *
 * Copyright (c) 2014 Daniel Verkamp
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * - Redistributions of source code must retain the above copyright
 * notice, this list of conditions and the following disclaimer.
 *
 * - Redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in
 * the documentation and/or other materials provided with the
 * distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
 * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
 * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
 * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY
 * WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 */

#include <stdlib.h>
#include <string.h>
#include <assert.h>

#include "narf/bytestream.h"

narf::ByteStreamWriter::ByteStreamWriter() {
}

narf::ByteStreamWriter::~ByteStreamWriter() {
}

// TODO: use vector's resize() and write directly to data if this turns out to be slow
void narf::ByteStreamWriter::writeLE16(uint16_t v) {
	data_.push_back(static_cast<uint8_t>(v));
	data_.push_back(static_cast<uint8_t>(v >> 8));
}

void narf::ByteStreamWriter::writeLE32(uint32_t v) {
	data_.push_back(static_cast<uint8_t>(v));
	data_.push_back(static_cast<uint8_t>(v >> 8));
	data_.push_back(static_cast<uint8_t>(v >> 16));
	data_.push_back(static_cast<uint8_t>(v >> 24));
}

narf::ByteStreamReader::ByteStreamReader(size_t size) {
	data_ = new uint8_t[size];
	if (data_ != nullptr) {
		size_ = size;
	} else {
		size_ = 0;
	}
	reset();
}

narf::ByteStreamReader::ByteStreamReader(const void* data, size_t size) :
	ByteStreamReader(size) {
	if (data_ != nullptr) {
		memcpy(data_, data, size);
	}
}

narf::ByteStreamReader::~ByteStreamReader() {
	if (data_ != nullptr) {
		delete[] data_;
	}
}

bool narf::ByteStreamReader::readLE16(uint16_t* v) {
	assert(v != nullptr);
	if (bytesLeft_ < 2) {
		return false;
	}
	*v =
		static_cast<uint16_t>(iter_[0]) |
		static_cast<uint16_t>(iter_[1]) << 8;
	iter_ += 2;
	bytesLeft_ -= 2;
	return true;
}

bool narf::ByteStreamReader::readLE32(uint32_t* v) {
	if (bytesLeft_ < 4) {
		return false;
	}
	*v =
		static_cast<uint32_t>(iter_[0]) |
		static_cast<uint32_t>(iter_[1]) << 8 |
		static_cast<uint32_t>(iter_[2]) << 16 |
		static_cast<uint32_t>(iter_[3]) << 24;
	iter_ += 4;
	bytesLeft_ -= 4;
	return true;
}
<commit_msg>bytestream: fix warning about uint16_t conversion<commit_after>/*
 * NarfBlock bytestream writer and reader
 *
 * Copyright (c) 2014 Daniel Verkamp
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * - Redistributions of source code must retain the above copyright
 * notice, this list of conditions and the following disclaimer.
 *
 * - Redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in
 * the documentation and/or other materials provided with the
 * distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
 * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
 * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
 * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY
 * WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 */

#include <stdlib.h>
#include <string.h>
#include <assert.h>

#include "narf/bytestream.h"

narf::ByteStreamWriter::ByteStreamWriter() {
}

narf::ByteStreamWriter::~ByteStreamWriter() {
}

// TODO: use vector's resize() and write directly to data if this turns out to be slow
void narf::ByteStreamWriter::writeLE16(uint16_t v) {
	data_.push_back(static_cast<uint8_t>(v));
	data_.push_back(static_cast<uint8_t>(v >> 8));
}

void narf::ByteStreamWriter::writeLE32(uint32_t v) {
	data_.push_back(static_cast<uint8_t>(v));
	data_.push_back(static_cast<uint8_t>(v >> 8));
	data_.push_back(static_cast<uint8_t>(v >> 16));
	data_.push_back(static_cast<uint8_t>(v >> 24));
}

narf::ByteStreamReader::ByteStreamReader(size_t size) {
	data_ = new uint8_t[size];
	if (data_ != nullptr) {
		size_ = size;
	} else {
		size_ = 0;
	}
	reset();
}

narf::ByteStreamReader::ByteStreamReader(const void* data, size_t size) :
	ByteStreamReader(size) {
	if (data_ != nullptr) {
		memcpy(data_, data, size);
	}
}

narf::ByteStreamReader::~ByteStreamReader() {
	if (data_ != nullptr) {
		delete[] data_;
	}
}

bool narf::ByteStreamReader::readLE16(uint16_t* v) {
	assert(v != nullptr);
	if (bytesLeft_ < 2) {
		return false;
	}
	*v = static_cast<uint16_t>(
		static_cast<uint16_t>(iter_[0]) |
		static_cast<uint16_t>(iter_[1]) << 8);
	iter_ += 2;
	bytesLeft_ -= 2;
	return true;
}

bool narf::ByteStreamReader::readLE32(uint32_t* v) {
	if (bytesLeft_ < 4) {
		return false;
	}
	*v = static_cast<uint32_t>(
		static_cast<uint32_t>(iter_[0]) |
		static_cast<uint32_t>(iter_[1]) << 8 |
		static_cast<uint32_t>(iter_[2]) << 16 |
		static_cast<uint32_t>(iter_[3]) << 24);
	iter_ += 4;
	bytesLeft_ -= 4;
	return true;
}
<|endoftext|>


<commit_before>#pragma once
#ifndef OPENGM_TESTDATASETS_HXX
#define OPENGM_TESTDATASETS_HXX

#include <vector>
#include <cstdlib>

#include <opengm/learning/dataset/dataset.hxx>
#include <opengm/functions/learnable/lpotts.hxx>
#include <opengm/functions/learnable/sum_of_experts.hxx>

namespace opengm {
   namespace datasets{

      template<class GM, class LOSS>
      class TestDataset1 : public Dataset<GM,LOSS>{
      public:
         typedef GM                     GMType;
         typedef GM                     GMWITHLOSS;
         typedef LOSS                   LossType;
         typedef typename GM::ValueType ValueType;
         typedef typename GM::IndexType IndexType;
         typedef typename GM::LabelType LabelType;
         typedef opengm::learning::Weights<ValueType> Weights;

         TestDataset1(size_t numModels=5);
      };

      template<class GM, class LOSS>
      class TestDataset2 : public Dataset<GM,LOSS>{
      public:
         typedef GM                     GMType;
         typedef GM                     GMWITHLOSS;
         typedef LOSS                   LossType;
         typedef typename GM::ValueType ValueType;
         typedef typename GM::IndexType IndexType;
         typedef typename GM::LabelType LabelType;
         typedef opengm::learning::Weights<ValueType> Weights;

         TestDataset2(size_t numModels=4);
      };

//***********************************
//** IMPL TestDataset 1
//***********************************
      template<class GM, class LOSS>
      TestDataset1<GM,LOSS>::TestDataset1(size_t numModels)
      {
         this->weights_ = Weights(1);
         LabelType numberOfLabels = 2;
         this->gt_.resize(numModels,std::vector<size_t>(64*64,0));
         for(size_t m=0;m<numModels;++m){
            for(size_t i=32*64; i<64*64; ++i){
               this->gt_[m][i] = 1;
            }
         }
         this->gms_.resize(numModels);
         for(size_t m=0; m<numModels; ++m){
            std::srand(m);
            for (int j = 0; j < 64*64; j++)
               this->gms_[m].addVariable(2);
            for(size_t y = 0; y < 64; ++y){
               for(size_t x = 0; x < 64; ++x) {
                  // function
                  const size_t shape[] = {numberOfLabels};
                  ExplicitFunction<ValueType> f(shape, shape + 1);
                  ValueType val = (double)(this->gt_[m][y*64+x]) + (double)(std::rand()) / (double) (RAND_MAX) * 1.5 - 0.75 ;
                  f(0) = std::fabs(val-0);
                  f(1) = std::fabs(val-1);
                  typename GM::FunctionIdentifier fid =  this->gms_[m].addFunction(f);

                  // factor
                  size_t variableIndices[] = {y*64+x};
                  this->gms_[m].addFactor(fid, variableIndices, variableIndices + 1);
               }
            }

            opengm::functions::learnable::LPotts<ValueType,IndexType,LabelType> f(this->weights_,2,std::vector<size_t>(1,0),std::vector<ValueType>(1,1));
            typename GM::FunctionIdentifier fid = this->gms_[m].addFunction(f);
            for(size_t y = 0; y < 64; ++y){
               for(size_t x = 0; x < 64; ++x) {
                  if(x + 1 < 64) { // (x, y) -- (x + 1, y)
                     size_t variableIndices[] = {y*64+x, y*64+x+1};
                     //sort(variableIndices, variableIndices + 2);
                     this->gms_[m].addFactor(fid, variableIndices, variableIndices + 2);
                  }
                  if(y + 1 < 64) { // (x, y) -- (x, y + 1)
                     size_t variableIndices[] = {y*64+x, (y+1)*64+x};
                     //sort(variableIndices, variableIndices + 2);
                     this->gms_[m].addFactor(fid, variableIndices, variableIndices + 2);
                  }
               }
            }
         }
      };

//***********************************
//** IMPL TestDataset 2
//***********************************
      template<class GM, class LOSS>
      TestDataset2<GM,LOSS>::TestDataset2(size_t numModels)
      {
         this->weights_ = Weights(3);
         LabelType numberOfLabels = 2;
         this->gt_.resize(numModels,std::vector<size_t>(64*64,0));
         for(size_t m=0;m<numModels;++m){
            for(size_t i=32*64; i<64*64; ++i){
               this->gt_[m][i] = 1;
            }
         }
         this->gms_.resize(numModels);
         for(size_t m=0; m<numModels; ++m){
            std::srand(m);
            for (int j = 0; j < 64*64; j++)
               this->gms_[m].addVariable(2);
            for(size_t y = 0; y < 64; ++y){
               for(size_t x = 0; x < 64; ++x) {
                  // function
                  const size_t numExperts = 2;
                  const std::vector<size_t> shape(1,numberOfLabels);
                  std::vector<marray::Marray<ValueType> > feat(numExperts,marray::Marray<ValueType>(shape.begin(), shape.end()));
                  ValueType val0 = (double)(this->gt_[m][y*64+x]) + (double)(std::rand()) / (double) (RAND_MAX) * 1.0 - 0.5 ;
                  feat[0](0) = std::fabs(val0-0);
                  feat[0](1) = std::fabs(val0-1);
                  ValueType val1 = (double)(this->gt_[m][y*64+x]) + (double)(std::rand()) / (double) (RAND_MAX) * 2.0 - 1.0 ;
                  feat[1](0) = std::fabs(val1-0);
                  feat[1](1) = std::fabs(val1-1);
                  std::vector<size_t> wID(2);
                  wID[0]=1;  wID[1]=2;
                  opengm::functions::learnable::SumOfExperts<ValueType,IndexType,LabelType> f(shape,this->weights_, wID, feat);
                  typename GM::FunctionIdentifier fid =  this->gms_[m].addFunction(f);

                  // factor
                  size_t variableIndices[] = {y*64+x};
                  this->gms_[m].addFactor(fid, variableIndices, variableIndices + 1);
               }
            }

            opengm::functions::learnable::LPotts<ValueType,IndexType,LabelType> f(this->weights_,2,std::vector<size_t>(1,0),std::vector<ValueType>(1,1));
            typename GM::FunctionIdentifier fid = this->gms_[m].addFunction(f);
            for(size_t y = 0; y < 64; ++y){
               for(size_t x = 0; x < 64; ++x) {
                  if(x + 1 < 64) { // (x, y) -- (x + 1, y)
                     size_t variableIndices[] = {y*64+x, y*64+x+1};
                     //sort(variableIndices, variableIndices + 2);
                     this->gms_[m].addFactor(fid, variableIndices, variableIndices + 2);
                  }
                  if(y + 1 < 64) { // (x, y) -- (x, y + 1)
                     size_t variableIndices[] = {y*64+x, (y+1)*64+x};
                     //sort(variableIndices, variableIndices + 2);
                     this->gms_[m].addFactor(fid, variableIndices, variableIndices + 2);
                  }
               }
            }
         }
      };

   }
} // namespace opengm

#endif
<commit_msg>add missing resize<commit_after>#pragma once
#ifndef OPENGM_TESTDATASETS_HXX
#define OPENGM_TESTDATASETS_HXX

#include <vector>
#include <cstdlib>

#include <opengm/learning/dataset/dataset.hxx>
#include <opengm/functions/learnable/lpotts.hxx>
#include <opengm/functions/learnable/sum_of_experts.hxx>

namespace opengm {
   namespace datasets{

      template<class GM, class LOSS>
      class TestDataset1 : public Dataset<GM,LOSS>{
      public:
         typedef GM                     GMType;
         typedef GM                     GMWITHLOSS;
         typedef LOSS                   LossType;
         typedef typename GM::ValueType ValueType;
         typedef typename GM::IndexType IndexType;
         typedef typename GM::LabelType LabelType;
         typedef opengm::learning::Weights<ValueType> Weights;

         TestDataset1(size_t numModels=5);
      };

      template<class GM, class LOSS>
      class TestDataset2 : public Dataset<GM,LOSS>{
      public:
         typedef GM                     GMType;
         typedef GM                     GMWITHLOSS;
         typedef LOSS                   LossType;
         typedef typename GM::ValueType ValueType;
         typedef typename GM::IndexType IndexType;
         typedef typename GM::LabelType LabelType;
         typedef opengm::learning::Weights<ValueType> Weights;

         TestDataset2(size_t numModels=4);
      };

//***********************************
//** IMPL TestDataset 1
//***********************************
      template<class GM, class LOSS>
      TestDataset1<GM,LOSS>::TestDataset1(size_t numModels)
      {
         this->count_.resize(numModels,0);
         this->weights_ = Weights(1);
         LabelType numberOfLabels = 2;
         this->gt_.resize(numModels,std::vector<size_t>(64*64,0));
         for(size_t m=0;m<numModels;++m){
            for(size_t i=32*64; i<64*64; ++i){
               this->gt_[m][i] = 1;
            }
         }
         this->gms_.resize(numModels);
         for(size_t m=0; m<numModels; ++m){
            std::srand(m);
            for (int j = 0; j < 64*64; j++)
               this->gms_[m].addVariable(2);
            for(size_t y = 0; y < 64; ++y){
               for(size_t x = 0; x < 64; ++x) {
                  // function
                  const size_t shape[] = {numberOfLabels};
                  ExplicitFunction<ValueType> f(shape, shape + 1);
                  ValueType val = (double)(this->gt_[m][y*64+x]) + (double)(std::rand()) / (double) (RAND_MAX) * 1.5 - 0.75 ;
                  f(0) = std::fabs(val-0);
                  f(1) = std::fabs(val-1);
                  typename GM::FunctionIdentifier fid =  this->gms_[m].addFunction(f);

                  // factor
                  size_t variableIndices[] = {y*64+x};
                  this->gms_[m].addFactor(fid, variableIndices, variableIndices + 1);
               }
            }

            opengm::functions::learnable::LPotts<ValueType,IndexType,LabelType> f(this->weights_,2,std::vector<size_t>(1,0),std::vector<ValueType>(1,1));
            typename GM::FunctionIdentifier fid = this->gms_[m].addFunction(f);
            for(size_t y = 0; y < 64; ++y){
               for(size_t x = 0; x < 64; ++x) {
                  if(x + 1 < 64) { // (x, y) -- (x + 1, y)
                     size_t variableIndices[] = {y*64+x, y*64+x+1};
                     //sort(variableIndices, variableIndices + 2);
                     this->gms_[m].addFactor(fid, variableIndices, variableIndices + 2);
                  }
                  if(y + 1 < 64) { // (x, y) -- (x, y + 1)
                     size_t variableIndices[] = {y*64+x, (y+1)*64+x};
                     //sort(variableIndices, variableIndices + 2);
                     this->gms_[m].addFactor(fid, variableIndices, variableIndices + 2);
                  }
               }
            }
         }
      };

//***********************************
//** IMPL TestDataset 2
//***********************************
      template<class GM, class LOSS>
      TestDataset2<GM,LOSS>::TestDataset2(size_t numModels)
      {
         this->count_.resize(numModels,0);
         this->weights_ = Weights(3);
         LabelType numberOfLabels = 2;
         this->gt_.resize(numModels,std::vector<size_t>(64*64,0));
         for(size_t m=0;m<numModels;++m){
            for(size_t i=32*64; i<64*64; ++i){
               this->gt_[m][i] = 1;
            }
         }
         this->gms_.resize(numModels);
         for(size_t m=0; m<numModels; ++m){
            std::srand(m);
            for (int j = 0; j < 64*64; j++)
               this->gms_[m].addVariable(2);
            for(size_t y = 0; y < 64; ++y){
               for(size_t x = 0; x < 64; ++x) {
                  // function
                  const size_t numExperts = 2;
                  const std::vector<size_t> shape(1,numberOfLabels);
                  std::vector<marray::Marray<ValueType> > feat(numExperts,marray::Marray<ValueType>(shape.begin(), shape.end()));
                  ValueType val0 = (double)(this->gt_[m][y*64+x]) + (double)(std::rand()) / (double) (RAND_MAX) * 1.0 - 0.5 ;
                  feat[0](0) = std::fabs(val0-0);
                  feat[0](1) = std::fabs(val0-1);
                  ValueType val1 = (double)(this->gt_[m][y*64+x]) + (double)(std::rand()) / (double) (RAND_MAX) * 2.0 - 1.0 ;
                  feat[1](0) = std::fabs(val1-0);
                  feat[1](1) = std::fabs(val1-1);
                  std::vector<size_t> wID(2);
                  wID[0]=1;  wID[1]=2;
                  opengm::functions::learnable::SumOfExperts<ValueType,IndexType,LabelType> f(shape,this->weights_, wID, feat);
                  typename GM::FunctionIdentifier fid =  this->gms_[m].addFunction(f);

                  // factor
                  size_t variableIndices[] = {y*64+x};
                  this->gms_[m].addFactor(fid, variableIndices, variableIndices + 1);
               }
            }

            opengm::functions::learnable::LPotts<ValueType,IndexType,LabelType> f(this->weights_,2,std::vector<size_t>(1,0),std::vector<ValueType>(1,1));
            typename GM::FunctionIdentifier fid = this->gms_[m].addFunction(f);
            for(size_t y = 0; y < 64; ++y){
               for(size_t x = 0; x < 64; ++x) {
                  if(x + 1 < 64) { // (x, y) -- (x + 1, y)
                     size_t variableIndices[] = {y*64+x, y*64+x+1};
                     //sort(variableIndices, variableIndices + 2);
                     this->gms_[m].addFactor(fid, variableIndices, variableIndices + 2);
                  }
                  if(y + 1 < 64) { // (x, y) -- (x, y + 1)
                     size_t variableIndices[] = {y*64+x, (y+1)*64+x};
                     //sort(variableIndices, variableIndices + 2);
                     this->gms_[m].addFactor(fid, variableIndices, variableIndices + 2);
                  }
               }
            }
         }
      };

   }
} // namespace opengm

#endif
<|endoftext|>