#include "OptionsManager.h"

#include <fstream>
#include <iostream>

#include <boost/filesystem.hpp>

#include <spotify/json.hpp>

#include "codecs/OptionsCodec.h"
#include "logging/Logging.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 (const spotify::json::decode_exception& e)
    {
        logError() << "spotify::json::decode_exception encountered at "
            << e.offset()
            << ": "
            << e.what();
        throw;
    }
    mOptions.paths.initialise(optionsFilename);
    createOutputDirectory();
}

void OptionsManager::createOutputDirectory()
{
    // TODO(hryniuk): move it elsewhere
    boost::filesystem::path p(mOptions.paths.directory);
    p.append(mOptions.outputDirectory);
    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"
#include "logging/Logging.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 (const spotify::json::decode_exception& e)
    {
        logError() << "spotify::json::decode_exception encountered at "
            << e.offset()
            << ": "
            << e.what();
        throw;
    }
    mOptions.paths.initialise(optionsFilename);
    createOutputDirectory();
}

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

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

Revert "Remove extra call to create_directories"


#include "vast/detail/cppa_type_info.h"

#include <cppa/announce.hpp>
#include "vast/chunk.h"
#include "vast/event.h"
#include "vast/expression.h"
#include "vast/schema.h"
#include "vast/segment.h"
#include "vast/to_string.h"
#include "vast/uuid.h"

namespace vast {
namespace detail {

template <typename T>
void cppa_announce()
{
  cppa::announce(typeid(T), new cppa_type_info<T>);
}

void cppa_announce_types()
{
  cppa_announce<uuid>();
  cppa_announce<event>();
  cppa_announce<chunk<event>>();

  cppa_announce<expression>();
  cppa_announce<segment>();
  cppa_announce<schema>();

  cppa::announce<std::vector<uuid>>();
  cppa::announce<std::vector<event>>();
}

} // namespace detail
} // namespace vast

#include "vast/detail/cppa_type_info.h"

#include <cppa/announce.hpp>
#include "vast/chunk.h"
#include "vast/event.h"
#include "vast/expression.h"
#include "vast/schema.h"
#include "vast/segment.h"
#include "vast/to_string.h"
#include "vast/uuid.h"

namespace vast {
namespace detail {

template <typename T>
void cppa_announce()
{
  cppa::announce(typeid(T), new cppa_type_info<T>);
}

void cppa_announce_types()
{
  cppa_announce<uuid>();
  cppa_announce<event>();
  cppa_announce<chunk<event>>();

  cppa_announce<expression>();
  cppa_announce<segment>();
  cppa_announce<schema>();

  cppa_announce<std::vector<uuid>>();
  cppa_announce<std::vector<event>>();
}

} // namespace detail
} // namespace vast

Fix nasty bug introduced due to naming glitch.


// RUN: %clangxx -g -DSHARED_LIB %s -fPIC -shared -o %dynamiclib %ld_flags_rpath_so
// RUN: %clangxx_cfi_diag -g %s -o %t %ld_flags_rpath_exe
// RUN: %run %t 2>&1 | FileCheck %s

// REQUIRES: cxxabi
// UNSUPPORTED: win32

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

struct A {
  virtual void f();
};

void *create_B();

#ifdef SHARED_LIB

struct B {
  virtual void f();
};
void B::f() {}

void *create_B() {
  return (void *)(new B());
}

#else

void A::f() {}

int main(int argc, char *argv[]) {
  void *p = create_B();
  // CHECK: runtime error: control flow integrity check for type 'A' failed during cast to unrelated type
  // CHECK: invalid vtable in module {{.*}}libtarget_uninstrumented.cpp.dynamic.so
  A *a = (A *)p;
  memset(p, 0, sizeof(A));
  // CHECK: runtime error: control flow integrity check for type 'A' failed during cast to unrelated type
  // CHECK-NOT: invalid vtable in module
  // CHECK: invalid vtable
  a = (A *)p;
  // CHECK: done
  fprintf(stderr, "done %p\n", a);
}
#endif

// RUN: %clangxx -g -DSHARED_LIB %s -fPIC -shared -o %dynamiclib %ld_flags_rpath_so
// RUN: %clangxx_cfi_diag -g %s -o %t %ld_flags_rpath_exe
// RUN: %run %t 2>&1 | FileCheck %s

// REQUIRES: cxxabi
// UNSUPPORTED: win32

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

struct A {
  virtual void f();
};

void *create_B();

#ifdef SHARED_LIB

struct B {
  virtual void f();
};
void B::f() {}

void *create_B() {
  return (void *)(new B());
}

#else

void A::f() {}

int main(int argc, char *argv[]) {
  void *p = create_B();
  // CHECK: runtime error: control flow integrity check for type 'A' failed during cast to unrelated type
  // CHECK: invalid vtable
  // CHECK: check failed in {{.*}}, vtable located in {{.*}}libtarget_uninstrumented.cpp.dynamic.so
  A *a = (A *)p;
  memset(p, 0, sizeof(A));

  // CHECK: runtime error: control flow integrity check for type 'A' failed during cast to unrelated type
  // CHECK: invalid vtable
  // CHECK: check failed in {{.*}}, vtable located in (unknown)
  a = (A *)p;
  // CHECK: done
  fprintf(stderr, "done %p\n", a);
}
#endif

Fix test broken by r335644


#include <iostream>
using namespace std;
#include "numvec.hpp"

template<typename T>
void f1(T &res, const T &x)
{
  T u,y = 2*x;
  y = 7*x;
  y -= 1.2;
  u = x + y;
  y = y/x;
  u = 3/x;
  u += -y;
  u += 1.1*x;
  y = sin(u);
  res = pow(x,y);
}

void test_correctness()
{
  const int len = 4;
  numvec<double, len> inp, out;
  for (int i=0;i<len;i++)
    inp[i] = i+0.1;
  f1(out,inp);
  double sumres = 0;
  for (int i=0;i<len;i++)
    {
      double outd;
      f1(outd,inp[i]);
      sumres += fabs(out[i] - outd);
      cout << outd << " " << out[i] << endl;
    }
  cout.precision(15);
  cout << "Sum of absolute differences " << sumres << endl;
}

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

#include <iostream>
using namespace std;
#include "numvec.hpp"

template<typename T>
void f1(T &res, const T &x)
{
  T u,y = 2*x;
  y = 7*x;
  y -= 1.2;
  u = x + y;
  y = y/x;
  u = 3/x;
  u += -y;
  u += 1.1*x;
  y = sin(u);
  res = pow(x,y);
  y = pow(res,1.2);
  res = pow(y,3);
}

void test_correctness()
{
  const int len = 4;
  numvec<double, len> inp, out;
  for (int i=0;i<len;i++)
    inp[i] = i+0.1;
  f1(out,inp);
  double sumres = 0;
  for (int i=0;i<len;i++)
    {
      double outd;
      f1(outd,inp[i]);
      sumres += fabs(out[i] - outd);
    }
  cout.precision(15);
  cout << "Sum of absolute differences " << sumres << endl;
}

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

Test pow with scalar double exponent and integer exponent.


// Copyright (c) 2015, Matthew Malensek.
// Distributed under the BSD 2-Clause License (see LICENSE.txt for details)

#include "HorizontalTile.h"

HorizontalTile::HorizontalTile(std::wstring bitmapName,
    int x, int y, int units, bool reverse) :
Meter(bitmapName, x, y, units),
_reverse(reverse) {
    _rect.Width = _bitmap->GetWidth();
    _rect.Height = _bitmap->GetHeight();

    _texture = new Gdiplus::TextureBrush(_bitmap, Gdiplus::WrapModeTile,
        0, 0, _rect.Width, _rect.Height);
    _shiftMat = new Gdiplus::Matrix(1, 0, 0, 1,
        (float) _rect.X, (float) _rect.Y);
    _texture->SetTransform(_shiftMat);
}

HorizontalTile::~HorizontalTile() {
    delete _texture;
    delete _shiftMat;
}

void HorizontalTile::Draw(
        Gdiplus::Bitmap *buffer, Gdiplus::Graphics *graphics) {

    int width = _rect.Width * CalcUnits();

    if (_reverse == false) {
        graphics->FillRectangle(_texture,
            _rect.X, _rect.Y, width, _rect.Height);
    } else {
        int xShift = _rect.Width * Units() - width;
        graphics->FillRectangle(_texture,
            _rect.X + xShift, _rect.Y, width, _rect.Height);
    }

    UpdateDrawnValues();
}

Remove space (major changes here, people)


#include <Python.h>
#include "Quantuccia/ql/time/calendars/unitedstates.hpp"

static PyObject*
get_holiday_date(PyObject *self, PyObject *args)
{
    return NULL;
}

static PyMethodDef QuantucciaMethods[] = {
	{"get_holiday_date", (PyCFunction)get_holiday_date, METH_VARARGS, NULL},
	{NULL,     NULL}        /* Sentinel */
};

PyObject* PyInit_pyQuantuccia(void){
    PyObject *m;
    m = PyCreate_Module("quantuccia", QuantucciaMethods);
    return m;
}

#include <Python.h>
#include "Quantuccia/ql/time/calendars/unitedstates.hpp"

static PyObject*
get_holiday_date(PyObject *self, PyObject *args)
{
    return NULL;
}

static PyMethodDef QuantucciaMethods[] = {
	{"get_holiday_date", (PyCFunction)get_holiday_date, METH_VARARGS, NULL},
	{NULL,     NULL}        /* Sentinel */
};

static struct PyModuleDef quantuccia_module_def = {
	PyModuleDef_HEAD_INIT,
	"quantuccia",
	NULL,
	-1,
	QuantucciaMethods,
};

PyObject* PyInit_pyQuantuccia(void){
    PyObject *m;
    m = PyCreate_Module(&quantuccia_module_def);
    return m;
}

Correct the way the module is defined.


// Copyright lowRISC contributors.
// Licensed under the Apache License, Version 2.0, see LICENSE for details.
// SPDX-License-Identifier: Apache-2.0

#include <signal.h>

#include <iostream>

#include "verilated_toplevel.h"
#include "verilator_sim_ctrl.h"

ibex_riscv_compliance *top;
VerilatorSimCtrl *simctrl;

int main(int argc, char **argv) {
  int retcode;
  top = new ibex_riscv_compliance;
  simctrl = new VerilatorSimCtrl(top, top->IO_CLK, top->IO_RST_N,
                                 VerilatorSimCtrlFlags::ResetPolarityNegative);

  // Setup simctrl
  retcode = simctrl->SetupSimulation(argc, argv);

  // Initialize RAM
  simctrl->InitRam("TOP.ibex_riscv_compliance.u_ram");

  // Run the simulation
  simctrl->RunSimulation();

  delete top;
  delete simctrl;
  return retcode;
}

// Copyright lowRISC contributors.
// Licensed under the Apache License, Version 2.0, see LICENSE for details.
// SPDX-License-Identifier: Apache-2.0

#include <signal.h>

#include <iostream>

#include "verilated_toplevel.h"
#include "verilator_sim_ctrl.h"

ibex_riscv_compliance *top;
VerilatorSimCtrl *simctrl;

int main(int argc, char **argv) {
  int retcode;
  top = new ibex_riscv_compliance;
  simctrl = new VerilatorSimCtrl(top, top->IO_CLK, top->IO_RST_N,
                                 VerilatorSimCtrlFlags::ResetPolarityNegative);

  // Setup simctrl
  retcode = simctrl->SetupSimulation(argc, argv);
  if (retcode != 0) {
    goto free_return;
  }

  // Initialize RAM
  simctrl->InitRam("TOP.ibex_riscv_compliance.u_ram");

  // Run the simulation
  simctrl->RunSimulation();

free_return:
  delete top;
  delete simctrl;
  return retcode;
}

Add exit check for setup call


/**
 * Author: Václav Volhejn
 * Source: KACTL notebook (various/chapter.tex)
 * Status: Tested manually, forAllSubsetMasks tested at Ptz
 * Description: Various bit manipulation functions/snippets.
 */
#include "../base.hpp"

int lowestSetBit(int x) { return x & -x }

void forAllSubsetMasks(int m) { // Including m itself
    for (int x = m; x; --x &= m) { /* ... */ }
}

int nextWithSamePopcount(int x) { // 3->5->6->9->10->12->17...
    int c = x&-x, r = x+c;
    return (((r^x) >> 2)/c) | r;
}

// For each mask, compute sum of values D[1<<i] of its set bits i
void sumsOfSubsets() {
    int K = 3;
    vector<int> D(1<<K, 0);
    D[1] = 4; D[2] = 3; D[4] = 8;
    rep(b,0,K) rep(i,0,(1 << K)) if (i & 1 << b) D[i] += D[i^(1 << b)];
}

/**
 * Name: Bit hacks
 * Author: Václav Volhejn
 * Source: KACTL notebook (various/chapter.tex)
 * Status: Tested manually, forAllSubsetMasks tested at Ptz
 * Description: Various bit manipulation functions/snippets.
 */
#include "../base.hpp"

int lowestSetBit(int x) { return x & -x }

void forAllSubsetMasks(int m) { // Including m itself
    for (int x = m; x; --x &= m) { /* ... */ }
}

int nextWithSamePopcount(int x) { // 3->5->6->9->10->12->17...
    int c = x&-x, r = x+c;
    return (((r^x) >> 2)/c) | r;
}

// For each mask, compute sum of values D[1<<i] of its set bits i
void sumsOfSubsets() {
    int K = 3;
    vector<int> D(1<<K, 0);
    D[1] = 4; D[2] = 3; D[4] = 8;
    rep(b,0,K) rep(i,0,(1 << K)) if (i & 1 << b) D[i] += D[i^(1 << b)];
}

Add name for bit hacks


#include "gameitem.h"

#include <QDeclarativeExpression>

GameItem::GameItem(QQuickItem *parent)
    : QQuickItem(parent),
      m_expression(0)
{
}

void GameItem::update(long delta)
{
    if (m_expression)
        m_expression->evaluate();
}

QDeclarativeScriptString GameItem::updateScript() const
{
    return m_updateScript;
}

void GameItem::setUpdateScript(QDeclarativeScriptString updateScript)
{
    m_updateScript = updateScript;

    if (m_expression)
        delete m_expression;

    m_expression = new QDeclarativeExpression(m_updateScript);

    emit updateScriptChanged();
}

#include "gameitem.h"

#include <QDeclarativeExpression>

GameItem::GameItem(QQuickItem *parent)
    : QQuickItem(parent),
      m_expression(0)
{
}

void GameItem::update(long delta)
{
    if (m_expression)
        m_expression->evaluate();
}

QDeclarativeScriptString GameItem::updateScript() const
{
    return m_updateScript;
}

void GameItem::setUpdateScript(QDeclarativeScriptString updateScript)
{
    m_updateScript = updateScript;

    if (m_expression)
        delete m_expression;

    m_expression = new QDeclarativeExpression(m_updateScript.context(), m_updateScript.scopeObject(), m_updateScript.script());

    emit updateScriptChanged();
}

Change declarative expression to get context and scopre from script


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

#include "base/string_piece.h"

namespace content {

ShellContentClient::~ShellContentClient() {
}

void ShellContentClient::SetActiveURL(const GURL& url) {
}

void ShellContentClient::SetGpuInfo(const GPUInfo& gpu_info) {
}

void ShellContentClient::AddPepperPlugins(
    std::vector<PepperPluginInfo>* plugins) {
}

bool ShellContentClient::CanSendWhileSwappedOut(const IPC::Message* msg) {
  return false;
}

bool ShellContentClient::CanHandleWhileSwappedOut(const IPC::Message& msg) {
  return false;
}

std::string ShellContentClient::GetUserAgent(bool mimic_windows) const {
  return std::string();
}

string16 ShellContentClient::GetLocalizedString(int message_id) const {
  return string16();
}

base::StringPiece ShellContentClient::GetDataResource(int resource_id) const {
  return base::StringPiece();
}

#if defined(OS_WIN)
bool ShellContentClient::SandboxPlugin(CommandLine* command_line,
                                       sandbox::TargetPolicy* policy) {
  return false;
}
#endif

}  // namespace content

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

#include "base/string_piece.h"
#include "webkit/glue/user_agent.h"

namespace content {

ShellContentClient::~ShellContentClient() {
}

void ShellContentClient::SetActiveURL(const GURL& url) {
}

void ShellContentClient::SetGpuInfo(const GPUInfo& gpu_info) {
}

void ShellContentClient::AddPepperPlugins(
    std::vector<PepperPluginInfo>* plugins) {
}

bool ShellContentClient::CanSendWhileSwappedOut(const IPC::Message* msg) {
  return false;
}

bool ShellContentClient::CanHandleWhileSwappedOut(const IPC::Message& msg) {
  return false;
}

std::string ShellContentClient::GetUserAgent(bool mimic_windows) const {
  return webkit_glue::BuildUserAgentHelper(mimic_windows, "Chrome/15.16.17.18");
}

string16 ShellContentClient::GetLocalizedString(int message_id) const {
  return string16();
}

base::StringPiece ShellContentClient::GetDataResource(int resource_id) const {
  return base::StringPiece();
}

#if defined(OS_WIN)
bool ShellContentClient::SandboxPlugin(CommandLine* command_line,
                                       sandbox::TargetPolicy* policy) {
  return false;
}
#endif

}  // namespace content

Use Chrome's user agent string for content_shell, since some sites (i.e. Gmail) give a degraded experience otherwise.


#include <MemoryManager.hh>

#include <cstddef>
#include <new>

void *operator new(std::size_t size)
{
   return MemoryManager::get().allocate(size);
}

void *operator new[](std::size_t size)
{
   return MemoryManager::get().allocate(size);
}

void operator delete(void* p)
{
   MemoryManager::get().deallocate(p);
}

void operator delete[](void* p)
{
   MemoryManager::get().deallocate(p);
}

void operator delete(void* p, std::size_t)
{
   MemoryManager::get().deallocate(p);
}

void operator delete[](void* p, std::size_t)
{
   MemoryManager::get().deallocate(p);
}

Add symbols for sized allocation


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


#include <QtPlugin>

#include "test_video_annotator.h"
#include "fish_detector/video_annotator/mainwindow.h"

#ifdef _WIN32
Q_IMPORT_PLUGIN(QWindowsIntegrationPlugin)
#endif

void TestVideoAnnotator::testLoadVideo() {
  fish_detector::video_annotator::MainWindow mainwin;
  mainwin.player_->loadVideo("slow_motion_drop.mp4");
}
void TestVideoAnnotator::testSaveAnnotationsNoFish() {
}

QTEST_MAIN(TestVideoAnnotator)
#include "test_video_annotator.moc"

#include <QtPlugin>

#include "test_video_annotator.h"
#include "fish_detector/video_annotator/mainwindow.h"

#ifdef _WIN32
Q_IMPORT_PLUGIN(QWindowsIntegrationPlugin)
#endif

void TestVideoAnnotator::testLoadVideo() {
  fish_detector::video_annotator::MainWindow mainwin;
  std::string name = "C:/local/FishDetector/test/video_annotator/slow_motion_drop.mp4";
  QVERIFY(mainwin.player_->loadVideo(name));
}
void TestVideoAnnotator::testSaveAnnotationsNoFish() {
  fish_detector::video_annotator::MainWindow mainwin;
  std::string filename = "slow_motion_drop.mp4";
  QVERIFY(mainwin.player_->loadVideo(filename));
  mainwin.onLoadVideoSuccess(QString::fromUtf8(filename.c_str()));
}

QTEST_MAIN(TestVideoAnnotator)
#include "test_video_annotator.moc"

Add content to second test


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

#include "base/values.h"
#include "chrome/browser/chromeos/input_method/input_method_manager.h"
#include "chrome/browser/chromeos/extensions/input_method_event_router.h"
#include "chrome/browser/extensions/extension_service.h"
#include "chrome/browser/profiles/profile.h"

GetInputMethodFunction::GetInputMethodFunction() {
}

GetInputMethodFunction::~GetInputMethodFunction() {
}

bool GetInputMethodFunction::RunImpl() {
#if !defined(OS_CHROMEOS)
  NOTREACHED();
#else
  chromeos::ExtensionInputMethodEventRouter* router =
      profile_->GetExtensionService()->input_method_event_router();
  chromeos::input_method::InputMethodManager* manager =
      chromeos::input_method::InputMethodManager::GetInstance();
  const std::string input_method =
      router->GetInputMethodForXkb(manager->current_input_method().id());
  result_.reset(Value::CreateStringValue(input_method));
  return true;
#endif
}

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

#include "base/values.h"
#include "chrome/browser/chromeos/input_method/input_method_manager.h"
#include "chrome/browser/chromeos/extensions/input_method_event_router.h"
#include "chrome/browser/extensions/extension_service.h"
#include "chrome/browser/profiles/profile.h"

GetInputMethodFunction::GetInputMethodFunction() {
}

GetInputMethodFunction::~GetInputMethodFunction() {
}

bool GetInputMethodFunction::RunImpl() {
#if !defined(OS_CHROMEOS)
  NOTREACHED();
  return false;
#else
  chromeos::ExtensionInputMethodEventRouter* router =
      profile_->GetExtensionService()->input_method_event_router();
  chromeos::input_method::InputMethodManager* manager =
      chromeos::input_method::InputMethodManager::GetInstance();
  const std::string input_method =
      router->GetInputMethodForXkb(manager->current_input_method().id());
  result_.reset(Value::CreateStringValue(input_method));
  return true;
#endif
}

Fix a build error when OS_CHROMEOS is not defined.


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

#ifndef REMOVE_VALUES
#ifndef CHECK_VALUES
#error "define one of REMOVE_VALUES or CHECK_VALUES"
#endif
#endif

#ifdef REMOVE_VALUES
#ifdef CHECK_VALUES
#error "define either REMOVE_VALUES or CHECK_VALUES"
#endif
#endif

int main()
{
	std::vector<int> myValues;
  for ( long int i=0L; i<100000000L; ++i )
		myValues.push_back(i%3);

	int iOriginalSize = myValues.size();
#ifdef REMOVE_VALUES
	myValues.erase(std::remove_if(myValues.begin(),myValues.end(),[](int i) { return i == 2; }),myValues.end());
#endif
	int sum = 0;
  for ( unsigned int i=0; i<myValues.size(); ++i )
	{
#ifdef CHECK_VALUES
		if ( myValues[i] != 2 )
		{
#endif
			sum += myValues[i];
#ifdef CHECK_VALUES
		}
#endif
	}

}

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

#ifndef REMOVE_VALUES
#ifndef CHECK_VALUES
#error "define one of REMOVE_VALUES or CHECK_VALUES"
#endif
#endif

#ifdef REMOVE_VALUES
#ifdef CHECK_VALUES
#error "define either REMOVE_VALUES or CHECK_VALUES"
#endif
#endif

int main()
{
	std::vector<int> myValues;
	for ( long int i=0L; i<10000000L; ++i )
		myValues.push_back(i%3);

	int iOriginalSize = myValues.size();
#ifdef REMOVE_VALUES
	myValues.erase(std::remove_if(myValues.begin(),myValues.end(),[](int i) { return i == 2; }),myValues.end());
#endif

	const int iterations = 100;
	for ( int iteration=0; iteration < iterations; ++iteration )
	{
		int sum = 0;
		for ( unsigned int i=0; i<myValues.size(); ++i )
		{
#ifdef CHECK_VALUES
			if ( myValues[i] != 2 )
			{
#endif
				sum += myValues[i];
#ifdef CHECK_VALUES
			}
#endif
		}
	}

}

Check vs Remove - not so not so clear


#include "Test.h"

TEST_CASE("Nets") {
    auto tree = SyntaxTree::fromText(R"(
module Top;
    wire logic f = 1;
endmodule
)");

    Compilation compilation;
    compilation.addSyntaxTree(tree);
    NO_COMPILATION_ERRORS;
}

TEST_CASE("Continuous Assignments") {
    auto tree = SyntaxTree::fromText(R"(
module Top;
    wire foo;
    assign foo = 1, foo = 'z;

    logic bar;
    assign bar = 1;
endmodule
)");

    Compilation compilation;
    compilation.addSyntaxTree(tree);
    NO_COMPILATION_ERRORS;
}

#include "Test.h"

#include <nlohmann/json.hpp>

TEST_CASE("Nets") {
    auto tree = SyntaxTree::fromText(R"(
module Top;
    wire logic f = 1;
endmodule
)");

    Compilation compilation;
    compilation.addSyntaxTree(tree);
    NO_COMPILATION_ERRORS;
}

TEST_CASE("Continuous Assignments") {
    auto tree = SyntaxTree::fromText(R"(
module Top;
    wire foo;
    assign foo = 1, foo = 'z;

    logic bar;
    assign bar = 1;
endmodule
)");

    Compilation compilation;
    compilation.addSyntaxTree(tree);
    NO_COMPILATION_ERRORS;
}

TEST_CASE("JSON dump") {
    auto tree = SyntaxTree::fromText(R"(
interface I;
    modport m();
endinterface

package p1;
    parameter int BLAH = 1;
endpackage

module Top;
    wire foo;
    assign foo = 1;

    I array [3] ();

    always_comb begin
    end

    if (1) begin
    end

    for (genvar i = 0; i < 10; i++) begin
    end

    import p1::BLAH;

    import p1::*;

    logic f;
    I stuff();
    Child child(.i(stuff), .f);

    function logic func(logic bar);
    endfunction

endmodule

module Child(I.m i, input logic f = 1);
endmodule
)");

    Compilation compilation;
    compilation.addSyntaxTree(tree);
    NO_COMPILATION_ERRORS;

    // This basic test just makes sure that JSON dumping doesn't crash.
    json output = compilation.getRoot();
    output.dump();
}

Add test for JSON dumping


#include <Automaton.h>
#include "Atm_blink.h"

Atm_blink & Atm_blink::begin( int attached_pin, int blinkrate )
{
  const static state_t state_table[] PROGMEM = {
  /*            ON_ENTER    ON_LOOP  ON_EXIT  EVT_TIMER   ELSE */
  /* LED_ON  */   ACT_ON,        -1,      -1,   LED_OFF,    -1,
  /* LED_OFF */  ACT_OFF,        -1,      -1,    LED_ON,    -1 };
  Machine::begin( state_table, ELSE );
  pin = attached_pin;
  timer.begin( this, blinkrate );
  pinMode( pin, OUTPUT );
  return *this;
}

int Atm_blink::event( int id )
{
  switch ( id ) {
  	case EVT_TIMER :
  	  return timer.expired();
   }
   return 0;
}

void Atm_blink::action( int id )
{
  switch ( id ) {
  	case ACT_ON :
  	  digitalWrite( pin, HIGH );
  	  return;
  	case ACT_OFF :
  	  digitalWrite( pin, LOW );
  	  return;
   }
}

Atm_blink & Atm_blink::onSwitch( swcb_sym_t switch_callback ) {

  Machine::onSwitch( switch_callback, "LED_ON\0LED_OFF", "EVT_TIMER\0ELSE" );
  return *this;
}

#include <Automaton.h>
#include "Atm_blink.h"

Atm_blink & Atm_blink::begin( int attached_pin, uint32_t blinkrate )
{
  const static state_t state_table[] PROGMEM = {
  /*            ON_ENTER    ON_LOOP  ON_EXIT  EVT_TIMER   ELSE */
  /* LED_ON  */   ACT_ON,        -1,      -1,   LED_OFF,    -1,
  /* LED_OFF */  ACT_OFF,        -1,      -1,    LED_ON,    -1 };
  Machine::begin( state_table, ELSE );
  pin = attached_pin;
  timer.begin( this, blinkrate );
  pinMode( pin, OUTPUT );
  return *this;
}

int Atm_blink::event( int id )
{
  switch ( id ) {
  	case EVT_TIMER :
  	  return timer.expired();
   }
   return 0;
}

void Atm_blink::action( int id )
{
  switch ( id ) {
  	case ACT_ON :
  	  digitalWrite( pin, HIGH );
  	  return;
  	case ACT_OFF :
  	  digitalWrite( pin, LOW );
  	  return;
   }
}

Atm_blink & Atm_blink::onSwitch( swcb_sym_t switch_callback ) {

  Machine::onSwitch( switch_callback, "LED_ON\0LED_OFF", "EVT_TIMER\0ELSE" );
  return *this;
}

Update blink_modular.ino: changed blinkrate argument to uint32_t


#include <iostream>

using namespace std;

class Complex {
	double re, im;
public:
	Complex(double r, double i) : re {r}, im {i} {}
	Complex operator+(Complex);
	Complex operator*(Complex);
	friend ostream &operator<<(ostream &os, Complex c);
};

ostream &operator<<(ostream &os, Complex c) {
	os << c.re;
	os << ((c.im >= 0) ? "+" : "-");
	os << c.im << "*i";
	return os;
}

Complex Complex::operator+(Complex c) {
	return Complex{this->re+c.re, this->im+c.im};
}

Complex Complex::operator*(Complex c) {
	double r = this->re*c.re - this->im*c.im;
	double i = this->im*c.re + this->re*c.im;
	// This is OK, probably because this is considered
	// as initializer
	return {r, i};
}

void f() {
	Complex a = Complex{1, 3.1};
	cout << a << endl;
	Complex b {1.2, 2};
	cout << b << endl;
	Complex c {b};
	cout << c << endl;

	cout << b+c << endl;
	cout << a*b + Complex{1, 2} << endl;
}

int main() {
	Complex c0 {0, 0};
	f();
	return 0;
}

#include <iostream>

using namespace std;

class Complex {
	double re, im;
public:
	Complex(double r, double i) : re {r}, im {i} {}
	Complex operator+(Complex);
	Complex operator*(Complex);
	friend ostream &operator<<(ostream &os, Complex c);
};

ostream &operator<<(ostream &os, Complex c) {
	os << c.re;
	os << ((c.im >= 0) ? "+" : "-");
	os << c.im << "*i";
	return os;
}

Complex Complex::operator+(Complex c) {
	return Complex{this->re+c.re, this->im+c.im};
}

Complex Complex::operator*(Complex c) {
	double r = this->re*c.re - this->im*c.im;
	double i = this->im*c.re + this->re*c.im;
	// This is OK, probably because this is considered
	// as initializer
	return {r, i};
}

void f() {
	Complex a = {1, 3.1};
	cout << a << endl;
	Complex b {1.2, 2};
	cout << b << endl;
	Complex c {b};
	cout << c << endl;

	cout << b+c << endl;
	cout << a*b + Complex{1, 2} << endl;
}

int main() {
	Complex c0 {0, 0};
	f();
	return 0;
}

Change to initilizer list construction


/**
 * atom_types_init.cc
 *
 * Link Grammar Atom Types used during Viterbi parsing.
 *
 * Copyright (c) 2009 Linas Vepstas <linasvepstas@gmail.com>
 */

#include "opencog/viterbi/atom_types.definitions"

using namespace opencog;

// library initialization
#if defined(WIN32) && defined(_DLL)
namespace win {
#include <windows.h>
}

win::BOOL APIENTRY DllMain(win::HINSTANCE hinstDLL,  // handle to DLL module
                           win::DWORD fdwReason,     // reason for calling function
                           win::LPVOID lpvReserved)  // reserved
{
    System::setModuleHandle(hinstDLL);
    switch (fdwReason) {
        case DLL_PROCESS_ATTACH:
            #include "opencog/viterbi/atom_types.inheritance"
            break;
        case DLL_THREAD_ATTACH:
            break;
        case DLL_THREAD_DETACH:
            break;
        case DLL_PROCESS_DETACH:
            break;
    }
    return TRUE;
}
#elif __GNUC__
static __attribute__ ((constructor)) void viterbi_init(void)
{
    #include "opencog/viterbi/atom_types.inheritance"
}

static __attribute__ ((destructor)) void viterbi_fini(void)
{
}

#endif

/**
 * atom_types_init.cc
 *
 * Link Grammar Atom Types used during Viterbi parsing.
 *
 * Copyright (c) 2009, 2013 Linas Vepstas <linasvepstas@gmail.com>
 */

#include <opencog/server/Module.h>
#include "opencog/viterbi/atom_types.definitions"

using namespace opencog;

// library initialization
#if defined(WIN32) && defined(_DLL)
namespace win {
#include <windows.h>
}

win::BOOL APIENTRY DllMain(win::HINSTANCE hinstDLL,  // handle to DLL module
                           win::DWORD fdwReason,     // reason for calling function
                           win::LPVOID lpvReserved)  // reserved
{
    System::setModuleHandle(hinstDLL);
    switch (fdwReason) {
        case DLL_PROCESS_ATTACH:
            #include "opencog/viterbi/atom_types.inheritance"
            break;
        case DLL_THREAD_ATTACH:
            break;
        case DLL_THREAD_DETACH:
            break;
        case DLL_PROCESS_DETACH:
            break;
    }
    return TRUE;
}
#elif __GNUC__
static __attribute__ ((constructor)) void viterbi_init(void)
{
    #include "opencog/viterbi/atom_types.inheritance"
}

static __attribute__ ((destructor)) void viterbi_fini(void)
{
}

#endif

TRIVIAL_MODULE(ViterbiTypesModule)
DECLARE_MODULE(ViterbiTypesModule)

Use the new atom types module macro


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.


//===- llvm/unittest/Support/TimeValueTest.cpp - Time Value tests ---------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//

#include "gtest/gtest.h"
#include "llvm/Support/TimeValue.h"
#include <time.h>

using namespace llvm;
namespace {

TEST(TimeValue, time_t) {
  sys::TimeValue now = sys::TimeValue::now();
  time_t now_t = time(NULL);
  EXPECT_TRUE(abs(static_cast<long>(now_t - now.toEpochTime())) < 2);
}

}

//===- llvm/unittest/Support/TimeValueTest.cpp - Time Value tests ---------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//

#include "gtest/gtest.h"
#include "llvm/Support/TimeValue.h"
#include <time.h>

using namespace llvm;
namespace {

TEST(TimeValue, time_t) {
  sys::TimeValue now = sys::TimeValue::now();
  time_t now_t = time(NULL);
  EXPECT_TRUE(abs(static_cast<long>(now_t - now.toEpochTime())) < 2);
}

TEST(TimeValue, Win32FILETIME) {
  uint64_t epoch_as_filetime = 0x19DB1DED53E8000ULL;
  uint32_t ns = 765432100;
  sys::TimeValue epoch;

  // FILETIME has 100ns of intervals.
  uint64_t ft1970 = epoch_as_filetime + ns / 100;
  epoch.fromWin32Time(ft1970);

  // The "seconds" part in Posix time may be expected as zero.
  EXPECT_EQ(ns / 100, epoch.toPosixTime());

  // Confirm it reversible.
  EXPECT_EQ(ft1970, epoch.toWin32Time());
}

}

Add TimeValue.Win32FILETIME, corresponding to r186374.


#include "GLPlatform.hpp"

void glPlatformInit()
{
#ifdef GL_PLATFORM_USING_WIN
  glewInit();
#endif
}

#include "GLPlatform.hpp"
#include <stdexcept>

void glPlatformInit()
{
#ifdef GL_PLATFORM_USING_WIN
  GLenum err = glewInit();
  if (GLEW_OK != err)
  {
    throw std::runtime_error("GLEW failed to initialize.");
  }
#endif
}

Add exception if GLEW fails to initialize.


#error Still to implement

string executable_path()
{
	char buffer[16 * 1024];

	int bytes = GetModuleFileName(NULL, buffer, sizeof(buffer));
	if (bytes == 0)
	{
		throw unable_to_find_executable_path{};
	}
	buffer[bytes] = '\0';
	string executable_path{buffer};

	return std::string{executable_path.cbegin(),
					   executable_path.cbegin() +
					   executable_path.find_last_of('/')};
}

#include <sdl_cpp/widgets/executable_path.h>
#include <string>
#include "Windows.h"
//#error Still to implement

using namespace ::std;

string executable_path()
{
	char buffer[16 * 1024];

	int bytes = GetModuleFileName(nullptr, buffer, sizeof(buffer));
	if (bytes == 0)
	{
		throw unable_to_find_executable_path{};
	}
	buffer[bytes] = '\0';
	string executable_path{buffer};

	return std::string{executable_path.cbegin(),
					   executable_path.cbegin() +
					   executable_path.find_last_of('\\')};
}

Add executable path on Windows


/**
* @file      BStringTests.cpp
* @copyright (c) 2014 by Petr Zemek (s3rvac@gmail.com) and contributors
* @license   BSD, see the @c LICENSE file for more details
* @brief     Tests for the BString class.
*/

#include <gtest/gtest.h>

#include "BString.h"

namespace bencoding {
namespace tests {

using namespace testing;

class BStringTests: public Test {};

TEST_F(BStringTests,
ValueReturnsCorrectValueAfterCreation) {
	auto i = BString::create("test");

	EXPECT_EQ("test", i->value());
}

TEST_F(BStringTests,
ValueReturnsCorrectValueAfterSet) {
	auto i = BString::create("test");
	i->setValue("other");

	EXPECT_EQ("other", i->value());
}

TEST_F(BStringTests,
LengthReturnsCorrectValue) {
	auto i = BString::create("test");

	EXPECT_EQ(4, i->length());
}

} // namespace tests
} // namespace bencoding

/**
* @file      BStringTests.cpp
* @copyright (c) 2014 by Petr Zemek (s3rvac@gmail.com) and contributors
* @license   BSD, see the @c LICENSE file for more details
* @brief     Tests for the BString class.
*/

#include <gtest/gtest.h>

#include "BString.h"

namespace bencoding {
namespace tests {

using namespace testing;

class BStringTests: public Test {};

TEST_F(BStringTests,
ValueReturnsCorrectValueAfterCreation) {
	auto s = BString::create("test");

	EXPECT_EQ("test", s->value());
}

TEST_F(BStringTests,
ValueReturnsCorrectValueAfterSet) {
	auto s = BString::create("test");
	s->setValue("other");

	EXPECT_EQ("other", s->value());
}

TEST_F(BStringTests,
LengthReturnsCorrectValue) {
	auto s = BString::create("test");

	EXPECT_EQ(4, s->length());
}

} // namespace tests
} // namespace bencoding

Fix the names of variables in the tests.


// Copyright 2015 http://switchdevice.com

#include "Arduino.cc"
#include "EEPROM.cc"
#include "Serial.cc"
#include "SoftwareSerial.cc"
#include "serialHelper.cc"
#include "Spark.cc"
#include "WiFi.cc"
#include "Wire.cc"
#include "SPI.cc"
#include "OneWire.cc"

#include "IRremote.cc"

// Copyright 2015 http://switchdevice.com

#include "Arduino.cc"
#include "Serial.cc"
#include "serialHelper.cc"
#include "OneWire.cc"
#include "SoftwareSerial.cc"

/* At WiTraC we don't make use of any of the following mocks. They are therefore
 *  commented out to save precious build time
 */
//#include "EEPROM.cc"
//#include "Spark.cc"
//#include "WiFi.cc"
//#include "Wire.cc"
//#include "SPI.cc"
//#include "IRremote.cc"

Comment out unused mocks to save build time


#include "rastertext.hpp"

bool RasterText::loadTexture()
{
    return true;
}

#include "rastertext.hpp"

// FIXME: unimplemented
Font::Font(Font const &f)
{ }

Font::~Font()
{ }

Font &Font::operator=(Font const &f)
{
    return *this;
}

bool RasterText::loadTexture()
{
    return true;
}

Add placeholder font code for Windows


/*************************************************************************
 *
 * REALM CONFIDENTIAL
 * __________________
 *
 *  [2011] - [2016] Realm Inc
 *  All Rights Reserved.
 *
 * NOTICE:  All information contained herein is, and remains
 * the property of Realm Incorporated and its suppliers,
 * if any.  The intellectual and technical concepts contained
 * herein are proprietary to Realm Incorporated
 * and its suppliers and may be covered by U.S. and Foreign Patents,
 * patents in process, and are protected by trade secret or copyright law.
 * Dissemination of this information or reproduction of this material
 * is strictly forbidden unless prior written permission is obtained
 * from Realm Incorporated.
 *
 **************************************************************************/

#include <realm/util/interprocess_mutex.hpp>

#ifdef REALM_ROBUST_MUTEX_EMULATION

using namespace realm::util;

std::map<File::UniqueID, std::weak_ptr<InterprocessMutex::LockInfo>> InterprocessMutex::s_info_map;
Mutex InterprocessMutex::s_mutex;

#endif

/*************************************************************************
 *
 * Copyright 2016 Realm 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 <realm/util/interprocess_mutex.hpp>

#ifdef REALM_ROBUST_MUTEX_EMULATION

using namespace realm::util;

std::map<File::UniqueID, std::weak_ptr<InterprocessMutex::LockInfo>> InterprocessMutex::s_info_map;
Mutex InterprocessMutex::s_mutex;

#endif

Update header in recently added file.


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


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

#include "xenia/base/platform_win.h"
#include "xenia/base/string.h"
#include "xenia/base/system.h"

namespace xe {

void LaunchWebBrowser(const std::string& url) {
  auto temp = xe::to_utf16(url);
  ShellExecuteW(nullptr, L"open", reinterpret_cast<LPCWSTR>(url.c_str()),
                nullptr, nullptr, SW_SHOWNORMAL);
}

void LaunchFileExplorer(const std::filesystem::path& url) {
  ShellExecuteW(nullptr, L"explore", url.c_str(), nullptr, nullptr,
                SW_SHOWNORMAL);
}

}  // namespace xe

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

#include "xenia/base/platform_win.h"
#include "xenia/base/string.h"
#include "xenia/base/system.h"

namespace xe {

void LaunchWebBrowser(const std::string& url) {
  auto temp = xe::to_utf16(url);
  ShellExecuteW(nullptr, L"open", reinterpret_cast<LPCWSTR>(temp.c_str()),
                nullptr, nullptr, SW_SHOWNORMAL);
}

void LaunchFileExplorer(const std::filesystem::path& url) {
  ShellExecuteW(nullptr, L"explore", url.c_str(), nullptr, nullptr,
                SW_SHOWNORMAL);
}

}  // namespace xe

Fix dangling pointer in LaunchWebBrowser.


// Copyright (c) 2015 Chaobin Zhang. All rights reserved.
// Use of this source code is governed by the BSD license that can be
// found in the LICENSE file.

#include "base/files/scoped_temp_dir.h"
#include "base/path_service.h"
#include "common/util.h"
#include "master/curl_helper.h"
#include "testing/gtest/include/gtest/gtest.h"

namespace master {

TEST(CurlHelperTest, GetWithMD5) {
  base::ScopedTempDir temp_dir;
  ASSERT_TRUE(temp_dir.CreateUniqueTempDir());

  base::FilePath readme_file_path;
  PathService::Get(base::DIR_SOURCE_ROOT, &readme_file_path);
  readme_file_path = readme_file_path.AppendASCII("README.md");

  base::FilePath file_path = temp_dir.path().AppendASCII("tmp_file");
  CurlHelper curl_helper;
  const std::string kReadmeURL =
      "https://raw.githubusercontent.com/zhchbin/DN/master/README.md";
  EXPECT_EQ(curl_helper.Get(kReadmeURL, file_path),
            common::GetMd5Digest(readme_file_path));
}

}  // namespace master

// Copyright (c) 2015 Chaobin Zhang. All rights reserved.
// Use of this source code is governed by the BSD license that can be
// found in the LICENSE file.

#include "base/files/scoped_temp_dir.h"
#include "base/path_service.h"
#include "common/util.h"
#include "master/curl_helper.h"
#include "testing/gtest/include/gtest/gtest.h"

namespace master {

TEST(CurlHelperTest, GetWithMD5) {
  base::ScopedTempDir temp_dir;
  ASSERT_TRUE(temp_dir.CreateUniqueTempDir());

  base::FilePath license_file_path;
  PathService::Get(base::DIR_SOURCE_ROOT, &license_file_path);
  license_file_path = license_file_path.AppendASCII("LICENSE");

  base::FilePath file_path = temp_dir.path().AppendASCII("tmp_file");
  CurlHelper curl_helper;
  const std::string klicenseURL =
      "https://raw.githubusercontent.com/zhchbin/DN/master/LICENSE";
  EXPECT_EQ(curl_helper.Get(klicenseURL, file_path),
            common::GetMd5Digest(license_file_path));
}

}  // namespace master

Use license file instead of readme.


/** @file
    @brief Implementation

    @date 2014

    @author
    Ryan Pavlik
    <ryan@sensics.com>
    <http://sensics.com>
*/

// Copyright 2014 Sensics, Inc.
//
// All rights reserved.
//
// (Final version intended to be licensed under
// the Apache License, Version 2.0)

// Internal Includes
#include <ogvr/PluginKit/DeviceToken.h>

// Library/third-party includes
// - none

// Standard includes
// - none

namespace ogvr {
	DeviceToken::DeviceToken(std::string const& name);
	DeviceToken::~DeviceToken() {}

	AsyncDeviceToken * DeviceToken::asAsyncDevice() {
		return NULL;
	}

	SyncDeviceToken * DeviceToken::asSyncDevice() {
		return NULL;
	}
}

/** @file
    @brief Implementation

    @date 2014

    @author
    Ryan Pavlik
    <ryan@sensics.com>
    <http://sensics.com>
*/

// Copyright 2014 Sensics, Inc.
//
// All rights reserved.
//
// (Final version intended to be licensed under
// the Apache License, Version 2.0)

// Internal Includes
#include <ogvr/PluginKit/DeviceToken.h>

// Library/third-party includes
// - none

// Standard includes
// - none

namespace ogvr {
DeviceToken::DeviceToken(std::string const &name) : m_name(name) {}
	DeviceToken::~DeviceToken() {}

	AsyncDeviceToken * DeviceToken::asAsyncDevice() {
		return NULL;
	}

	SyncDeviceToken * DeviceToken::asSyncDevice() {
		return NULL;
	}
}

Fix broken builds - stubs not stubby enough.


/***************************************************************************
 *  @file       main.cpp
 *  @author     Alan.W
 *  @date       02  Feb 2014
 *              13  Oct 2014
 *  @remark     This code is for the exercises from C++ Primer 5th Edition
 *  @note
 ***************************************************************************/
//!
//! Exercise 16.5:
//! Write a template version of the print function from § 6.2.4 (p. 217) that
//! takes a reference to an array and can handle arrays of any size and any
//! element type.
//!

#include <iostream>
#include <string>

/** @note
 *  1   any array is essentially a pointer, so the &ref here is a reference to pointer.
 *  2   size must be captured here to manage the loop.
 */
template<typename T, unsigned size>
void print(const T(&ref)[size])
{
    for (unsigned i = 0; i != size; ++i)
        std::cout << ref[i] << std::endl;
}

int main()
{
    std::string p[] = {"ssss","aaa","ssssss"};
    char c[] = {'a','b','c','d'};
    int  i[] = {1};
    print(i);
    print(c);
    print(p);

    std::cout << "\nexit normally\n";
    return 0;
}

/***************************************************************************
 *  @file       main.cpp
 *  @author     Alan.W
 *  @date       02  Feb 2014
 *              13  Oct 2014
 *  @remark     This code is for the exercises from C++ Primer 5th Edition
 *  @note
 ***************************************************************************/
//!
//! Exercise 16.5:
//! Write a template version of the print function from § 6.2.4 (p. 217) that
//! takes a reference to an array and can handle arrays of any size and any
//! element type.
//!

#include <iostream>
#include <string>

template<typename Arr>
void print(const Arr& a)
{
    for(const auto& elem : a)
        std::cout << elem << std::endl;
}

int main()
{
    std::string p[] = {"ssss","aaa","ssssss"};
    char c[] = {'a','b','c','d'};
    int  i[] = {1};
    print(i);
    print(c);
    print(p);

    std::cout << "\nexit normally\n";
    return 0;
}

Use range for instead of for


#define BOOST_TEST_ALTERNATIVE_INIT_API
#include <boost/test/unit_test.hpp>
#include "ReservoirBenchmark.h"
#include "TMGas.h"
using namespace boost::unit_test;

void performMeasurement() {
    int iterations = 1000;
    ReservoirFactory *rFactory = new TMGas::Reservoir::Factory(16);
    reservoirBenchmark(rFactory,iterations);
    delete rFactory;
}

bool init_function() {
    for (int k=0; k<15; ++k) {
        framework::master_test_suite().add(BOOST_TEST_CASE(&performMeasurement),0,60);
    }
    framework::master_test_suite().p_name.value = "TMGasBenchmark";
    return true;
}

int main( int argc, char* argv[] )
{
    return ::boost::unit_test::unit_test_main( &init_function, argc, argv );
}

#define BOOST_TEST_ALTERNATIVE_INIT_API
#include <boost/test/unit_test.hpp>
#include "ReservoirBenchmark.h"
#include "TMGas.h"
using namespace boost::unit_test;

void performMeasurement() {
    int iterations = 100;
    ReservoirFactory *rFactory = new TMGas::Reservoir::Factory(16);
    reservoirBenchmark(rFactory,iterations);
    delete rFactory;
}

bool init_function() {
    for (int k=0; k<15; ++k) {
        framework::master_test_suite().add(BOOST_TEST_CASE(&performMeasurement),0,60);
    }
    framework::master_test_suite().p_name.value = "TMGasBenchmark";
    return true;
}

int main( int argc, char* argv[] )
{
    return ::boost::unit_test::unit_test_main( &init_function, argc, argv );
}

Reduce the size of the TMGas measurement by an order of magnitude.


#include "Renderer.hpp"
#include "../OpenGL/OpenGLRenderer.hpp"
#include "../Vulkan/VulkanRenderer.hpp"

Renderer::~Renderer() {

}

Renderer* Renderer::makeRenderer(BACKEND backend, Window & window){
    // Create and return backend.
    if(backend == BACKEND::OpenGL)
        return new OpenGLRenderer(window);

    else if(backend == BACKEND::Vulkan)
        return new VulkanRenderer(window);

    return nullptr;
}

void Renderer::render() {

}

Remove implementation of pure virtual function.


#include <QDesktopWidget>
#include "WindowMaximize.h"
#include "WebPage.h"
#include "WebPageManager.h"

WindowMaximize::WindowMaximize(WebPageManager *manager, QStringList &arguments, QObject *parent) : WindowCommand(manager, arguments, parent) {
}

void WindowMaximize::windowFound(WebPage *page) {
  QDesktopWidget *desktop = QApplication::desktop();
  QRect area = desktop->availableGeometry();
  page->resize(area.width(), area.height());
  finish(true);
}

Make sure to include QDesktopWidget


/*
 * PartitionReader.cpp
 *
 *  Created on: 15.02.2013
 *      Author: Christian Staudt (christian.staudt@kit.edu)
 */

#include "PartitionReader.h"

namespace NetworKit {

Partition PartitionReader::read(std::string path) {

	std::ifstream file(path);

	// check if file readable
	if (!file) {
		throw std::runtime_error("invalid clustering file");
	}

	std::vector<index> temp;

	// push all cluster ids into vector in order of appearance
	std::string line;
	while(std::getline(file, line)) {
		index c = std::atoi(line.c_str());
		temp.push_back(c);
	}

	count n = temp.size();
	Partition zeta(n);

	#pragma omp parallel for
	for (node u = 0; u < n; ++u) {
		zeta[u] = temp[u];
	}

	return zeta;
}

} /* namespace NetworKit */

/*
 * PartitionReader.cpp
 *
 *  Created on: 15.02.2013
 *      Author: Christian Staudt (christian.staudt@kit.edu)
 */

#include "PartitionReader.h"

namespace NetworKit {

Partition PartitionReader::read(std::string path) {

	std::ifstream file(path);

	// check if file readable
	if (!file) {
		throw std::runtime_error("invalid clustering file");
	}

	Partition zeta(0);

	std::string line;
	index omega = 0;
	while(std::getline(file, line)) {
		index c = std::atoi(line.c_str());
		// extend the partition by one entry and store the cluster id
		zeta[zeta.extend()] = c;
		omega = std::max(c, omega);
	}

	zeta.setUpperBound(omega+1);

	return zeta;
}

} /* namespace NetworKit */

Simplify and fix the partition reader


/*
 * Qumulus UML editor
 * Author: Frank Erens
 * Author: Randy Thiemann
 *
 */

#include "PackageShape.h"
#include <QtGui/QBrush>

QUML_BEGIN_NAMESPACE_UD

PackageShape::PackageShape(QuUK::Element* e,
        DiagramElement* p) :
        SelectableShape(e, p),
        mTabItem(new QGraphicsRectItem(0, 0, 30, 10, this)),
        mBodyItem(new QGraphicsRectItem(0, 10, 100, 50, this)) {
    mTabItem->setBrush(QBrush(Qt::white));
    mBodyItem->setBrush(QBrush(Qt::white));
    addToGroup(mTabItem);
    addToGroup(mBodyItem);
}

PackageShape::PackageShape(const PackageShape& c) :
        SelectableShape(c) {

}

void PackageShape::resize(double w, double h) {
     if(minimumSize().isValid()) {
        w = std::max(w, minimumSize().width());
        h = std::max(h, minimumSize().height());
    }

    mBodyItem->setRect(0, 10, w, h - 10);

    setSize({w, h});
}

QUML_END_NAMESPACE_UD

/*
 * Qumulus UML editor
 * Author: Frank Erens
 * Author: Randy Thiemann
 *
 */

#include "PackageShape.h"
#include <QtGui/QBrush>

QUML_BEGIN_NAMESPACE_UD

PackageShape::PackageShape(QuUK::Element* e,
        DiagramElement* p) :
        SelectableShape(e, p),
        mTabItem(new QGraphicsRectItem(0, 0, 30, 10, this)),
        mBodyItem(new QGraphicsRectItem(0, 10, 100, 50, this)) {
    constexpr int kPackageZOrdering = -2;
    mTabItem->setBrush(QBrush(Qt::white));
    mBodyItem->setBrush(QBrush(Qt::white));
    addToGroup(mTabItem);
    addToGroup(mBodyItem);
    setZValue(kPackageZOrdering);
}

PackageShape::PackageShape(const PackageShape& c) :
        SelectableShape(c) {}

void PackageShape::resize(double w, double h) {
     if(minimumSize().isValid()) {
        w = std::max(w, minimumSize().width());
        h = std::max(h, minimumSize().height());
    }

    mBodyItem->setRect(0, 10, w, h - 10);

    setSize({w, h});
}

QUML_END_NAMESPACE_UD

Change default Z-order for packages.


#include "ofMain.h"
#include "ofApp.h"

//========================================================================
int main( ){
    ofGLWindowSettings settings;
    settings.setGLVersion(3, 2); // Using programmable renderer. Comment out this line to use the 'standard' GL renderer.
    settings.width = 1024;
    settings.height = 768;
    ofCreateWindow(settings);
    ofRunApp(new ofApp());
}

#include "ofMain.h"
#include "ofApp.h"

//========================================================================
int main( ){
    ofWindowSettings winSettings;
    winSettings.setSize(1024, 768);
    ofGLWindowSettings glSettings(winSettings);
    glSettings.setGLVersion(3, 2); // Using programmable renderer. Comment out this line to use the 'standard' GL renderer.
    ofCreateWindow(glSettings);
    ofRunApp(new ofApp());
}

Update example for openFrameworks 0.11.0


/* Copyright (c) 2006, NIF File Format Library and Tools
All rights reserved.  Please see niflib.h for licence. */

#include "SkinPartition.h"
using namespace Niflib;

//Constructor
SkinPartition::SkinPartition() : numVertices((ushort)0), numTriangles((ushort)0), numBones((ushort)0), numStrips((ushort)0), numWeightsPerVertex((ushort)0), hasVertexMap(false), hasVertexWeights(false), hasStrips(false), hasBoneIndices(false) {};

//Destructor
SkinPartition::~SkinPartition() {};

// needs to be moved elsewhere but this will work for now
ushort SkinPartition::CalcNumTriangles() const {
   ushort size = 0;
   if (stripLengths.empty()) {
      size = (ushort)triangles.size();
   } else {
      for (size_t i=0; i<stripLengths.size(); ++i)
         size += (ushort)stripLengths[i];
      size -= 2;
   }
   return size;
}

/* Copyright (c) 2006, NIF File Format Library and Tools
All rights reserved.  Please see niflib.h for licence. */

#include "SkinPartition.h"
using namespace Niflib;

//Constructor
SkinPartition::SkinPartition() : numVertices((ushort)0), numTriangles((ushort)0), numBones((ushort)0), numStrips((ushort)0), numWeightsPerVertex((ushort)0), hasVertexMap(false), hasVertexWeights(false), hasStrips(false), hasBoneIndices(false) {};

//Destructor
SkinPartition::~SkinPartition() {};

// needs to be moved elsewhere but this will work for now
ushort SkinPartition::CalcNumTriangles() const {
   ushort size = 0;
   if (stripLengths.empty()) {
      size = (ushort)triangles.size();
   } else {
      for (size_t i=0; i<stripLengths.size(); ++i)
         size += ((ushort)stripLengths[i] - 2);
   }
   return size;
}

Fix length calc based on m444x's suggestion.


#include "socketmanager.h"

std::shared_ptr<Socket> SocketManager::getSocket(const std::string& socketType) {
	void* sockFile = dlopen(("sockets/" + socketType + ".so").c_str(), RTLD_NOW);
	if (sockFile == nullptr)
		throw SocketLoadFailed (dlerror());
	void* spawnFunc = dlsym(sockFile, "spawn");
	if (spawnFunc == nullptr) {
		const char* loadError = dlerror();
		dlclose(sockFile);
		if (loadError)
			throw SocketLoadFailed (loadError);
		throw SocketLoadFailed ("The spawn symbol has been set to null, but it must be a valid function.");
	}
	Socket*(*spawnCallFunc)() = static_cast<Socket*(*)()> (spawnFunc);
	std::shared_ptr<Socket> newSocket (spawnCallFunc(), std::bind(&SocketManager::removeSocket, this, socketType, sockFile, std::placeholders::_1));
	if (sockAPIVersions.find(newSocket->apiVersion()) == sockAPIVersions.end())
		throw SocketAPIMismatch ();
	return newSocket;
}

void SocketManager::removeSocket(const std::string& socketType, void* sockFile, Socket* deletingSocket) {
	delete deletingSocket;
	dlclose(sockFile);
	LogManager* logger = LogManager::getHandle();
	logger->log(LOG_DEBUG, "socket-request", "A " + socketType + " socket has been unloaded.");
}

#include "socketmanager.h"

std::shared_ptr<Socket> SocketManager::getSocket(const std::string& socketType) {
	void* sockFile = dlopen(("sockets/" + socketType + ".so").c_str(), RTLD_NOW);
	if (sockFile == nullptr)
		throw SocketLoadFailed (dlerror());
	void* spawnFunc = dlsym(sockFile, "spawn");
	if (spawnFunc == nullptr) {
		const char* loadError = dlerror();
		dlclose(sockFile);
		if (loadError)
			throw SocketLoadFailed (loadError);
		throw SocketLoadFailed ("The spawn symbol has been set to null, but it must be a valid function.");
	}
	Socket*(*spawnCallFunc)() = (Socket*(*)()) spawnFunc;
	std::shared_ptr<Socket> newSocket (spawnCallFunc(), std::bind(&SocketManager::removeSocket, this, socketType, sockFile, std::placeholders::_1));
	if (sockAPIVersions.find(newSocket->apiVersion()) == sockAPIVersions.end())
		throw SocketAPIMismatch ();
	return newSocket;
}

void SocketManager::removeSocket(const std::string& socketType, void* sockFile, Socket* deletingSocket) {
	delete deletingSocket;
	dlclose(sockFile);
	LogManager* logger = LogManager::getHandle();
	logger->log(LOG_DEBUG, "socket-request", "A " + socketType + " socket has been unloaded.");
}

Fix socket manager loader to use a C-style cast on the function pointer


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

using namespace Halide;

int main(int argc, char **argv) {
    Var x, y;
    Var xo, xi, yo, yi;

    Func f, g;

    printf("Defining function...\n");

    f(x, y) = cast<float>(x);
    g(x, y) = f(x+1, y) + f(x-1, y);

    Target target = get_jit_target_from_environment();
    if (target.has_gpu_feature()) {
        Var xi, yi;
        g.gpu_tile(x, y, 8, 8, GPU_DEFAULT);
        f.compute_at(g, Var("blockidx")).gpu_threads(x, y, GPU_DEFAULT);
    }

    printf("Realizing function...\n");

    Image<float> im = g.realize(32, 32, target);

    for (int i = 0; i < 32; i++) {
        for (int j = 0; j < 32; j++) {
            if (im(i,j) != 2*i) {
                printf("im[%d, %d] = %f\n", i, j, im(i,j));
                return -1;
            }
        }
    }

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

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

using namespace Halide;

int main(int argc, char **argv) {
    Var x, y;
    Var xo, xi, yo, yi;

    Func f, g;

    printf("Defining function...\n");

    f(x, y) = cast<float>(x);
    g(x, y) = f(x+1, y) + f(x-1, y);

    Target target = get_jit_target_from_environment();
    // shared memory not currently working in OpenCL
    if (target.features & Target::CUDA) {
        Var xi, yi;
        g.gpu_tile(x, y, 8, 8, GPU_CUDA);
        f.compute_at(g, Var("blockidx")).gpu_threads(x, y, GPU_CUDA);
    }

    printf("Realizing function...\n");

    Image<float> im = g.realize(32, 32, target);

    for (int i = 0; i < 32; i++) {
        for (int j = 0; j < 32; j++) {
            if (im(i,j) != 2*i) {
                printf("im[%d, %d] = %f\n", i, j, im(i,j));
                return -1;
            }
        }
    }

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

Disable shared memory test for OpenCL until bugginess is resolved.


/*
 * Copyright (c) 2007 Digital Bazaar, Inc.  All rights reserved.
 */

#include <iostream>

#include "db/io/OStreamOutputStream.h"

using namespace std;
using namespace db::io;
using namespace db::rt;

OStreamOutputStream* OStreamOutputStream::mStdoutStream =
   new OStreamOutputStream(&cout);

OStreamOutputStream::OStreamOutputStream(ostream* stream)
{
   // store ostream
   mStream = stream;
}

OStreamOutputStream::~OStreamOutputStream()
{
}

bool OStreamOutputStream::write(const char* b, int length)
{
   bool rval = false;

   // do write
   mStream->write(b, length);

   // see if a failure has occurred
   if(mStream->fail())
   {
      Exception::setLast(new IOException("Could not write to ostream!"));
   }
   else
   {
      rval = true;
   }

   return rval;
}

OStreamOutputStream* OStreamOutputStream::getStdoutStream()
{
   return sStdoutStream;
}

/*
 * Copyright (c) 2007 Digital Bazaar, Inc.  All rights reserved.
 */

#include <iostream>

#include "db/io/OStreamOutputStream.h"

using namespace std;
using namespace db::io;
using namespace db::rt;

OStreamOutputStream* OStreamOutputStream::sStdoutStream =
   new OStreamOutputStream(&cout);

OStreamOutputStream::OStreamOutputStream(ostream* stream)
{
   // store ostream
   mStream = stream;
}

OStreamOutputStream::~OStreamOutputStream()
{
}

bool OStreamOutputStream::write(const char* b, int length)
{
   bool rval = false;

   // do write
   mStream->write(b, length);

   // see if a failure has occurred
   if(mStream->fail())
   {
      Exception::setLast(new IOException("Could not write to ostream!"));
   }
   else
   {
      rval = true;
   }

   return rval;
}

OStreamOutputStream* OStreamOutputStream::getStdoutStream()
{
   return sStdoutStream;
}

Use s prefix for static class vars


#include <esp_log.h>
#include <FreeRTOS.h>
#include <string>
#include <Task.h>
#include <I2C.h>

#include "sdkconfig.h"

#define SDA_PIN 25
#define SCL_PIN 26

//static char tag[] = "task_cpp_utils";

class I2CScanner: public Task {
	void run(void *data) override {
		I2C i2c;
		i2c.init((gpio_num_t)SDA_PIN, (gpio_num_t)SCL_PIN);
		i2c.scan();
	} // End run
};

static I2CScanner i2cScanner = I2CScanner();

void task_i2c_scanner(void *ignore) {
	i2cScanner.start();
	FreeRTOS::deleteTask();
}

#include <esp_log.h>
#include <FreeRTOS.h>
#include <string>
#include <Task.h>
#include <I2C.h>

#include "sdkconfig.h"

#define DEVICE_ADDRESS 0
#define SDA_PIN 25
#define SCL_PIN 26

//static char tag[] = "task_cpp_utils";

class I2CScanner: public Task {
	void run(void *data) override {
		I2C i2c;
		i2c.init((uint8_t)DEVICE_ADDRESS, (gpio_num_t)SDA_PIN, (gpio_num_t)SCL_PIN);
		i2c.scan();
	} // End run
};

static I2CScanner i2cScanner = I2CScanner();

void task_i2c_scanner(void *ignore) {
	i2cScanner.start();
	FreeRTOS::deleteTask();
}

Fix params passed to i2c.init() to include DEVICE_ADDRESS in the first position. Otherwise SDA becomes SCL_PIN and SCL becomes Default.


#include "phonevalidator.h"

PhoneValidator::PhoneValidator(QObject *parent) :
    QValidator(parent)
{
}

QValidator::State PhoneValidator::validate(QString &input, int &pos) const
{
    //DDD
    QRegExp ddd("(\\d{2})+");
    if (ddd.exactMatch(input))
    {
        input.insert(input.length(), ") ");
        input.insert(0, "(");
        pos = input.length();
    }

    //Slash
    QRegExp slash("\\(\\d{2}\\)\\s*\\d{4}");
    if (slash.exactMatch(input))
    {
        input.insert(input.length(), "-");
        pos = input.length();
    }

    //Separator
    QRegExp sep("[\\(]{0,1}[\\d]\{0,2}[\\)]{0,1}\\s*\\d*[\\-]{0,1}\\d*");

    if (sep.exactMatch(input))
        return QValidator::Acceptable;

    return QValidator::Invalid;
}

bool PhoneValidator::isValid(QString str)
{
    QRegExp sep("[\\(]{0,1}[\\d]\{0,2}[\\)]{0,1}\\s*\\d*[\\-]{0,1}\\d*");
    return sep.exactMatch(str);
}

#include "phonevalidator.h"

PhoneValidator::PhoneValidator(QObject *parent) :
    QValidator(parent)
{
}

QValidator::State PhoneValidator::validate(QString &input, int &pos) const
{
    //DDD
    QRegExp ddd("(\\d{2})+");
    if (ddd.exactMatch(input))
    {
        input.insert(input.length(), ") ");
        input.insert(0, "(");
        pos = input.length();
    }

    //Slash
    QRegExp slash("\\(\\d{2}\\)\\s{0,1}\\d{5}");
    if (slash.exactMatch(input))
    {
        input.insert(input.length()-1, "-");
        pos = input.length();
    }

    //Separator
    QRegExp sep("[\\(]{0,1}[\\d]\{0,2}[\\)]{0,1}\\s{0,1}\\d*-{0,1}\\d*");

    if (sep.exactMatch(input))
        return QValidator::Acceptable;

    return QValidator::Invalid;
}

bool PhoneValidator::isValid(QString str)
{
    QRegExp sep("[\\(]{0,1}[\\d]\{0,2}[\\)]{0,1}\\s*\\d*[\\-]{0,1}\\d*");
    return sep.exactMatch(str);
}

Fix bug when deletig phone


/* Test program to test the thread callbacks
*/

#include <iostream>
#include "SDL.hh"
using namespace RAGE;

Logger testlog("testThread");

class ObjectWithThreadCall
{
	public:

	int threadcall(void* args)
	{
		testlog << nl << " --- Thread " << SDL::getCurrentThreadID() << "called --- " << std::endl;
		return 0;
	}

};

int main(int argc, char *argv[])
{
	testlog.enableFileLog("testThread.log");
	testlog << nl<<"SDL init...";

	SDL::App::getInstance();

	testlog << nl<<"Creating instance";
	ObjectWithThreadCall obj;

	testlog << nl<<"Creating instance timer";
	SDL::Thread<ObjectWithThreadCall> thread;

	thread.setThreadCall(&obj,&ObjectWithThreadCall::threadcall,(void*)NULL);

	thread.run();

	testlog << nl<<"Waiting for thread to finish" << std::endl;
	thread.wait();

	return 0;
}

/* Test program to test the thread callbacks
*/

#include <iostream>
#include "SDL.hh"
using namespace RAGE;

Logger testlog("testThread");

class ObjectWithThreadCall
{
	public:
	ObjectWithThreadCall() {}

	int threadcall(void* args)
	{
		testlog << nl << " --- Thread " << SDL::getCurrentThreadID() << "called. Counting from 0 to 20000 --- " << std::endl;
		for (int i = 0; i < 20000; i++)
		{
			testlog << nl << "Iteration N" << i << std::endl;
		}
		return 0;
	}

};

int main(int argc, char *argv[])
{
	testlog.enableFileLog("testThread.log");
	testlog << nl<<"SDL init...";

	SDL::App::getInstance();

	testlog << nl<<"Creating instance";
	ObjectWithThreadCall * obj = new ObjectWithThreadCall();

	testlog << nl<<"Creating instance timer";
	SDL::Thread<ObjectWithThreadCall>* thread = new SDL::Thread<ObjectWithThreadCall>();

	thread->setThreadCall(obj,&ObjectWithThreadCall::threadcall,(void*)NULL);

	thread->run();

	testlog << nl<<"Waiting for thread" << std::endl;
	thread->wait();
	SDL::Delay(3000);
	testlog << nl <<"Killing thread: After That No Iteration Should Be Present" << std::endl;
	thread->kill();
	SDL::Delay(3000);
	return 0;
}

Update Test Thread to show that wait() and kill() are not working as expected


#include "utils/progressBar.h"
#include <iostream>
#include <glog/logging.h>

using namespace std;

const std::string ProgressBar::BEGINNING = "[";
const std::string ProgressBar::END = "]";
const std::string ProgressBar::FILLER = "-";
const size_t ProgressBar::LENGTH = 50;

ProgressBar::ProgressBar()
    : mProgress(0)
{}

void ProgressBar::setProgress(float progress) {
    mProgress = progress;
}

void ProgressBar::print() const {
    cout << "\r" << BEGINNING;

    const int amountOfFiller = static_cast<int>(mProgress * LENGTH);
    for (size_t i = 0; i < amountOfFiller; i++) {
        cout << FILLER;
    }

    LOG_IF(ERROR, amountOfFiller > LENGTH) << "Bad size";
    const int remaningSpace = LENGTH - amountOfFiller;
    for (size_t i = 0; i < remaningSpace; i++) {
        cout << " ";
    }

    cout << END
        << static_cast<int>(mProgress * 100) << "%"
        << flush;
}

#include "utils/progressBar.h"
#include <iostream>
#include <cmath>
#include <glog/logging.h>

using namespace std;

const std::string ProgressBar::BEGINNING = "[";
const std::string ProgressBar::END = "]";
const std::string ProgressBar::FILLER = "-";
const size_t ProgressBar::LENGTH = 50;

ProgressBar::ProgressBar()
    : mProgress(0)
{}

void ProgressBar::setProgress(float progress) {
    mProgress = progress;
}

void ProgressBar::print() const {
    cout << "\r" << BEGINNING;

    const int amountOfFiller = static_cast<int>(mProgress * LENGTH);
    for (size_t i = 0; i < amountOfFiller; i++) {
        cout << FILLER;
    }

    LOG_IF(ERROR, amountOfFiller > LENGTH) << "Bad size";
    const int remaningSpace = LENGTH - amountOfFiller;
    for (size_t i = 0; i < remaningSpace; i++) {
        cout << " ";
    }

    cout << END
        << round(mProgress * 100) << "%"
        << flush;
}

Fix progress bar rounding issue


#include "framework/applicationcontext.hh"
#include "framework/clientcode.hh"

using Framework::ApplicationContext;
using Framework::ClientCode;
using Framework::LoadClientCode;

using System::thread;

int applicationMain()
{
    ClientCode clientCode = LoadClientCode();

    ApplicationContext applicationContext;

    clientCode.ApplicationThreadEntry(&applicationContext);

    return 0;
}

#include "framework/applicationcontext.hh"
#include "framework/clientcode.hh"

using Framework::ApplicationContext;
using Framework::ClientCode;
using Framework::LoadClientCode;

int applicationMain()
{
    ClientCode clientCode = LoadClientCode();

    ApplicationContext applicationContext;

    clientCode.ApplicationThreadEntry(&applicationContext);

    return 0;
}

Remove unused reference to threads


#include <QActiveResource.h>
#include <QDebug>

int main()
{
    qDebug() << getenv("AR_BASE");
    QActiveResource::Resource resource(QUrl(getenv("AR_BASE")), getenv("AR_RESOURCE"));

    const QString field = getenv("AR_FIELD");

    for(int i = 0; i < 100; i++)
    {
        qDebug() << i;
        foreach(QActiveResource::Record record, resource.find())
        {
            qDebug() << record[field].toString();
        }
    }

    return 0;
}

#include <QActiveResource.h>
#include <QDebug>

int main()
{
    Q_ASSERT(getenv("AR_BASE") && getenv("AR_RESOURCE") && getenv("AR_FIELD"));

    qDebug() << getenv("AR_BASE");
    QActiveResource::Resource resource(QUrl(getenv("AR_BASE")), getenv("AR_RESOURCE"));

    const QString field = getenv("AR_FIELD");

    for(int i = 0; i < 100; i++)
    {
        qDebug() << i;
        foreach(QActiveResource::Record record, resource.find())
        {
            qDebug() << record[field].toString();
        }
    }

    return 0;
}

Make sure the env variables are set


#include "response_stream.h"

void rs::httpserver::ResponseStream::Flush() {
    socket_->Flush();
}

int rs::httpserver::ResponseStream::Write(const Stream::byte* buffer, int offset, int count) {
    auto written = 0;

    while (written < count) {
        auto sentBytes = socket_->Send(buffer + written, count - written);
        if (sentBytes <= 0) {
            throw SocketWriteException();
        }

        written += sentBytes;
        position_ += sentBytes;
        length_ += sentBytes;
    }

    return written;
}

#include "response_stream.h"

void rs::httpserver::ResponseStream::Flush() {
    socket_->Flush();
}

int rs::httpserver::ResponseStream::Write(const Stream::byte* buffer, int offset, int count) {
    auto written = 0;

    while (written < count) {
        auto sentBytes = socket_->Send(buffer + offset + written, count - written);
        if (sentBytes <= 0) {
            throw SocketWriteException();
        }

        written += sentBytes;
        position_ += sentBytes;
        length_ += sentBytes;
    }

    return written;
}

Fix response stream writes where we have a buffer offset


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

#include "SkColorMatrixFilter.h"

static SkScalar byte_to_scale(U8CPU byte) {
    if (0xFF == byte) {
        // want to get this exact
        return 1;
    } else {
        return byte * 0.00392156862745f;
    }
}

SkColorFilter* SkColorMatrixFilter::CreateLightingFilter(SkColor mul, SkColor add) {
    SkColorMatrix matrix;
    matrix.setScale(byte_to_scale(SkColorGetR(mul)),
                    byte_to_scale(SkColorGetG(mul)),
                    byte_to_scale(SkColorGetB(mul)),
                    1);
    matrix.postTranslate(SkIntToScalar(SkColorGetR(add)),
                         SkIntToScalar(SkColorGetG(add)),
                         SkIntToScalar(SkColorGetB(add)),
                         0);
    return SkColorMatrixFilter::Create(matrix);
}

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

#include "SkColorMatrixFilter.h"

static SkScalar byte_to_scale(U8CPU byte) {
    if (0xFF == byte) {
        // want to get this exact
        return 1;
    } else {
        return byte * 0.00392156862745f;
    }
}

SkColorFilter* SkColorMatrixFilter::CreateLightingFilter(SkColor mul, SkColor add) {
    if (0 == add) {
        return SkColorFilter::CreateModeFilter(mul | SK_ColorBLACK,
                                               SkXfermode::Mode::kModulate_Mode);
    }
    SkColorMatrix matrix;
    matrix.setScale(byte_to_scale(SkColorGetR(mul)),
                    byte_to_scale(SkColorGetG(mul)),
                    byte_to_scale(SkColorGetB(mul)),
                    1);
    matrix.postTranslate(SkIntToScalar(SkColorGetR(add)),
                         SkIntToScalar(SkColorGetG(add)),
                         SkIntToScalar(SkColorGetB(add)),
                         0);
    return SkColorMatrixFilter::Create(matrix);
}

Simplify LightingFilter in add-free case am: 0698300cc5 am: a184d5e49d am: 7e02270397


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

#include "base/thread_local.h"

#include <pthread.h>

#include "base/logging.h"

namespace base {

// static
void ThreadLocalPlatform::AllocateSlot(SlotType& slot) {
  int error = pthread_key_create(&slot, NULL);
  CHECK(error == 0);
}

// static
void ThreadLocalPlatform::FreeSlot(SlotType& slot) {
  int error = pthread_key_delete(slot);
  DCHECK(error == 0);
}

// static
void* ThreadLocalPlatform::GetValueFromSlot(SlotType& slot) {
  return pthread_getspecific(slot_);
}

// static
void ThreadLocalPlatform::SetValueInSlot(SlotType& slot, void* value) {
  int error = pthread_setspecific(slot, value);
  CHECK(error == 0);
}

}  // namespace base

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

#include "base/thread_local.h"

#include <pthread.h>

#include "base/logging.h"

namespace base {

// static
void ThreadLocalPlatform::AllocateSlot(SlotType& slot) {
  int error = pthread_key_create(&slot, NULL);
  CHECK(error == 0);
}

// static
void ThreadLocalPlatform::FreeSlot(SlotType& slot) {
  int error = pthread_key_delete(slot);
  DCHECK(error == 0);
}

// static
void* ThreadLocalPlatform::GetValueFromSlot(SlotType& slot) {
  return pthread_getspecific(slot);
}

// static
void ThreadLocalPlatform::SetValueInSlot(SlotType& slot, void* value) {
  int error = pthread_setspecific(slot, value);
  CHECK(error == 0);
}

}  // namespace base

Fix a typo that broke the posix build.


//
//  application_context.cpp
//  usbtest
//
//  Created by Kristoffer Andersen on 13/07/15.
//  Copyright (c) 2015 Monolit ApS. All rights reserved.
//

#include "application_context.h"
#include <display_painter.h>

extern "C" {
#include <project.h>
}

using namespace mono;

ApplicationContext ApplicationContext::singleton;
IApplicationContext *IApplicationContext::Instance = NULL;

ApplicationContext::ApplicationContext() : dispController()
{
    PWM_Start();
    PWM_WriteCompare2(0);

    IApplicationContext::Instance = this;
    displayController = &dispController;

}

int ApplicationContext::exec()
{

}

void ApplicationContext::setMonoApplication(mono::IApplication *monoApp)
{
    this->application = monoApp;
    mono::IApplicationContext::Instance->displayController->init();

    monoApp->monoWakeFromReset();
}

//
//  application_context.cpp
//  usbtest
//
//  Created by Kristoffer Andersen on 13/07/15.
//  Copyright (c) 2015 Monolit ApS. All rights reserved.
//

#include "application_context.h"
#include "application_controller_interface.h"
#include <display_painter.h>

extern "C" {
#include <project.h>
}

using namespace mono;

ApplicationContext ApplicationContext::singleton;
IApplicationContext *IApplicationContext::Instance = NULL;

ApplicationContext::ApplicationContext() : dispController()
{
    PWM_Start();
    PWM_WriteCompare2(0);

    IApplicationContext::Instance = this;
    displayController = &dispController;
}

int ApplicationContext::exec()
{
    return 0;
}

void ApplicationContext::setMonoApplication(mono::IApplication *monoApp)
{
    this->application = monoApp;
    mono::IApplicationContext::Instance->displayController->init();

    monoApp->monoWakeFromReset();
}

Fix compile error in GCC 5.


#include "stdafx.h"
#include "CppUnitTest.h"

#include "datastore.h"

using Assert = Microsoft::VisualStudio::CppUnitTestFramework::Assert;
using DataStore = You::DataStore::DataStore;

namespace YouDataStoreTests {
TEST_CLASS(DataStoreApiTest) {
public:
	TEST_METHOD(DataStore_Post_Basic_Test) {
		You::DataStore::DataStore sut;
		bool result = sut.post(0, DataStore::STask());
		Assert::IsTrue(result);
	}

	TEST_METHOD(DataStore_Post_DuplicateId_Test) {
		You::DataStore::DataStore sut;
		sut.post(0, DataStore::STask());
		bool result = sut.post(0, DataStore::STask());
		Assert::IsFalse(result);
	}
};
}  // namespace YouDataStoreTests

#include "stdafx.h"
#include "CppUnitTest.h"

#include "datastore.h"

using Assert = Microsoft::VisualStudio::CppUnitTestFramework::Assert;
using DataStore = You::DataStore::DataStore;

namespace YouDataStoreTests {
TEST_CLASS(DataStoreApiTest) {
public:
	DataStore sut;

	TEST_METHOD(DataStore_Post_Basic_Test) {
		bool result = sut.post(0, DataStore::STask());
		Assert::IsTrue(result);
	}

	TEST_METHOD(DataStore_Post_DuplicateId_Test) {
		sut.post(0, DataStore::STask());
		bool result = sut.post(0, DataStore::STask());
		Assert::IsFalse(result);
	}

	TEST_METHOD(DataStore_Put_Basic_Test) {
		sut.post(0, DataStore::STask());
		bool result = sut.put(0, DataStore::STask());
		Assert::IsTrue(result);
	}
};
}  // namespace YouDataStoreTests

Add test for put method


#include "settingsview.h"
#include "ui_settings.h"

SettingsView::SettingsView(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::SettingsView)
{
    ui->setupUi(this);
    QSettings settings;
    int syncingPreference = settings.value("syncingPreference", QVariant(static_cast<int>(SyncOptions::MANUAL_ONLY))).toInt();

    QStringList syncingOptions({
                                   "Manual Only",  // SyncOptions::MANUAL_ONLY
                                   "On Startup (Always)",  // SyncOptions::ON_STARTUP
                                   "On Startup (WiFi)",  // SyncOptions::WIFI
                               });
    ui->comboBox->addItems(syncingOptions);
    ui->comboBox->setCurrentIndex(syncingPreference);
}

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

void SettingsView::on_pushButton_2_clicked()
{
    emit backButtonClicked();
}

void SettingsView::on_pushButton_clicked()
{
    emit syncButtonClicked();
}

void SettingsView::on_comboBox_currentIndexChanged(int index)
{
    QSettings settings;
    settings.setValue("syncingPreference", index);
    settings.sync();
}

void SettingsView::updateLastSync()
{
    QSettings settings;
    ui->label->setText(settings.value("lastUpdate").toString());
}

#include "settingsview.h"
#include "ui_settings.h"

SettingsView::SettingsView(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::SettingsView)
{
    ui->setupUi(this);
    QSettings settings;
    int syncingPreference = settings.value("syncingPreference", QVariant(static_cast<int>(SyncOptions::MANUAL_ONLY))).toInt();

    QStringList syncingOptions({
                                   "Manual Only",  // SyncOptions::MANUAL_ONLY
                                   "On Startup (Always)",  // SyncOptions::ON_STARTUP
                                   "On Startup (WiFi)",  // SyncOptions::WIFI
                               });
    ui->comboBox->addItems(syncingOptions);
    ui->comboBox->setItemData(2, QVariant(0), Qt::UserRole - 1);  // Horrible hack according to peppe
    ui->comboBox->setCurrentIndex(syncingPreference);
}

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

void SettingsView::on_pushButton_2_clicked()
{
    emit backButtonClicked();
}

void SettingsView::on_pushButton_clicked()
{
    emit syncButtonClicked();
}

void SettingsView::on_comboBox_currentIndexChanged(int index)
{
    QSettings settings;
    settings.setValue("syncingPreference", index);
    settings.sync();
}

void SettingsView::updateLastSync()
{
    QSettings settings;
    ui->label->setText(settings.value("lastUpdate").toString());
}

Disable wireless entry in combobox for now


// RUN: clang-cc -emit-llvm-only -verify %s
// PR5454

class X {static void * operator new(unsigned long size) throw(); X(int); };
int a(), b();
void b(int x)
{
  new X(x ? a() : b());
}

// RUN: clang-cc -emit-llvm-only -verify %s
// PR5454
#include <stddef.h>

class X {static void * operator new(size_t size) throw(); X(int); };
int a(), b();
void b(int x)
{
  new X(x ? a() : b());
}

Make test more platform independent.


#include <cstdlib>
#include <iostream>

int main() {
#ifdef __APPLE__
  const char* name = "DYLD_LIBRARY_PATH";
#else
  const char* name = "LD_LIBRARY_PATH";
#endif

  const char* cetLDPathValue = getenv("CETD_LIBRARY_PATH");
  int res = setenv("DYLD_LIBRARY_PATH", cetLDPathValue, 1);

  const char* localLDPathValue = getenv(name);

  if(strcmp(localLDPathValue,cetLDPathValue) != 0) {
    return 1;
  }
  std::cout << localLDPathValue << std::endl;

  return 0;
}

#include <cstdlib>
#include <string.h>
#include <iostream>

int main() {
#ifdef __APPLE__
  const char* name = "DYLD_LIBRARY_PATH";
#else
  const char* name = "LD_LIBRARY_PATH";
#endif

  const char* cetLDPathValue = getenv("CETD_LIBRARY_PATH");
  int res = setenv("DYLD_LIBRARY_PATH", cetLDPathValue, 1);

  const char* localLDPathValue = getenv(name);

  if(strcmp(localLDPathValue,cetLDPathValue) != 0) {
    return 1;
  }
  std::cout << localLDPathValue << std::endl;

  return 0;
}

Add missing header on Linux


#include "GeometryObject.h"

GeometryObject::GeometryObject() {

}

GeometryObject::GeometryObject(const std::vector<Point3D>& vertices, const std::vector<uint8_t>& indices)
  : m_vertices(vertices), m_indices(indices){

}

GeometryObject::~GeometryObject() {

}

const std::vector<Triangle3D> GeometryObject::tessellate() const {
  //TODO: actual tessellation using vertices and indices

  return std::vector<Triangle3D> {
    Triangle3D(
      Point3D(-5.0f, 0.0f, 0.0f),
      Point3D(0.0f, 5.0f, 0.0f),
      Point3D(5.0f, 0.0f, 0.0f)
    )
  };
}

#include "GeometryObject.h"

GeometryObject::GeometryObject() {
  m_color = RGBColor(1, 0, 0);

}

GeometryObject::GeometryObject(const std::vector<Point3D>& vertices, const std::vector<uint8_t>& indices)
  : m_vertices(vertices), m_indices(indices){
  m_color = RGBColor(1, 0, 0);
}

GeometryObject::~GeometryObject() {

}

const std::vector<Triangle3D> GeometryObject::tessellate() const {
  //TODO: actual tessellation using vertices and indices

  return std::vector<Triangle3D> {
    Triangle3D(
      Point3D(-25.0f, 0.0f, 20.0f),
      Point3D(0.0f, 25.0f, 20.0f),
      Point3D(25.0f, 0.0f, 20.0f)
    )
  };
}

Initialize object color to red for testing purposes


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

#include "chrome/browser/banners/app_banner_manager_desktop.h"

#include "base/command_line.h"
#include "chrome/browser/banners/app_banner_data_fetcher_desktop.h"
#include "chrome/common/chrome_switches.h"
#include "extensions/common/constants.h"

namespace {
// TODO(dominickn) Enforce the set of icons which will guarantee the best
// user experience.
int kMinimumIconSize = extension_misc::EXTENSION_ICON_LARGE;
}  // anonymous namespace

DEFINE_WEB_CONTENTS_USER_DATA_KEY(banners::AppBannerManagerDesktop);

namespace banners {

bool AppBannerManagerDesktop::IsEnabled() {
#if defined(OS_CHROMEOS)
  return !base::CommandLine::ForCurrentProcess()->HasSwitch(
      switches::kDisableAddToShelf);
#else
  return base::CommandLine::ForCurrentProcess()->HasSwitch(
      switches::kEnableAddToShelf);
#endif
}

AppBannerDataFetcher* AppBannerManagerDesktop::CreateAppBannerDataFetcher(
    base::WeakPtr<AppBannerDataFetcher::Delegate> weak_delegate,
    const int ideal_icon_size) {
  return new AppBannerDataFetcherDesktop(web_contents(), weak_delegate,
                                         ideal_icon_size);
}

AppBannerManagerDesktop::AppBannerManagerDesktop(
    content::WebContents* web_contents)
    : AppBannerManager(web_contents, kMinimumIconSize) {
}

}  // namespace banners

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

#include "chrome/browser/banners/app_banner_manager_desktop.h"

#include "base/command_line.h"
#include "chrome/browser/banners/app_banner_data_fetcher_desktop.h"
#include "chrome/common/chrome_switches.h"
#include "extensions/common/constants.h"

namespace {
// TODO(dominickn) Enforce the set of icons which will guarantee the best
// user experience.
int kMinimumIconSize = extension_misc::EXTENSION_ICON_LARGE;
}  // anonymous namespace

DEFINE_WEB_CONTENTS_USER_DATA_KEY(banners::AppBannerManagerDesktop);

namespace banners {

bool AppBannerManagerDesktop::IsEnabled() {
  return base::CommandLine::ForCurrentProcess()->HasSwitch(
      switches::kEnableAddToShelf);
}

AppBannerDataFetcher* AppBannerManagerDesktop::CreateAppBannerDataFetcher(
    base::WeakPtr<AppBannerDataFetcher::Delegate> weak_delegate,
    const int ideal_icon_size) {
  return new AppBannerDataFetcherDesktop(web_contents(), weak_delegate,
                                         ideal_icon_size);
}

AppBannerManagerDesktop::AppBannerManagerDesktop(
    content::WebContents* web_contents)
    : AppBannerManager(web_contents, kMinimumIconSize) {
}

}  // namespace banners

Disable app banners on ChromeOS.


#include "perf_precomp.hpp"

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

typedef perf::TestBaseWithParam<std::string> fast;

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

PERF_TEST_P(fast, detectForORB, testing::Values(FAST_IMAGES))
{
    String filename = getDataPath(GetParam());
    Mat frame = imread(filename, IMREAD_GRAYSCALE);

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

    declare.in(frame);

    FastFeatureDetector fd(20, true, FastFeatureDetector::TYPE_5_8);
    vector<KeyPoint> points;

    TEST_CYCLE() fd.detect(frame, points);
    fd = FastFeatureDetector(20, true, FastFeatureDetector::TYPE_7_12);
    TEST_CYCLE() fd.detect(frame, points);
    fd = FastFeatureDetector(20, true, FastFeatureDetector::TYPE_9_16);
    TEST_CYCLE() fd.detect(frame, points);
}

#include "perf_precomp.hpp"

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

enum { TYPE_5_8 =FastFeatureDetector::TYPE_5_8, TYPE_7_12 = FastFeatureDetector::TYPE_7_12, TYPE_9_16 = FastFeatureDetector::TYPE_9_16 };
CV_ENUM(FastType, TYPE_5_8, TYPE_7_12, TYPE_9_16)

typedef std::tr1::tuple<String, FastType> File_Type_t;
typedef perf::TestBaseWithParam<File_Type_t> fast;

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

PERF_TEST_P(fast, detect, testing::Combine(
                            testing::Values(FAST_IMAGES),
                            testing::ValuesIn(FastType::all())
                          ))
{
    String filename = getDataPath(get<0>(GetParam()));
    int type = get<1>(GetParam());
    Mat frame = imread(filename, IMREAD_GRAYSCALE);

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

    declare.in(frame);

    FastFeatureDetector fd(20, true, type);
    vector<KeyPoint> points;

    TEST_CYCLE() fd.detect(frame, points);

    SANITY_CHECK(points);
}

Fix terrible perf test for FAST detector


#include <iostream>
#include <memory>
#include <utility>

#include "parse/Parse.hpp"

using namespace parse;
using std::cout;

class TreePrinter : public tree::TermVisitor
{
public:

    virtual void acceptTerm(const tree::Abstraction& term) override
    {
        cout << "(^";

        for (const std::string& arg : term.arguments)
        {
            cout << arg << " ";
        }

        cout << ". ";

        term.body->applyVisitor(*this);

        cout << ")";
    }

    virtual void acceptTerm(const tree::Application& term) override
    {
        cout << "(";

        bool isFirst = true;

        for (int termNdx = 0; termNdx < term.terms.size(); ++termNdx)
        {
            if (!isFirst)
            {
                cout << " ";
            }

            isFirst = false;

            term.terms[termNdx]->applyVisitor(*this);
        }

        cout << ")";
    }

    virtual void acceptTerm(const tree::Variable& term) override
    {
        cout << term.name;
    }
};

int main()
{
    std::unique_ptr<tree::Variable> vx(new tree::Variable), vy(new tree::Variable);

    vx->name = "x";
    vy->name = "y";

    std::unique_ptr<tree::Application> body(new tree::Application);

    body->terms.push_back(std::move(vx));
    body->terms.push_back(std::move(vy));

    std::unique_ptr<tree::Abstraction> abs(new tree::Abstraction);

    abs->arguments.push_back("x");
    abs->body = std::move(body);

    TreePrinter treePrinter;

    abs->applyVisitor(treePrinter);

    cout << "\n";
}

Test tree and try printing it


/* BZWorkbench
 * Copyright (c) 1993 - 2008 Tim Riker
 *
 * This package is free software;  you can redistribute it and/or
 * modify it under the terms of the license found in the file
 * named COPYING that should have accompanied this file.
 *
 * THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
 * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
 */

#include "windows/ConsoleWindow.h"

Console* ConsoleWindow::console = NULL;
bool ConsoleWindow::initialized = false;

// constructor
ConsoleWindow::ConsoleWindow(int lineLimit) :
	Fl_Window(DEFAULT_WIDTH, DEFAULT_HEIGHT, "BZWorkbench Messages") {

	end();

	console = new Console(10, 10, DEFAULT_WIDTH - 20, DEFAULT_HEIGHT - 20);
	add(console);

	initialized = true;

	console->setReadOnly(true);
}

// destructor
ConsoleWindow::~ConsoleWindow() {
	initialized = false;
}

// outputs text to the console widget
void ConsoleWindow::output(const char* text, ...) {

	// borrowed from TextUtils.cxx
	va_list args;
    va_start(args, text);
    string result = TextUtils::vformat(text, args);
    va_end(args);

	if(!initialized) {
	    printf("%s", result.c_str());
	}
	else {
		console->add( result );
	}
}

/* BZWorkbench
 * Copyright (c) 1993 - 2008 Tim Riker
 *
 * This package is free software;  you can redistribute it and/or
 * modify it under the terms of the license found in the file
 * named COPYING that should have accompanied this file.
 *
 * THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
 * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
 */

#include <stdio.h>
#include "windows/ConsoleWindow.h"

Console* ConsoleWindow::console = NULL;
bool ConsoleWindow::initialized = false;

// constructor
ConsoleWindow::ConsoleWindow(int lineLimit) :
	Fl_Window(DEFAULT_WIDTH, DEFAULT_HEIGHT, "BZWorkbench Messages") {

	end();

	console = new Console(10, 10, DEFAULT_WIDTH - 20, DEFAULT_HEIGHT - 20);
	add(console);

	initialized = true;

	console->setReadOnly(true);
}

// destructor
ConsoleWindow::~ConsoleWindow() {
	initialized = false;
}

// outputs text to the console widget
void ConsoleWindow::output(const char* text, ...) {

	// borrowed from TextUtils.cxx
	va_list args;
    va_start(args, text);
    string result = TextUtils::vformat(text, args);
    va_end(args);

	if(!initialized) {
	    printf("%s", result.c_str());
	}
	else {
		console->add( result );
	}
}

Include stdio.h for printf() declaration.


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

#include <sys/sysinfo.h>

#include "test/gtest_and_gmock.h"

namespace perfetto {

TEST(PerfettoDeviceFeatureTest, TestMaxCpusForAtraceChmod) {
  // Check that there are no more than 16 CPUs so that the assumption in the
  // atrace.rc for clearing CPU buffers is valid.
  ASSERT_LE(sysconf(_SC_NPROCESSORS_CONF), 16);
}

}  // namespace perfetto

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

#include <sys/sysinfo.h>

#include "test/gtest_and_gmock.h"

namespace perfetto {

TEST(PerfettoDeviceFeatureTest, TestMaxCpusForAtraceChmod) {
  // Check that there are no more than 24 CPUs so that the assumption in the
  // atrace.rc for clearing CPU buffers is valid.
  ASSERT_LE(sysconf(_SC_NPROCESSORS_CONF), 24);
}

}  // namespace perfetto

Increase core count for PerfettoDeviceFeatureTest