<commit_before>//extern "C"

#include <daqDA.h>

#include <event.h>
#include <monitor.h>

#include <Riostream.h>
#include <stdio.h>
#include <stdlib.h>

//AliRoot
#include <AliRawReaderDate.h>
#include <AliRawReader.h>
#include <AliT0RawReader.h>
#include <AliCDBManager.h>

//ROOT
#include "TFile.h"
#include "TKey.h"
#include "TH2S.h"
#include "TObject.h"
#include "TBenchmark.h"
#include "TRandom.h"
#include "TMath.h"
#include "TCanvas.h"
#include "TString.h"
#include "TH1.h"
#include "TF1.h"
#include "TSpectrum.h"
#include "TVirtualFitter.h"
#include "TProfile.h"

/* Main routine
      Arguments:
      1- monitoring data source
*/
int main(int argc, char **argv) {
  int status;

  if (argc!=2) {
    printf("Wrong number of arguments\n");
    return -1;
  }

  /* define data source : this is argument 1 */
  status=monitorSetDataSource( argv[1] );
  if (status!=0) {
    printf("monitorSetDataSource() failed : %s\n",monitorDecodeError(status));
    return -1;
  }

  /* declare monitoring program */
  status=monitorDeclareMp( __FILE__ );
  if (status!=0) {
    printf("monitorDeclareMp() failed : %s\n",monitorDecodeError(status));
    return -1;
  }

  /* define wait event timeout - 1s max */
  monitorSetNowait();
  monitorSetNoWaitNetworkTimeout(1000);

  /* log start of process */
  printf("T0 monitoring program started\n");

  // Allocation of histograms - start
  TH1F *hCFD[24];
  TH2F *hCFD_QTC[24]; TH2F *hCFD_LED[24];
  Char_t  buf1[10], buf2[10],buf3[10],buf4[10];

   for(Int_t ic=0; ic<24; ic++) {
      sprintf(buf1,"CFD_QTC%i",ic+1);
      sprintf(buf2,"CFD_LED%i",ic+1);

      hCFD_QTC[ic] = new TH2F(buf1,"CFD_QTC",8000,0.5,8000.5,2000,10000.5,20000.5);
      hCFD_LED[ic] = new TH2F(buf2,"CFD_LED",1000,-500.0,500.0,100,14600.0,14700.0);
      if(ic<12){
	sprintf(buf3,"T0_C_%i_CFD",ic+1);
	hCFD[ic] = new TH1F(buf3,"CFD", 30000,0., 30000.);
      }
      else{
        sprintf(buf4,"T0_A_%i_CFD",ic-11);
        hCFD[ic] = new TH1F(buf4,"CFD", 30000,0., 30000.);
      }
    }

  // Allocation of histograms - end

  Int_t iev=0;
  /* main loop (infinite) */
  for(;;) {
    struct eventHeaderStruct *event;
    eventTypeType eventT;

    /* check shutdown condition */
    if (daqDA_checkShutdown()) {break;}

    /* get next event (blocking call until timeout) */
    status=monitorGetEventDynamic((void **)&event);
    if (status==(int)MON_ERR_EOF) {
      printf ("End of File detected\n");
      break; /* end of monitoring file has been reached */
    }

    if (status!=0) {
      printf("monitorGetEventDynamic() failed : %s\n",monitorDecodeError(status));
      break;
    }

    /* retry if got no event */
    if (event==NULL) {
      continue;
    }

    iev++;

    /* use event - here, just write event id to result file */
    eventT=event->eventType;

    switch (event->eventType){

      case START_OF_RUN:
	break;

      case END_OF_RUN:
	break;

//      case CALIBRATION_EVENT:
      case PHYSICS_EVENT:
      printf(" event number = %i \n",iev);

      // Initalize raw-data reading and decoding
      AliRawReader *reader = new AliRawReaderDate((void*)event);

      // Enable the following two lines in case of real-data
   //       reader->LoadEquipmentIdsMap("T0map.txt");
    //     reader->RequireHeader(kFALSE);
     // 	  reader->RequireHeader(kTRUE);
      AliT0RawReader *start = new AliT0RawReader(reader, kTRUE);

      // Read raw data
      Int_t allData[105][5];
      for(Int_t i0=0;i0<105;i0++)
      	for(Int_t j0=0;j0<5;j0++)
		allData[i0][j0] = 0;

      if(start->Next())
      for (Int_t i=0; i<105; i++) {
	for(Int_t iHit=0;iHit<5;iHit++){
	  allData[i][iHit]= start->GetData(i,iHit);
        }
      }
	else
	printf("No T0 data found!!\n");

      // Fill the histograms

      for (Int_t ik = 0; ik<24; ik+=2)
         for (Int_t iHt=0; iHt<5; iHt++){
		 Int_t cc = ik/2;
		if((allData[cc+1][iHt]-allData[0][0])>0){
		 hCFD[cc]->Fill(allData[cc+1][iHt]-allData[0][0]);
		}
		if(allData[ik+25][iHt]!=0 && allData[ik+26][iHt]!=0 && allData[cc+1][iHt]!=0){
                 hCFD_QTC[cc]->Fill((allData[ik+25][iHt]-allData[ik+26][iHt]) , (allData[cc+1][iHt]-allData[0][0]));
		 }
                if(allData[cc+13][iHt]!=0 && allData[cc+1][iHt]!=0){
		 hCFD_LED[cc]->Fill(allData[cc+13][iHt]-allData[cc+1][iHt],allData[cc+1][iHt]-allData[0][0]);
		 }
	}

      for (Int_t ik = 24; ik<48; ik+=2)
         for (Int_t iHt=0; iHt<5; iHt++){
		 Int_t cc = ik/2;
                if((allData[cc+45][iHt]-allData[0][0])>0){
                 hCFD[cc]->Fill(allData[cc+45][iHt]-allData[0][0]);
                }

                if(allData[ik+57][iHt]!=0 && allData[ik+58][iHt]!=0){
                if(allData[cc+45][iHt]!=0)
                 hCFD_QTC[cc]->Fill(allData[ik+57][iHt]-allData[ik+58][iHt],allData[cc+45][iHt]-allData[0][0]);
		 }
                if(allData[cc+57][iHt]!=0 && allData[cc+45][iHt]!=0){
                 hCFD_LED[cc]->Fill(allData[cc+57][iHt]-allData[cc+45][iHt],allData[cc+45][iHt]-allData[0][0]);
                 }
	}

     delete start;
	start = 0x0;
     reader->Reset();
      // End of fill histograms

    }

    /* free resources */
    free(event);

    /* exit when last event received, no need to wait for TERM signal */
    if (eventT==END_OF_RUN) {
      printf("EOR event detected\n");
      break;
    }
  }
printf("After loop, before writing histos\n");
  // write a file with the histograms
  Char_t filehist[21];
  sprintf(filehist,"daLaser.root");
  TFile *hist = new TFile(filehist,"RECREATE");

  for(Int_t j=0;j<24;j++){
     hCFD_QTC[j]->Write();
     hCFD_LED[j]->Write();
     hCFD[j]->Write();
    }
  hist->Close();
  delete hist;

  return status;
}

<commit_msg>Adding the required documentation fields<commit_after>/*
TOF DA for online calibration

Contact: Michal.Oledzki@cern.ch
Link: www.if.pw.edu.pl:/~oledzki
Run Type: PHYSICS
DA Type: MON
Number of events needed: depending on the run, being run-level
Input Files:
Output Files: daLaser.root, to be exported to the DAQ FXS
Trigger types used: PHYSICS_EVENT

*/
//extern "C"

#define FILE_OUT "daLaser.root"

#include <daqDA.h>
#include <event.h>
#include <monitor.h>

#include <Riostream.h>
#include <stdio.h>
#include <stdlib.h>

//AliRoot
#include <AliRawReaderDate.h>
#include <AliRawReader.h>
#include <AliT0RawReader.h>

//ROOT
#include "TFile.h"
#include "TKey.h"
#include "TH2S.h"
#include "TObject.h"
#include "TBenchmark.h"
#include "TRandom.h"
#include "TMath.h"
#include "TCanvas.h"
#include "TString.h"
#include "TH1.h"
#include "TF1.h"
#include "TSpectrum.h"
#include "TVirtualFitter.h"
#include "TProfile.h"

/* Main routine
      Arguments:
      1- monitoring data source
*/
int main(int argc, char **argv) {
  int status;

  if (argc!=2) {
    printf("Wrong number of arguments\n");
    return -1;
  }

  /* define data source : this is argument 1 */
  status=monitorSetDataSource( argv[1] );
  if (status!=0) {
    printf("monitorSetDataSource() failed : %s\n",monitorDecodeError(status));
    return -1;
  }

  /* declare monitoring program */
  status=monitorDeclareMp( __FILE__ );
  if (status!=0) {
    printf("monitorDeclareMp() failed : %s\n",monitorDecodeError(status));
    return -1;
  }

  /* define wait event timeout - 1s max */
  monitorSetNowait();
  monitorSetNoWaitNetworkTimeout(1000);

  /* log start of process */
  printf("T0 monitoring program started\n");

  // Allocation of histograms - start
  TH1F *hCFD[24];
  TH2F *hCFD_QTC[24]; TH2F *hCFD_LED[24];
  Char_t  buf1[10], buf2[10],buf3[10],buf4[10];

   for(Int_t ic=0; ic<24; ic++) {
      sprintf(buf1,"CFD_QTC%i",ic+1);
      sprintf(buf2,"CFD_LED%i",ic+1);

      hCFD_QTC[ic] = new TH2F(buf1,"CFD_QTC",8000,0.5,8000.5,2000,10000.5,20000.5);
      hCFD_LED[ic] = new TH2F(buf2,"CFD_LED",1000,-500.0,500.0,100,14600.0,14700.0);
      if(ic<12){
	sprintf(buf3,"T0_C_%i_CFD",ic+1);
	hCFD[ic] = new TH1F(buf3,"CFD", 30000,0., 30000.);
      }
      else{
        sprintf(buf4,"T0_A_%i_CFD",ic-11);
        hCFD[ic] = new TH1F(buf4,"CFD", 30000,0., 30000.);
      }
    }

  // Allocation of histograms - end

  Int_t iev=0;
  /* main loop (infinite) */
  for(;;) {
    struct eventHeaderStruct *event;
    eventTypeType eventT;

    /* check shutdown condition */
    if (daqDA_checkShutdown()) {break;}

    /* get next event (blocking call until timeout) */
    status=monitorGetEventDynamic((void **)&event);
    if (status==(int)MON_ERR_EOF) {
      printf ("End of File detected\n");
      break; /* end of monitoring file has been reached */
    }

    if (status!=0) {
      printf("monitorGetEventDynamic() failed : %s\n",monitorDecodeError(status));
      break;
    }

    /* retry if got no event */
    if (event==NULL) {
      continue;
    }

    iev++;

    /* use event - here, just write event id to result file */
    eventT=event->eventType;

    switch (event->eventType){

      case START_OF_RUN:
	break;

      case END_OF_RUN:
	break;

//      case CALIBRATION_EVENT:
      case PHYSICS_EVENT:
      printf(" event number = %i \n",iev);

      // Initalize raw-data reading and decoding
      AliRawReader *reader = new AliRawReaderDate((void*)event);

      // Enable the following two lines in case of real-data
   //       reader->LoadEquipmentIdsMap("T0map.txt");
    //     reader->RequireHeader(kFALSE);
     // 	  reader->RequireHeader(kTRUE);
      AliT0RawReader *start = new AliT0RawReader(reader, kTRUE);

      // Read raw data
      Int_t allData[105][5];
      for(Int_t i0=0;i0<105;i0++)
      	for(Int_t j0=0;j0<5;j0++)
		allData[i0][j0] = 0;

      if(start->Next())
      for (Int_t i=0; i<105; i++) {
	for(Int_t iHit=0;iHit<5;iHit++){
	  allData[i][iHit]= start->GetData(i,iHit);
        }
      }
	else
	printf("No T0 data found!!\n");

      // Fill the histograms

      for (Int_t ik = 0; ik<24; ik+=2)
         for (Int_t iHt=0; iHt<5; iHt++){
		 Int_t cc = ik/2;
		if((allData[cc+1][iHt]-allData[0][0])>0){
		 hCFD[cc]->Fill(allData[cc+1][iHt]-allData[0][0]);
		}
		if(allData[ik+25][iHt]!=0 && allData[ik+26][iHt]!=0 && allData[cc+1][iHt]!=0){
                 hCFD_QTC[cc]->Fill((allData[ik+25][iHt]-allData[ik+26][iHt]) , (allData[cc+1][iHt]-allData[0][0]));
		 }
                if(allData[cc+13][iHt]!=0 && allData[cc+1][iHt]!=0){
		 hCFD_LED[cc]->Fill(allData[cc+13][iHt]-allData[cc+1][iHt],allData[cc+1][iHt]-allData[0][0]);
		 }
	}

      for (Int_t ik = 24; ik<48; ik+=2)
         for (Int_t iHt=0; iHt<5; iHt++){
		 Int_t cc = ik/2;
                if((allData[cc+45][iHt]-allData[0][0])>0){
                 hCFD[cc]->Fill(allData[cc+45][iHt]-allData[0][0]);
                }

                if(allData[ik+57][iHt]!=0 && allData[ik+58][iHt]!=0){
                if(allData[cc+45][iHt]!=0)
                 hCFD_QTC[cc]->Fill(allData[ik+57][iHt]-allData[ik+58][iHt],allData[cc+45][iHt]-allData[0][0]);
		 }
                if(allData[cc+57][iHt]!=0 && allData[cc+45][iHt]!=0){
                 hCFD_LED[cc]->Fill(allData[cc+57][iHt]-allData[cc+45][iHt],allData[cc+45][iHt]-allData[0][0]);
                 }
	}

     delete start;
	start = 0x0;
     reader->Reset();
      // End of fill histograms

    }

    /* free resources */
    free(event);

    /* exit when last event received, no need to wait for TERM signal */
    if (eventT==END_OF_RUN) {
      printf("EOR event detected\n");
      break;
    }
  }
printf("After loop, before writing histos\n");
  // write a file with the histograms
  TFile *hist = new TFile(FILE_OUT,"RECREATE");

  for(Int_t j=0;j<24;j++){
     hCFD_QTC[j]->Write();
     hCFD_LED[j]->Write();
     hCFD[j]->Write();
    }
  hist->Close();
  delete hist;

  return status;
}

<|endoftext|>


<commit_before>#include <stdio.h>
#include <PCU.h>
#include "parma.h"
#include "parma_balancer.h"
#include "parma_step.h"
#include "parma_sides.h"
#include "parma_weights.h"
#include "parma_targets.h"
#include "parma_selector.h"

namespace {
  class GhostElmBalancer : public parma::Balancer {
    private:
      int sideTol;
    public:
      GhostElmBalancer(apf::Mesh* m, int l, double f, int v)
        : Balancer(m, f, v, "ghostElms"), layers(l)
      {
        parma::Sides* s = parma::makeVtxSides(mesh);
        sideTol = static_cast<int>(parma::avgSharedSides(s));
        delete s;
        if( !PCU_Comm_Self() && verbose )
          fprintf(stdout, "sideTol %d\n", sideTol);
      }
      bool runStep(apf::MeshTag* wtag, double tolerance) {
        parma::Sides* s = parma::makeVtxSides(mesh);

        const double maxElmImb =
          Parma_GetWeightedEntImbalance(mesh, wtag, mesh->getDimension());
        double avgSides = parma::avgSharedSides(s);
        monitorUpdate(maxElmImb, iS, iA);
        monitorUpdate(avgSides, sS, sA);
        if( !PCU_Comm_Self() && verbose )
          fprintf(stdout, "avgSides %f\n", avgSides);

        parma::GhostWeights* gw =
          parma::makeGhostWeights(mesh, wtag, s, layers);
        parma::Weights* elmW = convertGhostToEntWeight(gw,3);
        destroyGhostWeights(gw);

        parma::Targets* t = parma::makeTargets(s, elmW, factor);
        parma::Selector* sel = parma::makeVtxSelector(mesh, wtag);

        if( verbose > 3 ) {
          fprintf(stderr, "%d tot %d %s\n", PCU_Comm_Self(), s->total(), s->print("sides").c_str());
          fprintf(stderr, "%d self %f %s\n", PCU_Comm_Self(), elmW->self(), elmW->print("weights").c_str());
          fprintf(stderr, "%d %s\n", PCU_Comm_Self(), t->print("tgts").c_str());
        }

        parma::BalOrStall* stopper =
          new parma::BalOrStall(iA, sA, sideTol*.001, verbose);
        parma::Stepper b(mesh, factor, s, elmW, t, sel, stopper);
        bool ret = b.step(tolerance, verbose);
        return ret;
      }
      int layers;
  };
}

class GhostElmGtVtxBalancer : public parma::Balancer {
  public:
    GhostElmGtVtxBalancer(apf::Mesh* m, int l, double f, int v)
      : Balancer(m, f, v, "ghostsElmGtVtx"), layers(l) { }
    bool runStep(apf::MeshTag*, double) { return true; }
    void balance(apf::MeshTag* wtag, double tolerance) {
      apf::Balancer* b = new GhostElmBalancer(mesh, layers, factor, verbose);
      b->balance(wtag, tolerance);
      delete b;
    }
  private:
    int layers;
};

apf::Balancer* Parma_MakeGhostDiffuser(apf::Mesh* m,
    int layers, double stepFactor, int verbosity) {
  return new GhostElmGtVtxBalancer(m, layers, stepFactor, verbosity);
}
<commit_msg>elm > vtx ghost balancer<commit_after>#include <stdio.h>
#include <PCU.h>
#include "parma.h"
#include "parma_balancer.h"
#include "parma_step.h"
#include "parma_sides.h"
#include "parma_weights.h"
#include "parma_targets.h"
#include "parma_selector.h"

namespace {
  class GhostElmBalancer : public parma::Balancer {
    private:
      int sideTol;
    public:
      GhostElmBalancer(apf::Mesh* m, int l, double f, int v)
        : Balancer(m, f, v, "ghostElms"), layers(l)
      {
        parma::Sides* s = parma::makeVtxSides(mesh);
        sideTol = static_cast<int>(parma::avgSharedSides(s));
        delete s;
        if( !PCU_Comm_Self() && verbose )
          fprintf(stdout, "sideTol %d\n", sideTol);
      }
      bool runStep(apf::MeshTag* wtag, double tolerance) {
        parma::Sides* s = parma::makeVtxSides(mesh);
        double avgSides = parma::avgSharedSides(s);
        if( !PCU_Comm_Self() && verbose )
          fprintf(stdout, "avgSides %f\n", avgSides);

        parma::GhostWeights* gw =
          parma::makeGhostWeights(mesh, wtag, s, layers);
        parma::Weights* elmW = convertGhostToEntWeight(gw,3);
        parma::Weights* vtxW = convertGhostToEntWeight(gw,0);
        destroyGhostWeights(gw);

        const double vtxImb = parma::getImbalance(vtxW);
        if( !PCU_Comm_Self() && verbose )
          fprintf(stdout, "vtx imbalance %.3f\n", vtxImb);

        const double elmImb = parma::getImbalance(elmW);
        monitorUpdate(elmImb, iS, iA);
        monitorUpdate(avgSides, sS, sA);

        parma::Targets* t = parma::makeTargets(s, elmW, factor);
        parma::Selector* sel = parma::makeElmSelector(mesh, wtag);
        parma::BalOrStall* stopper =
          new parma::BalOrStall(iA, sA, sideTol*.001, verbose);
        parma::Stepper b(mesh, factor, s, elmW, t, sel, stopper);
        bool ret = b.step(tolerance, verbose);
        return ret;
      }
      int layers;
  };

  class GhostVtxLtElmBalancer : public parma::Balancer {
    private:
      int sideTol;
      int layers;
      double maxElmImb;
      int stepNum;
    public:
      GhostVtxLtElmBalancer(apf::Mesh* m, double f, int v, int l)
        : Balancer(m, f, v, "ghostVtxLtElms"), layers(l), stepNum(0)
      {
        parma::Sides* s = parma::makeVtxSides(mesh);
        sideTol = static_cast<int>(parma::avgSharedSides(s));
        delete s;
        if( !PCU_Comm_Self() && verbose )
          fprintf(stdout, "sideTol %d\n", sideTol);
      }
      bool runStep(apf::MeshTag* wtag, double tolerance) {
        parma::Sides* s = parma::makeVtxSides(mesh);
        double avgSides = parma::avgSharedSides(s);
        if( !PCU_Comm_Self() && verbose )
          fprintf(stdout, "avgSides %f\n", avgSides);

        parma::GhostWeights* gw =
          parma::makeGhostWeights(mesh, wtag, s, layers);
        parma::Weights* vtxW = convertGhostToEntWeight(gw,0);
        parma::Weights* edgeW = convertGhostToEntWeight(gw,1);
        parma::Weights* elmW = convertGhostToEntWeight(gw,mesh->getDimension());
        destroyGhostWeights(gw);

        const double elmImb = parma::getImbalance(elmW);
        const double edgeImb = parma::getImbalance(edgeW);
        if( !PCU_Comm_Self() && verbose ) {
          fprintf(stdout, "elm imbalance %.3f\n", elmImb);
          fprintf(stdout, "edge imbalance %.3f\n", edgeImb);
        }
        if( !stepNum ) //FIXME need to set the imbalance at the beginning for the primary entity
          maxElmImb = elmImb;

        monitorUpdate(elmImb, iS, iA);
        monitorUpdate(avgSides, sS, sA);
        parma::Weights* w[2] = {elmW,vtxW};
        parma::Targets* t =
          parma::makeVtxElmTargets(s, w, sideTol, maxElmImb, factor); //FIXME
        delete w[0];
        parma::Selector* sel =
          parma::makeVtxLtElmSelector(mesh, wtag, maxElmImb);
        parma::BalOrStall* stopper =
          new parma::BalOrStall(iA, sA, sideTol*.001, verbose);
        parma::Stepper b(mesh, factor, s, vtxW, t, sel, stopper);
        bool ret = b.step(tolerance, verbose);
        stepNum++;
        return ret;
      }
  };
}

class GhostElmGtVtxBalancer : public parma::Balancer {
  public:
    GhostElmGtVtxBalancer(apf::Mesh* m, int l, double f, int v)
      : Balancer(m, f, v, "ghostsElmGtVtx"), layers(l) { }
    bool runStep(apf::MeshTag*, double) { return true; }
    void balance(apf::MeshTag* wtag, double tolerance) {
      apf::Balancer* b = new GhostElmBalancer(mesh, layers, factor, verbose);
      b->balance(wtag, tolerance);
      delete b;
      Parma_PrintPtnStats(mesh, "post-elements", (verbose>2));
      b = new GhostVtxLtElmBalancer(mesh, factor, verbose, layers);
      b->balance(wtag, tolerance);
      delete b;
    }
  private:
    int layers;
};

apf::Balancer* Parma_MakeGhostDiffuser(apf::Mesh* m,
    int layers, double stepFactor, int verbosity) {
  return new GhostElmGtVtxBalancer(m, layers, stepFactor, verbosity);
}
<|endoftext|>


<commit_before>// XFAIL: hexagon
// RUN: rm -rf %t
// RUN: %clang_cc1 -Wunused-local-typedef -x objective-c++ -fmodules -fimplicit-module-maps -fmodules-cache-path=%t -I %S/Inputs %s -fsyntax-only 2>&1 | FileCheck %s -check-prefix=CHECK_1
// RUN: %clang_cc1 -Wunused-local-typedef -x objective-c++ -fmodules -fimplicit-module-maps -fmodules-cache-path=%t -I %S/Inputs %s -fsyntax-only 2>&1 | FileCheck %s -check-prefix=CHECK_2 --allow-empty

// For modules, the warning should only fire the first time, when the module is
// built.
// CHECK_1: warning: unused typedef
// CHECK_2-NOT: warning: unused typedef
@import warn_unused_local_typedef;
<commit_msg>[Hexagon] unused-local-typedef warning test is passing.<commit_after>// RUN: rm -rf %t
// RUN: %clang_cc1 -Wunused-local-typedef -x objective-c++ -fmodules -fimplicit-module-maps -fmodules-cache-path=%t -I %S/Inputs %s -fsyntax-only 2>&1 | FileCheck %s -check-prefix=CHECK_1
// RUN: %clang_cc1 -Wunused-local-typedef -x objective-c++ -fmodules -fimplicit-module-maps -fmodules-cache-path=%t -I %S/Inputs %s -fsyntax-only 2>&1 | FileCheck %s -check-prefix=CHECK_2 --allow-empty

// For modules, the warning should only fire the first time, when the module is
// built.
// CHECK_1: warning: unused typedef
// CHECK_2-NOT: warning: unused typedef
@import warn_unused_local_typedef;
<|endoftext|>


<commit_before>#include "MACAddr.h"

#ifdef _WIN32
    #include <iphlpapi.h>
#endif

MACAddr::MACAddr() : addr(MAC_ADDR_LEN, 0){}

MACAddr::MACAddr(const string & macStr){
	addr.resize(6,0);
    std::istringstream macStream(macStr);
    for (uint8_t & macByte : addr){
        int byte;
        char colon;
        macStream >> std::hex >> byte >> colon;
        macByte = byte;
    }
}

MACAddr::MACAddr(const uint8_t * macAddrBytes){
	addr.clear();
    for (size_t ct=0; ct<6; ct++){
        addr.push_back(macAddrBytes[ct]);
    }
}

string MACAddr::to_string() const{
    std::ostringstream ss;
    for(const uint8_t curByte : addr){
        ss << std::hex << std::setfill('0') << std::setw(2) << static_cast<int>(curByte) << ":";
    }
    //remove the trailing ":"
    string myStr = ss.str();
    myStr.pop_back();
    return myStr;
}
<commit_msg>Remove unused header.<commit_after>#include "MACAddr.h"

MACAddr::MACAddr() : addr(MAC_ADDR_LEN, 0){}

MACAddr::MACAddr(const string & macStr){
	addr.resize(6,0);
    std::istringstream macStream(macStr);
    for (uint8_t & macByte : addr){
        int byte;
        char colon;
        macStream >> std::hex >> byte >> colon;
        macByte = byte;
    }
}

MACAddr::MACAddr(const uint8_t * macAddrBytes){
	addr.clear();
    for (size_t ct=0; ct<6; ct++){
        addr.push_back(macAddrBytes[ct]);
    }
}

string MACAddr::to_string() const{
    std::ostringstream ss;
    for(const uint8_t curByte : addr){
        ss << std::hex << std::setfill('0') << std::setw(2) << static_cast<int>(curByte) << ":";
    }
    //remove the trailing ":"
    string myStr = ss.str();
    myStr.pop_back();
    return myStr;
}
<|endoftext|>


<commit_before>#include <iostream>
#include <random>

#include <simulated_annealing.hpp>

//parameters to optimize
struct Parameters
{
    double x;
};

double cost_function(const Parameters& p)
{
    return p.x * (p.x - 1);
}

struct Energy
{
    double operator()(const Parameters& p) const
    {
        return cost_function(p);
    }
};

struct Generator
{
    Parameters operator()(Parameters const& p, const SimulatedAnnealing& s) const
    {
        std::random_device rd;
        std::mt19937 generator(rd());
        std::normal_distribution<> distrib(0, 1.0);

        // return Parameters{p.x + distrib(generator)};
        return Parameters{p.x + 0.01 * s.current_temperature * distrib(generator)};
    }
};

int main()
{
    SimulatedAnnealing sim(1e3, 1e-3, int(1e2));

    Energy energy;
    Parameters params{1e3};
    Generator gen;

    std::cout << "initial value: " << params.x << " (err: " << energy(params) << ")" << std::endl;

    sim(energy, params, gen);

    std::cout << "final value: " << params.x << " (err: " << energy(params) << ")" << std::endl;
}
<commit_msg>[simple_function2] updated function to optimize<commit_after>#include <iostream>
#include <random>

#include <simulated_annealing.hpp>

//parameters to optimize
struct Parameters
{
    double x;
};

double cost_function(const Parameters& p)
{
    return 5.0 * std::cos(0.25 * p.x) + p.x * (p.x / 750.0);
}

struct Energy
{
    double operator()(const Parameters& p) const
    {
        return cost_function(p);
    }
};

struct Generator
{
    Parameters operator()(Parameters const& p, const SimulatedAnnealing& s) const
    {
        std::random_device rd;
        std::mt19937 generator(rd());
        std::normal_distribution<> distrib(0, 1.0);

        // return Parameters{p.x + distrib(generator)};
        // return Parameters{p.x + 0.01 * s.current_temperature * distrib(generator)};
        // return Parameters{p.x + s.current_temperature * distrib(generator)};
        return Parameters{p.x + s.current_temperature * s.current_it * distrib(generator)};
    }
};

int main()
{
    SimulatedAnnealing sim(1e3, 1e-3, int(1e2));

    Energy energy;
    Parameters params{1e3};
    Generator gen;

    std::cout << "initial value: " << params.x << " (err: " << energy(params) << ")" << std::endl;

    sim(energy, params, gen);

    std::cout << "final value: " << params.x << " (err: " << energy(params) << ")" << std::endl;
}
<|endoftext|>


<commit_before>/***************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: altstrfunc.cxx,v $
 *
 *  $Revision: 1.6 $
 *
 *  last change: $Author: ihi $ $Date: 2007-11-23 16:51:12 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_lingucomponent.hxx"

#ifndef _ALT_STRFUNC_HXX_
#include "altstrfunc.hxx"
#endif

#include <sal/types.h>

std::string upperCase(const std::string &s) {
    std::string upper(s);
    for(size_t i = 0; i < s.length(); i++)
        upper[i] = sal::static_int_cast< char >( toupper(upper[i]) );
    return upper;
}

int start(const std::string &s1, const std::string &s2){
    size_t i;
    int ret = 0;

    size_t min = s1.length();
    if (min > s2.length())
        min = s2.length();

    for(i = 0; i < min && s2[i] && s1[i] && !ret; i++){
        ret = toupper(s1[i]) - toupper(s2[i]);
        if(s1[i] == '.' || s2[i] == '.'){ret = 0;}//. is a neutral character
    }
    return ret;
}

<commit_msg>INTEGRATION: CWS changefileheader (1.6.32); FILE MERGED 2008/04/01 12:31:36 thb 1.6.32.2: #i85898# Stripping all external header guards 2008/03/31 16:25:03 rt 1.6.32.1: #i87441# Change license header to LPGL v3.<commit_after>/***************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: altstrfunc.cxx,v $
 * $Revision: 1.7 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_lingucomponent.hxx"
#include "altstrfunc.hxx"

#include <sal/types.h>

std::string upperCase(const std::string &s) {
    std::string upper(s);
    for(size_t i = 0; i < s.length(); i++)
        upper[i] = sal::static_int_cast< char >( toupper(upper[i]) );
    return upper;
}

int start(const std::string &s1, const std::string &s2){
    size_t i;
    int ret = 0;

    size_t min = s1.length();
    if (min > s2.length())
        min = s2.length();

    for(i = 0; i < min && s2[i] && s1[i] && !ret; i++){
        ret = toupper(s1[i]) - toupper(s2[i]);
        if(s1[i] == '.' || s2[i] == '.'){ret = 0;}//. is a neutral character
    }
    return ret;
}

<|endoftext|>


<commit_before>#include "StdAfx.h"
#include "IEBrowserEngine.h"
#include "common/RhoConf.h"
#include "MainWindow.h"

#if defined(_WIN32_WCE)
#include <webvw.h>
#endif

CIEBrowserEngine::CIEBrowserEngine(HWND hParentWnd, HINSTANCE hInstance) :
    m_spIWebBrowser2(NULL)
{
#if defined(_WIN32_WCE)
    m_browser.Create(hParentWnd,
                     CWindow::rcDefault, // proper sizing is done in CMainWindow::OnSize
		    		 TEXT("Microsoft.PIEDocView"), // ProgID of the control
                     WS_CHILD, 0,
                     ID_BROWSER);

#else
	m_browser.Create(hParentWnd,
                     CWindow::rcDefault, // proper sizing is done in CMainWindow::OnSize
					 TEXT("Shell.Explorer"), // ProgID of the control
                     WS_CHILD | WS_CLIPSIBLINGS | WS_CLIPCHILDREN, 0,
                     ID_BROWSER);
#endif

    // cache IWebBrowser2 interface pointer
    HRESULT hr = m_browser.QueryControl(&m_spIWebBrowser2);
    m_spIWebBrowser2->put_AddressBar(VARIANT_FALSE);

    if ( !RHOCONF().getBool("wm_show_statusbar") )
        m_spIWebBrowser2->put_StatusBar(VARIANT_FALSE);

}

CIEBrowserEngine::~CIEBrowserEngine(void)
{
    //TODO: destroy browser
}

BOOL CIEBrowserEngine::Navigate(LPCTSTR szURL)
{
    BSTR bstrUrl = SysAllocString(szURL);
    BOOL bRes = m_spIWebBrowser2->Navigate(bstrUrl, NULL, &CComVariant(L"_self"), NULL, NULL) == S_OK;

    SysFreeString(bstrUrl);

    return bRes;
}

BOOL CIEBrowserEngine::ResizeOnTab(int iInstID,RECT rcNewSize)
{
    return m_browser.MoveWindow(&rcNewSize);
}

BOOL CIEBrowserEngine::BackOnTab(int iInstID,int iPagesBack /*= 1*/)
{
    return m_spIWebBrowser2->GoBack() == S_OK;
}

BOOL CIEBrowserEngine::ForwardOnTab(int iInstID)
{
    return m_spIWebBrowser2->GoForward() == S_OK;
}

BOOL CIEBrowserEngine::Reload(bool bFromCache)
{
    return m_spIWebBrowser2->Refresh() == S_OK;
}

static void writeHtmlToTheDoc (
#if defined(_WIN32_WCE) && !defined( OS_PLATFORM_CE )
					IPIEHTMLDocument2 *document
#else
					IHTMLDocument2 *document
#endif
					, LPCTSTR szHtml)
{
	HRESULT hresult = S_OK;
	VARIANT *param;
	SAFEARRAY *sfArray;
	//std::wstring html;
	BSTR bstr = SysAllocString(szHtml);

	// Creates a new one-dimensional array
	sfArray = SafeArrayCreateVector(VT_VARIANT, 0, 1);

	if (sfArray && document)
    {
	    hresult = SafeArrayAccessData(sfArray,(LPVOID*) & param);
	    param->vt = VT_BSTR;
	    param->bstrVal = bstr;
	    hresult = SafeArrayUnaccessData(sfArray);
	    hresult = document->write(sfArray);
    }

	SysFreeString(bstr);
	if (sfArray != NULL) {
		SafeArrayDestroy(sfArray);
	}
}

BOOL CIEBrowserEngine::NavigateToHtml(LPCTSTR szHtml)
{
	HRESULT hr;
	IDispatch* pHtmlDoc = NULL;

    // Retrieve the document object.
    hr = m_spIWebBrowser2->get_Document( &pHtmlDoc );
    if ( SUCCEEDED(hr) )
    {
#if defined(_WIN32_WCE)&& !defined( OS_PLATFORM_CE )
		IPIEHTMLDocument2* pDoc;
		hr = pHtmlDoc->QueryInterface(__uuidof(IPIEHTMLDocument2),  (void**)&pDoc );
#else
		IHTMLDocument2* pDoc;
		hr = pHtmlDoc->QueryInterface(__uuidof(IHTMLDocument2),  (void**)&pDoc );
#endif
        if ( SUCCEEDED(hr) )
        {
			// Write to the document
			writeHtmlToTheDoc(pDoc, szHtml);
			pDoc->Release();
        }
    }

    return TRUE;
}

LRESULT CIEBrowserEngine::OnWebKitMessages(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled)
{
    bHandled = FALSE;
    return 0;
}

void CIEBrowserEngine::RunMessageLoop(CMainWindow& mainWnd)
{
    MSG msg;
    while (GetMessage(&msg, NULL, 0, 0))
    {
        if (!mainWnd.TranslateAccelerator(&msg))
        {
            TranslateMessage(&msg);
            DispatchMessage(&msg);
        }
    }
}<commit_msg>wm: webkit config parsing implemented<commit_after>#include "stdafx.h"
#include "IEBrowserEngine.h"
#include "common/RhoConf.h"
#include "MainWindow.h"

#if defined(_WIN32_WCE)
#include <webvw.h>
#endif

CIEBrowserEngine::CIEBrowserEngine(HWND hParentWnd, HINSTANCE hInstance) :
    m_spIWebBrowser2(NULL)
{
#if defined(_WIN32_WCE)
    m_browser.Create(hParentWnd,
                     CWindow::rcDefault, // proper sizing is done in CMainWindow::OnSize
		    		 TEXT("Microsoft.PIEDocView"), // ProgID of the control
                     WS_CHILD, 0,
                     ID_BROWSER);

#else
	m_browser.Create(hParentWnd,
                     CWindow::rcDefault, // proper sizing is done in CMainWindow::OnSize
					 TEXT("Shell.Explorer"), // ProgID of the control
                     WS_CHILD | WS_CLIPSIBLINGS | WS_CLIPCHILDREN, 0,
                     ID_BROWSER);
#endif

    // cache IWebBrowser2 interface pointer
    HRESULT hr = m_browser.QueryControl(&m_spIWebBrowser2);
    m_spIWebBrowser2->put_AddressBar(VARIANT_FALSE);

    if ( !RHOCONF().getBool("wm_show_statusbar") )
        m_spIWebBrowser2->put_StatusBar(VARIANT_FALSE);

}

CIEBrowserEngine::~CIEBrowserEngine(void)
{
    //TODO: destroy browser
}

BOOL CIEBrowserEngine::Navigate(LPCTSTR szURL)
{
    BSTR bstrUrl = SysAllocString(szURL);
    BOOL bRes = m_spIWebBrowser2->Navigate(bstrUrl, NULL, &CComVariant(L"_self"), NULL, NULL) == S_OK;

    SysFreeString(bstrUrl);

    return bRes;
}

BOOL CIEBrowserEngine::ResizeOnTab(int iInstID,RECT rcNewSize)
{
    return m_browser.MoveWindow(&rcNewSize);
}

BOOL CIEBrowserEngine::BackOnTab(int iInstID,int iPagesBack /*= 1*/)
{
    return m_spIWebBrowser2->GoBack() == S_OK;
}

BOOL CIEBrowserEngine::ForwardOnTab(int iInstID)
{
    return m_spIWebBrowser2->GoForward() == S_OK;
}

BOOL CIEBrowserEngine::Reload(bool bFromCache)
{
    return m_spIWebBrowser2->Refresh() == S_OK;
}

static void writeHtmlToTheDoc (
#if defined(_WIN32_WCE) && !defined( OS_PLATFORM_CE )
					IPIEHTMLDocument2 *document
#else
					IHTMLDocument2 *document
#endif
					, LPCTSTR szHtml)
{
	HRESULT hresult = S_OK;
	VARIANT *param;
	SAFEARRAY *sfArray;
	//std::wstring html;
	BSTR bstr = SysAllocString(szHtml);

	// Creates a new one-dimensional array
	sfArray = SafeArrayCreateVector(VT_VARIANT, 0, 1);

	if (sfArray && document)
    {
	    hresult = SafeArrayAccessData(sfArray,(LPVOID*) & param);
	    param->vt = VT_BSTR;
	    param->bstrVal = bstr;
	    hresult = SafeArrayUnaccessData(sfArray);
	    hresult = document->write(sfArray);
    }

	SysFreeString(bstr);
	if (sfArray != NULL) {
		SafeArrayDestroy(sfArray);
	}
}

BOOL CIEBrowserEngine::NavigateToHtml(LPCTSTR szHtml)
{
	HRESULT hr;
	IDispatch* pHtmlDoc = NULL;

    // Retrieve the document object.
    hr = m_spIWebBrowser2->get_Document( &pHtmlDoc );
    if ( SUCCEEDED(hr) )
    {
#if defined(_WIN32_WCE)&& !defined( OS_PLATFORM_CE )
		IPIEHTMLDocument2* pDoc;
		hr = pHtmlDoc->QueryInterface(__uuidof(IPIEHTMLDocument2),  (void**)&pDoc );
#else
		IHTMLDocument2* pDoc;
		hr = pHtmlDoc->QueryInterface(__uuidof(IHTMLDocument2),  (void**)&pDoc );
#endif
        if ( SUCCEEDED(hr) )
        {
			// Write to the document
			writeHtmlToTheDoc(pDoc, szHtml);
			pDoc->Release();
        }
    }

    return TRUE;
}

LRESULT CIEBrowserEngine::OnWebKitMessages(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled)
{
    bHandled = FALSE;
    return 0;
}

void CIEBrowserEngine::RunMessageLoop(CMainWindow& mainWnd)
{
    MSG msg;
    while (GetMessage(&msg, NULL, 0, 0))
    {
        if (!mainWnd.TranslateAccelerator(&msg))
        {
            TranslateMessage(&msg);
            DispatchMessage(&msg);
        }
    }
}<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: imageresourceaccess.cxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-08 16:18:43 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#ifndef SVTOOLS_SOURCE_MISC_IMAGERESOURCEACCESS_HXX
#include "imageresourceaccess.hxx"
#endif

/** === begin UNO includes === **/
#ifndef _COM_SUN_STAR_IO_NOTCONNECTEDEXCEPTION_HPP_
#include <com/sun/star/io/NotConnectedException.hpp>
#endif
#ifndef _COM_SUN_STAR_IO_XSEEKABLE_HPP_
#include <com/sun/star/io/XSeekable.hpp>
#endif
#ifndef _COM_SUN_STAR_GRAPHIC_XGRAPHICPROVIDER_HPP_
#include <com/sun/star/graphic/XGraphicProvider.hpp>
#endif
#ifndef _COM_SUN_STAR_IO_XSTREAM_HPP_
#include <com/sun/star/io/XStream.hpp>
#endif
/** === end UNO includes === **/

#ifndef _UNTOOLS_UCBSTREAMHELPER_HXX
#include <unotools/ucbstreamhelper.hxx>
#endif
#ifndef _STREAM_HXX
#include <tools/stream.hxx>
#endif
#ifndef _UTL_STREAM_WRAPPER_HXX_
#include <unotools/streamwrap.hxx>
#endif
#ifndef _CPPUHELPER_IMPLBASE2_HXX_
#include <cppuhelper/implbase2.hxx>
#endif

//........................................................................
namespace svt
{
//........................................................................

    using namespace ::utl;
    using namespace ::comphelper;
    using namespace ::com::sun::star::io;
    using namespace ::com::sun::star::uno;
    using namespace ::com::sun::star::lang;
    using namespace ::com::sun::star::beans;
    using namespace ::com::sun::star::graphic;

    //====================================================================
    //= StreamSupplier
    //====================================================================
    typedef ::cppu::WeakImplHelper2 <   XStream
                                    ,   XSeekable
                                    >   StreamSupplier_Base;
    class StreamSupplier : public StreamSupplier_Base
    {
    private:
        Reference< XInputStream >   m_xInput;
        Reference< XOutputStream >  m_xOutput;
        Reference< XSeekable >      m_xSeekable;

    public:
        StreamSupplier( const Reference< XInputStream >& _rxInput, const Reference< XOutputStream >& _rxOutput );

    protected:
        // XStream
        virtual Reference< XInputStream > SAL_CALL getInputStream(  ) throw (RuntimeException);
        virtual Reference< XOutputStream > SAL_CALL getOutputStream(  ) throw (RuntimeException);

        // XSeekable
        virtual void SAL_CALL seek( ::sal_Int64 location ) throw (::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::io::IOException, ::com::sun::star::uno::RuntimeException);
        virtual ::sal_Int64 SAL_CALL getPosition(  ) throw (::com::sun::star::io::IOException, ::com::sun::star::uno::RuntimeException);
        virtual ::sal_Int64 SAL_CALL getLength(  ) throw (::com::sun::star::io::IOException, ::com::sun::star::uno::RuntimeException);
    };

    //--------------------------------------------------------------------
    StreamSupplier::StreamSupplier( const Reference< XInputStream >& _rxInput, const Reference< XOutputStream >& _rxOutput )
        :m_xInput( _rxInput )
        ,m_xOutput( _rxOutput )
    {
        m_xSeekable = m_xSeekable.query( m_xInput );
        if ( !m_xSeekable.is() )
            m_xSeekable = m_xSeekable.query( m_xOutput );
        OSL_ENSURE( m_xSeekable.is(), "StreamSupplier::StreamSupplier: at least one of both must be seekable!" );
    }

    //--------------------------------------------------------------------
    Reference< XInputStream > SAL_CALL StreamSupplier::getInputStream(  ) throw (RuntimeException)
    {
        return m_xInput;
    }

    //--------------------------------------------------------------------
    Reference< XOutputStream > SAL_CALL StreamSupplier::getOutputStream(  ) throw (RuntimeException)
    {
        return m_xOutput;
    }

    //--------------------------------------------------------------------
    void SAL_CALL StreamSupplier::seek( ::sal_Int64 location ) throw (IllegalArgumentException, IOException, RuntimeException)
    {
        if ( !m_xSeekable.is() )
            throw NotConnectedException();

        m_xSeekable->seek( location );
    }

    //--------------------------------------------------------------------
    ::sal_Int64 SAL_CALL StreamSupplier::getPosition(  ) throw (IOException, RuntimeException)
    {
        if ( !m_xSeekable.is() )
            throw NotConnectedException();

        return m_xSeekable->getPosition();
    }

    //--------------------------------------------------------------------
    ::sal_Int64 SAL_CALL StreamSupplier::getLength(  ) throw (IOException, RuntimeException)
    {
        if ( !m_xSeekable.is() )
            throw NotConnectedException();

        return m_xSeekable->getLength();
    }

    //====================================================================
    //= ImageResourceAccess
    //====================================================================
    //--------------------------------------------------------------------
    bool ImageResourceAccess::isImageResourceURL( const ::rtl::OUString& _rURL )
    {
        ::rtl::OUString sIndicator( RTL_CONSTASCII_USTRINGPARAM( "private:resource/" ) );
        return _rURL.indexOf( sIndicator ) == 0;
    }

    //--------------------------------------------------------------------
    SvStream* ImageResourceAccess::getImageStream( const Reference< XMultiServiceFactory >& _rxORB, const ::rtl::OUString& _rImageResourceURL )
    {
        SvStream* pReturn = NULL;

        try
        {
            // get a GraphicProvider
            Reference< XGraphicProvider > xProvider;
            if ( _rxORB.is() )
                xProvider = xProvider.query( _rxORB->createInstance( ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "com.sun.star.graphic.GraphicProvider" ) ) ) );
            OSL_ENSURE( xProvider.is(), "ImageResourceAccess::getImageStream: could not create a graphic provider!" );

            if ( !xProvider.is() )
                return pReturn;

            // let it create a graphic from the given URL
            Sequence< PropertyValue > aMediaProperties( 1 );
            aMediaProperties[0].Name = ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "URL" ) );
            aMediaProperties[0].Value <<= _rImageResourceURL;
            Reference< XGraphic > xGraphic( xProvider->queryGraphic( aMediaProperties ) );
            OSL_ENSURE( xGraphic.is(), "ImageResourceAccess::getImageStream: the provider did not give us a graphic object!" );
            if ( !xGraphic.is() )
                return pReturn;

            // copy the graphic to a in-memory buffer
            SvMemoryStream* pMemBuffer = new SvMemoryStream;
            Reference< XStream > xBufferAccess = new StreamSupplier(
                new OSeekableInputStreamWrapper( *pMemBuffer ),
                new OSeekableOutputStreamWrapper( *pMemBuffer )
            );

            aMediaProperties.realloc( 2 );
            aMediaProperties[0].Name = ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "OutputStream" ) );
            aMediaProperties[0].Value <<= xBufferAccess;
            aMediaProperties[1].Name = ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "MimeType" ) );
            aMediaProperties[1].Value <<= ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "image/png" ) );
            xProvider->storeGraphic( xGraphic, aMediaProperties );

            pMemBuffer->Seek( 0 );
            pReturn = pMemBuffer;
        }
        catch( const Exception& )
        {
            OSL_ENSURE( sal_False, "ImageResourceAccess::getImageStream: caught an exception!" );
        }

        return pReturn;
    }

    //--------------------------------------------------------------------
    Reference< XInputStream > ImageResourceAccess::getImageXStream( const Reference< XMultiServiceFactory >& _rxORB, const ::rtl::OUString& _rImageResourceURL )
    {
        return new OSeekableInputStreamWrapper( getImageStream( _rxORB, _rImageResourceURL ), sal_True );   // take ownership
    }

//........................................................................
} // namespace svt
//........................................................................

<commit_msg>INTEGRATION: CWS pchfix02 (1.3.326); FILE MERGED 2006/09/01 17:43:20 kaib 1.3.326.1: #i68856# Added header markers and pch files<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: imageresourceaccess.cxx,v $
 *
 *  $Revision: 1.4 $
 *
 *  last change: $Author: obo $ $Date: 2006-09-17 15:10:51 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_svtools.hxx"

#ifndef SVTOOLS_SOURCE_MISC_IMAGERESOURCEACCESS_HXX
#include "imageresourceaccess.hxx"
#endif

/** === begin UNO includes === **/
#ifndef _COM_SUN_STAR_IO_NOTCONNECTEDEXCEPTION_HPP_
#include <com/sun/star/io/NotConnectedException.hpp>
#endif
#ifndef _COM_SUN_STAR_IO_XSEEKABLE_HPP_
#include <com/sun/star/io/XSeekable.hpp>
#endif
#ifndef _COM_SUN_STAR_GRAPHIC_XGRAPHICPROVIDER_HPP_
#include <com/sun/star/graphic/XGraphicProvider.hpp>
#endif
#ifndef _COM_SUN_STAR_IO_XSTREAM_HPP_
#include <com/sun/star/io/XStream.hpp>
#endif
/** === end UNO includes === **/

#ifndef _UNTOOLS_UCBSTREAMHELPER_HXX
#include <unotools/ucbstreamhelper.hxx>
#endif
#ifndef _STREAM_HXX
#include <tools/stream.hxx>
#endif
#ifndef _UTL_STREAM_WRAPPER_HXX_
#include <unotools/streamwrap.hxx>
#endif
#ifndef _CPPUHELPER_IMPLBASE2_HXX_
#include <cppuhelper/implbase2.hxx>
#endif

//........................................................................
namespace svt
{
//........................................................................

    using namespace ::utl;
    using namespace ::comphelper;
    using namespace ::com::sun::star::io;
    using namespace ::com::sun::star::uno;
    using namespace ::com::sun::star::lang;
    using namespace ::com::sun::star::beans;
    using namespace ::com::sun::star::graphic;

    //====================================================================
    //= StreamSupplier
    //====================================================================
    typedef ::cppu::WeakImplHelper2 <   XStream
                                    ,   XSeekable
                                    >   StreamSupplier_Base;
    class StreamSupplier : public StreamSupplier_Base
    {
    private:
        Reference< XInputStream >   m_xInput;
        Reference< XOutputStream >  m_xOutput;
        Reference< XSeekable >      m_xSeekable;

    public:
        StreamSupplier( const Reference< XInputStream >& _rxInput, const Reference< XOutputStream >& _rxOutput );

    protected:
        // XStream
        virtual Reference< XInputStream > SAL_CALL getInputStream(  ) throw (RuntimeException);
        virtual Reference< XOutputStream > SAL_CALL getOutputStream(  ) throw (RuntimeException);

        // XSeekable
        virtual void SAL_CALL seek( ::sal_Int64 location ) throw (::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::io::IOException, ::com::sun::star::uno::RuntimeException);
        virtual ::sal_Int64 SAL_CALL getPosition(  ) throw (::com::sun::star::io::IOException, ::com::sun::star::uno::RuntimeException);
        virtual ::sal_Int64 SAL_CALL getLength(  ) throw (::com::sun::star::io::IOException, ::com::sun::star::uno::RuntimeException);
    };

    //--------------------------------------------------------------------
    StreamSupplier::StreamSupplier( const Reference< XInputStream >& _rxInput, const Reference< XOutputStream >& _rxOutput )
        :m_xInput( _rxInput )
        ,m_xOutput( _rxOutput )
    {
        m_xSeekable = m_xSeekable.query( m_xInput );
        if ( !m_xSeekable.is() )
            m_xSeekable = m_xSeekable.query( m_xOutput );
        OSL_ENSURE( m_xSeekable.is(), "StreamSupplier::StreamSupplier: at least one of both must be seekable!" );
    }

    //--------------------------------------------------------------------
    Reference< XInputStream > SAL_CALL StreamSupplier::getInputStream(  ) throw (RuntimeException)
    {
        return m_xInput;
    }

    //--------------------------------------------------------------------
    Reference< XOutputStream > SAL_CALL StreamSupplier::getOutputStream(  ) throw (RuntimeException)
    {
        return m_xOutput;
    }

    //--------------------------------------------------------------------
    void SAL_CALL StreamSupplier::seek( ::sal_Int64 location ) throw (IllegalArgumentException, IOException, RuntimeException)
    {
        if ( !m_xSeekable.is() )
            throw NotConnectedException();

        m_xSeekable->seek( location );
    }

    //--------------------------------------------------------------------
    ::sal_Int64 SAL_CALL StreamSupplier::getPosition(  ) throw (IOException, RuntimeException)
    {
        if ( !m_xSeekable.is() )
            throw NotConnectedException();

        return m_xSeekable->getPosition();
    }

    //--------------------------------------------------------------------
    ::sal_Int64 SAL_CALL StreamSupplier::getLength(  ) throw (IOException, RuntimeException)
    {
        if ( !m_xSeekable.is() )
            throw NotConnectedException();

        return m_xSeekable->getLength();
    }

    //====================================================================
    //= ImageResourceAccess
    //====================================================================
    //--------------------------------------------------------------------
    bool ImageResourceAccess::isImageResourceURL( const ::rtl::OUString& _rURL )
    {
        ::rtl::OUString sIndicator( RTL_CONSTASCII_USTRINGPARAM( "private:resource/" ) );
        return _rURL.indexOf( sIndicator ) == 0;
    }

    //--------------------------------------------------------------------
    SvStream* ImageResourceAccess::getImageStream( const Reference< XMultiServiceFactory >& _rxORB, const ::rtl::OUString& _rImageResourceURL )
    {
        SvStream* pReturn = NULL;

        try
        {
            // get a GraphicProvider
            Reference< XGraphicProvider > xProvider;
            if ( _rxORB.is() )
                xProvider = xProvider.query( _rxORB->createInstance( ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "com.sun.star.graphic.GraphicProvider" ) ) ) );
            OSL_ENSURE( xProvider.is(), "ImageResourceAccess::getImageStream: could not create a graphic provider!" );

            if ( !xProvider.is() )
                return pReturn;

            // let it create a graphic from the given URL
            Sequence< PropertyValue > aMediaProperties( 1 );
            aMediaProperties[0].Name = ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "URL" ) );
            aMediaProperties[0].Value <<= _rImageResourceURL;
            Reference< XGraphic > xGraphic( xProvider->queryGraphic( aMediaProperties ) );
            OSL_ENSURE( xGraphic.is(), "ImageResourceAccess::getImageStream: the provider did not give us a graphic object!" );
            if ( !xGraphic.is() )
                return pReturn;

            // copy the graphic to a in-memory buffer
            SvMemoryStream* pMemBuffer = new SvMemoryStream;
            Reference< XStream > xBufferAccess = new StreamSupplier(
                new OSeekableInputStreamWrapper( *pMemBuffer ),
                new OSeekableOutputStreamWrapper( *pMemBuffer )
            );

            aMediaProperties.realloc( 2 );
            aMediaProperties[0].Name = ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "OutputStream" ) );
            aMediaProperties[0].Value <<= xBufferAccess;
            aMediaProperties[1].Name = ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "MimeType" ) );
            aMediaProperties[1].Value <<= ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "image/png" ) );
            xProvider->storeGraphic( xGraphic, aMediaProperties );

            pMemBuffer->Seek( 0 );
            pReturn = pMemBuffer;
        }
        catch( const Exception& )
        {
            OSL_ENSURE( sal_False, "ImageResourceAccess::getImageStream: caught an exception!" );
        }

        return pReturn;
    }

    //--------------------------------------------------------------------
    Reference< XInputStream > ImageResourceAccess::getImageXStream( const Reference< XMultiServiceFactory >& _rxORB, const ::rtl::OUString& _rImageResourceURL )
    {
        return new OSeekableInputStreamWrapper( getImageStream( _rxORB, _rImageResourceURL ), sal_True );   // take ownership
    }

//........................................................................
} // namespace svt
//........................................................................

<|endoftext|>


<commit_before>#include <iostream>
#include <iomanip>
#include <cmath>
#include <fstream>
#include <string>

//For convenience.
using std::cout;
using std::cin;
using std::endl;
using std::ifstream;
using std::ofstream;
using std::setw;
using std::getline;
using std::string;

//Constant declarations.
const int   LOT  = 28;
const int   BLD  = 40;
const int   COL  = 2;
const float MAX  = 200000.0;

//Store parking lot info.
struct ParkingLot{
    string lotId;
    int    capacity;
};
//Store building info.
struct Building{
    string bldId;
    int    occupancy[24][5];
};

//For readability.
enum LotNames{ROSE, FAIRVIEW, BELL, INGRAMN, INGRAMS, PARKINGSERV, MAINST,
              PUBLICSAFETY, COLLEGEHEIGHTS, SPORTSPLEX, CITYVIEW, GREEKROW,
              RUTHERFORD, SOFTBALL, EZELL, MTSUBLVDG, REC, ABERNATHY, MTSU,
              HIGHLAND, MEC, BELLSTG, JACKSON, LIVESTOCK, GREENHOUSE,
              CHAMPIONWAYG, GREENLAND, MIDDLETN};

enum BldNames{PCS, FAIR, EHS, ING, ALOF, ALUM, UP, HARR, BH, JUB, PH, KOM, VET,
              AMG, SFA, WMB, JH, TODD, WPS, DSB, KUC, FH, BDA, CKNB, LRC, SCI,
              LIB, BAS, SAG, HMA, TCM, HOB, TLC, MB, BRAGG, COE, VA, HC, GH,
              HONR};

enum Weekday{MON, TUE, WED, THUR, FRI};

void   ReadFiles(ParkingLot lotArray[LOT], float distanceFromLot[LOT][BLD],
                 Building bldArray[BLD]);
/*
float  Gamma(string lotId, float distanceFromLot, float time, char day);
void   beta(float time, char day, std::string lotArray);
float  Population(float time, char day);
*/
int main()
{
    ParkingLot lotArray[LOT];
    Building   bldArray[BLD];
    float      distanceFromLot[LOT][BLD],
               time;
    char       day;
    ReadFiles(lotArray, distanceFromLot, bldArray);

   // Gamma(lotArray[].lotId, distanceFromLot[][], time, day);
   // beta(time, day, );
//    Population(time, day);
    return 0;
}

//Read parkinglots.dat file into an array of type ParkingLot.
void ReadFiles(ParkingLot lotArray[LOT], float distanceFromLot[LOT][BLD],
        Building bldArray[BLD])
{
    ifstream   inFile1,
               inFile2,
               inFile3;
    string     trashCollect;

    inFile1.open("parkinglots.dat");
    inFile2.open("buildingToLotDistance.dat");
    inFile3.open("RyansDesires.txt");

    getline(inFile1, trashCollect);
    getline(inFile2, trashCollect);

    for(int i = 0; i < LOT; i++)
    {
        inFile1 >> lotArray[i].lotId;
        for(int j = 0; j < COL; j++)
            inFile1 >> trashCollect;
        inFile1 >> lotArray[i].capacity;
    }

    for(int i = 0; i < LOT; i++)
    {
        inFile2 >> trashCollect;
        inFile2 >> trashCollect;
        for(int j = 0; j < BLD; j++)
            inFile2 >> distanceFromLot[i][j];
    }

    for(int i = 0; i < BLD; i++)
    {
        inFile3 >> bldArray[i].bldId;
        for(int j = 0; j < 24; j++)
            for(int k = MON; k <= FRI; k++)
                inFile3 >> bldArray[i].occupancy[j][k];

        cout << bldArray[i].bldId << endl << "-----------------------" << endl;
        for(int j = 0; j < 24; j++)
        {
            for(int k = MON; k <= FRI; k++)
                cout << bldArray[i].occupancy[j][k] << " ";
             cout << endl;
        }
    }

}
/*
float Gamma(string lotId, float distanceFromLot, float time, char day)
{
    float population;
    //beta(time, day, lotarray)
    if(time == 6 || time == 18)
        return MAX;
    population = ((time - 12)*(time - 12))/((time - 6)*(time - 18));

   return 0.01;
}

void beta(float time, char day, std::string lotArray)
{
    Population(time, day);
    return;
}

int Population(float time, char day, Building bldArray[BLD])
{
    int population = 0;

    if(day == 'm')
        for(int i = 0; i < BLD; i++)
            population += bldArray[i].occupancy[MON];
    else if(day == 't')
        for(int i = 0; i < BLD; i++)
            population += bldArray[i].occupancy[TUE];
    else if(day == 'w')
        for(int i = 0; i < BLD; i++)
            population += bldArray[i].occupancy[WED];
    else if(day == 'r')
        for(int i = 0; i < BLD; i++)
            population += bldArray[i].occupancy[THUR];
    else if(day == 'f')
        for(int i = 0; i < BLD; i++)
            population += bldArray[i].occupancy[FRI];

    return population;
}

*/
<commit_msg>Delete JasonBourneCity.cpp<commit_after><|endoftext|>


<commit_before>// Copyright 2017 Proyectos y Sistemas de Mantenimiento SL (eProsima).
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#include <fastrtps/xmlparser/XMLParser.h>
#include <xmlparser/XMLTree.h>

#include <gtest/gtest.h>

using eprosima::fastrtps::xmlparser::BaseNode;
using eprosima::fastrtps::xmlparser::DataNode;
using eprosima::fastrtps::xmlparser::NodeType;
using eprosima::fastrtps::xmlparser::XMLParser;

class XMLTreeTests : public ::testing::Test
{
  public:
    XMLTreeTests()
    {
    }

    ~XMLTreeTests()
    {
    }
};

TEST_F(XMLTreeTests, OnlyRoot)
{
    BaseNode test_base{NodeType::ROOT};
    ASSERT_EQ(NodeType::ROOT, test_base.getType());
    ASSERT_EQ(false, test_base.removeChild(0));
    ASSERT_EQ(nullptr, test_base.getChild(0));
    ASSERT_EQ(nullptr, test_base.getParent());
    ASSERT_EQ(0, test_base.getNumChildren());
}

TEST_F(XMLTreeTests, RootChildren)
{
    BaseNode test_base{NodeType::ROOT};

    ASSERT_EQ(false, test_base.removeChild(0));
    ASSERT_EQ(nullptr, test_base.getChild(0));
    ASSERT_EQ(0, test_base.getNumChildren());

    BaseNode* child = new BaseNode{NodeType::APPLICATION};
    test_base.addChild(std::unique_ptr<BaseNode>(child));

    ASSERT_EQ(1, test_base.getNumChildren());
    ASSERT_EQ(child, test_base.getChild(0));
    ASSERT_EQ(&test_base, test_base.getChild(0)->getParent());
    ASSERT_EQ(NodeType::APPLICATION, test_base.getChild(0)->getType());
    ASSERT_EQ(true, test_base.removeChild(0));
    ASSERT_EQ(0, test_base.getNumChildren());
    ASSERT_EQ(false, test_base.removeChild(0));
}

TEST_F(XMLTreeTests, RootMultipleChildren)
{
    const int num_children = 10;
    BaseNode test_base{NodeType::ROOT};

    ASSERT_EQ(false, test_base.removeChild(0));
    ASSERT_EQ(nullptr, test_base.getChild(0));
    ASSERT_EQ(0, test_base.getNumChildren());

    std::vector<BaseNode*> children_backup;
    for (int i = 0; i < num_children; ++i)
    {
        children_backup.push_back(new BaseNode{NodeType::APPLICATION});
        test_base.addChild(std::unique_ptr<BaseNode>(children_backup[i]));
    }

    for (int i = 0; i < num_children; ++i)
    {
        ASSERT_EQ(children_backup[i], test_base.getChild(i));
        ASSERT_EQ(&test_base, test_base.getChild(i)->getParent());
        ASSERT_EQ(NodeType::APPLICATION, test_base.getChild(i)->getType());
    }

    for (int i = 0; i < num_children; ++i)
    {
        ASSERT_EQ(num_children-i, test_base.getNumChildren());
        ASSERT_EQ(true, test_base.removeChild(0));
        ASSERT_EQ(num_children-i-1, test_base.getNumChildren());
        ASSERT_EQ(false, test_base.removeChild(num_children-i));
    }
}

TEST_F(XMLTreeTests, DataNode)
{;
    const std::string attribute_name0{"Attribute0"};
    const std::string attribute_name1{"Attribute1"};
    const std::string attribute_value0{"TESTATTRIBUTE"};
    const std::string attribute_value1{"TESTATTRIBUTE1"};

    DataNode<std::string> data_node{NodeType::PUBLISHER};
    std::string* data = new std::string("TESTDATA");

    data_node.setData(std::unique_ptr<std::string>(data));
    data_node.addAttribute(attribute_name0, attribute_value0);
    data_node.addAttribute(attribute_name1, attribute_value1);

    ASSERT_EQ(NodeType::PUBLISHER, data_node.getType());
    ASSERT_EQ(data, data_node.getData());
    ASSERT_STREQ(attribute_value0.data(), data_node.getAttributes().at(attribute_name0).data());
    ASSERT_STREQ(attribute_value1.data(), data_node.getAttributes().at(attribute_name1).data());
}

class XMLParserTests : public ::testing::Test
{
  public:
    XMLParserTests()
    {
    }

    ~XMLParserTests()
    {
    }
};

int main(int argc, char** argv)
{
    testing::InitGoogleTest(&argc, argv);
    return RUN_ALL_TESTS();
}<commit_msg>DataNode returns smart_pointer<commit_after>// Copyright 2017 Proyectos y Sistemas de Mantenimiento SL (eProsima).
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#include <fastrtps/xmlparser/XMLParser.h>
#include <xmlparser/XMLTree.h>

#include <gtest/gtest.h>

using eprosima::fastrtps::xmlparser::BaseNode;
using eprosima::fastrtps::xmlparser::DataNode;
using eprosima::fastrtps::xmlparser::NodeType;
using eprosima::fastrtps::xmlparser::XMLParser;

class XMLTreeTests : public ::testing::Test
{
  public:
    XMLTreeTests()
    {
    }

    ~XMLTreeTests()
    {
    }
};

TEST_F(XMLTreeTests, OnlyRoot)
{
    BaseNode test_base{NodeType::ROOT};
    ASSERT_EQ(NodeType::ROOT, test_base.getType());
    ASSERT_EQ(false, test_base.removeChild(0));
    ASSERT_EQ(nullptr, test_base.getChild(0));
    ASSERT_EQ(nullptr, test_base.getParent());
    ASSERT_EQ(0, test_base.getNumChildren());
}

TEST_F(XMLTreeTests, RootChildren)
{
    BaseNode test_base{NodeType::ROOT};

    ASSERT_EQ(false, test_base.removeChild(0));
    ASSERT_EQ(nullptr, test_base.getChild(0));
    ASSERT_EQ(0, test_base.getNumChildren());

    BaseNode* child = new BaseNode{NodeType::APPLICATION};
    test_base.addChild(std::unique_ptr<BaseNode>(child));

    ASSERT_EQ(1, test_base.getNumChildren());
    ASSERT_EQ(child, test_base.getChild(0));
    ASSERT_EQ(&test_base, test_base.getChild(0)->getParent());
    ASSERT_EQ(NodeType::APPLICATION, test_base.getChild(0)->getType());
    ASSERT_EQ(true, test_base.removeChild(0));
    ASSERT_EQ(0, test_base.getNumChildren());
    ASSERT_EQ(false, test_base.removeChild(0));
}

TEST_F(XMLTreeTests, RootMultipleChildren)
{
    const int num_children = 10;
    BaseNode test_base{NodeType::ROOT};

    ASSERT_EQ(false, test_base.removeChild(0));
    ASSERT_EQ(nullptr, test_base.getChild(0));
    ASSERT_EQ(0, test_base.getNumChildren());

    std::vector<BaseNode*> children_backup;
    for (int i = 0; i < num_children; ++i)
    {
        children_backup.push_back(new BaseNode{NodeType::APPLICATION});
        test_base.addChild(std::unique_ptr<BaseNode>(children_backup[i]));
    }

    for (int i = 0; i < num_children; ++i)
    {
        ASSERT_EQ(children_backup[i], test_base.getChild(i));
        ASSERT_EQ(&test_base, test_base.getChild(i)->getParent());
        ASSERT_EQ(NodeType::APPLICATION, test_base.getChild(i)->getType());
    }

    for (int i = 0; i < num_children; ++i)
    {
        ASSERT_EQ(num_children-i, test_base.getNumChildren());
        ASSERT_EQ(true, test_base.removeChild(0));
        ASSERT_EQ(num_children-i-1, test_base.getNumChildren());
        ASSERT_EQ(false, test_base.removeChild(num_children-i));
    }
}

TEST_F(XMLTreeTests, DataNode)
{;
    const std::string attribute_name0{"Attribute0"};
    const std::string attribute_name1{"Attribute1"};
    const std::string attribute_value0{"TESTATTRIBUTE"};
    const std::string attribute_value1{"TESTATTRIBUTE1"};

    DataNode<std::string> data_node{NodeType::PUBLISHER};
    std::string* data = new std::string("TESTDATA");

    data_node.setData(std::unique_ptr<std::string>(data));
    data_node.addAttribute(attribute_name0, attribute_value0);
    data_node.addAttribute(attribute_name1, attribute_value1);

    ASSERT_EQ(NodeType::PUBLISHER, data_node.getType());
    ASSERT_EQ(data, data_node.getData().get());
    ASSERT_STREQ(attribute_value0.data(), data_node.getAttributes().at(attribute_name0).data());
    ASSERT_STREQ(attribute_value1.data(), data_node.getAttributes().at(attribute_name1).data());
}

class XMLParserTests : public ::testing::Test
{
  public:
    XMLParserTests()
    {
    }

    ~XMLParserTests()
    {
    }
};

int main(int argc, char** argv)
{
    testing::InitGoogleTest(&argc, argv);
    return RUN_ALL_TESTS();
}<|endoftext|>


<commit_before>/**
 * @file   MqCommonTest.cpp
 * @brief  MqCommon class tester.
 * @author zer0
 * @date   2018-11-16
 */

#include <gtest/gtest.h>
#include <libtbag/mq/details/MqCommon.hpp>
#include <libtbag/log/Log.hpp>

using namespace libtbag;
using namespace libtbag::mq;
using namespace libtbag::mq::details;

TEST(MqCommonTest, ConvertUriToParams)
{
    auto const PARAMS1 = convertUriToParams("tcp://192.168.0.1:9999?read_error=10&verify_msg=true");
    ASSERT_STREQ("192.168.0.1", PARAMS1.address.c_str());
    ASSERT_EQ(9999, PARAMS1.port);
    ASSERT_EQ(MqType::MT_TCP, PARAMS1.type);
    ASSERT_EQ(10, PARAMS1.continuous_read_error_count);
    ASSERT_TRUE(PARAMS1.verify_restore_message);

    auto const PARAMS2 = convertUriToParams("pipe:////./pipe/test?tcp_ipv6=true&send_msg=5", true);
    ASSERT_STREQ("\\\\.\\pipe\\test", PARAMS2.address.c_str());
    ASSERT_EQ(MqType::MT_PIPE, PARAMS2.type);
    ASSERT_TRUE(PARAMS2.tcp_ipv6_only);
    ASSERT_EQ(5, PARAMS2.send_msg_size);

    auto const PARAMS3 = convertUriToParams("pipe:///home/user/test.sock?tcp_ipv6=false&try_reconnect=4");
    ASSERT_STREQ("/home/user/test.sock", PARAMS3.address.c_str());
    ASSERT_EQ(MqType::MT_PIPE, PARAMS3.type);
    ASSERT_FALSE(PARAMS3.tcp_ipv6_only);
    ASSERT_EQ(4, PARAMS3.try_reconnect_count);

    log::SeverityGuard guard;
    auto const PARAMS4 = convertUriToParams("http://localhost?recv_queue=8");
    ASSERT_FALSE(PARAMS4.address.empty());
    ASSERT_STRNE("localhost", PARAMS4.address.c_str());
    ASSERT_EQ(80, PARAMS4.port);
    ASSERT_EQ(MqType::MT_TCP, PARAMS4.type);
    ASSERT_EQ(8, PARAMS4.recv_queue_size);
}

<commit_msg>Create MqCommonTest.AppendLocalhost tester.<commit_after>/**
 * @file   MqCommonTest.cpp
 * @brief  MqCommon class tester.
 * @author zer0
 * @date   2018-11-16
 */

#include <gtest/gtest.h>
#include <libtbag/mq/details/MqCommon.hpp>
#include <libtbag/log/Log.hpp>

using namespace libtbag;
using namespace libtbag::mq;
using namespace libtbag::mq::details;

TEST(MqCommonTest, AppendLocalhost)
{
    std::string const TEST1   = "pIpE://\\\\.\\pipe\\temp";
    std::string const RESULT1 = "pIpE://localhost/\\\\.\\pipe\\temp";

    std::string const TEST2   = "pIpE://";
    std::string const RESULT2 = "pIpE://localhost/";

    ASSERT_EQ(RESULT1, __append_localhost_if_pipe_schema(TEST1));
    ASSERT_EQ(RESULT2, __append_localhost_if_pipe_schema(TEST2));
}

TEST(MqCommonTest, ConvertUriToParams)
{
    auto const PARAMS1 = convertUriToParams("tcp://192.168.0.1:9999?read_error=10&verify_msg=true");
    ASSERT_STREQ("192.168.0.1", PARAMS1.address.c_str());
    ASSERT_EQ(9999, PARAMS1.port);
    ASSERT_EQ(MqType::MT_TCP, PARAMS1.type);
    ASSERT_EQ(10, PARAMS1.continuous_read_error_count);
    ASSERT_TRUE(PARAMS1.verify_restore_message);

    auto const PARAMS2 = convertUriToParams("pipe://\\\\.\\pipe\\test?tcp_ipv6=true&send_msg=5");
    ASSERT_STREQ("\\\\.\\pipe\\test", PARAMS2.address.c_str());
    ASSERT_EQ(MqType::MT_PIPE, PARAMS2.type);
    ASSERT_TRUE(PARAMS2.tcp_ipv6_only);
    ASSERT_EQ(5, PARAMS2.send_msg_size);

    auto const PARAMS3 = convertUriToParams("pipe:///home/user/test.sock?tcp_ipv6=false&try_reconnect=4");
    ASSERT_STREQ("/home/user/test.sock", PARAMS3.address.c_str());
    ASSERT_EQ(MqType::MT_PIPE, PARAMS3.type);
    ASSERT_FALSE(PARAMS3.tcp_ipv6_only);
    ASSERT_EQ(4, PARAMS3.try_reconnect_count);

    log::SeverityGuard guard;
    auto const PARAMS4 = convertUriToParams("http://localhost?recv_queue=8");
    ASSERT_FALSE(PARAMS4.address.empty());
    ASSERT_STRNE("localhost", PARAMS4.address.c_str());
    ASSERT_EQ(80, PARAMS4.port);
    ASSERT_EQ(MqType::MT_TCP, PARAMS4.type);
    ASSERT_EQ(8, PARAMS4.recv_queue_size);
}

<|endoftext|>


<commit_before>// Copyright (c) 2009-2019 The Regents of the University of Michigan
// This file is part of the HOOMD-blue project, released under the BSD 3-Clause License.

// Maintainer: joaander

/*! \file BoxResizeUpdater.cc
    \brief Defines the BoxResizeUpdater class
*/

#include "BoxResizeUpdater.h"

#include <math.h>
#include <iostream>
#include <stdexcept>

using namespace std;
namespace py = pybind11;

/*! \param sysdef System definition containing the particle data to set the box size on
    \param Lx length of the x dimension over time
    \param Ly length of the y dimension over time
    \param Lz length of the z dimension over time

    The default setting is to scale particle positions along with the box.
*/
BoxResizeUpdater::BoxResizeUpdater(std::shared_ptr<SystemDefinition> sysdef,
                                   BoxDim box1,
                                   BoxDim box2,
                                   std::shared_ptr<Variant> variant)
    : Updater(sysdef), m_box1(box1), m_py_box1(pybind11::none()), m_box2(box2),
      m_py_box2(pybind11::none()), m_variant(variant), m_scale_particles(true)
    {
    m_exec_conf->msg->notice(5) << "Constructing BoxResizeUpdater" << endl;
    }

BoxResizeUpdater::BoxResizeUpdater(std::shared_ptr<SystemDefinition> sysdef,
                                   pybind11::object box1,
                                   pybind11::object box2,
                                   std::shared_ptr<Variant> variant)
    : Updater(sysdef), m_box1(getBoxDimFromPyObject(box1)), m_py_box1(box1),
      m_box2(getBoxDimFromPyObject(box2)), m_py_box2(box2),
      m_variant(variant), m_scale_particles(true)
    {
    m_exec_conf->msg->notice(5) << "Constructing BoxResizeUpdater" << endl;
    }

BoxResizeUpdater::~BoxResizeUpdater()
    {
    m_exec_conf->msg->notice(5) << "Destroying BoxResizeUpdater" << endl;
    }

void BoxResizeUpdater::setBox1(BoxDim box)
    {
    if (!m_py_box1.is_none())
        {
        m_py_box1 = m_py_box1.attr("__class__")
                            .attr("_from_cpp")(box);
        }
    m_box1 = box;
    }

void BoxResizeUpdater::setBox1Py(pybind11::object box)
    {
    m_box1 = getBoxDimFromPyObject(box);
    m_py_box1 = box;
    }

void BoxResizeUpdater::setBox2(BoxDim box)
    {
    if (!m_py_box2.is_none())
        {
        m_py_box2 = m_py_box2.attr("__class__")
                            .attr("_from_cpp")(box);
        }
    m_box2 = box;
    }

void BoxResizeUpdater::setBox2Py(pybind11::object box)
    {
    m_box2 = getBoxDimFromPyObject(box);
    m_py_box2 = box;
    }

/// Get the current box based on the timestep
BoxDim BoxResizeUpdater::getCurrentBox(unsigned int timestep)
    {
    Scalar min = m_variant->min();
    Scalar max = m_variant->max();
    Scalar cur_value = (*m_variant)(timestep);
    Scalar scale = 0;
    if (cur_value == max)
        {
        scale = 1;
        }
    else if (cur_value > min)
        {
        scale = (cur_value - min) / (max - min);
        }

    Scalar3 L1 = m_box1.getL();
    Scalar3 L2 = m_box2.getL();
    Scalar Lx = L2.x * scale + (1.0 - scale) * L1.x;
    Scalar Ly = L2.y * scale + (1.0 - scale) * L1.y;
    Scalar Lz = L2.z * scale + (1.0 - scale) * L1.z;
    Scalar xy = m_box2.getTiltFactorXY() * scale +
                (1.0 - scale) * m_box1.getTiltFactorXY();
    Scalar xz = m_box2.getTiltFactorXZ() * scale +
                (1.0 - scale) * m_box1.getTiltFactorXZ();
    Scalar yz = m_box2.getTiltFactorYZ() * scale +
                (1.0 - scale) * m_box1.getTiltFactorYZ();

    BoxDim new_box = BoxDim(make_scalar3(Lx, Ly, Lz));
    new_box.setTiltFactors(xy, xz, yz);
    return new_box;
    }

/// Return whether two boxes are equivalent upto 1e-7
bool BoxResizeUpdater::boxesAreEquivalent(BoxDim& box1, BoxDim& box2)
    {
    Scalar3 L1 = box1.getL();
    Scalar3 L2 = box2.getL();

    Scalar xy1 = box1.getTiltFactorXY();
    Scalar xy2 = box2.getTiltFactorXY();
    Scalar xz1 = box1.getTiltFactorXZ();
    Scalar xz2 = box2.getTiltFactorXZ();
    Scalar yz1 = box1.getTiltFactorYZ();
    Scalar yz2 = box2.getTiltFactorYZ();

    return fabs((L1.x - L2.x) / L1.x) < 1e-7 &&
           fabs((L1.y - L2.y) / L1.x) < 1e-7 &&
           fabs((L1.z - L2.z) / L1.x) < 1e-7 &&
           fabs((xy1 - xy2) / xy1) < 1e-7 &&
           fabs((xz1 - xz2) / xz1) < 1e-7 &&
           fabs((yz1 - yz2) / yz1) < 1e-7;
    }

/** Perform the needed calculations to scale the box size
    \param timestep Current time step of the simulation
*/
void BoxResizeUpdater::update(unsigned int timestep)
    {
    m_exec_conf->msg->notice(10) << "Box resize update" << endl;
    if (m_prof) m_prof->push("BoxResize");

    // first, compute the new box
    BoxDim new_box = getCurrentBox(timestep);

    // check if the current box size is the same
    BoxDim cur_box = m_pdata->getGlobalBox();

    // only change the box if there is a change in the box dimensions
    if (!boxesAreEquivalent(new_box, cur_box))
        {
        // set the new box
        m_pdata->setGlobalBox(new_box);

        // scale the particle positions (if we have been asked to)
        if (m_scale_particles)
            {
            // move the particles to be inside the new box
            ArrayHandle<Scalar4> h_pos(m_pdata->getPositions(),
                                       access_location::host,
                                       access_mode::readwrite);

            for (unsigned int i = 0; i < m_pdata->getN(); i++)
                {
                // obtain scaled coordinates in the old global box
                Scalar3 fractional_pos = cur_box.makeFraction(
                    make_scalar3(h_pos.data[i].x,
                                 h_pos.data[i].y,
                                 h_pos.data[i].z));

                // intentionally scale both rigid body and free particles, this
                // may waste a few cycles but it enables the debug inBox checks
                // to be left as is (otherwise, setRV cannot fixup rigid body
                // positions without failing the check)
                Scalar3 scaled_pos = new_box.makeCoordinates(fractional_pos);
                h_pos.data[i].x = scaled_pos.x;
                h_pos.data[i].y = scaled_pos.y;
                h_pos.data[i].z = scaled_pos.z;
                }
            }
        // otherwise, we need to ensure that the particles are still in their
        // local boxes by wrapping them if they are not
        else
            {
            ArrayHandle<Scalar4> h_pos(m_pdata->getPositions(),
                                       access_location::host,
                                       access_mode::readwrite);

            ArrayHandle<int3> h_image(m_pdata->getImages(),
                                      access_location::host,
                                      access_mode::readwrite);

            const BoxDim& local_box = m_pdata->getBox();

            for (unsigned int i = 0; i < m_pdata->getN(); i++)
                {
                // need to update the image if we move particles from one side
                // of the box to the other
                local_box.wrap(h_pos.data[i], h_image.data[i]);
                }
            }
        }
    if (m_prof) m_prof->pop();
    }

BoxDim getBoxDimFromPyObject(pybind11::object box)
    {
    auto type_name = box.get_type().attr("__name__").cast<std::string>();
    if (type_name != "Box")
        {
        std::string err = "Expected type of Box. Received type ";
        throw std::runtime_error(err + type_name);
        }
    return box.attr("_cpp_obj").cast<BoxDim>();
    }

void export_BoxResizeUpdater(py::module& m)
    {
    py::class_<BoxResizeUpdater, Updater,
               std::shared_ptr<BoxResizeUpdater> >(m,"BoxResizeUpdater")
    .def(pybind11::init<std::shared_ptr<SystemDefinition>,
                        pybind11::object, pybind11::object,
                        std::shared_ptr<Variant> >())
    .def_property("scale_particles",
                  &BoxResizeUpdater::getScaleParticles,
                  &BoxResizeUpdater::setScaleParticles)
    .def_property("box1",
                  &BoxResizeUpdater::getBox1Py,
                  &BoxResizeUpdater::setBox1Py)
    .def_property("box2",
                  &BoxResizeUpdater::getBox2Py,
                  &BoxResizeUpdater::setBox2Py)
    .def_property("variant",
                  &BoxResizeUpdater::getVariant,
                  &BoxResizeUpdater::setVariant)
    .def("get_current_box", &BoxResizeUpdater::getCurrentBox)
    ;
    }
<commit_msg>Move BoxResizeUpdater::boxesAreEquivalent to use absolute length checks<commit_after>// Copyright (c) 2009-2019 The Regents of the University of Michigan
// This file is part of the HOOMD-blue project, released under the BSD 3-Clause License.

// Maintainer: joaander

/*! \file BoxResizeUpdater.cc
    \brief Defines the BoxResizeUpdater class
*/

#include "BoxResizeUpdater.h"

#include <math.h>
#include <iostream>
#include <stdexcept>

using namespace std;
namespace py = pybind11;

/*! \param sysdef System definition containing the particle data to set the box size on
    \param Lx length of the x dimension over time
    \param Ly length of the y dimension over time
    \param Lz length of the z dimension over time

    The default setting is to scale particle positions along with the box.
*/
BoxResizeUpdater::BoxResizeUpdater(std::shared_ptr<SystemDefinition> sysdef,
                                   BoxDim box1,
                                   BoxDim box2,
                                   std::shared_ptr<Variant> variant)
    : Updater(sysdef), m_box1(box1), m_py_box1(pybind11::none()), m_box2(box2),
      m_py_box2(pybind11::none()), m_variant(variant), m_scale_particles(true)
    {
    m_exec_conf->msg->notice(5) << "Constructing BoxResizeUpdater" << endl;
    }

BoxResizeUpdater::BoxResizeUpdater(std::shared_ptr<SystemDefinition> sysdef,
                                   pybind11::object box1,
                                   pybind11::object box2,
                                   std::shared_ptr<Variant> variant)
    : Updater(sysdef), m_box1(getBoxDimFromPyObject(box1)), m_py_box1(box1),
      m_box2(getBoxDimFromPyObject(box2)), m_py_box2(box2),
      m_variant(variant), m_scale_particles(true)
    {
    m_exec_conf->msg->notice(5) << "Constructing BoxResizeUpdater" << endl;
    }

BoxResizeUpdater::~BoxResizeUpdater()
    {
    m_exec_conf->msg->notice(5) << "Destroying BoxResizeUpdater" << endl;
    }

void BoxResizeUpdater::setBox1(BoxDim box)
    {
    if (!m_py_box1.is_none())
        {
        m_py_box1 = m_py_box1.attr("__class__")
                            .attr("_from_cpp")(box);
        }
    m_box1 = box;
    }

void BoxResizeUpdater::setBox1Py(pybind11::object box)
    {
    m_box1 = getBoxDimFromPyObject(box);
    m_py_box1 = box;
    }

void BoxResizeUpdater::setBox2(BoxDim box)
    {
    if (!m_py_box2.is_none())
        {
        m_py_box2 = m_py_box2.attr("__class__")
                            .attr("_from_cpp")(box);
        }
    m_box2 = box;
    }

void BoxResizeUpdater::setBox2Py(pybind11::object box)
    {
    m_box2 = getBoxDimFromPyObject(box);
    m_py_box2 = box;
    }

/// Get the current box based on the timestep
BoxDim BoxResizeUpdater::getCurrentBox(unsigned int timestep)
    {
    Scalar min = m_variant->min();
    Scalar max = m_variant->max();
    Scalar cur_value = (*m_variant)(timestep);
    Scalar scale = 0;
    if (cur_value == max)
        {
        scale = 1;
        }
    else if (cur_value > min)
        {
        scale = (cur_value - min) / (max - min);
        }

    Scalar3 L1 = m_box1.getL();
    Scalar3 L2 = m_box2.getL();
    Scalar Lx = L2.x * scale + (1.0 - scale) * L1.x;
    Scalar Ly = L2.y * scale + (1.0 - scale) * L1.y;
    Scalar Lz = L2.z * scale + (1.0 - scale) * L1.z;
    Scalar xy = m_box2.getTiltFactorXY() * scale +
                (1.0 - scale) * m_box1.getTiltFactorXY();
    Scalar xz = m_box2.getTiltFactorXZ() * scale +
                (1.0 - scale) * m_box1.getTiltFactorXZ();
    Scalar yz = m_box2.getTiltFactorYZ() * scale +
                (1.0 - scale) * m_box1.getTiltFactorYZ();

    BoxDim new_box = BoxDim(make_scalar3(Lx, Ly, Lz));
    new_box.setTiltFactors(xy, xz, yz);
    return new_box;
    }

/// Return whether two boxes are equivalent upto 1e-7
bool BoxResizeUpdater::boxesAreEquivalent(BoxDim& box1, BoxDim& box2)
    {
    Scalar3 L1 = box1.getL();
    Scalar3 L2 = box2.getL();

    Scalar xy1 = box1.getTiltFactorXY();
    Scalar xy2 = box2.getTiltFactorXY();
    Scalar xz1 = box1.getTiltFactorXZ();
    Scalar xz2 = box2.getTiltFactorXZ();
    Scalar yz1 = box1.getTiltFactorYZ();
    Scalar yz2 = box2.getTiltFactorYZ();

    return L1.x == L2.x && L1.y == L2.y && L1.z == L2.z &&
           fabs((xy1 - xy2) / xy1) < 1e-7 &&
           fabs((xz1 - xz2) / xz1) < 1e-7 &&
           fabs((yz1 - yz2) / yz1) < 1e-7;
    }

/** Perform the needed calculations to scale the box size
    \param timestep Current time step of the simulation
*/
void BoxResizeUpdater::update(unsigned int timestep)
    {
    m_exec_conf->msg->notice(10) << "Box resize update" << endl;
    if (m_prof) m_prof->push("BoxResize");

    // first, compute the new box
    BoxDim new_box = getCurrentBox(timestep);

    // check if the current box size is the same
    BoxDim cur_box = m_pdata->getGlobalBox();

    // only change the box if there is a change in the box dimensions
    if (!boxesAreEquivalent(new_box, cur_box))
        {
        // set the new box
        m_pdata->setGlobalBox(new_box);

        // scale the particle positions (if we have been asked to)
        if (m_scale_particles)
            {
            // move the particles to be inside the new box
            ArrayHandle<Scalar4> h_pos(m_pdata->getPositions(),
                                       access_location::host,
                                       access_mode::readwrite);

            for (unsigned int i = 0; i < m_pdata->getN(); i++)
                {
                // obtain scaled coordinates in the old global box
                Scalar3 fractional_pos = cur_box.makeFraction(
                    make_scalar3(h_pos.data[i].x,
                                 h_pos.data[i].y,
                                 h_pos.data[i].z));

                // intentionally scale both rigid body and free particles, this
                // may waste a few cycles but it enables the debug inBox checks
                // to be left as is (otherwise, setRV cannot fixup rigid body
                // positions without failing the check)
                Scalar3 scaled_pos = new_box.makeCoordinates(fractional_pos);
                h_pos.data[i].x = scaled_pos.x;
                h_pos.data[i].y = scaled_pos.y;
                h_pos.data[i].z = scaled_pos.z;
                }
            }
        // otherwise, we need to ensure that the particles are still in their
        // local boxes by wrapping them if they are not
        else
            {
            ArrayHandle<Scalar4> h_pos(m_pdata->getPositions(),
                                       access_location::host,
                                       access_mode::readwrite);

            ArrayHandle<int3> h_image(m_pdata->getImages(),
                                      access_location::host,
                                      access_mode::readwrite);

            const BoxDim& local_box = m_pdata->getBox();

            for (unsigned int i = 0; i < m_pdata->getN(); i++)
                {
                // need to update the image if we move particles from one side
                // of the box to the other
                local_box.wrap(h_pos.data[i], h_image.data[i]);
                }
            }
        }
    if (m_prof) m_prof->pop();
    }

BoxDim getBoxDimFromPyObject(pybind11::object box)
    {
    auto type_name = box.get_type().attr("__name__").cast<std::string>();
    if (type_name != "Box")
        {
        std::string err = "Expected type of Box. Received type ";
        throw std::runtime_error(err + type_name);
        }
    return box.attr("_cpp_obj").cast<BoxDim>();
    }

void export_BoxResizeUpdater(py::module& m)
    {
    py::class_<BoxResizeUpdater, Updater,
               std::shared_ptr<BoxResizeUpdater> >(m,"BoxResizeUpdater")
    .def(pybind11::init<std::shared_ptr<SystemDefinition>,
                        pybind11::object, pybind11::object,
                        std::shared_ptr<Variant> >())
    .def_property("scale_particles",
                  &BoxResizeUpdater::getScaleParticles,
                  &BoxResizeUpdater::setScaleParticles)
    .def_property("box1",
                  &BoxResizeUpdater::getBox1Py,
                  &BoxResizeUpdater::setBox1Py)
    .def_property("box2",
                  &BoxResizeUpdater::getBox2Py,
                  &BoxResizeUpdater::setBox2Py)
    .def_property("variant",
                  &BoxResizeUpdater::getVariant,
                  &BoxResizeUpdater::setVariant)
    .def("get_current_box", &BoxResizeUpdater::getCurrentBox)
    ;
    }
<|endoftext|>