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

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

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

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

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

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

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

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

  return render_view_host_->Send(message);
}

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

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

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

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

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

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

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

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

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

  return render_view_host_->Send(message);
}

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

Fix invalid write in RenderViewHostObserver.


#define CATCH_CONFIG_RUNNER
#include "Catch/catch.hpp"

#include <memory>

#include "decoration.hpp"
#include "printing.hpp"

#include "TestUtils.hpp"

int
main(int argc, const char *argv[])
{
    PrintingSettings::set(std::make_shared<TestSettings>());

    decor::disableDecorations();

    // Remove destination directory if it exists to account for crashes.
    TempDirCopy tempDirCopy("tests/test-repo/_git", "tests/test-repo/.git",
                            true);

    return Catch::Session().run(argc, argv);
}

#define CATCH_CONFIG_RUNNER
#include "Catch/catch.hpp"

#include <boost/algorithm/string/predicate.hpp>

#include <cstdlib>
#include <cstring>

#include <memory>

#include "decoration.hpp"
#include "printing.hpp"

#include "TestUtils.hpp"

int
main(int argc, const char *argv[])
{
    // Drop all `GIT_*` environment variables as they might interfere with
    // running some tests.
    extern char **environ;
    for (char **e = environ; *e != NULL; ++e) {
        if (boost::starts_with(*e, "GIT_")) {
            unsetenv(std::string(*e, std::strchr(*e, '=')).c_str());
        }
    }

    PrintingSettings::set(std::make_shared<TestSettings>());

    decor::disableDecorations();

    // Remove destination directory if it exists to account for crashes.
    TempDirCopy tempDirCopy("tests/test-repo/_git", "tests/test-repo/.git",
                            true);

    return Catch::Session().run(argc, argv);
}

Drop all GIT_* variables in tests


#include "../src/Sphere.h"
#include "../src/Plane.h"

void World::build() {
	vp.set_hres(200);
	vp.set_vres(200);
	vp.set_pixel_size(1.0);
	tracerPtr = new MultipleObjects(this);
	backgroundColor = RGBColor(0.0f, 0.0f, 0.0f);

	Sphere* sphere_ptr = new Sphere;
	sphere_ptr->setCenter(glm::vec3(0.0f, -25.0f, 0.0f));
	sphere_ptr->setRadius(80);
	sphere_ptr->setColor(1, 0, 0);
	addObject(sphere_ptr);

	sphere_ptr = new Sphere(glm::vec3(0.0f, 30.0f, 0.0f), 60.0f);
	sphere_ptr->setColor(1, 1, 0);
	addObject(sphere_ptr);

	Plane* plane_ptr = new Plane(glm::vec3(0.0f, 0.0f, 0.0f), glm::vec3(0.0f, 1.0f, 1.0f));
	plane_ptr->setColor(0.0, 0.3, 0.0);
	addObject(plane_ptr);

}

#include "../src/Sphere.h"
#include "../src/Plane.h"
#include <iostream>

using namespace std;

void World::build() {
	vp.set_hres(200);
	vp.set_vres(200);
	vp.set_pixel_size(1.0);
	tracerPtr = new MultipleObjects(this);
	backgroundColor = RGBColor(0.0f, 0.0f, 0.0f);

	Sphere* sphere_ptr = new Sphere;
	sphere_ptr->setCenter(glm::vec3(0.0f, -25.0f, 0.0f));
	sphere_ptr->setRadius(80);
	sphere_ptr->setColor(1, 0, 0);
	addObject(sphere_ptr);

	sphere_ptr = new Sphere;
	sphere_ptr->setCenter(glm::vec3(0.0f, 30.0f, 0.0f));
	sphere_ptr->setRadius(60);
	sphere_ptr->setColor(1, 1, 0);
	addObject(sphere_ptr);

	Plane* plane_ptr = new Plane(glm::vec3(0.0f, 0.0f, 0.0f), glm::vec3(0.0f, 1.0f, 1.0f));
	plane_ptr->setColor(0.0, 0.3, 0.0);
	addObject(plane_ptr);

}

Make some small changes on the code without changing its semantics


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

// Disabled, http://crbug.com/30151.
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, DISABLED_Toolstrip) {
  ASSERT_TRUE(RunExtensionTest("toolstrip")) << 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 "chrome/browser/extensions/extension_apitest.h"

// Disabled, http://crbug.com/30151 (Linux and ChromeOS),
// http://crbug.com/35034 (others).
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, DISABLED_Toolstrip) {
  ASSERT_TRUE(RunExtensionTest("toolstrip")) << message_;
}

Update bug reference link in ExtensionApiTest.Toolstrip


#include "qmimedatabase.h"

#include <QtCore/QCoreApplication>
#include <QtCore/QFile>

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

    if (argc <= 1) {
        printf( "No filename specified\n" );
        return 1;
    }
    QString option;
    int fnPos = 1;
    if (argc > 2) {
        option = QString::fromLatin1(argv[1]);
        ++fnPos;
    }
    const QString fileName = QFile::decodeName(argv[fnPos]);
    //int accuracy;
    QMimeDatabase db;
    QMimeType mime;
    if (fileName == QLatin1String("-")) {
        QFile qstdin;
        qstdin.open(stdin, QIODevice::ReadOnly);
        const QByteArray data = qstdin.readAll();
        //mime = QMimeType::findByContent(data, &accuracy);
        mime = db.findByData(data);
    } else if (option == "-c") {
        QFile file(fileName);
        if (file.open(QIODevice::ReadOnly)) {
            mime = db.findByData(file.read(32000));
        }
    } else {
        //mime = QMimeType::findByPath(fileName, 0, args->isSet("f"), &accuracy);
        mime = db.findByFile(fileName);
    }
    if ( mime.isValid() /*&& !mime.isDefault()*/ ) {
        printf("%s\n", mime.name().toLatin1().constData());
        //printf("(accuracy %d)\n", accuracy);
    } else {
        return 1; // error
    }

    return 0;
}

#include "qmimedatabase.h"

#include <QtCore/QCoreApplication>
#include <QtCore/QFile>

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

    if (argc <= 1) {
        printf( "No filename specified\n" );
        return 1;
    }
    QString option;
    int fnPos = 1;
    if (argc > 2) {
        option = QString::fromLatin1(argv[1]);
        ++fnPos;
    }
    const QString fileName = QFile::decodeName(argv[fnPos]);
    //int accuracy;
    QMimeDatabase db;
    QMimeType mime;
    if (fileName == QLatin1String("-")) {
        QFile qstdin;
        qstdin.open(stdin, QIODevice::ReadOnly);
        const QByteArray data = qstdin.readAll();
        //mime = QMimeType::findByContent(data, &accuracy);
        mime = db.findByData(data);
    } else if (option == "-c") {
        QFile file(fileName);
        if (file.open(QIODevice::ReadOnly)) {
            mime = db.findByData(file.read(32000));
        }
    } else if (option == "-f") {
        mime = db.findByName(fileName);
    } else {
        mime = db.findByFile(fileName);
    }
    if ( mime.isValid() /*&& !mime.isDefault()*/ ) {
        printf("%s\n", mime.name().toLatin1().constData());
        //printf("(accuracy %d)\n", accuracy);
    } else {
        return 1; // error
    }

    return 0;
}

Add option -f (file name only)


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

// <random>

// template <class UIntType, UIntType a, UIntType c, UIntType m>
//   class linear_congruential_engine;

// template<class Sseq> void seed(Sseq& q);

#include <random>
#include <cassert>

int main()
{
    {
        unsigned a[] = {3, 5, 7};
        std::seed_seq sseq(a, a+3);
        std::linear_congruential_engine<unsigned, 5, 7, 11> e1;
        std::linear_congruential_engine<unsigned, 5, 7, 11> e2(4);
        assert(e1 != e2);
        e1.seed(sseq);
        assert(e1 == e2);
    }
}

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

// <random>

// template <class UIntType, UIntType a, UIntType c, UIntType m>
//   class linear_congruential_engine;

// template<class Sseq> void seed(Sseq& q);

#include <random>
#include <cassert>

int main()
{
    {
        unsigned a[] = {3, 5, 7};
        std::seed_seq sseq(a, a+3);
        std::linear_congruential_engine<unsigned, 5, 7, 11> e1;
        std::linear_congruential_engine<unsigned, 5, 7, 11> e2(4);
        assert(e1 != e2);
        e1.seed(sseq);
        assert(e1 == e2);
    }
    {
        unsigned a[] = {3, 5, 7, 9, 11};
        std::seed_seq sseq(a, a+5);
        typedef std::linear_congruential_engine<unsigned long long, 1, 1, 0x200000001ULL> E;
        E e1(4309005589);
        E e2(sseq);
        assert(e1 == e2);
    }
}

Fix a couple of bugs in linear_congruential_engine::seed. Regression test added.


#include <gloperate/painter/PipelineOutputCapability.h>

#include <gloperate/base/collection.hpp>

#include <gloperate/pipeline/AbstractPipeline.h>

namespace gloperate
{

/**
*  @brief
*    Constructor
*/
PipelineOutputCapability::PipelineOutputCapability(const gloperate::AbstractPipeline & pipeline)
    : AbstractOutputCapability{}
    , m_pipeline { pipeline }
{
}

/**
*  @brief
*    Destructor
*/
PipelineOutputCapability::~PipelineOutputCapability()
{
}

std::vector<gloperate::AbstractData*> PipelineOutputCapability::allOutputs() const
{
    return m_pipeline.allOutputs();
}

}

#include <gloperate/painter/PipelineOutputCapability.h>

#include <gloperate/base/collection.hpp>

#include <gloperate/pipeline/AbstractPipeline.h>

namespace gloperate
{

/**
*  @brief
*    Constructor
*/
PipelineOutputCapability::PipelineOutputCapability(const gloperate::AbstractPipeline & pipeline)
    : AbstractOutputCapability{}
    , m_pipeline ( pipeline )
{
}

/**
*  @brief
*    Destructor
*/
PipelineOutputCapability::~PipelineOutputCapability()
{
}

std::vector<gloperate::AbstractData*> PipelineOutputCapability::allOutputs() const
{
    return m_pipeline.allOutputs();
}

}

Fix compilation for GCC 4.8.2


#include "types.h"

#include <cassert>

namespace nadam {

MessageInfo::MessageInfo(std::string name, uint32_t size, bool isVariableSize)
	: name{name}, size{size}, isVariableSize{isVariableSize},
	hash{constructHash(name, size, isVariableSize)} {
	assert(name.length());
}

util::sha1::hash MessageInfo::constructHash(const std::string& name, uint32_t size, bool isVariableSize) {
	util::sha1::Digest sha;
	sha.put(name.data(), static_cast<uint32_t>(name.size()));
	sha.put(isVariableSize);
	for (size_t i = 0; i < sizeof(size); ++i) {
		size_t byteNumber = sizeof(size) - 1 - i;
		sha.put(size >> 8 * byteNumber & 0xff);
	}
	return sha.finish();
}

} // namespace nadam

#include "types.h"

#include <cassert>

namespace nadam {

MessageInfo::MessageInfo(std::string name, uint32_t size, bool isVariableSize)
	: name(name), size(size), isVariableSize(isVariableSize),
	hash(constructHash(name, size, isVariableSize)) {
	assert(name.length());
}

util::sha1::hash MessageInfo::constructHash(const std::string& name, uint32_t size, bool isVariableSize) {
	util::sha1::Digest sha;
	sha.put(name.data(), static_cast<uint32_t>(name.size()));
	sha.put(isVariableSize);
	for (size_t i = 0; i < sizeof(size); ++i) {
		size_t byteNumber = sizeof(size) - 1 - i;
		sha.put(size >> 8 * byteNumber & 0xff);
	}
	return sha.finish();
}

} // namespace nadam

Make initializer list compatible with older GCC


#include <iostream>
#include "Shell.h"
#include "RemoteCommand.h"

namespace RhIO
{
    RemoteCommand::RemoteCommand(std::string fullName_, std::string desc_)
        : fullName(fullName_), desc(desc_), origin(""), name("")
    {
        auto found = fullName.find_last_of("/");
        if (found > 0) {
            origin = fullName.substr(0, found);
            name = fullName.substr(found+1);
        } else {
            name = fullName;
        }
    }

    std::string RemoteCommand::getName()
    {
        return name;
    }

    std::string RemoteCommand::getDesc()
    {
        return desc;
    }

    std::string RemoteCommand::getOrigin()
    {
        return origin;
    }

    void RemoteCommand::process(std::vector<std::string> args)
    {
        auto response = shell->getClient()->call(fullName, args);
        std::cout << response;
        if (response.size() && response[response.size()-1]!='\n') {
            std::cout << std::endl;
        }
    }
}

#include <iostream>
#include "Shell.h"
#include "RemoteCommand.h"

namespace RhIO
{
    RemoteCommand::RemoteCommand(std::string fullName_, std::string desc_)
        : fullName(fullName_), desc(desc_), origin(""), name("")
    {
        auto found = fullName.find_last_of("/");
        if (found != std::string::npos) {
            origin = fullName.substr(0, found);
            name = fullName.substr(found+1);
        } else {
            name = fullName;
        }
    }

    std::string RemoteCommand::getName()
    {
        return name;
    }

    std::string RemoteCommand::getDesc()
    {
        return desc;
    }

    std::string RemoteCommand::getOrigin()
    {
        return origin;
    }

    void RemoteCommand::process(std::vector<std::string> args)
    {
        auto response = shell->getClient()->call(fullName, args);
        std::cout << response;
        if (response.size() && response[response.size()-1]!='\n') {
            std::cout << std::endl;
        }
    }
}

Fix in Remote command name parsing


#include "listener.h"
#include "log.h"
#include "buffers.h"

void conditionalEnqueue(QUEUE_TYPE(uint8_t)* queue, uint8_t* message,
        int messageSize) {
    if(queue_available(queue) < messageSize + 2) {
        debug("Dropped incoming CAN message -- send queue (at %p) full\r\n",
                queue);
        return;
    }

    for(int i = 0; i < messageSize; i++) {
        QUEUE_PUSH(uint8_t, queue, (uint8_t)message[i]);
    }
    QUEUE_PUSH(uint8_t, queue, (uint8_t)'\r');
    QUEUE_PUSH(uint8_t, queue, (uint8_t)'\n');
}

void sendMessage(Listener* listener, uint8_t* message, int messageSize) {
    conditionalEnqueue(&listener->usb->sendQueue, message, messageSize);
    conditionalEnqueue(&listener->serial->sendQueue, message, messageSize);
}

void processListenerQueues(Listener* listener) {
    // Must always process USB, because this function usually runs the MCU's USB
    // task that handles SETUP and enumeration.
    processInputQueue(listener->usb);
    processInputQueue(listener->serial);
}

#include "listener.h"
#include "log.h"
#include "buffers.h"

bool conditionalEnqueue(QUEUE_TYPE(uint8_t)* queue, uint8_t* message,
        int messageSize) {
    if(queue_available(queue) < messageSize + 2) {
        return false;
    }

    for(int i = 0; i < messageSize; i++) {
        QUEUE_PUSH(uint8_t, queue, (uint8_t)message[i]);
    }
    QUEUE_PUSH(uint8_t, queue, (uint8_t)'\r');
    QUEUE_PUSH(uint8_t, queue, (uint8_t)'\n');
    return true;
}

void sendMessage(Listener* listener, uint8_t* message, int messageSize) {
    if(!conditionalEnqueue(&listener->usb->sendQueue, message, messageSize)) {
        debug("USB send queue full, dropping CAN message: %s\r\n", message);
    }

    if(!conditionalEnqueue(&listener->serial->sendQueue, message, messageSize)) {
        debug("UART send queue full, dropping CAN message: %s\r\n", message);
    }
}

void processListenerQueues(Listener* listener) {
    // Must always process USB, because this function usually runs the MCU's USB
    // task that handles SETUP and enumeration.
    processInputQueue(listener->usb);
    processInputQueue(listener->serial);
}

Print a queue-specific debug message when dropping CAN messages.


// 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/in_process_webkit/webkit_thread.h"
#include "testing/gtest/include/gtest/gtest.h"

TEST(WebKitThreadTest, ExposedInChromeThread) {
  int* null = NULL;  // Help the template system out.
  EXPECT_FALSE(ChromeThread::DeleteSoon(ChromeThread::WEBKIT, FROM_HERE, null));
  {
    WebKitThread thread;
    EXPECT_FALSE(ChromeThread::DeleteSoon(ChromeThread::WEBKIT,
                                          FROM_HERE, null));
    thread.Initialize();
    EXPECT_TRUE(ChromeThread::DeleteSoon(ChromeThread::WEBKIT,
                                         FROM_HERE, null));
  }
  EXPECT_FALSE(ChromeThread::DeleteSoon(ChromeThread::WEBKIT,
                                        FROM_HERE, null));
}

// 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/in_process_webkit/webkit_thread.h"
#include "testing/gtest/include/gtest/gtest.h"

TEST(WebKitThreadTest, DISABLED_ExposedInChromeThread) {
  int* null = NULL;  // Help the template system out.
  EXPECT_FALSE(ChromeThread::DeleteSoon(ChromeThread::WEBKIT, FROM_HERE, null));
  {
    WebKitThread thread;
    EXPECT_FALSE(ChromeThread::DeleteSoon(ChromeThread::WEBKIT,
                                          FROM_HERE, null));
    thread.Initialize();
    EXPECT_TRUE(ChromeThread::DeleteSoon(ChromeThread::WEBKIT,
                                         FROM_HERE, null));
  }
  EXPECT_FALSE(ChromeThread::DeleteSoon(ChromeThread::WEBKIT,
                                        FROM_HERE, null));
}

Disable WebKitThreadTest.ExposedInChromeThread, due to subsequent assert.


// 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/browser/renderer_host/render_widget_host_view.h"

#include "base/logging.h"

// static
void RenderWidgetHostView::GetDefaultScreenInfo(
    WebKit::WebScreenInfo* results) {
  NOTIMPLEMENTED();
}

////////////////////////////////////////////////////////////////////////////////
// RenderWidgetHostView, public:

// static
RenderWidgetHostView* RenderWidgetHostView::CreateViewForWidget(
    RenderWidgetHost* widget) {
  NOTIMPLEMENTED();
  return NULL;
}

// 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/browser/renderer_host/render_widget_host_view.h"

#include "base/logging.h"

// static
void RenderWidgetHostViewBase::GetDefaultScreenInfo(
    WebKit::WebScreenInfo* results) {
  NOTIMPLEMENTED();
}

////////////////////////////////////////////////////////////////////////////////
// RenderWidgetHostView, public:

// static
RenderWidgetHostView* RenderWidgetHostView::CreateViewForWidget(
    RenderWidgetHost* widget) {
  NOTIMPLEMENTED();
  return NULL;
}

Fix compile error when building content_unittests for android.


/**
 ******************************************************************************
 * Xenia : Xbox 360 Emulator Research Project                                 *
 ******************************************************************************
 * Copyright 2016 Ben Vanik. All rights reserved.                             *
 * Released under the BSD license - see LICENSE in the root for more details. *
 ******************************************************************************
 */

#include "xenia/gpu/vulkan/vulkan_gpu_flags.h"

DEFINE_bool(vulkan_renderdoc_capture_all, false,
            "Capture everything with RenderDoc.");
DEFINE_bool(vulkan_native_msaa, true, "Use native MSAA");
DEFINE_bool(vulkan_dump_disasm, false,
            "Dump shader disassembly. NVIDIA only supported.");

/**
 ******************************************************************************
 * Xenia : Xbox 360 Emulator Research Project                                 *
 ******************************************************************************
 * Copyright 2016 Ben Vanik. All rights reserved.                             *
 * Released under the BSD license - see LICENSE in the root for more details. *
 ******************************************************************************
 */

#include "xenia/gpu/vulkan/vulkan_gpu_flags.h"

DEFINE_bool(vulkan_renderdoc_capture_all, false,
            "Capture everything with RenderDoc.");
DEFINE_bool(vulkan_native_msaa, false, "Use native MSAA");
DEFINE_bool(vulkan_dump_disasm, false,
            "Dump shader disassembly. NVIDIA only supported.");

Disable Vulkan native MSAA by default for now.


#include <gtest/gtest.h>
TEST(MathTest, TwoPlusTwoEqualsFour) {
EXPECT_EQ(2 + 2, 4);
}
int main(int argc, char **argv) {
::testing::InitGoogleTest( &argc, argv );
return RUN_ALL_TESTS();
}

#include <gtest/gtest.h>
TEST(MathTest, TwoPlusTwoEqualsFour) {
EXPECT_EQ(2 + 2, 5);
}
int main(int argc, char **argv) {
::testing::InitGoogleTest( &argc, argv );
return RUN_ALL_TESTS();
}

Make sure Travis detects failing test


#include "removegrain.h"
#include "clense.h"
#include "repair.h"
#include "vertical_cleaner.h"

const AVS_Linkage *AVS_linkage = nullptr;

extern "C" __declspec(dllexport) const char* __stdcall AvisynthPluginInit3(IScriptEnvironment* env, const AVS_Linkage* const vectors) {
    AVS_linkage = vectors;

    env->AddFunction("RemoveGrain2", "c[mode]i[modeU]i[modeV]i[opt]s", Create_RemoveGrain, 0);
    env->AddFunction("Repair2", "cc[mode]i[modeU]i[modeV]i[opt]s", Create_Repair, 0);
    env->AddFunction("Clense2", "c[previous]c[next]c[grey]b", Create_Clense, 0);
    env->AddFunction("ForwardClense2", "c[grey]b", Create_ForwardClense, 0);
    env->AddFunction("BackwardClense2", "c[grey]b", Create_BackwardClense, 0);
    env->AddFunction("VerticalCleaner2", "c[mode]i[modeU]i[modeV]i", Create_VerticalCleaner, 0);
    return "Itai, onii-chan!";
}

#include "removegrain.h"
#include "clense.h"
#include "repair.h"
#include "vertical_cleaner.h"

const AVS_Linkage *AVS_linkage = nullptr;

extern "C" __declspec(dllexport) const char* __stdcall AvisynthPluginInit3(IScriptEnvironment* env, const AVS_Linkage* const vectors) {
    AVS_linkage = vectors;

    env->AddFunction("RemoveGrain", "c[mode]i[modeU]i[modeV]i[opt]s", Create_RemoveGrain, 0);
    env->AddFunction("Repair", "cc[mode]i[modeU]i[modeV]i[opt]s", Create_Repair, 0);
    env->AddFunction("Clense", "c[previous]c[next]c[grey]b", Create_Clense, 0);
    env->AddFunction("ForwardClense", "c[grey]b", Create_ForwardClense, 0);
    env->AddFunction("BackwardClense", "c[grey]b", Create_BackwardClense, 0);
    env->AddFunction("VerticalCleaner", "c[mode]i[modeU]i[modeV]i", Create_VerticalCleaner, 0);
    return "Itai, onii-chan!";
}

Remove 2 from all filters' names


#include "Sprite.h"

Sprite::Sprite() : Node()
{
    // Image
    m_sprite_path = "";
}

Sprite::Sprite(std::string p_sprite_path) : Sprite()
{
    m_sprite_path = p_sprite_path;
}

Sprite::~Sprite() {}

std::string Sprite::getSpritePath()
{
    return m_sprite_path;
}

#include "Sprite.h"

Sprite::Sprite() : Node()
{
    // Image
    m_sprite_path = "";
}

Sprite::Sprite(std::string p_sprite_path) : Node()
{
    // Image
    m_sprite_path = p_sprite_path;
}

Sprite::~Sprite() {}

std::string Sprite::getSpritePath()
{
    return m_sprite_path;
}

Use more useful ancestor constructor


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

#include "base/logging.h"
#include "googleurl/src/gurl.h"

namespace renderer_logging {

// Sets the URL that is logged if the renderer crashes. Use GURL() to clear
// the URL.
void SetActiveRendererURL(const GURL& url) {
  // TODO(port): Once breakpad is integrated we can turn this on.
  NOTIMPLEMENTED();
}

}  // namespace renderer_logging

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

#include "base/logging.h"
#include "googleurl/src/gurl.h"

namespace renderer_logging {

// Sets the URL that is logged if the renderer crashes. Use GURL() to clear
// the URL.
void SetActiveRendererURL(const GURL& url) {
  // crbug.com/9646
}

}  // namespace renderer_logging

Comment out a very annoying NOTIMPLEMENTED().


Matrix2f M = Matrix2f::Random();
Matrix2f m;
m = M;
cout << "Here is the matrix m:" << endl << m << endl;
cout << "Now we want to replace m by its own transpose." << endl;
cout << "If we do m = m.transpose(), then m becomes:" << endl;
m = m.transpose() * 1;
cout << m << endl << "which is wrong!" << endl;
cout << "Now let us instead do m = m.transpose().eval(). Then m becomes" << endl;
m = M;
m = m.transpose().eval();
cout << m << endl << "which is right." << endl;

Matrix2f M = Matrix2f::Random();
Matrix2f m;
m = M;
cout << "Here is the matrix m:" << endl << m << endl;
cout << "Now we want to copy a column into a row." << endl;
cout << "If we do m.col(1) = m.row(0), then m becomes:" << endl;
m.col(1) = m.row(0);
cout << m << endl << "which is wrong!" << endl;
cout << "Now let us instead do m.col(1) = m.row(0).eval(). Then m becomes" << endl;
m = M;
m.col(1) = m.row(0).eval();
cout << m << endl << "which is right." << endl;

Make snippet run successfully again: the snippet for 'eval' was taking m=m.transpose() as an example of code that needs an explicit call to eval(), but that doesn't work anymore now that we have the clever assert detecting aliasing issues.


#include "CogServer.h"
#include "QueryProcessor.h"
#include "WordSenseProcessor.h"

using namespace opencog;

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

    // Cheapo hack to get the query processory up and running.
    // XXX fix me with some more permanent, appropriate solution.
    QueryProcessor *qp = new QueryProcessor();
    server.plugInMindAgent(qp, 1);

    WordSenseProcessor *wsd = new WordSenseProcessor();
    server.plugInMindAgent(wsd, 1);

    server.serverLoop();
}

#include "CogServer.h"
#include "QueryProcessor.h"
#include "WordSenseProcessor.h"
#include "Config.h"

using namespace opencog;

static void usage(char* progname) {
    cerr << "Usage: " << progname << " [-c <config-file>]\n\n";
}

int main(int argc, char *argv[]) {
    // check command line
    if ((argc == 1) || ((argc == 3) && (strcmp(argv[1], "-c") == 0))) {
        // load the configuration from file if a filename was supplied on the command line
        if (argc == 3) {
            try {
                config().load(argv[2]);
            } catch (RuntimeException &e) {
                cerr << e.getMessage() << std::endl;
                return 1;
            }
        }

        // create server instance
        CogServer server;

        // Cheapo hack to get the query processory up and running.
        // XXX fix me with some more permanent, appropriate solution.
        server.plugInMindAgent(new QueryProcessor(), 1);
        server.plugInMindAgent(new WordSenseProcessor(), 1);

        server.serverLoop();
    } else {
        usage(argv[0]);
        return 1;
    }
}

Add support to optionally load configuration parameters from a file at runtime by using the option "-c".


#include <iostream>

#include <sqlpp11/postgresql/postgresql.h>
#include <sqlpp11/postgresql/insert.h>
//#include <sqlpp11/sqlpp11.h>

#include "Sample.h"

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

  // Configuration
  auto config = std::make_shared<sqlpp::postgresql::connection_config>();

  // DB connection
  sqlpp::postgresql::connection db(config);

  // Model
  test::TabBar t_bar;

  auto ins_news = insert_into(t_bar)
	  .set(t_bar.gamma = true, t_bar.beta = "test")
	  .returning(t_bar.beta);
  return 0;
}

#include <iostream>

#include <sqlpp11/postgresql/postgresql.h>
#include <sqlpp11/postgresql/insert.h>
//#include <sqlpp11/sqlpp11.h>

#include "Sample.h"

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

  // Configuration
  //auto config = std::make_shared<sqlpp::postgresql::connection_config>();

  // DB connection
  //sqlpp::postgresql::connection db(config);

  // Model
  test::TabBar t_bar;
  auto ins_news = insert_into(t_bar)
	  .set(t_bar.gamma = true, t_bar.beta = "test")
	  .returning(t_bar.beta);

  return 0;
}

Disable database connection for now.


#include "perceptioninfoprivate.h"

#include "btperceptioninfoscriptable.h"

using namespace GluonEngine;

PerceptionInfoPrivate::PerceptionInfoPrivate(QObject * parent)
	: QSharedData()
{
	info = new btPerceptionInfoScriptable(parent);
	QScriptValue extensionObject = engine.globalObject();
	script = 0;
}

PerceptionInfoPrivate::PerceptionInfoPrivate(const PerceptionInfoPrivate& other)
	: QSharedData()
	, info(other.info)
	, updateFunc(other.updateFunc)
	, drawFunc(other.drawFunc)
	, getAdjustedValueFunc(other.getAdjustedValueFunc)
	, script(other.script)
{
	QScriptValue extensionObject = engine.globalObject();
}

PerceptionInfoPrivate::~PerceptionInfoPrivate()
{
}

#include "perceptioninfoprivate.h"

#include "btperceptioninfoscriptable.h"

using namespace GluonEngine;

PerceptionInfoPrivate::PerceptionInfoPrivate(QObject * parent)
	: QSharedData()
{
	info = new btPerceptionInfoScriptable(parent);
	QScriptValue extensionObject = engine.globalObject();
	script = 0;
}

PerceptionInfoPrivate::PerceptionInfoPrivate(const PerceptionInfoPrivate& other)
	: QSharedData()
	, info(other.info)
	, drawFunc(other.drawFunc)
	, updateFunc(other.updateFunc)
	, getAdjustedValueFunc(other.getAdjustedValueFunc)
	, script(other.script)
{
	QScriptValue extensionObject = engine.globalObject();
}

PerceptionInfoPrivate::~PerceptionInfoPrivate()
{
}

Fix an initialization order issue in the copy ctor to avoid the warning


#include "simplegameworld.h"

void SimpleGameWorld::addEntity(shared_ptr< gamefw::Entity > entity)
{
    m_entity_list.push_back(entity);
}

void SimpleGameWorld::update()
{
    foreach(shared_ptr<gamefw::Entity> entity, m_entity_list) {
            entity->m_position.x += entity->m_velocity_local.x *
                            glm::cos(glm::radians(entity->m_orientation.x)) +
                            -entity->m_velocity_local.z *
                            glm::sin(glm::radians(entity->m_orientation.x));
            entity->m_position.z += entity->m_velocity_local.x *
                            glm::sin(glm::radians(entity->m_orientation.x)) +
                            entity->m_velocity_local.z *
                            glm::cos(glm::radians(entity->m_orientation.x));
            entity->m_position.y += entity->m_velocity_local.y;
    }
}

#include "simplegameworld.h"

void SimpleGameWorld::addEntity(shared_ptr< gamefw::Entity > entity)
{
    m_entity_list.push_back(entity);
}

void SimpleGameWorld::update()
{
    foreach(shared_ptr<gamefw::Entity> entity, m_entity_list) {
            entity->m_position.x += entity->m_velocity_local.x *
                            glm::cos(glm::radians(entity->m_orientation.x)) +
                            -entity->m_velocity_local.z *
                            glm::sin(glm::radians(entity->m_orientation.x));
            entity->m_position.z += entity->m_velocity_local.x *
                            glm::sin(glm::radians(entity->m_orientation.x)) +
                            entity->m_velocity_local.z *
                            glm::cos(glm::radians(entity->m_orientation.x));
            entity->m_position.y += entity->m_velocity_local.y;

	    entity->m_orientation += entity->m_angular_velocity;
    }
}

Add orientation update in SimpleGameWorld::Update.


#include "util/file_piece.hh"

#include "util/file.hh"
#include "util/scoped.hh"
#include "util/string_piece.hh"
#include "util/tokenize_piece.hh"
#include "util/murmur_hash.hh"
#include "util/probing_hash_table.hh"

#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>

#include <fstream>
#include <iostream>

#include <boost/scoped_array.hpp>
#include <boost/functional/hash.hpp>

int main() {

  std::fstream backing("../source.uniq.rand.gz", std::ios::in);
  util::FilePiece test(backing, NULL, 1);
  //An example of how not to read a file (try/catch), will change later, but for now, hacking
  while(true){
    try {
      StringPiece line = test.ReadLine();

      std::cout << line << std::endl;

    } catch (util::EndOfFileException e){
      std::cout << "End of file" << std::endl;
      break;
    }
  }

  return 0;
}

#include "util/file_piece.hh"

#include "util/file.hh"
#include "util/scoped.hh"
#include "util/string_piece.hh"
#include "util/tokenize_piece.hh"
#include "util/murmur_hash.hh"
#include "util/probing_hash_table.hh"

#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>

#include <fstream>
#include <iostream>

#include <boost/scoped_array.hpp>
#include <boost/functional/hash.hpp>

int main() {

  //std::fstream backing("../source.uniq.rand.gz", std::ios::in);
  util::FilePiece test("../source.uniq.rand.gz", NULL, 1);
  //An example of how not to read a file (try/catch), will change later, but for now, hacking
  while(true){
    try {
      StringPiece line = test.ReadLine();

      std::cout << line << std::endl;

    } catch (util::EndOfFileException e){
      std::cout << "End of file" << std::endl;
      break;
    }
  }

  return 0;
}

Fix reading from archived file in example


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

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

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

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

namespace tensorflow {
namespace tpu {

/* static */
void TpuCompilationCacheMetrics::IncrementCacheLookupCount(
    bool is_cache_hit, absl::string_view session_name) {
  // A placeholder for tracking metrics.
}

/* static */
void TpuCompilationCacheMetrics::SetCacheEntryCount(int64 count) {
  // A placeholder for tracking metrics.
}

}  // namespace tpu
}  // namespace tensorflow

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

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

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

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

namespace tensorflow {
namespace tpu {

// TODO(henrytan): remove this once `TpuCompilationCache` migration to OSS is
// completed.
#if defined(LIBTFTPU)
/* static */
void TpuCompilationCacheMetrics::IncrementCacheLookupCount(
    bool is_cache_hit, absl::string_view session_name) {
  // A placeholder for tracking metrics.
}

/* static */
void TpuCompilationCacheMetrics::SetCacheEntryCount(int64 count) {
  // A placeholder for tracking metrics.
}
#endif  // LIBTFTPU

}  // namespace tpu
}  // namespace tensorflow

Add LIBTFTPU macro qualifier to the definition of the TpuCompilationCacheMetrics.


// Clang on MacOS can find libc++ living beside the installed compiler.
// This test makes sure our libTooling-based tools emulate this properly with
// fixed compilation database.
//
// RUN: rm -rf %t
// RUN: mkdir %t
//
// Install the mock libc++ (simulates the libc++ directory structure).
// RUN: cp -r %S/Inputs/mock-libcxx %t/
//
// RUN: cp $(which clang-check) %t/mock-libcxx/bin/
// RUN: cp "%s" "%t/test.cpp"
// RUN: %t/mock-libcxx/bin/clang-check -p "%t" "%t/test.cpp" -- -stdlib=libc++ -target x86_64-apple-darwin

#include <mock_vector>
vector v;

// Clang on MacOS can find libc++ living beside the installed compiler.
// This test makes sure our libTooling-based tools emulate this properly with
// fixed compilation database.
//
// RUN: rm -rf %t
// RUN: mkdir %t
//
// Install the mock libc++ (simulates the libc++ directory structure).
// RUN: cp -r %S/Inputs/mock-libcxx %t/
//
// RUN: cp $(which clang-check) %t/mock-libcxx/bin/
// RUN: cp "%s" "%t/test.cpp"
// RUN: %t/mock-libcxx/bin/clang-check -p "%t" "%t/test.cpp" -- -stdlib=libc++ -target x86_64-apple-darwin
// REQUIRES: system-darwin
#include <mock_vector>
vector v;

Add a REQUIRES: darwin line for a mac test.


#include "texture.hpp"

#include <string>

#include <SDL_image.h>

const std::string Texture::filename(const std::string &name)
{
  return "/textures/" + name;
}

Texture::Texture(const Adapter &adapter, const std::string &name)
{
  SDL_Surface *surface = IMG_Load(adapter.filename<Texture>(name).c_str());

  glGenTextures(1, &_id);
  glBindTexture(GL_TEXTURE_2D, _id);
  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
  glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, surface->w, surface->h, 0, GL_RGBA, GL_UNSIGNED_BYTE, surface->pixels);

  SDL_FreeSurface(surface);
}

void Texture::use() const
{
  glBindTexture(GL_TEXTURE_2D, _id);
}

#include "texture.hpp"

#include <string>

#define STB_IMAGE_IMPLEMENTATION
#define STBI_ASSERT(x)
#define STBI_ONLY_PNG
#include <stb_image.h>

const std::string Texture::filename(const std::string &name)
{
  return "/textures/" + name;
}

Texture::Texture(const Adapter &adapter, const std::string &name)
{
  GLsizei width, height, comp;
  GLvoid *data = stbi_load(adapter.filename<Texture>(name).c_str(), &width, &height, &comp, 0);

  glGenTextures(1, &_id);
  glBindTexture(GL_TEXTURE_2D, _id);
  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
  glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, data);

  stbi_image_free(data);
}

void Texture::use() const
{
  glBindTexture(GL_TEXTURE_2D, _id);
}

Use STB Image instead of SDL Image


#include "line.hpp"

// Include standard headers
#include <cmath>     // NAN, std::isnan, std::pow
#include <string>    // std::string
#include <vector>    // std::vector

namespace geometry
{
    // constructor.
    // can be used for creating n-dimensional lines.
    Line::Line(std::vector<float> point1, std::vector<float> point2)
    {
        if (point1 == point2)
        {
            this->is_valid = false; // two identical points do not define a line.
            this->general_form_coefficients.push_back(NAN);
            this->general_form_constant = NAN;
        }
        else
        {
            this->is_valid = true; // two distinct points define a line.
        }
    }

    // constructor.
    // can be used for creating n-dimensional lines.
    Line::Line(std::vector<float> general_form_coefficients, float general_form_constant)
    {
        this->general_form_coefficients = general_form_coefficients;
        this->general_form_constant = general_form_constant;
    }

    std::string Line::get_general_form_equation()
    {
        // TODO: implement this function!
        std::string line_equation;
        return line_equation;
    }
}

#include "line.hpp"

// Include standard headers
#include <cmath>     // NAN, std::isnan, std::pow
#include <string>    // std::string
#include <vector>    // std::vector

namespace geometry
{
    // constructor.
    // can be used for creating n-dimensional lines.
    Line::Line(std::vector<float> point1, std::vector<float> point2)
    {
        if (point1 == point2)
        {
            this->is_valid = false; // two identical points do not define a line.
            this->general_form_coefficients.push_back(NAN);
            this->general_form_constant = NAN;
        }
        else
        {
            this->is_valid = true; // two distinct points define a line.
            this->are_points_defined = true;
            this->point1 = point1;
            this->point2 = point2;
        }
    }

    // constructor.
    // can be used for creating n-dimensional lines.
    Line::Line(std::vector<float> general_form_coefficients, float general_form_constant)
    {
        this->general_form_coefficients = general_form_coefficients;
        this->general_form_constant = general_form_constant;
    }

    std::string Line::get_general_form_equation()
    {
        // TODO: implement this function!
        std::string line_equation;
        return line_equation;
    }
}

Define variables `are_points_defined`, `point1`, `point2`.


#include <MinConsole.hpp>
#include <Windows.h>

namespace MinConsole
{
void* GetOutputHandle()
{
	static void* Handle = nullptr;

	if( Handle == nullptr )
	{
		Handle = GetStdHandle(STD_OUTPUT_HANDLE);
	}

	return Handle;
}

void SetTextColor(Color NewColor)
{
	SetConsoleTextAttribute(
		GetOutputHandle(),
		static_cast<std::underlying_type_t<MinConsole::Color>>(NewColor)
	);
}

std::size_t GetWidth()
{
	CONSOLE_SCREEN_BUFFER_INFO ConsoleInfo;
	if( GetConsoleScreenBufferInfo(
		GetOutputHandle(),
		&ConsoleInfo) )
	{
		return static_cast<size_t>(ConsoleInfo.dwSize.X);
	}
	return 0;
}
}

#include <MinConsole.hpp>
#include <Windows.h>
#include <mutex>

namespace MinConsole
{
void* GetOutputHandle()
{
	static void* Handle = nullptr;
	std::once_flag HandleCached;
	std::call_once(HandleCached, [=]()
		{
			Handle = GetStdHandle(STD_OUTPUT_HANDLE);
		});
	return Handle;
}

void SetTextColor(Color NewColor)
{
	SetConsoleTextAttribute(
		GetOutputHandle(),
		static_cast<std::underlying_type_t<MinConsole::Color>>(NewColor)
	);
}

std::size_t GetWidth()
{
	CONSOLE_SCREEN_BUFFER_INFO ConsoleInfo;
	if( GetConsoleScreenBufferInfo(
		GetOutputHandle(),
		&ConsoleInfo) )
	{
		return static_cast<size_t>(ConsoleInfo.dwSize.X);
	}
	return 0;
}
}

Set StdHandle initialization with with call_once


// 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 "chrome/browser/sync/glue/chrome_report_unrecoverable_error.h"

#include "base/rand_util.h"
#include "build/build_config.h"

#if defined(OS_WIN)
#include <windows.h>
#endif

#include "chrome/common/chrome_constants.h"

namespace browser_sync {

static const double kErrorUploadRatio = 0.0;
void ChromeReportUnrecoverableError() {
  // TODO(lipalani): Add this for other platforms as well.
#if defined(OS_WIN)
  // We only want to upload |kErrorUploadRatio| ratio of errors.
  if (kErrorUploadRatio <= 0.0)
    return; // We are not allowed to upload errors.
  double random_number = base::RandDouble();
  if (random_number > kErrorUploadRatio)
    return;

  // Get the breakpad pointer from chrome.exe
  typedef void (__cdecl *DumpProcessFunction)();
  DumpProcessFunction DumpProcess = reinterpret_cast<DumpProcessFunction>(
      ::GetProcAddress(::GetModuleHandle(
                       chrome::kBrowserProcessExecutableName),
                       "DumpProcessWithoutCrash"));
  if (DumpProcess)
    DumpProcess();
#endif  // OS_WIN

}

}  // namespace browser_sync

// 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 "chrome/browser/sync/glue/chrome_report_unrecoverable_error.h"

#include "base/rand_util.h"
#include "build/build_config.h"

#if defined(OS_WIN)
#include <windows.h>
#endif

#include "chrome/common/chrome_constants.h"

namespace browser_sync {

static const double kErrorUploadRatio = 0.15;
void ChromeReportUnrecoverableError() {
  // TODO(lipalani): Add this for other platforms as well.
#if defined(OS_WIN)
  // We only want to upload |kErrorUploadRatio| ratio of errors.
  if (kErrorUploadRatio <= 0.0)
    return; // We are not allowed to upload errors.
  double random_number = base::RandDouble();
  if (random_number > kErrorUploadRatio)
    return;

  // Get the breakpad pointer from chrome.exe
  typedef void (__cdecl *DumpProcessFunction)();
  DumpProcessFunction DumpProcess = reinterpret_cast<DumpProcessFunction>(
      ::GetProcAddress(::GetModuleHandle(
                       chrome::kBrowserProcessExecutableName),
                       "DumpProcessWithoutCrash"));
  if (DumpProcess)
    DumpProcess();
#endif  // OS_WIN

}

}  // namespace browser_sync

Revert 191028 "[Sync] Disable unrecoverable error uploading."


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

#if defined(OS_CHROMEOS)
#include "base/basictypes.h"
#include "base/string_util.h"
#endif

namespace l10n_util {

// Return true blindly for now.
bool IsLocaleSupportedByOS(const std::string& locale) {
#if !defined(OS_CHROMEOS)
  return true;
#else
  // We don't have translations yet for am, fa and sw.
  // We don't have fonts for te and kn, yet.
  // TODO(jungshik): Once the above issues are resolved, change this back
  // to return true.
  static const char* kUnsupportedLocales[] = {"am", "fa", "kn", "sw", "te"};
  for (size_t i = 0; i < arraysize(kUnsupportedLocales); ++i) {
    if (LowerCaseEqualsASCII(locale, kUnsupportedLocales[i]))
      return false;
  }
  return true;
#endif
}

}  // namespace l10n_util

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

#if defined(OS_CHROMEOS)
#include "base/basictypes.h"
#include "base/string_util.h"
#endif

namespace l10n_util {

// Return true blindly for now.
bool IsLocaleSupportedByOS(const std::string& locale) {
#if !defined(OS_CHROMEOS)
  return true;
#else
  // We don't have translations yet for am, and sw.
  // TODO(jungshik): Once the above issues are resolved, change this back
  // to return true.
  static const char* kUnsupportedLocales[] = {"am", "sw"};
  for (size_t i = 0; i < arraysize(kUnsupportedLocales); ++i) {
    if (LowerCaseEqualsASCII(locale, kUnsupportedLocales[i]))
      return false;
  }
  return true;
#endif
}

}  // namespace l10n_util

Enable Kannada, Farsi and Telugu on CrOS


#include "OptionsManager.h"

#include <fstream>

#include <boost/filesystem.hpp>

#include <spotify/json.hpp>

#include "codecs/OptionsCodec.h"

OptionsManager::OptionsManager(std::string optionsFilename)
{
    loadOptions(optionsFilename);
}

void OptionsManager::loadOptions(std::string optionsFilename)
{
    std::ifstream ifs(optionsFilename);
    if (!ifs.good())
    {
        throw std::runtime_error("Could not open options file");
    }

    std::string str{std::istreambuf_iterator<char>(ifs),
                    std::istreambuf_iterator<char>()};

    mOptions = spotify::json::decode<Options>(str.c_str());
    mOptions.filename = optionsFilename;

    createOutputDirectory(optionsFilename);
}

void OptionsManager::createOutputDirectory(std::string optionsFilename)
{
    // TODO(hryniuk): move it elsewhere
    auto outputDirectory = mOptions.outputDirectory;
    boost::filesystem::path p(optionsFilename);
    p.remove_filename();
    p.append(outputDirectory);
    boost::filesystem::create_directories(p);
    auto relativeOutputDirectory = p.string();
    mOptions.relativeOutputDirectory = relativeOutputDirectory;
}

const Options& OptionsManager::getOptions() const
{
    return mOptions;
}

#include "OptionsManager.h"

#include <fstream>
#include <iostream>

#include <boost/filesystem.hpp>

#include <spotify/json.hpp>

#include "codecs/OptionsCodec.h"

OptionsManager::OptionsManager(std::string optionsFilename)
{
    loadOptions(optionsFilename);
}

void OptionsManager::loadOptions(std::string optionsFilename)
{
    std::ifstream ifs(optionsFilename);
    if (!ifs.good())
    {
        throw std::runtime_error("Could not open options file");
    }

    std::string str{std::istreambuf_iterator<char>(ifs),
                    std::istreambuf_iterator<char>()};
    try
    {
        mOptions = spotify::json::decode<Options>(str.c_str());
    }
    catch (spotify::json::decode_exception e)
    {
        std::cout << "spotify::json::decode_exception encountered at "
            << e.offset()
            << ": "
            << e.what();
        throw;
    }
    mOptions.filename = optionsFilename;

    createOutputDirectory(optionsFilename);
}

void OptionsManager::createOutputDirectory(std::string optionsFilename)
{
    // TODO(hryniuk): move it elsewhere
    auto outputDirectory = mOptions.outputDirectory;
    boost::filesystem::path p(optionsFilename);
    p.remove_filename();
    p.append(outputDirectory);
    boost::filesystem::create_directories(p);
    auto relativeOutputDirectory = p.string();
    mOptions.relativeOutputDirectory = relativeOutputDirectory;
}

const Options& OptionsManager::getOptions() const
{
    return mOptions;
}

Print exception details on decode failure


#include "SkinManager.h"

#include "Skin.h"

SkinManager *SkinManager::instance;

SkinManager *SkinManager::Instance() {
    if (instance == NULL) {
        instance = new SkinManager();
    }
    return instance;
}

SkinManager::~SkinManager() {
    delete _skin;
}

void SkinManager::LoadSkin(std::wstring skinXML) {
    delete _skin;
    _skin = new Skin(skinXML);
}

Skin *SkinManager::CurrentSkin() {
    return _skin;
}

#include "SkinManager.h"

#include "Skin.h"
#include "SkinV3.h"

SkinManager *SkinManager::instance;

SkinManager *SkinManager::Instance() {
    if (instance == NULL) {
        instance = new SkinManager();
    }
    return instance;
}

SkinManager::~SkinManager() {
    delete _skin;
}

void SkinManager::LoadSkin(std::wstring skinXML) {
    delete _skin;
    _skin = new SkinV3(skinXML);
}

Skin *SkinManager::CurrentSkin() {
    return _skin;
}

Load a v3 skin for now


// Test that verifies TSan runtime doesn't contain compiler-emitted
// memcpy/memmove calls. It builds the binary with TSan and passes it to
// check_memcpy.sh script.

// RUN: %clangxx_tsan -O1 %s -o %t
// RUN: llvm-objdump -d %t | FileCheck %s

int main() {
  return 0;
}

// CHECK-NOT: callq {{.*<(__interceptor_)?mem(cpy|set)>}}
// tail calls:
// CHECK-NOT: jmpq {{.*<(__interceptor_)?mem(cpy|set)>}}

// Test that verifies TSan runtime doesn't contain compiler-emitted
// memcpy/memmove calls. It builds the binary with TSan and passes it to
// check_memcpy.sh script.

// RUN: %clangxx_tsan -O1 %s -o %t
// RUN: llvm-objdump -d %t | FileCheck %s

// REQUIRES: compiler-rt-optimized

int main() {
  return 0;
}

// CHECK-NOT: callq {{.*<(__interceptor_)?mem(cpy|set)>}}
// tail calls:
// CHECK-NOT: jmpq {{.*<(__interceptor_)?mem(cpy|set)>}}

Disable test with debug runtime


#include "JSON.h"
#include <string>

namespace ouroboros
{
	JSON::JSON()
	:mpArr(nullptr)
	{}

	JSON::JSON(const std::string& aJSON)
	:mpArr(parse_json2(aJSON.c_str(), aJSON.length()))
	{}

	JSON::~JSON()
	{
		free(mpArr);
	}

	bool JSON::exists(const std::string& aPath) const
	{
		if (mpArr)
		{
			const json_token * ptr = find_json_token(mpArr, aPath.c_str());
			if (ptr)
			{
				return true;
			}
		}
		return false;
	}

	std::string JSON::get(const std::string& aPath) const
	{
		if (mpArr)
		{
			const json_token * ptr = find_json_token(mpArr, aPath.c_str());
			if (ptr)
			{
				return std::string(ptr->ptr, ptr->len);
			}
		}
		return std::string();
	}

	bool JSON::empty() const
	{
		return (!mpArr);
	}

}

#include "JSON.h"
#include <string>
#include <cstdlib>

namespace ouroboros
{
	JSON::JSON()
	:mpArr(nullptr)
	{}

	JSON::JSON(const std::string& aJSON)
	:mpArr(parse_json2(aJSON.c_str(), aJSON.length()))
	{}

	JSON::~JSON()
	{
		free(mpArr);
	}

	bool JSON::exists(const std::string& aPath) const
	{
		if (mpArr)
		{
			const json_token * ptr = find_json_token(mpArr, aPath.c_str());
			if (ptr)
			{
				return true;
			}
		}
		return false;
	}

	std::string JSON::get(const std::string& aPath) const
	{
		if (mpArr)
		{
			const json_token * ptr = find_json_token(mpArr, aPath.c_str());
			if (ptr)
			{
				return std::string(ptr->ptr, ptr->len);
			}
		}
		return std::string();
	}

	bool JSON::empty() const
	{
		return (!mpArr);
	}

}

Add cstdlib so that the code compiles on OSX


#include <string>
#include <ccspec/core/hooks.h>
#include <ccspec/core/example_group.h>

namespace ccspec {
namespace core {

void before(std::string entity, Hook hook) {
    ExampleGroup* parent_group = groups_being_defined.top();
    if (entity == "each")
        parent_group->addBeforeEachHook(hook);
    else
        throw "no such before hook type";
}

} // namespace core
} // namespace ccspec

#include <string>
#include <ccspec/core/hooks.h>
#include <ccspec/core/example_group.h>

namespace ccspec {
namespace core {

void before(std::string entity, Hook hook) {
    ExampleGroup* parent_group = groups_being_defined.top();
    if (entity == "each" || entity == "example")
        parent_group->addBeforeEachHook(hook);
    else
        throw "no such before hook type";
}

} // namespace core
} // namespace ccspec

Add "each" alias that's new in RSpec 3


#include <client/client.h>
#include <server/server.h>

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

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

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

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

  /* Start the server and send the compile command. */
  if (!clc::server::is_running())
    clc::server::start();

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

#include <client/client.h>
#include <server/server.h>

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

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

  separator = 0;
  for (int i = 1; i < argc; ++i) {
    if (strcmp(argv[i], "--") == 0) {
      separator = i;
      break;
    } else if (strcmp(argv[i], "--start") == 0) {
      clc::server::start();
      return EXIT_SUCCESS;
    } else if (strcmp(argv[i], "--stop") == 0) {
      clc::server::stop();
      return EXIT_SUCCESS;
    }
  }

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

  /* Start the server and send the compile command. */
  if (!clc::server::is_running())
    clc::server::start();

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

Add --start and --stop commands to manage the server.


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

// UNSUPPORTED: c++98, c++03

// <utility>

// template <class T1, class T2> struct pair

// constexpr pair();

#include <utility>
#include <type_traits>

#include "archetypes.hpp"

int main() {
    using NonThrowingDefault = NonThrowingTypes::DefaultOnly;
    using ThrowingDefault = NonTrivialTypes::DefaultOnly;
    static_assert(!std::is_nothrow_default_constructible<std::pair<ThrowingDefault, ThrowingDefault>>::value, "");
    static_assert(!std::is_nothrow_default_constructible<std::pair<NonThrowingDefault, ThrowingDefault>>::value, "");
    static_assert(!std::is_nothrow_default_constructible<std::pair<ThrowingDefault, NonThrowingDefault>>::value, "");
    static_assert( std::is_nothrow_default_constructible<std::pair<NonThrowingDefault, NonThrowingDefault>>::value, "");
}

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

// UNSUPPORTED: c++98, c++03

// <utility>

// template <class T1, class T2> struct pair

// constexpr pair();

#include <utility>
#include <type_traits>

struct ThrowingDefault {
  ThrowingDefault() { }
};

struct NonThrowingDefault {
  NonThrowingDefault() noexcept { }
};

int main() {

    static_assert(!std::is_nothrow_default_constructible<std::pair<ThrowingDefault, ThrowingDefault>>::value, "");
    static_assert(!std::is_nothrow_default_constructible<std::pair<NonThrowingDefault, ThrowingDefault>>::value, "");
    static_assert(!std::is_nothrow_default_constructible<std::pair<ThrowingDefault, NonThrowingDefault>>::value, "");
    static_assert( std::is_nothrow_default_constructible<std::pair<NonThrowingDefault, NonThrowingDefault>>::value, "");
}

Fix test failure on GCC 4.9


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

template<typename T>
struct X1 {
  friend void f6(int) { } // expected-error{{redefinition of}} \
                          // expected-note{{previous definition}}
};

X1<int> x1a;
X1<float> x1b; // expected-note {{in instantiation of}}

template<typename T>
struct X2 {
  operator int();

  friend void f(int x) { } // expected-error{{redefinition}} \
                           // expected-note{{previous definition}}
};

int array0[sizeof(X2<int>)];
int array1[sizeof(X2<float>)]; // expected-note{{instantiation of}}

void g() {
  X2<int> xi;
  f(xi);
  X2<float> xf;
  f(xf);
}

Add test case from PR6952, which now works (thanks to Gabor).


#include <iostream>

using namespace std;

class Greeting {
    protected:
        string s;
    public:
        Greeting(){
            s = "Hello, ";
        }
        virtual ~Greeting() { }
        virtual void printGreeting() = 0;
};

class GitHubGreeting : public Greeting {
    public:
        GitHubGreeting() {
            s += "GitHub!";
            printGreeting();
        }
        GitHubGreeting(GitHubGreeting & h) { }
        GitHubGreeting(GitHubGreeting * h) { }
        virtual ~GitHubGreeting() { }
        void operator=(GitHubGreeting & h) { }
        void printGreeting() {
            cout << s << endl;
        }
};

int main() {
    GitHubGreeting h;
    return 0;
}

#include <iostream>

using namespace std;

class Greeting {
    protected:
        string s;
    public:
        Greeting(){
            s = "Hello, ";
        }
        virtual ~Greeting() { }
        virtual void printGreeting() = 0;
};

class GitHubGreeting : public Greeting {
    public:
        GitHubGreeting() {
            s += "GitHub!";
            printGreeting();
        }
        GitHubGreeting(GitHubGreeting & h) { GitHubGreeting(); }
        GitHubGreeting(GitHubGreeting * h) { GitHubGreeting(); }
        virtual ~GitHubGreeting() { }
        void operator=(GitHubGreeting & h) { }
        void printGreeting() {
            cout << s << endl;
        }
};

int main() {
    GitHubGreeting h;
    return 0;
}

Fix the copy constructors to call the base constructor


// 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 "chrome/browser/chromeos/legacy_window_manager/initial_browser_window_observer.h"

#include "base/file_path.h"
#include "base/file_util.h"
#include "base/logging.h"
#include "chrome/common/chrome_notification_types.h"
#include "content/public/browser/notification_service.h"

namespace {

// Taken from the --initial_chrome_window_mapped_file flag in the chromeos-wm
// command line: http://goo.gl/uLwIL
const char kInitialWindowFile[] =
    "/var/run/state/windowmanager/initial-chrome-window-mapped";

}  // namespace

namespace chromeos {

InitialBrowserWindowObserver::InitialBrowserWindowObserver() {
  registrar_.Add(this,
                 chrome::NOTIFICATION_BROWSER_WINDOW_READY,
                 content::NotificationService::AllSources());
}

void InitialBrowserWindowObserver::Observe(
    int type,
    const content::NotificationSource& source,
    const content::NotificationDetails& details) {
  registrar_.RemoveAll();
  file_util::WriteFile(FilePath(kInitialWindowFile), "", 0);
}

}  // namespace chromeos

// 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 "chrome/browser/chromeos/legacy_window_manager/initial_browser_window_observer.h"

#include "base/bind.h"
#include "base/file_path.h"
#include "base/file_util.h"
#include "base/logging.h"
#include "chrome/common/chrome_notification_types.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/notification_service.h"

namespace {

// Taken from the --initial_chrome_window_mapped_file flag in the chromeos-wm
// command line: http://goo.gl/uLwIL
const char kInitialWindowFile[] =
    "/var/run/state/windowmanager/initial-chrome-window-mapped";

void WriteInitialWindowFile() {
  if (file_util::WriteFile(FilePath(kInitialWindowFile), "", 0) == -1)
    LOG(ERROR) << "Failed to touch " << kInitialWindowFile;
}

}  // namespace

namespace chromeos {

InitialBrowserWindowObserver::InitialBrowserWindowObserver() {
  registrar_.Add(this,
                 chrome::NOTIFICATION_BROWSER_WINDOW_READY,
                 content::NotificationService::AllSources());
}

void InitialBrowserWindowObserver::Observe(
    int type,
    const content::NotificationSource& source,
    const content::NotificationDetails& details) {
  registrar_.RemoveAll();
  content::BrowserThread::PostTask(
      content::BrowserThread::IO, FROM_HERE,
      base::Bind(&WriteInitialWindowFile));
}

}  // namespace chromeos

Write initial browser window file from IO thread.


#include "gtest/gtest.h"
#include "Models/GaussianModel.hpp"

#include "test_utils/test_utils.hpp"
#include <fstream>

namespace {
  using namespace BOOM;
  using std::endl;
  using std::cout;

  class ParamPolicy2Test : public ::testing::Test {
   protected:
    ParamPolicy2Test() {
      GlobalRng::rng.seed(8675309);
    }
  };

  TEST_F(ParamPolicy2Test, ParamVectorTest) {
    GaussianModel model1(1.2, 3.7);
    EXPECT_EQ(2, model1.parameter_vector().size());
    model1.disable_parameter_1();

    model1.set_mu(0.1);
    EXPECT_DOUBLE_EQ(0.1, model1.mu());
    EXPECT_DOUBLE_EQ(2.7, model1.sigma());

    EXPECT_EQ(1, model1.parameter_vector().size());

  }

}  // namespace

#include "gtest/gtest.h"
#include "Models/GaussianModel.hpp"

#include "test_utils/test_utils.hpp"
#include <fstream>

namespace {
  using namespace BOOM;
  using std::endl;
  using std::cout;

  class ParamPolicy2Test : public ::testing::Test {
   protected:
    ParamPolicy2Test() {
      GlobalRng::rng.seed(8675309);
    }
  };

  TEST_F(ParamPolicy2Test, ParamVectorTest) {
    GaussianModel model1(1.2, 3.7);
    EXPECT_EQ(2, model1.parameter_vector().size());

    // Fix the mean at its current value.
    model1.disable_parameter_1();

    model1.set_mu(0.1);
    EXPECT_DOUBLE_EQ(0.1, model1.mu());
    EXPECT_DOUBLE_EQ(3.7, model1.sigma());

    EXPECT_EQ(1, model1.parameter_vector().size());
    Vector params = model1.vectorize_params();
    EXPECT_EQ(1, params.size());
    EXPECT_DOUBLE_EQ(square(3.7), params[0]);
  }

}  // namespace

Fix a typo in a test case for ParamPolicy2.


#pragma once

#include <glkernel/Kernel.h>

#include <glm/vec2.hpp>

#include <glkernel/Kernel.h>

#include <glkernel/uniform_noise.h>
#include <glkernel/normal_noise.h>
#include <glkernel/square_points.hpp>

namespace glkernel
{

void test()
{
    { auto noise = glkernel::Kernel<float>();      }
    { auto noise = glkernel::Kernel<double>();     }

    { auto noise = glkernel::Kernel<glm::vec2>();  }
    { auto noise = glkernel::Kernel<glm::dvec2>(); }

    { auto noise = glkernel::Kernel<glm::vec3>();  }
    { auto noise = glkernel::Kernel<glm::dvec3>(); }

    { auto noise = glkernel::Kernel<glm::vec4>();  }
    { auto noise = glkernel::Kernel<glm::dvec4>(); }
}

} // namespace glkernel

Remove pragma once from cpp file


#include "ros/ros.h"
#include "sensor_msgs/LaserScan.h"
#include "OpenniLaserScanner.h"

class MyMwListener : public OpenniLaser::OpenniLaserScanner::Listener
{
public:
	sensor_msgs::LaserScan scan;
	void readyForNextData(OpenniLaser::OpenniLaserScanner* scanner)
	{
		openni::VideoFrameRef frame;
		scan = scanner->getNextData(frame);
	}
};

int main(int argc, char **argv)
{
	 ros::init(argc, argv, "openni2_laserscan");

	  ros::NodeHandle n;
	  ros::Publisher scan_pub = n.advertise<sensor_msgs::LaserScan>("openni2_laserscan", 50);

	  int count = 0;
	  ros::Rate r(1.0);

		OpenniLaser::OpenniLaserScanner laserScanner;

		if (!laserScanner.isValid())
		{
			printf("openni_laserscan: error in initialization\n");
			return 1;
		}
		printf("openni_laserscan: running\n");

		MyMwListener myListener;

		laserScanner.setListener(myListener);

	  while(n.ok()){
	    scan_pub.publish(myListener.scan);
	    ++count;
	    r.sleep();
	  }

	  laserScanner.resetListener();
	  printf("openni_laserscan: stopped\n");
	  return 0;
}

#include "ros/ros.h"
#include "sensor_msgs/LaserScan.h"
#include "OpenniLaserScanner.h"

class MyMwListener : public OpenniLaser::OpenniLaserScanner::Listener
{
public:
	sensor_msgs::LaserScan scan;
	void readyForNextData(OpenniLaser::OpenniLaserScanner* scanner)
	{
		openni::VideoFrameRef frame;
		scan = scanner->getNextData(frame);
	}
};

int main(int argc, char **argv)
{
	 ros::init(argc, argv, "openni2_laserscan");

	  ros::NodeHandle n;
	  ros::Publisher scan_pub = n.advertise<sensor_msgs::LaserScan>("openni2_laserscan", 50);

	  int count = 0;
	  ros::Rate r(30.0);

		OpenniLaser::OpenniLaserScanner laserScanner;

		if (!laserScanner.isValid())
		{
			printf("openni_laserscan: error in initialization\n");
			return 1;
		}
		printf("openni_laserscan: running\n");

		MyMwListener myListener;

		laserScanner.setListener(myListener);

	  while(n.ok()){
	    scan_pub.publish(myListener.scan);
	    ++count;
	    r.sleep();
	  }

	  laserScanner.resetListener();
	  printf("openni_laserscan: stopped\n");
	  return 0;
}

Set publishing fequenzy from 1 to 30 hz


#include "stdafx.h"
#include "AutowiringTest.h"
#include "Autowired.h"
#include "TestFixtures/SimpleObject.h"
#include "TestFixtures/SimpleReceiver.h"

TEST_F(AutowiringTest, VerifyAutowiredFast) {
  // Add an object:
  m_create->Inject<SimpleObject>();

  // Verify that AutowiredFast can find this object
  AutowiredFast<SimpleObject> sobj;
  ASSERT_TRUE(sobj.IsAutowired()) << "Failed to autowire an object which was just injected into a context";
}

TEST_F(AutowiringTest, VerifyAutowiredFastNontrivial) {
  // This will cause a cache entry to be inserted into the CoreContext's memoization system.
  // If there is any improper or incorrect invalidation in that system, then the null entry
  // will create problems when we attempt to perform an AutowiredFast later on.
  AutowiredFast<CallableInterface>();

  // Now we add the object
  AutoRequired<SimpleReceiver>();

  // Verify that AutowiredFast can find this object from its interface
  Autowired<CallableInterface> ci;
  ASSERT_TRUE(ci.IsAutowired()) << "Failed to autowire an interface advertised by a newly-inserted object";
}

#include "stdafx.h"
#include "AutowiringTest.h"
#include "Autowired.h"
#include "TestFixtures/SimpleObject.h"
#include "TestFixtures/SimpleReceiver.h"

TEST_F(AutowiringTest, VerifyAutowiredFast) {
  // Add an object:
  m_create->Inject<SimpleObject>();

  // Verify that AutowiredFast can find this object
  AutowiredFast<SimpleObject> sobj;
  ASSERT_TRUE(sobj.IsAutowired()) << "Failed to autowire an object which was just injected into a context";
}

TEST_F(AutowiringTest, VerifyAutowiredFastNontrivial) {
  // This will cause a cache entry to be inserted into the CoreContext's memoization system.
  // If there is any improper or incorrect invalidation in that system, then the null entry
  // will create problems when we attempt to perform an AutowiredFast later on.
  AutowiredFast<CallableInterface>();

  // Now we add the object
  AutoRequired<SimpleReceiver>();

  // Verify that AutowiredFast can find this object from its interface
  AutowiredFast<CallableInterface> ci;
  ASSERT_TRUE(ci.IsAutowired()) << "Failed to autowire an interface advertised by a newly-inserted object";
}

Revert "Fixed incorrect autowiring test."


// 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 "net/base/network_change_notifier_helper.h"
#include <algorithm>
#include "base/logging.h"

namespace net {

namespace internal {

NetworkChangeNotifierHelper::NetworkChangeNotifierHelper()
    : is_notifying_observers_(false) {}

NetworkChangeNotifierHelper::~NetworkChangeNotifierHelper() {
  DCHECK(observers_.empty());
}

void NetworkChangeNotifierHelper::AddObserver(Observer* observer) {
  DCHECK(!is_notifying_observers_);
  observers_.push_back(observer);
}

void NetworkChangeNotifierHelper::RemoveObserver(Observer* observer) {
  DCHECK(!is_notifying_observers_);
  observers_.erase(std::remove(observers_.begin(), observers_.end(), observer));
}

void NetworkChangeNotifierHelper::OnIPAddressChanged() {
  DCHECK(!is_notifying_observers_);
  is_notifying_observers_ = true;
  for (std::vector<Observer*>::iterator it = observers_.begin();
       it != observers_.end(); ++it) {
    (*it)->OnIPAddressChanged();
  }
  is_notifying_observers_ = false;
}

}  // namespace internal

}  // namespace net

// 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 "net/base/network_change_notifier_helper.h"
#include <algorithm>
#include "base/logging.h"

namespace net {

namespace internal {

NetworkChangeNotifierHelper::NetworkChangeNotifierHelper()
    : is_notifying_observers_(false) {}

NetworkChangeNotifierHelper::~NetworkChangeNotifierHelper() {
  // TODO(willchan): Re-enable this DCHECK after fixing http://crbug.com/34391
  // since we're leaking URLRequestContextGetters that cause this DCHECK to
  // fire.
  // DCHECK(observers_.empty());
}

void NetworkChangeNotifierHelper::AddObserver(Observer* observer) {
  DCHECK(!is_notifying_observers_);
  observers_.push_back(observer);
}

void NetworkChangeNotifierHelper::RemoveObserver(Observer* observer) {
  DCHECK(!is_notifying_observers_);
  observers_.erase(std::remove(observers_.begin(), observers_.end(), observer));
}

void NetworkChangeNotifierHelper::OnIPAddressChanged() {
  DCHECK(!is_notifying_observers_);
  is_notifying_observers_ = true;
  for (std::vector<Observer*>::iterator it = observers_.begin();
       it != observers_.end(); ++it) {
    (*it)->OnIPAddressChanged();
  }
  is_notifying_observers_ = false;
}

}  // namespace internal

}  // namespace net

Disable DCHECK'ing that all NetworkChangeNotifiers are removed. BUG=34391


/*
 * Rectangular Window Function Unit for Jamoma DSP
 * Copyright © 2009 by Trond Lossius
 *
 * License: This code is licensed under the terms of the "New BSD License"
 * http://creativecommons.org/licenses/BSD/
 */

#include "TTRectangularWindow.h"

#define thisTTClass RectangularWindow
#define thisTTClassName		"rectangular"
#define thisTTClassTags		"audio, processor, function, window"

TT_AUDIO_CONSTRUCTOR
{
	setProcessMethod(processAudio);
	setCalculateMethod(calculateValue);
}

RectangularWindow::~RectangularWindow()
{
	;
}

TTErr RectangularWindow::calculateValue(const TTFloat64& x, TTFloat64& y, TTPtrSizedInt data)
{
	if ((x>0) && (x<1.0))
		y = 1.0;
	else
		y = 0.0;

	return kTTErrNone;
}

TTErr RectangularWindow::processAudio(TTAudioSignalArrayPtr inputs, TTAudioSignalArrayPtr outputs)
{
	TT_WRAP_CALCULATE_METHOD(calculateValue);
}

/*
 * Rectangular Window Function Unit for Jamoma DSP
 * Copyright © 2009 by Trond Lossius
 *
 * License: This code is licensed under the terms of the "New BSD License"
 * http://creativecommons.org/licenses/BSD/
 */

#include "TTRectangularWindow.h"

#define thisTTClass RectangularWindow
#define thisTTClassName		"rectangular"
#define thisTTClassTags		"audio, processor, function, window"

TT_AUDIO_CONSTRUCTOR
{
	setProcessMethod(processAudio);
	setCalculateMethod(calculateValue);
}

RectangularWindow::~RectangularWindow()
{
	;
}

TTErr RectangularWindow::calculateValue(const TTFloat64& x, TTFloat64& y, TTPtrSizedInt data)
{
	y = 1.0;
	return kTTErrNone;
}

TTErr RectangularWindow::processAudio(TTAudioSignalArrayPtr inputs, TTAudioSignalArrayPtr outputs)
{
	TT_WRAP_CALCULATE_METHOD(calculateValue);
}

Revert "Fixing a bug with rectangular window that would prevent it from being 0 at the end points"


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

#include <bcm_host.h>
#include "WindowResourceRasp.hpp"
#include "utils/Log.hpp"

namespace ouzel
{
    WindowResourceRasp::WindowResourceRasp()
    {
        bcm_host_init();
    }

    WindowResourceRasp::~WindowResourceRasp()
    {
        bcm_host_deinit();
    }

    bool WindowResourceRasp::init(const Size2& newSize,
                                  bool newResizable,
                                  bool newFullscreen,
                                  bool newExclusiveFullscreen,
                                  const std::string& newTitle,
                                  bool newHighDpi,
                                  bool depth)
    {
        if (!WindowResource::init(newSize,
                                  newResizable,
                                  newFullscreen,
                                  newExclusiveFullscreen,
                                  newTitle,
                                  newHighDpi,
                                  depth))
        {
            return false;
        }

        uint32_t screenWidth;
        uint32_t screenHeight;
        int32_t success = graphics_get_display_size(0, &screenWidth, &screenHeight);

        if (success < 0)
        {
            Log(Log::Level::ERR) << "Failed to get display size";
            return false;
        }

        size.width = static_cast<float>(screenWidth);
        size.height = static_cast<float>(screenHeight);
        resolution = size;

        return true;
    }
}

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

#include <bcm_host.h>
#include "WindowResourceRasp.hpp"
#include "utils/Log.hpp"

namespace ouzel
{
    WindowResourceRasp::WindowResourceRasp()
    {
        bcm_host_init();
    }

    WindowResourceRasp::~WindowResourceRasp()
    {
        bcm_host_deinit();
    }

    bool WindowResourceRasp::init(const Size2& newSize,
                                  bool newResizable,
                                  bool newFullscreen,
                                  bool newExclusiveFullscreen,
                                  const std::string& newTitle,
                                  bool newHighDpi,
                                  bool depth)
    {
        if (!WindowResource::init(newSize,
                                  newResizable,
                                  newFullscreen,
                                  newExclusiveFullscreen,
                                  newTitle,
                                  newHighDpi,
                                  depth))
        {
            return false;
        }

        DISPMANX_DISPLAY_HANDLE_T display = vc_dispmanx_display_open(0);
        if (!display)
        {
            Log(Log::Level::ERR) << "Failed to open display";
            return false;
        }

        DISPMANX_MODEINFO_T modeInfo;
        int32_t success = vc_dispmanx_display_get_info(display, &modeInfo);

        if (success < 0)
        {
            Log(Log::Level::ERR) << "Failed to get display size";
            vc_dispmanx_display_close(display);
            return false;
        }

        size.width = static_cast<float>(modeInfo.width);
        size.height = static_cast<float>(modeInfo.height);
        resolution = size;

        vc_dispmanx_display_close(display);

        return true;
    }
}

Use vc_ functions to get display size


#include<ros/ros.h>
#include<servo_msgs/IdBased.h>
#include<ics3/ics>

ics::ICS3* driver {nullptr};
ros::Publisher pub;

void move(const servo_msgs::IdBased::ConstPtr& msg) {
  servo_msgs::IdBased result;
  try {
    result.angle = driver->move(msg->id, ics::Angle::newDegree(msg->angle));
    result.id = msg->id;
    pub.publish(result);
  } catch (std::runtime_error e) {
    ROS_INFO("Communicate error: %s", e.what());
  }
}

int main(int argc, char** argv) {
  ros::init(argc, argv, "servo_krs_node");
  ros::NodeHandle pn {"~"};
  std::string path {"/dev/ttyUSB0"};
  pn.param<std::string>("path", path, path);
  ROS_INFO("Open servo motor path: %s", path.c_str());
  ics::ICS3 ics {std::move(path)};
  driver = &ics;
  ros::NodeHandle n {};
  ros::Subscriber sub {n.subscribe("cmd_krs", 100, move)};
  pub = n.advertise<servo_msgs::IdBased>("pose_krs", 10);
  ros::spin();
  return 0;
}

#include<ros/ros.h>
#include<servo_msgs/IdBased.h>
#include<ics3/ics>

ics::ICS3* driver {nullptr};
ros::Publisher pub;

void move(const servo_msgs::IdBased::ConstPtr& msg) {
  servo_msgs::IdBased result;
  try {
    const auto& now_pos = driver->move(msg->id, ics::Angle::newDegree(msg->angle));
    result.angle = std::move(now_pos);
    result.id = msg->id;
    pub.publish(std::move(result));
  } catch (std::runtime_error e) {
    ROS_INFO("Communicate error: %s", e.what());
  }
}

int main(int argc, char** argv) {
  ros::init(argc, argv, "servo_krs_node");
  ros::NodeHandle pn {"~"};
  std::string path {"/dev/ttyUSB0"};
  pn.param<std::string>("path", path, path);
  ROS_INFO("Open servo motor path: %s", path.c_str());
  ics::ICS3 ics {std::move(path)};
  driver = &ics;
  ros::NodeHandle n {};
  ros::Subscriber sub {n.subscribe("cmd_krs", 100, move)};
  pub = n.advertise<servo_msgs::IdBased>("pose_krs", 10);
  ros::spin();
  return 0;
}

Add std::move to all local value


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

#include <memory>
#include <gflags/gflags.h>

#include <thrift/lib/cpp2/server/ThriftServer.h>

#include "treadmill/services/sleep/sleepserver/SleepHandler.h"

using namespace apache::thrift;
using namespace apache::thrift::async;

using namespace facebook::windtunnel::treadmill::services::sleep;

DEFINE_int32(port,
             12345,
             "Port for sleep service (default: 12345).");

DEFINE_int32(num_workers,
             4,
             "Number of workers (default: 4).");

int main(int argc, char* argv[]) {
  google::InitGoogleLogging(argv[0]);
  google::ParseCommandLineFlags(&argc, &argv, true);

  auto handler = std::make_shared<SleepHandler>();
  auto server = folly::make_unique<ThriftServer>();
  server->setPort(FLAGS_port);
  server->setNWorkerThreads(FLAGS_num_workers);
  server->setInterface(std::move(handler));

  server->serve();

  return 0;
}

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

#include <memory>
#include <gflags/gflags.h>

#include <thrift/lib/cpp2/server/ThriftServer.h>

#include "treadmill/services/sleep/sleepserver/SleepHandler.h"

using namespace apache::thrift;
using namespace apache::thrift::async;

using namespace facebook::windtunnel::treadmill::services::sleep;

DEFINE_int32(port,
             12345,
             "Port for sleep service (default: 12345).");

DEFINE_int32(num_workers,
             4,
             "Number of workers (default: 4).");

int main(int argc, char* argv[]) {
  google::InitGoogleLogging(argv[0]);
  google::ParseCommandLineFlags(&argc, &argv, true);

  auto handler = std::make_shared<SleepHandler>();
  auto server = folly::make_unique<ThriftServer>();
  server->setPort(FLAGS_port);
  server->setNumIOWorkerThreads(FLAGS_num_workers);
  server->setInterface(std::move(handler));

  server->serve();

  return 0;
}

Rename thrift methods from NWorker/NPoolThreads to NumIOWorker/NumCPUWorkerThreads for all remaining directories


#include "square.h"
#include <gtest/gtest.h>

TEST(TestSuite, squareTwo)
{
  const double ret = square(2);
  ASSERT_EQ(5, ret);
}

TEST(TestSuite, squareFour)
{
  const double ret = square(4.1);
  ASSERT_EQ(16.81, ret);
}

// Run all the tests that were declared with TEST()
int main(int argc, char **argv){
  testing::InitGoogleTest(&argc, argv);
  return RUN_ALL_TESTS();
}

#include "square.h"
#include <gtest/gtest.h>

TEST(TestSuite, squareTwo)
{
  const double ret = square(2);
  ASSERT_EQ(4, ret);
}

TEST(TestSuite, squareFour)
{
  const double ret = square(4.1);
  ASSERT_EQ(16.81, ret);
}

// Run all the tests that were declared with TEST()
int main(int argc, char **argv){
  testing::InitGoogleTest(&argc, argv);
  return RUN_ALL_TESTS();
}

Revert "Make sure failed tests actually fail."


#include "../test.h"
#include <QUrl>
#include "../../src/input/scxml_importer.h"

TEST(Test_ScxmlImporter, foo)
{
  ScxmlImporter importer(QUrl::fromLocalFile("../config/simple_state.xml"));
}

#include "../test.h"
#include <QUrl>
#include <QStateMachine>
#include <QGuiApplication>
#include <QWindow>
#include <QKeyEvent>
#include <thread>
#include <chrono>
#include "../../src/input/scxml_importer.h"

TEST(Test_ScxmlImporter, foo)
{
  int zero = 0;
  QGuiApplication application(zero, static_cast<char **>(nullptr));
  QWindow window;

  ScxmlImporter importer(QUrl::fromLocalFile("../config/simple_state.xml"),
                         &window);
  auto stateMachine = importer.getStateMachine();
  std::cout << "running:" << stateMachine->isRunning() << std::endl;

  stateMachine->start();

  window.show();

  std::cout << "running:" << stateMachine->isRunning() << std::endl;
  std::this_thread::sleep_for(std::chrono::milliseconds(500));

  std::cout << "error:" << stateMachine->errorString().toStdString() << std::endl;
  std::cout << "running:" << stateMachine->isRunning() << std::endl;

  stateMachine->postEvent(
      new QKeyEvent(QEvent::KeyPress, Qt::Key_A, Qt::NoModifier));

  application.exec();
}

Test for now starts an application.


/**
 * Copyright (c) 2016-present, Facebook, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include "aten_op.h"

namespace caffe2 {

REGISTER_CPU_OPERATOR(ATen, ATenOp<CPUContext>);
template<>
at::Backend ATenOp<CPUContext>::backend() const {
  return at::kCPU;
}

OPERATOR_SCHEMA(ATen);
CAFFE_KNOWN_TYPE(at::Half);

namespace math {
template<>
void Set<at::Half,CPUContext>(TIndex N, at::Half h, at::Half* v, CPUContext * c) {
  Set(0, h.x, (uint16_t*) v, c);
}
}

}

/**
 * Copyright (c) 2016-present, Facebook, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include "aten_op.h"

namespace caffe2 {

REGISTER_CPU_OPERATOR(ATen, ATenOp<CPUContext>);
template<>
at::Backend ATenOp<CPUContext>::backend() const {
  return at::kCPU;
}

OPERATOR_SCHEMA(ATen);
CAFFE_KNOWN_TYPE(at::Half);

namespace math {
template<>
void Set<at::Half,CPUContext>(const size_t N, const at::Half h, at::Half* v, CPUContext * c) {
  Set(0, h.x, (uint16_t*) v, c);
}
}

}

Fix function signature in ATenOp for at::Half Set function


#include "qmimedatabase.h"

#include <QtCore/QCoreApplication>
#include <QtCore/QFile>

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

    if (argc <= 1) {
        printf( "No filename specified\n" );
        return 1;
    }
    const QString fileName = QFile::decodeName(argv[1]);
    //int accuracy;
    QMimeDatabase db;
    QMimeType mime;
    if (fileName == QLatin1String("-")) {
        QFile qstdin;
        qstdin.open(stdin, QIODevice::ReadOnly);
        const QByteArray data = qstdin.readAll();
        //mime = QMimeType::findByContent(data, &accuracy);
        mime = db.findByData(data);
    //} else if (args->isSet("c")) {
        //mime = QMimeType::findByFileContent(fileName, &accuracy);
    } else {
        //mime = QMimeType::findByPath(fileName, 0, args->isSet("f"), &accuracy);
        mime = db.findByFile(fileName);
    }
    if ( mime.isValid() /*&& !mime.isDefault()*/ ) {
        printf("%s\n", mime.name().toLatin1().constData());
        //printf("(accuracy %d)\n", accuracy);
    } else {
        return 1; // error
    }

    return 0;
}

#include "qmimedatabase.h"

#include <QtCore/QCoreApplication>
#include <QtCore/QFile>

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

    if (argc <= 1) {
        printf( "No filename specified\n" );
        return 1;
    }
    QString option;
    int fnPos = 1;
    if (argc > 2) {
        option = QString::fromLatin1(argv[1]);
        ++fnPos;
    }
    const QString fileName = QFile::decodeName(argv[fnPos]);
    //int accuracy;
    QMimeDatabase db;
    QMimeType mime;
    if (fileName == QLatin1String("-")) {
        QFile qstdin;
        qstdin.open(stdin, QIODevice::ReadOnly);
        const QByteArray data = qstdin.readAll();
        //mime = QMimeType::findByContent(data, &accuracy);
        mime = db.findByData(data);
    } else if (option == "-c") {
        QFile file(fileName);
        if (file.open(QIODevice::ReadOnly)) {
            mime = db.findByData(file.read(32000));
        }
    } else {
        //mime = QMimeType::findByPath(fileName, 0, args->isSet("f"), &accuracy);
        mime = db.findByFile(fileName);
    }
    if ( mime.isValid() /*&& !mime.isDefault()*/ ) {
        printf("%s\n", mime.name().toLatin1().constData());
        //printf("(accuracy %d)\n", accuracy);
    } else {
        return 1; // error
    }

    return 0;
}

Add suport for mimetypefinder -c file (find by file contents)


#include <iostream>
#include <vector>
#include <iomanip>
#include <cmath>
#include <random>

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

using namespace std;

// Implementation of the One-Time Pad key generation

int main(int argc, char* argv[])
{
    if(argc < 2) {
        cout << "Usage: " << argv[0] << " len (key lenght in bytes)" << endl;
        return -1;
    }

    int len = atoi(argv[1]);
    if(len < 1)
    {
        cout << "Error in key size specification, must be > 1" << endl;
        return -1;
    }

    // Open random device:
    std::random_device rd2("/dev/random");
    std::uniform_int_distribution<> dis(0,255);
    for(unsigned int i = 0; i < len; ++i)
    {
        std::cout << hex << setw(2) << setfill('0') << dis(rd2);
    }
    std::cout << dec << endl;

    return 0;
}

#include <iostream>
#include <vector>
#include <iomanip>
#include <cmath>
#include <random>

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

using namespace std;

// Implementation of the One-Time Pad key generation

int main(int argc, char* argv[])
{
    if(argc < 2) {
        cout << "Usage: " << argv[0] << " len (key lenght in bytes)" << endl;
        return -1;
    }

    int len = atoi(argv[1]);
    if(len < 1)
    {
        cout << "Error in key size specification, must be > 1" << endl;
        return -1;
    }

    // Open random device:
    std::random_device rd("/dev/urandom");
    std::uniform_int_distribution<> dis(0,255);
    for(unsigned int i = 0; i < len; ++i)
    {
        std::cout << hex << setw(2) << setfill('0') << dis(rd);
    }
    std::cout << dec << endl;

    return 0;
}

Change to /dev/urandom, as /dev/random was just haning/very slow


#include "common.th"

_start:
  prologue

  c <- 67
  call(totient)

  illegal

// Computes the number of values less than C that are relatively prime to C.
// Stores the result in B.
totient:
  b <- 0
  d <- c

loop:
  k <- d == a
  jnzrel(k, done)

  pushall(b,c,d)

  call(gcd)

  k <- b <> 1
  k <- k + 1

  popall(b,c,d)

  b <- b + k

  d <- d - 1
  goto(loop)

done:
  ret

#include "common.th"

_start:
  prologue

  c <- 67
  call(totient)

  illegal

// Computes the number of values less than C that are relatively prime to C.
// Stores the result in B.
totient:
  b <- 0
  d <- c

loop:
  k <- d == a
  jnzrel(k, done)

  pushall(b,c,d)

  call(gcd)

  k <- b <> 1

  popall(b,c,d)

  b <- b + k + 1

  d <- d - 1
  goto(loop)

done:
  ret

Reduce instruction count of totient


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

// UNSUPPORTED: c++98, c++03
// REQUIRES: diagnose-if-support

// <unordered_set>

// Test that we generate a reasonable diagnostic when the specified hash is
// not enabled.

#include <unordered_set>
#include <utility>

using VT = std::pair<int, int>;
using Set = std::unordered_set<VT>;

int main() {

  Set s; // expected-error@__hash_table:* {{the specified hash functor does not meet the requirements for an enabled hash}}

  // FIXME: It would be great to suppress the below diagnostic all together.
  //        but for now it's sufficient that it appears last. However there is
  //        currently no way to test the order diagnostics are issued.
  // expected-error@memory:* {{call to implicitly-deleted default constructor of 'std::__1::hash<std::__1::pair<int, int> >'}}
}

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

// REQUIRES: diagnose-if-support
// UNSUPPORTED: c++98, c++03

// Libc++ only provides a defined primary template for std::hash in C++14 and
// newer.
// UNSUPPORTED: c++11

// <unordered_set>

// Test that we generate a reasonable diagnostic when the specified hash is
// not enabled.

#include <unordered_set>
#include <utility>

using VT = std::pair<int, int>;
using Set = std::unordered_set<VT>;

int main() {

  Set s; // expected-error@__hash_table:* {{the specified hash functor does not meet the requirements for an enabled hash}}

  // FIXME: It would be great to suppress the below diagnostic all together.
  //        but for now it's sufficient that it appears last. However there is
  //        currently no way to test the order diagnostics are issued.
  // expected-error@memory:* {{call to implicitly-deleted default constructor of 'std::__1::hash<std::__1::pair<int, int> >'}}
}

Mark test as unsupported in C++11


#include "SubstringWithConcatenationOfAllWords.hpp"

#include <unordered_map>
using namespace std;

vector<int> SubstringWithConcatenationOfAllWords::findSubstring(string s, vector<string>& words)
{
  vector<int> ret;
  size_t seglen = words[0].size();
  size_t nsegs = words.size();
  if (nsegs == 0 || s.size() == 0 || seglen == 0 || seglen * nsegs > s.size())
    return ret;

  unordered_map<string, int> records;
  for (auto w : words)
    records[w]++;

  int p = 0;
  while (p + seglen * nsegs - 1 < s.size()) {
    unordered_map<string, int> local = records;
    int i;
    for (i = 0; i < nsegs; i++) {
      string seg = s.substr(p + i * seglen, seglen);
      if (local.find(seg) == local.end() || local[seg] == 0)
        break;
      else
        local[seg]--;
    }
    if (i == nsegs)
      ret.push_back(p);
    p++;
  }

  return ret;
}

#include "SubstringWithConcatenationOfAllWords.hpp"

#include <unordered_map>
using namespace std;

vector<int> SubstringWithConcatenationOfAllWords::findSubstring(string s, vector<string>& words)
{
  vector<int> ret;
  size_t strlen = s.size();
  size_t numw = words.size();

  if (strlen == 0 || numw == 0) return ret;

  size_t wlen = words[0].size();
  size_t substrlen = numw * wlen;

  if (wlen == 0 || substrlen > strlen) return ret;

  unordered_map<string, int> records;
  for (auto w : words)
    records[w]++;

  for (int p = 0; p + substrlen - 1 < strlen; p++) {
    unordered_map<string, int> local = records;
    int q;
    for (q = 0; q < numw; q++) {
      string seg = s.substr(p + q * wlen, wlen);
      if (local.find(seg) == local.end() || local[seg] == 0)
        break;
      else
        local[seg]--;
    }
    if (q == numw)
      ret.push_back(p);
  }

  return ret;
}

Clean up Problem 30 solution


#include <motor/multirotor_quad_x_motor_mapper.hpp>

#include <array>

MultirotorQuadXMotorMapper::MultirotorQuadXMotorMapper() {
}

void MultirotorQuadXMotorMapper::init() {
  PWMMotorMapper::init();
}

void MultirotorQuadXMotorMapper::run(actuator_setpoint_t& input) {
  // Calculate output shifts
  std::array<float, 4> output_shifts = {
     1.0f * input.pitch_sp + 1.0f * input.roll_sp + 1.0f * input.yaw_sp, // front left
    -1.0f * input.pitch_sp + 1.0f * input.roll_sp - 1.0f * input.yaw_sp, // front right
    -1.0f * input.pitch_sp - 1.0f * input.roll_sp + 1.0f * input.yaw_sp, // back right
     1.0f * input.pitch_sp - 1.0f * input.roll_sp - 1.0f * input.yaw_sp  // back left
  };

  // Add throttle to shifts to get absolute output value
  std::array<float, 4> outputs = { 0 };
  for(int i = 0; i < 4; i++) {
    outputs[i] = input.throttle_sp + output_shifts[i];
  }

  setMotorSpeeds(outputs);
}

#include <motor/multirotor_quad_x_motor_mapper.hpp>

#include <array>

MultirotorQuadXMotorMapper::MultirotorQuadXMotorMapper() {
}

void MultirotorQuadXMotorMapper::init() {
  PWMMotorMapper::init();
}

void MultirotorQuadXMotorMapper::run(actuator_setpoint_t& input) {
  // Calculate output shifts
  // TODO(yoos): comment on motor indexing convention starting from positive
  // X in counterclockwise order.
  std::array<float, 4> output_shifts = {
      1.0f * input.roll_sp - 1.0f * input.pitch_sp + 1.0f * input.yaw_sp,   // front left
      1.0f * input.roll_sp + 1.0f * input.pitch_sp - 1.0f * input.yaw_sp,   // back left
    - 1.0f * input.roll_sp + 1.0f * input.pitch_sp + 1.0f * input.yaw_sp,   // back right
    - 1.0f * input.roll_sp - 1.0f * input.pitch_sp - 1.0f * input.yaw_sp    // front right
  };

  // Add throttle to shifts to get absolute output value
  std::array<float, 4> outputs = { 0 };
  for(int i = 0; i < 4; i++) {
    outputs[i] = input.throttle_sp + output_shifts[i];
  }

  setMotorSpeeds(outputs);
}

Reorder quadrotor motors per convention.