<commit_before>/*
    Copyright (C) 2007, 2008 Nikolas Zimmermann <zimmermann@kde.org>

    This file is part of the KDE project

    This library is free software you can redistribute it and/or
    modify it under the terms of the GNU Library General Public
    License as published by the Free Software Foundation either
    version 2 of the License, or (at your option) any later version.

    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
    Library General Public License for more details.

    You should have received a copy of the GNU Library General Public License
    aint with this library see the file COPYING.LIB.  If not, write to
    the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
    Boston, MA 02110-1301, USA.
*/

#include <QtCore/QCoreApplication>
#include <QtCore/QDebug>
#include <QtCore/QFile>
#include <QtCore/QStringList>

#include "GeoDataFolder.h"

#include "GeoDataParser.h"
#include "GeoDataDocument.h"

#include "GeoSceneDocument.h"
#include "GeoSceneHead.h"
#include "GeoSceneIcon.h"
#include "GeoSceneLayer.h"
#include "GeoSceneMap.h"
#include "GeoSceneParser.h"
#include "GeoSceneProperty.h"
#include "GeoSceneSettings.h"
#include "GeoSceneZoom.h"

#ifdef Q_OS_WIN
#include <stdio.h>
#include <stdlib.h>

void myMessageOutput(QtMsgType type, const char *msg)
{
    switch (type) {
        case QtDebugMsg:
            fprintf(stdout, "Debug: %s\n", msg);
            break;
        case QtWarningMsg:
            fprintf(stdout, "Warning: %s\n", msg);
            break;
        case QtCriticalMsg:
            fprintf(stdout, "Critical: %s\n", msg);
            break;
        case QtFatalMsg:
            fprintf(stdout, "Fatal: %s\n", msg);
            abort();
    }
}
#endif

using namespace Marble;

void dumpGeoDataDocument(GeoDataDocument*);
void dumpGeoSceneDocument(GeoSceneDocument*);

int main(int argc, char** argv)
{
#ifdef Q_OS_WIN
    qInstallMsgHandler(myMessageOutput);
#endif
    QCoreApplication app(argc, argv);

    // Expect document as first command line argument
    if (app.arguments().size() <= 1) {
        qWarning("Pass file name as first argument!");
        return -1;
    }

    // Check whether file exists
    QFile file(app.arguments().at(1));
    if (!file.exists()) {
        qWarning("File does not exist!");
        return -1;
    }

    // Open file in right mode
    file.open(QIODevice::ReadOnly);

    GeoParser* parser = 0;
    const QString& fileName = file.fileName().toLower();

    // A real application, would use other heuristics to determine the source type!
    if (fileName.endsWith(".dgml"))
        parser = new GeoSceneParser(GeoScene_DGML);
    else if (fileName.endsWith(".kml"))
        parser = new GeoDataParser(GeoData_KML);
    else if (fileName.endsWith(".gpx"))
        parser = new GeoDataParser(GeoData_GPX);

    if (!parser) {
        qWarning("Could not determine file format!");
        return -1;
    }

    if (!parser->read(&file)) {
        qWarning("Could not parse file!");
        return -1;
    }

    // Get result document
    GeoDocument* document = parser->releaseDocument();
    Q_ASSERT(document);

    if (document->isGeoDataDocument()) {
        GeoDataDocument *dataDocument = static_cast<GeoDataDocument*>(document);
        QVector<GeoDataFeature>::const_iterator it = dataDocument->features().constBegin();
        QVector<GeoDataFeature>::const_iterator end = dataDocument->features().constEnd();
        qDebug() << "---------------------------------------------------------";
        for (; it != end; ++it) {
            qDebug() << "Name: " << it->name();
        }
        dumpGeoDataDocument(static_cast<GeoDataDocument*>(document));
    } else if (document->isGeoSceneDocument()) {
        GeoSceneDocument *sceneDocument = static_cast<GeoSceneDocument*>(document);
        qDebug() << "Name: " << sceneDocument->head()->name();
        qDebug() << "Target: " << sceneDocument->head()->target();
        qDebug() << "Theme: " << sceneDocument->head()->theme();
        qDebug() << "Icon (pixmap): " << sceneDocument->head()->icon()->pixmap();
        qDebug() << "Icon (color) : " << sceneDocument->head()->icon()->color();
        qDebug() << "Description: " << sceneDocument->head()->description();
        qDebug() << "Visible: " << sceneDocument->head()->visible();
        qDebug() << "Discrete: " << sceneDocument->head()->zoom()->discrete();
        qDebug() << "Minimum: " << sceneDocument->head()->zoom()->minimum();
        qDebug() << "Maximum: " << sceneDocument->head()->zoom()->maximum();
        if(sceneDocument->settings() &&
           sceneDocument->settings()->property( "cities" ) &&
           sceneDocument->settings()->property( "relief" )) {
            qDebug() << "CitiesName: " << sceneDocument->settings()->property( "cities" )->name();
            qDebug() << "Available: " << sceneDocument->settings()->property( "cities" )->available();
            qDebug() << "Value: " << sceneDocument->settings()->property( "cities" )->value();
            qDebug() << "ReliefName: " << sceneDocument->settings()->property( "relief" )->name();
            qDebug() << "Available: " << sceneDocument->settings()->property( "relief" )->available();
            qDebug() << "Value: " << sceneDocument->settings()->property( "relief" )->value();
            qDebug() << "Test query a nonexistent property: " << sceneDocument->settings()->property( "nonexistent" )->name();
        }
        if(sceneDocument->map()) {
            qDebug() << "layers:" << sceneDocument->map()->layers().size();
            QVector<GeoSceneLayer*>::const_iterator it = sceneDocument->map()->layers().constBegin();
            QVector<GeoSceneLayer*>::const_iterator end = sceneDocument->map()->layers().constEnd();
            for (; it != end; it++) {
                GeoSceneLayer* layer = *it;
                qDebug() << "\t---------------------------------------------------------";
                qDebug() << "\tLayerName: " << layer->name();
                qDebug() << "\tBackend: " << layer->backend();
                QVector<GeoSceneAbstractDataset*>::const_iterator it = layer->datasets().constBegin();
                QVector<GeoSceneAbstractDataset*>::const_iterator end = layer->datasets().constEnd();
                for (; it != end; ++it) {
                    GeoSceneAbstractDataset* dataset = *it;
                    qDebug() << "\t\tDatasetName: " << dataset->name();
                    qDebug() << "\t\tFileformat: " << dataset->fileFormat();
                    qDebug() << "\t\tType: " << dataset->type();
                }
            }
        }
        dumpGeoSceneDocument(static_cast<GeoSceneDocument*>(document));
    }
    else {
        // A parsed document should either be a GeoDataDocument or a GeoSceneDocument!
        Q_ASSERT(false);
    }

    qDebug() << "\nSuccessfully parsed file!";
    delete document;
    qDebug() << "\nSuccessfully deleted file!";
    return 0;
}

QString formatOutput(int depth)
{
    QString result;
    for (int i = 0; i < depth; ++i)
        result += "  ";

    return result;
}

void dumpFoldersRecursively(const GeoDataContainer& container, int depth)
{
    QVector<GeoDataFolder> folders = container.folders();
    QString format = formatOutput(depth);

    fprintf(stderr, "%s", qPrintable(format + QString("Dumping container with %1 child folders!\n").arg(folders.size())));

    QVector<GeoDataFolder>::const_iterator it = folders.constBegin();
    const QVector<GeoDataFolder>::const_iterator end = folders.constEnd();

    for (; it != end; ++it) {
        fprintf(stderr, "%s", qPrintable(format + QString("Dumping child %1\n").arg(it - folders.constBegin() + 1)));
        dumpFoldersRecursively(*it, ++depth);
    }
}

void dumpGeoDataDocument(GeoDataDocument* document)
{
    dumpFoldersRecursively(*document, 0);
    // TODO: Dump all features!
}

void dumpGeoSceneDocument(GeoSceneDocument* document)
{
    // TODO: Maybe dump parsed datastructures here!
}
<commit_msg>add function to dump placemarks<commit_after>/*
    Copyright (C) 2007, 2008 Nikolas Zimmermann <zimmermann@kde.org>

    This file is part of the KDE project

    This library is free software you can redistribute it and/or
    modify it under the terms of the GNU Library General Public
    License as published by the Free Software Foundation either
    version 2 of the License, or (at your option) any later version.

    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
    Library General Public License for more details.

    You should have received a copy of the GNU Library General Public License
    aint with this library see the file COPYING.LIB.  If not, write to
    the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
    Boston, MA 02110-1301, USA.
*/

#include <QtCore/QCoreApplication>
#include <QtCore/QDebug>
#include <QtCore/QFile>
#include <QtCore/QStringList>

#include "GeoDataParser.h"
#include "GeoDataDocument.h"
#include "GeoDataFolder.h"
#include "GeoDataPlacemark.h"

#include "GeoSceneDocument.h"
#include "GeoSceneHead.h"
#include "GeoSceneIcon.h"
#include "GeoSceneLayer.h"
#include "GeoSceneMap.h"
#include "GeoSceneParser.h"
#include "GeoSceneProperty.h"
#include "GeoSceneSettings.h"
#include "GeoSceneZoom.h"

#ifdef Q_OS_WIN
#include <stdio.h>
#include <stdlib.h>

void myMessageOutput(QtMsgType type, const char *msg)
{
    switch (type) {
        case QtDebugMsg:
            fprintf(stdout, "Debug: %s\n", msg);
            break;
        case QtWarningMsg:
            fprintf(stdout, "Warning: %s\n", msg);
            break;
        case QtCriticalMsg:
            fprintf(stdout, "Critical: %s\n", msg);
            break;
        case QtFatalMsg:
            fprintf(stdout, "Fatal: %s\n", msg);
            abort();
    }
}
#endif

using namespace Marble;

void dumpGeoDataDocument(GeoDataDocument*);
void dumpGeoSceneDocument(GeoSceneDocument*);

int main(int argc, char** argv)
{
#ifdef Q_OS_WIN
    qInstallMsgHandler(myMessageOutput);
#endif
    QCoreApplication app(argc, argv);

    // Expect document as first command line argument
    if (app.arguments().size() <= 1) {
        qWarning("Pass file name as first argument!");
        return -1;
    }

    // Check whether file exists
    QFile file(app.arguments().at(1));
    if (!file.exists()) {
        qWarning("File does not exist!");
        return -1;
    }

    // Open file in right mode
    file.open(QIODevice::ReadOnly);

    GeoParser* parser = 0;
    const QString& fileName = file.fileName().toLower();

    // A real application, would use other heuristics to determine the source type!
    if (fileName.endsWith(".dgml"))
        parser = new GeoSceneParser(GeoScene_DGML);
    else if (fileName.endsWith(".kml"))
        parser = new GeoDataParser(GeoData_KML);
    else if (fileName.endsWith(".gpx"))
        parser = new GeoDataParser(GeoData_GPX);

    if (!parser) {
        qWarning("Could not determine file format!");
        return -1;
    }

    if (!parser->read(&file)) {
        qWarning("Could not parse file!");
        return -1;
    }

    // Get result document
    GeoDocument* document = parser->releaseDocument();
    Q_ASSERT(document);

    if (document->isGeoDataDocument()) {
        GeoDataDocument *dataDocument = static_cast<GeoDataDocument*>(document);
        QVector<GeoDataFeature>::const_iterator it = dataDocument->features().constBegin();
        QVector<GeoDataFeature>::const_iterator end = dataDocument->features().constEnd();
        qDebug() << "---------------------------------------------------------";
        for (; it != end; ++it) {
            qDebug() << "Name: " << it->name();
        }
        dumpGeoDataDocument(static_cast<GeoDataDocument*>(document));
    } else if (document->isGeoSceneDocument()) {
        GeoSceneDocument *sceneDocument = static_cast<GeoSceneDocument*>(document);
        qDebug() << "Name: " << sceneDocument->head()->name();
        qDebug() << "Target: " << sceneDocument->head()->target();
        qDebug() << "Theme: " << sceneDocument->head()->theme();
        qDebug() << "Icon (pixmap): " << sceneDocument->head()->icon()->pixmap();
        qDebug() << "Icon (color) : " << sceneDocument->head()->icon()->color();
        qDebug() << "Description: " << sceneDocument->head()->description();
        qDebug() << "Visible: " << sceneDocument->head()->visible();
        qDebug() << "Discrete: " << sceneDocument->head()->zoom()->discrete();
        qDebug() << "Minimum: " << sceneDocument->head()->zoom()->minimum();
        qDebug() << "Maximum: " << sceneDocument->head()->zoom()->maximum();
        if(sceneDocument->settings() &&
           sceneDocument->settings()->property( "cities" ) &&
           sceneDocument->settings()->property( "relief" )) {
            qDebug() << "CitiesName: " << sceneDocument->settings()->property( "cities" )->name();
            qDebug() << "Available: " << sceneDocument->settings()->property( "cities" )->available();
            qDebug() << "Value: " << sceneDocument->settings()->property( "cities" )->value();
            qDebug() << "ReliefName: " << sceneDocument->settings()->property( "relief" )->name();
            qDebug() << "Available: " << sceneDocument->settings()->property( "relief" )->available();
            qDebug() << "Value: " << sceneDocument->settings()->property( "relief" )->value();
            qDebug() << "Test query a nonexistent property: " << sceneDocument->settings()->property( "nonexistent" )->name();
        }
        if(sceneDocument->map()) {
            qDebug() << "layers:" << sceneDocument->map()->layers().size();
            QVector<GeoSceneLayer*>::const_iterator it = sceneDocument->map()->layers().constBegin();
            QVector<GeoSceneLayer*>::const_iterator end = sceneDocument->map()->layers().constEnd();
            for (; it != end; it++) {
                GeoSceneLayer* layer = *it;
                qDebug() << "\t---------------------------------------------------------";
                qDebug() << "\tLayerName: " << layer->name();
                qDebug() << "\tBackend: " << layer->backend();
                QVector<GeoSceneAbstractDataset*>::const_iterator it = layer->datasets().constBegin();
                QVector<GeoSceneAbstractDataset*>::const_iterator end = layer->datasets().constEnd();
                for (; it != end; ++it) {
                    GeoSceneAbstractDataset* dataset = *it;
                    qDebug() << "\t\tDatasetName: " << dataset->name();
                    qDebug() << "\t\tFileformat: " << dataset->fileFormat();
                    qDebug() << "\t\tType: " << dataset->type();
                }
            }
        }
        dumpGeoSceneDocument(static_cast<GeoSceneDocument*>(document));
    }
    else {
        // A parsed document should either be a GeoDataDocument or a GeoSceneDocument!
        Q_ASSERT(false);
    }

    qDebug() << "\nSuccessfully parsed file!";
    delete document;
    qDebug() << "\nSuccessfully deleted file!";
    return 0;
}

QString formatOutput(int depth)
{
    QString result;
    for (int i = 0; i < depth; ++i)
        result += "  ";

    return result;
}

void dumpGeoDataPlacemark(const GeoDataPlacemark& placemark)
{
    qDebug() << placemark.name() << placemark.population() << placemark.coordinate().toString();
}

void dumpFoldersRecursively(const GeoDataContainer& container, int depth)
{
    qDebug() << "dumping container with" << container.size() << "children...";

    QVector<GeoDataFolder> folders = container.folders();
    QVector<GeoDataPlacemark> placemarks = container.placemarks();
    QString format = formatOutput(depth);

    fprintf(stderr, "%s", qPrintable(format + QString("Dumping container with %1 child folders!\n").arg(folders.size())));

    QVector<GeoDataFolder>::const_iterator it = folders.constBegin();
    const QVector<GeoDataFolder>::const_iterator end = folders.constEnd();

    for (; it != end; ++it) {
        fprintf(stderr, "%s", qPrintable(format + QString("Dumping child %1\n").arg(it - folders.constBegin() + 1)));
        dumpFoldersRecursively(*it, ++depth);
    }

    fprintf(stderr, "%s", qPrintable(format + QString("Dumping container with %1 child placemarks!\n").arg(placemarks.size())));

    QVector<GeoDataPlacemark>::const_iterator pit = placemarks.constBegin();
    const QVector<GeoDataPlacemark>::const_iterator pend = placemarks.constEnd();

    for (; pit != pend; ++pit) {
        fprintf(stderr, "%s", qPrintable(format + QString("Dumping child %1\n").arg(pit - placemarks.constBegin() + 1)));
        dumpGeoDataPlacemark(*pit);
    }
}

void dumpGeoDataDocument(GeoDataDocument* document)
{
    dumpFoldersRecursively(*document, 0);
    // TODO: Dump all features!
}

void dumpGeoSceneDocument(GeoSceneDocument* document)
{
    // TODO: Maybe dump parsed datastructures here!
}
<|endoftext|>


<commit_before>// simplest make is g++ -O2 -std=c++11  fastavoidance.cpp  -g -o fastavoidance
#include <bitset>
#include <cassert>
#include <cmath>
#include <cstdint>
#include <cstdio>      /* printf, scanf, puts, NULL */
#include <cstdlib>
#include <cstring>
#include <ctime>
#include <iostream>
#include <fstream>
#include <queue>
#include <sys/time.h>
#include <vector>
#include "hashdb.h"
#include "fastavoidance.h"
#include "perm.h"
using namespace std;

// 1 to use a bithack inspired by permlab. Upshot: Code runs about a third faster. Downshot: Code is around 1/4 less memory efficient
#define USEBITHACK 1
#define USEPREFIXMAP 1

// Input: perm, inverse (which needs to be right in pos length - index - 1), perm length, index, complement of normalization of index - 1 largest letters in perm, a bitmap which should start off at zero for index = 0
// Output: bitmap is updated. answer is updated to be complement of normalization of index largest letters in perm
void extendnormalizetop(uint64_t perm, uint64_t inverse, int length, int index, uint64_t &answer, uint32_t & seenpos) {
  int i = length - index - 1;
  int oldpos = getdigit(inverse, i);
  int newpos = 0;
  if (oldpos != 0){
    uint32_t temp = seenpos << (32 - oldpos); // Note: shifting by 32 is ill-defined, which is why we explicitly eliminate digit = 0 case.
    newpos = __builtin_popcount(temp);
  }
  answer = setdigit(addpos(answer, newpos), newpos, index);
  seenpos = seenpos | (1 << oldpos);
}

void addprefixeshelper(uint64_t perm, int length, hashdb &table) {
  uint64_t entry = 0;
  uint64_t inverse = getinverse(perm, length);
  uint32_t seenpos = 0; // bit map of which letters we've seen so far
  for (int i = 0; i < length; i++) {
    extendnormalizetop(perm, inverse, length, i, entry, seenpos);
    //cout<<entry<<endl;
    if (!table.contains(entry)) table.add(entry);
  }
}

// build prefix table
void addprefixes(const hashdb &permset, hashdb &table) {
  vector <unsigned long long> patterns;
  permset.getvals(patterns);
  for (int i = 0; i < patterns.size(); i++) {
    uint64_t perm = patterns[i];
    int length = getmaxdigit(perm) + 1;
    displayperm(perm,length);
    addprefixeshelper(perm, length, table);
  }
}

unsigned long long stat1 = 0, stat2 = 0;

// THIS IS HOW YOU KEEP A FUNCTION FROM INLINING!
__attribute__((noinline)) uint64_t getinversecover(uint64_t perm, size_t length) {
  //__attribute__((noinline));
  return getinverse(perm, length);
}

// Detects if perm is in S_{length}(patternset), where maxavoidsize is the length of the longest pattern in patternset.
// Prerequisite:
// -- The subset of S_{n-1} contained in avoidset is exactly S_{n-1}(patternset)
// -- If USEBITHACK, then we also require that the user has already verified that all patterns in perm use both n and n-1.
static bool isavoider(uint64_t perm, uint64_t inverse, int maxavoidsize, int length, const hashdb &avoidset, const hashdb &patternset, const hashdb &prefixmap) {
  stat1++;
  if (length <= maxavoidsize && patternset.contains(perm)) { // if perm is an offending pattern
      return false;
  }
  uint32_t seenpos = 0;
  uint64_t prefixentry = 0;
  uint64_t currentperm = perm;
  if (length > 1) { // don't deal with permutations of size zero
    for (int i = length - 1; i >= 0 && i >= length - maxavoidsize - 1; i--) { // for i ranging from the largest-valued letter in perm to the (maxavoidsize + 1)-th largest-valued letter in perm
      if (i < length - 1) { // add back in digit we deleted a moment ago, but with value one smaller
        currentperm = addpos(currentperm, getdigit(inverse, i + 1));
	currentperm = setdigit(currentperm, getdigit(inverse, i + 1), i);
      }
      currentperm = killpos(currentperm, getdigit(inverse, i)); // now currentperm is perm, except with the letter of value i removed, and the permutation normalized to be on the letters 0,...,(length - 2)
      //displayperm(currentperm)
      if (!USEBITHACK || i < length - 2) stat2++;
      if ((!USEBITHACK || i < length - 2) && !avoidset.contains(currentperm)) { // Check if this sub-permutation of perm is in S_{length - 1}(patternset)
	return false; // found a subword not avoiding the patterns
      }

      if (USEPREFIXMAP) {
	extendnormalizetop(perm, inverse, length, length - 1 - i, prefixentry, seenpos);
	if (i < length - 1 && !prefixmap.contains(prefixentry)) return true;
	if (i == length - maxavoidsize) return false;
      }
      // The next two lines are special for when there is a single pattern and it is the identity. They reduce cache misses significantly. For |pi|=5, this gets roughly a x2 speedup
      // Can this hack be extended efficiently to arbitrary choices of pattern-sets?
      // if (i < length - 1 && getdigit(inverse, i) > getdigit(inverse, i + 1)) return true;
      // if (i == length - maxavoidsize) return false;
    }
  }
  return true;
}

// Get pos-th bit from bitmap. Indexing starts at 0
inline uint64_t getbit(uint64_t word, int pos) {
  return (word >> pos) & 1;
}

// Set pos-th bit from bitmap. Indexing starts at 0
inline uint64_t setbit(uint64_t word, uint64_t pos, uint64_t val) { // val is 1 or 0
  return (word & (~(0L) - (1<<pos))) + (1<<pos)*val;
}

// Shift the bits in positions pos, pos+1, ... to the right and insert bit with value val in position pos. Indexing starts at 0
// Note that due to bit-shift setup, is not capable to inserting in final position ==> Prereq: pos < 63
inline uint64_t insertbit(uint64_t word, uint64_t pos, uint64_t val) { // val is 1 or 0
  return (word & ((1 << pos) - 1) ) + ((word >> pos) << (pos + 1)) + val * (1 << pos);
}

// Builds the permutations in $S_1, ..., S_maxsize$ avoiding the
// patterns in patternset, the longest of which is length
// maxavoidsize. If justcount, does nothing with avoidervector but
// makes nuavoiders[i] be the number of avoiders in S_i (for i >
// 0). If !justcount, does nothing with numavoiders, but makes
// avoidervector contain a vector of all permutations in S_i in
// avoidervector[i] (for i > 0). plannedavoisetsize should be large if
// we expect a major computation and small otherwise (dictates how
// much memory is initially allocated to data structures at start of
// algorithm.).
// Note: Patternset patterns required to be size >= 2
void buildavoiders(const hashdb &patternset, int maxavoidsize, int maxsize,  vector < vector < uint64_t > > &avoidervector, vector < uint64_t > &numavoiders, bool justcount, uint64_t plannedavoidsetsize) {
  if (!justcount) avoidervector.resize(maxsize + 1);
    else numavoiders.resize(maxsize + 1);

  hashdb prefixmap(1<<3);
  addprefixes(patternset, prefixmap);
  hashdb avoidset = hashdb(plannedavoidsetsize); // hash table containing avoiders of all sizes
  uint64_t startperm = 0;
  avoidset.add(startperm); // identity in S_1
  if (!justcount) avoidervector[1].push_back(startperm);
  else numavoiders[1] = 1;

  std::queue<unsigned long long> avoiderstoextend; // queue of avoiders built so far.
  // when we find an avoider, we will add it to this queue. We will
  // then later take it out of the queue and use it to generate
  // options for avoiders of length one larger
  std::queue<unsigned long long> bitmaps; // Contains a bitmap associated with each avoider in avoiderstoextendd (if USEBITHACK)
  // The bitmap for a permutation w \in S_n has a 1 in position i iff
  // inserting letter (n + 1) in position i of w would result in
  // permutation w' such that if you removed the letter n from w', the
  // result would be a patternset-avoiding word. Thus when checking
  // whether w' is an avoider, we do not have to explicitly check for
  // this property, preventing a cache-miss.

  avoiderstoextend.push(startperm);
  if (USEBITHACK) bitmaps.push(3L);

  int currentlength = 1; // maintain as length of next permutation to be popped from avoiderstoextend
  int numleftcurrentlength = 1; // number of permutations left in avoiderstoextend until we have to increment currentlength
  int numnextlength = 0; // number of permutations of size currentlength + 1 in avoiderstoextend

  while (avoiderstoextend.size() > 0) {
    if (numleftcurrentlength == 0) {
      //cout<<"Finished n = "<<currentlength + 1<<" with "<<numavoiders[currentlength + 1]<<" avoiders"<<endl; // MEMORY EFFICIENCY NOTE: I TEMPORARILY LOOSE A FACTOR OF 1/3 WHEN I RESIZE
      numleftcurrentlength = numnextlength;
      numnextlength = 0;
      currentlength++;
    }
    uint64_t perm = avoiderstoextend.front();
    uint64_t bitmap = bitmaps.front();
    avoiderstoextend.pop();
    if (USEBITHACK) bitmaps.pop();
    numleftcurrentlength--;
    uint64_t inverse = getinversecover(perm, currentlength);
    uint64_t newinverse = setdigit(inverse, currentlength, currentlength); // inverse of the extended permutation
    for (int i = currentlength; i >= 0; i--) {
      // need to increment newinverse[perm[i]], decrement newinverse[currentlength]
      if (i < currentlength) newinverse = newinverse + (1L << (4 * getdigit(perm, i))) - (1L << (4 * currentlength));
      if (!USEBITHACK || getbit(bitmap, i) == 1) { // If we are using bithack, then we only bother extending perm by inserting value currentlength in i-th position if the bitmap tells tells us the result is a potential avoider
	uint64_t extendedperm = setdigit(addpos(perm, i), i, currentlength); // insert currentlength in i-th position (remember, values are indexed starting at 0)
	if (isavoider(extendedperm, newinverse, maxavoidsize, currentlength + 1, avoidset, patternset, prefixmap)) { // if extended permutation is avoider
	  if (!justcount) avoidervector[currentlength + 1].push_back(extendedperm);
	  else numavoiders[currentlength + 1]++;
	  if (currentlength + 1 < maxsize) {
	    avoiderstoextend.push(extendedperm);
	    avoidset.add(extendedperm);
	    numnextlength++;
	  }
	} else {
	  if (USEBITHACK) bitmap = setbit(bitmap, i, 0); // keep track of which insertion positions resulted in an avoider
	}
      }
    }
    if (USEBITHACK && currentlength + 1 < maxsize) {
      for (int i = currentlength; i >= 0; i--) {
	if (getbit(bitmap, i) == 1) {
	  bitmaps.push(insertbit(bitmap, i + 1, 1)); // using which insertion positions resulted in an avoider, build bitmap for each new avoider
	}
      }
    }
  }
}

// Example:
// string patternlist = "1234 3214"; // space separated list of patterns; need not be same sizes; must be in S_{<10}
// vector < vector < uint64_t > > avoidervector;
// buildavoidersfrompatternlist(patternlist, 10, avoidervector); // now avoidervector contains S_n(patternlist) stored in avoidervector[n] for 0 < n < 11
void buildavoidersfrompatternlist(string patternlist, int maxpermsize, vector < vector < uint64_t > > &avoidervector) {
  int maxpatternsize;
  hashdb patternset = hashdb(1<<3);
  makepatterns(patternlist, patternset, maxpatternsize);
  vector < uint64_t > numavoiders;
  buildavoiders(patternset, maxpatternsize, maxpermsize, avoidervector, numavoiders, false, (1L << 10)); // for large cases, make last argument much larger!
}

// Example:
// string patternlist = "1234 3214"; // space separated list of patterns; need not be same sizes; must be in S_{<10}
// vector < uint64_t > numavoiders;
// buildavoidersfrompatternlist(patternlist, 10, numavoiders); // now avoidervector contains |S_n(patternlist)| stored in numavoiders[n] for 0 < n < 11.
void countavoidersfrompatternlist(string patternlist, int maxpermsize, vector < uint64_t > &numavoiders) {
  int maxpatternsize;
  hashdb patternset = hashdb(1<<3);
  makepatterns(patternlist, patternset, maxpatternsize);
  vector < vector < uint64_t > > avoidervector;
  buildavoiders(patternset, maxpatternsize, maxpermsize, avoidervector, numavoiders, true, (1L << 10)); // for large cases, make last argument much larger!
}

// Inputs file stream containing string list of patterns on each line.
// e.g., infile might contain
// 1234 312
// 231 4132 312
// Outputs file stream alternating every other line
// (1) #<list of patterns>
// (2) |S_1(list of patterns)| |S_2(list of patterns)| ... |S_maxpermsize(list of patterns)|
// e.g., output file might contain
// #1234 312
// 0 2 5 13 31 66 127 225 373 586
// #231 4132 312
// 0 2 4 8 16 32 64 128 256 512
void countavoidersfromfile(ifstream &infile, ofstream &outfile, int maxpermsize, bool verbose) {
  string line;
  while (getline(infile, line)) {
    outfile<<"#"<<line<<endl;
    if (verbose) cout<<line<<endl;
    vector < uint64_t > numavoiders;
    timestamp_t start_time = get_timestamp();
    countavoidersfrompatternlist(line, maxpermsize, numavoiders);
    timestamp_t end_time = get_timestamp();
    for (int i = 1; i < numavoiders.size(); i++) {
      if (verbose) cout<<numavoiders[i]<<" ";
      outfile<<numavoiders[i]<<" ";
    }
    if (verbose) cout<<endl;
    outfile<<endl;
    if (verbose) cout<< "Time elapsed (s): "<<(end_time - start_time)/1000000.0L<<endl;
  }
  cout<<(double)stat2/(double)stat1<<endl;
  return;
}
<commit_msg>added a third statistic<commit_after>// simplest make is g++ -O2 -std=c++11  fastavoidance.cpp  -g -o fastavoidance
#include <bitset>
#include <cassert>
#include <cmath>
#include <cstdint>
#include <cstdio>      /* printf, scanf, puts, NULL */
#include <cstdlib>
#include <cstring>
#include <ctime>
#include <iostream>
#include <fstream>
#include <queue>
#include <sys/time.h>
#include <vector>
#include "hashdb.h"
#include "fastavoidance.h"
#include "perm.h"
using namespace std;

// 1 to use a bithack inspired by permlab. Upshot: Code runs about a third faster. Downshot: Code is around 1/4 less memory efficient
#define USEBITHACK 1
#define USEPREFIXMAP 1

// Input: perm, inverse (which needs to be right in pos length - index - 1), perm length, index, complement of normalization of index - 1 largest letters in perm, a bitmap which should start off at zero for index = 0
// Output: bitmap is updated. answer is updated to be complement of normalization of index largest letters in perm
void extendnormalizetop(uint64_t perm, uint64_t inverse, int length, int index, uint64_t &answer, uint32_t & seenpos) {
  int i = length - index - 1;
  int oldpos = getdigit(inverse, i);
  int newpos = 0;
  if (oldpos != 0){
    uint32_t temp = seenpos << (32 - oldpos); // Note: shifting by 32 is ill-defined, which is why we explicitly eliminate digit = 0 case.
    newpos = __builtin_popcount(temp);
  }
  answer = setdigit(addpos(answer, newpos), newpos, index);
  seenpos = seenpos | (1 << oldpos);
}

void addprefixeshelper(uint64_t perm, int length, hashdb &table) {
  uint64_t entry = 0;
  uint64_t inverse = getinverse(perm, length);
  uint32_t seenpos = 0; // bit map of which letters we've seen so far
  for (int i = 0; i < length; i++) {
    extendnormalizetop(perm, inverse, length, i, entry, seenpos);
    //cout<<entry<<endl;
    if (!table.contains(entry)) table.add(entry);
  }
}

// build prefix table
void addprefixes(const hashdb &permset, hashdb &table) {
  vector <unsigned long long> patterns;
  permset.getvals(patterns);
  for (int i = 0; i < patterns.size(); i++) {
    uint64_t perm = patterns[i];
    int length = getmaxdigit(perm) + 1;
    displayperm(perm,length);
    addprefixeshelper(perm, length, table);
  }
}

unsigned long long stat1 = 0, stat2 = 0, stat3 = 0;

// THIS IS HOW YOU KEEP A FUNCTION FROM INLINING!
__attribute__((noinline)) uint64_t getinversecover(uint64_t perm, size_t length) {
  //__attribute__((noinline));
  return getinverse(perm, length);
}

// Detects if perm is in S_{length}(patternset), where maxavoidsize is the length of the longest pattern in patternset.
// Prerequisite:
// -- The subset of S_{n-1} contained in avoidset is exactly S_{n-1}(patternset)
// -- If USEBITHACK, then we also require that the user has already verified that all patterns in perm use both n and n-1.
static bool isavoider(uint64_t perm, uint64_t inverse, int maxavoidsize, int length, const hashdb &avoidset, const hashdb &patternset, const hashdb &prefixmap) {
  stat1++;
  if (length <= maxavoidsize && patternset.contains(perm)) { // if perm is an offending pattern
      return false;
  }
  uint32_t seenpos = 0;
  uint64_t prefixentry = 0;
  uint64_t currentperm = perm;
  if (length > 1) { // don't deal with permutations of size zero
    for (int i = length - 1; i >= 0 && i >= length - maxavoidsize - 1; i--) { // for i ranging from the largest-valued letter in perm to the (maxavoidsize + 1)-th largest-valued letter in perm
      if (i < length - 1) { // add back in digit we deleted a moment ago, but with value one smaller
        currentperm = addpos(currentperm, getdigit(inverse, i + 1));
	currentperm = setdigit(currentperm, getdigit(inverse, i + 1), i);
      }
      currentperm = killpos(currentperm, getdigit(inverse, i)); // now currentperm is perm, except with the letter of value i removed, and the permutation normalized to be on the letters 0,...,(length - 2)
      //displayperm(currentperm)
      if (!USEBITHACK || i < length - 2) stat2++;
      if ((!USEBITHACK || i < length - 2) && !avoidset.contains(currentperm)) { // Check if this sub-permutation of perm is in S_{length - 1}(patternset)
	return false; // found a subword not avoiding the patterns
      }

      if (USEPREFIXMAP) {
	extendnormalizetop(perm, inverse, length, length - 1 - i, prefixentry, seenpos);
	if (i < length - 1 && !prefixmap.contains(prefixentry)) return true;
	if (i == length - maxavoidsize) return false;
      }
      // The next two lines are special for when there is a single pattern and it is the identity. They reduce cache misses significantly. For |pi|=5, this gets roughly a x2 speedup
      // Can this hack be extended efficiently to arbitrary choices of pattern-sets?
      // if (i < length - 1 && getdigit(inverse, i) > getdigit(inverse, i + 1)) return true;
      // if (i == length - maxavoidsize) return false;
    }
  }
  return true;
}

// Get pos-th bit from bitmap. Indexing starts at 0
inline uint64_t getbit(uint64_t word, int pos) {
  return (word >> pos) & 1;
}

// Set pos-th bit from bitmap. Indexing starts at 0
inline uint64_t setbit(uint64_t word, uint64_t pos, uint64_t val) { // val is 1 or 0
  return (word & (~(0L) - (1<<pos))) + (1<<pos)*val;
}

// Shift the bits in positions pos, pos+1, ... to the right and insert bit with value val in position pos. Indexing starts at 0
// Note that due to bit-shift setup, is not capable to inserting in final position ==> Prereq: pos < 63
inline uint64_t insertbit(uint64_t word, uint64_t pos, uint64_t val) { // val is 1 or 0
  return (word & ((1 << pos) - 1) ) + ((word >> pos) << (pos + 1)) + val * (1 << pos);
}

// Builds the permutations in $S_1, ..., S_maxsize$ avoiding the
// patterns in patternset, the longest of which is length
// maxavoidsize. If justcount, does nothing with avoidervector but
// makes nuavoiders[i] be the number of avoiders in S_i (for i >
// 0). If !justcount, does nothing with numavoiders, but makes
// avoidervector contain a vector of all permutations in S_i in
// avoidervector[i] (for i > 0). plannedavoisetsize should be large if
// we expect a major computation and small otherwise (dictates how
// much memory is initially allocated to data structures at start of
// algorithm.).
// Note: Patternset patterns required to be size >= 2
void buildavoiders(const hashdb &patternset, int maxavoidsize, int maxsize,  vector < vector < uint64_t > > &avoidervector, vector < uint64_t > &numavoiders, bool justcount, uint64_t plannedavoidsetsize) {
  if (!justcount) avoidervector.resize(maxsize + 1);
    else numavoiders.resize(maxsize + 1);

  hashdb prefixmap(1<<3);
  addprefixes(patternset, prefixmap);
  hashdb avoidset = hashdb(plannedavoidsetsize); // hash table containing avoiders of all sizes
  uint64_t startperm = 0;
  avoidset.add(startperm); // identity in S_1
  if (!justcount) avoidervector[1].push_back(startperm);
  else numavoiders[1] = 1;

  std::queue<unsigned long long> avoiderstoextend; // queue of avoiders built so far.
  // when we find an avoider, we will add it to this queue. We will
  // then later take it out of the queue and use it to generate
  // options for avoiders of length one larger
  std::queue<unsigned long long> bitmaps; // Contains a bitmap associated with each avoider in avoiderstoextendd (if USEBITHACK)
  // The bitmap for a permutation w \in S_n has a 1 in position i iff
  // inserting letter (n + 1) in position i of w would result in
  // permutation w' such that if you removed the letter n from w', the
  // result would be a patternset-avoiding word. Thus when checking
  // whether w' is an avoider, we do not have to explicitly check for
  // this property, preventing a cache-miss.

  avoiderstoextend.push(startperm);
  if (USEBITHACK) bitmaps.push(3L);

  int currentlength = 1; // maintain as length of next permutation to be popped from avoiderstoextend
  int numleftcurrentlength = 1; // number of permutations left in avoiderstoextend until we have to increment currentlength
  int numnextlength = 0; // number of permutations of size currentlength + 1 in avoiderstoextend

  while (avoiderstoextend.size() > 0) {
    if (numleftcurrentlength == 0) {
      //cout<<"Finished n = "<<currentlength + 1<<" with "<<numavoiders[currentlength + 1]<<" avoiders"<<endl; // MEMORY EFFICIENCY NOTE: I TEMPORARILY LOOSE A FACTOR OF 1/3 WHEN I RESIZE
      numleftcurrentlength = numnextlength;
      numnextlength = 0;
      currentlength++;
    }
    uint64_t perm = avoiderstoextend.front();
    uint64_t bitmap = bitmaps.front();
    avoiderstoextend.pop();
    if (USEBITHACK) bitmaps.pop();
    numleftcurrentlength--;
    uint64_t inverse = getinversecover(perm, currentlength);
    uint64_t newinverse = setdigit(inverse, currentlength, currentlength); // inverse of the extended permutation
    for (int i = currentlength; i >= 0; i--) {
      // need to increment newinverse[perm[i]], decrement newinverse[currentlength]
      stat3++;
      if (i < currentlength) newinverse = newinverse + (1L << (4 * getdigit(perm, i))) - (1L << (4 * currentlength));
      if (!USEBITHACK || getbit(bitmap, i) == 1) { // If we are using bithack, then we only bother extending perm by inserting value currentlength in i-th position if the bitmap tells tells us the result is a potential avoider
	uint64_t extendedperm = setdigit(addpos(perm, i), i, currentlength); // insert currentlength in i-th position (remember, values are indexed starting at 0)
	if (isavoider(extendedperm, newinverse, maxavoidsize, currentlength + 1, avoidset, patternset, prefixmap)) { // if extended permutation is avoider
	  if (!justcount) avoidervector[currentlength + 1].push_back(extendedperm);
	  else numavoiders[currentlength + 1]++;
	  if (currentlength + 1 < maxsize) {
	    avoiderstoextend.push(extendedperm);
	    avoidset.add(extendedperm);
	    numnextlength++;
	  }
	} else {
	  if (USEBITHACK) bitmap = setbit(bitmap, i, 0); // keep track of which insertion positions resulted in an avoider
	}
      }
    }
    if (USEBITHACK && currentlength + 1 < maxsize) {
      for (int i = currentlength; i >= 0; i--) {
	if (getbit(bitmap, i) == 1) {
	  bitmaps.push(insertbit(bitmap, i + 1, 1)); // using which insertion positions resulted in an avoider, build bitmap for each new avoider
	}
      }
    }
  }
}

// Example:
// string patternlist = "1234 3214"; // space separated list of patterns; need not be same sizes; must be in S_{<10}
// vector < vector < uint64_t > > avoidervector;
// buildavoidersfrompatternlist(patternlist, 10, avoidervector); // now avoidervector contains S_n(patternlist) stored in avoidervector[n] for 0 < n < 11
void buildavoidersfrompatternlist(string patternlist, int maxpermsize, vector < vector < uint64_t > > &avoidervector) {
  int maxpatternsize;
  hashdb patternset = hashdb(1<<3);
  makepatterns(patternlist, patternset, maxpatternsize);
  vector < uint64_t > numavoiders;
  buildavoiders(patternset, maxpatternsize, maxpermsize, avoidervector, numavoiders, false, (1L << 10)); // for large cases, make last argument much larger!
}

// Example:
// string patternlist = "1234 3214"; // space separated list of patterns; need not be same sizes; must be in S_{<10}
// vector < uint64_t > numavoiders;
// buildavoidersfrompatternlist(patternlist, 10, numavoiders); // now avoidervector contains |S_n(patternlist)| stored in numavoiders[n] for 0 < n < 11.
void countavoidersfrompatternlist(string patternlist, int maxpermsize, vector < uint64_t > &numavoiders) {
  int maxpatternsize;
  hashdb patternset = hashdb(1<<3);
  makepatterns(patternlist, patternset, maxpatternsize);
  vector < vector < uint64_t > > avoidervector;
  buildavoiders(patternset, maxpatternsize, maxpermsize, avoidervector, numavoiders, true, (1L << 10)); // for large cases, make last argument much larger!
}

// Inputs file stream containing string list of patterns on each line.
// e.g., infile might contain
// 1234 312
// 231 4132 312
// Outputs file stream alternating every other line
// (1) #<list of patterns>
// (2) |S_1(list of patterns)| |S_2(list of patterns)| ... |S_maxpermsize(list of patterns)|
// e.g., output file might contain
// #1234 312
// 0 2 5 13 31 66 127 225 373 586
// #231 4132 312
// 0 2 4 8 16 32 64 128 256 512
void countavoidersfromfile(ifstream &infile, ofstream &outfile, int maxpermsize, bool verbose) {
  string line;
  while (getline(infile, line)) {
    outfile<<"#"<<line<<endl;
    if (verbose) cout<<line<<endl;
    vector < uint64_t > numavoiders;
    timestamp_t start_time = get_timestamp();
    countavoidersfrompatternlist(line, maxpermsize, numavoiders);
    timestamp_t end_time = get_timestamp();
    for (int i = 1; i < numavoiders.size(); i++) {
      if (verbose) cout<<numavoiders[i]<<" ";
      outfile<<numavoiders[i]<<" ";
    }
    if (verbose) cout<<endl;
    outfile<<endl;
    if (verbose) cout<< "Time elapsed (s): "<<(end_time - start_time)/1000000.0L<<endl;
  }
  cout<<(double)stat2/(double)stat3<<endl;
  return;
}
<|endoftext|>


<commit_before>/****************************************************************************
 *
 *   (c) 2009-2016 QGROUNDCONTROL PROJECT <http://www.qgroundcontrol.org>
 *
 * QGroundControl is licensed according to the terms in the file
 * COPYING.md in the root of the source code directory.
 *
 ****************************************************************************/

#include <QStringList>
#include <QDebug>

#include "RallyPoint.h"

const char* RallyPoint::_longitudeFactName =    "Longitude";
const char* RallyPoint::_latitudeFactName =     "Latitude";
const char* RallyPoint::_altitudeFactName =     "Altitude";

QMap<QString, FactMetaData*> RallyPoint::_metaDataMap;

RallyPoint::RallyPoint(const QGeoCoordinate& coordinate, QObject* parent)
    : QObject(parent)
    , _dirty(false)
    , _longitudeFact(0, _longitudeFactName, FactMetaData::valueTypeDouble)
    , _latitudeFact(0, _latitudeFactName, FactMetaData::valueTypeDouble)
    , _altitudeFact(0, _altitudeFactName, FactMetaData::valueTypeDouble)
{
    setCoordinate(coordinate);

    _factSetup();
}

RallyPoint::RallyPoint(const RallyPoint& other, QObject* parent)
    : QObject(parent)
    , _dirty(false)
    , _longitudeFact(0, _longitudeFactName, FactMetaData::valueTypeDouble)
    , _latitudeFact(0, _latitudeFactName, FactMetaData::valueTypeDouble)
    , _altitudeFact(0, _altitudeFactName, FactMetaData::valueTypeDouble)
{
    _longitudeFact.setRawValue(other._longitudeFact.rawValue());
    _latitudeFact.setRawValue(other._latitudeFact.rawValue());
    _altitudeFact.setRawValue(other._altitudeFact.rawValue());

    _factSetup();
}

const RallyPoint& RallyPoint::operator=(const RallyPoint& other)
{
    _longitudeFact.setRawValue(other._longitudeFact.rawValue());
    _latitudeFact.setRawValue(other._latitudeFact.rawValue());
    _altitudeFact.setRawValue(other._altitudeFact.rawValue());

    emit coordinateChanged(coordinate());

    return *this;
}

RallyPoint::~RallyPoint()
{

}

void RallyPoint::_factSetup(void)
{
    if (_metaDataMap.isEmpty()) {
        _metaDataMap = FactMetaData::createMapFromJsonFile(QStringLiteral(":/json/RallyPoint.json"), NULL /* metaDataParent */);
    }

    _longitudeFact.setMetaData(_metaDataMap[_longitudeFactName]);
    _latitudeFact.setMetaData(_metaDataMap[_latitudeFactName]);
    _altitudeFact.setMetaData(_metaDataMap[_altitudeFactName]);

    _textFieldFacts.append(QVariant::fromValue(&_longitudeFact));
    _textFieldFacts.append(QVariant::fromValue(&_latitudeFact));
    _textFieldFacts.append(QVariant::fromValue(&_altitudeFact));

    connect(&_longitudeFact, &Fact::valueChanged, this, &RallyPoint::_sendCoordinateChanged);
    connect(&_latitudeFact, &Fact::valueChanged, this, &RallyPoint::_sendCoordinateChanged);
    connect(&_altitudeFact, &Fact::valueChanged, this, &RallyPoint::_sendCoordinateChanged);
}

void RallyPoint::setCoordinate(const QGeoCoordinate& coordinate)
{
    if (coordinate != this->coordinate()) {
        _longitudeFact.setRawValue(coordinate.longitude());
        _latitudeFact.setRawValue(coordinate.latitude());
        _altitudeFact.setRawValue(coordinate.altitude());
        emit coordinateChanged(coordinate);
        setDirty(true);
    }
}

void RallyPoint::setDirty(bool dirty)
{
    if (dirty != _dirty) {
        _dirty = dirty;
        emit dirtyChanged(dirty);
    }
}

QGeoCoordinate RallyPoint::coordinate(void) const
{
    return QGeoCoordinate(_latitudeFact.rawValue().toDouble(), _longitudeFact.rawValue().toDouble(), _altitudeFact.rawValue().toDouble());
}

void RallyPoint::_sendCoordinateChanged(void)
{
    emit coordinateChanged(coordinate());
}
<commit_msg>Use GridLayout for better layout<commit_after>/****************************************************************************
 *
 *   (c) 2009-2016 QGROUNDCONTROL PROJECT <http://www.qgroundcontrol.org>
 *
 * QGroundControl is licensed according to the terms in the file
 * COPYING.md in the root of the source code directory.
 *
 ****************************************************************************/

#include <QStringList>
#include <QDebug>

#include "RallyPoint.h"

const char* RallyPoint::_longitudeFactName =    "Longitude";
const char* RallyPoint::_latitudeFactName =     "Latitude";
const char* RallyPoint::_altitudeFactName =     "Altitude";

QMap<QString, FactMetaData*> RallyPoint::_metaDataMap;

RallyPoint::RallyPoint(const QGeoCoordinate& coordinate, QObject* parent)
    : QObject(parent)
    , _dirty(false)
    , _longitudeFact(0, _longitudeFactName, FactMetaData::valueTypeDouble)
    , _latitudeFact(0, _latitudeFactName, FactMetaData::valueTypeDouble)
    , _altitudeFact(0, _altitudeFactName, FactMetaData::valueTypeDouble)
{
    setCoordinate(coordinate);

    _factSetup();
}

RallyPoint::RallyPoint(const RallyPoint& other, QObject* parent)
    : QObject(parent)
    , _dirty(false)
    , _longitudeFact(0, _longitudeFactName, FactMetaData::valueTypeDouble)
    , _latitudeFact(0, _latitudeFactName, FactMetaData::valueTypeDouble)
    , _altitudeFact(0, _altitudeFactName, FactMetaData::valueTypeDouble)
{
    _longitudeFact.setRawValue(other._longitudeFact.rawValue());
    _latitudeFact.setRawValue(other._latitudeFact.rawValue());
    _altitudeFact.setRawValue(other._altitudeFact.rawValue());

    _factSetup();
}

const RallyPoint& RallyPoint::operator=(const RallyPoint& other)
{
    _longitudeFact.setRawValue(other._longitudeFact.rawValue());
    _latitudeFact.setRawValue(other._latitudeFact.rawValue());
    _altitudeFact.setRawValue(other._altitudeFact.rawValue());

    emit coordinateChanged(coordinate());

    return *this;
}

RallyPoint::~RallyPoint()
{

}

void RallyPoint::_factSetup(void)
{
    if (_metaDataMap.isEmpty()) {
        _metaDataMap = FactMetaData::createMapFromJsonFile(QStringLiteral(":/json/RallyPoint.FactMetaData.json"), NULL /* metaDataParent */);
    }

    _longitudeFact.setMetaData(_metaDataMap[_longitudeFactName]);
    _latitudeFact.setMetaData(_metaDataMap[_latitudeFactName]);
    _altitudeFact.setMetaData(_metaDataMap[_altitudeFactName]);

    _textFieldFacts.append(QVariant::fromValue(&_longitudeFact));
    _textFieldFacts.append(QVariant::fromValue(&_latitudeFact));
    _textFieldFacts.append(QVariant::fromValue(&_altitudeFact));

    connect(&_longitudeFact, &Fact::valueChanged, this, &RallyPoint::_sendCoordinateChanged);
    connect(&_latitudeFact, &Fact::valueChanged, this, &RallyPoint::_sendCoordinateChanged);
    connect(&_altitudeFact, &Fact::valueChanged, this, &RallyPoint::_sendCoordinateChanged);
}

void RallyPoint::setCoordinate(const QGeoCoordinate& coordinate)
{
    if (coordinate != this->coordinate()) {
        _longitudeFact.setRawValue(coordinate.longitude());
        _latitudeFact.setRawValue(coordinate.latitude());
        _altitudeFact.setRawValue(coordinate.altitude());
        emit coordinateChanged(coordinate);
        setDirty(true);
    }
}

void RallyPoint::setDirty(bool dirty)
{
    if (dirty != _dirty) {
        _dirty = dirty;
        emit dirtyChanged(dirty);
    }
}

QGeoCoordinate RallyPoint::coordinate(void) const
{
    return QGeoCoordinate(_latitudeFact.rawValue().toDouble(), _longitudeFact.rawValue().toDouble(), _altitudeFact.rawValue().toDouble());
}

void RallyPoint::_sendCoordinateChanged(void)
{
    emit coordinateChanged(coordinate());
}
<|endoftext|>


<commit_before>/*
Copyright 2016 Andreas Bjerkeholt

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

#include "Label.h"
#include <SDL.h>
#include "../graphics_utils.h"
#include <sstream>
#include <limits.h>
#include "../ScreenSystem/Screen.h"

using namespace std;

Label::Label()
{
	texture = NULL;
	text = "";
	textSize = 12;
	textColor = Color(0xff, 0xff, 0xff, 0xff);
	font = "semibold";
	ttfFont = NULL;
}

Label::~Label()
{
	if (texture != NULL)
		SDL_DestroyTexture(texture);
}

bool Label::OnInitialize()
{
	ttfFont = context->GetResourceManager()->GetTTFFont(font, textSize);

	if (ttfFont == NULL)
		return false;

	if (!RenderText(UINT_MAX))
		return false;

	return true;
}

bool Label::RenderText(Uint32 textAreaWidth)
{
	if (ttfFont == NULL)
		return false;

	if (texture != NULL)
		SDL_DestroyTexture(texture);

	texture = NULL;

	SDL_Color color;
	color.r = 0xff;
	color.g = 0xff;
	color.b = 0xff;
	color.a = 0xff;
	SDL_Surface* tempSurface = TTF_RenderText_Blended_Wrapped(ttfFont, text.c_str(), color, textAreaWidth);
	if (tempSurface == NULL)
		return false;

	SDL_Surface* clippedSurface = NULL;

	int areaWidth = size.w;
	if (size.w == SIZE_FILL_PARENT)
		areaWidth = calculatedSize.w;
	else if (size.w == SIZE_WRAP_CONTENT)
		areaWidth = tempSurface->w;

	if (areaWidth > 0 && tempSurface->w > areaWidth)
	{
		SDL_Rect r;
		r.x = 0;
		r.y = 0;
		r.w = areaWidth;
		r.h = tempSurface->h;
		clippedSurface = ClipSurface(tempSurface, &r);

		SDL_FreeSurface(tempSurface);

		// Apply alpha fadeout at end if text doesn't fit completely
		FadeOutSurface(clippedSurface, 16);
	}
	else
	{
		clippedSurface = tempSurface;
	}

	if (clippedSurface == NULL)
		return false;

	texture = SDL_CreateTextureFromSurface(context->GetRenderer(), clippedSurface);
	SDL_FreeSurface(clippedSurface);
	if (texture == NULL)
		return false;

	SDL_QueryTexture(texture, NULL, NULL, &contentSize.w, &contentSize.h);

	return true;
}

void Label::OnDraw(SDL_Renderer* renderer, Position offset)
{
	if (texture == NULL)
		return;

	SDL_Rect r;
	r.x = absolutePosition.x + offset.x;
	r.y = absolutePosition.y + offset.y;
	r.w = contentSize.w;
	r.h = contentSize.h;

	Position gravityOffset = GetGravityOffset(contentSize, calculatedSize, gravity);
	r.x += gravityOffset.x;
	r.y += gravityOffset.y;

	SDL_SetTextureColorMod(texture, textColor.r, textColor.g, textColor.b);

	drawTexture(&r, texture, renderer);
}

void Label::OnLayoutChange()
{
	if (size.w == SIZE_FILL_PARENT || size.h == SIZE_FILL_PARENT)
		RenderText(UINT_MAX);
}

View* Label::Copy()
{
	Label* view = new Label();

	CopyBase(view);
	view->SetText(text);
	view->SetTextSize(textSize);
	view->SetTextColor(textColor);
	view->SetFont(font);

	return view;
}

string Label::GetText()
{
	return text;
}

void Label::SetText(string text)
{
	this->text = text;

	if (IsInitialized())
	{
		RenderText(UINT_MAX);

		if (size.w == SIZE_WRAP_CONTENT || size.h == SIZE_WRAP_CONTENT)
		{
			View* parent = GetParentView();
			if (parent != NULL)
				parent->RecalculateLayout();
		}
	}
}

int Label::GetTextSize()
{
	return textSize;
}

void Label::SetTextSize(int textSize)
{
	this->textSize = textSize;
}

Color Label::GetTextColor()
{
	return textColor;
}

void Label::SetTextColor(Color textColor)
{
	this->textColor = textColor;
}

string Label::GetFont()
{
	return font;
}

void Label::SetFont(string font)
{
	this->font = font;
}

bool Label::SetProperty(string name, string value)
{
	bool propertyHandled = View::SetProperty(name, value);

	if (propertyHandled)
		return true;

	if (name == "text")
	{
		SetText(value);
		return true;
	}
	else if (name == "textSize")
	{
		textSize = atoi(value.c_str());

		if (textSize <= 0)
			throw runtime_error("invalid textSize value");

		return true;
	}
	else if (name == "textColor")
	{
		if (value.length() != 7 || value[0] != '#')
			throw runtime_error("invalid textColor value");

		istringstream(value.substr(1, 2)) >> std::hex >> textColor.r;
		istringstream(value.substr(3, 2)) >> std::hex >> textColor.g;
		istringstream(value.substr(5, 2)) >> std::hex >> textColor.b;

		return true;
	}
	else if (name == "font")
	{
		font = value;
		return true;
	}

	return false;
}

void Label::FillData(map<string, string>& data)
{
	text = FindAndReplace(text, data);

	if (IsInitialized())
	{
		RenderText(UINT_MAX);
		RecalculateLayout();
	}
}
<commit_msg>Use general function to parse color in Label<commit_after>/*
Copyright 2016 Andreas Bjerkeholt

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

#include "Label.h"
#include <SDL.h>
#include "../graphics_utils.h"
#include <sstream>
#include <limits.h>
#include "../ScreenSystem/Screen.h"

using namespace std;

Label::Label()
{
	texture = NULL;
	text = "";
	textSize = 12;
	textColor = Color(0xff, 0xff, 0xff, 0xff);
	font = "semibold";
	ttfFont = NULL;
}

Label::~Label()
{
	if (texture != NULL)
		SDL_DestroyTexture(texture);
}

bool Label::OnInitialize()
{
	ttfFont = context->GetResourceManager()->GetTTFFont(font, textSize);

	if (ttfFont == NULL)
		return false;

	if (!RenderText(UINT_MAX))
		return false;

	return true;
}

bool Label::RenderText(Uint32 textAreaWidth)
{
	if (ttfFont == NULL)
		return false;

	if (texture != NULL)
		SDL_DestroyTexture(texture);

	texture = NULL;

	SDL_Color color;
	color.r = 0xff;
	color.g = 0xff;
	color.b = 0xff;
	color.a = 0xff;
	SDL_Surface* tempSurface = TTF_RenderText_Blended_Wrapped(ttfFont, text.c_str(), color, textAreaWidth);
	if (tempSurface == NULL)
		return false;

	SDL_Surface* clippedSurface = NULL;

	int areaWidth = size.w;
	if (size.w == SIZE_FILL_PARENT)
		areaWidth = calculatedSize.w;
	else if (size.w == SIZE_WRAP_CONTENT)
		areaWidth = tempSurface->w;

	if (areaWidth > 0 && tempSurface->w > areaWidth)
	{
		SDL_Rect r;
		r.x = 0;
		r.y = 0;
		r.w = areaWidth;
		r.h = tempSurface->h;
		clippedSurface = ClipSurface(tempSurface, &r);

		SDL_FreeSurface(tempSurface);

		// Apply alpha fadeout at end if text doesn't fit completely
		FadeOutSurface(clippedSurface, 16);
	}
	else
	{
		clippedSurface = tempSurface;
	}

	if (clippedSurface == NULL)
		return false;

	texture = SDL_CreateTextureFromSurface(context->GetRenderer(), clippedSurface);
	SDL_FreeSurface(clippedSurface);
	if (texture == NULL)
		return false;

	SDL_QueryTexture(texture, NULL, NULL, &contentSize.w, &contentSize.h);

	return true;
}

void Label::OnDraw(SDL_Renderer* renderer, Position offset)
{
	if (texture == NULL)
		return;

	SDL_Rect r;
	r.x = absolutePosition.x + offset.x;
	r.y = absolutePosition.y + offset.y;
	r.w = contentSize.w;
	r.h = contentSize.h;

	Position gravityOffset = GetGravityOffset(contentSize, calculatedSize, gravity);
	r.x += gravityOffset.x;
	r.y += gravityOffset.y;

	SDL_SetTextureColorMod(texture, textColor.r, textColor.g, textColor.b);

	drawTexture(&r, texture, renderer);
}

void Label::OnLayoutChange()
{
	if (size.w == SIZE_FILL_PARENT || size.h == SIZE_FILL_PARENT)
		RenderText(UINT_MAX);
}

View* Label::Copy()
{
	Label* view = new Label();

	CopyBase(view);
	view->SetText(text);
	view->SetTextSize(textSize);
	view->SetTextColor(textColor);
	view->SetFont(font);

	return view;
}

string Label::GetText()
{
	return text;
}

void Label::SetText(string text)
{
	this->text = text;

	if (IsInitialized())
	{
		RenderText(UINT_MAX);

		if (size.w == SIZE_WRAP_CONTENT || size.h == SIZE_WRAP_CONTENT)
		{
			View* parent = GetParentView();
			if (parent != NULL)
				parent->RecalculateLayout();
		}
	}
}

int Label::GetTextSize()
{
	return textSize;
}

void Label::SetTextSize(int textSize)
{
	this->textSize = textSize;
}

Color Label::GetTextColor()
{
	return textColor;
}

void Label::SetTextColor(Color textColor)
{
	this->textColor = textColor;
}

string Label::GetFont()
{
	return font;
}

void Label::SetFont(string font)
{
	this->font = font;
}

bool Label::SetProperty(string name, string value)
{
	bool propertyHandled = View::SetProperty(name, value);

	if (propertyHandled)
		return true;

	if (name == "text")
	{
		SetText(value);
		return true;
	}
	else if (name == "textSize")
	{
		textSize = atoi(value.c_str());

		if (textSize <= 0)
			throw runtime_error("invalid textSize value");

		return true;
	}
	else if (name == "textColor")
	{
		this->textColor = ParseColor(value);
		return true;
	}
	else if (name == "font")
	{
		font = value;
		return true;
	}

	return false;
}

void Label::FillData(map<string, string>& data)
{
	text = FindAndReplace(text, data);

	if (IsInitialized())
	{
		RenderText(UINT_MAX);
		RecalculateLayout();
	}
}
<|endoftext|>


<commit_before>#include <gtest/gtest.h>
#include <mlfe/core.h>
#include <mlfe/operators.h>

using namespace mlfe;
namespace fn = functional;

TEST(unary_op, negative){
    using T = float;
    auto var = fn::create_variable({2, 2});
    auto result = fn::negative(var);
    var.mutable_data<T>()[0] = -1.35;
    var.mutable_data<T>()[1] = 357.5;
    var.mutable_data<T>()[2] = -3.5;
    var.mutable_data<T>()[3] = 3.15;
    result.eval();
    EXPECT_EQ(result.data<T>()[0], -var.data<T>()[0]);
    EXPECT_EQ(result.data<T>()[1], -var.data<T>()[1]);
    EXPECT_EQ(result.data<T>()[2], -var.data<T>()[2]);
    EXPECT_EQ(result.data<T>()[3], -var.data<T>()[3]);
}

TEST(unary_op, sigmoid){
    using T = float;
    auto var = fn::create_variable({2, 2});
    auto result = fn::sigmoid(var);
    var.mutable_data<T>()[0] = 0;
    var.mutable_data<T>()[1] = -0.5;
    var.mutable_data<T>()[2] = 0.5;
    var.mutable_data<T>()[3] = 1;
    result.eval();
    EXPECT_EQ(result.data<T>()[0], 0.5);

    EXPECT_LE(result.data<T>()[1], 0.3775 + 1e-4);
    EXPECT_GE(result.data<T>()[1], 0.3775 - 1e-4);

    EXPECT_LE(result.data<T>()[2], 0.6225 + 1e-4);
    EXPECT_GE(result.data<T>()[2], 0.6225 - 1e-4);

    EXPECT_LE(result.data<T>()[3], 0.7311 + 1e-4);
    EXPECT_GE(result.data<T>()[3], 0.7311 - 1e-4);
}

TEST(unary_op, relu){
    using T = float;
    auto var = fn::create_variable({2, 2});
    auto result = fn::relu(var);
    var.mutable_data<T>()[0] = -1.35;
    var.mutable_data<T>()[1] = 357.5;
    var.mutable_data<T>()[2] = -3.5;
    var.mutable_data<T>()[3] = 3.15;
    result.eval();
    EXPECT_EQ(result.data<T>()[0], 0);
    EXPECT_EQ(result.data<T>()[1], var.data<T>()[1]);
    EXPECT_EQ(result.data<T>()[2], 0);
    EXPECT_EQ(result.data<T>()[3], var.data<T>()[3]);
}<commit_msg>add gradient unit test as below: grad of negative op. grad of sigmoid op. grad of relu op.<commit_after>#include <gtest/gtest.h>
#include <mlfe/core.h>
#include <mlfe/operators.h>
#include <mlfe/utils/gradient_checker.h>
#include <random>

using namespace mlfe;
namespace fn = functional;

TEST(unary_op, negative){
    using T = float;
    auto var = fn::create_variable({2, 2});
    auto result = fn::negative(var);
    var.mutable_data<T>()[0] = -1.35;
    var.mutable_data<T>()[1] = 357.5;
    var.mutable_data<T>()[2] = -3.5;
    var.mutable_data<T>()[3] = 3.15;
    result.eval();
    EXPECT_EQ(result.data<T>()[0], -var.data<T>()[0]);
    EXPECT_EQ(result.data<T>()[1], -var.data<T>()[1]);
    EXPECT_EQ(result.data<T>()[2], -var.data<T>()[2]);
    EXPECT_EQ(result.data<T>()[3], -var.data<T>()[3]);
}

TEST(unary_op, negative_grad){
    using T = float;
    constexpr T grad_eps = 1e-4;
    constexpr T pass_eps = 1e-3;
    auto var = fn::create_variable({2, 2});
    auto result = fn::negative(var);
    auto analytical = std::vector<T>(var.size());
    std::mt19937 rng;
    std::uniform_real_distribution<T> dist(-1, 1);

    std::generate(var.begin<T>(), var.end<T>(), [&rng, &dist](){
        return dist(rng);
    });
    result.eval();
    result.backprop();
    std::copy(var.grad().begin<T>(), var.grad().end<T>(), analytical.begin());
    auto numerical = numerical_gradient(grad_eps, result, var);

    for(int n = 0; n < var.size(); ++n){
        auto diff = std::abs(analytical.data()[n] - numerical.data<T>()[n]);
        EXPECT_LE(diff, pass_eps);
        EXPECT_GE(diff, -pass_eps);
    }
}

TEST(unary_op, sigmoid){
    using T = float;
    auto var = fn::create_variable({2, 2});
    auto result = fn::sigmoid(var);
    var.mutable_data<T>()[0] = 0;
    var.mutable_data<T>()[1] = -0.5;
    var.mutable_data<T>()[2] = 0.5;
    var.mutable_data<T>()[3] = 1;
    result.eval();
    EXPECT_EQ(result.data<T>()[0], 0.5);

    EXPECT_LE(result.data<T>()[1], 0.3775 + 1e-4);
    EXPECT_GE(result.data<T>()[1], 0.3775 - 1e-4);

    EXPECT_LE(result.data<T>()[2], 0.6225 + 1e-4);
    EXPECT_GE(result.data<T>()[2], 0.6225 - 1e-4);

    EXPECT_LE(result.data<T>()[3], 0.7311 + 1e-4);
    EXPECT_GE(result.data<T>()[3], 0.7311 - 1e-4);
}

TEST(unary_op, sigmoid_grad){
    using T = float;
    constexpr T grad_eps = 1e-4;
    constexpr T pass_eps = 1e-3;
    auto var = fn::create_variable({2, 2});
    auto result = fn::sigmoid(var);
    auto analytical = std::vector<T>(var.size());
    std::mt19937 rng;
    std::uniform_real_distribution<T> dist(-1, 1);
    rng.seed(std::random_device()());

    std::generate(var.begin<T>(), var.end<T>(), [&rng, &dist](){
        return dist(rng);
    });
    result.eval();
    result.backprop();
    std::copy(var.grad().begin<T>(), var.grad().end<T>(), analytical.begin());
    auto numerical = numerical_gradient(grad_eps, result, var);

    for(int n = 0; n < var.size(); ++n){
        auto diff = std::abs(analytical.data()[n] - numerical.data<T>()[n]);
        EXPECT_LE(diff, pass_eps);
        EXPECT_GE(diff, -pass_eps);
    }
}

TEST(unary_op, relu){
    using T = float;
    auto var = fn::create_variable({2, 2});
    auto result = fn::relu(var);
    var.mutable_data<T>()[0] = -1.35;
    var.mutable_data<T>()[1] = 357.5;
    var.mutable_data<T>()[2] = -3.5;
    var.mutable_data<T>()[3] = 3.15;
    result.eval();
    EXPECT_EQ(result.data<T>()[0], 0);
    EXPECT_EQ(result.data<T>()[1], var.data<T>()[1]);
    EXPECT_EQ(result.data<T>()[2], 0);
    EXPECT_EQ(result.data<T>()[3], var.data<T>()[3]);
}

TEST(unary_op, relu_grad){
    using T = float;
    constexpr T grad_eps = 1e-4;
    constexpr T pass_eps = 1e-3;
    auto var = fn::create_variable({2, 2});
    auto result = fn::relu(var);
    auto analytical = std::vector<T>(var.size());
    std::mt19937 rng;
    std::uniform_real_distribution<T> dist(-1, 1);

    std::generate(var.begin<T>(), var.end<T>(), [&rng, &dist](){
        return dist(rng);
    });
    result.eval();
    result.backprop();
    std::copy(var.grad().begin<T>(), var.grad().end<T>(), analytical.begin());
    auto numerical = numerical_gradient(grad_eps, result, var);

    for(int n = 0; n < var.size(); ++n){
        auto diff = std::abs(analytical.data()[n] - numerical.data<T>()[n]);
        EXPECT_LE(diff, pass_eps);
        EXPECT_GE(diff, -pass_eps);
    }
}
<|endoftext|>


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

#ifndef _COM_SUN_STAR_AWT_RECTANGLE_HPP_
#include <com/sun/star/awt/Rectangle.hpp>
#endif

#ifndef _XMLOFF_VISAREAEXPORT_HXX
#include "VisAreaExport.hxx"
#endif
#ifndef _XMLOFF_XMLEXP_HXX
#include "xmlexp.hxx"
#endif

#ifndef _XMLOFF_XMLNMSPE_HXX
#include "xmlnmspe.hxx"
#endif

#ifndef _XMLOFF_NMSPMAP_HXX
#include "nmspmap.hxx"
#endif

#ifndef _XMLOFF_XMLTOKEN_HXX
#include "xmltoken.hxx"
#endif

#ifndef _XMLOFF_XMLUCONV_HXX
#include "xmluconv.hxx"
#endif

#ifndef _SV_GEN_HXX
#include <tools/gen.hxx>
#endif

using namespace ::xmloff::token;

XMLVisAreaExport::XMLVisAreaExport(SvXMLExport& rExport, const sal_Char *pName,
                            const Rectangle& aRect, const MapUnit aMapUnit)
{
    SvXMLUnitConverter& rUnitConv = rExport.GetMM100UnitConverter();

    // write VisArea Element and its Attributes
    rtl::OUStringBuffer sBuffer;
    rUnitConv.convertMeasure(sBuffer, aRect.getX(), aMapUnit);
    rExport.AddAttribute(XML_NAMESPACE_OFFICE, XML_X, sBuffer.makeStringAndClear());
    rUnitConv.convertMeasure(sBuffer, aRect.getY(), aMapUnit);
    rExport.AddAttribute(XML_NAMESPACE_OFFICE, XML_Y, sBuffer.makeStringAndClear());
    rUnitConv.convertMeasure(sBuffer, aRect.getWidth(), aMapUnit);
    rExport.AddAttribute(XML_NAMESPACE_OFFICE, XML_WIDTH, sBuffer.makeStringAndClear());
    rUnitConv.convertMeasure(sBuffer, aRect.getHeight(), aMapUnit);
    rExport.AddAttribute(XML_NAMESPACE_OFFICE, XML_HEIGHT, sBuffer.makeStringAndClear());
    SvXMLElementExport aVisAreaElem(rExport, XML_NAMESPACE_OFFICE, pName, sal_True, sal_True);
}

XMLVisAreaExport::XMLVisAreaExport(SvXMLExport& rExport, const sal_Char *pName,
                                   const com::sun::star::awt::Rectangle& aRect, const sal_Int16 nMeasureUnit )
{
    MapUnit aMapUnit = (MapUnit)nMeasureUnit;

    SvXMLUnitConverter& rUnitConv = rExport.GetMM100UnitConverter();

    // write VisArea Element and its Attributes
    rtl::OUStringBuffer sBuffer;
    rUnitConv.convertMeasure(sBuffer, aRect.X, aMapUnit);
    rExport.AddAttribute(XML_NAMESPACE_OFFICE, XML_X, sBuffer.makeStringAndClear());
    rUnitConv.convertMeasure(sBuffer, aRect.Y, aMapUnit);
    rExport.AddAttribute(XML_NAMESPACE_OFFICE, XML_Y, sBuffer.makeStringAndClear());
    rUnitConv.convertMeasure(sBuffer, aRect.Width, aMapUnit);
    rExport.AddAttribute(XML_NAMESPACE_OFFICE, XML_WIDTH, sBuffer.makeStringAndClear());
    rUnitConv.convertMeasure(sBuffer, aRect.Height, aMapUnit);
    rExport.AddAttribute(XML_NAMESPACE_OFFICE, XML_HEIGHT, sBuffer.makeStringAndClear());
    SvXMLElementExport aVisAreaElem(rExport, XML_NAMESPACE_OFFICE, pName, sal_True, sal_True);
}

XMLVisAreaExport::~XMLVisAreaExport()
{
}

<commit_msg>INTEGRATION: CWS ooo19126 (1.3.636); FILE MERGED 2005/09/05 14:39:16 rt 1.3.636.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: VisAreaExport.cxx,v $
 *
 *  $Revision: 1.4 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-09 14:30:46 $
 *
 *  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 _COM_SUN_STAR_AWT_RECTANGLE_HPP_
#include <com/sun/star/awt/Rectangle.hpp>
#endif

#ifndef _XMLOFF_VISAREAEXPORT_HXX
#include "VisAreaExport.hxx"
#endif
#ifndef _XMLOFF_XMLEXP_HXX
#include "xmlexp.hxx"
#endif

#ifndef _XMLOFF_XMLNMSPE_HXX
#include "xmlnmspe.hxx"
#endif

#ifndef _XMLOFF_NMSPMAP_HXX
#include "nmspmap.hxx"
#endif

#ifndef _XMLOFF_XMLTOKEN_HXX
#include "xmltoken.hxx"
#endif

#ifndef _XMLOFF_XMLUCONV_HXX
#include "xmluconv.hxx"
#endif

#ifndef _SV_GEN_HXX
#include <tools/gen.hxx>
#endif

using namespace ::xmloff::token;

XMLVisAreaExport::XMLVisAreaExport(SvXMLExport& rExport, const sal_Char *pName,
                            const Rectangle& aRect, const MapUnit aMapUnit)
{
    SvXMLUnitConverter& rUnitConv = rExport.GetMM100UnitConverter();

    // write VisArea Element and its Attributes
    rtl::OUStringBuffer sBuffer;
    rUnitConv.convertMeasure(sBuffer, aRect.getX(), aMapUnit);
    rExport.AddAttribute(XML_NAMESPACE_OFFICE, XML_X, sBuffer.makeStringAndClear());
    rUnitConv.convertMeasure(sBuffer, aRect.getY(), aMapUnit);
    rExport.AddAttribute(XML_NAMESPACE_OFFICE, XML_Y, sBuffer.makeStringAndClear());
    rUnitConv.convertMeasure(sBuffer, aRect.getWidth(), aMapUnit);
    rExport.AddAttribute(XML_NAMESPACE_OFFICE, XML_WIDTH, sBuffer.makeStringAndClear());
    rUnitConv.convertMeasure(sBuffer, aRect.getHeight(), aMapUnit);
    rExport.AddAttribute(XML_NAMESPACE_OFFICE, XML_HEIGHT, sBuffer.makeStringAndClear());
    SvXMLElementExport aVisAreaElem(rExport, XML_NAMESPACE_OFFICE, pName, sal_True, sal_True);
}

XMLVisAreaExport::XMLVisAreaExport(SvXMLExport& rExport, const sal_Char *pName,
                                   const com::sun::star::awt::Rectangle& aRect, const sal_Int16 nMeasureUnit )
{
    MapUnit aMapUnit = (MapUnit)nMeasureUnit;

    SvXMLUnitConverter& rUnitConv = rExport.GetMM100UnitConverter();

    // write VisArea Element and its Attributes
    rtl::OUStringBuffer sBuffer;
    rUnitConv.convertMeasure(sBuffer, aRect.X, aMapUnit);
    rExport.AddAttribute(XML_NAMESPACE_OFFICE, XML_X, sBuffer.makeStringAndClear());
    rUnitConv.convertMeasure(sBuffer, aRect.Y, aMapUnit);
    rExport.AddAttribute(XML_NAMESPACE_OFFICE, XML_Y, sBuffer.makeStringAndClear());
    rUnitConv.convertMeasure(sBuffer, aRect.Width, aMapUnit);
    rExport.AddAttribute(XML_NAMESPACE_OFFICE, XML_WIDTH, sBuffer.makeStringAndClear());
    rUnitConv.convertMeasure(sBuffer, aRect.Height, aMapUnit);
    rExport.AddAttribute(XML_NAMESPACE_OFFICE, XML_HEIGHT, sBuffer.makeStringAndClear());
    SvXMLElementExport aVisAreaElem(rExport, XML_NAMESPACE_OFFICE, pName, sal_True, sal_True);
}

XMLVisAreaExport::~XMLVisAreaExport()
{
}

<|endoftext|>


<commit_before>#include "helpclass.h"

HelpClass::HelpClass()
{
}

HelpClass::~HelpClass()
{
}

<commit_msg>Added serialize and deserialize members to serialization object<commit_after>#include "helpclass.h"

HelpClass::HelpClass()
{
}

HelpClass::~HelpClass()
{
}

void HelpClass::Serialize(const Serializator &s)
{

}

NObject *HelpClass::Deserialize(const Serializator &s)
{

}

<|endoftext|>


<commit_before><commit_msg>button colour change success<commit_after><|endoftext|>


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

#include <wangle/channel/FileRegion.h>
#include <folly/io/async/test/AsyncSocketTest.h>
#include <folly/portability/GTest.h>

#ifdef SPLICE_F_NONBLOCK
using namespace folly;
using namespace wangle;
using namespace testing;

struct FileRegionTest : public Test {
  FileRegionTest() {
    // Connect
    socket = AsyncSocket::newSocket(&evb);
    socket->connect(&ccb, server.getAddress(), 30);

    // Accept the connection
    acceptedSocket = server.acceptAsync(&evb);
    acceptedSocket->setReadCB(&rcb);

    // Create temp file
    char path[] = "/tmp/AsyncSocketTest.WriteFile.XXXXXX";
    fd = mkostemp(path, O_RDWR);
    EXPECT_TRUE(fd > 0);
    EXPECT_EQ(0, unlink(path));
  }

  ~FileRegionTest() override {
    // Close up shop
    close(fd);
    acceptedSocket->close();
    socket->close();
  }

  TestServer server;
  EventBase evb;
  std::shared_ptr<AsyncSocket> socket;
  std::shared_ptr<AsyncSocket> acceptedSocket;
  ConnCallback ccb;
  ReadCallback rcb;
  int fd;
};

TEST_F(FileRegionTest, Basic) {
  const size_t count = 1000000000; // 1 GB
  std::unique_ptr<uint8_t[]> zeroBuf = std::make_unique<uint8_t[]>(count);
  write(fd, zeroBuf.get(), count);

  FileRegion fileRegion(fd, 0, count);
  auto f = fileRegion.transferTo(socket);
  try {
    f.getVia(&evb);
  } catch (std::exception& e) {
    LOG(FATAL) << exceptionStr(e);
  }

  // Let the reads run to completion
  socket->shutdownWrite();
  evb.loopIgnoreKeepAlive();

  ASSERT_EQ(rcb.state, STATE_SUCCEEDED);

  size_t receivedBytes = 0;
  for (auto& buf : rcb.buffers) {
    receivedBytes += buf.length;
    ASSERT_EQ(memcmp(buf.buffer, zeroBuf.get(), buf.length), 0);
  }
  ASSERT_EQ(receivedBytes, count);
}

TEST_F(FileRegionTest, Repeated) {
  const size_t count = 1000000;
  std::unique_ptr<uint8_t[]> zeroBuf = std::make_unique<uint8_t[]>(count);
  write(fd, zeroBuf.get(), count);

  int sendCount = 1000;

  FileRegion fileRegion(fd, 0, count);
  std::vector<Future<Unit>> fs;
  for (int i = 0; i < sendCount; i++) {
    fs.push_back(fileRegion.transferTo(socket));
  }
  auto f = collectSemiFuture(fs).via(&evb);
  ASSERT_NO_THROW(f.getVia(&evb));

  // Let the reads run to completion
  socket->shutdownWrite();
  evb.loopIgnoreKeepAlive();

  ASSERT_EQ(rcb.state, STATE_SUCCEEDED);

  size_t receivedBytes = 0;
  for (auto& buf : rcb.buffers) {
    receivedBytes += buf.length;
  }
  ASSERT_EQ(receivedBytes, sendCount*count);
}
#endif
<commit_msg>Rename collectXSemiFuture to collectX<commit_after>/*
 * Copyright (c) Facebook, Inc. and its affiliates.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include <wangle/channel/FileRegion.h>
#include <folly/io/async/test/AsyncSocketTest.h>
#include <folly/portability/GTest.h>

#ifdef SPLICE_F_NONBLOCK
using namespace folly;
using namespace wangle;
using namespace testing;

struct FileRegionTest : public Test {
  FileRegionTest() {
    // Connect
    socket = AsyncSocket::newSocket(&evb);
    socket->connect(&ccb, server.getAddress(), 30);

    // Accept the connection
    acceptedSocket = server.acceptAsync(&evb);
    acceptedSocket->setReadCB(&rcb);

    // Create temp file
    char path[] = "/tmp/AsyncSocketTest.WriteFile.XXXXXX";
    fd = mkostemp(path, O_RDWR);
    EXPECT_TRUE(fd > 0);
    EXPECT_EQ(0, unlink(path));
  }

  ~FileRegionTest() override {
    // Close up shop
    close(fd);
    acceptedSocket->close();
    socket->close();
  }

  TestServer server;
  EventBase evb;
  std::shared_ptr<AsyncSocket> socket;
  std::shared_ptr<AsyncSocket> acceptedSocket;
  ConnCallback ccb;
  ReadCallback rcb;
  int fd;
};

TEST_F(FileRegionTest, Basic) {
  const size_t count = 1000000000; // 1 GB
  std::unique_ptr<uint8_t[]> zeroBuf = std::make_unique<uint8_t[]>(count);
  write(fd, zeroBuf.get(), count);

  FileRegion fileRegion(fd, 0, count);
  auto f = fileRegion.transferTo(socket);
  try {
    f.getVia(&evb);
  } catch (std::exception& e) {
    LOG(FATAL) << exceptionStr(e);
  }

  // Let the reads run to completion
  socket->shutdownWrite();
  evb.loopIgnoreKeepAlive();

  ASSERT_EQ(rcb.state, STATE_SUCCEEDED);

  size_t receivedBytes = 0;
  for (auto& buf : rcb.buffers) {
    receivedBytes += buf.length;
    ASSERT_EQ(memcmp(buf.buffer, zeroBuf.get(), buf.length), 0);
  }
  ASSERT_EQ(receivedBytes, count);
}

TEST_F(FileRegionTest, Repeated) {
  const size_t count = 1000000;
  std::unique_ptr<uint8_t[]> zeroBuf = std::make_unique<uint8_t[]>(count);
  write(fd, zeroBuf.get(), count);

  int sendCount = 1000;

  FileRegion fileRegion(fd, 0, count);
  std::vector<Future<Unit>> fs;
  for (int i = 0; i < sendCount; i++) {
    fs.push_back(fileRegion.transferTo(socket));
  }
  auto f = collect(fs).via(&evb);
  ASSERT_NO_THROW(f.getVia(&evb));

  // Let the reads run to completion
  socket->shutdownWrite();
  evb.loopIgnoreKeepAlive();

  ASSERT_EQ(rcb.state, STATE_SUCCEEDED);

  size_t receivedBytes = 0;
  for (auto& buf : rcb.buffers) {
    receivedBytes += buf.length;
  }
  ASSERT_EQ(receivedBytes, sendCount*count);
}
#endif
<|endoftext|>


<commit_before>#include "sodiumpp.h"
#include <string>
#include <iostream>
using namespace sodiumpp;

int main(int argc, const char ** argv) {
    secret_key sk_client;
    secret_key sk_server;

    // Create a nonce type that has a 32-bit sequential counter and constant random bytes for the remaining bytes
    typedef nonce<crypto_box_NONCEBYTES-4, 4> nonce32;

    boxer<nonce32> client_boxer(sk_server.pk, sk_client);
    unboxer<nonce32> server_unboxer(sk_client.pk, sk_server, client_boxer.nonce_constant());

    std::string boxed = client_boxer.box("Hello, world!\n");
    std::string unboxed = server_unboxer.unbox(boxed);
    std::cout << unboxed;

    boxed = client_boxer.box("From sodiumpp!\n");
    unboxed = server_unboxer.unbox(boxed);
    std::cout << unboxed;
    return 0;
}
<commit_msg>Added copyright header to example<commit_after>//  example.cpp
//
// Copyright (c) 2014, Ruben De Visscher
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
// 2. 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.
//
// 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 "sodiumpp.h"
#include <string>
#include <iostream>
using namespace sodiumpp;

int main(int argc, const char ** argv) {
    secret_key sk_client;
    secret_key sk_server;

    // Create a nonce type that has a 32-bit sequential counter and constant random bytes for the remaining bytes
    typedef nonce<crypto_box_NONCEBYTES-4, 4> nonce32;

    boxer<nonce32> client_boxer(sk_server.pk, sk_client);
    unboxer<nonce32> server_unboxer(sk_client.pk, sk_server, client_boxer.nonce_constant());

    std::string boxed = client_boxer.box("Hello, world!\n");
    std::string unboxed = server_unboxer.unbox(boxed);
    std::cout << unboxed;

    boxed = client_boxer.box("From sodiumpp!\n");
    unboxed = server_unboxer.unbox(boxed);
    std::cout << unboxed;
    return 0;
}
<|endoftext|>