#include <stdio.h>

int main(int argc, char* argv[])
{
	printf("One\n");
	printf("Two\n");
	printf("Three\n");
	printf("Four\n");

	return 0;
}

#include <stdio.h>
#include <iostream>
#include <fstream>
#include <vector>
#include <unordered_map>

int main(int argc, char* argv[])
{
	if (argc != 5)
	{
		std::cerr << "Path Finder only accepts 4 arguments\n";
		exit(1);
	}

	// Load in all page titles into a vector
	std::cout << "\033[92m==>\033[0m Reading in page titles as a vector & map\n";

	std::vector<std::string> pages;
	std::unordered_map<std::string, int> page_ids;

	{
		std::ifstream page_titles_file(argv[1]);
		std::string page_name;

		// We won't be using the first index of the vector for anything since
		// the page_id indexes start at 1 instead of 0. This should help to
		// prevent any errors during devlopment
		pages.push_back("");

		// Read the page name into the vector and into the hash-map
		int index = 1;

		while (std::getline(page_titles_file, page_name))
		{
			pages.push_back(page_name);
			page_ids[page_name] = index++;
		}
		std::cout << "\033[94m  -> \033[0mRead in " << index - 1 << " page titles\n";
	}

	return 0;
}

Read in the page names into a vector and hash


#include <memory>

#include "Vec2i.h"
#include "IMapElement.h"
#include "CActor.h"
#include "CWizard.h"

namespace WizardOfGalicia {
  CWizard::CWizard() : CActor() {
    emission = 20;
    view = '^';
    team = Team::HEROES;
    hp = 5;
    attack = 4;
    defence = 1;
    magicEnergy = 20;
  }

  void CWizard::update(std::shared_ptr<CMap> map) {
    if ( abs( magicEnergy ) > 0.0f ) {
      magicEnergy += ( magicEnergy / abs( magicEnergy ) );
    }

    emission = abs( magicEnergy );
  }

  void CWizard::turnLeft() {
    CActor::turnLeft();
    updateView();
  }

  void CWizard::turnRight() {
    CActor::turnRight();
    updateView();
  }

  void CWizard::updateView() {
    switch (direction) {
    case Direction::N:
      view = '^';
      break;
    case Direction::W:
      view = '<';
      break;
    case Direction::E:
      view = '>';
      break;
    case Direction::S:
      view = 'V';
      break;
    }
  }
}

#include <memory>

#include "Vec2i.h"
#include "IMapElement.h"
#include "CActor.h"
#include "CWizard.h"

namespace WizardOfGalicia {
  CWizard::CWizard() : CActor() {
    emission = 20;
    view = '^';
    team = Team::HEROES;
    hp = 5;
    attack = 4;
    defence = 1;
    magicEnergy = 20;
  }

  void CWizard::update(std::shared_ptr<CMap> map) {
    if ( abs( magicEnergy ) > 0.0f ) {
      magicEnergy += ( magicEnergy / abs( magicEnergy ) );
    }

    emission = abs( magicEnergy );
    attack = 4 + abs( magicEnergy );
    defence = 2 + abs( magicEnergy );
  }

  void CWizard::turnLeft() {
    CActor::turnLeft();
    updateView();
  }

  void CWizard::turnRight() {
    CActor::turnRight();
    updateView();
  }

  void CWizard::updateView() {
    switch (direction) {
    case Direction::N:
      view = '^';
      break;
    case Direction::W:
      view = '<';
      break;
    case Direction::E:
      view = '>';
      break;
    case Direction::S:
      view = 'V';
      break;
    }
  }
}

Change the player status based on it's own energy


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

#include "courgette/crc.h"

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

#include "base/basictypes.h"

namespace courgette {

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

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

  return ~crc;
}

}  // namespace

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

// Calculate Crc by calling CRC method in LZMA SDK

#include "courgette/crc.h"

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

namespace courgette {

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

}  // namespace

Revert 112083 - Try a different library for Crc32.


#include "KAI/Console/Console.h"

#include <iostream>

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

using namespace std;

USING_NAMESPACE_KAI

//static Color _color;

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

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

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

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

	return console.Run();
}

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

using namespace std;

USING_NAMESPACE_KAI

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

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

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

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

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

Remove explicit WIN32 references from Console app.


// REQUIRES: x86-64-registered-target
// RUN: %clang_cc1 -triple x86_64-apple-darwin10  -g -fno-limit-debug-info -S %s -o %t
// RUN: FileCheck %s < %t

// FIXME: This testcase shouldn't rely on assembly emission.
//CHECK: Lpubtypes_begin1:
//CHECK:         .asciz   "G"
//CHECK-NEXT:    .long   0
//CHECK-NEXT: Lpubtypes_end1:

class G {
public:
	void foo();
};

void G::foo() {
}

// REQUIRES: x86-64-registered-target
// RUN: %clang_cc1 -triple x86_64-apple-darwin10  -g -fno-limit-debug-info -S %s -o %t
// RUN: FileCheck %s < %t

// FIXME: This testcase shouldn't rely on assembly emission.
//CHECK: Lpubtypes_begin[[SECNUM:[0-9]:]]
//CHECK:         .asciz   "G"
//CHECK-NEXT:    .long   0
//CHECK-NEXT: Lpubtypes_end[[SECNUM]]

class G {
public:
	void foo();
};

void G::foo() {
}

Make the test less sensitive to DWARF emission implementation details.


/*
 * Copyright (C) 2004-2009  See the AUTHORS file for details.
 *
 * This program is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License version 2 as published
 * by the Free Software Foundation.
 */

#include "Server.h"

CServer::CServer(const CString& sName, unsigned short uPort, const CString& sPass, bool bSSL) {
	m_sName = sName;
	m_uPort = (uPort) ? uPort : 6667;
	m_sPass = sPass;
	m_bSSL = bSSL;
}

CServer::~CServer() {}

bool CServer::IsValidHostName(const CString& sHostName) {
	const char* p = sHostName.c_str();

	if (sHostName.empty()) {
		return false;
	}

	while (*p) {
		if (*p++ == ' ') {
			return false;
		}
	}

	return true;
}

const CString& CServer::GetName() const { return m_sName; }
unsigned short CServer::GetPort() const { return m_uPort; }
const CString& CServer::GetPass() const { return m_sPass; }
bool CServer::IsSSL() const { return m_bSSL; }

CString CServer::GetString() const {
	return m_sName + " " + CString(m_bSSL ? "+" : "") + CString(m_uPort) + CString(m_sPass.empty() ? "" : " " + m_sPass);
}

/*
 * Copyright (C) 2004-2009  See the AUTHORS file for details.
 *
 * This program is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License version 2 as published
 * by the Free Software Foundation.
 */

#include "Server.h"

CServer::CServer(const CString& sName, unsigned short uPort, const CString& sPass, bool bSSL) {
	m_sName = sName;
	m_uPort = (uPort) ? uPort : 6667;
	m_sPass = sPass;
	m_bSSL = bSSL;
}

CServer::~CServer() {}

bool CServer::IsValidHostName(const CString& sHostName) {
	if (sHostName.empty()) {
		return false;
	}

	if (sHostName.find(' ') != CString::npos) {
		return false;
	}

	return true;
}

const CString& CServer::GetName() const { return m_sName; }
unsigned short CServer::GetPort() const { return m_uPort; }
const CString& CServer::GetPass() const { return m_sPass; }
bool CServer::IsSSL() const { return m_bSSL; }

CString CServer::GetString() const {
	return m_sName + " " + CString(m_bSSL ? "+" : "") + CString(m_uPort) + CString(m_sPass.empty() ? "" : " " + m_sPass);
}

Use find() instead of walking strings 'by hand' in IsValidHostName


// Copyright (c) 2016, Herman Bergwerf. All rights reserved.
// Use of this source code is governed by a MIT-style license
// that can be found in the LICENSE file.

// Based on: http://seriss.com/people/erco/fltk/#FltkX

#include <FL/Fl.H>
#include <FL/fl_draw.H>
#include <FL/Fl_Box.H>
#include <FL/Fl_Double_Window.H>

/// Widget that draws two diagonal lines
class XWidget : public Fl_Box {
 public:
  /// Constuctor
  XWidget(int x, int y, int w, int h) : Fl_Box(x, y, w, h, 0) {}

  /// Draws the lines
  /*void draw() {
    fl_color(FL_BLACK);
    int x1 = x(), y1 = y();
    int x2 = x() + w() - 1, y2 = y() + h() - 1;
    fl_line(x1, y1, x2, y2);
    fl_line(x1, y2, x2, y1);
  }*/
};

int main() {
  Fl_Double_Window *win = new Fl_Double_Window(200, 200, "X");
  XWidget *x = new XWidget(0, 0, win -> w(), win -> h());
  x -> box(FL_UP_BOX);
  win -> resizable(x);
  win -> show();
  return Fl::run();
}

// Copyright (c) 2016, Herman Bergwerf. All rights reserved.
// Use of this source code is governed by a MIT-style license
// that can be found in the LICENSE file.

// Based on: http://seriss.com/people/erco/fltk/#FltkX

#include <FL/Fl.H>
#include <FL/fl_draw.H>
#include <FL/Fl_Box.H>
#include <FL/Fl_Double_Window.H>

/// Widget that draws two diagonal lines
class XWidget : public Fl_Widget {
 public:
  /// Constuctor
  XWidget(int x, int y, int w, int h) : Fl_Widget(x, y, w, h, 0) {}

  /// Draws the lines
  void draw() {
    fl_color(FL_BLACK);
    int x1 = x(), y1 = y();
    int x2 = x() + w() - 1, y2 = y() + h() - 1;
    fl_line(x1, y1, x2, y2);
    fl_line(x1, y2, x2, y1);
  }
};

int main() {
  Fl_Double_Window *win = new Fl_Double_Window(200, 200, "X");
  XWidget *x = new XWidget(0, 0, win -> w(), win -> h());
  win -> resizable(x);
  win -> show();
  return Fl::run();
}

Fix the draw X FLTK C++ example


#include <stdio.h>
#include <fcntl.h>

#include <chrono>
#include <thread>

void *start(void *data)
{
    int i;
    size_t idx = (size_t)data;
    for (i=0; i<30; i++)
    {
        if ( idx == 0 )
            std::this_thread::sleep_for(std::chrono::microseconds(1));
        std::this_thread::sleep_for(std::chrono::seconds(1));
    }
    return 0;
}

int main(int argc, char const *argv[])
{
    static const size_t nthreads = 16;
    std::thread threads[nthreads];
    size_t i;

    for (i=0; i<nthreads; i++)
        threads[i] = std::move(std::thread(start, (void*)i));

    for (i=0; i<nthreads; i++)
        threads[i].join();
}

#include <stdio.h>
#include <fcntl.h>

#include <chrono>
#include <thread>

#if defined(__linux__)
#include <sys/prctl.h>
#endif

void *start(void *data)
{
    int i;
    size_t idx = (size_t)data;
    for (i=0; i<30; i++)
    {
        if ( idx == 0 )
            std::this_thread::sleep_for(std::chrono::microseconds(1));
        std::this_thread::sleep_for(std::chrono::seconds(1));
    }
    return 0;
}

int main(int argc, char const *argv[])
{
#if defined(__linux__)
    // Immediately enable any ptracer so that we can allow the stub attach
    // operation to succeed.  Some Linux kernels are locked down so that
    // only an ancestor process can be a ptracer of a process.  This disables that
    // restriction.  Without it, attach-related stub tests will fail.
#if defined(PR_SET_PTRACER) && defined(PR_SET_PTRACER_ANY)
    // For now we execute on best effort basis.  If this fails for
    // some reason, so be it.
    const int prctl_result = prctl(PR_SET_PTRACER, PR_SET_PTRACER_ANY, 0, 0, 0);
    static_cast<void> (prctl_result);
#endif
#endif

    static const size_t nthreads = 16;
    std::thread threads[nthreads];
    size_t i;

    for (i=0; i<nthreads; i++)
        threads[i] = std::move(std::thread(start, (void*)i));

    for (i=0; i<nthreads; i++)
        threads[i].join();
}

Fix TestAttachResume test so it doesn't hang on Linux with ptrace lockdown.


#include <inttypes.h>
#include <stdlib.h>

#include <config/config_type_int.h>

ConfigTypeInt config_type_int;

bool
ConfigTypeInt::set(ConfigValue *cv, const std::string& vstr)
{
	if (ints_.find(cv) != ints_.end())
		return (false);

	const char *str = vstr.c_str();
	char *endp;
	intmax_t imax;

	imax = strtoimax(str, &endp, 0);
	if (*endp != '\0')
		return (false);

	ints_[cv] = imax;

	return (true);
}

#if !defined(__OPENNT)
#include <inttypes.h>
#endif
#include <stdlib.h>

#include <config/config_type_int.h>

ConfigTypeInt config_type_int;

bool
ConfigTypeInt::set(ConfigValue *cv, const std::string& vstr)
{
	if (ints_.find(cv) != ints_.end())
		return (false);

	const char *str = vstr.c_str();
	char *endp;
	intmax_t imax;

#if !defined(__OPENNT)
	imax = strtoimax(str, &endp, 0);
#else
	imax = strtoll(str, &endp, 0);
#endif
	if (*endp != '\0')
		return (false);

	ints_[cv] = imax;

	return (true);
}

Use strtoll like strtoimax on Interix.


/*
	This file is part of cpp-ethereum.

	cpp-ethereum is free software: you can redistribute it and/or modify
	it under the terms of the GNU General Public License as published by
	the Free Software Foundation, either version 3 of the License, or
	(at your option) any later version.

	cpp-ethereum 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 cpp-ethereum.  If not, see <http://www.gnu.org/licenses/>.
*/

#include "VMFace.h"
#include "VM.h"
#include <libevmjit/VM.h>

using namespace dev;
using namespace dev::eth;

std::unique_ptr<VMFace> VMFace::create(VMFace::Kind _kind, u256 _gas)
{
	std::unique_ptr<VMFace> vm(_kind == Kind::JIT ? static_cast<VMFace*>(new jit::VM) : new VM);
	vm->reset(_gas);
	return vm;
}

/*
	This file is part of cpp-ethereum.

	cpp-ethereum is free software: you can redistribute it and/or modify
	it under the terms of the GNU General Public License as published by
	the Free Software Foundation, either version 3 of the License, or
	(at your option) any later version.

	cpp-ethereum 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 cpp-ethereum.  If not, see <http://www.gnu.org/licenses/>.
*/

#include "VMFace.h"
#include "VM.h"
#include <libevmjit/VM.h>

using namespace dev;
using namespace dev::eth;

std::unique_ptr<VMFace> VMFace::create(VMFace::Kind _kind, u256 _gas)
{
	std::unique_ptr<VMFace> vm;
#if ETH_JIT
	vm.reset(_kind == Kind::JIT ? static_cast<VMFace*>(new jit::VM) : new VM);
#else
	vm.reset(new VM);
#endif
	vm->reset(_gas);
	return vm;
}

Return jit::VM only if ETH_JIT macro is on


/*
* Copyright (C) 2016 Google, Inc.
*
* 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 "Game.h"
#include "Shell.h"

#if (defined(_MSC_VER) && _MSC_VER < 1900 /*vs2015*/) ||                       \
    defined MINGW_HAS_SECURE_API
#include <basetsd.h>
#define snprintf sprintf_s
#endif

void Game::print_stats() {
    // Output frame count and measured elapsed time
    auto now = std::chrono::system_clock::now();
    auto elapsed = now - start_time;
    auto elapsed_millis =
        std::chrono::duration_cast<std::chrono::milliseconds>(elapsed).count();
    char msg[256];
    snprintf(msg, 255, "frames:%d, elapsedms:%ld", frame_count, elapsed_millis);
    shell_->log(Shell::LogPriority::LOG_INFO, msg);
}

void Game::quit() {
    print_stats();
    shell_->quit();
}

/*
* Copyright (C) 2016 Google, Inc.
*
* 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 <sstream>

#include "Game.h"
#include "Shell.h"

void Game::print_stats() {
    // Output frame count and measured elapsed time
    auto now = std::chrono::system_clock::now();
    auto elapsed = now - start_time;
    auto elapsed_millis =
        std::chrono::duration_cast<std::chrono::milliseconds>(elapsed).count();
    std::stringstream ss;
    ss << "frames:" << frame_count << ", elapsedms:" << elapsed_millis;
    shell_->log(Shell::LogPriority::LOG_INFO, ss.str().c_str());
}

void Game::quit() {
    print_stats();
    shell_->quit();
}

Fix compiler warning in smoketest


#include "daemon.h"

#include <err.h>
#include <iostream>
#include <string.h>
#include <unistd.h>

int main(int argc, char **argv)
{
  int separator = 0;
  char** compile_argv;

  for (int i = 1; i < argc; ++i) {
    if (strcmp(argv[i], "--") == 0) {
      separator = i;
      break;
    }
  }

  compile_argv = argv + separator;
  compile_argv[0] = separator >= 2 ? argv[separator - 1] : strdup("clang");

  if (clc::daemon::start()) {
    /* Send compile message to server. */
  }

  /* Run the compiler and print error message if execvp returns. */
  execvp(compile_argv[0], compile_argv);
  err(EXIT_FAILURE, "%s", compile_argv[0]);
}

#include "daemon.h"

#include <cstring>
#include <err.h>
#include <iostream>
#include <unistd.h>

int main(int argc, char **argv)
{
  int separator = 0;
  char** compile_argv;

  for (int i = 1; i < argc; ++i) {
    if (std::strcmp(argv[i], "--") == 0) {
      separator = i;
      break;
    }
  }

  compile_argv = argv + separator;
  compile_argv[0] = separator >= 2 ? argv[separator - 1] : (char*) "clang";

  if (clc::daemon::start()) {
    /* Send compile message to server. */
  }

  /* Run the compiler and print error message if execvp returns. */
  execvp(compile_argv[0], compile_argv);
  err(EXIT_FAILURE, "%s", compile_argv[0]);
}

Use C++ includes when appropriate.


#include <cstdio>

#include <string>
#include <vector>

using std::vector;
using std::string;

int main(int argc, char *argv[]) {
  vector<string> args(argv + 1, argv + argc);
  for (const auto &arg : args) {
    printf("%s\n", arg.c_str());
  }
  return 0;
}

#include <cstdio>

#include <string>
#include <vector>

#include <curl/curl.h>

using std::vector;
using std::string;

struct LinkTestData {
  string in_source_url;
  string in_href_url;
  string out_source_page;
};

size_t WriteData(void *buffer, size_t size, size_t nmemb, void *userp) {
  LinkTestData *link_test_data = (LinkTestData *)userp;
  char *body = (char *)buffer;
  link_test_data->out_source_page.append(body, body + nmemb);
  return size * nmemb;
}

int main(int argc, char *argv[]) {
  string root(argv[1]);

  printf("%s\n", root.c_str());

  curl_global_init(CURL_GLOBAL_ALL);
  CURL *handle = curl_easy_init();

  LinkTestData link = {};

  curl_easy_setopt(handle, CURLOPT_URL, root.c_str());
  curl_easy_setopt(handle, CURLOPT_WRITEFUNCTION, WriteData);
  curl_easy_setopt(handle, CURLOPT_WRITEDATA, &link);
  CURLcode success = curl_easy_perform(handle);

  printf("%s\n", link.out_source_page.c_str());

  curl_easy_cleanup(handle);
  curl_global_cleanup();

  return 0;
}

Make script download and print a web page.


/*
 *  Copyright (c) 2014, Facebook, Inc.
 *  All rights reserved.
 *
 *  This source code is licensed under the BSD-style license found in the
 *  LICENSE file in the root directory of this source tree. An additional grant
 *  of patent rights can be found in the PATENTS file in the same directory.
 *
 */

#include <thpp/Storage.h>

namespace thpp {
namespace detail {

IOBufAllocator::IOBufAllocator(folly::IOBuf&& iob)
  : iob_(std::move(iob)) {
  DCHECK(!iob_.isChained());
}

void* IOBufAllocator::malloc(long size) {
  CHECK(false) << "IOBufAllocator::malloc should never be called";
}

void* IOBufAllocator::realloc(void* ptr, long size) {
  CHECK_EQ(ptr, iob_.writableData());
  if (size > iob_.capacity()) {
    iob_.unshareOne();
    iob_.reserve(0, size - iob_.capacity());
  }
  if (size < iob_.length()) {
    iob_.trimEnd(iob_.length() - size);
  } else {
    iob_.append(size - iob_.length());
  }
  return iob_.writableData();
}

void IOBufAllocator::free(void* ptr) {
  CHECK_EQ(ptr, iob_.writableData());
  delete this;
}

}  // namespace detail

}  // namespaces

/*
 *  Copyright (c) 2014, Facebook, Inc.
 *  All rights reserved.
 *
 *  This source code is licensed under the BSD-style license found in the
 *  LICENSE file in the root directory of this source tree. An additional grant
 *  of patent rights can be found in the PATENTS file in the same directory.
 *
 */

#include <thpp/Storage.h>

namespace thpp {
namespace detail {

IOBufAllocator::IOBufAllocator(folly::IOBuf&& iob)
  : iob_(std::move(iob)) {
  DCHECK(!iob_.isChained());
}

void* IOBufAllocator::malloc(long size) {
  CHECK(false) << "IOBufAllocator::malloc should never be called";
}

void* IOBufAllocator::realloc(void* ptr, long size) {
  CHECK_EQ(ptr, iob_.writableData());
  if (size <= iob_.length()) {
    iob_.trimEnd(iob_.length() - size);
  } else {
    auto extra = size - iob_.length();
    if (extra > iob_.tailroom()) {
      iob_.unshareOne();
      iob_.reserve(0, extra);
    }
    iob_.append(extra);
  }
  return iob_.writableData();
}

void IOBufAllocator::free(void* ptr) {
  CHECK_EQ(ptr, iob_.writableData());
  delete this;
}

}  // namespace detail

}  // namespaces

Fix incorrect use of IOBuf::reserve


#include "readfile.h"
#include <stdexcept>
#include <sstream>
#include <cstdio>
#include <cerrno>
#include <cstring>

using namespace std;

/* read_file: read the entire contents of a file into a C++ string. */

string read_file(const string& filename)
{
    // Open the file
    int errno_;
    FILE* fd;
    if (NULL == (fd = fopen(filename.c_str(), "r")))
    {
        errno_ = errno;
        throw runtime_error(string("fopen: ") + strerror(errno_));
    }

    // Read the data onto a string
    char *buf = new char[BUFSIZ];
    string data;
    while (!feof(fd))
    {
        size_t sz = fread(buf, 1, BUFSIZ, fd);
        if (ferror(fd))
        {
            errno_ = errno;
            break;
        }
        data.append(buf, sz);
    }
    delete[] buf;

    // Check for errors / close file
    ostringstream errmsg;
    bool error = false;
    if (ferror(fd))
    {
        error = true;
        errmsg << "fread: " << strerror(errno_);
    }
    if (fclose(fd))
    {
        error = true;
        errno_ = errno;
        if (error) errmsg << "; ";
        errmsg << "fclose: " << strerror(errno_);
    }
    if (error)
        throw runtime_error(errmsg.str());

    // Return data
    return data;
}

#include "readfile.h"
#include <stdexcept>
#include <sstream>
#include <cstdio>
#include <cerrno>
#include <cstring>

using namespace std;

/* read_file: read the entire contents of a file into a C++ string. */

string read_file(const string& filename)
{
    // Open the file
    int errno_;
    FILE* fd;
    if (filename == "-")
    {
        fd = stdin;
    }
    else if (NULL == (fd = fopen(filename.c_str(), "r")))
    {
        errno_ = errno;
        throw runtime_error(string("fopen: ") + strerror(errno_));
    }

    // Read the data onto a string
    char *buf = new char[BUFSIZ];
    string data;
    while (!feof(fd))
    {
        size_t sz = fread(buf, 1, BUFSIZ, fd);
        if (ferror(fd))
        {
            errno_ = errno;
            break;
        }
        data.append(buf, sz);
    }
    delete[] buf;

    // Check for errors / close file
    ostringstream errmsg;
    bool error = false;
    if (ferror(fd))
    {
        error = true;
        errmsg << "fread: " << strerror(errno_);
    }
    if (filename != "-" && fclose(fd))
    {
        error = true;
        errno_ = errno;
        if (error) errmsg << "; ";
        errmsg << "fclose: " << strerror(errno_);
    }
    if (error)
        throw runtime_error(errmsg.str());

    // Return data
    return data;
}

Enable reading from stdin if the configuration filename is '-'.


#include <core.h>
#include "thermostat.h"
#include "keyboard.h"

#define BUTTONS 4
uint8_t keyPins[BUTTONS] = {KEY_MODE_PIN, KEY_UP_PIN, KEY_DOWN_PIN, KEY_SETUP_PIN};
uint32_t lastKeyChangeMillis[BUTTONS] = {0, 0, 0, 0};

using namespace core;
idType keyIds[BUTTONS];
idType idKeyMode, idKeyUp, idKeyDown, idKeySetup;

void setupKeyboard() {
  for (int i = 0; i < BUTTONS; i++) {
    pinMode(keyPins[i], INPUT);
    keyIds[i] = store::defineDigital();
  }

  idKeyMode = keyPins[0];
  idKeyUp = keyPins[1];
  idKeyDown = keyPins[2];
  idKeySetup = keyPins[3];
}

void checkKeys() {
  for (int i = 0; i < BUTTONS; i++) {
    uint8_t state = digitalRead(keyPins[i]);
    if (state == store::digitals[keyIds[i]]) {
      continue;
    }

    uint32_t now = millis();
    if (now - lastKeyChangeMillis[i] < 300) {
      continue;
    }

    lastKeyChangeMillis[i] = now;
    store::setDigital(keyIds[i], state);

    Serial.print("Key ");
    Serial.print(i);
    Serial.println(state == HIGH ? " down" : " up");
  }
}

#include <core.h>
#include "thermostat.h"
#include "keyboard.h"

#define BUTTONS 4
uint8_t keyPins[BUTTONS] = {KEY_MODE_PIN, KEY_UP_PIN, KEY_DOWN_PIN, KEY_SETUP_PIN};
uint32_t lastKeyChangeMillis[BUTTONS] = {0, 0, 0, 0};

using namespace core;
idType keyIds[BUTTONS];
idType idKeyMode, idKeyUp, idKeyDown, idKeySetup;

void setupKeyboard() {
  for (int i = 0; i < BUTTONS; i++) {
    pinMode(keyPins[i], INPUT);
    keyIds[i] = store::defineDigital();
  }

  idKeyMode = keyIds[0];
  idKeyUp = keyIds[1];
  idKeyDown = keyIds[2];
  idKeySetup = keyIds[3];
}

void checkKeys() {
  for (int i = 0; i < BUTTONS; i++) {
    uint8_t state = digitalRead(keyPins[i]);
    if (state == store::digitals[keyIds[i]]) {
      continue;
    }

    uint32_t now = millis();
    if (now - lastKeyChangeMillis[i] < 300) {
      continue;
    }

    lastKeyChangeMillis[i] = now;
    store::setDigital(keyIds[i], state);

    Serial.print("Key ");
    Serial.print(i);
    Serial.println(state == HIGH ? " down" : " up");
  }
}

Fix wrong assigned key digital ids


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

#include <iostream>
#include <cassert>

#include "test_macros.h"

// Test to make sure that the streams only get initialized once
// Taken from https://bugs.llvm.org/show_bug.cgi?id=43300

int main(int, char**)
{

    std::cout << "Hello!";
    std::ios_base::fmtflags stock_flags = std::cout.flags();

    std::cout << std::boolalpha << true;
    std::ios_base::fmtflags ba_flags = std::cout.flags();
    assert(stock_flags != ba_flags);

    std::ios_base::Init init_streams;
    std::ios_base::fmtflags after_init = std::cout.flags();
    assert(after_init == ba_flags);

    return 0;
}

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

#include <iostream>
#include <cassert>

#include "test_macros.h"

// Test to make sure that the streams only get initialized once
// Taken from https://bugs.llvm.org/show_bug.cgi?id=43300

// The dylibs shipped on macOS so far do not contain the fix for PR43300, so
// this test fails.
// XFAIL: with_system_cxx_lib=macosx10.15
// XFAIL: with_system_cxx_lib=macosx10.14
// XFAIL: with_system_cxx_lib=macosx10.13
// XFAIL: with_system_cxx_lib=macosx10.12
// XFAIL: with_system_cxx_lib=macosx10.11
// XFAIL: with_system_cxx_lib=macosx10.10
// XFAIL: with_system_cxx_lib=macosx10.9
// XFAIL: with_system_cxx_lib=macosx10.8
// XFAIL: with_system_cxx_lib=macosx10.7

int main(int, char**)
{

    std::cout << "Hello!";
    std::ios_base::fmtflags stock_flags = std::cout.flags();

    std::cout << std::boolalpha << true;
    std::ios_base::fmtflags ba_flags = std::cout.flags();
    assert(stock_flags != ba_flags);

    std::ios_base::Init init_streams;
    std::ios_base::fmtflags after_init = std::cout.flags();
    assert(after_init == ba_flags);

    return 0;
}

Mark iostreams test as XFAIL on older macOSes


#include "common/application_info.h"

namespace brightray {

std::string GetApplicationName() {
  return std::string();
}

std::string GetApplicationVersion() {
  return std::string();
}

}

#include "common/application_info.h"

#include "base/file_version_info.h"
#include "base/memory/scoped_ptr.h"
#include "base/utf_string_conversions.h"

namespace brightray {

std::string GetApplicationName() {
  auto info = make_scoped_ptr(FileVersionInfo::CreateFileVersionInfoForModule(GetModuleHandle(nullptr)));
  return UTF16ToUTF8(info->product_name());
}

std::string GetApplicationVersion() {
  auto info = make_scoped_ptr(FileVersionInfo::CreateFileVersionInfoForModule(GetModuleHandle(nullptr)));
  return UTF16ToUTF8(info->file_version());
}

}

Set the user agent string correctly on Windows


/*   This file is part of fus.
 *
 *   fus 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.
 *
 *   fus 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 fus.  If not, see <http://www.gnu.org/licenses/>.
 */

// Include all protocol headers here
#include "auth.h"
#include "common.h"

// Protocol utilities will help with compile-time verifications
#include "utils.h"

// Reinclude all of the protocol inlines to define objects
#include "protocol_objects_begin.inl"
#include "auth.h"
#include "common.inl"
#include "protocol_objects_end.inl"

/*   This file is part of fus.
 *
 *   fus 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.
 *
 *   fus 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 fus.  If not, see <http://www.gnu.org/licenses/>.
 */

// Include all protocol headers here
#include "auth.h"
#include "common.h"

// Protocol utilities will help with compile-time verifications
#include "utils.h"

// Reinclude all of the protocol inlines to define objects
#include "protocol_objects_begin.inl"
#include "auth.inl"
#include "common.inl"
#include "protocol_objects_end.inl"

Fix auth struct linker problem


#include "rdb_protocol/configured_limits.hpp"
#include <limits>
#include "rdb_protocol/wire_func.hpp"
#include "rdb_protocol/func.hpp"

namespace ql {
configured_limits_t
from_optargs(rdb_context_t *ctx, signal_t *interruptor, global_optargs_t *arguments)
{
    if (arguments->has_optarg("array_limit")) {
        // Fake an environment with no arguments.  We have to fake it
        // because of a chicken/egg problem; this function gets called
        // before there are any extant environments at all.  Only
        // because we use an empty argument list do we prevent an
        // infinite loop.
        env_t env(ctx, interruptor, std::map<std::string, wire_func_t>(),
                  nullptr);
        int64_t limit = arguments->get_optarg(&env, "array_limit")->as_int();
        rcheck_datum(limit > 1, base_exc_t::GENERIC,
                     strprintf("Illegal array size limit `%ld`.", limit));
        return configured_limits_t(limit);
    } else {
        return configured_limits_t();
    }
}

RDB_IMPL_ME_SERIALIZABLE_1(configured_limits_t, array_size_limit_);
INSTANTIATE_SERIALIZABLE_SELF_FOR_CLUSTER(configured_limits_t);

const configured_limits_t configured_limits_t::unlimited(std::numeric_limits<size_t>::max());

} // namespace ql

#include "rdb_protocol/configured_limits.hpp"
#include <limits>
#include "rdb_protocol/wire_func.hpp"
#include "rdb_protocol/func.hpp"

namespace ql {
configured_limits_t
from_optargs(rdb_context_t *ctx, signal_t *interruptor, global_optargs_t *arguments)
{
    if (arguments->has_optarg("array_limit")) {
        // Fake an environment with no arguments.  We have to fake it
        // because of a chicken/egg problem; this function gets called
        // before there are any extant environments at all.  Only
        // because we use an empty argument list do we prevent an
        // infinite loop.
        env_t env(ctx, interruptor, std::map<std::string, wire_func_t>(),
                  nullptr);
        int64_t limit = arguments->get_optarg(&env, "array_limit")->as_int();
        rcheck_datum(limit > 1, base_exc_t::GENERIC,
                     strprintf("Illegal array size limit `%" PRIi64 "`.", limit));
        return configured_limits_t(limit);
    } else {
        return configured_limits_t();
    }
}

RDB_IMPL_ME_SERIALIZABLE_1(configured_limits_t, array_size_limit_);
INSTANTIATE_SERIALIZABLE_SELF_FOR_CLUSTER(configured_limits_t);

const configured_limits_t configured_limits_t::unlimited(std::numeric_limits<size_t>::max());

} // namespace ql

Use PRIi64 macro to work around clang weirdness.


#include "LevelState.h"

LevelState::LevelState()
{
}

LevelState::~LevelState()
{
}

int LevelState::ShutDown()
{
	int result = 1;
	return result;
}

int LevelState::Initialize(GameStateHandler * gsh, ComponentHandler* cHandler)
{
	int result = 0;
	result = GameState::InitializeBase(gsh, cHandler);

	//Read from file
	//Get Components
	//Set Component values
	//Give Components to entities
	this->m_player1.Initialize();

	return result;
}

int LevelState::Update(float dt, InputHandler * inputHandler)
{
	int result = 0;

	this->m_player1.Update(dt, inputHandler);

	return result;
}

#include "LevelState.h"

LevelState::LevelState()
{
}

LevelState::~LevelState()
{
}

int LevelState::ShutDown()
{
	int result = 1;
	return result;
}

int LevelState::Initialize(GameStateHandler * gsh, ComponentHandler* cHandler)
{
	int result = 0;
	result = GameState::InitializeBase(gsh, cHandler);

	//Read from file
	//Get Components
	GraphicsComponent* tempComp = this->m_cHandler->GetGraphicsComponent();
	//Set Component values
	tempComp->active = 1;
	tempComp->modelID = 1337;
	tempComp->worldMatrix = DirectX::XMMatrixIdentity();
	//Give Components to entities
	this->m_player1.Initialize();
	return result;
}

int LevelState::Update(float dt, InputHandler * inputHandler)
{
	int result = 0;

	this->m_player1.Update(dt, inputHandler);

	return result;
}

ADD gets graphicscomponent and sets values


// Includes
#include "App/Factories/TextFileNFDelegate.h"
#include "App/Nodes/TextFileNode.h"
#include "App/Logger.h"

// STD.
#include <fstream>

TextFileNFDelegate::TextFileNFDelegate()
{
}

TextFileNFDelegate::~TextFileNFDelegate()
{

}

std::string TextFileNFDelegate::nodeType() const
{
    return "TextFile";
}

std::vector<std::string> TextFileNFDelegate::requiredParameters()
{
    std::vector<std::string> result;
    result.push_back("fileName");
    return result;
}

bool TextFileNFDelegate::isValidParameter(const std::string &parameter, const std::string &value) const
{
    if (parameter == "fileName")
    {
        std::ifstream file(value.c_str());
        if (file.is_open())
        {
            file.close();
            return true;
        }
        else
        {
            file.close();
            Logger::instance().logError("File with given file name cannot be opened.");
            return false;
        }
    }
    else
    {
        return false;
    }
}

Node *TextFileNFDelegate::createNode(const std::string &id, const std::map<std::string, std::string> &parameters)
{
    return new TextFileNode(id, parameters.at("fileName"));
}

// Includes
#include "App/Factories/TextFileNFDelegate.h"
#include "App/Nodes/TextFileNode.h"
#include "App/Logger.h"

// STD.
#include <fstream>

TextFileNFDelegate::TextFileNFDelegate()
{
}

TextFileNFDelegate::~TextFileNFDelegate()
{

}

std::string TextFileNFDelegate::nodeType() const
{
    return "TextFile";
}

std::vector<std::string> TextFileNFDelegate::requiredParameters()
{
    std::vector<std::string> result;
    result.push_back("fileName");
    return result;
}

bool TextFileNFDelegate::isValidParameter(const std::string &parameter, const std::string &value) const
{
    if (parameter == "fileName")
    {
        std::string extension = value.substr(value.size()-4);
        if (extension != ".txt")
        {
            Logger::instance().logError("Invalid parameter: incorrect extension, should be '.txt'.");
            return false;
        }

        std::ifstream file(value.c_str());
        if (file.is_open())
        {
            file.close();
            return true;
        }
        else
        {
            file.close();
            Logger::instance().logError("Invalid parameter: file with given file name cannot be opened.");
            return false;
        }
    }
    else
    {
        Logger::instance().logError("Invalid parameter: parameter not supported for text file node.");
        return false;
    }
}

Node *TextFileNFDelegate::createNode(const std::string &id, const std::map<std::string, std::string> &parameters)
{
    return new TextFileNode(id, parameters.at("fileName"));
}

Add check for “txt” extension.


/*
 * SchemeAdHoc.c
 *
 * Scheme adhoc callback into opencog
 *
 * Copyright (c) 2008 Linas Vepstas <linas@linas.org>
 */

#ifdef HAVE_GUILE

#include <libguile.h>

#include <opencog/server/CogServer.h>
#include <opencog/nlp/wsd/WordSenseProcessor.h>

#include "SchemeSmob.h"

using namespace opencog;

/* ============================================================== */

/**
 * Dispatcher to invoke various miscellaneous C++ riff-raff from
 * scheme code.
 */
SCM SchemeSmob::ss_ad_hoc(SCM command)
{
	std::string cmdname = decode_string (command, "cog-ad-hoc");

	if (0 == cmdname.compare("do-wsd"))
	{
		WordSenseProcessor wsp;
		wsp.use_threads(false);
		wsp.run_no_delay(CogServer::createInstance()); // XXX What an ugly interface. Alas.
		return SCM_BOOL_T;
	}

	return SCM_BOOL_F;
}

#endif
/* ===================== END OF FILE ============================ */

/*
 * SchemeAdHoc.c
 *
 * Scheme adhoc callback into opencog
 *
 * Copyright (c) 2008 Linas Vepstas <linas@linas.org>
 */

#ifdef HAVE_GUILE

#include <libguile.h>

#include <opencog/server/CogServer.h>
#include <opencog/nlp/wsd/WordSenseProcessor.h>

#include "SchemeSmob.h"

using namespace opencog;

/* ============================================================== */

/**
 * Dispatcher to invoke various miscellaneous C++ riff-raff from
 * scheme code.
 */
SCM SchemeSmob::ss_ad_hoc(SCM command)
{
	std::string cmdname = decode_string (command, "cog-ad-hoc");

	if (0 == cmdname.compare("do-wsd"))
	{
		WordSenseProcessor wsp;
		wsp.use_threads(false);
		wsp.run_no_delay(static_cast<CogServer *>(&server())); // XXX What an ugly interface. Alas.
		return SCM_BOOL_T;
	}

	return SCM_BOOL_F;
}

#endif
/* ===================== END OF FILE ============================ */

Fix passing of server to subsystem.


#include <iostream>

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

namespace
{

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

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

    int loop();
};

int Repl::loop()
{
  std::ostringstream oss;
  while (true)
  {
    out_ << prompt_;
    oss.str("");
    oss.clear();
    try
    {
      mclisp::ConsCell *exp = reader_.Read();
      oss << *exp;

      if (EQ(exp, EOF) || oss.str() == "QUIT" || oss.str() == "(QUIT)")
        // TODO implement real (quit) function.
        break;

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

} //end namespace

int main()
{
  // InitLisp must be called before the Reader object is initialized (which
  // happens in the Repl constructor).
  mclisp::InitLisp();

  Repl repl;
  return repl.loop();
}

#include <iostream>

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

namespace
{

bool ShouldQuit(mclisp::ConsCell *exp)
{
  std::ostringstream oss;
  oss << *exp;
  return EQ(exp, EOF) || oss.str() == "QUIT" || oss.str() == "(QUIT)";
}

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

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

    int loop();
};

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

      if (ShouldQuit(exp))
        break;

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

} //end namespace

int main()
{
  // InitLisp must be called before the Reader object is initialized (which
  // happens in the Repl constructor).
  mclisp::InitLisp();

  Repl repl;
  return repl.loop();
}

Call ShouldQuit function to determine when to exit the REPL.


#include "mbed.h"
#include "MicroBit.h"

void RefCounted::init()
{
    // Initialize to one reference (lowest bit set to 1)
    refCount = 3;
}

static inline bool isReadOnlyInline(RefCounted *t)
{
    uint32_t refCount = t->refCount;

    if (refCount == 0xffff)
        return true; // object in flash

    // Do some sanity checking while we're here
    if (refCount == 1)
        uBit.panic(MICROBIT_USE_AFTER_FREE); // object should have been deleted

    if ((refCount & 1) == 0)
        uBit.panic(MICROBIT_REF_COUNT_CORRUPTION); // refCount doesn't look right

    // Not read only
    return false;
}

bool RefCounted::isReadOnly()
{
    return isReadOnlyInline(this);
}

void RefCounted::incr()
{
    if (!isReadOnlyInline(this))
        refCount += 2;
}

void RefCounted::decr()
{
    if (isReadOnlyInline(this))
        return;

    refCount -= 2;
    if (refCount == 2) {
        free(this);
    }
}

#include "mbed.h"
#include "MicroBit.h"

void RefCounted::init()
{
    // Initialize to one reference (lowest bit set to 1)
    refCount = 3;
}

static inline bool isReadOnlyInline(RefCounted *t)
{
    uint32_t refCount = t->refCount;

    if (refCount == 0xffff)
        return true; // object in flash

    // Do some sanity checking while we're here
    if (refCount == 1)
        uBit.panic(MICROBIT_USE_AFTER_FREE); // object should have been deleted

    if ((refCount & 1) == 0)
        uBit.panic(MICROBIT_REF_COUNT_CORRUPTION); // refCount doesn't look right

    // Not read only
    return false;
}

bool RefCounted::isReadOnly()
{
    return isReadOnlyInline(this);
}

void RefCounted::incr()
{
    if (!isReadOnlyInline(this))
        refCount += 2;
}

void RefCounted::decr()
{
    if (isReadOnlyInline(this))
        return;

    refCount -= 2;
    if (refCount == 1) {
        free(this);
    }
}

Delete when ref-count goes to 1, not 2\!


#include <SFML/Graphics.hpp>

int main(int argc, char const *argv[]) {
  sf::RenderWindow window(sf::VideoMode(800, 600), "Lord of the Orb",
                          sf::Style::Titlebar | sf::Style::Close);

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

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

    window.display();
  }

  return 0;
}

#include <SFML/Graphics.hpp>

int main(int argc, char const *argv[]) {
  sf::RenderWindow window(sf::VideoMode(1280, 720),
                          "Lord of the Orb",
                          sf::Style::Close);

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

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

    window.display();
  }

  return 0;
}

Change resolution to 16:9 aspect ratio


#include <node.h>
#include <node_internals.h>
using namespace v8;

#include "runas.h"

namespace {

Handle<Value> Runas(const Arguments& args) {
  HandleScope scope;

  if (!args[0]->IsString() || !args[1]->IsArray() || !args[2]->IsObject())
    return node::ThrowError("Bad argument");

  std::string command(*String::Utf8Value(args[0]));
  std::vector<std::string> c_args;

  Handle<Array> v_args = Handle<Array>::Cast(args[1]);
  uint32_t length = v_args->Length();

  c_args.reserve(length);
  for (uint32_t i = 0; i < length; ++i) {
    std::string arg(*String::Utf8Value(v_args->Get(i)));
    c_args.push_back(arg);
  }

  Handle<Object> v_options = args[2]->ToObject();
  int options = runas::OPTION_NONE;
  if (v_options->Get(String::New("hide"))->BooleanValue())
    options |= runas::OPTION_HIDE;

  int code;
  if (!runas::Runas(command, c_args, options, &code))
    return node::ThrowError("Failed to call runas");

  return scope.Close(Integer::New(code));
}

void Init(Handle<Object> exports) {
  NODE_SET_METHOD(exports, "runas", Runas);
}

}  // namespace

NODE_MODULE(runas, Init)

#include "nan.h"
using namespace v8;

#include "runas.h"

namespace {

NAN_METHOD(Runas) {
  NanScope();

  if (!args[0]->IsString() || !args[1]->IsArray() || !args[2]->IsObject())
    return NanThrowTypeError("Bad argument");

  std::string command(*String::Utf8Value(args[0]));
  std::vector<std::string> c_args;

  Handle<Array> v_args = Handle<Array>::Cast(args[1]);
  uint32_t length = v_args->Length();

  c_args.reserve(length);
  for (uint32_t i = 0; i < length; ++i) {
    std::string arg(*String::Utf8Value(v_args->Get(i)));
    c_args.push_back(arg);
  }

  Handle<Object> v_options = args[2]->ToObject();
  int options = runas::OPTION_NONE;
  if (v_options->Get(String::New("hide"))->BooleanValue())
    options |= runas::OPTION_HIDE;

  int code;
  if (!runas::Runas(command, c_args, options, &code))
    return NanThrowError("Failed to call runas");

  NanReturnValue(Integer::New(code));
}

void Init(Handle<Object> exports) {
  NODE_SET_METHOD(exports, "runas", Runas);
}

}  // namespace

NODE_MODULE(runas, Init)

Use nan to wrap V8 functions.


#include "MOLPUpdateComputation.hpp"

MOLPUpdateComputation::MOLPUpdateComputation(MOLP a, MOLP b) : molpA(a), molpB(b) {
}

bool noDominance() {
  return (molpA.empty() ||
          molpB.empty() ||
          molpA.isInA1AreaOf(molpB) ||
          molpB.isInA1AreaOf(molpA));
}

void MOLPUpdateComputation::initIterators() {
  endA = molpA.edges().end();
  endB = molpB.edges().end();
  iterA = molpA.edges().begin();
  iterB = molpB.edges().begin();
  while (iterA->isInA1AreaOf(*iterB) && iterA != endA)
    ++iterA;
  while (iterB->isInA1AreaOf(*iterA) && iterB != endB)
    ++iterB;
}

DominanceStatus MOLPUpdateComputation::computeUpdate() {
  if (noDominance())
    return DominanceStatus::NO_DOM;
  initIterators();
}

#include "MOLPUpdateComputation.hpp"

MOLPUpdateComputation::MOLPUpdateComputation(MOLP a, MOLP b) : molpA(a), molpB(b) {
}

bool MOLPUpdateComputation::noDominance() {
  return (molpA.empty() ||
          molpB.empty() ||
          molpA.isInA1AreaOf(molpB) ||
          molpB.isInA1AreaOf(molpA));
}

void MOLPUpdateComputation::initIterators() {
  endA = molpA.edges().end();
  endB = molpB.edges().end();
  iterA = molpA.edges().begin();
  iterB = molpB.edges().begin();
  while (iterA->isInA1AreaOf(*iterB) && iterA != endA)
    ++iterA;
  while (iterB->isInA1AreaOf(*iterA) && iterB != endB)
    ++iterB;
}

DominanceStatus MOLPUpdateComputation::computeUpdate() {
  if (noDominance())
    return DominanceStatus::NO_DOM;
  initIterators();
}

Fix the scope of noDominance()


#include <Ab/Config.hpp>
#include <Ab/Memory.hpp>
#include <Ab/Test/BasicTest.hpp>
#include <gtest/gtest.h>

namespace Ab {
namespace Test {

class TestMemory : public BasicTest {};

TEST_F(TestMemory, initAndKill) {
	Memory m;
	ASSERT_EQ(m.init(Memory::defaultConfig()), MemoryError::SUCCESS);
	m.kill();
}

}  // namespace Test
}  // namespace Ab

#include <Ab/Config.hpp>
#include <Ab/Memory.hpp>
#include <Ab/Test/BasicTest.hpp>
#include <gtest/gtest.h>

namespace Ab {
namespace Test {

class TestMemory : public BasicTest {};

TEST_F(TestMemory, initAndKill) {
	Memory m;
	ASSERT_EQ(m.init(Memory::defaultConfig()), MemoryError::SUCCESS);
	m.kill();
}

TEST_F(TestMemory, grow) {
	Memory m;
	m.init(Memory::defaultConfig());
	for (std::size_t i = 0; i < 3; i++) {
		EXPECT_EQ(m.grow(), MemoryError::SUCCESS);
	}
	m.kill();
}

}  // namespace Test
}  // namespace Ab

Add a basic memory grow test


/**
 * \file heuristic.cc
 *
 *
 *
 * \author Ethan Burns
 * \date 2008-10-13
 */

#include "util/fixed_point.h"

#include "heuristic.h"

Heuristic::Heuristic(const SearchDomain *d) : domain(d), weight(fp_one) {}

Heuristic::~Heuristic() {}

void Heuristic::set_weight(float weight)
{
	weight = fp_one * weight;
}

fp_type Heuristic::get_weight(void) const
{
	return weight;
}

/**
 * \file heuristic.cc
 *
 *
 *
 * \author Ethan Burns
 * \date 2008-10-13
 */

#include "util/fixed_point.h"

#include "heuristic.h"

Heuristic::Heuristic(const SearchDomain *d) : domain(d), weight(fp_one) {}

Heuristic::~Heuristic() {}

void Heuristic::set_weight(float wt)
{
	weight = fp_one * wt;
}

fp_type Heuristic::get_weight(void) const
{
	return weight;
}

Fix a shadowed data member.


#include "omnicore/version.h"

#include "config/bitcoin-config.h"

#include <string>

#include <boost/test/unit_test.hpp>

BOOST_AUTO_TEST_SUITE(omnicore_version_tests)

BOOST_AUTO_TEST_CASE(version_comparison)
{
    BOOST_CHECK(OMNICORE_VERSION > 900300); // Master Core v0.0.9.3
}

/**
 * The following tests are very unhandy, because any version bump
 * breaks the tests.
 *
 * TODO: might be removed completely.
 */

BOOST_AUTO_TEST_CASE(version_string)
{
    BOOST_CHECK_EQUAL(OmniCoreVersion(), "0.0.10-rel");
}

BOOST_AUTO_TEST_CASE(version_number)
{
    BOOST_CHECK_EQUAL(OMNICORE_VERSION, 1000000);
}

BOOST_AUTO_TEST_CASE(config_package_version)
{
    // the package version is used in the file names:
    BOOST_CHECK_EQUAL(PACKAGE_VERSION, "0.0.10.0-rel");
}

BOOST_AUTO_TEST_SUITE_END()

#include "omnicore/version.h"

#include "config/bitcoin-config.h"

#include <string>

#include <boost/test/unit_test.hpp>

BOOST_AUTO_TEST_SUITE(omnicore_version_tests)

BOOST_AUTO_TEST_CASE(version_comparison)
{
    BOOST_CHECK(OMNICORE_VERSION > 1000000); // Omni Core v0.0.10.0
}

/**
 * The following tests are very unhandy, because any version bump
 * breaks the tests.
 *
 * TODO: might be removed completely.
 */

BOOST_AUTO_TEST_CASE(version_string)
{
    BOOST_CHECK_EQUAL(OmniCoreVersion(), "0.0.11-dev");
}

BOOST_AUTO_TEST_CASE(version_number)
{
    BOOST_CHECK_EQUAL(OMNICORE_VERSION, 1100000);
}

BOOST_AUTO_TEST_CASE(config_package_version)
{
    // the package version is used in the file names:
    BOOST_CHECK_EQUAL(PACKAGE_VERSION, "0.0.11.0-dev");
}

BOOST_AUTO_TEST_SUITE_END()

Update unit tests for 0.0.11.0-dev


#include <string>

#include <config/config.h>
#include <config/config_type_pointer.h>
#include <config/config_value.h>

ConfigTypePointer config_type_pointer;

bool
ConfigTypePointer::set(ConfigValue *cv, const std::string& vstr)
{
	if (pointers_.find(cv) != pointers_.end())
		return (false);

	Config *config = cv->config_;
	ConfigObject *co = config->lookup(vstr);
	if (co == NULL)
		return (false);

	pointers_[cv] = co;

	return (true);
}

#include <string>

#include <config/config.h>
#include <config/config_type_pointer.h>
#include <config/config_value.h>

ConfigTypePointer config_type_pointer;

bool
ConfigTypePointer::set(ConfigValue *cv, const std::string& vstr)
{
	if (pointers_.find(cv) != pointers_.end())
		return (false);

	/* XXX Have a magic None that is easily-detected?  */
	if (vstr == "None") {
		pointers_[cv] = NULL;
		return (true);
	}

	Config *config = cv->config_;
	ConfigObject *co = config->lookup(vstr);
	if (co == NULL)
		return (false);

	pointers_[cv] = co;

	return (true);
}

Support pointers to "None" as used in the wanproxy.conf.


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

#include "Labels.hpp"
#include "Utils.hpp"

static int currentLabel = 0;

std::string eddic::newLabel(){
   return "L" + toString(currentLabel++);
}

void eddic::resetNumbering(){
    currentLabel = 0;
}

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

#include "Labels.hpp"
#include "Utils.hpp"

__thread int currentLabel = 0;

std::string eddic::newLabel(){
   return "L" + toString(currentLabel++);
}

void eddic::resetNumbering(){
    currentLabel = 0;
}

Use thread local storage for label counter


/*
** © 2014 by Philipp Dunkel <pip@pipobscure.com>
** Licensed under MIT License.
*/

void FSEvents::emitEvent(const char *path, UInt32 flags, UInt64 id) {
  if (!handler) return;
  NanScope();
  v8::Local<v8::Value> argv[] = {
    NanNew<v8::String>(path),
    NanNew<v8::Number>(flags),
    NanNew<v8::Number>(id)
  };
  handler->Call(3, argv);
}

NAN_METHOD(FSEvents::New) {
  NanScope();

  char* path = static_cast<char *>(NanRawString(args[0], Nan::UTF8, NULL, NULL, 0, v8::String::NO_OPTIONS));
  NanCallback *callback = new NanCallback(args[1].As<v8::Function>());

  FSEvents *fse = new FSEvents(path, callback);
  fse->Wrap(args.This());

  NanReturnValue(args.This());
}

NAN_METHOD(FSEvents::Stop) {
  NanScope();

  FSEvents* fse = node::ObjectWrap::Unwrap<FSEvents>(args.This());

  fse->threadStop();
  fse->asyncStop();

  NanReturnValue(args.This());
}

NAN_METHOD(FSEvents::Start) {
  NanScope();

  FSEvents* fse = node::ObjectWrap::Unwrap<FSEvents>(args.This());
  fse->asyncStart();
  fse->threadStart();

  NanReturnValue(args.This());
}

/*
** © 2014 by Philipp Dunkel <pip@pipobscure.com>
** Licensed under MIT License.
*/

void FSEvents::emitEvent(const char *path, UInt32 flags, UInt64 id) {
  if (!handler) return;
  NanScope();
  v8::Local<v8::Value> argv[] = {
    NanNew<v8::String>(path),
    NanNew<v8::Number>(flags),
    NanNew<v8::Number>(id)
  };
  handler->Call(3, argv);
}

NAN_METHOD(FSEvents::New) {
  NanScope();

  char* path = static_cast<char *>(*NanUtf8String(args[0]));
  NanCallback *callback = new NanCallback(args[1].As<v8::Function>());

  FSEvents *fse = new FSEvents(path, callback);
  fse->Wrap(args.This());

  NanReturnValue(args.This());
}

NAN_METHOD(FSEvents::Stop) {
  NanScope();

  FSEvents* fse = node::ObjectWrap::Unwrap<FSEvents>(args.This());

  fse->threadStop();
  fse->asyncStop();

  NanReturnValue(args.This());
}

NAN_METHOD(FSEvents::Start) {
  NanScope();

  FSEvents* fse = node::ObjectWrap::Unwrap<FSEvents>(args.This());
  fse->asyncStart();
  fse->threadStart();

  NanReturnValue(args.This());
}

Replace deprecated NanRawString with NanUtf8String


/*
 * Copyright © 2017 Collabora Ltd.
 *
 * This file is part of vkmark.
 *
 * vkmark is free software: you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation, either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * vkmark is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with vkmark. If not, see <http://www.gnu.org/licenses/>.
 *
 * Authors:
 *   Alexandros Frantzis <alexandros.frantzis@collabora.com>
 */

#include "default_benchmarks.h"

std::vector<std::string> DefaultBenchmarks::get()
{
    return std::vector<std::string>{
        "vertex",
        "shading:shading=gouraud",
        "shading:shading=blinn-phong-inf",
        "shading:shading=phong",
        "shading:shading=cel",
        "cube",
        "clear"
    };
}

/*
 * Copyright © 2017 Collabora Ltd.
 *
 * This file is part of vkmark.
 *
 * vkmark is free software: you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation, either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * vkmark is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with vkmark. If not, see <http://www.gnu.org/licenses/>.
 *
 * Authors:
 *   Alexandros Frantzis <alexandros.frantzis@collabora.com>
 */

#include "default_benchmarks.h"

std::vector<std::string> DefaultBenchmarks::get()
{
    return std::vector<std::string>{
        "vertex:device-local=true",
        "vertex:device-local=false",
        "shading:shading=gouraud",
        "shading:shading=blinn-phong-inf",
        "shading:shading=phong",
        "shading:shading=cel",
        "cube",
        "clear"
    };
}

Add device-local variations of the vertex scene to the default benchmarks


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

namespace yks {

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

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

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

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

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

}

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

namespace yks {

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

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

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

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

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

}

Remove duplicated call to std::cos


// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.

#include "free_list.h"
#include <cassert>

namespace vespalib::datastore {

FreeList::FreeList()
    : _free_lists()
{
}

FreeList::~FreeList()
{
    assert(_free_lists.empty());
}

void
FreeList::attach(BufferFreeList& buf_list)
{
    _free_lists.push_back(&buf_list);
}

void
FreeList::detach(BufferFreeList& buf_list)
{
    if (!_free_lists.empty() && (_free_lists.back() == &buf_list)) {
        _free_lists.pop_back();
        return;
    }
    auto itr = std::find(_free_lists.begin(), _free_lists.end(), &buf_list);
    assert(itr != _free_lists.end());
    _free_lists.erase(itr);
}

}

// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.

#include "free_list.h"
#include <algorithm>
#include <cassert>

namespace vespalib::datastore {

FreeList::FreeList()
    : _free_lists()
{
}

FreeList::~FreeList()
{
    assert(_free_lists.empty());
}

void
FreeList::attach(BufferFreeList& buf_list)
{
    _free_lists.push_back(&buf_list);
}

void
FreeList::detach(BufferFreeList& buf_list)
{
    if (!_free_lists.empty() && (_free_lists.back() == &buf_list)) {
        _free_lists.pop_back();
        return;
    }
    auto itr = std::find(_free_lists.begin(), _free_lists.end(), &buf_list);
    assert(itr != _free_lists.end());
    _free_lists.erase(itr);
}

}

Include algorithm to get definition of std::find


#include "filefinder.h"

#if ! defined(_XOPEN_SOURCE) || _XOPEN_SOURCE < 600
#define _XOPEN_SOURCE 600       /* Get nftw() and S_IFSOCK declarations */
#endif
#include <ftw.h>

namespace{

std::vector<node> *nodes;

int dirTree(const char *pathname, const struct stat *sbuf, int type,
        struct FTW *ftwb){
  std::string filename(&pathname[ftwb->base]);
  std::string location(pathname);
  location = location.substr(0,location.size()-filename.size());
  nodes->emplace_back(filename,location,ftwb->level, type == FTW_D);
  return 0;
}

}

void find_files(std::vector<node>& ns){
  nodes = &ns;
  int flags = 0;
  if(nftw(".",dirTree,10,flags)== -1){
  }
}

#include "filefinder.h"

#if ! defined(_XOPEN_SOURCE) || _XOPEN_SOURCE < 600
#define _XOPEN_SOURCE 600       /* Get nftw() and S_IFSOCK declarations */
#endif
#include <ftw.h>

namespace{

std::vector<node> *nodes;

int dirTree(const char *pathname, const struct stat *, int type,
        struct FTW *ftwb){
  std::string filename(&pathname[ftwb->base]);
  std::string location(pathname);
  location = location.substr(0,location.size()-filename.size());
  nodes->emplace_back(filename,location,ftwb->level, type == FTW_D);
  return 0;
}

}

void find_files(std::vector<node>& ns){
  nodes = &ns;
  int flags = 0;
  if(nftw(".",dirTree,10,flags)== -1){
  }
}

Remove unused variable in file finder,


#include <string>
#include <vector>
#include <unistd.h>
#include <gtest/gtest.h>
#include <scxcorelib/scxstrencodingconv.h>
#include "getusername.h"

TEST(GetUserName,simple)
{
	// allocate a WCHAR_T buffer to receive username
	DWORD lpnSize = L_cuserid;
	WCHAR_T lpBuffer[lpnSize];

	BOOL result = GetUserName(lpBuffer, &lpnSize);

	// GetUserName returns 1 on success
	ASSERT_EQ(1, result);

	// get expected username
	std::string username(getlogin());

	// GetUserName sets lpnSize to length of username including null
	ASSERT_EQ(username.size()+1, lpnSize);

	// copy UTF-16 bytes (excluding null) from lpBuffer to vector for conversion
	unsigned char *begin = reinterpret_cast<unsigned char *>(&lpBuffer[0]);
	// -1 to skip null; *2 because UTF-16 encodes two bytes per character
	unsigned char *end = begin + (lpnSize-1)*2;
	std::vector<unsigned char> input(begin, end);
	// convert to UTF-8 for assertion
	std::string output;
	SCXCoreLib::Utf16leToUtf8(input, output);

	EXPECT_EQ(username, output);
}

#include <string>
#include <vector>
#include <unistd.h>
#include <gtest/gtest.h>
#include <scxcorelib/scxstrencodingconv.h>
#include "getusername.h"

class GetUserNameTest : public ::testing::Test {
protected:
	DWORD lpnSize;
	std::vector<WCHAR_T> lpBuffer;
	BOOL result;
	std::string userName;

	GetUserNameTest(): userName(std::string(getlogin())) {}

	void GetUserNameWithSize(DWORD size) {
		lpnSize = size;
		// allocate a WCHAR_T buffer to receive username
		lpBuffer.assign(lpnSize, '\0');
		result = GetUserName(&lpBuffer[0], &lpnSize);
	}
};

TEST_F(GetUserNameTest, NormalUse) {
	GetUserNameWithSize(L_cuserid);

	// GetUserName returns 1 on success
	ASSERT_EQ(1, result);

	// GetUserName sets lpnSize to length of username including null
	ASSERT_EQ(userName.size()+1, lpnSize);

	// copy UTF-16 bytes (excluding null) from lpBuffer to vector for conversion
	unsigned char *begin = reinterpret_cast<unsigned char *>(&lpBuffer[0]);
	// -1 to skip null; *2 because UTF-16 encodes two bytes per character
	unsigned char *end = begin + (lpnSize-1)*2;
	std::vector<unsigned char> input(begin, end);
	// convert to UTF-8 for assertion
	std::string output;
	SCXCoreLib::Utf16leToUtf8(input, output);

	EXPECT_EQ(userName, output);
}

Use test fixture in GetUserName unit tests


#include "KVProxy.h"
#include "KVProxy_p.h"
#include <iostream>

KVProxy::KVProxy(QObject *parent, unsigned short port) :
	QObject(parent), p("127.0.0.1", port)
{
	// Make the poll timer tell the proxy to poll; this will be started with
	// a timeout of 0, so it will effectively poll on every event loop tick
	connect(&pollTimer, SIGNAL(timeout()), this, SLOT(poll()));

	// Pass on new connections to a function in KVProxy_p
	p.on_connection([this](HttpProxy::Connection::Ptr con) {
		proxyHandleConnection(this, con);
	});
}

KVProxy::~KVProxy()
{

}

int KVProxy::port()
{
	return p.get_local_port_number();
}

void KVProxy::run(bool async)
{
	if(async)
		pollTimer.start(20);
	else
		p.run();
}

void KVProxy::poll()
{
	p.poll();
}

#include "KVProxy.h"
#include "KVProxy_p.h"
#include <iostream>
#include <string>

KVProxy::KVProxy(QObject *parent, unsigned short port) :
	QObject(parent), p("127.0.0.1", port)
{
	// Make the poll timer tell the proxy to poll; this will be started with
	// a timeout of 0, so it will effectively poll on every event loop tick
	connect(&pollTimer, SIGNAL(timeout()), this, SLOT(poll()));

	// Pass on new connections to a function in KVProxy_p
	p.on_connection([this](HttpProxy::Connection::Ptr con) {
		proxyHandleConnection(this, con);
	});

	p.on_error([](std::string str, bool){
		qDebug() << "Proxy Error: " << str.c_str();
	});
}

KVProxy::~KVProxy()
{

}

int KVProxy::port()
{
	return p.get_local_port_number();
}

void KVProxy::run(bool async)
{
	if(async)
		pollTimer.start(20);
	else
		p.run();
}

void KVProxy::poll()
{
	p.poll();
}

Print proxy errors to qDebug


#include <QGuiApplication>
#include <QQuickView>

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

    QQuickView view;
    view.setSource(QUrl::fromLocalFile("GameWindow.qml"));
    view.show();

    return app.exec();
}

#include <QGuiApplication>
#include <QQuickView>
#include <QDeclarativeEngine>
#include <QDir>

int main(int argc, char *argv[]) {
    QByteArray data = "1";
    qputenv("QML_IMPORT_TRACE", data);

    QGuiApplication app(argc, argv);

    QQuickView view;

    view.engine()->addImportPath("../../imports");

    view.setSource(QUrl::fromLocalFile("GameWindow.qml"));
    view.show();

    return app.exec();
}

Add import path to gamewindow example


//Precompiled header are used in this project
#include "stdafx.h"

//Include Annwvyn Engine.
#include <Annwvyn.h>
//Every Annwvyn classes are in the Annwvyn namespace
using namespace Annwvyn;

//Include our level/stages here
#include "myLevel.hpp"

AnnMain() //The application entry point is "AnnMain()". return type int.
{
	//Initialize the engine
	new AnnEngine("A game using Annwvyn");

	//Load your ressources here
	AnnEngine::Instance()->initResources();
	AnnEngine::Instance()->oculusInit();
	//If the player has to folow the integrated physics scheme
	AnnEngine::Instance()->initPlayerPhysics();
	//Do the other initialization herttEventListener(); //Basic events

	//Intentiate and register our basic level
	AnnEngine::Instance()->getLevelManager()->addLevel(new MyLevel);
	//This will make the game load and start the 1st we have registered
	AnnEngine::Instance()->getLevelManager()->jumpToFirstLevel();

	//This will recenter the facing direction of the player
	//in the real world with the VR
	AnnEngine::Instance()->resetOculusOrientation();

	//The game is rendering here now:
	AnnEngine::Instance()->startGameplayLoop();

	//destroy the engine
	delete AnnEngine::Instance();
	return EXIT_SUCCESS;
}

//Precompiled header are used in this project
#include "stdafx.h"

//Include Annwvyn Engine.
#include <Annwvyn.h>
//Every Annwvyn classes are in the Annwvyn namespace
using namespace Annwvyn;

//Include our level/stages here
#include "myLevel.hpp"

AnnMain() //The application entry point is "AnnMain()". return type int.
{
	//Initialize the engine
	AnnEngine::openConsole();
	new AnnEngine("A game using Annwvyn");

	//Load your ressources here
	AnnEngine::Instance()->initResources();
	AnnEngine::Instance()->oculusInit();
	//If the player has to folow the integrated physics scheme
	AnnEngine::Instance()->initPlayerPhysics();
	//Do the other initialization herttEventListener(); //Basic events

	//Intentiate and register our basic level
	AnnEngine::Instance()->getLevelManager()->addLevel(new MyLevel);
	//This will make the game load and start the 1st we have registered
	AnnEngine::Instance()->getLevelManager()->jumpToFirstLevel();

	//This will recenter the facing direction of the player
	//in the real world with the VR
	AnnEngine::Instance()->resetOculusOrientation();

	//The game is rendering here now:
	AnnEngine::Instance()->useDefaultEventListener();
	AnnEngine::Instance()->startGameplayLoop();

	//destroy the engine
	delete AnnEngine::Instance();
	return EXIT_SUCCESS;
}

Fix template game by using default event listener


#include <string>
#include <fstream>
#include <streambuf>

#include "exceptions.h"
#include "file_utils.h"

namespace file_utils {

std::vector<unicode> read_lines(const unicode& filename) {
    unicode contents = read(filename);

    return unicode(contents).split("\n");
}

unicode read(const unicode& filename) {

    std::ifstream t(filename.encode().c_str());
    if(!t) {
        throw IOError(_u("Unable to load file") + filename);
    }

    std::string str((std::istreambuf_iterator<char>(t)),
                 std::istreambuf_iterator<char>());

    return unicode(str);
}

}

#include <string>
#include <fstream>
#include <streambuf>

#include "exceptions.h"
#include "file_utils.h"

namespace file_utils {

std::vector<unicode> read_lines(const unicode& filename) {
    unicode contents = read(filename);

    return unicode(contents).split("\n");
}

unicode read(const unicode& filename) {

    std::ifstream in(filename.encode().c_str());
    if(!in) {
        throw IOError(_u("Unable to load file") + filename);
    }

    auto str = [&in]{
      std::ostringstream ss{};
      ss << in.rdbuf();
      return ss.str();
    }();

    return unicode(str);
}

}

Improve the file reading code to not be so buggy


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

#include "ppapi/tests/mojo/test_mojo.h"

#include "third_party/mojo/src/mojo/public/cpp/system/message_pipe.h"

REGISTER_TEST_CASE(Mojo);

TestMojo::TestMojo(TestingInstance* instance) : TestCase(instance) { }
bool TestMojo::Init() {
  return true;
}

void TestMojo::RunTests(const std::string& filter) {
  RUN_TEST(CreateMessagePipe, filter);
}

std::string TestMojo::TestCreateMessagePipe() {
  mojo::MessagePipe pipe;
  PASS();
}

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

#include "ppapi/tests/mojo/test_mojo.h"

#include "third_party/mojo/src/mojo/public/cpp/system/message_pipe.h"

REGISTER_TEST_CASE(Mojo);

TestMojo::TestMojo(TestingInstance* instance) : TestCase(instance) { }
bool TestMojo::Init() {
  return true;
}

void TestMojo::RunTests(const std::string& filter) {
  RUN_TEST(CreateMessagePipe, filter);
}

std::string TestMojo::TestCreateMessagePipe() {
  MojoHandle h0;
  MojoHandle h1;
  ASSERT_EQ(MOJO_RESULT_OK, MojoCreateMessagePipe(NULL, &h0, &h1));
  PASS();
}

Make Mojo test more strict.


#include <mettle.hpp>
using namespace mettle;

struct my_type {};

namespace my_namespace {
  struct another_type {};
}

suite<> test_type_name("type_name()", [](auto &_) {
  _.test("primitives", []() {
    expect(type_name<int>(), equal_to("int"));
    expect(type_name<int &>(), regex_match("int\\s*&"));
    expect(type_name<int &&>(), regex_match("int\\s*&&"));
    expect(type_name<const int>(), equal_to("const int"));
    expect(type_name<volatile int>(), equal_to("volatile int"));
    expect(type_name<const volatile int>(), equal_to("const volatile int"));
  });

  _.test("custom types", []() {
    expect(type_name<my_type>(), equal_to("my_type"));
    expect(type_name<my_namespace::another_type>(),
           equal_to("my_namespace::another_type"));
  });
});

#include <mettle.hpp>
using namespace mettle;

struct my_type {};

namespace my_namespace {
  struct another_type {};
}

suite<> test_type_name("type_name()", [](auto &_) {
  _.test("primitives", []() {
    expect(type_name<int>(), equal_to("int"));
    expect(type_name<int &>(), regex_match("int\\s*&"));
    expect(type_name<int &&>(), regex_match("int\\s*&&"));
    expect(type_name<const int>(), equal_to("const int"));
    expect(type_name<volatile int>(), equal_to("volatile int"));
    expect(type_name<const volatile int>(), any(
      equal_to("const volatile int"),
      equal_to("volatile const int")
    ));
  });

  _.test("custom types", []() {
    expect(type_name<my_type>(), regex_match("(struct )?my_type$"));
    expect(type_name<my_namespace::another_type>(),
           regex_match("(struct )?my_namespace::another_type$"));
  });
});

Fix type_name tests under Windows


#include "About.h"

#include "../../3RVX/Updater.h"

#include "../resource.h"

void About::Initialize() {
    INIT_CONTROL(LBL_TITLE, Label, _title);

    std::wstring version = Updater::MainAppVersionString();
    _title.Text(L"3RVX " + version);
}

void About::LoadSettings() {

}

void About::SaveSettings() {

}

#include "About.h"

#include "../Updater.h"
#include "../resource.h"

void About::Initialize() {
    INIT_CONTROL(LBL_TITLE, Label, _title);

    std::wstring version = Updater::MainAppVersionString();
    _title.Text(L"3RVX " + version);
}

void About::LoadSettings() {

}

void About::SaveSettings() {

}

Update about tab for Updater move


// Copyright (c) 2015-2017 William W. Fisher (at gmail dot com)
// This file is distributed under the MIT License.

#include "ofp/driver.h"
#include "ofp/unittest.h"

using namespace ofp;

class MockChannelListener : public ChannelListener {
 public:
  void onChannelUp(Channel *channel) override {}
  void onChannelDown(Channel *channel) override {}
  void onMessage(const Message *message) override;
};

void MockChannelListener::onMessage(const Message *message) {}

TEST(driver, test) {
  Driver driver;

  // Test installing signal handlers more than once.
  driver.installSignalHandlers();
  driver.installSignalHandlers();

  std::error_code err;

  UInt64 connId = driver.listen(
      ChannelOptions::FEATURES_REQ, 0, IPv6Endpoint{OFPGetDefaultPort()},
      ProtocolVersions::All, [] { return new MockChannelListener; }, err);

  EXPECT_NE(0, connId);

  // Don't call driver.run(). This test just tests initialization.
  // driver.run();
}

// Copyright (c) 2015-2017 William W. Fisher (at gmail dot com)
// This file is distributed under the MIT License.

#include "ofp/driver.h"
#include "ofp/unittest.h"

using namespace ofp;

class MockChannelListener : public ChannelListener {
 public:
  void onChannelUp(Channel *channel) override {}
  void onChannelDown(Channel *channel) override {}
  void onMessage(const Message *message) override;
};

void MockChannelListener::onMessage(const Message *message) {}

TEST(driver, test) {
  Driver driver;

  // Test installing signal handlers more than once.
  driver.installSignalHandlers();
  driver.installSignalHandlers();

  std::error_code err;
  UInt16 listenPort = UInt16_narrow_cast(OFPGetDefaultPort() + 10000);

  UInt64 connId = driver.listen(
      ChannelOptions::FEATURES_REQ, 0, {"127.0.0.1", listenPort},
      ProtocolVersions::All, [] { return new MockChannelListener; }, err);

  EXPECT_NE(0, connId);

  // Don't call driver.run(). This test just tests initialization.
  // driver.run();
}

Fix driver test so it doesn't fail if another oftr process is running.


#include "sieve.h"
#include <cmath>

namespace
{
bool is_prime(int n)
{
    if (n % 2 == 0) {
        return false;
    }
    const int max_factor = static_cast<int>(std::sqrt(n));
    for (int probe = 2; probe <= max_factor; ++probe) {
        if (n % probe == 0) {
            return false;
        }
    }
    return true;
}
}

namespace sieve
{

std::vector<int> primes(int n)
{
    std::vector<int> result;
    if (n >= 2) {
        result.push_back(2);
    }
    for (int candidate = 3; candidate < n; ++candidate) {
        if (is_prime(candidate)) {
            result.push_back(candidate);
        }
    }
    return result;
}

}

#include "sieve.h"
#include <algorithm>
#include <list>
#include <numeric>

namespace sieve
{

std::vector<int> primes(int n)
{
    std::vector<int> result;
    std::list<int> candidates(n-1);
    std::iota(candidates.begin(), candidates.end(), 2);
    while (!candidates.empty()) {
        const int next = candidates.front();
        candidates.pop_front();
        result.push_back(next);
        candidates.remove_if([next](int n) { return n % next == 0; });
    }
    return result;
}

}

Implement the algorithm as described in the problem


#include <gloperate/painter/Painter.h>

namespace gloperate
{

Painter::Painter(const std::string & name, ResourceManager & resourceManager, const std::string & relDataPath)
: Object(name)
, m_resourceManager(resourceManager)
, m_relDataPath(relDataPath)
, m_backgroundColor(1.0, 1.0, 1.0)
{
}

Painter::~Painter()
{
    for (auto & capability : m_capabilities)
    {
        delete capability;
    }
}

void Painter::initialize()
{
    onInitialize();
}

void Painter::paint()
{
    onPaint();
}

glm::vec3 Painter::backgroundColor() const
{
	return m_backgroundColor;
}

void Painter::setBackgroundColor(const glm::vec3 & color)
{
	m_backgroundColor = color;
}

AbstractCapability * Painter::addCapability(AbstractCapability * capability)
{
    m_capabilities.push_back(capability);

    return capability;
}

} // namespace gloperate

#include <gloperate/painter/Painter.h>

namespace gloperate
{

Painter::Painter(const std::string & name, ResourceManager & resourceManager, const std::string & relDataPath)
: Object(name)
, m_resourceManager(resourceManager)
, m_relDataPath(relDataPath)
, m_backgroundColor(0.0, 0.0, 0.0)
{
}

Painter::~Painter()
{
    for (auto & capability : m_capabilities)
    {
        delete capability;
    }
}

void Painter::initialize()
{
    onInitialize();
}

void Painter::paint()
{
    onPaint();
}

glm::vec3 Painter::backgroundColor() const
{
	return m_backgroundColor;
}

void Painter::setBackgroundColor(const glm::vec3 & color)
{
	m_backgroundColor = color;
}

AbstractCapability * Painter::addCapability(AbstractCapability * capability)
{
    m_capabilities.push_back(capability);

    return capability;
}

} // namespace gloperate

Change default background color to black


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

#ifdef SK_BUILD_FOR_ANDROID
#include "SkPicturePlayback.h"
#endif
#include "SkPictureRecorder.h"

SkCanvas* SkPictureRecorder::beginRecording(int width, int height,
                                            SkBBHFactory* bbhFactory /* = NULL */,
                                            uint32_t recordFlags /* = 0 */) {
    fPicture.reset(SkNEW(SkPicture));
    return fPicture->beginRecording(width, height, bbhFactory, recordFlags);
}

#ifdef SK_BUILD_FOR_ANDROID
void SkPictureRecorder::partialReplay(SkCanvas* canvas) {
    if (NULL == fPicture.get() || NULL == canvas) {
        // Not recording or nothing to replay into
        return;
    }

    SkASSERT(NULL != fPicture->fRecord);

    SkAutoTDelete<SkPicturePlayback> playback(SkPicture::FakeEndRecording(fPicture,
                                                                          *fPicture->fRecord,
                                                                          false));
    playback->draw(*canvas, NULL);
}
#endif

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

// Need to include SkTypes first, so that SK_BUILD_FOR_ANDROID is defined.
#include "SkTypes.h"
#ifdef SK_BUILD_FOR_ANDROID
#include "SkPicturePlayback.h"
#endif
#include "SkPictureRecorder.h"

SkCanvas* SkPictureRecorder::beginRecording(int width, int height,
                                            SkBBHFactory* bbhFactory /* = NULL */,
                                            uint32_t recordFlags /* = 0 */) {
    fPicture.reset(SkNEW(SkPicture));
    return fPicture->beginRecording(width, height, bbhFactory, recordFlags);
}

#ifdef SK_BUILD_FOR_ANDROID
void SkPictureRecorder::partialReplay(SkCanvas* canvas) {
    if (NULL == fPicture.get() || NULL == canvas) {
        // Not recording or nothing to replay into
        return;
    }

    SkASSERT(NULL != fPicture->fRecord);

    SkAutoTDelete<SkPicturePlayback> playback(SkPicture::FakeEndRecording(fPicture,
                                                                          *fPicture->fRecord,
                                                                          false));
    playback->draw(*canvas, NULL);
}
#endif

Include SkTypes to fix Android frameworks build


#include "blif_lexer.hpp"
#include "blif_lexer.gen.hpp" //For blifparse_lex_*()

extern YY_DECL; //For blifparse_lex()

namespace blifparse {

Lexer::Lexer(FILE* file, Callback& callback)
    : callback_(callback) {
    blifparse_lex_init(&state_);
    blifparse_set_in(file, state_);
}

Lexer::~Lexer() {
    blifparse_lex_destroy(state_);
}

Parser::symbol_type Lexer::next_token() {
    return blifparse_lex(state_, callback_);
}

const char* Lexer::text() const {
    return blifparse_get_text(state_);
}

int Lexer::lineno() const {
    return blifparse_get_lineno(state_);
}

}

#include "blif_lexer.hpp"

//Windows doesn't have unistd.h, so we set '%option nounistd'
//in blif_lexer.l, but flex still includes it in the generated
//header unless YY_NO_UNISTD_H is defined to 1
#define YY_NO_UNISTD_H 1
#include "blif_lexer.gen.hpp" //For blifparse_lex_*()

extern YY_DECL; //For blifparse_lex()

namespace blifparse {

Lexer::Lexer(FILE* file, Callback& callback)
    : callback_(callback) {
    blifparse_lex_init(&state_);
    blifparse_set_in(file, state_);
}

Lexer::~Lexer() {
    blifparse_lex_destroy(state_);
}

Parser::symbol_type Lexer::next_token() {
    return blifparse_lex(state_, callback_);
}

const char* Lexer::text() const {
    return blifparse_get_text(state_);
}

int Lexer::lineno() const {
    return blifparse_get_lineno(state_);
}

}

Remove unistd.h inclusion for Windows


#include <ncurses.h>

#include "../../../src/contents.hh"
#include "../../../src/key_aliases.hh"
#include "../../vick-move/src/move.hh"

void enter_insert_mode(contents& contents, boost::optional<int>) {
    char ch;
    contents.is_inserting = true;
    while((ch = getch()) != _escape) {
        contents.cont[contents.y].insert(contents.x, 1, ch);
        mvf(contents);
        if(get_contents().refresh) {
            print_contents(get_contents());
        }
    }
    contents.is_inserting = false;
}

void enter_replace_mode(contents& contents, boost::optional<int>) {
    char ch;
    contents.is_inserting = true;
    while((ch = getch()) != _escape) {
        if(contents.x >= contents.cont[contents.y].size()) {
            contents.cont[contents.y].push_back(ch);
        } else {
            contents.cont[contents.y][contents.x] = ch;
        }
        if(get_contents().refresh) {
            print_contents(get_contents());
        }
    }
    contents.is_inserting = false;
}

#include <ncurses.h>

#include "../../../src/contents.hh"
#include "../../../src/key_aliases.hh"
#include "../../vick-move/src/move.hh"

void enter_insert_mode(contents& contents, boost::optional<int>) {
    char ch;
    contents.is_inserting = true;
    while((ch = getch()) != _escape) {
        contents.cont[contents.y].insert(contents.x, 1, ch);
        mvf(contents);
        if(get_contents().refresh) {
            print_contents(get_contents());
        }
    }
    contents.is_inserting = false;
}

void enter_replace_mode(contents& contents, boost::optional<int>) {
    char ch;
    contents.is_inserting = true;
    while((ch = getch()) != _escape) {
        if(contents.x >= contents.cont[contents.y].size()) {
            contents.cont[contents.y].push_back(ch);
            contents.x = contents.cont[contents.y].size();
        } else {
            contents.cont[contents.y][contents.x] = ch;
            contents.x++;
        }
        if(get_contents().refresh) {
            print_contents(get_contents());
        }
    }
    contents.is_inserting = false;
}

Fix ``enter_replace_mode`` so that it works properly


#include "Penguin.h"

void Penguin::processEvents(SDL_Event* a_event)
{
	if (a_event->type == SDL_KEYDOWN)
	{
		switch (a_event->key.keysym.sym)
		{
			case SDLK_LEFT:
			{

			} break;

			case SDLK_RIGHT:
			{

			} break;
		}
	}
}

void Penguin::update(float a_deltaT)
{

}

void Penguin::startJump()
{
	if (m_onTheGround == true)
	{
		m_onTheGround = false;
	}
}

void Peguin::endJump()
{

}

#include "Penguin.h"

void Penguin::processEvents(SDL_Event* a_event)
{
	if (a_event->type == SDL_KEYDOWN)
	{
		switch (a_event->key.keysym.sym)
		{
			case SDLK_LEFT:
			{

			} break;

			case SDLK_RIGHT:
			{

			} break;
		}
	}
}

void Penguin::update(float a_deltaT)
{

}

void Penguin::startJump()
{
	if (m_jumping == false)
	{
		m_jumping = true;
	}
}

void Penguin::endJump()
{

}

Fix compile error on penguin sample game


// Copyright 2020 The Google Research Authors.
//
// 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 "benchmark_utils.h"

#include <utility>

#include "benchmark/benchmark.h"
#include "sketch.h"
#include "utils.h"

namespace sketch {

void Add(benchmark::State& state, Sketch* sketch) {
  for (auto _ : state) {
    state.PauseTiming();
    sketch->Reset();
    auto data = sketch::CreateStream(state.range(0)).first;
    state.ResumeTiming();
    for (const auto& [item, freq] : data) {
      sketch->Add(item, freq);
    }
  }
}

}  // namespace sketch

// Copyright 2020 The Google Research Authors.
//
// 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 "benchmark_utils.h"

#include <utility>

#include "benchmark/benchmark.h"
#include "sketch.h"
#include "utils.h"

namespace sketch {

constexpr int kAddBatchSize = 32;

auto MakeAddStreams(int count) {
  std::vector<std::vector<IntFloatPair>> streams(kAddBatchSize);
  for (auto& stream : streams) {
    stream = CreateStream(count).first;
  }
  return streams;
}

void Add(benchmark::State& state, Sketch* sketch) {
  auto streams = MakeAddStreams(state.range(0));
  while (state.KeepRunningBatch(kAddBatchSize)) {
    for (const auto& stream : streams) {
      for (const auto& [item, freq] : stream) {
        sketch->Add(item, freq);
      }
    }
  }
}

}  // namespace sketch

Improve benchmarks by batching data.


#include "msglistener.h"

#include <ei_connect.h>

namespace Mailbox {

MsgListener::MsgListener(int fd, QObject *parent) :
    QThread(parent),
    m_fd(fd)
{

}

void MsgListener::run()
{

}

} // namespace Mailbox

#include "msglistener.h"

#include <ei_connect.h>

namespace Mailbox {

MsgListener::MsgListener(int fd, QObject *parent) :
    QThread(parent),
    m_fd(fd)
{

}

void MsgListener::run()
{
    int length;
    erlang_msg msg;
    ei_x_buff buff;

    ei_x_new(&buff);

    length = ei_xreceive_msg_tmo(m_fd, &msg, &buff, 1000);

    if (length > 0 && (msg.msgtype == ERL_SEND || msg.msgtype == ERL_REG_SEND))
        emit messageRecieved();

    ei_x_free(&buff);
}

} // namespace Mailbox

Add Basic Message Recieve implementation


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

#include "content/browser/renderer_host/render_view_host_observer.h"

#include "content/browser/renderer_host/render_view_host.h"

RenderViewHostObserver::RenderViewHostObserver(RenderViewHost* render_view_host)
    : render_view_host_(render_view_host),
      routing_id_(render_view_host->routing_id()) {
  render_view_host_->AddObserver(this);
}

RenderViewHostObserver::~RenderViewHostObserver() {
  if (render_view_host_)
    render_view_host_->RemoveObserver(this);
}

void RenderViewHostObserver::RenderViewHostDestroyed() {
  delete this;
}

bool RenderViewHostObserver::OnMessageReceived(const IPC::Message& message) {
  return false;
}

bool RenderViewHostObserver::Send(IPC::Message* message) {
  if (!render_view_host_) {
    delete message;
    return false;
  }

  return render_view_host_->Send(message);
}

void RenderViewHostObserver::RenderViewHostDestruction() {
  render_view_host_->RemoveObserver(this);
  RenderViewHostDestroyed();
  render_view_host_ = NULL;
}

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

#include "content/browser/renderer_host/render_view_host_observer.h"

#include "content/browser/renderer_host/render_view_host.h"

RenderViewHostObserver::RenderViewHostObserver(RenderViewHost* render_view_host)
    : render_view_host_(render_view_host),
      routing_id_(render_view_host->routing_id()) {
  render_view_host_->AddObserver(this);
}

RenderViewHostObserver::~RenderViewHostObserver() {
  if (render_view_host_)
    render_view_host_->RemoveObserver(this);
}

void RenderViewHostObserver::RenderViewHostDestroyed() {
  delete this;
}

bool RenderViewHostObserver::OnMessageReceived(const IPC::Message& message) {
  return false;
}

bool RenderViewHostObserver::Send(IPC::Message* message) {
  if (!render_view_host_) {
    delete message;
    return false;
  }

  return render_view_host_->Send(message);
}

void RenderViewHostObserver::RenderViewHostDestruction() {
  render_view_host_ = NULL;
  RenderViewHostDestroyed();
}

Fix heap corruption that occurs when RenderViewHostObserver calls RenderViewHost to unregister when the latter is in its destructor.


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

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

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

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

#include "tensorflow/core/profiler/utils/errors.h"

namespace tensorflow {
namespace profiler {

const absl::string_view kErrorIncompleteStep =
    "Visualization based on incomplete step. No step markers observed and "
    "hence the step time is actually unknown. Instead, we use the trace "
    "duration as the step time. This may happen if your profiling duration "
    "is shorter than the step time. In that case, you may try to profile "
    "longer.";

const absl::string_view kErrorNoStepMarker =
    "Visualization contains on step based analysis. No step markers observed "
    "and hence the step time is actually unknown. This may happen if your "
    "profiling duration is shorter than the step time. In that case, you may "
    "try to profile longer.";

}  // namespace profiler
}  // namespace tensorflow

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

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

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

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

#include "tensorflow/core/profiler/utils/errors.h"

namespace tensorflow {
namespace profiler {

const absl::string_view kErrorIncompleteStep =
    "Incomplete step observed and hence the step time is unknown."
    "Instead, we use the trace duration as the step time. This may happen"
    " if your profiling duration is shorter than the step time. In this"
    " case, you may try to profile longer.";

const absl::string_view kErrorNoStepMarker =
    "No step marker observed and hence the step time is unknown."
    " This may happen if (1) training steps are not instrumented (e.g., if"
    " you are not using Keras) or (2) the profiling duration is shorter"
    " than the step time. For (1), you need to add step instrumentation;"
    " for (2), you may try to profile longer.";

}  // namespace profiler
}  // namespace tensorflow

Improve error messages of the Profiler.