#include "hiredis/hiredis.h"
#include <cstdlib>
#include <iostream>
#include <fstream>
#include <string>

using namespace std;

int
main (int argc, const char** argv)
{
  auto context = redisConnect("127.0.0.1", 6379);
//  auto context = redisConnectUnix("/tmp/redis.sock");
  if (context != NULL && context->err) {
    cerr << "Error: " << context->errstr << endl;
    return 1;
  }
  redisCommand (context, "FLUSHDB");
  string line;
  for (size_t param = 1; param < argc; ++param)
  {
    cout << argv [param] << endl;
    string filename = argv[param];
    ifstream dict (filename);
    if (dict.is_open())
    {
      size_t count = 0;
      while (getline(dict, line))
      {
        redisAppendCommand (context, "SET %s true", line.c_str());
        count++;
        if (count == 10000)
        {
          for (size_t j = 0; j < count; ++j)
            redisGetReply (context, NULL);
          count = 0;
          cout << "." << flush;
        }
      }
    }
    dict.close();
    cout << endl;
  }
  cout << endl;
  auto reply = (redisReply*) redisCommand (context, "DBSIZE");
  cout << "# Words: " << reply->integer << endl;
}

#include "hiredis/hiredis.h"
#include <cstdlib>
#include <iostream>
#include <fstream>
#include <string>

using namespace std;

int
main (int argc, const char** argv)
{
  auto context = redisConnect("127.0.0.1", 6379);
//  auto context = redisConnectUnix("/tmp/redis.sock");
  if (context != NULL && context->err) {
    cerr << "Error: " << context->errstr << endl;
    return 1;
  }
  redisCommand (context, "FLUSHDB");
  redisReply* reply;
  string line;
  for (size_t param = 1; param < argc; ++param)
  {
    cout << argv [param] << endl;
    string filename = argv[param];
    ifstream dict (filename);
    if (dict.is_open())
    {
      size_t count = 0;
      while (getline(dict, line))
      {
        redisAppendCommand (context, "SET %s true", line.c_str());
        count++;
        if (count == 10000)
        {
          for (size_t j = 0; j < count; ++j)
          {
            redisGetReply (context, (void**) &reply);
          }
          count = 0;
          cout << "." << flush;
        }
      }
      for (size_t j = 0; j < count; ++j)
      {
        redisGetReply (context, (void**) &reply);
      }
    }
    dict.close();
    cout << endl;
  }
  cout << endl;
  reply = (redisReply*) redisCommand (context, "DBSIZE");
  cout << "# Words: " << reply->integer << endl;
}

Fix handling of replies to show the number of words at the end.


#include <functional>
#include <stack>
#include <string>
#include <ccspec/core/example_group.h>

namespace ccspec {
namespace core {

using std::function;
using std::stack;
using std::string;

stack<ExampleGroup*> groups_being_defined;

// Public methods.

ExampleGroup::~ExampleGroup() {
    for (auto it = children_.begin(); it != children_.end(); ++it)
        delete *it;
}

void ExampleGroup::addExample(Example& example) {
    examples_.push_back(example);
}

void ExampleGroup::run() {
    for (auto& example : examples_)
        example.run();
    for (auto child : children_)
        child->run();
}

// Private methods.

ExampleGroup::ExampleGroup(string desc) : desc_(desc) {}

void ExampleGroup::addChild(ExampleGroup* example_group) {
    children_.push_back(example_group);
}

// Friend methods.

ExampleGroup* describe(string desc, function<void ()> spec) {
    ExampleGroup* example_group = new ExampleGroup(desc);

    if (!groups_being_defined.empty()) {
        ExampleGroup* current_group = groups_being_defined.top();
        current_group->addChild(example_group);
    }

    groups_being_defined.push(example_group);
    spec();
    groups_being_defined.pop();

    return example_group;
}

ExampleGroup* context(string desc, function<void ()> spec) {
    return describe(desc, spec);
}

} // namespace core
} // namespace ccspec

#include <functional>
#include <stack>
#include <string>
#include <ccspec/core/example_group.h>

namespace ccspec {
namespace core {

using std::function;
using std::stack;
using std::string;

stack<ExampleGroup*> groups_being_defined;

// Public methods.

ExampleGroup::~ExampleGroup() {
    for (auto& child : children_)
        delete child;
}

void ExampleGroup::addExample(Example& example) {
    examples_.push_back(example);
}

void ExampleGroup::run() {
    for (auto& example : examples_)
        example.run();
    for (auto child : children_)
        child->run();
}

// Private methods.

ExampleGroup::ExampleGroup(string desc) : desc_(desc) {}

void ExampleGroup::addChild(ExampleGroup* example_group) {
    children_.push_back(example_group);
}

// Friend methods.

ExampleGroup* describe(string desc, function<void ()> spec) {
    ExampleGroup* example_group = new ExampleGroup(desc);

    if (!groups_being_defined.empty()) {
        ExampleGroup* current_group = groups_being_defined.top();
        current_group->addChild(example_group);
    }

    groups_being_defined.push(example_group);
    spec();
    groups_being_defined.pop();

    return example_group;
}

ExampleGroup* context(string desc, function<void ()> spec) {
    return describe(desc, spec);
}

} // namespace core
} // namespace ccspec

Use c++11 syntax for succinct iterator syntax


// Copyright (c) 2010 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 "ppapi/tests/test_case.h"

#include <sstream>

std::string TestCase::MakeFailureMessage(const char* file,
                                         int line,
                                         const char* cmd) {
  std::ostringstream output;
  output << "Failure in " << file << "(" << line << "): " << cmd;
  return output.str();
}

// Copyright (c) 2010 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 "ppapi/tests/test_case.h"

#include <sstream>

std::string TestCase::MakeFailureMessage(const char* file,
                                         int line,
                                         const char* cmd) {
  // The mere presence of this local variable works around a gcc-4.2.4
  // compiler bug in official Chrome Linux builds.  If you remove it,
  // confirm this compile command still works:
  // GYP_DEFINES='branding=Chrome buildtype=Official target_arch=x64'
  //     gclient runhooks
  // make -k -j4 BUILDTYPE=Release ppapi_tests
  std::string s;

  std::ostringstream output;
  output << "Failure in " << file << "(" << line << "): " << cmd;
  return output.str();
}

Fix the Chrome Linux build by working around a compiler bug.


#include "ics3/eeprom.hpp"

#include "ics3/eepparam.hpp"
#include "ics3/ics3.hpp"

#include <stdexcept>

ics::EepParam ics::Eeprom::get(EepParam param) const {
  try {
    param.read(data);
  } catch (...) {
    throw std::runtime_error {"Fail data: non initialize EEPROM by ICS"};
  }
  return param;
}

void ics::Eeprom::set(const EepParam& param) noexcept {
  param.write(data);
}

void ics::Eeprom::copyTo(std::vector<unsigned char>& dest) const noexcept {
  dest.resize(data.size());
  std::copy(data.begin(), data.end(), dest.begin());
}

void ics::Eeprom::copyTo(std::array<unsigned char, 64>& dest) const noexcept {
  dest = data;
}

ics::Eeprom::Eeprom(const std::array<unsigned char, 64>& src)
: data {src}
{}

#include "ics3/eeprom.hpp"

#include "ics3/eepparam.hpp"

#include <stdexcept>

ics::EepParam ics::Eeprom::get(EepParam param) const {
  param.read(data);
  return param;
}

void ics::Eeprom::set(const EepParam& param) noexcept {
  param.write(data);
}

void ics::Eeprom::copyTo(std::vector<unsigned char>& dest) const noexcept {
  dest.resize(data.size());
  std::copy(data.begin(), data.end(), dest.begin());
}

void ics::Eeprom::copyTo(std::array<unsigned char, 64>& dest) const noexcept {
  dest = data;
}

ics::Eeprom::Eeprom(const std::array<unsigned char, 64>& src)
: data {src}
{}

Remove check invalid self; it only created ICS3


#ifndef NULL
#ifdef __cplusplus
#define NULL 0
#else
#define NULL ((void *)0)
#endif
#endif

extern "C" void KMain() {
	__asm {
		mov	ah, 0h
		int	010h
	}
}

#ifndef NULL
#ifdef __cplusplus
#define NULL 0
#else
#define NULL ((void *)0)
#endif
#endif

static struct {
	char size;
	char res;
	short transferSize;
	int dest;
	long source;
} LBAPacket = {0x10, 0, 0, 0, 0};

inline void PrintChar(char c) {
	__asm {
		mov AH, 0x0A;
		mov AL, c;
		mov CX, 1;
		int 0x10;
	}
}

inline char* ReadSector(int source, int size) {
	LBAPacket.source = source;
	LBAPacket.transferSize = size;

	__asm {
		mov SI, LBAPacket;
		mov AH, 0x42;
		mov DL, 0x80;
		int 0x13;
	}

	return (char*)0;
}

extern "C" void KMain() {

}

Implement util functions to read stage2


// RUN: %clangxx_tsan -O1 %s -DLIB -fPIC -fno-sanitize=thread -shared -o %T/libignore_lib0.so
// RUN: %clangxx_tsan -O1 %s -L%T -lignore_lib0 -o %t
// RUN: echo running w/o suppressions:
// RUN: LD_LIBRARY_PATH=%T not %t 2>&1 | FileCheck %s --check-prefix=CHECK-NOSUPP
// RUN: echo running with suppressions:
// RUN: LD_LIBRARY_PATH=%T TSAN_OPTIONS="$TSAN_OPTIONS suppressions=%s.supp" %t 2>&1 | FileCheck %s --check-prefix=CHECK-WITHSUPP

// Tests that interceptors coming from a library specified in called_from_lib
// suppression are ignored.

#ifndef LIB

extern "C" void libfunc();

int main() {
  libfunc();
}

#else  // #ifdef LIB

#include "ignore_lib_lib.h"

#endif  // #ifdef LIB

// CHECK-NOSUPP: WARNING: ThreadSanitizer: data race
// CHECK-NOSUPP: OK

// CHECK-WITHSUPP-NOT: WARNING: ThreadSanitizer: data race
// CHECK-WITHSUPP: OK

// RUN: %clangxx_tsan -O1 %s -DLIB -fPIC -fno-sanitize=thread -shared -o %T/libignore_lib0.so
// RUN: %clangxx_tsan -O1 %s -L%T -lignore_lib0 -o %t
// RUN: echo running w/o suppressions:
// RUN: LD_LIBRARY_PATH=%T${LD_LIBRARY_PATH:+:$LD_LIBRARY_PATH} not %t 2>&1 | FileCheck %s --check-prefix=CHECK-NOSUPP
// RUN: echo running with suppressions:
// RUN: LD_LIBRARY_PATH=%T${LD_LIBRARY_PATH:+:$LD_LIBRARY_PATH} TSAN_OPTIONS="$TSAN_OPTIONS suppressions=%s.supp" %t 2>&1 | FileCheck %s --check-prefix=CHECK-WITHSUPP

// Tests that interceptors coming from a library specified in called_from_lib
// suppression are ignored.

#ifndef LIB

extern "C" void libfunc();

int main() {
  libfunc();
}

#else  // #ifdef LIB

#include "ignore_lib_lib.h"

#endif  // #ifdef LIB

// CHECK-NOSUPP: WARNING: ThreadSanitizer: data race
// CHECK-NOSUPP: OK

// CHECK-WITHSUPP-NOT: WARNING: ThreadSanitizer: data race
// CHECK-WITHSUPP: OK

Make this test more portable


#include "extract.hpp"
#include "../huffman/decompress.hpp"

#include<fstream>
#include<vector>
#include<experimental/filesystem>

void extract(const char* in_file, const char* out_dir) {
	std::ifstream in(in_file);
	extract(in, out_dir);
}

void extract(std::istream& in_stream, const char* out_dir) {
	std::istreambuf_iterator<char> in_iterator(in_stream);

	std::vector<std::string> filenames;

	std::string fn;
	while(true) {
		char next = *in_iterator;
		++in_iterator;
		if(next == '\0') {
			if(fn.empty()) break;
			filenames.push_back(fn);
			fn.clear();
		}
		else {
			fn.push_back(next);
		}
	}

	BinaryRead bin_in(in_iterator);
	for(auto& fn : filenames) {
		std::string full_name = out_dir + ("/" + fn);
		const auto ind = full_name.find_last_of("/");
		std::experimental::filesystem::create_directories(full_name.substr(0, ind));

		std::ofstream out(full_name);
		std::ostreambuf_iterator<char> out_iterator(out);
		decompress(bin_in, out_iterator);
	}
}

#include "extract.hpp"
#include "../huffman/decompress.hpp"

#include<fstream>
#include<vector>
#include<experimental/filesystem>

namespace fs = std::experimental::filesystem;

void extract(const char* in_file, const char* out_dir) {
	std::ifstream in(in_file);
	extract(in, out_dir);
}

void extract(std::istream& in_stream, const char* out_dir) {
	std::istreambuf_iterator<char> in_iterator(in_stream);

	std::vector<std::string> filenames;

	std::string fn;
	while(true) {
		char next = *in_iterator;
		++in_iterator;
		if(next == '\0') {
			if(fn.empty()) break;
			filenames.push_back(fn);
			fn.clear();
		}
		else {
			fn.push_back(next);
		}
	}

	BinaryRead bin_in(in_iterator);
	for(auto& fn : filenames) {
		std::string full_name = fs::path(out_dir) / fn;
		const auto ind = full_name.find_last_of("/");
		fs::create_directories(full_name.substr(0, ind));

		std::ofstream out(full_name);
		std::ostreambuf_iterator<char> out_iterator(out);
		decompress(bin_in, out_iterator);
	}
}

Use filesystem library path concatenation


#include <algorithm>
#include <gtest/gtest.h>

TEST(array, sorting) {
    int foo[3] = {1, 3, 2};

    std::sort(foo, foo + 3);

    EXPECT_EQ(1, foo[0]);
    EXPECT_EQ(2, foo[1]);
    EXPECT_EQ(3, foo[2]);
}

TEST(swap, test1) {
    int a = 1;
    int b = 2;

    std::swap(a, b);

    EXPECT_EQ(2, a);
    EXPECT_EQ(1, b);
}

TEST(reverse, string) {
    std::string s = "abc";

    std::reverse(s.begin(), s.end());

    EXPECT_EQ("cba", s);
}

Add a std::string reverse test


#include <catch.hpp>

#include "WordDecoder.hpp"

namespace {

using namespace Core8;

TEST_CASE("Decode X from pattern vXvv", "[decoder]") {
  REQUIRE(WordDecoder::readX(0x0F00) == 0XF);
  REQUIRE(WordDecoder::readX(0xF0FF) == 0X0);
}

TEST_CASE("Decode Y from pattern vvYv", "[decoder]") {
  REQUIRE(WordDecoder::readY(0x00F0) == 0XF);
  REQUIRE(WordDecoder::readY(0xFF0F) == 0X0);
}

TEST_CASE("Decode N from pattern vvvN", "[decoder]") {
  REQUIRE(WordDecoder::readN(0x000F) == 0XF);
  REQUIRE(WordDecoder::readN(0xFFF0) == 0X0);
}

TEST_CASE("Decode NN from pattern vvNN", "[decoder]") {
  REQUIRE(WordDecoder::readNN(0x00FF) == 0XFF);
  REQUIRE(WordDecoder::readNN(0xFF11) == 0X11);
}

TEST_CASE("Decode NNN from pattern vNNN", "[decoder]") {
  REQUIRE(WordDecoder::readNNN(0x0FFF) == 0XFFF);
  REQUIRE(WordDecoder::readNNN(0xF111) == 0X111);
}

} // unnamed namespace

#include <catch.hpp>

#include "WordDecoder.hpp"

namespace {

TEST_CASE("Decode X from pattern vXvv", "[decoder]") {
  REQUIRE(Core8::WordDecoder::readX(0x0F00) == 0XF);
  REQUIRE(Core8::WordDecoder::readX(0xF0FF) == 0X0);
}

TEST_CASE("Decode Y from pattern vvYv", "[decoder]") {
  REQUIRE(Core8::WordDecoder::readY(0x00F0) == 0XF);
  REQUIRE(Core8::WordDecoder::readY(0xFF0F) == 0X0);
}

TEST_CASE("Decode N from pattern vvvN", "[decoder]") {
  REQUIRE(Core8::WordDecoder::readN(0x000F) == 0XF);
  REQUIRE(Core8::WordDecoder::readN(0xFFF0) == 0X0);
}

TEST_CASE("Decode NN from pattern vvNN", "[decoder]") {
  REQUIRE(Core8::WordDecoder::readNN(0x00FF) == 0XFF);
  REQUIRE(Core8::WordDecoder::readNN(0xFF11) == 0X11);
}

TEST_CASE("Decode NNN from pattern vNNN", "[decoder]") {
  REQUIRE(Core8::WordDecoder::readNNN(0x0FFF) == 0XFFF);
  REQUIRE(Core8::WordDecoder::readNNN(0xF111) == 0X111);
}

} // namespace

Refactor word decoder unit tests


#include <QTabBar>
#include "qclosabletabwidget.h"

QClosableTabWidget::QClosableTabWidget(QWidget *parent)
	: QTabWidget(parent)
{
	tabBar()->installEventFilter(this);
}

bool QClosableTabWidget::eventFilter(QObject *o, QEvent *e)
{
	if (o == tabBar() && e->type() == QEvent::MouseButtonPress)
	{
		QMouseEvent *mouseEvent = static_cast<QMouseEvent *>(e);
		if (mouseEvent->button() == Qt::MiddleButton)
		{
			int index = tabBar()->tabAt(mouseEvent->pos());
			widget(index)->deleteLater();
			removeTab(index);
			return true;
		}
	}

	return QTabWidget::eventFilter(o, e);
}

#include <QTabBar>
#include "qclosabletabwidget.h"

QClosableTabWidget::QClosableTabWidget(QWidget *parent)
	: QTabWidget(parent)
{
	tabBar()->installEventFilter(this);
}

bool QClosableTabWidget::eventFilter(QObject *o, QEvent *e)
{
	if (o == tabBar() && e->type() == QEvent::MouseButtonPress)
	{
		QMouseEvent *mouseEvent = static_cast<QMouseEvent *>(e);
		if (mouseEvent->button() == Qt::MiddleButton)
		{
			int index = tabBar()->tabAt(mouseEvent->pos());
			QWidget *w = widget(index);

			// Unclosable tabs have a maximum width of 16777214 (default: 16777215)
			if (w->maximumWidth() != 16777214)
			{
				w->deleteLater();
				removeTab(index);
				return true;
			}
		}
	}

	return QTabWidget::eventFilter(o, e);
}

Disable middle click close for unclosable tabs


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

#include "GrGLConfig.h"
#include "GrGLInterface.h"

void GrGLClearErr(const GrGLInterface* gl) {
    while (GR_GL_NO_ERROR != gl->fGetError()) {}
}

void GrGLCheckErr(const GrGLInterface* gl,
                  const char* location,
                  const char* call) {
    uint32_t err = GR_GL_GET_ERROR(gl);
    if (GR_GL_NO_ERROR != err) {
        GrPrintf("---- glGetError %x", GR_GL_GET_ERROR(gl));
        if (NULL != location) {
            GrPrintf(" at\n\t%s", location);
        }
        if (NULL != call) {
            GrPrintf("\n\t\t%s", call);
        }
        GrPrintf("\n");
    }
}

void GrGLResetRowLength(const GrGLInterface* gl) {
    if (gl->supportsDesktop()) {
        GR_GL_CALL(gl, PixelStorei(GR_GL_UNPACK_ROW_LENGTH, 0));
    }
}

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

#if GR_GL_LOG_CALLS
    bool gLogCallsGL = !!(GR_GL_LOG_CALLS_START);
#endif

#if GR_GL_CHECK_ERROR
    bool gCheckErrorGL = !!(GR_GL_CHECK_ERROR_START);
#endif

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

#include "GrGLConfig.h"
#include "GrGLInterface.h"

void GrGLClearErr(const GrGLInterface* gl) {
    while (GR_GL_NO_ERROR != gl->fGetError()) {}
}

void GrGLCheckErr(const GrGLInterface* gl,
                  const char* location,
                  const char* call) {
    uint32_t err = GR_GL_GET_ERROR(gl);
    if (GR_GL_NO_ERROR != err) {
        GrPrintf("---- glGetError %x", err);
        if (NULL != location) {
            GrPrintf(" at\n\t%s", location);
        }
        if (NULL != call) {
            GrPrintf("\n\t\t%s", call);
        }
        GrPrintf("\n");
    }
}

void GrGLResetRowLength(const GrGLInterface* gl) {
    if (gl->supportsDesktop()) {
        GR_GL_CALL(gl, PixelStorei(GR_GL_UNPACK_ROW_LENGTH, 0));
    }
}

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

#if GR_GL_LOG_CALLS
    bool gLogCallsGL = !!(GR_GL_LOG_CALLS_START);
#endif

#if GR_GL_CHECK_ERROR
    bool gCheckErrorGL = !!(GR_GL_CHECK_ERROR_START);
#endif

Fix gl error debug print.


# include <algorithm>
# include <iostream>
# include <iterator>
# include <vector>
# include <string>
# include <queue>
# include <stack>
# include <cmath>
# include <set>

using namespace std;

int main() {
    return 0;
}

# include <cmath>
# include <iostream>
# include <queue>
# include <set>
# include <stack>
# include <string>
# include <vector>

using namespace std;

int main() {
    return 0;
}

Remove some headers which are not frequently used


#include<iostream>
#include"InputHandler.h"
#include"Game.h"

InputHandler *InputHandler::instance = 0;

void InputHandler::initialiseJoysticks()
{
    if (SDL_WasInit(SDL_INIT_JOYSTICK) == 0) {
        SDL_InitSubSystem(SDL_INIT_JOYSTICK);
    }

    if (SDL_NumJoysticks() > 0) {
        joysticksInitialised = false;
        return;
    }

    for (int x = 0; x < SDL_NumJoysticks(); x++) {
        SDL_Joystick *joystick = SDL_JoystickOpen(x);

        if (!joystick) {
            std::cout << SDL_GetError() << std::endl;
            continue;
        }

        joysticks.push_back(joystick);
    }

    SDL_JoystickEventState(SDL_ENABLE);
    joysticksInitialised = true;

    std::cout << "Initialised " << joysticks.size() << " joystick(s)." << std::endl;
}

void InputHandler::clean()
{
    if (!joysticksInitialised) {
        return;
    }

    for (int x = 0; x < SDL_NumJoysticks(); x++) {
        SDL_JoystickClose(joysticks[x]);
    }
}

void InputHandler::update()
{
    SDL_Event event;

    while (SDL_PollEvent(&event)) {
        if (event.type == SDL_QUIT) {
            TheGame::getInstance()->clean();
        }
    }
}

#include<iostream>
#include"InputHandler.h"
#include"Game.h"

InputHandler *InputHandler::instance = 0;

void InputHandler::initialiseJoysticks()
{
    if (SDL_WasInit(SDL_INIT_JOYSTICK) == 0) {
        SDL_InitSubSystem(SDL_INIT_JOYSTICK);
    }

    if (SDL_NumJoysticks() <= 0) {
        joysticksInitialised = false;
        return;
    }

    for (int x = 0; x < SDL_NumJoysticks(); x++) {
        SDL_Joystick *joystick = SDL_JoystickOpen(x);

        if (!joystick) {
            std::cout << SDL_GetError() << std::endl;
            continue;
        }

        joysticks.push_back(joystick);
    }

    SDL_JoystickEventState(SDL_ENABLE);
    joysticksInitialised = true;

    std::cout << "Initialised " << joysticks.size() << " joystick(s)." << std::endl;
}

void InputHandler::clean()
{
    if (!joysticksInitialised) {
        return;
    }

    for (int x = 0; x < SDL_NumJoysticks(); x++) {
        SDL_JoystickClose(joysticks[x]);
    }
}

void InputHandler::update()
{
    SDL_Event event;

    while (SDL_PollEvent(&event)) {
        if (event.type == SDL_QUIT) {
            TheGame::getInstance()->clean();
        }
    }
}

Fix if condition from initialization of joysticks.


// RUN: %clang_cc1 -std=c++2a -verify %s
// expected-no-diagnostics

template<typename ...T, typename ...Lambda> void check_sizes(Lambda ...L) {
  static_assert(((sizeof(T) == sizeof(Lambda)) && ...));
}

template<typename ...T> void f(T ...v) {
  // Pack expansion of lambdas: each lambda captures only one pack element.
  check_sizes<T...>([=] { (void)&v; } ...);

  // Pack expansion inside lambda: captures all pack elements.
  auto l = [=] { ((void)&v, ...); };
  static_assert(sizeof(l) >= (sizeof(T) + ...));
}

template void f(int, char, double);

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

template<typename ...T, typename ...Lambda> void check_sizes(Lambda ...L) {
  static_assert(((sizeof(T) == sizeof(Lambda)) && ...));
}

template<typename ...T> void f(T ...v) {
  // Pack expansion of lambdas: each lambda captures only one pack element.
  check_sizes<T...>([=] { (void)&v; } ...);

  // Pack expansion inside lambda: captures all pack elements.
  auto l = [=] { ((void)&v, ...); };
  static_assert(sizeof(l) >= (sizeof(T) + ...));
}

template void f(int, char, double);

namespace PR41576 {
  template <class... Xs> constexpr int f(Xs ...xs) {
    return [&](auto ...ys) { // expected-note {{instantiation}}
      return ((xs + ys), ...); // expected-warning {{unused}}
    }(1, 2);
  }
  static_assert(f(3, 4) == 6); // expected-note {{instantiation}}
}

Add regression test for PR41576 (which is already fixed in trunk, perhaps by r361300).


#include "edge_common.h"

v8::Local<Value> throwV8Exception(v8::Local<Value> exception)
{
    Nan::EscapableHandleScope scope;
    Nan::ThrowError(exception);
    return scope.Escape(exception);
}

v8::Local<Value> throwV8Exception(const char* format, ...)
{
	va_list args;
	va_start(args, format);

	size_t size = vsnprintf(NULL, 0, format, args);
	char* message = new char[size + 1];

	vsnprintf(message, size + 1, format, args);

	Nan::EscapableHandleScope scope;

	v8::Local<v8::Object> exception = Nan::New<v8::Object>();
	exception->SetPrototype(Nan::GetCurrentContext(), v8::Exception::Error(Nan::New<v8::String>(message).ToLocalChecked()));

	v8::Local<v8::Value> exceptionValue = exception;
	Nan::ThrowError(exceptionValue);

	return scope.Escape(exception);
}

#include "edge_common.h"

v8::Local<Value> throwV8Exception(v8::Local<Value> exception)
{
    Nan::EscapableHandleScope scope;
    Nan::ThrowError(exception);
    return scope.Escape(exception);
}

v8::Local<Value> throwV8Exception(const char* format, ...)
{
	va_list args;
	va_start(args, format);

	size_t size = vsnprintf(NULL, 0, format, args);
	char* message = new char[size + 1];

	va_start(args, format);
	vsnprintf(message, size + 1, format, args);

	Nan::EscapableHandleScope scope;

	v8::Local<v8::Object> exception = Nan::New<v8::Object>();
	exception->SetPrototype(Nan::GetCurrentContext(), v8::Exception::Error(Nan::New<v8::String>(message).ToLocalChecked()));

	v8::Local<v8::Value> exceptionValue = exception;
	Nan::ThrowError(exceptionValue);

	return scope.Escape(exception);
}

Fix for issue that would cause an occasional segmentation fault on Linux if already in an error state in throwV8Exception. va_list must be reinitialized after each use.


#include "forgetthread.h"

void ForgetThread::launch(){
    //Aliases
    transactionHistory = transactionHistoryPtr[thread];
    tupleContent = tupleContentPtr[thread];

    mutexForget.lock();
    while(true){
        //Waits for the signal from main thread
        processingForgetThreadsNb++;
        conditionForget.wait(mutexForget);
        mutexForget.unlock();

        //Checks if the program is over
        if(referenceOver) break;

        //Actual forget work
        processForget();

        //When done processing decrements processingThreadNb
        if(--processingForgetThreadsNb==0){
            //Signals main thread
            mutexForget.lock();
            conditionForget.notify_all();
            mutexForget.unlock();
        }else{
            //waits for the releaser thread
            mutexForget.lock();
            conditionForget.wait(mutexForget);
        }
    }

    pthread_exit(EXIT_SUCCESS);
}

void ForgetThread::processForget(){
    Tuple bound{forgetTransactionId, 0};
    for(auto iter=transactionHistory->begin(); iter!=transactionHistory->end(); ++iter){
        auto * secondMap = &(iter->second);
        for(auto iter2=secondMap->begin(); iter2!=secondMap->end(); ++iter2){
            vector<Tuple> * tuples = &(iter2->second);
            tuples->erase(tuples->begin(), lower_bound(tuples->begin(), tuples->end(), bound));
        }
    }
    //Erase from tupleContent
    tupleContent->erase(tupleContent->begin(), tupleContent->lower_bound(bound));
}

#include "forgetthread.h"

void ForgetThread::launch(){
    //Aliases
    transactionHistory = transactionHistoryPtr[thread];
    tupleContent = tupleContentPtr[thread];

    mutexForget.lock();
    while(true){
        //Waits for the signal from main thread
        processingForgetThreadsNb++;
        conditionForget.wait(mutexForget);
        mutexForget.unlock();

        //Checks if the program is over
        if(referenceOver) break;

        //Actual forget work
        processForget();

        //When done processing decrements processingThreadNb
        if(--processingForgetThreadsNb==0){
            //Signals main thread
            mutexForget.lock();
            conditionForget.notify_all();
            mutexForget.unlock();
        }else{
            //waits for the releaser thread
            mutexForget.lock();
            conditionForget.wait(mutexForget);
        }
    }

    pthread_exit(EXIT_SUCCESS);
}

void ForgetThread::processForget(){
    Tuple bound{forgetTransactionId, 0};
    for(auto iter=transactionHistory->begin(); iter!=transactionHistory->end(); ++iter){
        auto * secondMap = &(iter->second);
        for(auto iter2=secondMap->begin(); iter2!=secondMap->end();){
            vector<Tuple> * tuples = &(iter2->second);
            tuples->erase(tuples->begin(), lower_bound(tuples->begin(), tuples->end(), bound));
            if(tuples->empty()){
                auto toErase = iter2;
                ++iter2;
                secondMap->erase(toErase);
            }else{
                ++iter2;
            }
        }
    }
    //Erase from tupleContent
    tupleContent->erase(tupleContent->begin(), tupleContent->lower_bound(bound));
}

Remove entry from map if vector<Tuple> empty in ForgetThread::processForget()


#if __cplusplus >= 201402L

#include "test.h"
#include "floaxie/ftoa.h"

void dtoa_floaxie(double v, char* buffer)
{
	floaxie::ftoa(v, buffer);
}

REGISTER_TEST(floaxie);

#endif

Fix building for pre-C++14 standards


// Copyright (c) 2012 Cloudera, Inc. All rights reserved.
//
// This file contains the main() function for the state store process,
// which exports the Thrift service StateStoreService.

#include <glog/logging.h>
#include <gflags/gflags.h>

#include "sparrow/state-store-service.h"
#include "util/cpu-info.h"

DEFINE_int32(state_store_port, 24000, "port where StateStoreService is exported");

int main(int argc, char** argv) {
  google::InitGoogleLogging(argv[0]);
  google::ParseCommandLineFlags(&argc, &argv, true);
  impala::CpuInfo::Init();

  boost::shared_ptr<sparrow::StateStore> state_store(new sparrow::StateStore());
  state_store->Start(FLAGS_state_store_port);
  state_store->WaitForServerToStop();
}

// Copyright (c) 2012 Cloudera, Inc. All rights reserved.
//
// This file contains the main() function for the state store process,
// which exports the Thrift service StateStoreService.

#include <glog/logging.h>
#include <gflags/gflags.h>
#include <iostream>

#include "common/status.h"
#include "sparrow/state-store-service.h"
#include "util/cpu-info.h"
#include "util/webserver.h"
#include "util/logging.h"
#include "util/default-path-handlers.h"

DECLARE_int32(state_store_port);
DECLARE_int32(webserver_port);
DECLARE_bool(enable_webserver);

using impala::Webserver;
using impala::Status;
using namespace std;

int main(int argc, char** argv) {
  // Override default for webserver port
  FLAGS_webserver_port = 9190;
  google::ParseCommandLineFlags(&argc, &argv, true);
  impala::InitGoogleLoggingSafe(argv[0]);
  impala::CpuInfo::Init();

  boost::shared_ptr<sparrow::StateStore> state_store(new sparrow::StateStore());

  boost::scoped_ptr<Webserver> webserver(new Webserver());

  if (FLAGS_enable_webserver) {
    impala::AddDefaultPathHandlers(webserver.get());
    EXIT_IF_ERROR(webserver->Start());
  } else {
    LOG(INFO) << "Not starting webserver";
  }

  state_store->Start(FLAGS_state_store_port);
  state_store->WaitForServerToStop();
}

Allow configuraiton of state-store log dir / name. Also add debug webserver to state-store.


#include "ReQL-ast-test.hpp"

class BlankTest : public ASTTest {
public:
  BlankTest() : ASTTest() {
  }

  void setup() {
    setName("BlankTest");
  }

  void run() {
  }

  void cleanup() {
  }
};

void ASTTest::setup() {
  setName("ASTTest");
  addTest(BlankTest());
}

#include "ReQL-ast-test.hpp"

using namespace ReQL;

class BlankTest : public ASTTest {
public:
  BlankTest() : ASTTest() {
  }

  void setup();

  void cleanup() {
    conn.close();
  }

  Connection conn;
};

class TableTermTest : public BlankTest {
public:
  TableTermTest() : BlankTest() {};

  void run() {
    table({expr("test")}).run(conn);
  }
};

void BlankTest::setup() {
  setName("BlankTest");
  conn = connect();
  assert(conn.isOpen(), "Connection failed.");
  addTest(TableTermTest());
}

void ASTTest::setup() {
  setName("ASTTest");
  addTest(BlankTest());
}

Add test to retrieve a table from database.


#include<iostream>

using namespace std;

class node{
	public:
		int data;
		node *left, *right;

		node(){}

		node(int d) {
			data=d;
			left=NULL;
			right=NULL;
		}

		node *insertNode(node *root, int d) {
			if(!root)
				return new node(d);
			else if(d <= root->data)
				root->left=insertNode(root->left,d);
			else
				root->right=insertNode(root->right,d);

			return root;
		}

		node *inorder(node *root) {
			if(root) {
				inorder(root->left);
				cout<<root->data<<"\n";
				inorder(root->right);
			}
		}
};

int main()
{
	int n,d;
	node nd;
	node *root=NULL;

	cout<<"Enter the number of elements in the tree:";
	cin>>n;

	for(int i=0;i<n;i++){
		cout<<"\nEnter the element "<<i+1<<" of the tree:";
		cin>>d;
		root=nd.insertNode(root,d);
	}

	cout<<"\nInorder traversal of the tree gives:\n";
	nd.inorder(root);
}

#include<iostream>

using namespace std;

class node{
	public:
		int data;
		node *left, *right;

		node(){}

		node(int d) {
			data=d;
			left=NULL;
			right=NULL;
		}

		node *insertNode(node *root, int d) {
			if(!root)
				return new node(d);
			if(d <= root->data)
				root->left=insertNode(root->left,d);
			else
				root->right=insertNode(root->right,d);

			return root;
		}

		node *inorder(node *root) {
			if(root) {
				if(root->left)
					inorder(root->left);

				cout<<root->data<<"\n";

				if(root->right)
					inorder(root->right);
			}
		}
};

int main()
{
	int n,d;
	node nd;
	node *root=NULL;

	cout<<"Enter the number of elements in the tree:";
	cin>>n;

	for(int i=0;i<n;i++){
		cout<<"\nEnter the element "<<i+1<<" of the tree:";
		cin>>d;
		root=nd.insertNode(root,d);
	}

	cout<<"\nInorder traversal of the tree gives:\n";
	nd.inorder(root);
}

Fix reference to unavailable nodes


#include "gtest/gtest.h"

#include "IMediaLibrary.h"

TEST( MediaLibary, Init )
{
    IMediaLibrary* ml = MediaLibraryFactory::create();
    ASSERT_TRUE( ml->initialize( "test.db" ) );
}

#include "gtest/gtest.h"

#include "IMediaLibrary.h"

class MLTest : public testing::Test
{
    public:
        static IMediaLibrary* ml;

    protected:
        virtual void SetUp()
        {
            ml = MediaLibraryFactory::create();
            bool res = ml->initialize( "test.db" );
            ASSERT_TRUE( res );
        }

        virtual void TearDown()
        {
            delete ml;
            unlink("test.db");
        }
};

IMediaLibrary* MLTest::ml;

TEST_F( MLTest, Init )
{
    // only test for correct test fixture behavior
}

TEST_F( MLTest, InsertFile )
{
    IFile* f = ml->addFile( "/dev/null" );
    ASSERT_TRUE( f != NULL );

    std::vector<IFile*> files = ml->files();
    ASSERT_EQ( files.size(), 1u );
    ASSERT_EQ( files[0]->mrl(), f->mrl() );
}

Clear database between each test & add a test for file insertion


#include "WebcamDataProvider.h"

namespace yarrar
{

WebcamDataProvider::WebcamDataProvider(const json11::Json& config)
    : DataProvider(config)
    , m_videoCapture(0)
    , m_dp({})
{
    if(!m_videoCapture.isOpened())
    {
        throw std::runtime_error("cant open video");
    }
}

const LockableData<Datapoint>& WebcamDataProvider::getData()
{
    cv::Mat ret;
    m_videoCapture >> ret;

    auto handle = m_dp.lockReadWrite();
    handle.set({ std::chrono::high_resolution_clock::now(),
        ret });

    return m_dp;
}

Dimensions WebcamDataProvider::getDimensions()
{
    const auto& data = getData();
    auto handle = data.lockRead();
    return {
        handle.get().data.cols,
        handle.get().data.rows
    };
}

DatatypeFlags WebcamDataProvider::provides()
{
    return RGB_CAMERA_FLAG;
}
}

#include "WebcamDataProvider.h"

namespace yarrar
{

WebcamDataProvider::WebcamDataProvider(const json11::Json& config)
    : DataProvider(config)
    , m_videoCapture(0)
    , m_dp({})
{
    if(!m_videoCapture.isOpened())
    {
        throw std::runtime_error("cant open video");
    }
}

const LockableData<Datapoint>& WebcamDataProvider::getData()
{
    cv::Mat ret;
    m_videoCapture >> ret;

    auto handle = m_dp.lockReadWrite();
    handle.set({ std::chrono::high_resolution_clock::now(),
        ret });

    return m_dp;
}

Dimensions WebcamDataProvider::getDimensions()
{
    return {
        static_cast<int>(m_videoCapture.get(CV_CAP_PROP_FRAME_WIDTH)),
        static_cast<int>(m_videoCapture.get(CV_CAP_PROP_FRAME_HEIGHT))
    };
}

DatatypeFlags WebcamDataProvider::provides()
{
    return RGB_CAMERA_FLAG;
}
}

Use cv::VideoCapture properties to get width and height.


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

using namespace Microsoft::VisualStudio::CppUnitTestFramework;

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

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

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

using namespace Microsoft::VisualStudio::CppUnitTestFramework;

namespace DNAnalyzerServerTest
{
	TEST_CLASS(DictionnaireTest)
	{
	public:
	};
}

Revert "Ajout de 2 methode de test Dictionnaire (reste incomplet)"


#include <iostream>
using std::cout;
using std::endl;

#include "problems/Factory.h"
#include "util/Timer.h"
using util::Timer;

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

  auto problem = problems::Factory::create(1);

  Timer t;

  t.start();
  problem->solve();
  t.stop();

  cout << problem->answer() << endl;
  cout << "Time elapsed: " << t << endl;

  return 0;
}

#include <iostream>
using std::cerr;
using std::cout;
using std::endl;
#include <stdexcept>
using std::exception;
using std::out_of_range;
#include <string>
using std::stoul;

#include "problems/Factory.h"
#include "util/Timer.h"
using util::Timer;

void all_problems();
void one_problem(const unsigned long problem);

int main(int argc, char **argv) {
  bool usage = false;

  try {
    if (argc > 2)
      usage = true;
    else if (argc == 2)
      one_problem(stoul(argv[1]));
    else
      all_problems();
  }
  catch (out_of_range oor) {
    usage = true;
    cerr << "Number too large.\n";
  }
  catch (exception ia) {
    usage = true;
  }

  if (usage) {
    cerr << "Invalid usage. Pass either a number or nothing to run all" << endl;
    return 1;
  }

  return 0;
}

void all_problems() {
}

void one_problem(const unsigned long problem) {
  auto p = problems::Factory::create(problem);

  Timer t;

  t.start();
  p->solve();
  t.stop();

  cout << p->answer() << "\n"
       << "Time elapsed: " << t << endl;
}

Make apps/pe accept problem number as argument


#include "notebooktree.h"
#include "treenotebookitem.h"
#include "treenotebookpageitem.h"
#include "notebookexception.h"

NotebookTree::NotebookTree(QWidget* parent) :
    QTreeWidget(parent)
{
    this->setColumnCount(1);
}

void NotebookTree::addNotebook(Notebook& notebook)
{
    TreeNotebookItem* treeItem = new TreeNotebookItem(notebook);
    if (this->notebookTrees.find(&notebook) == this->notebookTrees.end())
    {
        this->notebookTrees[&notebook] = treeItem;
        this->addTopLevelItem(treeItem);
    }
    else
    {
        delete treeItem;
        throw NotebookException("Cannot add a notebook multiple times to the tree");
    }
}

void NotebookTree::selectPage(Notebook* notebook, NotebookPage* page)
{
    auto notebookTreeIter = this->notebookTrees.find(notebook);
    if (notebookTreeIter == this->notebookTrees.end())
        throw NotebookException("Could not find tree node for the page to select");

    TreeNotebookItem* notebookTree = *notebookTreeIter;
    QTreeWidgetItem* sectionTree = 0;
    TreeNotebookPageItem* pageNode = 0;
    notebookTree->getPathToPage(page, sectionTree, pageNode);
    if (!sectionTree)
        throw NotebookException("Result from getPathToPage; sectionTree is null");
    if (!pageNode)
        throw NotebookException("Result from getPathToPage; pageNode is null");

    notebookTree->setExpanded(true);
    sectionTree->setExpanded(true);
    pageNode->setSelected(true);
}

#include "notebooktree.h"
#include "treenotebookitem.h"
#include "treenotebookpageitem.h"
#include "notebookexception.h"

#include <QHeaderView>

NotebookTree::NotebookTree(QWidget* parent) :
    QTreeWidget(parent)
{
    this->setColumnCount(1);
    this->header()->hide();
}

void NotebookTree::addNotebook(Notebook& notebook)
{
    TreeNotebookItem* treeItem = new TreeNotebookItem(notebook);
    if (this->notebookTrees.find(&notebook) == this->notebookTrees.end())
    {
        this->notebookTrees[&notebook] = treeItem;
        this->addTopLevelItem(treeItem);
    }
    else
    {
        delete treeItem;
        throw NotebookException("Cannot add a notebook multiple times to the tree");
    }
}

void NotebookTree::selectPage(Notebook* notebook, NotebookPage* page)
{
    auto notebookTreeIter = this->notebookTrees.find(notebook);
    if (notebookTreeIter == this->notebookTrees.end())
        throw NotebookException("Could not find tree node for the page to select");

    TreeNotebookItem* notebookTree = *notebookTreeIter;
    QTreeWidgetItem* sectionTree = 0;
    TreeNotebookPageItem* pageNode = 0;
    notebookTree->getPathToPage(page, sectionTree, pageNode);
    if (!sectionTree)
        throw NotebookException("Result from getPathToPage; sectionTree is null");
    if (!pageNode)
        throw NotebookException("Result from getPathToPage; pageNode is null");

    notebookTree->setExpanded(true);
    sectionTree->setExpanded(true);
    pageNode->setSelected(true);
}

Remove header from notebook tree


// Copyright (c) 2015 Andrew Sutton
// All rights reserved

#include "lingo/utility.hpp"

#include <cstdlib>
#include <cxxabi.h>

namespace lingo
{

String
type_str(std::type_info const& t)
{
  std::size_t n = 0;
  char* buf = abi::__cxa_demangle(t.name(), nullptr, &n, 0);
  String result(buf, n);
  std::free(buf);
  return result;
}

} // namespace lingo

// Copyright (c) 2015 Andrew Sutton
// All rights reserved

#include "lingo/utility.hpp"

#include <cstdlib>
#include <cxxabi.h>
#include <iostream>

namespace lingo
{

String
type_str(std::type_info const& t)
{
  std::size_t n = 0;
  char* buf = abi::__cxa_demangle(t.name(), nullptr, &n, 0);
  String result(buf);
  std::free(buf);
  return result;
}

} // namespace lingo

Fix bug in name demangling.


#include <QTest>
#include <QObject>

#include "uritests.h"

// This is all you need to run all the tests
int main(int argc, char *argv[])
{
    URITests test1;
    QTest::qExec(&test1);
}

#include <QTest>
#include <QObject>

#include "uritests.h"

// This is all you need to run all the tests
int main(int argc, char *argv[])
{
    bool fInvalid = false;

    URITests test1;
    if (QTest::qExec(&test1) != 0)
        fInvalid = true;

    return fInvalid;
}

Return !0 when qt tests fail.


#include "EjectOSD.h"

#include <Dbt.h>

#include "..\Monitor.h"
#include "..\Skin.h"

EjectOSD::EjectOSD() :
OSD(L"3RVX-EjectDispatcher") {
    _mWnd = new MeterWnd(L"3RVX-EjectOSD", L"3RVX-EjectOSD");

    Skin *skin = _settings.CurrentSkin();
    Gdiplus::Bitmap *bg = skin->OSDBgImg("eject");
    _mWnd->BackgroundImage(bg);
    _mWnd->Update();

    _mWnd->VisibleDuration(800);

    HMONITOR monitor = Monitor::Default();
    const int mWidth = Monitor::Width(monitor);
    const int mHeight = Monitor::Height(monitor);
    _mWnd->X(mWidth / 2 - _mWnd->Width() / 2);
    _mWnd->Y(mHeight - _mWnd->Height() - 140);
}

void EjectOSD::Hide() {
    _mWnd->Hide(false);
}

LRESULT
EjectOSD::WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) {
    if (message == WM_DEVICECHANGE) {
        if (wParam == DBT_DEVICEREMOVECOMPLETE) {
            CLOG(L"Device removal notification received");
            HideOthers(Eject);
            _mWnd->Show();
        }
    }

    return DefWindowProc(hWnd, message, wParam, lParam);
}

#include "EjectOSD.h"

#include <Dbt.h>

#include "..\Monitor.h"
#include "..\Skin.h"

EjectOSD::EjectOSD() :
OSD(L"3RVX-EjectDispatcher") {
    _mWnd = new MeterWnd(L"3RVX-EjectOSD", L"3RVX-EjectOSD");

    Skin *skin = _settings.CurrentSkin();

    if (skin->HasOSD("eject") == false) {
        return;
    }

    Gdiplus::Bitmap *bg = skin->OSDBgImg("eject");
    _mWnd->BackgroundImage(bg);
    _mWnd->Update();

    _mWnd->VisibleDuration(800);

    HMONITOR monitor = Monitor::Default();
    const int mWidth = Monitor::Width(monitor);
    const int mHeight = Monitor::Height(monitor);
    _mWnd->X(mWidth / 2 - _mWnd->Width() / 2);
    _mWnd->Y(mHeight - _mWnd->Height() - 140);
}

void EjectOSD::Hide() {
    _mWnd->Hide(false);
}

LRESULT
EjectOSD::WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) {
    if (message == WM_DEVICECHANGE) {
        if (wParam == DBT_DEVICEREMOVECOMPLETE) {
            CLOG(L"Device removal notification received");
            HideOthers(Eject);
            _mWnd->Show();
        }
    }

    return DefWindowProc(hWnd, message, wParam, lParam);
}

Make sure skin has OSD before initializing it


#include <QtCore/QCoreApplication>
#include <QtCore/QDebug>
#include <QtCore/QTimer>

#include <QtDBus/QtDBus>

#include <QtTest/QtTest>

#include <tests/lib/test.h>

class TestDoNothing : public Test
{
    Q_OBJECT

public:
    TestDoNothing(QObject *parent = 0)
        : Test(parent)
    { }

private slots:
    void initTestCase();
    void init();

    void doNothing();
    void doNothing2();

    void cleanup();
    void cleanupTestCase();
};

void TestDoNothing::initTestCase()
{
    initTestCaseImpl();
}

void TestDoNothing::init()
{
    initImpl();
}

void TestDoNothing::doNothing()
{
    QTimer::singleShot(0, mLoop, SLOT(quit()));
    QCOMPARE(mLoop->exec(), 0);
}

void TestDoNothing::doNothing2()
{
    QTimer::singleShot(0, mLoop, SLOT(quit()));
    QCOMPARE(mLoop->exec(), 0);
}

void TestDoNothing::cleanup()
{
    cleanupImpl();
}

void TestDoNothing::cleanupTestCase()
{
    cleanupTestCaseImpl();
}

QTEST_MAIN(TestDoNothing)
#include "_gen/do-nothing.cpp.moc.hpp"

#include <QtCore/QCoreApplication>
#include <QtCore/QDebug>
#include <QtCore/QTimer>

#include <QtDBus/QtDBus>

#include <QtTest/QtTest>

#include <tests/lib/test.h>

class TestDoNothing : public Test
{
    Q_OBJECT

public:
    TestDoNothing(QObject *parent = 0)
        : Test(parent)
    { }

private Q_SLOTS:
    void initTestCase();
    void init();

    void doNothing();
    void doNothing2();

    void cleanup();
    void cleanupTestCase();
};

void TestDoNothing::initTestCase()
{
    initTestCaseImpl();
}

void TestDoNothing::init()
{
    initImpl();
}

void TestDoNothing::doNothing()
{
    QTimer::singleShot(0, mLoop, SLOT(quit()));
    QCOMPARE(mLoop->exec(), 0);
}

void TestDoNothing::doNothing2()
{
    QTimer::singleShot(0, mLoop, SLOT(quit()));
    QCOMPARE(mLoop->exec(), 0);
}

void TestDoNothing::cleanup()
{
    cleanupImpl();
}

void TestDoNothing::cleanupTestCase()
{
    cleanupTestCaseImpl();
}

QTEST_MAIN(TestDoNothing)
#include "_gen/do-nothing.cpp.moc.hpp"

Fix build error, forgot to replace a "slots" to "Q_SLOTS"


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

// Calculate Crc by calling CRC method in LZMA SDK

#include "courgette/crc.h"

extern "C" {
#include "third_party/lzma_sdk/7zCrc.h"
}

namespace courgette {

uint32 CalculateCrc(const uint8* buffer, size_t size) {
  CrcGenerateTable();
  uint32 crc = 0xffffffffL;
  crc = ~CrcCalc(buffer, size);
  return crc;
}

}  // namespace

// Copyright (c) 2011 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 "courgette/crc.h"

#ifdef COURGETTE_USE_CRC_LIB
#  include "zlib.h"
#else
extern "C" {
#  include "third_party/lzma_sdk/7zCrc.h"
}
#endif

#include "base/basictypes.h"

namespace courgette {

uint32 CalculateCrc(const uint8* buffer, size_t size) {
  uint32 crc;

#ifdef COURGETTE_USE_CRC_LIB
  // Calculate Crc by calling CRC method in zlib
  crc = crc32(0, buffer, size);
#else
  // Calculate Crc by calling CRC method in LZMA SDK
  CrcGenerateTable();
  crc = CrcCalc(buffer, size);
#endif

  return ~crc;
}

}  // namespace

Use a different define to decide which CRC library to use.


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

#include "a.h"
#include "b2.h"

#pragma clang __debug macro FOO

FOO // xpected-no-diagnostics

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

#include "a.h"
#include "b2.h"

FOO // expected-no-diagnostics

Remove debugging aids from this test and fix its expectations.


/**
 *  @copyright Copyright 2017 The J-PET Framework 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 find a copy of the License in the LICENCE file.
 *
 * 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.
 *
 *  @file main.cpp
 */

#include "JPetManager/JPetManager.h"
#include "ImageReco.h"
#include "SinogramCreator.h"
#include "SinogramCreatorMC.h"
using namespace std;

int main(int argc, const char* argv[])
{
  JPetManager& manager = JPetManager::getManager();

  manager.registerTask<ImageReco>("ImageReco");
  manager.registerTask<SinogramCreator>("SinogramCreator");
  manager.registerTask<SinogramCreator>("SinogramCreatorMC");

  manager.useTask("ImageReco", "unk.evt", "reco");
  manager.useTask("SinogramCreator", "unk.evt", "sino");
  manager.useTask("SinogramCreatorMC", "unk.evt", "sino");

  manager.run(argc, argv);
}

/**
 *  @copyright Copyright 2017 The J-PET Framework 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 find a copy of the License in the LICENCE file.
 *
 * 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.
 *
 *  @file main.cpp
 */

#include "JPetManager/JPetManager.h"
#include "ImageReco.h"
#include "SinogramCreator.h"
#include "SinogramCreatorMC.h"
using namespace std;

int main(int argc, const char* argv[])
{
  JPetManager& manager = JPetManager::getManager();

  manager.registerTask<ImageReco>("ImageReco");
  manager.registerTask<SinogramCreator>("SinogramCreator");
  manager.registerTask<SinogramCreatorMC>("SinogramCreatorMC");

  manager.useTask("ImageReco", "unk.evt", "reco");
  manager.useTask("SinogramCreator", "unk.evt", "sino");
  manager.useTask("SinogramCreatorMC", "unk.evt", "sino.mc");

  manager.run(argc, argv);
}

Fix class name for SinogramCreatorMC


#include <string.h>
#include "tree_sitter/runtime.h"

void test_log(void *payload, TSLogType type, const char *string) { }

TSLogger logger = {
  .log = test_log,
};

extern "C" const TSLanguage *TS_LANG();

extern "C" int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) {
  const char *str = reinterpret_cast<const char *>(data);

  TSDocument *document = ts_document_new();
  ts_document_set_language(document, TS_LANG());
  ts_document_set_input_string_with_length(document, str, size);

  TSParseOptions options = {};
  options.halt_on_error = TS_HALT_ON_ERROR;
  ts_document_parse_with_options(document, options);

  TSNode root_node = ts_document_root_node(document);
  ts_document_free(document);

  return 0;
}

#include <string.h>
#include "tree_sitter/runtime.h"

void test_log(void *payload, TSLogType type, const char *string) { }

TSLogger logger = {
  .log = test_log,
};

extern "C" const TSLanguage *TS_LANG();

extern "C" int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) {
  const char *str = reinterpret_cast<const char *>(data);

  TSParser *parser = ts_parser_new();
  ts_parser_set_language(parser, TS_LANG());
  ts_parser_halt_on_error(parser, TS_HALT_ON_ERROR);

  TSTree *tree = ts_parser_parse_string(parser, NULL, str, size);
  TSNode root_node = ts_document_root_node(tree);

  ts_tree_delete(tree);
  ts_parser_delete(parser);

  return 0;
}

Update fuzz driver to use new API


/*
 * Podrios.cpp
 *
 *  Created on: 2014年10月23日
 *      Author: nemo
 */

#include <iostream>

using namespace std;

int main()
{
	cout << "Show Message." << endl;

	return 0;
}

/*
 * Podrios.cpp
 *
 *  Created on: 2014年10月23日
 *      Author: nemo
 */

#include <iostream>
#include <stdlib.h>

using namespace std;

int main()
{
	cout << "Show Message." << endl;

	system("pause");
	return 0;
}

Add system command for holding command console


// Copyright (c) 2013 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 "ui/base/ui_base_switches_util.h"

#include "base/command_line.h"
#include "ui/base/ui_base_switches.h"

namespace switches {

bool IsTouchDragDropEnabled() {
  return CommandLine::ForCurrentProcess()->HasSwitch(
      switches::kEnableTouchDragDrop);
}

bool IsTouchEditingEnabled() {
  return CommandLine::ForCurrentProcess()->HasSwitch(
      switches::kEnableTouchEditing);
}

bool IsNewDialogStyleEnabled() {
  CommandLine* command_line = CommandLine::ForCurrentProcess();
  if (command_line->HasSwitch(switches::kDisableNewDialogStyle))
    return false;
  if (command_line->HasSwitch(switches::kEnableNewDialogStyle))
    return true;
  return false;
}

}  // namespace switches

// Copyright (c) 2013 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 "ui/base/ui_base_switches_util.h"

#include "base/command_line.h"
#include "ui/base/ui_base_switches.h"

namespace switches {

bool IsTouchDragDropEnabled() {
  return CommandLine::ForCurrentProcess()->HasSwitch(
      switches::kEnableTouchDragDrop);
}

bool IsTouchEditingEnabled() {
  return CommandLine::ForCurrentProcess()->HasSwitch(
      switches::kEnableTouchEditing);
}

bool IsNewDialogStyleEnabled() {
  CommandLine* command_line = CommandLine::ForCurrentProcess();
  if (command_line->HasSwitch(switches::kDisableNewDialogStyle))
    return false;
  if (command_line->HasSwitch(switches::kEnableNewDialogStyle))
    return true;
  return true;
}

}  // namespace switches

Enable the new dialog style by default; etc.


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

using namespace Halide;

int main(int argc, char **argv) {
    Var x, y;
    Var xo, xi, yo, yi;

    Func f, g;

    printf("Defining function...\n");

    f(x, y) = cast<float>(x);
    g(x, y) = f(x+1, y) + f(x-1, y);

    Target target = get_jit_target_from_environment();
    if (target.has_gpu_feature()) {
        Var xi, yi;
        g.gpu_tile(x, y, 8, 8, GPU_DEFAULT);
        f.compute_at(g, Var("blockidx")).gpu_threads(x, y, GPU_DEFAULT);
    }

    printf("Realizing function...\n");

    Image<float> im = g.realize(32, 32, target);

    for (int i = 0; i < 32; i++) {
        for (int j = 0; j < 32; j++) {
            if (im(i,j) != 2*i) {
                printf("im[%d, %d] = %f\n", i, j, im(i,j));
                return -1;
            }
        }
    }

    printf("Success!\n");
    return 0;
}

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

using namespace Halide;

int main(int argc, char **argv) {
    Var x, y;
    Var xo, xi, yo, yi;

    Func f, g;

    printf("Defining function...\n");

    f(x, y) = cast<float>(x);
    g(x, y) = f(x+1, y) + f(x-1, y);

    Target target = get_jit_target_from_environment();
    // shared memory not currently working in OpenCL
    if (target.features & Target::CUDA) {
        Var xi, yi;
        g.gpu_tile(x, y, 8, 8, GPU_CUDA);
        f.compute_at(g, Var("blockidx")).gpu_threads(x, y, GPU_CUDA);
    }

    printf("Realizing function...\n");

    Image<float> im = g.realize(32, 32, target);

    for (int i = 0; i < 32; i++) {
        for (int j = 0; j < 32; j++) {
            if (im(i,j) != 2*i) {
                printf("im[%d, %d] = %f\n", i, j, im(i,j));
                return -1;
            }
        }
    }

    printf("Success!\n");
    return 0;
}

Disable shared memory test for OpenCL until bugginess is resolved.


#include "Precompiled.hpp"
#include "Error.hpp"
#include "SmartPtr.hpp"
#include "String.hpp"

std::string errno_string(int err)
{
    char buffer[1024];
    if (!strerror_s(buffer, sizeof(buffer), err)) throw std::runtime_error("strerror_s failed");
    return buffer;
}

#ifdef _WIN32

std::string win_error_string(int err)
{
    std::unique_ptr<wchar_t[], LocalFreeDeleter> buffer;
    FormatMessageW(
        FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
        nullptr, err, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
        (LPWSTR)(wchar_t**)unique_out_ptr(buffer), 0, nullptr);
    return utf16_to_utf8(buffer.get());
}

#endif

#include "Precompiled.hpp"
#include "Error.hpp"
#include "SmartPtr.hpp"
#include "String.hpp"

std::string errno_string(int err)
{
    char buffer[1024];
#ifdef _WIN32
    if (!strerror_s(buffer, sizeof(buffer), err)) throw std::runtime_error("strerror_s failed");
    return buffer;
#else
    return strerror_r(err, buffer, sizeof(buffer));
#endif
}

#ifdef _WIN32

std::string win_error_string(int err)
{
    std::unique_ptr<wchar_t[], LocalFreeDeleter> buffer;
    FormatMessageW(
        FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
        nullptr, err, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
        (LPWSTR)(wchar_t**)unique_out_ptr(buffer), 0, nullptr);
    return utf16_to_utf8(buffer.get());
}

#endif

Use strerror_r instead of strerror_s for GCC/Linux


#include "properties.h"

#include <QHeaderView>

Properties::Properties(QWidget* parent) : QTreeWidget(parent) {
	setRootIsDecorated(false);

	headerItem()->setText(0, "item");
	headerItem()->setText(1, "value");
	headerItem()->setFirstColumnSpanned(false);
	header()->setStretchLastSection(true);
}

void Properties::show(const std::vector<std::reference_wrapper<dependency_graph::Node>>& selection) {
	clear();

	for(auto& node : selection) {
		// create a top level item for each node
		QTreeWidgetItem* nodeItem = new QTreeWidgetItem();
		nodeItem->setText(0, node.get().name().c_str());

		addTopLevelItem(nodeItem);
	}
}

#include "properties.h"

#include <QHeaderView>

Properties::Properties(QWidget* parent) : QTreeWidget(parent) {
	setRootIsDecorated(false);

	headerItem()->setText(0, "item");
	headerItem()->setText(1, "value");
	headerItem()->setFirstColumnSpanned(false);
	header()->setStretchLastSection(true);
}

void Properties::show(const std::vector<std::reference_wrapper<dependency_graph::Node>>& selection) {
	clear();

	for(const auto& node : selection) {
		// create a top level item for each node
		QTreeWidgetItem* nodeItem = new QTreeWidgetItem();
		nodeItem->setText(0, node.get().name().c_str());

		addTopLevelItem(nodeItem);

		// add each port as a subitem
		for(unsigned pi = 0; pi != node.get().portCount(); ++pi) {
			const auto& port = node.get().port(pi);

			QTreeWidgetItem* portItem = new QTreeWidgetItem();
			portItem->setText(0, port.name().c_str());

			nodeItem->addChild(portItem);
		}
	}

	expandAll();
}

Add an item per port of each selected node


#include <openssl/eng_ossl.h>

/**
* Look for an OpenSSL-suported stream cipher (ARC4)
*/
StreamCipher*
OpenSSL_Engine::find_stream_cipher(const std::string& algo_spec) const
   {
   SCAN_Name request(algo_spec);

   if(request.algo_name() == "ARC4")
      return new ARC4_OpenSSL(request.argument_as_u32bit(0, 0));
   if(request.algo_name() == "RC4_drop")
      return new ARC4_OpenSSL(768);

   return 0;
   }

/**
OpenSSL Engine
(C) 2008 Jack Lloyd
*/

#include <botan/eng_ossl.h>

namespace Botan {

/**
* Look for an OpenSSL-suported stream cipher (ARC4)
*/
StreamCipher*
OpenSSL_Engine::find_stream_cipher(const std::string& algo_spec) const
   {
   SCAN_Name request(algo_spec);

   if(request.algo_name() == "ARC4")
      return new ARC4_OpenSSL(request.argument_as_u32bit(0, 0));
   if(request.algo_name() == "RC4_drop")
      return new ARC4_OpenSSL(768);

   return 0;
   }

}

Fix include, add namespace and copyright


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

namespace A {
int i;
}

// CHECK: [[FILE:![0-9]*]] = {{.*}} ; [ DW_TAG_file_type ] [{{.*}}/test/CodeGenCXX/debug-info-namespace.cpp]
// CHECK: [[VAR:![0-9]*]] = {{.*}}, metadata [[NS:![0-9]*]], metadata !"i", {{.*}} ; [ DW_TAG_variable ] [i]
// CHECK: [[NS]] = {{.*}}, metadata [[FILE]], {{.*}} ; [ DW_TAG_namespace ] [A] [line 3]

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

namespace A {
#line 1 "foo.cpp"
namespace B {
int i;
}
}

// CHECK: [[FILE:![0-9]*]] = {{.*}} ; [ DW_TAG_file_type ] [{{.*}}/test/CodeGenCXX/debug-info-namespace.cpp]
// CHECK: [[VAR:![0-9]*]] = {{.*}}, metadata [[NS:![0-9]*]], metadata !"i", {{.*}} ; [ DW_TAG_variable ] [i]
// CHECK: [[NS]] = {{.*}}, metadata [[FILE2:![0-9]*]], metadata [[CTXT:![0-9]*]], {{.*}} ; [ DW_TAG_namespace ] [B] [line 1]
// CHECK: [[FILE2:![0-9]*]] = {{.*}} ; [ DW_TAG_file_type ] [{{.*}}foo.cpp]
// CHECK: [[CTXT]] = {{.*}}, metadata [[FILE]], null, {{.*}} ; [ DW_TAG_namespace ] [A] [line 3]

Enhance debug info namespace test to check for context/scope reference


#include <ctime>

class util {
public:
    int static GetTimestamp() {
        return std::time(0);
    }

    void static OpenUrl(String url) {
        system("open " + url);
    }
};

#include <ctime>

class util {
public:
    int static GetTimestamp() {
        return std::time(0);
    }

    void static OpenUrl(const String url) {
        String cmd("open ");
        cmd += url;
        system(cmd.ToCString<char>());
    }
};

Fix the native part of Util.OpenUrl


#include "main.h"
#include "EventHandler.h"
#include "PythonModule.h"

extern "C" EXPORT unsigned int VcmpPluginInit(PluginFuncs* pluginFunctions, PluginCallbacks* pluginCallbacks, PluginInfo* pluginInfo)
{
	pluginInfo->pluginVersion = 0x103;
	pluginInfo->apiMajorVersion = PLUGIN_API_MAJOR;
	pluginInfo->apiMinorVersion = PLUGIN_API_MINOR;
	strcpy(pluginInfo->name, "vcmp-python-plugin");

	vcmpFunctions = pluginFunctions;
	if (pluginFunctions->structSize == sizeof(PluginFuncsNew))
		haveNewFunctions = true;
	vcmpCallbacks = pluginCallbacks;
	if (pluginCallbacks->structSize == sizeof(PluginCallbacksNew))
		haveNewCallbacks = true;
	RegisterCallbacks(pluginCallbacks);

	py::initialize_interpreter();

	return 1;
}

#include "main.h"
#include "EventHandler.h"
#include "PythonModule.h"

extern "C" EXPORT uint32_t VcmpPluginInit(PluginFuncs* pluginFunctions, PluginCallbacks* pluginCallbacks, PluginInfo* pluginInfo)
{
	pluginInfo->pluginVersion = 0x103;
	pluginInfo->apiMajorVersion = PLUGIN_API_MAJOR;
	pluginInfo->apiMinorVersion = PLUGIN_API_MINOR;
	strcpy(pluginInfo->name, "vcmp-python-plugin");

	vcmpFunctions = pluginFunctions;
	if (pluginFunctions->structSize == sizeof(PluginFuncsNew))
		haveNewFunctions = true;
	vcmpCallbacks = pluginCallbacks;
	if (pluginCallbacks->structSize == sizeof(PluginCallbacksNew))
		haveNewCallbacks = true;
	RegisterCallbacks(pluginCallbacks);

	py::initialize_interpreter();

	return 1;
}

Use uint32_t as return type.


#include "task_simple.h"
#include "factory_simple.h"
#include "on_tick_simple.h"

#include <fstream>

using namespace std;

int main(int argc, char *argv[])
{
    const string task_fname = "task_list.txt";
    const size_t concurrency = 2;

    ifstream task_stream{task_fname};
    TaskListSimple task_list{task_stream, "./"};
    JobList job_list;

    auto loop = AIO_UVW::Loop::getDefault();
    auto factory = make_shared<FactorySimple>(loop);
    auto on_tick = make_shared< OnTickSimple<JobList> >(job_list, factory, task_list);
    factory->set_OnTick(on_tick);

    for (size_t i = 1; i <= concurrency; i++)
    {
        auto task = task_list.get();
        if (!task)
            break;

        auto downloader = factory->create(*task);
        if (!downloader)
            continue;

        job_list.emplace_back(task, downloader);
    }

    loop->run();

    return 0;
}

#include "task_simple.h"
#include "factory_simple.h"
#include "on_tick_simple.h"

#include <fstream>
#include <iostream>

using namespace std;

int main(int argc, char *argv[])
{
    const string task_fname = "task_list.txt";
    const size_t concurrency = 2;

    ifstream task_stream{task_fname};
    if ( !task_stream.is_open() )
    {
        cout << "Can`t open <" << task_fname << ">, break." << endl;
        return 1;
    }
    TaskListSimple task_list{task_stream, "./"};
    JobList job_list;

    auto loop = AIO_UVW::Loop::getDefault();
    auto factory = make_shared<FactorySimple>(loop);
    auto on_tick = make_shared< OnTickSimple<JobList> >(job_list, factory, task_list);
    factory->set_OnTick(on_tick);

    for (size_t i = 1; i <= concurrency; i++)
    {
        auto task = task_list.get();
        if (!task)
            break;

        auto downloader = factory->create(*task);
        if (!downloader)
            continue;

        job_list.emplace_back(task, downloader);
    }

    loop->run();

    return 0;
}

Break if task file don`t exists


//
// main.cpp
//
//  Created on: 17 Mar 2015
//      Author: Guotai Wang
//
// Copyright (c) 2014-2016 University College London, United Kingdom. All rights reserved.
// http://cmictig.cs.ucl.ac.uk
//
// Distributed under the BSD-3 licence. Please see the file licence.txt
//

#include <fstream>
#include <iostream>
#include "Test/RFTestExample.h"

int main(int argc, char ** argv)
{
    srand (time(NULL));
    RFTestExample testExample;
    if(testExample.LoadData(BIODEG)) //DataSetName: BIODEG, MUSK, CTG, WINE
    {
        testExample.SetTrainDataChunk(0.5,1.0, 0.05);
        testExample.Run(100);
        testExample.PrintPerformance();
    }
    return 0;
}

//
// main.cpp
//
//  Created on: 17 Mar 2015
//      Author: Guotai Wang
//
// Copyright (c) 2014-2016 University College London, United Kingdom. All rights reserved.
// http://cmictig.cs.ucl.ac.uk
//
// Distributed under the BSD-3 licence. Please see the file licence.txt
//

#include <fstream>
#include <iostream>
#include "Test/RFTestExample.h"

int main(int argc, char ** argv)
{
    srand (time(NULL));
    RFTestExample testExample;
    if(testExample.LoadData(BIODEG)) //DataSetName: BIODEG, MUSK, CTG, WINE
    {
        testExample.SetTrainDataChunk(0.5,1.0, 0.05);
        testExample.Run(100);
        testExample.PrintPerformance();
    }
    return EXIT_SUCCESS;
}

Change return value to EXIT_SUCCESS


//----------------------------  job_identifier.cc  ---------------------------
//    $Id$
//    Version: $Name$
//
//    Copyright (C) 1998, 1999, 2000, 2001, 2002 by the deal authors
//
//    This file is subject to QPL and may not be  distributed
//    without copyright and license information. Please refer
//    to the file deal.II/doc/license.html for the  text  and
//    further information on this license.
//
//----------------------------  job_identifier.cc  ---------------------------

#include <base/job_identifier.h>
#include <ctime>
#include <sys/time.h>

#if HAVE_GETHOSTNAME
# include <unistd.h>
#endif

JobIdentifier dealjobid;

JobIdentifier::JobIdentifier()
{
  time_t t = std::time(0);
  id = std::string(program_id());

//TODO:[GK] try to avoid this hack
// It should be possible not to check DEBUG, but there is this
// tedious -ansi, which causes problems with linux headers

#if (HAVE_GETHOSTNAME && (!DEBUG))
  char name[100];
  gethostname(name,99);
  id += std::string(name) + std::string(" ");
#endif

  id += std::string(std::ctime(&t));
}

const std::string
JobIdentifier::operator ()() const
{
  return id;
}

//----------------------------  job_identifier.cc  ---------------------------
//    $Id$
//    Version: $Name$
//
//    Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003 by the deal authors
//
//    This file is subject to QPL and may not be  distributed
//    without copyright and license information. Please refer
//    to the file deal.II/doc/license.html for the  text  and
//    further information on this license.
//
//----------------------------  job_identifier.cc  ---------------------------

#include <base/job_identifier.h>
#include <ctime>
#include <sys/time.h>

#if HAVE_GETHOSTNAME
# include <unistd.h>
#endif

JobIdentifier dealjobid;

JobIdentifier::JobIdentifier()
{
  time_t t = std::time(0);
  id = std::string(program_id());

//TODO:[GK] try to avoid this hack
// It should be possible not to check DEBUG, but there is this
// tedious -ansi, which causes problems with linux headers

#if defined(HAVE_GETHOSTNAME) && !defined(DEBUG)
  char name[100];
  gethostname(name,99);
  id += std::string(name) + std::string(" ");
#endif

  id += std::string(std::ctime(&t));
}

const std::string
JobIdentifier::operator ()() const
{
  return id;
}

Use preprocessor 'defined' instead of relying on the preprocessor doing this automatically.


/*
  Copyright:    © 2018 SIL International.
  Description:  Internal keyboard class and adaptor class for the API.
  Create Date:  2 Oct 2018
  Authors:      Tim Eves (TSE)
  History:      7 Oct 2018 - TSE - Refactored out of km_kbp_keyboard_api.cpp
*/

#include "keyboard.hpp"
#include "json.hpp"

using namespace km::kbp;

keyboard::keyboard(std::filesystem::path const & path)
: _keyboard_id(path.stem().string()),
  _version_string("3.145"),
  _folder_path(path.parent_path()),
  _default_opts {KM_KBP_OPTIONS_END}
{
  version_string = _version_string.c_str();
  id = _keyboard_id.c_str();
  folder_path = _folder_path.native().c_str();
  default_options = _default_opts.data();
}

json & km::kbp::operator << (json & j, km::kbp::keyboard const & kb)
{
  j << json::object
      << "id" << kb.id
      << "folder" << kb.folder_path
      << "version" << kb.version_string
      << "rules" << json::array << json::close;

  return j << json::close;
}

/*
  Copyright:    © 2018 SIL International.
  Description:  Internal keyboard class and adaptor class for the API.
  Create Date:  2 Oct 2018
  Authors:      Tim Eves (TSE)
  History:      7 Oct 2018 - TSE - Refactored out of km_kbp_keyboard_api.cpp
*/

#include "keyboard.hpp"
#include "json.hpp"

using namespace km::kbp;

keyboard::keyboard(std::filesystem::path const & path)
: _keyboard_id(path.stem().string()),
  _version_string("3.145"),
  _folder_path(path.parent_path()),
  _default_opts {KM_KBP_OPTIONS_END}
{
  version_string = _version_string.c_str();
  id = _keyboard_id.c_str();
  folder_path = _folder_path.native().c_str();
  default_options = _default_opts.data();
}

json & km::kbp::operator << (json & j, km::kbp::keyboard const & kb)
{
  j << json::object
      << "id" << kb.id
      << "folder" <<  kb._folder_path.string()
      << "version" << kb.version_string
      << "rules" << json::array << json::close;

  return j << json::close;
}

Make sure to convert path to utf8 for json output of folder name.


#include <iostream>
#include <boost/log/common.hpp>
#include <boost/log/expressions.hpp>
#include <boost/log/utility/setup/file.hpp>
#include <boost/log/trivial.hpp>

#ifdef HAVE_CONFIG_H
#include "config.h"
#endif

namespace expr = boost::log::expressions;
namespace keywords = boost::log::keywords;

int
main(int argc, char *argv[])
{
  try {
    boost::log::add_file_log(
      keywords::file_name = LOGDIR "/agent.log",
      keywords::format = ( expr::stream << "<"
                                        << boost::log::trivial::severity
                                        << ">\t"
                                        << expr::smessage
			   ),
      keywords::auto_flush = true
    );
    BOOST_LOG_TRIVIAL(info) << "Agent - HelloWorld";
#ifdef HAVE_CONFIG_H
    BOOST_LOG_TRIVIAL(info) << "Version: " << VERSION;
#endif
  } catch (std::exception &ex) {
    std::cerr << ex.what() << '\n';
    BOOST_LOG_TRIVIAL(fatal) << ex.what();
    return 1;
  }

  return 0;
}

#include <iostream>
#include <boost/date_time/posix_time/posix_time_types.hpp>
#include <boost/log/common.hpp>
#include <boost/log/expressions.hpp>
#include <boost/log/utility/setup/file.hpp>
#include <boost/log/trivial.hpp>
#include <boost/log/support/date_time.hpp>
#include <boost/log/utility/setup/common_attributes.hpp>

#ifdef HAVE_CONFIG_H
#include "config.h"
#endif

namespace expr = boost::log::expressions;
namespace keywords = boost::log::keywords;

int
main(int argc, char *argv[])
{
  try {
    boost::log::add_common_attributes();

    boost::log::add_file_log(
      keywords::file_name = LOGDIR "/agent.log",
      keywords::format = ( expr::stream << expr::format_date_time< boost::posix_time::ptime >("TimeStamp", "%d.%m.%Y %H:%M:%S")
                                        << ": <"
                                        << boost::log::trivial::severity
                                        << ">\t"
                                        << expr::smessage
			   ),
      keywords::auto_flush = true
    );
    BOOST_LOG_TRIVIAL(info) << "Agent - HelloWorld";
#ifdef HAVE_CONFIG_H
    BOOST_LOG_TRIVIAL(info) << "Version: " << VERSION;
#endif

  } catch (std::exception &ex) {
    std::cerr << ex.what() << '\n';
    BOOST_LOG_TRIVIAL(fatal) << ex.what();
    return 1;
  }

  return 0;
}

Add timestamp field to agent logs


/*----------------------------------------*/
// Test receiving messages from master
//
// This receives a message from master (command 0x01),
// which tells it to turn an LED on or off.
//
/*----------------------------------------*/

#include <stdint.h>

#include "MultidropSlave.h"
#include "MultidropDataUart.h"

#define NODE_COUNT 5

int main() {
  uint8_t ledOn = 0;

  // LED on PB0
  DDRB |= (1 << PB0);
  PORTB &= ~(1 << PB0);

  MultidropDataUart serial;
  serial.begin(9600);

  MultidropSlave slave(&serial);
  slave.setAddress(1);

  while(1) {
    slave.read();
    if (slave.isReady() && slave.isAddressedToMe() && slave.getCommand() == 0x01) {
      ledOn = slave.getData()[0];

      if (ledOn) {
        PORTB |= (1 << PB0);
      } else {
        PORTB &= ~(1 << PB0);
      }
      slave.reset();
    }
  }
}

/*----------------------------------------*/
// Test receiving messages from master
//
// This receives a message from master (command 0x01),
// which tells it to turn an LED on or off.
//
/*----------------------------------------*/

#include <stdint.h>

#include "MultidropSlave.h"
#include "MultidropDataUart.h"

#define NODE_ADDRESS 1

int main() {
  uint8_t ledOn = 0;

  // LED on PB0
  DDRB |= (1 << PB0);
  PORTB &= ~(1 << PB0);

  MultidropDataUart serial;
  serial.begin(9600);

  MultidropSlave slave(&serial);
  slave.setAddress(NODE_ADDRESS);

  while(1) {
    slave.read();
    if (slave.isReady() && slave.isAddressedToMe() && slave.getCommand() == 0x01) {
      ledOn = slave.getData()[0];

      if (ledOn) {
        PORTB |= (1 << PB0);
      } else {
        PORTB &= ~(1 << PB0);
      }
      slave.reset();
    }
  }
}

Add NODE_ADDRESS value to slave_node program


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

#include "WatermarkDataFactory.h"

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

            }

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

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

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

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

#include "WatermarkDataFactory.h"

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

            }

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

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

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

Fix for generation of QR code when google analytics referrer token is unset. Buddy: Jonty


#include <iostream>
using std::cout;
using std::endl;

#include "problems/Factory.h"
#include "util/Timer.h"
using util::Timer;

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

  auto problem = problems::Factory::create(1);

  Timer t;

  t.start();
  for (int i = 0; i < 1000000; ++i)
    problem->solve();
  t.stop();

  cout << problem->answer() << endl;
  cout << "Time elapsed: " << t << endl;

  return 0;
}

#include <iostream>
using std::cout;
using std::endl;

#include "problems/Factory.h"
#include "util/Timer.h"
using util::Timer;

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

  auto problem = problems::Factory::create(1);

  Timer t;

  t.start();
  problem->solve();
  t.stop();

  cout << problem->answer() << endl;
  cout << "Time elapsed: " << t << endl;

  return 0;
}

Make apps/pe only run a problem once


#include <iostream>

#include "cons.h"
#include "error.h"
#include "eval.h"
#include "init.h"
#include "load.h"
#include "reader.h"
#include "utils.h"

namespace
{

class Repl
{
  std::istream& in_;
  std::ostream& out_;
  std::string prompt_ = "mclisp> ";
  mclisp::Reader reader_;

  public:
    explicit Repl(std::istream& in=std::cin, std::ostream& out=std::cout):
      in_(in), out_(out), reader_(in_) {};

    int loop();
};

int Repl::loop()
{
  while (true)
  {
    out_ << prompt_;
    try
    {
      mclisp::ConsCell *exp = reader_.Read();

      if (mclisp::ShouldQuit(exp))
        break;

      mclisp::ConsCell *value = Eval(exp);
      out_ << *value << std::endl;
    }
    catch (mclisp::Error& e)
    {
      out_ << e.what() << std::endl;
    }
  }
  return 0;
}

} //end namespace

int main()
{
  // InitLisp must be called before the Reader object is initialized.
  mclisp::InitLisp();
  mclisp::LoadFile("mclisp.lisp");

  Repl repl;
  return repl.loop();
}

#include <iostream>

#include "cons.h"
#include "error.h"
#include "eval.h"
#include "init.h"
#include "load.h"
#include "reader.h"
#include "utils.h"

namespace
{

class Repl
{
  std::istream& in_;
  std::ostream& out_;
  std::string prompt_ = "mclisp> ";
  mclisp::Reader reader_;

  public:
    explicit Repl(std::istream& in=std::cin, std::ostream& out=std::cerr):
      in_(in), out_(out), reader_(in_) {};

    int loop();
};

int Repl::loop()
{
  while (true)
  {
    out_ << prompt_;
    try
    {
      mclisp::ConsCell *exp = reader_.Read();

      if (mclisp::ShouldQuit(exp))
        break;

      mclisp::ConsCell *value = Eval(exp);
      out_ << *value << std::endl;
    }
    catch (mclisp::Error& e)
    {
      out_ << e.what() << std::endl;
    }
  }
  return 0;
}

} //end namespace

int main()
{
  // InitLisp must be called before the Reader object is initialized.
  mclisp::InitLisp();
  mclisp::LoadFile("mclisp.lisp");

  Repl repl;
  return repl.loop();
}

Print REPL output on std::cerr instead of cout.


#include "RequestParser.h"
#include <sstream>
#include <vector>

std::vector<std::string> ApiMock::RequestParser::projectToCollection(std::string const& request) {
	std::vector<std::string> fromRequest;
	std::string::size_type pos = 0;
	std::string::size_type prev = 0;

	while ((pos = request.find('\n', prev)) != std::string::npos) {
		fromRequest.push_back(request.substr(prev, pos - prev));
		prev = pos + 1;
	}

	fromRequest.push_back(request.substr(prev));
	return fromRequest;
}

ApiMock::RequestData ApiMock::RequestParser::parse(std::string const& requestBuffer) {
	std::vector<std::string> entireRequest = projectToCollection(requestBuffer);
	RequestData request;

	return request;
}

#include "RequestParser.h"
#include <sstream>
#include <vector>

std::vector<std::string> ApiMock::RequestParser::projectToCollection(std::string const& request) {
	const std::string CRLF = "\r\n";
	std::vector<std::string> fromRequest;
	std::string::size_type pos = 0;
	std::string::size_type prev = 0;

	while ((pos = request.find(CRLF, prev)) != std::string::npos) {
		fromRequest.push_back(request.substr(prev, pos - prev));
		prev = pos + 1;
	}

	fromRequest.push_back(request.substr(prev));
	return fromRequest;
}

ApiMock::RequestData ApiMock::RequestParser::parse(std::string const& requestBuffer) {
	std::vector<std::string> entireRequest = projectToCollection(requestBuffer);
	RequestData request;

	return request;
}

Use CRLF in requests instead of just LF


#include <iostream>

#include "rapidcheck/detail/NonRandomData.h"

namespace rc {
RandomData::RandomData(const uint8_t *Data, size_t Size) {
  std::cout << Data << std::endl;
  // TODO: really stupid way to fill the container
  const size_t size64 = Size / 8;
  auto Data64 = reinterpret_cast<const uint64_t *>(Data);
  for (size_t i = 0; i < size64; i++) {
    m_data.push(Data64[i]);
  }
}
} // namespace rc

#include <iostream>

#include "rapidcheck/detail/NonRandomData.h"

namespace rc {
RandomData::RandomData(const uint8_t *Data, size_t Size) {
  // TODO: really stupid way to fill the container
  const size_t size64 = Size / 8;
  auto Data64 = reinterpret_cast<const uint64_t *>(Data);
  for (size_t i = 0; i < size64; i++) {
    m_data.push(Data64[i]);
  }
}
} // namespace rc

Address Sanitation for the win: found memory bug.


#include <iostream>

using namespace std;

int main()
{
    cout << "Hello World!" << endl;
    return 0;
}

#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <iostream>

using namespace cv;
using namespace std;

int main(int argc, char** argv) {
    VideoCapture cap(0);

    namedWindow("MyVideo", CV_WINDOW_AUTOSIZE);

    int w = cap.get(CV_CAP_PROP_FRAME_WIDTH);
    int h = cap.get(CV_CAP_PROP_FRAME_HEIGHT);

    //cap.set(CV_CAP_PROP_SETTINGS, 1);

    // 24 x 19

    while (true) {
        Mat frame, frame2;
        cap.read(frame);

        Point2f src[] = {Point2f(140, 0), Point2f(520, 0), Point2f(73, 479), Point2f(586, 479)};
        Point2f dst[] = {Point2f(0, 0), Point2f(640, 0), Point2f(0, 480), Point2f(640, 480)};
        Mat m = getPerspectiveTransform(src, dst);

        warpPerspective(frame, frame2, m, cv::Size(w, h));
        resize(frame2, frame, cv::Size(21 * 30, 24 * 30));

        //cvtColor(frame, frame2, CV_BGR2GRAY);
        Mat frameParts[3];
        split(frame, frameParts);

        inRange(frameParts[1], cv::Scalar(60), cv::Scalar(255), frame);
        inRange(frameParts[0], cv::Scalar(60), cv::Scalar(255), frame2);

        Mat result = frame & ~frame2;
        Mat result2;

        auto kernel = getStructuringElement(MORPH_RECT, cv::Size(3, 3));
        erode(result, result2, kernel);

        auto kernel2 = getStructuringElement(MORPH_RECT, cv::Size(9, 9));
        dilate(result2, result, kernel2);

        imshow("MyVideo", result);

        if (waitKey(10) == 27) {
            break;
        }
    }

    return 0;
}

Add basic thresholding of green markers


#include "board.h"
#include <aery32/gpio.h>
#include <aery32/delay.h>
#include <aery32/intc.h>

using namespace aery;

void isrhandler_group2(void)
{
	gpio_toggle_pin(LED);
	delay_ms(100); /* Reduce glitch */
	porta->ifrc = (1 << 0); /* Remember to clear the interrupt */
}

int main(void)
{
	init_board();

	/* GPIO pins 0-13 can be "wired" to int group 2, see datasheet p. 42 */
	gpio_init_pin(AVR32_PIN_PA00, GPIO_INPUT|GPIO_PULLUP|GPIO_INT_PIN_CHANGE);

	/* Init interrupt controller */
	intc_init();
	intc_register_isrhandler(
		&isrhandler_group2, /* Function pointer to the ISR handler */
		2, /* Interrupt group number */
		0  /* Priority level */
	);

	/* Enable interrupts globally */
	intc_enable_globally();

	for(;;) {
		/*
		 * Now try to connect PA00 to GND and then disconnecting it
		 * to let pull-up to set the pin state high again. The LED
		 * should toggle between the pin change.
		 */

	}

	return 0;
}

#include "board.h"
#include <aery32/gpio.h>
#include <aery32/delay.h>
#include <aery32/intc.h>

using namespace aery;

void isrhandler_group2(void)
{
	gpio_toggle_pin(LED);
	delay_ms(100); /* Reduce glitches */
	porta->ifrc = (1 << 0); /* Remember to clear the interrupt */
}

int main(void)
{
	init_board();

	/* GPIO pins 0-13 can be "wired" to int group 2, see datasheet p. 42 */
	gpio_init_pin(AVR32_PIN_PA00, GPIO_INPUT|GPIO_PULLUP|GPIO_INT_PIN_CHANGE);

	/* Init interrupt controller */
	intc_init();
	intc_register_isrhandler(
		&isrhandler_group2, /* Function pointer to the ISR handler */
		2, /* Interrupt group number */
		0  /* Priority level */
	);

	/* Enable interrupts globally */
	intc_enable_globally();

	for(;;) {
		/*
		 * Now try to connect PA00 to GND and then disconnecting it
		 * to let the pull-up to set the pin state high again. The LED
		 * should toggle on the pin change.
		 */

	}

	return 0;
}

Improve comments in the external interrupt pin change example


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

#include <Rosetta/Tasks/SimpleTasks/ControlTask.hpp>
#include <Rosetta/Tasks/SimpleTasks/IncludeTask.hpp>

namespace RosettaStone::SimpleTasks
{
ControlTask::ControlTask(EntityType entityType) : ITask(entityType)
{
    // Do nothing
}

TaskID ControlTask::GetTaskID() const
{
    return TaskID::CONTROL;
}

TaskStatus ControlTask::Impl(Player& player)
{
    auto entities =
        IncludeTask::GetEntities(m_entityType, player, m_source, m_target);
    auto& myField = player.GetField();
    auto& opField = player.opponent->GetField();

    for (auto& entity : entities)
    {
        const auto minion = dynamic_cast<Minion*>(entity);
        if (minion == nullptr)
        {
            continue;
        }

        if (myField.IsFull())
        {
            entity->Destroy();
            continue;
        }

        const auto minionClone = new Minion(*minion);
        myField.AddMinion(*minionClone);
        opField.RemoveMinion(*minion);
    }

    return TaskStatus::COMPLETE;
}
}  // namespace RosettaStone::SimpleTasks

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

#include <Rosetta/Tasks/SimpleTasks/ControlTask.hpp>
#include <Rosetta/Tasks/SimpleTasks/IncludeTask.hpp>

namespace RosettaStone::SimpleTasks
{
ControlTask::ControlTask(EntityType entityType) : ITask(entityType)
{
    // Do nothing
}

TaskID ControlTask::GetTaskID() const
{
    return TaskID::CONTROL;
}

TaskStatus ControlTask::Impl(Player& player)
{
    auto entities =
        IncludeTask::GetEntities(m_entityType, player, m_source, m_target);
    auto& myField = player.GetField();
    auto& opField = player.opponent->GetField();

    for (auto& entity : entities)
    {
        const auto minion = dynamic_cast<Minion*>(entity);
        if (minion == nullptr)
        {
            continue;
        }

        if (myField.IsFull())
        {
            entity->Destroy();
            continue;
        }

        const auto minionClone = new Minion(*minion);
        minionClone->owner = &player;

        myField.AddMinion(*minionClone);
        opField.RemoveMinion(*minion);
    }

    return TaskStatus::COMPLETE;
}
}  // namespace RosettaStone::SimpleTasks

Add missing code that assigns new owner


#include "Boot.hpp"

using namespace HomieInternals;

Boot::Boot(const char* name)
: _name(name) {
}

void Boot::setup() {
  if (Interface::get().led.enabled) {
    pinMode(Interface::get().led.pin, OUTPUT);
    digitalWrite(Interface::get().led.pin, !Interface::get().led.on);
  }

  WiFi.persistent(true);  // Persist data on SDK as it seems Wi-Fi connection is faster

  Interface::get().getLogger() << F("🔌 Booting into ") << _name << F(" mode 🔌") << endl;
}

void Boot::loop() {
}

#include "Boot.hpp"

using namespace HomieInternals;

Boot::Boot(const char* name)
: _name(name) {
}

void Boot::setup() {
  if (Interface::get().led.enabled) {
    pinMode(Interface::get().led.pin, OUTPUT);
    digitalWrite(Interface::get().led.pin, !Interface::get().led.on);
  }

  WiFi.persistent(true);  // Persist data on SDK as it seems Wi-Fi connection is faster

  Interface::get().getLogger() << F("💡 Firmware ") << Interface::get().firmware.name << F(" (") << Interface::get().firmware.version << F(")") << endl;
  Interface::get().getLogger() << F("🔌 Booting into ") << _name << F(" mode 🔌") << endl;
}

void Boot::loop() {
}

Print firmware name and version at boot


/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    TreeNode* sortedArrayToBST(vector<int>& nums) {
        if(nums.size()==0) return NULL;
        return insertnode(0,nums.size(),nums);
    }
private:
    TreeNode* insertnode(int f,int r,vector<int>& nums){
        cout<<f<<" "<<r<<endl;
        if(f==r && f!=0) return NULL;
        if(f==nums.size()) return NULL;
        if(f==r || f==r-1){
            TreeNode* now=new TreeNode(nums[f]);
            return now;
        }
        TreeNode* now=new TreeNode(nums[(f+r)/2]);
        now->left=insertnode(f,(f+r)/2,nums);
        now->right=insertnode((f+r)/2+1,r,nums);
        return now;
    }
};

Convert Sorted Array to Binary Search Tree


#include "util.h"

#include <sstream>
#include <vector>

Header cpr::util::parseHeader(std::string headers) {
    Header header;
    std::vector<std::string> lines;
    std::istringstream stream(headers);
    {
        std::string line;
        while (std::getline(stream, line, '\n')) {
            lines.push_back(line);
        }
    }

    for (auto line = lines.begin(); line != lines.end(); ++line) {
        if (line->substr(0, 5) == "HTTP/") {
            header.clear();
        }

        if (line->length() > 0) {
            auto found = line->find(":");
            if (found != std::string::npos) {
                auto value = line->substr(found + 2, line->length() - 1);
                if (value.back() == '\r') {
                    value = value.substr(0, value.length() - 1);
                }
                header[line->substr(0, found)] = value;
            }
        }
    }

    return header;
}

std::string cpr::util::parseResponse(std::string response) {
    if (!response.empty()) {
        if (response.back() == '\n') {
            return response.substr(0, response.length() - 1);
        }
    }

    return response;
}

size_t cpr::util::writeFunction(void *ptr, size_t size, size_t nmemb, std::string* data) {
    data->append((char*) ptr, size * nmemb);
    return size * nmemb;
}

#include "util.h"

#include <sstream>
#include <vector>

Header cpr::util::parseHeader(std::string headers) {
    Header header;
    std::vector<std::string> lines;
    std::istringstream stream(headers);
    {
        std::string line;
        while (std::getline(stream, line, '\n')) {
            lines.push_back(line);
        }
    }

    for (auto& line : lines) {
        if (line.substr(0, 5) == "HTTP/") {
            header.clear();
        }

        if (line.length() > 0) {
            auto found = line.find(":");
            if (found != std::string::npos) {
                auto value = line.substr(found + 2, line.length() - 1);
                if (value.back() == '\r') {
                    value = value.substr(0, value.length() - 1);
                }
                header[line.substr(0, found)] = value;
            }
        }
    }

    return header;
}

std::string cpr::util::parseResponse(std::string response) {
    if (!response.empty()) {
        if (response.back() == '\n') {
            return response.substr(0, response.length() - 1);
        }
    }

    return response;
}

size_t cpr::util::writeFunction(void *ptr, size_t size, size_t nmemb, std::string* data) {
    data->append((char*) ptr, size * nmemb);
    return size * nmemb;
}

Use a for each loop


#include "GUI.hpp"

#if __APPLE__
#import <IOKit/pwr_mgt/IOPMLib.h>
#elif _WIN32
#include <Windows.h>
#pragma comment(lib, "user32.lib")
#endif

namespace Slic3r { namespace GUI {

IOPMAssertionID assertionID;

void
disable_screensaver()
{
    #if __APPLE__
    CFStringRef reasonForActivity = CFSTR("Slic3r");
    IOReturn success = IOPMAssertionCreateWithName(kIOPMAssertionTypeNoDisplaySleep,
        kIOPMAssertionLevelOn, reasonForActivity, &assertionID);
    // ignore result: success == kIOReturnSuccess
    #elif _WIN32
    SetThreadExecutionState(EXECUTION_STATE.ES_DISPLAY_REQUIRED | EXECUTION_STATE.ES_CONTINUOUS);
    #endif
}

void
enable_screensaver()
{
    #if __APPLE__
    IOReturn success = IOPMAssertionRelease(assertionID);
    #elif _WIN32
    SetThreadExecutionState(EXECUTION_STATE.ES_CONTINUOUS);
    #endif
}

} }

#include "GUI.hpp"

#if __APPLE__
#import <IOKit/pwr_mgt/IOPMLib.h>
#elif _WIN32
#include <Windows.h>
#pragma comment(lib, "user32.lib")
#endif

namespace Slic3r { namespace GUI {

#if __APPLE__
IOPMAssertionID assertionID;
#endif

void
disable_screensaver()
{
    #if __APPLE__
    CFStringRef reasonForActivity = CFSTR("Slic3r");
    IOReturn success = IOPMAssertionCreateWithName(kIOPMAssertionTypeNoDisplaySleep,
        kIOPMAssertionLevelOn, reasonForActivity, &assertionID);
    // ignore result: success == kIOReturnSuccess
    #elif _WIN32
    SetThreadExecutionState(EXECUTION_STATE.ES_DISPLAY_REQUIRED | EXECUTION_STATE.ES_CONTINUOUS);
    #endif
}

void
enable_screensaver()
{
    #if __APPLE__
    IOReturn success = IOPMAssertionRelease(assertionID);
    #elif _WIN32
    SetThreadExecutionState(EXECUTION_STATE.ES_CONTINUOUS);
    #endif
}

} }

Fix a compilation error on Win32


#include <cstdlib>
#include <iostream>
using namespace std;

int const n = 50;
long long save[n + 1];

long long fibonanci(int n){

	if (n <= 1)
		return 1;

	if (save[n])
		return save[n];

	return save[n] = fibonanci(n - 2) + fibonanci(n - 1);
}

/*

// CAUTION: This code will take too much time

int fibonanci(int n){

	if (n <= 1)
		return 1;

	return fibonanci(n - 2) + fibonanci(n - 1);
}

*/

int main(){

	printf("fibonanci of %d = %lld\n", n, fibonanci(n));

	return 0;
}

#include <cstdlib>
#include <iostream>
using namespace std;

int const n = 50;
long long save[n + 1];

long long fibonanci_dp(int n){

	if (n <= 0) return 0;

	if (n <= 2) return 1;

	if (save[n])
		return save[n];

	return save[n] = fibonanci_dp(n - 2) + fibonanci_dp(n - 1);
}

/*

// CAUTION: This code will take too much time

long long fibonanci(int n){

	if (n <= 0) return 0;

	if (n <= 2) return 1;

	return fibonanci(n - 2) + fibonanci(n - 1);
}

*/

long long fibonanci_loop(int n){

	long long a = 0, t = 0, b = 1;

	while (n--){
		// cout << a << endl;
		t = a, a = b;
		b = t + b;
	}

	// cout << a << endl;
	return a;
}

int main() {

	// using DP
	cout << fibonanci_dp(n) << endl;

	// using loop
	cout << fibonanci_loop(n) << endl;

	return 0;
}

Add fibonanci_loop method & Fix bug