#include <pybind11/pybind11.h>

#include "basics.hpp"
#include "containers.hpp"

namespace py = pybind11;

PYBIND11_DECLARE_HOLDER_TYPE(T, std::shared_ptr<T>);

namespace containers {

PYBIND11_PLUGIN(containers) {
    py::module m("containers", "wrapped C++ containers module");

    py::class_<containers::DoodadSet>(m, "DoodadSet")
        .def(py::init<>())
        .def("__len__", &containers::DoodadSet::size)
        .def("add", [](containers::DoodadSet &ds, std::shared_ptr<basics::Doodad> &d) { ds.add(d); });

    return m.ptr();
}

} // namespace containers

#include <pybind11/pybind11.h>
#include <pybind11/stl.h>

#include "basics.hpp"
#include "containers.hpp"

namespace py = pybind11;

PYBIND11_DECLARE_HOLDER_TYPE(T, std::shared_ptr<T>);

namespace containers {

PYBIND11_PLUGIN(containers) {
    py::module m("containers", "wrapped C++ containers module");

    py::class_<containers::DoodadSet>(m, "DoodadSet")
        .def(py::init<>())
        .def("__len__", &containers::DoodadSet::size)
        .def("add", [](containers::DoodadSet &ds, std::shared_ptr<basics::Doodad> &d) { ds.add(d); })
        .def("add", [](containers::DoodadSet &ds, std::pair<std::string, int> p) { ds.add(basics::WhatsIt{p.first, p.second}) ; })
        .def("as_dict", &containers::DoodadSet::as_map)
        .def("as_list", &containers::DoodadSet::as_vector)
        .def("assign", &containers::DoodadSet::assign);

    return m.ptr();
}

} // namespace containers

Support assignment and conversion to lists and dicts.


#include "stdafx.h"
#include "CppUnitTest.h"

#include "datastore.h"
#include "transaction.h"
#include "internal/operations/post_operation.h"
#include "dummy_values.h"

using Assert = Microsoft::VisualStudio::CppUnitTestFramework::Assert;

namespace You {
namespace DataStore {
namespace UnitTests {
TEST_CLASS(DataStoreApiTest) {
public:
	TEST_METHOD(pushOperationToTransaction) {
		Transaction sut;
		Internal::PostOperation postOp(0, task1);
		sut.push(std::shared_ptr<Internal::IOperation>(&postOp));
		Assert::AreEqual(boost::lexical_cast<size_t>(1), sut.operationsQueue.size());
	}
};

}  // namespace UnitTests
}  // namespace DataStore
}  // namespace You

#include "stdafx.h"
#include "CppUnitTest.h"

#include "datastore.h"
#include "transaction.h"
#include "internal/operations/post_operation.h"
#include "dummy_values.h"

using Assert = Microsoft::VisualStudio::CppUnitTestFramework::Assert;

namespace You {
namespace DataStore {
namespace UnitTests {
TEST_CLASS(DataStoreApiTest) {
public:
	TEST_METHOD(pushOperationToTransaction) {
		Transaction sut;
		std::shared_ptr<Internal::IOperation> postOp =
			std::make_shared<Internal::PostOperation>(0, task1);
		sut.push(postOp);
		Assert::AreEqual(boost::lexical_cast<size_t>(1), sut.operationsQueue.size());
	}
};

}  // namespace UnitTests
}  // namespace DataStore
}  // namespace You

Modify test to be correct


// RUN: rm -rf %t
// RUN: %clang_cc1 -fmodules -fimplicit-module-maps -fmodules-cache-path=%t -I %S/Inputs/self-referencing-lambda %s -verify -emit-obj -o %t2.o
// expected-no-diagnostics

#include "a.h"

// RUN: rm -rf %t
// RUN: %clang_cc1 -fmodules -fimplicit-module-maps -fmodules-cache-path=%t -I %S/Inputs/self-referencing-lambda %s -verify -emit-obj -std=c++14 -o %t2.o
// expected-no-diagnostics

#include "a.h"

Update test to mention it requires C++14.


#include "gtest/gtest.h"

#include "PrologInterface.h"
#include <iostream>

namespace {

static int glob_argc;
static char **glob_argv;

class PrologLifetimeTest : public ::testing::Test {
};

TEST_F(PrologLifetimeTest, BeginInitializesProlog) {
  PrologLifetime::begin(glob_argc, glob_argv);
  ASSERT_TRUE(PL_is_initialised(&glob_argc, &glob_argv));
  PrologLifetime::end();
}

}

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

#include "gtest/gtest.h"

#include "PrologInterface.h"
#include <iostream>

namespace {

static int glob_argc;
static char **glob_argv;

class PrologLifetimeTest : public ::testing::Test {
};

TEST_F(PrologLifetimeTest, BeginInitializesProlog) {
  PrologLifetime::begin(glob_argc, glob_argv);
  ASSERT_TRUE(PL_is_initialised(&glob_argc, &glob_argv));
  PrologLifetime::end();
}

TEST_F(PrologLifetimeTest, MultipleInitialization) {
  PrologLifetime::begin(glob_argc, glob_argv);
  ASSERT_TRUE(PL_is_initialised(&glob_argc, &glob_argv));
  PrologLifetime::end();

  ASSERT_FALSE(PL_is_initialised(&glob_argc, &glob_argv));

  PrologLifetime::begin(glob_argc, glob_argv);
  ASSERT_TRUE(PL_is_initialised(&glob_argc, &glob_argv));
  PrologLifetime::end();
}

}

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

Test multiple initialization for SWI-Prolog


#include"ics3/eepparam.hpp"

#include<stdexcept>

constexpr int byteSize {4};
constexpr uint16_t mask {0xF};

void ics::EepParam::write(std::array<uint8_t, 64>& dest) const noexcept {
  uint16_t nowData {data};
  for (size_t i {offset + length - 1}; i >= offset; --i) {
    dest[i] = nowData & mask;
    nowData >>= byteSize;
  }
}

void ics::EepParam::read(const std::array<uint8_t, 64>& src) {
  uint16_t result {0};
  for (size_t i {0}; i < length; ++i)
    result |= (src[offset + length - 1 - i] & mask) << (i * byteSize);
  set(result); // throw std::invalid_argument
}

#include"ics3/eepparam.hpp"

#include<stdexcept>

constexpr int byteSize {4};
constexpr uint16_t mask {0xF};

void ics::EepParam::write(std::array<uint8_t, 64>& dest) const noexcept {
  uint16_t nowData {data};
  for (size_t i {offset + length - 1}; i >= offset; --i) {
    dest[i] = nowData & mask;
    nowData >>= byteSize;
  }
}

void ics::EepParam::read(const std::array<uint8_t, 64>& src) {
  uint16_t result {0};
  const size_t loopend = offset + length;
  for (size_t i {offset}; i < loopend; ++i) {
    result <<= byteSize;
    result |= src[i] & mask;
  }
  set(result); // throw std::invalid_argument
}

Update read method for readability


#include <Headers\Native IO Board\MainStream IO\Native MainInput\IO Board.h>

using namespace std;

int main()
{

}

#include <Headers\Native IO Board\MainStream IO\Native MainInput\IO Board.h>

int main()
{

}

Remove standard namespace from source file.


// RUN: %clang_cc1 %s -triple i386-unknown-unknown -emit-llvm -o - | FileCheck %s

struct A {
  virtual int operator-() = 0;
};

void f(A *a) {
  // CHECK: call i32 %
  -*a;
}

// RUN: %clang_cc1 %s -triple i386-unknown-unknown -emit-llvm -o - | FileCheck %s

struct A {
  virtual int operator-();
};

void f(A a, A *ap) {
  // CHECK: call i32 @_ZN1AngEv(%struct.A* %a)
  -a;

  // CHECK: call i32 %
  -*ap;
}

Add a test for devirtualization of virtual operator calls.


Update Binary tree preorder inorder successor


#include <stdio.h>

#include <Logging.h>
#include <ZipFile.h>

int main()
{
	v::Log::Level = v::Log::LogLevel_Trace;

	v::Log::Debug("Creating zip file");

	{
		v::ZipFile zip;
		zip.Read("meow.zip");

		s::StackArray<v::ZipEntry> entries;
		zip.GetEntries(entries);

		for (auto &entry : entries) {
			v::Log::Debug("Zip entry %1: %2", FVAR(entry.GetIndex()), FVAR(entry.GetName()));

			s::MemoryStream strm;
			entry.Read(strm);
			v::Log::Debug("Contents at %1 with size %2", FVAR(strm.strm_pubBuffer), FVAR(strm.Size()));
		}
	}

	v::Log::Debug("Meow.zip created");

	getchar();
	return 0;
}

#include <stdio.h>

#include <Logging.h>
#include <ZipFile.h>

int main()
{
	v::Log::Level = v::Log::LogLevel_Trace;

	v::Log::Debug("Reading zip file test.zip");

	try {
		v::ZipFile zip;
		zip.Read("test.zip");

		s::StackArray<v::ZipEntry> entries;
		zip.GetEntries(entries);

		for (auto &entry : entries) {
			v::Log::Debug("Zip entry %1: %2", FVAR(entry.GetIndex()), FVAR(entry.GetName()));

			s::MemoryStream strm;
			entry.Read(strm);
			v::Log::Debug("Contents at %1 with size %2", FVAR(strm.strm_pubBuffer), FVAR(strm.Size()));
		}
	} catch (s::Exception ex) {
		v::Log::Fatal("Error: %1", FVAR(ex.Message));
	}

	getchar();
	return 0;
}

Clean up and error example


/* This file is part of python_mapnik (c++/python mapping toolkit)
 * Copyright (C) 2005 Artem Pavlenko, Jean-Francois Doyon
 *
 * Mapnik 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 2
 * of the License, or any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 */

//$Id$

#include <boost/python.hpp>
#include <mapnik.hpp>

using mapnik::text_symbolizer;
using mapnik::Color;

void export_text_symbolizer()
{
    using namespace boost::python;

    class_<text_symbolizer>("TextSymbolizer",
			    init<std::string const&,unsigned,Color const&>("TODO"))
	;
}

/* This file is part of python_mapnik (c++/python mapping toolkit)
 * Copyright (C) 2005 Artem Pavlenko, Jean-Francois Doyon
 *
 * Mapnik 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 2
 * of the License, or any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 */

//$Id$

#include <boost/python.hpp>
#include <mapnik.hpp>

using mapnik::text_symbolizer;
using mapnik::Color;

void export_text_symbolizer()
{
    using namespace boost::python;

    class_<text_symbolizer>("TextSymbolizer",
			    init<std::string const&,unsigned,Color const&>())
        .add_property("halo_fill",make_function(
                      &text_symbolizer::get_halo_fill,return_value_policy<copy_const_reference>()),
                      &text_symbolizer::set_halo_fill)
        .add_property("halo_radius",&text_symbolizer::get_halo_radius, &text_symbolizer::set_halo_radius)
	;
}

Add support for halo's to TextSymbolizer().


// Copyright (c) 2012-2013, the scalloc Project Authors.  All rights reserved.
// Please see the AUTHORS file for details.  Use of this source code is governed
// by a BSD license that can be found in the LICENSE file.

#include "allocators/page_heap.h"

#include "common.h"
#include "log.h"
#include "system-alloc.h"

namespace scalloc {

PageHeap PageHeap::page_heap_ cache_aligned;

void PageHeap::InitModule() {
  DistributedQueue::InitModule();

  page_heap_.page_pool_.Init(kPageHeapBackends);
}

void PageHeap::AsyncRefill() {
  uintptr_t ptr = reinterpret_cast<uintptr_t>(SystemAlloc_Mmap(
      kPageSize * kPageRefill, NULL));
  if (UNLIKELY(ptr == 0)) {
    ErrorOut("SystemAlloc failed");
  }
  for (size_t i = 0; i < kPageRefill; i++) {
    page_pool_.Enqueue(reinterpret_cast<void*>(ptr));
    ptr += kPageSize;
  }
}

}  // namespace scalloc

// Copyright (c) 2012-2013, the scalloc Project Authors.  All rights reserved.
// Please see the AUTHORS file for details.  Use of this source code is governed
// by a BSD license that can be found in the LICENSE file.

#include "allocators/page_heap.h"

#include "common.h"
#include "log.h"
#include "system-alloc.h"

namespace scalloc {

PageHeap PageHeap::page_heap_ cache_aligned;

void PageHeap::InitModule() {
  DistributedQueue::InitModule();

  page_heap_.page_pool_.Init(kPageHeapBackends);
}

void PageHeap::AsyncRefill() {
  uintptr_t ptr = reinterpret_cast<uintptr_t>(SystemAlloc_Mmap(
      kPageSize * kPageRefill, NULL));
  if (UNLIKELY(ptr == 0)) {
    ErrorOut("SystemAlloc failed");
  }
  for (size_t i = 0; i < kPageRefill; i++) {
    Put(reinterpret_cast<void*>(ptr));
    ptr += kPageSize;
  }
}

}  // namespace scalloc

Use public API for inserting a block in refill.


//===-- main.cpp ------------------------------------------------*- C++ -*-===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//

// This test verifies the correct handling of program counter jumps.

int otherfn();

template<typename T>
T min(T a, T b)
{
    if (a < b)
    {
        return a; // 1st marker
    } else {
        return b; // 2nd marker
    }
}

int main ()
{
    int i;
    double j;

    i = min(4, 5); // 3rd marker
    j = min(7.0, 8.0); // 4th marker

    return 0;
}

//===-- main.cpp ------------------------------------------------*- C++ -*-===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//

// This test verifies the correct handling of program counter jumps.

int otherfn();

template<typename T>
T min(T a, T b)
{
    if (a < b)
    {
        return a; // 1st marker
    } else {
        return b; // 2nd marker
    }
}

int main ()
{
    int i;
    double j;
    int min_i_a = 4, min_i_b = 5;
    double min_j_a = 7.0, min_j_b = 8.0;
    i = min(min_i_a, min_i_b); // 3rd marker
    j = min(min_j_a, min_j_b); // 4th marker

    return 0;
}

Fix the thread jump test case for 32-bit inferiors. A jump was going back to a function call using a source line number. However, the parameters being passed to the function were setup before the instruction we jumped to. In other words, the source line was associated with assembly after the function parameters had been setup for the function to be called.


// RUN: rm -rf %t
// RUN: %clang_cc1 -fmodule-cache-path %t -fauto-module-import -I %S/Inputs/submodules %s -verify

__import_module__ std.vector;
__import_module__ std.typetraits; // expected-error{{no submodule named 'typetraits' in module 'std'; did you mean 'type_traits'?}}
__import_module__ std.vector.compare; // expected-error{{no submodule named 'compare' in module 'std.vector'}}

// RUN: rm -rf %t
// RUN: %clang_cc1 -Eonly -fmodule-cache-path %t -fauto-module-import -I %S/Inputs/submodules %s -verify
// RUN: %clang_cc1 -fmodule-cache-path %t -fauto-module-import -I %S/Inputs/submodules %s -verify

__import_module__ std.vector;
__import_module__ std.typetraits; // expected-error{{no submodule named 'typetraits' in module 'std'; did you mean 'type_traits'?}}
__import_module__ std.vector.compare; // expected-error{{no submodule named 'compare' in module 'std.vector'}}

Add preprocessor-only test for submodule imports


#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include <QQmlContext>
#include "applications.h"
#include "iconprovider.h"
#include "process.h"

/**
 * @todo: Config file in ~/.config/qmldmenu/
 * @todo: SHIFT(ENTER) for sudo
 * @todo: TAB For command (term /{usr}/bin/) / app (.desktop) mode
 */
int main(int argc, char *argv[])
{
    QGuiApplication app(argc, argv);

    QQmlApplicationEngine engine;

    qmlRegisterType<Process>("Process", 1, 0, "Process");
    qmlRegisterType<Applications>("Applications", 1, 0, "Applications");
    engine.addImageProvider(QLatin1String("appicon"), new IconProvider);
    engine.load(QUrl(QStringLiteral("qrc:/main.qml")));

    return app.exec();
}

#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include <QQmlContext>
#include <QtQml>
#include "applications.h"
#include "iconprovider.h"
#include "process.h"

/**
 * @todo: Config file in ~/.config/qmldmenu/
 * @todo: SHIFT(ENTER) for sudo
 * @todo: TAB For command (term /{usr}/bin/) / app (.desktop) mode
 */
int main(int argc, char *argv[])
{
    QGuiApplication app(argc, argv);

    QQmlApplicationEngine engine;

    qmlRegisterType<Process>("Process", 1, 0, "Process");
    qmlRegisterType<Applications>("Applications", 1, 0, "Applications");
    engine.addImageProvider(QLatin1String("appicon"), new IconProvider);
    engine.load(QUrl(QStringLiteral("qrc:/main.qml")));

    return app.exec();
}

Fix compilation on Ubuntu 16.04


/** @file main.cpp
 * 	@brief Главный файл сервера репозитория
 * */
#include <QCoreApplication>
#include <QTextCodec>

#include "server.h"

int main(int argc, char *argv[])
{
	QTextCodec *codec = QTextCodec::codecForName("UTF-8");
	QTextCodec::setCodecForCStrings(codec);

	QCoreApplication app(argc, argv);

	int port = 6666;
	if (argc == 2) {
		port = QString(argv[1]).toInt();
	}

	repoServer::QRealRepoServer repo(port);

	return app.exec();
}

/** @file main.cpp
 * 	@brief Главный файл сервера репозитория
 * */
#include <QCoreApplication>
#include <QTextCodec>
#include <QFile>

#include "server.h"

int main(int argc, char *argv[])
{
	QTextCodec *codec = QTextCodec::codecForName("UTF-8");
	QTextCodec::setCodecForCStrings(codec);

	QCoreApplication app(argc, argv);

	int port = 6666;
	while (argc > 1)
	{
		argc--;
		if (!strcmp(argv[argc], "-e"))
		{
			QFile::remove("repothread_log.txt");
			continue;
		}
		port = QString(argv[argc]).toInt();
		if (port == 0)
			port = 6666;
	}

	repoServer::QRealRepoServer repo(port);

	return app.exec();
}

Add '-e' cmd key to reposerver which means 'immediate exterminatus'.


#include <QGuiApplication>
#include <QQuickView>

#include "sailfishapplication.h"

Q_DECL_EXPORT int main(int argc, char *argv[])
{
    QScopedPointer<QGuiApplication> app(Sailfish::createApplication(argc, argv));
    QScopedPointer<QQuickView> view(Sailfish::createView("main.qml"));

    Sailfish::showView(view.data());

    return app->exec();
}

#include <QGuiApplication>
#include <QQuickView>
#include <QQmlContext>

#include "sailfishapplication.h"
#include "servercomm.h"

Q_DECL_EXPORT int main(int argc, char *argv[])
{
    QScopedPointer<QGuiApplication> app(Sailfish::createApplication(argc, argv));
    QScopedPointer<QQuickView> view(Sailfish::createView("main.qml"));

    ServerComm sc;
    view->rootContext()->setContextProperty("serverComm", &sc);

    Sailfish::showView(view.data());

    return app->exec();
}

Connect the C++ classes with QML


//===-- llvm/CodeGen/GlobalISel/EmptyFile.cpp ------ EmptyFile ---*- C++ -*-==//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
/// \file
/// The purpose of this file is to please cmake by not creating an
/// empty library when we do not build GlobalISel.
/// \todo This file should be removed when GlobalISel is not optional anymore.
//===----------------------------------------------------------------------===//

#include "llvm/Support/Compiler.h"

// Anonymous namespace so that we do not step on anyone's toes.
namespace {
LLVM_ATTRIBUTE_UNUSED void foo(void) {
}
}

//===-- llvm/CodeGen/GlobalISel/EmptyFile.cpp ------ EmptyFile ---*- C++ -*-==//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
/// \file
/// The purpose of this file is to please cmake by not creating an
/// empty library when we do not build GlobalISel.
/// \todo This file should be removed when GlobalISel is not optional anymore.
//===----------------------------------------------------------------------===//

#include "llvm/Support/Compiler.h"

namespace llvm {
// Export a global symbol so that ranlib does not complain
// about the TOC being empty for the global-isel library when
// we do not build global-isel.
LLVM_ATTRIBUTE_UNUSED void DummyFunctionToSilenceRanlib(void) {
}
}

Fix a ranlib warning about empty TOC.


#include "OptionsManager.h"

#include <fstream>
#include <iostream>

#include <boost/filesystem.hpp>

#include <spotify/json.hpp>

#include "codecs/OptionsCodec.h"
#include "logging/Logging.h"

OptionsManager::OptionsManager(std::string optionsFilename)
{
    loadOptions(optionsFilename);
}

void OptionsManager::loadOptions(std::string optionsFilename)
{
    std::ifstream ifs(optionsFilename);
    if (!ifs.good())
    {
        throw std::runtime_error("Could not open options file");
    }

    std::string str{std::istreambuf_iterator<char>(ifs),
        std::istreambuf_iterator<char>()};
    try
    {
        mOptions = spotify::json::decode<Options>(str.c_str());
    }
    catch (const spotify::json::decode_exception& e)
    {
        logError() << "spotify::json::decode_exception encountered at "
            << e.offset()
            << ": "
            << e.what();
        throw;
    }
    mOptions.paths.initialise(optionsFilename);
    createOutputDirectory();
}

void OptionsManager::createOutputDirectory()
{
    // TODO(hryniuk): move it elsewhere
    boost::filesystem::path p(mOptions.paths.directory);
    p.append(mOptions.outputDirectory);
    boost::filesystem::create_directories(p);
    auto relativeOutputDirectory = p.string();
    mOptions.relativeOutputDirectory = relativeOutputDirectory;
}

const Options& OptionsManager::getOptions() const
{
    return mOptions;
}

#include "OptionsManager.h"

#include <fstream>
#include <iostream>

#include <boost/filesystem.hpp>

#include <spotify/json.hpp>

#include "codecs/OptionsCodec.h"
#include "logging/Logging.h"

OptionsManager::OptionsManager(std::string optionsFilename)
{
    loadOptions(optionsFilename);
}

void OptionsManager::loadOptions(std::string optionsFilename)
{
    std::ifstream ifs(optionsFilename);
    if (!ifs.good())
    {
        throw std::runtime_error("Could not open options file");
    }

    std::string str{std::istreambuf_iterator<char>(ifs),
        std::istreambuf_iterator<char>()};
    try
    {
        mOptions = spotify::json::decode<Options>(str.c_str());
    }
    catch (const spotify::json::decode_exception& e)
    {
        logError() << "spotify::json::decode_exception encountered at "
            << e.offset()
            << ": "
            << e.what();
        throw;
    }
    mOptions.paths.initialise(optionsFilename);
    createOutputDirectory();
}

void OptionsManager::createOutputDirectory()
{
    // TODO(hryniuk): move it elsewhere
    boost::filesystem::path p(mOptions.paths.directory);
    p.append(mOptions.outputDirectory);
    auto relativeOutputDirectory = p.string();
    mOptions.relativeOutputDirectory = relativeOutputDirectory;
}

const Options& OptionsManager::getOptions() const
{
    return mOptions;
}

Remove extra call to create_directories


// Copyright eeGeo Ltd (2012-2015), All Rights Reserved

#include "WatermarkDataFactory.h"

namespace ExampleApp
{
    namespace Watermark
    {
        namespace View
        {
            WatermarkDataFactory::WatermarkDataFactory(const std::string& appName,
                                                       const std::string& googleAnalyticsReferrerToken)
            : m_appName(appName)
            , m_googleAnalyticsReferrerToken(googleAnalyticsReferrerToken)
            {

            }

            WatermarkData WatermarkDataFactory::Create(const std::string& imageAssetUrl,
                                                       const std::string& popupTitle,
                                                       const std::string& popupBody,
                                                       const std::string& webUrl,
                                                       const bool shouldShowShadow)
            {
                return WatermarkData(imageAssetUrl,
                                     popupTitle,
                                     popupBody,
                                     webUrl,
                                     shouldShowShadow);
            }

            WatermarkData WatermarkDataFactory::CreateDefaultEegeo()
            {
                std::string imageAssetName = "eegeo_logo";
                std::string popupTitle = "Maps by eeGeo";
                std::string popupBody = "This app is open source. It's built using the eeGeo maps SDK, a cross platform API for building engaging, customizable apps.";
                std::string webUrl = "http://eegeo.com/?utm_source=" + m_googleAnalyticsReferrerToken + "&utm_medium=referral&utm_campaign=eegeo";

                return Create(imageAssetName,
                              popupTitle,
                              popupBody,
                              webUrl);
            }
        }
    }
}

// Copyright eeGeo Ltd (2012-2015), All Rights Reserved

#include "WatermarkDataFactory.h"

namespace ExampleApp
{
    namespace Watermark
    {
        namespace View
        {
            WatermarkDataFactory::WatermarkDataFactory(const std::string& appName,
                                                       const std::string& googleAnalyticsReferrerToken)
            : m_appName(appName)
            , m_googleAnalyticsReferrerToken(googleAnalyticsReferrerToken)
            {

            }

            WatermarkData WatermarkDataFactory::Create(const std::string& imageAssetUrl,
                                                       const std::string& popupTitle,
                                                       const std::string& popupBody,
                                                       const std::string& webUrl,
                                                       const bool shouldShowShadow)
            {
                return WatermarkData(imageAssetUrl,
                                     popupTitle,
                                     popupBody,
                                     webUrl,
                                     shouldShowShadow);
            }

            WatermarkData WatermarkDataFactory::CreateDefaultEegeo()
            {
                std::string imageAssetName = "eegeo_logo";
                std::string popupTitle = "Maps by WRLD";
                std::string popupBody = "This app is open source. It's built using the WRLD maps SDK, a cross platform API for building engaging, customizable apps.";
                std::string webUrl = "http://eegeo.com/?utm_source=" + m_googleAnalyticsReferrerToken + "&utm_medium=referral&utm_campaign=eegeo";

                return Create(imageAssetName,
                              popupTitle,
                              popupBody,
                              webUrl);
            }
        }
    }
}

Update eegeo reference in company watermark info page. Buddy: Vimmy.


#include "catch.hpp"
#include "matrix.h"

TEST_CASE( "Test matrix", "[matrix]" ) {
  matrix<int> m0;
  REQUIRE( m0.rows() == 0 );
  REQUIRE( m0.columns() == 0 );

  matrix<int> m3_4(3,4);
  REQUIRE( m3_4.rows() == 3 );
  REQUIRE( m3_4.columns() == 4 );

  matrix<int> m_init_2 = {};
  REQUIRE( m_init_2.rows() == 0 );
  REQUIRE( m_init_2.columns() == 0 );

  matrix<int> m_init = {{1,2,3},{4,5,6}};
  REQUIRE( m_init.rows() == 2 );
  REQUIRE( m_init.columns() == 3 );
  REQUIRE( m_init.at(0,0) == 1 );
  REQUIRE( m_init.at(0,1) == 2 );
  REQUIRE( m_init.at(0,2) == 3 );
  REQUIRE( m_init.at(1,0) == 4 );
  REQUIRE( m_init.at(1,1) == 5 );
  REQUIRE( m_init.at(1,2) == 6 );
}

#include "catch.hpp"
#include "matrix.h"

TEST_CASE( "Test default constructor", "[matrix][constructors]" ) {
  matrix<int> m0;
  REQUIRE( m0.rows() == 0 );
  REQUIRE( m0.columns() == 0 );
}

TEST_CASE( "Test size constructor", "[matrix][constructors]" ) {
  matrix<int> m3_4(3,4);
  REQUIRE( m3_4.rows() == 3 );
  REQUIRE( m3_4.columns() == 4 );

  matrix<int> m0_0(0,0);
  REQUIRE( m0_0.rows() == 0 );
  REQUIRE( m0_0.columns() == 0 );
}

TEST_CASE( "Test initializer list constructor", "[matrix][constructors]" ) {
  matrix<int> m_init = {{1,2,3},{4,5,6}};
  REQUIRE( m_init.rows() == 2 );
  REQUIRE( m_init.columns() == 3 );
  REQUIRE( m_init.at(0,0) == 1 );
  REQUIRE( m_init.at(0,1) == 2 );
  REQUIRE( m_init.at(0,2) == 3 );
  REQUIRE( m_init.at(1,0) == 4 );
  REQUIRE( m_init.at(1,1) == 5 );
  REQUIRE( m_init.at(1,2) == 6 );

  matrix<int> m_init_2 = {};
  REQUIRE( m_init_2.rows() == 0 );
  REQUIRE( m_init_2.columns() == 0 );
}

Split tests to multiple test cases.


#include <stdlib.h>
#include <v8.h>
#include <nan.h>
#include <node.h>

using namespace node;
using namespace v8;

extern "C" void init (Handle<Object>);

NAN_METHOD(Random) {
  NanScope();
  NanReturnValue(NanNew<Number>(rand()/((double)RAND_MAX + 1)));
}

NAN_METHOD(Rand) {
  NanScope();
  NanReturnValue(NanNew<Integer>(rand()));
}

NAN_METHOD(SRand) {
  NanScope();
  if (args.Length() == 0) {
    NanThrowError(Exception::Error(NanNew<String>("Usage: srand(n)")));
  }
  srand(args[0]->Uint32Value());
  NanReturnValue(NanUndefined());
}

extern "C" void init (Handle<Object> target) {
  NODE_SET_METHOD(target, "random", Random);
  NODE_SET_METHOD(target, "rand", Rand);
  NODE_SET_METHOD(target, "srand", SRand);
  NODE_SET_METHOD(target, "seed", SRand);
  NODE_DEFINE_CONSTANT(target, RAND_MAX);
}

NODE_MODULE(srand, init)

#include <stdlib.h>
#include <v8.h>
#include <nan.h>
#include <node.h>
#include <cstdlib>

using namespace node;
using namespace v8;

extern "C" void init (Handle<Object>);

NAN_METHOD(Random) {
  NanScope();
  NanReturnValue(NanNew<Number>(rand()/((double)RAND_MAX + 1)));
}

NAN_METHOD(Rand) {
  NanScope();
  NanReturnValue(NanNew<Integer>(rand()));
}

NAN_METHOD(SRand) {
  NanScope();
  if (args.Length() == 0) {
    NanThrowError(Exception::Error(NanNew<String>("Usage: srand(n)")));
  }
  srand(args[0]->Uint32Value());
  NanReturnValue(NanUndefined());
}

extern "C" void init (Handle<Object> target) {
  NODE_SET_METHOD(target, "random", Random);
  NODE_SET_METHOD(target, "rand", Rand);
  NODE_SET_METHOD(target, "srand", SRand);
  NODE_SET_METHOD(target, "seed", SRand);
  NODE_DEFINE_CONSTANT(target, RAND_MAX);
}

NODE_MODULE(srand, init)

Add cstdlib.h to compile in CircleCI


// RUN: %clang_cc1 -fsyntax-only -verify %s

#define NODEREF __attribute__((noderef))

void Func() {
  int NODEREF i; // expected-warning{{'noderef' can only be used on an array or pointer type}}
  int NODEREF *i_ptr;

  // There should be no difference whether a macro defined type is used or not.
  auto __attribute__((noderef)) *auto_i_ptr = i_ptr;
  auto __attribute__((noderef)) auto_i = i; // expected-warning{{'noderef' can only be used on an array or pointer type}}

  auto NODEREF *auto_i_ptr2 = i_ptr;
  auto NODEREF auto_i2 = i; // expected-warning{{'noderef' can only be used on an array or pointer type}}
}

// Added test for fix for P41835
#define _LIBCPP_FLOAT_ABI __attribute__((pcs("aapcs")))
struct A {
  _LIBCPP_FLOAT_ABI int operator()() throw(); // expected-warning{{'pcs' calling convention ignored for this target}}
};

// RUN: %clang_cc1 -fsyntax-only -verify -triple x86_64-linux-gnu %s

#define NODEREF __attribute__((noderef))

void Func() {
  int NODEREF i; // expected-warning{{'noderef' can only be used on an array or pointer type}}
  int NODEREF *i_ptr;

  // There should be no difference whether a macro defined type is used or not.
  auto __attribute__((noderef)) *auto_i_ptr = i_ptr;
  auto __attribute__((noderef)) auto_i = i; // expected-warning{{'noderef' can only be used on an array or pointer type}}

  auto NODEREF *auto_i_ptr2 = i_ptr;
  auto NODEREF auto_i2 = i; // expected-warning{{'noderef' can only be used on an array or pointer type}}
}

// Added test for fix for P41835
#define _LIBCPP_FLOAT_ABI __attribute__((pcs("aapcs")))
struct A {
  _LIBCPP_FLOAT_ABI int operator()() throw(); // expected-warning{{'pcs' calling convention ignored for this target}}
};

Add target triple to test.


/**
 * \file register_loader_saver_lcp.cpp
 * Defines IO for a GCSA LCPArray from stream files.
 */

#include <vg/io/registry.hpp>

#include <gcsa/gcsa.h>
#include <gcsa/algorithms.h>

namespace vg {

namespace io {

using namespace std;
using namespace vg::io;

void register_loader_saver_lcp() {
    Registry::register_bare_loader_saver<gcsa::LCPArray>("LCP", [](istream& input) -> void* {
        // Allocate an LCPArray
        gcsa::LCPArray* index = new gcsa::LCPArray();

        // Load it
        index->load(input);

        // Return it so the caller owns it.
        return (void*) index;
    }, [](const void* index_void, ostream& output) {
        // Cast to LCP and serialize to the stream.
        ((const gcsa::LCPArray*) index_void)->serialize(output);
    });

}

}

}

/**
 * \file register_loader_saver_lcp.cpp
 * Defines IO for a GCSA LCPArray from stream files.
 */

#include <vg/io/registry.hpp>

#include <gcsa/gcsa.h>
#include <gcsa/algorithms.h>

namespace vg {

namespace io {

using namespace std;
using namespace vg::io;

void register_loader_saver_lcp() {
    std::uint32_t magic_number = gcsa::LCPHeader::TAG;
    std::string magic_string(reinterpret_cast<char*>(&magic_number), sizeof(magic_number));

    Registry::register_bare_loader_saver_with_magic<gcsa::LCPArray>("LCP", magic_string, [](istream& input) -> void* {
        // Allocate an LCPArray
        gcsa::LCPArray* index = new gcsa::LCPArray();

        // Load it
        index->load(input);

        // Return it so the caller owns it.
        return (void*) index;
    }, [](const void* index_void, ostream& output) {
        // Cast to LCP and serialize to the stream.
        ((const gcsa::LCPArray*) index_void)->serialize(output);
    });

}

}

}

Use a magic number with the LCP array as well


/*
 *  Copyright 2019 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 "pc/ice_transport.h"

#include <memory>
#include <utility>

namespace webrtc {

IceTransportWithPointer::~IceTransportWithPointer() {
  // We depend on the signaling thread to call Clear() before dropping
  // its last reference to this object; if the destructor is called
  // on the signaling thread, it's OK to not have called Clear().
  if (internal_) {
    RTC_DCHECK_RUN_ON(creator_thread_);
  }
}

cricket::IceTransportInternal* IceTransportWithPointer::internal() {
  RTC_DCHECK_RUN_ON(creator_thread_);
  return internal_;
}

void IceTransportWithPointer::Clear() {
  RTC_DCHECK_RUN_ON(creator_thread_);
  internal_ = nullptr;
}

}  // namespace webrtc

/*
 *  Copyright 2019 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 "pc/ice_transport.h"

#include <memory>
#include <utility>

namespace webrtc {

IceTransportWithPointer::~IceTransportWithPointer() {
  // We depend on the networking thread to call Clear() before dropping
  // its last reference to this object; if the destructor is called
  // on the networking thread, it's OK to not have called Clear().
  if (internal_) {
    RTC_DCHECK_RUN_ON(creator_thread_);
  }
}

cricket::IceTransportInternal* IceTransportWithPointer::internal() {
  RTC_DCHECK_RUN_ON(creator_thread_);
  return internal_;
}

void IceTransportWithPointer::Clear() {
  RTC_DCHECK_RUN_ON(creator_thread_);
  internal_ = nullptr;
}

}  // namespace webrtc

Fix comment - ice transport is cleared on the networking thread.


#include "junior-simple.h"
#include <vector>

namespace junior
{
	std::vector<window> windows;

	window& create_window(const wchar_t* title)
	{
		windows.push_back(window(title));
		return windows.back();
	}

	inline window& main_window()
	{
		return windows.front();
	}

	void draw_line(const int x1, const int y1, const int x2, const int y2)
	{
		main_window().draw_line(x1, y1, x2, y2);
	}

	void draw_circle(const int x, const int y, const int radius)
	{
		main_window().draw_circle(x, y, radius);
	}

	void write(const wchar_t* text, const int x, const int y)
	{
		main_window().write(text, x, y);
	}
}

#include "junior-simple.h"
#include <vector>
#include <Windows.h>

namespace junior
{
	std::vector<window> windows;

	window& create_window(const wchar_t* title)
	{
		ShowWindow(GetConsoleWindow(), SW_HIDE);
		windows.push_back(window(title));
		return windows.back();
	}

	inline window& main_window()
	{
		return windows.front();
	}

	void draw_line(const int x1, const int y1, const int x2, const int y2)
	{
		main_window().draw_line(x1, y1, x2, y2);
	}

	void draw_circle(const int x, const int y, const int radius)
	{
		main_window().draw_circle(x, y, radius);
	}

	void write(const wchar_t* text, const int x, const int y)
	{
		main_window().write(text, x, y);
	}
}

Hide console window when creating a new window using simple API


// This code is based on Sabberstone project.
// Copyright (c) 2017-2019 SabberStone Team, darkfriend77 & rnilva
// Hearthstone++ is hearthstone simulator using C++ with reinforcement learning.
// Copyright (c) 2019 Chris Ohk, Youngjoong Kim, SeungHyun Jeon

#include <Rosetta/Actions/Targeting.hpp>
#include <Rosetta/Games/Game.hpp>

namespace RosettaStone::Generic
{
bool IsValidTarget(Entity* source, Entity* target)
{
    for (auto& requirement : source->card.playRequirements)
    {
        switch (requirement.first)
        {
            case +PlayReq::REQ_MINION_TARGET:
            {
                if (dynamic_cast<Minion*>(target) == nullptr)
                {
                    return false;
                }
            }
            case +PlayReq::REQ_ENEMY_TARGET:
            {
                if (&target->GetOwner() == &source->GetOwner())
                {
                    return false;
                }
            }
            case +PlayReq::REQ_TARGET_TO_PLAY:
            {
                if (dynamic_cast<Character*>(target) == nullptr)
                {
                    return false;
                }
            }
            default:
                break;
        }
    }

    return true;
}
}  // namespace RosettaStone::Generic

// This code is based on Sabberstone project.
// Copyright (c) 2017-2019 SabberStone Team, darkfriend77 & rnilva
// Hearthstone++ is hearthstone simulator using C++ with reinforcement learning.
// Copyright (c) 2019 Chris Ohk, Youngjoong Kim, SeungHyun Jeon

#include <Rosetta/Actions/Targeting.hpp>
#include <Rosetta/Games/Game.hpp>

namespace RosettaStone::Generic
{
bool IsValidTarget(Entity* source, Entity* target)
{
    for (auto& requirement : source->card.playRequirements)
    {
        switch (requirement.first)
        {
            case +PlayReq::REQ_MINION_TARGET:
            {
                if (dynamic_cast<Minion*>(target) == nullptr)
                {
                    return false;
                }
                break;
            }
            case +PlayReq::REQ_ENEMY_TARGET:
            {
                if (&target->GetOwner() == &source->GetOwner())
                {
                    return false;
                }
                break;
            }
            case +PlayReq::REQ_TARGET_TO_PLAY:
            {
                if (dynamic_cast<Character*>(target) == nullptr)
                {
                    return false;
                }
                break;
            }
            default:
                break;
        }
    }

    return true;
}
}  // namespace RosettaStone::Generic

Add 'break' in switch-case statement


class Solution {
public:
    int removeDuplicates(vector<int>& nums) {
        if(nums.size()==0) return 0;
        for(int i=0;i<nums.size()-1;i++){
            int j=i+1;
            while(nums[j]==nums[i] && j<nums.size()){
                j++;
            }
            nums.erase(nums.begin()+i+1,nums.begin()+j);
        }
        return nums.size();
    }
};

Remove Duplicates from Sorted Array


// main.cpp
// This file is part of the EScript programming language.
// See copyright notice in EScript.h
// ------------------------------------------------------
#ifdef ES_BUILD_APPLICATION
#include <cstdlib>
#include <iostream>
#include <string>

#include "../EScript/EScript.h"

using namespace EScript;

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

	if(argc<2){
		std::cout << ES_VERSION<<"\nNo filename given.\n";
		return EXIT_SUCCESS;
	}

	EScript::init();
	ERef<Runtime> rt(new Runtime());

	// --- Set program parameters
	declareConstant(rt->getGlobals(),"args",Array::create(argc,argv));

	// --- Load and execute script
	std::pair<bool,ObjRef> result = EScript::loadAndExecute(*rt.get(),argv[1]);

	// --- output result
	if (!result.second.isNull()) {
		std::cout << "\n\n --- "<<"\nResult: " << result.second.toString()<<"\n";
	}

	return result.first ? EXIT_SUCCESS : EXIT_FAILURE;
}
#endif // ES_BUILD_APPLICATION

// main.cpp
// This file is part of the EScript programming language.
// See copyright notice in EScript.h
// ------------------------------------------------------
#ifdef ES_BUILD_APPLICATION
#include <cstdlib>
#include <iostream>
#include <string>
#include <utility>

#include "../EScript/EScript.h"

int main(int argc, char * argv[]) {
	EScript::init();
	EScript::ERef<EScript::Runtime> rt(new EScript::Runtime());

	// --- Set program parameters
	declareConstant(rt->getGlobals(), "args", EScript::Array::create(argc, argv));

	// --- Load and execute script
	std::pair<bool, EScript::ObjRef> result;
	if(argc == 1) {
		result = EScript::executeStream(*rt.get(), std::cin);
	} else {
		result = EScript::loadAndExecute(*rt.get(), argv[1]);
	}

	// --- output result
	if(!result.second.isNull()) {
		std::cout << "\n\n --- " << "\nResult: " << result.second.toString() << "\n";
	}

	return result.first ? EXIT_SUCCESS : EXIT_FAILURE;
}

#endif // ES_BUILD_APPLICATION

Change EScript application to support executing a string from a pipe/from stdin.


#include <pthread.h>
#include <stdlib.h>
#include <stdio.h>

void *Thread1(void *p) {
  *(int*)p = 42;
  return 0;
}

void *Thread2(void *p) {
  *(int*)p = 44;;
  return 0;
}

void *alloc() {
  return malloc(99);
}

void *AllocThread(void*) {
  return alloc();
}

int main() {
  void *p = 0;
  pthread_t t[2];
  pthread_create(&t[0], 0, AllocThread, 0);
  pthread_join(t[0], &p);
  fprintf(stderr, "addr=%p\n", p);
  pthread_create(&t[0], 0, Thread1, (char*)p + 16);
  pthread_create(&t[1], 0, Thread2, (char*)p + 16);
  pthread_join(t[0], 0);
  pthread_join(t[1], 0);
  return 0;
}

// CHECK: addr=[[ADDR:0x[0-9,a-f]+]]
// CHECK: WARNING: ThreadSanitizer: data race
//...
// CHECK:   Location is heap block of size 99 at [[ADDR]] allocated by thread 1:
// CHECK:     #0 alloc
// CHECK:     #1 AllocThread
//...
// CHECK:   Thread 1 (finished) created at:
// CHECK:     #0 pthread_create
// CHECK:     #1 main

#include <pthread.h>
#include <stdlib.h>
#include <stdio.h>

void *Thread1(void *p) {
  *(int*)p = 42;
  return 0;
}

void *Thread2(void *p) {
  *(int*)p = 44;
  return 0;
}

void *alloc() {
  return malloc(99);
}

void *AllocThread(void* arg) {
  return alloc();
}

int main() {
  void *p = 0;
  pthread_t t[2];
  pthread_create(&t[0], 0, AllocThread, 0);
  pthread_join(t[0], &p);
  fprintf(stderr, "addr=%p\n", p);
  pthread_create(&t[0], 0, Thread1, (char*)p + 16);
  pthread_create(&t[1], 0, Thread2, (char*)p + 16);
  pthread_join(t[0], 0);
  pthread_join(t[1], 0);
  return 0;
}

// CHECK: addr=[[ADDR:0x[0-9,a-f]+]]
// CHECK: WARNING: ThreadSanitizer: data race
// ...
// CHECK:   Location is heap block of size 99 at [[ADDR]] allocated by thread 1:
// CHECK:     #0 alloc
// CHECK:     #1 AllocThread
// ...
// CHECK:   Thread 1 (finished) created at:
// CHECK:     #0 pthread_create
// CHECK:     #1 main

Fix style warinings in output test


/*
* (C) 2016 Jack Lloyd
*
* Botan is released under the Simplified BSD License (see license.txt)
*/

#include "tests.h"

#if defined(BOTAN_HAS_PUBLIC_KEY_CRYPTO)
  #include <botan/workfactor.h>
#endif

namespace Botan_Tests {

class PK_Workfactor_Tests : public Text_Based_Test
   {
   public:
      PK_Workfactor_Tests() : Text_Based_Test("pubkey/workfactor.vec",
                                              {"ParamSize", "Workfactor"})
         {}

      Test::Result run_one_test(const std::string& type, const VarMap& vars) override
         {
         const size_t param_size  = get_req_sz(vars, "ParamSize");
         const size_t exp_output  = get_req_sz(vars, "Workfactor");

         size_t output = 0;

         // TODO: test McEliece strength tests also

         if(type == "RSA_Strength")
            output = Botan::if_work_factor(param_size);
         else if(type == "DL_Exponent_Size")
            output = Botan::dl_exponent_size(param_size) / 2;

         Test::Result result(type + " work factor calculation");
         result.test_eq("Calculated workfactor for " + std::to_string(param_size),
                        output, exp_output);
         return result;
         }
   };

BOTAN_REGISTER_TEST("pk_workfactor", PK_Workfactor_Tests);

}

/*
* (C) 2016 Jack Lloyd
*
* Botan is released under the Simplified BSD License (see license.txt)
*/

#include "tests.h"

#if defined(BOTAN_HAS_PUBLIC_KEY_CRYPTO)
  #include <botan/workfactor.h>
#endif

namespace Botan_Tests {

#if defined(BOTAN_HAS_PUBLIC_KEY_CRYPTO)
class PK_Workfactor_Tests : public Text_Based_Test
   {
   public:
      PK_Workfactor_Tests() : Text_Based_Test("pubkey/workfactor.vec",
                                              {"ParamSize", "Workfactor"})
         {}

      Test::Result run_one_test(const std::string& type, const VarMap& vars) override
         {
         const size_t param_size  = get_req_sz(vars, "ParamSize");
         const size_t exp_output  = get_req_sz(vars, "Workfactor");

         size_t output = 0;

         // TODO: test McEliece strength tests also

         if(type == "RSA_Strength")
            output = Botan::if_work_factor(param_size);
         else if(type == "DL_Exponent_Size")
            output = Botan::dl_exponent_size(param_size) / 2;

         Test::Result result(type + " work factor calculation");
         result.test_eq("Calculated workfactor for " + std::to_string(param_size),
                        output, exp_output);
         return result;
         }
   };

BOTAN_REGISTER_TEST("pk_workfactor", PK_Workfactor_Tests);
#endif

}

Add missing macro check in test


#include "various.hpp"

#include <fstream>
#include <iostream>
#include <memory>

std::string
utils::slurp_file(std::string const& path)
{
  std::ifstream file = std::ifstream(path);
  if (!file.is_open()) {
    std::cerr << "Failed to open \"" << path << "\"" << std::endl;
    return std::string("");
  }

  file.seekg(0, std::ios::end);
  auto const size = file.tellg();
  file.seekg(0, std::ios::beg);

  std::unique_ptr<char[]> content = std::make_unique<char[]>(static_cast<size_t>(size) + 1ll);
  file.read(content.get(), size);
  content[static_cast<size_t>(size)] = '\0';

  return std::string(content.get());
}

#include "various.hpp"

#include "core/Log.h"

#include <fstream>
#include <iostream>
#include <memory>

std::string
utils::slurp_file(std::string const& path)
{
  std::ifstream file = std::ifstream(path);
  if (!file.is_open()) {
    LogError("Failed to open \"%s\"", path.c_str());
    return std::string("");
  }

  file.seekg(0, std::ios::end);
  auto const size = file.tellg();
  file.seekg(0, std::ios::beg);

  std::unique_ptr<char[]> content = std::make_unique<char[]>(static_cast<size_t>(size) + 1ll);
  file.read(content.get(), size);
  content[static_cast<size_t>(size)] = '\0';

  return std::string(content.get());
}

Use the logging functions in `utils::slurp_file()`


//
// Copyright (c) 2014 The ANGLE 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.
//

// Error.cpp: Implements the gl::Error class which encapsulates an OpenGL error
// and optional error message.

#include "libGLESv2/Error.h"

#include "common/angleutils.h"

#include <cstdarg>

namespace gl
{

Error::Error(GLenum errorCode)
    : mCode(errorCode),
      mMessage()
{
}

Error::Error(GLenum errorCode, const std::string &msg, ...)
    : mCode(errorCode),
      mMessage()
{
    va_list vararg;
    va_start(vararg, msg);
    mMessage = Format(msg, vararg);
    va_end(vararg);
}

Error::Error(const Error &other)
    : mCode(other.mCode),
      mMessage(other.mMessage)
{
}

Error &Error::operator=(const Error &other)
{
    mCode = other.mCode;
    mMessage = other.mMessage;
    return *this;
}

}

//
// Copyright (c) 2014 The ANGLE 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.
//

// Error.cpp: Implements the gl::Error class which encapsulates an OpenGL error
// and optional error message.

#include "libGLESv2/Error.h"

#include "common/angleutils.h"

#include <cstdarg>

namespace gl
{

Error::Error(GLenum errorCode)
    : mCode(errorCode),
      mMessage()
{
}

Error::Error(GLenum errorCode, const std::string &msg, ...)
    : mCode(errorCode),
      mMessage()
{
    va_list vararg;
    va_start(vararg, msg);
    mMessage = FormatString(msg, vararg);
    va_end(vararg);
}

Error::Error(const Error &other)
    : mCode(other.mCode),
      mMessage(other.mMessage)
{
}

Error &Error::operator=(const Error &other)
{
    mCode = other.mCode;
    mMessage = other.mMessage;
    return *this;
}

}

Fix compilation error due to bad merge.


#include "catch.hpp"

#include "libx6adc.h"

TEST_CASE("board present", "[get_num_devices]"){
	SECTION("at least one board present"){
		unsigned numDevices;
		get_num_devices(&numDevices);
		REQUIRE( numDevices >= 1);
	}
}

TEST_CASE("board temperature is sane", "[get_logic_temperature]"){

	connect_x6(0);

	SECTION("reported temperature is between 20C and 70C"){
		float logicTemp;
	    get_logic_temperature(0, &logicTemp);
		REQUIRE( logicTemp > 20 );
		REQUIRE( logicTemp < 70 );
	}

	disconnect_x6(0);
}

TEST_CASE("firmware version", "[get_firmware_version]") {

	connect_x6(0);

	SECTION("firmware version checks") {
		uint16_t ver;

		SECTION("BBN firmware is greater than 0.8"){
			get_firmware_version(0, BBN_X6, &ver);
			REQUIRE( ver >= 0x0008);
		}

		SECTION("BBN QDSP firmware is greater than 1.0"){
			get_firmware_version(0, BBN_QDSP, &ver);
			REQUIRE( ver >= 0x0100);
		}

		SECTION("BBN PG firmware is greater than 0.1"){
			get_firmware_version(0, BBN_PG, &ver);
			REQUIRE( ver >= 0x0001);
		}
	}

	disconnect_x6(0);
}

#include "catch.hpp"

#include "libx6adc.h"

TEST_CASE("board present", "[get_num_devices]"){
	SECTION("at least one board present"){
		unsigned numDevices;
		get_num_devices(&numDevices);
		REQUIRE( numDevices >= 1);
	}
}

TEST_CASE("board temperature is sane", "[get_logic_temperature]"){

	connect_x6(0);

	SECTION("reported temperature is between 20C and 70C"){
		float logicTemp;
	    get_logic_temperature(0, &logicTemp);
		REQUIRE( logicTemp > 20 );
		REQUIRE( logicTemp < 70 );
	}

	disconnect_x6(0);
}

TEST_CASE("firmware version", "[get_firmware_version]") {

	connect_x6(0);

	SECTION("firmware version checks") {
		uint16_t ver;

		get_firmware_version(0, BBN_X6, &ver);
		REQUIRE( ver >= 0x0008);
		get_firmware_version(0, BBN_QDSP, &ver);
		REQUIRE( ver >= 0x0100);
		get_firmware_version(0, BBN_PG, &ver);
		REQUIRE( ver >= 0x0001);
	}

	disconnect_x6(0);
}

Consolidate firmware version checks into single section


// https://github.com/KubaO/stackoverflown/tree/master/questions/lineedit-frame-37831979
#include <QtWidgets>
#include <QtUiTools>

const char ui[] = R"EOF(
 <ui version="4.0">
  <class>Form</class>
  <widget class="QWidget" name="Form">
   <layout class="QFormLayout" name="formLayout">
    <item row="0" column="0">
     <widget class="QLabel" name="label">
      <property name="text">
       <string>TextLabel</string>
      </property>
     </widget>
    </item>
    <item row="0" column="1">
     <widget class="QLineEdit" name="lineEdit"/>
    </item>
   </layout>
  </widget>
  <resources/>
  <connections/>
 </ui>)EOF";

int main(int argc, char ** argv) {
   QApplication app{argc, argv};
   QBuffer buf;
   buf.setData(ui, sizeof(ui));
   auto w = QUiLoader().load(&buf);
   auto & layout = *static_cast<QFormLayout*>(w->layout());
   QLineEdit edit;
   layout.addRow("Edit here", &edit);
   w->show();
   return app.exec();
}

// https://github.com/KubaO/stackoverflown/tree/master/questions/lineedit-frame-37831979
#include <QtWidgets>
#include <QtUiTools>

const char ui[] = R"EOF(
 <ui version="4.0">
  <class>Form</class>
  <widget class="QWidget" name="Form">
   <layout class="QFormLayout" name="formLayout">
    <item row="0" column="0">
     <widget class="QLabel" name="label">
      <property name="text">
       <string>TextLabel</string>
      </property>
     </widget>
    </item>
    <item row="0" column="1">
     <widget class="QLineEdit" name="lineEdit"/>
    </item>
   </layout>
  </widget>
  <resources/>
  <connections/>
 </ui>)EOF";

int main(int argc, char ** argv) {
   QApplication app{argc, argv};
   QBuffer buf;
   buf.setData(ui, sizeof(ui));
   auto w = QUiLoader().load(&buf);
   auto & layout = *static_cast<QFormLayout*>(w->layout());
   QLineEdit edit;
   layout.itemAt(0)->widget()->setMinimumHeight(50);
   layout.addRow("Edit here", &edit);
   edit.setMinimumHeight(100);
   layout.activate();
   w->show();
   return app.exec();
}

Tweak to indicate that different sizes still work.


#include "./labels.h"
#include <vector>

std::function<void()>
Labels::subscribe(std::function<void(const Label &)> subscriber)
{
  int erasePosition = subscribers.size();
  subscribers.push_back(subscriber);

  return [this, erasePosition]()
  {
    subscribers.erase(subscribers.begin() + erasePosition);
  };
}

void Labels::add(Label label)
{
  labels[label.id] = label;
  notify(label);
}

std::vector<Label> Labels::getLabels()
{
  std::vector<Label> result(labels.size());
  for (auto &pair : labels)
    result.push_back(pair.second);

  return result;
}

void Labels::updateAnchor(int id, Eigen::Vector3f anchorPosition)
{
  labels[id].anchorPosition = anchorPosition;
  notify(labels[id]);
}

void Labels::notify(const Label& label)
{
  for (auto &subscriber : subscribers)
    subscriber(label);
}

#include "./labels.h"
#include <vector>

std::function<void()>
Labels::subscribe(std::function<void(const Label &)> subscriber)
{
  int erasePosition = subscribers.size();
  subscribers.push_back(subscriber);

  return [this, erasePosition]()
  {
    subscribers.erase(subscribers.begin() + erasePosition);
  };
}

void Labels::add(Label label)
{
  labels[label.id] = label;
  notify(label);
}

std::vector<Label> Labels::getLabels()
{
  std::vector<Label> result;
  for (auto &pair : labels)
    result.push_back(pair.second);

  return result;
}

void Labels::updateAnchor(int id, Eigen::Vector3f anchorPosition)
{
  labels[id].anchorPosition = anchorPosition;
  notify(labels[id]);
}

void Labels::notify(const Label& label)
{
  for (auto &subscriber : subscribers)
    subscriber(label);
}

Fix error in Labels::getLabels: Wrong constructor for vector.


// Intercept the implicit 'this' argument of class member functions.
//
// RUN: %clangxx_xray -g -std=c++11 %s -o %t
// RUN: rm log-args-this-* || true
// RUN: XRAY_OPTIONS="patch_premain=true verbosity=1 xray_logfile_base=log-args-this-" %run %t
//
// XFAIL: freebsd || arm || aarch64 || mips
// UNSUPPORTED: powerpc64le
#include "xray/xray_interface.h"
#include <cassert>

class A {
 public:
  [[clang::xray_always_instrument, clang::xray_log_args(1)]] void f() {
    // does nothing.
  }
};

volatile uint64_t captured = 0;

void handler(int32_t, XRayEntryType, uint64_t arg1) {
  captured = arg1;
}

int main() {
  __xray_set_handler_arg1(handler);
  A instance;
  instance.f();
  __xray_remove_handler_arg1();
  assert(captured == (uint64_t)&instance);
}

// Intercept the implicit 'this' argument of class member functions.
//
// RUN: %clangxx_xray -g -std=c++11 %s -o %t
// RUN: rm log-args-this-* || true
// RUN: XRAY_OPTIONS="patch_premain=true verbosity=1 xray_logfile_base=log-args-this-" %run %t
//
// XFAIL: FreeBSD || arm || aarch64 || mips
// UNSUPPORTED: powerpc64le
#include "xray/xray_interface.h"
#include <cassert>

class A {
 public:
  [[clang::xray_always_instrument, clang::xray_log_args(1)]] void f() {
    // does nothing.
  }
};

volatile uint64_t captured = 0;

void handler(int32_t, XRayEntryType, uint64_t arg1) {
  captured = arg1;
}

int main() {
  __xray_set_handler_arg1(handler);
  A instance;
  instance.f();
  __xray_remove_handler_arg1();
  assert(captured == (uint64_t)&instance);
}

Fix supposely failing test for FreeBSD


/*
 * openvrupdateslavecallback.cpp
 *
 *  Created on: Dec 18, 2015
 *      Author: Chris Denham
 */

#include "openvrupdateslavecallback.h"

void OpenVRUpdateSlaveCallback::updateSlave(osg::View& view, osg::View::Slave& slave)
{
	if (m_cameraType == LEFT_CAMERA)
	{
		m_device->updatePose();
	}

	osg::Vec3 position = m_device->position();
	osg::Quat orientation = m_device->orientation();

	osg::Matrix viewOffset = (m_cameraType == LEFT_CAMERA) ? m_device->viewMatrixLeft() : m_device->viewMatrixRight();

	viewOffset.preMultRotate(orientation);
	viewOffset.setTrans(position);

	slave._viewOffset = viewOffset;

	slave.updateSlaveImplementation(view);
}

/*
 * openvrupdateslavecallback.cpp
 *
 *  Created on: Dec 18, 2015
 *      Author: Chris Denham
 */

#include "openvrupdateslavecallback.h"

void OpenVRUpdateSlaveCallback::updateSlave(osg::View& view, osg::View::Slave& slave)
{
	if (m_cameraType == LEFT_CAMERA)
	{
		m_device->updatePose();
	}

	osg::Vec3 position = m_device->position();
	osg::Quat orientation = m_device->orientation();

	osg::Matrix viewOffset = (m_cameraType == LEFT_CAMERA) ? m_device->viewMatrixLeft() : m_device->viewMatrixRight();

	viewOffset.preMultRotate(orientation);
	viewOffset.setTrans(viewOffset.getTrans() + position);

	slave._viewOffset = viewOffset;

	slave.updateSlaveImplementation(view);
}

Fix problem that caused left and right eyes to have the exact same image.


/Od
/I "P:\PROJEKTE\GERTICO\Win32VC80\ACE+TAO-5.6.5"
/I "C:\FHG\GERTICO"
/I "..\..\..\..\LevelTwo\common\include"
/I "..\..\..\..\LevelCommonIEEE\include"
/I "..\..\..\..\LevelCommonIEEE\include\RTI_1516"
/I "..\..\..\..\LevelTwo\phase_III"
/D "_WIN32_"
/D "WIN32"
/D "_UT_DEBUG"
/D "_NDEBUG"
/D "_CONSOLE"
/D "_CRT_SECURE_NO_DEPRECATE"
/D "IEEE_1516"
/D "GERTICO_1516"
/D "_UNICODE"
/D "UNICODE"
/FD
/EHsc /EHsc /EHsc
/MD
/Zc:forScope-
/Fo".\Release\\"
/Fd".\Release\vc80.pdb"
/W3
/nologo
/c
/Wp64
/TP
/wd4290
/wd4267
/wd4244
/wd4311
/errorReport:prompt

/Od
/I "P:\PROJEKTE\GERTICO\Win32VC80\ACE+TAO-5.6.5"
/I "C:\FHG\GERTICO"
/I "..\..\..\..\LevelTwo\common\include"
/I "..\..\..\..\LevelCommonIEEE\include"
/I "..\..\..\..\LevelCommonIEEE\include\RTI_1516"
/I "..\..\..\..\LevelTwo\phase_III"
/D "_WIN32_"
/D "WIN32"
/D "_UT_DEBUG"
/D "_NDEBUG"
/D "_CONSOLE"
/D "_CRT_SECURE_NO_DEPRECATE"
/D "IEEE_1516"
/D "GERTICO_1516"
/D "_UNICODE"
/D "UNICODE"
/FD
/EHsc Maus
/MD
/Zc:forScope-
/Fo".\Release\\"
/Fd".\Release\vc80.pdb"
/W3
/nologo
/c
/Wp64
/TP
/wd4290
/wd4267
/wd4244
/wd4311
/errorReport:prompt

Use maus instead of mouse.


// Copyright (c) 2008-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 "chrome/browser/history/history_publisher.h"

#include "base/utf_string_conversions.h"

namespace history {

const char* const HistoryPublisher::kThumbnailImageFormat = "image/jpeg";

void HistoryPublisher::PublishPageThumbnail(
    const std::vector<unsigned char>& thumbnail, const GURL& url,
    const base::Time& time) const {
  PageData page_data = {
    time,
    url,
    NULL,
    NULL,
    kThumbnailImageFormat,
    &thumbnail,
  };

  PublishDataToIndexers(page_data);
}

void HistoryPublisher::PublishPageContent(const base::Time& time,
                                          const GURL& url,
                                          const std::wstring& title,
                                          const string16& contents) const {
  PageData page_data = {
    time,
    url,
    UTF16ToWide(contents).c_str(),
    title.c_str(),
    NULL,
    NULL,
  };

  PublishDataToIndexers(page_data);
}

}  // namespace history

// Copyright (c) 2008-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 "chrome/browser/history/history_publisher.h"

#include "base/utf_string_conversions.h"

namespace history {

const char* const HistoryPublisher::kThumbnailImageFormat = "image/jpeg";

void HistoryPublisher::PublishPageThumbnail(
    const std::vector<unsigned char>& thumbnail, const GURL& url,
    const base::Time& time) const {
  PageData page_data = {
    time,
    url,
    NULL,
    NULL,
    kThumbnailImageFormat,
    &thumbnail,
  };

  PublishDataToIndexers(page_data);
}

void HistoryPublisher::PublishPageContent(const base::Time& time,
                                          const GURL& url,
                                          const std::wstring& title,
                                          const string16& contents) const {
  std::wstring wide_contents = UTF16ToWide(contents);
  PageData page_data = {
    time,
    url,
    wide_contents.c_str(),
    title.c_str(),
    NULL,
    NULL,
  };

  PublishDataToIndexers(page_data);
}

}  // namespace history

Make sure the pointer in PageData::html remains valid while PageData is called.


// Copyright (c) 2013 GitHub, Inc. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#ifndef ATOM_BROWSER_API_ATOM_API_RECORDED_OBJECT_
#define ATOM_BROWSER_API_ATOM_API_RECORDED_OBJECT_

#include "browser/api/atom_api_recorded_object.h"

#include "base/compiler_specific.h"
#include "browser/api/atom_api_objects_registry.h"
#include "browser/atom_browser_context.h"

namespace atom {

namespace api {

RecordedObject::RecordedObject(v8::Handle<v8::Object> wrapper)
    : ALLOW_THIS_IN_INITIALIZER_LIST(id_(
          AtomBrowserContext::Get()->objects_registry()->Add(this))) {
  Wrap(wrapper);

  wrapper->SetAccessor(v8::String::New("id"), IDGetter);
}

RecordedObject::~RecordedObject() {
}

// static
v8::Handle<v8::Value> RecordedObject::IDGetter(v8::Local<v8::String> property,
                                               const v8::AccessorInfo& info) {
  RecordedObject* self = RecordedObject::Unwrap<RecordedObject>(info.This());
  return v8::Integer::New(self->id_);
}

}  // namespace api

}  // namespace atom

#endif  // ATOM_BROWSER_API_ATOM_API_RECORDED_OBJECT_

// Copyright (c) 2013 GitHub, Inc. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#ifndef ATOM_BROWSER_API_ATOM_API_RECORDED_OBJECT_
#define ATOM_BROWSER_API_ATOM_API_RECORDED_OBJECT_

#include "browser/api/atom_api_recorded_object.h"

#include "base/compiler_specific.h"
#include "browser/api/atom_api_objects_registry.h"
#include "browser/atom_browser_context.h"

namespace atom {

namespace api {

RecordedObject::RecordedObject(v8::Handle<v8::Object> wrapper)
    : ALLOW_THIS_IN_INITIALIZER_LIST(id_(
          AtomBrowserContext::Get()->objects_registry()->Add(this))) {
  Wrap(wrapper);

  wrapper->SetAccessor(v8::String::New("id"), IDGetter);
}

RecordedObject::~RecordedObject() {
  AtomBrowserContext::Get()->objects_registry()->Remove(id());
}

// static
v8::Handle<v8::Value> RecordedObject::IDGetter(v8::Local<v8::String> property,
                                               const v8::AccessorInfo& info) {
  RecordedObject* self = RecordedObject::Unwrap<RecordedObject>(info.This());
  return v8::Integer::New(self->id_);
}

}  // namespace api

}  // namespace atom

#endif  // ATOM_BROWSER_API_ATOM_API_RECORDED_OBJECT_

Remove recorded object from registry in desturctor.


#include <iostream>
#include <string>

#include <memory>

#include <Lexer.hpp>
#include <Parser.hpp>
#include <Visitors.hpp>

int main() {
    std::string input_line;

    double ans = 0;

    std::cout << "miniMAT: It's like MATLAB, but smaller." << std::endl;
    std::cout << "Copyright (C) 2014 Federico Menozzi" << std::endl;
    std::cout << std::endl;

    while (true) {
        std::cout << ">>> ";

        std::getline(std::cin, input_line);
        if (input_line == "quit" || input_line == "exit")
            break;
        else if (input_line == "ans") {
            std::cout << "ans = " << ans << std::endl;
            continue;
        } else if (input_line == "")
            continue;

        if (std::cin.eof()) {
            std::cout << std::endl;
            break;
        }

        auto reporter = std::make_shared<miniMAT::reporter::ErrorReporter>();
        miniMAT::lexer::Lexer   lexer(input_line, reporter);
        miniMAT::parser::Parser parser(lexer, reporter);

        auto ast = parser.Parse();

        if (reporter->HasErrors())
            reporter->ReportErrors();
        else {
            ans = ast->VisitEvaluate();
            std::cout << "ans = " << std::endl << std::endl;
            std::cout << "     " << ans << std::endl << std::endl;
        }
    }

    return 0;
}

#include <iostream>
#include <string>

#include <memory>

#include <Lexer.hpp>
#include <Parser.hpp>
#include <Visitors.hpp>

int main() {
    std::string input_line;

    double ans = 0;

    std::cout << "miniMAT: It's like MATLAB, but smaller." << std::endl;
    std::cout << "Copyright (C) 2014 Federico Menozzi" << std::endl;
    std::cout << std::endl;

    while (true) {
        std::cout << ">>> ";

        std::getline(std::cin, input_line);
        if (input_line == "quit" || input_line == "exit")
            break;
        else if (input_line == "ans") {
            std::cout << "ans = " << std::endl << std::endl;
            std::cout << "     " << ans << std::endl << std::endl;
            continue;
        } else if (input_line == "")
            continue;

        if (std::cin.eof()) {
            std::cout << std::endl;
            break;
        }

        auto reporter = std::make_shared<miniMAT::reporter::ErrorReporter>();
        miniMAT::lexer::Lexer   lexer(input_line, reporter);
        miniMAT::parser::Parser parser(lexer, reporter);

        auto ast = parser.Parse();

        if (reporter->HasErrors())
            reporter->ReportErrors();
        else {
            ans = ast->VisitEvaluate();
            std::cout << "ans = " << std::endl << std::endl;
            std::cout << "     " << ans << std::endl << std::endl;
        }
    }

    return 0;
}

Adjust output when user enters 'ans'


// RUN: rm -rf %t
// RUN: %clang_cc1 -I%S/Inputs/PR21547 -verify %s
// RUN: %clang_cc1 -fmodules -fimplicit-module-maps -fmodules-cache-path=%t -I%S/Inputs/PR21547 -verify %s

#include "Inputs/PR21547/FirstHeader.h"

//expected-no-diagnostics

// RUN: rm -rf %t
// RUN: %clang_cc1 -I%S/Inputs/PR21547 -verify %s
// RUN: %clang_cc1 -fmodules -fimplicit-module-maps -fmodules-cache-path=%t -I%S/Inputs/PR21547 -verify %s
// RUN: %clang_cc1 -fmodules -fimplicit-module-maps -fmodules-cache-path=%t -I%S/Inputs/PR21547 -emit-llvm-only %s

#include "Inputs/PR21547/FirstHeader.h"

//expected-no-diagnostics

Add -emit-llvm-only to the regression test for PR21547.


// Copyright (c) 2014 Andrew Toulouse.
// Distributed under the MIT License.

#include <iostream>
#include <fstream>

#include <libOL/File.h>

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

    std::ifstream ifs("/Users/toulouse/code/lol/lmao/rofl/22923174.rofl", std::ios::binary);

    libol::File file = libol::File::decode(ifs);

    //std::cout << file << std::endl;
    return 0;
}

// Copyright (c) 2014 Andrew Toulouse.
// Distributed under the MIT License.

#include <iostream>
#include <fstream>

#include <libOL/File.h>
#include <libOL/Chunks.h>

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

    std::ifstream ifs("/Users/toulouse/code/lol/lmao/rofl/22923174.rofl", std::ios::binary);

    libol::File file = libol::File::decode(ifs);

    auto decryptionKey = file.payloadHeader.getDecodedEncryptionKey();

    auto header0 = file.chunkHeaders[0];
    std::vector<uint8_t> chunk0;
    chunk0.resize(header0.chunkLength);

    ifs.seekg(file.header.payloadOffset +
              file.payloadHeader.chunkCount * 17 +
              file.payloadHeader.keyframeCount  * 17 +
              header0.offset);
    ifs.read(reinterpret_cast<char *>(&chunk0[0]), header0.chunkLength);

    auto chunk0decrypted = libol::Chunks::decryptAndDecompress(chunk0, decryptionKey);
    std::cout << "foo" << std::endl;
    return 0;
}

Add some test code for decryption


#define CAF_TEST_NO_MAIN
#include <caf/test/unit_test_impl.hpp>

#include "vast/announce.h"

int main(int argc, char** argv)
{
  vast::announce_types();
  return caf::test::main(argc, argv);
}

#define CAF_TEST_NO_MAIN
#include <caf/test/unit_test_impl.hpp>

#include "vast/announce.h"
#include "vast/config.h"

#ifdef VAST_MACOS
#include <sys/resource.h> // setrlimit
#endif

namespace {

bool adjust_resource_limits()
{
#ifdef VAST_MACOS
  auto rl = ::rlimit{4096, 8192};
  auto result = ::setrlimit(RLIMIT_NOFILE,  &rl);
  return result == 0;
#endif
  return true;
}

} // namespace <anonymous>

int main(int argc, char** argv)
{
  if (! adjust_resource_limits())
    return 1;
  vast::announce_types();
  return caf::test::main(argc, argv);
}

Increase low default ulimit -n of 256 on Mac OS


// RUN: %clang_cc1 -fsyntax-only -verify %s
// RUN: cp %s %t
// RUN: %clang_cc1 -fixit -x c++ %t
// RUN: FileCheck -input-file=%t %s

void f(int a[10][20]) {
  // CHECK: delete[] a;
  delete a; // expected-warning {{'delete' applied to a pointer-to-array type}}
}

// RUN: %clang_cc1 -fsyntax-only -verify %s
// RUN: cp %s %t
// RUN: %clang_cc1 -fixit -x c++ %t
// RUN: %clang_cc1 -E -o - %t | FileCheck %s

void f(int a[10][20]) {
  // CHECK: delete[] a;
  delete a; // expected-warning {{'delete' applied to a pointer-to-array type}}
}

Fix a test case where FileCheck is used to test code corrected by -fixit. If the code file is not run through the preproccessor to remove comments, then FileCheck will match the strings within the CHECK commands rendering the test useless.


// REQUIRES: x86-64-registered-target
// RUN: %clang -cc1 -triple x86_64-apple-darwin10  -g -fno-limit-debug-info -S %s -o %t
// RUN: FileCheck %s < %t

//CHECK:         .asciz   "G"
//CHECK-NEXT:    .long   0
//CHECK-NEXT: Lpubtypes_end1:

class G {
public:
	void foo();
};

void G::foo() {
}

// REQUIRES: x86-64-registered-target
// RUN: %clang -cc1 -triple x86_64-apple-darwin10  -g -fno-limit-debug-info -S %s -o %t
// RUN: FileCheck %s < %t

// FIXME: This testcase shouldn't rely on assembly emission.
//CHECK: Lpubtypes_begin1:
//CHECK:         .asciz   "G"
//CHECK-NEXT:    .long   0
//CHECK-NEXT: Lpubtypes_end1:

class G {
public:
	void foo();
};

void G::foo() {
}

Update test for llvm assembly output change. Also add a fixme that this shouldn't be relying on assembly emission.


#include <string.h>
#include <stdlib.h>
#include <stdio.h>

#include <3ds.h>

#include "constants.h"
#include "patches.h"

#define log(...) fprintf(stderr, __VA_ARGS__)

int main(int argc, char** argv)
{
	gfxInitDefault();
	consoleInit(GFX_TOP, NULL);
	GetVersionConstants();
    PatchSrvAccess();

    svcBackdoor(PatchProcessWrapper);
    log("[0x%08X] - Patched process\n", ret);

	// Main loop
	while (aptMainLoop())
	{
		hidScanInput();

		u32 kDown = hidKeysDown();
		if (kDown & KEY_START)
			break;
		gspWaitForVBlank();
	}

	gfxExit();
	return 0;
}

#include <string.h>
#include <stdlib.h>
#include <stdio.h>

#include <3ds.h>

#include "constants.h"
#include "patches.h"

#define log(...) fprintf(stderr, __VA_ARGS__)

int main(int argc, char** argv)
{
	gfxInitDefault();
	consoleInit(GFX_TOP, NULL);
	GetVersionConstants();
    PatchSrvAccess();

// ONLY UNCOMMENT AFTER CUSTOMIZING PatchProcessWrapper
    // svcBackdoor(PatchProcessWrapper);
    // log("[0x%08X] - Patched process\n", ret);

	// Main loop
	while (aptMainLoop())
	{
		hidScanInput();

		u32 kDown = hidKeysDown();
		if (kDown & KEY_START)
			break;
		gspWaitForVBlank();
	}

	gfxExit();
	return 0;
}

Disable process patching by default (probably wasn't a good idea to patch with all zeroes)


// RUN: %clang_cc1 -std=c++11 -verify %s

// rdar://12240916 stack overflow.
namespace rdar12240916 {

struct S2 {
  S2(const S2&);
  S2();
};

struct S { // expected-note {{not complete}}
  S x; // expected-error {{incomplete type}}
  S2 y;
};

S foo() {
  S s;
  return s;
}

struct S3; // expected-note {{forward declaration}}

struct S4 {
  S3 x; // expected-error {{incomplete type}}
  S2 y;
};

struct S3 {
  S4 x;
  S2 y;
};

S4 foo2() {
  S4 s;
  return s;
}

}

// rdar://12542261 stack overflow.
namespace rdar12542261 {

template <class _Tp>
struct check_complete
{
  static_assert(sizeof(_Tp) > 0, "Type must be complete.");
};

template<class _Rp>
class function // expected-note 2 {{candidate}}
{
public:
  template<class _Fp>
  function(_Fp, typename check_complete<_Fp>::type* = 0);  // expected-note {{candidate}}
};

void foobar()
{
  auto LeftCanvas = new Canvas(); // expected-error {{unknown type name}}
  function<void()> m_OnChange = [&, LeftCanvas]() { }; // expected-error {{no viable conversion}}
}

}

Add a test case for the stack overflow in rdar://12542261


/*
 * Copyright (C) 2017 Incognito
 *
 * 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 "core.h"

#include <boost/scoped_ptr.hpp>

boost::scoped_ptr<Core> core;

Core::Core()
{
	data.reset(new Data);
	grid.reset(new Grid);
	streamer.reset(new Streamer);
}

/*
 * Copyright (C) 2017 Incognito
 *
 * 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 "core.h"

#include <boost/scoped_ptr.hpp>

boost::scoped_ptr<Core> core;

Core::Core()
{
	data.reset(new Data);
	grid.reset(new Grid);
	chunkStreamer.reset(new ChunkStreamer);
	streamer.reset(new Streamer);
}

Fix crash when player connects


// Regression test for http://llvm.org/bugs/show_bug.cgi?id=21621
// This test relies on timing between threads, so any failures will be flaky.
// RUN: LSAN_BASE="use_stacks=0:use_registers=0"
// RUN: %clangxx_lsan %s -std=c++11 -o %t
// RUN: %run %t
#include <thread>
#include <chrono>

void func() {
      std::this_thread::sleep_for(std::chrono::milliseconds(500));
}

int main() {
      std::thread(func).detach();
}

// Regression test for http://llvm.org/bugs/show_bug.cgi?id=21621
// This test relies on timing between threads, so any failures will be flaky.
// RUN: LSAN_BASE="use_stacks=0:use_registers=0"
// RUN: %clangxx_lsan %s -o %t
// RUN: %run %t
#include <assert.h>
#include <pthread.h>
#include <stdlib.h>
#include <unistd.h>

void *func(void *arg) {
  sleep(1);
  free(arg);
  return 0;
}

void create_detached_thread() {
  pthread_t thread_id;
  pthread_attr_t attr;

  pthread_attr_init(&attr);
  pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);

  void *arg = malloc(1337);
  assert(arg);
  int res = pthread_create(&thread_id, &attr, func, arg);
  assert(res == 0);
}

int main() {
  create_detached_thread();
}

Rewrite the test from r223419 to not use C++11.


/// \file    main.cpp

#include "HelloTriangleApplication.hpp"
#include "VDeleter.hpp"

// waf-generated header
#include "config.hpp"

#define DOCTEST_CONFIG_IMPLEMENT
#include "doctest.h"

#define GLFW_INCLUDE_VULKAN
#include <GLFW/glfw3.h>

#include <iostream>
#include <string>

int main(int argc, char* argv[])
{
  int res{0};
#ifndef DOCTEST_CONFIG_DISABLE
  doctest::Context context(argc, argv);

  context.setOption("no-run", true);

  context.applyCommandLine(argc, argv);

  using namespace std::literals::string_literals;
  auto begin_argv = argv + 1;
  auto end_argv = argv + argc;
  if (end_argv != std::find(begin_argv, end_argv, "--test"s)) {
    context.setOption("no-run", false);
    context.setOption("exit", true);
  }

  res = context.run();
  if (context.shouldExit()) return res;
#endif
  HelloTriangleApplication app;

  try {
    app.run();
  }
  catch (const std::runtime_error& e) {
    std::cerr << e.what() << std::endl;
    return EXIT_FAILURE;
  }

  return EXIT_SUCCESS + res;
}

// vim:set et ts=2 sw=2 sts=2:

/// \file    main.cpp

#include "HelloTriangleApplication.hpp"
#include "VDeleter.hpp"

// waf-generated header
#include "config.hpp"

#define DOCTEST_CONFIG_IMPLEMENT
#include "doctest.h"

#define GLFW_INCLUDE_VULKAN
#include <GLFW/glfw3.h>

#include <iostream>
#include <string>

int main(int argc, char* argv[])
{
  int res{0};
#ifndef DOCTEST_CONFIG_DISABLE
  doctest::Context context;

  context.setOption("no-run", true);

  context.applyCommandLine(argc, argv);

  using namespace std::literals::string_literals;
  auto begin_argv = argv + 1;
  auto end_argv = argv + argc;
  if (end_argv != std::find(begin_argv, end_argv, "--test"s)) {
    context.setOption("no-run", false);
    context.setOption("exit", true);
  }

  res = context.run();
  if (context.shouldExit()) return res;
#endif
  HelloTriangleApplication app;

  try {
    app.run();
  }
  catch (const std::runtime_error& e) {
    std::cerr << e.what() << std::endl;
    return EXIT_FAILURE;
  }

  return EXIT_SUCCESS + res;
}

// vim:set et ts=2 sw=2 sts=2:

Bring doctest code to better doctest 1.1 usage


#include "ReQL-test.hpp"

#include "catch.h"

using namespace ReQL;

TEST_CASE("Connection", "[c++][connect]") {
  Connection conn = connect();

  REQUIRE(conn.isOpen());
}

TEST_CASE("Expr", "[c][expr]") {
  SECTION("string") {
    _ReQL_Op_t string;

    const uint32_t size = 12;

    uint8_t buf[size] = "Hello World";

    std::string orig = std::string((char *)buf, size);

    _reql_string_init(&string, buf, size, size);

    CHECK(orig.compare(0, size, (char *)_reql_string_buf(&string), size) == 0);
    CHECK(size == _reql_string_size(&string));
  }
}

#include "ReQL-test.hpp"

#include "catch.h"

#include <limits>

using namespace ReQL;

TEST_CASE("Connection", "[c++][connect]") {
  Connection conn = connect();

  REQUIRE(conn.isOpen());
}

TEST_CASE("Expr", "[c][expr]") {
  SECTION("number") {
    _ReQL_Op_t num;

    const double val = 42.0;

    _reql_number_init(&num, val);

    CHECK(val == _reql_to_number(&num));
  }
  SECTION("number edges") {
    _ReQL_Op_t num;

    const double val = std::numeric_limits<std::double_t>::max();

    _reql_number_init(&num, val);

    CHECK(val == _reql_to_number(&num));
  }
  SECTION("string") {
    _ReQL_Op_t string;

    const uint32_t size = 12;

    uint8_t buf[size] = "Hello World";

    std::string orig = std::string((char *)buf, size);

    _reql_string_init(&string, buf, size, size);

    CHECK(orig.compare(0, size, (char *)_reql_string_buf(&string), size) == 0);
    CHECK(size == _reql_string_size(&string));
  }
}

Add number c constructor tests.


#include <cppunit/BriefTestProgressListener.h>
#include <cppunit/CompilerOutputter.h>
#include <cppunit/extensions/TestFactoryRegistry.h>
#include <cppunit/TestResult.h>
#include <cppunit/TestResultCollector.h>

#include <cppunit/TestRunner.h>

#include "Suite.h"

#if OGRE_PLATFORM == OGRE_PLATFORM_WIN32
#define WIN32_LEAN_AND_MEAN
#include "windows.h"

INT WINAPI WinMain( HINSTANCE hInst, HINSTANCE, LPSTR strCmdLine, INT )
#else
int main(int argc, char *argv[])
#endif
{

    setUpSuite();

    // Create the event manager and test controller
    CPPUNIT_NS::TestResult controller;

    // Add a listener that colllects test result
    CPPUNIT_NS::TestResultCollector result;
    controller.addListener( &result );

    // Add a listener that print dots as test run.
    CPPUNIT_NS::BriefTestProgressListener progress;
    controller.addListener( &progress );

    // Add the top suite to the test runner
    CPPUNIT_NS::TestRunner runner;
    runner.addTest( CPPUNIT_NS::TestFactoryRegistry::getRegistry().makeTest() );
    runner.run( controller );

    // Print test in a compiler compatible format.
    CPPUNIT_NS::CompilerOutputter* outputter =
        CPPUNIT_NS::CompilerOutputter::defaultOutputter(&result, std::cout);
    outputter->write();
    delete outputter;

    tearDownSuite();

    return result.wasSuccessful() ? 0 : 1;

}

#include <cppunit/BriefTestProgressListener.h>
#include <cppunit/CompilerOutputter.h>
#include <cppunit/extensions/TestFactoryRegistry.h>
#include <cppunit/TestResult.h>
#include <cppunit/TestResultCollector.h>

#include <cppunit/TestRunner.h>

#include "Suite.h"

#if OGRE_PLATFORM == OGRE_PLATFORM_WIN32
#define WIN32_LEAN_AND_MEAN
#include "windows.h"

INT WINAPI WinMain( HINSTANCE hInst, HINSTANCE, LPSTR strCmdLine, INT )
#else
int main(int argc, char *argv[])
#endif
{

    setUpSuite();

    // Create the event manager and test controller
    CPPUNIT_NS::TestResult controller;

    // Add a listener that colllects test result
    CPPUNIT_NS::TestResultCollector result;
    controller.addListener( &result );

    // Add a listener that print dots as test run.
    CPPUNIT_NS::BriefTestProgressListener progress;
    controller.addListener( &progress );

    // Add the top suite to the test runner
    CPPUNIT_NS::TestRunner runner;
    runner.addTest( CPPUNIT_NS::TestFactoryRegistry::getRegistry().makeTest() );
    runner.run( controller );

    // Print test results to a file
	std::ofstream ofile("OgreTestResults.log");

    CPPUNIT_NS::CompilerOutputter* outputter =
        CPPUNIT_NS::CompilerOutputter::defaultOutputter(&result, ofile);
    outputter->write();
    delete outputter;

    tearDownSuite();

    return result.wasSuccessful() ? 0 : 1;

}

Write test results to a file for easier examination


//
//  main.cpp
//  MacGPusher
//
//  Created by Nyxouf on 6/23/13.
//  Copyright (c) 2013 MacGeneration. All rights reserved.
//

#include "global.hpp"
#include "MMGAPNSConnection.hpp"
#include "MMGDevice.hpp"
#include "MMGPayload.hpp"

int main(int argc, const char* argv[])
{
	// Create a device object
	const unsigned int badge = 1;
	MMGDevice device("device-token", badge);

	// Create a payload object
	MMGPayload payload("Push message", device.GetBadge(), "sound.caf", "Slider LABEL");

	// Create the APNS connection
	MMGAPNSConnection connection(MMG_APNS_CA_PATH, MMG_APNS_CERT_PATH, MMG_APNS_PRIVATEKEY_PATH, true);
	// Open the connection
	if (connection.OpenConnection() != MMGConnectionError::MMGNoError)
		return -1;

	// Send the payload
	connection.SendPayloadToDevice(payload, device);

	// Close the connection
	connection.CloseConnection();

	return 0;
}

//
//  main.cpp
//  MacGPusher
//
//  Created by Nyx0uf on 6/23/13.
//  Copyright (c) 2013 MacGeneration. All rights reserved.
//

#include "global.hpp"
#include "MMGAPNSConnection.hpp"
#include "MMGDevice.hpp"
#include "MMGPayload.hpp"

int main(int argc, const char* argv[])
{
	// Create a device object
	const unsigned int badge = 1;
	MMGDevice device("device-token", badge);

	// Create a payload object
	MMGPayload payload("Push message", device.GetBadge(), "sound.caf", "Slider label");

	// Create the APNS connection, empty string if no password for the private key
	MMGAPNSConnection connection(MMG_APNS_CA_PATH, MMG_APNS_CERT_PATH, MMG_APNS_PRIVATEKEY_PATH, "private-key-password", true);
	// Open the connection
	if (connection.OpenConnection() != MMGConnectionError::MMGNoError)
		return -1;

	// Send the payload
	connection.SendPayloadToDevice(payload, device);

	// Close the connection
	connection.CloseConnection();

	return 0;
}

Update example to use private key password


// Copyright (C) 2017 Elviss Strazdins
// This file is part of the Ouzel engine.

#ifdef _WIN32
#define NOMINMAX
#include <winsock2.h>
#else
#include <sys/socket.h>
#include <netinet/in.h>
#include <poll.h>
#endif
#include "Network.hpp"
#include "utils/Log.hpp"

namespace ouzel
{
    namespace network
    {
        Network::Network()
        {
        }

        Network::~Network()
        {
            WSACleanup();
        }

        bool Network::init()
        {
            WORD sockVersion = MAKEWORD(2, 2);
            WSADATA wsaData;
            int error = WSAStartup(sockVersion, &wsaData);
            if (error != 0)
            {
                Log(Log::Level::ERR) << "Failed to start Winsock failed, error: " << error;
                return false;
            }

            if (wsaData.wVersion != sockVersion)
            {
                Log(Log::Level::ERR) << "Incorrect Winsock version";
                WSACleanup();
                return false;
            }

            return true;
        }
    } // namespace network
} // namespace ouzel

// Copyright (C) 2017 Elviss Strazdins
// This file is part of the Ouzel engine.

#ifdef _WIN32
#define NOMINMAX
#include <winsock2.h>
#else
#include <sys/socket.h>
#include <netinet/in.h>
#include <poll.h>
#endif
#include "Network.hpp"
#include "utils/Log.hpp"

namespace ouzel
{
    namespace network
    {
        Network::Network()
        {
        }

        Network::~Network()
        {
            WSACleanup();
        }

        bool Network::init()
        {
#ifdef _WIN32
            WORD sockVersion = MAKEWORD(2, 2);
            WSADATA wsaData;
            int error = WSAStartup(sockVersion, &wsaData);
            if (error != 0)
            {
                Log(Log::Level::ERR) << "Failed to start Winsock failed, error: " << error;
                return false;
            }

            if (wsaData.wVersion != sockVersion)
            {
                Log(Log::Level::ERR) << "Incorrect Winsock version";
                WSACleanup();
                return false;
            }
#endif

            return true;
        }
    } // namespace network
} // namespace ouzel

Initialize Winsock only on Windows


#include "Database.h"

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

using namespace std;

Database::Database(string filename) {
  char filenameCharArray[100];
  strcpy(filenameCharArray, filename.c_str());
  sqlite3_open(filenameCharArray, &db);
}

Database::~Database() { sqlite3_close(db); }

int callback(void *res, int columns, char **data, char **) {
  vector<vector<string>> &results =
      *(static_cast<vector<vector<string>> *>(res));
  vector<string> row;

  for (int i = 0; i < columns; i++) {
    row.push_back(data[i] ? data[i] : "NULL");
    cout << data[i] << " ";
  }

  results.push_back(row);

  return 0;
}

vector<vector<string>> Database::execute(string command) const {
  cout << "Executing command: " << command << endl;
  vector<vector<string>> results;
  sqlite3_exec(db,              /* An open database */
               command.c_str(), /* SQL to be evaluated */
               callback,        /* Callback function */
               &results,        /* 1st argument to callback */
               0                /* Error msg written here */
               );
  return results;
}

#include "Database.h"

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

using namespace std;

Database::Database(string filename) {
  char filenameCharArray[100];
  strcpy(filenameCharArray, filename.c_str());
  sqlite3_open(filenameCharArray, &db);
}

Database::~Database() { sqlite3_close(db); }

int callback(void *res, int columns, char **data, char **) {
  vector<vector<string>> &results =
      *(static_cast<vector<vector<string>> *>(res));
  vector<string> row;

  for (int i = 0; i < columns; i++) {
    row.push_back(data[i] ? data[i] : "NULL");
    cout << data[i] << ", ";
  }

  results.push_back(row);

  return 0;
}

vector<vector<string>> Database::execute(string command) const {
  cout << "Executing SQL: " << command << endl;
  cout << "Data: ";
  vector<vector<string>> results;
  char *err;
  int status = sqlite3_exec(db,              /* An open database */
                            command.c_str(), /* SQL to be evaluated */
                            callback,        /* Callback function */
                            &results,        /* 1st argument to callback */
                            &err             /* Error msg written here */
                            );

  cout << endl;
  cout << "DB status: " << status;
  if (err) {
    cout << ", Error: " << err;
    sqlite3_free(err);
  }
  cout << endl;

  return results;
}

Add error messages for sqlite


#include <QtGui>
#include "mdi_background.h"

void QMdiAreaWBackground::resizeEvent(QResizeEvent *reEvent)
{
        size = reEvent->size();
        resize(size);
        QMdiArea::resizeEvent(reEvent);
}

void QMdiAreaWBackground::resize(QSize& size)
{
        setBackground(i.scaled(size));//,Qt::KeepAspectRatio);
}

void QMdiAreaWBackground::setBackgroundPath(QString& str) {
        i = QImage(str);
        resize(size);
}

QMdiAreaWBackground::QMdiAreaWBackground(QString& str)
{
        i = QImage(str);
}

#include <QtGui>
#include "mdi_background.h"

void QMdiAreaWBackground::resizeEvent(QResizeEvent *reEvent)
{
	size = reEvent->size();
	resize(size);
	QMdiArea::resizeEvent(reEvent);
}

void QMdiAreaWBackground::resize(QSize& size)
{
	/* XXX Conversion of image to the ARGB32 format is placed here because of setBackroung() works on Embox correctly
	 * only if the image is not opaque. I've looked for the method in which Qt determines that image is opaque,
	 * and discovered that ARGB32 format is a workaround for this problem.
	 * Also it is not obviously for me why _opaque_ images is not drawn while not-opaque is drawn... -- Alexander */
	setBackground((i.scaled(size)).convertToFormat(QImage::Format_ARGB32));//,Qt::KeepAspectRatio);
}

void QMdiAreaWBackground::setBackgroundPath(QString& str) {
	i = QImage(str);
	resize(size);
}

QMdiAreaWBackground::QMdiAreaWBackground(QString& str)
{
	i = QImage(str);
}

Change of wallpaper works on vnc


#include <cstring>

#include <Bull/Core/Log/Log.hpp>
#include <Bull/Core/Support/Win32/Windows.hpp>

#include <Bull/Core/System/Win32/ClipboardImpl.hpp>

namespace Bull
{
    namespace prv
    {
        void ClipboardImpl::flush()
        {
            if(OpenClipboard(nullptr))
            {
                EmptyClipboard();
            }
        }

        void ClipboardImpl::setContent(const String& content)
        {
            flush();

            if(!OpenClipboard(nullptr))
            {
                Log::getInstance()->error("Failed to open clipboard");
            }

            std::size_t size = (content.getSize() + 1) * sizeof(char);
            HANDLE handler = GlobalAlloc(CF_UNICODETEXT, size);

            if(handler)
            {
                std::memcpy(GlobalLock(handler), content.getBuffer(), size);
                GlobalUnlock(handler);
                SetClipboardData(CF_UNICODETEXT, handler);
            }

            CloseClipboard();
        }

        String ClipboardImpl::getContent()
        {
            String text;
            HANDLE clipboard;

            if(!OpenClipboard(nullptr))
            {
                Log::getInstance()->error("Failed to open clipboard");

                return text;
            }

            clipboard = GetClipboardData(CF_UNICODETEXT);

            if(clipboard)
            {
                Log::getInstance()->error("Failed to open clipboard");

                CloseClipboard();

                return text;
            }

            text = String(static_cast<const char*>(GlobalLock(clipboard)));
            GlobalUnlock(clipboard);

            CloseClipboard();

            return text;
        }
    }
}

#include <cstring>

#include <Bull/Core/Exception/Throw.hpp>
#include <Bull/Core/Support/Win32/Win32Error.hpp>
#include <Bull/Core/Support/Win32/Windows.hpp>
#include <Bull/Core/System/Win32/ClipboardImpl.hpp>

namespace Bull
{
    namespace prv
    {
        void ClipboardImpl::flush()
        {
            if(OpenClipboard(nullptr))
            {
                EmptyClipboard();
            }
        }

        void ClipboardImpl::setContent(const String& content)
        {
            flush();

            if(!OpenClipboard(nullptr))
            {
                Throw(Win32Error, "ClipboardImpl::setContent", "Failed to open clipboard");
            }

            std::size_t size = (content.getSize() + 1) * sizeof(char);
            HANDLE handler = GlobalAlloc(CF_UNICODETEXT, size);

            if(handler)
            {
                std::memcpy(GlobalLock(handler), content.getBuffer(), size);
                GlobalUnlock(handler);
                SetClipboardData(CF_UNICODETEXT, handler);
            }

            CloseClipboard();
        }

        String ClipboardImpl::getContent()
        {
            String text;
            HANDLE clipboard;

            if(!OpenClipboard(nullptr))
            {
                Throw(Win32Error, "ClipboardImpl::getContent", "Failed to open clipboard");
            }

            clipboard = GetClipboardData(CF_UNICODETEXT);

            if(clipboard)
            {
                Throw(Win32Error, "ClipboardImpl::getContent", "Failed to get clipboard content");
            }

            text = String(static_cast<const char*>(GlobalLock(clipboard)));
            GlobalUnlock(clipboard);

            CloseClipboard();

            return text;
        }
    }
}

Throw Win32Error in case of failure instead of just writing the log


//=======================================================================
// Copyright Baptiste Wicht 2013-2014.
// 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)
//=======================================================================

typedef unsigned int uint8_t __attribute__((__mode__(__QI__)));
typedef unsigned int uint16_t __attribute__ ((__mode__ (__HI__)));
typedef unsigned int uint32_t __attribute__ ((__mode__ (__SI__)));
typedef unsigned int uint64_t __attribute__ ((__mode__ (__DI__)));

uint8_t make_color(uint8_t fg, uint8_t bg){
    return fg | bg << 4;
}

uint16_t make_vga_entry(char c, uint8_t color){
    uint16_t c16 = c;
    uint16_t color16 = color;
    return c16 | color16 << 8;
}

int main(){
    uint16_t* vga_buffer = reinterpret_cast<uint16_t*>(0x0B8000);

    vga_buffer[10 * 80 + 40] = make_vga_entry('1', make_color(15, 0));

    return 0;
}

Modify one to use system call


#define BOOST_TEST_MODULE Gridcoin Test Suite
#include <boost/test/unit_test.hpp>

#include "db.h"
#include "main.h"
#include "wallet.h"

CWallet* pwalletMain;
CClientUIInterface uiInterface;

extern bool fPrintToConsole;
extern void noui_connect();

struct TestingSetup {
    TestingSetup() {
        fPrintToDebugger = true; // don't want to write to debug.log file
        noui_connect();
        bitdb.MakeMock();
        LoadBlockIndex(true);
        bool fFirstRun;
        pwalletMain = new CWallet("wallet.dat");
        pwalletMain->LoadWallet(fFirstRun);
        RegisterWallet(pwalletMain);
    }
    ~TestingSetup()
    {
        delete pwalletMain;
        pwalletMain = NULL;
        bitdb.Flush(true);
    }
};

BOOST_GLOBAL_FIXTURE(TestingSetup);

void Shutdown(void* parg)
{
  exit(0);
}

void StartShutdown()
{
  exit(0);
}

#define BOOST_TEST_MODULE Gridcoin Test Suite
#include <boost/test/unit_test.hpp>

#include "db.h"
#include "main.h"
#include "wallet.h"

CWallet* pwalletMain;
CClientUIInterface uiInterface;

extern bool fPrintToConsole;
extern void noui_connect();

struct TestingSetup {
    TestingSetup() {
        fPrintToDebugger = true; // don't want to write to debug.log file
        fUseFastIndex = true; // Don't verify block hashes when loading
        noui_connect();
        bitdb.MakeMock();
        LoadBlockIndex(true);
        bool fFirstRun;
        pwalletMain = new CWallet("wallet.dat");
        pwalletMain->LoadWallet(fFirstRun);
        RegisterWallet(pwalletMain);
    }
    ~TestingSetup()
    {
        delete pwalletMain;
        pwalletMain = NULL;
        bitdb.Flush(true);
    }
};

BOOST_GLOBAL_FIXTURE(TestingSetup);

void Shutdown(void* parg)
{
  exit(0);
}

void StartShutdown()
{
  exit(0);
}

Use fast block indices for faster test runner loading.


#include <Arduino.h>

//TODO(edcoyne): remove this when it is present upstream.
// Currently this is needed to use std::string on Arduino.
namespace std{
void __throw_out_of_range(const char* str) {
    panic();
}
}

#include <Arduino.h>

//TODO(edcoyne): remove this when it is present upstream.
// Currently this is needed to use std::string on Arduino.
namespace std{
void __attribute__((weak)) __throw_out_of_range(const char* str) {
    panic();
}
}

Change function to weak declaration