#include "test/catch.hpp"

#include <string>
#include <vector>

#include "main/exception/FileOpenException.hpp"
#include "main/exception/InvalidArgumentException.hpp"
#include "main/MainApp.hpp"

TEST_CASE("MainApp class") {
    using std::string;
    using std::vector;
    using pyconv::exception::FileOpenException;
    using pyconv::exception::InvalidArgumentException;
    using pyconv::MainApp;

    SECTION("Exceptions Thrown") {
        vector<string> args;
        try {
            MainApp mainApp(args);
        } catch (InvalidArgumentException const & e) {
            CHECK(e.message() == "No arguments provided");
        }
        args.push_back("cpp");
        try {
            MainApp mainApp(args);
        } catch (InvalidArgumentException const & e) {
            CHECK(e.message() == "Only one argument provided");
        }
        args[0] = "java";
        args.push_back("nonexistingfolder/nonexistingfile.py");
        try {
            MainApp mainApp(args);
        } catch (InvalidArgumentException const & e) {
            CHECK(e.message() == "Invalid language type: java");
        }
    }

    SECTION("No Exceptions Thrown") {
        vector<string> args {"cpp", "./src/PyConv/test/testfiles/properFile.py"};
        MainApp mainApp(args);
        CHECK_NOTHROW(mainApp.run());
        args[0] = "python";
        mainApp = MainApp(args);
        CHECK_NOTHROW(mainApp.run());
    }
}

#include "test/catch.hpp"

#include <string>
#include <vector>

#include "main/exception/FileOpenException.hpp"
#include "main/exception/InvalidArgumentException.hpp"
#include "main/MainApp.hpp"

TEST_CASE("MainApp class") {
    using std::string;
    using std::vector;
    using pyconv::exception::FileOpenException;
    using pyconv::exception::InvalidArgumentException;
    using pyconv::MainApp;

    SECTION("Exceptions Thrown") {
        vector<string> args;
        try {
            MainApp mainApp(args);
        } catch (InvalidArgumentException const & e) {
            CHECK(e.message() == "No arguments provided");
        }
        args.push_back("cpp");
        try {
            MainApp mainApp(args);
        } catch (InvalidArgumentException const & e) {
            CHECK(e.message() == "Only one argument provided");
        }
        args[0] = "java";
        args.push_back("nonexistingfolder/nonexistingfile.py");
        try {
            MainApp mainApp(args);
        } catch (InvalidArgumentException const & e) {
            CHECK(e.message() == "Invalid language type: java");
        }
    }

    SECTION("No Exceptions Thrown") {
        vector<string> args {"cpp", "./src/PyConv/test/testfiles/properFile.py"};
        MainApp mainApp(args);
        CHECK_NOTHROW(mainApp.run());
        args[1] = "nonexistingfolder/nonexistingfile.py";
        mainApp = MainApp(args);
        CHECK_NOTHROW(mainApp.run());
        args[0] = "python";
        mainApp = MainApp(args);
        CHECK_NOTHROW(mainApp.run());
    }
}

Add test to cover unable to open file

Add test to cover unable to open file


/* -*- mode:linux -*- */
/**
 * \file timeout.cc
 *
 *
 *
 * \author Ethan Burns
 * \date 2008-12-16
 */

#include <iostream>

#include <signal.h>
#include <stdlib.h>
#include <unistd.h>

using namespace std;

void alarm_action(int sig)
{
	cout << "No Solution" << endl
	     << "cost: infinity" << endl
	     << "length: infinity" << endl
	     << "wall_time: infinity" << endl
	     << "CPU_time: infinity" << endl
	     << "generated: infinity" << endl
	     << "expanded: infinity" << endl;

	exit(EXIT_SUCCESS);
}

void timeout(unsigned int sec)
{
	struct sigaction sa;

	sa.sa_flags = 0;
	sa.sa_sigaction = NULL;
	sa.sa_restorer = NULL;
	sa.sa_handler = alarm_action;
	sigfillset(&sa.sa_mask);
	sigaction(SIGALRM, &sa, NULL);

	alarm(sec);
}

/* -*- mode:linux -*- */
/**
 * \file timeout.cc
 *
 *
 *
 * \author Ethan Burns
 * \date 2008-12-16
 */

#include <iostream>

#include <signal.h>
#include <stdlib.h>
#include <unistd.h>

using namespace std;

void alarm_action(int sig)
{
	cout << "No Solution" << endl
	     << "cost: infinity" << endl
	     << "length: infinity" << endl
	     << "wall_time: infinity" << endl
	     << "CPU_time: infinity" << endl
	     << "generated: infinity" << endl
	     << "expanded: infinity" << endl;

	exit(EXIT_SUCCESS);
}

void timeout(unsigned int sec)
{
	struct sigaction sa;

	memset(&sa, '\0', sizeof(sa));

	sa.sa_handler = alarm_action;
	sigfillset(&sa.sa_mask);
	sigaction(SIGALRM, &sa, NULL);

	alarm(sec);
}

Fix sigaction to be more portable.

Fix sigaction to be more portable.


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

#include "SkNullCanvas.h"

#include "SkCanvas.h"
#include "SKNWayCanvas.h"

SkCanvas* SkCreateNullCanvas() {
    // An N-Way canvas forwards calls to N canvas's. When N == 0 it's
    // effectively a null canvas.
    return SkNEW(SkNWayCanvas);
}

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

#include "SkNullCanvas.h"

#include "SkCanvas.h"
#include "SKNWayCanvas.h"

SkCanvas* SkCreateNullCanvas() {
    // An N-Way canvas forwards calls to N canvas's. When N == 0 it's
    // effectively a null canvas.
    return SkNEW(SkNWayCanvas(0,0));
}

Fix SkNWayCanvas cons call when creating null canvas.

git-svn-id: e8541e15acce502a64c929015570ad1648e548cd@4223 2bbb7eff-a529-9590-31e7-b0007b416f81


#include "performance_model.h"
#include "log.h"

using std::endl;

SimplePerformanceModel::SimplePerformanceModel()
    : m_instruction_count(0)
    , m_cycle_count(0)
{
}

SimplePerformanceModel::~SimplePerformanceModel()
{
}

void SimplePerformanceModel::outputSummary(std::ostream &os)
{
   os << "  Instructions: " << getInstructionCount() << endl
      << "  Cycles: " << getCycleCount() << endl;
}

void SimplePerformanceModel::handleInstruction(Instruction *instruction)
{
   m_instruction_count++;
   m_cycle_count += instruction->getCost();
}

#include "performance_model.h"
#include "log.h"

using std::endl;

SimplePerformanceModel::SimplePerformanceModel()
    : m_instruction_count(0)
    , m_cycle_count(0)
{
}

SimplePerformanceModel::~SimplePerformanceModel()
{
}

void SimplePerformanceModel::outputSummary(std::ostream &os)
{
   os << "  Instructions: " << getInstructionCount() << endl
      << "  Cycles: " << getCycleCount() << endl;
}

void SimplePerformanceModel::handleInstruction(Instruction *instruction)
{
   // compute cost
   UInt64 cost = 0;

   const OperandList &ops = instruction->getOperands();

   for (unsigned int i = 0; i < ops.size(); i++)
   {
      const Operand &o = ops[i];

      if (o.m_type == Operand::MEMORY &&
          o.m_direction == Operand::READ)
      {
         DynamicInstructionInfo &i = getDynamicInstructionInfo();
         LOG_ASSERT_ERROR(i.type == DynamicInstructionInfo::INFO_MEMORY,
                          "Expected memory info.");

         cost += i.memory_info.latency;
         // ignore address

         popDynamicInstructionInfo();
      }
   }

   cost += instruction->getCost();

   // update counters
   m_instruction_count++;
   m_cycle_count += cost;
}

[perf] Add simple memory model to consume latency of memory operations. Still needs them to be pushed.


/*
  Copyright 2007 Albert Strasheim <fullung@gmail.com>

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

// TODO look at issues with the GIL here when multiple session threads
// call into the Python code (could happen with Openwire?)

#include <boost/python.hpp>
#include <cms/MessageListener.h>

using namespace boost::python;
using cms::MessageListener;
using cms::Message;

struct MessageListenerWrap : MessageListener, wrapper<MessageListener>
{
    virtual void onMessage(const Message* message)
    {
        // should be: this->getOverride("onMessage")(message);
        // but that doesn't work with Visual C++
        call<void>(this->get_override("onMessage").ptr(), message);
    }
};

void export_MessageListener()
{
    class_<MessageListenerWrap, boost::noncopyable>("MessageListener")
        .def("onMessage", pure_virtual(&MessageListener::onMessage))
        ;
}

/*
  Copyright 2007 Albert Strasheim <fullung@gmail.com>

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

// TODO look at issues with the GIL here when multiple session threads
// call into the Python code (could happen with Openwire?)

#include <boost/python.hpp>
#include <cms/MessageListener.h>
#include <cms/Message.h>

using namespace boost::python;
using cms::MessageListener;
using cms::Message;

struct MessageListenerWrap : MessageListener, wrapper<MessageListener>
{
    virtual void onMessage(const Message* message)
    {
        // should be: this->getOverride("onMessage")(message);
        // but that doesn't work with Visual C++
        call<void>(this->get_override("onMessage").ptr(), message);
    }
};

void export_MessageListener()
{
    class_<MessageListenerWrap, boost::noncopyable>("MessageListener")
        .def("onMessage", pure_virtual(&MessageListener::onMessage))
        ;
}

Fix compilation with GCC 4.1.1.

Fix compilation with GCC 4.1.1.


#include "scene.h"
#include "geometry/differential_geometry.h"
#include "lights/occlusion_tester.h"

void OcclusionTester::set_points(const Point &a, const Point &b){
	float dist = a.distance(b);
	ray = Ray{a, (b - a) / dist, 1e-6f, dist * (1.f - 1e-6f)};
}
void OcclusionTester::set_ray(const Point &p, const Vector &d){
	ray = Ray{p, d.normalized(), 1e-6f};
}
bool OcclusionTester::occluded(const Scene &scene){
	DifferentialGeometry dg;
	return scene.get_root().intersect(ray, dg);
}

#include "scene.h"
#include "geometry/differential_geometry.h"
#include "lights/occlusion_tester.h"

void OcclusionTester::set_points(const Point &a, const Point &b){
	ray = Ray{a, b - a, 1e-4f, 1};
}
void OcclusionTester::set_ray(const Point &p, const Vector &d){
	ray = Ray{p, d.normalized(), 1e-4f};
}
bool OcclusionTester::occluded(const Scene &scene){
	DifferentialGeometry dg;
	return scene.get_root().intersect(ray, dg);
}

Fix occlusion tester segment ray creation to behave like before


/*
 * Copyright 2014 Cloudius Systems
 */

#include "database.hh"
#include "core/app-template.hh"
#include "core/smp.hh"
#include "thrift/server.hh"

namespace bpo = boost::program_options;

int main(int ac, char** av) {
    app_template app;
    app.add_options()
        ("thrift-port", bpo::value<uint16_t>()->default_value(9160), "Thrift port")
        ("datadir", bpo::value<std::string>()->default_value("/var/lib/cassandra/data"), "data directory");

    auto server = std::make_unique<distributed<thrift_server>>();;

    return app.run(ac, av, [&] {
        auto&& config = app.configuration();
        uint16_t port = config["thrift-port"].as<uint16_t>();
        sstring datadir = config["datadir"].as<std::string>();

        database db(datadir);

        auto server = new distributed<thrift_server>;
        server->start(std::ref(db)).then([server = std::move(server), port] () mutable {
            server->invoke_on_all(&thrift_server::listen, ipv4_addr{port});
        }).then([port] {
            std::cout << "Thrift server listening on port " << port << " ...\n";
        });
    });
}

/*
 * Copyright 2014 Cloudius Systems
 */

#include "database.hh"
#include "core/app-template.hh"
#include "core/smp.hh"
#include "thrift/server.hh"

namespace bpo = boost::program_options;

int main(int ac, char** av) {
    app_template app;
    app.add_options()
        ("thrift-port", bpo::value<uint16_t>()->default_value(9160), "Thrift port")
        ("datadir", bpo::value<std::string>()->default_value("/var/lib/cassandra/data"), "data directory");

    auto server = std::make_unique<distributed<thrift_server>>();;

    std::unique_ptr<database> db;
    return app.run(ac, av, [&] {
        auto&& config = app.configuration();
        uint16_t port = config["thrift-port"].as<uint16_t>();
        sstring datadir = config["datadir"].as<std::string>();

        db.reset(std::make_unique<database>(datadir).release());

        auto server = new distributed<thrift_server>;
        server->start(std::ref(*db)).then([server = std::move(server), port] () mutable {
            server->invoke_on_all(&thrift_server::listen, ipv4_addr{port});
        }).then([port] {
            std::cout << "Thrift server listening on port " << port << " ...\n";
        });
    });
}

Fix use-after-free on database object

Fix use-after-free on database object

Caused urchin to SIGSEGV.


// RUN: rm -rf %t
// RUN: mkdir -p %t/prebuilt_modules
//
// RUN: %clang_cc1 -triple %itanium_abi_triple                          \
// RUN:     -fmodules-ts -fprebuilt-module-path=%t/prebuilt-modules     \
// RUN:     -emit-module-interface -pthread -DBUILD_MODULE              \
// RUN:     %s -o %t/prebuilt_modules/mismatching_module.pcm
//
// RUN: not %clang_cc1 -triple %itanium_abi_triple -fmodules-ts         \
// RUN:     -fprebuilt-module-path=%t/prebuilt_modules -DCHECK_MISMATCH \
// RUN:     %s 2>&1 | FileCheck %s

#ifdef BUILD_MODULE
export module mismatching_module;
#endif

#ifdef CHECK_MISMATCH
import mismatching_module;
// CHECK: error: POSIX thread support was enabled in PCH file but is currently disabled
// CHECK-NEXT: module file {{.*}}/mismatching_module.pcm cannot be loaded due to a configuration mismatch with the current compilation
#endif

// RUN: rm -rf %t
// RUN: mkdir -p %t/prebuilt_modules
//
// RUN: %clang_cc1 -triple %itanium_abi_triple                          \
// RUN:     -fmodules-ts -fprebuilt-module-path=%t/prebuilt-modules     \
// RUN:     -emit-module-interface -pthread -DBUILD_MODULE              \
// RUN:     %s -o %t/prebuilt_modules/mismatching_module.pcm
//
// RUN: not %clang_cc1 -triple %itanium_abi_triple -fmodules-ts         \
// RUN:     -fprebuilt-module-path=%t/prebuilt_modules -DCHECK_MISMATCH \
// RUN:     %s 2>&1 | FileCheck %s

#ifdef BUILD_MODULE
export module mismatching_module;
#endif

#ifdef CHECK_MISMATCH
import mismatching_module;
// CHECK: error: POSIX thread support was enabled in PCH file but is currently disabled
// CHECK-NEXT: module file {{.*[/|\\\\]}}mismatching_module.pcm cannot be loaded due to a configuration mismatch with the current compilation
#endif

Fix test from r346439 to also work on Windows due to path separator differences.

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


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

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

class ExtensionWebRequestApiTest : public ExtensionApiTest {
 public:
  virtual void SetUpInProcessBrowserTestFixture() {
    ExtensionApiTest::SetUpInProcessBrowserTestFixture();
    host_resolver()->AddRule("*", "127.0.0.1");
    ASSERT_TRUE(StartTestServer());
  }
};

IN_PROC_BROWSER_TEST_F(ExtensionWebRequestApiTest, WebRequest) {
  CommandLine::ForCurrentProcess()->AppendSwitch(
      switches::kEnableExperimentalExtensionApis);

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

IN_PROC_BROWSER_TEST_F(ExtensionWebRequestApiTest, WebRequestEvents) {
  CommandLine::ForCurrentProcess()->AppendSwitch(
    switches::kEnableExperimentalExtensionApis);

  ASSERT_TRUE(RunExtensionTest("webrequest/events")) << message_;
}

// 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/command_line.h"
#include "chrome/browser/extensions/extension_apitest.h"
#include "chrome/common/chrome_switches.h"
#include "net/base/mock_host_resolver.h"

class ExtensionWebRequestApiTest : public ExtensionApiTest {
 public:
  virtual void SetUpInProcessBrowserTestFixture() {
    ExtensionApiTest::SetUpInProcessBrowserTestFixture();
    host_resolver()->AddRule("*", "127.0.0.1");
    ASSERT_TRUE(StartTestServer());
  }
};

IN_PROC_BROWSER_TEST_F(ExtensionWebRequestApiTest, WebRequest) {
  CommandLine::ForCurrentProcess()->AppendSwitch(
      switches::kEnableExperimentalExtensionApis);

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

// See crbug.com/79081
IN_PROC_BROWSER_TEST_F(ExtensionWebRequestApiTest, FLAKY_WebRequestEvents) {
  CommandLine::ForCurrentProcess()->AppendSwitch(
    switches::kEnableExperimentalExtensionApis);

  ASSERT_TRUE(RunExtensionTest("webrequest/events")) << message_;
}

Mark ExtensionWebRequestApiTest.WebRequestEvents flaky.
BUG=79081
TEST=N/A
TBR=dmichael@chromium.org
Review URL: http://codereview.chromium.org/6821051

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


// RUN: %clang -### -Wlarge-by-value-copy %s 2>&1 | FileCheck -check-prefix=LARGE_VALUE_COPY_DEFAULT %s
// LARGE_VALUE_COPY_DEFAULT: -Wlarge-by-value-copy=64
// RUN: %clang -### -Wlarge-by-value-copy=128 %s 2>&1 | FileCheck -check-prefix=LARGE_VALUE_COPY_JOINED %s
// LARGE_VALUE_COPY_JOINED: -Wlarge-by-value-copy=128

// Check that -isysroot warns on nonexistent paths.
// RUN: %clang -### -c -target i386-apple-darwin10 -isysroot %T/warning-options %s 2>&1 | FileCheck --check-prefix=CHECK-ISYSROOT %s
// CHECK-ISYSROOT: warning: no such sysroot directory: '{{([A-Za-z]:.*)?}}/warning-options'

// RUN: %clang -### -Wlarge-by-value-copy %s 2>&1 | FileCheck -check-prefix=LARGE_VALUE_COPY_DEFAULT %s
// LARGE_VALUE_COPY_DEFAULT: -Wlarge-by-value-copy=64
// RUN: %clang -### -Wlarge-by-value-copy=128 %s 2>&1 | FileCheck -check-prefix=LARGE_VALUE_COPY_JOINED %s
// LARGE_VALUE_COPY_JOINED: -Wlarge-by-value-copy=128

// Check that -isysroot warns on nonexistent paths.
// RUN: %clang -### -c -target i386-apple-darwin10 -isysroot %T/warning-options %s 2>&1 | FileCheck --check-prefix=CHECK-ISYSROOT %s
// CHECK-ISYSROOT: warning: no such sysroot directory: '{{.*}}/warning-options'

Fix a regex error breaking tests.

Fix a regex error breaking tests.

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


/*
* Darwin SecRandomCopyBytes EntropySource
* (C) 2015 Daniel Seither (Kullo GmbH)
*
* Botan is released under the Simplified BSD License (see license.txt)
*/

#include <botan/internal/darwin_secrandom.h>
#include <Security/Security.h>

namespace Botan {

/**
* Gather entropy from SecRandomCopyBytes
*/
void Darwin_SecRandom::poll(Entropy_Accumulator& accum)
   {
   secure_vector<byte>& buf = accum.get_io_buf(BOTAN_SYSTEM_RNG_POLL_REQUEST);

   if(0 == SecRandomCopyBytes(kSecRandomDefault, buf.size(), buf.data()))
      {
      accum.add(buf.data(), buf.size(), BOTAN_ENTROPY_ESTIMATE_STRONG_RNG);
      }
   }

}

/*
* Darwin SecRandomCopyBytes EntropySource
* (C) 2015 Daniel Seither (Kullo GmbH)
*
* Botan is released under the Simplified BSD License (see license.txt)
*/

#include <botan/internal/darwin_secrandom.h>
#include <Security/Security.h>
#include <Security/SecRandom.h>

namespace Botan {

/**
* Gather entropy from SecRandomCopyBytes
*/
void Darwin_SecRandom::poll(Entropy_Accumulator& accum)
   {
   secure_vector<byte>& buf = accum.get_io_buf(BOTAN_SYSTEM_RNG_POLL_REQUEST);

   if(0 == SecRandomCopyBytes(kSecRandomDefault, buf.size(), buf.data()))
      {
      accum.add(buf.data(), buf.size(), BOTAN_ENTROPY_ESTIMATE_STRONG_RNG);
      }
   }

}

Fix SecRandomCopyBytes call with older OS X SDKs

In 10.8 (and presumably older) versions, the header for SecRandomCopyBytes
is SecRandom.h, and Security.h does not include SecRandom.h

With this change, the include of Security.h may be redundant for all versions,
but I have no way to test this.

GH #528


#include "common.th"

_start:
    bare_metal_init()
    prologue

top:
    d <- [rel(min0)]
    e <- [rel(min1)]
    f <- [rel(sec0)]
    g <- [rel(sec1)]

    h <- d << 4 + e
    h <- h << 4 + f
    h <- h << 4 + g
    h -> [0x100]

    c <- 1
    call(sleep)

    g <- g + 1
    h <- g == 10
    g <- g &~ h
    f <- f - h
    h <- f == 6
    f <- f &~ h
    e <- e - h
    h <- e == 10
    e <- e &~ h
    d <- d - h
    h <- d == 6
    d <- d &~ h

    d -> [rel(min0)]
    e -> [rel(min1)]
    f -> [rel(sec0)]
    g -> [rel(sec1)]
    goto(top)

    illegal

sleep:
    c <- c * 1070
    c <- c * 1780
    call(ticks)
    ret

ticks:
    pushall(d,e)
    d <- 0
Lticks_loop:
    e <- d < c
    d <- d + 1
    jnzrel(e,Lticks_loop)
    popall_ret(d,e)

min0: .word 0
min1: .word 0
sec0: .word 0
sec1: .word 0

#include "common.th"

_start:
    bare_metal_init()
    prologue

top:
    d <- [rel(min0)]
    e <- [rel(min1)]
    f <- [rel(sec0)]
    g <- [rel(sec1)]

    h <- d << 4 + e
    h <- h << 4 + f
    h <- h << 4 + g
    h -> [0x100]

    c <- 1
    call(sleep)

    g <- g + 1
    h <- g == 10
    g <- g &~ h
    f <- f - h
    h <- f == 6
    f <- f &~ h
    e <- e - h
    h <- e == 10
    e <- e &~ h
    d <- d - h
    h <- d == 6
    d <- d &~ h

    d -> [rel(min0)]
    e -> [rel(min1)]
    f -> [rel(sec0)]
    g -> [rel(sec1)]
    goto(top)

    illegal

sleep:
    // 40MHz clock, 4-cycle ticks() loop, 8cpi
    c <- c * 1000
    c <- c * 1250
    call(ticks)
    ret

ticks:
    pushall(d,e)
    d <- 0
Lticks_loop:
    e <- d < c
    d <- d + 1
    a <- a // delay to make the loop 4 cycles long
    jnzrel(e,Lticks_loop)
    popall_ret(d,e)

min0: .word 0
min1: .word 0
sec0: .word 0
sec1: .word 0

Update clock delay for new 8-cycle instruction

Change delay loop to four cycles per tick. Currently we use a 40MHz clock, so
this is 12500000 ticks per second, which is a nice round number.


#include "MainWindow.h"
#include "SpritePackerProjectFile.h"
#include <QApplication>

int commandLine(QCoreApplication& app);

int main(int argc, char *argv[])
{
    QApplication app(argc, argv);
#ifdef Q_OS_WIN32
        QApplication::setStyle(QStyleFactory::create("Fusion"));
#endif

    QCoreApplication::setOrganizationName("amakaseev");
    QCoreApplication::setOrganizationDomain("spicyminds-lab.com");
    QCoreApplication::setApplicationName("SpriteSheetPacker");
    QCoreApplication::setApplicationVersion("1.0.3");
    //QDir::setCurrent(QApplication::applicationDirPath());

    SpritePackerProjectFile::factory().set<SpritePackerProjectFile>("json");
    SpritePackerProjectFile::factory().set<SpritePackerProjectFileOLD>("sp");
    SpritePackerProjectFile::factory().set<SpritePackerProjectFileTPS>("tps");

    if (argc > 1) {
        return commandLine(app);
    } else {
        MainWindow w;
        w.show();
        return app.exec();
    }
}

#include "MainWindow.h"
#include "SpritePackerProjectFile.h"
#include <QApplication>

int commandLine(QCoreApplication& app);

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

    QCoreApplication::setOrganizationName("amakaseev");
    QCoreApplication::setOrganizationDomain("spicyminds-lab.com");
    QCoreApplication::setApplicationName("SpriteSheetPacker");
    QCoreApplication::setApplicationVersion("1.0.3");
    //QDir::setCurrent(QApplication::applicationDirPath());

    SpritePackerProjectFile::factory().set<SpritePackerProjectFile>("json");
    SpritePackerProjectFile::factory().set<SpritePackerProjectFileOLD>("sp");
    SpritePackerProjectFile::factory().set<SpritePackerProjectFileTPS>("tps");

    if (argc > 1) {
        return commandLine(app);
    } else {
        MainWindow w;
        w.show();
        return app.exec();
    }
}

Use windows native look and feel

Use windows native look and feel


/*
 * Copyright (c) Facebook, Inc. and its affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 *
 */

#include <quic/common/BufAccessor.h>
#include <folly/portability/GTest.h>

namespace quic {
TEST(SimpleBufAccessor, BasicAccess) {
  SimpleBufAccessor accessor(1000);
  EXPECT_TRUE(accessor.ownsBuffer());
  auto buf = accessor.obtain();
  EXPECT_EQ(1000, buf->capacity());
  EXPECT_FALSE(accessor.ownsBuffer());
  auto empty = accessor.obtain();
  EXPECT_EQ(nullptr, empty);
  accessor.release(buf->clone());
  EXPECT_TRUE(accessor.ownsBuffer());
  EXPECT_DEATH(accessor.release(std::move(buf)), "");
}

TEST(SimpleBufAccessor, CapacityMatch) {
  SimpleBufAccessor accessor(1000);
  auto buf = accessor.obtain();
  buf = folly::IOBuf::create(2000);
  EXPECT_DEATH(accessor.release(std::move(buf)), "");
}

TEST(SimpleBufAccessor, RefuseChainedBuf) {
  SimpleBufAccessor accessor(1000);
  auto buf = accessor.obtain();
  buf->prependChain(folly::IOBuf::create(0));
  EXPECT_DEATH(accessor.release(std::move(buf)), "");
}
} // namespace quic

/*
 * Copyright (c) Facebook, Inc. and its affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 *
 */

#include <quic/common/BufAccessor.h>
#include <folly/portability/GTest.h>

namespace quic {
TEST(SimpleBufAccessor, BasicAccess) {
  SimpleBufAccessor accessor(1000);
  EXPECT_TRUE(accessor.ownsBuffer());
  auto buf = accessor.obtain();
  EXPECT_LE(1000, buf->capacity());
  EXPECT_FALSE(accessor.ownsBuffer());
  auto empty = accessor.obtain();
  EXPECT_EQ(nullptr, empty);
  accessor.release(buf->clone());
  EXPECT_TRUE(accessor.ownsBuffer());
  EXPECT_DEATH(accessor.release(std::move(buf)), "");
}

TEST(SimpleBufAccessor, CapacityMatch) {
  SimpleBufAccessor accessor(1000);
  auto buf = accessor.obtain();
  buf = folly::IOBuf::create(2000);
  EXPECT_DEATH(accessor.release(std::move(buf)), "");
}

TEST(SimpleBufAccessor, RefuseChainedBuf) {
  SimpleBufAccessor accessor(1000);
  auto buf = accessor.obtain();
  buf->prependChain(folly::IOBuf::create(0));
  EXPECT_DEATH(accessor.release(std::move(buf)), "");
}
} // namespace quic

Fix capacity check in BufAccessor test

Fix capacity check in BufAccessor test

Summary:
IOBuf creates a buffer that has the capacity GE the input capacity.

(Note: this ignores all push blocking failures!)

Reviewed By: mjoras

Differential Revision: D21302978

fbshipit-source-id: 1c815389f514fe902a7d64520357051bb9f592e1


#include <QtGui>
#include <sequanto/automation.h>
#include <sequanto/tree.h>
#include <sequanto/QtWrapper.h>
#include "../cxx/src/cxx_root.h"

#include <windows.h>

using namespace sequanto::automation;

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

   sq_init ();

   sq_server_init ( &server, 4321 );

   QApplication * application = new QApplication ( argc, argv );

   ListNode * test = new ListNode ("test");

   sq_get_cxx_root()->AddChild ( test );

   QtWrapper::WrapApplication ( test );

   sq_server_poll ( &server );

   atexit ( sq_shutdown );
}

#include <QtGui>
#include <sequanto/automation.h>
#include <sequanto/tree.h>
#include <sequanto/QtWrapper.h>
#include "../cxx/src/cxx_root.h"
#include "config.h"

using namespace sequanto::automation;

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

   sq_init ();

   sq_server_init ( &server, 4321 );

   QApplication * application = new QApplication ( argc, argv );

   ListNode * test = new ListNode ("test");

   sq_get_cxx_root()->AddChild ( test );

   QtWrapper::WrapApplication ( test );

   sq_server_poll ( &server );

   atexit ( sq_shutdown );
}

Include config.h instead of windows.h in shared library test project.


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

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

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

  ASSERT_TRUE(RunExtensionTest("popup")) << message_;
}

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

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

// Flaky, http://crbug.com/46601.
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, FLAKY_Popup) {
  CommandLine::ForCurrentProcess()->AppendSwitch(
      switches::kEnableExperimentalExtensionApis);

  ASSERT_TRUE(RunExtensionTest("popup")) << message_;
}

Mark ExtensionApiTest.Popup as FLAKY, it is still flaky.

TBR=twiz

BUG=46601
TEST=browser_tests

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

git-svn-id: http://src.chromium.org/svn/trunk/src@58208 4ff67af0-8c30-449e-8e8b-ad334ec8d88c

Former-commit-id: 560f4161b64346fee74116d2676e11f782df53ee


// 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 "chrome/common/desktop_notifications/active_notification_tracker.h"
#include "testing/gtest/include/gtest/gtest.h"

TEST(ActiveNotificationTrackerTest, TestLookupAndClear) {
  ActiveNotificationTracker tracker;

  WebKit::WebNotification notification1;
  int id1 = tracker.RegisterNotification(notification1);

  WebKit::WebNotification notification2;
  int id2 = tracker.RegisterNotification(notification2);

  WebKit::WebNotification result;
  tracker.GetNotification(id1, &result);
  EXPECT_TRUE(result == notification1);

  tracker.GetNotification(id2, &result);
  EXPECT_TRUE(result == notification2);

  tracker.Clear();
}

// 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 "chrome/common/desktop_notifications/active_notification_tracker.h"
#include "testing/gtest/include/gtest/gtest.h"

TEST(ActiveNotificationTrackerTest, DISABLED_TestLookupAndClear) {
  ActiveNotificationTracker tracker;

  WebKit::WebNotification notification1;
  int id1 = tracker.RegisterNotification(notification1);

  WebKit::WebNotification notification2;
  int id2 = tracker.RegisterNotification(notification2);

  WebKit::WebNotification result;
  tracker.GetNotification(id1, &result);
  EXPECT_TRUE(result == notification1);

  tracker.GetNotification(id2, &result);
  EXPECT_TRUE(result == notification2);

  tracker.Clear();
}

Disable unit test that breaks valgrind.  Failure is related to the fact that I can't create distinct WebCore objects in the test.

BUG=none
TEST=valgrind

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

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


#include "insect/records.h"

static void
__record(Record *);

#include <assert.h>

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

static void
__path_copy(RecordPath path, RecordPath *ref)
{
	int len = strnlen(path, RECORD_PATH_MAX);
	assert(ref);
	*ref = malloc(len + 1);
	assert(*ref);
	(void) strncpy(*ref, path, len + 1);
}

Record *
record_new(RecordPath path)
{
	Record *record;
	assert(path);
	record = malloc(sizeof(Record));
	assert(record);
	record->hits = 1;
	record->path = NULL;
	__path_copy(path, &record->path);
	__record(record);
	return record;
}

void
record_free(Record *record)
{
	assert(record);
	record->hits = 0;
	free(record->path);
	free(record);
}

#include "insect/records.h"

static void
__record(Record *);

static void
__path_copy(Path, Path *);
/* FIMXE(teh): ^ inline? */

#include <assert.h>

#include <stdlib.h>

Record *
record_new(Path path)
{
	Record *record;
	assert(path);
	record = malloc(sizeof(Record));
	assert(record);
	record->hits = 1;
	record->path = NULL;
	__path_copy(path, &record->path);
	__record(record);
	return record;
}

void
record_free(Record *record)
{
	assert(record);
	record->hits = 0;
	free((void *) record->path);
	free(record);
}

/* */

#include <string.h>

static void
__path_copy(Path old_path, Path *new_copy)
{
	int len;
	assert(old_path && new_copy);
	len = strnlen(old_path, INSECT_PATH_MAX);
	*new_copy = malloc(len + 1);
	assert(*new_copy);
	(void) strncpy((char *) *new_copy, old_path, len + 1);
}

Rewrite c-string copy helper function cleanly


#include <functional>
#include <boost/optional.hpp>

#include "key_aliases.hh"
#include "file_contents.hh"
#include "contents.hh"
#include "mode.hh"
#include "show_message.hh"

std::map < char, std::function < void (contents&, boost::optional<int>) > >
    global_normal_map,
    global_insert_map;

mode::mode(const std::string& name, bool (*const handle)(char))
    : name(name)
    , handle(handle) { }

bool mode::operator()(char ch) const {
    return handle(ch);
}

const std::string& mode::get_name() const {
    return this->name;
}

static bool fundamental_handle(char ch) {
    if(ch == _resize) return true;
    std::map < char, fun > :: iterator
        it = global_normal_map.find(ch);
    if(it == global_normal_map.end()) return false;

    clear_message();
    it->second(get_contents(),boost::none);
    return true;
}

mode mode::fundamental("Fundamental",fundamental_handle);

#include <functional>
#include <boost/optional.hpp>

#include "key_aliases.hh"
#include "file_contents.hh"
#include "contents.hh"
#include "mode.hh"
#include "show_message.hh"

std::map < char, std::function < void (contents&, boost::optional<int>) > >
    global_normal_map,
    global_insert_map;

mode::mode(const std::string& name, bool (*const handle)(char))
    : name(name)
    , handle(handle) { }

bool mode::operator()(char ch) const {
    return handle(ch);
}

const std::string& mode::get_name() const {
    return this->name;
}

static bool fundamental_handle(char ch) {
    if(ch == _resize) return true;

    auto it = global_normal_map.find(ch);
    if(it == global_normal_map.end()) return false;

    clear_message();
    it->second(get_contents(),boost::none);
    return true;
}

mode mode::fundamental("Fundamental",fundamental_handle);

Use a little type deduction

Use a little type deduction


#include <mlopen/hipoc_kernel.hpp>
#include <mlopen/errors.hpp>

namespace mlopen {

void HIPOCKernelInvoke::run(void* args, std::size_t size) const
{
    hipEvent_t start = nullptr;
    hipEvent_t stop = nullptr;
    void *config[] = {
        HIP_LAUNCH_PARAM_BUFFER_POINTER, args,
        HIP_LAUNCH_PARAM_BUFFER_SIZE, &size,
        HIP_LAUNCH_PARAM_END
    };
    if (callback)
    {
        hipEventCreate(&start);
        hipEventCreate(&stop);

        hipEventRecord(start, nullptr);
    }

    auto status = hipModuleLaunchKernel(fun, gdims[0], gdims[1], gdims[2], ldims[0], ldims[1], ldims[2], 0, stream, nullptr, (void**)&config);
    if(status != hipSuccess) MLOPEN_THROW_HIP_STATUS(status, "Failed to launch kernel");

    if (callback)
    {
        hipEventRecord(stop, nullptr);
        hipEventSynchronize(stop);
        callback(start, stop);
    }
}

HIPOCKernelInvoke HIPOCKernel::Invoke(hipStream_t stream, std::function<void(hipEvent_t, hipEvent_t)> callback)
{
    return HIPOCKernelInvoke{stream, fun, ldims, gdims, name, callback};
}
}

#include <mlopen/hipoc_kernel.hpp>
#include <mlopen/errors.hpp>

namespace mlopen {

void HIPOCKernelInvoke::run(void* args, std::size_t size) const
{
    hipEvent_t start = nullptr;
    hipEvent_t stop = nullptr;
    void *config[] = {
        HIP_LAUNCH_PARAM_BUFFER_POINTER, args,
        HIP_LAUNCH_PARAM_BUFFER_SIZE, &size,
        HIP_LAUNCH_PARAM_END
    };
    if (callback)
    {
        hipEventCreate(&start);
        hipEventCreate(&stop);

        hipEventRecord(start, nullptr);
    }

    // std::cerr << "Launch kernel: " << name << std::endl;
    auto status = hipModuleLaunchKernel(fun, gdims[0], gdims[1], gdims[2], ldims[0], ldims[1], ldims[2], 0, stream, nullptr, (void**)&config);
    if(status != hipSuccess) MLOPEN_THROW_HIP_STATUS(status, "Failed to launch kernel");

    if (callback)
    {
        hipEventRecord(stop, nullptr);
        hipEventSynchronize(stop);
        callback(start, stop);
    }
}

HIPOCKernelInvoke HIPOCKernel::Invoke(hipStream_t stream, std::function<void(hipEvent_t, hipEvent_t)> callback)
{

    return HIPOCKernelInvoke{stream, fun, ldims, gdims, name, callback};
}
}

Add statement to show kernel

Add statement to show kernel


//
// Created by dar on 2/11/16.
//

#include <gui/GuiText.h>
#include "TextManager.h"

TextManager::TextManager() : GuiElementRender() {
    this->charRender = new CharRender();
}

TextManager::~TextManager() {
    delete this->charRender;
}

void TextManager::render(const GuiElement *const element, glm::mat4 projectionMatrix, glm::mat4 viewMatrix, double scale) {
    const GuiText *const text = (const GuiText *const) element;
    int x = (int) text->getX();
    for (int i = 0; i < text->getString().length(); i++) {
        int j = this->charRender->getGlyphPos(text->getString().at(i));
        if (j == -1) {
            x += this->charRender->TEXT_SPACESIZE * scale;
            continue;
        }
        this->charRender->render(text->getString().at(i), projectionMatrix, viewMatrix, x, (int) text->getY(), text->getScale(), text->getColor(), text->getFlags());
        x += this->charRender->getGlyphSize(j) * scale + SPACING_PX;
    }
}

//
// Created by dar on 2/11/16.
//

#include <gui/GuiText.h>
#include "TextManager.h"

TextManager::TextManager() : GuiElementRender() {
    this->charRender = new CharRender();
}

TextManager::~TextManager() {
    delete this->charRender;
}

void TextManager::render(const GuiElement *const element, glm::mat4 projectionMatrix, glm::mat4 viewMatrix, double scale) {
    const GuiText *const text = (const GuiText *const) element;
    int x = (int) text->getX();
    for (int i = 0; i < text->getString().length(); i++) {
        int j = this->charRender->getGlyphPos(text->getString().at(i));
        if (j == -1) {
            x += this->charRender->TEXT_SPACESIZE * scale;
            continue;
        }
        this->charRender->render(text->getString().at(i), projectionMatrix, viewMatrix, x, (int) text->getY(), text->getScale() * scale, text->getColor(), text->getFlags());
        x += this->charRender->getGlyphSize(j) * scale + SPACING_PX;
    }
}

Include "scale" parameter in calculations


#ifdef CHIPKIT

#include "serialutil.h"
#include "buffers.h"
#include "log.h"

void readFromSerial(SerialDevice* serial, bool (*callback)(uint8_t*)) {
    int bytesAvailable = serial->device->available();
    if(bytesAvailable > 0) {
        for(int i = 0; i < bytesAvailable && !queue_full(&serial->receiveQueue);
						i++) {
            char byte = serial->device->read();
			QUEUE_PUSH(uint8_t, &serial->receiveQueue, (uint8_t) byte);
        }
		processQueue(&serial->receiveQueue, callback);
    }
}

void initializeSerial(SerialDevice* serial) {
    serial->device->begin(115200);
	queue_init(&serial->receiveQueue);
}

void processInputQueue(SerialDevice* device) {
    int byteCount = 0;
    char sendBuffer[MAX_MESSAGE_SIZE];
    while(!queue_empty(&device->sendQueue) && byteCount < 64) {
        sendBuffer[byteCount++] = QUEUE_POP(uint8_t, &device->sendQueue);
    }

    // Serial transfers are really, really slow, so we don't want to send unless
    // explicitly set to do so at compile-time. Alternatively, we could send
    // on serial whenever we detect below that we're probably not connected to a
    // USB device, but explicit is better than implicit.
    device->device->write((const uint8_t*)sendBuffer, byteCount);
}

#endif // CHIPKIT

#ifdef CHIPKIT

#include "serialutil.h"
#include "buffers.h"
#include "log.h"

void readFromSerial(SerialDevice* serial, bool (*callback)(uint8_t*)) {
    int bytesAvailable = serial->device->available();
    if(bytesAvailable > 0) {
        for(int i = 0; i < bytesAvailable && !queue_full(&serial->receiveQueue);
						i++) {
            char byte = serial->device->read();
			QUEUE_PUSH(uint8_t, &serial->receiveQueue, (uint8_t) byte);
        }
		processQueue(&serial->receiveQueue, callback);
    }
}

void initializeSerial(SerialDevice* serial) {
    serial->device->begin(115200);
	queue_init(&serial->receiveQueue);
}

void processInputQueue(SerialDevice* device) {
    int byteCount = 0;
    char sendBuffer[MAX_MESSAGE_SIZE];
    while(!queue_empty(&device->sendQueue) && byteCount < MAX_MESSAGE_SIZE) {
        sendBuffer[byteCount++] = QUEUE_POP(uint8_t, &device->sendQueue);
    }

    device->device->write((const uint8_t*)sendBuffer, byteCount);
}

#endif // CHIPKIT

Send more bytes per batch over serial.

Send more bytes per batch over serial.


// test/SemaCXX/coroutine-traits-undefined-template.cpp

// This file contains references to sections of the Coroutines TS, which can be
// found at http://wg21.link/coroutines.

// RUN: %clang_cc1 -std=c++14 -fcoroutines-ts -verify %s -fcxx-exceptions -fexceptions -Wunused-result

namespace std {
namespace experimental {

template<typename ...T>
struct coroutine_traits {
  struct promise_type {};
};

template<> struct coroutine_traits<void>; // expected-note {{forward declaration of 'std::experimental::coroutine_traits<void>'}}
}} // namespace std::experimental

void uses_forward_declaration() {
  co_return; // expected-error {{this function cannot be a coroutine: missing definition of specialization 'coroutine_traits<void>'}}
}

[SemaCXX] Remove comment from coroutines test, NFC

Summary:
The file name was accidentally included when the test file was added.

Test Plan: check-clang

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


/****************************************************************************
**
** Copyright (C) 2016 The Qt Company Ltd.
** Contact: https://www.qt.io/licensing/
**
** This file is part of Qbs.
**
** $QT_BEGIN_LICENSE:GPL-EXCEPT$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company. For licensing terms
** and conditions see https://www.qt.io/terms-conditions. For further
** information use the contact form at https://www.qt.io/contact-us.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3 as published by the Free Software
** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
** included in the packaging of this file. Please review the following
** information to ensure the GNU General Public License requirements will
** be met: https://www.gnu.org/licenses/gpl-3.0.html.
**
** $QT_END_LICENSE$
**
****************************************************************************/

#include <cstdio>

int main()
{
    printf("%s..\n", TEXT);
    return 0;
}

/****************************************************************************
**
** Copyright (C) 2016 The Qt Company Ltd.
** Contact: https://www.qt.io/licensing/
**
** This file is part of Qbs.
**
** $QT_BEGIN_LICENSE:GPL-EXCEPT$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company. For licensing terms
** and conditions see https://www.qt.io/terms-conditions. For further
** information use the contact form at https://www.qt.io/contact-us.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3 as published by the Free Software
** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
** included in the packaging of this file. Please review the following
** information to ensure the GNU General Public License requirements will
** be met: https://www.gnu.org/licenses/gpl-3.0.html.
**
** $QT_END_LICENSE$
**
****************************************************************************/

#include <cstdio>

int main()
{
    std::printf("%s..\n", TEXT);
    return 0;
}

tests: Add 'std' prefix for printf() in blackbox::configure test

We need to use the 'std' namespace prefix for all functions
from the <cstdio> header. Otherwise the compilation may fails
on some toolchains (e.g. on Open Watcom).

Change-Id: I7824d96a9d0432c65e73f957653c865fd3754641
Reviewed-by: Ivan Komissarov <96f14e4d07227e958f51f7d2898113639e9498d9@gmail.com>


///////////////////////////////////////
/// file: linklist_test.cpp
///////////////////////////////////////

#include <iostream>
#include "linklist.h"
using namespace std;

///
/// 打印链表
///
template<typename T>
void PrintList(LinkList<T> L)
{
    cout << "(";
    auto p = L->next;
    while(p) {
        cout << " " << p->data;
        p = p->next;
    }
    cout << " )" << endl;
}

bool eq(int a, int b)
{
    return a==b;
}

void print(int x)
{
    cout << " " << x;
}

int main()
{
    // 建立链表
    LinkList<int> L;
    // 初始化
    InitList(L);
    PrintList(L);

    // 插入元素
    ListInsert(L,1,3);
    ListInsert(L,2,1);
    ListInsert(L,3,4);
    ListInsert(L,4,1);
    ListInsert(L,5,5);
    ListInsert(L,6,9);
    PrintList(L);

    // 元素定位
    cout << "LocateElem 9 = ";
    cout << "L(@" << LocateElem(L,9,eq) << ")" << endl;

    // 遍历线性表
    cout << "ListTraverse: ";
    ListTraverse(L,print);
    cout << endl;

    // 销毁链表
    DestroyList(L);

    return 0;
}

///////////////////////////////////////
/// file: linklist_test2.cpp
///////////////////////////////////////

#include <iostream>
#include "linklist.h"
using namespace std;

///
/// 打印链表
///
template<typename T>
void PrintList(LinkList<T> L)
{
    cout << "(";
    auto p = L->next;
    while(p) {
        cout << " " << p->data;
        p = p->next;
    }
    cout << " )" << endl;
}

bool eq(int a, int b)
{
    return a==b;
}

void print(int x)
{
    cout << " " << x;
}

///
/// 在单链表中定位元素，遍历顺序表
///
int main()
{
    // 建立链表
    LinkList<int> L;
    // 初始化
    InitList(L);
    PrintList(L);

    // 插入元素
    ListInsert(L,1,3);
    ListInsert(L,2,1);
    ListInsert(L,3,4);
    ListInsert(L,4,1);
    ListInsert(L,5,5);
    ListInsert(L,6,9);
    PrintList(L);

    // 元素定位
    cout << "LocateElem 9 = ";
    cout << "L(@" << LocateElem(L,9,eq) << ")" << endl;

    // 遍历线性表
    cout << "ListTraverse: ";
    ListTraverse(L,print);
    cout << endl;

    // 销毁链表
    DestroyList(L);

    return 0;
}

Update LinkList test2 (locate and traverse)


#include "viewer/details-window.h"
#include <QLabel>
#include <ui_details-window.h>
#include "helpers.h"
#include "models/image.h"

DetailsWindow::DetailsWindow(Profile *profile, QWidget *parent)
	: QDialog(parent), ui(new Ui::DetailsWindow), m_profile(profile)
{
	ui->setupUi(this);
}

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

void DetailsWindow::setImage(QSharedPointer<Image> image)
{
	clearLayout(ui->formLayout);

	for (QPair<QString, QString> row : image->detailsData())
	{
		if (row.first.isEmpty() && row.second.isEmpty())
		{
			ui->formLayout->addItem(new QSpacerItem(10, 10));
		}
		else
		{
			auto label = new QLabel(QString("<b>%1</b>").arg(row.first), this);
			auto field = new QLabel(row.second, this);
			field->setWordWrap(true);
			ui->formLayout->addRow(label, field);
		}
	}

	resize(QSize(400, 200));
}

#include "viewer/details-window.h"
#include <QLabel>
#include <ui_details-window.h>
#include "helpers.h"
#include "models/image.h"

DetailsWindow::DetailsWindow(Profile *profile, QWidget *parent)
	: QDialog(parent), ui(new Ui::DetailsWindow), m_profile(profile)
{
	ui->setupUi(this);
}

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

void DetailsWindow::setImage(QSharedPointer<Image> image)
{
	clearLayout(ui->formLayout);

	for (QPair<QString, QString> row : image->detailsData())
	{
		if (row.first.isEmpty() && row.second.isEmpty())
		{
			ui->formLayout->addItem(new QSpacerItem(10, 10));
		}
		else
		{
			auto label = new QLabel(QString("<b>%1</b>").arg(row.first), this);
			auto field = new QLabel(row.second, this);
			field->setWordWrap(true);
			ui->formLayout->addRow(label, field);
		}
	}

	update();
	resize(sizeHint());
}

Fix layout issue in details window

Fix layout issue in details window


#include <vector>
#include <string>

std::string createString(){
	std::string hi("Hello world!");
	return hi;
}

std::vector<std::string> createVector(){
	std::vector<std::string> my_vector;
	my_vector.push_back(createString());
	my_vector.push_back(createString());
	my_vector.push_back(createString());
	return my_vector;
}

int putStringsInVector(int num){
	std::vector<std::string> my_strings;
	for(int i=0; i<num; i++){
		my_strings.push_back(createString());
	}
	return my_strings.size();
}

void modifyVector(std::vector<int> & vector){
	int count = 0;
	for(int i:vector){
		if(count % 5 == 0){
			i = 42;
		}
	}
}

Add code for function test.

Add code for function test.


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

#include "clang/AST/Type.h"

#include "llvm/Support/raw_ostream.h"

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

}

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

#include "clang/AST/Type.h"

#include "llvm/Support/raw_ostream.h"

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

Put the symbol requester func into the proper namespace!

git-svn-id: acec3fd5b7ea1eb9e79d6329d318e8118ee2e14f@46987 27541ba8-7e3a-0410-8455-c3a389f83636


#ifdef __LPC17XX__

#include "canread.h"

CanMessage receiveCanMessage(CanBus* bus) {
    CAN_MSG_Type message;
    CAN_ReceiveMsg(bus->controller, &message);

    CanMessage result = {message.id, 0};
    result.data = message.dataA[0];
    result.data |= (message.dataA[1] << 8);
    result.data |= (message.dataA[2] << 16);
    result.data |= (message.dataA[3] << 24);
    result.data |= (((uint64_t)message.dataB[0]) << 32);
    result.data |= (((uint64_t)message.dataB[1]) << 40);
    result.data |= (((uint64_t)message.dataB[2]) << 48);
    result.data |= (((uint64_t)message.dataB[3]) << 56);

    return result;
}

#endif // __LPC17XX__

#ifdef __LPC17XX__

#include "canread.h"
#include "signals.h"

extern "C" {

void CAN_IRQHandler() {
    if((CAN_IntGetStatus(LPC_CAN1) & 0x01) == 1) {
        getCanBuses()[0].messageReceived = true;
    } else if((CAN_IntGetStatus(LPC_CAN2) & 0x01) == 1) {
        getCanBuses()[1].messageReceived = true;
    }
}

}

CanMessage receiveCanMessage(CanBus* bus) {
    CAN_MSG_Type message;
    CAN_ReceiveMsg(bus->controller, &message);

    CanMessage result = {message.id, 0};
    result.data = message.dataA[0];
    result.data |= (message.dataA[1] << 8);
    result.data |= (message.dataA[2] << 16);
    result.data |= (message.dataA[3] << 24);
    result.data |= (((uint64_t)message.dataB[0]) << 32);
    result.data |= (((uint64_t)message.dataB[1]) << 40);
    result.data |= (((uint64_t)message.dataB[2]) << 48);
    result.data |= (((uint64_t)message.dataB[3]) << 56);

    return result;
}

#endif // __LPC17XX__

Handle CAN interrupts on LPC.

Handle CAN interrupts on LPC.


#include <iostream>
#include <array>
#include <asio/steady_timer.hpp>
#include <asio.hpp>
#include <thread>
#include "node/raft_node.h"

using namespace std;

std::vector<raft_node_endpoint_t> peers{
        {1ul, "localhost", 12345, 13001},
        {2ul, "localhost", 12346, 13002},
        {3ul, "localhost", 12347, 13003}
};

int main(int argc, char* argv[]) {
    try {
        // Start raft_nodes
        std::vector<std::thread> workers;
        std::vector<raft_node> nodes;
        for (auto &peer : peers) {
            nodes.emplace_back(peer.uuid, std::make_shared<raft::config>(peers));
        }
        for (auto &node : nodes) {
            workers.push_back(std::thread([&node]() {
                node.run();
            }));
        }
        workers.push_back(std::thread([&nodes]() {
            while (true) {
                std::cout << "Assigned roles for cluster: " << std::endl;
                for (auto &node : nodes) {
                    std::cout << node.describe() << std::endl;
                }
                std::this_thread::sleep_for(2s);

            }
        }));

        // Wait for raft_nodes to finish
        std::for_each(workers.begin(), workers.end(), [](std::thread &t){
            t.join();
        });
    }
    catch(std::exception& e) {
        std::cerr << "Error" << std::endl;
        std::cerr << e.what() << std::endl;
    }

    return 0;
}

#include <iostream>
#include <array>
#include <asio/steady_timer.hpp>
#include <asio.hpp>
#include <thread>
#include "node/raft_node.h"

using namespace std;

std::vector<raft_node_endpoint_t> peers{
        {1ul, "localhost", 12345, 13001},
        {2ul, "localhost", 12346, 13002},
        {3ul, "localhost", 12347, 13003}
};

int main(int argc, char* argv[]) {
    try {
        // Start raft_nodes
        std::vector<std::thread> workers;
        for (auto &peer : peers) {
            workers.push_back(std::thread([&peer]() {
                auto node = raft_node(peer.uuid, std::make_shared<raft::config>(peers));
                node.run();
            }));
        }

        // Wait for raft_nodes to finish
        std::for_each(workers.begin(), workers.end(), [](std::thread &t){
            t.join();
        });
    }
    catch(std::exception& e) {
        std::cerr << "Error" << std::endl;
        std::cerr << e.what() << std::endl;
    }

    return 0;
}

Remove usage of broken move constructor

Remove usage of broken move constructor


#include "planning/jet/filter_sim.hh"

#include "eigen_helpers.hh"

namespace planning {
namespace jet {

estimation::jet_filter::State kf_state_from_xlqr_state(const State& x,
                                                       const Controls& u,
                                                       const Parameters& z) {
  estimation::jet_filter::State kf_state;
  const SE3 world_from_body = SE3(x.R_world_from_body, x.x);

  kf_state.T_body_from_world = world_from_body.inverse();

  const jcc::Vec3 dR_dt = x.w;
  const jcc::Vec3 dx_dt = x.v;

  const jcc::Vec3 net_force = x.R_world_from_body * (jcc::Vec3::UnitZ() * x.throttle_pct);
  const jcc::Vec3 dv_dt = (z.external_force + net_force) / z.mass;
  const jcc::Vec3 dw_dt = u.q;

  kf_state.eps_dot = jcc::vstack(dx_dt, (-dR_dt).eval());
  kf_state.eps_ddot = jcc::vstack(dv_dt, dw_dt);
  return kf_state;
}

}  // namespace jet
}  // namespace planning

#include "planning/jet/filter_sim.hh"

#include "eigen_helpers.hh"

namespace planning {
namespace jet {

estimation::jet_filter::State kf_state_from_xlqr_state(const State& x,
                                                       const Controls& u,
                                                       const Parameters& z) {
  estimation::jet_filter::State kf_state;
  const SE3 world_from_body = SE3(x.R_world_from_body, x.x);

  kf_state.R_world_from_body = x.R_world_from_body;
  kf_state.x_world = x.x;

  const jcc::Vec3 dR_dt = x.w;
  const jcc::Vec3 dx_dt = x.v;

  const jcc::Vec3 net_force = x.R_world_from_body * (jcc::Vec3::UnitZ() * x.throttle_pct);
  const jcc::Vec3 dv_dt = (z.external_force + net_force) / z.mass;
  const jcc::Vec3 dw_dt = u.q;

  kf_state.eps_dot = jcc::vstack(dx_dt, (-dR_dt).eval());
  kf_state.eps_ddot = jcc::vstack(dv_dt, dw_dt);
  return kf_state;
}

}  // namespace jet
}  // namespace planning

Make planning respect world frame velocity


#include "RobotState.h"

RobotStateInterface* RobotState::impl = 0;

void RobotState::SetImplementation(RobotStateInterface* i) {
    impl = i;
}

bool RobotState::IsDisabled() {
    if (impl != 0) {
        return impl->IsDisabled();
    }
    return true;
}

bool RobotState::IsEnabled() {
    if (impl != 0) {
        impl->IsEnabled();
    }
    return false;
}

bool RobotState::IsOperatorControl() {
    if (impl != 0) {
        impl->IsOperatorControl();
    }
    return true;
}

bool RobotState::IsAutonomous() {
    if (impl != 0) {
        impl->IsAutonomous();
    }
    return false;
}

bool RobotState::IsTest() {
    if (impl != 0) {
        impl->IsTest();
    }
    return false;
}

#include "RobotState.h"

RobotStateInterface* RobotState::impl = 0;

void RobotState::SetImplementation(RobotStateInterface* i) {
    impl = i;
}

bool RobotState::IsDisabled() {
    if (impl != 0) {
        return impl->IsDisabled();
    }
    return true;
}

bool RobotState::IsEnabled() {
    if (impl != 0) {
        return impl->IsEnabled();
    }
    return false;
}

bool RobotState::IsOperatorControl() {
    if (impl != 0) {
        return impl->IsOperatorControl();
    }
    return true;
}

bool RobotState::IsAutonomous() {
    if (impl != 0) {
        return impl->IsAutonomous();
    }
    return false;
}

bool RobotState::IsTest() {
    if (impl != 0) {
        return impl->IsTest();
    }
    return false;
}

Fix changes where the default value was always being returned for many of the robot state status functions.

Change-Id: I50f11ce6d8ba4cbaa9ab7f44cd2f353e8bba72dd


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

#include "chrome/browser/history/history_publisher.h"

#include "base/utf_string_conversions.h"

namespace history {

const char* const HistoryPublisher::kThumbnailImageFormat = "image/jpeg";

void HistoryPublisher::PublishPageThumbnail(
    const std::vector<unsigned char>& thumbnail, const GURL& url,
    const base::Time& time) const {
  PageData page_data = {
    time,
    url,
    NULL,
    NULL,
    kThumbnailImageFormat,
    &thumbnail,
  };

  PublishDataToIndexers(page_data);
}

void HistoryPublisher::PublishPageContent(const base::Time& time,
                                          const GURL& url,
                                          const std::wstring& title,
                                          const string16& contents) const {
  PageData page_data = {
    time,
    url,
    UTF16ToWide(contents).c_str(),
    title.c_str(),
    NULL,
    NULL,
  };

  PublishDataToIndexers(page_data);
}

}  // namespace history

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

#include "chrome/browser/history/history_publisher.h"

#include "base/utf_string_conversions.h"

namespace history {

const char* const HistoryPublisher::kThumbnailImageFormat = "image/jpeg";

void HistoryPublisher::PublishPageThumbnail(
    const std::vector<unsigned char>& thumbnail, const GURL& url,
    const base::Time& time) const {
  PageData page_data = {
    time,
    url,
    NULL,
    NULL,
    kThumbnailImageFormat,
    &thumbnail,
  };

  PublishDataToIndexers(page_data);
}

void HistoryPublisher::PublishPageContent(const base::Time& time,
                                          const GURL& url,
                                          const std::wstring& title,
                                          const string16& contents) const {
  std::wstring wide_contents = UTF16ToWide(contents);
  PageData page_data = {
    time,
    url,
    wide_contents.c_str(),
    title.c_str(),
    NULL,
    NULL,
  };

  PublishDataToIndexers(page_data);
}

}  // namespace history

Make sure the pointer in PageData::html remains valid while PageData is called.

BUG=46835

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

git-svn-id: dd90618784b6a4b323ea0c23a071cb1c9e6f2ac7@50173 4ff67af0-8c30-449e-8e8b-ad334ec8d88c


// Validate multiple reads

#include <sstream>
#include <string>

int main()
{
	std::istringstream stream{"John Smith 32"};

	std::string first_name;
	std::string family_name;
	int age;

	if (stream >> first_name &&
	    stream >> family_name &&
	    stream >> age) {
		// Use values
	}
}

// Validate reading multiple values from an input stream.
//
// We create a [`std::istringstream`](cpp/io/basic_istringstream) as
// the example input stream, which contains some values that we wish
// to read ([8]). This stream could be replaced by any other
// input stream, such as [`std::cin`](cpp/io/cin) or a file stream.
// We then create some objects on [10-11] into which we will read
// values from the stream.
//
// In the condition of the `if` statement on [14-16], we perform the
// extractions. The `&&` operators ensure that the condition
// is `true` only when all extractions succeed. Short-circuiting
// also ensures that an extraction is only evaluated if the previous
// extractions were successful.
//
// If you are reading values on multiple lines, consider [reading
// from the stream line-by-line](/common-tasks/input-streams/read-lines-from-stream.html)
// and then parsing each line.

// Validate multiple reads

#include <sstream>
#include <string>

int main()
{
	std::istringstream stream{"John Smith 32"};

	std::string first_name;
	std::string family_name;
	int age;

	if (stream >> first_name &&
	    stream >> family_name &&
	    stream >> age) {
		// Use values
	}
}

// Ensure that multiple stream reads are successful before using the
// extracted values.
//
// We create a [`std::istringstream`](cpp/io/basic_istringstream) as
// the example input stream, which contains some values that we wish
// to read ([8]). This stream could be replaced by any other
// input stream, such as [`std::cin`](cpp/io/cin) or a file stream.
// We then create some objects on [10-11] into which we will read
// values from the stream.
//
// In the condition of the `if` statement on [14-16], we perform the
// extractions. The `&&` operators ensure that the condition
// is `true` only when all extractions succeed. Short-circuiting
// also ensures that an extraction is only evaluated if the previous
// extractions were successful.
//
// If you are reading values on multiple lines, consider [reading
// from the stream line-by-line](/common-tasks/input-streams/read-lines-from-stream.html)
// and then parsing each line.

Edit the validate multiple reads sample

Edit the validate multiple reads sample


#include <gtest/gtest.h>

#include "../c_oriented.h"
#include "../c_moveable.h"

using aronnax::Vector2d;
using spacegun::Moveable;
using spacegun::Oriented;

class OrientedTest : public testing::Test {
  protected:
    virtual void SetUp() {
      expectedAngle_ = 15.0;
      moveable_ = new Moveable(Vector2d(), Vector2d(), expectedAngle_);
      oriented_ = new Oriented(*moveable_);
    }

    virtual void TearDown() {
      delete oriented_;
      delete moveable_;
    }

  Oriented* oriented_;
  Moveable* moveable_;
  float expectedAngle_;
};

#define radiansToDegrees(angleRadians) (angleRadians * 180.0 / M_PI)

TEST_F(OrientedTest, Constructor) {
  auto expected = 139.43671;
  EXPECT_FLOAT_EQ(expected, oriented_->getNormalizedAngle());
}

TEST_F(OrientedTest, getType) {
  using spacegun::COMPONENT_TYPE_ORIENTED;
  auto actual = oriented_->getType();

  EXPECT_EQ(COMPONENT_TYPE_ORIENTED, actual);
}

TEST_F(OrientedTest, facingNorth) {
  auto actual = oriented_->facingNorth();
  EXPECT_FALSE(actual);
}

Add oriented tests for facingNorth

Add oriented tests for facingNorth


/******************************************************
 * This is CIR-KIT 3rd robot control driver.
 * Author : Arita Yuta(Kyutech)
 ******************************************************/
#include "cirkit_unit03_driver.hpp"

#include <string>
#include <utility>

int main(int argc, char** argv)
{
  ros::init(argc, argv, "cirkit_unit03_driver_node");
  ROS_INFO("cirkit unit03 robot driver for ROS.");

  ros::NodeHandle n {"~"};
  std::string imcs01_port {"/dev/urbtc0"};
  n.param<std::string>("imcs01_port", imcs01_port, imcs01_port);

  cirkit::CirkitUnit03Driver driver(std::move(imcs01_port), ros::NodeHandle {});
  driver.run();

  return 0;
}

/******************************************************
 * This is CIR-KIT 3rd robot control driver.
 * Author : Arita Yuta(Kyutech)
 ******************************************************/
#include "cirkit_unit03_driver.hpp"

#include <string>
#include <utility>

int main(int argc, char** argv)
{
  ros::init(argc, argv, "cirkit_unit03_driver_node");
  ROS_INFO("cirkit unit03 robot driver for ROS.");

  ros::NodeHandle n {"~"};
  std::string imcs01_port {"/dev/urbtc0"};
  n.param<std::string>("imcs01_port", imcs01_port, imcs01_port);

  cirkit::CirkitUnit03Driver driver {std::move(imcs01_port), ros::NodeHandle {}};
  driver.run();

  return 0;
}

Update init writing to universal init

Update init writing to universal init


#include "Progression.h"

Progression* Progression::m_instance = nullptr;

Progression::Progression()
{
	this->m_currentLevel = 0;
	this->m_currentCheckpoint = 0;
	this->m_unlockedLevels = 0;
}

Progression::~Progression()
{

}

bool Progression::WriteToFile(std::string filename)
{
	std::ofstream saveFile;

	saveFile.open("..\\Debug\\Saves\\" + filename + ".txt");

	if (!saveFile.is_open()) {
		return false;
	}
	else
	{

		saveFile << "Allhuakbar" << "\r\n";
		saveFile.close();
	}
	return true;
}

bool Progression::ReadFromFile(std::string filename)
{
	return false;
}

#include "Progression.h"

Progression* Progression::m_instance = nullptr;

Progression::Progression()
{
	this->m_currentLevel = 0;
	this->m_currentCheckpoint = 0;
	this->m_unlockedLevels = 0;
}

Progression::~Progression()
{

}

bool Progression::WriteToFile(std::string filename)
{
	std::ofstream saveFile;

	saveFile.open("..\\Debug\\Saves\\" + filename + ".txt");

	if (!saveFile.is_open()) {
		return false;
	}
	else
	{
		saveFile << this->m_currentLevel << "\r\n";
		saveFile << this->m_currentCheckpoint << "\r\n";
		saveFile << this->m_unlockedLevels << "\r\n";
		saveFile.close();
	}
	return true;
}

bool Progression::ReadFromFile(std::string filename)
{
	return false;
}

ADD print the saved data to the save file


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

int List::numberOfNodes = 0;

void List::addToHead(int value) {
	node *temp=new node;
    temp->data=value;
    temp->next=head;
    head=temp;
	numberOfNodes++;
}

void List::addToTail(int value) {
	node *temp = new node;
	temp->data = value;
    temp->next = NULL;
	if(head == NULL) {
		head = temp;
		tail = temp;
		temp = NULL;
    } else {
        tail->next = temp;
        tail = temp;
    }
	numberOfNodes++;
}

void List::toString() {
	node *temp = new node;
	temp=head;
	while(temp!=NULL) {
		std::cout << temp->data <<"\t";
		temp = temp->next;
	}
	std::cout << std::endl;
}

Change 4 spaces to tab

Change 4 spaces to tab


#include <Ab/Config.hpp>
#include <Ab/Memory.hpp>

namespace Ab {

const MemoryConfig Memory::defaultConfig_;

}  // namespace Ab

#include <Ab/Config.hpp>
#include <Ab/Memory.hpp>

namespace Ab {

constexpr const MemoryConfig Memory::defaultConfig_;

}  // namespace Ab

Add constexpr keyword to inline inited variable

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


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

using namespace Halide;

int main() {
    // This test must be run with an OpenGL target
    const Target &target = get_jit_target_from_environment();
    if (!target.has_feature(Target::OpenGL))  {
        fprintf(stderr,"ERROR: This test must be run with an OpenGL target, e.g. by setting HL_JIT_TARGET=host-opengl.\n");
        return 1;
    }

    Func f;
    Var x, y, c;

    f(x, y, c) = cast<uint8_t>(select(c == 0, 10*x + y,
                                      c == 1, 127, 12));

    Image<uint8_t> out(10, 10, 3);
    f.bound(c, 0, 3).glsl(x, y, c);
    f.realize(out);

    out.copy_to_host();
    for (int y=0; y<out.height(); y++) {
        for (int x=0; x<out.width(); x++) {
            if (!(out(x, y, 0) == 10*x+y && out(x, y, 1) == 127 && out(x, y, 2) == 12)) {
                fprintf(stderr, "Incorrect pixel (%d, %d, %d) at x=%d y=%d.\n",
                        out(x, y, 0), out(x, y, 1), out(x, y, 2),
                        x, y);
                return 1;
            }
        }
    }

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

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

using namespace Halide;

int main() {
    // This test must be run with an OpenGL target
    const Target &target = get_jit_target_from_environment();
    if (!target.has_feature(Target::OpenGL))  {
        fprintf(stderr,"ERROR: This test must be run with an OpenGL target, e.g. by setting HL_JIT_TARGET=host-opengl.\n");
        return 1;
    }

    Func f;
    Var x, y, c;

    f(x, y, c) = cast<uint8_t>(42);

    Image<uint8_t> out(10, 10, 3);
    f.bound(c, 0, 3).glsl(x, y, c);
    f.realize(out);

    out.copy_to_host();
    for (int y=0; y<out.height(); y++) {
        for (int x=0; x<out.width(); x++) {
            for (int z=0; x<out.channels(); x++) {
                if (!(out(x, y, z) == 42)) {
                    fprintf(stderr, "Incorrect pixel (%d) at x=%d y=%d z=%d.\n",
                            out(x, y, z), x, y, z);
                    return 1;
                }
            }
        }
    }

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

Add a trivial write only GLSL test.

Add a trivial write only GLSL test.

Former-commit-id: 7c0144cf1e95caa1d49b76543638e7e55fed6f6a


/**
 * @file
 *
 * The driver program.
 */
#include "bi/build/Driver.hpp"
#include "bi/exception/DriverException.hpp"
#include "bi/build/misc.hpp"

#include <iostream>

int main(int argc, char** argv) {
  using namespace bi;
  try {
    /* first option (should be a program name) */
    std::string prog;
    if (argc > 1) {
      prog = argv[1];
    } else {
      throw DriverException("No command given.");
    }

    Driver driver(argc - 1, argv + 1);
    if (prog.compare("build") == 0) {
      driver.build();
    } else if (prog.compare("install") == 0) {
      driver.install();
    } else if (prog.compare("uninstall") == 0) {
      driver.uninstall();
    } else if (prog.compare("dist") == 0) {
      driver.dist();
    } else if (prog.compare("clean") == 0) {
      driver.clean();
    } else if (prog.compare("init") == 0) {
      driver.init();
    } else if (prog.compare("check") == 0) {
      driver.check();
    } else if (prog.compare("docs") == 0) {
      driver.docs();
    } else {
      driver.run(prog + "_");  // underscore suffix for user-specified names
    }
  } catch (Exception& e) {
    std::cerr << e.msg << std::endl;
  }

  return 0;
}

/**
 * @file
 *
 * The driver program.
 */
#include "bi/build/Driver.hpp"
#include "bi/exception/DriverException.hpp"
#include "bi/build/misc.hpp"

#include <iostream>

int main(int argc, char** argv) {
  using namespace bi;
  try {
    /* first option (should be a program name) */
    std::string prog;
    if (argc > 1) {
      prog = argv[1];
    } else {
      throw DriverException("No command given.");
    }

    Driver driver(argc - 1, argv + 1);
    if (prog.compare("build") == 0) {
      driver.build();
    } else if (prog.compare("install") == 0) {
      driver.install();
    } else if (prog.compare("uninstall") == 0) {
      driver.uninstall();
    } else if (prog.compare("dist") == 0) {
      driver.dist();
    } else if (prog.compare("clean") == 0) {
      driver.clean();
    } else if (prog.compare("init") == 0) {
      driver.init();
    } else if (prog.compare("check") == 0) {
      driver.check();
    } else if (prog.compare("docs") == 0) {
      driver.docs();
    } else {
      driver.run(prog + "_");  // underscore suffix for user-specified names
    }
    return 0;
  } catch (Exception& e) {
    std::cerr << e.msg << std::endl;
    return 1;
  }
}

Return code of driver program now non-zero on error.


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

// This is a simple allocator based on the windows heap.

extern "C" {

HANDLE win_heap;

bool win_heap_init(bool use_lfh) {
  win_heap = HeapCreate(0, 0, 0);
  if (win_heap == NULL)
    return false;

  if (use_lfh) {
    ULONG enable_lfh = 2;
    HeapSetInformation(win_heap, HeapCompatibilityInformation,
                       &enable_lfh, sizeof(enable_lfh));
    // NOTE: Setting LFH may fail.  Vista already has it enabled.
    //       And under the debugger, it won't use LFH.  So we
    //       ignore any errors.
  }

  return true;
}

void* win_heap_malloc(size_t s) {
  return HeapAlloc(win_heap, 0, s);
}

void* win_heap_realloc(void* p, size_t s) {
  if (!p)
    return win_heap_malloc(s);
  return HeapReAlloc(win_heap, 0, p, s);
}

void win_heap_free(void* s) {
  HeapFree(win_heap, 0, s);
}

size_t win_heap_msize(void* p) {
  return HeapSize(win_heap, 0, p);
}

}  // extern "C"

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

// This is a simple allocator based on the windows heap.

extern "C" {

HANDLE win_heap;

bool win_heap_init(bool use_lfh) {
  win_heap = HeapCreate(0, 0, 0);
  if (win_heap == NULL)
    return false;

  if (use_lfh) {
    ULONG enable_lfh = 2;
    HeapSetInformation(win_heap, HeapCompatibilityInformation,
                       &enable_lfh, sizeof(enable_lfh));
    // NOTE: Setting LFH may fail.  Vista already has it enabled.
    //       And under the debugger, it won't use LFH.  So we
    //       ignore any errors.
  }

  return true;
}

void* win_heap_malloc(size_t size) {
  return HeapAlloc(win_heap, 0, size);
}

void win_heap_free(void* size) {
  HeapFree(win_heap, 0, size);
}

void* win_heap_realloc(void* ptr, size_t size) {
  if (!ptr)
    return win_heap_malloc(size);
  if (!size) {
    win_heap_free(ptr);
    return NULL;
  }
  return HeapReAlloc(win_heap, 0, ptr, size);
}

size_t win_heap_msize(void* ptr) {
  return HeapSize(win_heap, 0, ptr);
}

}  // extern "C"

Fix the windows allocator to behave properly on realloc.

The spec says that calling realloc(ptr, 0) should free ptr
and return NULL.

BUG=none
TEST=none

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

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


#include "Moves/Queenside_Castle.h"

#include "Moves/Move.h"
#include "Game/Board.h"
#include "Pieces/Piece.h"

Queenside_Castle::Queenside_Castle() : Move(-2, 0)
{
}

bool Queenside_Castle::move_specific_legal(const Board& board, char file_start, int rank_start) const
{
    return     ! board.piece_has_moved(file_start, rank_start)
            && ! board.piece_has_moved('a', rank_start)
            && ! board.king_is_in_check(board.whose_turn())
            && board.safe_for_king('d', rank_start, board.whose_turn())
            && ! board.view_piece_on_square('b', rank_start);
}

bool Queenside_Castle::can_capture() const
{
    return false;
}

void Queenside_Castle::side_effects(Board& board, char /* file_start */, int rank_start) const
{
    board.make_move('a', rank_start, 'd', rank_start); // move Rook
}

std::string Queenside_Castle::name() const
{
    return "Queenside Castle";
}

std::string Queenside_Castle::game_record_item(const Board&, char, int) const
{
    return "O-O-O";
}

#include "Moves/Queenside_Castle.h"

#include "Moves/Move.h"
#include "Game/Board.h"
#include "Pieces/Piece.h"

Queenside_Castle::Queenside_Castle() : Move(-2, 0)
{
}

bool Queenside_Castle::move_specific_legal(const Board& board, char file_start, int rank_start) const
{
    return     ! board.piece_has_moved(file_start, rank_start)
            && ! board.piece_has_moved('a', rank_start)
            && ! board.view_piece_on_square('b', rank_start)
            && ! board.king_is_in_check(board.whose_turn())
            && board.safe_for_king('d', rank_start, board.whose_turn());
}

bool Queenside_Castle::can_capture() const
{
    return false;
}

void Queenside_Castle::side_effects(Board& board, char /* file_start */, int rank_start) const
{
    board.make_move('a', rank_start, 'd', rank_start); // move Rook
}

std::string Queenside_Castle::name() const
{
    return "Queenside Castle";
}

std::string Queenside_Castle::game_record_item(const Board&, char, int) const
{
    return "O-O-O";
}

Put fast legality checks first

Put fast legality checks first


/*
 @ 0xCCCCCCCC
*/

int main()
{
    return 0;
}

/*
 @ 0xCCCCCCCC
*/

#include <conio.h>

#include <random>
#include <sstream>

#include "klog/klog_worker.h"

void WorkerTest()
{
    klog::LogWorker worker(std::wstring(L"test.log"), std::chrono::seconds(3));
    std::random_device rd;
    std::default_random_engine engine(rd());
    std::uniform_int_distribution<> dist(100, 1000);
    int count = 10;
    for (auto i = 0; i < count; ++i) {
        std::ostringstream ss;
        ss << "This is the " << i << "th trial\n";
        worker.Send(ss.str());
        ss.clear();
        std::this_thread::sleep_for(std::chrono::milliseconds(dist(engine)));
    }
}

int main()
{
    _getch();
    return 0;
}

Add quick test for logging worker.

Add quick test for logging worker.


#include "./ShapeSphere.hpp"
#include "math/misc.hpp"
#include "math/Sphere.hpp"
#include <cmath>

using namespace yks;

Optional<float> ShapeSphere::hasIntersection(const Ray& r) const {
	const Ray local_ray = transform.localFromParent * r;
	return intersect_with_sphere(vec3_0, 1.0f, local_ray);
}

Optional<Intersection> ShapeSphere::intersect(const Ray& r) const {
	const Ray local_ray = transform.localFromParent * r;
	const Optional<float> intersection = intersect_with_sphere(vec3_0, 1.0f, local_ray);

	if (!intersection) {
		return Optional<Intersection>();
	}
	const float t = *intersection;

	Intersection i;
	i.t = t;
	i.position = r(t);
	vec3 local_pos = local_ray(t);
	i.uv = mvec2(std::atan2(local_pos[2], local_pos[0]) / (2*pi) + 0.5f, std::acos(local_pos[1]) / pi);
	i.normal = mvec3(transpose(transform.localFromParent) * mvec4(normalized(local_ray(t)), 0.0f));
	return make_optional<Intersection>(i);
}

#include "./ShapeSphere.hpp"
#include "math/misc.hpp"
#include "math/Sphere.hpp"
#include <cmath>

using namespace yks;

Optional<float> ShapeSphere::hasIntersection(const Ray& r) const {
	const Ray local_ray = transform.localFromParent * r;
	return intersect_with_sphere(vec3_0, 1.0f, local_ray);
}

Optional<Intersection> ShapeSphere::intersect(const Ray& r) const {
	const Ray local_ray = transform.localFromParent * r;
	const Optional<float> intersection = intersect_with_sphere(vec3_0, 1.0f, local_ray);

	if (!intersection) {
		return Optional<Intersection>();
	}
	const float t = *intersection;

	Intersection i;
	i.t = t;
	i.position = r(t);
	vec3 local_pos = local_ray(t);
	i.uv = mvec2(std::atan2(local_pos[2], local_pos[0]) / (2*pi) + 0.5f, std::acos(local_pos[1]) / pi);
	i.normal = normalized(mvec3(transpose(transform.localFromParent) * mvec4(local_ray(t), 0.0f)));
	return make_optional<Intersection>(i);
}

Fix normal calculation for scaled spheres.


#include <stdexcept>

#include "gtest/gtest.h"
#include "map/Level.h"
#include "map/Tile.h"

TEST(LevelTest, DefaultLevelIsWalls)
{
	Level l1(10, 10);

	EXPECT_EQ(WallTile, l1.getTile(5, 5));
}

TEST(LevelTest, LevelGetTile)
{
	Level l1(10, 10);

	EXPECT_NO_THROW(l1.getTile(5, 5));
	EXPECT_THROW(l1.getTile(50, 50), std::out_of_range);
}

TEST(LevelTest, LevelArrayAccess)
{
	Level l1(10, 10);

	EXPECT_NO_THROW(l1[5][5]);
	EXPECT_THROW(l1[50][50], std::out_of_range);
}

#include <stdexcept>

#include "gtest/gtest.h"
#include "map/Level.h"
#include "map/Tile.h"

TEST(LevelTest, DefaultLevelIsWalls)
{
	Level l1(10, 10);

	EXPECT_EQ(WallTile, l1.getTile(5, 5));
}

TEST(LevelTest, LevelGetTile)
{
	Level l1(10, 10);

	EXPECT_NO_THROW(l1.getTile(9, 9));
	EXPECT_THROW(l1.getTile(10, 10), std::out_of_range);
}

TEST(LevelTest, LevelArrayAccess)
{
	Level l1(10, 10);

	EXPECT_NO_THROW(l1[9][9]);
	EXPECT_THROW(l1[10][10], std::out_of_range);
}

Modify Level tests to focus on boundaries.


// RUN: %clangxx_asan -coverage -O0 %s -o %t
// RUN: %env_asan_opts=check_initialization_order=1 %run %t 2>&1 | FileCheck %s
// XFAIL: android
#include <stdio.h>
int foo() { return 1; }
int XXX = foo();
int main() {
  printf("PASS\n");
// CHECK: PASS
}

// RUN: %clangxx_asan -coverage -O0 %s -o %t
// RUN: %env_asan_opts=check_initialization_order=1 %run %t 2>&1 | FileCheck %s
// XFAIL: android
// We don't really support running tests using profile runtime on Windows.
// UNSUPPORTED: win32
#include <stdio.h>
int foo() { return 1; }
int XXX = foo();
int main() {
  printf("PASS\n");
// CHECK: PASS
}

[ASan] Disable test that uses profile runtime on Windows.

git-svn-id: c199f293c43da69278bea8e88f92242bf3aa95f7@260561 91177308-0d34-0410-b5e6-96231b3b80d8


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

#include "libEGL/AttributeMap.h"

namespace egl
{

AttributeMap::AttributeMap()
{
}

AttributeMap::AttributeMap(const EGLint *attributes)
{
    for (const EGLint *curAttrib = attributes; curAttrib[0] != EGL_NONE; curAttrib++)
    {
        insert(curAttrib[0], curAttrib[1]);
    }
}

void AttributeMap::insert(EGLint key, EGLint value)
{
    mAttributes[key] = value;
}

bool AttributeMap::contains(EGLint key) const
{
    return (mAttributes.find(key) != mAttributes.end());
}

EGLint AttributeMap::get(EGLint key, EGLint defaultValue) const
{
    std::map<EGLint, EGLint>::const_iterator iter = mAttributes.find(key);
    return (mAttributes.find(key) != mAttributes.end()) ? iter->second : defaultValue;
}

}

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

#include "libEGL/AttributeMap.h"

namespace egl
{

AttributeMap::AttributeMap()
{
}

AttributeMap::AttributeMap(const EGLint *attributes)
{
    for (const EGLint *curAttrib = attributes; curAttrib[0] != EGL_NONE; curAttrib += 2)
    {
        insert(curAttrib[0], curAttrib[1]);
    }
}

void AttributeMap::insert(EGLint key, EGLint value)
{
    mAttributes[key] = value;
}

bool AttributeMap::contains(EGLint key) const
{
    return (mAttributes.find(key) != mAttributes.end());
}

EGLint AttributeMap::get(EGLint key, EGLint defaultValue) const
{
    std::map<EGLint, EGLint>::const_iterator iter = mAttributes.find(key);
    return (mAttributes.find(key) != mAttributes.end()) ? iter->second : defaultValue;
}

}

Fix an incorrect iteration over EGL attributes.

BUG=angle:490

Change-Id: If7a86ee0a5226f2b45e26bbadf4a84f8f605d1c2
Reviewed-on: https://chromium-review.googlesource.com/227231
Reviewed-by: Jamie Madill <7e492b4f1c8458024932de3ba475cbf015424c30@chromium.org>
Tested-by: Geoff Lang <b6fc25fe0362055230985c05cbfa8adb741ccc0f@chromium.org>


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

#include "content/renderer/render_view_impl.h"

#include "base/command_line.h"
#include "base/message_loop.h"
#include "cc/trees/layer_tree_host.h"
#include "content/renderer/gpu/render_widget_compositor.h"

namespace content {

void RenderViewImpl::OnUpdateTopControlsState(bool enable_hiding,
                                              bool enable_showing,
                                              bool animate) {
  DCHECK(compositor_);
  if (compositor_) {
    compositor_->UpdateTopControlsState(enable_hiding, enable_showing, animate);
  }
}

}  // namespace content

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

#include "content/renderer/render_view_impl.h"

#include "base/command_line.h"
#include "base/message_loop.h"
#include "cc/trees/layer_tree_host.h"
#include "content/renderer/gpu/render_widget_compositor.h"

namespace content {

void RenderViewImpl::OnUpdateTopControlsState(bool enable_hiding,
                                              bool enable_showing,
                                              bool animate) {
  // TODO(tedchoc): Investigate why messages are getting here before the
  //                compositor has been initialized.
  LOG_IF(WARNING, !compositor_) << "OnUpdateTopControlsState was unhandled.";
  if (compositor_)
    compositor_->UpdateTopControlsState(enable_hiding, enable_showing, animate);
}

}  // namespace content

Remove DCHECK on the compositor in OnEnableHidingTopControls.

It is crashing our tests.  Removing while I investigate whether these
IPCs are getting sent before the compositor was initialized or after it
died.

BUG=224511
NOTRY=true

Review URL: https://chromiumcodereview.appspot.com/13142006

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


#include "main.h"

#include <boost/program_options.hpp>
#include <iostream>

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

int main(int argc, char **argv)
{
	po::options_description program_desc("Simplicity window manager");

	program_desc.add_options()
		("help", "Display usage")
	;

	po::variables_map args;
	po::store(po::parse_command_line(argc, argv, program_desc), args);
	po::notify(args);

	if (args.count("help"))
	{
		cout << program_desc << endl;
		return 1;
	}

	return 0;
}

#include "main.h"

#include <boost/program_options.hpp>
#include <iostream>

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

void print_version(void);

int main(int argc, char **argv)
{
	po::options_description program_desc("Simplicity window manager");

	program_desc.add_options()
		("help",    "Display usage")
		("version", "Print simplicity version")
	;

	po::variables_map args;
	po::store(po::parse_command_line(argc, argv, program_desc), args);
	po::notify(args);

	if (args.count("help"))
	{
		cout << program_desc << endl;
		return 1;
	}

	if (args.count("version"))
	{
		print_version();
		return 0;
	}

	return 0;
}

void print_version(void)
{
	cout << PACKAGE_STRING << endl;
	cout << "Copyright (C) 2014 James Durand\n"
			"This is free software; see the source for copying conditions.\n"
			"There is NO warranty." << endl;
}

Add version command line option

Add version command line option


/**
* Assimp2XML3D
*
* Copyright (c)2015, Christian Schlinkmann
*
*
**/

#include <assimp/version.h>
#include <assimp/postprocess.h>
#include <assimp/scene.h>
#include <assimp/Importer.hpp>
#include <assimp/Exporter.hpp>

#include <iostream>

int invalidUsageExit() {
	std::cout << "usage: assimp2xml3d [FLAGS] inputFile [outputFile]" << std::endl;
	return -1;
}

int main(int argc, char *argv[]) {
	if (argc < 2) {
		return invalidUsageExit();
	}

}

/**
* Assimp2XML3D
*
* Copyright (c)2015, Christian Schlinkmann
*
*
**/

#include <assimp/version.h>
#include <assimp/postprocess.h>
#include <assimp/scene.h>
#include <assimp/Importer.hpp>
#include <assimp/Exporter.hpp>

#include <iostream>

extern Assimp::Exporter::ExportFormatEntry Assimp2XML3D_desc;

int invalidUsageExit() {
	std::cout << "usage: assimp2xml3d [FLAGS] inputFile [outputFile]" << std::endl;
	return -1;
}

int main(int argc, char *argv[]) {
	if (argc < 3) {
		return invalidUsageExit();
	}

	const char* input = argv[1], *output = argv[2];

	Assimp::Importer importer;
	importer.SetPropertyBool(AI_CONFIG_PP_FD_REMOVE, true);

	const aiScene* const scene = importer.ReadFile(input, aiProcessPreset_TargetRealtime_MaxQuality);

	if (!scene) {
		std::cerr << "Assimp: Could not read file " << input << std::endl;
		return -1;
	}

	std::cout << "Assimp read file successfully";

	Assimp::Exporter exporter;
	exporter.RegisterExporter(Assimp2XML3D_desc);
	exporter.Export(scene, "xml", output);
}

Add the barebones logic needed to import a scene into Assimp and start exporting it


#include <iostream>
#include <stdexcept>
#include <string>
#include "application.hpp"
#include <GL/glew.h>

void init_glew()
{
    GLenum err = glewInit();
    if (GLEW_OK != err)
    {
        throw std::runtime_error(reinterpret_cast<const char *>(glewGetErrorString(err)));
    }
}

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

    try
    {
        Application atlasTest {800, 600, "Atlas Tests"};

        init_glew();
        glClearColor(0.5f, 0.5f, 0.5f, 1.0f);

        while (atlasTest.process_events())
        {
            glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
            atlasTest.swap();
        }

    } catch (std::runtime_error &err) {
        SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_ERROR, "Runtime Error", err.what(), nullptr);
        return 1;
    }

    return 0;
}

#include <iostream>
#include <stdexcept>
#include <string>
#include "application.hpp"
#include <GL/glew.h>

void init_sdl()
{
    if (SDL_Init(SDL_INIT_EVERYTHING) != 0)
    {
        throw std::runtime_error(SDL_GetError());
    }
}

void init_glew()
{
    GLenum err = glewInit();
    if (GLEW_OK != err)
    {
        throw std::runtime_error(reinterpret_cast<const char *>(glewGetErrorString(err)));
    }
}

void run()
{
    init_sdl();
    Application atlasTest {800, 600, "Atlas Tests"};

    init_glew();
    glClearColor(0.5f, 0.5f, 0.5f, 1.0f);

    while (atlasTest.process_events())
    {
        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
        atlasTest.swap();
    }
}

int main(int argc, char const *argv[])
{
    // This is mainly is a global exception handler to show friendly messages to users.

    try
    {
        run();

    } catch (std::runtime_error &err) {
        SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_ERROR, "Runtime Error", err.what(), nullptr);
        return 1;
    }

    return 0;
}

Add error handling to sdl init.

Add error handling to sdl init.


#include <cstdlib>
#include <iostream>
#include <boost/asio.hpp>
#include <boost/thread.hpp>
#include <proxylib/proxylib.h>

void signal_handler(int signal) {
	fprintf(stderr, "Received signal %d\nExiting...\n", signal);
	exit(0);
}

void install_sighandlers() {
	signal(SIGHUP, SIG_IGN);
	signal(SIGINT, signal_handler);
	signal(SIGTERM, signal_handler);
	signal(SIGKILL, signal_handler);
	signal(SIGQUIT, signal_handler);
}

int main(int argc, char** argv) {
	try {
		if (argc != 2) {
			std::cerr << "Usage: proxy <port>" << std::endl;
			return EXIT_FAILURE;
		}

		install_sighandlers();

		namespace socks4a = proxylib::asio::socks4a;

		boost::asio::io_service	io_service;
		socks4a::server			server(io_service, std::atoi(argv[1]));
		boost::thread			server_thread;

		server_thread = boost::thread(boost::bind(&socks4a::server::run, &server));
		server_thread.join();
//		server.run();
	} catch (std::exception& ex) {
		std::cerr << "Exception: " << ex.what() << std::endl;
	}

	return EXIT_SUCCESS;
}

#include <cstdlib>
#include <iostream>
#include <boost/asio.hpp>
#include <boost/thread.hpp>
#include <proxylib/proxylib.h>

void signal_handler(int signal) {
	std::cerr << "Received signal "  << signal << "\nExiting..." << std::endl;
	exit(0);
}

void install_sighandlers() {
	signal(SIGHUP, SIG_IGN);
	signal(SIGINT, signal_handler);
	signal(SIGTERM, signal_handler);
	signal(SIGKILL, signal_handler);
	signal(SIGQUIT, signal_handler);
}

int main(int argc, char** argv) {
	try {
		if (argc != 2) {
			std::cerr << "Usage: proxy <port>" << std::endl;
			return EXIT_FAILURE;
		}

		install_sighandlers();

		namespace socks4a = proxylib::asio::socks4a;

		boost::asio::io_service	io_service;
		socks4a::server			server(io_service, std::atoi(argv[1]));
		boost::thread			server_thread;

		server_thread = boost::thread(boost::bind(&socks4a::server::run, &server));
		server_thread.join();
//		server.run();
	} catch (std::exception& ex) {
		std::cerr << "Exception: " << ex.what() << std::endl;
	}

	return EXIT_SUCCESS;
}

Use std ostream instead of fprintf.

Use std ostream instead of fprintf.


#include "crash_reporting.h"

#include "infrastructure/breakpad.h"
#include <fmt/format.h>
#include "platform/windows.h"

Breakpad::Breakpad(const std::wstring &crashDumpFolder, bool fullDump)
{

	mHandler = std::make_unique<InProcessCrashReporting>(crashDumpFolder, fullDump, [this](const std::wstring &minidump_path) {

		auto msg = fmt::format(L"Sorry! TemplePlus seems to have crashed. A crash report was written to {}.\n\n"
			L"If you want to report this issue, please contact us on our forums at RPGCodex or send an email to templeplushelp@gmail.com.",
			minidump_path);
		if (!extraMessage().empty()) {
			msg.append(extraMessage());
		}

		// Now starts the tedious work of reporting on this crash, heh.
		MessageBox(NULL, msg.c_str(), L"TemplePlus Crashed - Oops!", MB_OK);

	});

}

Breakpad::~Breakpad()
{
}

#include "crash_reporting.h"

#include "infrastructure/breakpad.h"
#include <fmt/format.h>
#include "platform/windows.h"
#include <infrastructure/stringutil.h>
#include <filesystem>
#include <Shlwapi.h>

namespace fs = std::filesystem;

Breakpad::Breakpad(const std::wstring &crashDumpFolder, bool fullDump)
{

	mHandler = std::make_unique<InProcessCrashReporting>(crashDumpFolder, fullDump, [this, crashDumpFolder](const std::wstring &minidump_path) {

		auto msg = fmt::format(L"Sorry! TemplePlus seems to have crashed. A crash report was written to {}.\n\n"
			L"If you want to report this issue, please contact us on our forums at RPGCodex or send an email to templeplushelp@gmail.com.",
			minidump_path);
		if (!extraMessage().empty()) {
			msg.append(extraMessage());
		}

		// Now starts the tedious work of reporting on this crash, heh.
		MessageBox(NULL, msg.c_str(), L"TemplePlus Crashed - Oops!", MB_OK);

		// copy the log so it doesn't get erased on next startup
		try {
			std::wstring logfilename = crashDumpFolder + L"TemplePlus.log";
			auto logfilenameNew = fs::path(minidump_path).replace_extension("log");

			std::filesystem::copy(logfilename, logfilenameNew);
		}
		catch (...) {

		}
	});

}

Breakpad::~Breakpad()
{
}

Copy logfile when crashed so users don't have to do so manually


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

#include "chrome/browser/extensions/extension_function.h"

#include "chrome/browser/extensions/extension_function_dispatcher.h"

void ExtensionFunction::SendResponse(bool success) {
  if (success) {
    dispatcher_->SendResponse(this);
  } else {
    // TODO(aa): In case of failure, send the error message to an error
    // callback.
  }
}

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

#include "chrome/browser/extensions/extension_function.h"

#include "chrome/browser/extensions/extension_function_dispatcher.h"

void ExtensionFunction::SendResponse(bool success) {
  if (success) {
    if (has_callback()) {
      dispatcher_->SendResponse(this);
    }
  } else {
    // TODO(aa): In case of failure, send the error message to an error
    // callback.
  }
}

Check that the ExtensionFunction has a callback for attempting to send a response.

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

git-svn-id: dd90618784b6a4b323ea0c23a071cb1c9e6f2ac7@13406 4ff67af0-8c30-449e-8e8b-ad334ec8d88c


#include "Context.hpp"

Context* _global_ctx = nullptr;

namespace Backend {
  void init_global_context() {
    if (!_global_ctx)
      _global_ctx = new Context;
    // TODO: Add other device types (esp CUDA)
    _global_ctx->device = SPIKE_DEVICE_DUMMY;
  }

  Context* get_current_context() {
    return _global_ctx;
  }
}

#include "Context.hpp"

Context* _global_ctx = nullptr;

namespace Backend {
  void init_global_context() {
    if (!_global_ctx)
      _global_ctx = new Context;
    // TODO: Add other device types (esp CUDA)
#ifdef SPIKE_WITH_CUDA
    _global_ctx->device = SPIKE_DEVICE_CUDA;
#else
    _global_ctx->device = SPIKE_DEVICE_DUMMY;
#endif
  }

  Context* get_current_context() {
    return _global_ctx;
  }
}

Switch default device type to CUDA if available; now to fix runtime errors and TODO items