<commit_before>// Copyright 2009, Google Inc.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
//     * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//     * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
//     * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Author: wan@google.com (Zhanyong Wan)
//
// Tests for Google C++ Mocking Framework (Google Mock)
//
// Sometimes it's desirable to build most of Google Mock's own tests
// by compiling a single file.  This file serves this purpose.
#include "test/gmock-actions_test.cc"
#include "test/gmock-cardinalities_test.cc"
#include "test/gmock-generated-actions_test.cc"
#include "test/gmock-generated-function-mockers_test.cc"
#include "test/gmock-generated-internal-utils_test.cc"
#include "test/gmock-generated-matchers_test.cc"
#include "test/gmock-internal-utils_test.cc"
#include "test/gmock-matchers_test.cc"
#include "test/gmock-more-actions_test.cc"
#include "test/gmock-nice-strict_test.cc"
#include "test/gmock-port_test.cc"
#include "test/gmock-spec-builders_test.cc"
#include "test/gmock_test.cc"
<commit_msg>Clarify the rationale for gmock_all_test.cc, and pull in gtest 669<commit_after>// Copyright 2009, Google Inc.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
//     * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//     * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
//     * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Author: wan@google.com (Zhanyong Wan)
//
// Tests for Google C++ Mocking Framework (Google Mock)
//
// Some users use a build system that Google Mock doesn't support directly,
// yet they still want to build and run Google Mock's own tests.  This file
// includes most such tests, making it easier for these users to maintain
// their build scripts (they just need to build this file, even though the
// below list of actual *_test.cc files might change).
#include "test/gmock-actions_test.cc"
#include "test/gmock-cardinalities_test.cc"
#include "test/gmock-generated-actions_test.cc"
#include "test/gmock-generated-function-mockers_test.cc"
#include "test/gmock-generated-internal-utils_test.cc"
#include "test/gmock-generated-matchers_test.cc"
#include "test/gmock-internal-utils_test.cc"
#include "test/gmock-matchers_test.cc"
#include "test/gmock-more-actions_test.cc"
#include "test/gmock-nice-strict_test.cc"
#include "test/gmock-port_test.cc"
#include "test/gmock-spec-builders_test.cc"
#include "test/gmock_test.cc"
<|endoftext|>


<commit_before>/*
  This file is part of the PhantomJS project from Ofi Labs.

  Copyright (C) 2011 Ariya Hidayat <ariya.hidayat@gmail.com>
  Copyright (C) 2010 Ariya Hidayat <ariya.hidayat@gmail.com>

  Redistribution and use in source and binary forms, with or without
  modification, are permitted provided that the following conditions are met:

    * Redistributions of source code must retain the above copyright
      notice, this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright
      notice, this list of conditions and the following disclaimer in the
      documentation and/or other materials provided with the distribution.
    * Neither the name of the <organization> nor the
      names of its contributors may be used to endorse or promote products
      derived from this software without specific prior written permission.

  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
  DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
  (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
  ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
  THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

#include "webpage.h"

#include <iostream>
#include <math.h>

#include <QApplication>
#include <QDesktopServices>
#include <QDir>
#include <QFileInfo>
#include <QNetworkRequest>
#include <QNetworkAccessManager>
#include <QPainter>
#include <QPrinter>
#include <QWebFrame>
#include <QWebPage>

#include <gifwriter.h>

class CustomPage: public QWebPage
{
public:
    CustomPage(QObject *parent = 0)
        : QWebPage(parent)
    {
        m_userAgent = QWebPage::userAgentForUrl(QUrl());
    }

public slots:
    bool shouldInterruptJavaScript() {
        QApplication::processEvents(QEventLoop::AllEvents, 42);
        return false;
    }

protected:
    void javaScriptAlert(QWebFrame *originatingFrame, const QString &msg) {
        Q_UNUSED(originatingFrame);
        std::cout << "JavaScript alert: " << qPrintable(msg) << std::endl;
    }

    void javaScriptConsoleMessage(const QString &message, int lineNumber, const QString &sourceID) {
        if (!sourceID.isEmpty())
            std::cout << qPrintable(sourceID) << ":" << lineNumber << " ";
        std::cout << qPrintable(message) << std::endl;
    }

    QString userAgentForUrl(const QUrl &url) const {
        Q_UNUSED(url);
        return m_userAgent;
    }

private:
    QString m_userAgent;
    friend class WebPage;
};

WebPage::WebPage(QObject *parent)
    : QObject(parent)
{
    setObjectName("WebPage");
    m_webPage = new CustomPage(this);
    m_mainFrame = m_webPage->mainFrame();

    connect(m_webPage, SIGNAL(loadFinished(bool)), SLOT(finish(bool)));

    // Start with transparent background.
    QPalette palette = m_webPage->palette();
    palette.setBrush(QPalette::Base, Qt::transparent);
    m_webPage->setPalette(palette);

    // Page size does not need to take scrollbars into account.
    m_mainFrame->setScrollBarPolicy(Qt::Horizontal, Qt::ScrollBarAlwaysOff);
    m_mainFrame->setScrollBarPolicy(Qt::Vertical, Qt::ScrollBarAlwaysOff);

    m_webPage->settings()->setAttribute(QWebSettings::OfflineStorageDatabaseEnabled, true);
    m_webPage->settings()->setOfflineStoragePath(QDesktopServices::storageLocation(QDesktopServices::DataLocation));

    m_webPage->settings()->setAttribute(QWebSettings::LocalStorageDatabaseEnabled, true);

#if QT_VERSION >= QT_VERSION_CHECK(4, 7, 0)
    m_webPage->settings()->setAttribute(QWebSettings::FrameFlatteningEnabled, true);
#endif

#if QT_VERSION >= QT_VERSION_CHECK(4, 6, 0)
    m_webPage->settings()->setAttribute(QWebSettings::LocalStorageEnabled, true);
    m_webPage->settings()->setLocalStoragePath(QDesktopServices::storageLocation(QDesktopServices::DataLocation));
#endif

    // Ensure we have at least document.body.
    m_mainFrame->setHtml("");

    m_webPage->setViewportSize(QSize(400, 300));
}

QWebFrame *WebPage::mainFrame()
{
    return m_mainFrame;
}

void WebPage::setNetworkAccessManager(QNetworkAccessManager *networkAccessManager)
{
    m_webPage->setNetworkAccessManager(networkAccessManager);
}

QString WebPage::content() const
{
    return m_mainFrame->toHtml();
}

void WebPage::setContent(const QString &content)
{
    m_mainFrame->setHtml(content);
}

void WebPage::applySettings(const QVariantMap &def)
{
    QWebSettings *opt = m_webPage->settings();

    opt->setAttribute(QWebSettings::AutoLoadImages, def["loadImages"].toBool());
    opt->setAttribute(QWebSettings::PluginsEnabled, def["loadPlugins"].toBool());

    if (def.contains("userAgent"))
        m_webPage->m_userAgent = def["userAgent"].toString();
}

QString WebPage::userAgent() const
{
    return m_webPage->m_userAgent;
}

void WebPage::setViewportSize(const QVariantMap &size)
{
    int w = size.value("width").toInt();
    int h = size.value("height").toInt();
    if (w > 0 && h > 0)
        m_webPage->setViewportSize(QSize(w, h));
}

QVariantMap WebPage::viewportSize() const
{
    QVariantMap result;
    QSize size = m_webPage->viewportSize();
    result["width"] = size.width();
    result["height"] = size.height();
    return result;
}

void WebPage::setClipRect(const QVariantMap &size)
{
    int w = size.value("width").toInt();
    int h = size.value("height").toInt();
    int top = size.value("top").toInt();
    int left = size.value("left").toInt();

    if (w >= 0 && h >= 0)
        m_clipRect = QRect(left, top, w, h);
}

QVariantMap WebPage::clipRect() const
{
    QVariantMap result;
    result["width"] = m_clipRect.width();
    result["height"] = m_clipRect.height();
    result["top"] = m_clipRect.top();
    result["left"] = m_clipRect.left();
    return result;
}

void WebPage::setPaperSize(const QVariantMap &size)
{
    m_paperSize = size;
}

QVariantMap WebPage::paperSize() const
{
    return m_paperSize;
}

QVariant WebPage::evaluate(const QString &code)
{
    QString function = "(" + code + ")()";
    return m_mainFrame->evaluateJavaScript(function);
}

void WebPage::finish(bool ok)
{
    QString status = ok ? "success" : "fail";
    emit loadStatusChanged(status);
}

void WebPage::openUrl(const QString &address, const QVariant &op, const QVariantMap &settings)
{
    QString operation;
    QByteArray body;

    applySettings(settings);
    m_webPage->triggerAction(QWebPage::Stop);

    if (op.type() == QVariant::String)
        operation = op.toString();

    if (op.type() == QVariant::Map) {
        operation = op.toMap().value("operation").toString();
        body = op.toMap().value("data").toByteArray();
    }

    if (operation.isEmpty())
        operation = "get";

    QNetworkAccessManager::Operation networkOp = QNetworkAccessManager::UnknownOperation;
    operation = operation.toLower();
    if (operation == "get")
        networkOp = QNetworkAccessManager::GetOperation;
    else if (operation == "head")
        networkOp = QNetworkAccessManager::HeadOperation;
    else if (operation == "put")
        networkOp = QNetworkAccessManager::PutOperation;
    else if (operation == "post")
        networkOp = QNetworkAccessManager::PostOperation;
    else if (operation == "delete")
        networkOp = QNetworkAccessManager::DeleteOperation;

    if (networkOp == QNetworkAccessManager::UnknownOperation) {
        m_mainFrame->evaluateJavaScript("console.error('Unknown network operation: " + operation + "');");
        return;
    }

    m_mainFrame->load(QNetworkRequest(QUrl(address)), networkOp, body);
}

bool WebPage::render(const QString &fileName)
{
    if (m_mainFrame->contentsSize().isEmpty())
        return false;

    QFileInfo fileInfo(fileName);
    QDir dir;
    dir.mkpath(fileInfo.absolutePath());

    if (fileName.endsWith(".pdf", Qt::CaseInsensitive))
        return renderPdf(fileName);

    QImage buffer = renderImage();
    if (fileName.toLower().endsWith(".gif")) {
        return exportGif(buffer, fileName);
    }

    return buffer.save(fileName);
}

QImage WebPage::renderImage()
{
    QRect frameRect = QRect(QPoint(0, 0), m_mainFrame->contentsSize());
    if (!m_clipRect.isNull())
        frameRect = m_clipRect;

    QImage buffer(frameRect.size(), QImage::Format_ARGB32);
    buffer.fill(qRgba(255, 255, 255, 0));
    QPainter p(&buffer);

    p.setRenderHint(QPainter::Antialiasing, true);
    p.setRenderHint(QPainter::TextAntialiasing, true);
    p.setRenderHint(QPainter::SmoothPixmapTransform, true);

    QSize viewportSize = m_webPage->viewportSize();
    m_webPage->setViewportSize(m_mainFrame->contentsSize());

    p.translate(-frameRect.left(), -frameRect.top());
    m_mainFrame->render(&p, QRegion(frameRect));
    p.end();

    m_webPage->setViewportSize(viewportSize);

    return buffer;
}

#define PHANTOMJS_PDF_DPI 72            // Different defaults. OSX: 72, X11: 75(?), Windows: 96

qreal stringToPointSize(const QString &string)
{
    static const struct {
        QString unit;
        qreal factor;
    } units[] = {
        { "mm", 72 / 25.4 },
        { "cm", 72 / 2.54 },
        { "in", 72 },
        { "px", 72.0 / PHANTOMJS_PDF_DPI / 2.54 },
        { "", 72.0 / PHANTOMJS_PDF_DPI / 2.54 }
    };
    for (uint i = 0; i < sizeof(units) / sizeof(units[0]); ++i) {
        if (string.endsWith(units[i].unit)) {
            QString value = string;
            value.chop(units[i].unit.length());
            return value.toDouble() * units[i].factor;
        }
    }
    return 0;
}

bool WebPage::renderPdf(const QString &fileName)
{
    QPrinter printer;
    printer.setOutputFormat(QPrinter::PdfFormat);
    printer.setOutputFileName(fileName);
    printer.setResolution(PHANTOMJS_PDF_DPI);
    QVariantMap paperSize = m_paperSize;

    if (paperSize.isEmpty()) {
        const QSize pageSize = m_mainFrame->contentsSize();
        paperSize.insert("width", QString::number(pageSize.width()) + "px");
        paperSize.insert("height", QString::number(pageSize.height()) + "px");
        paperSize.insert("border", "0px");
    }

    if (paperSize.contains("width") && paperSize.contains("height")) {
        const QSizeF sizePt(ceil(stringToPointSize(paperSize.value("width").toString())),
                            ceil(stringToPointSize(paperSize.value("height").toString())));
        printer.setPaperSize(sizePt, QPrinter::Point);
    } else if (paperSize.contains("format")) {
        const QPrinter::Orientation orientation = paperSize.contains("orientation")
                && paperSize.value("orientation").toString().compare("landscape", Qt::CaseInsensitive) == 0 ?
                    QPrinter::Landscape : QPrinter::Portrait;
        printer.setOrientation(orientation);
        static const struct {
            QString format;
            QPrinter::PaperSize paperSize;
        } formats[] = {
            { "A3", QPrinter::A3 },
            { "A4", QPrinter::A4 },
            { "A5", QPrinter::A5 },
            { "Legal", QPrinter::Legal },
            { "Letter", QPrinter::Letter },
            { "Tabloid", QPrinter::Tabloid }
        };
        printer.setPaperSize(QPrinter::A4); // Fallback
        for (uint i = 0; i < sizeof(formats) / sizeof(formats[0]); ++i) {
            if (paperSize.value("format").toString().compare(formats[i].format, Qt::CaseInsensitive) == 0) {
                printer.setPaperSize(formats[i].paperSize);
                break;
            }
        }
    } else {
        return false;
    }

    const qreal border = paperSize.contains("border") ?
                floor(stringToPointSize(paperSize.value("border").toString())) : 0;
    printer.setPageMargins(border, border, border, border, QPrinter::Point);

    m_mainFrame->print(&printer);
    return true;
}
<commit_msg>Render the web page using tiling approach.<commit_after>/*
  This file is part of the PhantomJS project from Ofi Labs.

  Copyright (C) 2011 Ariya Hidayat <ariya.hidayat@gmail.com>
  Copyright (C) 2010 Ariya Hidayat <ariya.hidayat@gmail.com>

  Redistribution and use in source and binary forms, with or without
  modification, are permitted provided that the following conditions are met:

    * Redistributions of source code must retain the above copyright
      notice, this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright
      notice, this list of conditions and the following disclaimer in the
      documentation and/or other materials provided with the distribution.
    * Neither the name of the <organization> nor the
      names of its contributors may be used to endorse or promote products
      derived from this software without specific prior written permission.

  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
  DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
  (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
  ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
  THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

#include "webpage.h"

#include <iostream>
#include <math.h>

#include <QApplication>
#include <QDesktopServices>
#include <QDir>
#include <QFileInfo>
#include <QNetworkRequest>
#include <QNetworkAccessManager>
#include <QPainter>
#include <QPrinter>
#include <QWebFrame>
#include <QWebPage>

#include <gifwriter.h>

class CustomPage: public QWebPage
{
public:
    CustomPage(QObject *parent = 0)
        : QWebPage(parent)
    {
        m_userAgent = QWebPage::userAgentForUrl(QUrl());
    }

public slots:
    bool shouldInterruptJavaScript() {
        QApplication::processEvents(QEventLoop::AllEvents, 42);
        return false;
    }

protected:
    void javaScriptAlert(QWebFrame *originatingFrame, const QString &msg) {
        Q_UNUSED(originatingFrame);
        std::cout << "JavaScript alert: " << qPrintable(msg) << std::endl;
    }

    void javaScriptConsoleMessage(const QString &message, int lineNumber, const QString &sourceID) {
        if (!sourceID.isEmpty())
            std::cout << qPrintable(sourceID) << ":" << lineNumber << " ";
        std::cout << qPrintable(message) << std::endl;
    }

    QString userAgentForUrl(const QUrl &url) const {
        Q_UNUSED(url);
        return m_userAgent;
    }

private:
    QString m_userAgent;
    friend class WebPage;
};

WebPage::WebPage(QObject *parent)
    : QObject(parent)
{
    setObjectName("WebPage");
    m_webPage = new CustomPage(this);
    m_mainFrame = m_webPage->mainFrame();

    connect(m_webPage, SIGNAL(loadFinished(bool)), SLOT(finish(bool)));

    // Start with transparent background.
    QPalette palette = m_webPage->palette();
    palette.setBrush(QPalette::Base, Qt::transparent);
    m_webPage->setPalette(palette);

    // Page size does not need to take scrollbars into account.
    m_mainFrame->setScrollBarPolicy(Qt::Horizontal, Qt::ScrollBarAlwaysOff);
    m_mainFrame->setScrollBarPolicy(Qt::Vertical, Qt::ScrollBarAlwaysOff);

    m_webPage->settings()->setAttribute(QWebSettings::OfflineStorageDatabaseEnabled, true);
    m_webPage->settings()->setOfflineStoragePath(QDesktopServices::storageLocation(QDesktopServices::DataLocation));

    m_webPage->settings()->setAttribute(QWebSettings::LocalStorageDatabaseEnabled, true);

#if QT_VERSION >= QT_VERSION_CHECK(4, 7, 0)
    m_webPage->settings()->setAttribute(QWebSettings::FrameFlatteningEnabled, true);
#endif

#if QT_VERSION >= QT_VERSION_CHECK(4, 6, 0)
    m_webPage->settings()->setAttribute(QWebSettings::LocalStorageEnabled, true);
    m_webPage->settings()->setLocalStoragePath(QDesktopServices::storageLocation(QDesktopServices::DataLocation));
#endif

    // Ensure we have at least document.body.
    m_mainFrame->setHtml("");

    m_webPage->setViewportSize(QSize(400, 300));
}

QWebFrame *WebPage::mainFrame()
{
    return m_mainFrame;
}

void WebPage::setNetworkAccessManager(QNetworkAccessManager *networkAccessManager)
{
    m_webPage->setNetworkAccessManager(networkAccessManager);
}

QString WebPage::content() const
{
    return m_mainFrame->toHtml();
}

void WebPage::setContent(const QString &content)
{
    m_mainFrame->setHtml(content);
}

void WebPage::applySettings(const QVariantMap &def)
{
    QWebSettings *opt = m_webPage->settings();

    opt->setAttribute(QWebSettings::AutoLoadImages, def["loadImages"].toBool());
    opt->setAttribute(QWebSettings::PluginsEnabled, def["loadPlugins"].toBool());

    if (def.contains("userAgent"))
        m_webPage->m_userAgent = def["userAgent"].toString();
}

QString WebPage::userAgent() const
{
    return m_webPage->m_userAgent;
}

void WebPage::setViewportSize(const QVariantMap &size)
{
    int w = size.value("width").toInt();
    int h = size.value("height").toInt();
    if (w > 0 && h > 0)
        m_webPage->setViewportSize(QSize(w, h));
}

QVariantMap WebPage::viewportSize() const
{
    QVariantMap result;
    QSize size = m_webPage->viewportSize();
    result["width"] = size.width();
    result["height"] = size.height();
    return result;
}

void WebPage::setClipRect(const QVariantMap &size)
{
    int w = size.value("width").toInt();
    int h = size.value("height").toInt();
    int top = size.value("top").toInt();
    int left = size.value("left").toInt();

    if (w >= 0 && h >= 0)
        m_clipRect = QRect(left, top, w, h);
}

QVariantMap WebPage::clipRect() const
{
    QVariantMap result;
    result["width"] = m_clipRect.width();
    result["height"] = m_clipRect.height();
    result["top"] = m_clipRect.top();
    result["left"] = m_clipRect.left();
    return result;
}

void WebPage::setPaperSize(const QVariantMap &size)
{
    m_paperSize = size;
}

QVariantMap WebPage::paperSize() const
{
    return m_paperSize;
}

QVariant WebPage::evaluate(const QString &code)
{
    QString function = "(" + code + ")()";
    return m_mainFrame->evaluateJavaScript(function);
}

void WebPage::finish(bool ok)
{
    QString status = ok ? "success" : "fail";
    emit loadStatusChanged(status);
}

void WebPage::openUrl(const QString &address, const QVariant &op, const QVariantMap &settings)
{
    QString operation;
    QByteArray body;

    applySettings(settings);
    m_webPage->triggerAction(QWebPage::Stop);

    if (op.type() == QVariant::String)
        operation = op.toString();

    if (op.type() == QVariant::Map) {
        operation = op.toMap().value("operation").toString();
        body = op.toMap().value("data").toByteArray();
    }

    if (operation.isEmpty())
        operation = "get";

    QNetworkAccessManager::Operation networkOp = QNetworkAccessManager::UnknownOperation;
    operation = operation.toLower();
    if (operation == "get")
        networkOp = QNetworkAccessManager::GetOperation;
    else if (operation == "head")
        networkOp = QNetworkAccessManager::HeadOperation;
    else if (operation == "put")
        networkOp = QNetworkAccessManager::PutOperation;
    else if (operation == "post")
        networkOp = QNetworkAccessManager::PostOperation;
    else if (operation == "delete")
        networkOp = QNetworkAccessManager::DeleteOperation;

    if (networkOp == QNetworkAccessManager::UnknownOperation) {
        m_mainFrame->evaluateJavaScript("console.error('Unknown network operation: " + operation + "');");
        return;
    }

    m_mainFrame->load(QNetworkRequest(QUrl(address)), networkOp, body);
}

bool WebPage::render(const QString &fileName)
{
    if (m_mainFrame->contentsSize().isEmpty())
        return false;

    QFileInfo fileInfo(fileName);
    QDir dir;
    dir.mkpath(fileInfo.absolutePath());

    if (fileName.endsWith(".pdf", Qt::CaseInsensitive))
        return renderPdf(fileName);

    QImage buffer = renderImage();
    if (fileName.toLower().endsWith(".gif")) {
        return exportGif(buffer, fileName);
    }

    return buffer.save(fileName);
}

QImage WebPage::renderImage()
{
    QRect frameRect = QRect(QPoint(0, 0), m_mainFrame->contentsSize());
    if (!m_clipRect.isNull())
        frameRect = m_clipRect;

    QSize viewportSize = m_webPage->viewportSize();
    m_webPage->setViewportSize(m_mainFrame->contentsSize());

    QImage buffer(frameRect.size(), QImage::Format_ARGB32);
    buffer.fill(qRgba(255, 255, 255, 0));

    QPainter painter;

    // We use tiling approach to work-around Qt software rasterizer bug
    // when dealing with very large paint device.
    // See http://code.google.com/p/phantomjs/issues/detail?id=54.
    const int tileSize = 4096;
    int htiles = (buffer.width() + tileSize - 1) / tileSize;
    int vtiles = (buffer.height() + tileSize - 1) / tileSize;
    for (int x = 0; x < htiles; ++x) {
        for (int y = 0; y < vtiles; ++y) {

            QImage tileBuffer(tileSize, tileSize, QImage::Format_ARGB32);
            tileBuffer.fill(qRgba(255, 255, 255, 0));

            // Render the web page onto the small tile first
            painter.begin(&tileBuffer);
            painter.setRenderHint(QPainter::Antialiasing, true);
            painter.setRenderHint(QPainter::TextAntialiasing, true);
            painter.setRenderHint(QPainter::SmoothPixmapTransform, true);
            painter.translate(-frameRect.left(), -frameRect.top());
            painter.translate(-x * tileSize, -y * tileSize);
            m_mainFrame->render(&painter, QRegion(frameRect));
            painter.end();

            // Copy the tile to the main buffer
            painter.begin(&buffer);
            painter.setCompositionMode(QPainter::CompositionMode_Source);
            painter.drawImage(x * tileSize, y * tileSize, tileBuffer);
            painter.end();
        }
    }

    m_webPage->setViewportSize(viewportSize);

    return buffer;
}

#define PHANTOMJS_PDF_DPI 72            // Different defaults. OSX: 72, X11: 75(?), Windows: 96

qreal stringToPointSize(const QString &string)
{
    static const struct {
        QString unit;
        qreal factor;
    } units[] = {
        { "mm", 72 / 25.4 },
        { "cm", 72 / 2.54 },
        { "in", 72 },
        { "px", 72.0 / PHANTOMJS_PDF_DPI / 2.54 },
        { "", 72.0 / PHANTOMJS_PDF_DPI / 2.54 }
    };
    for (uint i = 0; i < sizeof(units) / sizeof(units[0]); ++i) {
        if (string.endsWith(units[i].unit)) {
            QString value = string;
            value.chop(units[i].unit.length());
            return value.toDouble() * units[i].factor;
        }
    }
    return 0;
}

bool WebPage::renderPdf(const QString &fileName)
{
    QPrinter printer;
    printer.setOutputFormat(QPrinter::PdfFormat);
    printer.setOutputFileName(fileName);
    printer.setResolution(PHANTOMJS_PDF_DPI);
    QVariantMap paperSize = m_paperSize;

    if (paperSize.isEmpty()) {
        const QSize pageSize = m_mainFrame->contentsSize();
        paperSize.insert("width", QString::number(pageSize.width()) + "px");
        paperSize.insert("height", QString::number(pageSize.height()) + "px");
        paperSize.insert("border", "0px");
    }

    if (paperSize.contains("width") && paperSize.contains("height")) {
        const QSizeF sizePt(ceil(stringToPointSize(paperSize.value("width").toString())),
                            ceil(stringToPointSize(paperSize.value("height").toString())));
        printer.setPaperSize(sizePt, QPrinter::Point);
    } else if (paperSize.contains("format")) {
        const QPrinter::Orientation orientation = paperSize.contains("orientation")
                && paperSize.value("orientation").toString().compare("landscape", Qt::CaseInsensitive) == 0 ?
                    QPrinter::Landscape : QPrinter::Portrait;
        printer.setOrientation(orientation);
        static const struct {
            QString format;
            QPrinter::PaperSize paperSize;
        } formats[] = {
            { "A3", QPrinter::A3 },
            { "A4", QPrinter::A4 },
            { "A5", QPrinter::A5 },
            { "Legal", QPrinter::Legal },
            { "Letter", QPrinter::Letter },
            { "Tabloid", QPrinter::Tabloid }
        };
        printer.setPaperSize(QPrinter::A4); // Fallback
        for (uint i = 0; i < sizeof(formats) / sizeof(formats[0]); ++i) {
            if (paperSize.value("format").toString().compare(formats[i].format, Qt::CaseInsensitive) == 0) {
                printer.setPaperSize(formats[i].paperSize);
                break;
            }
        }
    } else {
        return false;
    }

    const qreal border = paperSize.contains("border") ?
                floor(stringToPointSize(paperSize.value("border").toString())) : 0;
    printer.setPageMargins(border, border, border, border, QPrinter::Point);

    m_mainFrame->print(&printer);
    return true;
}
<|endoftext|>


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

#ifndef _DBACCESS_UI_CALLBACKS_HXX_
#define _DBACCESS_UI_CALLBACKS_HXX_

#ifndef _SOT_EXCHANGE_HXX
#include <sot/exchange.hxx>
#endif
#ifndef _SOT_FORMATS_HXX
#include <sot/formats.hxx>
#endif
#ifndef _COM_SUN_STAR_CONTAINER_XCONTAINER_HPP_
#include <com/sun/star/container/XContainer.hpp>
#endif

class CommandEvent;
struct AcceptDropEvent;
struct ExecuteDropEvent;

//........................................................................
namespace dbaui
{
//........................................................................
    //====================================================================
    //= IControlActionListener
    //====================================================================
    class IControlActionListener
    {
    public:
        /** handler for context menu requests
            @return <TRUE/> if the request was handled
        */
        virtual sal_Bool    requestContextMenu( const CommandEvent& _rEvent ) = 0;

        /** handler for StartDrag requests
            @return <TRUE/> if a drag operation was started
        */
        virtual sal_Bool    requestDrag( sal_Int8 _nAction, const Point& _rPosPixel ) = 0;

        /** check whether or no a drop request should be accepted
        */
        virtual sal_Int8    queryDrop( const AcceptDropEvent& _rEvt, const DataFlavorExVector& _rFlavors ) = 0;

        /** execute a drop request
        */
        virtual sal_Int8    executeDrop( const ExecuteDropEvent& _rEvt ) = 0;
    };

    //====================================================================
    //= IDragTransferableListener
    //====================================================================
    class IDragTransferableListener
    {
    public:
        /// called when a drag operation done with a Transferable has been finished
        virtual void        dragFinished( ) = 0;
    };

    //====================================================================
    //= IContainerFoundListener
    //====================================================================
    class SAL_NO_VTABLE IContainerFoundListener
    {
    public:
        /// called when a container was found
        virtual void containerFound( const ::com::sun::star::uno::Reference< ::com::sun::star::container::XContainer >& _xContainer) = 0;
    };

    //====================================================================
    //= IViewChangeListener
    //====================================================================
    class SAL_NO_VTABLE IViewChangeListener
    {
    public:
        /// called when the preview mode was changed
        virtual void previewChanged( sal_Int32 _nMode) = 0;
    };

//........................................................................
}   // namespace dbaui
//........................................................................

#endif // _DBACCESS_UI_CALLBACKS_HXX_

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

#ifndef _DBACCESS_UI_CALLBACKS_HXX_
#define _DBACCESS_UI_CALLBACKS_HXX_

#ifndef _SOT_EXCHANGE_HXX
#include <sot/exchange.hxx>
#endif
#ifndef _SOT_FORMATS_HXX
#include <sot/formats.hxx>
#endif
#ifndef _COM_SUN_STAR_CONTAINER_XCONTAINER_HPP_
#include <com/sun/star/container/XContainer.hpp>
#endif

class CommandEvent;
class SvLBoxEntry;
class String;
struct AcceptDropEvent;
struct ExecuteDropEvent;

//........................................................................
namespace dbaui
{
//........................................................................

    //====================================================================
    //= IControlActionListener
    //====================================================================
    class IControlActionListener
    {
    public:
        /** handler for context menu requests
            @return <TRUE/> if the request was handled
        */
        virtual sal_Bool    requestContextMenu( const CommandEvent& _rEvent ) = 0;

        /** requests a quick help text to display
            @return <FALSE/> if the default quick help text should be used
        */
        virtual sal_Bool    requestQuickHelp( const SvLBoxEntry* _pEntry, String& _rText ) const = 0;

        /** handler for StartDrag requests
            @return <TRUE/> if a drag operation was started
        */
        virtual sal_Bool    requestDrag( sal_Int8 _nAction, const Point& _rPosPixel ) = 0;

        /** check whether or no a drop request should be accepted
        */
        virtual sal_Int8    queryDrop( const AcceptDropEvent& _rEvt, const DataFlavorExVector& _rFlavors ) = 0;

        /** execute a drop request
        */
        virtual sal_Int8    executeDrop( const ExecuteDropEvent& _rEvt ) = 0;
    };

    //====================================================================
    //= IDragTransferableListener
    //====================================================================
    class IDragTransferableListener
    {
    public:
        /// called when a drag operation done with a Transferable has been finished
        virtual void        dragFinished( ) = 0;
    };

    //====================================================================
    //= IContainerFoundListener
    //====================================================================
    class SAL_NO_VTABLE IContainerFoundListener
    {
    public:
        /// called when a container was found
        virtual void containerFound( const ::com::sun::star::uno::Reference< ::com::sun::star::container::XContainer >& _xContainer) = 0;
    };

    //====================================================================
    //= IViewChangeListener
    //====================================================================
    class SAL_NO_VTABLE IViewChangeListener
    {
    public:
        /// called when the preview mode was changed
        virtual void previewChanged( sal_Int32 _nMode) = 0;
    };

//........................................................................
}   // namespace dbaui
//........................................................................

#endif // _DBACCESS_UI_CALLBACKS_HXX_

<|endoftext|>


<commit_before>/*
 * Copyright (c) 2015 FinChain, Inc., and contributors.
 *
 * The MIT License
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */

#include <boost/test/unit_test.hpp>

#include <graphene/chain/database.hpp>
#include <graphene/chain/exceptions.hpp>
#include <graphene/chain/hardfork.hpp>

#include <graphene/chain/account_object.hpp>
#include <graphene/chain/asset_object.hpp>
#include <graphene/chain/committee_member_object.hpp>
#include <graphene/chain/market_object.hpp>
#include <graphene/chain/vesting_balance_object.hpp>
#include <graphene/chain/withdraw_permission_object.hpp>
#include <graphene/chain/witness_object.hpp>

#include <fc/crypto/digest.hpp>

#include "../common/database_fixture.hpp"

using namespace graphene::chain;
using namespace graphene::chain::test;

BOOST_FIXTURE_TEST_SUITE( operation_tests, database_fixture )

BOOST_AUTO_TEST_CASE(lock_balance_test)
{
	try {
		ACTORS((dan));
		const auto& core = asset_id_type()(db);
		auto total = get_balance(committee_account, asset_id_type());
		auto total3 = get_balance(account_id_type(3), asset_id_type());
		BOOST_CHECK_EQUAL(get_balance(dan_id, asset_id_type()), 0);
		transfer(committee_account, dan_id, asset(10000));
		transfer(committee_account, account_id_type(3), asset(100000000));

		create_lock_able_asset(committee_account,asset_id_type(0),50,45,300000000LL*100000LL);
		{
			lock_balance_operation op;
			op.fee = asset();
			op.issuer = dan_id;
			op.amount = asset(1000);
			op.period = 3600 * 24;
			trx.operations.push_back(op);

			sign(trx, dan_private_key);
			db.push_transaction(trx);
			trx.clear();
		}
		generate_block();
		BOOST_CHECK_EQUAL(get_balance(dan_id, asset_id_type()), 10000 - 1000);
#if 1
		{
			unlock_balance_operation op;
			op.fee = asset();
			op.issuer = dan_id;
			const auto & ids = db.get_locked_balance_ids(dan_id, asset_id_type());
			FC_ASSERT(ids.size() > 0, "dan didn't has locked balance!");

			unlock_balance_operation::unlock_detail one;
			one.locked_id = ids.at(0);
			one.expired = false;
			op.locked.push_back(one);
			trx.operations.push_back(op);

			sign(trx, dan_private_key);
			db.push_transaction(trx);
			trx.clear();
		}
		generate_block();

		BOOST_CHECK_EQUAL(get_balance(dan_id, asset_id_type()), 10000);
#endif

#if 1
		{
			donation_balance_operation op;
			op.fee = asset();
			op.issuer = dan_id;
			op.amount = asset(999);

			trx.operations.push_back(op);

			sign(trx, dan_private_key);
			db.push_transaction(trx);
			trx.clear();
		}
		generate_block();
		BOOST_CHECK_EQUAL(get_balance(dan_id, asset_id_type()), 10000 - 999);
#endif
	}
	catch (fc::exception& e) {
		edump((e.to_detail_string()));
		throw;
	}
}

BOOST_AUTO_TEST_SUITE_END()
<commit_msg>compile issue<commit_after>/*
 * Copyright (c) 2015 FinChain, Inc., and contributors.
 *
 * The MIT License
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */

#include <boost/test/unit_test.hpp>

#include <graphene/chain/database.hpp>
#include <graphene/chain/exceptions.hpp>
#include <graphene/chain/hardfork.hpp>

#include <graphene/chain/account_object.hpp>
#include <graphene/chain/asset_object.hpp>
#include <graphene/chain/committee_member_object.hpp>
#include <graphene/chain/market_object.hpp>
#include <graphene/chain/vesting_balance_object.hpp>
#include <graphene/chain/withdraw_permission_object.hpp>
#include <graphene/chain/witness_object.hpp>

#include <fc/crypto/digest.hpp>

#include "../common/database_fixture.hpp"

using namespace graphene::chain;
using namespace graphene::chain::test;

BOOST_FIXTURE_TEST_SUITE( operation_tests, database_fixture )

BOOST_AUTO_TEST_CASE(lock_balance_test)
{
	try {
		ACTORS((dan));
		const auto& core = asset_id_type()(db);
		auto total = get_balance(committee_account, asset_id_type());
		auto total3 = get_balance(account_id_type(3), asset_id_type());
		BOOST_CHECK_EQUAL(get_balance(dan_id, asset_id_type()), 0);
		transfer(committee_account, dan_id, asset(10000));
		transfer(committee_account, account_id_type(3), asset(100000000));

		create_lock_able_asset(committee_account,asset_id_type(0),50,45,300000000LL*100000LL);
		{
			lock_balance_operation op;
			op.fee = asset();
			op.issuer = dan_id;
			op.amount = asset(1000);
			op.period = 3600 * 24;
			trx.operations.push_back(op);

			sign(trx, dan_private_key);
			db.push_transaction(trx);
			trx.clear();
		}
		generate_block();
		BOOST_CHECK_EQUAL(get_balance(dan_id, asset_id_type()), 10000 - 1000);
#if 1
		{
			unlock_balance_operation op;
			op.fee = asset();
			op.issuer = dan_id;
			const auto & ids = db.get_locked_balance_ids(dan_id, asset_id_type());
			FC_ASSERT(ids.size() > 0, "dan didn't has locked balance!");

			unlock_balance_operation::unlock_detail one;
			one.locked_id = ids.at(0);
			one.expired = false;
			op.lockeds.push_back(one);
			trx.operations.push_back(op);

			sign(trx, dan_private_key);
			db.push_transaction(trx);
			trx.clear();
		}
		generate_block();

		BOOST_CHECK_EQUAL(get_balance(dan_id, asset_id_type()), 10000);
#endif

#if 1
		{
			donation_balance_operation op;
			op.fee = asset();
			op.issuer = dan_id;
			op.amount = asset(999);

			trx.operations.push_back(op);

			sign(trx, dan_private_key);
			db.push_transaction(trx);
			trx.clear();
		}
		generate_block();
		BOOST_CHECK_EQUAL(get_balance(dan_id, asset_id_type()), 10000 - 999);
#endif
	}
	catch (fc::exception& e) {
		edump((e.to_detail_string()));
		throw;
	}
}

BOOST_AUTO_TEST_SUITE_END()
<|endoftext|>


<commit_before>/*
 *  tinyTest.c
 *  BEAGLE
 *
 *  Created by Andrew Rambaut on 20/03/2009.
 *  Copyright 2009 __MyCompanyName__. All rights reserved.
 *
 */
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <iostream>

#include "libhmsbeagle/beagle.h"

char *human = "AGAAATATGTCTGATAAAAGAGTTACTTTGATAGAGTAAATAATAGGAGCTTAAACCCCCTTATTTCTACTAGGACTATGAGAATCGAACCCATCCCTGAGAATCCAAAATTCTCCGTGCCACCTATCACACCCCATCCTAAGTAAGGTCAGCTAAATAAGCTATCGGGCCCATACCCCGAAAATGTTGGTTATACCCTTCCCGTACTAAGAAATTTAGGTTAAATACAGACCAAGAGCCTTCAAAGCCCTCAGTAAGTTG-CAATACTTAATTTCTGTAAGGACTGCAAAACCCCACTCTGCATCAACTGAACGCAAATCAGCCACTTTAATTAAGCTAAGCCCTTCTAGACCAATGGGACTTAAACCCACAAACACTTAGTTAACAGCTAAGCACCCTAATCAAC-TGGCTTCAATCTAAAGCCCCGGCAGG-TTTGAAGCTGCTTCTTCGAATTTGCAATTCAATATGAAAA-TCACCTCGGAGCTTGGTAAAAAGAGGCCTAACCCCTGTCTTTAGATTTACAGTCCAATGCTTCA-CTCAGCCATTTTACCACAAAAAAGGAAGGAATCGAACCCCCCAAAGCTGGTTTCAAGCCAACCCCATGGCCTCCATGACTTTTTCAAAAGGTATTAGAAAAACCATTTCATAACTTTGTCAAAGTTAAATTATAGGCT-AAATCCTATATATCTTA-CACTGTAAAGCTAACTTAGCATTAACCTTTTAAGTTAAAGATTAAGAGAACCAACACCTCTTTACAGTGA";
char *chimp = "AGAAATATGTCTGATAAAAGAATTACTTTGATAGAGTAAATAATAGGAGTTCAAATCCCCTTATTTCTACTAGGACTATAAGAATCGAACTCATCCCTGAGAATCCAAAATTCTCCGTGCCACCTATCACACCCCATCCTAAGTAAGGTCAGCTAAATAAGCTATCGGGCCCATACCCCGAAAATGTTGGTTACACCCTTCCCGTACTAAGAAATTTAGGTTAAGCACAGACCAAGAGCCTTCAAAGCCCTCAGCAAGTTA-CAATACTTAATTTCTGTAAGGACTGCAAAACCCCACTCTGCATCAACTGAACGCAAATCAGCCACTTTAATTAAGCTAAGCCCTTCTAGATTAATGGGACTTAAACCCACAAACATTTAGTTAACAGCTAAACACCCTAATCAAC-TGGCTTCAATCTAAAGCCCCGGCAGG-TTTGAAGCTGCTTCTTCGAATTTGCAATTCAATATGAAAA-TCACCTCAGAGCTTGGTAAAAAGAGGCTTAACCCCTGTCTTTAGATTTACAGTCCAATGCTTCA-CTCAGCCATTTTACCACAAAAAAGGAAGGAATCGAACCCCCTAAAGCTGGTTTCAAGCCAACCCCATGACCTCCATGACTTTTTCAAAAGATATTAGAAAAACTATTTCATAACTTTGTCAAAGTTAAATTACAGGTT-AACCCCCGTATATCTTA-CACTGTAAAGCTAACCTAGCATTAACCTTTTAAGTTAAAGATTAAGAGGACCGACACCTCTTTACAGTGA";
char *gorilla = "AGAAATATGTCTGATAAAAGAGTTACTTTGATAGAGTAAATAATAGAGGTTTAAACCCCCTTATTTCTACTAGGACTATGAGAATTGAACCCATCCCTGAGAATCCAAAATTCTCCGTGCCACCTGTCACACCCCATCCTAAGTAAGGTCAGCTAAATAAGCTATCGGGCCCATACCCCGAAAATGTTGGTCACATCCTTCCCGTACTAAGAAATTTAGGTTAAACATAGACCAAGAGCCTTCAAAGCCCTTAGTAAGTTA-CAACACTTAATTTCTGTAAGGACTGCAAAACCCTACTCTGCATCAACTGAACGCAAATCAGCCACTTTAATTAAGCTAAGCCCTTCTAGATCAATGGGACTCAAACCCACAAACATTTAGTTAACAGCTAAACACCCTAGTCAAC-TGGCTTCAATCTAAAGCCCCGGCAGG-TTTGAAGCTGCTTCTTCGAATTTGCAATTCAATATGAAAT-TCACCTCGGAGCTTGGTAAAAAGAGGCCCAGCCTCTGTCTTTAGATTTACAGTCCAATGCCTTA-CTCAGCCATTTTACCACAAAAAAGGAAGGAATCGAACCCCCCAAAGCTGGTTTCAAGCCAACCCCATGACCTTCATGACTTTTTCAAAAGATATTAGAAAAACTATTTCATAACTTTGTCAAGGTTAAATTACGGGTT-AAACCCCGTATATCTTA-CACTGTAAAGCTAACCTAGCGTTAACCTTTTAAGTTAAAGATTAAGAGTATCGGCACCTCTTTGCAGTGA";

int* getStates(char *sequence) {
	int n = strlen(sequence);
	int *states = (int*) malloc(sizeof(int) * n);

	for (int i = 0; i < n; i++) {
		switch (sequence[i]) {
			case 'A':
				states[i] = 0;
				break;
			case 'C':
				states[i] = 1;
				break;
			case 'G':
				states[i] = 2;
				break;
			case 'T':
				states[i] = 3;
				break;
			default:
				states[i] = 4;
				break;
		}
	}
	return states;
}

double* getPartials(char *sequence) {
	int n = strlen(sequence);
	double *partials = (double*)malloc(sizeof(double) * n * 4);

    int k = 0;
	for (int i = 0; i < n; i++) {
		switch (sequence[i]) {
			case 'A':
				partials[k++] = 1;
				partials[k++] = 0;
				partials[k++] = 0;
				partials[k++] = 0;
				break;
			case 'C':
				partials[k++] = 0;
				partials[k++] = 1;
				partials[k++] = 0;
				partials[k++] = 0;
				break;
			case 'G':
				partials[k++] = 0;
				partials[k++] = 0;
				partials[k++] = 1;
				partials[k++] = 0;
				break;
			case 'T':
				partials[k++] = 0;
				partials[k++] = 0;
				partials[k++] = 0;
				partials[k++] = 1;
				break;
			default:
				partials[k++] = 1;
				partials[k++] = 1;
				partials[k++] = 1;
				partials[k++] = 1;
				break;
		}
	}
	return partials;
}

int main( int argc, const char* argv[] )
{
    // print resource list
    ResourceList* rList;
    rList = getResourceList();
    fprintf(stdout, "Available resources:\n");
    for (int i = 0; i < rList->length; i++) {
        fprintf(stdout, "\tResource %i:\n\t\tName : %s\n", i, rList->list[i].name);
        fprintf(stdout, "\t\tFlags:");
        if (rList->list[i].flags & DOUBLE)
            fprintf(stdout, " DOUBLE");
        if (rList->list[i].flags & SINGLE)
            fprintf(stdout, " SINGLE");
        if (rList->list[i].flags & ASYNCH)
            fprintf(stdout, " ASYNCH");
        if (rList->list[i].flags & SYNCH)
            fprintf(stdout, " SYNCH");
        if (rList->list[i].flags & CPU)
            fprintf(stdout, " CPU");
        if (rList->list[i].flags & GPU)
            fprintf(stdout, " GPU");
        if (rList->list[i].flags & FPGA)
            fprintf(stdout, " FPGA");
        if (rList->list[i].flags & SSE)
            fprintf(stdout, " SSE");
        if (rList->list[i].flags & CELL)
            fprintf(stdout, " CELL");
        fprintf(stdout, "\n");

    }
    free(rList->list);
    free(rList);

    // is nucleotides...
    int stateCount = 4;

    // get the number of site patterns
	int nPatterns = strlen(human);

    // create an instance of the BEAGLE library
	int instance = createInstance(
                                  3,				/**< Number of tip data elements (input) */
                                  5,	            /**< Number of partials buffers to create (input) */
                                  0,		        /**< Number of compact state representation buffers to create (input) */
                                  stateCount,		/**< Number of states in the continuous-time Markov chain (input) */
                                  nPatterns,		/**< Number of site patterns to be handled by the instance (input) */
                                  1,		        /**< Number of rate matrix eigen-decomposition buffers to allocate (input) */
                                  4,		        /**< Number of rate matrix buffers (input) */
                                  1,              /**< Number of rate categories (input) */
                                  5,              /**< Number of scaling buffers */
                                  NULL,			/**< List of potential resource on which this instance is allowed (input, NULL implies no restriction */
                                  0,			    /**< Length of resourceList list (input) */
                                  0,		        /**< Bit-flags indicating preferred implementation charactertistics, see BeagleFlags (input) */
                                  0		        /**< Bit-flags indicating required implementation characteristics, see BeagleFlags (input) */
                                  );
    if (instance < 0) {
	    fprintf(stderr, "Failed to obtain BEAGLE instance\n\n");
	    exit(1);
    }

    // initialize the instance
    int error = initializeInstance(instance, NULL);

    if (error < 0) {
	    fprintf(stderr, "Failed to initialize BEAGLE instance\n\n");
	    exit(1);
    }

    //	setTipStates(instance, 0, getStates(human));
    //	setTipStates(instance, 1, getStates(chimp));
    //	setTipStates(instance, 2, getStates(gorilla));

    // set the sequences for each tip using partial likelihood arrays
	setTipPartials(instance, 0, getPartials(human));
	setTipPartials(instance, 1, getPartials(chimp));
	setTipPartials(instance, 2, getPartials(gorilla));

	double rates[1] = { 1.0 };
	setCategoryRates(instance, rates);

    // create base frequency array
	double freqs[4] = { 0.25, 0.25, 0.25, 0.25 };

    // create an array containing site category weights
	const double weights[1] = { 1.0 };

	// an eigen decomposition for the JC69 model
	double evec[4 * 4] = {
        1.0,  2.0,  0.0,  0.5,
        1.0,  -2.0,  0.5,  0.0,
        1.0,  2.0, 0.0,  -0.5,
        1.0,  -2.0,  -0.5,  0.0
	};

	double ivec[4 * 4] = {
        0.25,  0.25,  0.25,  0.25,
        0.125,  -0.125,  0.125,  -0.125,
        0.0,  1.0,  0.0,  -1.0,
        1.0,  0.0,  -1.0,  0.0
	};

	double eval[4] = { 0.0, -1.3333333333333333, -1.3333333333333333, -1.3333333333333333 };

    // set the Eigen decomposition
	setEigenDecomposition(instance, 0, evec, ivec, eval);

    // a list of indices and edge lengths
	int nodeIndices[4] = { 0, 1, 2, 3 };
	double edgeLengths[4] = { 0.1, 0.1, 0.2, 0.1 };

    // tell BEAGLE to populate the transition matrices for the above edge lengths
	updateTransitionMatrices(instance,     // instance
	                         0,             // eigenIndex
	                         nodeIndices,   // probabilityIndices
	                         NULL,          // firstDerivativeIndices
	                         NULL,          // secondDervativeIndices
	                         edgeLengths,   // edgeLengths
	                         4);            // count

    // create a list of partial likelihood update operations
    // the order is [dest, destScaling, source1, matrix1, source2, matrix2]
	int operations[7 * 2] = {
		3, 3, 0, 0, 0, 1, 1,
		4, 4, 0, 2, 2, 3, 3
	};
	int rootIndex = 4;

    // update the partials
	updatePartials( &instance,      // instance
                   1,              // instanceCount
                   operations,     // eigenIndex
                   2,              // operationCount
                   0);             // rescale ? 0 = no

	double *patternLogLik = (double*)malloc(sizeof(double) * nPatterns);

    int scalingFactorsIndices[2] = {3, 4}; // internal nodes
    int scalingFactorsCount = 2;

    int cumulativeScalingFactorIndex = 0;

    resetScaleFactors(instance,
                      cumulativeScalingFactorIndex);

    accumulateScaleFactors(instance,
                           scalingFactorsIndices,
                           scalingFactorsCount,
                           cumulativeScalingFactorIndex);

    // calculate the site likelihoods at the root node
	calculateRootLogLikelihoods(instance,               // instance
	                            (const int *)&rootIndex,// bufferIndices
	                            weights,                // weights
	                            freqs,                 // stateFrequencies
                                &cumulativeScalingFactorIndex,
	                            1,                      // count
	                            patternLogLik);         // outLogLikelihoods

	double logL = 0.0;
	for (int i = 0; i < nPatterns; i++) {
		std::cerr << "site lnL[" << i << "] = " << patternLogLik[i] << '\n';
		logL += patternLogLik[i];
	}

	fprintf(stdout, "logL = %.5f (PAUP logL = -1574.63623)\n\n", logL);

    finalize(instance);

}
<commit_msg>added support for run time selection of resource (not very robust at the moment but allows running on CPU or GPU, see example in tinytest, genomictest);<commit_after>/*
 *  tinyTest.c
 *  BEAGLE
 *
 *  Created by Andrew Rambaut on 20/03/2009.
 *  Copyright 2009 __MyCompanyName__. All rights reserved.
 *
 */
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <iostream>

#include "libhmsbeagle/beagle.h"

char *human = "AGAAATATGTCTGATAAAAGAGTTACTTTGATAGAGTAAATAATAGGAGCTTAAACCCCCTTATTTCTACTAGGACTATGAGAATCGAACCCATCCCTGAGAATCCAAAATTCTCCGTGCCACCTATCACACCCCATCCTAAGTAAGGTCAGCTAAATAAGCTATCGGGCCCATACCCCGAAAATGTTGGTTATACCCTTCCCGTACTAAGAAATTTAGGTTAAATACAGACCAAGAGCCTTCAAAGCCCTCAGTAAGTTG-CAATACTTAATTTCTGTAAGGACTGCAAAACCCCACTCTGCATCAACTGAACGCAAATCAGCCACTTTAATTAAGCTAAGCCCTTCTAGACCAATGGGACTTAAACCCACAAACACTTAGTTAACAGCTAAGCACCCTAATCAAC-TGGCTTCAATCTAAAGCCCCGGCAGG-TTTGAAGCTGCTTCTTCGAATTTGCAATTCAATATGAAAA-TCACCTCGGAGCTTGGTAAAAAGAGGCCTAACCCCTGTCTTTAGATTTACAGTCCAATGCTTCA-CTCAGCCATTTTACCACAAAAAAGGAAGGAATCGAACCCCCCAAAGCTGGTTTCAAGCCAACCCCATGGCCTCCATGACTTTTTCAAAAGGTATTAGAAAAACCATTTCATAACTTTGTCAAAGTTAAATTATAGGCT-AAATCCTATATATCTTA-CACTGTAAAGCTAACTTAGCATTAACCTTTTAAGTTAAAGATTAAGAGAACCAACACCTCTTTACAGTGA";
char *chimp = "AGAAATATGTCTGATAAAAGAATTACTTTGATAGAGTAAATAATAGGAGTTCAAATCCCCTTATTTCTACTAGGACTATAAGAATCGAACTCATCCCTGAGAATCCAAAATTCTCCGTGCCACCTATCACACCCCATCCTAAGTAAGGTCAGCTAAATAAGCTATCGGGCCCATACCCCGAAAATGTTGGTTACACCCTTCCCGTACTAAGAAATTTAGGTTAAGCACAGACCAAGAGCCTTCAAAGCCCTCAGCAAGTTA-CAATACTTAATTTCTGTAAGGACTGCAAAACCCCACTCTGCATCAACTGAACGCAAATCAGCCACTTTAATTAAGCTAAGCCCTTCTAGATTAATGGGACTTAAACCCACAAACATTTAGTTAACAGCTAAACACCCTAATCAAC-TGGCTTCAATCTAAAGCCCCGGCAGG-TTTGAAGCTGCTTCTTCGAATTTGCAATTCAATATGAAAA-TCACCTCAGAGCTTGGTAAAAAGAGGCTTAACCCCTGTCTTTAGATTTACAGTCCAATGCTTCA-CTCAGCCATTTTACCACAAAAAAGGAAGGAATCGAACCCCCTAAAGCTGGTTTCAAGCCAACCCCATGACCTCCATGACTTTTTCAAAAGATATTAGAAAAACTATTTCATAACTTTGTCAAAGTTAAATTACAGGTT-AACCCCCGTATATCTTA-CACTGTAAAGCTAACCTAGCATTAACCTTTTAAGTTAAAGATTAAGAGGACCGACACCTCTTTACAGTGA";
char *gorilla = "AGAAATATGTCTGATAAAAGAGTTACTTTGATAGAGTAAATAATAGAGGTTTAAACCCCCTTATTTCTACTAGGACTATGAGAATTGAACCCATCCCTGAGAATCCAAAATTCTCCGTGCCACCTGTCACACCCCATCCTAAGTAAGGTCAGCTAAATAAGCTATCGGGCCCATACCCCGAAAATGTTGGTCACATCCTTCCCGTACTAAGAAATTTAGGTTAAACATAGACCAAGAGCCTTCAAAGCCCTTAGTAAGTTA-CAACACTTAATTTCTGTAAGGACTGCAAAACCCTACTCTGCATCAACTGAACGCAAATCAGCCACTTTAATTAAGCTAAGCCCTTCTAGATCAATGGGACTCAAACCCACAAACATTTAGTTAACAGCTAAACACCCTAGTCAAC-TGGCTTCAATCTAAAGCCCCGGCAGG-TTTGAAGCTGCTTCTTCGAATTTGCAATTCAATATGAAAT-TCACCTCGGAGCTTGGTAAAAAGAGGCCCAGCCTCTGTCTTTAGATTTACAGTCCAATGCCTTA-CTCAGCCATTTTACCACAAAAAAGGAAGGAATCGAACCCCCCAAAGCTGGTTTCAAGCCAACCCCATGACCTTCATGACTTTTTCAAAAGATATTAGAAAAACTATTTCATAACTTTGTCAAGGTTAAATTACGGGTT-AAACCCCGTATATCTTA-CACTGTAAAGCTAACCTAGCGTTAACCTTTTAAGTTAAAGATTAAGAGTATCGGCACCTCTTTGCAGTGA";

int* getStates(char *sequence) {
	int n = strlen(sequence);
	int *states = (int*) malloc(sizeof(int) * n);

	for (int i = 0; i < n; i++) {
		switch (sequence[i]) {
			case 'A':
				states[i] = 0;
				break;
			case 'C':
				states[i] = 1;
				break;
			case 'G':
				states[i] = 2;
				break;
			case 'T':
				states[i] = 3;
				break;
			default:
				states[i] = 4;
				break;
		}
	}
	return states;
}

double* getPartials(char *sequence) {
	int n = strlen(sequence);
	double *partials = (double*)malloc(sizeof(double) * n * 4);

    int k = 0;
	for (int i = 0; i < n; i++) {
		switch (sequence[i]) {
			case 'A':
				partials[k++] = 1;
				partials[k++] = 0;
				partials[k++] = 0;
				partials[k++] = 0;
				break;
			case 'C':
				partials[k++] = 0;
				partials[k++] = 1;
				partials[k++] = 0;
				partials[k++] = 0;
				break;
			case 'G':
				partials[k++] = 0;
				partials[k++] = 0;
				partials[k++] = 1;
				partials[k++] = 0;
				break;
			case 'T':
				partials[k++] = 0;
				partials[k++] = 0;
				partials[k++] = 0;
				partials[k++] = 1;
				break;
			default:
				partials[k++] = 1;
				partials[k++] = 1;
				partials[k++] = 1;
				partials[k++] = 1;
				break;
		}
	}
	return partials;
}

int main( int argc, const char* argv[] )
{
    // print resource list
    ResourceList* rList;
    rList = getResourceList();
    fprintf(stdout, "Available resources:\n");
    for (int i = 0; i < rList->length; i++) {
        fprintf(stdout, "\tResource %i:\n\t\tName : %s\n", i, rList->list[i].name);
        fprintf(stdout, "\t\tFlags:");
        if (rList->list[i].flags & DOUBLE)
            fprintf(stdout, " DOUBLE");
        if (rList->list[i].flags & SINGLE)
            fprintf(stdout, " SINGLE");
        if (rList->list[i].flags & ASYNCH)
            fprintf(stdout, " ASYNCH");
        if (rList->list[i].flags & SYNCH)
            fprintf(stdout, " SYNCH");
        if (rList->list[i].flags & CPU)
            fprintf(stdout, " CPU");
        if (rList->list[i].flags & GPU)
            fprintf(stdout, " GPU");
        if (rList->list[i].flags & FPGA)
            fprintf(stdout, " FPGA");
        if (rList->list[i].flags & SSE)
            fprintf(stdout, " SSE");
        if (rList->list[i].flags & CELL)
            fprintf(stdout, " CELL");
        fprintf(stdout, "\n");

    }

    // is nucleotides...
    int stateCount = 4;

    // get the number of site patterns
	int nPatterns = strlen(human);

    // create an instance of the BEAGLE library
	int instance = createInstance(
                                  3,				/**< Number of tip data elements (input) */
                                  5,	            /**< Number of partials buffers to create (input) */
                                  0,		        /**< Number of compact state representation buffers to create (input) */
                                  stateCount,		/**< Number of states in the continuous-time Markov chain (input) */
                                  nPatterns,		/**< Number of site patterns to be handled by the instance (input) */
                                  1,		        /**< Number of rate matrix eigen-decomposition buffers to allocate (input) */
                                  4,		        /**< Number of rate matrix buffers (input) */
                                  1,              /**< Number of rate categories (input) */
                                  5,              /**< Number of scaling buffers */
                                  NULL,			/**< List of potential resource on which this instance is allowed (input, NULL implies no restriction */
                                  0,			    /**< Length of resourceList list (input) */
                                  0,		        /**< Bit-flags indicating preferred implementation charactertistics, see BeagleFlags (input) */
                                  0		        /**< Bit-flags indicating required implementation characteristics, see BeagleFlags (input) */
                                  );
    if (instance < 0) {
	    fprintf(stderr, "Failed to obtain BEAGLE instance\n\n");
	    exit(1);
    }

    // initialize the instance
    int error = initializeInstance(instance, NULL);

    if (error < 0) {
	    fprintf(stderr, "Failed to initialize BEAGLE instance\n\n");
	    exit(1);
    }

    //	setTipStates(instance, 0, getStates(human));
    //	setTipStates(instance, 1, getStates(chimp));
    //	setTipStates(instance, 2, getStates(gorilla));

    // set the sequences for each tip using partial likelihood arrays
	setTipPartials(instance, 0, getPartials(human));
	setTipPartials(instance, 1, getPartials(chimp));
	setTipPartials(instance, 2, getPartials(gorilla));

	double rates[1] = { 1.0 };
	setCategoryRates(instance, rates);

    // create base frequency array
	double freqs[4] = { 0.25, 0.25, 0.25, 0.25 };

    // create an array containing site category weights
	const double weights[1] = { 1.0 };

	// an eigen decomposition for the JC69 model
	double evec[4 * 4] = {
        1.0,  2.0,  0.0,  0.5,
        1.0,  -2.0,  0.5,  0.0,
        1.0,  2.0, 0.0,  -0.5,
        1.0,  -2.0,  -0.5,  0.0
	};

	double ivec[4 * 4] = {
        0.25,  0.25,  0.25,  0.25,
        0.125,  -0.125,  0.125,  -0.125,
        0.0,  1.0,  0.0,  -1.0,
        1.0,  0.0,  -1.0,  0.0
	};

	double eval[4] = { 0.0, -1.3333333333333333, -1.3333333333333333, -1.3333333333333333 };

    // set the Eigen decomposition
	setEigenDecomposition(instance, 0, evec, ivec, eval);

    // a list of indices and edge lengths
	int nodeIndices[4] = { 0, 1, 2, 3 };
	double edgeLengths[4] = { 0.1, 0.1, 0.2, 0.1 };

    // tell BEAGLE to populate the transition matrices for the above edge lengths
	updateTransitionMatrices(instance,     // instance
	                         0,             // eigenIndex
	                         nodeIndices,   // probabilityIndices
	                         NULL,          // firstDerivativeIndices
	                         NULL,          // secondDervativeIndices
	                         edgeLengths,   // edgeLengths
	                         4);            // count

    // create a list of partial likelihood update operations
    // the order is [dest, destScaling, source1, matrix1, source2, matrix2]
	int operations[7 * 2] = {
		3, 3, 0, 0, 0, 1, 1,
		4, 4, 0, 2, 2, 3, 3
	};
	int rootIndex = 4;

    // update the partials
	updatePartials( &instance,      // instance
                   1,              // instanceCount
                   operations,     // eigenIndex
                   2,              // operationCount
                   0);             // rescale ? 0 = no

	double *patternLogLik = (double*)malloc(sizeof(double) * nPatterns);

    int scalingFactorsIndices[2] = {3, 4}; // internal nodes
    int scalingFactorsCount = 2;

    int cumulativeScalingFactorIndex = 0;

    resetScaleFactors(instance,
                      cumulativeScalingFactorIndex);

    accumulateScaleFactors(instance,
                           scalingFactorsIndices,
                           scalingFactorsCount,
                           cumulativeScalingFactorIndex);

    // calculate the site likelihoods at the root node
	calculateRootLogLikelihoods(instance,               // instance
	                            (const int *)&rootIndex,// bufferIndices
	                            weights,                // weights
	                            freqs,                 // stateFrequencies
                                &cumulativeScalingFactorIndex,
	                            1,                      // count
	                            patternLogLik);         // outLogLikelihoods

	double logL = 0.0;
	for (int i = 0; i < nPatterns; i++) {
//		std::cerr << "site lnL[" << i << "] = " << patternLogLik[i] << '\n';
		logL += patternLogLik[i];
	}

	fprintf(stdout, "logL = %.5f (PAUP logL = -1574.63623)\n\n", logL);

    finalize(instance);

}
<|endoftext|>


<commit_before><commit_msg>fix: check file content is empty or not<commit_after><|endoftext|>


<commit_before>namespace WorkBreak2 {
  class Solution {
  public:

      void findall(vector<vector<int> > &prevs, int endPos, string s, vector<string> &res, string curStr) {

          if (endPos == 0) {
              res.push_back(curStr);
              return;
          }

          vector<int> & prev = prevs[endPos];

          for (vector<int>::iterator it = prev.begin(); it != prev.end(); it++) {
              int prevPos = *it;
              string str = s.substr(prevPos, endPos - prevPos);

              string origStr = curStr;
              if (curStr != "") {
                  curStr = str + " " + curStr;
              } else {
                  curStr = str;

              }
              findall(prevs, prevPos, s, res, curStr);
              curStr = origStr;
          }
      }

      vector<string> wordBreak(string s, unordered_set<string> &dict) {

          vector<string> res;
          if (s.empty() || dict.empty()) {
              return res;
          }
          int minLen = INT_MAX;
          int maxLen = 0;

          for(unordered_set<string>::iterator it = dict.begin(); it != dict.end(); it++) {
              string str = *it;
              if (str.length() > maxLen) {
                  maxLen = str.length();
              }

              if (str.length() < minLen) {
                  minLen = str.length();
              }
          }

          int strlen = s.length();
          vector<bool> dp(strlen + 1);
          dp[0] = true;
          vector<vector<int> > prevs(strlen + 1);
          for (int i = 1; i <= strlen; i++) {
              if (dp[i - 1] == false) {
                  continue;
              }

              for (int len = minLen; len <= maxLen; len++) {
                  int endPos = i + len;
                  if (endPos > strlen + 1) {
                      break;
                  }

                  string subStr = s.substr(i - 1, len);
                  if (dict.find(subStr) != dict.end()) {
                      dp[endPos - 1] = true;
                      prevs[endPos - 1].push_back(i - 1);
                  }
              }
          }

          // can't be break properly
          if (dp[strlen] == false) {
              return res;
          }

          findall(prevs, strlen, s, res, "");
          return res;

      }
  };
}
<commit_msg>Update WordBreak2.cc<commit_after>// https://oj.leetcode.com/problems/word-break-ii/
// solution based on 1-D dp
class Solution {
public:
    void genStrings(string &s, vector<vector<int> > &bt, int cur, vector<string>& res, string curstr) {
        if (cur == 0) {
            res.push_back(curstr);
            return;
        }

        vector<int> preIdxs = bt[cur];
        for (int i = 0; i < preIdxs.size(); i++) {
            genStrings(s, bt, preIdxs[i], res, s.substr(preIdxs[i], cur - preIdxs[i]) + " " + curstr);
        }
    }

    vector<string> wordBreak(string s, unordered_set<string> &dict) {
        vector<bool> dp(s.size() + 1, false);
        vector<vector<int> > bt(s.size() + 1, vector<int>());
        dp[0] = true;
        bt[0].push_back(-1); // mark end
        for (int i = 1 ; i <= s.size(); i++) {
            if (dp[i - 1]) {
                for (unordered_set<string>::iterator it = dict.begin(); it != dict.end(); it++) {
                    const string& word = *it;
                    if (i + word.size() - 1 <= s.size() && s.substr(i - 1, word.size()) == word) {
                        dp[i + word.size() - 1] = true;
                        bt[i + word.size() - 1].push_back(i - 1);
                    }
                }
            }
        }

        // generate result by backtrace
        vector<string> res;
        string curstr = "";
        vector<int> preIdxs = bt[s.size()];
        for (int i = 0; i < preIdxs.size(); i++) {
            genStrings(s, bt, preIdxs[i], res, s.substr(preIdxs[i], s.size() - preIdxs[i]));
        }
        return res;
    }
};
<|endoftext|>