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

#include "CPlusPlusLanguage.h"

#include "lldb/Core/ConstString.h"
#include "lldb/Core/PluginManager.h"

using namespace lldb;
using namespace lldb_private;

void
CPlusPlusLanguage::Initialize()
{
    PluginManager::RegisterPlugin (GetPluginNameStatic(),
                                   "C++ Language",
                                   CreateInstance);
}

void
CPlusPlusLanguage::Terminate()
{
    PluginManager::UnregisterPlugin (CreateInstance);
}

lldb_private::ConstString
CPlusPlusLanguage::GetPluginNameStatic()
{
    static ConstString g_name("cplusplus");
    return g_name;
}

//------------------------------------------------------------------
// PluginInterface protocol
//------------------------------------------------------------------
lldb_private::ConstString
CPlusPlusLanguage::GetPluginName()
{
    return GetPluginNameStatic();
}

uint32_t
CPlusPlusLanguage::GetPluginVersion()
{
    return 1;
}

//------------------------------------------------------------------
// Static Functions
//------------------------------------------------------------------
Language *
CPlusPlusLanguage::CreateInstance (lldb::LanguageType language)
{
    switch (language)
    {
        case lldb::eLanguageTypeC_plus_plus:
        case lldb::eLanguageTypeC_plus_plus_03:
        case lldb::eLanguageTypeC_plus_plus_11:
        case lldb::eLanguageTypeC_plus_plus_14:
            return new CPlusPlusLanguage();
        default:
            return nullptr;
    }
}

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

#include "CPlusPlusLanguage.h"

#include "lldb/Core/ConstString.h"
#include "lldb/Core/PluginManager.h"

using namespace lldb;
using namespace lldb_private;

void
CPlusPlusLanguage::Initialize()
{
    PluginManager::RegisterPlugin (GetPluginNameStatic(),
                                   "C++ Language",
                                   CreateInstance);
}

void
CPlusPlusLanguage::Terminate()
{
    PluginManager::UnregisterPlugin (CreateInstance);
}

lldb_private::ConstString
CPlusPlusLanguage::GetPluginNameStatic()
{
    static ConstString g_name("cplusplus");
    return g_name;
}

//------------------------------------------------------------------
// PluginInterface protocol
//------------------------------------------------------------------
lldb_private::ConstString
CPlusPlusLanguage::GetPluginName()
{
    return GetPluginNameStatic();
}

uint32_t
CPlusPlusLanguage::GetPluginVersion()
{
    return 1;
}

//------------------------------------------------------------------
// Static Functions
//------------------------------------------------------------------
Language *
CPlusPlusLanguage::CreateInstance (lldb::LanguageType language)
{
    if (Language::LanguageIsCPlusPlus(language))
        return new CPlusPlusLanguage();
    return nullptr;
}

Use Language::LanguageIsCPlusPlus instead of doing the same switch over language

git-svn-id: 4c4cc70b1ef44ba2b7963015e681894188cea27e@246613 91177308-0d34-0410-b5e6-96231b3b80d8


#include "environment.h"
#include <webdriverxx/client.h>
#include <gtest/gtest.h>

namespace test {

using namespace webdriverxx;

class TestClient : public ::testing::Test {
protected:
	static void SetUpTestCase() {
		client = new Client(GetWebDriverUrl());
	}

	static void TearDownTestCase() {
		delete client;
		client = 0;
	}

	static Client* client;
};

Client* TestClient::client = 0;

TEST_F(TestClient, GetsStatus) {
	picojson::object status = client->GetStatus();
	ASSERT_TRUE(status["build"].is<picojson::object>());
	ASSERT_TRUE(status["os"].is<picojson::object>());
}

TEST_F(TestClient, GetsSessions) {
	client->GetSessions();
}

TEST_F(TestClient, CreatesSession) {
 	Parameters params = GetParameters();
	client->CreateSession(params.required, params.desired);
}

} // namespace test

#include "environment.h"
#include <webdriverxx/client.h>
#include <gtest/gtest.h>

namespace test {

using namespace webdriverxx;

class TestClient : public ::testing::Test {
protected:
	static void SetUpTestCase() {
		client = new Client(GetWebDriverUrl());
	}

	static void TearDownTestCase() {
		delete client;
		client = 0;
	}

	static Client* client;
};

Client* TestClient::client = 0;

TEST_F(TestClient, GetsStatus) {
	picojson::object status = client->GetStatus();
	ASSERT_TRUE(status["build"].is<picojson::object>());
	ASSERT_TRUE(status["os"].is<picojson::object>());
}

TEST_F(TestClient, GetsSessions) {
	client->GetSessions();
}

TEST_F(TestClient, CreatesSession) {
 	Parameters params = GetParameters();
	client->CreateSession(params.desired, params.required);
}

} // namespace test

Fix wrong parameters order in client test


/* -*- Mode: C; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */
/*
 *     Copyright 2013 Couchbase, 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 <libcouchbase/debug.h>

/**
 * This is just an example program intended to show you how to use
 * the debug functionalities of libcouchbase
 */

static void dumpHttpCommand(void) {
    lcb_http_cmd_t http_cmd("/foo/bar", 8, NULL, 0, LCB_HTTP_METHOD_POST,
                            1, "applicaiton/json");
    std::cout << http_cmd << std::endl;
}

int main(void)
{
    dumpHttpCommand();
    exit(EXIT_SUCCESS);
}

/* -*- Mode: C; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */
/*
 *     Copyright 2013 Couchbase, 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 <libcouchbase/debug.h>
#include <cstdlib>

using namespace std;

/**
 * This is just an example program intended to show you how to use
 * the debug functionalities of libcouchbase
 */

static void dumpHttpCommand(void) {
    lcb_http_cmd_t http_cmd("/foo/bar", 8, NULL, 0, LCB_HTTP_METHOD_POST,
                            1, "applicaiton/json");
    cout << http_cmd << endl;
}

int main(void)
{
    dumpHttpCommand();
    exit(EXIT_SUCCESS);
}

Fix buildbreak for missing error code from cstdlib

Change-Id: I6b15a0d0169161f24a81a571ceb6dabfacc87eb2
Reviewed-on: http://review.couchbase.org/23983
Reviewed-by: Trond Norbye <60edd2ef23891a753f231b0c6f161dc634079a93@gmail.com>
Tested-by: Trond Norbye <60edd2ef23891a753f231b0c6f161dc634079a93@gmail.com>


#include "string_split.h"

namespace psz {

std::vector<std::string> SplitString(const std::string& str,
                                     const std::string& sep) {
  std::vector<std::string> results;
  size_t prev = 0;
  size_t pos = str.find(sep);
  while (pos != std::string::npos) {
    results.push_back(str.substr(prev, pos - prev));
    prev = pos + 1;
    pos = str.find(sep, prev);
  }
  results.push_back(str.substr(prev, str.length() - prev));
  return results;
}

std::vector<unsigned int> SplitStringAndParse(const std::string& str,
                                              const std::string& sep,
                                              int shift) {
  std::vector<unsigned int> result;
  for (const auto& val : SplitString(str, sep)) {
    if (val.empty()) {
      continue;
    }
    unsigned int val_u = std::stoul(val);
    // CHECK_LE(-shift, val_u);
    result.push_back(val_u + shift);
  }
  return result;
}

}  // namespace psz

#include "string_split.h"

namespace psz {

std::vector<std::string> SplitString(const std::string& str,
                                     const std::string& sep) {
  std::vector<std::string> results;
  size_t prev = 0;
  size_t pos = str.find(sep);
  while (pos != std::string::npos) {
    // TODO optimize!
    auto s = str.substr(prev, pos - prev);
    if (!s.empty()) {
      results.push_back(s);
    }
    prev = pos + 1;
    pos = str.find(sep, prev);
  }
  results.push_back(str.substr(prev, str.length() - prev));
  return results;
}

std::vector<unsigned int> SplitStringAndParse(const std::string& str,
                                              const std::string& sep,
                                              int shift) {
  std::vector<unsigned int> result;
  for (const auto& val : SplitString(str, sep)) {
    if (val.empty()) {
      continue;
    }
    unsigned int val_u = std::stoul(val);
    // CHECK_LE(-shift, val_u);
    result.push_back(val_u + shift);
  }
  return result;
}

}  // namespace psz

Fix empty string being added to string vector.


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

#include <Windows.h>
#include "Application.h"

int WINAPI WinMain(HINSTANCE hInstance,
	HINSTANCE hPrevInstance,
	LPSTR lpCmdLine,
	int nCmdShow)
{
	ouzel::Application* application = new ouzel::Application();
	//TODO: create main window
	//TODO: attach Renderer's view to this window
	//TODO: run main loop

	return 0;
}

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

#include <windows.h>
#include "Application.h"

int WINAPI WinMain(HINSTANCE hInstance,
	HINSTANCE hPrevInstance,
	LPSTR lpCmdLine,
	int nCmdShow)
{
	ouzel::Application* application = new ouzel::Application();
	//TODO: create main window
	//TODO: attach Renderer's view to this window
	//TODO: run main loop

	return 0;
}

Fix the case of windows.h for consistency


#include "../src/logger.h"

#define CATCH_CONFIG_MAIN
#include <lightstep/catch/catch.hpp>

using namespace lightstep;

TEST_CASE("logger") {
  LogLevel logged_level = LogLevel::off;
  std::string logged_message;
  Logger logger{[&](LogLevel level, opentracing::string_view message) {
    logged_level = level;
    logged_message = message;
  }};
  logger.set_level(LogLevel::warn);

  SECTION(
      "If log level is less than the logger's level, the message is ignored") {
    logger.Info("t");
    CHECK(logged_message.empty());
  }

  SECTION(
      "If log level is greater than or equal to the logger's message, the "
      "logger sink receive's the message") {
    logger.Warn("t1");
    CHECK(logged_level == LogLevel::warn);
    CHECK(logged_message == "t1");

    logger.Error("t2");
    CHECK(logged_level == LogLevel::error);
    CHECK(logged_message == "t2");
  }
}

#include "../src/logger.h"

#define CATCH_CONFIG_MAIN
#include <lightstep/catch/catch.hpp>

using namespace lightstep;

TEST_CASE("logger") {
  LogLevel logged_level = LogLevel::off;
  std::string logged_message;
  Logger logger{[&](LogLevel level, opentracing::string_view message) {
    logged_level = level;
    logged_message = message;
  }};
  logger.set_level(LogLevel::warn);

  SECTION(
      "If log level is less than the logger's level, the message is ignored") {
    logger.Info("t");
    CHECK(logged_message.empty());
  }

  SECTION(
      "If log level is greater than or equal to the logger's message, the "
      "logger sink receive's the message") {
    logger.Warn("t1");
    CHECK(logged_level == LogLevel::warn);
    CHECK(logged_message == "t1");

    logger.Error("t2");
    CHECK(logged_level == LogLevel::error);
    CHECK(logged_message == "t2");
  }

  SECTION("Multiple arguments are concatenated together") {
    logger.Warn("a", "bc");
    CHECK(logged_message == "abc");

    logger.Warn("a", "bc", 123);
    CHECK(logged_message == "abc123");
  }
}

Add concatenation test to logger.

Add concatenation test to logger.


//===--- ArgumentsAdjusters.cpp - Command line arguments adjuster ---------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file contains definitions of classes which implement ArgumentsAdjuster
// interface.
//
//===----------------------------------------------------------------------===//

#include "clang/Tooling/ArgumentsAdjusters.h"

namespace clang {
namespace tooling {

void ArgumentsAdjuster::anchor() {
}

/// Add -fsyntax-only option to the commnand line arguments.
CommandLineArguments
ClangSyntaxOnlyAdjuster::Adjust(const CommandLineArguments &Args) {
  CommandLineArguments AdjustedArgs = Args;
  // FIXME: Remove options that generate output.
  AdjustedArgs.push_back("-fsyntax-only");
  return AdjustedArgs;
}

} // end namespace tooling
} // end namespace clang

//===--- ArgumentsAdjusters.cpp - Command line arguments adjuster ---------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file contains definitions of classes which implement ArgumentsAdjuster
// interface.
//
//===----------------------------------------------------------------------===//

#include "clang/Tooling/ArgumentsAdjusters.h"
#include "clang/Basic/LLVM.h"
#include "llvm/ADT/StringRef.h"

namespace clang {
namespace tooling {

void ArgumentsAdjuster::anchor() {
}

/// Add -fsyntax-only option to the commnand line arguments.
CommandLineArguments
ClangSyntaxOnlyAdjuster::Adjust(const CommandLineArguments &Args) {
  CommandLineArguments AdjustedArgs;
  for (size_t i = 0, e = Args.size(); i != e; ++i) {
    StringRef Arg = Args[i];
    // FIXME: Remove options that generate output.
    if (!Arg.startswith("-fcolor-diagnostics") &&
        !Arg.startswith("-fdiagnostics-color"))
      AdjustedArgs.push_back(Args[i]);
  }
  AdjustedArgs.push_back("-fsyntax-only");
  return AdjustedArgs;
}

} // end namespace tooling
} // end namespace clang

Make clang tools ignore -fcolor-diagnostics and -fdiagnostics-color retrieved from the compilation database.

Summary:
Clang tools' diagnostic output could be force colored when a command
line from the compilation database contains -fcolor-diagnostics or
-fdiagnostics-color. This is not what we want e.g. for vim integration.

Reviewers: klimek

Reviewed By: klimek

CC: cfe-commits, revane, jordan_rose

Differential Revision: http://llvm-reviews.chandlerc.com/D917

git-svn-id: ffe668792ed300d6c2daa1f6eba2e0aa28d7ec6c@183304 91177308-0d34-0410-b5e6-96231b3b80d8


#include "ui/region_picker.hpp"

int main()
{
	EasyGIF::UI::RegionPicker picker(false);
	picker.Activate();
	while(picker.IsRunning())
	{
		picker.UpdateEvents();
		picker.ProcessInput();
		picker.Draw();
	}

	return 0;
}

#include "img/image_frame.hpp"
#include "img/image_grabber.hpp"
#include "img/image_saver.hpp"
#include "ui/region_picker.hpp"
#include <unistd.h>

int main()
{
	EasyGIF::UI::RegionPicker picker(false);
	EasyGIF::ImageFrame frame;
	EasyGIF::ImageGrabber grabber;
	EasyGIF::ImageSaver saver;
	picker.Activate();
	while(picker.IsRunning())
	{
		picker.UpdateEvents();
		if(picker.IsConfirmed())
		{
			::EasyGIF::Utility::Rectangle rect = picker.GetRect();
			picker.Shutdown();
			sleep(5); // let X close the window
			frame = grabber.Grab(rect);
			saver.LoadData(frame);
			saver.Save("./test_picker.png");
		}
		else
		{
			picker.ProcessInput();
			picker.Draw();
		}
	}

	return 0;
}

Test for saving a selected region to a file


#include <cassert>
#include <iostream>

#include "ColorFinder.hpp"

int main() {
  constexpr ColorFinder::Color c{0x82, 0x12, 0x18};
  constexpr auto name = getClosestColorName(c);
  std::cout << name << std::endl;
  return 0;
}

#include <cassert>
#include <iostream>

#include "ColorFinder.hpp"

int main() {
  constexpr ColorFinder::Color c{0x82, 0x12, 0x18};
  constexpr auto name = getClosestColorName(c);
  static_assert(name == "Falu Red", "Something went wrong");
  std::cout << name << std::endl;
  return 0;
}

Add static_assert to check evaluated value


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

#include <evm2wasm.h>

using namespace std;

int main(int argc, char **argv) {
    if (argc < 2) {
        cerr << "Usage: " << argv[0] << " <EVM file>" << endl;
        return 1;
    }

    ifstream input(argv[1]);
    if (!input.is_open()) {
        cerr << "File not found: " << argv[1] << endl;
        return 1;
    }

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

    cout << evm2wasm::evm2wasm(str) << endl;

    return 0;
}

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

#include <evm2wasm.h>

using namespace std;

int main(int argc, char **argv) {
    if (argc < 2) {
        cerr << "Usage: " << argv[0] << " <EVM file> [--wast]" << endl;
        return 1;
    }

    bool wast = false;
    if (argc == 3) {
        wast = (string(argv[2]) == "--wast");
        if (!wast) {
            cerr << "Usage: " << argv[0] << " <EVM file> [--wast]" << endl;
            return 1;
        }
    }

    ifstream input(argv[1]);
    if (!input.is_open()) {
        cerr << "File not found: " << argv[1] << endl;
        return 1;
    }

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

    if (wast) {
        cout << evm2wasm::evm2wast(str) << endl;
    } else {
        cout << evm2wasm::evm2wasm(str) << endl;
    }

    return 0;
}

Add --wast option to evm2wasm CLI

Add --wast option to evm2wasm CLI


#include "Genes/Freedom_To_Move_Gene.h"

#include <string>

#include "Genes/Gene.h"
#include "Game/Board.h"
#include "Game/Color.h"

double Freedom_To_Move_Gene::score_board(const Board& board, Piece_Color perspective, size_t) const noexcept
{
    static auto initial_score = double(Board().legal_moves().size());
    if(perspective == board.whose_turn())
    {
        return board.legal_moves().size()/initial_score;
    }
    else
    {
        return board.previous_moves_count()/initial_score;
    }
}

std::string Freedom_To_Move_Gene::name() const noexcept
{
    return "Freedom to Move Gene";
}

#include "Genes/Freedom_To_Move_Gene.h"

#include <string>

#include "Genes/Gene.h"
#include "Game/Board.h"
#include "Game/Color.h"

double Freedom_To_Move_Gene::score_board(const Board& board, Piece_Color perspective, size_t) const noexcept
{
    static const auto initial_score = double(Board().legal_moves().size());
    if(perspective == board.whose_turn())
    {
        return board.legal_moves().size()/initial_score;
    }
    else
    {
        return board.previous_moves_count()/initial_score;
    }
}

std::string Freedom_To_Move_Gene::name() const noexcept
{
    return "Freedom to Move Gene";
}

Add const to constant value

Add const to constant value


#include "mainwindow.h"
#include <QApplication>
#include <QDialog>
#include <QGridLayout>
#include <QLayout>
#include <QDebug>

#include "application.h"

int main(int argc, char *argv[])
{
	QCoreApplication::setOrganizationName("JASP");
	QCoreApplication::setOrganizationDomain("jasp-stats.org");
	QCoreApplication::setApplicationName("JASP");

	Application a(argc, argv);
	MainWindow w;

    w.show();

	if (argc > 1)
		w.open(QString(argv[1]));

    return a.exec();
}

#include "mainwindow.h"
#include <QApplication>
#include <QDialog>
#include <QGridLayout>
#include <QLayout>
#include <QDebug>

#include "application.h"

int main(int argc, char *argv[])
{
	QCoreApplication::setOrganizationName("JASP");
	QCoreApplication::setOrganizationDomain("jasp-stats.org");
	QCoreApplication::setApplicationName("JASP");

	Application a(argc, argv);
	MainWindow w;

	w.show();

	QStringList args = QApplication::arguments();

	if (args.length() > 1)
		w.open(args.at(1));

    return a.exec();
}

Fix to unicode cmd line argument handling


/*
  Copyright (c) 2014 DataStax

  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 "logger.hpp"

namespace cass {

void default_log_callback(cass_uint64_t time_ms, CassLogLevel severity,
                          CassString message, void* data) {
  // TODO(mpenick): Format time
  fprintf(stderr, "%llu [%s]: %.*s\n", time_ms, cass_log_level_string(severity),
          static_cast<int>(message.length), message.data);
}
}

/*
  Copyright (c) 2014 DataStax

  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 "logger.hpp"

namespace cass {

void default_log_callback(cass_uint64_t time_ms, CassLogLevel severity,
                          CassString message, void* data) {
  fprintf(stderr, "%u.%03u [%s]: %.*s\n",
          (unsigned int)(time_ms/1000), (unsigned int)(time_ms % 1000),
          cass_log_level_string(severity),
          static_cast<int>(message.length), message.data);
}
}

Fix to work with different definitions of cass_uint64_t


#include "PrimaryTreeIndex.h"

void PrimaryTreeIndex::buildIndex(Table & table, int column) {
    int rowno = 0;
    for(auto &currentRow : table) {
        index.emplace(currentRow[column], rowno++);
    }
}

int PrimaryTreeIndex::size() const {
    return index.size();
}

int PrimaryTreeIndex::exactMatch(const std::string& key) const {
    auto it = index.find(key);
    return it == index.end() ? -1 : it->second;
}

int PrimaryTreeIndex::bestMatch(const std::string& key) const {
    auto bounds = index.equal_range(key);
    auto lower_bound = bounds.first;
    auto upper_bound = bounds.second;

    if(lower_bound != index.end() && lower_bound->first == key) {
        return lower_bound->second;
    } else {
        std::map<std::string,int>::const_reverse_iterator rbegin(upper_bound);
        std::map<std::string,int>::const_reverse_iterator rend(index.begin());
        for(auto it = rbegin; it!=rend; it++) {
            auto idx = key.find(it->first);
            if(idx != std::string::npos) {
                return it->second;
            }
        }
    }

    return -1;
}

#include "PrimaryTreeIndex.h"

void PrimaryTreeIndex::buildIndex(Table & table, int column) {
    int rowno = 0;
    for(auto &currentRow : table) {
        index.emplace(currentRow[column], rowno++);
    }
}

int PrimaryTreeIndex::size() const {
    return index.size();
}

int PrimaryTreeIndex::exactMatch(const std::string& key) const {
    auto it = index.find(key);
    return it == index.end() ? -1 : it->second;
}

int PrimaryTreeIndex::bestMatch(const std::string& key) const {
    auto lower_bound = index.lower_bound(key);
    if(lower_bound != index.end() && lower_bound->first == key) {
        return lower_bound->second;
    } else {
        std::map<std::string,int>::const_reverse_iterator rbegin(lower_bound);
        std::map<std::string,int>::const_reverse_iterator rend(index.begin());
        for(auto it = rbegin; it!=rend; it++) {
            auto idx = key.find(it->first);
            if(idx != std::string::npos) {
                return it->second;
            }
        }
    }

    return -1;
}

Simplify bestMatch code as lower_bound = upper_bound when no exact match found


#include <iostream>
#include <memory>

#include <windows.h>

#include <chewingwrapper.hpp>

int main()
{
    SetEnvironmentVariable("CHEWING_PATH", CHEWING_PATH);
    SetEnvironmentVariable("CHEWING_USER_PATH", CHEWING_USER_PATH);

    const wchar_t EXPECT[] = { 0x6e2c, 0x8a66, 0 /* 測試 */ };

    ChewingWrapper ctx;

    ctx.handle_default('h');
    ctx.handle_default('k');
    ctx.handle_default('4');
    ctx.handle_default('g');
    ctx.handle_default('4');
    ctx.handle_enter();

    if (!ctx.has_commit()) {
        std::cerr << "has_commit shall return true" << std::endl;
        return -1;
    }

    std::unique_ptr<wchar_t> commit_string(ctx.get_commit());
    if (wcscmp(commit_string.get(), EXPECT)) {
        std::cerr << "commit_string shall return " << EXPECT << std::endl;
        return -1;
    }

    return 0;
}

#include <iostream>
#include <memory>

#include <windows.h>

#include <chewingwrapper.hpp>

int main()
{
    // XXX: Use SetEnvironmentVariableA here will cause crash in Visual Studio.
    _putenv("CHEWING_PATH="CHEWING_PATH);
    _putenv("CHEWING_USER_PATH="CHEWING_USER_PATH);

    const wchar_t EXPECT[] = { 0x6e2c, 0x8a66, 0 /* 測試 */ };

    ChewingWrapper ctx;

    ctx.handle_default('h');
    ctx.handle_default('k');
    ctx.handle_default('4');
    ctx.handle_default('g');
    ctx.handle_default('4');
    ctx.handle_enter();

    if (!ctx.has_commit()) {
        std::cerr << "has_commit shall return true" << std::endl;
        return -1;
    }

    std::unique_ptr<wchar_t> commit_string(ctx.get_commit());
    if (wcscmp(commit_string.get(), EXPECT)) {
        std::cerr << "commit_string shall return " << EXPECT << std::endl;
        return -1;
    }

    return 0;
}

Use _putenv instead of SetEnvironmentVariable


// Copyright (c) 2015 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.

#include "atom/common/api/event_emitter_caller.h"

#include "atom/common/api/locker.h"
#include "atom/common/node_includes.h"

namespace mate {

namespace internal {

v8::Local<v8::Value> CallMethodWithArgs(v8::Isolate* isolate,
                                        v8::Local<v8::Object> obj,
                                        const char* method,
                                        ValueVector* args) {
  // Perform microtask checkpoint after running JavaScript.
  v8::MicrotasksScope script_scope(isolate,
                                   v8::MicrotasksScope::kRunMicrotasks);
  // Use node::MakeCallback to call the callback, and it will also run pending
  // tasks in Node.js.
  return node::MakeCallback(isolate, obj, method, args->size(), &args->front(),
                            {0, 0}).ToLocalChecked();
}

}  // namespace internal

}  // namespace mate

// Copyright (c) 2015 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.

#include "atom/common/api/event_emitter_caller.h"

#include "atom/common/api/locker.h"
#include "atom/common/node_includes.h"

namespace mate {

namespace internal {

v8::Local<v8::Value> CallMethodWithArgs(v8::Isolate* isolate,
                                        v8::Local<v8::Object> obj,
                                        const char* method,
                                        ValueVector* args) {
  // Perform microtask checkpoint after running JavaScript.
  v8::MicrotasksScope script_scope(isolate,
                                   v8::MicrotasksScope::kRunMicrotasks);
  // Use node::MakeCallback to call the callback, and it will also run pending
  // tasks in Node.js.
  v8::MaybeLocal<v8::Value> ret = node::MakeCallback(isolate, obj, method, args->size(), &args->front(),
                            {0, 0});
  if (ret.IsEmpty()) {
    return v8::Boolean::New(isolate, false);
  }
  return ret.ToLocalChecked();
}

}  // namespace internal

}  // namespace mate

Fix crash when emitting unhandled error on native EventEmitter


// RUN: %clang_cc1 -std=c++17 -emit-llvm -fchar8_t -triple x86_64-linux %s -o - | FileCheck %s

// CHECK: define void @_Z1fDu(
void f(char8_t c) {}

// CHECK: define void @_Z1gIiEvDTplplcvT__ELA4_KDuELDu114EE
template<typename T> void g(decltype(T() + u8"foo" + u8'r')) {}
template void g<int>(const char8_t*);

// RUN: %clang_cc1 -std=c++17 -emit-llvm -fchar8_t -triple x86_64-linux %s -o - | FileCheck %s

// CHECK: define void @_Z1fDu(
void f(char8_t c) {}

// CHECK: define weak_odr void @_Z1gIiEvDTplplcvT__ELA4_KDuELDu114EE
template<typename T> void g(decltype(T() + u8"foo" + u8'r')) {}
template void g<int>(const char8_t*);

Fix up r331244 - the emitted definition is weak_odr linkage. Should get
the build bots to healthy again without a full revert. As the
functionality added has nothing to do with linkage this seems unlikely
to represent a deep or interesting bug in the patch.

git-svn-id: ffe668792ed300d6c2daa1f6eba2e0aa28d7ec6c@331245 91177308-0d34-0410-b5e6-96231b3b80d8


#include <util/maker.hpp>
#include <iostream>
#include <iomanip>

void show_help() noexcept {
    std::cout << "usage: shinobi [options]\n\n";
    std::cout << std::left << '\t' << std::setw(25) << "-h, --help" << "show this message and exit" << '\n';
    std::cout << std::left << '\t' << std::setw(25) << "-d, --debug" << "create debug ninja file" << '\n';
    std::cout << std::left << '\t' << std::setw(25) << "-r, --release" << "create release ninja file (default)" << '\n';
}

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

    std::ofstream out("build.ninja");
    util::maker creator{out};

    std::set<std::string> args{argv, argv + argc};

    if(args.count("-h") || args.count("--help")) {
        show_help();
        return 0;
    }

    if(args.count("-d") || args.count("--debug")) {
        creator.debug(true);
    }

    if(args.count("-r") || args.count("--release")) {
        creator.debug(false);
    }

    creator.regular_parse();
}

#include <util/maker.hpp>
#include <iostream>
#include <iomanip>
#include <map>

void show_help() noexcept {
    std::cout << "usage: shinobi [options] [--] [filename]\n\n";
    std::cout << std::left << '\t' << std::setw(25) << "-h, --help" << "show this message and exit" << '\n';
    std::cout << std::left << '\t' << std::setw(25) << "-d, --debug" << "create debug ninja file" << '\n';
    std::cout << std::left << '\t' << std::setw(25) << "-r, --release" << "create release ninja file (default)" << '\n';
}

int main(int argc, char* argv[]) {
    std::string filename("build.ninja");
    std::map<std::string, int> args;
    for(int i = 0; i < argc; ++i) {
        args.emplace(argv[i], i);
    }

    if(args.count("-h") || args.count("--help")) {
        show_help();
        return 0;
    }

    auto it = args.find("--");

    if(it != args.end()) {
        if(argv[it->second + 1] != nullptr) {
            filename = std::string(argv[it->second + 1]) + ".ninja";
        }
    }

    std::ofstream out(filename);
    util::maker creator{out};

    if(args.count("-d") || args.count("--debug")) {
        creator.debug(true);
    }

    if(args.count("-r") || args.count("--release")) {
        creator.debug(false);
    }

    creator.regular_parse();
}

Add support for custom filenames with the command line


#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

So it will grow stronger with the more energy it absorbs.


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

BUG=
TEST=

Review URL: http://codereview.chromium.org/8569018

TBR=dgarrett@chromium.org
Review URL: http://codereview.chromium.org/8742002

git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@112104 0039d316-1c4b-4281-b951-d872f2087c98


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

Note: the ":" goes into the regex because FileCheck wrongly complains about
unbalanced brackets otherwise.

git-svn-id: ffe668792ed300d6c2daa1f6eba2e0aa28d7ec6c@168934 91177308-0d34-0410-b5e6-96231b3b80d8


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

git-svn-id: 3ad904ec35b89a071badd9cb0113dfe58093e920@1363 726aef4b-f618-498e-8847-2d620e286838


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

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.

Similar to previous fix, this augments the test inferior to
immediately indicate it may be ptraced by any Linux process
when the appropriate symbols are defined.

This seems to indicate we need to fix our lldb attach logic to
catch when an attach fails, and trigger an appropriate error
instead of the current behavior of hanging indefinitely.

git-svn-id: 4c4cc70b1ef44ba2b7963015e681894188cea27e@220654 91177308-0d34-0410-b5e6-96231b3b80d8


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

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

demos: Fix compiler warning in smoketest

Replaced snprintf with stringstream.


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

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;
}

broken_link_checker: 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

Fix incorrect use of IOBuf::reserve

Differential Revision: D2037078

fb-gh-sync-id: d8bc304506ea70bfde3a3490f1aac23bc4392efa
shipit-source-id: d8bc304506ea70bfde3a3490f1aac23bc4392efa


#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

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;
}

[libc++] Mark iostreams test as XFAIL on older macOSes

git-svn-id: 756ef344af921d95d562d9e9f9389127a89a6314@372620 91177308-0d34-0410-b5e6-96231b3b80d8


#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

We use the main executable's ProductName and FileVersion resources to build the
user agent string.


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

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.

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.

Fix passing of server to subsystem.

modified:
  opencog/guile/SchemeAdHoc.cc


#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

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.

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()

MUC: 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

Add a basic memory grow test

Signed-off-by: Robert Young <42c59959a3f4413d6a1b4d7b4f99db457d199e49@gmail.com>


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

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

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"
    };
}

main: 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

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,

Remove unused variable in file finder,