#include "Server.h"
#include "IgnoreDebugOutput.h"
#include "StdinNotifier.h"
#include <QApplication>
#include <iostream>
#ifdef Q_OS_UNIX
  #include <unistd.h>
#endif

int main(int argc, char **argv) {
#ifdef Q_OS_UNIX
  if (setpgid(0, 0) < 0) {
    std::cerr << "Unable to set new process group." << std::endl;
    return 1;
  }
#endif

  QApplication app(argc, argv);
  app.setApplicationName("capybara-webkit");
  app.setOrganizationName("thoughtbot, inc");
  app.setOrganizationDomain("thoughtbot.com");

  StdinNotifier notifier;
  QObject::connect(&notifier, SIGNAL(eof()), &app, SLOT(quit()));

  ignoreDebugOutput();
  Server server(0);

  if (server.start()) {
    std::cout << "Capybara-webkit server started, listening on port: " << server.server_port() << std::endl;
    return app.exec();
  } else {
    std::cerr << "Couldn't start capybara-webkit server" << std::endl;
    return 1;
  }
}

#include "Server.h"
#include "IgnoreDebugOutput.h"
#include "StdinNotifier.h"
#include <QApplication>
#include <iostream>
#ifdef Q_OS_UNIX
  #include <unistd.h>
#endif

int main(int argc, char **argv) {
#ifdef Q_OS_UNIX
  if (setpgid(0, 0) < 0) {
    std::cerr << "Unable to set new process group." << std::endl;
    return 1;
  }
#endif

#ifdef Q_OS_MAC
  QApplication::setStyle(QStyleFactory::create("Fusion"));
#endif

  QApplication app(argc, argv);
  app.setApplicationName("capybara-webkit");
  app.setOrganizationName("thoughtbot, inc");
  app.setOrganizationDomain("thoughtbot.com");

  StdinNotifier notifier;
  QObject::connect(&notifier, SIGNAL(eof()), &app, SLOT(quit()));

  ignoreDebugOutput();
  Server server(0);

  if (server.start()) {
    std::cout << "Capybara-webkit server started, listening on port: " << server.server_port() << std::endl;
    return app.exec();
  } else {
    std::cerr << "Couldn't start capybara-webkit server" << std::endl;
    return 1;
  }
}

Use the Fusion Qt Style on OS X


#include <QtCore/QSettings>
#include <QtCore/QVariant>
#include <QtGui/QApplication>
#include <QtGui/QFont>

#include <memory>

extern "C" {
#include <libxslt/xslt.h>
#include <libxml/parser.h>
#include <libxml/xpath.h>
#include <libexslt/exslt.h>
}

#include "DactMainWindow.h"

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    QSettings settings("RUG", "Dact");
    QVariant fontValue = settings.value("appFont", qApp->font().toString());
    QFont appFont;
    appFont.fromString(fontValue.toString());
    qApp->setFont(appFont);

    xmlInitMemory();
    xmlInitParser();

    // EXSLT extensions
    exsltRegisterAll();

    // XPath
    xmlXPathInit();

    std::auto_ptr<DactMainWindow> w(new DactMainWindow);
    w->show();

    if (qApp->arguments().size() == 2)
        w->readCorpus(qApp->arguments().at(1));

    int r = a.exec();

    xsltCleanupGlobals();
    xmlCleanupParser();

    return r;
}

#include <QtCore/QSettings>
#include <QtCore/QVariant>
#include <QtGui/QApplication>
#include <QtGui/QFont>
#include <QScopedPointer>

extern "C" {
#include <libxslt/xslt.h>
#include <libxml/parser.h>
#include <libxml/xpath.h>
#include <libexslt/exslt.h>
}

#include "DactMainWindow.h"

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    QSettings settings("RUG", "Dact");
    QVariant fontValue = settings.value("appFont", qApp->font().toString());
    QFont appFont;
    appFont.fromString(fontValue.toString());
    qApp->setFont(appFont);

    xmlInitMemory();
    xmlInitParser();

    // EXSLT extensions
    exsltRegisterAll();

    // XPath
    xmlXPathInit();

    QScopedPointer<DactMainWindow> w(new DactMainWindow);
    w->show();

    if (qApp->arguments().size() == 2)
        w->readCorpus(qApp->arguments().at(1));

    int r = a.exec();

    xsltCleanupGlobals();
    xmlCleanupParser();

    return r;
}

Use QScopedPointer instead of std::auto_ptr, per Daniel's request


#include<cmath>
#include<iostream>

using namespace std;

bool isPrimeBruteForce(int x)
{
	if (x < 2)
		return false;
	float sqroot_x = sqrt(x);
	for(int i=0; i <= sqroot_x; i++) { /* If there were only factors above the square root of x, they would be bigger than x itself. */
		if (x%i==0)
			return false;
	}
	return true;
}

int main(int argc, char* argv[])
{
	int number;
	bool result;
	cout << "Enter number to test if it's prime: ";
	cin >> number;
	result = isPrimeBruteForce(number);
	if result {
		cout << number << " is a prime number.";
	} else {
		cout << number << " is not a prime number.";
	}
	return 0;
}

#include<cmath>
#include<iostream>

using namespace std;

bool isPrimeBruteForce(int x)
{
	if (x < 2)
		return false;
	float sqroot_x = sqrt(x);
	for(int i=0; i <= sqroot_x; i++) { /* If there were only factors above the square root of x, they would be bigger than x itself. */
		if (x%i==0)
			return false;
	}
	return true;
}

int main(int argc, char* argv[])
{
	int number;
	bool result;
	cout << "Enter number to test if it's prime: ";
	cin >> number;
	result = isPrimeBruteForce(number);
	if (result) {
		cout << number << " is a prime number.";
	} else {
		cout << number << " is not a prime number.";
	}
	return 0;
}

Correct syntax error in line 25


#include "WebSocketWrapper.hpp"
#include <thread>
#include <iostream>

using namespace rtcdcpp;

WebSocketWrapper::WebSocketWrapper(std::string url) : url(url), send_queue() { ; }

WebSocketWrapper::~WebSocketWrapper() { delete this->ws; }

bool WebSocketWrapper::Initialize() {
  this->ws = WebSocket::from_url(this->url);
  return this->ws ? true : false;
}

void WebSocketWrapper::SetOnMessage(std::function<void(std::string)> onMessage) { this->onMessage = onMessage; }

void WebSocketWrapper::Start() {
  this->stopping = false;
  this->send_loop = std::thread(&WebSocketWrapper::Loop, this);
}

void WebSocketWrapper::Loop() {
  while (!this->stopping) {
    this->ws->poll();
    std::this_thread::sleep_for(std::chrono::milliseconds(500));
    if (!this->send_queue.empty()) {
      ChunkPtr chunk = this->send_queue.wait_and_pop();
      std::string msg(reinterpret_cast<char const*>(chunk->Data()), chunk->Length());
      this->ws->send(msg);
      this->ws->poll();
    }
    this->ws->dispatch(this->onMessage);
  }
}

void WebSocketWrapper::Send(std::string msg) { this->send_queue.push(std::shared_ptr<Chunk>(new Chunk((const void*)msg.c_str(), msg.length()))); }

void WebSocketWrapper::Close() { this->stopping = true; this->send_loop.join(); }

#include "WebSocketWrapper.hpp"
#include <thread>
#include <iostream>

using namespace rtcdcpp;

WebSocketWrapper::WebSocketWrapper(std::string url) : url(url), send_queue() { ; }

WebSocketWrapper::~WebSocketWrapper() { delete this->ws; }

bool WebSocketWrapper::Initialize() {
  this->ws = WebSocket::from_url(this->url);
  return this->ws ? true : false;
}

void WebSocketWrapper::SetOnMessage(std::function<void(std::string)> onMessage) { this->onMessage = onMessage; }

void WebSocketWrapper::Start() {
  this->stopping = false;
  this->send_loop = std::thread(&WebSocketWrapper::Loop, this);
}

void WebSocketWrapper::Loop() {
  while (!this->stopping) {
    this->ws->poll();
    std::this_thread::sleep_for(std::chrono::milliseconds(50));
    if (!this->send_queue.empty()) {
      ChunkPtr chunk = this->send_queue.wait_and_pop();
      std::string msg(reinterpret_cast<char const*>(chunk->Data()), chunk->Length());
      this->ws->send(msg);
      this->ws->poll();
    }
    this->ws->dispatch(this->onMessage);
  }
}

void WebSocketWrapper::Send(std::string msg) { this->send_queue.push(std::shared_ptr<Chunk>(new Chunk((const void*)msg.c_str(), msg.length()))); }

void WebSocketWrapper::Close() { this->stopping = true; this->send_loop.join(); }

Reduce WebSocket poll delay to 50ms


#include <iostream>

#include "absl/strings/str_cat.h"
#include "absl/strings/string_view.h"
#include "google/protobuf/util/json_util.h"

#include "src/protobuf/test.pb.h"

int main() {
  // verify link and compile versions are the same
  GOOGLE_PROTOBUF_VERIFY_VERSION;

  // testing absl
  std::cout << absl::StrCat("Hello ", "World!") << std::endl;

  TestMessage test_message;
  test_message.set_value(10);
  test_message.set_name("My String");

  // as a string
  std::cout << "String debug:" << std::endl;
  std::cout << test_message.DebugString() << std::endl;

  // as JSON
  std::string json_output;
  google::protobuf::util::MessageToJsonString(test_message, &json_output);
  std::cout << "JSON:" << std::endl;
  std::cout << json_output << std::endl << std::endl;

  // parsing JSON
  TestMessage test_message_2;
  google::protobuf::util::JsonStringToMessage(
      "{\"value\":1, \"name\": \"Testing\" }",
      &test_message_2);
  std::cout << "Debug Reading:" << std::endl;
  std::cout << test_message_2.DebugString() << std::endl;

  return 0;
};

#include <iostream>
#include <string>

// #include "absl/strings/str_cat.h"
// #include "absl/strings/string_view.h"
#include "google/protobuf/util/json_util.h"

#include "src/protobuf/bmv2/program.pb.h"

void ReadStdin(std::string& str) {
  std::istreambuf_iterator<char> cin_iterator{std::cin};
  std::istreambuf_iterator<char> end;
  str = std::string(cin_iterator, end);
}

int main() {
  // verify link and compile versions are the same
  GOOGLE_PROTOBUF_VERIFY_VERSION;

  std::string input;
  ReadStdin(input);

  // testing absl
  // std::cout << absl::StrCat("Hello ", "World!") << std::endl;

  // parsing JSON
  P4Program program;
  google::protobuf::util::JsonParseOptions parsing_options;
  parsing_options.ignore_unknown_fields = true;
  google::protobuf::util::JsonStringToMessage(input, &program, parsing_options);

  // printing JSON
  google::protobuf::util::JsonPrintOptions dumping_options;
  dumping_options.add_whitespace = true;
  dumping_options.always_print_primitive_fields = true;
  dumping_options.preserve_proto_field_names = true;

  std::string output;
  google::protobuf::util::MessageToJsonString(program, &output, dumping_options);
  std::cout << output << std::endl;

  return 0;
};

Add simple C++ stub for testing protobuf definitions


#include <iostream>

#include "Board.h"

int main()
{
  Board b(10, 10);
  b.fillRandomly(10);

  std::cout << "main executed" << std::endl;
  return 0;
}

#include <cstdio>

#include "Board.h"
#include "AGE/Engine.h"

int main()
{
  AGE::Engine engine;

  printf("Initializing...\n");
  if (!engine.init())
  {
    printf("Advanced Game Engine failed to initialize. Exiting.\n");
    exit(1);
  }

  printf("Initialization complete.\nLoading the media...\n");
  if (!engine.loadMedia())
  {
    printf("Warning: some media files failed to load!\n");
  }
  printf("Media loded.\n");

  engine.startLoop();

  // Destroys the window and quits the SDL system:
  engine.close();
  return 0;
}

Use the engine to create a game window


/*
 * BasicLayout.cpp
 *
 * Copyright 2000, LifeLine Networks BV (www.lifeline.nl). All rights reserved.
 * Copyright 2000, Bastiaan Bakker. All rights reserved.
 *
 * See the COPYING file for the terms of usage and distribution.
 */

#include "PortabilityImpl.hh"
#include <log4cpp/BasicLayout.hh>
#include <log4cpp/Priority.hh>
#include <log4cpp/FactoryParams.hh>
#ifdef LOG4CPP_HAVE_SSTREAM
#include <sstream>
#endif

namespace log4cpp {

    BasicLayout::BasicLayout() {
    }

    BasicLayout::~BasicLayout() {
    }

    std::string BasicLayout::format(const LoggingEvent& event) {
        std::ostringstream message;

        const std::string& priorityName = Priority::getPriorityName(event.priority);
        message << event.timeStamp.getSeconds() << " " << priorityName << " "
                << event.categoryName << " " << event.ndc << ": "
                << event.message << std::endl;

        return message.str();
    }

    std::auto_ptr<Layout> create_basic_layout(const FactoryParams& params)
    {
       return std::auto_ptr<Layout>(new BasicLayout);
    }
}

/*
 * BasicLayout.cpp
 *
 * Copyright 2000, LifeLine Networks BV (www.lifeline.nl). All rights reserved.
 * Copyright 2000, Bastiaan Bakker. All rights reserved.
 *
 * See the COPYING file for the terms of usage and distribution.
 */

#include "PortabilityImpl.hh"
#include <log4cpp/BasicLayout.hh>
#include <log4cpp/Priority.hh>
#include <log4cpp/FactoryParams.hh>
#ifdef LOG4CPP_HAVE_SSTREAM
#include <sstream>
#endif
#include <memory>

namespace log4cpp {

    BasicLayout::BasicLayout() {
    }

    BasicLayout::~BasicLayout() {
    }

    std::string BasicLayout::format(const LoggingEvent& event) {
        std::ostringstream message;

        const std::string& priorityName = Priority::getPriorityName(event.priority);
        message << event.timeStamp.getSeconds() << " " << priorityName << " "
                << event.categoryName << " " << event.ndc << ": "
                << event.message << std::endl;

        return message.str();
    }

    std::auto_ptr<Layout> create_basic_layout(const FactoryParams& params)
    {
       return std::auto_ptr<Layout>(new BasicLayout);
    }
}

Add missing header file for Ubuntu Jaunty and beyond


#include "Interpreter.hpp"

#include "modules/error-handler/ErrorHandler.hpp"
#include "modules/lexer/Lexer.hpp"

#include <iostream>

using Interpreter = tkom::Interpreter;
using ErrorHandler = tkom::modules::ErrorHandler;
using Lexer = tkom::modules::Lexer;

Interpreter::Interpreter(const std::vector<std::string>& arguments)
{
    try
    {
        if (arguments.size() < 1)
        {
            ErrorHandler::error("No input file specified");
        }

        Lexer lexer(arguments.at(0));

        Token token;

        do
        {
            token = lexer.nextToken();

            std::cout << tkom::modules::utils::getTokenTypeName(token.type) << " = " << token.value << std::endl;
        }
        while(token.type != TokenType::Invalid && token.type != TokenType::EndOfFile);
    }
    catch(ErrorHandler::Exception &e)
    {
        ErrorHandler::error("Terminating...", true);
    }
}

#include "Interpreter.hpp"

#include "modules/error-handler/ErrorHandler.hpp"
#include "modules/lexer/Lexer.hpp"
#include "modules/parser/Parser.hpp"

using Interpreter = tkom::Interpreter;
using ErrorHandler = tkom::modules::ErrorHandler;
using Lexer = tkom::modules::Lexer;
using Parser = tkom::modules::Parser;

Interpreter::Interpreter(const std::vector<std::string>& arguments)
{
    try
    {
        if (arguments.size() < 1)
        {
            ErrorHandler::error("No input file specified");
        }

        Lexer lexer(arguments.at(0));
        Parser parser(lexer);

        parser.parse();
    }
    catch(ErrorHandler::Exception &e)
    {
        ErrorHandler::error("Terminating...", true);
    }
}

Use Parser module to parse a file


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

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

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

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

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

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

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

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

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


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

#include "chrome/test/chromedriver/chrome/device_metrics.h"

DeviceMetrics::DeviceMetrics(int width, int height, double device_scale_factor)
  : width(width),
    height(height),
    device_scale_factor(device_scale_factor),
    mobile(false),
    fit_window(false),
    text_autosizing(true),
    font_scale_factor(1) {}

DeviceMetrics::~DeviceMetrics() {}

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

#include "chrome/test/chromedriver/chrome/device_metrics.h"

DeviceMetrics::DeviceMetrics(int width, int height, double device_scale_factor)
  : width(width),
    height(height),
    device_scale_factor(device_scale_factor),
    mobile(true),
    fit_window(false),
    text_autosizing(true),
    font_scale_factor(1) {}

DeviceMetrics::~DeviceMetrics() {}

Set mobile=true when calling setDeviceMetricsOverride


#include "scene/scenegroup.hpp"

#include <algorithm>

using namespace scene;

SceneGroup::SceneGroup(unsigned int octreeLevels) {
	addOctreeLayers(octreeLevels);
}

void SceneGroup::addOctreeLayers(unsigned int levels) {
	childGroups.reset(new std::array<SceneGroup,8>);

	std::for_each(childGroups->begin(), childGroups->end(),
	[&levels](SceneGroup& child) {
		child.addOctreeLayers(--levels);
	});
}

void SceneGroup::updateScene() {
	std::for_each(childItems.begin(), childItems.end(), [](std::unique_ptr<SceneItem>& child) {
		child->update();
	});

	if(childGroups != nullptr) {
		std::for_each(childGroups->begin(), childGroups->end(),
		[](SceneGroup& child) {
			child.updateScene();
		});
	}
}

void SceneGroup::renderScene() {
	std::for_each(childItems.begin(), childItems.end(), [](std::unique_ptr<SceneItem>& child) {
		child->draw();
	});

	if(childGroups != nullptr) {
		std::for_each(childGroups->begin(), childGroups->end(),
		[](SceneGroup& child) {
			child.renderScene();
		});
	}
}

#include "scene/scenegroup.hpp"

#include <algorithm>

using namespace scene;

SceneGroup::SceneGroup(unsigned int octreeLevels) {
	addOctreeLayers(octreeLevels);
}

void SceneGroup::addOctreeLayers(unsigned int levels) {
	if(levels != 0) {
		childGroups.reset(new std::array<SceneGroup,8>);

		std::for_each(childGroups->begin(), childGroups->end(),
		[&levels](SceneGroup& child) {
			child.addOctreeLayers(--levels);
		});
	}
}

void SceneGroup::updateScene() {
	std::for_each(childItems.begin(), childItems.end(), [](std::unique_ptr<SceneItem>& child) {
		child->update();
	});

	if(childGroups != nullptr) {
		std::for_each(childGroups->begin(), childGroups->end(),
		[](SceneGroup& child) {
			child.updateScene();
		});
	}
}

void SceneGroup::renderScene() {
	std::for_each(childItems.begin(), childItems.end(), [](std::unique_ptr<SceneItem>& child) {
		child->draw();
	});

	if(childGroups != nullptr) {
		std::for_each(childGroups->begin(), childGroups->end(),
		[](SceneGroup& child) {
			child.renderScene();
		});
	}
}

Fix recursive add of octreelevels in SceneGroup


// RUN: %clang_cl_asan -O0 %s -Fe%t
// RUN: env ASAN_OPTIONS=handle_segv=0 %run %t 2>&1 | FileCheck %s --check-prefix=USER
// RUN: env ASAN_OPTIONS=handle_segv=1 not %run %t 2>&1 | FileCheck %s --check-prefix=ASAN
// Test the default.
// RUN: not %run %t 2>&1 | FileCheck %s --check-prefix=ASAN

// This test exits zero when its unhandled exception filter is set. ASan should
// not disturb it when handle_segv=0.

// USER: in main
// USER: in SEHHandler

// ASAN: in main
// ASAN: ERROR: AddressSanitizer: access-violation

#include <windows.h>
#include <stdio.h>

static long WINAPI SEHHandler(EXCEPTION_POINTERS *info) {
  DWORD exception_code = info->ExceptionRecord->ExceptionCode;
  if (exception_code == EXCEPTION_ACCESS_VIOLATION) {
    fprintf(stderr, "in SEHHandler\n");
    fflush(stdout);
    TerminateProcess(GetCurrentProcess(), 0);
  }
  return EXCEPTION_CONTINUE_SEARCH;
}

int main() {
  SetUnhandledExceptionFilter(SEHHandler);
  fprintf(stderr, "in main\n");

  volatile int *p = nullptr;
  *p = 42;
}

// RUN: %clang_cl_asan -O0 %s -Fe%t
// RUN: env ASAN_OPTIONS=handle_segv=0 %run %t 2>&1 | FileCheck %s --check-prefix=USER
// RUN: env ASAN_OPTIONS=handle_segv=1 not %run %t 2>&1 | FileCheck %s --check-prefix=ASAN
// Test the default.
// RUN: not %run %t 2>&1 | FileCheck %s --check-prefix=ASAN

// This test exits zero when its unhandled exception filter is set. ASan should
// not disturb it when handle_segv=0.

// USER: in main
// USER: in SEHHandler

// ASAN: in main
// ASAN: ERROR: AddressSanitizer: access-violation

#include <windows.h>
#include <stdio.h>

static long WINAPI SEHHandler(EXCEPTION_POINTERS *info) {
  DWORD exception_code = info->ExceptionRecord->ExceptionCode;
  if (exception_code == EXCEPTION_ACCESS_VIOLATION) {
    fprintf(stderr, "in SEHHandler\n");
    fflush(stderr);
    TerminateProcess(GetCurrentProcess(), 0);
  }
  return EXCEPTION_CONTINUE_SEARCH;
}

int main() {
  SetUnhandledExceptionFilter(SEHHandler);
  fprintf(stderr, "in main\n");
  fflush(stderr);

  volatile int *p = nullptr;
  *p = 42;
}

Add flushes to try to fix test


#include "singletons/Emotes.hpp"

#include "Application.hpp"
#include "controllers/accounts/AccountController.hpp"

namespace chatterino {

void Emotes::initialize(Application &app)
{
    app.accounts->twitch.currentUserChanged.connect([this, &app] {
        auto currentUser = app.accounts->twitch.getCurrent();
        assert(currentUser);
        this->twitch.refresh(currentUser);
    });

    this->emojis.load();
    this->bttv.loadGlobalEmotes();
    this->ffz.loadGlobalEmotes();

    this->gifTimer.initialize();
}

bool Emotes::isIgnoredEmote(const QString &)
{
    return false;
}

}  // namespace chatterino

#include "singletons/Emotes.hpp"

#include "Application.hpp"
#include "controllers/accounts/AccountController.hpp"

namespace chatterino {

void Emotes::initialize(Application &app)
{
    const auto refreshTwitchEmotes = [this, &app] {
        auto currentUser = app.accounts->twitch.getCurrent();
        assert(currentUser);
        this->twitch.refresh(currentUser);
    };
    app.accounts->twitch.currentUserChanged.connect(refreshTwitchEmotes);
    refreshTwitchEmotes();

    this->emojis.load();
    this->bttv.loadGlobalEmotes();
    this->ffz.loadGlobalEmotes();

    this->gifTimer.initialize();
}

bool Emotes::isIgnoredEmote(const QString &)
{
    return false;
}

}  // namespace chatterino

Load twitch emotes on initialize as well


#define BOOST_TEST_MAIN
#define BOOST_TEST_DYN_LINK
#define BOOST_TEST_MODULE flatten_tests
#include <boost/test/unit_test.hpp>

#include "flatten/flatten.hpp"

BOOST_AUTO_TEST_CASE(flatten_tests)
{

}

#define BOOST_TEST_MAIN
#define BOOST_TEST_DYN_LINK
#define BOOST_TEST_MODULE flatten_tests
#include <boost/test/unit_test.hpp>

#include <list>
#include <vector>
#include <map>

#include "flatten/flatten.hpp"

typedef std::vector<int> IntList;
typedef std::vector<IntList> IntListList;
typedef std::vector<IntListList> IntListListList;

IntListListList example1_values()
{
    IntListListList values;
    IntListList a;
    IntList a1;
    IntList a2;
    IntList a3;
    IntListList b;
    IntList b1;
    IntList b2;
    IntList b3;

    a1.push_back(1);
    a1.push_back(2);
    a1.push_back(3);

    a2.push_back(4);
    a2.push_back(5);
    a2.push_back(6);

    /* a3 empty */

    b1.push_back(7);

    b2.push_back(8);

    b3.push_back(9);

    a.push_back(a1);
    a.push_back(a2);
    a.push_back(a3);

    b.push_back(b1);
    b.push_back(b2);
    b.push_back(b3);

    values.push_back(a);
    values.push_back(b);
    return values;
}

BOOST_AUTO_TEST_CASE(example1)
{
    IntListListList values = example1_values();
    IntList result;

    flatten::flatten<int>(
        values.begin(), values.end(), std::back_inserter(result)
    );

    for (int i = 0; i < 9; ++i)
    {
        BOOST_REQUIRE(i < result.size());
        BOOST_CHECK_EQUAL(result[i], i + 1);
    }
}

Add test for Example 1.


#if defined(__x86_64__) || defined(_M_X64)
  X86_64

#elif defined(__i386__) || defined(__i386) || defined(_M_IX86)
  X86_32

#elif defined(__aarch64__) || defined(__ARM_ARCH_ISA_A64)
  ARM64

#elif defined(__arm__) || defined(_M_ARM) || defined(__ARM_ARCH_7A__)
  ARM32

#elif defined(__powerpc64__) || defined(__ppc64__) || defined(_ARCH_PPC64)
  PPC64

#elif defined(__powerpc__) || defined(__ppc__) || defined(_ARCH_PPC)
  PPC32

#elif defined(__mips__) || defined(__mips)
  MIPS32

#elif defined(__sparc__)
  SPARC32

#elif defined(__alpha__)
  ALPHA

#elif defined(__hppa__) || defined(__hppa)
  HPPA

#elif defined(__ia64__)
  IA64

#elif defined(__m68k__)
  M68K

#elif defined(__sh__)
  SH

#elif defined(__s390x__)
  S390X

#elif defined(__s390__)
  S390

#else
  UNKNOWN

#endif

#if defined(__x86_64__) || defined(_M_X64)
  X86_64

#elif defined(__i386__) || defined(__i386) || defined(_M_IX86)
  X86_32

#elif defined(__aarch64__) || defined(__ARM_ARCH_ISA_A64)
  ARM64

#elif defined(__arm__) || defined(_M_ARM) || defined(__ARM_ARCH_7A__)
  ARM32

#elif defined(__powerpc64__) || defined(__ppc64__) || defined(_ARCH_PPC64)
  PPC64

#elif defined(__powerpc__) || defined(__ppc__) || defined(_ARCH_PPC)
  PPC32

#elif defined(__mips__) || defined(__mips)

  #if defined(__LP64__) || defined(_LP64)
  MIPS64
  #else
  MIPS32
  #endif

#elif defined(__sparc__)

  #if defined(__LP64__) || defined(_LP64)
  SPARC64
  #else
  SPARC32
  #endif

#elif defined(__alpha__)
  ALPHA

#elif defined(__hppa__) || defined(__hppa)
  HPPA

#elif defined(__ia64__)
  IA64

#elif defined(__m68k__)
  M68K

#elif defined(__sh__)
  SH

#elif defined(__s390x__)
  S390X

#elif defined(__s390__)
  S390

#else
  UNKNOWN

#endif

Fix autodetection of sparc64/mips64


// ========================================================================== //
// This file is part of DO++, a basic set of libraries in C++ for computer
// vision.
//
// Copyright (C) 2013 David Ok <david.ok8@gmail.com>
//
// This Source Code Form is subject to the terms of the Mozilla Public
// License v. 2.0. If a copy of the MPL was not distributed with this file,
// you can obtain one at http://mozilla.org/MPL/2.0/.
// ========================================================================== //

#include <gtest/gtest.h>

#include <DO/Defines.hpp>
#include <DO/ImageProcessing/Deriche.hpp>

#include "utilities.hpp"

using namespace std;
using namespace DO;

TEST(TestDericheFilter, test_inplace_deriche_blur)
{
}

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

// ========================================================================== //
// This file is part of DO++, a basic set of libraries in C++ for computer
// vision.
//
// Copyright (C) 2013 David Ok <david.ok8@gmail.com>
//
// This Source Code Form is subject to the terms of the Mozilla Public
// License v. 2.0. If a copy of the MPL was not distributed with this file,
// you can obtain one at http://mozilla.org/MPL/2.0/.
// ========================================================================== //

#include <gtest/gtest.h>

#include <DO/Defines.hpp>
#include <DO/ImageProcessing/Deriche.hpp>

using namespace std;
using namespace DO;

TEST(TestDericheFilter, test_inplace_deriche_blur)
{
}

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

Remove inclusion of unversioned header.


/**
 ** Test code for libport/shared-ptr.hh features.
 */

#include <libport/ref-counted.hh>
#include <libport/shared-ptr.hh>

#define INSTANCES(N) assert(Counted::instances == N)

using libport::shared_ptr;

struct Counted : libport::RefCounted
{
  Counted () : libport::RefCounted() { ++instances; }
  virtual ~Counted () { assert (0 < instances); --instances; }
  static unsigned instances;
};

struct SubCounted : Counted
{
};

unsigned Counted::instances;

typedef shared_ptr<Counted> rCounted;
typedef shared_ptr<SubCounted> rSubCounted;

int
main ()
{
  {
    SubCounted* subcounted = new SubCounted;
    rSubCounted r1 (subcounted);
    {
      INSTANCES(1);
      rCounted r2;
      INSTANCES(1);
      r2 = r1;
      INSTANCES(1);
      rSubCounted r3 = r2.cast<SubCounted>();
      INSTANCES(1);
      rCounted r4 = new Counted;
      INSTANCES(2);
      r4 = r3;
      INSTANCES(1);
    }
    INSTANCES(1);
  }
  INSTANCES(0);
}

/**
 ** Test code for libport/shared-ptr.hh features.
 */

#include <libport/ref-counted.hh>
#include <libport/shared-ptr.hh>

#define INSTANCES(N) assert(Counted::instances == N)

using libport::shared_ptr;

struct Counted : libport::RefCounted
{
  Counted () : libport::RefCounted() { ++instances; }
  virtual ~Counted () { assert (0 < instances); --instances; }
  static unsigned instances;
};

struct SubCounted : Counted
{
};

unsigned Counted::instances;

typedef shared_ptr<Counted> rCounted;
typedef shared_ptr<SubCounted> rSubCounted;

int
main ()
{
  {
    SubCounted* subcounted = new SubCounted;
    rSubCounted r1 (subcounted);
    {
      INSTANCES(1);
      rCounted r2;
      INSTANCES(1);
      r2 = r1;
      INSTANCES(1);
      rSubCounted r3 = r2.cast<SubCounted>();
      INSTANCES(1);
      rCounted r4 = new Counted;
      INSTANCES(2);
      r4 = r3;
      INSTANCES(1);
    }
    INSTANCES(1);
  }
  INSTANCES(0);

  {
    rSubCounted p = new SubCounted();
    p = p;
    INSTANCES(1);
  }
  INSTANCES(0);
}

Test shared pointers assignment to self.


#include <iostream>
#include <cstdlib>
#include "NTClient.h"
using namespace std;

void initBot() {
	NTClient nclient = NTClient(20, 0.89);
	nclient.login("sascf3", "123asd123"); // Throw-away account
	nclient.connect();
}
int main(int argc, char** argv) {
	srand(static_cast<unsigned int>(time(0)));
	initBot();
	return 0;
}

#include <iostream>
#include <cstdlib>
#include <fstream>
#include "NTClient.h"
#include "colors.h"
#include "json.hpp"
using namespace std;

void initBot(string username, string password, int wpm, double acc) {
	NTClient nclient = NTClient(wpm, acc);
	nclient.login(username, password);
	nclient.connect();
}
void initlog(string msg) {
	cout << CLR_GRN << STYLE_BOLD << "[INIT] " << CLR_RESET << CLR_WHT << msg << CLR_RESET;
}
void errlog(string msg) {
	cout << CLR_RED << STYLE_BOLD << "[ERR!] " << CLR_RESET << CLR_WHT << msg << CLR_RESET;
}
int main(int argc, char** argv) {
	srand(static_cast<unsigned int>(time(0)));
	ifstream configf;
	configf.exceptions(std::ios::failbit | std::ios::badbit);
	try {
		configf.open("config.json");
	} catch(const exception& e) {
		errlog("Failed to open the JSON config. For help, read the UltraType++ repository README.\n");
		return 1;
	}
	return 0;
}

Add basic config file support


#include <iostream>

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

  std::cout << "Hello Lamure Virtual Texture!\n";
  return 0;
}

#include <iostream>

// scism shit
#include <scm/core.h>
#include <scm/log.h>
#include <scm/core/pointer_types.h>
#include <scm/core/io/tools.h>
#include <scm/core/time/accum_timer.h>
#include <scm/core/time/high_res_timer.h>

#include <scm/gl_core.h>

#include <scm/gl_util/data/imaging/texture_loader.h>
#include <scm/gl_util/manipulators/trackball_manipulator.h>
#include <scm/gl_util/primitives/box.h>
#include <scm/gl_util/primitives/quad.h>
#include <scm/gl_util/primitives/wavefront_obj.h>

// Window library
#include <GL/freeglut.h>

static int winx = 1600;
static int winy = 1024;

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

    // init GLUT and create Window
    glutInit(&argc, argv);
    glutInitContextVersion (4,2);
    glutInitContextProfile(GLUT_CORE_PROFILE);

    glutInitDisplayMode(GLUT_DEPTH | GLUT_DOUBLE | GLUT_RGBA);

    // set properties from window
    glutCreateWindow("First test with GLUT and SCHISM");
    glutInitWindowPosition(0, 0);
    glutInitWindowSize(winx, winy);

    // register callbacks
    glutDisplayFunc(display);

    // enter GLUT event processing cycle
    glutMainLoop();
    return 0;
}

Implement first basic black window setup without any content


#define BOOST_TEST_DYN_LINK
#define BOOST_TEST_MODULE JPetEventTest
#include <boost/test/unit_test.hpp>

#include "../JPetAnalysisTools/JPetAnalysisTools.h"

BOOST_AUTO_TEST_SUITE(FirstSuite)

BOOST_AUTO_TEST_CASE(constructor_getHitsOrderedByTime)
{
  std::vector<JPetHit> hits(4);
  hits[0].setTime(2);
  hits[1].setTime(1);
  hits[2].setTime(4);
  hits[3].setTime(3);
  auto results = JPetAnalysisTools::getHitsOrderedByTime(hits);
  BOOST_REQUIRE_EQUAL(results[0].getTime(), 1);
  BOOST_REQUIRE_EQUAL(results[1].getTime(), 2);
  BOOST_REQUIRE_EQUAL(results[2].getTime(), 3);
  BOOST_REQUIRE_EQUAL(results[3].getTime(), 4);
}

BOOST_AUTO_TEST_SUITE_END()

#define BOOST_TEST_DYN_LINK
#define BOOST_TEST_MODULE JPetEventTest
#include <boost/test/unit_test.hpp>

#include "../JPetAnalysisTools/JPetAnalysisTools.h"

BOOST_AUTO_TEST_SUITE(FirstSuite)

BOOST_AUTO_TEST_CASE(constructor_getHitsOrderedByTime)
{
  std::vector<JPetHit> hits(4);
  hits[0].setTime(2);
  hits[1].setTime(1);
  hits[2].setTime(4);
  hits[3].setTime(3);
  auto results = JPetAnalysisTools::getHitsOrderedByTime(hits);
  double epsilon = 0.0001;
  BOOST_REQUIRE_CLOSE(results[0].getTime(), 1, epsilon );
  BOOST_REQUIRE_CLOSE(results[1].getTime(), 2, epsilon );
  BOOST_REQUIRE_CLOSE(results[2].getTime(), 3, epsilon );
  BOOST_REQUIRE_CLOSE(results[3].getTime(), 4, epsilon );
}

BOOST_AUTO_TEST_SUITE_END()

Change tests in JPetAnalysisTools to use double instead of int


#include "AppInfo.h"
#include "Builder.h"
#include "LibInfoDySySim.h"

#include <fstream>
#include <iomanip>
#include <iostream>
#include <string>

namespace dss = dysysim;

int main(int argc, char *argv[])
{
   std::cout << "-- " APPNAME_VERSION " " << std::string(50, '-') << std::endl
             << "-- uses " + dss::libName + " v" << dss::libVersion << std::endl
             << std::endl;

   dss::Builder builder;

   std::ifstream programFile;

   if (argc > 2) {
      return 1;
   }

   if (argc == 1) {
      programFile.open("../appDySySim/data/RCnetwork.dss");
   } else {
      programFile.open(argv[1]);
   }

   if (programFile.is_open()) {
       std::cout << "\n-- Syntax check\n";
     builder(programFile);
   }
   std::cout << "\n";

   programFile.close();

   return 0;
}

#include "AppInfo.h"
#include "Builder.h"
#include "LibInfoDySySim.h"

#include <fstream>
#include <iomanip>
#include <iostream>
#include <string>

namespace dss = dysysim;

int main(int argc, char *argv[])
{
   std::cout << "-- " APPNAME_VERSION " " << std::string(50, '-') << std::endl
             << "-- uses " + dss::libName + " v" << dss::libVersion << std::endl
             << std::endl;

   dss::Builder builder;

   std::ifstream programFile;

   if (argc > 2) {
      return 1;
   }

   if (argc == 1) {
      programFile.open("../appDySySim/scripts/RCnetwork.dss");
   } else {
      programFile.open(argv[1]);
   }

   if (programFile.is_open()) {
      std::cout << "\n-- Syntax check\n";
      builder(programFile);
   }
   std::cout << "\n";

   programFile.close();

   return 0;
}

Rename dir data to scripts


//===--- ThreadSanitizer.cpp - Thread Sanitizer support -------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2021 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
//
// Thread Sanitizer support for the Swift Task runtime
//
//===----------------------------------------------------------------------===//

#include "TaskPrivate.h"

#include <dlfcn.h>

using TSanFunc = void(void *);

void swift::_swift_tsan_acquire(void *addr) {
  static auto ptr = (TSanFunc *)dlsym(RTLD_DEFAULT, "__tsan_acquire");
  if (ptr) {
    ptr(addr);
  }
}

void swift::_swift_tsan_release(void *addr) {
  static auto ptr = (TSanFunc *)dlsym(RTLD_DEFAULT, "__tsan_release");
  if (ptr) {
    ptr(addr);
  }
}

//===--- ThreadSanitizer.cpp - Thread Sanitizer support -------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2021 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
//
// Thread Sanitizer support for the Swift Task runtime
//
//===----------------------------------------------------------------------===//

#include "TaskPrivate.h"

#if defined(_WIN32)
#define NOMINMAX
#include <windows.h>
#else
#include <dlfcn.h>
#endif

using TSanFunc = void(void *);

namespace {
static TSanFunc *loadSymbol(const char *name) {
#if defined(_WIN32)
  return (TSanFunc *)GetProcAddress(GetModuleHandle(NULL), name);
#else
  return (TSanFunc *)dlsym(RTLD_DEFAULT, name);
#endif
}
}

void swift::_swift_tsan_acquire(void *addr) {
  static auto ptr = loadSymbol("__tsan_acquire");
  if (ptr) {
    ptr(addr);
  }
}

void swift::_swift_tsan_release(void *addr) {
  static auto ptr = loadSymbol("__tsan_release");
  if (ptr) {
    ptr(addr);
  }
}

Fix TSan symbol lookup on Windows


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

// <experimental/utility>

#include <experimental/utility>

int main()
{
    std::experimental::erased_type e();
}

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

// <experimental/utility>

#include <experimental/utility>

int main()
{
    std::experimental::erased_type e;
}

Fix vexing parse in test.


/* **********************************************************
 * Copyright (c) 2011 Google, Inc.  All rights reserved.
 * **********************************************************/

/* Dr. Memory: the memory debugger
 *
 * 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;
 * version 2.1 of the License, and no 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
 * Library 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 Street, Fifth Floor, Boston, MA 02110-1301 USA.
 */

#include <windows.h>

#include "gtest/gtest.h"

TEST(NtUserTests, SystemParametersInfo) {
    NONCLIENTMETRICS metrics;
    ZeroMemory(&metrics, sizeof(NONCLIENTMETRICS));
    metrics.cbSize = sizeof(NONCLIENTMETRICS);
    EXPECT_NE(0, SystemParametersInfo(SPI_GETNONCLIENTMETRICS,
                                      sizeof(NONCLIENTMETRICS), &metrics, 0));
}

/* **********************************************************
 * Copyright (c) 2011 Google, Inc.  All rights reserved.
 * **********************************************************/

/* Dr. Memory: the memory debugger
 *
 * 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;
 * version 2.1 of the License, and no 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
 * Library 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 Street, Fifth Floor, Boston, MA 02110-1301 USA.
 */

#include <windows.h>

#include "gtest/gtest.h"

TEST(NtUserTests, SystemParametersInfo) {
    NONCLIENTMETRICS metrics;
    ZeroMemory(&metrics, sizeof(NONCLIENTMETRICS));
    metrics.cbSize = sizeof(NONCLIENTMETRICS);
    SystemParametersInfo(SPI_GETNONCLIENTMETRICS, sizeof(NONCLIENTMETRICS),
                         &metrics, 0);
}

Remove the return value check in the SystemParametersInfo test since it is failing on Windows XP for some reason


// Copyright (C) 2012-2015 Leap Motion, Inc. All rights reserved.
#include "stdafx.h"
#include <autowiring/config_descriptor.h>
#include <autowiring/config.h>
#include <autowiring/ConfigRegistry.h>
#include <autowiring/observable.h>

namespace aw = autowiring;

class AutoConfig_SliderTest :
  public testing::Test
{};

namespace {
  struct slider {
    template<typename T>
    struct valid {
      static const bool value = std::is_integral<T>::value;
    };
  };

  class ClassWithASlider {
  public:
    std::string api_path;
    int timeout;

    static aw::config_descriptor GetConfigDescriptor(void) {
      return{
        { "api_path", &ClassWithASlider::api_path },
        { "timeout", &ClassWithASlider::timeout, slider{} }
      };
    }
  };
}

// Copyright (C) 2012-2015 Leap Motion, Inc. All rights reserved.
#include "stdafx.h"
#include <autowiring/config_descriptor.h>
#include <autowiring/config.h>
#include <autowiring/ConfigRegistry.h>
#include <autowiring/observable.h>

namespace aw = autowiring;

class AutoConfig_SliderTest :
  public testing::Test
{};

namespace {
  struct slider {
    template<typename T>
    struct valid {
      static const bool value = std::is_integral<T>::value;
    };
  };

  class ClassWithASlider {
  public:
    std::string api_path;
    int timeout;

    static aw::config_descriptor GetConfigDescriptor(void) {
      return{
        { "api_path", &ClassWithASlider::api_path, slider{} },
        { "timeout", &ClassWithASlider::timeout, slider{} }
      };
    }
  };

  class SliderManager {
    SliderManager(void) {
      AutoCurrentContext ctxt;
      ctxt->Config.When([](const aw::config_field& field, const slider&) {
      });
    }
  };
}

TEST_F(AutoConfig_SliderTest, CanFindAllSliders) {

  // Get a full list of all sliders:
}

Extend slider use case test


//=======================================================================
// 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 <iostream>

#include "il/Main.hpp"
#include "AssemblyFileWriter.hpp"

using namespace eddic;

void Main::write(AssemblyFileWriter& writer){
    writer.stream() << ".text" << std::endl
                    << ".globl main" << std::endl
                    << "\t.type main, @function" << std::endl;
}

//=======================================================================
// 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 <iostream>

#include "il/Main.hpp"
#include "AssemblyFileWriter.hpp"

using namespace eddic;

void Main::write(AssemblyFileWriter& writer){
    writer.stream() << ".text" << std::endl
                    << ".globl _start" << std::endl

                    << "_start:" << std::endl
                    << "call main" << std::endl
                    << "movl $1, %eax" << std::endl
                    << "xorl %ebx, %ebx" << std::endl
                    << "int $0x80" << std::endl;
}

Improve main declaration to include runtime start


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

#include "PerfHelper.h"
#include "llvm/Config/config.h"
#include "gmock/gmock.h"
#include "gtest/gtest.h"

namespace exegesis {
namespace pfm {
namespace {

using ::testing::IsEmpty;
using ::testing::Not;

TEST(PerfHelperTest, FunctionalTest) {
#ifdef HAVE_LIBPFM
  ASSERT_FALSE(pfmInitialize());
  const PerfEvent SingleEvent("CYCLES:u");
  const auto &EmptyFn = []() {};
  std::string CallbackEventName;
  std::string CallbackEventNameFullyQualifed;
  int64_t CallbackEventCycles;
  Measure(llvm::makeArrayRef(SingleEvent),
          [&](const PerfEvent &Event, int64_t Value) {
            CallbackEventName = Event.name();
            CallbackEventNameFullyQualifed = Event.getPfmEventString();
            CallbackEventCycles = Value;
          },
          EmptyFn);
  EXPECT_EQ(CallbackEventName, "CYCLES:u");
  EXPECT_THAT(CallbackEventNameFullyQualifed, Not(IsEmpty()));
  pfmTerminate();
#else
  ASSERT_TRUE(PfmInitialize());
#endif
}

} // namespace
} // namespace pfm
} // namespace exegesis

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

#include "PerfHelper.h"
#include "llvm/Config/config.h"
#include "gmock/gmock.h"
#include "gtest/gtest.h"

namespace exegesis {
namespace pfm {
namespace {

using ::testing::IsEmpty;
using ::testing::Not;

TEST(PerfHelperTest, FunctionalTest) {
#ifdef HAVE_LIBPFM
  ASSERT_FALSE(pfmInitialize());
  const PerfEvent SingleEvent("CYCLES:u");
  const auto &EmptyFn = []() {};
  std::string CallbackEventName;
  std::string CallbackEventNameFullyQualifed;
  int64_t CallbackEventCycles;
  Measure(llvm::makeArrayRef(SingleEvent),
          [&](const PerfEvent &Event, int64_t Value) {
            CallbackEventName = Event.name();
            CallbackEventNameFullyQualifed = Event.getPfmEventString();
            CallbackEventCycles = Value;
          },
          EmptyFn);
  EXPECT_EQ(CallbackEventName, "CYCLES:u");
  EXPECT_THAT(CallbackEventNameFullyQualifed, Not(IsEmpty()));
  pfmTerminate();
#else
  ASSERT_TRUE(pfmInitialize());
#endif
}

} // namespace
} // namespace pfm
} // namespace exegesis

Fix build when libpfm is not available.


/* Copyright 2015 The TensorFlow Authors. All Rights Reserved.

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 "tensorflow/core/kernels/cwise_ops_common.h"

namespace tensorflow {
REGISTER2(BinaryOp, CPU, "Zeta", functor::zeta, float, double);
REGISTER2(BinaryOp, CPU, "Polygamma", functor::polygamma, float, double);
}  // namespace tensorflow

/* Copyright 2015 The TensorFlow Authors. All Rights Reserved.

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 "tensorflow/core/kernels/cwise_ops_common.h"

namespace tensorflow {
REGISTER2(BinaryOp, CPU, "Zeta", functor::zeta, float, double);
REGISTER2(BinaryOp, CPU, "Polygamma", functor::polygamma, float, double);

#if GOOGLE_CUDA
REGISTER2(BinaryOp, GPU, "Zeta", functor::zeta, float, double);
REGISTER2(BinaryOp, GPU, "Polygamma", functor::polygamma, float, double);
#endif
}  // namespace tensorflow

Enable GPU support for Zeta and Polygamma ops.


// Check existence of a key
// C++11

#include <map>
#include <string>

int main()
{
  std::map<string, int> m = {{"a", 1}, {"b", 2}, {"c", 3}};

  if (m.count("b"))
  {
     // We know "b" is in m
  }
}

// Check if a particular key is in an associative container.
//
// On [9], we create a [`std::map`](cpp/container/map) as an example
// associative container and initialise it with key-value pairs.
//
// On [11], we count the number of occurrences of the key "b" in m
// by using the memeber function [`count`](cpp/container/map/count).
// If "b" is in m, count will return 1; otherwise it will return 0.
//
// Note: in C++14, an instance of the searched key will not be created
// if the container's comparator is
// [transparent](http://stackoverflow.com/q/20317413/150634) and
// supports the appropriate comparison without conversions.

// Check existence of a key
// C++11

#include <map>
#include <string>

int main()
{
	std::map<std::string, int> m = {{"a", 1}, {"b", 2}, {"c", 3}};

	if (m.count("b"))
	{
		// We know "b" is in m
	}
}

// Check if a particular key is in an associative container.
//
// On [9], we create a [`std::map`](cpp/container/map) as an example
// associative container and initialize it with key-value pairs.
//
// On [11], we count the number of occurrences of the key `"b"` in `m`
// by using the memeber function [`count`](cpp/container/map/count).
// If `"b"` is in `m`, `count` will return 1; otherwise it will return
// 0.
//
// Note: in C++14, an instance of the searched key will not be created
// if the container's comparator is
// [transparent](http://stackoverflow.com/q/20317413/150634) and
// supports the appropriate comparison without conversions.

Make corrections to key existence sample


#include <QApplication>
#include <QQmlApplicationEngine>
#include <QDir>
#include <QFile>
#include <QFileInfo>

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

	QQmlApplicationEngine engine;

	if (argc < 2) {
		printf("Usage: OwaViewer [directory]\n");
		return 1;
	}

	QDir dirPath(argv[1]);
	QString qmlPath;

	// It's a directory
	if (QFileInfo(dirPath.path()).isDir()) {

		// Trying to read QML file in the directory
		qmlPath = dirPath.filePath("app.qml");
		if (!QFile(qmlPath).exists()) {

			qmlPath = dirPath.filePath("App.qml");
			if (!QFile(qmlPath).exists()) {
				printf("OwaNEXT Application doesn't exist.\n");
				return 1;
			}
		}
	}

	engine.load(QUrl(qmlPath));

	return app.exec();
}

#include <QApplication>
#include <QQmlApplicationEngine>
#include <QDir>
#include <QFile>
#include <QFileInfo>

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

	QQmlApplicationEngine engine;

	if (argc < 2) {
		printf("Usage: OwaViewer [directory]\n");
		printf("   or: OwaViewer [File]\n");
		return 1;
	}

	QDir dirPath(argv[1]);
	QString qmlPath;

	// It's a directory
	if (QFileInfo(dirPath.path()).isDir()) {

		// Trying to read QML file in the directory
		qmlPath = dirPath.filePath("app.qml");
		if (!QFile(qmlPath).exists()) {

			qmlPath = dirPath.filePath("App.qml");
			if (!QFile(qmlPath).exists()) {
				printf("Cannot find application in the directory.\n");
				return 1;
			}
		}
	} else {

		// Whether does the QML file exists or not?
		qmlPath = dirPath.path();
		if (!QFile(qmlPath).exists()) {
			printf("OwaNEXT Application doesn't exist.\n");
			return 1;
		}
	}

	// Run it
	engine.load(QUrl(qmlPath));

	return app.exec();
}

Support to specify single QML file by argument


#include "cameras/itf/pinhole_camera.h"

#include "core/itf/film.h"
#include "core/itf/ray.h"
#include "core/itf/sampling.h"

#include <iostream>

using namespace lb;

/// Constructs a pinhole camera, where the image plane's origin is pointed to
/// the by the look at vector relative from the camera's location. Together with
/// the look at vector, the up vector defines the camera's roll, pitch, and
/// tilt. Note: up vector should be a unit vector preferably.
PinholeCamera::PinholeCamera(std::unique_ptr<Film> film,
        const Point3d& location, const Vector3d& lookAt, const Vector3d& up):
    Camera(std::move(film), location),
    lookAt_(lookAt),
    left_(-cross(lookAt, up)),
    top_(cross(lookAt.normalize(), left_)),
    dx_(-2 * left_ / (film_->xResolution() - 1)),
    dy_(-2 * top_ / (film_->yResolution() - 1))
{
}

void PinholeCamera::calculateRay(const Sample& s, Ray& r) const
{
    r.o = location_;
    r.d = ((r.o + lookAt_ + left_ + s.imageX * dx_ + top_ + s.imageY * dy_) - r.o).normalize();
    // std::cout << r.o << "\n";
}

#include "cameras/itf/pinhole_camera.h"

#include "core/itf/film.h"
#include "core/itf/ray.h"
#include "core/itf/sampling.h"

using namespace lb;

/// Constructs a pinhole camera, where the image plane's origin is pointed to
/// the by the look at vector relative from the camera's location. Together with
/// the look at vector, the up vector defines the camera's roll, pitch, and
/// tilt. Note: up vector should be a unit vector preferably.
PinholeCamera::PinholeCamera(std::unique_ptr<Film> film,
        const Point3d& location, const Vector3d& lookAt, const Vector3d& up):
    Camera(std::move(film), location),
    lookAt_(lookAt),
    left_(-cross(lookAt, up)),
    top_(cross(lookAt.normalize(), left_)),
    dx_(-2 * left_ / (film_->xResolution() - 1)),
    dy_(-2 * top_ / (film_->yResolution() - 1))
{
}

void PinholeCamera::calculateRay(const Sample& s, Ray& r) const
{
    r.o = location_;
    r.d = ((r.o + lookAt_ + left_ + s.imageX * dx_ + top_ + s.imageY * dy_) - r.o).normalize();
}

Remove comment and redundant include


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

// Various tests for -fno-exceptions

typedef __typeof(sizeof(int)) size_t;

namespace test0 {
  // rdar://problem/7878149
  class Foo {
  public:
    void* operator new(size_t x);
  private:
    void operator delete(void *x);
  };

  void test() {
    // Under -fexceptions, this does access control for the associated
    // 'operator delete'.
    (void) new Foo();
  }
}

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

// Various tests for -fno-exceptions

typedef __SIZE_TYPE__ size_t;

namespace test0 {
  // rdar://problem/7878149
  class Foo {
  public:
    void* operator new(size_t x);
  private:
    void operator delete(void *x);
  };

  void test() {
    // Under -fexceptions, this does access control for the associated
    // 'operator delete'.
    (void) new Foo();
  }
}

Use __SIZE_TYPE__ as suggested by dgregor.


/*
Copyright (c), Helios
All rights reserved.

Distributed under a permissive license. See COPYING.txt for details.
*/

#include "ImageViewerApplication.h"

int main(int argc, char **argv){
	try{
		initialize_supported_extensions();
		ImageViewerApplication app(argc, argv, "BorderlessViewer" + get_per_user_unique_id());
		return app.exec();
	}catch (ApplicationAlreadyRunningException &){
		return 0;
	}catch (NoWindowsException &){
		return 0;
	}
}

/*
Copyright (c), Helios
All rights reserved.

Distributed under a permissive license. See COPYING.txt for details.
*/

#include "ImageViewerApplication.h"
#include <QImageReader>

int main(int argc, char **argv){
	try{
		//Set the limit to 1 GiB.
		QImageReader::setAllocationLimit(1024);
		initialize_supported_extensions();
		ImageViewerApplication app(argc, argv, "BorderlessViewer" + get_per_user_unique_id());
		return app.exec();
	}catch (ApplicationAlreadyRunningException &){
		return 0;
	}catch (NoWindowsException &){
		return 0;
	}
}

Increase the QImageReader allocation limit.


/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
// SOComWindowPeer.cpp : Implementation of CHelpApp and DLL registration.

#include "stdafx2.h"
#include "so_activex.h"
#include "SOComWindowPeer.h"

/////////////////////////////////////////////////////////////////////////////
//

STDMETHODIMP SOComWindowPeer::InterfaceSupportsErrorInfo(REFIID riid)
{
    static const IID* arr[] =
    {
        &IID_ISOComWindowPeer,
    };

    for (int i=0;i<SAL_N_ELEMENTS(arr);i++)
    {
#if defined(_MSC_VER) && (_MSC_VER >= 1300)
        if (InlineIsEqualGUID(*arr[i],riid))
#else
        if (::ATL::InlineIsEqualGUID(*arr[i],riid))
#endif
            return S_OK;
    }
    return S_FALSE;
}

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */

/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
// SOComWindowPeer.cpp : Implementation of CHelpApp and DLL registration.

#include "stdafx2.h"
#include "so_activex.h"
#include "SOComWindowPeer.h"

/////////////////////////////////////////////////////////////////////////////
//

STDMETHODIMP SOComWindowPeer::InterfaceSupportsErrorInfo(REFIID riid)
{
    static const IID* arr[] =
    {
        &IID_ISOComWindowPeer,
    };

    for (int i=0;i<sizeof(arr)/sizeof(arr[0]);i++)
    {
#if defined(_MSC_VER) && (_MSC_VER >= 1300)
        if (InlineIsEqualGUID(*arr[i],riid))
#else
        if (::ATL::InlineIsEqualGUID(*arr[i],riid))
#endif
            return S_OK;
    }
    return S_FALSE;
}

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */

Revert SAL_N_ELEMENTS change for one file


// 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 "chrome/browser/extensions/extension_input_method_api.h"

#include "base/values.h"
#include "chrome/browser/chromeos/input_method/input_method_manager.h"
#include "chrome/browser/chromeos/extensions/input_method_event_router.h"
#include "chrome/browser/extensions/extension_service.h"
#include "chrome/browser/profiles/profile.h"

GetInputMethodFunction::GetInputMethodFunction() {
}

GetInputMethodFunction::~GetInputMethodFunction() {
}

bool GetInputMethodFunction::RunImpl() {
#if !defined(OS_CHROMEOS)
  NOTREACHED();
#else
  chromeos::ExtensionInputMethodEventRouter* router =
      profile_->GetExtensionService()->input_method_event_router();
  chromeos::input_method::InputMethodManager* manager =
      chromeos::input_method::InputMethodManager::GetInstance();
  const std::string input_method =
      router->GetInputMethodForXkb(manager->current_input_method().id());
  result_.reset(Value::CreateStringValue(input_method));
  return true;
#endif
}

// 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 "chrome/browser/extensions/extension_input_method_api.h"

#include "base/values.h"
#include "chrome/browser/chromeos/input_method/input_method_manager.h"
#include "chrome/browser/chromeos/extensions/input_method_event_router.h"
#include "chrome/browser/extensions/extension_service.h"
#include "chrome/browser/profiles/profile.h"

GetInputMethodFunction::GetInputMethodFunction() {
}

GetInputMethodFunction::~GetInputMethodFunction() {
}

bool GetInputMethodFunction::RunImpl() {
#if !defined(OS_CHROMEOS)
  NOTREACHED();
  return false;
#else
  chromeos::ExtensionInputMethodEventRouter* router =
      profile_->GetExtensionService()->input_method_event_router();
  chromeos::input_method::InputMethodManager* manager =
      chromeos::input_method::InputMethodManager::GetInstance();
  const std::string input_method =
      router->GetInputMethodForXkb(manager->current_input_method().id());
  result_.reset(Value::CreateStringValue(input_method));
  return true;
#endif
}

Fix a build error when OS_CHROMEOS is not defined.


#include <cstdint>

#include <Magick++/Blob.h>
#include <Magick++/Image.h>

#define FUZZ_ENCODER_STRING_LITERAL(name) #name
#define FUZZ_ENCODER FUZZ_ENCODER_STRING_LITERAL(FUZZ_IMAGEMAGICK_ENCODER)

extern "C" int LLVMFuzzerTestOneInput(const uint8_t *Data, size_t Size) {
  const Magick::Blob blob(Data, Size);
  Magick::Image image;
  try {
    image.magick(FUZZ_ENCODER);
    image.fileName(FUZZ_ENCODER + ':');
    image.read(blob);
  } catch (Magick::Exception &e) {
    return 0;
  }

  Magick::Blob outBlob;
  try {
    image.write(&outBlob, FUZZ_ENCODER);
  } catch (Magick::Exception &e) {
  }
  return 0;
}

#include <cstdint>

#include <Magick++/Blob.h>
#include <Magick++/Image.h>

#define FUZZ_ENCODER_STRING_LITERAL(name) #name
#define FUZZ_ENCODER FUZZ_ENCODER_STRING_LITERAL(FUZZ_IMAGEMAGICK_ENCODER)

extern "C" int LLVMFuzzerTestOneInput(const uint8_t *Data, size_t Size) {
  const Magick::Blob blob(Data, Size);
  Magick::Image image;
  try {
    image.read(blob, FUZZ_ENCODER);
  } catch (Magick::Exception &e) {
    return 0;
  }

  Magick::Blob outBlob;
  try {
    image.write(&outBlob, FUZZ_ENCODER);
  } catch (Magick::Exception &e) {
  }
  return 0;
}

Use new overload when reading the image.


#include <iostream>
#include <string>
#include <maproute/ip.hpp>
#include <maproute/ip_convertor.hpp>
#include <maproute/stringhelp.hpp>
#include <maproute/tr_parser.hpp>
#include <maproute/ip_location_finder.hpp>

int main() {

    IPLocationFinder finder{};

    while (std::cin.good()) {
        std::string line;
        std::string ip_string;
        IPV4Convertor convertor{};
        TracerouteLineParser parser{};
        IPV4 ip {0, 0, 0, 0};

        std::getline(std::cin, line);
        bool success = parser.parse(&line, &ip);

        if (!success) {
            std::cerr << "Failed to parse: '"
                      << line
                      << "' did the request timeout?"
                      << std::endl;
        } else {
            convertor.ip_to_string(&ip, &ip_string);
            std::cout << ip_string << std::endl;
        }
    }

    finder.close();

    return 0;

}

#include <iostream>
#include <string>
#include <maproute/ip.hpp>
#include <maproute/ip_convertor.hpp>
#include <maproute/stringhelp.hpp>
#include <maproute/tr_parser.hpp>
#include <maproute/ip_location_finder.hpp>

int main() {

    while (std::cin.good()) {
        std::string line;
        std::string ip_string;
        IPV4Convertor convertor{};
        TracerouteLineParser parser{};
        IPV4 ip {0, 0, 0, 0};

        std::getline(std::cin, line);
        bool success = parser.parse(&line, &ip);

        if (!success) {
            std::cerr << "Failed to parse: '"
                      << line
                      << "' did the request timeout?"
                      << std::endl;
        } else {
            convertor.ip_to_string(&ip, &ip_string);
            std::cout << ip_string << std::endl;
        }
    }

    return 0;

}

Remove unused finder on traceroute parse command


#include "material.hpp"

Material::Material():
        name{},
        ka{0,0,0},
        kd{0,0,0},
        ks{0,0,0},
        m{0}
        {}

Material::Material(std::string const& name, Color const& ka, Color const& kd,
                Color const& ks, float m):
        name{name},
        ka{ka},
        kd{kd},
        ks{ks},
        m{m}
        {}

std::string const& Material::getName() const {
        return name;
}

Color const& Material::getColorKa() const {
        return ka;
}

Color const& Material::getColorKd() const {
        return kd;
}

Color const& Material::getColorKs() const {
        return ks;
}

float const Material::getM() const {
        return m;
}

std::ostream& operator<<(std::ostream& os, Material const& m) {
        os << "--------" << "\n" << "Material " << "\n" << "--------" << "\n"
                << "Name: " << m.getName() << "\n" << "Colors (RGB):" << "\n"
                << "        ka: " << m.getColorKa() << "        kd: "
                << m.getColorKd() << "        ks: " << m.getColorKs()
                << "m: " << m.getM();
        return os;
}

#include "material.hpp"

Material::Material():
        name{},
        ka{0,0,0},
        kd{0,0,0},
        ks{0,0,0},
        m{0}
        {}

Material::Material(std::string const& name, Color const& ka, Color const& kd,
                Color const& ks, float m):
        name{name},
        ka{ka},
        kd{kd},
        ks{ks},
        m{m}
        {}

std::string const& Material::getName() const {
        return name;
}

Color const& Material::getColorKa() const {
        return ka;
}

Color const& Material::getColorKd() const {
        return kd;
}

Color const& Material::getColorKs() const {
        return ks;
}

float const Material::getM() const {
        return m;
}

std::ostream& operator<<(std::ostream& os, Material const& m) {
        os << "--------" << "\n" << "Material " << "\n" << "--------" << "\n"
                << "Name: " << m.getName() << "\n" << "Light coefficients:" << "\n"
                << "        ka: " << m.getColorKa() << "        kd: "
                << m.getColorKd() << "        ks: " << m.getColorKs()
                << "m: " << m.getM();
        return os;
}

Change print to match actual content of ka, kd, ks.


#include "perf_precomp.hpp"

using namespace std;
using namespace cv;
using namespace perf;
using std::tr1::make_tuple;
using std::tr1::get;

#define MAT_TYPES_DFT  CV_32FC1, CV_64FC1
#define MAT_SIZES_DFT  sz1080p, sz2K
#define TEST_MATS_DFT  testing::Combine(testing::Values(MAT_SIZES_DFT), testing::Values(MAT_TYPES_DFT))

PERF_TEST_P(Size_MatType, dft, TEST_MATS_DFT)
{
    Size sz = get<0>(GetParam());
    int type = get<1>(GetParam());

    Mat src(sz, type);
    Mat dst(sz, type);

    declare.in(src, WARMUP_RNG).time(60);

    TEST_CYCLE() dft(src, dst);

    SANITY_CHECK(dst, 1e-5);
}

#include "perf_precomp.hpp"

using namespace std;
using namespace cv;
using namespace perf;
using std::tr1::make_tuple;
using std::tr1::get;

#define MAT_TYPES_DFT  CV_32FC1, CV_64FC1
#define MAT_SIZES_DFT  sz1080p, sz2K
#define TEST_MATS_DFT  testing::Combine(testing::Values(MAT_SIZES_DFT), testing::Values(MAT_TYPES_DFT))

PERF_TEST_P(Size_MatType, dft, TEST_MATS_DFT)
{
    Size sz = get<0>(GetParam());
    int type = get<1>(GetParam());

    Mat src(sz, type);
    Mat dst(sz, type);

    declare.in(src, WARMUP_RNG).time(60);

    TEST_CYCLE() dft(src, dst);

    SANITY_CHECK(dst, 1e-5, ERROR_RELATIVE);
}

Change sanity check for perfomance test of dft


#include "test/catch.hpp"

#include <string>
#include <vector>

#include "main/exception/FileOpenException.hpp"
#include "main/exception/InvalidArgumentException.hpp"
#include "main/MainApp.hpp"

TEST_CASE("MainApp class") {
    using std::string;
    using std::vector;
    using pyconv::exception::FileOpenException;
    using pyconv::exception::InvalidArgumentException;
    using pyconv::MainApp;

    SECTION("Exceptions Thrown") {
        vector<string> args;
        try {
            MainApp mainApp(args);
        } catch (InvalidArgumentException const & e) {
            CHECK(e.message() == "No arguments provided");
        }
        args.push_back("cpp");
        try {
            MainApp mainApp(args);
        } catch (InvalidArgumentException const & e) {
            CHECK(e.message() == "Only one argument provided");
        }
        args[0] = "java";
        args.push_back("nonexistingfolder/nonexistingfile.py");
        try {
            MainApp mainApp(args);
        } catch (InvalidArgumentException const & e) {
            CHECK(e.message() == "Invalid language type: java");
        }
    }

    SECTION("No Exceptions Thrown") {
        vector<string> args {"cpp", "./src/PyConv/test/testfiles/properFile.py"};
        MainApp mainApp(args);
        CHECK_NOTHROW(mainApp.run());
        args[0] = "python";
        mainApp = MainApp(args);
        CHECK_NOTHROW(mainApp.run());
    }
}

#include "test/catch.hpp"

#include <string>
#include <vector>

#include "main/exception/FileOpenException.hpp"
#include "main/exception/InvalidArgumentException.hpp"
#include "main/MainApp.hpp"

TEST_CASE("MainApp class") {
    using std::string;
    using std::vector;
    using pyconv::exception::FileOpenException;
    using pyconv::exception::InvalidArgumentException;
    using pyconv::MainApp;

    SECTION("Exceptions Thrown") {
        vector<string> args;
        try {
            MainApp mainApp(args);
        } catch (InvalidArgumentException const & e) {
            CHECK(e.message() == "No arguments provided");
        }
        args.push_back("cpp");
        try {
            MainApp mainApp(args);
        } catch (InvalidArgumentException const & e) {
            CHECK(e.message() == "Only one argument provided");
        }
        args[0] = "java";
        args.push_back("nonexistingfolder/nonexistingfile.py");
        try {
            MainApp mainApp(args);
        } catch (InvalidArgumentException const & e) {
            CHECK(e.message() == "Invalid language type: java");
        }
    }

    SECTION("No Exceptions Thrown") {
        vector<string> args {"cpp", "./src/PyConv/test/testfiles/properFile.py"};
        MainApp mainApp(args);
        CHECK_NOTHROW(mainApp.run());
        args[1] = "nonexistingfolder/nonexistingfile.py";
        mainApp = MainApp(args);
        CHECK_NOTHROW(mainApp.run());
        args[0] = "python";
        mainApp = MainApp(args);
        CHECK_NOTHROW(mainApp.run());
    }
}

Add test to cover unable to open file


/* -*- mode:linux -*- */
/**
 * \file timeout.cc
 *
 *
 *
 * \author Ethan Burns
 * \date 2008-12-16
 */

#include <iostream>

#include <signal.h>
#include <stdlib.h>
#include <unistd.h>

using namespace std;

void alarm_action(int sig)
{
	cout << "No Solution" << endl
	     << "cost: infinity" << endl
	     << "length: infinity" << endl
	     << "wall_time: infinity" << endl
	     << "CPU_time: infinity" << endl
	     << "generated: infinity" << endl
	     << "expanded: infinity" << endl;

	exit(EXIT_SUCCESS);
}

void timeout(unsigned int sec)
{
	struct sigaction sa;

	sa.sa_flags = 0;
	sa.sa_sigaction = NULL;
	sa.sa_restorer = NULL;
	sa.sa_handler = alarm_action;
	sigfillset(&sa.sa_mask);
	sigaction(SIGALRM, &sa, NULL);

	alarm(sec);
}

/* -*- mode:linux -*- */
/**
 * \file timeout.cc
 *
 *
 *
 * \author Ethan Burns
 * \date 2008-12-16
 */

#include <iostream>

#include <signal.h>
#include <stdlib.h>
#include <unistd.h>

using namespace std;

void alarm_action(int sig)
{
	cout << "No Solution" << endl
	     << "cost: infinity" << endl
	     << "length: infinity" << endl
	     << "wall_time: infinity" << endl
	     << "CPU_time: infinity" << endl
	     << "generated: infinity" << endl
	     << "expanded: infinity" << endl;

	exit(EXIT_SUCCESS);
}

void timeout(unsigned int sec)
{
	struct sigaction sa;

	memset(&sa, '\0', sizeof(sa));

	sa.sa_handler = alarm_action;
	sigfillset(&sa.sa_mask);
	sigaction(SIGALRM, &sa, NULL);

	alarm(sec);
}

Fix sigaction to be more portable.


/*
 * 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 "SkNullCanvas.h"

#include "SkCanvas.h"
#include "SKNWayCanvas.h"

SkCanvas* SkCreateNullCanvas() {
    // An N-Way canvas forwards calls to N canvas's. When N == 0 it's
    // effectively a null canvas.
    return SkNEW(SkNWayCanvas);
}

/*
 * 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 "SkNullCanvas.h"

#include "SkCanvas.h"
#include "SKNWayCanvas.h"

SkCanvas* SkCreateNullCanvas() {
    // An N-Way canvas forwards calls to N canvas's. When N == 0 it's
    // effectively a null canvas.
    return SkNEW(SkNWayCanvas(0,0));
}

Fix SkNWayCanvas cons call when creating null canvas.


#include "performance_model.h"
#include "log.h"

using std::endl;

SimplePerformanceModel::SimplePerformanceModel()
    : m_instruction_count(0)
    , m_cycle_count(0)
{
}

SimplePerformanceModel::~SimplePerformanceModel()
{
}

void SimplePerformanceModel::outputSummary(std::ostream &os)
{
   os << "  Instructions: " << getInstructionCount() << endl
      << "  Cycles: " << getCycleCount() << endl;
}

void SimplePerformanceModel::handleInstruction(Instruction *instruction)
{
   m_instruction_count++;
   m_cycle_count += instruction->getCost();
}

#include "performance_model.h"
#include "log.h"

using std::endl;

SimplePerformanceModel::SimplePerformanceModel()
    : m_instruction_count(0)
    , m_cycle_count(0)
{
}

SimplePerformanceModel::~SimplePerformanceModel()
{
}

void SimplePerformanceModel::outputSummary(std::ostream &os)
{
   os << "  Instructions: " << getInstructionCount() << endl
      << "  Cycles: " << getCycleCount() << endl;
}

void SimplePerformanceModel::handleInstruction(Instruction *instruction)
{
   // compute cost
   UInt64 cost = 0;

   const OperandList &ops = instruction->getOperands();

   for (unsigned int i = 0; i < ops.size(); i++)
   {
      const Operand &o = ops[i];

      if (o.m_type == Operand::MEMORY &&
          o.m_direction == Operand::READ)
      {
         DynamicInstructionInfo &i = getDynamicInstructionInfo();
         LOG_ASSERT_ERROR(i.type == DynamicInstructionInfo::INFO_MEMORY,
                          "Expected memory info.");

         cost += i.memory_info.latency;
         // ignore address

         popDynamicInstructionInfo();
      }
   }

   cost += instruction->getCost();

   // update counters
   m_instruction_count++;
   m_cycle_count += cost;
}

Add simple memory model to consume latency of memory operations. Still needs them to be pushed.


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


#include "scene.h"
#include "geometry/differential_geometry.h"
#include "lights/occlusion_tester.h"

void OcclusionTester::set_points(const Point &a, const Point &b){
	float dist = a.distance(b);
	ray = Ray{a, (b - a) / dist, 1e-6f, dist * (1.f - 1e-6f)};
}
void OcclusionTester::set_ray(const Point &p, const Vector &d){
	ray = Ray{p, d.normalized(), 1e-6f};
}
bool OcclusionTester::occluded(const Scene &scene){
	DifferentialGeometry dg;
	return scene.get_root().intersect(ray, dg);
}

#include "scene.h"
#include "geometry/differential_geometry.h"
#include "lights/occlusion_tester.h"

void OcclusionTester::set_points(const Point &a, const Point &b){
	ray = Ray{a, b - a, 1e-4f, 1};
}
void OcclusionTester::set_ray(const Point &p, const Vector &d){
	ray = Ray{p, d.normalized(), 1e-4f};
}
bool OcclusionTester::occluded(const Scene &scene){
	DifferentialGeometry dg;
	return scene.get_root().intersect(ray, dg);
}

Fix occlusion tester segment ray creation to behave like before


/*
 * Copyright 2014 Cloudius Systems
 */

#include "database.hh"
#include "core/app-template.hh"
#include "core/smp.hh"
#include "thrift/server.hh"

namespace bpo = boost::program_options;

int main(int ac, char** av) {
    app_template app;
    app.add_options()
        ("thrift-port", bpo::value<uint16_t>()->default_value(9160), "Thrift port")
        ("datadir", bpo::value<std::string>()->default_value("/var/lib/cassandra/data"), "data directory");

    auto server = std::make_unique<distributed<thrift_server>>();;

    return app.run(ac, av, [&] {
        auto&& config = app.configuration();
        uint16_t port = config["thrift-port"].as<uint16_t>();
        sstring datadir = config["datadir"].as<std::string>();

        database db(datadir);

        auto server = new distributed<thrift_server>;
        server->start(std::ref(db)).then([server = std::move(server), port] () mutable {
            server->invoke_on_all(&thrift_server::listen, ipv4_addr{port});
        }).then([port] {
            std::cout << "Thrift server listening on port " << port << " ...\n";
        });
    });
}

/*
 * Copyright 2014 Cloudius Systems
 */

#include "database.hh"
#include "core/app-template.hh"
#include "core/smp.hh"
#include "thrift/server.hh"

namespace bpo = boost::program_options;

int main(int ac, char** av) {
    app_template app;
    app.add_options()
        ("thrift-port", bpo::value<uint16_t>()->default_value(9160), "Thrift port")
        ("datadir", bpo::value<std::string>()->default_value("/var/lib/cassandra/data"), "data directory");

    auto server = std::make_unique<distributed<thrift_server>>();;

    std::unique_ptr<database> db;
    return app.run(ac, av, [&] {
        auto&& config = app.configuration();
        uint16_t port = config["thrift-port"].as<uint16_t>();
        sstring datadir = config["datadir"].as<std::string>();

        db.reset(std::make_unique<database>(datadir).release());

        auto server = new distributed<thrift_server>;
        server->start(std::ref(*db)).then([server = std::move(server), port] () mutable {
            server->invoke_on_all(&thrift_server::listen, ipv4_addr{port});
        }).then([port] {
            std::cout << "Thrift server listening on port " << port << " ...\n";
        });
    });
}

Fix use-after-free on database object


// RUN: rm -rf %t
// RUN: mkdir -p %t/prebuilt_modules
//
// RUN: %clang_cc1 -triple %itanium_abi_triple                          \
// RUN:     -fmodules-ts -fprebuilt-module-path=%t/prebuilt-modules     \
// RUN:     -emit-module-interface -pthread -DBUILD_MODULE              \
// RUN:     %s -o %t/prebuilt_modules/mismatching_module.pcm
//
// RUN: not %clang_cc1 -triple %itanium_abi_triple -fmodules-ts         \
// RUN:     -fprebuilt-module-path=%t/prebuilt_modules -DCHECK_MISMATCH \
// RUN:     %s 2>&1 | FileCheck %s

#ifdef BUILD_MODULE
export module mismatching_module;
#endif

#ifdef CHECK_MISMATCH
import mismatching_module;
// CHECK: error: POSIX thread support was enabled in PCH file but is currently disabled
// CHECK-NEXT: module file {{.*}}/mismatching_module.pcm cannot be loaded due to a configuration mismatch with the current compilation
#endif

// RUN: rm -rf %t
// RUN: mkdir -p %t/prebuilt_modules
//
// RUN: %clang_cc1 -triple %itanium_abi_triple                          \
// RUN:     -fmodules-ts -fprebuilt-module-path=%t/prebuilt-modules     \
// RUN:     -emit-module-interface -pthread -DBUILD_MODULE              \
// RUN:     %s -o %t/prebuilt_modules/mismatching_module.pcm
//
// RUN: not %clang_cc1 -triple %itanium_abi_triple -fmodules-ts         \
// RUN:     -fprebuilt-module-path=%t/prebuilt_modules -DCHECK_MISMATCH \
// RUN:     %s 2>&1 | FileCheck %s

#ifdef BUILD_MODULE
export module mismatching_module;
#endif

#ifdef CHECK_MISMATCH
import mismatching_module;
// CHECK: error: POSIX thread support was enabled in PCH file but is currently disabled
// CHECK-NEXT: module file {{.*[/|\\\\]}}mismatching_module.pcm cannot be loaded due to a configuration mismatch with the current compilation
#endif

Fix test from r346439 to also work on Windows due to path separator differences.


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

// Check that -isysroot warns on nonexistent paths.
// RUN: %clang -### -c -target i386-apple-darwin10 -isysroot %T/warning-options %s 2>&1 | FileCheck --check-prefix=CHECK-ISYSROOT %s
// CHECK-ISYSROOT: warning: no such sysroot directory: '{{([A-Za-z]:.*)?}}/warning-options'

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

// Check that -isysroot warns on nonexistent paths.
// RUN: %clang -### -c -target i386-apple-darwin10 -isysroot %T/warning-options %s 2>&1 | FileCheck --check-prefix=CHECK-ISYSROOT %s
// CHECK-ISYSROOT: warning: no such sysroot directory: '{{.*}}/warning-options'

Fix a regex error breaking tests.


/*
* Darwin SecRandomCopyBytes EntropySource
* (C) 2015 Daniel Seither (Kullo GmbH)
*
* Botan is released under the Simplified BSD License (see license.txt)
*/

#include <botan/internal/darwin_secrandom.h>
#include <Security/Security.h>

namespace Botan {

/**
* Gather entropy from SecRandomCopyBytes
*/
void Darwin_SecRandom::poll(Entropy_Accumulator& accum)
   {
   secure_vector<byte>& buf = accum.get_io_buf(BOTAN_SYSTEM_RNG_POLL_REQUEST);

   if(0 == SecRandomCopyBytes(kSecRandomDefault, buf.size(), buf.data()))
      {
      accum.add(buf.data(), buf.size(), BOTAN_ENTROPY_ESTIMATE_STRONG_RNG);
      }
   }

}

/*
* Darwin SecRandomCopyBytes EntropySource
* (C) 2015 Daniel Seither (Kullo GmbH)
*
* Botan is released under the Simplified BSD License (see license.txt)
*/

#include <botan/internal/darwin_secrandom.h>
#include <Security/Security.h>
#include <Security/SecRandom.h>

namespace Botan {

/**
* Gather entropy from SecRandomCopyBytes
*/
void Darwin_SecRandom::poll(Entropy_Accumulator& accum)
   {
   secure_vector<byte>& buf = accum.get_io_buf(BOTAN_SYSTEM_RNG_POLL_REQUEST);

   if(0 == SecRandomCopyBytes(kSecRandomDefault, buf.size(), buf.data()))
      {
      accum.add(buf.data(), buf.size(), BOTAN_ENTROPY_ESTIMATE_STRONG_RNG);
      }
   }

}

Fix SecRandomCopyBytes call with older OS X SDKs


#include "common.th"

_start:
    bare_metal_init()
    prologue

top:
    d <- [rel(min0)]
    e <- [rel(min1)]
    f <- [rel(sec0)]
    g <- [rel(sec1)]

    h <- d << 4 + e
    h <- h << 4 + f
    h <- h << 4 + g
    h -> [0x100]

    c <- 1
    call(sleep)

    g <- g + 1
    h <- g == 10
    g <- g &~ h
    f <- f - h
    h <- f == 6
    f <- f &~ h
    e <- e - h
    h <- e == 10
    e <- e &~ h
    d <- d - h
    h <- d == 6
    d <- d &~ h

    d -> [rel(min0)]
    e -> [rel(min1)]
    f -> [rel(sec0)]
    g -> [rel(sec1)]
    goto(top)

    illegal

sleep:
    c <- c * 1070
    c <- c * 1780
    call(ticks)
    ret

ticks:
    pushall(d,e)
    d <- 0
Lticks_loop:
    e <- d < c
    d <- d + 1
    jnzrel(e,Lticks_loop)
    popall_ret(d,e)

min0: .word 0
min1: .word 0
sec0: .word 0
sec1: .word 0

#include "common.th"

_start:
    bare_metal_init()
    prologue

top:
    d <- [rel(min0)]
    e <- [rel(min1)]
    f <- [rel(sec0)]
    g <- [rel(sec1)]

    h <- d << 4 + e
    h <- h << 4 + f
    h <- h << 4 + g
    h -> [0x100]

    c <- 1
    call(sleep)

    g <- g + 1
    h <- g == 10
    g <- g &~ h
    f <- f - h
    h <- f == 6
    f <- f &~ h
    e <- e - h
    h <- e == 10
    e <- e &~ h
    d <- d - h
    h <- d == 6
    d <- d &~ h

    d -> [rel(min0)]
    e -> [rel(min1)]
    f -> [rel(sec0)]
    g -> [rel(sec1)]
    goto(top)

    illegal

sleep:
    // 40MHz clock, 4-cycle ticks() loop, 8cpi
    c <- c * 1000
    c <- c * 1250
    call(ticks)
    ret

ticks:
    pushall(d,e)
    d <- 0
Lticks_loop:
    e <- d < c
    d <- d + 1
    a <- a // delay to make the loop 4 cycles long
    jnzrel(e,Lticks_loop)
    popall_ret(d,e)

min0: .word 0
min1: .word 0
sec0: .word 0
sec1: .word 0

Update clock delay for new 8-cycle instruction


#include "MainWindow.h"
#include "SpritePackerProjectFile.h"
#include <QApplication>

int commandLine(QCoreApplication& app);

int main(int argc, char *argv[])
{
    QApplication app(argc, argv);
#ifdef Q_OS_WIN32
        QApplication::setStyle(QStyleFactory::create("Fusion"));
#endif

    QCoreApplication::setOrganizationName("amakaseev");
    QCoreApplication::setOrganizationDomain("spicyminds-lab.com");
    QCoreApplication::setApplicationName("SpriteSheetPacker");
    QCoreApplication::setApplicationVersion("1.0.3");
    //QDir::setCurrent(QApplication::applicationDirPath());

    SpritePackerProjectFile::factory().set<SpritePackerProjectFile>("json");
    SpritePackerProjectFile::factory().set<SpritePackerProjectFileOLD>("sp");
    SpritePackerProjectFile::factory().set<SpritePackerProjectFileTPS>("tps");

    if (argc > 1) {
        return commandLine(app);
    } else {
        MainWindow w;
        w.show();
        return app.exec();
    }
}

#include "MainWindow.h"
#include "SpritePackerProjectFile.h"
#include <QApplication>

int commandLine(QCoreApplication& app);

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

    QCoreApplication::setOrganizationName("amakaseev");
    QCoreApplication::setOrganizationDomain("spicyminds-lab.com");
    QCoreApplication::setApplicationName("SpriteSheetPacker");
    QCoreApplication::setApplicationVersion("1.0.3");
    //QDir::setCurrent(QApplication::applicationDirPath());

    SpritePackerProjectFile::factory().set<SpritePackerProjectFile>("json");
    SpritePackerProjectFile::factory().set<SpritePackerProjectFileOLD>("sp");
    SpritePackerProjectFile::factory().set<SpritePackerProjectFileTPS>("tps");

    if (argc > 1) {
        return commandLine(app);
    } else {
        MainWindow w;
        w.show();
        return app.exec();
    }
}

Use windows native look and feel


/*
 * Copyright (c) Facebook, Inc. and its affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 *
 */

#include <quic/common/BufAccessor.h>
#include <folly/portability/GTest.h>

namespace quic {
TEST(SimpleBufAccessor, BasicAccess) {
  SimpleBufAccessor accessor(1000);
  EXPECT_TRUE(accessor.ownsBuffer());
  auto buf = accessor.obtain();
  EXPECT_EQ(1000, buf->capacity());
  EXPECT_FALSE(accessor.ownsBuffer());
  auto empty = accessor.obtain();
  EXPECT_EQ(nullptr, empty);
  accessor.release(buf->clone());
  EXPECT_TRUE(accessor.ownsBuffer());
  EXPECT_DEATH(accessor.release(std::move(buf)), "");
}

TEST(SimpleBufAccessor, CapacityMatch) {
  SimpleBufAccessor accessor(1000);
  auto buf = accessor.obtain();
  buf = folly::IOBuf::create(2000);
  EXPECT_DEATH(accessor.release(std::move(buf)), "");
}

TEST(SimpleBufAccessor, RefuseChainedBuf) {
  SimpleBufAccessor accessor(1000);
  auto buf = accessor.obtain();
  buf->prependChain(folly::IOBuf::create(0));
  EXPECT_DEATH(accessor.release(std::move(buf)), "");
}
} // namespace quic

/*
 * Copyright (c) Facebook, Inc. and its affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 *
 */

#include <quic/common/BufAccessor.h>
#include <folly/portability/GTest.h>

namespace quic {
TEST(SimpleBufAccessor, BasicAccess) {
  SimpleBufAccessor accessor(1000);
  EXPECT_TRUE(accessor.ownsBuffer());
  auto buf = accessor.obtain();
  EXPECT_LE(1000, buf->capacity());
  EXPECT_FALSE(accessor.ownsBuffer());
  auto empty = accessor.obtain();
  EXPECT_EQ(nullptr, empty);
  accessor.release(buf->clone());
  EXPECT_TRUE(accessor.ownsBuffer());
  EXPECT_DEATH(accessor.release(std::move(buf)), "");
}

TEST(SimpleBufAccessor, CapacityMatch) {
  SimpleBufAccessor accessor(1000);
  auto buf = accessor.obtain();
  buf = folly::IOBuf::create(2000);
  EXPECT_DEATH(accessor.release(std::move(buf)), "");
}

TEST(SimpleBufAccessor, RefuseChainedBuf) {
  SimpleBufAccessor accessor(1000);
  auto buf = accessor.obtain();
  buf->prependChain(folly::IOBuf::create(0));
  EXPECT_DEATH(accessor.release(std::move(buf)), "");
}
} // namespace quic

Fix capacity check in BufAccessor test


#include <QtGui>
#include <sequanto/automation.h>
#include <sequanto/tree.h>
#include <sequanto/QtWrapper.h>
#include "../cxx/src/cxx_root.h"

#include <windows.h>

using namespace sequanto::automation;

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

   sq_init ();

   sq_server_init ( &server, 4321 );

   QApplication * application = new QApplication ( argc, argv );

   ListNode * test = new ListNode ("test");

   sq_get_cxx_root()->AddChild ( test );

   QtWrapper::WrapApplication ( test );

   sq_server_poll ( &server );

   atexit ( sq_shutdown );
}

#include <QtGui>
#include <sequanto/automation.h>
#include <sequanto/tree.h>
#include <sequanto/QtWrapper.h>
#include "../cxx/src/cxx_root.h"
#include "config.h"

using namespace sequanto::automation;

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

   sq_init ();

   sq_server_init ( &server, 4321 );

   QApplication * application = new QApplication ( argc, argv );

   ListNode * test = new ListNode ("test");

   sq_get_cxx_root()->AddChild ( test );

   QtWrapper::WrapApplication ( test );

   sq_server_poll ( &server );

   atexit ( sq_shutdown );
}

Include config.h instead of windows.h in shared library test project.


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

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

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

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

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

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

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

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

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


#include "insect/records.h"

static void
__record(Record *);

#include <assert.h>

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

static void
__path_copy(RecordPath path, RecordPath *ref)
{
	int len = strnlen(path, RECORD_PATH_MAX);
	assert(ref);
	*ref = malloc(len + 1);
	assert(*ref);
	(void) strncpy(*ref, path, len + 1);
}

Record *
record_new(RecordPath path)
{
	Record *record;
	assert(path);
	record = malloc(sizeof(Record));
	assert(record);
	record->hits = 1;
	record->path = NULL;
	__path_copy(path, &record->path);
	__record(record);
	return record;
}

void
record_free(Record *record)
{
	assert(record);
	record->hits = 0;
	free(record->path);
	free(record);
}

#include "insect/records.h"

static void
__record(Record *);

static void
__path_copy(Path, Path *);
/* FIMXE(teh): ^ inline? */

#include <assert.h>

#include <stdlib.h>

Record *
record_new(Path path)
{
	Record *record;
	assert(path);
	record = malloc(sizeof(Record));
	assert(record);
	record->hits = 1;
	record->path = NULL;
	__path_copy(path, &record->path);
	__record(record);
	return record;
}

void
record_free(Record *record)
{
	assert(record);
	record->hits = 0;
	free((void *) record->path);
	free(record);
}

/* */

#include <string.h>

static void
__path_copy(Path old_path, Path *new_copy)
{
	int len;
	assert(old_path && new_copy);
	len = strnlen(old_path, INSECT_PATH_MAX);
	*new_copy = malloc(len + 1);
	assert(*new_copy);
	(void) strncpy((char *) *new_copy, old_path, len + 1);
}

Rewrite c-string copy helper function cleanly


#include <functional>
#include <boost/optional.hpp>

#include "key_aliases.hh"
#include "file_contents.hh"
#include "contents.hh"
#include "mode.hh"
#include "show_message.hh"

std::map < char, std::function < void (contents&, boost::optional<int>) > >
    global_normal_map,
    global_insert_map;

mode::mode(const std::string& name, bool (*const handle)(char))
    : name(name)
    , handle(handle) { }

bool mode::operator()(char ch) const {
    return handle(ch);
}

const std::string& mode::get_name() const {
    return this->name;
}

static bool fundamental_handle(char ch) {
    if(ch == _resize) return true;
    std::map < char, fun > :: iterator
        it = global_normal_map.find(ch);
    if(it == global_normal_map.end()) return false;

    clear_message();
    it->second(get_contents(),boost::none);
    return true;
}

mode mode::fundamental("Fundamental",fundamental_handle);

#include <functional>
#include <boost/optional.hpp>

#include "key_aliases.hh"
#include "file_contents.hh"
#include "contents.hh"
#include "mode.hh"
#include "show_message.hh"

std::map < char, std::function < void (contents&, boost::optional<int>) > >
    global_normal_map,
    global_insert_map;

mode::mode(const std::string& name, bool (*const handle)(char))
    : name(name)
    , handle(handle) { }

bool mode::operator()(char ch) const {
    return handle(ch);
}

const std::string& mode::get_name() const {
    return this->name;
}

static bool fundamental_handle(char ch) {
    if(ch == _resize) return true;

    auto it = global_normal_map.find(ch);
    if(it == global_normal_map.end()) return false;

    clear_message();
    it->second(get_contents(),boost::none);
    return true;
}

mode mode::fundamental("Fundamental",fundamental_handle);

Use a little type deduction


#include <mlopen/hipoc_kernel.hpp>
#include <mlopen/errors.hpp>

namespace mlopen {

void HIPOCKernelInvoke::run(void* args, std::size_t size) const
{
    hipEvent_t start = nullptr;
    hipEvent_t stop = nullptr;
    void *config[] = {
        HIP_LAUNCH_PARAM_BUFFER_POINTER, args,
        HIP_LAUNCH_PARAM_BUFFER_SIZE, &size,
        HIP_LAUNCH_PARAM_END
    };
    if (callback)
    {
        hipEventCreate(&start);
        hipEventCreate(&stop);

        hipEventRecord(start, nullptr);
    }

    auto status = hipModuleLaunchKernel(fun, gdims[0], gdims[1], gdims[2], ldims[0], ldims[1], ldims[2], 0, stream, nullptr, (void**)&config);
    if(status != hipSuccess) MLOPEN_THROW_HIP_STATUS(status, "Failed to launch kernel");

    if (callback)
    {
        hipEventRecord(stop, nullptr);
        hipEventSynchronize(stop);
        callback(start, stop);
    }
}

HIPOCKernelInvoke HIPOCKernel::Invoke(hipStream_t stream, std::function<void(hipEvent_t, hipEvent_t)> callback)
{
    return HIPOCKernelInvoke{stream, fun, ldims, gdims, name, callback};
}
}

#include <mlopen/hipoc_kernel.hpp>
#include <mlopen/errors.hpp>

namespace mlopen {

void HIPOCKernelInvoke::run(void* args, std::size_t size) const
{
    hipEvent_t start = nullptr;
    hipEvent_t stop = nullptr;
    void *config[] = {
        HIP_LAUNCH_PARAM_BUFFER_POINTER, args,
        HIP_LAUNCH_PARAM_BUFFER_SIZE, &size,
        HIP_LAUNCH_PARAM_END
    };
    if (callback)
    {
        hipEventCreate(&start);
        hipEventCreate(&stop);

        hipEventRecord(start, nullptr);
    }

    // std::cerr << "Launch kernel: " << name << std::endl;
    auto status = hipModuleLaunchKernel(fun, gdims[0], gdims[1], gdims[2], ldims[0], ldims[1], ldims[2], 0, stream, nullptr, (void**)&config);
    if(status != hipSuccess) MLOPEN_THROW_HIP_STATUS(status, "Failed to launch kernel");

    if (callback)
    {
        hipEventRecord(stop, nullptr);
        hipEventSynchronize(stop);
        callback(start, stop);
    }
}

HIPOCKernelInvoke HIPOCKernel::Invoke(hipStream_t stream, std::function<void(hipEvent_t, hipEvent_t)> callback)
{

    return HIPOCKernelInvoke{stream, fun, ldims, gdims, name, callback};
}
}

Add statement to show kernel