<commit_before>// .SECTION Thanks
// This test was implemented by Philippe Pebay, Kitware SAS 2012

#include "vtkDataObjectCollection.h"
#include "vtkDoubleArray.h"
#include "vtkMath.h"
#include "vtkMultiBlockDataSet.h"
#include "vtkStringArray.h"
#include "vtkTable.h"
#include "vtkTimerLog.h"
#include "vtkAutoCorrelativeStatistics.h"

//=============================================================================
int TestAutoCorrelativeStatistics( int, char *[] )
{
  int testStatus = 0;

  // ************** Test with 3 columns of input data **************

  // Input data
  double mingledData[] =
    {
      46,
      45,
      47,
      49,
      46,
      47,
      46,
      46,
      47,
      46,
      47,
      49,
      49,
      49,
      47,
      45,
      50,
      50,
      46,
      46,
      51,
      50,
      48,
      48,
      52,
      54,
      48,
      47,
      52,
      52,
      49,
      49,
      53,
      54,
      50,
      50,
      53,
      54,
      50,
      52,
      53,
      53,
      50,
      51,
      54,
      54,
      49,
      49,
      52,
      52,
      50,
      51,
      52,
      52,
      49,
      47,
      48,
      48,
      48,
      50,
      46,
      48,
      47,
      47,
    };

  // Test with entire data set
  int nVals1 = 32;

  vtkDoubleArray* dataset1Arr = vtkDoubleArray::New();
  dataset1Arr->SetNumberOfComponents( 1 );
  dataset1Arr->SetName( "Metric 0" );

  vtkDoubleArray* dataset2Arr = vtkDoubleArray::New();
  dataset2Arr->SetNumberOfComponents( 1 );
  dataset2Arr->SetName( "Metric 1" );

  vtkDoubleArray* dataset3Arr = vtkDoubleArray::New();
  dataset3Arr->SetNumberOfComponents( 1 );
  dataset3Arr->SetName( "Metric 2" );

  for ( int i = 0; i < nVals1; ++ i )
    {
    int ti = i << 1;
    dataset1Arr->InsertNextValue( mingledData[ti] );
    dataset2Arr->InsertNextValue( mingledData[ti + 1] );
    dataset3Arr->InsertNextValue( -1. );
    }

  vtkTable* datasetTable1 = vtkTable::New();
  datasetTable1->AddColumn( dataset1Arr );
  dataset1Arr->Delete();
  datasetTable1->AddColumn( dataset2Arr );
  dataset2Arr->Delete();
  datasetTable1->AddColumn( dataset3Arr );
  dataset3Arr->Delete();

  // Pairs of interest
  int nMetrics = 3;
  vtkStdString columns[] =
    {
      "Metric 1",
      "Metric 2",
      "Metric 0"
    };

  // Reference values
  // Means for metrics 0, 1, and 2, respectively
  double means1[] = { 49.21875 , 49.5, -1. };

  // Standard deviations for metrics 0, 1, and 2, respectively
  double vars1[] = { 5.9828629, 7.548397, 0. };

  // Set autocorrelative statistics algorithm and its input data port
  vtkAutoCorrelativeStatistics* as1 = vtkAutoCorrelativeStatistics::New();

  // First verify that absence of input does not cause trouble
  cout << "\n## Verifying that absence of input does not cause trouble... ";
  as1->Update();
  cout << "done.\n";

  // Prepare first test with data
  as1->SetInputData( vtkStatisticsAlgorithm::INPUT_DATA, datasetTable1 );
  datasetTable1->Delete();

  // Select Columns of Interest
  for ( int i = 0; i< nMetrics; ++ i )
    {
    as1->AddColumn( columns[i] );
    }

  // Test Learn, and Derive options
  as1->SetLearnOption( true );
  as1->SetDeriveOption( true );
  as1->SetAssessOption( false );
  as1->SetTestOption( false );
  as1->Update();

  // Get output data and meta tables
  vtkTable* outputData1 = as1->GetOutput( vtkStatisticsAlgorithm::OUTPUT_DATA );
  vtkMultiBlockDataSet* outputMetaAS1 = vtkMultiBlockDataSet::SafeDownCast( as1->GetOutputDataObject( vtkStatisticsAlgorithm::OUTPUT_MODEL ) );
  vtkTable* outputPrimary1 = vtkTable::SafeDownCast( outputMetaAS1->GetBlock( 0 ) );
  vtkTable* outputDerived1 = vtkTable::SafeDownCast( outputMetaAS1->GetBlock( 1 ) );
  vtkTable* outputTest1 = as1->GetOutput( vtkStatisticsAlgorithm::OUTPUT_TEST );

  cout << "\n## Calculated the following primary statistics for first data set:\n";
  for ( vtkIdType r = 0; r < outputPrimary1->GetNumberOfRows(); ++ r )
    {
    cout << "   ";
    for ( int i = 0; i < outputPrimary1->GetNumberOfColumns(); ++ i )
      {
      cout << outputPrimary1->GetColumnName( i )
           << "="
           << outputPrimary1->GetValue( r, i ).ToString()
           << "  ";
      }

    // Verify some of the calculated primary statistics
    if ( fabs ( outputPrimary1->GetValueByName( r, "Mean Xs" ).ToDouble() - means1[r] ) > 1.e-6 )
      {
      vtkGenericWarningMacro("Incorrect mean");
      testStatus = 1;
      }
    cout << "\n";
    }

  cout << "\n## Calculated the following derived statistics for first data set:\n";
  for ( vtkIdType r = 0; r < outputDerived1->GetNumberOfRows(); ++ r )
    {
    cout << "   ";
    for ( int i = 0; i < outputDerived1->GetNumberOfColumns(); ++ i )
      {
      cout << outputDerived1->GetColumnName( i )
           << "="
           << outputDerived1->GetValue( r, i ).ToString()
           << "  ";
      }

    // Verify some of the calculated derived statistics
    if ( fabs ( outputDerived1->GetValueByName( r, "Variance Xs" ).ToDouble() - vars1[r] ) > 1.e-5 )
      {
      vtkGenericWarningMacro("Incorrect variance");
      testStatus = 1;
      }
    cout << "\n";
    }

  // Clean up
  as1->Delete();

  // ************** Pseudo-random sample to inspect auto-correlation properties *********
  int nVals = 10000;

  vtkDoubleArray* datasetNormal = vtkDoubleArray::New();
  datasetNormal->SetNumberOfComponents( 1 );
  datasetNormal->SetName( "Standard Normal" );

  vtkDoubleArray* datasetUniform = vtkDoubleArray::New();
  datasetUniform->SetNumberOfComponents( 1 );
  datasetUniform->SetName( "Standard Uniform" );

  vtkDoubleArray* datasetLogNormal = vtkDoubleArray::New();
  datasetLogNormal->SetNumberOfComponents( 1 );
  datasetLogNormal->SetName( "Standard Log-Normal" );

  vtkDoubleArray* datasetExponential = vtkDoubleArray::New();
  datasetExponential->SetNumberOfComponents( 1 );
  datasetExponential->SetName( "Standard Exponential" );

  vtkDoubleArray* datasetLaplace = vtkDoubleArray::New();
  datasetLaplace->SetNumberOfComponents( 1 );
  datasetLaplace->SetName( "Standard Laplace" );

  // Seed random number generator
  vtkMath::RandomSeed( static_cast<int>( vtkTimerLog::GetUniversalTime() ) );

  for ( int i = 0; i < nVals; ++ i )
    {
    datasetNormal->InsertNextValue( vtkMath::Gaussian() );
    datasetUniform->InsertNextValue( vtkMath::Random() );
    datasetLogNormal->InsertNextValue( exp( vtkMath::Gaussian() ) );
    datasetExponential->InsertNextValue( -log ( vtkMath::Random() ) );
    double u = vtkMath::Random() - .5;
    datasetLaplace->InsertNextValue( ( u < 0. ? 1. : -1. ) * log ( 1. - 2. * fabs( u ) ) );
    }

  vtkTable* gaussianTable = vtkTable::New();
  gaussianTable->AddColumn( datasetNormal );
  datasetNormal->Delete();
  gaussianTable->AddColumn( datasetUniform );
  datasetUniform->Delete();
  gaussianTable->AddColumn( datasetLogNormal );
  datasetLogNormal->Delete();
  gaussianTable->AddColumn( datasetExponential );
  datasetExponential->Delete();
  gaussianTable->AddColumn( datasetLaplace );
  datasetLaplace->Delete();

  // Set autocorrelative statistics algorithm and its input data port
  vtkAutoCorrelativeStatistics* as2 = vtkAutoCorrelativeStatistics::New();
  as2->SetInputData( vtkStatisticsAlgorithm::INPUT_DATA, gaussianTable );
  gaussianTable->Delete();

  // Select Column of Interest
  as2->AddColumn( "Standard Normal" );
  as2->AddColumn( "Standard Uniform" );
  as2->AddColumn( "Standard Log-Normal" );
  as2->AddColumn( "Standard Exponential" );
  as2->AddColumn( "Standard Laplace" );

  // Test Learn, and Derive options
  as2->SetLearnOption( true );
  as2->SetDeriveOption( true );
  as2->SetTestOption( false );
  as2->SetAssessOption( false );
  as2->SetAutoCorrelationOffset( 1 );
  as2->Update();

  // Get output data and meta tables
  vtkMultiBlockDataSet* outputMetaAS2 = vtkMultiBlockDataSet::SafeDownCast( as2->GetOutputDataObject( vtkStatisticsAlgorithm::OUTPUT_MODEL ) );
  vtkTable* outputPrimary4 = vtkTable::SafeDownCast( outputMetaAS2->GetBlock( 0 ) );
  vtkTable* outputDerived4 = vtkTable::SafeDownCast( outputMetaAS2->GetBlock( 1 ) );
  vtkTable* outputTest4 = as2->GetOutput( vtkStatisticsAlgorithm::OUTPUT_TEST );

  cout << "\n## Calculated the following primary statistics for pseudo-random variables (n="
       << nVals
       << "):\n";
  for ( vtkIdType r = 0; r < outputPrimary4->GetNumberOfRows(); ++ r )
    {
    cout << "   ";
    for ( int i = 0; i < outputPrimary4->GetNumberOfColumns(); ++ i )
      {
      cout << outputPrimary4->GetColumnName( i )
           << "="
           << outputPrimary4->GetValue( r, i ).ToString()
           << "  ";
      }

    cout << "\n";
    }

  cout << "\n## Calculated the following derived statistics for pseudo-random variables (n="
       << nVals
       << "):\n";
  for ( vtkIdType r = 0; r < outputDerived4->GetNumberOfRows(); ++ r )
    {
    cout << "   ";
    for ( int i = 0; i < outputDerived4->GetNumberOfColumns(); ++ i )
      {
      cout << outputDerived4->GetColumnName( i )
           << "="
           << outputDerived4->GetValue( r, i ).ToString()
           << "  ";
      }

    cout << "\n";
    }

  // Clean up
  as2->Delete();

  return testStatus;
}
<commit_msg>Removed forgotten unused variables from test<commit_after>// .SECTION Thanks
// This test was implemented by Philippe Pebay, Kitware SAS 2012

#include "vtkDataObjectCollection.h"
#include "vtkDoubleArray.h"
#include "vtkMath.h"
#include "vtkMultiBlockDataSet.h"
#include "vtkStringArray.h"
#include "vtkTable.h"
#include "vtkTimerLog.h"
#include "vtkAutoCorrelativeStatistics.h"

//=============================================================================
int TestAutoCorrelativeStatistics( int, char *[] )
{
  int testStatus = 0;

  // ************** Test with 3 columns of input data **************

  // Input data
  double mingledData[] =
    {
      46,
      45,
      47,
      49,
      46,
      47,
      46,
      46,
      47,
      46,
      47,
      49,
      49,
      49,
      47,
      45,
      50,
      50,
      46,
      46,
      51,
      50,
      48,
      48,
      52,
      54,
      48,
      47,
      52,
      52,
      49,
      49,
      53,
      54,
      50,
      50,
      53,
      54,
      50,
      52,
      53,
      53,
      50,
      51,
      54,
      54,
      49,
      49,
      52,
      52,
      50,
      51,
      52,
      52,
      49,
      47,
      48,
      48,
      48,
      50,
      46,
      48,
      47,
      47,
    };

  // Test with entire data set
  int nVals1 = 32;

  vtkDoubleArray* dataset1Arr = vtkDoubleArray::New();
  dataset1Arr->SetNumberOfComponents( 1 );
  dataset1Arr->SetName( "Metric 0" );

  vtkDoubleArray* dataset2Arr = vtkDoubleArray::New();
  dataset2Arr->SetNumberOfComponents( 1 );
  dataset2Arr->SetName( "Metric 1" );

  vtkDoubleArray* dataset3Arr = vtkDoubleArray::New();
  dataset3Arr->SetNumberOfComponents( 1 );
  dataset3Arr->SetName( "Metric 2" );

  for ( int i = 0; i < nVals1; ++ i )
    {
    int ti = i << 1;
    dataset1Arr->InsertNextValue( mingledData[ti] );
    dataset2Arr->InsertNextValue( mingledData[ti + 1] );
    dataset3Arr->InsertNextValue( -1. );
    }

  vtkTable* datasetTable1 = vtkTable::New();
  datasetTable1->AddColumn( dataset1Arr );
  dataset1Arr->Delete();
  datasetTable1->AddColumn( dataset2Arr );
  dataset2Arr->Delete();
  datasetTable1->AddColumn( dataset3Arr );
  dataset3Arr->Delete();

  // Pairs of interest
  int nMetrics = 3;
  vtkStdString columns[] =
    {
      "Metric 1",
      "Metric 2",
      "Metric 0"
    };

  // Reference values
  // Means for metrics 0, 1, and 2, respectively
  double means1[] = { 49.21875 , 49.5, -1. };

  // Standard deviations for metrics 0, 1, and 2, respectively
  double vars1[] = { 5.9828629, 7.548397, 0. };

  // Set autocorrelative statistics algorithm and its input data port
  vtkAutoCorrelativeStatistics* as1 = vtkAutoCorrelativeStatistics::New();

  // First verify that absence of input does not cause trouble
  cout << "\n## Verifying that absence of input does not cause trouble... ";
  as1->Update();
  cout << "done.\n";

  // Prepare first test with data
  as1->SetInputData( vtkStatisticsAlgorithm::INPUT_DATA, datasetTable1 );
  datasetTable1->Delete();

  // Select Columns of Interest
  for ( int i = 0; i< nMetrics; ++ i )
    {
    as1->AddColumn( columns[i] );
    }

  // Test Learn, and Derive options
  as1->SetLearnOption( true );
  as1->SetDeriveOption( true );
  as1->SetAssessOption( false );
  as1->SetTestOption( false );
  as1->Update();

  // Get output data and meta tables
  vtkMultiBlockDataSet* outputMetaAS1 = vtkMultiBlockDataSet::SafeDownCast( as1->GetOutputDataObject( vtkStatisticsAlgorithm::OUTPUT_MODEL ) );
  vtkTable* outputPrimary1 = vtkTable::SafeDownCast( outputMetaAS1->GetBlock( 0 ) );
  vtkTable* outputDerived1 = vtkTable::SafeDownCast( outputMetaAS1->GetBlock( 1 ) );

  cout << "\n## Calculated the following primary statistics for first data set:\n";
  for ( vtkIdType r = 0; r < outputPrimary1->GetNumberOfRows(); ++ r )
    {
    cout << "   ";
    for ( int i = 0; i < outputPrimary1->GetNumberOfColumns(); ++ i )
      {
      cout << outputPrimary1->GetColumnName( i )
           << "="
           << outputPrimary1->GetValue( r, i ).ToString()
           << "  ";
      }

    // Verify some of the calculated primary statistics
    if ( fabs ( outputPrimary1->GetValueByName( r, "Mean Xs" ).ToDouble() - means1[r] ) > 1.e-6 )
      {
      vtkGenericWarningMacro("Incorrect mean");
      testStatus = 1;
      }
    cout << "\n";
    }

  cout << "\n## Calculated the following derived statistics for first data set:\n";
  for ( vtkIdType r = 0; r < outputDerived1->GetNumberOfRows(); ++ r )
    {
    cout << "   ";
    for ( int i = 0; i < outputDerived1->GetNumberOfColumns(); ++ i )
      {
      cout << outputDerived1->GetColumnName( i )
           << "="
           << outputDerived1->GetValue( r, i ).ToString()
           << "  ";
      }

    // Verify some of the calculated derived statistics
    if ( fabs ( outputDerived1->GetValueByName( r, "Variance Xs" ).ToDouble() - vars1[r] ) > 1.e-5 )
      {
      vtkGenericWarningMacro("Incorrect variance");
      testStatus = 1;
      }
    cout << "\n";
    }

  // Clean up
  as1->Delete();

  // ************** Pseudo-random sample to inspect auto-correlation properties *********
  int nVals = 10000;

  vtkDoubleArray* datasetNormal = vtkDoubleArray::New();
  datasetNormal->SetNumberOfComponents( 1 );
  datasetNormal->SetName( "Standard Normal" );

  vtkDoubleArray* datasetUniform = vtkDoubleArray::New();
  datasetUniform->SetNumberOfComponents( 1 );
  datasetUniform->SetName( "Standard Uniform" );

  vtkDoubleArray* datasetLogNormal = vtkDoubleArray::New();
  datasetLogNormal->SetNumberOfComponents( 1 );
  datasetLogNormal->SetName( "Standard Log-Normal" );

  vtkDoubleArray* datasetExponential = vtkDoubleArray::New();
  datasetExponential->SetNumberOfComponents( 1 );
  datasetExponential->SetName( "Standard Exponential" );

  vtkDoubleArray* datasetLaplace = vtkDoubleArray::New();
  datasetLaplace->SetNumberOfComponents( 1 );
  datasetLaplace->SetName( "Standard Laplace" );

  // Seed random number generator
  vtkMath::RandomSeed( static_cast<int>( vtkTimerLog::GetUniversalTime() ) );

  for ( int i = 0; i < nVals; ++ i )
    {
    datasetNormal->InsertNextValue( vtkMath::Gaussian() );
    datasetUniform->InsertNextValue( vtkMath::Random() );
    datasetLogNormal->InsertNextValue( exp( vtkMath::Gaussian() ) );
    datasetExponential->InsertNextValue( -log ( vtkMath::Random() ) );
    double u = vtkMath::Random() - .5;
    datasetLaplace->InsertNextValue( ( u < 0. ? 1. : -1. ) * log ( 1. - 2. * fabs( u ) ) );
    }

  vtkTable* gaussianTable = vtkTable::New();
  gaussianTable->AddColumn( datasetNormal );
  datasetNormal->Delete();
  gaussianTable->AddColumn( datasetUniform );
  datasetUniform->Delete();
  gaussianTable->AddColumn( datasetLogNormal );
  datasetLogNormal->Delete();
  gaussianTable->AddColumn( datasetExponential );
  datasetExponential->Delete();
  gaussianTable->AddColumn( datasetLaplace );
  datasetLaplace->Delete();

  // Set autocorrelative statistics algorithm and its input data port
  vtkAutoCorrelativeStatistics* as2 = vtkAutoCorrelativeStatistics::New();
  as2->SetInputData( vtkStatisticsAlgorithm::INPUT_DATA, gaussianTable );
  gaussianTable->Delete();

  // Select Column of Interest
  as2->AddColumn( "Standard Normal" );
  as2->AddColumn( "Standard Uniform" );
  as2->AddColumn( "Standard Log-Normal" );
  as2->AddColumn( "Standard Exponential" );
  as2->AddColumn( "Standard Laplace" );

  // Test Learn, and Derive options
  as2->SetLearnOption( true );
  as2->SetDeriveOption( true );
  as2->SetTestOption( false );
  as2->SetAssessOption( false );
  as2->SetAutoCorrelationOffset( 1 );
  as2->Update();

  // Get output data and meta tables
  vtkMultiBlockDataSet* outputMetaAS2 = vtkMultiBlockDataSet::SafeDownCast( as2->GetOutputDataObject( vtkStatisticsAlgorithm::OUTPUT_MODEL ) );
  vtkTable* outputPrimary4 = vtkTable::SafeDownCast( outputMetaAS2->GetBlock( 0 ) );
  vtkTable* outputDerived4 = vtkTable::SafeDownCast( outputMetaAS2->GetBlock( 1 ) );

  cout << "\n## Calculated the following primary statistics for pseudo-random variables (n="
       << nVals
       << "):\n";
  for ( vtkIdType r = 0; r < outputPrimary4->GetNumberOfRows(); ++ r )
    {
    cout << "   ";
    for ( int i = 0; i < outputPrimary4->GetNumberOfColumns(); ++ i )
      {
      cout << outputPrimary4->GetColumnName( i )
           << "="
           << outputPrimary4->GetValue( r, i ).ToString()
           << "  ";
      }

    cout << "\n";
    }

  cout << "\n## Calculated the following derived statistics for pseudo-random variables (n="
       << nVals
       << "):\n";
  for ( vtkIdType r = 0; r < outputDerived4->GetNumberOfRows(); ++ r )
    {
    cout << "   ";
    for ( int i = 0; i < outputDerived4->GetNumberOfColumns(); ++ i )
      {
      cout << outputDerived4->GetColumnName( i )
           << "="
           << outputDerived4->GetValue( r, i ).ToString()
           << "  ";
      }

    cout << "\n";
    }

  // Clean up
  as2->Delete();

  return testStatus;
}
<|endoftext|>


<commit_before>/*
 * FlexEnumParam.cpp
 *
 * Copyright (C) 2017 by Universitaet Stuttgart (VIS).
 * Alle Rechte vorbehalten.
 */

#include "stdafx.h"
#include "mmcore/param/FlexEnumParam.h"
#include "vislib/IllegalStateException.h"
#include "vislib/StringConverter.h"
#include "vislib/UTF8Encoder.h"
#include <set>

using namespace megamol::core::param;

/*
 * FlexEnumParam::FlexEnumParam
 */
FlexEnumParam::FlexEnumParam(const std::string& initVal)
        : AbstractParam(), val(initVal), values() {
    // intentionally empty
}

/*
 * FlexEnumParam::~FlexEnumParam
 */
FlexEnumParam::~FlexEnumParam(void) {
    // intentionally empty
}

/*
 * FlexEnumParam::ClearTypePairs
 */
void megamol::core::param::FlexEnumParam::ClearValues(void) {
    this->SetHash(this->GetHash() + 1);
    this->values.clear();
}

/*
 * FlexEnumParam::Definition
 */
void FlexEnumParam::Definition(vislib::RawStorage& outDef) const {
    vislib::StringA utf8;
    unsigned int s = 6;
    unsigned int c = 0;
    for (auto &v : this->values) {
        s += v.length() + 1; //terminating zero
    }
    s += sizeof(unsigned int);

    outDef.AssertSize(s);
    memcpy(outDef.AsAt<char>(0), "MMFENU", 6);
    s = 6 + sizeof(unsigned int);
    std::set<std::string> sorted(this->values.begin(), this->values.end());
    for (auto &v: sorted) {
        unsigned int strsize = v.length() + 1;
        memcpy(outDef.AsAt<char>(s), v.c_str(), strsize);
        s += strsize;
        c++;
    }
    *outDef.AsAt<unsigned int>(6) = c;
}

/*
 * FlexEnumParam::ParseValue
 */
bool FlexEnumParam::ParseValue(const vislib::TString& v) {
    try {
        this->SetValue(T2A(v));
        //auto iter = this->values.find(std::string(T2A(v)));
        //if (iter == this->values.end()) {
        //    return false;
        //} else {
        //    this->SetValue(*iter);
        //    return true;
        //}
    } catch(...) {
    }
    return false;
}

/*
 * FlexEnumParam::AddValue
 */
FlexEnumParam* FlexEnumParam::AddValue(const std::string& name) {
    auto iter = this->values.find(name);
    if (iter == this->values.end()) {
        this->SetHash(this->GetHash() + 1);
        this->values.insert(name);
    }
    return this;
}

/*
 * FlexEnumParam::SetValue
 */
void FlexEnumParam::SetValue(const std::string& v, bool setDirty) {
    if (this->val != v) {
        this->val = v;
        if (setDirty) this->setDirty();
    }
}

/*
 * FlexEnumParam::ValueString
 */
vislib::TString FlexEnumParam::ValueString(void) const {
    return A2T(val.c_str());
}
<commit_msg>Fixed Linux issue.<commit_after>/*
 * FlexEnumParam.cpp
 *
 * Copyright (C) 2017 by Universitaet Stuttgart (VIS).
 * Alle Rechte vorbehalten.
 */

#include "stdafx.h"
#include "mmcore/param/FlexEnumParam.h"
#include "vislib/IllegalStateException.h"
#include "vislib/StringConverter.h"
#include "vislib/UTF8Encoder.h"
#include <set>

using namespace megamol::core::param;

/*
 * FlexEnumParam::FlexEnumParam
 */
FlexEnumParam::FlexEnumParam(const std::string& initVal)
        : AbstractParam(), val(initVal), values() {
    // intentionally empty
}

/*
 * FlexEnumParam::~FlexEnumParam
 */
FlexEnumParam::~FlexEnumParam(void) {
    // intentionally empty
}

/*
 * FlexEnumParam::ClearTypePairs
 */
void megamol::core::param::FlexEnumParam::ClearValues(void) {
    this->SetHash(this->GetHash() + 1);
    this->values.clear();
}

/*
 * FlexEnumParam::Definition
 */
void FlexEnumParam::Definition(vislib::RawStorage& outDef) const {
    vislib::StringA utf8;
    unsigned int s = 6;
    unsigned int c = 0;
    for (auto &v : this->values) {
        s += v.length() + 1; //terminating zero
    }
    s += sizeof(unsigned int);

    outDef.AssertSize(s);
    memcpy(outDef.AsAt<char>(0), "MMFENU", 6);
    s = 6 + sizeof(unsigned int);
    std::set<std::string> sorted(this->values.begin(), this->values.end());
    for (auto &v: sorted) {
        unsigned int strsize = v.length() + 1;
        memcpy(outDef.AsAt<char>(s), v.c_str(), strsize);
        s += strsize;
        c++;
    }
    *outDef.AsAt<unsigned int>(6) = c;
}

/*
 * FlexEnumParam::ParseValue
 */
bool FlexEnumParam::ParseValue(const vislib::TString& v) {
    try {
        this->SetValue(std::string(T2A(v)));
        //auto iter = this->values.find(std::string(T2A(v)));
        //if (iter == this->values.end()) {
        //    return false;
        //} else {
        //    this->SetValue(*iter);
        //    return true;
        //}
    } catch(...) {
    }
    return false;
}

/*
 * FlexEnumParam::AddValue
 */
FlexEnumParam* FlexEnumParam::AddValue(const std::string& name) {
    auto iter = this->values.find(name);
    if (iter == this->values.end()) {
        this->SetHash(this->GetHash() + 1);
        this->values.insert(name);
    }
    return this;
}

/*
 * FlexEnumParam::SetValue
 */
void FlexEnumParam::SetValue(const std::string& v, bool setDirty) {
    if (this->val != v) {
        this->val = v;
        if (setDirty) this->setDirty();
    }
}

/*
 * FlexEnumParam::ValueString
 */
vislib::TString FlexEnumParam::ValueString(void) const {
    return A2T(val.c_str());
}
<|endoftext|>


<commit_before>
#include "diff_system.h"
#include "equation_systems.h"
#include "linear_solver.h"
#include "newton_solver.h"
#include "numeric_vector.h"
#include "sparse_matrix.h"

NewtonSolver::NewtonSolver (sys_type& s) :
  Parent(s), linear_solver(LinearSolver<Number>::build())
{
}

NewtonSolver::~NewtonSolver ()
{
}

void NewtonSolver::solve()
{
// The number of steps and the stopping criterion
// for the nonlinear iterations.
const unsigned int max_nonlinear_steps = 100;
const unsigned int max_linear_iterations = 10000;

// Stopping criteria for nonlinear iterations
const Real nonlinear_abs_step_tolerance = 1.e-9;
const Real nonlinear_rel_step_tolerance = 1.e-9;
const Real nonlinear_abs_res_tolerance = 1.e-9;
const Real nonlinear_rel_res_tolerance = 1.e-9;
// Maximum amount by which to reduce Newton steps
const Real minsteplength = 0.1;
// Initial linear solver tolerance in main nonlinear solver
const Real linear_tolerance = 1.e-3;
// Amount by which nonlinear residual should exceed linear solver
// tolerance
const Real relative_tolerance = 1.e-3;
// We'll shut up eventually...
const bool verbose_convergence_chatter = true;

  EquationSystems equation_systems = _system.get_equation_systems();

  equation_systems.parameters.set<unsigned int>
                   ("linear solver maximum iterations") =
                   max_linear_iterations;

  NumericVector<Number> &solution = *(_system.solution);
  NumericVector<Number> &newton_iterate =
    _system.get_vector("_nonlinear_solution");
  NumericVector<Number> &rhs = *(_system.rhs);

  SparseMatrix<Number> &matrix = *(_system.matrix);

  // Now we begin the nonlinear loop
  newton_iterate.zero();
  newton_iterate.close();

  // Prepare to take incomplete steps
  Real last_residual, first_residual;

  // Set starting linear tolerance
  Real current_linear_tolerance = linear_tolerance;

  for (unsigned int l=0; l<max_nonlinear_steps; ++l)
    {
      _system.assembly(true, true);
      rhs.close();
      Real current_residual = rhs.l2_norm();
      if (!l)
        first_residual = current_residual;
      last_residual = current_residual;
std::cout << "Nonlinear Residual: " << current_residual << std::endl;

      // Make sure our linear tolerance is low enough
      if (current_linear_tolerance > current_residual * relative_tolerance)
        {
          current_linear_tolerance = current_residual * relative_tolerance;
          equation_systems.parameters.set<Real>
            ("linear solver tolerance") = current_linear_tolerance;
        }

      // At this point newton_iterate is the current guess, and
      // solution is now about to become the NEGATIVE of the next
      // Newton step

std::cout << "Linear solve starting" << std::endl;

      // Solve the linear system.  Two cases:
      const std::pair<unsigned int, Real> rval =
        (_system.have_matrix("Preconditioner")) ?
      // 1.) User-supplied preconditioner
        linear_solver->solve (matrix, _system.get_matrix("Preconditioner"),
                              solution, rhs, current_linear_tolerance,
                              max_linear_iterations) :
      // 2.) Use system matrix for the preconditioner
        linear_solver->solve (matrix, solution, rhs,
                              current_linear_tolerance,
                              max_linear_iterations);

std::cout << "Linear solve converged, step " << rval.first
          << ", residual " << rval.second
          << ", tolerance " << current_linear_tolerance << std::endl;

      // Compute the l2 norm of the nonlinear update
      Real norm_delta = solution.l2_norm();

std::cout << "Taking full Newton step" << std::endl;
          // Take a full Newton step
      newton_iterate.add (-1., solution);
      newton_iterate.close();

      // Check residual with full Newton step
      Real steplength = 1.;
      _system.assembly(true, false);

      // backtrack if necessary
      rhs.close()
      current_residual = rhs.l2_norm();
      while (current_residual > last_residual)
        {
          // Reduce step size to 1/2, 1/4, etc.
          steplength /= 2.;
          norm_delta /= 2.;
std::cout << "Shrinking Newton step to " << steplength << std::endl;
              newton_iterate.add (steplength, solution);
              newton_iterate.close();

          // Check residual with fractional Newton step
          std::cout << "          Checking " << std::flush;
          _system.assembly (true, false);
          current_residual = rhs.l2_norm();

          if (steplength/2. < minsteplength &&
              current_residual > last_residual)
            {
std::cout << "Inexact Newton step FAILED at step " << l << std::endl;

              error();
            }
        }

      // Compute the l2 norm of the whole solution
      const Real norm_total = newton_iterate.l2_norm();

      // Print out information for the
      // nonlinear iterations.
      std::cout << "    Nonlinear step: |du|/|u| = "
                << norm_delta / norm_total
                << ", |du| = "
                << norm_delta
                << std::endl;

      // We haven't converged unless we pass a convergence test
      bool has_converged = false;

      // Is our absolute residual low enough?
      if (current_residual < nonlinear_abs_res_tolerance)
        {
          std::cout << "  Nonlinear solver converged, step "
                    << l
                    << ", residual "
                    << current_residual
                    << std::endl;
          has_converged = true;
        }
      else if (verbose_convergence_chatter)
        {
          std::cout << "  Nonlinear solver current_residual "
                    << current_residual
                    << " > "
                    << (nonlinear_abs_res_tolerance)
                    << std::endl;
        }

      // Is our relative residual low enough?
      if ((current_residual / first_residual) < nonlinear_rel_res_tolerance)
        {
          std::cout << "  Nonlinear solver converged, step "
                    << l
                    << ", residual reduction "
                    << current_residual / first_residual
                    << std::endl;
          has_converged = true;
        }
      else if (verbose_convergence_chatter)
        {
          std::cout << "  Nonlinear solver current/first residual "
                    << (current_residual / first_residual)
                    << " > "
                    << nonlinear_rel_res_tolerance
                    << std::endl;
        }

      // Is our absolute Newton step size small enough?
      if (l != 0 && (norm_delta / steplength <
          nonlinear_abs_step_tolerance))
        {
          std::cout << "  Nonlinear solver converged, step "
                    << l
                    << ", absolute step size "
                    << norm_delta / steplength
                    << std::endl;
          has_converged = true;
        }

      // Is our relative Newton step size small enough?
      if (l != 0 && (norm_delta / steplength / norm_total <
          nonlinear_rel_step_tolerance))
        {
          std::cout << "  Nonlinear solver converged, step "
                    << l
                    << ", relative step size "
                    << (norm_delta / steplength / norm_total)
                    << std::endl;
          has_converged = true;
        }

      // Terminate the solution iteration if the difference between
      // this iteration and the last is sufficiently small.
      if (has_converged)
        {
          break;
        }
      if (l >= max_nonlinear_steps - 1)
        {
          std::cout << "  Nonlinear solver DIVERGED at step "
                    << l
                    << std::endl;
          error();
          continue;
        }
    } // end nonlinear loop
}
<commit_msg>Typo fix<commit_after>
#include "diff_system.h"
#include "equation_systems.h"
#include "linear_solver.h"
#include "newton_solver.h"
#include "numeric_vector.h"
#include "sparse_matrix.h"

NewtonSolver::NewtonSolver (sys_type& s) :
  Parent(s), linear_solver(LinearSolver<Number>::build())
{
}

NewtonSolver::~NewtonSolver ()
{
}

void NewtonSolver::solve()
{
// The number of steps and the stopping criterion
// for the nonlinear iterations.
const unsigned int max_nonlinear_steps = 100;
const unsigned int max_linear_iterations = 10000;

// Stopping criteria for nonlinear iterations
const Real nonlinear_abs_step_tolerance = 1.e-9;
const Real nonlinear_rel_step_tolerance = 1.e-9;
const Real nonlinear_abs_res_tolerance = 1.e-9;
const Real nonlinear_rel_res_tolerance = 1.e-9;
// Maximum amount by which to reduce Newton steps
const Real minsteplength = 0.1;
// Initial linear solver tolerance in main nonlinear solver
const Real linear_tolerance = 1.e-3;
// Amount by which nonlinear residual should exceed linear solver
// tolerance
const Real relative_tolerance = 1.e-3;
// We'll shut up eventually...
const bool verbose_convergence_chatter = true;

  EquationSystems equation_systems = _system.get_equation_systems();

  equation_systems.parameters.set<unsigned int>
                   ("linear solver maximum iterations") =
                   max_linear_iterations;

  NumericVector<Number> &solution = *(_system.solution);
  NumericVector<Number> &newton_iterate =
    _system.get_vector("_nonlinear_solution");
  NumericVector<Number> &rhs = *(_system.rhs);

  SparseMatrix<Number> &matrix = *(_system.matrix);

  // Now we begin the nonlinear loop
  newton_iterate.zero();
  newton_iterate.close();

  // Prepare to take incomplete steps
  Real last_residual, first_residual;

  // Set starting linear tolerance
  Real current_linear_tolerance = linear_tolerance;

  for (unsigned int l=0; l<max_nonlinear_steps; ++l)
    {
      _system.assembly(true, true);
      rhs.close();
      Real current_residual = rhs.l2_norm();
      if (!l)
        first_residual = current_residual;
      last_residual = current_residual;
std::cout << "Nonlinear Residual: " << current_residual << std::endl;

      // Make sure our linear tolerance is low enough
      if (current_linear_tolerance > current_residual * relative_tolerance)
        {
          current_linear_tolerance = current_residual * relative_tolerance;
          equation_systems.parameters.set<Real>
            ("linear solver tolerance") = current_linear_tolerance;
        }

      // At this point newton_iterate is the current guess, and
      // solution is now about to become the NEGATIVE of the next
      // Newton step

std::cout << "Linear solve starting" << std::endl;

      // Solve the linear system.  Two cases:
      const std::pair<unsigned int, Real> rval =
        (_system.have_matrix("Preconditioner")) ?
      // 1.) User-supplied preconditioner
        linear_solver->solve (matrix, _system.get_matrix("Preconditioner"),
                              solution, rhs, current_linear_tolerance,
                              max_linear_iterations) :
      // 2.) Use system matrix for the preconditioner
        linear_solver->solve (matrix, solution, rhs,
                              current_linear_tolerance,
                              max_linear_iterations);

std::cout << "Linear solve converged, step " << rval.first
          << ", residual " << rval.second
          << ", tolerance " << current_linear_tolerance << std::endl;

      // Compute the l2 norm of the nonlinear update
      Real norm_delta = solution.l2_norm();

std::cout << "Taking full Newton step" << std::endl;
          // Take a full Newton step
      newton_iterate.add (-1., solution);
      newton_iterate.close();

      // Check residual with full Newton step
      Real steplength = 1.;
      _system.assembly(true, false);

      // backtrack if necessary
      rhs.close();
      current_residual = rhs.l2_norm();
      while (current_residual > last_residual)
        {
          // Reduce step size to 1/2, 1/4, etc.
          steplength /= 2.;
          norm_delta /= 2.;
std::cout << "Shrinking Newton step to " << steplength << std::endl;
              newton_iterate.add (steplength, solution);
              newton_iterate.close();

          // Check residual with fractional Newton step
          std::cout << "          Checking " << std::flush;
          _system.assembly (true, false);
          current_residual = rhs.l2_norm();

          if (steplength/2. < minsteplength &&
              current_residual > last_residual)
            {
std::cout << "Inexact Newton step FAILED at step " << l << std::endl;

              error();
            }
        }

      // Compute the l2 norm of the whole solution
      const Real norm_total = newton_iterate.l2_norm();

      // Print out information for the
      // nonlinear iterations.
      std::cout << "    Nonlinear step: |du|/|u| = "
                << norm_delta / norm_total
                << ", |du| = "
                << norm_delta
                << std::endl;

      // We haven't converged unless we pass a convergence test
      bool has_converged = false;

      // Is our absolute residual low enough?
      if (current_residual < nonlinear_abs_res_tolerance)
        {
          std::cout << "  Nonlinear solver converged, step "
                    << l
                    << ", residual "
                    << current_residual
                    << std::endl;
          has_converged = true;
        }
      else if (verbose_convergence_chatter)
        {
          std::cout << "  Nonlinear solver current_residual "
                    << current_residual
                    << " > "
                    << (nonlinear_abs_res_tolerance)
                    << std::endl;
        }

      // Is our relative residual low enough?
      if ((current_residual / first_residual) < nonlinear_rel_res_tolerance)
        {
          std::cout << "  Nonlinear solver converged, step "
                    << l
                    << ", residual reduction "
                    << current_residual / first_residual
                    << std::endl;
          has_converged = true;
        }
      else if (verbose_convergence_chatter)
        {
          std::cout << "  Nonlinear solver current/first residual "
                    << (current_residual / first_residual)
                    << " > "
                    << nonlinear_rel_res_tolerance
                    << std::endl;
        }

      // Is our absolute Newton step size small enough?
      if (l != 0 && (norm_delta / steplength <
          nonlinear_abs_step_tolerance))
        {
          std::cout << "  Nonlinear solver converged, step "
                    << l
                    << ", absolute step size "
                    << norm_delta / steplength
                    << std::endl;
          has_converged = true;
        }

      // Is our relative Newton step size small enough?
      if (l != 0 && (norm_delta / steplength / norm_total <
          nonlinear_rel_step_tolerance))
        {
          std::cout << "  Nonlinear solver converged, step "
                    << l
                    << ", relative step size "
                    << (norm_delta / steplength / norm_total)
                    << std::endl;
          has_converged = true;
        }

      // Terminate the solution iteration if the difference between
      // this iteration and the last is sufficiently small.
      if (has_converged)
        {
          break;
        }
      if (l >= max_nonlinear_steps - 1)
        {
          std::cout << "  Nonlinear solver DIVERGED at step "
                    << l
                    << std::endl;
          error();
          continue;
        }
    } // end nonlinear loop
}
<|endoftext|>


<commit_before>/**
 * This file is part of TelepathyQt
 *
 * @copyright Copyright (C) 2009-2011 Collabora Ltd. <http://www.collabora.co.uk/>
 * @license LGPL 2.1
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 */

#include <TelepathyQt/Debug>
#include <TelepathyQt/Types>

#include <QDebug>
#include <QtGui>

#include "roster-window.h"

int main(int argc, char **argv)
{
    QApplication app(argc, argv);

    if (argc < 2) {
        qDebug() << "usage:" << argv[0] << "<account name, as in mc-tool list>";
        return 1;
    }

    Tp::registerTypes();
    Tp::enableDebug(true);
    Tp::enableWarnings(true);

    QString accountPath = QLatin1String(argv[1]);
    RosterWindow w(accountPath);
    w.show();

    return app.exec();
}
<commit_msg>roster example: Include QApplication header as it's not part of QtGui in Qt5.<commit_after>/**
 * This file is part of TelepathyQt
 *
 * @copyright Copyright (C) 2009-2011 Collabora Ltd. <http://www.collabora.co.uk/>
 * @license LGPL 2.1
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 */

#include <TelepathyQt/Debug>
#include <TelepathyQt/Types>

#include <QApplication>
#include <QDebug>
#include <QtGui>

#include "roster-window.h"

int main(int argc, char **argv)
{
    QApplication app(argc, argv);

    if (argc < 2) {
        qDebug() << "usage:" << argv[0] << "<account name, as in mc-tool list>";
        return 1;
    }

    Tp::registerTypes();
    Tp::enableDebug(true);
    Tp::enableWarnings(true);

    QString accountPath = QLatin1String(argv[1]);
    RosterWindow w(accountPath);
    w.show();

    return app.exec();
}
<|endoftext|>


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

#include "Win32_StackTrace.h"
#include "Win32_RedisLog.h"
#include <DbgHelp.h>
#include <signal.h>
#include <stdio.h>

static HANDLE process;
static IMAGEHLP_SYMBOL64* pSymbol = (IMAGEHLP_SYMBOL64*) malloc(sizeof(IMAGEHLP_SYMBOL64) + MAX_PATH*sizeof(TCHAR));
static IMAGEHLP_LINE64 line;
static BOOLEAN processingException = FALSE;
static CHAR modulePath[MAX_PATH];
static BOOL symbolsInitialized = FALSE;

static const char* exceptionDescription(const DWORD& code)
{
    switch (code) {
    case EXCEPTION_ACCESS_VIOLATION:         return "EXCEPTION_ACCESS_VIOLATION";
    case EXCEPTION_ARRAY_BOUNDS_EXCEEDED:    return "EXCEPTION_ARRAY_BOUNDS_EXCEEDED";
    case EXCEPTION_BREAKPOINT:               return "EXCEPTION_BREAKPOINT";
    case EXCEPTION_DATATYPE_MISALIGNMENT:    return "EXCEPTION_DATATYPE_MISALIGNMENT";
    case EXCEPTION_FLT_DENORMAL_OPERAND:     return "EXCEPTION_FLT_DENORMAL_OPERAND";
    case EXCEPTION_FLT_DIVIDE_BY_ZERO:       return "EXCEPTION_FLT_DIVIDE_BY_ZERO";
    case EXCEPTION_FLT_INEXACT_RESULT:       return "EXCEPTION_FLT_INEXACT_RESULT";
    case EXCEPTION_FLT_INVALID_OPERATION:    return "EXCEPTION_FLT_INVALID_OPERATION";
    case EXCEPTION_FLT_OVERFLOW:             return "EXCEPTION_FLT_OVERFLOW";
    case EXCEPTION_FLT_STACK_CHECK:          return "EXCEPTION_FLT_STACK_CHECK";
    case EXCEPTION_FLT_UNDERFLOW:            return "EXCEPTION_FLT_UNDERFLOW";
    case EXCEPTION_ILLEGAL_INSTRUCTION:      return "EXCEPTION_ILLEGAL_INSTRUCTION";
    case EXCEPTION_IN_PAGE_ERROR:            return "EXCEPTION_IN_PAGE_ERROR";
    case EXCEPTION_INT_DIVIDE_BY_ZERO:       return "EXCEPTION_INT_DIVIDE_BY_ZERO";
    case EXCEPTION_INT_OVERFLOW:             return "EXCEPTION_INT_OVERFLOW";
    case EXCEPTION_INVALID_DISPOSITION:      return "EXCEPTION_INVALID_DISPOSITION";
    case EXCEPTION_NONCONTINUABLE_EXCEPTION: return "EXCEPTION_NONCONTINUABLE_EXCEPTION";
    case EXCEPTION_PRIV_INSTRUCTION:         return "EXCEPTION_PRIV_INSTRUCTION";
    case EXCEPTION_SINGLE_STEP:              return "EXCEPTION_SINGLE_STEP";
    case EXCEPTION_STACK_OVERFLOW:           return "EXCEPTION_STACK_OVERFLOW";
    default: return "UNKNOWN EXCEPTION";
    }
}

/* Returns the index of the last backslash in the file path */
int GetFilenameStart(CHAR* path) {
    int pos = 0;
    int found = 0;
    if (path != NULL) {
        while (path[pos] != '\0' && pos < MAX_PATH) {
            if (path[pos] == '\\') {
                found = pos + 1;
            }
            ++pos;
        }
    }

    return found;
}

#ifdef _WIN64
void LogStackTrace() {
    BOOL            result;
    HANDLE          thread;
    CONTEXT         context;
    STACKFRAME64    stack;
    ULONG           frame;
    DWORD64         dw64Displacement;
    DWORD           dwDisplacement;

    memset(&stack, 0, sizeof(STACKFRAME64));
    memset(pSymbol, '\0', sizeof(*pSymbol) + MAX_PATH);
    memset(&modulePath[0], '\0', sizeof(modulePath));
    line.LineNumber = 0;

    RtlCaptureContext(&context);
    process = GetCurrentProcess();
    thread = GetCurrentThread();
    dw64Displacement = 0;
    stack.AddrPC.Offset = context.Rip;
    stack.AddrPC.Mode = AddrModeFlat;
    stack.AddrStack.Offset = context.Rsp;
    stack.AddrStack.Mode = AddrModeFlat;
    stack.AddrFrame.Offset = context.Rbp;
    stack.AddrFrame.Mode = AddrModeFlat;

    for (frame = 0;; frame++){
        result = StackWalk64(
            IMAGE_FILE_MACHINE_AMD64,
            process,
            thread,
            &stack,
            &context,
            NULL,
            SymFunctionTableAccess64,
            SymGetModuleBase64,
            NULL
            );

        pSymbol->MaxNameLength = MAX_PATH;
        pSymbol->SizeOfStruct = sizeof(IMAGEHLP_SYMBOL64);

        SymGetSymFromAddr64(process, stack.AddrPC.Offset, &dw64Displacement, pSymbol);
        SymGetLineFromAddr64(process, stack.AddrPC.Offset, &dwDisplacement, &line);

        DWORD64 moduleBase = SymGetModuleBase64(process, stack.AddrPC.Offset);
        if (moduleBase)
        {
            GetModuleFileNameA((HINSTANCE) moduleBase, modulePath, MAX_PATH);
        }

        redisLog(REDIS_WARNING | REDIS_LOG_RAW, "%s!%s(%s:%d)(0x%08LX, 0x%08LX, 0x%08LX, 0x%08LX)\n",
            &modulePath[GetFilenameStart(modulePath)],
            pSymbol->Name,
            line.FileName,
            line.LineNumber,
            stack.Params[0],
            stack.Params[1],
            stack.Params[2],
            stack.Params[3]
            );

        if (!result) {
            break;
        }
    }
}
#else
void LogStackTrace() {}
#endif

void StackTraceInfo() {
    if (symbolsInitialized) {
        redisLog(REDIS_WARNING, "--- STACK TRACE");
        LogStackTrace();
    }
}

void ServerInfo() {
    redisLog(REDIS_WARNING, "--- INFO OUTPUT");
    // Call antirez routine to log the info output
    redisLogRaw(REDIS_WARNING | REDIS_LOG_RAW, genRedisInfoString("all"));
}

void BugReportEnd(){
    redisLogRaw(REDIS_WARNING,
        "\n=== REDIS BUG REPORT END. Make sure to include from START to END. ===\n\n"
        "       Please report the crash by opening an issue on github:\n\n"
        "           http://github.com/MSOpenTech/redis/issues\n\n"
        "  Suspect RAM error? Use redis-server --test-memory to verify it.\n\n"
        );
}

LONG WINAPI UnhandledExceptiontHandler(PEXCEPTION_POINTERS info) {
    if (!processingException) {
        processingException = true;
        if (info->ExceptionRecord == NULL || info->ExceptionRecord->ExceptionCode == NULL) {
            redisLog(REDIS_WARNING, "Unhandled Exception: code not available");
            return EXCEPTION_CONTINUE_SEARCH;
        }

        const char* exDescription = exceptionDescription(info->ExceptionRecord->ExceptionCode);
        // If it's an application exception don't process it
        if (strcmp(exDescription, "UNKNOWN EXCEPTION") == 0) {
            return EXCEPTION_CONTINUE_SEARCH;
        }

        // Call antirez routine to log the start of the bug report (for asserts in antirez code, the start has already been logged)
        bugReportStart();
        redisLog(REDIS_WARNING, "--- %s", exDescription);
        StackTraceInfo();
        ServerInfo();
        BugReportEnd();
        processingException = false;
    }
    return EXCEPTION_CONTINUE_SEARCH;
}

/* Handler to trap dlmalloc abort calls */
extern "C" void AbortHandler(int signal_number) {
    bugReportStart();
    redisLog(REDIS_WARNING, "--- ABORT WAS CALLED");
    StackTraceInfo();
    BugReportEnd();
}

void InitSymbols() {
    // Symbols preloading, it's required to print the stacktrace when an OOM exception is raised
    SymSetOptions(SYMOPT_LOAD_LINES | SYMOPT_UNDNAME );

    line.SizeOfStruct = sizeof(IMAGEHLP_LINE64);
    symbolsInitialized = SymInitialize(process, NULL, TRUE);
    if (!symbolsInitialized) {
        DWORD error = GetLastError();
        redisLog(REDIS_WARNING, "Failed to initialize process symbols, error: %d", error);
    }
}

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

#include "Win32_StackTrace.h"
#include "Win32_RedisLog.h"
#include <DbgHelp.h>
#include <signal.h>
#include <stdio.h>

static IMAGEHLP_SYMBOL64* pSymbol = (IMAGEHLP_SYMBOL64*) malloc(sizeof(IMAGEHLP_SYMBOL64) + MAX_PATH*sizeof(TCHAR));
static IMAGEHLP_LINE64 line;
static BOOLEAN processingException = FALSE;
static CHAR modulePath[MAX_PATH];
static BOOL symbolsInitialized = FALSE;

static const char* exceptionDescription(const DWORD& code)
{
    switch (code) {
    case EXCEPTION_ACCESS_VIOLATION:         return "EXCEPTION_ACCESS_VIOLATION";
    case EXCEPTION_ARRAY_BOUNDS_EXCEEDED:    return "EXCEPTION_ARRAY_BOUNDS_EXCEEDED";
    case EXCEPTION_BREAKPOINT:               return "EXCEPTION_BREAKPOINT";
    case EXCEPTION_DATATYPE_MISALIGNMENT:    return "EXCEPTION_DATATYPE_MISALIGNMENT";
    case EXCEPTION_FLT_DENORMAL_OPERAND:     return "EXCEPTION_FLT_DENORMAL_OPERAND";
    case EXCEPTION_FLT_DIVIDE_BY_ZERO:       return "EXCEPTION_FLT_DIVIDE_BY_ZERO";
    case EXCEPTION_FLT_INEXACT_RESULT:       return "EXCEPTION_FLT_INEXACT_RESULT";
    case EXCEPTION_FLT_INVALID_OPERATION:    return "EXCEPTION_FLT_INVALID_OPERATION";
    case EXCEPTION_FLT_OVERFLOW:             return "EXCEPTION_FLT_OVERFLOW";
    case EXCEPTION_FLT_STACK_CHECK:          return "EXCEPTION_FLT_STACK_CHECK";
    case EXCEPTION_FLT_UNDERFLOW:            return "EXCEPTION_FLT_UNDERFLOW";
    case EXCEPTION_ILLEGAL_INSTRUCTION:      return "EXCEPTION_ILLEGAL_INSTRUCTION";
    case EXCEPTION_IN_PAGE_ERROR:            return "EXCEPTION_IN_PAGE_ERROR";
    case EXCEPTION_INT_DIVIDE_BY_ZERO:       return "EXCEPTION_INT_DIVIDE_BY_ZERO";
    case EXCEPTION_INT_OVERFLOW:             return "EXCEPTION_INT_OVERFLOW";
    case EXCEPTION_INVALID_DISPOSITION:      return "EXCEPTION_INVALID_DISPOSITION";
    case EXCEPTION_NONCONTINUABLE_EXCEPTION: return "EXCEPTION_NONCONTINUABLE_EXCEPTION";
    case EXCEPTION_PRIV_INSTRUCTION:         return "EXCEPTION_PRIV_INSTRUCTION";
    case EXCEPTION_SINGLE_STEP:              return "EXCEPTION_SINGLE_STEP";
    case EXCEPTION_STACK_OVERFLOW:           return "EXCEPTION_STACK_OVERFLOW";
    default: return "UNKNOWN EXCEPTION";
    }
}

/* Returns the index of the last backslash in the file path */
int GetFilenameStart(CHAR* path) {
    int pos = 0;
    int found = 0;
    if (path != NULL) {
        while (path[pos] != '\0' && pos < MAX_PATH) {
            if (path[pos] == '\\') {
                found = pos + 1;
            }
            ++pos;
        }
    }

    return found;
}

#ifdef _WIN64
void LogStackTrace() {
    BOOL            result;
    HANDLE          thread;
    HANDLE          process;
    CONTEXT         context;
    STACKFRAME64    stack;
    ULONG           frame;
    DWORD64         dw64Displacement;
    DWORD           dwDisplacement;

    memset(&stack, 0, sizeof(STACKFRAME64));
    memset(pSymbol, '\0', sizeof(*pSymbol) + MAX_PATH);
    memset(&modulePath[0], '\0', sizeof(modulePath));
    line.LineNumber = 0;

    RtlCaptureContext(&context);
    process = GetCurrentProcess();
    thread = GetCurrentThread();
    dw64Displacement = 0;
    stack.AddrPC.Offset = context.Rip;
    stack.AddrPC.Mode = AddrModeFlat;
    stack.AddrStack.Offset = context.Rsp;
    stack.AddrStack.Mode = AddrModeFlat;
    stack.AddrFrame.Offset = context.Rbp;
    stack.AddrFrame.Mode = AddrModeFlat;

    for (frame = 0;; frame++){
        result = StackWalk64(
            IMAGE_FILE_MACHINE_AMD64,
            process,
            thread,
            &stack,
            &context,
            NULL,
            SymFunctionTableAccess64,
            SymGetModuleBase64,
            NULL
            );

        pSymbol->MaxNameLength = MAX_PATH;
        pSymbol->SizeOfStruct = sizeof(IMAGEHLP_SYMBOL64);

        SymGetSymFromAddr64(process, stack.AddrPC.Offset, &dw64Displacement, pSymbol);
        SymGetLineFromAddr64(process, stack.AddrPC.Offset, &dwDisplacement, &line);

        DWORD64 moduleBase = SymGetModuleBase64(process, stack.AddrPC.Offset);
        if (moduleBase)
        {
            GetModuleFileNameA((HINSTANCE) moduleBase, modulePath, MAX_PATH);
        }

        redisLog(REDIS_WARNING | REDIS_LOG_RAW, "%s!%s(%s:%d)(0x%08LX, 0x%08LX, 0x%08LX, 0x%08LX)\n",
            &modulePath[GetFilenameStart(modulePath)],
            pSymbol->Name,
            line.FileName,
            line.LineNumber,
            stack.Params[0],
            stack.Params[1],
            stack.Params[2],
            stack.Params[3]
            );

        if (!result) {
            break;
        }
    }
}
#else
void LogStackTrace() {}
#endif

void StackTraceInfo() {
    if (symbolsInitialized) {
        redisLog(REDIS_WARNING, "--- STACK TRACE");
        LogStackTrace();
    }
}

void ServerInfo() {
    redisLog(REDIS_WARNING, "--- INFO OUTPUT");
    // Call antirez routine to log the info output
    redisLogRaw(REDIS_WARNING | REDIS_LOG_RAW, genRedisInfoString("all"));
}

void BugReportEnd(){
    redisLogRaw(REDIS_WARNING,
        "\n=== REDIS BUG REPORT END. Make sure to include from START to END. ===\n\n"
        "       Please report the crash by opening an issue on github:\n\n"
        "           http://github.com/MSOpenTech/redis/issues\n\n"
        "  Suspect RAM error? Use redis-server --test-memory to verify it.\n\n"
        );
}

LONG WINAPI UnhandledExceptiontHandler(PEXCEPTION_POINTERS info) {
    if (!processingException) {
        const char* exDescription = "Exception code not available";
        processingException = true;
        if (info->ExceptionRecord != NULL && info->ExceptionRecord->ExceptionCode != NULL) {
            exDescription = exceptionDescription(info->ExceptionRecord->ExceptionCode);
            // If it's an application exception don't process it, here we don't want to catch
            // exceptions like the one thrown by the code that processes the command arguments
            if (strcmp(exDescription, "UNKNOWN EXCEPTION") == 0) {
                return EXCEPTION_CONTINUE_SEARCH;
            }
        }

        // Call antirez routine to log the start of the bug report
        bugReportStart();
        redisLog(REDIS_WARNING, "--- %s", exDescription);
        StackTraceInfo();
        ServerInfo();
        BugReportEnd();
        processingException = false;
    }
    return EXCEPTION_CONTINUE_SEARCH;
}

/* Handler to trap abort() calls */
extern "C" void AbortHandler(int signal_number) {
    bugReportStart();
    redisLog(REDIS_WARNING, "--- ABORT");
    StackTraceInfo();
    BugReportEnd();
}

void InitSymbols() {
    // Preload symbols so they will be available in case of out-of-memory exception
    SymSetOptions(SYMOPT_LOAD_LINES | SYMOPT_UNDNAME);
    line.SizeOfStruct = sizeof(IMAGEHLP_LINE64);
    HANDLE process = GetCurrentProcess();
    symbolsInitialized = SymInitialize(process, NULL, TRUE);
    if (!symbolsInitialized) {
        DWORD error = GetLastError();
        redisLog(REDIS_WARNING, "Failed to initialize process symbols, error: %d", error);
    }
}

void StackTraceInit(void) {
    InitSymbols();
    // Global handler for unhandled exceptions
    SetUnhandledExceptionFilter(UnhandledExceptiontHandler);
    // Handler for abort()
    signal(SIGABRT, &AbortHandler);
}
<|endoftext|>


<commit_before>/**
 *   C++ Examples - a collection of C++ examples intended to serve as a tutorial
 *   Copyright (C) 2011 Alejandro Cabrera
 *
 *   This program is free software: you can redistribute it and/or modify
 *   it under the terms of the GNU General Public License as published by
 *   the Free Software Foundation, 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 General Public License for more details.
 *
 *   You should have received a copy of the GNU General Public License
 *   along with this program.  If not, see <http://www.gnu.org/licenses/>.
 **/
#include <iostream>

struct Base {
  Base() {
    cout << "Base\n";
  }

  void f(const char x) {
    cout << "Base::f()\n";
  }
};

struct Derived : Base {
  Derived() {
    cout << "Derived\n";
  }

  using B::f;
  void f(const int x) {
    cout << "Derived::f\n";
  }
};

int main()
{
  Base b;
  Derived d;

  b.f(1);
  d.f(2);

  return 0;
}
<commit_msg>Fixed compile error in inheriting_constructor.<commit_after>/**
 *   C++ Examples - a collection of C++ examples intended to serve as a tutorial
 *   Copyright (C) 2011 Alejandro Cabrera
 *
 *   This program is free software: you can redistribute it and/or modify
 *   it under the terms of the GNU General Public License as published by
 *   the Free Software Foundation, 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 General Public License for more details.
 *
 *   You should have received a copy of the GNU General Public License
 *   along with this program.  If not, see <http://www.gnu.org/licenses/>.
 **/
#include <iostream>
using namespace std;

struct Base {
  Base() {
    cout << "Base\n";
  }

  void f(const char x) {
    cout << "Base::f()\n";
  }
};

struct Derived : Base {
  Derived() {
    cout << "Derived\n";
  }

  using B::f;
  void f(const int x) {
    cout << "Derived::f\n";
  }
};

int main()
{
  Base b;
  Derived d;

  b.f(1);
  d.f(2);

  return 0;
}
<|endoftext|>


<commit_before>/*
 * Algorithm.hpp
 *
 * Copyright (C) 2009-12 by RStudio, Inc.
 *
 * Unless you have received this program directly from RStudio pursuant
 * to the terms of a commercial license agreement with RStudio, then
 * this program is licensed to you under the terms of version 3 of the
 * GNU Affero General Public License. This program is distributed WITHOUT
 * ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT,
 * MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the
 * AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details.
 *
 */

#ifndef CORE_ALGORITHM_HPP
#define CORE_ALGORITHM_HPP

#include <vector>
#include <algorithm>

#include <boost/type_traits.hpp>

#include <core/type_traits/TypeTraits.hpp>

namespace rstudio {
namespace core {
namespace algorithm {

template<typename InputIterator, typename OutputIterator, typename Predicate>
OutputIterator copy_if(InputIterator begin,
                       InputIterator end,
                       OutputIterator destBegin,
                       Predicate p)
{
   while (begin != end)
   {
      if (p(*begin))
        *destBegin++ = *begin;
      ++begin;
   }
   return destBegin;
}

template<typename InputIterator,
         typename OutputIterator,
         typename Predicate,
         typename UnaryOperator>
OutputIterator copy_transformed_if(InputIterator begin,
                                   InputIterator end,
                                   OutputIterator destBegin,
                                   Predicate p,
                                   UnaryOperator op)
{
   while (begin != end)
   {
      if (p(*begin))
        *destBegin++ = op(*begin);
      ++begin;
   }
   return destBegin;
}

namespace detail {

template <typename Container, typename ValueType>
typename boost::enable_if_c< type_traits::has_key_type<Container>::value, bool >::type
contains(const Container& container, const ValueType& value, boost::true_type)
{
   return container.count(value);
}

template <typename Container, typename ValueType>
typename boost::disable_if_c< type_traits::has_key_type<Container>::value, bool >::type
contains(const Container& container, const ValueType& value, boost::false_type)
{
   return std::find(container.begin(), container.end(), value) != container.end();
}

} // namespace detail

template <typename Container, typename ValueType>
bool contains(const Container& container, const ValueType& value)
{
   return detail::contains(
            container,
            value,
            type_traits::has_key_type<Container>());
}

/* Wrappers for the erase-remove idiom */
template <typename Container, typename ValueType>
void discard(Container& container, const ValueType& value)
{
   container.erase(std::remove(container.begin(), container.end(), value), container.end());
}

template <typename Container, typename Predicate>
void discard_if(Container& container, Predicate predicate)
{
   container.erase(std::remove_if(container.begin(), container.end(), predicate), container.end());
}

template <typename Container, typename ValueType>
Container without(Container& container, const ValueType& value)
{
   container.erase(std::remove(container.begin(), container.end(), value), container.end());
}

template <typename Container, typename Predicate>
Container without_if(Container& container, Predicate predicate)
{
   container.erase(std::remove_if(container.begin(), container.end(), predicate), container.end());
}

template <typename T>
std::vector<T> seq(T length)
{
   std::vector<T> result;
   result.reserve(length);
   for (std::size_t i = 0; i < length; ++i)
      result.push_back(i);
   return result;
}

template <typename AssociativeContainer,
          typename KeyType,
          typename MappedType>
bool get(const AssociativeContainer& container,
         const KeyType& key,
         MappedType** ppValue)
{
   if (!container.count(key))
      return false;

   *ppValue = &(const_cast<AssociativeContainer&>(container)[key]);
   return true;
}

} // namespace algorithm
} // namespace core
} // namespace rstudio

#endif // CORE_ALGORITHM_HPP
<commit_msg>insertion wrappers<commit_after>/*
 * Algorithm.hpp
 *
 * Copyright (C) 2009-12 by RStudio, Inc.
 *
 * Unless you have received this program directly from RStudio pursuant
 * to the terms of a commercial license agreement with RStudio, then
 * this program is licensed to you under the terms of version 3 of the
 * GNU Affero General Public License. This program is distributed WITHOUT
 * ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT,
 * MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the
 * AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details.
 *
 */

#ifndef CORE_ALGORITHM_HPP
#define CORE_ALGORITHM_HPP

#include <vector>
#include <algorithm>

#include <boost/type_traits.hpp>

#include <core/type_traits/TypeTraits.hpp>

namespace rstudio {
namespace core {
namespace algorithm {

template<typename InputIterator, typename OutputIterator, typename Predicate>
OutputIterator copy_if(InputIterator begin,
                       InputIterator end,
                       OutputIterator destBegin,
                       Predicate p)
{
   while (begin != end)
   {
      if (p(*begin))
        *destBegin++ = *begin;
      ++begin;
   }
   return destBegin;
}

template<typename InputIterator,
         typename OutputIterator,
         typename Predicate,
         typename UnaryOperator>
OutputIterator copy_transformed_if(InputIterator begin,
                                   InputIterator end,
                                   OutputIterator destBegin,
                                   Predicate p,
                                   UnaryOperator op)
{
   while (begin != end)
   {
      if (p(*begin))
        *destBegin++ = op(*begin);
      ++begin;
   }
   return destBegin;
}

namespace detail {

template <typename Container, typename ValueType>
typename boost::enable_if_c< type_traits::has_key_type<Container>::value, bool >::type
contains(const Container& container, const ValueType& value, boost::true_type)
{
   return container.count(value);
}

template <typename Container, typename ValueType>
typename boost::disable_if_c< type_traits::has_key_type<Container>::value, bool >::type
contains(const Container& container, const ValueType& value, boost::false_type)
{
   return std::find(container.begin(), container.end(), value) != container.end();
}

} // namespace detail

template <typename Container, typename ValueType>
bool contains(const Container& container, const ValueType& value)
{
   return detail::contains(
            container,
            value,
            type_traits::has_key_type<Container>());
}

namespace detail {

template <typename Container, typename ValueType>
typename boost::enable_if_c<type_traits::has_key_type<Container>::value, void>::type
insert(Container& container, const ValueType& value, boost::true_type)
{
   container.insert(value);
}

template <typename Container, typename ValueType>
typename boost::disable_if_c<type_traits::has_key_type<Container>::value, void>::type
insert(Container& container, const ValueType& value, boost::false_type)
{
   container.push_back(value);
}

} // namespace detail

template <typename Container, typename ValueType>
void insert(Container& container, const ValueType& value)
{
   detail::insert(container, value, type_traits::has_key_type<Container>());
}

namespace detail {

template <typename Container, typename Iterator>
typename boost::enable_if_c<type_traits::has_key_type<Container>::value, void>::type
insert(Container& container, Iterator begin, Iterator end, boost::true_type)
{
   container.insert(begin, end);
}

template <typename Container, typename Iterator>
typename boost::disable_if_c<type_traits::has_key_type<Container>::value, void>::type
insert(Container& container, Iterator begin, Iterator end, boost::false_type)
{
   container.insert(container.end(), begin, end);
}

} // namespace detail

template <typename Container, typename Iterator>
void insert(Container& container, Iterator begin, Iterator end)
{
   detail::insert(container, begin, end,
                  type_traits::has_key_type<Container>());
}

/* Wrappers for the erase-remove idiom */
template <typename Container, typename ValueType>
void discard(Container& container, const ValueType& value)
{
   container.erase(std::remove(container.begin(), container.end(), value), container.end());
}

template <typename Container, typename Predicate>
void discard_if(Container& container, Predicate predicate)
{
   container.erase(std::remove_if(container.begin(), container.end(), predicate), container.end());
}

template <typename Container, typename ValueType>
Container without(Container& container, const ValueType& value)
{
   container.erase(std::remove(container.begin(), container.end(), value), container.end());
}

template <typename Container, typename Predicate>
Container without_if(Container& container, Predicate predicate)
{
   container.erase(std::remove_if(container.begin(), container.end(), predicate), container.end());
}

template <typename T>
std::vector<T> seq(T length)
{
   std::vector<T> result;
   result.reserve(length);
   for (std::size_t i = 0; i < length; ++i)
      result.push_back(i);
   return result;
}

template <typename AssociativeContainer,
          typename KeyType,
          typename MappedType>
bool get(const AssociativeContainer& container,
         const KeyType& key,
         MappedType** ppValue)
{
   if (!container.count(key))
      return false;

   *ppValue = &(const_cast<AssociativeContainer&>(container)[key]);
   return true;
}

} // namespace algorithm
} // namespace core
} // namespace rstudio

#endif // CORE_ALGORITHM_HPP
<|endoftext|>


<commit_before>/*
 * RTokenizerTests.cpp
 *
 * Copyright (C) 2009-12 by RStudio, Inc.
 *
 * Unless you have received this program directly from RStudio pursuant
 * to the terms of a commercial license agreement with RStudio, then
 * this program is licensed to you under the terms of version 3 of the
 * GNU Affero General Public License. This program is distributed WITHOUT
 * ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT,
 * MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the
 * AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details.
 *
 */

#define RSTUDIO_ENABLE_DEBUG_MACROS

#include <core/r_util/RTokenizer.hpp>

#include <iostream>

#include <boost/foreach.hpp>

#include <tests/TestThat.hpp>

namespace rstudio {
namespace core {
namespace r_util {

namespace {

class Verifier
{
public:
   Verifier(wchar_t defaultTokenType,
            const std::wstring& prefix,
            const std::wstring& suffix)
      : defaultTokenType_(defaultTokenType),
        prefix_(prefix),
        suffix_(suffix)
   {
   }

   void verify(const std::wstring& value)
   {
      verify(defaultTokenType_, value) ;
   }

   void verify(wchar_t tokenType, const std::wstring& value)
   {

      RTokenizer rt(prefix_ + value + suffix_) ;
      RToken t ;
      while ((t = rt.nextToken()))
      {
         if (t.offset() == prefix_.length())
         {
            if (tokenType != t.type())
            {
               std::wcerr << value << L" : " << t.content() << std::endl;
            }
            expect_true(tokenType == t.type());
            expect_true(value.length() == t.length());
            expect_true(value == t.content());
            return ;
         }
      }

   }

   void verify(const std::deque<std::wstring>& values)
   {
      verify(defaultTokenType_, values);
   }

   void verify(int tokenType, const std::deque<std::wstring>& values)
   {
      BOOST_FOREACH(const std::wstring& value, values)
         verify(tokenType, value);
   }

private:
   const wchar_t defaultTokenType_ ;
   const std::wstring prefix_ ;
   const std::wstring suffix_ ;

};

void testVoid()
{
   RTokenizer rt(L"") ;
   expect_true(!rt.nextToken());
}

void testSimple()
{
   Verifier v(RToken::ERR, L" ", L" ") ;
   v.verify(RToken::LPAREN, L"(") ;
   v.verify(RToken::RPAREN, L")") ;
   v.verify(RToken::LBRACKET, L"[") ;
   v.verify(RToken::RBRACKET, L"]") ;
   v.verify(RToken::LBRACE, L"{") ;
   v.verify(RToken::RBRACE, L"}") ;
   v.verify(RToken::COMMA, L",") ;
   v.verify(RToken::SEMI, L";") ;
}

void testError()
{
   Verifier v(RToken::ERR, L" ", L" ") ;
}

void testComment()
{
   Verifier v(RToken::COMMENT, L" ", L"\n") ;
   v.verify(L"#");
   v.verify(L"# foo #");

   Verifier v2(RToken::COMMENT, L" ", L"\r\n") ;
   v2.verify(L"#");
   v2.verify(L"# foo #");
}

void testNumbers()
{
   Verifier v(RToken::NUMBER, L" ", L" ") ;
   v.verify(L"1");
   v.verify(L"10");
   v.verify(L"0.1");
   v.verify(L".2");
   v.verify(L"1e-7");
   v.verify(L"1.2e+7");
   v.verify(L"2e");
   v.verify(L"3e+");
   v.verify(L"0x");
   v.verify(L"0x0");
   v.verify(L"0xDEADBEEF");
   v.verify(L"0xcafebad");
   v.verify(L"1L");
   v.verify(L"0x10L");
   v.verify(L"1000000L");
   v.verify(L"1e6L");
   v.verify(L"1.1L");
   v.verify(L"1e-3L");
   v.verify(L"2i");
   v.verify(L"4.1i");
   v.verify(L"1e-2i");
}

void testOperators()
{
   Verifier v(RToken::OPER, L" ", L" ") ;
   v.verify(L"+");
   v.verify(L"-");
   v.verify(L"*");
   v.verify(L"/");
   v.verify(L"^");
   v.verify(L">");
   v.verify(L">=");
   v.verify(L"<");
   v.verify(L"<=");
   v.verify(L"==");
   v.verify(L"!=");
   v.verify(L"!");
   v.verify(L"&");
   v.verify(L"|");
   v.verify(L"~");
   v.verify(L"->");
   v.verify(L"<-");
   v.verify(L"$");
   v.verify(L":");
   v.verify(L"=");
}

void testUOperators()
{
   Verifier v(RToken::UOPER, L" ", L" ") ;
   v.verify(L"%%");
   v.verify(L"%test test%");
}

void testStrings()
{
   Verifier v(RToken::STRING, L" ", L" ") ;
   v.verify(L"\"test\"") ;
   v.verify(L"\" '$\t\r\n\\\"\"") ;
   v.verify(L"\"\"") ;
   v.verify(L"''") ;
   v.verify(L"'\"'") ;
   v.verify(L"'\\\"'") ;
   v.verify(L"'\n'") ;
   v.verify(L"'foo bar \\U654'") ;
}

void testIdentifiers()
{
   Verifier v(RToken::ID, L" ", L" ") ;
   v.verify(L".");
   v.verify(L"...");
   v.verify(L"..1");
   v.verify(L"..2");
   v.verify(L"foo");
   v.verify(L"FOO");
   v.verify(L"f1");
   v.verify(L"a_b");
   v.verify(L"ab_");
   v.verify(L"`foo`");
   v.verify(L"`$@!$@#$`");
   v.verify(L"`a\n\"'b`");

   v.verify(L"\x00C1" L"qc1");
   v.verify(L"\x00C1" L"qc1" L"\x00C1");
}

void testWhitespace()
{
   Verifier v(RToken::WHITESPACE, L"a", L"z") ;
   v.verify(L" ");
   v.verify(L"      ");
   v.verify(L"\t\n");
   v.verify(L"\x00A0") ;
   v.verify(L"  \x3000  ") ;
   v.verify(L" \x00A0\t\x3000\r  ") ;
}

} // anonymous namespace

context("RTokenizer")
{
   test_that("We tokenize various strings correctly")
   {
      testVoid();
      testComment();
      testSimple();
      testError();
      testNumbers();
      testOperators();
      testUOperators();
      testStrings();
      testIdentifiers();
      testWhitespace();
   }

   test_that("Comments are tokenized without a trailing newline")
   {
      RTokens rTokens(L"## this is a comment\n1");
      expect_true(rTokens.size() == 3);
      expect_true(rTokens.at(0).isType(RToken::COMMENT));
      expect_true(rTokens.at(1).isType(RToken::WHITESPACE));
      expect_true(rTokens.at(1).contentEquals(L"\n"));
      expect_true(rTokens.at(2).isType(RToken::NUMBER));
   }

   test_that("'**' is properly tokenized as a single operator")
   {
      RTokens rTokens(L"1 ** 2");
      expect_true(rTokens.size() == 5);
      expect_true(rTokens.at(0).isType(RToken::NUMBER));
      expect_true(rTokens.at(1).isType(RToken::WHITESPACE));
      expect_true(rTokens.at(2).isType(RToken::OPER));
      expect_true(rTokens.at(2).contentEquals(L"**"));
   }
}

} // namespace r_util
} // namespace core
} // namespace rstudio

<commit_msg>add some more tokenizer tests for C++ side<commit_after>/*
 * RTokenizerTests.cpp
 *
 * Copyright (C) 2009-12 by RStudio, Inc.
 *
 * Unless you have received this program directly from RStudio pursuant
 * to the terms of a commercial license agreement with RStudio, then
 * this program is licensed to you under the terms of version 3 of the
 * GNU Affero General Public License. This program is distributed WITHOUT
 * ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT,
 * MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the
 * AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details.
 *
 */

#define RSTUDIO_ENABLE_DEBUG_MACROS

#include <core/r_util/RTokenizer.hpp>

#include <iostream>

#include <boost/foreach.hpp>

#include <tests/TestThat.hpp>

namespace rstudio {
namespace core {
namespace r_util {

namespace {

class Verifier
{
public:
   Verifier(wchar_t defaultTokenType,
            const std::wstring& prefix,
            const std::wstring& suffix)
      : defaultTokenType_(defaultTokenType),
        prefix_(prefix),
        suffix_(suffix)
   {
   }

   void verify(const std::wstring& value)
   {
      verify(defaultTokenType_, value) ;
   }

   void verify(wchar_t tokenType, const std::wstring& value)
   {

      RTokenizer rt(prefix_ + value + suffix_) ;
      RToken t ;
      while ((t = rt.nextToken()))
      {
         if (t.offset() == prefix_.length())
         {
            if (tokenType != t.type())
            {
               std::wcerr << value << L" : " << t.content() << std::endl;
            }
            expect_true(tokenType == t.type());
            expect_true(value.length() == t.length());
            expect_true(value == t.content());
            return ;
         }
      }

   }

   void verify(const std::deque<std::wstring>& values)
   {
      verify(defaultTokenType_, values);
   }

   void verify(int tokenType, const std::deque<std::wstring>& values)
   {
      BOOST_FOREACH(const std::wstring& value, values)
         verify(tokenType, value);
   }

private:
   const wchar_t defaultTokenType_ ;
   const std::wstring prefix_ ;
   const std::wstring suffix_ ;

};

void testVoid()
{
   RTokenizer rt(L"") ;
   expect_true(!rt.nextToken());
}

void testSimple()
{
   Verifier v(RToken::ERR, L" ", L" ") ;
   v.verify(RToken::LPAREN, L"(") ;
   v.verify(RToken::RPAREN, L")") ;
   v.verify(RToken::LBRACKET, L"[") ;
   v.verify(RToken::RBRACKET, L"]") ;
   v.verify(RToken::LBRACE, L"{") ;
   v.verify(RToken::RBRACE, L"}") ;
   v.verify(RToken::COMMA, L",") ;
   v.verify(RToken::SEMI, L";") ;
}

void testError()
{
   Verifier v(RToken::ERR, L" ", L" ") ;
}

void testComment()
{
   Verifier v(RToken::COMMENT, L" ", L"\n") ;
   v.verify(L"#");
   v.verify(L"# foo #");

   Verifier v2(RToken::COMMENT, L" ", L"\r\n") ;
   v2.verify(L"#");
   v2.verify(L"# foo #");
}

void testNumbers()
{
   Verifier v(RToken::NUMBER, L" ", L" ") ;
   v.verify(L"1");
   v.verify(L"10");
   v.verify(L"0.1");
   v.verify(L"1.");
   v.verify(L".2");
   v.verify(L"1e-7");
   v.verify(L"1.2e+7");
   v.verify(L"2e");
   v.verify(L"3e+");
   v.verify(L"0x");
   v.verify(L"0x0");
   v.verify(L"0xDEADBEEF");
   v.verify(L"0xcafebad");
   v.verify(L"1L");
   v.verify(L"0x10L");
   v.verify(L"1000000L");
   v.verify(L"1e6L");
   v.verify(L"1.1L");
   v.verify(L"1e-3L");
   v.verify(L"2i");
   v.verify(L"4.1i");
   v.verify(L"1e-2i");
}

void testOperators()
{
   Verifier v(RToken::OPER, L" ", L" ") ;
   v.verify(L"+");
   v.verify(L"-");
   v.verify(L"*");
   v.verify(L"/");
   v.verify(L"^");
   v.verify(L">");
   v.verify(L">=");
   v.verify(L"<");
   v.verify(L"<=");
   v.verify(L"==");
   v.verify(L"!=");
   v.verify(L"!");
   v.verify(L"&");
   v.verify(L"|");
   v.verify(L"~");
   v.verify(L"->");
   v.verify(L"<-");
   v.verify(L"->>");
   v.verify(L"<<-");
   v.verify(L"$");
   v.verify(L":");
   v.verify(L"=");
   v.verify(L":=");
}

void testUOperators()
{
   Verifier v(RToken::UOPER, L" ", L" ") ;
   v.verify(L"%%");
   v.verify(L"%test test%");
}

void testStrings()
{
   Verifier v(RToken::STRING, L" ", L" ") ;
   v.verify(L"\"test\"") ;
   v.verify(L"\" '$\t\r\n\\\"\"") ;
   v.verify(L"\"\"") ;
   v.verify(L"''") ;
   v.verify(L"'\"'") ;
   v.verify(L"'\\\"'") ;
   v.verify(L"'\n'") ;
   v.verify(L"'foo bar \\U654'") ;
}

void testIdentifiers()
{
   Verifier v(RToken::ID, L" ", L" ") ;
   v.verify(L".");
   v.verify(L"...");
   v.verify(L"..1");
   v.verify(L"..2");
   v.verify(L"foo");
   v.verify(L"FOO");
   v.verify(L"f1");
   v.verify(L"a_b");
   v.verify(L"ab_");
   v.verify(L"`foo`");
   v.verify(L"`$@!$@#$`");
   v.verify(L"`a\n\"'b`");

   v.verify(L"\x00C1" L"qc1");
   v.verify(L"\x00C1" L"qc1" L"\x00C1");
}

void testWhitespace()
{
   Verifier v(RToken::WHITESPACE, L"a", L"z") ;
   v.verify(L" ");
   v.verify(L"      ");
   v.verify(L"\t\n");
   v.verify(L"\x00A0") ;
   v.verify(L"  \x3000  ") ;
   v.verify(L" \x00A0\t\x3000\r  ") ;
}

} // anonymous namespace

context("RTokenizer")
{
   test_that("We tokenize various strings correctly")
   {
      testVoid();
      testComment();
      testSimple();
      testError();
      testNumbers();
      testOperators();
      testUOperators();
      testStrings();
      testIdentifiers();
      testWhitespace();
   }

   test_that("Comments are tokenized without a trailing newline")
   {
      RTokens rTokens(L"## this is a comment\n1");
      expect_true(rTokens.size() == 3);
      expect_true(rTokens.at(0).isType(RToken::COMMENT));
      expect_true(rTokens.at(1).isType(RToken::WHITESPACE));
      expect_true(rTokens.at(1).contentEquals(L"\n"));
      expect_true(rTokens.at(2).isType(RToken::NUMBER));
   }

   test_that("'**' is properly tokenized as a single operator")
   {
      RTokens rTokens(L"1 ** 2");
      expect_true(rTokens.size() == 5);
      expect_true(rTokens.at(0).isType(RToken::NUMBER));
      expect_true(rTokens.at(1).isType(RToken::WHITESPACE));
      expect_true(rTokens.at(2).isType(RToken::OPER));
      expect_true(rTokens.at(2).contentEquals(L"**"));
   }
}

} // namespace r_util
} // namespace core
} // namespace rstudio

<|endoftext|>


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

  Program:   Insight Segmentation & Registration Toolkit
  Module:    itkTransformTest.cxx
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

Copyright (c) 2001 Insight Consortium
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

 * Redistributions of source code must retain the above copyright notice,
   this list of conditions and the following disclaimer.

 * Redistributions in binary form must reproduce the above copyright notice,
   this list of conditions and the following disclaimer in the documentation
   and/or other materials provided with the distribution.

 * The name of the Insight Consortium, nor the names of any consortium members,
   nor of any contributors, may be used to endorse or promote products derived
   from this software without specific prior written permission.

  * Modified source versions must be plainly marked as such, and must not be
    misrepresented as being the original software.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER AND CONTRIBUTORS ``AS IS''
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHORS OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

=========================================================================*/

#include <iostream>

#include "itkTransform.h"
#include "itkMatrix.h"

int main()
{

  typedef  itk::Matrix<double,3,3>   MatrixType;
  typedef  itk::Vector<double,3>     VectorType;
  typedef  itk::Point<double,3>      ParametersType;
  typedef  itk::Matrix<double,3,3>   JacobianType;

  typedef  itk::Transform<double,3,3,ParametersType,JacobianType> TransformType;

  TransformType::Pointer transform = TransformType::New();

}
<commit_msg>FIX: return was missing<commit_after>/*=========================================================================

  Program:   Insight Segmentation & Registration Toolkit
  Module:    itkTransformTest.cxx
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

Copyright (c) 2001 Insight Consortium
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

 * Redistributions of source code must retain the above copyright notice,
   this list of conditions and the following disclaimer.

 * Redistributions in binary form must reproduce the above copyright notice,
   this list of conditions and the following disclaimer in the documentation
   and/or other materials provided with the distribution.

 * The name of the Insight Consortium, nor the names of any consortium members,
   nor of any contributors, may be used to endorse or promote products derived
   from this software without specific prior written permission.

  * Modified source versions must be plainly marked as such, and must not be
    misrepresented as being the original software.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER AND CONTRIBUTORS ``AS IS''
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHORS OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

=========================================================================*/

#include <iostream>

#include "itkTransform.h"
#include "itkMatrix.h"

int main()
{

  typedef  itk::Matrix<double,3,3>   MatrixType;
  typedef  itk::Vector<double,3>     VectorType;
  typedef  itk::Point<double,3>      ParametersType;
  typedef  itk::Matrix<double,3,3>   JacobianType;

  typedef  itk::Transform<double,3,3,ParametersType,JacobianType> TransformType;

  TransformType::Pointer transform = TransformType::New();

  return EXIT_SUCCESS

}
<|endoftext|>