<commit_before>#include <qpdf/BitStream.hh>
#include <qpdf/BitWriter.hh>
#include <qpdf/Pl_Buffer.hh>
#include <iostream>
#include <stdio.h>

// See comments in bits.cc
#define BITS_TESTING 1
#define BITS_READ 1
#define BITS_WRITE 1
#include "../libqpdf/bits.icc"

static void
print_values(int byte_offset, unsigned int bit_offset,
	     unsigned int bits_available)
{
    std::cout << "byte offset = " << byte_offset << ", "
	      << "bit offset = " << bit_offset << ", "
	      << "bits available = " << bits_available << std::endl;
}

static void
test_read_bits(unsigned char const* buf,
	       unsigned char const*& p, unsigned int& bit_offset,
	       unsigned int& bits_available, int bits_wanted)
{
    unsigned long result =
	read_bits(p, bit_offset, bits_available, bits_wanted);

    std::cout << "bits read: " << bits_wanted << ", result = " << result
	      << std::endl;
    print_values(p - buf, bit_offset, bits_available);
}

static void
test_write_bits(unsigned char& ch, unsigned int& bit_offset, unsigned long val,
		int bits, Pl_Buffer* bp)
{
    write_bits(ch, bit_offset, val, bits, bp);
    printf("ch = %02x, bit_offset = %d\n",
           static_cast<unsigned int>(ch), bit_offset);
}

static void
print_buffer(Pl_Buffer* bp)
{
    bp->finish();
    Buffer* b = bp->getBuffer();
    unsigned char const* p = b->getBuffer();
    size_t l = b->getSize();
    for (unsigned long i = 0; i < l; ++i)
    {
	printf("%02x%s", static_cast<unsigned int>(p[i]),
	       (i == l - 1) ? "\n" : " ");
    }
    printf("\n");
    delete b;
}

static void
test()
{
    // 11110101 00010101 01100101 01111001 00010010 10001001 01110101 01001011
    // F5 15 65 79 12 89 75 4B

    // Read tests

    static unsigned char const buf[] = {
	0xF5, 0x15, 0x65, 0x79, 0x12, 0x89, 0x75, 0x4B
    };

    unsigned char const* p = buf;
    unsigned int bit_offset = 7;
    unsigned int bits_available = 64;

    // 11110:101 0:001010:1 01100101: 01111001
    // 0:00:1:0010 10001001 01110101 01001:011
    print_values(p - buf, bit_offset, bits_available);
    test_read_bits(buf, p, bit_offset, bits_available, 5);
    test_read_bits(buf, p, bit_offset, bits_available, 4);
    test_read_bits(buf, p, bit_offset, bits_available, 6);
    test_read_bits(buf, p, bit_offset, bits_available, 9);
    test_read_bits(buf, p, bit_offset, bits_available, 9);
    test_read_bits(buf, p, bit_offset, bits_available, 2);
    test_read_bits(buf, p, bit_offset, bits_available, 1);
    test_read_bits(buf, p, bit_offset, bits_available, 0);
    test_read_bits(buf, p, bit_offset, bits_available, 25);

    try
    {
	test_read_bits(buf, p, bit_offset, bits_available, 4);
    }
    catch (std::exception& e)
    {
	std::cout << "exception: " << e.what() << std::endl;
	print_values(p - buf, bit_offset, bits_available);
    }

    test_read_bits(buf, p, bit_offset, bits_available, 3);
    std::cout << std::endl;

    // 11110101 00010101 01100101 01111001: 00010010 10001001 01110101 01001011

    p = buf;
    bit_offset = 7;
    bits_available = 64;
    print_values(p - buf, bit_offset, bits_available);
    test_read_bits(buf, p, bit_offset, bits_available, 32);
    test_read_bits(buf, p, bit_offset, bits_available, 32);
    std::cout << std::endl;

    BitStream b(buf, 8);
    std::cout << b.getBits(32) << std::endl;
    b.reset();
    std::cout << b.getBits(32) << std::endl;
    std::cout << b.getBits(32) << std::endl;
    std::cout << std::endl;

    b.reset();
    std::cout << b.getBits(6) << std::endl;
    b.skipToNextByte();
    std::cout << b.getBits(8) << std::endl;
    b.skipToNextByte();
    std::cout << b.getBits(8) << std::endl;
    std::cout << std::endl;

    // Write tests

    // 11110:101 0:001010:1 01100101: 01111001
    // 0:00:1:0010 10001001 01110101 01001:011

    unsigned char ch = 0;
    bit_offset = 7;
    Pl_Buffer* bp = new Pl_Buffer("buffer");

    test_write_bits(ch, bit_offset, 30UL, 5, bp);
    test_write_bits(ch, bit_offset, 10UL, 4, bp);
    test_write_bits(ch, bit_offset, 10UL, 6, bp);
    test_write_bits(ch, bit_offset, 16059UL, 0, bp);
    test_write_bits(ch, bit_offset, 357UL, 9, bp);
    print_buffer(bp);

    test_write_bits(ch, bit_offset, 242UL, 9, bp);
    test_write_bits(ch, bit_offset, 0UL, 2, bp);
    test_write_bits(ch, bit_offset, 1UL, 1, bp);
    test_write_bits(ch, bit_offset, 5320361UL, 25, bp);
    test_write_bits(ch, bit_offset, 3UL, 3, bp);

    print_buffer(bp);
    test_write_bits(ch, bit_offset, 4111820153UL, 32, bp);
    test_write_bits(ch, bit_offset, 310998347UL, 32, bp);
    print_buffer(bp);

    BitWriter bw(bp);
    bw.writeBits(30UL, 5);
    bw.flush();
    bw.flush();
    bw.writeBits(0xABUL, 8);
    bw.flush();
    print_buffer(bp);

    delete bp;
}

int main()
{
    try
    {
	test();
    }
    catch (std::exception& e)
    {
	std::cout << "unexpected exception: " << e.what() << std::endl;
	exit(2);
    }
    std::cout << "done" << std::endl;
    return 0;
}
<commit_msg>Include stdlib.h to provide exit<commit_after>#include <qpdf/BitStream.hh>
#include <qpdf/BitWriter.hh>
#include <qpdf/Pl_Buffer.hh>
#include <iostream>
#include <stdio.h>
#include <stdlib.h>

// See comments in bits.cc
#define BITS_TESTING 1
#define BITS_READ 1
#define BITS_WRITE 1
#include "../libqpdf/bits.icc"

static void
print_values(int byte_offset, unsigned int bit_offset,
	     unsigned int bits_available)
{
    std::cout << "byte offset = " << byte_offset << ", "
	      << "bit offset = " << bit_offset << ", "
	      << "bits available = " << bits_available << std::endl;
}

static void
test_read_bits(unsigned char const* buf,
	       unsigned char const*& p, unsigned int& bit_offset,
	       unsigned int& bits_available, int bits_wanted)
{
    unsigned long result =
	read_bits(p, bit_offset, bits_available, bits_wanted);

    std::cout << "bits read: " << bits_wanted << ", result = " << result
	      << std::endl;
    print_values(p - buf, bit_offset, bits_available);
}

static void
test_write_bits(unsigned char& ch, unsigned int& bit_offset, unsigned long val,
		int bits, Pl_Buffer* bp)
{
    write_bits(ch, bit_offset, val, bits, bp);
    printf("ch = %02x, bit_offset = %d\n",
           static_cast<unsigned int>(ch), bit_offset);
}

static void
print_buffer(Pl_Buffer* bp)
{
    bp->finish();
    Buffer* b = bp->getBuffer();
    unsigned char const* p = b->getBuffer();
    size_t l = b->getSize();
    for (unsigned long i = 0; i < l; ++i)
    {
	printf("%02x%s", static_cast<unsigned int>(p[i]),
	       (i == l - 1) ? "\n" : " ");
    }
    printf("\n");
    delete b;
}

static void
test()
{
    // 11110101 00010101 01100101 01111001 00010010 10001001 01110101 01001011
    // F5 15 65 79 12 89 75 4B

    // Read tests

    static unsigned char const buf[] = {
	0xF5, 0x15, 0x65, 0x79, 0x12, 0x89, 0x75, 0x4B
    };

    unsigned char const* p = buf;
    unsigned int bit_offset = 7;
    unsigned int bits_available = 64;

    // 11110:101 0:001010:1 01100101: 01111001
    // 0:00:1:0010 10001001 01110101 01001:011
    print_values(p - buf, bit_offset, bits_available);
    test_read_bits(buf, p, bit_offset, bits_available, 5);
    test_read_bits(buf, p, bit_offset, bits_available, 4);
    test_read_bits(buf, p, bit_offset, bits_available, 6);
    test_read_bits(buf, p, bit_offset, bits_available, 9);
    test_read_bits(buf, p, bit_offset, bits_available, 9);
    test_read_bits(buf, p, bit_offset, bits_available, 2);
    test_read_bits(buf, p, bit_offset, bits_available, 1);
    test_read_bits(buf, p, bit_offset, bits_available, 0);
    test_read_bits(buf, p, bit_offset, bits_available, 25);

    try
    {
	test_read_bits(buf, p, bit_offset, bits_available, 4);
    }
    catch (std::exception& e)
    {
	std::cout << "exception: " << e.what() << std::endl;
	print_values(p - buf, bit_offset, bits_available);
    }

    test_read_bits(buf, p, bit_offset, bits_available, 3);
    std::cout << std::endl;

    // 11110101 00010101 01100101 01111001: 00010010 10001001 01110101 01001011

    p = buf;
    bit_offset = 7;
    bits_available = 64;
    print_values(p - buf, bit_offset, bits_available);
    test_read_bits(buf, p, bit_offset, bits_available, 32);
    test_read_bits(buf, p, bit_offset, bits_available, 32);
    std::cout << std::endl;

    BitStream b(buf, 8);
    std::cout << b.getBits(32) << std::endl;
    b.reset();
    std::cout << b.getBits(32) << std::endl;
    std::cout << b.getBits(32) << std::endl;
    std::cout << std::endl;

    b.reset();
    std::cout << b.getBits(6) << std::endl;
    b.skipToNextByte();
    std::cout << b.getBits(8) << std::endl;
    b.skipToNextByte();
    std::cout << b.getBits(8) << std::endl;
    std::cout << std::endl;

    // Write tests

    // 11110:101 0:001010:1 01100101: 01111001
    // 0:00:1:0010 10001001 01110101 01001:011

    unsigned char ch = 0;
    bit_offset = 7;
    Pl_Buffer* bp = new Pl_Buffer("buffer");

    test_write_bits(ch, bit_offset, 30UL, 5, bp);
    test_write_bits(ch, bit_offset, 10UL, 4, bp);
    test_write_bits(ch, bit_offset, 10UL, 6, bp);
    test_write_bits(ch, bit_offset, 16059UL, 0, bp);
    test_write_bits(ch, bit_offset, 357UL, 9, bp);
    print_buffer(bp);

    test_write_bits(ch, bit_offset, 242UL, 9, bp);
    test_write_bits(ch, bit_offset, 0UL, 2, bp);
    test_write_bits(ch, bit_offset, 1UL, 1, bp);
    test_write_bits(ch, bit_offset, 5320361UL, 25, bp);
    test_write_bits(ch, bit_offset, 3UL, 3, bp);

    print_buffer(bp);
    test_write_bits(ch, bit_offset, 4111820153UL, 32, bp);
    test_write_bits(ch, bit_offset, 310998347UL, 32, bp);
    print_buffer(bp);

    BitWriter bw(bp);
    bw.writeBits(30UL, 5);
    bw.flush();
    bw.flush();
    bw.writeBits(0xABUL, 8);
    bw.flush();
    print_buffer(bp);

    delete bp;
}

int main()
{
    try
    {
	test();
    }
    catch (std::exception& e)
    {
	std::cout << "unexpected exception: " << e.what() << std::endl;
	exit(2);
    }
    std::cout << "done" << std::endl;
    return 0;
}
<|endoftext|>


<commit_before>
/*
    pbrt source code Copyright(c) 1998-2010 Matt Pharr and Greg Humphreys.

    This file is part of pbrt.

    pbrt is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation; either version 2 of the License, or
    (at your option) any later version.  Note that the text contents of
    the book "Physically Based Rendering" are *not* licensed under the
    GNU GPL.

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

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.

 */

// lights/point.cpp*
#include "lights/point.h"
#include "sh.h"
#include "scene.h"
#include "paramset.h"
#include "montecarlo.h"

// PointLight Method Definitions
PointLight::PointLight(const Transform &light2world,
                       const Spectrum &intensity)
    : Light(light2world) {
    lightPos = LightToWorld(Point(0,0,0));
    Intensity = intensity;
}

Spectrum PointLight::Sample_L(const Point &p, float pEpsilon,
         const LightSample &ls, float time, Vector *wi, float *pdf,
         VisibilityTester *visibility) const {
    *wi = Normalize(lightPos - p);
    *pdf = 1.f;
    visibility->SetSegment(p, pEpsilon, lightPos, 0., time);
    return Intensity / DistanceSquared(lightPos, p);
}

Spectrum PointLight::Power(const Scene *) const {
    return 4.f * M_PI * Intensity;
}

PointLight *CreatePointLight(const Transform &light2world,
        const ParamSet &paramSet) {
    Spectrum I = paramSet.FindOneSpectrum("I", Spectrum(1.0));
    Spectrum sc = paramSet.FindOneSpectrum("scale", Spectrum(1.0));
    Point P = paramSet.FindOnePoint("from", Point(0,0,0));
    Transform l2w = Translate(Vector(P.x, P.y, P.z)) * light2world;
    return new PointLight(l2w, I * sc);
}

float PointLight::Pdf(const Point &, const Vector &) const {
    return 0.;
}

Spectrum PointLight::Sample_L(const Scene *scene, const LightSample &ls,
        float u1, float u2, float time, Ray *ray, Normal *Ns,
        float *pdf) const {
    *ray = Ray(lightPos, UniformSampleSphere(ls.uPos[0], ls.uPos[1]),
               0.f, INFINITY, time);
    *Ns = (Normal)ray->d;
    *pdf = UniformSpherePdf();
    return Intensity;
}

void PointLight::SHProject(const Point &p, float pEpsilon, int lmax,
        const Scene *scene, bool computeLightVisibility, float time,
        RNG &rng, Spectrum *coeffs) const {
    for (int i = 0; i < SHTerms(lmax); ++i)
        coeffs[i] = 0.f;
    if (computeLightVisibility &&
        scene->IntersectP(Ray(p, Normalize(lightPos - p), pEpsilon,
                              1.f, time)))
        return;
    // Project point light source to SH
    float *Ylm = ALLOCA(float, SHTerms(lmax));
    Vector wi = Normalize(lightPos - p);
    SHEvaluate(wi, lmax, Ylm);
    Spectrum Li = Intensity / DistanceSquared(lightPos, p);
    for (int i = 0; i < SHTerms(lmax); ++i)
        coeffs[i] = Li * Ylm[i];
}

<commit_msg>Fix bug in code for point light projection to SH coefficients.<commit_after>
/*
    pbrt source code Copyright(c) 1998-2010 Matt Pharr and Greg Humphreys.

    This file is part of pbrt.

    pbrt is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation; either version 2 of the License, or
    (at your option) any later version.  Note that the text contents of
    the book "Physically Based Rendering" are *not* licensed under the
    GNU GPL.

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

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.

 */

// lights/point.cpp*
#include "lights/point.h"
#include "sh.h"
#include "scene.h"
#include "paramset.h"
#include "montecarlo.h"

// PointLight Method Definitions
PointLight::PointLight(const Transform &light2world,
                       const Spectrum &intensity)
    : Light(light2world) {
    lightPos = LightToWorld(Point(0,0,0));
    Intensity = intensity;
}

Spectrum PointLight::Sample_L(const Point &p, float pEpsilon,
         const LightSample &ls, float time, Vector *wi, float *pdf,
         VisibilityTester *visibility) const {
    *wi = Normalize(lightPos - p);
    *pdf = 1.f;
    visibility->SetSegment(p, pEpsilon, lightPos, 0., time);
    return Intensity / DistanceSquared(lightPos, p);
}

Spectrum PointLight::Power(const Scene *) const {
    return 4.f * M_PI * Intensity;
}

PointLight *CreatePointLight(const Transform &light2world,
        const ParamSet &paramSet) {
    Spectrum I = paramSet.FindOneSpectrum("I", Spectrum(1.0));
    Spectrum sc = paramSet.FindOneSpectrum("scale", Spectrum(1.0));
    Point P = paramSet.FindOnePoint("from", Point(0,0,0));
    Transform l2w = Translate(Vector(P.x, P.y, P.z)) * light2world;
    return new PointLight(l2w, I * sc);
}

float PointLight::Pdf(const Point &, const Vector &) const {
    return 0.;
}

Spectrum PointLight::Sample_L(const Scene *scene, const LightSample &ls,
        float u1, float u2, float time, Ray *ray, Normal *Ns,
        float *pdf) const {
    *ray = Ray(lightPos, UniformSampleSphere(ls.uPos[0], ls.uPos[1]),
               0.f, INFINITY, time);
    *Ns = (Normal)ray->d;
    *pdf = UniformSpherePdf();
    return Intensity;
}

void PointLight::SHProject(const Point &p, float pEpsilon, int lmax,
        const Scene *scene, bool computeLightVisibility, float time,
        RNG &rng, Spectrum *coeffs) const {
    for (int i = 0; i < SHTerms(lmax); ++i)
        coeffs[i] = 0.f;
    if (computeLightVisibility &&
        scene->IntersectP(Ray(p, Normalize(lightPos - p), pEpsilon,
                              Distance(lightPos, p), time)))
        return;
    // Project point light source to SH
    float *Ylm = ALLOCA(float, SHTerms(lmax));
    Vector wi = Normalize(lightPos - p);
    SHEvaluate(wi, lmax, Ylm);
    Spectrum Li = Intensity / DistanceSquared(lightPos, p);
    for (int i = 0; i < SHTerms(lmax); ++i)
        coeffs[i] = Li * Ylm[i];
}

<|endoftext|>


<commit_before>/*  vim:expandtab:shiftwidth=2:tabstop=2:smarttab:
 *
 *  Data Differential YATL (i.e. libtest)  library
 *
 *  Copyright (C) 2012 Data Differential, http://datadifferential.com/
 *
 *  Redistribution and use in source and binary forms, with or without
 *  modification, are permitted provided that the following conditions are
 *  met:
 *
 *      * Redistributions of source code must retain the above copyright
 *  notice, this list of conditions and the following disclaimer.
 *
 *      * Redistributions in binary form must reproduce the above
 *  copyright notice, this list of conditions and the following disclaimer
 *  in the documentation and/or other materials provided with the
 *  distribution.
 *
 *      * The names of its contributors may not be used to endorse or
 *  promote products derived from this software without specific prior
 *  written permission.
 *
 *  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 *  "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 *  LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 *  A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 *  OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 *  SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 *  LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 *  DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 *  THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 *  (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 *  OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 */

#include <config.h>
#include <libtest/common.h>

#include <cstdlib>
#include <unistd.h>

namespace libtest {

bool has_memcached_support(void)
{
  if (HAVE_LIBMEMCACHED)
  {
    return true;
  }

  return false;
}

bool has_libdrizzle(void)
{
  if (HAVE_LIBDRIZZLE)
  {
    return true;
  }

  return false;
}

bool has_postgres_support(void)
{
  if (getenv("POSTGES_IS_RUNNING_AND_SETUP"))
  {
    if (HAVE_LIBPQ)
    {
      return true;
    }
  }

  return false;
}

bool has_gearmand()
{
  if (HAVE_GEARMAND_BINARY)
  {
    std::stringstream arg_buffer;

    if (getenv("PWD"))
    {
      arg_buffer << getenv("PWD");
      arg_buffer << "/";
    }
    arg_buffer << GEARMAND_BINARY;

    if (access(arg_buffer.str().c_str(), X_OK) == 0)
    {
      return true;
    }
  }

  return false;
}

bool has_drizzled()
{
  if (HAVE_DRIZZLED_BINARY)
  {
    if (access(DRIZZLED_BINARY, X_OK) == 0)
    {
      return true;
    }
  }

  return false;
}

bool has_memcached()
{
  if (HAVE_MEMCACHED_BINARY)
  {
    if (access(MEMCACHED_BINARY, X_OK) == 0)
    {
      return true;
    }
  }

  return false;
}

bool has_memcached_sasl()
{
  if (HAVE_MEMCACHED_SASL_BINARY)
  {
    if (access(MEMCACHED_SASL_BINARY, X_OK) == 0)
    {
      return true;
    }
  }

  return false;
}

} // namespace libtest
<commit_msg>Check for local memcached, and then add PWD<commit_after>/*  vim:expandtab:shiftwidth=2:tabstop=2:smarttab:
 *
 *  Data Differential YATL (i.e. libtest)  library
 *
 *  Copyright (C) 2012 Data Differential, http://datadifferential.com/
 *
 *  Redistribution and use in source and binary forms, with or without
 *  modification, are permitted provided that the following conditions are
 *  met:
 *
 *      * Redistributions of source code must retain the above copyright
 *  notice, this list of conditions and the following disclaimer.
 *
 *      * Redistributions in binary form must reproduce the above
 *  copyright notice, this list of conditions and the following disclaimer
 *  in the documentation and/or other materials provided with the
 *  distribution.
 *
 *      * The names of its contributors may not be used to endorse or
 *  promote products derived from this software without specific prior
 *  written permission.
 *
 *  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 *  "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 *  LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 *  A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 *  OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 *  SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 *  LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 *  DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 *  THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 *  (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 *  OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 */

#include <config.h>
#include <libtest/common.h>

#include <cstdlib>
#include <unistd.h>

namespace libtest {

bool has_libmemcached(void)
{
  if (HAVE_LIBMEMCACHED)
  {
    return true;
  }

  return false;
}

bool has_libdrizzle(void)
{
  if (HAVE_LIBDRIZZLE)
  {
    return true;
  }

  return false;
}

bool has_postgres_support(void)
{
  if (getenv("POSTGES_IS_RUNNING_AND_SETUP"))
  {
    if (HAVE_LIBPQ)
    {
      return true;
    }
  }

  return false;
}

bool has_gearmand()
{
  if (HAVE_GEARMAND_BINARY)
  {
    std::stringstream arg_buffer;

    if (getenv("PWD"))
    {
      arg_buffer << getenv("PWD");
      arg_buffer << "/";
    }
    arg_buffer << GEARMAND_BINARY;

    if (access(arg_buffer.str().c_str(), X_OK) == 0)
    {
      return true;
    }
  }

  return false;
}

bool has_drizzled()
{
  if (HAVE_DRIZZLED_BINARY)
  {
    if (access(DRIZZLED_BINARY, X_OK) == 0)
    {
      return true;
    }
  }

  return false;
}

bool has_memcached()
{
  if (HAVE_MEMCACHED_BINARY)
  {
    std::stringstream arg_buffer;

    if (getenv("PWD"))
    {
      arg_buffer << getenv("PWD");
      arg_buffer << "/";
    }
    arg_buffer << MEMCACHED_BINARY;

    if (access(arg_buffer.str().c_str(), X_OK) == 0)
    {
      return true;
    }
  }

  return false;
}

bool has_memcached_sasl()
{
  if (HAVE_MEMCACHED_SASL_BINARY)
  {
    if (access(MEMCACHED_SASL_BINARY, X_OK) == 0)
    {
      return true;
    }
  }

  return false;
}

} // namespace libtest
<|endoftext|>


<commit_before>/*
 * Copyright(c) Sophist Solutions, Inc. 1990-2012.  All rights reserved
 */
#include    "../StroikaPreComp.h"

#include    <algorithm>
#include    <cstdlib>
#include    <fstream>
#include    <sstream>

#if     qPlatform_POSIX
#include    <sys/types.h>
#include    <unistd.h>
#include    <sys/stat.h>
#include    <fcntl.h>
#endif

#include    "../../Foundation/Characters/Format.h"
#include    "../../Foundation/Containers/Common.h"
#include    "../../Foundation/Debug/Assertions.h"
#include    "../../Foundation/Debug/Trace.h"
#include    "../../Foundation/Execution/CommandLine.h"
#include    "../../Foundation/Execution/Exceptions.h"
#include    "../../Foundation/Execution/ErrNoException.h"
#include    "../../Foundation/Execution/Module.h"
#include    "../../Foundation/Execution/ThreadAbortException.h"
#include    "../../Foundation/Execution/Signals.h"
#include    "../../Foundation/Execution/Sleep.h"
#include    "../../Foundation/Execution/WaitTimedOutException.h"
#include    "../../Foundation/IO/FileSystem/FileUtils.h"
#include    "../../Foundation/Memory/SmallStackBuffer.h"

#include    "Main.h"

using   namespace   Stroika::Foundation;
using   namespace   Stroika::Foundation::Containers;
using   namespace   Stroika::Foundation::Memory;

using   namespace   Stroika::Frameworks;
using   namespace   Stroika::Frameworks::Service;

/*
 ********************************************************************************
 ****************************** Service::Main::IRep *****************************
 ********************************************************************************
 */
Main::IRep::IRep ()
    : fStopping_ (false)
    , fMustReReadConfig (false)
{
}

Main::IRep::~IRep ()
{
}

void    Main::IRep::OnStartRequest ()
{
    // This procedure ends when the entire service process ends...
    Debug::TraceContextBumper traceCtx (TSTR ("Stroika::Frameworks::Service::Main::IRep::OnStartRequest"));
    MainLoop ();
}

void    Main::IRep::OnStopRequest ()
{
    Debug::TraceContextBumper traceCtx (TSTR ("Stroika::Frameworks::Service::Main::IRep::OnStopRequest"));
    // default to using thread stuff to send us a signal to abort...
    fStopping_ = true;
}

void    Main::IRep::OnReReadConfigurationRequest ()
{
    fMustReReadConfig = true;
}

String  Main::IRep::GetServiceStatusMessage () const
{
    return String ();
}

#if     qPlatform_POSIX
String  Main::IRep::GetPIDFileName () const
{
    return L"/tmp/" + GetServiceDescription ().fName + L".pid";
}
#endif

#if     qPlatform_POSIX
void    Main::IRep::SignalHandler (int signum)
{
    Debug::TraceContextBumper traceCtx (TSTR ("Stroika::Frameworks::Service::Main::IRep::SignalHandler"));
    DbgTrace (L"(signal = %s)", Execution::SignalToName (signum).c_str ());
    // VERY PRIMITIVE IMPL FOR NOW -- LGP 2011-09-24
    switch (signum) {
        case    SIGTERM:
            DbgTrace ("setting fStopping_ to true");
            fStopping_ = true;
            break;
#if     qCompilerAndStdLib_Supports_constexpr
        case    kSIG_ReReadConfiguration:
#else
        case    SIGHUP:
#endif
            OnReReadConfigurationRequest ();
            break;
    }
}
#endif

/*
 ********************************************************************************
 ************************************ Service::Main *****************************
 ********************************************************************************
 */

const   wchar_t Service::Main::CommandNames::kRunAsService[]        =   L"Run-As-Service";
const   wchar_t Service::Main::CommandNames::kStart[]               =   L"Start";
const   wchar_t Service::Main::CommandNames::kStop[]                =   L"Stop";
const   wchar_t Service::Main::CommandNames::kKill[]                =   L"Kill";
const   wchar_t Service::Main::CommandNames::kRestart[]             =   L"Restart";
const   wchar_t Service::Main::CommandNames::kReloadConfiguration[] =   L"Reload-Configuration";
const   wchar_t Service::Main::CommandNames::kPause[]               =   L"Pause";
const   wchar_t Service::Main::CommandNames::kContinue[]            =   L"Continue";

shared_ptr<Main::IRep>   Main::_sRep;

Main::Main (shared_ptr<IRep> rep)
{
    Require  (_sRep.get () == nullptr);     // singleton
    _sRep = rep;
#if     qPlatform_POSIX
    SetupSignalHanlders_ ();
#endif
}

#if     qPlatform_POSIX
void    Main::SetupSignalHanlders_ ()
{
    Execution::SignalHandlerRegistry::Get ().AddSignalHandler (SIGTERM, SignalHandler);
    Execution::SignalHandlerRegistry::Get ().AddSignalHandler (kSIG_ReReadConfiguration, SignalHandler);
}
#endif

Main::State Main::GetState () const
{
#if     qPlatform_POSIX
    if (GetServicePID () != 0) {
        return eRunning;
    }
#endif
    return State::eStopped;    // otherwise (esp on other platforms where not implemented) must  be stopped
}

#if     qPlatform_POSIX
pid_t   Main::GetServicePID () const
{
    ifstream    in (_sRep->GetPIDFileName ().AsTString ().c_str ());
    if (in) {
        pid_t   n = 0;
        in >> n;
        return n;
    }
    return 0;
}
#endif

String      Main::GetServiceStatusMessage () const
{
    Debug::TraceContextBumper traceCtx (TSTR ("Stroika::Frameworks::Service::Main::GetServiceStatusMessage"));
    const   wchar_t kTAB[]  =   L"    ";    // use spaces instead of tab so formatting independent of tabstop settings
    ServiceDescription  svd =   GetServiceDescription ();
    wstringstream   tmp;
    tmp << L"Service '" << svd.fName.As<wstring> () << "'" << endl;
    switch (this->GetState ()) {
        case    State::eStopped:
            tmp << kTAB << L"State:  " << kTAB << kTAB << kTAB << kTAB << "STOPPED" << endl;
            break;
        case    State::eRunning:
            tmp << kTAB << L"State:  " << kTAB << kTAB << kTAB << kTAB << "Running" << endl;
#if     qPlatform_POSIX
            tmp << kTAB << L"PID:    " << kTAB << kTAB << kTAB << kTAB << GetServicePID () << endl;
#endif
            break;
        case    State::ePaused:
            tmp << kTAB << L"State:  " << kTAB << kTAB << kTAB << kTAB << "PAUSED" << endl;
#if     qPlatform_POSIX
            tmp << kTAB << L"PID:    " << kTAB << kTAB << kTAB << kTAB << GetServicePID () << endl;
#endif
            break;
        default:
            AssertNotReached ();
    }
    tmp << _sRep->GetServiceStatusMessage ().As<wstring> ();
    DbgTrace (L"returning status: (%s)", tmp.str ().c_str ());
    return tmp.str ();
}

void    Main::RunAsService ()
{
    Debug::TraceContextBumper traceCtx (TSTR ("Stroika::Frameworks::Service::Main::RunAsService"));
    // VERY PRIMITIVE IMPL - WE NEED LOCKING on tmpfile stuff - add good tempfile supprot to fileuitls or use existing...

    try {
#if     qPlatform_POSIX
        ofstream    out (_sRep->GetPIDFileName ().AsTString ().c_str ());
        out << getpid () << endl;
#endif
        _sRep->OnStartRequest ();
    }
    catch (const Execution::ThreadAbortException& /*threadAbort*/) {
#if     qPlatform_POSIX
        unlink (_sRep->GetPIDFileName ().AsTString ().c_str ());
#endif
        // ignore this - just means service ended normally
    }
    catch (...) {
        DbgTrace (TSTR ("Unexpected exception ended running service"));
#if     qPlatform_POSIX
        unlink (_sRep->GetPIDFileName ().AsTString ().c_str ());
#endif
        throw;
    }
}

void    Main::_Start (Time::DurationSecondsType timeout)
{
    Debug::TraceContextBumper traceCtx (TSTR ("Stroika::Frameworks::Service::Main::Start"));
    DbgTrace ("(timeout = %f)", timeout);

    Time::DurationSecondsType timeoutAt =   Time::GetTickCount () + timeout;

    // Check not already runnig, (someday) and then for and exec the

    if (_IsServiceFailed ()) {
        _CleanupDeadService ();
    }

#if     qPlatform_POSIX
    // REALLY should use GETSTATE - and return state based on if PID file exsits...
    if (GetServicePID ()  != 0) {
        Execution::DoThrow (Execution::StringException (L"Cannot Start service because its already running"));
    }
#endif

    Characters::TString thisEXEPath =   Execution::GetEXEPath ();
#if     qPlatform_POSIX
    pid_t   pid =   fork ();
    Execution::ThrowErrNoIfNegative (pid);
    if (pid == 0) {
        /*
         * Very primitive code to detatch the console. No error checking cuz frankly we dont care.
         *
         * Possibly should close more descriptors?
         */
        for (int i = 0; i < 3; ++i) {
            ::close (i);
        }
        int id = open ("/dev/null", O_RDWR);
        dup2 (id, 0);
        dup2 (id, 1);
        dup2 (id, 2);

        int r   =   execl (thisEXEPath.c_str (), thisEXEPath.c_str (), (String (L"--") + String (CommandNames::kRunAsService)).AsTString ().c_str (), nullptr);
        exit (-1);
    }
    else {
        // parent - in this case - no reason to wait - our work is done... Future versions might wait to
        // see if the 'pidfile' got created....
        //      --LGP 2011-09-23
    }
#endif

    while (not _IsServiceActuallyRunning ()) {
        Execution::Sleep (0.5);
        if (Time::GetTickCount () > timeoutAt) {
            Execution::DoThrow (Execution::WaitTimedOutException ());
        }
    }
}

void    Main::_Stop (Time::DurationSecondsType timeout)
{
    Debug::TraceContextBumper traceCtx (TSTR ("Stroika::Frameworks::Service::Main::Stop"));
    DbgTrace ("(timeout = %f)", timeout);

    Time::DurationSecondsType timeoutAt =   Time::GetTickCount () + timeout;
    // Send signal to server to stop
#if     qPlatform_POSIX
    Execution::ThrowErrNoIfNegative (kill (GetServicePID (), SIGTERM));
#endif
    while (_IsServiceActuallyRunning ()) {
        Execution::Sleep (0.5);
        if (Time::GetTickCount () > timeoutAt) {
            Execution::DoThrow (Execution::WaitTimedOutException ());
        }
    }
}

void    Main::Kill ()
{
    Debug::TraceContextBumper traceCtx (TSTR ("Stroika::Frameworks::Service::Main::Kill"));
    Stop ();
    // Send signal to server to stop
#if     qPlatform_POSIX
    Execution::ThrowErrNoIfNegative (kill (GetServicePID (), SIGKILL));
    // REALY should WAIT for server to stop and only do this it fails -
    unlink (_sRep->GetPIDFileName ().AsTString ().c_str ());
#endif
}

void    Main::_Restart (Time::DurationSecondsType timeout)
{
    Debug::TraceContextBumper traceCtx (TSTR ("Stroika::Frameworks::Service::Main::Restart"));
    DbgTrace ("(timeout = %f)", timeout);

    Time::DurationSecondsType endAt =   Time::GetTickCount () + timeout;
    IgnoreExceptionsForCall (Stop (timeout));
#if     qPlatform_POSIX
    // REALY should WAIT for server to stop and only do this it fails -
    unlink (_sRep->GetPIDFileName ().AsTString ().c_str ());
#endif
    Start (endAt - Time::GetTickCount ());
}

bool    Main::_IsServiceFailed ()
{
    Debug::TraceContextBumper traceCtx (TSTR ("Stroika::Frameworks::Service::Main::_IsServiceFailed"));
#if     qPlatform_POSIX
    pid_t   servicePID  =   GetServicePID ();
    if (servicePID > 0) {
        return not _IsServiceActuallyRunning ();
    }
#endif
    return false;
}

void    Main::_CleanupDeadService ()
{
    Debug::TraceContextBumper traceCtx (TSTR ("Stroika::Frameworks::Service::Main::_CleanupDeadService"));
#if     qPlatform_POSIX
    // REALY should WAIT for server to stop and only do this it fails -
    unlink (_sRep->GetPIDFileName ().AsTString ().c_str ());
#endif
}

bool    Main::_IsServiceActuallyRunning ()
{
#if     qPlatform_POSIX
    pid_t   servicePID  =   GetServicePID ();
    if (servicePID > 0) {
        int result  =   ::kill (servicePID, 0);
        return result == 0;
    }
#endif
    return false;
}

void    Main::ReReadConfiguration ()
{
    Debug::TraceContextBumper traceCtx (TSTR ("Stroika::Frameworks::Service::Main::ReReadConfiguration"));
    // SEND APPROPRIATE SIGNAL
#if     qPlatform_POSIX
    pid_t   pid =   GetServicePID ();
    Assert (pid != 0);  // maybe throw if non-zero???
    Execution::ThrowErrNoIfNegative (kill (GetServicePID (), kSIG_ReReadConfiguration));
#endif
}

void    Main::Pause ()
{
    AssertNotImplemented ();
}

void    Main::Continue ()
{
    AssertNotImplemented ();
}

Main::ServiceDescription    Main::GetServiceDescription () const
{
    return _sRep->GetServiceDescription ();
}

#if     qPlatform_POSIX
void    Main::SignalHandler (int signum)
{
    _sRep->SignalHandler (signum);
}
#endif

bool    Main::_HandleStandardCommandLineArgument (const String& arg)
{
    Debug::TraceContextBumper traceCtx (TSTR ("Stroika::Frameworks::Service::Main::_HandleStandardCommandLineArgument"));
    if (Execution::MatchesCommandLineArgument (arg, CommandNames::kRunAsService)) {
        RunAsService ();
        return true;
    }
    else if (Execution::MatchesCommandLineArgument (arg, CommandNames::kStart)) {
        Start ();
        return true;
    }
    else if (Execution::MatchesCommandLineArgument (arg, CommandNames::kStop)) {
        Stop ();
        return true;
    }
    else if (Execution::MatchesCommandLineArgument (arg, CommandNames::kKill)) {
        Kill ();
        return true;
    }
    else if (Execution::MatchesCommandLineArgument (arg, CommandNames::kRestart)) {
        Restart ();
        return true;
    }
    else if (Execution::MatchesCommandLineArgument (arg, CommandNames::kReloadConfiguration)) {
        ReReadConfiguration ();
        return true;
    }
    else if (Execution::MatchesCommandLineArgument (arg, CommandNames::kPause)) {
        Pause ();
        return true;
    }
    else if (Execution::MatchesCommandLineArgument (arg, CommandNames::kContinue)) {
        Continue ();
        return true;
    }
    /// MANY more neeeded, and fix to use named constants...
    return false;
}

<commit_msg>fix scoped enum for POSIX specific code<commit_after>/*
 * Copyright(c) Sophist Solutions, Inc. 1990-2012.  All rights reserved
 */
#include    "../StroikaPreComp.h"

#include    <algorithm>
#include    <cstdlib>
#include    <fstream>
#include    <sstream>

#if     qPlatform_POSIX
#include    <sys/types.h>
#include    <unistd.h>
#include    <sys/stat.h>
#include    <fcntl.h>
#endif

#include    "../../Foundation/Characters/Format.h"
#include    "../../Foundation/Containers/Common.h"
#include    "../../Foundation/Debug/Assertions.h"
#include    "../../Foundation/Debug/Trace.h"
#include    "../../Foundation/Execution/CommandLine.h"
#include    "../../Foundation/Execution/Exceptions.h"
#include    "../../Foundation/Execution/ErrNoException.h"
#include    "../../Foundation/Execution/Module.h"
#include    "../../Foundation/Execution/ThreadAbortException.h"
#include    "../../Foundation/Execution/Signals.h"
#include    "../../Foundation/Execution/Sleep.h"
#include    "../../Foundation/Execution/WaitTimedOutException.h"
#include    "../../Foundation/IO/FileSystem/FileUtils.h"
#include    "../../Foundation/Memory/SmallStackBuffer.h"

#include    "Main.h"

using   namespace   Stroika::Foundation;
using   namespace   Stroika::Foundation::Containers;
using   namespace   Stroika::Foundation::Memory;

using   namespace   Stroika::Frameworks;
using   namespace   Stroika::Frameworks::Service;

/*
 ********************************************************************************
 ****************************** Service::Main::IRep *****************************
 ********************************************************************************
 */
Main::IRep::IRep ()
    : fStopping_ (false)
    , fMustReReadConfig (false)
{
}

Main::IRep::~IRep ()
{
}

void    Main::IRep::OnStartRequest ()
{
    // This procedure ends when the entire service process ends...
    Debug::TraceContextBumper traceCtx (TSTR ("Stroika::Frameworks::Service::Main::IRep::OnStartRequest"));
    MainLoop ();
}

void    Main::IRep::OnStopRequest ()
{
    Debug::TraceContextBumper traceCtx (TSTR ("Stroika::Frameworks::Service::Main::IRep::OnStopRequest"));
    // default to using thread stuff to send us a signal to abort...
    fStopping_ = true;
}

void    Main::IRep::OnReReadConfigurationRequest ()
{
    fMustReReadConfig = true;
}

String  Main::IRep::GetServiceStatusMessage () const
{
    return String ();
}

#if     qPlatform_POSIX
String  Main::IRep::GetPIDFileName () const
{
    return L"/tmp/" + GetServiceDescription ().fName + L".pid";
}
#endif

#if     qPlatform_POSIX
void    Main::IRep::SignalHandler (int signum)
{
    Debug::TraceContextBumper traceCtx (TSTR ("Stroika::Frameworks::Service::Main::IRep::SignalHandler"));
    DbgTrace (L"(signal = %s)", Execution::SignalToName (signum).c_str ());
    // VERY PRIMITIVE IMPL FOR NOW -- LGP 2011-09-24
    switch (signum) {
        case    SIGTERM:
            DbgTrace ("setting fStopping_ to true");
            fStopping_ = true;
            break;
#if     qCompilerAndStdLib_Supports_constexpr
        case    kSIG_ReReadConfiguration:
#else
        case    SIGHUP:
#endif
            OnReReadConfigurationRequest ();
            break;
    }
}
#endif

/*
 ********************************************************************************
 ************************************ Service::Main *****************************
 ********************************************************************************
 */

const   wchar_t Service::Main::CommandNames::kRunAsService[]        =   L"Run-As-Service";
const   wchar_t Service::Main::CommandNames::kStart[]               =   L"Start";
const   wchar_t Service::Main::CommandNames::kStop[]                =   L"Stop";
const   wchar_t Service::Main::CommandNames::kKill[]                =   L"Kill";
const   wchar_t Service::Main::CommandNames::kRestart[]             =   L"Restart";
const   wchar_t Service::Main::CommandNames::kReloadConfiguration[] =   L"Reload-Configuration";
const   wchar_t Service::Main::CommandNames::kPause[]               =   L"Pause";
const   wchar_t Service::Main::CommandNames::kContinue[]            =   L"Continue";

shared_ptr<Main::IRep>   Main::_sRep;

Main::Main (shared_ptr<IRep> rep)
{
    Require  (_sRep.get () == nullptr);     // singleton
    _sRep = rep;
#if     qPlatform_POSIX
    SetupSignalHanlders_ ();
#endif
}

#if     qPlatform_POSIX
void    Main::SetupSignalHanlders_ ()
{
    Execution::SignalHandlerRegistry::Get ().AddSignalHandler (SIGTERM, SignalHandler);
    Execution::SignalHandlerRegistry::Get ().AddSignalHandler (kSIG_ReReadConfiguration, SignalHandler);
}
#endif

Main::State Main::GetState () const
{
#if     qPlatform_POSIX
    if (GetServicePID () != 0) {
        return State::eRunning;
    }
#endif
    return State::eStopped;    // otherwise (esp on other platforms where not implemented) must  be stopped
}

#if     qPlatform_POSIX
pid_t   Main::GetServicePID () const
{
    ifstream    in (_sRep->GetPIDFileName ().AsTString ().c_str ());
    if (in) {
        pid_t   n = 0;
        in >> n;
        return n;
    }
    return 0;
}
#endif

String      Main::GetServiceStatusMessage () const
{
    Debug::TraceContextBumper traceCtx (TSTR ("Stroika::Frameworks::Service::Main::GetServiceStatusMessage"));
    const   wchar_t kTAB[]  =   L"    ";    // use spaces instead of tab so formatting independent of tabstop settings
    ServiceDescription  svd =   GetServiceDescription ();
    wstringstream   tmp;
    tmp << L"Service '" << svd.fName.As<wstring> () << "'" << endl;
    switch (this->GetState ()) {
        case    State::eStopped:
            tmp << kTAB << L"State:  " << kTAB << kTAB << kTAB << kTAB << "STOPPED" << endl;
            break;
        case    State::eRunning:
            tmp << kTAB << L"State:  " << kTAB << kTAB << kTAB << kTAB << "Running" << endl;
#if     qPlatform_POSIX
            tmp << kTAB << L"PID:    " << kTAB << kTAB << kTAB << kTAB << GetServicePID () << endl;
#endif
            break;
        case    State::ePaused:
            tmp << kTAB << L"State:  " << kTAB << kTAB << kTAB << kTAB << "PAUSED" << endl;
#if     qPlatform_POSIX
            tmp << kTAB << L"PID:    " << kTAB << kTAB << kTAB << kTAB << GetServicePID () << endl;
#endif
            break;
        default:
            AssertNotReached ();
    }
    tmp << _sRep->GetServiceStatusMessage ().As<wstring> ();
    DbgTrace (L"returning status: (%s)", tmp.str ().c_str ());
    return tmp.str ();
}

void    Main::RunAsService ()
{
    Debug::TraceContextBumper traceCtx (TSTR ("Stroika::Frameworks::Service::Main::RunAsService"));
    // VERY PRIMITIVE IMPL - WE NEED LOCKING on tmpfile stuff - add good tempfile supprot to fileuitls or use existing...

    try {
#if     qPlatform_POSIX
        ofstream    out (_sRep->GetPIDFileName ().AsTString ().c_str ());
        out << getpid () << endl;
#endif
        _sRep->OnStartRequest ();
    }
    catch (const Execution::ThreadAbortException& /*threadAbort*/) {
#if     qPlatform_POSIX
        unlink (_sRep->GetPIDFileName ().AsTString ().c_str ());
#endif
        // ignore this - just means service ended normally
    }
    catch (...) {
        DbgTrace (TSTR ("Unexpected exception ended running service"));
#if     qPlatform_POSIX
        unlink (_sRep->GetPIDFileName ().AsTString ().c_str ());
#endif
        throw;
    }
}

void    Main::_Start (Time::DurationSecondsType timeout)
{
    Debug::TraceContextBumper traceCtx (TSTR ("Stroika::Frameworks::Service::Main::Start"));
    DbgTrace ("(timeout = %f)", timeout);

    Time::DurationSecondsType timeoutAt =   Time::GetTickCount () + timeout;

    // Check not already runnig, (someday) and then for and exec the

    if (_IsServiceFailed ()) {
        _CleanupDeadService ();
    }

#if     qPlatform_POSIX
    // REALLY should use GETSTATE - and return state based on if PID file exsits...
    if (GetServicePID ()  != 0) {
        Execution::DoThrow (Execution::StringException (L"Cannot Start service because its already running"));
    }
#endif

    Characters::TString thisEXEPath =   Execution::GetEXEPath ();
#if     qPlatform_POSIX
    pid_t   pid =   fork ();
    Execution::ThrowErrNoIfNegative (pid);
    if (pid == 0) {
        /*
         * Very primitive code to detatch the console. No error checking cuz frankly we dont care.
         *
         * Possibly should close more descriptors?
         */
        for (int i = 0; i < 3; ++i) {
            ::close (i);
        }
        int id = open ("/dev/null", O_RDWR);
        dup2 (id, 0);
        dup2 (id, 1);
        dup2 (id, 2);

        int r   =   execl (thisEXEPath.c_str (), thisEXEPath.c_str (), (String (L"--") + String (CommandNames::kRunAsService)).AsTString ().c_str (), nullptr);
        exit (-1);
    }
    else {
        // parent - in this case - no reason to wait - our work is done... Future versions might wait to
        // see if the 'pidfile' got created....
        //      --LGP 2011-09-23
    }
#endif

    while (not _IsServiceActuallyRunning ()) {
        Execution::Sleep (0.5);
        if (Time::GetTickCount () > timeoutAt) {
            Execution::DoThrow (Execution::WaitTimedOutException ());
        }
    }
}

void    Main::_Stop (Time::DurationSecondsType timeout)
{
    Debug::TraceContextBumper traceCtx (TSTR ("Stroika::Frameworks::Service::Main::Stop"));
    DbgTrace ("(timeout = %f)", timeout);

    Time::DurationSecondsType timeoutAt =   Time::GetTickCount () + timeout;
    // Send signal to server to stop
#if     qPlatform_POSIX
    Execution::ThrowErrNoIfNegative (kill (GetServicePID (), SIGTERM));
#endif
    while (_IsServiceActuallyRunning ()) {
        Execution::Sleep (0.5);
        if (Time::GetTickCount () > timeoutAt) {
            Execution::DoThrow (Execution::WaitTimedOutException ());
        }
    }
}

void    Main::Kill ()
{
    Debug::TraceContextBumper traceCtx (TSTR ("Stroika::Frameworks::Service::Main::Kill"));
    Stop ();
    // Send signal to server to stop
#if     qPlatform_POSIX
    Execution::ThrowErrNoIfNegative (kill (GetServicePID (), SIGKILL));
    // REALY should WAIT for server to stop and only do this it fails -
    unlink (_sRep->GetPIDFileName ().AsTString ().c_str ());
#endif
}

void    Main::_Restart (Time::DurationSecondsType timeout)
{
    Debug::TraceContextBumper traceCtx (TSTR ("Stroika::Frameworks::Service::Main::Restart"));
    DbgTrace ("(timeout = %f)", timeout);

    Time::DurationSecondsType endAt =   Time::GetTickCount () + timeout;
    IgnoreExceptionsForCall (Stop (timeout));
#if     qPlatform_POSIX
    // REALY should WAIT for server to stop and only do this it fails -
    unlink (_sRep->GetPIDFileName ().AsTString ().c_str ());
#endif
    Start (endAt - Time::GetTickCount ());
}

bool    Main::_IsServiceFailed ()
{
    Debug::TraceContextBumper traceCtx (TSTR ("Stroika::Frameworks::Service::Main::_IsServiceFailed"));
#if     qPlatform_POSIX
    pid_t   servicePID  =   GetServicePID ();
    if (servicePID > 0) {
        return not _IsServiceActuallyRunning ();
    }
#endif
    return false;
}

void    Main::_CleanupDeadService ()
{
    Debug::TraceContextBumper traceCtx (TSTR ("Stroika::Frameworks::Service::Main::_CleanupDeadService"));
#if     qPlatform_POSIX
    // REALY should WAIT for server to stop and only do this it fails -
    unlink (_sRep->GetPIDFileName ().AsTString ().c_str ());
#endif
}

bool    Main::_IsServiceActuallyRunning ()
{
#if     qPlatform_POSIX
    pid_t   servicePID  =   GetServicePID ();
    if (servicePID > 0) {
        int result  =   ::kill (servicePID, 0);
        return result == 0;
    }
#endif
    return false;
}

void    Main::ReReadConfiguration ()
{
    Debug::TraceContextBumper traceCtx (TSTR ("Stroika::Frameworks::Service::Main::ReReadConfiguration"));
    // SEND APPROPRIATE SIGNAL
#if     qPlatform_POSIX
    pid_t   pid =   GetServicePID ();
    Assert (pid != 0);  // maybe throw if non-zero???
    Execution::ThrowErrNoIfNegative (kill (GetServicePID (), kSIG_ReReadConfiguration));
#endif
}

void    Main::Pause ()
{
    AssertNotImplemented ();
}

void    Main::Continue ()
{
    AssertNotImplemented ();
}

Main::ServiceDescription    Main::GetServiceDescription () const
{
    return _sRep->GetServiceDescription ();
}

#if     qPlatform_POSIX
void    Main::SignalHandler (int signum)
{
    _sRep->SignalHandler (signum);
}
#endif

bool    Main::_HandleStandardCommandLineArgument (const String& arg)
{
    Debug::TraceContextBumper traceCtx (TSTR ("Stroika::Frameworks::Service::Main::_HandleStandardCommandLineArgument"));
    if (Execution::MatchesCommandLineArgument (arg, CommandNames::kRunAsService)) {
        RunAsService ();
        return true;
    }
    else if (Execution::MatchesCommandLineArgument (arg, CommandNames::kStart)) {
        Start ();
        return true;
    }
    else if (Execution::MatchesCommandLineArgument (arg, CommandNames::kStop)) {
        Stop ();
        return true;
    }
    else if (Execution::MatchesCommandLineArgument (arg, CommandNames::kKill)) {
        Kill ();
        return true;
    }
    else if (Execution::MatchesCommandLineArgument (arg, CommandNames::kRestart)) {
        Restart ();
        return true;
    }
    else if (Execution::MatchesCommandLineArgument (arg, CommandNames::kReloadConfiguration)) {
        ReReadConfiguration ();
        return true;
    }
    else if (Execution::MatchesCommandLineArgument (arg, CommandNames::kPause)) {
        Pause ();
        return true;
    }
    else if (Execution::MatchesCommandLineArgument (arg, CommandNames::kContinue)) {
        Continue ();
        return true;
    }
    /// MANY more neeeded, and fix to use named constants...
    return false;
}

<|endoftext|>


<commit_before>/**
 * @attention
 * Generated by jccpy {{jcppy_version}}~{{jcppy_revision}}.
 * Do not edit!
 */

#include <cstring>
#include <sstream>
#include <stdexcept>
#include <algorithm>
#include <iterator>
#include <inttypes.h>
#include <cstring>
#include <cstdio>
#include "{{header_filename}}"

/*********************************************************/
/*         Inline embedjson library goes below           */
/*********************************************************/

{{embedjson}}

/*********************************************************/
/*         End of inline embedjson library               */
/*********************************************************/

{{Name}}::{{Name}}()
{
}

{{Name}} {{Name}}::fromJson(const std::string& json)
{
  return fromJson(json.data(), json.size());
}

{{Name}} {{Name}}::fromJson(const char* json, std::size_t size)
{
  {{Name}}Reader reader;
  reader.read(json, size);
  return reader.instance();
}

{{Name}} {{Name}}::readJson(std::istream& stream)
{
  char buffer[1024];
  {{Name}}Reader reader;
  while (stream.good()) {
    stream.read(buffer, sizeof(buffer));
    std::size_t nread = stream ? sizeof(buffer) : stream.gcount();
    reader.read(buffer, nread);
  }
  return reader.instance();
}

std::string {{Name}}::toJson() const
{
  std::stringstream ss;
  writeJson(ss);
  return ss.str();
}

std::ostream& {{Name}}::writeJson(std::ostream& stream) const
{
  std::ostream_iterator<char> out(stream);
  {{Name}}Writer writer(this);
  writer.write(out, true);
  return stream;
}

<commit_msg>Configure embedjson before inclusion<commit_after>/**
 * @attention
 * Generated by jccpy {{jcppy_version}}~{{jcppy_revision}}.
 * Do not edit!
 */

#include <cstring>
#include <sstream>
#include <stdexcept>
#include <algorithm>
#include <iterator>
#include <inttypes.h>
#include <cstring>
#include <cstdio>
#include <cstddef>
#include "{{header_filename}}"

/*********************************************************/
/*         Inline embedjson library goes below           */
/*********************************************************/

#define EMBEDJSON_DYNAMIC_STACK 0
#define EMBEDJSON_STATIC_STACK_SIZE 16
#define EMBEDJSON_VALIDATE_UTF8 1
#define EMBEDJSON_SIZE_T std::size_t
{{embedjson}}

/*********************************************************/
/*         End of inline embedjson library               */
/*********************************************************/

{{Name}}::{{Name}}()
{
}

{{Name}} {{Name}}::fromJson(const std::string& json)
{
  return fromJson(json.data(), json.size());
}

{{Name}} {{Name}}::fromJson(const char* json, std::size_t size)
{
  {{Name}}Reader reader;
  reader.read(json, size);
  return reader.instance();
}

{{Name}} {{Name}}::readJson(std::istream& stream)
{
  char buffer[1024];
  {{Name}}Reader reader;
  while (stream.good()) {
    stream.read(buffer, sizeof(buffer));
    std::size_t nread = stream ? sizeof(buffer) : stream.gcount();
    reader.read(buffer, nread);
  }
  return reader.instance();
}

std::string {{Name}}::toJson() const
{
  std::stringstream ss;
  writeJson(ss);
  return ss.str();
}

std::ostream& {{Name}}::writeJson(std::ostream& stream) const
{
  std::ostream_iterator<char> out(stream);
  {{Name}}Writer writer(this);
  writer.write(out, true);
  return stream;
}

<|endoftext|>


<commit_before><commit_msg>Checking buffer underlying resource<commit_after><|endoftext|>


<commit_before>#include <signal.h>
#include <kapplication.h>
#include <klocale.h>
#include <kcmdlineargs.h>
#include <kaboutdata.h>
#include <kdebug.h>
#include "version.h"
#include "mainwindow.h"

namespace
{
  const char* description = I18N_NOOP("KDE Time tracker tool");

  void cleanup( int )
  {
    kdDebug(5970) << i18n("Just caught a software interrupt.") << endl;
    kapp->exit();
  }
}

static const KCmdLineOptions options[] =
{
  { "+file", I18N_NOOP( "The iCalendar file to open" ), 0 },
  KCmdLineLastOption
};

int main( int argc, char *argv[] )
{
  KAboutData aboutData( "karm", I18N_NOOP("KArm"),
      KARM_VERSION, description, KAboutData::License_GPL,
      "(c) 1997-2004, KDE PIM Developers" );

  aboutData.addAuthor( "Mark Bucciarelli", I18N_NOOP( "Current Maintainer" ),
                       "mark@hubcapconsulting.com" );
  aboutData.addAuthor( "Sirtaj Singh Kang", I18N_NOOP( "Original Author" ),
                       "taj@kde.org" );
  aboutData.addAuthor( "Allen Winter",      0, "winterz@verizon.net" );
  aboutData.addAuthor( "David Faure",       0, "faure@kde.org" );
  aboutData.addAuthor( "Espen Sand",        0, "espen@kde.org" );
  aboutData.addAuthor( "Gioele Barabucci",  0, "gioele@gioelebarabucci.com" );
  aboutData.addAuthor( "Jan Schaumann",     0, "jschauma@netmeister.org" );
  aboutData.addAuthor( "Jesper Pedersen",   0, "blackie@kde.org" );
  aboutData.addAuthor( "Kalle Dalheimer",   0, "kalle@kde.org" );
  aboutData.addAuthor( "Scott Monachello",  0, "smonach@cox.net" );
  aboutData.addAuthor( "Thorsten Staerk",   0, "kde@staerk.de" );
  aboutData.addAuthor( "Tomas Pospisek",    0, "tpo_deb@sourcepole.ch" );
  aboutData.addAuthor( "Willi Richert",     0, "w.richert@gmx.net" );

  KCmdLineArgs::init( argc, argv, &aboutData );
  KCmdLineArgs::addCmdLineOptions( options );
  KApplication myApp;

  KCmdLineArgs *args = KCmdLineArgs::parsedArgs();

  MainWindow *mainWindow;
  if ( args->count() > 0 )
  {
    QString icsfile = QString::fromLocal8Bit( args->arg( 0 ) );
    // FIXME: there is probably a Qt or KDE fcn for this test
    if ( icsfile.startsWith( "/" )
        || icsfile.toLower().startsWith( "http://" )
        || icsfile.toLower().startsWith( "ftp://" )
        )
    {
      // leave as is
      ;
    }
    else
    {
      icsfile = KCmdLineArgs::cwd() + "/" + icsfile;
    }
    mainWindow = new MainWindow( icsfile );
  }
  else
  {
    mainWindow = new MainWindow();
  }

  myApp.setMainWidget( mainWindow );

  if (kapp->isSessionRestored() && KMainWindow::canBeRestored( 1 ))
    mainWindow->restore( 1, false );
  else
    mainWindow->show();

  signal( SIGQUIT, cleanup );
  signal( SIGINT, cleanup );
  int ret = myApp.exec();

  delete mainWindow;
  return ret;
}
<commit_msg>find out protocol by KURL means<commit_after>#include <signal.h>
#include <kapplication.h>
#include <klocale.h>
#include <kcmdlineargs.h>
#include <kaboutdata.h>
#include <kdebug.h>
#include "version.h"
#include "mainwindow.h"

namespace
{
  const char* description = I18N_NOOP("KDE Time tracker tool");

  void cleanup( int )
  {
    kdDebug(5970) << i18n("Just caught a software interrupt.") << endl;
    kapp->exit();
  }
}

static const KCmdLineOptions options[] =
{
  { "+file", I18N_NOOP( "The iCalendar file to open" ), 0 },
  KCmdLineLastOption
};

int main( int argc, char *argv[] )
{
  KAboutData aboutData( "karm", I18N_NOOP("KArm"),
      KARM_VERSION, description, KAboutData::License_GPL,
      "(c) 1997-2004, KDE PIM Developers" );

  aboutData.addAuthor( "Mark Bucciarelli", I18N_NOOP( "Current Maintainer" ),
                       "mark@hubcapconsulting.com" );
  aboutData.addAuthor( "Sirtaj Singh Kang", I18N_NOOP( "Original Author" ),
                       "taj@kde.org" );
  aboutData.addAuthor( "Allen Winter",      0, "winterz@verizon.net" );
  aboutData.addAuthor( "David Faure",       0, "faure@kde.org" );
  aboutData.addAuthor( "Espen Sand",        0, "espen@kde.org" );
  aboutData.addAuthor( "Gioele Barabucci",  0, "gioele@gioelebarabucci.com" );
  aboutData.addAuthor( "Jan Schaumann",     0, "jschauma@netmeister.org" );
  aboutData.addAuthor( "Jesper Pedersen",   0, "blackie@kde.org" );
  aboutData.addAuthor( "Kalle Dalheimer",   0, "kalle@kde.org" );
  aboutData.addAuthor( "Scott Monachello",  0, "smonach@cox.net" );
  aboutData.addAuthor( "Thorsten Staerk",   0, "kde@staerk.de" );
  aboutData.addAuthor( "Tomas Pospisek",    0, "tpo_deb@sourcepole.ch" );
  aboutData.addAuthor( "Willi Richert",     0, "w.richert@gmx.net" );

  KCmdLineArgs::init( argc, argv, &aboutData );
  KCmdLineArgs::addCmdLineOptions( options );
  KApplication myApp;

  KCmdLineArgs *args = KCmdLineArgs::parsedArgs();

  MainWindow *mainWindow;
  if ( args->count() > 0 )
  {
    QString icsfile = QString::fromLocal8Bit( args->arg( 0 ) );

    KURL* icsfileurl=new KURL(QString::fromLocal8Bit( args->arg( 0 ) ));
    if (( icsfileurl->protocol() == "http" ) || ( icsfileurl->protocol() == "ftp" ) || ( icsfileurl->isLocalFile() ))
    {
      // leave as is
      ;
    }
    else
    {
      icsfile = KCmdLineArgs::cwd() + "/" + icsfile;
    }
    mainWindow = new MainWindow( icsfile );
  }
  else
  {
    mainWindow = new MainWindow();
  }

  myApp.setMainWidget( mainWindow );

  if (kapp->isSessionRestored() && KMainWindow::canBeRestored( 1 ))
    mainWindow->restore( 1, false );
  else
    mainWindow->show();

  signal( SIGQUIT, cleanup );
  signal( SIGINT, cleanup );
  int ret = myApp.exec();

  delete mainWindow;
  return ret;
}
<|endoftext|>


<commit_before>// ------------------------------------------------------------------------
// kvu_fd_io.cpp: Helper functions for reading from, writing to and
//                waiting on UNIX file descriptors.
//
// Copyright (C) 2002 Kai Vehmanen (kai.vehmanen@wakkanet.fi)
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 2 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307  USA
// ------------------------------------------------------------------------

#include <unistd.h>      /* POSIX: read()/write() */
#include <sys/poll.h>    /* XPG4-UNIX: poll() */

#include "kvu_fd_io.h"

/**
 * Attempts to read up to 'count' bytes from file descriptor 'fd'
 * into the buffer starting at 'buf'. If no data is available
 * for reading, up to 'timeout' milliseconds will be waited.
 * A negative value means infinite timeout.
 */
ssize_t kvu_fd_read(int fd, void *buf, size_t count, int timeout)
{
  int nfds = 1;
  struct pollfd ufds;
  ssize_t rescount = 0;

  ufds.fd = fd;
  ufds.events = POLLIN | POLLPRI;
  ufds.revents = 0;

  int ret = poll(&ufds, nfds, timeout);
  if (ret > 0) {
    if (ufds.revents & POLLIN ||
	ufds.revents & POLLPRI) {
      rescount = ::read(fd, buf, count);
    }
  }
  else if (ret == 0) {
    /* timeout */
    rescount = -1;
  }
  return(rescount);
}

/**
 * Attempts to write up to 'count' bytes to file descriptor 'fd'
 * from the buffer starting at 'buf'. If no space is available
 * for writing, up to 'timeout' milliseconds will be waited.
 * A negative value means infinite timeout.
 */
ssize_t kvu_fd_write(int fd, const void *buf, size_t count, int timeout)
{
  int nfds = 1;
  struct pollfd ufds;
  ssize_t rescount = 0;

  ufds.fd = fd;
  ufds.events = POLLOUT;
  ufds.revents = 0;

  int ret = poll(&ufds, nfds, timeout);
  if (ret > 0) {
    if (ufds.revents & POLLOUT) {
      rescount = ::write(fd, buf, count);
    }
  }
  else if (ret == 0) {
    /* timeout */
    rescount = -1;
  }
  return(rescount);
}

/**
 * Blocks until state of file descriptor 'fd'
 * changes. State changes include 'fd' becoming
 * readable, writing or an error condition.
 * A maximum of 'timeout' milliseconds will be
 * waited. A negative value means infinite timeout.
 *
 * @return on success returns 0, on error -1
 */
int kvu_fd_wait(int fd, int timeout)
{
  int nfds = 1;
  struct pollfd ufds;

  ufds.fd = fd;
  ufds.events = POLLIN | POLLPRI | POLLOUT;
  ufds.revents = 0;

  int ret = poll(&ufds, nfds, timeout);
  if (ret > 0) {
    if (ufds.revents & POLLERR ||
	ufds.revents & POLLHUP ||
	ufds.revents & POLLNVAL) {
      ret = -1;
    }
    else if (ret == 0) {
      /* timeout */
      ret = -1;
    }
  }
  return(ret);
}
<commit_msg>Fix kvu_fd_wait return values.<commit_after>// ------------------------------------------------------------------------
// kvu_fd_io.cpp: Helper functions for reading from, writing to and
//                waiting on UNIX file descriptors.
//
// Copyright (C) 2002 Kai Vehmanen (kai.vehmanen@wakkanet.fi)
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 2 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307  USA
// ------------------------------------------------------------------------

#include <unistd.h>      /* POSIX: read()/write() */
#include <sys/poll.h>    /* XPG4-UNIX: poll() */

#include "kvu_fd_io.h"

/**
 * Attempts to read up to 'count' bytes from file descriptor 'fd'
 * into the buffer starting at 'buf'. If no data is available
 * for reading, up to 'timeout' milliseconds will be waited.
 * A negative value means infinite timeout.
 */
ssize_t kvu_fd_read(int fd, void *buf, size_t count, int timeout)
{
  int nfds = 1;
  struct pollfd ufds;
  ssize_t rescount = 0;

  ufds.fd = fd;
  ufds.events = POLLIN | POLLPRI;
  ufds.revents = 0;

  int ret = poll(&ufds, nfds, timeout);
  if (ret > 0) {
    if (ufds.revents & POLLIN ||
	ufds.revents & POLLPRI) {
      rescount = ::read(fd, buf, count);
    }
  }
  else if (ret == 0) {
    /* timeout */
    rescount = -1;
  }
  return(rescount);
}

/**
 * Attempts to write up to 'count' bytes to file descriptor 'fd'
 * from the buffer starting at 'buf'. If no space is available
 * for writing, up to 'timeout' milliseconds will be waited.
 * A negative value means infinite timeout.
 */
ssize_t kvu_fd_write(int fd, const void *buf, size_t count, int timeout)
{
  int nfds = 1;
  struct pollfd ufds;
  ssize_t rescount = 0;

  ufds.fd = fd;
  ufds.events = POLLOUT;
  ufds.revents = 0;

  int ret = poll(&ufds, nfds, timeout);
  if (ret > 0) {
    if (ufds.revents & POLLOUT) {
      rescount = ::write(fd, buf, count);
    }
  }
  else if (ret == 0) {
    /* timeout */
    rescount = -1;
  }
  return(rescount);
}

/**
 * Blocks until state of file descriptor 'fd'
 * changes. State changes include 'fd' becoming
 * readable, writing or an error condition.
 * A maximum of 'timeout' milliseconds will be
 * waited. A negative value means infinite timeout.
 *
 * @return returns 1 for success, 0 for timeout
 *         and -1 on error
 */
int kvu_fd_wait(int fd, int timeout)
{
  int nfds = 1;
  struct pollfd ufds;

  ufds.fd = fd;
  ufds.events = POLLIN | POLLPRI | POLLOUT;
  ufds.revents = 0;

  int ret = poll(&ufds, nfds, timeout);
  if (ret > 0) {
    if (ufds.revents & POLLERR ||
	ufds.revents & POLLHUP ||
	ufds.revents & POLLNVAL) {
      /* error */
      return(-1);
    }
    else {
      /* success */
      return(1);
    }
  }
  else if (ret == 0) {
    /* timeout */
    return(0);
  }

  /* error */
  return(-1);
}
<|endoftext|>


<commit_before>#include <vector>
#include <cmath>
#include <sstream>

#include "Tools/Exception/exception.hpp"

#include "Encoder_polar.hpp"

using namespace aff3ct::module;

template <typename B>
Encoder_polar<B>
::Encoder_polar(const int& K, const int& N, const std::vector<bool>& frozen_bits, const int n_frames)
: Encoder<B>(K, N, n_frames), m((int)std::log2(N)), frozen_bits(frozen_bits), X_N_tmp(this->N)
{
	const std::string name = "Encoder_polar";
	this->set_name(name);
	this->set_sys(false);

	if (this->N != (int)frozen_bits.size())
	{
		std::stringstream message;
		message << "'frozen_bits.size()' has to be equal to 'N' ('frozen_bits.size()' = " << frozen_bits.size()
		        << ", 'N' = " << N << ").";
		throw tools::length_error(__FILE__, __LINE__, __func__, message.str());
	}

	auto k = 0; for (auto i = 0; i < this->N; i++) if (frozen_bits[i] == 0) k++;
	if (this->K != k)
	{
		std::stringstream message;
		message << "The number of information bits in the frozen_bits is invalid ('K' = " << K << ", 'k' = "
		        << k << ").";
		throw tools::runtime_error(__FILE__, __LINE__, __func__, message.str());
	}

	this->notify_frozenbits_update();
}

template <typename B>
void Encoder_polar<B>
::_encode(const B *U_K, B *X_N, const int frame_id)
{
	this->convert(U_K, X_N);
	this->light_encode(X_N);
}

template <typename B>
void Encoder_polar<B>
::light_encode(B *bits)
{
	for (auto k = (this->N >> 1); k > 0; k >>= 1)
		for (auto j = 0; j < this->N; j += 2 * k)
			for (auto i = 0; i < k; i++)
				bits[j + i] = bits[j + i] ^ bits[k + j + i];
}

template <typename B>
void Encoder_polar<B>
::convert(const B *U_K, B *U_N)
{
	if (U_K == U_N)
	{
		std::vector<B> U_K_tmp(this->K);
		std::copy(U_K, U_K + this->K, U_K_tmp.begin());

		auto j = 0;
		for (unsigned i = 0; i < frozen_bits.size(); i++)
			U_N[i] = (frozen_bits[i]) ? (B)0 : U_K_tmp[j++];
	}
	else
	{
		auto j = 0;
		for (unsigned i = 0; i < frozen_bits.size(); i++)
			U_N[i] = (frozen_bits[i]) ? (B)0 : U_K[j++];
	}
}

template <typename B>
bool Encoder_polar<B>
::is_codeword(const B *X_N)
{
	for (auto i = 0; i < this->N; i++)
		this->X_N_tmp[i] = (B)(!this->frozen_bits[i]) && X_N[i];
	this->light_encode(this->X_N_tmp.data());

	for (auto i = 0; i < this->N; i++)
		this->X_N_tmp[i] = (B)(!this->frozen_bits[i]) && this->X_N_tmp[i];
	this->light_encode(this->X_N_tmp.data());

	auto n = 0;
	while (n < this->N && (X_N[n] == this->X_N_tmp[n])) n++;

	return n == this->N;
}

template <typename B>
void Encoder_polar<B>
::notify_frozenbits_update()
{
	auto k = 0;
	for (auto n = 0; n < this->N; n++)
		if (!frozen_bits[n])
			this->info_bits_pos[k++] = n;
}

// ==================================================================================== explicit template instantiation
#include "Tools/types.h"
#ifdef MULTI_PREC
template class aff3ct::module::Encoder_polar<B_8>;
template class aff3ct::module::Encoder_polar<B_16>;
template class aff3ct::module::Encoder_polar<B_32>;
template class aff3ct::module::Encoder_polar<B_64>;
#else
template class aff3ct::module::Encoder_polar<B>;
#endif
// ==================================================================================== explicit template instantiation
<commit_msg>Speedup the Polar encoder 'is_codeword()' method.<commit_after>#include <vector>
#include <cmath>
#include <sstream>

#include "Tools/Exception/exception.hpp"

#include "Encoder_polar.hpp"

using namespace aff3ct::module;

template <typename B>
Encoder_polar<B>
::Encoder_polar(const int& K, const int& N, const std::vector<bool>& frozen_bits, const int n_frames)
: Encoder<B>(K, N, n_frames), m((int)std::log2(N)), frozen_bits(frozen_bits), X_N_tmp(this->N)
{
	const std::string name = "Encoder_polar";
	this->set_name(name);
	this->set_sys(false);

	if (this->N != (int)frozen_bits.size())
	{
		std::stringstream message;
		message << "'frozen_bits.size()' has to be equal to 'N' ('frozen_bits.size()' = " << frozen_bits.size()
		        << ", 'N' = " << N << ").";
		throw tools::length_error(__FILE__, __LINE__, __func__, message.str());
	}

	auto k = 0; for (auto i = 0; i < this->N; i++) if (frozen_bits[i] == 0) k++;
	if (this->K != k)
	{
		std::stringstream message;
		message << "The number of information bits in the frozen_bits is invalid ('K' = " << K << ", 'k' = "
		        << k << ").";
		throw tools::runtime_error(__FILE__, __LINE__, __func__, message.str());
	}

	this->notify_frozenbits_update();
}

template <typename B>
void Encoder_polar<B>
::_encode(const B *U_K, B *X_N, const int frame_id)
{
	this->convert(U_K, X_N);
	this->light_encode(X_N);
}

template <typename B>
void Encoder_polar<B>
::light_encode(B *bits)
{
	for (auto k = (this->N >> 1); k > 0; k >>= 1)
		for (auto j = 0; j < this->N; j += 2 * k)
			for (auto i = 0; i < k; i++)
				bits[j + i] = bits[j + i] ^ bits[k + j + i];
}

template <typename B>
void Encoder_polar<B>
::convert(const B *U_K, B *U_N)
{
	if (U_K == U_N)
	{
		std::vector<B> U_K_tmp(this->K);
		std::copy(U_K, U_K + this->K, U_K_tmp.begin());

		auto j = 0;
		for (unsigned i = 0; i < frozen_bits.size(); i++)
			U_N[i] = (frozen_bits[i]) ? (B)0 : U_K_tmp[j++];
	}
	else
	{
		auto j = 0;
		for (unsigned i = 0; i < frozen_bits.size(); i++)
			U_N[i] = (frozen_bits[i]) ? (B)0 : U_K[j++];
	}
}

#include <iostream>

template <typename B>
bool Encoder_polar<B>
::is_codeword(const B *X_N)
{
	std::copy(X_N, X_N + this->N, this->X_N_tmp.data());

	for (auto k = (this->N >> 1); k > 0; k >>= 1)
		for (auto j = 0; j < this->N; j += 2 * k)
		{
			for (auto i = 0; i < k; i++)
				this->X_N_tmp[j + i] = this->X_N_tmp[j + i] ^ this->X_N_tmp[k + j + i];

			if (this->frozen_bits[j + k -1] && this->X_N_tmp[j + k -1])
				return false;
		}

	return true;
}

template <typename B>
void Encoder_polar<B>
::notify_frozenbits_update()
{
	auto k = 0;
	for (auto n = 0; n < this->N; n++)
		if (!frozen_bits[n])
			this->info_bits_pos[k++] = n;
}

// ==================================================================================== explicit template instantiation
#include "Tools/types.h"
#ifdef MULTI_PREC
template class aff3ct::module::Encoder_polar<B_8>;
template class aff3ct::module::Encoder_polar<B_16>;
template class aff3ct::module::Encoder_polar<B_32>;
template class aff3ct::module::Encoder_polar<B_64>;
#else
template class aff3ct::module::Encoder_polar<B>;
#endif
// ==================================================================================== explicit template instantiation
<|endoftext|>


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

  Program:   ORFEO Toolbox
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

  Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.
  See OTBCopyright.txt for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notices for more information.

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

#include "otbSamplerBase.h"
#include "otbMath.h"

namespace otb
{

void
SamplerBase::Reset(void)
{
  this->m_ChosenElements = 0UL;
  this->m_ProcessedElements = 0UL;
}

void
SamplerBase::SetNumberOfElements(unsigned long needed, unsigned long total)
{
  bool modified = false;
  if (needed > total)
    {
    itkExceptionMacro(<< "Needed elements (" << needed <<
      ") greater than total elements" << total << ")." << std::endl);
    }
  if (m_NeededElements != needed)
    {
    m_NeededElements = needed;
    modified = true;
    }
  if (m_TotalElements != total)
    {
    m_TotalElements = total;
    modified = true;
    }
  if (modified)
    {
    if (m_TotalElements > 0)
      {
      m_Rate = (double)(m_NeededElements) / (double)(m_TotalElements);
      }
    else
      {
      m_Rate = 0.0;
      }
    this->Modified();
    }
}

void
SamplerBase::SetRate(double rate, unsigned long total)
{
  bool modified = false;
  if (m_Rate != rate)
    {
    m_Rate = rate;
    modified = true;
    }
  if (m_TotalElements != total)
    {
    m_TotalElements = total;
    modified = true;
    }
  if (modified)
    {
    m_NeededElements = (unsigned long)(vcl_floor(0.5 + m_Rate * (double)(m_TotalElements) ));
    this->Modified();
    }
}

SamplerBase::SamplerBase()
  : m_ChosenElements(0UL)
  , m_ProcessedElements(0UL)
  , m_TotalElements(0UL)
  , m_NeededElements(0UL)
  , m_Rate(0.0)
{
}

}
<commit_msg>ENH: clamp values given to any Sampler<commit_after>/*=========================================================================

  Program:   ORFEO Toolbox
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

  Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.
  See OTBCopyright.txt for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notices for more information.

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

#include "otbSamplerBase.h"
#include "otbMath.h"

namespace otb
{

void
SamplerBase::Reset(void)
{
  this->m_ChosenElements = 0UL;
  this->m_ProcessedElements = 0UL;
}

void
SamplerBase::SetNumberOfElements(unsigned long needed, unsigned long total)
{
  bool modified = false;
  unsigned long neededChecked = needed;
  if (needed > total)
    {
    itkWarningMacro(<< "Needed elements (" << needed <<
      ") will be clamped to total elements (" << total << ")" << std::endl);
    neededChecked = total;
    }
  if (m_NeededElements != neededChecked)
    {
    m_NeededElements = neededChecked;
    modified = true;
    }
  if (m_TotalElements != total)
    {
    m_TotalElements = total;
    modified = true;
    }
  if (modified)
    {
    if (m_TotalElements > 0)
      {
      m_Rate = (double)(m_NeededElements) / (double)(m_TotalElements);
      }
    else
      {
      m_Rate = 0.0;
      }
    this->Modified();
    }
}

void
SamplerBase::SetRate(double rate, unsigned long total)
{
  bool modified = false;
  double rateChecked = rate;
  if (rate > 1.0)
    {
    itkWarningMacro(<< "Rate (" << rate <<
      ") will be clamped to 1.0" << std::endl);
    rateChecked = 1.0;
    }
  if (rate < 0.0)
    {
    itkWarningMacro(<< "Rate (" << rate <<
      ") will be clamped to 0.0" << std::endl);
    rateChecked = 0.0;
    }
  if (m_Rate != rateChecked)
    {
    m_Rate = rateChecked;
    modified = true;
    }
  if (m_TotalElements != total)
    {
    m_TotalElements = total;
    modified = true;
    }
  if (modified)
    {
    m_NeededElements = (unsigned long)(vcl_floor(0.5 + m_Rate * (double)(m_TotalElements) ));
    this->Modified();
    }
}

SamplerBase::SamplerBase()
  : m_ChosenElements(0UL)
  , m_ProcessedElements(0UL)
  , m_TotalElements(0UL)
  , m_NeededElements(0UL)
  , m_Rate(0.0)
{
}

}
<|endoftext|>


<commit_before>/*
 * Copyright (C) 2017 Smirnov Vladimir mapron1@gmail.com
 * Source code licensed under the Apache License, Version 2.0 (the "License");
 * You may not use this file except in compliance with the License.
 * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 or in file COPYING-APACHE-2.0.txt
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.h
 */

#include "GccCommandLineParser.h"
#include <StringUtils.h>

namespace Wuild
{

void GccCommandLineParser::UpdateInfo()
{
	bool skipNext = false;
	int argIndex = -1;
	m_invocation.m_inputNameIndex  = -1;
	m_invocation.m_outputNameIndex = -1;
	m_invocation.m_type = ToolInvocation::InvokeType::Unknown;
	for (const auto & arg : m_invocation.m_args)
	{
		argIndex ++;
		if (skipNext)
		{
			skipNext = false;
			continue;
		}
		if (arg.size() > 1 && arg[0] == '-')
		{
			if (arg[1] == 'c')
			{
				m_invokeTypeIndex = argIndex;
				m_invocation.m_type = ToolInvocation::InvokeType::Compile;
			}
			if (arg[1] == 'E')
			{
				m_invokeTypeIndex = argIndex;
				m_invocation.m_type = ToolInvocation::InvokeType::Preprocess;
			}
			if (arg[1] == 'o')
			{
				m_invocation.m_outputNameIndex = argIndex + 1;
				skipNext = true;
			}
			if (arg[1] == 'x')
			{
				skipNext = true;
			}
			if (arg == "-MF" || arg == "-MT" || arg == "-isysroot" || arg == "-isystem" || arg == "-iframework")
				skipNext = true;

			continue;
		}
		else if (!IsIgnored(arg))
		{
			if (m_invocation.m_inputNameIndex != -1)
			{
				m_invocation.m_type = ToolInvocation::InvokeType::Unknown;
				return;
			}
		   m_invocation.m_inputNameIndex = argIndex;
		}
	}
	if (m_invocation.m_inputNameIndex == -1 || m_invocation.m_outputNameIndex == -1 || m_invocation.m_outputNameIndex >= (int)m_invocation.m_args.size())
	{
		m_invocation.m_inputNameIndex = -1;
		m_invocation.m_outputNameIndex = -1;
		m_invocation.m_type = ToolInvocation::InvokeType::Unknown;
	}

}

void GccCommandLineParser::SetInvokeType(ToolInvocation::InvokeType type)
{
	if (m_invocation.m_type == ToolInvocation::InvokeType::Unknown)
		return;

	m_invocation.m_type = type;
	m_invocation.m_args[m_invokeTypeIndex] = type == ToolInvocation::InvokeType::Preprocess ? "-E" : "-c";
}

void GccCommandLineParser::RemoveDependencyFiles()
{
	StringVector newArgs;
	bool skipNext = false;
	for (const auto &arg : m_invocation.m_args)
	{
		if (skipNext)
		{
			skipNext = false;
			continue;
		}
		if (arg == "-MMD" || arg == "-MD")
			continue;
		if (arg == "-MF" || arg == "-MT")
		{
			skipNext = true;
			continue;
		}
		newArgs.push_back(arg);
	}
	m_invocation.m_args = newArgs;
	UpdateInfo();
}

void GccCommandLineParser::RemovePrepocessorFlags()
{
	StringVector newArgs;
	bool skipNext = false;
	for (const auto & arg : m_invocation.m_args)
	{
		if (skipNext)
		{
			skipNext = false;
			continue;
		}
		if (arg.size() > 1 && arg[0] == '-')
		{
			if (arg[1] == 'I' || arg[1] == 'D' || arg[1] == 'F' )
				continue;

			if (arg == "-isysroot" || arg == "-iframework" || arg == "-isystem" )
			{
				skipNext = true;
				continue;
			}
		}
		newArgs.push_back(arg);
	}
	m_invocation.m_args = newArgs;
	UpdateInfo();
}

}
<commit_msg>Fixed serialize-diagnostics argument parsing.<commit_after>/*
 * Copyright (C) 2017 Smirnov Vladimir mapron1@gmail.com
 * Source code licensed under the Apache License, Version 2.0 (the "License");
 * You may not use this file except in compliance with the License.
 * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 or in file COPYING-APACHE-2.0.txt
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.h
 */

#include "GccCommandLineParser.h"
#include <StringUtils.h>

namespace Wuild
{

void GccCommandLineParser::UpdateInfo()
{
	bool skipNext = false;
	int argIndex = -1;
	m_invocation.m_inputNameIndex  = -1;
	m_invocation.m_outputNameIndex = -1;
	m_invocation.m_type = ToolInvocation::InvokeType::Unknown;
	for (const auto & arg : m_invocation.m_args)
	{
		argIndex ++;
		if (skipNext)
		{
			skipNext = false;
			continue;
		}
		if (arg.size() > 1 && arg[0] == '-')
		{
			if (arg[1] == 'c')
			{
				m_invokeTypeIndex = argIndex;
				m_invocation.m_type = ToolInvocation::InvokeType::Compile;
			}
			if (arg[1] == 'E')
			{
				m_invokeTypeIndex = argIndex;
				m_invocation.m_type = ToolInvocation::InvokeType::Preprocess;
			}
			if (arg[1] == 'o')
			{
				m_invocation.m_outputNameIndex = argIndex + 1;
				skipNext = true;
			}
			if (arg[1] == 'x')
			{
				skipNext = true;
			}
			if (arg == "-MF" || arg == "-MT" || arg == "-isysroot" || arg == "-isystem" || arg == "-iframework" || arg == "--serialize-diagnostics" || arg == "-arch")
				skipNext = true;

			continue;
		}
		else if (!IsIgnored(arg))
		{
			if (m_invocation.m_inputNameIndex != -1)
			{
				m_invocation.m_type = ToolInvocation::InvokeType::Unknown;
				return;
			}
		   m_invocation.m_inputNameIndex = argIndex;
		}
	}
	if (m_invocation.m_inputNameIndex == -1 || m_invocation.m_outputNameIndex == -1 || m_invocation.m_outputNameIndex >= (int)m_invocation.m_args.size())
	{
		m_invocation.m_inputNameIndex = -1;
		m_invocation.m_outputNameIndex = -1;
		m_invocation.m_type = ToolInvocation::InvokeType::Unknown;
	}

}

void GccCommandLineParser::SetInvokeType(ToolInvocation::InvokeType type)
{
	if (m_invocation.m_type == ToolInvocation::InvokeType::Unknown)
		return;

	m_invocation.m_type = type;
	m_invocation.m_args[m_invokeTypeIndex] = type == ToolInvocation::InvokeType::Preprocess ? "-E" : "-c";
}

void GccCommandLineParser::RemoveDependencyFiles()
{
	StringVector newArgs;
	bool skipNext = false;
	for (const auto &arg : m_invocation.m_args)
	{
		if (skipNext)
		{
			skipNext = false;
			continue;
		}
		if (arg == "-MMD" || arg == "-MD")
			continue;
		if (arg == "-MF" || arg == "-MT")
		{
			skipNext = true;
			continue;
		}
		newArgs.push_back(arg);
	}
	m_invocation.m_args = newArgs;
	UpdateInfo();
}

void GccCommandLineParser::RemovePrepocessorFlags()
{
	StringVector newArgs;
	bool skipNext = false;
	for (const auto & arg : m_invocation.m_args)
	{
		if (skipNext)
		{
			skipNext = false;
			continue;
		}
		if (arg.size() > 1 && arg[0] == '-')
		{
			if (arg[1] == 'I' || arg[1] == 'D' || arg[1] == 'F' )
				continue;

			if (arg == "-isysroot" || arg == "-iframework" || arg == "-isystem" || arg == "--serialize-diagnostics")
			{
				skipNext = true;
				continue;
			}
		}
		newArgs.push_back(arg);
	}
	m_invocation.m_args = newArgs;
	UpdateInfo();
}

}
<|endoftext|>


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

The Medical Imaging Interaction Toolkit (MITK)

Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics.
All rights reserved.

This software is distributed WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE.

See LICENSE.txt or http://www.mitk.org for details.

===================================================================*/
#include <mitkCommon.h>
#include <usModuleContext.h>
#include <usServiceReference.h>
#include <usGetModuleContext.h>
#include <mitkTestingMacros.h>
#include <mitkIPersistenceService.h>
#include <mitkPersistenceService.h>
#include <mitkSceneIO.h>
#include <mitkIOUtil.h>
#include <itksys\SystemTools.hxx>

struct PersistenceTestClass
{
  PersistenceTestClass()
    : id(""), param1(1), param2(2), param3(false)
  {
  }
  std::string id;
  int param1;
  double param2;
  bool param3;

  PERSISTENCE_CREATE3(PersistenceTestClass, id, param1, param2, param3)
};

struct TestPropertyListReplacedObserver: public mitk::PropertyListReplacedObserver
{
  TestPropertyListReplacedObserver(): counter(0) {}
  virtual void BeforePropertyListReplaced( const std::string& id, mitk::PropertyList* propertyList )
  {
    if( id == m_Id )
      counter++;
  }

  virtual void AfterPropertyListReplaced( const std::string& id, mitk::PropertyList* propertyList )
  {
    if( id == m_Id )
      counter++;
  }

  int counter;
  std::string m_Id;
};

std::string testClassId = "testClass";
int param1 = 100;
double param2 = 201.56;
bool param3 = true;

void testParams( const PersistenceTestClass& testClass, const std::string& testClassName )
{
  MITK_INFO << "Testing parameters of " << testClassName;
  MITK_TEST_CONDITION( testClass.id == testClassId, "testClass.id (" << testClass.id << ") != testClassId (" << testClassId << ")" );
  MITK_TEST_CONDITION( testClass.param1 == param1, "testClass.param1 (" << testClass.param1 << ") != param1 (" << param1 << ")" );
  MITK_TEST_CONDITION( testClass.param2 == param2, "testClass.param2 (" << testClass.param2 << ") != param2 (" << param2 << ")" );
  MITK_TEST_CONDITION( testClass.param3 == param3, "testClass.param3 (" << testClass.param3 << ") != param3 (" << param3 << ")" );
}

int mitkPersistenceTest(int /*argc*/, char* /*argv*/[])
{
  MITK_TEST_BEGIN("PersistenceTest")
    // dummy load of SceneIO, otherwise PersistenceService won't be available
    //mitk::PersistenceService::LoadModule();

    MITK_INFO << "Testing availability of the PersistenceService.";
  PERSISTENCE_GET_SERVICE_MACRO
    MITK_TEST_CONDITION_REQUIRED(persistenceService, "IPersistenceService available")

    MITK_INFO << "Initialize testable parameter values.";

  std::string defaultPersistenceFile = persistenceService->GetDefaultPersistenceFile();
  PersistenceTestClass autoLoadTestClass;
  autoLoadTestClass.id = testClassId;
  if( itksys::SystemTools::FileExists(defaultPersistenceFile.c_str(), true) && persistenceService->GetAutoLoadAndSave() )
  {
    MITK_INFO << "Testing auto load/save of the PersistenceService.";
    itksys::SystemTools::RemoveFile(defaultPersistenceFile.c_str());
    autoLoadTestClass.FromPropertyList();

    testParams( autoLoadTestClass, "autoLoadTestClass" );
  }

  MITK_INFO << "Removing left-over test files.";
  std::string testTempFile = mitk::IOUtil::CreateTemporaryFile("XXXXXX.mitk");
  std::string testXmlTempFile = mitk::IOUtil::CreateTemporaryFile("PersistenceTestFileXXXXXX.xml");

  MITK_INFO << "Testing standard write to scene file/xml file.";
  PersistenceTestClass testClass;
  testClass.id = testClassId;
  testClass.param1 = param1;
  testClass.param2 = param2;
  testClass.param3 = param3;
  MITK_TEST_CONDITION_REQUIRED( testClass.Save(testTempFile), "Testing to save a scene file");
  MITK_TEST_CONDITION_REQUIRED( testClass.Save(testXmlTempFile), "testing to save an xml file");

  MITK_INFO << "Testing read from scene file.";
  MITK_TEST_CONDITION_REQUIRED( persistenceService->RemovePropertyList(testClassId), "persistenceService->RemovePropertyList(testClassId)");
  PersistenceTestClass testClass2;
  testClass2.id = testClassId;
  MITK_TEST_CONDITION_REQUIRED( testClass2.Load(testTempFile), "testClass2.Load(testTempFile.path())");

  testParams( testClass2, "testClass2" );

  MITK_INFO << "Testing read from xml file.";
  MITK_TEST_CONDITION_REQUIRED( persistenceService->RemovePropertyList(testClassId), "persistenceService->RemovePropertyList(testClassId)");
  PersistenceTestClass testClass3;
  testClass3.id = testClassId;
  MITK_TEST_CONDITION_REQUIRED( testClass3.Load(testXmlTempFile), "testClass3.Load(testXmlTempFile.path())");

  testParams( testClass3, "testClass3" );

  MITK_INFO << "Testing appendChanges functionality with scene load/write.";
  MITK_TEST_CONDITION_REQUIRED( persistenceService->RemovePropertyList(testClassId), "persistenceService->RemovePropertyList(testClassId)");
  MITK_TEST_CONDITION_REQUIRED( persistenceService->Save(testTempFile, true), "persistenceService->Save(testTempFile.path())");
  MITK_TEST_CONDITION_REQUIRED( persistenceService->Load(testTempFile), "persistenceService->Load(testTempFile.path())");

  PersistenceTestClass testClass4;
  testClass4.id = testClassId;
  testClass4.FromPropertyList();
  testParams( testClass4, "testClass4" );

  MITK_INFO << "Testing appendChanges functionality with xml load/write.";
  MITK_TEST_CONDITION_REQUIRED( persistenceService->RemovePropertyList(testClassId), "persistenceService->RemovePropertyList(testClassId)");
  MITK_TEST_CONDITION_REQUIRED( persistenceService->Save(testXmlTempFile, true), "persistenceService->Save(testXmlTempFile.path())");
  MITK_TEST_CONDITION_REQUIRED( persistenceService->Load(testXmlTempFile), "persistenceService->Load(testXmlTempFile.path())");

  PersistenceTestClass testClass5;
  testClass5.id = testClassId;
  testClass5.FromPropertyList();
  testParams( testClass5, "testClass5" );

  MITK_INFO << "Testing observer functionality.";
  TestPropertyListReplacedObserver testObserver;
  testObserver.m_Id = testClassId;
  persistenceService->AddPropertyListReplacedObserver( &testObserver );
  persistenceService->Load(testTempFile);
  MITK_TEST_CONDITION( testObserver.counter == 2, "testObserver.counter == 2, testObserver.counter is " << testObserver.counter );

  autoLoadTestClass.param1 = param1;
  autoLoadTestClass.param2 = param2;
  autoLoadTestClass.param3 = param3;
  autoLoadTestClass.ToPropertyList();
  MITK_TEST_END()
}<commit_msg>Converted Test into a cppunit test suite<commit_after>/*===================================================================

The Medical Imaging Interaction Toolkit (MITK)

Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics.
All rights reserved.

This software is distributed WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE.

See LICENSE.txt or http://www.mitk.org for details.

===================================================================*/
#include <mitkCommon.h>
#include <usModuleContext.h>
#include <usServiceReference.h>
#include <usGetModuleContext.h>
#include <mitkTestingMacros.h>
#include <mitkTestFixture.h>
#include <mitkIPersistenceService.h>
#include <mitkPersistenceService.h>
#include <mitkSceneIO.h>
#include <mitkIOUtil.h>
#include <itksys\SystemTools.hxx>

struct PersistenceTestClass
{
  PersistenceTestClass()
    : id(""), param1(1), param2(2), param3(false)
  {
  }
  std::string id;
  int param1;
  double param2;
  bool param3;

  PERSISTENCE_CREATE3(PersistenceTestClass, id, param1, param2, param3)
};

struct TestPropertyListReplacedObserver: public mitk::PropertyListReplacedObserver
{
  TestPropertyListReplacedObserver(): counter(0) {}
  virtual void BeforePropertyListReplaced( const std::string& id, mitk::PropertyList* propertyList )
  {
    if( id == m_Id )
      counter++;
  }

  virtual void AfterPropertyListReplaced( const std::string& id, mitk::PropertyList* propertyList )
  {
    if( id == m_Id )
      counter++;
  }

  int counter;
  std::string m_Id;
};

class mitkPersistenceTestSuite : public mitk::TestFixture
{
   CPPUNIT_TEST_SUITE(mitkPersistenceTestSuite);
   MITK_TEST(PersistenceTest);
   CPPUNIT_TEST_SUITE_END();

private:
  // private test members that are initialized by setUp()
  std::string testClassId;
  int param1;
  double param2;
  bool param3;

public:

  void setUp()
  {
    testClassId = "testClass";
    param1 = 100;
    param2 = 201.56;
    param3 = true;
  }

  void PersistenceTest()
  {
      // dummy load of SceneIO, otherwise PersistenceService won't be available
      //mitk::PersistenceService::LoadModule();

    PERSISTENCE_GET_SERVICE_MACRO
      CPPUNIT_ASSERT_MESSAGE("Testing availability of the PersistenceService.", persistenceService != NULL);

    // Initialize testable parameter values
    std::string defaultPersistenceFile = persistenceService->GetDefaultPersistenceFile();
    PersistenceTestClass autoLoadTestClass;
    autoLoadTestClass.id = testClassId;
    if( itksys::SystemTools::FileExists(defaultPersistenceFile.c_str(), true) && persistenceService->GetAutoLoadAndSave() )
    {
      /// Test auto load/save of the PersistenceService.
      itksys::SystemTools::RemoveFile(defaultPersistenceFile.c_str());
      autoLoadTestClass.FromPropertyList();
      testParams( autoLoadTestClass, "autoLoadTestClass" );
    }

    std::string testTempFile = mitk::IOUtil::CreateTemporaryFile("XXXXXX.mitk");
    std::string testXmlTempFile = mitk::IOUtil::CreateTemporaryFile("PersistenceTestFileXXXXXX.xml");

    MITK_INFO << "Testing standard write to scene file/xml file.";
    PersistenceTestClass testClass;
    testClass.id = testClassId;
    testClass.param1 = param1;
    testClass.param2 = param2;
    testClass.param3 = param3;
    CPPUNIT_ASSERT_MESSAGE( "Testing to save a scene file", testClass.Save(testTempFile));
    CPPUNIT_ASSERT_MESSAGE( "testing to save an xml file", testClass.Save(testXmlTempFile));

    CPPUNIT_ASSERT_MESSAGE( "Testing read from scene file: persistenceService->RemovePropertyList(testClassId)", persistenceService->RemovePropertyList(testClassId));
    PersistenceTestClass testClass2;
    testClass2.id = testClassId;
    CPPUNIT_ASSERT_MESSAGE( "Testing read from scene file: testClass2.Load(testTempFile.path())", testClass2.Load(testTempFile));

    testParams( testClass2, "testClass2" );

    CPPUNIT_ASSERT_MESSAGE( "Testing read from xml file: persistenceService->RemovePropertyList(testClassId)", persistenceService->RemovePropertyList(testClassId));
    PersistenceTestClass testClass3;
    testClass3.id = testClassId;
    CPPUNIT_ASSERT_MESSAGE( "Testing read from xml file: testClass3.Load(testXmlTempFile.path())", testClass3.Load(testXmlTempFile));

    testParams( testClass3, "testClass3" );

    CPPUNIT_ASSERT_MESSAGE( "Testing appendChanges functionality with scene load/write: persistenceService->RemovePropertyList(testClassId)", persistenceService->RemovePropertyList(testClassId));
    CPPUNIT_ASSERT_MESSAGE( "Testing appendChanges functionality with scene load/write: persistenceService->Save(testTempFile.path())",persistenceService->Save(testTempFile, true));
    CPPUNIT_ASSERT_MESSAGE( "Testing appendChanges functionality with scene load/write: persistenceService->Load(testTempFile.path())", persistenceService->Load(testTempFile));

    PersistenceTestClass testClass4;
    testClass4.id = testClassId;
    testClass4.FromPropertyList();
    testParams( testClass4, "testClass4" );

    CPPUNIT_ASSERT_MESSAGE( "Testing appendChanges functionality with xml load/write: persistenceService->RemovePropertyList(testClassId)", persistenceService->RemovePropertyList(testClassId));
    CPPUNIT_ASSERT_MESSAGE( "Testing appendChanges functionality with xml load/write: persistenceService->Save(testXmlTempFile.path())", persistenceService->Save(testXmlTempFile, true));
    CPPUNIT_ASSERT_MESSAGE( "Testing appendChanges functionality with xml load/write: persistenceService->Load(testXmlTempFile.path())", persistenceService->Load(testXmlTempFile));

    PersistenceTestClass testClass5;
    testClass5.id = testClassId;
    testClass5.FromPropertyList();
    testParams( testClass5, "testClass5" );

    // Test Observer Functionality
    TestPropertyListReplacedObserver testObserver;
    testObserver.m_Id = testClassId;
    persistenceService->AddPropertyListReplacedObserver( &testObserver );
    persistenceService->Load(testTempFile);
    CPPUNIT_ASSERT_MESSAGE( "Testing observer functionality: testObserver.counter == 2, testObserver.counter is " + testObserver.counter, testObserver.counter == 2 );

    autoLoadTestClass.param1 = param1;
    autoLoadTestClass.param2 = param2;
    autoLoadTestClass.param3 = param3;
    autoLoadTestClass.ToPropertyList();
  }

   /**
  * Helper Method that compares the returned class to its base values
  */
  void testParams( const PersistenceTestClass& testClass, const std::string& testClassName )
  {
    CPPUNIT_ASSERT_MESSAGE( "Parameter of TestClass not equal to reference value: testClass.id", testClass.id == testClassId );
    CPPUNIT_ASSERT_MESSAGE( "Parameter of TestClass not equal to reference value: testClass.param1" , testClass.param1 == param1);
    CPPUNIT_ASSERT_MESSAGE( "Parameter of TestClass not equal to reference value: testClass.param2" , testClass.param2 == param2);
    CPPUNIT_ASSERT_MESSAGE( "Parameter of TestClass not equal to reference value: testClass.param3" , testClass.param3 == param3);
  }
};
MITK_TEST_SUITE_REGISTRATION(mitkPersistence)<|endoftext|>