<commit_before>/****************************************************************************
**
** Copyright (c) 2008-2009 Nokia Corporation and/or its subsidiary(-ies).
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the Qt Mobility Components.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain
** additional rights. These rights are described in the Nokia Qt LGPL
** Exception version 1.0, included in the file LGPL_EXCEPTION.txt in this
** package.
**
** If you have questions regarding the use of this file, please
** contact Nokia at http://www.qtsoftware.com/contact.
** $QT_END_LICENSE$
**
****************************************************************************/

#include <QtGui>

#include <qservicemanager.h>
#include <qserviceinterfacedescriptor.h>

#include "servicebrowser.h"

Q_DECLARE_METATYPE(QServiceInterfaceDescriptor)

ServiceBrowser::ServiceBrowser(QWidget *parent, Qt::WindowFlags flags)
    : QWidget(parent, flags)
{
    serviceManager = new QServiceManager(this);

    registerExampleServices();

    initWidgets();
    reloadServicesList();

    setWindowTitle(tr("Services Browser"));
}

ServiceBrowser::~ServiceBrowser()
{
    unregisterExampleServices();
}

void ServiceBrowser::currentInterfaceImplChanged(QListWidgetItem *current, QListWidgetItem *previous)
{
    Q_UNUSED(previous);
    if (!current)
        return;

    reloadAttributesList();
    reloadAttributesRadioButtonText();

    QServiceInterfaceDescriptor descriptor = current->data(Qt::UserRole).value<QServiceInterfaceDescriptor>();
    if (descriptor.isValid()) {
        defaultInterfaceButton->setText(tr("Set as default implementation for %1")
                .arg(descriptor.interfaceName()));
        defaultInterfaceButton->setEnabled(true);
    }
}

void ServiceBrowser::reloadServicesList()
{
    servicesListWidget->clear();

    QStringList services = serviceManager->findServices();
    for (int i=0; i<services.count(); i++)
        servicesListWidget->addItem(services[i]);

    servicesListWidget->addItem(showAllServicesItem);
}

void ServiceBrowser::reloadInterfaceImplementationsList()
{
    QString serviceName;
    if (servicesListWidget->currentItem()
            && servicesListWidget->currentItem() != showAllServicesItem) {
        serviceName = servicesListWidget->currentItem()->text();
        interfacesGroup->setTitle(tr("Interfaces implemented by %1").arg(serviceName));
    } else {
        interfacesGroup->setTitle(tr("All interface implementations"));
    }

    QList<QServiceInterfaceDescriptor> descriptors = serviceManager->findInterfaces(serviceName);

    interfacesListWidget->clear();
    for (int i=0; i<descriptors.count(); i++) {
        QString text = QString("%1 %2.%3")
                .arg(descriptors[i].interfaceName())
                .arg(descriptors[i].majorVersion())
                .arg(descriptors[i].minorVersion());

        if (serviceName.isEmpty())
            text += " (" + descriptors[i].serviceName() + ")";

        QServiceInterfaceDescriptor defaultInterfaceImpl =
                serviceManager->interfaceDefault(descriptors[i].interfaceName());
        if (descriptors[i] == defaultInterfaceImpl)
            text += tr(" (default)");

        QListWidgetItem *item = new QListWidgetItem(text);
        item->setData(Qt::UserRole, qVariantFromValue(descriptors[i]));
        interfacesListWidget->addItem(item);
    }

    defaultInterfaceButton->setEnabled(false);
}

void ServiceBrowser::reloadAttributesList()
{
    QListWidgetItem *item = interfacesListWidget->currentItem();
    if (!item)
        return;

    QServiceInterfaceDescriptor selectedImpl =
            item->data(Qt::UserRole).value<QServiceInterfaceDescriptor>();

    QObject *implementationRef;
    if (selectedImplRadioButton->isChecked())
        implementationRef = serviceManager->loadInterface(selectedImpl, 0, 0);
    else
        implementationRef = serviceManager->loadInterface(selectedImpl.interfaceName(), 0, 0);

    attributesListWidget->clear();
    if (!implementationRef) {
        attributesListWidget->addItem(tr("(Error loading service plugin)"));
        return;
    }

    const QMetaObject *metaObject = implementationRef->metaObject();
    attributesGroup->setTitle(tr("Invokable attributes for %1 class")
            .arg(QString(metaObject->className())));
    for (int i=0; i<metaObject->methodCount(); i++) {
        QMetaMethod method = metaObject->method(i);
        attributesListWidget->addItem("[METHOD] " + QString(method.signature()));
    }
    for (int i=0; i<metaObject->propertyCount(); i++) {
        QMetaProperty property = metaObject->property(i);
        attributesListWidget->addItem("[PROPERTY] " + QString(property.name()));
    }
}

void ServiceBrowser::setDefaultInterfaceImplementation()
{
    QListWidgetItem *item = interfacesListWidget->currentItem();
    if (!item)
        return;

    QServiceInterfaceDescriptor descriptor = item->data(Qt::UserRole).value<QServiceInterfaceDescriptor>();
    if (descriptor.isValid()) {
        if (serviceManager->setInterfaceDefault(descriptor)) {
            int currentIndex = interfacesListWidget->row(item);
            reloadInterfaceImplementationsList();
            interfacesListWidget->setCurrentRow(currentIndex);
        } else {
            qWarning() << "Unable to set default service for interface:"
                    << descriptor.interfaceName();
        }
    }
}

void ServiceBrowser::registerExampleServices()
{
    QStringList exampleXmlFiles;
    exampleXmlFiles << "filemanagerservice.xml" << "bluetoothtransferservice.xml";
    foreach (const QString &fileName, exampleXmlFiles) {
        QString path = QCoreApplication::applicationDirPath() + "/xmldata/" + fileName;
        serviceManager->addService(path);
    }
}

void ServiceBrowser::unregisterExampleServices()
{
    serviceManager->removeService("FileManagerService");
    serviceManager->removeService("BluetoothTransferService");
}

void ServiceBrowser::reloadAttributesRadioButtonText()
{
    QListWidgetItem *item = interfacesListWidget->currentItem();
    if (!item)
        return;

    QServiceInterfaceDescriptor selectedImpl =
            item->data(Qt::UserRole).value<QServiceInterfaceDescriptor>();
    QServiceInterfaceDescriptor defaultImpl =
            serviceManager->interfaceDefault(selectedImpl.interfaceName());

    defaultImplRadioButton->setText(tr("Default implementation for %1\n(currently provided by %2)")
            .arg(defaultImpl.interfaceName())
            .arg(defaultImpl.serviceName()));
}

void ServiceBrowser::initWidgets()
{
    showAllServicesItem = new QListWidgetItem(tr("(All registered services)"));

    servicesListWidget = new QListWidget;
    interfacesListWidget = new QListWidget;
    interfacesListWidget->addItem(tr("(Select a service)"));
    attributesListWidget = new QListWidget;
    attributesListWidget->addItem(tr("(Select an interface implementation)"));

    interfacesListWidget->setMinimumWidth(450);

    connect(servicesListWidget, SIGNAL(currentItemChanged(QListWidgetItem*,QListWidgetItem*)),
            this, SLOT(reloadInterfaceImplementationsList()));

    connect(interfacesListWidget, SIGNAL(currentItemChanged(QListWidgetItem*,QListWidgetItem*)),
            this, SLOT(currentInterfaceImplChanged(QListWidgetItem*,QListWidgetItem*)));

    defaultInterfaceButton = new QPushButton(tr("Set as default implementation"));
    defaultInterfaceButton->setEnabled(false);
    connect(defaultInterfaceButton, SIGNAL(clicked()),
            this, SLOT(setDefaultInterfaceImplementation()));

    selectedImplRadioButton = new QRadioButton(tr("Selected interface implementation"));
    defaultImplRadioButton = new QRadioButton(tr("Default implementation"));
    selectedImplRadioButton->setChecked(true);

    QButtonGroup *radioButtons = new QButtonGroup(this);
    radioButtons->addButton(selectedImplRadioButton);
    radioButtons->addButton(defaultImplRadioButton);
    connect(radioButtons, SIGNAL(buttonClicked(QAbstractButton*)),
            this, SLOT(reloadAttributesList()));

    QGroupBox *servicesGroup = new QGroupBox(tr("Show services for:"));
    QVBoxLayout *servicesLayout = new QVBoxLayout;
    servicesLayout->addWidget(servicesListWidget);
    servicesGroup->setLayout(servicesLayout);

    interfacesGroup = new QGroupBox(tr("Interface implementations"));
    QVBoxLayout *interfacesLayout = new QVBoxLayout;
    interfacesLayout->addWidget(interfacesListWidget);
    interfacesLayout->addWidget(defaultInterfaceButton);
    interfacesGroup->setLayout(interfacesLayout);

    attributesGroup = new QGroupBox(tr("Invokable attributes"));
    QVBoxLayout *attributesLayout = new QVBoxLayout;
    attributesLayout->addWidget(attributesListWidget);
    attributesLayout->addWidget(new QLabel(tr("Show attributes for:")));
    attributesLayout->addWidget(selectedImplRadioButton);
    attributesLayout->addWidget(defaultImplRadioButton);
    attributesGroup->setLayout(attributesLayout);

    QGridLayout *layout = new QGridLayout;
    layout->addWidget(servicesGroup, 0, 0);
    layout->addWidget(attributesGroup, 0, 1, 2, 1);
    layout->addWidget(interfacesGroup, 1, 0);
    setLayout(layout);
}
<commit_msg>Remove spurious file.<commit_after><|endoftext|>


<commit_before>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <assert.h>
#include <semaphore.h>

#include "PcieTestBenchIndicationWrapper.h"
#include "PcieTestBenchRequestProxy.h"
#include "GeneratedTypes.h"

class PcieTestBenchIndication : public PcieTestBenchIndicationWrapper
{
  sem_t sem;
  sem_t done_sem;
public:
  uint32_t cnt;
  void incr_cnt(){
    if (++cnt == 7)
      exit(0);
  }
  virtual void finished(uint32_t v){
    fprintf(stderr, "finished(%x)\n", v);
    sem_post(&done_sem);
  }
  virtual void started(uint32_t words){
    fprintf(stderr, "started(%x)\n", words);
  }
  void tlpout(const TLPData16 &tlp) {
    fprintf(stderr, "Received tlp: %08x%08x%08x%08x\n", tlp.data3, tlp.data2, tlp.data1, tlp.data0);
    sem_post(&sem);
  }
  PcieTestBenchIndication(unsigned int id) : PcieTestBenchIndicationWrapper(id), cnt(0)
  {
    sem_init(&sem, 0, 0);
    sem_init(&done_sem,0,0);
  }
  void wait() {
    sem_wait(&sem);
  }
};

int main(int argc, const char **argv)
{
  PcieTestBenchIndication *indication = new PcieTestBenchIndication(IfcNames_PcieTestBenchIndication);
  PcieTestBenchRequestProxy *device = new PcieTestBenchRequestProxy(IfcNames_PcieTestBenchRequest);

  PortalAlloc *srcAlloc;
  unsigned int *srcBuffer = 0;

  pthread_t tid;
  fprintf(stderr, "Main::creating exec thread\n");
  if(pthread_create(&tid, NULL,  portalExec, NULL)){
    fprintf(stderr, "Main::error creating exec thread\n");
    exit(1);
  }

}
<commit_msg>flush out the cpp a bit<commit_after>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <assert.h>
#include <semaphore.h>
#include <sys/mman.h>

#include "StdDmaIndication.h"
#include "DmaConfigProxy.h"
#include "PcieTestBenchIndicationWrapper.h"
#include "PcieTestBenchRequestProxy.h"
#include "GeneratedTypes.h"

sem_t test_sem;
int numWords = 0x12400/4;
size_t test_sz  = numWords*sizeof(unsigned int);
size_t alloc_sz = test_sz;
int burstLen = 16;

class PcieTestBenchIndication : public PcieTestBenchIndicationWrapper
{
public:
  PcieTestBenchRequestProxy *device;
  virtual void finished(uint32_t v){
    fprintf(stderr, "finished(%x)\n", v);
    sem_post(&test_sem);
  }
  virtual void started(uint32_t words){
    fprintf(stderr, "started(%x)\n", words);
  }
  void tlpout(const TLPData16 &tlp) {
    fprintf(stderr, "Received tlp: %08x%08x%08x%08x\n", tlp.data3, tlp.data2, tlp.data1, tlp.data0);
    TLPData16 resp;
    device->tlpin(resp);
  }
  PcieTestBenchIndication(PcieTestBenchRequestProxy *device, unsigned int id) : PcieTestBenchIndicationWrapper(id), device(device){}
};

int main(int argc, const char **argv)
{
  PcieTestBenchRequestProxy *device = new PcieTestBenchRequestProxy(IfcNames_PcieTestBenchRequest);
  PcieTestBenchIndication *deviceIndication = new PcieTestBenchIndication(device, IfcNames_PcieTestBenchIndication);

  DmaConfigProxy *dma = new DmaConfigProxy(IfcNames_DmaConfig);
  DmaIndication *dmaIndication = new DmaIndication(dma, IfcNames_DmaIndication);

  PortalAlloc *srcAlloc;
  unsigned int *srcBuffer = 0;

  dma->alloc(alloc_sz, &srcAlloc);
  srcBuffer = (unsigned int *)mmap(0, alloc_sz, PROT_READ|PROT_WRITE|PROT_EXEC, MAP_SHARED, srcAlloc->header.fd, 0);
  for (int i = 0; i < numWords; i++)
    srcBuffer[i] = i;

  pthread_t tid;
  fprintf(stderr, "Main::creating exec thread\n");
  if(pthread_create(&tid, NULL,  portalExec, NULL)){
   fprintf(stderr, "error creating exec thread\n");
   exit(1);
  }

  dma->dCacheFlushInval(srcAlloc, srcBuffer);
  unsigned int ref_srcAlloc = dma->reference(srcAlloc);

  device->startRead(ref_srcAlloc, numWords, burstLen);
  sem_wait(&test_sem);
}
<|endoftext|>


<commit_before>#ifndef BVECT
#define BVECT

#include <vector>

using namespace std;

class BVect {
  private:
    double _z1;
    double _z2;
    vector<double> _x;
  public:
    BVect () {}
    BVect (double z1, double z2, vector<double> x) : _z1(z1), _z2(z2), _x(x) {}
    BVect (const BVect& b1, const BVect& b2, double lambda) {
      _z1 = lambda * b1.z1() + (1-lambda) * b2.z1();
      _z2 = lambda * b1.z2() + (1-lambda) * b2.z2();
      for (unsigned i = 0; i < b1.x().size(); ++i) {
        _x.push_back(lambda * b1.x().at(i) + (1-lambda) * b2.x().at(i));
      }
    }
    double z1() const {return _z1;}
    double z2() const {return _z2;}
    vector<double> x() const {return _x;}
    bool operator == (const BVect& bv) const {
      return (this->z1() == bv.z1() && this->z2() == bv.z2());
    }
    bool operator != (const BVect bv) const {
      return !(*this == bv);
    }
    bool weaklyDominates(const BVect& bv) const {
      return (this->z1() <= bv.z1() && this->z2() <= bv.z2());
    }
    bool dominates(const BVect& bv) const {
      return (this->weaklyDominates(bv) && (*this != bv));
    }
    bool strictlyDominates(const BVect& bv) const {
      return (this->z1() < bv.z1() && this->z2() < bv.z2());
    }
    bool isInA1AreaOf(const BVect& bv) const {
      return (bv.z1() > this->z1() && bv.z2() < this->z2());
    }
    bool isInA2AreaOf(const BVect& bv) const {
      return bv.isInA1AreaOf(*this);
    }
};

#endif
<commit_msg>BVect: Add << ostream operator<commit_after>#ifndef BVECT
#define BVECT

#include <vector>
#include <iostream>

using namespace std;

class BVect {
  private:
    double _z1;
    double _z2;
    vector<double> _x;
  public:
    BVect () {}
    BVect (double z1, double z2, vector<double> x) : _z1(z1), _z2(z2), _x(x) {}
    BVect (const BVect& b1, const BVect& b2, double lambda) {
      _z1 = lambda * b1.z1() + (1-lambda) * b2.z1();
      _z2 = lambda * b1.z2() + (1-lambda) * b2.z2();
      for (unsigned i = 0; i < b1.x().size(); ++i) {
        _x.push_back(lambda * b1.x().at(i) + (1-lambda) * b2.x().at(i));
      }
    }
    double z1() const {return _z1;}
    double z2() const {return _z2;}
    vector<double> x() const {return _x;}
    bool operator == (const BVect& bv) const {
      return (this->z1() == bv.z1() && this->z2() == bv.z2());
    }
    bool operator != (const BVect bv) const {
      return !(*this == bv);
    }
    bool weaklyDominates(const BVect& bv) const {
      return (this->z1() <= bv.z1() && this->z2() <= bv.z2());
    }
    bool dominates(const BVect& bv) const {
      return (this->weaklyDominates(bv) && (*this != bv));
    }
    bool strictlyDominates(const BVect& bv) const {
      return (this->z1() < bv.z1() && this->z2() < bv.z2());
    }
    bool isInA1AreaOf(const BVect& bv) const {
      return (bv.z1() > this->z1() && bv.z2() < this->z2());
    }
    bool isInA2AreaOf(const BVect& bv) const {
      return bv.isInA1AreaOf(*this);
    }
    friend ostream& operator << (ostream& s, const BVect& bv) {
      s << "(" << bv.z1() << ", " << bv.z2() << ")";
      return s;
    }
};

#endif
<|endoftext|>


<commit_before>///
/// @file   Wheel.hpp
/// @brief  Data structures related to wheel factorization.
///         Wheel factorization is used to skip multiples of small
///         primes in the sieve of Eratosthenes.
///
/// Copyright (C) 2015 Kim Walisch, <kim.walisch@gmail.com>
///
/// This file is distributed under the BSD License. See the COPYING
/// file in the top level directory.
///

#ifndef WHEEL_HPP
#define WHEEL_HPP

#include <pmath.hpp>

#include <stdint.h>
#include <algorithm>
#include <cassert>
#include <vector>

namespace primecount {

/// The InitWheel data structure is used to calculate the first
/// multiple >= start of each sieving prime.
///
struct InitWheel
{
  int8_t next_multiple_factor;
  int8_t wheel_index;
};

struct NextWheel
{
  int8_t next_multiple_factor;
  int8_t next_wheel_index;
};

struct WheelItem
{
  WheelItem(int64_t multiple, int8_t i)
    : next_multiple(multiple), wheel_index(i)
  { }
  int64_t next_multiple;
  int8_t wheel_index;
};

class Wheel
{
public:
  template <typename Primes>
  Wheel(Primes& primes,
        int64_t low,
        int64_t size,
        int64_t c)
  {
    assert(size <= primes.size());
    int64_t b = 1;

    wheelItems_.reserve(size);
    // primecount uses 1-indexing, 0-index is a dummy
    wheelItems_.push_back(WheelItem(0, 0));

    // for the first c primes only multiples of 2 are skipped
    for (; b < std::min(c + 1, size); b++)
    {
      int64_t prime = primes[b];
      int64_t multiple = ceil_div(low, prime) * prime;
      multiple += prime * (~multiple & 1);

#if __cplusplus >= 201103L
      wheelItems_.emplace_back(multiple, 0);
#else
      wheelItems_.push_back(WheelItem(multiple, 0));
#endif
    }

    for (; b < size; b++)
    {
      int64_t prime = primes[b];
      int64_t quotient = ceil_div(low, prime);

      // calculate the first multiple of prime >= low
      int64_t multiple = prime * quotient;
      if (multiple % 2 == 0) { multiple += prime; quotient += 1; }

      // calculate the next multiple of prime that is not
      // divisible by any of the wheel's factors (2, 3, 5, 7)
      uint64_t next_multiple_factor = initWheel210[quotient % 210].next_multiple_factor;
      multiple += prime * next_multiple_factor;
      int8_t wheel_index = initWheel210[quotient % 210].wheel_index;

#if __cplusplus >= 201103L
      wheelItems_.emplace_back(multiple, wheel_index);
#else
      wheelItems_.push_back(WheelItem(multiple, wheel_index));
#endif
    }
  }
  WheelItem& operator[](int64_t i)
  {
    return wheelItems_[i];
  }
  static int64_t next_multiple_factor(int64_t* wheel_index)
  {
    assert(i < 8);
    int64_t next_multiple_factor = nextWheel210[*wheel_index].next_multiple_factor;
    *wheel_index = nextWheel210[*wheel_index].next_wheel_index;
    return next_multiple_factor;
  }
private:
  static const InitWheel initWheel210[210];
  static const NextWheel nextWheel210[48];
  std::vector<WheelItem> wheelItems_;
};

} // namespace primecount

#endif
<commit_msg>Remove assert<commit_after>///
/// @file   Wheel.hpp
/// @brief  Data structures related to wheel factorization.
///         Wheel factorization is used to skip multiples of small
///         primes in the sieve of Eratosthenes.
///
/// Copyright (C) 2015 Kim Walisch, <kim.walisch@gmail.com>
///
/// This file is distributed under the BSD License. See the COPYING
/// file in the top level directory.
///

#ifndef WHEEL_HPP
#define WHEEL_HPP

#include <pmath.hpp>

#include <stdint.h>
#include <algorithm>
#include <cassert>
#include <vector>

namespace primecount {

/// The InitWheel data structure is used to calculate the first
/// multiple >= start of each sieving prime.
///
struct InitWheel
{
  int8_t next_multiple_factor;
  int8_t wheel_index;
};

struct NextWheel
{
  int8_t next_multiple_factor;
  int8_t next_wheel_index;
};

struct WheelItem
{
  WheelItem(int64_t multiple, int8_t i)
    : next_multiple(multiple), wheel_index(i)
  { }
  int64_t next_multiple;
  int8_t wheel_index;
};

class Wheel
{
public:
  template <typename Primes>
  Wheel(Primes& primes,
        int64_t low,
        int64_t size,
        int64_t c)
  {
    assert(size <= primes.size());
    int64_t b = 1;

    wheelItems_.reserve(size);
    // primecount uses 1-indexing, 0-index is a dummy
    wheelItems_.push_back(WheelItem(0, 0));

    // for the first c primes only multiples of 2 are skipped
    for (; b < std::min(c + 1, size); b++)
    {
      int64_t prime = primes[b];
      int64_t multiple = ceil_div(low, prime) * prime;
      multiple += prime * (~multiple & 1);

#if __cplusplus >= 201103L
      wheelItems_.emplace_back(multiple, 0);
#else
      wheelItems_.push_back(WheelItem(multiple, 0));
#endif
    }

    for (; b < size; b++)
    {
      int64_t prime = primes[b];
      int64_t quotient = ceil_div(low, prime);

      // calculate the first multiple of prime >= low
      int64_t multiple = prime * quotient;
      if (multiple % 2 == 0) { multiple += prime; quotient += 1; }

      // calculate the next multiple of prime that is not
      // divisible by any of the wheel's factors (2, 3, 5, 7)
      uint64_t next_multiple_factor = initWheel210[quotient % 210].next_multiple_factor;
      multiple += prime * next_multiple_factor;
      int8_t wheel_index = initWheel210[quotient % 210].wheel_index;

#if __cplusplus >= 201103L
      wheelItems_.emplace_back(multiple, wheel_index);
#else
      wheelItems_.push_back(WheelItem(multiple, wheel_index));
#endif
    }
  }
  WheelItem& operator[](int64_t i)
  {
    return wheelItems_[i];
  }
  static int64_t next_multiple_factor(int64_t* wheel_index)
  {
    int64_t next_multiple_factor = nextWheel210[*wheel_index].next_multiple_factor;
    *wheel_index = nextWheel210[*wheel_index].next_wheel_index;
    return next_multiple_factor;
  }
private:
  static const InitWheel initWheel210[210];
  static const NextWheel nextWheel210[48];
  std::vector<WheelItem> wheelItems_;
};

} // namespace primecount

#endif
<|endoftext|>


<commit_before>/**
 * Copyright  2012-2013 Sergio Arroutbi Braojos <sarroutbi@gmail.com>
 *
 * Permission to use, copy, modify, and/or distribute this software
 * for any purpose with or without fee is hereby granted, provided that
 * the above copyright notice and this permission notice appear in all copies.
 *
 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
 * AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
 * INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
 * LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
 * NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE
 * OR PERFORMANCE OF THIS SOFTWARE.
 **/
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <list>
#include <iostream>

#include "HtmlParser.h"

using namespace std;

inline void trim(const char* cstr, char* trimmed,
                 uint32_t trim_length)
{
  std::string str(cstr);
  str.erase(0, str.find_first_not_of(' '));
  str.erase(str.find_last_not_of(' ')+1);
  strncpy(trimmed, str.c_str(), trim_length);
}

HtmlParser::HtmlParser ()
{
  memset(_file, 0, FILENAME_MAX);
}

HtmlParser::HtmlParser (const char* file)
{
  setFile(file);
}

HtmlParser::~HtmlParser ()
{
  _bikeList.clear();
}

uint8_t
HtmlParser::dissertUrl (const char* url, char* link, const uint16_t urlMax,
                        char* urlText, const uint16_t urlTextMax)
{
  /**
   * URL input here has next format
   * "http://url.com/the_url" target="_blank">URL TEXT
   */
  char* now = const_cast<char*>(url);
  char* aux;
  now = strstr(now, "\"");
  if(!now)
  {
     goto error_no_link;
  }
  now += 1; // avoid '"' character
  if(sscanf(now, "%[^\"]>", link) <1)
  {
     goto error_no_link;
  }
  now += strlen(link);
  if((aux = strstr(now, "target=\"_blank\">")))
  {
    now = aux;
    now += strlen("target=\"_blank\">");
  }
  if(sscanf(now, "%[^<]	", urlText) <= 0)
  {
     goto error_no_link;
  }
  return 0;
error_no_link:
  fprintf(stderr, "Error parsing link. Could parse up to:=>%s<=\n", now);
  return 1;
}

void HtmlParser::setFile(const char* file)
{
  if(file)
    strncpy(_file, file, FILENAME_MAX);
}

uint8_t HtmlParser::dummyBikeFill (Bike* bike)
{
  if(bike)
    bike->set("Specialized", "2013", "http://test.com/test-url", "TheStore",
              "Specialized 2013", (rand()*999), BIKE_TYPE_MTB);
}

uint8_t HtmlParser::parseABike (const char* htmlPiece, uint32_t htmlPieceSize, Bike* bike)
{
  uint8_t err = 0;

  /* Each html piece of each bike is of the type:
   *    Trademark
   *    Model
   *    Type
   *    Price
   *    Store
   *   URL TEXT
   */
  char trademark[MAX_TRADEMARK] = "";
  char model    [MAX_MODEL]     = "";
  char store    [MAX_STORE]     = "";
  char c_type   [MAX_TYPE]      = "";
  char c_price  [MAX_PRICE]     = "";
  char url      [MAX_URL]       = "";
  char url_text [MAX_URL_TEXT]  = "";
  char url_all  [MAX_HTML_PIECE_LINE] = "";
  float       price = 0;
  bike_type_t type  = BIKE_TYPE_UNDEFINED;

  if(bike)
  {
    char* now = const_cast<char*>(htmlPiece);
    while(now = strstr(now, ""))
    {
      now += strlen("");
      if(!strlen(trademark))
      {
        sscanf(now, "%[^<]	", trademark);
        now += strlen(trademark);
      }
      else if(!strlen(model))
      {
        sscanf(now, "%[^<]	", model);
        now += strlen(model);
      }
      else if(!strlen(c_type))
      {
        sscanf(now, "%[^<]	", c_type);
        now += strlen(c_type);
      }
      else if(!strlen(c_price))
      {
        sscanf(now, "%[^<]	", c_price);
        now += strlen(c_price);
        price = strtod(c_price, NULL);
      }
      else if(!strlen(store))
      {
        sscanf(now, "%[^<]	", store);
        now += strlen(store);
      }
      else if(!strlen(url_all))
      {
        now += 1; // avoid '<' of ....
        sscanf(now, "%[^<]", url_all);
        dissertUrl(url_all, url, MAX_URL, url_text, MAX_URL_TEXT);
      }
      else
      {
        break;
      }
      now += strlen("	");
    }
    bike->set(trademark, model, store, url, url_text, price, type);
  }
  else
  {
    err = 1;
  }
  return err;
}

uint16_t
HtmlParser::getHtmlPiece (FILE* f, char* htmlPiece, const uint16_t maxHtml)
{
  uint16_t read = 0;
  bool pieceStart = false;
  bool finish = false;
  if(f && htmlPiece)
  {
    char line[MAX_HTML_PIECE_LINE];
    char trimmedLine[MAX_HTML_PIECE_LINE];
    uint16_t piecePending = MAX_HTML_PIECE_LINE;

    while((fgets(line, MAX_HTML_PIECE, f)) && (!finish)
          && (read <= maxHtml))
    {
      if (strstr(line, "
"))
      {
         pieceStart = true;
      }
      else if(pieceStart && strstr(line, "
"))
      {
         pieceStart = false;
        finish = true;
      }
      else if(pieceStart)
      {
        piecePending -= strlen(line);
        read += strlen(line);
        strncat(htmlPiece, line, piecePending);
      }
    }
  }
  return read;
}

void HtmlParser:: logList ()
{
  BikeList::iterator i;

  for(i = _bikeList.begin(); i != _bikeList.end(); ++i)
    (*i).log();
}

uint8_t HtmlParser::parse ()
{
  uint8_t  err = 0;
  uint16_t pieceLength = 0;
  FILE*    f = fopen(_file, "r");
  char     htmlPiece[MAX_HTML_PIECE];

  memset(htmlPiece, 0, MAX_HTML_PIECE);

  if(!f)
  {
    err = 1;
  }
  else
  {
    while((pieceLength = getHtmlPiece(f, htmlPiece, MAX_HTML_PIECE))>0)
    {
      //fprintf(stderr, "Read html piece of [%d] bytes, =>%s<=\n",
      //        pieceLength, htmlPiece);
      Bike bike;
      parseABike(htmlPiece, pieceLength, &bike);
      memset(htmlPiece, 0, MAX_HTML_PIECE);
      _bikeList.push_back(bike);
    }
    fclose(f);
  }
  return err;
}

uint8_t HtmlParser::parse (const char* file)
{
  uint8_t err = 1;
  if(file)
  {
    setFile(file);
    err = parse();
  }
  return err;
}

const BikeList & HtmlParser::getList ()
{
  parse(_file);
  return _bikeList;
}
<commit_msg>Fixing issue that was making half of the results to be dumped<commit_after>/**
 * Copyright  2012-2013 Sergio Arroutbi Braojos <sarroutbi@gmail.com>
 *
 * Permission to use, copy, modify, and/or distribute this software
 * for any purpose with or without fee is hereby granted, provided that
 * the above copyright notice and this permission notice appear in all copies.
 *
 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
 * AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
 * INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
 * LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
 * NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE
 * OR PERFORMANCE OF THIS SOFTWARE.
 **/
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <list>
#include <iostream>

#include "HtmlParser.h"

using namespace std;

inline void trim(const char* cstr, char* trimmed,
                 uint32_t trim_length)
{
  std::string str(cstr);
  str.erase(0, str.find_first_not_of(' '));
  str.erase(str.find_last_not_of(' ')+1);
  strncpy(trimmed, str.c_str(), trim_length);
}

HtmlParser::HtmlParser ()
{
  memset(_file, 0, FILENAME_MAX);
}

HtmlParser::HtmlParser (const char* file)
{
  setFile(file);
}

HtmlParser::~HtmlParser ()
{
  _bikeList.clear();
}

uint8_t
HtmlParser::dissertUrl (const char* url, char* link, const uint16_t urlMax,
                        char* urlText, const uint16_t urlTextMax)
{
  /**
   * URL input here has next format
   * "http://url.com/the_url" target="_blank">URL TEXT
   */
  char* now = const_cast<char*>(url);
  char* aux;
  now = strstr(now, "\"");
  if(!now)
  {
     goto error_no_link;
  }
  now += 1; // avoid '"' character
  if(sscanf(now, "%[^\"]>", link) <1)
  {
     goto error_no_link;
  }
  now += strlen(link);
  if((aux = strstr(now, "target=\"_blank\">")))
  {
    now = aux;
    now += strlen("target=\"_blank\">");
  }
  if(sscanf(now, "%[^<]	", urlText) <= 0)
  {
     goto error_no_link;
  }
  return 0;
error_no_link:
  fprintf(stderr, "Error parsing link. Could parse up to:=>%s<=\n", now);
  return 1;
}

void HtmlParser::setFile(const char* file)
{
  if(file)
    strncpy(_file, file, FILENAME_MAX);
}

uint8_t HtmlParser::dummyBikeFill (Bike* bike)
{
  if(bike)
    bike->set("Specialized", "2013", "http://test.com/test-url", "TheStore",
              "Specialized 2013", (rand()*999), BIKE_TYPE_MTB);
}

uint8_t HtmlParser::parseABike (const char* htmlPiece, uint32_t htmlPieceSize, Bike* bike)
{
  uint8_t err = 0;

  /* Each html piece of each bike is of the type:
   *    Trademark
   *    Model
   *    Type
   *    Price
   *    Store
   *   URL TEXT
   */
  char trademark[MAX_TRADEMARK] = "";
  char model    [MAX_MODEL]     = "";
  char store    [MAX_STORE]     = "";
  char c_type   [MAX_TYPE]      = "";
  char c_price  [MAX_PRICE]     = "";
  char url      [MAX_URL]       = "";
  char url_text [MAX_URL_TEXT]  = "";
  char url_all  [MAX_HTML_PIECE_LINE] = "";
  float       price = 0;
  bike_type_t type  = BIKE_TYPE_UNDEFINED;

  if(bike)
  {
    char* now = const_cast<char*>(htmlPiece);
    while(now = strstr(now, ""))
    {
      now += strlen("");
      if(!strlen(trademark))
      {
        sscanf(now, "%[^<]	", trademark);
        now += strlen(trademark);
      }
      else if(!strlen(model))
      {
        sscanf(now, "%[^<]	", model);
        now += strlen(model);
      }
      else if(!strlen(c_type))
      {
        sscanf(now, "%[^<]	", c_type);
        now += strlen(c_type);
      }
      else if(!strlen(c_price))
      {
        sscanf(now, "%[^<]	", c_price);
        now += strlen(c_price);
        price = strtod(c_price, NULL);
      }
      else if(!strlen(store))
      {
        sscanf(now, "%[^<]	", store);
        now += strlen(store);
      }
      else if(!strlen(url_all))
      {
        now += 1; // avoid '<' of ....
        sscanf(now, "%[^<]", url_all);
        dissertUrl(url_all, url, MAX_URL, url_text, MAX_URL_TEXT);
      }
      else
      {
        break;
      }
      now += strlen("	");
    }
    bike->set(trademark, model, store, url, url_text, price, type);
  }
  else
  {
    err = 1;
  }
  return err;
}

uint16_t
HtmlParser::getHtmlPiece (FILE* f, char* htmlPiece, const uint16_t maxHtml)
{
  uint16_t read = 0;
  bool pieceStart = false;
  bool finish = false;
  if(f && htmlPiece)
  {
    char line[MAX_HTML_PIECE_LINE];
    char trimmedLine[MAX_HTML_PIECE_LINE];
    uint16_t piecePending = MAX_HTML_PIECE_LINE;

    while((!finish) && (read <= maxHtml) && (fgets(line, MAX_HTML_PIECE, f)))
    {
      // fprintf(stderr, "Line:=>%s<=", line);
      if (strstr(line, "
"))
      {
        pieceStart = true;
      }
      else if(pieceStart && strstr(line, "
"))
      {
        pieceStart = false;
        finish = true;
      }
      else if(pieceStart && (!finish))
      {
        strncat(htmlPiece, line, piecePending);
        read += strlen(line);
      }
    }
  }
  return read;
}

void HtmlParser:: logList ()
{
  BikeList::iterator i;

  for(i = _bikeList.begin(); i != _bikeList.end(); ++i)
    (*i).log();
  cout << "Total number of bikes:=>" << _bikeList.size() << "<=" << endl;
}

uint8_t HtmlParser::parse ()
{
  uint8_t  err = 0;
  uint16_t pieceLength = 0;
  FILE*    f = fopen(_file, "r");
  char     htmlPiece[MAX_HTML_PIECE];

  memset(htmlPiece, 0, MAX_HTML_PIECE);

  if(!f)
  {
    err = 1;
  }
  else
  {
    while((pieceLength = getHtmlPiece(f, htmlPiece, MAX_HTML_PIECE))>0)
    {
      // fprintf(stderr, "Read html piece of [%d] bytes, =>%s<=\n",
      //         pieceLength, htmlPiece);
      Bike bike;
      parseABike(htmlPiece, pieceLength, &bike);
      memset(htmlPiece, 0, MAX_HTML_PIECE);
      _bikeList.push_back(bike);
    }
    fclose(f);
  }
  return err;
}

uint8_t HtmlParser::parse (const char* file)
{
  uint8_t err = 1;
  if(file)
  {
    setFile(file);
    err = parse();
  }
  return err;
}

const BikeList & HtmlParser::getList ()
{
  parse(_file);
  return _bikeList;
}
<|endoftext|>


<commit_before><commit_msg>remove unnecessary debug message<commit_after><|endoftext|>


<commit_before><commit_msg>Make search provider enforce that keyword search term visits have a decreasing relevance. Without this we could end up with visits having the same relevance, which results in randomness as to which is first, when we really wanted one to be before the other.<commit_after><|endoftext|>


<commit_before><commit_msg>Disable flaky TabDraggingTest.Tab1Tab3Escape.<commit_after><|endoftext|>


<commit_before><commit_msg>Fixed a corner case issue with printing XPS documents to the Microsoft XPS Document Writer which would not generate a job id.<commit_after><|endoftext|>


<commit_before>//------------------------------------------------------------------------------
// CLING - the C++ LLVM-based InterpreterG :)
// version: $Id$
// author:  Axel Naumann <axel@cern.ch>
//------------------------------------------------------------------------------

#include <cling/UserInterface/UserInterface.h>

#include <cling/MetaProcessor/MetaProcessor.h>
#include "textinput/TextInput.h"
#include "textinput/StreamReader.h"
#include "textinput/TerminalDisplay.h"

#include <iostream>
#include <sys/stat.h>

namespace llvm {
  class Module;
}

//---------------------------------------------------------------------------
// Construct an interface for an interpreter
//---------------------------------------------------------------------------
cling::UserInterface::UserInterface(Interpreter& interp, const char* prompt /*= "[cling] $"*/):
m_MetaProcessor(new MetaProcessor(interp))
{
}

//---------------------------------------------------------------------------
// Destruct the interface
//---------------------------------------------------------------------------
cling::UserInterface::~UserInterface()
{
  delete m_MetaProcessor;
}

//---------------------------------------------------------------------------
// Interact with the user using a prompt
//---------------------------------------------------------------------------
void cling::UserInterface::runInteractively(bool nologo /* = false */)
{
  if (!nologo) {
    std::cerr << std::endl;
    std::cerr << "****************** CLING ******************" << std::endl;
    std::cerr << "* Type C++ code and press enter to run it *" << std::endl;
    std::cerr << "*             Type .q to exit             *" << std::endl;
    std::cerr << "*******************************************" << std::endl;
  }
  static const char* histfile = ".cling_history";
  std::string Prompt("[cling]$ ");

  using namespace textinput;
  StreamReader* R = StreamReader::Create();
  TerminalDisplay* D = TerminalDisplay::Create();
  TextInput TI(*R, *D, histfile);
  TI.SetPrompt(Prompt.c_str());
  std::string line;
  MetaProcessorOpts& MPOpts = m_MetaProcessor->getMetaProcessorOpts();

  while (!MPOpts.Quitting) {
    TextInput::EReadResult RR = TI.ReadInput();
    TI.TakeInput(line);
    if (RR == TextInput::kRREOF) {
      MPOpts.Quitting = true;
      continue;
    }

    int indent = m_MetaProcessor->process(line.c_str());
    Prompt = "[cling]";
    if (MPOpts.RawInput)
      Prompt.append("! ");
    else
      Prompt.append("$ ");

    if (indent > 0)
      // Continuation requested.
      Prompt.append('?' + std::string(indent * 3, ' '));

    TI.SetPrompt(Prompt.c_str());

  }
}
<commit_msg>Don't use iostream.<commit_after>//------------------------------------------------------------------------------
// CLING - the C++ LLVM-based InterpreterG :)
// version: $Id$
// author:  Axel Naumann <axel@cern.ch>
//------------------------------------------------------------------------------

#include <cling/UserInterface/UserInterface.h>

#include <cling/MetaProcessor/MetaProcessor.h>
#include "textinput/TextInput.h"
#include "textinput/StreamReader.h"
#include "textinput/TerminalDisplay.h"

#include "llvm/Support/raw_ostream.h"

//---------------------------------------------------------------------------
// Construct an interface for an interpreter
//---------------------------------------------------------------------------
cling::UserInterface::UserInterface(Interpreter& interp, const char* prompt /*= "[cling] $"*/):
m_MetaProcessor(new MetaProcessor(interp))
{
}

//---------------------------------------------------------------------------
// Destruct the interface
//---------------------------------------------------------------------------
cling::UserInterface::~UserInterface()
{
  delete m_MetaProcessor;
}

//---------------------------------------------------------------------------
// Interact with the user using a prompt
//---------------------------------------------------------------------------
void cling::UserInterface::runInteractively(bool nologo /* = false */)
{
  if (!nologo) {
    llvm::outs() << "\n";
    llvm::outs() << "****************** CLING ******************" << "\n";
    llvm::outs() << "* Type C++ code and press enter to run it *" << "\n";
    llvm::outs() << "*             Type .q to exit             *" << "\n";
    llvm::outs() << "*******************************************" << "\n";
  }
  static const char* histfile = ".cling_history";
  std::string Prompt("[cling]$ ");

  using namespace textinput;
  StreamReader* R = StreamReader::Create();
  TerminalDisplay* D = TerminalDisplay::Create();
  TextInput TI(*R, *D, histfile);
  TI.SetPrompt(Prompt.c_str());
  std::string line;
  MetaProcessorOpts& MPOpts = m_MetaProcessor->getMetaProcessorOpts();

  while (!MPOpts.Quitting) {
    TextInput::EReadResult RR = TI.ReadInput();
    TI.TakeInput(line);
    if (RR == TextInput::kRREOF) {
      MPOpts.Quitting = true;
      continue;
    }

    int indent = m_MetaProcessor->process(line.c_str());
    Prompt = "[cling]";
    if (MPOpts.RawInput)
      Prompt.append("! ");
    else
      Prompt.append("$ ");

    if (indent > 0)
      // Continuation requested.
      Prompt.append('?' + std::string(indent * 3, ' '));

    TI.SetPrompt(Prompt.c_str());

  }
}
<|endoftext|>


<commit_before>#include "BilliardBuddy.h"

int BilliardBuddy::frameIterator = 0;
cv::vector<Vec2i> BilliardBuddy::cueCoords = cv::vector<Vec2i>(0, 0);

int main(int argc, char* argv[])
{
		BilliardBuddy::help();

		// Read config settings.
		const string inputSettingsFile = argc > 1 ? argv[1] : "config.xml";
		FileStorage fs(inputSettingsFile, FileStorage::READ);
		if (!fs.isOpened())
		{
			std::cout << "Could not open the configuration file: \"" << inputSettingsFile << "\"" << std::endl;
			return -1;
		}
		Settings settings;
		fs["Settings"] >> settings;
		fs.release();

		// Check validity of inputs before training begins.
		if (!settings.goodInput)
		{
			std::cout << "Invalid input detected. Application stopping. " << std::endl;
			return -1;
		}

		// MAIN LOGIC
		BilliardBuddy::process(settings);

		return 0;
}

void BilliardBuddy::process(Settings& settings) {
	bool preprocess = true;

	// Initialize CameraInterface
	CameraInterface cameraInterface = CameraInterface(settings);

	// Initialize PreProcessor
	Mat cameraMatrix, distCoeffs;
	cameraMatrix = settings.getCameraMatrix();
	distCoeffs = settings.getDistCoeffs();
	PreProcessor preProcessor = PreProcessor(cameraMatrix, distCoeffs);

	// Initialize Feature Detector(s)
	PoolTableDetector poolTableDetector = PoolTableDetector();
	CueDetector cueDetector = CueDetector();

	//Initialize Physics Model Calculator
	PhysicsModel physicsModel = PhysicsModel();

	// Initialize Visual Augmentors
	TextAugmentor textAugmentor = TextAugmentor();
	CueAugmentor cueAugmentor = CueAugmentor();

	// Initialize HMD interface.
	HMDInterface hmdInterface = HMDInterface();

	// Processing Loop
	bool result;
	do {
		result = processFrame(preprocess, cameraInterface, preProcessor, poolTableDetector, cueDetector, physicsModel, textAugmentor, cueAugmentor, hmdInterface);
		result = pollKeyboard(preprocess);
	} while (result == true);
}

bool BilliardBuddy::pollKeyboard(bool& preprocess)
{
	// Check for keyboard inputs.
	char key = (char)waitKey(1);
	const char ESC_KEY = 27;
	if (key == 'u')
		preprocess = !preprocess;
	if (key == ESC_KEY)
		return false;

	return true;
}

bool BilliardBuddy::processFrame(bool& preprocess, CameraInterface& cameraInterface, PreProcessor& preProcessor, PoolTableDetector& poolTableDetector, CueDetector& cueDetector, PhysicsModel& physicsModel, TextAugmentor& textAugmentor, CueAugmentor& cueAugmentor, HMDInterface& hmdInterface) {
	// Fetch feed from camera interface.
	Mat leftFrame, rightFrame;
	cameraInterface.getFrames(leftFrame, rightFrame);

	// Pre-process feed.
	if (preprocess)
	{
		preProcessor.preProcess(leftFrame);
		preProcessor.preProcess(rightFrame);
	}

	// Detect features.
	cv::vector<pocket> pocketPoints = poolTableDetector.detectTable(rightFrame, frameIterator);

	//Detect Cue
	if (frameIterator == 1 || frameIterator == 0)
	{
		cueCoords = cueDetector.detect(rightFrame, frameIterator);
	}

	//Detect White Ball
	//TODO
	cv::vector<Vec2i> whiteBall(1);
	whiteBall[0] = { 200, 100 };

	//Detect other balls
	//TODO?? Brian?
	cv::vector<Vec2i> balls(2);
	balls[0] = { 200, 140 };
	balls[1] = { 200, 170 };
	//balls[2] = { 150, 150 };

	// Calculate Physics Model
	//cv::vector<Path> pathVector = physicsModel.calculate(rightFrame, pocketPoints, cueCoords, whiteBall, balls);

	// Visually augment.
	textAugmentor.augment(rightFrame);
	cueAugmentor.augment(rightFrame, cueCoords);
	hmdInterface.drawToHMD(leftFrame, rightFrame);

	if (frameIterator == 5)
	{
		frameIterator = 1;
	}
	else
	{
		frameIterator++;
	}

	// check for errors and return false at some point
	return true;
}

int BilliardBuddy::getFrameIterator()
{
	return frameIterator;
}

void BilliardBuddy::help()
{
	std::cout << "Welcome to the BilliardBuddy trainer!" << std::endl
		<< "Usage: BilliardBuddy.exe <configpath.xml>" << std::endl
		<< "Near the sample file you'll find the configuration file, which has detailed help of "
		"how to edit it.  It may be any OpenCV supported file format XML/YAML." << std::endl;
}

void read(const FileNode& node, Settings& x, const Settings& default_value = Settings())
{
	// This is called when the ">>" operator is used between a FileNode and a Settings.
	if (node.empty())
		x = default_value;
	else
		x.read(node);
}<commit_msg>Fixed frameIteration not iterating through full range  - range max from 5 to 6<commit_after>#include "BilliardBuddy.h"

int BilliardBuddy::frameIterator = 0;
cv::vector<Vec2i> BilliardBuddy::cueCoords = cv::vector<Vec2i>(0, 0);

int main(int argc, char* argv[])
{
		BilliardBuddy::help();

		// Read config settings.
		const string inputSettingsFile = argc > 1 ? argv[1] : "config.xml";
		FileStorage fs(inputSettingsFile, FileStorage::READ);
		if (!fs.isOpened())
		{
			std::cout << "Could not open the configuration file: \"" << inputSettingsFile << "\"" << std::endl;
			return -1;
		}
		Settings settings;
		fs["Settings"] >> settings;
		fs.release();

		// Check validity of inputs before training begins.
		if (!settings.goodInput)
		{
			std::cout << "Invalid input detected. Application stopping. " << std::endl;
			return -1;
		}

		// MAIN LOGIC
		BilliardBuddy::process(settings);

		return 0;
}

void BilliardBuddy::process(Settings& settings) {
	bool preprocess = true;

	// Initialize CameraInterface
	CameraInterface cameraInterface = CameraInterface(settings);

	// Initialize PreProcessor
	Mat cameraMatrix, distCoeffs;
	cameraMatrix = settings.getCameraMatrix();
	distCoeffs = settings.getDistCoeffs();
	PreProcessor preProcessor = PreProcessor(cameraMatrix, distCoeffs);

	// Initialize Feature Detector(s)
	PoolTableDetector poolTableDetector = PoolTableDetector();
	CueDetector cueDetector = CueDetector();

	//Initialize Physics Model Calculator
	PhysicsModel physicsModel = PhysicsModel();

	// Initialize Visual Augmentors
	TextAugmentor textAugmentor = TextAugmentor();
	CueAugmentor cueAugmentor = CueAugmentor();

	// Initialize HMD interface.
	HMDInterface hmdInterface = HMDInterface();

	// Processing Loop
	bool result;
	do {
		result = processFrame(preprocess, cameraInterface, preProcessor, poolTableDetector, cueDetector, physicsModel, textAugmentor, cueAugmentor, hmdInterface);
		result = pollKeyboard(preprocess);
	} while (result == true);
}

bool BilliardBuddy::pollKeyboard(bool& preprocess)
{
	// Check for keyboard inputs.
	char key = (char)waitKey(1);
	const char ESC_KEY = 27;
	if (key == 'u')
		preprocess = !preprocess;
	if (key == ESC_KEY)
		return false;

	return true;
}

bool BilliardBuddy::processFrame(bool& preprocess, CameraInterface& cameraInterface, PreProcessor& preProcessor, PoolTableDetector& poolTableDetector, CueDetector& cueDetector, PhysicsModel& physicsModel, TextAugmentor& textAugmentor, CueAugmentor& cueAugmentor, HMDInterface& hmdInterface) {
	// Fetch feed from camera interface.
	Mat leftFrame, rightFrame;
	cameraInterface.getFrames(leftFrame, rightFrame);

	// Pre-process feed.
	if (preprocess)
	{
		preProcessor.preProcess(leftFrame);
		preProcessor.preProcess(rightFrame);
	}

	// Detect features.
	cv::vector<pocket> pocketPoints = poolTableDetector.detectTable(rightFrame, frameIterator);

	//Detect Cue
	if (frameIterator == 1 || frameIterator == 0)
	{
		cueCoords = cueDetector.detect(rightFrame, frameIterator);
	}

	//Detect White Ball
	//TODO
	cv::vector<Vec2i> whiteBall(1);
	whiteBall[0] = { 200, 100 };

	//Detect other balls
	//TODO?? Brian?
	cv::vector<Vec2i> balls(2);
	balls[0] = { 200, 140 };
	balls[1] = { 200, 170 };
	//balls[2] = { 150, 150 };

	// Calculate Physics Model
	//cv::vector<Path> pathVector = physicsModel.calculate(rightFrame, pocketPoints, cueCoords, whiteBall, balls);

	// Visually augment.
	textAugmentor.augment(rightFrame);
	cueAugmentor.augment(rightFrame, cueCoords);
	hmdInterface.drawToHMD(leftFrame, rightFrame);

	if (frameIterator == 7)
	{
		frameIterator = 1;
	}
	else
	{
		frameIterator++;
	}

	// check for errors and return false at some point
	return true;
}

int BilliardBuddy::getFrameIterator()
{
	return frameIterator;
}

void BilliardBuddy::help()
{
	std::cout << "Welcome to the BilliardBuddy trainer!" << std::endl
		<< "Usage: BilliardBuddy.exe <configpath.xml>" << std::endl
		<< "Near the sample file you'll find the configuration file, which has detailed help of "
		"how to edit it.  It may be any OpenCV supported file format XML/YAML." << std::endl;
}

void read(const FileNode& node, Settings& x, const Settings& default_value = Settings())
{
	// This is called when the ">>" operator is used between a FileNode and a Settings.
	if (node.empty())
		x = default_value;
	else
		x.read(node);
}<|endoftext|>


<commit_before>#include <iostream>
#include <cstring>      // Needed for memset
#include <sys/socket.h> // Needed for the socket functions
#include <netdb.h>      // Needed for the socket functions
#include <unistd.h>
#include <assert.h>
#include <memory> // unique_ptr

#include "sim.h"
#include "jsoncpp/json/json.h"

#define PORT "25041"

/**
 * \brief Read from environment variable as string
 */
static char* get_env_str(const char *envname, const char *defaultvalue)
{
    char *env;
    env = getenv (envname);

    if (env==NULL) {

        return (char*) defaultvalue;
    }

    return env;
}

int smlt_tree_parse_wrapper(const char* json_string,
                            unsigned ncores,
                            uint16_t** model,
                            uint32_t** leafs,
                            uint32_t* t_root,
                            uint32_t* len_model)
{
    Json::Value root;
    // Json::CharReaderBuilder rbuilder;
    // rbuilder["collectComments"] = false;
    std::string errs;
    // bool ok = Json::parseFromStream(rbuilder, rec, &root, &errs);

    Json::CharReaderBuilder rbuilder;
    Json::CharReader* reader = rbuilder.newCharReader();

    reader->parse(json_string, json_string+strlen(json_string)-1,
                  &root, &errs);
    // Extract last node
    Json::Value ln = root.get("root", "");
    int lnval = ln.asInt();
    *t_root = (uint32_t)lnval;

    // Extract leaf node

    Json::Value leafs_j = root.get("leaf_nodes", "");
    *leafs = (uint32_t*) malloc(sizeof(uint32_t)*leafs_j.size());
    assert(*leafs != NULL);

    for (unsigned i=0; i<leafs_j.size(); i++) {
        (*leafs)[i] = leafs_j.get(i, Json::Value()).asInt();
    }

    Json::Value elem = root.get("model", "");
    *model = (uint16_t*)  malloc(sizeof(uint16_t)*elem.size()*elem.size());
    assert(*model != NULL);
    int x = 0;
    int y = 0;
    *len_model = elem.size();
    for (Json::ValueIterator i=elem.begin(); i != elem.end(); i++) {
        y = 0;
        Json::Value inner = (*i);
        for (Json::ValueIterator k=inner.begin(); k != inner.end(); k++) {

            Json::Value val = (*k);
            (*model)[x*elem.size()+y] = (uint32_t) val.asInt();
            y++;
        }
        x++;
    }

    return 0;
}

static int smlt_tree_config_request(const char *hostname,
                                    const char* msg,
                                    unsigned ncores,
                                    uint16_t** model,
                                    uint32_t** leafs,
                                    uint32_t* t_root,
                                    uint32_t* len_model)
{

    int status;
    struct addrinfo host_info;       // The struct that getaddrinfo() fills up with data.
    struct addrinfo *host_info_list; // Pointer to the to the linked list of host_info's.

    // The MAN page of getaddrinfo() states "All  the other fields in the structure pointed
    // to by hints must contain either 0 or a null pointer, as appropriate." When a struct
    // is created in c++, it will be given a block of memory. This memory is not nessesary
    // empty. Therefor we use the memset function to make sure all fields are NULL.
    memset(&host_info, 0, sizeof host_info);

    host_info.ai_family = AF_UNSPEC;     // IP version not specified. Can be both.
    host_info.ai_socktype = SOCK_STREAM; // Use SOCK_STREAM for TCP or SOCK_DGRAM for UDP.

    // Now fill up the linked list of host_info structs with google's address information.
    status = getaddrinfo(hostname, PORT, &host_info, &host_info_list);
    // getaddrinfo returns 0 on succes, or some other value when an error occured.
    // (translated into human readable text by the gai_gai_strerror function).
    if (status != 0) {
        std::cout << "getaddrinfo error" << gai_strerror(status) ;
        return 1;
    }

    int socketfd ; // The socket descripter
    socketfd = socket(host_info_list->ai_family, host_info_list->ai_socktype,
                  host_info_list->ai_protocol);
    if (socketfd == -1) {
        std::cout << "socket error " ;
        return 1;
    }

    status = connect(socketfd, host_info_list->ai_addr, host_info_list->ai_addrlen);
    if (status == -1) {
        std::cout << "connect error" ;
        return 1;
    }

    int len = strlen(msg);
    int bytes_sent;

    bytes_sent = send(socketfd, msg, len, 0);
    assert (bytes_sent==len);

    ssize_t bytes_recieved;
    char incomming_data_buffer[1000];

    std::string rec;

    do {
        bytes_recieved = recv(socketfd, incomming_data_buffer,1000, 0);

        // If no data arrives, the program will just wait here until some data arrives.
        if (bytes_recieved > 0) {
            incomming_data_buffer[bytes_recieved] = '\0' ;

            rec.append(incomming_data_buffer);
        }
        else {
            if (bytes_recieved == 0) {
               printf("host shut down \n");
            } else if (bytes_recieved == -1) {
               printf("receive error \n");
               return 1;
            }
        }

    } while(bytes_recieved>0);

    freeaddrinfo(host_info_list);
    shutdown(socketfd, SHUT_RDWR);
    assert(model != NULL);
    char* inp = (char*) rec.c_str();

    return smlt_tree_parse_wrapper(inp, ncores, model, leafs, t_root, len_model);
}

#define NAMELEN 1000U

int smlt_tree_generate_wrapper(unsigned ncores,
                               uint32_t* cores,
                               const char* tree_name,
                               uint16_t** model,
                               uint32_t** leafs,
                               uint32_t* t_root,
                               uint32_t* len_model)
{
    // Ask the Simulator to build a model
    const char *host = get_env_str("SMLT_HOSTNAME", "");
    const char *machine = get_env_str("SMLT_MACHINE", "unknown");

    // Determine hostname of this machine
    char thishost[NAMELEN];
    gethostname(thishost, NAMELEN);

    if (strlen(host)>0) {
        printf("Hostname is %s \n", host);
    } else {
        printf("No hostname give, not contacting generator \n");
        return 1;
    }

    Json::StreamWriterBuilder wbuilder;
    wbuilder["indentatin"] = "\t";

    // Override hostname if given as environment variable
    if (strcmp(machine, "unknown") != 0) {
        printf("Overriding hosname %s --> %s\n", thishost, machine);
        strncpy(thishost, machine, NAMELEN);
    }

    Json::Value root;   // 'root' will contain the root value after parsing.
    root["machine"] = thishost;
    if (tree_name == NULL) {
        root["topology"] = "adaptivetree";
    } else {
        root["topology"] = tree_name;
    }

    Json::Value coreids;

    if (cores != NULL) {
        for (unsigned i=0; i<ncores; i++)
            coreids.append(cores[i]);
    } else {
        for (unsigned i=0; i<ncores; i++)
            coreids.append(i);
    }

    root["cores"] = coreids;

    std::string doc = Json::writeString(wbuilder, root);

    return smlt_tree_config_request(host, doc.c_str(), ncores,
                                    model, leafs, t_root, len_model);
}
<commit_msg>Added env variable SMLT_TOPO to set topology to be generated<commit_after>#include <iostream>
#include <cstring>      // Needed for memset
#include <sys/socket.h> // Needed for the socket functions
#include <netdb.h>      // Needed for the socket functions
#include <unistd.h>
#include <assert.h>
#include <memory> // unique_ptr

#include "sim.h"
#include "jsoncpp/json/json.h"

#define PORT "25041"

/**
 * \brief Read from environment variable as string
 */
static char* get_env_str(const char *envname, const char *defaultvalue)
{
    char *env;
    env = getenv (envname);

    if (env==NULL) {

        return (char*) defaultvalue;
    }

    return env;
}

int smlt_tree_parse_wrapper(const char* json_string,
                            unsigned ncores,
                            uint16_t** model,
                            uint32_t** leafs,
                            uint32_t* t_root,
                            uint32_t* len_model)
{
    Json::Value root;
    // Json::CharReaderBuilder rbuilder;
    // rbuilder["collectComments"] = false;
    std::string errs;
    // bool ok = Json::parseFromStream(rbuilder, rec, &root, &errs);

    Json::CharReaderBuilder rbuilder;
    Json::CharReader* reader = rbuilder.newCharReader();

    reader->parse(json_string, json_string+strlen(json_string)-1,
                  &root, &errs);
    // Extract last node
    Json::Value ln = root.get("root", "");
    int lnval = ln.asInt();
    *t_root = (uint32_t)lnval;

    // Extract leaf node

    Json::Value leafs_j = root.get("leaf_nodes", "");
    *leafs = (uint32_t*) malloc(sizeof(uint32_t)*leafs_j.size());
    assert(*leafs != NULL);

    for (unsigned i=0; i<leafs_j.size(); i++) {
        (*leafs)[i] = leafs_j.get(i, Json::Value()).asInt();
    }

    Json::Value elem = root.get("model", "");
    *model = (uint16_t*)  malloc(sizeof(uint16_t)*elem.size()*elem.size());
    assert(*model != NULL);
    int x = 0;
    int y = 0;
    *len_model = elem.size();
    for (Json::ValueIterator i=elem.begin(); i != elem.end(); i++) {
        y = 0;
        Json::Value inner = (*i);
        for (Json::ValueIterator k=inner.begin(); k != inner.end(); k++) {

            Json::Value val = (*k);
            (*model)[x*elem.size()+y] = (uint32_t) val.asInt();
            y++;
        }
        x++;
    }

    return 0;
}

static int smlt_tree_config_request(const char *hostname,
                                    const char* msg,
                                    unsigned ncores,
                                    uint16_t** model,
                                    uint32_t** leafs,
                                    uint32_t* t_root,
                                    uint32_t* len_model)
{

    int status;
    struct addrinfo host_info;       // The struct that getaddrinfo() fills up with data.
    struct addrinfo *host_info_list; // Pointer to the to the linked list of host_info's.

    // The MAN page of getaddrinfo() states "All  the other fields in the structure pointed
    // to by hints must contain either 0 or a null pointer, as appropriate." When a struct
    // is created in c++, it will be given a block of memory. This memory is not nessesary
    // empty. Therefor we use the memset function to make sure all fields are NULL.
    memset(&host_info, 0, sizeof host_info);

    host_info.ai_family = AF_UNSPEC;     // IP version not specified. Can be both.
    host_info.ai_socktype = SOCK_STREAM; // Use SOCK_STREAM for TCP or SOCK_DGRAM for UDP.

    // Now fill up the linked list of host_info structs with google's address information.
    status = getaddrinfo(hostname, PORT, &host_info, &host_info_list);
    // getaddrinfo returns 0 on succes, or some other value when an error occured.
    // (translated into human readable text by the gai_gai_strerror function).
    if (status != 0) {
        std::cout << "getaddrinfo error" << gai_strerror(status) ;
        return 1;
    }

    int socketfd ; // The socket descripter
    socketfd = socket(host_info_list->ai_family, host_info_list->ai_socktype,
                  host_info_list->ai_protocol);
    if (socketfd == -1) {
        std::cout << "socket error " ;
        return 1;
    }

    status = connect(socketfd, host_info_list->ai_addr, host_info_list->ai_addrlen);
    if (status == -1) {
        std::cout << "connect error" ;
        return 1;
    }

    int len = strlen(msg);
    int bytes_sent;

    bytes_sent = send(socketfd, msg, len, 0);
    assert (bytes_sent==len);

    ssize_t bytes_recieved;
    char incomming_data_buffer[1000];

    std::string rec;

    do {
        bytes_recieved = recv(socketfd, incomming_data_buffer,1000, 0);

        // If no data arrives, the program will just wait here until some data arrives.
        if (bytes_recieved > 0) {
            incomming_data_buffer[bytes_recieved] = '\0' ;

            rec.append(incomming_data_buffer);
        }
        else {
            if (bytes_recieved == 0) {
               printf("host shut down \n");
            } else if (bytes_recieved == -1) {
               printf("receive error \n");
               return 1;
            }
        }

    } while(bytes_recieved>0);

    freeaddrinfo(host_info_list);
    shutdown(socketfd, SHUT_RDWR);
    assert(model != NULL);
    char* inp = (char*) rec.c_str();

    return smlt_tree_parse_wrapper(inp, ncores, model, leafs, t_root, len_model);
}

#define NAMELEN 1000U

int smlt_tree_generate_wrapper(unsigned ncores,
                               uint32_t* cores,
                               const char* tree_name,
                               uint16_t** model,
                               uint32_t** leafs,
                               uint32_t* t_root,
                               uint32_t* len_model)
{
    // Ask the Simulator to build a model
    const char *host = get_env_str("SMLT_HOSTNAME", "");
    const char *machine = get_env_str("SMLT_MACHINE", "unknown");

    // Determine hostname of this machine
    char thishost[NAMELEN];
    gethostname(thishost, NAMELEN);

    if (strlen(host)>0) {
        printf("Hostname is %s \n", host);
    } else {
        printf("No hostname give, not contacting generator \n");
        return 1;
    }

    Json::StreamWriterBuilder wbuilder;
    wbuilder["indentatin"] = "\t";

    // Override hostname if given as environment variable
    if (strcmp(machine, "unknown") != 0) {
        printf("Overriding hosname %s --> %s\n", thishost, machine);
        strncpy(thishost, machine, NAMELEN);
    }

    Json::Value root;   // 'root' will contain the root value after parsing.
    root["machine"] = thishost;

    const char *topo_name;

    if (tree_name == NULL) {
        printf("Getting topo from env string\n");
        topo_name = get_env_str("SMLT_TOPO", "adaptivetree");
    } else {
        topo_name = tree_name;
    }

    root["topology"] = topo_name;
    printf("Requesting topology: %s\n", topo_name);

    Json::Value coreids;

    if (cores != NULL) {
        for (unsigned i=0; i<ncores; i++)
            coreids.append(cores[i]);
    } else {
        for (unsigned i=0; i<ncores; i++)
            coreids.append(i);
    }

    root["cores"] = coreids;

    std::string doc = Json::writeString(wbuilder, root);

    return smlt_tree_config_request(host, doc.c_str(), ncores,
                                    model, leafs, t_root, len_model);
}
<|endoftext|>


<commit_before>#include <cstdlib>

#include "buffer.hh"

namespace mimosa
{
  namespace stream
  {
    Buffer::Buffer(uint64_t size)
      : size_(size),
        data_(reinterpret_cast<char *>(::malloc(size + 4)))
    {
      data_[size_ - 3] = 0;
      data_[size_ - 2] = 0;
      data_[size_ - 1] = 0;
      data_[size_]     = 0;
    }

    Buffer::~Buffer()
    {
      free(data_);
      size_ = 0;
      data_ = nullptr;
    }

    void
    Buffer::resize(uint64_t size)
    {
      data_            = reinterpret_cast<char *>(::realloc(data_, size + 4));
      size_            = size;
      data_[size_ - 3] = 0;
      data_[size_ - 2] = 0;
      data_[size_ - 1] = 0;
      data_[size_]     = 0;
    }
  }
}
<commit_msg>Buffer has now 4 trailling null bytes which make more sense in case of utf-16 or utf-32 buffer.<commit_after>#include <cstdlib>

#include "buffer.hh"

namespace mimosa
{
  namespace stream
  {
    Buffer::Buffer(uint64_t size)
      : size_(size),
        data_(reinterpret_cast<char *>(::malloc(size + 4)))
    {
      data_[size_ + 3] = 0;
      data_[size_ + 2] = 0;
      data_[size_ + 1] = 0;
      data_[size_]     = 0;
    }

    Buffer::~Buffer()
    {
      free(data_);
      size_ = 0;
      data_ = nullptr;
    }

    void
    Buffer::resize(uint64_t size)
    {
      data_            = reinterpret_cast<char *>(::realloc(data_, size + 4));
      size_            = size;
      data_[size_ + 3] = 0;
      data_[size_ + 2] = 0;
      data_[size_ + 1] = 0;
      data_[size_]     = 0;
    }
  }
}
<|endoftext|>


<commit_before><commit_msg>Edit a comment.<commit_after><|endoftext|>


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

  Program:   Visualization Toolkit
  Module:    vtkContextMouseEvent.cxx

  Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
  All rights reserved.
  See Copyright.txt or http://www.kitware.com/Copyright.htm for details.

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

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

#include "vtkContextMouseEvent.h"
#include "vtkRenderWindowInteractor.h"

int vtkContextMouseEvent::GetModifiers() const
{
  int modifier = vtkContextMouseEvent::NO_MODIFIER;
  if (this->Interactor)
    {
    if (this->Interactor->GetAltKey() > 0)
      {
      modifier |= vtkContextMouseEvent::ALT_MODIFIER;
      }
    if (this->Interactor->GetShiftKey() > 0)
      {
      modifier |= vtkContextMouseEvent::SHIFT_MODIFIER;
      }
    if (this->Interactor->GetControlKey() > 0)
      {
      modifier |= vtkContextMouseEvent::CONTROL_MODIFIER;
      }
    }
  return modifier;
}
<commit_msg>COMP: Fix AIX include order issues.<commit_after>/*=========================================================================

  Program:   Visualization Toolkit
  Module:    vtkContextMouseEvent.cxx

  Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
  All rights reserved.
  See Copyright.txt or http://www.kitware.com/Copyright.htm for details.

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

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

#include "vtkRenderWindowInteractor.h" // AIX include order issues.
#include "vtkContextMouseEvent.h"

int vtkContextMouseEvent::GetModifiers() const
{
  int modifier = vtkContextMouseEvent::NO_MODIFIER;
  if (this->Interactor)
    {
    if (this->Interactor->GetAltKey() > 0)
      {
      modifier |= vtkContextMouseEvent::ALT_MODIFIER;
      }
    if (this->Interactor->GetShiftKey() > 0)
      {
      modifier |= vtkContextMouseEvent::SHIFT_MODIFIER;
      }
    if (this->Interactor->GetControlKey() > 0)
      {
      modifier |= vtkContextMouseEvent::CONTROL_MODIFIER;
      }
    }
  return modifier;
}
<|endoftext|>


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

  Program:   Visualization Toolkit
  Module:    vtkScatterPlotMatrix.cxx

  Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
  All rights reserved.
  See Copyright.txt or http://www.kitware.com/Copyright.htm for details.

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

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

#include "vtkScatterPlotMatrix.h"

#include "vtkTable.h"
#include "vtkFloatArray.h"
#include "vtkIntArray.h"
#include "vtkChartXY.h"
#include "vtkPlot.h"
#include "vtkAxis.h"
#include "vtkStdString.h"
#include "vtkStringArray.h"
#include "vtkNew.h"
#include "vtkMathUtilities.h"
#include "vtkObjectFactory.h"

class vtkScatterPlotMatrix::PIMPL
{
public:
  PIMPL() : VisibleColumnsModified(true), BigChart(NULL)
  {
  }

  ~PIMPL()
  {
  }

  vtkNew<vtkTable> Histogram;
  bool VisibleColumnsModified;
  vtkChart* BigChart;
};

namespace
{

int NumberOfBins = 10;

// This is just here for now - quick and dirty historgram calculations...
bool PopulateHistograms(vtkTable *input, vtkTable *output, vtkStringArray *s)
{
  // The output table will have the twice the number of columns, they will be
  // the x and y for input column. This is the bin centers, and the population.
  for (vtkIdType i = output->GetNumberOfColumns() - 1; i >= 0; --i)
    {
    output->RemoveColumn(i);
    }
  for (vtkIdType i = 0; i < s->GetNumberOfTuples(); ++i)
    {
    double minmax[2] = { 0.0, 0.0 };
    vtkStdString name(s->GetValue(i));
    vtkDataArray *in =
        vtkDataArray::SafeDownCast(input->GetColumnByName(name.c_str()));
    if (in)
      {
      // The bin values are the centers, extending +/- half an inc either side
      in->GetRange(minmax);
      if (minmax[0] == minmax[1])
        {
        minmax[1] = minmax[0] + 1.0;
        }
      double inc = (minmax[1] - minmax[0]) / NumberOfBins;
      double halfInc = inc / 2.0;
      vtkNew<vtkFloatArray> extents;
      extents->SetName(vtkStdString(name + "_extents").c_str());
      extents->SetNumberOfTuples(NumberOfBins);
      float *centers = static_cast<float *>(extents->GetVoidPointer(0));
      for (int j = 0; j < NumberOfBins; ++j)
        {
        extents->SetValue(j, minmax[0] + j * inc);
        }
      vtkNew<vtkIntArray> populations;
      populations->SetName(vtkStdString(name + "_pops").c_str());
      populations->SetNumberOfTuples(NumberOfBins);
      int *pops = static_cast<int *>(populations->GetVoidPointer(0));
      for (int k = 0; k < NumberOfBins; ++k)
        {
        pops[k] = 0;
        }
      for (vtkIdType j = 0; j < in->GetNumberOfTuples(); ++j)
        {
        double v(0.0);
        in->GetTuple(j, &v);
        for (int k = 0; k < NumberOfBins; ++k)
          {
          if (vtkMathUtilities::FuzzyCompare(v, double(centers[k]), halfInc))
            {
            ++pops[k];
            break;
            }
          }
        }
      output->AddColumn(extents.GetPointer());
      output->AddColumn(populations.GetPointer());
      }
    }
  return true;
}
}

vtkStandardNewMacro(vtkScatterPlotMatrix)

vtkScatterPlotMatrix::vtkScatterPlotMatrix()
{
  this->Private = new PIMPL;
}

vtkScatterPlotMatrix::~vtkScatterPlotMatrix()
{
  delete this->Private;
}

void vtkScatterPlotMatrix::Update()
{
  if (this->Private->VisibleColumnsModified)
    {
    // We need to handle layout changes due to modified visibility.
    // Build up our histograms data before updating the layout.
    PopulateHistograms(this->Input.GetPointer(),
                       this->Private->Histogram.GetPointer(),
                       this->VisibleColumns.GetPointer());
    this->UpdateLayout();
    this->Private->VisibleColumnsModified = false;
    }
}

bool vtkScatterPlotMatrix::Paint(vtkContext2D *painter)
{
  this->Update();
  return Superclass::Paint(painter);
}

bool vtkScatterPlotMatrix::SetActivePlot(const vtkVector2i &pos)
{
  if (pos.X() + pos.Y() + 1 < this->Size.X() && pos.X() < this->Size.X() &&
      pos.Y() < this->Size.Y())
    {
    // The supplied index is valid (in the lower quadrant).
    this->ActivePlot = pos;
    if (this->Private->BigChart)
      {
      vtkPlot *plot = this->Private->BigChart->GetPlot(0);
      if (!plot)
        {
        plot = this->Private->BigChart->AddPlot(vtkChart::POINTS);
        vtkChartXY *xy = vtkChartXY::SafeDownCast(this->Private->BigChart);
        if (xy)
          {
          xy->SetPlotCorner(plot, 2);
          }
        }
      plot->SetInput(this->Input.GetPointer(),
                     this->VisibleColumns->GetValue(pos.X()),
                     this->VisibleColumns->GetValue(this->Size.X() -
                                                    pos.Y() - 1));
      }
    return true;
    }
  else
    {
    return false;
    }
}

vtkVector2i vtkScatterPlotMatrix::GetActivePlot()
{
  return this->ActivePlot;
}

void vtkScatterPlotMatrix::SetInput(vtkTable *table)
{
  if(table && table->GetNumberOfRows() == 0)
    {
    // do nothing if the table is emtpy
    return;
    }

  if (this->Input != table)
    {
    // Set the input, then update the size of the scatter plot matrix, set
    // their inputs and all the other stuff needed.
    this->Input = table;
    this->Modified();

    if (table == NULL)
      {
      this->SetSize(vtkVector2i(0, 0));
      this->SetColumnVisibilityAll(true);
      return;
      }

    int n = static_cast<int>(this->Input->GetNumberOfColumns());
    this->SetColumnVisibilityAll(true);
    this->SetSize(vtkVector2i(n, n));
    }
}

void vtkScatterPlotMatrix::SetColumnVisibility(const vtkStdString &name,
                                               bool visible)
{
  if (visible)
    {
    for (vtkIdType i = 0; i < this->VisibleColumns->GetNumberOfTuples(); ++i)
      {
      if (this->VisibleColumns->GetValue(i) == name)
        {
        // Already there, nothing more needs to be done
        return;
        }
      }
    // Add the column to the end of the list
    this->VisibleColumns->InsertNextValue(name);
    this->Private->VisibleColumnsModified = true;
    this->SetSize(vtkVector2i(this->VisibleColumns->GetNumberOfTuples(),
                              this->VisibleColumns->GetNumberOfTuples()));
    this->Modified();
    }
  else
    {
    // Remove the value if present
    for (vtkIdType i = 0; i < this->VisibleColumns->GetNumberOfTuples(); ++i)
      {
      if (this->VisibleColumns->GetValue(i) == name)
        {
        // Move all the later elements down by one, and reduce the size
        while (i < this->VisibleColumns->GetNumberOfTuples()-1)
          {
          this->VisibleColumns->SetValue(i,
                                         this->VisibleColumns->GetValue(i+1));
          ++i;
          }
        this->VisibleColumns->SetNumberOfTuples(
            this->VisibleColumns->GetNumberOfTuples()-1);
        this->SetSize(vtkVector2i(this->VisibleColumns->GetNumberOfTuples(),
                                  this->VisibleColumns->GetNumberOfTuples()));
        this->Private->VisibleColumnsModified = true;
        this->Modified();
        return;
        }
      }
    }
}

bool vtkScatterPlotMatrix::GetColumnVisibility(const vtkStdString &name)
{
  for (vtkIdType i = 0; i < this->VisibleColumns->GetNumberOfTuples(); ++i)
    {
    if (this->VisibleColumns->GetValue(i) == name)
      {
      return true;
      }
    }
  return false;
}

void vtkScatterPlotMatrix::SetColumnVisibilityAll(bool visible)
{
  if (visible && this->Input)
    {
    vtkIdType n = this->Input->GetNumberOfColumns();
    this->VisibleColumns->SetNumberOfTuples(n);
    for (vtkIdType i = 0; i < n; ++i)
      {
      this->VisibleColumns->SetValue(i, this->Input->GetColumnName(i));
      }
    }
  else
    {
    this->SetSize(vtkVector2i(0, 0));
    this->VisibleColumns->SetNumberOfTuples(0);
    }

  this->Private->VisibleColumnsModified = true;
}

vtkStringArray* vtkScatterPlotMatrix::GetVisibleColumns()
{
  return this->VisibleColumns.GetPointer();
}

void vtkScatterPlotMatrix::UpdateLayout()
{
  // We want scatter plots on the lower-left triangle, then histograms along
  // the diagonal and a big plot in the top-right. The basic layout is,
  //
  // 0 H   +++
  // 1 S H +++
  // 2 S S H
  // 3 S S S H
  //   0 1 2 3
  //
  // Where the indices are those of the columns. The indices of the charts
  // originate in the bottom-left.
  int n = this->Size.X();
  for (int i = 0; i < n; ++i)
    {
    for (int j = 0; j < n; ++j)
      {
      vtkVector2i pos(i, j);
      if (i + j + 1 < n)
        {
        // Lower-left triangle - scatter plots.
        vtkPlot *plot = this->GetChart(pos)->AddPlot(vtkChart::POINTS);
        plot->SetInput(this->Input.GetPointer(), i, n - j - 1);
        }
      else if (i == n - j - 1)
        {
        // We are on the diagonal - need a histogram plot.
        vtkPlot *plot = this->GetChart(pos)->AddPlot(vtkChart::BAR);
        vtkStdString name(this->VisibleColumns->GetValue(i));
        plot->SetInput(this->Private->Histogram.GetPointer(),
                       name + "_extents", name + "_pops");
        vtkAxis *axis = this->GetChart(pos)->GetAxis(vtkAxis::TOP);
        axis->SetTitle(name.c_str());
        if (i != n - 1)
          {
          axis->SetBehavior(vtkAxis::FIXED);
          }
        // Set the plot corner to the top-right
        vtkChartXY *xy = vtkChartXY::SafeDownCast(this->GetChart(pos));
        if (xy)
          {
          xy->SetPlotCorner(plot, 2);
          }
        }
      else if (i == static_cast<int>(n / 2.0) + n % 2 && i == j)
        {
        // This big plot in the top-right
        this->Private->BigChart = this->GetChart(pos);
        this->SetChartSpan(pos, vtkVector2i(n - i, n - j));
        this->SetActivePlot(vtkVector2i(0, n - 2));
        }
      // Only show bottom axis label for bottom plots
      if (j > 0)
        {
        vtkAxis *axis = this->GetChart(pos)->GetAxis(vtkAxis::BOTTOM);
        axis->SetTitle("");
        axis->SetLabelsVisible(false);
        axis->SetBehavior(vtkAxis::FIXED);
        }
      else
        {
        vtkAxis *axis = this->GetChart(pos)->GetAxis(vtkAxis::BOTTOM);
        axis->SetTitle(this->VisibleColumns->GetValue(i));
        this->AttachAxisRangeListener(axis);
        }
      // Only show the left axis labels for left-most plots
      if (i > 0)
        {
        vtkAxis *axis = this->GetChart(pos)->GetAxis(vtkAxis::LEFT);
        axis->SetTitle("");
        axis->SetLabelsVisible(false);
        axis->SetBehavior(vtkAxis::FIXED);
        }
      else
        {
        vtkAxis *axis = this->GetChart(pos)->GetAxis(vtkAxis::LEFT);
        axis->SetTitle(this->VisibleColumns->GetValue(n - j - 1));
        this->AttachAxisRangeListener(axis);
        }
      }
    }
}

void vtkScatterPlotMatrix::AttachAxisRangeListener(vtkAxis* axis)
{
  axis->AddObserver(vtkChart::UpdateRange, this,
                    &vtkScatterPlotMatrix::AxisRangeForwarderCallback);
}

void vtkScatterPlotMatrix::AxisRangeForwarderCallback(vtkObject*,
                                                      unsigned long, void*)
{
  // Only set on the end axes, and propagated to all other matching axes.
  double r[2];
  int n = this->GetSize().X() - 1;
  for (int i = 0; i < n; ++i)
    {
    this->GetChart(vtkVector2i(i, 0))->GetAxis(vtkAxis::BOTTOM)->GetRange(r);
    for (int j = 1; j < n - i; ++j)
      {
      this->GetChart(vtkVector2i(i, j))->GetAxis(vtkAxis::BOTTOM)->SetRange(r);
      }
    this->GetChart(vtkVector2i(i, n-i))->GetAxis(vtkAxis::TOP)->SetRange(r);
    this->GetChart(vtkVector2i(0, i))->GetAxis(vtkAxis::LEFT)->GetRange(r);
    for (int j = 1; j < n - i; ++j)
      {
      this->GetChart(vtkVector2i(j, i))->GetAxis(vtkAxis::LEFT)->SetRange(r);
      }
    }
}

void vtkScatterPlotMatrix::PrintSelf(ostream &os, vtkIndent indent)
{
  Superclass::PrintSelf(os, indent);
}
<commit_msg>BUG: Delete all charts, then resize.<commit_after>/*=========================================================================

  Program:   Visualization Toolkit
  Module:    vtkScatterPlotMatrix.cxx

  Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
  All rights reserved.
  See Copyright.txt or http://www.kitware.com/Copyright.htm for details.

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

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

#include "vtkScatterPlotMatrix.h"

#include "vtkTable.h"
#include "vtkFloatArray.h"
#include "vtkIntArray.h"
#include "vtkChartXY.h"
#include "vtkPlot.h"
#include "vtkAxis.h"
#include "vtkStdString.h"
#include "vtkStringArray.h"
#include "vtkNew.h"
#include "vtkMathUtilities.h"
#include "vtkObjectFactory.h"

class vtkScatterPlotMatrix::PIMPL
{
public:
  PIMPL() : VisibleColumnsModified(true), BigChart(NULL)
  {
  }

  ~PIMPL()
  {
  }

  vtkNew<vtkTable> Histogram;
  bool VisibleColumnsModified;
  vtkChart* BigChart;
};

namespace
{

int NumberOfBins = 10;

// This is just here for now - quick and dirty historgram calculations...
bool PopulateHistograms(vtkTable *input, vtkTable *output, vtkStringArray *s)
{
  // The output table will have the twice the number of columns, they will be
  // the x and y for input column. This is the bin centers, and the population.
  for (vtkIdType i = output->GetNumberOfColumns() - 1; i >= 0; --i)
    {
    output->RemoveColumn(i);
    }
  for (vtkIdType i = 0; i < s->GetNumberOfTuples(); ++i)
    {
    double minmax[2] = { 0.0, 0.0 };
    vtkStdString name(s->GetValue(i));
    vtkDataArray *in =
        vtkDataArray::SafeDownCast(input->GetColumnByName(name.c_str()));
    if (in)
      {
      // The bin values are the centers, extending +/- half an inc either side
      in->GetRange(minmax);
      if (minmax[0] == minmax[1])
        {
        minmax[1] = minmax[0] + 1.0;
        }
      double inc = (minmax[1] - minmax[0]) / NumberOfBins;
      double halfInc = inc / 2.0;
      vtkNew<vtkFloatArray> extents;
      extents->SetName(vtkStdString(name + "_extents").c_str());
      extents->SetNumberOfTuples(NumberOfBins);
      float *centers = static_cast<float *>(extents->GetVoidPointer(0));
      for (int j = 0; j < NumberOfBins; ++j)
        {
        extents->SetValue(j, minmax[0] + j * inc);
        }
      vtkNew<vtkIntArray> populations;
      populations->SetName(vtkStdString(name + "_pops").c_str());
      populations->SetNumberOfTuples(NumberOfBins);
      int *pops = static_cast<int *>(populations->GetVoidPointer(0));
      for (int k = 0; k < NumberOfBins; ++k)
        {
        pops[k] = 0;
        }
      for (vtkIdType j = 0; j < in->GetNumberOfTuples(); ++j)
        {
        double v(0.0);
        in->GetTuple(j, &v);
        for (int k = 0; k < NumberOfBins; ++k)
          {
          if (vtkMathUtilities::FuzzyCompare(v, double(centers[k]), halfInc))
            {
            ++pops[k];
            break;
            }
          }
        }
      output->AddColumn(extents.GetPointer());
      output->AddColumn(populations.GetPointer());
      }
    }
  return true;
}
}

vtkStandardNewMacro(vtkScatterPlotMatrix)

vtkScatterPlotMatrix::vtkScatterPlotMatrix()
{
  this->Private = new PIMPL;
}

vtkScatterPlotMatrix::~vtkScatterPlotMatrix()
{
  delete this->Private;
}

void vtkScatterPlotMatrix::Update()
{
  if (this->Private->VisibleColumnsModified)
    {
    // We need to handle layout changes due to modified visibility.
    // Build up our histograms data before updating the layout.
    PopulateHistograms(this->Input.GetPointer(),
                       this->Private->Histogram.GetPointer(),
                       this->VisibleColumns.GetPointer());
    this->UpdateLayout();
    this->Private->VisibleColumnsModified = false;
    }
}

bool vtkScatterPlotMatrix::Paint(vtkContext2D *painter)
{
  this->Update();
  return Superclass::Paint(painter);
}

bool vtkScatterPlotMatrix::SetActivePlot(const vtkVector2i &pos)
{
  if (pos.X() + pos.Y() + 1 < this->Size.X() && pos.X() < this->Size.X() &&
      pos.Y() < this->Size.Y())
    {
    // The supplied index is valid (in the lower quadrant).
    this->ActivePlot = pos;
    if (this->Private->BigChart)
      {
      vtkPlot *plot = this->Private->BigChart->GetPlot(0);
      if (!plot)
        {
        plot = this->Private->BigChart->AddPlot(vtkChart::POINTS);
        vtkChartXY *xy = vtkChartXY::SafeDownCast(this->Private->BigChart);
        if (xy)
          {
          xy->SetPlotCorner(plot, 2);
          }
        }
      plot->SetInput(this->Input.GetPointer(),
                     this->VisibleColumns->GetValue(pos.X()),
                     this->VisibleColumns->GetValue(this->Size.X() -
                                                    pos.Y() - 1));
      }
    return true;
    }
  else
    {
    return false;
    }
}

vtkVector2i vtkScatterPlotMatrix::GetActivePlot()
{
  return this->ActivePlot;
}

void vtkScatterPlotMatrix::SetInput(vtkTable *table)
{
  if(table && table->GetNumberOfRows() == 0)
    {
    // do nothing if the table is emtpy
    return;
    }

  if (this->Input != table)
    {
    // Set the input, then update the size of the scatter plot matrix, set
    // their inputs and all the other stuff needed.
    this->Input = table;
    this->SetSize(vtkVector2i(0, 0));
    this->Modified();

    if (table == NULL)
      {
      this->SetColumnVisibilityAll(true);
      return;
      }

    int n = static_cast<int>(this->Input->GetNumberOfColumns());
    this->SetColumnVisibilityAll(true);
    this->SetSize(vtkVector2i(n, n));
    }
}

void vtkScatterPlotMatrix::SetColumnVisibility(const vtkStdString &name,
                                               bool visible)
{
  if (visible)
    {
    for (vtkIdType i = 0; i < this->VisibleColumns->GetNumberOfTuples(); ++i)
      {
      if (this->VisibleColumns->GetValue(i) == name)
        {
        // Already there, nothing more needs to be done
        return;
        }
      }
    // Add the column to the end of the list
    this->VisibleColumns->InsertNextValue(name);
    this->Private->VisibleColumnsModified = true;
    this->SetSize(vtkVector2i(0, 0));
    this->SetSize(vtkVector2i(this->VisibleColumns->GetNumberOfTuples(),
                              this->VisibleColumns->GetNumberOfTuples()));
    this->Modified();
    }
  else
    {
    // Remove the value if present
    for (vtkIdType i = 0; i < this->VisibleColumns->GetNumberOfTuples(); ++i)
      {
      if (this->VisibleColumns->GetValue(i) == name)
        {
        // Move all the later elements down by one, and reduce the size
        while (i < this->VisibleColumns->GetNumberOfTuples()-1)
          {
          this->VisibleColumns->SetValue(i,
                                         this->VisibleColumns->GetValue(i+1));
          ++i;
          }
        this->VisibleColumns->SetNumberOfTuples(
            this->VisibleColumns->GetNumberOfTuples()-1);
        this->SetSize(vtkVector2i(0, 0));
        this->SetSize(vtkVector2i(this->VisibleColumns->GetNumberOfTuples(),
                                  this->VisibleColumns->GetNumberOfTuples()));
        this->Private->VisibleColumnsModified = true;
        this->Modified();
        return;
        }
      }
    }
}

bool vtkScatterPlotMatrix::GetColumnVisibility(const vtkStdString &name)
{
  for (vtkIdType i = 0; i < this->VisibleColumns->GetNumberOfTuples(); ++i)
    {
    if (this->VisibleColumns->GetValue(i) == name)
      {
      return true;
      }
    }
  return false;
}

void vtkScatterPlotMatrix::SetColumnVisibilityAll(bool visible)
{
  if (visible && this->Input)
    {
    vtkIdType n = this->Input->GetNumberOfColumns();
    this->VisibleColumns->SetNumberOfTuples(n);
    for (vtkIdType i = 0; i < n; ++i)
      {
      this->VisibleColumns->SetValue(i, this->Input->GetColumnName(i));
      }
    }
  else
    {
    this->SetSize(vtkVector2i(0, 0));
    this->VisibleColumns->SetNumberOfTuples(0);
    }

  this->Private->VisibleColumnsModified = true;
}

vtkStringArray* vtkScatterPlotMatrix::GetVisibleColumns()
{
  return this->VisibleColumns.GetPointer();
}

void vtkScatterPlotMatrix::UpdateLayout()
{
  // We want scatter plots on the lower-left triangle, then histograms along
  // the diagonal and a big plot in the top-right. The basic layout is,
  //
  // 0 H   +++
  // 1 S H +++
  // 2 S S H
  // 3 S S S H
  //   0 1 2 3
  //
  // Where the indices are those of the columns. The indices of the charts
  // originate in the bottom-left.
  int n = this->Size.X();
  for (int i = 0; i < n; ++i)
    {
    for (int j = 0; j < n; ++j)
      {
      vtkVector2i pos(i, j);
      if (i + j + 1 < n)
        {
        // Lower-left triangle - scatter plots.
        vtkPlot *plot = this->GetChart(pos)->AddPlot(vtkChart::POINTS);
        plot->SetInput(this->Input.GetPointer(), i, n - j - 1);
        }
      else if (i == n - j - 1)
        {
        // We are on the diagonal - need a histogram plot.
        vtkPlot *plot = this->GetChart(pos)->AddPlot(vtkChart::BAR);
        vtkStdString name(this->VisibleColumns->GetValue(i));
        plot->SetInput(this->Private->Histogram.GetPointer(),
                       name + "_extents", name + "_pops");
        vtkAxis *axis = this->GetChart(pos)->GetAxis(vtkAxis::TOP);
        axis->SetTitle(name.c_str());
        if (i != n - 1)
          {
          axis->SetBehavior(vtkAxis::FIXED);
          }
        // Set the plot corner to the top-right
        vtkChartXY *xy = vtkChartXY::SafeDownCast(this->GetChart(pos));
        if (xy)
          {
          xy->SetPlotCorner(plot, 2);
          }
        }
      else if (i == static_cast<int>(n / 2.0) + n % 2 && i == j)
        {
        // This big plot in the top-right
        this->Private->BigChart = this->GetChart(pos);
        this->SetChartSpan(pos, vtkVector2i(n - i, n - j));
        this->SetActivePlot(vtkVector2i(0, n - 2));
        }
      // Only show bottom axis label for bottom plots
      if (j > 0)
        {
        vtkAxis *axis = this->GetChart(pos)->GetAxis(vtkAxis::BOTTOM);
        axis->SetTitle("");
        axis->SetLabelsVisible(false);
        axis->SetBehavior(vtkAxis::FIXED);
        }
      else
        {
        vtkAxis *axis = this->GetChart(pos)->GetAxis(vtkAxis::BOTTOM);
        axis->SetTitle(this->VisibleColumns->GetValue(i));
        this->AttachAxisRangeListener(axis);
        }
      // Only show the left axis labels for left-most plots
      if (i > 0)
        {
        vtkAxis *axis = this->GetChart(pos)->GetAxis(vtkAxis::LEFT);
        axis->SetTitle("");
        axis->SetLabelsVisible(false);
        axis->SetBehavior(vtkAxis::FIXED);
        }
      else
        {
        vtkAxis *axis = this->GetChart(pos)->GetAxis(vtkAxis::LEFT);
        axis->SetTitle(this->VisibleColumns->GetValue(n - j - 1));
        this->AttachAxisRangeListener(axis);
        }
      }
    }
}

void vtkScatterPlotMatrix::AttachAxisRangeListener(vtkAxis* axis)
{
  axis->AddObserver(vtkChart::UpdateRange, this,
                    &vtkScatterPlotMatrix::AxisRangeForwarderCallback);
}

void vtkScatterPlotMatrix::AxisRangeForwarderCallback(vtkObject*,
                                                      unsigned long, void*)
{
  // Only set on the end axes, and propagated to all other matching axes.
  double r[2];
  int n = this->GetSize().X() - 1;
  for (int i = 0; i < n; ++i)
    {
    this->GetChart(vtkVector2i(i, 0))->GetAxis(vtkAxis::BOTTOM)->GetRange(r);
    for (int j = 1; j < n - i; ++j)
      {
      this->GetChart(vtkVector2i(i, j))->GetAxis(vtkAxis::BOTTOM)->SetRange(r);
      }
    this->GetChart(vtkVector2i(i, n-i))->GetAxis(vtkAxis::TOP)->SetRange(r);
    this->GetChart(vtkVector2i(0, i))->GetAxis(vtkAxis::LEFT)->GetRange(r);
    for (int j = 1; j < n - i; ++j)
      {
      this->GetChart(vtkVector2i(j, i))->GetAxis(vtkAxis::LEFT)->SetRange(r);
      }
    }
}

void vtkScatterPlotMatrix::PrintSelf(ostream &os, vtkIndent indent)
{
  Superclass::PrintSelf(os, indent);
}
<|endoftext|>


<commit_before>/**
 * Clever programming language
 * Copyright (c) Clever Team
 *
 * This file is distributed under the MIT license. See LICENSE for details.
 */

#include "core/cthread.h"

namespace clever {
CCondition::CCondition()
{
	pthread_cond_init(&condition, NULL);
}

CCondition::~CCondition()
{
	pthread_cond_destroy(&condition);
}

bool CCondition::signal()
{
	return pthread_cond_signal(&condition) == 0;
}

bool CCondition::broadcast()
{
	return pthread_cond_broadcast(&condition) == 0;
}

bool CCondition::wait(CMutex& m)
{
	return pthread_cond_wait(&condition, &m.m_mut) == 0;
}

CMutex::CMutex()
{
#ifdef CLEVER_THREADS
# ifndef CLEVER_WIN32
	pthread_mutex_init(&m_mut, NULL);
# else
	m_mut = CreateMutex(NULL, FALSE, NULL);
# endif
#endif
}

CMutex::~CMutex()
{
#ifdef CLEVER_THREADS
# ifndef CLEVER_WIN32
	pthread_mutex_destroy(&m_mut);
# else
	CloseHandle(m_mut);
# endif
#endif
}

bool CMutex::lock()
{
#ifdef CLEVER_THREADS
# ifndef CLEVER_WIN32
	return pthread_mutex_lock(&m_mut) == 0;
# else
	WaitForSingleObject(m_mut, INFINITE);
# endif
#endif
}

bool CMutex::trylock()
{
	return pthread_mutex_trylock(&m_mut) == 0;
}

bool CMutex::unlock()
{
#ifdef CLEVER_THREADS
# ifndef CLEVER_WIN32
	return pthread_mutex_unlock(&m_mut) == 0;
# else
	ReleaseMutex(m_mut);
# endif
#endif
}

void CThread::create(ThreadFunc thread_func, void* args)
{
#ifdef CLEVER_THREADS
# ifndef CLEVER_WIN32
	pthread_attr_t attr;
	pthread_attr_init(&attr);
	pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);

	pthread_create(&t_handler, &attr, thread_func, args);

	pthread_attr_destroy(&attr);
# else
	t_handler = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)thread_func, args, 0, NULL);
# endif
#endif

	m_is_running = true;
}

int CThread::wait()
{
#ifdef CLEVER_THREADS
	int status;

#ifndef CLEVER_WIN32
	status = pthread_join(t_handler, NULL);
#else
	status = WaitForSingleObject(t_handler, INFINITE);
	status = (status != WAIT_FAILED ? 0x0 : status);
	CloseHandle(t_handler);
#endif
	m_is_running = false;
	return status;
#else
	return 0;
#endif

}

} // clever
<commit_msg>- Cosmetics<commit_after>/**
 * Clever programming language
 * Copyright (c) Clever Team
 *
 * This file is distributed under the MIT license. See LICENSE for details.
 */

#include "core/cthread.h"

namespace clever {

CCondition::CCondition()
{
	pthread_cond_init(&condition, NULL);
}

CCondition::~CCondition()
{
	pthread_cond_destroy(&condition);
}

bool CCondition::signal()
{
	return pthread_cond_signal(&condition) == 0;
}

bool CCondition::broadcast()
{
	return pthread_cond_broadcast(&condition) == 0;
}

bool CCondition::wait(CMutex& m)
{
	return pthread_cond_wait(&condition, &m.m_mut) == 0;
}

CMutex::CMutex()
{
#ifdef CLEVER_THREADS
# ifndef CLEVER_WIN32
	pthread_mutex_init(&m_mut, NULL);
# else
	m_mut = CreateMutex(NULL, FALSE, NULL);
# endif
#endif
}

CMutex::~CMutex()
{
#ifdef CLEVER_THREADS
# ifndef CLEVER_WIN32
	pthread_mutex_destroy(&m_mut);
# else
	CloseHandle(m_mut);
# endif
#endif
}

bool CMutex::lock()
{
#ifdef CLEVER_THREADS
# ifndef CLEVER_WIN32
	return pthread_mutex_lock(&m_mut) == 0;
# else
	WaitForSingleObject(m_mut, INFINITE);
# endif
#endif
}

bool CMutex::trylock()
{
	return pthread_mutex_trylock(&m_mut) == 0;
}

bool CMutex::unlock()
{
#ifdef CLEVER_THREADS
# ifndef CLEVER_WIN32
	return pthread_mutex_unlock(&m_mut) == 0;
# else
	ReleaseMutex(m_mut);
# endif
#endif
}

void CThread::create(ThreadFunc thread_func, void* args)
{
#ifdef CLEVER_THREADS
# ifndef CLEVER_WIN32
	pthread_attr_t attr;
	pthread_attr_init(&attr);
	pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);

	pthread_create(&t_handler, &attr, thread_func, args);

	pthread_attr_destroy(&attr);
# else
	t_handler = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)thread_func, args, 0, NULL);
# endif
#endif
	m_is_running = true;
}

int CThread::wait()
{
#ifdef CLEVER_THREADS
	int status;

#ifndef CLEVER_WIN32
	status = pthread_join(t_handler, NULL);
#else
	status = WaitForSingleObject(t_handler, INFINITE);
	status = (status != WAIT_FAILED ? 0x0 : status);
	CloseHandle(t_handler);
#endif
	m_is_running = false;
	return status;
#else
	return 0;
#endif
}

} // clever
<|endoftext|>