#include "filename/ast/filename-node-conditional.h"
#include "filename/ast/filename-visitor.h"

FilenameNodeConditional::FilenameNodeConditional(FilenameNodeCondition *condition, FilenameNode *ifTrue, FilenameNode *ifFalse)
	: condition(condition), ifTrue(ifTrue), ifFalse(ifFalse)
{}

FilenameNodeConditional::~FilenameNodeConditional()
{
	delete condition;
	delete ifTrue;
	delete ifFalse;
}

void FilenameNodeConditional::accept(FilenameVisitor &v) const
{
	v.visit(*this);
}

#include "filename/ast/filename-node-conditional.h"
#include "filename/ast/filename-node-condition.h"
#include "filename/ast/filename-visitor.h"

FilenameNodeConditional::FilenameNodeConditional(FilenameNodeCondition *condition, FilenameNode *ifTrue, FilenameNode *ifFalse)
	: condition(condition), ifTrue(ifTrue), ifFalse(ifFalse)
{}

FilenameNodeConditional::~FilenameNodeConditional()
{
	delete condition;
	delete ifTrue;
	delete ifFalse;
}

void FilenameNodeConditional::accept(FilenameVisitor &v) const
{
	v.visit(*this);
}

Fix warning about deleting non full type


#include <cstdlib>

#include "Application/Parameters/ApplicationParameters.h"
#include "Application/Parameters/ApplicationParametersBuilder.h"
#include "Application/Parameters/ApplicationParametersManager.h"
#include "Application/Parameters/ApplicationParametersReader.h"
#include "FileSystem/Entities/Executable.h"
#include "FileSystem/Factories/EntityFactory.h"
#include "FileSystem/Entities/Exceptions/InvalidExecutablePathException.h"
#include <memory>
#include <iostream>

using namespace clt::filesystem;
using namespace clt::filesystem::factories;
using namespace clt::filesystem::entities;
using namespace clt::filesystem::entities::exceptions;
using namespace application::parameters;

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

	if (argc < 2)
	{
		// TODO: real arguments management
		printf("not enough argument, need the path of your executable");
		return EXIT_FAILURE;
	}

	ApplicationParametersManager parametersManager(std::make_unique<ApplicationParametersBuilder>(), std::make_unique<ApplicationParametersReader>());
	parametersManager.start(argc, argv);
	ApplicationParameters parameters = parametersManager.getParameters();

	EntityFactory entityFactory;

	try
	{
		Executable executable = entityFactory.createExecutable(parameters.getExecutablePath());
		executable.execute();
	}
	catch (InvalidExecutablePathException exception) {
		std::cout << "Invalid executable path : " << std::endl << "\t - " << exception.getDescription() << std::endl;
	}

	return EXIT_SUCCESS;
}

#include <cstdlib>

#include "Application/Parameters/ApplicationParameters.h"
#include "Application/Parameters/ApplicationParametersBuilder.h"
#include "Application/Parameters/ApplicationParametersManager.h"
#include "Application/Parameters/ApplicationParametersReader.h"
#include "FileSystem/Entities/Executable.h"
#include "FileSystem/Factories/EntityFactory.h"
#include "FileSystem/Entities/Exceptions/InvalidExecutablePathException.h"
#include <memory>
#include <iostream>

using namespace clt::filesystem;
using namespace clt::filesystem::factories;
using namespace clt::filesystem::entities;
using namespace clt::filesystem::entities::exceptions;
using namespace application::parameters;

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

	ApplicationParametersManager parametersManager(std::make_unique<ApplicationParametersBuilder>(), std::make_unique<ApplicationParametersReader>());
	parametersManager.start(argc, argv);
	ApplicationParameters parameters = parametersManager.getParameters();

	EntityFactory entityFactory;

	try
	{
		Executable executable = entityFactory.createExecutable(parameters.getExecutablePath());
		executable.execute();
	}
	catch (InvalidExecutablePathException exception) {
		std::cout << "Invalid executable path : " << std::endl << "\t - " << exception.getDescription() << std::endl;
	}

	return EXIT_SUCCESS;
}

Remove test that have not to be here


#include <stan/prob/distributions/univariate/continuous/Cauchy.hpp>
#include <gtest/gtest.h>

TEST(stanProbDistributionsUnivariateContinuousCauchy,headerParses) {
  EXPECT_TRUE(true);
}

#include <stan/prob/distributions/univariate/continuous/cauchy.hpp>
#include <gtest/gtest.h>

TEST(stanProbDistributionsUnivariateContinuousCauchy,headerParses) {
  EXPECT_TRUE(true);
}

Fix case of cauchy.h header in test to allow to compile on Linux.


// Use RAII types

#include <map>
#include <memory>
#include <string>
#include <vector>

int main()
{
	std::vector<int> vec = {1, 2, 3, 4, 5};
	std::map<std::string, int> map = {{"Foo", 10}, {"Bar", 20}};
	std::string str = "Some text";
	std::unique_ptr<int> ptr1 = std::make_unique<int>(8);
	std::shared_ptr<int> ptr2 = std::make_shared<int>(16);
}

// Avoid manual memory management to improve safety and reduce bugs
// and memory leaks.
//
// Every object created on [10-14] will internally manage some
// dynamically allocated memory (allocated with the `new` keyword).
// They are all, however, implemented such that they deallocate that
// memory when they are destroyed. This practice is known as RAII.
//
// The user of these classes does not need to perform manual memory
// management, reducing the risk of memory leaks and other bugs. In
// fact, the use of `new` and `delete` can be avoided entirely by
// using these RAII types.
//
// Likewise, it is good practice to ensure your own classes also
// implement the RAII idiom with the
// [rule of three](/common-tasks/rule-of-three.html)
// or [rule of zero](/common-tasks/rule-of-zero.html).

// Use RAII types

#include <map>
#include <memory>
#include <string>
#include <vector>

int main()
{
	std::vector<int> vec = {1, 2, 3, 4, 5};
	std::map<std::string, int> map = {{"Foo", 10}, {"Bar", 20}};
	std::string str = "Some text";
	std::unique_ptr<int> ptr1 = std::make_unique<int>(8);
	std::shared_ptr<int> ptr2 = std::make_shared<int>(16);
}

// Avoid manual memory management to improve safety and reduce bugs
// and memory leaks.
//
// Every object created on [10-14] will internally manage some
// dynamically allocated memory (allocated with the `new` keyword).
// They are all, however, implemented such that they deallocate that
// memory when they are destroyed. This practice is known as RAII.
//
// The user of these classes does not need to perform manual memory
// management, reducing the risk of memory leaks and other bugs. In
// fact, the use of `new` and `delete` can be avoided entirely by
// using these RAII types.
//
// Likewise, it is good practice to ensure your own classes also
// implement the RAII idiom with the
// [rule of five](/common-tasks/rule-of-five.html)
// or [rule of zero](/common-tasks/rule-of-zero.html).

Fix link from "use RAII" to rule of five


#include "brents_fun.h"

using namespace std;

double fun1(double x)
{
  return -2.0*x+1;
}

double fun2(double x)
{
  return x*x-2.0*x-3;
}
void brents_fun_test()
{
     double eta=1e-8;
     double x;
     x=brents_fun(fun1,-1.0,5.0,eta);
     if(abs(x-0.5)<eta) cout<<"brents_fun passed quadratic order test!\n";
     else cout<<"Warning!!!!brents_fun failed quadratic order test!!\n";

     x=brents_fun(fun2,1.0,5.0,eta);
     if(abs(x-3.0)<eta) cout<<"brents_fun passed quadratic order test!\n";
     else cout<<"Warning!!!!brents_fun failed quadratic order test!!\n";

}

#include "brents_fun.h"

using namespace std;

double fun1(double x)
{
  return -2.0*x+1;
}

double fun2(double x)
{
  return x*x-2.0*x-3;
}

double fun3(double x,double y)
{
  return x*x-2.0*x-1.0-y;
}

void brents_fun_test()
{
     double eta=1e-8;
     double x;
     x=brents_fun(fun1,-1.0,5.0,eta);
     if(abs(x-0.5)<eta) cout<<"brents_fun passed quadratic order test!\n";
     else cout<<"Warning!!!!brents_fun failed quadratic order test!!\n";

     x=brents_fun(fun2,1.0,5.0,eta);
     if(abs(x-3.0)<eta) cout<<"brents_fun passed quadratic order test!\n";
     else cout<<"Warning!!!!brents_fun failed quadratic order test!!\n";

     x=brents_fun([](double x) { return fun3(x, 7.0); },0.0,5.0,eta);
     if(abs(x-4.0)<eta) cout<<"brents_fun passed partially function quadratic order test!\n";
     else cout<<"Warning!!!!brents_fun failed partially function quadratic order test!!\n";
}

Add one test (example) to use a lamba.


#include "AddChunksStage.h"

#include <globjects/globjects.h>

#include <gloperate/painter/AbstractCameraCapability.h>

using namespace gl;
using namespace glm;
using namespace globjects;

AddChunksStage::AddChunksStage()
:   AbstractStage("AddChunks")
{
    addInput("camera", camera);

    addOutput("chunksToAdd", chunksToAdd);
}

void AddChunksStage::initialize()
{

}

void AddChunksStage::process()
{
    std::queue<vec3> empty;
    std::swap(chunksToAdd.data(), empty);

    int directionMax = 8;
    int upMax = 3;
    int rightMax = 4;

    auto startPosition = camera.data()->eye();

    auto direction = normalize(camera.data()->center() - camera.data()->eye());
    auto up = normalize(camera.data()->up());
    auto right = normalize(cross(up, direction));

    for (int z = 0; z < directionMax; ++z)
    {
        for (int y = -upMax; y < upMax; ++y)
        {
            for (int x = -rightMax; x < rightMax; ++x)
            {
                auto newOffset = ivec3(startPosition + right * float(x) + up * float(y) + direction * float(z));

                chunksToAdd->push(vec3(newOffset));
            }
        }
    }

    invalidateOutputs();
}

#include "AddChunksStage.h"

#include <globjects/globjects.h>

#include <gloperate/painter/AbstractCameraCapability.h>

using namespace gl;
using namespace glm;
using namespace globjects;

AddChunksStage::AddChunksStage()
:   AbstractStage("AddChunks")
{
    addInput("camera", camera);

    addOutput("chunksToAdd", chunksToAdd);
}

void AddChunksStage::initialize()
{

}

void AddChunksStage::process()
{
    std::queue<vec3> empty;
    std::swap(chunksToAdd.data(), empty);

    int directionMax = 8;
    int upMax = 3;
    int rightMax = 4;

    auto startPosition = camera.data()->eye();

    auto direction = normalize(camera.data()->center() - camera.data()->eye());
    auto up = normalize(camera.data()->up());
    auto right = normalize(cross(up, direction));

    for (int z = 0; z < directionMax; ++z)
    {
        for (int y = -upMax; y < upMax; ++y)
        {
            for (int x = -rightMax; x < rightMax; ++x)
            {
                auto pos = startPosition + right * float(x) + up * float(y) + direction * float(z);
                auto newOffset = vec3(floor(pos.x), floor(pos.y), floor(pos.z));

                chunksToAdd->push(newOffset);
            }
        }
    }

    invalidateOutputs();
}

Fix rounding in chunk adding


#include <QtCore/QCoreApplication>
#include <QNetworkAccessManager>
#include <QTimer>
#include <QJSonDocument>
#include <QJsonObject>
#include <QDebug>

#include "../QPubNub.h"

int main(int argc, char *argv[]) {
    QCoreApplication a(argc, argv);

    QNetworkAccessManager networkAccessManager;

    QPubNub pubnub(&networkAccessManager);
    pubnub.connect(&pubnub, &QPubNub::trace, [](QString message) {
      qDebug() << "Trace:" << qPrintable(message);
    });
    pubnub.time();
    pubnub.setPublishKey("demo");
    pubnub.setSubscribeKey("demo");
    pubnub.connect(&pubnub, &QPubNub::error, [](QString message, int code) {
      qDebug() << "error:" << qPrintable(message);
    });
    pubnub.setCipherKey("enigma");
    pubnub.publish("qwertz", QJsonValue(QString("test")));
    pubnub.subscribe("qwertz");
    pubnub.connect(&pubnub, &QPubNub::message, [](QJsonValue value, QString timeToken, QString channel) {
      qDebug().nospace() << "[" << qPrintable(channel) << "]:" << value;
    });

    return a.exec();
}

#include <QtCore/QCoreApplication>
#include <QNetworkAccessManager>
#include <QTimer>
#include <QJSonDocument>
#include <QJsonObject>
#include <QDebug>

#include "../QPubNub.h"

int main(int argc, char *argv[]) {
    QCoreApplication a(argc, argv);

    QNetworkAccessManager networkAccessManager;

    QPubNub pubnub(&networkAccessManager);
    pubnub.connect(&pubnub, &QPubNub::trace, [](QString message) {
      qDebug() << "Trace:" << qPrintable(message);
    });
    pubnub.time();
    pubnub.setPublishKey("demo");
    pubnub.setSubscribeKey("demo");
    pubnub.connect(&pubnub, &QPubNub::error, [](QString message, int /* code */) {
      qDebug() << "error:" << qPrintable(message);
    });
    pubnub.setCipherKey("enigma");
    pubnub.publish("qwertz", QJsonValue(QString("test")));
    pubnub.subscribe("qwertz");
    pubnub.connect(&pubnub, &QPubNub::message, [](QJsonValue value, QString timeToken, QString channel) {
      qDebug().nospace() << "[" << qPrintable(channel) << "]:" << value;
    });

    return a.exec();
}

Fix warning for unreferenced parameter


// Test for the leak_check_at_exit flag.
// RUN: LSAN_BASE="use_stacks=0:use_registers=0"
// RUN: %clangxx_lsan %s -o %t
// RUN: LSAN_OPTIONS=$LSAN_BASE not %run %t foo 2>&1 | FileCheck %s --check-prefix=CHECK-do
// RUN: LSAN_OPTIONS=$LSAN_BASE not %run %t 2>&1 | FileCheck %s --check-prefix=CHECK-do
// RUN: LSAN_OPTIONS=$LSAN_BASE:"leak_check_at_exit=0" not %run %t foo 2>&1 | FileCheck %s --check-prefix=CHECK-do
// RUN: LSAN_OPTIONS=%LSAN_BASE:"leak_check_at_exit=0" %run %t 2>&1 | FileCheck %s --check-prefix=CHECK-dont

#include <stdio.h>
#include <stdlib.h>
#include <sanitizer/lsan_interface.h>

int main(int argc, char *argv[]) {
  fprintf(stderr, "Test alloc: %p.\n", malloc(1337));
  if (argc > 1)
    __lsan_do_leak_check();
  return 0;
}

// CHECK-do: SUMMARY: {{(Leak|Address)}}Sanitizer:
// CHECK-dont-NOT: SUMMARY: {{(Leak|Address)}}Sanitizer:

// Test for the leak_check_at_exit flag.
// RUN: LSAN_BASE="use_stacks=0:use_registers=0"
// RUN: %clangxx_lsan %s -o %t
// RUN: LSAN_OPTIONS=$LSAN_BASE not %run %t foo 2>&1 | FileCheck %s --check-prefix=CHECK-do
// RUN: LSAN_OPTIONS=$LSAN_BASE not %run %t 2>&1 | FileCheck %s --check-prefix=CHECK-do
// RUN: LSAN_OPTIONS=$LSAN_BASE:"leak_check_at_exit=0" not %run %t foo 2>&1 | FileCheck %s --check-prefix=CHECK-do
// RUN: LSAN_OPTIONS=$LSAN_BASE:"leak_check_at_exit=0" %run %t 2>&1 | FileCheck %s --check-prefix=CHECK-dont

#include <stdio.h>
#include <stdlib.h>
#include <sanitizer/lsan_interface.h>

int main(int argc, char *argv[]) {
  fprintf(stderr, "Test alloc: %p.\n", malloc(1337));
  if (argc > 1)
    __lsan_do_leak_check();
  return 0;
}

// CHECK-do: SUMMARY: {{(Leak|Address)}}Sanitizer:
// CHECK-dont-NOT: SUMMARY: {{(Leak|Address)}}Sanitizer:

Fix a typo in a test.


#include "TwoLevelDetection.h"
#include <opencv2/imgproc/imgproc.hpp>

void TwoLevelDetection(const cv::Mat& input, cv::Mat& output, double detectionLevel, double measurementLevel, TwoLevelDetectionTemp& temp)
{
    if (measurementLevel > detectionLevel) {
        throw std::runtime_error("TwoLevelDetection: it is required that measurementLevel <= detectionLevel");
    }

    cv::threshold(input, output, measurementLevel, 1, cv::THRESH_BINARY);

    temp.contours.clear();
    cv::findContours(output, temp.contours, cv::RETR_EXTERNAL, cv::CHAIN_APPROX_SIMPLE);

    temp.mask.create(input.size(), CV_8UC1);

    output.setTo(0);

    for (size_t i = 0, end = temp.contours.size(); i < end; ++i) {
        temp.mask.setTo(0);
        cv::drawContours(temp.mask, temp.contours, static_cast<int>(i), 255, -1);

        double minVal, maxVal;
        cv::minMaxIdx(input, &minVal, &maxVal, NULL, NULL, temp.mask);

        if (maxVal >= detectionLevel) {
            output.setTo(1, temp.mask);
        }
    }
}

#include "TwoLevelDetection.h"
#include <opencv2/imgproc/imgproc.hpp>

void TwoLevelDetection(const cv::Mat& input, cv::Mat& output, double detectionLevel, double measurementLevel, TwoLevelDetectionTemp& temp)
{
    if (measurementLevel > detectionLevel) {
        throw std::runtime_error("TwoLevelDetection: it is required that measurementLevel <= detectionLevel");
    }

    cv::threshold(input, output, measurementLevel, 1, cv::THRESH_BINARY);

    temp.contours.clear();
    cv::findContours(output, temp.contours, cv::RETR_EXTERNAL, cv::CHAIN_APPROX_SIMPLE);

    temp.mask.create(input.size(), CV_8UC1);

    output.setTo(0);

    for (size_t i = 0, end = temp.contours.size(); i < end; ++i) {
        temp.mask.setTo(0);
        cv::drawContours(temp.mask, temp.contours, static_cast<int>(i), 255, -1);

        double minVal, maxVal;
        cv::minMaxIdx(input, &minVal, &maxVal, NULL, NULL, temp.mask);

        if (maxVal >= detectionLevel) {
            output.setTo(std::numeric_limits<unsigned char>::max(), temp.mask);
        }
    }
}

Change two-level detection result output to 255 (was 1).


#include "cropview.hpp"

CropView::CropView(QGraphicsScene *scene) : QGraphicsView(scene) {
    setFrameShape(QFrame::NoFrame); // Time taken to solve: A george99g and 38 minutes.
    setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
    setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
    setWindowFlags(Qt::WindowStaysOnTopHint | Qt::FramelessWindowHint);
    setRenderHints(QPainter::Antialiasing | QPainter::SmoothPixmapTransform | QPainter::HighQualityAntialiasing);
    setCursor(QCursor(Qt::CrossCursor));
}

void CropView::keyPressEvent(QKeyEvent *e) {
    if (e->key() == Qt::Key_Escape) {
        close();
        e->accept();
        return;
    }
    QGraphicsView::keyPressEvent(e);
}

#include "cropview.hpp"

CropView::CropView(QGraphicsScene *scene) : QGraphicsView(scene) {
    setFrameShape(QFrame::NoFrame); // Time taken to solve: A george99g and 38 minutes.
    setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
    setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
    setWindowFlags(Qt::WindowStaysOnTopHint | Qt::FramelessWindowHint | Qt::X11BypassWindowManagerHint);
    setRenderHints(QPainter::Antialiasing | QPainter::SmoothPixmapTransform | QPainter::HighQualityAntialiasing);
    setCursor(QCursor(Qt::CrossCursor));
}

void CropView::keyPressEvent(QKeyEvent *e) {
    if (e->key() == Qt::Key_Escape) {
        close();
        e->accept();
        return;
    }
    QGraphicsView::keyPressEvent(e);
}

Fix an issue with possible minimizing of CropEditor by a WM


// Copyright (c) 2016-2018 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#include <wallet/test/wallet_test_fixture.h>

#include <rpc/server.h>
#include <wallet/db.h>
#include <wallet/wallet.h>

CWallet *pwalletMain;

WalletTestingSetup::WalletTestingSetup(const std::string& chainName):
    TestingSetup(chainName)
{
    bitdb.MakeMock();

    bool fFirstRun;
    std::unique_ptr<CWalletDBWrapper> dbw(new CWalletDBWrapper(&bitdb, "wallet_test.dat"));
    pwalletMain = new CWallet(std::move(dbw));
    pwalletMain->LoadWallet(fFirstRun);
    RegisterValidationInterface(pwalletMain);

    RegisterWalletRPCCommands(tableRPC);
}

WalletTestingSetup::~WalletTestingSetup()
{
    UnregisterValidationInterface(pwalletMain);
    delete pwalletMain;
    pwalletMain = nullptr;

    bitdb.Flush(true);
    bitdb.Reset();
}

// Copyright (c) 2016-2018 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#include <wallet/test/wallet_test_fixture.h>

#include <rpc/server.h>
#include <wallet/db.h>
#include <wallet/wallet.h>

std::unique_ptr<CWallet> pwalletMain;

WalletTestingSetup::WalletTestingSetup(const std::string& chainName):
    TestingSetup(chainName)
{
    bitdb.MakeMock();

    bool fFirstRun;
    std::unique_ptr<CWalletDBWrapper> dbw(new CWalletDBWrapper(&bitdb, "wallet_test.dat"));
    pwalletMain = std::unique_ptr<CWallet>(new CWallet(std::move(dbw)));
    pwalletMain->LoadWallet(fFirstRun);
    RegisterValidationInterface(pwalletMain.get());

    RegisterWalletRPCCommands(tableRPC);
}

WalletTestingSetup::~WalletTestingSetup()
{
    UnregisterValidationInterface(pwalletMain.get());
    pwalletMain.reset();

    bitdb.Flush(true);
    bitdb.Reset();
}

Use unique_ptr for pwalletMain (CWallet)


#define SYS_CLOCK_GETTIME 263
#include "linux_clock.cpp"

#ifdef BITS_64
#define SYS_CLOCK_GETTIME 113
#endif

#ifdef BITS_32
#define SYS_CLOCK_GETTIME 263
#endif

#include "linux_clock.cpp"

Fix a syscall number for 64-bit arm


#include "Halide.h"
#include <stdio.h>
#include <future>

using namespace Halide;

static std::atomic<int> foo;

int main(int argc, char **argv) {
    // Test if the compiler itself is thread-safe. This test is
    // intended to be run in a thread-sanitizer.
    std::vector<std::future<void>> futures;
    for (int i = 0; i < 1000; i++) {
        futures.emplace_back(std::async(std::launch::async, []{
            Func f;
            Var x;
            f(x) = x;
            f.realize(100);
        }));
    }

    for (auto &f : futures) {
        f.wait();
    }

    printf("Success!\n");

    return 0;
}

#include "Halide.h"
#include <stdio.h>
#include <thread>

using namespace Halide;

int main(int argc, char **argv) {
    // Test if the compiler itself is thread-safe. This test is
    // intended to be run in a thread-sanitizer.

    // std::thread has implementation-dependent behavior; some implementations
    // may refuse to create an arbitrary number. So let's create a smallish
    // number (8) and have each one do enough work that contention is likely
    // to be encountered.
    constexpr int total_iters = 1024;
    constexpr int num_threads = 8;

    std::vector<std::thread> threads;
    for (int i = 0; i < num_threads; i++) {
        threads.emplace_back([]{
            for (int i = 0; i < (total_iters / num_threads); i++) {
                Func f;
                Var x;
                f(x) = x;
                f.realize(100);
            }
        });
    }

    for (auto &t : threads) {
        t.join();
    }

    printf("Success!\n");

    return 0;
}

Use a pool of 8 threads.


#include "application.hpp"
#include <SDL2/SDL.h>
#include <stdexcept>

Application *Application::instance_ = nullptr;

Application::Application(int &argc, char **argv)
{
    if (instance_ != nullptr)
        throw std::runtime_error("The program can have only one instance of Application");
    instance_ = this;
    if (SDL_Init(SDL_INIT_EVERYTHING) != 0)
        throw std::runtime_error("SDL_Init Error: " + std::string(SDL_GetError()));
}

Application::~Application()
{
    SDL_Quit();
    instance_ = nullptr;
}

int Application::exec()
{
    bool done = false;
    while (!done)
    {
        SDL_Event e;
        while (SDL_PollEvent(&e))
        {
            switch (e.type)
            {
            case SDL_QUIT:
                done = true;
                break;
            }
        }
    }
    return 0;
}

Application *Application::instance()
{
    return instance_;
}

void Application::addWidget(Widget *)
{

}

void Application::removeWidget(Widget *)
{

}

#include "application.hpp"
#include <SDL2/SDL.h>
#include <stdexcept>
#include <string>

Application *Application::instance_ = nullptr;

Application::Application(int &argc, char **argv)
{
    if (instance_ != nullptr)
        throw std::runtime_error("The program can have only one instance of Application");
    instance_ = this;
    if (SDL_Init(SDL_INIT_EVERYTHING) != 0)
        throw std::runtime_error("SDL_Init Error: " + std::string(SDL_GetError()));
}

Application::~Application()
{
    SDL_Quit();
    instance_ = nullptr;
}

int Application::exec()
{
    bool done = false;
    while (!done)
    {
        SDL_Event e;
        while (SDL_PollEvent(&e))
        {
            switch (e.type)
            {
            case SDL_QUIT:
                done = true;
                break;
            }
        }
    }
    return 0;
}

Application *Application::instance()
{
    return instance_;
}

void Application::addWidget(Widget *)
{

}

void Application::removeWidget(Widget *)
{

}

Fix build for Mac OS X


#include "TestIODevice.hpp"

#include <iostream>

void TestIODevice::fakeWrite(const QByteArray& data)
{
    readStore.append(data);
    emit readyRead();
}

qint64 TestIODevice::readData(char* data, qint64 maxSize)
{
    auto readData = readStore.left(maxSize);
    //std::cerr << "Read " << readData.size() << " byte(s) from mock IO device, requested " << maxSize << std::endl;
    qstrcpy(data, readData.constData());
    if (readStore.size() == readData.size()) {
        readStore.clear();
    } else {
        readStore = readStore.right(readStore.size() - readData.size());
    }
    return readData.size();
}

qint64 TestIODevice::writeData(const char* data, qint64 maxSize)
{
    writeStore.append(data, maxSize);
    return maxSize;
}

#include "TestIODevice.hpp"

#include <iostream>
#include <cstring>

void TestIODevice::fakeWrite(const QByteArray& data)
{
    readStore.append(data);
    emit readyRead();
}

qint64 TestIODevice::readData(char* data, qint64 maxSize)
{
    auto readData = readStore.left(maxSize);
    //std::cerr << "Read " << readData.size() << " byte(s) from mock IO device, requested " << maxSize << std::endl;
    memcpy(data, readData.constData(), readData.size());
    if (readStore.size() == readData.size()) {
        readStore.clear();
    } else {
        readStore = readStore.right(readStore.size() - readData.size());
    }
    return readData.size();
}

qint64 TestIODevice::writeData(const char* data, qint64 maxSize)
{
    writeStore.append(data, maxSize);
    return maxSize;
}

Use memcpy, not qstrcpy, when copying data in the test device


#include "tests-base.hpp"

#include "helpers-casemapping.hpp"
#include "helpers-strings.hpp"

TEST(SpecialCasing, LithuanianRemoveDotAbove)
{
	// Remove DOT ABOVE after "i" with upper or titlecase

	// U+0049 U+0307
	// U+0069

	EXPECT_STREQ("lt-LT", setlocale(LC_ALL, "lt-LT"));
	EXPECT_CASEMAPPING_EQ("i\xCC\x87", "i\xCC\x87", "I", "I");
	setlocale(LC_ALL, "C");
}

#include "tests-base.hpp"

#include "helpers-casemapping.hpp"
#include "helpers-strings.hpp"

TEST(SpecialCasing, LithuanianRemoveDotAbove)
{
	EXPECT_STREQ("lt-LT", setlocale(LC_ALL, "lt-LT"));

	// Remove DOT ABOVE after "i" with upper or titlecase

	EXPECT_CASEMAPPING_EQ("i\xCC\x87", "i\xCC\x87", "I", "I"); // COMBINING DOT ABOVE

	setlocale(LC_ALL, "C");
}

TEST(SpecialCasing, LithuanianIntroduceExplicitDot)
{
	EXPECT_STREQ("lt-LT", setlocale(LC_ALL, "lt-LT"));

	// Introduce an explicit dot above when lowercasing capital I's and J's
	// whenever there are more accents above.
	// (of the accents used in Lithuanian: grave, acute, tilde above, and ogonek)

	EXPECT_CASEMAPPING_EQ("I", "i\xCC\x87", "I", "I"); // LATIN CAPITAL LETTER I
	EXPECT_CASEMAPPING_EQ("J", "j\xCC\x87", "J", "J"); // LATIN CAPITAL LETTER J
	EXPECT_CASEMAPPING_EQ("\xC4\xAE", "\xC4\xAF\xCC\x87", "\xC4\xAE", "\xC4\xAE"); // LATIN CAPITAL LETTER I WITH OGONEK
	EXPECT_CASEMAPPING_EQ("\xC3\x8C", "i\xCC\x87\xCC\x80", "\xC3\x8C", "\xC3\x8C"); // LATIN CAPITAL LETTER I WITH GRAVE
	EXPECT_CASEMAPPING_EQ("\xC3\x8D", "i\xCC\x87\xCC\x81", "\xC3\x8D", "\xC3\x8D"); // LATIN CAPITAL LETTER I WITH ACUTE
	EXPECT_CASEMAPPING_EQ("\xC4\xA8", "i\xCC\x87\xCC\x83", "\xC4\xA8", "\xC4\xA8"); // LATIN CAPITAL LETTER I WITH TILDE

	setlocale(LC_ALL, "C");
}

Add tests for Lithuanian special case mapping.


/*
 * Copyright 2011 Google Inc.
 *
 * Use of this source code is governed by a BSD-style license that can be
 * found in the LICENSE file.
 */

#include "SkColorMatrixFilter.h"

static SkScalar byte_to_scale(U8CPU byte) {
    if (0xFF == byte) {
        // want to get this exact
        return 1;
    } else {
        return byte * 0.00392156862745f;
    }
}

SkColorFilter* SkColorMatrixFilter::CreateLightingFilter(SkColor mul, SkColor add) {
    SkColorMatrix matrix;
    matrix.setScale(byte_to_scale(SkColorGetR(mul)),
                    byte_to_scale(SkColorGetG(mul)),
                    byte_to_scale(SkColorGetB(mul)),
                    1);
    matrix.postTranslate(SkIntToScalar(SkColorGetR(add)),
                         SkIntToScalar(SkColorGetG(add)),
                         SkIntToScalar(SkColorGetB(add)),
                         0);
    return SkColorMatrixFilter::Create(matrix);
}

/*
 * Copyright 2011 Google Inc.
 *
 * Use of this source code is governed by a BSD-style license that can be
 * found in the LICENSE file.
 */

#include "SkColorMatrixFilter.h"

static SkScalar byte_to_scale(U8CPU byte) {
    if (0xFF == byte) {
        // want to get this exact
        return 1;
    } else {
        return byte * 0.00392156862745f;
    }
}

SkColorFilter* SkColorMatrixFilter::CreateLightingFilter(SkColor mul, SkColor add) {
    if (0 == add) {
        return SkColorFilter::CreateModeFilter(mul | SK_ColorBLACK,
                                               SkXfermode::Mode::kModulate_Mode);
    }
    SkColorMatrix matrix;
    matrix.setScale(byte_to_scale(SkColorGetR(mul)),
                    byte_to_scale(SkColorGetG(mul)),
                    byte_to_scale(SkColorGetB(mul)),
                    1);
    matrix.postTranslate(SkIntToScalar(SkColorGetR(add)),
                         SkIntToScalar(SkColorGetG(add)),
                         SkIntToScalar(SkColorGetB(add)),
                         0);
    return SkColorMatrixFilter::Create(matrix);
}

Simplify LightingFilter in add-free case am: 0698300cc5 am: a184d5e49d


// RUN: %clang_cc1 -triple x86_64-unknown-unknown %s -O3 -emit-llvm -gline-tables-only -S -verify -o /dev/null
// REQUIRES: x86-registered-target

// Test verifies optimization failures generated by the backend are handled
// correctly by clang. LLVM tests verify all of the failure conditions.

void test_switch(int *A, int *B, int Length) {
#pragma clang loop vectorize(enable) unroll(disable)
  for (int i = 0; i < Length; i++) {
    /* expected-warning {{loop not vectorized: failed explicitly specified loop vectorization}} */ switch (A[i]) {
    case 0:
      B[i] = 1;
      break;
    case 1:
      B[i] = 2;
      break;
    default:
      B[i] = 3;
    }
  }
}

// RUN: %clang_cc1 -triple x86_64-unknown-unknown %s -O3 -emit-llvm -gline-tables-only -S -verify -o /dev/null
// REQUIRES: x86-registered-target

// Test verifies optimization failures generated by the backend are handled
// correctly by clang. LLVM tests verify all of the failure conditions.

void test_switch(int *A, int *B, int Length) {
#pragma clang loop vectorize(enable) unroll(disable)
  /* expected-warning {{loop not vectorized: failed explicitly specified loop vectorization}} */ for (int i = 0; i < Length; i++) {
    switch (A[i]) {
    case 0:
      B[i] = 1;
      break;
    case 1:
      B[i] = 2;
      break;
    default:
      B[i] = 3;
    }
  }
}

Adjust test to handle fallout from r217102.


#include "WindowsAPIs.h"
#include "TaskIcon.h"

INT WINAPI WinMain(HINSTANCE hinst, HINSTANCE, LPSTR, INT)
{
    hinstance = hinst;

    TaskIcon().MessageLoop();

    return 0;
}

#include "WindowsAPIs.h"
#include "TaskIcon.h"

INT WINAPI WinMain(HINSTANCE hinst, HINSTANCE, LPSTR, INT)
{
    hinstance = hinst;

    XInputEnable(TRUE);
    TaskIcon().MessageLoop();

    return 0;
}

Enable XINPUT right away maybe?


#include <SegmentList.hh>

#include "catch.hpp"

SCENARIO("Kernel heap allocator SegmentList", "[kernelheap]")
{
   GIVEN("A segment list")
   {
      SegmentList list;

      WHEN("The list is empty")
      {
         THEN("The count of the list is zero")
         {
            CHECK(list.count() == 0);
         }

         AND_WHEN("Creating an iterator")
         {
            auto i = list.getIterator();

            THEN("The iterator has no next item")
            {
               CHECK(i.hasNext() == false);
            }
         }
      }
   }
}

#include <SegmentList.hh>

#include "catch.hpp"

SCENARIO("Kernel heap allocator SegmentList", "[kernelheap]")
{
   GIVEN("A segment list")
   {
      SegmentList list;

      WHEN("The list is empty")
      {
         THEN("The count of the list is zero")
         {
            CHECK(list.count() == 0);
         }

         AND_WHEN("Creating an iterator")
         {
            auto i = list.getIterator();

            THEN("The iterator has no next item")
            {
               CHECK(i.hasNext() == false);
            }
         }
      }

      WHEN("An item is added")
      {
         Segment* s1 = new Segment();
         s1->setSize(1);

         list.add(s1);

         AND_WHEN("Creating an iterator")
         {
            auto i = list.getIterator();

            THEN("Iterator has a next item")
            {
               CHECK(i.hasNext() == true);

               AND_THEN("The next item is the item added")
               {
                  CHECK(&i.getNext() == s1);

                  AND_THEN("The iterator has no next item")
                  {
                     CHECK(i.hasNext() == false);
                  }
               }
            }
         }
      }

      WHEN("Three items are present")
      {
         Segment* s2 = new Segment();
         Segment* s3 = new Segment();

         s2->setSize(2);
         s3->setSize(3);

         list.add(s2);
         list.add(s3);
      }
   }
}

Add more tests for iteration


#include "main_action_planner_node.hpp"

int main(int argc, char** argv) {
  return 0;
}

#include "main_action_planner_node.hpp"

int main(int argc, char** argv) {
  ros::init(argc, argv, "main_action_planner_node");
  ros::NodeHandle nh("~");

  return 0;
}

Add minimum code to main func of MAP node.


#include "cg-operator-common.h"
#include <binpac/autogen/operators/function.h>

using namespace binpac;
using namespace binpac::codegen;

void CodeBuilder::visit(expression::operator_::function::Call* i)
{
    auto func = ast::checkedCast<expression::Function>(i->op1());
    auto args = callParameters(i->op2());

    shared_ptr<hilti::Expression> cookie = nullptr;

    if ( in<declaration::Function>() || in<declaration::Hook>() )
        cookie = hilti::builder::id::create("__cookie", i->location());
    else
        cookie = hilti::builder::reference::createNull(i->location());

    auto result = cg()->hiltiCall(func, args, cookie);
    setResult(result);
}

#include "cg-operator-common.h"
#include <binpac/autogen/operators/function.h>

using namespace binpac;
using namespace binpac::codegen;

void CodeBuilder::visit(expression::operator_::function::Call* i)
{
    auto func = ast::checkedCast<expression::Function>(i->op1());
    auto args = callParameters(i->op2());

    shared_ptr<hilti::Expression> cookie = nullptr;

    if ( in<declaration::Function>() || in<declaration::Hook>() || in<declaration::Type>() )
        cookie = hilti::builder::id::create("__cookie", i->location());
    else
        cookie = hilti::builder::reference::createNull(i->location());

    auto result = cg()->hiltiCall(func, args, cookie);
    setResult(result);
}

Fix for in-unit hooks not passing the cookie on to C.


#include <QtQuick>

#include <sailfishapp.h>
#include <QScopedPointer>
#include <QQuickView>
#include <QQmlEngine>
#include <QGuiApplication>

#include "factor.h"

int main(int argc, char *argv[])
{
    // For this example, wizard-generates single line code would be good enough,
    // but very soon it won't be enough for you anyway, so use this more detailed example from start
    QScopedPointer<QGuiApplication> app(SailfishApp::application(argc, argv));
    QScopedPointer<QQuickView> view(SailfishApp::createView());

    Factorizer fact;

    runUnitTests();

//    Here's how you will add QML components whenever you start using them
//    Check https://github.com/amarchen/Wikipedia for a more full example
//    view->engine()->addImportPath(SailfishApp::pathTo("qml/components").toString());
    view->engine()->rootContext()->setContextProperty("fact", &fact);
    view->setSource(SailfishApp::pathTo("qml/main.qml"));

    view->show();

    return app->exec();
}

#include <QtQuick>

#include <sailfishapp.h>
#include <QScopedPointer>
#include <QQuickView>
#include <QQmlEngine>
#include <QGuiApplication>

#include "factor.h"

int main(int argc, char *argv[])
{
    // For this example, wizard-generates single line code would be good enough,
    // but very soon it won't be enough for you anyway, so use this more detailed example from start
    QScopedPointer<QGuiApplication> app(SailfishApp::application(argc, argv));
    QScopedPointer<QQuickView> view(SailfishApp::createView());

    Factorizer fact;

    runUnitTests();

//    Here's how you will add QML components whenever you start using them
//    Check https://github.com/amarchen/Wikipedia for a more full example
//    view->engine()->addImportPath(SailfishApp::pathTo("qml/components").toString());
    view->engine()->rootContext()->setContextProperty("fact", &fact);
    view->setSource(SailfishApp::pathTo("qml/main.qml"));

    view->setTitle("Sailfactor");

    app->setApplicationName("harbour-sailfactor");
    app->setApplicationDisplayName("Sailfactor");

    view->show();

    return app->exec();
}

Set some names and titles just in case they are useful to set.


//===- IListIterator.cpp --------------------------------------------------===//
//
//                            The Bold Project
//
//  This file is distributed under the New BSD License.
//  See LICENSE for details.
//
//===----------------------------------------------------------------------===//
#include <bold/ADT/IListIterator.h>
#include <cassert>

using namespace bold;

//===----------------------------------------------------------------------===//
// IListIteratorBase
//===----------------------------------------------------------------------===//
IListIteratorBase::IListIteratorBase()
  : m_pNodePtr(NULL) {
}

IListIteratorBase::IListIteratorBase(NodeBase* pNode)
  : m_pNodePtr(pNode) {
}

void IListIteratorBase::advance()
{
  assert(NULL != m_pNodePtr && "trivial iterator can not advance");
  m_pNodePtr = m_pNodePtr->getNext();
}

void IListIteratorBase::retreat()
{
  assert(NULL != m_pNodePtr && "trivial iterator can not retreat");
  m_pNodePtr = m_pNodePtr->getPrev();
}

//===- IListIterator.cpp --------------------------------------------------===//
//
//                            The Bold Project
//
//  This file is distributed under the New BSD License.
//  See LICENSE for details.
//
//===----------------------------------------------------------------------===//
#include <bold/ADT/IListIterator.h>
#include <cassert>

using namespace bold;

//===----------------------------------------------------------------------===//
// IListIteratorBase
//===----------------------------------------------------------------------===//
IListIteratorBase::IListIteratorBase()
  : m_pNodePtr(NULL) {
}

IListIteratorBase::IListIteratorBase(IListNodeBase* pNode)
  : m_pNodePtr(pNode) {
}

void IListIteratorBase::advance()
{
  assert(NULL != m_pNodePtr && "trivial iterator can not advance");
  m_pNodePtr = m_pNodePtr->getNext();
}

void IListIteratorBase::retreat()
{
  assert(NULL != m_pNodePtr && "trivial iterator can not retreat");
  m_pNodePtr = m_pNodePtr->getPrev();
}

Use IListNodeBase instead of type redefinition.


#include <boost/python.hpp>

#include "mue_algorithm.h"
#include "teams.h"
#include "distances.h"
#include "seen_table.h"

char const * peng() {
	return mue::peng().c_str();
}

BOOST_PYTHON_MODULE (_pymue)
{
	using namespace boost::python;

	def ("peng", peng);

	class_<mue::Team>("Team", init<int>())
		.def("id", &mue::Team::id);

	class_<mue::Distance_matrix>("DistanceMatrix", init<int>())
		.def("set_cost", &mue::Distance_matrix::set_cost)
		.def("lookup", &mue::Distance_matrix::lookup);

	class_<mue::Seen_table>("SeenTable", init<int>())
		.def("clone", &mue::Seen_table::clone)
		.def("generation", &mue::Seen_table::generation)
		.def("seen", &mue::Seen_table::seen)
		.def("add_meeting", &mue::Seen_table::add_meeting);
}

#include <boost/python.hpp>

#include "mue_algorithm.h"
#include "teams.h"
#include "distances.h"

#include "seen_table_wrapper.h"

char const * peng() {
	return mue::peng().c_str();
}

BOOST_PYTHON_MODULE (_pymue)
{
	using namespace boost::python;

	def ("peng", peng);

	class_<mue::Team>("Team", init<int>())
		.def("id", &mue::Team::id);

	class_<mue::Distance_matrix>("DistanceMatrix", init<int>())
		.def("set_cost", &mue::Distance_matrix::set_cost)
		.def("lookup", &mue::Distance_matrix::lookup);

	class_<pymue::Seen_table_wrapper>("SeenTable", init<int>())
		.def("clone", &pymue::Seen_table_wrapper::clone)
		.def("generation", &pymue::Seen_table_wrapper::generation)
		.def("seen", &pymue::Seen_table_wrapper::seen)
		.def("add_meeting", &pymue::Seen_table_wrapper::add_meeting);
}

Replace Seen_table with Seen_table_wrapper in the binding


//===----------------------------------------------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
//
// UNSUPPORTED: libcpp-has-no-threads

// <mutex>

// class mutex;

// void lock();

#include <mutex>
#include <thread>
#include <cstdlib>
#include <cassert>

#include <iostream>

std::mutex m;

typedef std::chrono::system_clock Clock;
typedef Clock::time_point time_point;
typedef Clock::duration duration;
typedef std::chrono::milliseconds ms;
typedef std::chrono::nanoseconds ns;

void f()
{
    time_point t0 = Clock::now();
    m.lock();
    time_point t1 = Clock::now();
    m.unlock();
    ns d = t1 - t0 - ms(250);
    assert(d < ms(50));  // within 50ms
}

int main()
{
    m.lock();
    std::thread t(f);
    std::this_thread::sleep_for(ms(250));
    m.unlock();
    t.join();
}

//===----------------------------------------------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
//
// UNSUPPORTED: libcpp-has-no-threads

// FLAKY_TEST.

// <mutex>

// class mutex;

// void lock();

#include <mutex>
#include <thread>
#include <cstdlib>
#include <cassert>

#include <iostream>

std::mutex m;

typedef std::chrono::system_clock Clock;
typedef Clock::time_point time_point;
typedef Clock::duration duration;
typedef std::chrono::milliseconds ms;
typedef std::chrono::nanoseconds ns;

void f()
{
    time_point t0 = Clock::now();
    m.lock();
    time_point t1 = Clock::now();
    m.unlock();
    ns d = t1 - t0 - ms(250);
    assert(d < ms(50));  // within 50ms
}

int main()
{
    m.lock();
    std::thread t(f);
    std::this_thread::sleep_for(ms(250));
    m.unlock();
    t.join();
}

Mark another test as flaky


/**********************************************************************
 *
 * GEOS - Geometry Engine Open Source
 * http://geos.refractions.net
 *
 * Copyright (C) 2001-2002 Vivid Solutions Inc.
 *
 * This is free software; you can redistribute and/or modify it under
 * the terms of the GNU Lesser General Public Licence as published
 * by the Free Software Foundation.
 * See the COPYING file for more information.
 *
 **********************************************************************/

#include <geos/geom/Coordinate.h>
#include <geos/platform.h> // for ISNAN

#include <sstream>
#include <string>

#ifndef GEOS_INLINE
# include <geos/geom/Coordinate.inl>
#endif

using namespace std;

namespace geos {
namespace geom { // geos::geom

Coordinate Coordinate::nullCoord=Coordinate(DoubleNotANumber,DoubleNotANumber,DoubleNotANumber);

Coordinate&
Coordinate::getNull()
{
	return nullCoord;
}

string
Coordinate::toString() const
{
	ostringstream s;
	s<<*this;
	return s.str();
}

std::ostream& operator<< (std::ostream& os, const Coordinate& c)
{
	if ( ISNAN(c.z) )
	{
		os << c.x << " " << c.y;
	} else {
		os << c.x << " " << c.y << " " << c.z;
	}
	return os;
}

} // namespace geos::geom
} // namespace geos

/**********************************************************************
 *
 * GEOS - Geometry Engine Open Source
 * http://geos.refractions.net
 *
 * Copyright (C) 2001-2002 Vivid Solutions Inc.
 *
 * This is free software; you can redistribute and/or modify it under
 * the terms of the GNU Lesser General Public Licence as published
 * by the Free Software Foundation.
 * See the COPYING file for more information.
 *
 **********************************************************************/

#include <geos/geom/Coordinate.h>
#include <geos/platform.h> // for ISNAN

#include <sstream>
#include <string>
#include <iomanip>

#ifndef GEOS_INLINE
# include <geos/geom/Coordinate.inl>
#endif

using namespace std;

namespace geos {
namespace geom { // geos::geom

Coordinate Coordinate::nullCoord=Coordinate(DoubleNotANumber,DoubleNotANumber,DoubleNotANumber);

Coordinate&
Coordinate::getNull()
{
	return nullCoord;
}

string
Coordinate::toString() const
{
	ostringstream s;
	s << std::setprecision(17) << *this;
	return s.str();
}

std::ostream& operator<< (std::ostream& os, const Coordinate& c)
{
	if ( ISNAN(c.z) )
	{
		os << c.x << " " << c.y;
	} else {
		os << c.x << " " << c.y << " " << c.z;
	}
	return os;
}

} // namespace geos::geom
} // namespace geos

Use 18 significant digits for TopologyException point coordinates


#include "insertion.hpp"
#include "swap.hpp"

void insertion(int *data, const int size_of_data)
{
    for(int i = 0; i < size_of_data; ++i)
    {
        int j;
        for(j = i; j >= 0 && data[j] < data[i]; --j);
        swap(data[i], data[j]);
    }
}

#include "insertion.hpp"
#include "swap.hpp"

void insertion(int *data, const int size_of_data)
{
    for(int i = 0; i < size_of_data; ++i)
    {
        for(int j = i; j > 0 && data[j] < data[j - 1]; --j) swap(data[j], data[j - 1]);
    }
}

Fix the logic of Insertion sort which is not working


#include <Bull/Core/Exception/RuntimeError.hpp>

#include <Bull/Render/Buffer/VertexArrayObject.hpp>
#include <Bull/Render/OpenGL.hpp>

namespace Bull
{
    VertexArrayObject::VertexArrayObject() :
        m_vao(0)
    {
        gl::genVertexArrays(1, &m_vao);

        if(!gl::isVertexArray(m_vao))
        {
            throw RuntimeError("Failed to create VAO");
        }
    }

    VertexArrayObject::~VertexArrayObject()
    {
        gl::deleteVertexArrays(1, &m_vao);
    }

    void VertexArrayObject::runBound(const Functor<void>& functor) const
    {
        gl::bindVertexArray(m_vao);
        functor();
        gl::bindVertexArray(0);
    }
}

#include <Bull/Core/Exception/RuntimeError.hpp>

#include <Bull/Render/Buffer/VertexArrayObject.hpp>
#include <Bull/Render/OpenGL.hpp>

namespace Bull
{
    VertexArrayObject::VertexArrayObject() :
        m_vao(0)
    {
        gl::genVertexArrays(1, &m_vao);

        if(!m_vao)
        {
            throw RuntimeError("Failed to create VAO");
        }
    }

    VertexArrayObject::~VertexArrayObject()
    {
        gl::deleteVertexArrays(1, &m_vao);
    }

    void VertexArrayObject::runBound(const Functor<void>& functor) const
    {
        gl::bindVertexArray(m_vao);
        functor();
        gl::bindVertexArray(0);
    }
}

Rename creation method to avoid ambiguity with resource loading


// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "../client/gles2_lib.h"
#include "../common/thread_local.h"

namespace gles2 {
namespace {
gpu::ThreadLocalKey g_gl_context_key;
}  // namespace anonymous

void Initialize() {
  g_gl_context_key = gpu::ThreadLocalAlloc();
}

void Terminate() {
  gpu::ThreadLocalFree(g_gl_context_key);
  g_gl_context_key = 0;
}

gpu::gles2::GLES2Implementation* GetGLContext() {
  return static_cast<gpu::gles2::GLES2Implementation*>(
    gpu::ThreadLocalGetValue(g_gl_context_key));
}

void SetGLContext(gpu::gles2::GLES2Implementation* context) {
  gpu::ThreadLocalSetValue(g_gl_context_key, context);
}
}  // namespace gles2

// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "../client/gles2_lib.h"
#include "../common/thread_local.h"

namespace gles2 {
// TODO(kbr): the use of this anonymous namespace core dumps the
// linker on Mac OS X 10.6 when the symbol ordering file is used
// namespace {
static gpu::ThreadLocalKey g_gl_context_key;
// }  // namespace anonymous

void Initialize() {
  g_gl_context_key = gpu::ThreadLocalAlloc();
}

void Terminate() {
  gpu::ThreadLocalFree(g_gl_context_key);
  g_gl_context_key = 0;
}

gpu::gles2::GLES2Implementation* GetGLContext() {
  return static_cast<gpu::gles2::GLES2Implementation*>(
    gpu::ThreadLocalGetValue(g_gl_context_key));
}

void SetGLContext(gpu::gles2::GLES2Implementation* context) {
  gpu::ThreadLocalSetValue(g_gl_context_key, context);
}
}  // namespace gles2

Work around bug in gcc's name mangling causing linker to crash on Mac OS X.


// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "base/command_line.h"
#include "chrome/browser/extensions/extension_apitest.h"
#include "chrome/common/chrome_switches.h"

// Flaky, http://crbug.com/46601.
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, FLAKY_Popup) {
  CommandLine::ForCurrentProcess()->AppendSwitch(
      switches::kEnableExperimentalExtensionApis);

  ASSERT_TRUE(RunExtensionTest("popup/popup_main")) << message_;
}

IN_PROC_BROWSER_TEST_F(ExtensionApiTest, PopupFromInfobar) {
  CommandLine::ForCurrentProcess()->AppendSwitch(
    switches::kEnableExperimentalExtensionApis);

  ASSERT_TRUE(RunExtensionTest("popup/popup_from_infobar")) << message_;
}

// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "base/command_line.h"
#include "chrome/browser/extensions/extension_apitest.h"
#include "chrome/common/chrome_switches.h"

// Times out. See http://crbug.com/46601.
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, DISABLED_Popup) {
  CommandLine::ForCurrentProcess()->AppendSwitch(
      switches::kEnableExperimentalExtensionApis);

  ASSERT_TRUE(RunExtensionTest("popup/popup_main")) << message_;
}

IN_PROC_BROWSER_TEST_F(ExtensionApiTest, PopupFromInfobar) {
  CommandLine::ForCurrentProcess()->AppendSwitch(
    switches::kEnableExperimentalExtensionApis);

  ASSERT_TRUE(RunExtensionTest("popup/popup_from_infobar")) << message_;
}

Disable ExtensionApiTest.Popup. It's been timing out for the last 750+ runs.


#include "stdafx.h"
#include <string>
#include "Logger.h"

#ifdef _WIN64
#define PYTHONPATH L"python-embed-amd64"
#else
#define PYTHONPATH L"python-embed-win32"
#endif

EXTERN_C IMAGE_DOS_HEADER __ImageBase;

std::wstring getPythonPath()
{
    // https://stackoverflow.com/questions/6924195/get-dll-path-at-runtime
    WCHAR DllPath[MAX_PATH] = { 0 };
    if (GetModuleFileNameW((HINSTANCE)&__ImageBase, DllPath, _countof(DllPath)) == 0)
    {
        LOG_ERROR("Error getting Pythia DLL path");
        return L"";
    }
    std::wstring DllPath_s = DllPath;

    std::wstring directory;
    const size_t last_slash_idx = DllPath_s.rfind(L'\\');
    if (std::string::npos != last_slash_idx)
    {
        directory = DllPath_s.substr(0, last_slash_idx);
    }

    std::wstring pythonPath = directory + L"\\" + PYTHONPATH;
    return pythonPath;
}

#include "stdafx.h"
#include <string>
#include "Logger.h"

#ifdef _WIN64
#define EMBEDDEDPYTHONPATH L"python-embed-amd64"
#else
#define EMBEDDEDPYTHONPATH L"python-embed-win32"
#endif

EXTERN_C IMAGE_DOS_HEADER __ImageBase;

std::wstring getPythonPath()
{
    // https://stackoverflow.com/questions/6924195/get-dll-path-at-runtime
    WCHAR DllPath[MAX_PATH] = { 0 };
    if (GetModuleFileNameW((HINSTANCE)&__ImageBase, DllPath, _countof(DllPath)) == 0)
    {
        LOG_ERROR("Error getting Pythia DLL path");
        return L"";
    }
    std::wstring DllPath_s = DllPath;

    std::wstring directory;
    const size_t last_slash_idx = DllPath_s.rfind(L'\\');
    if (std::string::npos != last_slash_idx)
    {
        directory = DllPath_s.substr(0, last_slash_idx);
    }

    std::wstring pythonPath = directory + L"\\" + EMBEDDEDPYTHONPATH;
    return pythonPath;
}

Change define name to prevent name clashes with the python interpreter


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

#include <unistd.h>

namespace asylo {

extern "C" {

int __asylo_handle_signal(const char *input, size_t input_len) {
  return 0;
}

int __asylo_take_snapshot(char **output, size_t *output_len) {
  return 0;
}

int __asylo_restore(const char *snapshot_layout, size_t snapshot_layout_len,
                    char **output, size_t *output_len) {
  return 0;
}

int __asylo_transfer_secure_snapshot_key(const char *input, size_t input_len,
                                         char **output, size_t *output_len) {
  return 0;
}

}  // extern "C"

}  // namespace asylo

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

#include <unistd.h>

namespace asylo {

extern "C" {

int __asylo_take_snapshot(char **output, size_t *output_len) {
  return 0;
}

int __asylo_restore(const char *snapshot_layout, size_t snapshot_layout_len,
                    char **output, size_t *output_len) {
  return 0;
}

int __asylo_transfer_secure_snapshot_key(const char *input, size_t input_len,
                                         char **output, size_t *output_len) {
  return 0;
}

}  // extern "C"

}  // namespace asylo

Revert dummy handle signal definition


#include "stdafx.h"
#include "CppUnitTest.h"
#include "../DNAnalyzerServer/Dictionnaire.h"
#include <exception>
#include <cstring>

using namespace Microsoft::VisualStudio::CppUnitTestFramework;

namespace DNAnalyzerServerTest
{
	TEST_CLASS(DictionnaireTest)
	{
	public:
		//ObtenirInstance
		TEST_METHOD(ObtenirInstance_NotNull)
		{
			// L'instance retourne ne doit pas tre null
			Assert::IsTrue(&(Dictionnaire::ObtenirInstance())!=(Dictionnaire*) nullptr);
		}

		TEST_METHOD(ObtenirInstance_SameReference)
		{
			// L'instance retourne doit toujours tre la mme
			Assert::IsTrue(&(Dictionnaire::ObtenirInstance()) == &(Dictionnaire::ObtenirInstance()));
		}
	};
}

#include "stdafx.h"
#include "CppUnitTest.h"
#include "../DNAnalyzerServer/Dictionnaire.h"
#include "../DNAnalyzerServer/Mots.h"
#include <exception>
#include <unordered_set>
#include <cstring>
#include <string>

using namespace Microsoft::VisualStudio::CppUnitTestFramework;

namespace DNAnalyzerServerTest
{
	TEST_CLASS(DictionnaireTest)
	{
	public:
		//ObtenirInstance
		TEST_METHOD(ObtenirInstance_NotNull)
		{
			// L'instance retourne ne doit pas tre null
			Assert::IsTrue(&(Dictionnaire::ObtenirInstance())!=(Dictionnaire*) nullptr);
		}

		TEST_METHOD(ObtenirInstance_SameReference)
		{
			// L'instance retourne doit toujours tre la mme
			Assert::IsTrue(&(Dictionnaire::ObtenirInstance()) == &(Dictionnaire::ObtenirInstance()));
		}
		TEST_METHOD(ObtenirMaladie_KnownMaladie) {

		}
		TEST_METHOD(ObtenirMaladie_UnKnownMaladie) {

		}
		TEST_METHOD(ObtenirMaladies_NoMaladies) {
			char motInexistant[] = "ATCGINEXISTANT";
			unsigned int indexMotInexistant = Mots::ObtenirInstance().InsererMot(motInexistant);
			const unordered_set<const Maladie*> resutat = Dictionnaire::ObtenirInstance().ObtenirMaladies(indexMotInexistant);
			Assert::AreEqual(resutat.size, 0);
		}
		TEST_METHOD(ObtenirMaladies_OneMaladies) {

		}
		TEST_METHOD(ObtenirMaladies_TwoMaladies) {

		}
		TEST_METHOD(ObtenirNomMaladies_EmptyDictionnaire) {

		}
		TEST_METHOD(ObtenirNomMaladies_NotEmptyDictionnaire) {

		}
	};
}

Revert "Revert "Ajout de methode de test (incomplete) de Dictionnaire""


#include <string>
#include <vector>
#include <unistd.h>
#include <gtest/gtest.h>
#include <scxcorelib/scxstrencodingconv.h>
#include "getusername.h"

TEST(GetUserName,simple)
{
	// allocate a WCHAR_T buffer to receive username
	DWORD lpnSize = L_cuserid;
	WCHAR_T lpBuffer[lpnSize];

	BOOL result = GetUserName(lpBuffer, &lpnSize);

	// GetUserName returns 1 on success
	ASSERT_EQ(1, result);

	// get expected username
	std::string username(getlogin());

	// GetUserName sets lpnSize to length of username including null
	ASSERT_EQ(username.size()+1, lpnSize);

	// copy UTF-16 bytes (excluding null) from lpBuffer to vector for conversion
	unsigned char *begin = reinterpret_cast<unsigned char *>(&lpBuffer[0]);
	// -1 to skip null; *2 because UTF-16 encodes two bytes per character
	unsigned char *end = begin + (lpnSize-1)*2;
	std::vector<unsigned char> input(begin, end);
	// convert to UTF-8 for assertion
	std::string output;
	SCXCoreLib::Utf16leToUtf8(input, output);

	EXPECT_EQ(username, output);
}

#include <string>
#include <vector>
#include <unistd.h>
#include <gtest/gtest.h>
#include <scxcorelib/scxstrencodingconv.h>
#include "getusername.h"

class GetUserNameTest : public ::testing::Test {
protected:
	DWORD lpnSize;
	std::vector<WCHAR_T> lpBuffer;
	BOOL result;
	std::string userName;

	GetUserNameTest(): userName(std::string(getlogin())) {}

	void GetUserNameWithSize(DWORD size) {
		lpnSize = size;
		// allocate a WCHAR_T buffer to receive username
		lpBuffer.assign(lpnSize, '\0');
		result = GetUserName(&lpBuffer[0], &lpnSize);
	}
};

TEST_F(GetUserNameTest, NormalUse) {
	GetUserNameWithSize(L_cuserid);

	// GetUserName returns 1 on success
	ASSERT_EQ(1, result);

	// GetUserName sets lpnSize to length of username including null
	ASSERT_EQ(userName.size()+1, lpnSize);

	// copy UTF-16 bytes (excluding null) from lpBuffer to vector for conversion
	unsigned char *begin = reinterpret_cast<unsigned char *>(&lpBuffer[0]);
	// -1 to skip null; *2 because UTF-16 encodes two bytes per character
	unsigned char *end = begin + (lpnSize-1)*2;
	std::vector<unsigned char> input(begin, end);
	// convert to UTF-8 for assertion
	std::string output;
	SCXCoreLib::Utf16leToUtf8(input, output);

	EXPECT_EQ(userName, output);
}

Use test fixture in GetUserName unit tests


#include "textfile.ih"

vector<unsigned char> indexedcorpus::readFile(string const &filename)
{
	QFileInfo p(filename.c_str());
	if (p.isFile())
          throw runtime_error(string("readFile: '") + filename + "' is not a regular file!");

	vector<unsigned char> data;

	ifstream dataStream(filename.c_str());
	if (!dataStream)
          throw runtime_error(string("readFile: '") + filename + "' could be read!");

	dataStream >> noskipws;

	copy(istream_iterator<char>(dataStream), istream_iterator<char>(),
		back_inserter(data));

	return data;
}

#include "textfile.ih"

vector<unsigned char> indexedcorpus::readFile(string const &filename)
{
	QFileInfo p(filename.c_str());
	if (!p.isFile())
          throw runtime_error(string("readFile: '") + filename + "' is not a regular file!");

	vector<unsigned char> data;

	ifstream dataStream(filename.c_str());
	if (!dataStream)
          throw runtime_error(string("readFile: '") + filename + "' could be read!");

	dataStream >> noskipws;

	copy(istream_iterator<char>(dataStream), istream_iterator<char>(),
		back_inserter(data));

	return data;
}

Fix a flawed check in indexedcorpus::readFile.


/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.
 * Use of this file is governed by the BSD 3-clause license that
 * can be found in the LICENSE.txt file in the project root.
 */

#include "Exceptions.h"

using namespace antlr4;

RuntimeException::RuntimeException(const std::string &msg) : std::exception(), _message(msg) {
}

const char* RuntimeException::what() const NOEXCEPT {
  return _message.c_str();
}

//------------------ IOException ---------------------------------------------------------------------------------------

IOException::IOException(const std::string &msg) : std::exception(), _message(msg) {
}

const char* IOException::what() const NOEXCEPT {
  return _message.c_str();
}

IllegalStateException::~IllegalStateException() = default;
IllegalArgumentException::~IllegalArgumentException() = default;
NullPointerException::~NullPointerException() = default;
IndexOutOfBoundsException::~IndexOutOfBoundsException() = default;
UnsupportedOperationException::~UnsupportedOperationException() = default;
EmptyStackException::~EmptyStackException() = default;
CancellationException::~CancellationException() = default;
ParseCancellationException::~ParseCancellationException() = default;

Change virtual dtor to empty bodies


// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "base/command_line.h"
#include "chrome/browser/extensions/extension_apitest.h"
#include "chrome/common/chrome_switches.h"

IN_PROC_BROWSER_TEST_F(ExtensionApiTest, Popup) {
  CommandLine::ForCurrentProcess()->AppendSwitch(
      switches::kEnableExperimentalExtensionApis);

  ASSERT_TRUE(RunExtensionTest("popup")) << message_;
}

// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "base/command_line.h"
#include "chrome/browser/extensions/extension_apitest.h"
#include "chrome/common/chrome_switches.h"

// Flaky, http://crbug.com/46601.
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, FLAKY_Popup) {
  CommandLine::ForCurrentProcess()->AppendSwitch(
      switches::kEnableExperimentalExtensionApis);

  ASSERT_TRUE(RunExtensionTest("popup")) << message_;
}

Mark ExtensionApiTest.Popup as FLAKY, it is still flaky.


/*
 *  Copyright (c) 2013 The WebRTC project authors. All Rights Reserved.
 *
 *  Use of this source code is governed by a BSD-style license
 *  that can be found in the LICENSE file in the root of the source
 *  tree. An additional intellectual property rights grant can be found
 *  in the file PATENTS.  All contributing project authors may
 *  be found in the AUTHORS file in the root of the source tree.
 */

#include <memory>

#include "absl/debugging/failure_signal_handler.h"
#include "absl/debugging/symbolize.h"
#include "test/test_main_lib.h"

int main(int argc, char* argv[]) {
  // Initialize the symbolizer to get a human-readable stack trace
  absl::InitializeSymbolizer(argv[0]);

  absl::FailureSignalHandlerOptions options;
  absl::InstallFailureSignalHandler(options);

  std::unique_ptr<webrtc::TestMain> main = webrtc::TestMain::Create();
  int err_code = main->Init(&argc, argv);
  if (err_code != 0) {
    return err_code;
  }
  return main->Run(argc, argv);
}

/*
 *  Copyright (c) 2013 The WebRTC project authors. All Rights Reserved.
 *
 *  Use of this source code is governed by a BSD-style license
 *  that can be found in the LICENSE file in the root of the source
 *  tree. An additional intellectual property rights grant can be found
 *  in the file PATENTS.  All contributing project authors may
 *  be found in the AUTHORS file in the root of the source tree.
 */

#include <memory>

#include "absl/debugging/failure_signal_handler.h"
#include "absl/debugging/symbolize.h"
#include "test/test_main_lib.h"

int main(int argc, char* argv[]) {
  // Initialize the symbolizer to get a human-readable stack trace
  // TODO(crbug.com/1050976): Breaks iossim tests, re-enable when fixed.
  // absl::InitializeSymbolizer(argv[0]);

  // absl::FailureSignalHandlerOptions options;
  // absl::InstallFailureSignalHandler(options);

  std::unique_ptr<webrtc::TestMain> main = webrtc::TestMain::Create();
  int err_code = main->Init(&argc, argv);
  if (err_code != 0) {
    return err_code;
  }
  return main->Run(argc, argv);
}

Revert "Re-enable absl FailureSignalHandler in tests."


#include "DotGraphOutput.hh"
#include "EdgeType.hh"

string getEdgeStyle(EdgeType t) {
  switch (t) {
  case EdgeType::Plane:
    return "[color=red]";
  case EdgeType::Train:
    return "[color=blue,style=dotted]";
  default:
    return "";
  }
}

template <typename V>
void DotGraphOutput<V>::output(string path) {

  cout << "Exporting " << this->graph_.name() << " to " << path << endl;

  ofstream st(path, ofstream::out);

  st << "digraph " << this->graph_.name() << " {" << endl;

  for (unsigned int i = 0; i < this->graph_.verticesNb(); i++)
    for (auto e : this->graph_.outgoingEdges(i)) {
      st << "\t" << i
	 << " -> " << e->getOtherEnd(i)
	 << " " << getEdgeStyle(e->type())
	 << ";" << endl;
    }

  st << "}" << endl;

  st.close();
}

template class DotGraphOutput<double>;

#include "DotGraphOutput.hh"
#include "EdgeType.hh"

string getEdgeStyle(EdgeType t) {
  switch (t) {
  case EdgeType::Plane:
    return "[color=red]";
  case EdgeType::Train:
    return "[color=blue,style=dotted]";
  default:
    return "";
  }
}

template <typename V>
void DotGraphOutput<V>::output(string path) {

  cout << "Exporting " << this->graph_.name() << " to " << path << endl;

  ofstream st(path, ofstream::out);

  st << "digraph " << this->graph_.name() << " {" << endl;

  for (unsigned int i = 0; i < this->graph_.verticesNb(); i++)
    for (auto e : this->graph_.outgoingEdges(i)) {
      st << "\t" << this->graph_.getVertex(i).name()
	 << " -> " << this->graph_.getVertex(e->getOtherEnd(i)).name()
	 << " " << getEdgeStyle(e->type())
	 << ";" << endl;
    }

  st << "}" << endl;

  st.close();
}

template class DotGraphOutput<double>;

Add the nodes name to the dot output


#include "cpr/timeout.h"

#include <limits>
#include <stdexcept>
#include <string>
#include <type_traits>

namespace cpr {

long Timeout::Milliseconds() const {
    static_assert(std::is_same<std::chrono::milliseconds, decltype(ms)>::value,
                  "Following casting expects milliseconds.");

    if (ms.count() > std::numeric_limits<long>::max()) {
        throw std::overflow_error("cpr::Timeout: timeout value overflow: " +
                                  std::to_string(ms.count()) + " ms.");
    }
    if (ms.count() < std::numeric_limits<long>::min()) {
        throw std::underflow_error("cpr::Timeout: timeout value underflow: " +
                                   std::to_string(ms.count()) + " ms.");
    }

    return ms.count();
}

} // namespace cpr

#include "cpr/timeout.h"

#include <limits>
#include <stdexcept>
#include <string>
#include <type_traits>

namespace cpr {

long Timeout::Milliseconds() const {
    static_assert(std::is_same<std::chrono::milliseconds, decltype(ms)>::value,
                  "Following casting expects milliseconds.");

    if (ms.count() > std::numeric_limits<long>::max()) {
        throw std::overflow_error("cpr::Timeout: timeout value overflow: " +
                                  std::to_string(ms.count()) + " ms.");
    }
    if (ms.count() < std::numeric_limits<long>::min()) {
        throw std::underflow_error("cpr::Timeout: timeout value underflow: " +
                                   std::to_string(ms.count()) + " ms.");
    }

    return static_cast<long>(ms.count());
}

} // namespace cpr

Revert some casts that are needed.


#include "Log.h"

#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>

#include <string.h>
#include <iostream>

Log m_globalLog;

Log* Log::instance()
{
	return &m_globalLog;
}

Log::Log()
: m_fd(-1)
{
}

Log::~Log()
{
	close(m_fd);
}

void Log::open(const std::string& path)
{
	m_fd = ::open(path.c_str(),S_IRUSR);
}

void Log::write(Type type, const char* text)
{
	std::cerr << "log " << text << std::endl;
	::write(m_fd,text,strlen(text));
}

#include "Log.h"

#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>

#include <string.h>
#include <iostream>

Log m_globalLog;

Log* Log::instance()
{
	return &m_globalLog;
}

Log::Log()
: m_fd(-1)
{
}

Log::~Log()
{
	close(m_fd);
}

void Log::open(const std::string& path)
{
	m_fd = ::open(path.c_str(),S_IRUSR);
}

void Log::write(Type type, const char* text)
{
	switch (type)
	{
		case Info:
			std::cerr << "INFO  ";
			break;
		case Warn:
			std::cerr << "WARN  ";
			break;
		case Error:
			std::cerr << "ERROR ";
			break;
	}
	std::cerr << text << std::endl;

	if (m_fd >= 0)
	{
		::write(m_fd,text,strlen(text));
	}
}

Add entry type information at the start of each log file entry.


#include "eval.h"
#include "env.h"

namespace mclisp
{
ConsCell *Eval(const ConsCell *exp, ConsCell *env /* env::g_user_env */)
{
  if (Atom(exp))
    return env::Lookup(env, exp);

  if (Atom(Car(exp)))
  {
    if (Eq(Car(exp), g_builtin_symbols["QUOTE"]))
      return Cadr(exp);

    if (Eq(Car(exp), g_builtin_symbols["ATOM"]))
      return FromBool(Atom(Eval(Cadr(exp), env)));
  }

  return MakeSymbol("42");
}

} // namespace mclisp

#include "eval.h"
#include "env.h"

namespace
{
using namespace mclisp;

ConsCell *Evcon(const ConsCell *clauses, ConsCell *env)
{
  // TODO Might want throw something more descriptive than TypeError.
  TYPECHECK(clauses, Listp);

  if (Null(clauses))
    return kNil;

  TYPECHECK(Car(clauses), Consp);

  if (*Eval(Caar(clauses), env))
    return Eval(Cadar(clauses), env);

  return Evcon(Cdr(clauses), env);
}
} // namespace

namespace mclisp
{
ConsCell *Eval(const ConsCell *exp, ConsCell *env /* env::g_user_env */)
{
#define EQ(exp, sym) Eq(exp, g_builtin_symbols[#sym])

  if (Atom(exp))
    return env::Lookup(env, exp);

  if (Atom(Car(exp)))
  {
    if (EQ(Car(exp), QUOTE))
      return Cadr(exp);

    if (EQ(Car(exp), ATOM))
      return FromBool(Atom(Eval(Cadr(exp), env)));

    if (EQ(Car(exp), EQ))
      return FromBool(Eq(Eval(Cadr(exp), env), Eval(Caddr(exp), env)));

    if (EQ(Car(exp), COND))
      return Evcon(Cdr(exp), env);

    if (EQ(Car(exp), CAR))
      return Car(Eval(Cadr(exp), env));

    if (EQ(Car(exp), CDR))
      return Cdr(Eval(Cadr(exp), env));

    if (EQ(Car(exp), CONS))
      return Cons(Eval(Cadr(exp), env), Eval(Caddr(exp), env));
  }

#undef EQ
  return MakeSymbol("42");
}

} // namespace mclisp

Add EQ, COND, CAR, CDR and CONS to Eval.


#include "localserver.h"

namespace rclog {

LocalServer::LocalServer(boost::asio::io_service &io_service, std::string socket_path)
    :socket_(io_service, datagram_protocol::endpoint(socket_path)) {
    do_receive();
}

void LocalServer::do_receive() {
    socket_.async_receive_from(boost::asio::buffer(data_, max_length), sender_endpoint_,
                               boost::bind(&LocalServer::handle_message, this, _1, _2));
}

void LocalServer::do_send(std::size_t length) {
  std::cout << "EP: " << sender_endpoint_ << std::endl;
  socket_.async_send_to(
      boost::asio::buffer(data_, length), sender_endpoint_,
      [this](boost::system::error_code /*ec*/, std::size_t /*bytes_sent*/) {
        do_receive();
  });
}

void LocalServer::handle_message(boost::system::error_code ec, std::size_t bytes_recvd)
{
    if (!ec && bytes_recvd > 0) {
        std::cout << "Got: '";
        std::cout.write(data_, bytes_recvd);
        std::cout << "'" << std::endl;
        do_send(bytes_recvd);
    }
    else
        do_receive();
}

}

#include "localserver.h"

namespace rclog {

LocalServer::LocalServer(boost::asio::io_service &io_service, std::string socket_path)
    :socket_(io_service, datagram_protocol::endpoint(socket_path)) {
    do_receive();
}

void LocalServer::do_receive() {
    socket_.async_receive_from(boost::asio::buffer(data_, max_length), sender_endpoint_,
                               boost::bind(&LocalServer::handle_message, this, _1, _2));
}

void LocalServer::do_send(std::size_t length) {
  std::cout << "EP: " << sender_endpoint_ << std::endl;
  socket_.async_send_to(
      boost::asio::buffer(data_, length), sender_endpoint_,
      [this](boost::system::error_code /*ec*/, std::size_t /*bytes_sent*/) {
        do_receive();
  });
}

void LocalServer::handle_message(boost::system::error_code ec, std::size_t bytes_recvd)
{
    if (!ec && bytes_recvd > 0) {
        std::cout << "Got: '";
        std::cout.write(data_, bytes_recvd);
        std::cout << "'" << std::endl;
        do_send(bytes_recvd);
        return;
    }

    if (ec == boost::asio::error::message_size)
        std::cerr << "Error: got message greater then buffer size";    // TODO: send error

    do_receive();
}

}

Add message_size error handle to rclogd


#include "gamescene.h"

void GameScene::append_gameItem(QDeclarativeListProperty<GameItem> *list, GameItem *gameItem)
{
    GameScene *scene = qobject_cast<GameScene *>(list->object);
    if (scene) {
        gameItem->setParentItem(scene);
        scene->m_gameItems.append(gameItem);
    }
}

GameScene::GameScene(QQuickItem *parent)
    : QQuickItem(parent)
{
}

QDeclarativeListProperty<GameItem> GameScene::gameItems()
{
    return QDeclarativeListProperty<GameItem>(this, 0, &GameScene::append_gameItem);
}

void GameScene::update(long delta)
{
    if (!m_running) // TODO: stop Qt animations as well
        return;

    GameItem *item;

    foreach (item, m_gameItems)
        item->update(delta);
}

bool GameScene::running() const
{
    return m_running;
}

void GameScene::setRunning(bool running)
{
    m_running = running;

    emit runningChanged();
}

#include "gamescene.h"

void GameScene::append_gameItem(QDeclarativeListProperty<GameItem> *list, GameItem *gameItem)
{
    GameScene *scene = qobject_cast<GameScene *>(list->object);
    if (scene) {
        gameItem->setParentItem(scene);
        scene->m_gameItems.append(gameItem);
    }
}

GameScene::GameScene(QQuickItem *parent)
    : QQuickItem(parent)
    , m_running(true)
{
}

QDeclarativeListProperty<GameItem> GameScene::gameItems()
{
    return QDeclarativeListProperty<GameItem>(this, 0, &GameScene::append_gameItem);
}

void GameScene::update(long delta)
{
    if (!m_running) // TODO: stop Qt animations as well
        return;

    GameItem *item;

    foreach (item, m_gameItems)
        item->update(delta);
}

bool GameScene::running() const
{
    return m_running;
}

void GameScene::setRunning(bool running)
{
    m_running = running;

    emit runningChanged();
}

Change default running state to true


#include <stan/math/prim/scal.hpp>
#include <gtest/gtest.h>
#include <limits>

TEST(MathFunctions, is_nan) {
  using stan::math::is_nan;
  double infinity = std::numeric_limits<double>::infinity();
  double nan = std::numeric_limits<double>::quiet_NaN();
  double min = std::numeric_limits<double>::min();
  double max = std::numeric_limits<double>::max();
  EXPECT_TRUE(stan::math::is_nan(nan));
  EXPECT_FALSE(stan::math::is_nan(infinity));
  EXPECT_FALSE(stan::math::is_nan(0));
  EXPECT_FALSE(stan::math::is_nan(1));
  EXPECT_FALSE(stan::math::is_nan(min));
  EXPECT_FALSE(stan::math::is_nan(max));
}

#include <stan/math/prim/scal.hpp>
#include <gtest/gtest.h>
#include <limits>

TEST(MathFunctions, is_nan) {
  using stan::math::is_nan;
  double infinity = std::numeric_limits<double>::infinity();
  double nan = std::numeric_limits<double>::quiet_NaN();
  double min = std::numeric_limits<double>::min();
  double max = std::numeric_limits<double>::max();
  EXPECT_TRUE(is_nan(nan));
  EXPECT_FALSE(is_nan(infinity));
  EXPECT_FALSE(is_nan(0));
  EXPECT_FALSE(is_nan(1));
  EXPECT_FALSE(is_nan(min));
  EXPECT_FALSE(is_nan(max));
}

TEST(MathFunctions, is_nan_variadic) {
  using stan::math::is_nan;
  double infinity = std::numeric_limits<double>::infinity();
  double nan = std::numeric_limits<double>::quiet_NaN();
  double min = std::numeric_limits<double>::min();
  double max = std::numeric_limits<double>::max();

  EXPECT_TRUE(is_nan(nan, infinity, 1.0));
  EXPECT_TRUE(is_nan(max, infinity, nan, 2.0, 5.0));
  EXPECT_TRUE(is_nan(max, min, nan));
  EXPECT_FALSE(is_nan(1.0, 2.0, 20.0, 1, 2));
}

Add tests for variadic calls


//=======================================================================
// Copyright Baptiste Wicht 2011-2012.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
//  http://www.boost.org/LICENSE_1_0.txt)
//=======================================================================

#include "mtac/Loop.hpp"
#include "mtac/basic_block.hpp"

using namespace eddic;

mtac::Loop::Loop(const std::set<mtac::basic_block_p>& blocks) : m_blocks(blocks) {
    //Nothing
}

mtac::Loop::iterator mtac::Loop::begin(){
    return m_blocks.begin();
}

mtac::Loop::iterator mtac::Loop::end(){
    return m_blocks.begin();
}

int mtac::Loop::estimate(){
    return m_estimate;
}

void mtac::Loop::set_estimate(int estimate){
    this->m_estimate = estimate;
}

mtac::Loop::iterator mtac::begin(std::shared_ptr<mtac::Loop> loop){
    return loop->end();
}

mtac::Loop::iterator mtac::end(std::shared_ptr<mtac::Loop> loop){
    return loop->begin();
}

std::set<mtac::basic_block_p>& mtac::Loop::blocks(){
    return m_blocks;
}

//=======================================================================
// Copyright Baptiste Wicht 2011-2012.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
//  http://www.boost.org/LICENSE_1_0.txt)
//=======================================================================

#include "mtac/Loop.hpp"
#include "mtac/basic_block.hpp"

using namespace eddic;

mtac::Loop::Loop(const std::set<mtac::basic_block_p>& blocks) : m_blocks(blocks) {
    //Nothing
}

mtac::Loop::iterator mtac::Loop::begin(){
    return m_blocks.begin();
}

mtac::Loop::iterator mtac::Loop::end(){
    return m_blocks.end();
}

int mtac::Loop::estimate(){
    return m_estimate;
}

void mtac::Loop::set_estimate(int estimate){
    this->m_estimate = estimate;
}

mtac::Loop::iterator mtac::begin(std::shared_ptr<mtac::Loop> loop){
    return loop->begin();
}

mtac::Loop::iterator mtac::end(std::shared_ptr<mtac::Loop> loop){
    return loop->end();
}

std::set<mtac::basic_block_p>& mtac::Loop::blocks(){
    return m_blocks;
}

Fix iteration through loop bb


#include <turbodbc/time_helpers.h>

#include <sql.h>

#include <boost/date_time/gregorian/gregorian_types.hpp>
#include <boost/date_time/posix_time/posix_time_types.hpp>

namespace turbodbc {

    boost::posix_time::ptime const timestamp_epoch({1970, 1, 1}, {0, 0, 0, 0});

    int64_t timestamp_to_microseconds(char const * data_pointer)
    {
        auto & sql_ts = *reinterpret_cast<SQL_TIMESTAMP_STRUCT const *>(data_pointer);
        intptr_t const microseconds = sql_ts.fraction / 1000;
        boost::posix_time::ptime const ts({static_cast<unsigned short>(sql_ts.year), sql_ts.month, sql_ts.day},
                {sql_ts.hour, sql_ts.minute, sql_ts.second, microseconds});
        return (ts - timestamp_epoch).total_microseconds();
    }

    boost::gregorian::date const date_epoch(1970, 1, 1);

    intptr_t date_to_days(char const * data_pointer)
    {
        auto & sql_date = *reinterpret_cast<SQL_DATE_STRUCT const *>(data_pointer);
        boost::gregorian::date const date(sql_date.year, sql_date.month, sql_date.day);
        return (date - date_epoch).days();
    }

}

#include <turbodbc/time_helpers.h>

#ifdef _WIN32
#include <windows.h>
#endif
#include <cstring>
#include <sql.h>

#include <boost/date_time/gregorian/gregorian_types.hpp>
#include <boost/date_time/posix_time/posix_time_types.hpp>

namespace turbodbc {

    boost::posix_time::ptime const timestamp_epoch({1970, 1, 1}, {0, 0, 0, 0});

    int64_t timestamp_to_microseconds(char const * data_pointer)
    {
        auto & sql_ts = *reinterpret_cast<SQL_TIMESTAMP_STRUCT const *>(data_pointer);
        intptr_t const microseconds = sql_ts.fraction / 1000;
        boost::posix_time::ptime const ts({static_cast<unsigned short>(sql_ts.year), sql_ts.month, sql_ts.day},
                {sql_ts.hour, sql_ts.minute, sql_ts.second, microseconds});
        return (ts - timestamp_epoch).total_microseconds();
    }

    boost::gregorian::date const date_epoch(1970, 1, 1);

    intptr_t date_to_days(char const * data_pointer)
    {
        auto & sql_date = *reinterpret_cast<SQL_DATE_STRUCT const *>(data_pointer);
        boost::gregorian::date const date(sql_date.year, sql_date.month, sql_date.day);
        return (date - date_epoch).days();
    }

}

Add missing includes for Windows


#include "../include/parlex/detail/abstract_syntax_tree.hpp"

#include "graphviz_dot.hpp"

#include "parlex/builder.hpp"
#include "parlex/detail/grammar.hpp"

parlex::detail::ast_node::ast_node(match const & m, std::vector<ast_node> const & children, leaf const * l) : match(m), children(children), l(l) {}

std::string parlex::detail::ast_node::to_dot(grammar const & g) const
{
	auto const nameFunc = [&](ast_node const * n)
	{
		std::stringstream result;
		result << g.get_recognizer(uint16_t(n->l->recognizer_index)).name << " (" << n << ")";
		return result.str();
	};
	auto const edgeFunc = [&](ast_node const * n) {
		std::vector<std::pair<std::string, ast_node const *>> results;
		for (auto i = n->children.begin(); i != n->children.end(); ++i) {
			results.emplace_back("label=" + enquote(std::to_string(i - n->children.begin() + 1)), &*i);
		}
		return results;
	};
	auto const propFunc = [&](ast_node const * n) { return std::string(); };
	return directed_graph<ast_node const *>(this, nameFunc, edgeFunc, propFunc);
}

#include "../include/parlex/detail/abstract_syntax_tree.hpp"

#include "graphviz_dot.hpp"

#include "parlex/builder.hpp"
#include "parlex/detail/grammar.hpp"

parlex::detail::ast_node::ast_node(match const & m, std::vector<ast_node> const & children, leaf const * l) : match(m), children(children), l(l) {}

std::string parlex::detail::ast_node::to_dot(grammar const & g) const
{
	auto const nameFunc = [&](ast_node const * n)
	{
		std::stringstream result;
		result << g.get_recognizer(n->recognizer_index).name << " (" + std::to_string(n->document_position + 1) + " - " + std::to_string(n->consumed_character_count + n->document_position) + ")";
		return result.str();
	};
	auto const edgeFunc = [&](ast_node const * n) {
		std::vector<std::pair<std::string, ast_node const *>> results;
		for (auto i = n->children.begin(); i != n->children.end(); ++i) {
			results.emplace_back("label=" + enquote(std::to_string(i - n->children.begin() + 1)), &*i);
		}
		return results;
	};
	auto const propFunc = [&](ast_node const * n) { return std::string(); };
	return directed_graph<ast_node const *>(this, nameFunc, edgeFunc, propFunc);
}

Make the output of ast_node::to_dot give friendlier node names.


#include <iostream>
#include <QtConcurrent>
#include <QCoreApplication>
#include <stdint.h>
#include <pulse/simple.h>

#include "DBMeter.hpp"

using namespace std;

DBMeter::DBMeter()
{
	settings.setCodec("audio/PCM");
	settings.setChannelCount(1);
	settings.setSampleRate(16000);

	recorder = new QAudioRecorder(this);
	recorder->setAudioInput("pulseaudio:");
	recorder->setAudioSettings(settings);

	QUrl url = QString("/dev/null");
	recorder->setOutputLocation(url);

	probe = new QAudioProbe(this);
	connect(probe, SIGNAL(audioBufferProbed(QAudioBuffer)), this, SLOT(AudioCb(QAudioBuffer)));
	probe->setSource(recorder);
}

DBMeter::~DBMeter()
{
	delete recorder;
}

void DBMeter::Start()
{
	recorder->record();
}

void DBMeter::Stop()
{
	recorder->stop();
}

void DBMeter::AudioCb(const QAudioBuffer &buffer)
{
	const int16_t *ptr = buffer.constData<int16_t>();
	uint16_t maxVal = 0, val;
	int nbFrame = buffer.sampleCount();

	while (nbFrame--) {
		val = abs(*ptr++);
		if (val > maxVal) maxVal = val;
	}
	cerr << " maxVal " << maxVal << endl;
}

#include <iostream>
#include <QtConcurrent>
#include <QCoreApplication>
#include <stdint.h>

#include "DBMeter.hpp"

using namespace std;

DBMeter::DBMeter()
{
	settings.setCodec("audio/PCM");
	settings.setChannelCount(1);
	settings.setSampleRate(16000);

	recorder = new QAudioRecorder(this);
	recorder->setAudioInput("pulseaudio:");
	recorder->setAudioSettings(settings);

	QUrl url = QString("/dev/null");
	recorder->setOutputLocation(url);

	probe = new QAudioProbe(this);
	connect(probe, SIGNAL(audioBufferProbed(QAudioBuffer)), this, SLOT(AudioCb(QAudioBuffer)));
	probe->setSource(recorder);
}

DBMeter::~DBMeter()
{
	delete recorder;
}

void DBMeter::Start()
{
	recorder->record();
}

void DBMeter::Stop()
{
	recorder->stop();
}

void DBMeter::AudioCb(const QAudioBuffer &buffer)
{
	const int16_t *ptr = buffer.constData<int16_t>();
	uint16_t maxVal = 0, val;
	int nbFrame = buffer.sampleCount();

	while (nbFrame--) {
		val = abs(*ptr++);
		if (val > maxVal) maxVal = val;
	}
	cerr << " maxVal " << maxVal << endl;
}

Remove an include not needed


// Copyright 2016 Zheng Xian Qiu

#include "Seeker.h"

namespace Seeker {

  vector<ISubscriber*> Event::subscribers;

  void Event::Refresh() {
    SDL_Event ev;
    while(SDL_PollEvent(&ev)) {
      switch(ev.type) {
        case SDL_KEYDOWN:
          Dispatch(EventType::Key);
          break;
        case SDL_QUIT:
          Dispatch(EventType::Quit);
          break;
        case SDL_MOUSEBUTTONDOWN:
          Dispatch(EventType::Mouse);
          break;
      }
    }
  }

  void Event::On(ISubscriber* event) {
    if(Exists(event)) return;
    subscribers.push_back(event);
  }

  void Event::Off(ISubscriber* event) {
    if(Exists(event)) {
      subscribers.erase(std::remove(subscribers.begin(), subscribers.end(), event), subscribers.end());
    }
  }

  bool Event::Exists(ISubscriber* event) {
    for(auto &current : subscribers) {
      if(current == event) {
        return true;
      }
    }
    return false;
  }

  void Event::Dispatch(const EventType type) {
    for(auto &current : subscribers) {
      current->OnEvent(type);
    }
  }
}

// Copyright 2016 Zheng Xian Qiu

#include "Seeker.h"

#include<algorithm> // Prevent use C++17 std::remove

namespace Seeker {

  vector<ISubscriber*> Event::subscribers;

  void Event::Refresh() {
    SDL_Event ev;
    while(SDL_PollEvent(&ev)) {
      switch(ev.type) {
        case SDL_KEYDOWN:
          Dispatch(EventType::Key);
          break;
        case SDL_QUIT:
          Dispatch(EventType::Quit);
          break;
        case SDL_MOUSEBUTTONDOWN:
          Dispatch(EventType::Mouse);
          break;
      }
    }
  }

  void Event::On(ISubscriber* event) {
    if(Exists(event)) return;
    subscribers.push_back(event);
  }

  void Event::Off(ISubscriber* event) {
    if(Exists(event)) {
      subscribers.erase(std::remove(subscribers.begin(), subscribers.end(), event), subscribers.end());
    }
  }

  bool Event::Exists(ISubscriber* event) {
    for(auto &current : subscribers) {
      if(current == event) {
        return true;
      }
    }
    return false;
  }

  void Event::Dispatch(const EventType type) {
    for(auto &current : subscribers) {
      current->OnEvent(type);
    }
  }
}

Fix compiler use wrong version std::remove


/*
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 3 of the License, or
 * (at your option) any later version.
 *
 * Written (W) 2012 Chiyuan Zhang
 * Copyright (C) 2012 Chiyuan Zhang
 */

#include <shogun/multiclass/ecoc/ECOCOVOEncoder.h>

using namespace shogun;

SGMatrix<int32_t> CECOCOVOEncoder::create_codebook(int32_t num_classes)
{
    SGMatrix<int32_t> code_book(num_classes*(num_classes-1)/2, num_classes, true);
    code_book.zero();
    int32_t k=0;
    for (int32_t i=0; i < num_classes; ++i)
    {
        for (int32_t j=0; j < num_classes; ++j)
        {
            code_book(k, i) = 1;
            code_book(k, j) = -1;
            k++;
        }
    }

    return code_book;
}

/*
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 3 of the License, or
 * (at your option) any later version.
 *
 * Written (W) 2012 Chiyuan Zhang
 * Copyright (C) 2012 Chiyuan Zhang
 */

#include <shogun/multiclass/ecoc/ECOCOVOEncoder.h>

using namespace shogun;

SGMatrix<int32_t> CECOCOVOEncoder::create_codebook(int32_t num_classes)
{
    SGMatrix<int32_t> code_book(num_classes*(num_classes-1)/2, num_classes, true);
    code_book.zero();
    int32_t k=0;
    for (int32_t i=0; i < num_classes; ++i)
    {
        for (int32_t j=i+1; j < num_classes; ++j)
        {
            code_book(k, i) = 1;
            code_book(k, j) = -1;
            k++;
        }
    }

    return code_book;
}

Fix bug in ECOC OvO encoder


// Standard includes
#include <stdlib.h>

// OpenGL includes
#include <GL/glew.h>
#include <GLFW/glfw3.h>

#include "fluidDynamics.h"

void simulate() {
    // We ping-pong back and forth between two buffers on the GPU
    // u = advect(u);
    // u = diffuse(u);
    // u = addForces(u);
    //
    // p = computePressure(u);
    // u = subtractPressureGradient(u, p);
}

int main(int argc, char** argv) {
    GLFWmonitor* monitor = glfwGetPrimaryMonitor();
    GLFWwindow* window;

    if (!glfwInit()) {
        return -1;
    }

    window = glfwCreateWindow(640, 480, "FlickFlow", monitor, NULL);

    if (!window) {
        glfwTerminate();
        return -1;
    }

    glfwMakeContextCurrent(window);

    while (!glfwWindowShouldClose(window))
    {
        /* Render here */

        glfwSwapBuffers(window);
        glfwPollEvents();
    }

    glfwTerminate();
    return EXIT_SUCCESS;
}

// Standard includes
#include <stdlib.h>

// OpenGL includes
#include <GL/glew.h>
#include <GLFW/glfw3.h>

#include "fluidDynamics.h"

#define DEFAULT_WIDTH 640
#define DEFAULT_HEIGHT 480

void simulate() {
    // We ping-pong back and forth between two buffers on the GPU
    // u = advect(u);
    // u = diffuse(u);
    // u = addForces(u);
    //
    // p = computePressure(u);
    // u = subtractPressureGradient(u, p);
}

int main(int argc, char** argv) {
    GLFWmonitor* monitor = glfwGetPrimaryMonitor();
    GLFWwindow* window;

    if (!glfwInit()) {
        return -1;
    }

    window = glfwCreateWindow(DEFAULT_WIDTH, DEFAULT_HEIGHT, "FlickFlow", monitor, NULL);

    if (!window) {
        glfwTerminate();
        return -1;
    }

    glfwMakeContextCurrent(window);
    if (glewInit() != GLEW_OK) {
        return -1;
    }

    printf("%s", glGetString(GL_VERSION));

    loadShaders();

    while (!glfwWindowShouldClose(window))
    {
        /* Render here */

        glfwSwapBuffers(window);
        glfwPollEvents();
    }

    glfwTerminate();
    return EXIT_SUCCESS;
}

Call glewInit before trying to load shaders


#include "serialutil.h"
#include "usbutil.h"
#include "listener.h"
#include "signals.h"
#include "log.h"

#define VERSION_CONTROL_COMMAND 0x80
#define RESET_CONTROL_COMMAND 0x81

// USB
#define DATA_ENDPOINT 1

extern void reset();
void setup();
void loop();

const char* VERSION = "2.0-pre";

#ifdef __CHIPKIT__
SerialDevice serialDevice = {&Serial1};
#else
SerialDevice serialDevice;
#endif // __CHIPKIT__

UsbDevice USB_DEVICE = {
#ifdef CHIPKIT
    USBDevice(usbCallback),
#endif // CHIPKIT
    DATA_ENDPOINT,
    MAX_USB_PACKET_SIZE_BYTES};

Listener listener = {&USB_DEVICE, &serialDevice};

int main(void) {
#ifdef CHIPKIT
	init();
#endif
	setup();

	for (;;)
		loop();

	return 0;
}

bool handleControlRequest(uint8_t request) {
    switch(request) {
    case VERSION_CONTROL_COMMAND:
        char combinedVersion[strlen(VERSION) + strlen(getMessageSet()) + 4];
        sprintf(combinedVersion, "%s (%s)", VERSION, getMessageSet());
        debug("Version: %s", combinedVersion);

        sendControlMessage((uint8_t*)combinedVersion, strlen(combinedVersion));
        return true;
    case RESET_CONTROL_COMMAND:
        debug("Resetting...");
        reset();
        return true;
    default:
        return false;
    }
}

#include "serialutil.h"
#include "usbutil.h"
#include "listener.h"
#include "signals.h"
#include "log.h"

#define VERSION_CONTROL_COMMAND 0x80
#define RESET_CONTROL_COMMAND 0x81

// USB
#define DATA_ENDPOINT 1

extern void reset();
void setup();
void loop();

const char* VERSION = "2.0-pre";

#ifdef __CHIPKIT__
SerialDevice serialDevice = {&Serial1};
#else
SerialDevice serialDevice;
#endif // __CHIPKIT__

UsbDevice USB_DEVICE = {
#ifdef CHIPKIT
    USBDevice(usbCallback),
#endif // CHIPKIT
    DATA_ENDPOINT,
    MAX_USB_PACKET_SIZE_BYTES};

Listener listener = {&USB_DEVICE, &serialDevice};

int main(void) {
#ifdef CHIPKIT
	init();
#endif
	setup();

	for (;;)
		loop();

	return 0;
}

bool handleControlRequest(uint8_t request) {
    switch(request) {
    case VERSION_CONTROL_COMMAND:
        char combinedVersion[strlen(VERSION) + strlen(getMessageSet()) + 4];
        sprintf(combinedVersion, "%s (%s)", VERSION, getMessageSet());
        debug("Version: %s\r\n", combinedVersion);

        sendControlMessage((uint8_t*)combinedVersion, strlen(combinedVersion));
        return true;
    case RESET_CONTROL_COMMAND:
        debug("Resetting...\r\n");
        reset();
        return true;
    default:
        return false;
    }
}

Add newlines to control commands.


//===-- AVRTargetInfo.cpp - AVR Target Implementation ---------------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//

#include "llvm/IR/Module.h"
#include "llvm/Support/TargetRegistry.h"
namespace llvm {
Target &getTheAVRTarget() {
  static Target TheAVRTarget;
  return TheAVRTarget;
}
}

extern "C" void LLVMInitializeAVRTargetInfo() {
  llvm::RegisterTarget<llvm::Triple::avr> X(llvm::getTheAVRTarget(), "avr",
                                            "Atmel AVR Microcontroller");
}

//===-- AVRTargetInfo.cpp - AVR Target Implementation ---------------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//

#include "llvm/IR/Module.h"
#include "llvm/Support/TargetRegistry.h"
namespace llvm {
Target &getTheAVRTarget() {
  static Target TheAVRTarget;
  return TheAVRTarget;
}
}

extern "C" void LLVMInitializeAVRTargetInfo() {
  llvm::RegisterTarget<llvm::Triple::avr> X(llvm::getTheAVRTarget(), "avr",
                                            "Atmel AVR Microcontroller", "AVR");
}

Add backend name to AVR Target to enable runtime info to be fed back into TableGen


#include <SFML\Window.hpp>

int main()
{
	sf::Window window(sf::VideoMode(800, 600), "SFML works!");

	while (window.isOpen())
	{
		sf::Event event;
		while (window.pollEvent(event))
		{
			if (event.type == sf::Event::Closed)
				window.close();
		}

		window.display();
	}

	return 0;
}

#include <SFML\Window.hpp>

int main()
{
	bool fullscreen = false;
	sf::Window window(sf::VideoMode(800, 600), "SFML works!");

	while (window.isOpen())
	{
		sf::Event event;
		while (window.pollEvent(event))
		{
			if (event.type == sf::Event::Closed)
				window.close();

			if (event.type == sf::Event::KeyPressed) {
				if (event.key.code == sf::Keyboard::F) {
					window.close();
					if (fullscreen) {
						window.create(sf::VideoMode(800, 600), "SFML works!");
						fullscreen = false;
					}
					else {
						window.create(sf::VideoMode(800, 600), "SFML works!", sf::Style::Fullscreen);
						fullscreen = true;
					}
				}
				else if (event.key.code == sf::Keyboard::Escape) {
					window.close();
				}
			}
		}

		window.display();
	}

	return 0;
}

ADD fullscreen option for sfml window, press F atm


#include "arithmetics.hpp"
#include "gtest/gtest.h"

TEST(AddTest, PerformsAdditionOnTwoIntegers) {
  EXPECT_EQ(2, arithmetics::add(1, 1));
  EXPECT_EQ(2, arithmetics::add_buggy(1, 1));
}

int main(int argc, char **argv) {
  ::testing::InitGoogleTest(&argc, argv);
  return RUN_ALL_TESTS();
}

#include "arithmetics.hpp"
#include "gtest/gtest.h"

TEST(TestAdd, PerformsAdditionOnTwoIntegers) {
  EXPECT_EQ(2, arithmetics::add(1, 1));
}

TEST(TestAdd, PerformsAdditionOnTwoIntegers_2) {
  EXPECT_EQ(2, arithmetics::add_buggy(1, 1));
}

int main(int argc, char **argv) {
  ::testing::InitGoogleTest(&argc, argv);
  return RUN_ALL_TESTS();
}

Split tests into 2 distict tests


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

#include <common/sput.h>
#include "secure_cell_test.hpp"
#include "secure_message_test.hpp"
#include "secure_session_test.hpp"

int main(){
  sput_start_testing();
  themispp::secure_cell_test::run_secure_cell_test();
  themispp::secure_message_test::run_secure_message_test();
  themispp::secure_session_test::run_secure_session_test();
  sput_finish_testing();
  return sput_get_return_value();
}

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

#include <common/sput.h>
#include "secure_cell_test.hpp"
#include "secure_message_test.hpp"
#include "secure_session_test.hpp"
#include "secure_comparator_test.hpp"

int main(){
  sput_start_testing();
  themispp::secure_cell_test::run_secure_cell_test();
  themispp::secure_message_test::run_secure_message_test();
  themispp::secure_session_test::run_secure_session_test();
  themispp::secure_session_test::run_secure_comparator_test();
  sput_finish_testing();
  return sput_get_return_value();
}

Add secure comparator C++ wrapper test