#include"qca.h"
#include<stdio.h>

int main(int argc, char **argv)
{
	QCA::Initializer init;
	QCString cs = (argc >= 2) ? argv[1] : "hello";

	if( !QCA::isSupported("sha1") )
		printf("SHA1 not supported!\n");
	else {
		QCA::SHA1 sha1Hash;
		QString result = sha1Hash.hashToString(cs);
		printf("sha1(\"%s\") = [%s]\n", cs.data(), result.latin1());
	}

	if( !QCA::isSupported("md5") )
		printf("MD5 not supported!\n");
	else {
		QCA::MD5 md5Hash;
		QString result = md5Hash.hashToString(cs);
		printf("md5(\"%s\") = [%s]\n", cs.data(), result.latin1());
	}

	return 0;
}

#include"qca.h"
#include<stdio.h>

int main(int argc, char **argv)
{
	QCA::Initializer init;
	QCString cs = (argc >= 2) ? argv[1] : "hello";

	if( !QCA::isSupported("sha1") )
		printf("SHA1 not supported!\n");
	else {
		QString result = QCA::SHA1().hashToString(cs);
		printf("sha1(\"%s\") = [%s]\n", cs.data(), result.latin1());
	}

	if( !QCA::isSupported("md5") )
		printf("MD5 not supported!\n");
	else {
		QString result = QCA::MD5().hashToString(cs);
		printf("md5(\"%s\") = [%s]\n", cs.data(), result.latin1());
	}

	return 0;
}

Update to use static versions.

Update to use static versions.

svn path=/trunk/kdesupport/qca/; revision=359801


#include "catch.hpp"

#include "StringToInteger.hpp"

TEST_CASE("String To Integer") {
  Solution s;

  SECTION("Normal tests") {
    REQUIRE(s.myAtoi("1") == 1);
  }

  SECTION("Normal tests 2") {
    REQUIRE(s.myAtoi("    010") == 10);
  }
}

#include "catch.hpp"

#include "StringToInteger.hpp"

TEST_CASE("String To Integer") {
  Solution s;

  SECTION("Normal tests") {
    REQUIRE(s.myAtoi("1") == 1);
    REQUIRE(s.myAtoi("378") == 378);
    REQUIRE(s.myAtoi("-239") == -239);
    REQUIRE(s.myAtoi("+832") == 832);
  }

  SECTION("Boundary tests") {
    REQUIRE(s.myAtoi("-2147483648") == -2147483648);
    REQUIRE(s.myAtoi("-2147483649") == -2147483648);
    REQUIRE(s.myAtoi("2147483647") == 2147483647);
    REQUIRE(s.myAtoi("2147483648") == 2147483647);
  }

  SECTION("Format tests") {
    REQUIRE(s.myAtoi("asdfasf") == 0);
    REQUIRE(s.myAtoi("--124") == 0);
    REQUIRE(s.myAtoi("++4") == 0);
    REQUIRE(s.myAtoi("    +110?_+120__") == 110);
  }
}

Update Problem 8 test case

Update Problem 8 test case


#include "component.h"
#include "entity.h"
#include "gtest/gtest.h"

/*
class TestC : public aronnax::Component {
  public:
    void update(aronnax::Entity &entity, const uint32_t dt)
    {
      return;
    }

    std::string getType()
    {
      return "TestComponent";
    }
};

class EntityTest : public testing::Test {
protected:

  virtual void SetUp() {
  }

  // Declares the variables your tests want to use.
  aronnax::Components cla_;
  aronnax::Entity ea_;
};
*/

TEST(Entity, DefaultConstructor) {
  const aronnax::Components cla_;
  const aronnax::Entity ea_(cla_);
  EXPECT_EQ(0, ea_.pos.x) << "Constructs with position as 0 by default";
  EXPECT_EQ(0, ea_.pos.y);
  EXPECT_EQ(0, ea_.box.x);
  EXPECT_EQ(0, ea_.box.y);
  EXPECT_EQ(0, ea_.v.x);
  EXPECT_EQ(0, ea_.v.y);
}

#include "component.h"
#include "entity.h"
#include "gtest/gtest.h"

/*
class TestC : public aronnax::Component {
  public:
    void update(aronnax::Entity &entity, const uint32_t dt)
    {
      return;
    }

    std::string getType()
    {
      return "TestComponent";
    }
};
*/

class EntityTest : public testing::Test {
protected:

  virtual void SetUp() {
    ea_ = new aronnax::Entity(cla_);
  }

  // Declares the variables your tests want to use.
  aronnax::Components cla_;
  aronnax::Entity* ea_;
};

TEST_F(EntityTest, DefaultConstructor) {
  EXPECT_EQ(0, ea_->pos.x) << "Constructs with position as 0 by default";
  EXPECT_EQ(0, ea_->pos.y);
  EXPECT_EQ(0, ea_->box.x);
  EXPECT_EQ(0, ea_->box.y);
  EXPECT_EQ(0, ea_->v.x);
  EXPECT_EQ(0, ea_->v.y);
}

Change entity test to use fixtures

Change entity test to use fixtures

This allows me to reuse thes same data structures in teh tests.


#include "orderinginfo.h"
#include "defs.h"
#include "eval.h"
#include <cstring>

OrderingInfo::OrderingInfo(const TranspTable* tt) {
  _tt = tt;
  _ply = 0;
  std::memset(_history, 0, sizeof(_history));
}

void OrderingInfo::incrementHistory(Color color, int from, int to, int depth) {
  _history[color][from][to] += depth^2;
}

int OrderingInfo::getHistory(Color color, int from, int to) const {
  return _history[color][from][to];
}

void OrderingInfo::incrementPly() {
  _ply++;
}

void OrderingInfo::deincrementPly() {
  _ply--;
}

int OrderingInfo::getPly() const {
  return _ply;
}

const TranspTable* OrderingInfo::getTt() const {
  return _tt;
}

void OrderingInfo::updateKillers(int ply, Move move) {
  _killer2[ply] = _killer1[ply];
  _killer1[ply] = move;
}

Move OrderingInfo::getKiller1(int ply) const {
  return _killer1[ply];
}

Move OrderingInfo::getKiller2(int ply) const {
  return _killer2[ply];
}

#include "orderinginfo.h"
#include "defs.h"
#include "eval.h"
#include <cstring>

OrderingInfo::OrderingInfo(const TranspTable* tt) {
  _tt = tt;
  _ply = 0;
  std::memset(_history, 0, sizeof(_history));
}

void OrderingInfo::incrementHistory(Color color, int from, int to, int depth) {
  _history[color][from][to] += depth*depth;
}

int OrderingInfo::getHistory(Color color, int from, int to) const {
  return _history[color][from][to];
}

void OrderingInfo::incrementPly() {
  _ply++;
}

void OrderingInfo::deincrementPly() {
  _ply--;
}

int OrderingInfo::getPly() const {
  return _ply;
}

const TranspTable* OrderingInfo::getTt() const {
  return _tt;
}

void OrderingInfo::updateKillers(int ply, Move move) {
  _killer2[ply] = _killer1[ply];
  _killer1[ply] = move;
}

Move OrderingInfo::getKiller1(int ply) const {
  return _killer1[ply];
}

Move OrderingInfo::getKiller2(int ply) const {
  return _killer2[ply];
}

Fix incorrect operator in OrderingInfo

Fix incorrect operator in OrderingInfo

XOR is not the same thing as exponentiation


#include <utils/unique_alias.hpp>

#include <atomic>
#include <chrono>
#include <sstream>

static std::atomic<int> __counter(0);

utils::unique_alias::unique_alias()
{
    std::ostringstream s;

    s << "benchmarks-"
      << std::chrono::duration_cast<std::chrono::seconds>(
             std::chrono::steady_clock::now().time_since_epoch())
             .count()
      << "-" << __counter++ << "-000000";

    _string = s.str();
}

void utils::unique_alias::set_watermark(unsigned long iteration)
{
    size_t index = _string.size();
    for (int digit = 0; digit < 6; digit++)
    {
        _string[--index] = '0' + (iteration & 63);
        iteration /= 64;
    }
}

#include <utils/unique_alias.hpp>

#include <atomic>
#include <chrono>
#include <sstream>

static std::atomic<int> __counter(0);

static const char __base64[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";

utils::unique_alias::unique_alias()
{
    std::ostringstream s;

    s << "benchmarks-"
      << std::chrono::duration_cast<std::chrono::seconds>(std::chrono::steady_clock::now().time_since_epoch()).count()
      << "-" << __counter++ << "-AAAAAA"; // reserve 6 chars for the watermark

    _string = s.str();
}

void utils::unique_alias::set_watermark(unsigned long iteration)
{
    size_t index = _string.size();
    for (int digit = 0; digit < 6; digit++)
    {
        _string[--index] = __base64[iteration & 63];
        iteration /= 64;
    }
}

Use proper base 64 encoding for the watermark


#include "utf8_string.hpp"

#include "../std/iterator.hpp"

#include "../3party/utfcpp/source/utf8/unchecked.h"

namespace utf8_string
{
  bool Split(string const & str, vector<string> & out, IsDelimiterFuncT f)
  {
    out.clear();
    string::const_iterator curr = str.begin();
    string::const_iterator end = str.end();
    string word;
    back_insert_iterator<string> inserter = back_inserter(word);
    while (curr != end)
    {
      uint32_t symbol = ::utf8::unchecked::next(curr);
      if (f(symbol))
      {
        if (!word.empty())
        {
          out.push_back(word);
          word.clear();
          inserter = back_inserter(word);
        }
      }
      else
      {
        inserter = utf8::unchecked::append(symbol, inserter);
      }
    }
    if (!word.empty())
      out.push_back(word);
    return !out.empty();
  }

  bool IsSearchDelimiter(uint32_t symbol)
  {
    // latin table optimization
    if (symbol >= ' ' && symbol < '0')
      return true;

    switch (symbol)
    {
    case ':':
    case ';':
    case '[':
    case ']':
    case '\\':
    case '^':
    case '_':
    case '`':
    case '{':
    case '}':
    case '|':
    case '~':
    case 0x0336:
      return true;
    }
    return false;
  }
}

#include "utf8_string.hpp"

#include "../std/iterator.hpp"

#include "../3party/utfcpp/source/utf8/unchecked.h"

namespace utf8_string
{
  bool Split(string const & str, vector<string> & out, IsDelimiterFuncT f)
  {
    out.clear();
    string::const_iterator curr = str.begin();
    string::const_iterator end = str.end();
    string word;
    back_insert_iterator<string> inserter = back_inserter(word);
    while (curr != end)
    {
      uint32_t symbol = ::utf8::unchecked::next(curr);
      if (f(symbol))
      {
        if (!word.empty())
        {
          out.push_back(word);
          word.clear();
          inserter = back_inserter(word);
        }
      }
      else
      {
        inserter = utf8::unchecked::append(symbol, inserter);
      }
    }
    if (!word.empty())
      out.push_back(word);
    return !out.empty();
  }

  bool IsSearchDelimiter(uint32_t symbol)
  {
    // latin table optimization
    if (symbol >= ' ' && symbol < '0')
      return true;

    switch (symbol)
    {
    case ':':
    case ';':
    case '<':
    case '=':
    case '>':
    case '[':
    case ']':
    case '\\':
    case '^':
    case '_':
    case '`':
    case '{':
    case '}':
    case '|':
    case '~':
    case 0x0336:
      return true;
    }
    return false;
  }
}

Add '<', '=', '>' as search delimeters.

Add '<', '=', '>' as search delimeters.


// Copyright (C) 2012-2015 Leap Motion, Inc. All rights reserved.
#include "stdafx.h"
#include <autowiring/observable.h>

class ObservableTest:
  public testing::Test
{};

TEST_F(ObservableTest, SimpleAssignmentCheck) {
  autowiring::observable<int> ob;

  bool hit = false;
  ob.onChanged += [&hit] { hit = true; };
  ob = 2;
  ASSERT_TRUE(hit) << "OnChanged handler not hit when the observable value was modified";
}

TEST_F(ObservableTest, BeforeAndAfter) {
  autowiring::observable<int> ob;
  ob = 8;

  bool hit = false;
  ob.onChanged += [&hit] { hit = true; };

  int obBefore = 0;
  int obAfter = 0;
  ob.onBeforeChanged += [&] (const int& before, const int& after) {
    obBefore = before;
    obAfter = after;
  };

  ob = 9;

  ASSERT_TRUE(hit) << "Change notification not raised";
  ASSERT_EQ(8, obBefore) << "\"Before\" value in onBeforeChanged was not correct";
  ASSERT_EQ(9, obAfter) << "\"AfFter\" value in onBeforeChanged was not correct";
}

// Copyright (C) 2012-2015 Leap Motion, Inc. All rights reserved.
#include "stdafx.h"
#include <autowiring/observable.h>

class ObservableTest:
  public testing::Test
{};

TEST_F(ObservableTest, SimpleAssignmentCheck) {
  autowiring::observable<int> ob;

  bool hit = false;
  ob.onChanged += [&hit] { hit = true; };
  ob = 2;
  ASSERT_TRUE(hit) << "OnChanged handler not hit when the observable value was modified";
  ASSERT_EQ(2, *ob) << "operator * gives an incorrect value";
}

TEST_F(ObservableTest, BeforeAndAfter) {
  autowiring::observable<int> ob;
  ob = 8;

  bool hit = false;
  ob.onChanged += [&hit] { hit = true; };

  int obBefore = 0;
  int obAfter = 0;
  ob.onBeforeChanged += [&] (const int& before, const int& after) {
    obBefore = before;
    obAfter = after;
  };

  ob = 9;

  ASSERT_TRUE(hit) << "Change notification not raised";
  ASSERT_EQ(8, obBefore) << "\"Before\" value in onBeforeChanged was not correct";
  ASSERT_EQ(9, obAfter) << "\"AfFter\" value in onBeforeChanged was not correct";
}

Add a test case for operator *

Add a test case for operator *


#include "SVGImage.h"

#define NANOSVG_IMPLEMENTATION
#include <nanosvg.h>

SVGImage::SVGImage() : _nanoSvgImage(nullptr) {
}

SVGImage::SVGImage(const boost::filesystem::path &path) : SVGImage() {
    open(path);
}

SVGImage::~SVGImage() {
    if (_nanoSvgImage) {
	::nsvgDelete(_nanoSvgImage);
    }
    _nanoSvgImage = nullptr;
}

bool SVGImage::open(const boost::filesystem::path &path) {
    _nanoSvgImage = ::nsvgParseFromFile(path.string().c_str(), "", 72.f);
    return (_nanoSvgImage->width > 0.0f && _nanoSvgImage->height > 0.0 && _nanoSvgImage->shapes);
}

void SVGImage::draw() {
}

#include "SVGImage.h"

#define NANOSVG_IMPLEMENTATION
#include <nanosvg.h>
#include <nanovg.h>
// XXX This is bad, but easy.
#define NANOVG_GL_IMPLEMENTATION
#include <GLES2/gl2.h>
#include <GLES2/gl2ext.h>
#include <GLES2/gl2platform.h>
#include <nanovg_gl.h>
#include <nanovg.c>

SVGImage::SVGImage() : _nanoSvgImage(nullptr) {
}

SVGImage::SVGImage(const boost::filesystem::path &path) : SVGImage() {
    open(path);
}

SVGImage::~SVGImage() {
    if (_nanoSvgImage) {
	::nsvgDelete(_nanoSvgImage);
    }
    _nanoSvgImage = nullptr;
}

bool SVGImage::open(const boost::filesystem::path &path) {
    _nanoSvgImage = ::nsvgParseFromFile(path.string().c_str(), "", 72.f);
    return (_nanoSvgImage->width > 0.0f && _nanoSvgImage->height > 0.0 && _nanoSvgImage->shapes);
}

void SVGImage::draw() {
}

Add some headers so we can use NanoVG to render NanoSVG.


#include <cppfs/FileEventHandler.h>

#include <cppfs/FileHandle.h>

namespace cppfs
{

FileEventHandler::FileEventHandler()
{
}

FileEventHandler::~FileEventHandler()
{
}

void FileEventHandler::onFileEvent(FileHandle & fh, FileEvent event)
{
    if (event & FileCreated) {
        onFileCreated(fh);
    } else if (event & FileRemoved) {
        onFileRemoved(fh);
    } else if (event & FileModified) {
        onFileModified(fh);
    }
}

void FileEventHandler::onFileCreated(FileHandle &)
{
}

void FileEventHandler::onFileRemoved(FileHandle &)
{
}

void FileEventHandler::onFileModified(FileHandle &)
{
}

} // namespace cppfs

#include <cppfs/FileEventHandler.h>

#include <cppfs/FileHandle.h>

namespace cppfs
{

FileEventHandler::FileEventHandler()
{
}

FileEventHandler::~FileEventHandler()
{
}

void FileEventHandler::onFileEvent(FileHandle & fh, FileEvent event)
{
    switch (event) {
        case FileCreated:
            onFileCreated(fh);
            break;

        case FileRemoved:
            onFileRemoved(fh);
            break;

        case FileModified:
            onFileModified(fh);
            break;

        default:
            break;
    }
}

void FileEventHandler::onFileCreated(FileHandle &)
{
}

void FileEventHandler::onFileRemoved(FileHandle &)
{
}

void FileEventHandler::onFileModified(FileHandle &)
{
}

} // namespace cppfs

Remove bit field logic where not necessary


#include "LinearEllipticPDE.hpp"

double f1(Point const & point) {
	return point.x() * point.x();
}

double f2(Point const & point) {
	return point.y() * point.y();
}

int main() {
	// laplace
	ConstTensor I(3, 0.);
	I(0, 0) = I(1, 1) = I(2, 2) = 1.;
	LinearEllipticPDE LaplacesEquation3D(I, 0., zeroFunc);
	std::cout << "div(D grad u) = f, D:" << '\n';
	LaplacesEquation3D.diffusionTensor().save(std::cout);
	std::cout << "f(0, 0, 0): " << LaplacesEquation3D.forceTerm(Point()) << std::endl;
	// my problem example
	Tensor D(2);
	//D.load(std::cin);
	D(0, 0) = f1;
	D(1, 1) = f2;
	D(0, 1) = zeroFunc;
	NonLinearEllipticPDE MyEqn2D(D, f1, zeroFunc);
	Point dummy(1., 2.);
	std::cout << "Coeff of u_{xx}, u_{yy} etc. at (1, 2):" << '\n';
	MyEqn2D.diffusionTensor(dummy).save(std::cout);
	std::cout << "gamma(1, 2): " << MyEqn2D.gamma(dummy) << '\n'
			  << "f(1, 2): " << MyEqn2D.forceTerm(dummy) << std::endl;
	return 0;
}

#include "LinearEllipticPDE.hpp"
#include "BC.hpp"

double g(Point const & point) { // u = g on Г
	return point.x() * point.y();
}

int main() {
	// Laplace's eqn on the plane
	ConstTensor I(2, 0.);
	I(0, 0) = I(1, 1) = 1.;
	LinearEllipticPDE LaplacesEquation2D(I, 0., zeroFunc);
	BC myBC(g); // simple Dirichlet problem
	std::cout << "u(2, 3) = " << myBC.dirichlet(Point(2., 3.)) << std::endl;
	return 0;
}

Add example of creating BC for Laplaces eqn


#include "level.hpp"

using namespace engine;

void Level::load(){
  for(auto game_object : objects){
    std::cout << "Loading " << game_object->name << std::endl;
    game_object->load();
    for(auto hit : game_object->get_hitboxes()){
      hit->initialize();
    }
  }
}

void Level::free(){
  for(auto game_object : objects){
    std::cout << "Freeing" << game_object->name << std::endl;
    game_object->free();
  }
  EventHandler::listeners.clear();
}

void Level::draw(){
  for(auto game_object : objects){
    if(game_object->is_active()){
      game_object->draw();
    }
  }
}

#include "level.hpp"
#include <iostream>

using namespace engine;

void Level::load(){
  for(auto game_object : objects){
    std::cout << "Loading " << game_object->name << std::endl;
    game_object->load();
    for(auto hit : game_object->get_hitboxes()){
      hit->initialize();
    }
  }
}

void Level::free(){
  for(auto game_object : objects){
    std::cout << "Freeing" << game_object->name << std::endl;
    game_object->free();
  }
  EventHandler::listeners.clear();
}

void Level::draw(){
  for(auto game_object : objects){
    if(game_object->is_active()){
      if(game_object->name == "arm_left"){
        game_object->set_actual_animation(game_object->animations["left_arm"]);
      }

      game_object->draw();
    }
  }
}

Fix wrong animation of boss arm

Fix wrong animation of boss arm

Signed-off-by: Matheus Miranda <6faf3a473c1bf7863f2eb74400dd6142ec07131e@gmail.com>


//
// Copyright (C) Alexandr Vorontsov. 2017
// Distributed under the MIT License (license terms are at http://opensource.org/licenses/MIT).
//

#include "stdafx.h"

#include <Kioto.h>

#include <windows.h>

void OnEngineInited()
{
    Kioto::Scene* scene = new Kioto::Scene();
    Kioto::SetScene(scene);
    OutputDebugStringA("init engine");
}

int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE prevInstance, PSTR cmdLine, int nCmdShow)
{
    Kioto::KiotoMain(hInstance, prevInstance, cmdLine, nCmdShow, L"Kioto game", OnEngineInited);
    return 0;
}

//
// Copyright (C) Alexandr Vorontsov. 2017
// Distributed under the MIT License (license terms are at http://opensource.org/licenses/MIT).
//

#include "stdafx.h"

#include <Kioto.h>

#include <windows.h>

class TestScene : public Kioto::Scene
{
public:
    ~TestScene()
    {
    }
};

class TestSceneSystem : public Kioto::SceneSystem
{
public:
    void Update(float32 dt) override
    {
    }
    ~TestSceneSystem()
    {
    }
};

void OnEngineInited()
{
    Kioto::Scene* scene = new TestScene();
    scene->AddSystem(new TestSceneSystem{});
    Kioto::SetScene(scene);
}

int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE prevInstance, PSTR cmdLine, int nCmdShow)
{
    Kioto::KiotoMain(hInstance, prevInstance, cmdLine, nCmdShow, L"Kioto game", OnEngineInited);
    return 0;
}

Add test scene with test scene system.

Add test scene with test scene system.


#include "InputHandler.h"
#include "SFML/Window.hpp"
#include "SFData.h"

Player::Direction InputHandler::LastInput;
int InputHandler::InputTime;
bool InputHandler::WindowClosed = false;

void InputHandler::PollEvents()
{
    sf::Event event;
    while (SFData::Window->pollEvent(event))
    {
		switch (event.type)
		{
			case sf::Event::KeyPressed:
				Player::Direction newInput = -1;
				switch (event.key.code)
				{
					case sf::Keyboard::W:
						newInput = Player::Up;
						break;
					case sf::Keyboard::A:
						newInput = Player::Left;
						break;
					case sf::Keyboard::S:
						newInput = Player::Down;
						break;
					case sf::Keyboard::D:
						newInput = Player::Right;
						break;
					default:
						continue;
				}
				if (newInput != LastInput)
				{
					LastInput = newInput;
					InputTime = -1;
				}
				break;
			case sf::Event::Closed:
				WindowClosed = true;
				break;
		}
	}
	InputTime++;
}

#include "InputHandler.h"
#include "SFML/Window.hpp"
#include "SFData.h"

Player::Direction InputHandler::LastInput;
int InputHandler::InputTime;
bool InputHandler::WindowClosed = false;

void InputHandler::PollEvents()
{
    sf::Event event;
    while (SFData::Window->pollEvent(event))
    {
		switch (event.type)
		{
			case sf::Event::KeyPressed:
				Player::Direction newInput = (Player::Direction)-1;
				switch (event.key.code)
				{
					case sf::Keyboard::W:
						newInput = Player::Up;
						break;
					case sf::Keyboard::A:
						newInput = Player::Left;
						break;
					case sf::Keyboard::S:
						newInput = Player::Down;
						break;
					case sf::Keyboard::D:
						newInput = Player::Right;
						break;
					default:
						continue;
				}
				LastInput = newInput;
				InputTime = -1;
				break;
			case sf::Event::Closed:
				WindowClosed = true;
				break;
		}
	}
	InputTime++;
}

Allow repeated input to reset frame counter


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

#include "content/test/unittest_test_suite.h"

#include "base/logging.h"
#include "base/test/test_suite.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebKit.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/platform/WebKitPlatformSupport.h"

// A stubbed out WebKit platform support impl.
class UnitTestTestSuite::UnitTestWebKitPlatformSupport
    : public WebKit::WebKitPlatformSupport {
 public:
  UnitTestWebKitPlatformSupport() {}
  virtual ~UnitTestWebKitPlatformSupport() {}
  virtual void cryptographicallyRandomValues(unsigned char* buffer,
                                             size_t length) OVERRIDE {
    memset(buffer, 0, length);
  }
};

UnitTestTestSuite::UnitTestTestSuite(base::TestSuite* test_suite)
    : test_suite_(test_suite) {
  DCHECK(test_suite);
  webkit_platform_support_.reset(new UnitTestWebKitPlatformSupport);
  WebKit::initialize(webkit_platform_support_.get());
}

UnitTestTestSuite::~UnitTestTestSuite() {
  WebKit::shutdown();
}

int UnitTestTestSuite::Run() {
  return test_suite_->Run();
}

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

#include "content/test/unittest_test_suite.h"

#include "base/logging.h"
#include "base/test/test_suite.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebKit.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/platform/WebKitPlatformSupport.h"

// A stubbed out WebKit platform support impl.
class UnitTestTestSuite::UnitTestWebKitPlatformSupport
    : public WebKit::WebKitPlatformSupport {
 public:
  UnitTestWebKitPlatformSupport() {}
  virtual ~UnitTestWebKitPlatformSupport() {}
  virtual void cryptographicallyRandomValues(unsigned char* buffer,
                                             size_t length) OVERRIDE {
    memset(buffer, 0, length);
  }
  virtual const unsigned char* getTraceCategoryEnabledFlag(
      const char* categoryName) {
    // Causes tracing macros to be disabled.
    static const unsigned char kEnabled = 0;
    return &kEnabled;
  }
};

UnitTestTestSuite::UnitTestTestSuite(base::TestSuite* test_suite)
    : test_suite_(test_suite) {
  DCHECK(test_suite);
  webkit_platform_support_.reset(new UnitTestWebKitPlatformSupport);
  WebKit::initialize(webkit_platform_support_.get());
}

UnitTestTestSuite::~UnitTestTestSuite() {
  WebKit::shutdown();
}

int UnitTestTestSuite::Run() {
  return test_suite_->Run();
}

Implement required tracing API for UnitTestWebKitPlatformSupport.

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

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


#include "vm/vm.hpp"

#include "util/thread.hpp"
#include "gc/managed.hpp"
#include "shared_state.hpp"

namespace rubinius {
  thread::ThreadData<ManagedThread*> _current_thread;

  ManagedThread::ManagedThread(uint32_t id, SharedState& ss, ManagedThread::Kind kind)
    : shared_(ss)
    , kind_(kind)
    , name_(kind == eRuby ? "<ruby>" : "<system>")
    , id_(id)
  {}

  ManagedThread* ManagedThread::current() {
    return _current_thread.get();
  }

  void ManagedThread::set_current(ManagedThread* th) {
    th->os_thread_ = pthread_self();
    _current_thread.set(th);
  }
}

#include "vm/vm.hpp"

#include "util/thread.hpp"
#include "gc/managed.hpp"
#include "shared_state.hpp"

namespace rubinius {
  thread::ThreadData<ManagedThread*> _current_thread;

  ManagedThread::ManagedThread(uint32_t id, SharedState& ss, ManagedThread::Kind kind)
    : shared_(ss)
    , kind_(kind)
    , name_(kind == eRuby ? "<ruby>" : "<system>")
    , run_state_(eIndependent)
    , id_(id)
  {}

  ManagedThread* ManagedThread::current() {
    return _current_thread.get();
  }

  void ManagedThread::set_current(ManagedThread* th) {
    th->os_thread_ = pthread_self();
    _current_thread.set(th);
  }
}

Add missing initialization of ManagedThread::run_state_


// Copyright 2013 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 "ozone/wayland/inputs/input_method_event_filter.h"

#include "ui/base/ime/input_method.h"
#include "ui/base/ime/input_method_factory.h"

namespace ozonewayland {

////////////////////////////////////////////////////////////////////////////////
// InputMethodEventFilter, public:

WaylandInputMethodEventFilter::WaylandInputMethodEventFilter()
    : input_method_(ui::CreateInputMethod(this, NULL)) {
  // TODO(yusukes): Check if the root window is currently focused and pass the
  // result to Init().
  input_method_->Init(true);
}

WaylandInputMethodEventFilter::~WaylandInputMethodEventFilter()
{
}

////////////////////////////////////////////////////////////////////////////////
// InputMethodEventFilter, ui::InputMethodDelegate implementation:

bool WaylandInputMethodEventFilter::DispatchKeyEventPostIME(
    const base::NativeEvent& event)
{
}

bool WaylandInputMethodEventFilter::DispatchFabricatedKeyEventPostIME(
    ui::EventType type,
    ui::KeyboardCode key_code,
    int flags)
{
}

}  // namespace ozonewayland

// Copyright 2013 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 "ozone/wayland/inputs/input_method_event_filter.h"

#include "ui/base/ime/input_method.h"
#include "ui/base/ime/input_method_factory.h"

namespace ozonewayland {

////////////////////////////////////////////////////////////////////////////////
// InputMethodEventFilter, public:

WaylandInputMethodEventFilter::WaylandInputMethodEventFilter()
    : input_method_(ui::CreateInputMethod(this, 0)) {
  // TODO(yusukes): Check if the root window is currently focused and pass the
  // result to Init().
  input_method_->Init(true);
}

WaylandInputMethodEventFilter::~WaylandInputMethodEventFilter()
{
}

////////////////////////////////////////////////////////////////////////////////
// InputMethodEventFilter, ui::InputMethodDelegate implementation:

bool WaylandInputMethodEventFilter::DispatchKeyEventPostIME(
    const base::NativeEvent& event)
{
}

bool WaylandInputMethodEventFilter::DispatchFabricatedKeyEventPostIME(
    ui::EventType type,
    ui::KeyboardCode key_code,
    int flags)
{
}

}  // namespace ozonewayland

Work around a build error in a very hackish way.

ui::CreateInputMethod()'s second parameter is not a pointer. 0 does not make
things much better either, but this is an area we are not particularly
interested in at the moment.


#include "../http/client-channel.hh"
#include "http-call.hh"
#include "json.hh"

namespace mimosa
{
namespace rpc
{

bool httpCall(const std::string               &url,
              const google::protobuf::Message &request,
              google::protobuf::Message       *response)
{
    http::ClientChannel cc;
    http::RequestWriter::Ptr rw = new http::RequestWriter(cc);

    /* request header */
    rw->setUrl(url);
    rw->setMethod(http::kMethodPost);
    rw->setProto(1, 1);
    rw->setContentLength(request.ByteSize());
    rw->setContentType("application/json");
    if (!rw->sendRequest())
        return false;

    /* request body (JSON) */
    jsonEncode(rw.get(), request);

    /* decode response */
    auto rr = rw->response();
    if (!rr)
        return false;

    if (response)
        jsonDecode(rr.get(), response);

    return true;
}

}
}

#include "../stream/string-stream.hh"
#include "../stream/copy.hh"
#include "../http/client-channel.hh"
#include "http-call.hh"
#include "json.hh"

namespace mimosa
{
namespace rpc
{

bool httpCall(const std::string               &url,
              const google::protobuf::Message &request,
              google::protobuf::Message       *response)
{
    http::ClientChannel cc;
    http::RequestWriter::Ptr rw = new http::RequestWriter(cc);

    /* request body (JSON) */
    stream::StringStream::Ptr data = new stream::StringStream;
    jsonEncode(data.get(), request);

    /* request header */
    rw->setUrl(url);
    rw->setMethod(http::kMethodPost);
    rw->setProto(1, 1);
    rw->setContentType("application/json");
    rw->setContentLength(data->str().size());
    if (!rw->sendRequest())
        return false;

    stream::copy(*data, *rw);

    /* decode response */
    auto rr = rw->response();
    if (!rr)
        return false;

    if (response)
        jsonDecode(rr.get(), response);

    return true;
}

}
}

Make a full json buffer first

Make a full json buffer first


// %llvmgcc %s -S -o -
namespace std {
  class exception { };

  class type_info {
  public:
    virtual ~type_info();
  };

}

namespace __cxxabiv1 {
  class __si_class_type_info : public std::type_info {
    ~__si_class_type_info();
  };
}

class recursive_init: public std::exception {
public:
  virtual ~recursive_init() throw ();
};

recursive_init::~recursive_init() throw() { }

// RUN: %llvmgcc %s -S -o -
namespace std {
  class exception { };

  class type_info {
  public:
    virtual ~type_info();
  };

}

namespace __cxxabiv1 {
  class __si_class_type_info : public std::type_info {
    ~__si_class_type_info();
  };
}

class recursive_init: public std::exception {
public:
  virtual ~recursive_init() throw ();
};

recursive_init::~recursive_init() throw() { }

Add a RUN: line so this test doesn't fail.

git-svn-id: 0ff597fd157e6f4fc38580e8d64ab130330d2411@26790 91177308-0d34-0410-b5e6-96231b3b80d8


// RUN: clang-tidy %s -- --serialize-diagnostics %t | FileCheck %s
// CHECK: :[[@LINE+1]]:12: error: expected ';' after struct [clang-diagnostic-error]
struct A {}

// RUN: clang-tidy -checks=-*,llvm-namespace-comment %s -- -serialize-diagnostics %t | FileCheck %s
// CHECK: :[[@LINE+1]]:12: error: expected ';' after struct [clang-diagnostic-error]
struct A {}

[clang-tidy] Make a test independent of the default check set.

git-svn-id: a34e9779ed74578ad5922b3306b3d80a0c825546@223232 91177308-0d34-0410-b5e6-96231b3b80d8


//===- AlphaSubtarget.cpp - Alpha Subtarget Information ---------*- C++ -*-===//
//
//                     The LLVM Compiler Infrastructure
//
// This file was developed by Andrew Lenharth and is distributed under the
// University of Illinois Open Source License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file implements the Alpha specific subclass of TargetSubtarget.
//
//===----------------------------------------------------------------------===//

#include "AlphaSubtarget.h"
#include "Alpha.h"
#include "llvm/Module.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Target/SubtargetFeature.h"
#include "AlphaGenSubtarget.inc"
using namespace llvm;

enum {
  FeatureKVSize = sizeof(FeatureKV) / sizeof(SubtargetFeatureKV),
  SubTypeKVSize = sizeof(SubTypeKV) / sizeof(SubtargetFeatureKV)
};

AlphaSubtarget::AlphaSubtarget(const Module &M, const std::string &FS)
  : HasF2I(false), HasCT(false) {
  std::string CPU = "generic";
  uint32_t Bits =
    SubtargetFeatures::Parse(FS, CPU,
                             SubTypeKV, SubTypeKVSize,
                             FeatureKV, FeatureKVSize);
  HasF2I = (Bits & FeatureFIX) != 0;
  HasCT  = (Bits & FeatureCIX) != 0;
}

//===- AlphaSubtarget.cpp - Alpha Subtarget Information ---------*- C++ -*-===//
//
//                     The LLVM Compiler Infrastructure
//
// This file was developed by Andrew Lenharth and is distributed under the
// University of Illinois Open Source License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file implements the Alpha specific subclass of TargetSubtarget.
//
//===----------------------------------------------------------------------===//

#include "AlphaSubtarget.h"
#include "Alpha.h"
#include "AlphaGenSubtarget.inc"
using namespace llvm;

AlphaSubtarget::AlphaSubtarget(const Module &M, const std::string &FS)
  : HasF2I(false), HasCT(false) {
  std::string CPU = "generic";
  uint32_t Bits =
    SubtargetFeatures::Parse(FS, CPU,
                             SubTypeKV, SubTypeKVSize,
                             FeatureKV, FeatureKVSize);
  HasF2I = (Bits & FeatureFIX) != 0;
  HasCT  = (Bits & FeatureCIX) != 0;
}

Simplify this due to changes in the tblgen side

git-svn-id: 0ff597fd157e6f4fc38580e8d64ab130330d2411@23908 91177308-0d34-0410-b5e6-96231b3b80d8


#include "lcd.h"
#include <TFT.h>  // Arduino LCD library

// pin definition for LCD
#define LCD_CS   10
#define LCD_DC   9
#define LCD_RST  8

namespace LCD {
  TFT TFTscreen = TFT(LCD_CS, LCD_DC, LCD_RST);

  void setup() {
    // initialize the display
    TFTscreen.begin();
    // clear the screen with a black background
    TFTscreen.background(0, 0, 0);
    // set the font color to white
    TFTscreen.stroke(255, 255, 255);
  }

  void clearScreen() {
    // clear the screen to show refreshed data
    TFTscreen.background(0, 0, 0);
  }

  void displayTemp(int tempInt) {
    char tempChar[6];
    snprintf(tempChar, sizeof tempChar, "%d", tempInt);
    // print temp text
    TFTscreen.text(tempChar, 0, 20);
  }
}

#include "display.h"
#include "sensor.h"
#include <LiquidCrystal.h>  // Arduino LCD library
#include <Arduino.h>  // enables use of byte pics

// pin definition for LCD
#define LCD_CS   10
#define LCD_DC   9
#define LCD_RST  8

namespace LCD {
  TFT TFTscreen = TFT(LCD_CS, LCD_DC, LCD_RST);

  void setup() {
    // initialize the display
    TFTscreen.begin();
    // clear the screen with a black background
    TFTscreen.background(0, 0, 0);
    // set the font color to white
    TFTscreen.stroke(255, 255, 255);
  }

  void clearScreen() {
    // clear the screen to show refreshed data
    TFTscreen.background(0, 0, 0);
  }

  void displayTemp(int tempInt) {
    char tempChar[6];
    snprintf(tempChar, sizeof tempChar, "%d", tempInt);
    // print temp text
    TFTscreen.text(tempChar, 0, 20);
  }
}

Update libraries to reflect screen hardware change


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

#include "content/public/browser/android/devtools_auth.h"

#include "base/logging.h"

namespace content {

bool CanUserConnectToDevTools(uid_t uid, gid_t gid) {
  struct passwd* creds = getpwuid(uid);
  if (!creds || !creds->pw_name) {
    LOG(WARNING) << "DevTools: can't obtain creds for uid " << uid;
    return false;
  }
  if (gid == uid &&
      (strcmp("root", creds->pw_name) == 0 ||  // For rooted devices
       strcmp("shell", creds->pw_name) == 0)) {  // For non-rooted devices
    return true;
  }
  LOG(WARNING) << "DevTools: connection attempt from " << creds->pw_name;
  return false;
}

}  // namespace content

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

#include "content/public/browser/android/devtools_auth.h"

#include <unistd.h>
#include <sys/types.h>

#include "base/logging.h"

namespace content {

bool CanUserConnectToDevTools(uid_t uid, gid_t gid) {
  struct passwd* creds = getpwuid(uid);
  if (!creds || !creds->pw_name) {
    LOG(WARNING) << "DevTools: can't obtain creds for uid " << uid;
    return false;
  }
  if (gid == uid &&
      (strcmp("root", creds->pw_name) == 0 ||   // For rooted devices
       strcmp("shell", creds->pw_name) == 0 ||  // For non-rooted devices
       uid == getuid())) {  // From processes signed with the same key
    return true;
  }
  LOG(WARNING) << "DevTools: connection attempt from " << creds->pw_name;
  return false;
}

}  // namespace content

[Android] Allow connections from the same user to DevTools server socket

Allow connections to DevTools web debugging socket from the apps that run under
the same UID than the browser app process itself. This requires signing the
corresponding APK with the same keys than the browser app.

BUG=398357

Review URL: https://codereview.chromium.org/425013002

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


#include "../src/utility.h"
#include "../src/HDD/HardDrive.h"

void unittest(){
    const size_t emptyOff = 0x80120;

    HDD first(1,true);
    first.init();

    int data[1000];
    for(int i = 0 ; i < 1000 ; ++i){
        data[i] = i;
    }
    first.writeaddr(emptyOff,&data,4*1000);
    int res;
    first.readaddr(emptyOff + 4 *42,&res,4);
    printf("%d\n",res);
    first.readaddr(emptyOff + 4 *999,&res,4);
    printf("%d\n",res);
    res = 45;
    first.writeaddr(emptyOff + 4 *537,&res,4);
    first.readaddr(emptyOff + 4 *753,&res,4);
    printf("%d\n",res);
    first.readaddr(emptyOff + 4 *537,&res,4);
    printf("%d\n",res);
}

#include "../src/utility.h"
#include "../src/HDD/HardDrive.h"

void unittest(){
    const size_t emptyOff = 0x80120;

    HDD::HDD first(1,true);
    first.init();

    int data[1000];
    for(int i = 0 ; i < 1000 ; ++i){
        data[i] = i;
    }
    first.writeaddr(emptyOff,&data,4*1000);
    int res;
    first.readaddr(emptyOff + 4 *42,&res,4);
    printf("%d\n",res);
    first.readaddr(emptyOff + 4 *999,&res,4);
    printf("%d\n",res);
    res = 45;
    first.writeaddr(emptyOff + 4 *537,&res,4);
    first.readaddr(emptyOff + 4 *753,&res,4);
    printf("%d\n",res);
    first.readaddr(emptyOff + 4 *537,&res,4);
    printf("%d\n",res);
}

Fix compilation error in HDD's unittest

Fix compilation error in HDD's unittest


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

#include "chrome/browser/extensions/extension_apitest.h"
#include "chrome/test/base/ui_test_utils.h"

IN_PROC_BROWSER_TEST_F(ExtensionApiTest,
                       ExtensionPointerLockAccessFail) {
  // Test that pointer lock cannot be accessed from an extension without
  // permission.
  ASSERT_TRUE(RunPlatformAppTest("pointer_lock/no_permission")) << message_;
}

IN_PROC_BROWSER_TEST_F(ExtensionApiTest,
                       ExtensionPointerLockAccessPass) {
  // Test that pointer lock can be accessed from an extension with permission.
  ASSERT_TRUE(RunPlatformAppTest("pointer_lock/has_permission")) << message_;
}

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

#include "chrome/browser/extensions/extension_apitest.h"
#include "chrome/test/base/ui_test_utils.h"

IN_PROC_BROWSER_TEST_F(ExtensionApiTest,
                       ExtensionPointerLockAccessFail) {
  // Test that pointer lock cannot be accessed from an extension without
  // permission.
  ASSERT_TRUE(RunPlatformAppTest("pointer_lock/no_permission")) << message_;
}

// http://crbug.com/223447
#if defined(OS_LINUX)
#define MAYBE_ExtensionPointerLockAccessPass \
    DISABLED_ExtensionPointerLockAccessPass
#else
#define MAYBE_ExtensionPointerLockAccessPass ExtensionPointerLockAccessPass
#endif
IN_PROC_BROWSER_TEST_F(ExtensionApiTest,
                       MAYBE_ExtensionPointerLockAccessPass) {
  // Test that pointer lock can be accessed from an extension with permission.
  ASSERT_TRUE(RunPlatformAppTest("pointer_lock/has_permission")) << message_;
}

Disable test that is failing on linux trybots.

BUG=223447
NOTRY=True
TBR=jeremya@chromium.org

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

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


#include "stdafx.h"
#include "ExpressionFunctions.h"
#include "Misc.h"
#include "Common.h"

ExpressionValue expressionFunctionEndianness(const std::vector<ExpressionValue>& parameters)
{
	Endianness endianness = g_fileManager->getEndianness();

	ExpressionValue result;
	result.type = ExpressionValueType::String;

	switch (endianness)
	{
	case Endianness::Little:
		result.strValue = L"little";
		break;
	case Endianness::Big:
		result.strValue = L"big";
		break;
	}

	return result;
}

const ExpressionFunctionMap expressionFunctions = {
	{ L"endianness",	{ &expressionFunctionEndianness,	0,	0 } },
};

#include "stdafx.h"
#include "ExpressionFunctions.h"
#include "Misc.h"
#include "Common.h"

ExpressionValue expFuncEndianness(const std::vector<ExpressionValue>& parameters)
{
	Endianness endianness = g_fileManager->getEndianness();

	ExpressionValue result;
	result.type = ExpressionValueType::String;

	switch (endianness)
	{
	case Endianness::Little:
		result.strValue = L"little";
		break;
	case Endianness::Big:
		result.strValue = L"big";
		break;
	}

	return result;
}

ExpressionValue expFuncFileExists(const std::vector<ExpressionValue>& parameters)
{
	ExpressionValue result;

	if (parameters[0].isString() == false)
	{
		Logger::queueError(Logger::Error,L"Invalid parameter");
		return result;
	}

	std::wstring fileName = getFullPathName(parameters[0].strValue);

	result.type = ExpressionValueType::Integer;
	result.intValue = fileExists(fileName) ? 1 : 0;
	return result;
}

ExpressionValue expFuncFileSize(const std::vector<ExpressionValue>& parameters)
{
	ExpressionValue result;

	if (parameters[0].isString() == false)
	{
		Logger::queueError(Logger::Error,L"Invalid parameter");
		return result;
	}

	std::wstring fileName = getFullPathName(parameters[0].strValue);

	result.type = ExpressionValueType::Integer;
	result.intValue = fileSize(fileName);
	return result;
}

const ExpressionFunctionMap expressionFunctions = {
	{ L"endianness",	{ &expFuncEndianness,	0,	0 } },
	{ L"fileexists",	{ &expFuncFileExists,	1,	1 } },
	{ L"filesize",		{ &expFuncFileSize,		1,	1 } },
};

Add fileExists and fileSize expression functions


// REQUIRES: static-analyzer
// RUN: clang-tidy %s -checks='-*,clang-analyzer-*' -- | FileCheck %s
extern void *malloc(unsigned long);
extern void free(void *);

void f() {
  int *p = new int(42);
  delete p;
  delete p;
  // CHECK: warning: Attempt to delete released memory [clang-analyzer-cplusplus.NewDelete]
}

void g() {
  void *q = malloc(132);
  free(q);
  free(q);
  // CHECK: warning: Attempt to free released memory [clang-analyzer-unix.Malloc]
}

// REQUIRES: static-analyzer
// RUN: clang-tidy %s -checks='-*,clang-analyzer-*' -- | FileCheck %s
extern void *malloc(unsigned long);
extern void free(void *);

void f() {
  int *p = new int(42);
  delete p;
  delete p;
  // CHECK: warning: Attempt to free released memory [clang-analyzer-cplusplus.NewDelete]
}

void g() {
  void *q = malloc(132);
  free(q);
  free(q);
  // CHECK: warning: Attempt to free released memory [clang-analyzer-unix.Malloc]
}

Revert rCTE349288 'Fix a lit test failure after MallocChecker changes'

git-svn-id: a34e9779ed74578ad5922b3306b3d80a0c825546@349341 91177308-0d34-0410-b5e6-96231b3b80d8


/*
 * 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 "GrGLConfig.h"
#include "GrGLInterface.h"

void GrGLClearErr(const GrGLInterface* gl) {
    while (GR_GL_NO_ERROR != gl->fGetError()) {}
}

void GrGLCheckErr(const GrGLInterface* gl,
                  const char* location,
                  const char* call) {
    uint32_t err = GR_GL_GET_ERROR(gl);
    if (GR_GL_NO_ERROR != err) {
        GrPrintf("---- glGetError %x", GR_GL_GET_ERROR(gl));
        if (NULL != location) {
            GrPrintf(" at\n\t%s", location);
        }
        if (NULL != call) {
            GrPrintf("\n\t\t%s", call);
        }
        GrPrintf("\n");
    }
}

void GrGLResetRowLength(const GrGLInterface* gl) {
    if (gl->supportsDesktop()) {
        GR_GL_CALL(gl, PixelStorei(GR_GL_UNPACK_ROW_LENGTH, 0));
    }
}

///////////////////////////////////////////////////////////////////////////////

#if GR_GL_LOG_CALLS
    bool gLogCallsGL = !!(GR_GL_LOG_CALLS_START);
#endif

#if GR_GL_CHECK_ERROR
    bool gCheckErrorGL = !!(GR_GL_CHECK_ERROR_START);
#endif

/*
 * 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 "GrGLConfig.h"
#include "GrGLInterface.h"

void GrGLClearErr(const GrGLInterface* gl) {
    while (GR_GL_NO_ERROR != gl->fGetError()) {}
}

void GrGLCheckErr(const GrGLInterface* gl,
                  const char* location,
                  const char* call) {
    uint32_t err = GR_GL_GET_ERROR(gl);
    if (GR_GL_NO_ERROR != err) {
        GrPrintf("---- glGetError %x", err);
        if (NULL != location) {
            GrPrintf(" at\n\t%s", location);
        }
        if (NULL != call) {
            GrPrintf("\n\t\t%s", call);
        }
        GrPrintf("\n");
    }
}

void GrGLResetRowLength(const GrGLInterface* gl) {
    if (gl->supportsDesktop()) {
        GR_GL_CALL(gl, PixelStorei(GR_GL_UNPACK_ROW_LENGTH, 0));
    }
}

///////////////////////////////////////////////////////////////////////////////

#if GR_GL_LOG_CALLS
    bool gLogCallsGL = !!(GR_GL_LOG_CALLS_START);
#endif

#if GR_GL_CHECK_ERROR
    bool gCheckErrorGL = !!(GR_GL_CHECK_ERROR_START);
#endif

Fix gl error debug print.

Fix gl error debug print.

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


#include <Pith/Config.hpp>
#include <Pith/LockGuard.hpp>
#include <Pith/SharedLock.hpp>
#include <gtest/gtest.h>

using namespace Pith;

TEST(SharedLock, multipleShared) {
	SharedLock lock;
	SharedLockGuard<SharedLock> shared1(lock);
	EXPECT_TRUE(trySharedLock(lock));
}

TEST(SharedLock, failToTakeExclusive) {
	SharedLock lock;
	SharedLockGuard<SharedLock> shared(lock);
	EXPECT_FALSE(tryExclusiveLock(lock));
}

TEST(SharedLock, exclusiveThenShared) {
	SharedLock lock;
	{
		ExclusiveLockGuard<SharedLock> exclusive(lock);
		EXPECT_TRUE(lock.isLocked<Access::EXCLUSIVE>());
	}
	EXPECT_FALSE(lock.isLocked<Access::EXCLUSIVE>());
	{
		SharedLockGuard<SharedLock> shared(lock);
		EXPECT_TRUE(lock.isLocked<Access::SHARED>());
	}
	EXPECT_FALSE(lock.isLocked<Access::SHARED>());
}

#include <Pith/Config.hpp>
#include <Pith/LockGuard.hpp>
#include <Pith/SharedLock.hpp>
#include <gtest/gtest.h>

using namespace Pith;

TEST(SharedLock, multipleShared) {
	SharedLock lock;
	SharedLockGuard<SharedLock> shared1(lock);
	EXPECT_TRUE(trySharedLock(lock));
}

TEST(SharedLock, DISABLED_failToTakeExclusive) {
	SharedLock lock;
	SharedLockGuard<SharedLock> shared(lock);
	EXPECT_FALSE(tryExclusiveLock(lock));
}

TEST(SharedLock, DISABLED_exclusiveThenShared) {
	SharedLock lock;
	{
		ExclusiveLockGuard<SharedLock> exclusive(lock);
		EXPECT_TRUE(lock.isLocked<Access::EXCLUSIVE>());
	}
	EXPECT_FALSE(lock.isLocked<Access::EXCLUSIVE>());
	{
		SharedLockGuard<SharedLock> shared(lock);
		EXPECT_TRUE(lock.isLocked<Access::SHARED>());
	}
	EXPECT_FALSE(lock.isLocked<Access::SHARED>());
}

Disable some shared lock tests

Disable some shared lock tests

Since the shared lock is unimplemented, these tests aren't showing the
expected behaviour.

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


#include "ReadFileManager.h"        // Own interface
#include "ReadFile.h"               // engine::ReadFile

namespace engine {

    ReadFileManager::ReadFileManager()
    {
        // Default number of open files
        max_open_files = 10;
    }

    ReadFile *ReadFileManager::getReadFile( std::string fileName )
    {
        ReadFile *f = read_files.extractFromMap( fileName );

        // Remove non-valid ReadFiles
        if( f && !f->isValid() )
        {
            delete f;
            f = NULL;
        }

        if( !f )
            f = new ReadFile( fileName );

        // Insert at front ( remove the last used at the  back )
        read_files.insertAtFront( fileName , f );

        // Remove old File descriptors if necessary
        while( (int)read_files.size() > max_open_files )
        {

            ReadFile *rf = read_files.extractFromBack();

            if( rf == f )
                LM_X(1, ("Internal error"));

            rf->close();
            delete rf;
        }

        return f;
    }

}

#include "ReadFileManager.h"        // Own interface
#include "ReadFile.h"               // engine::ReadFile

namespace engine {

    ReadFileManager::ReadFileManager()
    {
        // Default number of open files
        max_open_files = 100;
    }

    ReadFile *ReadFileManager::getReadFile( std::string fileName )
    {
        ReadFile *f = read_files.extractFromMap( fileName );

        // Remove non-valid ReadFiles
        if( f && !f->isValid() )
        {
            delete f;
            f = NULL;
        }

        if( !f )
            f = new ReadFile( fileName );

        // Insert at front ( remove the last used at the  back )
        read_files.insertAtFront( fileName , f );

        // Remove old File descriptors if necessary
        while( (int)read_files.size() > max_open_files )
        {

            ReadFile *rf = read_files.extractFromBack();

            if( rf == f )
                LM_X(1, ("Internal error"));

            rf->close();
            delete rf;
        }

        return f;
    }

}

Fix wrong number of max open files

Fix wrong number of max open files

git-svn-id: 9714148d14941aebeae8d7f7841217f5ffc02bc5@1163 4143565c-f3ec-42ea-b729-f8ce0cf5cbc3


//
//  WindowSettings.cpp
//  Hume
//
//  Created by Marshall Clyburn on 7/11/14.
//  Copyright (c) 2014 Marshall Clyburn. All rights reserved.
//

#include "WindowSettings.h"

namespace hm
{
	/*
	 Default to a fullscreen window at the maximum
	 resolution supported by the attached screen.
	 */
	WindowSettings::WindowSettings() : fullscreen(true), title("Hume Window")
	{
		setBestFullscreenMode();
	}

	WindowSettings::~WindowSettings()
	{

	}

	/*
	 Set the window to fullscreen at the best possible
	 resolution attainable.
	*/
	void WindowSettings::setBestFullscreenMode()
	{
		fullscreen = true;
		int display_mode_count = SDL_GetNumDisplayModes(0);
		if(display_mode_count < 1)
		{
			Logger::getLogger()->log("No available display modes.", ERROR);
			exit(0);
		}
		else
		{
			SDL_DisplayMode mode;
			int success;
			do
			{
				success = SDL_GetDisplayMode(0, 0, &mode);
			}
			while(success != 0);

			if(Logger::getLogger()->getLogLevel() >= LogLevel::INFO)
			{
				std::string msg = "Using resolution of ";
				msg += mode.w;
				msg += "x";
				msg += mode.h;
				msg += ".";
				Logger::getLogger()->log(msg);
			}
		}
	}
}

//
//  WindowSettings.cpp
//  Hume
//
//  Created by Marshall Clyburn on 7/11/14.
//  Copyright (c) 2014 Marshall Clyburn. All rights reserved.
//

#include "WindowSettings.h"

namespace hm
{
	/*
	 Default to a fullscreen window at the maximum
	 resolution supported by the attached screen.
	 */
	WindowSettings::WindowSettings() : fullscreen(true), title("Hume Window")
	{
		setBestFullscreenMode();
	}

	WindowSettings::~WindowSettings()
	{

	}

	/*
	 Set the window to fullscreen at the best possible
	 resolution attainable.
	*/
	void WindowSettings::setBestFullscreenMode()
	{
		fullscreen = true;
		int display_mode_count = SDL_GetNumDisplayModes(0);
		if(display_mode_count < 1)
		{
			Logger::getLogger()->log("No available display modes.", ERROR);
			exit(0);
		}
		else
		{
			SDL_DisplayMode mode;
			int success;
			do
			{
				success = SDL_GetDisplayMode(0, 0, &mode);
			}
			while(success != 0);

			if(Logger::getLogger()->getLogLevel() >= LogLevel::INFO)
			{
				std::string msg = "Using resolution of " +
				std::to_string(mode.w) + "x" +
				std::to_string(mode.h) + ".";
				Logger::getLogger()->log(msg);
			}
		}
	}
}

Fix logging resolution as chars.

Fix logging resolution as chars.


#include <iostream>
#include <cstdlib>

#include "population.h"

int **POPULATION::initializePopulation(int individuals, int genes, bool FILL_ZERO)
{
  int **population;

  if (!FILL_ZERO)
  {
    population = (int **) malloc(individuals * sizeof(int *));
    for (int i = 0; i < individuals; i++)
      population[i] = (int *) malloc(genes * sizeof(int));
  }
  else
  {
    population = (int **) calloc(individuals, sizeof(int *));
    for (int i = 0; i < individuals; i++)
      population[i] = (int *) calloc(genes, sizeof(int));
  }

  return population;
}

int **POPULATION::createRandomPopulation(int **population, int individuals, int genes)
{
  // Fill the 2d array with random genes
  for (int pop = 0; pop < individuals; pop++)
  {
    for (int gene = 0; gene < genes; gene++)
    {
      population[pop][gene] = rand() % 2;
    }
  }
  return 0;
}

#include <iostream>
#include <cstdlib>

#include "population.h"

int **POPULATION::initializePopulation(int individuals, int genes, bool FILL_ZERO)
{
  int **population;

  if (!FILL_ZERO)
  {
    population = (int **) malloc(individuals * sizeof(int *));
    for (int i = 0; i < individuals; i++)
      population[i] = (int *) malloc(genes * sizeof(int));
  }
  else
  {
    population = (int **) calloc(individuals, sizeof(int *));
    for (int i = 0; i < individuals; i++)
      population[i] = (int *) calloc(genes, sizeof(int));
  }

  return population;
}

int POPULATION::createRandomPopulation(int **population, int individuals, int genes)
{
  // Fill the 2d array with random genes
  for (int pop = 0; pop < individuals; pop++)
  {
    for (int gene = 0; gene < genes; gene++)
    {
      population[pop][gene] = rand() % 2;
    }
  }
  return 1;
}

Update return datatype function 'createRandomPopulation'.


#include "connection.h"

hwo_connection::hwo_connection(const std::string& host, const std::string& port)
  : socket(io_service)
{
  tcp::resolver resolver(io_service);
  tcp::resolver::query query(host, port);
  boost::asio::connect(socket, resolver.resolve(query));
  response_buf.prepare(8192);
}

hwo_connection::~hwo_connection()
{
  socket.close();
}

jsoncons::json hwo_connection::receive_response(boost::system::error_code& error)
{
  boost::asio::read_until(socket, response_buf, "\n", error);
  if (error)
  {
    return jsoncons::json();
  }
  std::istream s(&response_buf);
  return jsoncons::json::parse(s);
}

void hwo_connection::send_requests(const std::vector<jsoncons::json>& msgs)
{
  jsoncons::output_format format;
  format.escape_all_non_ascii(true);
  boost::asio::streambuf request_buf;
  std::ostream s(&request_buf);
  for (const auto& m : msgs) {
    m.to_stream(s, format);
    s << std::endl;
  }
  socket.send(request_buf.data());
}

#include "connection.h"

hwo_connection::hwo_connection(const std::string& host, const std::string& port)
  : socket(io_service)
{
  tcp::resolver resolver(io_service);
  tcp::resolver::query query(host, port);
  boost::asio::connect(socket, resolver.resolve(query));
  response_buf.prepare(8192);
}

hwo_connection::~hwo_connection()
{
  socket.close();
}

jsoncons::json hwo_connection::receive_response(boost::system::error_code& error)
{
  auto len = boost::asio::read_until(socket, response_buf, "\n", error);
  if (error)
  {
    return jsoncons::json();
  }
  auto buf = response_buf.data();
  std::string reply(boost::asio::buffers_begin(buf), boost::asio::buffers_begin(buf) + len);
  response_buf.consume(len);
  return jsoncons::json::parse_string(reply);
}

void hwo_connection::send_requests(const std::vector<jsoncons::json>& msgs)
{
  jsoncons::output_format format;
  format.escape_all_non_ascii(true);
  boost::asio::streambuf request_buf;
  std::ostream s(&request_buf);
  for (const auto& m : msgs) {
    m.to_stream(s, format);
    s << std::endl;
  }
  socket.send(request_buf.data());
}

Fix case where received message was potentially dropped in C++ bot

The read_until() may leave trailing data to read buffer, and this
was not handled properly by the sample bot.

Big thanks to Mika Urtela for spotting this.

Signed-off-by: Harri Salokorpi <eefb23b8deb8c30dca252cd0ae751b67337dc69f@reaktor.fi>
Signed-off-by: Sami Rosendahl <b33c757bb777642ab0d59c699f8d5782929a814f@reaktor.fi>


#include "browser/inspectable_web_contents.h"

#include "browser/inspectable_web_contents_impl.h"

namespace brightray {

InspectableWebContents* InspectableWebContents::Create(const content::WebContents::CreateParams& create_params) {
  return Create(content::WebContents::Create(create_params));
}

InspectableWebContents* InspectableWebContents::Create(content::WebContents* web_contents) {
  return new InspectableWebContentsImpl(web_contents);
}

}

#include "browser/inspectable_web_contents.h"

#include "browser/inspectable_web_contents_impl.h"

#include "content/public/browser/web_contents_view.h"

namespace brightray {

InspectableWebContents* InspectableWebContents::Create(const content::WebContents::CreateParams& create_params) {
  auto contents = content::WebContents::Create(create_params);
#if defined(OS_MACOSX)
  // Work around http://crbug.com/279472.
  contents->GetView()->SetAllowOverlappingViews(true);
#endif

  return Create(contents);
}

InspectableWebContents* InspectableWebContents::Create(content::WebContents* web_contents) {
  return new InspectableWebContentsImpl(web_contents);
}

}

Fix flashing in WebContents we create

Fix flashing in WebContents we create

If the embedding app creates them it's up to them to fix this.


// RUN: %clangxx_msan -fsanitize-memory-track-origins -O0 %s -o %t && not %run %t >%t.out 2>&1
// RUN: FileCheck %s < %t.out && FileCheck %s < %t.out
// RUN: %clangxx_msan -fsanitize-memory-track-origins -O3 %s -o %t && not %run %t >%t.out 2>&1
// RUN: FileCheck %s < %t.out && FileCheck %s < %t.out

// Test origin propagation through insertvalue IR instruction.

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

struct mypair {
 int64_t x;
 int y;
};

mypair my_make_pair(int64_t x, int y)  {
 mypair p;
 p.x = x;
 p.y = y;
 return p;
}

int main() {
 int64_t * volatile p = new int64_t;
 mypair z = my_make_pair(*p, 0);
 if (z.x)
   printf("zzz\n");
 // CHECK: MemorySanitizer: use-of-uninitialized-value
 // CHECK: {{in main .*insertvalue_origin.cc:}}[[@LINE-3]]

 // CHECK: Uninitialized value was created by a heap allocation
 // CHECK: {{in main .*insertvalue_origin.cc:}}[[@LINE-8]]
 delete p;
 return 0;
}

// RUN: %clangxx_msan -fsanitize-memory-track-origins -O0 %s -o %t && not %run %t >%t.out 2>&1
// RUN: FileCheck %s < %t.out && FileCheck %s < %t.out
// RUN: %clangxx_msan -fsanitize-memory-track-origins -O3 %s -o %t && not %run %t >%t.out 2>&1
// RUN: FileCheck %s < %t.out && FileCheck %s < %t.out

// Test origin propagation through insertvalue IR instruction.
// REQUIRES: stable-runtime

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

struct mypair {
 int64_t x;
 int y;
};

mypair my_make_pair(int64_t x, int y)  {
 mypair p;
 p.x = x;
 p.y = y;
 return p;
}

int main() {
 int64_t * volatile p = new int64_t;
 mypair z = my_make_pair(*p, 0);
 if (z.x)
   printf("zzz\n");
 // CHECK: MemorySanitizer: use-of-uninitialized-value
 // CHECK: {{in main .*insertvalue_origin.cc:}}[[@LINE-3]]

 // CHECK: Uninitialized value was created by a heap allocation
 // CHECK: {{in main .*insertvalue_origin.cc:}}[[@LINE-8]]
 delete p;
 return 0;
}

Disable one MSAN test in AArch64 until we have a proper fix

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


//===------------------------- cxa_exception.cpp --------------------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is dual licensed under the MIT and the University of Illinois Open
// Source Licenses. See LICENSE.TXT for details.
//
//
//  This file implements the "Exception Handling APIs"
//  http://mentorembedded.github.io/cxx-abi/abi-eh.html
//
//===----------------------------------------------------------------------===//

// Support functions for the no-exceptions libc++ library

#include "config.h"
#include "cxxabi.h"

#include <exception>        // for std::terminate
#include "cxa_exception.hpp"
#include "cxa_handlers.hpp"

namespace __cxxabiv1 {

extern "C" {

void
__cxa_increment_exception_refcount(void *thrown_object) throw() {
    if (thrown_object != nullptr)
        std::terminate();
}

void
__cxa_decrement_exception_refcount(void *thrown_object) throw() {
    if (thrown_object != nullptr)
      std::terminate();
}

void *__cxa_current_primary_exception() throw() { return nullptr; }

void
__cxa_rethrow_primary_exception(void* thrown_object) {
    if (thrown_object != nullptr)
      std::terminate();
}

bool
__cxa_uncaught_exception() throw() { return false; }

unsigned int
__cxa_uncaught_exceptions() throw() { return 0; }

}  // extern "C"

}  // abi

//===------------------------- cxa_exception.cpp --------------------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is dual licensed under the MIT and the University of Illinois Open
// Source Licenses. See LICENSE.TXT for details.
//
//
//  This file implements the "Exception Handling APIs"
//  http://mentorembedded.github.io/cxx-abi/abi-eh.html
//
//===----------------------------------------------------------------------===//

// Support functions for the no-exceptions libc++ library

#include "cxxabi.h"

#include <exception>        // for std::terminate
#include "cxa_exception.hpp"
#include "cxa_handlers.hpp"

namespace __cxxabiv1 {

extern "C" {

void
__cxa_increment_exception_refcount(void *thrown_object) throw() {
    if (thrown_object != nullptr)
        std::terminate();
}

void
__cxa_decrement_exception_refcount(void *thrown_object) throw() {
    if (thrown_object != nullptr)
      std::terminate();
}

void *__cxa_current_primary_exception() throw() { return nullptr; }

void
__cxa_rethrow_primary_exception(void* thrown_object) {
    if (thrown_object != nullptr)
      std::terminate();
}

bool
__cxa_uncaught_exception() throw() { return false; }

unsigned int
__cxa_uncaught_exceptions() throw() { return 0; }

}  // extern "C"

}  // abi

Remove missed use of config.h

[libc++abi] Remove missed use of config.h

git-svn-id: 6a9f6578bdee8d959f0ed58970538b4ab6004734@299143 91177308-0d34-0410-b5e6-96231b3b80d8


#include <QtPlugin>
\
#include "animatedtilesplugin.h"
#include "animatedtilesitem.h"

AnimatedTilesPlugin::AnimatedTilesPlugin()
{
    this->mName = "AnimatedTiles";
    //This should not be an advertized plugin until it is implemented
    //this->mRole = "animatedTiles";
}

Q_EXPORT_PLUGIN2(animatedTiles, AnimatedTilesPlugin)

void AnimatedTilesPlugin::registerPlugin(QDeclarativeContext *context)
{
    qmlRegisterType<AnimatedTilesItem>("AnimatedTiles", 1, 0, "AnimatedTiles");
}

#include <QtPlugin>
\
#include "animatedtilesplugin.h"
#include "animatedtilesitem.h"

AnimatedTilesPlugin::AnimatedTilesPlugin()
{
    setName("AnimatedTiles");
    //This should not be an advertized plugin until it is implemented
    //setRole("animatedTiles");
}

Q_EXPORT_PLUGIN2(animatedTiles, AnimatedTilesPlugin)

void AnimatedTilesPlugin::registerPlugin(QDeclarativeContext *context)
{
    qmlRegisterType<AnimatedTilesItem>("AnimatedTiles", 1, 0, "AnimatedTiles");
}

Adjust minor animated tiles transgression


#include "AbsPositionOverview.h"

AbsPositionOverview::AbsPositionOverview(QObject *parent) :
    QObject(parent)
{
}

void AbsPositionOverview::parseGpsRawInt(LinkInterface *link, const mavlink_message_t &message, const mavlink_gps_raw_int_t &state)
{
    if (state.fix_type > 2)
    {
        this->setLat(state.lat);
        this->setLon(state.lon);
        this->setAlt(state.alt);
        this->setVel(state.vel);
    }
}

void AbsPositionOverview::parseGlobalPositionInt(LinkInterface *link, const mavlink_message_t &message, const mavlink_global_position_int_t &state)
{
    this->setRelativeAlt(state.relative_alt);
}

void AbsPositionOverview::messageReceived(LinkInterface* link,mavlink_message_t message)
{
    switch (message.msgid)
    {
        case MAVLINK_MSG_ID_GPS_RAW_INT:
        {
            mavlink_gps_raw_int_t state;
            mavlink_msg_gps_raw_int_decode(&message, &state);
            parseGpsRawInt(link,message,state);
            break;
        }
        case MAVLINK_MSG_ID_GLOBAL_POSITION_INT:
        {
            mavlink_global_position_int_t state;
            mavlink_msg_global_position_int_decode(&message, &state);
            parseGlobalPositionInt(link,message,state);
            break;
        }
    }
}

#include "AbsPositionOverview.h"

AbsPositionOverview::AbsPositionOverview(QObject *parent) :
    QObject(parent)
{
}

void AbsPositionOverview::parseGpsRawInt(LinkInterface *link, const mavlink_message_t &message, const mavlink_gps_raw_int_t &state)
{
    if (state.fix_type > 2)
    {
        this->setLat(state.lat);
        this->setLon(state.lon);
        this->setAlt(state.alt);
        this->setVel(state.vel);
    }
}

void AbsPositionOverview::parseGlobalPositionInt(LinkInterface *link, const mavlink_message_t &message, const mavlink_global_position_int_t &state)
{
    this->setRelativeAlt(state.relative_alt/1000.0);
}

void AbsPositionOverview::messageReceived(LinkInterface* link,mavlink_message_t message)
{
    switch (message.msgid)
    {
        case MAVLINK_MSG_ID_GPS_RAW_INT:
        {
            mavlink_gps_raw_int_t state;
            mavlink_msg_gps_raw_int_decode(&message, &state);
            parseGpsRawInt(link,message,state);
            break;
        }
        case MAVLINK_MSG_ID_GLOBAL_POSITION_INT:
        {
            mavlink_global_position_int_t state;
            mavlink_msg_global_position_int_decode(&message, &state);
            parseGlobalPositionInt(link,message,state);
            break;
        }
    }
}

UAS: Fix altitude not being reported in metres to PFD


#include "gtest/gtest.h"
#include "Console.hpp"

#include <memory>

using namespace warbler;

class ConsoleTest
{
public:
    static void noopCommandHandler(const std::shared_ptr<const std::vector<ConsoleArg>> &args) {};
    static const std::shared_ptr<std::vector<ConsoleArgType>> args;
};

const std::shared_ptr<std::vector<ConsoleArgType>> ConsoleTest::args = std::make_shared<std::vector<ConsoleArgType>>();

TEST(constructor, default_constructor)
{
    Console c;
}

TEST(methods, registerCommand)
{
    Console c;
    c.registerCommand("test", ConsoleTest::noopCommandHandler, ConsoleTest::args);
}

TEST(methods, registerCommand_null_func_throws)
{
    Console c;
    ASSERT_ANY_THROW(c.registerCommand("test", nullptr, ConsoleTest::args));
}

TEST(methods, registerCommand_empty_name_throws)
{
    Console c;
    ASSERT_ANY_THROW(c.registerCommand("", ConsoleTest::noopCommandHandler, ConsoleTest::args));
}

#include "gtest/gtest.h"
#include "Console.hpp"

#include <memory>

using namespace warbler;

class ConsoleTest
{
public:
    static void noopCommandHandler(const std::shared_ptr<const std::vector<ConsoleArg>> &args) {};
    static const std::shared_ptr<std::vector<ConsoleArgType>> args;
};

const std::shared_ptr<std::vector<ConsoleArgType>> ConsoleTest::args = std::make_shared<std::vector<ConsoleArgType>>();

TEST(constructor, default_constructor)
{
    ASSERT_NO_THROW(Console c);
}

TEST(methods, registerCommand)
{
    Console c;
    ASSERT_NO_THROW(c.registerCommand("test", ConsoleTest::noopCommandHandler, ConsoleTest::args));
}

TEST(methods, registerCommand_null_func_throws)
{
    Console c;
    ASSERT_ANY_THROW(c.registerCommand("test", nullptr, ConsoleTest::args));
}

TEST(methods, registerCommand_empty_name_throws)
{
    Console c;
    ASSERT_ANY_THROW(c.registerCommand("", ConsoleTest::noopCommandHandler, ConsoleTest::args));
}

Modify a couple tests to use asserts.

Modify a couple tests to use asserts.

Former-commit-id: 60bee038bc7d01fa0eed5cb4f4a34a70650de97b [formerly 13be900e6fa1f86d7bd68dbcd5a408d00b432c2c]
Former-commit-id: 87eae1ec908b0a38284b4f477a38e13008c30d31


#include <iostream>
#include "version.h"
#include "parser.h"
using namespace lean;

int main() {
    std::cout << "Lean (version " << LEAN_VERSION_MAJOR << "." << LEAN_VERSION_MINOR << ")\n";
    frontend f;
    return parse_commands(f, std::cin) ? 0 : 1;
}

#include <iostream>
#include <fstream>
#include "version.h"
#include "parser.h"
using namespace lean;

int main(int argc, char ** argv) {
    std::cout << "Lean (version " << LEAN_VERSION_MAJOR << "." << LEAN_VERSION_MINOR << ")\n";
    frontend f;
    if (argc == 1) {
        return parse_commands(f, std::cin) ? 0 : 1;
    } else {
        bool ok = true;
        for (int i = 1; i < argc; i++) {
            std::ifstream in(argv[i]);
            if (!parse_commands(f, in))
                ok = false;
        }
        return ok ? 0 : 1;
    }
}

Add support for reading input files from the command line.

Signed-off-by: Leonardo de Moura <7610bae85f2b530654cc716772f1fe653373e892@microsoft.com>


/*
 * Deck.cpp
 *
 *  Created on: 11.01.2017
 *      Author: Stefan
 */

#include <memory>
#include <random>
#include "Deck.h"
#include "Card.h"
#include "GlobalDeclarations.h"

void Deck::AddSets(std::size_t N)
{
	for(std::size_t i = 0; i < N; ++i)
	{
		AddCompleteSet();
	}
}

Deck::pCard Deck::Draw()
{
	// Random generator, copied from http://stackoverflow.com/questions/5008804/generating-random-integer-from-a-range
	std::mt19937 rng(_rd());    // random-number engine used (Mersenne-Twister in this case)
	std::uniform_int_distribution<int> uniformDist(0, Base::NumCards()-1); // guaranteed unbiased
	auto random_integer = uniformDist(rng);
	return Base::RemoveCard(random_integer);
}

void Deck::PrintNumCards() const
{
	std::cout << "Cards in Deck = " << Base::NumCards() << std::endl;
}

void Deck::AddCompleteSet()
{
	for( const auto & suit : SUIT)
	{
		for(const auto & face : FACE)
		{
			AddCard(pCard(new Card(face.first, suit)));
		}
	}
}

/*
 * Deck.cpp
 *
 *  Created on: 11.01.2017
 *      Author: Stefan
 */

#include <memory>
#include <random>
#include "Deck.h"
#include "Card.h"
#include "GlobalDeclarations.h"
#include <chrono>

void Deck::AddSets(std::size_t N)
{
	for(std::size_t i = 0; i < N; ++i)
	{
		AddCompleteSet();
	}
}

Deck::pCard Deck::Draw()
{
	// Use the time for a new seed each time a card is darwn
	unsigned seed = std::chrono::system_clock::now().time_since_epoch().count();
	std::default_random_engine rng(seed);
	std::uniform_int_distribution<int> uniformDist(0, Base::NumCards()-1);
	auto random_integer = uniformDist(rng);
	return Base::RemoveCard(random_integer);
}

void Deck::PrintNumCards() const
{
	std::cout << "Cards in Deck = " << Base::NumCards() << std::endl;
}

void Deck::AddCompleteSet()
{
	for( const auto & suit : SUIT)
	{
		for(const auto & face : FACE)
		{
			AddCard(pCard(new Card(face.first, suit)));
		}
	}
}

Fix random drawing of cards

Fix random drawing of cards


#include <iostream>
#include <thread>
#include <vector>
#include "World.h"

using namespace std;

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

    if (argc != 4) {
        std::cerr << "use: " << argv[0]  << " dim iterations nworkers\n";
        return -1;
    }
    int dim         = atoi(argv[1]);
    int iterations  = atoi(argv[2]);
    int workers     = atoi(argv[3]);
    World world(dim, dim, workers);
    //world.randomize_world(42, 3);
    /* GLIDER */
    world.set_cell(1, 2, ALIVE);
    world.set_cell(2, 3, ALIVE);
    world.set_cell(3, 1, ALIVE);
    world.set_cell(3, 2, ALIVE);
    world.set_cell(3, 3, ALIVE);
    /**/

    world.print_world();
    world.update_world(iterations);
    world.print_world();

    return(0);
}

#include <iostream>
#include <thread>
#include <vector>
#include "World.h"

using namespace std;

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

    if (argc < 4) {
        std::cerr << "use: " << argv[0]  << " dim iterations nworkers ?[print: on]\n";
        return -1;
    }

    int dim        = atoi(argv[1]);
    int iterations = atoi(argv[2]);
    int workers    = atoi(argv[3]);
    int print      = 0;

    if (argc >= 5) print = (std::string(argv[4]) == "on");

    World world(dim, dim, workers);
    //world.randomize_world(42, 3);

    /* GLIDER */
    world.set_cell(1, 2, ALIVE);
    world.set_cell(2, 3, ALIVE);
    world.set_cell(3, 1, ALIVE);
    world.set_cell(3, 2, ALIVE);
    world.set_cell(3, 3, ALIVE);

    if(print)
        world.print_world();
    world.update_world(iterations);
    if(print)
        world.print_world();
    return(0);
}

Add extra argument to toggle board printing


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

#include "chrome/browser/chromeos/status_area_button.h"

#include "app/gfx/canvas.h"
#include "app/gfx/skbitmap_operations.h"
#include "app/resource_bundle.h"
#include "grit/theme_resources.h"
#include "views/border.h"
#include "views/view.h"

////////////////////////////////////////////////////////////////////////////////
// StatusAreaButton

StatusAreaButton::StatusAreaButton(views::ViewMenuDelegate* menu_delegate)
    : MenuButton(NULL, std::wstring(), menu_delegate, false) {
  set_border(NULL);
  SetShowHighlighted(true);
}

void StatusAreaButton::Paint(gfx::Canvas* canvas, bool for_drag) {
  int bitmap_id;

  switch(state()) {
    case BS_NORMAL:
      bitmap_id = IDR_STATUSBAR_CONTAINER;
      break;
    case BS_HOT:
      bitmap_id = IDR_STATUSBAR_CONTAINER_HOVER;
      break;
    case BS_PUSHED:
      bitmap_id = IDR_STATUSBAR_CONTAINER_PRESSED;
      break;
    default:
      NOTREACHED();
  }
  SkBitmap* container =
      ResourceBundle::GetSharedInstance().GetBitmapNamed(bitmap_id);
  canvas->DrawBitmapInt(*container, 0, 0);
  canvas->DrawBitmapInt(icon(), 0, 0);
}

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

#include "chrome/browser/chromeos/status_area_button.h"

#include "app/gfx/canvas.h"
#include "app/gfx/skbitmap_operations.h"
#include "app/resource_bundle.h"
#include "grit/theme_resources.h"
#include "views/border.h"
#include "views/view.h"

////////////////////////////////////////////////////////////////////////////////
// StatusAreaButton

StatusAreaButton::StatusAreaButton(views::ViewMenuDelegate* menu_delegate)
    : MenuButton(NULL, std::wstring(), menu_delegate, false) {
  set_border(NULL);
  SetShowHighlighted(true);
}

void StatusAreaButton::Paint(gfx::Canvas* canvas, bool for_drag) {
  int bitmap_id;

  switch(state()) {
    case BS_NORMAL:
      bitmap_id = IDR_STATUSBAR_CONTAINER;
      break;
    case BS_HOT:
      bitmap_id = IDR_STATUSBAR_CONTAINER_HOVER;
      break;
    case BS_PUSHED:
      bitmap_id = IDR_STATUSBAR_CONTAINER_PRESSED;
      break;
    default:
      bitmap_id = IDR_STATUSBAR_CONTAINER;
      NOTREACHED();
  }
  SkBitmap* container =
      ResourceBundle::GetSharedInstance().GetBitmapNamed(bitmap_id);
  canvas->DrawBitmapInt(*container, 0, 0);
  canvas->DrawBitmapInt(icon(), 0, 0);
}

Fix for Release build break

Fix for Release build break

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

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


#ifdef __unix__

#include <iostream>
#include <signal.h>
#include <stdio.h>
#include <unistd.h>

#include "Types.h"

#include "Tools.h"

void StartBotProcess(const BotConfig &Agent, const std::string& CommandLine, void **ProcessId)
{
    FILE* pipe = popen(CommandLine.c_str(), "r");
    if (!pipe)
    {
        std::cerr << "Can't launch command '" <<
            CommandLine << "'" << std::endl;
        return;
    }
	*ProcessId = pipe;
    int returnCode = pclose(pipe);
    if (returnCode != 0)
    {
        std::cerr << "Failed to finish command '" <<
            CommandLine << "', code: " << returnCode << std::endl;
    }
}

void SleepFor(int seconds)
{
    sleep(seconds);
}

void KillSc2Process(unsigned long pid)
{
    kill(pid, SIGKILL);
}

bool MoveReplayFile(const char* lpExistingFileName, const  char* lpNewFileName)
{
	// todo
	throw "MoveFile is not implemented for linux yet.";
}

void KillBotProcess(void *ProcessStruct);
{
	// This needs to be implemented
}

#endif

#if defined(__unix__) || defined(__APPLE__)

#include <iostream>
#include <signal.h>
#include <stdio.h>
#include <unistd.h>

#include "Types.h"

#include "Tools.h"

void StartBotProcess(const BotConfig &Agent, const std::string& CommandLine, void **ProcessId)
{
    FILE* pipe = popen(CommandLine.c_str(), "r");
    if (!pipe)
    {
        std::cerr << "Can't launch command '" <<
            CommandLine << "'" << std::endl;
        return;
    }
	*ProcessId = pipe;
    int returnCode = pclose(pipe);
    if (returnCode != 0)
    {
        std::cerr << "Failed to finish command '" <<
            CommandLine << "', code: " << returnCode << std::endl;
    }
}

void SleepFor(int seconds)
{
    sleep(seconds);
}

void KillSc2Process(unsigned long pid)
{
    kill(pid, SIGKILL);
}

bool MoveReplayFile(const char* lpExistingFileName, const  char* lpNewFileName)
{
	// todo
	throw "MoveFile is not implemented for linux yet.";
}

void KillBotProcess(void *ProcessStruct);
{
	// This needs to be implemented
}

#endif

Fix Tools compilation under OS X

Fix Tools compilation under OS X

__unix__ is defined only on Linux. Use OS X specific define.


// Copyright (c) 2011 Zeex
//
// 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 <cstring>

#include "hooknative.h"

AMX_NATIVE HookNative(AMX *amx, const char *nativeName, AMX_NATIVE native) {
    AMX_HEADER *hdr = reinterpret_cast<AMX_HEADER*>(amx->base);
    AMX_FUNCSTUBNT *natives = reinterpret_cast<AMX_FUNCSTUBNT*>(amx->base + hdr->natives);

    int numberOfNatives;
    amx_NumNatives(amx, &numberOfNatives);

    for (int i = 0; i < numberOfNatives; i++) {
        char *currentName = reinterpret_cast<char*>(amx->base + natives[i].nameofs);
        if (std::strcmp(currentName, nativeName) == 0) {
            cell address = natives[i].address;
            natives[i].address = reinterpret_cast<cell>(native);
            return reinterpret_cast<AMX_NATIVE>(address);
        }
    }

    return 0;
}

// Copyright (c) 2011 Zeex
//
// 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 <cstring>

AMX_NATIVE HookNative(AMX *amx, const char *nativeName, AMX_NATIVE native) {
    AMX_HEADER *hdr = reinterpret_cast<AMX_HEADER*>(amx->base);
    AMX_FUNCSTUBNT *natives = reinterpret_cast<AMX_FUNCSTUBNT*>(amx->base + hdr->natives);

    int numberOfNatives;
    amx_NumNatives(amx, &numberOfNatives);

    for (int i = 0; i < numberOfNatives; i++) {
        char *currentName = reinterpret_cast<char*>(amx->base + natives[i].nameofs);
        if (std::strcmp(currentName, nativeName) == 0) {
            cell address = natives[i].address;
            natives[i].address = reinterpret_cast<cell>(native);
            return reinterpret_cast<AMX_NATIVE>(address);
        }
    }

    return 0;
}

Fix weird undefined reference to HookNative (GCC 4.5.2)


//
//  SNA.cpp
//  Clock Signal
//
//  Created by Thomas Harte on 24/04/2021.
//  Copyright © 2021 Thomas Harte. All rights reserved.
//

#include "SNA.hpp"

using namespace Storage::State;

std::unique_ptr<Analyser::Static::Target> SNA::load(const std::string &file_name) {
	// 0x1a byte header:
	//
	//	00	I
	//	01	HL'
	//	03	DE'
	//	05	BC'
	//	07	AF'
	//	09	HL
	//	0B	DE
	//	0D	BC
	//	0F	IY
	//	11	IX
	//	13	IFF2 (in bit 2)
	//	14	R
	//	15	AF
	//	17	SP
	//	19	interrupt mode
	//	1A	border colour
	//	1B–	48kb RAM contents

	(void)file_name;
	return nullptr;
}

//
//  SNA.cpp
//  Clock Signal
//
//  Created by Thomas Harte on 24/04/2021.
//  Copyright © 2021 Thomas Harte. All rights reserved.
//

#include "SNA.hpp"

using namespace Storage::State;

std::unique_ptr<Analyser::Static::Target> SNA::load(const std::string &file_name) {
	// 0x1a byte header:
	//
	//	00	I
	//	01	HL'
	//	03	DE'
	//	05	BC'
	//	07	AF'
	//	09	HL
	//	0B	DE
	//	0D	BC
	//	0F	IY
	//	11	IX
	//	13	IFF2 (in bit 2)
	//	14	R
	//	15	AF
	//	17	SP
	//	19	interrupt mode
	//	1A	border colour
	//	1B–	48kb RAM contents
	//
	// (perform a POP to get the PC)

	(void)file_name;
	return nullptr;
}

Add further note to future self.

Add further note to future self.


/*
  High_Temp.cpp

  2014 Copyright (c) Seeed Technology Inc.  All right reserved.

  Loovee
  2013-4-14

  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 License, 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., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
*/

#include <Arduino.h>
#include "High_Temp_MCP320x.h"

HighTempMCP320x::HighTempMCP320x(int _spiCS, int _pinTmp, int _pinThmc) : HighTemp(_pinTmp, _pinThmc)
{
    spiChipSelect = _spiCS;
    adc = MCP3208(spiChipSelect);
}

int HighTempMCP320x::getAnalog(int pin)
{
    return adc.analogRead(pin);
}

/*
  High_Temp.cpp

  2014 Copyright (c) Seeed Technology Inc.  All right reserved.

  Loovee
  2013-4-14

  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 License, 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., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
*/

#include <Arduino.h>
#include "High_Temp_MCP320x.h"

HighTempMCP320x::HighTempMCP320x(int _spiCS, int _pinTmp, int _pinThmc) : HighTemp(_pinTmp, _pinThmc)
{
    adc = MCP3208(_spiCS);
    adc.begin();
}

int HighTempMCP320x::getAnalog(int pin)
{
    return adc.analogRead(pin);
}

Add missing call to begin() for MCP3208 object


// Based on Euler.ino example

#include "NAxisMotion.h"

NAxisMotion imu;
unsigned long prevTime = 0;
const int streamPeriod = 20; // ms

void setup()
{
  Serial.begin(115200);
  I2C.begin();
  imu.initSensor(); // I2C Address can be changed here if needed
  imu.setOperationMode(OPERATION_MODE_NDOF);

  // Default update mode is AUTO.
  // MANUAL requires calling update functions prior to calling the read functions
  // Setting to MANUAL requires fewer reads to the sensor
  imu.setUpdateMode(MANUAL);
}

void loop()
{
  if ((millis() - prevTime) >= streamPeriod)
  {
    prevTime = millis();
    imu.updateEuler();        // Update the Euler data into the structure of the object
    imu.updateCalibStatus();  // Update the Calibration Status

    Serial.print("Time:");
    Serial.print(prevTime); // ms

    Serial.print(",H:");
    Serial.print(imu.readEulerHeading()); // deg

    Serial.print(",R:");
    Serial.print(imu.readEulerRoll()); // deg

    Serial.print(",P:");
    Serial.print(imu.readEulerPitch()); // deg

    // Calib status values range from 0 - 3
    Serial.print(",A:");
    Serial.print(imu.readAccelCalibStatus());

    Serial.print(",M:");
    Serial.print(imu.readMagCalibStatus());

    Serial.print(",G:");
    Serial.print(imu.readGyroCalibStatus());

    Serial.print(",S:");
    Serial.print(imu.readSystemCalibStatus());

    Serial.println();
  }
}

#include "NAxisMotion.h"

NAxisMotion imu;
unsigned long prevTime = 0;
const int streamPeriod = 20; // ms

void setup()
{
  Serial.begin(115200);
  I2C.begin();
  imu.initSensor(); // I2C Address can be changed here if needed
  imu.setOperationMode(OPERATION_MODE_NDOF);
  imu.setUpdateMode(MANUAL);
}

void loop()
{
  if ((millis() - prevTime) >= streamPeriod)
  {
    prevTime = millis();
    imu.updateQuat();
    imu.updateCalibStatus();

    Serial.print("Time:");
    Serial.print(prevTime); // ms

    // Quaternion values
    Serial.print(",qw:");
    Serial.print(imu.readQuatW());
    Serial.print(",qx:");
    Serial.print(imu.readQuatX());
    Serial.print(",qy:");
    Serial.print(imu.readQuatY());
    Serial.print(",qz:");
    Serial.print(imu.readQuatZ());

    // Calib status values range from 0 - 3
    Serial.print(",A:");
    Serial.print(imu.readAccelCalibStatus());
    Serial.print(",M:");
    Serial.print(imu.readMagCalibStatus());
    Serial.print(",G:");
    Serial.print(imu.readGyroCalibStatus());
    Serial.print(",S:");
    Serial.print(imu.readSystemCalibStatus());

    Serial.println();
  }
}

Write quaternion components instead of Euler angles


// RUN: %clang_cc1 %s -emit-llvm-only -verify
// PR7291

struct Foo {
  unsigned file_id;

  Foo(unsigned arg);
};

Foo::Foo(unsigned arg) : file_id(arg = 42)
{ }

// RUN: %clang_cc1 %s -emit-llvm -o - | FileCheck %s
// PR7291

struct Foo {
  unsigned file_id;

  Foo(unsigned arg);
};

Foo::Foo(unsigned arg) : file_id(arg = 42)
{ }

// CHECK: define void @_ZN3FooC2Ej
// CHECK: [[ARG:%.*]] = alloca i32
// CHECK: store i32 42, i32* [[ARG]]
// CHECK: [[ARGVAL:%.*]] = load i32* [[ARG]]
// CHECK: store i32 [[ARGVAL]], i32* %{{.*}}
// CHECK: ret void

Check the output of this test.

Check the output of this test.

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


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

// <random>

// template<class RealType = double>
// class piecewise_linear_distribution

// template <class charT, class traits>
// basic_ostream<charT, traits>&
// operator<<(basic_ostream<charT, traits>& os,
//            const piecewise_linear_distribution& x);
//
// template <class charT, class traits>
// basic_istream<charT, traits>&
// operator>>(basic_istream<charT, traits>& is,
//            piecewise_linear_distribution& x);

#include <random>
#include <sstream>
#include <cassert>

int main()
{
    {
        typedef std::piecewise_linear_distribution<> D;
        double b[] = {10, 14, 16, 17};
        double p[] = {25, 62.5, 12.5, 25};
        const size_t Np = sizeof(p) / sizeof(p[0]);
        D d1(b, b+Np+1, p);
        std::ostringstream os;
        os << d1;
        std::istringstream is(os.str());
        D d2;
        is >> d2;
        assert(d1 == d2);
    }
}

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

// <random>

// template<class RealType = double>
// class piecewise_linear_distribution

// template <class charT, class traits>
// basic_ostream<charT, traits>&
// operator<<(basic_ostream<charT, traits>& os,
//            const piecewise_linear_distribution& x);
//
// template <class charT, class traits>
// basic_istream<charT, traits>&
// operator>>(basic_istream<charT, traits>& is,
//            piecewise_linear_distribution& x);

#include <random>
#include <sstream>
#include <cassert>

int main()
{
    {
        typedef std::piecewise_linear_distribution<> D;
        double b[] = {10, 14, 16, 17};
        double p[] = {25, 62.5, 12.5, 25};
        const size_t Np = sizeof(p) / sizeof(p[0]);
        D d1(b, b+Np, p);
        std::ostringstream os;
        os << d1;
        std::istringstream is(os.str());
        D d2;
        is >> d2;
        assert(d1 == d2);
    }
}

Fix bug in test; found by AddressSanitizer

git-svn-id: 756ef344af921d95d562d9e9f9389127a89a6314@177464 91177308-0d34-0410-b5e6-96231b3b80d8


/******************************************************************************
 ** Filename:    mfdefs.cpp
 ** Purpose:     Basic routines for manipulating micro-features
 ** Author:      Dan Johnson
 **
 ** (c) Copyright Hewlett-Packard Company, 1988.
 ** 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 "mfdefs.h"

#include <cmath>

namespace tesseract {

/*----------------------------------------------------------------------------
              Public Code
----------------------------------------------------------------------------**/

/**
 * This routine allocates and returns a new micro-feature
 * data structure.
 * @return New MICROFEATURE
 */
MICROFEATURE NewMicroFeature() {
  return (static_cast<MICROFEATURE>(malloc(sizeof(MFBLOCK))));
} /* NewMicroFeature */

/**
 * This routine deallocates all of the memory consumed by
 * a list of micro-features.
 * @param MicroFeatures list of micro-features to be freed
 */
void FreeMicroFeatures(MICROFEATURES MicroFeatures) {
  destroy_nodes(MicroFeatures, free);
} /* FreeMicroFeatures */

} // namespace tesseract

/******************************************************************************
 ** Filename:    mfdefs.cpp
 ** Purpose:     Basic routines for manipulating micro-features
 ** Author:      Dan Johnson
 **
 ** (c) Copyright Hewlett-Packard Company, 1988.
 ** 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 "mfdefs.h"

#include <cmath>

namespace tesseract {

/*----------------------------------------------------------------------------
              Public Code
----------------------------------------------------------------------------**/

/**
 * This routine allocates and returns a new micro-feature
 * data structure.
 * @return New MICROFEATURE
 */
MICROFEATURE NewMicroFeature() {
  return new MFBLOCK;
} /* NewMicroFeature */

/**
 * This routine deallocates all of the memory consumed by
 * a list of micro-features.
 * @param MicroFeatures list of micro-features to be freed
 */
void FreeMicroFeatures(MICROFEATURES MicroFeatures) {
  auto list = MicroFeatures;
  while (list != NIL_LIST) {
    delete first_node(list);
    list = pop(list);
  }
} /* FreeMicroFeatures */

} // namespace tesseract

Replace malloc / free by new / delete for MICROFEATURE

Signed-off-by: Stefan Weil <8d4c780fcfdc41841e5070f4c43da8958ba6aec0@weilnetz.de>


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

#include "chrome/browser/chromeos/legacy_window_manager/initial_browser_window_observer.h"

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

namespace {

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

}  // namespace

namespace chromeos {

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

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

}  // namespace chromeos

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

#include "chrome/browser/chromeos/legacy_window_manager/initial_browser_window_observer.h"

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

namespace {

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

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

}  // namespace

namespace chromeos {

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

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

}  // namespace chromeos

aura: Write initial browser window file from IO thread.

I was carelessly doing this from the UI thread before. :-(

BUG=107938
TEST=none

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

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


#include "qtfirebaseanalytics.h"
#include "qtfirebaseremoteconfig.h"
#include "qtfirebaseadmob.h"
#include "qtfirebaseauth.h"
#include "qtfirebasedatabase.h"

#ifdef QTFIREBASE_BUILD_ANALYTICS
QtFirebaseAnalytics* QtFirebaseAnalytics::self = nullptr;
#endif

#ifdef QTFIREBASE_BUILD_REMOTE_CONFIG
QtFirebaseRemoteConfig* QtFirebaseRemoteConfig::self = nullptr;
#endif

#ifdef QTFIREBASE_BUILD_ADMOB
QtFirebaseAdMob *QtFirebaseAdMob::self = nullptr;
#endif

#ifdef QTFIREBASE_BUILD_AUTH
QtFirebaseAuth *QtFirebaseAuth::self = nullptr;
#endif

#ifdef QTFIREBASE_BUILD_DATABASE
QtFirebaseDatabase *QtFirebaseDatabase::self = nullptr;
#endif

#include "qtfirebaseanalytics.h"
#include "qtfirebaseremoteconfig.h"
#include "qtfirebaseadmob.h"
#include "qtfirebaseauth.h"
#include "qtfirebasedatabase.h"
#include "qtfirebasemessaging.h"

#ifdef QTFIREBASE_BUILD_ANALYTICS
QtFirebaseAnalytics* QtFirebaseAnalytics::self = nullptr;
#endif

#ifdef QTFIREBASE_BUILD_REMOTE_CONFIG
QtFirebaseRemoteConfig* QtFirebaseRemoteConfig::self = nullptr;
#endif

#ifdef QTFIREBASE_BUILD_ADMOB
QtFirebaseAdMob *QtFirebaseAdMob::self = nullptr;
#endif

#ifdef QTFIREBASE_BUILD_AUTH
QtFirebaseAuth *QtFirebaseAuth::self = nullptr;
#endif

#ifdef QTFIREBASE_BUILD_DATABASE
QtFirebaseDatabase *QtFirebaseDatabase::self = nullptr;
#endif

#ifdef QTFIREBASE_BUILD_MESSAGING
QtFirebaseMessaging *QtFirebaseMessaging::self = nullptr;
#endif

Fix build with stub implementation

Fix build with stub implementation