<commit_before>/***************************************************************************
 *   Copyright (c) 2004 Werner Mayer <wmayer[at]users.sourceforge.net>     *
 *                                                                         *
 *   This file is part of the FreeCAD CAx development system.              *
 *                                                                         *
 *   This library is free software; you can redistribute it and/or         *
 *   modify it under the terms of the GNU Library General Public           *
 *   License as published by the Free Software Foundation; either          *
 *   version 2 of the License, or (at your option) any later version.      *
 *                                                                         *
 *   This library  is distributed in the hope that it will be useful,      *
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
 *   GNU Library General Public License for more details.                  *
 *                                                                         *
 *   You should have received a copy of the GNU Library General Public     *
 *   License along with this library; see the file COPYING.LIB. If not,    *
 *   write to the Free Software Foundation, Inc., 59 Temple Place,         *
 *   Suite 330, Boston, MA  02111-1307, USA                                *
 *                                                                         *
 ***************************************************************************/

#include "PreCompiled.h"
#ifndef _PreComp_
# include <QApplication>
# include <QClipboard>
# include <QMutex>
# include <QProcess>
# include <QSysInfo>
# include <QTextStream>
# include <QWaitCondition>
# include <Python.h>
# include <Inventor/C/basic.h>
# include <Inventor/Qt/SoQtBasic.h>
#endif

#include "Splashscreen.h"
#include "ui_AboutApplication.h"
#include <Base/Console.h>
#include <App/Application.h>
#include <Gui/MainWindow.h>

using namespace Gui;
using namespace Gui::Dialog;

namespace Gui {
/** Displays all messages at startup inside the splash screen.
 * \author Werner Mayer
 */
class SplashObserver : public Base::ConsoleObserver
{
public:
    SplashObserver(QSplashScreen* splasher=0, const char* name=0)
      : splash(splasher), alignment(Qt::AlignBottom|Qt::AlignLeft), textColor(Qt::black)
    {
        Base::Console().AttachObserver(this);

        // allow to customize text position and color
        const std::map<std::string,std::string>& cfg = App::GetApplication().Config();
        std::map<std::string,std::string>::const_iterator al = cfg.find("SplashAlignment");
        if (al != cfg.end()) {
            QString alt = QString::fromAscii(al->second.c_str());
            int align=0;
            if (alt.startsWith(QLatin1String("VCenter")))
                align = Qt::AlignVCenter;
            else if (alt.startsWith(QLatin1String("Top")))
                align = Qt::AlignTop;
            else
                align = Qt::AlignBottom;

            if (alt.endsWith(QLatin1String("HCenter")))
                align += Qt::AlignHCenter;
            else if (alt.endsWith(QLatin1String("Right")))
                align += Qt::AlignRight;
            else
                align += Qt::AlignLeft;

            alignment = align;
        }

        // choose text color
        std::map<std::string,std::string>::const_iterator tc = cfg.find("SplashTextColor");
        if (tc != cfg.end()) {
            QColor col; col.setNamedColor(QString::fromAscii(tc->second.c_str()));
            if (col.isValid())
                textColor = col;
        }
    }

    virtual ~SplashObserver()
    {
        Base::Console().DetachObserver(this);
    }

    void Warning(const char * s)
    {
        Log(s);
    }
    void Message(const char * s)
    {
        Log(s);
    }
    void Error  (const char * s)
    {
        Log(s);
    }
    void Log (const char * s)
    {
        QString msg(QString::fromUtf8(s));
        QRegExp rx;
        // ignore 'Init:' and 'Mod:' prefixes
        rx.setPattern(QLatin1String("^\\s*(Init:|Mod:)\\s*"));
        int pos = rx.indexIn(msg);
        if (pos != -1) {
            msg = msg.mid(rx.matchedLength());
        }
        else {
            // ignore activation of commands
            rx.setPattern(QLatin1String("^\\s*(\\+App::|Create|CmdC:|CmdG:|Act:)\\s*"));
            pos = rx.indexIn(msg);
            if (pos == 0)
                return;
        }

        splash->showMessage(msg.replace(QLatin1String("\n"), QString()), alignment, textColor);
        QMutex mutex;
        mutex.lock();
        QWaitCondition().wait(&mutex, 50);
    }

private:
    QSplashScreen* splash;
    int alignment;
    QColor textColor;
};
} // namespace Gui

// ------------------------------------------------------------------------------

/**
 * Constructs a splash screen that will display the pixmap.
 */
SplashScreen::SplashScreen(  const QPixmap & pixmap , Qt::WFlags f )
    : QSplashScreen(pixmap, f)
{
    // write the messages to splasher
    messages = new SplashObserver(this);
}

/** Destruction. */
SplashScreen::~SplashScreen()
{
    delete messages;
}

/**
 * Draws the contents of the splash screen using painter \a painter. The default
 * implementation draws the message passed by message().
 */
void SplashScreen::drawContents ( QPainter * painter )
{
    QSplashScreen::drawContents(painter);
}

// ------------------------------------------------------------------------------

AboutDialogFactory* AboutDialogFactory::factory = 0;

AboutDialogFactory::~AboutDialogFactory()
{
}

QDialog *AboutDialogFactory::create(QWidget *parent) const
{
    return new AboutDialog(false, parent);
}

const AboutDialogFactory *AboutDialogFactory::defaultFactory()
{
    static const AboutDialogFactory this_factory;
    if (factory)
        return factory;
    return &this_factory;
}

void AboutDialogFactory::setDefaultFactory(AboutDialogFactory *f)
{
    if (factory != f)
        delete factory;
    factory = f;
}

// ------------------------------------------------------------------------------

/* TRANSLATOR Gui::Dialog::AboutDialog */

/**
 *  Constructs an AboutDialog which is a child of 'parent', with the
 *  name 'name' and widget flags set to 'WStyle_Customize|WStyle_NoBorder|WType_Modal'
 *
 *  The dialog will be modal.
 */
AboutDialog::AboutDialog(bool showLic, QWidget* parent)
  : QDialog(parent, Qt::FramelessWindowHint), ui(new Ui_AboutApplication)
{
    setModal(true);
    ui->setupUi(this);
    ui->labelSplashPicture->setPixmap(getMainWindow()->splashImage());
    if (!showLic)
        ui->licenseButton->hide();
    setupLabels();
}

/**
 *  Destroys the object and frees any allocated resources
 */
AboutDialog::~AboutDialog()
{
    // no need to delete child widgets, Qt does it all for us
    delete ui;
}

static QString getPlatform()
{
#if defined (Q_OS_WIN32)
    switch(QSysInfo::windowsVersion())
    {
        case QSysInfo::WV_NT:
            return QString::fromAscii("Windows NT");
        case QSysInfo::WV_2000:
            return QString::fromAscii("Windows 2000");
        case QSysInfo::WV_XP:
            return QString::fromAscii("Windows XP");
        case QSysInfo::WV_2003:
            return QString::fromAscii("Windows Server 2003");
        case QSysInfo::WV_VISTA:
            return QString::fromAscii("Windows Vista");
        case QSysInfo::WV_WINDOWS7:
            return QString::fromAscii("Windows 7");
        default:
            return QString::fromAscii("Windows");
    }
#elif defined (Q_OS_MAC)
    return QString::fromAscii("Mac OS X");
#elif defined (Q_OS_LINUX)
    QString exe(QLatin1String("lsb_release"));
    QStringList args;
    args << QLatin1String("-ds");
    QProcess proc;
    proc.setEnvironment(QProcess::systemEnvironment());
    proc.start(exe, args);
    if (proc.waitForStarted() && proc.waitForFinished()) {
        QByteArray info = proc.readAll();
        info.replace('\n',"");
        return QString::fromAscii((const char*)info);
    }

    return QString::fromAscii("Linux");
#elif defined (Q_OS_UNIX)
    return QString::fromAscii("UNIX");
#else
    return QString();
#endif
}

void AboutDialog::setupLabels()
{
    std::map<std::string, std::string>& config = App::Application::Config();
    QString exeName = QString::fromAscii(config["ExeName"].c_str());
    std::map<std::string,std::string>::iterator it = config.find("WindowTitle");
    if (it != config.end())
        exeName = QString::fromUtf8(it->second.c_str());
    QString banner  = QString::fromUtf8(config["CopyrightInfo"].c_str());
    banner = banner.left( banner.indexOf(QLatin1Char('\n')) );
    QString major  = QString::fromAscii(config["BuildVersionMajor"].c_str());
    QString minor  = QString::fromAscii(config["BuildVersionMinor"].c_str());
    QString build  = QString::fromAscii(config["BuildRevision"].c_str());
    QString disda  = QString::fromAscii(config["BuildRevisionDate"].c_str());
    QString mturl  = QString::fromAscii(config["MaintainerUrl"].c_str());

    QString author = ui->labelAuthor->text();
    author.replace(QString::fromAscii("Unknown Application"), exeName);
    author.replace(QString::fromAscii("(c) Unknown Author"), banner);
    ui->labelAuthor->setText(author);
    ui->labelAuthor->setUrl(mturl);

    QString version = ui->labelBuildVersion->text();
    version.replace(QString::fromAscii("Unknown"), QString::fromAscii("%1.%2").arg(major).arg(minor));
    ui->labelBuildVersion->setText(version);

    QString revision = ui->labelBuildRevision->text();
    revision.replace(QString::fromAscii("Unknown"), build);
    ui->labelBuildRevision->setText(revision);

    QString date = ui->labelBuildDate->text();
    date.replace(QString::fromAscii("Unknown"), disda);
    ui->labelBuildDate->setText(date);

    QString platform = ui->labelBuildPlatform->text();
    platform.replace(QString::fromAscii("Unknown"),
        QString::fromAscii("%1 (%2-bit)").arg(getPlatform()).arg(QSysInfo::WordSize));
    ui->labelBuildPlatform->setText(platform);

    // branch name
    it = config.find("BuildRevisionBranch");
    if (it != config.end()) {
        QString branch = ui->labelBuildBranch->text();
        branch.replace(QString::fromAscii("Unknown"), QString::fromAscii(it->second.c_str()));
        ui->labelBuildBranch->setText(branch);
    }
    else {
        ui->labelBranch->hide();
        ui->labelBuildBranch->hide();
    }

    // hash id
    it = config.find("BuildRevisionHash");
    if (it != config.end()) {
        QString hash = ui->labelBuildHash->text();
        hash.replace(QString::fromAscii("Unknown"), QString::fromAscii(it->second.c_str()));
        ui->labelBuildHash->setText(hash);
    }
    else {
        ui->labelHash->hide();
        ui->labelBuildHash->hide();
    }
}

void AboutDialog::on_licenseButton_clicked()
{
}

void AboutDialog::on_copyButton_clicked()
{
    QString data;
    QTextStream str(&data);
    std::map<std::string, std::string>& config = App::Application::Config();
    std::map<std::string,std::string>::iterator it;

    QString major  = QString::fromAscii(config["BuildVersionMajor"].c_str());
    QString minor  = QString::fromAscii(config["BuildVersionMinor"].c_str());
    QString build  = QString::fromAscii(config["BuildRevision"].c_str());
    str << "Platform: " << getPlatform() << " (" << QSysInfo::WordSize << "-bit)" << endl;
    str << "Version: " << major << "." << minor << "." << build << endl;
    it = config.find("BuildRevisionBranch");
    if (it != config.end())
        str << "Branch: " << it->second.c_str() << endl;
    it = config.find("BuildRevisionHash");
    if (it != config.end())
        str << "Hash: " << it->second.c_str() << endl;
    // report also the version numbers of the most important libraries in FreeCAD
    str << "Python version: " << PY_VERSION << endl;
    str << "Qt version: " << QT_VERSION_STR << endl;
    str << "Coin version: " << COIN_VERSION << endl;
    str << "SoQt version: " << SOQT_VERSION << endl;
    it = config.find("OCC_VERSION");
    if (it != config.end())
        str << "OCC version: " << it->second.c_str() << endl;

    QClipboard* cb = QApplication::clipboard();
    cb->setText(data);
}

#include "moc_Splashscreen.cpp"
<commit_msg>Fix warning<commit_after>/***************************************************************************
 *   Copyright (c) 2004 Werner Mayer <wmayer[at]users.sourceforge.net>     *
 *                                                                         *
 *   This file is part of the FreeCAD CAx development system.              *
 *                                                                         *
 *   This library is free software; you can redistribute it and/or         *
 *   modify it under the terms of the GNU Library General Public           *
 *   License as published by the Free Software Foundation; either          *
 *   version 2 of the License, or (at your option) any later version.      *
 *                                                                         *
 *   This library  is distributed in the hope that it will be useful,      *
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
 *   GNU Library General Public License for more details.                  *
 *                                                                         *
 *   You should have received a copy of the GNU Library General Public     *
 *   License along with this library; see the file COPYING.LIB. If not,    *
 *   write to the Free Software Foundation, Inc., 59 Temple Place,         *
 *   Suite 330, Boston, MA  02111-1307, USA                                *
 *                                                                         *
 ***************************************************************************/

#include "PreCompiled.h"
#ifndef _PreComp_
# include <Python.h>
# include <QApplication>
# include <QClipboard>
# include <QMutex>
# include <QProcess>
# include <QSysInfo>
# include <QTextStream>
# include <QWaitCondition>
# include <Inventor/C/basic.h>
# include <Inventor/Qt/SoQtBasic.h>
#endif

#include "Splashscreen.h"
#include "ui_AboutApplication.h"
#include <Base/Console.h>
#include <App/Application.h>
#include <Gui/MainWindow.h>

using namespace Gui;
using namespace Gui::Dialog;

namespace Gui {
/** Displays all messages at startup inside the splash screen.
 * \author Werner Mayer
 */
class SplashObserver : public Base::ConsoleObserver
{
public:
    SplashObserver(QSplashScreen* splasher=0, const char* name=0)
      : splash(splasher), alignment(Qt::AlignBottom|Qt::AlignLeft), textColor(Qt::black)
    {
        Base::Console().AttachObserver(this);

        // allow to customize text position and color
        const std::map<std::string,std::string>& cfg = App::GetApplication().Config();
        std::map<std::string,std::string>::const_iterator al = cfg.find("SplashAlignment");
        if (al != cfg.end()) {
            QString alt = QString::fromAscii(al->second.c_str());
            int align=0;
            if (alt.startsWith(QLatin1String("VCenter")))
                align = Qt::AlignVCenter;
            else if (alt.startsWith(QLatin1String("Top")))
                align = Qt::AlignTop;
            else
                align = Qt::AlignBottom;

            if (alt.endsWith(QLatin1String("HCenter")))
                align += Qt::AlignHCenter;
            else if (alt.endsWith(QLatin1String("Right")))
                align += Qt::AlignRight;
            else
                align += Qt::AlignLeft;

            alignment = align;
        }

        // choose text color
        std::map<std::string,std::string>::const_iterator tc = cfg.find("SplashTextColor");
        if (tc != cfg.end()) {
            QColor col; col.setNamedColor(QString::fromAscii(tc->second.c_str()));
            if (col.isValid())
                textColor = col;
        }
    }

    virtual ~SplashObserver()
    {
        Base::Console().DetachObserver(this);
    }

    void Warning(const char * s)
    {
        Log(s);
    }
    void Message(const char * s)
    {
        Log(s);
    }
    void Error  (const char * s)
    {
        Log(s);
    }
    void Log (const char * s)
    {
        QString msg(QString::fromUtf8(s));
        QRegExp rx;
        // ignore 'Init:' and 'Mod:' prefixes
        rx.setPattern(QLatin1String("^\\s*(Init:|Mod:)\\s*"));
        int pos = rx.indexIn(msg);
        if (pos != -1) {
            msg = msg.mid(rx.matchedLength());
        }
        else {
            // ignore activation of commands
            rx.setPattern(QLatin1String("^\\s*(\\+App::|Create|CmdC:|CmdG:|Act:)\\s*"));
            pos = rx.indexIn(msg);
            if (pos == 0)
                return;
        }

        splash->showMessage(msg.replace(QLatin1String("\n"), QString()), alignment, textColor);
        QMutex mutex;
        mutex.lock();
        QWaitCondition().wait(&mutex, 50);
    }

private:
    QSplashScreen* splash;
    int alignment;
    QColor textColor;
};
} // namespace Gui

// ------------------------------------------------------------------------------

/**
 * Constructs a splash screen that will display the pixmap.
 */
SplashScreen::SplashScreen(  const QPixmap & pixmap , Qt::WFlags f )
    : QSplashScreen(pixmap, f)
{
    // write the messages to splasher
    messages = new SplashObserver(this);
}

/** Destruction. */
SplashScreen::~SplashScreen()
{
    delete messages;
}

/**
 * Draws the contents of the splash screen using painter \a painter. The default
 * implementation draws the message passed by message().
 */
void SplashScreen::drawContents ( QPainter * painter )
{
    QSplashScreen::drawContents(painter);
}

// ------------------------------------------------------------------------------

AboutDialogFactory* AboutDialogFactory::factory = 0;

AboutDialogFactory::~AboutDialogFactory()
{
}

QDialog *AboutDialogFactory::create(QWidget *parent) const
{
    return new AboutDialog(false, parent);
}

const AboutDialogFactory *AboutDialogFactory::defaultFactory()
{
    static const AboutDialogFactory this_factory;
    if (factory)
        return factory;
    return &this_factory;
}

void AboutDialogFactory::setDefaultFactory(AboutDialogFactory *f)
{
    if (factory != f)
        delete factory;
    factory = f;
}

// ------------------------------------------------------------------------------

/* TRANSLATOR Gui::Dialog::AboutDialog */

/**
 *  Constructs an AboutDialog which is a child of 'parent', with the
 *  name 'name' and widget flags set to 'WStyle_Customize|WStyle_NoBorder|WType_Modal'
 *
 *  The dialog will be modal.
 */
AboutDialog::AboutDialog(bool showLic, QWidget* parent)
  : QDialog(parent, Qt::FramelessWindowHint), ui(new Ui_AboutApplication)
{
    setModal(true);
    ui->setupUi(this);
    ui->labelSplashPicture->setPixmap(getMainWindow()->splashImage());
    if (!showLic)
        ui->licenseButton->hide();
    setupLabels();
}

/**
 *  Destroys the object and frees any allocated resources
 */
AboutDialog::~AboutDialog()
{
    // no need to delete child widgets, Qt does it all for us
    delete ui;
}

static QString getPlatform()
{
#if defined (Q_OS_WIN32)
    switch(QSysInfo::windowsVersion())
    {
        case QSysInfo::WV_NT:
            return QString::fromAscii("Windows NT");
        case QSysInfo::WV_2000:
            return QString::fromAscii("Windows 2000");
        case QSysInfo::WV_XP:
            return QString::fromAscii("Windows XP");
        case QSysInfo::WV_2003:
            return QString::fromAscii("Windows Server 2003");
        case QSysInfo::WV_VISTA:
            return QString::fromAscii("Windows Vista");
        case QSysInfo::WV_WINDOWS7:
            return QString::fromAscii("Windows 7");
        default:
            return QString::fromAscii("Windows");
    }
#elif defined (Q_OS_MAC)
    return QString::fromAscii("Mac OS X");
#elif defined (Q_OS_LINUX)
    QString exe(QLatin1String("lsb_release"));
    QStringList args;
    args << QLatin1String("-ds");
    QProcess proc;
    proc.setEnvironment(QProcess::systemEnvironment());
    proc.start(exe, args);
    if (proc.waitForStarted() && proc.waitForFinished()) {
        QByteArray info = proc.readAll();
        info.replace('\n',"");
        return QString::fromAscii((const char*)info);
    }

    return QString::fromAscii("Linux");
#elif defined (Q_OS_UNIX)
    return QString::fromAscii("UNIX");
#else
    return QString();
#endif
}

void AboutDialog::setupLabels()
{
    std::map<std::string, std::string>& config = App::Application::Config();
    QString exeName = QString::fromAscii(config["ExeName"].c_str());
    std::map<std::string,std::string>::iterator it = config.find("WindowTitle");
    if (it != config.end())
        exeName = QString::fromUtf8(it->second.c_str());
    QString banner  = QString::fromUtf8(config["CopyrightInfo"].c_str());
    banner = banner.left( banner.indexOf(QLatin1Char('\n')) );
    QString major  = QString::fromAscii(config["BuildVersionMajor"].c_str());
    QString minor  = QString::fromAscii(config["BuildVersionMinor"].c_str());
    QString build  = QString::fromAscii(config["BuildRevision"].c_str());
    QString disda  = QString::fromAscii(config["BuildRevisionDate"].c_str());
    QString mturl  = QString::fromAscii(config["MaintainerUrl"].c_str());

    QString author = ui->labelAuthor->text();
    author.replace(QString::fromAscii("Unknown Application"), exeName);
    author.replace(QString::fromAscii("(c) Unknown Author"), banner);
    ui->labelAuthor->setText(author);
    ui->labelAuthor->setUrl(mturl);

    QString version = ui->labelBuildVersion->text();
    version.replace(QString::fromAscii("Unknown"), QString::fromAscii("%1.%2").arg(major).arg(minor));
    ui->labelBuildVersion->setText(version);

    QString revision = ui->labelBuildRevision->text();
    revision.replace(QString::fromAscii("Unknown"), build);
    ui->labelBuildRevision->setText(revision);

    QString date = ui->labelBuildDate->text();
    date.replace(QString::fromAscii("Unknown"), disda);
    ui->labelBuildDate->setText(date);

    QString platform = ui->labelBuildPlatform->text();
    platform.replace(QString::fromAscii("Unknown"),
        QString::fromAscii("%1 (%2-bit)").arg(getPlatform()).arg(QSysInfo::WordSize));
    ui->labelBuildPlatform->setText(platform);

    // branch name
    it = config.find("BuildRevisionBranch");
    if (it != config.end()) {
        QString branch = ui->labelBuildBranch->text();
        branch.replace(QString::fromAscii("Unknown"), QString::fromAscii(it->second.c_str()));
        ui->labelBuildBranch->setText(branch);
    }
    else {
        ui->labelBranch->hide();
        ui->labelBuildBranch->hide();
    }

    // hash id
    it = config.find("BuildRevisionHash");
    if (it != config.end()) {
        QString hash = ui->labelBuildHash->text();
        hash.replace(QString::fromAscii("Unknown"), QString::fromAscii(it->second.c_str()));
        ui->labelBuildHash->setText(hash);
    }
    else {
        ui->labelHash->hide();
        ui->labelBuildHash->hide();
    }
}

void AboutDialog::on_licenseButton_clicked()
{
}

void AboutDialog::on_copyButton_clicked()
{
    QString data;
    QTextStream str(&data);
    std::map<std::string, std::string>& config = App::Application::Config();
    std::map<std::string,std::string>::iterator it;

    QString major  = QString::fromAscii(config["BuildVersionMajor"].c_str());
    QString minor  = QString::fromAscii(config["BuildVersionMinor"].c_str());
    QString build  = QString::fromAscii(config["BuildRevision"].c_str());
    str << "Platform: " << getPlatform() << " (" << QSysInfo::WordSize << "-bit)" << endl;
    str << "Version: " << major << "." << minor << "." << build << endl;
    it = config.find("BuildRevisionBranch");
    if (it != config.end())
        str << "Branch: " << it->second.c_str() << endl;
    it = config.find("BuildRevisionHash");
    if (it != config.end())
        str << "Hash: " << it->second.c_str() << endl;
    // report also the version numbers of the most important libraries in FreeCAD
    str << "Python version: " << PY_VERSION << endl;
    str << "Qt version: " << QT_VERSION_STR << endl;
    str << "Coin version: " << COIN_VERSION << endl;
    str << "SoQt version: " << SOQT_VERSION << endl;
    it = config.find("OCC_VERSION");
    if (it != config.end())
        str << "OCC version: " << it->second.c_str() << endl;

    QClipboard* cb = QApplication::clipboard();
    cb->setText(data);
}

#include "moc_Splashscreen.cpp"
<|endoftext|>


<commit_before>#include "KittlerThreshold.h"

KittlerThreshold::KittlerThreshold(std::string fileName)
    : BaseImage(fileName, 0, 0)
    , m_lPointerOffsetForResult(0)
    , m_usUserThreshold(0)
    , m_ppResult(NULL)
{
    CreateHisto(m_ppImageMatrix, m_iColumns, m_iRows, UCHAR_MAX+1);
}

KittlerThreshold::~KittlerThreshold()
{
    if(m_ppResult != NULL)
    {
        m_ppResult + m_lPointerOffsetForResult;
        free(m_ppResult);
        m_ppResult = NULL;
    }
}

void KittlerThreshold::Filter()
{
    Filter(m_ppImageMatrix);
}

void KittlerThreshold::Filter(unsigned char** input)
{
    Filter(input, m_iColumns, m_iRows);
}

void KittlerThreshold::Filter(unsigned char** input, int col, int row)
{
    int i = 0, j = 0;
    int first = 255, last = 0;
    double mu1Prev = 0.0, mu1 = 0.0, mu2Prev = 0.0, mu2 = 0.0,
           var1Prev = 0.0, var1 = 0.0, var2Prev = 0, var2 = 0.0,
           q1 = 0, q2 = 0, q1Prev = 0, q2Prev = 0, mu = 0.0, H = 0.0;
    double threshold = 255;
    int threshold_i = 255;

    m_ppResult = (unsigned char**)BaseImage::CreateMatrix(m_iColumns, m_iRows, 0, 0, sizeof(unsigned char), &m_lPointerOffsetForResult);

    for(i=1;i<UCHAR_MAX;i++)
    {
        if(m_dP[i] != 0 && m_dP[i+1] != 0 && first > i)
        {
            first = i;
        }

        if(m_dP[i] != 0 && m_dP[i+1] != 0)
        {
            last = i;
        }
    }

    q1Prev = m_dP[first];
    q2Prev = 1-q1Prev;
    q1 = q1Prev;
    q2 = q2Prev;

    for(i=0;i<=UCHAR_MAX;i++)
    {
        mu += m_dP[i]*i;
    }

    mu1Prev = first;
    mu1 = mu1Prev;
    mu2Prev = Mean(first+1, UCHAR_MAX+1);
    //mu2Prev = (mu-mu1*q1)/q2;
    mu2 = mu2Prev;

    //var1Prev = 0.0;
    var1Prev = (first-mu1)*(first-mu1)*m_dP[first]/q1;
    var1 = var1Prev;
    /*for(i=first+1;i<last;i++)
    {
        var2Prev += m_dP[i]*i*i;
    }
    var2Prev -= mu2*mu2;*/
    for(i=first;i<last;i++)
    {
        var2Prev += (i-mu2)*(i-mu2)*m_dP[i]/q2;
    }
    var2 = var2Prev;

    for(i=first+1;i<last;i++)
    {
        q1 = q1Prev+m_dP[i];
        q2 = 1-q1;
        /*if(q1 == 0 || q2 == 0)
        {
            q1Prev = q1;
            q2Prev = q2;
            mu1Prev = mu1;
            mu2Prev = mu2;
            var1Prev = var1;
            var2Prev = var2;
            continue;
        }*/

        mu1 = (q1Prev*mu1Prev+i*m_dP[i])/q1;
        var1 = (q1Prev*(var1Prev+(mu1Prev-mu1)*(mu1Prev-mu1))+
                m_dP[i]*(i-mu1)*(i-mu1))/q1;

        mu2 = (mu-q1*mu1)/q2;
        var2 = (q2Prev*(var2Prev+(mu2Prev-mu2)*(mu2Prev-mu2))-
                m_dP[i]*(i-mu2)*(i-mu2))/q2;

        /*if(var1 <= 0 || var2 <= 0)
        {
            q1Prev = q1;
            q2Prev = q2;
            mu1Prev = mu1;
            mu2Prev = mu2;
            var1Prev = var1;
            var2Prev = var2;
            continue;
        }*/

        H = (q1*log(var1)+q2*log(var2))/2-q1*log(q1)-q2*log(q2);
        if(H<threshold)
        {
            threshold = H;
            threshold_i = i;
        }
#ifdef _DEBUG
        std::cout<</*i<<": "<<*/H<<std::endl;
#endif
        q1Prev = q1;
        q2Prev = q2;
        mu1Prev = mu1;
        mu2Prev = mu2;
        var1Prev = var1;
        var2Prev = var2;
    }

    if(m_usUserThreshold>0)
    {
        threshold_i = m_usUserThreshold;
    }

    for(i=0;i<row;i++)
    {
        for(j=0;j<col;j++)
        {
            if(m_ppImageMatrix[i][j]>=threshold_i)
            {
                m_ppResult[i][j] = 255;
            }
            else
            {
                m_ppResult[i][j] = 0; // Black foreground
            }
        }
    }
}

void KittlerThreshold::SaveResult(std::string filename)
{
    SaveResult(filename, m_iColumns, m_iRows);
}

void KittlerThreshold::SaveResult(std::string filename, int col, int row)
{
    WriteToFile(filename, m_ppResult, 0, 0, col, row);
}

void KittlerThreshold::SetColumns(int col)
{
    m_iColumns = col;
}

void KittlerThreshold::SetRows(int row)
{
    m_iRows = row;
}

void KittlerThreshold::SetUserThreshold(unsigned short t)
{
    m_usUserThreshold = t;
}
<commit_msg>Small fix<commit_after>#include "KittlerThreshold.h"

KittlerThreshold::KittlerThreshold(std::string fileName)
    : BaseImage(fileName, 0, 0)
    , m_lPointerOffsetForResult(0)
    , m_usUserThreshold(0)
    , m_ppResult(NULL)
{
    CreateHisto(m_ppImageMatrix, m_iColumns, m_iRows, UCHAR_MAX+1);
}

KittlerThreshold::~KittlerThreshold()
{
    if(m_ppResult != NULL)
    {
        m_ppResult += m_lPointerOffsetForResult;
        free(m_ppResult);
        m_ppResult = NULL;
    }
}

void KittlerThreshold::Filter()
{
    Filter(m_ppImageMatrix);
}

void KittlerThreshold::Filter(unsigned char** input)
{
    Filter(input, m_iColumns, m_iRows);
}

void KittlerThreshold::Filter(unsigned char** input, int col, int row)
{
    int i = 0, j = 0;
    int first = 255, last = 0;
    double mu1Prev = 0.0, mu1 = 0.0, mu2Prev = 0.0, mu2 = 0.0,
           var1Prev = 0.0, var1 = 0.0, var2Prev = 0, var2 = 0.0,
           q1 = 0, q2 = 0, q1Prev = 0, q2Prev = 0, mu = 0.0, H = 0.0;
    double threshold = 255;
    int threshold_i = 255;

    m_ppResult = (unsigned char**)BaseImage::CreateMatrix(m_iColumns, m_iRows, 0, 0, sizeof(unsigned char), &m_lPointerOffsetForResult);

    for(i=1;i<UCHAR_MAX;i++)
    {
        if(m_dP[i] != 0 && m_dP[i+1] != 0 && first > i)
        {
            first = i;
        }

        if(m_dP[i] != 0 && m_dP[i+1] != 0)
        {
            last = i;
        }
    }

    q1Prev = m_dP[first];
    q2Prev = 1-q1Prev;
    q1 = q1Prev;
    q2 = q2Prev;

    for(i=0;i<=UCHAR_MAX;i++)
    {
        mu += m_dP[i]*i;
    }

    mu1Prev = first;
    mu1 = mu1Prev;
    mu2Prev = Mean(first+1, UCHAR_MAX+1);
    //mu2Prev = (mu-mu1*q1)/q2;
    mu2 = mu2Prev;

    //var1Prev = 0.0;
    var1Prev = (first-mu1)*(first-mu1)*m_dP[first]/q1;
    var1 = var1Prev;
    /*for(i=first+1;i<last;i++)
    {
        var2Prev += m_dP[i]*i*i;
    }
    var2Prev -= mu2*mu2;*/
    for(i=first;i<last;i++)
    {
        var2Prev += (i-mu2)*(i-mu2)*m_dP[i]/q2;
    }
    var2 = var2Prev;

    for(i=first+1;i<last;i++)
    {
        q1 = q1Prev+m_dP[i];
        q2 = 1-q1;
        /*if(q1 == 0 || q2 == 0)
        {
            q1Prev = q1;
            q2Prev = q2;
            mu1Prev = mu1;
            mu2Prev = mu2;
            var1Prev = var1;
            var2Prev = var2;
            continue;
        }*/

        mu1 = (q1Prev*mu1Prev+i*m_dP[i])/q1;
        var1 = (q1Prev*(var1Prev+(mu1Prev-mu1)*(mu1Prev-mu1))+
                m_dP[i]*(i-mu1)*(i-mu1))/q1;

        mu2 = (mu-q1*mu1)/q2;
        var2 = (q2Prev*(var2Prev+(mu2Prev-mu2)*(mu2Prev-mu2))-
                m_dP[i]*(i-mu2)*(i-mu2))/q2;

        /*if(var1 <= 0 || var2 <= 0)
        {
            q1Prev = q1;
            q2Prev = q2;
            mu1Prev = mu1;
            mu2Prev = mu2;
            var1Prev = var1;
            var2Prev = var2;
            continue;
        }*/

        H = (q1*log(var1)+q2*log(var2))/2-q1*log(q1)-q2*log(q2);
        if(H<threshold)
        {
            threshold = H;
            threshold_i = i;
        }
#ifdef _DEBUG
        std::cout<</*i<<": "<<*/H<<std::endl;
#endif
        q1Prev = q1;
        q2Prev = q2;
        mu1Prev = mu1;
        mu2Prev = mu2;
        var1Prev = var1;
        var2Prev = var2;
    }

    if(m_usUserThreshold>0)
    {
        threshold_i = m_usUserThreshold;
    }

    for(i=0;i<row;i++)
    {
        for(j=0;j<col;j++)
        {
            if(m_ppImageMatrix[i][j]>=threshold_i)
            {
                m_ppResult[i][j] = 255;
            }
            else
            {
                m_ppResult[i][j] = 0; // Black foreground
            }
        }
    }
}

void KittlerThreshold::SaveResult(std::string filename)
{
    SaveResult(filename, m_iColumns, m_iRows);
}

void KittlerThreshold::SaveResult(std::string filename, int col, int row)
{
    WriteToFile(filename, m_ppResult, 0, 0, col, row);
}

void KittlerThreshold::SetColumns(int col)
{
    m_iColumns = col;
}

void KittlerThreshold::SetRows(int row)
{
    m_iRows = row;
}

void KittlerThreshold::SetUserThreshold(unsigned short t)
{
    m_usUserThreshold = t;
}
<|endoftext|>


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

  Program:   Visualization Toolkit
  Module:    vtkArrayExtents.cxx

-------------------------------------------------------------------------
  Copyright 2008 Sandia Corporation.
  Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation,
  the U.S. Government retains certain rights in this software.
-------------------------------------------------------------------------

  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 "vtkArrayCoordinates.h"
#include "vtkArrayExtents.h"

#include <vtksys/stl/functional>
#include <vtksys/stl/numeric>

vtkArrayExtents::vtkArrayExtents()
{
}

vtkArrayExtents::vtkArrayExtents(vtkIdType i) :
  Storage(1)
{
  this->Storage[0] = i;
}

vtkArrayExtents::vtkArrayExtents(vtkIdType i, vtkIdType j) :
  Storage(2)
{
  this->Storage[0] = i;
  this->Storage[1] = j;
}

vtkArrayExtents::vtkArrayExtents(vtkIdType i, vtkIdType j, vtkIdType k) :
  Storage(3)
{
  this->Storage[0] = i;
  this->Storage[1] = j;
  this->Storage[2] = k;
}

const vtkArrayExtents vtkArrayExtents::Uniform(vtkIdType n, vtkIdType m)
{
  vtkArrayExtents result;
  result.Storage = vtksys_stl::vector<vtkIdType>(n, m);
  return result;
}

void vtkArrayExtents::Append(vtkIdType extent)
{
  this->Storage.push_back(extent);
}

vtkIdType vtkArrayExtents::GetDimensions() const
{
  return this->Storage.size();
}

vtkIdType vtkArrayExtents::GetSize() const
{
  if(this->Storage.empty())
    return 0;

  return vtkstd::accumulate(this->Storage.begin(), this->Storage.end(), 1, vtkstd::multiplies<vtkIdType>());
}

void vtkArrayExtents::SetDimensions(vtkIdType dimensions)
{
  this->Storage.assign(dimensions, 0);
}

vtkIdType& vtkArrayExtents::operator[](vtkIdType i)
{
  return this->Storage[i];
}

const vtkIdType& vtkArrayExtents::operator[](vtkIdType i) const
{
  return this->Storage[i];
}

bool vtkArrayExtents::operator==(const vtkArrayExtents& rhs) const
{
  return this->Storage == rhs.Storage;
}

bool vtkArrayExtents::operator!=(const vtkArrayExtents& rhs) const
{
  return !(*this == rhs);
}

bool vtkArrayExtents::Contains(const vtkArrayCoordinates& coordinates) const
{
  if(coordinates.GetDimensions() != this->GetDimensions())
    return false;

  for(vtkIdType i = 0; i != this->GetDimensions(); ++i)
    {
    if(coordinates[i] < 0)
      return false;
    if(coordinates[i] >= this->Storage[i])
      return false;
    }

  return true;
}

ostream& operator<<(ostream& stream, const vtkArrayExtents& rhs)
{
  for(unsigned int i = 0; i != rhs.Storage.size(); ++i)
    {
    if(i)
      stream << "x";
    stream << rhs.Storage[i];
    }

  return stream;
}

<commit_msg>COMP: change vtkArrayExtents::Uniform to initialize with a for loop as IA64 HP-UX doesnt support vector.assign nor the 2 arguement vector constructor vector<T>(n, value).<commit_after>/*=========================================================================

  Program:   Visualization Toolkit
  Module:    vtkArrayExtents.cxx

-------------------------------------------------------------------------
  Copyright 2008 Sandia Corporation.
  Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation,
  the U.S. Government retains certain rights in this software.
-------------------------------------------------------------------------

  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 "vtkArrayCoordinates.h"
#include "vtkArrayExtents.h"

#include <vtksys/stl/functional>
#include <vtksys/stl/numeric>

vtkArrayExtents::vtkArrayExtents()
{
}

vtkArrayExtents::vtkArrayExtents(vtkIdType i) :
  Storage(1)
{
  this->Storage[0] = i;
}

vtkArrayExtents::vtkArrayExtents(vtkIdType i, vtkIdType j) :
  Storage(2)
{
  this->Storage[0] = i;
  this->Storage[1] = j;
}

vtkArrayExtents::vtkArrayExtents(vtkIdType i, vtkIdType j, vtkIdType k) :
  Storage(3)
{
  this->Storage[0] = i;
  this->Storage[1] = j;
  this->Storage[2] = k;
}

const vtkArrayExtents vtkArrayExtents::Uniform(vtkIdType n, vtkIdType m)
{
  vtkArrayExtents result;
  // IA64 HP-UX doesnt seem to have the vector<T> vector1(n, value)
  // overload nor the assign(n, value) method, so we use the single
  // arguement constructor and initialize the values manually.
  // result.Storage = vtksys_stl::vector<vtkIdType>(n, m);

  result.Storage = vtksys_stl::vector<vtkIdType>(n);
  for(int i = 0; i < n; i++)
    {
    result.Storage[i] = m;
    }
  return result;
}

void vtkArrayExtents::Append(vtkIdType extent)
{
  this->Storage.push_back(extent);
}

vtkIdType vtkArrayExtents::GetDimensions() const
{
  return this->Storage.size();
}

vtkIdType vtkArrayExtents::GetSize() const
{
  if(this->Storage.empty())
    return 0;

  return vtkstd::accumulate(this->Storage.begin(), this->Storage.end(), 1, vtkstd::multiplies<vtkIdType>());
}

void vtkArrayExtents::SetDimensions(vtkIdType dimensions)
{
  this->Storage.assign(dimensions, 0);
}

vtkIdType& vtkArrayExtents::operator[](vtkIdType i)
{
  return this->Storage[i];
}

const vtkIdType& vtkArrayExtents::operator[](vtkIdType i) const
{
  return this->Storage[i];
}

bool vtkArrayExtents::operator==(const vtkArrayExtents& rhs) const
{
  return this->Storage == rhs.Storage;
}

bool vtkArrayExtents::operator!=(const vtkArrayExtents& rhs) const
{
  return !(*this == rhs);
}

bool vtkArrayExtents::Contains(const vtkArrayCoordinates& coordinates) const
{
  if(coordinates.GetDimensions() != this->GetDimensions())
    return false;

  for(vtkIdType i = 0; i != this->GetDimensions(); ++i)
    {
    if(coordinates[i] < 0)
      return false;
    if(coordinates[i] >= this->Storage[i])
      return false;
    }

  return true;
}

ostream& operator<<(ostream& stream, const vtkArrayExtents& rhs)
{
  for(unsigned int i = 0; i != rhs.Storage.size(); ++i)
    {
    if(i)
      stream << "x";
    stream << rhs.Storage[i];
    }

  return stream;
}

<|endoftext|>


<commit_before>#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <vector>
#include <queue>
#include <poll.h>
#include <fcntl.h>
#include <sys/mman.h>

using namespace std;

#include "simDefs.h"
#include "channel.h"
//#include "svdpi.h"
//#include "svImports.h"
#include "vc_hdrs.h"
#include "svdpi_src.h"

Channel *cmdChannel = NULL;
Channel *respChannel = NULL;

int sendResp(simCmd *cmd) {
  simCmd resp;
  resp.id = cmd->id;
  resp.cmd = cmd->cmd;
  resp.size = cmd->size;
  switch (cmd->cmd) {
    case READY:
      resp.size = 0;
      break;
    default:
      EPRINTF("[SIM] Command %d not supported!\n", cmd->cmd);
      exit(-1);
  }

  respChannel->send(&resp);
  return cmd->id;
}

int numCycles = 0;
queue<simCmd*> pendingOps;

class DRAMRequest {
public:
  uint64_t addr;
  uint64_t tag;
  bool isWr;
  uint32_t *wdata;
  uint32_t delay;
  uint32_t elapsed;

  DRAMRequest(uint64_t a, uint64_t t, bool wr, uint32_t *wd) {
    addr = a;
    tag = t;
    isWr = wr;
    if (isWr) {
      wdata = (uint32_t*) malloc(16 * sizeof(uint32_t));
      for (int i=0; i<16; i++) {
        wdata[i] = wd[i];
      }
    } else {
      wdata = NULL;
    }

    delay = abs(rand()) % 150 + 50;
    elapsed = 0;
  }

  void print() {
    EPRINTF("---- DRAM REQ ----\n");
    EPRINTF("addr : %lx\n", addr);
    EPRINTF("tag  : %lx\n", tag);
    EPRINTF("isWr : %lx\n", tag);
    EPRINTF("delay: %u\n", delay);
    if (isWr) {
      EPRINTF("wdata0 : %u\n", wdata[0]);
      EPRINTF("wdata1 : %u\n", wdata[1]);
    }
    EPRINTF("------------------\n");
  }

  ~DRAMRequest() {
    if (wdata != NULL) free(wdata);
  }
};

std::queue<DRAMRequest*> dramRequestQ;

extern "C" {
  void sendDRAMRequest(
      long long addr,
      int tag,
      int isWr,
      int wdata0,
      int wdata1,
      int wdata2,
      int wdata3,
      int wdata4,
      int wdata5,
      int wdata6,
      int wdata7,
      int wdata8,
      int wdata9,
      int wdata10,
      int wdata11,
      int wdata12,
      int wdata13,
      int wdata14,
      int wdata15
    ) {
    // view addr as uint64_t without doing sign extension
    uint64_t cmdAddr = *(uint64_t*)&addr;
    uint64_t cmdTag = (uint64_t)(*(uint32_t*)&tag);
    bool cmdIsWr = isWr > 0;
    uint32_t cmdWdata0 = (*(uint32_t*)&wdata0);
    uint32_t cmdWdata1 = (*(uint32_t*)&wdata1);
    uint32_t cmdWdata2 = (*(uint32_t*)&wdata2);
    uint32_t cmdWdata3 = (*(uint32_t*)&wdata3);
    uint32_t cmdWdata4 = (*(uint32_t*)&wdata4);
    uint32_t cmdWdata5 = (*(uint32_t*)&wdata5);
    uint32_t cmdWdata6 = (*(uint32_t*)&wdata6);
    uint32_t cmdWdata7 = (*(uint32_t*)&wdata7);
    uint32_t cmdWdata8 = (*(uint32_t*)&wdata8);
    uint32_t cmdWdata9 = (*(uint32_t*)&wdata9);
    uint32_t cmdWdata10 = (*(uint32_t*)&wdata10);
    uint32_t cmdWdata11 = (*(uint32_t*)&wdata11);
    uint32_t cmdWdata12 = (*(uint32_t*)&wdata12);
    uint32_t cmdWdata13 = (*(uint32_t*)&wdata13);
    uint32_t cmdWdata14 = (*(uint32_t*)&wdata14);
    uint32_t cmdWdata15 = (*(uint32_t*)&wdata15);

    uint32_t wdata[16] = { cmdWdata0, cmdWdata1, cmdWdata2, cmdWdata3, cmdWdata4, cmdWdata5, cmdWdata6, cmdWdata7, cmdWdata8, cmdWdata9, cmdWdata10, cmdWdata11, cmdWdata12, cmdWdata13, cmdWdata14, cmdWdata15};
    DRAMRequest *req = new DRAMRequest(cmdAddr, cmdTag, cmdIsWr, wdata);
    dramRequestQ.push(req);
    req->print();
  }

  void checkDRAMResponse() {
    if (dramRequestQ.size() > 0) {
      DRAMRequest *req = dramRequestQ.front();
      req->elapsed++;
      if(req->elapsed == req->delay) {
        dramRequestQ.pop();

        uint32_t rdata[16] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};

        if (req->isWr) {
          // Write request: Update 1 burst-length bytes at *addr
          uint32_t *waddr = (uint32_t*) req->addr;
          for (int i=0; i<16; i++) {
            waddr[i] = req->wdata[i];
          }
        } else {
          // Read request: Read burst-length bytes at *addr
          uint32_t *raddr = (uint32_t*) req->addr;
          for (int i=0; i<16; i++) {
            rdata[i] = raddr[i];
            EPRINTF("rdata[%d] = %u\n", i, rdata[i]);
          }

        }
        pokeDRAMResponse(
            req->tag,
            rdata[0],
            rdata[1],
            rdata[2],
            rdata[3],
            rdata[4],
            rdata[5],
            rdata[6],
            rdata[7],
            rdata[8],
            rdata[9],
            rdata[10],
            rdata[11],
            rdata[12],
            rdata[13],
            rdata[14],
            rdata[15]
          );

      }

    }
  }

  // Function is called every clock cycle
  int tick() {
    bool exitTick = false;
    int finishSim = 0;
    numCycles++;

   // Check for DRAM response and send it to design

   checkDRAMResponse();

    // Handle pending operations, if any
    if (pendingOps.size() > 0) {
      simCmd *cmd = pendingOps.front();
      pendingOps.pop();

      switch (cmd->cmd) {
        case READ_REG:
          // Construct and send response
          simCmd resp;
          resp.id = cmd->id;
          resp.cmd = cmd->cmd;
          SV_BIT_PACKED_ARRAY(32, rdataHi);
          SV_BIT_PACKED_ARRAY(32, rdataLo);
          readRegRdataHi32((svBitVec32*)&rdataHi);
          readRegRdataLo32((svBitVec32*)&rdataLo);
          *(uint32_t*)resp.data = (uint32_t)*rdataLo;
          *((uint32_t*)resp.data + 1) = (uint32_t)*rdataHi;
          resp.size = sizeof(uint64_t);
          respChannel->send(&resp);
          break;
        default:
          EPRINTF("[SIM] Ignoring unknown pending command %u\n", cmd->cmd);
          break;
      }
      free(cmd);
    }

    // Handle new incoming operations
    while (!exitTick) {
      simCmd *cmd = cmdChannel->recv();
      simCmd readResp;
      uint32_t reg = 0;
      uint64_t data = 0;
      switch (cmd->cmd) {
        case MALLOC: {
          size_t size = *(size_t*)cmd->data;
          int fd = open("/dev/zero", O_RDWR);
          void *ptr = mmap(0, size, PROT_READ|PROT_WRITE, MAP_PRIVATE, fd, 0);
          close(fd);

          simCmd resp;
          resp.id = cmd->id;
          resp.cmd = cmd->cmd;
          *(uint64_t*)resp.data = (uint64_t)ptr;
          resp.size = sizeof(size_t);
          EPRINTF("[SIM] MALLOC(%u), returning %lx\n", size, ptr);
          respChannel->send(&resp);
          break;
        }
        case FREE: {
          void *ptr = (void*)(*(uint64_t*)cmd->data);
          ASSERT(ptr != NULL, "Attempting to call free on null pointer\n");
          EPRINTF("[SIM] FREE(%lx)\n", ptr);

          break;
        }
        case MEMCPY_H2D: {
          uint64_t *data = (uint64_t*)cmd->data;
          void *dst = (void*)data[0];
          size_t size = data[1];

          EPRINTF("[SIM] Received memcpy request to %lx, size %u\n", dst, size);

          // Now to receive 'size' bytes from the cmd stream
          cmdChannel->recvFixedBytes(dst, size);

          // Send ack back indicating end of memcpy
          simCmd resp;
          resp.id = cmd->id;
          resp.cmd = cmd->cmd;
          resp.size = 0;
          respChannel->send(&resp);
          break;
        }
        case MEMCPY_D2H: {
          // Transfer 'size' bytes from src
          uint64_t *data = (uint64_t*)cmd->data;
          void *src = (void*)data[0];
          size_t size = data[1];

          // Now to receive 'size' bytes from the cmd stream
          respChannel->sendFixedBytes(src, size);
          break;
        }
        case RESET:
          rst();
          exitTick = true;
          break;
        case START:
          start();
          exitTick = true;
          break;
        case STEP:
          exitTick = true;
          break;
        case READ_REG: {
            reg = *((uint32_t*)cmd->data);

            // Issue read addr
            readRegRaddr(reg);

            // Append to pending ops - will return in the next cycle
            simCmd *pendingCmd = (simCmd*) malloc(sizeof(simCmd));
            memcpy(pendingCmd, cmd, sizeof(simCmd));
            pendingOps.push(pendingCmd);

            exitTick = true;
            break;
         }
        case WRITE_REG: {
            reg = *((uint32_t*)cmd->data);
            data = *((uint64_t*)((uint32_t*)cmd->data + 1));

            // Perform write
//            writeReg(reg, (svBitVecVal)data);
            writeReg(reg, data);
            exitTick = true;
            break;
          }
        case FIN:
          finishSim = 1;
          exitTick = true;
          break;
        default:
          break;
      }
    }
    return finishSim;
  }

  // Called before simulation begins
  void sim_init() {
    EPRINTF("[SIM] Sim process started!\n");

    // 0. Create Channel structures
    cmdChannel = new Channel(SIM_CMD_FD, -1);
    respChannel = new Channel(-1, SIM_RESP_FD);

    // 1. Read command
    simCmd *cmd = cmdChannel->recv();
    EPRINTF("[SIM] Received:\n");
    cmdChannel->printPkt(cmd);

    // 2. Send response
    sendResp(cmd);
  }
}
<commit_msg>Print isWr correctly, remove printing rdata<commit_after>#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <vector>
#include <queue>
#include <poll.h>
#include <fcntl.h>
#include <sys/mman.h>

using namespace std;

#include "simDefs.h"
#include "channel.h"
//#include "svdpi.h"
//#include "svImports.h"
#include "vc_hdrs.h"
#include "svdpi_src.h"

Channel *cmdChannel = NULL;
Channel *respChannel = NULL;

int sendResp(simCmd *cmd) {
  simCmd resp;
  resp.id = cmd->id;
  resp.cmd = cmd->cmd;
  resp.size = cmd->size;
  switch (cmd->cmd) {
    case READY:
      resp.size = 0;
      break;
    default:
      EPRINTF("[SIM] Command %d not supported!\n", cmd->cmd);
      exit(-1);
  }

  respChannel->send(&resp);
  return cmd->id;
}

int numCycles = 0;
queue<simCmd*> pendingOps;

class DRAMRequest {
public:
  uint64_t addr;
  uint64_t tag;
  bool isWr;
  uint32_t *wdata;
  uint32_t delay;
  uint32_t elapsed;

  DRAMRequest(uint64_t a, uint64_t t, bool wr, uint32_t *wd) {
    addr = a;
    tag = t;
    isWr = wr;
    if (isWr) {
      wdata = (uint32_t*) malloc(16 * sizeof(uint32_t));
      for (int i=0; i<16; i++) {
        wdata[i] = wd[i];
      }
    } else {
      wdata = NULL;
    }

    delay = abs(rand()) % 150 + 50;
    elapsed = 0;
  }

  void print() {
    EPRINTF("---- DRAM REQ ----\n");
    EPRINTF("addr : %lx\n", addr);
    EPRINTF("tag  : %lx\n", tag);
    EPRINTF("isWr : %lx\n", isWr);
    EPRINTF("delay: %u\n", delay);
    if (isWr) {
      EPRINTF("wdata0 : %u\n", wdata[0]);
      EPRINTF("wdata1 : %u\n", wdata[1]);
    }
    EPRINTF("------------------\n");
  }

  ~DRAMRequest() {
    if (wdata != NULL) free(wdata);
  }
};

std::queue<DRAMRequest*> dramRequestQ;

extern "C" {
  void sendDRAMRequest(
      long long addr,
      int tag,
      int isWr,
      int wdata0,
      int wdata1,
      int wdata2,
      int wdata3,
      int wdata4,
      int wdata5,
      int wdata6,
      int wdata7,
      int wdata8,
      int wdata9,
      int wdata10,
      int wdata11,
      int wdata12,
      int wdata13,
      int wdata14,
      int wdata15
    ) {
    // view addr as uint64_t without doing sign extension
    uint64_t cmdAddr = *(uint64_t*)&addr;
    uint64_t cmdTag = (uint64_t)(*(uint32_t*)&tag);
    bool cmdIsWr = isWr > 0;
    uint32_t cmdWdata0 = (*(uint32_t*)&wdata0);
    uint32_t cmdWdata1 = (*(uint32_t*)&wdata1);
    uint32_t cmdWdata2 = (*(uint32_t*)&wdata2);
    uint32_t cmdWdata3 = (*(uint32_t*)&wdata3);
    uint32_t cmdWdata4 = (*(uint32_t*)&wdata4);
    uint32_t cmdWdata5 = (*(uint32_t*)&wdata5);
    uint32_t cmdWdata6 = (*(uint32_t*)&wdata6);
    uint32_t cmdWdata7 = (*(uint32_t*)&wdata7);
    uint32_t cmdWdata8 = (*(uint32_t*)&wdata8);
    uint32_t cmdWdata9 = (*(uint32_t*)&wdata9);
    uint32_t cmdWdata10 = (*(uint32_t*)&wdata10);
    uint32_t cmdWdata11 = (*(uint32_t*)&wdata11);
    uint32_t cmdWdata12 = (*(uint32_t*)&wdata12);
    uint32_t cmdWdata13 = (*(uint32_t*)&wdata13);
    uint32_t cmdWdata14 = (*(uint32_t*)&wdata14);
    uint32_t cmdWdata15 = (*(uint32_t*)&wdata15);

    uint32_t wdata[16] = { cmdWdata0, cmdWdata1, cmdWdata2, cmdWdata3, cmdWdata4, cmdWdata5, cmdWdata6, cmdWdata7, cmdWdata8, cmdWdata9, cmdWdata10, cmdWdata11, cmdWdata12, cmdWdata13, cmdWdata14, cmdWdata15};
    DRAMRequest *req = new DRAMRequest(cmdAddr, cmdTag, cmdIsWr, wdata);
    dramRequestQ.push(req);
    req->print();
  }

  void checkDRAMResponse() {
    if (dramRequestQ.size() > 0) {
      DRAMRequest *req = dramRequestQ.front();
      req->elapsed++;
      if(req->elapsed == req->delay) {
        dramRequestQ.pop();

        uint32_t rdata[16] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};

        if (req->isWr) {
          // Write request: Update 1 burst-length bytes at *addr
          uint32_t *waddr = (uint32_t*) req->addr;
          for (int i=0; i<16; i++) {
            waddr[i] = req->wdata[i];
          }
        } else {
          // Read request: Read burst-length bytes at *addr
          uint32_t *raddr = (uint32_t*) req->addr;
          for (int i=0; i<16; i++) {
            rdata[i] = raddr[i];
//            EPRINTF("rdata[%d] = %u\n", i, rdata[i]);
          }

        }
        pokeDRAMResponse(
            req->tag,
            rdata[0],
            rdata[1],
            rdata[2],
            rdata[3],
            rdata[4],
            rdata[5],
            rdata[6],
            rdata[7],
            rdata[8],
            rdata[9],
            rdata[10],
            rdata[11],
            rdata[12],
            rdata[13],
            rdata[14],
            rdata[15]
          );

      }

    }
  }

  // Function is called every clock cycle
  int tick() {
    bool exitTick = false;
    int finishSim = 0;
    numCycles++;

   // Check for DRAM response and send it to design

   checkDRAMResponse();

    // Handle pending operations, if any
    if (pendingOps.size() > 0) {
      simCmd *cmd = pendingOps.front();
      pendingOps.pop();

      switch (cmd->cmd) {
        case READ_REG:
          // Construct and send response
          simCmd resp;
          resp.id = cmd->id;
          resp.cmd = cmd->cmd;
          SV_BIT_PACKED_ARRAY(32, rdataHi);
          SV_BIT_PACKED_ARRAY(32, rdataLo);
          readRegRdataHi32((svBitVec32*)&rdataHi);
          readRegRdataLo32((svBitVec32*)&rdataLo);
          *(uint32_t*)resp.data = (uint32_t)*rdataLo;
          *((uint32_t*)resp.data + 1) = (uint32_t)*rdataHi;
          resp.size = sizeof(uint64_t);
          respChannel->send(&resp);
          break;
        default:
          EPRINTF("[SIM] Ignoring unknown pending command %u\n", cmd->cmd);
          break;
      }
      free(cmd);
    }

    // Handle new incoming operations
    while (!exitTick) {
      simCmd *cmd = cmdChannel->recv();
      simCmd readResp;
      uint32_t reg = 0;
      uint64_t data = 0;
      switch (cmd->cmd) {
        case MALLOC: {
          size_t size = *(size_t*)cmd->data;
          int fd = open("/dev/zero", O_RDWR);
          void *ptr = mmap(0, size, PROT_READ|PROT_WRITE, MAP_PRIVATE, fd, 0);
          close(fd);

          simCmd resp;
          resp.id = cmd->id;
          resp.cmd = cmd->cmd;
          *(uint64_t*)resp.data = (uint64_t)ptr;
          resp.size = sizeof(size_t);
          EPRINTF("[SIM] MALLOC(%u), returning %lx\n", size, ptr);
          respChannel->send(&resp);
          break;
        }
        case FREE: {
          void *ptr = (void*)(*(uint64_t*)cmd->data);
          ASSERT(ptr != NULL, "Attempting to call free on null pointer\n");
          EPRINTF("[SIM] FREE(%lx)\n", ptr);

          break;
        }
        case MEMCPY_H2D: {
          uint64_t *data = (uint64_t*)cmd->data;
          void *dst = (void*)data[0];
          size_t size = data[1];

          EPRINTF("[SIM] Received memcpy request to %lx, size %u\n", dst, size);

          // Now to receive 'size' bytes from the cmd stream
          cmdChannel->recvFixedBytes(dst, size);

          // Send ack back indicating end of memcpy
          simCmd resp;
          resp.id = cmd->id;
          resp.cmd = cmd->cmd;
          resp.size = 0;
          respChannel->send(&resp);
          break;
        }
        case MEMCPY_D2H: {
          // Transfer 'size' bytes from src
          uint64_t *data = (uint64_t*)cmd->data;
          void *src = (void*)data[0];
          size_t size = data[1];

          // Now to receive 'size' bytes from the cmd stream
          respChannel->sendFixedBytes(src, size);
          break;
        }
        case RESET:
          rst();
          exitTick = true;
          break;
        case START:
          start();
          exitTick = true;
          break;
        case STEP:
          exitTick = true;
          break;
        case READ_REG: {
            reg = *((uint32_t*)cmd->data);

            // Issue read addr
            readRegRaddr(reg);

            // Append to pending ops - will return in the next cycle
            simCmd *pendingCmd = (simCmd*) malloc(sizeof(simCmd));
            memcpy(pendingCmd, cmd, sizeof(simCmd));
            pendingOps.push(pendingCmd);

            exitTick = true;
            break;
         }
        case WRITE_REG: {
            reg = *((uint32_t*)cmd->data);
            data = *((uint64_t*)((uint32_t*)cmd->data + 1));

            // Perform write
//            writeReg(reg, (svBitVecVal)data);
            writeReg(reg, data);
            exitTick = true;
            break;
          }
        case FIN:
          finishSim = 1;
          exitTick = true;
          break;
        default:
          break;
      }
    }
    return finishSim;
  }

  // Called before simulation begins
  void sim_init() {
    EPRINTF("[SIM] Sim process started!\n");

    // 0. Create Channel structures
    cmdChannel = new Channel(SIM_CMD_FD, -1);
    respChannel = new Channel(-1, SIM_RESP_FD);

    // 1. Read command
    simCmd *cmd = cmdChannel->recv();
    EPRINTF("[SIM] Received:\n");
    cmdChannel->printPkt(cmd);

    // 2. Send response
    sendResp(cmd);
  }
}
<|endoftext|>


<commit_before>#ifndef __STAN__PROB__DISTRIBUTIONS__DOUBLE_EXPONENTIAL_HPP__
#define __STAN__PROB__DISTRIBUTIONS__DOUBLE_EXPONENTIAL_HPP__

#include <stan/agrad.hpp>
#include <stan/math/error_handling.hpp>
#include <stan/math/special_functions.hpp>
#include <stan/meta/traits.hpp>
#include <stan/prob/constants.hpp>
#include <stan/prob/traits.hpp>
#include <boost/math/special_functions/sign.hpp>

namespace stan {

  namespace prob {

    // DoubleExponential(y|mu,sigma)  [sigma > 0]
    // FIXME: add documentation
    template <bool propto,
              typename T_y, typename T_loc, typename T_scale,
              class Policy>
    typename return_type<T_y,T_loc,T_scale>::type
    double_exponential_log(const T_y& y, const T_loc& mu, const T_scale& sigma,
                           const Policy&) {
      static const char* function
        = "stan::prob::double_exponential_log(%1%)";

      using stan::is_constant_struct;
      using stan::math::check_finite;
      using stan::math::check_positive;
      using stan::math::check_consistent_sizes;
      using stan::math::value_of;
      using stan::prob::include_summand;
      using std::log;
      using std::fabs;
      using boost::math::sign;

      // check if any vectors are zero length
      if (!(stan::length(y)
            && stan::length(mu)
            && stan::length(sigma)))
        return 0.0;

      // set up return value accumulator
      double logp(0.0);
      if(!check_finite(function, y, "Random variable", &logp, Policy()))
        return logp;
      if(!check_finite(function, mu, "Location parameter",
                       &logp, Policy()))
        return logp;
      if(!check_finite(function, sigma, "Scale parameter",
                       &logp, Policy()))
        return logp;
      if(!check_positive(function, sigma, "Scale parameter",
                         &logp, Policy()))
        return logp;
      if (!(check_consistent_sizes(function,
                                   y,mu,sigma,
				   "Random variable","Location parameter","Shape parameter",
                                   &logp, Policy())))
        return logp;

      // check if no variables are involved and prop-to
      if (!include_summand<propto,T_y,T_loc,T_scale>::value)
	return 0.0;

      // set up template expressions wrapping scalars into vector views
      VectorView<const T_y> y_vec(y);
      VectorView<const T_loc> mu_vec(mu);
      VectorView<const T_scale> sigma_vec(sigma);
      size_t N = max_size(y, mu, sigma);
      agrad::OperandsAndPartials<T_y,T_loc,T_scale> operands_and_partials(y, mu, sigma);

      DoubleVectorView<include_summand<propto,T_y,T_loc,T_scale>::value,T_scale>
	inv_sigma(length(sigma));
      DoubleVectorView<!is_constant_struct<T_scale>::value,T_scale>
	inv_sigma_squared(length(sigma));
      DoubleVectorView<include_summand<propto,T_scale>::value,T_scale>
	log_sigma(length(sigma));
      for (size_t i = 0; i < length(sigma); i++) {
	const double sigma_dbl = value_of(sigma_vec[i]);
	if (include_summand<propto,T_y,T_loc,T_scale>::value)
	  inv_sigma[i] = 1.0 / sigma_dbl;
	if (include_summand<propto,T_scale>::value)
	  log_sigma[i] = log(value_of(sigma_vec[i]));
	if (!is_constant_struct<T_scale>::value)
	  inv_sigma_squared[i] = inv_sigma[i] * inv_sigma[i];
      }

      for (size_t n = 0; n < N; n++) {
	const double y_dbl = value_of(y_vec[n]);
	const double mu_dbl = value_of(mu_vec[n]);

	// reusable subexpressions values
	const double y_m_mu = y_dbl - mu_dbl;
	const double fabs_y_m_mu = fabs(y_m_mu);

	// log probability
	if (include_summand<propto>::value)
	  logp += NEG_LOG_TWO;
	if (include_summand<propto,T_scale>::value)
	  logp -= log_sigma[n];
	if (include_summand<propto,T_y,T_loc,T_scale>::value)
	  logp -= fabs_y_m_mu * inv_sigma[n];

	// gradients
	double sign_y_m_mu_times_inv_sigma(0);
	if (!is_constant_struct<T_y>::value || !is_constant_struct<T_loc>::value)
	  sign_y_m_mu_times_inv_sigma = sign(y_m_mu) * inv_sigma[n];
	if (!is_constant_struct<T_y>::value) {
	  operands_and_partials.d_x1[n] -= sign_y_m_mu_times_inv_sigma;
	}
	if (!is_constant_struct<T_loc>::value) {
	  operands_and_partials.d_x2[n] += sign_y_m_mu_times_inv_sigma;
	}
	if (!is_constant_struct<T_scale>::value)
	  operands_and_partials.d_x3[n] += -inv_sigma[n] + fabs_y_m_mu * inv_sigma_squared[n];
      }
      return operands_and_partials.to_var(logp);
    }

    template <bool propto,
              typename T_y, typename T_loc, typename T_scale>
    typename return_type<T_y,T_loc,T_scale>::type
    double_exponential_log(const T_y& y, const T_loc& mu,
                           const T_scale& sigma) {
      return double_exponential_log<propto>(y,mu,sigma,
                                            stan::math::default_policy());
    }

    template <typename T_y, typename T_loc, typename T_scale,
              class Policy>
    typename return_type<T_y,T_loc,T_scale>::type
    double_exponential_log(const T_y& y, const T_loc& mu, const T_scale& sigma,
                           const Policy&) {
      return double_exponential_log<false>(y,mu,sigma,Policy());
    }

    template <typename T_y, typename T_loc, typename T_scale>
    typename return_type<T_y,T_loc,T_scale>::type
    double_exponential_log(const T_y& y, const T_loc& mu,
                           const T_scale& sigma) {
      return double_exponential_log<false>(y,mu,sigma,
                                           stan::math::default_policy());
    }

    /**
     * Calculates the double exponential cumulative density function.
     *
     * \f$ f(y|\mu,\sigma) = \begin{cases} \
           \frac{1}{2} \exp\left(\frac{y-\mu}{\sigma}\right), \mbox{if } y < \mu \\
           1 - \frac{1}{2} \exp\left(-\frac{y-\mu}{\sigma}\right), \mbox{if } y \ge \mu \
           \end{cases}\f$
     *
     * @param y A scalar variate.
     * @param mu The location parameter.
     * @param sigma The scale parameter.
     *
     * @return The cumulative density function.
     */
    template <typename T_y, typename T_loc, typename T_scale,
              class Policy>
    typename return_type<T_y,T_loc,T_scale>::type
    double_exponential_cdf(const T_y& y, const T_loc& mu, const T_scale& sigma,
                         const Policy&) {
      static const char* function
        = "stan::prob::double_exponential_cdf(%1%)";

      using stan::math::check_finite;
      using stan::math::check_positive;
      using boost::math::tools::promote_args;

      typename promote_args<T_y,T_loc,T_scale>::type lp(0.0);
      if(!check_finite(function, y, "Random variable", &lp, Policy()))
        return lp;
      if(!check_finite(function, mu, "Location parameter",
                       &lp, Policy()))
        return lp;
      if(!check_finite(function, sigma, "Scale parameter",
                       &lp, Policy()))
        return lp;
      if(!check_positive(function, sigma, "Scale parameter",
                         &lp, Policy()))
        return lp;

      if (y < mu)
        return exp((y-mu)/sigma)/2;
      else
        return 1 - exp((mu-y)/sigma)/2;
    }

    template <typename T_y, typename T_loc, typename T_scale>
    typename boost::math::tools::promote_args<T_y,T_loc,T_scale>::type
    double_exponential_cdf(const T_y& y, const T_loc& mu, const T_scale& sigma) {
      return double_exponential_cdf(y,mu,sigma,stan::math::default_policy());
    }

  }
}
#endif
<commit_msg>substitute simple sign() function for boost's sign() function<commit_after>#ifndef __STAN__PROB__DISTRIBUTIONS__DOUBLE_EXPONENTIAL_HPP__
#define __STAN__PROB__DISTRIBUTIONS__DOUBLE_EXPONENTIAL_HPP__

#include <stan/agrad.hpp>
#include <stan/math/error_handling.hpp>
#include <stan/math/special_functions.hpp>
#include <stan/meta/traits.hpp>
#include <stan/prob/constants.hpp>
#include <stan/prob/traits.hpp>

namespace stan {

  namespace prob {
    template<typename T>
    inline int sign(const T& z) {
      return (z == 0) ? 0 : z < 0 ? -1 : 1;
    }

    // DoubleExponential(y|mu,sigma)  [sigma > 0]
    // FIXME: add documentation
    template <bool propto,
              typename T_y, typename T_loc, typename T_scale,
              class Policy>
    typename return_type<T_y,T_loc,T_scale>::type
    double_exponential_log(const T_y& y, const T_loc& mu, const T_scale& sigma,
                           const Policy&) {
      static const char* function
        = "stan::prob::double_exponential_log(%1%)";

      using stan::is_constant_struct;
      using stan::math::check_finite;
      using stan::math::check_positive;
      using stan::math::check_consistent_sizes;
      using stan::math::value_of;
      using stan::prob::include_summand;
      using std::log;
      using std::fabs;

      // check if any vectors are zero length
      if (!(stan::length(y)
            && stan::length(mu)
            && stan::length(sigma)))
        return 0.0;

      // set up return value accumulator
      double logp(0.0);
      if(!check_finite(function, y, "Random variable", &logp, Policy()))
        return logp;
      if(!check_finite(function, mu, "Location parameter",
                       &logp, Policy()))
        return logp;
      if(!check_finite(function, sigma, "Scale parameter",
                       &logp, Policy()))
        return logp;
      if(!check_positive(function, sigma, "Scale parameter",
                         &logp, Policy()))
        return logp;
      if (!(check_consistent_sizes(function,
                                   y,mu,sigma,
				   "Random variable","Location parameter","Shape parameter",
                                   &logp, Policy())))
        return logp;

      // check if no variables are involved and prop-to
      if (!include_summand<propto,T_y,T_loc,T_scale>::value)
	return 0.0;

      // set up template expressions wrapping scalars into vector views
      VectorView<const T_y> y_vec(y);
      VectorView<const T_loc> mu_vec(mu);
      VectorView<const T_scale> sigma_vec(sigma);
      size_t N = max_size(y, mu, sigma);
      agrad::OperandsAndPartials<T_y,T_loc,T_scale> operands_and_partials(y, mu, sigma);

      DoubleVectorView<include_summand<propto,T_y,T_loc,T_scale>::value,T_scale>
	inv_sigma(length(sigma));
      DoubleVectorView<!is_constant_struct<T_scale>::value,T_scale>
	inv_sigma_squared(length(sigma));
      DoubleVectorView<include_summand<propto,T_scale>::value,T_scale>
	log_sigma(length(sigma));
      for (size_t i = 0; i < length(sigma); i++) {
	const double sigma_dbl = value_of(sigma_vec[i]);
	if (include_summand<propto,T_y,T_loc,T_scale>::value)
	  inv_sigma[i] = 1.0 / sigma_dbl;
	if (include_summand<propto,T_scale>::value)
	  log_sigma[i] = log(value_of(sigma_vec[i]));
	if (!is_constant_struct<T_scale>::value)
	  inv_sigma_squared[i] = inv_sigma[i] * inv_sigma[i];
      }

      for (size_t n = 0; n < N; n++) {
	const double y_dbl = value_of(y_vec[n]);
	const double mu_dbl = value_of(mu_vec[n]);

	// reusable subexpressions values
	const double y_m_mu = y_dbl - mu_dbl;
	const double fabs_y_m_mu = fabs(y_m_mu);

	// log probability
	if (include_summand<propto>::value)
	  logp += NEG_LOG_TWO;
	if (include_summand<propto,T_scale>::value)
	  logp -= log_sigma[n];
	if (include_summand<propto,T_y,T_loc,T_scale>::value)
	  logp -= fabs_y_m_mu * inv_sigma[n];

	// gradients
	double sign_y_m_mu_times_inv_sigma(0);
	if (!is_constant_struct<T_y>::value || !is_constant_struct<T_loc>::value)
	  sign_y_m_mu_times_inv_sigma = sign(y_m_mu) * inv_sigma[n];
	if (!is_constant_struct<T_y>::value) {
	  operands_and_partials.d_x1[n] -= sign_y_m_mu_times_inv_sigma;
	}
	if (!is_constant_struct<T_loc>::value) {
	  operands_and_partials.d_x2[n] += sign_y_m_mu_times_inv_sigma;
	}
	if (!is_constant_struct<T_scale>::value)
	  operands_and_partials.d_x3[n] += -inv_sigma[n] + fabs_y_m_mu * inv_sigma_squared[n];
      }
      return operands_and_partials.to_var(logp);
    }

    template <bool propto,
              typename T_y, typename T_loc, typename T_scale>
    typename return_type<T_y,T_loc,T_scale>::type
    double_exponential_log(const T_y& y, const T_loc& mu,
                           const T_scale& sigma) {
      return double_exponential_log<propto>(y,mu,sigma,
                                            stan::math::default_policy());
    }

    template <typename T_y, typename T_loc, typename T_scale,
              class Policy>
    typename return_type<T_y,T_loc,T_scale>::type
    double_exponential_log(const T_y& y, const T_loc& mu, const T_scale& sigma,
                           const Policy&) {
      return double_exponential_log<false>(y,mu,sigma,Policy());
    }

    template <typename T_y, typename T_loc, typename T_scale>
    typename return_type<T_y,T_loc,T_scale>::type
    double_exponential_log(const T_y& y, const T_loc& mu,
                           const T_scale& sigma) {
      return double_exponential_log<false>(y,mu,sigma,
                                           stan::math::default_policy());
    }

    /**
     * Calculates the double exponential cumulative density function.
     *
     * \f$ f(y|\mu,\sigma) = \begin{cases} \
           \frac{1}{2} \exp\left(\frac{y-\mu}{\sigma}\right), \mbox{if } y < \mu \\
           1 - \frac{1}{2} \exp\left(-\frac{y-\mu}{\sigma}\right), \mbox{if } y \ge \mu \
           \end{cases}\f$
     *
     * @param y A scalar variate.
     * @param mu The location parameter.
     * @param sigma The scale parameter.
     *
     * @return The cumulative density function.
     */
    template <typename T_y, typename T_loc, typename T_scale,
              class Policy>
    typename return_type<T_y,T_loc,T_scale>::type
    double_exponential_cdf(const T_y& y, const T_loc& mu, const T_scale& sigma,
                         const Policy&) {
      static const char* function
        = "stan::prob::double_exponential_cdf(%1%)";

      using stan::math::check_finite;
      using stan::math::check_positive;
      using boost::math::tools::promote_args;

      typename promote_args<T_y,T_loc,T_scale>::type lp(0.0);
      if(!check_finite(function, y, "Random variable", &lp, Policy()))
        return lp;
      if(!check_finite(function, mu, "Location parameter",
                       &lp, Policy()))
        return lp;
      if(!check_finite(function, sigma, "Scale parameter",
                       &lp, Policy()))
        return lp;
      if(!check_positive(function, sigma, "Scale parameter",
                         &lp, Policy()))
        return lp;

      if (y < mu)
        return exp((y-mu)/sigma)/2;
      else
        return 1 - exp((mu-y)/sigma)/2;
    }

    template <typename T_y, typename T_loc, typename T_scale>
    typename boost::math::tools::promote_args<T_y,T_loc,T_scale>::type
    double_exponential_cdf(const T_y& y, const T_loc& mu, const T_scale& sigma) {
      return double_exponential_cdf(y,mu,sigma,stan::math::default_policy());
    }

  }
}
#endif
<|endoftext|>


<commit_before>#include <stdlio.h>
#include <opencv2/opencv.hpp>
#include <opencv2/highgui/highgui.hpp>
#include "camera.hpp"

#pragma comment(lib,"opencv_world320.lib")

int main(void)
{
	cv::Mat red = Mred(takePhoto());
	countArea(red);
	getCenter(red);
}
<commit_msg>debug<commit_after>#include <stdlo.h>
#include <opencv2/opencv.hpp>
#include <opencv2/highgui/highgui.hpp>
#include "camera.hpp"

#pragma comment(lib,"opencv_world320.lib")

int main(void)
{
	cv::Mat red = Mred(takePhoto());
	countArea(red);
	getCenter(red);
}
<|endoftext|>


<commit_before>#ifndef EFU_TARGET_H
#include "target.h"
#endif

#include <array>
#include <stdexcept>
#include <sstream>
#include <iostream>
#include <fstream>
#include <iomanip>

#include <openssl/md5.h>
#include <openssl/sha.h>
#include <openssl/evp.h>

#ifndef EFU_CURLEASY_H
#include "curleasy.h"
#endif

#ifdef _WIN32

#ifndef EFU_WINERRORSTRING_H
#include "win_error_string.h"
#endif

#else

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

#endif

namespace
{
    void make_dir(const std::string &path);

    void make_dir(const std::string &path)
    {
    #ifdef _WIN32
        unsigned file_start = path.find_last_of("/\\");
        if (file_start == std::string::npos)
        {
            return;
        }
        if (!CreateDirectory(path.substr(0, file_start).c_str(), nullptr))
        {
            WinErrorString wes;
            if (wes.code() != ERROR_ALREADY_EXISTS)
            {
                throw std::ios_base::failure("Failed creating "
                    + path + ": " + wes.str());
            }
        }
    #else
        auto elems = split(path, '/');
        std::string descend;
        for (size_t i = 0, k = elems.size() - 1; i < k; ++i)
        {
            const std::string &s(elems[i]);
            if (s.size() && s != ".")
            {
                descend.append((i > 0 ? "/" : "") + s);
                auto status = mkdir(descend.c_str(), S_IRWXU);
                if (status == -1)
                {
                    std::error_code err(errno, std::generic_category());
                    if (err != std::errc::file_exists)
                    {
                        std::cout << "error making dir: "
                            << descend << ": "
                            << err.message() << std::endl;
                    }
                }
            }
        }
    #endif
    }
}

strvec &split(const std::string &s, char delim, strvec &elems)
{
    std::stringstream ss(s);
    std::string item;
    while (std::getline(ss, item, delim))
    {
        elems.push_back(item);
    }
    return elems;
}

strvec split(const std::string &s, char delim)
{
    strvec elems;
    return split(s, delim, elems);
}

const std::string file_checksum(const std::string &path)
{
#ifdef md_md5
    auto md = EVP_md5();
    const int md_len = MD5_DIGEST_LENGTH;
#else
    auto md = EVP_sha1();
    const int md_len = SHA_DIGEST_LENGTH;
#endif
    std::array<unsigned char, md_len> result;
    EVP_MD_CTX *mdctx = nullptr;
    std::ifstream is(path, std::ios::binary);
    if (!is.good())
    {
        std::cout << "Couldn't open file " << path
           << " for checksumming." << std::endl;
        return std::string();
    }

    const int length = 8 * 1024;
    std::array<unsigned char, length> buffer;
    auto buf = reinterpret_cast<char *>(buffer.data());
    mdctx = EVP_MD_CTX_create();
    int status = EVP_DigestInit_ex(mdctx, md, nullptr);
    while (status && is)
    {
        is.read(buf, length);
        status = EVP_DigestUpdate(mdctx, buffer.data(),
            static_cast<size_t>(is.gcount()));
    }
    status = EVP_DigestFinal_ex(mdctx, result.data(), nullptr);
    EVP_MD_CTX_destroy(mdctx);
    std::stringstream calcsum;
    calcsum << std::setfill('0');

#ifdef CPP11_FOR_EACH
    for (const unsigned char c : result)
#else
    std::for_each(std::begin(result), std::end(result),
            [&calcsum](const unsigned char c)
#endif
    {
        calcsum << std::hex << std::setw(2)
            << static_cast<unsigned int>(c);
    }
#ifndef CPP11_FOR_EACH
    );
#endif

    return calcsum.str();
}

Target::Target(const std::string &dlpath,
    const std::string &name, const std::string &checksum):
    m_dlpath(dlpath),
    m_name(name.find_first_of('/') == std::string::npos
        ? name : name, name.find_first_of('/') + 1, name.size() - 1),
    m_checksum(checksum)
{
}

void Target::fetch() const
{
    std::cout << "Statting target " << name() << "...";
    std::fstream fs(dlpath() + name(), std::ios_base::in);
    if (!fs.good())
    {
        fs.close();
        std::cout << " doesn't exist, creating new." << std::endl;
        make_dir(dlpath() + name());
        fs.open(dlpath() + name(), std::ios_base::out);
        if (!fs.good())
        {
            fs.close();
            std::cout << "Failed to create file: " << dlpath() + name() << std::endl;
        }
        else
        {
            fs.close();
            do_fetch();
            return;
        }
    }
    if (fs.good())
    {
        fs.close();
        if (status() == Status::Current)
        {
            std::cout << " already up to date." << std::endl;
        }
        else
        {
            std::cout << " outdated, downloading new." << std::endl;
            do_fetch();
        }
    }
}

Target::Status Target::status() const
{
    std::ifstream is(dlpath() + name());
    if (!is.good())
    {
        return Status::Nonexistent;
    }
    is.close();

    auto calcsum(file_checksum(dlpath() + name()));
    if (calcsum == checksum())
    {
        return Status::Current;
    }
    else
    {
        return Status::Outdated;
    }
}

void Target::do_fetch() const
{
    std::ofstream ofs(dlpath() + name(), std::ios::binary);
    if (ofs.good())
    {
        std::string s;
        std::string url(patch_dir + name());
        CurlEasy curl(url);
        curl.write_to(s);
        curl.progressbar(true);
        curl.perform();

        ofs << s;
        ofs.close();
        std::cout << "Finished downloading " << name() << std::endl;
    }
    else
    {
        std::cout << "Couldn't write to " << dlpath() + name() << std::endl;
    }
}<commit_msg>Fix not trying to make directories in working dir.<commit_after>#ifndef EFU_TARGET_H
#include "target.h"
#endif

#include <array>
#include <stdexcept>
#include <sstream>
#include <iostream>
#include <fstream>
#include <iomanip>

#include <openssl/md5.h>
#include <openssl/sha.h>
#include <openssl/evp.h>

#ifndef EFU_CURLEASY_H
#include "curleasy.h"
#endif

#ifdef _WIN32

#ifndef EFU_WINERRORSTRING_H
#include "win_error_string.h"
#endif

#else

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

#endif

namespace
{
    void make_dir(const std::string &path);

    void make_dir(const std::string &path)
    {
    #ifdef _WIN32
        unsigned file_start = path.find_last_of("/\\");
        if (file_start == std::string::npos)
        {
            return;
        }
        if (!CreateDirectory(path.substr(0, file_start).c_str(), nullptr))
        {
            WinErrorString wes;
            if (wes.code() != ERROR_ALREADY_EXISTS)
            {
                throw std::ios_base::failure("Failed creating "
                    + path + ": " + wes.str());
            }
        }
    #else
        auto elems = split(path, '/');
        std::string descend;
        for (size_t i = 0, k = elems.size() - 1; i < k; ++i)
        {
            const std::string &s(elems[i]);
            if (s.size())
            {
                descend.append((i > 0 ? "/" : "") + s);
                auto status = mkdir(descend.c_str(), S_IRWXU);
                if (status == -1)
                {
                    std::error_code err(errno, std::generic_category());
                    if (err != std::errc::file_exists)
                    {
                        std::cout << "error making dir: "
                            << descend << ": "
                            << err.message() << std::endl;
                    }
                }
            }
        }
    #endif
    }
}

strvec &split(const std::string &s, char delim, strvec &elems)
{
    std::stringstream ss(s);
    std::string item;
    while (std::getline(ss, item, delim))
    {
        elems.push_back(item);
    }
    return elems;
}

strvec split(const std::string &s, char delim)
{
    strvec elems;
    return split(s, delim, elems);
}

const std::string file_checksum(const std::string &path)
{
#ifdef md_md5
    auto md = EVP_md5();
    const int md_len = MD5_DIGEST_LENGTH;
#else
    auto md = EVP_sha1();
    const int md_len = SHA_DIGEST_LENGTH;
#endif
    std::array<unsigned char, md_len> result;
    EVP_MD_CTX *mdctx = nullptr;
    std::ifstream is(path, std::ios::binary);
    if (!is.good())
    {
        std::cout << "Couldn't open file " << path
           << " for checksumming." << std::endl;
        return std::string();
    }

    const int length = 8 * 1024;
    std::array<unsigned char, length> buffer;
    auto buf = reinterpret_cast<char *>(buffer.data());
    mdctx = EVP_MD_CTX_create();
    int status = EVP_DigestInit_ex(mdctx, md, nullptr);
    while (status && is)
    {
        is.read(buf, length);
        status = EVP_DigestUpdate(mdctx, buffer.data(),
            static_cast<size_t>(is.gcount()));
    }
    status = EVP_DigestFinal_ex(mdctx, result.data(), nullptr);
    EVP_MD_CTX_destroy(mdctx);
    std::stringstream calcsum;
    calcsum << std::setfill('0');

#ifdef CPP11_FOR_EACH
    for (const unsigned char c : result)
#else
    std::for_each(std::begin(result), std::end(result),
            [&calcsum](const unsigned char c)
#endif
    {
        calcsum << std::hex << std::setw(2)
            << static_cast<unsigned int>(c);
    }
#ifndef CPP11_FOR_EACH
    );
#endif

    return calcsum.str();
}

Target::Target(const std::string &dlpath,
    const std::string &name, const std::string &checksum):
    m_dlpath(dlpath),
    m_name(name.find_first_of('/') == std::string::npos
        ? name : name, name.find_first_of('/') + 1, name.size() - 1),
    m_checksum(checksum)
{
}

void Target::fetch() const
{
    std::cout << "Statting target " << name() << "...";
    std::fstream fs(dlpath() + name(), std::ios_base::in);
    if (!fs.good())
    {
        fs.close();
        std::cout << " doesn't exist, creating new." << std::endl;
        make_dir(dlpath() + name());
        fs.open(dlpath() + name(), std::ios_base::out);
        if (!fs.good())
        {
            fs.close();
            std::cout << "Failed to create file: " << dlpath() + name() << std::endl;
        }
        else
        {
            fs.close();
            do_fetch();
            return;
        }
    }
    if (fs.good())
    {
        fs.close();
        if (status() == Status::Current)
        {
            std::cout << " already up to date." << std::endl;
        }
        else
        {
            std::cout << " outdated, downloading new." << std::endl;
            do_fetch();
        }
    }
}

Target::Status Target::status() const
{
    std::ifstream is(dlpath() + name());
    if (!is.good())
    {
        return Status::Nonexistent;
    }
    is.close();

    auto calcsum(file_checksum(dlpath() + name()));
    if (calcsum == checksum())
    {
        return Status::Current;
    }
    else
    {
        return Status::Outdated;
    }
}

void Target::do_fetch() const
{
    std::ofstream ofs(dlpath() + name(), std::ios::binary);
    if (ofs.good())
    {
        std::string s;
        std::string url(patch_dir + name());
        CurlEasy curl(url);
        curl.write_to(s);
        curl.progressbar(true);
        curl.perform();

        ofs << s;
        ofs.close();
        std::cout << "Finished downloading " << name() << std::endl;
    }
    else
    {
        std::cout << "Couldn't write to " << dlpath() + name() << std::endl;
    }
}
<|endoftext|>