<commit_before>//
// Copyright (c) 2012 Kim Walisch, <kim.walisch@gmail.com>.
// All rights reserved.
//
// This file is part of primesieve.
// Homepage: http://primesieve.googlecode.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.
//   * Neither the name of the author nor the names of its
//     contributors may 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 "PrimeNumberFinder.h"
#include "PrimeSieve.h"
#include "SieveOfEratosthenes.h"
#include "config.h"
#include "bithacks.h"

#include <stdint.h>
#include <algorithm>
#include <cstdlib>
#include <iostream>
#include <sstream>

#if defined(_OPENMP)
  #include <omp.h>
#endif

namespace soe {

/// Bit patterns corresponding to prime k-tuplets
/// within bytes of the sieve array.
const uint32_t PrimeNumberFinder::kTupletBitmasks_[6][5] =
{
  { 0x06, 0x18, 0xc0, END },       // Twin primes
  { 0x07, 0x0e, 0x1c, 0x38, END }, // Prime triplets
  { 0x1e, END },                   // Prime quadruplets
  { 0x1f, 0x3e, END },             // Prime quintuplets
  { 0x3f, END },                   // Prime sextuplets
  { 0xfe, END }                    // Prime septuplets
};

PrimeNumberFinder::PrimeNumberFinder(PrimeSieve& ps) :
  SieveOfEratosthenes(
      std::max<uint64_t>(7, ps.getStart()),
      ps.getStop(),
      ps.getPreSieveLimit(),
      ps.getSieveSize()),
  ps_(ps),
  kTupletByteCounts_(NULL)
{
  static_assert(PrimeSieve::COUNTS_SIZE == 7, "PrimeSieve::COUNTS_SIZE == 7");
  if (ps_.testFlags(ps_.COUNT_KTUPLETS))
    initLookupTables();
}

PrimeNumberFinder::~PrimeNumberFinder() {
  if (kTupletByteCounts_ != NULL) {
    for (int i = 0; i < 6; i++)
      delete[] kTupletByteCounts_[i];
    delete[] kTupletByteCounts_;
  }
}

/**
 * Check if PrimeNumberFinder requires a PrimeNumberGenerator
 * object to generate its sieving primes.
 */
bool PrimeNumberFinder::needGenerator() const {
  return getPreSieveLimit() < getSquareRoot();
}

/**
 * Initialize the lookup tables needed to count prime k-tuplets
 * (twin primes, prime triplets, ...) per byte.
 */
void PrimeNumberFinder::initLookupTables() {
  kTupletByteCounts_ = new uint32_t*[6];
  for (uint32_t i = 0; i < 6; i++) {
    kTupletByteCounts_[i] = NULL;
    if (ps_.isFlag(ps_.COUNT_TWINS << i)) {
      kTupletByteCounts_[i] = new uint32_t[256];
      for (uint32_t j = 0; j < 256; j++) {
        uint32_t bitmaskCount = 0;
        for (const uint32_t* b = kTupletBitmasks_[i]; *b <= j; b++) {
          if ((j & *b) == *b)
            bitmaskCount++;
        }
        kTupletByteCounts_[i][j] = bitmaskCount;
      }
    }
  }
}

/**
 * Generate/count the primes and prime k-tuplets within the current
 * segment i.e. [segmentLow_+7, segmentHigh_].
 */
void PrimeNumberFinder::analyseSieve(const uint8_t* sieve, uint32_t sieveSize) {
  if (ps_.testFlags(ps_.COUNT_FLAGS))
    count(sieve, sieveSize);
  if (ps_.testFlags(ps_.GENERATE_FLAGS))
    generate(sieve, sieveSize);
  if (ps_.isFlag(ps_.CALCULATE_STATUS))
    ps_()->calcStatus(sieveSize * NUMBERS_PER_BYTE);
}

/**
 * Count the primes and prime k-tuplets within
 * the current segment.
 */
void PrimeNumberFinder::count(const uint8_t* sieve, uint32_t sieveSize) {
  // count prime numbers (1 bits within the sieve array)
  if (ps_.isFlag(ps_.COUNT_PRIMES)) {
    const uint64_t* sieve64 = reinterpret_cast<const uint64_t*>(sieve);
    uint32_t sieveSize64 = sieveSize / 8;
    uint32_t bytesLeft = sieveSize % 8;
    // see bithacks.h
    uint32_t primeCount = popcount_lauradoux(sieve64, sieveSize64);
    if (bytesLeft > 0)
      primeCount += popcount_kernighan(&sieve[sieveSize - bytesLeft], bytesLeft);
    // add up to total prime count
    ps_.counts_[0] += primeCount;
  }
  // count prime k-tuplets (i=0 twins, i=1 triplets, ...)
  // using lookup tables
  for (uint32_t i = 0; i < 6; i++) {
    if (ps_.isFlag(ps_.COUNT_TWINS << i)) {
      uint32_t kCount = 0;
      for (uint32_t j = 0; j < sieveSize; j++)
        kCount += kTupletByteCounts_[i][sieve[j]];
      ps_.counts_[i+1] += kCount;
    }
  }
}

/**
 * Generate the primes or prime k-tuplets (twin primes, prime
 * triplets, ...) within the current segment.
 */
void PrimeNumberFinder::generate(const uint8_t* sieve, uint32_t sieveSize) {
  if (ps_.testFlags(ps_.PRINT_KTUPLETS)) {
    const uint64_t segmentLow = getSegmentLow();
    // i = 0 twins, i = 1 triplets, ...
    uint32_t i = 0;
    for (; !ps_.isFlag(ps_.PRINT_TWINS << i); i++)
      ;
    // print prime k-tuplets to std::cout
    for (uint32_t j = 0; j < sieveSize; j++) {
      for (const uint32_t* bitmask = kTupletBitmasks_[i]; *bitmask <= sieve[j]; bitmask++) {
        if ((sieve[j] & *bitmask) == *bitmask) {
          std::ostringstream kTuplet;
          kTuplet << "(";
          uint32_t bits = *bitmask;
          uint64_t offset = segmentLow + j * NUMBERS_PER_BYTE;
          for (; bits & (bits - 1); bits &= bits - 1)
            kTuplet << offset + getFirstSetBitValue(bits) << ", ";
          kTuplet << offset + getFirstSetBitValue(bits) << ")\n";
          std::cout << kTuplet.str();
        }
      }
    }
  }
  else
#if defined(_OPENMP)
  #pragma omp critical (generate)
#endif
  {
    // GENERATE_PRIMES() is defined in SieveOfEratosthenes.h
         if (ps_.isFlag(ps_.CALLBACK32_PRIMES))     GENERATE_PRIMES(ps_.callback32_, uint32_t)
    else if (ps_.isFlag(ps_.CALLBACK32_OOP_PRIMES)) GENERATE_PRIMES(callback32_OOP,  uint32_t)
    else if (ps_.isFlag(ps_.CALLBACK64_PRIMES))     GENERATE_PRIMES(ps_.callback64_, uint64_t)
    else if (ps_.isFlag(ps_.CALLBACK64_OOP_PRIMES)) GENERATE_PRIMES(callback64_OOP,  uint64_t)
    else if (ps_.isFlag(ps_.PRINT_PRIMES))          GENERATE_PRIMES(print,           uint64_t)
  }
}

void PrimeNumberFinder::callback32_OOP(uint32_t prime) const {
  ps_.callback32_OOP_(prime, ps_.cbObj_);
}

void PrimeNumberFinder::callback64_OOP(uint64_t prime) const {
  ps_.callback64_OOP_(prime, ps_.cbObj_);
}

void PrimeNumberFinder::print(uint64_t prime) const {
  std::cout << prime << '\n';
}

} // namespace soe
<commit_msg>minor modification<commit_after>//
// Copyright (c) 2012 Kim Walisch, <kim.walisch@gmail.com>.
// All rights reserved.
//
// This file is part of primesieve.
// Homepage: http://primesieve.googlecode.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.
//   * Neither the name of the author nor the names of its
//     contributors may 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 "PrimeNumberFinder.h"
#include "PrimeSieve.h"
#include "SieveOfEratosthenes.h"
#include "config.h"
#include "bithacks.h"

#include <stdint.h>
#include <algorithm>
#include <cstdlib>
#include <iostream>
#include <sstream>

#if defined(_OPENMP)
  #include <omp.h>
#endif

namespace soe {

/// Bit patterns corresponding to prime k-tuplets
/// within bytes of the sieve array.
const uint32_t PrimeNumberFinder::kTupletBitmasks_[6][5] =
{
  { 0x06, 0x18, 0xc0, END },       // Twin primes
  { 0x07, 0x0e, 0x1c, 0x38, END }, // Prime triplets
  { 0x1e, END },                   // Prime quadruplets
  { 0x1f, 0x3e, END },             // Prime quintuplets
  { 0x3f, END },                   // Prime sextuplets
  { 0xfe, END }                    // Prime septuplets
};

PrimeNumberFinder::PrimeNumberFinder(PrimeSieve& ps) :
  SieveOfEratosthenes(
      std::max<uint64_t>(7, ps.getStart()),
      ps.getStop(),
      ps.getPreSieveLimit(),
      ps.getSieveSize()),
  ps_(ps),
  kTupletByteCounts_(NULL)
{
  static_assert(PrimeSieve::COUNTS_SIZE == 7, "PrimeSieve::COUNTS_SIZE == 7");
  if (ps_.testFlags(ps_.COUNT_KTUPLETS))
    initLookupTables();
}

PrimeNumberFinder::~PrimeNumberFinder() {
  if (kTupletByteCounts_ != NULL) {
    for (int i = 0; i < 6; i++)
      delete[] kTupletByteCounts_[i];
    delete[] kTupletByteCounts_;
  }
}

/**
 * Check if PrimeNumberFinder requires a PrimeNumberGenerator
 * object to generate its sieving primes.
 */
bool PrimeNumberFinder::needGenerator() const {
  return getPreSieveLimit() < getSquareRoot();
}

/**
 * Initialize the lookup tables needed to count prime k-tuplets
 * (twin primes, prime triplets, ...) per byte.
 */
void PrimeNumberFinder::initLookupTables() {
  kTupletByteCounts_ = new uint32_t*[6];
  for (uint32_t i = 0; i < 6; i++) {
    kTupletByteCounts_[i] = NULL;
    if (ps_.isFlag(ps_.COUNT_TWINS << i)) {
      kTupletByteCounts_[i] = new uint32_t[256];
      for (uint32_t j = 0; j < 256; j++) {
        uint32_t bitmaskCount = 0;
        for (const uint32_t* b = kTupletBitmasks_[i]; *b <= j; b++) {
          if ((j & *b) == *b)
            bitmaskCount++;
        }
        kTupletByteCounts_[i][j] = bitmaskCount;
      }
    }
  }
}

/**
 * Generate/count the primes and prime k-tuplets within the current
 * segment i.e. [segmentLow_+7, segmentHigh_].
 */
void PrimeNumberFinder::analyseSieve(const uint8_t* sieve, uint32_t sieveSize) {
  if (ps_.testFlags(ps_.COUNT_FLAGS))
    count(sieve, sieveSize);
  if (ps_.testFlags(ps_.GENERATE_FLAGS))
    generate(sieve, sieveSize);
  if (ps_.isFlag(ps_.CALCULATE_STATUS))
    ps_.calcStatus(sieveSize * NUMBERS_PER_BYTE);
}

/**
 * Count the primes and prime k-tuplets within
 * the current segment.
 */
void PrimeNumberFinder::count(const uint8_t* sieve, uint32_t sieveSize) {
  // count prime numbers (1 bits within the sieve array)
  if (ps_.isFlag(ps_.COUNT_PRIMES)) {
    const uint64_t* sieve64 = reinterpret_cast<const uint64_t*>(sieve);
    uint32_t sieveSize64 = sieveSize / 8;
    uint32_t bytesLeft = sieveSize % 8;
    // see bithacks.h
    uint32_t primeCount = popcount_lauradoux(sieve64, sieveSize64);
    if (bytesLeft > 0)
      primeCount += popcount_kernighan(&sieve[sieveSize - bytesLeft], bytesLeft);
    // add up to total prime count
    ps_.counts_[0] += primeCount;
  }
  // count prime k-tuplets (i=0 twins, i=1 triplets, ...)
  // using lookup tables
  for (uint32_t i = 0; i < 6; i++) {
    if (ps_.isFlag(ps_.COUNT_TWINS << i)) {
      uint32_t kCount = 0;
      for (uint32_t j = 0; j < sieveSize; j++)
        kCount += kTupletByteCounts_[i][sieve[j]];
      ps_.counts_[i+1] += kCount;
    }
  }
}

/**
 * Generate the primes or prime k-tuplets (twin primes, prime
 * triplets, ...) within the current segment.
 */
void PrimeNumberFinder::generate(const uint8_t* sieve, uint32_t sieveSize) {
  if (ps_.testFlags(ps_.PRINT_KTUPLETS)) {
    const uint64_t segmentLow = getSegmentLow();
    // i = 0 twins, i = 1 triplets, ...
    uint32_t i = 0;
    for (; !ps_.isFlag(ps_.PRINT_TWINS << i); i++)
      ;
    // print prime k-tuplets to std::cout
    for (uint32_t j = 0; j < sieveSize; j++) {
      for (const uint32_t* bitmask = kTupletBitmasks_[i]; *bitmask <= sieve[j]; bitmask++) {
        if ((sieve[j] & *bitmask) == *bitmask) {
          std::ostringstream kTuplet;
          kTuplet << "(";
          uint32_t bits = *bitmask;
          uint64_t offset = segmentLow + j * NUMBERS_PER_BYTE;
          for (; bits & (bits - 1); bits &= bits - 1)
            kTuplet << offset + getFirstSetBitValue(bits) << ", ";
          kTuplet << offset + getFirstSetBitValue(bits) << ")\n";
          std::cout << kTuplet.str();
        }
      }
    }
  }
  else
#if defined(_OPENMP)
  #pragma omp critical (generate)
#endif
  {
    // GENERATE_PRIMES() is defined in SieveOfEratosthenes.h
         if (ps_.isFlag(ps_.CALLBACK32_PRIMES))     GENERATE_PRIMES(ps_.callback32_, uint32_t)
    else if (ps_.isFlag(ps_.CALLBACK32_OOP_PRIMES)) GENERATE_PRIMES(callback32_OOP,  uint32_t)
    else if (ps_.isFlag(ps_.CALLBACK64_PRIMES))     GENERATE_PRIMES(ps_.callback64_, uint64_t)
    else if (ps_.isFlag(ps_.CALLBACK64_OOP_PRIMES)) GENERATE_PRIMES(callback64_OOP,  uint64_t)
    else if (ps_.isFlag(ps_.PRINT_PRIMES))          GENERATE_PRIMES(print,           uint64_t)
  }
}

void PrimeNumberFinder::callback32_OOP(uint32_t prime) const {
  ps_.callback32_OOP_(prime, ps_.cbObj_);
}

void PrimeNumberFinder::callback64_OOP(uint64_t prime) const {
  ps_.callback64_OOP_(prime, ps_.cbObj_);
}

void PrimeNumberFinder::print(uint64_t prime) const {
  std::cout << prime << '\n';
}

} // namespace soe
<|endoftext|>


<commit_before>#include "earth_shape.h"
#include "himan_common.h"

using namespace himan;

earth_shape::earth_shape() : itsA(MissingDouble()), itsB(MissingDouble())
{
}

earth_shape::earth_shape(double r) : itsA(r), itsB(r)
{
}

earth_shape::earth_shape(double theA, double theB) : itsA(theA), itsB(theB)
{
}

bool earth_shape::operator==(const earth_shape& other) const
{
	return (itsA == other.itsA && itsB == other.itsB);
}

bool earth_shape::operator!=(const earth_shape& other) const
{
        return !(*this == other);
}

double earth_shape::A() const
{
	return itsA;
}

void earth_shape::A(double theA)
{
	itsA = theA;
}

double earth_shape::B() const
{
	return itsB;
}

void earth_shape::B(double theB)
{
	itsB = theB;
}

double earth_shape::F() const
{
	return (itsA - itsB) / itsA;
}

std::ostream& himan::earth_shape::Write(std::ostream& file) const
{
        file << "<" << ClassName() << ">" << std::endl;
        file << "__itsA__ " << std::fixed << itsA << std::endl;
        file << "__itsB__ " << std::fixed << itsB << std::endl;

        return file;
}

<commit_msg>Modify operator== so that comparison between default constructed objects return true<commit_after>#include "earth_shape.h"
#include "himan_common.h"

using namespace himan;

earth_shape::earth_shape() : itsA(MissingDouble()), itsB(MissingDouble())
{
}

earth_shape::earth_shape(double r) : itsA(r), itsB(r)
{
}

earth_shape::earth_shape(double theA, double theB) : itsA(theA), itsB(theB)
{
}

bool earth_shape::operator==(const earth_shape& other) const
{
	if (itsA == other.itsA && itsB == other.itsB)
	{
		return true;
	}

	// Check for missing values so that we can compare with default constructor
	return ((IsMissing(itsA) && IsMissing(other.itsA)) && (IsMissing(itsB) && IsMissing(other.itsB)));
}

bool earth_shape::operator!=(const earth_shape& other) const
{
	return !(*this == other);
}

double earth_shape::A() const
{
	return itsA;
}

void earth_shape::A(double theA)
{
	itsA = theA;
}

double earth_shape::B() const
{
	return itsB;
}

void earth_shape::B(double theB)
{
	itsB = theB;
}

double earth_shape::F() const
{
	return (itsA - itsB) / itsA;
}

std::ostream& himan::earth_shape::Write(std::ostream& file) const
{
	file << "<" << ClassName() << ">" << std::endl;
	file << "__itsA__ " << std::fixed << itsA << std::endl;
	file << "__itsB__ " << std::fixed << itsB << std::endl;

	return file;
}
<|endoftext|>


<commit_before>// @(#)root/build:$Name:  $:$Id: mainroot.cxx,v 1.2 2006/03/21 00:21:00 rdm Exp $
// Author: Axel Naumann   21/03/06

/*************************************************************************
 * Copyright (C) 1995-2006, Rene Brun and Fons Rademakers.               *
 * All rights reserved.                                                  *
 *                                                                       *
 * For the licensing terms see $ROOTSYS/LICENSE.                         *
 * For the list of contributors see $ROOTSYS/README/CREDITS.             *
 *************************************************************************/

extern "C" {
#if defined(__sun) && defined(__SUNPRO_CC)
#include <signal.h>
#endif
#include "def.h"
}

#include <string>

extern "C" int main_orig(int argc, char **argv);
extern "C" int unlink (const char *FILENAME);

int rootBuild = 0;

int isDict = 0;
int newFile = 0;
std::string currentDependencies;
std::string currentFileBase;

extern "C"
void ROOT_newFile()
{
   newFile = 1;
}

void ROOT_flush()
{
   if (!currentFileBase.empty()) {
      fwrite(")\n", 2, 1, stdout); // closing "$(wildcard"
      bool haveOldNonDict = !isDict;
      if (haveOldNonDict) {
         currentFileBase += "o";
         fwrite(currentFileBase.c_str(), currentFileBase.length(), 1, stdout);
         currentDependencies += '\n';
         fwrite(currentDependencies.c_str(), currentDependencies.length(), 1, stdout);
      }
   }
   currentFileBase.clear();
   currentDependencies.clear();
}

extern "C"
void ROOT_adddep(char* buf, size_t len)
{
   char* posColon = 0;
   if (newFile)
      posColon = strstr(buf, ".o: ");

   if (!posColon) {
      fwrite(buf, len, 1, stdout);
      currentDependencies += buf;
      return;
   }

/* isDict:
   sed -e 's@^\(.*\)\.o[ :]*\(.*\)\@
             \1.d: $\(wildcard \2\)\@\1.cxx: $\(wildcard \2\)@'
       -e 's@^#.*$@@'
       -e '/^$/d'
   | tr '@' '\n'
else
   sed -e 's@^\(.*\)\.o[ :]*\(.*\)@
             \1.d: $\(wildcard \2\)\@\1.o: \2@'
       -e 's@^#.*$@@'
       -e '/^$/d' $1.tmp
   | tr '@' '\n'
*/
   // flush out the old dependencies
   ROOT_flush();

   newFile = 0;

   buf[0] = ' ';
   if (isDict) {
      posColon[1]=0;
      strcat(posColon, "cxx");
      fwrite(buf, (posColon - buf)+4, 1, stdout); // .cxx
   }

   posColon[1]='d';
   fwrite(buf, (posColon - buf)+2, 1, stdout); // .d

   if (!isDict) {
      posColon[1] = 0;
      currentFileBase = buf + 1;
      currentDependencies = posColon + 2;
   }
   fwrite(": $(wildcard ", 13, 1, stdout);
   fwrite(posColon + 4, len - (posColon + 4 - buf), 1, stdout);
}

int main(int argc, char **argv)
{
   if (argc<3 || strcmp(argv[1], "-R"))
      return main_orig(argc, argv);

   rootBuild = 1;
   int skip = 2;
   const char* outname = argv[2]+skip;
   while (outname[0] == ' ') outname = argv[2] + (++skip);
   if (outname)
      isDict = (strstr(outname, "/G__") != 0 && strstr(outname, ".cxx"));

   argv[1] = argv[0]; // keep program name
   int ret = main_orig(argc-1, &argv[1]);
   if (ret) {
      // delete output file
      unlink(outname);
   } else
      ROOT_flush();
   return ret;
}
<commit_msg>Fix a compilation problem on FreeBSD 6.1.<commit_after>// @(#)root/build:$Name:  $:$Id: mainroot.cxx,v 1.3 2006/03/23 14:00:18 rdm Exp $
// Author: Axel Naumann   21/03/06

/*************************************************************************
 * Copyright (C) 1995-2006, Rene Brun and Fons Rademakers.               *
 * All rights reserved.                                                  *
 *                                                                       *
 * For the licensing terms see $ROOTSYS/LICENSE.                         *
 * For the list of contributors see $ROOTSYS/README/CREDITS.             *
 *************************************************************************/

#include <string>

extern "C" {
#if defined(__sun) && defined(__SUNPRO_CC)
#include <signal.h>
#endif
#include "def.h"
}

extern "C" int main_orig(int argc, char **argv);
extern "C" int unlink (const char *FILENAME);

int rootBuild = 0;

int isDict = 0;
int newFile = 0;
std::string currentDependencies;
std::string currentFileBase;

extern "C"
void ROOT_newFile()
{
   newFile = 1;
}

void ROOT_flush()
{
   if (!currentFileBase.empty()) {
      fwrite(")\n", 2, 1, stdout); // closing "$(wildcard"
      bool haveOldNonDict = !isDict;
      if (haveOldNonDict) {
         currentFileBase += "o";
         fwrite(currentFileBase.c_str(), currentFileBase.length(), 1, stdout);
         currentDependencies += '\n';
         fwrite(currentDependencies.c_str(), currentDependencies.length(), 1, stdout);
      }
   }
   currentFileBase.clear();
   currentDependencies.clear();
}

extern "C"
void ROOT_adddep(char* buf, size_t len)
{
   char* posColon = 0;
   if (newFile)
      posColon = strstr(buf, ".o: ");

   if (!posColon) {
      fwrite(buf, len, 1, stdout);
      currentDependencies += buf;
      return;
   }

/* isDict:
   sed -e 's@^\(.*\)\.o[ :]*\(.*\)\@
             \1.d: $\(wildcard \2\)\@\1.cxx: $\(wildcard \2\)@'
       -e 's@^#.*$@@'
       -e '/^$/d'
   | tr '@' '\n'
else
   sed -e 's@^\(.*\)\.o[ :]*\(.*\)@
             \1.d: $\(wildcard \2\)\@\1.o: \2@'
       -e 's@^#.*$@@'
       -e '/^$/d' $1.tmp
   | tr '@' '\n'
*/
   // flush out the old dependencies
   ROOT_flush();

   newFile = 0;

   buf[0] = ' ';
   if (isDict) {
      posColon[1]=0;
      strcat(posColon, "cxx");
      fwrite(buf, (posColon - buf)+4, 1, stdout); // .cxx
   }

   posColon[1]='d';
   fwrite(buf, (posColon - buf)+2, 1, stdout); // .d

   if (!isDict) {
      posColon[1] = 0;
      currentFileBase = buf + 1;
      currentDependencies = posColon + 2;
   }
   fwrite(": $(wildcard ", 13, 1, stdout);
   fwrite(posColon + 4, len - (posColon + 4 - buf), 1, stdout);
}

int main(int argc, char **argv)
{
   if (argc<3 || strcmp(argv[1], "-R"))
      return main_orig(argc, argv);

   rootBuild = 1;
   int skip = 2;
   const char* outname = argv[2]+skip;
   while (outname[0] == ' ') outname = argv[2] + (++skip);
   if (outname)
      isDict = (strstr(outname, "/G__") != 0 && strstr(outname, ".cxx"));

   argv[1] = argv[0]; // keep program name
   int ret = main_orig(argc-1, &argv[1]);
   if (ret) {
      // delete output file
      unlink(outname);
   } else
      ROOT_flush();
   return ret;
}
<|endoftext|>


<commit_before>#include <cstdio>
#include <cstring>
#include <mosquittopp.h>

void print_error(const char *topic, char **topics, int topic_count)
{
	int i;
	printf("TOPIC: %s\n", topic);
	printf("TOKENS: ", topic);
	for(i=0; i<topic_count; i++){
		printf("%s", topics[i]);
		if(i+1<topic_count){
			printf("/");
		}
	}
	printf("\n");
}

int main(int argc, char *argv[])
{
	char **topics;
	int topic_count;

	if(mosqpp::sub_topic_tokenise("topic", &topics, &topic_count)){
		printf("Out of memory.\n");
		return 1;
	}
	if(topic_count != 1 || strcmp(topics[0], "topic")){
		print_error("topic", topics, topic_count);
		return 1;
	}

	if(mosqpp::sub_topic_tokenise("a/deep/topic/hierarchy", &topics, &topic_count)){
		printf("Out of memory.\n");
		return 1;
	}
	if(topic_count != 4
			|| strcmp(topics[0], "a")
			|| strcmp(topics[1], "deep")
			|| strcmp(topics[2], "topic")
			|| strcmp(topics[3], "hierarchy")){
		print_error("a/deep/topic/hierarchy", topics, topic_count);
		return 1;
	}

	if(mosqpp::sub_topic_tokenise("/a/deep/topic/hierarchy", &topics, &topic_count)){
		printf("Out of memory.\n");
		return 1;
	}
	if(topic_count != 5
			|| topics[0]
			|| strcmp(topics[1], "a")
			|| strcmp(topics[2], "deep")
			|| strcmp(topics[3], "topic")
			|| strcmp(topics[4], "hierarchy")){
		print_error("/a/deep/topic/hierarchy", topics, topic_count);
		return 1;
	}

	if(mosqpp::sub_topic_tokenise("a/b/c", &topics, &topic_count)){
		printf("Out of memory.\n");
		return 1;
	}
	if(topic_count != 3
			|| strcmp(topics[0], "a")
			|| strcmp(topics[1], "b")
			|| strcmp(topics[2], "c")){
		print_error("a/b/c", topics, topic_count);
		return 1;
	}

	if(mosqpp::sub_topic_tokenise("/a/b/c", &topics, &topic_count)){
		printf("Out of memory.\n");
		return 1;
	}
	if(topic_count != 4
			|| topics[0]
			|| strcmp(topics[1], "a")
			|| strcmp(topics[2], "b")
			|| strcmp(topics[3], "c")){
		print_error("/a/b/c", topics, topic_count);
		return 1;
	}
	return 0;
}

<commit_msg>Test compilation fix.<commit_after>#include <cstdio>
#include <cstring>
#include <mosquittopp.h>

void print_error(const char *topic, char **topics, int topic_count)
{
	int i;
	printf("TOPIC: %s\n", topic);
	printf("TOKENS: ");
	for(i=0; i<topic_count; i++){
		printf("%s", topics[i]);
		if(i+1<topic_count){
			printf("/");
		}
	}
	printf("\n");
}

int main(int argc, char *argv[])
{
	char **topics;
	int topic_count;

	if(mosqpp::sub_topic_tokenise("topic", &topics, &topic_count)){
		printf("Out of memory.\n");
		return 1;
	}
	if(topic_count != 1 || strcmp(topics[0], "topic")){
		print_error("topic", topics, topic_count);
		return 1;
	}

	if(mosqpp::sub_topic_tokenise("a/deep/topic/hierarchy", &topics, &topic_count)){
		printf("Out of memory.\n");
		return 1;
	}
	if(topic_count != 4
			|| strcmp(topics[0], "a")
			|| strcmp(topics[1], "deep")
			|| strcmp(topics[2], "topic")
			|| strcmp(topics[3], "hierarchy")){
		print_error("a/deep/topic/hierarchy", topics, topic_count);
		return 1;
	}

	if(mosqpp::sub_topic_tokenise("/a/deep/topic/hierarchy", &topics, &topic_count)){
		printf("Out of memory.\n");
		return 1;
	}
	if(topic_count != 5
			|| topics[0]
			|| strcmp(topics[1], "a")
			|| strcmp(topics[2], "deep")
			|| strcmp(topics[3], "topic")
			|| strcmp(topics[4], "hierarchy")){
		print_error("/a/deep/topic/hierarchy", topics, topic_count);
		return 1;
	}

	if(mosqpp::sub_topic_tokenise("a/b/c", &topics, &topic_count)){
		printf("Out of memory.\n");
		return 1;
	}
	if(topic_count != 3
			|| strcmp(topics[0], "a")
			|| strcmp(topics[1], "b")
			|| strcmp(topics[2], "c")){
		print_error("a/b/c", topics, topic_count);
		return 1;
	}

	if(mosqpp::sub_topic_tokenise("/a/b/c", &topics, &topic_count)){
		printf("Out of memory.\n");
		return 1;
	}
	if(topic_count != 4
			|| topics[0]
			|| strcmp(topics[1], "a")
			|| strcmp(topics[2], "b")
			|| strcmp(topics[3], "c")){
		print_error("/a/b/c", topics, topic_count);
		return 1;
	}
	return 0;
}

<|endoftext|>


<commit_before>// Author: Enrico Guiraud, Danilo Piparo CERN  12/2016

/*************************************************************************
 * Copyright (C) 1995-2016, Rene Brun and Fons Rademakers.               *
 * All rights reserved.                                                  *
 *                                                                       *
 * For the licensing terms see $ROOTSYS/LICENSE.                         *
 * For the list of contributors see $ROOTSYS/README/CREDITS.             *
 *************************************************************************/

/**
  \defgroup dataframe Data Frame
The ROOT Data Frame allows to analyse data stored in TTrees with a high level interface.
*/

#ifndef ROOT_TDATAFRAME
#define ROOT_TDATAFRAME

#include "ROOT/TActionResultProxy.hxx"
#include "ROOT/TDataFrameInterface.hxx"
#include "ROOT/TDFNodes.hxx"
#include "ROOT/TDFUtils.hxx"
#include "TChain.h"

#include <memory>
#include <iosfwd> // std::ostringstream
#include <stdexcept>
#include <string>
class TDirectory;
class TTree;

#ifndef __ROOTCLING__
R__LOAD_LIBRARY(libTreePlayer)
#endif

namespace cling {
// TDataFrame pretty-printing
std::string printValue(ROOT::Experimental::TDataFrame *tdf);
}

namespace ROOT {
namespace Experimental {

class TDataFrame : public TDataFrameInterface<ROOT::Detail::TDataFrameImpl> {
private:
   std::shared_ptr<TTree> fTree;
   void InitTree(TTree &tree, bool ownsTree);

public:
   TDataFrame(const std::string &treeName, const std::string &filenameglob, const BranchNames_t &defaultBranches = {});
   ////////////////////////////////////////////////////////////////////////////
   /// \brief Build the dataframe
   /// \tparam FILENAMESCOLL The type of the file collection: only requirement: must have begin and end.
   /// \param[in] treeName Name of the tree contained in the directory
   /// \param[in] filenamescoll Collection of file names, for example a list of strings.
   /// \param[in] defaultBranches Collection of default branches.
   ///
   /// The default branches are looked at in case no branch is specified in the
   /// booking of actions or transformations.
   /// See ROOT::Experimental::TDataFrameInterface for the documentation of the
   /// methods available.
   template <
      typename FILENAMESCOLL,
      typename std::enable_if<ROOT::Internal::TDFTraitsUtils::TIsContainer<FILENAMESCOLL>::fgValue, int>::type = 0>
   TDataFrame(const std::string &treeName, const FILENAMESCOLL &filenamescoll,
              const BranchNames_t &defaultBranches = {});
   TDataFrame(const std::string &treeName, ::TDirectory *dirPtr, const BranchNames_t &defaultBranches = {});
   TDataFrame(TTree &tree, const BranchNames_t &defaultBranches = {});
};

template <typename FILENAMESCOLL,
          typename std::enable_if<ROOT::Internal::TDFTraitsUtils::TIsContainer<FILENAMESCOLL>::fgValue, int>::type>
TDataFrame::TDataFrame(const std::string &treeName, const FILENAMESCOLL &filenamescoll,
                       const BranchNames_t &defaultBranches)
   : TDataFrameInterface<ROOT::Detail::TDataFrameImpl>(
        std::make_shared<ROOT::Detail::TDataFrameImpl>(nullptr, defaultBranches))
{
   auto chain = new TChain(treeName.c_str());
   for (auto &fileName : filenamescoll) chain->Add(ROOT::Internal::ToConstCharPtr(fileName));
   fTree = std::make_shared<TTree>(static_cast<TTree *>(chain));
   fProxiedPtr->SetTree(chain);
}

} // end NS Experimental
} // end NS ROOT

////////////////////////////////////////////////////////////////////////////////
/// Print a TDataFrame at the prompt:
namespace cling {
inline std::string printValue(ROOT::Experimental::TDataFrame *tdf)
{
   auto df          = tdf->GetDataFrameChecked();
   auto treeName    = df->GetTreeName();
   auto defBranches = df->GetDefaultBranches();
   auto tmpBranches = df->GetTmpBranches();

   std::ostringstream ret;
   ret << "A data frame built on top of the " << treeName << " dataset.";
   if (!defBranches.empty()) {
      if (defBranches.size() == 1)
         ret << "\nDefault branch: " << defBranches[0];
      else {
         ret << "\nDefault branches:\n";
         for (auto &&branch : defBranches) {
            ret << " - " << branch << "\n";
         }
      }
   }

   return ret.str();
}
} // namespace cling

#endif // ROOT_TDATAFRAME
<commit_msg>[TDF] Remove protection inhibiting load of library during dictionary cration<commit_after>// Author: Enrico Guiraud, Danilo Piparo CERN  12/2016

/*************************************************************************
 * Copyright (C) 1995-2016, Rene Brun and Fons Rademakers.               *
 * All rights reserved.                                                  *
 *                                                                       *
 * For the licensing terms see $ROOTSYS/LICENSE.                         *
 * For the list of contributors see $ROOTSYS/README/CREDITS.             *
 *************************************************************************/

/**
  \defgroup dataframe Data Frame
The ROOT Data Frame allows to analyse data stored in TTrees with a high level interface.
*/

#ifndef ROOT_TDATAFRAME
#define ROOT_TDATAFRAME

#include "ROOT/TActionResultProxy.hxx"
#include "ROOT/TDataFrameInterface.hxx"
#include "ROOT/TDFNodes.hxx"
#include "ROOT/TDFUtils.hxx"
#include "TChain.h"

#include <memory>
#include <iosfwd> // std::ostringstream
#include <stdexcept>
#include <string>
class TDirectory;
class TTree;

R__LOAD_LIBRARY(libTreePlayer)

namespace cling {
// TDataFrame pretty-printing
std::string printValue(ROOT::Experimental::TDataFrame *tdf);
}

namespace ROOT {
namespace Experimental {

class TDataFrame : public TDataFrameInterface<ROOT::Detail::TDataFrameImpl> {
private:
   std::shared_ptr<TTree> fTree;
   void InitTree(TTree &tree, bool ownsTree);

public:
   TDataFrame(const std::string &treeName, const std::string &filenameglob, const BranchNames_t &defaultBranches = {});
   ////////////////////////////////////////////////////////////////////////////
   /// \brief Build the dataframe
   /// \tparam FILENAMESCOLL The type of the file collection: only requirement: must have begin and end.
   /// \param[in] treeName Name of the tree contained in the directory
   /// \param[in] filenamescoll Collection of file names, for example a list of strings.
   /// \param[in] defaultBranches Collection of default branches.
   ///
   /// The default branches are looked at in case no branch is specified in the
   /// booking of actions or transformations.
   /// See ROOT::Experimental::TDataFrameInterface for the documentation of the
   /// methods available.
   template <
      typename FILENAMESCOLL,
      typename std::enable_if<ROOT::Internal::TDFTraitsUtils::TIsContainer<FILENAMESCOLL>::fgValue, int>::type = 0>
   TDataFrame(const std::string &treeName, const FILENAMESCOLL &filenamescoll,
              const BranchNames_t &defaultBranches = {});
   TDataFrame(const std::string &treeName, ::TDirectory *dirPtr, const BranchNames_t &defaultBranches = {});
   TDataFrame(TTree &tree, const BranchNames_t &defaultBranches = {});
};

template <typename FILENAMESCOLL,
          typename std::enable_if<ROOT::Internal::TDFTraitsUtils::TIsContainer<FILENAMESCOLL>::fgValue, int>::type>
TDataFrame::TDataFrame(const std::string &treeName, const FILENAMESCOLL &filenamescoll,
                       const BranchNames_t &defaultBranches)
   : TDataFrameInterface<ROOT::Detail::TDataFrameImpl>(
        std::make_shared<ROOT::Detail::TDataFrameImpl>(nullptr, defaultBranches))
{
   auto chain = new TChain(treeName.c_str());
   for (auto &fileName : filenamescoll) chain->Add(ROOT::Internal::ToConstCharPtr(fileName));
   fTree = std::make_shared<TTree>(static_cast<TTree *>(chain));
   fProxiedPtr->SetTree(chain);
}

} // end NS Experimental
} // end NS ROOT

////////////////////////////////////////////////////////////////////////////////
/// Print a TDataFrame at the prompt:
namespace cling {
inline std::string printValue(ROOT::Experimental::TDataFrame *tdf)
{
   auto df          = tdf->GetDataFrameChecked();
   auto treeName    = df->GetTreeName();
   auto defBranches = df->GetDefaultBranches();
   auto tmpBranches = df->GetTmpBranches();

   std::ostringstream ret;
   ret << "A data frame built on top of the " << treeName << " dataset.";
   if (!defBranches.empty()) {
      if (defBranches.size() == 1)
         ret << "\nDefault branch: " << defBranches[0];
      else {
         ret << "\nDefault branches:\n";
         for (auto &&branch : defBranches) {
            ret << " - " << branch << "\n";
         }
      }
   }

   return ret.str();
}
} // namespace cling

#endif // ROOT_TDATAFRAME
<|endoftext|>


<commit_before>/** \file call_main.cpp
 *
 * Defines the "vg call" subcommand, which calls variation from an augmented graph
 */

#include <omp.h>
#include <unistd.h>
#include <getopt.h>

#include <list>
#include <fstream>

#include "subcommand.hpp"
#include "../path.hpp"
#include "../graph_caller.hpp"
#include "../xg.hpp"
#include <vg/io/stream.hpp>
#include <vg/io/vpkg.hpp>

using namespace std;
using namespace vg;
using namespace vg::subcommand;

void help_call2(char** argv) {
  cerr << "usage: " << argv[0] << " call [options] <graph> > output.vcf" << endl
       << "Call variants or genotype known variants" << endl
       << endl
       << "support calling options:" << endl
       << "    -k, --pack FILE         Supports created from vg pack (input graph must be xg)" << endl
       << "general options:" << endl
       << "    -v, --vcf FILE          VCF file to genotype (must have been used to construct input graph with -a)" << endl
       << "    -f, --ref-fasta FILE    Reference fasta (required if VCF contains symbolic deletions or inversions)" << endl
       << "    -i, --ins-fasta FILE    Insertions fasta (required if VCF contains symbolic insertions)" << endl
       << "    -s, --sample NAME       Sample name [default=SAMPLE]" << endl
       << "    -r, --snarls FILE       Snarls (from vg snarls) to avoid recomputing." << endl
       << "    -p, --ref-path NAME     Reference path to call on (multipile allowed.  defaults to all paths)" << endl
       << "    -t, --threads N         number of threads to use" << endl;
}

int main_call2(int argc, char** argv) {

    string pack_filename;
    string vcf_filename;
    string sample_name = "SAMPLE";
    string snarl_filename;
    string ref_fasta_filename;
    string ins_fasta_filename;
    vector<string> ref_paths;

    int c;
    optind = 2; // force optind past command positional argument
    while (true) {

        static const struct option long_options[] = {
            {"pack", required_argument, 0, 'k'},
            {"vcf", required_argument, 0, 'v'},
            {"ref-fasta", required_argument, 0, 'f'},
            {"ins-fasta", required_argument, 0, 'i'},
            {"sample", required_argument, 0, 's'},
            {"snarls", required_argument, 0, 'r'},
            {"ref-path", required_argument, 0, 'p'},
            {"threads", required_argument, 0, 't'},
            {"help", no_argument, 0, 'h'},
            {0, 0, 0, 0}
        };

        int option_index = 0;

        c = getopt_long (argc, argv, "k:v:f:i:s:r:p:t:h",
                         long_options, &option_index);

        // Detect the end of the options.
        if (c == -1)
            break;

        switch (c)
        {
        case 'k':
            pack_filename = optarg;
            break;
        case 'v':
            vcf_filename = optarg;
            break;
        case 'f':
            ref_fasta_filename = optarg;
            break;
        case 'i':
            ins_fasta_filename = optarg;
            break;
        case 's':
            sample_name = optarg;
            break;
        case 'r':
            snarl_filename = optarg;
            break;
        case 'p':
            ref_paths.push_back(optarg);
            break;
        case 't':
        {
            int num_threads = parse<int>(optarg);
            if (num_threads <= 0) {
                cerr << "error:[vg call] Thread count (-t) set to " << num_threads << ", must set to a positive integer." << endl;
                exit(1);
            }
            omp_set_num_threads(num_threads);
            break;
        }
        case 'h':
        case '?':
            /* getopt_long already printed an error message. */
            help_call2(argv);
            exit(1);
            break;
        default:
            abort ();
        }
    }

    if (argc <= 2) {
        help_call2(argv);
        return 1;
    }

    // Read the graph
    unique_ptr<PathHandleGraph> graph;
    get_input_file(optind, argc, argv, [&](istream& in) {
            graph = vg::io::VPKG::load_one<PathHandleGraph>(in);
        });

    // Check our paths
    for (const string& ref_path : ref_paths) {
        if (!graph->has_path(ref_path)) {
            cerr << "error [vg call]: Reference path \"" << ref_path << "\" not found in graph" << endl;
            return 1;
        }
    }
    // No paths specified: use them all
    if (ref_paths.empty()) {
        graph->for_each_path_handle([&](path_handle_t path_handle) {
                const string& name = graph->get_path_name(path_handle);
                if (!Paths::is_alt(name)) {
                    ref_paths.push_back(name);
                }
            });
    }

    // Load or compute the snarls
    unique_ptr<SnarlManager> snarl_manager;
    if (!snarl_filename.empty()) {
        ifstream snarl_file(snarl_filename.c_str());
        if (!snarl_file) {
            cerr << "Error [vg call]: Unable to load snarls file: " << snarl_filename << endl;
            return 1;
        }
        snarl_manager = vg::io::VPKG::load_one<SnarlManager>(snarl_file);
    } else {
        CactusSnarlFinder finder(*graph);
        snarl_manager = unique_ptr<SnarlManager>(new SnarlManager(std::move(finder.find_snarls())));
    }

    unique_ptr<GraphCaller> graph_caller;
    unique_ptr<SnarlCaller> snarl_caller;

    // Make a Packed Support Caller
    unique_ptr<Packer> packer;
    if (!pack_filename.empty()) {
        if (dynamic_cast<xg::XG*>(graph.get()) == nullptr) {
            cerr << "error [vg call]: Packed support option requires input graph in XG format" << endl;
            return 1;
        }
        // Load our packed supports (they must have come from vg pack on graph)
        packer = unique_ptr<Packer>(new Packer(dynamic_cast<xg::XG*>(graph.get())));
        packer->load_from_file(pack_filename);
        PackedSupportSnarlCaller* packed_caller = new PackedSupportSnarlCaller(*packer, *snarl_manager);
        snarl_caller = unique_ptr<SnarlCaller>(packed_caller);
    }

    if (!snarl_caller) {
        cerr << "error [vg call]: pack file (-p) is required" << endl;
        return 1;
    }

    vcflib::VariantCallFile variant_file;
    unique_ptr<FastaReference> ref_fasta;
    unique_ptr<FastaReference> ins_fasta;
    if (!vcf_filename.empty()) {
        // Genotype the VCF
        variant_file.parseSamples = false;
        variant_file.open(vcf_filename);
        if (!variant_file.is_open()) {
            cerr << "error: [vg call] could not open " << vcf_filename << endl;
            return 1;
        }

        // load up the fasta
        if (!ref_fasta_filename.empty()) {
            ref_fasta = unique_ptr<FastaReference>(new FastaReference);
            ref_fasta->open(ref_fasta_filename);
        }
        if (!ins_fasta_filename.empty()) {
            ins_fasta = unique_ptr<FastaReference>(new FastaReference);
            ins_fasta->open(ins_fasta_filename);
        }

        VCFGenotyper* vcf_genotyper = new VCFGenotyper(*graph, *snarl_caller,
                                                       *snarl_manager, variant_file,
                                                       sample_name, ref_paths,
                                                       ref_fasta.get(),
                                                       ins_fasta.get());
        graph_caller = unique_ptr<GraphCaller>(vcf_genotyper);
    } else {
        // de-novo caller (port of the old vg call code, which requires a support based caller)
        LegacyCaller* legacy_caller = new LegacyCaller(*dynamic_cast<PathPositionHandleGraph*>(graph.get()),
                                                       *dynamic_cast<SupportBasedSnarlCaller*>(snarl_caller.get()),
                                                        *snarl_manager,
                                                        sample_name, ref_paths);
        graph_caller = unique_ptr<GraphCaller>(legacy_caller);
    }

    // Call the graph
    cout << graph_caller->vcf_header(*graph, ref_paths) << flush;
    graph_caller->call_top_level_snarls();

    return 0;
}

// Register subcommand
static Subcommand vg_call2("call2", "call2 variants", PIPELINE, 5, main_call2);

<commit_msg>remove mistakenly committed file<commit_after><|endoftext|>


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

#ifndef _PREVIEWADAPTER_HXX_
#define _PREVIEWADAPTER_HXX_

#ifndef _SAL_TYPES_H_
#include <sal/types.h>
#endif

#ifndef _COM_SUN_STAR_UNO_SEQUENCE_HXX_
#include <com/sun/star/uno/Sequence.hxx>
#endif

#ifndef _COM_SUN_STAR_UNO_RUNTIMEEXCEPTION_HPP_
#include <com/sun/star/uno/RuntimeException.hpp>
#endif

#ifndef _COM_SUN_STAR_LANG_ILLEGALARGUMENTEXCEPTION_HPP_
#include <com/sun/star/lang/IllegalArgumentException.hpp>
#endif

#ifndef _COM_SUN_STAR_UNO_ANY_HXX_
#include <com/sun/star/uno/Any.hxx>
#endif

#include <windows.h>
#include <memory>

// forward declaration
class CPreviewAdapterImpl;

//---------------------------------------------
// A kind of a facade for the preview class.
// We want to hide the fact that the preview
// window may only become visible if there is
// a valid parent window (means, the FilePicker)
// is in execution mode. So unless someone sets
// the preview active with a valid parent
// window the preview may not be visible
//---------------------------------------------

class CPreviewAdapter
{
public:

    // ctor
    CPreviewAdapter(HINSTANCE instance);

    ~CPreviewAdapter();

    ::com::sun::star::uno::Sequence<sal_Int16> SAL_CALL getSupportedImageFormats();

    sal_Int32 SAL_CALL getTargetColorDepth();

    sal_Int32 SAL_CALL getAvailableWidth();

    sal_Int32 SAL_CALL getAvailableHeight();

    void SAL_CALL setImage(sal_Int16 aImageFormat, const ::com::sun::star::uno::Any& aImage)
        throw (::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::uno::RuntimeException);

    sal_Bool SAL_CALL setShowState(sal_Bool bShowState);

    sal_Bool SAL_CALL getShowState();

    void SAL_CALL setParent(HWND parent);

    //--------------------------------------
    // notification from parent
    //--------------------------------------

    void SAL_CALL notifyParentShow(sal_Bool bShow);

    void SAL_CALL notifyParentSizeChanged();

    void SAL_CALL notifyParentWindowPosChanged(sal_Bool bIsVisible);

private:
    // hide implementation details using the
    // bridge pattern
    std::auto_ptr<CPreviewAdapterImpl> m_pImpl;

// prevent copy and assignment
private:
    CPreviewAdapter(const CPreviewAdapter&);
    CPreviewAdapter& operator=(const CPreviewAdapter&);
};

#endif
<commit_msg>INTEGRATION: CWS sb59 (1.5.100); FILE MERGED 2006/08/10 12:04:53 sb 1.5.100.1: #i67487# Made code warning-free (wntmsci10).<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: previewadapter.hxx,v $
 *
 *  $Revision: 1.6 $
 *
 *  last change: $Author: obo $ $Date: 2006-10-12 10:54:28 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#ifndef _PREVIEWADAPTER_HXX_
#define _PREVIEWADAPTER_HXX_

#ifndef _SAL_TYPES_H_
#include <sal/types.h>
#endif

#ifndef _COM_SUN_STAR_UNO_SEQUENCE_HXX_
#include <com/sun/star/uno/Sequence.hxx>
#endif

#ifndef _COM_SUN_STAR_UNO_RUNTIMEEXCEPTION_HPP_
#include <com/sun/star/uno/RuntimeException.hpp>
#endif

#ifndef _COM_SUN_STAR_LANG_ILLEGALARGUMENTEXCEPTION_HPP_
#include <com/sun/star/lang/IllegalArgumentException.hpp>
#endif

#ifndef _COM_SUN_STAR_UNO_ANY_HXX_
#include <com/sun/star/uno/Any.hxx>
#endif

#if defined _MSC_VER
#pragma warning(push, 1)
#endif
#include <windows.h>
#if defined _MSC_VER
#pragma warning(pop)
#endif
#include <memory>

// forward declaration
class CPreviewAdapterImpl;

//---------------------------------------------
// A kind of a facade for the preview class.
// We want to hide the fact that the preview
// window may only become visible if there is
// a valid parent window (means, the FilePicker)
// is in execution mode. So unless someone sets
// the preview active with a valid parent
// window the preview may not be visible
//---------------------------------------------

class CPreviewAdapter
{
public:

    // ctor
    CPreviewAdapter(HINSTANCE instance);

    ~CPreviewAdapter();

    ::com::sun::star::uno::Sequence<sal_Int16> SAL_CALL getSupportedImageFormats();

    sal_Int32 SAL_CALL getTargetColorDepth();

    sal_Int32 SAL_CALL getAvailableWidth();

    sal_Int32 SAL_CALL getAvailableHeight();

    void SAL_CALL setImage(sal_Int16 aImageFormat, const ::com::sun::star::uno::Any& aImage)
        throw (::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::uno::RuntimeException);

    sal_Bool SAL_CALL setShowState(sal_Bool bShowState);

    sal_Bool SAL_CALL getShowState();

    void SAL_CALL setParent(HWND parent);

    //--------------------------------------
    // notification from parent
    //--------------------------------------

    void SAL_CALL notifyParentShow(bool bShow);

    void SAL_CALL notifyParentSizeChanged();

    void SAL_CALL notifyParentWindowPosChanged();

private:
    // hide implementation details using the
    // bridge pattern
    std::auto_ptr<CPreviewAdapterImpl> m_pImpl;

// prevent copy and assignment
private:
    CPreviewAdapter(const CPreviewAdapter&);
    CPreviewAdapter& operator=(const CPreviewAdapter&);
};

#endif
<|endoftext|>


<commit_before>/***************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (directui@nokia.com)
**
** This file is part of libmeegotouch.
**
** If you have questions regarding the use of this file, please contact
** Nokia at directui@nokia.com.
**
** This library is free software; you can redistribute it and/or
** modify it under the terms of the GNU Lesser General Public
** License version 2.1 as published by the Free Software Foundation
** and appearing in the file LICENSE.LGPL included in the packaging
** of this file.
**
****************************************************************************/

#include <QCoreApplication>
#include <QTextCodec>
#include <MLocale>
#include <unicode/uversion.h>

#include "pt_mcalendar.h"

void Pt_MCalendar::initTestCase()
{
    static int argc = 0;
    static char *argv[1] = { (char *) "" };
    qap = new QCoreApplication(argc, argv);
    QTextCodec::setCodecForCStrings(QTextCodec::codecForName("UTF-8"));
    QProcess process;
    process.start("sh -c \"dpkg -s libicu44 | grep Version | perl -pe 's/^Version:[[:space:]]*([^[[:space:]]+)$/$1/g'\"");
    if (!process.waitForFinished()) {
        qDebug() << "cannot run process to check libicu44 package version , exiting ...";
        exit(1);
    }
    icuPackageVersion = process.readAllStandardOutput();
    icuPackageVersion.replace("\n", "");
    qDebug() << "libicu44 package version is:" << icuPackageVersion;
}

void Pt_MCalendar::cleanupTestCase()
{
    delete qap;
}

void Pt_MCalendar::init()
{
}

void Pt_MCalendar::cleanup()
{
}

void Pt_MCalendar::benchmarkFormatDateTimePosixFormatString_U_QDateTime()
{
    QString language("en_US");   // will be overridden
    QString lcMessages("en_US"); // should not matter
    QString lcTime("ar_SA");     // this overrides language
    QString lcNumeric("en_US");  // should not matter
    MLocale locale(language);
    locale.setCategoryLocale(MLocale::MLcMessages, lcMessages);
    locale.setCategoryLocale(MLocale::MLcTime, lcTime);
    locale.setCategoryLocale(MLocale::MLcNumeric, lcNumeric);
    locale.setCalendarType(MLocale::GregorianCalendar);
    MCalendar mcal(locale);
    int year = 2008;
    int month = 7;
    int day = 21;
    int hour = 14;
    int minute = 31;
    int second = 3;
    mcal.setDate(year, month, day);
    mcal.setTime(hour, minute, second);
    QDate date(year, month, day);
    QTime time(hour, minute, second);
    QDateTime datetime(date, time, Qt::LocalTime);
    QLocale qlocale(language);
    QString format("%U");
    QString result("٢٩");
    QCOMPARE(locale.formatDateTime(mcal, format), result);
    QCOMPARE(locale.formatDateTime(datetime, format), result);

    QBENCHMARK {
        locale.formatDateTime(datetime, format);
    }
}

void Pt_MCalendar::benchmarkFormatDateTimePosixFormatString_U_MCalendar()
{
    QString language("en_US");   // will be overridden
    QString lcMessages("en_US"); // should not matter
    QString lcTime("ar_SA");     // this overrides language
    QString lcNumeric("en_US");  // should not matter
    MLocale locale(language);
    locale.setCategoryLocale(MLocale::MLcMessages, lcMessages);
    locale.setCategoryLocale(MLocale::MLcTime, lcTime);
    locale.setCategoryLocale(MLocale::MLcNumeric, lcNumeric);
    locale.setCalendarType(MLocale::GregorianCalendar);
    MCalendar mcal(locale);
    int year = 2008;
    int month = 7;
    int day = 21;
    int hour = 14;
    int minute = 31;
    int second = 3;
    mcal.setDate(year, month, day);
    mcal.setTime(hour, minute, second);
    QDate date(year, month, day);
    QTime time(hour, minute, second);
    QDateTime datetime(date, time, Qt::LocalTime);
    QLocale qlocale(language);
    QString format("%U");
    QString result("٢٩");
    QCOMPARE(locale.formatDateTime(mcal, format), result);
    QCOMPARE(locale.formatDateTime(datetime, format), result);

    QBENCHMARK {
        locale.formatDateTime(mcal, format);
    }
}

void Pt_MCalendar::benchmarkFormatDateTimePosixFormatString_V_MCalendar()
{
    QString language("en_US");   // will be overridden
    QString lcMessages("en_US"); // should not matter
    QString lcTime("ar_SA");     // this overrides language
    QString lcNumeric("en_US");  // should not matter
    MLocale locale(language);
    locale.setCategoryLocale(MLocale::MLcMessages, lcMessages);
    locale.setCategoryLocale(MLocale::MLcTime, lcTime);
    locale.setCategoryLocale(MLocale::MLcNumeric, lcNumeric);
    locale.setCalendarType(MLocale::GregorianCalendar);
    MCalendar mcal(locale);
    int year = 2008;
    int month = 7;
    int day = 21;
    int hour = 14;
    int minute = 31;
    int second = 3;
    mcal.setDate(year, month, day);
    mcal.setTime(hour, minute, second);
    QDate date(year, month, day);
    QTime time(hour, minute, second);
    QDateTime datetime(date, time, Qt::LocalTime);
    QLocale qlocale(language);
    QString format("%V");
    QString result("٣٠");
    QCOMPARE(locale.formatDateTime(mcal, format), result);
    QCOMPARE(locale.formatDateTime(datetime, format), result);

    QBENCHMARK {
        locale.formatDateTime(mcal, format);
    }
}

void Pt_MCalendar::benchmarkFormatDateTimePosixFormatString_r_MCalendar()
{
    QString language("en_US");   // will be overridden
    QString lcMessages("en_US"); // should not matter
    QString lcTime("ar_SA");     // this overrides language
    QString lcNumeric("en_US");  // should not matter
    MLocale locale(language);
    locale.setCategoryLocale(MLocale::MLcMessages, lcMessages);
    locale.setCategoryLocale(MLocale::MLcTime, lcTime);
    locale.setCategoryLocale(MLocale::MLcNumeric, lcNumeric);
    locale.setCalendarType(MLocale::GregorianCalendar);
    MCalendar mcal(locale);
    int year = 2008;
    int month = 7;
    int day = 21;
    int hour = 14;
    int minute = 31;
    int second = 3;
    mcal.setDate(year, month, day);
    mcal.setTime(hour, minute, second);
    QDate date(year, month, day);
    QTime time(hour, minute, second);
    QDateTime datetime(date, time, Qt::LocalTime);
    QLocale qlocale(language);
    QString format("%r");
    QString result("٢:٣١ م");
    QCOMPARE(locale.formatDateTime(mcal, format), result);
    QCOMPARE(locale.formatDateTime(datetime, format), result);

    QBENCHMARK {
        locale.formatDateTime(mcal, format);
    }
}

void Pt_MCalendar::benchmarkFormatDateTimePosixFormatString_R_MCalendar()
{
    QString language("en_US");   // will be overridden
    QString lcMessages("en_US"); // should not matter
    QString lcTime("ar_SA");     // this overrides language
    QString lcNumeric("en_US");  // should not matter
    MLocale locale(language);
    locale.setCategoryLocale(MLocale::MLcMessages, lcMessages);
    locale.setCategoryLocale(MLocale::MLcTime, lcTime);
    locale.setCategoryLocale(MLocale::MLcNumeric, lcNumeric);
    locale.setCalendarType(MLocale::GregorianCalendar);
    MCalendar mcal(locale);
    int year = 2008;
    int month = 7;
    int day = 21;
    int hour = 14;
    int minute = 31;
    int second = 3;
    mcal.setDate(year, month, day);
    mcal.setTime(hour, minute, second);
    QDate date(year, month, day);
    QTime time(hour, minute, second);
    QDateTime datetime(date, time, Qt::LocalTime);
    QLocale qlocale(language);
    QString format("%R");
    QString result("١٤:٣١");
    QCOMPARE(locale.formatDateTime(mcal, format), result);
    QCOMPARE(locale.formatDateTime(datetime, format), result);

    QBENCHMARK {
        locale.formatDateTime(mcal, format);
    }
}

void Pt_MCalendar::benchmarkFormatDateTimePosixFormatString_t_MCalendar()
{
    QString language("en_US");   // will be overridden
    QString lcMessages("en_US"); // should not matter
    QString lcTime("ar_SA");     // this overrides language
    QString lcNumeric("en_US");  // should not matter
    MLocale locale(language);
    locale.setCategoryLocale(MLocale::MLcMessages, lcMessages);
    locale.setCategoryLocale(MLocale::MLcTime, lcTime);
    locale.setCategoryLocale(MLocale::MLcNumeric, lcNumeric);
    locale.setCalendarType(MLocale::GregorianCalendar);
    MCalendar mcal(locale);
    int year = 2008;
    int month = 7;
    int day = 21;
    int hour = 14;
    int minute = 31;
    int second = 3;
    mcal.setDate(year, month, day);
    mcal.setTime(hour, minute, second);
    QDate date(year, month, day);
    QTime time(hour, minute, second);
    QDateTime datetime(date, time, Qt::LocalTime);
    QLocale qlocale(language);
    QString format("%t");
    QString result("\t");
    QCOMPARE(locale.formatDateTime(mcal, format), result);
    QCOMPARE(locale.formatDateTime(datetime, format), result);

    QBENCHMARK {
        locale.formatDateTime(mcal, format);
    }
}

void Pt_MCalendar::benchmarkIcuFormatString()
{
    QString language("en_US");   // will be overridden
    QString lcMessages("en_US"); // should not matter
    QString lcTime("fi_FI");     // this overrides language
    QString lcNumeric("en_US");  // should not matter
    MLocale locale(language);
    locale.setCategoryLocale(MLocale::MLcMessages, lcMessages);
    locale.setCategoryLocale(MLocale::MLcTime, lcTime);
    locale.setCategoryLocale(MLocale::MLcNumeric, lcNumeric);
    locale.setCalendarType(MLocale::IslamicCalendar); // should not matter
    QCOMPARE(locale.icuFormatString(
                 MLocale::DateFull,
                 MLocale::TimeFull,
                 MLocale::GregorianCalendar),
             QString("cccc d. MMMM y H:mm:ss zzzz"));

    QBENCHMARK {
        locale.icuFormatString(
                 MLocale::DateFull,
                 MLocale::TimeFull,
                 MLocale::GregorianCalendar);
    }
}

void Pt_MCalendar::benchmarkFormatDateTime()
{
    QString language("en_US");   // will be overridden
    QString lcMessages("en_US"); // should not matter
    QString lcTime("fi_FI");     // this overrides language
    QString lcNumeric("en_US");  // should not matter
    MLocale locale(language);
    locale.setCategoryLocale(MLocale::MLcMessages, lcMessages);
    locale.setCategoryLocale(MLocale::MLcTime, lcTime);
    locale.setCategoryLocale(MLocale::MLcNumeric, lcNumeric);
    MCalendar::setSystemTimeZone("Europe/Helsinki");
    MCalendar calendar;
    calendar.setDateTime(QDateTime(QDate(2010, 7, 13),
                                   QTime(14, 51, 07, 0),
                                   Qt::LocalTime));

    QCOMPARE(locale.formatDateTime(
                 calendar, MLocale::DateFull, MLocale::TimeFull),
             QString("tiistai 13. heinäkuuta 2010 14:51:07 Itä-Euroopan kesäaika"));

    QBENCHMARK {
        locale.formatDateTime(
            calendar, MLocale::DateFull, MLocale::TimeFull);
    }
}

QTEST_APPLESS_MAIN(Pt_MCalendar);

<commit_msg>Changes: fix benchmarks pt_mcalendar.cpp<commit_after>/***************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (directui@nokia.com)
**
** This file is part of libmeegotouch.
**
** If you have questions regarding the use of this file, please contact
** Nokia at directui@nokia.com.
**
** This library is free software; you can redistribute it and/or
** modify it under the terms of the GNU Lesser General Public
** License version 2.1 as published by the Free Software Foundation
** and appearing in the file LICENSE.LGPL included in the packaging
** of this file.
**
****************************************************************************/

#include <QCoreApplication>
#include <QTextCodec>
#include <MLocale>
#include <unicode/uversion.h>

#include "pt_mcalendar.h"

void Pt_MCalendar::initTestCase()
{
    static int argc = 0;
    static char *argv[1] = { (char *) "" };
    qap = new QCoreApplication(argc, argv);
    QTextCodec::setCodecForCStrings(QTextCodec::codecForName("UTF-8"));
    QProcess process;
    process.start("sh -c \"dpkg -s libicu44 | grep Version | perl -pe 's/^Version:[[:space:]]*([^[[:space:]]+)$/$1/g'\"");
    if (!process.waitForFinished()) {
        qDebug() << "cannot run process to check libicu44 package version , exiting ...";
        exit(1);
    }
    icuPackageVersion = process.readAllStandardOutput();
    icuPackageVersion.replace("\n", "");
    qDebug() << "libicu44 package version is:" << icuPackageVersion;
}

void Pt_MCalendar::cleanupTestCase()
{
    delete qap;
}

void Pt_MCalendar::init()
{
}

void Pt_MCalendar::cleanup()
{
}

void Pt_MCalendar::benchmarkFormatDateTimePosixFormatString_U_QDateTime()
{
    QString language("en_US");   // will be overridden
    QString lcMessages("en_US"); // should not matter
    QString lcTime("ar_SA");     // this overrides language
    QString lcNumeric("ar_SA");  // does matter, overrides localized numbers in dates
    MLocale locale(language);
    locale.setCategoryLocale(MLocale::MLcMessages, lcMessages);
    locale.setCategoryLocale(MLocale::MLcTime, lcTime);
    locale.setCategoryLocale(MLocale::MLcNumeric, lcNumeric);
    locale.setCalendarType(MLocale::GregorianCalendar);
    MCalendar mcal(locale);
    int year = 2008;
    int month = 7;
    int day = 21;
    int hour = 14;
    int minute = 31;
    int second = 3;
    mcal.setDate(year, month, day);
    mcal.setTime(hour, minute, second);
    QDate date(year, month, day);
    QTime time(hour, minute, second);
    QDateTime datetime(date, time, Qt::LocalTime);
    QLocale qlocale(language);
    QString format("%U");
    QString result("٢٩");
    QCOMPARE(locale.formatDateTime(mcal, format), result);
    QCOMPARE(locale.formatDateTime(datetime, format), result);

    QBENCHMARK {
        locale.formatDateTime(datetime, format);
    }
}

void Pt_MCalendar::benchmarkFormatDateTimePosixFormatString_U_MCalendar()
{
    QString language("en_US");   // will be overridden
    QString lcMessages("en_US"); // should not matter
    QString lcTime("ar_SA");     // this overrides language
    QString lcNumeric("ar_SA");  // does matter, overrides localized numbers in dates
    MLocale locale(language);
    locale.setCategoryLocale(MLocale::MLcMessages, lcMessages);
    locale.setCategoryLocale(MLocale::MLcTime, lcTime);
    locale.setCategoryLocale(MLocale::MLcNumeric, lcNumeric);
    locale.setCalendarType(MLocale::GregorianCalendar);
    MCalendar mcal(locale);
    int year = 2008;
    int month = 7;
    int day = 21;
    int hour = 14;
    int minute = 31;
    int second = 3;
    mcal.setDate(year, month, day);
    mcal.setTime(hour, minute, second);
    QDate date(year, month, day);
    QTime time(hour, minute, second);
    QDateTime datetime(date, time, Qt::LocalTime);
    QLocale qlocale(language);
    QString format("%U");
    QString result("٢٩");
    QCOMPARE(locale.formatDateTime(mcal, format), result);
    QCOMPARE(locale.formatDateTime(datetime, format), result);

    QBENCHMARK {
        locale.formatDateTime(mcal, format);
    }
}

void Pt_MCalendar::benchmarkFormatDateTimePosixFormatString_V_MCalendar()
{
    QString language("en_US");   // will be overridden
    QString lcMessages("en_US"); // should not matter
    QString lcTime("ar_SA");     // this overrides language
    QString lcNumeric("ar_SA");  // does matter, overrides localized numbers in dates
    MLocale locale(language);
    locale.setCategoryLocale(MLocale::MLcMessages, lcMessages);
    locale.setCategoryLocale(MLocale::MLcTime, lcTime);
    locale.setCategoryLocale(MLocale::MLcNumeric, lcNumeric);
    locale.setCalendarType(MLocale::GregorianCalendar);
    MCalendar mcal(locale);
    int year = 2008;
    int month = 7;
    int day = 21;
    int hour = 14;
    int minute = 31;
    int second = 3;
    mcal.setDate(year, month, day);
    mcal.setTime(hour, minute, second);
    QDate date(year, month, day);
    QTime time(hour, minute, second);
    QDateTime datetime(date, time, Qt::LocalTime);
    QLocale qlocale(language);
    QString format("%V");
    QString result("٣٠");
    QCOMPARE(locale.formatDateTime(mcal, format), result);
    QCOMPARE(locale.formatDateTime(datetime, format), result);

    QBENCHMARK {
        locale.formatDateTime(mcal, format);
    }
}

void Pt_MCalendar::benchmarkFormatDateTimePosixFormatString_r_MCalendar()
{
    QString language("en_US");   // will be overridden
    QString lcMessages("en_US"); // should not matter
    QString lcTime("ar_SA");     // this overrides language
    QString lcNumeric("ar_SA");  // does matter, overrides localized numbers in dates
    MLocale locale(language);
    locale.setCategoryLocale(MLocale::MLcMessages, lcMessages);
    locale.setCategoryLocale(MLocale::MLcTime, lcTime);
    locale.setCategoryLocale(MLocale::MLcNumeric, lcNumeric);
    locale.setCalendarType(MLocale::GregorianCalendar);
    MCalendar mcal(locale);
    int year = 2008;
    int month = 7;
    int day = 21;
    int hour = 14;
    int minute = 31;
    int second = 3;
    mcal.setDate(year, month, day);
    mcal.setTime(hour, minute, second);
    QDate date(year, month, day);
    QTime time(hour, minute, second);
    QDateTime datetime(date, time, Qt::LocalTime);
    QLocale qlocale(language);
    QString format("%r");
    QString result("٢:٣١ م");
    QCOMPARE(locale.formatDateTime(mcal, format), result);
    QCOMPARE(locale.formatDateTime(datetime, format), result);

    QBENCHMARK {
        locale.formatDateTime(mcal, format);
    }
}

void Pt_MCalendar::benchmarkFormatDateTimePosixFormatString_R_MCalendar()
{
    QString language("en_US");   // will be overridden
    QString lcMessages("en_US"); // should not matter
    QString lcTime("ar_SA");     // this overrides language
    QString lcNumeric("ar_SA");  // does matter, overrides localized numbers in dates
    MLocale locale(language);
    locale.setCategoryLocale(MLocale::MLcMessages, lcMessages);
    locale.setCategoryLocale(MLocale::MLcTime, lcTime);
    locale.setCategoryLocale(MLocale::MLcNumeric, lcNumeric);
    locale.setCalendarType(MLocale::GregorianCalendar);
    MCalendar mcal(locale);
    int year = 2008;
    int month = 7;
    int day = 21;
    int hour = 14;
    int minute = 31;
    int second = 3;
    mcal.setDate(year, month, day);
    mcal.setTime(hour, minute, second);
    QDate date(year, month, day);
    QTime time(hour, minute, second);
    QDateTime datetime(date, time, Qt::LocalTime);
    QLocale qlocale(language);
    QString format("%R");
    QString result("١٤:٣١");
    QCOMPARE(locale.formatDateTime(mcal, format), result);
    QCOMPARE(locale.formatDateTime(datetime, format), result);

    QBENCHMARK {
        locale.formatDateTime(mcal, format);
    }
}

void Pt_MCalendar::benchmarkFormatDateTimePosixFormatString_t_MCalendar()
{
    QString language("en_US");   // will be overridden
    QString lcMessages("en_US"); // should not matter
    QString lcTime("ar_SA");     // this overrides language
    QString lcNumeric("ar_SA");  // does matter, overrides localized numbers in dates
    MLocale locale(language);
    locale.setCategoryLocale(MLocale::MLcMessages, lcMessages);
    locale.setCategoryLocale(MLocale::MLcTime, lcTime);
    locale.setCategoryLocale(MLocale::MLcNumeric, lcNumeric);
    locale.setCalendarType(MLocale::GregorianCalendar);
    MCalendar mcal(locale);
    int year = 2008;
    int month = 7;
    int day = 21;
    int hour = 14;
    int minute = 31;
    int second = 3;
    mcal.setDate(year, month, day);
    mcal.setTime(hour, minute, second);
    QDate date(year, month, day);
    QTime time(hour, minute, second);
    QDateTime datetime(date, time, Qt::LocalTime);
    QLocale qlocale(language);
    QString format("%t");
    QString result("\t");
    QCOMPARE(locale.formatDateTime(mcal, format), result);
    QCOMPARE(locale.formatDateTime(datetime, format), result);

    QBENCHMARK {
        locale.formatDateTime(mcal, format);
    }
}

void Pt_MCalendar::benchmarkIcuFormatString()
{
    QString language("en_US");   // will be overridden
    QString lcMessages("en_US"); // should not matter
    QString lcTime("fi_FI");     // this overrides language
    QString lcNumeric("en_US");  // should not matter, no localized numbers involved
    MLocale locale(language);
    locale.setCategoryLocale(MLocale::MLcMessages, lcMessages);
    locale.setCategoryLocale(MLocale::MLcTime, lcTime);
    locale.setCategoryLocale(MLocale::MLcNumeric, lcNumeric);
    locale.setCalendarType(MLocale::IslamicCalendar); // should not matter
    QCOMPARE(locale.icuFormatString(
                 MLocale::DateFull,
                 MLocale::TimeFull,
                 MLocale::GregorianCalendar),
             QString("cccc d. MMMM y H:mm:ss zzzz"));

    QBENCHMARK {
        locale.icuFormatString(
                 MLocale::DateFull,
                 MLocale::TimeFull,
                 MLocale::GregorianCalendar);
    }
}

void Pt_MCalendar::benchmarkFormatDateTime()
{
    QString language("en_US");   // will be overridden
    QString lcMessages("en_US"); // should not matter
    QString lcTime("fi_FI");     // this overrides language
    QString lcNumeric("en_US");  // should not matter, no localized numbers involved
    MLocale locale(language);
    locale.setCategoryLocale(MLocale::MLcMessages, lcMessages);
    locale.setCategoryLocale(MLocale::MLcTime, lcTime);
    locale.setCategoryLocale(MLocale::MLcNumeric, lcNumeric);
    MCalendar::setSystemTimeZone("Europe/Helsinki");
    MCalendar calendar;
    calendar.setDateTime(QDateTime(QDate(2010, 7, 13),
                                   QTime(14, 51, 07, 0),
                                   Qt::LocalTime));

    QCOMPARE(locale.formatDateTime(
                 calendar, MLocale::DateFull, MLocale::TimeFull),
             QString("tiistai 13. heinäkuuta 2010 14:51:07 Itä-Euroopan kesäaika"));

    QBENCHMARK {
        locale.formatDateTime(
            calendar, MLocale::DateFull, MLocale::TimeFull);
    }
}

QTEST_APPLESS_MAIN(Pt_MCalendar);

<|endoftext|>


<commit_before>#include "Component.h"
#include "Simulation.h"
#include "MooseApp.h"

unsigned int Component::subdomain_ids = 0;
unsigned int Component::bc_ids = 0;

template<>
InputParameters validParams<Component>()
{
  InputParameters params = validParams<R7Object>();
  params.addPrivateParam<Simulation *>("_sim");

  params.addParam<std::string>("physics_input_file", "Input file with physics");
  params.addPrivateParam<std::string>("built_by_action", "add_component");

  return params;
}

/*
 * Class used by Component class to map vector variables through friendly names
 * i.e. friendly name = inlet:K_loss; variableName = K_loss, position = 1
 */
RavenMapContainer::RavenMapContainer()
{
}
/*
 * CHANGE VARIABLENAME to ControllableName
 */
RavenMapContainer::RavenMapContainer(const std::string & controllableParName, unsigned int & position):
   _controllableParName(controllableParName),
   _position(position)
{
}
RavenMapContainer::~RavenMapContainer(){
}
const std::string &
RavenMapContainer::getControllableParName(){
   return _controllableParName;
}
unsigned int &
RavenMapContainer::getControllableParPosition(){
   return _position;
}

/*
 * Component implementation
 */
static unsigned int comp_id = 0;

std::string
Component::genName(const std::string & prefix, unsigned int id, const std::string & suffix)
{
  std::stringstream ss;
  ss << prefix << id << suffix;
  return ss.str();
}

std::string
Component::genName(const std::string & prefix, const std::string & suffix)
{
  std::stringstream ss;
  ss << prefix << ":" << suffix;
  return ss.str();
}
std::string
Component::genName(const std::string & prefix, const std::string & middle, const std::string & suffix)
{
  std::stringstream ss;
  ss << prefix << middle << suffix;
  return ss.str();
}

std::vector<std::string>
Component::split(const std::string & rname)
{
  std::vector<std::string> splitted;
  MooseUtils::tokenize(rname, splitted, 1, ":");

  std::string section_name("");
  for (unsigned int i = 0; i < splitted.size() - 1; i++)
  {
    if (i > 0)
      section_name.append(":");
    section_name.append(splitted[i]);
  }
  std::string prop_name = splitted[splitted.size() - 1];

  // construct the 2 element array with section and property name
  std::vector<std::string> result(2);
  result[0] = section_name;
  result[1] = prop_name;

  return result;
}

Component::Component(const std::string & name, InputParameters parameters) :
    R7Object(name, parameters),
    _id(comp_id++),
    _parent(parameters.have_parameter<Component *>("_parent") ? getParam<Component *>("_parent") : NULL),
    _sim(*getParam<Simulation *>("_sim")),
    _factory(_app.getFactory()),
    _mesh(_sim.mesh()),
    _phys_mesh(_sim.physicalMesh()),

    _input_file_name(getParam<std::string>("physics_input_file")),

    _zero(_sim._zero)
{
}

Component::~Component()
{
}

void
Component::init()
{
}

unsigned int
Component::getNextSubdomainId()
{
  unsigned int sd_id = subdomain_ids++;
  _subdomains.push_back(sd_id);
  if (_parent)
    _parent->_subdomains.push_back(sd_id);
  return sd_id;
}

unsigned int
Component::getNextBCId()
{
  unsigned int id = bc_ids++;
  return id;
}

void
Component::aliasParam(const std::string & rname, const std::string & name, Component * comp/* = NULL*/)
{
  if (comp == NULL)
    _param_alias_map[rname] = std::pair<Component *, std::string>(this, name);
  else
    _param_alias_map[rname] = std::pair<Component *, std::string>(comp, name);
}

void
Component::aliasVectorParam(const std::string & rname, const std::string & name, unsigned int pos, Component * /*comp = NULL*/)
{
  createVectorControllableParMapping(rname, name, pos);
}

void
Component::connectObject(const std::string & rname, const std::string & mooseName, const std::string & name)
{
  RavenNameEntry rne(mooseName, name);
  _rname_map[rname][name].push_back(rne);
}

void
Component::connectObject(const std::string & rname, const std::string & mooseName, const std::string & name, const std::string & par_name)
{
  RavenNameEntry rne(mooseName, par_name);
  _rname_map[rname][name].push_back(rne);
}

void
Component::createVectorControllableParMapping(const std::string & rname, const std::string & mooseName, unsigned int pos)
{
  _rvect_map[rname] = RavenMapContainer(mooseName, pos);
}
<commit_msg>genName() is using ':' as a separator in all variants (refs idaholab/relap-7#2293)<commit_after>#include "Component.h"
#include "Simulation.h"
#include "MooseApp.h"

unsigned int Component::subdomain_ids = 0;
unsigned int Component::bc_ids = 0;

template<>
InputParameters validParams<Component>()
{
  InputParameters params = validParams<R7Object>();
  params.addPrivateParam<Simulation *>("_sim");

  params.addParam<std::string>("physics_input_file", "Input file with physics");
  params.addPrivateParam<std::string>("built_by_action", "add_component");

  return params;
}

/*
 * Class used by Component class to map vector variables through friendly names
 * i.e. friendly name = inlet:K_loss; variableName = K_loss, position = 1
 */
RavenMapContainer::RavenMapContainer()
{
}
/*
 * CHANGE VARIABLENAME to ControllableName
 */
RavenMapContainer::RavenMapContainer(const std::string & controllableParName, unsigned int & position):
   _controllableParName(controllableParName),
   _position(position)
{
}
RavenMapContainer::~RavenMapContainer(){
}
const std::string &
RavenMapContainer::getControllableParName(){
   return _controllableParName;
}
unsigned int &
RavenMapContainer::getControllableParPosition(){
   return _position;
}

/*
 * Component implementation
 */
static unsigned int comp_id = 0;

std::string
Component::genName(const std::string & prefix, unsigned int id, const std::string & suffix)
{
  std::stringstream ss;
  ss << prefix << ":" << id << ":" << suffix;
  return ss.str();
}

std::string
Component::genName(const std::string & prefix, const std::string & suffix)
{
  std::stringstream ss;
  ss << prefix << ":" << suffix;
  return ss.str();
}
std::string
Component::genName(const std::string & prefix, const std::string & middle, const std::string & suffix)
{
  std::stringstream ss;
  ss << prefix << ":" << middle << ":" << suffix;
  return ss.str();
}

std::vector<std::string>
Component::split(const std::string & rname)
{
  std::vector<std::string> splitted;
  MooseUtils::tokenize(rname, splitted, 1, ":");

  std::string section_name("");
  for (unsigned int i = 0; i < splitted.size() - 1; i++)
  {
    if (i > 0)
      section_name.append(":");
    section_name.append(splitted[i]);
  }
  std::string prop_name = splitted[splitted.size() - 1];

  // construct the 2 element array with section and property name
  std::vector<std::string> result(2);
  result[0] = section_name;
  result[1] = prop_name;

  return result;
}

Component::Component(const std::string & name, InputParameters parameters) :
    R7Object(name, parameters),
    _id(comp_id++),
    _parent(parameters.have_parameter<Component *>("_parent") ? getParam<Component *>("_parent") : NULL),
    _sim(*getParam<Simulation *>("_sim")),
    _factory(_app.getFactory()),
    _mesh(_sim.mesh()),
    _phys_mesh(_sim.physicalMesh()),

    _input_file_name(getParam<std::string>("physics_input_file")),

    _zero(_sim._zero)
{
}

Component::~Component()
{
}

void
Component::init()
{
}

unsigned int
Component::getNextSubdomainId()
{
  unsigned int sd_id = subdomain_ids++;
  _subdomains.push_back(sd_id);
  if (_parent)
    _parent->_subdomains.push_back(sd_id);
  return sd_id;
}

unsigned int
Component::getNextBCId()
{
  unsigned int id = bc_ids++;
  return id;
}

void
Component::aliasParam(const std::string & rname, const std::string & name, Component * comp/* = NULL*/)
{
  if (comp == NULL)
    _param_alias_map[rname] = std::pair<Component *, std::string>(this, name);
  else
    _param_alias_map[rname] = std::pair<Component *, std::string>(comp, name);
}

void
Component::aliasVectorParam(const std::string & rname, const std::string & name, unsigned int pos, Component * /*comp = NULL*/)
{
  createVectorControllableParMapping(rname, name, pos);
}

void
Component::connectObject(const std::string & rname, const std::string & mooseName, const std::string & name)
{
  RavenNameEntry rne(mooseName, name);
  _rname_map[rname][name].push_back(rne);
}

void
Component::connectObject(const std::string & rname, const std::string & mooseName, const std::string & name, const std::string & par_name)
{
  RavenNameEntry rne(mooseName, par_name);
  _rname_map[rname][name].push_back(rne);
}

void
Component::createVectorControllableParMapping(const std::string & rname, const std::string & mooseName, unsigned int pos)
{
  _rvect_map[rname] = RavenMapContainer(mooseName, pos);
}
<|endoftext|>