// RUN: %check_clang_tidy %s hicpp-exception-baseclass %t

namespace std {
class exception {};
} // namespace std

class derived_exception : public std::exception {};
class non_derived_exception {};

void problematic() {
  try {
    throw int(42); // Built in is not allowed
// CHECK-MESSAGES: [[@LINE-1]]:5: warning: throwing an exception whose type is not derived from 'std::exception'
  } catch (int e) {
  }
  throw int(42); // Bad
// CHECK-MESSAGES: [[@LINE-1]]:3: warning: throwing an exception whose type is not derived from 'std::exception'

  try {
    throw non_derived_exception(); // Some class is not allowed
// CHECK-MESSAGES: [[@LINE-1]]:5: warning: throwing an exception whose type is not derived from 'std::exception'
// CHECK-MESSAGES: 8:1: note: type defined here
  } catch (non_derived_exception &e) {
  }
  throw non_derived_exception(); // Bad
// CHECK-MESSAGES: [[@LINE-1]]:3: warning: throwing an exception whose type is not derived from 'std::exception'
// CHECK-MESSAGES: 8:1: note: type defined here
}

void allowed_throws() {
  try {
    throw std::exception(); // Ok
  } catch (std::exception &e) { // Ok
  }
  throw std::exception();

  try {
    throw derived_exception(); // Ok
  } catch (derived_exception &e) { // Ok
  }
  throw derived_exception(); // Ok
}

// RUN: %check_clang_tidy %s hicpp-exception-baseclass %t -- -- -fcxx-exceptions

namespace std {
class exception {};
} // namespace std

class derived_exception : public std::exception {};
class non_derived_exception {};

void problematic() {
  try {
    throw int(42); // Built in is not allowed
// CHECK-MESSAGES: [[@LINE-1]]:5: warning: throwing an exception whose type is not derived from 'std::exception'
  } catch (int e) {
  }
  throw int(42); // Bad
// CHECK-MESSAGES: [[@LINE-1]]:3: warning: throwing an exception whose type is not derived from 'std::exception'

  try {
    throw non_derived_exception(); // Some class is not allowed
// CHECK-MESSAGES: [[@LINE-1]]:5: warning: throwing an exception whose type is not derived from 'std::exception'
// CHECK-MESSAGES: 8:1: note: type defined here
  } catch (non_derived_exception &e) {
  }
  throw non_derived_exception(); // Bad
// CHECK-MESSAGES: [[@LINE-1]]:3: warning: throwing an exception whose type is not derived from 'std::exception'
// CHECK-MESSAGES: 8:1: note: type defined here
}

void allowed_throws() {
  try {
    throw std::exception(); // Ok
  } catch (std::exception &e) { // Ok
  }
  throw std::exception();

  try {
    throw derived_exception(); // Ok
  } catch (derived_exception &e) { // Ok
  }
  throw derived_exception(); // Ok
}

Enable exceptions for this test case to speculatively fix the build bots.


#include "mapped_file.h"

#include <exception/os.h>

#include <fcntl.h>
#include <sys/mman.h>
#include <sys/stat.h>

namespace sasm { namespace utils {

mapped_file::~mapped_file()
{
  if (_is_mapped)
    unmap();
}

void mapped_file::map()
{
  int fd;
  struct stat buf;
  char* begin;

  if ((fd = open(get_path(), O_RDONLY)) == -1)
    throw sasm::exception::os("open", get_path());

  if (fstat(fd, &buf) == -1)
    throw sasm::exception::os("fstat");

  if ((begin = (char*) mmap(NULL, buf.st_size, PROT_READ, MAP_PRIVATE, fd, 0)) == MAP_FAILED)
    throw sasm::exception::os("mmap");

  close(fd);

  _is_mapped = true;
  _begin = begin;
  _size = buf.st_size;
}

void mapped_file::unmap()
{
  if (munmap((void*) _begin, _size) == -1)
    throw sasm::exception::os("munmap");

  _is_mapped = false;
}

const char* mapped_file::get_path() const
{
  return _path.c_str();
}

}}

#include "mapped_file.h"

#include <exception/elf.h>
#include <exception/os.h>

#include <fcntl.h>
#include <sys/mman.h>
#include <sys/stat.h>

namespace sasm { namespace utils {

mapped_file::~mapped_file()
{
  if (_is_mapped)
    unmap();
}

void mapped_file::map()
{
  int fd;
  struct stat buf;
  char* begin;

  if ((fd = open(get_path(), O_RDONLY)) == -1)
    throw sasm::exception::os("open", get_path());

  if (fstat(fd, &buf) == -1)
    throw sasm::exception::os("fstat");

  if (buf.st_size == 0)
    throw sasm::exception::elf(_path.c_str(), "invalid ELF file");

  if ((begin = (char*) mmap(NULL, buf.st_size, PROT_READ, MAP_PRIVATE, fd, 0)) == MAP_FAILED)
    throw sasm::exception::os("mmap");

  close(fd);

  _is_mapped = true;
  _begin = begin;
  _size = buf.st_size;
}

void mapped_file::unmap()
{
  if (munmap((void*) _begin, _size) == -1)
    throw sasm::exception::os("munmap");

  _is_mapped = false;
}

const char* mapped_file::get_path() const
{
  return _path.c_str();
}

}}

Handle a little bug with empty files.


VectorXf v;
v.setLinSpaced(5,0.5f,1.5f).transpose();
cout << v << endl;

VectorXf v;
v.setLinSpaced(5,0.5f,1.5f);
cout << v << endl;

Remove confusing transpose() in setLinSpaced() docs.


//===----------------------------------------------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
//
// UNSUPPORTED: libcpp-has-no-threads

// <mutex>

// class recursive_timed_mutex;

// void lock();

#include <mutex>
#include <thread>
#include <cstdlib>
#include <cassert>

#include <iostream>

std::recursive_timed_mutex m;

typedef std::chrono::system_clock Clock;
typedef Clock::time_point time_point;
typedef Clock::duration duration;
typedef std::chrono::milliseconds ms;
typedef std::chrono::nanoseconds ns;

void f()
{
    time_point t0 = Clock::now();
    m.lock();
    time_point t1 = Clock::now();
    m.lock();
    m.unlock();
    m.unlock();
    ns d = t1 - t0 - ms(250);
    assert(d < ms(50));  // within 50ms
}

int main()
{
    m.lock();
    std::thread t(f);
    std::this_thread::sleep_for(ms(250));
    m.unlock();
    t.join();
}

//===----------------------------------------------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
//
// UNSUPPORTED: libcpp-has-no-threads

// FLAKY_TEST.

// <mutex>

// class recursive_timed_mutex;

// void lock();

#include <mutex>
#include <thread>
#include <cstdlib>
#include <cassert>

#include <iostream>

std::recursive_timed_mutex m;

typedef std::chrono::system_clock Clock;
typedef Clock::time_point time_point;
typedef Clock::duration duration;
typedef std::chrono::milliseconds ms;
typedef std::chrono::nanoseconds ns;

void f()
{
    time_point t0 = Clock::now();
    m.lock();
    time_point t1 = Clock::now();
    m.lock();
    m.unlock();
    m.unlock();
    ns d = t1 - t0 - ms(250);
    assert(d < ms(50));  // within 50ms
}

int main()
{
    m.lock();
    std::thread t(f);
    std::this_thread::sleep_for(ms(250));
    m.unlock();
    t.join();
}

Mark another test as flaky


#include <cppunit/XmlOutputter.h>
#include <cppunit/extensions/TestFactoryRegistry.h>
#include <cppunit/ui/text/TestRunner.h>
#include <cppunit/TestResult.h>
#include <cppunit/TestResultCollector.h>

#include "SystemTest.h"

int main(int argc, char* argv[])
{
    CppUnit::TestResult controller;
    CppUnit::TestResultCollector result;
    controller.addListener(&result);

    // Get the top level suite from the registry
    CppUnit::Test *suite = CppUnit::TestFactoryRegistry::getRegistry().makeTest();

    // Adds the test to the list of test to run
    CppUnit::TextUi::TestRunner runner;

    runner.addTest( suite );
    runner.run(controller);

    // Change the default outputter to a compiler error format
    // outputter
    std::ofstream xmlFileOut("cpptestresults.xml");
    CppUnit::XmlOutputter xmlOut(&result, xmlFileOut);
    xmlOut.write();

    // Return error code 1 if the one of test failed.
    return result.testFailuresTotal() ? 0 : 1;
}

#include <cppunit/XmlOutputter.h>
#include <cppunit/extensions/TestFactoryRegistry.h>
#include <cppunit/ui/text/TestRunner.h>
#include <cppunit/TestResult.h>
#include <cppunit/TestResultCollector.h>

#include "SystemTest.h"

int main(int argc, char* argv[])
{
    CppUnit::TestResult controller;
    CppUnit::TestResultCollector result;
    controller.addListener(&result);

    // Get the top level suite from the registry
    CppUnit::Test *suite = CppUnit::TestFactoryRegistry::getRegistry().makeTest();

    // Adds the test to the list of test to run
    CppUnit::TextUi::TestRunner runner;

    runner.addTest( suite );
    runner.run(controller);

    // Change the default outputter to a compiler error format
    // outputter
    std::ofstream xmlFileOut("cpptestresults.xml");
    CppUnit::XmlOutputter xmlOut(&result, xmlFileOut);
    xmlOut.write();

    // Return error code 1 if the one of test failed.
    return result.testFailuresTotal() ? 1 : 0 ;
}

Send correct exit code on test failure.


#include "common.th"

// c <- multiplicand
// d <- multiplier
// b -> product
.global imul
imul:
    pushall(h,i,j)

    b <- 0
#if IMUL_EARLY_EXITS
    i <- d == 0
    i <- c == 0 + i
    i <- i <> 0
    jnzrel(i, L_done)
#endif

    h <- 1

    j <- d >> 31    // save sign bit in j
    j <- -j         // convert sign to flag
    d <- d ^ j      // adjust multiplier
    d <- d - j

L_top:
    // use constant 1 in h to combine instructions
    i <- d & h - 1
    i <- c &~ i
    b <- b + i
    c <- c << 1
    d <- d >> 1
    i <- d <> 0
    jnzrel(i, L_top)

    b <- b ^ j      // adjust product for signed math
    b <- b - j

L_done:
    popall(h,i,j)
    ret

#include "common.th"

// c <- multiplicand
// d <- multiplier
// b -> product
.global imul
imul:
#if IMUL_EARLY_EXITS
    b <- c == 0
    d <- d &~ b     // d = (c == 0) ? 0 : d
    b <- d <> 0
    jzrel(b, L_done)
#endif

    pushall(h,i,j)

    b <- 0
    h <- 1

    j <- d >> 31    // save sign bit in j
    j <- -j         // convert sign to flag
    d <- d ^ j      // adjust multiplier
    d <- d - j

L_top:
    // use constant 1 in h to combine instructions
    i <- d & h - 1
    i <- c &~ i
    b <- b + i
    c <- c << 1
    d <- d >> 1
    i <- d <> 0
    jnzrel(i, L_top)

    b <- b ^ j      // adjust product for signed math
    b <- b - j

    popall(h,i,j)
L_done:
    ret

Make early exits, when active, more efficient


/** \file    SysLog.h
 *  \brief   Declaration of class SysLog.
 *  \author  Dr. Johannes Ruscheinski
 */

/*
 *  Copyright 2020 University Library of Tübingen
 *
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU Affero General Public License as
 *  published by the Free Software Foundation, either version 3 of the
 *  License, or (at your option) 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 Affero 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, see <http://www.gnu.org/licenses/>.
 */
#include "SysLog.h"

SysLog::SysLog(const std::string &message_prefix, const int option, const int facility) {
    ::openlog(message_prefix.c_str(), option, facility);
    ::setlogmask(LOG_EMERG | LOG_ALERT | LOG_CRIT | LOG_ERR | LOG_WARNING | LOG_NOTICE | LOG_INFO);
}

SysLog::~SysLog() {
    ::closelog();
}

void SysLog::log(const LogLevel level, const std::string &message) {
    ::syslog(level, "%s", message.c_str());
}

/** \file    SysLog.h
 *  \brief   Declaration of class SysLog.
 *  \author  Dr. Johannes Ruscheinski
 */

/*
 *  Copyright 2020 University Library of Tübingen
 *
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU Affero General Public License as
 *  published by the Free Software Foundation, either version 3 of the
 *  License, or (at your option) 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 Affero 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, see <http://www.gnu.org/licenses/>.
 */
#include "SysLog.h"

SysLog::SysLog(const std::string &message_prefix, const int option, const int facility) {
    ::openlog(message_prefix.empty() ? nullptr : message_prefix.c_str(), option, facility);
    ::setlogmask(LOG_EMERG | LOG_ALERT | LOG_CRIT | LOG_ERR | LOG_WARNING | LOG_NOTICE | LOG_INFO);
}

SysLog::~SysLog() {
    ::closelog();
}

void SysLog::log(const LogLevel level, const std::string &message) {
    ::syslog(level, "%s", message.c_str());
}

Use progran name as default log entry prefix.


Matrix2f M = Matrix2f::Random();
Matrix2f m;
m = M;
cout << "Here is the matrix m:" << endl << m << endl;
cout << "Now we want to replace m by its own transpose." << endl;
cout << "If we do m = m.transpose(), then m becomes:" << endl;
m = m.transpose() * 1;
cout << m << endl << "which is wrong!" << endl;
cout << "Now let us instead do m = m.transpose().eval(). Then m becomes" << endl;
m = M;
m = m.transpose().eval();
cout << m << endl << "which is right." << endl;

Matrix2f M = Matrix2f::Random();
Matrix2f m;
m = M;
cout << "Here is the matrix m:" << endl << m << endl;
cout << "Now we want to copy a column into a row." << endl;
cout << "If we do m.col(1) = m.row(0), then m becomes:" << endl;
m.col(1) = m.row(0);
cout << m << endl << "which is wrong!" << endl;
cout << "Now let us instead do m.col(1) = m.row(0).eval(). Then m becomes" << endl;
m = M;
m.col(1) = m.row(0).eval();
cout << m << endl << "which is right." << endl;

Make snippet run successfully again: the snippet for 'eval' was taking m=m.transpose() as an example of code that needs an explicit call to eval(), but that doesn't work anymore now that we have the clever assert detecting aliasing issues.


#define SYS_CLOCK_GETTIME 263
#include "linux_clock.cpp"

#ifdef BITS_64
#define SYS_CLOCK_GETTIME 113
#endif

#ifdef BITS_32
#define SYS_CLOCK_GETTIME 263
#endif

#include "linux_clock.cpp"

Fix a syscall number for 64-bit arm


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

#include "chrome/browser/idle.h"

#include "base/basictypes.h"

#if defined(USE_X11)
#include "chrome/browser/idle_query_x11.h"
#endif

#if !defined(OS_CHROMEOS)
#include "chrome/browser/screensaver_window_finder_x11.h"
#endif

void CalculateIdleTime(IdleTimeCallback notify) {
#if defined(USE_X11)
  chrome::IdleQueryX11 idle_query;
  notify.Run(idle_query.IdleTime());
#endif
}

bool CheckIdleStateIsLocked() {
  // Usually the screensaver is used to lock the screen, so we do not need to
  // check if the workstation is locked.
#if defined(OS_CHROMEOS)
  return false;
#else
  return ScreensaverWindowFinder::ScreensaverWindowExists();
#endif
}

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

#include "chrome/browser/idle.h"

#include "base/basictypes.h"

#if defined(USE_X11)
#include "chrome/browser/idle_query_x11.h"
#endif

#if !defined(OS_CHROMEOS)
#include "chrome/browser/screensaver_window_finder_x11.h"
#endif

void CalculateIdleTime(IdleTimeCallback notify) {
#if defined(USE_X11)
  chrome::IdleQueryX11 idle_query;
  notify.Run(idle_query.IdleTime());
#endif
}

bool CheckIdleStateIsLocked() {
  // Usually the screensaver is used to lock the screen, so we do not need to
  // check if the workstation is locked.
#if defined(OS_CHROMEOS)
  return false;
#elif defined(USE_OZONE)
  return false;
#else
  return ScreensaverWindowFinder::ScreensaverWindowExists();
#endif
}

Check idle state for Ozone platform


// RUN: %clang_cl_asan -O0 %s -Fe%t
// RUN: not %run %t 2>&1 | FileCheck %s

#include <windows.h>

HANDLE done;

DWORD CALLBACK work_item(LPVOID) {
  int subscript = -1;
  volatile char stack_buffer[42];
  stack_buffer[subscript] = 42;
// CHECK: AddressSanitizer: stack-buffer-underflow on address [[ADDR:0x[0-9a-f]+]]
// CHECK: WRITE of size 1 at [[ADDR]] thread T1
// CHECK:   {{#0 .* work_item.*queue_user_work_item_report.cc}}:[[@LINE-3]]
// CHECK: Address [[ADDR]] is located in stack of thread T1 at offset {{.*}} in frame
// CHECK:   work_item
  SetEvent(done);
  return 0;
}

int main(int argc, char **argv) {
  done = CreateEvent(0, false, false, "job is done");
  if (!done)
    return 1;
// CHECK-NOT: Thread T1 created
  QueueUserWorkItem(&work_item, nullptr, 0);
  if (WAIT_OBJECT_0 != WaitForSingleObject(done, 10 * 1000))
    return 2;
}

// RUN: %clang_cl_asan -O0 %s -Fe%t
// RUN: not %run %t 2>&1 | FileCheck %s

#include <windows.h>

HANDLE done;

DWORD CALLBACK work_item(LPVOID) {
  int subscript = -1;
  volatile char stack_buffer[42];
  stack_buffer[subscript] = 42;
// CHECK: AddressSanitizer: stack-buffer-underflow on address [[ADDR:0x[0-9a-f]+]]
// CHECK: WRITE of size 1 at [[ADDR]] thread T1
// CHECK:   {{#0 .* work_item.*queue_user_work_item_report.cc}}:[[@LINE-3]]
  SetEvent(done);
  return 0;
}

int main(int argc, char **argv) {
  done = CreateEvent(0, false, false, "job is done");
  if (!done)
    return 1;
// CHECK-NOT: Thread T1 created
  QueueUserWorkItem(&work_item, nullptr, 0);
  if (WAIT_OBJECT_0 != WaitForSingleObject(done, 10 * 1000))
    return 2;
}

Remove stale CHECK lines that should have been included in r277478


#include <stdint.h>
#include "receiver.h"

Receiver::Receiver(
    uint8_t spiClockPin,
    uint8_t spiDataPin,
    uint8_t spiSelectPin
) {
    this->driver.init(spiClockPin, spiDataPin, spiSelectPin);
}

void Receiver::setFrequency(uint16_t frequency) {
    uint16_t flO = (frequency - 479) / 2;
    uint16_t regN = frequency / 32;
    uint16_t regA = frequency % 32;
    uint16_t synthRegB = (regN << 7) | regA;

    this->driver.setSynthRegisterB(synthRegB);
}

#include <stdint.h>
#include "receiver.h"

Receiver::Receiver(
    uint8_t spiClockPin,
    uint8_t spiDataPin,
    uint8_t spiSelectPin
) {
    this->driver.init(spiClockPin, spiDataPin, spiSelectPin);
}

void Receiver::setFrequency(uint16_t frequency) {
    uint16_t fLo = (frequency - 479) / 2;
    uint16_t regN = fLo / 32;
    uint16_t regA = fLo % 32;
    uint16_t synthRegB = (regN << 7) | regA;

    this->driver.setSynthRegisterB(synthRegB);
}

Fix broken synth reg A gen


// Copyright 2015 Alessio Sclocco <a.sclocco@vu.nl>
//
// 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 <ReadData.hpp>

namespace AstroData {

RingBufferError::RingBufferError() {}

RingBufferError::~RingBufferError() throw () {}

const char * RingBufferError::what() const throw() {
    return ("Impossible to read from the PSRDada ring buffer.");
}

void readZappedChannels(Observation & observation, const std::string & inputFileName, std::vector< uint8_t > & zappedChannels) {
  unsigned int nrChannels = 0;
  std::ifstream input;

  input.open(inputFileName);
  while ( !input.eof() ) {
    unsigned int channel = 0;

    input >> channel;
    if ( channel < observation.getNrChannels() ) {
      zappedChannels[channel] = 1;
      nrChannels++;
    }
  }
  input.close();
  observation.setNrZappedChannels(nrChannels);
}

} // AstroData

// Copyright 2015 Alessio Sclocco <a.sclocco@vu.nl>
//
// 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 <ReadData.hpp>

namespace AstroData {

RingBufferError::RingBufferError() {}

RingBufferError::~RingBufferError() throw () {}

const char * RingBufferError::what() const throw() {
    return ("Impossible to read from the PSRDada ring buffer.");
}

void readZappedChannels(Observation & observation, const std::string & inputFileName, std::vector< uint8_t > & zappedChannels) {
  unsigned int nrChannels = 0;
  std::ifstream input;

  input.open(inputFileName);
  while ( !input.eof() ) {
    unsigned int channel = observation.getNrChannels();

    input >> channel;
    if ( channel < observation.getNrChannels() ) {
      zappedChannels[channel] = 1;
      nrChannels++;
    }
  }
  input.close();
  observation.setNrZappedChannels(nrChannels);
}

} // AstroData

Fix to avoid empty files. Could still be improved, but it is enough for now.


// REQUIRES: x86-registered-target,x86-64-registered-target
// RUN: %clang_cc1 -triple x86_64-apple-darwin -std=c++11 -S %s -o %t-64.s
// RUN: FileCheck -check-prefix CHECK-LP64 --input-file=%t-64.s %s
// RUN: %clang_cc1 -triple i386-apple-darwin -std=c++11 -S %s -o %t-32.s
// RUN: FileCheck -check-prefix CHECK-LP32 --input-file=%t-32.s %s

struct A { A(const A&, int i1 = 1); };

struct B : A { };

A f(const B &b) {
  return b;
}

// CHECK-LP64: callq    __ZN1AC1ERKS_i

// CHECK-LP32: calll     L__ZN1AC1ERKS_i

// RUN: %clang_cc1 -triple x86_64-apple-darwin -std=c++11 -emit-llvm %s -o - | \
// RUN: FileCheck %s
// RUN: %clang_cc1 -triple i386-apple-darwin -std=c++11 -emit-llvm %s -o - | \
// RUN: FileCheck %s

struct A { A(const A&, int i1 = 1); };

struct B : A { };

A f(const B &b) {
  return b;
}

// CHECK: call void @_ZN1AC1ERKS_i

Check IR instead of assembly in this test.


// this is for emacs file handling -*- mode: c++; indent-tabs-mode: nil -*-

// -- BEGIN LICENSE BLOCK ----------------------------------------------
// -- END LICENSE BLOCK ------------------------------------------------

//----------------------------------------------------------------------
/*!\file
 *
 * \author  Felix Exner exner@fzi.de
 * \date    2019-06-14
 *
 */
//----------------------------------------------------------------------

#include <ur_robot_driver/ur/calibration_checker.h>

namespace ur_driver
{
CalibrationChecker::CalibrationChecker(const std::string& expected_hash)
  : expected_hash_(expected_hash), checked_(false)
{
}
bool CalibrationChecker::consume(std::shared_ptr<primary_interface::PrimaryPackage> product)
{
  auto kin_info = std::dynamic_pointer_cast<primary_interface::KinematicsInfo>(product);
  if (kin_info != nullptr)
  {
    // LOG_INFO("%s", product->toString().c_str());
    //
    if (kin_info->toHash() != expected_hash_)
    {
      LOG_ERROR("The calibration parameters of the connected robot don't match the ones from the given kinematics "
                "config file. Please be aware that this can lead to critical inaccuracies of tcp positions. Use the "
                "ur_calibration tool to extract the correct calibration from the robot and pass that into the "
                "description. See [TODO Link to documentation] for details.");
    }
    else
    {
      LOG_INFO("Calibration checked successfully.");
    }

    checked_ = true;
  }

  return true;
}
}  // namespace ur_driver

// this is for emacs file handling -*- mode: c++; indent-tabs-mode: nil -*-

// -- BEGIN LICENSE BLOCK ----------------------------------------------
// -- END LICENSE BLOCK ------------------------------------------------

//----------------------------------------------------------------------
/*!\file
 *
 * \author  Felix Exner exner@fzi.de
 * \date    2019-06-14
 *
 */
//----------------------------------------------------------------------

#include <ur_robot_driver/ur/calibration_checker.h>

namespace ur_driver
{
CalibrationChecker::CalibrationChecker(const std::string& expected_hash)
  : expected_hash_(expected_hash), checked_(false)
{
}
bool CalibrationChecker::consume(std::shared_ptr<primary_interface::PrimaryPackage> product)
{
  auto kin_info = std::dynamic_pointer_cast<primary_interface::KinematicsInfo>(product);
  if (kin_info != nullptr)
  {
    // LOG_INFO("%s", product->toString().c_str());
    //
    if (kin_info->toHash() != expected_hash_)
    {
      LOG_ERROR("The calibration parameters of the connected robot don't match the ones from the given kinematics "
                "config file. Please be aware that this can lead to critical inaccuracies of tcp positions. Use the "
                "ur_calibration tool to extract the correct calibration from the robot and pass that into the "
                "description. See "
                "[https://github.com/UniversalRobots/Universal_Robots_ROS_Driver#extract-calibration-information] for "
                "details.");
    }
    else
    {
      LOG_INFO("Calibration checked successfully.");
    }

    checked_ = true;
  }

  return true;
}
}  // namespace ur_driver

Add actual documentation link into calibration checker output


//===-- asan_test_main.cc -------------------------------------------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file is a part of AddressSanitizer, an address sanity checker.
//
//===----------------------------------------------------------------------===//
#include "asan_test_utils.h"

int main(int argc, char **argv) {
  testing::GTEST_FLAG(death_test_style) = "threadsafe";
  testing::InitGoogleTest(&argc, argv);
  return RUN_ALL_TESTS();
}

//===-- asan_test_main.cc -------------------------------------------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file is a part of AddressSanitizer, an address sanity checker.
//
//===----------------------------------------------------------------------===//
#include "asan_test_utils.h"

// Default ASAN_OPTIONS for the unit tests. Let's turn symbolication off to
// speed up testing (unit tests don't use it anyway).
extern "C" const char* __asan_default_options() {
  return "symbolize=false";
}

int main(int argc, char **argv) {
  testing::GTEST_FLAG(death_test_style) = "threadsafe";
  testing::InitGoogleTest(&argc, argv);
  return RUN_ALL_TESTS();
}

Speed up ASan unit tests by turning off symbolication


// Copyright 2018-2020 Intel Corporation
// SPDX-License-Identifier: Apache-2.0

#include "GLFWOSPRayWindow.h"
#include "example_common.h"

using namespace ospray;
using rkcommon::make_unique;

int main(int argc, const char *argv[])
{
  bool denoiser = ospLoadModule("denoiser") == OSP_NO_ERROR;

  initializeOSPRay(argc, argv);

  auto glfwOSPRayWindow =
      make_unique<GLFWOSPRayWindow>(vec2i(1024, 768), denoiser);
  glfwOSPRayWindow->mainLoop();
  glfwOSPRayWindow.reset();

  ospShutdown();

  return 0;
}

// Copyright 2018-2020 Intel Corporation
// SPDX-License-Identifier: Apache-2.0

#include "GLFWOSPRayWindow.h"
#include "example_common.h"

using namespace ospray;
using rkcommon::make_unique;

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

  bool denoiser = ospLoadModule("denoiser") == OSP_NO_ERROR;

  auto glfwOSPRayWindow =
      make_unique<GLFWOSPRayWindow>(vec2i(1024, 768), denoiser);
  glfwOSPRayWindow->mainLoop();
  glfwOSPRayWindow.reset();

  ospShutdown();

  return 0;
}

Load the denoiser module after initializing OSPRay


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

#include "config.h"
#include "PluginData.h"

#include "PluginInfoStore.h"

#undef LOG
#include "webkit/glue/glue_util.h"
#include "webkit/glue/webkit_glue.h"

namespace WebCore {

static bool refreshData = false;

void PluginData::initPlugins()
{
    std::vector<WebPluginInfo> plugins;
    if (!webkit_glue::GetPlugins(refreshData, &plugins))
        return;
    refreshData = false;

    PluginInfoStore c;
    for (size_t i = 0; i < plugins.size(); ++i) {
        PluginInfo* info = c.createPluginInfoForPluginAtIndex(i);
        m_plugins.append(info);
    }
}

void PluginData::refresh()
{
    // When next we initialize a PluginData, it'll be fresh.
    refreshData = true;
}

}

// Copyright (c) 2008, Google Inc.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
//     * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//     * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
//     * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

#include "config.h"
#include "PluginData.h"

#include "PluginInfoStore.h"

namespace WebCore {

void PluginData::initPlugins()
{
    PluginInfoStore c;
    for (size_t i = 0; i < c.pluginCount(); ++i)
        m_plugins.append(c.createPluginInfoForPluginAtIndex(i));
}

void PluginData::refresh()
{
    refreshPlugins(true);
}

}

Fix plugin data refreshing to work again.


#include <gtest/gtest.h>

#include "photoeffects.hpp"

using namespace cv;

TEST(photoeffects, SepiaFakeTest) {
    Mat src(10, 10, CV_8UC1), dst;

    EXPECT_EQ(0, sepia(src, dst));
}

TEST(photoeffects, SepiaFailTest) {
    Mat src(10, 10, CV_8UC3), dst;

    EXPECT_EQ(1, sepia(src, dst));
}

/*
TEST(photoeffects, SepiaTest) {
    Mat src(10, 10, CV_8UC1), dst, hsvDst;
    vector<Mat> channels(3);

    EXPECT_EQ(0, sepia(src, dst));
    cvtColor(dst, hsvDst, CV_BGR2HSV);
    split(hsvDst, channels);
    EXPECT_EQ(src.at<uchar>(0, 0) + 20, channels[2].at<uchar>(0, 0));
}
*/

#include <gtest/gtest.h>

#include "photoeffects.hpp"

using namespace cv;

TEST(photoeffects, SepiaFakeTest) {
    Mat src(10, 10, CV_8UC1), dst;

    EXPECT_EQ(0, sepia(src, dst));
}

TEST(photoeffects, SepiaFailTest) {
    Mat src(10, 10, CV_8UC3), dst;

    EXPECT_EQ(1, sepia(src, dst));
}

TEST(photoeffects, SepiaTest) {
    Mat src(10, 10, CV_8UC1), dst, hsvDst;
    vector<Mat> channels(3);

    EXPECT_EQ(0, sepia(src, dst));
    cvtColor(dst, hsvDst, CV_BGR2HSV);
    split(hsvDst, channels);
    EXPECT_LE(19 - 1, channels[0].at<uchar>(0, 0)); // hue = 19
    EXPECT_GE(19 + 1, channels[0].at<uchar>(0, 0));
    EXPECT_LE(78 - 1, channels[1].at<uchar>(0, 0)); // saturation = 78
    EXPECT_GE(78 + 1, channels[1].at<uchar>(0, 0));
    EXPECT_LE(src.at<uchar>(0, 0) + 20 - 1, channels[2].at<uchar>(0, 0));
    EXPECT_GE(src.at<uchar>(0, 0) + 20 + 1, channels[2].at<uchar>(0, 0));
}

Test was restored, interval [<v>-1,<v>+1] was set for hue, saturation and value.


/**
 * Test suite for the iterator_concepts_ordering.hpp header.
 */

#include <duck/detail/iterator_concepts_ordering.hpp>

#include <boost/mpl/assert.hpp>

BOOST_MPL_ASSERT((duck::is_more_specific_than<
                    duck::BidirectionalIterator,
                    duck::RandomAccessIterator>));

BOOST_MPL_ASSERT((duck::is_more_specific_than<
                    duck::IncrementableIterator,
                    duck::RandomAccessIterator>));

BOOST_MPL_ASSERT_NOT((duck::is_more_specific_than<
                        duck::RandomAccessIterator,
                        duck::BidirectionalIterator>));

BOOST_MPL_ASSERT_NOT((duck::is_more_specific_than<
                        duck::RandomAccessIterator,
                        duck::IncrementableIterator>));

BOOST_MPL_ASSERT_NOT((duck::is_more_specific_than<
                        duck::ForwardIterator,
                        duck::ForwardIterator>));

/**
 * Test suite for the iterator_concepts_ordering.hpp header.
 */

#include <duck/detail/iterator_concepts_ordering.hpp>

#include <boost/mpl/assert.hpp>

BOOST_MPL_ASSERT((duck::is_more_specific_than<
                    duck::BidirectionalIterator,
                    duck::RandomAccessIterator>));

BOOST_MPL_ASSERT((duck::is_more_specific_than<
                    duck::IncrementableIterator,
                    duck::RandomAccessIterator>));

BOOST_MPL_ASSERT((duck::is_more_specific_than<
                    duck::ForwardIterator,
                    duck::RandomAccessIterator>));

BOOST_MPL_ASSERT_NOT((duck::is_more_specific_than<
                        duck::RandomAccessIterator,
                        duck::BidirectionalIterator>));

BOOST_MPL_ASSERT_NOT((duck::is_more_specific_than<
                        duck::RandomAccessIterator,
                        duck::IncrementableIterator>));

BOOST_MPL_ASSERT_NOT((duck::is_more_specific_than<
                        duck::ForwardIterator,
                        duck::ForwardIterator>));

BOOST_MPL_ASSERT_NOT((duck::is_more_specific_than<
                        duck::RandomAccessIterator,
                        duck::ForwardIterator>));

Add more iterator concept ordering tests.


#include <vector>
#include <iostream>
#include <algorithm>

#ifndef REMOVE_VALUES
#ifndef CHECK_VALUES
#error "define one of REMOVE_VALUES or CHECK_VALUES"
#endif
#endif

#ifdef REMOVE_VALUES
#ifdef CHECK_VALUES
#error "define either REMOVE_VALUES or CHECK_VALUES"
#endif
#endif

int main()
{
	std::vector<int> myValues;
  for ( long int i=0L; i<100000000L; ++i )
		myValues.push_back(i%3);

	int iOriginalSize = myValues.size();
#ifdef REMOVE_VALUES
	myValues.erase(std::remove_if(myValues.begin(),myValues.end(),[](int i) { return i == 2; }),myValues.end());
#endif
	int sum = 0;
  for ( unsigned int i=0; i<myValues.size(); ++i )
	{
#ifdef CHECK_VALUES
		if ( myValues[i] != 2 )
		{
#endif
			sum += myValues[i];
#ifdef CHECK_VALUES
		}
#endif
	}

}

#include <vector>
#include <iostream>
#include <algorithm>

#ifndef REMOVE_VALUES
#ifndef CHECK_VALUES
#error "define one of REMOVE_VALUES or CHECK_VALUES"
#endif
#endif

#ifdef REMOVE_VALUES
#ifdef CHECK_VALUES
#error "define either REMOVE_VALUES or CHECK_VALUES"
#endif
#endif

int main()
{
	std::vector<int> myValues;
	for ( long int i=0L; i<10000000L; ++i )
		myValues.push_back(i%3);

	int iOriginalSize = myValues.size();
#ifdef REMOVE_VALUES
	myValues.erase(std::remove_if(myValues.begin(),myValues.end(),[](int i) { return i == 2; }),myValues.end());
#endif

	const int iterations = 100;
	for ( int iteration=0; iteration < iterations; ++iteration )
	{
		int sum = 0;
		for ( unsigned int i=0; i<myValues.size(); ++i )
		{
#ifdef CHECK_VALUES
			if ( myValues[i] != 2 )
			{
#endif
				sum += myValues[i];
#ifdef CHECK_VALUES
			}
#endif
		}
	}
}

Check vs Remove - not so not so clear


// Copyright 2004-present Facebook. All Rights Reserved.

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

#include "osquery/database.h"

namespace osquery {
namespace tables {

QueryData genArp() {
  Row r;
  QueryData results;
  FILE *arp_cmd_output;
  char *line;
  size_t length;

  char ip[32];
  char arp[64];
  char iface[32];

  // We are already calling 'popen', let's give it some more work with sed to clean.
  arp_cmd_output = popen("arp -an | sed 's,^[^(]*(\\([^)]*\\)) at \\([^ ]*\\).*on \\([^ ]*\\).*$,\\1 \\2 \\3,'", "r");
  if (arp_cmd_output == NULL) {
    return results;
  }

  line = fgetln(arp_cmd_output, &length);
  while (line) {
    sscanf(line, "%s %s %s", ip, arp, iface);

    r["ip"] = ip;
    r["arp"] = arp;
    r["iface"] = iface;

    results.push_back(r);

    line = fgetln(arp_cmd_output, &length);
  }

  return results;
}
}
}

// Copyright 2004-present Facebook. All Rights Reserved.

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

#include "osquery/database.h"

namespace osquery {
namespace tables {

QueryData genArp() {
  Row r;
  QueryData results;
  FILE *arp_cmd_output;
  char *line = NULL;
  size_t length;
  int ret;

  char ip[32];
  char arp[64];
  char iface[32];

  // We are already calling 'popen', let's give it some more work with sed to clean.
  arp_cmd_output = popen("arp -an | sed 's,^[^(]*(\\([^)]*\\)) at \\([^ ]*\\).*on \\([^ ]*\\).*$,\\1 \\2 \\3,'", "r");
  if (arp_cmd_output == NULL) {
    return results;
  }

  ret = getline(&line, &length, arp_cmd_output);
  while (ret > 0) {
    sscanf(line, "%s %s %s", ip, arp, iface);

    r["ip"] = ip;
    r["arp"] = arp;
    r["iface"] = iface;

    results.push_back(r);

    line = NULL;
    ret = getline(&line, &length, arp_cmd_output);
  }

  return results;
}
}
}

Change fgetln (osx specific) in favour of getline (both osx and linux)


#include <proton/default_container.hpp>
#include <proton/messaging_handler.hpp>

#include <string>

class ExampleHandler: public proton::messaging_handler {
    std::string url_;

    // The container has started
    void on_container_start(proton::container&) override {
    }

    // A message can be sent
    void on_sendable(proton::sender&) override {
    }

    // A message is received
    void on_message(proton::delivery&, proton::message&) override {
    }

  public:
    ExampleHandler(const std::string& url) : url_(url) {}
};

int main() {
    ExampleHandler h("localhost");
    proton::default_container(h).run();
}

#include <proton/default_container.hpp>
#include <proton/messaging_handler.hpp>

#include <string>

class ExampleHandler: public proton::messaging_handler {
    std::string url_;

    // The container has started
    void on_container_start(proton::container& c) override {
    }

    // A message can be sent
    void on_sendable(proton::sender& s) override {
    }

    // A message is received
    void on_message(proton::delivery& d, proton::message& m) override {
    }

  public:
    ExampleHandler(const std::string& url) : url_(url) {}
};

int main() {
    ExampleHandler h("localhost");
    proton::default_container(h).run();
}

Make change parallel to guide


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

#include "views/focus/focus_manager.h"

#include "base/logging.h"

namespace views {

void FocusManager::ClearNativeFocus() {
  NOTIMPLEMENTED();
}

void FocusManager::FocusNativeView(gfx::NativeView native_view) {
  NOTIMPLEMENTED();
}

 // static
FocusManager* FocusManager::GetFocusManagerForNativeView(
    gfx::NativeView native_view) {
  NOTIMPLEMENTED();
}

}  // namespace views

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

#include "views/focus/focus_manager.h"

#include "base/logging.h"

namespace views {

void FocusManager::ClearNativeFocus() {
  NOTIMPLEMENTED();
}

void FocusManager::FocusNativeView(gfx::NativeView native_view) {
  NOTIMPLEMENTED();
}

 // static
FocusManager* FocusManager::GetFocusManagerForNativeView(
    gfx::NativeView native_view) {
  NOTIMPLEMENTED();
  return NULL;
}

}  // namespace views

Fix compilation error in the focus manager by returning NULL from unimplemented function.


#include "TestCommon.h"

USING_NAMESPACE_KAI

struct TestString : TestCommon
{
protected:
    void AddrequiredClasses() override
    {
        Reg().AddClass<bool>();
        Reg().AddClass<int>();
        Reg().AddClass<String>();
    }
};

TEST_F(TestString, TestBoolean)
{
    Pointer<String> s0 = Reg().New<String>("foo");
    ASSERT_TRUE(s0.GetClass()->Boolean(s0.GetStorageBase()));
    *s0 = "";
    ASSERT_FALSE(s0.GetClass()->Boolean(s0.GetStorageBase()));
}

TEST_F(TestString, TestCompare)
{
    Pointer<String> s0 = Reg().New<String>("a");
    Pointer<String> s1 = Reg().New<String>("a");

    ASSERT_TRUE(s0.GetClass()->Equiv(s0.GetStorageBase(), s1.GetStorageBase()));

    *s1 = "b";
    ASSERT_FALSE(s0.GetClass()->Equiv(s0.GetStorageBase(), s1.GetStorageBase()));
    ASSERT_TRUE(s0.GetClass()->Less(s0.GetStorageBase(), s1.GetStorageBase()));
    ASSERT_FALSE(s0.GetClass()->Greater(s0.GetStorageBase(), s1.GetStorageBase()));
}

TEST_F(TestString, TestConcat)
{
}

TEST_F(TestString, TestLength)
{
}

TEST_F(TestString, TestStringStreamInsert)
{
}

TEST_F(TestString, TestStringStreamExtract)
{
}

#include "TestCommon.h"

USING_NAMESPACE_KAI

struct TestString : TestCommon
{
protected:
    void AddrequiredClasses() override
    {
        Reg().AddClass<bool>();
        Reg().AddClass<int>();
        Reg().AddClass<String>();
    }
};

TEST_F(TestString, TestCompare)
{
    Pointer<String> s0 = Reg().New<String>("a");
    Pointer<String> s1 = Reg().New<String>("a");

    ASSERT_TRUE(s0.GetClass()->Equiv(s0.GetStorageBase(), s1.GetStorageBase()));

    *s1 = "b";
    ASSERT_FALSE(s0.GetClass()->Equiv(s0.GetStorageBase(), s1.GetStorageBase()));
    ASSERT_TRUE(s0.GetClass()->Less(s0.GetStorageBase(), s1.GetStorageBase()));
    ASSERT_FALSE(s0.GetClass()->Greater(s0.GetStorageBase(), s1.GetStorageBase()));
}

TEST_F(TestString, TestConcat)
{
}

TEST_F(TestString, TestLength)
{
}

TEST_F(TestString, TestStringStreamInsert)
{
}

TEST_F(TestString, TestStringStreamExtract)
{
}

Remove test that compared an empty string to bool


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

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

    return a.exec();
}

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

const QString APP_ORGNAME = "PepperNote";
const QString APP_APPNAME = "PepperNote";

int main(int argc, char *argv[])
{
    QCoreApplication::setOrganizationName(APP_ORGNAME);
    QCoreApplication::setApplicationName(APP_APPNAME);

    QApplication a(argc, argv);
    MainWindow w;
    w.show();

    return a.exec();
}

Set org name and app name


/*
 * Copyright 2015 - 2017 gtalent2@gmail.com
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 */
#include <map>
#include <ox/std/std.hpp>

using namespace std;
using namespace ox::std;

template<typename T>
int testBigEndianAdapt(string str) {
	auto i = (T) stoull(str, nullptr, 16);
	return !(bigEndianAdapt(bigEndianAdapt(i)) == i);
}

map<string, int(*)(string)> tests = {
	{
		{ "bigEndianAdapt<uint16_t>", testBigEndianAdapt<uint16_t> },
		{ "bigEndianAdapt<uint32_t>", testBigEndianAdapt<uint32_t> },
		{ "bigEndianAdapt<uint64_t>", testBigEndianAdapt<uint64_t> },
	},
};

int main(int argc, const char **args) {
	int retval = -1;
	if (argc > 1) {
		auto testName = args[1];
		string testArg = args[2];
		if (tests.find(testName) != tests.end()) {
			retval = tests[testName](testArg);
		}
	}
	return retval;
}

/*
 * Copyright 2015 - 2017 gtalent2@gmail.com
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 */
#include <map>
#include <string>
#include <ox/std/std.hpp>

using namespace std;
using namespace ox::std;

template<typename T>
int testBigEndianAdapt(string str) {
	auto i = (T) stoull(str, nullptr, 16);
	return !(bigEndianAdapt(bigEndianAdapt(i)) == i);
}

map<string, int(*)(string)> tests = {
	{
		{ "bigEndianAdapt<uint16_t>", testBigEndianAdapt<uint16_t> },
		{ "bigEndianAdapt<uint32_t>", testBigEndianAdapt<uint32_t> },
		{ "bigEndianAdapt<uint64_t>", testBigEndianAdapt<uint64_t> },
	},
};

int main(int argc, const char **args) {
	int retval = -1;
	if (argc > 1) {
		auto testName = args[1];
		string testArg = args[2];
		if (tests.find(testName) != tests.end()) {
			retval = tests[testName](testArg);
		}
	}
	return retval;
}

Add explicit <string> include to byteswap test


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

#include <errno.h>

#include "bin/utils.h"

OSError::OSError() {
  set_code(errno);
  SetMessage(strerror(errno));
}

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

#include <errno.h>

#include "bin/utils.h"

OSError::OSError() : code_(0), message_(NULL) {
  set_code(errno);
  SetMessage(strerror(errno));
}

Fix missing member initialization on Mac OS


#include <cstdlib>
#include <stdio.h>
#include <string.h>
#include <set>
#include <string>
#include <assert.h>

using namespace std;

set<string> done;

void dump_header(string header) {
    if (done.find(header) != done.end()) return;
    done.insert(header);

    FILE *f = fopen(header.c_str(), "r");

    if (f == NULL) {
      fprintf(stderr, "Could not open header %s.\n", header.c_str());
      exit(1);
    }

    char line[1024];

    while (fgets(line, 1024, f)) {
        if (strncmp(line, "#include \"", 10) == 0) {
            char *sub_header = line + 10;
            for (int i = 0; i < 1014; i++) {
                if (sub_header[i] == '"') sub_header[i] = 0;
            }
            size_t slash_pos = header.rfind('/');
            std::string path;
            if (slash_pos != std::string::npos)
                path = header.substr(0, slash_pos + 1);
            dump_header(path + sub_header);
        } else {
            fputs(line, stdout);
        }
    }

    fclose(f);
}

int main(int argc, char **headers) {
    for (int i = 1; i < argc; i++) {
        dump_header(headers[i]);
    }

    return 0;
}

#include <cstdlib>
#include <stdio.h>
#include <string.h>
#include <set>
#include <string>
#include <assert.h>

std::set<std::string> done;

void dump_header(std::string header) {
    if (done.find(header) != done.end()) return;
    done.insert(header);

    FILE *f = fopen(header.c_str(), "r");

    if (f == NULL) {
      fprintf(stderr, "Could not open header %s.\n", header.c_str());
      exit(1);
    }

    char line[1024];

    while (fgets(line, 1024, f)) {
        if (strncmp(line, "#include \"", 10) == 0) {
            char *sub_header = line + 10;
            for (int i = 0; i < 1014; i++) {
                if (sub_header[i] == '"') sub_header[i] = 0;
            }
            size_t slash_pos = header.rfind('/');
            std::string path;
            if (slash_pos != std::string::npos)
                path = header.substr(0, slash_pos + 1);
            dump_header(path + sub_header);
        } else {
            fputs(line, stdout);
        }
    }

    fclose(f);
}

int main(int argc, char **headers) {
    for (int i = 1; i < argc; i++) {
        dump_header(headers[i]);
    }

    return 0;
}

Remove dependency on importing std into global namespace.


#include "channel.h"
#include "timing/timingfactory.h"

class Channel::Private
{
public:
    Private()
    : id(0)
    {
    }

    int id;
    QString target;
    QString certificate;
    TimingPtr timing;
};

Channel::Channel()
: d(new Private)
{
}

Channel::Channel(const int &id, const QString &target, const QString &certificate, const TimingPtr &timing)
: d(new Private)
{
    d->id = id;
    d->target = target;
    d->certificate = certificate;
    d->timing = timing;
}

Channel::~Channel()
{
    delete d;
}

ChannelPtr Channel::fromVariant(const QVariant &variant)
{
    QVariantMap hash = variant.toMap();

    return ChannelPtr(new Channel(hash.value("id").toInt(),
                                  hash.value("target").toString(),
                                  hash.value("certificate").toString(),
                                  TimingFactory::timingFromVariant(hash.value("timing"))));
}

QVariant Channel::toVariant() const
{
    QVariantMap hash;
    hash.insert("id", d->id);
    hash.insert("target", d->target);
    hash.insert("certificate", d->certificate);
    hash.insert("timing", d->timing->toVariant());
    return hash;
}

void Channel::setTarget(const QString &target)
{
    d->target = target;
}

QString Channel::target() const
{
    return d->target;
}

TimingPtr Channel::timing() const
{
    return d->timing;
}

#include "channel.h"
#include "timing/timingfactory.h"

class Channel::Private
{
public:
    Private()
    : id(0)
    {
    }

    int id;
    QString target;
    QString certificate;
    TimingPtr timing;
};

Channel::Channel()
: d(new Private)
{
}

Channel::Channel(const int &id, const QString &target, const QString &certificate, const TimingPtr &timing)
: d(new Private)
{
    d->id = id;
    d->target = target;
    d->certificate = certificate;
    d->timing = timing;
}

Channel::~Channel()
{
    delete d;
}

ChannelPtr Channel::fromVariant(const QVariant &variant)
{
    QVariantMap hash = variant.toMap();

    return ChannelPtr(new Channel(hash.value("id").toInt(),
                                  hash.value("target").toString(),
                                  hash.value("certificate").toString(),
                                  TimingFactory::timingFromVariant(hash.value("timing"))));
}

QVariant Channel::toVariant() const
{
    QVariantMap hash;
    hash.insert("id", d->id);
    hash.insert("target", d->target);
    hash.insert("certificate", d->certificate);
    if(d->timing)
    {
        hash.insert("timing", d->timing->toVariant());
    }
    return hash;
}

void Channel::setTarget(const QString &target)
{
    d->target = target;
}

QString Channel::target() const
{
    return d->target;
}

TimingPtr Channel::timing() const
{
    return d->timing;
}

Fix bug when timing is not set inc hannel


#include <jni.h>
#include "Device.h"

namespace crown
{

//-----------------------------------------------------------------------------
extern "C" JNIEXPORT void JNICALL Java_crown_android_CrownLib_init(JNIEnv* env, jobject obj)
{
	device()->init(0, NULL);
}

//-----------------------------------------------------------------------------
extern "C" JNIEXPORT void JNICALL Java_crown_android_CrownLib_shutdown(JNIEnv* env, jobject obj)
{
	device()->shutdown();
}

//-----------------------------------------------------------------------------
extern "C" JNIEXPORT void JNICALL Java_crown_android_CrownLib_frame(JNIEnv* env, jobject obj)
{
	device()->frame();
}

//-----------------------------------------------------------------------------
extern "C" JNIEXPORT bool JNICALL Java_crown_android_CrownLib_isInit(JNIEnv* env, jobject obj)
{
	return device()->is_init();
}

//-----------------------------------------------------------------------------
extern "C" JNIEXPORT bool JNICALL Java_crown_android_CrownLib_isRunning(JNIEnv* env, jobject obj)
{
	return device()->is_running();
}

} // namespace crown

#include <jni.h>
#include "Device.h"

namespace crown
{

//-----------------------------------------------------------------------------
extern "C" JNIEXPORT void JNICALL Java_crown_android_CrownLib_init(JNIEnv* env, jobject obj)
{
	const char* argv[] = { "crown-android", "--root-path", "", "--dev" };

	device()->init(4, (char**)argv);
}

//-----------------------------------------------------------------------------
extern "C" JNIEXPORT void JNICALL Java_crown_android_CrownLib_shutdown(JNIEnv* env, jobject obj)
{
	device()->shutdown();
}

//-----------------------------------------------------------------------------
extern "C" JNIEXPORT void JNICALL Java_crown_android_CrownLib_frame(JNIEnv* env, jobject obj)
{
	device()->frame();
}

//-----------------------------------------------------------------------------
extern "C" JNIEXPORT bool JNICALL Java_crown_android_CrownLib_isInit(JNIEnv* env, jobject obj)
{
	return device()->is_init();
}

//-----------------------------------------------------------------------------
extern "C" JNIEXPORT bool JNICALL Java_crown_android_CrownLib_isRunning(JNIEnv* env, jobject obj)
{
	return device()->is_running();
}

} // namespace crown

Add some CL options for android


// Copyright (c) 2017 Pierre Fourgeaud
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.

#include "rendersystems/GL/indexbufferGL.h"
#include <glad/glad.h>

namespace CodeHero {

IndexBufferGL::IndexBufferGL() {
    glGenBuffers(1, &_GetGPUObjectHandle()->intHandle);
}

IndexBufferGL::~IndexBufferGL() {
    glDeleteBuffers(1, &_GetGPUObjectHandle()->intHandle);
}

void IndexBufferGL::Use() {
    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, GetGPUObject().intHandle);
}

void IndexBufferGL::Unuse() {
    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
}

void IndexBufferGL::_SetDataImpl(const void* iData) {
    Use();

    glBufferData(
            GL_ELEMENT_ARRAY_BUFFER,
            m_IndexSize,
            iData,
            m_IsDynamic ? GL_DYNAMIC_DRAW : GL_STATIC_DRAW);
}

} // namespace CodeHero

// Copyright (c) 2017 Pierre Fourgeaud
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.

#include "rendersystems/GL/indexbufferGL.h"
#include <glad/glad.h>

namespace CodeHero {

IndexBufferGL::IndexBufferGL() {
    glGenBuffers(1, &_GetGPUObjectHandle()->intHandle);
}

IndexBufferGL::~IndexBufferGL() {
    glDeleteBuffers(1, &_GetGPUObjectHandle()->intHandle);
}

void IndexBufferGL::Use() {
    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, GetGPUObject().intHandle);
}

void IndexBufferGL::Unuse() {
    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
}

void IndexBufferGL::_SetDataImpl(const void* iData) {
    Use();

    // TODO(pierre) The sizeof should be more abstracted
    glBufferData(
            GL_ELEMENT_ARRAY_BUFFER,
            m_IndexSize * sizeof(unsigned int),
            iData,
            m_IsDynamic ? GL_DYNAMIC_DRAW : GL_STATIC_DRAW);
}

} // namespace CodeHero

Fix wrong size for index buffer


#include <iostream>
#include <string>

#include <cppassist/cmdline/ArgumentParser.h>

int main(int argc, char* argv[])
{
  cppassist::ArgumentParser argParser;
  argParser.parse(argc, argv);

  auto inFileName = argParser.value("--input");
  auto outFileName = argParser.value("--output");

  auto outFileType = outFileName.substr(outFileName.find_last_of('.') + 1);

  auto fromGeneratedKernel = argParser.isSet("-k");

  if (fromGeneratedKernel)
  {
    std::cout << "Converting kernel \"" << inFileName << "\" to output file \"" << outFileName << "\" (type: " << outFileType << ")" <<std::endl;
  }
  else
  {
    std::cout << "Using kernel description \"" << inFileName << "\" to generate kernel \"" << outFileName << "\" (type: " << outFileType << ")" << std::endl;
  }

}

Add basic command line flag handling using cppassist/cmdline


#include "headers/mainwindow.h"
#include "ui_mainwindow.h"

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow) {
    ui->setupUi(this);

    /***************************************************************************
     * Create and set the settings button on the top left of the tabs
     **************************************************************************/
    buttonSettings = new QPushButton();
    ui->tabWidget->setCornerWidget(buttonSettings, Qt::TopLeftCorner);
    setupMenu();
    connect(buttonSettings, SIGNAL(clicked()),
            this, SLOT(openMenu()));

}

MainWindow::~MainWindow() {
    delete ui;
}

void MainWindow::setupMenu() {
    menuSettings = new QMenu(this);
    menuSettings->addAction("&File");
    menuSettings->addAction("&Help");

    QAction* aSettings = menuSettings->addAction("&Settings");
    connect(aSettings, SIGNAL(triggered()),
            this, SLOT(openSettings()));
    menuSettings->addSeparator();

    // Quit action
    QAction* aQuit = menuSettings->addAction("&Quit");
    this->addAction(aQuit);
    aQuit->setShortcut(QKeySequence(Qt::CTRL + Qt::Key_Q));
    connect(aQuit, SIGNAL(triggered()),
            this, SLOT(close()));
}

void MainWindow::openMenu() {
    menuSettings->exec(buttonSettings->mapToGlobal(QPoint(0, buttonSettings->height())));
}

void MainWindow::openSettings() {
    OptionsWindow* settings =  new OptionsWindow(this);
    settings->show();
}

#include "headers/mainwindow.h"
#include "ui_mainwindow.h"

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow) {
    ui->setupUi(this);

    /***************************************************************************
     * Create and set the settings button on the top left of the tabs
     **************************************************************************/
    buttonSettings = new QPushButton();
    buttonSettings->setText(QString("QtChronos"));
    ui->tabWidget->setCornerWidget(buttonSettings, Qt::TopLeftCorner);
    setupMenu();
    connect(buttonSettings, SIGNAL(clicked()),
            this, SLOT(openMenu()));

}

MainWindow::~MainWindow() {
    delete ui;
}

void MainWindow::setupMenu() {
    menuSettings = new QMenu(this);
    menuSettings->addAction("&File");
    menuSettings->addAction("&Help");

    QAction* aSettings = menuSettings->addAction("&Settings");
    connect(aSettings, SIGNAL(triggered()),
            this, SLOT(openSettings()));
    menuSettings->addSeparator();

    // Quit action
    QAction* aQuit = menuSettings->addAction("&Quit");
    this->addAction(aQuit);
    aQuit->setShortcut(QKeySequence(Qt::CTRL + Qt::Key_Q));
    connect(aQuit, SIGNAL(triggered()),
            this, SLOT(close()));
}

void MainWindow::openMenu() {
    menuSettings->exec(buttonSettings->mapToGlobal(QPoint(0, buttonSettings->height())));
}

void MainWindow::openSettings() {
    OptionsWindow* settings =  new OptionsWindow(this);
    settings->show();
}

Set TopLeft button text as QtChronos


// RUN: %clang_cc1 %s -emit-llvm -o - -triple=i686-apple-darwin9 | FileCheck %s
struct A {
  _Atomic(int) i;
  A(int j);
  void v(int j);
};
// Storing to atomic values should be atomic
// CHECK: store atomic i32
void A::v(int j) { i = j; }
// Initialising atomic values should not be atomic
// CHECK-NOT: store atomic
A::A(int j) : i(j) {}

struct B {
  int i;
  B(int x) : i(x) {}
};

_Atomic(B) b;

// CHECK: define void @_Z11atomic_initR1Ai
void atomic_init(A& a, int i) {
  // CHECK-NOT: atomic
  __atomic_init(&b, B(i));
}

// RUN: %clang_cc1 %s -emit-llvm -o - -triple=i686-apple-darwin9 | FileCheck %s
struct A {
  _Atomic(int) i;
  A(int j);
  void v(int j);
};
// Storing to atomic values should be atomic
// CHECK: store atomic i32
void A::v(int j) { i = j; }
// Initialising atomic values should not be atomic
// CHECK-NOT: store atomic
A::A(int j) : i(j) {}

struct B {
  int i;
  B(int x) : i(x) {}
};

_Atomic(B) b;

// CHECK: define void @_Z11atomic_initR1Ai
void atomic_init(A& a, int i) {
  // CHECK-NOT: atomic
  __c11_atomic_init(&b, B(i));
}

Update recently-added test to use new __c11_ form of atomic builtins.


//===-- sanitizer_vector_test.cc ------------------------------------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file is a part of *Sanitizer runtime.
//
//===----------------------------------------------------------------------===//
#include "sanitizer_common/sanitizer_vector.h"
#include "gtest/gtest.h"

namespace __sanitizer {

TEST(Vector, Basic) {
  Vector<int> v;
  EXPECT_EQ(v.Size(), (uptr)0);
  v.PushBack(42);
  EXPECT_EQ(v.Size(), (uptr)1);
  EXPECT_EQ(v[0], 42);
  v.PushBack(43);
  EXPECT_EQ(v.Size(), (uptr)2);
  EXPECT_EQ(v[0], 42);
  EXPECT_EQ(v[1], 43);
}

TEST(Vector, Stride) {
  Vector<int> v;
  for (int i = 0; i < 1000; i++) {
    v.PushBack(i);
    EXPECT_EQ(v.Size(), (uptr)(i + 1));
    EXPECT_EQ(v[i], i);
  }
  for (int i = 0; i < 1000; i++) {
    EXPECT_EQ(v[i], i);
  }
}

}  // namespace __sanitizer

//===-- sanitizer_vector_test.cc ------------------------------------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file is a part of *Sanitizer runtime.
//
//===----------------------------------------------------------------------===//
#include "sanitizer_common/sanitizer_vector.h"
#include "gtest/gtest.h"

namespace __sanitizer {

TEST(Vector, Basic) {
  Vector<int> v;
  EXPECT_EQ(v.Size(), 0u);
  v.PushBack(42);
  EXPECT_EQ(v.Size(), 1u);
  EXPECT_EQ(v[0], 42);
  v.PushBack(43);
  EXPECT_EQ(v.Size(), 2u);
  EXPECT_EQ(v[0], 42);
  EXPECT_EQ(v[1], 43);
}

TEST(Vector, Stride) {
  Vector<int> v;
  for (int i = 0; i < 1000; i++) {
    v.PushBack(i);
    EXPECT_EQ(v.Size(), i + 1u);
    EXPECT_EQ(v[i], i);
  }
  for (int i = 0; i < 1000; i++) {
    EXPECT_EQ(v[i], i);
  }
}

}  // namespace __sanitizer

Replace cast with unsigned literals in tests


#include <Halide.h>
#include <sys/time.h>

using namespace Halide;

double currentTime() {
    timeval t;
    gettimeofday(&t, NULL);
    return t.tv_sec * 1000.0 + t.tv_usec / 1000.0f;
}

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

    Func f, g, h; Var x, y;

    h(x) = x;
    g(x) = h(x-1) + h(x+1);
    f(x, y) = (g(x-1) + g(x+1)) + y;

    h.root();
    g.root();

    if (use_gpu()) {
        f.cudaTile(x, y, 16, 16);
        g.cudaTile(x, 128);
        h.cudaTile(x, 128);
    }

    Image<int> out = f.realize(32, 32);

    for (int y = 0; y < 32; y++) {
        for (int x = 0; x < 32; x++) {
            if (out(x, y) != x*4 + y) {
                printf("out(%d, %d) = %d instead of %d\n", x, y, out(x, y), x*4+y);
                return -1;
            }
        }
    }

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

#include <Halide.h>
using namespace Halide;

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

    Func f, g, h; Var x, y;

    h(x) = x;
    g(x) = h(x-1) + h(x+1);
    f(x, y) = (g(x-1) + g(x+1)) + y;

    h.root();
    g.root();

    if (use_gpu()) {
        f.cudaTile(x, y, 16, 16);
        g.cudaTile(x, 128);
        h.cudaTile(x, 128);
    }

    Image<int> out = f.realize(32, 32);

    for (int y = 0; y < 32; y++) {
        for (int x = 0; x < 32; x++) {
            if (out(x, y) != x*4 + y) {
                printf("out(%d, %d) = %d instead of %d\n", x, y, out(x, y), x*4+y);
                return -1;
            }
        }
    }

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

Clear spurious timing code from bounds_interence


// RUN: rm -rf %t
// RUN: pp-trace -ignore FileChanged,MacroDefined %s -x objective-c++ -undef -target x86_64 -std=c++11 -fmodules -fcxx-modules -fmodules-cache-path=%t -I%S -I%S/Input | FileCheck --strict-whitespace %s

// CHECK: ---

@import Level1A;

// CHECK-NEXT: - Callback: moduleImport
// CHECK-NEXT:   ImportLoc: "{{.*}}{{[/\\]}}pp-trace-modules.cpp:[[@LINE-3]]:2"
// CHECK-NEXT:   Path: [{Name: Level1A, Loc: "{{.*}}{{[/\\]}}pp-trace-modules.cpp:[[@LINE-4]]:9"}]
// CHECK-NEXT:   Imported: Level1A

@import Level1B.Level2B;

// CHECK-NEXT: - Callback: moduleImport
// CHECK-NEXT:   ImportLoc: "{{.*}}{{[/\\]}}pp-trace-modules.cpp:[[@LINE-3]]:2"
// CHECK-NEXT:   Path: [{Name: Level1B, Loc: "{{.*}}{{[/\\]}}pp-trace-modules.cpp:[[@LINE-4]]:9"}, {Name: Level2B, Loc: "{{.*}}{{[/\\]}}pp-trace-modules.cpp:[[@LINE-4]]:17"}]
// CHECK-NEXT:   Imported: Level2B
// CHECK-NEXT: - Callback: EndOfMainFile
// CHECK-NEXT: ...

// RUN: rm -rf %t
// RUN: pp-trace -ignore FileChanged,MacroDefined %s -x objective-c++ -undef -target x86_64 -std=c++11 -fmodules -fcxx-modules -fmodules-cache-path=%t -I%S -I%S/Input | FileCheck --strict-whitespace %s
// REQUIRES: x86-registered-target
// CHECK: ---

@import Level1A;

// CHECK-NEXT: - Callback: moduleImport
// CHECK-NEXT:   ImportLoc: "{{.*}}{{[/\\]}}pp-trace-modules.cpp:[[@LINE-3]]:2"
// CHECK-NEXT:   Path: [{Name: Level1A, Loc: "{{.*}}{{[/\\]}}pp-trace-modules.cpp:[[@LINE-4]]:9"}]
// CHECK-NEXT:   Imported: Level1A

@import Level1B.Level2B;

// CHECK-NEXT: - Callback: moduleImport
// CHECK-NEXT:   ImportLoc: "{{.*}}{{[/\\]}}pp-trace-modules.cpp:[[@LINE-3]]:2"
// CHECK-NEXT:   Path: [{Name: Level1B, Loc: "{{.*}}{{[/\\]}}pp-trace-modules.cpp:[[@LINE-4]]:9"}, {Name: Level2B, Loc: "{{.*}}{{[/\\]}}pp-trace-modules.cpp:[[@LINE-4]]:17"}]
// CHECK-NEXT:   Imported: Level2B
// CHECK-NEXT: - Callback: EndOfMainFile
// CHECK-NEXT: ...

Add a missing target requirement.


#include "spaghetti/logger.h"

namespace spaghetti::log {

Logger g_loggerConsole{};
Logger g_loggerFile{};

void init()
{
  if (!g_loggerConsole) g_loggerConsole = spdlog::stdout_color_mt("console");
  if (!g_loggerFile) g_loggerFile = spdlog::basic_logger_mt("file", "spaghetti.log");

  spdlog::set_pattern("[%Y.%m.%d %H:%M:%S.%e] [%n] [%L] %v");
}

Loggers get()
{
  return { g_loggerConsole, g_loggerFile };
}

} // namespace spaghetti::log

#include "spaghetti/logger.h"

namespace spaghetti::log {

Logger g_loggerConsole{};
Logger g_loggerFile{};

void init()
{
  if (!g_loggerConsole) g_loggerConsole = spdlog::stdout_color_mt("console");
  if (!g_loggerFile) g_loggerFile = spdlog::basic_logger_mt("file", "spaghetti.log");

  spdlog::set_pattern("[%Y.%m.%d %H:%M:%S.%e] [%n] [%L] %v");

  g_loggerConsole->set_level(spdlog::level::debug);
}

Loggers get()
{
  return { g_loggerConsole, g_loggerFile };
}

} // namespace spaghetti::log

Set console log level to debug


/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/*
 * This file is part of the libone project.
 *
 * 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 <string>
#include <librevenge-stream/librevenge-stream.h>
#include <unordered_map>
#include <iostream>
#include <iostream>
#include <iomanip>
#include "StringInStorageBuffer.h"
#include "libone_utils.h"

namespace libone {

  void StringInStorageBuffer::parse(librevenge::RVNGInputStream *input) {
    std::stringstream stream;
    length = readU32(input);
    std::vector<char> string;
    char *buf = (char *) readNBytes(input, length*2);
    string.assign(buf, buf+length*2);
    ustring = librevenge::RVNGString((char *) &string[0]);

    ONE_DEBUG_MSG(("read length1 %lu length2 %lu string1 %s string2 %s end\n", length, ustring.len(), &string[0], ustring.cstr()));
  }

  std::string StringInStorageBuffer::to_string() {
    return ustring.cstr();
  }

}

/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/*
 * This file is part of the libone project.
 *
 * 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 <string>
#include <librevenge-stream/librevenge-stream.h>
#include <unordered_map>
#include <iostream>
#include <iostream>
#include <iomanip>
#include "StringInStorageBuffer.h"
#include "libone_utils.h"

namespace libone {

  void StringInStorageBuffer::parse(librevenge::RVNGInputStream *input) {
    std::stringstream stream;
    length = readU32(input);
    std::vector<char> string;
    char *buf = (char *) readNBytes(input, length*2);
    string.assign(buf, buf+length*2);
    ustring = librevenge::RVNGString((char *) &string[0]);

    ONE_DEBUG_MSG(("read length1 %u length2 %u string1 %s string2 %s end\n", length, ustring.len(), &string[0], ustring.cstr()));
  }

  std::string StringInStorageBuffer::to_string() {
    return ustring.cstr();
  }

}

Fix some more debugging fallout


#include <QInputDialog>

#include "QGCTCPLinkConfiguration.h"
#include "ui_QGCTCPLinkConfiguration.h"
#include <stdint.h>

QGCTCPLinkConfiguration::QGCTCPLinkConfiguration(TCPLink* link, QWidget *parent) :
    QWidget(parent),
    link(link),
    ui(new Ui::QGCTCPLinkConfiguration)
{
    ui->setupUi(this);
    uint16_t port = link->getPort();
    ui->portSpinBox->setValue(port);
    QString addr = link->getHostAddress().toString();
    ui->hostAddressLineEdit->setText(addr);
    connect(ui->portSpinBox, SIGNAL(valueChanged(int)), link, SLOT(setPort(int)));
    connect(ui->hostAddressLineEdit, SIGNAL(textChanged (const QString &)), link, SLOT(setAddress(const QString &)));
}

QGCTCPLinkConfiguration::~QGCTCPLinkConfiguration()
{
    delete ui;
}

void QGCTCPLinkConfiguration::changeEvent(QEvent *e)
{
    QWidget::changeEvent(e);
    switch (e->type()) {
    case QEvent::LanguageChange:
        ui->retranslateUi(this);
        break;
    default:
        break;
    }
}

#include <QInputDialog>

#include "QGCTCPLinkConfiguration.h"
#include "ui_QGCTCPLinkConfiguration.h"
#include <stdint.h>

QGCTCPLinkConfiguration::QGCTCPLinkConfiguration(TCPLink* link, QWidget *parent) :
    QWidget(parent),
    link(link),
    ui(new Ui::QGCTCPLinkConfiguration)
{
    ui->setupUi(this);
    uint16_t port = link->getPort();
    ui->portSpinBox->setValue(port);
    QString addr = link->getHostAddress().toString();
    ui->hostAddressLineEdit->setText(addr);
    connect(ui->portSpinBox, SIGNAL(valueChanged(int)), link, SLOT(setPort(int)));
    connect(ui->hostAddressLineEdit, SIGNAL(textChanged (const QString &)), link, SLOT(setHostAddress(const QString &)));
}

QGCTCPLinkConfiguration::~QGCTCPLinkConfiguration()
{
    delete ui;
}

void QGCTCPLinkConfiguration::changeEvent(QEvent *e)
{
    QWidget::changeEvent(e);
    switch (e->type()) {
    case QEvent::LanguageChange:
        ui->retranslateUi(this);
        break;
    default:
        break;
    }
}

Fix basic issue with connecting using TCP


#include "authdialog.h"

#include <qconnman/manager.h>
#include <qconnman/agent.h>

#include <QDebug>

AuthDialog::AuthDialog(Manager *manager, QWidget *parent):
    QDialog(parent),
    m_manager(manager)
{
    ui.setupUi(this);

    connect(ui.showPassword, SIGNAL(toggled(bool)), SLOT(showPassword(bool)));
}

int AuthDialog::exec()
{
    Agent *agent = qobject_cast<Agent *>(QObject::sender());
    Agent::InputRequest *request = agent->currentInputRequest();

    ui.label->setText(trUtf8("This network requires a %1 password to connect. Please enter the password bellow.")
                      .arg(m_manager->service(request->service)->security().join("").toUpper()));

    int result = QDialog::exec();
    if (result == QDialog::Accepted)
        request->response.passphrase = ui.password->text();
    else
        request->cancel = true;

    return result;
}

void AuthDialog::showPassword(bool checked)
{
    if (!checked)
        ui.password->setEchoMode(QLineEdit::Password);
    else
        ui.password->setEchoMode(QLineEdit::Normal);
}

#include "authdialog.h"

#include <qconnman/manager.h>
#include <qconnman/agent.h>

#include <QDebug>

AuthDialog::AuthDialog(Manager *manager, QWidget *parent):
    QDialog(parent),
    m_manager(manager)
{
    ui.setupUi(this);

    connect(ui.showPassword, SIGNAL(toggled(bool)), SLOT(showPassword(bool)));
}

int AuthDialog::exec()
{
    Agent *agent = qobject_cast<Agent *>(QObject::sender());
    Agent::InputRequest *request = agent->currentInputRequest();

    ui.password->clear();
    ui.password->setFocus();
    ui.label->setText(trUtf8("This network requires a %1 password to connect. Please enter the password bellow.")
                      .arg(m_manager->service(request->service)->security().join("").toUpper()));

    int result = QDialog::exec();
    if (result == QDialog::Accepted)
        request->response.passphrase = ui.password->text();
    else
        request->cancel = true;

    return result;
}

void AuthDialog::showPassword(bool checked)
{
    if (!checked)
        ui.password->setEchoMode(QLineEdit::Password);
    else
        ui.password->setEchoMode(QLineEdit::Normal);
}

Set focus on password field


// Copyright 2017, Dawid Kurek, <dawikur@gmail.com>

#include "lel/operation/unary.hpp"

#include "gtest/gtest.h"

TEST(unary_test, logical_not_can_be_used_in_constexpr) {
  std::logical_not<> logical_not;

  static_assert(logical_not(false), "");
}

TEST(unary_test, indirection_can_be_used_in_constexpr) {
  LeL::Operation::__Indirection indirection;

  int const val = 5;

  static_assert(indirection(&val) == 5, "");
}

Remove problemanic on VS test


#include <iostream>

#include <texturebased/polarmapped.h>

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

    // TODO: glfw

    return 0;
}

#include <iostream>

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

#include <glbinding/Binding.h>

#include <glbinding/gl/gl.h>
#include <globjects/globjects.h>

using namespace gl;

void error(int errnum, const char * errmsg)
{
    std::cerr << errnum << ": " << errmsg << std::endl;
}

void key_callback(GLFWwindow * window, int key, int /*scancode*/, int action, int /*mods*/)
{
    if (key == GLFW_KEY_ESCAPE && action == GLFW_PRESS)
        glfwSetWindowShouldClose(window, 1);
}

int main(int, char *[])
{
    if (!glfwInit())
        return 1;

    glfwSetErrorCallback(error);

    glfwDefaultWindowHints();

#ifdef SYSTEM_DARWIN
    glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
    glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 2);
    glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, true);
    glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
#endif

    GLFWwindow * window = glfwCreateWindow(640, 480, "Texture Demo", nullptr, nullptr);
    if (!window)
    {
        glfwTerminate();
        return -1;
    }

    glfwSetKeyCallback(window, key_callback);

    glfwMakeContextCurrent(window);

    glbinding::Binding::initialize(false); // only resolve functions that are actually used (lazy)
    globjects::init();

    while (!glfwWindowShouldClose(window))
    {
        glfwPollEvents();
        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
        glfwSwapBuffers(window);
    }

    glfwTerminate();
    return 0;
}

Add glfw window to texture demo


#include "ImwWindowManagerDX11.h"
#include "ImwPlatformWindowDX11.h"

#include <imgui_impl_dx11.h>

using namespace ImWindow;

ImwWindowManagerDX11::ImwWindowManagerDX11()
{
	ImwPlatformWindowDX11::InitDX11();
}

ImwWindowManagerDX11::~ImwWindowManagerDX11()
{
	ImwPlatformWindowDX11::ShutdownDX11();
	//ImGui_ImplDX11_Shutdown();
}

void ImwWindowManagerDX11::InternalRun()
{
	MSG msg;
	if (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE))
	{
		TranslateMessage(&msg);
		DispatchMessage(&msg);
	}
	else
	{
		Update();
	}
}

ImwPlatformWindow* ImwWindowManagerDX11::CreatePlatformWindow(bool bMain, ImwPlatformWindow* pParent, bool bDragWindow)
{
	ImwPlatformWindowDX11* pWindow = new ImwPlatformWindowDX11(bMain, bDragWindow);
	ImwTest(pWindow->Init(pParent));
	return (ImwPlatformWindow*)pWindow;
}

ImVec2 ImwWindowManagerDX11::GetCursorPos()
{
	POINT oPoint;
	::GetCursorPos(&oPoint);
	return ImVec2(oPoint.x, oPoint.y);
}

#include "ImwWindowManagerDX11.h"
#include "ImwPlatformWindowDX11.h"

#include <imgui_impl_dx11.h>

using namespace ImWindow;

ImwWindowManagerDX11::ImwWindowManagerDX11()
{
	ImwPlatformWindowDX11::InitDX11();
}

ImwWindowManagerDX11::~ImwWindowManagerDX11()
{
	ImwPlatformWindowDX11::ShutdownDX11();
	//ImGui_ImplDX11_Shutdown();
}

void ImwWindowManagerDX11::InternalRun()
{
	MSG msg;
	if (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE))
	{
		TranslateMessage(&msg);
		DispatchMessage(&msg);
	}
	else
	{
		Update();
		Sleep(16);
	}
}

ImwPlatformWindow* ImwWindowManagerDX11::CreatePlatformWindow(bool bMain, ImwPlatformWindow* pParent, bool bDragWindow)
{
	ImwPlatformWindowDX11* pWindow = new ImwPlatformWindowDX11(bMain, bDragWindow);
	ImwTest(pWindow->Init(pParent));
	return (ImwPlatformWindow*)pWindow;
}

ImVec2 ImwWindowManagerDX11::GetCursorPos()
{
	POINT oPoint;
	::GetCursorPos(&oPoint);
	return ImVec2(oPoint.x, oPoint.y);
}

Add sleep of 16 milliseconds for reduce framerate (High framerate make than my GPU do sharp creepy sound)


/*
 * RecorderEndPoint.cpp - Kurento Media Server
 *
 * Copyright (C) 2013 Kurento
 * Contact: Miguel París Díaz <mparisdiaz@gmail.com>
 * Contact: José Antonio Santos Cadenas <santoscadenas@kurento.com>
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License version 3
 * as published by the Free Software Foundation.
 *
 * 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, see <http://www.gnu.org/licenses/>.
 */

#include "RecorderEndPoint.hpp"

namespace kurento
{

RecorderEndPoint::RecorderEndPoint (std::shared_ptr<MediaManager> parent, const std::string &uri)
  : UriEndPoint (parent, uri, UriEndPointType::type::RECORDER_END_POINT)
{

}

RecorderEndPoint::~RecorderEndPoint() throw ()
{

}

} // kurento

/*
 * RecorderEndPoint.cpp - Kurento Media Server
 *
 * Copyright (C) 2013 Kurento
 * Contact: Miguel París Díaz <mparisdiaz@gmail.com>
 * Contact: José Antonio Santos Cadenas <santoscadenas@kurento.com>
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License version 3
 * as published by the Free Software Foundation.
 *
 * 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, see <http://www.gnu.org/licenses/>.
 */

#include "RecorderEndPoint.hpp"

namespace kurento
{

RecorderEndPoint::RecorderEndPoint (std::shared_ptr<MediaManager> parent, const std::string &uri)
  : UriEndPoint (parent, uri, UriEndPointType::type::RECORDER_END_POINT)
{
  gchar *name;

  name = getIdStr ();
  element = gst_element_factory_make ("recorderendpoint", name);
  g_free (name);

  g_object_ref (element);
  gst_bin_add (GST_BIN (parent->element), element);
  gst_element_sync_state_with_parent (element);
}

RecorderEndPoint::~RecorderEndPoint() throw ()
{
  gst_bin_remove (GST_BIN (parent->element), element);
  gst_element_set_state (element, GST_STATE_NULL);
  g_object_unref (element);
}

} // kurento

Create element for recorder endpoint


// This file is distributed under the MIT license.
// See the LICENSE file for details.

#include <visionaray/detail/macros.h>

#if defined(VSNRAY_OS_WIN32)
#include <windows.h>
#else
#include <unistd.h>
#endif

#include "util.h"

unsigned visionaray::get_num_processors()
{
#if defined(VSNRAY_OS_WIN32)

    SYSTEM_INFO sysinfo;
    GetNativeSystemInfo(&sysinfo);
    return static_cast<unsigned>(sysinfo.dwNumberOfProcessors);

#else

    return static_cast<unsigned>(sysconf(_SC_NPROCESSORS_ONLN));

#endif
}

// This file is distributed under the MIT license.
// See the LICENSE file for details.

#include <visionaray/detail/macros.h>
#include <visionaray/detail/platform.h>

#if defined(VSNRAY_OS_WIN32)
#include <windows.h>
#else
#include <unistd.h>
#endif

#include "util.h"

unsigned visionaray::get_num_processors()
{
#if defined(VSNRAY_OS_WIN32)

    SYSTEM_INFO sysinfo;
    GetNativeSystemInfo(&sysinfo);
    return static_cast<unsigned>(sysinfo.dwNumberOfProcessors);

#else

    return static_cast<unsigned>(sysconf(_SC_NPROCESSORS_ONLN));

#endif
}

Include platform header before determining OS


#include <iostream>

#include "floaxie/dtoa.h"

using namespace std;
using namespace floaxie;

int main(int, char**)
{
	double pi = 0.1;
	char buffer[128];

	for (int i = 0; i < 128; ++i)
		buffer[i] = 0;

	dtoa(pi, buffer);
	std::cout << "pi: " << pi << ", buffer: " << buffer << std::endl;

	return 0;
}

#include <iostream>

#include "floaxie/dtoa.h"

using namespace std;
using namespace floaxie;

int main(int, char**)
{
	double pi = 0.1;
	char buffer[128];

	dtoa(pi, buffer);
	std::cout << "pi: " << pi << ", buffer: " << buffer << std::endl;

	return 0;
}

Remove unnecessary zeroing out of output buffer


/*
 * Copyright (c) 2012 by Matthias Noack, Zuse Institute Berlin
 *
 * Licensed under the BSD License, see LICENSE file for details.
 *
 */

#include "libxtreemfs/interrupt.h"

#include <boost/date_time.hpp>

namespace xtreemfs
{

  Interruptibilizer::query_function Interruptibilizer::f_ = NULL;

  void
  Interruptibilizer::Initialize(query_function f)
  {
    f_ = f;
  }

  bool
  Interruptibilizer::WasInterrupted()
  {
    return (f_ == NULL) ? false : static_cast<bool>(f_()); // TODO: NULL check still needed and usefull?
  }

  void
  Interruptibilizer::SleepInterruptible(int rel_time_in_ms)
  {
    assert(rel_time_in_ms >= 0);
    const int intervall_in_ms = 100;
    int runs = rel_time_in_ms / intervall_in_ms
        + ((rel_time_in_ms % intervall_in_ms) > 0 ? 1 : 0);

    for (int i = 0; i < runs && !Interruptibilizer::WasInterrupted(); ++i)
      {
        boost::this_thread::sleep(boost::posix_time::millisec(intervall_in_ms));
      }
  }

} // namespace xtreemfs

/*
 * Copyright (c) 2012 by Matthias Noack, Zuse Institute Berlin
 *
 * Licensed under the BSD License, see LICENSE file for details.
 *
 */

#include "libxtreemfs/interrupt.h"

#include <boost/date_time/posix_time/posix_time_types.hpp>

namespace xtreemfs
{

  Interruptibilizer::query_function Interruptibilizer::f_ = NULL;

  void
  Interruptibilizer::Initialize(query_function f)
  {
    f_ = f;
  }

  bool
  Interruptibilizer::WasInterrupted()
  {
    return (f_ == NULL) ? false : static_cast<bool>(f_()); // TODO: NULL check still needed and usefull?
  }

  void
  Interruptibilizer::SleepInterruptible(int rel_time_in_ms)
  {
    assert(rel_time_in_ms >= 0);
    const int intervall_in_ms = 100;
    int runs = rel_time_in_ms / intervall_in_ms
        + ((rel_time_in_ms % intervall_in_ms) > 0 ? 1 : 0);

    for (int i = 0; i < runs && !Interruptibilizer::WasInterrupted(); ++i)
      {
        boost::this_thread::sleep(boost::posix_time::millisec(intervall_in_ms));
      }
  }

} // namespace xtreemfs

Fix compilation error by including a more specific header file.


/*
* System Call getentropy(2)
* (C) 2017 Alexander Bluhm (genua GmbH)
*
* Botan is released under the Simplified BSD License (see license.txt)
*/

#include <botan/internal/getentropy.h>

#if defined(BOTAN_TARGET_OS_IS_OPENBSD) || defined(BOTAN_TARGET_OS_IS_FREEBSD) || defined(BOTAN_TARGET_OS_IS_SOLARIS)
   #include <unistd.h>
#else
   #include <sys/random.h>
#endif

namespace Botan {

/**
* Gather 256 bytes entropy from getentropy(2).  Note that maximum
* buffer size is limited to 256 bytes.  On OpenBSD this does neither
* block nor fail.
*/
size_t Getentropy::poll(RandomNumberGenerator& rng)
   {
   secure_vector<uint8_t> buf(256);

   if(::getentropy(buf.data(), buf.size()) == 0)
      {
      rng.add_entropy(buf.data(), buf.size());
      return buf.size() * 8;
      }

   return 0;
   }
}

/*
* System Call getentropy(2)
* (C) 2017 Alexander Bluhm (genua GmbH)
*
* Botan is released under the Simplified BSD License (see license.txt)
*/

#include <botan/internal/getentropy.h>

#if defined(BOTAN_TARGET_OS_IS_OPENBSD) || defined(BOTAN_TARGET_OS_IS_FREEBSD) || defined(BOTAN_TARGET_OS_IS_SOLARIS)
   #include <unistd.h>
#else
   #if defined(BOTAN_TARGET_OS_HAS_POSIX1)
      // Allows successful compilation on macOS older than 10.12: Provides a missing typedef for `u_int`.
      #include <sys/types.h>
   #endif
   #include <sys/random.h>
#endif

namespace Botan {

/**
* Gather 256 bytes entropy from getentropy(2).  Note that maximum
* buffer size is limited to 256 bytes.  On OpenBSD this does neither
* block nor fail.
*/
size_t Getentropy::poll(RandomNumberGenerator& rng)
   {
   secure_vector<uint8_t> buf(256);

   if(::getentropy(buf.data(), buf.size()) == 0)
      {
      rng.add_entropy(buf.data(), buf.size());
      return buf.size() * 8;
      }

   return 0;
   }
}

Fix compilation issue on older mac (< 10.12)


//
//  src/utils/directory.cc
//  tbd
//
//  Created by inoahdev on 10/17/17.
//  Copyright © 2017 inoahdev. All rights reserved.
//

#include "directory.h"

namespace utils {
    directory::open_result directory::open(const char *path) {
        dir = opendir(path);
        if (!dir) {
            return open_result::failed_to_open_directory;
        }

        this->path = path;
        return open_result::ok;
    }

    directory::open_result directory::open(const std::string &path) {
        dir = opendir(path.data());
        if (!dir) {
            return open_result::failed_to_open_directory;
        }

        this->path = path;
        return open_result::ok;
    }

    directory::~directory() noexcept {
        if (dir != nullptr) {
            closedir(dir);
            dir = nullptr;
        }
    }
}

//
//  src/utils/directory.cc
//  tbd
//
//  Created by inoahdev on 10/17/17.
//  Copyright © 2017 inoahdev. All rights reserved.
//

#include "directory.h"

namespace utils {
    directory::open_result directory::open(const char *path) {
        this->path = path;
        this->dir = opendir(path);

        if (!dir) {
            return open_result::failed_to_open_directory;
        }

        return open_result::ok;
    }

    directory::open_result directory::open(const std::string &path) {
        this->path = path;
        this->dir = opendir(path.data());

        if (!dir) {
            return open_result::failed_to_open_directory;
        }

        return open_result::ok;
    }

    directory::~directory() noexcept {
        if (dir != nullptr) {
            closedir(dir);
            dir = nullptr;
        }
    }
}

Fix bug where directories would fail to open when recursing


#include "robobo.h"
#include "configuration.cpp"
#include "servercapab.cpp"
#include "socket.cpp"

std::string input, command, currentNick;
std::vector<std::string> inputParams;
bool registered;

int main(int argc, char** argv) {
	ConfigReader config;
	Socket bot_socket (config.getServer(), config.getPort());
	bot_socket.sendMsg("NICK :RoBoBo");
	bot_socket.sendMsg("USER RoBoBo here " + config.getServer() + " :RoBoBo-IRC-BoBo IRC Bot");
	currentNick = "RoBoBo";
	while (true) {
		if (!bot_socket.isConnected()) {
			bot_socket.closeConnection();
			std::cout << "Disconnected from server." << std::endl;
			return 0;
		}
		input = bot_socket.receive();
		std::cout << input << std::endl;
		inputParams.clear();
		inputParams = bot_socket.parseLine(input);
		command = inputParams[1];
		std::cout << "Command/Numeric: " << command << std::endl;
		if (command == "001")
			registered = true;
		if (command == "005")
			handleCapab(inputParams);
		if (command == "433" && !registered) {
			currentNick += "_";
			bot_socket.sendMsg("NICK :" + currentNick);
		}
	}
}

#include "robobo.h"
#include "configuration.cpp"
#include "servercapab.cpp"
#include "socket.cpp"

std::string input, command, currentNick;
std::vector<std::string> inputParams;
bool registered;

int main(int argc, char** argv) {
	ConfigReader config;
	Socket bot_socket (config.getServer(), config.getPort());
	bot_socket.sendMsg("NICK :RoBoBo");
	bot_socket.sendMsg("USER RoBoBo here " + config.getServer() + " :RoBoBo-IRC-BoBo IRC Bot");
	currentNick = "RoBoBo";
	while (true) {
		if (!bot_socket.isConnected()) {
			bot_socket.closeConnection();
			std::cout << "Disconnected from server." << std::endl;
			return 0;
		}
		input = bot_socket.receive();
		std::cout << input << std::endl;
		inputParams.clear();
		inputParams = bot_socket.parseLine(input);
		command = inputParams[1];
		if (command == "001")
			registered = true;
		if (command == "005")
			handleCapab(inputParams);
		if (command == "433" && !registered) {
			currentNick += "_";
			bot_socket.sendMsg("NICK :" + currentNick);
		}
	}
}

Remove a line included to test the parser.


#include "DMRecordTask.h"
#include "DMUtil.h"
#include "DMWriteTask.h"
#include "SkCommandLineFlags.h"
#include "SkRecording.h"

DEFINE_bool(skr, false, "If true, run SKR tests.");

namespace DM {

RecordTask::RecordTask(const Task& parent, skiagm::GM* gm, SkBitmap reference)
    : CpuTask(parent)
    , fName(UnderJoin(parent.name().c_str(), "skr"))
    , fGM(gm)
    , fReference(reference)
    {}

void RecordTask::draw() {
    // Record the GM into an SkRecord.
    EXPERIMENTAL::SkRecording recording(fReference.width(), fReference.height());
    fGM->draw(recording.canvas());
    SkAutoTDelete<const EXPERIMENTAL::SkPlayback> playback(recording.releasePlayback());

    // Draw the SkRecord back into a bitmap.
    SkBitmap bitmap;
    SetupBitmap(fReference.colorType(), fGM.get(), &bitmap);
    SkCanvas target(bitmap);
    playback->draw(&target);

    if (!BitmapsEqual(bitmap, fReference)) {
        this->fail();
        this->spawnChild(SkNEW_ARGS(WriteTask, (*this, bitmap)));
    }
}

bool RecordTask::shouldSkip() const {
    return !FLAGS_skr;
}

}  // namespace DM

#include "DMRecordTask.h"
#include "DMUtil.h"
#include "DMWriteTask.h"
#include "SkCommandLineFlags.h"
#include "SkRecording.h"

DEFINE_bool(skr, false, "If true, run SKR tests.");

namespace DM {

RecordTask::RecordTask(const Task& parent, skiagm::GM* gm, SkBitmap reference)
    : CpuTask(parent)
    , fName(UnderJoin(parent.name().c_str(), "skr"))
    , fGM(gm)
    , fReference(reference)
    {}

void RecordTask::draw() {
    // Record the GM into an SkRecord.
    EXPERIMENTAL::SkRecording recording(fReference.width(), fReference.height());
    recording.canvas()->concat(fGM->getInitialTransform());
    fGM->draw(recording.canvas());
    SkAutoTDelete<const EXPERIMENTAL::SkPlayback> playback(recording.releasePlayback());

    // Draw the SkRecord back into a bitmap.
    SkBitmap bitmap;
    SetupBitmap(fReference.colorType(), fGM.get(), &bitmap);
    SkCanvas target(bitmap);
    playback->draw(&target);

    if (!BitmapsEqual(bitmap, fReference)) {
        this->fail();
        this->spawnChild(SkNEW_ARGS(WriteTask, (*this, bitmap)));
    }
}

bool RecordTask::shouldSkip() const {
    return !FLAGS_skr;
}

}  // namespace DM

Apply initial transform in --skr mode.


// http://www.nuonsoft.com/blog/2017/08/10/implementing-a-thread-safe-singleton-with-c11-using-magic-statics/
// http://blog.mbedded.ninja/programming/languages/c-plus-plus/magic-statics

#include <iostream>

class CSingleton final {
 public:
  static CSingleton& GetInstance();
  int getValue() const { return mValue; }

  CSingleton(const CSingleton&) = delete;
  CSingleton& operator=(const CSingleton&) = delete;
  CSingleton(CSingleton&&) = delete;
  CSingleton& operator=(CSingleton&&) = delete;

 private:
  CSingleton() = default;
  ~CSingleton() = default;

  int mValue = 0;
};

CSingleton& CSingleton::GetInstance() {
  static CSingleton instance;
  return instance;
}

int main() {
  auto const value{CSingleton::GetInstance().getValue()};
  std::cout << value << '\n';
}

// http://www.nuonsoft.com/blog/2017/08/10/implementing-a-thread-safe-singleton-with-c11-using-magic-statics/
// http://blog.mbedded.ninja/programming/languages/c-plus-plus/magic-statics

#include <iostream>

class CSingleton final {
 public:
  static CSingleton& GetInstance() {
    static CSingleton instance;
    return instance;
  }

  int getValue() const { return mValue; }

 private:
  CSingleton() = default;
  ~CSingleton() = default;

  CSingleton(const CSingleton&) = delete;
  CSingleton& operator=(const CSingleton&) = delete;
  CSingleton(CSingleton&&) = delete;
  CSingleton& operator=(CSingleton&&) = delete;

  int mValue = 0;
};

int main() {
  auto const value{CSingleton::GetInstance().getValue()};
  std::cout << value << '\n';
}

Make deleted special member functions private.


#include"qca.h"
#include<stdio.h>

int main(int argc, char **argv)
{
	QCA::Initializer init;
	QCString cs = (argc >= 2) ? argv[1] : "hello";

	if( !QCA::isSupported("sha1") )
		printf("SHA1 not supported!\n");
	else {
		QCA::SHA1 sha1Hash;
		QString result = sha1Hash.hashToString(cs);
		printf("sha1(\"%s\") = [%s]\n", cs.data(), result.latin1());
	}

	if( !QCA::isSupported("md5") )
		printf("MD5 not supported!\n");
	else {
		QCA::MD5 md5Hash;
		QString result = md5Hash.hashToString(cs);
		printf("md5(\"%s\") = [%s]\n", cs.data(), result.latin1());
	}

	return 0;
}

#include"qca.h"
#include<stdio.h>

int main(int argc, char **argv)
{
	QCA::Initializer init;
	QCString cs = (argc >= 2) ? argv[1] : "hello";

	if( !QCA::isSupported("sha1") )
		printf("SHA1 not supported!\n");
	else {
		QString result = QCA::SHA1().hashToString(cs);
		printf("sha1(\"%s\") = [%s]\n", cs.data(), result.latin1());
	}

	if( !QCA::isSupported("md5") )
		printf("MD5 not supported!\n");
	else {
		QString result = QCA::MD5().hashToString(cs);
		printf("md5(\"%s\") = [%s]\n", cs.data(), result.latin1());
	}

	return 0;
}

Update to use static versions.


#include "catch.hpp"

#include "StringToInteger.hpp"

TEST_CASE("String To Integer") {
  Solution s;

  SECTION("Normal tests") {
    REQUIRE(s.myAtoi("1") == 1);
  }

  SECTION("Normal tests 2") {
    REQUIRE(s.myAtoi("    010") == 10);
  }
}

#include "catch.hpp"

#include "StringToInteger.hpp"

TEST_CASE("String To Integer") {
  Solution s;

  SECTION("Normal tests") {
    REQUIRE(s.myAtoi("1") == 1);
    REQUIRE(s.myAtoi("378") == 378);
    REQUIRE(s.myAtoi("-239") == -239);
    REQUIRE(s.myAtoi("+832") == 832);
  }

  SECTION("Boundary tests") {
    REQUIRE(s.myAtoi("-2147483648") == -2147483648);
    REQUIRE(s.myAtoi("-2147483649") == -2147483648);
    REQUIRE(s.myAtoi("2147483647") == 2147483647);
    REQUIRE(s.myAtoi("2147483648") == 2147483647);
  }

  SECTION("Format tests") {
    REQUIRE(s.myAtoi("asdfasf") == 0);
    REQUIRE(s.myAtoi("--124") == 0);
    REQUIRE(s.myAtoi("++4") == 0);
    REQUIRE(s.myAtoi("    +110?_+120__") == 110);
  }
}

Update Problem 8 test case


#include "component.h"
#include "entity.h"
#include "gtest/gtest.h"

/*
class TestC : public aronnax::Component {
  public:
    void update(aronnax::Entity &entity, const uint32_t dt)
    {
      return;
    }

    std::string getType()
    {
      return "TestComponent";
    }
};

class EntityTest : public testing::Test {
protected:

  virtual void SetUp() {
  }

  // Declares the variables your tests want to use.
  aronnax::Components cla_;
  aronnax::Entity ea_;
};
*/

TEST(Entity, DefaultConstructor) {
  const aronnax::Components cla_;
  const aronnax::Entity ea_(cla_);
  EXPECT_EQ(0, ea_.pos.x) << "Constructs with position as 0 by default";
  EXPECT_EQ(0, ea_.pos.y);
  EXPECT_EQ(0, ea_.box.x);
  EXPECT_EQ(0, ea_.box.y);
  EXPECT_EQ(0, ea_.v.x);
  EXPECT_EQ(0, ea_.v.y);
}

#include "component.h"
#include "entity.h"
#include "gtest/gtest.h"

/*
class TestC : public aronnax::Component {
  public:
    void update(aronnax::Entity &entity, const uint32_t dt)
    {
      return;
    }

    std::string getType()
    {
      return "TestComponent";
    }
};
*/

class EntityTest : public testing::Test {
protected:

  virtual void SetUp() {
    ea_ = new aronnax::Entity(cla_);
  }

  // Declares the variables your tests want to use.
  aronnax::Components cla_;
  aronnax::Entity* ea_;
};

TEST_F(EntityTest, DefaultConstructor) {
  EXPECT_EQ(0, ea_->pos.x) << "Constructs with position as 0 by default";
  EXPECT_EQ(0, ea_->pos.y);
  EXPECT_EQ(0, ea_->box.x);
  EXPECT_EQ(0, ea_->box.y);
  EXPECT_EQ(0, ea_->v.x);
  EXPECT_EQ(0, ea_->v.y);
}

Change entity test to use fixtures


#include "orderinginfo.h"
#include "defs.h"
#include "eval.h"
#include <cstring>

OrderingInfo::OrderingInfo(const TranspTable* tt) {
  _tt = tt;
  _ply = 0;
  std::memset(_history, 0, sizeof(_history));
}

void OrderingInfo::incrementHistory(Color color, int from, int to, int depth) {
  _history[color][from][to] += depth^2;
}

int OrderingInfo::getHistory(Color color, int from, int to) const {
  return _history[color][from][to];
}

void OrderingInfo::incrementPly() {
  _ply++;
}

void OrderingInfo::deincrementPly() {
  _ply--;
}

int OrderingInfo::getPly() const {
  return _ply;
}

const TranspTable* OrderingInfo::getTt() const {
  return _tt;
}

void OrderingInfo::updateKillers(int ply, Move move) {
  _killer2[ply] = _killer1[ply];
  _killer1[ply] = move;
}

Move OrderingInfo::getKiller1(int ply) const {
  return _killer1[ply];
}

Move OrderingInfo::getKiller2(int ply) const {
  return _killer2[ply];
}

#include "orderinginfo.h"
#include "defs.h"
#include "eval.h"
#include <cstring>

OrderingInfo::OrderingInfo(const TranspTable* tt) {
  _tt = tt;
  _ply = 0;
  std::memset(_history, 0, sizeof(_history));
}

void OrderingInfo::incrementHistory(Color color, int from, int to, int depth) {
  _history[color][from][to] += depth*depth;
}

int OrderingInfo::getHistory(Color color, int from, int to) const {
  return _history[color][from][to];
}

void OrderingInfo::incrementPly() {
  _ply++;
}

void OrderingInfo::deincrementPly() {
  _ply--;
}

int OrderingInfo::getPly() const {
  return _ply;
}

const TranspTable* OrderingInfo::getTt() const {
  return _tt;
}

void OrderingInfo::updateKillers(int ply, Move move) {
  _killer2[ply] = _killer1[ply];
  _killer1[ply] = move;
}

Move OrderingInfo::getKiller1(int ply) const {
  return _killer1[ply];
}

Move OrderingInfo::getKiller2(int ply) const {
  return _killer2[ply];
}

Fix incorrect operator in OrderingInfo