<commit_before>#include <tests/Base.hh>

#include <aleph/containers/PointCloud.hh>

#include <aleph/geometry/BruteForce.hh>
#include <aleph/geometry/VietorisRipsComplex.hh>

#include <aleph/geometry/distances/Euclidean.hh>

#include <aleph/persistentHomology/Calculation.hh>
#include <aleph/persistentHomology/PhiPersistence.hh>

#include <aleph/topology/BarycentricSubdivision.hh>
#include <aleph/topology/Simplex.hh>
#include <aleph/topology/SimplicialComplex.hh>
#include <aleph/topology/Skeleton.hh>
#include <aleph/topology/Spine.hh>

#include <aleph/topology/io/LinesAndPoints.hh>

#include <random>
#include <vector>

#include <cmath>

template <class T> void testDisk()
{
  ALEPH_TEST_BEGIN( "Spine: disk" );

  using DataType   = bool;
  using VertexType = T;

  using Simplex           = aleph::topology::Simplex<DataType, VertexType>;
  using SimplicialComplex = aleph::topology::SimplicialComplex<Simplex>;

  std::vector<Simplex> simplices;

  unsigned n = 7;
  for( unsigned i = 0; i < n; i++ )
  {
    if( i+1 < n )
      simplices.push_back( Simplex( {T(0),T(i+1),T(i+2)} ) );
    else
      simplices.push_back( Simplex( {T(0),T(i+1),T(  1)} ) );
  }

  SimplicialComplex K( simplices.begin(), simplices.end() );

  K.createMissingFaces();
  K.sort();

  auto L = aleph::topology::spine( K );

  ALEPH_ASSERT_THROW( L.size() < K.size() );
  ALEPH_ASSERT_EQUAL( L.size(), 1 );

  ALEPH_TEST_END();
}

template <class T> void testPinchedTorus()
{
  using DataType   = T;
  using PointCloud = aleph::containers::PointCloud<DataType>;

  ALEPH_TEST_BEGIN( "Spine: pinched torus" );

  unsigned n =  40;
  unsigned m =  20;
  PointCloud pc( n*m, 3 );

  auto g = [] ( T x, T y )
  {
    return T(2) + std::sin(x/2) * std::cos(y);
  };

  std::random_device rd;
  std::mt19937 rng( rd() );

  std::normal_distribution<DataType> noise( T(0), T(0.05) );

  unsigned k = 0;
  for( unsigned i = 0; i < n; i++ )
  {
    auto x = T( 2*M_PI / n * i );
    for( unsigned j = 0; j < m; j++ )
    {
      auto y = T( 2*M_PI / m * j );

      auto x0 = g(x,y) * std::cos(x)        + noise( rng );
      auto x1 = g(x,y) * std::sin(x)        + noise( rng );
      auto x2 = std::sin(x/2) * std::sin(y) + noise( rng );

      pc.set(k++, {x0,x1,x2} );
    }
  }

  using Distance          = aleph::geometry::distances::Euclidean<DataType>;
  using NearestNeighbours = aleph::geometry::BruteForce<PointCloud, Distance>;

  auto K
    = aleph::geometry::buildVietorisRipsComplex(
      NearestNeighbours( pc ),
      DataType( 0.640 ),
      2
  );

  std::ofstream out( "/tmp/Pinched_torus.txt" );
  aleph::topology::io::LinesAndPoints lap;
  lap( out, K, pc );

  auto D1 = aleph::calculatePersistenceDiagrams( K );

  ALEPH_ASSERT_EQUAL( D1.size(), 2 );
  ALEPH_ASSERT_EQUAL( D1[0].dimension(), 0 );
  ALEPH_ASSERT_EQUAL( D1[1].dimension(), 1 );
  ALEPH_ASSERT_EQUAL( D1[1].betti(),     1 );

#if 0

  // FIXME: this is still too large to be easily processed by the
  // algorithm...

  auto L  = aleph::topology::spine( K );

  ALEPH_ASSERT_THROW( L.size() < K.size() );

  auto K0 = aleph::topology::Skeleton()(0, K);
  auto K1 = K0;
  auto K2 = K;
  auto D2 = aleph::calculateIntersectionHomology( L, {K0,K1,K2}, aleph::PerversityGM( {0} ) );

  ALEPH_ASSERT_EQUAL( D2.size(), 3 );

#endif

  ALEPH_TEST_END();
}

template <class T> void testS1vS1()
{
  using DataType   = T;
  using PointCloud = aleph::containers::PointCloud<DataType>;

  ALEPH_TEST_BEGIN( "Spine: S^1 v S^1" );

  unsigned n = 50;

  PointCloud pc( 2*n, 2 );

  for( unsigned i = 0; i < n; i++ )
  {
    auto x0 = DataType( std::cos( 2*M_PI / n * i ) );
    auto y0 = DataType( std::sin( 2*M_PI / n * i ) );

    auto x1 = x0 + 2;
    auto y1 = y0;

    pc.set(2*i  , {x0, y0});
    pc.set(2*i+1, {x1, y1});
  }

  using Distance          = aleph::geometry::distances::Euclidean<DataType>;
  using NearestNeighbours = aleph::geometry::BruteForce<PointCloud, Distance>;

  auto K
    = aleph::geometry::buildVietorisRipsComplex(
      NearestNeighbours( pc ),
      DataType( 0.30 ),
      2
  );

  auto D1 = aleph::calculatePersistenceDiagrams( K );

  // Persistent homology -----------------------------------------------
  //
  // This should not be surprising: it is possible to extract the two
  // circles from the data set. They form one connected component.

  ALEPH_ASSERT_EQUAL( D1.size(),     2 );
  ALEPH_ASSERT_EQUAL( D1[0].betti(), 1 );
  ALEPH_ASSERT_EQUAL( D1[1].betti(), 2 );

  // Persistent intersection homology ----------------------------------
  //
  // Regardless of the stratification, it is impossible to detect the
  // singularity in dimension 0.

  auto L  = aleph::topology::BarycentricSubdivision()( K, [] ( std::size_t dimension ) { return dimension == 0 ? 0 : 0.5; } );
  auto K0 = aleph::topology::Skeleton()( 0, K );
  auto D2 = aleph::calculateIntersectionHomology( L, {K0,K}, aleph::Perversity( {-1} ) );

  ALEPH_ASSERT_EQUAL( D2.size(),         3 );
  ALEPH_ASSERT_EQUAL( D2[0].dimension(), 0 );
  ALEPH_ASSERT_EQUAL( D2[0].betti(),     1 );

  // Spine calculation -------------------------------------------------

  auto M = aleph::topology::spine( K );

  {
    auto D = aleph::calculatePersistenceDiagrams( M );

    ALEPH_ASSERT_EQUAL( D.size()    ,     2 );
    ALEPH_ASSERT_EQUAL( D[0].dimension(), 0 );
    ALEPH_ASSERT_EQUAL( D[1].dimension(), 1 );
    ALEPH_ASSERT_EQUAL( D[0].betti(),     1 );
    ALEPH_ASSERT_EQUAL( D[1].betti(),     2 );
  }

  ALEPH_ASSERT_THROW( M.size() < K .size() );
  ALEPH_TEST_END();

  L       = aleph::topology::BarycentricSubdivision()( M, [] ( std::size_t dimension ) { return dimension == 0 ? 0 : 0.5; } );
  K0      = aleph::topology::Skeleton()(0, M);
  auto D3 = aleph::calculateIntersectionHomology( L, {K0,M}, aleph::Perversity( {0} ) );

  ALEPH_ASSERT_EQUAL( D3.size(),         3  );
  ALEPH_ASSERT_EQUAL( D3[0].dimension(), 0  );
  ALEPH_ASSERT_EQUAL( D3[0].betti(),     43 );
}

template <class T> void testTriangle()
{
  using DataType   = bool;
  using VertexType = T;

  using Simplex           = aleph::topology::Simplex<DataType, VertexType>;
  using SimplicialComplex = aleph::topology::SimplicialComplex<Simplex>;

  SimplicialComplex K = {
    {0,1,2},
    {0,1}, {0,2}, {1,2},
    {0}, {1}, {2}
  };

  auto L = aleph::topology::spine( K );

  ALEPH_ASSERT_THROW( L.size() < K.size() );
  ALEPH_ASSERT_EQUAL( L.size(), 1 );
}

int main( int, char** )
{
  testDisk<short>   ();
  testDisk<unsigned>();

  testPinchedTorus<float> ();
  testPinchedTorus<double>();

  testS1vS1<float> ();
  testS1vS1<double>();

  testTriangle<short>   ();
  testTriangle<unsigned>();
}
<commit_msg>Disabled test for 'pinched torus'<commit_after>#include <tests/Base.hh>

#include <aleph/containers/PointCloud.hh>

#include <aleph/geometry/BruteForce.hh>
#include <aleph/geometry/VietorisRipsComplex.hh>

#include <aleph/geometry/distances/Euclidean.hh>

#include <aleph/persistentHomology/Calculation.hh>
#include <aleph/persistentHomology/PhiPersistence.hh>

#include <aleph/topology/BarycentricSubdivision.hh>
#include <aleph/topology/Simplex.hh>
#include <aleph/topology/SimplicialComplex.hh>
#include <aleph/topology/Skeleton.hh>
#include <aleph/topology/Spine.hh>

#include <aleph/topology/io/LinesAndPoints.hh>

#include <random>
#include <vector>

#include <cmath>

template <class T> void testDisk()
{
  ALEPH_TEST_BEGIN( "Spine: disk" );

  using DataType   = bool;
  using VertexType = T;

  using Simplex           = aleph::topology::Simplex<DataType, VertexType>;
  using SimplicialComplex = aleph::topology::SimplicialComplex<Simplex>;

  std::vector<Simplex> simplices;

  unsigned n = 7;
  for( unsigned i = 0; i < n; i++ )
  {
    if( i+1 < n )
      simplices.push_back( Simplex( {T(0),T(i+1),T(i+2)} ) );
    else
      simplices.push_back( Simplex( {T(0),T(i+1),T(  1)} ) );
  }

  SimplicialComplex K( simplices.begin(), simplices.end() );

  K.createMissingFaces();
  K.sort();

  auto L = aleph::topology::spine( K );

  ALEPH_ASSERT_THROW( L.size() < K.size() );
  ALEPH_ASSERT_EQUAL( L.size(), 1 );

  ALEPH_TEST_END();
}

template <class T> void testPinchedTorus()
{
  using DataType   = T;
  using PointCloud = aleph::containers::PointCloud<DataType>;

  ALEPH_TEST_BEGIN( "Spine: pinched torus" );

  unsigned n =  40;
  unsigned m =  20;
  PointCloud pc( n*m, 3 );

  auto g = [] ( T x, T y )
  {
    return T(2) + std::sin(x/2) * std::cos(y);
  };

  std::random_device rd;
  std::mt19937 rng( rd() );

  std::normal_distribution<DataType> noise( T(0), T(0.05) );

  unsigned k = 0;
  for( unsigned i = 0; i < n; i++ )
  {
    auto x = T( 2*M_PI / n * i );
    for( unsigned j = 0; j < m; j++ )
    {
      auto y = T( 2*M_PI / m * j );

      auto x0 = g(x,y) * std::cos(x)        + noise( rng );
      auto x1 = g(x,y) * std::sin(x)        + noise( rng );
      auto x2 = std::sin(x/2) * std::sin(y) + noise( rng );

      pc.set(k++, {x0,x1,x2} );
    }
  }

  using Distance          = aleph::geometry::distances::Euclidean<DataType>;
  using NearestNeighbours = aleph::geometry::BruteForce<PointCloud, Distance>;

  auto K
    = aleph::geometry::buildVietorisRipsComplex(
      NearestNeighbours( pc ),
      DataType( 0.700 ),
      2
  );

  std::ofstream out( "/tmp/Pinched_torus.txt" );
  aleph::topology::io::LinesAndPoints lap;
  lap( out, K, pc );

  auto D1 = aleph::calculatePersistenceDiagrams( K );

  ALEPH_ASSERT_EQUAL( D1.size(), 2 );
  ALEPH_ASSERT_EQUAL( D1[0].dimension(), 0 );
  ALEPH_ASSERT_EQUAL( D1[1].dimension(), 1 );
  ALEPH_ASSERT_EQUAL( D1[1].betti(),     1 );

#if 0

  // FIXME: this is still too large to be easily processed by the
  // algorithm...

  auto L  = aleph::topology::spine( K );

  ALEPH_ASSERT_THROW( L.size() < K.size() );

  auto K0 = aleph::topology::Skeleton()(0, K);
  auto K1 = K0;
  auto K2 = K;
  auto D2 = aleph::calculateIntersectionHomology( L, {K0,K1,K2}, aleph::PerversityGM( {0} ) );

  ALEPH_ASSERT_EQUAL( D2.size(), 3 );

#endif

  ALEPH_TEST_END();
}

template <class T> void testS1vS1()
{
  using DataType   = T;
  using PointCloud = aleph::containers::PointCloud<DataType>;

  ALEPH_TEST_BEGIN( "Spine: S^1 v S^1" );

  unsigned n = 50;

  PointCloud pc( 2*n, 2 );

  for( unsigned i = 0; i < n; i++ )
  {
    auto x0 = DataType( std::cos( 2*M_PI / n * i ) );
    auto y0 = DataType( std::sin( 2*M_PI / n * i ) );

    auto x1 = x0 + 2;
    auto y1 = y0;

    pc.set(2*i  , {x0, y0});
    pc.set(2*i+1, {x1, y1});
  }

  using Distance          = aleph::geometry::distances::Euclidean<DataType>;
  using NearestNeighbours = aleph::geometry::BruteForce<PointCloud, Distance>;

  auto K
    = aleph::geometry::buildVietorisRipsComplex(
      NearestNeighbours( pc ),
      DataType( 0.30 ),
      2
  );

  auto D1 = aleph::calculatePersistenceDiagrams( K );

  // Persistent homology -----------------------------------------------
  //
  // This should not be surprising: it is possible to extract the two
  // circles from the data set. They form one connected component.

  ALEPH_ASSERT_EQUAL( D1.size(),     2 );
  ALEPH_ASSERT_EQUAL( D1[0].betti(), 1 );
  ALEPH_ASSERT_EQUAL( D1[1].betti(), 2 );

  // Persistent intersection homology ----------------------------------
  //
  // Regardless of the stratification, it is impossible to detect the
  // singularity in dimension 0.

  auto L  = aleph::topology::BarycentricSubdivision()( K, [] ( std::size_t dimension ) { return dimension == 0 ? 0 : 0.5; } );
  auto K0 = aleph::topology::Skeleton()( 0, K );
  auto D2 = aleph::calculateIntersectionHomology( L, {K0,K}, aleph::Perversity( {-1} ) );

  ALEPH_ASSERT_EQUAL( D2.size(),         3 );
  ALEPH_ASSERT_EQUAL( D2[0].dimension(), 0 );
  ALEPH_ASSERT_EQUAL( D2[0].betti(),     1 );

  // Spine calculation -------------------------------------------------

  auto M = aleph::topology::spine( K );

  {
    auto D = aleph::calculatePersistenceDiagrams( M );

    ALEPH_ASSERT_EQUAL( D.size()    ,     2 );
    ALEPH_ASSERT_EQUAL( D[0].dimension(), 0 );
    ALEPH_ASSERT_EQUAL( D[1].dimension(), 1 );
    ALEPH_ASSERT_EQUAL( D[0].betti(),     1 );
    ALEPH_ASSERT_EQUAL( D[1].betti(),     2 );
  }

  ALEPH_ASSERT_THROW( M.size() < K .size() );
  ALEPH_TEST_END();

  L       = aleph::topology::BarycentricSubdivision()( M, [] ( std::size_t dimension ) { return dimension == 0 ? 0 : 0.5; } );
  K0      = aleph::topology::Skeleton()(0, M);
  auto D3 = aleph::calculateIntersectionHomology( L, {K0,M}, aleph::Perversity( {0} ) );

  ALEPH_ASSERT_EQUAL( D3.size(),         3  );
  ALEPH_ASSERT_EQUAL( D3[0].dimension(), 0  );
  ALEPH_ASSERT_EQUAL( D3[0].betti(),     43 );
}

template <class T> void testTriangle()
{
  using DataType   = bool;
  using VertexType = T;

  using Simplex           = aleph::topology::Simplex<DataType, VertexType>;
  using SimplicialComplex = aleph::topology::SimplicialComplex<Simplex>;

  SimplicialComplex K = {
    {0,1,2},
    {0,1}, {0,2}, {1,2},
    {0}, {1}, {2}
  };

  auto L = aleph::topology::spine( K );

  ALEPH_ASSERT_THROW( L.size() < K.size() );
  ALEPH_ASSERT_EQUAL( L.size(), 1 );
}

int main( int, char** )
{
  testDisk<short>   ();
  testDisk<unsigned>();

#if 0
  testPinchedTorus<float> ();
  testPinchedTorus<double>();
#endif

  testS1vS1<float> ();
  testS1vS1<double>();

  testTriangle<short>   ();
  testTriangle<unsigned>();
}
<|endoftext|>


<commit_before>// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.

#include "docsumconfig.h"
#include "docsumwriter.h"
#include "idocsumenvironment.h"
#include "rankfeaturesdfw.h"
#include "textextractordfw.h"
#include "geoposdfw.h"
#include "positionsdfw.h"
#include "juniperdfw.h"
#include <vespa/vespalib/util/stringfmt.h>
#include <vespa/vespalib/util/exceptions.h>

namespace search::docsummary {

using vespalib::IllegalArgumentException;
using vespalib::make_string;

const ResultConfig &
DynamicDocsumConfig::getResultConfig() const {
    return *_writer->GetResultConfig();
}

IDocsumFieldWriter::UP
DynamicDocsumConfig::createFieldWriter(const string & fieldName, const string & overrideName, const string & argument, bool & rc)
{
    const ResultConfig & resultConfig = getResultConfig();
    rc = false;
    IDocsumFieldWriter::UP fieldWriter;
    if (overrideName == "dynamicteaser") {
        if ( ! argument.empty() ) {
            const char *langFieldName = "something unused";
            DynamicTeaserDFW *fw = new DynamicTeaserDFW(getEnvironment()->getJuniper());
            fieldWriter.reset(fw);
            rc = fw->Init(fieldName.c_str(), langFieldName, resultConfig, argument.c_str());
        } else {
            throw IllegalArgumentException("Missing argument");
        }
    } else if (overrideName == "textextractor") {
        if ( ! argument.empty() ) {
            TextExtractorDFW * fw = new TextExtractorDFW();
            fieldWriter.reset(fw);
            rc = fw->init(fieldName, argument, resultConfig);
        } else {
            throw IllegalArgumentException("Missing argument");
        }
    } else if (overrideName == "summaryfeatures") {
        SummaryFeaturesDFW *fw = new SummaryFeaturesDFW();
        fieldWriter.reset(fw);
        fw->init(getEnvironment());
        rc = true;
    } else if (overrideName == "rankfeatures") {
        RankFeaturesDFW * fw = new RankFeaturesDFW();
        fw->init(getEnvironment());
        fieldWriter.reset(fw);
        rc = true;
    } else if (overrideName == "empty") {
        EmptyDFW *fw = new EmptyDFW();
        fieldWriter.reset(fw);
        rc = true;
    } else if (overrideName == "copy") {
        if ( ! argument.empty() ) {
            CopyDFW *fw = new CopyDFW();
            fieldWriter.reset(fw);
            rc = fw->Init(resultConfig, argument.c_str());
        } else {
            throw IllegalArgumentException("Missing argument");
        }
    } else if (overrideName == "absdist") {
        if (getEnvironment()) {
            IAttributeManager *am = getEnvironment()->getAttributeManager();
            fieldWriter = createAbsDistanceDFW(argument.c_str(), am);
            rc = fieldWriter.get();
        }
    } else if (overrideName == "positions") {
        if (getEnvironment()) {
            IAttributeManager *am = getEnvironment()->getAttributeManager();
            fieldWriter = createPositionsDFW(argument.c_str(), am);
            rc = fieldWriter.get();
        }
    } else if (overrideName == "geopos") {
        if (getEnvironment()) {
            IAttributeManager *am = getEnvironment()->getAttributeManager();
            fieldWriter = GeoPositionDFW::create(argument.c_str(), am);
            rc = fieldWriter.get();
        }
    } else if (overrideName == "attribute") {
        const char *vectorName = argument.c_str();
        if (getEnvironment() && getEnvironment()->getAttributeManager()) {
            IDocsumFieldWriter *fw = AttributeDFWFactory::create(*getEnvironment()->getAttributeManager(), vectorName);
            fieldWriter.reset(fw);
            rc = fw != NULL;
        }
    } else {
        throw IllegalArgumentException("unknown override operation '" + overrideName + "' for field '" + fieldName + "'.");
    }
    return fieldWriter;
}

void
DynamicDocsumConfig::configure(const vespa::config::search::SummarymapConfig &cfg)
{
    std::vector<string> strCfg;
    if ((cfg.defaultoutputclass != -1) && !_writer->SetDefaultOutputClass(cfg.defaultoutputclass)) {
        throw IllegalArgumentException(make_string("could not set default output class to %d", cfg.defaultoutputclass));
    }
    for (size_t i = 0; i < cfg.override.size(); ++i) {
        const vespa::config::search::SummarymapConfig::Override & o = cfg.override[i];
        // DYNAMIC TEASER
        bool rc(false);
        IDocsumFieldWriter::UP fieldWriter = createFieldWriter(o.field, o.command, o.arguments, rc);
        if (rc && fieldWriter.get() != NULL) {
            rc = _writer->Override(o.field.c_str(), fieldWriter.release()); // OBJECT HAND-OVER
        }
        if (!rc) {
            throw IllegalArgumentException(o.command + " override operation failed during initialization");
        }
    }
}

}
<commit_msg>Ignore new 'attributecombiner' document summary transform until it is supported.<commit_after>// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.

#include "docsumconfig.h"
#include "docsumwriter.h"
#include "idocsumenvironment.h"
#include "rankfeaturesdfw.h"
#include "textextractordfw.h"
#include "geoposdfw.h"
#include "positionsdfw.h"
#include "juniperdfw.h"
#include <vespa/vespalib/util/stringfmt.h>
#include <vespa/vespalib/util/exceptions.h>

namespace search::docsummary {

using vespalib::IllegalArgumentException;
using vespalib::make_string;

const ResultConfig &
DynamicDocsumConfig::getResultConfig() const {
    return *_writer->GetResultConfig();
}

IDocsumFieldWriter::UP
DynamicDocsumConfig::createFieldWriter(const string & fieldName, const string & overrideName, const string & argument, bool & rc)
{
    const ResultConfig & resultConfig = getResultConfig();
    rc = false;
    IDocsumFieldWriter::UP fieldWriter;
    if (overrideName == "dynamicteaser") {
        if ( ! argument.empty() ) {
            const char *langFieldName = "something unused";
            DynamicTeaserDFW *fw = new DynamicTeaserDFW(getEnvironment()->getJuniper());
            fieldWriter.reset(fw);
            rc = fw->Init(fieldName.c_str(), langFieldName, resultConfig, argument.c_str());
        } else {
            throw IllegalArgumentException("Missing argument");
        }
    } else if (overrideName == "textextractor") {
        if ( ! argument.empty() ) {
            TextExtractorDFW * fw = new TextExtractorDFW();
            fieldWriter.reset(fw);
            rc = fw->init(fieldName, argument, resultConfig);
        } else {
            throw IllegalArgumentException("Missing argument");
        }
    } else if (overrideName == "summaryfeatures") {
        SummaryFeaturesDFW *fw = new SummaryFeaturesDFW();
        fieldWriter.reset(fw);
        fw->init(getEnvironment());
        rc = true;
    } else if (overrideName == "rankfeatures") {
        RankFeaturesDFW * fw = new RankFeaturesDFW();
        fw->init(getEnvironment());
        fieldWriter.reset(fw);
        rc = true;
    } else if (overrideName == "empty") {
        EmptyDFW *fw = new EmptyDFW();
        fieldWriter.reset(fw);
        rc = true;
    } else if (overrideName == "copy") {
        if ( ! argument.empty() ) {
            CopyDFW *fw = new CopyDFW();
            fieldWriter.reset(fw);
            rc = fw->Init(resultConfig, argument.c_str());
        } else {
            throw IllegalArgumentException("Missing argument");
        }
    } else if (overrideName == "absdist") {
        if (getEnvironment()) {
            IAttributeManager *am = getEnvironment()->getAttributeManager();
            fieldWriter = createAbsDistanceDFW(argument.c_str(), am);
            rc = fieldWriter.get();
        }
    } else if (overrideName == "positions") {
        if (getEnvironment()) {
            IAttributeManager *am = getEnvironment()->getAttributeManager();
            fieldWriter = createPositionsDFW(argument.c_str(), am);
            rc = fieldWriter.get();
        }
    } else if (overrideName == "geopos") {
        if (getEnvironment()) {
            IAttributeManager *am = getEnvironment()->getAttributeManager();
            fieldWriter = GeoPositionDFW::create(argument.c_str(), am);
            rc = fieldWriter.get();
        }
    } else if (overrideName == "attribute") {
        const char *vectorName = argument.c_str();
        if (getEnvironment() && getEnvironment()->getAttributeManager()) {
            IDocsumFieldWriter *fw = AttributeDFWFactory::create(*getEnvironment()->getAttributeManager(), vectorName);
            fieldWriter.reset(fw);
            rc = fw != NULL;
        }
    } else {
        throw IllegalArgumentException("unknown override operation '" + overrideName + "' for field '" + fieldName + "'.");
    }
    return fieldWriter;
}

void
DynamicDocsumConfig::configure(const vespa::config::search::SummarymapConfig &cfg)
{
    std::vector<string> strCfg;
    if ((cfg.defaultoutputclass != -1) && !_writer->SetDefaultOutputClass(cfg.defaultoutputclass)) {
        throw IllegalArgumentException(make_string("could not set default output class to %d", cfg.defaultoutputclass));
    }
    for (size_t i = 0; i < cfg.override.size(); ++i) {
        const vespa::config::search::SummarymapConfig::Override & o = cfg.override[i];
        if (o.command == "attributecombiner") {
            // TODO: Remove this when support has been added
            continue;
        }
        bool rc(false);
        IDocsumFieldWriter::UP fieldWriter = createFieldWriter(o.field, o.command, o.arguments, rc);
        if (rc && fieldWriter.get() != NULL) {
            rc = _writer->Override(o.field.c_str(), fieldWriter.release()); // OBJECT HAND-OVER
        }
        if (!rc) {
            throw IllegalArgumentException(o.command + " override operation failed during initialization");
        }
    }
}

}
<|endoftext|>


<commit_before>// addon.cc
#include <list>
#include <string>
#include <chrono>
#include <thread>
#include <iostream>
#include <functional>

#include <node.h>

#include "DHT22.h"
#include "TSL2561.h"
#include "BMP180.h"
#include "sensor_result.h"
#include "scheduler.h"

using namespace v8;

/**
 * Init a sensor based of the V8 object given. If no sensor could be created, nullptr is returned. Will throw
 * exception if any error occured during the creation of the sensor
 * @param  sensorName   The name of the sensor
 * @param  sensorConfig The sensor configuration. Must contains the type of sensor
 * @return              The created sensor, or nullptr
 */
sensor::sensor* InitSensor(const Local<String>& sensorName, const Local<Object>& sensorConfig) {
    Isolate* isolate = Isolate::GetCurrent();

    // String used in the method
    const Local<String> pin = String::NewFromUtf8(isolate, "pin");
    const Local<String> addr = String::NewFromUtf8(isolate, "address");
    const Local<String> t = String::NewFromUtf8(isolate, "type");
    const Local<String> freq = String::NewFromUtf8(isolate, "frequence");

    if(!sensorConfig->Has(freq) || !sensorConfig->Get(freq)->IsNumber())
        throw Exception::TypeError(
            String::NewFromUtf8(isolate, "Error : all sensors require a valid 'frequence' property (number >= 0)"));

    if(!sensorConfig->Has(t) || !sensorConfig->Get(t)->IsString())
        throw Exception::TypeError(
            String::NewFromUtf8(isolate, "Error : no type specified. All sensors require a valid 'type' property"));

    // Get the type of sensor
    const Local<Value> jsvalue = sensorConfig->Get(t);
    String::Utf8Value value(jsvalue->ToString());
    const std::string type = std::string(*value);

    // Get the frequence
    const Local<Value> jsFrequence = sensorConfig->Get(freq);
    int frequence = (int) jsFrequence->NumberValue();

    // Only type is required
    if (type == "DHT22") {
        // Get the pin
        if(!sensorConfig->Has(pin) || !sensorConfig->Get(pin)->IsNumber()) {
            throw Exception::TypeError(
                String::NewFromUtf8(isolate, "Error : DHT22 require a valid 'pin' property (number > 0)"));
        }

        Local<Number> pinValue = Local<Number>::Cast(sensorConfig->Get(pin));

        std::cout << "Sensor of type DHT22 created" << std::endl;
        return (sensor::sensor*) new sensor::DHT22_sensor((unsigned) pinValue->NumberValue(), frequence);
    }
    else if (type == "TSL2561") {
        // Get the address
        if(!sensorConfig->Has(addr) || !sensorConfig->Get(addr)->IsNumber()) {
            throw Exception::TypeError(
                String::NewFromUtf8(isolate, "Error : TSL2561 require a valid 'address' property (number > 0)"));
        }

        Local<Number> addrValue = Local<Number>::Cast(sensorConfig->Get(addr));

        std::cout << "Sensor of type TSL2561 created" << std::endl;
        return (sensor::sensor*) new sensor::TSL2561_sensor((uint16_t) addrValue->NumberValue(), frequence);
    }
    else if (type == "BMP180") {
        // Get the address
        if(!sensorConfig->Has(addr) || !sensorConfig->Get(addr)->IsNumber()) {
            throw Exception::TypeError(
                String::NewFromUtf8(isolate, "Error : BMP180 require a valid 'address' property (number > 0)"));
        }

        Local<Number> addrValue = Local<Number>::Cast(sensorConfig->Get(addr));

        std::cout << "Sensor of type BMP180 created" << std::endl;
        return (sensor::sensor*) new sensor::BMP180_sensor((uint16_t) addrValue->NumberValue(), frequence);
    }
    else {
        throw Exception::TypeError(
            String::NewFromUtf8(isolate, "Error : invalid sensor type"));
    }

    return nullptr;
}

/**
 * For now, main method of the NodeJS plugin
 * @param args The arguments used to call the method. Must contains a callbacks and a V8 object
 */
void RunCallback(const FunctionCallbackInfo<Value>& args) {
    Isolate* isolate = Isolate::GetCurrent();
    HandleScope scope(isolate);

    std::list<sensor::sensor*> sensors;

    try {
        // Check that all the parameters are good
        if (args.Length() < 2)
            throw Exception::TypeError(
                String::NewFromUtf8(isolate, "Error : Wrong number of arguments : two are required"));

        if (!args[0]->IsFunction() || !args[1]->IsObject())
            throw Exception::TypeError(
                String::NewFromUtf8(isolate, "Error : Wrong argument(s) : first must be a callback, and the second must be the configuration"));

        // Get elements
        Local<Function> cb = Local<Function>::Cast(args[0]);
        Local<Object> options = Local<Object>::Cast(args[1]);

        Persistent<Function, CopyablePersistentTraits<Function>> callback(isolate, cb);

        // Iter on each property
        const Local<Array> props = options->GetPropertyNames();
        const uint32_t length = props->Length();

        for (uint32_t i = 0 ; i < length ; i++) {
            const Local<Value> key = props->Get(i);
            const Local<Value> value = options->Get(key);

            // Init the sensor
            sensor::sensor* s = InitSensor(key->ToString(), value->ToObject());

            if(s != nullptr) {
                s->initialize();
                sensors.push_back(s);
            }
        }

        // Create & launch the main scheduler
        sensor::scheduler* handler = new sensor::scheduler(sensors, [callback, isolate](sensor::sensor* s, sensor::result* r) {
            // Get the type of value & the value
            Local<Object> result = Object::New(isolate);

            Local<String> type;
            Local<String> unit;
            Local<String> unit_display;
            Local<Number> value;

            // Local reference of the callback
            Local<Function> cb = Local<Function>::New(isolate, callback);

            if(r->getType() == sensor::resultType::TEMPERATURE) {
                type = String::NewFromUtf8(isolate, "Temperature");
                unit = String::NewFromUtf8(isolate, "Degree Celsius");
                unit_display = String::NewFromUtf8(isolate, "°C");
                value = Number::New(isolate, r->getValue().f);
            }
            else if(r->getType() == sensor::resultType::HUMIDITY) {
                type = String::NewFromUtf8(isolate, "Humidity");
                unit = String::NewFromUtf8(isolate, "Percent");
                unit_display = String::NewFromUtf8(isolate, "%");
                value = Number::New(isolate, r->getValue().f);
            }
            else if(r->getType() == sensor::resultType::LIGHT) {
                type = String::NewFromUtf8(isolate, "Light");
                unit = String::NewFromUtf8(isolate, "Lux");
                unit_display = String::NewFromUtf8(isolate, "Lux");
                value = Number::New(isolate, r->getValue().i);
            }
            else if(r->getType() == sensor::resultType::PRESSURE) {
                type = String::NewFromUtf8(isolate, "Pressure");
                unit = String::NewFromUtf8(isolate, "Pascal");
                unit_display = String::NewFromUtf8(isolate, "Pa");
                value = Number::New(isolate, r->getValue().f);
            }
            else {
                type = String::NewFromUtf8(isolate, "Other");
                unit = String::NewFromUtf8(isolate, "-");
                unit_display = String::NewFromUtf8(isolate, "");
                value = Number::New(isolate, 0);
            }

            result->Set(String::NewFromUtf8(isolate, "type"), type);
            result->Set(String::NewFromUtf8(isolate, "unit"), unit);
            result->Set(String::NewFromUtf8(isolate, "unit_display"), unit_display);
            result->Set(String::NewFromUtf8(isolate, "value"), value);
            result->Set(String::NewFromUtf8(isolate, "date"), Date::New(isolate, r->getTimestamp()));
            result->Set(String::NewFromUtf8(isolate, "timestamp"), Number::New(isolate, r->getTimestamp()));

            // Call the callback with the values
            Local<Value> argv[1] = { result };
            cb->Call(isolate->GetCurrentContext()->Global(), 1, argv);
        });

        handler->launch();

    } catch(Local<Value> &e) {
        // If we catch any error error here, then no thread are launched : everything can be free'd
        // TODO free every sensor

        // Transfer the exception to node
        isolate->ThrowException(e);
    }
}

void Init(Handle<Object> exports, Handle<Object> module) {
    NODE_SET_METHOD(module, "exports", RunCallback);
}

// TODO handle destructor ?

NODE_MODULE(meteonetwork, Init)
<commit_msg>Add name for each sensor in plugin.cc<commit_after>// addon.cc
#include <list>
#include <string>
#include <chrono>
#include <thread>
#include <iostream>
#include <functional>

#include <node.h>

#include "DHT22.h"
#include "TSL2561.h"
#include "BMP180.h"
#include "sensor_result.h"
#include "scheduler.h"

using namespace v8;

/**
 * Init a sensor based of the V8 object given. If no sensor could be created, nullptr is returned. Will throw
 * exception if any error occured during the creation of the sensor
 * @param  sensorName   The name of the sensor
 * @param  sensorConfig The sensor configuration. Must contains the type of sensor
 * @return              The created sensor, or nullptr
 */
sensor::sensor* InitSensor(const Local<String>& sensorName, const Local<Object>& sensorConfig) {
    Isolate* isolate = Isolate::GetCurrent();

    // String used in the method
    const Local<String> pin = String::NewFromUtf8(isolate, "pin");
    const Local<String> addr = String::NewFromUtf8(isolate, "address");
    const Local<String> t = String::NewFromUtf8(isolate, "type");
    const Local<String> freq = String::NewFromUtf8(isolate, "frequence");

    if(!sensorConfig->Has(freq) || !sensorConfig->Get(freq)->IsNumber())
        throw Exception::TypeError(
            String::NewFromUtf8(isolate, "Error : all sensors require a valid 'frequence' property (number >= 0)"));

    if(!sensorConfig->Has(t) || !sensorConfig->Get(t)->IsString())
        throw Exception::TypeError(
            String::NewFromUtf8(isolate, "Error : no type specified. All sensors require a valid 'type' property"));

    // Get the type of sensor
    const Local<Value> jsvalue = sensorConfig->Get(t);
    String::Utf8Value value(jsvalue->ToString());
    const std::string type = std::string(*value);

    // Get the frequence
    const Local<Value> jsFrequence = sensorConfig->Get(freq);
    int frequence = (int) jsFrequence->NumberValue();

    // Only type is required
    if (type == "DHT22") {
        // Get the pin
        if(!sensorConfig->Has(pin) || !sensorConfig->Get(pin)->IsNumber()) {
            throw Exception::TypeError(
                String::NewFromUtf8(isolate, "Error : DHT22 require a valid 'pin' property (number > 0)"));
        }

        Local<Number> pinValue = Local<Number>::Cast(sensorConfig->Get(pin));

        std::cout << "Sensor of type DHT22 created" << std::endl;
        return (sensor::sensor*) new sensor::DHT22_sensor((unsigned) pinValue->NumberValue(), frequence, std::string(*sensorName));
    }
    else if (type == "TSL2561") {
        // Get the address
        if(!sensorConfig->Has(addr) || !sensorConfig->Get(addr)->IsNumber()) {
            throw Exception::TypeError(
                String::NewFromUtf8(isolate, "Error : TSL2561 require a valid 'address' property (number > 0)"));
        }

        Local<Number> addrValue = Local<Number>::Cast(sensorConfig->Get(addr));

        std::cout << "Sensor of type TSL2561 created" << std::endl;
        return (sensor::sensor*) new sensor::TSL2561_sensor((uint16_t) addrValue->NumberValue(), frequence, std::string(*sensorName));
    }
    else if (type == "BMP180") {
        // Get the address
        if(!sensorConfig->Has(addr) || !sensorConfig->Get(addr)->IsNumber()) {
            throw Exception::TypeError(
                String::NewFromUtf8(isolate, "Error : BMP180 require a valid 'address' property (number > 0)"));
        }

        Local<Number> addrValue = Local<Number>::Cast(sensorConfig->Get(addr));

        std::cout << "Sensor of type BMP180 created" << std::endl;
        return (sensor::sensor*) new sensor::BMP180_sensor((uint16_t) addrValue->NumberValue(), frequence, std::string(*sensorName));
    }
    else {
        throw Exception::TypeError(
            String::NewFromUtf8(isolate, "Error : invalid sensor type"));
    }

    return nullptr;
}

/**
 * For now, main method of the NodeJS plugin
 * @param args The arguments used to call the method. Must contains a callbacks and a V8 object
 */
void RunCallback(const FunctionCallbackInfo<Value>& args) {
    Isolate* isolate = Isolate::GetCurrent();
    HandleScope scope(isolate);

    std::list<sensor::sensor*> sensors;

    try {
        // Check that all the parameters are good
        if (args.Length() < 2)
            throw Exception::TypeError(
                String::NewFromUtf8(isolate, "Error : Wrong number of arguments : two are required"));

        if (!args[0]->IsFunction() || !args[1]->IsObject())
            throw Exception::TypeError(
                String::NewFromUtf8(isolate, "Error : Wrong argument(s) : first must be a callback, and the second must be the configuration"));

        // Get elements
        Local<Function> cb = Local<Function>::Cast(args[0]);
        Local<Object> options = Local<Object>::Cast(args[1]);

        Persistent<Function, CopyablePersistentTraits<Function>> callback(isolate, cb);

        // Iter on each property
        const Local<Array> props = options->GetPropertyNames();
        const uint32_t length = props->Length();

        for (uint32_t i = 0 ; i < length ; i++) {
            const Local<Value> key = props->Get(i);
            const Local<Value> value = options->Get(key);

            // Init the sensor
            sensor::sensor* s = InitSensor(key->ToString(), value->ToObject());

            if(s != nullptr) {
                s->initialize();
                sensors.push_back(s);
            }
        }

        // Create & launch the main scheduler
        sensor::scheduler* handler = new sensor::scheduler(sensors, [callback, isolate](sensor::sensor* s, sensor::result* r) {
            // Get the type of value & the value
            Local<Object> result = Object::New(isolate);

            Local<String> type;
            Local<String> unit;
            Local<String> unit_display;
            Local<Number> value;

            // Local reference of the callback
            Local<Function> cb = Local<Function>::New(isolate, callback);

            if(r->getType() == sensor::resultType::TEMPERATURE) {
                type = String::NewFromUtf8(isolate, "Temperature");
                unit = String::NewFromUtf8(isolate, "Degree Celsius");
                unit_display = String::NewFromUtf8(isolate, "°C");
                value = Number::New(isolate, r->getValue().f);
            }
            else if(r->getType() == sensor::resultType::HUMIDITY) {
                type = String::NewFromUtf8(isolate, "Humidity");
                unit = String::NewFromUtf8(isolate, "Percent");
                unit_display = String::NewFromUtf8(isolate, "%");
                value = Number::New(isolate, r->getValue().f);
            }
            else if(r->getType() == sensor::resultType::LIGHT) {
                type = String::NewFromUtf8(isolate, "Light");
                unit = String::NewFromUtf8(isolate, "Lux");
                unit_display = String::NewFromUtf8(isolate, "Lux");
                value = Number::New(isolate, r->getValue().i);
            }
            else if(r->getType() == sensor::resultType::PRESSURE) {
                type = String::NewFromUtf8(isolate, "Pressure");
                unit = String::NewFromUtf8(isolate, "Pascal");
                unit_display = String::NewFromUtf8(isolate, "Pa");
                value = Number::New(isolate, r->getValue().f);
            }
            else {
                type = String::NewFromUtf8(isolate, "Other");
                unit = String::NewFromUtf8(isolate, "-");
                unit_display = String::NewFromUtf8(isolate, "");
                value = Number::New(isolate, 0);
            }

            result->Set(String::NewFromUtf8(isolate, "type"), type);
            result->Set(String::NewFromUtf8(isolate, "unit"), unit);
            result->Set(String::NewFromUtf8(isolate, "unit_display"), unit_display);
            result->Set(String::NewFromUtf8(isolate, "value"), value);
            result->Set(String::NewFromUtf8(isolate, "date"), Date::New(isolate, r->getTimestamp()));
            result->Set(String::NewFromUtf8(isolate, "timestamp"), Number::New(isolate, r->getTimestamp()));

            // Call the callback with the values
            Local<Value> argv[1] = { result };
            cb->Call(isolate->GetCurrentContext()->Global(), 1, argv);
        });

        handler->launch();

    } catch(Local<Value> &e) {
        // If we catch any error error here, then no thread are launched : everything can be free'd
        // TODO free every sensor

        // Transfer the exception to node
        isolate->ThrowException(e);
    }
}

void Init(Handle<Object> exports, Handle<Object> module) {
    NODE_SET_METHOD(module, "exports", RunCallback);
}

// TODO handle destructor ?

NODE_MODULE(meteonetwork, Init)
<|endoftext|>


<commit_before>#include "testvectorsfile.h"
#include "serializer.h"
#include "consts.h"
#include "blob.h"

#include <iostream>
#include <string>

namespace
{
    template< typename T >
    Blob createFileBlobHash( const T& content )
    {
        std::vector< Blob > partials;

        for ( size_t pos = 0; pos < content.size(); pos += simpleFileSizeLimit )
        {
            size_t partSize = std::min( simpleFileSizeLimit, content.size() - pos );
            std::vector<char> partContent( content.begin()+pos, content.begin()+pos+partSize );
            partials.push_back( Blob::newHashValidatedBlob( blobType_simpleStaticFile, content ) );
        }

        // Make sure we've got at least one blob
        if ( partials.empty() )
        {
            partials.push_back( Blob::newHashValidatedBlob( blobType_simpleStaticFile, std::string() ) );
        }

        // Don't have to split the blob if it fits in one part
        if ( partials.size() == 1 )
        {
            return partials.front();
        }

        std::cout << "SPLIT FILE!!!" << std::endl;

        // Create extra blob containing information about the parts
        Serializer s;

        s << content.size() << partials.size();
        for ( const auto& blob: partials ) s << blob.getBid() << blob.getKey();

        return Blob::newHashValidatedBlob( blobType_splitStaticFile, s.getData() );
    }

    void dumpFileBlobHash( const std::string& content )
    {
        std::string name = "Simple File: '" + content.substr(0,20);
        if ( content.size()>20 ) name.append("...");
        name.append("'");

        createFileBlobHash(content).dump( name );
    }
}

void createFileTestVectors()
{
    dumpFileBlobHash( "" );
    dumpFileBlobHash( "a" );
    dumpFileBlobHash( "Hello World!" );

    std::string str;
    for( char ch = 'a'; ch <= 'z'; ch++ ) str.push_back(ch);
    for( char ch = 'A'; ch <= 'Z'; ch++ ) str.push_back(ch);
    dumpFileBlobHash( str );

    /**/
    std::string aaa;
    for ( size_t i=0; i<simpleFileSizeLimit; i++ ) aaa.push_back('a');
    dumpFileBlobHash( aaa );

    /**/
}
<commit_msg>Change the description of max simple file test<commit_after>#include "testvectorsfile.h"
#include "serializer.h"
#include "consts.h"
#include "blob.h"

#include <iostream>
#include <string>

namespace
{
    template< typename T >
    Blob createFileBlobHash( const T& content )
    {
        std::vector< Blob > partials;

        for ( size_t pos = 0; pos < content.size(); pos += simpleFileSizeLimit )
        {
            size_t partSize = std::min( simpleFileSizeLimit, content.size() - pos );
            std::vector<char> partContent( content.begin()+pos, content.begin()+pos+partSize );
            partials.push_back( Blob::newHashValidatedBlob( blobType_simpleStaticFile, content ) );
        }

        // Make sure we've got at least one blob
        if ( partials.empty() )
        {
            partials.push_back( Blob::newHashValidatedBlob( blobType_simpleStaticFile, std::string() ) );
        }

        // Don't have to split the blob if it fits in one part
        if ( partials.size() == 1 )
        {
            return partials.front();
        }

        std::cout << "SPLIT FILE!!!" << std::endl;

        // Create extra blob containing information about the parts
        Serializer s;

        s << content.size() << partials.size();
        for ( const auto& blob: partials ) s << blob.getBid() << blob.getKey();

        return Blob::newHashValidatedBlob( blobType_splitStaticFile, s.getData() );
    }

    void dumpFileBlobHash( const std::string& content, const std::string& name )
    {
        createFileBlobHash(content).dump( name );
    }

    void dumpFileBlobHash( const std::string& content )
    {
        std::string name = "Simple File: '" + content.substr(0,20);
        if ( content.size()>20 ) name.append("...");
        name.append("'");

        dumpFileBlobHash( content, name );
    }
}

void createFileTestVectors()
{
    dumpFileBlobHash( "" );
    dumpFileBlobHash( "a" );
    dumpFileBlobHash( "Hello World!" );

    std::string str;
    for( char ch = 'a'; ch <= 'z'; ch++ ) str.push_back(ch);
    for( char ch = 'A'; ch <= 'Z'; ch++ ) str.push_back(ch);
    dumpFileBlobHash( str );

    std::string aaa;
    for ( size_t i=0; i<simpleFileSizeLimit; i++ ) aaa.push_back('a');
    dumpFileBlobHash( aaa, "Maximum simple file size filled with 'a'" );
}
<|endoftext|>


<commit_before>#include "SocketSession.h"
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include "lua_engine.h"
#include "fxtimer.h"
#include "ifnet.h"

#include <signal.h>

#define WORK_PATH "scripts"
#define CLIENTCOUNT 1

char* g_strIp = "127.0.0.1";
unsigned int g_dwPort = 20000;
bool g_bRun = true;

static FxSession* g_sSessions[CLIENTCOUNT] = { 0 };

class TestTimer1 : public IFxTimer
{
public:
	TestTimer1()
	{
		m_i = 0;
	}
	virtual bool OnTimer(double fSecond)
	{
		int nLen = rand() % 256;
		nLen += 768;
		bool bSended = true;
		for (int i = 0; i < CLIENTCOUNT; ++i)
		{
			sprintf(szMsg, "%s....%d......%d.....%d", GetExePath(), g_sSessions[i]->GetRemotePort(), m_i, nLen);
			if (!g_sSessions[i]->GetConnection())
			{
				continue;
			}
			if (!g_sSessions[i]->IsConnected())
			{
				continue;
			}
			if(!g_sSessions[i]->Send(szMsg, 512))
			{
				if (!g_sSessions[i]->IsConnected())
				{
					LogExe(LogLv_Error, "error!!!!!!!!!!!!!!!!!!!!!!!!");
					g_bRun = false;
					break;
				}
				bSended = false;
			}
		}
		if(bSended)
		{
			++m_i;
		}
		GetTimeHandler()->AddDelayTimer(0.01, this);
		return true;
	}
	char szMsg[1024];
	int m_i;
};
TestTimer1 g_sTimer1;

void EndFun(int n)
{
	if (n == SIGINT || n == SIGTERM)
	{
		g_bRun = false;
	}
	else
	{
		printf("unknown signal : %d !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n", n);
	}
}

int main(int argc, char **argv)
{
	//--------------------order can't change begin-------------------------//
	signal(SIGINT, EndFun);
	signal(SIGTERM, EndFun);
	if (!CLuaEngine::CreateInstance())
	{
		return 0;
	}
	std::vector<ToluaFunctionOpen*> vecFunctions;
	int tolua_LuaMeta_open(lua_State*);
	vecFunctions.push_back(tolua_LuaMeta_open);
	if (!CLuaEngine::Instance()->Init(vecFunctions))
	{
		return 0;
	}
	if (!CLuaEngine::Instance()->Reload(WORK_PATH))
	{
		return 0;
	}
	// must defined before goto
	IFxNet* pNet = NULL;
	UINT32 dwIP = 0;
	char szMsg[1024] = "";
	int j = 0;

	if (!CLuaEngine::Instance()->CommandLineFunction(argv, argc))
	{
		g_bRun = false;
		goto STOP;
	}
	if (!GetTimeHandler()->Init())
	{
		g_bRun = false;
		goto STOP;
	}
	GetTimeHandler()->Run();

	pNet = FxNetGetModule();
	if (!pNet)
	{
		g_bRun = false;
		goto STOP;
	}
	//--------------------order can't change end-------------------------//

	dwIP = inet_addr(g_strIp);

	for (int i = 0; i < CLIENTCOUNT; ++i)
	{
		g_sSessions[i] = oSessionFactory.CreateSession();
		pNet->UdpConnect(g_sSessions[i], dwIP, g_dwPort, true);
	}

	GetTimeHandler()->AddDelayTimer(0.08f, &g_sTimer1);

	while (g_bRun)
	{
		GetTimeHandler()->Run();
		pNet->Run(0xffffffff);
		FxSleep(10);
		++j;
	}
	for (int i = 0; i < CLIENTCOUNT; ++i)
	{
		g_sSessions[i]->Close();
	}
	FxSleep(10);
	pNet->Run(0xffffffff);
	FxSleep(10);
	pNet->Release();
	return 0;
STOP:
	printf("error!!!!!!!!\n");
	//LogThread::Instance()->Stop();
}
<commit_msg>客户端连接断开 就关闭<commit_after>#include "SocketSession.h"
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include "lua_engine.h"
#include "fxtimer.h"
#include "ifnet.h"

#include <signal.h>

#define WORK_PATH "scripts"
#define CLIENTCOUNT 1

char* g_strIp = "127.0.0.1";
unsigned int g_dwPort = 20000;
bool g_bRun = true;

static FxSession* g_sSessions[CLIENTCOUNT] = { 0 };

class TestTimer1 : public IFxTimer
{
public:
	TestTimer1()
	{
		m_i = 0;
	}
	virtual bool OnTimer(double fSecond)
	{
		int nLen = rand() % 256;
		nLen += 768;
		bool bSended = true;
		for (int i = 0; i < CLIENTCOUNT; ++i)
		{
			sprintf(szMsg, "%s....%d......%d.....%d", GetExePath(), g_sSessions[i]->GetRemotePort(), m_i, nLen);
			if(!g_sSessions[i]->Send(szMsg, 512))
			{
				if (!g_sSessions[i]->IsConnected())
				{
					LogExe(LogLv_Error, "error!!!!!!!!!!!!!!!!!!!!!!!!");
					g_bRun = false;
					break;
				}
				bSended = false;
			}
		}
		if(bSended)
		{
			++m_i;
		}
		GetTimeHandler()->AddDelayTimer(0.01, this);
		return true;
	}
	char szMsg[1024];
	int m_i;
};
TestTimer1 g_sTimer1;

void EndFun(int n)
{
	if (n == SIGINT || n == SIGTERM)
	{
		g_bRun = false;
	}
	else
	{
		printf("unknown signal : %d !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n", n);
	}
}

int main(int argc, char **argv)
{
	//--------------------order can't change begin-------------------------//
	signal(SIGINT, EndFun);
	signal(SIGTERM, EndFun);
	if (!CLuaEngine::CreateInstance())
	{
		return 0;
	}
	std::vector<ToluaFunctionOpen*> vecFunctions;
	int tolua_LuaMeta_open(lua_State*);
	vecFunctions.push_back(tolua_LuaMeta_open);
	if (!CLuaEngine::Instance()->Init(vecFunctions))
	{
		return 0;
	}
	if (!CLuaEngine::Instance()->Reload(WORK_PATH))
	{
		return 0;
	}
	// must defined before goto
	IFxNet* pNet = NULL;
	UINT32 dwIP = 0;
	char szMsg[1024] = "";
	int j = 0;

	if (!CLuaEngine::Instance()->CommandLineFunction(argv, argc))
	{
		g_bRun = false;
		goto STOP;
	}
	if (!GetTimeHandler()->Init())
	{
		g_bRun = false;
		goto STOP;
	}
	GetTimeHandler()->Run();

	pNet = FxNetGetModule();
	if (!pNet)
	{
		g_bRun = false;
		goto STOP;
	}
	//--------------------order can't change end-------------------------//

	dwIP = inet_addr(g_strIp);

	for (int i = 0; i < CLIENTCOUNT; ++i)
	{
		g_sSessions[i] = oSessionFactory.CreateSession();
		pNet->UdpConnect(g_sSessions[i], dwIP, g_dwPort, true);
	}

	GetTimeHandler()->AddDelayTimer(0.08f, &g_sTimer1);

	while (g_bRun)
	{
		GetTimeHandler()->Run();
		pNet->Run(0xffffffff);
		FxSleep(10);
		++j;
	}
	for (int i = 0; i < CLIENTCOUNT; ++i)
	{
		g_sSessions[i]->Close();
	}
	FxSleep(10);
	pNet->Run(0xffffffff);
	FxSleep(10);
	pNet->Release();
	return 0;
STOP:
	printf("error!!!!!!!!\n");
	//LogThread::Instance()->Stop();
}
<|endoftext|>


<commit_before>#include "catch.hpp"

#include "libx6adc.h"

TEST_CASE("board present", "[get_num_devices]"){
	SECTION("at least one board present"){
		unsigned numDevices;
		get_num_devices(&numDevices);
		REQUIRE( numDevices >= 1);
	}
}

TEST_CASE("board temperature is sane", "[get_logic_temperature]"){

	connect_x6(0);

	SECTION("reported temperature is between 20C and 70C"){
		float logicTemp;
	    get_logic_temperature(0, &logicTemp);
		REQUIRE( logicTemp > 20 );
		REQUIRE( logicTemp < 70 );
	}
}
<commit_msg>:construction: add firmware version checking to unit test<commit_after>#include "catch.hpp"

#include "libx6adc.h"

TEST_CASE("board present", "[get_num_devices]"){
	SECTION("at least one board present"){
		unsigned numDevices;
		get_num_devices(&numDevices);
		REQUIRE( numDevices >= 1);
	}
}

TEST_CASE("board temperature is sane", "[get_logic_temperature]"){

	connect_x6(0);

	SECTION("reported temperature is between 20C and 70C"){
		float logicTemp;
	    get_logic_temperature(0, &logicTemp);
		REQUIRE( logicTemp > 20 );
		REQUIRE( logicTemp < 70 );
	}

	disconnect_x6(0);
}

TEST_CASE("firmware version", "[get_firmware_version]") {

	connect_x6(0);

	SECTION("firmware version checks") {
		uint16_t ver;

		SECTION("BBN firmware is greater than 0.8"){
			get_firmware_version(0, BBN_X6, &ver);
			REQUIRE( ver >= 0x0008);
		}

		SECTION("BBN QDSP firmware is greater than 1.0"){
			get_firmware_version(0, BBN_QDSP, &ver);
			REQUIRE( ver >= 0x0100);
		}

		SECTION("BBN PG firmware is greater than 0.1"){
			get_firmware_version(0, BBN_PG, &ver);
			REQUIRE( ver >= 0x0001);
		}
	}

	disconnect_x6(0);
}
<|endoftext|>


<commit_before>#include "RenderWindow.h"

#include <QtGui/QtGui>
#include <QtOpenGL/QtOpenGL>
#include <assert.h>

RenderWindow::RenderWindow(MasterController& masterController, QString dataset, QListWidget *listWidget_Lock, unsigned int iCounter, QGLWidget* glShareWidget, QWidget* parent, Qt::WindowFlags flags) :
	m_Renderer((GPUSBVR*)masterController.RequestNewVolumerenderer(OPENGL_SBVR)),
	QGLWidget(parent, glShareWidget, flags),
	m_MasterController(masterController),
	m_strDataset(dataset),
	m_listWidget_Lock(listWidget_Lock)
{
	m_strID = tr("[%1] %2").arg(iCounter).arg(m_strDataset);
	setWindowTitle(m_strID);
	m_listWidget_Lock->addItem(m_strID);

	if (!m_Renderer->LoadDataset(m_strDataset.toStdString()))

	m_Renderer->SetCurrentView(0);

	xRot = 0;
}

RenderWindow::~RenderWindow()
{
	makeCurrent();
	m_Renderer->Cleanup();
}

QSize RenderWindow::minimumSizeHint() const
{
	return QSize(50, 50);
}

QSize RenderWindow::sizeHint() const
{
	return QSize(400, 400);
}

void RenderWindow::initializeGL()
{
	if (m_Renderer != NULL) m_Renderer->Initialize();
}

void RenderWindow::paintGL()
{
	if (m_Renderer != NULL) m_Renderer->Paint();
}

void RenderWindow::resizeGL(int width, int height)
{
	if (m_Renderer != NULL) m_Renderer->Resize(width, height);
}

void RenderWindow::mousePressEvent(QMouseEvent *event)
{
	lastPos = event->pos();

	if (event->buttons() & Qt::RightButton) {
		if (m_Renderer != NULL) m_Renderer->SetCurrentView((m_Renderer->GetCurrentView()+1) %3);
		emit RenderWindowViewChanged(m_Renderer->GetCurrentView());
		updateGL();
	}
}

void RenderWindow::mouseMoveEvent(QMouseEvent *event)
{
	// int dx = event->x() - lastPos.x();
	int dy = event->y() - lastPos.y();

	if (event->buttons() & Qt::LeftButton) {
		int angle = xRot + 8 * dy;
		normalizeAngle(&angle);
		if (angle != xRot) {
			xRot = angle;
			if (m_Renderer != NULL) m_Renderer->SetRotation(xRot);
			updateGL();
		}
	}
	lastPos = event->pos();
}

void RenderWindow::normalizeAngle(int *angle)
{
	while (*angle < 0) *angle += 360 * 16;
	while (*angle > 360 * 16) *angle -= 360 * 16;
}

void RenderWindow::ToggleRenderWindowView1x3() {
	if (m_Renderer != NULL) m_Renderer->SetCurrentView(0);
	emit RenderWindowViewChanged(0);
	updateGL();
}

void RenderWindow::ToggleRenderWindowView2x2() {
	if (m_Renderer != NULL) m_Renderer->SetCurrentView(1);
	emit RenderWindowViewChanged(1);
	updateGL();
}

void RenderWindow::ToggleRenderWindowViewSingle() {
	if (m_Renderer != NULL) m_Renderer->SetCurrentView(2);
	emit RenderWindowViewChanged(2);
	updateGL();
}

void RenderWindow::closeEvent(QCloseEvent *event) {
	QGLWidget::closeEvent(event);

	QList<QListWidgetItem*> l = m_listWidget_Lock->findItems(m_strID,  Qt::MatchExactly);
	assert(l.size() == 1); // if l.size() != 1 something went wrong during the creation of the list
	delete l[0];
}
<commit_msg><commit_after>#include "RenderWindow.h"

#include <QtGui/QtGui>
#include <QtOpenGL/QtOpenGL>
#include <assert.h>

RenderWindow::RenderWindow(MasterController& masterController, QString dataset, QListWidget *listWidget_Lock, unsigned int iCounter, QGLWidget* glShareWidget, QWidget* parent, Qt::WindowFlags flags) :
	QGLWidget(parent, glShareWidget, flags),
	m_Renderer((GPUSBVR*)masterController.RequestNewVolumerenderer(OPENGL_SBVR)),
	m_MasterController(masterController),
	m_strDataset(dataset),
	m_listWidget_Lock(listWidget_Lock)
{
	m_strID = tr("[%1] %2").arg(iCounter).arg(m_strDataset);
	setWindowTitle(m_strID);
	m_listWidget_Lock->addItem(m_strID);

	m_Renderer->LoadDataset(m_strDataset.toStdString());
	m_Renderer->SetCurrentView(0);

	xRot = 0;
}

RenderWindow::~RenderWindow()
{
	makeCurrent();
	m_Renderer->Cleanup();
}

QSize RenderWindow::minimumSizeHint() const
{
	return QSize(50, 50);
}

QSize RenderWindow::sizeHint() const
{
	return QSize(400, 400);
}

void RenderWindow::initializeGL()
{
	if (m_Renderer != NULL) m_Renderer->Initialize();
}

void RenderWindow::paintGL()
{
	if (m_Renderer != NULL) m_Renderer->Paint();
}

void RenderWindow::resizeGL(int width, int height)
{
	if (m_Renderer != NULL) m_Renderer->Resize(width, height);
}

void RenderWindow::mousePressEvent(QMouseEvent *event)
{
	lastPos = event->pos();

	if (event->buttons() & Qt::RightButton) {
		if (m_Renderer != NULL) m_Renderer->SetCurrentView((m_Renderer->GetCurrentView()+1) %3);
		emit RenderWindowViewChanged(m_Renderer->GetCurrentView());
		updateGL();
	}
}

void RenderWindow::mouseMoveEvent(QMouseEvent *event)
{
	// int dx = event->x() - lastPos.x();
	int dy = event->y() - lastPos.y();

	if (event->buttons() & Qt::LeftButton) {
		int angle = xRot + 8 * dy;
		normalizeAngle(&angle);
		if (angle != xRot) {
			xRot = angle;
			if (m_Renderer != NULL) m_Renderer->SetRotation(xRot);
			updateGL();
		}
	}
	lastPos = event->pos();
}

void RenderWindow::normalizeAngle(int *angle)
{
	while (*angle < 0) *angle += 360 * 16;
	while (*angle > 360 * 16) *angle -= 360 * 16;
}

void RenderWindow::ToggleRenderWindowView1x3() {
	if (m_Renderer != NULL) m_Renderer->SetCurrentView(0);
	emit RenderWindowViewChanged(0);
	updateGL();
}

void RenderWindow::ToggleRenderWindowView2x2() {
	if (m_Renderer != NULL) m_Renderer->SetCurrentView(1);
	emit RenderWindowViewChanged(1);
	updateGL();
}

void RenderWindow::ToggleRenderWindowViewSingle() {
	if (m_Renderer != NULL) m_Renderer->SetCurrentView(2);
	emit RenderWindowViewChanged(2);
	updateGL();
}

void RenderWindow::closeEvent(QCloseEvent *event) {
	QGLWidget::closeEvent(event);

	QList<QListWidgetItem*> l = m_listWidget_Lock->findItems(m_strID,  Qt::MatchExactly);
	assert(l.size() == 1); // if l.size() != 1 something went wrong during the creation of the list
	delete l[0];
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: persistentwindowstate.hxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: rt $ $Date: 2004-11-26 14:28:38 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (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.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#ifndef __FRAMEWORK_HELPER_PERSISTENTWINDOWSTATE_HXX_
#define __FRAMEWORK_HELPER_PERSISTENTWINDOWSTATE_HXX_

//_________________________________________________________________________________________________________________
//  my own includes
//_________________________________________________________________________________________________________________

#ifndef __FRAMEWORK_THREADHELP_THREADHELPBASE_HXX_
#include <threadhelp/threadhelpbase.hxx>
#endif

#ifndef __FRAMEWORK_MACROS_DEBUG_HXX_
#include <macros/debug.hxx>
#endif

#ifndef __FRAMEWORK_MACROS_XINTERFACE_HXX_
#include <macros/xinterface.hxx>
#endif

#ifndef __FRAMEWORK_MACROS_XTYPEPROVIDER_HXX_
#include <macros/xtypeprovider.hxx>
#endif

#ifndef __FRAMEWORK_GENERAL_H_
#include <general.h>
#endif

//_________________________________________________________________________________________________________________
//  interface includes
//_________________________________________________________________________________________________________________

#ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#endif

#ifndef _COM_SUN_STAR_LANG_XINITIALIZATION_HPP_
#include <com/sun/star/lang/XInitialization.hpp>
#endif

#ifndef _COM_SUN_STAR_FRAME_XFRAME_HPP_
#include <com/sun/star/frame/XFrame.hpp>
#endif

#ifndef _COM_SUN_STAR_FRAME_XFRAMEACTIONLISTENER_HPP_
#include <com/sun/star/frame/XFrameActionListener.hpp>
#endif

#ifndef _COM_SUN_STAR_LANG_XEVENTLISTENER_HPP_
#include <com/sun/star/lang/XEventListener.hpp>
#endif

//_________________________________________________________________________________________________________________
//  other includes
//_________________________________________________________________________________________________________________

#ifndef INCLUDED_SVTOOLS_MODULEOPTIONS_HXX
#include <svtools/moduleoptions.hxx>
#endif

#ifndef _CPPUHELPER_WEAK_HXX_
#include <cppuhelper/weak.hxx>
#endif

//_________________________________________________________________________________________________________________
//  const
//_________________________________________________________________________________________________________________

//_________________________________________________________________________________________________________________
//  namespace
//_________________________________________________________________________________________________________________

namespace framework{

//_________________________________________________________________________________________________________________
//  declarations
//_________________________________________________________________________________________________________________

/*-************************************************************************************************************//**
    @short          listener for closing document frames to make her window state persistent
    @descr          It's a feature of our office. If a document window was created by ourself (and not from
                    any external process e.g. the office bean) we save and restore the window state of it
                    corresponding to the document service factory. That means: one instance of this class will be
                    a listener on one frame which container window was created by ourself.
                    We listen for frame action events and everytimes a component will deattached from a frame
                    we store its current position and size to the configuration. Everytimes a new component is
                    attached to a frame first time(!) we restore this informations again.

    @base           ThreadHelpBase
                        guarantee right initialized lock member during startup of instances of this class.

    @base           OWeakObject
                        implements ref counting for this class.

    @devstatus      ready
    @threadsafe     yes
    @modified       06.08.2004 08:41, as96863
*//*-*************************************************************************************************************/
class PersistentWindowState :   // interfaces
                                public css::lang::XTypeProvider,
                                public css::lang::XInitialization,
                                public css::frame::XFrameActionListener, // => XEventListener
                                // baseclasses (order neccessary for right initialization!)
                                private ThreadHelpBase,
                                public  ::cppu::OWeakObject
{
    //________________________________
    // member

    private:

        /// may we need an uno service manager to create own services
        css::uno::Reference< css::lang::XMultiServiceFactory > m_xSMGR;

        /// reference to the frame which was created by the office himself
        css::uno::WeakReference< css::frame::XFrame > m_xFrame;

    //________________________________
    // interface

    public:

        //____________________________
        // ctor/dtor
                 PersistentWindowState(const css::uno::Reference< css::lang::XMultiServiceFactory >& xSMGR);
        virtual ~PersistentWindowState(                                                                   );

        //____________________________
        // XInterface, XTypeProvider
        DECLARE_XINTERFACE
        DECLARE_XTYPEPROVIDER

        //____________________________
        // XInitialization
        virtual void SAL_CALL initialize(const css::uno::Sequence< css::uno::Any >& lArguments)
            throw(css::uno::Exception       ,
                  css::uno::RuntimeException);

        //____________________________
        // XFrameActionListener
        virtual void SAL_CALL frameAction(const css::frame::FrameActionEvent& aEvent)
            throw(css::uno::RuntimeException);

        //____________________________
        // XEventListener
        virtual void SAL_CALL disposing(const css::lang::EventObject& aEvent)
            throw(css::uno::RuntimeException);

    //________________________________
    // helper

    private:
        //____________________________
        /** @short  identify the application module, which  is used behind the component
                    of our frame.

            @param  xSMGR
                    needed to create needed uno resources.

            @param  xFrame
                    contains the component, wich must be identified.

            @return [string]
                    a module identifier for the current frame component.
         */
        static ::rtl::OUString implst_identifyModule(const css::uno::Reference< css::lang::XMultiServiceFactory >& xSMGR ,
                                                     const css::uno::Reference< css::frame::XFrame >&              xFrame);

        //____________________________
        /** @short  retrieve the window state from the configuration.

            @param  xSMGR
                    needed to create the configuration access.

            @param  sModuleName
                    identifies the application module, where the
                    information should be getted for.

            @return [string]
                    contains the information about position and size.
         */
        static ::rtl::OUString implst_getWindowStateFromConfig(const css::uno::Reference< css::lang::XMultiServiceFactory >& xSMGR      ,
                                                               const ::rtl::OUString&                                        sModuleName);

        //____________________________
        /** @short  retrieve the window state from the container window.

            @param  xWindow
                    must point to the container window of the frame.
                    We use it VCL part here - because the toolkit doesnt
                    provide the right functionality!

            @return [string]
                    contains the information about position and size.
         */
        static ::rtl::OUString implst_getWindowStateFromWindow(const css::uno::Reference< css::awt::XWindow >& xWindow);

        //____________________________
        /** @short  restore the position and size on the container window.

            @param  xSMGR
                    needed to create the configuration access.

            @param  sModuleName
                    identifies the application module, where the
                    information should be setted on.

            @param  sWindowState
                    contains the information about position and size.
         */
        static void implst_setWindowStateOnConfig(const css::uno::Reference< css::lang::XMultiServiceFactory >& xSMGR         ,
                                                  const ::rtl::OUString&                                        sModuleName   ,
                                                  const ::rtl::OUString&                                        sWindowState  );

        //____________________________
        /** @short  restore the position and size on the container window.

            @param  xWindow
                    must point to the container window of the frame.
                    We use it VCL part here - because the toolkit doesnt
                    provide the right functionality!

            @param  sWindowState
                    contains the information about position and size.
         */
        static void implst_setWindowStateOnWindow(const css::uno::Reference< css::awt::XWindow >& xWindow     ,
                                                  const ::rtl::OUString&                          sWindowState);

}; // class PersistentWindowState

} // namespace framework

#endif // #ifndef __FRAMEWORK_HELPER_PERSISTENTWINDOWSTATE_HXX_
<commit_msg>INTEGRATION: CWS fwkbeta01 (1.2.6); FILE MERGED 2004/12/01 12:07:21 as 1.2.6.1: #i38089# restore view data one times only for the same frame<commit_after>/*************************************************************************
 *
 *  $RCSfile: persistentwindowstate.hxx,v $
 *
 *  $Revision: 1.4 $
 *
 *  last change: $Author: kz $ $Date: 2004-12-03 14:04:13 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (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.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#ifndef __FRAMEWORK_HELPER_PERSISTENTWINDOWSTATE_HXX_
#define __FRAMEWORK_HELPER_PERSISTENTWINDOWSTATE_HXX_

//_________________________________________________________________________________________________________________
//  my own includes
//_________________________________________________________________________________________________________________

#ifndef __FRAMEWORK_THREADHELP_THREADHELPBASE_HXX_
#include <threadhelp/threadhelpbase.hxx>
#endif

#ifndef __FRAMEWORK_MACROS_DEBUG_HXX_
#include <macros/debug.hxx>
#endif

#ifndef __FRAMEWORK_MACROS_XINTERFACE_HXX_
#include <macros/xinterface.hxx>
#endif

#ifndef __FRAMEWORK_MACROS_XTYPEPROVIDER_HXX_
#include <macros/xtypeprovider.hxx>
#endif

#ifndef __FRAMEWORK_GENERAL_H_
#include <general.h>
#endif

//_________________________________________________________________________________________________________________
//  interface includes
//_________________________________________________________________________________________________________________

#ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#endif

#ifndef _COM_SUN_STAR_LANG_XINITIALIZATION_HPP_
#include <com/sun/star/lang/XInitialization.hpp>
#endif

#ifndef _COM_SUN_STAR_FRAME_XFRAME_HPP_
#include <com/sun/star/frame/XFrame.hpp>
#endif

#ifndef _COM_SUN_STAR_FRAME_XFRAMEACTIONLISTENER_HPP_
#include <com/sun/star/frame/XFrameActionListener.hpp>
#endif

#ifndef _COM_SUN_STAR_LANG_XEVENTLISTENER_HPP_
#include <com/sun/star/lang/XEventListener.hpp>
#endif

//_________________________________________________________________________________________________________________
//  other includes
//_________________________________________________________________________________________________________________

#ifndef INCLUDED_SVTOOLS_MODULEOPTIONS_HXX
#include <svtools/moduleoptions.hxx>
#endif

#ifndef _CPPUHELPER_WEAK_HXX_
#include <cppuhelper/weak.hxx>
#endif

//_________________________________________________________________________________________________________________
//  const
//_________________________________________________________________________________________________________________

//_________________________________________________________________________________________________________________
//  namespace
//_________________________________________________________________________________________________________________

namespace framework{

//_________________________________________________________________________________________________________________
//  declarations
//_________________________________________________________________________________________________________________

/*-************************************************************************************************************//**
    @short          listener for closing document frames to make her window state persistent
    @descr          It's a feature of our office. If a document window was created by ourself (and not from
                    any external process e.g. the office bean) we save and restore the window state of it
                    corresponding to the document service factory. That means: one instance of this class will be
                    a listener on one frame which container window was created by ourself.
                    We listen for frame action events and everytimes a component will deattached from a frame
                    we store its current position and size to the configuration. Everytimes a new component is
                    attached to a frame first time(!) we restore this informations again.

    @base           ThreadHelpBase
                        guarantee right initialized lock member during startup of instances of this class.

    @base           OWeakObject
                        implements ref counting for this class.

    @devstatus      ready
    @threadsafe     yes
    @modified       06.08.2004 08:41, as96863
*//*-*************************************************************************************************************/
class PersistentWindowState :   // interfaces
                                public css::lang::XTypeProvider,
                                public css::lang::XInitialization,
                                public css::frame::XFrameActionListener, // => XEventListener
                                // baseclasses (order neccessary for right initialization!)
                                private ThreadHelpBase,
                                public  ::cppu::OWeakObject
{
    //________________________________
    // member

    private:

        /// may we need an uno service manager to create own services
        css::uno::Reference< css::lang::XMultiServiceFactory > m_xSMGR;

        /// reference to the frame which was created by the office himself
        css::uno::WeakReference< css::frame::XFrame > m_xFrame;

        /// we call SetWindowState one times only for the same frame!
        sal_Bool m_bWindowStateAlreadySet;

    //________________________________
    // interface

    public:

        //____________________________
        // ctor/dtor
                 PersistentWindowState(const css::uno::Reference< css::lang::XMultiServiceFactory >& xSMGR);
        virtual ~PersistentWindowState(                                                                   );

        //____________________________
        // XInterface, XTypeProvider
        DECLARE_XINTERFACE
        DECLARE_XTYPEPROVIDER

        //____________________________
        // XInitialization
        virtual void SAL_CALL initialize(const css::uno::Sequence< css::uno::Any >& lArguments)
            throw(css::uno::Exception       ,
                  css::uno::RuntimeException);

        //____________________________
        // XFrameActionListener
        virtual void SAL_CALL frameAction(const css::frame::FrameActionEvent& aEvent)
            throw(css::uno::RuntimeException);

        //____________________________
        // XEventListener
        virtual void SAL_CALL disposing(const css::lang::EventObject& aEvent)
            throw(css::uno::RuntimeException);

    //________________________________
    // helper

    private:
        //____________________________
        /** @short  identify the application module, which  is used behind the component
                    of our frame.

            @param  xSMGR
                    needed to create needed uno resources.

            @param  xFrame
                    contains the component, wich must be identified.

            @return [string]
                    a module identifier for the current frame component.
         */
        static ::rtl::OUString implst_identifyModule(const css::uno::Reference< css::lang::XMultiServiceFactory >& xSMGR ,
                                                     const css::uno::Reference< css::frame::XFrame >&              xFrame);

        //____________________________
        /** @short  retrieve the window state from the configuration.

            @param  xSMGR
                    needed to create the configuration access.

            @param  sModuleName
                    identifies the application module, where the
                    information should be getted for.

            @return [string]
                    contains the information about position and size.
         */
        static ::rtl::OUString implst_getWindowStateFromConfig(const css::uno::Reference< css::lang::XMultiServiceFactory >& xSMGR      ,
                                                               const ::rtl::OUString&                                        sModuleName);

        //____________________________
        /** @short  retrieve the window state from the container window.

            @param  xWindow
                    must point to the container window of the frame.
                    We use it VCL part here - because the toolkit doesnt
                    provide the right functionality!

            @return [string]
                    contains the information about position and size.
         */
        static ::rtl::OUString implst_getWindowStateFromWindow(const css::uno::Reference< css::awt::XWindow >& xWindow);

        //____________________________
        /** @short  restore the position and size on the container window.

            @param  xSMGR
                    needed to create the configuration access.

            @param  sModuleName
                    identifies the application module, where the
                    information should be setted on.

            @param  sWindowState
                    contains the information about position and size.
         */
        static void implst_setWindowStateOnConfig(const css::uno::Reference< css::lang::XMultiServiceFactory >& xSMGR         ,
                                                  const ::rtl::OUString&                                        sModuleName   ,
                                                  const ::rtl::OUString&                                        sWindowState  );

        //____________________________
        /** @short  restore the position and size on the container window.

            @param  xWindow
                    must point to the container window of the frame.
                    We use it VCL part here - because the toolkit doesnt
                    provide the right functionality!

            @param  sWindowState
                    contains the information about position and size.
         */
        static void implst_setWindowStateOnWindow(const css::uno::Reference< css::awt::XWindow >& xWindow     ,
                                                  const ::rtl::OUString&                          sWindowState);

}; // class PersistentWindowState

} // namespace framework

#endif // #ifndef __FRAMEWORK_HELPER_PERSISTENTWINDOWSTATE_HXX_
<|endoftext|>


<commit_before>#include "stdafx.h"

#include "Trap.h"
#include "ETypes.h"
#include <ATF/global.hpp>
#include <ATF/_qry_case_addpvppoint.hpp>

namespace GameServer
{
    namespace Fixes
    {
        void CTrap::load()
        {
            auto& core = ATF::CATFCore::get_instance();
            core.set_hook(&ATF::CTrap::RecvKillMessage, &CTrap::RecvKillMessage);
            core.set_hook(&ATF::CTrap::SendMsg_FixPosition, &CTrap::SendMsg_FixPosition);
            core.set_hook(&ATF::CPlayer::pc_MakeTrapRequest, &CTrap::pc_MakeTrapRequest);

        }

        void CTrap::unload()
        {
            auto& core = ATF::CATFCore::get_instance();
            core.unset_hook(&ATF::CTrap::RecvKillMessage);
            core.unset_hook(&ATF::CTrap::SendMsg_FixPosition);
            core.unset_hook(&ATF::CPlayer::pc_MakeTrapRequest);
        }

        void CTrap::loop()
        {
        }

        ModuleVersion_t CTrap::get_version()
        {
            return ATF::usVersion;
        }

        ModuleName_t CTrap::get_name()
        {
            static const ModuleName_t name = "fix_trap";
            return name;
        }

        void CTrap::configure(
            const rapidjson::Value & nodeConfig)
        {
            UNREFERENCED_PARAMETER(nodeConfig);
        }

        void WINAPIV CTrap::RecvKillMessage(
            ATF::CTrap* pObj,
            ATF::CCharacter* pDier,
            ATF::info::CTrapRecvKillMessage70_ptr next)
        {
            UNREFERENCED_PARAMETER(next);
            if (pObj->m_pMaster)
            {
                if (pObj->m_pMaster->m_bLive
                    && pObj->m_pMaster->m_bOper
                    && pObj->m_pMaster->m_dwObjSerial == pObj->m_dwMasterSerial)
                {
                    pObj->m_pMaster->vfptr->RecvKillMessage(pObj->m_pMaster, pDier);
                }
                return;
            }

            if (!pDier->m_ObjID.m_byID && pObj->m_dwMasterSerial != -1)
            {
                auto pPlayerDier = (ATF::CPlayer *)pDier;

                auto dDierPvPPoint = pPlayerDier->m_Param.GetPvPPoint() + 10000.0;
                auto dMasterPvPPoint = pObj->m_dMasterPvPPoint + 10000.0;

                auto dAlterPoint = dDierPvPPoint / dMasterPvPPoint * 500.0 + 0.5;
                if (dAlterPoint > pPlayerDier->m_Param.GetPvPPoint())
                    dAlterPoint = pPlayerDier->m_Param.GetPvPPoint();

                // todo : replcat coeff in config
                dAlterPoint *= 0.3;

                if (dAlterPoint < 1.0)
                    dAlterPoint = 1.0;

                if (dAlterPoint > 100000000.0)
                    dAlterPoint = 100000000.0;

                ATF::_qry_case_addpvppoint qryAddpvppoint;
                qryAddpvppoint.dwSerial = pObj->m_dwMasterSerial;
                qryAddpvppoint.dwPoint = (unsigned int)floor(dAlterPoint);
                qryAddpvppoint.dwCashBag = (unsigned int)floor(dAlterPoint);

                ATF::global::g_MainThread->PushDQSData(0xFFFFFFFF, 0, 13, (char *)&qryAddpvppoint, qryAddpvppoint.size());

                pPlayerDier->AlterPvPPoint(-dAlterPoint, ATF::PVP_ALTER_TYPE::die_dec, pObj->m_dwMasterSerial);
            }
        }

        void WINAPIV CTrap::SendMsg_FixPosition(
            ATF::CTrap* pTrap,
            int n,
            ATF::info::CTrapSendMsg_FixPosition82_ptr next)
        {
            ATF::CPlayer* pPlayer = &ATF::global::g_Player[n];
            if (pTrap->m_dwMasterSerial != pPlayer->m_Param.GetCharSerial())
            {
                if (!pPlayer->m_EP.GetEff_State(23))
                {
                    return;
                }
            }

            next(pTrap, n);
        }

        void WINAPIV CTrap::pc_MakeTrapRequest(
            ATF::CPlayer * pObj,
            uint16_t wSkillIndex,
            uint16_t wTrapItemSerial,
            float * pfPos,
            uint16_t * pConsumeSerial,
            ATF::info::CPlayerpc_MakeTrapRequest1783_ptr next)
        {
            do
            {
                if (pObj->m_bMapLoading)
                    break;

                auto pTrapItem = pObj->m_Param.m_dbInven.GetPtrFromSerial(wTrapItemSerial);
                if (!pTrapItem)
                    break;

                if (pTrapItem->m_byTableCode != (BYTE)e_code_item_table::tbl_code_trap)
                    break;

                auto& tblItemData = ATF::global::g_MainThread->m_tblItemData[pTrapItem->m_byTableCode];
                ATF::_TrapItem_fld* pTrapFld = (ATF::_TrapItem_fld*)tblItemData.GetRecord(pTrapItem->m_wItemIndex);
                if (!pTrapFld)
                    break;

                if (pObj->GetLevel() > pTrapFld->m_nUpLevelLim)
                    break;

                if (pObj->GetLevel() < pTrapFld->m_nLevelLim)
                    break;

                next(pObj, wSkillIndex, wTrapItemSerial, pfPos, pConsumeSerial);
            } while (false);
        }
    }
}<commit_msg>Refactoring<commit_after>#include "stdafx.h"

#include "Trap.h"
#include "ETypes.h"
#include <ATF/global.hpp>
#include <ATF/_qry_case_addpvppoint.hpp>

namespace GameServer
{
    namespace Fixes
    {
        void CTrap::load()
        {
            auto& core = ATF::CATFCore::get_instance();
            core.set_hook(&ATF::CTrap::RecvKillMessage, &CTrap::RecvKillMessage);
            core.set_hook(&ATF::CTrap::SendMsg_FixPosition, &CTrap::SendMsg_FixPosition);
            core.set_hook(&ATF::CPlayer::pc_MakeTrapRequest, &CTrap::pc_MakeTrapRequest);

        }

        void CTrap::unload()
        {
            auto& core = ATF::CATFCore::get_instance();
            core.unset_hook(&ATF::CTrap::RecvKillMessage);
            core.unset_hook(&ATF::CTrap::SendMsg_FixPosition);
            core.unset_hook(&ATF::CPlayer::pc_MakeTrapRequest);
        }

        void CTrap::loop()
        {
        }

        ModuleVersion_t CTrap::get_version()
        {
            return ATF::usVersion;
        }

        ModuleName_t CTrap::get_name()
        {
            static const ModuleName_t name = "fix_trap";
            return name;
        }

        void CTrap::configure(
            const rapidjson::Value & nodeConfig)
        {
            UNREFERENCED_PARAMETER(nodeConfig);
        }

        void WINAPIV CTrap::RecvKillMessage(
            ATF::CTrap* pObj,
            ATF::CCharacter* pDier,
            ATF::info::CTrapRecvKillMessage70_ptr next)
        {
            UNREFERENCED_PARAMETER(next);
            if (pObj->m_pMaster)
            {
                if (pObj->m_pMaster->m_bLive
                    && pObj->m_pMaster->m_bOper
                    && pObj->m_pMaster->m_dwObjSerial == pObj->m_dwMasterSerial)
                {
                    pObj->m_pMaster->RecvKillMessage(pDier);
                }
                return;
            }

            if (pDier->m_ObjID.m_byID == (BYTE)e_obj_id::obj_id_player && pObj->m_dwMasterSerial != -1)
            {
                auto pPlayerDier = (ATF::CPlayer *)pDier;

                auto dDierPvPPoint = pPlayerDier->m_Param.GetPvPPoint() + 10000.0;
                auto dMasterPvPPoint = pObj->m_dMasterPvPPoint + 10000.0;

                auto dAlterPoint = dDierPvPPoint / dMasterPvPPoint * 500.0 + 0.5;
                if (dAlterPoint > pPlayerDier->m_Param.GetPvPPoint())
                    dAlterPoint = pPlayerDier->m_Param.GetPvPPoint();

                // todo : replcat coeff in config
                dAlterPoint *= 0.3;

                if (dAlterPoint < 1.0)
                    dAlterPoint = 1.0;

                if (dAlterPoint > 100000000.0)
                    dAlterPoint = 100000000.0;

                ATF::_qry_case_addpvppoint qryAddpvppoint;
                qryAddpvppoint.dwSerial = pObj->m_dwMasterSerial;
                qryAddpvppoint.dwPoint = (unsigned int)floor(dAlterPoint);
                qryAddpvppoint.dwCashBag = (unsigned int)floor(dAlterPoint);

                ATF::global::g_MainThread->PushDQSData(0xFFFFFFFF, 0, 13, (char *)&qryAddpvppoint, qryAddpvppoint.size());

                pPlayerDier->AlterPvPPoint(-dAlterPoint, ATF::PVP_ALTER_TYPE::die_dec, pObj->m_dwMasterSerial);
            }
        }

        void WINAPIV CTrap::SendMsg_FixPosition(
            ATF::CTrap* pTrap,
            int n,
            ATF::info::CTrapSendMsg_FixPosition82_ptr next)
        {
            ATF::CPlayer* pPlayer = &ATF::global::g_Player[n];
            if (pTrap->m_dwMasterSerial != pPlayer->m_Param.GetCharSerial())
            {
                if (!pPlayer->m_EP.GetEff_State(23))
                {
                    return;
                }
            }

            next(pTrap, n);
        }

        void WINAPIV CTrap::pc_MakeTrapRequest(
            ATF::CPlayer * pObj,
            uint16_t wSkillIndex,
            uint16_t wTrapItemSerial,
            float * pfPos,
            uint16_t * pConsumeSerial,
            ATF::info::CPlayerpc_MakeTrapRequest1783_ptr next)
        {
            do
            {
                if (pObj->m_bMapLoading)
                    break;

                auto pTrapItem = pObj->m_Param.m_dbInven.GetPtrFromSerial(wTrapItemSerial);
                if (!pTrapItem)
                    break;

                if (pTrapItem->m_byTableCode != (BYTE)e_code_item_table::tbl_code_trap)
                    break;

                auto& tblItemData = ATF::global::g_MainThread->m_tblItemData[pTrapItem->m_byTableCode];
                ATF::_TrapItem_fld* pTrapFld = (ATF::_TrapItem_fld*)tblItemData.GetRecord(pTrapItem->m_wItemIndex);
                if (!pTrapFld)
                    break;

                if (pObj->GetLevel() > pTrapFld->m_nUpLevelLim)
                    break;

                if (pObj->GetLevel() < pTrapFld->m_nLevelLim)
                    break;

                next(pObj, wSkillIndex, wTrapItemSerial, pfPos, pConsumeSerial);
            } while (false);
        }
    }
}<|endoftext|>