/**
 * \file tiles_costs.cpp
 *
 *
 *
 * \author eaburns
 * \date 05-01-2010
 */

#include <string>
#include <iostream>
using namespace std;

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

#include "tiles_costs.h"

struct cost_tab_ent {
	string name;
	TilesCostFunction &fun;
};

static TilesUnitCost unit_cost = TilesUnitCost();
static TilesSqrtCost sqrt_cost = TilesSqrtCost();
static TilesInverseCost inverse_cost = TilesInverseCost();

// Table of cost functions.
static cost_tab_ent cost_functions[] = {
	{ "", unit_cost }, // default value
	{ "unit", unit_cost },
	{ "sqrt", sqrt_cost },
	{ "inverse", inverse_cost },
};

TilesCostFunction &get_cost_function_by_name(string name)
{
	unsigned int n = sizeof(cost_functions) / sizeof(*cost_functions);
	unsigned int i;

	for (i = 0; i < n; i += 1)
		if (cost_functions[i].name == name)
			return cost_functions[i].fun;

	exit(EXIT_FAILURE);
}

/**
 * \file tiles_costs.cpp
 *
 *
 *
 * \author eaburns
 * \date 05-01-2010
 */

#include <string>
#include <iostream>
using namespace std;

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

#include "tiles_costs.h"

struct cost_tab_ent {
	string name;
	TilesCostFunction &fun;
};

static TilesUnitCost unit_cost = TilesUnitCost();
static TilesSqrtCost sqrt_cost = TilesSqrtCost();
static TilesInverseCost inverse_cost = TilesInverseCost();

// Table of cost functions.
static cost_tab_ent cost_functions[] = {
	{ "", unit_cost }, // default value
	{ "unit", unit_cost },
	{ "sqrt", sqrt_cost },
	{ "inverse", inverse_cost },
};

TilesCostFunction &get_cost_function_by_name(string name)
{
	unsigned int n = sizeof(cost_functions) / sizeof(*cost_functions);
	unsigned int i;

	for (i = 0; i < n; i += 1)
		if (cost_functions[i].name == name)
			return cost_functions[i].fun;

	std::cerr << "Bad cost function: " << name << std::endl;
	exit(EXIT_FAILURE);
}

Print an error on a bad tiles cost function name instead of silently quitting.


#include "google/gtest/gtest.h"

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

#include "google/gtest/gtest.h"
#include <messmer/cpp-utils/assert/backtrace.h>

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

Test cases print stack trace on sigsegv

Test cases print stack trace on sigsegv


/* * This file is part of Maliit framework *
 *
 * Copyright (C) 2014 Dinesh Manajipet <saidinesh5@gmail.com>
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License version 2.1 as published by the Free Software Foundation
 * and appearing in the file LICENSE.LGPL included in the packaging
 * of this file.
 */

#include "mirplatform.h"
#include "mirplatformconnection.h"

#include <QRegion>
#include <QWindow>

namespace Maliit {

MirPlatform::MirPlatform():
    AbstractPlatform(),
    m_mirPlatformConnection(new MirPlatformConnection)
{
}

void MirPlatform::setupInputPanel(QWindow *window, Maliit::Position position)
{
    Q_UNUSED(window)
    Q_UNUSED(position)
}

void MirPlatform::setInputRegion(QWindow *window, const QRegion &region)
{
    Q_UNUSED(window)

    if (!region.rects().isEmpty()) {
        m_mirPlatformConnection->setGeometry(region.rects().first());
    }
}

}

/* * This file is part of Maliit framework *
 *
 * Copyright (C) 2014 Dinesh Manajipet <saidinesh5@gmail.com>
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License version 2.1 as published by the Free Software Foundation
 * and appearing in the file LICENSE.LGPL included in the packaging
 * of this file.
 */

#include "mirplatform.h"
#include "mirplatformconnection.h"

#include <QRegion>
#include <QWindow>
#include <QVariant>

#include <ubuntu/application/ui/window_properties.h>

namespace Maliit {

MirPlatform::MirPlatform():
    AbstractPlatform(),
    m_mirPlatformConnection(new MirPlatformConnection)
{
}

void MirPlatform::setupInputPanel(QWindow *window, Maliit::Position position)
{
    Q_UNUSED(position)
    window->setProperty("role", QVariant(U_ON_SCREEN_KEYBOARD_ROLE));
}

void MirPlatform::setInputRegion(QWindow *window, const QRegion &region)
{
    Q_UNUSED(window)

    if (!region.rects().isEmpty()) {
        m_mirPlatformConnection->setGeometry(region.rects().first());
    }
}

}

Set window role for Mir backend

Set window role for Mir backend


#include "MMU.hpp"

#include <iterator>
#include <limits>

namespace Core8 {

Chip8::BYTE MMU::readByte(const std::size_t address) const {
  const auto byte = memory.at(address);

  return byte;
}

Chip8::WORD MMU::readWord(const std::size_t address) const {
  const auto msb = memory.at(address) << std::numeric_limits<Chip8::BYTE>::digits;
  const auto lsb = memory.at(address + 1);

  return msb | lsb;
}

void MMU::writeByte(const Chip8::BYTE byte, const std::size_t address) {
  memory.at(address) = byte;
}

void MMU::load(std::istream& rom, const std::size_t address) {
  std::noskipws(rom);

  std::copy(std::istream_iterator<Chip8::BYTE>(rom),
            std::istream_iterator<Chip8::BYTE>(),
            &memory.at(address));
}

void MMU::clear() {
  memory.fill(0x0);
}

} // namespace Core8

#include "MMU.hpp"

#include <algorithm>
#include <iterator>
#include <limits>
#include <vector>

namespace Core8 {

Chip8::BYTE MMU::readByte(const std::size_t address) const {
  const auto byte = memory.at(address);

  return byte;
}

Chip8::WORD MMU::readWord(const std::size_t address) const {
  const auto msb = memory.at(address) << std::numeric_limits<Chip8::BYTE>::digits;
  const auto lsb = memory.at(address + 1);

  return msb | lsb;
}

void MMU::writeByte(const Chip8::BYTE byte, const std::size_t address) {
  memory.at(address) = byte;
}

void MMU::load(std::istream& rom, const std::size_t address) {
  std::noskipws(rom);

  const std::vector<Chip8::BYTE> data{std::istream_iterator<Chip8::BYTE>(rom),
                                      std::istream_iterator<Chip8::BYTE>()};

  const auto availableMemory = memory.size() - address;
  const auto dataSize = data.size();
  const auto length = dataSize > availableMemory ? availableMemory : dataSize;

  std::copy_n(std::begin(data), length,
              std::next(std::begin(memory), address));
}

void MMU::clear() {
  memory.fill(0x0);
}

} // namespace Core8

Fix load rom memory boundaries

Fix load rom memory boundaries


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

#ifdef _WIN32
#define NOMINMAX
#include <winsock2.h>
#else
#include <sys/socket.h>
#include <netinet/in.h>
#include <poll.h>
#endif
#include "Network.hpp"
#include "utils/Log.hpp"

namespace ouzel
{
    namespace network
    {
        Network::Network()
        {
        }

        Network::~Network()
        {
            WSACleanup();
        }

        bool Network::init()
        {
#ifdef _WIN32
            WORD sockVersion = MAKEWORD(2, 2);
            WSADATA wsaData;
            int error = WSAStartup(sockVersion, &wsaData);
            if (error != 0)
            {
                Log(Log::Level::ERR) << "Failed to start Winsock failed, error: " << error;
                return false;
            }

            if (wsaData.wVersion != sockVersion)
            {
                Log(Log::Level::ERR) << "Incorrect Winsock version";
                WSACleanup();
                return false;
            }
#endif

            return true;
        }
    } // namespace network
} // namespace ouzel

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

#ifdef _WIN32
#define NOMINMAX
#include <winsock2.h>
#else
#include <sys/socket.h>
#include <netinet/in.h>
#include <poll.h>
#endif
#include "Network.hpp"
#include "utils/Log.hpp"

namespace ouzel
{
    namespace network
    {
        Network::Network()
        {
        }

        Network::~Network()
        {
#ifdef _WIN32
            WSACleanup();
#endif
        }

        bool Network::init()
        {
#ifdef _WIN32
            WORD sockVersion = MAKEWORD(2, 2);
            WSADATA wsaData;
            int error = WSAStartup(sockVersion, &wsaData);
            if (error != 0)
            {
                Log(Log::Level::ERR) << "Failed to start Winsock failed, error: " << error;
                return false;
            }

            if (wsaData.wVersion != sockVersion)
            {
                Log(Log::Level::ERR) << "Incorrect Winsock version";
                WSACleanup();
                return false;
            }
#endif

            return true;
        }
    } // namespace network
} // namespace ouzel

Call WSACleanup only on Windows

Call WSACleanup only on Windows


#include <SFML/Graphics.hpp>
#include <SFML/System/Clock.hpp>
#include <iostream>

int main() {
    sf::RenderWindow window(sf::VideoMode(800,600),  "Psychic Dangerzone");
    window.setVerticalSyncEnabled(true);

    sf::Clock world_clock;

    float last_frame_time;
    while(window.isOpen()) {
        last_frame_time = world_clock.getElapsedTime().asSeconds();

        sf::Event event;
        while(window.pollEvent(event)) {
            // TODO: process events
            if(event.type == sf::Event::Closed) {
                window.close();
            }
        }

        window.clear(sf::Color::Black);
        window.display();
        std::cout << world_clock.getElapsedTime().asSeconds() - last_frame_time << std::endl;
    }

    return 0;
}

#include <SFML/Graphics.hpp>
#include <SFML/System/Clock.hpp>
#include <iostream>

int main() {
    sf::RenderWindow window(sf::VideoMode(800,600),  "Psychic Dangerzone");
    window.setVerticalSyncEnabled(true);

    sf::Clock world_clock;

    sf::CircleShape player(50);

    float last_frame_time;
    while(window.isOpen()) {
        last_frame_time = world_clock.getElapsedTime().asSeconds();

        sf::Event event;
        while(window.pollEvent(event)) {
            if(event.type == sf::Event::Closed) {
                window.close();
            }
        }

        sf::Vector2f velocity;
        if (sf::Keyboard::isKeyPressed(sf::Keyboard::Left)) {
          velocity.x -= 10;
        }
        if (sf::Keyboard::isKeyPressed(sf::Keyboard::Right)) {
          velocity.x += 10;
        }
        if (sf::Keyboard::isKeyPressed(sf::Keyboard::Up)) {
          velocity.y -= 10;
        }
        if (sf::Keyboard::isKeyPressed(sf::Keyboard::Down)) {
          velocity.y += 10;
        }

        player.move(velocity);
        //player.move(velocity.x, velocity.y);

        window.clear(sf::Color::Black);

        window.draw(player);

        window.display();
        std::cout << world_clock.getElapsedTime().asSeconds() - last_frame_time << std::endl;
    }

    return 0;
}

Add a player circle that can move

Add a player circle that can move


#include "gtest/gtest.h"
#include "lms/endian.h"

TEST(Endian, uint16) {
    using lms::Endian;
    ASSERT_EQ(uint16_t(0xCAFEu), Endian::betoh(Endian::htobe(uint16_t(0xCAFEu))));
    ASSERT_EQ(uint16_t(0xCAFEu), Endian::letoh(Endian::htole(uint16_t(0xCAFEu))));
}

TEST(Endian, uint32) {
    using lms::Endian;
    ASSERT_EQ(uint32_t(0xDEADBEEFu), Endian::betoh(Endian::htobe(uint32_t(0xDEADBEEFu))));
    ASSERT_EQ(uint32_t(0xDEADBEEFu), Endian::letoh(Endian::htole(uint32_t(0xDEADBEEFu))));
}

TEST(Endian, uint64) {
    using lms::Endian;
    ASSERT_EQ(uint64_t(0xFEEDCAFEDEADBEEFu), Endian::betoh(Endian::htobe(uint64_t(0xFEEDCAFEDEADBEEFu))));
    ASSERT_EQ(uint64_t(0xFEEDCAFEDEADBEEFu), Endian::letoh(Endian::htole(uint64_t(0xFEEDCAFEDEADBEEFu))));
}

#include "gtest/gtest.h"
#include "lms/endian.h"

TEST(Endian, uint16) {
    using lms::Endian;
    ASSERT_EQ(0xFECAu, Endian::letoh(Endian::htobe(uint16_t(0xCAFEu))));
    ASSERT_EQ(0xFECAu, Endian::betoh(Endian::htole(uint16_t(0xCAFEu))));
}

TEST(Endian, uint32) {
    using lms::Endian;
    ASSERT_EQ(0xEFBEADDEu, Endian::letoh(Endian::htobe(uint32_t(0xDEADBEEFu))));
    ASSERT_EQ(0xEFBEADDEu, Endian::betoh(Endian::htole(uint32_t(0xDEADBEEFu))));
}

TEST(Endian, uint64) {
    using lms::Endian;
    ASSERT_EQ(0xEFBEADDEFECAEDFEu, Endian::letoh(Endian::htobe(0xFEEDCAFEDEADBEEFu)));
    ASSERT_EQ(0xEFBEADDEFECAEDFEu, Endian::betoh(Endian::htole(0xFEEDCAFEDEADBEEFu)));
}

Improve test cases for lms::Endian

Improve test cases for lms::Endian


#include "linalg/ray.h"
#include "geometry/differential_geometry.h"
#include "geometry/geometry.h"
#include "scene.h"
#include "integrator/surface_integrator.h"
#include "renderer/renderer.h"

Renderer::Renderer(std::unique_ptr<SurfaceIntegrator> surface_integrator)
	: surface_integrator(std::move(surface_integrator))
{}
Colorf Renderer::illumination(RayDifferential &ray, const Scene &scene) const {
	DifferentialGeometry dg;
	if (scene.get_root().intersect(ray, dg)){
		dg.compute_differentials(ray);
		return surface_integrator->illumination(scene, *this, ray, dg);
	}
	else {
		//TODO: Compute light along the ray coming from lights
		return Colorf{0};
	}
}

#include "linalg/ray.h"
#include "geometry/differential_geometry.h"
#include "geometry/geometry.h"
#include "scene.h"
#include "integrator/surface_integrator.h"
#include "renderer/renderer.h"

Renderer::Renderer(std::unique_ptr<SurfaceIntegrator> surface_integrator)
	: surface_integrator(std::move(surface_integrator))
{}
Colorf Renderer::illumination(RayDifferential &ray, const Scene &scene) const {
	DifferentialGeometry dg;
	if (scene.get_root().intersect(ray, dg)){
		dg.compute_differentials(ray);
		return surface_integrator->illumination(scene, *this, ray, dg);
	}
	else if (scene.get_environment()){
		//TODO: Compute light along the ray coming from lights
		DifferentialGeometry dg;
		dg.point = Point{ray.d.x, ray.d.y, ray.d.z};
		return scene.get_environment()->sample(dg);
	}
	return Colorf{0};
}

Fix regression of not taking into account environment map

Although this will likely be migrated to treat as an infinite area light
source like PBR does


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

// Verify that we can't initialize non-aggregates with an initializer
// list.
struct NonAggr1 {
  NonAggr1(int) { }

  int m;
};

struct Base { };
struct NonAggr2 : public Base {
  int m;
};

class NonAggr3 {
  int m;
};

struct NonAggr4 {
  int m;
  virtual void f();
};

NonAggr1 na1 = { 17 }; // expected-error{{non-aggregate type 'struct NonAggr1' cannot be initialized with an initializer list}}
NonAggr2 na2 = { 17 }; // expected-error{{non-aggregate type 'struct NonAggr2' cannot be initialized with an initializer list}}
NonAggr3 na3 = { 17 }; // expected-error{{non-aggregate type 'class NonAggr3' cannot be initialized with an initializer list}}
NonAggr4 na4 = { 17 }; // expected-error{{non-aggregate type 'struct NonAggr4' cannot be initialized with an initializer list}}

// PR5817
typedef int type[][2];
const type foo = {0};

Add testcase for PR5817, although the bug was already fixed

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


#include "generator.h"

#include <iostream>
#include <fstream>

using namespace Mugen;

CharacterGenerator::CharacterGenerator(const std::string & filename):
filename(filename){
}

CharacterGenerator::~CharacterGenerator(){
}

void CharacterGenerator::output(const std::string & file){
    Mugen::PythonStream out;
    out.open(file);
    out << "import mugen" << PythonStream::endl;
    out <<  "class TestCharacter(mugen.Character):" << PythonStream::endl;
    out << PythonStream::indent;
    out << "def __init__(self):" << PythonStream::endl;
    out << PythonStream::indent;
    out << "self.setName('TestCharacter')" << PythonStream::endl;
    out.clearIndents();
    out << "char = TestCharacter()" << PythonStream::endl;
    out << "print char.name" << PythonStream::endl;
    out.close();
}

Indent code to more or less visualize the indentation of the outputed python code.


#include <istream>
#include <fstream>
#include <set>
#include <vector>
#include <array>
#include <algorithm>
#include <iterator>

using namespace std;

int main() {
	ifstream cin("combo.in");
	ofstream cout("combo.out");

	int size;
	cin >> size;

	set<int> options;
	for (int i = 0; i < 2; i++) {
		int a, b, c;
		cin >> a >> b >> c;

		// creates permutations of allowable combinations and turns them into
		// an integer so that set can compare them and only retain uniques

		// the indexes here start at -3 and end at +1 because the input starts
		// at 1 but here we want it to start at 0
		for (int i = a - 3; i <= a + 1; i++) {
			for (int j = b - 3; j <= b + 1; j++) {
				for (int k = c - 3; k <= c + 1; k++) {
					options.insert(((((i % size) + size) % size) << 0) +
								   ((((j % size) + size) % size) << 8) +
								   ((((k % size) + size) % size) << 16));
				}
			}
		}
	}

	// the size of the set is the number of unique combinations
	cout << options.size() << endl;

	return 0;
}

#include <fstream>
#include <set>

using namespace std;

int main() {
	ifstream cin("combo.in");
	ofstream cout("combo.out");

	int size;
	cin >> size;

	set<int> options;
	for (int i = 0; i < 2; i++) {
		int a, b, c;
		cin >> a >> b >> c;

		// creates permutations of allowable combinations and turns them into
		// an integer so that set can compare them and only retain uniques

		// the indexes here start at -3 and end at +1 because the input starts
		// at 1 but here we want it to start at 0
		for (int i = a - 3; i <= a + 1; i++) {
			for (int j = b - 3; j <= b + 1; j++) {
				for (int k = c - 3; k <= c + 1; k++) {
					options.insert(((((i % size) + size) % size) << 0) +
								   ((((j % size) + size) % size) << 8) +
								   ((((k % size) + size) % size) << 16));
				}
			}
		}
	}

	// the size of the set is the number of unique combinations
	cout << options.size() << endl;

	return 0;
}

Remove unused includes from the C++11 solution for Nov. 2013 Bronze Problem 1


/*
 * ModSecurity, http://www.modsecurity.org/
 * Copyright (c) 2015 Trustwave Holdings, Inc. (http://www.trustwave.com/)
 *
 * 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
 *
 * If any of the files related to licensing are missing or if you have any
 * other questions related to licensing please contact Trustwave Holdings, Inc.
 * directly using the email address security@modsecurity.org.
 *
 */

#include "regression/custom_debug_log.h"

#include <iostream>
#include <string>

#include "modsecurity/debug_log.h"
#include "utils/regex.h"

namespace modsecurity_test {

CustomDebugLog *CustomDebugLog::new_instance() {
    return new CustomDebugLog();
}

void CustomDebugLog::write(int level, const std::string& message) {
    m_log << "[" << level << "] " << message << std::endl;
}

bool CustomDebugLog::contains(const std::string& pattern) {
    ModSecurity::Utils::Regex re(pattern);
    ModSecurity::Utils::SMatch match;
    std::string s = m_log.str();
    return (ModSecurity::Utils::regex_search(s, &match, re)
        && match.size() >= 1);
}

std::string CustomDebugLog::log_messages() {
    return m_log.str();
}

}  // namespace modsecurity_test

/*
 * ModSecurity, http://www.modsecurity.org/
 * Copyright (c) 2015 Trustwave Holdings, Inc. (http://www.trustwave.com/)
 *
 * 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
 *
 * If any of the files related to licensing are missing or if you have any
 * other questions related to licensing please contact Trustwave Holdings, Inc.
 * directly using the email address security@modsecurity.org.
 *
 */

#include "regression/custom_debug_log.h"

#include <iostream>
#include <string>

#include "modsecurity/debug_log.h"
#include "utils/regex.h"

namespace modsecurity_test {

CustomDebugLog *CustomDebugLog::new_instance() {
    return new CustomDebugLog();
}

void CustomDebugLog::write(int level, const std::string& message) {
    m_log << "[" << level << "] " << message << std::endl;
}

bool CustomDebugLog::contains(const std::string& pattern) {
    ModSecurity::Utils::Regex re(pattern);
    ModSecurity::Utils::SMatch match;
    std::string s = m_log.str();
    return ModSecurity::Utils::regex_search(s, re);
}

std::string CustomDebugLog::log_messages() {
    return m_log.str();
}

}  // namespace modsecurity_test

Fix the regression test regexp validation


// RUN: clang-diff -ast-dump %s -- \
// RUN: | %python -c 'import json, sys; json.dump(json.loads(sys.stdin.read()), sys.stdout, sort_keys=True, indent=2)' \
// RUN: | FileCheck %s

// CHECK: "begin": 294,
// CHECK: "type": "CXXRecordDecl",
// CHECK: "type": "FieldDecl",
// CHECK: "end": 314,
class A {
  int x;
};

// CHECK: "children": [
// CHECK-NEXT: {
// CHECK-NEXT: "begin":
// CHECK-NEXT: "children": []
// CHECK-NEXT: "end":
// CHECK-NEXT: "id":
// CHECK-NEXT: "type": "CharacterLiteral"
// CHECK-NEXT: }
// CHECK: ]
// CHECK: "type": "VarDecl",
char nl = '\n';

// CHECK: "value": "abc \n\t\u0000\u001f\u0123 \ub370\ubc15"
char s[] = "abc \n\t\0\x1f\u0123 데박";

// RUN: clang-diff -ast-dump %s -- \
// RUN: | %python -c 'import json, sys; json.dump(json.loads(sys.stdin.read()), sys.stdout, sort_keys=True, indent=2)' \
// RUN: | FileCheck %s

// CHECK: "begin": 294,
// CHECK: "type": "CXXRecordDecl",
// CHECK: "type": "FieldDecl",
// CHECK: "end": 314,
class A {
  int x;
};

// CHECK: "children": [
// CHECK-NEXT: {
// CHECK-NEXT: "begin":
// CHECK-NEXT: "children": []
// CHECK-NEXT: "end":
// CHECK-NEXT: "id":
// CHECK-NEXT: "type": "CharacterLiteral"
// CHECK-NEXT: }
// CHECK: ]
// CHECK: "type": "VarDecl",
char nl = '\n';

// CHECK: "value": "abc \n\t\u0000\u001f"
char s[] = "abc \n\t\0\x1f";

Fix test for python 3

[clang-diff] Fix test for python 3

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


/*
// This file is part of SnakePredictor
//
//  (c) Daniel McAssey <hello@glokon.me>
//
// For the full copyright and license information, please view the LICENSE
// file that was distributed with this source code.
*/
// stdafx.cpp : source file that includes just the standard includes
// CallWinsock.pch will be the pre-compiled header
// stdafx.obj will contain the pre-compiled type information

#include "stdafx.h"

// TODO: reference any additional headers you need in STDAFX.H
// and not in this file

/*
// This file is part of SnakePredictor
//
//  (c) Daniel McAssey <hello@glokon.me>
//
// For the full copyright and license information, please view the LICENSE
// file that was distributed with this source code.
*/
// stdafx.cpp : source file that includes just the standard includes
// SnakePredictor.pch will be the pre-compiled header
// stdafx.obj will contain the pre-compiled type information

#include "stdafx.h"

// TODO: reference any additional headers you need in STDAFX.H
// and not in this file

Fix incorrect comment on precompiled header


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

#include "datastore.h"

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

namespace YouDataStoreTests {
TEST_CLASS(DataStoreApiTest) {
public:
	TEST_METHOD(DataStoreDummyTest) {
		// You::DataStore::DataStore sut;
		// sut.post(std::unordered_map<std::wstring, std::wstring>());
		Assert::IsTrue(true);
	}
};
}  // namespace YouDataStoreTests

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

#include "datastore.h"

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

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

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

Add unit test for post method

Add unit test for post method


#include <ionWindow.h>
#include <ionGraphicsGL.h>

using namespace ion;

int main()
{
	Log::AddDefaultOutputs();

	SingletonPointer<CWindowManager> WindowManager;
	SingletonPointer<CGraphicsAPI> GraphicsAPI;

	GraphicsAPI->Init(new Graphics::COpenGLImplementation());
	WindowManager->Init(GraphicsAPI);
	WindowManager->CreateWindow(vec2i(640, 480), "TestWindowManager", EWindowType::Windowed);

	while (! WindowManager->ShouldClose())
		WindowManager->PollEvents();

	return 0;
}

#include <ionWindow.h>
#include <ionGraphicsGL.h>

using namespace ion;

int main()
{
	Log::AddDefaultOutputs();

	Log::Info("Info");
	Log::Warn("Warning");
	Log::Error("Error");

	SingletonPointer<CWindowManager> WindowManager;
	SingletonPointer<CGraphicsAPI> GraphicsAPI;

	GraphicsAPI->Init(new Graphics::COpenGLImplementation());
	WindowManager->Init(GraphicsAPI);
	WindowManager->CreateWindow(vec2i(640, 480), "TestWindowManager", EWindowType::Windowed);

	while (! WindowManager->ShouldClose())
	{
		WindowManager->PollEvents();
	}

	return 0;
}

Add example of log channels

[Demo01] Add example of log channels


/* This file is part of python_mapnik (c++/python mapping toolkit)
 * Copyright (C) 2005 Artem Pavlenko, Jean-Francois Doyon
 *
 * Mapnik is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or any later version.
 *
 * This program 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 General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 */

//$Id$

#include <boost/python.hpp>
#include <mapnik.hpp>

using mapnik::text_symbolizer;
using mapnik::Color;

void export_text_symbolizer()
{
    using namespace boost::python;

    class_<text_symbolizer>("TextSymbolizer",
			    init<std::string const&,unsigned,Color const&>("TODO"))
	;
}

/* This file is part of python_mapnik (c++/python mapping toolkit)
 * Copyright (C) 2005 Artem Pavlenko, Jean-Francois Doyon
 *
 * Mapnik is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or any later version.
 *
 * This program 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 General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 */

//$Id$

#include <boost/python.hpp>
#include <mapnik.hpp>

using mapnik::text_symbolizer;
using mapnik::Color;

void export_text_symbolizer()
{
    using namespace boost::python;

    class_<text_symbolizer>("TextSymbolizer",
			    init<std::string const&,unsigned,Color const&>())
        .add_property("halo_fill",make_function(
                      &text_symbolizer::get_halo_fill,return_value_policy<copy_const_reference>()),
                      &text_symbolizer::set_halo_fill)
        .add_property("halo_radius",&text_symbolizer::get_halo_radius, &text_symbolizer::set_halo_radius)
	;
}

Add support for halo's to TextSymbolizer().

git-svn-id: 5adfda8227e14e59fd47d5bd9925a30df16fed74@184 d397654b-2ff0-0310-9e29-ba003691a0f9


#include <boost/config.hpp>

struct Foo {
  char x;
#include <leathers/push>
#include <leathers/padded>
  long y;
#include <leathers/pop>
};

int main() {
  // struct Foo must be used, otherwise there will be no warning (clang)
  return static_cast<int>(Foo().y);
}

#include <boost/config.hpp>

struct Foo {
  char x;
#include <leathers/push>
#if !defined(SHOW_WARNINGS)
# include <leathers/padded>
#endif
  long y;
#include <leathers/pop>
};

int main() {
  // struct Foo must be used, otherwise there will be no warning (clang)
  return static_cast<int>(Foo().y);
}

Check SHOW_WARNINGS macro in example

Check SHOW_WARNINGS macro in example


// Copyright (c) 2018 Chris Ohk, Youngjoong Kim, SeungHyun Jeon

// We are making my contributions/submissions to this project solely in our
// personal capacity and are not conveying any rights to any intellectual
// property of any third parties.

#include <Utils/TestUtils.hpp>
#include "gtest/gtest.h"

#include <hspp/Cards/Minion.hpp>
#include <hspp/Managers/GameAgent.hpp>
#include <hspp/Tasks/SimpleTasks/ControlTask.hpp>

using namespace Hearthstonepp;
using namespace SimpleTasks;
using namespace TestUtils;

TEST(ControlTask, GetTaskID)
{
    const ControlTask control(EntityType::TARGET);
    EXPECT_EQ(control.GetTaskID(), +TaskID::CONTROL);
}

TEST(ControlTask, Run)
{
    GameAgent agent(CardClass::ROGUE, CardClass::DRUID, PlayerType::PLAYER1);
    Player& player1 = agent.GetPlayer1();
    Player& player2 = agent.GetPlayer2();

    std::vector<Card> cards;
    cards.reserve(5);

    const std::string name = "test";
    for (size_t i = 0; i < 5; ++i)
    {
        const auto id = static_cast<char>(i + 0x30);
        cards.emplace_back(GenerateMinionCard(name + id, 1, 1));
        PlayMinionCard(player1, cards[i]);
        PlayMinionCard(player2, cards[i]);
    }

    ControlTask control(EntityType::TARGET);
    control.SetTarget(player2.GetField()[0]);
    MetaData result = control.Run(player1);

    EXPECT_EQ(result, MetaData::CONTROL_SUCCESS);
    EXPECT_EQ(player1.GetField().size(), 6u);
    EXPECT_EQ(player2.GetField().size(), 4u);
}

Add unit test for ControlTask

[WIP] test: Add unit test for ControlTask


#include <avr/io.h>

#include "lcd.h"

LCD5110 myGLCD;

void LCD_init(void)
{
  /* Set MOSI and SCK output */
  DDRB |= (1<<PB3)|(1<<PB5);

  /* Enable SPI, Master, CPOL=1, CPHA=1 */
  /* Also: MSB first, clock=fosc/4 */
  SPCR = (1<<SPE)|(1<<MSTR)|(1<<CPOL)|(1<<CPHA) | 3;

  /* Set the pins for DC, RST and CS to output */
  DDRB |= (1<<PB0) | (1<<PB2);
  DDRC |= (1<<PC0);

  myGLCD.InitLCD(0x46);
}

#include <avr/io.h>

#include "lcd.h"

LCD5110 myGLCD;

void LCD_init(void)
{
  /* Set MOSI and SCK output */
  DDRB |= (1<<PB3)|(1<<PB5);

  /* Enable SPI, Master, CPOL=1, CPHA=1 */
  /* Also: MSB first, clock=fosc/4 */
  SPCR = (1<<SPE)|(1<<MSTR)|(1<<CPOL)|(1<<CPHA) | (1<<SPR0);

  /* Set the pins for DC, RST and CS to output */
  DDRB |= (1<<PB0) | (1<<PB2);
  DDRC |= (1<<PC0);

  myGLCD.InitLCD(0x46);
}

Use a faster SPI clock to the LCD

Use a faster SPI clock to the LCD


#include "chunk.hpp"
#include "chunk_master.hpp"
#include "code/ylikuutio/hierarchy/hierarchy_templates.hpp"

namespace yli
{
    namespace ontology
    {
        void Chunk::bind_to_parent()
        {
            // requirements:
            // `this->parent` must not be `nullptr`.
            yli::ontology::ChunkMaster* const chunk_master = this->parent;

            if (chunk_master == nullptr)
            {
                std::cerr << "ERROR: `Chunk::bind_to_parent`: `chunk_master` is `nullptr`!\n";
                return;
            }

            // get `childID` from the `ChunkMaster` and set pointer to this `Chunk`.
            chunk_master->bind_chunk(this);
        }

        Chunk::~Chunk()
        {
            // destructor.

            // set pointer to this `Chunk` to nullptr.
            this->parent->set_chunk_pointer(this->childID, nullptr);
        }

        void Chunk::render()
        {
            if (this->vram_buffer_in_use)
            {
                // Render this `Chunk`.
                // If any vertex of the `Chunk` has changed, the vertex data
                // of the `Chunk` needs to be reconstructed before rendering.
            }
        }
    }
}

#include "chunk.hpp"
#include "chunk_master.hpp"
#include "code/ylikuutio/hierarchy/hierarchy_templates.hpp"

namespace yli
{
    namespace ontology
    {
        void Chunk::bind_to_parent()
        {
            // requirements:
            // `this->parent` must not be `nullptr`.
            yli::ontology::ChunkMaster* const chunk_master = this->parent;

            if (chunk_master == nullptr)
            {
                std::cerr << "ERROR: `Chunk::bind_to_parent`: `chunk_master` is `nullptr`!\n";
                return;
            }

            // get `childID` from the `ChunkMaster` and set pointer to this `Chunk`.
            chunk_master->bind_chunk(this);
        }

        Chunk::~Chunk()
        {
            // destructor.
            //
            // requirements:
            // `this->parent` must not be `nullptr`.
            yli::ontology::ChunkMaster* const chunk_master = this->parent;

            if (chunk_master == nullptr)
            {
                std::cerr << "ERROR: `Chunk::~Chunk`: `chunk_master` is `nullptr`!\n";
                return;
            }

            chunk_master->unbind_chunk(this->childID);
        }

        void Chunk::render()
        {
            if (this->vram_buffer_in_use)
            {
                // Render this `Chunk`.
                // If any vertex of the `Chunk` has changed, the vertex data
                // of the `Chunk` needs to be reconstructed before rendering.
            }
        }
    }
}

`Chunk::~Chunk`: Check `parent` for `nullptr`. Cleaning up code.

	modified:   code/ylikuutio/ontology/chunk.cpp


// Native C++ Libraries
#include <iostream>
#include <string>

// C++ Interpreter Libraries
#include <Console.h>

using namespace std;

int main()
{

}

// Native C++ Libraries
#include <iostream>
#include <string>

// C++ Interpreter Libraries
#include <Console.h>

using namespace std;

int main()
{
	RESTART:
	string input = "";
	getline(cin, input);
	cin.ignore();
	goto RESTART;
}

Add a way of Input and program loop.

Add a way of Input and program loop.

Added a way of enabling input from the user. The loop is used for to
reset the program instead of exiting from it.


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

// debug.cpp: Debugging utilities.

#include "compiler/translator/compilerdebug.h"

#include <stdarg.h>
#include <stdio.h>

#include "compiler/translator/InitializeParseContext.h"
#include "compiler/translator/ParseContext.h"

static const int kTraceBufferLen = 1024;

#ifdef TRACE_ENABLED
extern "C" {
void Trace(const char *format, ...) {
    if (!format) return;

    TParseContext* parseContext = GetGlobalParseContext();
    if (parseContext) {
        char buf[kTraceBufferLen];
        va_list args;
        va_start(args, format);
        vsnprintf(buf, kTraceBufferLen, format, args);
        va_end(args);

        parseContext->trace(buf);
    }
}
}  // extern "C"
#endif  // TRACE_ENABLED

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

// debug.cpp: Debugging utilities.

#include "compiler/translator/compilerdebug.h"

#include <stdarg.h>
#include <stdio.h>

#include "compiler/translator/InitializeParseContext.h"
#include "compiler/translator/ParseContext.h"

#ifdef TRACE_ENABLED
static const int kTraceBufferLen = 1024;

extern "C" {
void Trace(const char *format, ...) {
    if (!format) return;

    TParseContext* parseContext = GetGlobalParseContext();
    if (parseContext) {
        char buf[kTraceBufferLen];
        va_list args;
        va_start(args, format);
        vsnprintf(buf, kTraceBufferLen, format, args);
        va_end(args);

        parseContext->trace(buf);
    }
}
}  // extern "C"
#endif  // TRACE_ENABLED

Fix unused variable warning in compiler/debug.cpp.

BUG=angle:534

Change-Id: I893e552628c7deba4bc67baae6e5e28b6161c5d4
Reviewed-on: https://chromium-review.googlesource.com/178438
Reviewed-by: Geoff Lang <b6fc25fe0362055230985c05cbfa8adb741ccc0f@chromium.org>
Commit-Queue: Geoff Lang <b6fc25fe0362055230985c05cbfa8adb741ccc0f@chromium.org>
Tested-by: Geoff Lang <b6fc25fe0362055230985c05cbfa8adb741ccc0f@chromium.org>


#include <miniMAT/util/NumDigits.hpp>

#include <cmath>

namespace miniMAT {
    namespace util {
        int NumDigits(double num) {
            return log10(num) + 1;
        }
    }
}

#include <miniMAT/util/NumDigits.hpp>

#include <cmath>

namespace miniMAT {
    namespace util {
        int NumDigits(double num) {
            return num == 0 ? 1 : fabs(log10(num)) + 1;
        }
    }
}

Fix bug involving printing 'zeroed' matrices


#include "RestServer.h"

#include <qhttpserver.hpp>
#include <qhttpserverrequest.hpp>
#include <qhttpserverresponse.hpp>
#include <QLoggingCategory>

Q_LOGGING_CATEGORY(REST, "ledify.restserver", QtWarningMsg)

using namespace qhttp::server;

RestServer::RestServer(QObject *parent) : QObject(parent) {
    m_server = new QHttpServer(this);
    m_server->listen(QHostAddress::Any, 8033, [this] (QHttpRequest* req, QHttpResponse* res) {
        emit requestReceived(req, res);
    });

    if ( m_server->isListening() ) {
        qCDebug(REST, "Started REST server");
    } else {
        qCWarning(REST, "Failed to start REST server");
    }
}

void RestServer::requestReceived(QHttpRequest *req, QHttpResponse *res) {
    QString urlString = req->url().toString();

    if (urlString.size() < 2) {
        res->setStatusCode(qhttp::ESTATUS_NOT_ACCEPTABLE);
        res->end("Send me more!\n");
        return;
    }
    auto command = urlString.mid(1);
    qCDebug(REST) << "Received command" << command;
    res->setStatusCode(qhttp::ESTATUS_OK);
    res->end(m_callback(command).toUtf8());
}

#include "RestServer.h"

#include <qhttpserver.hpp>
#include <qhttpserverrequest.hpp>
#include <qhttpserverresponse.hpp>
#include <QLoggingCategory>

Q_LOGGING_CATEGORY(REST, "ledify.restserver", QtWarningMsg)

using namespace qhttp::server;

RestServer::RestServer(QObject *parent) : QObject(parent) {
    m_server = new QHttpServer(this);
    m_server->listen(QHostAddress::Any, 8033, [this] (QHttpRequest* req, QHttpResponse* res) {
        emit requestReceived(req, res);
    });

    if ( m_server->isListening() ) {
        qCDebug(REST, "Started REST server");
    } else {
        qCWarning(REST, "Failed to start REST server");
    }
}

void RestServer::requestReceived(QHttpRequest *req, QHttpResponse *res) {
    QString urlString = req->url().toString();

    if (urlString.size() < 2) {
        res->setStatusCode(qhttp::ESTATUS_NOT_ACCEPTABLE);
        res->end("Send me more!\n");
        return;
    }
    auto commands = urlString.mid(1);

    QByteArray responses = "";
    foreach(auto command, commands.split("+", QString::SplitBehavior::SkipEmptyParts)) {
        qCDebug(REST) << "Received command" << command;
        responses += m_callback(command).toUtf8() + ";";
    }
    res->setStatusCode(qhttp::ESTATUS_OK);
    res->end(responses);
}

Allow multiple commands to be sent to the server


//===--- OpenMPKinds.cpp - Token Kinds Support ----------------------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
/// \file
/// \brief This file implements the OpenMP enum and support functions.
///
//===----------------------------------------------------------------------===//

#include "clang/Basic/OpenMPKinds.h"
#include "clang/Basic/IdentifierTable.h"
#include "clang/Lex/Token.h"
#include "llvm/ADT/StringSwitch.h"
#include "llvm/Support/ErrorHandling.h"
#include <cassert>

using namespace clang;

OpenMPDirectiveKind clang::getOpenMPDirectiveKind(StringRef Str) {
  return llvm::StringSwitch<OpenMPDirectiveKind>(Str)
#define OPENMP_DIRECTIVE(Name) \
           .Case(#Name, OMPD_##Name)
#include "clang/Basic/OpenMPKinds.def"
           .Default(OMPD_unknown);
}

const char *clang::getOpenMPDirectiveName(OpenMPDirectiveKind Kind) {
  assert(Kind < NUM_OPENMP_DIRECTIVES);
  switch (Kind) {
  case OMPD_unknown:
    return ("unknown");
#define OPENMP_DIRECTIVE(Name) \
  case OMPD_##Name : return #Name;
#include "clang/Basic/OpenMPKinds.def"
  default:
    break;
  }
  llvm_unreachable("Invalid OpenMP directive kind");
}

//===--- OpenMPKinds.cpp - Token Kinds Support ----------------------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
/// \file
/// \brief This file implements the OpenMP enum and support functions.
///
//===----------------------------------------------------------------------===//

#include "clang/Basic/OpenMPKinds.h"
#include "clang/Basic/IdentifierTable.h"
#include "llvm/ADT/StringRef.h"
#include "llvm/ADT/StringSwitch.h"
#include "llvm/Support/ErrorHandling.h"
#include <cassert>

using namespace clang;

OpenMPDirectiveKind clang::getOpenMPDirectiveKind(StringRef Str) {
  return llvm::StringSwitch<OpenMPDirectiveKind>(Str)
#define OPENMP_DIRECTIVE(Name) \
           .Case(#Name, OMPD_##Name)
#include "clang/Basic/OpenMPKinds.def"
           .Default(OMPD_unknown);
}

const char *clang::getOpenMPDirectiveName(OpenMPDirectiveKind Kind) {
  assert(Kind < NUM_OPENMP_DIRECTIVES);
  switch (Kind) {
  case OMPD_unknown:
    return ("unknown");
#define OPENMP_DIRECTIVE(Name) \
  case OMPD_##Name : return #Name;
#include "clang/Basic/OpenMPKinds.def"
  default:
    break;
  }
  llvm_unreachable("Invalid OpenMP directive kind");
}

Fix a layering violation introduced in r177705.

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


// vim:sw=2:ai

/*
 * Copyright (C) 2010 DeNA Co.,Ltd.. All rights reserved.
 * See COPYRIGHT.txt for details.
 */

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

#include "fatal.hpp"

namespace dena {

const int opt_syslog = LOG_ERR | LOG_PID | LOG_CONS;

void
fatal_exit(const std::string& message)
{
  fprintf(stderr, "FATAL_EXIT: %s\n", message.c_str());
  syslog(opt_syslog, "FATAL_EXIT: %s", message.c_str());
  _exit(1);
}

void
fatal_abort(const std::string& message)
{
  fprintf(stderr, "FATAL_COREDUMP: %s\n", message.c_str());
  syslog(opt_syslog, "FATAL_COREDUMP: %s", message.c_str());
  abort();
}

};

// vim:sw=2:ai

/*
 * Copyright (C) 2010 DeNA Co.,Ltd.. All rights reserved.
 * See COPYRIGHT.txt for details.
 */

#include <stdlib.h>
#include <stdio.h>
#include <syslog.h>
#include <unistd.h>

#include "fatal.hpp"

namespace dena {

const int opt_syslog = LOG_ERR | LOG_PID | LOG_CONS;

void
fatal_exit(const std::string& message)
{
  fprintf(stderr, "FATAL_EXIT: %s\n", message.c_str());
  syslog(opt_syslog, "FATAL_EXIT: %s", message.c_str());
  _exit(1);
}

void
fatal_abort(const std::string& message)
{
  fprintf(stderr, "FATAL_COREDUMP: %s\n", message.c_str());
  syslog(opt_syslog, "FATAL_COREDUMP: %s", message.c_str());
  abort();
}

};

Add missing include (fixes compile failure with gcc 4.7).


/*
 * Podrios.cpp
 *
 *  Created on: 2014年10月23日
 *      Author: nemo
 */

#include "GameTable/GamblingTable.h"
#include <iostream>

using namespace std;

int main()
{
	cout << "Start Podrios." << endl;

	GamblingTable *gamblingTable_Ptr = new GamblingTable();

	return 0;
}

/*
 * Podrios.cpp
 *
 *  Created on: 2014年10月23日
 *      Author: nemo
 */

#include "GameTable/GamblingTable.h"
#include <iostream>

using namespace std;

int main()
{
	cout << "Start Podrios." << endl;

	GamblingTable gamblingTable;

	return 0;
}

Modify the way of GambilingTable construct.


// Copyright (c) 2011, Christian Rorvik
// Distributed under the Simplified BSD License (See accompanying file LICENSE.txt)

#include "crunch/concurrency/yield.hpp"

#include <windows.h>

namespace Crunch { namespace Concurrency {

void ThreadYield()
{
    SwitchToThread();
}

void ThreadSleep(Duration duration)
{
    Sleep(static_cast<DWORD>(duration.GetTotalMilliseconds()));
}

}}

// Copyright (c) 2011, Christian Rorvik
// Distributed under the Simplified BSD License (See accompanying file LICENSE.txt)

#include "crunch/concurrency/yield.hpp"

#include <windows.h>

namespace Crunch { namespace Concurrency {

void ThreadYield()
{
    ::SwitchToThread();
}

void ThreadSleep(Duration duration)
{
    if (duration.IsNegative())
        return;

    ::Sleep(static_cast<DWORD>(duration.GetTotalMilliseconds()));
}

}}

Check for negative duration in ThreadSleep on Windows


//===-- SystemInitializerLLGS.cpp -------------------------------*- C++ -*-===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//

#include "SystemInitializerLLGS.h"

#if defined(__APPLE__)
#include "Plugins/ObjectFile/Mach-O/ObjectFileMachO.h"
using HostObjectFile = lldb_private::ObjectFileMachO;
#elif defined(_WIN32)
#include "Plugins/ObjectFile/PECOFF/ObjectFilePECOFF.h"
using HostObjectFile = lldb_private::ObjectFilePECOFF;
#else
#include "Plugins/ObjectFile/ELF/ObjectFileELF.h"
using HostObjectFile = ObjectFileELF;
#endif

using namespace lldb_private;

void SystemInitializerLLGS::Initialize() {
  SystemInitializerCommon::Initialize();
  HostObjectFile::Initialize();
}

void SystemInitializerLLGS::Terminate() {
  HostObjectFile::Terminate();
  SystemInitializerCommon::Terminate();
}

//===-- SystemInitializerLLGS.cpp -------------------------------*- C++ -*-===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//

#include "SystemInitializerLLGS.h"

#if defined(__APPLE__)
#include "Plugins/ObjectFile/Mach-O/ObjectFileMachO.h"
using HostObjectFile = ObjectFileMachO;
#elif defined(_WIN32)
#include "Plugins/ObjectFile/PECOFF/ObjectFilePECOFF.h"
using HostObjectFile = ObjectFilePECOFF;
#else
#include "Plugins/ObjectFile/ELF/ObjectFileELF.h"
using HostObjectFile = ObjectFileELF;
#endif

using namespace lldb_private;

void SystemInitializerLLGS::Initialize() {
  SystemInitializerCommon::Initialize();
  HostObjectFile::Initialize();
}

void SystemInitializerLLGS::Terminate() {
  HostObjectFile::Terminate();
  SystemInitializerCommon::Terminate();
}

Fix windows/mac builds broken by r333182.

I should've known that something was wrong when only one of my plugins
was prefixed by the lldb_private namespace.

git-svn-id: 4c4cc70b1ef44ba2b7963015e681894188cea27e@333183 91177308-0d34-0410-b5e6-96231b3b80d8


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

#include "sky/engine/tonic/dart_invoke.h"

#include "base/logging.h"
#include "base/trace_event/trace_event.h"
#include "sky/engine/tonic/dart_error.h"

namespace blink {

bool DartInvokeAppField(Dart_Handle target, Dart_Handle name,
                               int number_of_arguments,
                               Dart_Handle* arguments) {
  TRACE_EVENT0("sky", "DartInvoke::DartInvokeAppField");
  return LogIfError(Dart_Invoke(target, name, number_of_arguments, arguments));
}

bool DartInvokeAppClosure(Dart_Handle closure,
                          int number_of_arguments,
                          Dart_Handle* arguments) {
  TRACE_EVENT0("sky", "DartInvoke::DartInvokeAppClosure");
  return LogIfError(
      Dart_InvokeClosure(closure, number_of_arguments, arguments));
}

}  // namespace blink

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

#include "sky/engine/tonic/dart_invoke.h"

#include "base/logging.h"
#include "base/trace_event/trace_event.h"
#include "sky/engine/tonic/dart_error.h"

namespace blink {

bool DartInvokeAppField(Dart_Handle target, Dart_Handle name,
                               int number_of_arguments,
                               Dart_Handle* arguments) {
  TRACE_EVENT0("sky", "DartInvoke::DartInvokeAppField");
  return LogIfError(Dart_Invoke(target, name, number_of_arguments, arguments));
}

bool DartInvokeAppClosure(Dart_Handle closure,
                          int number_of_arguments,
                          Dart_Handle* arguments) {
  TRACE_EVENT0("sky", "DartInvoke::DartInvokeAppClosure");
  Dart_Handle handle = Dart_InvokeClosure(closure, number_of_arguments, arguments);
  bool result = LogIfError(handle);
  CHECK(!Dart_IsCompilationError(handle));
  return result;
}

}  // namespace blink

Check if invocation of a closure failed due to a compilation error

This is a fix for bug #1325.  The test framework is running the test code
as a microtask using DartInvokeAppClosure.  If the test causes a compilation
error, the test framework Dart code can not catch it.  The invocation in
sky_shell will return a compilation error handle.  The sky_shell process
will not shut down, and the test framework will hang.

This change will cause sky_shell to shut down on a compilation error in
the test microtask.


// RUN: %clang_cc1 -debug-info-kind=limited -triple %itanium_abi_triple \
// RUN:   -fdebug-prefix-map=%S=/SOURCE_ROOT %s -emit-llvm -o - | FileCheck %s

template <typename T> void b(T) {}
void c() {
  // CHECK: !DISubprogram(name: "b<(lambda at
  // CHECK-SAME:          SOURCE_ROOT
  // CHECK-SAME:          [[@LINE+1]]:{{[0-9]+}})>"
  b([]{});
}

// RUN: %clang_cc1 -std=c++14 -debug-info-kind=limited \
// RUN:   -triple %itanium_abi_triple \
// RUN:   -fdebug-prefix-map=%S=/SOURCE_ROOT %s -emit-llvm -o - | FileCheck %s

template <typename T> void b(T) {}
void c() {
  // CHECK: !DISubprogram(name: "b<(lambda at
  // CHECK-SAME:          SOURCE_ROOT
  // CHECK-SAME:          [[@LINE+1]]:{{[0-9]+}})>"
  b([]{});
}

Add an explicit -std=c++14 to this test.


// RUN: rm -rf %t
// RUN: %clang_cc1 -fmodules -fno-implicit-modules -emit-module -fmodule-name=a %S/Inputs/explicit-build-prefer-self/map -o a.pcm
// RUN: %clang_cc1 -fmodules -fno-implicit-modules -emit-module -fmodule-name=b %S/Inputs/explicit-build-prefer-self/map -o b.pcm

// RUN: rm -rf %t
// RUN: %clang_cc1 -fmodules -fno-implicit-modules -emit-module -fmodule-name=a %S/Inputs/explicit-build-prefer-self/map -o %t/a.pcm
// RUN: %clang_cc1 -fmodules -fno-implicit-modules -emit-module -fmodule-name=b %S/Inputs/explicit-build-prefer-self/map -o %t/b.pcm

Write output file to temp directory. The tests shouldn't assume that
they can write to the current working directory.

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


#include "AnimationProgram.h"

#include "esp_log.h"

static const char* TAG = "PROGRAM";

AnimationProgram::AnimationProgram(Timer &animator) : programs(), animator(animator) {

}

void AnimationProgram::putAnimation(uint8_t index, Animation *animation) {
    programs[index] = animation;
}

void AnimationProgram::drawFrame() {
    // fixme check index
    programs[index]->drawFrame();
}

void AnimationProgram::setProgram(uint8_t index) {
    ESP_LOGI(TAG, "set program %d", index);
    this->index = index;
    animator.setIntervalSecs(index == 4 || index == 5 ? .3 : .03);
}

#include "AnimationProgram.h"

#include "esp_log.h"

static const char* TAG = "AnimationProgram";

AnimationProgram::AnimationProgram(Timer &animator) : programs(), animator(animator) {

}

void AnimationProgram::putAnimation(uint8_t index, Animation *animation) {
    programs[index] = animation;
}

void AnimationProgram::drawFrame() {
    // fixme check index
    programs[index]->drawFrame();
}

void AnimationProgram::setProgram(uint8_t index) {
    ESP_LOGI(TAG, "set program %d", index);
    if (index < programs.size()) {
        this->index = index;
        animator.setIntervalSecs(index == 4 || index == 5 ? .3 : .03);
    } else {
        ESP_LOGW(TAG, "set program ignored: out of range: 0-%d", programs.size() - 1);
    }
}

Add range check for set program

Add range check for set program


#include "catch.hpp"

#include <lua.hpp>
#include <luwra.hpp>

int test_function_1(int a, int b) {
	return a - b;
}

int test_function_2(int a, int b, int c) {
	return a + b * c;
}

void test_function_3(int) {

}

TEST_CASE("stack_interaction") {
	lua_State* state = luaL_newstate();

	luwra::push(state, 1);
	luwra::push(state, 2);
	luwra::push(state, 4);

	// Redundant function
	luwra::apply(state, test_function_3);

	// Absolute index
	REQUIRE(luwra::apply(state, test_function_1) == -1);
	REQUIRE(luwra::apply(state, 1, test_function_1) == -1);
	REQUIRE(luwra::apply(state, test_function_2) == 9);
	REQUIRE(luwra::apply(state, 1, test_function_2) == 9);

	// Relative index
	REQUIRE(luwra::apply(state, -2, test_function_1) == -2);
	REQUIRE(luwra::apply(state, -3, test_function_1) == -1);
	REQUIRE(luwra::apply(state, -3, test_function_2) == 9);

	lua_close(state);
}

#include "catch.hpp"

#include <lua.hpp>
#include <luwra.hpp>

static
int test_function_1(int a, int b) {
	return a - b;
}

static
int test_function_2(int a, int b, int c) {
	return a + b * c;
}

static
void test_function_3(int) {

}

TEST_CASE("stack_interaction") {
	lua_State* state = luaL_newstate();

	luwra::push(state, 1);
	luwra::push(state, 2);
	luwra::push(state, 4);

	// Redundant function
	luwra::apply(state, test_function_3);

	// Absolute index
	REQUIRE(luwra::apply(state, test_function_1) == -1);
	REQUIRE(luwra::apply(state, 1, test_function_1) == -1);
	REQUIRE(luwra::apply(state, test_function_2) == 9);
	REQUIRE(luwra::apply(state, 1, test_function_2) == 9);

	// Relative index
	REQUIRE(luwra::apply(state, -2, test_function_1) == -2);
	REQUIRE(luwra::apply(state, -3, test_function_1) == -1);
	REQUIRE(luwra::apply(state, -3, test_function_2) == 9);

	lua_close(state);
}

Make functions used in tests static

tests: Make functions used in tests static


#include "utils/distance.hpp"

// Returns the minimum distance (straight line) between two points
double distance(cv::Point one, cv::Point two)
{
    return std::sqrt(std::pow(one.x - two.x, 2) + std::pow(one.y - two.y, 2));
}

// Returns the two dimensional distance between the components of two points
double distance2D(double comp1, double comp2)
{
    return std::abs(comp2 - comp1);
}

double getShortestDistance (cv::Point2f rectPoints[4], double focalLen, int dist, int height)
{
	// 20 inches real width
	int realWidth = 20;
	int pixelWidth = 0;
	double theta = 0;
	double d = 0;

	int length = static_cast<int>(distance (rectPoints[0], rectPoints[3]));
	int width = static_cast<int>(distance (rectPoints[0], rectPoints[1]));
	if (length > width)
    {
		pixelWidth = length;
    }
	else
	{
		pixelWidth = width;
    }
	d = (realWidth * focalLen) / pixelWidth;
	theta = std::asin(static_cast<double>(height) / dist) * 180 / PI;
	return d;
}

#include "utils/distance.hpp"

// Returns the minimum distance (straight line) between two points
double distance(cv::Point one, cv::Point two)
{
    return std::sqrt(std::pow(one.x - two.x, 2) + std::pow(one.y - two.y, 2));
}

double getShortestDistance (cv::Point2f rectPoints[4], double focalLen, int dist, int height)
{
	// The target's base is 20 inches wide in real life
	int realWidth = 20;
	int pixelWidth = 0;
	double theta = 0;
	double d = 0;

	int length = static_cast<int>(distance (rectPoints[0], rectPoints[3]));
	int width = static_cast<int>(distance (rectPoints[0], rectPoints[1]));

	if (length > width)
		pixelWidth = length;
	else
		pixelWidth = width;

	d = (realWidth * focalLen) / pixelWidth;
	return d;
}

Remove redundant brackets and lines of code

Former-commit-id: 43b8b2723d2b93f3bd13198701f8e113828c2968


//
// Created by Adam Getchell on 2017-12-02.
//
#define CATCH_CONFIG_RUNNER
#include <catch2/catch.hpp>

int main( int argc, char* argv[] )
{
    Catch::Session session; // There must be exactly one instance

    // writing to session.configData() here sets defaults
    // this is the preferred way to set them

    int returnCode = session.applyCommandLine( argc, argv );
    if( returnCode != 0 ) // Indicates a command line error
        return returnCode;

    // writing to session.configData() or session.Config() here
    // overrides command line args
    // only do this if you know you need to

    int numFailed = session.run();

    // numFailed is clamped to 255 as some unices only use the lower 8 bits.
    // This clamping has already been applied, so just return it here
    // You can also do any post run clean-up here
    return numFailed;
}

//
// Created by Adam Getchell on 2017-12-02.
//
#define CATCH_CONFIG_RUNNER
#include "catch.hpp"

int main( int argc, char* argv[] )
{
    Catch::Session session; // There must be exactly one instance

    // writing to session.configData() here sets defaults
    // this is the preferred way to set them

    int returnCode = session.applyCommandLine( argc, argv );
    if( returnCode != 0 ) // Indicates a command line error
        return returnCode;

    // writing to session.configData() or session.Config() here
    // overrides command line args
    // only do this if you know you need to

    int numFailed = session.run();

    // numFailed is clamped to 255 as some unices only use the lower 8 bits.
    // This clamping has already been applied, so just return it here
    // You can also do any post run clean-up here
    return numFailed;
}

Revert back to older Catch2

Revert back to older Catch2


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

#include "base/logging.h"
#include "views/view.h"

namespace ui_controls {

bool SendKeyPress(gfx::NativeWindow window,
                  ui::KeyboardCode key,
                  bool control,
                  bool shift,
                  bool alt,
                  bool command) {
  NOTIMPLEMENTED();
  return true;
}

bool SendKeyPressNotifyWhenDone(gfx::NativeWindow window,
                                ui::KeyboardCode key,
                                bool control,
                                bool shift,
                                bool alt,
                                bool command,
                                Task* task) {
  NOTIMPLEMENTED();
  return true;
}

bool SendMouseMove(long x, long y) {
  NOTIMPLEMENTED();
  return true;
}

bool SendMouseMoveNotifyWhenDone(long x, long y, Task* task) {
  NOTIMPLEMENTED();
  return true;
}

bool SendMouseEvents(MouseButton type, int state) {
  NOTIMPLEMENTED();
  return true;
}

bool SendMouseEventsNotifyWhenDone(MouseButton type, int state, Task* task) {
  NOTIMPLEMENTED();
  return true;
}

bool SendMouseClick(MouseButton type) {
  return SendMouseEvents(type, UP | DOWN);
}

void MoveMouseToCenterAndPress(views::View* view, MouseButton button,
                               int state, Task* task) {
  NOTIMPLEMENTED();
}

}  // namespace ui_controls

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

#include "base/logging.h"
#include "views/view.h"

namespace ui_controls {

bool SendKeyPress(gfx::NativeWindow window,
                  ui::KeyboardCode key,
                  bool control,
                  bool shift,
                  bool alt,
                  bool command) {
  NOTIMPLEMENTED();
  return true;
}

bool SendKeyPressNotifyWhenDone(gfx::NativeWindow window,
                                ui::KeyboardCode key,
                                bool control,
                                bool shift,
                                bool alt,
                                bool command,
                                const base::Closure& task) {
  NOTIMPLEMENTED();
  return true;
}

bool SendMouseMove(long x, long y) {
  NOTIMPLEMENTED();
  return true;
}

bool SendMouseMoveNotifyWhenDone(long x, long y, const base::Closure& task) {
  NOTIMPLEMENTED();
  return true;
}

bool SendMouseEvents(MouseButton type, int state) {
  NOTIMPLEMENTED();
  return true;
}

bool SendMouseEventsNotifyWhenDone(MouseButton type, int state,
    const base::Closure& task) {
  NOTIMPLEMENTED();
  return true;
}

bool SendMouseClick(MouseButton type) {
  return SendMouseEvents(type, UP | DOWN);
}

void MoveMouseToCenterAndPress(views::View* view, MouseButton button,
                               int state, const base::Closure& task) {
  NOTIMPLEMENTED();
}

}  // namespace ui_controls

aura: Fix chrome compile after the switch from Task to base::Bind.

TBR=jhawkins@chromium.org
BUG=none
TEST=none

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

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


#include "Game.hpp"

namespace arduino_pong
{

void Game::run()
{
    while(true)
    {
        gameField_.update();
        gameField_.render();
    }
}

}  // namespace arduino_pong

#include "Game.hpp"

#include <Arduino.h>

namespace
{

constexpr uint32_t MsPerUpdate = 16;

}  // namespace

namespace arduino_pong
{

void Game::run()
{

    uint32_t previous = millis();
    uint32_t lag = 0;

    while(true)
    {
        uint32_t current = millis();
        uint32_t elapsed = current - previous;
        previous = current;
        lag += elapsed;

        while(lag >= MsPerUpdate)
        {
            gameField_.update();
			lag -= MsPerUpdate;
        }

        gameField_.render();
    }
}

}  // namespace arduino_pong

Add implementation of a basic game loop.

Derived from http://gameprogrammingpatterns.com/game-loop.html


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

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

#include "base/utf_string_conversions.h"

namespace history {

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

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

  PublishDataToIndexers(page_data);
}

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

  PublishDataToIndexers(page_data);
}

}  // namespace history

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

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

#include "base/utf_string_conversions.h"

namespace history {

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

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

  PublishDataToIndexers(page_data);
}

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

  PublishDataToIndexers(page_data);
}

}  // namespace history

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

BUG=46835

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

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


#include "client.h"
#include "tests/test.h"

#include <QGuiApplication>
#include <QQuickView>
#include <QQmlContext>
#include <QtQml>
#include <QUrl>

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

    qmlRegisterUncreatableType<AbstractTest>("mplane", 1, 0, "AbstractTest", "abstract class");
    qmlRegisterUncreatableType<Client>("mplane", 1, 0, "Client", "This is a singleton");
    qmlRegisterUncreatableType<TestScheduler>("mplane", 1, 0, "TestScheduler", "uncreatable type");

    QQuickView view;

    QQmlContext* rootContext = view.rootContext();
    rootContext->setContextProperty("client", Client::instance());

    view.setResizeMode(QQuickView::SizeRootObjectToView);
    view.setSource( QUrl("qrc:/qml/main.qml") );
    view.show();

    return app.exec();
}

#include "client.h"
#include "tests/test.h"

#include <QGuiApplication>
#include <QQuickView>
#include <QQmlContext>
#include <QQmlEngine>
#include <QtQml>
#include <QUrl>

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

    qmlRegisterUncreatableType<AbstractTest>("mplane", 1, 0, "AbstractTest", "abstract class");
    qmlRegisterUncreatableType<Client>("mplane", 1, 0, "Client", "This is a singleton");
    qmlRegisterUncreatableType<TestScheduler>("mplane", 1, 0, "TestScheduler", "uncreatable type");

    QQuickView view;

    QQmlEngine* engine = view.engine();
    QObject::connect(engine, SIGNAL(quit()), &app, SLOT(quit()));

    QQmlContext* rootContext = view.rootContext();
    rootContext->setContextProperty("client", Client::instance());

    view.setResizeMode(QQuickView::SizeRootObjectToView);
    view.setSource( QUrl("qrc:/qml/main.qml") );
    view.show();

    return app.exec();
}

Quit the application when qml engine wants to.


//=======================================================================
// Copyright Baptiste Wicht 2011-2012.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
//  http://www.boost.org/LICENSE_1_0.txt)
//=======================================================================

#include <iostream>

#include "timing.hpp"

using namespace eddic;

timing_timer::timing_timer(timing_system& system, const std::string& name) : system(system), name(name) {
    //Nothing
}

timing_timer::~timing_timer(){
    system.register_timing(name, timer.elapsed());
}

timing_system::timing_system(std::shared_ptr<Configuration> configuration) : configuration(configuration) {
    //Nothing
}

timing_system::~timing_system(){
    if(configuration->option_defined("timing")){
        for(auto& timing : timings){
            std::cout << timing.first << ":" << timing.second << "ms" << std::endl;
        }
    }
}

void timing_system::register_timing(std::string name, double time){
    timings[name] += time;
}

//=======================================================================
// Copyright Baptiste Wicht 2011-2012.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
//  http://www.boost.org/LICENSE_1_0.txt)
//=======================================================================

#include <iostream>

#include "timing.hpp"

using namespace eddic;

timing_timer::timing_timer(timing_system& system, const std::string& name) : system(system), name(name) {
    //Nothing
}

timing_timer::~timing_timer(){
    system.register_timing(name, timer.elapsed());
}

timing_system::timing_system(std::shared_ptr<Configuration> configuration) : configuration(configuration) {
    //Nothing
}

timing_system::~timing_system(){
    if(configuration->option_defined("time")){
        for(auto& timing : timings){
            std::cout << timing.first << ":" << timing.second << "ms" << std::endl;
        }
    }
}

void timing_system::register_timing(std::string name, double time){
    timings[name] += time;
}

Fix the name of the option

Fix the name of the option


// Copyright 2014 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/child/file_info_util.h"

#include "base/logging.h"
#include "third_party/WebKit/public/platform/WebFileInfo.h"

namespace content {

void FileInfoToWebFileInfo(const base::File::Info& file_info,
                           blink::WebFileInfo* web_file_info) {
  DCHECK(web_file_info);
  // WebKit now expects NaN as uninitialized/null Date.
  if (file_info.last_modified.is_null()) {
    web_file_info->modificationTime = std::numeric_limits<double>::quiet_NaN();
    web_file_info->modificationTimeMS =
        std::numeric_limits<double>::quiet_NaN();
  } else {
    web_file_info->modificationTime = file_info.last_modified.ToDoubleT();
    web_file_info->modificationTimeMS = file_info.last_modified.ToJsTime();
  }
  web_file_info->length = file_info.size;
  if (file_info.is_directory)
    web_file_info->type = blink::WebFileInfo::TypeDirectory;
  else
    web_file_info->type = blink::WebFileInfo::TypeFile;
}

static_assert(std::numeric_limits<double>::has_quiet_NaN,
              "should have quiet NaN");

}  // namespace content

// Copyright 2014 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/child/file_info_util.h"

#include "base/logging.h"
#include "third_party/WebKit/public/platform/WebFileInfo.h"

namespace content {

void FileInfoToWebFileInfo(const base::File::Info& file_info,
                           blink::WebFileInfo* web_file_info) {
  DCHECK(web_file_info);
  // Blink now expects NaN as uninitialized/null Date.
  if (file_info.last_modified.is_null()) {
    web_file_info->modificationTime = std::numeric_limits<double>::quiet_NaN();
    web_file_info->modificationTimeMS =
        std::numeric_limits<double>::quiet_NaN();
  } else {
    web_file_info->modificationTime = file_info.last_modified.ToJsTime();
    web_file_info->modificationTimeMS = file_info.last_modified.ToJsTime();
  }
  web_file_info->length = file_info.size;
  if (file_info.is_directory)
    web_file_info->type = blink::WebFileInfo::TypeDirectory;
  else
    web_file_info->type = blink::WebFileInfo::TypeFile;
}

static_assert(std::numeric_limits<double>::has_quiet_NaN,
              "should have quiet NaN");

}  // namespace content

Upgrade Blink to milliseconds-based last modified filetimes, part 4.

Have content::FileInfoToWebFileInfo() set the temporarily Blink-unused
field WebFileInfo::modificationTime to something milliseconds-based

Once landed, this is to allow Blink to switch to no longer using
WebFileInfo::modificationTimeMS, but modificationTime only (again.)

This is the fourth patch in the following series,

1: [blink] add WebFileInfo::modificationTimeMS [ https://codereview.chromium.org/873723004/ ]
2: [chromium] fill in modificationTimeMS [ https://codereview.chromium.org/884413002/ ]
3: [blink] make use of modificationTimeMS [ https://codereview.chromium.org/884393002/ ]
4: [chromium] *this one* [ https://codereview.chromium.org/862203003/ ]
5: [blink] switch to using modificationTime instead of *MS [ https://codereview.chromium.org/882343002/ ]
6: [chromium] stop setting modificationTimeMS [ https://codereview.chromium.org/890523002/ ]
7: [blink] remove modificationTimeMS [ https://codereview.chromium.org/869613005/ ]

R=jochen
BUG=451747

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

Cr-Commit-Position: 972c6d2dc6dd5efdad1377c0d224e03eb8f276f7@{#315322}


// Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2019 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#include <util/validation.h>

#include <consensus/validation.h>
#include <tinyformat.h>

/** Convert ValidationState to a human-readable message for logging */
std::string FormatStateMessage(const ValidationState &state)
{
    return strprintf("%s%s",
        state.GetRejectReason(),
        state.GetDebugMessage().empty() ? "" : ", "+state.GetDebugMessage());
}

const std::string strMessageMagic = "Peercoin Signed Message:\n";

// Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2019 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#include <util/validation.h>

#include <consensus/validation.h>
#include <tinyformat.h>

/** Convert ValidationState to a human-readable message for logging */
std::string FormatStateMessage(const ValidationState &state)
{
    if (state.IsValid()) {
        return "Valid";
    }

    return strprintf("%s%s",
        state.GetRejectReason(),
        state.GetDebugMessage().empty() ? "" : ", "+state.GetDebugMessage());
}

const std::string strMessageMagic = "Peercoin Signed Message:\n";

Format CValidationState properly in all cases

FormatStateMessage does not properly handle the case where
CValidationState::IsValid() returns true. Use "Valid" for the state in
this case.


#include <glbinding/GetProcAddress.h>
#include <cassert>

#ifdef WIN32
    #include <string>
    #include <windows.h>
#elif __APPLE__
    #include <string>
    #include <dlfcn.h>
#else
    #include <GL/glx.h>
#endif

namespace gl {

ProcAddress GetProcAddress(const char * name)
{
#ifdef WIN32

    typedef void (__stdcall * PROCADDRESS)();
    PROCADDRESS procAddress = reinterpret_cast<PROCADDRESS>(wglGetProcAddress(name));

    if (procAddress == nullptr)
    {
        static HMODULE module = LoadLibrary(L"OPENGL32.DLL");
        procAddress = reinterpret_cast<PROCADDRESS>(::GetProcAddress(module, name));
    }

#elif __APPLE__

    typedef void * PROCADDRESS;

    void * library = dlopen("/System/Library/Frameworks/OpenGL.framework/Versions/Current/OpenGL", RTLD_LAZY);
    assert(library != nullptr);

    void * symbol = dlsym(library, name);

    PROCADDRESS procAddress = reinterpret_cast<PROCADDRESS>(symbol);

#else

    typedef void (* PROCADDRESS)();
    PROCADDRESS procAddress = reinterpret_cast<PROCADDRESS>(glXGetProcAddress(reinterpret_cast<const unsigned char*>(name)));

#endif

    return reinterpret_cast<ProcAddress>(procAddress);
}

} // namespace gl

#include <glbinding/GetProcAddress.h>

#ifdef WIN32
    #include <string>
    #include <windows.h>
#elif __APPLE__
    #include <cassert>
    #include <string>
    #include <dlfcn.h>
#else
    #include <GL/glx.h>
#endif

namespace gl {

ProcAddress GetProcAddress(const char * name)
{
#ifdef WIN32

    typedef void (__stdcall * PROCADDRESS)();
    PROCADDRESS procAddress = reinterpret_cast<PROCADDRESS>(wglGetProcAddress(name));

    if (procAddress == nullptr)
    {
        static HMODULE module = LoadLibrary(L"OPENGL32.DLL");
        procAddress = reinterpret_cast<PROCADDRESS>(::GetProcAddress(module, name));
    }

#elif __APPLE__

    typedef void * PROCADDRESS;

    void * library = dlopen("/System/Library/Frameworks/OpenGL.framework/Versions/Current/OpenGL", RTLD_LAZY);
    assert(library != nullptr);

    void * symbol = dlsym(library, name);

    PROCADDRESS procAddress = reinterpret_cast<PROCADDRESS>(symbol);

#else

    typedef void (* PROCADDRESS)();
    PROCADDRESS procAddress = reinterpret_cast<PROCADDRESS>(glXGetProcAddress(reinterpret_cast<const unsigned char*>(name)));

#endif

    return reinterpret_cast<ProcAddress>(procAddress);
}

} // namespace gl

Move cassert include to OS X specific code


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

ics::ICS3* driver {nullptr};

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

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

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

ics::ICS3* driver {nullptr};

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

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

Update subscribe topic for add pub topic

今後のpublish topicのためにトピック名をわかりやすいものに変更


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

std::string path;

void move(const servo_msgs::IdBased::ConstPtr& msg) {
  static ics::ICS3 ics {path.c_str(), ics::Baudrate::RATE115200()};
  auto degree = ics::Angle::newDegree(msg->angle);
  auto nowpos = ics.move(msg->id, degree);
  // TODO: publish now pos
}

int main(int argc, char** argv) {
  ros::init(argc, argv, "servo_krs_node");
  ros::NodeHandle n;
  ros::NodeHandle pn {"~"};
  pn.param<std::string>("path", path, "ttyUSB0");
  ros::Subscriber sub = n.subscribe("krs", 100, move);
  ros::spin();
  return 0;
}

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

ics::ICS3* driver;

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

int main(int argc, char** argv) {
  ros::init(argc, argv, "servo_krs_node");
  ros::NodeHandle n {};
  ros::NodeHandle pn {"~"};
  std::string path {"ttyUSB0"};
  pn.param<std::string>("path", path, path);
  ics::ICS3 ics {path.c_str()};
  driver = &ics;
  ros::Subscriber sub = n.subscribe("krs", 100, move);
  ros::spin();
  return 0;
}

Update timing of make ics instance

Update timing of make ics instance


#include <google/protobuf/compiler/command_line_interface.h>
#include <google/protobuf/compiler/cpp/cpp_generator.h>
#include <google/protobuf/compiler/perlxs/perlxs_generator.h>

#include <iostream>
#include <string>

using namespace std;

int main(int argc, char* argv[]) {
  google::protobuf::compiler::CommandLineInterface cli;

  // Proto2 C++ (for convenience, so the user doesn't need to call
  // protoc separately)

  google::protobuf::compiler::cpp::CppGenerator cpp_generator;
  cli.RegisterGenerator("--cpp_out", &cpp_generator,
                        "Generate C++ header and source.");

  // Proto2 Perl/XS
  google::protobuf::compiler::perlxs::PerlXSGenerator perlxs_generator;
  cli.RegisterGenerator("--out", &perlxs_generator,
                        "Generate Perl/XS source files.");

  cli.SetVersionInfo(perlxs_generator.GetVersionInfo());

  // process Perl/XS command line options first, and filter them out
  // of the argument list.  we really need to be able to register
  // options with the CLI instead of doing this stupid hack here.

  int j = 1;
  for (int i = 1; i < argc; i++) {
    if (perlxs_generator.ProcessOption(argv[i]) == false) {
      argv[j++] = argv[i];
    }
  }

  return cli.Run(j, argv);
}

#include <google/protobuf/compiler/command_line_interface.h>
#include <google/protobuf/compiler/cpp/cpp_generator.h>
#include <google/protobuf/compiler/perlxs/perlxs_generator.h>

#include <iostream>
#include <string>

int main(int argc, char* argv[]) {
  google::protobuf::compiler::CommandLineInterface cli;

  // Proto2 C++ (for convenience, so the user doesn't need to call
  // protoc separately)

  google::protobuf::compiler::cpp::CppGenerator cpp_generator;
  cli.RegisterGenerator("--cpp_out", &cpp_generator,
                        "Generate C++ header and source.");

  // Proto2 Perl/XS
  google::protobuf::compiler::perlxs::PerlXSGenerator perlxs_generator;
  cli.RegisterGenerator("--out", &perlxs_generator,
                        "Generate Perl/XS source files.");

  cli.SetVersionInfo(perlxs_generator.GetVersionInfo());

  // process Perl/XS command line options first, and filter them out
  // of the argument list.  we really need to be able to register
  // options with the CLI instead of doing this stupid hack here.

  int j = 1;
  for (int i = 1; i < argc; i++) {
    if (perlxs_generator.ProcessOption(argv[i]) == false) {
      argv[j++] = argv[i];
    }
  }

  return cli.Run(j, argv);
}

Remove unused `using namespace std`

Remove unused `using namespace std`


#ifndef MAIN_CPP
#define MAIN_CPP

#include <iostream>
#include <bitset>
#include <string>
#include <fstream>

int main() {

  std::ifstream myfile;
  std::string message,value,translate;
  enum States{W,Z,O,I};
  States state = W;

  myfile.open("input1.txt");

  while(!myfile.eof()) {
    std::getline(myfile,value,' ');
     value = value.substr(2,1);

    switch(state) {
      case W: {
        if(value == "0") {
          state = Z;
          message += value;
        }
        break;
      }
      case Z: {
        if(value == "1") {
          state = O;
          message +=value;
        }
        else {
          state = W;
          message = "";
        }
        break;
      }
      case O: {
        if(value == "1" || value == "0") {
          message += value;
          state = I;
        }
        else {
          state = W;
          value = "";
        }
        break;
      }
      case I: {
        if(!(value == "1" || value == "0")) {
          state = W;
        }

        else {
          message += value;

          if(message.length() == 8) {
            std::bitset<8> bs(message);
            translate += char(bs.to_ulong());
            message = "";

          }
        }
        break;
      }
      }

    }

    std::cout << translate;

};

#endif

#ifndef MAIN_CPP
#define MAIN_CPP

#include <iostream>
#include <bitset>
#include <string>

int main() {

  std::string message,value,translate;
  enum States{W,Z,O,I};
  States state = W;

  while(std::getline(std::cin,value,' ')) {
     value = value.substr(2,1);

    switch(state) {
      case W: {
        if(value == "0") {
          state = Z;
          message += value;
        }
        break;
      }
      case Z: {
        if(value == "1") {
          state = O;
          message +=value;
        }
        else {
          state = W;
          message = "";
        }
        break;
      }
      case O: {
        if(value == "1" || value == "0") {
          message += value;
          state = I;
        }
        else {
          state = W;
          value = "";
        }
        break;
      }
      case I: {
        if(!(value == "1" || value == "0")) {
          state = W;
        }

        else {
          message += value;

          if(message.length() == 8) {
            std::bitset<8> bs(message);
            translate += char(bs.to_ulong());
            message = "";

          }
        }
        break;
      }
      }

    }

    std::cout << translate;

};

#endif

Update c++ steganography solution to use cin


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

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

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

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

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

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

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

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

// Times out. See http://crbug.com/46601.
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, DISABLED_Popup) {
  CommandLine::ForCurrentProcess()->AppendSwitch(
      switches::kEnableExperimentalExtensionApis);

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

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

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

Disable ExtensionApiTest.Popup. It's been timing out for the last 750+ runs.

TBR=michaeln

BUG=46601
TEST=ExtensionApiTest.FLAKY_Popup no longer runs
Review URL: http://codereview.chromium.org/3603003

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


#include "particle.h"

Particle::Particle(const Vector4D &p, const Vector4D &v) :
    position(p),
    velocity(v),
    lifetime(0) {
}

#include "particle.h"

Particle::Particle(const Vector4D &p, const Vector4D &v) :
    position(p),
    velocity(v),
    lifetime(-1) {
}

Set default lifetime to lt 0

Set default lifetime to lt 0


#include "gamelib/core/res/SpriteResource.hpp"
#include "gamelib/core/res/ResourceManager.hpp"
#include "gamelib/utils/json.hpp"

namespace gamelib
{
    void registerSpriteLoader(ResourceManager& resmgr)
    {
        resmgr.registerFileType("spr", spriteLoader);
    }

    BaseResourceHandle spriteLoader(const std::string& fname, ResourceManager* resmgr)
    {
        Json::Value node;
        if (!loadJsonFromFile(fname, node))
            return nullptr;

        if (!node.isMember("texture"))
        {
            LOG_ERROR("No texture specified for sprite: ", fname);
            return nullptr;
        }

        auto sprite = SpriteResource::create();
        sprite->tex = resmgr->get(node["texture"].asString()).as<TextureResource>();

        math::Vec2f tmp;

        if (loadFromJson(node["framepos"], tmp))
            sprite->rect.pos = tmp;

        if (loadFromJson(node["framesize"], tmp))
            sprite->rect.size = tmp;

        if (loadFromJson(node["origin"], tmp))
            sprite->origin = tmp.asPoint();

        sprite->ani.length = node.get("length", 1).asInt();
        sprite->ani.speed = node.get("speed", 0).asFloat();
        sprite->ani.setIndex(node.get("offset", 0).asInt());

        return sprite.as<BaseResource>();
    }
}

#include "gamelib/core/res/SpriteResource.hpp"
#include "gamelib/core/res/ResourceManager.hpp"
#include "gamelib/utils/json.hpp"
#include "gamelib/utils/conversions.hpp"

namespace gamelib
{
    void registerSpriteLoader(ResourceManager& resmgr)
    {
        resmgr.registerFileType("spr", spriteLoader);
    }

    BaseResourceHandle spriteLoader(const std::string& fname, ResourceManager* resmgr)
    {
        Json::Value node;
        if (!loadJsonFromFile(fname, node))
            return nullptr;

        if (!node.isMember("texture"))
        {
            LOG_ERROR("No texture specified for sprite: ", fname);
            return nullptr;
        }

        auto sprite = SpriteResource::create();
        sprite->tex = resmgr->get(node["texture"].asString()).as<TextureResource>();

        math::Vec2f pos, size = convert(sprite->tex->getSize());
        loadFromJson(node["framepos"], pos);
        loadFromJson(node["framesize"], size);

        sprite->rect.pos = pos;
        sprite->rect.size = size;

        loadFromJson(node["origin"], sprite->origin);

        sprite->ani.length = node.get("length", 1).asInt();
        sprite->ani.speed = node.get("speed", 0).asFloat();
        sprite->ani.setIndex(node.get("offset", 0).asInt());

        return sprite.as<BaseResource>();
    }
}

Use texture size as sprite frame size if not given


#include "h264manager.h"

H264Manager::H264Manager()
{
    encodingParameters = "-c:v libx264 -preset ultrafast -f matroska";
}

void H264Manager::start(QProcess &process, QString file)
{
    QString command = "ffmpeg -re -i \"" + file + "\" -c:v libx264 -preset ultrafast -an -f matroska udp://localhost:" + ENCODED_VIDEO_PORT + " -c:v libx264 -preset ultrafast -an -f matroska udp://localhost:"  + VIDEO_PROBE_PORT;
    process.start(command.toUtf8().constData());
}

Remove extra functions from codec classes


#include <ncurses.h>

#include "../../../src/contents.hh"
#include "../../../src/key_aliases.hh"
#include "../../vick-move/src/move.hh"

void enter_insert_mode(contents& contents, boost::optional<int>) {
    char ch;
    while(ch = getch() != _escape) {
        contents.cont[contents.y].insert(contents.x, 1, ch);
        mvf(contents);
    }
}

void enter_replace_insert_mode(contents& contents, boost::optional<int>) {
    char ch;
    while(ch = getch() != _escape) {
        if(contents.x >= contents.cont[contents.y].size()) {
            contents.cont[contents.y].push_back(ch);
        } else {
            contents.cont[contents.y][contents.x] = ch;
        }
    }
}

#include <ncurses.h>

#include "../../../src/contents.hh"
#include "../../../src/key_aliases.hh"
#include "../../vick-move/src/move.hh"

void enter_insert_mode(contents& contents, boost::optional<int>) {
    char ch;
    while((ch = getch()) != _escape) {
        contents.cont[contents.y].insert(contents.x, 1, ch);
        mvf(contents);
    }
}

void enter_replace_insert_mode(contents& contents, boost::optional<int>) {
    char ch;
    while((ch = getch()) != _escape) {
        if(contents.x >= contents.cont[contents.y].size()) {
            contents.cont[contents.y].push_back(ch);
        } else {
            contents.cont[contents.y][contents.x] = ch;
        }
    }
}

Use parens to silence clang warnings

Use parens to silence clang warnings


#include "gtest/gtest.h"
#include "hemi/launch.h"

HEMI_MEM_DEVICE int result;
HEMI_MEM_DEVICE int rGDim;
HEMI_MEM_DEVICE int rBDim;

template <typename... Arguments>
struct k {
	HEMI_DEV_CALLABLE_MEMBER void operator()(Arguments... args) {
		result = sizeof...(args);
		rGDim = 1;//gridDim.x;
		rBDim = 1;//blockDim.x;
	}
};

TEST(PortableLaunchTest, KernelFunction_AutoConfig) {
	k<int> kernel;
	hemi::launch(kernel, 1);
}

#include "gtest/gtest.h"
#include "hemi/launch.h"

HEMI_MEM_DEVICE int result;
HEMI_MEM_DEVICE int rGDim;
HEMI_MEM_DEVICE int rBDim;

template <typename T, typename... Arguments>
HEMI_DEV_CALLABLE
T first(T f, Arguments...) {
	return f;
}

template <typename... Arguments>
struct k {
	HEMI_DEV_CALLABLE_MEMBER void operator()(Arguments... args) {
		result = first(args...); //sizeof...(args);
		rGDim = 1;//gridDim.x;
		rBDim = 1;//blockDim.x;
	}
};

TEST(PortableLaunchTest, KernelFunction_AutoConfig) {
	k<int> kernel;
	hemi::launch(kernel, 1);
}

Work around gcc variadic arguments warning


class Solution {
public:
    // Backtracking
    vector<vector<int>> subsets(vector<int>& nums) {
        vector<vector<int>> res;
        vector<int> sub;
        subsets(nums, sub, res, 0);
        return res;
    }

    void subsets(vector<int>& nums, vector<int>& sub, vector<vector<int>>& subs, int start) {
        subs.push_back(sub);
        for (int i = start; i < nums.size(); i++) {
            sub.push_back(nums[i]);
            subsets(nums, sub, subs, i + 1);
            sub.pop_back();
        }
    }

    // Iterative
    vector<vector<int>> subsets(vector<int>& nums) {
        vector<vector<int>> res;
        vector<int> sub;
        res.push_back(sub);
        for (int i = 0; i < nums.size(); i++) {
            int size = res.size();
            for (int j = 0; j < size; j++) {
                res.push_back(res[j]);
                res.back().push_back(nums[i]);
            }
        }
        return res;
    }
};

class Solution {
public:
    // Backtracking
    vector<vector<int>> subsets(vector<int>& nums) {
        vector<vector<int>> res;
        vector<int> sub;
        subsets(nums, sub, res, 0);
        return res;
    }

    void subsets(vector<int>& nums, vector<int>& sub, vector<vector<int>>& subs, int start) {
        subs.push_back(sub);
        for (int i = start; i < nums.size(); i++) {
            sub.push_back(nums[i]);
            subsets(nums, sub, subs, i + 1);
            sub.pop_back();
        }
    }

    // Iterative
    vector<vector<int>> subsets(vector<int>& nums) {
        vector<vector<int>> res;
        vector<int> sub;
        res.push_back(sub);
        for (int i = 0; i < nums.size(); i++) {
            int size = res.size();
            for (int j = 0; j < size; j++) {
                res.push_back(res[j]);
                res.back().push_back(nums[i]);
            }
        }
        return res;
    }

    // Bit manipulation
    vector<vector<int>> subsets(vector<int>& nums) {
        int n = nums.size();
        int resSize = (int)pow(2, n);
        vector<vector<int>> res(resSize, vector<int>());
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < resSize; j++) {
                if ((j >> i) & 1) {
                    res[j].push_back(nums[i]);
                }
            }
        }
        return res;
    }
};

Add another solution for the problem

Add another solution for the problem


#include "ElevatorSubsystem.h"
#include "../RobotMap.h"

ElevatorSubsystem::ElevatorSubsystem() :
		Subsystem("ElevatorSubsystem"),
		pullMotorRight(PULL_MOTOR_RIGHT),pullMotorLeft(PULL_MOTOR_LEFT),
		underSwitch(UNDER_LIMIT),upSwitch(UP_LIMIT)
{

}

void ElevatorSubsystem::InitDefaultCommand()
{
	// Set the default command for a subsystem here.
	//SetDefaultCommand(new MySpecialCommand());
}

// Put methods for controlling this subsystem
// here. Call these from Commands.
void ElevatorSubsystem::DriveElevator(float pullSpeed){
	pullMotorLeft.Set(pullSpeed);
	pullMotorRight.Set(pullSpeed);
}

#include "ElevatorSubsystem.h"
#include "../RobotMap.h"

ElevatorSubsystem::ElevatorSubsystem() :
		Subsystem("ElevatorSubsystem"),
		pullMotorRight(PULL_MOTOR_RIGHT),pullMotorLeft(PULL_MOTOR_LEFT),
		underSwitch(UNDER_LIMIT),upSwitch(UP_LIMIT)
{

}

void ElevatorSubsystem::InitDefaultCommand()
{
	// Set the default command for a subsystem here.
	//SetDefaultCommand(new MySpecialCommand());
}

// Put methods for controlling this subsystem
// here. Call these from Commands.
void ElevatorSubsystem::DriveElevator(float pullSpeed){
	//if underSwitch is pushed and pullspeed is plus, elevator doesn't move
	//if upSwitch is pushed and pullspeed is minus, elevator doesn't move
	if(!(underSwitch.Get() && pullSpeed > 0) && !(upSwitch.Get() && pullSpeed < 0)){
		pullMotorLeft.Set(pullSpeed);
		pullMotorRight.Set(pullSpeed);
	}
}

Fix Elevator Subsystem limit swtich

Fix Elevator Subsystem limit swtich


/*
 * Copyright (c) 2011 by Michael Berlin, Zuse Institute Berlin
 *
 * Licensed under the BSD License, see LICENSE file for details.
 *
 */

#include "libxtreemfs/callback/execute_sync_request.h"

using namespace xtreemfs::rpc;
using namespace xtreemfs::util;

namespace xtreemfs {

boost::thread_specific_ptr<int> intr_pointer;

void InterruptSyncRequest(int signal) {
  if (Logging::log->loggingActive(LEVEL_DEBUG)) {
    Logging::log->getLog(LEVEL_DEBUG)
        << "INTERRUPT triggered, setting TLS pointer" << std::endl;
  }
  intr_pointer.reset(new int(0));
}

}  // namespace xtreemfs

/*
 * Copyright (c) 2011 by Michael Berlin, Zuse Institute Berlin
 *
 * Licensed under the BSD License, see LICENSE file for details.
 *
 */

#include "libxtreemfs/callback/execute_sync_request.h"

using namespace xtreemfs::rpc;
using namespace xtreemfs::util;

namespace xtreemfs {

/** The TLS pointer is set to != NULL if the current operation shall be
 *  interrupted. */
boost::thread_specific_ptr<int> intr_pointer(NULL);

/** Calling malloc() inside a signal handler is a really bad idea as there may
 *  occur a dead lock on the lock of the heap: that happens if a malloc is in
 *  progress, which already obtained a lock on the heap, and now a signal
 *  handler is called (and executed in the same thread) and also tries to
 *  execute malloc.
 *
 *  For this reason the TLS is filled with the address of a static integer
 *  instead of a new-ly created integer.
 */
int dummy_integer = 1;

void InterruptSyncRequest(int signal) {
  if (Logging::log->loggingActive(LEVEL_DEBUG)) {
    Logging::log->getLog(LEVEL_DEBUG)
        << "INTERRUPT triggered, setting TLS pointer" << std::endl;
  }
  intr_pointer.reset(&dummy_integer);
}

}  // namespace xtreemfs

client: Remove implicit malloc() from interruption signal handler to prevent a deadlock of the whole client.

git-svn-id: 4a24f560d5bb049edaa12cbc2145b2f5ee41c6a2@2708 f8528748-c2c0-11dd-ba5c-d3b7c2b3b534


// RUN: %clang -fsyntax-only -verify %s
// RUN: %clang -fsyntax-only -verify -fshort-wchar %s

#include <limits.h>

const bool swchar = (wchar_t)-1 > (wchar_t)0;

#ifdef __WCHAR_UNSIGNED__
int signed_test[!swchar];
#else
int signed_test[swchar];
#endif

int max_test[WCHAR_MAX == (swchar ? -(WCHAR_MIN+1) : (wchar_t)-1)];
int min_test[WCHAR_MIN == (swchar ? 0 : -WCHAR_MAX-1)];

// RUN: %clang_cc1 -ffreestanding -fsyntax-only -verify %s
// RUN: %clang_cc1 -ffreestanding -fsyntax-only -verify -fshort-wchar %s

#include <limits.h>

const bool swchar = (wchar_t)-1 > (wchar_t)0;

#ifdef __WCHAR_UNSIGNED__
int signed_test[!swchar];
#else
int signed_test[swchar];
#endif

int max_test[WCHAR_MAX == (swchar ? -(WCHAR_MIN+1) : (wchar_t)-1)];
int min_test[WCHAR_MIN == (swchar ? 0 : -WCHAR_MAX-1)];

Use -ffreestanding with clang_cc1 to make the test picks the clang builtin include.

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