<commit_before>// Author: Bertrand Bellenot   22/08/02

/*************************************************************************
 * Copyright (C) 1995-2002, Bertrand Bellenot.                           *
 * All rights reserved.                                                  *
 *                                                                       *
 * For the licensing terms see the LICENSE file.                         *
 *************************************************************************/

#include <stdlib.h>

#include <TRandom.h>
#include <TParticle.h>
#include "MyParticle.h"
#include "TVector3.h"
#include "constants.h"
#include "RootShower.h"
#include "ParticlesDef.h"

//______________________________________________________________________________
//
// MyParticle class implementation
//______________________________________________________________________________

ClassImp(MyParticle)

//______________________________________________________________________________
MyParticle::MyParticle() : TParticle()
{
    // MyParticle constructor
    // initialize members to zero
    fstatus = 0;
    fnChildren = 0;
    fdecay_type = UNDEFINE;
    flocation = new TVector3();
    fpassed = 0.0;
    fEloss = 0.0;
    fdecay_length = 0.0;
    fChild[0] = 0;
    fChild[1] = 0;
    fChild[2] = 0;
    fChild[3] = 0;
    fChild[4] = 0;
    fChild[5] = 0;
    ftimeOfDecay = 0.0;
}

//______________________________________________________________________________
MyParticle::MyParticle(Int_t id, Int_t pType,Int_t pStat,Int_t pDecayType,const TVector3 &pLocation,
                       const TVector3 &pMomentum,Double_t pPassed, Double_t pDecayLen = 0.0,
                       Double_t pEnergy = 0.0)
          : TParticle(pType, pStat, 1, 0, 0, 0, pMomentum.x(), pMomentum.y(),
                        pMomentum.z(), pEnergy, pLocation.x(), pLocation.y(),
                        pLocation.z(), 0.0)
{
    // MyParticle constructor
    // initialize members with parameters passed in argument
    fId = id;
    fstatus = pStat;
    fnChildren = 0;
    fdecay_type = pDecayType;
    flocation = new TVector3(pLocation);
    fpassed = pPassed;
    fdecay_length = pDecayLen;
    fChild[0] = 0;
    fChild[1] = 0;
    fChild[2] = 0;
    fChild[3] = 0;
    fChild[4] = 0;
    fChild[5] = 0;
    ftimeOfDecay = 0.0;
}

//______________________________________________________________________________
MyParticle::MyParticle(Int_t id, Int_t pType,Int_t pStat,Int_t pDecayType,const TVector3 &pLocation,
                       const TVector3 &pMomentum)
          : TParticle(pType, pStat, 1, 0, 0, 0, pMomentum.x(), pMomentum.y(),
                        pMomentum.z(), 0.0, pLocation.x(), pLocation.y(),
                        pLocation.z(), 0.0)
{
    // MyParticle constructor
    // initialize members with parameters passed in argument
    fId = id;
    Double_t energy;
    fstatus = pStat;
    fnChildren = 0;
    fdecay_type = pDecayType;
    flocation = new TVector3(pLocation);
    fpassed = 0.0;
    fEloss = 0.0;
    fdecay_length = 0.0;
    fChild[0] = 0;
    fChild[1] = 0;
    fChild[2] = 0;
    fChild[3] = 0;
    fChild[4] = 0;
    fChild[5] = 0;
    if(GetMass() == 0.0)
        energy = pMomentum.Mag();
    else
        energy = sqrt((pMomentum * pMomentum)
                 +  (GetMass() * GetMass()));
    TParticle::SetMomentum(pMomentum.x(),pMomentum.y(),pMomentum.z(),energy);
    ftimeOfDecay = 0.0;
}

//______________________________________________________________________________
char *MyParticle::GetObjectInfo(Int_t, Int_t) const
{
   static char info[64];
   sprintf(info,"Particle = %s, E = %1.3e", GetName(), Energy());
   return info;
}

void MyParticle::SetMoment(const TVector3 &mom)
{
    // Set particle momentum with TVector3 members
    Double_t energy;
    if(GetMass() == 0.0)
        energy = mom.Mag();
    else
        energy = sqrt((mom * mom) +  (GetMass() * GetMass()));
    SetMomentum(mom.x(), mom.y(), mom.z(), energy);
}

void MyParticle::GenerateTimeOfDecay()
{
    // Generates time of decay for this type of particle.
    Int_t i;
    ftimeOfDecay = (GetPDG()->Lifetime() > 0 && GetPDG()->Lifetime() < 1e8)
	  ? gRandom->Exp(GetPDG()->Lifetime())
	  : GetPDG()->Lifetime();
    if(ftimeOfDecay == 0.0) {
        Int_t my_code = GetPdgCode();
        ftimeOfDecay = 1.0e-20;
        for(i=0;i<total_defs;i++) {
            if(particle_def[i].code == my_code) {
                ftimeOfDecay = particle_def[i].lifetime;
                break;
            }
        }
//        ftimeOfDecay *= 1.0e3;
        if (ftimeOfDecay <= 1.0e-20) {
            ftimeOfDecay = gRandom->Exp(1.0e-8);
        }
        else if (ftimeOfDecay > 0 && ftimeOfDecay < 1e8)
            ftimeOfDecay = gRandom->Exp(ftimeOfDecay);
    }
    // Apply Lorentz transformation for time dilatation
    ftimeOfDecay /= TMath::Sqrt(1.0 - (0.996 * 0.996));
}

//______________________________________________________________________________
const Char_t *MyParticle::GetName() const
{
    // get name of particle with its PDG number, or Unknown if
    // particle name is not defined into ParticlesDef.h
    Int_t i;
    Char_t *pdg_name = new Char_t[40];
    Int_t my_code = GetPdgCode();

    sprintf(pdg_name,"Unknown");
    for(i=0;i<total_defs;i++) {
        if(particle_def[i].code == my_code) {
            sprintf(pdg_name,"%s", particle_def[i].name);
            break;
        }
    }
    return pdg_name;
}

//______________________________________________________________________________
MyParticle::~MyParticle()
{
    // destructor
    delete   flocation;
}

<commit_msg>Remove optional default arguments in implementation file<commit_after>// Author: Bertrand Bellenot   22/08/02

/*************************************************************************
 * Copyright (C) 1995-2002, Bertrand Bellenot.                           *
 * All rights reserved.                                                  *
 *                                                                       *
 * For the licensing terms see the LICENSE file.                         *
 *************************************************************************/

#include <stdlib.h>

#include <TRandom.h>
#include <TParticle.h>
#include "MyParticle.h"
#include "TVector3.h"
#include "constants.h"
#include "RootShower.h"
#include "ParticlesDef.h"

//______________________________________________________________________________
//
// MyParticle class implementation
//______________________________________________________________________________

ClassImp(MyParticle)

//______________________________________________________________________________
MyParticle::MyParticle() : TParticle()
{
    // MyParticle constructor
    // initialize members to zero
    fstatus = 0;
    fnChildren = 0;
    fdecay_type = UNDEFINE;
    flocation = new TVector3();
    fpassed = 0.0;
    fEloss = 0.0;
    fdecay_length = 0.0;
    fChild[0] = 0;
    fChild[1] = 0;
    fChild[2] = 0;
    fChild[3] = 0;
    fChild[4] = 0;
    fChild[5] = 0;
    ftimeOfDecay = 0.0;
}

//______________________________________________________________________________
MyParticle::MyParticle(Int_t id, Int_t pType,Int_t pStat,Int_t pDecayType,const TVector3 &pLocation,
                       const TVector3 &pMomentum,Double_t pPassed, Double_t pDecayLen,
                       Double_t pEnergy)
          : TParticle(pType, pStat, 1, 0, 0, 0, pMomentum.x(), pMomentum.y(),
                        pMomentum.z(), pEnergy, pLocation.x(), pLocation.y(),
                        pLocation.z(), 0.0)
{
    // MyParticle constructor
    // initialize members with parameters passed in argument
    fId = id;
    fstatus = pStat;
    fnChildren = 0;
    fdecay_type = pDecayType;
    flocation = new TVector3(pLocation);
    fpassed = pPassed;
    fdecay_length = pDecayLen;
    fChild[0] = 0;
    fChild[1] = 0;
    fChild[2] = 0;
    fChild[3] = 0;
    fChild[4] = 0;
    fChild[5] = 0;
    ftimeOfDecay = 0.0;
}

//______________________________________________________________________________
MyParticle::MyParticle(Int_t id, Int_t pType,Int_t pStat,Int_t pDecayType,const TVector3 &pLocation,
                       const TVector3 &pMomentum)
          : TParticle(pType, pStat, 1, 0, 0, 0, pMomentum.x(), pMomentum.y(),
                        pMomentum.z(), 0.0, pLocation.x(), pLocation.y(),
                        pLocation.z(), 0.0)
{
    // MyParticle constructor
    // initialize members with parameters passed in argument
    fId = id;
    Double_t energy;
    fstatus = pStat;
    fnChildren = 0;
    fdecay_type = pDecayType;
    flocation = new TVector3(pLocation);
    fpassed = 0.0;
    fEloss = 0.0;
    fdecay_length = 0.0;
    fChild[0] = 0;
    fChild[1] = 0;
    fChild[2] = 0;
    fChild[3] = 0;
    fChild[4] = 0;
    fChild[5] = 0;
    if(GetMass() == 0.0)
        energy = pMomentum.Mag();
    else
        energy = sqrt((pMomentum * pMomentum)
                 +  (GetMass() * GetMass()));
    TParticle::SetMomentum(pMomentum.x(),pMomentum.y(),pMomentum.z(),energy);
    ftimeOfDecay = 0.0;
}

//______________________________________________________________________________
char *MyParticle::GetObjectInfo(Int_t, Int_t) const
{
   static char info[64];
   sprintf(info,"Particle = %s, E = %1.3e", GetName(), Energy());
   return info;
}

void MyParticle::SetMoment(const TVector3 &mom)
{
    // Set particle momentum with TVector3 members
    Double_t energy;
    if(GetMass() == 0.0)
        energy = mom.Mag();
    else
        energy = sqrt((mom * mom) +  (GetMass() * GetMass()));
    SetMomentum(mom.x(), mom.y(), mom.z(), energy);
}

void MyParticle::GenerateTimeOfDecay()
{
    // Generates time of decay for this type of particle.
    Int_t i;
    ftimeOfDecay = (GetPDG()->Lifetime() > 0 && GetPDG()->Lifetime() < 1e8)
	  ? gRandom->Exp(GetPDG()->Lifetime())
	  : GetPDG()->Lifetime();
    if(ftimeOfDecay == 0.0) {
        Int_t my_code = GetPdgCode();
        ftimeOfDecay = 1.0e-20;
        for(i=0;i<total_defs;i++) {
            if(particle_def[i].code == my_code) {
                ftimeOfDecay = particle_def[i].lifetime;
                break;
            }
        }
//        ftimeOfDecay *= 1.0e3;
        if (ftimeOfDecay <= 1.0e-20) {
            ftimeOfDecay = gRandom->Exp(1.0e-8);
        }
        else if (ftimeOfDecay > 0 && ftimeOfDecay < 1e8)
            ftimeOfDecay = gRandom->Exp(ftimeOfDecay);
    }
    // Apply Lorentz transformation for time dilatation
    ftimeOfDecay /= TMath::Sqrt(1.0 - (0.996 * 0.996));
}

//______________________________________________________________________________
const Char_t *MyParticle::GetName() const
{
    // get name of particle with its PDG number, or Unknown if
    // particle name is not defined into ParticlesDef.h
    Int_t i;
    Char_t *pdg_name = new Char_t[40];
    Int_t my_code = GetPdgCode();

    sprintf(pdg_name,"Unknown");
    for(i=0;i<total_defs;i++) {
        if(particle_def[i].code == my_code) {
            sprintf(pdg_name,"%s", particle_def[i].name);
            break;
        }
    }
    return pdg_name;
}

//______________________________________________________________________________
MyParticle::~MyParticle()
{
    // destructor
    delete   flocation;
}

<|endoftext|>


<commit_before>#undef SLOT

#include <ecl/ecl.h>
#include <eql5/eql.h>
#include <QApplication>
#include <QTextCodec>
#include <QSettings>
#include <QTranslator>

extern "C" void init_lib_NEXT__ALL_SYSTEMS(cl_object);

int catch_all_qexec() {
    int ret = 0;
    CL_CATCH_ALL_BEGIN(ecl_process_env()) {
        ret = QApplication::exec(); }
    CL_CATCH_ALL_END;
    return ret; }

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

    QCoreApplication::setAttribute(Qt::AA_ShareOpenGLContexts); // for Qt WebEngine
    QApplication qapp(argc, argv);

    QTextCodec* utf8 = QTextCodec::codecForName("UTF-8");
    QTextCodec::setCodecForLocale(utf8);

    EQL eql;

#ifdef Q_OS_WIN
    // print output would crash program
    eql.ignoreIOStreams();
#endif

    eql.exec(init_lib_NEXT__ALL_SYSTEMS);

    return catch_all_qexec(); } // closing the main/last window will quit the program
<commit_msg>simplified main.cpp<commit_after>#undef SLOT

#include <ecl/ecl.h>
#include <eql5/eql.h>
#include <QApplication>
#include <QTextCodec>
#include <QSettings>
#include <QTranslator>

extern "C" void init_lib_NEXT__ALL_SYSTEMS(cl_object);

int catch_all_qexec() {
    int ret = 0;
    CL_CATCH_ALL_BEGIN(ecl_process_env()) {
        ret = QApplication::exec(); }
    CL_CATCH_ALL_END;
    return ret; }

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

    EQL::ini(argv);

    QApplication qapp(argc, argv);

    QTextCodec* utf8 = QTextCodec::codecForName("UTF-8");
    QTextCodec::setCodecForLocale(utf8);

    EQL eql;

    eql.exec(init_lib_NEXT__ALL_SYSTEMS);

    return catch_all_qexec(); } // closing the main/last window will quit the program
<|endoftext|>


<commit_before>/*!
 * \page YieldTestSuite_cpp Command-Line Test to Demonstrate How To Test the AirRAC Project
 * \code
 */
// //////////////////////////////////////////////////////////////////////
// Import section
// //////////////////////////////////////////////////////////////////////
// STL
#include <sstream>
#include <fstream>
#include <string>
// Boost Unit Test Framework (UTF)
#define BOOST_TEST_DYN_LINK
#define BOOST_TEST_MAIN
#define BOOST_TEST_MODULE YieldTestSuite
#include <boost/test/unit_test.hpp>
// StdAir
#include <stdair/basic/BasLogParams.hpp>
#include <stdair/basic/BasDBParams.hpp>
#include <stdair/basic/BasFileMgr.hpp>
#include <stdair/bom/TravelSolutionStruct.hpp>
#include <stdair/service/Logger.hpp>
// Airrac
#include <airrac/AIRRAC_Service.hpp>
#include <airrac/config/airrac-paths.hpp>

namespace boost_utf = boost::unit_test;

// (Boost) Unit Test XML Report
std::ofstream utfReportStream ("YieldTestSuite_utfresults.xml");

/**
 * Configuration for the Boost Unit Test Framework (UTF)
 */
struct UnitTestConfig {
  /** Constructor. */
  UnitTestConfig() {
    boost_utf::unit_test_log.set_stream (utfReportStream);
    boost_utf::unit_test_log.set_format (boost_utf::XML);
    boost_utf::unit_test_log.set_threshold_level (boost_utf::log_test_units);
    //boost_utf::unit_test_log.set_threshold_level (boost_utf::log_successful_tests);
  }

  /** Destructor. */
  ~UnitTestConfig() {
  }
};

// /////////////// Main: Unit Test Suite //////////////

// Set the UTF configuration (re-direct the output to a specific file)
BOOST_GLOBAL_FIXTURE (UnitTestConfig);

// Start the test suite
BOOST_AUTO_TEST_SUITE (master_test_suite)

/**
 * Test a simple inventory sell
 */
BOOST_AUTO_TEST_CASE (airrac_simple_yield) {

  // Travel solution
  stdair::TravelSolutionStruct lTravelSolution;
  stdair::TravelSolutionList_T lTravelSolutionList;

  // Input file name
  const stdair::Filename_T lYieldInputFilename (STDAIR_SAMPLE_DIR
                                                "/yieldstore01.csv");

  // Check that the file path given as input corresponds to an actual file
  bool doesExistAndIsReadable =
    stdair::BasFileMgr::doesExistAndIsReadable (lYieldInputFilename);
  BOOST_CHECK_MESSAGE (doesExistAndIsReadable == true,
                       "The '" << lYieldInputFilename
                       << "' input file can not be open and read");

  // Output log File
  const stdair::Filename_T lLogFilename ("YieldTestSuite.log");

  // Set the log parameters
  std::ofstream logOutputFile;
  // Open and clean the log outputfile
  logOutputFile.open (lLogFilename.c_str());
  logOutputFile.clear();

  // Initialise the list of classes/buckets
  const stdair::BasLogParams lLogParams (stdair::LOG::DEBUG, logOutputFile);
  AIRRAC::AIRRAC_Service airracService (lLogParams, lYieldInputFilename);

  // Calculate the yields for the given travel solution
  lTravelSolutionList.push_back(lTravelSolution);
  airracService.calculateYields (lTravelSolutionList);

  // Close the log file
  logOutputFile.close();
}

// End the test suite
BOOST_AUTO_TEST_SUITE_END()

/*!
 * \endcode
 */

<commit_msg>[AirRAC][Test] Various updates from AirRAC tests.<commit_after>/*!
 * \page YieldTestSuite_cpp Command-Line Test to Demonstrate How To Test the AirRAC Project
 * \code
 */
// //////////////////////////////////////////////////////////////////////
// Import section
// //////////////////////////////////////////////////////////////////////
// STL
#include <sstream>
#include <fstream>
#include <string>
// Boost Unit Test Framework (UTF)
#define BOOST_TEST_DYN_LINK
#define BOOST_TEST_MAIN
#define BOOST_TEST_MODULE YieldTestSuite
#include <boost/test/unit_test.hpp>
// StdAir
#include <stdair/basic/BasLogParams.hpp>
#include <stdair/basic/BasDBParams.hpp>
#include <stdair/basic/BasFileMgr.hpp>
#include <stdair/bom/TravelSolutionStruct.hpp>
#include <stdair/service/Logger.hpp>
// Airrac
#include <airrac/AIRRAC_Service.hpp>
#include <airrac/config/airrac-paths.hpp>

namespace boost_utf = boost::unit_test;

// (Boost) Unit Test XML Report
std::ofstream utfReportStream ("YieldTestSuite_utfresults.xml");

/**
 * Configuration for the Boost Unit Test Framework (UTF)
 */
struct UnitTestConfig {
  /** Constructor. */
  UnitTestConfig() {
    boost_utf::unit_test_log.set_stream (utfReportStream);
    boost_utf::unit_test_log.set_format (boost_utf::XML);
    boost_utf::unit_test_log.set_threshold_level (boost_utf::log_test_units);
    //boost_utf::unit_test_log.set_threshold_level (boost_utf::log_successful_tests);
  }

  /** Destructor. */
  ~UnitTestConfig() {
  }
};

// /////////////// Main: Unit Test Suite //////////////

// Set the UTF configuration (re-direct the output to a specific file)
BOOST_GLOBAL_FIXTURE (UnitTestConfig);

// Start the test suite
BOOST_AUTO_TEST_SUITE (master_test_suite)

/**
 * Test a simple inventory sell
 */
BOOST_AUTO_TEST_CASE (airrac_simple_yield) {

  // Travel solution
  stdair::TravelSolutionStruct lTravelSolution;
  stdair::TravelSolutionList_T lTravelSolutionList;

  // Input file name
  const stdair::Filename_T lYieldInputFilename (STDAIR_SAMPLE_DIR
                                                "/yieldstore01.csv");

  // Check that the file path given as input corresponds to an actual file
  bool doesExistAndIsReadable =
    stdair::BasFileMgr::doesExistAndIsReadable (lYieldInputFilename);
  BOOST_CHECK_MESSAGE (doesExistAndIsReadable == true,
                       "The '" << lYieldInputFilename
                       << "' input file can not be open and read");

  // Output log File
  const stdair::Filename_T lLogFilename ("YieldTestSuite.log");

  // Set the log parameters
  std::ofstream logOutputFile;
  // Open and clean the log outputfile
  logOutputFile.open (lLogFilename.c_str());
  logOutputFile.clear();

  // Initialise the list of classes/buckets
  const stdair::BasLogParams lLogParams (stdair::LOG::DEBUG, logOutputFile);

  AIRRAC::AIRRAC_Service airracService (lLogParams);

  // Build the BOM tree from parsing a yield file
  airracService.parseAndLoad (lYieldInputFilename);

  // Calculate the yields for the given travel solution
  lTravelSolutionList.push_back(lTravelSolution);
  airracService.calculateYields (lTravelSolutionList);

  // Close the log file
  logOutputFile.close();
}

// End the test suite
BOOST_AUTO_TEST_SUITE_END()

/*!
 * \endcode
 */

<|endoftext|>


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

  Program:   Visualization Toolkit
  Module:    vtkImplicitWindowFunction.cxx
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

Copyright (c) 1993-1996 Ken Martin, Will Schroeder, Bill Lorensen.

This software is copyrighted by Ken Martin, Will Schroeder and Bill Lorensen.
The following terms apply to all files associated with the software unless
explicitly disclaimed in individual files. This copyright specifically does
not apply to the related textbook "The Visualization Toolkit" ISBN
013199837-4 published by Prentice Hall which is covered by its own copyright.

The authors hereby grant permission to use, copy, and distribute this
software and its documentation for any purpose, provided that existing
copyright notices are retained in all copies and that this notice is included
verbatim in any distributions. Additionally, the authors grant permission to
modify this software and its documentation for any purpose, provided that
such modifications are not distributed without the explicit consent of the
authors and that existing copyright notices are retained in all copies. Some
of the algorithms implemented by this software are patented, observe all
applicable patent law.

IN NO EVENT SHALL THE AUTHORS OR DISTRIBUTORS BE LIABLE TO ANY PARTY FOR
DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
OF THE USE OF THIS SOFTWARE, ITS DOCUMENTATION, OR ANY DERIVATIVES THEREOF,
EVEN IF THE AUTHORS HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

THE AUTHORS AND DISTRIBUTORS SPECIFICALLY DISCLAIM ANY WARRANTIES, INCLUDING,
BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
PARTICULAR PURPOSE, AND NON-INFRINGEMENT.  THIS SOFTWARE IS PROVIDED ON AN
"AS IS" BASIS, AND THE AUTHORS AND DISTRIBUTORS HAVE NO OBLIGATION TO PROVIDE
MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.

=========================================================================*/
#include "vtkImplicitWindowFunction.h"

// Description:
// Construct object with window range (0,1) and window values (0,1).
vtkImplicitWindowFunction::vtkImplicitWindowFunction()
{
  this->ImplicitFunction = NULL;

  this->WindowRange[0] = 0.0;
  this->WindowRange[1] = 1.0;

  this->WindowValues[0] = 0.0;
  this->WindowValues[1] = 1.0;
}

vtkImplicitWindowFunction::~vtkImplicitWindowFunction()
{
}

// Description
// Evaluate window function.
float vtkImplicitWindowFunction::EvaluateFunction(float x[3])
{
  static int beenWarned=0;
  float value, diff1, diff2, scaledRange;

  if ( ! this->ImplicitFunction && ! beenWarned )
    {
    vtkErrorMacro(<<"Implicit function must be defined");
    beenWarned = 1;
    return 0.0;
    }

  value = this->ImplicitFunction->EvaluateFunction(x);

  diff1 = value - this->WindowRange[0];
  diff2 = value - this->WindowRange[1];

  scaledRange = (this->WindowValues[1] - this->WindowValues[0]) / 2.0;
  if ( scaledRange == 0.0 ) scaledRange = 1.0;

  if ( diff1 >= 0.0 && diff2 <= 0.0 ) //within window
    {
    if ( diff1 <= (-diff2) )
      {
      value = diff1 / scaledRange + this->WindowValues[0];
      }
    else
      {
      value = (-diff2) / scaledRange + this->WindowValues[0];
      }
    }

  else if ( diff1 < 0.0 ) //below window
    {
    value = diff1 / scaledRange + this->WindowValues[0];
    }

  else //above window
    {
    value = -diff2 / scaledRange + this->WindowValues[0];
    }

  return value;
}

// Description
// Evaluate window function gradient. Just return implicit function gradient.
void vtkImplicitWindowFunction::EvaluateGradient(float x[3], float n[3])
{
    if ( this->ImplicitFunction )
      {
      this->ImplicitFunction->EvaluateGradient(x,n);
      }
}

unsigned long int vtkImplicitWindowFunction::GetMTime()
{
  unsigned long int fMtime;
  unsigned long int mtime = this->vtkImplicitFunction::GetMTime();

  if ( this->ImplicitFunction ) fMtime = this->ImplicitFunction->GetMTime();
  if ( fMtime > mtime ) mtime = fMtime;

  return mtime;
}

void vtkImplicitWindowFunction::PrintSelf(ostream& os, vtkIndent indent)
{
  vtkImplicitFunction::PrintSelf(os,indent);

  if ( this->ImplicitFunction )
    {
    os << indent << "Implicit Function: " << this->ImplicitFunction << "\n";
    }
  else
    {
    os << indent << "No implicit function defined.\n";
    }

  os << indent << "Window Range: (" << this->WindowRange[0]
     << ", " << this->WindowRange[1] << ")\n";

  os << indent << "Window Values: (" << this->WindowValues[0]
     << ", " << this->WindowValues[1] << ")\n";

}
<commit_msg>ERR: in GetMTime, fMtime was undefined if no ImplicitFunction was present.<commit_after>/*=========================================================================

  Program:   Visualization Toolkit
  Module:    vtkImplicitWindowFunction.cxx
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

Copyright (c) 1993-1996 Ken Martin, Will Schroeder, Bill Lorensen.

This software is copyrighted by Ken Martin, Will Schroeder and Bill Lorensen.
The following terms apply to all files associated with the software unless
explicitly disclaimed in individual files. This copyright specifically does
not apply to the related textbook "The Visualization Toolkit" ISBN
013199837-4 published by Prentice Hall which is covered by its own copyright.

The authors hereby grant permission to use, copy, and distribute this
software and its documentation for any purpose, provided that existing
copyright notices are retained in all copies and that this notice is included
verbatim in any distributions. Additionally, the authors grant permission to
modify this software and its documentation for any purpose, provided that
such modifications are not distributed without the explicit consent of the
authors and that existing copyright notices are retained in all copies. Some
of the algorithms implemented by this software are patented, observe all
applicable patent law.

IN NO EVENT SHALL THE AUTHORS OR DISTRIBUTORS BE LIABLE TO ANY PARTY FOR
DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
OF THE USE OF THIS SOFTWARE, ITS DOCUMENTATION, OR ANY DERIVATIVES THEREOF,
EVEN IF THE AUTHORS HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

THE AUTHORS AND DISTRIBUTORS SPECIFICALLY DISCLAIM ANY WARRANTIES, INCLUDING,
BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
PARTICULAR PURPOSE, AND NON-INFRINGEMENT.  THIS SOFTWARE IS PROVIDED ON AN
"AS IS" BASIS, AND THE AUTHORS AND DISTRIBUTORS HAVE NO OBLIGATION TO PROVIDE
MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.

=========================================================================*/
#include "vtkImplicitWindowFunction.h"

// Description:
// Construct object with window range (0,1) and window values (0,1).
vtkImplicitWindowFunction::vtkImplicitWindowFunction()
{
  this->ImplicitFunction = NULL;

  this->WindowRange[0] = 0.0;
  this->WindowRange[1] = 1.0;

  this->WindowValues[0] = 0.0;
  this->WindowValues[1] = 1.0;
}

vtkImplicitWindowFunction::~vtkImplicitWindowFunction()
{
}

// Description
// Evaluate window function.
float vtkImplicitWindowFunction::EvaluateFunction(float x[3])
{
  static int beenWarned=0;
  float value, diff1, diff2, scaledRange;

  if ( ! this->ImplicitFunction && ! beenWarned )
    {
    vtkErrorMacro(<<"Implicit function must be defined");
    beenWarned = 1;
    return 0.0;
    }

  value = this->ImplicitFunction->EvaluateFunction(x);

  diff1 = value - this->WindowRange[0];
  diff2 = value - this->WindowRange[1];

  scaledRange = (this->WindowValues[1] - this->WindowValues[0]) / 2.0;
  if ( scaledRange == 0.0 ) scaledRange = 1.0;

  if ( diff1 >= 0.0 && diff2 <= 0.0 ) //within window
    {
    if ( diff1 <= (-diff2) )
      {
      value = diff1 / scaledRange + this->WindowValues[0];
      }
    else
      {
      value = (-diff2) / scaledRange + this->WindowValues[0];
      }
    }

  else if ( diff1 < 0.0 ) //below window
    {
    value = diff1 / scaledRange + this->WindowValues[0];
    }

  else //above window
    {
    value = -diff2 / scaledRange + this->WindowValues[0];
    }

  return value;
}

// Description
// Evaluate window function gradient. Just return implicit function gradient.
void vtkImplicitWindowFunction::EvaluateGradient(float x[3], float n[3])
{
    if ( this->ImplicitFunction )
      {
      this->ImplicitFunction->EvaluateGradient(x,n);
      }
}

unsigned long int vtkImplicitWindowFunction::GetMTime()
{
  unsigned long int fMtime;
  unsigned long int mtime = this->vtkImplicitFunction::GetMTime();

  if ( this->ImplicitFunction )
  {
    fMtime = this->ImplicitFunction->GetMTime();
    if ( fMtime > mtime ) mtime = fMtime;
  }
  return mtime;
}

void vtkImplicitWindowFunction::PrintSelf(ostream& os, vtkIndent indent)
{
  vtkImplicitFunction::PrintSelf(os,indent);

  if ( this->ImplicitFunction )
    {
    os << indent << "Implicit Function: " << this->ImplicitFunction << "\n";
    }
  else
    {
    os << indent << "No implicit function defined.\n";
    }

  os << indent << "Window Range: (" << this->WindowRange[0]
     << ", " << this->WindowRange[1] << ")\n";

  os << indent << "Window Values: (" << this->WindowValues[0]
     << ", " << this->WindowValues[1] << ")\n";

}
<|endoftext|>


<commit_before>//===----------------------------------------------------------------------===//
//
//                         PelotonDB
//
// index_test.cpp
//
// Identification: test/index/index_util_test.cpp
//
// Copyright (c) 2015-16, Carnegie Mellon University Database Group
//
//===----------------------------------------------------------------------===//

#include "gtest/gtest.h"
#include "common/harness.h"

#include "common/logger.h"
#include "common/platform.h"
#include "index/index_factory.h"
#include "storage/tuple.h"
#include "index/index_util.h"

namespace peloton {
namespace test {

class IndexUtilTests : public PelotonTest {};

// These two are here since the IndexMetadata object does not claim
// ownership for the two schema objects so they will be not destroyed
// automatically
//
// Put them here to avoid Valgrind warning
static catalog::Schema *tuple_schema = nullptr;
static catalog::Schema *key_schema = nullptr;

/*
 * BuildIndex() - Builds an index with 4 columns
 *
 * The index has 4 columns as tuple key (A, B, C, D), and three of them
 * are indexed:
 *
 * tuple key: 0 1 2 3
 * index key: 3 0   1 (i.e. the 1st column of index key is the 3rd column of
 *                     tuple key)
 */
static const index::Index *BuildIndex() {
  // Build tuple and key schema
  std::vector<catalog::Column> tuple_column_list{};
  std::vector<catalog::Column> index_column_list{};

  // The following key are both in index key and tuple key and they are
  // indexed
  // The size of the key is:
  //   integer 4 * 3 = total 12

  catalog::Column column0(VALUE_TYPE_INTEGER,
                          GetTypeSize(VALUE_TYPE_INTEGER),
                          "A",
                          true);

  catalog::Column column1(VALUE_TYPE_VARCHAR,
                          1024,
                          "B",
                          false);

  // The following twoc constitutes tuple schema but does not appear in index

  catalog::Column column2(VALUE_TYPE_DOUBLE,
                          GetTypeSize(VALUE_TYPE_DOUBLE),
                          "C",
                          true);

  catalog::Column column3(VALUE_TYPE_INTEGER,
                          GetTypeSize(VALUE_TYPE_INTEGER),
                          "D",
                          true);

  // Use all four columns to build tuple schema

  tuple_column_list.push_back(column0);
  tuple_column_list.push_back(column1);
  tuple_column_list.push_back(column2);
  tuple_column_list.push_back(column3);

  tuple_schema = new catalog::Schema(tuple_column_list);

  // Use column 3, 0, 1 to build index key

  index_column_list.push_back(column3);
  index_column_list.push_back(column0);
  index_column_list.push_back(column1);

  // This will be copied into the key schema as well as into the IndexMetadata
  // object to identify indexed columns
  std::vector<oid_t> key_attrs = {3, 0, 1};

  // key schame also needs the mapping relation from index key to tuple key
  key_schema = new catalog::Schema(index_column_list);
  key_schema->SetIndexedColumns(key_attrs);

  // Build index metadata
  //
  // NOTE: Since here we use a relatively small key (size = 12)
  // so index_test is only testing with a certain kind of key
  // (most likely, GenericKey)
  //
  // For testing IntsKey and TupleKey we need more test cases
  index::IndexMetadata *index_metadata = \
    new index::IndexMetadata("index_util_test",
                             88888,                       // Index oid
                             INDEX_TYPE_BWTREE,
                             INDEX_CONSTRAINT_TYPE_DEFAULT,
                             tuple_schema,
                             key_schema,
                             key_attrs,
                             true);                      // unique_keys

  // Build index
  index::Index *index = index::IndexFactory::GetInstance(index_metadata);

  // Actually this will never be hit since if index creation fails an exception
  // would be raised (maybe out of memory would result in a nullptr? Anyway
  // leave it here)
  EXPECT_TRUE(index != NULL);

  return index;
}

/*
 * IsPointQueryTest() - Tests whether the index util correctly recognizes
 *                      point query
 *
 * The index configuration is as follows:
 *
 * tuple key: 0 1 2 3
 * index_key: 3 0 1
 */
TEST_F(IndexUtilTests, IsPointQueryTest) {
  const index::Index *index_p = BuildIndex();
  bool ret;

  std::vector<std::pair<oid_t, oid_t>> value_index_list{};

  // Test basic

  ret = IsPointQuery(index_p->GetMetadata(),
                     {3, 0, 1},
                     {EXPRESSION_TYPE_COMPARE_EQUAL,
                      EXPRESSION_TYPE_COMPARE_EQUAL,
                      EXPRESSION_TYPE_COMPARE_EQUAL},
                     value_index_list);
  EXPECT_EQ(ret, true);
  value_index_list.clear();

  ret = IsPointQuery(index_p->GetMetadata(),
                     {1, 0, 3},
                     {EXPRESSION_TYPE_COMPARE_EQUAL,
                      EXPRESSION_TYPE_COMPARE_EQUAL,
                      EXPRESSION_TYPE_COMPARE_EQUAL},
                     value_index_list);
  EXPECT_EQ(ret, true);
  value_index_list.clear();

  ret = IsPointQuery(index_p->GetMetadata(),
                     {0, 1, 3},
                     {EXPRESSION_TYPE_COMPARE_EQUAL,
                      EXPRESSION_TYPE_COMPARE_EQUAL,
                      EXPRESSION_TYPE_COMPARE_EQUAL},
                     value_index_list);
  EXPECT_EQ(ret, true);
  value_index_list.clear();

  // Test whether reconizes if only two columns are matched

  ret = IsPointQuery(index_p->GetMetadata(),
                     {0, 1},
                     {EXPRESSION_TYPE_COMPARE_EQUAL,
                      EXPRESSION_TYPE_COMPARE_EQUAL},
                     value_index_list);
  EXPECT_EQ(ret, false);
  value_index_list.clear();

  ret = IsPointQuery(index_p->GetMetadata(),
                     {3, 0},
                     {EXPRESSION_TYPE_COMPARE_EQUAL,
                      EXPRESSION_TYPE_COMPARE_EQUAL},
                     value_index_list);
  EXPECT_EQ(ret, false);
  value_index_list.clear();

  // Test empty

  ret = IsPointQuery(index_p->GetMetadata(),
                     {},
                     {},
                     value_index_list);
  EXPECT_EQ(ret, false);
  value_index_list.clear();

  // Test redundant conditions

  // This should return false, since the < already defines a lower bound
  ret = IsPointQuery(index_p->GetMetadata(),
                     {0, 3, 3, 0, 3, 1},
                     {EXPRESSION_TYPE_COMPARE_LESSTHAN,
                      EXPRESSION_TYPE_COMPARE_EQUAL,
                      EXPRESSION_TYPE_COMPARE_LESSTHAN,
                      EXPRESSION_TYPE_COMPARE_EQUAL,
                      EXPRESSION_TYPE_COMPARE_EQUAL,
                      EXPRESSION_TYPE_COMPARE_EQUAL},
                     value_index_list);
  EXPECT_EQ(ret, false);
  value_index_list.clear();

  // This should return true
  ret = IsPointQuery(index_p->GetMetadata(),
                     {0, 3, 3, 0, 3, 1},
                     {EXPRESSION_TYPE_COMPARE_EQUAL,
                      EXPRESSION_TYPE_COMPARE_EQUAL,
                      EXPRESSION_TYPE_COMPARE_LESSTHAN,
                      EXPRESSION_TYPE_COMPARE_LESSTHAN,
                      EXPRESSION_TYPE_COMPARE_EQUAL,
                      EXPRESSION_TYPE_COMPARE_EQUAL},
                     value_index_list);
  EXPECT_EQ(ret, true);
  value_index_list.clear();

  // Test duplicated conditions on a single column

  ret = IsPointQuery(index_p->GetMetadata(),
                     {3, 3, 3},
                     {EXPRESSION_TYPE_COMPARE_EQUAL,
                      EXPRESSION_TYPE_COMPARE_EQUAL,
                      EXPRESSION_TYPE_COMPARE_EQUAL},
                     value_index_list);
  EXPECT_EQ(ret, false);
  value_index_list.clear();

  //
  // The last test should logically be classified as point query
  // but our procedure does not give positive result to reduce
  // the complexity
  //

  ret = IsPointQuery(index_p->GetMetadata(),
                     {3, 0, 1, 0},
                     {EXPRESSION_TYPE_COMPARE_EQUAL,
                      EXPRESSION_TYPE_COMPARE_LESSTHANOREQUALTO,
                      EXPRESSION_TYPE_COMPARE_EQUAL,
                      EXPRESSION_TYPE_COMPARE_GREATERTHANOREQUALTO},
                     value_index_list);
  EXPECT_EQ(ret, false);
  value_index_list.clear();

  return;
}

}  // End test namespace
}  // End peloton namespace
<commit_msg>Change test case accordingly when the function name changes<commit_after>//===----------------------------------------------------------------------===//
//
//                         PelotonDB
//
// index_test.cpp
//
// Identification: test/index/index_util_test.cpp
//
// Copyright (c) 2015-16, Carnegie Mellon University Database Group
//
//===----------------------------------------------------------------------===//

#include "gtest/gtest.h"
#include "common/harness.h"

#include "common/logger.h"
#include "common/platform.h"
#include "index/index_factory.h"
#include "storage/tuple.h"
#include "index/index_util.h"

namespace peloton {
namespace test {

class IndexUtilTests : public PelotonTest {};

// These two are here since the IndexMetadata object does not claim
// ownership for the two schema objects so they will be not destroyed
// automatically
//
// Put them here to avoid Valgrind warning
static catalog::Schema *tuple_schema = nullptr;
static catalog::Schema *key_schema = nullptr;

/*
 * BuildIndex() - Builds an index with 4 columns
 *
 * The index has 4 columns as tuple key (A, B, C, D), and three of them
 * are indexed:
 *
 * tuple key: 0 1 2 3
 * index key: 3 0   1 (i.e. the 1st column of index key is the 3rd column of
 *                     tuple key)
 */
static const index::Index *BuildIndex() {
  // Build tuple and key schema
  std::vector<catalog::Column> tuple_column_list{};
  std::vector<catalog::Column> index_column_list{};

  // The following key are both in index key and tuple key and they are
  // indexed
  // The size of the key is:
  //   integer 4 * 3 = total 12

  catalog::Column column0(VALUE_TYPE_INTEGER,
                          GetTypeSize(VALUE_TYPE_INTEGER),
                          "A",
                          true);

  catalog::Column column1(VALUE_TYPE_VARCHAR,
                          1024,
                          "B",
                          false);

  // The following twoc constitutes tuple schema but does not appear in index

  catalog::Column column2(VALUE_TYPE_DOUBLE,
                          GetTypeSize(VALUE_TYPE_DOUBLE),
                          "C",
                          true);

  catalog::Column column3(VALUE_TYPE_INTEGER,
                          GetTypeSize(VALUE_TYPE_INTEGER),
                          "D",
                          true);

  // Use all four columns to build tuple schema

  tuple_column_list.push_back(column0);
  tuple_column_list.push_back(column1);
  tuple_column_list.push_back(column2);
  tuple_column_list.push_back(column3);

  tuple_schema = new catalog::Schema(tuple_column_list);

  // Use column 3, 0, 1 to build index key

  index_column_list.push_back(column3);
  index_column_list.push_back(column0);
  index_column_list.push_back(column1);

  // This will be copied into the key schema as well as into the IndexMetadata
  // object to identify indexed columns
  std::vector<oid_t> key_attrs = {3, 0, 1};

  // key schame also needs the mapping relation from index key to tuple key
  key_schema = new catalog::Schema(index_column_list);
  key_schema->SetIndexedColumns(key_attrs);

  // Build index metadata
  //
  // NOTE: Since here we use a relatively small key (size = 12)
  // so index_test is only testing with a certain kind of key
  // (most likely, GenericKey)
  //
  // For testing IntsKey and TupleKey we need more test cases
  index::IndexMetadata *index_metadata = \
    new index::IndexMetadata("index_util_test",
                             88888,                       // Index oid
                             INDEX_TYPE_BWTREE,
                             INDEX_CONSTRAINT_TYPE_DEFAULT,
                             tuple_schema,
                             key_schema,
                             key_attrs,
                             true);                      // unique_keys

  // Build index
  index::Index *index = index::IndexFactory::GetInstance(index_metadata);

  // Actually this will never be hit since if index creation fails an exception
  // would be raised (maybe out of memory would result in a nullptr? Anyway
  // leave it here)
  EXPECT_TRUE(index != NULL);

  return index;
}

/*
 * IsPointQueryTest() - Tests whether the index util correctly recognizes
 *                      point query
 *
 * The index configuration is as follows:
 *
 * tuple key: 0 1 2 3
 * index_key: 3 0 1
 */
TEST_F(IndexUtilTests, IsPointQueryTest) {
  const index::Index *index_p = BuildIndex();
  bool ret;

  std::vector<std::pair<oid_t, oid_t>> value_index_list{};

  // Test basic

  ret = FindValueIndex(index_p->GetMetadata(),
                       {3, 0, 1},
                       {EXPRESSION_TYPE_COMPARE_EQUAL,
                        EXPRESSION_TYPE_COMPARE_EQUAL,
                        EXPRESSION_TYPE_COMPARE_EQUAL},
                       value_index_list);
  EXPECT_EQ(ret, true);
  value_index_list.clear();

  ret = FindValueIndex(index_p->GetMetadata(),
                       {1, 0, 3},
                       {EXPRESSION_TYPE_COMPARE_EQUAL,
                        EXPRESSION_TYPE_COMPARE_EQUAL,
                        EXPRESSION_TYPE_COMPARE_EQUAL},
                       value_index_list);
  EXPECT_EQ(ret, true);
  value_index_list.clear();

  ret = FindValueIndex(index_p->GetMetadata(),
                       {0, 1, 3},
                       {EXPRESSION_TYPE_COMPARE_EQUAL,
                        EXPRESSION_TYPE_COMPARE_EQUAL,
                        EXPRESSION_TYPE_COMPARE_EQUAL},
                       value_index_list);
  EXPECT_EQ(ret, true);
  value_index_list.clear();

  // Test whether reconizes if only two columns are matched

  ret = FindValueIndex(index_p->GetMetadata(),
                       {0, 1},
                       {EXPRESSION_TYPE_COMPARE_EQUAL,
                        EXPRESSION_TYPE_COMPARE_EQUAL},
                       value_index_list);
  EXPECT_EQ(ret, false);
  value_index_list.clear();

  ret = FindValueIndex(index_p->GetMetadata(),
                       {3, 0},
                       {EXPRESSION_TYPE_COMPARE_EQUAL,
                        EXPRESSION_TYPE_COMPARE_EQUAL},
                       value_index_list);
  EXPECT_EQ(ret, false);
  value_index_list.clear();

  // Test empty

  ret = FindValueIndex(index_p->GetMetadata(),
                       {},
                       {},
                       value_index_list);
  EXPECT_EQ(ret, false);
  value_index_list.clear();

  // Test redundant conditions

  // This should return false, since the < already defines a lower bound
  ret = FindValueIndex(index_p->GetMetadata(),
                       {0, 3, 3, 0, 3, 1},
                       {EXPRESSION_TYPE_COMPARE_LESSTHAN,
                        EXPRESSION_TYPE_COMPARE_EQUAL,
                        EXPRESSION_TYPE_COMPARE_LESSTHAN,
                        EXPRESSION_TYPE_COMPARE_EQUAL,
                        EXPRESSION_TYPE_COMPARE_EQUAL,
                        EXPRESSION_TYPE_COMPARE_EQUAL},
                       value_index_list);
  EXPECT_EQ(ret, false);
  value_index_list.clear();

  // This should return true
  ret = FindValueIndex(index_p->GetMetadata(),
                       {0, 3, 3, 0, 3, 1},
                       {EXPRESSION_TYPE_COMPARE_EQUAL,
                        EXPRESSION_TYPE_COMPARE_EQUAL,
                        EXPRESSION_TYPE_COMPARE_LESSTHAN,
                        EXPRESSION_TYPE_COMPARE_LESSTHAN,
                        EXPRESSION_TYPE_COMPARE_EQUAL,
                        EXPRESSION_TYPE_COMPARE_EQUAL},
                       value_index_list);
  EXPECT_EQ(ret, true);
  value_index_list.clear();

  // Test duplicated conditions on a single column

  ret = FindValueIndex(index_p->GetMetadata(),
                       {3, 3, 3},
                       {EXPRESSION_TYPE_COMPARE_EQUAL,
                        EXPRESSION_TYPE_COMPARE_EQUAL,
                        EXPRESSION_TYPE_COMPARE_EQUAL},
                       value_index_list);
  EXPECT_EQ(ret, false);
  value_index_list.clear();

  //
  // The last test should logically be classified as point query
  // but our procedure does not give positive result to reduce
  // the complexity
  //

  ret = FindValueIndex(index_p->GetMetadata(),
                       {3, 0, 1, 0},
                       {EXPRESSION_TYPE_COMPARE_EQUAL,
                        EXPRESSION_TYPE_COMPARE_LESSTHANOREQUALTO,
                        EXPRESSION_TYPE_COMPARE_EQUAL,
                        EXPRESSION_TYPE_COMPARE_GREATERTHANOREQUALTO},
                       value_index_list);
  EXPECT_EQ(ret, false);
  value_index_list.clear();

  return;
}

}  // End test namespace
}  // End peloton namespace
<|endoftext|>


<commit_before>// The MIT License (MIT)

// Copyright (c) 2016, Microsoft

// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:

// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.

// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.

#include <iostream>  // TODO: remove.

#include "CorrelateCommand.h"
#include "BitFunnel/Index/Factories.h"
#include "Environment.h"
#include "LoggerInterfaces/Check.h"

namespace BitFunnel
{
    //*************************************************************************
    //
    // Correlate - analyze row table densities.
    //
    //*************************************************************************
    Correlate::Correlate(Environment & environment,
                     Id id,
                     char const * /*parameters*/)
        : TaskBase(environment, id, Type::Synchronous)
    {
    }

    void Correlate::Execute()
    {
        CHECK_NE(*GetEnvironment().GetOutputDir().c_str(), '\0')
            << "Output directory not set. "
            << "Please use the 'cd' command to set an "
            << "output directory";

        std::cout << "Dummy correlate command." << std::endl;
    }

    ICommand::Documentation Correlate::GetDocumentation()
    {
        return Documentation(
            "correlate",
            "Calculate RowTables correlations.",
            "correlate\n"
            "  Calculate RowTables correlations.\n"
        );
    }

}
<commit_msg>Fix typo.<commit_after>// The MIT License (MIT)

// Copyright (c) 2016, Microsoft

// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:

// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.

// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.

#include <iostream>  // TODO: remove.

#include "CorrelateCommand.h"
#include "BitFunnel/Index/Factories.h"
#include "Environment.h"
#include "LoggerInterfaces/Check.h"

namespace BitFunnel
{
    //*************************************************************************
    //
    // Correlate - analyze row table densities.
    //
    //*************************************************************************
    Correlate::Correlate(Environment & environment,
                     Id id,
                     char const * /*parameters*/)
        : TaskBase(environment, id, Type::Synchronous)
    {
    }

    void Correlate::Execute()
    {
        CHECK_NE(*GetEnvironment().GetOutputDir().c_str(), '\0')
            << "Output directory not set. "
            << "Please use the 'cd' command to set an "
            << "output directory";

        std::cout << "Dummy correlate command." << std::endl;
    }

    ICommand::Documentation Correlate::GetDocumentation()
    {
        return Documentation(
            "correlate",
            "Calculate RowTable correlations.",
            "correlate\n"
            "  Calculate RowTable correlations.\n"
        );
    }

}
<|endoftext|>


<commit_before>/*************************************************************************
*    UrBackup - Client/Server backup system
*    Copyright (C) 2011-2016 Martin Raiber
*
*    This program is free software: you can redistribute it and/or modify
*    it under the terms of the GNU Affero General Public License as published by
*    the Free Software Foundation, either version 3 of the License, or
*    (at your option) any later version.
*
*    This program is distributed in the hope that it will be useful,
*    but WITHOUT ANY WARRANTY; without even the implied warranty of
*    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
*    GNU Affero General Public License for more details.
*
*    You should have received a copy of the GNU Affero General Public License
*    along with this program.  If not, see <http://www.gnu.org/licenses/>.
**************************************************************************/

#pragma warning ( disable:4005 )
#pragma warning ( disable:4996 )

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

#include "../vld.h"
#include "../Interface/Server.h"
#include "CUDPThread.h"
#include "settings.h"
#include "packet_ids.h"
#include "log.h"
#include "FileServ.h"
#include "../stringtools.h"
#include <memory.h>
#ifdef _WIN32
#include <ws2tcpip.h>
#endif

std::string getSystemServerName(bool use_fqdn)
{
	char hostname[MAX_PATH];
#ifdef __APPLE__
	//TODO: Fix FQDN for Apple
	while (true)
	{
		FILE* fd = popen("/bin/hostname", "r");
		if (fd != NULL)
		{
			if (fgets(hostname, MAX_PATH, fd) != NULL)
			{
				if (trim(hostname) == "localhost")
				{
					Server->wait(100);
					continue;
				}

				return trim(hostname);
			}
			pclose(fd);
		}
		else
		{
			Server->wait(100);
		}
	}
#endif

    _i32 rc=gethostname(hostname, MAX_PATH);

	if(rc==SOCKET_ERROR)
	{
		return "_error_";
	}

	if(!use_fqdn)
	{
		return hostname;
	}

	std::string ret;

	addrinfo* h;
	addrinfo hints;
	memset(&hints, 0, sizeof(hints));
	hints.ai_flags = AI_CANONNAME;
	if(getaddrinfo(hostname, NULL, NULL, &h)==0)
	{
		if(h->ai_canonname==NULL ||
			strlower(h->ai_canonname)==strlower(hostname))
		{
			ret = hostname;
		}
		else
		{
			ret = h->ai_canonname;
		}

		freeaddrinfo(h);
	}
	else
	{
		ret = hostname;
	}

	return ret;
}

bool CUDPThread::hasError(void)
{
	return has_error;
}

CUDPThread::CUDPThread(_u16 udpport,std::string servername, bool use_fqdn)
{
	init(udpport, servername, use_fqdn);
}

void CUDPThread::init(_u16 udpport,std::string servername, bool use_fqdn)
{
	has_error=false;
	do_stop=false;
	udpport_=udpport;
	use_fqdn_=use_fqdn;

	{
		int type = SOCK_DGRAM;
#if !defined(_WIN32) && defined(SOCK_CLOEXEC)
		type |= SOCK_CLOEXEC;
#endif
		udpsock=socket(AF_INET, type, 0);

#if !defined(_WIN32) && !defined(SOCK_CLOEXEC)
		fcntl(udpsock, F_SETFD, fcntl(udpsock, F_GETFD, 0) | FD_CLOEXEC);
#endif

		int optval=1;
		int rc=setsockopt(udpsock, SOL_SOCKET, SO_REUSEADDR, (char*)&optval, sizeof(int));
		if(rc==SOCKET_ERROR)
		{
			Log("Failed setting SO_REUSEADDR in CUDPThread::CUDPThread", LL_ERROR);
			return;
		}

		sockaddr_in addr_udp;
		memset(&addr_udp, 0, sizeof(addr_udp));

		addr_udp.sin_family=AF_INET;
		addr_udp.sin_port=htons(udpport);
		addr_udp.sin_addr.s_addr= htonl(INADDR_ANY);

		Log("Binding UDP socket at port "+convert(udpport)+"...", LL_DEBUG);
		rc=bind(udpsock, (sockaddr*)&addr_udp, sizeof(sockaddr_in));
		if(rc==SOCKET_ERROR)
		{
#ifdef LOG_SERVER
			Server->Log("Binding UDP socket to port "+convert(udpport)+" failed", LL_ERROR);
#else
			Log("Failed binding UDP socket.", LL_ERROR);
#endif
			has_error=true;
			return;
		}
		Log("done.", LL_DEBUG);

#ifdef _WIN32
		DWORD dwBytesReturned = 0;
		BOOL bNewBehavior = FALSE;
		DWORD status;

		Log("Disabling new behavior...", LL_DEBUG);
		// disable  new behavior using
		// IOCTL: SIO_UDP_CONNRESET
		#define SIO_UDP_CONNRESET _WSAIOW(IOC_VENDOR,12)
		status = WSAIoctl(udpsock, SIO_UDP_CONNRESET,
						&bNewBehavior, sizeof(bNewBehavior),
					NULL, 0, &dwBytesReturned,
					NULL, NULL);
		if (SOCKET_ERROR == status)
		{
			Log("Setting SIO_UDP_CONNRESET via WSAIoctl FAILED!", LL_WARNING);
			//return;
		}
#endif
	}

	if( servername!="" )
		mServername=servername;
	else
		mServername=getSystemServerName(use_fqdn);

	Log("Servername: -"+mServername+"-", LL_INFO);
}

std::string CUDPThread::getServername()
{
	return mServername;
}

CUDPThread::~CUDPThread()
{
	if(udpsock!=SOCKET_ERROR)
	{
		closesocket(udpsock);
	}
}

void CUDPThread::operator()(void)
{
	Log("UDP Thread startet", LL_DEBUG);
#ifdef _WIN32
	SetThreadPriority( GetCurrentThread(), THREAD_PRIORITY_HIGHEST);
#endif

	do
	{
		while(UdpStep()==true && do_stop==false);

		if(!do_stop && has_error)
		{
			Log("Trying to restart UDP listening...", LL_DEBUG);

			if(udpsock!=SOCKET_ERROR)
			{
				closesocket(udpsock);
			}

			init(udpport_, mServername, use_fqdn_);

			if(has_error)
			{
				break;
			}

			if(!UdpStep())
			{
				break;
			}
		}
		else
		{
			break;
		}

	} while (true);

#ifdef LOG_SERVER
	Server->Log("CUDPThread exited.", LL_DEBUG);
#endif
	if(do_stop)
	{
		delete this;
	}
}

bool CUDPThread::UdpStep(void)
{
	if(has_error)
		return false;

	int rc;
	if(!do_stop)
	{
#ifdef _WIN32
		fd_set fdset;
		FD_ZERO(&fdset);
		FD_SET(udpsock, &fdset);

		timeval lon;
		memset(&lon,0,sizeof(timeval) );
		lon.tv_sec=60;
		rc=select((int)udpsock+1, &fdset, 0, 0, &lon);
#else
		pollfd conn[1];
		conn[0].fd=udpsock;
		conn[0].events=POLLIN;
		conn[0].revents=0;
		rc = poll(conn, 1, 60*1000);
#endif
	}
	else
	{
		rc=SOCKET_ERROR;
	}

	if(rc>0)
	{
		//Log("Receiving UDP packet...");
		char buffer[BUFFERSIZE];
		socklen_t addrsize=sizeof(sockaddr_in);
		sockaddr_in sender = {};
		_i32 err = recvfrom(udpsock, buffer, BUFFERSIZE, 0, (sockaddr*)&sender, &addrsize);
		if(err==SOCKET_ERROR)
		{
#ifdef LOG_SERVER
			Server->Log("Recvfrom error in CUDPThread::UdpStep", LL_ERROR);
#ifdef _WIN32
			Server->Log("Last error: "+ convert((int)GetLastError()), LL_ERROR);
#endif
#endif
			has_error=true;
			return false;
		}
		else if(err>0)
		{
			if(buffer[0]==ID_PING)
			{
				unsigned int rsleep=Server->getRandomNumber()%500;
				//Log("UDP: PING received... sending PONG. Delay="+convert(rsleep)+"ms", LL_DEBUG);
				Server->wait(rsleep);
				char *buffer=new char[mServername.size()+2];
				buffer[0]=ID_PONG;
				buffer[1]=VERSION;
				memcpy(&buffer[2], mServername.c_str(), mServername.size());
				int rc=sendto(udpsock, buffer, (int)mServername.size()+2, 0, (sockaddr*)&sender, addrsize );
				if( rc==SOCKET_ERROR )
				{
					Log("Sending reply failed "+convert(rc), LL_DEBUG);
				}
				delete[] buffer;
			}
			else
			{
#ifdef LOG_SERVER
				Server->Log("Unknown UDP packet id", LL_WARNING);
#endif
			}
		}
	}
	else if( rc==SOCKET_ERROR )
	{
#ifdef LOG_SERVER
			Server->Log("Select error in CUDPThread::UdpStep", LL_ERROR);
#ifdef _WIN32
			Server->Log("Last error: "+ convert((int)GetLastError()), LL_ERROR);
#endif
#endif
		has_error=true;
		return false;
	}

	return true;
}

void CUDPThread::stop(void)
{
	do_stop=true;
	Log("Stopping CUPDThread...", LL_DEBUG);
#ifdef _WIN32
	::shutdown(udpsock, SD_BOTH);
#else
	::shutdown(udpsock, SHUT_RDWR);
#endif
}<commit_msg>Reset thread priority to default<commit_after>/*************************************************************************
*    UrBackup - Client/Server backup system
*    Copyright (C) 2011-2016 Martin Raiber
*
*    This program is free software: you can redistribute it and/or modify
*    it under the terms of the GNU Affero General Public License as published by
*    the Free Software Foundation, either version 3 of the License, or
*    (at your option) any later version.
*
*    This program is distributed in the hope that it will be useful,
*    but WITHOUT ANY WARRANTY; without even the implied warranty of
*    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
*    GNU Affero General Public License for more details.
*
*    You should have received a copy of the GNU Affero General Public License
*    along with this program.  If not, see <http://www.gnu.org/licenses/>.
**************************************************************************/

#pragma warning ( disable:4005 )
#pragma warning ( disable:4996 )

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

#include "../vld.h"
#include "../Interface/Server.h"
#include "CUDPThread.h"
#include "settings.h"
#include "packet_ids.h"
#include "log.h"
#include "FileServ.h"
#include "../stringtools.h"
#include <memory.h>
#ifdef _WIN32
#include <ws2tcpip.h>
#endif

std::string getSystemServerName(bool use_fqdn)
{
	char hostname[MAX_PATH];
#ifdef __APPLE__
	//TODO: Fix FQDN for Apple
	while (true)
	{
		FILE* fd = popen("/bin/hostname", "r");
		if (fd != NULL)
		{
			if (fgets(hostname, MAX_PATH, fd) != NULL)
			{
				if (trim(hostname) == "localhost")
				{
					Server->wait(100);
					continue;
				}

				return trim(hostname);
			}
			pclose(fd);
		}
		else
		{
			Server->wait(100);
		}
	}
#endif

    _i32 rc=gethostname(hostname, MAX_PATH);

	if(rc==SOCKET_ERROR)
	{
		return "_error_";
	}

	if(!use_fqdn)
	{
		return hostname;
	}

	std::string ret;

	addrinfo* h;
	addrinfo hints;
	memset(&hints, 0, sizeof(hints));
	hints.ai_flags = AI_CANONNAME;
	if(getaddrinfo(hostname, NULL, NULL, &h)==0)
	{
		if(h->ai_canonname==NULL ||
			strlower(h->ai_canonname)==strlower(hostname))
		{
			ret = hostname;
		}
		else
		{
			ret = h->ai_canonname;
		}

		freeaddrinfo(h);
	}
	else
	{
		ret = hostname;
	}

	return ret;
}

bool CUDPThread::hasError(void)
{
	return has_error;
}

CUDPThread::CUDPThread(_u16 udpport,std::string servername, bool use_fqdn)
{
	init(udpport, servername, use_fqdn);
}

void CUDPThread::init(_u16 udpport,std::string servername, bool use_fqdn)
{
	has_error=false;
	do_stop=false;
	udpport_=udpport;
	use_fqdn_=use_fqdn;

	{
		int type = SOCK_DGRAM;
#if !defined(_WIN32) && defined(SOCK_CLOEXEC)
		type |= SOCK_CLOEXEC;
#endif
		udpsock=socket(AF_INET, type, 0);

#if !defined(_WIN32) && !defined(SOCK_CLOEXEC)
		fcntl(udpsock, F_SETFD, fcntl(udpsock, F_GETFD, 0) | FD_CLOEXEC);
#endif

		int optval=1;
		int rc=setsockopt(udpsock, SOL_SOCKET, SO_REUSEADDR, (char*)&optval, sizeof(int));
		if(rc==SOCKET_ERROR)
		{
			Log("Failed setting SO_REUSEADDR in CUDPThread::CUDPThread", LL_ERROR);
			return;
		}

		sockaddr_in addr_udp;
		memset(&addr_udp, 0, sizeof(addr_udp));

		addr_udp.sin_family=AF_INET;
		addr_udp.sin_port=htons(udpport);
		addr_udp.sin_addr.s_addr= htonl(INADDR_ANY);

		Log("Binding UDP socket at port "+convert(udpport)+"...", LL_DEBUG);
		rc=bind(udpsock, (sockaddr*)&addr_udp, sizeof(sockaddr_in));
		if(rc==SOCKET_ERROR)
		{
#ifdef LOG_SERVER
			Server->Log("Binding UDP socket to port "+convert(udpport)+" failed", LL_ERROR);
#else
			Log("Failed binding UDP socket.", LL_ERROR);
#endif
			has_error=true;
			return;
		}
		Log("done.", LL_DEBUG);

#ifdef _WIN32
		DWORD dwBytesReturned = 0;
		BOOL bNewBehavior = FALSE;
		DWORD status;

		Log("Disabling new behavior...", LL_DEBUG);
		// disable  new behavior using
		// IOCTL: SIO_UDP_CONNRESET
		#define SIO_UDP_CONNRESET _WSAIOW(IOC_VENDOR,12)
		status = WSAIoctl(udpsock, SIO_UDP_CONNRESET,
						&bNewBehavior, sizeof(bNewBehavior),
					NULL, 0, &dwBytesReturned,
					NULL, NULL);
		if (SOCKET_ERROR == status)
		{
			Log("Setting SIO_UDP_CONNRESET via WSAIoctl FAILED!", LL_WARNING);
			//return;
		}
#endif
	}

	if( servername!="" )
		mServername=servername;
	else
		mServername=getSystemServerName(use_fqdn);

	Log("Servername: -"+mServername+"-", LL_INFO);
}

std::string CUDPThread::getServername()
{
	return mServername;
}

CUDPThread::~CUDPThread()
{
	if(udpsock!=SOCKET_ERROR)
	{
		closesocket(udpsock);
	}
}

void CUDPThread::operator()(void)
{
	Log("UDP Thread startet", LL_DEBUG);
#ifdef _WIN32
	SetThreadPriority( GetCurrentThread(), THREAD_PRIORITY_HIGHEST);
#endif

	do
	{
		while(UdpStep()==true && do_stop==false);

		if(!do_stop && has_error)
		{
			Log("Trying to restart UDP listening...", LL_DEBUG);

			if(udpsock!=SOCKET_ERROR)
			{
				closesocket(udpsock);
			}

			init(udpport_, mServername, use_fqdn_);

			if(has_error)
			{
				break;
			}

			if(!UdpStep())
			{
				break;
			}
		}
		else
		{
			break;
		}

	} while (true);

#ifdef LOG_SERVER
	Server->Log("CUDPThread exited.", LL_DEBUG);
#endif
	if(do_stop)
	{
		delete this;
	}

#ifdef _WIN32
	SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_NORMAL);
#endif
}

bool CUDPThread::UdpStep(void)
{
	if(has_error)
		return false;

	int rc;
	if(!do_stop)
	{
#ifdef _WIN32
		fd_set fdset;
		FD_ZERO(&fdset);
		FD_SET(udpsock, &fdset);

		timeval lon;
		memset(&lon,0,sizeof(timeval) );
		lon.tv_sec=60;
		rc=select((int)udpsock+1, &fdset, 0, 0, &lon);
#else
		pollfd conn[1];
		conn[0].fd=udpsock;
		conn[0].events=POLLIN;
		conn[0].revents=0;
		rc = poll(conn, 1, 60*1000);
#endif
	}
	else
	{
		rc=SOCKET_ERROR;
	}

	if(rc>0)
	{
		//Log("Receiving UDP packet...");
		char buffer[BUFFERSIZE];
		socklen_t addrsize=sizeof(sockaddr_in);
		sockaddr_in sender = {};
		_i32 err = recvfrom(udpsock, buffer, BUFFERSIZE, 0, (sockaddr*)&sender, &addrsize);
		if(err==SOCKET_ERROR)
		{
#ifdef LOG_SERVER
			Server->Log("Recvfrom error in CUDPThread::UdpStep", LL_ERROR);
#ifdef _WIN32
			Server->Log("Last error: "+ convert((int)GetLastError()), LL_ERROR);
#endif
#endif
			has_error=true;
			return false;
		}
		else if(err>0)
		{
			if(buffer[0]==ID_PING)
			{
				unsigned int rsleep=Server->getRandomNumber()%500;
				//Log("UDP: PING received... sending PONG. Delay="+convert(rsleep)+"ms", LL_DEBUG);
				Server->wait(rsleep);
				char *buffer=new char[mServername.size()+2];
				buffer[0]=ID_PONG;
				buffer[1]=VERSION;
				memcpy(&buffer[2], mServername.c_str(), mServername.size());
				int rc=sendto(udpsock, buffer, (int)mServername.size()+2, 0, (sockaddr*)&sender, addrsize );
				if( rc==SOCKET_ERROR )
				{
					Log("Sending reply failed "+convert(rc), LL_DEBUG);
				}
				delete[] buffer;
			}
			else
			{
#ifdef LOG_SERVER
				Server->Log("Unknown UDP packet id", LL_WARNING);
#endif
			}
		}
	}
	else if( rc==SOCKET_ERROR )
	{
#ifdef LOG_SERVER
			Server->Log("Select error in CUDPThread::UdpStep", LL_ERROR);
#ifdef _WIN32
			Server->Log("Last error: "+ convert((int)GetLastError()), LL_ERROR);
#endif
#endif
		has_error=true;
		return false;
	}

	return true;
}

void CUDPThread::stop(void)
{
	do_stop=true;
	Log("Stopping CUPDThread...", LL_DEBUG);
#ifdef _WIN32
	::shutdown(udpsock, SD_BOTH);
#else
	::shutdown(udpsock, SHUT_RDWR);
#endif
}<|endoftext|>


<commit_before>/*
	This file is part of cpp-ethereum.

	cpp-ethereum is free software: you can redistribute it and/or modify
	it under the terms of the GNU General Public License as published by
	the Free Software Foundation, either version 3 of the License, or
	(at your option) any later version.

	cpp-ethereum is distributed in the hope that it will be useful,
	but WITHOUT ANY WARRANTY; without even the implied warranty of
	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
	GNU General Public License for more details.

	You should have received a copy of the GNU General Public License
	along with cpp-ethereum.  If not, see <http://www.gnu.org/licenses/>.
*/
/** @file gasPricer.cpp
 * @author Christoph Jentzsch <cj@ethdev.com>
 * @date 2015
 */

#include <libtestutils/BlockChainLoader.h>
#include <libethereum/State.h>
#include <libethereum/BlockChain.h>
#include <libethereum/Client.h>
#include <libdevcore/TransientDirectory.h>
#include "../TestHelper.h"

using namespace std;
using namespace dev;
using namespace dev::eth;

namespace dev {  namespace test {

void executeGasPricerTest(const string name, double _etherPrice, double _blockFee, const string bcTestPath, TransactionPriority _txPrio, u256 _expectedAsk, u256 _expectedBid)
{
	cnote << name;
	BasicGasPricer gp(u256(double(ether / 1000) / _etherPrice), u256(_blockFee * 1000));

	Json::Value vJson = test::loadJsonFromFile(test::getTestPath() + bcTestPath);
	test::BlockChainLoader bcLoader(vJson[name]);
	BlockChain const& bc = bcLoader.bc();

	gp.update(bc);
	BOOST_CHECK_EQUAL(gp.ask(State()), _expectedAsk);
	BOOST_CHECK_EQUAL(gp.bid(_txPrio), _expectedBid);
}
} }

BOOST_AUTO_TEST_SUITE(GasPricer)

BOOST_AUTO_TEST_CASE(trivialGasPricer)
{
	cnote << "trivialGasPricer";
	std::shared_ptr<dev::eth::GasPricer> gp(new TrivialGasPricer);
	BOOST_CHECK_EQUAL(gp->ask(State()), 10 * szabo);
	BOOST_CHECK_EQUAL(gp->bid(), 10 * szabo);
	gp->update(BlockChain(bytes(), TransientDirectory().path(), WithExisting::Kill));
	BOOST_CHECK_EQUAL(gp->ask(State()), 10 * szabo);
	BOOST_CHECK_EQUAL(gp->bid(), 10 * szabo);
}

BOOST_AUTO_TEST_CASE(basicGasPricerNoUpdate)
{
	cnote << "basicGasPricer";
	BasicGasPricer gp(u256(double(ether / 1000) / 30.679), u256(15.0 * 1000));
	BOOST_CHECK_EQUAL(gp.ask(State()), 155632494086);
	BOOST_CHECK_EQUAL(gp.bid(), 155632494086);

	gp.setRefPrice(u256(0));
	BOOST_CHECK_EQUAL(gp.ask(State()), 0);
	BOOST_CHECK_EQUAL(gp.bid(), 0);

	gp.setRefPrice(u256(1));
	gp.setRefBlockFees(u256(0));
	BOOST_CHECK_EQUAL(gp.ask(State()), 0);
	BOOST_CHECK_EQUAL(gp.bid(), 0);

	gp.setRefPrice(u256("0x100000000000000000000000000000000"));
	BOOST_CHECK_THROW(gp.setRefBlockFees(u256("0x100000000000000000000000000000000")), Overflow);
	BOOST_CHECK_EQUAL(gp.ask(State()), 0);
	BOOST_CHECK_EQUAL(gp.bid(), 0);

	gp.setRefPrice(1);
	gp.setRefBlockFees(u256("0x100000000000000000000000000000000"));
	BOOST_CHECK_THROW(gp.setRefPrice(u256("0x100000000000000000000000000000000")), Overflow);
	BOOST_CHECK_EQUAL(gp.ask(State()), u256("108315264019305646138446560671076"));
	BOOST_CHECK_EQUAL(gp.bid(), u256("108315264019305646138446560671076"));
}

BOOST_AUTO_TEST_CASE(basicGasPricer_RPC_API_Test)
{
	dev::test::executeGasPricerTest("RPC_API_Test", 30.679, 15.0, "/BlockTests/bcRPC_API_Test.json", TransactionPriority::Medium, 155632494086, 1);
}

BOOST_AUTO_TEST_CASE(basicGasPricer_bcValidBlockTest)
{
	dev::test::executeGasPricerTest("SimpleTx", 30.679, 15.0, "/BlockTests/bcValidBlockTest.json", TransactionPriority::Medium, 155632494086, 10);
}

BOOST_AUTO_TEST_CASE(basicGasPricer_bcUncleTest)
{
	dev::test::executeGasPricerTest("twoUncle", 30.679, 15.0, "/BlockTests/bcUncleTest.json", TransactionPriority::Medium, 155632494086, 1);
}

BOOST_AUTO_TEST_CASE(basicGasPricer_bcUncleHeaderValiditiy)
{
	dev::test::executeGasPricerTest("correct", 30.679, 15.0, "/BlockTests/bcUncleHeaderValiditiy.json", TransactionPriority::Medium, 155632494086, 1);
}

BOOST_AUTO_TEST_CASE(basicGasPricer_notxs)
{
	dev::test::executeGasPricerTest("notxs", 30.679, 15.0, "/BlockTests/bcGasPricerTest.json", TransactionPriority::Medium, 155632494086, 155632494086);
}

BOOST_AUTO_TEST_CASE(basicGasPricer_highGasUsage_LowestPrio)
{
	dev::test::executeGasPricerTest("highGasUsage", 30.679, 15.0, "/BlockTests/bcGasPricerTest.json", TransactionPriority::Lowest, 15731282021, 10000000000000);
}

BOOST_AUTO_TEST_CASE(basicGasPricer_highGasUsage_LowPrio)
{
	dev::test::executeGasPricerTest("highGasUsage", 30.679, 15.0, "/BlockTests/bcGasPricerTest.json", TransactionPriority::Low, 15731282021, 15734152261884);
}

BOOST_AUTO_TEST_CASE(basicGasPricer_highGasUsage_MediumPrio)
{
	dev::test::executeGasPricerTest("highGasUsage", 30.679, 15.0, "/BlockTests/bcGasPricerTest.json", TransactionPriority::Medium, 15731282021, 20000000000000);
}

BOOST_AUTO_TEST_CASE(basicGasPricer_highGasUsage_HighPrio)
{
	dev::test::executeGasPricerTest("highGasUsage", 30.679, 15.0, "/BlockTests/bcGasPricerTest.json", TransactionPriority::High, 15731282021, 24265847738115);
}

BOOST_AUTO_TEST_CASE(basicGasPricer_highGasUsage_HighestPrio)
{
	dev::test::executeGasPricerTest("highGasUsage", 30.679, 15.0, "/BlockTests/bcGasPricerTest.json", TransactionPriority::Highest, 15731282021, 30000000000000);
}
BOOST_AUTO_TEST_SUITE_END()
<commit_msg>update gas pricer test path<commit_after>/*
	This file is part of cpp-ethereum.

	cpp-ethereum is free software: you can redistribute it and/or modify
	it under the terms of the GNU General Public License as published by
	the Free Software Foundation, either version 3 of the License, or
	(at your option) any later version.

	cpp-ethereum is distributed in the hope that it will be useful,
	but WITHOUT ANY WARRANTY; without even the implied warranty of
	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
	GNU General Public License for more details.

	You should have received a copy of the GNU General Public License
	along with cpp-ethereum.  If not, see <http://www.gnu.org/licenses/>.
*/
/** @file gasPricer.cpp
 * @author Christoph Jentzsch <cj@ethdev.com>
 * @date 2015
 */

#include <libtestutils/BlockChainLoader.h>
#include <libethereum/State.h>
#include <libethereum/BlockChain.h>
#include <libethereum/Client.h>
#include <libdevcore/TransientDirectory.h>
#include "../TestHelper.h"

using namespace std;
using namespace dev;
using namespace dev::eth;

namespace dev {  namespace test {

void executeGasPricerTest(const string name, double _etherPrice, double _blockFee, const string bcTestPath, TransactionPriority _txPrio, u256 _expectedAsk, u256 _expectedBid)
{
	cnote << name;
	BasicGasPricer gp(u256(double(ether / 1000) / _etherPrice), u256(_blockFee * 1000));

	Json::Value vJson = test::loadJsonFromFile(test::getTestPath() + bcTestPath);
	test::BlockChainLoader bcLoader(vJson[name]);
	BlockChain const& bc = bcLoader.bc();

	gp.update(bc);
	BOOST_CHECK_EQUAL(gp.ask(State()), _expectedAsk);
	BOOST_CHECK_EQUAL(gp.bid(_txPrio), _expectedBid);
}
} }

BOOST_AUTO_TEST_SUITE(GasPricer)

BOOST_AUTO_TEST_CASE(trivialGasPricer)
{
	cnote << "trivialGasPricer";
	std::shared_ptr<dev::eth::GasPricer> gp(new TrivialGasPricer);
	BOOST_CHECK_EQUAL(gp->ask(State()), 10 * szabo);
	BOOST_CHECK_EQUAL(gp->bid(), 10 * szabo);
	gp->update(BlockChain(bytes(), TransientDirectory().path(), WithExisting::Kill));
	BOOST_CHECK_EQUAL(gp->ask(State()), 10 * szabo);
	BOOST_CHECK_EQUAL(gp->bid(), 10 * szabo);
}

BOOST_AUTO_TEST_CASE(basicGasPricerNoUpdate)
{
	cnote << "basicGasPricer";
	BasicGasPricer gp(u256(double(ether / 1000) / 30.679), u256(15.0 * 1000));
	BOOST_CHECK_EQUAL(gp.ask(State()), 155632494086);
	BOOST_CHECK_EQUAL(gp.bid(), 155632494086);

	gp.setRefPrice(u256(0));
	BOOST_CHECK_EQUAL(gp.ask(State()), 0);
	BOOST_CHECK_EQUAL(gp.bid(), 0);

	gp.setRefPrice(u256(1));
	gp.setRefBlockFees(u256(0));
	BOOST_CHECK_EQUAL(gp.ask(State()), 0);
	BOOST_CHECK_EQUAL(gp.bid(), 0);

	gp.setRefPrice(u256("0x100000000000000000000000000000000"));
	BOOST_CHECK_THROW(gp.setRefBlockFees(u256("0x100000000000000000000000000000000")), Overflow);
	BOOST_CHECK_EQUAL(gp.ask(State()), 0);
	BOOST_CHECK_EQUAL(gp.bid(), 0);

	gp.setRefPrice(1);
	gp.setRefBlockFees(u256("0x100000000000000000000000000000000"));
	BOOST_CHECK_THROW(gp.setRefPrice(u256("0x100000000000000000000000000000000")), Overflow);
	BOOST_CHECK_EQUAL(gp.ask(State()), u256("108315264019305646138446560671076"));
	BOOST_CHECK_EQUAL(gp.bid(), u256("108315264019305646138446560671076"));
}

BOOST_AUTO_TEST_CASE(basicGasPricer_RPC_API_Test)
{
	dev::test::executeGasPricerTest("RPC_API_Test", 30.679, 15.0, "/BlockchainTests/bcRPC_API_Test.json", TransactionPriority::Medium, 155632494086, 1);
}

BOOST_AUTO_TEST_CASE(basicGasPricer_bcValidBlockTest)
{
	dev::test::executeGasPricerTest("SimpleTx", 30.679, 15.0, "/BlockchainTests/bcValidBlockTest.json", TransactionPriority::Medium, 155632494086, 10);
}

BOOST_AUTO_TEST_CASE(basicGasPricer_bcUncleTest)
{
	dev::test::executeGasPricerTest("twoUncle", 30.679, 15.0, "/BlockchainTests/bcUncleTest.json", TransactionPriority::Medium, 155632494086, 1);
}

BOOST_AUTO_TEST_CASE(basicGasPricer_bcUncleHeaderValiditiy)
{
	dev::test::executeGasPricerTest("correct", 30.679, 15.0, "/BlockchainTests/bcUncleHeaderValiditiy.json", TransactionPriority::Medium, 155632494086, 1);
}

BOOST_AUTO_TEST_CASE(basicGasPricer_notxs)
{
	dev::test::executeGasPricerTest("notxs", 30.679, 15.0, "/BlockchainTests/bcGasPricerTest.json", TransactionPriority::Medium, 155632494086, 155632494086);
}

BOOST_AUTO_TEST_CASE(basicGasPricer_highGasUsage_LowestPrio)
{
	dev::test::executeGasPricerTest("highGasUsage", 30.679, 15.0, "/BlockchainTests/bcGasPricerTest.json", TransactionPriority::Lowest, 15731282021, 10000000000000);
}

BOOST_AUTO_TEST_CASE(basicGasPricer_highGasUsage_LowPrio)
{
	dev::test::executeGasPricerTest("highGasUsage", 30.679, 15.0, "/BlockchainTests/bcGasPricerTest.json", TransactionPriority::Low, 15731282021, 15734152261884);
}

BOOST_AUTO_TEST_CASE(basicGasPricer_highGasUsage_MediumPrio)
{
	dev::test::executeGasPricerTest("highGasUsage", 30.679, 15.0, "/BlockchainTests/bcGasPricerTest.json", TransactionPriority::Medium, 15731282021, 20000000000000);
}

BOOST_AUTO_TEST_CASE(basicGasPricer_highGasUsage_HighPrio)
{
	dev::test::executeGasPricerTest("highGasUsage", 30.679, 15.0, "/BlockchainTests/bcGasPricerTest.json", TransactionPriority::High, 15731282021, 24265847738115);
}

BOOST_AUTO_TEST_CASE(basicGasPricer_highGasUsage_HighestPrio)
{
	dev::test::executeGasPricerTest("highGasUsage", 30.679, 15.0, "/BlockchainTests/bcGasPricerTest.json", TransactionPriority::Highest, 15731282021, 30000000000000);
}
BOOST_AUTO_TEST_SUITE_END()
<|endoftext|>


<commit_before>/*
 * W.J. van der Laan 2011-2012
 */
#include "bitcoingui.h"
#include "clientmodel.h"
#include "walletmodel.h"
#include "optionsmodel.h"
#include "guiutil.h"
#include "guiconstants.h"

#include "init.h"
#include "ui_interface.h"
#include "qtipcserver.h"

#include <QApplication>
#include <QMessageBox>
#include <QTextCodec>
#include <QLocale>
#include <QTranslator>
#include <QSplashScreen>
#include <QLibraryInfo>

#if defined(BITCOIN_NEED_QT_PLUGINS) && !defined(_BITCOIN_QT_PLUGINS_INCLUDED)
#define _BITCOIN_QT_PLUGINS_INCLUDED
#define __INSURE__
#include <QtPlugin>
Q_IMPORT_PLUGIN(qcncodecs)
Q_IMPORT_PLUGIN(qjpcodecs)
Q_IMPORT_PLUGIN(qtwcodecs)
Q_IMPORT_PLUGIN(qkrcodecs)
Q_IMPORT_PLUGIN(qtaccessiblewidgets)
#endif

// Need a global reference for the notifications to find the GUI
static BitcoinGUI *guiref;
static QSplashScreen *splashref;

static void ThreadSafeMessageBox(const std::string& message, const std::string& caption, int style)
{
    // Message from network thread
    if(guiref)
    {
        bool modal = (style & CClientUIInterface::MODAL);
        // in case of modal message, use blocking connection to wait for user to click OK
        QMetaObject::invokeMethod(guiref, "error",
                                   modal ? GUIUtil::blockingGUIThreadConnection() : Qt::QueuedConnection,
                                   Q_ARG(QString, QString::fromStdString(caption)),
                                   Q_ARG(QString, QString::fromStdString(message)),
                                   Q_ARG(bool, modal));
    }
    else
    {
        printf("%s: %s\n", caption.c_str(), message.c_str());
        fprintf(stderr, "%s: %s\n", caption.c_str(), message.c_str());
    }
}

static bool ThreadSafeAskFee(int64 nFeeRequired, const std::string& strCaption)
{
    if(!guiref)
        return false;
    if(nFeeRequired < MIN_TX_FEE || nFeeRequired <= nTransactionFee || fDaemon)
        return true;
    bool payFee = false;

    QMetaObject::invokeMethod(guiref, "askFee", GUIUtil::blockingGUIThreadConnection(),
                               Q_ARG(qint64, nFeeRequired),
                               Q_ARG(bool*, &payFee));

    return payFee;
}

static void ThreadSafeHandleURI(const std::string& strURI)
{
    if(!guiref)
        return;

    QMetaObject::invokeMethod(guiref, "handleURI", GUIUtil::blockingGUIThreadConnection(),
                               Q_ARG(QString, QString::fromStdString(strURI)));
}

static void InitMessage(const std::string &message)
{
    if(splashref)
    {
        splashref->showMessage(QString::fromStdString(message), Qt::AlignBottom|Qt::AlignHCenter, QColor(255,255,200));
        QApplication::instance()->processEvents();
    }
}

static void QueueShutdown()
{
    QMetaObject::invokeMethod(QCoreApplication::instance(), "quit", Qt::QueuedConnection);
}

/*
   Translate string to current locale using Qt.
 */
static std::string Translate(const char* psz)
{
    return QCoreApplication::translate("bitcoin-core", psz).toStdString();
}

/* Handle runaway exceptions. Shows a message box with the problem and quits the program.
 */
static void handleRunawayException(std::exception *e)
{
    PrintExceptionContinue(e, "Runaway exception");
    QMessageBox::critical(0, "Runaway exception", BitcoinGUI::tr("A fatal error occurred. FlutterCoin can no longer continue safely and will quit.") + QString("\n\n") + QString::fromStdString(strMiscWarning));
    exit(1);
}

#ifndef BITCOIN_QT_TEST
int main(int argc, char *argv[])
{
    // Do this early as we don't want to bother initializing if we are just calling IPC
    ipcScanRelay(argc, argv);

    // Internal string conversion is all UTF-8
    QTextCodec::setCodecForTr(QTextCodec::codecForName("UTF-8"));
    QTextCodec::setCodecForCStrings(QTextCodec::codecForTr());

    Q_INIT_RESOURCE(bitcoin);
    QApplication app(argc, argv);

    // Install global event filter that makes sure that long tooltips can be word-wrapped
    app.installEventFilter(new GUIUtil::ToolTipToRichTextFilter(TOOLTIP_WRAP_THRESHOLD, &app));

    // Command-line options take precedence:
    ParseParameters(argc, argv);

    // ... then bitcoin.conf:
    if (!boost::filesystem::is_directory(GetDataDir(false)))
    {
        // This message can not be translated, as translation is not initialized yet
        // (which not yet possible because lang=XX can be overridden in bitcoin.conf in the data directory)
        QMessageBox::critical(0, "FlutterCoin",
                              QString("Error: Specified data directory \"%1\" does not exist.").arg(QString::fromStdString(mapArgs["-datadir"])));
        return 1;
    }
    ReadConfigFile(mapArgs, mapMultiArgs);

    // Application identification (must be set before OptionsModel is initialized,
    // as it is used to locate QSettings)
    app.setOrganizationName("FlutterCoin");
    app.setOrganizationDomain("fluttercoin.su");
    if(GetBoolArg("-testnet")) // Separate UI settings for testnet
        app.setApplicationName("FlutterCoin-Qt-testnet");
    else
        app.setApplicationName("FlutterCoin-Qt");

    // ... then GUI settings:
    OptionsModel optionsModel;

    // Get desired locale (e.g. "de_DE") from command line or use system locale
    QString lang_territory = QString::fromStdString(GetArg("-lang", QLocale::system().name().toStdString()));
    QString lang = lang_territory;
    // Convert to "de" only by truncating "_DE"
    lang.truncate(lang_territory.lastIndexOf('_'));

    QTranslator qtTranslatorBase, qtTranslator, translatorBase, translator;
    // Load language files for configured locale:
    // - First load the translator for the base language, without territory
    // - Then load the more specific locale translator

    // Load e.g. qt_de.qm
    if (qtTranslatorBase.load("qt_" + lang, QLibraryInfo::location(QLibraryInfo::TranslationsPath)))
        app.installTranslator(&qtTranslatorBase);

    // Load e.g. qt_de_DE.qm
    if (qtTranslator.load("qt_" + lang_territory, QLibraryInfo::location(QLibraryInfo::TranslationsPath)))
        app.installTranslator(&qtTranslator);

    // Load e.g. bitcoin_de.qm (shortcut "de" needs to be defined in bitcoin.qrc)
    if (translatorBase.load(lang, ":/translations/"))
        app.installTranslator(&translatorBase);

    // Load e.g. bitcoin_de_DE.qm (shortcut "de_DE" needs to be defined in bitcoin.qrc)
    if (translator.load(lang_territory, ":/translations/"))
        app.installTranslator(&translator);

    // Subscribe to global signals from core
    uiInterface.ThreadSafeMessageBox.connect(ThreadSafeMessageBox);
    uiInterface.ThreadSafeAskFee.connect(ThreadSafeAskFee);
    uiInterface.ThreadSafeHandleURI.connect(ThreadSafeHandleURI);
    uiInterface.InitMessage.connect(InitMessage);
    uiInterface.QueueShutdown.connect(QueueShutdown);
    uiInterface.Translate.connect(Translate);

    // Show help message immediately after parsing command-line options (for "-lang") and setting locale,
    // but before showing splash screen.
    if (mapArgs.count("-?") || mapArgs.count("--help"))
    {
        GUIUtil::HelpMessageBox help;
        help.showOrPrint();
        return 1;
    }

    QSplashScreen splash(QPixmap(":/images/splash"), 0);
    if (GetBoolArg("-splash", true) && !GetBoolArg("-min"))
    {
        splash.show();
        splash.setAutoFillBackground(true);
        splashref = &splash;
    }

    app.processEvents();

    app.setQuitOnLastWindowClosed(false);

    try
    {
        // Regenerate startup link, to fix links to old versions
        if (GUIUtil::GetStartOnSystemStartup())
            GUIUtil::SetStartOnSystemStartup(true);

        BitcoinGUI window;
        guiref = &window;
        if(AppInit2())
        {
            {
                // Put this in a block, so that the Model objects are cleaned up before
                // calling Shutdown().

                if (splashref)
                    splash.finish(&window);

                ClientModel clientModel(&optionsModel);
                WalletModel walletModel(pwalletMain, &optionsModel);

                window.setClientModel(&clientModel);
                window.setWalletModel(&walletModel);

                // If -min option passed, start window minimized.
                if(GetBoolArg("-min"))
                {
                    window.showMinimized();
                }
                else
                {
                    window.show();
                }

                // Place this here as guiref has to be defined if we don't want to lose URIs
                ipcInit(argc, argv);

                app.exec();

                window.hide();
                window.setClientModel(0);
                window.setWalletModel(0);
                guiref = 0;
            }
            // Shutdown the core and its threads, but don't exit Bitcoin-Qt here
            Shutdown(NULL);
        }
        else
        {
            return 1;
        }
    } catch (std::exception& e) {
        handleRunawayException(&e);
    } catch (...) {
        handleRunawayException(NULL);
    }
    return 0;
}
#endif // BITCOIN_QT_TEST
<commit_msg>Change status text form nearly white to green and an option not to fill the background of the splash image. On linux it was fine as is int windows was solid black<commit_after>/*
 * W.J. van der Laan 2011-2012
 */
#include "bitcoingui.h"
#include "clientmodel.h"
#include "walletmodel.h"
#include "optionsmodel.h"
#include "guiutil.h"
#include "guiconstants.h"

#include "init.h"
#include "ui_interface.h"
#include "qtipcserver.h"

#include <QApplication>
#include <QMessageBox>
#include <QTextCodec>
#include <QLocale>
#include <QTranslator>
#include <QSplashScreen>
#include <QLibraryInfo>

#if defined(BITCOIN_NEED_QT_PLUGINS) && !defined(_BITCOIN_QT_PLUGINS_INCLUDED)
#define _BITCOIN_QT_PLUGINS_INCLUDED
#define __INSURE__
#include <QtPlugin>
Q_IMPORT_PLUGIN(qcncodecs)
Q_IMPORT_PLUGIN(qjpcodecs)
Q_IMPORT_PLUGIN(qtwcodecs)
Q_IMPORT_PLUGIN(qkrcodecs)
Q_IMPORT_PLUGIN(qtaccessiblewidgets)
#endif

// Need a global reference for the notifications to find the GUI
static BitcoinGUI *guiref;
static QSplashScreen *splashref;

static void ThreadSafeMessageBox(const std::string& message, const std::string& caption, int style)
{
    // Message from network thread
    if(guiref)
    {
        bool modal = (style & CClientUIInterface::MODAL);
        // in case of modal message, use blocking connection to wait for user to click OK
        QMetaObject::invokeMethod(guiref, "error",
                                   modal ? GUIUtil::blockingGUIThreadConnection() : Qt::QueuedConnection,
                                   Q_ARG(QString, QString::fromStdString(caption)),
                                   Q_ARG(QString, QString::fromStdString(message)),
                                   Q_ARG(bool, modal));
    }
    else
    {
        printf("%s: %s\n", caption.c_str(), message.c_str());
        fprintf(stderr, "%s: %s\n", caption.c_str(), message.c_str());
    }
}

static bool ThreadSafeAskFee(int64 nFeeRequired, const std::string& strCaption)
{
    if(!guiref)
        return false;
    if(nFeeRequired < MIN_TX_FEE || nFeeRequired <= nTransactionFee || fDaemon)
        return true;
    bool payFee = false;

    QMetaObject::invokeMethod(guiref, "askFee", GUIUtil::blockingGUIThreadConnection(),
                               Q_ARG(qint64, nFeeRequired),
                               Q_ARG(bool*, &payFee));

    return payFee;
}

static void ThreadSafeHandleURI(const std::string& strURI)
{
    if(!guiref)
        return;

    QMetaObject::invokeMethod(guiref, "handleURI", GUIUtil::blockingGUIThreadConnection(),
                               Q_ARG(QString, QString::fromStdString(strURI)));
}

static void InitMessage(const std::string &message)
{
    if(splashref)
    {
        splashref->showMessage(QString::fromStdString(message), Qt::AlignBottom|Qt::AlignHCenter, QColor(0,255,0));
        QApplication::instance()->processEvents();
    }
}

static void QueueShutdown()
{
    QMetaObject::invokeMethod(QCoreApplication::instance(), "quit", Qt::QueuedConnection);
}

/*
   Translate string to current locale using Qt.
 */
static std::string Translate(const char* psz)
{
    return QCoreApplication::translate("bitcoin-core", psz).toStdString();
}

/* Handle runaway exceptions. Shows a message box with the problem and quits the program.
 */
static void handleRunawayException(std::exception *e)
{
    PrintExceptionContinue(e, "Runaway exception");
    QMessageBox::critical(0, "Runaway exception", BitcoinGUI::tr("A fatal error occurred. FlutterCoin can no longer continue safely and will quit.") + QString("\n\n") + QString::fromStdString(strMiscWarning));
    exit(1);
}

#ifndef BITCOIN_QT_TEST
int main(int argc, char *argv[])
{
    // Do this early as we don't want to bother initializing if we are just calling IPC
    ipcScanRelay(argc, argv);

    // Internal string conversion is all UTF-8
    QTextCodec::setCodecForTr(QTextCodec::codecForName("UTF-8"));
    QTextCodec::setCodecForCStrings(QTextCodec::codecForTr());

    Q_INIT_RESOURCE(bitcoin);
    QApplication app(argc, argv);

    // Install global event filter that makes sure that long tooltips can be word-wrapped
    app.installEventFilter(new GUIUtil::ToolTipToRichTextFilter(TOOLTIP_WRAP_THRESHOLD, &app));

    // Command-line options take precedence:
    ParseParameters(argc, argv);

    // ... then bitcoin.conf:
    if (!boost::filesystem::is_directory(GetDataDir(false)))
    {
        // This message can not be translated, as translation is not initialized yet
        // (which not yet possible because lang=XX can be overridden in bitcoin.conf in the data directory)
        QMessageBox::critical(0, "FlutterCoin",
                              QString("Error: Specified data directory \"%1\" does not exist.").arg(QString::fromStdString(mapArgs["-datadir"])));
        return 1;
    }
    ReadConfigFile(mapArgs, mapMultiArgs);

    // Application identification (must be set before OptionsModel is initialized,
    // as it is used to locate QSettings)
    app.setOrganizationName("FlutterCoin");
    app.setOrganizationDomain("fluttercoin.su");
    if(GetBoolArg("-testnet")) // Separate UI settings for testnet
        app.setApplicationName("FlutterCoin-Qt-testnet");
    else
        app.setApplicationName("FlutterCoin-Qt");

    // ... then GUI settings:
    OptionsModel optionsModel;

    // Get desired locale (e.g. "de_DE") from command line or use system locale
    QString lang_territory = QString::fromStdString(GetArg("-lang", QLocale::system().name().toStdString()));
    QString lang = lang_territory;
    // Convert to "de" only by truncating "_DE"
    lang.truncate(lang_territory.lastIndexOf('_'));

    QTranslator qtTranslatorBase, qtTranslator, translatorBase, translator;
    // Load language files for configured locale:
    // - First load the translator for the base language, without territory
    // - Then load the more specific locale translator

    // Load e.g. qt_de.qm
    if (qtTranslatorBase.load("qt_" + lang, QLibraryInfo::location(QLibraryInfo::TranslationsPath)))
        app.installTranslator(&qtTranslatorBase);

    // Load e.g. qt_de_DE.qm
    if (qtTranslator.load("qt_" + lang_territory, QLibraryInfo::location(QLibraryInfo::TranslationsPath)))
        app.installTranslator(&qtTranslator);

    // Load e.g. bitcoin_de.qm (shortcut "de" needs to be defined in bitcoin.qrc)
    if (translatorBase.load(lang, ":/translations/"))
        app.installTranslator(&translatorBase);

    // Load e.g. bitcoin_de_DE.qm (shortcut "de_DE" needs to be defined in bitcoin.qrc)
    if (translator.load(lang_territory, ":/translations/"))
        app.installTranslator(&translator);

    // Subscribe to global signals from core
    uiInterface.ThreadSafeMessageBox.connect(ThreadSafeMessageBox);
    uiInterface.ThreadSafeAskFee.connect(ThreadSafeAskFee);
    uiInterface.ThreadSafeHandleURI.connect(ThreadSafeHandleURI);
    uiInterface.InitMessage.connect(InitMessage);
    uiInterface.QueueShutdown.connect(QueueShutdown);
    uiInterface.Translate.connect(Translate);

    // Show help message immediately after parsing command-line options (for "-lang") and setting locale,
    // but before showing splash screen.
    if (mapArgs.count("-?") || mapArgs.count("--help"))
    {
        GUIUtil::HelpMessageBox help;
        help.showOrPrint();
        return 1;
    }

    QSplashScreen splash(QPixmap(":/images/splash"), 0);
    if (GetBoolArg("-splash", true) && !GetBoolArg("-min"))
    {
        splash.show();
        splash.setAutoFillBackground(false);
        splashref = &splash;
    }

    app.processEvents();

    app.setQuitOnLastWindowClosed(false);

    try
    {
        // Regenerate startup link, to fix links to old versions
        if (GUIUtil::GetStartOnSystemStartup())
            GUIUtil::SetStartOnSystemStartup(true);

        BitcoinGUI window;
        guiref = &window;
        if(AppInit2())
        {
            {
                // Put this in a block, so that the Model objects are cleaned up before
                // calling Shutdown().

                if (splashref)
                    splash.finish(&window);

                ClientModel clientModel(&optionsModel);
                WalletModel walletModel(pwalletMain, &optionsModel);

                window.setClientModel(&clientModel);
                window.setWalletModel(&walletModel);

                // If -min option passed, start window minimized.
                if(GetBoolArg("-min"))
                {
                    window.showMinimized();
                }
                else
                {
                    window.show();
                }

                // Place this here as guiref has to be defined if we don't want to lose URIs
                ipcInit(argc, argv);

                app.exec();

                window.hide();
                window.setClientModel(0);
                window.setWalletModel(0);
                guiref = 0;
            }
            // Shutdown the core and its threads, but don't exit Bitcoin-Qt here
            Shutdown(NULL);
        }
        else
        {
            return 1;
        }
    } catch (std::exception& e) {
        handleRunawayException(&e);
    } catch (...) {
        handleRunawayException(NULL);
    }
    return 0;
}
#endif // BITCOIN_QT_TEST
<|endoftext|>


<commit_before>#include "gtest/gtest.h"
#include "joedb/compiler/nested_namespace.h"

#include <sstream>

/////////////////////////////////////////////////////////////////////////////
TEST(nested_namespace, split_namespace)
/////////////////////////////////////////////////////////////////////////////
{
 auto n = joedb::split_namespace("split::this::name");

 EXPECT_EQ(3, int(n.size()));
 EXPECT_EQ("split", n[0]);
 EXPECT_EQ("this", n[1]);
 EXPECT_EQ("name", n[2]);
}

/////////////////////////////////////////////////////////////////////////////
TEST(nested_namespace, namespace_write)
/////////////////////////////////////////////////////////////////////////////
{
 auto n = joedb::split_namespace("split::this::name");
 std::ostringstream out;
 joedb::namespace_write(out, n, "!");
 EXPECT_EQ("split!this!name", out.str());
}
<commit_msg>more namespace tests<commit_after>#include "gtest/gtest.h"
#include "joedb/compiler/nested_namespace.h"

#include <sstream>

/////////////////////////////////////////////////////////////////////////////
TEST(nested_namespace, split_namespace)
/////////////////////////////////////////////////////////////////////////////
{
 auto n = joedb::split_namespace("split::this::name");

 EXPECT_EQ(3, int(n.size()));
 EXPECT_EQ("split", n[0]);
 EXPECT_EQ("this", n[1]);
 EXPECT_EQ("name", n[2]);
}

/////////////////////////////////////////////////////////////////////////////
TEST(nested_namespace, namespace_write)
/////////////////////////////////////////////////////////////////////////////
{
 auto n = joedb::split_namespace("split::this::name");
 std::ostringstream out;
 joedb::namespace_write(out, n, "!");
 EXPECT_EQ("split!this!name", out.str());
}

/////////////////////////////////////////////////////////////////////////////
TEST(nested_namespace, namespace_string)
/////////////////////////////////////////////////////////////////////////////
{
 auto n = joedb::split_namespace("split::this::name");
 EXPECT_EQ("split..this..name", joedb::namespace_string(n, ".."));
}

/////////////////////////////////////////////////////////////////////////////
TEST(nested_namespace, namespace_open)
/////////////////////////////////////////////////////////////////////////////
{
 auto n = joedb::split_namespace("split::this::name");
 std::ostringstream out;
 joedb::namespace_open(out, n);
 EXPECT_EQ("namespace split {namespace this {namespace name {\n", out.str());
}

/////////////////////////////////////////////////////////////////////////////
TEST(nested_namespace, namespace_close)
/////////////////////////////////////////////////////////////////////////////
{
 auto n = joedb::split_namespace("split::this::name");
 std::ostringstream out;
 joedb::namespace_close(out, n);
 EXPECT_EQ("}}}\n", out.str());
}

/////////////////////////////////////////////////////////////////////////////
TEST(nested_namespace, namespace_include_guard)
/////////////////////////////////////////////////////////////////////////////
{
 auto n = joedb::split_namespace("split::this::name");
 std::ostringstream out;
 joedb::namespace_include_guard(out, "X", n);
 EXPECT_EQ
 (
  "#ifndef split_this_name_X_declared\n#define split_this_name_X_declared\n",
  out.str()
 );
}
<|endoftext|>