<commit_before>// $Id$
//
// Ported from JTS junit/linearref/AbstractIndexedLineTest.java rev. 1.10
// and  junit/linearref/LengthIndexedLineTest.java rev. 1.10

#include <tut.hpp>
#include <utility.h>
// geos
#include <geos/platform.h>
#include <geos/io/WKTReader.h>
#include <geos/geom/PrecisionModel.h>
#include <geos/geom/GeometryFactory.h>
#include <geos/geom/Geometry.h> // required for use in auto_ptr
#include <geos/geom/LineString.h>
#include <geos/geom/Coordinate.h>
#include <geos/linearref/LengthIndexedLine.h>

// std
#include <cmath>
#include <sstream>
#include <string>
#include <memory>

using namespace geos::geom;
using namespace geos::linearref;
using namespace std;

/**
 * Tests the {@link LocationIndexedLine} class
 */

namespace tut {

    typedef auto_ptr<Geometry> GeomPtr;
    static const double TOLERANCE_DIST = 0.001;

    struct test_lengthindexedline_data
    {
      test_lengthindexedline_data()
          : pm(), gf(&pm), reader(&gf)
      {}

      PrecisionModel pm;
      GeometryFactory gf;
      geos::io::WKTReader reader;

      void checkExpected(Geometry* result, string const& expected)
      {
          GeomPtr subLine(reader.read(expected));
          ensure_equals_geometry(subLine.get(), result);
      }

      void checkExpected(Geometry* result, const Geometry* expected)
      {
          ensure_equals_geometry(expected, result);
      }

      void runIndicesOfThenExtract(string const& inputStr, string const& subLineStr)
      {
          GeomPtr input(reader.read(inputStr));
          GeomPtr subLine(reader.read(subLineStr));
          GeomPtr result(indicesOfThenExtract(input.get(), subLine.get()));

          checkExpected(result.get(), subLine.get());
      }

        bool indexOfAfterCheck(Geometry* linearGeom, Coordinate testPt)
        {
            LengthIndexedLine indexedLine(linearGeom);

            // check locations are consecutive
            double loc1 = indexedLine.indexOf(testPt);
            double loc2 = indexedLine.indexOfAfter(testPt, loc1);
            if (loc2 <= loc1) return false;

            // check extracted points are the same as the input
            Coordinate pt1 = indexedLine.extractPoint(loc1);
            Coordinate pt2 = indexedLine.extractPoint(loc2);
            if (! pt1.equals2D(testPt)) return false;
            if (! pt2.equals2D(testPt)) return false;

            return true;
        }

        void runIndexOfAfterTest(string const& inputStr, string const& testPtWKT)
        {
            GeomPtr input(reader.read(inputStr));
            GeomPtr testPoint(reader.read(testPtWKT));
            const Coordinate* testPt = testPoint->getCoordinate();
            bool resultOK = indexOfAfterCheck(input.get(), *testPt);
            ensure(resultOK);
        }

        void runOffsetTest(string const& inputWKT, string const& testPtWKT,
                           double offsetDistance, string const& expectedPtWKT)
        {
            GeomPtr input(reader.read(inputWKT));
            GeomPtr testPoint(reader.read(testPtWKT));
            GeomPtr expectedPoint(reader.read(expectedPtWKT));
            const Coordinate* testPt = testPoint->getCoordinate();
            const Coordinate* expectedPt = expectedPoint->getCoordinate();
            Coordinate offsetPt = extractOffsetAt(input.get(), *testPt, offsetDistance);

            bool isOk = offsetPt.distance(*expectedPt) < TOLERANCE_DIST;
            if (! isOk)
                cout << "Expected = " << *expectedPoint << "  Actual = " << offsetPt << endl;
            ensure(isOk);
        }

        Coordinate extractOffsetAt(Geometry* linearGeom, Coordinate testPt, double offsetDistance)
        {
            LengthIndexedLine indexedLine(linearGeom);
            double index = indexedLine.indexOf(testPt);
            return indexedLine.extractPoint(index, offsetDistance);
        }

        void checkExtractLine(const char* wkt, double start, double end, const char* expected)
        {
            string wktstr(wkt);
            GeomPtr linearGeom(reader.read(wktstr));
            LengthIndexedLine indexedLine(linearGeom.get());
            GeomPtr result(indexedLine.extractLine(start, end));
            checkExpected(result.get(), expected);
        }

        Geometry* indicesOfThenExtract(Geometry* linearGeom, Geometry* subLine)
        {
            LengthIndexedLine indexedLine(linearGeom);
            double* loc = indexedLine.indicesOf(subLine);
            Geometry* result = indexedLine.extractLine(loc[0], loc[1]);
            delete [] loc;
            return result;
        }

    }; // struct test_lengthindexedline_data

    typedef test_group<test_lengthindexedline_data> group;
    typedef group::object object;

    group test_lengthindexedline_group("geos::linearref::LocationIndexedLine");

    //1 - testML
    template<>
  template<>
  void object::test<1>()
  {
      runIndicesOfThenExtract("MULTILINESTRING ((0 0, 10 10), (20 20, 30 30))",
                            "MULTILINESTRING ((1 1, 10 10), (20 20, 25 25))");
  }

      //2 - testPartOfSegmentNoVertex
  template<>
  template<>
  void object::test<2>()
  {
  runIndicesOfThenExtract("LINESTRING (0 0, 10 10, 20 20)",
          "LINESTRING (1 1, 9 9)");
}

//3 - testPartOfSegmentContainingVertex()
  template<>
  template<>
  void object::test<3>()
{
  runIndicesOfThenExtract("LINESTRING (0 0, 10 10, 20 20)",
          "LINESTRING (5 5, 10 10, 15 15)");
}

/**
 * Tests that duplicate coordinates are handled correctly.
 *
 * @throws Exception
 */
// 4 - testPartOfSegmentContainingDuplicateCoords
  template<>
  template<>
  void object::test<4>()
{
  runIndicesOfThenExtract("LINESTRING (0 0, 10 10, 10 10, 20 20)",
          "LINESTRING (5 5, 10 10, 10 10, 15 15)");
}

/**
 * Following tests check that correct portion of loop is identified.
 * This requires that the correct vertex for (0,0) is selected.
 */

//5 - testLoopWithStartSubLine
  template<>
  template<>
  void object::test<5>()
{
  runIndicesOfThenExtract("LINESTRING (0 0, 0 10, 10 10, 10 0, 0 0)",
          "LINESTRING (0 0, 0 10, 10 10)");
}

//6 - testLoopWithEndingSubLine()
  template<>
  template<>
  void object::test<6>()
{
  runIndicesOfThenExtract("LINESTRING (0 0, 0 10, 10 10, 10 0, 0 0)",
          "LINESTRING (10 10, 10 0, 0 0)");
}

// test a subline equal to the parent loop
//7 - testLoopWithIdenticalSubLine()
  template<>
  template<>
  void object::test<7>()
{
  runIndicesOfThenExtract("LINESTRING (0 0, 0 10, 10 10, 10 0, 0 0)",
          "LINESTRING (0 0, 0 10, 10 10, 10 0, 0 0)");
}

// test a zero-length subline equal to the start point
//8 - testZeroLenSubLineAtStart()
  template<>
  template<>
  void object::test<8>()
{
  runIndicesOfThenExtract("LINESTRING (0 0, 0 10, 10 10, 10 0, 0 0)",
          "LINESTRING (0 0, 0 0)");
}

// test a zero-length subline equal to a mid point
//9 - testZeroLenSubLineAtMidVertex()
  template<>
  template<>
  void object::test<9>()
{
  runIndicesOfThenExtract("LINESTRING (0 0, 0 10, 10 10, 10 0, 0 0)",
          "LINESTRING (10 10, 10 10)");
}

//10 - testIndexOfAfterSquare()
  template<>
  template<>
  void object::test<10>()
{
  runIndexOfAfterTest("LINESTRING (0 0, 0 10, 10 10, 10 0, 0 0)",
          "POINT (0 0)");
}

//11 - testIndexOfAfterRibbon()
  template<>
  template<>
  void object::test<11>()
{
  runIndexOfAfterTest("LINESTRING (0 0, 0 60, 50 60, 50 20, -20 20)",
          "POINT (0 20)");
}

//12 -  testOffsetStartPoint()
  template<>
  template<>
  void object::test<12>()
{
  runOffsetTest("LINESTRING (0 0, 10 10, 10 10, 20 20)", "POINT(0 0)", 1.0, "POINT (-0.7071067811865475 0.7071067811865475)");
  runOffsetTest("LINESTRING (0 0, 10 10, 10 10, 20 20)", "POINT(0 0)", -1.0, "POINT (0.7071067811865475 -0.7071067811865475)");
  runOffsetTest("LINESTRING (0 0, 10 10, 10 10, 20 20)", "POINT(10 10)", 5.0, "POINT (6.464466094067262 13.535533905932738)");
  runOffsetTest("LINESTRING (0 0, 10 10, 10 10, 20 20)", "POINT(10 10)", -5.0, "POINT (13.535533905932738 6.464466094067262)");
}

//13 - testExtractLineBeyondRange()
  template<>
  template<>
  void object::test<13>()
{
  checkExtractLine("LINESTRING (0 0, 10 10)", -100, 100, "LINESTRING (0 0, 10 10)");
}

//14 - testExtractLineReverse()
  template<>
  template<>
  void object::test<14>()
{
  checkExtractLine("LINESTRING (0 0, 10 0)", 9, 1, "LINESTRING (9 0, 1 0)");
}

//15 - testExtractLineReverseMulti()
  template<>
  template<>
  void object::test<15>()
{
  checkExtractLine("MULTILINESTRING ((0 0, 10 0), (20 0, 25 0, 30 0))",
                   19, 1, "MULTILINESTRING ((29 0, 25 0, 20 0), (10 0, 1 0))");
}

//16 - testExtractLineNegative()
  template<>
  template<>
  void object::test<16>()
{
  checkExtractLine("LINESTRING (0 0, 10 0)", -9, -1, "LINESTRING (1 0, 9 0)");
}

//17 - testExtractLineNegativeReverse()
  template<>
  template<>
  void object::test<17>()
{
  checkExtractLine("LINESTRING (0 0, 10 0)", -1, -9, "LINESTRING (9 0, 1 0)");
}

//18 - testExtractLineIndexAtEndpoint()
  template<>
  template<>
  void object::test<18>()
{
  checkExtractLine("MULTILINESTRING ((0 0, 10 0), (20 0, 25 0, 30 0))",
                   10, -1, "LINESTRING (20 0, 25 0, 29 0)");
}

//19 - testExtractLineBothIndicesAtEndpoint()
  template<>
  template<>
  void object::test<19>()
{
  checkExtractLine("MULTILINESTRING ((0 0, 10 0), (20 0, 25 0, 30 0))",
                   10, 10, "LINESTRING (20 0, 20 0)");
}

//20 - testExtractLineBothIndicesAtEndpointNegative()
  template<>
  template<>
  void object::test<20>()
{
  checkExtractLine("MULTILINESTRING ((0 0, 10 0), (20 0, 25 0, 30 0))",
                   -10, 10, "LINESTRING (20 0, 20 0)");
}

//21 - testExtractPointBeyondRange()
  template<>
  template<>
  void object::test<21>()
{
  GeomPtr linearGeom(reader.read("LINESTRING (0 0, 10 10)"));
  LengthIndexedLine indexedLine(linearGeom.get());
  Coordinate pt = indexedLine.extractPoint(100);
  ensure(pt == Coordinate(10, 10));

  Coordinate pt2 = indexedLine.extractPoint(0);
  ensure(pt2 == Coordinate(0, 0));
}

//22 - testProjectPointWithDuplicateCoords()
  template<>
  template<>
  void object::test<22>()
{
  GeomPtr linearGeom(reader.read("LINESTRING (0 0, 10 0, 10 0, 20 0)"));
  LengthIndexedLine indexedLine(linearGeom.get());
  double projIndex = indexedLine.project(Coordinate(10, 1));
  ensure(projIndex == 10.0);
}

/**
 * Tests that z values are interpolated
 *
 */
//23 - testComputeZ()
  template<>
  template<>
  void object::test<23>()
{
  GeomPtr linearGeom(reader.read("LINESTRING (0 0 0, 10 10 10)"));
  LengthIndexedLine indexedLine(linearGeom.get());
  double projIndex = indexedLine.project(Coordinate(5, 5));
  Coordinate projPt = indexedLine.extractPoint(projIndex);
//    System.out.println(projPt);
  ensure(projPt.equals3D(Coordinate(5, 5, 5)));
}

/**
 * Tests that if the input does not have Z ordinates, neither does the output.
 *
 */
//24 - testComputeZNaN()
  template<>
  template<>
  void object::test<24>()
{

  GeomPtr linearGeom(reader.read("LINESTRING (0 0, 10 10 10)"));
  LengthIndexedLine indexedLine(linearGeom.get());
  double projIndex = indexedLine.project(Coordinate(5, 5));
  Coordinate projPt = indexedLine.extractPoint(projIndex);
  ensure(0 != ISNAN(projPt.z));
}

}
<commit_msg>Tidy up messy code in tests/unit/linearref<commit_after>// $Id$
//
// Ported from JTS junit/linearref/AbstractIndexedLineTest.java rev. 1.10
// and  junit/linearref/LengthIndexedLineTest.java rev. 1.10

#include <tut.hpp>
#include <utility.h>
// geos
#include <geos/platform.h>
#include <geos/io/WKTReader.h>
#include <geos/geom/PrecisionModel.h>
#include <geos/geom/GeometryFactory.h>
#include <geos/geom/Geometry.h> // required for use in auto_ptr
#include <geos/geom/LineString.h>
#include <geos/geom/Coordinate.h>
#include <geos/linearref/LengthIndexedLine.h>

// std
#include <cmath>
#include <sstream>
#include <string>
#include <memory>

using namespace geos::geom;
using namespace geos::linearref;
using namespace std;

/**
 * Tests the {@link LocationIndexedLine} class
 */
namespace tut {

typedef auto_ptr<Geometry> GeomPtr;
static const double TOLERANCE_DIST = 0.001;

struct test_lengthindexedline_data
{
    test_lengthindexedline_data()
        : pm(), gf(&pm), reader(&gf)
    {}

    PrecisionModel pm;
    GeometryFactory gf;
    geos::io::WKTReader reader;

    void checkExpected(Geometry* result, string const& expected)
    {
        GeomPtr subLine(reader.read(expected));
        ensure_equals_geometry(subLine.get(), result);
    }

    void checkExpected(Geometry* result, const Geometry* expected)
    {
        ensure_equals_geometry(expected, result);
    }

    void runIndicesOfThenExtract(string const& inputStr, string const& subLineStr)
    {
        GeomPtr input(reader.read(inputStr));
        GeomPtr subLine(reader.read(subLineStr));
        GeomPtr result(indicesOfThenExtract(input.get(), subLine.get()));

        checkExpected(result.get(), subLine.get());
    }

    bool indexOfAfterCheck(Geometry* linearGeom, Coordinate testPt)
    {
        LengthIndexedLine indexedLine(linearGeom);

        // check locations are consecutive
        double loc1 = indexedLine.indexOf(testPt);
        double loc2 = indexedLine.indexOfAfter(testPt, loc1);
        if (loc2 <= loc1) return false;

        // check extracted points are the same as the input
        Coordinate pt1 = indexedLine.extractPoint(loc1);
        Coordinate pt2 = indexedLine.extractPoint(loc2);
        if (! pt1.equals2D(testPt)) return false;
        if (! pt2.equals2D(testPt)) return false;

        return true;
    }

    void runIndexOfAfterTest(string const& inputStr, string const& testPtWKT)
    {
        GeomPtr input(reader.read(inputStr));
        GeomPtr testPoint(reader.read(testPtWKT));
        const Coordinate* testPt = testPoint->getCoordinate();
        bool resultOK = indexOfAfterCheck(input.get(), *testPt);
        ensure(resultOK);
    }

    void runOffsetTest(string const& inputWKT, string const& testPtWKT,
                       double offsetDistance, string const& expectedPtWKT)
    {
        GeomPtr input(reader.read(inputWKT));
        GeomPtr testPoint(reader.read(testPtWKT));
        GeomPtr expectedPoint(reader.read(expectedPtWKT));
        const Coordinate* testPt = testPoint->getCoordinate();
        const Coordinate* expectedPt = expectedPoint->getCoordinate();
        Coordinate offsetPt = extractOffsetAt(input.get(), *testPt, offsetDistance);

        bool isOk = offsetPt.distance(*expectedPt) < TOLERANCE_DIST;
        if (! isOk)
            cout << "Expected = " << *expectedPoint << "  Actual = " << offsetPt << endl;
        ensure(isOk);
    }

    Coordinate extractOffsetAt(Geometry* linearGeom, Coordinate testPt, double offsetDistance)
    {
        LengthIndexedLine indexedLine(linearGeom);
        double index = indexedLine.indexOf(testPt);
        return indexedLine.extractPoint(index, offsetDistance);
    }

    void checkExtractLine(const char* wkt, double start, double end, const char* expected)
    {
        string wktstr(wkt);
        GeomPtr linearGeom(reader.read(wktstr));
        LengthIndexedLine indexedLine(linearGeom.get());
        GeomPtr result(indexedLine.extractLine(start, end));
        checkExpected(result.get(), expected);
    }

    Geometry* indicesOfThenExtract(Geometry* linearGeom, Geometry* subLine)
    {
        LengthIndexedLine indexedLine(linearGeom);
        double* loc = indexedLine.indicesOf(subLine);
        Geometry* result = indexedLine.extractLine(loc[0], loc[1]);
        delete [] loc;
        return result;
    }

}; // struct test_lengthindexedline_data

typedef test_group<test_lengthindexedline_data> group;
typedef group::object object;

group test_lengthindexedline_group("geos::linearref::LocationIndexedLine");

//1 - testML
template<>
template<>
void object::test<1>()
{
    runIndicesOfThenExtract("MULTILINESTRING ((0 0, 10 10), (20 20, 30 30))",
                            "MULTILINESTRING ((1 1, 10 10), (20 20, 25 25))");
}

//2 - testPartOfSegmentNoVertex
template<>
template<>
void object::test<2>()
{
    runIndicesOfThenExtract("LINESTRING (0 0, 10 10, 20 20)",
                            "LINESTRING (1 1, 9 9)");
}

//3 - testPartOfSegmentContainingVertex()
template<>
template<>
void object::test<3>()
{
    runIndicesOfThenExtract("LINESTRING (0 0, 10 10, 20 20)",
                            "LINESTRING (5 5, 10 10, 15 15)");
}

/**
 * Tests that duplicate coordinates are handled correctly.
 *
 * @throws Exception
 */
// 4 - testPartOfSegmentContainingDuplicateCoords
template<>
template<>
void object::test<4>()
{
    runIndicesOfThenExtract("LINESTRING (0 0, 10 10, 10 10, 20 20)",
                            "LINESTRING (5 5, 10 10, 10 10, 15 15)");
}

/**
 * Following tests check that correct portion of loop is identified.
 * This requires that the correct vertex for (0,0) is selected.
 */

//5 - testLoopWithStartSubLine
template<>
template<>
void object::test<5>()
{
    runIndicesOfThenExtract("LINESTRING (0 0, 0 10, 10 10, 10 0, 0 0)",
                            "LINESTRING (0 0, 0 10, 10 10)");
}

//6 - testLoopWithEndingSubLine()
template<>
template<>
void object::test<6>()
{
    runIndicesOfThenExtract("LINESTRING (0 0, 0 10, 10 10, 10 0, 0 0)",
                            "LINESTRING (10 10, 10 0, 0 0)");
}

// test a subline equal to the parent loop
//7 - testLoopWithIdenticalSubLine()
template<>
template<>
void object::test<7>()
{
    runIndicesOfThenExtract("LINESTRING (0 0, 0 10, 10 10, 10 0, 0 0)",
                            "LINESTRING (0 0, 0 10, 10 10, 10 0, 0 0)");
}

// test a zero-length subline equal to the start point
//8 - testZeroLenSubLineAtStart()
template<>
template<>
void object::test<8>()
{
    runIndicesOfThenExtract("LINESTRING (0 0, 0 10, 10 10, 10 0, 0 0)",
                            "LINESTRING (0 0, 0 0)");
}

// test a zero-length subline equal to a mid point
//9 - testZeroLenSubLineAtMidVertex()
template<>
template<>
void object::test<9>()
{
    runIndicesOfThenExtract("LINESTRING (0 0, 0 10, 10 10, 10 0, 0 0)",
                            "LINESTRING (10 10, 10 10)");
}

//10 - testIndexOfAfterSquare()
template<>
template<>
void object::test<10>()
{
    runIndexOfAfterTest("LINESTRING (0 0, 0 10, 10 10, 10 0, 0 0)",
                        "POINT (0 0)");
}

//11 - testIndexOfAfterRibbon()
template<>
template<>
void object::test<11>()
{
    runIndexOfAfterTest("LINESTRING (0 0, 0 60, 50 60, 50 20, -20 20)",
                        "POINT (0 20)");
}

//12 -  testOffsetStartPoint()
template<>
template<>
void object::test<12>()
{
    runOffsetTest("LINESTRING (0 0, 10 10, 10 10, 20 20)", "POINT(0 0)", 1.0, "POINT (-0.7071067811865475 0.7071067811865475)");
    runOffsetTest("LINESTRING (0 0, 10 10, 10 10, 20 20)", "POINT(0 0)", -1.0, "POINT (0.7071067811865475 -0.7071067811865475)");
    runOffsetTest("LINESTRING (0 0, 10 10, 10 10, 20 20)", "POINT(10 10)", 5.0, "POINT (6.464466094067262 13.535533905932738)");
    runOffsetTest("LINESTRING (0 0, 10 10, 10 10, 20 20)", "POINT(10 10)", -5.0, "POINT (13.535533905932738 6.464466094067262)");
}

//13 - testExtractLineBeyondRange()
template<>
template<>
void object::test<13>()
{
    checkExtractLine("LINESTRING (0 0, 10 10)", -100, 100, "LINESTRING (0 0, 10 10)");
}

//14 - testExtractLineReverse()
template<>
template<>
void object::test<14>()
{
    checkExtractLine("LINESTRING (0 0, 10 0)", 9, 1, "LINESTRING (9 0, 1 0)");
}

//15 - testExtractLineReverseMulti()
template<>
template<>
void object::test<15>()
{
    checkExtractLine("MULTILINESTRING ((0 0, 10 0), (20 0, 25 0, 30 0))",
                     19, 1, "MULTILINESTRING ((29 0, 25 0, 20 0), (10 0, 1 0))");
}

//16 - testExtractLineNegative()
template<>
template<>
void object::test<16>()
{
    checkExtractLine("LINESTRING (0 0, 10 0)", -9, -1, "LINESTRING (1 0, 9 0)");
}

//17 - testExtractLineNegativeReverse()
template<>
template<>
void object::test<17>()
{
    checkExtractLine("LINESTRING (0 0, 10 0)", -1, -9, "LINESTRING (9 0, 1 0)");
}

//18 - testExtractLineIndexAtEndpoint()
template<>
template<>
void object::test<18>()
{
    checkExtractLine("MULTILINESTRING ((0 0, 10 0), (20 0, 25 0, 30 0))",
                     10, -1, "LINESTRING (20 0, 25 0, 29 0)");
}

//19 - testExtractLineBothIndicesAtEndpoint()
template<>
template<>
void object::test<19>()
{
    checkExtractLine("MULTILINESTRING ((0 0, 10 0), (20 0, 25 0, 30 0))",
                     10, 10, "LINESTRING (20 0, 20 0)");
}

//20 - testExtractLineBothIndicesAtEndpointNegative()
template<>
template<>
void object::test<20>()
{
    checkExtractLine("MULTILINESTRING ((0 0, 10 0), (20 0, 25 0, 30 0))",
                     -10, 10, "LINESTRING (20 0, 20 0)");
}

//21 - testExtractPointBeyondRange()
template<>
template<>
void object::test<21>()
{
    GeomPtr linearGeom(reader.read("LINESTRING (0 0, 10 10)"));
    LengthIndexedLine indexedLine(linearGeom.get());
    Coordinate pt = indexedLine.extractPoint(100);
    ensure(pt == Coordinate(10, 10));

    Coordinate pt2 = indexedLine.extractPoint(0);
    ensure(pt2 == Coordinate(0, 0));
}

//22 - testProjectPointWithDuplicateCoords()
template<>
template<>
void object::test<22>()
{
    GeomPtr linearGeom(reader.read("LINESTRING (0 0, 10 0, 10 0, 20 0)"));
    LengthIndexedLine indexedLine(linearGeom.get());
    double projIndex = indexedLine.project(Coordinate(10, 1));
    ensure(projIndex == 10.0);
}

/**
 * Tests that z values are interpolated
 *
 */
//23 - testComputeZ()
template<>
template<>
void object::test<23>()
{
    GeomPtr linearGeom(reader.read("LINESTRING (0 0 0, 10 10 10)"));
    LengthIndexedLine indexedLine(linearGeom.get());
    double projIndex = indexedLine.project(Coordinate(5, 5));
    Coordinate projPt = indexedLine.extractPoint(projIndex);
    //    System.out.println(projPt);
    ensure(projPt.equals3D(Coordinate(5, 5, 5)));
}

/**
 * Tests that if the input does not have Z ordinates, neither does the output.
 *
 */
//24 - testComputeZNaN()
template<>
template<>
void object::test<24>()
{

    GeomPtr linearGeom(reader.read("LINESTRING (0 0, 10 10 10)"));
    LengthIndexedLine indexedLine(linearGeom.get());
    double projIndex = indexedLine.project(Coordinate(5, 5));
    Coordinate projPt = indexedLine.extractPoint(projIndex);
    ensure(0 != ISNAN(projPt.z));
}

} // namespace tut

<|endoftext|>


<commit_before>#include <dirent.h>
#include "../InternalTypes.h"

void DirectoryType::__constructor__() {
	auto file_path = Program::argument<TextInstance>();
	auto self = Program::create<DirectoryInstance>();

	self->file_path = file_path->text();
	Program::push(self);
}

void DirectoryType::contents() {
	auto self = Program::argument<DirectoryInstance>();

    auto contents = Program::create<ListInstance>();
    auto directory = opendir(self->file_path.c_str());

    if (directory != nullptr) { // TODO: Throw exception
        while(auto entry = readdir(directory)) {
            contents->val.push_back(Program::intern(new DirectoryEntryInstance(std::string(entry->d_name), entry->d_type)));
        }
    }

    Program::push(contents);
}

std::string DirectoryInstance::text() {
	return "Directory(" + this->file_path + ")";
}

bool DirectoryInstance::boolean() {
	return true;
}

<commit_msg>Thorw user mode exception in Directory.contents<commit_after>#include <dirent.h>
#include "../InternalTypes.h"

void DirectoryType::__constructor__() {
	auto file_path = Program::argument<TextInstance>();
	auto self = Program::create<DirectoryInstance>();

	self->file_path = file_path->text();
	Program::push(self);
}

void DirectoryType::contents() {
	auto self = Program::argument<DirectoryInstance>();

    auto contents = Program::create<ListInstance>();
    auto directory = opendir(self->file_path.c_str());

    if (directory == nullptr) {
        throw ExceptionInstance(Program::create<TextInstance>("Cannot read directory contents"));
    }

    while(auto entry = readdir(directory)) {
        contents->val.push_back(Program::intern(new DirectoryEntryInstance(std::string(entry->d_name), entry->d_type)));
    }

    Program::push(contents);
}

std::string DirectoryInstance::text() {
	return "Directory(" + this->file_path + ")";
}

bool DirectoryInstance::boolean() {
	return true;
}

<|endoftext|>


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

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

#include "testtoolloader.hxx"

#ifndef _OSL_MODULE_H_
#include <osl/module.h>
#endif
#ifndef _OSL_FILE_HXX_
#include <osl/file.hxx>
#endif
#ifndef _RTL_LOGFILE_HXX_
#include <rtl/logfile.hxx>
#endif
#ifndef _VOS_PROCESS_HXX_
#include <vos/process.hxx>
#endif
#ifndef _SOLAR_H
#include "solar.h"
#endif
#ifndef _STRING_HXX
#include "string.hxx"
#endif
#ifndef _TOOLS_DEBUG_HXX
#include "debug.hxx"
#endif

using namespace rtl;

namespace tools
{
    typedef void ( *pfunc_CreateRemoteControl)();
    typedef void ( *pfunc_DestroyRemoteControl)();

static oslModule    aTestToolModule = 0;

sal_uInt32 GetCommandLineParamCount()
{
    NAMESPACE_VOS( OStartupInfo ) aStartInfo;
    return aStartInfo.getCommandArgCount();
}

String GetCommandLineParam( sal_uInt32 nParam )
{
    NAMESPACE_VOS( OStartupInfo ) aStartInfo;
    ::rtl::OUString aParam;
    NAMESPACE_VOS( OStartupInfo )::TStartupError eError = aStartInfo.getCommandArg( nParam, aParam );
    if ( eError == NAMESPACE_VOS( OStartupInfo )::E_None )
        return String( aParam );
    else
    {
        DBG_ERROR( "Unable to get CommandLineParam" );
        return String();
    }
}

void InitTestToolLib()
{
    RTL_LOGFILE_CONTEXT( aLog, "desktop (cd100003) ::InitTestToolLib" );

    sal_uInt32 i;
    // are we to be automated at all?
    bool bAutomate = false;

    for ( i = 0 ; i < GetCommandLineParamCount() ; i++ )
    {
        if ( GetCommandLineParam( i ).EqualsIgnoreCaseAscii("/enableautomation")
            || GetCommandLineParam( i ).EqualsIgnoreCaseAscii("-enableautomation"))
        {
            bAutomate = true;
            break;
        }
    }

    if ( !bAutomate )
        return;

    OUString    aFuncName( RTL_CONSTASCII_USTRINGPARAM( "CreateRemoteControl" ));
    OUString    aModulePath;

    ::vos::OStartupInfo().getExecutableFile( aModulePath );
    sal_uInt32  lastIndex = aModulePath.lastIndexOf('/');
    if ( lastIndex > 0 )
        aModulePath = aModulePath.copy( 0, lastIndex+1 );

    aModulePath += OUString::createFromAscii( SVLIBRARY( "sts" ) );

    // Shortcut for Performance: We expect that the test tool library is not installed
    // (only for testing purpose). It should be located beside our executable.
    // We don't want to pay for searching through LD_LIBRARY_PATH so we check for
    // existence only in our executable path!!
    osl::DirectoryItem  aItem;
    osl::FileBase::RC   nResult = osl::DirectoryItem::get( aModulePath, aItem );

    if ( nResult == osl::FileBase::E_None )
    {
        aTestToolModule = osl_loadModule( aModulePath.pData, SAL_LOADMODULE_DEFAULT );
        if ( aTestToolModule )
        {
            oslGenericFunction pInitFunc = osl_getFunctionSymbol(
                aTestToolModule, aFuncName.pData );
            if ( pInitFunc )
                (reinterpret_cast< pfunc_CreateRemoteControl >(pInitFunc))();
            else
            {
                   DBG_ERROR1( "Unable to get Symbol 'CreateRemoteControl' from library %s while loading testtool support.", SVLIBRARY( "sts" ) );
            }
        }
        else
        {
               DBG_ERROR1( "Error loading library %s while loading testtool support.", SVLIBRARY( "sts" ) );
        }
    }
    else
    {
        DBG_ERROR1( "Unable to access library %s while loading testtool support.", SVLIBRARY( "sts" ) );
    }
}

void DeInitTestToolLib()
{
    if ( aTestToolModule )
    {
        OUString    aFuncName( RTL_CONSTASCII_USTRINGPARAM( "DestroyRemoteControl" ));

        oslGenericFunction pDeInitFunc = osl_getFunctionSymbol(
            aTestToolModule, aFuncName.pData );
        if ( pDeInitFunc )
            (reinterpret_cast< pfunc_DestroyRemoteControl >(pDeInitFunc))();

        osl_unloadModule( aTestToolModule );
    }
}

} // namespace tools
<commit_msg>INTEGRATION: CWS hedaburemove01 (1.6.50); FILE MERGED 2006/12/12 16:28:12 vg 1.6.50.1: #i72503# get rid of hedabu<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: testtoolloader.cxx,v $
 *
 *  $Revision: 1.7 $
 *
 *  last change: $Author: vg $ $Date: 2007-04-11 20:22:50 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

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

#include "tools/testtoolloader.hxx"

#ifndef _OSL_MODULE_H_
#include <osl/module.h>
#endif
#ifndef _OSL_FILE_HXX_
#include <osl/file.hxx>
#endif
#ifndef _RTL_LOGFILE_HXX_
#include <rtl/logfile.hxx>
#endif
#ifndef _VOS_PROCESS_HXX_
#include <vos/process.hxx>
#endif
#ifndef _SOLAR_H
#include "tools/solar.h"
#endif
#ifndef _STRING_HXX
#include "tools/string.hxx"
#endif
#ifndef _TOOLS_DEBUG_HXX
#include "tools/debug.hxx"
#endif

using namespace rtl;

namespace tools
{
    typedef void ( *pfunc_CreateRemoteControl)();
    typedef void ( *pfunc_DestroyRemoteControl)();

static oslModule    aTestToolModule = 0;

sal_uInt32 GetCommandLineParamCount()
{
    NAMESPACE_VOS( OStartupInfo ) aStartInfo;
    return aStartInfo.getCommandArgCount();
}

String GetCommandLineParam( sal_uInt32 nParam )
{
    NAMESPACE_VOS( OStartupInfo ) aStartInfo;
    ::rtl::OUString aParam;
    NAMESPACE_VOS( OStartupInfo )::TStartupError eError = aStartInfo.getCommandArg( nParam, aParam );
    if ( eError == NAMESPACE_VOS( OStartupInfo )::E_None )
        return String( aParam );
    else
    {
        DBG_ERROR( "Unable to get CommandLineParam" );
        return String();
    }
}

void InitTestToolLib()
{
    RTL_LOGFILE_CONTEXT( aLog, "desktop (cd100003) ::InitTestToolLib" );

    sal_uInt32 i;
    // are we to be automated at all?
    bool bAutomate = false;

    for ( i = 0 ; i < GetCommandLineParamCount() ; i++ )
    {
        if ( GetCommandLineParam( i ).EqualsIgnoreCaseAscii("/enableautomation")
            || GetCommandLineParam( i ).EqualsIgnoreCaseAscii("-enableautomation"))
        {
            bAutomate = true;
            break;
        }
    }

    if ( !bAutomate )
        return;

    OUString    aFuncName( RTL_CONSTASCII_USTRINGPARAM( "CreateRemoteControl" ));
    OUString    aModulePath;

    ::vos::OStartupInfo().getExecutableFile( aModulePath );
    sal_uInt32  lastIndex = aModulePath.lastIndexOf('/');
    if ( lastIndex > 0 )
        aModulePath = aModulePath.copy( 0, lastIndex+1 );

    aModulePath += OUString::createFromAscii( SVLIBRARY( "sts" ) );

    // Shortcut for Performance: We expect that the test tool library is not installed
    // (only for testing purpose). It should be located beside our executable.
    // We don't want to pay for searching through LD_LIBRARY_PATH so we check for
    // existence only in our executable path!!
    osl::DirectoryItem  aItem;
    osl::FileBase::RC   nResult = osl::DirectoryItem::get( aModulePath, aItem );

    if ( nResult == osl::FileBase::E_None )
    {
        aTestToolModule = osl_loadModule( aModulePath.pData, SAL_LOADMODULE_DEFAULT );
        if ( aTestToolModule )
        {
            oslGenericFunction pInitFunc = osl_getFunctionSymbol(
                aTestToolModule, aFuncName.pData );
            if ( pInitFunc )
                (reinterpret_cast< pfunc_CreateRemoteControl >(pInitFunc))();
            else
            {
                   DBG_ERROR1( "Unable to get Symbol 'CreateRemoteControl' from library %s while loading testtool support.", SVLIBRARY( "sts" ) );
            }
        }
        else
        {
               DBG_ERROR1( "Error loading library %s while loading testtool support.", SVLIBRARY( "sts" ) );
        }
    }
    else
    {
        DBG_ERROR1( "Unable to access library %s while loading testtool support.", SVLIBRARY( "sts" ) );
    }
}

void DeInitTestToolLib()
{
    if ( aTestToolModule )
    {
        OUString    aFuncName( RTL_CONSTASCII_USTRINGPARAM( "DestroyRemoteControl" ));

        oslGenericFunction pDeInitFunc = osl_getFunctionSymbol(
            aTestToolModule, aFuncName.pData );
        if ( pDeInitFunc )
            (reinterpret_cast< pfunc_DestroyRemoteControl >(pDeInitFunc))();

        osl_unloadModule( aTestToolModule );
    }
}

} // namespace tools
<|endoftext|>


<commit_before>/*
 * LCALifLayer.cpp
 *
 *  Created on: Jun 26, 2012
 *      Author: slundquist & dpaiton
 */

#include "LCALIFLayer.hpp"

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <math.h>

//////////////////////////////////////////////////////
// implementation of LIF kernels
//////////////////////////////////////////////////////
#ifdef __cplusplus
extern "C" {
#endif
#ifndef PV_USE_OPENCL
#  include "../kernels/LCALIF_update_state.cl"
#else
#  undef PV_USE_OPENCL
#  undef USE_CLRANDOM
#  include "../kernels/LCALIF_update_state.cl"
#  define PV_USE_OPENCL
#endif
#ifdef __cplusplus
}
#endif

//Kernel update state implementation receives all necessary variables
//for required computation. File is included above.
#ifdef __cplusplus
extern "C" {
#endif
void LCALIF_update_state(
   const int numNeurons,
   const float time,
   const float dt,

   const int nx,
   const int ny,
   const int nf,
   const int nb,

   pvdata_t dynVthScale,
   pvdata_t * dynVthRest,
   const float tauLCA,
   const float tauTHR,
   const float targetRate,

   pvdata_t * integratedSpikeCount,

   CL_MEM_CONST LIF_params * params,
   CL_MEM_GLOBAL uint4 * rnd,
   CL_MEM_GLOBAL float * V,
   CL_MEM_GLOBAL float * Vth,
   CL_MEM_GLOBAL float * G_E,
   CL_MEM_GLOBAL float * G_I,
   CL_MEM_GLOBAL float * G_IB,
   CL_MEM_GLOBAL float * GSynHead,
   CL_MEM_GLOBAL float * activity,

   const float sum_gap,
   CL_MEM_GLOBAL float * G_Gap
);
#ifdef __cplusplus
}
#endif

namespace PV {
LCALIFLayer::LCALIFLayer() {
   initialize_base();
  // initialize(arguments) should *not* be called by the protected constructor.
}

LCALIFLayer::LCALIFLayer(const char * name, HyPerCol * hc) {
   initialize_base();
   initialize(name, hc, MAX_CHANNELS + 1, "LCALIF_update_state");
}

int LCALIFLayer::initialize_base(){
   tauLCA = 200;
   tauTHR = 1000;
   targetRate = 50;
   dynVthScale = DEFAULT_DYNVTHSCALE;
   dynVthRest = NULL;
   integratedSpikeCount = NULL;
   return PV_SUCCESS;
}

int LCALIFLayer::initialize(const char * name, HyPerCol * hc, int num_channels, const char * kernel_name){
   LIFGap::initialize(name, hc, TypeLCA, num_channels, kernel_name);
   PVParams * params = hc->parameters();

   tauLCA     = params->value(name, "tauLCA", tauLCA);
   tauTHR     = params->value(name, "tauTHR", tauTHR);
   targetRate = params->value(name, "targetRate", targetRate);

   //Initialize dynVthRest to vthRest
   for (int i = 0; i < (int)getNumNeurons(); i++){
      //std::cout << "VthRest: " << VthRest << "\n";
      dynVthRest[i] = lParams.VthRest;
   }
   float defaultDynVthScale = lParams.VthRest-lParams.Vrest;
   dynVthScale = defaultDynVthScale > 0 ? dynVthScale : DEFAULT_DYNVTHSCALE;
   dynVthScale = params->value(name, "dynVthScale", dynVthScale);
   if (dynVthScale <= 0) {
      if (hc->columnId()==0) {
         fprintf(stderr,"LCALIFLayer \"%s\": dynVthScale must be positive (value in params is %f).\n", name, dynVthScale);
      }
      abort();
   }

   return PV_SUCCESS;
}

LCALIFLayer::~LCALIFLayer()
{
   free(integratedSpikeCount);
   free(dynVthRest);
}

int LCALIFLayer::allocateBuffers() {
   const size_t numNeurons = getNumNeurons();
   //Allocate data to keep track of trace
   integratedSpikeCount = (pvdata_t *) calloc(numNeurons, sizeof(pvdata_t));
   assert(integratedSpikeCount != NULL);
   dynVthRest = (pvdata_t *) calloc(numNeurons, sizeof(pvdata_t));
   assert(dynVthRest != NULL);
   return LIFGap::allocateBuffers();
}

int LCALIFLayer::updateState(float time, float dt)
{
   //Call update_state kernel
//   std::cout << clayer->activity->data[1000] << " " << integratedSpikeCount[1000] << "\n";
   LCALIF_update_state(getNumNeurons(), time, dt, clayer->loc.nx, clayer->loc.ny, clayer->loc.nf,
         clayer->loc.nb, dynVthScale, dynVthRest, tauLCA, tauTHR, targetRate, integratedSpikeCount, &lParams,
         rand_state, clayer->V, Vth, G_E, G_I, G_IB, GSyn[0], clayer->activity->data, sumGap, G_Gap);
   return PV_SUCCESS;
}
}
<commit_msg>Fixed a bug for write step in LCALIFLayer<commit_after>/*
 * LCALifLayer.cpp
 *
 *  Created on: Jun 26, 2012
 *      Author: slundquist & dpaiton
 */

#include "LCALIFLayer.hpp"

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <math.h>

//////////////////////////////////////////////////////
// implementation of LIF kernels
//////////////////////////////////////////////////////
#ifdef __cplusplus
extern "C" {
#endif
#ifndef PV_USE_OPENCL
#  include "../kernels/LCALIF_update_state.cl"
#else
#  undef PV_USE_OPENCL
#  undef USE_CLRANDOM
#  include "../kernels/LCALIF_update_state.cl"
#  define PV_USE_OPENCL
#endif
#ifdef __cplusplus
}
#endif

//Kernel update state implementation receives all necessary variables
//for required computation. File is included above.
#ifdef __cplusplus
extern "C" {
#endif
void LCALIF_update_state(
   const int numNeurons,
   const float time,
   const float dt,

   const int nx,
   const int ny,
   const int nf,
   const int nb,

   pvdata_t dynVthScale,
   pvdata_t * dynVthRest,
   const float tauLCA,
   const float tauTHR,
   const float targetRate,

   pvdata_t * integratedSpikeCount,

   CL_MEM_CONST LIF_params * params,
   CL_MEM_GLOBAL uint4 * rnd,
   CL_MEM_GLOBAL float * V,
   CL_MEM_GLOBAL float * Vth,
   CL_MEM_GLOBAL float * G_E,
   CL_MEM_GLOBAL float * G_I,
   CL_MEM_GLOBAL float * G_IB,
   CL_MEM_GLOBAL float * GSynHead,
   CL_MEM_GLOBAL float * activity,

   const float sum_gap,
   CL_MEM_GLOBAL float * G_Gap
);
#ifdef __cplusplus
}
#endif

namespace PV {
LCALIFLayer::LCALIFLayer() {
   initialize_base();
  // initialize(arguments) should *not* be called by the protected constructor.
}

LCALIFLayer::LCALIFLayer(const char * name, HyPerCol * hc) {
   initialize_base();
   initialize(name, hc, MAX_CHANNELS + 1, "LCALIF_update_state");
}

int LCALIFLayer::initialize_base(){
   tauLCA = 200;
   tauTHR = 1000;
   targetRate = 50;
   dynVthScale = DEFAULT_DYNVTHSCALE;
   dynVthRest = NULL;
   integratedSpikeCount = NULL;
   return PV_SUCCESS;
}

int LCALIFLayer::initialize(const char * name, HyPerCol * hc, int num_channels, const char * kernel_name){
   LIFGap::initialize(name, hc, TypeLCA, num_channels, kernel_name);
   PVParams * params = hc->parameters();

   tauLCA     = params->value(name, "tauLCA", tauLCA);
   tauTHR     = params->value(name, "tauTHR", tauTHR);
   targetRate = params->value(name, "targetRate", targetRate);

   //Initialize dynVthRest to vthRest
   for (int i = 0; i < (int)getNumNeurons(); i++){
      //std::cout << "VthRest: " << VthRest << "\n";
      dynVthRest[i] = lParams.VthRest;
   }
   float defaultDynVthScale = lParams.VthRest-lParams.Vrest;
   dynVthScale = defaultDynVthScale > 0 ? dynVthScale : DEFAULT_DYNVTHSCALE;
   dynVthScale = params->value(name, "dynVthScale", dynVthScale);
   if (dynVthScale <= 0) {
      if (hc->columnId()==0) {
         fprintf(stderr,"LCALIFLayer \"%s\": dynVthScale must be positive (value in params is %f).\n", name, dynVthScale);
      }
      abort();
   }

   return PV_SUCCESS;
}

LCALIFLayer::~LCALIFLayer()
{
   free(integratedSpikeCount);
   free(dynVthRest);
}

int LCALIFLayer::allocateBuffers() {
   const size_t numNeurons = getNumNeurons();
   //Allocate data to keep track of trace
   integratedSpikeCount = (pvdata_t *) calloc(numNeurons, sizeof(pvdata_t));
   assert(integratedSpikeCount != NULL);
   dynVthRest = (pvdata_t *) calloc(numNeurons, sizeof(pvdata_t));
   assert(dynVthRest != NULL);
   return LIFGap::allocateBuffers();
}

int LCALIFLayer::updateState(float time, float dt)
{
   //Call update_state kernel
//   std::cout << clayer->activity->data[1000] << " " << integratedSpikeCount[1000] << "\n";
   LCALIF_update_state(getNumNeurons(), time, dt, clayer->loc.nx, clayer->loc.ny, clayer->loc.nf,
         clayer->loc.nb, dynVthScale, dynVthRest, tauLCA, tauTHR, targetRate, integratedSpikeCount, &lParams,
         rand_state, clayer->V, Vth, G_E, G_I, G_IB, GSyn[0], clayer->activity->data, sumGap, G_Gap);
   updateActiveIndices();
   return PV_SUCCESS;
}
}
<|endoftext|>


<commit_before>/*  Copyright (c) MediaArea.net SARL. All Rights Reserved.
 *
 *  Use of this source code is governed by a BSD-style license that can
 *  be found in the License.html file in the root of the source tree.
 */

//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
//
// Source: http://svn.mplayerhq.hu/nut/docs/nut.txt?view=markup
//
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

//---------------------------------------------------------------------------
// Pre-compilation
#include "MediaInfo/PreComp.h"
#ifdef __BORLANDC__
    #pragma hdrstop
#endif
//---------------------------------------------------------------------------

//---------------------------------------------------------------------------
#include "MediaInfo/Setup.h"
//---------------------------------------------------------------------------

//---------------------------------------------------------------------------
#if defined(MEDIAINFO_NUT_YES)
//---------------------------------------------------------------------------

//---------------------------------------------------------------------------
#include "MediaInfo/Multiple/File_Nut.h"
//---------------------------------------------------------------------------

namespace MediaInfoLib
{

//***************************************************************************
// Const
//***************************************************************************

//---------------------------------------------------------------------------
namespace Elements
{
    const int64u main       =0x4E4D7A561F5F04ADLL;
    const int64u stream     =0x4E5311405BF2F9DBLL;
    const int64u syncpoint  =0x4E4BE4ADEECA4569LL;
    const int64u index      =0x4E58DD672F23E64ELL;
    const int64u info       =0x4E49AB68B596BA78LL;
}

//***************************************************************************
// Buffer
//***************************************************************************

//---------------------------------------------------------------------------
void File_Nut::FileHeader_Parse()
{
    //Parsing
    Element_Begin1("Nut header");
    std::string file_id_string;
    int8u file_id_string_zero;
    Get_String(24, file_id_string,                               "file_id_string");
    Get_B1 (file_id_string_zero,                                 "file_id_string zero");
    Element_End0();

    FILLING_BEGIN();
        //Integrity
        if (file_id_string!="nut/multimedia container" || file_id_string_zero)
        {
            Reject("Nut");
            return;
        }

        //Filling
        Accept("Nut");

        Fill(Stream_General, 0, General_Format, "Nut");
    FILLING_END();
}

//***************************************************************************
// Elements
//***************************************************************************

//---------------------------------------------------------------------------
void File_Nut::Header_Parse()
{
    //Parsing
    int8u  N;
    Peek_B1(N);
    if (N==0x4E) //'N'
    {
        //Header
        int64u startcode, forward_ptr;
        Get_B8(startcode,                                       "startcode");
        Get_VS(forward_ptr,                                     "forward_ptr");
        if (forward_ptr>4096)
            Skip_B4(                                            "header_checksum");

        Header_Fill_Code(startcode, Ztring().From_Number(startcode, 16)); //Quick filling for CC8 with text
        Header_Fill_Size(Element_Offset+forward_ptr); //4 for cheksum

    }
    else
    {
        //Frame
        Header_Fill_Code(0, "Frame");
        Header_Fill_Size(0);
        Finish();
    }
}

//---------------------------------------------------------------------------
void File_Nut::Data_Parse()
{
    #define ELEMENT_CASE(_NAME) \
        case Elements::_NAME : _NAME(); break;

    //Parsing
    if (Element_Size < 4)
    {
        Skip_XX(Element_Size,                                   "Unknown");
        return;
    }
    Element_Size-=4;
    #ifndef __BORLANDC__
        switch (Element_Code)
    #else //__BORLANDC__
        switch (Element_Code&0xFFFFFFFF) //Borland does not like int64u for const?
    #endif //__BORLANDC__
    {
        ELEMENT_CASE(main);
        ELEMENT_CASE(stream);
        ELEMENT_CASE(syncpoint);
        ELEMENT_CASE(index);
        ELEMENT_CASE(info);
        default : Skip_XX(Element_Size,                         "Data");
    }

    Element_Size+=4;
    if (Element_Offset+4!=Element_Size)
        Skip_XX(Element_Size - 4 - Element_Offset,              "Unknown");
    Skip_B4(                                                    "cheksum");
}

//***************************************************************************
// Elements
//***************************************************************************

//---------------------------------------------------------------------------
void File_Nut::main()
{
    Element_Name("main");

    //Parsing
    int64u time_base_count;
    Skip_VS(                                                    "version");
    Skip_VS(                                                    "stream_count");
    Skip_VS(                                                    "max_distance");
    Get_VS (time_base_count,                                    "time_base_count");
    for(int64u i=0; i<time_base_count; i++)
    {
        Skip_VS(                                                "time_base_num");
        Skip_VS(                                                "time_base_denom");
        //time_base[i]= time_base_num/time_base_denom
    }
    int64u tmp_mul=1;

    for(int16u i=0; i<256;)
    {
        int64u tmp_fields, tmp_size, tmp_res, count;
        Skip_VS(                                                "tmp_flag");
        Get_VS (tmp_fields,                                     "tmp_fields");
        if(tmp_fields>0)
            Skip_VS(                                            "tmp_pts"); //TODO: signed
        if(tmp_fields>1)
            Skip_VS(                                            "tmp_mul");
        if(tmp_fields>2)
            Skip_VS(                                            "tmp_stream");
        if(tmp_fields>3)
            Get_VS (tmp_size,                                   "tmp_size");
        else
            tmp_size=0;
        if(tmp_fields>4)
            Get_VS (tmp_res,                                    "tmp_res");
        else
            tmp_res=0;
        if(tmp_fields>5)
            Get_VS(count,                                       "count");
        else
            count=tmp_mul-tmp_size;
        for(int64u j=6; j<tmp_fields; j++)
            Skip_VS(                                            "tmp_reserved[i]");

        for(int64u j=0; j<count && i<256; j++, i++)
        {
            if (i == 'N')
            {
                //flags[i]= FLAG_INVALID;
                j--;
                continue;
            }
            //flags[i]= tmp_flag;
            //stream_id[i]= tmp_stream;
            //data_size_mul[i]= tmp_mul;
            //data_size_lsb[i]= tmp_size + j;
            //pts_delta[i]= tmp_pts;
            //reserved_count[i]= tmp_res;
        }
    }
}

//---------------------------------------------------------------------------
void File_Nut::stream()
{
    Element_Name("stream");

    //Parsing
    int64u stream_class, fourcc_length, codec_specific_data_length;
    Skip_VS(                                                    "stream_id");
    Get_VS (stream_class,                                       "stream_class");
    Get_VS (fourcc_length,                                      "fourcc length");
    switch (fourcc_length)
    {
        case 2 : Skip_C2(                                       "fourcc"); break;
        case 4 : Skip_C4(                                       "fourcc"); break;
        default: Skip_XX(fourcc_length,                         "fourcc");
    }
    Skip_VS(                                                    "time_base_id");
    Skip_VS(                                                    "msb_pts_shift");
    Skip_VS(                                                    "max_pts_distance");
    Skip_VS(                                                    "decode_delay");
    Skip_VS(                                                    "stream_flags");
    Get_VS (codec_specific_data_length,                         "codec_specific_data length");
    Skip_XX(codec_specific_data_length,                         "codec_specific_data");
    switch (stream_class)
    {
        case 0 : //video
            {
                Skip_VS(                                        "width");
                Skip_VS(                                        "height");
                Skip_VS(                                        "sample_width");
                Skip_VS(                                        "sample_height");
                Skip_VS(                                        "colorspace_type");
            }
            break;
        case 1 : //audio
            {
                Skip_VS(                                         "samplerate_num");
                Skip_VS(                                         "samplerate_denom");
                Skip_VS(                                         "channel_count");
            }
            break;
        case 2 : //subtitles
            {
            }
            break;
        case 3 : //userdata
            {
            }
            break;
        default: ;
    }

    if (Element_Offset!=Element_Size)
        Skip_XX(Element_Size - Element_Offset,                  "Data");
}

//---------------------------------------------------------------------------
void File_Nut::syncpoint()
{
    Element_Name("syncpoint");

    //Parsing
    Skip_XX(Element_Size,                                        "Data");
}

//---------------------------------------------------------------------------
void File_Nut::index()
{
    Element_Name("index");

    //Parsing
    Skip_XX(Element_Size,                                        "Data");
}

//---------------------------------------------------------------------------
void File_Nut::info()
{
    Element_Name("info");

    //Parsing
    Skip_XX(Element_Size,                                        "Data");
}

}

#endif //MEDIAINFO_NUT_YES

<commit_msg>x Nut: fix crash with some files<commit_after>/*  Copyright (c) MediaArea.net SARL. All Rights Reserved.
 *
 *  Use of this source code is governed by a BSD-style license that can
 *  be found in the License.html file in the root of the source tree.
 */

//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
//
// Source: http://svn.mplayerhq.hu/nut/docs/nut.txt?view=markup
//
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

//---------------------------------------------------------------------------
// Pre-compilation
#include "MediaInfo/PreComp.h"
#ifdef __BORLANDC__
    #pragma hdrstop
#endif
//---------------------------------------------------------------------------

//---------------------------------------------------------------------------
#include "MediaInfo/Setup.h"
//---------------------------------------------------------------------------

//---------------------------------------------------------------------------
#if defined(MEDIAINFO_NUT_YES)
//---------------------------------------------------------------------------

//---------------------------------------------------------------------------
#include "MediaInfo/Multiple/File_Nut.h"
//---------------------------------------------------------------------------

namespace MediaInfoLib
{

//***************************************************************************
// Const
//***************************************************************************

//---------------------------------------------------------------------------
namespace Elements
{
    const int64u main       =0x4E4D7A561F5F04ADLL;
    const int64u stream     =0x4E5311405BF2F9DBLL;
    const int64u syncpoint  =0x4E4BE4ADEECA4569LL;
    const int64u index      =0x4E58DD672F23E64ELL;
    const int64u info       =0x4E49AB68B596BA78LL;
}

//***************************************************************************
// Buffer
//***************************************************************************

//---------------------------------------------------------------------------
void File_Nut::FileHeader_Parse()
{
    //Parsing
    Element_Begin1("Nut header");
    std::string file_id_string;
    int8u file_id_string_zero;
    Get_String(24, file_id_string,                               "file_id_string");
    Get_B1 (file_id_string_zero,                                 "file_id_string zero");
    Element_End0();

    FILLING_BEGIN();
        //Integrity
        if (file_id_string!="nut/multimedia container" || file_id_string_zero)
        {
            Reject("Nut");
            return;
        }

        //Filling
        Accept("Nut");

        Fill(Stream_General, 0, General_Format, "Nut");
    FILLING_END();
}

//***************************************************************************
// Elements
//***************************************************************************

//---------------------------------------------------------------------------
void File_Nut::Header_Parse()
{
    //Parsing
    int8u  N;
    Peek_B1(N);
    if (N==0x4E) //'N'
    {
        //Header
        int64u startcode, forward_ptr;
        Get_B8(startcode,                                       "startcode");
        Get_VS(forward_ptr,                                     "forward_ptr");
        if (forward_ptr>4096)
            Skip_B4(                                            "header_checksum");

        Header_Fill_Code(startcode, Ztring().From_Number(startcode, 16)); //Quick filling for CC8 with text
        Header_Fill_Size(Element_Offset+forward_ptr); //4 for cheksum

    }
    else
    {
        //Frame
        Header_Fill_Code(0, "Frame");
        Header_Fill_Size(File_Size-(File_Offset+Buffer_Offset+Element_Offset));
    }
}

//---------------------------------------------------------------------------
void File_Nut::Data_Parse()
{
    #define ELEMENT_CASE(_NAME) \
        case Elements::_NAME : _NAME(); break;

    //Parsing
    if (Element_Size < 4)
    {
        Skip_XX(Element_Size,                                   "Unknown");
        return;
    }
    Element_Size-=4;
    #ifndef __BORLANDC__
        switch (Element_Code)
    #else //__BORLANDC__
        switch (Element_Code&0xFFFFFFFF) //Borland does not like int64u for const?
    #endif //__BORLANDC__
    {
        ELEMENT_CASE(main);
        ELEMENT_CASE(stream);
        ELEMENT_CASE(syncpoint);
        ELEMENT_CASE(index);
        ELEMENT_CASE(info);
        default : Skip_XX(Element_Size,                         "Data");
    }

    Element_Size+=4;
    if (Element_Offset+4!=Element_Size)
        Skip_XX(Element_Size - 4 - Element_Offset,              "Unknown");
    Skip_B4(                                                    "cheksum");
}

//***************************************************************************
// Elements
//***************************************************************************

//---------------------------------------------------------------------------
void File_Nut::main()
{
    Element_Name("main");

    //Parsing
    int64u time_base_count;
    Skip_VS(                                                    "version");
    Skip_VS(                                                    "stream_count");
    Skip_VS(                                                    "max_distance");
    Get_VS (time_base_count,                                    "time_base_count");
    for(int64u i=0; i<time_base_count; i++)
    {
        Skip_VS(                                                "time_base_num");
        Skip_VS(                                                "time_base_denom");
        //time_base[i]= time_base_num/time_base_denom
    }
    int64u tmp_mul=1;

    for(int16u i=0; i<256;)
    {
        int64u tmp_fields, tmp_size, tmp_res, count;
        Skip_VS(                                                "tmp_flag");
        Get_VS (tmp_fields,                                     "tmp_fields");
        if(tmp_fields>0)
            Skip_VS(                                            "tmp_pts"); //TODO: signed
        if(tmp_fields>1)
            Skip_VS(                                            "tmp_mul");
        if(tmp_fields>2)
            Skip_VS(                                            "tmp_stream");
        if(tmp_fields>3)
            Get_VS (tmp_size,                                   "tmp_size");
        else
            tmp_size=0;
        if(tmp_fields>4)
            Get_VS (tmp_res,                                    "tmp_res");
        else
            tmp_res=0;
        if(tmp_fields>5)
            Get_VS(count,                                       "count");
        else
            count=tmp_mul-tmp_size;
        for(int64u j=6; j<tmp_fields; j++)
            Skip_VS(                                            "tmp_reserved[i]");

        for(int64u j=0; j<count && i<256; j++, i++)
        {
            if (i == 'N')
            {
                //flags[i]= FLAG_INVALID;
                j--;
                continue;
            }
            //flags[i]= tmp_flag;
            //stream_id[i]= tmp_stream;
            //data_size_mul[i]= tmp_mul;
            //data_size_lsb[i]= tmp_size + j;
            //pts_delta[i]= tmp_pts;
            //reserved_count[i]= tmp_res;
        }
    }
}

//---------------------------------------------------------------------------
void File_Nut::stream()
{
    Element_Name("stream");

    //Parsing
    int64u stream_class, fourcc_length, codec_specific_data_length;
    Skip_VS(                                                    "stream_id");
    Get_VS (stream_class,                                       "stream_class");
    Get_VS (fourcc_length,                                      "fourcc length");
    switch (fourcc_length)
    {
        case 2 : Skip_C2(                                       "fourcc"); break;
        case 4 : Skip_C4(                                       "fourcc"); break;
        default: Skip_XX(fourcc_length,                         "fourcc");
    }
    Skip_VS(                                                    "time_base_id");
    Skip_VS(                                                    "msb_pts_shift");
    Skip_VS(                                                    "max_pts_distance");
    Skip_VS(                                                    "decode_delay");
    Skip_VS(                                                    "stream_flags");
    Get_VS (codec_specific_data_length,                         "codec_specific_data length");
    Skip_XX(codec_specific_data_length,                         "codec_specific_data");
    switch (stream_class)
    {
        case 0 : //video
            {
                Skip_VS(                                        "width");
                Skip_VS(                                        "height");
                Skip_VS(                                        "sample_width");
                Skip_VS(                                        "sample_height");
                Skip_VS(                                        "colorspace_type");
            }
            break;
        case 1 : //audio
            {
                Skip_VS(                                         "samplerate_num");
                Skip_VS(                                         "samplerate_denom");
                Skip_VS(                                         "channel_count");
            }
            break;
        case 2 : //subtitles
            {
            }
            break;
        case 3 : //userdata
            {
            }
            break;
        default: ;
    }

    if (Element_Offset!=Element_Size)
        Skip_XX(Element_Size - Element_Offset,                  "Data");
}

//---------------------------------------------------------------------------
void File_Nut::syncpoint()
{
    Element_Name("syncpoint");

    //Parsing
    Skip_XX(Element_Size,                                        "Data");
}

//---------------------------------------------------------------------------
void File_Nut::index()
{
    Element_Name("index");

    //Parsing
    Skip_XX(Element_Size,                                        "Data");
}

//---------------------------------------------------------------------------
void File_Nut::info()
{
    Element_Name("info");

    //Parsing
    Skip_XX(Element_Size,                                        "Data");
}

}

#endif //MEDIAINFO_NUT_YES

<|endoftext|>


<commit_before>/*
*
* Copyright 2013 Telefonica Investigacion y Desarrollo, S.A.U
*
* This file is part of Orion Context Broker.
*
* Orion Context Broker is free software: you can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* Orion Context Broker is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero
* General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with Orion Context Broker. If not, see http://www.gnu.org/licenses/.
*
* For those usages not covered by this license please contact with
* fermin at tid dot es
*
* Author: Ken Zangelin
*/
#include <time.h>

#include "logMsg/logMsg.h"
#include "logMsg/traceLevels.h"

#include "common/globals.h"
#include "common/sem.h"
#include "serviceRoutines/versionTreat.h"     // For orionInit()
#include "mongoBackend/MongoGlobal.h"         // For orionInit()
#include "ngsiNotify/onTimeIntervalThread.h"  // For orionInit()

/* ****************************************************************************
*
* Globals
*/
static Timer*     timer             = NULL;
int               startTime         = -1;
int               statisticsTime    = -1;
OrionExitFunction orionExitFunction = NULL;

/* ****************************************************************************
*
* orionInit -
*/
void orionInit(OrionExitFunction exitFunction, const char* version)
{
  // Give the rest library the correct version string of this executable
  versionSet(version);

  // The function to call on fatal error
  orionExitFunction = exitFunction;

  /* Initialize the semaphore used by mongoBackend */
  semInit();

  /* Set timer object (singleton) */
  setTimer(new Timer());

  /* Set notifier object (singleton) */
  setNotifier(new Notifier());

  /* Set start time */
  startTime      = getCurrentTime();
  statisticsTime = startTime;
}

/* ****************************************************************************
*
* isTrue -
*/
bool isTrue(const std::string& s)
{
  if (strcasecmp(s.c_str(), "true") == 0)
    return true;
  if (strcasecmp(s.c_str(), "yes") == 0)
    return true;

  return false;
}

/* ****************************************************************************
*
* isFalse -
*/
bool isFalse(const std::string& s)
{
  if (strcasecmp(s.c_str(), "false") == 0)
    return true;
  if (strcasecmp(s.c_str(), "no") == 0)
    return true;

  return false;
}

/*****************************************************************************
*
* getTimer -
*/
Timer* getTimer() {
    return timer;
}

/*****************************************************************************
*
* setTimer -
*/
void setTimer(Timer* t) {
    timer = t;
}

/* ****************************************************************************
*
* getCurrentTime -
*/
int getCurrentTime(void)
{
  if (getTimer() == NULL)
  {
    LM_E(("getTimer() == NULL - calling exit function for library user"));
    orionExitFunction(1, "getTimer() == NULL");
    return -1;
  }

  return getTimer()->getCurrentTime();
}

/* ****************************************************************************
*
* toSeconds -
*/
long long toSeconds(int value, char what, bool dayPart)
{
  long long result = -1;

  if (dayPart == true)
  {
    if (what == 'Y')
      result = 365L * 24 * 3600 * value;
    else if (what == 'M')
      result = 30 * 24 * 3600 * value;
    else if (what == 'W')
      result = 7 * 24 * 3600 * value;
    else if (what == 'D')
      result = 24 * 3600 * value;
  }
  else
  {
    if (what == 'H')
      result = 3600 * value;
    else if (what == 'M')
      result = 60 * value;
    else if (what == 'S')
      result = value;
  }

  if (result == -1)
    LM_E(("ERROR in duration string!"));

  return result;
}

/*****************************************************************************
*
* parse8601 -
*
* This is common code for Duration and Throttling (at least)
*
*/
long long parse8601(std::string s)
{
    if (s == "")
        return 0;

    char*      duration    = strdup(s.c_str());
    char*      toFree      = duration;
    bool       dayPart     = true;
    long long  accumulated = 0;
    char*      start;

    if (*duration != 'P')
    {
      free(toFree);
      return -1;
    }

    ++duration;
    start = duration;

    while (*duration != 0)
    {
      if (isdigit(*duration))
        ++duration;
      else if ((dayPart == true) && ((*duration == 'Y') || (*duration == 'M') || (*duration == 'D') || (*duration == 'W')))
      {
        char what = *duration;

        *duration = 0;
        int value = atoi(start);

        accumulated += toSeconds(value, what, dayPart);
        ++duration;
        start = duration;
      }
      else if ((dayPart == true) && (*duration == 'T'))
      {
        dayPart = false;
        ++duration;
        start = duration;
      }
      else if ((dayPart == false) && ((*duration == 'H') || (*duration == 'M') || (*duration == 'S')))
      {
        char what = *duration;

        *duration = 0;
        int value = atoi(start);

        accumulated += toSeconds(value, what, dayPart);
        ++duration;
        start = duration;
      }
      else
      {
         free(toFree);
         return -1; // ParseError
      }
    }

free(toFree);

    return accumulated;
}
<commit_msg>Fixed a indentation error and some more 'L's for long<commit_after>/*
*
* Copyright 2013 Telefonica Investigacion y Desarrollo, S.A.U
*
* This file is part of Orion Context Broker.
*
* Orion Context Broker is free software: you can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* Orion Context Broker is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero
* General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with Orion Context Broker. If not, see http://www.gnu.org/licenses/.
*
* For those usages not covered by this license please contact with
* fermin at tid dot es
*
* Author: Ken Zangelin
*/
#include <time.h>

#include "logMsg/logMsg.h"
#include "logMsg/traceLevels.h"

#include "common/globals.h"
#include "common/sem.h"
#include "serviceRoutines/versionTreat.h"     // For orionInit()
#include "mongoBackend/MongoGlobal.h"         // For orionInit()
#include "ngsiNotify/onTimeIntervalThread.h"  // For orionInit()

/* ****************************************************************************
*
* Globals
*/
static Timer*     timer             = NULL;
int               startTime         = -1;
int               statisticsTime    = -1;
OrionExitFunction orionExitFunction = NULL;

/* ****************************************************************************
*
* orionInit -
*/
void orionInit(OrionExitFunction exitFunction, const char* version)
{
  // Give the rest library the correct version string of this executable
  versionSet(version);

  // The function to call on fatal error
  orionExitFunction = exitFunction;

  /* Initialize the semaphore used by mongoBackend */
  semInit();

  /* Set timer object (singleton) */
  setTimer(new Timer());

  /* Set notifier object (singleton) */
  setNotifier(new Notifier());

  /* Set start time */
  startTime      = getCurrentTime();
  statisticsTime = startTime;
}

/* ****************************************************************************
*
* isTrue -
*/
bool isTrue(const std::string& s)
{
  if (strcasecmp(s.c_str(), "true") == 0)
    return true;
  if (strcasecmp(s.c_str(), "yes") == 0)
    return true;

  return false;
}

/* ****************************************************************************
*
* isFalse -
*/
bool isFalse(const std::string& s)
{
  if (strcasecmp(s.c_str(), "false") == 0)
    return true;
  if (strcasecmp(s.c_str(), "no") == 0)
    return true;

  return false;
}

/*****************************************************************************
*
* getTimer -
*/
Timer* getTimer() {
    return timer;
}

/*****************************************************************************
*
* setTimer -
*/
void setTimer(Timer* t) {
    timer = t;
}

/* ****************************************************************************
*
* getCurrentTime -
*/
int getCurrentTime(void)
{
  if (getTimer() == NULL)
  {
    LM_E(("getTimer() == NULL - calling exit function for library user"));
    orionExitFunction(1, "getTimer() == NULL");
    return -1;
  }

  return getTimer()->getCurrentTime();
}

/* ****************************************************************************
*
* toSeconds -
*/
long long toSeconds(int value, char what, bool dayPart)
{
  long long result = -1;

  if (dayPart == true)
  {
    if (what == 'Y')
      result = 365L * 24 * 3600 * value;
    else if (what == 'M')
      result = 30L * 24 * 3600 * value;
    else if (what == 'W')
      result = 7L * 24 * 3600 * value;
    else if (what == 'D')
      result = 24L * 3600 * value;
  }
  else
  {
    if (what == 'H')
      result = 3600L * value;
    else if (what == 'M')
      result = 60L * value;
    else if (what == 'S')
      result = value;
  }

  if (result == -1)
    LM_E(("ERROR in duration string!"));

  return result;
}

/*****************************************************************************
*
* parse8601 -
*
* This is common code for Duration and Throttling (at least)
*
*/
long long parse8601(std::string s)
{
    if (s == "")
        return 0;

    char*      duration    = strdup(s.c_str());
    char*      toFree      = duration;
    bool       dayPart     = true;
    long long  accumulated = 0;
    char*      start;

    if (*duration != 'P')
    {
      free(toFree);
      return -1;
    }

    ++duration;
    start = duration;

    while (*duration != 0)
    {
      if (isdigit(*duration))
        ++duration;
      else if ((dayPart == true) && ((*duration == 'Y') || (*duration == 'M') || (*duration == 'D') || (*duration == 'W')))
      {
        char what = *duration;

        *duration = 0;
        int value = atoi(start);

        accumulated += toSeconds(value, what, dayPart);
        ++duration;
        start = duration;
      }
      else if ((dayPart == true) && (*duration == 'T'))
      {
        dayPart = false;
        ++duration;
        start = duration;
      }
      else if ((dayPart == false) && ((*duration == 'H') || (*duration == 'M') || (*duration == 'S')))
      {
        char what = *duration;

        *duration = 0;
        int value = atoi(start);

        accumulated += toSeconds(value, what, dayPart);
        ++duration;
        start = duration;
      }
      else
      {
         free(toFree);
         return -1; // ParseError
      }
    }

    free(toFree);

    return accumulated;
}
<|endoftext|>


<commit_before>//
// Name:        LayerPropDlg.cpp
//
// Copyright (c) 2002 Virtual Terrain Project
// Free for all uses, see license.txt for details.
//

#ifdef __GNUG__
    #pragma implementation "LayerPropDlg.cpp"
#endif

// For compilers that support precompilation, includes "wx/wx.h".
#include "wx/wxprec.h"

#ifdef __BORLANDC__
    #pragma hdrstop
#endif

#include "LayerPropDlg.h"

// WDR: class implementations

//----------------------------------------------------------------------------
// LayerPropDlg
//----------------------------------------------------------------------------

// WDR: event table for LayerPropDlg

BEGIN_EVENT_TABLE(LayerPropDlg,AutoDialog)
END_EVENT_TABLE()

LayerPropDlg::LayerPropDlg( wxWindow *parent, wxWindowID id, const wxString &title,
    const wxPoint &position, const wxSize& size, long style ) :
    AutoDialog( parent, id, title, position, size, style )
{
    ElevPropDialogFunc( this, TRUE );
}

// WDR: handler implementations for LayerPropDlg

void LayerPropDlg::OnInitDialog(wxInitDialogEvent& event)
{
	AddNumValidator(ID_LEFT, &m_fLeft);
	AddNumValidator(ID_TOP, &m_fTop);
	AddNumValidator(ID_RIGHT, &m_fRight);
	AddNumValidator(ID_BOTTOM, &m_fBottom);

	AddValidator(ID_PROPS, &m_strText);

    wxDialog::OnInitDialog(event);  // calls TransferDataToWindow()
}

<commit_msg>chg name of dialog fn to LayerPropDialogFunc<commit_after>//
// Name:        LayerPropDlg.cpp
//
// Copyright (c) 2002 Virtual Terrain Project
// Free for all uses, see license.txt for details.
//

#ifdef __GNUG__
    #pragma implementation "LayerPropDlg.cpp"
#endif

// For compilers that support precompilation, includes "wx/wx.h".
#include "wx/wxprec.h"

#ifdef __BORLANDC__
    #pragma hdrstop
#endif

#include "LayerPropDlg.h"

// WDR: class implementations

//----------------------------------------------------------------------------
// LayerPropDlg
//----------------------------------------------------------------------------

// WDR: event table for LayerPropDlg

BEGIN_EVENT_TABLE(LayerPropDlg,AutoDialog)
END_EVENT_TABLE()

LayerPropDlg::LayerPropDlg( wxWindow *parent, wxWindowID id, const wxString &title,
    const wxPoint &position, const wxSize& size, long style ) :
    AutoDialog( parent, id, title, position, size, style )
{
    LayerPropDialogFunc( this, TRUE );
}

// WDR: handler implementations for LayerPropDlg

void LayerPropDlg::OnInitDialog(wxInitDialogEvent& event)
{
	AddNumValidator(ID_LEFT, &m_fLeft);
	AddNumValidator(ID_TOP, &m_fTop);
	AddNumValidator(ID_RIGHT, &m_fRight);
	AddNumValidator(ID_BOTTOM, &m_fBottom);

	AddValidator(ID_PROPS, &m_strText);

    wxDialog::OnInitDialog(event);  // calls TransferDataToWindow()
}

<|endoftext|>


<commit_before>/**************************************************************************
**
** This file is part of the Qt Build Suite
**
** Copyright (c) 2012 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation (info@qt.nokia.com)
**
**
** GNU Lesser General Public License Usage
**
** This file may be used under the terms of the GNU Lesser General Public
** License version 2.1 as published by the Free Software Foundation and
** appearing in the file LICENSE.LGPL included in the packaging of this file.
** Please review the following information to ensure the GNU Lesser General
** Public License version 2.1 requirements will be met:
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU General
** Public License version 3.0 as published by the Free Software Foundation
** and appearing in the file LICENSE.GPL included in the packaging of this
** file.
** Please review the following information to ensure the GNU General
** Public License version 3.0 requirements will be met:
** http://www.gnu.org/copyleft/gpl.html.
**
** Other Usage
** Alternatively, this file may be used in accordance with the terms and
** conditions contained in a signed written agreement between you and Nokia.
**
**************************************************************************/

#include "fileinfo.h"
#include <QtCore/QCoreApplication>
#include <QDir>
#include <QFileInfo>
#include <QDebug>
#include <cassert>

#ifdef Q_OS_UNIX
#include <sys/stat.h>
#endif

namespace qbs {

QString FileInfo::fileName(const QString &fp)
{
    int last = fp.lastIndexOf('/');
    if (last < 0)
        return fp;
    return fp.mid(last + 1);
}

QString FileInfo::baseName(const QString &fp)
{
    QString fn = fileName(fp);
    int dot = fn.indexOf('.');
    if (dot < 0)
        return fp;
    return fn.mid(0, dot);
}

QString FileInfo::completeBaseName(const QString &fp)
{
    QString fn = fileName(fp);
    int dot = fn.lastIndexOf('.');
    if (dot < 0)
        return fp;
    return fn.mid(0, dot);
}

QString FileInfo::path(const QString &fp)
{
    if (fp.isEmpty())
        return QString();
    if (fp.at(fp.size() - 1) == '/')
        return fp;
    int last = fp.lastIndexOf('/');
    if (last < 0)
        return ".";
    return QDir::cleanPath(fp.mid(0, last));
}

bool FileInfo::exists(const QString &fp)
{
    return FileInfo(fp).exists();
}

// from creator/src/shared/proparser/ioutils.cpp
bool FileInfo::isAbsolute(const QString &path)
{
    if (path.startsWith(QLatin1Char('/')))
        return true;
#ifdef Q_OS_WIN
    if (path.startsWith(QLatin1Char('\\')))
        return true;
    // Unlike QFileInfo, this won't accept a relative path with a drive letter.
    // Such paths result in a royal mess anyway ...
    if (path.length() >= 3 && path.at(1) == QLatin1Char(':') && path.at(0).isLetter()
            && (path.at(2) == QLatin1Char('/') || path.at(2) == QLatin1Char('\\')))
        return true;
#endif
    return false;
}

QString FileInfo::resolvePath(const QString &base, const QString &rel)
{
    if (isAbsolute(rel))
        return rel;
    if (rel == QLatin1String("."))
        return base;

    QString r = base;
    if (!r.endsWith('/')) {
        r.append('/');
    }
    r.append(rel);

    return r;
}

bool FileInfo::globMatches(const QString &pattern, const QString &subject)
{
    // ### the QRegExp wildcard matcher is slow!
    //QRegExp rex(pattern, Qt::CaseSensitive, QRegExp::Wildcard);
    //return rex.exactMatch(subject);
    return subject.endsWith(pattern.mid(1), Qt::CaseInsensitive);
}

static QString resolveSymlinks(const QString &fileName)
{
    QFileInfo fi(fileName);
    while (fi.isSymLink())
        fi.setFile(fi.symLinkTarget());
    return fi.absoluteFilePath();
}

#if defined(Q_OS_WIN)

#include <qt_windows.h>

#define z(x) reinterpret_cast<WIN32_FILE_ATTRIBUTE_DATA*>(const_cast<FileInfo::InternalStatType*>(&x))

template<bool> struct CompileTimeAssert;
template<> struct CompileTimeAssert<true> {};

FileInfo::FileInfo(const QString &fileName)
{
    static CompileTimeAssert<
        sizeof(FileInfo::InternalStatType) == sizeof(WIN32_FILE_ATTRIBUTE_DATA)
            > internal_type_has_wrong_size;
    if (!GetFileAttributesEx(reinterpret_cast<const WCHAR*>(fileName.utf16()),
                             GetFileExInfoStandard, &m_stat))
    {
        z(m_stat)->dwFileAttributes = INVALID_FILE_ATTRIBUTES;
    }
}

bool FileInfo::exists() const
{
    return z(m_stat)->dwFileAttributes != INVALID_FILE_ATTRIBUTES;
}

FileTime FileInfo::lastModified() const
{
    return FileTime(*reinterpret_cast<const FileTime::InternalType*>(
        &z(m_stat)->ftLastWriteTime));
}

QString applicationDirPath()
{
    static const QString appDirPath = FileInfo::path(resolveSymlinks(QCoreApplication::applicationFilePath()));
    return appDirPath;
}

#elif defined(Q_OS_UNIX)

FileInfo::FileInfo(const QString &fileName)
{
    if (stat(fileName.toLocal8Bit(), &m_stat) == -1)
        m_stat.st_mtime = 0;
}

bool FileInfo::exists() const
{
    return m_stat.st_mtime != 0;
}

FileTime FileInfo::lastModified() const
{
    return m_stat.st_mtime;
}

QString applicationDirPath()
{
    return QCoreApplication::applicationDirPath();
}

#endif

// adapted from qtc/plugins/vcsbase/cleandialog.cpp
static bool removeFileRecursion(const QFileInfo &f, QString *errorMessage)
{
    if (!f.exists())
        return true;
    if (f.isDir()) {
        const QDir dir(f.absoluteFilePath());
        foreach(const QFileInfo &fi, dir.entryInfoList(QDir::AllEntries|QDir::NoDotAndDotDot|QDir::Hidden))
            removeFileRecursion(fi, errorMessage);
        QDir parent = f.absoluteDir();
        if (!parent.rmdir(f.fileName())) {
            errorMessage->append(FileInfo::tr("The directory %1 could not be deleted.").
                                 arg(QDir::toNativeSeparators(f.absoluteFilePath())));
            return false;
        }
    } else if (!QFile::remove(f.absoluteFilePath())) {
        if (!errorMessage->isEmpty())
            errorMessage->append(QLatin1Char('\n'));
        errorMessage->append(FileInfo::tr("The file %1 could not be deleted.").
                             arg(QDir::toNativeSeparators(f.absoluteFilePath())));
        return false;
    }
    return true;
}

bool removeDirectoryWithContents(const QString &path, QString *errorMessage)
{
    QFileInfo f(path);
    if (f.exists() && !f.isDir()) {
        *errorMessage = FileInfo::tr("%1 is not a directory.").arg(QDir::toNativeSeparators(path));
        return false;
    }
    return removeFileRecursion(f, errorMessage);
}

QString qbsRootPath()
{
    return QDir::cleanPath(applicationDirPath() + QLatin1String("/../"));
}

}
<commit_msg>use QLatin1Char when appropriate<commit_after>/**************************************************************************
**
** This file is part of the Qt Build Suite
**
** Copyright (c) 2012 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation (info@qt.nokia.com)
**
**
** GNU Lesser General Public License Usage
**
** This file may be used under the terms of the GNU Lesser General Public
** License version 2.1 as published by the Free Software Foundation and
** appearing in the file LICENSE.LGPL included in the packaging of this file.
** Please review the following information to ensure the GNU Lesser General
** Public License version 2.1 requirements will be met:
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU General
** Public License version 3.0 as published by the Free Software Foundation
** and appearing in the file LICENSE.GPL included in the packaging of this
** file.
** Please review the following information to ensure the GNU General
** Public License version 3.0 requirements will be met:
** http://www.gnu.org/copyleft/gpl.html.
**
** Other Usage
** Alternatively, this file may be used in accordance with the terms and
** conditions contained in a signed written agreement between you and Nokia.
**
**************************************************************************/

#include "fileinfo.h"
#include <QtCore/QCoreApplication>
#include <QDir>
#include <QFileInfo>
#include <QDebug>
#include <cassert>

#ifdef Q_OS_UNIX
#include <sys/stat.h>
#endif

namespace qbs {

QString FileInfo::fileName(const QString &fp)
{
    int last = fp.lastIndexOf('/');
    if (last < 0)
        return fp;
    return fp.mid(last + 1);
}

QString FileInfo::baseName(const QString &fp)
{
    QString fn = fileName(fp);
    int dot = fn.indexOf('.');
    if (dot < 0)
        return fp;
    return fn.mid(0, dot);
}

QString FileInfo::completeBaseName(const QString &fp)
{
    QString fn = fileName(fp);
    int dot = fn.lastIndexOf('.');
    if (dot < 0)
        return fp;
    return fn.mid(0, dot);
}

QString FileInfo::path(const QString &fp)
{
    if (fp.isEmpty())
        return QString();
    if (fp.at(fp.size() - 1) == '/')
        return fp;
    int last = fp.lastIndexOf('/');
    if (last < 0)
        return ".";
    return QDir::cleanPath(fp.mid(0, last));
}

bool FileInfo::exists(const QString &fp)
{
    return FileInfo(fp).exists();
}

// from creator/src/shared/proparser/ioutils.cpp
bool FileInfo::isAbsolute(const QString &path)
{
    if (path.startsWith(QLatin1Char('/')))
        return true;
#ifdef Q_OS_WIN
    if (path.startsWith(QLatin1Char('\\')))
        return true;
    // Unlike QFileInfo, this won't accept a relative path with a drive letter.
    // Such paths result in a royal mess anyway ...
    if (path.length() >= 3 && path.at(1) == QLatin1Char(':') && path.at(0).isLetter()
            && (path.at(2) == QLatin1Char('/') || path.at(2) == QLatin1Char('\\')))
        return true;
#endif
    return false;
}

QString FileInfo::resolvePath(const QString &base, const QString &rel)
{
    if (isAbsolute(rel))
        return rel;
    if (rel.size() == 1 && rel.at(0) == QLatin1Char('.'))
        return base;

    QString r = base;
    if (!r.endsWith(QLatin1Char('/')))
        r.append(QLatin1Char('/'));
    r.append(rel);

    return r;
}

bool FileInfo::globMatches(const QString &pattern, const QString &subject)
{
    // ### the QRegExp wildcard matcher is slow!
    //QRegExp rex(pattern, Qt::CaseSensitive, QRegExp::Wildcard);
    //return rex.exactMatch(subject);
    return subject.endsWith(pattern.mid(1), Qt::CaseInsensitive);
}

static QString resolveSymlinks(const QString &fileName)
{
    QFileInfo fi(fileName);
    while (fi.isSymLink())
        fi.setFile(fi.symLinkTarget());
    return fi.absoluteFilePath();
}

#if defined(Q_OS_WIN)

#include <qt_windows.h>

#define z(x) reinterpret_cast<WIN32_FILE_ATTRIBUTE_DATA*>(const_cast<FileInfo::InternalStatType*>(&x))

template<bool> struct CompileTimeAssert;
template<> struct CompileTimeAssert<true> {};

FileInfo::FileInfo(const QString &fileName)
{
    static CompileTimeAssert<
        sizeof(FileInfo::InternalStatType) == sizeof(WIN32_FILE_ATTRIBUTE_DATA)
            > internal_type_has_wrong_size;
    if (!GetFileAttributesEx(reinterpret_cast<const WCHAR*>(fileName.utf16()),
                             GetFileExInfoStandard, &m_stat))
    {
        z(m_stat)->dwFileAttributes = INVALID_FILE_ATTRIBUTES;
    }
}

bool FileInfo::exists() const
{
    return z(m_stat)->dwFileAttributes != INVALID_FILE_ATTRIBUTES;
}

FileTime FileInfo::lastModified() const
{
    return FileTime(*reinterpret_cast<const FileTime::InternalType*>(
        &z(m_stat)->ftLastWriteTime));
}

QString applicationDirPath()
{
    static const QString appDirPath = FileInfo::path(resolveSymlinks(QCoreApplication::applicationFilePath()));
    return appDirPath;
}

#elif defined(Q_OS_UNIX)

FileInfo::FileInfo(const QString &fileName)
{
    if (stat(fileName.toLocal8Bit(), &m_stat) == -1)
        m_stat.st_mtime = 0;
}

bool FileInfo::exists() const
{
    return m_stat.st_mtime != 0;
}

FileTime FileInfo::lastModified() const
{
    return m_stat.st_mtime;
}

QString applicationDirPath()
{
    return QCoreApplication::applicationDirPath();
}

#endif

// adapted from qtc/plugins/vcsbase/cleandialog.cpp
static bool removeFileRecursion(const QFileInfo &f, QString *errorMessage)
{
    if (!f.exists())
        return true;
    if (f.isDir()) {
        const QDir dir(f.absoluteFilePath());
        foreach(const QFileInfo &fi, dir.entryInfoList(QDir::AllEntries|QDir::NoDotAndDotDot|QDir::Hidden))
            removeFileRecursion(fi, errorMessage);
        QDir parent = f.absoluteDir();
        if (!parent.rmdir(f.fileName())) {
            errorMessage->append(FileInfo::tr("The directory %1 could not be deleted.").
                                 arg(QDir::toNativeSeparators(f.absoluteFilePath())));
            return false;
        }
    } else if (!QFile::remove(f.absoluteFilePath())) {
        if (!errorMessage->isEmpty())
            errorMessage->append(QLatin1Char('\n'));
        errorMessage->append(FileInfo::tr("The file %1 could not be deleted.").
                             arg(QDir::toNativeSeparators(f.absoluteFilePath())));
        return false;
    }
    return true;
}

bool removeDirectoryWithContents(const QString &path, QString *errorMessage)
{
    QFileInfo f(path);
    if (f.exists() && !f.isDir()) {
        *errorMessage = FileInfo::tr("%1 is not a directory.").arg(QDir::toNativeSeparators(path));
        return false;
    }
    return removeFileRecursion(f, errorMessage);
}

QString qbsRootPath()
{
    return QDir::cleanPath(applicationDirPath() + QLatin1String("/../"));
}

}
<|endoftext|>


<commit_before>// Copyright (c) 2014 Andrew Toulouse.
// Distributed under the MIT License.

#include "Block.h"

#include <fstream>
#include <cassert>
#include <cstring>

namespace libol {
    bool get_bit(uint8_t byte, int n) {
        return (byte >> (7 - n)) & 1;
    }

    Block::Stream Block::createStream(size_t offset) {
        Stream stream(*this, offset);
        return stream;
    }

    Block Block::decode(std::ifstream& ifs, Block* previous) {
        Block block;

        uint8_t marker = ifs.get();

        // Bit 1: Time format
        block.time.isAbsolute = get_bit(marker, 0);
        if(block.time.isAbsolute) {
            block.time.diff = ifs.get();
        } else {
            ifs.read(reinterpret_cast<char*>(&block.time.absolute), sizeof(block.time.absolute));
        }

        // Bit 4: Size size
        if(get_bit(marker, 3)) {
            block.size = (unsigned) ifs.get();
        } else {
            ifs.read(reinterpret_cast<char*>(&block.size), sizeof(block.size));
        }

        // Bit 2: Has type
        block.hasExplicitType = !get_bit(marker, 1);
        if(block.hasExplicitType) {
            block.type = ifs.get();
        } else {
            if(previous != nullptr) {
                block.type = previous->type;
            } else {
                std::cout << "typeless block as first block" << std::endl;
                exit(1);
            }
        }

        // Bit 3: Blockdata size
        block.param.is32 = !get_bit(marker, 2);
        if(block.param.is32) {
            ifs.read(reinterpret_cast<char*>(&block.param.value32), sizeof(block.param.value32));
        } else {
            block.param.value8 = ifs.get();
        }

        // Read content
        block.content.resize(block.size);
        ifs.read(reinterpret_cast<char*>(block.content.data()), block.size);

        return block;
    }
}
<commit_msg>Fix block time<commit_after>// Copyright (c) 2014 Andrew Toulouse.
// Distributed under the MIT License.

#include "Block.h"

#include <fstream>
#include <cassert>
#include <cstring>

namespace libol {
    bool get_bit(uint8_t byte, int n) {
        return (byte >> (7 - n)) & 1;
    }

    Block::Stream Block::createStream(size_t offset) {
        Stream stream(*this, offset);
        return stream;
    }

    Block Block::decode(std::ifstream& ifs, Block* previous) {
        Block block;

        uint8_t marker = ifs.get();

        // Bit 1: Time format
        block.time.isAbsolute = !get_bit(marker, 0);
        if(block.time.isAbsolute) {
            ifs.read(reinterpret_cast<char*>(&block.time.absolute), sizeof(block.time.absolute));
        } else {
            block.time.diff = ifs.get();
        }

        // Bit 4: Size size
        if(get_bit(marker, 3)) {
            block.size = (unsigned) ifs.get();
        } else {
            ifs.read(reinterpret_cast<char*>(&block.size), sizeof(block.size));
        }

        // Bit 2: Has type
        block.hasExplicitType = !get_bit(marker, 1);
        if(block.hasExplicitType) {
            block.type = ifs.get();
        } else {
            if(previous != nullptr) {
                block.type = previous->type;
            } else {
                std::cout << "typeless block as first block" << std::endl;
                exit(1);
            }
        }

        // Bit 3: Blockdata size
        block.param.is32 = !get_bit(marker, 2);
        if(block.param.is32) {
            ifs.read(reinterpret_cast<char*>(&block.param.value32), sizeof(block.param.value32));
        } else {
            block.param.value8 = ifs.get();
        }

        // Read content
        block.content.resize(block.size);
        ifs.read(reinterpret_cast<char*>(block.content.data()), block.size);

        return block;
    }
}
<|endoftext|>