//===- AArch64MachineLegalizer.cpp -------------------------------*- C++ -*-==//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
/// \file
/// This file implements the targeting of the Machinelegalizer class for
/// AArch64.
/// \todo This should be generated by TableGen.
//===----------------------------------------------------------------------===//

#include "AArch64MachineLegalizer.h"
#include "llvm/CodeGen/ValueTypes.h"
#include "llvm/IR/Type.h"
#include "llvm/IR/DerivedTypes.h"
#include "llvm/Target/TargetOpcodes.h"

using namespace llvm;

#ifndef LLVM_BUILD_GLOBAL_ISEL
#error "You shouldn't build this"
#endif

AArch64MachineLegalizer::AArch64MachineLegalizer() {
  setAction(TargetOpcode::G_ADD, LLT::vector(2, 64), Legal);
  computeTables();
}

//===- AArch64MachineLegalizer.cpp -------------------------------*- C++ -*-==//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
/// \file
/// This file implements the targeting of the Machinelegalizer class for
/// AArch64.
/// \todo This should be generated by TableGen.
//===----------------------------------------------------------------------===//

#include "AArch64MachineLegalizer.h"
#include "llvm/CodeGen/ValueTypes.h"
#include "llvm/IR/Type.h"
#include "llvm/IR/DerivedTypes.h"
#include "llvm/Target/TargetOpcodes.h"

using namespace llvm;

#ifndef LLVM_BUILD_GLOBAL_ISEL
#error "You shouldn't build this"
#endif

AArch64MachineLegalizer::AArch64MachineLegalizer() {
  using namespace TargetOpcode;
  const LLT s32 = LLT::scalar(32);
  const LLT s64 = LLT::scalar(64);
  const LLT v2s32 = LLT::vector(2, 32);
  const LLT v4s32 = LLT::vector(4, 32);
  const LLT v2s64 = LLT::vector(2, 64);

  for (auto BinOp : {G_ADD, G_SUB, G_AND, G_OR, G_XOR})
    for (auto Ty : {s32, s64, v2s32, v4s32, v2s64})
      setAction(BinOp, Ty, Legal);

  for (auto MemOp : {G_LOAD, G_STORE})
    for (auto Ty : {s32, s64})
      setAction(MemOp, Ty, Legal);

  setAction(G_BR, LLT::unsized(), Legal);

  computeTables();
}

Mark basic binops/memops as legal.


#include <memory>
#include "PPMLoader.hpp"

std::shared_ptr<Image> PPMLoader::load(const char *pathToImage) {
	FILE *file = fopen(pathToImage, "r");

	char magicNumber[8];
	fscanf(file, "%s\n", magicNumber);

	int width, height;
	fscanf(file, "%d %d\n", &width, &height);

	int maxValue;
	fscanf(file, "%d\n", &maxValue);

	auto image = std::make_shared<Image>(width, height);

	size_t index = 0;

	while (1) {
		uint8_t r, g, b;
		int elementsRead = fscanf(file, "%d %d %d", &r, &g, &b);

		if (elementsRead < 3) {
			break;
		}
		image->setValueOnChannel1(index, normalize(r, maxValue, 255));
		image->setValueOnChannel2(index, normalize(g, maxValue, 255));
		image->setValueOnChannel3(index, normalize(b, maxValue, 255));
		index++;
	}
	image->colorSpace = ColorSpaceRGB;
	return image;
}

size_t PPMLoader::normalize(size_t colorValue, int originalMaxValue, int normalizedMaxValue) {
	return (size_t) ((colorValue / (float) originalMaxValue) * normalizedMaxValue);
}

#include <memory>
#include "PPMLoader.hpp"

std::shared_ptr<Image> PPMLoader::load(const char *pathToImage) {
	FILE *file = fopen(pathToImage, "r");

	char magicNumber[8];
	fscanf(file, "%s\n", magicNumber);

	int width, height;
	fscanf(file, "%d %d\n", &width, &height);

	int maxValue;
	fscanf(file, "%d\n", &maxValue);

	auto image = std::make_shared<Image>(width, height);

	size_t index = 0;

	while (1) {
		size_t r, g, b;
		int elementsRead = fscanf(file, "%d %d %d", &r, &g, &b);

		if (elementsRead < 3) {
			break;
		}
		image->setValueOnChannel1(index, normalize(r, maxValue, 255));
		image->setValueOnChannel2(index, normalize(g, maxValue, 255));
		image->setValueOnChannel3(index, normalize(b, maxValue, 255));
		index++;
	}
	image->colorSpace = ColorSpaceRGB;
	return image;
}

size_t PPMLoader::normalize(size_t colorValue, int originalMaxValue, int normalizedMaxValue) {
	return (size_t) ((colorValue / (float) originalMaxValue) * normalizedMaxValue);
}

Replace int_8 with size_t to fix conversion bug


// Includes.
#include "UI/mainwindow.h"
#include "App/App.h"

#include "App/Factories/AdditionNFDelegate.h"
#include "App/Factories/ConstantNFDelegate.h"
#include "App/Factories/PrinterNFDelegate.h"
#include "App/Factories/TextFileNFDelegate.h"

#include "System/QtBasedFileSystem.h"

// Qt.
#include <QApplication>

QString titleString()
{
    QString name = QString::fromStdString(App::appName());
    QString version = QString::fromStdString(App::appVersion());
    return QString("%1 - v%2").arg(name).arg(version);
}

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

    QtBasedFileSystem file_system;

    App app(&file_system);
    app.addNodeFactory(new AdditionNFDelegate);
    app.addNodeFactory(new ConstantNFDelegate);
    app.addNodeFactory(new PrinterNFDelegate);
    app.addNodeFactory(new TextFileNFDelegate);

    MainWindow w(&app);
    w.setWindowTitle(titleString());
    w.setMinimumSize(800, 600);
    w.show();

    app.setUI(&w);
    app.setDelegate(&w);

    return a.exec();
}

// Includes.
#include "UI/mainwindow.h"
#include "App/App.h"

#include "App/Factories/AdditionNFDelegate.h"
#include "App/Factories/ConstantNFDelegate.h"
#include "App/Factories/PrinterNFDelegate.h"
#include "App/Factories/TextFileNFDelegate.h"

#include "System/QtBasedFileSystem.h"

// Qt.
#include <QApplication>

QString titleString()
{
    QString name = QString::fromStdString(App::appName());
    QString version = QString::fromStdString(App::appVersion());
    return QString("%1 - v%2").arg(name).arg(version);
}

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

    QtBasedFileSystem file_system;

    App app(&file_system);
    app.addNodeFactory(new AdditionNFDelegate);
    app.addNodeFactory(new ConstantNFDelegate);
    app.addNodeFactory(new PrinterNFDelegate);
    app.addNodeFactory(new TextFileNFDelegate);
    app.loadScriptNodes("Nodin/NodeScripts/Lua");

    MainWindow w(&app);
    w.setWindowTitle(titleString());
    w.setMinimumSize(800, 600);
    w.show();

    app.setUI(&w);
    app.setDelegate(&w);

    return a.exec();
}

Use function to load all script files in script directory.


#include <QApplication>
#include <QtDeclarative>
#include <QDeclarativeView>
#include <QDeclarativeContext>

#include "settingspersistor.h"

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

    QSettings settings("qmltweeter.conf", QSettings::IniFormat);
    settings.sync();

    QDeclarativeView view;
    QDeclarativeContext *context = view.rootContext();

    SettingsPersistor settingsPersistor(context, &settings);
    context->setContextProperty("settings", &settingsPersistor);

    QString searchTerm = settings.value("searchTerm", QString("meego")).toString();
    context->setContextProperty("searchTerm", QVariant::fromValue(searchTerm));

    view.setSource(QUrl("qrc:///qml/qmltweeter.qml"));

    QObject *rootObject = dynamic_cast<QObject*>(view.rootObject());
    QObject::connect(&settingsPersistor, SIGNAL(settingsSaved(QVariant)), rootObject, SLOT(settingsSaved(QVariant)));

    view.show();

    return app.exec();
}

#include <QApplication>
#include <QtDeclarative>
#include <QDeclarativeView>
#include <QDeclarativeContext>

#include "settingspersistor.h"

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

    QSettings settings("qmltweeter.conf", QSettings::IniFormat);
    settings.sync();

    QDeclarativeView view;
    QDeclarativeContext *context = view.rootContext();

    SettingsPersistor settingsPersistor(context, &settings);
    context->setContextProperty("settings", &settingsPersistor);

    QString searchTerm = settings.value("searchTerm", QString("meego")).toString();
    context->setContextProperty("searchTerm", QVariant::fromValue(searchTerm));

    view.setSource(QUrl("qrc:///qml/qmltweeter.qml"));

    QObject *rootObject = view.rootObject();
    QObject::connect(&settingsPersistor, SIGNAL(settingsSaved(QVariant)), rootObject, SLOT(settingsSaved(QVariant)));

    view.show();

    return app.exec();
}

Remove unnecessary dynamic_cast to base class


// request symbols
#include "cling/Interpreter/Interpreter.h"
#include "cling/Interpreter/CValuePrinter.h"
#include "cling/Interpreter/DynamicExprInfo.h"
#include "cling/Interpreter/InterpreterCallbacks.h"
#include "cling/Interpreter/LookupHelper.h"
#include "cling/Interpreter/ValuePrinter.h"
#include "cling/Interpreter/ValuePrinterInfo.h"
#include "cling/UserInterface/UserInterface.h"

#include "clang/AST/Type.h"

#include "llvm/Support/raw_ostream.h"

namespace cling {
void libcling__symbol_requester() {
   const char* const argv[] = {"libcling__symbol_requester", 0};
   cling::Interpreter I(1, argv);
   cling::UserInterface U(I);
   cling::ValuePrinterInfo VPI(0, 0); // asserts, but we don't call.
   printValuePublicDefault(llvm::outs(), 0, VPI);
   cling_PrintValue(0, 0, 0);
   flushOStream(llvm::outs());
   LookupHelper h(0);
   h.findType("");
   h.findScope("");
   h.findFunctionProto(0, "", "");
   h.findFunctionArgs(0, "", "");
   cling::runtime::internal::DynamicExprInfo DEI(0,0,false);
   DEI.getExpr();
   cling::InterpreterCallbacks cb(0);
}

}

// request symbols
#include "cling/Interpreter/Interpreter.h"
#include "cling/Interpreter/CValuePrinter.h"
#include "cling/Interpreter/DynamicExprInfo.h"
#include "cling/Interpreter/InterpreterCallbacks.h"
#include "cling/Interpreter/LookupHelper.h"
#include "cling/Interpreter/ValuePrinter.h"
#include "cling/Interpreter/ValuePrinterInfo.h"
#include "cling/UserInterface/UserInterface.h"

#include "clang/AST/Type.h"

#include "llvm/Support/raw_ostream.h"

namespace cling {
namespace internal {
void libcling__symbol_requester() {
   const char* const argv[] = {"libcling__symbol_requester", 0};
   cling::Interpreter I(1, argv);
   cling::UserInterface U(I);
   cling::ValuePrinterInfo VPI(0, 0); // asserts, but we don't call.
   printValuePublicDefault(llvm::outs(), 0, VPI);
   cling_PrintValue(0, 0, 0);
   flushOStream(llvm::outs());
   LookupHelper h(0);
   h.findType("");
   h.findScope("");
   h.findFunctionProto(0, "", "");
   h.findFunctionArgs(0, "", "");
   cling::runtime::internal::DynamicExprInfo DEI(0,0,false);
   DEI.getExpr();
   cling::InterpreterCallbacks cb(0);
}
}
}

Put the symbol requester func into the proper namespace!


/*
 * Copyright (c) , Arm Limited and affiliates.
 * SPDX-License-Identifier: Apache-2.0
 *
 * 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 "platform/mbed_assert.h"
#include "gtest/gtest.h"
#include <stdio.h>
#include <stdbool.h>

bool mbed_assert_throw_errors = false;

extern "C" void mbed_assert_internal(const char *expr, const char *file, int line)
{
    fprintf(stderr, "mbed assertation failed: %s, file: %s, line %d \n", expr, file, line);
    if (mbed_assert_throw_errors) {
        throw 1;
    }

    /* Ensure we fail the unit test if the Mbed assertion fails. Without this,
     * we might not notice the assertion failure as it wouldn't be bubbled up
     * to googletest. Note that this is after the above throw, as some tests
     * check that an exception is thrown (i.e. negative tests). */
    FAIL();
}

/*
 * Copyright (c) , Arm Limited and affiliates.
 * SPDX-License-Identifier: Apache-2.0
 *
 * 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 "platform/mbed_assert.h"
#include "gtest/gtest.h"
#include <stdio.h>
#include <stdbool.h>

bool mbed_assert_throw_errors = false;

extern "C" void mbed_assert_internal(const char *expr, const char *file, int line)
{
    fprintf(stderr, "mbed assertation failed: %s, file: %s, line %d \n", expr, file, line);
    if (mbed_assert_throw_errors) {
#ifdef __EXCEPTIONS
        throw 1;
#else
        FAIL();
#endif
    }

    /* Ensure we fail the unit test if the Mbed assertion fails. Without this,
     * we might not notice the assertion failure as it wouldn't be bubbled up
     * to googletest. Note that this is after the above throw, as some tests
     * check that an exception is thrown (i.e. negative tests). */
    FAIL();
}

Allow unit tests to be compiled with -fno-exception


/*
 * dis.cpp
 *
 *  Created on: Sep 20, 2015
 *      Author: anon
 */

#include "arm/ARMDisassembler.h"

#include <memory>
#include <string>
#include <cstdint>
#include <iostream>

using namespace std;
using namespace Disassembler;

int main(int argc, char **argv) {
    if (argc < 2) {
        cerr << "Usage: ./%s [thumb|arm] <hex_opcode>" << endl;
        return -1;
    }

    string arg_mode { argv[1] };
    string arg_opcode { argv[2] };

    ARMMode mode = (arg_mode == "thumb") ? ARMMode_Thumb : ARMMode_ARM;
    uint32_t opcode = std::stoul(arg_opcode, nullptr, 16);

    ARMDisassembler dis;
    shared_ptr<ARMInstruction> ins = dis.disassemble(opcode, mode);
    cout << "Disassembled instruction: " << (void *) opcode << " -> " << ins->toString() << endl;

    return 0;
}

/*
 * dis.cpp
 *
 *  Created on: Sep 20, 2015
 *      Author: anon
 */

#include "arm/ARMDisassembler.h"

#include <memory>
#include <string>
#include <cstdint>
#include <iostream>

using namespace std;
using namespace Disassembler;

int main(int argc, char **argv) {
    if (argc < 2) {
        cerr << "Usage: ./%s [thumb|arm] <hex_opcode>" << endl;
        return -1;
    }

    string arg_mode { argv[1] };
    string arg_opcode { argv[2] };

    uint32_t opcode = std::stoul(arg_opcode, nullptr, 16);

    ARMMode mode;
    if (arg_mode == "thumb") {
        mode = ARMMode_Thumb;
        cout << "Using mode THUMB" << endl;

        if (opcode > 0xffff) {
            opcode = (opcode >> 16) | ((opcode << 16) & 0xffffffff);
        }
    } else {
        mode = ARMMode_ARM;
        cout << "Using mode THUMB" << endl;
    }

    ARMDisassembler dis { ARMv7All };
    shared_ptr<ARMInstruction> ins = dis.disassemble(opcode, mode);
    cout << "Disassembled instruction: " << (void *) opcode << " -> " << ins->toString() << endl;

    return 0;
}

Make sure we invert the thumb2 opcodes.


#include "util/testing.h"

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

namespace cert_trans {
namespace test {

void InitTesting(const char* name, int* argc, char*** argv,
                 bool remove_flags) {
  // Change the defaults. Can be overridden on command line.
  // Log to stderr instead of log files.
  FLAGS_logtostderr = true;
  // Only log fatal messages by default.
  FLAGS_minloglevel = 3;
  ::testing::InitGoogleTest(argc, *argv);
  google::ParseCommandLineFlags(argc, argv, remove_flags);
  google::InitGoogleLogging(name);
}

}  // namespace test
}  // namespace cert_trans

#include "util/testing.h"

#include <event2/thread.h>
#include <gflags/gflags.h>
#include <glog/logging.h>
#include <gtest/gtest.h>

namespace cert_trans {
namespace test {

void InitTesting(const char* name, int* argc, char*** argv,
                 bool remove_flags) {
  // Change the defaults. Can be overridden on command line.
  // Log to stderr instead of log files.
  FLAGS_logtostderr = true;
  // Only log fatal messages by default.
  FLAGS_minloglevel = 3;
  ::testing::InitGoogleTest(argc, *argv);
  google::ParseCommandLineFlags(argc, argv, remove_flags);
  google::InitGoogleLogging(name);
  evthread_use_pthreads();
}

}  // namespace test
}  // namespace cert_trans

Call evthread_use_pthreads() in all tests.


// REQUIRES: static-analyzer
// RUN: clang-tidy %s -checks='-*,clang-analyzer-*' -- | FileCheck %s
extern void *malloc(unsigned long);
extern void free(void *);

void f() {
  int *p = new int(42);
  delete p;
  delete p;
  // CHECK: warning: Attempt to free released memory [clang-analyzer-cplusplus.NewDelete]
}

void g() {
  void *q = malloc(132);
  free(q);
  free(q);
  // CHECK: warning: Attempt to free released memory [clang-analyzer-unix.Malloc]
}

// REQUIRES: static-analyzer
// RUN: clang-tidy %s -checks='-*,clang-analyzer-*' -- | FileCheck %s
extern void *malloc(unsigned long);
extern void free(void *);

void f() {
  int *p = new int(42);
  delete p;
  delete p;
  // CHECK: warning: Attempt to delete released memory [clang-analyzer-cplusplus.NewDelete]
}

void g() {
  void *q = malloc(132);
  free(q);
  free(q);
  // CHECK: warning: Attempt to free released memory [clang-analyzer-unix.Malloc]
}

Fix a lit test failure after MallocChecker changes


#include "arithmetics.hpp"

namespace arithmetics
{
	int add(int a, int b)
	{
		return a + b;
	}

	int add_buggy(int a, int b)
	{
		return a + b + 1;
	}
}

#include "arithmetics.hpp"

namespace arithmetics
{
	int add(int a, int b)
	{
		return a + b;
	}

	int add_buggy(int a, int b)
	{
		return a + b;
	}
}

Fix bug to see Travis succeed


#include <numeric>
#include <vector>

#include SPECIFIC_HEADER

int main(int /*argc*/, char** /*argv*/)
{
  constexpr unsigned num_entries = 1e7;
  std::vector<int> in(num_entries);
  std::iota(std::begin(in), std::end(in), 0);
  auto out = product_except(in);

  bool success = out[1] == 0;
  return !success;
}

#include <numeric>
#include <vector>

#include SPECIFIC_HEADER

int main(int /*argc*/, char** /*argv*/)
{
  constexpr unsigned num_entries = 10000000;
  std::vector<int> in(num_entries);
  std::iota(std::begin(in), std::end(in), 0);
  auto out = product_except(in);

  bool success = out[1] == 0;
  return !success;
}

Fix double to unsigned error


#include <iostream>
#include <algorithm>
#include "io/PGMIO.hpp"
#include "matrix/Matrix.hpp"

using namespace sipl;

int main(int argc, char** argv)
{
    if (argc < 2) {
        std::cout << "Usage:" << std::endl;
        std::cout << "    " << argv[0] << " file.pgm" << std::endl;
        std::exit(1);
    }

    // const std::string filename{argv[1]};
    PGMIO pgm;
    auto mat = pgm.read<uint8_t>("tmp_ascii.pgm");
    // pgm.write(mat, "tmp_binary.pgm", PGMIO::PType::BINARY);
    pgm.write(mat, "tmp_ascii2.pgm", PGMIO::PType::ASCII);
}

#include <iostream>
#include <algorithm>
#include "io/PgmIO.hpp"
#include "matrix/Matrix.hpp"

using namespace sipl;

int main(int argc, char** argv)
{
    if (argc < 3) {
        std::cout << "Usage:" << std::endl;
        std::cout << "    " << argv[0] << " infile.pgm outfile.pgm"
                  << std::endl;
        std::exit(1);
    }

    // const std::string filename{argv[1]};
    PgmIO pgm;
    auto mat = pgm.read(argv[1]);
    pgm.write(mat, argv[2], PGMIO::PType::BINARY);
    // pgm.write(mat, argv[2], PGMIO::PType::ASCII);
}

Update for removal of type-specifier from reader


#include <iostream>
#include <fstream>
#include <memory>

#include "..\..\shared\ProblemEngine.h"

int FindSingleElement(const std::shared_ptr<int>& inputArray, int size);

int main(int argc, char * argv[])
{
	ProblemEngine engine("input.txt");
	if (!engine.IsFileOk())
	{
		std::cout << "Unable to open input.txt" << std::endl;
		return 1;
	}

	auto testCases = engine.LoadTestCases();

	for (const auto& testCase : testCases)
	{
		if (testCase.Size % 2 == 0) //only odd inputs accepted
			continue;

		auto singleElement = FindSingleElement(testCase.Data, testCase.Size);

		std::cout << singleElement << std::endl;
	}

	return 0;
}

int FindSingleElement(const std::shared_ptr<int>& inputArray, int size)
{
	return 0;
}

#include <iostream>
#include <fstream>
#include <memory>

#include "..\..\shared\ProblemEngine.h"

int FindSingleElement(const std::shared_ptr<int>& inputArray, int size);

int main(int argc, char * argv[])
{
	ProblemEngine engine("input.txt");
	if (!engine.IsFileOk())
	{
		std::cout << "Unable to open input.txt" << std::endl;
		return 1;
	}

	auto testCases = engine.LoadTestCases();

	for (const auto& testCase : testCases)
	{
		if (testCase.Size % 2 == 0) //only odd inputs accepted
			continue;

		auto singleElement = FindSingleElement(testCase.Data, testCase.Size);

		std::cout << singleElement << std::endl;
	}

	return 0;
}

int FindSingleElement(const std::shared_ptr<int>& inputArray, int size)
{
	const int INT_SIZE_IN_BITS = 32;

	//this method only works if there are 'n' occurrences of each element other than the single element
	//in the case of this test data, there are two occurrences of every other element since the problem states pairs of people
	const int EXPECTED_ELEMENT_OCCURRENCES = 2;

	int result = 0;
	auto ptr = inputArray.get();

	for (int bit = 0; bit < INT_SIZE_IN_BITS; ++bit)
	{
		int sum = 0;
		int bitMask = 1 << bit;

		for (int i = 0; i < size; ++i)
			if (ptr[i] & bitMask)
				sum++;

		if (sum % EXPECTED_ELEMENT_OCCURRENCES != 0)
			result |= bitMask;
	}

	return result;
}

Implement method for finding single element by counting occurrences of each bit across all elements in the input array


#include <Eigen/Core>
#include "./test.h"
#include "../src/labelling/labels.h"
#include "../src/labelling/label.h"

TEST(Test_Labels, ChangeNotification)
{
  Labels labels;

  int changedLabelId = -1;
  Labels::Action receivedAction;

  auto removeSubscription = labels.subscribe([&changedLabelId, &receivedAction](
      Labels::Action action, const Label &label)
                                             {
                                               receivedAction = action;
                                               changedLabelId = label.id;
                                             });

  labels.add(Label(1, "Label text", Eigen::Vector3f(1, 2, 3)));

  ASSERT_EQ(1, changedLabelId);
  ASSERT_EQ(Labels::Action::Add, receivedAction);

  removeSubscription();
  labels.add(Label(2, "Label text", Eigen::Vector3f(1, 2, 3)));

  ASSERT_EQ(1, changedLabelId);
}

TEST(Test_Labels, Remove)
{
  Labels labels;

  Label label(1, "Label text", Eigen::Vector3f(1, 2, 3));
  labels.add(label);

  ASSERT_EQ(1, labels.count());

  int changedLabelId = -1;
  Labels::Action receivedAction;
  auto removeSubscription = labels.subscribe([&changedLabelId, &receivedAction](
      Labels::Action action, const Label &label)
                                             {
                                               receivedAction = action;
                                               changedLabelId = label.id;
                                             });
  labels.remove(label);

  ASSERT_EQ(0, labels.count());
  ASSERT_EQ(1, changedLabelId);
  ASSERT_EQ(Labels::Action::Delete, receivedAction);
}

Add test for removing a label.


//===--------------------- cxa_thread_atexit_test.cpp ---------------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is dual licensed under the MIT and the University of Illinois Open
// Source Licenses. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//

// REQUIRES: linux

#include <assert.h>
#include <cxxabi.h>

static bool AtexitImplCalled = false;

extern "C" int __cxa_thread_atexit_impl(void (*dtor)(void *), void *obj,
                                        void *dso_symbol) {
  assert(dtor == reinterpret_cast<void (*)(void *)>(1));
  assert(obj == reinterpret_cast<void *>(2));
  assert(dso_symbol == reinterpret_cast<void *>(3));
  AtexitImplCalled = true;
  return 4;
}

int main() {
  int RV = __cxxabiv1::__cxa_thread_atexit(
      reinterpret_cast<void (*)(void *)>(1), reinterpret_cast<void *>(2),
      reinterpret_cast<void *>(3));
  assert(RV == 4);
  assert(AtexitImplCalled);
  return 0;
}

//===--------------------- cxa_thread_atexit_test.cpp ---------------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is dual licensed under the MIT and the University of Illinois Open
// Source Licenses. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//

// UNSUPPORTED: libcppabi-no-threads
// REQUIRES: linux

#include <assert.h>
#include <cxxabi.h>

static bool AtexitImplCalled = false;

extern "C" int __cxa_thread_atexit_impl(void (*dtor)(void *), void *obj,
                                        void *dso_symbol) {
  assert(dtor == reinterpret_cast<void (*)(void *)>(1));
  assert(obj == reinterpret_cast<void *>(2));
  assert(dso_symbol == reinterpret_cast<void *>(3));
  AtexitImplCalled = true;
  return 4;
}

int main() {
  int RV = __cxxabiv1::__cxa_thread_atexit(
      reinterpret_cast<void (*)(void *)>(1), reinterpret_cast<void *>(2),
      reinterpret_cast<void *>(3));
  assert(RV == 4);
  assert(AtexitImplCalled);
  return 0;
}

Mark thread exit test as unsupported w/o threads


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

#include "base/command_line.h"
#include "chrome/browser/extensions/extension_apitest.h"
#include "chrome/common/chrome_switches.h"

IN_PROC_BROWSER_TEST_F(ExtensionApiTest, WebNavigation) {
  CommandLine::ForCurrentProcess()->AppendSwitch(
      switches::kEnableExperimentalExtensionApis);

  ASSERT_TRUE(RunExtensionTest("webnavigation/api")) << message_;
}

IN_PROC_BROWSER_TEST_F(ExtensionApiTest, WebNavigationEvents1) {
  CommandLine::ForCurrentProcess()->AppendSwitch(
      switches::kEnableExperimentalExtensionApis);

  ASSERT_TRUE(RunExtensionTest("webnavigation/navigation1")) << message_;
}

IN_PROC_BROWSER_TEST_F(ExtensionApiTest, WebNavigationEvents2) {
  CommandLine::ForCurrentProcess()->AppendSwitch(
      switches::kEnableExperimentalExtensionApis);

  ASSERT_TRUE(RunExtensionTest("webnavigation/navigation2")) << message_;
}

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

#include "base/command_line.h"
#include "chrome/browser/extensions/extension_apitest.h"
#include "chrome/common/chrome_switches.h"

IN_PROC_BROWSER_TEST_F(ExtensionApiTest, WebNavigation) {
  CommandLine::ForCurrentProcess()->AppendSwitch(
      switches::kEnableExperimentalExtensionApis);

  ASSERT_TRUE(RunExtensionTest("webnavigation/api")) << message_;
}

// Disabled, flakily exceeds timeout, http://crbug.com/72165.
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, DISABLED_WebNavigationEvents1) {
  CommandLine::ForCurrentProcess()->AppendSwitch(
      switches::kEnableExperimentalExtensionApis);

  ASSERT_TRUE(RunExtensionTest("webnavigation/navigation1")) << message_;
}

IN_PROC_BROWSER_TEST_F(ExtensionApiTest, WebNavigationEvents2) {
  CommandLine::ForCurrentProcess()->AppendSwitch(
      switches::kEnableExperimentalExtensionApis);

  ASSERT_TRUE(RunExtensionTest("webnavigation/navigation2")) << message_;
}

Disable ExtensionApiTest.WebNavigationEvents1, flakily exceeds test timeout


#include "pch.h"

#include "style.h"

using namespace Windows::Foundation;

style::style()
    : fill_(paint_type::color, Colors::Black)
    , stroke_(paint_type::none, Colors::Black)
    , strokeWidth_(length{ 0, unit::unspecified })
{
}

ICanvasBrush^ style::fillBrush(ICanvasResourceCreator^ resourceCreator)
{
    return fill_.brush(resourceCreator);
}

ICanvasBrush^ style::strokeBrush(ICanvasResourceCreator^ resourceCreator)
{
    return stroke_.brush(resourceCreator);
}

float style::stroke_width()
{
    return strokeWidth_.Number; // TODO: respect the Unit!
}

inherited_style::inherited_style()
{
    style defaultStyle;
    stack_.push(defaultStyle);
}

void inherited_style::push()
{
    stack_.push(stack_.top());
}

void inherited_style::pop()
{
    stack_.pop();
    assert(!stack_.empty());
}

#include "pch.h"

#include "style.h"

using namespace Windows::Foundation;

style::style()
    : fill_(paint_type::color, Colors::Black)
    , stroke_(paint_type::none, Colors::Black)
    , strokeWidth_(length{ 1, unit::unspecified })
{
}

ICanvasBrush^ style::fillBrush(ICanvasResourceCreator^ resourceCreator)
{
    return fill_.brush(resourceCreator);
}

ICanvasBrush^ style::strokeBrush(ICanvasResourceCreator^ resourceCreator)
{
    return stroke_.brush(resourceCreator);
}

float style::stroke_width()
{
    return strokeWidth_.Number; // TODO: respect the Unit!
}

inherited_style::inherited_style()
{
    style defaultStyle;
    stack_.push(defaultStyle);
}

void inherited_style::push()
{
    stack_.push(stack_.top());
}

void inherited_style::pop()
{
    stack_.pop();
    assert(!stack_.empty());
}

Set default stroke-width to 1


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

#include <math.h>
#include <stdlib.h>

#include "util.h"

#ifdef _MSC_VER
    #include <locale.h>
#else
    #include <sstream>
#endif

double atof_dot(const char *str)
{
#ifdef _MSC_VER
    return _atof_l(str, _create_locale(LC_NUMERIC, "C"));
#else
    double result;
    std::istringstream s(str);
    std::locale l("C");
    s.imbue(l);
    s >> result;
    return result;
#endif
}

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

#include <math.h>
#include <stdlib.h>

#include "util.h"

#ifdef _MSC_VER
    #include <locale.h>
#else
    #include <sstream>
#endif

double atof_dot(const char *str)
{
#ifdef _MSC_VER
    _locale_t l = _create_locale(LC_NUMERIC, "C");
    double result = _atof_l(str, l);
    _free_locale(l);
    return result;
#else
    double result;
    std::istringstream s(str);
    std::locale l("C");
    s.imbue(l);
    s >> result;
    return result;
#endif
}

Fix memory leak in float literal parsing Issue=93


// 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 "webkit/support/gc_extension.h"

#include "v8/include/v8.h"

const char kGCExtensionName[] = "v8/GCController";

namespace extensions_v8 {

// static
v8::Extension* GCExtension::Get() {
  v8::Extension* extension = new v8::Extension(
      kGCExtensionName,
      "(function () {"
      "   var v8_gc;"
      "   if (gc) v8_gc = gc;"
      "   GCController = new Object();"
      "   GCController.collect ="
      "     function() {if (v8_gc) v8_gc(); };"
      " })();");
  return extension;
}

}  // namespace extensions_v8

// 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 "webkit/support/gc_extension.h"

#include "v8/include/v8.h"

const char kGCExtensionName[] = "v8/GCController";

namespace extensions_v8 {

// static
v8::Extension* GCExtension::Get() {
  v8::Extension* extension = new v8::Extension(
      kGCExtensionName,
      "(function () {"
      "   var v8_gc;"
      "   if (gc) v8_gc = gc;"
      "   GCController = new Object();"
      "   GCController.collect ="
      "     function() {if (v8_gc) v8_gc(); };"
      "   GCController.minorCollect ="
      "     function() {if (v8_gc) v8_gc(true); };"
      " })();");
  return extension;
}

}  // namespace extensions_v8

Add GCController.minorCollect(), which triggers one minor GC cycle


#include "HalideRuntime.h"
#include "runtime_internal.h"

extern "C" {

WEAK __attribute__((always_inline)) int halide_profiler_set_current_func(halide_profiler_state *state, int tok, int t) {
    __sync_synchronize();
    state->current_func = tok + t;
    __sync_synchronize();
    return 0;
}

}

#include "HalideRuntime.h"
#include "runtime_internal.h"

extern "C" {

WEAK __attribute__((always_inline)) int halide_profiler_set_current_func(halide_profiler_state *state, int tok, int t) {
    // Do a volatile store to discourage llvm from reordering it.
    volatile int *ptr = &(state->current_func);
    *ptr = tok + t;
    return 0;
}

}

Use a volatile store instead of a memory barrier


#include "pch.h"
#include "json_rpc_debug_logger.h"

#include <QDebug>

namespace jcon {

void JsonRpcDebugLogger::logInfo(const QString& message)
{
    qDebug().noquote() << message;
}

void JsonRpcDebugLogger::logWarning(const QString& message)
{
    qDebug().noquote() << message;
}

void JsonRpcDebugLogger::logError(const QString& message)
{
    qDebug().noquote() << message;
}

}

Remove inclusion of non-existing precompiled header


#include "reg_filter_mode_translator.h"
#include "orz/types.h"

namespace Reg {
	namespace Internal {
		boost::optional<FilterModeTranslator::external_type> FilterModeTranslator::get_value(internal_type const sval) {
			if (sval.empty()) return boost::none;
			if (sval == "Bilinear") {
				return Filter::Mode::Bilinear;
			}
			if (sval == "Nearest") {
				return Filter::Mode::NearestNeighbor;
			}
			if (sval == "Lanczos3") {
				return Filter::Mode::Lanczos3;
			}

			switch (FromAString<int>(sval)) {
			case 1:
				return Filter::Mode::NearestNeighbor;
			case 2:
				return Filter::Mode::Bilinear;
			case 3:
				return Filter::Mode::Lanczos3;
			}

			return boost::none;
		}

		boost::optional<FilterModeTranslator::internal_type> FilterModeTranslator::put_value(external_type const& val) {
			switch (val) {
			case Filter::Mode::NearestNeighbor:
				return "Nearest";
			case Filter::Mode::Bilinear:
				return "Bilinear";
			case Filter::Mode::Lanczos3:
				return "Lanczos3";
			}

			return boost::none;
		}
	}
}

#include "reg_filter_mode_translator.h"
#include "orz/types.h"

namespace Reg {
	namespace Internal {
		boost::optional<FilterModeTranslator::external_type> FilterModeTranslator::get_value(internal_type const sval) {
			if (sval.empty()) return boost::none;
			if (sval == "Bilinear") {
				return Filter::Mode::Bilinear;
			}
			if (sval == "Nearest") {
				return Filter::Mode::NearestNeighbor;
			}
			if (sval == "Lanczos3") {
				return Filter::Mode::Lanczos3;
			}

			switch (FromAString<int>(sval)) {
			case 1:
				return Filter::Mode::NearestNeighbor;
			case 2:
				return Filter::Mode::Bilinear;
			case 3:
				return Filter::Mode::Lanczos3;
			}

			return boost::none;
		}

		boost::optional<FilterModeTranslator::internal_type> FilterModeTranslator::put_value(external_type const& val) {
			switch (val) {
			case Filter::Mode::NearestNeighbor:
				return std::string("Nearest");
			case Filter::Mode::Bilinear:
				return std::string("Bilinear");
			case Filter::Mode::Lanczos3:
				return std::string("Lanczos3");
			}

			return boost::none;
		}
	}
}

Fix compile errors on Linux


#include <sdk/config.h>

#ifndef SCHEDULER_CORO_OSTHREAD
# include "Coro.c"
#endif

Include sdk/config.h before testing configuration macros.


//===- MachineDominators.cpp - Machine Dominator Calculation --------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file implements simple dominator construction algorithms for finding
// forward dominators on machine functions.
//
//===----------------------------------------------------------------------===//

#include "llvm/CodeGen/MachineDominators.h"
#include "llvm/CodeGen/Passes.h"

using namespace llvm;

TEMPLATE_INSTANTIATION(class DomTreeNodeBase<MachineBasicBlock>);
TEMPLATE_INSTANTIATION(class DominatorTreeBase<MachineBasicBlock>);

namespace {
  char MachineDominatorTree::ID = 0;
  RegisterPass<MachineDominatorTree>
  E("machinedomtree", "MachineDominator Tree Construction", true);
}

const PassInfo *llvm::MachineDominatorsID = E.getPassInfo();

//===- MachineDominators.cpp - Machine Dominator Calculation --------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file implements simple dominator construction algorithms for finding
// forward dominators on machine functions.
//
//===----------------------------------------------------------------------===//

#include "llvm/CodeGen/MachineDominators.h"
#include "llvm/CodeGen/Passes.h"

using namespace llvm;

TEMPLATE_INSTANTIATION(class DomTreeNodeBase<MachineBasicBlock>);
TEMPLATE_INSTANTIATION(class DominatorTreeBase<MachineBasicBlock>);

char MachineDominatorTree::ID = 0;

namespace {
  RegisterPass<MachineDominatorTree>
  E("machinedomtree", "MachineDominator Tree Construction", true);
}

const PassInfo *llvm::MachineDominatorsID = E.getPassInfo();

Fix build issue on certain compilers.


#include "gtest/gtest.h"
#include "braincloud/BrainCloudClient.h"
#include "TestResult.h"
#include "TestBCGlobalFile.h"
#include <vector>
using namespace BrainCloud;

static const std::string testfileName = "png1.png";
static const std::string testFileId = "34802251-0da0-419e-91b5-59d91790af15";
static const std::string testFolderPath = "/existingfolder/";

TEST_F(TestBCGlobalFile, GetFileInfo)
{
	TestResult tr;
	m_bc->getGlobalFileService()->getFileInfo(testFileId, &tr);
	tr.run(m_bc);
}

TEST_F(TestBCGlobalFile, GetFileInfoSimple)
{
	TestResult tr;
	m_bc->getGlobalFileService()->getFileInfoSimple(testFolderPath, testfileName, &tr);
	tr.run(m_bc);
}

TEST_F(TestBCGlobalFile, GetGlobalCDNUrl)
{
	TestResult tr;
	m_bc->getGlobalFileService()->getGlobalCDNUrl(testFileId, &tr);
	tr.run(m_bc);
}

TEST_F(TestBCGlobalFile, GetGlobalFileList)
{
	TestResult tr;
	m_bc->getGlobalFileService()->getGlobalFileList(testFolderPath, true, &tr);
	tr.run(m_bc);
}

#include "gtest/gtest.h"
#include "braincloud/BrainCloudClient.h"
#include "TestResult.h"
#include "TestBCGlobalFile.h"
#include <vector>
using namespace BrainCloud;

static const std::string testfileName = "testGlobalFile.png";
static const std::string testFileId = "ed2d2924-4650-4a88-b095-94b75ce9aa18";
static const std::string testFolderPath = "/fname/";

TEST_F(TestBCGlobalFile, GetFileInfo)
{
	TestResult tr;
	m_bc->getGlobalFileService()->getFileInfo(testFileId, &tr);
	tr.run(m_bc);
}

TEST_F(TestBCGlobalFile, GetFileInfoSimple)
{
	TestResult tr;
	m_bc->getGlobalFileService()->getFileInfoSimple(testFolderPath, testfileName, &tr);
	tr.run(m_bc);
}

TEST_F(TestBCGlobalFile, GetGlobalCDNUrl)
{
	TestResult tr;
	m_bc->getGlobalFileService()->getGlobalCDNUrl(testFileId, &tr);
	tr.run(m_bc);
}

TEST_F(TestBCGlobalFile, GetGlobalFileList)
{
	TestResult tr;
	m_bc->getGlobalFileService()->getGlobalFileList(testFolderPath, true, &tr);
	tr.run(m_bc);
}

Revert updating file/folder parameter for Global File unit tests


#include "JNIRhodes.h"

#include "gapikey.h"

#include <common/rhoparams.h>

#undef DEFAULT_LOGCATEGORY
#define DEFAULT_LOGCATEGORY "MapView"

RHO_GLOBAL void mapview_create(rho_param *p)
{
#ifdef GOOGLE_API_KEY
    jclass clsMapView = getJNIClass(RHODES_JAVA_CLASS_MAPVIEW);
    if (!clsMapView) return;
    jmethodID midCreate = getJNIClassStaticMethod(clsMapView, "create", "(Ljava/lang/String;Ljava/util/Map;)V");
    if (!midCreate) return;

    if (p->type != RHO_PARAM_HASH) {
        RAWLOG_ERROR("create: wrong input parameter (expect Hash)");
        return;
    }

    JNIEnv *env = jnienv();
    jobject paramsObj = RhoValueConverter(env).createObject(p);
    env->CallStaticVoidMethod(clsMapView, midCreate, env->NewStringUTF(GOOGLE_API_KEY), paramsObj);
#else
    RHO_NOT_IMPLEMENTED;
#endif
}

#include "JNIRhodes.h"

#include "gapikey.h"

#include <common/rhoparams.h>

#undef DEFAULT_LOGCATEGORY
#define DEFAULT_LOGCATEGORY "MapView"

extern "C" void alert_show_popup(char *);

RHO_GLOBAL void mapview_create(rho_param *p)
{
#ifdef GOOGLE_API_KEY
    jclass clsMapView = getJNIClass(RHODES_JAVA_CLASS_MAPVIEW);
    if (!clsMapView) return;
    jmethodID midCreate = getJNIClassStaticMethod(clsMapView, "create", "(Ljava/lang/String;Ljava/util/Map;)V");
    if (!midCreate) return;

    if (p->type != RHO_PARAM_HASH) {
        RAWLOG_ERROR("create: wrong input parameter (expect Hash)");
        return;
    }

    JNIEnv *env = jnienv();
    jobject paramsObj = RhoValueConverter(env).createObject(p);
    env->CallStaticVoidMethod(clsMapView, midCreate, env->NewStringUTF(GOOGLE_API_KEY), paramsObj);
#else
    alert_show_popup("Google API key problem");
#endif
}

Add alert when Google API key was not specified


#include "DotGraphOutput.hh"
#include "EdgeType.hh"

string getEdgeStyle(EdgeType t) {
  switch (t) {
  case EdgeType::Plane:
    return "[color=red]";
  case EdgeType::Train:
    return "[color=blue,style=dotted]";
  default:
    return "";
  }
}

template <typename V>
void DotGraphOutput<V>::output(string path) {

  cout << "Exporting " << this->graph_.name() << " to " << path << endl;

  ofstream st(path, ofstream::out);

  st << "digraph " << this->graph_.name() << " {" << endl;

  for (unsigned int i = 0; i < this->graph_.verticesNb(); i++)
    for (auto e : this->graph_.outgoingEdges(i)) {
      st << "\t" << this->graph_.getVertex(i).name()
	 << " -> " << this->graph_.getVertex(e->getOtherEnd(i)).name()
	 << " " << getEdgeStyle(e->type())
	 << ";" << endl;
    }

  st << "}" << endl;

  st.close();
}

template class DotGraphOutput<double>;

#include "DotGraphOutput.hh"
#include "EdgeType.hh"

#include <sstream>

template <typename V>
string getEdgeStyle(EdgeType t, V val) {

  stringstream ss;
  string end("\"]");

  switch (t) {
  case EdgeType::Plane:
    ss << string("[color=red, label=\"") << val << end;
    break;
  case EdgeType::Train:
    ss << string("[color=blue, style=dotted, label=\"") << val << end ;
    break;
  default:
    ss << string("[label=\"") << val << end;
    break;
  }
  return ss.str();
}

template <typename V>
void DotGraphOutput<V>::output(string path) {

  cout << "Exporting " << this->graph_.name() << " to " << path << endl;

  ofstream st(path, ofstream::out);

  st << "digraph " << this->graph_.name() << " {" << endl;

  for (unsigned int i = 0; i < this->graph_.verticesNb(); i++)
    st << "\t" << i << " [label=\"" << this->graph_.getVertex(i).name() << "\"];" << endl;

  for (unsigned int i = 0; i < this->graph_.verticesNb(); i++)
    for (auto e : this->graph_.outgoingEdges(i)) {
      st << "\t" << i
	 << " -> " << e->getOtherEnd(i)
	 << " " << getEdgeStyle(e->type(), e->distance())
	 << ";" << endl;
    }

  st << "}" << endl;

  st.close();
}

template class DotGraphOutput<double>;

Add edges values and proper labels to node in Dot output


#ifdef LEGACY_LINUX

// Wrappers for eventfd(), since CentOS backported the system
// calls but not the libc wrappers.

#include "arch/linux/system_event/eventfd.hpp"
#include "utils.hpp"
#include <sys/syscall.h>

int eventfd(int count, int flags) {
    rassert(flags == 0); // Legacy kernel doesn't have eventfd2.
    return syscall(SYS_eventfd, count);
}

int eventfd_read(int fd, eventfd_t *value) {
    int res = read(fd, value, sizeof(eventfd_t));
    return (res == sizeof(eventfd_t)) ? 0 : -1;
}

int eventfd_write(int fd, eventfd_t value) {
  int res = write(fd, &value, sizeof(eventfd_t));
  return (res == sizeof(eventfd_t)) ? 0 : -1;
}

#endif

#ifdef LEGACY_LINUX

// Wrappers for eventfd(), since CentOS backported the system
// calls but not the libc wrappers.

#include "arch/linux/system_event/eventfd.hpp"
#include "utils.hpp"
#include <sys/syscall.h>

int eventfd(int count, UNUSED int flags) {
    rassert(flags == 0); // Legacy kernel doesn't have eventfd2.
    return syscall(SYS_eventfd, count);
}

int eventfd_read(int fd, eventfd_t *value) {
    int res = read(fd, value, sizeof(eventfd_t));
    return (res == sizeof(eventfd_t)) ? 0 : -1;
}

int eventfd_write(int fd, eventfd_t value) {
  int res = write(fd, &value, sizeof(eventfd_t));
  return (res == sizeof(eventfd_t)) ? 0 : -1;
}

#endif

Fix a compiler error glitch with some bullshit.


/*
 * This file is part of the UnTech Editor Suite.
 * Copyright (c) 2016 - 2019, Marcus Rowe <undisbeliever@gmail.com>.
 * Distributed under The MIT License: https://opensource.org/licenses/MIT
 */

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

using namespace UnTech::GuiQt;

int main(int argc, char* argv[])
{
    QApplication app(argc, argv);
    app.setApplicationDisplayName("UnTech Editor GUI");
    app.setOrganizationDomain(UNTECH_DOMAIN);
    app.setApplicationVersion(UNTECH_VERSION);

    QCommandLineParser parser;
    parser.addHelpOption();
    parser.addVersionOption();
    parser.addPositionalArgument("file", "utres file", "[file]");
    parser.process(app);

    MainWindow* window = new MainWindow();
    window->show();

    const QStringList args = parser.positionalArguments();
    if (args.size() > 0) {
        window->loadProject(args.first());
    }

    return app.exec();
}

/*
 * This file is part of the UnTech Editor Suite.
 * Copyright (c) 2016 - 2019, Marcus Rowe <undisbeliever@gmail.com>.
 * Distributed under The MIT License: https://opensource.org/licenses/MIT
 */

#include "mainwindow.h"
#include "version.h"
#include <QApplication>
#include <QCommandLineParser>
#include <QSettings>

using namespace UnTech::GuiQt;

int main(int argc, char* argv[])
{
    QApplication app(argc, argv);
    app.setApplicationDisplayName("UnTech Editor GUI");
    app.setOrganizationDomain(UNTECH_DOMAIN);
    app.setApplicationVersion(UNTECH_VERSION);

#ifdef Q_OS_WIN
    // Use an ini file instead of the registry to store GUI settings.
    //
    // The `window_state` QSettings key is ~5.3KB (as of December 2019) and
    // Microsoft's documentation recommends that we do not store values > 2048 bytes in the registry.
    // https://docs.microsoft.com/en-us/windows/win32/sysinfo/registry-element-size-limits
    QSettings::setDefaultFormat(QSettings::IniFormat);
#endif

    QCommandLineParser parser;
    parser.addHelpOption();
    parser.addVersionOption();
    parser.addPositionalArgument("file", "utres file", "[file]");
    parser.process(app);

    MainWindow* window = new MainWindow();
    window->show();

    const QStringList args = parser.positionalArguments();
    if (args.size() > 0) {
        window->loadProject(args.first());
    }

    return app.exec();
}

Use an ini file to store GUI settings in windows


#include "nwg_service.h"

#include "nwg_eventloop.h"

namespace Nwg
{

Service::Service(EventLoop *eventLoop)
    : _eventLoop(eventLoop),
      _protocolCodec(nullptr),
      _handler(nullptr)
{
}

Service::~Service()
{
    _protocolCodec.reset();
    _handler.reset();
}

void Service::setBuffSize(int buffSize) { _buffSize = buffSize; }
void Service::setReadBuffSize(int readBuffSize) { _readBuffSize = readBuffSize; }

void Service::setProtocolCodec(const std::shared_ptr<ProtocolCodec> &protocolCodec)
{
    _protocolCodec = protocolCodec;
}

void Service::setHandler(const std::shared_ptr<Handler> &handler)
{
    _handler = handler;
}

EventLoop *Service::getEventLoop() const { return _eventLoop; }

size_t Service::getBuffSize() { return _buffSize; }
size_t Service::getReadBuffSize() { return _readBuffSize; }

ProtocolCodec &Service::getProtocolCodec()
{
    return *_protocolCodec;
}

Handler &Service::getHandler()
{
    return *_handler;
}

} /* namespace Nwg */

#include "nwg_service.h"

#include "nwg_eventloop.h"
#include "nwg_basicprotocolcodec.h"

namespace Nwg
{

Service::Service(EventLoop *eventLoop)
    : _eventLoop(eventLoop),
      _protocolCodec(nullptr),
      _handler(nullptr)
{
}

Service::~Service()
{
    _protocolCodec.reset();
    _handler.reset();
}

void Service::setBuffSize(int buffSize) { _buffSize = buffSize; }
void Service::setReadBuffSize(int readBuffSize) { _readBuffSize = readBuffSize; }

void Service::setProtocolCodec(const std::shared_ptr<ProtocolCodec> &protocolCodec)
{
    _protocolCodec = protocolCodec;
}

void Service::setHandler(const std::shared_ptr<Handler> &handler)
{
    _handler = handler;
}

EventLoop *Service::getEventLoop() const { return _eventLoop; }

size_t Service::getBuffSize() { return _buffSize; }
size_t Service::getReadBuffSize() { return _readBuffSize; }

ProtocolCodec &Service::getProtocolCodec()
{
    if (_protocolCodec == nullptr) {
        _protocolCodec = std::make_shared<Nwg::BasicProtocolCodec>();
    }
    return *_protocolCodec;
}

Handler &Service::getHandler()
{
    return *_handler;
}

} /* namespace Nwg */

Create BasicProtocolCodec if _protocolCodec is null


#include "PrologInterface.h"

void PrologLifetime::begin(int argc, char *argv[]) {
  if (!PL_initialise(argc, argv)) {
    PL_halt(EXIT_FAILURE);
  }
}

void PrologLifetime::end() {
  PL_halt(EXIT_SUCCESS);
}

#include "PrologInterface.h"

void PrologLifetime::begin(int argc, char *argv[]) {
  if (!PL_initialise(argc, argv)) {
    PL_halt(EXIT_FAILURE);
  }
}

void PrologLifetime::end() {
  PL_cleanup(EXIT_SUCCESS);
}

Use PL_cleanup instead of PL_halt


// 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/event_emitter_caller.h"

namespace mate {

namespace internal {

v8::Local<v8::Value> CallEmitWithArgs(v8::Isolate* isolate,
                                      v8::Local<v8::Object> obj,
                                      ValueVector* args) {
  v8::Local<v8::String> emit_name = StringToSymbol(isolate, "emit");
  v8::Local<v8::Value> emit = obj->Get(emit_name);
  if (emit.IsEmpty() || !emit->IsFunction()) {
    isolate->ThrowException(v8::Exception::TypeError(
        StringToV8(isolate, "\"emit\" is not a function")));
    return v8::Undefined(isolate);
  }

  v8::MaybeLocal<v8::Value> result = emit.As<v8::Function>()->Call(
      isolate->GetCurrentContext(), obj, args->size(), &args->front());
  if (result.IsEmpty()) {
    return v8::Undefined(isolate);
  }

  return result.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/event_emitter_caller.h"

#include "atom/common/node_includes.h"

namespace mate {

namespace internal {

v8::Local<v8::Value> CallEmitWithArgs(v8::Isolate* isolate,
                                      v8::Local<v8::Object> obj,
                                      ValueVector* args) {
  return node::MakeCallback(
      isolate, obj, "emit", args->size(), &args->front());
}

}  // namespace internal

}  // namespace mate

Use node::MakeCallback to emit events in C++


#include "GoogleLogFatalHandler.hpp"

#include "Headers.hpp"

namespace google {
namespace glog_internal_namespace_ {
void DumpStackTraceToString(string* stacktrace);
}
}  // namespace google

static void DumpStackTraceToFileAndExit() {
  string s;
  google::glog_internal_namespace_::DumpStackTraceToString(&s);
  LOG(ERROR) << "STACK TRACE:\n" << s;

  // TOOD(hamaji): Use signal instead of sigaction?
  if (google::glog_internal_namespace_::IsFailureSignalHandlerInstalled()) {
// Set the default signal handler for SIGABRT, to avoid invoking our
// own signal handler installed by InstallFailureSignalHandler().
#ifdef HAVE_SIGACTION
    struct sigaction sig_action;
    memset(&sig_action, 0, sizeof(sig_action));
    sigemptyset(&sig_action.sa_mask);
    sig_action.sa_handler = SIG_DFL;
    sigaction(SIGABRT, &sig_action, NULL);
#elif defined(OS_WINDOWS)
    signal(SIGABRT, SIG_DFL);
#endif  // HAVE_SIGACTION
  }

  abort();
}

namespace et {
void GoogleLogFatalHandler::handle() {
  google::InstallFailureFunction(&DumpStackTraceToFileAndExit);
}

}  // namespace et

#include "GoogleLogFatalHandler.hpp"

#include "Headers.hpp"

namespace google {
namespace glog_internal_namespace_ {
void DumpStackTraceToString(string* stacktrace);
}
}  // namespace google

static void DumpStackTraceToFileAndExit() {
  string s;
  google::glog_internal_namespace_::DumpStackTraceToString(&s);
  LOG(ERROR) << "STACK TRACE:\n" << s;
  abort();
}

namespace et {
void GoogleLogFatalHandler::handle() {
  google::InstallFailureFunction(&DumpStackTraceToFileAndExit);
}

}  // namespace et

Remove logic that isn't supported on Ubuntu/Debian


#include <RGBColor.h>

RGBColor RGBColor::black(glm::vec3(0.f, 0.f, 0.f));
RGBColor RGBColor::red(glm::vec3(1.f, 0.f, 0.f));

RGBColor::RGBColor()
    : color(glm::vec3(0.f, 0.f, 0.f))
{
}

RGBColor::RGBColor(const glm::vec3& color)
    : color(color)
{
}

glm::vec3 RGBColor::GetRGBComponents() const
{
    return this->color;
}

uint32_t RGBColor::GetRGBAIntPacked() const
{
    uint32_t col = 0xFF;
    col = col | ((uint32_t)(color.x * 0xFF) << 24);
    col = col | ((uint32_t)(color.y * 0xFF) << 16);
    col = col | ((uint32_t)(color.z * 0xFF) << 8);
    return col;
}

#include <RGBColor.h>

RGBColor RGBColor::black(glm::vec3(0.f, 0.f, 0.f));
RGBColor RGBColor::red(glm::vec3(1.f, 0.f, 0.f));

RGBColor::RGBColor()
    : color(glm::vec3(0.f, 0.f, 0.f))
{
}

RGBColor::RGBColor(const glm::vec3& color)
    : color(color)
{
}

glm::vec3 RGBColor::GetRGBComponents() const
{
    return this->color;
}

uint32_t RGBColor::GetRGBAIntPacked() const
{
    uint32_t col = 0;
    col = col | ((uint32_t)(color.x * 0xFF));
    col = col | ((uint32_t)(color.y * 0xFF) << 8);
    col = col | ((uint32_t)(color.z * 0xFF) << 16);
    col = col | (0xFF << 24);
    return col;
}

Correct for color order inside PNG


// RUN: grep -Ev "// *[A-Z-]+:" %s > %t.cpp
// RUN: clang-tidy %t.cpp -fix -checks=llvm.* --
// RUN: FileCheck -input-file=%t.cpp %s

namespace i {
}
// CHECK: } // namespace i

class A { A(int i); }; // Not fixing this, because the check is in google-.
// CHECK: class A { A(int i); };

// RUN: grep -Ev "// *[A-Z-]+:" %s > %t.cpp
// RUN: clang-tidy %t.cpp -fix -checks=^llvm-.* --
// RUN: FileCheck -input-file=%t.cpp %s

namespace i {
}
// CHECK: } // namespace i

class A { A(int i); }; // Not fixing this, because the check is in google-.
// CHECK: class A { A(int i); };

Use more specific checks filter in the test.


// XFAIL: hexagon
// Test this without pch.
// RUN: %clang_cc1 -include %S/cxx-typeid.h -fsyntax-only -verify %s

// RUN: %clang_cc1 -x c++-header -emit-pch -o %t.pch %S/cxx-typeid.h
// RUN: %clang_cc1 -include-pch %t.pch -fsyntax-only -verify %s

// expected-no-diagnostics

void f() {
    (void)typeid(int);
}

Remove XFAIL now that the test is standalone.


#include <tabulate/table.hpp>

using namespace tabulate;

int main() {
  Table employees;

  // Add rows
  employees.add_row({"Emp. ID", "First Name", "Last Name", "Department / Business Unit"});
  employees.add_row({"101", "Donald", "Patrick", "Finance"});
  employees.add_row({"102", "Donald", "Patrick", "Marketing and Operational Logistics Planning"});
  employees.add_row({"103", "Ian", "Jacob", "Engineering"});

  employees.format()
    .font_color(Color::cyan)
    .font_background_color(Color::white)
    .corner_color(Color::blue)
    .border_color(Color::yellow)
    .padding_top(1)
    .padding_bottom(1);

  employees.column(3).format()
    .width(16);

  employees[0][3].format()
    .font_color(Color::none)
    .border_color(Color::red)
    .width(20);

  // employees[1].format()
  //   .width(15);

  // employees[1][2].format()
  //   .width(20);

  // // Print the table
  // employees.print(std::cout);

  // // Set width of column 1 to 13
  // employees.column(1).format()
  //   .width(13);

  // Print the table
  employees.print(std::cout);
}

#include <tabulate/table.hpp>

using namespace tabulate;

int main() {
  Table employees;

  // Add rows
  employees.add_row({"Emp. ID", "First Name", "Last Name", "Department / Business Unit"});
  employees.add_row({"101", "Donald", "Patrick", "Finance"});
  employees.add_row({"102", "Donald", "Patrick", "Marketing and Operational Logistics Planning"});
  employees.add_row({"103", "Ian", "Jacob", "Engineering"});

  // Print the table
  employees.print(std::cout);
}

Reset all styles in sample


#include <iostream>
#include <ctime>
#include <QCPP.h>

int main() {

	// make it more non-deterministic
	srand(time(NULL));

	// initialize Quantum state with 5 qubits
	Quantum qubits(5);

	// turns all qubits into every state with same probabilities
	qubits.Hadamard(0, 1, 2, 3, 4);
	// or
	// for(int i = 0;i < qubits.size();i++) qubits.Hadamard(i);
	// or
	// qubits.Hadamard({0, 1, 2, 3, 4});
	// would result the same

	// the possibility should be the same
	for(int i = 0;i < (1 << qubits.size());i++) {
		std::cout << "Probabilities of being " << i << " : " << qubits.getProbability(i) << std::endl;
	}

	// try to observe
	for(int i = 0;i < 10;i++) {
		std::cout << "State of qubits : " << qubits.getState() << std::endl;
	}

	return 0;
}

#include <iostream>
#include <ctime>
#include <QCPP.h>

int main() {

	// make it more non-deterministic
	srand(time(NULL));

	// initialize Quantum state with 5 qubits
	Quantum qubits(5);

	// turns all qubits into every state with same probabilities
	qubits.hadamard(0, 1, 2, 3, 4);
	// or
	// for(int i = 0;i < qubits.size();i++) qubits.Hadamard(i);
	// or
	// qubits.hadamard({0, 1, 2, 3, 4});
	// would result the same

	// the possibility should be the same
	for(int i = 0;i < (1 << qubits.size());i++) {
		std::cout << "Probabilities of being " << i << " : " << qubits.getProbability(i) << std::endl;
	}

	// try to observe
	for(int i = 0;i < 10;i++) {
		std::cout << "State of qubits : " << qubits.getState() << std::endl;
	}

	return 0;
}

Fix functions' names according to last change


#include <iostream>
#include <fstream>
#include <spv_utils.h>
#include <cstdint>

int main() {
  // Read spv binary module from a file
  std::ifstream spv_file("../sample_spv_modules/test.frag.spv", std::ios::binary |
                         std::ios::ate | std::ios::in);
  if (spv_file.is_open()) {
    std::streampos size = spv_file.tellg();

    spv_file.seekg(0, std::ios::beg);
    char *data = new char[size];
    spv_file.read(data, size);
    spv_file.close();

    // Parse the module
    sut::OpcodeStream stream(data, size);
    for (auto &i : stream) {
      if (i.GetOpcode() == spv::Op::OpCapability) {
        uint32_t instruction = 0xDEADBEEF;
        i.InsertAfter(&instruction, 1U);
        i.Remove();
      }
    }
    std::vector<uint32_t> filtered_stream = stream.EmitFilteredStream();

    delete[] data;
    data = nullptr;
  }

  return 0;
};

#include <iostream>
#include <fstream>
#include <spv_utils.h>
#include <cstdint>

int main() {
  // Read spv binary module from a file
  std::ifstream spv_file("../sample_spv_modules/test.frag.spv", std::ios::binary |
                         std::ios::ate | std::ios::in);
  if (spv_file.is_open()) {
    std::streampos size = spv_file.tellg();

    spv_file.seekg(0, std::ios::beg);
    char *data = new char[size];
    spv_file.read(data, size);
    spv_file.close();

    // Parse the module
    sut::OpcodeStream stream(data, size);
    for (auto &i : stream) {
      if (i.GetOpcode() == spv::Op::OpCapability) {
        uint32_t instruction = 0xDEADBEEF;
        std::vector<uint32_t> longer_instruction = {
          0xFFFFEEEE,
          0xFFFFDDDD,
          0xFFFFFFFF,
          0xDEADBEEF
        };
        uint32_t instruction2 = 0xDEADBEEF;
        i.InsertBefore(longer_instruction.data(), longer_instruction.size());
        i.InsertAfter(&instruction, 1U);
        i.Remove();
      }
    }
    std::vector<uint32_t> filtered_stream = stream.EmitFilteredStream();

    delete[] data;
    data = nullptr;
  }

  return 0;
};

Add longer instruction test to sample


// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.

#include <stdio.h>

#include "Arduino.h"

asm(".global _printf_float");
asm(".global _scanf_float");

extern "C" {
    size_t _write(int handle, const unsigned char *buf, size_t bufSize)
    {
        /* Check for the command to flush all handles */
        if (handle == -1) {
            return 0;
        }

        /* Check for stdout and stderr (only necessary if FILE descriptors are enabled.) */
        if (handle != 1 && handle != 2) {
            return -1;
        }

        size_t nChars = 0;
        for (; bufSize > 0; --bufSize, ++buf, ++nChars) {
            Serial.write(*buf);
        }
        return nChars;
    }
}

// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.

#include <stdio.h>

#include "Arduino.h"

// these are needed by the serializer, so force link
asm(".global _printf_float");
asm(".global _scanf_float");

extern "C" {
    size_t _write(int handle, const unsigned char *buf, size_t bufSize)
    {
        /* Check for the command to flush all handles */
        if (handle == -1) {
            return 0;
        }

        /* Check for stdout and stderr (only necessary if FILE descriptors are enabled.) */
        if (handle != 1 && handle != 2) {
            return -1;
        }

        size_t nChars = 0;
        for (; bufSize > 0; --bufSize, ++buf, ++nChars) {
            Serial.write(*buf);
        }
        return nChars;
    }
}

Add note about _printf_float and _scanf_float


/*********************************************************************
 * thread-sleep: Force Node.js to sleep
 *
 * Copyright (c) 2015 Forbes Lindesay
 * Copyright (c) 2015 Tiancheng "Timothy" Gu
 *
 * MIT License
 ********************************************************************/

#include <nan.h>
#ifdef _WIN32
#include <windows.h>
#else
#include <ctime>
#endif

using v8::FunctionTemplate;
using Nan::GetFunction;
using Nan::New;
using Nan::Set;

void SleepSync(const Nan::FunctionCallbackInfo<v8::Value>& info) {
  // expect a number as the first argument
  int millisec = args[0]->Uint32Value();

#ifdef _WIN32
  Sleep(millisec);
#else
  struct timespec req;
  req.tv_sec = millisec / 1000;
  req.tv_nsec = (millisec % 1000) * 1000000L;
  nanosleep(&req, (struct timespec *)NULL);
#endif

  info.GetReturnValue().Set(millisec);
}

// Expose SleepSync() as sleep() in JS
NAN_MODULE_INIT(InitAll) {
  Set(target, New("sleep").ToLocalChecked(),
    GetFunction(New<FunctionTemplate>(SleepSync)).ToLocalChecked());
}

NODE_MODULE(thread_sleep, InitAll)

/*********************************************************************
 * thread-sleep: Force Node.js to sleep
 *
 * Copyright (c) 2015 Forbes Lindesay
 * Copyright (c) 2015 Tiancheng "Timothy" Gu
 *
 * MIT License
 ********************************************************************/

#include <nan.h>
#ifdef _WIN32
#include <windows.h>
#else
#include <ctime>
#endif

using v8::FunctionTemplate;
using Nan::GetFunction;
using Nan::New;
using Nan::Set;

void SleepSync(const Nan::FunctionCallbackInfo<v8::Value>& info) {
#ifdef _WIN32
  // expect a number as the first argument
  DWORD millisec = info[0]->Uint32Value();

  Sleep(millisec);
#else
  // expect a number as the first argument
  uint32_t millisec = info[0]->Uint32Value();

  struct timespec req;
  req.tv_sec = millisec / 1000;
  req.tv_nsec = (millisec % 1000) * 1000000L;
  nanosleep(&req, (struct timespec *)NULL);
#endif

  info.GetReturnValue().Set(millisec);
}

// Expose SleepSync() as sleep() in JS
NAN_MODULE_INIT(InitAll) {
  Set(target, New("sleep").ToLocalChecked(),
    GetFunction(New<FunctionTemplate>(SleepSync)).ToLocalChecked());
}

NODE_MODULE(thread_sleep, InitAll)

Use correct type for millisec


// RUN: %clang_cc1 %s -triple=x86_64-apple-darwin -g -emit-llvm -o - | FileCheck %s
// This test is for a crash when emitting debug info for not-yet-completed types.
// Test that we don't actually emit a forward decl for the offending class:
// CHECK:  [ DW_TAG_class_type ] [Derived<const __CFString, Foo>] {{.*}} [def]
// rdar://problem/15931354
typedef const struct __CFString * CFStringRef;
template <class R> class Returner {};
typedef const __CFString String;

template <class A, class B> class Derived;

template <class A, class B>
class Base
{
  static Derived<A, B>* create();
};

template <class A, class B>
class Derived : public Base<A, B> {
public:
  static void foo();
};

class Foo
{
  Foo();
  static Returner<Base<String,Foo> > all();
};

Foo::Foo(){}

Returner<Base<String,Foo> > Foo::all()
{
  Derived<String,Foo>::foo();
  return Foo::all();
}

// RUN: %clang_cc1 %s -triple=x86_64-apple-darwin -g -emit-llvm -o - | FileCheck %s
// This test is for a crash when emitting debug info for not-yet-completed types.
// Test that we don't actually emit a forward decl for the offending class:
// CHECK:  [ DW_TAG_class_type ] [Derived<Foo>] {{.*}} [def]
// rdar://problem/15931354
template <class R> class Returner {};
template <class A> class Derived;

template <class A>
class Base
{
  static Derived<A>* create();
};

template <class A>
class Derived : public Base<A> {
public:
  static void foo();
};

class Foo
{
  Foo();
  static Returner<Base<Foo> > all();
};

Foo::Foo(){}

Returner<Base<Foo> > Foo::all()
{
  Derived<Foo>::foo();
  return Foo::all();
}

Simplify testcase from r200797 some more.


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

#include "ui/ozone/platform/drm/gpu/gpu_lock.h"

#include <fcntl.h>
#include <unistd.h>

#include "base/logging.h"
#include "base/posix/eintr_wrapper.h"

namespace ui {

namespace {
const char kGpuLockFile[] = "/run/frecon";
}

GpuLock::GpuLock() {
  fd_ = open(kGpuLockFile, O_RDWR);
  if (fd_ < 0) {
    PLOG(ERROR) << "Failed to open lock file '" << kGpuLockFile << "'";
    return;
  }

  struct flock data;
  memset(&data, 0, sizeof(data));
  data.l_type = F_WRLCK;
  data.l_whence = SEEK_SET;

  VLOG(1) << "Taking write lock on '" << kGpuLockFile << "'";
  if (HANDLE_EINTR(fcntl(fd_, F_SETLKW, &data)))
    PLOG(ERROR) << "Error while trying to get lock on '" << kGpuLockFile << "'";

  VLOG(1) << "Done trying to take write lock on '" << kGpuLockFile << "'";
}

GpuLock::~GpuLock() {
  // Failed to open the lock file, so nothing to do here.
  if (fd_ < 0)
    return;

  VLOG(1) << "Releasing write lock on '" << kGpuLockFile << "'";
  close(fd_);
}

}  // namespace ui

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

#include "ui/ozone/platform/drm/gpu/gpu_lock.h"

#include <sys/file.h>
#include <unistd.h>

#include "base/logging.h"
#include "base/posix/eintr_wrapper.h"

namespace ui {

namespace {
const char kGpuLockFile[] = "/run/frecon";
}

GpuLock::GpuLock() {
  fd_ = open(kGpuLockFile, O_RDWR);
  if (fd_ < 0) {
    PLOG(ERROR) << "Failed to open lock file '" << kGpuLockFile << "'";
    return;
  }

  VLOG(1) << "Taking write lock on '" << kGpuLockFile << "'";
  if (HANDLE_EINTR(flock(fd_, LOCK_EX)))
    PLOG(ERROR) << "Error while trying to get lock on '" << kGpuLockFile << "'";

  VLOG(1) << "Done trying to take write lock on '" << kGpuLockFile << "'";
}

GpuLock::~GpuLock() {
  // Failed to open the lock file, so nothing to do here.
  if (fd_ < 0)
    return;

  VLOG(1) << "Releasing write lock on '" << kGpuLockFile << "'";
  close(fd_);
}

}  // namespace ui

Change file locking from Posix to BSD style


#include <bits/stdc++.h>

using namespace std;
typedef long long ll;
typedef vector < ll > vl;

vl arr(3);
/*
	returs gcd(a,b) and find the coeficcients of bezout
	such that d = ax + by
	arr[0] gcd
	arr[1] x
	arr[2] y
*/
void extended(ll a, ll b){
	ll y =0;
	ll x =1;
	ll xx =0;
	ll yy =1;
	while(b){
		ll	 q = a / b;
		ll t = b;
		b = a%b;
		a = t;

		t = xx;
		xx = x-q*xx;
		x = t;

		t = yy;
		yy = y -q*yy;
		y = t;
	}
	arr[0] = a;
	arr[1] = x;
	arr[2] = y;
}

int main(){
	ll a = 20, b = 50;
	extended(a,b);
	printf("gcd(%lld, %lld) = %lld = %lld * %lld + %lld * %lld\n", a, b, arr[0], a,arr[1], b, arr[2]);
	return 0;
}

#include <bits/stdc++.h>

using namespace std;
typedef long long ll;
typedef vector < ll > vl;

vl arr(3);
/*
	returs gcd(a,b) and find the coeficcients of bezout
	such that d = ax + by
	arr[0] gcd
	arr[1] x
	arr[2] y
*/
void extended(ll a, ll b){
	ll y =0;
	ll x =1;
	ll xx =0;
	ll yy =1;
	while(b){
		ll	 q = a / b;
		ll t = b;
		b = a%b;
		a = t;

		t = xx;
		xx = x-q*xx;
		x = t;

		t = yy;
		yy = y -q*yy;
		y = t;
	}
	arr[0] = a;
	arr[1] = x;
	arr[2] = y;
}
/*

	ax + by  = c
	mcd(a,b) = d
	ax0 + by0 = d
	c = d * c'

	Bezouts identity

		X = x0 * c' - (b/d) * k
		Y = y0 * c' + (a/d) * k

*/

int main(){
	ll a = 20, b = 50;
	extended(a,b);
	printf("gcd(%lld, %lld) = %lld = %lld * %lld + %lld * %lld\n", a, b, arr[0], a,arr[1], b, arr[2]);
	return 0;
}

Add Bezouts identity, very useful.


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

using namespace std;

#define X(a,b) (x[a]*10+x[b])

int mkInt(vector<int> &v) {
    int ret = 0;
    for (vector<int>::iterator it = v.begin(); it != v.end(); ++it) {
        ret = ret * 10 + *it;
    }
    return ret;
}

int main() {
    int init_x[] = { 0, 2, 3, 4, 5, 6, 7, 8, 9 };
    vector<int> x = vector<int>(init_x, init_x + 9);
    do {
        vector<int> vec_ab = vector<int>(x.begin() + 0, x.begin() + 2);
        vector<int> vec_cd = vector<int>(x.begin() + 2, x.begin() + 4);
        vector<int> vec_ef = vector<int>(x.begin() + 4, x.begin() + 6);
        vector<int> vec_gh = vector<int>(x.begin() + 6, x.begin() + 8);

        int ab = mkInt(vec_ab), cd = mkInt(vec_cd), ef = mkInt(vec_ef), gh = mkInt(vec_gh);
        if ((ab >= 10 && cd >= 10 && ef >= 10 && gh >= 10) && (ab - cd) == ef && (ef + gh) == 111) {
            cout << ab << " + " << cd << " = " << ef << ", " << ef << " - " << gh << " = 111" << endl;
        }
    } while (next_permutation(x.begin(), x.end()));

    return 0;
}

Refactor C++ code to real C++ code


#include <iostream>

using namespace std;

const int MAX = 100;

struct Person {
  string firstName;
  string lastName;

  void input() {
    cout << "Enter person's first and last names separated by a space: ";
    cin >> firstName >> lastName;
  }

  void print() {
    cout << firstName << ' ' << lastName << '\n';
  }
};

struct Client {
  Person person;
  double account;

  void input() {
    person.input();

    cout << "Enter account: ";
    cin >> account;
  }

  void print() {
    person.print();
    cout << "Account: " << account << '\n';
  };
};

void inputClients(Client clients[], int n) {
  for (int i = 0; i < n; ++i) {
    clients[i].input();
  }
}

void printClients(Client clients[], int n) {
  for (int i = 0; i < n; ++i) {
    clients[i].print();
  }
}

double sumAccounts(Client clients[], int n) {
  double sum = 0;

  for (int i = 0; i < n; ++i) {
    sum += clients[i].account;
  }

  return sum;
}

int main() {
  Client clients[MAX];
  int clientsCount = 3;

  inputClients(clients, clientsCount);
  printClients(clients, clientsCount);
  cout << sumAccounts(clients, clientsCount) << '\n';

  return 0;
}

#include <iostream>

using namespace std;

struct Person {
  char firstName[32];
  char lastName[32];

  void input() {
    cout << "Enter person's first and last names separated by a space: ";
    cin >> firstName >> lastName;
  }

  void print() {
    cout << firstName << ' ' << lastName << '\n';
  }
};

struct Client {
  Person person;
  double account;

  void input() {
    person.input();

    cout << "Enter account: ";
    cin >> account;
  }

  void print() {
    person.print();
    cout << "Account: " << account << '\n';
  };
};

void inputClients(Client clients[], int n) {
  for (int i = 0; i < n; ++i) {
    clients[i].input();
  }
}

void printClients(Client clients[], int n) {
  for (int i = 0; i < n; ++i) {
    clients[i].print();
  }
}

double sumAccounts(Client clients[], int n) {
  double sum = 0;

  for (int i = 0; i < n; ++i) {
    sum += clients[i].account;
  }

  return sum;
}

int main() {
  Client clients[100];
  int clientsCount = 3;

  inputClients(clients, clientsCount);
  printClients(clients, clientsCount);
  cout << sumAccounts(clients, clientsCount) << '\n';

  return 0;
}

Use char[] instead of std::string


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

#include "remoting/host/event_executor_mac.h"

namespace remoting {

EventExecutorMac::EventExecutorMac(Capturer* capturer)
  : EventExecutor(capturer) {
}

EventExecutorMac::~EventExecutorMac() {
}

void EventExecutorMac::HandleInputEvent(ChromotingClientMessage* message) {
  delete message;
}

}  // namespace remoting

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

#include "remoting/host/event_executor_mac.h"

#include "remoting/protocol/messages_decoder.h"

namespace remoting {

EventExecutorMac::EventExecutorMac(Capturer* capturer)
  : EventExecutor(capturer) {
}

EventExecutorMac::~EventExecutorMac() {
}

void EventExecutorMac::HandleInputEvent(ChromotingClientMessage* message) {
  delete message;
}

}  // namespace remoting

Fix build break on mac. TBR=ajwong


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

#include "net/disk_cache/cache_util.h"

#include "base/file_util.h"
#include "base/logging.h"
#include "base/string_util.h"

namespace disk_cache {

bool MoveCache(const FilePath& from_path, const FilePath& to_path) {
  // Just use the version from base.
  return file_util::Move(from_path, to_path);
}

void DeleteCache(const FilePath& path, bool remove_folder) {
  file_util::FileEnumerator iter(path,
                                 /* recursive */ false,
                                 file_util::FileEnumerator::FILES);
  for (FilePath file = iter.Next(); !file.value().empty(); file = iter.Next()) {
    if (!file_util::Delete(file, /* recursive */ false))
      NOTREACHED();
  }

  if (remove_folder) {
    if (!file_util::Delete(path, /* recursive */ false))
      NOTREACHED();
  }
}

bool DeleteCacheFile(const FilePath& name) {
  return file_util::Delete(name, false);
}

}  // namespace disk_cache

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

#include "net/disk_cache/cache_util.h"

#include "base/file_util.h"
#include "base/logging.h"
#include "base/string_util.h"

namespace disk_cache {

bool MoveCache(const FilePath& from_path, const FilePath& to_path) {
  // Just use the version from base.
  return file_util::Move(from_path, to_path);
}

void DeleteCache(const FilePath& path, bool remove_folder) {
  file_util::FileEnumerator iter(path,
                                 /* recursive */ false,
                                 file_util::FileEnumerator::FILES);
  for (FilePath file = iter.Next(); !file.value().empty(); file = iter.Next()) {
    if (!file_util::Delete(file, /* recursive */ false)) {
      LOG(WARNING) << "Unable to delete cache.";
      return;
    }
  }

  if (remove_folder) {
    if (!file_util::Delete(path, /* recursive */ false)) {
      LOG(WARNING) << "Unable to delete cache folder.";
      return;
    }
  }
}

bool DeleteCacheFile(const FilePath& name) {
  return file_util::Delete(name, false);
}

}  // namespace disk_cache

Change NOTREACHED for a LOG(WARNING) when we can't delete the cache. This should help the unit tests.


#include <QApplication>
#include <QSettings>
#include <QLocale>
#include <QTranslator>
#include <QLibraryInfo>

#include "trayicon.h"

int main(int argc, char **argv)
{
    QApplication app(argc, argv);
    QApplication::setOrganizationName("Restnotifier");
    app.setQuitOnLastWindowClosed(false);

    // Set language
    QSettings settings;
    QString lang;
    QTranslator translator, qtTranslator;
    if (settings.contains("lang"))
        lang = settings.value("lang").toString();
    else
        lang = QLocale::languageToString(QLocale::system().language());
    if (lang == "ru")
    {
        QLocale::setDefault(QLocale("ru"));

        // install qt translator
#if defined Q_WS_X11
        const QString loc = QLibraryInfo::location(QLibraryInfo::TranslationsPath);
#elif defined Q_WS_WIN
        const QString loc();
#endif
        qtTranslator.load("qt_ru", loc);
        app.installTranslator(&qtTranslator);

        // install app translator
        translator.load("restnotifier_ru");
        app.installTranslator(&translator);
    }

    TrayIcon *trayIcon = new TrayIcon();
    trayIcon->show();
    QObject::connect(trayIcon, SIGNAL(quitScheduled()), &app, SLOT(quit()));
    int code = app.exec();
    delete trayIcon;
    return code;
}

#include <QApplication>
#include <QSettings>
#include <QLocale>
#include <QTranslator>
#include <QLibraryInfo>

#include "trayicon.h"

int main(int argc, char **argv)
{
    QApplication app(argc, argv);
    QApplication::setOrganizationName("Restnotifier");
    app.setQuitOnLastWindowClosed(false);

    // Set language
    QSettings settings;
    QString lang;
    QTranslator translator, qtTranslator;
    if (settings.contains("lang"))
        lang = settings.value("lang").toString();
    else
        lang = QLocale::languageToString(QLocale::system().language());
    if (lang == "ru")
    {
        QLocale::setDefault(QLocale("ru"));

        // install qt translator
#if defined Q_WS_X11
        const QString loc = QLibraryInfo::location(QLibraryInfo::TranslationsPath);
#elif defined Q_WS_WIN
        const QString loc();
#endif
        qtTranslator.load("qt_ru", loc);
        app.installTranslator(&qtTranslator);

        // install app translator
        QString translationsPath = settings.value("tr_path", QString()).toString();
        translator.load("restnotifier_ru", translationsPath);
        app.installTranslator(&translator);
    }

    TrayIcon *trayIcon = new TrayIcon();
    trayIcon->show();
    QObject::connect(trayIcon, SIGNAL(quitScheduled()), &app, SLOT(quit()));
    int code = app.exec();
    delete trayIcon;
    return code;
}

Allow to change path to translations


#include "common/application_info.h"

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

namespace brightray {

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

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

}  // namespace brightray

#include "common/application_info.h"

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

namespace brightray {

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

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

}  // namespace brightray

Update for move of string conversion functions into base::


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

#include "GrDrawBatch.h"

GrDrawBatch::GrDrawBatch(uint32_t classID) : INHERITED(classID), fPipelineInstalled(false) { }

GrDrawBatch::~GrDrawBatch() {
    if (fPipelineInstalled) {
        this->pipeline()->~GrPipeline();
    }
}

void GrDrawBatch::getPipelineOptimizations(GrPipelineOptimizations* opt) const {
    GrInitInvariantOutput color;
    GrInitInvariantOutput coverage;
    this->computePipelineOptimizations(&color, &coverage, &opt->fOverrides);
    opt->fColorPOI.initUsingInvariantOutput(color);
    opt->fCoveragePOI.initUsingInvariantOutput(coverage);
}

bool GrDrawBatch::installPipeline(const GrPipeline::CreateArgs& args) {
    GrXPOverridesForBatch overrides;
    void* location = fPipelineStorage.get();
    if (!GrPipeline::CreateAt(location, args, &overrides)) {
        return false;
    }
    this->initBatchTracker(overrides);
    fPipelineInstalled = true;
    return true;
}

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

#include "GrDrawBatch.h"

GrDrawBatch::GrDrawBatch(uint32_t classID) : INHERITED(classID), fPipelineInstalled(false) { }

GrDrawBatch::~GrDrawBatch() {
    if (fPipelineInstalled) {
        this->pipeline()->~GrPipeline();
    }
}

void GrDrawBatch::getPipelineOptimizations(GrPipelineOptimizations* opt) const {
    GrInitInvariantOutput color;
    GrInitInvariantOutput coverage;
    this->computePipelineOptimizations(&color, &coverage, &opt->fOverrides);
    opt->fColorPOI.initUsingInvariantOutput(color);
    opt->fCoveragePOI.initUsingInvariantOutput(coverage);
}

bool GrDrawBatch::installPipeline(const GrPipeline::CreateArgs& args) {
    GrXPOverridesForBatch overrides;
    void* location = fPipelineStorage.get();
    if (!GrPipeline::CreateAt(location, args, &overrides)) {
        return false;
    }
    fPipelineInstalled = true;
    this->initBatchTracker(overrides);
    return true;
}

Fix assert accessing pipeline from initBatchTracker


// This file is part of the GLERI project
//
// Copyright (c) 2012 by Mike Sharov <msharov@users.sourceforge.net>
// This file is free software, distributed under the MIT License.

#include "rglrp.h"

#define N(n,s)	#n "\0" #s "\0"
/*static*/ const char PRGLR::_cmdNames[] =
     "\0"	// Dirty trick: object name is 4 bytes, but must be zero terminated
     N(GLError,s)
     N(Restate,(nnqqyyyy))
     N(Expose,)
     N(Event,(unnuu))
;
#undef N

/*static*/ inline const char* PRGLR::LookupCmdName (ECmd cmd, size_type& sz) noexcept
{
    return (CCmdBuf::LookupCmdName((unsigned)cmd,sz,_cmdNames+1,sizeof(_cmdNames)-2));
}

/*static*/ PRGLR::ECmd PRGLR::LookupCmd (const char* name, size_type bleft) noexcept
{
    return (ECmd(CCmdBuf::LookupCmd(name+1,bleft,_cmdNames+1,sizeof(_cmdNames)-2)));
}

bstro PRGLR::CreateCmd (ECmd cmd, size_type sz) noexcept
{
    size_type msz;
    const char* m = LookupCmdName(cmd, msz);
    return (CCmdBuf::CreateCmd (RGLRObject, m-1, msz+1, sz));
}

// This file is part of the GLERI project
//
// Copyright (c) 2012 by Mike Sharov <msharov@users.sourceforge.net>
// This file is free software, distributed under the MIT License.

#include "rglrp.h"

#define N(n,s)	#n "\0" #s "\0"
/*static*/ const char PRGLR::_cmdNames[] =
     N(Error,s)
     N(Restate,(nnqqyyyy))
     N(Expose,)
     N(Event,(unnuu))
;
#undef N

/*static*/ inline const char* PRGLR::LookupCmdName (ECmd cmd, size_type& sz) noexcept
{
    return (CCmdBuf::LookupCmdName((unsigned)cmd,sz,_cmdNames+1,sizeof(_cmdNames)-2));
}

/*static*/ PRGLR::ECmd PRGLR::LookupCmd (const char* name, size_type bleft) noexcept
{
    return (ECmd(CCmdBuf::LookupCmd(name+1,bleft,_cmdNames+1,sizeof(_cmdNames)-2)));
}

bstro PRGLR::CreateCmd (ECmd cmd, size_type sz) noexcept
{
    size_type msz;
    const char* m = LookupCmdName(cmd, msz);
    return (CCmdBuf::CreateCmd (RGLRObject, m-1, msz+1, sz));
}

Revert "Rename Error call to GLError"


#include "forth_common.th"

// A little Forth.

.set link, 0
.global __zero
__zero:
__boot:
    S <- [reloc(_PSPinit)]
    R <- [reloc(_RSPinit)]
    I <- reloc(QUIT)        // enter text interpreter
    goto(NEXT)

    .global _PSPinit
    .global _RSPinit
_PSPinit:   .word   0x007fffff
_RSPinit:   .word   0x00ffffff

// TODO smudge internal words
head(RESET_RSP,RESET_RSP): .word . + 1
    R <- [reloc(_RSPinit)]
    goto(NEXT)

head(NEXT,NEXT):
    W  <- [I]
    W  <-  rel(W)
    I  <-  I + 1
    X  <- [W]
    jmp(X)

head(ENTER,ENTER):
    .word . + 1
    push(R,I)
    I  <- W + 1
    goto(NEXT)

head(EXIT,EXIT):
    .word . + 1
    pop(R,I)
    goto(NEXT)

    .global source_id
source_id: .word 0
head(SOURCE_ID,SOURCE-ID): .word
    @ENTER, @LITERAL, @source_id, @RELOC, @EXIT

    .global __done
__done:
    // return to caller of forth, abort, whatever is required
    //p <- reloc(__boot)
    illegal

#include "forth_common.th"

// A little Forth.

.set link, 0
.global __zero
__zero:
__boot:
    S <- [reloc(_PSPinit)]
    R <- [reloc(_RSPinit)]
    I <- reloc(QUIT)        // enter text interpreter
    goto(NEXT)

    .global _PSPinit
    .global _RSPinit
_PSPinit:   .word   0x007fffff
_RSPinit:   .word   0x00ffffff

// TODO smudge internal words
head(RESET_RSP,RESET_RSP): .word . + 1
    R <- [reloc(_RSPinit)]
    goto(NEXT)

head(NEXT,NEXT):
    W  <- [I]
    W  <-  rel(W)
    I  <-  I + 1
    X  <- [W]
    jmp(X)

head(ENTER,ENTER):
    // ENTER is special and does not have an interp-word entry
    push(R,I)
    I  <- W + 1
    goto(NEXT)

head(EXIT,EXIT):
    .word . + 1
    pop(R,I)
    goto(NEXT)

    .global source_id
source_id: .word 0
head(SOURCE_ID,SOURCE-ID): .word
    @ENTER, @LITERAL, @source_id, @RELOC, @EXIT

    .global __done
__done:
    // return to caller of forth, abort, whatever is required
    //p <- reloc(__boot)
    illegal

Drop interp-word pointer in ENTER


#include <stan/math/rev/scal.hpp>
#include <gtest/gtest.h>
#include <test/unit/math/rev/scal/util.hpp>
#include <limits>

TEST(MathFunctions, is_any_nan_variadic_rev) {
  using stan::math::is_any_nan;

  double dbl_inf = std::numeric_limits<double>::infinity();
  double dbl_nan = std::numeric_limits<double>::quiet_NaN();

  AVAR var_nan(dbl_nan);
  AVAR var_inf(dbl_inf);

  AVAR a = 7.0;
  AVAR b = 2.0;

  EXPECT_TRUE(is_any_nan(var_nan, b, 6, 5.0));
  EXPECT_TRUE(is_any_nan(var_nan, var_inf, 6, 5.0));
  EXPECT_TRUE(is_any_nan(dbl_nan, a, b, 6, 5.0));

  EXPECT_FALSE(is_any_nan(dbl_inf, b, 6, var_inf));
  EXPECT_FALSE(is_any_nan(a, b, 6, 7.0));
}

#include <stan/math/rev/scal.hpp>
#include <gtest/gtest.h>
#include <test/unit/math/rev/scal/util.hpp>
#include <test/unit/math/rev/scal/fun/util.hpp>
#include <limits>

TEST(MathFunctions, is_any_nan_variadic_rev) {
  using stan::math::is_any_nan;

  double dbl_inf = std::numeric_limits<double>::infinity();
  double dbl_nan = std::numeric_limits<double>::quiet_NaN();

  AVAR var_nan(dbl_nan);
  AVAR var_inf(dbl_inf);

  AVAR a = 7.0;
  AVAR b = 2.0;

  EXPECT_TRUE(is_any_nan(var_nan, b, 6, 5.0));
  EXPECT_TRUE(is_any_nan(var_nan, var_inf, 6, 5.0));
  EXPECT_TRUE(is_any_nan(dbl_nan, a, b, 6, 5.0));

  EXPECT_FALSE(is_any_nan(dbl_inf, b, 6, var_inf));
  EXPECT_FALSE(is_any_nan(a, b, 6, 7.0));
}

Fix includes for AVAR typedef.


#include "module_wpad.hpp"
using namespace com::googlecode::libproxy;

static const char *DEFAULT_WPAD_ORDER[] = {
	"wpad_dhcp",
	"wpad_slp",
	"wpad_dns",
	"wpad_dnsdevolution",
	NULL
};

bool wpad_module::operator<(const wpad_module& module) const {
	for (int i=0 ; DEFAULT_WPAD_ORDER[i] ; i++) {
		if (module.get_id() == DEFAULT_WPAD_ORDER[i])
			break;
		if (this->get_id() == DEFAULT_WPAD_ORDER[i])
			return true;
	}
	return false;
}

#include "module_wpad.hpp"
using namespace com::googlecode::libproxy;

static const char *DEFAULT_WPAD_ORDER[] = {
	"wpad_dhcp",
	"wpad_slp",
	"wpad_dns_srv",
	"wpad_dns_txt",
	"wpad_dns_alias",
	NULL
};

bool wpad_module::operator<(const wpad_module& module) const {
	for (int i=0 ; DEFAULT_WPAD_ORDER[i] ; i++) {
		if (module.get_id() == DEFAULT_WPAD_ORDER[i])
			break;
		if (this->get_id() == DEFAULT_WPAD_ORDER[i])
			return true;
	}
	return false;
}

Fix wpad ordering table after wpad_dns -> wpad_dns_alias rename


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

extern "C" int printf(...);

static int count;
static float fcount;

class xpto {
public:
  xpto() : i(count++), f(fcount++) {
    printf("xpto::xpto()\n");
  }
  int i;
  float f;

  ~xpto() {
    printf("xpto::~xpto()\n");
  }
};

int main() {
  xpto array[2][3][4];
  for (int h = 0; h < 2; h++)
   for (int i = 0; i < 3; i++)
    for (int j = 0; j < 4; j++)
       printf("array[%d][%d][%d] = {%d, %f}\n",
              h, i, j, array[h][i][j].i, array[h][i][j].f);
}

// CHECK-LP64: callq    __ZN4xptoC1Ev

// CHECK-LP32: calll     L__ZN4xptoC1Ev

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

extern "C" int printf(...);

static int count;
static float fcount;

class xpto {
public:
  xpto() : i(count++), f(fcount++) {
    printf("xpto::xpto()\n");
  }
  int i;
  float f;

  ~xpto() {
    printf("xpto::~xpto()\n");
  }
};

int main() {
  xpto array[2][3][4];
  for (int h = 0; h < 2; h++)
   for (int i = 0; i < 3; i++)
    for (int j = 0; j < 4; j++)
       printf("array[%d][%d][%d] = {%d, %f}\n",
              h, i, j, array[h][i][j].i, array[h][i][j].f);
}

// CHECK: call void @_ZN4xptoC1Ev

Check IR in this test.


#include "stdafx.h"
#include "MultipleSenderTest.h"
#include "EventSender.h"

class MultiEventA:
  public virtual EventReceiver
{
public:
  virtual void EventA(void) = 0;
};

class MultiEventB:
  public virtual EventReceiver
{
public:
  virtual void EventB(void) = 0;
};

class MultiSender:
  public EventSender<MultiEventA, MultiEventB>
{
};

MultipleSenderTest::MultipleSenderTest(void) {}

TEST_F(MultipleSenderTest, VerifyMultiSendA) {
  m_sender->Fire(&MultiEventA::EventA)();
}

TEST_F(MultipleSenderTest, VerifyMultiSendB) {
  m_sender->Fire(&MultiEventB::EventB)();
}

#include "stdafx.h"
#include "MultipleSenderTest.h"
#include "EventSender.h"

class MultiEventA:
  public virtual EventReceiver
{
public:
  virtual void Event(void) = 0;
};

class MultiEventB:
  public virtual EventReceiver
{
public:
  virtual void Event(void) = 0;
};

class MultiSender:
  public EventSender<MultiEventA, MultiEventB>
{
};

MultipleSenderTest::MultipleSenderTest(void) {}

TEST_F(MultipleSenderTest, VerifyMultiSendA) {
  m_sender->Fire(&MultiEventA::Event)();
}

TEST_F(MultipleSenderTest, VerifyMultiSendB) {
  m_sender->Fire(&MultiEventB::Event)();
}

Test amended to ensure that potential naming collisions do not necessarily affect execution


// RUN: %clang_cc1 -emit-llvm -g -triple x86_64-apple-darwin %s -o - | FileCheck %s

// CHECK: DW_TAG_subrange_type

struct StructName {
  int member[];
};

struct StructName SN;

// RUN: %clang_cc1 -emit-llvm -g -triple x86_64-apple-darwin %s -o - | FileCheck %s

// CHECK: metadata !{i32 {{.*}}, i64 1, i64 0}        ; [ DW_TAG_subrange_type ]

struct StructName {
  int member[];
};

struct StructName SN;

Check that we have an unknown upper bound range for our flexible array members.


#include "iorequest.h"
#include <QtDebug>
#include "event.h"
#include "actions/action.h"

IORequest::IORequest(Player* source, IORequest::RequestType type, int refCount) :
    QObject(NULL),
    mRefCount(refCount),
    m_source(source),
    m_type(type),
    m_response(NULL)
{
}

IORequest::~IORequest()
{
}

IORequest::RequestType IORequest::type() const
{
    return m_type;
}

void IORequest::putExtra(const QString& key, const QVariant& value)
{
    m_extras.insert(key, value);
}

QVariant IORequest::extra(const QString& key) const
{
    Q_ASSERT(m_extras.contains(key));
    return m_extras.value(key);
}

void IORequest::setResponse(void* r)
{
    m_response = r;
}

void* IORequest::response() const
{
    return m_response;
}

void IORequest::clearRef()
{
    if (mRefCount-- <= 0)
        delete this;
}

#include "iorequest.h"
#include <QtDebug>
#include "event.h"
#include "actions/action.h"

IORequest::IORequest(Player* source, IORequest::RequestType type, int refCount) :
    QObject(NULL),
    mRefCount(refCount),
    m_source(source),
    m_type(type),
    m_response(NULL)
{
}

IORequest::~IORequest()
{
}

IORequest::RequestType IORequest::type() const
{
    return m_type;
}

void IORequest::putExtra(const QString& key, const QVariant& value)
{
    m_extras.insert(key, value);
}

QVariant IORequest::extra(const QString& key) const
{
    Q_ASSERT(m_extras.contains(key));
    return m_extras.value(key);
}

void IORequest::setResponse(void* r)
{
    m_response = r;
}

void* IORequest::response() const
{
    return m_response;
}

void IORequest::clearRef()
{
    if (--mRefCount <= 0)
        delete this;
}

Fix memory leak: IORequest needed 3 calls (instead of 2) to deRef to delete itself


#include "StdAfx.h"
#include "BlackArea.h"
/*
    RawSpeed - RAW file decoder.

    Copyright (C) 2009 Klaus Post

    This library 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 of the License, or (at your option) any later version.

    This library 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 this library; if not, write to the Free Software
    Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA

    http://www.klauspost.com
*/

namespace RawSpeed {

BlackArea::BlackArea( int _offset, int _size, bool _isVertical ) :
offset(_offset), size(_size), isVertical(isVertical)
{

}

BlackArea::~BlackArea(void)
{
}

} // namespace RawSpeed

#include "StdAfx.h"
#include "BlackArea.h"
/*
    RawSpeed - RAW file decoder.

    Copyright (C) 2009 Klaus Post

    This library 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 of the License, or (at your option) any later version.

    This library 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 this library; if not, write to the Free Software
    Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA

    http://www.klauspost.com
*/

namespace RawSpeed {

BlackArea::BlackArea( int _offset, int _size, bool _isVertical ) :
offset(_offset), size(_size), isVertical(_isVertical)
{

}

BlackArea::~BlackArea(void)
{
}

} // namespace RawSpeed

Fix orientation of black areas (value left uninitialized).


#include "perf_precomp.hpp"

using namespace std;
using namespace cv;
using namespace perf;
using std::tr1::make_tuple;
using std::tr1::get;

CV_ENUM(AgastType, AgastFeatureDetector::AGAST_5_8, AgastFeatureDetector::AGAST_7_12d,
                   AgastFeatureDetector::AGAST_7_12s, AgastFeatureDetector::OAST_9_16)

typedef std::tr1::tuple<string, AgastType> File_Type_t;
typedef perf::TestBaseWithParam<File_Type_t> agast;

#define AGAST_IMAGES \
    "cv/detectors_descriptors_evaluation/images_datasets/leuven/img1.png",\
    "stitching/a3.png"

PERF_TEST_P(agast, detect, testing::Combine(
                            testing::Values(AGAST_IMAGES),
                            AgastType::all()
                          ))
{
    string filename = getDataPath(get<0>(GetParam()));
    int type = get<1>(GetParam());
    Mat frame = imread(filename, IMREAD_GRAYSCALE);

    if (frame.empty())
        FAIL() << "Unable to load source image " << filename;

    declare.in(frame);

    Ptr<FeatureDetector> fd = AgastFeatureDetector::create(20, true, type);
    ASSERT_FALSE( fd.empty() );
    vector<KeyPoint> points;

    TEST_CYCLE() fd->detect(frame, points);

    SANITY_CHECK_KEYPOINTS(points);
}

#include "perf_precomp.hpp"

using namespace std;
using namespace cv;
using namespace perf;
using std::tr1::make_tuple;
using std::tr1::get;

CV_ENUM(AgastType, AgastFeatureDetector::AGAST_5_8, AgastFeatureDetector::AGAST_7_12d,
                   AgastFeatureDetector::AGAST_7_12s, AgastFeatureDetector::OAST_9_16)

typedef std::tr1::tuple<string, AgastType> File_Type_t;
typedef perf::TestBaseWithParam<File_Type_t> agast;

#define AGAST_IMAGES \
    "cv/detectors_descriptors_evaluation/images_datasets/leuven/img1.png",\
    "stitching/a3.png"

PERF_TEST_P(agast, detect, testing::Combine(
                            testing::Values(AGAST_IMAGES),
                            AgastType::all()
                          ))
{
    string filename = getDataPath(get<0>(GetParam()));
    int type = get<1>(GetParam());
    Mat frame = imread(filename, IMREAD_GRAYSCALE);

    if (frame.empty())
        FAIL() << "Unable to load source image " << filename;

    declare.in(frame);

    Ptr<FeatureDetector> fd = AgastFeatureDetector::create(70, true, type);
    ASSERT_FALSE( fd.empty() );
    vector<KeyPoint> points;

    TEST_CYCLE() fd->detect(frame, points);

    SANITY_CHECK_KEYPOINTS(points);
}

Adjust AGAST perftest to be at parity (better) with FAST ones.