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

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/

#include "tensorflow/core/kernels/cwise_ops_common.h"

namespace tensorflow {
REGISTER2(UnaryOp, CPU, "Tan", functor::tan, float, double);

#if GOOGLE_CUDA
REGISTER2(UnaryOp, GPU, "Tan", functor::tan, float, double);
#endif

#ifdef TENSORFLOW_USE_SYCL
REGISTER2(UnaryOp, SYCL, "Tan", functor::tan, float, double);
#endif  // TENSORFLOW_USE_SYCL
}  // namespace tensorflow

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

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/

#include "tensorflow/core/kernels/cwise_ops_common.h"

namespace tensorflow {
REGISTER4(UnaryOp, CPU, "Tan", functor::tan, float, double, complex64, complex128);

#if GOOGLE_CUDA
REGISTER2(UnaryOp, GPU, "Tan", functor::tan, float, double);
#endif

#ifdef TENSORFLOW_USE_SYCL
REGISTER2(UnaryOp, SYCL, "Tan", functor::tan, float, double);
#endif  // TENSORFLOW_USE_SYCL
}  // namespace tensorflow

Add complex support for tan


#include <cstring>
#include <iostream>

#include <UnitTest++/UnitTest++.h>
#include <UnitTest++/TestReporterStdout.h>

using std::cerr;
using std::endl;
using std::strcmp;

/*
  Function object returning true for a specified test name
 */
struct MatchTestName {
  const char * const tname;
  MatchTestName (const char* tn) : tname {tn} {};
  bool operator () (const UnitTest::Test* const test) const { return strcmp(test->m_details.testName, tname) == 0; }
};

/*
  Locate and run all tests
 */
int main(int argc, const char* argv[]) {
  if (argc < 2)
    return UnitTest::RunAllTests();
  else if (argc >= 2){
    UnitTest::TestReporterStdout reporter;
    UnitTest::TestRunner runner (reporter);
    if (argc == 2)
      return runner.RunTestsIf (UnitTest::Test::GetTestList(),
                                argv[1],
                                UnitTest::True(),
                                0);
    else if (argc == 3)
      return runner.RunTestsIf (UnitTest::Test::GetTestList(),
                                argv[1],
                                MatchTestName(argv[2]),
                                0);
    else
      cerr << "Usage: tester [suite [test]]" << endl;
  }
}

#include <cstring>
#include <iostream>

#include <UnitTest++/UnitTest++.h>
#include <UnitTest++/TestReporterStdout.h>

using std::cerr;
using std::endl;
using std::strcmp;

/*
  Function object returning true for a specified test name
 */
struct MatchTestName {
  const char * const tname;
  MatchTestName (const char* tn) : tname {tn} {};
  bool operator () (const UnitTest::Test* const test) const { return strcmp(test->m_details.testName, tname) == 0; }
};

/*
  Runs a specific suite/test if a suite, or a suite and a test, is provided,
  or all tests if none are provided.

  To execute, run ./tester [suite [test]]
 */
int main(int argc, const char* argv[]) {
  if (argc < 2)
    return UnitTest::RunAllTests();
  else if (argc >= 2){
    UnitTest::TestReporterStdout reporter;
    UnitTest::TestRunner runner (reporter);
    if (argc == 2)
      return runner.RunTestsIf (UnitTest::Test::GetTestList(),
                                argv[1],
                                UnitTest::True(),
                                0);
    else if (argc == 3)
      return runner.RunTestsIf (UnitTest::Test::GetTestList(),
                                argv[1],
                                MatchTestName(argv[2]),
                                0);
    else
      cerr << "Usage: ./tester [suite [test]]" << endl;
  }
}

Update documentation for main() in tester


// Copyright (C) 2012-2016 Leap Motion, Inc. All rights reserved.
#include "stdafx.h"
#include "MentionsVariousOtherTypes.hpp"
#include <autowiring/autowiring.h>

MentionsVariousOtherTypes::MentionsVariousOtherTypes(void) {
  AutoRequired<AutoPacketFactory>();
}

// Copyright (C) 2012-2016 Leap Motion, Inc. All rights reserved.
#include "MentionsVariousOtherTypes.hpp"
#include <autowiring/autowiring.h>

MentionsVariousOtherTypes::MentionsVariousOtherTypes(void) {
  AutoRequired<AutoPacketFactory>();
}

Remove PCH that seems to hit a rogue extern "C" on Travis


// Copyright (C) 2012-2015 Leap Motion, Inc. All rights reserved.
#include "stdafx.h"
#include "auto_id.h"

using namespace autowiring;

// Index that will be given to the next auto_id instance.  Zero is reserved.
static int s_index = 1;

const auto_id_block auto_id_t<void>::s_block{
  0,
  &typeid(void),
  &typeid(s<void>),
  0,
  0,
  nullptr,
  nullptr
};

const auto_id_t_init<void, true> auto_id_t_init<void, true>::init;
const auto_id_t_init<void, false> auto_id_t_init<void, false>::init;

int autowiring::CreateIndex(void) {
  return s_index++;
}

std::shared_ptr<CoreObject> auto_id_block::NullToObj(const std::shared_ptr<void>&) AUTO_NOEXCEPT
{
  return nullptr;
}

std::shared_ptr<void> auto_id_block::NullFromObj(const std::shared_ptr<CoreObject>&) AUTO_NOEXCEPT
{
  return nullptr;
}

// Copyright (C) 2012-2015 Leap Motion, Inc. All rights reserved.
#include "stdafx.h"
#include "auto_id.h"

using namespace autowiring;

// Index that will be given to the next auto_id instance.  Zero is reserved.
static int s_index = 1;

const auto_id_block auto_id_t<void>::s_block{
  0,
  &typeid(void),
  &typeid(s<void>),
  0,
  0,
  nullptr,
  nullptr
};

const auto_id_t_init<void, true> auto_id_t_init<void, true>::init{};
const auto_id_t_init<void, false> auto_id_t_init<void, false>::init{};

int autowiring::CreateIndex(void) {
  return s_index++;
}

std::shared_ptr<CoreObject> auto_id_block::NullToObj(const std::shared_ptr<void>&) AUTO_NOEXCEPT
{
  return nullptr;
}

std::shared_ptr<void> auto_id_block::NullFromObj(const std::shared_ptr<CoreObject>&) AUTO_NOEXCEPT
{
  return nullptr;
}

Use initializer syntax to satisfy clang


#include "comb.h"

int main()
{
//  for(int i=0;i<6;i++){
    sweep(20*2*pi,0.7*2*pi,1,400000,1000,1/pow(10,10),0,10,16,50,600,15,0,0.001,"Gaussian");
    sweep(20*2*pi,0.7*2*pi,1,400000,1000,1/pow(10,10),0,10,17,50,600,15,0,0.001,"Gaussian");
//  }
      //gamma2(Hz),line width(GHz),sweep steps, total steps, power(uW/cm2),convergence condition,convergence threshold,convergency steps,ADM order,n1 interval,n2 interval,Matrix self multiplication,laser detune,A Factor
      // The last argument is the function type "Sinc" for Sinc Function other for Gaussian function

//0.7*2*pi;//0.0052227*2*pi;//

system("./mail.py");
return 0;

}

#include "comb.h"
#include <ctime>

int main()
{

  fstream file1;
  file1.open("./Data/result.txt",ios::out | ios::trunc);
  file1<<"Function\t"<<"Order\t"<<"Steps\t"<<endl;

  for(int i=1;i<6;i++){
   for(int j=1;j<4;j++){
    time_t T1 = clock(),T2;
    sweep(20*2*pi,0.7*2*pi,1,400000,1000,1/pow(10,10),0,10,12-i,10*j,600,15,0,0.001,"Gaussian");
    T2 = clock();
    file1<<"Gaussian\t"<<12-i<<"\t"<<10*j<<"\t"<<(T2-T1)<<endl;
    sweep(20*2*pi,0.7*2*pi,1,400000,1000,1/pow(10,10),0,10,12-i,10*j,600,15,0,0.001,"Sinc");
    T1 = clock();
    file1<<"sinc\t"<<12-i<<"\t"<<10*j<<"\t"<<(T1-T2)<<endl;
   }
  }

      //gamma2(Hz),line width(GHz),sweep steps, total steps, power(uW/cm2),convergence condition,convergence threshold,convergency steps,ADM order,n1 interval,n2   interval,Matrix self multiplication,laser detune,A Factor
      // The last argument is the function type "Sinc" for Sinc Function other for Gaussian function

//0.7*2*pi;//0.0052227*2*pi;//

system("./mail.py");

return 0;

}

Add benchmark feature in main functin.


#include "mock/unittest_utils.hpp"

#include <stdlib.h>

#include "errors.hpp"
#include <boost/bind.hpp>

#include "arch/timing.hpp"
#include "arch/runtime/starter.hpp"
#include "utils.hpp"            // randint

namespace mock {

temp_file_t::temp_file_t(const char *tmpl) {
    size_t len = strlen(tmpl);
    filename.init(len + 1);
    memcpy(filename.data(), tmpl, len+1);
    int fd = mkstemp(filename.data());
    guarantee_err(fd != -1, "Couldn't create a temporary file");
    close(fd);
}

temp_file_t::~temp_file_t() {
    unlink(filename.data());
}

void let_stuff_happen() {
    nap(100);
}

int randport() {
    return 10000 + randint(20000);
}

void run_in_thread_pool(const boost::function<void()>& fun, int num_workers) {
    ::run_in_thread_pool(fun, num_workers);
}

}  // namespace mock

#include "mock/unittest_utils.hpp"

#include <stdlib.h>

#include "errors.hpp"
#include <boost/bind.hpp>

#include "arch/timing.hpp"
#include "arch/runtime/starter.hpp"
#include "utils.hpp"            // randint

namespace mock {

temp_file_t::temp_file_t(const char *tmpl) {
    size_t len = strlen(tmpl);
    filename.init(len + 1);
    memcpy(filename.data(), tmpl, len+1);
    int fd = mkstemp(filename.data());
    guarantee_err(fd != -1, "Couldn't create a temporary file");
    close(fd);
}

temp_file_t::~temp_file_t() {
    unlink(filename.data());
}

void let_stuff_happen() {
#ifdef VALGRIND
    nap(2000);
#else
    nap(100);
#endif
}

int randport() {
    return 10000 + randint(20000);
}

void run_in_thread_pool(const boost::function<void()>& fun, int num_workers) {
    ::run_in_thread_pool(fun, num_workers);
}

}  // namespace mock

Make let_stuff_happen() wait longer under valgrind.


#include <boost/test/unit_test.hpp>

#include "../uint256.h"

extern void SHA256Transform(void* pstate, void* pinput, const void* pinit);

BOOST_AUTO_TEST_SUITE(miner_tests)

BOOST_AUTO_TEST_CASE(sha256transform_equality)
{
    unsigned int pSHA256InitState[8] = {0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19};

    unsigned char pstate[32];
    unsigned char pinput[32];

    int i;

    for (i = 0; i < 32; i++) {
        pinput[i] = i;
        pstate[i] = 0;
    }

    uint256 hash;

    SHA256Transform(&hash, pinput, pSHA256InitState);

		BOOST_TEST_MESSAGE(hash.GetHex());

    uint256 hash_reference("0x2df5e1c65ef9f8cde240d23cae2ec036d31a15ec64bc68f64be242b1da6631f3");

    BOOST_CHECK(hash == hash_reference);
}

BOOST_AUTO_TEST_SUITE_END()

#include <boost/test/unit_test.hpp>

#include "../uint256.h"

extern void SHA256Transform(void* pstate, void* pinput, const void* pinit);

BOOST_AUTO_TEST_SUITE(miner_tests)

BOOST_AUTO_TEST_CASE(sha256transform_equality)
{
    unsigned int pSHA256InitState[8] = {0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19};

    unsigned char pstate[32];
    unsigned char pinput[64];

    int i;

    for (i = 0; i < 32; i++) {
        pinput[i] = i;
        pinput[i+32] = 0;
    }

    uint256 hash;

    SHA256Transform(&hash, pinput, pSHA256InitState);

    BOOST_TEST_MESSAGE(hash.GetHex());

    uint256 hash_reference("0x2df5e1c65ef9f8cde240d23cae2ec036d31a15ec64bc68f64be242b1da6631f3");

    BOOST_CHECK(hash == hash_reference);
}

BOOST_AUTO_TEST_SUITE_END()

Fix miner_test unit test bug


// RUN: %clangxx -shared -o /dev/null -v -fxray-instrument %s -###
// RUN: %clangxx -shared -o /dev/null -v -fxray-instrument %s -### 2>&1 | \
// RUN:     FileCheck %s --check-prefix=SHARED
// RUN: %clangxx -static -o /dev/null -v -fxray-instrument %s -### -DMAIN
// RUN: %clangxx -static -o /dev/null -v -fxray-instrument %s -### 2>&1 -DMAIN \
// RUN:     | FileCheck %s --check-prefix=STATIC
//
// SHARED-NOT: {{clang_rt\.xray-}}
// STATIC: {{clang_rt\.xray-}}
//
// REQUIRES: enable_shared
int foo() { return 42; }

#ifdef MAIN
int main() { return foo(); }
#endif

// RUN: %clangxx -shared -o /dev/null -v -fxray-instrument %s -###
// RUN: %clangxx -shared -o /dev/null -v -fxray-instrument %s -### 2>&1 | \
// RUN:     FileCheck %s --check-prefix=SHARED
// RUN: %clangxx -static -o /dev/null -v -fxray-instrument %s -### -DMAIN
// RUN: %clangxx -static -o /dev/null -v -fxray-instrument %s -### 2>&1 -DMAIN \
// RUN:     | FileCheck %s --check-prefix=STATIC
//
// SHARED-NOT: {{clang_rt\.xray-}}
// STATIC: {{clang_rt\.xray-}}
//
// REQUIRES: linux, enable_shared
int foo() { return 42; }

#ifdef MAIN
int main() { return foo(); }
#endif

Revert part of r. 325746 D43378


#include "ZulipAboutDialog.h"

#include "ui_ZulipAboutDialog.h"
#include "Config.h"

#include <QFile>
#include <QDebug>

ZulipAboutDialog::ZulipAboutDialog(QWidget *parent) :
    QDialog(parent), m_ui(new Ui::ZulipAboutDialog)
{
    m_ui->setupUi(this);

    QFile html(":/about.html");
    if (!html.open(QIODevice::ReadOnly)) {
        qWarning() << "Failed to read from qrc:/about.html";
    } else {
        QString contents = QString::fromUtf8(html.readAll());
        // Add version string

        QString license;
#ifdef SSO_BUILD
        license = "the Zulip Enterprise License Agreement";
#else
        license = "the license described in the Zulip Terms of Service";
#endif
        contents = contents.replace("{{ZULIP_VERSION_STRING}}", ZULIP_VERSION_STRING);
        contents = contents.replace("{{ZULIP_LICENSE_AGREEMENT}}", license);
        m_ui->webView->loadHTML(contents);
    }
}

ZulipAboutDialog::~ZulipAboutDialog()
{
}

#include "ZulipAboutDialog.h"

#include "ui_ZulipAboutDialog.h"
#include "Config.h"
#include "ZulipApplication.h"
#include "ZulipWindow.h"

#include <QFile>
#include <QDebug>

ZulipAboutDialog::ZulipAboutDialog(QWidget *parent) :
    QDialog(parent), m_ui(new Ui::ZulipAboutDialog)
{
    m_ui->setupUi(this);

    connect(m_ui->webView, SIGNAL(linkClicked(QUrl)), APP->mainWindow(), SLOT(linkClicked(QUrl)));

    QFile html(":/about.html");
    if (!html.open(QIODevice::ReadOnly)) {
        qWarning() << "Failed to read from qrc:/about.html";
    } else {
        QString contents = QString::fromUtf8(html.readAll());
        // Add version string

        QString license;
#ifdef SSO_BUILD
        license = "the Zulip Enterprise License Agreement";
#else
        license = "the license described in the Zulip Terms of Service";
#endif
        contents = contents.replace("{{ZULIP_VERSION_STRING}}", ZULIP_VERSION_STRING);
        contents = contents.replace("{{ZULIP_LICENSE_AGREEMENT}}", license);
        m_ui->webView->loadHTML(contents);
    }
}

ZulipAboutDialog::~ZulipAboutDialog()
{
}

Fix Terms URL in about dialog to open in browser


#include "ProxyImage.h"
#include "StringHelper.h"

#include <sprite2/S2_Texture.h>

namespace gum
{

ProxyImage::ProxyImage(int id, int w, int h, int format)
{
	Init(id, w, h, format);
}

ProxyImage::~ProxyImage()
{
// 	m_id = 0; // avoid release in Image
// 	          // managed by other
}

void ProxyImage::Init(int id, int w, int h, int format)
{
	m_width  = w;
	m_height = h;
	m_format = format;
	m_id     = id;

	m_filepath = GetFilepath(id);

	m_s2_tex->Init(w, h, id);
}

std::string ProxyImage::GetFilepath(int id)
{
	return "_proxy" + StringHelper::ToString(id);
}

}

#include "ProxyImage.h"
#include "StringHelper.h"

#include <sprite2/S2_Texture.h>

namespace gum
{

ProxyImage::ProxyImage(int id, int w, int h, int format)
{
	Init(id, w, h, format);
}

ProxyImage::~ProxyImage()
{
	m_id = 0; // avoid release in Image
	          // managed by other
}

void ProxyImage::Init(int id, int w, int h, int format)
{
	m_width  = w;
	m_height = h;
	m_format = format;
	m_id     = id;

	m_filepath = GetFilepath(id);

	m_s2_tex->Init(w, h, id);
}

std::string ProxyImage::GetFilepath(int id)
{
	return "_proxy" + StringHelper::ToString(id);
}

}

Revert "[FIXED] proxy img dtor"


#include "HttpClient.h"

#include <mbedtls/ssl.h>
#include <mbedtls/x509.h>

namespace ceema {
    CURLcode HttpClient::ssl_ctx_callback_mbedtls(CURL *curl, void *ssl_ctx, void *client_ptr) {
        HttpClient& client = *static_cast<HttpClient*>(client_ptr);

        if (client.m_cert.empty()) {
            return CURLE_OK;
        }

        LOG_DEBUG(logging::loggerRoot, "Inserting SSL cert");
        CURLcode status = CURLE_OK;

        auto mbed_ctx = static_cast<mbedtls_ssl_config*>(ssl_ctx);

        mbedtls_x509_crt cacert;
        mbedtls_x509_crt_init( &cacert );

        if (mbedtls_x509_crt_parse(
                &cacert,
                reinterpret_cast<const unsigned char*>(client.m_cert.c_str()),
                client.m_cert.size()) != 0) {
            status = CURLE_SSL_CERTPROBLEM;
        } else {
            mbedtls_ssl_conf_ca_chain(mbed_ctx, &cacert, nullptr);
        }

        return status;
    }
}

#include "HttpClient.h"

#include <mbedtls/ssl.h>
#include <mbedtls/x509.h>

namespace ceema {
    CURLcode HttpClient::ssl_ctx_callback_mbedtls(CURL *curl, void *ssl_ctx, void *client_ptr) {
        HttpClient& client = *static_cast<HttpClient*>(client_ptr);

        if (client.m_cert.empty()) {
            return CURLE_OK;
        }

        LOG_DEBUG(logging::loggerRoot, "Inserting SSL cert");
        CURLcode status = CURLE_OK;

        auto mbed_ctx = static_cast<mbedtls_ssl_config*>(ssl_ctx);

        mbedtls_x509_crt cacert;
        mbedtls_x509_crt_init( &cacert );

        if (mbedtls_x509_crt_parse(
                &cacert,
                reinterpret_cast<const unsigned char*>(client.m_cert.c_str()),
                client.m_cert.size() + 1) != 0) {
            status = CURLE_SSL_CERTPROBLEM;
        } else {
            mbedtls_ssl_conf_ca_chain(mbed_ctx, &cacert, nullptr);
        }

        return status;
    }
}

Fix error in size for parsing the certificate by mbedtls_x509_crt_parse


#include "common.h"

void siren_ary_to_xyz(VALUE ary, Standard_Real& x, Standard_Real& y, Standard_Real& z)
{
  x = 0.0; y = 0.0; z = 0.0;

  Check_Type(ary, T_ARRAY);

  int len = RARRAY_LEN(ary);
  if (len > 0) {
    x = NUM2DBL(RARRAY_AREF(ary, 0));
  }
  if (len > 1) {
    y = NUM2DBL(RARRAY_AREF(ary, 1));
  }
  if (len > 2) {
    z = NUM2DBL(RARRAY_AREF(ary, 2));
  }
  return;
}

#include "common.h"

void siren_ary_to_xyz(VALUE ary, Standard_Real& x, Standard_Real& y, Standard_Real& z)
{
  x = 0.0; y = 0.0; z = 0.0;

  int len = RARRAY_LEN(ary);
  if (len > 0) {
    x = NUM2DBL(RARRAY_AREF(ary, 0));
  }
  if (len > 1) {
    y = NUM2DBL(RARRAY_AREF(ary, 1));
  }
  if (len > 2) {
    z = NUM2DBL(RARRAY_AREF(ary, 2));
  }
  return;
}

Fix bug. support implicit cast Vec to Array again.


#include "KAI/Console/Console.h"

#include <iostream>

#ifdef WIN32
#define WIN32_LEAN_AND_MEAN
#include <Windows.h>
#endif

using namespace std;

USING_NAMESPACE_KAI

//static Color _color;

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

	cout << "pyro v0.1" << endl;

	Console console;
	console.SetLanguage(Language::Pi);

	Process::trace = 0;
	console.GetExecutor()->SetTraceLevel(0);

	return console.Run();
}

#include <KAI/Console/Console.h>
#include <iostream>

using namespace std;

USING_NAMESPACE_KAI

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

	cout << "KAI v0.1" << endl;

	Console console;
	console.SetLanguage(Language::Pi);

	// the higher the number, the greater the verbosity of debug output
	Process::trace = 0;
	console.GetExecutor()->SetTraceLevel(0);

	// start the REPL
	return console.Run();
}

Remove explicit WIN32 references from Console app.


#include "Rotate.hpp"

#include "../../../Libraries/bullet3/src/LinearMath/btTransform.h"
#include <Scenes/Entity.hpp>
#include <Engine/Engine.hpp>
#include <Physics/Colliders/Collider.hpp>
#include <Maths/Maths.hpp>

namespace test
{
	Rotate::Rotate(const Vector3 &direction, const int &test) :
		m_direction(direction),
		m_test(test),
		m_rotation(Vector3())
	{
	}

	void Rotate::Start()
	{
	}

	void Rotate::Update()
	{
		m_rotation += m_direction * Engine::Get()->GetDelta().AsSeconds();
		Transform &transform = GetParent()->GetLocalTransform();
		transform.SetRotation(m_rotation);

		if (m_test == 1)
		{
			Quaternion rotation = Quaternion(m_rotation.m_x, m_rotation.m_y, m_rotation.m_z);
			transform.SetRotation(rotation.ToEuler());
		}
		else if (m_test == 2)
		{
			btTransform transform1 = Collider::Convert(transform);
			transform = Collider::Convert(transform1, transform.GetScaling());
		}
	}

	void Rotate::Decode(const Metadata &metadata)
	{
		m_direction = metadata.GetChild<Vector3>("Direction");
	}

	void Rotate::Encode(Metadata &metadata) const
	{
		metadata.SetChild<Vector3>("Direction", m_direction);
	}
}

#include "Rotate.hpp"

#include <bullet/LinearMath/btTransform.h>
#include <Scenes/Entity.hpp>
#include <Engine/Engine.hpp>
#include <Physics/Colliders/Collider.hpp>
#include <Maths/Maths.hpp>

namespace test
{
	Rotate::Rotate(const Vector3 &direction, const int &test) :
		m_direction(direction),
		m_test(test),
		m_rotation(Vector3())
	{
	}

	void Rotate::Start()
	{
	}

	void Rotate::Update()
	{
		m_rotation += m_direction * Engine::Get()->GetDelta().AsSeconds();
		Transform &transform = GetParent()->GetLocalTransform();
		transform.SetRotation(m_rotation);

		if (m_test == 1)
		{
			Quaternion rotation = Quaternion(m_rotation.m_x, m_rotation.m_y, m_rotation.m_z);
			transform.SetRotation(rotation.ToEuler());
		}
		else if (m_test == 2)
		{
			btTransform transform1 = Collider::Convert(transform);
			transform = Collider::Convert(transform1, transform.GetScaling());
		}
	}

	void Rotate::Decode(const Metadata &metadata)
	{
		m_direction = metadata.GetChild<Vector3>("Direction");
	}

	void Rotate::Encode(Metadata &metadata) const
	{
		metadata.SetChild<Vector3>("Direction", m_direction);
	}
}

Fix tests include for bullet


#include <iostream>

#include "libport/cli.hh"
#include "libport/sysexits.hh"
#include "libport/program-name.hh"

namespace libport
{
  void
  usage_error (const std::string& opt, const std::string& err)
  {
    std::cerr << program_name << ": " << opt << ": " << err << std::endl
	      << libport::exit (EX_USAGE);
  }

  void
  required_argument (const std::string& opt)
  {
    usage_error (opt, "requires an argument");
  }

  void
  missing_argument (const std::string& opt)
  {
    usage_error (opt, "missing argument");
  }

  void
  invalid_option (const std::string& opt)
  {
    usage_error (opt, "invalid option");
  }

  void
  invalid_option_val (const std::string& opt, const std::string& arg)
  {
    usage_error (opt, "invalid argument: " + arg);
  }

}

#include <iostream>

#include "libport/cli.hh"
#include "libport/sysexits.hh"
#include "libport/program-name.hh"

namespace libport
{
  void
  usage_error (const std::string& opt, const std::string& err)
  {
    std::cerr
      << program_name << ": " << opt << ": " << err
      << std::endl
      << "Try `" << program_name << " --help' for more information."
      << std::endl
      << libport::exit (EX_USAGE);
  }

  void
  required_argument (const std::string& opt)
  {
    usage_error (opt, "requires an argument");
  }

  void
  missing_argument (const std::string& opt)
  {
    usage_error (opt, "missing argument");
  }

  void
  invalid_option (const std::string& opt)
  {
    usage_error (opt, "invalid option");
  }

  void
  invalid_option_val (const std::string& opt, const std::string& arg)
  {
    usage_error (opt, "invalid argument: " + arg);
  }

}

Improve error message on bad options.


// Standard headers
#include "InputArgs.hpp"

InputArgs::InputArgs(int argc, char const *const *argv)
    : argstream(argv, argv + argc) {
  read_input();
  process_input();
}

void InputArgs::process_input() {
  if (n_threads == 0)
    n_threads = std::thread::hardware_concurrency();
}

void InputArgs::read_input() {
  argstream[1] >> n_threads;
  argstream[2] >> stop_criteria;
  argstream[3] >> precision;
  argstream[4] >> angle;

  if (argstream.size() >= 5)
    argstream[5] >> debug_level;
}

// Standard headers
#include "InputArgs.hpp"

InputArgs::InputArgs(int argc, char const *const *argv)
    : argstream(argv, argv + argc) {
  read_input();
  process_input();
}

void InputArgs::process_input() {
  if (n_threads == 0)
    n_threads = std::thread::hardware_concurrency();
}

void InputArgs::read_input() {
  argstream[1] >> n_threads;
  argstream[2] >> stop_criteria;
  argstream[3] >> precision;
  argstream[4] >> angle;

  if (argstream.size() > 5)
    argstream[5] >> debug_level;
}

Correct check of number of arguments


#include "misc_util.h"

namespace dlib {

    void string_fmt_time(std::string& ret) {
        time_t now = time(NULL);
        struct tm *t = localtime(&now);
        while(!strftime((char *)ret.data(), ret.capacity(), "%Y:%m:%d %H:%M", t))
            ret.reserve(ret.size() << 1);
    }

}

#include "misc_util.h"

namespace dlib {

    void string_fmt_time(std::string& ret) {
        time_t now = time(NULL);
        struct tm *t = localtime(&now);
        while(!strftime((char *)ret.data(), ret.capacity(), "%Y:%m:%d %H:%M", t))
            ret.reserve(ret.capacity() ? ret.capacity() << 1: 16);
    }

}

Fix mistake of using size instead of capacity.


#include <iostream>
#include <fstream>
#include "huffman.hpp"

using namespace algorithm;

static enum
{
    E_SUCCESS = 0,
    E_ARGUMENT_NOT_PROVIDED,
    E_FILE_NOT_FOUND,
}
StatusType;

int
main(const int argc, const char * argv[])
{
    if(argc < 2)
    {
        fprintf(stderr, "Usage: %s [file name]\n", argv[0]);
        return E_ARGUMENT_NOT_PROVIDED;
    }

    std::string f_name = argv[1];

    std::ifstream f(f_name, std::ios::binary);
    if(! f.is_open())
    {
        fprintf(stderr, "Error: File '%s' not found.\n", f_name.c_str());
        return E_FILE_NOT_FOUND;
    }

    Huffman huffman;
    huffman.CollectRuns(f);
    huffman.PrintAllRuns(stdout);

    f.close();

    return E_SUCCESS;
}

#include <iostream>
#include <fstream>
#include "include/huffman.hpp"

using namespace algorithm;

static enum
{
    E_SUCCESS = 0,
    E_ARGUMENT_NOT_PROVIDED,
    E_FILE_NOT_FOUND,
}
StatusType;

int
main(const int argc, const char * argv[])
{
    if(argc < 2)
    {
        fprintf(stderr, "Usage: %s [file name]\n", argv[0]);
        return E_ARGUMENT_NOT_PROVIDED;
    }

    std::string f_name = argv[1];

    std::ifstream f(f_name, std::ios::binary);
    if(! f.is_open())
    {
        fprintf(stderr, "Error: File '%s' not found.\n", f_name.c_str());
        return E_FILE_NOT_FOUND;
    }

    Huffman huffman;
    huffman.CollectRuns(f);
    huffman.PrintAllRuns(stdout);

    f.close();

    return E_SUCCESS;
}

Fix the path of header file


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

#include <sys/types.h>
#include <sys/wait.h>
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sysexits.h>
#include <unistd.h>

char* getinput(char *buffer, size_t buflen) {
  printf("$$ ");
  return fgets(buffer, buflen, stdin);
}

int main(int argc, char **argv) {
  char buf[1024];
  pid_t pid;
  int status;

  while (getinput(buf, sizeof(buf))) {
    buf[strlen(buf) - 1] = '\0';

    if ((pid = fork()) == -1) {
      fprintf(stderr, "shell: can't fork: %s\n", strerror(errno));
      continue;
    } else if (pid == 0) {
      execlp(buf, buf, (char*) 0);
      fprintf(stderr, "shell: couldn't exec %s: %s\n", buf, strerror(errno));
      exit(EX_DATAERR);
    }

    if ((pid = waitpid(pid, &status, 0)) < 0) {
      fprintf(stderr, "shell: waitpid error: %s\n", strerror(errno));
    }
  }

  exit(EX_OK);

  return 0;
}

Add execution of simple programs


// https://github.com/KubaO/stackoverflown/tree/master/questions/lambda-list-37615204
#include <QtWidgets>

class Widget : public QWidget {
   struct Buyable {
      void buy(int) const {}
   };
   QList<Buyable> m_list;
   QList<QList<QWidget*>> m_widgets;
   int m_amountMultiplier = 2;
public:
   Widget() {
      auto button = [this]{ return new QPushButton(this); };
      for (int i = 0; i < 5; ++i) {
         m_list << Buyable();
         m_widgets << QList<QWidget*>{button(), button(), button()};
      }
   }
   void test() {
      Q_ASSERT(m_list.size() == m_widgets.size());
      for (int i = 0; i < m_list.size(); ++i) {
         connect(static_cast<QAbstractButton*>(m_widgets.at(i).at(2)),
                 &QAbstractButton::clicked,
                 [this, i]() {
            m_list.at(i).buy(m_amountMultiplier);}
         );
      }
   }
};

int main() {}

// https://github.com/KubaO/stackoverflown/tree/master/questions/lambda-list-37615204
#include <QtWidgets>

struct Building {
   void buy() {}
};

class Class : public QObject {
   QList<Building> m_buildings;
   QList<QList<QWidget*>> m_widgets;
public:
   Class() {
      for (int i = 0; i<m_buildings.size(); ++i)
         connect(static_cast<QAbstractButton*>(m_widgets.at(i).at(2)), &QAbstractButton::clicked, [=] {
            m_buildings[i].buy();
         });
   }
};

int main() {}

Update to match edited question.


#include "scene.h"
#include "mesh.h"
#include "material.h"
#include <glm/gtc/matrix_transform.hpp>
#include <assimp/Importer.hpp>
#include <assimp/scene.h>
#include <assimp/postprocess.h>

Scene::Scene()
{

}

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

bool Scene::load(const char* fileName)
{
    Assimp::Importer importer;
    const aiScene* scene = importer.ReadFile(fileName,
            aiProcess_Triangulate |
            aiProcess_JoinIdenticalVertices |
            aiProcess_SortByPType);
    if(!scene)
    {
        std::cerr << "Error loading mesh " << fileName << ": " << importer.GetErrorString() << std::endl;
        return false;
    }

    for (int m = 0; m < scene->mNumMeshes; ++m) {
        const aiMesh* aiM = scene->mMeshes[m];

        Mesh* mesh = new Mesh();;
        if (!mesh->load(aiM))
        {
            return false;
        }
        m_meshes.push_back(mesh);
    }

    return true;
}

void Scene::render(Material* mat)
{
    for (auto it = m_meshes.begin(); it != m_meshes.end(); ++it)
    {
        mat->setUniform("model", (*it)->getModelMatrix());
        (*it)->render();
    }
}

#include "scene.h"
#include "mesh.h"
#include "material.h"
#include <glm/gtc/matrix_transform.hpp>
#include <assimp/Importer.hpp>
#include <assimp/scene.h>
#include <assimp/postprocess.h>

Scene::Scene()
{

}

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

bool Scene::load(const char* fileName)
{
    Assimp::Importer importer;
    const aiScene* scene = importer.ReadFile(fileName,
            aiProcess_Triangulate |
            aiProcess_JoinIdenticalVertices |
            aiProcess_SortByPType);
    if(!scene)
    {
        std::cerr << "Error loading scene " << fileName << ": " << importer.GetErrorString() << std::endl;
        return false;
    }

    for (int m = 0; m < scene->mNumMeshes; ++m) {
        const aiMesh* aiM = scene->mMeshes[m];

        Mesh* mesh = new Mesh();
        if (!mesh->load(aiM))
        {
            delete mesh;
            return false;
        }
        m_meshes.push_back(mesh);
    }

    return true;
}

void Scene::render(Material* mat)
{
    for (auto it = m_meshes.begin(); it != m_meshes.end(); ++it)
    {
        mat->setUniform("model", (*it)->getModelMatrix());
        (*it)->render();
    }
}

Fix potential memory leak in vertex shading example


// This file extends the QWebView class to add additional functionality.

#include "stdafx.h"
using namespace std;
void QWebViewWithHooks::watch(string selector, Getter getter, Callback callback){
	int uuid = watchUuid++;
	watches.push_back(make_tuple(QString::fromStdString(selector), getter, callback, uuid) );
	watchValues[uuid] = "";
	//TODO: Change to return unwatch function. However, quite lazy.
}

void QWebViewWithHooks::keyReleaseEvent(QKeyEvent * ev)
{
	// Look for all watches and get values that are changed.
	// If there is a change, call the callback.
	for(auto it = watches.begin(); it != watches.end(); ++it) {
		auto selector = get<0>(*it);
		auto getter = get<1>(*it);
		auto callback = get<2>(*it);
		auto uuid = get<3>(*it);
		auto element = this->page()->mainFrame()->findFirstElement(selector);
		auto currentValue = getter(element).toStdString();
		if(currentValue != watchValues[uuid] || ev->key() == Qt::Key_Enter || ev->key() == Qt::Key_Return)
		{
			watchValues[uuid] = currentValue;
			callback(currentValue, ev);
		}
	}
}

// This file extends the QWebView class to add additional functionality.

#include "stdafx.h"
using namespace std;
void QWebViewWithHooks::watch(string selector, Getter getter, Callback callback){
	int uuid = watchUuid++;
	watches.push_back(make_tuple(QString::fromStdString(selector), getter, callback, uuid) );
	watchValues[uuid] = "";
	//TODO: Change to return unwatch function. However, quite lazy.
}

void QWebViewWithHooks::keyReleaseEvent(QKeyEvent * ev)
{
	// Look for all watches and get values that are changed.
	// If there is a change, call the callback.
	for(auto it = watches.begin(); it != watches.end(); ++it) {
		auto selector = get<0>(*it);
		auto getter = get<1>(*it);
		auto callback = get<2>(*it);
		auto uuid = get<3>(*it);
		auto element = this->page()->mainFrame()->findFirstElement(selector);
		auto currentValue = getter(element).toStdString();
		if(currentValue != watchValues[uuid])
		{
			watchValues[uuid] = currentValue;
			callback(currentValue, ev);
		}
	}
}

Fix tack poh's merge conflict which he is aware of but doesn't want to fix.


/*
 * Chemharp, an efficient IO library for chemistry file formats
 * Copyright (C) 2015 Guillaume Fraux
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/
*/

#include "chemharp-python.hpp"

void register_trajectory() {
    /* Trajectory class *******************************************************/
    py::class_<Trajectory, boost::noncopyable>("Trajectory",
            py::init<string, py::optional<string, string>>())
        .def("read_next_step", &Trajectory::read_next_step)
        .def("read_at_step", &Trajectory::read_at_step)
        .def("write_step", &Trajectory::write_step)
        .def("done", &Trajectory::done)
        .def("close", &Trajectory::close)
        .def("nsteps", &Trajectory::nsteps)
        .def("topology",
            static_cast<void (Trajectory::*)(const Topology&)>(&Trajectory::topology))
        .def("topology",
            static_cast<void (Trajectory::*)(const string&)>(&Trajectory::topology))
    ;
}

/*
 * Chemharp, an efficient IO library for chemistry file formats
 * Copyright (C) 2015 Guillaume Fraux
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/
*/

#include "chemharp-python.hpp"

void register_trajectory() {
    /* Trajectory class *******************************************************/
    py::class_<Trajectory, boost::noncopyable>("Trajectory",
            py::init<string, py::optional<string, string>>())
        .def("read", &Trajectory::read)
        .def("read_at", &Trajectory::read_at)
        .def("write", &Trajectory::write)
        .def("done", &Trajectory::done)
        .def("close", &Trajectory::close)
        .def("nsteps", &Trajectory::nsteps)
        .def("topology",
            static_cast<void (Trajectory::*)(const Topology&)>(&Trajectory::topology))
        .def("topology",
            static_cast<void (Trajectory::*)(const string&)>(&Trajectory::topology))
    ;
}

Update the Python interface with the new names


/*
 * URELogger.cc
 *
 * Copyright (C) 2016 OpenCog Foundation
 *
 * Author: Nil Geisweiller
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License v3 as
 * published by the Free Software Foundation and including the exceptions
 * at http://opencog.org/wiki/Licenses
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program; if not, write to:
 * Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
 */

#include "URELogger.h"

using namespace opencog;

// Create and return the single instance
Logger& opencog::ure_logger()
{
	auto bc_logger_instantiate = []() {
		Logger tmp;
		tmp.set_component("URE");
		return tmp;
	};
	static Logger bc_instance(bc_logger_instantiate());
    return bc_instance;
}

/*
 * URELogger.cc
 *
 * Copyright (C) 2016 OpenCog Foundation
 *
 * Author: Nil Geisweiller
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License v3 as
 * published by the Free Software Foundation and including the exceptions
 * at http://opencog.org/wiki/Licenses
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program; if not, write to:
 * Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
 */

#include "URELogger.h"

using namespace opencog;

// Create and return the single instance
Logger& opencog::ure_logger()
{
	auto ure_logger_instantiate = []() {
		Logger tmp;
		tmp.set_component("URE");
		return tmp;
	};
	static Logger ure_instance(ure_logger_instantiate());
    return ure_instance;
}

Rename bc_* by ure_* in ure_logger()


#include <iostream>

using namespace std;

class BankAccount {
  char clientName[23];
  char id[15];
  double account;

public:

  BankAccount(const char _clientName[], const char _id[], double _account) {
    strcpy(clientName, _clientName);
    strcpy(id, _id);
    account = _account;
  }

  void print() {
    cout << "Name: " << clientName << '\n' <<
            "Account ID: " << id << '\n' <<
            "Account: " << account << '\n';
  }

  void transfer(double amount) {
    account += amount;
  }

  void draw(double amount) {
    account -= amount;
  }
};

int main() {
  BankAccount bankAccount("Ivan", "1", 2000);
  bankAccount.print();

  bankAccount.transfer(300);
  bankAccount.print();

  bankAccount.draw(500);
  bankAccount.print();

  return 0;
}

#include <iostream>

using namespace std;

class BankAccount {
  char clientName[23];
  char id[15];
  double account;

public:

  BankAccount(const char _clientName[], const char _id[], double _account) {
    strcpy(clientName, _clientName);
    strcpy(id, _id);
    account = _account;
  }

  void print() {
    cout << "Name: " << clientName << '\n' <<
            "Account ID: " << id << '\n' <<
            "Account: " << account << '\n';
  }

  void transfer(double amount) {
    account += amount;
  }

  void draw(double amount) {
    if (account >= amount) {
      account -= amount;
    }
  }
};

int main() {
  BankAccount bankAccount("Ivan", "1", 2000);
  bankAccount.print();

  bankAccount.transfer(300);
  bankAccount.print();

  bankAccount.draw(500);
  bankAccount.print();

  return 0;
}

Add validation for draw method. Don't draw amount if there is not enough in account


/**
 * \file tiles_costs.cpp
 *
 *
 *
 * \author eaburns
 * \date 05-01-2010
 */

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

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

#include "tiles_costs.h"

struct cost_tab_ent {
	string name;
	TilesCostFunction &fun;
};

static TilesUnitCost unit_cost = TilesUnitCost();
static TilesSqrtCost sqrt_cost = TilesSqrtCost();
static TilesInverseCost inverse_cost = TilesInverseCost();

// Table of cost functions.
static cost_tab_ent cost_functions[] = {
	{ "", unit_cost }, // default value
	{ "unit", unit_cost },
	{ "sqrt", sqrt_cost },
	{ "inverse", inverse_cost },
};

TilesCostFunction &get_cost_function_by_name(string name)
{
	unsigned int n = sizeof(cost_functions) / sizeof(*cost_functions);
	unsigned int i;

	for (i = 0; i < n; i += 1)
		if (cost_functions[i].name == name)
			return cost_functions[i].fun;

	exit(EXIT_FAILURE);
}

/**
 * \file tiles_costs.cpp
 *
 *
 *
 * \author eaburns
 * \date 05-01-2010
 */

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

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

#include "tiles_costs.h"

struct cost_tab_ent {
	string name;
	TilesCostFunction &fun;
};

static TilesUnitCost unit_cost = TilesUnitCost();
static TilesSqrtCost sqrt_cost = TilesSqrtCost();
static TilesInverseCost inverse_cost = TilesInverseCost();

// Table of cost functions.
static cost_tab_ent cost_functions[] = {
	{ "", unit_cost }, // default value
	{ "unit", unit_cost },
	{ "sqrt", sqrt_cost },
	{ "inverse", inverse_cost },
};

TilesCostFunction &get_cost_function_by_name(string name)
{
	unsigned int n = sizeof(cost_functions) / sizeof(*cost_functions);
	unsigned int i;

	for (i = 0; i < n; i += 1)
		if (cost_functions[i].name == name)
			return cost_functions[i].fun;

	std::cerr << "Bad cost function: " << name << std::endl;
	exit(EXIT_FAILURE);
}

Print an error on a bad tiles cost function name instead of silently quitting.


#include "google/gtest/gtest.h"

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

#include "google/gtest/gtest.h"
#include <messmer/cpp-utils/assert/backtrace.h>

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

Test cases print stack trace on sigsegv


/* * This file is part of Maliit framework *
 *
 * Copyright (C) 2014 Dinesh Manajipet <saidinesh5@gmail.com>
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License version 2.1 as published by the Free Software Foundation
 * and appearing in the file LICENSE.LGPL included in the packaging
 * of this file.
 */

#include "mirplatform.h"
#include "mirplatformconnection.h"

#include <QRegion>
#include <QWindow>

namespace Maliit {

MirPlatform::MirPlatform():
    AbstractPlatform(),
    m_mirPlatformConnection(new MirPlatformConnection)
{
}

void MirPlatform::setupInputPanel(QWindow *window, Maliit::Position position)
{
    Q_UNUSED(window)
    Q_UNUSED(position)
}

void MirPlatform::setInputRegion(QWindow *window, const QRegion &region)
{
    Q_UNUSED(window)

    if (!region.rects().isEmpty()) {
        m_mirPlatformConnection->setGeometry(region.rects().first());
    }
}

}

/* * This file is part of Maliit framework *
 *
 * Copyright (C) 2014 Dinesh Manajipet <saidinesh5@gmail.com>
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License version 2.1 as published by the Free Software Foundation
 * and appearing in the file LICENSE.LGPL included in the packaging
 * of this file.
 */

#include "mirplatform.h"
#include "mirplatformconnection.h"

#include <QRegion>
#include <QWindow>
#include <QVariant>

#include <ubuntu/application/ui/window_properties.h>

namespace Maliit {

MirPlatform::MirPlatform():
    AbstractPlatform(),
    m_mirPlatformConnection(new MirPlatformConnection)
{
}

void MirPlatform::setupInputPanel(QWindow *window, Maliit::Position position)
{
    Q_UNUSED(position)
    window->setProperty("role", QVariant(U_ON_SCREEN_KEYBOARD_ROLE));
}

void MirPlatform::setInputRegion(QWindow *window, const QRegion &region)
{
    Q_UNUSED(window)

    if (!region.rects().isEmpty()) {
        m_mirPlatformConnection->setGeometry(region.rects().first());
    }
}

}

Set window role for Mir backend


#include "MMU.hpp"

#include <iterator>
#include <limits>

namespace Core8 {

Chip8::BYTE MMU::readByte(const std::size_t address) const {
  const auto byte = memory.at(address);

  return byte;
}

Chip8::WORD MMU::readWord(const std::size_t address) const {
  const auto msb = memory.at(address) << std::numeric_limits<Chip8::BYTE>::digits;
  const auto lsb = memory.at(address + 1);

  return msb | lsb;
}

void MMU::writeByte(const Chip8::BYTE byte, const std::size_t address) {
  memory.at(address) = byte;
}

void MMU::load(std::istream& rom, const std::size_t address) {
  std::noskipws(rom);

  std::copy(std::istream_iterator<Chip8::BYTE>(rom),
            std::istream_iterator<Chip8::BYTE>(),
            &memory.at(address));
}

void MMU::clear() {
  memory.fill(0x0);
}

} // namespace Core8

#include "MMU.hpp"

#include <algorithm>
#include <iterator>
#include <limits>
#include <vector>

namespace Core8 {

Chip8::BYTE MMU::readByte(const std::size_t address) const {
  const auto byte = memory.at(address);

  return byte;
}

Chip8::WORD MMU::readWord(const std::size_t address) const {
  const auto msb = memory.at(address) << std::numeric_limits<Chip8::BYTE>::digits;
  const auto lsb = memory.at(address + 1);

  return msb | lsb;
}

void MMU::writeByte(const Chip8::BYTE byte, const std::size_t address) {
  memory.at(address) = byte;
}

void MMU::load(std::istream& rom, const std::size_t address) {
  std::noskipws(rom);

  const std::vector<Chip8::BYTE> data{std::istream_iterator<Chip8::BYTE>(rom),
                                      std::istream_iterator<Chip8::BYTE>()};

  const auto availableMemory = memory.size() - address;
  const auto dataSize = data.size();
  const auto length = dataSize > availableMemory ? availableMemory : dataSize;

  std::copy_n(std::begin(data), length,
              std::next(std::begin(memory), address));
}

void MMU::clear() {
  memory.fill(0x0);
}

} // namespace Core8

Fix load rom memory boundaries


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

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

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

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

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

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

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

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

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

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

        Network::~Network()
        {
#ifdef _WIN32
            WSACleanup();
#endif
        }

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

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

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

Call WSACleanup only on Windows


#include <SFML/Graphics.hpp>
#include <SFML/System/Clock.hpp>
#include <iostream>

int main() {
    sf::RenderWindow window(sf::VideoMode(800,600),  "Psychic Dangerzone");
    window.setVerticalSyncEnabled(true);

    sf::Clock world_clock;

    float last_frame_time;
    while(window.isOpen()) {
        last_frame_time = world_clock.getElapsedTime().asSeconds();

        sf::Event event;
        while(window.pollEvent(event)) {
            // TODO: process events
            if(event.type == sf::Event::Closed) {
                window.close();
            }
        }

        window.clear(sf::Color::Black);
        window.display();
        std::cout << world_clock.getElapsedTime().asSeconds() - last_frame_time << std::endl;
    }

    return 0;
}

#include <SFML/Graphics.hpp>
#include <SFML/System/Clock.hpp>
#include <iostream>

int main() {
    sf::RenderWindow window(sf::VideoMode(800,600),  "Psychic Dangerzone");
    window.setVerticalSyncEnabled(true);

    sf::Clock world_clock;

    sf::CircleShape player(50);

    float last_frame_time;
    while(window.isOpen()) {
        last_frame_time = world_clock.getElapsedTime().asSeconds();

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

        sf::Vector2f velocity;
        if (sf::Keyboard::isKeyPressed(sf::Keyboard::Left)) {
          velocity.x -= 10;
        }
        if (sf::Keyboard::isKeyPressed(sf::Keyboard::Right)) {
          velocity.x += 10;
        }
        if (sf::Keyboard::isKeyPressed(sf::Keyboard::Up)) {
          velocity.y -= 10;
        }
        if (sf::Keyboard::isKeyPressed(sf::Keyboard::Down)) {
          velocity.y += 10;
        }

        player.move(velocity);
        //player.move(velocity.x, velocity.y);

        window.clear(sf::Color::Black);

        window.draw(player);

        window.display();
        std::cout << world_clock.getElapsedTime().asSeconds() - last_frame_time << std::endl;
    }

    return 0;
}

Add a player circle that can move


#include "gtest/gtest.h"
#include "lms/endian.h"

TEST(Endian, uint16) {
    using lms::Endian;
    ASSERT_EQ(uint16_t(0xCAFEu), Endian::betoh(Endian::htobe(uint16_t(0xCAFEu))));
    ASSERT_EQ(uint16_t(0xCAFEu), Endian::letoh(Endian::htole(uint16_t(0xCAFEu))));
}

TEST(Endian, uint32) {
    using lms::Endian;
    ASSERT_EQ(uint32_t(0xDEADBEEFu), Endian::betoh(Endian::htobe(uint32_t(0xDEADBEEFu))));
    ASSERT_EQ(uint32_t(0xDEADBEEFu), Endian::letoh(Endian::htole(uint32_t(0xDEADBEEFu))));
}

TEST(Endian, uint64) {
    using lms::Endian;
    ASSERT_EQ(uint64_t(0xFEEDCAFEDEADBEEFu), Endian::betoh(Endian::htobe(uint64_t(0xFEEDCAFEDEADBEEFu))));
    ASSERT_EQ(uint64_t(0xFEEDCAFEDEADBEEFu), Endian::letoh(Endian::htole(uint64_t(0xFEEDCAFEDEADBEEFu))));
}

#include "gtest/gtest.h"
#include "lms/endian.h"

TEST(Endian, uint16) {
    using lms::Endian;
    ASSERT_EQ(0xFECAu, Endian::letoh(Endian::htobe(uint16_t(0xCAFEu))));
    ASSERT_EQ(0xFECAu, Endian::betoh(Endian::htole(uint16_t(0xCAFEu))));
}

TEST(Endian, uint32) {
    using lms::Endian;
    ASSERT_EQ(0xEFBEADDEu, Endian::letoh(Endian::htobe(uint32_t(0xDEADBEEFu))));
    ASSERT_EQ(0xEFBEADDEu, Endian::betoh(Endian::htole(uint32_t(0xDEADBEEFu))));
}

TEST(Endian, uint64) {
    using lms::Endian;
    ASSERT_EQ(0xEFBEADDEFECAEDFEu, Endian::letoh(Endian::htobe(0xFEEDCAFEDEADBEEFu)));
    ASSERT_EQ(0xEFBEADDEFECAEDFEu, Endian::betoh(Endian::htole(0xFEEDCAFEDEADBEEFu)));
}

Improve test cases for lms::Endian


#include "linalg/ray.h"
#include "geometry/differential_geometry.h"
#include "geometry/geometry.h"
#include "scene.h"
#include "integrator/surface_integrator.h"
#include "renderer/renderer.h"

Renderer::Renderer(std::unique_ptr<SurfaceIntegrator> surface_integrator)
	: surface_integrator(std::move(surface_integrator))
{}
Colorf Renderer::illumination(RayDifferential &ray, const Scene &scene) const {
	DifferentialGeometry dg;
	if (scene.get_root().intersect(ray, dg)){
		dg.compute_differentials(ray);
		return surface_integrator->illumination(scene, *this, ray, dg);
	}
	else {
		//TODO: Compute light along the ray coming from lights
		return Colorf{0};
	}
}

#include "linalg/ray.h"
#include "geometry/differential_geometry.h"
#include "geometry/geometry.h"
#include "scene.h"
#include "integrator/surface_integrator.h"
#include "renderer/renderer.h"

Renderer::Renderer(std::unique_ptr<SurfaceIntegrator> surface_integrator)
	: surface_integrator(std::move(surface_integrator))
{}
Colorf Renderer::illumination(RayDifferential &ray, const Scene &scene) const {
	DifferentialGeometry dg;
	if (scene.get_root().intersect(ray, dg)){
		dg.compute_differentials(ray);
		return surface_integrator->illumination(scene, *this, ray, dg);
	}
	else if (scene.get_environment()){
		//TODO: Compute light along the ray coming from lights
		DifferentialGeometry dg;
		dg.point = Point{ray.d.x, ray.d.y, ray.d.z};
		return scene.get_environment()->sample(dg);
	}
	return Colorf{0};
}

Fix regression of not taking into account environment map


// RUN: %clang_cc1 -fsyntax-only -verify -std=c++98 %s

// Verify that we can't initialize non-aggregates with an initializer
// list.
struct NonAggr1 {
  NonAggr1(int) { }

  int m;
};

struct Base { };
struct NonAggr2 : public Base {
  int m;
};

class NonAggr3 {
  int m;
};

struct NonAggr4 {
  int m;
  virtual void f();
};

NonAggr1 na1 = { 17 }; // expected-error{{non-aggregate type 'struct NonAggr1' cannot be initialized with an initializer list}}
NonAggr2 na2 = { 17 }; // expected-error{{non-aggregate type 'struct NonAggr2' cannot be initialized with an initializer list}}
NonAggr3 na3 = { 17 }; // expected-error{{non-aggregate type 'class NonAggr3' cannot be initialized with an initializer list}}
NonAggr4 na4 = { 17 }; // expected-error{{non-aggregate type 'struct NonAggr4' cannot be initialized with an initializer list}}

// PR5817
typedef int type[][2];
const type foo = {0};

Add testcase for PR5817, although the bug was already fixed


#include "generator.h"

#include <iostream>
#include <fstream>

using namespace Mugen;

CharacterGenerator::CharacterGenerator(const std::string & filename):
filename(filename){
}

CharacterGenerator::~CharacterGenerator(){
}

void CharacterGenerator::output(const std::string & file){
    Mugen::PythonStream out;
    out.open(file);
    out << "import mugen" << PythonStream::endl;
    out <<  "class TestCharacter(mugen.Character):" << PythonStream::endl;
    out << PythonStream::indent;
    out << "def __init__(self):" << PythonStream::endl;
    out << PythonStream::indent;
    out << "self.setName('TestCharacter')" << PythonStream::endl;
    out.clearIndents();
    out << "char = TestCharacter()" << PythonStream::endl;
    out << "print char.name" << PythonStream::endl;
    out.close();
}

Indent code to more or less visualize the indentation of the outputed python code.


#include <istream>
#include <fstream>
#include <set>
#include <vector>
#include <array>
#include <algorithm>
#include <iterator>

using namespace std;

int main() {
	ifstream cin("combo.in");
	ofstream cout("combo.out");

	int size;
	cin >> size;

	set<int> options;
	for (int i = 0; i < 2; i++) {
		int a, b, c;
		cin >> a >> b >> c;

		// creates permutations of allowable combinations and turns them into
		// an integer so that set can compare them and only retain uniques

		// the indexes here start at -3 and end at +1 because the input starts
		// at 1 but here we want it to start at 0
		for (int i = a - 3; i <= a + 1; i++) {
			for (int j = b - 3; j <= b + 1; j++) {
				for (int k = c - 3; k <= c + 1; k++) {
					options.insert(((((i % size) + size) % size) << 0) +
								   ((((j % size) + size) % size) << 8) +
								   ((((k % size) + size) % size) << 16));
				}
			}
		}
	}

	// the size of the set is the number of unique combinations
	cout << options.size() << endl;

	return 0;
}

#include <fstream>
#include <set>

using namespace std;

int main() {
	ifstream cin("combo.in");
	ofstream cout("combo.out");

	int size;
	cin >> size;

	set<int> options;
	for (int i = 0; i < 2; i++) {
		int a, b, c;
		cin >> a >> b >> c;

		// creates permutations of allowable combinations and turns them into
		// an integer so that set can compare them and only retain uniques

		// the indexes here start at -3 and end at +1 because the input starts
		// at 1 but here we want it to start at 0
		for (int i = a - 3; i <= a + 1; i++) {
			for (int j = b - 3; j <= b + 1; j++) {
				for (int k = c - 3; k <= c + 1; k++) {
					options.insert(((((i % size) + size) % size) << 0) +
								   ((((j % size) + size) % size) << 8) +
								   ((((k % size) + size) % size) << 16));
				}
			}
		}
	}

	// the size of the set is the number of unique combinations
	cout << options.size() << endl;

	return 0;
}

Remove unused includes from the C++11 solution for Nov. 2013 Bronze Problem 1


/*
 * ModSecurity, http://www.modsecurity.org/
 * Copyright (c) 2015 Trustwave Holdings, Inc. (http://www.trustwave.com/)
 *
 * You may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * If any of the files related to licensing are missing or if you have any
 * other questions related to licensing please contact Trustwave Holdings, Inc.
 * directly using the email address security@modsecurity.org.
 *
 */

#include "regression/custom_debug_log.h"

#include <iostream>
#include <string>

#include "modsecurity/debug_log.h"
#include "utils/regex.h"

namespace modsecurity_test {

CustomDebugLog *CustomDebugLog::new_instance() {
    return new CustomDebugLog();
}

void CustomDebugLog::write(int level, const std::string& message) {
    m_log << "[" << level << "] " << message << std::endl;
}

bool CustomDebugLog::contains(const std::string& pattern) {
    ModSecurity::Utils::Regex re(pattern);
    ModSecurity::Utils::SMatch match;
    std::string s = m_log.str();
    return (ModSecurity::Utils::regex_search(s, &match, re)
        && match.size() >= 1);
}

std::string CustomDebugLog::log_messages() {
    return m_log.str();
}

}  // namespace modsecurity_test

/*
 * ModSecurity, http://www.modsecurity.org/
 * Copyright (c) 2015 Trustwave Holdings, Inc. (http://www.trustwave.com/)
 *
 * You may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * If any of the files related to licensing are missing or if you have any
 * other questions related to licensing please contact Trustwave Holdings, Inc.
 * directly using the email address security@modsecurity.org.
 *
 */

#include "regression/custom_debug_log.h"

#include <iostream>
#include <string>

#include "modsecurity/debug_log.h"
#include "utils/regex.h"

namespace modsecurity_test {

CustomDebugLog *CustomDebugLog::new_instance() {
    return new CustomDebugLog();
}

void CustomDebugLog::write(int level, const std::string& message) {
    m_log << "[" << level << "] " << message << std::endl;
}

bool CustomDebugLog::contains(const std::string& pattern) {
    ModSecurity::Utils::Regex re(pattern);
    ModSecurity::Utils::SMatch match;
    std::string s = m_log.str();
    return ModSecurity::Utils::regex_search(s, re);
}

std::string CustomDebugLog::log_messages() {
    return m_log.str();
}

}  // namespace modsecurity_test

Fix the regression test regexp validation


// RUN: clang-diff -ast-dump %s -- \
// RUN: | %python -c 'import json, sys; json.dump(json.loads(sys.stdin.read()), sys.stdout, sort_keys=True, indent=2)' \
// RUN: | FileCheck %s

// CHECK: "begin": 294,
// CHECK: "type": "CXXRecordDecl",
// CHECK: "type": "FieldDecl",
// CHECK: "end": 314,
class A {
  int x;
};

// CHECK: "children": [
// CHECK-NEXT: {
// CHECK-NEXT: "begin":
// CHECK-NEXT: "children": []
// CHECK-NEXT: "end":
// CHECK-NEXT: "id":
// CHECK-NEXT: "type": "CharacterLiteral"
// CHECK-NEXT: }
// CHECK: ]
// CHECK: "type": "VarDecl",
char nl = '\n';

// CHECK: "value": "abc \n\t\u0000\u001f\u0123 \ub370\ubc15"
char s[] = "abc \n\t\0\x1f\u0123 데박";

// RUN: clang-diff -ast-dump %s -- \
// RUN: | %python -c 'import json, sys; json.dump(json.loads(sys.stdin.read()), sys.stdout, sort_keys=True, indent=2)' \
// RUN: | FileCheck %s

// CHECK: "begin": 294,
// CHECK: "type": "CXXRecordDecl",
// CHECK: "type": "FieldDecl",
// CHECK: "end": 314,
class A {
  int x;
};

// CHECK: "children": [
// CHECK-NEXT: {
// CHECK-NEXT: "begin":
// CHECK-NEXT: "children": []
// CHECK-NEXT: "end":
// CHECK-NEXT: "id":
// CHECK-NEXT: "type": "CharacterLiteral"
// CHECK-NEXT: }
// CHECK: ]
// CHECK: "type": "VarDecl",
char nl = '\n';

// CHECK: "value": "abc \n\t\u0000\u001f"
char s[] = "abc \n\t\0\x1f";

Fix test for python 3


/*
// This file is part of SnakePredictor
//
//  (c) Daniel McAssey <hello@glokon.me>
//
// For the full copyright and license information, please view the LICENSE
// file that was distributed with this source code.
*/
// stdafx.cpp : source file that includes just the standard includes
// CallWinsock.pch will be the pre-compiled header
// stdafx.obj will contain the pre-compiled type information

#include "stdafx.h"

// TODO: reference any additional headers you need in STDAFX.H
// and not in this file

/*
// This file is part of SnakePredictor
//
//  (c) Daniel McAssey <hello@glokon.me>
//
// For the full copyright and license information, please view the LICENSE
// file that was distributed with this source code.
*/
// stdafx.cpp : source file that includes just the standard includes
// SnakePredictor.pch will be the pre-compiled header
// stdafx.obj will contain the pre-compiled type information

#include "stdafx.h"

// TODO: reference any additional headers you need in STDAFX.H
// and not in this file

Fix incorrect comment on precompiled header


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

#include "datastore.h"

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

namespace YouDataStoreTests {
TEST_CLASS(DataStoreApiTest) {
public:
	TEST_METHOD(DataStoreDummyTest) {
		// You::DataStore::DataStore sut;
		// sut.post(std::unordered_map<std::wstring, std::wstring>());
		Assert::IsTrue(true);
	}
};
}  // namespace YouDataStoreTests

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

#include "datastore.h"

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

namespace YouDataStoreTests {
TEST_CLASS(DataStoreApiTest) {
public:
	TEST_METHOD(DataStore_Post_Basic_Test) {
		You::DataStore::DataStore sut;
		bool result = sut.post(0, DataStore::STask());
		Assert::IsTrue(result);
	}

	TEST_METHOD(DataStore_Post_DuplicateId_Test) {
		You::DataStore::DataStore sut;
		sut.post(0, DataStore::STask());
		bool result = sut.post(0, DataStore::STask());
		Assert::IsFalse(result);
	}
};
}  // namespace YouDataStoreTests

Add unit test for post method


#include <ionWindow.h>
#include <ionGraphicsGL.h>

using namespace ion;

int main()
{
	Log::AddDefaultOutputs();

	SingletonPointer<CWindowManager> WindowManager;
	SingletonPointer<CGraphicsAPI> GraphicsAPI;

	GraphicsAPI->Init(new Graphics::COpenGLImplementation());
	WindowManager->Init(GraphicsAPI);
	WindowManager->CreateWindow(vec2i(640, 480), "TestWindowManager", EWindowType::Windowed);

	while (! WindowManager->ShouldClose())
		WindowManager->PollEvents();

	return 0;
}

#include <ionWindow.h>
#include <ionGraphicsGL.h>

using namespace ion;

int main()
{
	Log::AddDefaultOutputs();

	Log::Info("Info");
	Log::Warn("Warning");
	Log::Error("Error");

	SingletonPointer<CWindowManager> WindowManager;
	SingletonPointer<CGraphicsAPI> GraphicsAPI;

	GraphicsAPI->Init(new Graphics::COpenGLImplementation());
	WindowManager->Init(GraphicsAPI);
	WindowManager->CreateWindow(vec2i(640, 480), "TestWindowManager", EWindowType::Windowed);

	while (! WindowManager->ShouldClose())
	{
		WindowManager->PollEvents();
	}

	return 0;
}

Add example of log channels


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

//$Id$

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

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

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

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

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

//$Id$

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

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

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

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

Add support for halo's to TextSymbolizer().


#include <boost/config.hpp>

struct Foo {
  char x;
#include <leathers/push>
#include <leathers/padded>
  long y;
#include <leathers/pop>
};

int main() {
  // struct Foo must be used, otherwise there will be no warning (clang)
  return static_cast<int>(Foo().y);
}

#include <boost/config.hpp>

struct Foo {
  char x;
#include <leathers/push>
#if !defined(SHOW_WARNINGS)
# include <leathers/padded>
#endif
  long y;
#include <leathers/pop>
};

int main() {
  // struct Foo must be used, otherwise there will be no warning (clang)
  return static_cast<int>(Foo().y);
}

Check SHOW_WARNINGS macro in example


// Copyright (c) 2018 Chris Ohk, Youngjoong Kim, SeungHyun Jeon

// We are making my contributions/submissions to this project solely in our
// personal capacity and are not conveying any rights to any intellectual
// property of any third parties.

#include <Utils/TestUtils.hpp>
#include "gtest/gtest.h"

#include <hspp/Cards/Minion.hpp>
#include <hspp/Managers/GameAgent.hpp>
#include <hspp/Tasks/SimpleTasks/ControlTask.hpp>

using namespace Hearthstonepp;
using namespace SimpleTasks;
using namespace TestUtils;

TEST(ControlTask, GetTaskID)
{
    const ControlTask control(EntityType::TARGET);
    EXPECT_EQ(control.GetTaskID(), +TaskID::CONTROL);
}

TEST(ControlTask, Run)
{
    GameAgent agent(CardClass::ROGUE, CardClass::DRUID, PlayerType::PLAYER1);
    Player& player1 = agent.GetPlayer1();
    Player& player2 = agent.GetPlayer2();

    std::vector<Card> cards;
    cards.reserve(5);

    const std::string name = "test";
    for (size_t i = 0; i < 5; ++i)
    {
        const auto id = static_cast<char>(i + 0x30);
        cards.emplace_back(GenerateMinionCard(name + id, 1, 1));
        PlayMinionCard(player1, cards[i]);
        PlayMinionCard(player2, cards[i]);
    }

    ControlTask control(EntityType::TARGET);
    control.SetTarget(player2.GetField()[0]);
    MetaData result = control.Run(player1);

    EXPECT_EQ(result, MetaData::CONTROL_SUCCESS);
    EXPECT_EQ(player1.GetField().size(), 6u);
    EXPECT_EQ(player2.GetField().size(), 4u);
}

Add unit test for ControlTask


#include <avr/io.h>

#include "lcd.h"

LCD5110 myGLCD;

void LCD_init(void)
{
  /* Set MOSI and SCK output */
  DDRB |= (1<<PB3)|(1<<PB5);

  /* Enable SPI, Master, CPOL=1, CPHA=1 */
  /* Also: MSB first, clock=fosc/4 */
  SPCR = (1<<SPE)|(1<<MSTR)|(1<<CPOL)|(1<<CPHA) | 3;

  /* Set the pins for DC, RST and CS to output */
  DDRB |= (1<<PB0) | (1<<PB2);
  DDRC |= (1<<PC0);

  myGLCD.InitLCD(0x46);
}

#include <avr/io.h>

#include "lcd.h"

LCD5110 myGLCD;

void LCD_init(void)
{
  /* Set MOSI and SCK output */
  DDRB |= (1<<PB3)|(1<<PB5);

  /* Enable SPI, Master, CPOL=1, CPHA=1 */
  /* Also: MSB first, clock=fosc/4 */
  SPCR = (1<<SPE)|(1<<MSTR)|(1<<CPOL)|(1<<CPHA) | (1<<SPR0);

  /* Set the pins for DC, RST and CS to output */
  DDRB |= (1<<PB0) | (1<<PB2);
  DDRC |= (1<<PC0);

  myGLCD.InitLCD(0x46);
}

Use a faster SPI clock to the LCD


#include "chunk.hpp"
#include "chunk_master.hpp"
#include "code/ylikuutio/hierarchy/hierarchy_templates.hpp"

namespace yli
{
    namespace ontology
    {
        void Chunk::bind_to_parent()
        {
            // requirements:
            // `this->parent` must not be `nullptr`.
            yli::ontology::ChunkMaster* const chunk_master = this->parent;

            if (chunk_master == nullptr)
            {
                std::cerr << "ERROR: `Chunk::bind_to_parent`: `chunk_master` is `nullptr`!\n";
                return;
            }

            // get `childID` from the `ChunkMaster` and set pointer to this `Chunk`.
            chunk_master->bind_chunk(this);
        }

        Chunk::~Chunk()
        {
            // destructor.

            // set pointer to this `Chunk` to nullptr.
            this->parent->set_chunk_pointer(this->childID, nullptr);
        }

        void Chunk::render()
        {
            if (this->vram_buffer_in_use)
            {
                // Render this `Chunk`.
                // If any vertex of the `Chunk` has changed, the vertex data
                // of the `Chunk` needs to be reconstructed before rendering.
            }
        }
    }
}

#include "chunk.hpp"
#include "chunk_master.hpp"
#include "code/ylikuutio/hierarchy/hierarchy_templates.hpp"

namespace yli
{
    namespace ontology
    {
        void Chunk::bind_to_parent()
        {
            // requirements:
            // `this->parent` must not be `nullptr`.
            yli::ontology::ChunkMaster* const chunk_master = this->parent;

            if (chunk_master == nullptr)
            {
                std::cerr << "ERROR: `Chunk::bind_to_parent`: `chunk_master` is `nullptr`!\n";
                return;
            }

            // get `childID` from the `ChunkMaster` and set pointer to this `Chunk`.
            chunk_master->bind_chunk(this);
        }

        Chunk::~Chunk()
        {
            // destructor.
            //
            // requirements:
            // `this->parent` must not be `nullptr`.
            yli::ontology::ChunkMaster* const chunk_master = this->parent;

            if (chunk_master == nullptr)
            {
                std::cerr << "ERROR: `Chunk::~Chunk`: `chunk_master` is `nullptr`!\n";
                return;
            }

            chunk_master->unbind_chunk(this->childID);
        }

        void Chunk::render()
        {
            if (this->vram_buffer_in_use)
            {
                // Render this `Chunk`.
                // If any vertex of the `Chunk` has changed, the vertex data
                // of the `Chunk` needs to be reconstructed before rendering.
            }
        }
    }
}

Check `parent` for `nullptr`. Cleaning up code.


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

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

using namespace std;

int main()
{

}

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

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

using namespace std;

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

Add a way of Input and program loop.


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

// debug.cpp: Debugging utilities.

#include "compiler/translator/compilerdebug.h"

#include <stdarg.h>
#include <stdio.h>

#include "compiler/translator/InitializeParseContext.h"
#include "compiler/translator/ParseContext.h"

static const int kTraceBufferLen = 1024;

#ifdef TRACE_ENABLED
extern "C" {
void Trace(const char *format, ...) {
    if (!format) return;

    TParseContext* parseContext = GetGlobalParseContext();
    if (parseContext) {
        char buf[kTraceBufferLen];
        va_list args;
        va_start(args, format);
        vsnprintf(buf, kTraceBufferLen, format, args);
        va_end(args);

        parseContext->trace(buf);
    }
}
}  // extern "C"
#endif  // TRACE_ENABLED

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

// debug.cpp: Debugging utilities.

#include "compiler/translator/compilerdebug.h"

#include <stdarg.h>
#include <stdio.h>

#include "compiler/translator/InitializeParseContext.h"
#include "compiler/translator/ParseContext.h"

#ifdef TRACE_ENABLED
static const int kTraceBufferLen = 1024;

extern "C" {
void Trace(const char *format, ...) {
    if (!format) return;

    TParseContext* parseContext = GetGlobalParseContext();
    if (parseContext) {
        char buf[kTraceBufferLen];
        va_list args;
        va_start(args, format);
        vsnprintf(buf, kTraceBufferLen, format, args);
        va_end(args);

        parseContext->trace(buf);
    }
}
}  // extern "C"
#endif  // TRACE_ENABLED

Fix unused variable warning in compiler/debug.cpp.


#include <miniMAT/util/NumDigits.hpp>

#include <cmath>

namespace miniMAT {
    namespace util {
        int NumDigits(double num) {
            return log10(num) + 1;
        }
    }
}

#include <miniMAT/util/NumDigits.hpp>

#include <cmath>

namespace miniMAT {
    namespace util {
        int NumDigits(double num) {
            return num == 0 ? 1 : fabs(log10(num)) + 1;
        }
    }
}

Fix bug involving printing 'zeroed' matrices


#include "RestServer.h"

#include <qhttpserver.hpp>
#include <qhttpserverrequest.hpp>
#include <qhttpserverresponse.hpp>
#include <QLoggingCategory>

Q_LOGGING_CATEGORY(REST, "ledify.restserver", QtWarningMsg)

using namespace qhttp::server;

RestServer::RestServer(QObject *parent) : QObject(parent) {
    m_server = new QHttpServer(this);
    m_server->listen(QHostAddress::Any, 8033, [this] (QHttpRequest* req, QHttpResponse* res) {
        emit requestReceived(req, res);
    });

    if ( m_server->isListening() ) {
        qCDebug(REST, "Started REST server");
    } else {
        qCWarning(REST, "Failed to start REST server");
    }
}

void RestServer::requestReceived(QHttpRequest *req, QHttpResponse *res) {
    QString urlString = req->url().toString();

    if (urlString.size() < 2) {
        res->setStatusCode(qhttp::ESTATUS_NOT_ACCEPTABLE);
        res->end("Send me more!\n");
        return;
    }
    auto command = urlString.mid(1);
    qCDebug(REST) << "Received command" << command;
    res->setStatusCode(qhttp::ESTATUS_OK);
    res->end(m_callback(command).toUtf8());
}

#include "RestServer.h"

#include <qhttpserver.hpp>
#include <qhttpserverrequest.hpp>
#include <qhttpserverresponse.hpp>
#include <QLoggingCategory>

Q_LOGGING_CATEGORY(REST, "ledify.restserver", QtWarningMsg)

using namespace qhttp::server;

RestServer::RestServer(QObject *parent) : QObject(parent) {
    m_server = new QHttpServer(this);
    m_server->listen(QHostAddress::Any, 8033, [this] (QHttpRequest* req, QHttpResponse* res) {
        emit requestReceived(req, res);
    });

    if ( m_server->isListening() ) {
        qCDebug(REST, "Started REST server");
    } else {
        qCWarning(REST, "Failed to start REST server");
    }
}

void RestServer::requestReceived(QHttpRequest *req, QHttpResponse *res) {
    QString urlString = req->url().toString();

    if (urlString.size() < 2) {
        res->setStatusCode(qhttp::ESTATUS_NOT_ACCEPTABLE);
        res->end("Send me more!\n");
        return;
    }
    auto commands = urlString.mid(1);

    QByteArray responses = "";
    foreach(auto command, commands.split("+", QString::SplitBehavior::SkipEmptyParts)) {
        qCDebug(REST) << "Received command" << command;
        responses += m_callback(command).toUtf8() + ";";
    }
    res->setStatusCode(qhttp::ESTATUS_OK);
    res->end(responses);
}

Allow multiple commands to be sent to the server


//===--- OpenMPKinds.cpp - Token Kinds Support ----------------------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
/// \file
/// \brief This file implements the OpenMP enum and support functions.
///
//===----------------------------------------------------------------------===//

#include "clang/Basic/OpenMPKinds.h"
#include "clang/Basic/IdentifierTable.h"
#include "clang/Lex/Token.h"
#include "llvm/ADT/StringSwitch.h"
#include "llvm/Support/ErrorHandling.h"
#include <cassert>

using namespace clang;

OpenMPDirectiveKind clang::getOpenMPDirectiveKind(StringRef Str) {
  return llvm::StringSwitch<OpenMPDirectiveKind>(Str)
#define OPENMP_DIRECTIVE(Name) \
           .Case(#Name, OMPD_##Name)
#include "clang/Basic/OpenMPKinds.def"
           .Default(OMPD_unknown);
}

const char *clang::getOpenMPDirectiveName(OpenMPDirectiveKind Kind) {
  assert(Kind < NUM_OPENMP_DIRECTIVES);
  switch (Kind) {
  case OMPD_unknown:
    return ("unknown");
#define OPENMP_DIRECTIVE(Name) \
  case OMPD_##Name : return #Name;
#include "clang/Basic/OpenMPKinds.def"
  default:
    break;
  }
  llvm_unreachable("Invalid OpenMP directive kind");
}

//===--- OpenMPKinds.cpp - Token Kinds Support ----------------------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
/// \file
/// \brief This file implements the OpenMP enum and support functions.
///
//===----------------------------------------------------------------------===//

#include "clang/Basic/OpenMPKinds.h"
#include "clang/Basic/IdentifierTable.h"
#include "llvm/ADT/StringRef.h"
#include "llvm/ADT/StringSwitch.h"
#include "llvm/Support/ErrorHandling.h"
#include <cassert>

using namespace clang;

OpenMPDirectiveKind clang::getOpenMPDirectiveKind(StringRef Str) {
  return llvm::StringSwitch<OpenMPDirectiveKind>(Str)
#define OPENMP_DIRECTIVE(Name) \
           .Case(#Name, OMPD_##Name)
#include "clang/Basic/OpenMPKinds.def"
           .Default(OMPD_unknown);
}

const char *clang::getOpenMPDirectiveName(OpenMPDirectiveKind Kind) {
  assert(Kind < NUM_OPENMP_DIRECTIVES);
  switch (Kind) {
  case OMPD_unknown:
    return ("unknown");
#define OPENMP_DIRECTIVE(Name) \
  case OMPD_##Name : return #Name;
#include "clang/Basic/OpenMPKinds.def"
  default:
    break;
  }
  llvm_unreachable("Invalid OpenMP directive kind");
}

Fix a layering violation introduced in r177705.


// vim:sw=2:ai

/*
 * Copyright (C) 2010 DeNA Co.,Ltd.. All rights reserved.
 * See COPYRIGHT.txt for details.
 */

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

#include "fatal.hpp"

namespace dena {

const int opt_syslog = LOG_ERR | LOG_PID | LOG_CONS;

void
fatal_exit(const std::string& message)
{
  fprintf(stderr, "FATAL_EXIT: %s\n", message.c_str());
  syslog(opt_syslog, "FATAL_EXIT: %s", message.c_str());
  _exit(1);
}

void
fatal_abort(const std::string& message)
{
  fprintf(stderr, "FATAL_COREDUMP: %s\n", message.c_str());
  syslog(opt_syslog, "FATAL_COREDUMP: %s", message.c_str());
  abort();
}

};

// vim:sw=2:ai

/*
 * Copyright (C) 2010 DeNA Co.,Ltd.. All rights reserved.
 * See COPYRIGHT.txt for details.
 */

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

#include "fatal.hpp"

namespace dena {

const int opt_syslog = LOG_ERR | LOG_PID | LOG_CONS;

void
fatal_exit(const std::string& message)
{
  fprintf(stderr, "FATAL_EXIT: %s\n", message.c_str());
  syslog(opt_syslog, "FATAL_EXIT: %s", message.c_str());
  _exit(1);
}

void
fatal_abort(const std::string& message)
{
  fprintf(stderr, "FATAL_COREDUMP: %s\n", message.c_str());
  syslog(opt_syslog, "FATAL_COREDUMP: %s", message.c_str());
  abort();
}

};

Add missing include (fixes compile failure with gcc 4.7).


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

#include "GameTable/GamblingTable.h"
#include <iostream>

using namespace std;

int main()
{
	cout << "Start Podrios." << endl;

	GamblingTable *gamblingTable_Ptr = new GamblingTable();

	return 0;
}

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

#include "GameTable/GamblingTable.h"
#include <iostream>

using namespace std;

int main()
{
	cout << "Start Podrios." << endl;

	GamblingTable gamblingTable;

	return 0;
}

Modify the way of GambilingTable construct.


// Copyright (c) 2011, Christian Rorvik
// Distributed under the Simplified BSD License (See accompanying file LICENSE.txt)

#include "crunch/concurrency/yield.hpp"

#include <windows.h>

namespace Crunch { namespace Concurrency {

void ThreadYield()
{
    SwitchToThread();
}

void ThreadSleep(Duration duration)
{
    Sleep(static_cast<DWORD>(duration.GetTotalMilliseconds()));
}

}}

// Copyright (c) 2011, Christian Rorvik
// Distributed under the Simplified BSD License (See accompanying file LICENSE.txt)

#include "crunch/concurrency/yield.hpp"

#include <windows.h>

namespace Crunch { namespace Concurrency {

void ThreadYield()
{
    ::SwitchToThread();
}

void ThreadSleep(Duration duration)
{
    if (duration.IsNegative())
        return;

    ::Sleep(static_cast<DWORD>(duration.GetTotalMilliseconds()));
}

}}

Check for negative duration in ThreadSleep on Windows


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

#include "SystemInitializerLLGS.h"

#if defined(__APPLE__)
#include "Plugins/ObjectFile/Mach-O/ObjectFileMachO.h"
using HostObjectFile = lldb_private::ObjectFileMachO;
#elif defined(_WIN32)
#include "Plugins/ObjectFile/PECOFF/ObjectFilePECOFF.h"
using HostObjectFile = lldb_private::ObjectFilePECOFF;
#else
#include "Plugins/ObjectFile/ELF/ObjectFileELF.h"
using HostObjectFile = ObjectFileELF;
#endif

using namespace lldb_private;

void SystemInitializerLLGS::Initialize() {
  SystemInitializerCommon::Initialize();
  HostObjectFile::Initialize();
}

void SystemInitializerLLGS::Terminate() {
  HostObjectFile::Terminate();
  SystemInitializerCommon::Terminate();
}

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

#include "SystemInitializerLLGS.h"

#if defined(__APPLE__)
#include "Plugins/ObjectFile/Mach-O/ObjectFileMachO.h"
using HostObjectFile = ObjectFileMachO;
#elif defined(_WIN32)
#include "Plugins/ObjectFile/PECOFF/ObjectFilePECOFF.h"
using HostObjectFile = ObjectFilePECOFF;
#else
#include "Plugins/ObjectFile/ELF/ObjectFileELF.h"
using HostObjectFile = ObjectFileELF;
#endif

using namespace lldb_private;

void SystemInitializerLLGS::Initialize() {
  SystemInitializerCommon::Initialize();
  HostObjectFile::Initialize();
}

void SystemInitializerLLGS::Terminate() {
  HostObjectFile::Terminate();
  SystemInitializerCommon::Terminate();
}

Fix windows/mac builds broken by r333182.


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

#include "sky/engine/tonic/dart_invoke.h"

#include "base/logging.h"
#include "base/trace_event/trace_event.h"
#include "sky/engine/tonic/dart_error.h"

namespace blink {

bool DartInvokeAppField(Dart_Handle target, Dart_Handle name,
                               int number_of_arguments,
                               Dart_Handle* arguments) {
  TRACE_EVENT0("sky", "DartInvoke::DartInvokeAppField");
  return LogIfError(Dart_Invoke(target, name, number_of_arguments, arguments));
}

bool DartInvokeAppClosure(Dart_Handle closure,
                          int number_of_arguments,
                          Dart_Handle* arguments) {
  TRACE_EVENT0("sky", "DartInvoke::DartInvokeAppClosure");
  return LogIfError(
      Dart_InvokeClosure(closure, number_of_arguments, arguments));
}

}  // namespace blink

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

#include "sky/engine/tonic/dart_invoke.h"

#include "base/logging.h"
#include "base/trace_event/trace_event.h"
#include "sky/engine/tonic/dart_error.h"

namespace blink {

bool DartInvokeAppField(Dart_Handle target, Dart_Handle name,
                               int number_of_arguments,
                               Dart_Handle* arguments) {
  TRACE_EVENT0("sky", "DartInvoke::DartInvokeAppField");
  return LogIfError(Dart_Invoke(target, name, number_of_arguments, arguments));
}

bool DartInvokeAppClosure(Dart_Handle closure,
                          int number_of_arguments,
                          Dart_Handle* arguments) {
  TRACE_EVENT0("sky", "DartInvoke::DartInvokeAppClosure");
  Dart_Handle handle = Dart_InvokeClosure(closure, number_of_arguments, arguments);
  bool result = LogIfError(handle);
  CHECK(!Dart_IsCompilationError(handle));
  return result;
}

}  // namespace blink

Check if invocation of a closure failed due to a compilation error


// RUN: %clang_cc1 -debug-info-kind=limited -triple %itanium_abi_triple \
// RUN:   -fdebug-prefix-map=%S=/SOURCE_ROOT %s -emit-llvm -o - | FileCheck %s

template <typename T> void b(T) {}
void c() {
  // CHECK: !DISubprogram(name: "b<(lambda at
  // CHECK-SAME:          SOURCE_ROOT
  // CHECK-SAME:          [[@LINE+1]]:{{[0-9]+}})>"
  b([]{});
}

// RUN: %clang_cc1 -std=c++14 -debug-info-kind=limited \
// RUN:   -triple %itanium_abi_triple \
// RUN:   -fdebug-prefix-map=%S=/SOURCE_ROOT %s -emit-llvm -o - | FileCheck %s

template <typename T> void b(T) {}
void c() {
  // CHECK: !DISubprogram(name: "b<(lambda at
  // CHECK-SAME:          SOURCE_ROOT
  // CHECK-SAME:          [[@LINE+1]]:{{[0-9]+}})>"
  b([]{});
}

Add an explicit -std=c++14 to this test.


// RUN: rm -rf %t
// RUN: %clang_cc1 -fmodules -fno-implicit-modules -emit-module -fmodule-name=a %S/Inputs/explicit-build-prefer-self/map -o a.pcm
// RUN: %clang_cc1 -fmodules -fno-implicit-modules -emit-module -fmodule-name=b %S/Inputs/explicit-build-prefer-self/map -o b.pcm

// RUN: rm -rf %t
// RUN: %clang_cc1 -fmodules -fno-implicit-modules -emit-module -fmodule-name=a %S/Inputs/explicit-build-prefer-self/map -o %t/a.pcm
// RUN: %clang_cc1 -fmodules -fno-implicit-modules -emit-module -fmodule-name=b %S/Inputs/explicit-build-prefer-self/map -o %t/b.pcm

Write output file to temp directory. The tests shouldn't assume that they can write to the current working directory.


#include "AnimationProgram.h"

#include "esp_log.h"

static const char* TAG = "PROGRAM";

AnimationProgram::AnimationProgram(Timer &animator) : programs(), animator(animator) {

}

void AnimationProgram::putAnimation(uint8_t index, Animation *animation) {
    programs[index] = animation;
}

void AnimationProgram::drawFrame() {
    // fixme check index
    programs[index]->drawFrame();
}

void AnimationProgram::setProgram(uint8_t index) {
    ESP_LOGI(TAG, "set program %d", index);
    this->index = index;
    animator.setIntervalSecs(index == 4 || index == 5 ? .3 : .03);
}

#include "AnimationProgram.h"

#include "esp_log.h"

static const char* TAG = "AnimationProgram";

AnimationProgram::AnimationProgram(Timer &animator) : programs(), animator(animator) {

}

void AnimationProgram::putAnimation(uint8_t index, Animation *animation) {
    programs[index] = animation;
}

void AnimationProgram::drawFrame() {
    // fixme check index
    programs[index]->drawFrame();
}

void AnimationProgram::setProgram(uint8_t index) {
    ESP_LOGI(TAG, "set program %d", index);
    if (index < programs.size()) {
        this->index = index;
        animator.setIntervalSecs(index == 4 || index == 5 ? .3 : .03);
    } else {
        ESP_LOGW(TAG, "set program ignored: out of range: 0-%d", programs.size() - 1);
    }
}

Add range check for set program


#include "catch.hpp"

#include <lua.hpp>
#include <luwra.hpp>

int test_function_1(int a, int b) {
	return a - b;
}

int test_function_2(int a, int b, int c) {
	return a + b * c;
}

void test_function_3(int) {

}

TEST_CASE("stack_interaction") {
	lua_State* state = luaL_newstate();

	luwra::push(state, 1);
	luwra::push(state, 2);
	luwra::push(state, 4);

	// Redundant function
	luwra::apply(state, test_function_3);

	// Absolute index
	REQUIRE(luwra::apply(state, test_function_1) == -1);
	REQUIRE(luwra::apply(state, 1, test_function_1) == -1);
	REQUIRE(luwra::apply(state, test_function_2) == 9);
	REQUIRE(luwra::apply(state, 1, test_function_2) == 9);

	// Relative index
	REQUIRE(luwra::apply(state, -2, test_function_1) == -2);
	REQUIRE(luwra::apply(state, -3, test_function_1) == -1);
	REQUIRE(luwra::apply(state, -3, test_function_2) == 9);

	lua_close(state);
}

#include "catch.hpp"

#include <lua.hpp>
#include <luwra.hpp>

static
int test_function_1(int a, int b) {
	return a - b;
}

static
int test_function_2(int a, int b, int c) {
	return a + b * c;
}

static
void test_function_3(int) {

}

TEST_CASE("stack_interaction") {
	lua_State* state = luaL_newstate();

	luwra::push(state, 1);
	luwra::push(state, 2);
	luwra::push(state, 4);

	// Redundant function
	luwra::apply(state, test_function_3);

	// Absolute index
	REQUIRE(luwra::apply(state, test_function_1) == -1);
	REQUIRE(luwra::apply(state, 1, test_function_1) == -1);
	REQUIRE(luwra::apply(state, test_function_2) == 9);
	REQUIRE(luwra::apply(state, 1, test_function_2) == 9);

	// Relative index
	REQUIRE(luwra::apply(state, -2, test_function_1) == -2);
	REQUIRE(luwra::apply(state, -3, test_function_1) == -1);
	REQUIRE(luwra::apply(state, -3, test_function_2) == 9);

	lua_close(state);
}

Make functions used in tests static


#include "utils/distance.hpp"

// Returns the minimum distance (straight line) between two points
double distance(cv::Point one, cv::Point two)
{
    return std::sqrt(std::pow(one.x - two.x, 2) + std::pow(one.y - two.y, 2));
}

// Returns the two dimensional distance between the components of two points
double distance2D(double comp1, double comp2)
{
    return std::abs(comp2 - comp1);
}

double getShortestDistance (cv::Point2f rectPoints[4], double focalLen, int dist, int height)
{
	// 20 inches real width
	int realWidth = 20;
	int pixelWidth = 0;
	double theta = 0;
	double d = 0;

	int length = static_cast<int>(distance (rectPoints[0], rectPoints[3]));
	int width = static_cast<int>(distance (rectPoints[0], rectPoints[1]));
	if (length > width)
    {
		pixelWidth = length;
    }
	else
	{
		pixelWidth = width;
    }
	d = (realWidth * focalLen) / pixelWidth;
	theta = std::asin(static_cast<double>(height) / dist) * 180 / PI;
	return d;
}

#include "utils/distance.hpp"

// Returns the minimum distance (straight line) between two points
double distance(cv::Point one, cv::Point two)
{
    return std::sqrt(std::pow(one.x - two.x, 2) + std::pow(one.y - two.y, 2));
}

double getShortestDistance (cv::Point2f rectPoints[4], double focalLen, int dist, int height)
{
	// The target's base is 20 inches wide in real life
	int realWidth = 20;
	int pixelWidth = 0;
	double theta = 0;
	double d = 0;

	int length = static_cast<int>(distance (rectPoints[0], rectPoints[3]));
	int width = static_cast<int>(distance (rectPoints[0], rectPoints[1]));

	if (length > width)
		pixelWidth = length;
	else
		pixelWidth = width;

	d = (realWidth * focalLen) / pixelWidth;
	return d;
}

Remove redundant brackets and lines of code


//
// Created by Adam Getchell on 2017-12-02.
//
#define CATCH_CONFIG_RUNNER
#include <catch2/catch.hpp>

int main( int argc, char* argv[] )
{
    Catch::Session session; // There must be exactly one instance

    // writing to session.configData() here sets defaults
    // this is the preferred way to set them

    int returnCode = session.applyCommandLine( argc, argv );
    if( returnCode != 0 ) // Indicates a command line error
        return returnCode;

    // writing to session.configData() or session.Config() here
    // overrides command line args
    // only do this if you know you need to

    int numFailed = session.run();

    // numFailed is clamped to 255 as some unices only use the lower 8 bits.
    // This clamping has already been applied, so just return it here
    // You can also do any post run clean-up here
    return numFailed;
}

//
// Created by Adam Getchell on 2017-12-02.
//
#define CATCH_CONFIG_RUNNER
#include "catch.hpp"

int main( int argc, char* argv[] )
{
    Catch::Session session; // There must be exactly one instance

    // writing to session.configData() here sets defaults
    // this is the preferred way to set them

    int returnCode = session.applyCommandLine( argc, argv );
    if( returnCode != 0 ) // Indicates a command line error
        return returnCode;

    // writing to session.configData() or session.Config() here
    // overrides command line args
    // only do this if you know you need to

    int numFailed = session.run();

    // numFailed is clamped to 255 as some unices only use the lower 8 bits.
    // This clamping has already been applied, so just return it here
    // You can also do any post run clean-up here
    return numFailed;
}

Revert back to older Catch2


// 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 "chrome/browser/automation/ui_controls.h"

#include "base/logging.h"
#include "views/view.h"

namespace ui_controls {

bool SendKeyPress(gfx::NativeWindow window,
                  ui::KeyboardCode key,
                  bool control,
                  bool shift,
                  bool alt,
                  bool command) {
  NOTIMPLEMENTED();
  return true;
}

bool SendKeyPressNotifyWhenDone(gfx::NativeWindow window,
                                ui::KeyboardCode key,
                                bool control,
                                bool shift,
                                bool alt,
                                bool command,
                                Task* task) {
  NOTIMPLEMENTED();
  return true;
}

bool SendMouseMove(long x, long y) {
  NOTIMPLEMENTED();
  return true;
}

bool SendMouseMoveNotifyWhenDone(long x, long y, Task* task) {
  NOTIMPLEMENTED();
  return true;
}

bool SendMouseEvents(MouseButton type, int state) {
  NOTIMPLEMENTED();
  return true;
}

bool SendMouseEventsNotifyWhenDone(MouseButton type, int state, Task* task) {
  NOTIMPLEMENTED();
  return true;
}

bool SendMouseClick(MouseButton type) {
  return SendMouseEvents(type, UP | DOWN);
}

void MoveMouseToCenterAndPress(views::View* view, MouseButton button,
                               int state, Task* task) {
  NOTIMPLEMENTED();
}

}  // namespace ui_controls

// 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 "chrome/browser/automation/ui_controls.h"

#include "base/logging.h"
#include "views/view.h"

namespace ui_controls {

bool SendKeyPress(gfx::NativeWindow window,
                  ui::KeyboardCode key,
                  bool control,
                  bool shift,
                  bool alt,
                  bool command) {
  NOTIMPLEMENTED();
  return true;
}

bool SendKeyPressNotifyWhenDone(gfx::NativeWindow window,
                                ui::KeyboardCode key,
                                bool control,
                                bool shift,
                                bool alt,
                                bool command,
                                const base::Closure& task) {
  NOTIMPLEMENTED();
  return true;
}

bool SendMouseMove(long x, long y) {
  NOTIMPLEMENTED();
  return true;
}

bool SendMouseMoveNotifyWhenDone(long x, long y, const base::Closure& task) {
  NOTIMPLEMENTED();
  return true;
}

bool SendMouseEvents(MouseButton type, int state) {
  NOTIMPLEMENTED();
  return true;
}

bool SendMouseEventsNotifyWhenDone(MouseButton type, int state,
    const base::Closure& task) {
  NOTIMPLEMENTED();
  return true;
}

bool SendMouseClick(MouseButton type) {
  return SendMouseEvents(type, UP | DOWN);
}

void MoveMouseToCenterAndPress(views::View* view, MouseButton button,
                               int state, const base::Closure& task) {
  NOTIMPLEMENTED();
}

}  // namespace ui_controls

Fix chrome compile after the switch from Task to base::Bind.