<commit_before>#include <QtNetwork>
#include <QtWidgets>

#define USER_AGENT  "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko)" \
                    "Chrome/55.0.0.0 Safari/537.36 Dobostorta/" GIT_VERSION

#define CONNECTION_NAME  "dobostorta-downloader.sock"

class TortaRequestHandler : public QLocalServer {
    Q_OBJECT

    TortaRequestHandler() {
        listen(CONNECTION_NAME);
        connect(this, &QLocalServer::newConnection, this, &TortaRequestHandler::newConnection);
    }

    void newConnection() {
        QLocalSocket *sock = nextPendingConnection();
        connect(sock, &QLocalSocket::disconnected, sock, &QLocalSocket::close);

        sock->waitForReadyRead();

        QDataStream stream(sock);
        QByteArray data;
        stream >> data;
        emit receivedRequest({data});
    }

public:
    ~TortaRequestHandler() {
        close();
    }

    static TortaRequestHandler *open() {
        auto server = new TortaRequestHandler();
        if (server->isListening())
            return server;

        delete server;
        return nullptr;
    }

    static bool request(const QUrl &url) {
        QLocalSocket sock;
        sock.connectToServer(CONNECTION_NAME);

        if (!sock.isValid()) {
            qCritical() << tr("Failed to open socket: ") << sock.errorString();
            return false;
        }

        QByteArray block;
        QDataStream stream(&block, QIODevice::WriteOnly);
        stream << url.toEncoded();
        sock.write(block);

        sock.waitForBytesWritten();

        return true;
    }

signals:
    void receivedRequest(const QUrl &url);
};

class TortaDownload : public QWidget {
    Q_OBJECT

    QNetworkReply * const reply;
    QVBoxLayout layout;
    QProgressBar progress;
    QPushButton actionButton;
    QPushButton clearButton;
    QTimer intervalTimer;
    QElapsedTimer elapsedTimer;

    void saveTo(const QString &path) {
        QFile file(path);
        if (!file.open(QIODevice::WriteOnly)) {
            QMessageBox message(QMessageBox::Critical,
                                reply->url().toString(),
                                tr("Failed create %1\n%2").arg(path, file.errorString()),
                                QMessageBox::Retry | QMessageBox::Abort,
                                this);
            if (message.exec() == QMessageBox::Retry)
                saveTo(path);
            return;
        }

        file.write(reply->readAll());
        file.close();
    }

    static QString bytesToKMG(int bytes) {
        static const char* units[] = {"B", "KB", "MB", "GB", "TB", "PB", nullptr};
        for (int i=0; units[i+1] != nullptr; i++) {
            if (bytes < qPow(1024, i + 1)) {
                if (qPow(1024, i + 1) / 10 < bytes)
                    return QString("%1%2")
                             .arg(static_cast<float>(bytes) / qPow(1024, i + 1), 0, 'f', 1)
                             .arg(units[i + 1]);
                else if (bytes < qPow(1024, i + 1) / 100)
                    return QString("%1%2")
                             .arg(static_cast<float>(bytes) / qPow(1024, i), 0, 'f', 1)
                             .arg(units[i]);
                else
                    return QString("%1%2").arg(bytes / qPow(1024, i), 0, 'f', 0).arg(units[i]);
            }
        }
        return QString("%1PB").arg(bytes / qPow(1024, 5), 0, 'f', 0);
    }

    void setProgressBarColor(const QColor &color) {
        QPalette p;
        p.setColor(QPalette::Highlight, color);
        progress.setPalette(p);
    }

    void finished(const QString &filePath) {
        if (reply->error() && reply->error() != QNetworkReply::OperationCanceledError) {
            QMessageBox message(QMessageBox::Critical,
                                reply->url().toString(),
                                tr("Failed download\n%1").arg(reply->errorString()),
                                QMessageBox::Retry | QMessageBox::Abort,
                                this);
            if (message.exec() == QMessageBox::Retry)
                emit retry();
        }
        clearButton.show();

        intervalTimer.stop();
        if (!reply->error()) {
            saveTo(filePath);
            progress.setFormat(QString("done [%1]").arg(bytesToKMG(progress.maximum())));
            setProgressBarColor(Qt::gray);
            actionButton.setText("open");
        } else {
            progress.setFormat(QString("%p% [%1] %2").arg(bytesToKMG(progress.maximum()))
                                                     .arg(reply->errorString()));
            setProgressBarColor(Qt::darkRed);
            actionButton.setText("retry");
        }
    }

public:
    TortaDownload(QWidget *parent, QNetworkReply *reply, const QString &filePath)
            : QWidget(parent), reply(reply), layout(this), progress(this),
              actionButton("cancel", this), clearButton("clear", this) {
        setLayout(&layout);

        auto horizontal = new QHBoxLayout;
        layout.addLayout(horizontal);

        auto left = new QVBoxLayout;
        horizontal->addLayout(left, 1);

        QFileInfo info(filePath);
        auto path = new QLabel(info.dir().path() + "/" + info.fileName() + "", this);
        path->setWordWrap(true);
        left->addWidget(path);

        auto url = new QLabel(QString("%1").arg(reply->url().toString()), this);
        url->setOpenExternalLinks(true);
        url->setWordWrap(true);
        left->addWidget(url);

        horizontal->addWidget(&actionButton);
        horizontal->addWidget(&clearButton);
        clearButton.hide();
        connect(&actionButton, &QPushButton::clicked, [this, reply, filePath]{
            if (reply->isRunning())
                reply->abort();
			else if (reply->error())
                emit retry();
            else
				QDesktopServices::openUrl(QUrl("file://" + filePath));
        });
        connect(&clearButton,  &QPushButton::clicked, [this]{ emit clear(); });

        progress.setFormat("%p% [%vB / %mB]");
        setProgressBarColor(Qt::darkGray);
        layout.addWidget(&progress);

        connect(reply, &QNetworkReply::downloadProgress, [this](qint64 received, qint64 total){
            updateProgressFormat();

            progress.setRange(0, total);
            progress.setValue(received);
        });
        connect(reply, &QNetworkReply::finished, [this, filePath]{ finished(filePath); });
        intervalTimer.setSingleShot(false);
        connect(&intervalTimer, &QTimer::timeout, this, &TortaDownload::updateProgressFormat);
        intervalTimer.start(1000);
        elapsedTimer.start();
    }

signals:
    void clear();
    void retry();

private slots:
    void updateProgressFormat() {
        const int remain = qMax(
            0.0f,
            ((progress.maximum() * elapsedTimer.elapsed()) / static_cast<float>(progress.value())
            - elapsedTimer.elapsed()) / 1000
        );

        QString remainStr;
        if (remain < 60)
            remainStr = QString("%1 sec").arg(remain);
        else if (remain < 60 * 60)
            remainStr = QString("%1' %2\"").arg(remain/60).arg(remain % 60, 2, 'd', 0, '0');
        else
            remainStr = QString("%1:%2'").arg(remain/60/60).arg(remain/60 % 60, 2, 'd', 0, '0');

        progress.setFormat("%p% " + QString("[%1 / %2] %3").arg(bytesToKMG(progress.value()))
                                                           .arg(bytesToKMG(progress.maximum()))
                                                           .arg(remainStr));
    }
};

class TortaDL : public QScrollArea {
    Q_OBJECT

    QVBoxLayout layout;
    QNetworkAccessManager manager;
    TortaRequestHandler * const handler;

protected:
    void closeEvent(QCloseEvent *e) override {
        handler->close();
        QWidget::closeEvent(e);
    }

public:
    TortaDL(TortaRequestHandler *handler) : handler(handler) {
        setWindowTitle("Dobostorta downloader");

        setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
        layout.setAlignment(Qt::AlignTop);
        auto listArea = new QWidget(this);
        listArea->setLayout(&layout);
        setWidget(listArea);
        setWidgetResizable(true);

        connect(handler, &TortaRequestHandler::receivedRequest,
                [this](const QUrl &url){ startDownload(url); });
    }

    void startDownload(const QUrl &url, const QString &fname) {
        QNetworkRequest request(url);
        request.setRawHeader("User-Agent", USER_AGENT);

        auto dl = new TortaDownload(widget(), manager.get(request), fname);

        layout.addWidget(dl);

        connect(dl, &TortaDownload::retry, [this, url, fname]{ startDownload(url, fname); });
        connect(dl, &TortaDownload::clear, [this, dl]{
            layout.removeWidget(dl);
            delete dl;
        });
    }

    bool startDownload(const QUrl &url) {
        const QString filter(QMimeDatabase().mimeTypeForFile(url.fileName()).filterString());
        const QString path(QFileDialog::getSaveFileName(
            this,
            tr("Save file"),
            QFileInfo(QFileDialog().directory(), url.fileName()).absoluteFilePath(),
            filter + tr(";; All files (*)")
        ));
        if (path != "")
            startDownload(url, path);
        return path != "";
    }
};

int main(int argc, char **argv) {
    if (argc == 1) {
        qWarning("Dobostorta Downloader\n$ %s URL...", argv[0]);
        return -1;
    }

    QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
    QApplication app(argc, argv);

    auto handler = TortaRequestHandler::open();
    if (handler == nullptr) {
        for (int i=1; i<argc; i++) {
            if (!TortaRequestHandler::request({argv[i]}))
                return -1;
        }

        return 0;
    }

    TortaDL win(handler);

    bool started = false;
    for (int i=1; i<argc; i++)
        started = started || win.startDownload({argv[i]});

    if (!started) {
        win.close();
        return 1;
    }

    win.show();

    return app.exec();
}

#include "main.moc"
<commit_msg>Fixed indent<commit_after>#include <QtNetwork>
#include <QtWidgets>

#define USER_AGENT  "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko)" \
                    "Chrome/55.0.0.0 Safari/537.36 Dobostorta/" GIT_VERSION

#define CONNECTION_NAME  "dobostorta-downloader.sock"

class TortaRequestHandler : public QLocalServer {
    Q_OBJECT

    TortaRequestHandler() {
        listen(CONNECTION_NAME);
        connect(this, &QLocalServer::newConnection, this, &TortaRequestHandler::newConnection);
    }

    void newConnection() {
        QLocalSocket *sock = nextPendingConnection();
        connect(sock, &QLocalSocket::disconnected, sock, &QLocalSocket::close);

        sock->waitForReadyRead();

        QDataStream stream(sock);
        QByteArray data;
        stream >> data;
        emit receivedRequest({data});
    }

public:
    ~TortaRequestHandler() {
        close();
    }

    static TortaRequestHandler *open() {
        auto server = new TortaRequestHandler();
        if (server->isListening())
            return server;

        delete server;
        return nullptr;
    }

    static bool request(const QUrl &url) {
        QLocalSocket sock;
        sock.connectToServer(CONNECTION_NAME);

        if (!sock.isValid()) {
            qCritical() << tr("Failed to open socket: ") << sock.errorString();
            return false;
        }

        QByteArray block;
        QDataStream stream(&block, QIODevice::WriteOnly);
        stream << url.toEncoded();
        sock.write(block);

        sock.waitForBytesWritten();

        return true;
    }

signals:
    void receivedRequest(const QUrl &url);
};

class TortaDownload : public QWidget {
    Q_OBJECT

    QNetworkReply * const reply;
    QVBoxLayout layout;
    QProgressBar progress;
    QPushButton actionButton;
    QPushButton clearButton;
    QTimer intervalTimer;
    QElapsedTimer elapsedTimer;

    void saveTo(const QString &path) {
        QFile file(path);
        if (!file.open(QIODevice::WriteOnly)) {
            QMessageBox message(QMessageBox::Critical,
                                reply->url().toString(),
                                tr("Failed create %1\n%2").arg(path, file.errorString()),
                                QMessageBox::Retry | QMessageBox::Abort,
                                this);
            if (message.exec() == QMessageBox::Retry)
                saveTo(path);
            return;
        }

        file.write(reply->readAll());
        file.close();
    }

    static QString bytesToKMG(int bytes) {
        static const char* units[] = {"B", "KB", "MB", "GB", "TB", "PB", nullptr};
        for (int i=0; units[i+1] != nullptr; i++) {
            if (bytes < qPow(1024, i + 1)) {
                if (qPow(1024, i + 1) / 10 < bytes)
                    return QString("%1%2")
                             .arg(static_cast<float>(bytes) / qPow(1024, i + 1), 0, 'f', 1)
                             .arg(units[i + 1]);
                else if (bytes < qPow(1024, i + 1) / 100)
                    return QString("%1%2")
                             .arg(static_cast<float>(bytes) / qPow(1024, i), 0, 'f', 1)
                             .arg(units[i]);
                else
                    return QString("%1%2").arg(bytes / qPow(1024, i), 0, 'f', 0).arg(units[i]);
            }
        }
        return QString("%1PB").arg(bytes / qPow(1024, 5), 0, 'f', 0);
    }

    void setProgressBarColor(const QColor &color) {
        QPalette p;
        p.setColor(QPalette::Highlight, color);
        progress.setPalette(p);
    }

    void finished(const QString &filePath) {
        if (reply->error() && reply->error() != QNetworkReply::OperationCanceledError) {
            QMessageBox message(QMessageBox::Critical,
                                reply->url().toString(),
                                tr("Failed download\n%1").arg(reply->errorString()),
                                QMessageBox::Retry | QMessageBox::Abort,
                                this);
            if (message.exec() == QMessageBox::Retry)
                emit retry();
        }
        clearButton.show();

        intervalTimer.stop();
        if (!reply->error()) {
            saveTo(filePath);
            progress.setFormat(QString("done [%1]").arg(bytesToKMG(progress.maximum())));
            setProgressBarColor(Qt::gray);
            actionButton.setText("open");
        } else {
            progress.setFormat(QString("%p% [%1] %2").arg(bytesToKMG(progress.maximum()))
                                                     .arg(reply->errorString()));
            setProgressBarColor(Qt::darkRed);
            actionButton.setText("retry");
        }
    }

public:
    TortaDownload(QWidget *parent, QNetworkReply *reply, const QString &filePath)
            : QWidget(parent), reply(reply), layout(this), progress(this),
              actionButton("cancel", this), clearButton("clear", this) {
        setLayout(&layout);

        auto horizontal = new QHBoxLayout;
        layout.addLayout(horizontal);

        auto left = new QVBoxLayout;
        horizontal->addLayout(left, 1);

        QFileInfo info(filePath);
        auto path = new QLabel(info.dir().path() + "/" + info.fileName() + "", this);
        path->setWordWrap(true);
        left->addWidget(path);

        auto url = new QLabel(QString("%1").arg(reply->url().toString()), this);
        url->setOpenExternalLinks(true);
        url->setWordWrap(true);
        left->addWidget(url);

        horizontal->addWidget(&actionButton);
        horizontal->addWidget(&clearButton);
        clearButton.hide();
        connect(&actionButton, &QPushButton::clicked, [this, reply, filePath]{
            if (reply->isRunning())
                reply->abort();
            else if (reply->error())
                emit retry();
            else
                QDesktopServices::openUrl(QUrl("file://" + filePath));
        });
        connect(&clearButton,  &QPushButton::clicked, [this]{ emit clear(); });

        progress.setFormat("%p% [%vB / %mB]");
        setProgressBarColor(Qt::darkGray);
        layout.addWidget(&progress);

        connect(reply, &QNetworkReply::downloadProgress, [this](qint64 received, qint64 total){
            updateProgressFormat();

            progress.setRange(0, total);
            progress.setValue(received);
        });
        connect(reply, &QNetworkReply::finished, [this, filePath]{ finished(filePath); });
        intervalTimer.setSingleShot(false);
        connect(&intervalTimer, &QTimer::timeout, this, &TortaDownload::updateProgressFormat);
        intervalTimer.start(1000);
        elapsedTimer.start();
    }

signals:
    void clear();
    void retry();

private slots:
    void updateProgressFormat() {
        const int remain = qMax(
            0.0f,
            ((progress.maximum() * elapsedTimer.elapsed()) / static_cast<float>(progress.value())
            - elapsedTimer.elapsed()) / 1000
        );

        QString remainStr;
        if (remain < 60)
            remainStr = QString("%1 sec").arg(remain);
        else if (remain < 60 * 60)
            remainStr = QString("%1' %2\"").arg(remain/60).arg(remain % 60, 2, 'd', 0, '0');
        else
            remainStr = QString("%1:%2'").arg(remain/60/60).arg(remain/60 % 60, 2, 'd', 0, '0');

        progress.setFormat("%p% " + QString("[%1 / %2] %3").arg(bytesToKMG(progress.value()))
                                                           .arg(bytesToKMG(progress.maximum()))
                                                           .arg(remainStr));
    }
};

class TortaDL : public QScrollArea {
    Q_OBJECT

    QVBoxLayout layout;
    QNetworkAccessManager manager;
    TortaRequestHandler * const handler;

protected:
    void closeEvent(QCloseEvent *e) override {
        handler->close();
        QWidget::closeEvent(e);
    }

public:
    TortaDL(TortaRequestHandler *handler) : handler(handler) {
        setWindowTitle("Dobostorta downloader");

        setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
        layout.setAlignment(Qt::AlignTop);
        auto listArea = new QWidget(this);
        listArea->setLayout(&layout);
        setWidget(listArea);
        setWidgetResizable(true);

        connect(handler, &TortaRequestHandler::receivedRequest,
                [this](const QUrl &url){ startDownload(url); });
    }

    void startDownload(const QUrl &url, const QString &fname) {
        QNetworkRequest request(url);
        request.setRawHeader("User-Agent", USER_AGENT);

        auto dl = new TortaDownload(widget(), manager.get(request), fname);

        layout.addWidget(dl);

        connect(dl, &TortaDownload::retry, [this, url, fname]{ startDownload(url, fname); });
        connect(dl, &TortaDownload::clear, [this, dl]{
            layout.removeWidget(dl);
            delete dl;
        });
    }

    bool startDownload(const QUrl &url) {
        const QString filter(QMimeDatabase().mimeTypeForFile(url.fileName()).filterString());
        const QString path(QFileDialog::getSaveFileName(
            this,
            tr("Save file"),
            QFileInfo(QFileDialog().directory(), url.fileName()).absoluteFilePath(),
            filter + tr(";; All files (*)")
        ));
        if (path != "")
            startDownload(url, path);
        return path != "";
    }
};

int main(int argc, char **argv) {
    if (argc == 1) {
        qWarning("Dobostorta Downloader\n$ %s URL...", argv[0]);
        return -1;
    }

    QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
    QApplication app(argc, argv);

    auto handler = TortaRequestHandler::open();
    if (handler == nullptr) {
        for (int i=1; i<argc; i++) {
            if (!TortaRequestHandler::request({argv[i]}))
                return -1;
        }

        return 0;
    }

    TortaDL win(handler);

    bool started = false;
    for (int i=1; i<argc; i++)
        started = started || win.startDownload({argv[i]});

    if (!started) {
        win.close();
        return 1;
    }

    win.show();

    return app.exec();
}

#include "main.moc"
<|endoftext|>


<commit_before>
#include "cmd.hpp"
#include <unistd.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <string>

Cmd::Cmd()
{}

Cmd::Cmd(string input1)
{
	uCmd = input1;
	//	cout << "uCmd: " << uCmd << endl;
}

//where the magic happens
//uses fork and exec to execute commands and returns bool values to indicate a valid/invalid command
bool Cmd::execute(vector<string> myArgs)
{
	//cout << (char*)cmd_s.c_str() << endl;
	char* args[512];
	unsigned i;
	for ( i = 0; i < myArgs.size(); i++)
	{
		args[i] = (char*)myArgs[i].c_str();
		cout << "ARG I = " << args[i] << endl;
	}
	args[i] = NULL;

	pid_t pid;
	pid = fork();
	int status;

	if (pid == -1)
	{
		perror("fork");
		exit(1);
	}
	if (pid == 0) // child process
	{
		if (execvp(args[0], args) == -1)
		{
			perror("exec");
			exit(1);

		}
	}
	else // parent process
	{
		if (waitpid(pid, &status, 0) == -1)
		{
			perror("wait");
			exit(1);
		}
		if (WEXITSTATUS(status) != 0)
		{
			return false;
		}
	}

	return true;

}

<commit_msg>removed debugging statement<commit_after>
#include "cmd.hpp"
#include <unistd.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <string>

Cmd::Cmd()
{}

Cmd::Cmd(string input1)
{
	uCmd = input1;
	//	cout << "uCmd: " << uCmd << endl;
}

//where the magic happens
//uses fork and exec to execute commands and returns bool values to indicate a valid/invalid command
bool Cmd::execute(vector<string> myArgs)
{
	//cout << (char*)cmd_s.c_str() << endl;
	char* args[512];
	unsigned i;
	for ( i = 0; i < myArgs.size(); i++)
	{
		args[i] = (char*)myArgs[i].c_str();
	}
	args[i] = NULL;

	pid_t pid;
	pid = fork();
	int status;

	if (pid == -1)
	{
		perror("fork");
		exit(1);
	}
	if (pid == 0) // child process
	{
		if (execvp(args[0], args) == -1)
		{
			perror("exec");
			exit(1);

		}
	}
	else // parent process
	{
		if (waitpid(pid, &status, 0) == -1)
		{
			perror("wait");
			exit(1);
		}
		if (WEXITSTATUS(status) != 0)
		{
			return false;
		}
	}

	return true;

}

<|endoftext|>


<commit_before>// @(#)root/tree:$Name$:$Id$
// Author: Rene Brun   14/04/97

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

//////////////////////////////////////////////////////////////////////////
//                                                                      //
// TCut                                                                 //
//                                                                      //
//  A specialized string object used for TTree selections.              //
//  A TCut object has a name and a title. It does not add any data      //
//  members compared to a TNamed. It only add a set of operators to     //
//  facilitate logical string concatenation. For example, assume        //
//     cut1 = "x<1"  and cut2 = "y>2"                                   //
//  then                                                                //
//     cut1 && cut2 will be the string "(x<1)&&(y>2)"                   //
//                                                                      //
//  Operators =, +=, +, *, !, &&, || overloaded.                        //
//                                                                      //
//   Examples of use:                                                   //
//     Root > TCut c1 = "x<1"                                           //
//     Root > TCut c2 = "y<0"                                           //
//     Root > TCut c3 = c1&&c2                                          //
//     Root > ntuple.Draw("x", c1)                                      //
//     Root > ntuple.Draw("x", c1||"x>0")                               //
//     Root > ntuple.Draw("x", c1&&c2)                                  //
//     Root > ntuple.Draw("x", "(x+y)"*(c1&&c2))                        //
//                                                                      //
//////////////////////////////////////////////////////////////////////////

#include "TCut.h"

ClassImp(TCut)

//______________________________________________________________________________
TCut::TCut() : TNamed()
{

}

//______________________________________________________________________________
TCut::TCut(const char *title) : TNamed("CUT",title)
{

}

//______________________________________________________________________________
TCut::TCut(const char *name, const char *title) : TNamed(name,title)
{

}

//______________________________________________________________________________
TCut::TCut(const TCut &cut) : TNamed(cut)
{
   //fName  = cut.fName;
   //fTitle = cut.fTitle;
}

//______________________________________________________________________________
TCut::~TCut()
{

}

//______________________________________________________________________________
TCut& TCut::operator=(const char *rhs)
{
   fTitle = rhs;
   return *this;
}

//______________________________________________________________________________
TCut& TCut::operator=(const TCut& rhs)
{
   if (this != &rhs)
      TNamed::operator=(rhs);

   return *this;
}

//______________________________________________________________________________
TCut& TCut::operator+=(const char *rhs)
{
   fTitle = "(" + fTitle + ")&&(" + TString(rhs) + ")";
   return *this;
}

//______________________________________________________________________________
TCut& TCut::operator+=(const TCut& rhs)
{
   fTitle = "(" + fTitle + ")&&(" + rhs.fTitle + ")";
   return *this;
}

//______________________________________________________________________________
TCut& TCut::operator*=(const char *rhs)
{
   fTitle = fTitle + "*(" + TString(rhs) + ")";;
   return *this;
}

//______________________________________________________________________________
TCut& TCut::operator*=(const TCut& rhs)
{
   fTitle = fTitle + "*(" + rhs.fTitle + ")";;
   return *this;
}

//______________________________________________________________________________
TCut operator+(const TCut& lhs, const char *rhs)
{
   return TCut(lhs) += rhs;
}

//______________________________________________________________________________
TCut operator+(const char *lhs, const TCut& rhs)
{
   return TCut(lhs) += rhs;
}

//______________________________________________________________________________
TCut operator+(const TCut& lhs, const TCut& rhs)
{
   return TCut(lhs) += rhs;
}

//______________________________________________________________________________
TCut operator*(const TCut& lhs, const char *rhs)
{
   return TCut(lhs) *= rhs;
}

//______________________________________________________________________________
TCut operator*(const char *lhs, const TCut& rhs)
{
   return TCut(lhs) *= rhs;
}

//______________________________________________________________________________
TCut operator*(const TCut& lhs, const TCut& rhs)
{
   return TCut(lhs) *= rhs;
}

//______________________________________________________________________________
TCut operator&&(const TCut& lhs, const char *rhs)
{
   return TCut(lhs) += rhs;
}

//______________________________________________________________________________
TCut operator&&(const char *lhs, const TCut& rhs)
{
   return TCut(lhs) += rhs;
}

//______________________________________________________________________________
TCut operator&&(const TCut& lhs, const TCut& rhs)
{
   return TCut(lhs) += rhs;
}

//______________________________________________________________________________
TCut operator||(const TCut& lhs, const char *rhs)
{
   TString s = "(" + lhs.fTitle + ")||(" + TString(rhs) + ")";
   return TCut(s.Data());
}

//______________________________________________________________________________
TCut operator||(const char *lhs, const TCut& rhs)
{
   TString s = "(" + TString(lhs) + ")||(" + rhs.fTitle + ")";
   return TCut(s.Data());
}

//______________________________________________________________________________
TCut operator||(const TCut& lhs, const TCut& rhs)
{
   TString s = "(" + lhs.fTitle + ")||(" + rhs.fTitle + ")";
   return TCut(s.Data());
}

//______________________________________________________________________________
TCut operator!(const TCut &rhs)
{
   TString s = "!(" + rhs.fTitle + ")";
   return TCut(s.Data());
}

<commit_msg>surround cut with ( ) with operator*.<commit_after>// @(#)root/tree:$Name:  $:$Id: TCut.cxx,v 1.1.1.1 2000/05/16 17:00:45 rdm Exp $
// Author: Rene Brun   14/04/97

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

//////////////////////////////////////////////////////////////////////////
//                                                                      //
// TCut                                                                 //
//                                                                      //
//  A specialized string object used for TTree selections.              //
//  A TCut object has a name and a title. It does not add any data      //
//  members compared to a TNamed. It only add a set of operators to     //
//  facilitate logical string concatenation. For example, assume        //
//     cut1 = "x<1"  and cut2 = "y>2"                                   //
//  then                                                                //
//     cut1 && cut2 will be the string "(x<1)&&(y>2)"                   //
//                                                                      //
//  Operators =, +=, +, *, !, &&, || overloaded.                        //
//                                                                      //
//   Examples of use:                                                   //
//     Root > TCut c1 = "x<1"                                           //
//     Root > TCut c2 = "y<0"                                           //
//     Root > TCut c3 = c1&&c2                                          //
//     Root > ntuple.Draw("x", c1)                                      //
//     Root > ntuple.Draw("x", c1||"x>0")                               //
//     Root > ntuple.Draw("x", c1&&c2)                                  //
//     Root > ntuple.Draw("x", "(x+y)"*(c1&&c2))                        //
//                                                                      //
//////////////////////////////////////////////////////////////////////////

#include "TCut.h"

ClassImp(TCut)

//______________________________________________________________________________
TCut::TCut() : TNamed()
{

}

//______________________________________________________________________________
TCut::TCut(const char *title) : TNamed("CUT",title)
{

}

//______________________________________________________________________________
TCut::TCut(const char *name, const char *title) : TNamed(name,title)
{

}

//______________________________________________________________________________
TCut::TCut(const TCut &cut) : TNamed(cut)
{
   //fName  = cut.fName;
   //fTitle = cut.fTitle;
}

//______________________________________________________________________________
TCut::~TCut()
{

}

//______________________________________________________________________________
TCut& TCut::operator=(const char *rhs)
{
   fTitle = rhs;
   return *this;
}

//______________________________________________________________________________
TCut& TCut::operator=(const TCut& rhs)
{
   if (this != &rhs)
      TNamed::operator=(rhs);

   return *this;
}

//______________________________________________________________________________
TCut& TCut::operator+=(const char *rhs)
{
   fTitle = "(" + fTitle + ")&&(" + TString(rhs) + ")";
   return *this;
}

//______________________________________________________________________________
TCut& TCut::operator+=(const TCut& rhs)
{
   fTitle = "(" + fTitle + ")&&(" + rhs.fTitle + ")";
   return *this;
}

//______________________________________________________________________________
TCut& TCut::operator*=(const char *rhs)
{
   fTitle = "(" + fTitle + ")*(" + TString(rhs) + ")";
   return *this;
}

//______________________________________________________________________________
TCut& TCut::operator*=(const TCut& rhs)
{
   fTitle = "(" + fTitle + ")*(" + rhs.fTitle + ")";
   return *this;
}

//______________________________________________________________________________
TCut operator+(const TCut& lhs, const char *rhs)
{
   return TCut(lhs) += rhs;
}

//______________________________________________________________________________
TCut operator+(const char *lhs, const TCut& rhs)
{
   return TCut(lhs) += rhs;
}

//______________________________________________________________________________
TCut operator+(const TCut& lhs, const TCut& rhs)
{
   return TCut(lhs) += rhs;
}

//______________________________________________________________________________
TCut operator*(const TCut& lhs, const char *rhs)
{
   return TCut(lhs) *= rhs;
}

//______________________________________________________________________________
TCut operator*(const char *lhs, const TCut& rhs)
{
   return TCut(lhs) *= rhs;
}

//______________________________________________________________________________
TCut operator*(const TCut& lhs, const TCut& rhs)
{
   return TCut(lhs) *= rhs;
}

//______________________________________________________________________________
TCut operator&&(const TCut& lhs, const char *rhs)
{
   return TCut(lhs) += rhs;
}

//______________________________________________________________________________
TCut operator&&(const char *lhs, const TCut& rhs)
{
   return TCut(lhs) += rhs;
}

//______________________________________________________________________________
TCut operator&&(const TCut& lhs, const TCut& rhs)
{
   return TCut(lhs) += rhs;
}

//______________________________________________________________________________
TCut operator||(const TCut& lhs, const char *rhs)
{
   TString s = "(" + lhs.fTitle + ")||(" + TString(rhs) + ")";
   return TCut(s.Data());
}

//______________________________________________________________________________
TCut operator||(const char *lhs, const TCut& rhs)
{
   TString s = "(" + TString(lhs) + ")||(" + rhs.fTitle + ")";
   return TCut(s.Data());
}

//______________________________________________________________________________
TCut operator||(const TCut& lhs, const TCut& rhs)
{
   TString s = "(" + lhs.fTitle + ")||(" + rhs.fTitle + ")";
   return TCut(s.Data());
}

//______________________________________________________________________________
TCut operator!(const TCut &rhs)
{
   TString s = "!(" + rhs.fTitle + ")";
   return TCut(s.Data());
}

<|endoftext|>


<commit_before>//g++ *.cpp -lpthread -lwiringPi -std=c++11
//LATER MET GUI MAKEFILE <sudo make>

#include "I22cCom.h"
// Sensors -------------------
#include "Sensor.h"
#include "Log.h"
#include "Camera.h"
#include "Light.h"
#include "MotionSensor.h"
#include "PressureSensor.h"
// GUI ----------
#include "dialog.h"
#include <QApplication>
#include "temperatuur.h"
// ----------
//#define I2CLOC "/dev/i2c-1"// <-- this is the real I2C device you need with the scale model
#define I2CLOC "/dev/simudrv"
#define LOG "Slaaplog.txt"

#include <vector>
#include <iostream>
#include <wiringPi.h>  //compile with -lwiringPi

using namespace std;

vector<Sensor*> motionSensors;    //Vector of the sensors
vector<Light*> lights;      //Vector of the lights
vector<int> active;
PressureSensor* pressureSensor;
Camera* cam;                //Pointer to the camera
Log* log;

int pressureValue;
bool asleep = false;
bool day = true;
bool anomaly = false;
int temperature = 20;
long sleepTimer = 0;

void checkAnomaly();
void updateSensors();
void checkCam();
void sendAlert();
void init();

int GUImain(int argc, char *argv[]){
	QApplication a(argc, argv);
	Dialog w;
	w.show();
	a.exec();
}

int main() {
  init();
  while(1) {
        updateSensors();
        checkAnomaly();
        checkCam();
        checkTemperature();
  }
}

/*Init for the main*/
void init() {
	std::thread GUIloop(GUImain);
	GUIloop.join();
	wiringPiSetupGpio();
	I2CCom i2c(I2CLOC);     //the i2c to communicate with sensor
	Light x(22);
	MotionSensor s1(0xFC,i2c);
	MotionSensor s2(0xBC,i2c);
	MotionSensor s3(0xEC,i2c);
	PressureSensor s4(0x06, i2c);
	Log l1(LOG);
	Camera c1;
	cam = &c1;
	log = &l1;
	pressureSensor = &s4;
	motionSensors.push_back(&s1);
	motionSensors.push_back(&s2);
	motionSensors.push_back(&s3);
	lights.push_back(&x);

active.resize(motionSensors.size());
}
/*Updates sensors*/
void updateSensors() {
    //update van elke sensor de value en de active
    bool alert = true;
    for(int i = 0; i<motionSensors.size();i++) {
        if(motionSensors[i]->check()) {
            //active[i]=1;
            alert = false;
		cout <<"halleyula" <<endl;
        } else{
            //active[i]=0;
        }
    }
    if (s4->check()) {
        asleep = true;
    }
    if(alert & !asleep) {
        sendAlert();
    }
    pressureValue = s4->getValue();
}

/*Send Alarm*/
void sendAlert(){
    cout<<"Alert"<<endl;
}

/*Sets the camera*/
void checkCam(){
    if(day) {
        cam->setCamera(true);
    } else if(anomaly) {
        cam->setCamera(true);
    } else {
        cam->setCamera(false);
    }
}

/*Checks if there is an anomaly, otherwise checks if Tim's asleep*/
void checkAnomaly(){
    if(pressureValue < 20) {
        asleep = false;
        sleepTimer = 0;
    } else if(pressureValue > 20 && pressureValue < 150) {
        anomaly = true;
        sleepTimer = 0;
    } else if(pressureValue > 150 && pressureValue < 200) {
        sleepTimer = 0;
        // Changing positions while asleep
        //Do nothing, maybe verify if person really is sleeping
    } else if(pressureValue > 200 && sleepTimer = 0) {
        sleepTimer = time(0) + 900;
    } else if(pressureValue >200 && sleepTimer != 0) {
        if( time(0) >= sleepTimer) {
            asleep = true
        }
    }

}

/*Checks the set temperature from the gui*/
checkTemperature() {
    temperature = IngesteldeTemperatuur;
}

<commit_msg>bugfix<commit_after>//g++ *.cpp -lpthread -lwiringPi -std=c++11
//LATER MET GUI MAKEFILE <sudo make>

#include "I22cCom.h"
// Sensors -------------------
#include "Sensor.h"
#include "Log.h"
#include "Camera.h"
#include "Light.h"
#include "MotionSensor.h"
#include "PressureSensor.h"
// GUI ----------
#include "dialog.h"
#include <QApplication>
#include "temperatuur.h"
// ----------
//#define I2CLOC "/dev/i2c-1"// <-- this is the real I2C device you need with the scale model
#define I2CLOC "/dev/simudrv"
#define LOG "Slaaplog.txt"

#include <vector>
#include <iostream>
#include <wiringPi.h>  //compile with -lwiringPi

using namespace std;

vector<Sensor*> motionSensors;    //Vector of the sensors
vector<Light*> lights;      //Vector of the lights
vector<int> active;
PressureSensor* pressureSensor;
Camera* cam;                //Pointer to the camera
Log* log;

int pressureValue;
bool asleep = false;
bool day = true;
bool anomaly = false;
int temperature = 20;
long sleepTimer = 0;

void checkAnomaly();
void updateSensors();
void checkCam();
void sendAlert();
void init();

int GUImain(int argc, char *argv[]){
	QApplication a(argc, argv);
	Dialog w;
	w.show();
	a.exec();
}

int main() {
  init();
  while(1) {
        updateSensors();
        checkAnomaly();
        checkCam();
        checkTemperature();
  }
}

/*Init for the main*/
void init() {
	thread GUIloop(GUImain);
	GUIloop.join();
	wiringPiSetupGpio();
	I2CCom i2c(I2CLOC);     //the i2c to communicate with sensor
	Light x(22);
	MotionSensor s1(0xFC,i2c);
	MotionSensor s2(0xBC,i2c);
	MotionSensor s3(0xEC,i2c);
	PressureSensor s4(0x06, i2c);
	Log l1(LOG);
	Camera c1;
	cam = &c1;
	log = &l1;
	pressureSensor = &s4;
	motionSensors.push_back(&s1);
	motionSensors.push_back(&s2);
	motionSensors.push_back(&s3);
	lights.push_back(&x);

active.resize(motionSensors.size());
}
/*Updates sensors*/
void updateSensors() {
    //update van elke sensor de value en de active
    bool alert = true;
    for(int i = 0; i<motionSensors.size();i++) {
        if(motionSensors[i]->check()) {
            //active[i]=1;
            alert = false;
		cout <<"halleyula" <<endl;
        } else{
            //active[i]=0;
        }
    }
    if (s4->check()) {
        asleep = true;
    }
    if(alert & !asleep) {
        sendAlert();
    }
    pressureValue = s4->getValue();
}

/*Send Alarm*/
void sendAlert(){
    cout<<"Alert"<<endl;
}

/*Sets the camera*/
void checkCam(){
    if(day) {
        cam->setCamera(true);
    } else if(anomaly) {
        cam->setCamera(true);
    } else {
        cam->setCamera(false);
    }
}

/*Checks if there is an anomaly, otherwise checks if Tim's asleep*/
void checkAnomaly(){
    if(pressureValue < 20) {
        asleep = false;
        sleepTimer = 0;
    } else if(pressureValue > 20 && pressureValue < 150) {
        anomaly = true;
        sleepTimer = 0;
    } else if(pressureValue > 150 && pressureValue < 200) {
        sleepTimer = 0;
        // Changing positions while asleep
        //Do nothing, maybe verify if person really is sleeping
    } else if(pressureValue > 200 && sleepTimer = 0) {
        sleepTimer = time(0) + 900;
    } else if(pressureValue >200 && sleepTimer != 0) {
        if( time(0) >= sleepTimer) {
            asleep = true
        }
    }

}

/*Checks the set temperature from the gui*/
checkTemperature() {
    temperature = IngesteldeTemperatuur;
}

<|endoftext|>


<commit_before>//g++ *.cpp -lpthread -lwiringPi -std=c++11
//LATER MET GUI MAKEFILE <sudo make>

#include "Sensor.h"
#include "I22cCom.h"
#include "Log.h"
#include "Camera.h"
#include "Light.h"
#include "MotionSensor.h"
#include "PressureSensor.h"
#define I2CLOC "/dev/i2c-1"// <-- this is the real I2C device you need with the scale model
///#define I2CLOC "/dev/simudrv"
#define LOG "Slaaplog.txt"

#include <vector>
#include <iostream>
#include <wiringPi.h>  //compile with -lwiringPi

using namespace std;

vector<Sensor*> motionSensors;    //Vector of the sensors
vector<Light*> lights;      //Vector of the lights
vector<int> active;
PressureSensor* pressureSensor;
Camera* cam;                //Pointer to the camera
Log* log;

int pressureValue;
bool asleep = false;
bool day = true;
bool anomaly = false;
int temperature = 20;

void checkAnomaly();
void updateSensors();
void checkCam();
void sendAlert();
void init();

int main() {

    init();

    while(1) {
        updateSensors();
        checkAnomaly();
        checkCam();
	}
}

/*Init for the main*/
void init() {
    wiringPiSetupGpio();
    I2CCom i2c(I2CLOC);     //the i2c to communicate with sensors

    Light x(22);
    MotionSensor s1(0x05,i2c);
    PressureSensor s2(0x06, i2c);
    Log l1(LOG);
    Camera c1;

    cam = &c1;
    log = &l1;
    pressureSensor = &s2;
    motionSensors.push_back(&s1);
    lights.push_back(&x);

    active.resize(motionSensors.size());
}
/*Updates sensors*/
void updateSensors() {
    //update van elke sensor de value en de active
    bool alert = true;
    for(int i = 0; i<motionSensors.size();i++) {
        if(motionSensors[i]->check()) {
            active[i]=1;
            alert = false;
        } else {
            active[i]=0;
        }
    }
    if(alert & !asleep) {
        sendAlert();
    }
}

/*Send Alarm*/
void sendAlert(){
    cout<<"Alert"<<endl;
}

/*Sets the camera*/
void checkCam(){
    if(day) {
        cam->setCamera(true);
    } else if(anomaly) {
        cam->setCamera(true);
    } else {
        cam->setCamera(false);
    }
}

void checkAnomaly(){

    if(pressureValue > 20 && pressureValue < 150) {
        anomaly = true;
    }
    if(pressureValue > 150 && pressureValue < 200) { // Changing positions while asleep
        //Do nothing, maybe verify if person really is sleeping
    }
    if(pressureValue > 200) {
        asleep = true;
    }

}

<commit_msg>Main Update<commit_after>//g++ *.cpp -lpthread -lwiringPi -std=c++11
//LATER MET GUI MAKEFILE <sudo make>

#include "Sensor.h"
#include "I22cCom.h"
#include "Log.h"
#include "Camera.h"
#include "Light.h"
#include "MotionSensor.h"
#include "PressureSensor.h"
//#define I2CLOC "/dev/i2c-1"// <-- this is the real I2C device you need with the scale model
#define I2CLOC "/dev/simudrv"
#define LOG "Slaaplog.txt"

#include <vector>
#include <iostream>
#include <wiringPi.h>  //compile with -lwiringPi

using namespace std;

vector<Sensor*> motionSensors;    //Vector of the sensors
vector<Light*> lights;      //Vector of the lights
vector<int> active;
PressureSensor* pressureSensor;
Camera* cam;                //Pointer to the camera
Log* log;

int pressureValue;
bool asleep = false;
bool day = true;
bool anomaly = false;
int temperature = 20;

void checkAnomaly();
void updateSensors();
void checkCam();
void sendAlert();
void init();

int main() {
  init();
  while(1) {
        updateSensors();
        checkAnomaly();
        checkCam();
  }
}

/*Init for the main*/
void init() {
    wiringPiSetupGpio();
    I2CCom i2c(I2CLOC);     //the i2c to communicate with sensor
    Light x(22);
    MotionSensor s1(0xFC,i2c);
    MotionSensor s2(0xBC,i2c);
    MotionSensor s3(0xEC,i2c);
    PressureSensor s4(0x06, i2c);
    Log l1(LOG);
    Camera c1;
    cam = &c1;
    log = &l1;
    pressureSensor = &s4;
    motionSensors.push_back(&s1);
    motionSensors.push_back(&s2);
    motionSensors.push_back(&s3);
    lights.push_back(&x);

    active.resize(motionSensors.size());
}
/*Updates sensors*/
void updateSensors() {
    //update van elke sensor de value en de active
    bool alert = true;
    for(int i = 0; i<motionSensors.size()-1;i++) {
        if(motionSensors[i]->check()) {
            //active[i]=1;
            alert = false;
		cout <<"halleyula" <<endl;
        } else{
            //active[i]=0;
        }
    }
    if(alert & !asleep) {
        sendAlert();
    }
}

/*Send Alarm*/
void sendAlert(){
    cout<<"Alert"<<endl;
}

/*Sets the camera*/
void checkCam(){
    if(day) {
        cam->setCamera(true);
    } else if(anomaly) {
        cam->setCamera(true);
    } else {
        cam->setCamera(false);
    }
}

void checkAnomaly(){

    if(pressureValue > 20 && pressureValue < 150) {
        anomaly = true;
    }
    if(pressureValue > 150 && pressureValue < 200) { // Changing positions while asleep
        //Do nothing, maybe verify if person really is sleeping
    }
    if(pressureValue > 200) {
        asleep = true;
    }

}

<|endoftext|>


<commit_before>//g++ *.cpp -lpthread -lwiringPi -std=c++11
//LATER MET GUI MAKEFILE <sudo make>

#include "Sensor.h"
#include "I22cCom.h"
#include "Log.h"
#include "Camera.h"
#include "Light.h"
#include "MotionSensor.h"
#include "PressureSensor.h"
#define I2CLOC "/dev/i2c-1"// <-- this is the real I2C device you need with the scale model
///#define I2CLOC "/dev/simudrv"
#define LOG "Slaaplog.txt"

#include <vector>
#include <iostream>
#include <wiringPi.h>  //compile with -lwiringPi

using namespace std;

vector<Sensor*> motionSensors;    //Vector of the sensors
vector<Light*> lights;      //Vector of the lights
vector<int> active;
PressureSensor& pressureSensor;
Camera& cam;                //Pointer to the camera
Log& log;

int pressureValue;
bool sleep = false;
bool day = true;
bool anomaly = false;
int temperature = 20;

int sumActive(int active[]) {
	int sum=0;
	for(int i=0;i<sizeof(active[])/sizeof(active[0]);i++)
		sum+=active[i];
	return sum;
}

void checkAnomaly();
void updateSensors();
void checkCam();
void sendAlert();
void init();

int main() {

    init();

    while(1) {
        /*
        for(int i=0;i<sensors.capacity();i++) // For every sensor
            if(sensors[i]->Check()) { // Call their check function
				active[i]=1; // And if the check is positive (returns true).
				//TODO ENABLE LIGHTS
			} else active[i]=0;
		if(sumActive(active)==0) {
            sendAlert();
		}
		for(i=0;i<lights.capacity();i++) // For every light
			lights[i]->Check(); // Check if timer expired yet
        */
        updateSensors();
        checkAnomaly();
        checkCam();
	}
}

/*Init for the main*/
void init() {
    wiringPiSetupGpio();
    I2CCom i2c(I2CLOC);     //the i2c to communicate with sensors

    Light x(22);
    MotionSensor s1(0x05,i2c);
    PressureSensor s2(0x06, i2c, log);
    Log l1(LOG);
    Camera c1();

    cam = &c1
    log = &l1;
    pressureSensor = &s2;
    motionSensors.push_back(&s1);
    lights.push_back(&x);

    active.resize(motionSensors.size);
}
/*Updates sensors*/
void updateSensors() {
    //update van elke sensor de value en de active
    bool alert = true;
    for(int i = 0; i<motionSensors.size();i++) {
        if(motionSensors[i]->check()) {
            active[i]=1;
            alert = false;
        } else {
            active[i]=0;
        }
    }
    if(alert) {
        sendAlert();
    }
}

/*Send Alarm*/
void sendAlert(){
    cout<<"Alert"<<endl;
}

/*Sets the camera*/
void checkCam(){
    if(day) {
        cam.setCamera(true);
    } else if(anomaly) {
        cam.setCamera(true);
    } else {
        cam.setCamera(false);
    }
}

void checkAnomaly(){

    if(pressureValue > 20 && pressureValue < 150) {
        anomaly = true;
    }
    if(pressureValue > 150 && pressureValue < 200) { // Changing positions while asleep
        //Do nothing, maybe verify if person really is sleeping
    }
    if(pressureValue > 200) {
        sleep = true;
    }

}

<commit_msg>main fix<commit_after>//g++ *.cpp -lpthread -lwiringPi -std=c++11
//LATER MET GUI MAKEFILE <sudo make>

#include "Sensor.h"
#include "I22cCom.h"
#include "Log.h"
#include "Camera.h"
#include "Light.h"
#include "MotionSensor.h"
#include "PressureSensor.h"
#define I2CLOC "/dev/i2c-1"// <-- this is the real I2C device you need with the scale model
///#define I2CLOC "/dev/simudrv"
#define LOG "Slaaplog.txt"

#include <vector>
#include <iostream>
#include <wiringPi.h>  //compile with -lwiringPi

using namespace std;

vector<Sensor*> motionSensors;    //Vector of the sensors
vector<Light*> lights;      //Vector of the lights
vector<int> active;
PressureSensor& pressureSensor;
Camera& cam;                //Pointer to the camera
Log& log;

int pressureValue;
bool sleep = false;
bool day = true;
bool anomaly = false;
int temperature = 20;

int sumActive(int active[]) {
	int sum=0;
	for(int i=0;i<sizeof(active[])/sizeof(active[0]);i++)
		sum+=active[i];
	return sum;
}

void checkAnomaly();
void updateSensors();
void checkCam();
void sendAlert();
void init();

int main() {

    init();

    while(1) {
        /*
        for(int i=0;i<sensors.capacity();i++) // For every sensor
            if(sensors[i]->Check()) { // Call their check function
				active[i]=1; // And if the check is positive (returns true).
				//TODO ENABLE LIGHTS
			} else active[i]=0;
		if(sumActive(active)==0) {
            sendAlert();
		}
		for(i=0;i<lights.capacity();i++) // For every light
			lights[i]->Check(); // Check if timer expired yet
        */
        updateSensors();
        checkAnomaly();
        checkCam();
	}
}

/*Init for the main*/
void init() {
    wiringPiSetupGpio();
    I2CCom i2c(I2CLOC);     //the i2c to communicate with sensors

    Light x(22);
    MotionSensor s1(0x05,i2c);
    PressureSensor s2(0x06, i2c, log);
    Log l1(LOG);
    Camera c1();

    cam = &c1
    log = &l1;
    pressureSensor = &s2;
    motionSensors.push_back(&s1);
    lights.push_back(&x);

    active.resize(motionSensors.size);
}
/*Updates sensors*/
void updateSensors() {
    //update van elke sensor de value en de active
    bool alert = true;
    for(int i = 0; i<motionSensors.size();i++) {
        if(motionSensors[i]->check()) {
            active[i]=1;
            alert = false;
        } else {
            active[i]=0;
        }
    }
    if(alert && sleep = false) {
        sendAlert();
    }
}

/*Send Alarm*/
void sendAlert(){
    cout<<"Alert"<<endl;
}

/*Sets the camera*/
void checkCam(){
    if(day) {
        cam.setCamera(true);
    } else if(anomaly) {
        cam.setCamera(true);
    } else {
        cam.setCamera(false);
    }
}

void checkAnomaly(){

    if(pressureValue > 20 && pressureValue < 150) {
        anomaly = true;
    }
    if(pressureValue > 150 && pressureValue < 200) { // Changing positions while asleep
        //Do nothing, maybe verify if person really is sleeping
    }
    if(pressureValue > 200) {
        sleep = true;
    }

}

<|endoftext|>


<commit_before>#include <iostream>
#include <iomanip>
#include <string>
#include <openssl/sha.h>

using namespace std;
#define HASHSIZE 32

int main(int argc, char* argv[])
{
    string input;

    // a sha1 hash is 20 bytes
    unsigned char hash[HASHSIZE];

    for (int i = 0; i < HASHSIZE; i++) {
        hash[i] = 'x';
    }

    //cout << "enter your string: ";
    //getline(cin, input);
  	input = "hello";

    // compute the sha1 of the input, and store it our  hash array
    SHA256((unsigned char*)input.c_str(), input.size(), hash);
    // the above is the exact same thing as doing:
    //    SHA_CTX ctx;
    //
    //    SHA1_Init(&ctx);
    //    SHA1_Update(&ctx, input.c_str(), input.size());
    //    SHA1_Final(hash, &ctx);

    // since the hash array just contains a bunch of bytes,
    // print them as hexadecimal values
    cout << "the hash was: ";
    for(int i = 0; i < HASHSIZE; ++i) {
        cout << hex << setw(2) << setfill('0') << (int)hash[i];
    }
    cout << endl;
    cout << "DONE!" << endl;
}

string getPassword(string masterpass, string location) {
	string prehash = masterpass+location;

	//unsigned char hash[20];
	return prehash;
}<commit_msg>added a method to do fast conversion between byes and a base 64 string<commit_after>#include <iostream>
#include <iomanip>
#include <string>
#include <openssl/sha.h>

using namespace std;
#define HASHSIZE 32

string getCutHex(unsigned char hash[HASHSIZE]) {
	unsigned char b64_1 = hash[0] >> 2;
	unsigned char b64_2 = ((hash[0]&0x03)<<4) + (hash[1]>>4);
	unsigned char b64_3 = ((hash[1]&0x0F)<<2) + (hash[2]>>6);
	unsigned char b64_4 = hash[2] & 0x3F;
	cout << (int)0x3F << endl;
	cout << (int)hash[0] << ":" << (int)hash[1] << ":" << (int)hash[2] << endl;
	cout << (int)b64_1 << ":" << (int)b64_2 << ":" << (int)b64_3 << ":" << (int)b64_4 << endl;

	return "";
}

string getPassword(string masterpass, string domain) {
	string prehash = masterpass+domain;
	unsigned char hash[HASHSIZE];
	SHA256((unsigned char*)prehash.c_str(), prehash.size(), hash);

	getCutHex(hash);

	//unsigned char hash[20];
	return prehash;
}

int main(int argc, char* argv[]) {
	string input;

	// a sha1 hash is 20 bytes

	// for (int i = 0; i < HASHSIZE; i++) {
	// 	hash[i] = 'x';
	// }

	//cout << "enter your string: ";
	//getline(cin, input);
	input = "hello";

	// compute the sha1 of the input, and store it our  hash array

	// the above is the exact same thing as doing:
	//    SHA_CTX ctx;
	//
	//    SHA1_Init(&ctx);
	//    SHA1_Update(&ctx, input.c_str(), input.size());
	//    SHA1_Final(hash, &ctx);

	// since the hash array just contains a bunch of bytes,
	// print them as hexadecimal values
	// cout << "the hash was: ";
	// for(int i = 0; i < HASHSIZE; ++i) {
	// 	cout << hex << setw(2) << setfill('0') << (int)hash[i];
	// }
	// cout << endl;

	getPassword ("harvy","dent");

	cout << "DONE!" << endl;
}<|endoftext|>


<commit_before>#pragma once
/**
	@file
	@brief definition of Op
	@author MITSUNARI Shigeo(@herumi)
	@license modified new BSD license
	http://opensource.org/licenses/BSD-3-Clause
*/
#include <mcl/gmp_util.hpp>
#include <memory.h>
#include <mcl/array.hpp>

#if defined(__EMSCRIPTEN__) || defined(__wasm__)
	#define MCL_DONT_USE_XBYAK
	#define MCL_DONT_USE_OPENSSL
#endif
#if !defined(MCL_DONT_USE_XBYAK) && (defined(_WIN64) || defined(__x86_64__)) && (MCL_SIZEOF_UNIT == 8) && !defined(MCL_STATIC_CODE)
	#define MCL_USE_XBYAK
#endif
#if defined(MCL_USE_XBYAK) || defined(MCL_STATIC_CODE)
	#define MCL_X64_ASM
	#define MCL_XBYAK_DIRECT_CALL
#endif

#define MCL_MAX_HASH_BIT_SIZE 512

namespace mcl {

static const int version = 0x163; /* 0xABC = A.BC */

/*
	specifies available string format mode for X::setIoMode()
	// for Fp, Fp2, Fp6, Fp12
	default(0) : IoDec
	printable string(zero terminated, variable size)
	IoBin(2) | IoDec(10) | IoHex(16) | IoBinPrefix | IoHexPrefix

	byte string(not zero terminated, fixed size)
	IoArray | IoArrayRaw
	IoArray = IoSerialize

	// for Ec
	affine(0) | IoEcCompY | IoComp
	default : affine

	affine and IoEcCompY are available with ioMode for Fp
	IoSerialize ignores ioMode for Fp

	IoAuto
		dec or hex according to ios_base::fmtflags
	IoBin
		binary number([01]+)
	IoDec
		decimal number
	IoHex
		hexadecimal number([0-9a-fA-F]+)
	IoBinPrefix
		0b + <binary number>
	IoHexPrefix
		0x + <hexadecimal number>
	IoArray
		array of Unit(fixed size = Fp::getByteSize())
	IoArrayRaw
		array of Unit(fixed size = Fp::getByteSize()) without Montgomery conversion

	// for Ec::setIoMode()
	IoEcAffine(default)
	"0" ; infinity
	"1 <x> <y>" ; affine coordinate

	IoEcProj
	"4" <x> <y> <z> ; projective or jacobi coordinate

	IoEcCompY
		1-bit y prepresentation of elliptic curve
		"2 <x>" ; compressed for even y
		"3 <x>" ; compressed for odd y

	IoSerialize
		if isMSBserialize(): // p is not full bit
			size = Fp::getByteSize()
			use MSB of array of x for 1-bit y for prime p where (p % 8 != 0)
			[0] ; infinity
			<x> ; for even y
			<x>|1 ; for odd y ; |1 means set MSB of x
		else:
			size = Fp::getByteSize() + 1
			[0] ; infinity
			2 <x> ; for even y
			3 <x> ; for odd y
*/
enum IoMode {
	IoAuto = 0, // dec or hex according to ios_base::fmtflags
	IoBin = 2, // binary number without prefix
	IoDec = 10, // decimal number without prefix
	IoHex = 16, // hexadecimal number without prefix
	IoArray = 32, // array of Unit(fixed size)
	IoArrayRaw = 64, // raw array of Unit without Montgomery conversion
	IoPrefix = 128, // append '0b'(bin) or '0x'(hex)
	IoBinPrefix = IoBin | IoPrefix,
	IoHexPrefix = IoHex | IoPrefix,
	IoEcAffine = 0, // affine coordinate
	IoEcCompY = 256, // 1-bit y representation of elliptic curve
	IoSerialize = 512, // use MBS for 1-bit y
	IoFixedSizeByteSeq = IoSerialize, // obsolete
	IoEcProj = 1024, // projective or jacobi coordinate
	IoSerializeHexStr = 2048, // printable hex string
	IoEcAffineSerialize = 4096 // serialize [x:y]
};

namespace fp {

inline bool isIoSerializeMode(int ioMode)
{
	return ioMode & (IoArray | IoArrayRaw | IoSerialize | IoEcAffineSerialize | IoSerializeHexStr);
}

const size_t maxMulVecN = 32; // inner loop of mulVec

#ifndef MCL_MAX_MUL_VEC_NGLV
	#define MCL_MAX_MUL_VEC_NGLV 16
#endif
const size_t maxMulVecNGLV = MCL_MAX_MUL_VEC_NGLV; // inner loop of mulVec with GLV

struct FpGenerator;
struct Op;

typedef void (*void1u)(Unit*);
typedef void (*void2u)(Unit*, const Unit*);
typedef void (*void2uI)(Unit*, const Unit*, Unit);
typedef void (*void2uIu)(Unit*, const Unit*, Unit, const Unit*);
typedef void (*void2uOp)(Unit*, const Unit*, const Op&);
typedef void (*void3u)(Unit*, const Unit*, const Unit*);
typedef void (*void4u)(Unit*, const Unit*, const Unit*, const Unit*);
typedef int (*int2u)(Unit*, const Unit*);

typedef Unit (*u1uII)(Unit*, Unit, Unit);
typedef Unit (*u3u)(Unit*, const Unit*, const Unit*);

/*
	disable -Wcast-function-type
	the number of arguments of some JIT functions is smaller than that of T
*/
template<class T, class S>
T func_ptr_cast(S func)
{
	return reinterpret_cast<T>(reinterpret_cast<void*>(func));
}
struct Block {
	const Unit *p; // pointer to original FpT.v_
	size_t n;
	Unit v_[maxUnitSize];
};

enum Mode {
	FP_AUTO,
	FP_GMP,
	FP_GMP_MONT,
	FP_LLVM,
	FP_LLVM_MONT,
	FP_XBYAK
};

enum PrimeMode {
	PM_GENERIC = 0,
	PM_NIST_P192,
	PM_SECP256K1,
	PM_NIST_P521
};

struct Op {
	/*
		don't change the layout of rp and p
		asm code assumes &rp + 1 == p
	*/
	Unit rp;
	Unit p[maxUnitSize];
	mpz_class mp;
	uint32_t pmod4;
	mcl::SquareRoot sq;
	mcl::Modp modp;
	mcl::SmallModp smallModp;
	Unit half[maxUnitSize]; // (p + 1) / 2
	Unit oneRep[maxUnitSize]; // 1(=inv R if Montgomery)
	/*
		for Montgomery
		one = 1
		R = (1 << (N * sizeof(Unit) * 8)) % p
		R2 = (R * R) % p
		R3 = RR^3
	*/
	Unit one[maxUnitSize];
	Unit R2[maxUnitSize];
	Unit R3[maxUnitSize];
#ifdef MCL_USE_XBYAK
	FpGenerator *fg;
#endif
#ifdef MCL_X64_ASM
	mcl::Array<Unit> invTbl;
#endif
	void3u fp_addA_;
	void3u fp_subA_;
	void2u fp_negA_;
	void3u fp_mulA_;
	void2u fp_sqrA_;
	void2u fp_mul2A_;
	void2u fp_mul9A_;
	void3u fp2_addA_;
	void3u fp2_subA_;
	void2u fp2_negA_;
	void3u fp2_mulA_;
	void2u fp2_sqrA_;
	void2u fp2_mul2A_;
	void3u fpDbl_addA_;
	void3u fpDbl_subA_;
	void2u fpDbl_modA_;
	void3u fp2Dbl_mulPreA_;
	void2u fp2Dbl_sqrPreA_;
	void2u fp2Dbl_mul_xiA_;
	size_t maxN;
	size_t N;
	size_t bitSize;
	bool (*fp_isZero)(const Unit*);
	void1u fp_clear;
	void2u fp_copy;
	void2u fp_shr1;
	void3u fp_neg;
	void4u fp_add;
	void4u fp_sub;
	void4u fp_mul;
	void3u fp_sqr;
	void3u fp_mul2;
	void2uOp fp_invOp;
	void2uIu fp_mulUnit; // fpN1_mod + fp_mulUnitPre

	void3u fpDbl_mulPre;
	void2u fpDbl_sqrPre;
	int2u fp_preInv;
	void2uI fp_mulUnitPre; // z[N + 1] = x[N] * y
	void3u fpN1_mod; // y[N] = x[N + 1] % p[N]

	void4u fpDbl_add;
	void4u fpDbl_sub;
	void3u fpDbl_mod;

	u3u fp_addPre; // without modulo p
	u3u fp_subPre; // without modulo p
	u3u fpDbl_addPre;
	u3u fpDbl_subPre;
	/*
		for Fp2 = F[u] / (u^2 + 1)
		x = a + bu
	*/
	int xi_a; // xi = xi_a + u
	void4u fp2_mulNF;
	void2u fp2_mul_xiA_;
	uint32_t (*hash)(void *out, uint32_t maxOutSize, const void *msg, uint32_t msgSize);

	PrimeMode primeMode;
	bool isFullBit; // true if bitSize % uniSize == 0
	bool isMont; // true if use Montgomery
	bool isFastMod; // true if modulo is fast

	Op()
	{
		clear();
	}
	~Op()
	{
#ifdef MCL_USE_XBYAK
		destroyFpGenerator(fg);
#endif
	}
	void clear()
	{
		rp = 0;
		memset(p, 0, sizeof(p));
		mp = 0;
		pmod4 = 0;
		sq.clear();
		// fg is not set
		memset(half, 0, sizeof(half));
		memset(oneRep, 0, sizeof(oneRep));
		memset(one, 0, sizeof(one));
		memset(R2, 0, sizeof(R2));
		memset(R3, 0, sizeof(R3));
#ifdef MCL_X64_ASM
		invTbl.clear();
#endif
		fp_addA_ = 0;
		fp_subA_ = 0;
		fp_negA_ = 0;
		fp_mulA_ = 0;
		fp_sqrA_ = 0;
		fp_mul2A_ = 0;
		fp_mul9A_ = 0;
		fp2_addA_ = 0;
		fp2_subA_ = 0;
		fp2_negA_ = 0;
		fp2_mulA_ = 0;
		fp2_sqrA_ = 0;
		fp2_mul2A_ = 0;
		fpDbl_addA_ = 0;
		fpDbl_subA_ = 0;
		fpDbl_modA_ = 0;
		fp2Dbl_mulPreA_ = 0;
		fp2Dbl_sqrPreA_ = 0;
		fp2Dbl_mul_xiA_ = 0;
		maxN = 0;
		N = 0;
		bitSize = 0;
		fp_isZero = 0;
		fp_clear = 0;
		fp_copy = 0;
		fp_shr1 = 0;
		fp_neg = 0;
		fp_add = 0;
		fp_sub = 0;
		fp_mul = 0;
		fp_sqr = 0;
		fp_mul2 = 0;
		fp_invOp = 0;
		fp_mulUnit = 0;

		fpDbl_mulPre = 0;
		fpDbl_sqrPre = 0;
		fp_preInv = 0;
		fp_mulUnitPre = 0;
		fpN1_mod = 0;

		fpDbl_add = 0;
		fpDbl_sub = 0;
		fpDbl_mod = 0;

		fp_addPre = 0;
		fp_subPre = 0;
		fpDbl_addPre = 0;
		fpDbl_subPre = 0;

		xi_a = 0;
		fp2_mulNF = 0;
		fp2_mul_xiA_ = 0;
		hash = 0;

		primeMode = PM_GENERIC;
		isFullBit = false;
		isMont = false;
		isFastMod = false;
	}
	void fromMont(Unit* y, const Unit *x) const
	{
		/*
			M(x, y) = xyR^-1
			y = M(x, 1) = xR^-1
		*/
		fp_mul(y, x, one, p);
	}
	void toMont(Unit* y, const Unit *x) const
	{
		/*
			y = M(x, R2) = xR^2 R^-1 = xR
		*/
		fp_mul(y, x, R2, p);
	}
	bool init(const mpz_class& p, size_t maxBitSize, int xi_a, Mode mode, size_t mclMaxBitSize = MCL_MAX_BIT_SIZE);
#ifdef MCL_USE_XBYAK
	static FpGenerator* createFpGenerator();
	static void destroyFpGenerator(FpGenerator *fg);
#endif
private:
	Op(const Op&);
	void operator=(const Op&);
};

inline const char* getIoSeparator(int ioMode)
{
	return (ioMode & (IoArray | IoArrayRaw | IoSerialize | IoSerializeHexStr | IoEcAffineSerialize)) ? "" : " ";
}

inline void dump(const void *buf, size_t n)
{
	const uint8_t *s = (const uint8_t *)buf;
	for (size_t i = 0; i < n; i++) {
		printf("%02x ", s[i]);
	}
	printf("\n");
}

#ifndef CYBOZU_DONT_USE_STRING
int detectIoMode(int ioMode, const std::ios_base& ios);

inline void dump(const std::string& s)
{
	dump(s.c_str(), s.size());
}
#endif

} } // mcl::fp
<commit_msg>v1.64<commit_after>#pragma once
/**
	@file
	@brief definition of Op
	@author MITSUNARI Shigeo(@herumi)
	@license modified new BSD license
	http://opensource.org/licenses/BSD-3-Clause
*/
#include <mcl/gmp_util.hpp>
#include <memory.h>
#include <mcl/array.hpp>

#if defined(__EMSCRIPTEN__) || defined(__wasm__)
	#define MCL_DONT_USE_XBYAK
	#define MCL_DONT_USE_OPENSSL
#endif
#if !defined(MCL_DONT_USE_XBYAK) && (defined(_WIN64) || defined(__x86_64__)) && (MCL_SIZEOF_UNIT == 8) && !defined(MCL_STATIC_CODE)
	#define MCL_USE_XBYAK
#endif
#if defined(MCL_USE_XBYAK) || defined(MCL_STATIC_CODE)
	#define MCL_X64_ASM
	#define MCL_XBYAK_DIRECT_CALL
#endif

#define MCL_MAX_HASH_BIT_SIZE 512

namespace mcl {

static const int version = 0x164; /* 0xABC = A.BC */

/*
	specifies available string format mode for X::setIoMode()
	// for Fp, Fp2, Fp6, Fp12
	default(0) : IoDec
	printable string(zero terminated, variable size)
	IoBin(2) | IoDec(10) | IoHex(16) | IoBinPrefix | IoHexPrefix

	byte string(not zero terminated, fixed size)
	IoArray | IoArrayRaw
	IoArray = IoSerialize

	// for Ec
	affine(0) | IoEcCompY | IoComp
	default : affine

	affine and IoEcCompY are available with ioMode for Fp
	IoSerialize ignores ioMode for Fp

	IoAuto
		dec or hex according to ios_base::fmtflags
	IoBin
		binary number([01]+)
	IoDec
		decimal number
	IoHex
		hexadecimal number([0-9a-fA-F]+)
	IoBinPrefix
		0b + <binary number>
	IoHexPrefix
		0x + <hexadecimal number>
	IoArray
		array of Unit(fixed size = Fp::getByteSize())
	IoArrayRaw
		array of Unit(fixed size = Fp::getByteSize()) without Montgomery conversion

	// for Ec::setIoMode()
	IoEcAffine(default)
	"0" ; infinity
	"1 <x> <y>" ; affine coordinate

	IoEcProj
	"4" <x> <y> <z> ; projective or jacobi coordinate

	IoEcCompY
		1-bit y prepresentation of elliptic curve
		"2 <x>" ; compressed for even y
		"3 <x>" ; compressed for odd y

	IoSerialize
		if isMSBserialize(): // p is not full bit
			size = Fp::getByteSize()
			use MSB of array of x for 1-bit y for prime p where (p % 8 != 0)
			[0] ; infinity
			<x> ; for even y
			<x>|1 ; for odd y ; |1 means set MSB of x
		else:
			size = Fp::getByteSize() + 1
			[0] ; infinity
			2 <x> ; for even y
			3 <x> ; for odd y
*/
enum IoMode {
	IoAuto = 0, // dec or hex according to ios_base::fmtflags
	IoBin = 2, // binary number without prefix
	IoDec = 10, // decimal number without prefix
	IoHex = 16, // hexadecimal number without prefix
	IoArray = 32, // array of Unit(fixed size)
	IoArrayRaw = 64, // raw array of Unit without Montgomery conversion
	IoPrefix = 128, // append '0b'(bin) or '0x'(hex)
	IoBinPrefix = IoBin | IoPrefix,
	IoHexPrefix = IoHex | IoPrefix,
	IoEcAffine = 0, // affine coordinate
	IoEcCompY = 256, // 1-bit y representation of elliptic curve
	IoSerialize = 512, // use MBS for 1-bit y
	IoFixedSizeByteSeq = IoSerialize, // obsolete
	IoEcProj = 1024, // projective or jacobi coordinate
	IoSerializeHexStr = 2048, // printable hex string
	IoEcAffineSerialize = 4096 // serialize [x:y]
};

namespace fp {

inline bool isIoSerializeMode(int ioMode)
{
	return ioMode & (IoArray | IoArrayRaw | IoSerialize | IoEcAffineSerialize | IoSerializeHexStr);
}

const size_t maxMulVecN = 32; // inner loop of mulVec

#ifndef MCL_MAX_MUL_VEC_NGLV
	#define MCL_MAX_MUL_VEC_NGLV 16
#endif
const size_t maxMulVecNGLV = MCL_MAX_MUL_VEC_NGLV; // inner loop of mulVec with GLV

struct FpGenerator;
struct Op;

typedef void (*void1u)(Unit*);
typedef void (*void2u)(Unit*, const Unit*);
typedef void (*void2uI)(Unit*, const Unit*, Unit);
typedef void (*void2uIu)(Unit*, const Unit*, Unit, const Unit*);
typedef void (*void2uOp)(Unit*, const Unit*, const Op&);
typedef void (*void3u)(Unit*, const Unit*, const Unit*);
typedef void (*void4u)(Unit*, const Unit*, const Unit*, const Unit*);
typedef int (*int2u)(Unit*, const Unit*);

typedef Unit (*u1uII)(Unit*, Unit, Unit);
typedef Unit (*u3u)(Unit*, const Unit*, const Unit*);

/*
	disable -Wcast-function-type
	the number of arguments of some JIT functions is smaller than that of T
*/
template<class T, class S>
T func_ptr_cast(S func)
{
	return reinterpret_cast<T>(reinterpret_cast<void*>(func));
}
struct Block {
	const Unit *p; // pointer to original FpT.v_
	size_t n;
	Unit v_[maxUnitSize];
};

enum Mode {
	FP_AUTO,
	FP_GMP,
	FP_GMP_MONT,
	FP_LLVM,
	FP_LLVM_MONT,
	FP_XBYAK
};

enum PrimeMode {
	PM_GENERIC = 0,
	PM_NIST_P192,
	PM_SECP256K1,
	PM_NIST_P521
};

struct Op {
	/*
		don't change the layout of rp and p
		asm code assumes &rp + 1 == p
	*/
	Unit rp;
	Unit p[maxUnitSize];
	mpz_class mp;
	uint32_t pmod4;
	mcl::SquareRoot sq;
	mcl::Modp modp;
	mcl::SmallModp smallModp;
	Unit half[maxUnitSize]; // (p + 1) / 2
	Unit oneRep[maxUnitSize]; // 1(=inv R if Montgomery)
	/*
		for Montgomery
		one = 1
		R = (1 << (N * sizeof(Unit) * 8)) % p
		R2 = (R * R) % p
		R3 = RR^3
	*/
	Unit one[maxUnitSize];
	Unit R2[maxUnitSize];
	Unit R3[maxUnitSize];
#ifdef MCL_USE_XBYAK
	FpGenerator *fg;
#endif
#ifdef MCL_X64_ASM
	mcl::Array<Unit> invTbl;
#endif
	void3u fp_addA_;
	void3u fp_subA_;
	void2u fp_negA_;
	void3u fp_mulA_;
	void2u fp_sqrA_;
	void2u fp_mul2A_;
	void2u fp_mul9A_;
	void3u fp2_addA_;
	void3u fp2_subA_;
	void2u fp2_negA_;
	void3u fp2_mulA_;
	void2u fp2_sqrA_;
	void2u fp2_mul2A_;
	void3u fpDbl_addA_;
	void3u fpDbl_subA_;
	void2u fpDbl_modA_;
	void3u fp2Dbl_mulPreA_;
	void2u fp2Dbl_sqrPreA_;
	void2u fp2Dbl_mul_xiA_;
	size_t maxN;
	size_t N;
	size_t bitSize;
	bool (*fp_isZero)(const Unit*);
	void1u fp_clear;
	void2u fp_copy;
	void2u fp_shr1;
	void3u fp_neg;
	void4u fp_add;
	void4u fp_sub;
	void4u fp_mul;
	void3u fp_sqr;
	void3u fp_mul2;
	void2uOp fp_invOp;
	void2uIu fp_mulUnit; // fpN1_mod + fp_mulUnitPre

	void3u fpDbl_mulPre;
	void2u fpDbl_sqrPre;
	int2u fp_preInv;
	void2uI fp_mulUnitPre; // z[N + 1] = x[N] * y
	void3u fpN1_mod; // y[N] = x[N + 1] % p[N]

	void4u fpDbl_add;
	void4u fpDbl_sub;
	void3u fpDbl_mod;

	u3u fp_addPre; // without modulo p
	u3u fp_subPre; // without modulo p
	u3u fpDbl_addPre;
	u3u fpDbl_subPre;
	/*
		for Fp2 = F[u] / (u^2 + 1)
		x = a + bu
	*/
	int xi_a; // xi = xi_a + u
	void4u fp2_mulNF;
	void2u fp2_mul_xiA_;
	uint32_t (*hash)(void *out, uint32_t maxOutSize, const void *msg, uint32_t msgSize);

	PrimeMode primeMode;
	bool isFullBit; // true if bitSize % uniSize == 0
	bool isMont; // true if use Montgomery
	bool isFastMod; // true if modulo is fast

	Op()
	{
		clear();
	}
	~Op()
	{
#ifdef MCL_USE_XBYAK
		destroyFpGenerator(fg);
#endif
	}
	void clear()
	{
		rp = 0;
		memset(p, 0, sizeof(p));
		mp = 0;
		pmod4 = 0;
		sq.clear();
		// fg is not set
		memset(half, 0, sizeof(half));
		memset(oneRep, 0, sizeof(oneRep));
		memset(one, 0, sizeof(one));
		memset(R2, 0, sizeof(R2));
		memset(R3, 0, sizeof(R3));
#ifdef MCL_X64_ASM
		invTbl.clear();
#endif
		fp_addA_ = 0;
		fp_subA_ = 0;
		fp_negA_ = 0;
		fp_mulA_ = 0;
		fp_sqrA_ = 0;
		fp_mul2A_ = 0;
		fp_mul9A_ = 0;
		fp2_addA_ = 0;
		fp2_subA_ = 0;
		fp2_negA_ = 0;
		fp2_mulA_ = 0;
		fp2_sqrA_ = 0;
		fp2_mul2A_ = 0;
		fpDbl_addA_ = 0;
		fpDbl_subA_ = 0;
		fpDbl_modA_ = 0;
		fp2Dbl_mulPreA_ = 0;
		fp2Dbl_sqrPreA_ = 0;
		fp2Dbl_mul_xiA_ = 0;
		maxN = 0;
		N = 0;
		bitSize = 0;
		fp_isZero = 0;
		fp_clear = 0;
		fp_copy = 0;
		fp_shr1 = 0;
		fp_neg = 0;
		fp_add = 0;
		fp_sub = 0;
		fp_mul = 0;
		fp_sqr = 0;
		fp_mul2 = 0;
		fp_invOp = 0;
		fp_mulUnit = 0;

		fpDbl_mulPre = 0;
		fpDbl_sqrPre = 0;
		fp_preInv = 0;
		fp_mulUnitPre = 0;
		fpN1_mod = 0;

		fpDbl_add = 0;
		fpDbl_sub = 0;
		fpDbl_mod = 0;

		fp_addPre = 0;
		fp_subPre = 0;
		fpDbl_addPre = 0;
		fpDbl_subPre = 0;

		xi_a = 0;
		fp2_mulNF = 0;
		fp2_mul_xiA_ = 0;
		hash = 0;

		primeMode = PM_GENERIC;
		isFullBit = false;
		isMont = false;
		isFastMod = false;
	}
	void fromMont(Unit* y, const Unit *x) const
	{
		/*
			M(x, y) = xyR^-1
			y = M(x, 1) = xR^-1
		*/
		fp_mul(y, x, one, p);
	}
	void toMont(Unit* y, const Unit *x) const
	{
		/*
			y = M(x, R2) = xR^2 R^-1 = xR
		*/
		fp_mul(y, x, R2, p);
	}
	bool init(const mpz_class& p, size_t maxBitSize, int xi_a, Mode mode, size_t mclMaxBitSize = MCL_MAX_BIT_SIZE);
#ifdef MCL_USE_XBYAK
	static FpGenerator* createFpGenerator();
	static void destroyFpGenerator(FpGenerator *fg);
#endif
private:
	Op(const Op&);
	void operator=(const Op&);
};

inline const char* getIoSeparator(int ioMode)
{
	return (ioMode & (IoArray | IoArrayRaw | IoSerialize | IoSerializeHexStr | IoEcAffineSerialize)) ? "" : " ";
}

inline void dump(const void *buf, size_t n)
{
	const uint8_t *s = (const uint8_t *)buf;
	for (size_t i = 0; i < n; i++) {
		printf("%02x ", s[i]);
	}
	printf("\n");
}

#ifndef CYBOZU_DONT_USE_STRING
int detectIoMode(int ioMode, const std::ios_base& ios);

inline void dump(const std::string& s)
{
	dump(s.c_str(), s.size());
}
#endif

} } // mcl::fp
<|endoftext|>


<commit_before>/**
 * @file
 *
 * @brief Tests for yanlr plugin
 *
 * @copyright BSD License (see LICENSE.md or https://www.libelektra.org)
 *
 */

// -- Imports ------------------------------------------------------------------------------------------------------------------------------

#include "yanlr.hpp"

#include <kdbmodule.h>
#include <kdbprivate.h>

#include <tests.h>
#include <tests.hpp>

using ckdb::keyNew;

using CppKeySet = kdb::KeySet;
using CppKey = kdb::Key;

// -- Macros -------------------------------------------------------------------------------------------------------------------------------

#define OPEN_PLUGIN(parentName, filepath)                                                                                \
	CppKeySet modules{ 0, KS_END };                                                                                \
	CppKeySet config{ 0, KS_END };                                                                                \
	elektraModulesInit (modules.getKeySet (), 0);                                                                                \
	CppKey parent{ parentName, KEY_VALUE, filepath, KEY_END };                                                                         \
	Plugin * plugin = elektraPluginOpen ("yanlr", modules.getKeySet (), config.getKeySet (), *parent);                                 \
	exit_if_fail (plugin != NULL, "Could not open yanlr plugin")

#define CLOSE_PLUGIN()                                                                                \
	elektraPluginClose (plugin, 0);                                                                                \
	elektraModulesClose (modules.getKeySet (), 0);                                                                                \
	ksDel (modules.release ());                                                                                \
	config.release ()

#define PREFIX "user/tests/yanlr/"

// -- Functions  ---------------------------------------------------------------------------------------------------------------------------

void test_read (string const & filepath, CppKeySet expected, int const status = ELEKTRA_PLUGIN_STATUS_SUCCESS)
#ifdef __llvm__
	__attribute__ ((annotate ("oclint:suppress[high ncss method]"), annotate ("oclint:suppress[empty if statement]"),
			annotate ("oclint:suppress[too few branches in switch statement]")))
#endif
{
	OPEN_PLUGIN (PREFIX, srcdir_file (filepath.c_str ()));

	// We replace the value of the parent key of expected keyset, if the header file specifies the value @CONFIG_FILEPATH@.
	// We could also do that via CMake, but the current solution should be easier for now.
	CppKey root = expected.lookup (PREFIX, KDB_O_POP);
	if (root)
	{
		if (root.getString () == "@CONFIG_FILEPATH@") root.setString (srcdir_file (filepath.c_str ()));
		expected.append (root);
	}

	CppKeySet keys;
	succeed_if_same (plugin->kdbGet (plugin, keys.getKeySet (), *parent), status, "Call of `kdbGet` failed");
	compare_keyset (expected, keys);

	CLOSE_PLUGIN ();
}

// -- Tests --------------------------------------------------------------------------------------------------------------------------------

TEST (yanlr, basics)
{
	OPEN_PLUGIN ("system/elektra/modules/yanlr", "file/path");

	CppKeySet keys;
	succeed_if_same (plugin->kdbGet (plugin, keys.getKeySet (), *parent), ELEKTRA_PLUGIN_STATUS_SUCCESS,
			 "Could not retrieve plugin contract");

	CLOSE_PLUGIN ();
}

TEST (yanlr, empty)
{
	test_read ("yanlr/null.yaml",
#include "yanlr/null.hpp"
		   , ELEKTRA_PLUGIN_STATUS_NO_UPDATE);
	test_read ("yanlr/comment.yaml",
#include "yanlr/null.hpp"
		   , ELEKTRA_PLUGIN_STATUS_NO_UPDATE);
}

TEST (yanlr, scalar)
{
	test_read ("yanlr/plain_scalar-word_chars.yaml",
#include "yanlr/plain_scalar-word_chars.hpp"
	);
	test_read ("yanlr/plain_scalar-word_chars_space.yaml",
#include "yanlr/plain_scalar-word_chars_space.hpp"
	);
	test_read ("yanlr/single_quoted_scalar.yaml",
#include "yanlr/single_quoted_scalar.hpp"
	);
	test_read ("yanlr/double_quoted_scalar.yaml",
#include "yanlr/double_quoted_scalar.hpp"
	);
}

TEST (yanlr, list)
{
	test_read ("yanlr/list-plain_scalars.yaml",
#include "yanlr/list-plain_scalars.hpp"
	);
	test_read ("yanlr/list-list_map-mixed_scalars.yaml",
#include "yanlr/list-list_map-mixed_scalars.hpp"
	);
}

TEST (yanlr, map)
{
	test_read ("yanlr/map-null.yaml",
#include "yanlr/map-null.hpp"
	);
	test_read ("yanlr/map-plain_scalar.yaml",
#include "yanlr/map-plain_scalar.hpp"
	);
	test_read ("yanlr/map-plain_scalars.yaml",
#include "yanlr/map-plain_scalars.hpp"
	);
	test_read ("yanlr/map-list-plain_scalars.yaml",
#include "yanlr/map-list-plain_scalars.hpp"
	);
	test_read ("yanlr/map-map-plain_scalars.yaml",
#include "yanlr/map-map-plain_scalars.hpp"
	);
}

// -- Main ---------------------------------------------------------------------------------------------------------------------------------

int main (int argc, char * argv[])
{
	init (argc, argv); // Required for `srcdir_file` to work properly
	::testing::InitGoogleTest (&argc, argv);
	return RUN_ALL_TESTS ();
}
<commit_msg>Yan LR: Simplify unit tests macros<commit_after>/**
 * @file
 *
 * @brief Tests for yanlr plugin
 *
 * @copyright BSD License (see LICENSE.md or https://www.libelektra.org)
 *
 */

// -- Imports ------------------------------------------------------------------------------------------------------------------------------

#include "yanlr.hpp"

#include <kdbmodule.h>
#include <kdbprivate.h>

#include <tests.h>
#include <tests.hpp>

using ckdb::keyNew;

using CppKeySet = kdb::KeySet;
using CppKey = kdb::Key;

// -- Macros -------------------------------------------------------------------------------------------------------------------------------

#define OPEN_PLUGIN(parentName, filepath)                                                                                \
	CppKeySet modules{ 0, KS_END };                                                                                \
	elektraModulesInit (modules.getKeySet (), 0);                                                                                \
	CppKeySet config{ 0, KS_END };                                                                                \
	CppKey parent{ parentName, KEY_VALUE, filepath, KEY_END };                                                                         \
	Plugin * plugin = elektraPluginOpen ("yanlr", modules.getKeySet (), config.getKeySet (), *parent);

#define CLOSE_PLUGIN()                                                                                \
	config.release ();                                                                                \
	elektraPluginClose (plugin, 0);                                                                                \
	elektraModulesClose (modules.getKeySet (), 0)

#define PREFIX "user/tests/yanlr/"

// -- Functions  ---------------------------------------------------------------------------------------------------------------------------

void test_read (string const & filepath, CppKeySet expected, int const status = ELEKTRA_PLUGIN_STATUS_SUCCESS)
#ifdef __llvm__
	__attribute__ ((annotate ("oclint:suppress[high ncss method]"), annotate ("oclint:suppress[empty if statement]"),
			annotate ("oclint:suppress[too few branches in switch statement]")))
#endif
{
	OPEN_PLUGIN (PREFIX, srcdir_file (filepath.c_str ()));

	// We replace the value of the parent key of expected keyset, if the header file specifies the value @CONFIG_FILEPATH@.
	// We could also do that via CMake, but the current solution should be easier for now.
	CppKey root = expected.lookup (PREFIX, KDB_O_POP);
	if (root)
	{
		if (root.getString () == "@CONFIG_FILEPATH@") root.setString (srcdir_file (filepath.c_str ()));
		expected.append (root);
	}

	CppKeySet keys;
	succeed_if_same (plugin->kdbGet (plugin, keys.getKeySet (), *parent), status, "Call of `kdbGet` failed");
	compare_keyset (expected, keys);

	CLOSE_PLUGIN ();
}

// -- Tests --------------------------------------------------------------------------------------------------------------------------------

TEST (yanlr, basics)
{
	OPEN_PLUGIN ("system/elektra/modules/yanlr", "file/path");

	CppKeySet keys;
	succeed_if_same (plugin->kdbGet (plugin, keys.getKeySet (), *parent), ELEKTRA_PLUGIN_STATUS_SUCCESS,
			 "Could not retrieve plugin contract");

	CLOSE_PLUGIN ();
}

TEST (yanlr, empty)
{
	test_read ("yanlr/null.yaml",
#include "yanlr/null.hpp"
		   , ELEKTRA_PLUGIN_STATUS_NO_UPDATE);
	test_read ("yanlr/comment.yaml",
#include "yanlr/null.hpp"
		   , ELEKTRA_PLUGIN_STATUS_NO_UPDATE);
}

TEST (yanlr, scalar)
{
	test_read ("yanlr/plain_scalar-word_chars.yaml",
#include "yanlr/plain_scalar-word_chars.hpp"
	);
	test_read ("yanlr/plain_scalar-word_chars_space.yaml",
#include "yanlr/plain_scalar-word_chars_space.hpp"
	);
	test_read ("yanlr/single_quoted_scalar.yaml",
#include "yanlr/single_quoted_scalar.hpp"
	);
	test_read ("yanlr/double_quoted_scalar.yaml",
#include "yanlr/double_quoted_scalar.hpp"
	);
}

TEST (yanlr, list)
{
	test_read ("yanlr/list-plain_scalars.yaml",
#include "yanlr/list-plain_scalars.hpp"
	);
	test_read ("yanlr/list-list_map-mixed_scalars.yaml",
#include "yanlr/list-list_map-mixed_scalars.hpp"
	);
}

TEST (yanlr, map)
{
	test_read ("yanlr/map-null.yaml",
#include "yanlr/map-null.hpp"
	);
	test_read ("yanlr/map-plain_scalar.yaml",
#include "yanlr/map-plain_scalar.hpp"
	);
	test_read ("yanlr/map-plain_scalars.yaml",
#include "yanlr/map-plain_scalars.hpp"
	);
	test_read ("yanlr/map-list-plain_scalars.yaml",
#include "yanlr/map-list-plain_scalars.hpp"
	);
	test_read ("yanlr/map-map-plain_scalars.yaml",
#include "yanlr/map-map-plain_scalars.hpp"
	);
}

// -- Main ---------------------------------------------------------------------------------------------------------------------------------

int main (int argc, char * argv[])
{
	init (argc, argv); // Required for `srcdir_file` to work properly
	::testing::InitGoogleTest (&argc, argv);
	return RUN_ALL_TESTS ();
}
<|endoftext|>


<commit_before>/**
 * @file
 *
 * @brief Tests for yanlr plugin
 *
 * @copyright BSD License (see LICENSE.md or https://www.libelektra.org)
 *
 */

// -- Imports ------------------------------------------------------------------------------------------------------------------------------

#include "yanlr.hpp"

#include <kdbmodule.h>
#include <kdbprivate.h>

#include <tests.h>
#include <tests.hpp>

using ckdb::keyNew;

using CppKeySet = kdb::KeySet;
using CppKey = kdb::Key;

// -- Macros -------------------------------------------------------------------------------------------------------------------------------

#define OPEN_PLUGIN(parentName, filepath)                                                                                \
	CppKeySet modules{ 0, KS_END };                                                                                \
	elektraModulesInit (modules.getKeySet (), 0);                                                                                \
	CppKeySet config{ 0, KS_END };                                                                                \
	CppKey parent{ parentName, KEY_VALUE, filepath, KEY_END };                                                                         \
	Plugin * plugin = elektraPluginOpen ("yanlr", modules.getKeySet (), config.getKeySet (), *parent);

#define CLOSE_PLUGIN()                                                                                \
	config.release ();                                                                                \
	elektraPluginClose (plugin, 0);                                                                                \
	elektraModulesClose (modules.getKeySet (), 0)

#define PREFIX "user:/tests/yanlr/"

// -- Functions  ---------------------------------------------------------------------------------------------------------------------------

void test_read (string const & filepath, CppKeySet expected)
#ifdef __llvm__
	__attribute__ ((annotate ("oclint:suppress[high ncss method]"), annotate ("oclint:suppress[empty if statement]"),
			annotate ("oclint:suppress[too few branches in switch statement]")))
#endif
{
	OPEN_PLUGIN (PREFIX, srcdir_file (filepath.c_str ()));

	// We replace the value of the parent key of expected keyset, if the header file specifies the value @CONFIG_FILEPATH@.
	// We could also do that via CMake, but the current solution should be easier for now.
	CppKey root = expected.lookup (PREFIX, KDB_O_POP);
	if (root)
	{
		if (root.getString () == "@CONFIG_FILEPATH@") root.setString (srcdir_file (filepath.c_str ()));
		expected.append (root);
	}

	CppKeySet keys;
	succeed_if_same (plugin->kdbGet (plugin, keys.getKeySet (), *parent), ELEKTRA_PLUGIN_STATUS_SUCCESS, "Call of `kdbGet` failed");
	compare_keyset (expected, keys);

	CLOSE_PLUGIN ();
}

// -- Tests --------------------------------------------------------------------------------------------------------------------------------

TEST (yanlr, basics)
{
	OPEN_PLUGIN ("system:/elektra/modules/yanlr", "file/path");

	CppKeySet keys;
	succeed_if_same (plugin->kdbGet (plugin, keys.getKeySet (), *parent), ELEKTRA_PLUGIN_STATUS_SUCCESS,
			 "Could not retrieve plugin contract");

	CLOSE_PLUGIN ();
}

TEST (yanlr, empty)
{
	test_read ("yanlr/null.yaml",
#include "yanlr/null.hpp"
	);
	test_read ("yanlr/comment.yaml",
#include "yanlr/null.hpp"
	);
}

TEST (yanlr, scalar)
{
	test_read ("yanlr/plain_scalar-word_chars.yaml",
#include "yanlr/plain_scalar-word_chars.hpp"
	);
	test_read ("yanlr/plain_scalar-word_chars_space.yaml",
#include "yanlr/plain_scalar-word_chars_space.hpp"
	);
	test_read ("yanlr/single_quoted_scalar.yaml",
#include "yanlr/single_quoted_scalar.hpp"
	);
	test_read ("yanlr/double_quoted_scalar.yaml",
#include "yanlr/double_quoted_scalar.hpp"
	);
}

TEST (yanlr, list)
{
	test_read ("yanlr/list-plain_scalars.yaml",
#include "yanlr/list-plain_scalars.hpp"
	);
	test_read ("yanlr/list-list_map-mixed_scalars.yaml",
#include "yanlr/list-list_map-mixed_scalars.hpp"
	);
}

TEST (yanlr, map)
{
	test_read ("yanlr/map-null.yaml",
#include "yanlr/map-null.hpp"
	);
	test_read ("yanlr/map-plain_scalar.yaml",
#include "yanlr/map-plain_scalar.hpp"
	);
	test_read ("yanlr/map-plain_scalars.yaml",
#include "yanlr/map-plain_scalars.hpp"
	);
	test_read ("yanlr/map-list-plain_scalars.yaml",
#include "yanlr/map-list-plain_scalars.hpp"
	);
	test_read ("yanlr/map-map-plain_scalars.yaml",
#include "yanlr/map-map-plain_scalars.hpp"
	);
}

// -- Main ---------------------------------------------------------------------------------------------------------------------------------

int main (int argc, char * argv[])
{
	init (argc, argv); // Required for `srcdir_file` to work properly
	::testing::InitGoogleTest (&argc, argv);
	return RUN_ALL_TESTS ();
}
<commit_msg>Yan LR: Update suppressions for OCLint 20.11<commit_after>/**
 * @file
 *
 * @brief Tests for yanlr plugin
 *
 * @copyright BSD License (see LICENSE.md or https://www.libelektra.org)
 *
 */

// -- Imports ------------------------------------------------------------------------------------------------------------------------------

#include "yanlr.hpp"

#include <kdbmodule.h>
#include <kdbprivate.h>

#include <tests.h>
#include <tests.hpp>

using ckdb::keyNew;

using CppKeySet = kdb::KeySet;
using CppKey = kdb::Key;

// -- Macros -------------------------------------------------------------------------------------------------------------------------------

#define OPEN_PLUGIN(parentName, filepath)                                                                                \
	CppKeySet modules{ 0, KS_END };                                                                                \
	elektraModulesInit (modules.getKeySet (), 0);                                                                                \
	CppKeySet config{ 0, KS_END };                                                                                \
	CppKey parent{ parentName, KEY_VALUE, filepath, KEY_END };                                                                         \
	Plugin * plugin = elektraPluginOpen ("yanlr", modules.getKeySet (), config.getKeySet (), *parent);

#define CLOSE_PLUGIN()                                                                                \
	config.release ();                                                                                \
	elektraPluginClose (plugin, 0);                                                                                \
	elektraModulesClose (modules.getKeySet (), 0)

#define PREFIX "user:/tests/yanlr/"

// -- Functions  ---------------------------------------------------------------------------------------------------------------------------

void test_read (string const & filepath, CppKeySet expected)
#ifdef __llvm__
	__attribute__ ((annotate ("oclint:suppress[high ncss method]"), annotate ("oclint:suppress[empty if statement]"),
			annotate ("oclint:suppress[too few branches in switch statement]")))
#endif
{
	OPEN_PLUGIN (PREFIX, srcdir_file (filepath.c_str ()));

	// We replace the value of the parent key of expected keyset, if the header file specifies the value @CONFIG_FILEPATH@.
	// We could also do that via CMake, but the current solution should be easier for now.
	CppKey root = expected.lookup (PREFIX, KDB_O_POP);
	if (root)
	{
		if (root.getString () == "@CONFIG_FILEPATH@") root.setString (srcdir_file (filepath.c_str ()));
		expected.append (root);
	}

	CppKeySet keys;
	succeed_if_same (plugin->kdbGet (plugin, keys.getKeySet (), *parent), ELEKTRA_PLUGIN_STATUS_SUCCESS, "Call of `kdbGet` failed");
	compare_keyset (expected, keys);

	CLOSE_PLUGIN ();
}

// -- Tests --------------------------------------------------------------------------------------------------------------------------------

TEST (yanlr, basics) //! OCLint (avoid private static members)
#ifdef __llvm__
__attribute__ ((annotate ("oclint:suppress[empty if statement]"), annotate ("oclint:suppress[too few branches in switch statement]")))
#endif
{
	OPEN_PLUGIN ("system:/elektra/modules/yanlr", "file/path");

	CppKeySet keys;
	succeed_if_same (plugin->kdbGet (plugin, keys.getKeySet (), *parent), ELEKTRA_PLUGIN_STATUS_SUCCESS,
			 "Could not retrieve plugin contract");

	CLOSE_PLUGIN ();
}

TEST (yanlr, empty) //! OCLint (avoid private static members)
{
	test_read ("yanlr/null.yaml",
#include "yanlr/null.hpp"
	);
	test_read ("yanlr/comment.yaml",
#include "yanlr/null.hpp"
	);
}

TEST (yanlr, scalar) //! OCLint (avoid private static members)
{
	test_read ("yanlr/plain_scalar-word_chars.yaml",
#include "yanlr/plain_scalar-word_chars.hpp"
	);
	test_read ("yanlr/plain_scalar-word_chars_space.yaml",
#include "yanlr/plain_scalar-word_chars_space.hpp"
	);
	test_read ("yanlr/single_quoted_scalar.yaml",
#include "yanlr/single_quoted_scalar.hpp"
	);
	test_read ("yanlr/double_quoted_scalar.yaml",
#include "yanlr/double_quoted_scalar.hpp"
	);
}

TEST (yanlr, list) //! OCLint (avoid private static members)
{
	test_read ("yanlr/list-plain_scalars.yaml",
#include "yanlr/list-plain_scalars.hpp"
	);
	test_read ("yanlr/list-list_map-mixed_scalars.yaml",
#include "yanlr/list-list_map-mixed_scalars.hpp"
	);
}

TEST (yanlr, map) //! OCLint (avoid private static members)
{
	test_read ("yanlr/map-null.yaml",
#include "yanlr/map-null.hpp"
	);
	test_read ("yanlr/map-plain_scalar.yaml",
#include "yanlr/map-plain_scalar.hpp"
	);
	test_read ("yanlr/map-plain_scalars.yaml",
#include "yanlr/map-plain_scalars.hpp"
	);
	test_read ("yanlr/map-list-plain_scalars.yaml",
#include "yanlr/map-list-plain_scalars.hpp"
	);
	test_read ("yanlr/map-map-plain_scalars.yaml",
#include "yanlr/map-map-plain_scalars.hpp"
	);
}

// -- Main ---------------------------------------------------------------------------------------------------------------------------------

int main (int argc, char * argv[])
{
	init (argc, argv); // Required for `srcdir_file` to work properly
	::testing::InitGoogleTest (&argc, argv);
	return RUN_ALL_TESTS ();
}
<|endoftext|>