#include "VolumeSlider.h"

#include "Skin.h"

VolumeSlider::VolumeSlider(HINSTANCE hInstance, Settings &settings) :
OSD(hInstance, L"3RVX-VolumeSlider", settings),
_mWnd(hInstance, L"3RVX-VolumeSliderWnd", L"3RVX Volume Slider") {

    std::wstring skinXML = settings.SkinXML();
    Skin skin(skinXML);

    long styles = GetWindowLongPtr(_mWnd.HWnd(), GWL_EXSTYLE);
    styles &= ~(WS_EX_NOACTIVATE | WS_EX_TRANSPARENT);
    SetWindowLongPtr(_mWnd.HWnd(), GWL_EXSTYLE, styles);

    Gdiplus::Bitmap *bg = skin.ControllerBgImg("volume");
    _mWnd.BackgroundImage(bg);
    _mWnd.Update();
    _mWnd.Show();

}

void VolumeSlider::Hide() {
    _mWnd.Hide(false);
}

#include "VolumeSlider.h"

#include "Skin.h"

VolumeSlider::VolumeSlider(HINSTANCE hInstance, Settings &settings) :
OSD(hInstance, L"3RVX-VolumeSlider", settings),
_sWnd(hInstance, L"3RVX-VolumeSliderWnd", L"3RVX Volume Slider") {

    std::wstring skinXML = settings.SkinXML();
    Skin skin(skinXML);

    Gdiplus::Bitmap *bg = skin.ControllerBgImg("volume");
    _sWnd.BackgroundImage(bg);
    _sWnd.Update();
    _sWnd.Show();
}

void VolumeSlider::Hide() {
    _sWnd.Hide(false);
}

Update for new SliderWnd class


#include "mainwindow.h"

#include "bucketlist.h"

#include <QLabel>
#include <QBoxLayout>
#include <QtWebKit>
#include <QSettings>
#include <QInputDialog>

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent)
{
    QWidget *central = new QWidget;
    setCentralWidget(central);

    QBoxLayout *topLayout = new QHBoxLayout(central);

    BucketList *bucketList = new BucketList;
    topLayout->addWidget(bucketList);

    m_view = new QWebView;
    topLayout->addWidget(m_view);

    getServerPath();

    connect(&m_server, SIGNAL(started()), SLOT(loadView()));
    m_server.start();
}

MainWindow::~MainWindow()
{
    m_server.stop();
}

void MainWindow::getServerPath()
{
    QSettings settings;

    QString path = settings.value("view/path").toString();
    if (path.isEmpty()) {
        path = QInputDialog::getText(this, "View path", "Enter base path of view for web server");
    }
    settings.setValue("view/path", path);

    m_server.setPath(path);
}

void MainWindow::loadView()
{
    m_view->setUrl(QUrl("http://localhost:8765"));
    m_view->show();
}

#include "mainwindow.h"

#include "bucketlist.h"

#include <QLabel>
#include <QBoxLayout>
#include <QtWebKit>
#include <QSettings>
#include <QInputDialog>

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent)
{
    QWidget *central = new QWidget;
    setCentralWidget(central);

    QBoxLayout *topLayout = new QHBoxLayout(central);

    BucketList *bucketList = new BucketList;
    topLayout->addWidget(bucketList);

    m_view = new QWebView;
    topLayout->addWidget(m_view, 1);
    m_view->setMinimumSize(1000, 540);

    getServerPath();

    connect(&m_server, SIGNAL(started()), SLOT(loadView()));
    m_server.start();
}

MainWindow::~MainWindow()
{
    m_server.stop();
}

void MainWindow::getServerPath()
{
    QSettings settings;

    QString path = settings.value("view/path").toString();
    if (path.isEmpty()) {
        path = QInputDialog::getText(this, "View path", "Enter base path of view for web server");
    }
    settings.setValue("view/path", path);

    m_server.setPath(path);
}

void MainWindow::loadView()
{
    m_view->setUrl(QUrl("http://localhost:8765"));
    m_view->show();
}

Make widget always fit the view


// Copyright 2015 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 "chromeos/system/devicetype.h"

#include <string>

#include "base/sys_info.h"

namespace chromeos {

namespace {
const char kDeviceType[] = "CHROMEOS_DEVICE_TYPE";
}

DeviceType GetDeviceType() {
  std::string value;
  if (base::SysInfo::GetLsbReleaseValue(kDeviceType, &value)) {
    if (value == "CHROMEBASE")
      return DeviceType::kChromebase;
    else if (value == "CHROMEBIT")
      return DeviceType::kChromebit;
    // Most devices are Chromebooks, so we will also consider reference boards
    // as chromebooks.
    else if (value == "CHROMEBOOK" || value == "REFERENCE")
      return DeviceType::kChromebook;
    else if (value == "CHROMEBOX")
      return DeviceType::kChromebox;
    else
      LOG(ERROR) << "Unknown device type \"" << value << "\"";
  }

  return DeviceType::kUnknown;
}

}  // namespace chromeos

// Copyright 2015 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 "chromeos/system/devicetype.h"

#include <string>

#include "base/sys_info.h"

namespace chromeos {

namespace {
const char kDeviceType[] = "DEVICETYPE";
}

DeviceType GetDeviceType() {
  std::string value;
  if (base::SysInfo::GetLsbReleaseValue(kDeviceType, &value)) {
    if (value == "CHROMEBASE")
      return DeviceType::kChromebase;
    else if (value == "CHROMEBIT")
      return DeviceType::kChromebit;
    // Most devices are Chromebooks, so we will also consider reference boards
    // as chromebooks.
    else if (value == "CHROMEBOOK" || value == "REFERENCE")
      return DeviceType::kChromebook;
    else if (value == "CHROMEBOX")
      return DeviceType::kChromebox;
    else
      LOG(ERROR) << "Unknown device type \"" << value << "\"";
  }

  return DeviceType::kUnknown;
}

}  // namespace chromeos

Use the correct lsb key when fetching the CrOS device type.


#include <3ds.h>
#include <stdio.h>

void shutdown3DS()
{
	Handle nssHandle = 0;
	Result result = srvGetServiceHandle(&nssHandle, "ns:s");
	if (result != 0)
		return;

	// http://3dbrew.org/wiki/NSS:ShutdownAsync

	u32 *commandBuffer = getThreadCommandBuffer();
	commandBuffer[0] = 0x000E0000;

	svcSendSyncRequest(nssHandle);
	svcCloseHandle(nssHandle);
}

int main(int argc, char **argv)
{
	shutdown3DS();

	// Hack: the 3ds crashes ("An error has occcurred.") for some reason
	// without one iteration of the APT main loop.
	aptMainLoop();
	return 0;
}

#include <3ds.h>
#include <stdio.h>

// http://3dbrew.org/wiki/NSS:ShutdownAsync
void NSS_ShutdownAsync(void)
{
	Handle nssHandle = 0;
	Result result = srvGetServiceHandle(&nssHandle, "ns:s");
	if (result != 0)
		return;

	u32 *commandBuffer = getThreadCommandBuffer();
	commandBuffer[0] = 0x000E0000;

	svcSendSyncRequest(nssHandle);
	svcCloseHandle(nssHandle);
}

int main(int argc, char **argv)
{
	NSS_ShutdownAsync();

	// Hack: the 3ds crashes ("An error has occcurred.") for some reason
	// without one iteration of the APT main loop.
	aptMainLoop();
	return 0;
}

Call it NSS_ShutdownAsync instead of shutdown3DS.


#include "Name.h"

bool Name::init(String name) {
    size = name.length() + 1;

    data = (uint8_t *) malloc(size);

    if (data != NULL) {
        uint8_t lastDot = size;

        for (uint8_t i = size - 1; i > 0; i--) {
            uint8_t c = name.charAt(i - 1);

            if (c == '.') {
                data[i] = lastDot - i - 1;
                lastDot = i;
            } else {
                data[i] = c;
            }
        }

        data[0] = lastDot - 1;
    }

    return data != NULL;
}

uint8_t Name::getSize() {
    return size;
}

bool Name::match(uint8_t c) {
    matches &= data[matchOffset++] = c;

    return matches;
}

void Name::write(Buffer buffer) {
    if (writtenOffset == 0) {
        writtenOffset = buffer.getOffset();

        for (int i = 0; i < size; i++) {
            buffer.writeUInt8(data[i]);
        }
    } else {
        buffer.writeUInt16((BACK_REF << 8) | writtenOffset);
    }
}

void Name::reset() {
    matches = true;
    matchOffset = 0;
    writtenOffset = 0;
}

#include "Name.h"

bool Name::init(String name) {
    size = name.length() + 1;

    data = (uint8_t *) malloc(size);

    if (data != NULL) {
        uint8_t lastDot = size;

        for (uint8_t i = size - 1; i > 0; i--) {
            uint8_t c = name.charAt(i - 1);

            if (c == '.') {
                data[i] = lastDot - i - 1;
                lastDot = i;
            } else {
                data[i] = c;
            }
        }

        data[0] = lastDot - 1;
    }

    return data != NULL;
}

uint8_t Name::getSize() {
    return size;
}

bool Name::match(uint8_t c) {
    matches = matches && matchOffset < size && data[matchOffset++] == c;

    return matches;
}

void Name::write(Buffer buffer) {
    if (writtenOffset == 0) {
        writtenOffset = buffer.getOffset();

        for (int i = 0; i < size; i++) {
            buffer.writeUInt8(data[i]);
        }
    } else {
        buffer.writeUInt16((BACK_REF << 8) | writtenOffset);
    }
}

void Name::reset() {
    matches = true;
    matchOffset = 0;
    writtenOffset = 0;
}

Correct buffer overflow in match(...)


#include "./Sphere.hpp"
#include "./misc.hpp"
#include <algorithm>
#include <cmath>

namespace yks {

	Optional<float> intersect(const vec3& origin, float radius, const Ray& r) {
		const vec3 o = r.origin - origin;
		const vec3 v = r.direction;

		float t1, t2;
		const int solutions = solve_quadratic(dot(v, v), 2*dot(o, v), dot(o, o) - radius*radius, t1, t2);

		if (solutions == 0) {
			return Optional<float>();
		} else if (solutions == 1) {
			return make_optional<float>(t1);
		} else {
			return make_optional<float>(std::min(t1, t2));
		}
	}

	vec3 uniform_point_on_sphere(float a, float b) {
		const float y = 2.0f * a - 1.0f;
		const float latitude = std::asin(y);
		const float longitude = b * two_pi;

		return mvec3(cos(latitude) * cos(longitude), y, cos(latitude) * sin(longitude));
	}

}

#include "./Sphere.hpp"
#include "./misc.hpp"
#include <algorithm>
#include <cmath>

namespace yks {

	Optional<float> intersect(const vec3& origin, float radius, const Ray& r) {
		const vec3 o = r.origin - origin;
		const vec3 v = r.direction;

		float t1, t2;
		const int solutions = solve_quadratic(dot(v, v), 2*dot(o, v), dot(o, o) - radius*radius, t1, t2);

		if (solutions == 0) {
			return Optional<float>();
		} else if (solutions == 1) {
			return make_optional<float>(t1);
		} else {
			return make_optional<float>(std::min(t1, t2));
		}
	}

	vec3 uniform_point_on_sphere(float a, float b) {
		const float y = 2.0f * a - 1.0f;
		const float latitude = std::asin(y);
		const float longitude = b * two_pi;
		const float cos_latitude = std::cos(latitude);

		return mvec3(cos_latitude * cos(longitude), y, cos_latitude * sin(longitude));
	}

}

Remove duplicated call to std::cos


// RUN: %clang -### -Wlarge-by-value-copy %s 2>&1 | FileCheck -check-prefix=LARGE_VALUE_COPY_DEFAULT %s
// LARGE_VALUE_COPY_DEFAULT: -Wlarge-by-value-copy=64
// RUN: %clang -### -Wlarge-by-value-copy=128 %s 2>&1 | FileCheck -check-prefix=LARGE_VALUE_COPY_JOINED %s
// LARGE_VALUE_COPY_JOINED: -Wlarge-by-value-copy=128

// RUN: %clang -### -c -Wmonkey -Wno-monkey -Wno-unused-command-line-arguments \
// RUN:        -Wno-unused-command-line-argument %s 2>&1 | FileCheck %s
// CHECK: unknown warning option '-Wmonkey'
// CHECK: unknown warning option '-Wno-monkey'
// CHECK: unknown warning option '-Wno-unused-command-line-arguments'; did you mean '-Wno-unused-command-line-argument'?

// FIXME: Remove this together with -Warc-abi once an Xcode is released that doesn't pass this flag.
// RUN: %clang -### -Warc-abi -Wno-arc-abi %s 2>&1 | FileCheck -check-prefix=ARCABI %s
// ARCABI-NOT: unknown warning option '-Warc-abi'
// ARCABI-NOT: unknown warning option '-Wno-arc-abi'

Add a test for -Warc-abi as requested by Fariborz.


#include "rdb_protocol/configured_limits.hpp"
#include "rdb_protocol/wire_func.hpp"
#include "rdb_protocol/func.hpp"

namespace ql {
configured_limits_t
from_optargs(const std::map<std::string, wire_func_t> &arguments)
{
    auto p = arguments.find("arrayLimit");
    if (p != arguments.end()) {
        // Fake an environment with no arguments.
        cond_t cond;
        rdb_context_t context;
        // Can't use the original arguments, because it will cause an infinite loop.
        env_t env(&context, &cond, std::map<std::string, wire_func_t>(),
                  profile_bool_t::DONT_PROFILE);
        return configured_limits_t((*p).second.compile_wire_func()->call(&env)->as_int());
    } else {
        return configured_limits_t();
    }
}

} // namespace ql

#include "rdb_protocol/configured_limits.hpp"
#include "rdb_protocol/wire_func.hpp"
#include "rdb_protocol/func.hpp"

namespace ql {
configured_limits_t
from_optargs(const std::map<std::string, wire_func_t> &arguments)
{
    auto p = arguments.find("arrayLimit");
    if (p != arguments.end()) {
        // Fake an environment with no arguments.  We have to fake it
        // because of a chicken/egg problem; this function gets called
        // before there are any extant environments at all.  Only
        // because we use an empty argument list do we prevent an
        // infinite loop.
        cond_t cond;
        rdb_context_t context;
        env_t env(&context, &cond, std::map<std::string, wire_func_t>(),
                  profile_bool_t::DONT_PROFILE);
        return configured_limits_t((*p).second.compile_wire_func()->call(&env)->as_int());
    } else {
        return configured_limits_t();
    }
}

} // namespace ql

Expand on why we need a fake, here.


//===---------------------------- temporary.cpp ---------------------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is dual licensed under the MIT and the University of Illinois Open
// Source Licenses. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//

#pragma GCC visibility push(default)

extern "C"
{

void (*__cxa_new_handler)() = 0;
void (*__cxa_terminate_handler)() = 0;
void (*__cxa_unexpected_handler)() = 0;

}

#pragma GCC visibility pop

//===---------------------------- temporary.cpp ---------------------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is dual licensed under the MIT and the University of Illinois Open
// Source Licenses. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//

#include "abort_message.h"

#pragma GCC visibility push(default)

extern "C"
{

static
void f()
{
    abort_message("this shouldn't be called");
}

void (*__cxa_new_handler)() = f;
void (*__cxa_terminate_handler)() = f;
void (*__cxa_unexpected_handler)() = f;

}

#pragma GCC visibility pop

Add a little paranoia for testing purposes.


/*
 * main.cpp
 *
 * Copyright (C) 2018 [ A Legge Up ]
 *
 * This software may be modified and distributed under the terms
 * of the MIT license.  See the LICENSE file for details.
 */

#include <stdio.h>

#include "HardwareConfig.h"
#include "AnimationTask.h"

extern "C" void app_main()
{
    HardwareConfig hardwareConfig(HardwareConfig::DEV0);
    AnimationTask *pAnimationTask = new AnimationTask("AnimationTask");
    pAnimationTask->start();
}

/*
 * main.cpp
 *
 * Copyright (C) 2018 [ A Legge Up ]
 *
 * This software may be modified and distributed under the terms
 * of the MIT license.  See the LICENSE file for details.
 */

#include <stdio.h>

#include "HardwareConfig.h"
#include "AnimationTask.h"

extern "C" void app_main()
{
    HardwareConfig hardwareConfig(HardwareConfig::DEV0);
    AnimationTask *pAnimationTask = new AnimationTask("AnimationTask");
    pAnimationTask->start(0);
}

Add a throw-away parameter for task start to remove warning


#include "rssitem.h"

#include "3rd-party/catch.hpp"
#include "cache.h"
#include "configcontainer.h"

using namespace newsboat;

TEST_CASE("RssItem::sort_flags() cleans up flags", "[rss]")
{
	ConfigContainer cfg;
	Cache rsscache(":memory:", &cfg);
	RssItem item(&rsscache);

	SECTION("Repeated letters do not erase other letters") {
		std::string inputflags = "Abcdecf";
		std::string result = "Abcdef";
		item.set_flags(inputflags);
		REQUIRE(result == item.flags());
	}

	SECTION("Non alpha characters in input flags are ignored") {
		std::string inputflags = "Abcd";
		item.set_flags(inputflags + "1234568790^\"#'é(£");
		REQUIRE(inputflags == item.flags());
	}
}

#include "rssitem.h"

#include "3rd-party/catch.hpp"
#include "cache.h"
#include "configcontainer.h"

using namespace newsboat;

TEST_CASE("RssItem::sort_flags() cleans up flags", "[RssItem]")
{
	ConfigContainer cfg;
	Cache rsscache(":memory:", &cfg);
	RssItem item(&rsscache);

	SECTION("Repeated letters do not erase other letters") {
		std::string inputflags = "Abcdecf";
		std::string result = "Abcdef";
		item.set_flags(inputflags);
		REQUIRE(result == item.flags());
	}

	SECTION("Non alpha characters in input flags are ignored") {
		std::string inputflags = "Abcd";
		item.set_flags(inputflags + "1234568790^\"#'é(£");
		REQUIRE(inputflags == item.flags());
	}
}

Mark RssItem tests with appropriate tag


#include "Renderer.hpp"
#include "Window.hpp"
#include <cstring>
#include <iostream>
#include "Particle.png.hpp"

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

    bool measure = false;
    if (argc > 1 && strcmp(argv[1], "measure") == 0) {
        std::cout << "Measuring..." << std::endl;
        measure = true;
    }

    Renderer* renderer = new Renderer(window);
    renderer->setTexture(PARTICLE_PNG, PARTICLE_PNG_LENGTH);

    double lastTime = glfwGetTime();
    while(!glfwWindowShouldClose(window.getWindow())){
        glfwPollEvents();

        double deltaTime = glfwGetTime() - lastTime;
        lastTime = glfwGetTime();

        renderer->update(deltaTime);
        renderer->render();

        glfwSwapBuffers(window.getWindow());
    }

    delete renderer;

    return 0;
}

#include "Renderer.hpp"
#include "Window.hpp"
#include <cstring>
#include <iostream>
#include "Particle.png.hpp"

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

    bool measure = false;
    if (argc > 1 && strcmp(argv[1], "measure") == 0) {
        std::cout << "Measuring..." << std::endl;
        measure = true;
    }

    Renderer* renderer = new Renderer(window);
    renderer->setTexture(PARTICLE_PNG, PARTICLE_PNG_LENGTH);

    double lastTime = glfwGetTime();
    while(!glfwWindowShouldClose(window.getWindow())){
        glfwPollEvents();

        double deltaTime = glfwGetTime() - lastTime;
        lastTime = glfwGetTime();

        renderer->update(measure ? 1.0/60.0 : deltaTime);
        renderer->render();

        glfwSwapBuffers(window.getWindow());
    }

    delete renderer;

    return 0;
}

Use constant delta time when in measure mode


// If user provides his own libc functions, ASan doesn't
// intercept these functions.

// RUN: %clangxx_asan -O0 %s -o %t && %run %t 2>&1 | FileCheck %s
// RUN: %clangxx_asan -O1 %s -o %t && %run %t 2>&1 | FileCheck %s
// RUN: %clangxx_asan -O2 %s -o %t && %run %t 2>&1 | FileCheck %s
// RUN: %clangxx_asan -O3 %s -o %t && %run %t 2>&1 | FileCheck %s
// XFAIL: freebsd

// On Windows, defining strtoll in a static build results in linker errors, but
// it works with the dynamic runtime.
// XFAIL: win32-static-asan

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

extern "C" long strtol(const char *nptr, char **endptr, int base) {
  fprintf(stderr, "my_strtol_interceptor\n");
  if (endptr)
    *endptr = (char*)nptr + strlen(nptr);
  return 0;
}

int main() {
  char *x = (char*)malloc(10 * sizeof(char));
  free(x);
  return (int)strtol(x, 0, 10);
  // CHECK: my_strtol_interceptor
  // CHECK-NOT: heap-use-after-free
}

// If user provides his own libc functions, ASan doesn't
// intercept these functions.

// RUN: %clangxx_asan -O0 %s -o %t && %run %t 2>&1 | FileCheck %s
// RUN: %clangxx_asan -O1 %s -o %t && %run %t 2>&1 | FileCheck %s
// RUN: %clangxx_asan -O2 %s -o %t && %run %t 2>&1 | FileCheck %s
// RUN: %clangxx_asan -O3 %s -o %t && %run %t 2>&1 | FileCheck %s
// XFAIL: freebsd

// On Windows, defining strtoll in a static build results in linker errors, but
// it works with the dynamic runtime.
// XFAIL: win32-static-asan

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

extern "C" long strtol(const char *nptr, char **endptr, int base) {
  fprintf(stderr, "my_strtol_interceptor\n");
  if (endptr)
    *endptr = (char*)nptr + strlen(nptr);
  return 0;
}

int main() {
  char *x = (char*)malloc(10 * sizeof(char));
  free(x);
  return (int)strtol(x, 0, 10);
  // CHECK: my_strtol_interceptor
  // CHECK-NOT: heap-use-after-free
}

Add missing header in a test.


#include "iomidi.h"
#include "db.h"

#include <QtTest>

class TestIOMIdi : public QObject
{
    Q_OBJECT

private slots:
    void test_handle();
    void test_clientId();
    void test_portId();

private:
    IOMidi io;
};

void TestIOMIdi::test_handle()
{
    snd_seq_t* seq = io.handle();
    QVERIFY(seq);

    snd_seq_client_info_t *info;
    snd_seq_client_info_alloca(&info);
    QCOMPARE(snd_seq_get_client_info(seq, info), 0);
    QVERIFY(!QString(snd_seq_client_info_get_name(info)).isNull());
}

void TestIOMIdi::test_clientId()
{
    QVERIFY(io.clientId() > 0);
}

void TestIOMIdi::test_portId()
{
    QVERIFY(io.clientId() > 0);
}

QTEST_APPLESS_MAIN(TestIOMIdi)

#include "tst_iomidi.moc"

#include "iomidi.h"
#include "db.h"

#include <QtTest>

class TestIOMIdi : public QObject
{
    Q_OBJECT

private slots:
    void initTestCase();

    void test_handle();
    void test_clientId();
    void test_portId();

private:
    IOMidi* io;
};

void TestIOMIdi::initTestCase() {
    io = nullptr;
    try {
        io = new IOMidi(this);
    }
    catch (const std::exception&) {
    }
}

void TestIOMIdi::test_handle()
{
    if (!io) {
        return;
    }

    snd_seq_t* seq = io->handle();
    QVERIFY(seq);

    snd_seq_client_info_t *info;
    snd_seq_client_info_alloca(&info);
    QCOMPARE(snd_seq_get_client_info(seq, info), 0);
    QVERIFY(!QString(snd_seq_client_info_get_name(info)).isNull());
}

void TestIOMIdi::test_clientId()
{
    if (!io) {
        return;
    }

    QVERIFY(io->clientId() > 0);
}

void TestIOMIdi::test_portId()
{
    if (!io) {
        return;
    }

    QVERIFY(io->clientId() > 0);
}

QTEST_APPLESS_MAIN(TestIOMIdi)

#include "tst_iomidi.moc"

Fix breaking tests when sequencer can not be opened


#include <iostream>

#include "ignition/transport.hh"

#include "fcmt/ign_nodes/examples/proto/echo.pb.h"

int main(int argc, char *argv[]) {
  auto i = 0;
  while (true) {
    ignition::transport::Node node;
    fcmt::ign_nodes::examples::proto::EchoRequest request;
    request.set_value(i++);
    fcmt::ign_nodes::examples::proto::EchoReply reply;
    bool result = false;
    auto timeout = 5000;
    auto executed = node.Request("/echo", request, timeout, reply, result);
    if (executed) {
      if (result) {
        std::cout << "Reply: [" << reply.value() << "]" << std::endl;
      }
      else {
        std::cout << "Service call failed" << std::endl;
      }
    } else {
      std::cerr << "Service call timed out" << std::endl;
    }
  }
}

#include <iostream>

#include "ignition/transport.hh"

#include "fcmt/ign_nodes/examples/proto/echo.pb.h"

int main(int argc, char *argv[]) {
  auto i = 0;
  ignition::transport::Node node;
  while (true) {
    fcmt::ign_nodes::examples::proto::EchoRequest request;
    request.set_value(i++);
    fcmt::ign_nodes::examples::proto::EchoReply reply;
    bool result = false;
    auto timeout = 5000;
    auto executed = node.Request("/echo", request, timeout, reply, result);
    if (executed) {
      if (result) {
        std::cout << "Reply: [" << reply.value() << "]" << std::endl;
      }
      else {
        std::cout << "Service call failed" << std::endl;
      }
    } else {
      std::cerr << "Service call timed out" << std::endl;
    }
  }
}

Create node once in ign_nodes_examples_client


//===----------------------------------------------------------------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is dual licensed under the MIT and the University of Illinois Open
// Source Licenses. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//

// <streambuf>

// template <class charT, class traits = char_traits<charT> >
// class basic_streambuf;

// void pbump(int n);
//
// REQUIRES: long_tests

#include <sstream>
#include <cassert>
#include "test_macros.h"

struct SB : std::stringbuf
{
  SB() : std::stringbuf(std::ios::ate|std::ios::out) { }
  const char* pubpbase() const { return pbase(); }
  const char* pubpptr() const { return pptr(); }
};

int main()
{
#ifndef TEST_HAS_NO_EXCEPTIONS
    try {
#endif
    	std::string str(2147483648, 'a');
		SB sb;
		sb.str(str);
		assert(sb.pubpbase() <= sb.pubpptr());
#ifndef TEST_HAS_NO_EXCEPTIONS
	}
	catch (const std::bad_alloc &) {}
#endif
}

//===----------------------------------------------------------------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is dual licensed under the MIT and the University of Illinois Open
// Source Licenses. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//

// <streambuf>

// template <class charT, class traits = char_traits<charT> >
// class basic_streambuf;

// void pbump(int n);
//
// REQUIRES: long_tests

#include <sstream>
#include <cassert>
#include "test_macros.h"

struct SB : std::stringbuf
{
  SB() : std::stringbuf(std::ios::ate|std::ios::out) { }
  const char* pubpbase() const { return pbase(); }
  const char* pubpptr() const { return pptr(); }
};

int main()
{
#ifndef TEST_HAS_NO_EXCEPTIONS
    try {
#endif
        std::string str(2147483648, 'a');
        SB sb;
        sb.str(str);
        assert(sb.pubpbase() <= sb.pubpptr());
#ifndef TEST_HAS_NO_EXCEPTIONS
    }
    catch (const std::length_error &) {} // maybe the string can't take 2GB
    catch (const std::bad_alloc    &) {} // maybe we don't have enough RAM
#endif
}

Add a catch for std::length_error for the case where the string can't handle 2GB. (like say 32-bit big-endian)


/* RTcmix  - Copyright (C) 2000  The RTcmix Development Team
   See ``AUTHORS'' for a list of contributors. See ``LICENSE'' for
   the license to this software and for a DISCLAIMER OF ALL WARRANTIES.
*/
#include <RTcmix.h>
#include <Instrument.h>
#include <ugens.h>

int Instrument::rtsetoutput(float start, float dur, Instrument *theInst)
{
  // DS: Adding check to be sure rtoutput() did not fail.

  if (!RTcmix::outputOpen()) {
  	 die(theInst->name(),
		 "rtsetoutput: No output open for this instrument (rtoutput failed?)!");
	 return -1;
  }

	if (start < 0.0f) {
		die(theInst->name(),
			"rtsetoutput: start time must be >= 0.0");
		return -1;
	}
	if (dur < 0.0f) {
		die(theInst->name(),
			"rtsetoutput: duration must be >= 0.0");
		return -1;
	}

  theInst->_start = start;
  theInst->_dur = dur;
  theInst->_nsamps = (int)(0.5 + dur * RTcmix::sr());

  return 0;
}

/* RTcmix  - Copyright (C) 2000  The RTcmix Development Team
   See ``AUTHORS'' for a list of contributors. See ``LICENSE'' for
   the license to this software and for a DISCLAIMER OF ALL WARRANTIES.
*/
#include <RTcmix.h>
#include <Instrument.h>
#include <ugens.h>

int Instrument::rtsetoutput(float start, float dur, Instrument *theInst)
{
  // DS: Adding check to be sure rtoutput() did not fail.

  if (!RTcmix::outputOpen()) {
  	 die(theInst->name(),
		 "rtsetoutput: No output open for this instrument (rtoutput failed?)!");
	 return -1;
  }

	if (start < 0.0f) {
		die(theInst->name(),
			"rtsetoutput: start time must be >= 0.0");
		return -1;
	}
	if (dur < 0.0f) {
		die(theInst->name(),
			"rtsetoutput: duration must be >= 0.0");
		return -1;
	}

  theInst->_start = start;
  theInst->_dur = dur;
  theInst->_nsamps = (int)(0.5 + dur * RTcmix::sr());
	if (theInst->_nsamps < 0) {
		rtcmix_warn(theInst->name(), "rtsetoutput: sample count exceeds MAXINT - limiting");
		theInst->_nsamps = INT_MAX;
	}

  return 0;
}

Add code to catch NSAMPS size wraparound.


#include "mainwindow.h"
#include <QApplication>

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    MainWindow w;
    w.show();

    return a.exec();
}

#include "mainwindow.h"
#include <QApplication>

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    std::locale::global( std::locale( "C" ) );
    MainWindow w;
    w.show();

    return a.exec();
}

Set local to C. Maybe not the best longterm solution.


// RUN: %clang_cc1 %s -g -S -emit-llvm -o - | FileCheck %s

// FIXME: Failing on i686.
// XFAIL: *
// RUN: %clang_cc1 -triple i686-linux %s -g -S -emit-llvm -o - | FileCheck %s

struct A {
  virtual void f();
};

struct B {
  virtual void f();
};

struct C : A, B {
  virtual void f();
};

void C::f() { }

// CHECK: [ DW_TAG_subprogram ] [line 15] [def] [_ZThn8_N1C1fEv]

// RUN: %clang_cc1 %s -g -S -emit-llvm -o - | FileCheck %s

struct A {
  virtual void f();
};

struct B {
  virtual void f();
};

struct C : A, B {
  virtual void f();
};

void C::f() { }

// CHECK: [ DW_TAG_subprogram ] [line 15] [def] [_ZThn{{4|8}}_N1C1fEv]

Fix test suppressed in r166683 on 32-bit Linux


// RUN: %clang_cc1 -triple x86_64-apple-darwin -emit-llvm -debug-info-kind=line-tables-only %s -o - | FileCheck %s
// Crasher for PR22929.
class Base {
  virtual void VariadicFunction(...);
};

class Derived : public virtual Base {
  virtual void VariadicFunction(...);
};

void Derived::VariadicFunction(...) { }

// CHECK: define void @_ZN7Derived16VariadicFunctionEz({{.*}} !dbg ![[SP:[0-9]+]]
// CHECK: ret void, !dbg ![[LOC:[0-9]+]]
// CHECK: define void @_ZT{{.+}}N7Derived16VariadicFunctionEz({{.*}} !dbg ![[SP_I:[0-9]+]]
// CHECK: ret void, !dbg ![[LOC_I:[0-9]+]]
//
// CHECK: ![[SP]] = distinct !DISubprogram(name: "VariadicFunction"
// CHECK: ![[LOC]] = !DILocation({{.*}}scope: ![[SP]])
// CHECK: ![[SP_I]] = distinct !DISubprogram(name: "VariadicFunction"
// CHECK: ![[LOC_I]] = !DILocation({{.*}}scope: ![[SP_I]])

// RUN: %clang_cc1 -triple x86_64-apple-darwin -emit-llvm -debug-info-kind=line-tables-only %s -o - | FileCheck %s
// Crasher for PR22929.
class Base {
  virtual void VariadicFunction(...);
};

class Derived : public virtual Base {
  virtual void VariadicFunction(...);
};

void Derived::VariadicFunction(...) { }

// CHECK: define void @_ZN7Derived16VariadicFunctionEz({{.*}} !dbg ![[SP:[0-9]+]]
// CHECK: ret void, !dbg ![[LOC:[0-9]+]]
// CHECK-LABEL: define void @_ZT{{.+}}N7Derived16VariadicFunctionEz(
// CHECK: ret void, !dbg ![[LOC:[0-9]+]]
//
// CHECK: ![[SP]] = distinct !DISubprogram(name: "VariadicFunction"
// CHECK: ![[LOC]] = !DILocation({{.*}}scope: ![[SP]])

Revert r302476 "Update testcase for upstream LLVM changes."


#include "dota2api/gamemode.cpp"
#include "gtest/gtest.h"

TEST(GameMode, gameModeFromInt)
{
    EXPECT_EQ
        (
         dota2::GameMode::Unknown,
         dota2::gameModeFromInt(-1)
        );
    for(const auto &mode : dota2::gameModes)
    {
        EXPECT_EQ
            (
            mode.second,
            dota2::gameModeFromInt(mode.first)
            );
    }
}

#include "dota2api/gamemode.hpp"
#include "gtest/gtest.h"

TEST(GameMode, gameModeFromInt)
{
    EXPECT_EQ
        (
         dota2::GameMode::Unknown,
         dota2::gameModeFromInt(-1)
        );
    for(const auto &mode : dota2::gameModes)
    {
        EXPECT_EQ
            (
            mode.second,
            dota2::gameModeFromInt(mode.first)
            );
    }
}

Include header file instead of cpp


#include "kobjects.h"
#include "constants.h"

#define PAGE_SIZE 0x1000

KCodeSet* FindTitleCodeSet(u64 title_id)
{
    for (unsigned kproc_index = 0; kproc_index < kproc_num; kproc_index++) {
        KCodeSet* curr_codeset = (KCodeSet*)(kproc_start + kproc_size * kproc_index + kproc_codeset_offset);
        if (curr_codeset != nullptr && curr_codeset->title_id == title_id)
            return curr_codeset;
    }
    return nullptr;
}

u32 FindCodeOffsetKAddr(KCodeSet* code_set, u32 code_offset)
{
    u32 curr_offset = 0;

    if (code_set == nullptr)
        return 0;

    KLinkedListNode* node = code_set->text_info.first_node;

    // Iterate through all the blocks in the codeset
    do {
        KBlockInfo* block_info = (KBlockInfo*)node->data;
        u32 block_size = block_info->page_count * PAGE_SIZE;

        // The code offset is within this block
        if (code_offset > curr_offset && code_offset < curr_offset + block_size)
            return block_info->mem_section_start + (code_offset - curr_offset);

        // Current offset: amount of bytes searched so far
        curr_offset += block_size;
        node = node->next;
    } while (node->next != nullptr);

    return 0;
}

#include "kobjects.h"
#include "constants.h"

#define PAGE_SIZE 0x1000

KCodeSet* FindTitleCodeSet(u64 title_id)
{
    for (unsigned kproc_index = 0; kproc_index < kproc_num; kproc_index++) {
        KCodeSet* curr_codeset = *(KCodeSet**)(kproc_start + kproc_size * kproc_index + kproc_codeset_offset);
        if (curr_codeset != nullptr && curr_codeset->title_id == title_id)
            return curr_codeset;
    }
    return nullptr;
}

u32 FindCodeOffsetKAddr(KCodeSet* code_set, u32 code_offset)
{
    u32 curr_offset = 0;

    if (code_set == nullptr)
        return 0;

    KLinkedListNode* node = code_set->text_info.first_node;

    // Iterate through all the blocks in the codeset
    do {
        KBlockInfo* block_info = (KBlockInfo*)node->data;
        u32 block_size = block_info->page_count * PAGE_SIZE;

        // The code offset is within this block
        if (code_offset > curr_offset && code_offset < curr_offset + block_size)
            return block_info->mem_section_start + (code_offset - curr_offset);

        // Current offset: amount of bytes searched so far
        curr_offset += block_size;
        node = node->next;
    } while (node->next != nullptr);

    return 0;
}

Fix bug where we were using a KCodeSet** as a KCodeSet* in codeset finding


// Copyright (c) 2012 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 "content/public/test/layouttest_support.h"

#include "base/callback.h"
#include "base/lazy_instance.h"
#include "content/renderer/render_view_impl.h"
#include "third_party/WebKit/Tools/DumpRenderTree/chromium/TestRunner/public/WebTestProxy.h"

using WebTestRunner::WebTestProxy;
using WebTestRunner::WebTestProxyBase;

namespace content {

namespace {

base::LazyInstance<base::Callback<void(RenderView*, WebTestProxyBase*)> >::Leaky
    g_callback;

RenderViewImpl* CreateWebTestProxy(RenderViewImplParams* params) {
  typedef WebTestProxy<RenderViewImpl, RenderViewImplParams*> ProxyType;
  ProxyType* render_view_proxy = new ProxyType(
      reinterpret_cast<RenderViewImplParams*>(params));
  if (g_callback == 0)
    return render_view_proxy;
  g_callback.Get().Run(
      static_cast<RenderView*>(render_view_proxy), render_view_proxy);
  return render_view_proxy;
}

}  // namespace

void EnableWebTestProxyCreation(
    const base::Callback<void(RenderView*, WebTestProxyBase*)>& callback) {
  g_callback.Get() = callback;
  RenderViewImpl::InstallCreateHook(CreateWebTestProxy);
}

}  // namespace content

// Copyright (c) 2012 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 "content/public/test/layouttest_support.h"

#include "base/callback.h"
#include "base/lazy_instance.h"
#include "content/renderer/render_view_impl.h"
#include "third_party/WebKit/Tools/DumpRenderTree/chromium/TestRunner/public/WebTestProxy.h"

using WebTestRunner::WebTestProxy;
using WebTestRunner::WebTestProxyBase;

namespace content {

namespace {

base::LazyInstance<base::Callback<void(RenderView*, WebTestProxyBase*)> >::Leaky
    g_callback = LAZY_INSTANCE_INITIALIZER;

RenderViewImpl* CreateWebTestProxy(RenderViewImplParams* params) {
  typedef WebTestProxy<RenderViewImpl, RenderViewImplParams*> ProxyType;
  ProxyType* render_view_proxy = new ProxyType(
      reinterpret_cast<RenderViewImplParams*>(params));
  if (g_callback == 0)
    return render_view_proxy;
  g_callback.Get().Run(
      static_cast<RenderView*>(render_view_proxy), render_view_proxy);
  return render_view_proxy;
}

}  // namespace

void EnableWebTestProxyCreation(
    const base::Callback<void(RenderView*, WebTestProxyBase*)>& callback) {
  g_callback.Get() = callback;
  RenderViewImpl::InstallCreateHook(CreateWebTestProxy);
}

}  // namespace content

Add missing lazy instance initializer


// Copyright (c) 2006-2008 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 "net/disk_cache/cache_util.h"

#include "base/file_util.h"
#include "base/logging.h"
#include "base/string_util.h"

namespace disk_cache {

bool MoveCache(const std::wstring& from_path, const std::wstring& to_path) {
  // Just use the version from base.
  return file_util::Move(from_path.c_str(), to_path.c_str());
}

void DeleteCache(const std::wstring& path, bool remove_folder) {
  if (remove_folder) {
    file_util::Delete(path, false);
  } else {
    std::wstring name(path);
    // TODO(rvargas): Fix this after file_util::delete is fixed.
    // file_util::AppendToPath(&name, L"*");
    file_util::Delete(name, true);
  }
}

bool DeleteCacheFile(const std::wstring& name) {
  return file_util::Delete(name, false);
}

void WaitForPendingIO(int* num_pending_io) {
  if (*num_pending_io) {
    NOTIMPLEMENTED();
  }
}

}  // namespace disk_cache

// Copyright (c) 2006-2008 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 "net/disk_cache/cache_util.h"

#include "base/file_util.h"
#include "base/logging.h"
#include "base/string_util.h"

namespace disk_cache {

bool MoveCache(const std::wstring& from_path, const std::wstring& to_path) {
  // Just use the version from base.
  return file_util::Move(from_path.c_str(), to_path.c_str());
}

void DeleteCache(const std::wstring& path, bool remove_folder) {
  file_util::FileEnumerator iter(path, /* recursive */ false,
                                 file_util::FileEnumerator::FILES);
  for (std::wstring file = iter.Next(); !file.empty(); file = iter.Next()) {
    if (!file_util::Delete(file, /* recursive */ false))
      NOTREACHED();
  }

  if (remove_folder) {
    if (!file_util::Delete(path, /* recursive */ false))
      NOTREACHED();
  }
}

bool DeleteCacheFile(const std::wstring& name) {
  return file_util::Delete(name, false);
}

void WaitForPendingIO(int* num_pending_io) {
  if (*num_pending_io) {
    NOTIMPLEMENTED();
  }
}

}  // namespace disk_cache

Fix DeleteCache on POSIX. It wasn't successfully deleting before.


#include "exceptions.hpp"
#include <nan.h>
#include <gfcpp/GemfireCppCache.hpp>
#include <sstream>

void ThrowGemfireException(const gemfire::Exception & e) {
  std::stringstream errorMessageStream;
  errorMessageStream << e.getName() << ": " << e.getMessage();

  e.printStackTrace();

  NanThrowError(errorMessageStream.str().c_str());
}

#include "exceptions.hpp"
#include <nan.h>
#include <gfcpp/GemfireCppCache.hpp>
#include <sstream>

void ThrowGemfireException(const gemfire::Exception & e) {
  std::stringstream errorMessageStream;
  errorMessageStream << e.getName() << ": " << e.getMessage();
  NanThrowError(errorMessageStream.str().c_str());
}

Stop printing stack trace noise


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

#include "GrTypes.h"
#include "SkThread.h"       // for sk_atomic_inc

// This used to be a global scope, but we got a warning about unused variable
// so we moved it into here. We just want it to compile, so we can test the
// static asserts.
static inline void dummy_function_to_avoid_unused_var_warning() {
    static const GrCacheID::Key kAssertKey;
    GR_STATIC_ASSERT(sizeof(kAssertKey.fData8) == sizeof(kAssertKey.fData32));
    GR_STATIC_ASSERT(sizeof(kAssertKey.fData8) == sizeof(kAssertKey.fData64));
    GR_STATIC_ASSERT(sizeof(kAssertKey.fData8) == sizeof(kAssertKey));
}

GrCacheID::Domain GrCacheID::GenerateDomain() {
    static int32_t gNextDomain = kInvalid_Domain + 1;

    int32_t domain = sk_atomic_inc(&gNextDomain);
    if (domain >= 1 << (8 * sizeof(Domain))) {
        GrCrash("Too many Cache Domains");
    }

    return static_cast<Domain>(domain);
}

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

#include "GrTypes.h"
#include "SkThread.h"       // for sk_atomic_inc

// Well, the dummy_ "fix" caused a warning on windows, so hiding all of it
// until we can find a universal fix.
#if 0
// This used to be a global scope, but we got a warning about unused variable
// so we moved it into here. We just want it to compile, so we can test the
// static asserts.
static inline void dummy_function_to_avoid_unused_var_warning() {
    GrCacheID::Key kAssertKey;
    GR_STATIC_ASSERT(sizeof(kAssertKey.fData8) == sizeof(kAssertKey.fData32));
    GR_STATIC_ASSERT(sizeof(kAssertKey.fData8) == sizeof(kAssertKey.fData64));
    GR_STATIC_ASSERT(sizeof(kAssertKey.fData8) == sizeof(kAssertKey));
}
#endif

GrCacheID::Domain GrCacheID::GenerateDomain() {
    static int32_t gNextDomain = kInvalid_Domain + 1;

    int32_t domain = sk_atomic_inc(&gNextDomain);
    if (domain >= 1 << (8 * sizeof(Domain))) {
        GrCrash("Too many Cache Domains");
    }

    return static_cast<Domain>(domain);
}

Revert r7595 due to housekeeper warning-as-error.


#include "aquila/source/generator/SineGenerator.h"
#include "aquila/wrappers/SoundBufferAdapter.h"
#include "UnitTest++/UnitTest++.h"

SUITE(SoundBufferAdapter)
{
    TEST(NumSamples)
    {
        Aquila::SineGenerator generator(128);
        generator.setAmplitude(1).setFrequency(8).generate(64);
        Aquila::SoundBufferAdapter buffer(generator);
        CHECK_EQUAL(generator.length(), buffer.getSampleCount());
    }
}

#include "aquila/source/generator/SineGenerator.h"
#include "aquila/wrappers/SoundBufferAdapter.h"
#include "UnitTest++/UnitTest++.h"

SUITE(SoundBufferAdapter)
{
    TEST(NumSamples)
    {
        Aquila::SineGenerator generator(128);
        generator.setAmplitude(1).setFrequency(8).generate(64);
        Aquila::SoundBufferAdapter buffer(generator);
        CHECK_EQUAL(generator.length(), buffer.getSampleCount());
    }

    TEST(SampleFrequency)
    {
        Aquila::SineGenerator generator(128);
        generator.setAmplitude(1).setFrequency(8).generate(64);
        Aquila::SoundBufferAdapter buffer(generator);
        CHECK_EQUAL(static_cast<unsigned int>(generator.getSampleFrequency()), buffer.getSampleRate());
    }
}

Check that sample frequencies agree between original generator and buffer.


/**
 * @file
 *
 * @brief compilation test for checking if the Botan library is available.
 *
 * @copyright BSD License (see LICENSE.md or https://www.libelektra.org)
 *
 */

#include <botan/init.h>

int main (int argc, char ** argv)
{
	Botan::LibraryInitializer::initialize ("");
	return 0;
}

/**
 * @file
 *
 * @brief compilation test for checking if the Botan library is available.
 *
 * @copyright BSD License (see LICENSE.md or https://www.libelektra.org)
 *
 */

#include <botan/init.h>

int main (void)
{
	Botan::LibraryInitializer::initialize ("");
	return 0;
}

Fix detection of lib if we use `-Werror`


#include "pch.h"
#include "json_rpc_debug_logger.h"

#include <QDebug>

namespace jcon {

void JsonRpcDebugLogger::logInfo(const QString& message)
{
    qDebug().noquote() << message;
}

void JsonRpcDebugLogger::logWarning(const QString& message)
{
    qDebug().noquote() << message;
}

void JsonRpcDebugLogger::logError(const QString& message)
{
    qDebug().noquote() << message;
}

}

Add inclusion of precompiled header


// REQUIRES: x86-registered-target
// RUN: %clang_cc1 -triple x86_64-pc-linux-gnu -O1 -fmerge-functions -emit-llvm -o - -x c++ < %s | FileCheck %s

// Basic functionality test. Function merging doesn't kick in on functions that
// are too simple.

struct A {
  virtual int f(int x, int *p) { return x ? *p : 1; }
  virtual int g(int x, int *p) { return x ? *p : 1; }
} a;

// CHECK: define {{.*}} @_ZN1A1gEiPi
// CHECK-NEXT: tail call i32 @_ZN1A1fEiPi
// CHECK-NEXT: ret

// REQUIRES: x86-registered-target
// RUN: %clang_cc1 -triple x86_64-pc-linux-gnu -O1 -fmerge-functions -emit-llvm -o - -x c++ < %s | FileCheck %s -implicit-check-not=_ZN1A1gEiPi

// Basic functionality test. Function merging doesn't kick in on functions that
// are too simple.

struct A {
  virtual int f(int x, int *p) { return x ? *p : 1; }
  virtual int g(int x, int *p) { return x ? *p : 1; }
} a;

// CHECK: define {{.*}} @_ZN1A1fEiPi

Update clang test for r350939


//===----------------------------------------------------------------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is dual licensed under the MIT and the University of Illinois Open
// Source Licenses. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//

// <array>

// iterator begin();

#include <array>
#include <cassert>

// std::array is explicitly allowed to be initialized with A a = { init-list };.
// Disable the missing braces warning for this reason.
#include "disable_missing_braces_warning.h"

struct NoDefault {
  NoDefault(int) {}
};

int main()
{
    {
        typedef double T;
        typedef std::array<T, 3> C;
        C c = {1, 2, 3.5};
        C::iterator i;
        i = c.begin();
        assert(*i == 1);
        assert(&*i == c.data());
        *i = 5.5;
        assert(c[0] == 5.5);
    }
    {
      typedef NoDefault T;
      typedef std::array<T, 0> C;
      C c = {};
      assert(c.begin() == c.end());
    }
}

//===----------------------------------------------------------------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is dual licensed under the MIT and the University of Illinois Open
// Source Licenses. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//

// <array>

// iterator begin();

#include <array>
#include <cassert>

#include "test_macros.h"

// std::array is explicitly allowed to be initialized with A a = { init-list };.
// Disable the missing braces warning for this reason.
#include "disable_missing_braces_warning.h"

struct NoDefault {
  NoDefault(int) {}
};

int main()
{
    {
        typedef double T;
        typedef std::array<T, 3> C;
        C c = {1, 2, 3.5};
        C::iterator i;
        i = c.begin();
        assert(*i == 1);
        assert(&*i == c.data());
        *i = 5.5;
        assert(c[0] == 5.5);
    }
    {
      typedef NoDefault T;
      typedef std::array<T, 0> C;
      C c = {};
      C::iterator ib, ie;
      ib = c.begin();
      ie = c.end();
      assert(ib == ie);
      LIBCPP_ASSERT(ib != nullptr);
      LIBCPP_ASSERT(ie != nullptr);
    }
}

Add checks for unique value of array<T, 0>.begin() and array<T, 0>.end()


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

#include "SkSRGB.h"
#include "SkTypes.h"
#include "Test.h"
#include <math.h>

static uint8_t linear_to_srgb(float l) {
    return (uint8_t)sk_linear_to_srgb(Sk4f{l})[0];
}

DEF_TEST(sk_linear_to_srgb, r) {
    // All bytes should round trip.
    for (int i = 0; i < 256; i++) {
        int actual = linear_to_srgb(sk_linear_from_srgb[i]);
        if (i != actual) {
            ERRORF(r, "%d -> %d\n", i, actual);
        }
    }

    // Should be monotonic between 0 and 1.
    uint8_t prev = 0;
    for (float f = FLT_MIN; f <= 1.0f; ) {  // We don't bother checking denorm values.
        uint8_t srgb = linear_to_srgb(f);

        REPORTER_ASSERT(r, srgb >= prev);
        prev = srgb;

        union { float flt; uint32_t bits; } pun = { f };
        pun.bits++;
        f = pun.flt;
    }
}

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

#include "SkSRGB.h"
#include "SkTypes.h"
#include "Test.h"
#include <math.h>

static uint8_t linear_to_srgb(float l) {
    return (uint8_t)sk_linear_to_srgb(Sk4f{l})[0];
}

DEF_TEST(sk_linear_to_srgb, r) {
    // All bytes should round trip.
    for (int i = 0; i < 256; i++) {
        int actual = linear_to_srgb(sk_linear_from_srgb[i]);
        if (i != actual) {
            ERRORF(r, "%d -> %d\n", i, actual);
        }
    }

    // Should be monotonic between 0 and 1.
    uint8_t prev = 0;
    for (float f = FLT_MIN; f <= 1.0f; ) {  // We don't bother checking denorm values.
        uint8_t srgb = linear_to_srgb(f);

        REPORTER_ASSERT(r, srgb >= prev);
        prev = srgb;

        union { float flt; uint32_t bits; } pun = { f };
        pun.bits++;
        SkDEBUGCODE(pun.bits += 127);
        f = pun.flt;
    }
}

Test sk_linear_to_srgb() less exhaustively in Debug mode.


#include <iostream>
#include <QApplication>
#include <QPushButton>
#include "src/common/Game.h"

int main(int argc, char *argv[]) {
    std::cout << "Welcome to the client interface of Bomberman :)" << std::endl;

    // This part should be moved to another class, that's just for test
    QApplication app(argc, argv);
    QWidget mainWindow;
    mainWindow.setFixedSize(300, 300);

    QPushButton createGameButton("Create game", &mainWindow);
    createGameButton.setCursor(Qt::PointingHandCursor);
    createGameButton.move(100, 75);

    QPushButton joinGameButton("Join game", &mainWindow);
    joinGameButton.setCursor(Qt::PointingHandCursor);
    joinGameButton.move(100, 150);

    QPushButton quitWindowButton("Quit Bomberman", &mainWindow);
    quitWindowButton.setCursor(Qt::PointingHandCursor);
    quitWindowButton.move(100, 225);

    QObject::connect(&quitWindowButton, SIGNAL(clicked()), &app, SLOT(quit()));

    mainWindow.show();

    return app.exec();
}

#include <iostream>
#include <QApplication>
#include <QPushButton>
#include "src/common/Game.h"

#include "easylogging++.h"

_INITIALIZE_EASYLOGGINGPP

int main(int argc, char *argv[]) {
    std::cout << "Welcome to the client interface of Bomberman :)" << std::endl;

    _START_EASYLOGGINGPP(argc, argv);
    LOG(INFO) << "Started client";

    // This part should be moved to another class, that's just for test
    QApplication app(argc, argv);
    QWidget mainWindow;
    mainWindow.setFixedSize(300, 300);

    QPushButton createGameButton("Create game", &mainWindow);
    createGameButton.setCursor(Qt::PointingHandCursor);
    createGameButton.move(100, 75);

    QPushButton joinGameButton("Join game", &mainWindow);
    joinGameButton.setCursor(Qt::PointingHandCursor);
    joinGameButton.move(100, 150);

    QPushButton quitWindowButton("Quit Bomberman", &mainWindow);
    quitWindowButton.setCursor(Qt::PointingHandCursor);
    quitWindowButton.move(100, 225);

    QObject::connect(&quitWindowButton, SIGNAL(clicked()), &app, SLOT(quit()));

    mainWindow.show();

    return app.exec();
}

Add an example of how to use the logging library.


// Native C++ Libraries
#include <iostream>
#include <string>

// C++ Interpreter Libraries
#include <Console.h>

using namespace std;

int main()
{
	RESTART:
	string input = "";
	getline(cin, input);
	goto RESTART;
}

// Native C++ Libraries
#include <iostream>
#include <string>
#include <sstream>
#include <vector>

// C++ Interpreter Libraries
#include <Console.h>

using namespace std;

int main()
{
	RESTART:
	string input = "";
	getline(cin, input);
	goto RESTART;
}

Add stringstream and vector library to main source.


/*
 * Copyright (C) 2018 The Android Open Source Project
 *
 * 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 <sys/sysinfo.h>

#include "test/gtest_and_gmock.h"

namespace perfetto {

TEST(PerfettoDeviceFeatureTest, TestMaxCpusForAtraceChmod) {
  // Check that there are no more than 16 CPUs so that the assumption in the
  // atrace.rc for clearing CPU buffers is valid.
  ASSERT_LE(sysconf(_SC_NPROCESSORS_CONF), 16);
}

}  // namespace perfetto

/*
 * Copyright (C) 2018 The Android Open Source Project
 *
 * 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 <sys/sysinfo.h>

#include "test/gtest_and_gmock.h"

namespace perfetto {

TEST(PerfettoDeviceFeatureTest, TestMaxCpusForAtraceChmod) {
  // Check that there are no more than 24 CPUs so that the assumption in the
  // atrace.rc for clearing CPU buffers is valid.
  ASSERT_LE(sysconf(_SC_NPROCESSORS_CONF), 24);
}

}  // namespace perfetto

Increase core count for PerfettoDeviceFeatureTest


/* Any copyright is dedicated to the Public Domain.
 * http://creativecommons.org/publicdomain/zero/1.0/ */

#include "catch.hpp"

#include "hooks.hh"

static int i;
void inc_i(vick::contents&) { ++i; }

TEST_CASE("hook proc", "[hook]") {
    vick::hook h;
    vick::contents c;
    h.add(inc_i);
    int li = i;
    h.proc(c);
    REQUIRE(li + 1 == i);
}

TEST_CASE("hook remove", "[hook]") {
    vick::hook h;
    vick::contents c;
    int li = i;
    h.add(inc_i);
    REQUIRE(li == i);
    h.proc(c);
    REQUIRE(li + 1 == i);
    REQUIRE(h.remove(inc_i));
    REQUIRE_FALSE(h.remove(inc_i));
    REQUIRE(li + 1 == i);
    h.proc(c);
    REQUIRE(li + 1 == i);
}

TEST_CASE("hook add multiple", "[hook]") {
    vick::hook h;
    vick::contents c;
    int li = i;
    h.add(inc_i);
    h.add(inc_i);
    REQUIRE(li == i);
    h.proc(c);
    REQUIRE(li + 2 == i);
    REQUIRE(h.remove(inc_i));
    REQUIRE_FALSE(h.remove(inc_i));
    REQUIRE(li + 2 == i);
    h.proc(c);
    REQUIRE(li + 2 == i);
}

/* Any copyright is dedicated to the Public Domain.
 * http://creativecommons.org/publicdomain/zero/1.0/ */

#include "catch.hpp"

#include "hooks.hh"

static int i;
static void inc_i(vick::contents&) { ++i; }

TEST_CASE("hook proc", "[hook]") {
    vick::hook h;
    vick::contents c;
    h.add(inc_i);
    int li = i;
    h.proc(c);
    REQUIRE(li + 1 == i);
}

TEST_CASE("hook remove", "[hook]") {
    vick::hook h;
    vick::contents c;
    int li = i;
    h.add(inc_i);
    REQUIRE(li == i);
    h.proc(c);
    REQUIRE(li + 1 == i);
    REQUIRE(h.remove(inc_i));
    REQUIRE_FALSE(h.remove(inc_i));
    REQUIRE(li + 1 == i);
    h.proc(c);
    REQUIRE(li + 1 == i);
}

TEST_CASE("hook add multiple", "[hook]") {
    vick::hook h;
    vick::contents c;
    int li = i;
    h.add(inc_i);
    h.add(inc_i);
    REQUIRE(li == i);
    h.proc(c);
    REQUIRE(li + 2 == i);
    REQUIRE(h.remove(inc_i));
    REQUIRE_FALSE(h.remove(inc_i));
    REQUIRE(li + 2 == i);
    h.proc(c);
    REQUIRE(li + 2 == i);
}

Make testing utility function `static`


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

#include "Test.h"

// This is a GPU-backend specific test
#if SK_SUPPORT_GPU

#include "GrContextFactory.h"

DEF_GPUTEST(GLInterfaceValidation, reporter, factory) {
    for (int i = 0; i <= GrContextFactory::kLastGLContextType; ++i) {
        GrContextFactory::GLContextType glCtxType = (GrContextFactory::GLContextType)i;
        // this forces the factory to make the context if it hasn't yet
        factory->get(glCtxType);
        SkGLContext* glCtx = factory->getGLContext(glCtxType);

        // We're supposed to fail the NVPR context type when we the native context that does not
        // support the NVPR extension.
        if (GrContextFactory::kNVPR_GLContextType == glCtxType &&
            factory->getGLContext(GrContextFactory::kNative_GLContextType) &&
            !factory->getGLContext(GrContextFactory::kNative_GLContextType)->gl()->hasExtension("GL_NV_path_rendering")) {
            REPORTER_ASSERT(reporter, NULL == glCtx);
            continue;
        }

        if (glCtx) {
            const GrGLInterface* interface = glCtx->gl();
            REPORTER_ASSERT(reporter, interface->validate());
        }
    }
}

#endif

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

#include "Test.h"

// This is a GPU-backend specific test
#if SK_SUPPORT_GPU

#include "GrContextFactory.h"

DEF_GPUTEST(GLInterfaceValidation, reporter, factory) {
    for (int i = 0; i <= GrContextFactory::kLastGLContextType; ++i) {
        GrContextFactory::GLContextType glCtxType = (GrContextFactory::GLContextType)i;
        // this forces the factory to make the context if it hasn't yet
        factory->get(glCtxType);
        SkGLContext* glCtx = factory->getGLContext(glCtxType);

        // We're supposed to fail the NVPR context type when we the native context that does not
        // support the NVPR extension.
        if (GrContextFactory::kNVPR_GLContextType == glCtxType &&
            factory->getGLContext(GrContextFactory::kNative_GLContextType) &&
            !factory->getGLContext(GrContextFactory::kNative_GLContextType)->gl()->hasExtension("GL_NV_path_rendering")) {
            REPORTER_ASSERT(reporter, NULL == glCtx);
            continue;
        }

        REPORTER_ASSERT(reporter, glCtx);
        if (glCtx) {
            const GrGLInterface* interface = glCtx->gl();
            REPORTER_ASSERT(reporter, interface->validate());
        }
    }
}

#endif

Revert "One more ASAN fix."


#include "bct.h"
#include <cassert>
#include <gsl/gsl_matrix.h>
#include <gsl/gsl_vector.h>

/*
 * Computes the clustering coefficient for a binary undirected graph.  Results
 * are returned in a vector where each element is the clustering coefficient of
 * the corresponding node.
 */
gsl_vector* bct::clustering_coef_bu(const gsl_matrix* m) {
	assert(m->size1 == m->size2);
	gsl_vector* clustering_coef = gsl_vector_calloc(m->size1);
	for (int i = 0; i < m->size1; i++) {
		gsl_vector_const_view row = gsl_matrix_const_row(m, i);
		int k = bct::nnz(&row.vector);
		if (k >= 2) {
			gsl_vector* neighbors = bct::find(&row.vector);
			gsl_matrix* s = bct::submatrix(m, neighbors, neighbors);
			int actual_connections = bct::nnz(s);
			int possible_connections = k * (k - 1);
			gsl_vector_set(clustering_coef, i, (double)actual_connections / (double)possible_connections);
			gsl_matrix_free(s);
			gsl_vector_free(neighbors);
		}
	}
	return clustering_coef;
}

#include "bct.h"
#include <cassert>
#include <gsl/gsl_matrix.h>
#include <gsl/gsl_vector.h>

/*
 * Computes the clustering coefficient for a binary undirected graph.  Results
 * are returned in a vector where each element is the clustering coefficient of
 * the corresponding node.
 */
gsl_vector* bct::clustering_coef_bu(const gsl_matrix* m) {
	assert(m->size1 == m->size2);
	gsl_vector* clustering_coef = gsl_vector_calloc(m->size1);
	gsl_matrix* zdm = zero_diagonal(m);
	for (int i = 0; i < zdm->size1; i++) {
		gsl_vector_const_view row = gsl_matrix_const_row(zdm, i);
		int k = bct::nnz(&row.vector);
		if (k >= 2) {
			gsl_vector* neighbors = bct::find(&row.vector);
			gsl_matrix* s = bct::submatrix(zdm, neighbors, neighbors);
			int actual_connections = bct::nnz(s);
			int possible_connections = k * (k - 1);
			gsl_vector_set(clustering_coef, i, (double)actual_connections / (double)possible_connections);
			gsl_matrix_free(s);
			gsl_vector_free(neighbors);
		}
	}
	gsl_matrix_free(zdm);
	return clustering_coef;
}

Undo r13; clustering coefficient should ignore loops.


#include "util/testing.h"

#include <event2/thread.h>
#include <gflags/gflags.h>
#include <glog/logging.h>
#include <gtest/gtest.h>

namespace cert_trans {
namespace test {

void InitTesting(const char* name, int* argc, char*** argv,
                 bool remove_flags) {
  // Change the defaults. Can be overridden on command line.
  // Log to stderr instead of log files.
  FLAGS_logtostderr = true;
  // Only log fatal messages by default.
  FLAGS_minloglevel = 3;
  ::testing::InitGoogleTest(argc, *argv);
  google::ParseCommandLineFlags(argc, argv, remove_flags);
  google::InitGoogleLogging(name);
  evthread_use_pthreads();
}

}  // namespace test
}  // namespace cert_trans

#include "util/testing.h"

#include <event2/thread.h>
#include <gflags/gflags.h>
#include <glog/logging.h>
#include <gtest/gtest.h>

namespace cert_trans {
namespace test {

void InitTesting(const char* name, int* argc, char*** argv,
                 bool remove_flags) {
  ::testing::InitGoogleTest(argc, *argv);
  google::ParseCommandLineFlags(argc, argv, remove_flags);
  google::InitGoogleLogging(name);
  evthread_use_pthreads();
}

}  // namespace test
}  // namespace cert_trans

Stop overriding the logging behaviour in tests.


#include <iostream>
using namespace std;

long long solve(int n)
{
    long long *res = new long long[n + 1];
    switch (n) {
    case 1: return 1;
    case 2: return 2;
    case 3: return 3;
    case 4: return 6;
    }
    res[1] = 1;
    res[2] = 2;
    res[3] = 3;
    res[4] = 6;
    for (int i = 5; i <= n; i++) {
        res[i] = res[i - 1] + res[i - 2] + res[i - 4];
    }
    long long x = res[n];
    delete [] res;
    return x;
}

int main()
{
    int T;
    cin >> T;
    while (T--) {
        int x;
        cin >> x;
        cout << solve(x) << endl;
    }
    return 0;
}

#include <iostream>
using namespace std;

long long solve_1(int n)
{
    long long *res = new long long[n + 1];
    switch (n) {
    case 1: return 1;
    case 2: return 2;
    case 3: return 3;
    case 4: return 6;
    }
    res[1] = 1;
    res[2] = 2;
    res[3] = 3;
    res[4] = 6;
    for (int i = 5; i <= n; i++) {
        res[i] = res[i - 1] + res[i - 2] + res[i - 4];
    }
    long long x = res[n];
    delete [] res;
    return x;
}

long long solve_2(int n)
{
    switch (n) {
    case 1: return 1;
    case 2: return 2;
    case 3: return 3;
    case 4: return 6;
    }
    long long a = 1;
    long long b = 2;
    long long c = 3;
    long long d = 6;
    long long res;
    for (int i = 5; i <= n; i++) {
        res = d + c + a;
        a = b;
        b = c;
        c = d;
        d = res;
    }
    return d;
}

int main()
{
    int T;
    cin >> T;
    while (T--) {
        int x;
        cin >> x;
        cout << solve_2(x) << endl;
    }
    return 0;
}

Add a solution with better space cost to "Cached Calculations".


#include "hash.h"
#include <QClipboard>
#include <QGuiApplication>
#include <QQmlContext>
#include <QStringList>

const int password_length = 30;

Hash::Hash(QQmlContext *c, QObject *parent) :
    QObject(parent),
    hash(QCryptographicHash::Sha3_224),
    settings("pasgen"),
    context(c)
{
    context->setContextProperty("myModel", settings.value("pages").toStringList());
}

QString Hash::Do(QString password, QString page, bool isCheck)
{
    QStringList pages = settings.value("pages").toStringList();
    if (!isCheck && !page.isEmpty())
    {
        if (!pages.contains(page))
            pages.append(page);

        pages.move(pages.indexOf(page), 0);
        settings.setValue("pages", pages);
        context->setContextProperty("myModel", pages);
    }

    hash.reset();
    hash.addData(password.toUtf8());
    hash.addData(page.toUtf8());
    QString result = hash.result().toHex().left(password_length);

    if (!isCheck)
        qApp->clipboard()->setText(result);

    return result;
}

void Hash::Remove(QString page)
{
    QStringList pages = settings.value("pages").toStringList();
    pages.removeAll(page);
    settings.setValue("pages", pages);
    context->setContextProperty("myModel", pages);
}

#include "hash.h"
#include <QClipboard>
#include <QGuiApplication>
#include <QQmlContext>
#include <QStringList>

const int password_length = 30;

Hash::Hash(QQmlContext *c, QObject *parent) :
    QObject(parent),
    hash(QCryptographicHash::Sha3_224),
    settings("pasgen"),
    context(c)
{
    context->setContextProperty("myModel", settings.value("pages").toStringList());
}

QString Hash::Do(QString password, QString page, bool isCheck)
{
    QStringList pages = settings.value("pages").toStringList();
    if (!isCheck && !page.isEmpty())
    {
        if (!pages.contains(page))
            pages.append(page);

        pages.move(pages.indexOf(page), 0);
        settings.setValue("pages", pages);
        context->setContextProperty("myModel", pages);
    }

    hash.reset();
    hash.addData(password.toUtf8());
    hash.addData(page.toUtf8());
    QString result = hash.result().toHex().left(password_length);

    if (!isCheck)
    {
        qApp->clipboard()->setText(result, QClipboard::Clipboard);
        qApp->clipboard()->setText(result, QClipboard::Selection);
    }

    return result;
}

void Hash::Remove(QString page)
{
    QStringList pages = settings.value("pages").toStringList();
    pages.removeAll(page);
    settings.setValue("pages", pages);
    context->setContextProperty("myModel", pages);
}

Save password also to selection clipboard.


#include "rapidjson/document.h"
#include "rapidjson/writer.h"
#include "rapidjson/stringbuffer.h"
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>

using namespace std;

void read_file(string filename, stringstream &buffer){
  ifstream f(filename.c_str());
  if (f)
  {
    buffer << f.rdbuf();
    f.close();
  }
}

using namespace rapidjson;

int main() {
    std::stringstream ss;
    read_file("./1.json", ss);

    string text = ss.str();
    Document jobj; jobj.Parse(text.c_str());

    const Value &coordinates = jobj["coordinates"];
    int len = coordinates.Size();
    double x = 0, y = 0, z = 0;

    for (SizeType i = 0; i < len; i++) {
      const Value &coord = coordinates[i];
      x += coord["x"].GetDouble();
      y += coord["y"].GetDouble();
      z += coord["z"].GetDouble();
    }

    std::cout << x / len << std::endl;
    std::cout << y / len << std::endl;
    std::cout << z / len << std::endl;

    return 0;
}

#include "rapidjson/document.h"
#include "rapidjson/filereadstream.h"
#include <cstdio>
#include <iostream>

using namespace std;
using namespace rapidjson;

int main() {
    FILE* fp = std::fopen("./1.json", "r");
    char buffer[65536];
    FileReadStream frs(fp, buffer, sizeof(buffer));
    Document jobj;
    jobj.ParseStream(frs);

    const Value &coordinates = jobj["coordinates"];
    int len = coordinates.Size();
    double x = 0, y = 0, z = 0;

    for (SizeType i = 0; i < len; i++) {
      const Value &coord = coordinates[i];
      x += coord["x"].GetDouble();
      y += coord["y"].GetDouble();
      z += coord["z"].GetDouble();
    }

    std::cout << x / len << std::endl;
    std::cout << y / len << std::endl;
    std::cout << z / len << std::endl;

    fclose(fp);

    return 0;
}

Use FileReadStream instead of multiple conversions.


#include "MainWindow.h"

#include <QBoxLayout>
#include <QLabel>
#include <QSpinBox>

#include <fiblib/Fibonacci.h>

MainWindow::MainWindow()
{
    // Create content widget
    QWidget * content = new QWidget(this);
    setCentralWidget(content);

    // Create layout
    QBoxLayout * layout = new QVBoxLayout();
    content->setLayout(layout);

    // Add title
    QLabel * title = new QLabel(content);
    title->setText("Please enter n:");
    layout->addWidget(title);

    // Add input field
    QSpinBox * editNumber = new QSpinBox(content);
    editNumber->setMinimum(0);
    layout->addWidget(editNumber);

    // Add result
    QLabel * result = new QLabel(content);
    result->setText("Fib(0) = 0");
    layout->addWidget(result);

    // When input changes, calculate and output the fibonacci number
    connect(editNumber, static_cast<void (QSpinBox::*)(int)>(&QSpinBox::valueChanged), [result] (int n)
    {
        fiblib::Fibonacci fib;
        result->setText("Fib(" + QString::number(n) + ") = " + QString::number(fib(n)));
    });
}

MainWindow::~MainWindow()
{
}

#include "MainWindow.h"

#include <QBoxLayout>
#include <QLabel>
#include <QSpinBox>

#include <fiblib/Fibonacci.h>

MainWindow::MainWindow()
{
    // Create content widget
    QWidget * content = new QWidget(this);
    setCentralWidget(content);

    // Create layout
    QBoxLayout * boxLayout = new QVBoxLayout();
    content->setLayout(boxLayout);

    // Add title
    QLabel * title = new QLabel(content);
    title->setText("Please enter n:");
    boxLayout->addWidget(title);

    // Add input field
    QSpinBox * editNumber = new QSpinBox(content);
    editNumber->setMinimum(0);
    boxLayout->addWidget(editNumber);

    // Add result
    QLabel * result = new QLabel(content);
    result->setText("Fib(0) = 0");
    boxLayout->addWidget(result);

    // When input changes, calculate and output the fibonacci number
    connect(editNumber, static_cast<void (QSpinBox::*)(int)>(&QSpinBox::valueChanged), [result] (int n)
    {
        fiblib::Fibonacci fib;
        result->setText("Fib(" + QString::number(n) + ") = " + QString::number(fib(static_cast<unsigned int>(n))));
    });
}

MainWindow::~MainWindow()
{
}

Remove simple to fix warnings


#include <botan/botan.h>
#include <botan/ecdsa.h>

#include <memory>
#include <iostream>

using namespace Botan;

int main()
   {
   try
      {
      std::auto_ptr<RandomNumberGenerator> rng(
         RandomNumberGenerator::make_rng());

      EC_Domain_Params params = get_EC_Dom_Pars_by_oid("1.3.132.0.8");

      std::cout << params.get_curve().get_p() << "\n";
      std::cout << params.get_order() << "\n";

      ECDSA_PrivateKey ecdsa(*rng, params);
      }
   catch(std::exception& e)
      {
      std::cout << e.what() << "\n";
      }
   }

#include <botan/botan.h>
#include <botan/ecdsa.h>

#include <memory>
#include <iostream>

using namespace Botan;

int main()
   {
   try
      {
      std::auto_ptr<RandomNumberGenerator> rng(
         RandomNumberGenerator::make_rng());

      EC_Domain_Params params = get_EC_Dom_Pars_by_oid("1.3.132.0.8");

      std::cout << params.get_curve().get_p() << "\n";
      std::cout << params.get_order() << "\n";

      ECDSA_PrivateKey ecdsa(*rng, params);

      std::cout << X509::PEM_encode(ecdsa);
      }
   catch(std::exception& e)
      {
      std::cout << e.what() << "\n";
      }
   }

Print generated public key in ECDSA example


#include "other.hpp"
#include "item.hpp"
using namespace LD22;

Other::~Other()
{ }

void Other::advance()
{
    scanItems();
    if (m_item) {
        int wx = centerx(), wy = centery();
        int ix = m_item->centerx(), iy = m_item->centery();
        int dx = ix - wx, dy = iy - wy;
        if (dx < -20)
            m_xpush = -PUSH_SCALE;
        else if (dx > 20)
            m_xpush = PUSH_SCALE;
        else
            m_xpush = 0;
        (void) dy;
    } else {
        m_xpush = 0;
    }
    Walker::advance();
}

#include "other.hpp"
#include "item.hpp"
using namespace LD22;

Other::~Other()
{ }

void Other::advance()
{
    scanItems();
    if (m_item) {
        int wx = centerx(), wy = centery();
        int ix = m_item->centerx(), iy = m_item->centery();
        int dx = ix - wx, dy = iy - wy;
        if (dx < -20)
            m_xpush = -PUSH_SCALE;
        else if (dx > 20)
            m_xpush = PUSH_SCALE;
        else
            m_xpush = 0;
        if (dy > 80)
            m_ypush = 1;
        else
            m_ypush = 0;
    } else {
        m_xpush = 0;
        m_ypush = 0;
    }
    Walker::advance();
}

Make Other jump after star


// Author: Jingyue

// Hook functions are declared with extern "C", because we want to disable
// the C++ name mangling and make the instrumentation easier.

#include <cstdio>
#include <cstdlib>

extern "C" void ReportMissingAlias(unsigned VIDOfP, unsigned VIDOfQ, void *V) {
  fprintf(stderr, "value(%u) = value(%u) = %p\n", VIDOfP, VIDOfQ, V);
}

extern "C" void AbortIfMissed(void *P, unsigned VIDOfP,
                              void *Q, unsigned VIDOfQ) {
  if (P == Q && P) {
    ReportMissingAlias(VIDOfP, VIDOfQ, P);
    abort();
  }
}

extern "C" void ReportIfMissed(void *P, unsigned VIDOfP,
                               void *Q, unsigned VIDOfQ) {
  if (P == Q && P) {
    ReportMissingAlias(VIDOfP, VIDOfQ, P);
  }
}

// Author: Jingyue

// Hook functions are declared with extern "C", because we want to disable
// the C++ name mangling and make the instrumentation easier.

#include <cstdio>
#include <cstdlib>

#define DISABLE_REPORT

extern "C" void ReportMissingAlias(unsigned VIDOfP, unsigned VIDOfQ, void *V) {
#ifndef DISABLE_REPORT
  fprintf(stderr, "value(%u) = value(%u) = %p\n", VIDOfP, VIDOfQ, V);
#endif
}

extern "C" void AbortIfMissed(void *P, unsigned VIDOfP,
                              void *Q, unsigned VIDOfQ) {
  if (P == Q && P) {
    ReportMissingAlias(VIDOfP, VIDOfQ, P);
    abort();
  }
}

extern "C" void ReportIfMissed(void *P, unsigned VIDOfP,
                               void *Q, unsigned VIDOfQ) {
  if (P == Q && P) {
    ReportMissingAlias(VIDOfP, VIDOfQ, P);
  }
}

Disable alias report by default


// This example shows how to use the TCP server. It listens at given port,
// receives one message and sends one message.

#include <memory>
#include <iostream>

#include <gflags/gflags.h>
#include "c24/communication/stream.h"
#include "c24/communication/stream_tcp_server.h"
#include "c24/communication/stream_backend_interface.h"

using c24::communication::StreamBackendInterface;
using c24::communication::StreamTcpServer;
using c24::communication::Stream;

DEFINE_int32(port, 5500,
             "Define port number where do you want to listen for connection.");

int main(int argc, char** argv) {
  google::InitGoogleLogging(*argv);
  google::ParseCommandLineFlags(&argc, &argv, true);
  Stream stream = Stream(std::unique_ptr<StreamBackendInterface>(
      new StreamTcpServer(FLAGS_port)));
  std::cout << stream.GetMessage() << std::endl;
  stream.SendMessage("HELLO CLIENT");

  return 0;
}

// This example shows how to use the TCP server. It listens at given port,
// receives one message and sends one message.

#include <memory>
#include <iostream>

#include <gflags/gflags.h>
#include <glog/logging.h>
#include "c24/communication/stream.h"
#include "c24/communication/stream_tcp_server.h"
#include "c24/communication/stream_backend_interface.h"

using c24::communication::StreamBackendInterface;
using c24::communication::StreamTcpServer;
using c24::communication::Stream;

DEFINE_int32(port, 5500,
             "Define port number where do you want to listen for connection.");

int main(int argc, char** argv) {
  google::InitGoogleLogging(*argv);
  google::ParseCommandLineFlags(&argc, &argv, true);
  Stream stream = Stream(std::unique_ptr<StreamBackendInterface>(
      new StreamTcpServer(FLAGS_port)));
  std::cout << stream.GetMessage() << std::endl;
  stream.SendMessage("HELLO CLIENT");

  return 0;
}

Add missing include to tcp server example.


#include "../../testing/testing.hpp"

#include "../country.hpp"

#include "../../coding/file_writer.hpp"
#include "../../coding/file_reader.hpp"

#include "../../base/start_mem_debug.hpp"

UNIT_TEST(CountrySerialization)
{
  string const TEST_URL = "http://someurl.com/somemap.dat";
  uint64_t const TEST_SIZE = 123456790;
  char const * TEST_FILE_NAME = "some_temporary_update_file.tmp";
  mapinfo::Country c("North America", "USA", "Alaska");
  c.AddUrl(mapinfo::TUrl(TEST_URL, TEST_SIZE));

  {
    mapinfo::TCountriesContainer countries;
    countries[c.Group()].push_back(c);

    FileWriter writer(TEST_FILE_NAME);
    mapinfo::SaveCountries(countries, writer);
  }

  mapinfo::TCountriesContainer loadedCountries;
  {
    TEST( mapinfo::LoadCountries(loadedCountries, TEST_FILE_NAME), ());
  }

  TEST_GREATER(loadedCountries.size(), 0, ());
  mapinfo::Country const & c2 = loadedCountries.begin()->second.front();
  TEST_EQUAL(c.Group(), loadedCountries.begin()->first, ());
  TEST_EQUAL(c.Group(), c2.Group(), ());
  TEST_EQUAL(c.Name(), c2.Name(), ());
  TEST_GREATER(c2.Urls().size(), 0, ());
  TEST_EQUAL(*c.Urls().begin(), *c2.Urls().begin(), ());
}

#include "../../testing/testing.hpp"

#include "../country.hpp"

#include "../../coding/file_writer.hpp"
#include "../../coding/file_reader.hpp"

#include "../../base/start_mem_debug.hpp"

UNIT_TEST(CountrySerialization)
{
  string const TEST_URL = "http://someurl.com/somemap.dat";
  uint64_t const TEST_SIZE = 123456790;
  char const * TEST_FILE_NAME = "some_temporary_update_file.tmp";
  mapinfo::Country c("North America", "USA", "Alaska");
  c.AddUrl(mapinfo::TUrl(TEST_URL, TEST_SIZE));

  {
    mapinfo::TCountriesContainer countries;
    countries[c.Group()].push_back(c);

    FileWriter writer(TEST_FILE_NAME);
    mapinfo::SaveCountries(countries, writer);
  }

  mapinfo::TCountriesContainer loadedCountries;
  {
    TEST( mapinfo::LoadCountries(loadedCountries, TEST_FILE_NAME), ());
  }

  TEST_GREATER(loadedCountries.size(), 0, ());
  mapinfo::Country const & c2 = loadedCountries.begin()->second.front();
  TEST_EQUAL(c.Group(), loadedCountries.begin()->first, ());
  TEST_EQUAL(c.Group(), c2.Group(), ());
  TEST_EQUAL(c.Name(), c2.Name(), ());
  TEST_GREATER(c2.Urls().size(), 0, ());
  TEST_EQUAL(*c.Urls().begin(), *c2.Urls().begin(), ());

  FileWriter::DeleteFile(TEST_FILE_NAME);
}

Delete temporary file after unit test


/* * This file is part of Maliit framework *
 *
 * Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies).
 *
 * All rights reserved.
 *
 * Contact: maliit-discuss@lists.maliit.org
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License version 2.1 as published by the Free Software Foundation
 * and appearing in the file LICENSE.LGPL included in the packaging
 * of this file.
 */

#include <qpa/qplatforminputcontextplugin_p.h>
#include <QtCore/QStringList>
#include <QDebug>

#include "minputcontext.h"

class MaliitPlatformInputContextPlugin: public QPlatformInputContextPlugin
{
    Q_OBJECT
    Q_PLUGIN_METADATA(IID "org.qt-project.Qt.QPlatformInputContextFactoryInterface" FILE "maliit.json")

public:
    QPlatformInputContext *create(const QString&, const QStringList&);
};

QPlatformInputContext *MaliitPlatformInputContextPlugin::create(const QString &system, const QStringList &paramList)
{
    Q_UNUSED(paramList);

    if (system.compare(system, QStringLiteral("maliit"), Qt::CaseInsensitive) == 0) {
        return new MInputContext;
    }
    return 0;
}

#include "main.moc"

/* * This file is part of Maliit framework *
 *
 * Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies).
 *
 * All rights reserved.
 *
 * Contact: maliit-discuss@lists.maliit.org
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License version 2.1 as published by the Free Software Foundation
 * and appearing in the file LICENSE.LGPL included in the packaging
 * of this file.
 */

#include <qpa/qplatforminputcontextplugin_p.h>
#include <QtCore/QStringList>
#include <QDebug>

#include "minputcontext.h"

class MaliitPlatformInputContextPlugin: public QPlatformInputContextPlugin
{
    Q_OBJECT
    Q_PLUGIN_METADATA(IID QPlatformInputContextFactoryInterface_iid FILE "maliit.json")

public:
    QPlatformInputContext *create(const QString&, const QStringList&);
};

QPlatformInputContext *MaliitPlatformInputContextPlugin::create(const QString &system, const QStringList &paramList)
{
    Q_UNUSED(paramList);

    if (system.compare(system, QStringLiteral("maliit"), Qt::CaseInsensitive) == 0) {
        return new MInputContext;
    }
    return 0;
}

#include "main.moc"

Replace hard coded string with QPlatformInputContextFactoryInterface_iid (fixes compatibility with Qt 5.5 where this string has changed)


/**
 * This is free and unencumbered software released into the public domain.
**/
#include "Miner.h"

#include <memory>

class CpuMiner : public Miner
{
public:
   ~CpuMiner() {}

public:
   static MinerPtr createInstance()
   {
      return MinerPtr( new CpuMiner );
   }
};

MinerRegistration<CpuMiner> registration( "cpu" );

/**
 * This is free and unencumbered software released into the public domain.
**/
#include "Miner.h"

#include <memory>
#include <limits>
#include <cassert>

class CpuMiner : public Miner
{
public:
   ~CpuMiner() {}

public:
   static MinerPtr createInstance()
   {
      return MinerPtr( new CpuMiner );
   }

protected:
   virtual Result _mine( const Sha256& preHash, const ByteArray& reverseTarget, uint32_t& nonce )
   {
      assert( reverseTarget.size() == sizeof(Sha256::Digest) );

      nonce = 0;
      do
      {
         // Complete the first hash
         Sha256 hash( preHash );
         Sha256::Digest digest;

         hash.update( &nonce, sizeof(nonce) * CHAR_BIT );
         hash.digest( digest );

         // Do it again
         auto result = Sha256::hash( digest.toByteArray() );

         for( int i = result.size() - 1; i >= 0; --i )
         {
            if( result[i] > reverseTarget[i] )
            {
               break;
            }

            if( result[i] < reverseTarget[i] )
            {
               return SolutionFound;
            }
         }
      } while( nonce++ < std::numeric_limits<uint32_t>::max() );

      return NoSolutionFound;
   }
};

MinerRegistration<CpuMiner> registration( "cpu" );

Implement basic cpu mining logic


/*
  Copyright 2007 Albert Strasheim <fullung@gmail.com>

  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.
*/

// TODO look at issues with the GIL here when multiple session threads
// call into the Python code (could happen with Openwire?)

#include <boost/python.hpp>
#include <cms/MessageListener.h>

using namespace boost::python;
using cms::MessageListener;
using cms::Message;

struct MessageListenerWrap : MessageListener, wrapper<MessageListener>
{
    virtual void onMessage(const Message* message)
    {
        // should be: this->getOverride("onMessage")(message);
        // but that doesn't work with Visual C++
        call<void>(this->get_override("onMessage").ptr(), message);
    }
};

void export_MessageListener()
{
    class_<MessageListenerWrap, boost::noncopyable>("MessageListener")
        .def("onMessage", pure_virtual(&MessageListener::onMessage))
        ;
}

/*
  Copyright 2007 Albert Strasheim <fullung@gmail.com>

  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.
*/

// TODO look at issues with the GIL here when multiple session threads
// call into the Python code (could happen with Openwire?)

#include <boost/python.hpp>
#include <cms/MessageListener.h>
#include <cms/Message.h>

using namespace boost::python;
using cms::MessageListener;
using cms::Message;

struct MessageListenerWrap : MessageListener, wrapper<MessageListener>
{
    virtual void onMessage(const Message* message)
    {
        // should be: this->getOverride("onMessage")(message);
        // but that doesn't work with Visual C++
        call<void>(this->get_override("onMessage").ptr(), message);
    }
};

void export_MessageListener()
{
    class_<MessageListenerWrap, boost::noncopyable>("MessageListener")
        .def("onMessage", pure_virtual(&MessageListener::onMessage))
        ;
}

Fix compilation with GCC 4.1.1.


/* RMS power gauge, based on the one in csound.  -JGG */

#include "RMS.h"

RMS :: RMS(double srate) : Filter(srate)
{
   gain = 1.0;
   subLowFilter = new OnePole(srate);
   subLowFilter->setFreq(10.0);
   windowSize = DEFAULT_CONTROL_RATE;
   counter = 0;
   lastOutput = 0.0;
   outputs = inputs = NULL;                    // unused
}

RMS :: ~RMS()
{
   delete subLowFilter;
}

void RMS :: clear()
{
   lastOutput = 0.0;
   counter = 0;
}

void RMS :: setFreq(double freq)
{
   subLowFilter->setFreq(freq);
}

void RMS :: setWindowSize(int nsamples)
{
   windowSize = nsamples;
   counter = 0;
}

double RMS :: tick(double sample)
{
   double temp = subLowFilter->tick(sample * sample);
   if (--counter < 0) {
      lastOutput = sqrt(temp);
      counter = windowSize;
   }
   return lastOutput;
}

/* RMS power gauge, based on the one in csound.  -JGG */

#include "RMS.h"

RMS :: RMS(double srate) : Filter(srate)
{
   gain = 1.0;
   subLowFilter = new OnePole(srate);
   subLowFilter->setFreq(10.0);
   windowSize = DEFAULT_CONTROL_RATE;
   counter = 0;
   lastOutput = 0.0;
   outputs = inputs = NULL;                    // unused
}

RMS :: ~RMS()
{
   delete subLowFilter;
}

void RMS :: clear()
{
   lastOutput = 0.0;
   counter = 0;
   subLowFilter->clear();
}

void RMS :: setFreq(double freq)
{
   subLowFilter->setFreq(freq);
}

void RMS :: setWindowSize(int nsamples)
{
   windowSize = nsamples;
   counter = 0;
}

double RMS :: tick(double sample)
{
   double temp = subLowFilter->tick(sample * sample);
   if (--counter < 0) {
      lastOutput = sqrt(temp);
      counter = windowSize;
   }
   return lastOutput;
}

Clear should also clear filter.


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

#include <memory>

#include <boost/variant.hpp>

#include "tac/Printer.hpp"
#include "tac/Program.hpp"

#include "VisitorUtils.hpp"

using namespace eddic;

struct DebugVisitor : public boost::static_visitor<> {
    void operator()(tac::Program& program){
        std::cout << "TAC Program " << std::endl << std::endl;

        visit_each_non_variant(*this, program.functions);
    }

    void operator()(std::shared_ptr<tac::Function> function){
        std::cout << "Function " << function->getName() << std::endl;
    }
};

void tac::Printer::print(tac::Program& program) const {
   DebugVisitor visitor;
   visitor(program);
}

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

#include <memory>

#include <boost/variant.hpp>

#include "tac/Printer.hpp"
#include "tac/Program.hpp"

#include "VisitorUtils.hpp"

using namespace eddic;

struct DebugVisitor : public boost::static_visitor<> {
    void operator()(tac::Program& program){
        std::cout << "TAC Program " << std::endl << std::endl;

        visit_each_non_variant(*this, program.functions);
    }

    void operator()(std::shared_ptr<tac::Function> function){
        std::cout << "Function " << function->getName() << std::endl;

        visit_each(*this, function->getStatements());
    }

    void operator()(tac::Quadruple& quadruple){

    }

    void operator()(tac::IfFalse& ifFalse){

    }

    void operator()(tac::Goto& goto_){

    }

    void operator()(tac::Param& param){

    }

    void operator()(tac::Return& return_){

    }

    void operator()(tac::Call& call){

    }

    void operator()(std::string& label){
        std::cout << label << ":" << std::endl;
    }
};

void tac::Printer::print(tac::Program& program) const {
   DebugVisitor visitor;
   visitor(program);
}

Add prototypes for the debug printer


#include "Cursor.h"

Cursor* Cursor::instance = NULL;

Cursor::Cursor() : Sprite()
{
    // Status
    m_show = true;

    // Arrangement
    m_anchor = Vec2<double>(0.0, 0.0);

    m_texture_dst = new SDL_Rect;
    m_texture_dst->x = -m_size.x;
    m_texture_dst->y = -m_size.y;
    m_texture_dst->w = m_size.x;
    m_texture_dst->h = m_size.y;

    // Image
    m_sprite_path = "resources/cursor.png";
    m_sprite_path = "resources/potato.jpg";
}

Cursor* Cursor::getInstance()
{
	if (instance == NULL)
		instance = new Cursor;

	return instance;
}

Cursor::~Cursor() {}

void Cursor::update()
{

}

#include "Cursor.h"

Cursor* Cursor::instance = NULL;

Cursor::Cursor() : Sprite()
{
    // Status
    m_show = true;

    // Arrangement
    m_anchor = Vec2<double>(0.0, 0.0);

    m_texture_dst = new SDL_Rect;
    m_texture_dst->x = -m_size.x;
    m_texture_dst->y = -m_size.y;
    m_texture_dst->w = m_size.x;
    m_texture_dst->h = m_size.y;

    // Image
    m_sprite_path = "resources/cursor.png";
}

Cursor* Cursor::getInstance()
{
	if (instance == NULL)
		instance = new Cursor;

	return instance;
}

Cursor::~Cursor() {}

void Cursor::update()
{

}

Change default cursor-image location to non-test path


#include "vertexbuffer.hpp"

#include "collisiondetection/axisalignedboundingbox.hpp"

using namespace modelloader;

VertexBuffer::VertexBuffer(VertexBuffer&& other) : vBO{other.vBO}, iBO{other.iBO}, nBO{other.nBO}, numIndices{other.numIndices}, extremes{other.extremes},
bounds(std::move(other.bounds)){
}

VertexBuffer::VertexBuffer(GLuint myVBO, GLuint myIBO, GLuint myNBO, unsigned int myNumIndices, std::tuple<glm::vec3, glm::vec3> myExtremes)
: vBO(myVBO), iBO(myIBO), nBO(myNBO), numIndices(myNumIndices), extremes(myExtremes), bounds{new collisiondetection::AxisAlignedBoundingBox(extremes)} {
	//Generate VAO
	glGenVertexArrays(1, &vao);
	glBindVertexArray(vao);

	glBindBuffer(GL_ARRAY_BUFFER, vBO);
	glVertexAttribPointer(0, 3, GL_FLOAT, false, 0, 0);
	glEnableVertexAttribArray(0);

	glBindBuffer(GL_ARRAY_BUFFER, nBO);
	glVertexAttribPointer(1, 3, GL_FLOAT, false, 0, 0);
	glEnableVertexAttribArray(1);
}

void VertexBuffer::bindBuffers() const {
	glBindVertexArray(vao);
	glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, iBO);
}

#include "vertexbuffer.hpp"

#include "collisiondetection/axisalignedboundingbox.hpp"

using namespace modelloader;

VertexBuffer::VertexBuffer(VertexBuffer&& other) : vBO{other.vBO}, iBO{other.iBO}, nBO{other.nBO}, vao(other.vao), numIndices{other.numIndices}, extremes{other.extremes},
bounds(std::move(other.bounds)){
}

VertexBuffer::VertexBuffer(GLuint myVBO, GLuint myIBO, GLuint myNBO, unsigned int myNumIndices, std::tuple<glm::vec3, glm::vec3> myExtremes)
: vBO(myVBO), iBO(myIBO), nBO(myNBO), numIndices(myNumIndices), extremes(myExtremes), bounds{new collisiondetection::AxisAlignedBoundingBox(extremes)} {
	//Generate VAO
	glGenVertexArrays(1, &vao);
	glBindVertexArray(vao);

	glBindBuffer(GL_ARRAY_BUFFER, vBO);
	glVertexAttribPointer(0, 3, GL_FLOAT, false, 0, 0);
	glEnableVertexAttribArray(0);

	glBindBuffer(GL_ARRAY_BUFFER, nBO);
	glVertexAttribPointer(1, 3, GL_FLOAT, false, 0, 0);
	glEnableVertexAttribArray(1);
}

void VertexBuffer::bindBuffers() const {
	glBindVertexArray(vao);
	glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, iBO);
}

Fix VertexBuffer move-constructor, vao was not copied.


//! \file CacheJsonToArticleConverter.cpp

#include "CacheJsonToArticleConverter.h"

#include <json/json.h>

#include "WalkerException.h"
#include "Article.h"

ArticleCollection& CacheJsonToArticleConverter::convertToArticle(std::string json,
        ArticleCollection& articleCache)
{
    Json::Reader reader;
    Json::Value document;
    bool success = reader.parse(json, document, false);

    if(!success) {
        throw WalkerException("Error parsing JSON");
    }

    // get all "main" articles first
    for(auto& titleElement : document.getMemberNames()) {
        std::string title = titleElement;

        Article* a = articleCache.get(title);

        if(a == nullptr) {
            a = new Article(title);
            articleCache.add(a);
        }

        auto links = document
                        .get(title, Json::Value::nullSingleton())
                        .get("forward_links", Json::Value::nullSingleton());

        if(links.isNull()) {
            /* don't need to set article analyzed to false,
             * since that's the default */
            continue;
        }

        a->setAnalyzed(true);

        for(auto linkedArticle : links) {
            std::string linkedTitle = linkedArticle.asString();
            Article* la = articleCache.get(linkedTitle);

            if(la == nullptr) {
                la = new Article(linkedTitle);
                articleCache.add(la);
            }

            a->addLink(la);
        }
    }

    return articleCache;
    /*
        a->setAnalyzed(true); ?
    */
}

//! \file CacheJsonToArticleConverter.cpp

#include "CacheJsonToArticleConverter.h"

#include <json/json.h>

#include "WalkerException.h"
#include "Article.h"

ArticleCollection& CacheJsonToArticleConverter::convertToArticle(std::string json,
        ArticleCollection& articleCache)
{
    Json::Reader reader;
    Json::Value document;
    bool success = reader.parse(json, document, false);

    if(!success) {
        throw WalkerException("Error parsing JSON");
    }

    // get all "main" articles first
    for(auto& titleElement : document.getMemberNames()) {
        std::string title = titleElement;

        auto a = articleCache.get(title);

        if(a == nullptr) {
            a = std::make_shared<Article>(title);
            articleCache.add(a);
        }

        auto links = document
                        .get(title, Json::Value::nullSingleton())
                        .get("forward_links", Json::Value::nullSingleton());

        if(links.isNull()) {
            /* don't need to set article analyzed to false,
             * since that's the default */
            continue;
        }

        a->setAnalyzed(true);

        for(auto linkedArticle : links) {
            std::string linkedTitle = linkedArticle.asString();
            std::shared_ptr<Article> la = articleCache.get(linkedTitle);

            if(la == nullptr) {
                la = std::make_shared<Article>(linkedTitle);
                articleCache.add(la);
            }

            a->addLink(la);
        }
    }

    return articleCache;
    /*
        a->setAnalyzed(true); ?
    */
}

Migrate to smart pointers, part five


#include <ncurses.h>

#include <string>

int main() {

    /*
     * init term
     */

    initscr();
    cbreak();
    noecho();
    clear();

    /*
     * init title
     */

    move(5, 5);
    std::string title = "TERMINAL QUEST";
    for (int i; i < title.size(); i++) {
        addch(title[i]);
        addch(' ');
    }

    refresh();
    while(true);

    /*
     * exit
     */

    return 0;
}

#include <ncurses.h>

#include <string>

using namespace std;

void menuShow();
void menuAdd(int pos, string str);
void menuDone();

int main() {

    /*
     * init term
     */

    initscr();
    cbreak();
    noecho();
    clear();

    /*
     * init title
     */
    menuShow();

    refresh();
    while(true);

    /*
     * exit
     */

    return 0;
}

void menuShow() {

    move(5, 5); // move cursor to (x,y)

    string text = "TERMINAL QUEST";
    for (size_t i = 0; i < text.size(); i++) {
        addch(text[i]);
        addch(' ');
    }

    menuAdd(1, "start");
    menuAdd(2, "quit");
    menuDone();

    refresh();

    while(1);
}

void close() {
    endwin();
}

// Private functions

void menuAdd(int pos, string str) {
    if (pos > 0 && str.length() > 0) {
        move((pos + 6), 8);
        addstr(str.c_str());
    }
}

void menuDone() {
    move(7, 6);
}

Move title screen init to private fn


/*
 * This file is part of libqcalparser
 *
 * Copyright (C) Rohan Garg <rohan16garg@gmail.com>
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 */

#include "qcalparser.h"
#include "qcalevent.h"

#include <QtCore/QCoreApplication>
#include <QFile>
#include <QString>
#include <QDebug>

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);
    QFile *file = new QFile(a.arguments().at(1));
    QCalParser *parser = new QCalParser(file);
    foreach(QCalEvent* event, parser->getEventList()) {
        qDebug() << event->eventUID();
        qDebug() << event->categoryList();
        qDebug() << event->eventDescription();
        qDebug() << event->eventUrl();
        qDebug() << event->eventUrlType();
        qDebug() << event->eventLocation();
        qDebug() << event->eventRoomName();
        qDebug() << event->eventStartDate();
        qDebug() << event->eventStopDate();
     }
}

Add proper licensing to file