<commit_before>// This file is part of the dune-gdt project:
//   http://users.dune-project.org/projects/dune-gdt
// Copyright holders: Felix Schindler
// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)

#ifndef DUNE_STUFF_TEST_MAIN_ENABLE_INFO_LOGGING
# define DUNE_STUFF_TEST_MAIN_ENABLE_INFO_LOGGING 1
#endif

// This one has to come first (includes the config.h)!
#include <dune/stuff/test/main.hxx>

#include <dune/common/exceptions.hh>

#include <tuple>

#if HAVE_ALUGRID
# include <dune/grid/alugrid.hh>
#endif

#include <dune/stuff/common/exceptions.hh>
#include <dune/stuff/common/type_utils.hh>
#include <dune/stuff/common/color.hh>
#include <dune/stuff/common/print.hh>
#include <dune/stuff/common/string.hh>
#include <dune/stuff/common/float_cmp.hh>
#include <dune/stuff/functions/combined.hh>
#include <dune/stuff/la/solver.hh>

#include "elliptic-testcases.hh"
#include "elliptic-cg-discretization.hh"
#include "elliptic-swipdg-discretization.hh"

// +-----------------------------------------------------------------------+
// | Global options. Can be used to disable output or enable slow solvers. |
// +-----------------------------------------------------------------------+

// change this to test all solvers (even really slow ones)
const bool test_all_solvers = false;

// +--------------------------------------------------+
// | 1st we define the test structs that do something |
// +--------------------------------------------------+

struct EllipticDiscretizations
{
  template< class DiscretizationType >
  static void run(const DiscretizationType& discretization, const std::string discretization_id, const bool sec = true)
  {
    try {
      using namespace Dune;
      using namespace Dune::GDT;

      typedef typename DiscretizationType::MatrixType MatrixType;

      auto solution_vector = discretization.create_vector();
      auto tmp_vector = discretization.create_vector();
      Stuff::LA::Solver< MatrixType > linear_solver(discretization.system_matrix());

      // print table header
      const size_t min_first_column_width = std::string("solver option").size();
      size_t first_column_width = min_first_column_width;
      for (auto type : linear_solver.types())
        first_column_width = std::max(first_column_width, type.size());
      std::stringstream header;
      std::stringstream delimiter;
      header    << "   solver type";
      delimiter << "--------------";
      for (size_t ii = 0; ii <= first_column_width - min_first_column_width; ++ii) {
        header << " ";
        delimiter << "-";
      }
      if (sec) {
        header    << "| time (s) ";
        delimiter << "+----------";
      } else {
        header    << "| time (ms) ";
        delimiter << "+-----------";
      }
      header    << "| L^oo error (abs|rel) | thrown exception (see dune/stuff/solver.hh) ";
      delimiter << "+----------------------+---------------------------------------------";

      Dune::Timer timer;
      discretization.assemble();

      DSC_LOG_INFO << Stuff::Common::whitespaceify(header.str(), '=') << std::endl;
      DSC_LOG_INFO << discretization_id << ", polorder " << discretization.polOrder << ", system size "
               << discretization.system_matrix().rows() << "x" << discretization.system_matrix().cols()
               << ", assembly took " << std::setprecision(2) << std::fixed << timer.elapsed() << "s" << std::endl;
      DSC_LOG_INFO << Stuff::Common::whitespaceify(header.str(), '-') << std::endl;
      DSC_LOG_INFO << header.str() << std::endl;
      DSC_LOG_INFO << delimiter.str() << std::endl;

      // loop over all available options
      size_t printed_rows = 0;
      for (auto type : linear_solver.types()) {
        // exclude some solvers that take too long to test
        if (test_all_solvers || !(type == "qr.sparse" || type == "bicgstab.identity"
                                  || type == "bicgstab.diagonal" || type.substr(0, 3) == "cg.")) {
          const Stuff::Common::Configuration options = linear_solver.options(type);
          // print delimiter after every 3rd row
          if (printed_rows == 3) {
            DSC_LOG_INFO << delimiter.str() << std::endl;
            printed_rows = 0;
          }
          // print
          DSC_LOG_INFO << " " << type << std::flush;
          for (size_t ii = 0; ii < first_column_width - type.size(); ++ii)
            DSC_LOG_INFO << " ";
          // solve the system
          timer.reset();
          std::stringstream error_msg;
          bool success = true;
          try {
            linear_solver.apply(discretization.rhs_vector(), solution_vector, options);
          } catch (Stuff::Exceptions::linear_solver_failed_bc_data_did_not_fulfill_requirements&) {
            error_msg << Stuff::Common::colorStringRed("matrix_did_not_fulfill_requirements");
            success = false;
          } catch (Stuff::Exceptions::linear_solver_failed_bc_it_did_not_converge&) {
            error_msg << Stuff::Common::colorStringRed("did_not_converge");
          } catch (Stuff::Exceptions::linear_solver_failed_bc_it_was_not_set_up_correctly&) {
            error_msg << Stuff::Common::colorStringRed("was_not_set_up_correctly");
            success = false;
          } catch (Stuff::Exceptions::linear_solver_failed_bc_the_solution_does_not_solve_the_system&) {
            error_msg << Stuff::Common::colorStringRed("solution_does_not_solve_the_system");
          } catch (Stuff::Exceptions::linear_solver_failed&) {
            error_msg << Stuff::Common::colorStringRed("linear_solver_failed");
            success = false;
          }
          if (sec)
            DSC_LOG_INFO << " | " << std::setw(8) << std::setprecision(2) << std::fixed << timer.elapsed();
          else
            DSC_LOG_INFO << " | " << std::setw(9) << std::setprecision(2) << std::fixed << 1000 * timer.elapsed();
          DSC_LOG_INFO << " | ";
          // test solution
          if (success) {
            discretization.system_matrix().mv(solution_vector, tmp_vector);
            tmp_vector -= discretization.rhs_vector();
            double threshhold = options.get< double >("post_check_solves_system");
            if (options.has_key("precision"))
              threshhold = options.get< double >("precision");
            std::stringstream absolute_error;
            absolute_error << std::setw(9) << std::setprecision(2) << std::scientific << tmp_vector.sup_norm();
            if (tmp_vector.sup_norm() < threshhold)
              DSC_LOG_INFO << Stuff::Common::colorString(Stuff::Common::toString(absolute_error.str()),
                                                      Stuff::Common::Colors::green);
            else if (tmp_vector.sup_norm() < std::exp(0.5 * std::log(threshhold)))
              DSC_LOG_INFO << Stuff::Common::colorString(Stuff::Common::toString(absolute_error.str()),
                                                      Stuff::Common::Colors::brown);
            else
              DSC_LOG_INFO << Stuff::Common::colorStringRed(Stuff::Common::toString(absolute_error.str()));
            DSC_LOG_INFO << " | " << std::setw(8) << std::setprecision(2) << std::scientific
                     << tmp_vector.sup_norm()/discretization.rhs_vector().sup_norm();
          } else
            DSC_LOG_INFO << "                    ";
          DSC_LOG_INFO << " | " << error_msg.str() << std::endl;
          ++printed_rows;
        }
      } // loop over all available options
    } catch (Dune::Stuff::Exceptions::spe10_data_file_missing& ee) {  // <- the SPE10Model1 function needs a data file on disc
      std::cerr << ee.what() << std::endl;
    }
  } // ... run(...)
}; // struct EllipticDiscretizations

template< class TestTuple >
struct SmallEllipticSystems
  : public ::testing::Test
  , EllipticDiscretizations
{
  typedef typename std::tuple_element< 0, TestTuple >::type TestCase;
  typedef typename std::tuple_element< 1, TestTuple >::type MatrixType;
  typedef typename std::tuple_element< 2, TestTuple >::type VectorType;

  typedef typename TestCase::GridViewType GridViewType;
  typedef typename TestCase::GridPartType GridPartType;

  void produces_correct_results() const
  {
    using namespace Dune;

    DSC_LOG_INFO << " test case:   " << Stuff::Common::Typename< TestCase >::value() << std::endl;
    DSC_LOG_INFO << " matrix type: " << Stuff::Common::Typename< MatrixType >::value() << std::endl;
    DSC_LOG_INFO << " vector type: " << Stuff::Common::Typename< VectorType >::value() << std::endl;

    const TestCase test_case;
    const auto grid_view = test_case.level_grid_view(1);
    const auto grid_part = test_case.level_grid_part(1);

    run(EllipticCG::Discretization< GridViewType, 1, MatrixType, VectorType >(grid_view,
                                                                              test_case.boundary_info(),
                                                                              test_case.diffusion(),
                                                                              test_case.force(),
                                                                              test_case.dirichlet(),
                                                                              test_case.neumann()),
        "continuous Galerkin", false);

    run(EllipticSWIPDG::Discretization< GridPartType, 1, MatrixType, VectorType >(grid_part,
                                                                                test_case.boundary_info(),
                                                                                test_case.diffusion(),
                                                                                test_case.force(),
                                                                                test_case.dirichlet(),
                                                                                test_case.neumann()),
        "SWIP discontinuous Galerkin", false);
  } // ... produces_correct_results()
}; // SmallEllipticSystems

template< class TestTuple >
struct DISABLED_LargeEllipticSystems
  : public ::testing::Test
  , EllipticDiscretizations
{
  typedef typename std::tuple_element< 0, TestTuple >::type TestCase;
  typedef typename std::tuple_element< 1, TestTuple >::type MatrixType;
  typedef typename std::tuple_element< 2, TestTuple >::type VectorType;

  typedef typename TestCase::GridViewType GridViewType;
  typedef typename TestCase::GridPartType GridPartType;

  void produces_correct_results() const
  {
    using namespace Dune;

    DSC_LOG_INFO << " test case:   " << Stuff::Common::Typename< TestCase >::value() << std::endl;
    DSC_LOG_INFO << " matrix type: " << Stuff::Common::Typename< MatrixType >::value() << std::endl;
    DSC_LOG_INFO << " vector type: " << Stuff::Common::Typename< VectorType >::value() << std::endl;

    const TestCase test_case;
    const auto grid_view = test_case.reference_grid_view();
    const auto grid_part = test_case.reference_grid_part();

    run(EllipticCG::Discretization< GridViewType, 1, MatrixType, VectorType >(grid_view,
                                                                              test_case.boundary_info(),
                                                                              test_case.diffusion(),
                                                                              test_case.force(),
                                                                              test_case.dirichlet(),
                                                                              test_case.neumann()),
        "continuous Galerkin");

    run(EllipticSWIPDG::Discretization< GridPartType, 2, MatrixType, VectorType >(grid_part,
                                                                                test_case.boundary_info(),
                                                                                test_case.diffusion(),
                                                                                test_case.force(),
                                                                                test_case.dirichlet(),
                                                                                test_case.neumann()),
        "SWIP discontinuous Galerkin");
  } // ... produces_correct_results()
}; // LargeEllipticSystems

// +----------------------------------------------------------------------------+
// | 2nd we define all arguments the above test structs are to be compiled with |
// +----------------------------------------------------------------------------+

#if HAVE_ALUGRID

typedef Dune::ALUGrid< 2, 2, Dune::simplex, Dune::conforming> AluConform2dGridType;

#define ALU_CONFORM_2D_COMMONDENSE_TEST_CASES \
    /*std::tuple< EllipticTestCase::ESV07< AluConform2dGridType >,*/ \
                /*Dune::Stuff::LA::CommonDenseMatrix< double >,*/ \
                /*Dune::Stuff::LA::CommonDenseVector< double > >*/ \
  /*,*/ std::tuple< EllipticTestCase::LocalThermalBlock< AluConform2dGridType >, \
                Dune::Stuff::LA::CommonDenseMatrix< double >, \
                Dune::Stuff::LA::CommonDenseVector< double > > \
  /*, std::tuple< EllipticTestCase::ER07< AluConform2dGridType >,*/ \
                /*Dune::Stuff::LA::CommonDenseMatrix< double >,*/ \
                /*Dune::Stuff::LA::CommonDenseVector< double > >*/ \
  , std::tuple< EllipticTestCase::MixedBoundaryTypes< AluConform2dGridType >, \
                Dune::Stuff::LA::CommonDenseMatrix< double >, \
                Dune::Stuff::LA::CommonDenseVector< double > > \
  /*, std::tuple< EllipticTestCase::Spe10Model1< AluConform2dGridType >,*/ \
                /*Dune::Stuff::LA::CommonDenseMatrix< double >,*/ \
                /*Dune::Stuff::LA::CommonDenseVector< double > >*/

#define ALU_CONFORM_2D_EIGENDENSE_TEST_CASES \
    /*std::tuple< EllipticTestCase::ESV07< AluConform2dGridType >,*/ \
                /*Dune::Stuff::LA::EigenDenseMatrix< double >,*/ \
                /*Dune::Stuff::LA::EigenDenseVector< double > >*/ \
  /*,*/ std::tuple< EllipticTestCase::LocalThermalBlock< AluConform2dGridType >, \
                Dune::Stuff::LA::EigenDenseMatrix< double >, \
                Dune::Stuff::LA::EigenDenseVector< double > > \
  /*, std::tuple< EllipticTestCase::ER07< AluConform2dGridType >,*/ \
                /*Dune::Stuff::LA::EigenDenseMatrix< double >,*/ \
                /*Dune::Stuff::LA::EigenDenseVector< double > >*/ \
  , std::tuple< EllipticTestCase::MixedBoundaryTypes< AluConform2dGridType >, \
                Dune::Stuff::LA::EigenDenseMatrix< double >, \
                Dune::Stuff::LA::EigenDenseVector< double > > \
  /*, std::tuple< EllipticTestCase::Spe10Model1< AluConform2dGridType >,*/ \
                /*Dune::Stuff::LA::EigenDenseMatrix< double >,*/ \
                /*Dune::Stuff::LA::EigenDenseVector< double > >*/

#define ALU_CONFORM_2D_EIGENSPARSE_TEST_CASES \
    std::tuple< EllipticTestCase::ESV07< AluConform2dGridType >, \
                Dune::Stuff::LA::EigenRowMajorSparseMatrix< double >, \
                Dune::Stuff::LA::EigenDenseVector< double > > \
  , std::tuple< EllipticTestCase::LocalThermalBlock< AluConform2dGridType >, \
                Dune::Stuff::LA::EigenRowMajorSparseMatrix< double >, \
                Dune::Stuff::LA::EigenDenseVector< double > > \
  , std::tuple< EllipticTestCase::ER07< AluConform2dGridType >, \
                Dune::Stuff::LA::EigenRowMajorSparseMatrix< double >, \
                Dune::Stuff::LA::EigenDenseVector< double > > \
  , std::tuple< EllipticTestCase::MixedBoundaryTypes< AluConform2dGridType >, \
                Dune::Stuff::LA::EigenRowMajorSparseMatrix< double >, \
                Dune::Stuff::LA::EigenDenseVector< double > > \
  , std::tuple< EllipticTestCase::Spe10Model1< AluConform2dGridType >, \
                Dune::Stuff::LA::EigenRowMajorSparseMatrix< double >, \
                Dune::Stuff::LA::EigenDenseVector< double > >

#define ALU_CONFORM_2D_ISTLSPARSE_TEST_CASES \
    std::tuple< EllipticTestCase::ESV07< AluConform2dGridType >, \
                Dune::Stuff::LA::IstlRowMajorSparseMatrix< double >, \
                Dune::Stuff::LA::IstlDenseVector< double > > \
  , std::tuple< EllipticTestCase::LocalThermalBlock< AluConform2dGridType >, \
                Dune::Stuff::LA::IstlRowMajorSparseMatrix< double >, \
                Dune::Stuff::LA::IstlDenseVector< double > > \
  , std::tuple< EllipticTestCase::ER07< AluConform2dGridType >, \
                Dune::Stuff::LA::IstlRowMajorSparseMatrix< double >, \
                Dune::Stuff::LA::IstlDenseVector< double > > \
  , std::tuple< EllipticTestCase::MixedBoundaryTypes< AluConform2dGridType >, \
                Dune::Stuff::LA::IstlRowMajorSparseMatrix< double >, \
                Dune::Stuff::LA::IstlDenseVector< double > > \
  , std::tuple< EllipticTestCase::Spe10Model1< AluConform2dGridType >, \
                Dune::Stuff::LA::IstlRowMajorSparseMatrix< double >, \
                Dune::Stuff::LA::IstlDenseVector< double > >

#define ISTL_EIGEN_COMPARISON \
    std::tuple< EllipticTestCase::ESV07< AluConform2dGridType >, \
                Dune::Stuff::LA::IstlRowMajorSparseMatrix< double >, \
                Dune::Stuff::LA::IstlDenseVector< double > > \
  , std::tuple< EllipticTestCase::ESV07< AluConform2dGridType >, \
                Dune::Stuff::LA::EigenRowMajorSparseMatrix< double >, \
                Dune::Stuff::LA::EigenDenseVector< double > > \
  , std::tuple< EllipticTestCase::LocalThermalBlock< AluConform2dGridType >, \
                Dune::Stuff::LA::IstlRowMajorSparseMatrix< double >, \
                Dune::Stuff::LA::IstlDenseVector< double > > \
  , std::tuple< EllipticTestCase::LocalThermalBlock< AluConform2dGridType >, \
                Dune::Stuff::LA::EigenRowMajorSparseMatrix< double >, \
                Dune::Stuff::LA::EigenDenseVector< double > > \
  , std::tuple< EllipticTestCase::ER07< AluConform2dGridType >, \
                Dune::Stuff::LA::IstlRowMajorSparseMatrix< double >, \
                Dune::Stuff::LA::IstlDenseVector< double > > \
  , std::tuple< EllipticTestCase::ER07< AluConform2dGridType >, \
                Dune::Stuff::LA::EigenRowMajorSparseMatrix< double >, \
                Dune::Stuff::LA::EigenDenseVector< double > > \
  , std::tuple< EllipticTestCase::MixedBoundaryTypes< AluConform2dGridType >, \
                Dune::Stuff::LA::IstlRowMajorSparseMatrix< double >, \
                Dune::Stuff::LA::IstlDenseVector< double > > \
  , std::tuple< EllipticTestCase::MixedBoundaryTypes< AluConform2dGridType >, \
                Dune::Stuff::LA::EigenRowMajorSparseMatrix< double >, \
                Dune::Stuff::LA::EigenDenseVector< double > > \
  , std::tuple< EllipticTestCase::Spe10Model1< AluConform2dGridType >, \
                Dune::Stuff::LA::IstlRowMajorSparseMatrix< double >, \
                Dune::Stuff::LA::IstlDenseVector< double > > \
  , std::tuple< EllipticTestCase::Spe10Model1< AluConform2dGridType >, \
                Dune::Stuff::LA::EigenRowMajorSparseMatrix< double >, \
                Dune::Stuff::LA::EigenDenseVector< double > >

#endif // HAVE_ALUGRID

typedef testing::Types<
#if HAVE_ALUGRID
                        ALU_CONFORM_2D_COMMONDENSE_TEST_CASES
# if HAVE_EIGEN
                      , ALU_CONFORM_2D_EIGENDENSE_TEST_CASES
                      , ALU_CONFORM_2D_EIGENSPARSE_TEST_CASES
# endif // HAVE_EIGEN
# if HAVE_DUNE_ISTL
                      , ALU_CONFORM_2D_ISTLSPARSE_TEST_CASES
# endif
#endif // HAVE_ALUGRID
                      > Small_TestCases;

typedef testing::Types<
#if HAVE_ALUGRID
                        ALU_CONFORM_2D_ISTLSPARSE_TEST_CASES
# if HAVE_EIGEN
                      , ALU_CONFORM_2D_EIGENSPARSE_TEST_CASES
# endif // HAVE_EIGEN
#endif // HAVE_ALUGRID
                      > Large_TestCases;

//typedef testing::Types< ISTL_EIGEN_COMPARISON
//                      > Large_TestCases;

// +--------------------------------------------------------------------------------------+
// | 3rd we combine the test structs with their appropriate arguments to create the tests |
// +--------------------------------------------------------------------------------------+

TYPED_TEST_CASE(SmallEllipticSystems, Small_TestCases);
TYPED_TEST(SmallEllipticSystems, produces_correct_results) {
  this->produces_correct_results();
}

TYPED_TEST_CASE(DISABLED_LargeEllipticSystems, Large_TestCases);
TYPED_TEST(DISABLED_LargeEllipticSystems, produces_correct_results) {
  this->produces_correct_results();
}

// +--------------------------------------------------------------------------------------+
// | 4th we run all the tests                                                             |
// | (run the resulting executable with '--gtest_catch_exceptions=0' to see an exception) |
// +--------------------------------------------------------------------------------------+
<commit_msg>[test.stuff-la-solver] removed (should be in dune-stuff), closes #26<commit_after><|endoftext|>


<commit_before>// Module:  Log4CPLUS
// File:    filter.cxx
// Created: 5/2003
// Author:  Tad E. Smith
//
//
// Copyright (C) Tad E. Smith  All rights reserved.
//
// This software is published under the terms of the Apache Software
// License version 1.1, a copy of which has been included with this
// distribution in the LICENSE.APL file.
//
// $Log: not supported by cvs2svn $
// Revision 1.1  2003/05/28 17:36:03  tcsmith
// Initial version.
//

#include <log4cplus/spi/filter.h>
#include <log4cplus/helpers/loglog.h>
#include <log4cplus/helpers/stringhelper.h>

using namespace log4cplus;
using namespace log4cplus::spi;
using namespace log4cplus::helpers;

///////////////////////////////////////////////////////////////////////////////
// global methods
///////////////////////////////////////////////////////////////////////////////

FilterResult
log4cplus::spi::checkFilter(const Filter* filter,
                            const InternalLoggingEvent& event)
{
    const Filter* currentFilter = filter;
    while(currentFilter) {
        FilterResult result = currentFilter->decide(event);
        if(result != NEUTRAL) {
            return result;
        }

        currentFilter = currentFilter->next.get();
    }

    return ACCEPT;
}

///////////////////////////////////////////////////////////////////////////////
// Filter implementation
///////////////////////////////////////////////////////////////////////////////

Filter::Filter()
{
}

Filter::~Filter()
{
}

void
Filter::appendFilter(FilterPtr filter)
{
    if(next.get() == 0) {
        next = filter;
    }
    else {
        next->appendFilter(filter);
    }
}

///////////////////////////////////////////////////////////////////////////////
// DenyAllFilter implementation
///////////////////////////////////////////////////////////////////////////////

FilterResult
DenyAllFilter::decide(const InternalLoggingEvent&) const
{
    return DENY;
}

///////////////////////////////////////////////////////////////////////////////
// LogLevelMatchFilter implementation
///////////////////////////////////////////////////////////////////////////////

LogLevelMatchFilter::LogLevelMatchFilter()
{
    init();
}

LogLevelMatchFilter::LogLevelMatchFilter(const Properties& properties)
{
    init();

    tstring tmp = properties.getProperty( LOG4CPLUS_TEXT("AcceptOnMatch") );
    acceptOnMatch = (tolower(tmp) == LOG4CPLUS_TEXT("true"));

    tmp = properties.getProperty( LOG4CPLUS_TEXT("LogLevelToMatch") );
    logLevelToMatch = getLogLevelManager().fromString(tmp);
}

void
LogLevelMatchFilter::init()
{
    acceptOnMatch = true;
    logLevelToMatch = NOT_SET_LOG_LEVEL;
}

FilterResult
LogLevelMatchFilter::decide(const InternalLoggingEvent& event) const
{
    if(logLevelToMatch == NOT_SET_LOG_LEVEL) {
        return NEUTRAL;
    }

    bool matchOccured = (logLevelToMatch == event.ll);

    if(acceptOnMatch) {
        return (matchOccured ? ACCEPT : DENY);
    }
    else {
        return (matchOccured ? DENY : ACCEPT);
    }
}

///////////////////////////////////////////////////////////////////////////////
// LogLevelMatchFilter implementation
///////////////////////////////////////////////////////////////////////////////

LogLevelRangeFilter::LogLevelRangeFilter()
{
    init();
}

LogLevelRangeFilter::LogLevelRangeFilter(const Properties& properties)
{
    init();

    tstring tmp = properties.getProperty( LOG4CPLUS_TEXT("AcceptOnMatch") );
    acceptOnMatch = (tolower(tmp) == LOG4CPLUS_TEXT("true"));

    tmp = properties.getProperty( LOG4CPLUS_TEXT("LogLevelMin") );
    logLevelMin = getLogLevelManager().fromString(tmp);

    tmp = properties.getProperty( LOG4CPLUS_TEXT("LogLevelMax") );
    logLevelMax = getLogLevelManager().fromString(tmp);
}

void
LogLevelRangeFilter::init()
{
    acceptOnMatch = true;
    logLevelMin = NOT_SET_LOG_LEVEL;
    logLevelMax = NOT_SET_LOG_LEVEL;
}

FilterResult
LogLevelRangeFilter::decide(const InternalLoggingEvent& event) const
{
    if((logLevelMin != NOT_SET_LOG_LEVEL) && (event.ll < logLevelMin)) {
        // priority of event is less than minimum
        return DENY;
    }

    if((logLevelMax != NOT_SET_LOG_LEVEL) && (event.ll > logLevelMax)) {
        // priority of event is greater than maximum
        return DENY;
    }

    if(acceptOnMatch) {
        // this filter set up to bypass later filters and always return
        // accept if priority in range
        return ACCEPT;
    }
    else {
        // event is ok for this filter; allow later filters to have a look...
        return NEUTRAL;
    }
}

///////////////////////////////////////////////////////////////////////////////
// StringMatchFilter implementation
///////////////////////////////////////////////////////////////////////////////

StringMatchFilter::StringMatchFilter()
{
    init();
}

StringMatchFilter::StringMatchFilter(const Properties& properties)
{
    init();

    tstring tmp = properties.getProperty( LOG4CPLUS_TEXT("AcceptOnMatch") );
    acceptOnMatch = (tolower(tmp) == LOG4CPLUS_TEXT("true"));

    stringToMatch = properties.getProperty( LOG4CPLUS_TEXT("StringToMatch") );
}

void
StringMatchFilter::init()
{
    acceptOnMatch = true;
}

FilterResult
StringMatchFilter::decide(const InternalLoggingEvent& event) const
{
    if(stringToMatch.length() == 0 || event.message.length() == 0) {
        return NEUTRAL;
    }

    if(event.message.find(stringToMatch) == tstring::npos) {
        return NEUTRAL;
    }
    else {  // we've got a match
        return (acceptOnMatch ? ACCEPT : DENY);
    }
}

<commit_msg>Corrected the LogLevelMatchFilter::decide() implementation.<commit_after>// Module:  Log4CPLUS
// File:    filter.cxx
// Created: 5/2003
// Author:  Tad E. Smith
//
//
// Copyright (C) Tad E. Smith  All rights reserved.
//
// This software is published under the terms of the Apache Software
// License version 1.1, a copy of which has been included with this
// distribution in the LICENSE.APL file.
//
// $Log: not supported by cvs2svn $
// Revision 1.2  2003/06/04 00:13:57  tcsmith
// Corrected some of the filtering implementations.
//
// Revision 1.1  2003/05/28 17:36:03  tcsmith
// Initial version.
//

#include <log4cplus/spi/filter.h>
#include <log4cplus/helpers/loglog.h>
#include <log4cplus/helpers/stringhelper.h>

using namespace log4cplus;
using namespace log4cplus::spi;
using namespace log4cplus::helpers;

///////////////////////////////////////////////////////////////////////////////
// global methods
///////////////////////////////////////////////////////////////////////////////

FilterResult
log4cplus::spi::checkFilter(const Filter* filter,
                            const InternalLoggingEvent& event)
{
    const Filter* currentFilter = filter;
    while(currentFilter) {
        FilterResult result = currentFilter->decide(event);
        if(result != NEUTRAL) {
            return result;
        }

        currentFilter = currentFilter->next.get();
    }

    return ACCEPT;
}

///////////////////////////////////////////////////////////////////////////////
// Filter implementation
///////////////////////////////////////////////////////////////////////////////

Filter::Filter()
{
}

Filter::~Filter()
{
}

void
Filter::appendFilter(FilterPtr filter)
{
    if(next.get() == 0) {
        next = filter;
    }
    else {
        next->appendFilter(filter);
    }
}

///////////////////////////////////////////////////////////////////////////////
// DenyAllFilter implementation
///////////////////////////////////////////////////////////////////////////////

FilterResult
DenyAllFilter::decide(const InternalLoggingEvent&) const
{
    return DENY;
}

///////////////////////////////////////////////////////////////////////////////
// LogLevelMatchFilter implementation
///////////////////////////////////////////////////////////////////////////////

LogLevelMatchFilter::LogLevelMatchFilter()
{
    init();
}

LogLevelMatchFilter::LogLevelMatchFilter(const Properties& properties)
{
    init();

    tstring tmp = properties.getProperty( LOG4CPLUS_TEXT("AcceptOnMatch") );
    acceptOnMatch = (tolower(tmp) == LOG4CPLUS_TEXT("true"));

    tmp = properties.getProperty( LOG4CPLUS_TEXT("LogLevelToMatch") );
    logLevelToMatch = getLogLevelManager().fromString(tmp);
}

void
LogLevelMatchFilter::init()
{
    acceptOnMatch = true;
    logLevelToMatch = NOT_SET_LOG_LEVEL;
}

FilterResult
LogLevelMatchFilter::decide(const InternalLoggingEvent& event) const
{
    if(logLevelToMatch == NOT_SET_LOG_LEVEL) {
        return NEUTRAL;
    }

    bool matchOccured = (logLevelToMatch == event.ll);

    if(matchOccurred) {
        return (acceptOnMatch ? ACCEPT : DENY);
    }
    else {
        return NEUTRAL;
    }
}

///////////////////////////////////////////////////////////////////////////////
// LogLevelRangeFilter implementation
///////////////////////////////////////////////////////////////////////////////

LogLevelRangeFilter::LogLevelRangeFilter()
{
    init();
}

LogLevelRangeFilter::LogLevelRangeFilter(const Properties& properties)
{
    init();

    tstring tmp = properties.getProperty( LOG4CPLUS_TEXT("AcceptOnMatch") );
    acceptOnMatch = (tolower(tmp) == LOG4CPLUS_TEXT("true"));

    tmp = properties.getProperty( LOG4CPLUS_TEXT("LogLevelMin") );
    logLevelMin = getLogLevelManager().fromString(tmp);

    tmp = properties.getProperty( LOG4CPLUS_TEXT("LogLevelMax") );
    logLevelMax = getLogLevelManager().fromString(tmp);
}

void
LogLevelRangeFilter::init()
{
    acceptOnMatch = true;
    logLevelMin = NOT_SET_LOG_LEVEL;
    logLevelMax = NOT_SET_LOG_LEVEL;
}

FilterResult
LogLevelRangeFilter::decide(const InternalLoggingEvent& event) const
{
    if((logLevelMin != NOT_SET_LOG_LEVEL) && (event.ll < logLevelMin)) {
        // priority of event is less than minimum
        return DENY;
    }

    if((logLevelMax != NOT_SET_LOG_LEVEL) && (event.ll > logLevelMax)) {
        // priority of event is greater than maximum
        return DENY;
    }

    if(acceptOnMatch) {
        // this filter set up to bypass later filters and always return
        // accept if priority in range
        return ACCEPT;
    }
    else {
        // event is ok for this filter; allow later filters to have a look...
        return NEUTRAL;
    }
}

///////////////////////////////////////////////////////////////////////////////
// StringMatchFilter implementation
///////////////////////////////////////////////////////////////////////////////

StringMatchFilter::StringMatchFilter()
{
    init();
}

StringMatchFilter::StringMatchFilter(const Properties& properties)
{
    init();

    tstring tmp = properties.getProperty( LOG4CPLUS_TEXT("AcceptOnMatch") );
    acceptOnMatch = (tolower(tmp) == LOG4CPLUS_TEXT("true"));

    stringToMatch = properties.getProperty( LOG4CPLUS_TEXT("StringToMatch") );
}

void
StringMatchFilter::init()
{
    acceptOnMatch = true;
}

FilterResult
StringMatchFilter::decide(const InternalLoggingEvent& event) const
{
    if(stringToMatch.length() == 0 || event.message.length() == 0) {
        return NEUTRAL;
    }

    if(event.message.find(stringToMatch) == tstring::npos) {
        return NEUTRAL;
    }
    else {  // we've got a match
        return (acceptOnMatch ? ACCEPT : DENY);
    }
}

<|endoftext|>


<commit_before><commit_msg>Fix filtering items in thumbnailview when painting.<commit_after><|endoftext|>


<commit_before>/*
    data_access.hpp - support file for writing LV2 plugins in C++

    Copyright (C) 2012 Michael Fisher <mfisher31@gmail.com>

    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, write to the Free Software
    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 01222-1307  USA
 */
/**
    @file data_access.hpp
    C++ convenience header for the LV2 data access extension.
    LV2 C Version Support: 1.6 (2012-04-17)

    This mixin implements the LV2_Extension_Data_Feature.  It provides
    access to LV2_Descriptor::extension_data() for plugin UIs or other
    potentially remote users of a plugin via a data_access() method.
 */

#ifndef LVTK_LV2_DATA_ACCESS_HPP
#define LVTK_LV2_DATA_ACCESS_HPP

#include <lv2/lv2plug.in/ns/ext/data-access/data-access.h>

#include <lvtk/private/types.hpp>

namespace lvtk
{

    /** The Data Access Mixin

        @see The internal struct I for API details
        @headerfile lvtk/data_access.hpp
        @ingroup guimixins
     */
    template<bool Required = true>
    struct DataAccess
    {
        template<class Derived>
        struct I : Extension<Required>
        {
            I() : p_da(NULL) { }

            /** @internal */
            static void
            map_feature_handlers(FeatureHandlerMap& hmap)
            {
                hmap[LV2_DATA_ACCESS_URI] = &I<Derived>::handle_feature;
            }

            /** @internal */
            static void
            handle_feature(LV2UI_Handle instance, FeatureData data)
            {
                Derived* derived = reinterpret_cast<Derived*>(instance);
                I<Derived>* mixin = static_cast<I<Derived>*>(derived);

                mixin->p_da =
                        reinterpret_cast<LV2_Extension_Data_Feature*>(data);
                mixin->m_ok = (mixin->p_da != NULL);
            }

            bool
            check_ok()
            {
                if (!Required)
                    return true;

                if (LVTK_DEBUG)
                {
                    std::clog << "    [DataAccess] Validation "
                            << (this->m_ok ? "succeeded" : "failed")
                            << "." << std::endl;
                }
                return this->m_ok;
            }

            /**
             A UI can call this to get data (of a type specified by some other
             extension) from the plugin.

             This call never is never guaranteed to return anything, UIs should
             degrade gracefully if direct access to the plugin data is not possible
             (in which case this function will return NULL).

             This is for access to large data that can only possibly work if the UI
             and plugin are running in the same process.  For all other things, use
             the normal LV2 UI communication system.

             @param uri The uri string to query
             @return Not NULL on Success
             */
            const void*
            data_access(const char *uri)
            {
                if (NULL != p_da)
                    return p_da->data_access(uri);
                return NULL;
            }

        protected:
            /** @internal Feature Data passed from host */
            LV2_Extension_Data_Feature *p_da;
        };
    };

} /* namespace lvtk */

#endif /* LVTK_LV2_DATA_ACCESS_HPP */
<commit_msg>Housekeeping<commit_after>/*
    data_access.hpp - support file for writing LV2 plugins in C++

    Copyright (C) 2012 Michael Fisher <mfisher31@gmail.com>

    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, write to the Free Software
    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 01222-1307  USA
 */
/**
    @file data_access.hpp
    C++ convenience header for the LV2 data access extension.
    LV2 C Version Support: 1.6 (2012-04-17)

    This mixin implements the LV2_Extension_Data_Feature.  It provides
    access to LV2_Descriptor::extension_data() for plugin UIs or other
    potentially remote users of a plugin via a data_access() method.
 */

#ifndef LVTK_DATA_ACCESS_HPP
#define LVTK_DATA_ACCESS_HPP

#include <lv2/lv2plug.in/ns/ext/data-access/data-access.h>

#include <lvtk/private/types.hpp>

namespace lvtk
{

    /** The Data Access Mixin

        @see The internal struct I for API details
        @headerfile lvtk/data_access.hpp
        @ingroup guimixins
     */
    template<bool Required = true>
    struct DataAccess
    {
        template<class Derived>
        struct I : Extension<Required>
        {
            I() : p_da(NULL) { }

            /** @internal */
            static void
            map_feature_handlers(FeatureHandlerMap& hmap)
            {
                hmap[LV2_DATA_ACCESS_URI] = &I<Derived>::handle_feature;
            }

            /** @internal */
            static void
            handle_feature(LV2UI_Handle instance, FeatureData data)
            {
                Derived* derived = reinterpret_cast<Derived*>(instance);
                I<Derived>* mixin = static_cast<I<Derived>*>(derived);

                mixin->p_da =
                        reinterpret_cast<LV2_Extension_Data_Feature*>(data);
                mixin->m_ok = (mixin->p_da != NULL);
            }

            bool
            check_ok()
            {
                if (!Required)
                    return true;

                if (LVTK_DEBUG)
                {
                    std::clog << "    [DataAccess] Validation "
                            << (this->m_ok ? "succeeded" : "failed")
                            << "." << std::endl;
                }
                return this->m_ok;
            }

            /** A UI can call this to get data (of a type specified by some other
                extension) from the plugin.

                This call never is never guaranteed to return anything, UIs should
                degrade gracefully if direct access to the plugin data is not possible
                (in which case this function will return NULL).

                This is for access to large data that can only possibly work if the UI
                and plugin are running in the same process.  For all other things, use
                the normal LV2 UI communication system.

                @param uri The uri string to query
                @return Not NULL on Success
             */
            const void*
            data_access(const char *uri)
            {
                if (NULL != p_da)
                    return p_da->data_access(uri);
                return NULL;
            }

        protected:
            /** @internal Feature Data passed from host */
            LV2_Extension_Data_Feature *p_da;
        };
    };

} /* namespace lvtk */

#endif /* LVTK_DATA_ACCESS_HPP */
<|endoftext|>


<commit_before>/***************************************************************
 *
 * Copyright (C) 1990-2007, Condor Team, Computer Sciences Department,
 * University of Wisconsin-Madison, WI.
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you
 * may not use this file except in compliance with the License.  You may
 * obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 ***************************************************************/

#include "condor_common.h"
#include "condor_debug.h"
#include "classad_newold.h"

#include "NewClassAdJobLogConsumer.h"

#include <string>

#define WANT_CLASSAD_NAMESPACE
#undef open
#include "classad/classad_distribution.h"

NewClassAdJobLogConsumer::NewClassAdJobLogConsumer() { }

void
NewClassAdJobLogConsumer::Reset()
{
	classad::LocalCollectionQuery query;
	std::string key;

	query.Bind(&m_collection);
	query.Query("root", NULL);
	query.ToFirst();

	if (query.Current(key)) {
		do {
			m_collection.RemoveClassAd(key);
		} while(query.Next(key));
	}
}

bool
NewClassAdJobLogConsumer::NewClassAd(const char *key,
									 const char * /*type*/,
									 const char * /*target*/)
{
	classad::ClassAd* ad;
	bool using_existing_ad = false;

	ad = m_collection.GetClassAd(key);
	if (ad && ad->size() == 0) {
			// This is a cluster ad created in advance so that
			// children could be chained from it.
		using_existing_ad = true;
	} else {
		ad = new classad::ClassAd();
	}

		// Chain this ad to its parent, if any.
	PROC_ID proc = getProcByString(key);
	if(proc.proc >= 0) {
		char cluster_key[PROC_ID_STR_BUFLEN];
			// NOTE: cluster keys start with a 0: e.g. 021.-1
		sprintf(cluster_key,"0%d.-1", proc.cluster);
		classad::ClassAd* cluster_ad =
			m_collection.GetClassAd(cluster_key);
		if (!cluster_ad) {
				// The cluster ad doesn't exist yet.  This is expected.
				// For example, once the job queue is rewritten (i.e.
				// truncated), the order of entries in it is arbitrary.
			cluster_ad = new classad::ClassAd();
			if (!m_collection.AddClassAd(cluster_key, cluster_ad)) {
				dprintf(D_ALWAYS,
						"error processing %s: failed to add '%s' to "
						"ClassAd collection.\n",
						m_reader->GetClassAdLogFileName(), cluster_key);
				return true; // XXX: why is this ok?
			}
		}

		ad->ChainToAd(cluster_ad);
	}

	if (!using_existing_ad) {
		if (!m_collection.AddClassAd(key, ad)) {
			dprintf(D_ALWAYS,
					"error processing %s: failed to add '%s' to "
					"ClassAd collection.\n",
					m_reader->GetClassAdLogFileName(),
					key);
				// XXX: why is this ok?
		}
	}

	return true;
}

bool
NewClassAdJobLogConsumer::DestroyClassAd(const char *key)
{
	m_collection.RemoveClassAd(key);

	return true;
}

bool
NewClassAdJobLogConsumer::SetAttribute(const char *key,
									   const char *name,
									   const char *value)
{
	classad::ClassAd *ad = m_collection.GetClassAd(key);
	if (!ad) {
		dprintf(D_ALWAYS,
				"error reading %s: no such ad in collection: %s\n",
				m_reader->GetClassAdLogFileName(), key);
		return false;
	}
	MyString new_classad_value, err_msg;
	if (!old_classad_value_to_new_classad_value(value,
												new_classad_value,
												&err_msg)) {
		dprintf(D_ALWAYS,
				"error reading %s: failed to convert expression from "
				"old to new ClassAd format: %s\n",
				m_reader->GetClassAdLogFileName(), err_msg.Value());
		return false;
	}

	classad::ClassAdParser ad_parser;

	classad::ExprTree *expr =
		ad_parser.ParseExpression(new_classad_value.Value());
	if (!expr) {
		dprintf(D_ALWAYS,
				"error reading %s: failed to parse expression: %s\n",
				m_reader->GetClassAdLogFileName(), value);
		ASSERT(expr);
		return false;
	}
	ad->Insert(name,expr);

	return true;
}

bool
NewClassAdJobLogConsumer::DeleteAttribute(const char *key,
										  const char *name)
{
	classad::ClassAd *ad = m_collection.GetClassAd(key);
	if (!ad) {
		dprintf(D_ALWAYS,
				"error reading %s: no such ad in collection: %s\n",
				m_reader->GetClassAdLogFileName(), key);
		return false;
	}
	ad->Delete(name);

		// The above will return false if the attribute doesn't exist
		// in the ad.  However, this is expected, because the schedd
		// sometimes will blindly delete attributes that do not exist
		// (e.g. RemoteSlotID).  Therefore, we ignore the return
		// value.

	return true;
}

<commit_msg>Initialize a member in a constructor<commit_after>/***************************************************************
 *
 * Copyright (C) 1990-2007, Condor Team, Computer Sciences Department,
 * University of Wisconsin-Madison, WI.
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you
 * may not use this file except in compliance with the License.  You may
 * obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 ***************************************************************/

#include "condor_common.h"
#include "condor_debug.h"
#include "classad_newold.h"

#include "NewClassAdJobLogConsumer.h"

#include <string>

#define WANT_CLASSAD_NAMESPACE
#undef open
#include "classad/classad_distribution.h"

NewClassAdJobLogConsumer::NewClassAdJobLogConsumer() : m_reader(0) { }

void
NewClassAdJobLogConsumer::Reset()
{
	classad::LocalCollectionQuery query;
	std::string key;

	query.Bind(&m_collection);
	query.Query("root", NULL);
	query.ToFirst();

	if (query.Current(key)) {
		do {
			m_collection.RemoveClassAd(key);
		} while(query.Next(key));
	}
}

bool
NewClassAdJobLogConsumer::NewClassAd(const char *key,
									 const char * /*type*/,
									 const char * /*target*/)
{
	classad::ClassAd* ad;
	bool using_existing_ad = false;

	ad = m_collection.GetClassAd(key);
	if (ad && ad->size() == 0) {
			// This is a cluster ad created in advance so that
			// children could be chained from it.
		using_existing_ad = true;
	} else {
		ad = new classad::ClassAd();
	}

		// Chain this ad to its parent, if any.
	PROC_ID proc = getProcByString(key);
	if(proc.proc >= 0) {
		char cluster_key[PROC_ID_STR_BUFLEN];
			// NOTE: cluster keys start with a 0: e.g. 021.-1
		sprintf(cluster_key,"0%d.-1", proc.cluster);
		classad::ClassAd* cluster_ad =
			m_collection.GetClassAd(cluster_key);
		if (!cluster_ad) {
				// The cluster ad doesn't exist yet.  This is expected.
				// For example, once the job queue is rewritten (i.e.
				// truncated), the order of entries in it is arbitrary.
			cluster_ad = new classad::ClassAd();
			if (!m_collection.AddClassAd(cluster_key, cluster_ad)) {
				dprintf(D_ALWAYS,
						"error processing %s: failed to add '%s' to "
						"ClassAd collection.\n",
						m_reader->GetClassAdLogFileName(), cluster_key);
				return true; // XXX: why is this ok?
			}
		}

		ad->ChainToAd(cluster_ad);
	}

	if (!using_existing_ad) {
		if (!m_collection.AddClassAd(key, ad)) {
			dprintf(D_ALWAYS,
					"error processing %s: failed to add '%s' to "
					"ClassAd collection.\n",
					m_reader->GetClassAdLogFileName(),
					key);
				// XXX: why is this ok?
		}
	}

	return true;
}

bool
NewClassAdJobLogConsumer::DestroyClassAd(const char *key)
{
	m_collection.RemoveClassAd(key);

	return true;
}

bool
NewClassAdJobLogConsumer::SetAttribute(const char *key,
									   const char *name,
									   const char *value)
{
	classad::ClassAd *ad = m_collection.GetClassAd(key);
	if (!ad) {
		dprintf(D_ALWAYS,
				"error reading %s: no such ad in collection: %s\n",
				m_reader->GetClassAdLogFileName(), key);
		return false;
	}
	MyString new_classad_value, err_msg;
	if (!old_classad_value_to_new_classad_value(value,
												new_classad_value,
												&err_msg)) {
		dprintf(D_ALWAYS,
				"error reading %s: failed to convert expression from "
				"old to new ClassAd format: %s\n",
				m_reader->GetClassAdLogFileName(), err_msg.Value());
		return false;
	}

	classad::ClassAdParser ad_parser;

	classad::ExprTree *expr =
		ad_parser.ParseExpression(new_classad_value.Value());
	if (!expr) {
		dprintf(D_ALWAYS,
				"error reading %s: failed to parse expression: %s\n",
				m_reader->GetClassAdLogFileName(), value);
		ASSERT(expr);
		return false;
	}
	ad->Insert(name,expr);

	return true;
}

bool
NewClassAdJobLogConsumer::DeleteAttribute(const char *key,
										  const char *name)
{
	classad::ClassAd *ad = m_collection.GetClassAd(key);
	if (!ad) {
		dprintf(D_ALWAYS,
				"error reading %s: no such ad in collection: %s\n",
				m_reader->GetClassAdLogFileName(), key);
		return false;
	}
	ad->Delete(name);

		// The above will return false if the attribute doesn't exist
		// in the ad.  However, this is expected, because the schedd
		// sometimes will blindly delete attributes that do not exist
		// (e.g. RemoteSlotID).  Therefore, we ignore the return
		// value.

	return true;
}

<|endoftext|>


<commit_before>#include <cstdint>
#include <cstdlib>
#include <iostream>
#include <random>
#include <sstream>
#include <string>
#include <vector>
#include "snarkfront.hpp"

using namespace snarkfront;
using namespace std;

void printUsage(const char* exeName) {
    const string
        SHA = " -b 1|224|256|384|512|512_224|512_256",
        PAIR = " -p BN128|Edwards",
        R = " -r",
        DIG = " -d digest",
        EQ = " -e pattern",
        NEQ = " -n pattern",
        optPAIR = " [-p BN128|Edwards]",
        optR = " [-r]",
        optDIG = " [-d hex_digest]",
        optEQ = " [-e equal_pattern]",
        optNEQ = " [-n not_equal_pattern]";

    cout << "usage: " << exeName << SHA << optPAIR << optR << optDIG << optEQ << optNEQ << endl
         << endl
         << "text from standard input:" << endl
         << "echo \"abc\" | " << exeName << PAIR << SHA << endl
         << endl
         << "pre-image pattern and hash:" << endl
         << "echo \"abc\" | " << exeName << PAIR << SHA << DIG << EQ << NEQ << endl
         << endl
         << "hash only, skip zero knowledge proof:" << endl
         << "echo \"abc\" | " << exeName << SHA << endl
         << endl
         << "random data:" << endl
         << exeName << PAIR << SHA << R << endl;

    exit(EXIT_FAILURE);
}

template <typename ZK_SHA, typename EVAL_SHA>
bool runTest(const bool stdInput,
             const bool hashOnly,
             const string& hashDig,
             const string& eqPattern,
             const string& neqPattern)
{
    DataBufferStream buf;

    if (stdInput) {
        // fill message block(s) from standard input
        cin >> buf;

        ZK_SHA::padMessage(buf);

    } else {
        // fill entire message block with random data
        random_device rd;
        const size_t M = sizeof(typename EVAL_SHA::WordType) / sizeof(uint32_t);
        for (size_t i = 0; i < 16 * M; ++i)
            buf->push32(rd());

        // no padding is not SHA-2 standard (compression function only)
    }

    if (!hashOnly) {
        // print buffer
        HexDumper dump(cout);
        dump.print(buf);
    }

    // compute message digest (adds padding if necessary)
    typename ZK_SHA::DigType zk_digest;
    if (eqPattern.empty() && neqPattern.empty()) {
        // just hash the buffer data
        zk_digest = digest(ZK_SHA(), buf);

    } else {
        // additional constraints on pre-image
        // must expose buffer as variables
        std::size_t idx = 0;

        ZK_SHA hashAlgo;

        auto bufCopy = buf;
        while (! bufCopy.empty()) {
            typename ZK_SHA::MsgType msg;
            bless(msg, bufCopy);
            hashAlgo.msgInput(msg);

            // pre-image buffer variables as octets
            typename ZK_SHA::PreType preimg;
            bless(preimg, msg);

            PrintHex pr(cout, false);

            // constraints on pre-image, if any
            for (std::size_t i = 0; i < preimg.size(); ++i) {
                // equal
                if ((idx < eqPattern.size()) && ('?' != eqPattern[idx])) {
                    assert_true(preimg[i] == eqPattern[idx]);

                    cout << "constrain preimage[" << idx << "] == ";
                    pr.pushOctet(eqPattern[idx]);
                    cout << endl;
                }

                // not equal
                if ((idx < neqPattern.size()) && ('?' != neqPattern[idx])) {
                    assert_true(preimg[i] != neqPattern[idx]);

                    cout << "constrain preimage[" << idx << "] != ";
                    pr.pushOctet(neqPattern[idx]);
                    cout << endl;
                }

                ++idx;
            }
        }

        hashAlgo.computeHash();
        zk_digest = hashAlgo.digest();
    }

    const auto eval_digest = digest(EVAL_SHA(), buf);

    assert(zk_digest.size() == eval_digest.size());

    DataBuffer<PrintHex> hexpr(cout, false);

    // compare message digest values
    bool ok = true;
    for (size_t i = 0; i < zk_digest.size(); ++i) {
        if (zk_digest[i]->value() != eval_digest[i]) {
            ok = false;
            cout << "digest[" << i << "] error zk: ";
            hexpr.push(zk_digest[i]->value());
            cout << " eval: ";
            hexpr.push(eval_digest[i]);
            cout << endl;
        }
    }

    // message digest proof constraint
    if (hashDig.empty()) {
        // hash digest calculated by SHA template
        assert_true(zk_digest == eval_digest);

    } else {
        // hash digest specified as ASCII hex string
        vector<uint8_t> v;
        if (!asciiHexToVector(hashDig, v)) {
            ok = false;

        } else {
            // check that hash digest is correct size
            const size_t N = sizeof(typename EVAL_SHA::DigType);
            if (v.size() != N) {
                ok = false;
                cout << "error: hash digest " << hashDig
                     << " must be for " << N << " octets"
                     << endl;

            } else {
                DataBufferStream digBuf(v);

                typename ZK_SHA::DigType dig;
                bless(dig, digBuf);

                assert_true(zk_digest == dig);
            }
        }
    }

    if (!hashOnly) cout << "digest ";
    cout << asciiHex(eval_digest, !hashOnly) << endl;

    return ok;
}

template <typename PAIRING>
bool runTest(const string& shaBits,
             const bool stdInput,
             const bool hashOnly,
             const string& hashDig,
             const string& eqPattern,
             const string& neqPattern)
{
    reset<PAIRING>();

    bool valueOK = false;
    typedef typename PAIRING::Fr FR;

    if ("1" == shaBits) {
        valueOK = runTest<zk::SHA1<FR>, eval::SHA1>(stdInput, hashOnly,
                                                    hashDig, eqPattern, neqPattern);
    } else if ("224" == shaBits) {
        valueOK = runTest<zk::SHA224<FR>, eval::SHA224>(stdInput, hashOnly,
                                                        hashDig, eqPattern, neqPattern);
    } else if ("256" == shaBits) {
        valueOK = runTest<zk::SHA256<FR>, eval::SHA256>(stdInput, hashOnly,
                                                        hashDig, eqPattern, neqPattern);
    } else if ("384" == shaBits) {
        valueOK = runTest<zk::SHA384<FR>, eval::SHA384>(stdInput, hashOnly,
                                                        hashDig, eqPattern, neqPattern);
    } else if ("512" == shaBits) {
        valueOK = runTest<zk::SHA512<FR>, eval::SHA512>(stdInput, hashOnly,
                                                        hashDig, eqPattern, neqPattern);
    } else if ("512_224" == shaBits) {
        valueOK = runTest<zk::SHA512_224<FR>, eval::SHA512_224>(stdInput, hashOnly,
                                                                hashDig, eqPattern, neqPattern);
    } else if ("512_256" == shaBits) {
        valueOK = runTest<zk::SHA512_256<FR>, eval::SHA512_256>(stdInput, hashOnly,
                                                                hashDig, eqPattern, neqPattern);
    }

    // special case for hash only, skip zero knowledge proof
    if (hashOnly) return valueOK;

    cout << "variable count " << variable_count<PAIRING>() << endl;

    GenericProgressBar progress1(cerr), progress2(cerr, 50);

    cerr << "generate key pair";
    const auto key = keypair<PAIRING>(progress2);
    cerr << endl;

    const auto in = input<PAIRING>();

    cerr << "generate proof";
    const auto p = proof(key, progress2);
    cerr << endl;

    cerr << "verify proof ";
    const bool proofOK = verify(key, in, p, progress1);
    cerr << endl;

    return valueOK && proofOK;
}

int main(int argc, char *argv[])
{
    Getopt cmdLine(argc, argv, "pbden", "", "r");
    if (!cmdLine || cmdLine.empty()) printUsage(argv[0]);

    auto pairing = cmdLine.getString('p');

    const auto
        shaBits = cmdLine.getString('b'),
        hashDig = cmdLine.getString('d'),
        eqPattern = cmdLine.getString('e'),
        neqPattern = cmdLine.getString('n');

    const auto stdInput = !cmdLine.getFlag('r');

    // special case for hash only, skip zero knowledge proof
    const bool hashOnly = pairing.empty() && validSHA2Name(shaBits) && stdInput;
    if (hashOnly) pairing = "BN128"; // elliptic curve pairing is arbitrary

    if (!validPairingName(pairing) || !validSHA2Name(shaBits))
        printUsage(argv[0]);

    bool result;

    if (pairingBN128(pairing)) {
        // Barreto-Naehrig 128 bits
        init_BN128();
        result = runTest<BN128_PAIRING>(shaBits,
                                        stdInput,
                                        hashOnly,
                                        hashDig,
                                        eqPattern,
                                        neqPattern);

    } else if (pairingEdwards(pairing)) {
        // Edwards 80 bits
        init_Edwards();
        result = runTest<EDWARDS_PAIRING>(shaBits,
                                          stdInput,
                                          hashOnly,
                                          hashDig,
                                          eqPattern,
                                          neqPattern);
    }

    if (!hashOnly) {
        cout << "test " << (result ? "passed" : "failed") << endl;
    }

    exit(EXIT_SUCCESS);
}
<commit_msg>return EXIT_SUCCESS from main()<commit_after>#include <cstdint>
#include <cstdlib>
#include <iostream>
#include <random>
#include <sstream>
#include <string>
#include <vector>
#include "snarkfront.hpp"

using namespace snarkfront;
using namespace std;

void printUsage(const char* exeName) {
    const string
        SHA = " -b 1|224|256|384|512|512_224|512_256",
        PAIR = " -p BN128|Edwards",
        R = " -r",
        DIG = " -d digest",
        EQ = " -e pattern",
        NEQ = " -n pattern",
        optPAIR = " [-p BN128|Edwards]",
        optR = " [-r]",
        optDIG = " [-d hex_digest]",
        optEQ = " [-e equal_pattern]",
        optNEQ = " [-n not_equal_pattern]";

    cout << "usage: " << exeName << SHA << optPAIR << optR << optDIG << optEQ << optNEQ << endl
         << endl
         << "text from standard input:" << endl
         << "echo \"abc\" | " << exeName << PAIR << SHA << endl
         << endl
         << "pre-image pattern and hash:" << endl
         << "echo \"abc\" | " << exeName << PAIR << SHA << DIG << EQ << NEQ << endl
         << endl
         << "hash only, skip zero knowledge proof:" << endl
         << "echo \"abc\" | " << exeName << SHA << endl
         << endl
         << "random data:" << endl
         << exeName << PAIR << SHA << R << endl;

    exit(EXIT_FAILURE);
}

template <typename ZK_SHA, typename EVAL_SHA>
bool runTest(const bool stdInput,
             const bool hashOnly,
             const string& hashDig,
             const string& eqPattern,
             const string& neqPattern)
{
    DataBufferStream buf;

    if (stdInput) {
        // fill message block(s) from standard input
        cin >> buf;

        ZK_SHA::padMessage(buf);

    } else {
        // fill entire message block with random data
        random_device rd;
        const size_t M = sizeof(typename EVAL_SHA::WordType) / sizeof(uint32_t);
        for (size_t i = 0; i < 16 * M; ++i)
            buf->push32(rd());

        // no padding is not SHA-2 standard (compression function only)
    }

    if (!hashOnly) {
        // print buffer
        HexDumper dump(cout);
        dump.print(buf);
    }

    // compute message digest (adds padding if necessary)
    typename ZK_SHA::DigType zk_digest;
    if (eqPattern.empty() && neqPattern.empty()) {
        // just hash the buffer data
        zk_digest = digest(ZK_SHA(), buf);

    } else {
        // additional constraints on pre-image
        // must expose buffer as variables
        std::size_t idx = 0;

        ZK_SHA hashAlgo;

        auto bufCopy = buf;
        while (! bufCopy.empty()) {
            typename ZK_SHA::MsgType msg;
            bless(msg, bufCopy);
            hashAlgo.msgInput(msg);

            // pre-image buffer variables as octets
            typename ZK_SHA::PreType preimg;
            bless(preimg, msg);

            PrintHex pr(cout, false);

            // constraints on pre-image, if any
            for (std::size_t i = 0; i < preimg.size(); ++i) {
                // equal
                if ((idx < eqPattern.size()) && ('?' != eqPattern[idx])) {
                    assert_true(preimg[i] == eqPattern[idx]);

                    cout << "constrain preimage[" << idx << "] == ";
                    pr.pushOctet(eqPattern[idx]);
                    cout << endl;
                }

                // not equal
                if ((idx < neqPattern.size()) && ('?' != neqPattern[idx])) {
                    assert_true(preimg[i] != neqPattern[idx]);

                    cout << "constrain preimage[" << idx << "] != ";
                    pr.pushOctet(neqPattern[idx]);
                    cout << endl;
                }

                ++idx;
            }
        }

        hashAlgo.computeHash();
        zk_digest = hashAlgo.digest();
    }

    const auto eval_digest = digest(EVAL_SHA(), buf);

    assert(zk_digest.size() == eval_digest.size());

    DataBuffer<PrintHex> hexpr(cout, false);

    // compare message digest values
    bool ok = true;
    for (size_t i = 0; i < zk_digest.size(); ++i) {
        if (zk_digest[i]->value() != eval_digest[i]) {
            ok = false;
            cout << "digest[" << i << "] error zk: ";
            hexpr.push(zk_digest[i]->value());
            cout << " eval: ";
            hexpr.push(eval_digest[i]);
            cout << endl;
        }
    }

    // message digest proof constraint
    if (hashDig.empty()) {
        // hash digest calculated by SHA template
        assert_true(zk_digest == eval_digest);

    } else {
        // hash digest specified as ASCII hex string
        vector<uint8_t> v;
        if (!asciiHexToVector(hashDig, v)) {
            ok = false;

        } else {
            // check that hash digest is correct size
            const size_t N = sizeof(typename EVAL_SHA::DigType);
            if (v.size() != N) {
                ok = false;
                cout << "error: hash digest " << hashDig
                     << " must be for " << N << " octets"
                     << endl;

            } else {
                DataBufferStream digBuf(v);

                typename ZK_SHA::DigType dig;
                bless(dig, digBuf);

                assert_true(zk_digest == dig);
            }
        }
    }

    if (!hashOnly) cout << "digest ";
    cout << asciiHex(eval_digest, !hashOnly) << endl;

    return ok;
}

template <typename PAIRING>
bool runTest(const string& shaBits,
             const bool stdInput,
             const bool hashOnly,
             const string& hashDig,
             const string& eqPattern,
             const string& neqPattern)
{
    reset<PAIRING>();

    bool valueOK = false;
    typedef typename PAIRING::Fr FR;

    if ("1" == shaBits) {
        valueOK = runTest<zk::SHA1<FR>, eval::SHA1>(stdInput, hashOnly,
                                                    hashDig, eqPattern, neqPattern);
    } else if ("224" == shaBits) {
        valueOK = runTest<zk::SHA224<FR>, eval::SHA224>(stdInput, hashOnly,
                                                        hashDig, eqPattern, neqPattern);
    } else if ("256" == shaBits) {
        valueOK = runTest<zk::SHA256<FR>, eval::SHA256>(stdInput, hashOnly,
                                                        hashDig, eqPattern, neqPattern);
    } else if ("384" == shaBits) {
        valueOK = runTest<zk::SHA384<FR>, eval::SHA384>(stdInput, hashOnly,
                                                        hashDig, eqPattern, neqPattern);
    } else if ("512" == shaBits) {
        valueOK = runTest<zk::SHA512<FR>, eval::SHA512>(stdInput, hashOnly,
                                                        hashDig, eqPattern, neqPattern);
    } else if ("512_224" == shaBits) {
        valueOK = runTest<zk::SHA512_224<FR>, eval::SHA512_224>(stdInput, hashOnly,
                                                                hashDig, eqPattern, neqPattern);
    } else if ("512_256" == shaBits) {
        valueOK = runTest<zk::SHA512_256<FR>, eval::SHA512_256>(stdInput, hashOnly,
                                                                hashDig, eqPattern, neqPattern);
    }

    // special case for hash only, skip zero knowledge proof
    if (hashOnly) return valueOK;

    cout << "variable count " << variable_count<PAIRING>() << endl;

    GenericProgressBar progress1(cerr), progress2(cerr, 50);

    cerr << "generate key pair";
    const auto key = keypair<PAIRING>(progress2);
    cerr << endl;

    const auto in = input<PAIRING>();

    cerr << "generate proof";
    const auto p = proof(key, progress2);
    cerr << endl;

    cerr << "verify proof ";
    const bool proofOK = verify(key, in, p, progress1);
    cerr << endl;

    return valueOK && proofOK;
}

int main(int argc, char *argv[])
{
    Getopt cmdLine(argc, argv, "pbden", "", "r");
    if (!cmdLine || cmdLine.empty()) printUsage(argv[0]);

    auto pairing = cmdLine.getString('p');

    const auto
        shaBits = cmdLine.getString('b'),
        hashDig = cmdLine.getString('d'),
        eqPattern = cmdLine.getString('e'),
        neqPattern = cmdLine.getString('n');

    const auto stdInput = !cmdLine.getFlag('r');

    // special case for hash only, skip zero knowledge proof
    const bool hashOnly = pairing.empty() && validSHA2Name(shaBits) && stdInput;
    if (hashOnly) pairing = "BN128"; // elliptic curve pairing is arbitrary

    if (!validPairingName(pairing) || !validSHA2Name(shaBits))
        printUsage(argv[0]);

    bool result;

    if (pairingBN128(pairing)) {
        // Barreto-Naehrig 128 bits
        init_BN128();
        result = runTest<BN128_PAIRING>(shaBits,
                                        stdInput,
                                        hashOnly,
                                        hashDig,
                                        eqPattern,
                                        neqPattern);

    } else if (pairingEdwards(pairing)) {
        // Edwards 80 bits
        init_Edwards();
        result = runTest<EDWARDS_PAIRING>(shaBits,
                                          stdInput,
                                          hashOnly,
                                          hashDig,
                                          eqPattern,
                                          neqPattern);
    }

    if (!hashOnly) {
        cout << "test " << (result ? "passed" : "failed") << endl;
    }

    return EXIT_SUCCESS;
}
<|endoftext|>


<commit_before>/**********************************************************************
* File:        ShortCutsDialog.cpp
* Description: Dialog for shorcuts
* Author:      Zdenko Podobny
* Created:     2011-03-21
*
* (C) Copyright 2011-2012, Zdenko Podobny
**
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
**
**    http://www.apache.org/licenses/LICENSE-2.0
**
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*
**********************************************************************/

#include "dialogs/ShortCutsDialog.h"

ShortCutsDialog::ShortCutsDialog(QWidget* parent)
  : QDialog(parent) {
  setupUi(this);
  textEdit -> setHtml(tr(
                        "
Editor shortcuts
"
                        "
F1 — this help
"
                        "Ins — insert symbol below current symbol
"
                        "Del — delete current symbol
"
                        "CTRL + 1 — join current symbol with next symbol"
                        "
"
                        "CTRL + 2 — split current symbol to 2 symbols"
                        "
"
                        "
"
                        "CTRL + B — set symbol as bold
"
                        "CTRL + I — set symbol as italic
"
                        "CTRL + U — set symbol as underlined
"
                        "
"
                        "CTRL + Z — undo last change
"
                        "CTRL + Y — redo last undo
"
                        "
"
                        "CTRL + +/- — zoom image
"
                        "CTRL + * — zoom image to original scale
"
                        "CTRL + . — zoom image to fit whole image in "
                        "current view
"
                        "CTRL + > — zoom image to fit height of "
                        "image in current view"
                        "
"
                        "CTRL + < — zoom image to fit width of image"
                        " in current view
"
                        "CTRL + / — zoom current box to fit in current"
                        " view
"
                        "
"
                        "CTRL + D — direct type mode
"
                        "
"
                        "CTRL + arrows up/down — move symbol up/down in"
                            " table
"
                        "CTRL + G — go to row id…
"
                        "CTRL + M — Move row to row id…
"
                        "CTRL + T — setting dialog
"
                        "
"
                        "CTRL + F — find symbol
"
                        "
"
                        "CTRL + L — show/hide balloon symbols on "
                            "image
"
                        "CTRL + H — show/hide all boxes on image
"
                        "CTRL + R — draw/hide rectangle on image
"
                        "
"
                        "
"
                        "
Mouse tips for image area
"
                        "
CTRL + wheel — zoom in/out
"
                        "CTRL + left button click (on symbol) — "
                            "select/highlight symbol
"
                        "CTRL + left button click and drag — add "
                            "symbols to selections
"
                        "Left button click and drag symbol border — "
                            "change symbol box. Works with single symbol "
                            "selection only.
"
                        "
"));
}
<commit_msg>fine tune help info<commit_after>/**********************************************************************
* File:        ShortCutsDialog.cpp
* Description: Dialog for shorcuts
* Author:      Zdenko Podobny
* Created:     2011-03-21
*
* (C) Copyright 2011-2012, Zdenko Podobny
**
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
**
**    http://www.apache.org/licenses/LICENSE-2.0
**
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*
**********************************************************************/

#include "dialogs/ShortCutsDialog.h"

ShortCutsDialog::ShortCutsDialog(QWidget* parent)
  : QDialog(parent) {
  setupUi(this);
  textEdit -> setHtml(tr(
                        "
Editor shortcuts
"
                        "
F1 — this help
"
                        "Ins — insert symbol below current symbol
"
                        "Del — delete current symbol
"
                        "CTRL + 1 — join current symbol with next symbol"
                        "
"
                        "CTRL + 2 — split current symbol to 2 symbols"
                        "
"
                        "
"
                        "CTRL + B — set symbol as bold
"
                        "CTRL + I — set symbol as italic
"
                        "CTRL + U — set symbol as underlined
"
                        "
"
                        "CTRL + Z — undo last change
"
                        "CTRL + Y — redo last undo
"
                        "
"
                        "CTRL + +/- — zoom image
"
                        "CTRL + * — zoom image to original scale
"
                        "CTRL + . — zoom image to fit whole image in "
                        "current view
"
                        "CTRL + > — zoom image to fit height of "
                        "image in current view"
                        "
"
                        "CTRL + < — zoom image to fit width of image"
                        " in current view
"
                        "CTRL + / — zoom current box to fit in current"
                        " view
"
                        "
"
                        "CTRL + D — direct type mode
"
                        "
"
                        "CTRL + Arrows up/down — move symbol up/down in"
                            " table
"
                        "CTRL + G — go to row id…
"
                        "CTRL + M — Move row to row id…
"
                        "CTRL + T — setting dialog
"
                        "
"
                        "CTRL + F — find symbol
"
                        "
"
                        "CTRL + L — show/hide balloon symbols on "
                            "image
"
                        "CTRL + H — show/hide all boxes on image
"
                        "CTRL + R — draw/hide rectangle on image
"
                        "Arrows in table area — move "
                        "focus/selection
"
                        "Arrows in image area — scroll image
"
                        "
"
                        "
"
                        "
Mouse tips for image area
"
                        "Wheel — scroll image
"
                        "CTRL + Wheel — zoom in/out
"
                        "CTRL + Click (left button) on symbol — "
                            "select/highlight symbol
"
                        "CTRL + Click (left button) and CTRL +"
                            " drag — add symbols to selection
"
                          "Click (Left button) and Drag symbol border — "
                            "change symbol box. It works with single symbol "
                            "selection only.
"
                        "
"));
}
<|endoftext|>


<commit_before>#include <cstdio>
#include <cstdlib>
#include <pthread.h>
//#include "carbon_user.h"
#include <time.h>
#include <sys/timeb.h>

#define MAX            100000000
#define INT_MAX        100000000
#define BILLION 1E9

int _W[8][8] =
{
  {0,   2,      1,      17,     MAX,    MAX,    MAX,    MAX},
  {2,   0,      MAX,    MAX,    2,      6,      MAX,    MAX},
  {1,   MAX,    0,      MAX,    MAX,    MAX,    MAX,    8},
  {17,  MAX,    MAX,    0,      MAX,    2,      1,      9},
  {MAX, 2,      MAX,    MAX,    0,      4,      MAX,    MAX},
  {MAX, 6,      MAX,    2,      4,      0,      5,      MAX},
  {MAX, MAX,    MAX,    1,      MAX,    5,      0,      3},
  {MAX, MAX,    8,      9,      MAX,    MAX,    3,      0}
};

int min = INT_MAX;
int min_index = 0;
pthread_mutex_t lock;

//change the number of locks to approx or greater N
pthread_mutex_t locks[4194304];
int u = -1;

  void init_weights(int N, int DEG, int** W, int** W_index)
  {
          int range = DEG + (N - DEG)/16;

          // Initialize to -1
          for(int i = 0; i < N; i++)
                  for(int j = 0; j < DEG; j++)
                          W_index[i][j]= -1;

          // Populate Index Array
          for(int i = 0; i < N; i++)
          {
                  int last = 0;
                  int min = 0;
                  int max = DEG;
                  for(int j = 0; j < DEG; j++)
                  {
                          if(W_index[i][j] == -1)
                          {
                                  int neighbor = i + j;//rand()%(max);
                                  if(neighbor > last)
                                  {
                                          W_index[i][j] = neighbor;
                                          last = W_index[i][j];
                                  }
                                  else
                                  {
                                          if(last < (N-1))
                                          {
                                                  W_index[i][j] = (last + 1);
                                                  last = W_index[i][j];
                                          }
                                  }
                          }
                          else
                          {
                                  last = W_index[i][j];
                          }
                          if(W_index[i][j]>=N)
                          {
                                  W_index[i][j] = N-1;
                          }
                  }
          }

          // Populate Cost Array
          for(int i = 0; i < N; i++)
          {
                  for(int j = 0; j < DEG; j++)
                  {
                          double v = drand48();
                          /*if(v > 0.8 || W_index[i][j] == -1)
                          {       W[i][j] = MAX;
                                  W_index[i][j] = -1;
                          }

                          else*/ if(W_index[i][j] == i)
                                  W[i][j] = 0;

                          else
                                  W[i][j] = (int) (v*100) + 1;
                          //printf("   %d  ",W_index[i][j]);
                  }
                  //printf("\n");
          }
  }

int initialize_single_source(int* D, int* Q, int source, int N);
void relax(int u, int i, volatile int* D, int** W, int** W_index, int N);
int get_local_min(volatile int* Q, volatile int* D, int start, int stop, int N, int** W_index, int** W, int u);

typedef struct
{
  int*      local_min;
  int*      global_min;
  int*      Q;
  int*      D;
  int**     W;
  int**     W_index;
  int*      d_count;
  int       tid;
  int       P;
  int       N;
  int       DEG;
  pthread_barrier_t* barrier;
} thread_arg_t;

int local_min_buffer[1024];
int global_min_buffer;
int terminate = 0;
int range=1;
int old_range =1;
int difference=0;
int pid=0;
int *test;
int *id;
int P_max=8;
thread_arg_t thread_arg[1024];
pthread_t   thread_handle[1024];

void* do_work(void* args)
{
  volatile thread_arg_t* arg = (thread_arg_t*) args;

  volatile int* count      = arg->d_count;
  volatile int* global_min = arg->global_min;
  volatile int* local_min  = arg->local_min;
  int tid                  = arg->tid;
  int P                    = arg->P;
  volatile int* Q          = arg->Q;
  int* D                   = arg->D;
  int** W                  = arg->W;
  int** W_index            = arg->W_index;
  const int N              = arg->N;
  const int DEG            = arg->DEG;
  int local_count          = N;
  int i, j, po;
	int uu = 0;

  int cntr = 0;
  int i_start =  0;  //tid    * DEG / (arg->P);
  int i_stop  = 0;   //(tid+1) * DEG / (arg->P);
	int start = 0;
	int stop = 1;
	int neighbor=0;

	pthread_barrier_wait(arg->barrier);

while(terminate==0){
  while(terminate==0)
  {
	  for(uu=start;uu<stop;uu++)
		{

		if(test[uu]==0)
			continue;

    for(int i = 0; i < DEG; i++)
    {
			if(uu<N)
        neighbor = W_index[uu][i];

			if(neighbor>=N)
				break;

			pthread_mutex_lock(&locks[neighbor]);

			if(uu>=N)
				terminate=1;

			if((D[W_index[uu][i]] > (D[uu] + W[uu][i])))
				D[W_index[uu][i]] = D[uu] + W[uu][i];
      //Q[uu]=0;

			pthread_mutex_unlock(&locks[neighbor]);
    }
		}

   pthread_barrier_wait(arg->barrier);

	 if(tid==0)
		{
			//range heuristic here
			 old_range=range;
		   range = range*DEG; //change this for range heuristic e.g. range = range+DEG;

			 if(old_range==1)
				 old_range=0;

			 if(range>=N)
				 range=N;

			 difference = range-old_range;
			if(difference<P)
			{
					pid=difference;
		  }
			else
				  pid=P;
			if(pid==0)
				pid=P;
		}

		pthread_barrier_wait(arg->barrier);

		//start = old_range  +  (difference/P)*(tid);            //(tid    * range)  / (arg->P)    + old_range;
		//stop  = old_range  +  (difference/P)*(tid+1);            //((tid+1) * range)  / (arg->P)   + old_range;
	  start = tid * (range/P);
		stop = (tid+1) * (range/P);

		if(stop>range)
		 stop=range;

		//{ pthread_mutex_lock(&lock);
       if(start==N || uu>N-1)
				 terminate=1;
		//} pthread_mutex_unlock(&lock);

    pthread_barrier_wait(arg->barrier);

		//printf("\n TID:%d   start:%d stop:%d terminate:%d",tid,start,stop,terminate);
	}
	pthread_barrier_wait(arg->barrier);
	if(tid==0)
	{
		cntr++;
		if(cntr<P_max)
		{
			terminate=0;
			old_range=1;
			range=1;
			difference=0;
			pid=0;
		}
	}
	start=0;
	stop=1;
	pthread_barrier_wait(arg->barrier);
}

  return NULL;
}

int main(int argc, char** argv)
{
  // Start the simulator
  //CarbonStartSim(argc, argv);

	char filename[100];
	printf("Please Enter The Name Of The File You Would Like To Fetch\n");
	scanf("%s", filename);
	FILE *file0 = fopen(filename,"r");

	int lines_to_check=0;
	char c;
	int number0;
	int number1;
	int starting_node = 0;
	int previous_node = 0;
	int check = 0;
	int inter = -1;
	int N = 4194304; //can be read from file if needed, this is a default upper limit
	int DEG = 8;     //also can be reda from file if needed, upper limit here again

  const int P = atoi(argv[1]);

	if (DEG > N)
  {
                fprintf(stderr, "Degree of graph cannot be grater than number of Vertices\n");
                exit(EXIT_FAILURE);
  }

  int* D;
  int* Q;

	posix_memalign((void**) &D, 64, N * sizeof(int));
  posix_memalign((void**) &Q, 64, N * sizeof(int));
	posix_memalign((void**) &test, 64, N * sizeof(int));
	posix_memalign((void**) &id, 64, N * sizeof(int));
  int d_count = N;
  pthread_barrier_t barrier;

  int** W = (int**) malloc(N*sizeof(int*));
  int** W_index = (int**) malloc(N*sizeof(int*));
  for(int i = 0; i < N; i++)
  {
    int ret = posix_memalign((void**) &W[i], 64, DEG*sizeof(int));
    int re1 = posix_memalign((void**) &W_index[i], 64, DEG*sizeof(int));
    if (ret != 0 || re1!=0)
    {
       fprintf(stderr, "Could not allocate memory\n");
       exit(EXIT_FAILURE);
    }
  }

	for(int i=0;i<N;i++)
	{
		for(int j=0;j<DEG;j++)
		{
			W[i][j] = INT_MAX;
			W_index[i][j] = INT_MAX;
		}
		test[i]=0;
		id[0] = 0;
	}

for(c=getc(file0); c!=EOF; c=getc(file0))
  {
    if(c=='\n')
      lines_to_check++;

    if(lines_to_check>3)
    {
      fscanf(file0, "%d %d", &number0,&number1);
      //printf("\n%d %d",number0,number1);

      test[number0] = 1;
			id[number0] = number0;
      if(number0==previous_node)
			{
			  inter++;
			}
			else
				inter=0;

			W[number0][inter] = inter;
			W_index[number0][inter] = number1;
			previous_node = number0;
    }
  }

  //init_weights(N, DEG, W, W_index);
  /*for(int i = 0;i<N;i++)
  {
        for(int j = 0;j<DEG;j++)
        {
                printf(" %d ",W[i][j]);
        }
        printf("\n");
  }*/

  pthread_barrier_init(&barrier, NULL, P);
  pthread_mutex_init(&lock, NULL);
	for(int i=0; i<N; i++)
		pthread_mutex_init(&locks[i], NULL);

	initialize_single_source(D, Q, 0, N);

  for(int j = 0; j < P; j++) {
    thread_arg[j].local_min  = local_min_buffer;
    thread_arg[j].global_min = &global_min_buffer;
    thread_arg[j].Q          = Q;
    thread_arg[j].D          = D;
    thread_arg[j].W          = W;
    thread_arg[j].W_index    = W_index;
    thread_arg[j].d_count    = &d_count;
    thread_arg[j].tid        = j;
    thread_arg[j].P          = P;
    thread_arg[j].N          = N;
    thread_arg[j].DEG        = DEG;
    thread_arg[j].barrier    = &barrier;
  }

  // Enable performance and energy models
  //CarbonEnableModels();

  //for clock time
  struct timespec requestStart, requestEnd;
  clock_gettime(CLOCK_REALTIME, &requestStart);

  //create threads
  for(int j = 1; j < P; j++) {
    pthread_create(thread_handle+j,
                   NULL,
                   do_work,
                   (void*)&thread_arg[j]);
  }
  do_work((void*) &thread_arg[0]);

	//join threads
  for(int j = 1; j < P; j++) { //mul = mul*2;
    pthread_join(thread_handle[j],NULL);
  }

	//read clock for time
	clock_gettime(CLOCK_REALTIME, &requestEnd);
	  double accum = ( requestEnd.tv_sec - requestStart.tv_sec ) + ( requestEnd.tv_nsec - requestStart.tv_nsec ) / BILLION;
		  printf( "%lf\n", accum );

  // Enable performance and energy models
  //CarbonDisableModels();
  //printf("\ndistance:%d \n",D[N-1]);

	//for distance values check
    for(int i = 0; i < 2097152; i++)
		{
			if(test[i]==1)
        printf(" %d ", D[i]);
    }
    printf("\n");

  // Stop the simulator
  //CarbonStopSim();
  return 0;
}

int initialize_single_source(int*  D,
                             int*  Q,
                             int   source,
                             int   N)
{
  for(int i = 0; i < N+1; i++)
  {
		D[i] = INT_MAX;
    D[i] = i;
    Q[i] = 1;
  }

  D[source] = 0;
  return 0;
}

int get_local_min(volatile int* Q, volatile int* D, int start, int stop, int N, int** W_index, int** W, int u)
{
  int min = INT_MAX;
  int min_index = N;

  for(int i = start; i < stop; i++)
  {
   if(W_index[u][i]==-1 || W[u][i]==INT_MAX)
     continue;
    if(D[i] < min && Q[i])
    {
      min = D[i];
      min_index = W_index[u][i];
    }
  }
  return min_index;
}

void relax(int u, int i, volatile int* D, int** W, int** W_index, int N)
{
  if((D[W_index[u][i]] > (D[u] + W[u][i]) && (W_index[u][i]!=-1 && W_index[u][i]<N && W[u][i]!=INT_MAX)))
    D[W_index[u][i]] = D[u] + W[u][i];
}
<commit_msg>fixed dijk<commit_after>#include <cstdio>
#include <cstdlib>
#include <pthread.h>
//#include "carbon_user.h"
#include <time.h>
#include <sys/timeb.h>

#define MAX            100000000
#define INT_MAX        100000000
#define BILLION 1E9

int _W[8][8] =
{
  {0,   2,      1,      17,     MAX,    MAX,    MAX,    MAX},
  {2,   0,      MAX,    MAX,    2,      6,      MAX,    MAX},
  {1,   MAX,    0,      MAX,    MAX,    MAX,    MAX,    8},
  {17,  MAX,    MAX,    0,      MAX,    2,      1,      9},
  {MAX, 2,      MAX,    MAX,    0,      4,      MAX,    MAX},
  {MAX, 6,      MAX,    2,      4,      0,      5,      MAX},
  {MAX, MAX,    MAX,    1,      MAX,    5,      0,      3},
  {MAX, MAX,    8,      9,      MAX,    MAX,    3,      0}
};

int min = INT_MAX;
int min_index = 0;
pthread_mutex_t lock;

//change the number of locks to approx or greater N
pthread_mutex_t locks[4194304];
int u = -1;

  void init_weights(int N, int DEG, int** W, int** W_index)
  {
          int range = DEG + (N - DEG)/16;

          // Initialize to -1
          for(int i = 0; i < N; i++)
                  for(int j = 0; j < DEG; j++)
                          W_index[i][j]= -1;

          // Populate Index Array
          for(int i = 0; i < N; i++)
          {
                  int last = 0;
                  int min = 0;
                  int max = DEG;
                  for(int j = 0; j < DEG; j++)
                  {
                          if(W_index[i][j] == -1)
                          {
                                  int neighbor = i + j;//rand()%(max);
                                  if(neighbor > last)
                                  {
                                          W_index[i][j] = neighbor;
                                          last = W_index[i][j];
                                  }
                                  else
                                  {
                                          if(last < (N-1))
                                          {
                                                  W_index[i][j] = (last + 1);
                                                  last = W_index[i][j];
                                          }
                                  }
                          }
                          else
                          {
                                  last = W_index[i][j];
                          }
                          if(W_index[i][j]>=N)
                          {
                                  W_index[i][j] = N-1;
                          }
                  }
          }

          // Populate Cost Array
          for(int i = 0; i < N; i++)
          {
                  for(int j = 0; j < DEG; j++)
                  {
                          double v = drand48();
                          /*if(v > 0.8 || W_index[i][j] == -1)
                          {       W[i][j] = MAX;
                                  W_index[i][j] = -1;
                          }

                          else*/ if(W_index[i][j] == i)
                                  W[i][j] = 0;

                          else
                                  W[i][j] = (int) (v*100) + 1;
                          //printf("   %d  ",W_index[i][j]);
                  }
                  //printf("\n");
          }
  }

int initialize_single_source(int* D, int* Q, int source, int N);
void relax(int u, int i, volatile int* D, int** W, int** W_index, int N);
int get_local_min(volatile int* Q, volatile int* D, int start, int stop, int N, int** W_index, int** W, int u);

typedef struct
{
  int*      local_min;
  int*      global_min;
  int*      Q;
  int*      D;
  int**     W;
  int**     W_index;
  int*      d_count;
  int       tid;
  int       P;
  int       N;
  int       DEG;
  pthread_barrier_t* barrier;
} thread_arg_t;

int local_min_buffer[1024];
int global_min_buffer;
int terminate = 0;
int range=1;
int old_range =1;
int difference=0;
int pid=0;
int *test;
int *id;
int P_max=8;
thread_arg_t thread_arg[1024];
pthread_t   thread_handle[1024];

void* do_work(void* args)
{
  volatile thread_arg_t* arg = (thread_arg_t*) args;

  volatile int* count      = arg->d_count;
  volatile int* global_min = arg->global_min;
  volatile int* local_min  = arg->local_min;
  int tid                  = arg->tid;
  int P                    = arg->P;
  volatile int* Q          = arg->Q;
  int* D                   = arg->D;
  int** W                  = arg->W;
  int** W_index            = arg->W_index;
  const int N              = arg->N;
  const int DEG            = arg->DEG;
  int local_count          = N;
  int i, j, po;
	int uu = 0;

  int cntr = 0;
  int i_start =  0;  //tid    * DEG / (arg->P);
  int i_stop  = 0;   //(tid+1) * DEG / (arg->P);
	int start = 0;
	int stop = 1;
	int neighbor=0;

	pthread_barrier_wait(arg->barrier);

while(terminate==0){
  while(terminate==0)
  {
	  for(uu=start;uu<stop;uu++)
		{

		if(test[uu]==0)
			continue;

    for(int i = 0; i < DEG; i++)
    {
			if(uu<N)
        neighbor = W_index[uu][i];

			if(neighbor>=N)
				break;

			pthread_mutex_lock(&locks[neighbor]);

			if(uu>=N)
				terminate=1;

			if((D[W_index[uu][i]] > (D[uu] + W[uu][i])))
				D[W_index[uu][i]] = D[uu] + W[uu][i];
      //Q[uu]=0;

			pthread_mutex_unlock(&locks[neighbor]);
    }
		}

   pthread_barrier_wait(arg->barrier);

	 if(tid==0)
		{
			//range heuristic here
			 old_range=range;
		   range = range*DEG; //change this for range heuristic e.g. range = range+DEG;

			 if(old_range==1)
				 old_range=0;

			 if(range>=N)
				 range=N;

			 difference = range-old_range;
			if(difference<P)
			{
					pid=difference;
		  }
			else
				  pid=P;
			if(pid==0)
				pid=P;
		}

		pthread_barrier_wait(arg->barrier);

		//start = old_range  +  (difference/P)*(tid);            //(tid    * range)  / (arg->P)    + old_range;
		//stop  = old_range  +  (difference/P)*(tid+1);            //((tid+1) * range)  / (arg->P)   + old_range;
	  start = tid * (range/P);
		stop = (tid+1) * (range/P);

		if(stop>range)
		 stop=range;

		//{ pthread_mutex_lock(&lock);
       if(start==N || uu>N-1)
				 terminate=1;
		//} pthread_mutex_unlock(&lock);

    pthread_barrier_wait(arg->barrier);

		//printf("\n TID:%d   start:%d stop:%d terminate:%d",tid,start,stop,terminate);
	}
	pthread_barrier_wait(arg->barrier);
	if(tid==0)
	{
		cntr++;
		if(cntr<P_max)
		{
			terminate=0;
			old_range=1;
			range=1;
			difference=0;
			pid=0;
		}
	}
	start=0;
	stop=1;
	pthread_barrier_wait(arg->barrier);
}

  return NULL;
}

int main(int argc, char** argv)
{
  // Start the simulator
  //CarbonStartSim(argc, argv);

	char filename[100];
	printf("Please Enter The Name Of The File You Would Like To Fetch\n");
	scanf("%s", filename);
	FILE *file0 = fopen(filename,"r");

	int lines_to_check=0;
	char c;
	int number0;
	int number1;
	int starting_node = 0;
	int previous_node = 0;
	int check = 0;
	int inter = -1;
	int N = 4194304; //can be read from file if needed, this is a default upper limit
	int DEG = 8;     //also can be reda from file if needed, upper limit here again

  const int P = atoi(argv[1]);

	if (DEG > N)
  {
                fprintf(stderr, "Degree of graph cannot be grater than number of Vertices\n");
                exit(EXIT_FAILURE);
  }

  int* D;
  int* Q;

	posix_memalign((void**) &D, 64, N * sizeof(int));
  posix_memalign((void**) &Q, 64, N * sizeof(int));
	posix_memalign((void**) &test, 64, N * sizeof(int));
	posix_memalign((void**) &id, 64, N * sizeof(int));
  int d_count = N;
  pthread_barrier_t barrier;

  int** W = (int**) malloc(N*sizeof(int*));
  int** W_index = (int**) malloc(N*sizeof(int*));
  for(int i = 0; i < N; i++)
  {
    int ret = posix_memalign((void**) &W[i], 64, DEG*sizeof(int));
    int re1 = posix_memalign((void**) &W_index[i], 64, DEG*sizeof(int));
    if (ret != 0 || re1!=0)
    {
       fprintf(stderr, "Could not allocate memory\n");
       exit(EXIT_FAILURE);
    }
  }

	for(int i=0;i<N;i++)
	{
		for(int j=0;j<DEG;j++)
		{
			W[i][j] = INT_MAX;
			W_index[i][j] = INT_MAX;
		}
		test[i]=0;
		id[0] = 0;
	}

for(c=getc(file0); c!=EOF; c=getc(file0))
  {
    if(c=='\n')
      lines_to_check++;

    if(lines_to_check>3)
    {
      fscanf(file0, "%d %d", &number0,&number1);
      //printf("\n%d %d",number0,number1);

      test[number0] = 1;
			id[number0] = number0;
      if(number0==previous_node)
			{
			  inter++;
			}
			else
				inter=0;

			W[number0][inter] = inter+1;
			W_index[number0][inter] = number1;
			previous_node = number0;
    }
  }

  //init_weights(N, DEG, W, W_index);
  /*for(int i = 0;i<N;i++)
  {
        for(int j = 0;j<DEG;j++)
        {
                printf(" %d ",W[i][j]);
        }
        printf("\n");
  }*/

  pthread_barrier_init(&barrier, NULL, P);
  pthread_mutex_init(&lock, NULL);
	for(int i=0; i<N; i++)
		pthread_mutex_init(&locks[i], NULL);

	initialize_single_source(D, Q, 0, N);

  for(int j = 0; j < P; j++) {
    thread_arg[j].local_min  = local_min_buffer;
    thread_arg[j].global_min = &global_min_buffer;
    thread_arg[j].Q          = Q;
    thread_arg[j].D          = D;
    thread_arg[j].W          = W;
    thread_arg[j].W_index    = W_index;
    thread_arg[j].d_count    = &d_count;
    thread_arg[j].tid        = j;
    thread_arg[j].P          = P;
    thread_arg[j].N          = N;
    thread_arg[j].DEG        = DEG;
    thread_arg[j].barrier    = &barrier;
  }

  // Enable performance and energy models
  //CarbonEnableModels();

  //for clock time
  struct timespec requestStart, requestEnd;
  clock_gettime(CLOCK_REALTIME, &requestStart);

  //create threads
  for(int j = 1; j < P; j++) {
    pthread_create(thread_handle+j,
                   NULL,
                   do_work,
                   (void*)&thread_arg[j]);
  }
  do_work((void*) &thread_arg[0]);

	//join threads
  for(int j = 1; j < P; j++) { //mul = mul*2;
    pthread_join(thread_handle[j],NULL);
  }

	//read clock for time
	clock_gettime(CLOCK_REALTIME, &requestEnd);
	  double accum = ( requestEnd.tv_sec - requestStart.tv_sec ) + ( requestEnd.tv_nsec - requestStart.tv_nsec ) / BILLION;
		  printf( "%lf\n", accum );

  // Enable performance and energy models
  //CarbonDisableModels();
  //printf("\ndistance:%d \n",D[N-1]);

	//for distance values check
    for(int i = 0; i < 2097152; i++)
		{
			if(D[i]!=INT_MAX)
        printf("\ndistance(%d) = %d ", i, D[i]);
    }
    printf("\n");

  // Stop the simulator
  //CarbonStopSim();
  return 0;
}

int initialize_single_source(int*  D,
                             int*  Q,
                             int   source,
                             int   N)
{
  for(int i = 0; i < N+1; i++)
  {
		D[i] = INT_MAX;
    Q[i] = 1;
  }

  D[source] = 0;
  return 0;
}

int get_local_min(volatile int* Q, volatile int* D, int start, int stop, int N, int** W_index, int** W, int u)
{
  int min = INT_MAX;
  int min_index = N;

  for(int i = start; i < stop; i++)
  {
   if(W_index[u][i]==-1 || W[u][i]==INT_MAX)
     continue;
    if(D[i] < min && Q[i])
    {
      min = D[i];
      min_index = W_index[u][i];
    }
  }
  return min_index;
}

void relax(int u, int i, volatile int* D, int** W, int** W_index, int N)
{
  if((D[W_index[u][i]] > (D[u] + W[u][i]) && (W_index[u][i]!=-1 && W_index[u][i]<N && W[u][i]!=INT_MAX)))
    D[W_index[u][i]] = D[u] + W[u][i];
}
<|endoftext|>