/*
 * Copyright 2021 The Android Open Source Project
 *
 * 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 <inttypes.h>
#include <cstddef>

#include <unwindstack/Memory.h>
#include <unwindstack/PeCoffInterface.h>

// The most basic fuzzer for PE/COFF parsing. Generates really poor coverage as
// it is not PE/COFF file structure aware.
extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) {
  std::shared_ptr<unwindstack::Memory> memory =
      unwindstack::Memory::CreateOfflineMemory(data, 0, size);
  unwindstack::PeCoffInterface<uint64_t> pe_coff_interface(memory.get());
  pe_coff_interface.Init();
  return 0;
}

/*
 * Copyright 2021 The Android Open Source Project
 *
 * 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 <inttypes.h>
#include <cstddef>

#include <unwindstack/Memory.h>
#include <unwindstack/PeCoffInterface.h>

namespace {
template <typename AddressType>
void FuzzPeCoffInterface(const uint8_t* data, size_t size) {
  std::shared_ptr<unwindstack::Memory> memory =
      unwindstack::Memory::CreateOfflineMemory(data, 0, size);
  unwindstack::PeCoffInterface<AddressType> pe_coff_interface(memory.get());
  pe_coff_interface.Init();
}
}  // namespace

// The most basic fuzzer for PE/COFF parsing, not PE/COFF structure aware.
extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) {
  FuzzPeCoffInterface<uint32_t>(data, size);
  FuzzPeCoffInterface<uint64_t>(data, size);
  return 0;
}

Add fuzzing for 32-bit PE/COFF files


#include "emptyScene.h"

void emptyScene::setup(){

//    parameters.add(param);

    loadCode("emptyScene/exampleCode.cpp");
}

void emptyScene::update(){

}

void emptyScene::draw(){

}

void emptyScene::drawCode(){
    string codeReplaced = getCodeWithParamsReplaced();
    ofDrawBitmapString(codeReplaced, 40,40);
}

#include "emptyScene.h"

void emptyScene::setup(){

//    parameters.add(param);

    loadCode("emptyScene/exampleCode.cpp");
}

void emptyScene::update(){

}

void emptyScene::draw(){
    drawCode();
}

void emptyScene::drawCode(){
    string codeReplaced = getCodeWithParamsReplaced();
    ofDrawBitmapString(codeReplaced, 40,40);
}

Update empty scene to draw code


#include <climits>
#include <cstdlib>
#include <cstring>
#include <unistd.h>
#include <iostream>
#include <algorithm>
#include <list>
#include <deque>
#include <vector>
#include <X11/keysym.h>
#include <xcb/xcb.h>
#include <xcb/xcb_atom.h>
#include <xcb/xcb_keysyms.h>
#include <xcb/damage.h>
#include <xcb/xinerama.h>
#include <xcb/composite.h>

#include "data_types.hpp"
#include "x_event_handler.hpp"
#include "x_connection.hpp"
#include "x_client.hpp"
#include "x_event_source.hpp"
#include "x_client_container.hpp"
#include "x_clients_preview.hpp"
#include "layout_t.hpp"
#include "grid.hpp"

int main(int argc, char ** argv)
{
  x_connection c;
  c.grab_key(XCB_MOD_MASK_4, XK_Tab);

  x_event_source es(c);
  x_client_container cc(c, es);

  grid_t grid;
  x_clients_preview cp(c, &grid, cc);

  es.register_handler(&c);
  es.register_handler(&cp);

  es.run_event_loop();

  return 0;
}

#include <xcb/xcb.h>
#include <X11/keysym.h>

#include "data_types.hpp"
#include "x_event_handler.hpp"
#include "x_connection.hpp"
#include "x_client.hpp"
#include "x_event_source.hpp"
#include "x_client_container.hpp"
#include "x_clients_preview.hpp"
#include "layout_t.hpp"
#include "grid.hpp"

int main(int argc, char ** argv)
{
  x_connection c;
  c.grab_key(XCB_MOD_MASK_4, XK_Tab);

  x_event_source es(c);
  x_client_container cc(c, es);

  grid_t grid;
  x_clients_preview cp(c, &grid, cc);

  es.register_handler(&c);
  es.register_handler(&cp);

  es.run_event_loop();

  return 0;
}

Remove superfluous headers from main file


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

// type_traits

// alignment_of

#include <type_traits>
#include <cstdint>

template <class T, unsigned A>
void test_alignment_of()
{
    static_assert( std::alignment_of<T>::value == A, "");
    static_assert( std::alignment_of<const T>::value == A, "");
    static_assert( std::alignment_of<volatile T>::value == A, "");
    static_assert( std::alignment_of<const volatile T>::value == A, "");
}

class Class
{
public:
    ~Class();
};

int main()
{
    test_alignment_of<int&, 4>();
    test_alignment_of<Class, 1>();
    test_alignment_of<int*, sizeof(intptr_t)>();
    test_alignment_of<const int*, sizeof(intptr_t)>();
    test_alignment_of<char[3], 1>();
    test_alignment_of<int, 4>();
    test_alignment_of<double, 8>();
    test_alignment_of<bool, 1>();
    test_alignment_of<unsigned, 4>();
}

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

// type_traits

// alignment_of

#include <type_traits>
#include <cstdint>

template <class T, unsigned A>
void test_alignment_of()
{
    static_assert( std::alignment_of<T>::value == A, "");
    static_assert( std::alignment_of<const T>::value == A, "");
    static_assert( std::alignment_of<volatile T>::value == A, "");
    static_assert( std::alignment_of<const volatile T>::value == A, "");
}

class Class
{
public:
    ~Class();
};

int main()
{
    test_alignment_of<int&, 4>();
    test_alignment_of<Class, 1>();
    test_alignment_of<int*, sizeof(intptr_t)>();
    test_alignment_of<const int*, sizeof(intptr_t)>();
    test_alignment_of<char[3], 1>();
    test_alignment_of<int, 4>();
    test_alignment_of<double, 8>();
#if (defined(__ppc__) && !defined(__ppc64__))
    test_alignment_of<bool, 4>();	// 32-bit PPC has four byte bool
#else
    test_alignment_of<bool, 1>();
#endif
    test_alignment_of<unsigned, 4>();
}

Fix erroneous test; was failing on darwin-ppc32. Fixes PR18469.


//== AnalysisManager.cpp - Path sensitive analysis data manager ----*- C++ -*-//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file implements the AnalysisManager class.
//
//===----------------------------------------------------------------------===//

#include "clang/Analysis/PathSensitive/AnalysisManager.h"
#include "clang/Basic/SourceManager.h"

using namespace clang;

void AnalysisManager::DisplayFunction(Decl *D) {

  if (DisplayedFunction)
    return;

  DisplayedFunction = true;

  // FIXME: Is getCodeDecl() always a named decl?
  if (isa<FunctionDecl>(D) || isa<ObjCMethodDecl>(D)) {
    const NamedDecl *ND = cast<NamedDecl>(D);
    SourceManager &SM = getASTContext().getSourceManager();
    llvm::errs() << "ANALYZE: "
                 << SM.getPresumedLoc(ND->getLocation()).getFilename()
                 << ' ' << ND->getNameAsString() << '\n';
  }
}

//== AnalysisManager.cpp - Path sensitive analysis data manager ----*- C++ -*-//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file implements the AnalysisManager class.
//
//===----------------------------------------------------------------------===//

#include "clang/Analysis/PathSensitive/AnalysisManager.h"
#include "clang/Basic/SourceManager.h"

using namespace clang;

void AnalysisManager::DisplayFunction(Decl *D) {

  if (DisplayedFunction)
    return;

  DisplayedFunction = true;

  // FIXME: Is getCodeDecl() always a named decl?
  if (isa<FunctionDecl>(D) || isa<ObjCMethodDecl>(D)) {
    const NamedDecl *ND = cast<NamedDecl>(D);
    SourceManager &SM = getASTContext().getSourceManager();
    (llvm::errs() << "ANALYZE: "
                  << SM.getPresumedLoc(ND->getLocation()).getFilename()
                  << ' ' << ND->getNameAsString() << '\n').flush();
  }
}

Fix 'clang-cc -analyzer-display-progress' by flushing standard error after printing the name of the analyzed function.


#include <gtest/gtest.h>
#include <graph/list_graph.hpp>

namespace {

class ListGraphTest : public ::testing::Test {
protected:
    ListGraphTest() {}
    virtual ~ListGraphTest() {}
    virtual void SetUp() {}
    virtual void TearDown() {}
};

}

TEST_F(ListGraphTest, add_vertex)
{
    ListGraph<false, int> g;
    EXPECT_EQ(0, g.vertex_num());

    g.add_vertex(Vertex<int>(2));
    EXPECT_EQ(3, g.vertex_num());

    EXPECT_EQ(-1, g.add_vertex(Vertex<int>(2)));
}

TEST_F(ListGraphTest, set_vertex)
{
    ListGraph<false, int> g;
    EXPECT_EQ(0, g.vertex_num());

    g.set_vertex(Vertex<int>(1, 4));
    EXPECT_EQ(2, g.vertex_num());
    EXPECT_EQ(4, g.vertex(1).data());

    g.set_vertex(Vertex<int>(1, 5));
    EXPECT_EQ(2, g.vertex_num());
    EXPECT_EQ(5, g.vertex(1).data());
}

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

#include <gtest/gtest.h>
#include <graph/list_graph.hpp>

namespace {

class ListGraphUndirectedTest : public ::testing::Test {
protected:
    ListGraph<false, int> g;
};

TEST_F(ListGraphUndirectedTest, test_add_vertex)
{
    EXPECT_EQ(0, g.vertex_num());
    g.add_vertex(Vertex<int>(2));
    EXPECT_EQ(3, g.vertex_num());
    EXPECT_EQ(-1, g.add_vertex(Vertex<int>(2)));
}

TEST_F(ListGraphUndirectedTest, test_set_vertex)
{
    EXPECT_EQ(0, g.vertex_num());

    g.set_vertex(Vertex<int>(1, 4));
    EXPECT_EQ(2, g.vertex_num());
    EXPECT_EQ(4, g.vertex(1).data());

    g.set_vertex(Vertex<int>(1, 5));
    EXPECT_EQ(2, g.vertex_num());
    EXPECT_EQ(5, g.vertex(1).data());
}

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

Fix tests: store graph in fixture class


#include <algorithm>
#include <chrono>
#include <cmath>
#include <iostream>
#include <string>
#include <sys/time.h>
#include <thread>

#include <rclcpp/rclcpp.hpp>

#include <simple_msgs/AllBuiltinTypes.h>
#include <simple_msgs/AllDynamicArrayTypes.h>
#include <simple_msgs/AllPrimitiveTypes.h>
#include <simple_msgs/AllStaticArrayTypes.h>
#include <simple_msgs/Nested.h>
#include <simple_msgs/String.h>
#include <simple_msgs/Uint32.h>

#include <userland_msgs/AddTwoInts.h>

void add(const std::shared_ptr<userland_msgs::AddTwoIntsRequest> req,
         std::shared_ptr<userland_msgs::AddTwoIntsResponse> res)
{
  std::cout << "Incoming request" << std::endl;
  res->sum = req->a + req->b;
}

int main(int argc, char** argv)
{
  rclcpp::init(argc, argv);

  auto node = rclcpp::Node::make_shared("add_two_ints_server");

  node->create_service<userland_msgs::AddTwoInts>("add_two_ints", add);

  rclcpp::spin(node);

  return 0;
}

#include <algorithm>
#include <chrono>
#include <cmath>
#include <iostream>
#include <string>
#include <sys/time.h>
#include <thread>

#include <rclcpp/rclcpp.hpp>

#include <simple_msgs/AllBuiltinTypes.h>
#include <simple_msgs/AllDynamicArrayTypes.h>
#include <simple_msgs/AllPrimitiveTypes.h>
#include <simple_msgs/AllStaticArrayTypes.h>
#include <simple_msgs/Nested.h>
#include <simple_msgs/String.h>
#include <simple_msgs/Uint32.h>

#include <userland_msgs/AddTwoInts.h>

void add(const std::shared_ptr<userland_msgs::AddTwoIntsRequestWithHeader> req,
         std::shared_ptr<userland_msgs::AddTwoIntsResponse> res)
{
  std::cout << "Incoming request" << std::endl;
  std::cout << "a: " << req->request.a << " b: " << req->request.b << std::endl;
  res->sum = req->request.a + req->request.b;
}

int main(int argc, char** argv)
{
  rclcpp::init(argc, argv);

  auto node = rclcpp::Node::make_shared("add_two_ints_server");

  node->create_service<userland_msgs::AddTwoInts>("add_two_ints", add);

  rclcpp::spin(node);

  return 0;
}

Move request header to a separate structure


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

// <functional>

// reference_wrapper

// Test that reference wrapper meets the requirements of TriviallyCopyable,
// CopyConstructible and CopyAssignable.

#include <functional>
#include <type_traits>

int main()
{
    typedef std::reference_wrapper<int> T;
    static_assert(std::is_copy_constructible<T>::value, "");
    static_assert(std::is_copy_assignable<T>::value, "");
    // Extension up for standardization: See N4151.
    static_assert(std::is_trivially_copyable<T>::value, "");
}

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

// <functional>

// reference_wrapper

// Test that reference wrapper meets the requirements of TriviallyCopyable,
// CopyConstructible and CopyAssignable.

#include <functional>
#include <type_traits>
#include <string>

#ifndef _LIBCPP_HAS_NO_RVALUE_REFERENCES
class MoveOnly
{
    MoveOnly(const MoveOnly&);
    MoveOnly& operator=(const MoveOnly&);

    int data_;
public:
    MoveOnly(int data = 1) : data_(data) {}
    MoveOnly(MoveOnly&& x)
        : data_(x.data_) {x.data_ = 0;}
    MoveOnly& operator=(MoveOnly&& x)
        {data_ = x.data_; x.data_ = 0; return *this;}

    int get() const {return data_;}
};
#endif

template <class T>
void test()
{
    typedef std::reference_wrapper<T> Wrap;
    static_assert(std::is_copy_constructible<Wrap>::value, "");
    static_assert(std::is_copy_assignable<Wrap>::value, "");
    // Extension up for standardization: See N4151.
    static_assert(std::is_trivially_copyable<Wrap>::value, "");
}

int main()
{
    test<int>();
    test<double>();
    test<std::string>();
#ifndef _LIBCPP_HAS_NO_RVALUE_REFERENCES
    test<MoveOnly>();
#endif
}

Add tests to ensure that reference_wrapper<T> is trivially copyable. This was added to C++1z with the adoption of N4277, but libc++ already implemented it as a conforming extension. No code changes were needed, just more tests.


//
//  ODCManager.cpp
//  opendatacon_suite
//
//  Created by Alan Murray on 6/06/2017.
//
//

#include <opendatacon/ODCManager.h>

namespace odc {
	ODCManager::ODCManager(
				  uint32_t concurrencyHint,
				  openpal::ICryptoProvider* crypto,
				  std::function<void()> onThreadStart,
				  std::function<void()> onThreadExit
			   ) :
	ios_working(new asio::io_service::work(IOS)),
	scheduler(IOS)
	{
		for (size_t i = 0; i < concurrencyHint; ++i)
			std::thread([&](){ IOS.run(); }).detach();
	}

}

//
//  ODCManager.cpp
//  opendatacon_suite
//
//  Created by Alan Murray on 6/06/2017.
//
//

#include <opendatacon/ODCManager.h>
#include <iostream>

namespace odc {
	ODCManager::ODCManager(
				  uint32_t concurrencyHint,
				  openpal::ICryptoProvider* crypto,
				  std::function<void()> onThreadStart,
				  std::function<void()> onThreadExit
			   ) :
	ios_working(new asio::io_service::work(IOS)),
	scheduler(IOS)
	{
		for (size_t i = 0; i < concurrencyHint; ++i)
			std::thread([&](){
				for (;;) {
					try {
						IOS.run();
						break;
					} catch (std::exception& e) {
						std::cout << "Exception: " << e.what() << std::endl;
						// TODO: work out what best to do
						// log exception
						// shutdown port, restart application?
					}

				}
			}).detach();
	}

}

Add exception handling to threads


#include <iostream>

#include "SparseReorderingFeature.h"

using namespace std;

namespace Moses
{

SparseReorderingFeature::SparseReorderingFeature(const std::string &line)
  :StatefulFeatureFunction("StatefulFeatureFunction", line)
{
  cerr << "Constructing a Sparse Reordering feature" << endl;
}

FFState* SparseReorderingFeature::EvaluateChart(
  const ChartHypothesis& /* cur_hypo */,
  int /* featureID - used to index the state in the previous hypotheses */,
  ScoreComponentCollection* accumulator) const
{
  return new SparseReorderingState();
}

}

#include <iostream>

#include "moses/ChartHypothesis.h"

#include "SparseReorderingFeature.h"

using namespace std;

namespace Moses
{

SparseReorderingFeature::SparseReorderingFeature(const std::string &line)
  :StatefulFeatureFunction("StatefulFeatureFunction",0, line)
{
  cerr << "Constructing a Sparse Reordering feature" << endl;
}

FFState* SparseReorderingFeature::EvaluateChart(
  const ChartHypothesis&  cur_hypo ,
  int  featureID /*- used to index the state in the previous hypotheses */,
  ScoreComponentCollection* accumulator) const
{
  // get index map for underlying hypotheses
  const AlignmentInfo::NonTermIndexMap &nonTermIndexMap =
    cur_hypo.GetCurrTargetPhrase().GetAlignNonTerm().GetNonTermIndexMap();

  return new SparseReorderingState();
}

}

Set dense feature count to 0


//
// This file is part of the Marble Virtual Globe.
//
// This program is free software licensed under the GNU LGPL. You can
// find a copy of this license in LICENSE.txt in the top directory of
// the source code.
//
// Copyright (C) 2012 Illya Kovalevskyy <illya.kovalevskyy@gmail.com>
//

#include "GeoSceneLicense.h"

namespace Marble
{

GeoSceneLicense::GeoSceneLicense() :
    m_attribution( OptOut )
{
    // nothing to do
}

QString GeoSceneLicense::license() const
{
    return m_fullLicense;
}

QString GeoSceneLicense::shortLicense() const
{
    return m_shortLicense;
}

GeoSceneLicense::Attribution GeoSceneLicense::attribution() const
{
    return m_attribution;
}

void GeoSceneLicense::setLicense(const QString &license )
{
    m_fullLicense = license;
}

void GeoSceneLicense::setShortLicense( const QString &license )
{
    m_shortLicense = license;
}

void GeoSceneLicense::setAttribution(Attribution attr )
{
    m_attribution = attr;
}

}

//
// This file is part of the Marble Virtual Globe.
//
// This program is free software licensed under the GNU LGPL. You can
// find a copy of this license in LICENSE.txt in the top directory of
// the source code.
//
// Copyright (C) 2012 Illya Kovalevskyy <illya.kovalevskyy@gmail.com>
//

#include "GeoSceneLicense.h"

namespace Marble
{

GeoSceneLicense::GeoSceneLicense() :
    m_attribution( OptOut )
{
    // nothing to do
}

QString GeoSceneLicense::license() const
{
    return m_fullLicense.isEmpty() ? m_shortLicense : m_fullLicense;
}

QString GeoSceneLicense::shortLicense() const
{
    return m_shortLicense.isEmpty() ? m_fullLicense : m_shortLicense;
}

GeoSceneLicense::Attribution GeoSceneLicense::attribution() const
{
    return m_attribution;
}

void GeoSceneLicense::setLicense(const QString &license )
{
    m_fullLicense = license;
}

void GeoSceneLicense::setShortLicense( const QString &license )
{
    m_shortLicense = license;
}

void GeoSceneLicense::setAttribution(Attribution attr )
{
    m_attribution = attr;
}

}

Use the short/full as fallback when the full/short is not set


#include <iostream>

#include "boost/program_options.hpp"

using namespace std;
namespace po = boost::program_options;

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

    // Declare the supported options.
    po::options_description desc("Accepted options");
    desc.add_options()
        ("help", "produce help message")
        ("temperature", "sort by temperature")
    ;

    po::variables_map vm;
    po::store(po::parse_command_line(argc, argv, desc), vm);
    po::notify(vm);

    if (vm.count("help")) {
        cout << desc << "\n";
        return 1;
    }

    if (vm.count("temperature")) {
        cout << "All righty, we'll sort by temperature.\n";
    } else {
        cout << "We'll sort randomly. Like a bawse.\n";
    }

    return 0;
}

#include <iostream>

#include "boost/program_options.hpp"

using namespace std;
namespace po = boost::program_options;

po::variables_map parse_args(int argc, char **argv) {
    po::options_description desc("Accepted options");
    desc.add_options()
        ("help", "produce help message")
        ("temp", "sort by temperature instead of location")
        ("location", po::value<vector<string> >(), "location(s)")
    ;

    po::positional_options_description p;
    p.add("location", -1);

    po::variables_map vm;
    po::store(po::command_line_parser(argc, argv).options(desc).positional(p).run(), vm);
    po::notify(vm);

    if (vm.count("help")) {
        cout << desc << "\n";
    }

    return vm;
}

int main(int argc, char **argv) {
    po::variables_map vm = parse_args(argc, argv);
    if (vm.count("help")) {
        return 1;
    }

    if (vm.count("location") == 0) {
        cerr << "No locations given" << endl;
        return 2;
    }

    if (vm.count("temp")) {
        cout << "All righty, we'll sort by temperature instead of location" << endl;
    }

    return 0;
}

Refactor program options and make them "temp" and "location"


#include "deviceinfo.h"
#include "log/logger.h"

#include <QCryptographicHash>
#include <QDir>
#include <fstab.h>

LOGGER(DeviceInfo);

DeviceInfo::DeviceInfo()
: d(NULL)
{
}

DeviceInfo::~DeviceInfo()
{
}

QString DeviceInfo::deviceId() const
{
    if (int ret = setfsent() != 1)
    {
        LOG_ERROR(QString("Error opening fstab: setfsent returned %1").arg(ret));
        return QString();
    }

    fstab* tab = getfsfile("/");
    if (!tab)
    {
        LOG_ERROR("Mount point / not found!");
        endfsent();
        return QString();
    }

    QByteArray uuid = QByteArray::fromRawData(tab->fs_spec, strlen(tab->fs_spec));

    if (uuid.indexOf("UUID=") == 0)
    {
        uuid.remove(0, 5);
    }
    else
    {
        LOG_ERROR(QString("fs_spec does not contain an UUID: %1").arg(QString::fromLatin1(uuid)));
    }

    endfsent();

    LOG_INFO(QString("HDD UUID: %1").arg(QString::fromLatin1(uuid)));

    QCryptographicHash hash(QCryptographicHash::Sha224);
    hash.addData(uuid);

    return QString::fromLatin1(hash.result().toHex());
}

#include "deviceinfo.h"
#include "log/logger.h"

#include <QCryptographicHash>
#include <QDir>
#include <fstab.h>

LOGGER(DeviceInfo);

namespace
{
    static const char* FSEntries[] = {
        "/",
        "/boot",
        NULL
    };
}

DeviceInfo::DeviceInfo()
: d(NULL)
{
}

DeviceInfo::~DeviceInfo()
{
}

QString DeviceInfo::deviceId() const
{
    if (int ret = setfsent() != 1)
    {
        LOG_ERROR(QString("Error opening fstab: setfsent returned %1").arg(ret));
        return QString();
    }

    QByteArray uuid;

    for(const char** fsentry=FSEntries; *fsentry != NULL; ++fsentry)
    {
        fstab* tab = getfsfile(*fsentry);
        if (!tab)
        {
            continue;
        }

        uuid = QByteArray::fromRawData(tab->fs_spec, strlen(tab->fs_spec));

        if (uuid.indexOf("UUID=") == 0)
        {
            uuid.remove(0, 5);
            break;
        }
        else
        {
            uuid.clear();
        }
    }

    endfsent();

    if (uuid.isEmpty())
    {
        LOG_ERROR("No HDD UID found!");
        return QString();
    }

    LOG_INFO(QString("HDD UUID: %1").arg(QString::fromLatin1(uuid)));

    QCryptographicHash hash(QCryptographicHash::Sha224);
    hash.addData(uuid);

    return QString::fromLatin1(hash.result().toHex());
}

Check / and /boot for uuids, not only /.


#include <iostream>
#include "../../Parser/Tagger/converter.h"

void testConverter(string sentence);

using namespace std;

int main()
{
    testConverter("This is a Bear");
    testConverter("That is not a building");       /// Bug , comma in dictionary
    testConverter("Who told you that?");
//    testConverter("That's what she said.");
    return 0;
}

/**
 * Test case for Converter class
 * @param none
 */
void testConverter(string sentence) {
    std::cout << "---   Testing Converter -----\n";
    try {

        NLP::Converter converted(sentence); // Passed
        list<NLP::Word> myParsedWords = converted.getWords();
        for(NLP::Word wd: myParsedWords)
            cout << wd << " : " << wd.getRawtypes() << endl;

    } catch (const char* e) {
        cout << "something went wrong : " << "Converter" << endl;
    }
    cout << "-------- End of Converter test case -----\n\n";
}

/** BUG
  * STokenize may not map all characters, if new character is found, just add
  * it to the token.h (UNKNOWN Token feature not working)
  */

#include <iostream>
#include "../../Parser/Tagger/converter.h"

void testConverter(string sentence);

using namespace std;

int main()
{
    testConverter("This is a Bear");
    testConverter("That is not a building");       /// Bug , comma in dictionary
    testConverter("Who told you that?");
    testConverter("That's what she said.");
    testConverter("In general, the dative marks the indirect object of a verb, although in some instances, the dative is used for the direct object of a verb pertaining directly to an act of giving something");
    testConverter("These pronouns are not proper datives anymore in modern English, because they are also used for functions of the accusative.");
    return 0;
}

/**
 * Test case for Converter class
 * @param none
 */
void testConverter(string sentence) {
    std::cout << "---   Testing Converter -----\n";
    try {

        NLP::Converter converted(sentence); // Passed
        list<NLP::Word> myParsedWords = converted.getWords();
        for(NLP::Word wd: myParsedWords)
            cout << wd << " : " << wd.getRawtypes() << endl;

    } catch (const char* e) {
        cout << "something went wrong : " << "Converter" << endl;
    }
    cout << "-------- End of Converter test case -----\n\n";
}

/** BUG
  * STokenize may not map all characters, if new character is found, just add
  * it to the token.h (UNKNOWN Token feature not working)
  */

Add more testcases with longer sentences


#include "demo/system/precompiled.h"

#if (DEA_PLATFORM == DEA_PLATFORM_WINDOWS)
#include <windows.h>
#endif

int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, PSTR pScmdline, int iCmdshow)
{
	/* Just the get this to compile for now */
	(void*)hInstance;
	(void*)hPrevInstance;
	(void*)pScmdline;
	--iCmdshow;

	return 0;
}

#include "demo/system/precompiled.h"
#include "engine/system/system.h"

DEA_START()

#if (DEA_PLATFORM == DEA_PLATFORM_WINDOWS)
#include <windows.h>

int WINAPI WinMain(HINSTANCE hinstance, HINSTANCE prev_instance, PSTR cmd_line, int cmd_show)
{
	/* Just the get this to compile for now */
	(void*)hinstance;
	(void*)prev_instance;
	(void*)cmd_line;
	--cmd_show;

	const bool fullscreen = false;
	window windows[2];
	create_window(1280, 720, 0.5f, 0.5f, L"Engine", fullscreen, windows[0]);
	create_window(600, 400, 0.0f, 0.0f, L"Editor", fullscreen, windows[1]);
	focus_window(windows[0]);

	run();

	destroy_window(windows[0], fullscreen);
	destroy_window(windows[1], fullscreen);

	return 0;
}
#else
#error No Main for current platform
#endif

DEA_END()

Create and destroy two windows


#include <iostream>
#include <memory>
#include <boost/interprocess/ipc/message_queue.hpp>

#include "messageQueue.h"

using namespace boost::interprocess;

int main()
{
    std::unique_ptr<message_queue> mq = nullptr;

    try {
        mq = std::make_unique<message_queue>(open_only, mqName);
    } catch (std::exception const&){
        std::cout << "Couldn't connect to the game. Make sure the game is running and try again." << std::endl;
        std::cout << "Press any key..." << std::endl;
        std::getchar();
        return 0;
    }

    std::string msg;
    for (;;) {
        std::getline(std::cin, msg);

        if (msg == "quit") {
            return 0;
        }

        mq->send(msg.data(), msg.size(), 0);
    }
}

#include <iostream>
#include <memory>
#include <fstream>
#include <boost/interprocess/ipc/message_queue.hpp>

#include "messageQueue.h"

using namespace boost::interprocess;

int main()
{
    std::unique_ptr<message_queue> mq = nullptr;

    try {
        mq = std::make_unique<message_queue>(open_only, mqName);
    } catch (std::exception const&){
        std::cout << "Couldn't connect to the game. Make sure the game is running and try again." << std::endl;
        std::cout << "Press any key..." << std::endl;
        std::getchar();
        return 0;
    }

    {
        std::ifstream initFile("vttainit.ini");
        if (initFile.good()) {
            std::string msg;
            while (std::getline(initFile, msg)) {
                std::cout << msg << std::endl;

                if (msg == "quit") {
                    return 0;
                }

                mq->send(msg.data(), msg.size(), 0);
            }
        }
    }

    std::string msg;
    for (;;) {
        std::getline(std::cin, msg);

        if (msg == "quit") {
            return 0;
        }

        mq->send(msg.data(), msg.size(), 0);
    }
}

Read initial commands from file


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

#include <config/config_type_int.h>

ConfigTypeInt config_type_int;

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

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

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

	ints_[cv] = imax;

	return (true);
}

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

#include <config/config_type_int.h>

ConfigTypeInt config_type_int;

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

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

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

	ints_[cv] = imax;

	return (true);
}

Use strtoll like strtoimax on Interix.


// RUN: %clang_cc1 -fsyntax-only -verify %s

// Clang used to crash trying to recover while adding 'this->' before Work(x);

template <typename> struct A {
  static void Work(int);  // expected-note{{must qualify identifier}}
};

template <typename T> struct B : public A<T> {
  template <typename T2> B(T2 x) {
    Work(x);  // expected-error{{use of undeclared identifier}}
  }
};

void Test() {
  B<int> b(0);  // expected-note{{in instantiation of function template}}
}

// Don't crash here.
namespace PR16134 {
  template <class P> struct S // expected-error {{expected ';'}}
  template <> static S<Q>::f() // expected-error +{{}}
}

Add testcase for PR16134, which no longer crashes with ToT.


#include "stdafx.h"
#include "myLevel.hpp"

MyLevel::MyLevel() : AnnAbstractLevel()
{
}

void MyLevel::load()
{
	//For having a lighter syntax :
	auto engine(AnnEngine::Instance());

	//Load Sinbad:
	auto Sinbad (engine->createGameObject("Sinbad.mesh"));
	Sinbad->setUpPhysics(100, phyShapeType::boxShape);
	//Add it to the level list
	levelContent.push_back(Sinbad);

	//Load Ground:
	auto Ground (engine->createGameObject("Ground.mesh"));
	Ground->setPos(0,-2,0);
	Ground->setUpPhysics();
	//Add it to the level list
	levelContent.push_back(Ground);

	//Create a light source
	auto light(engine->addLight());
	light->setPosition(0,1,3);
	//Add it to the level lst
	levelLighting.push_back(light);

	engine->setAmbiantLight(Ogre::ColourValue::White/2);

}

void MyLevel::runLogic()
{
}

#include "stdafx.h"
#include "myLevel.hpp"

MyLevel::MyLevel() : AnnAbstractLevel()
{
}

void MyLevel::load()
{
	//For having a lighter syntax :
	auto engine(AnnEngine::Instance());

	//Load Sinbad:
	auto Sinbad (engine->createGameObject("Sinbad.mesh"));
	Sinbad->setUpPhysics(100, phyShapeType::boxShape);
	//Add it to the level list
	levelContent.push_back(Sinbad);

	//Load Ground:
	auto Ground (engine->createGameObject("Ground.mesh"));
	Ground->setPos(0,-2,0);
	Ground->setUpPhysics();
	//Add it to the level list
	levelContent.push_back(Ground);

	//Create a light source
	auto light(engine->addLight());
	light->setPosition(AnnVect3(0,1,3));
	//Add it to the level lst
	levelLighting.push_back(light);

	engine->setAmbiantLight(Ogre::ColourValue::White/2);

}

void MyLevel::runLogic()
{
}

Make it compile on newer Annwvyn version


#include <cuda_runtime_api.h>
#include <stdio.h>

int main(void)
{
  int num_devices = 0;
  cudaGetDeviceCount(&num_devices);
  if(num_devices > 0)
  {
    cudaDeviceProp properties;
    cudaGetDeviceProperties(&properties, 0);
    printf("--gpu-architecture=sm_%d%d", properties.major, properties.minor);
    return 0;
  } // end if

  return -1;
}

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

void usage(const char *name)
{
  printf("usage: %s [device_id]\n", name);
}

int main(int argc, char **argv)
{
  int num_devices = 0;
  int device_id = 0;
  if(argc == 2)
  {
    device_id = atoi(argv[1]);
  }
  else if(argc > 2)
  {
    usage(argv[0]);
    exit(-1);
  }

  cudaGetDeviceCount(&num_devices);
  if(num_devices > device_id)
  {
    cudaDeviceProp properties;
    cudaGetDeviceProperties(&properties, device_id);
    printf("--gpu-architecture=sm_%d%d", properties.major, properties.minor);
    return 0;
  } // end if
  else
  {
    printf("No available device with id %d\n", device_id);
  }

  return -1;
}

Add an optional device_id command line argument.


#include <iostream>

#include "demo/demo.h"

int main()
{
    using namespace demo;
    // create demo
    Demo demo;

    // run demo
    demo.startup();
    demo.run();
    demo.shutdown();

    return 0;
}

#include <iostream>

#include "demo/demo.h"

int main()
{
    // create demo
    demo::Demo demo;

    // run demo
    demo.startup();
    demo.run();
    demo.shutdown();

    return 0;
}

Remove using since it is unnecessary.


#include <sensormanagerinterface.h>

int main()
{
    SensorManagerInterface* m_remoteSensorManager;
    m_remoteSensorManager = &SensorManagerInterface::instance();
    return 0;
}

#include <sensormanagerinterface.h>
#include <datatypes/magneticfield.h>

int main()
{
    SensorManagerInterface* m_remoteSensorManager;
    m_remoteSensorManager = &SensorManagerInterface::instance();
    return 0;
}

Add a header check to the sensord configure test.


/* -*- mode:linux -*- */
/**
 * \file completion_counter.cc
 *
 *
 *
 * \author Ethan Burns
 * \date 2008-10-24
 */

#include <pthread.h>

#include "completion_counter.h"
#include <iostream>;

CompletionCounter::CompletionCounter(unsigned int max)
	: counter(0), max(max)
{
	pthread_mutex_init(&mutex, NULL);
	pthread_cond_init(&cond, NULL);
}

void CompletionCounter::complete(void)
{
	pthread_mutex_lock(&mutex);
	counter += 1;
	pthread_cond_signal(&cond);
	pthread_mutex_unlock(&mutex);
}

/**
 * Wait for all the completions. (counter == max)
 */
void CompletionCounter::wait(void)
{
	pthread_mutex_lock(&mutex);
	while (counter < max)
		pthread_cond_wait(&cond, &mutex);
	pthread_mutex_unlock(&mutex);
}

/* -*- mode:linux -*- */
/**
 * \file completion_counter.cc
 *
 *
 *
 * \author Ethan Burns
 * \date 2008-10-24
 */

#include <pthread.h>

#include "completion_counter.h"
#include <iostream>

CompletionCounter::CompletionCounter(unsigned int max)
	: counter(0), max(max)
{
	pthread_mutex_init(&mutex, NULL);
	pthread_cond_init(&cond, NULL);
}

void CompletionCounter::complete(void)
{
	pthread_mutex_lock(&mutex);
	counter += 1;
	pthread_cond_signal(&cond);
	pthread_mutex_unlock(&mutex);
}

/**
 * Wait for all the completions. (counter == max)
 */
void CompletionCounter::wait(void)
{
	pthread_mutex_lock(&mutex);
	while (counter < max)
		pthread_cond_wait(&cond, &mutex);
	pthread_mutex_unlock(&mutex);
}

Remove a ; from after a pre-processor directive


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

#include "tac/Optimizer.hpp"

using namespace eddic;

void tac::Optimizer::optimize(tac::Program& program) const {
    //TODO
}

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

#include <boost/variant.hpp>

#include "tac/Optimizer.hpp"
#include "tac/Program.hpp"

using namespace eddic;

namespace {

struct ArithmeticIdentities : public boost::static_visitor<tac::Statement> {
    template<typename T>
    tac::Statement operator()(T& statement) const {
        return statement;
    }
};

}

template<typename Visitor>
void apply_to_all(Visitor visitor, tac::Program& program){
    for(auto& function : program.functions){
        for(auto& block : function->getBasicBlocks()){
            for(auto& statement : block->statements){
                statement = boost::apply_visitor(visitor, statement);
            }
        }
    }
}

void tac::Optimizer::optimize(tac::Program& program) const {
    ArithmeticIdentities identities;
    apply_to_all(identities, program);
}

Introduce the structure of the optimizer


#include <iostream>

#include <gtest/gtest.h>

#include <mongo/bson/bson.h>
#include <mongo/client/dbclient.h>

namespace {

    // Check that we can reproduce the example from bsonspec.org
    TEST(OID, gen) {
        const mongo::OID anOid = mongo::OID::gen();
    }

} // namespace

#include <gtest/gtest.h>
#include <mongo/bson/bson.h>

namespace {

    TEST(OID, gen) {
        const mongo::OID oid1 = mongo::OID::gen();
        const mongo::OID oid2 = mongo::OID::gen();
        EXPECT_NE(oid1, oid2);
    }

} // namespace

Clean up test a bit


#include <QtDebug>

#include "hsqml.h"
#include "HsQMLManager.h"
#include "HsQMLEngine.h"
#include "HsQMLObject.h"
#include "HsQMLWindow.h"

HsQMLEngine::HsQMLEngine(HsQMLEngineConfig& config)
{
  mEngine.rootContext()->setContextObject(config.globalObject->object());

  HsQMLWindow* win = new HsQMLWindow(this);
  win->setSource(config.initialURL);
  win->setVisible(true);
  mWindows.insert(win);
}

HsQMLEngine::~HsQMLEngine()
{
}

QDeclarativeEngine* HsQMLEngine::engine()
{
  return &mEngine;
}

extern "C" void hsqml_create_engine(
  HsQMLObjectHandle* globalObject,
  const char* initialURL)
{
  HsQMLEngineConfig config;
  config.globalObject = (HsQMLObjectProxy*)globalObject;
  config.initialURL = QUrl(QString(initialURL));

  Q_ASSERT (gManager);
  QMetaObject::invokeMethod(
    gManager, "createEngine", Qt::QueuedConnection,
    Q_ARG(HsQMLEngineConfig, config));
}

#include <QtDebug>

#include "hsqml.h"
#include "HsQMLManager.h"
#include "HsQMLEngine.h"
#include "HsQMLObject.h"
#include "HsQMLWindow.h"

HsQMLEngine::HsQMLEngine(HsQMLEngineConfig& config)
{
  // Obtain, re-parent, and set QML global object
  QObject* globalObject = config.globalObject->object();
  globalObject->setParent(this);
  mEngine.rootContext()->setContextObject(globalObject);

  // Create window
  HsQMLWindow* win = new HsQMLWindow(this);
  win->setSource(config.initialURL);
  win->setVisible(true);
  mWindows.insert(win);
}

HsQMLEngine::~HsQMLEngine()
{
}

QDeclarativeEngine* HsQMLEngine::engine()
{
  return &mEngine;
}

extern "C" void hsqml_create_engine(
  HsQMLObjectHandle* globalObject,
  const char* initialURL)
{
  HsQMLEngineConfig config;
  config.globalObject = (HsQMLObjectProxy*)globalObject;
  config.initialURL = QUrl(QString(initialURL));

  Q_ASSERT (gManager);
  QMetaObject::invokeMethod(
    gManager, "createEngine", Qt::QueuedConnection,
    Q_ARG(HsQMLEngineConfig, config));
}

Fix leaking QML global object on engine termination.


// RUN: %clang_cc1 -emit-llvm -triple=le32-unknown-nacl -o - %s | FileCheck %s

int f();

// Test that PNaCl uses the Itanium/x86 ABI in which the static
// variable's guard variable is tested via "load i8 and compare with
// zero" rather than the ARM ABI which uses "load i32 and test the
// bottom bit".
void g() {
  static int a = f();
}
// CHECK: load atomic i8* bitcast (i64* @_ZGVZ1gvE1a to i8*) acquire
// CHECK-NEXT: %guard.uninitialized = icmp eq i8 %0, 0
// CHECK-NEXT: br i1 %guard.uninitialized, label %init.check, label %init.end

// RUN: %clang_cc1 -emit-llvm -triple=le32-unknown-nacl -o - %s | FileCheck %s

int f();

// Test that PNaCl uses the Itanium/x86 ABI in which the static
// variable's guard variable is tested via "load i8 and compare with
// zero" rather than the ARM ABI which uses "load i32 and test the
// bottom bit".
void g() {
  static int a = f();
}
// CHECK: [[LOAD:%.*]] = load atomic i8* bitcast (i64* @_ZGVZ1gvE1a to i8*) acquire
// CHECK-NEXT: [[GUARD:%.*]] = icmp eq i8 [[LOAD]], 0
// CHECK-NEXT: br i1 [[GUARD]]

Make test pass in Release builds, IR names don't get emitted there.


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

#include "TexComp.h"

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

  if(argc != 2) {
    fprintf(stderr, "Usage: %s <imagefile>\n", argv[0]);
    exit(1);
  }

  ImageFile file (argv[1]);

  SCompressionSettings settings;
  CompressedImage *ci = CompressImage(file, settings);

  // Cleanup
  delete ci;
  return 0;
}

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

#include "TexComp.h"

void PrintUsage() {
   fprintf(stderr, "Usage: tc [-s|-t <num>] <imagefile>\n");
}

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

  int fileArg = 1;

  int quality = 50;
  int numThreads = 1;
  bool bUseSIMD = false;

  bool knowArg = false;
  do {
    knowArg = false;

    if(strcmp(argv[fileArg], "-s") == 0) {
      fileArg++;
      bUseSIMD = true;
      knowArg = true;
    }

    if(strcmp(argv[fileArg], "-t") == 0) {
      fileArg++;

      if(fileArg == argc || (numThreads = atoi(argv[fileArg])) < 1) {
	PrintUsage();
	exit(1);
      }

      fileArg++;
      knowArg = true;
    }

    if(strcmp(argv[fileArg], "-q") == 0) {
      fileArg++;

      if(fileArg == argc || (quality = atoi(argv[fileArg])) < 1) {
	PrintUsage();
	exit(1);
      }

      fileArg++;
      knowArg = true;
    }

  } while(knowArg);

  if(fileArg == argc) {
    PrintUsage();
    exit(1);
  }

  ImageFile file (argv[fileArg]);

  SCompressionSettings settings;
  settings.bUseSIMD = bUseSIMD;
  settings.iNumThreads = numThreads;

  CompressedImage *ci = CompressImage(file, settings);

  // Cleanup
  delete ci;
  return 0;
}

Add some more flag support to unix command line tool...


/**
 *  @copyright Copyright 2018 The J-PET Framework Authors. All rights reserved.
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may find a copy of the License in the LICENCE file.
 *
 * 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.
 *
 *  @file JPetSmearingFunctionsTest.cpp
 */

#define BOOST_TEST_DYN_LINK
#define BOOST_TEST_MODULE JPetSmearingFunctionsTest
#include <boost/test/unit_test.hpp>

#include "JPetSmearingFunctions/JPetSmearingFunctions.h"

BOOST_AUTO_TEST_SUITE(FirstSuite)

BOOST_AUTO_TEST_CASE(testOne)
{
  JPetHitExperimentalParametrizer parametrizer;
  parametrizer.addEnergySmearing(0,0,0);
  parametrizer.addZHitSmearing(0,0,0);
  parametrizer.addTimeSmearing(0,0,0,0);
}

BOOST_AUTO_TEST_SUITE_END()

/**
 *  @copyright Copyright 2018 The J-PET Framework Authors. All rights reserved.
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may find a copy of the License in the LICENCE file.
 *
 * 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.
 *
 *  @file JPetSmearingFunctionsTest.cpp
 */

#define BOOST_TEST_DYN_LINK
#define BOOST_TEST_MODULE JPetSmearingFunctionsTest
#include <boost/test/unit_test.hpp>

#include "JPetSmearingFunctions/JPetSmearingFunctions.h"

BOOST_AUTO_TEST_SUITE(FirstSuite)

BOOST_AUTO_TEST_CASE(testOne)
{
  JPetHitExperimentalParametrizer parametrizer;
  parametrizer.addEnergySmearing(1,1,1);
  parametrizer.addZHitSmearing(1,1,1);
  parametrizer.addTimeSmearing(1,1,1,1);
}

BOOST_AUTO_TEST_SUITE_END()

Change the smearing test values to non-zero


/* RTcmix  - Copyright (C) 2000  The RTcmix Development Team
   See ``AUTHORS'' for a list of contributors. See ``LICENSE'' for
   the license to this software and for a DISCLAIMER OF ALL WARRANTIES.
*/
#include <globals.h>
#include <ugens.h>
#include <iostream.h>
#include "Instrument.h"
#include "rtdefs.h"
#include "dbug.h"
#include <stdlib.h>

//extern double schedtime;

int Instrument::rtsetoutput(float start, float dur, Instrument *theInst)
{
// I know this is silly, but I wanted nsamps and I wanted it to
// look like "setnote" in orig cmix insts
  // DJT:  then perhaps we should call it rtsetnote?

  // DS: Adding check to be sure rtoutput() did not fail.

  if (rtfileit < 0) {
  	 die(theInst->name(), "rtsetoutput: No output file open for this instrument (rtoutput failed?)!");
  }

  theInst->_start = start;
  theInst->_dur = dur;
  theInst->nsamps = (int)(dur * SR);

  return(theInst->nsamps);
}

/* RTcmix  - Copyright (C) 2000  The RTcmix Development Team
   See ``AUTHORS'' for a list of contributors. See ``LICENSE'' for
   the license to this software and for a DISCLAIMER OF ALL WARRANTIES.
*/
#include <globals.h>
#include <ugens.h>
#include <iostream.h>
#include "Instrument.h"
#include "rtdefs.h"
#include "dbug.h"
#include <stdlib.h>

int Instrument::rtsetoutput(float start, float dur, Instrument *theInst)
{
	if (rtfileit < 0) {
		die(theInst->name(),
					"No output file open for this instrument (rtoutput failed?)!");
		return -1;
	}

	theInst->_start = start;
	theInst->_dur = dur;
	theInst->nsamps = (int) (dur * SR + 0.5);

	return 0;
}

Fix roundoff error setting nsamps; return status rather than nsamps.


// See LICENSE file for copyright and license details.

#include "ui/event/end_turn.hpp"
#include <cassert>
#include <SDL/SDL_opengl.h>
#include "core/misc.hpp"
#include "core/v2i.hpp"
#include "core/dir.hpp"
#include "core/core.hpp"
#include "core/path.hpp"
#include "ui/v2f.hpp"
#include "ui/vertex_array.hpp"
#include "ui/game.hpp"

EventEndTurnVisualizer::EventEndTurnVisualizer(Game& game, const Event& event)
  : EventVisualizer(game),
    mEventEndTurn(dynamic_cast<const EventEndTurn&>(event))
{
}

EventEndTurnVisualizer::~EventEndTurnVisualizer() {
}

int EventEndTurnVisualizer::framesCount() {
  return 0;
}

bool EventEndTurnVisualizer::isUnitVisible(const Unit& u) {
  UNUSED(u);
  return false;
}

void EventEndTurnVisualizer::draw() {
  // die("TODO"); // TODO: ...
}

void EventEndTurnVisualizer::end() {
  game().core().calculateFow();
  game().setVaFogOfWar(game().buildFowArray());
}

// See LICENSE file for copyright and license details.

#include "ui/event/end_turn.hpp"
#include <cassert>
#include <SDL/SDL_opengl.h>
#include "core/misc.hpp"
#include "core/v2i.hpp"
#include "core/dir.hpp"
#include "core/core.hpp"
#include "core/path.hpp"
#include "ui/v2f.hpp"
#include "ui/vertex_array.hpp"
#include "ui/game.hpp"

EventEndTurnVisualizer::EventEndTurnVisualizer(Game& game, const Event& event)
  : EventVisualizer(game),
    mEventEndTurn(dynamic_cast<const EventEndTurn&>(event))
{
}

EventEndTurnVisualizer::~EventEndTurnVisualizer() {
}

int EventEndTurnVisualizer::framesCount() {
  return 0;
}

bool EventEndTurnVisualizer::isUnitVisible(const Unit& u) {
  UNUSED(u);
  return false;
}

void EventEndTurnVisualizer::draw() {
  // die("TODO"); // TODO: ...
}

void EventEndTurnVisualizer::end() {
  game().core().calculateFow();
  game().setVaFogOfWar(game().buildFowArray());
  game().setVaWalkableMap(VertexArray());
}

Clear reachable tiles at the end of turn


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

#include "llvm/TargetTransformInfo.h"
#include "llvm/Support/ErrorHandling.h"

using namespace llvm;

/// Default ctor.
///
/// @note This has to exist, because this is a pass, but it should never be
/// used.
TargetTransformInfo::TargetTransformInfo() : ImmutablePass(ID) {
  report_fatal_error("Bad TargetTransformInfo ctor used.  "
                     "Tool did not specify a TargetTransformInfo to use?");
}

INITIALIZE_PASS(TargetTransformInfo, "TargetTransformInfo",
                "Target Transform Info", false, true)
char TargetTransformInfo::ID = 0;

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

#include "llvm/TargetTransformInfo.h"
#include "llvm/Support/ErrorHandling.h"

using namespace llvm;

/// Default ctor.
///
/// @note This has to exist, because this is a pass, but it should never be
/// used.
TargetTransformInfo::TargetTransformInfo() : ImmutablePass(ID) {
  /// You are seeing this error because your pass required the TTI
  /// using a call to "getAnalysis<TargetTransformInfo>()", and you did
  /// not initialize a machine target which can provide the TTI.
  /// You should use "getAnalysisIfAvailable<TargetTransformInfo>()" instead.
  report_fatal_error("Bad TargetTransformInfo ctor used.  "
                     "Tool did not specify a TargetTransformInfo to use?");
}

INITIALIZE_PASS(TargetTransformInfo, "TargetTransformInfo",
                "Target Transform Info", false, true)
char TargetTransformInfo::ID = 0;

Add a comment which explains why the assert fired and how to fix it.


//===- llvm/unittest/IR/TypesTest.cpp - Type unit tests -------------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//

#include "llvm/IR/DerivedTypes.h"
#include "llvm/IR/LLVMContext.h"
#include "gtest/gtest.h"
using namespace llvm;

namespace {

TEST(TypesTest, StructType) {
  LLVMContext C;

  // PR13522
  StructType *Struct = StructType::create(C, "FooBar");
  EXPECT_EQ("FooBar", Struct->getName());
  Struct->setName(Struct->getName().substr(0, 3));
  EXPECT_EQ("Foo", Struct->getName());
  Struct->setName("");
  EXPECT_TRUE(Struct->getName().empty());
  EXPECT_FALSE(Struct->hasName());
}

}  // end anonymous namespace

//===- llvm/unittest/IR/TypesTest.cpp - Type unit tests -------------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//

#include "llvm/IR/DerivedTypes.h"
#include "llvm/IR/LLVMContext.h"
#include "gtest/gtest.h"
using namespace llvm;

namespace {

TEST(TypesTest, StructType) {
  LLVMContext C;

  // PR13522
  StructType *Struct = StructType::create(C, "FooBar");
  EXPECT_EQ("FooBar", Struct->getName());
  Struct->setName(Struct->getName().substr(0, 3));
  EXPECT_EQ("Foo", Struct->getName());
  Struct->setName("");
  EXPECT_TRUE(Struct->getName().empty());
  EXPECT_FALSE(Struct->hasName());
}

TEST(TypesTest, LayoutIdenticalEmptyStructs) {
  LLVMContext C;

  StructType *Foo = StructType::create(C, "Foo");
  StructType *Bar = StructType::create(C, "Bar");
  EXPECT_TRUE(Foo->isLayoutIdentical(Bar));
}

}  // end anonymous namespace

Add unit test for isLayoutIdentical(empty, empty). It was previously asserting in Visual C++ debug mode on a null iterator passed to std::equal.


// 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 "base/basictypes.h"
#include "base/file_path.h"
#include "build/build_config.h"
#include "chrome/test/ui/ui_test.h"
#include "net/base/net_util.h"

class IFrameTest : public UITest {
 protected:
  void NavigateAndVerifyTitle(const char* url, const wchar_t* page_title) {
    FilePath test_file(test_data_directory_);
    test_file = test_file.AppendASCII(url);

    NavigateToURL(net::FilePathToFileURL(test_file));
    EXPECT_EQ(std::wstring(page_title), GetActiveTabTitle());
  }
};

TEST_F(IFrameTest, Crash) {
  NavigateAndVerifyTitle("iframe.html", L"iframe test");
}

TEST_F(IFrameTest, InEmptyFrame) {
  NavigateAndVerifyTitle("iframe_in_empty_frame.html", L"iframe test");
}

// 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 "base/basictypes.h"
#include "base/file_path.h"
#include "build/build_config.h"
#include "chrome/test/ui/ui_test.h"
#include "net/base/net_util.h"

class IFrameTest : public UITest {
 protected:
  void NavigateAndVerifyTitle(const char* url, const wchar_t* page_title) {
    FilePath test_file(test_data_directory_);
    test_file = test_file.AppendASCII(url);

    NavigateToURL(net::FilePathToFileURL(test_file));
    EXPECT_EQ(std::wstring(page_title), GetActiveTabTitle());
  }
};

TEST_F(IFrameTest, Crash) {
  NavigateAndVerifyTitle("iframe.html", L"iframe test");
}

// Fails consistently on Linux ChromeOS: http://crbug.com/100101
#if defined(OS_CHROMEOS)
#define MAYBE_InEmptyFrame FAILS_InEmptyFrame
#else
#define MAYBE_InEmptyFrame InEmptyFrame
#endif
TEST_F(IFrameTest, MAYBE_InEmptyFrame) {
  NavigateAndVerifyTitle("iframe_in_empty_frame.html", L"iframe test");
}

Mark IFrameTest.InEmptyFrame FAILS_ on OS_CHROMEOS.


// 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 "./frustum_optimizer.h"
#include "./nodes.h"

FrustumOptimizer::FrustumOptimizer(std::shared_ptr<Nodes> nodes) : nodes(nodes)
{
}

void FrustumOptimizer::update(Eigen::Matrix4f viewMatrix)
{
  float min = std::numeric_limits<float>::max();
  float max = -min;
  for (auto node : nodes->getNodes())
  {
    auto obb = node->getObb();
    if (!obb.get())
      continue;

    for (int i = 0; i < 8; ++i)
    {
      auto point = obb->corners[i];

      Eigen::Vector4f transformed = mul(viewMatrix, point);

      if (transformed.z() < min)
        min = transformed.z();

      if (transformed.z() > max)
        max = transformed.z();
    }
  }

  near = std::max(0.1f, -max - 0.1f);
  far = -min + 0.1f;
}

float FrustumOptimizer::getNear()
{
  return near;
}

float FrustumOptimizer::getFar()
{
  return far;
}

#include "./frustum_optimizer.h"
#include <limits>
#include <algorithm>
#include "./nodes.h"

FrustumOptimizer::FrustumOptimizer(std::shared_ptr<Nodes> nodes) : nodes(nodes)
{
}

void FrustumOptimizer::update(Eigen::Matrix4f viewMatrix)
{
  float min = std::numeric_limits<float>::max();
  float max = -min;
  for (auto node : nodes->getNodes())
  {
    auto obb = node->getObb();
    if (!obb.get())
      continue;

    for (int i = 0; i < 8; ++i)
    {
      auto point = obb->corners[i];

      Eigen::Vector4f transformed = mul(viewMatrix, point);

      if (transformed.z() < min)
        min = transformed.z();

      if (transformed.z() > max)
        max = transformed.z();
    }
  }

  near = std::max(0.1f, -max - 0.1f);
  far = -min + 0.1f;
}

float FrustumOptimizer::getNear()
{
  return near;
}

float FrustumOptimizer::getFar()
{
  return far;
}

Fix linting errors in FrustumOptimizer.


#include <dirent.h>
#include "../../../../runtime/types/InternalTypes.h"

void DirectoryType::__constructor__() {
    auto self = Program::create<DirectoryInstance>();
	auto file_path = Program::argument<TextInstance>();

	self->file_path = file_path->text();
	Program::push(self);
}

void DirectoryType::contents() {
	auto self = Program::argument<DirectoryInstance>();

    auto contents = Program::create<ListInstance>();
    auto directory = opendir(self->file_path.c_str());

    if (directory == nullptr) {
        throw Program::create<ExceptionInstance>(Program::create<TextInstance>("Cannot read directory contents"));
    }

    while(auto entry = readdir(directory)) {
        contents->val.push_back(Program::intern(new DirectoryEntryInstance(std::string(entry->d_name), entry->d_type)));
    }

    Program::push(contents);
}

std::string DirectoryInstance::text() {
	return "Directory(" + this->file_path + ")";
}

bool DirectoryInstance::boolean() {
	return true;
}

#include <dirent.h>
#include "../../../../runtime/types/InternalTypes.h"

void DirectoryType::__constructor__() {
    auto self = Program::create<DirectoryInstance>();
	auto file_path = Program::argument<TextInstance>();

	self->file_path = file_path->text();
	Program::push(self);
}

void DirectoryType::contents() {
	auto self = Program::argument<DirectoryInstance>();

    auto contents = Program::create<ListInstance>();
    auto directory = opendir(self->file_path.c_str());

    if (directory == nullptr) {
        throw Program::create<ExceptionInstance>(Program::create<TextInstance>("Cannot read file list of directory " + self->file_path));
    }

    while(auto entry = readdir(directory)) {
        contents->val.push_back(Program::intern(new DirectoryEntryInstance(std::string(entry->d_name), entry->d_type)));
    }

    Program::push(contents);
}

std::string DirectoryInstance::text() {
	return "Directory(" + this->file_path + ")";
}

bool DirectoryInstance::boolean() {
	return true;
}

Make directory exceptions more usable


#if defined(WIN32) && !defined(_DEBUG)
#pragma comment(linker, "/SUBSYSTEM:WINDOWS /entry:mainCRTStartup")
#endif

#include <memory>

#include <QFileInfo>

#include <gloperate-qt/viewer/Application.h>
#include <gloperate-qt/viewer/Viewer.h>

#include <widgetzeug/dark_fusion_style.hpp>

class Application : public gloperate_qt::Application
{
public:
    Application(int & argc, char ** argv)
    : gloperate_qt::Application(argc, argv)
    {
        const QFileInfo fi(QCoreApplication::applicationFilePath());

        QApplication::setApplicationDisplayName(fi.baseName());

        QApplication::setApplicationName("glexamples");
        QApplication::setApplicationVersion("1.0.0");

        QApplication::setOrganizationName("HPI Computer Graphics Systems Group");
        QApplication::setOrganizationDomain("https://github.com/hpicgs");
    }

    virtual ~Application() = default;
};

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

    widgetzeug::enableDarkFusionStyle();

    gloperate_qt::Viewer viewer;
    viewer.show();

    return app.exec();
}

#if defined(WIN32) && !defined(_DEBUG)
#pragma comment(linker, "/SUBSYSTEM:WINDOWS /entry:mainCRTStartup")
#endif

#include <memory>

#include <QFileInfo>

#include <gloperate-qt/viewer/Application.h>
#include <gloperate-qt/viewer/Viewer.h>

#include <widgetzeug/dark_fusion_style.hpp>

#include "glexamples-version.h"

class Application : public gloperate_qt::Application
{
public:
    Application(int & argc, char ** argv)
    : gloperate_qt::Application(argc, argv)
    {
        const QFileInfo fi(QCoreApplication::applicationFilePath());

        QApplication::setApplicationDisplayName(fi.baseName());

        QApplication::setApplicationName(GLEXAMPLES_PROJECT_NAME);
        QApplication::setApplicationVersion(GLEXAMPLES_VERSION);

        QApplication::setOrganizationName(GLEXAMPLES_AUTHOR_ORGANIZATION);
        QApplication::setOrganizationDomain(GLEXAMPLES_AUTHOR_DOMAIN);
    }

    virtual ~Application() = default;
};

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

    widgetzeug::enableDarkFusionStyle();

    gloperate_qt::Viewer viewer;
    viewer.show();

    return app.exec();
}

Use project definitions for version info


#include <stdint.h>
#include <stdio.h>
#include "impl.h"

int main(int /*argc*/, const char ** /*argv*/)
{
    SSE2NEON::SSE2NEONTest *test = SSE2NEON::SSE2NEONTest::create();
    uint32_t passCount = 0;
    uint32_t failedCount = 0;
    for (uint32_t i = 0; i < SSE2NEON::IT_LAST; i++) {
        SSE2NEON::InstructionTest it = SSE2NEON::InstructionTest(i);
        printf("Running Test %s\n",
               SSE2NEON::SSE2NEONTest::getInstructionTestString(it));
        bool ok = test->runTest(it);
        // If the test fails, we will run it again so we can step into the
        // debugger and figure out why!
        if (!ok) {
            printf("**FAILURE** SSE2NEONTest %s\n",
                   SSE2NEON::SSE2NEONTest::getInstructionTestString(it));
        }
        if (ok) {
            passCount++;
        } else {
            failedCount++;
        }
    }
    test->release();
    printf("SSE2NEONTest Complete: Passed %d tests : Failed %d\n", passCount,
           failedCount);

    return 0;
}

#include <stdint.h>
#include <stdio.h>
#include "impl.h"

int main(int /*argc*/, const char ** /*argv*/)
{
    SSE2NEON::SSE2NEONTest *test = SSE2NEON::SSE2NEONTest::create();
    uint32_t passCount = 0;
    uint32_t failedCount = 0;
    for (uint32_t i = 0; i < SSE2NEON::IT_LAST; i++) {
        SSE2NEON::InstructionTest it = SSE2NEON::InstructionTest(i);
        printf("Running Test %s\n",
               SSE2NEON::SSE2NEONTest::getInstructionTestString(it));
        bool ok = test->runTest(it);
        // If the test fails, we will run it again so we can step into the
        // debugger and figure out why!
        if (!ok) {
            printf("**FAILURE** SSE2NEONTest %s\n",
                   SSE2NEON::SSE2NEONTest::getInstructionTestString(it));
        }
        if (ok) {
            passCount++;
        } else {
            failedCount++;
        }
    }
    test->release();
    printf("SSE2NEONTest Complete: Passed %d tests : Failed %d\n", passCount,
           failedCount);

    return failedCount ? -1 : 0;
}

Return -1 exit code when unit test fails


/**
 ** \file libport/perror.cc
 ** \brief perror: implements file libport/perror.hh
 */

#include <cstdio>
#include <iostream>

#include "libport/cstring"

namespace libport
{

  void
  perror (const char* s)
  {
#ifndef WIN32
    ::perror(s);
#else
    int errnum;
    const char* errstring;
    const char* colon;

    errnum = WSAGetLastError();
    errstring = strerror(errnum);

    if (s == NULL || *s == '\0')
      s = colon = "";
    else
      colon = ": ";

    std::cerr << s << colon << errstring << std::endl;
#endif
  }

}

/**
 ** \file libport/perror.cc
 ** \brief perror: implements file libport/perror.hh
 */

#include <cstdio>
#include <iostream>

#include "libport/windows.hh"
#include "libport/cstring"

namespace libport
{

  void
  perror (const char* s)
  {
#ifndef WIN32
    ::perror(s);
#else
    int errnum;
    const char* errstring;
    const char* colon;

    errnum = WSAGetLastError();
    errstring = strerror(errnum);

    if (s == NULL || *s == '\0')
      s = colon = "";
    else
      colon = ": ";

    std::cerr << s << colon << errstring << std::endl;
#endif
  }

}

Add missing header for windows.


// RUN: %clang_cc1 -emit-llvm -g %s -o - | FileCheck %s
// Test that the line table info for Foo<T>::bar() is pointing to the
// right header file.
// CHECK: define{{.*}}bar
// CHECK-NOT: define
// CHECK: ret {{.*}}, !dbg ![[DBG:.*]]
// CHECK: ![[HPP:.*]] = metadata !{metadata !"./template.hpp",
// CHECK:![[BLOCK:.*]] = metadata !{{{.*}}, metadata ![[HPP]], {{.*}}} ; [ DW_TAG_lexical_block ]
// CHECK: [[DBG]] = metadata !{i32 23, i32 0, metadata ![[BLOCK]], null}
# 1 "./template.h" 1
template <typename T>
class Foo {
public:
 int bar();
};
# 21 "./template.hpp"
template <typename T>
int Foo<T>::bar() {
}
int main (int argc, const char * argv[])
{
  Foo<int> f;
  f.bar();
}

// RUN: %clang_cc1 -emit-llvm -g %s -o - | FileCheck %s
// Test that the line table info for Foo<T>::bar() is pointing to the
// right header file.
// CHECK: define{{.*}}bar
// CHECK-NOT: define
// CHECK: ret {{.*}}, !dbg ![[DBG:.*]]
// CHECK-DAG: ![[HPP:.*]] = metadata !{metadata !"./template.hpp",
// CHECK-DAG: ![[BLOCK:.*]] = metadata !{{{.*}}, metadata ![[HPP]], {{.*}}} ; [ DW_TAG_lexical_block ]
// CHECK-DAG: ![[DBG]] = metadata !{i32 23, i32 0, metadata ![[BLOCK]], null}
# 1 "./template.h" 1
template <typename T>
class Foo {
public:
 int bar();
};
# 21 "./template.hpp"
template <typename T>
int Foo<T>::bar() {
}
int main (int argc, const char * argv[])
{
  Foo<int> f;
  f.bar();
}

Use CHECK-DAG in a test so that it isn't sensitive to metadata order.


#include "Director.hpp"

#include "detail/env.hpp"

namespace Rice {

  Director::Director(Object self) {
    self_ = self;
  }

  bool Director::callIsFromRuby(const char* methodName) const {
    return (getSelf().value() == ruby_frame->self) && ( rb_id2name(ruby_frame->orig_func) != methodName );
  }

  void Director::raisePureVirtual() const {
    rb_raise(rb_eNotImpError, "Cannot call super() into a pure-virtual C++ method");
  }

}

#include "Director.hpp"

#include "detail/ruby.hpp"

#ifdef RUBY_VM
/* YARV */
#include "detail/cfp.hpp"
#else
/* pre-YARV */
#include "detail/env.hpp"
#endif

namespace Rice {

  Director::Director(Object self) {
    self_ = self;
  }

  bool Director::callIsFromRuby(const char* methodName) const {
#   ifdef RUBY_VM
    VALUE * cfp = Rice::detail::cfp();
    return
      (getSelf().value() == Rice::detail::cfp_self(cfp)) &&
      (rb_id2name(rb_frame_callee()) != methodName);
#   else
    return
      (getSelf().value() == ruby_frame->self) &&
      (rb_id2name(ruby_frame->orig_func) != methodName);
#   endif
  }

  void Director::raisePureVirtual() const {
    rb_raise(rb_eNotImpError, "Cannot call super() into a pure-virtual C++ method");
  }

}

Use cfp.hpp as an alternative to accessing ruby_frame directly.


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

#include "webkit/glue/resource_loader_bridge.h"

#include "net/http/http_response_headers.h"

namespace webkit_glue {

ResourceLoaderBridge::ResponseInfo::ResponseInfo() {
  content_length = -1;
#if defined(OS_WIN)
  response_data_file = base::kInvalidPlatformFileValue;
#elif defined(OS_POSIX)
  response_data_file.fd = base::kInvalidPlatformFileValue;
  response_data_file.auto_close = false;
#endif
}

ResourceLoaderBridge::ResponseInfo::~ResponseInfo() {
}

ResourceLoaderBridge::SyncLoadResponse::SyncLoadResponse() {
}

ResourceLoaderBridge::SyncLoadResponse::~SyncLoadResponse() {
}

ResourceLoaderBridge::ResourceLoaderBridge() {
}

ResourceLoaderBridge::~ResourceLoaderBridge() {
}

}  // namespace webkit_glue

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

#include "webkit/glue/resource_loader_bridge.h"
#include "webkit/glue/webappcachecontext.h"

#include "net/http/http_response_headers.h"

namespace webkit_glue {

ResourceLoaderBridge::ResponseInfo::ResponseInfo() {
  content_length = -1;
  app_cache_id = WebAppCacheContext::kNoAppCacheId;
#if defined(OS_WIN)
  response_data_file = base::kInvalidPlatformFileValue;
#elif defined(OS_POSIX)
  response_data_file.fd = base::kInvalidPlatformFileValue;
  response_data_file.auto_close = false;
#endif
}

ResourceLoaderBridge::ResponseInfo::~ResponseInfo() {
}

ResourceLoaderBridge::SyncLoadResponse::SyncLoadResponse() {
}

ResourceLoaderBridge::SyncLoadResponse::~SyncLoadResponse() {
}

ResourceLoaderBridge::ResourceLoaderBridge() {
}

ResourceLoaderBridge::~ResourceLoaderBridge() {
}

}  // namespace webkit_glue

Fix an issue found by purify with my previous submission.


// Microsoft compiler does not allow main to be in a library.
// So we define one here.

#include <urbi/umain.hh>

int
main(int argc, const char* argv[])
{
  return urbi::main(argc, argv);
}

// Microsoft compiler does not allow main to be in a library.
// So we define one here.

#include <urbi/umain.hh>
#include <libport/detect-win32.h>

#ifndef WIN32
 __attribute__((visibility("default")))
#endif
int
main(int argc, const char* argv[])
{
  return urbi::main(argc, argv);
}

Mark main with a default visibility.


#include "cli.h"
#include "../definitions.h"

bool flag_set(char** begin, char** end, const std::string& long_option) {
    return std::find(begin, end, long_option) != end;
}

Options get_options(int argc, char* argv[]) {
    char** begin = argv;
    char** end = argv + argc;

    if (argc < 2) {
        fatal_error("Please provide a ROM file to run");
    }

    bool debugger = flag_set(begin, end, "--debug");
    bool trace = flag_set(begin, end, "--trace");
    bool disable_logs = flag_set(begin, end, "--nolog");
    bool headless = flag_set(begin, end, "--headless");
    bool show_full_framebuffer = flag_set(begin, end, "--full-framebuffer");
    bool exit_on_infinite_jr = flag_set(begin, end, "--exit-on-infinite-jr");

    std::string filename = argv[1];

    return Options { debugger, trace, disable_logs, headless, show_full_framebuffer, exit_on_infinite_jr, filename };
}

LogLevel get_log_level(Options& options) {
    if (options.disable_logs) return LogLevel::Error;

    auto log_level = options.trace
        ? LogLevel::Trace
        : LogLevel::Debug;

    return log_level;
}

#include "cli.h"
#include "../definitions.h"

bool flag_set(char** begin, char** end, const std::string& long_option) {
    return std::find(begin, end, long_option) != end;
}

Options get_options(int argc, char* argv[]) {
    char** begin = argv;
    char** end = argv + argc;

    if (argc < 2) {
        fatal_error("Please provide a ROM file to run");
    }

    bool debugger = flag_set(begin, end, "--debug");
    bool trace = flag_set(begin, end, "--trace");
    bool disable_logs = flag_set(begin, end, "--silent");
    bool headless = flag_set(begin, end, "--headless");
    bool show_full_framebuffer = flag_set(begin, end, "--full-framebuffer");
    bool exit_on_infinite_jr = flag_set(begin, end, "--exit-on-infinite-jr");

    std::string filename = argv[1];

    return Options { debugger, trace, disable_logs, headless, show_full_framebuffer, exit_on_infinite_jr, filename };
}

LogLevel get_log_level(Options& options) {
    if (options.disable_logs) return LogLevel::Error;

    auto log_level = options.trace
        ? LogLevel::Trace
        : LogLevel::Debug;

    return log_level;
}

Use --silent instead of --nolog to disable logs


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

The Medical Imaging Interaction Toolkit (MITK)

Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics.
All rights reserved.

This software is distributed WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE.

See LICENSE.txt or http://www.mitk.org for details.

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

#include "mitkUSUIActivator.h"
#include "QmitkUSControlsCustomVideoDeviceWidget.h"
#include "QmitkUSControlsCustomDiPhASDeviceWidget.h"

mitk::USUIActivator::USUIActivator()
{
}

mitk::USUIActivator::~USUIActivator()
{
}

void mitk::USUIActivator::Load(us::ModuleContext* context)
{
  m_USCustomWidgets.push_back(new QmitkUSControlsCustomVideoDeviceWidget());
  m_USCustomWidgets.push_back(new QmitkUSControlsCustomDiPhASDeviceWidget());
}

void mitk::USUIActivator::Unload(us::ModuleContext* /*context*/)
{
  for (auto &elem : m_USCustomWidgets)
  {
    delete elem;
  }
}

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

The Medical Imaging Interaction Toolkit (MITK)

Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics.
All rights reserved.

This software is distributed WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE.

See LICENSE.txt or http://www.mitk.org for details.

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

#include "mitkUSUIActivator.h"
#include "QmitkUSControlsCustomVideoDeviceWidget.h"
#include "QmitkUSControlsCustomDiPhASDeviceWidget.h"

mitk::USUIActivator::USUIActivator()
{
}

mitk::USUIActivator::~USUIActivator()
{
}

void mitk::USUIActivator::Load(us::ModuleContext* /*context*/)
{
  m_USCustomWidgets.push_back(new QmitkUSControlsCustomVideoDeviceWidget());
  m_USCustomWidgets.push_back(new QmitkUSControlsCustomDiPhASDeviceWidget());
}

void mitk::USUIActivator::Unload(us::ModuleContext* /*context*/)
{
  for (auto &elem : m_USCustomWidgets)
  {
    delete elem;
  }
}

Fix follow-up compilation error raised due to warnings treated as errors


#include <memory>
#include "film/color.h"
#include "material/bsdf.h"
#include "material/blinn_distribution.h"
#include "material/anisotropic_distribution.h"
#include "material/torrance_sparrow.h"
#include "material/lambertian.h"
#include "material/fresnel.h"
#include "material/plastic_material.h"

PlasticMaterial::PlasticMaterial(const Texture *diffuse, const Texture *specular, float roughness)
	: diffuse(diffuse), specular(specular), roughness(roughness)
{}
BSDF PlasticMaterial::get_bsdf(const DifferentialGeometry &dg) const {
	BSDF bsdf{dg};
	Colorf kd = diffuse->sample(dg).normalized();
	Colorf ks = specular->sample(dg).normalized();
	bsdf.add(std::make_unique<Lambertian>(kd));
	bsdf.add(std::make_unique<TorranceSparrow>(ks,
		std::make_unique<FresnelDielectric>(1.5, 1),
		std::make_unique<AnisotropicDistribution>(1.f / roughness, 10 / roughness)));
	return bsdf;
}

#include <memory>
#include "film/color.h"
#include "material/bsdf.h"
#include "material/blinn_distribution.h"
#include "material/torrance_sparrow.h"
#include "material/lambertian.h"
#include "material/fresnel.h"
#include "material/plastic_material.h"

PlasticMaterial::PlasticMaterial(const Texture *diffuse, const Texture *specular, float roughness)
	: diffuse(diffuse), specular(specular), roughness(roughness)
{}
BSDF PlasticMaterial::get_bsdf(const DifferentialGeometry &dg) const {
	BSDF bsdf{dg};
	Colorf kd = diffuse->sample(dg).normalized();
	Colorf ks = specular->sample(dg).normalized();
	bsdf.add(std::make_unique<Lambertian>(kd));
	bsdf.add(std::make_unique<TorranceSparrow>(ks,
		std::make_unique<FresnelDielectric>(1.5, 1),
		std::make_unique<BlinnDistribution>(1.f / roughness)));
	return bsdf;
}

Revert plastic back to be plastic


// RUN: not %clang_cc1 %s -fno-rtti -triple=i686-pc-win32 -emit-llvm -o /dev/null 2>&1 | FileCheck --check-prefix=CHECK32
// RUN: %clang_cc1 %s -fno-rtti -triple=x86_64-pc-win32 -emit-llvm -o - | FileCheck --check-prefix=CHECK64

namespace byval_thunk {
struct Agg {
  Agg();
  Agg(const Agg &);
  ~Agg();
  int x;
};

struct A { virtual void foo(Agg x); };
struct B { virtual void foo(Agg x); };
struct C : A, B { virtual void foo(Agg x); };
C c;

// CHECK32: cannot compile this non-trivial argument copy for thunk yet

// CHECK64-LABEL: define linkonce_odr void @"\01?foo@C@byval_thunk@@W7EAAXUAgg@2@@Z"
// CHECK64:             (%"struct.byval_thunk::C"* %this, %"struct.byval_thunk::Agg"* %x)
// CHECK64:   getelementptr i8* %{{.*}}, i32 -8
// CHECK64:   call void @"\01?foo@C@byval_thunk@@UEAAXUAgg@2@@Z"(%"struct.byval_thunk::C"* %2, %"struct.byval_thunk::Agg"* %x)
// CHECK64-NOT: call
// CHECK64:   ret void
}

// RUN: not %clang_cc1 %s -fno-rtti -triple=i686-pc-win32 -emit-llvm -o /dev/null 2>&1 | FileCheck --check-prefix=CHECK32 %s
// RUN: %clang_cc1 %s -fno-rtti -triple=x86_64-pc-win32 -emit-llvm -o - | FileCheck --check-prefix=CHECK64 %s

namespace byval_thunk {
struct Agg {
  Agg();
  Agg(const Agg &);
  ~Agg();
  int x;
};

struct A { virtual void foo(Agg x); };
struct B { virtual void foo(Agg x); };
struct C : A, B { virtual void foo(Agg x); };
C c;

// CHECK32: cannot compile this non-trivial argument copy for thunk yet

// CHECK64-LABEL: define linkonce_odr void @"\01?foo@C@byval_thunk@@W7EAAXUAgg@2@@Z"
// CHECK64:             (%"struct.byval_thunk::C"* %this, %"struct.byval_thunk::Agg"* %x)
// CHECK64:   getelementptr i8* %{{.*}}, i32 -8
// CHECK64:   call void @"\01?foo@C@byval_thunk@@UEAAXUAgg@2@@Z"(%"struct.byval_thunk::C"* %2, %"struct.byval_thunk::Agg"* %x)
// CHECK64-NOT: call
// CHECK64:   ret void
}

Fix my busted FileCheck invocation


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

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

Remove confusing transpose() in setLinSpaced() docs.


#include <iostream>

using namespace std;

#include <QCoreApplication>
#include <QDebug>
#include <QTest>

#include "canpie_frame.hpp"
#include "canpie_frame_error.hpp"
#include "test_canpie_timestamp.hpp"
#include "test_qcan_frame.hpp"
#include "test_qcan_socket.hpp"

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

   cout << "#===========================================================\n";
   cout << "# Run test cases for QCan classes                           \n";
   cout << "#                                                           \n";
   cout << "#===========================================================\n";
   cout << "\n";

   //----------------------------------------------------------------
   // test CpTimestamp
   //
   TestCpTimestamp  clTestCpTimestampT;
   slResultT = QTest::qExec(&clTestCpTimestampT, argc, &argv[0]);

   //----------------------------------------------------------------
   // test QCanFrame
   //
   TestQCanFrame  clTestQCanFrameT;
   slResultT = QTest::qExec(&clTestQCanFrameT, argc, &argv[0]);

   //----------------------------------------------------------------
   // test QCanStub
   //
   TestQCanSocket  clTestQCanSockT;
   slResultT = QTest::qExec(&clTestQCanSockT) + slResultT;

   cout << "\n";
   cout << "#===========================================================\n";
   cout << "# Total result                                              \n";
   cout << "# " << slResultT << " test cases failed                     \n";
   cout << "#===========================================================\n";

}

Add additional indlude files for future tests


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

#include "SkCanvas.h"
#include "SkPaint.h"
#include "SkRegion.h"
#include "SkSurface.h"

bool FuzzRegionDeserialize(sk_sp<SkData> bytes) {
    SkRegion region;
    if (!region.readFromMemory(bytes->data(), bytes->size())) {
        return false;
    }
    region.computeRegionComplexity();
    region.isComplex();
    SkRegion r2;
    if (region == r2) {
        region.contains(0,0);
    } else {
        region.contains(1,1);
    }
    auto s = SkSurface::MakeRasterN32Premul(1024, 1024);
    s->getCanvas()->drawRegion(region, SkPaint());
    SkDEBUGCODE(region.validate());
    return true;
}

#if defined(IS_FUZZING_WITH_LIBFUZZER)
extern "C" int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) {
    auto bytes = SkData::MakeWithoutCopy(data, size);
    FuzzRegionDeserialize(bytes);
    return 0;
}
#endif

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

#include "SkCanvas.h"
#include "SkPaint.h"
#include "SkRegion.h"
#include "SkSurface.h"

bool FuzzRegionDeserialize(sk_sp<SkData> bytes) {
    SkRegion region;
    if (!region.readFromMemory(bytes->data(), bytes->size())) {
        return false;
    }
    region.computeRegionComplexity();
    region.isComplex();
    SkRegion r2;
    if (region == r2) {
        region.contains(0,0);
    } else {
        region.contains(1,1);
    }
    auto s = SkSurface::MakeRasterN32Premul(128, 128);
    if (!s) {
        // May return nullptr in memory-constrained fuzzing environments
        return false;
    }
    s->getCanvas()->drawRegion(region, SkPaint());
    SkDEBUGCODE(region.validate());
    return true;
}

#if defined(IS_FUZZING_WITH_LIBFUZZER)
extern "C" int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) {
    auto bytes = SkData::MakeWithoutCopy(data, size);
    FuzzRegionDeserialize(bytes);
    return 0;
}
#endif

Check for nullptrs when fuzzing region_deserialize


#include <GL/glew.h>
#include <SDL2/SDL.h>

int main(void)
{
  int flags = SDL_WINDOW_OPENGL | SDL_RENDERER_PRESENTVSYNC;

  SDL_Init(SDL_INIT_EVERYTHING);
  auto window = SDL_CreateWindow("title", 0, 0, 320, 240, flags);
  auto context = SDL_GL_CreateContext(window);

  glewInit();
  glClearColor(0, 1, 0, 1);
  glClear(GL_COLOR_BUFFER_BIT);

  SDL_Event event;
  while (true)
  {
    while (SDL_PollEvent(&event))
      if (event.type == SDL_QUIT)
        goto quit;
      else if (event.type == SDL_KEYDOWN)
        switch (event.key.keysym.sym)
        {
          case SDLK_ESCAPE:
            goto quit;
            break;
        }
    SDL_Delay(10);
    SDL_GL_SwapWindow(window);
  }

quit:
  SDL_DestroyWindow(window);
  SDL_Quit();
  return 0;
}

#include <GL/glew.h>
#include <SDL2/SDL.h>

int main(void)
{
  int flags = SDL_WINDOW_OPENGL | SDL_RENDERER_PRESENTVSYNC;

  SDL_Init(SDL_INIT_EVERYTHING);
  auto window = SDL_CreateWindow("Warg", 0, 0, 320, 240, flags);
  auto context = SDL_GL_CreateContext(window);

  glewInit();
  glClearColor(0, 1, 0, 1);
  glClear(GL_COLOR_BUFFER_BIT);

  SDL_Event event;
  while (true)
  {
    while (SDL_PollEvent(&event))
      if (event.type == SDL_QUIT)
        goto quit;
      else if (event.type == SDL_KEYDOWN)
        switch (event.key.keysym.sym)
        {
          case SDLK_ESCAPE:
            goto quit;
            break;
        }
    SDL_Delay(10);
    SDL_GL_SwapWindow(window);
  }

quit:
  SDL_DestroyWindow(window);
  SDL_Quit();
  return 0;
}

Change window title to 'Warg'


/**
 * \file
 * \brief lowLevelInitialization() implementation for ARMv6-M and ARMv7-M
 *
 * \author Copyright (C) 2015 Kamil Szczygiel http://www.distortec.com http://www.freddiechopin.info
 *
 * \par License
 * This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not
 * distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
 */

#include "distortos/architecture/lowLevelInitialization.hpp"

#include "distortos/chip/CMSIS-proxy.h"

namespace distortos
{

namespace architecture
{

/*---------------------------------------------------------------------------------------------------------------------+
| global functions
+---------------------------------------------------------------------------------------------------------------------*/

void lowLevelInitialization()
{
#if __FPU_PRESENT == 1 && __FPU_USED == 1
	SCB->CPACR |= (3 << 10 * 2) | (3 << 11 * 2);	// full access to CP10 and CP11
#endif	// __FPU_PRESENT == 1 && __FPU_USED == 1
}

}	// namespace architecture

}	// namespace distortos

/**
 * \file
 * \brief lowLevelInitialization() implementation for ARMv6-M and ARMv7-M
 *
 * \author Copyright (C) 2015 Kamil Szczygiel http://www.distortec.com http://www.freddiechopin.info
 *
 * \par License
 * This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not
 * distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
 */

#include "distortos/architecture/lowLevelInitialization.hpp"

#include "distortos/chip/CMSIS-proxy.h"

namespace distortos
{

namespace architecture
{

/*---------------------------------------------------------------------------------------------------------------------+
| global functions
+---------------------------------------------------------------------------------------------------------------------*/

void lowLevelInitialization()
{
#ifdef CONFIG_ARCHITECTURE_ARM_CORTEX_M3_R1P1
	SCB->CCR |= SCB_CCR_STKALIGN_Msk;
#endif	// def CONFIG_ARCHITECTURE_ARM_CORTEX_M3_R1P1
#if __FPU_PRESENT == 1 && __FPU_USED == 1
	SCB->CPACR |= (3 << 10 * 2) | (3 << 11 * 2);	// full access to CP10 and CP11
#endif	// __FPU_PRESENT == 1 && __FPU_USED == 1
}

}	// namespace architecture

}	// namespace distortos

Set STKALIGN bit in SCB->CCR for ARM Cortex-M3 r1p1


#include <iostream>
#include <string>
#include <utility>

#include "pool.h"

void Pool::add_machine(const Machine& new_machine)
{
    const std::string& machine_name = new_machine.get_name();

    std::cout << "Adding machine to pool: " << machine_name << std::endl;
    machines.insert(std::make_pair(machine_name, new_machine));
}

void Pool::add_job(const Job& new_job)
{
    const int job_id = new_job.get_id();
    const std::string& machine_name = new_job.get_machine();

    std::cout << "Adding job to pool: " << job_id << " (" << machine_name << ")" << std::endl;
    jobs.insert(std::make_pair(job_id, new_job));

    std::map<std::string, Machine>::iterator iter = machines.find(machine_name);
    if (iter != machines.end()) {
        std::cout << "Adding job to machine: " << machine_name << std::endl;
        iter->second.add_job(new_job);
    }
}

#include <iostream>
#include <string>
#include <utility>

#include "pool.h"

void Pool::add_machine(const Machine& new_machine)
{
    const std::string& machine_name = new_machine.get_name();

    std::cout << "Adding machine to pool: " << machine_name << std::endl;
    machines.insert(std::make_pair(machine_name, new_machine));
}

void Pool::add_job(const Job& new_job)
{
    const int job_id = new_job.get_id();
    const std::string& machine_name = new_job.get_machine();

    std::cout << "Adding job to pool: " << job_id << " (" << machine_name << ")" << std::endl;
    jobs.insert(std::make_pair(job_id, new_job));

    auto iter = machines.find(machine_name);
    if (iter != machines.end()) {
        std::cout << "Adding job to machine: " << machine_name << std::endl;
        iter->second.add_job(new_job);
    }
}

Use 'auto' for iterator type.


// 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 "views/controls/menu/menu_config.h"

#include "grit/app_resources.h"
#include "third_party/skia/include/core/SkBitmap.h"
#include "ui/base/resource/resource_bundle.h"

namespace views {

// static
MenuConfig* MenuConfig::Create() {
  MenuConfig* config = new MenuConfig();
  ResourceBundle& rb = ResourceBundle::GetSharedInstance();
  config->font = rb.GetFont(ResourceBundle::BaseFont);
  config->arrow_width = rb.GetBitmapNamed(IDR_MENU_ARROW)->width();
  // Add 4 to force some padding between check and label.
  config->check_width = rb.GetBitmapNamed(IDR_MENU_CHECK)->width() + 4;
  config->check_height = rb.GetBitmapNamed(IDR_MENU_CHECK)->height();
  return config;
}

}  // namespace views

// 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 "views/controls/menu/menu_config.h"

#include "grit/app_resources.h"
#include "third_party/skia/include/core/SkBitmap.h"
#include "ui/base/resource/resource_bundle.h"

namespace views {

// static
MenuConfig* MenuConfig::Create() {
  MenuConfig* config = new MenuConfig();
  ResourceBundle& rb = ResourceBundle::GetSharedInstance();
#if defined(TOUCH_UI)
  config->font = rb.GetFont(ResourceBundle::LargeFont);
#else
  config->font = rb.GetFont(ResourceBundle::BaseFont);
#endif
  config->arrow_width = rb.GetBitmapNamed(IDR_MENU_ARROW)->width();
  // Add 4 to force some padding between check and label.
  config->check_width = rb.GetBitmapNamed(IDR_MENU_CHECK)->width() + 4;
  config->check_height = rb.GetBitmapNamed(IDR_MENU_CHECK)->height();
  return config;
}

}  // namespace views

Increase the base font size for touch ui


// RUN: %clang_cc1 -analyze -analyzer-checker=core -analyzer-store=region -verify %s
// expected-no-diagnostics

bool PR14634(int x) {
  double y = (double)x;
  return !y;
}

bool PR14634_implicit(int x) {
  double y = (double)x;
  return y;
}

void intAsBoolAsSwitchCondition(int c) {
  switch ((bool)c) {
  case 0:
    break;
  }
}

// RUN: %clang_cc1 -analyze -analyzer-checker=core -analyzer-store=region -verify %s

bool PR14634(int x) {
  double y = (double)x;
  return !y;
}

bool PR14634_implicit(int x) {
  double y = (double)x;
  return y;
}

void intAsBoolAsSwitchCondition(int c) {
  switch ((bool)c) { // expected-warning {{switch condition has boolean value}}
  case 0:
    break;
  }

  switch ((int)(bool)c) { // no-warning
    case 0:
      break;
  }
}

Fix test in previous commit to account for compiler warning.


// RUN: %clang_cc1 -emit-llvm  -triple=armv7-apple-darwin -std=c++11 %s -o - -O1 \
// RUN:    | FileCheck %s
// RUN: %clang_cc1 -emit-llvm -triple=armv7-apple-darwin -std=c++11 %s -o - -O1 \
// RUN:    -discard-value-names | FileCheck %s --check-prefix=DISCARDVALUE

extern "C" void branch();

bool test(bool pred) {
  // DISCARDVALUE: br i1 %0, label %2, label %3
  // CHECK: br i1 %pred, label %if.then, label %if.end

  if (pred) {
    // DISCARDVALUE: ; <label>:2:
    // DISCARDVALUE-NEXT: tail call void @branch()
    // DISCARDVALUE-NEXT: br label %3

    // CHECK: if.then:
    // CHECK-NEXT: tail call void @branch()
    // CHECK-NEXT: br label %if.end
    branch();
  }

  // DISCARDVALUE: ; <label>:3:
  // DISCARDVALUE-NEXT: ret i1 %0

  // CHECK: if.end:
  // CHECK-NEXT: ret i1 %pred
  return pred;
}

// RUN: %clang_cc1 -emit-llvm  -triple=armv7-apple-darwin -std=c++11 %s -o - -O1 \
// RUN:    | FileCheck %s
// RUN: %clang_cc1 -emit-llvm -triple=armv7-apple-darwin -std=c++11 %s -o - -O1 \
// RUN:    -discard-value-names | FileCheck %s --check-prefix=DISCARDVALUE

extern "C" void branch();

bool test(bool pred) {
  // DISCARDVALUE: br i1 %0, label %2, label %3
  // CHECK: br i1 %pred, label %if.then, label %if.end

  if (pred) {
    // DISCARDVALUE: 2:
    // DISCARDVALUE-NEXT: tail call void @branch()
    // DISCARDVALUE-NEXT: br label %3

    // CHECK: if.then:
    // CHECK-NEXT: tail call void @branch()
    // CHECK-NEXT: br label %if.end
    branch();
  }

  // DISCARDVALUE: 3:
  // DISCARDVALUE-NEXT: ret i1 %0

  // CHECK: if.end:
  // CHECK-NEXT: ret i1 %pred
  return pred;
}

Support parsing numeric block ids, and emit them in textual output.


// RUN: %clang_cc1 -x c++-module-map %s -fmodule-name=a -verify
module a {
  module b {
    requires cplusplus11
  }
}
#pragma clang module contents
// expected-error@3 {{module 'a.b' requires feature 'cplusplus11'}}
#pragma clang module begin a.b // expected-note {{entering module 'a' due to this pragma}}
int f();
int g() { f(); }
#pragma clang module end // expected-error {{no matching '#pragma clang module begin'}}

// RUN: %clang_cc1 -x c++-module-map %s -fmodule-name=a -verify -std=c++98
module a {
  module b {
    requires cplusplus11
  }
}
#pragma clang module contents
// expected-error@3 {{module 'a.b' requires feature 'cplusplus11'}}
#pragma clang module begin a.b // expected-note {{entering module 'a' due to this pragma}}
int f();
int g() { f(); }
#pragma clang module end // expected-error {{no matching '#pragma clang module begin'}}

Add an explicit -std= to test to unbreak on PS4 targets.


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

#include "osfhandle.h"

#include <io.h>

#include "v8-profiler.h"
#include "v8-inspector.h"

namespace node {

int open_osfhandle(intptr_t osfhandle, int flags) {
  return _open_osfhandle(osfhandle, flags);
}

int close(int fd) {
  return _close(fd);
}

void ReferenceSymbols() {
  // Following symbols are used by electron.exe but got stripped by compiler,
  // for some reason, adding them to ForceSymbolReferences does not work,
  // probably because of VC++ bugs.
  v8::TracingCpuProfiler::Create(nullptr);
  reinterpret_cast<v8_inspector::V8InspectorClient*>(nullptr)->unmuteMetrics(0);
}

}  // namespace node

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

#include "osfhandle.h"

#include <io.h>

#include "v8-profiler.h"
#include "v8-inspector.h"

namespace node {

int open_osfhandle(intptr_t osfhandle, int flags) {
  return _open_osfhandle(osfhandle, flags);
}

int close(int fd) {
  return _close(fd);
}

void ReferenceSymbols() {
  // Following symbols are used by electron.exe but got stripped by compiler,
  // for some reason, adding them to ForceSymbolReferences does not work,
  // probably because of VC++ bugs.
  v8::TracingCpuProfiler::Create(nullptr);
  reinterpret_cast<v8_inspector::V8InspectorSession*>(nullptr)->
      canDispatchMethod(v8_inspector::StringView());
  reinterpret_cast<v8_inspector::V8InspectorClient*>(nullptr)->unmuteMetrics(0);
}

}  // namespace node

Fix missing of symbols when linking win32 build