/*
 * Timer compilation example.
 * TODO
 */

#include <fastarduino/FastIO.hh>
#include <fastarduino/Timer.hh>

constexpr const Board::Timer TIMER = Board::Timer::TIMER1;
// Define vectors we need in the example
USE_TIMERS(1);

using TIMER_TYPE = Timer<TIMER>;
constexpr const uint32_t PERIOD_US = 1000000;

constexpr const TIMER_TYPE::TIMER_PRESCALER PRESCALER = TIMER_TYPE::prescaler(PERIOD_US);
static_assert(TIMER_TYPE::is_adequate(PRESCALER, PERIOD_US), "TIMER_TYPE::is_adequate(PRESCALER, PERIOD_US)");
constexpr const TIMER_TYPE::TIMER_TYPE COUNTER = TIMER_TYPE::counter(PRESCALER, PERIOD_US);

class Handler: public TimerCallback
{
public:
	Handler(): _led{PinMode::OUTPUT, false} {}

	virtual void on_timer() override
	{
		_led.toggle();
	}

private:
	FastPinType<Board::DigitalPin::LED>::TYPE _led;
};

int main()
{
	sei();
	Handler handler;
	TIMER_TYPE timer{handler};
	timer.begin(PRESCALER, COUNTER);

	while (true) ;
}

/*
 * Timer compilation example.
 * Shows how to use a CTC Timer (not RTT) to blink a LED.
 *
 * Wiring:
 * - on ATmega328P based boards (including Arduino UNO):
 *   - D13 (PB5) LED connected to ground through a resistor
 * - on Arduino MEGA:
 *   - D13 (PB7) LED connected to ground through a resistor
 * - on ATtinyX4 based boards:
 *   - D7 (PA7) LED connected to ground through a resistor
 */

#include <fastarduino/FastIO.hh>
#include <fastarduino/Timer.hh>

constexpr const Board::Timer TIMER = Board::Timer::TIMER1;
// Define vectors we need in the example
USE_TIMERS(1)

using TIMER_TYPE = Timer<TIMER>;
constexpr const uint32_t PERIOD_US = 1000000;

constexpr const TIMER_TYPE::TIMER_PRESCALER PRESCALER = TIMER_TYPE::prescaler(PERIOD_US);
static_assert(TIMER_TYPE::is_adequate(PRESCALER, PERIOD_US), "TIMER_TYPE::is_adequate(PRESCALER, PERIOD_US)");
constexpr const TIMER_TYPE::TIMER_TYPE COUNTER = TIMER_TYPE::counter(PRESCALER, PERIOD_US);

class Handler: public TimerCallback
{
public:
	Handler(): _led{PinMode::OUTPUT, false} {}

	virtual void on_timer() override
	{
		_led.toggle();
	}

private:
	FastPinType<Board::DigitalPin::LED>::TYPE _led;
};

int main()
{
	sei();
	Handler handler;
	TIMER_TYPE timer{handler};
	timer.begin(PRESCALER, COUNTER);

	while (true) ;
}

Rework and fix Timer ISR size optimization.


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

#include "chrome/browser/ui/webui/print_preview_ui.h"

#include "base/values.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/ui/webui/print_preview_handler.h"
#include "chrome/browser/ui/webui/print_preview_ui_html_source.h"
#include "content/browser/browser_thread.h"
#include "content/browser/tab_contents/tab_contents.h"

PrintPreviewUI::PrintPreviewUI(TabContents* contents)
    : WebUI(contents),
      html_source_(new PrintPreviewUIHTMLSource()) {
  // PrintPreviewUI owns |handler|.
  PrintPreviewHandler* handler = new PrintPreviewHandler();
  AddMessageHandler(handler->Attach(this));

  // Set up the chrome://print/ source.
  contents->profile()->GetChromeURLDataManager()->AddDataSource(html_source_);
}

PrintPreviewUI::~PrintPreviewUI() {
}

PrintPreviewUIHTMLSource* PrintPreviewUI::html_source() {
  return html_source_.get();
}

void PrintPreviewUI::PreviewDataIsAvailable(int expected_pages_count) {
  FundamentalValue pages_count(expected_pages_count);
  CallJavascriptFunction("createPDFPlugin", pages_count);
}

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

#include "chrome/browser/ui/webui/print_preview_ui.h"

#include "base/values.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/ui/webui/print_preview_handler.h"
#include "chrome/browser/ui/webui/print_preview_ui_html_source.h"
#include "content/browser/browser_thread.h"
#include "content/browser/tab_contents/tab_contents.h"

PrintPreviewUI::PrintPreviewUI(TabContents* contents)
    : WebUI(contents),
      html_source_(new PrintPreviewUIHTMLSource()) {
  // PrintPreviewUI owns |handler|.
  PrintPreviewHandler* handler = new PrintPreviewHandler();
  AddMessageHandler(handler->Attach(this));

  // Set up the chrome://print/ source.
  contents->profile()->GetChromeURLDataManager()->AddDataSource(html_source_);
}

PrintPreviewUI::~PrintPreviewUI() {
}

PrintPreviewUIHTMLSource* PrintPreviewUI::html_source() {
  return html_source_.get();
}

void PrintPreviewUI::PreviewDataIsAvailable(int expected_pages_count) {
  FundamentalValue pages_count(expected_pages_count);
  CallJavascriptFunction("updatePrintPreview", pages_count);
}

Print Preview: Fix typo from r78639.

Print Preview: Fix typo from r78639.

BUG=76707
TEST=page count initialized correctly in print preview.
R=arv@chromium.org
Review URL: http://codereview.chromium.org/6688041

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


#include "TilePartitionerBase.h"

void TilePartitionerBase::applyWeights(const std::vector<float>& weights, std::vector<sf::Uint8>& alphas)
{
    int err = 255;
    float total_weight = 0.f;
    for (auto weight : weights)
        total_weight += weight;
    if (total_weight == 0.f)
    {
        // This shouldn't happen, but it is easy to make weight masks
        // where this does happen.
        for (auto& alpha : alphas)
        {
            alpha = 0;
        }
        return;
    }
    for (size_t i = 0; i < weights.size(); i++)
    {
        int alpha = (int)((255 * weights[i]) / total_weight);
        err -= alpha;
        alphas[i] = (sf::Uint8)alpha;
    }
    size_t i = 0;
    while (err > 0)
    {
        sf::Uint8& alpha = alphas[i%alphas.size()];
        if (alpha > 0)
        {
            alpha++;
            err--;
        }
        i++;
    }
}

TilePartitionerBase::TilePartitionerBase(const Options & options) :
    mOptions(options)
{
}

TilePartitionerBase::~TilePartitionerBase()
{
}

#include "TilePartitionerBase.h"

void TilePartitionerBase::applyWeights(const std::vector<float>& weights, std::vector<sf::Uint8>& alphas)
{
    int err = 255;
    float total_weight = 0.f;
    for (auto weight : weights)
        total_weight += weight;
    for (auto& alpha : alphas)
    {
        alpha = 0;
    }
    if (total_weight == 0.f)
    {
        // This shouldn't happen, but it is easy to make weight masks
        // where this does happen.

        return;
    }
    else
    {
        size_t max_idx = -1;
        float max_weight = -1.;
        for (size_t i = 0; i < weights.size(); i++)
        {
            if (weights[i] > max_weight)
            {
                max_idx = i;
                max_weight = weights[i];
            }
        }
        alphas[max_idx] = 255;
    }
    //for (size_t i = 0; i < weights.size(); i++)
    //{
    //    int alpha = (int)((255 * weights[i]) / total_weight);
    //    err -= alpha;
    //    alphas[i] = (sf::Uint8)alpha;
    //}
    //size_t i = 0;
    //while (err > 0)
    //{
    //    sf::Uint8& alpha = alphas[i%alphas.size()];
    //    if (alpha > 0)
    //    {
    //        alpha++;
    //        err--;
    //    }
    //    i++;
    //}
}

TilePartitionerBase::TilePartitionerBase(const Options & options) :
    mOptions(options)
{
}

TilePartitionerBase::~TilePartitionerBase()
{
}

Replace the alpha calculator with winner-takes-all

Both will have to become instances of a base class or function type in
future.


#include "capu/util/ConsoleLogAppender.h"
#include "capu/util/LogMessage.h"
#include "capu/os/Console.h"
#include "capu/os/Time.h"
#include <stdio.h>

namespace capu
{
    Mutex ConsoleLogAppender::m_logMutex;

    ConsoleLogAppender::~ConsoleLogAppender()
    {
    }

    void ConsoleLogAppender::logMessage(const LogMessage& logMessage)
    {
        m_logMutex.lock();
        const uint64_t now = Time::GetMilliseconds();
        Console::Print(Console::WHITE, "%.3f ", now/1000.0);

        switch(logMessage.getLogLevel())
        {
        case LL_TRACE:
            Console::Print(Console::WHITE, "[  Trace  ] ");
            break;
        default:
        case LL_DEBUG :
            Console::Print(Console::WHITE, "[  Debug  ] ");
            break;
        case LL_INFO :
            Console::Print(Console::GREEN, "[  Info   ] ");
            break;
        case LL_WARN :
            Console::Print(Console::YELLOW, "[  Warn   ] ");
            break;
        case LL_ERROR :
            Console::Print(Console::RED, "[  Error  ] ");
            break;
        case LL_FATAL :
            Console::Print(Console::RED, "[  Fatal  ] ");
            break;
        }

        Console::Print(Console::AQUA, logMessage.getContext().getContextName().c_str());
        Console::Print(" | %s\n", logMessage.getLogMessage());
        Console::Flush();
        m_logMutex.unlock();
    }
}

#include "capu/util/ConsoleLogAppender.h"
#include "capu/util/LogMessage.h"
#include "capu/util/ScopedLock.h"
#include "capu/os/Console.h"
#include "capu/os/Time.h"
#include <stdio.h>

namespace capu
{
    Mutex ConsoleLogAppender::m_logMutex;

    ConsoleLogAppender::~ConsoleLogAppender()
    {
    }

    void ConsoleLogAppender::logMessage(const LogMessage& logMessage)
    {
        ScopedMutexLock lock(m_logMutex);
        const uint64_t now = Time::GetMilliseconds();
        Console::Print(Console::WHITE, "%.3f ", now/1000.0);

        switch(logMessage.getLogLevel())
        {
        case LL_TRACE:
            Console::Print(Console::WHITE, "[  Trace  ] ");
            break;
        default:
        case LL_DEBUG :
            Console::Print(Console::WHITE, "[  Debug  ] ");
            break;
        case LL_INFO :
            Console::Print(Console::GREEN, "[  Info   ] ");
            break;
        case LL_WARN :
            Console::Print(Console::YELLOW, "[  Warn   ] ");
            break;
        case LL_ERROR :
            Console::Print(Console::RED, "[  Error  ] ");
            break;
        case LL_FATAL :
            Console::Print(Console::RED, "[  Fatal  ] ");
            break;
        }

        Console::Print(Console::AQUA, logMessage.getContext().getContextName().c_str());
        Console::Print(" | %s\n", logMessage.getLogMessage());
        Console::Flush();
    }
}

Replace manual locking by ScopedLock

Replace manual locking by ScopedLock

Change-Id: Ice9efbc1d0445b9251ae411c344290e85e73ceac


#include<cmath>
#include<iostream>

using namespace std;

bool isPrimeBruteForce(int x)
{
	if (x < 2)
		return false;
	float sqroot_x = sqrt(x);
	for(int i=0; i <= sqroot_x; i++) { /* If there were only factors above the square root of x, they would be bigger than x itself. */
		if (x%i==0)
			return false;
	}
	return true;
}

int main(int argc, char* argv[])
{
	int number;
	bool result;
	cout << "Enter number to test if it's prime: ";
	cin >> number;
	result = isPrimeBruteForce(number);
	if (result) {
		cout << number << " is a prime number.";
	} else {
		cout << number << " is not a prime number.";
	}
	return 0;
}

#include<cmath>
#include<iostream>

using namespace std;

bool isPrimeBruteForce(double x)
{
	if (x < 2)
		return false;
	double sqroot_x = sqrt(x);
	for(int i=0; i <= sqroot_x; i++) { /* If there were only factors above the square root of x, they would be bigger than x itself. */
		if (x%i==0)
			return false;
	}
	return true;
}

int main(int argc, char* argv[])
{
	double number;
	bool result;
	cout << "Enter number to test if it's prime: ";
	cin >> number;
	result = isPrimeBruteForce(number);
	if (result) {
		cout << number << " is a prime number.";
	} else {
		cout << number << " is not a prime number.";
	}
	return 0;
}

Correct wrong type of variables 'number' and 'x' (int->double)


// RUN: %clang_cc1 -fcxx-exceptions -fexceptions -Wno-unreachable-code -Werror -emit-llvm -o - %s | FileCheck %s
// expected-no-diagnostics

int val = 42;
int& test1() {
  return throw val, val;
}

int test2() {
  return val ? throw val : val;
}

// rdar://problem/8608801
void test3() {
  throw false;
}

// PR10582
int test4() {
  return 1 ? throw val : val;
}

// PR15923
int test5(bool x, bool y, int z) {
  return (x ? throw 1 : y) ? z : throw 2;
}
// CHECK: define i32 @_Z5test5bbi(
// CHECK: br i1
//
// x.true:
// CHECK: call void @__cxa_throw(
// CHECK-NEXT: unreachable
//
// x.false:
// CHECK: br i1
//
// y.true:
// CHECK: load i32*
// CHECK: br label
//
// y.false:
// CHECK: call void @__cxa_throw(
// CHECK-NEXT: unreachable
//
// end:
// CHECK: ret i32

// RUN: %clang_cc1 -fcxx-exceptions -fexceptions -Wno-unreachable-code -Werror -triple x86_64-linux-gnu -emit-llvm -o - %s | FileCheck %s

int val = 42;
int& test1() {
  return throw val, val;
}

int test2() {
  return val ? throw val : val;
}

// rdar://problem/8608801
void test3() {
  throw false;
}

// PR10582
int test4() {
  return 1 ? throw val : val;
}

// PR15923
int test5(bool x, bool y, int z) {
  return (x ? throw 1 : y) ? z : throw 2;
}
// CHECK: define i32 @_Z5test5bbi(
// CHECK: br i1
//
// x.true:
// CHECK: call void @__cxa_throw(
// CHECK-NEXT: unreachable
//
// x.false:
// CHECK: br i1
//
// y.true:
// CHECK: load i32*
// CHECK: br label
//
// y.false:
// CHECK: call void @__cxa_throw(
// CHECK-NEXT: unreachable
//
// end:
// CHECK: ret i32

Add missing triple to unit test.

Add missing triple to unit test.

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


#include "CIndexBuffer.h"

#include <glad/glad.h>

namespace ion
{
	namespace Graphics
	{
		namespace GL
		{

			void CIndexBuffer::UploadData(void const * Data, size_t const Elements, EValueType const ValueType)
			{
				CheckedGLCall(glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, Handle));
				CheckedGLCall(glBufferData(GL_ELEMENT_ARRAY_BUFFER, Elements * GetValueTypeSize(ValueType), Data, GL_STATIC_DRAW));
				CheckedGLCall(glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0));
			}

		}
	}
}

#include "CIndexBuffer.h"

#include <glad/glad.h>

namespace ion
{
	namespace Graphics
	{
		namespace GL
		{

			void CIndexBuffer::UploadData(void const * Data, size_t const Elements, EValueType const ValueType)
			{
				CheckedGLCall(glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, Handle));
				CheckedGLCall(glBufferData(GL_ELEMENT_ARRAY_BUFFER, Elements * GetValueTypeSize(ValueType), Data, GL_STATIC_DRAW));
				CheckedGLCall(glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0));
				Size = Elements;
			}

		}
	}
}

Fix bug where uninitialized index buffers still wouldn't work after initialization


#include "MainWindow.h"
#include "ui_MainWindow.h"

#include "CuteNode.h"
#include "NodeScene.h"

MainWindow::MainWindow(QWidget* parent)
    : QMainWindow(parent)
    , _scene{std::make_unique<NodeScene>(QRectF(0.0, 0.0, 3000.0, 3000.0))}
    , _ui{std::make_unique<Ui::MainWindow>()}
{
    _ui->setupUi(this);

    for (int i=0; i<5; ++i)
    {
        CuteNode* node = new CuteNode;
        node->setPos(i*300.0, 300.0);
        _scene->addItem(node);
    }

    _ui->nodeView->setScene(_scene.get());
    _ui->nodeView->centerOn(0.0, 0.0);

    connect(_ui->actionToggleSnap, &QAction::triggered, _scene.get(), &NodeScene::toggleGridSnapping);
    connect(_ui->actionToggleOverlap, &QAction::triggered, _scene.get(), &NodeScene::toggleNodeOverlap);
}

MainWindow::~MainWindow()
{
}

void MainWindow::on_actionAddNode_triggered()
{
    CuteNode* node = new CuteNode;
    node->setPos(500, 300);
    _scene->addItem(node);
}

#include "MainWindow.h"
#include "ui_MainWindow.h"

#include "CuteNode.h"
#include "NodeScene.h"

MainWindow::MainWindow(QWidget* parent)
    : QMainWindow(parent)
    , _scene{std::make_unique<NodeScene>(QRectF(0.0, 0.0, 3000.0, 3000.0))}
    , _ui{std::make_unique<Ui::MainWindow>()}
{
    _ui->setupUi(this);

    for (int i=3; i<8; ++i)
    {
        CuteNode* node = new CuteNode;
        node->setPos(i*300.0, 1000.0);
        _scene->addItem(node);
    }

    _ui->nodeView->setScene(_scene.get());
    _ui->nodeView->centerOn(1000.0, 1000.0);

    connect(_ui->actionToggleSnap, &QAction::triggered, _scene.get(), &NodeScene::toggleGridSnapping);
    connect(_ui->actionToggleOverlap, &QAction::triggered, _scene.get(), &NodeScene::toggleNodeOverlap);
}

MainWindow::~MainWindow()
{
}

void MainWindow::on_actionAddNode_triggered()
{
    CuteNode* node = new CuteNode;
    node->setPos(500, 300);
    _scene->addItem(node);
}

Put nodes into middle of scene to improve zooming


#include "command.h"
#include "../CommandHandler.h"
#include "../option.h"

/* full name of the command */
_CMDNAME("manual");
/* description of the command */
_CMDDESCR("view the lynxbot manual");
/* command usage synopsis */
_CMDUSAGE("$manual");

/* manual: view the lynxbot manual */
std::string CommandHandler::manual(char *out, struct command *c)
{
	int opt;
	static struct option long_opts[] = {
		{ "help", NO_ARG, 'h' },
		{ 0, 0, 0 }
	};

	opt_init();
	while ((opt = getopt_long(c->argc, c->argv, "", long_opts)) != EOF) {
		switch (opt) {
		case 'h':
			_HELPMSG(out, _CMDNAME, _CMDUSAGE, _CMDDESCR);
			return "";
		case '?':
			_sprintf(out, MAX_MSG, "%s", opterr());
			return "";
		default:
			return "";
		}
	}

	if (optind != c->argc)
		_USAGEMSG(out, _CMDNAME, _CMDUSAGE);
	else
		_sprintf(out, MAX_MSG, "[MANUAL] %s/manual/index.html",
				BOT_WEBSITE);
	return "";
}

#include "command.h"
#include "../CommandHandler.h"
#include "../option.h"

/* full name of the command */
_CMDNAME("manual");
/* description of the command */
_CMDDESCR("view the lynxbot manual");
/* command usage synopsis */
_CMDUSAGE("$manual");

/* manual: view the lynxbot manual */
std::string CommandHandler::manual(char *out, struct command *c)
{
	int opt;
	static struct option long_opts[] = {
		{ "help", NO_ARG, 'h' },
		{ 0, 0, 0 }
	};

	opt_init();
	while ((opt = getopt_long(c->argc, c->argv, "", long_opts)) != EOF) {
		switch (opt) {
		case 'h':
			_HELPMSG(out, _CMDNAME, _CMDUSAGE, _CMDDESCR);
			return "";
		case '?':
			_sprintf(out, MAX_MSG, "%s", opterr());
			return "";
		default:
			return "";
		}
	}

	if (optind != c->argc)
		_USAGEMSG(out, _CMDNAME, _CMDUSAGE);
	else
		_sprintf(out, MAX_MSG, "[MANUAL] %s/manual/index.html",
				_BOT_WEBSITE);
	return "";
}

Use new website macro instead

Use new website macro instead


#include "tag-database-factory.h"
#include "tag-database-in-memory.h"
#include "tag-database-sqlite.h"
#include <QFile>

TagDatabase *TagDatabaseFactory::Create(QString directory)
{
	if (!directory.endsWith("/") && !directory.endsWith("\\"))
		directory += "/";

	QString typesFile = directory + "tag-types.txt";

	if (QFile::exists(directory + "tags.txt"))
		return new TagDatabaseInMemory(typesFile, directory + "tags.txt");

	return new TagDatabaseSqlite(typesFile, directory + "tags.db");
}

#include "tag-database-factory.h"
#include "tag-database-in-memory.h"
#include "tag-database-sqlite.h"
#include <QFile>

TagDatabase *TagDatabaseFactory::Create(QString directory)
{
	if (!directory.endsWith("/") && !directory.endsWith("\\"))
		directory += "/";

	QString typesFile = directory + "tag-types.txt";

	if (QFile::exists(directory + "tags.db"))
		return new TagDatabaseSqlite(typesFile, directory + "tags.db");

	return new TagDatabaseInMemory(typesFile, directory + "tags.txt");
}

Use InMemory TagDatabase by default if none exists


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

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

#include "util.h"

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

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

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

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

#include "util.h"

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

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

Fix memory leak in float literal parsing
Issue=93

Contributed by Benoit Jacob

git-svn-id: 947ae547afacb859f3991e003b9d6feb04be57d7@504 736b8ea6-26fd-11df-bfd4-992fa37f6226


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

#include "chrome/browser/sync/glue/chrome_encryptor.h"

#include "chrome/browser/password_manager/encryptor.h"

namespace browser_sync {

ChromeEncryptor::~ChromeEncryptor() {}

bool ChromeEncryptor::EncryptString(const std::string& plaintext,
                                    std::string* ciphertext) {
  return ::Encryptor::EncryptString(plaintext, ciphertext);
}

bool ChromeEncryptor::DecryptString(const std::string& ciphertext,
                                    std::string* plaintext) {
  return ::Encryptor::EncryptString(ciphertext, plaintext);
}

}  // namespace browser_sync

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

#include "chrome/browser/sync/glue/chrome_encryptor.h"

#include "chrome/browser/password_manager/encryptor.h"

namespace browser_sync {

ChromeEncryptor::~ChromeEncryptor() {}

bool ChromeEncryptor::EncryptString(const std::string& plaintext,
                                    std::string* ciphertext) {
  return ::Encryptor::EncryptString(plaintext, ciphertext);
}

bool ChromeEncryptor::DecryptString(const std::string& ciphertext,
                                    std::string* plaintext) {
  return ::Encryptor::DecryptString(ciphertext, plaintext);
}

}  // namespace browser_sync

[Sync] Fix EncryptString call that should be a DecryptString call

Unit tests to catch this will come in another CL.

BUG=116607
TEST=

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

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


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

#include <emscripten.h>
#include <emscripten/bind.h>
#include "tools/viewer/SampleSlide.h"
#include <string>

using namespace emscripten;

EMSCRIPTEN_BINDINGS(Viewer) {
    function("MakeSlide", optional_override([](std::string name)->sk_sp<Slide> {
        if (name == "WavyPathText") {
            extern Sample* MakeWavyPathTextSample();
            return sk_make_sp<SampleSlide>(MakeWavyPathTextSample);
        }
        return nullptr;
    }));
    class_<Slide>("Slide")
        .smart_ptr<sk_sp<Slide>>("sk_sp<Slide>")
        .function("load", &Slide::load)
        .function("animate", &Slide::animate)
        .function("draw", optional_override([](Slide& self, SkCanvas& canvas) {
            self.draw(&canvas);
        }));
}

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

#include <emscripten.h>
#include <emscripten/bind.h>
#include "include/core/SkCanvas.h"
#include "tools/viewer/SampleSlide.h"
#include <string>

using namespace emscripten;

EMSCRIPTEN_BINDINGS(Viewer) {
    function("MakeSlide", optional_override([](std::string name)->sk_sp<Slide> {
        if (name == "WavyPathText") {
            extern Sample* MakeWavyPathTextSample();
            return sk_make_sp<SampleSlide>(MakeWavyPathTextSample);
        }
        return nullptr;
    }));
    class_<Slide>("Slide")
        .smart_ptr<sk_sp<Slide>>("sk_sp<Slide>")
        .function("load", &Slide::load)
        .function("animate", &Slide::animate)
        .function("draw", optional_override([](Slide& self, SkCanvas& canvas) {
            self.draw(&canvas);
        }));
}

Fix the CanvasKit viewer build

Fix the CanvasKit viewer build

Change-Id: I82e28478bd9c52f5633e74472ab2b256961cdf45
Reviewed-on: https://skia-review.googlesource.com/c/skia/+/281050
Reviewed-by: Kevin Lubick <7cdab2cfab351f23814786ba39716e90eed69047@google.com>


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

int main() {
    ofGLFWWindowSettings settings;
    settings.width = 1280;
    settings.height = 720;
    settings.setPosition(ofVec2f(300,0));
    settings.resizable = true;
    shared_ptr<ofAppBaseWindow> mainWindow = ofCreateWindow(settings);
    mainWindow->setFullscreen(true);

    settings.width = 500;
    settings.height = 900;
    settings.setPosition(ofVec2f(0,0));
    settings.shareContextWith = mainWindow;
    shared_ptr<ofAppBaseWindow> guiWindow = ofCreateWindow(settings);

    shared_ptr<ofApp> mainApp(new ofApp);
    mainApp->setupGui();
    ofAddListener(guiWindow->events().draw, mainApp.get(), &ofApp::drawGui);
    ofAddListener(guiWindow->events().keyPressed, mainApp.get(), &ofApp::guiKeyPressed);

    ofRunApp(mainWindow, mainApp);
    ofRunMainLoop();
}

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

int main() {
    ofGLFWWindowSettings settings;
    settings.width = 1280;
    settings.height = 720;
    settings.setPosition(ofVec2f(300,0));
    settings.resizable = true;
    shared_ptr<ofAppBaseWindow> mainWindow = ofCreateWindow(settings);
    mainWindow->setFullscreen(true);

    settings.width = 500;
    settings.height = ofGetScreenHeight();
    settings.setPosition(ofVec2f(0,0));
    settings.shareContextWith = mainWindow;
    shared_ptr<ofAppBaseWindow> guiWindow = ofCreateWindow(settings);

    shared_ptr<ofApp> mainApp(new ofApp);
    mainApp->setupGui();
    ofAddListener(guiWindow->events().draw, mainApp.get(), &ofApp::drawGui);
    ofAddListener(guiWindow->events().keyPressed, mainApp.get(), &ofApp::guiKeyPressed);

    ofRunApp(mainWindow, mainApp);
    ofRunMainLoop();
}

Make gui window a bit more responsive

Make gui window a bit more responsive


#include "../kontsevich_graph_series.hpp"
#include <ginac/ginac.h>
#include <iostream>
using namespace std;
using namespace GiNaC;

size_t order = 2;

int main()
{
    // Compute relevant primes
    map< size_t, set<KontsevichGraph> > primes;
    for (size_t n = 0; n <= order; ++n)
    {
        primes[n] = KontsevichGraph::graphs(n, 2, true, true,
                        [](KontsevichGraph g) -> bool
                        {
                            return g.positive_differential_order() && g.is_prime();
                        });
    }
    // Make a table of (symbolic) weights
    map<KontsevichGraph, symbol> weights;
    size_t weight_count = 0;
    for (size_t n = 0; n <= order; ++n)
    {
        for (KontsevichGraph g : primes[n])
        {
            weights[g] = symbol("w_" + weight_count++);
        }
    }
    KontsevichGraphSeries<symbol> star_product;
}

#include "../kontsevich_graph_series.hpp"
#include <ginac/ginac.h>
#include <iostream>
using namespace std;
using namespace GiNaC;

size_t order = 2;

int main()
{
    // Compute relevant primes
    map< size_t, set<KontsevichGraph> > primes;
    for (size_t n = 0; n <= order; ++n)
    {
        primes[n] = KontsevichGraph::graphs(n, 2, true, true,
                        [](KontsevichGraph g) -> bool
                        {
                            return g.positive_differential_order() && g.is_prime();
                        });
    }
    // Make a table of (symbolic) weights
    map<KontsevichGraph, symbol> weights;
    size_t weight_count = 0;
    for (size_t n = 0; n <= order; ++n)
    {
        for (KontsevichGraph g : primes[n])
        {
            weights[g] = symbol("w_" + to_string(weight_count++));
        }
    }
    KontsevichGraphSeries<symbol> star_product;
}

Append a size_t to a string in the correct way, using std::to_string.


/* * This file is part of meego-im-framework *
 *
 * Copyright (C) 2012 Mattia Barbon <mattia@develer.com>
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License version 2.1 as published by the Free Software Foundation
 * and appearing in the file LICENSE.LGPL included in the packaging
 * of this file.
 */

#include "mainwindow.h"

#include <QApplication>
#if (defined(Q_WS_QPA) || defined(Q_WS_QWS)) && (QT_VERSION < 0x050000)
#include <QInputContextFactory>
#endif

int main(int argc, char **argv)
{
    QApplication kit(argc, argv);
#if (defined(Q_WS_QPA) || defined(Q_WS_QWS)) && (QT_VERSION < 0x050000)
    // Workaround for lighthouse Qt
    kit.setInputContext(QInputContextFactory::create("Maliit", &kit));
#endif
    MainWindow settings;

    settings.show();
    kit.exec();
}

/* This file is part of Maliit framework
 *
 * Copyright (C) 2012 Mattia Barbon <mattia@develer.com>
 *
 * Contact: maliit-discuss@lists.maliit.org
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the licence, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the
 * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
 * Boston, MA 02111-1307, USA.
 */

#include "mainwindow.h"

#include <QApplication>
#if (defined(Q_WS_QPA) || defined(Q_WS_QWS)) && (QT_VERSION < 0x050000)
#include <QInputContextFactory>
#endif

int main(int argc, char **argv)
{
    QApplication kit(argc, argv);
#if (defined(Q_WS_QPA) || defined(Q_WS_QWS)) && (QT_VERSION < 0x050000)
    // Workaround for lighthouse Qt
    kit.setInputContext(QInputContextFactory::create("Maliit", &kit));
#endif
    MainWindow settings;

    settings.show();
    kit.exec();
}

Fix license in settings example.

Fix license in settings example.

RevBy: Jon Nordby


#define FPL_AUTO_NAMESPACE
#include <final_platform_layer.hpp>

int main(int argc, char **args) {
	Settings settings = DefaultSettings();
	CopyAnsiString("Software Rendering Example", settings.window.windowTitle, FPL_ARRAYCOUNT(settings.window.windowTitle) - 1);
	settings.video.driverType = VideoDriverType::Software;
	if (InitPlatform(InitFlags::Video, settings)) {
		VideoBackBuffer *videoContext = GetVideoBackBuffer();
		while (WindowUpdate()) {
			uint32_t *p = videoContext->pixels;
			for (uint32_t y = 0; y < videoContext->height; ++y) {
				uint32_t color = 0xFFFF0000;
				for (uint32_t x = 0; x < videoContext->width; ++x) {
					*p++ = color;
				}
			}
			WindowFlip();
		}
		ReleasePlatform();
	}
	return 0;
}

#define FPL_AUTO_NAMESPACE
#include <final_platform_layer.hpp>

struct RandomSeries {
	uint16_t index;
};

static uint16_t RandomU16(RandomSeries &series) {
	series.index ^= (series.index << 13);
    series.index ^= (series.index >> 9);
	series.index ^= (series.index << 7);
	return (series.index);
}

static uint8_t RandomByte(RandomSeries &series) {
	uint8_t result = RandomU16(series) % UINT8_MAX;
	return(result);
}

int main(int argc, char **args) {
	Settings settings = DefaultSettings();
	CopyAnsiString("Software Rendering Example", settings.window.windowTitle, FPL_ARRAYCOUNT(settings.window.windowTitle) - 1);
	settings.video.driverType = VideoDriverType::Software;
	if (InitPlatform(InitFlags::Video, settings)) {
		RandomSeries series = {1337};
		VideoBackBuffer *videoContext = GetVideoBackBuffer();
		while (WindowUpdate()) {
			uint32_t *p = videoContext->pixels;
			for (uint32_t y = 0; y < videoContext->height; ++y) {
				for (uint32_t x = 0; x < videoContext->width; ++x) {
					uint8_t r = RandomByte(series);
					uint8_t g = RandomByte(series);
					uint8_t b = RandomByte(series);
					uint32_t color = (0xFF << 24) | (r << 16) | (g << 8) | b;
					*p++ = color;
				}
			}
			WindowFlip();
		}
		ReleasePlatform();
	}
	return 0;
}

Use random for software rendering demo

Use random for software rendering demo


/*
 * 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 "SkFontHost.h"
#include "SkTypeface.h"
#include "SkTypeface_win.h"

//static
void SkFontHost::EnsureTypefaceAccessible(const SkTypeface& typeface) {
    //No sandbox, nothing to do.
}

/*
 * 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 "SkFontHost.h"
#include "SkTypeface.h"

//static
void SkFontHost::EnsureTypefaceAccessible(const SkTypeface& typeface) {
    //No sandbox, nothing to do.
}

Remove unneeded include which is breaking build.

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


#include "side_pane.hpp"

#include <cppurses/painter/color.hpp>
#include <cppurses/painter/glyph.hpp>
#include <cppurses/widget/widgets/text_display.hpp>

using namespace cppurses;

namespace demos {
namespace glyph_paint {

Side_pane::Side_pane() {
    this->width_policy.fixed(16);

    space1.wallpaper = L'─';
    space2.wallpaper = L'─';

    glyph_select.height_policy.preferred(6);
    color_select_stack.height_policy.fixed(3);

    for (auto& child : color_select_stack.top_row.children.get()) {
        child->brush.set_background(Color::Light_gray);
        child->brush.set_foreground(Color::Black);
    }

    show_glyph.height_policy.fixed(1);
    show_glyph.set_alignment(Alignment::Center);
}
}  // namespace glyph_paint
}  // namespace demos

#include "side_pane.hpp"

#include <cppurses/painter/color.hpp>
#include <cppurses/painter/glyph.hpp>
#include <cppurses/widget/widgets/text_display.hpp>

using namespace cppurses;

namespace demos {
namespace glyph_paint {

Side_pane::Side_pane() {
    this->width_policy.fixed(16);

    space1.wallpaper = L'─';
    space2.wallpaper = L'─';

    glyph_select.height_policy.preferred(6);
    color_select_stack.height_policy.fixed(3);

    show_glyph.height_policy.fixed(1);
    show_glyph.set_alignment(Alignment::Center);
}
}  // namespace glyph_paint
}  // namespace demos

Remove duplicate brush color set in glyph paint cycle box.


// Copyright (c) 2017 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 "quic/test_tools/failing_proof_source.h"

#include "absl/strings/string_view.h"

namespace quic {
namespace test {

void FailingProofSource::GetProof(const QuicSocketAddress& /*server_address*/,
                                  const QuicSocketAddress& /*client_address*/,
                                  const std::string& /*hostname*/,
                                  const std::string& /*server_config*/,
                                  QuicTransportVersion /*transport_version*/,
                                  absl::string_view /*chlo_hash*/,
                                  std::unique_ptr<Callback> callback) {
  callback->Run(false, nullptr, QuicCryptoProof(), nullptr);
}

QuicReferenceCountedPointer<ProofSource::Chain>
FailingProofSource::GetCertChain(const QuicSocketAddress& /*server_address*/,
                                 const QuicSocketAddress& /*client_address*/,
                                 const std::string& /*hostname*/,
                                 bool* /*cert_matched_sni*/) {
  return QuicReferenceCountedPointer<Chain>();
}

void FailingProofSource::ComputeTlsSignature(
    const QuicSocketAddress& /*server_address*/,
    const QuicSocketAddress& /*client_address*/,
    const std::string& /*hostname*/,
    uint16_t /*signature_algorithm*/,
    absl::string_view /*in*/,
    std::unique_ptr<SignatureCallback> callback) {
  callback->Run(false, "", nullptr);
}

}  // namespace test
}  // namespace quic

// Copyright (c) 2017 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 "quic/test_tools/failing_proof_source.h"

#include "absl/strings/string_view.h"

namespace quic {
namespace test {

void FailingProofSource::GetProof(const QuicSocketAddress& /*server_address*/,
                                  const QuicSocketAddress& /*client_address*/,
                                  const std::string& /*hostname*/,
                                  const std::string& /*server_config*/,
                                  QuicTransportVersion /*transport_version*/,
                                  absl::string_view /*chlo_hash*/,
                                  std::unique_ptr<Callback> callback) {
  callback->Run(false, nullptr, QuicCryptoProof(), nullptr);
}

QuicReferenceCountedPointer<ProofSource::Chain>
FailingProofSource::GetCertChain(const QuicSocketAddress& /*server_address*/,
                                 const QuicSocketAddress& /*client_address*/,
                                 const std::string& /*hostname*/,
                                 bool* cert_matched_sni) {
  *cert_matched_sni = false;
  return QuicReferenceCountedPointer<Chain>();
}

void FailingProofSource::ComputeTlsSignature(
    const QuicSocketAddress& /*server_address*/,
    const QuicSocketAddress& /*client_address*/,
    const std::string& /*hostname*/,
    uint16_t /*signature_algorithm*/,
    absl::string_view /*in*/,
    std::unique_ptr<SignatureCallback> callback) {
  callback->Run(false, "", nullptr);
}

}  // namespace test
}  // namespace quic

Fix an ASAN failure in //third_party/quic/core:tls_server_handshaker_test by always setting *cert_matched_sni in GetCertChain().

PiperOrigin-RevId: 395802856


#include <test/unit/math/test_ad.hpp>

TEST(MathMixMatFun, reverse) {
  auto f = [](const auto& x) { return stan::math::reverse(x); };

  // 0 x 0
  Eigen::VectorXd x0(0);
  stan::test::expect_ad(f, x0);

  // 1 x 1
  Eigen::VectorXd x1(1);
  x1 << 1;
  stan::test::expect_ad(f, x1);

  // 4 x 4
  Eigen::VectorXd x(4);
  x << 1, 3, 4, -5;
  stan::test::expect_ad(f, x);
}

#include <test/unit/math/test_ad.hpp>
#include <vector>

TEST(MathMixMatFun, reverse_vector) {
  auto f = [](const auto& x) { return stan::math::reverse(x); };

  // 0 x 0
  Eigen::VectorXd x0(0);
  stan::test::expect_ad(f, x0);

  // 1 x 1
  Eigen::VectorXd x1(1);
  x1 << 1;
  stan::test::expect_ad(f, x1);

  // 4 x 4
  Eigen::VectorXd x(4);
  x << 1, 3, 4, -5;
  stan::test::expect_ad(f, x);
}

TEST(MathMixMatFun, reverse_row_vector) {
  auto f = [](const auto& x) { return stan::math::reverse(x); };

  // 0 x 0
  Eigen::RowVectorXd x0(0);
  stan::test::expect_ad(f, x0);

  // 1 x 1
  Eigen::RowVectorXd x1(1);
  x1 << 1;
  stan::test::expect_ad(f, x1);

  // 4 x 4
  Eigen::RowVectorXd x(4);
  x << 1, 3, 4, -5;
  stan::test::expect_ad(f, x);
}

TEST(MathMixMatFun, reverse_array) {
  auto f = [](const auto& x) { return stan::math::reverse(x); };

  // 0 x 0
  std::vector<double> x0(0);
  stan::test::expect_ad(f, x0);

  // 1 x 1
  std::vector<double> x1{1};
  stan::test::expect_ad(f, x1);

  // 4 x 4
  std::vector<double> x{1, 3, 4, -5};
  stan::test::expect_ad(f, x);
}

Add tests for row vector and array

Add tests for row vector and array


#include "stdafx.h"
#include "CppUnitTest.h"
#include "../DNAnalyzerServer/Dictionnaire.h"
#include "../DNAnalyzerServer/Mots.h"
#include <exception>
#include <unordered_set>
#include <cstring>
#include <string>

using namespace Microsoft::VisualStudio::CppUnitTestFramework;

namespace DNAnalyzerServerTest
{
	TEST_CLASS(DictionnaireTest)
	{
	public:
		//ObtenirInstance
		TEST_METHOD(ObtenirInstance_NotNull)
		{
			// L'instance retourne ne doit pas tre null
			Assert::IsTrue(&(Dictionnaire::ObtenirInstance())!=(Dictionnaire*) nullptr);
		}

		TEST_METHOD(ObtenirInstance_SameReference)
		{
			// L'instance retourne doit toujours tre la mme
			Assert::IsTrue(&(Dictionnaire::ObtenirInstance()) == &(Dictionnaire::ObtenirInstance()));
		}
		TEST_METHOD(ObtenirMaladie_KnownMaladie) {

		}
		TEST_METHOD(ObtenirMaladie_UnKnownMaladie) {

		}
		TEST_METHOD(ObtenirMaladies_NoMaladies) {
			char motInexistant[] = "ATCGINEXISTANT";
			unsigned int indexMotInexistant = Mots::ObtenirInstance().InsererMot(motInexistant);
			const unordered_set<const Maladie*> resutat = Dictionnaire::ObtenirInstance().ObtenirMaladies(indexMotInexistant);
			Assert::AreEqual(resutat.size, 0);
		}
		TEST_METHOD(ObtenirMaladies_OneMaladies) {

		}
		TEST_METHOD(ObtenirMaladies_TwoMaladies) {

		}
		TEST_METHOD(ObtenirNomMaladies_EmptyDictionnaire) {

		}
		TEST_METHOD(ObtenirNomMaladies_NotEmptyDictionnaire) {

		}
	};
}

#include "stdafx.h"
#include "CppUnitTest.h"
#include "../DNAnalyzerServer/Dictionnaire.h"
#include <exception>
#include <cstring>

using namespace Microsoft::VisualStudio::CppUnitTestFramework;

namespace DNAnalyzerServerTest
{
	TEST_CLASS(DictionnaireTest)
	{
	public:
		//ObtenirInstance
		TEST_METHOD(ObtenirInstance_NotNull)
		{
			// L'instance retourne ne doit pas tre null
			Assert::IsTrue(&(Dictionnaire::ObtenirInstance())!=(Dictionnaire*) nullptr);
		}

		TEST_METHOD(ObtenirInstance_SameReference)
		{
			// L'instance retourne doit toujours tre la mme
			Assert::IsTrue(&(Dictionnaire::ObtenirInstance()) == &(Dictionnaire::ObtenirInstance()));
		}
	};
}

Revert "Ajout de methode de test (incomplete) de Dictionnaire"

This reverts commit 4a9fd803dd205891d3ed0866c4c64300c5ac27c7.


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

  Library:   CTK

  Copyright (c) 2010  Kitware 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.commontk.org/LICENSE

  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.

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

// Qt includes
#include <QApplication>

// CTK includes
#include "ctkDateRangeWidget.h"

// STD includes
#include <cstdlib>
#include <iostream>

//-----------------------------------------------------------------------------
int ctkDateRangeWidgetTest1(int argc, char * argv [] )
{
  QApplication app(argc, argv);

  ctkDateRangeWidget dateRange;

  dateRange.show();
  return EXIT_SUCCESS;
}

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

  Library:   CTK

  Copyright (c) 2010  Kitware 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.commontk.org/LICENSE

  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.

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

// Qt includes
#include <QApplication>
#include <QTimer>

// CTK includes
#include "ctkDateRangeWidget.h"

// STD includes
#include <cstdlib>
#include <iostream>

//-----------------------------------------------------------------------------
int ctkDateRangeWidgetTest1(int argc, char * argv [] )
{
  QApplication app(argc, argv);

  ctkDateRangeWidget dateRange;
  dateRange.show();
  dateRange.onToday();
  dateRange.onYesterday();
  dateRange.onAnyDate();
  dateRange.onLastMonth();
  dateRange.onLastWeek();
  dateRange.onSelectRange();

  return EXIT_SUCCESS;
}

Add extra date range widget tests

Add extra date range widget tests


#include <iostream>
#include "Crown.h"
#include "lua.hpp"
#include <unistd.h>

using namespace crown;

static void report_errors(lua_State* state, const int status)
{
  if (status != 0)
  {
    std::cerr << "-- " << lua_tostring(state, -1) << std::endl;

    lua_pop(state, 1);
  }
}

int main(int argc, char** argv)
{
  lua_State* lua_state;

  Filesystem fs("/home/mikymod/test/res_compiled");

  FileResourceArchive archive(fs);

  MallocAllocator allocator;

  ResourceManager res_manager(archive, allocator);

  ResourceId script = res_manager.load("lua/hello.lua");

  res_manager.flush();

  while (1)
  {
    if (res_manager.is_loaded(script))
    {

      lua_state = luaL_newstate();
      luaL_openlibs(lua_state);

      ScriptResource* resource = (ScriptResource*)res_manager.data(script);

      int s = luaL_loadbuffer(lua_state, (char*)resource->data(), 47, "");

      if (s == 0)
      {
        s = lua_pcall(lua_state, 0, LUA_MULTRET, 0);
      }

      report_errors(lua_state, s);

      break;
    }
  }

  lua_close(lua_state);

  return 0;
}

#include <iostream>
#include "Crown.h"
#include "lua.hpp"
#include <unistd.h>

using namespace crown;

static void report_errors(lua_State* state, const int status)
{
  if (status != 0)
  {
    std::cerr << "-- " << lua_tostring(state, -1) << std::endl;

    lua_pop(state, 1);
  }
}

int main(int argc, char** argv)
{
  lua_State* lua_state;

  Filesystem fs("/home/mikymod/test/res_compiled");

  FileResourceArchive archive(fs);

  ResourceManager res_manager(archive);

  ResourceId script = res_manager.load("lua/hello.lua");

  res_manager.flush();

  while (1)
  {
    if (res_manager.is_loaded(script))
    {

      lua_state = luaL_newstate();
      luaL_openlibs(lua_state);

      ScriptResource* resource = (ScriptResource*)res_manager.data(script);

      int s = luaL_loadbuffer(lua_state, (char*)resource->data(), 47, "");

      if (s == 0)
      {
        s = lua_pcall(lua_state, 0, LUA_MULTRET, 0);
      }

      report_errors(lua_state, s);

      break;
    }
  }

  lua_close(lua_state);

  return 0;
}

Fix building of the engine

Fix building of the engine


#include <Magick++/Functions.h>
#include <Magick++/ResourceLimits.h>
#include <Magick++/SecurityPolicy.h>

#ifndef FUZZ_MAX_SIZE
#define FUZZ_MAX_SIZE 2048
#endif

class FuzzingInitializer {
public:
  FuzzingInitializer() {
    Magick::InitializeMagick((const char *) NULL);
    Magick::SecurityPolicy::maxMemoryRequest(256000000);
    Magick::ResourceLimits::memory(1000000000);
    Magick::ResourceLimits::map(500000000);
    Magick::ResourceLimits::width(FUZZ_MAX_SIZE);
    Magick::ResourceLimits::height(FUZZ_MAX_SIZE);
    Magick::ResourceLimits::listLength(32);
  }
};

FuzzingInitializer fuzzingInitializer;

#if BUILD_MAIN
#include "encoder_format.h"

EncoderFormat encoderFormat;

#define FUZZ_ENCODER encoderFormat.get()
#endif // BUILD_MAIN

#include <Magick++/Functions.h>
#include <Magick++/ResourceLimits.h>
#include <Magick++/SecurityPolicy.h>

#ifndef FUZZ_MAX_SIZE
#define FUZZ_MAX_SIZE 2048
#endif

class FuzzingInitializer {
public:
  FuzzingInitializer() {

    // Disable SIMD in jpeg turbo.
    (void) putenv(const_cast<char *>("JSIMD_FORCENONE=1"));

    Magick::InitializeMagick((const char *) NULL);
    Magick::SecurityPolicy::maxMemoryRequest(256000000);
    Magick::ResourceLimits::memory(1000000000);
    Magick::ResourceLimits::map(500000000);
    Magick::ResourceLimits::width(FUZZ_MAX_SIZE);
    Magick::ResourceLimits::height(FUZZ_MAX_SIZE);
    Magick::ResourceLimits::listLength(32);
  }
};

FuzzingInitializer fuzzingInitializer;

#if BUILD_MAIN
#include "encoder_format.h"

EncoderFormat encoderFormat;

#define FUZZ_ENCODER encoderFormat.get()
#endif // BUILD_MAIN

Disable SIMD in jpeg turbo as suggested to check if that fixes the uninitialised memory issue.


#include "main_window.hpp"
#include <QVBoxLayout>
#include <QMessageBox>
#include "executable_viewer.hpp"

MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent)
{
    setWindowTitle(QString("Interactive Executable Mangler"));

    mdiArea = new QMdiArea();

    QVBoxLayout *layout = new QVBoxLayout();
    layout->addWidget(mdiArea);

    QMenu *file = menuBar()->addMenu(QString("File"));
    QWidget *central = new QWidget(this);
    central->setLayout(layout);
    setCentralWidget(central);

    createActions();

    file->addAction(newAction);
    file->addAction(aboutAction);
}

void MainWindow::createActions()
{
    newAction = new QAction(QString("New"), this);
    aboutAction = new QAction(QString("About"), this);
    connect(newAction, SIGNAL(triggered()), this, SLOT(newFile()));
    connect(aboutAction, SIGNAL(triggered()), this, SLOT(about()));
}

void MainWindow::newFile()
{
    QString filename("hacker.out");
    ExecutableViewer *viewer = new ExecutableViewer(filename, mdiArea);
    mdiArea->addSubWindow(viewer);
    viewer->show();
    mdiArea->tileSubWindows();
}

void MainWindow::about()
{
    QMessageBox::about(this, QString("About"),
        QString("
Ștefan Mirea & Adrian Dobrică 2016.

Click!
"));
}

#include "main_window.hpp"
#include <QMessageBox>
#include "executable_viewer.hpp"

MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent)
{
    setWindowTitle(QString("Interactive Executable Mangler"));

    mdiArea = new QMdiArea();

    QMenu *file = menuBar()->addMenu(QString("File"));
    setCentralWidget(mdiArea);

    createActions();

    file->addAction(newAction);
    file->addAction(aboutAction);
}

void MainWindow::createActions()
{
    newAction = new QAction(QString("New"), this);
    aboutAction = new QAction(QString("About"), this);
    connect(newAction, SIGNAL(triggered()), this, SLOT(newFile()));
    connect(aboutAction, SIGNAL(triggered()), this, SLOT(about()));
}

void MainWindow::newFile()
{
    QString filename("hacker.out");
    ExecutableViewer *viewer = new ExecutableViewer(filename, mdiArea);
    mdiArea->addSubWindow(viewer);
    viewer->show();
    mdiArea->tileSubWindows();
}

void MainWindow::about()
{
    QMessageBox::about(this, QString("About"),
        QString("
Ștefan Mirea & Adrian Dobrică 2016.

Click!
"));
}

Use mdiArea directly as the window's central widget


#include "common.th"

// c <- multiplicand
// d <- multiplier
// b -> product
.global imul
imul:
    pushall(h,i)

    i <- d == 0
    jnzrel(i, L_done)

L_top:
    h <- d & 1
    i <- h <> 0
    i <- c & i
    b <- b + i
    c <- c << 1
    d <- d >> 1
    i <- d <> 0
    jnzrel(i, L_top)

L_done:
    popall(h,i)
    ret

#include "common.th"

// c <- multiplicand
// d <- multiplier
// b -> product
.global imul
imul:
    pushall(h,i,j,k)

    i <- d == 0
    jnzrel(i, L_done)
    h <- 1
    b <- 0

    j <- c >> 31    // save sign bit in j
    j <- -j         // convert sign to flag
    c <- c ^ j      // adjust multiplicand
    c <- c - j

    k <- d >> 31    // save sign bit in k
    k <- -k         // convert sign to flag
    d <- d ^ k      // adjust multiplier
    d <- d - k

    j <- j ^ k      // final flip flag is in j

L_top:
    // use constant 1 in h to combine instructions
    i <- d & h - 1
    i <- c &~ i
    b <- b + i
    c <- c << 1
    d <- d >> 1
    i <- d <> 0
    jnzrel(i, L_top)

L_done:
    b <- b ^ j      // adjust product for signed math
    b <- b - j

    popall(h,i,j,k)
    ret

Support signed numbers in imul

Support signed numbers in imul


#include "UnitTest++/UnitTest++.h"

#include <fstream>
#include <cereal/archives/binary.hpp>

SUITE( CerealTest )
{
    TEST( basicSaveAndLoad )
    {
        const std::string saveFileName = "CerealTest";
        const int expectedData = 42;
        int actualData = 666;

        {
            std::ofstream file( saveFileName, std::ios::binary );
            CHECK( !file.fail() );

            cereal::BinaryOutputArchive archive( file );
            archive( expectedData );
        }

        {
            std::ifstream file( saveFileName, std::ios::binary );
            CHECK( !file.fail() );

            cereal::BinaryInputArchive archive( file );
            archive( actualData );
        }

        CHECK_EQUAL( expectedData, actualData );

        // Delete save file
        CHECK( !remove( saveFileName.data() ) ) ;
    }
}

#include "UnitTest++/UnitTest++.h"

#include <fstream>
#include <cereal/archives/binary.hpp>

class Base
{
    public:
        Base() : someConstant(1)
        {
        }

    private:
        const int someConstant;

        friend cereal::access;
        template < class Archive >
        void serialize( Archive & ar )
        {
            ar( const_cast< int & >( someConstant ) );
        }
};

SUITE( CerealTest )
{
    TEST( basicSaveAndLoad )
    {
        const std::string saveFileName = "CerealTest";
        const int expectedData = 42;
        int actualData = 666;

        {
            std::ofstream file( saveFileName, std::ios::binary );
            CHECK( !file.fail() );

            cereal::BinaryOutputArchive archive( file );
            archive( expectedData );
        }

        {
            std::ifstream file( saveFileName, std::ios::binary );
            CHECK( !file.fail() );

            cereal::BinaryInputArchive archive( file );
            archive( actualData );
        }

        CHECK_EQUAL( expectedData, actualData );

        // Delete save file
        CHECK( !remove( saveFileName.data() ) ) ;
    }

    TEST( loadConstantVariable )
    {
        const std::string saveFileName = "CerealTest";
        const int expectedData = 42;
        const int actualData = 666;

        {
            std::ofstream file( saveFileName, std::ios::binary );
            CHECK( !file.fail() );

            cereal::BinaryOutputArchive archive( file );
            archive( expectedData );
        }

        {
            std::ifstream file( saveFileName, std::ios::binary );
            CHECK( !file.fail() );

            cereal::BinaryInputArchive archive( file );
            archive( const_cast< int & >( actualData ) );
        }

        CHECK_EQUAL( expectedData, actualData );

        // Delete save file
        CHECK( !remove( saveFileName.data() ) ) ;
    }
}

Test cereal for loading a constant variable (using a const_cast)


#include "variables.hpp"

#ifdef _VARS
std::ostream& var_defs_stream = cerr;
#endif

#include "variables.hpp"

#ifdef _VARS
std::ostream& var_defs_stream = cout;
#endif

Print variable debug output to stdout

sat-solver: Print variable debug output to stdout

Printing them to stderr makes it hard to see them in the context of
regular program output when piping usually to "grep" or "less").


/* This file is part of the KDE libraries
   Copyright (C) 2003 Hamish Rodda <rodda@kde.org>
   Copyright (C) 2001 Christoph Cullmann <cullmann@kde.org>

   This library is free software; you can redistribute it and/or
   modify it under the terms of the GNU Library General Public
   License version 2 as published by the Free Software Foundation.

   This library is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
   Library General Public License for more details.

   You should have received a copy of the GNU Library General Public License
   along with this library; see the file COPYING.LIB.  If not, write to
   the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
   Boston, MA 02111-1307, USA.
*/

#include "editinterfaceext.h"
#include "document.h"

using namespace KTextEditor;

uint EditInterfaceExt::globalEditInterfaceExtNumber = 0;

EditInterfaceExt::EditInterfaceExt()
	: d(0L)
{
  globalEditInterfaceExtNumber++;
  myEditInterfaceExtNumber = globalEditInterfaceExtNumber;
}

EditInterfaceExt::~EditInterfaceExt()
{
}

uint EditInterfaceExt::editInterfaceExtNumber() const
{
  return myEditInterfaceExtNumber;
}

EditInterfaceExt *KTextEditor::editInterfaceExt (Document *doc)
{
  if (!doc)
    return 0;

  return static_cast<EditInterfaceExt*>(doc->qt_cast("KTextEditor::EditInterfaceExt"));
}

Add licence (yes, this means that editinterface.cpp has no licence)

svn path=/trunk/kdelibs/interfaces/ktexteditor/; revision=266753


#include "NMakefile.hpp"

#include <configure/Build.hpp>
#include <configure/Filesystem.hpp>
#include <configure/quote.hpp>

namespace configure { namespace generators {

	std::string NMakefile::name() const
	{ return "NMakefile"; }

	bool NMakefile::is_available(Build& build) const
	{
		return build.fs().which("nmake") != boost::none;
	}

	void NMakefile::dump_command(
		    std::ostream& out,
		    std::vector<std::string> const& cmd) const
	{
		out << quote<CommandParser::nmake>(cmd);
	}

	std::vector<std::string>
	NMakefile::build_command(Build& build, std::string const& target) const
	{
		return {
			"nmake", "-f", (build.directory() / "Makefile").string(),
			target.empty() ? "all" : target
		};
	}

}}

#include "NMakefile.hpp"

#include <configure/Build.hpp>
#include <configure/Filesystem.hpp>
#include <configure/quote.hpp>

namespace configure { namespace generators {

	std::string NMakefile::name() const
	{ return "NMakefile"; }

	bool NMakefile::is_available(Build& build) const
	{
		return build.fs().which("nmake") != boost::none;
	}

	void NMakefile::dump_command(
		    std::ostream& out,
		    std::vector<std::string> const& cmd) const
	{
		out << quote<CommandParser::nmake>(cmd);
	}

	std::vector<std::string>
	NMakefile::build_command(Build& build, std::string const& target) const
	{
		return {
			"nmake", "-nologo", "-f", (build.directory() / "Makefile").string(),
			target.empty() ? "all" : target
		};
	}

}}

Add -nologo in nmake command lines.

Add -nologo in nmake command lines.


#include "analyzer.h"

#include "dal.h"

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

namespace holmes {

kj::Promise<bool> Analyzer::run(DAL *dal) {
  std::vector<Holmes::Fact::Reader> searchedFacts;
  auto ctxs = dal->getFacts(premises);
  kj::Array<kj::Promise<bool>> analResults =
    KJ_MAP(ctx, ctxs) {
      if (cache.miss(ctx)) {
        auto req = analysis.analyzeRequest();
        auto ctxBuilder = req.initContext(ctx.size());
        auto dex = 0;
        for (auto&& val : ctx) {
          ctxBuilder.setWithCaveats(dex++, val);
        }
        return req.send().then([this, dal, ctx = kj::mv(ctx)](Holmes::Analysis::AnalyzeResults::Reader res){
          auto dfs = res.getDerived();
          bool dirty = false;
          if (dal->setFacts(dfs) != 0) {
            dirty = true;
          }
          cache.add(ctx);
          return dirty;
        });
      }
      return kj::Promise<bool>(false);
    };
  return kj::joinPromises(kj::mv(analResults)).then([this](kj::Array<bool> x){
    bool dirty = false;
    for (auto v : x) {
      dirty |= v;
    }
    return dirty;
  });
}

}

#include "analyzer.h"

#include "dal.h"

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

namespace holmes {

kj::Promise<bool> Analyzer::run(DAL *dal) {
  std::vector<Holmes::Fact::Reader> searchedFacts;
  DLOG(INFO) << "Starting analysis " << name;
  DLOG(INFO) << "Getting facts for " << name;
  auto ctxs = dal->getFacts(premises);
  DLOG(INFO) << "Got facts for " << name;
  kj::Array<kj::Promise<bool>> analResults =
    KJ_MAP(ctx, ctxs) {
      if (cache.miss(ctx)) {
        auto req = analysis.analyzeRequest();
        auto ctxBuilder = req.initContext(ctx.size());
        auto dex = 0;
        for (auto&& val : ctx) {
          ctxBuilder.setWithCaveats(dex++, val);
        }
        return req.send().then([this, dal, ctx = kj::mv(ctx)](Holmes::Analysis::AnalyzeResults::Reader res){
          auto dfs = res.getDerived();
          bool dirty = false;
          if (dal->setFacts(dfs) != 0) {
            dirty = true;
          }
          cache.add(ctx);
          return dirty;
        });
      }
      return kj::Promise<bool>(false);
    };
  return kj::joinPromises(kj::mv(analResults)).then([this](kj::Array<bool> x){
    bool dirty = false;
    for (auto v : x) {
      dirty |= v;
    }
    DLOG(INFO) << "Finished analysis " << name;
    return dirty;
  });
}

}

Add logging to analysis for profiling

Add logging to analysis for profiling


#include <PIDController.h>
#include <iostream>

using namespace std;

int main(int argc, char *argv[])
{
	PIDController* pid = new PIDController(1,0,0,-100,100);

    pid->on();
    pid->targetSetpoint(100);
    pid->off();

    cout << "Hello World!" << endl;

	return 0;
}

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

using namespace std;

int main(int argc, char *argv[])
{
	PIDController* pid = new PIDController(5,0.5,0.25,-100,100);

    pid->on(); // Turn PID controller on
    pid->targetSetpoint(10); // Change desired setpoint to 10

    double t = 0; // Init with time t=0
    double controlVariable = 0; // Init with zero actuation
    double processVariable = 0; // Init with zero position

    while(1) {
        controlVariable = pid->calc(processVariable); // Calculate next controlVariable
        processVariable += controlVariable/(20 + ((rand() % 11) - 5)); // Arbitrary function to simulate a plant

        cout << "Time: " << t << ", Setpoint: " << pid->getSetpoint() << ", PV: " << processVariable << endl;

        usleep(100000); // 100ms delay to simulate actuation time
        t += 0.1; // Increment time variable by 100ms
    }

	return 0;
}

Update example to be actually somewhat useful


#include "gtest/gtest.h"

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

#include "gtest/gtest.h"
#include "sodium.h"

int main(int argc, char **argv) {
  assert(sodium_init() != -1);
  testing::InitGoogleTest(&argc, argv);
  return RUN_ALL_TESTS();
}

Initialize libsodium in the gtest suite.


#include "../../include/core/StateCell.hpp"
#include "../../include/core/Cell.hpp"

bool StateCell::isState(StateCell* state) const
{
  return state == this; //All state are singletons, so if state has the same class as this, it is the same instance
}

EmptyCell::EmptyCell()
{}

EmptyCell* EmptyCell::instance = new EmptyCell();

EmptyCell* EmptyCell::emptyCell()
{
  return instance;
}

std::string EmptyCell::toString() const
{
  return "EmptyCell";
}

StateCell* EmptyCell::iterate(Cell const* cell)
{
  return AliveCell::aliveCell();
}

AliveCell::AliveCell()
{}

AliveCell* AliveCell::instance = new AliveCell();

AliveCell* AliveCell::aliveCell()
{
  return instance;
}

std::string AliveCell::toString() const
{
  return "AliveCell";
}

StateCell* AliveCell::iterate(Cell const* cell)
{
  return EmptyCell::emptyCell();
}

#include "../../include/core/StateCell.hpp"
#include "../../include/core/Cell.hpp"

bool StateCell::isState(StateCell* state) const
{
  return state == this; //All state are singletons, so if state has the same class as this, it is the same instance
}

EmptyCell::EmptyCell()
{}

EmptyCell* EmptyCell::instance = new EmptyCell();

EmptyCell* EmptyCell::emptyCell()
{
  return instance;
}

std::string EmptyCell::toString() const
{
  return "EmptyCell";
}

StateCell* EmptyCell::iterate(Cell const* cell)
{
  int nbAliveNeighbors(0);
  std::vector<Cell const*> neighbors = cell->getNeighbors();

  for(int i = 0; i < neighbors.size(); i++)
  {
    if(neighbors[i]->isState(AliveCell::aliveCell()))
    {
      nbAliveNeighbors++;
    }
  }

  if(nbAliveNeighbors > 2)
    return AliveCell::aliveCell();
  else
    return EmptyCell::emptyCell();
}

AliveCell::AliveCell()
{}

AliveCell* AliveCell::instance = new AliveCell();

AliveCell* AliveCell::aliveCell()
{
  return instance;
}

std::string AliveCell::toString() const
{
  return "AliveCell";
}

StateCell* AliveCell::iterate(Cell const* cell)
{
  int nbAliveNeighbors(0);
  std::vector<Cell const*> neighbors = cell->getNeighbors();

  for(int i = 0; i < neighbors.size(); i++)
  {
    if(neighbors[i]->isState(AliveCell::aliveCell()))
    {
      nbAliveNeighbors ++;
    }
  }

  if(nbAliveNeighbors < 2) //Solitude
    return EmptyCell::emptyCell();
  else if(nbAliveNeighbors > 3) //Surpopulation
    return EmptyCell::emptyCell();
  else
    return AliveCell::aliveCell();
}

Modify states methods to implement the game of life


#include <QtCore/QList>

struct SmallType {
    char a[8];
};

struct BigType {
    char a[9];
};

void foo()
{
    QList<BigType> bigT; // Warning
    QList<SmallType> smallT; // OK
}

class A {
public:
    void foo()
    {
        m_big.clear();
    }

    QList<BigType> m_big; // Warning
};

void foo1(QList<BigType> big2)
{
    QList<BigType> bigt; // Warning
    bigt = big2;
}

void test_bug358740()
{
    QList<int> list; // OK
    int a, b;
}

Add test-case for a bug report

inefficient-qlist: Add test-case for a bug report

CCBUG: 358740


// dllmain.cpp : Defines the entry point for the DLL application.
#include "stdafx.h"
#include "commctrl.h"
#include "accctrl.h"

BOOL APIENTRY DllMain(
    HMODULE hModule,
    DWORD  ul_reason_for_call,
    LPVOID lpReserved)
{
    switch (ul_reason_for_call)
    {
        case DLL_PROCESS_ATTACH:
        case DLL_THREAD_ATTACH:
        case DLL_THREAD_DETACH:
        case DLL_PROCESS_DETACH:
            break;
    }

    return TRUE;
}

// dllmain.cpp : Defines the entry point for the DLL application.
#include "stdafx.h"
#include "commctrl.h"
#include "accctrl.h"
#include "shellapi.h"
#include "shlobj.h"

BOOL APIENTRY DllMain(
    HMODULE hModule,
    DWORD  ul_reason_for_call,
    LPVOID lpReserved)
{
    switch (ul_reason_for_call)
    {
        case DLL_PROCESS_ATTACH:
        case DLL_THREAD_ATTACH:
        case DLL_THREAD_DETACH:
        case DLL_PROCESS_DETACH:
            break;
    }

    return TRUE;
}

Add shell includes to test project for searching purposes


#include "test.h"

// When defining a facility, it has to occur before including the logger.
#define VAST_LOG_FACILITY "test"
#include "vast/logger.h"

#if VAST_LOG_LEVEL >= 5

using namespace vast;

int foo()
{
  VAST_ENTER();
  VAST_RETURN(-1);
  return -1;
};

void bar(int i, std::string s, char c)
{
  VAST_ENTER(VAST_ARG(i, s, c));
  VAST_MSG("about to call foo");
  foo();
  VAST_LEAVE("leaving with a message");
};

BOOST_AUTO_TEST_CASE(logging_test)
{
  foo();
  bar(42, "***", 'A');
}

#endif

#include "test.h"

// When defining a facility, it has to occur before including the logger.
#define VAST_LOG_FACILITY "test"
#include "vast/logger.h"

#if VAST_LOG_LEVEL > 5

using namespace vast;

int foo()
{
  VAST_ENTER();
  VAST_RETURN(-1);
  return -1;
};

void bar(int i, std::string s, char c)
{
  VAST_ENTER(VAST_ARG(i, s, c));
  VAST_MSG("about to call foo");
  foo();
  VAST_LEAVE("leaving with a message");
};

BOOST_AUTO_TEST_CASE(logging_test)
{
  foo();
  bar(42, "***", 'A');
}

#endif

Define tracing unit tests with proper log level.


// FIXME: Same as test/asan/TestCases/Linux/odr-violation.cc ?
// XFAIL: android

// RUN: %clangxx_asan -fno-rtti -DBUILD_SO1 -fPIC -shared %s -o %t1.so
// RUN: %clangxx_asan -fno-rtti -DBUILD_SO2 -fPIC -shared %s -o %t2.so
// RUN: %clangxx_asan -fno-rtti %t1.so %t2.so %s -Wl,-R. -o %t
// RUN: %env_asan_opts=fast_unwind_on_malloc=0:detect_odr_violation=2 not %run %t 2>&1 | FileCheck %s

struct XYZ {
  virtual void foo();
};

#if defined(BUILD_SO1)

void XYZ::foo() {}

#elif defined(BUILD_SO2)

void XYZ::foo() {}

#else

int main() {}

#endif

// CHECK: AddressSanitizer: odr-violation
// CHECK-NEXT: 'vtable for XYZ'
// CHECK-NEXT: 'vtable for XYZ'

Disable ODR test on Android

[asan] Disable ODR test on Android

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


#include "PolarisBlock.h"

#include "Poco/Net/ServerSocket.h"
#include "Poco/Net/SocketReactor.h"
#include "Poco/Net/SocketAcceptor.h"
#include "PolarisConnection.h"

using Poco::Net::ServerSocket;
using Poco::Net::SocketReactor;
using Poco::Net::SocketAcceptor;
using Poco::Thread;

int main(int argc, char** argv) {
    return PolarisBlockApp().run(argc, argv);
}

int PolarisBlockApp::main(const std::vector<std::string> &args) {
    // Create + Bind socket
    ServerSocket blockSocket(12201); // TODO Config file / Argument / Whatever

    // Make the reactor
    SocketReactor reactor;

    // Assign the Connector
    SocketAcceptor<PolarisConnection> acceptor(blockSocket, reactor);

    Thread thread;
    logger().information("Starting reactor...");
    thread.start(reactor);

    waitForTerminationRequest();

    reactor.stop();
    thread.join();

    return Application::EXIT_OK;
}

#include "PolarisBlock.h"

#include "Poco/Net/ServerSocket.h"
#include "Poco/Net/SocketReactor.h"
#include "Poco/Net/SocketAcceptor.h"
#include "Poco/Thread.h"
#include "PolarisConnection.h"

using Poco::Net::ServerSocket;
using Poco::Net::SocketReactor;
using Poco::Net::SocketAcceptor;
using Poco::Thread;

int main(int argc, char** argv) {
    return PolarisBlockApp().run(argc, argv);
}

int PolarisBlockApp::main(const std::vector<std::string> &args) {
    // Create + Bind socket
    ServerSocket blockSocket(12201); // TODO Config file / Argument / Whatever

    // Make the reactor
    SocketReactor reactor;

    // Assign the Connector
    SocketAcceptor<PolarisConnection> acceptor(blockSocket, reactor);

    Thread thread;
    logger().information("Starting reactor...");
    thread.start(reactor);

    waitForTerminationRequest();

    reactor.stop();
    thread.join();

    return Application::EXIT_OK;
}

Add thread to fix gcc

Add thread to fix gcc


#include "quasigame.h"
#include "gamescene.h"

QuasiGame::QuasiGame(QQuickItem *parent)
    : QQuickItem(parent)
    , m_currentScene(0)
    , m_fps(DEFAULT_FPS)
{
    connect(&m_updateTimer, SIGNAL(timeout()), this, SLOT(onUpdate()));
    m_gameTime.start();
    m_updateTimer.start(1000 / m_fps);
}

GameScene *QuasiGame::currentScene() const {
    return m_currentScene;
}

void QuasiGame::setCurrentScene(GameScene *currentScene) {
    if (m_currentScene)
        disconnect(SIGNAL(update(long)));

    m_currentScene = currentScene;

    if (m_currentScene)
        connect(this, SIGNAL(update(long)), m_currentScene, SLOT(update(long)));

    emit currentSceneChanged();
}

int QuasiGame::fps() const
{
    return m_fps;
}

void QuasiGame::setFps(int fps)
{
    m_fps = fps;

    emit fpsChanged();
}

void QuasiGame::onUpdate()
{
    long elapsedTime = m_gameTime.restart();
    emit update(elapsedTime);
}

#include "quasigame.h"
#include "gamescene.h"

QuasiGame::QuasiGame(QQuickItem *parent)
    : QQuickItem(parent)
    , m_currentScene(0)
    , m_fps(DEFAULT_FPS)
{
    connect(&m_updateTimer, SIGNAL(timeout()), this, SLOT(onUpdate()));
    m_gameTime.start();
    m_updateTimer.start(1000 / m_fps);
}

GameScene *QuasiGame::currentScene() const {
    return m_currentScene;
}

void QuasiGame::setCurrentScene(GameScene *currentScene) {
    if (m_currentScene != currentScene) {
        if (m_currentScene)
            disconnect(SIGNAL(update(long)));

        m_currentScene = currentScene;

        if (m_currentScene)
            connect(this, SIGNAL(update(long)), m_currentScene, SLOT(update(long)));

        emit currentSceneChanged();
    }
}

int QuasiGame::fps() const
{
    return m_fps;
}

void QuasiGame::setFps(int fps)
{
    if (m_fps != fps) {
        m_fps = fps;

        emit fpsChanged();
    }
}

void QuasiGame::onUpdate()
{
    long elapsedTime = m_gameTime.restart();
    emit update(elapsedTime);
}

Check properties changes before emitting notify signal


#include "JNIRhodes.h"

#include "gapikey.h"

#include <common/rhoparams.h>

#undef DEFAULT_LOGCATEGORY
#define DEFAULT_LOGCATEGORY "MapView"

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

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

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

#include "JNIRhodes.h"

#include "gapikey.h"

#include <common/rhoparams.h>

#undef DEFAULT_LOGCATEGORY
#define DEFAULT_LOGCATEGORY "MapView"

extern "C" void alert_show_popup(char *);

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

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

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

Add alert when Google API key was not specified


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

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

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

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

#include "tensorflow/core/kernels/cwise_ops_common.h"

namespace tensorflow {

REGISTER6(UnaryOp, CPU, "Sinh", functor::sinh, float, double, bfloat16,
          Eigen::half, complex64, complex128);

#if GOOGLE_CUDA || TENSORFLOW_USE_ROCM
#if !defined(MLIR_GENERATED_GPU_KERNELS_ENABLED)
REGISTER3(UnaryOp, GPU, "Sinh", functor::sinh, float, double);
#endif
REGISTER(UnaryOp, GPU, "Sinh", functor::sinh, bfloat16)
#endif

}  // namespace tensorflow

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

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

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

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

#include "tensorflow/core/kernels/cwise_ops_common.h"

namespace tensorflow {

REGISTER6(UnaryOp, CPU, "Sinh", functor::sinh, float, double, bfloat16,
          Eigen::half, complex64, complex128);

#if GOOGLE_CUDA || TENSORFLOW_USE_ROCM
#if !defined(MLIR_GENERATED_GPU_KERNELS_ENABLED)
REGISTER3(UnaryOp, GPU, "Sinh", functor::sinh, Eigen::half, float, double);
#endif
REGISTER(UnaryOp, GPU, "Sinh", functor::sinh, bfloat16)
#endif

}  // namespace tensorflow

Fix registration of Sinh GPU Eigen kernel

PiperOrigin-RevId: 378123173
Change-Id: Ibcc42c7324fb30132790aa74b166d1807d717dd3


/* Include the SDL main definition header */
#include "SDL_main.h"

/*******************************************************************************
                 Functions called by JNI
*******************************************************************************/
#include <jni.h>

// Called before SDL_main() to initialize JNI bindings in SDL library
extern "C" void SDL_Android_Init(JNIEnv* env, jclass cls);

// Library init
extern "C" jint JNI_OnLoad(JavaVM* vm, void* reserved)
{
    return JNI_VERSION_1_4;
}

// Start up the SDL app
extern "C" void Java_org_libsdl_app_SDLActivity_nativeInit(JNIEnv* env, jclass cls, jobject obj)
{
    /* This interface could expand with ABI negotiation, calbacks, etc. */
    SDL_Android_Init(env, cls);

    /* Run the application code! */
    char *argv[2];
    argv[0] = strdup("SDL_app");
    argv[1] = NULL;
    SDL_main(1, argv);
}

/* Include the SDL main definition header */
#include "SDL_main.h"

/*******************************************************************************
                 Functions called by JNI
*******************************************************************************/
#include <jni.h>

// Called before SDL_main() to initialize JNI bindings in SDL library
extern "C" void SDL_Android_Init(JNIEnv* env, jclass cls);

// Library init
extern "C" jint JNI_OnLoad(JavaVM* vm, void* reserved)
{
    return JNI_VERSION_1_4;
}

// Start up the SDL app
extern "C" void Java_org_libsdl_app_SDLActivity_nativeInit(JNIEnv* env, jclass cls, jobject obj)
{
    /* This interface could expand with ABI negotiation, calbacks, etc. */
    SDL_Android_Init(env, cls);

    /* Run the application code! */
    int status;
    char *argv[2];
    argv[0] = strdup("SDL_app");
    argv[1] = NULL;
    status = SDL_main(1, argv);

    /* We exit here for consistency with other platforms. */
    exit(status);
}

/* vi: set ts=4 sw=4 expandtab: */

Make sure we shut down the app if SDL_main() returns instead of exiting.


/* $Id$ */

#include <grid/geometry_info.h>

// enable these lines for gcc2.95
//
//const unsigned int GeometryInfo<deal_II_dimension>::vertices_per_cell;
//const unsigned int GeometryInfo<deal_II_dimension>::lines_per_cell;
//const unsigned int GeometryInfo<deal_II_dimension>::quads_per_cell;
//const unsigned int GeometryInfo<deal_II_dimension>::hexes_per_cell;
//const unsigned int GeometryInfo<deal_II_dimension>::children_per_cell;

template <>
const unsigned int GeometryInfo<1>::opposite_face[GeometryInfo<1>::faces_per_cell]
= { 0, 1 };

template <>
const unsigned int GeometryInfo<2>::opposite_face[GeometryInfo<2>::faces_per_cell]
= { 2, 3, 0, 1 };

template <>
const unsigned int GeometryInfo<3>::opposite_face[GeometryInfo<3>::faces_per_cell]
= { 1, 0, 4, 5, 2, 3 };

/* $Id$ */

#include <grid/geometry_info.h>

const unsigned int GeometryInfo<deal_II_dimension>::vertices_per_cell;
const unsigned int GeometryInfo<deal_II_dimension>::lines_per_cell;
const unsigned int GeometryInfo<deal_II_dimension>::quads_per_cell;
const unsigned int GeometryInfo<deal_II_dimension>::hexes_per_cell;
const unsigned int GeometryInfo<deal_II_dimension>::children_per_cell;

template <>
const unsigned int GeometryInfo<1>::opposite_face[GeometryInfo<1>::faces_per_cell]
= { 0, 1 };

template <>
const unsigned int GeometryInfo<2>::opposite_face[GeometryInfo<2>::faces_per_cell]
= { 2, 3, 0, 1 };

template <>
const unsigned int GeometryInfo<3>::opposite_face[GeometryInfo<3>::faces_per_cell]
= { 1, 0, 4, 5, 2, 3 };

Use actual definitions of static variables.

git-svn-id: 31d9d2f6432a47c86a3640814024c107794ea77c@2445 0785d39b-7218-0410-832d-ea1e28bc413d


/*
 * 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 "SkFontHost.h"
#include "SkTypeface.h"
#include "SkTypeface_win.h"

//static
void SkFontHost::EnsureTypefaceAccessible(const SkTypeface& typeface) {
    //No sandbox, nothing to do.
}

/*
 * 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 "SkFontHost.h"
#include "SkTypeface.h"

//static
void SkFontHost::EnsureTypefaceAccessible(const SkTypeface& typeface) {
    //No sandbox, nothing to do.
}

Remove unneeded include which is breaking build.

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


#include "Example1.h"

#include <string.h>
#include <GLES3/gl3.h>
#include <jni.h>
#include <iostream>
#include <glm/gtc/matrix_transform.hpp>
#include <shader_program.h>

using namespace std;

bool
Example1::Init() {
}

void
Example1::onDraw() {
}

void
Example1::onShutdown() {
}

std::shared_ptr<Example1> application;

void applicationMain(FWPlatformBase * platform) {
	application = std::make_shared<Example1>(platform);
	platform->setApplication(application.get());
}

#include "Example1.h"

#include <string.h>
#include <GLES3/gl3.h>
#include <jni.h>
#include <iostream>
#include <glm/gtc/matrix_transform.hpp>
#include <shader_program.h>
#include <Context.h>
#include <AndroidPlatform.h>
#include <ContextAndroid.h>

using namespace std;

bool
Example1::Init() {
}

void
Example1::onDraw() {
}

void
Example1::onShutdown() {
}

std::shared_ptr<Example1> application;

void applicationMain(FWPlatformBase * platform) {
	application = std::make_shared<Example1>(platform);
	platform->setApplication(application.get());
}

Add includes to use debugging showCanvas


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

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

void move(const servo_msgs::IdBased::ConstPtr& msg) {
  auto degree = ics::Angle::newDegree(msg->angle);
  auto nowpos = driver->move(msg->id, degree);
  servo_msgs::IdBased result;
  result.id = msg->id;
  result.angle = nowpos;
  pub.publish(result);
}

int main(int argc, char** argv) {
  ros::init(argc, argv, "servo_krs_node");
  ros::NodeHandle n {};
  ros::NodeHandle pn {"~"};
  std::string path {"/dev/ttyUSB0"};
  pn.param<std::string>("path", path, path);
  try {
    ics::ICS3 ics {path.c_str()};
    driver = &ics;
  } catch (std::runtime_error e) {
    ROS_INFO("Error: Cannot make ICS3 instance [%s]", e.what());
    ROS_INFO("I tried open [%s]", path.c_str());
    return -1;
  }
  ros::Subscriber sub = n.subscribe("cmd_krs", 100, move);
  pub = n.advertise<servo_msgs::IdBased>("pose_krs", 10);
  ros::spin();
  return 0;
}

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

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

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

int main(int argc, char** argv) {
  ros::init(argc, argv, "servo_krs_node");
  ros::NodeHandle n {};
  ros::NodeHandle pn {"~"};
  std::string path {"/dev/ttyUSB0"};
  pn.param<std::string>("path", path, path);
  try {
    ics::ICS3 ics {path.c_str()};
    driver = &ics;
  } catch (std::runtime_error e) {
    ROS_INFO("Error: Cannot make ICS3 instance [%s]", e.what());
    ROS_INFO("I tried open [%s]", path.c_str());
    return -1;
  }
  ros::Subscriber sub = n.subscribe("cmd_krs", 100, move);
  pub = n.advertise<servo_msgs::IdBased>("pose_krs", 10);
  ros::spin();
  return 0;
}

Add try block for receive error on connection

On subscribe, ICS3 have connection of ics communication.
It mean exist USB adaptor but fail servo motor.
So we save connection.


//
// Created by dar on 1/25/16.
//

#include "GuiButton.h"

GuiButton::GuiButton(int x, int y, int width, int height) {
    this->x = x;
    this->y = y;
    this->width = width;
    this->height = height;
}

bool virtual GuiButton::onClick(int action, float x, float y) {
    if (onClickListener == NULL) return false;
    return onClickListener(action, x, y);
}

void virtual GuiButton::setOnClickListener(std::function<bool(int, float, float)> onClickListener) {
    this->onClickListener = onClickListener;
}

//
// Created by dar on 1/25/16.
//

#include "GuiButton.h"

GuiButton::GuiButton(int x, int y, int width, int height) {
    this->x = x;
    this->y = y;
    this->width = width;
    this->height = height;
}

bool GuiButton::onClick(int action, float x, float y) {
    if (onClickListener == NULL) return false;
    return onClickListener(action, x, y);
}

void GuiButton::setOnClickListener(std::function<bool(int, float, float)> onClickListener) {
    this->onClickListener = onClickListener;
}

Fix 'virtual out of class' error

Fix 'virtual out of class' error


// RUN: %clang_cc1 -fsyntax-only -verify -std=c++1z %s

namespace [[deprecated]] {}  // expected-warning {{'deprecated' attribute on anonymous namespace ignored}}

namespace [[deprecated]] N { // expected-note 4{{'N' has been explicitly marked deprecated here}}
  int X;
  int Y = X; // Ok
  int f();
}

int N::f() { // Ok
  return Y; // Ok
}

void f() {
  int Y = N::f(); // expected-warning {{'N' is deprecated}}
  using N::X; // expected-warning {{'N' is deprecated}}
  int Z = X; //Ok
}

void g() {
  using namespace N; // expected-warning {{'N' is deprecated}}
  int Z = Y; // Ok
}

namespace M = N; // expected-warning {{'N' is deprecated}}

// Shouldn't diag:
[[nodiscard, deprecated("")]] int PR37935();

Add regression test for PR37935.

Add regression test for PR37935.

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


#include "object/object.h"
#include "object/jsobject.h"
#include "object/function.h"
#include "parser/functionstatement.h"
#include "vm/instruction-builder.h"
#include "vm/instruction.h"
#include "vm/context.h"
#include "vm/vm.h"

namespace grok {
namespace parser {

using namespace grok::vm;
using namespace grok::obj;

/// emits code for function definition
/// We don't generate the code for the body now but defer it until
/// it is required i.e. when a call is placed to this function during
/// execution
void FunctionStatement::emit(std::shared_ptr<InstructionBuilder>)
{
    std::string Name = proto_->GetName();
    auto F = std::make_shared<Function>(std::move(body_), std::move(proto_));
    auto VS = GetVStore(GetGlobalVMContext());
    auto V = Value{};
    V.O = std::make_shared<Object>(F);
    VS->StoreValue(Name, V);
}

void FunctionPrototype::emit(std::shared_ptr<InstructionBuilder>)
{
    // do nothing
}

} // parser
} // grok

#include "object/object.h"
#include "object/jsobject.h"
#include "object/function.h"
#include "parser/functionstatement.h"
#include "vm/instruction-builder.h"
#include "vm/instruction.h"
#include "vm/context.h"
#include "vm/vm.h"

namespace grok {
namespace parser {

using namespace grok::vm;
using namespace grok::obj;

/// emits code for function definition
/// We don't generate the code for the body now but defer it until
/// it is required i.e. when a call is placed to this function during
/// execution
void FunctionStatement::emit(std::shared_ptr<InstructionBuilder> builder)
{
    std::string Name = proto_->GetName();
    auto F = std::make_shared<Function>(std::move(body_), std::move(proto_));
    auto VS = GetVStore(GetGlobalVMContext());

    if (Name.length()) {
        auto V = Value{};
        V.O = std::make_shared<Object>(F);
        VS->StoreValue(Name, V);
    }

    auto instr = InstructionBuilder::Create<Instructions::push>();
    instr->data_type_ = d_obj;
    instr->data_ = std::make_shared<Object>(F);

    builder->AddInstruction(std::move(instr));
}

void FunctionPrototype::emit(std::shared_ptr<InstructionBuilder>)
{
    // do nothing
}

} // parser
} // grok

Allow unnamed function and their assigning to other values


//@author A0097630B
#include "stdafx.h"
#include "query_executor.h"

namespace You {
namespace Controller {
namespace Internal {

QueryExecutor::QueryExecutor(std::unique_ptr<You::QueryEngine::Query>&& query) {
}

Result QueryExecutor::execute() {
	QueryEngine::Response response = QueryEngine::executeQuery(
		std::move(query));
	return processResponse(response);
}

}  // namespace Internal
}  // namespace Controller
}  // namespace You

//@author A0097630B
#include "stdafx.h"
#include "query_executor.h"

namespace You {
namespace Controller {
namespace Internal {

QueryExecutor::QueryExecutor(std::unique_ptr<You::QueryEngine::Query>&& query)
: query(std::move(query)) {
}

Result QueryExecutor::execute() {
	QueryEngine::Response response = QueryEngine::executeQuery(
		std::move(query));
	return processResponse(response);
}

}  // namespace Internal
}  // namespace Controller
}  // namespace You

Store the query that is to be executed later.


// Copyright eeGeo Ltd (2012-2015), All Rights Reserved

#include "WindowsInitialExperienceModule.h"
#include "WindowsInitialExperiencePreLoadModel.h"
#include "InitialExperienceIntroStep.h"
//#include "InitialExperienceSearchResultAttractModeModel.h"

namespace ExampleApp
{
    namespace InitialExperience
    {
        namespace SdkModel
        {
            WindowsInitialExperienceModule::WindowsInitialExperienceModule(
                WindowsNativeState& nativeState,
                PersistentSettings::IPersistentSettingsModel& persistentSettings,
                ExampleAppMessaging::TMessageBus& messageBus
            )
                : InitialExperienceModuleBase(persistentSettings)
                , m_nativeState(nativeState)
                , m_messageBus(messageBus)
                //, m_pInitialExperienceSearchResultAttractModeModule(NULL)
            {

            }

            WindowsInitialExperienceModule::~WindowsInitialExperienceModule()
            {
                //Eegeo_DELETE m_pInitialExperienceSearchResultAttractModeModule;
            }

            std::vector<IInitialExperienceStep*> WindowsInitialExperienceModule::CreateSteps(WorldAreaLoader::SdkModel::IWorldAreaLoaderModel &worldAreaLoaderModel)
            {
                std::vector<IInitialExperienceStep*> steps;

				// TODO: Recreate MEA initial experience steps for windows...

                return steps;
            }
        }
    }
}

// Copyright eeGeo Ltd (2012-2015), All Rights Reserved

#include "WindowsInitialExperienceModule.h"
#include "WindowsInitialExperiencePreLoadModel.h"
#include "InitialExperienceIntroStep.h"
//#include "InitialExperienceSearchResultAttractModeModel.h"
#include "WorldPinVisibility.h"

namespace ExampleApp
{
    namespace InitialExperience
    {
        namespace SdkModel
        {
            WindowsInitialExperienceModule::WindowsInitialExperienceModule(
                WindowsNativeState& nativeState,
                PersistentSettings::IPersistentSettingsModel& persistentSettings,
                ExampleAppMessaging::TMessageBus& messageBus
            )
                : InitialExperienceModuleBase(persistentSettings)
                , m_nativeState(nativeState)
                , m_messageBus(messageBus)
                //, m_pInitialExperienceSearchResultAttractModeModule(NULL)
            {

            }

            WindowsInitialExperienceModule::~WindowsInitialExperienceModule()
            {
                //Eegeo_DELETE m_pInitialExperienceSearchResultAttractModeModule;
            }

            std::vector<IInitialExperienceStep*> WindowsInitialExperienceModule::CreateSteps(WorldAreaLoader::SdkModel::IWorldAreaLoaderModel &worldAreaLoaderModel)
            {
                std::vector<IInitialExperienceStep*> steps;

				// TODO: Recreate MEA initial experience steps for windows...

				m_messageBus.Publish(WorldPins::WorldPinsVisibilityMessage(WorldPins::SdkModel::WorldPinVisibility::All));

                return steps;
            }
        }
    }
}

Fix for missing Hovercards in Windows. Buddy: Mark


#include "aboutwindow.h"
#include "ui_aboutwindow.h"

aboutWindow::aboutWindow(QString version, QWidget *parent) : QDialog(parent), ui(new Ui::aboutWindow)
{
    ui->setupUi(this);

	ui->labelCurrent->setText(version);
	m_version = version.replace(".", "").toInt();

	QNetworkAccessManager *m = new QNetworkAccessManager();
	connect(m, SIGNAL(finished(QNetworkReply*)), this, SLOT(finished(QNetworkReply*)));
	m->get(QNetworkRequest(QUrl("http://imgbrd-grabber.googlecode.com/svn/trunk/VERSION")));

	setFixedSize(400, 170);
}

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

void aboutWindow::finished(QNetworkReply *r)
{
	QString l = r->readAll();
	int latest = l.replace(".", "").toInt();
	if (latest <= m_version)
	{ ui->labelMessage->setText("
"+tr("Grabber est  jour")+"
"); }
	else
	{ ui->labelMessage->setText("
"+tr("Une nouvelle version est disponible : %1").arg(l)+"
"); }
}

#include "aboutwindow.h"
#include "ui_aboutwindow.h"

aboutWindow::aboutWindow(QString version, QWidget *parent) : QDialog(parent), ui(new Ui::aboutWindow)
{
    ui->setupUi(this);

	ui->labelCurrent->setText(version);
	m_version = version.replace(".", "").toInt();

	QNetworkAccessManager *m = new QNetworkAccessManager();
	connect(m, SIGNAL(finished(QNetworkReply*)), this, SLOT(finished(QNetworkReply*)));
	m->get(QNetworkRequest(QUrl("http://imgbrd-grabber.googlecode.com/svn/trunk/VERSION")));

	setFixedSize(400, 170);
}

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

void aboutWindow::finished(QNetworkReply *r)
{
	QString l = r->readAll(), last = l;
	int latest = last.replace(".", "").toInt();
	if (latest <= m_version)
	{ ui->labelMessage->setText("
"+tr("Grabber est  jour")+"
"); }
	else
	{ ui->labelMessage->setText("
"+tr("Une nouvelle version est disponible : %1").arg(l)+"
"); }
}

Fix last version writing in aboutWindow

Fix last version writing in aboutWindow


#include "enfa.h"

#include <string>

namespace tinygrep {

namespace enfa {

std::string EpsilonNFA::to_graph() const {
  return "";
}

}  // namespace enfa

}  // namespace tinygrep

#include "enfa.h"

#include <string>
#include <sstream>

namespace tinygrep {

namespace enfa {

// The default scale of a generated graph.
const unsigned int DEFAULT_PNG_SIZE = 10;
const std::string LABEL_BEGIN   = " [label=\"",
                  LABEL_END     = "\"]",
                  EDGE_ARROW    = " -> ",
                  STATE_PREFIX  = "q",
                  ENDLINE       = ";\n";

std::string EpsilonNFA::to_graph() const {
  const unsigned int png_size = DEFAULT_PNG_SIZE;
  std::stringstream output;
  output << "digraph epsilon_nfa {\n"
         << "rankdir=LR; size=\""
         << png_size << "," << png_size << "\""
         << ENDLINE;
  // add start state
  output << "foo [style = invis]"
         << ENDLINE;
  output << "node [shape = circle]; "
         << STATE_PREFIX << start_state_
         << ENDLINE;
  output << "foo" << EDGE_ARROW
         << STATE_PREFIX << start_state_
         << LABEL_BEGIN << "start" << LABEL_END
         << ENDLINE;
  // add accepting state
  output << "node [shape = doublecircle]; "
         << STATE_PREFIX << accept_state_
         << ENDLINE;
  // add remaining states
  output << "node [shape = circle]"
         << ENDLINE;
  // add transitions
  for (state_type from = 0; from < state_count_; from++) {
    // epsilon-transitions
    for (state_type to : epsilon_transitions_[from]) {
      output << STATE_PREFIX << from
             << EDGE_ARROW
             << STATE_PREFIX << to
             << LABEL_BEGIN << LABEL_END
             << ENDLINE;
    }
    // literal-transitions
    for (Transition transition : literal_transitions_[from]) {
      output << STATE_PREFIX << from
             << EDGE_ARROW
             << STATE_PREFIX << transition.target
             << LABEL_BEGIN << transition.literal << LABEL_END
             << ENDLINE;
    }
  }
  output << "}\n";
  return output.str();
}

}  // namespace enfa

}  // namespace tinygrep

Complete function for parsing epsilon-NFA -> .gv file.


#include <gtest/gtest.h>
#include <rapidxml_utils.hpp>

#include "llvm/compiler.hpp"
#include "parser/xmlParser.hpp"

class LLVMCompilerTest: public ::testing::Test {
protected:
  XMLParser xpx = XMLParser();

  inline rapidxml::file<> xmlFile(std::string path) {
    #define Q(x) #x
    #define QUOTE(x) Q(x)
    path = QUOTE(DATA_PARENT_DIR) + ("/" + path);
    #undef QUOTE
    #undef Q
    return rapidxml::file<>(path.c_str());
  }

  inline void noThrowOnCompile(std::string xmlFilePath) {
    xpx.parse(xmlFile(xmlFilePath));
    CompileVisitor::Link visitor = CompileVisitor::create(globalContext, xmlFilePath, xpx.getTree());
    try {
      visitor->visit();
    } catch (InternalError& err) {
      EXPECT_NO_THROW(throw InternalError(err));
      println(err.what());
    }
    visitor->getModule()->dump();
  }
};

TEST_F(LLVMCompilerTest, ExitCodes) {
  noThrowOnCompile("data/llvm/exit_code.xml");
  noThrowOnCompile("data/llvm/stored_return.xml");
}

TEST_F(LLVMCompilerTest, Declarations) {
  noThrowOnCompile("data/llvm/primitive.xml");
}

TEST_F(LLVMCompilerTest, Branches) {
  noThrowOnCompile("data/llvm/if.xml");
  noThrowOnCompile("data/llvm/if-else.xml");
  noThrowOnCompile("data/llvm/else-if.xml");
}

#include <gtest/gtest.h>
#include <rapidxml_utils.hpp>

#include "llvm/compiler.hpp"
#include "parser/xmlParser.hpp"

class LLVMCompilerTest: public ::testing::Test {
protected:
  XMLParser xpx = XMLParser();

  inline rapidxml::file<> xmlFile(std::string path) {
    path = DATA_PARENT_DIR + ("/" + path);
    return rapidxml::file<>(path.c_str());
  }

  inline void noThrowOnCompile(std::string xmlFilePath) {
    xpx.parse(xmlFile(xmlFilePath));
    CompileVisitor::Link visitor = CompileVisitor::create(globalContext, xmlFilePath, xpx.getTree());
    try {
      visitor->visit();
    } catch (InternalError& err) {
      EXPECT_NO_THROW(throw InternalError(err));
      println(err.what());
    }
    visitor->getModule()->dump();
  }
};

TEST_F(LLVMCompilerTest, ExitCodes) {
  noThrowOnCompile("data/llvm/exit_code.xml");
  noThrowOnCompile("data/llvm/stored_return.xml");
}

TEST_F(LLVMCompilerTest, Declarations) {
  noThrowOnCompile("data/llvm/primitive.xml");
}

TEST_F(LLVMCompilerTest, Branches) {
  noThrowOnCompile("data/llvm/if.xml");
  noThrowOnCompile("data/llvm/if-else.xml");
  noThrowOnCompile("data/llvm/else-if.xml");
}

Revert "Fixed command line macro's missing quotes"

This reverts commit 6c97b96c36b8a0d526a8fc543514f4dea33243b4.


#include "Timer.hpp"

using namespace HomieInternals;

Timer::Timer()
: _initialTime(0)
, _interval(0)
, _tickAtBeginning(false) {
}

void Timer::setInterval(uint32_t interval, bool tickAtBeginning) {
  _interval = interval;
  _tickAtBeginning = tickAtBeginning;

  this->reset();
}

bool Timer::check() const {
  if (_tickAtBeginning && _initialTime == 0) return true;
  if (millis() - _initialTime >= _interval) return true;

  return false;
}

void Timer::reset() {
  if (tickAtBeginning) {
    _initialTime = 0;
  } else {
    this->tick();
  }
}

void Timer::tick() {
  _initialTime = millis();
}

#include "Timer.hpp"

using namespace HomieInternals;

Timer::Timer()
: _initialTime(0)
, _interval(0)
, _tickAtBeginning(false) {
}

void Timer::setInterval(uint32_t interval, bool tickAtBeginning) {
  _interval = interval;
  _tickAtBeginning = tickAtBeginning;

  this->reset();
}

bool Timer::check() const {
  if (_tickAtBeginning && _initialTime == 0) return true;
  if (millis() - _initialTime >= _interval) return true;

  return false;
}

void Timer::reset() {
  if (_tickAtBeginning) {
    _initialTime = 0;
  } else {
    this->tick();
  }
}

void Timer::tick() {
  _initialTime = millis();
}

:bug: Add missing underscore - fix last commit