<commit_before>#include "pipe.hpp"
#include <unistd.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/wait.h>
#include <string>
#include <stdio.h>

Pipe::Pipe()
{}

bool Pipe::execute(const vector<string> &lhs, const vector<string> &rhs)
{
	int pid1;
	int status;
	int pipes[2];
	//int out;

	//pass in commands to args
	char* leftArgs[512];
	unsigned i;
	for (i = 0; i < lhs.size()-1; i++)
	{
		leftArgs[i] = (char*)lhs[i].c_str();
	}
	leftArgs[i] = NULL;

	char* rightArgs[512];
	unsigned j;
	for (j = 0; j < rhs.size(); j++)
	{
		rightArgs[j] = (char*)rhs[j].c_str();
	}
	rightArgs[j] = NULL;
	//set file descriptors
	//int in = open(input.c_str(), O_RDONLY);

	int outback = dup(1);
	//int inback = dup(0);

	//set output destination
	string filename = lhs[lhs.size() - 1];
	int in = open(filename.c_str(), O_RDONLY);

	//create pipe
	pipe(pipes);
	dup2(pipes[0], in);
	dup2(pipes[1], STDOUT_FILENO);

	pid1 = fork();

	if (pid1 == -1)
	{
		perror("fork");
		exit(1);
	}
	if (pid1 == 0) // child process
	{
		if (execvp(leftArgs[0], leftArgs) == -1)
		{
			perror("exec");
			//exit(1);

		}
		exit(1);
	}
	else // parent process
	{
		if (waitpid(pid1, &status, 0) == -1)
		{
			perror("wait");
			exit(1);
		}
		if (WEXITSTATUS(status) != 0)
		{
			return false;
		}
	}
	close(pipes[0]);
	int pid2 = fork();

	if (pid2 == -1)
	{
		perror("fork");
		exit(1);
	}
	if (pid2 == 0)
	{
		//dup2(pipes[0], 0);
		//close(pipes[1]);
		if (execvp(rightArgs[0], rightArgs) == -1)
		{
			perror("exec");
			exit(1);
		}
	}
	else
	{
		//dup2(pipes[1], newOut);
		//close(pipes[0]);
		if (execvp(rightArgs[0], rightArgs) == -1)
		{
			perror("exec");
			exit(1);
		}
		dup2(outback, 1);
		dup2(outback, pipes[1]);
		close(pipes[1]);
	}
	return true;
}<commit_msg>pipe trial<commit_after>#include "pipe.hpp"
#include <unistd.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/wait.h>
#include <string>
#include <stdio.h>

Pipe::Pipe()
{}

bool Pipe::execute(const vector<string> &lhs, const vector<string> &rhs)
{
	pid_t pid1;
	int status;
	int pipes[2];
	//int out;

	//pass in commands to args
	char* leftArgs[512];
	unsigned i;
	for (i = 0; i < lhs.size()-1; i++)
	{
		leftArgs[i] = (char*)lhs[i].c_str();
	}
	leftArgs[i] = NULL;

	char* rightArgs[512];
	unsigned j;
	for (j = 0; j < rhs.size(); j++)
	{
		rightArgs[j] = (char*)rhs[j].c_str();
	}
	rightArgs[j] = NULL;
	//set file descriptors
	//int in = open(input.c_str(), O_RDONLY);

	int outback = dup(1);
	//int inback = dup(0);

	//set output destination
	string filename = lhs[lhs.size() - 1];
	int in = open(filename.c_str(), O_RDONLY);

	//create pipe
	pipe(pipes);
	dup2(pipes[0], in);
	dup2(pipes[1], STDOUT_FILENO);

	pid1 = fork();

	if (pid1 == -1)
	{
		perror("fork");
		exit(1);
	}
	if (pid1 == 0) // child process
	{
		cout << "1ST FORK" << endl;
		if (execvp(leftArgs[0], leftArgs) == -1)
		{
			perror("exec");
			//exit(1);

		}
		exit(1);
	}
	else // parent process
	{
		if (waitpid(pid1, &status, 0) == -1)
		{
			perror("wait");
			exit(1);
		}
		if (WEXITSTATUS(status) != 0)
		{
			return false;
		}
	}
	close(pipes[0]);
	pid_t pid2 = fork();

	if (pid2 == -1)
	{
		perror("fork");
		exit(1);
	}
	if (pid2 == 0)
	{
		cout << "2ND FORK" << endl;
		//dup2(pipes[0], 0);
		//close(pipes[1]);
		if (execvp(rightArgs[0], rightArgs) == -1)
		{
			perror("exec");
			exit(1);
		}
	}
	else
	{
		//dup2(pipes[1], newOut);
		//close(pipes[0]);
		if (execvp(rightArgs[0], rightArgs) == -1)
		{
			perror("exec");
			exit(1);
		}
		dup2(outback, 1);
		dup2(outback, pipes[1]);
		close(pipes[1]);
	}
	return true;
}<|endoftext|>


<commit_before>//Copyright (c) 2020 Ultimaker B.V.
//CuraEngine is released under the terms of the AGPLv3 or higher.

#include "DistributedBeadingStrategy.h"

namespace cura
{

DistributedBeadingStrategy::Beading DistributedBeadingStrategy::compute(coord_t thickness, coord_t bead_count) const
{
    Beading ret;

    ret.total_thickness = thickness;
    if (bead_count > 0)
    {
        ret.bead_widths.resize(bead_count, thickness / bead_count);
        for (coord_t bead_idx = 0; bead_idx < bead_count; bead_idx++)
        {
            ret.toolpath_locations.emplace_back(thickness * (bead_idx * 2 + 1) / bead_count / 2);
        }
        ret.left_over = 0;
    }
    else
    {
        ret.left_over = thickness;
    }

    return ret;
}

coord_t DistributedBeadingStrategy::getOptimalThickness(coord_t bead_count) const
{
    return std::max(0LL, (bead_count - 2)) * optimal_width_inner + std::min(2LL, bead_count) * optimal_width_outer;
}

coord_t DistributedBeadingStrategy::getTransitionThickness(coord_t lower_bead_count) const
{
    // TODO: doesnt take min and max width into account
    const coord_t optimal_thickness = this->getOptimalThickness(lower_bead_count);
    return optimal_thickness + (optimal_thickness < 2 ? optimal_width_outer : optimal_width_inner) / 2;
}

coord_t DistributedBeadingStrategy::getOptimalBeadCount(coord_t thickness) const
{
    coord_t thickness_left = thickness;
    coord_t count = 0;
    count += std::min(2LL, (thickness + optimal_width_outer / 2) / optimal_width_outer);
    thickness_left -= count * optimal_width_outer;
    if (thickness_left >= (optimal_width_inner / 2))
    {
        count += (thickness_left + optimal_width_inner / 2) / optimal_width_inner;
    }
    return count;
}

} // namespace cura
<commit_msg>Process one more review comment.<commit_after>//Copyright (c) 2020 Ultimaker B.V.
//CuraEngine is released under the terms of the AGPLv3 or higher.

#include "DistributedBeadingStrategy.h"

namespace cura
{

DistributedBeadingStrategy::Beading DistributedBeadingStrategy::compute(coord_t thickness, coord_t bead_count) const
{
    Beading ret;

    ret.total_thickness = thickness;
    if (bead_count > 0)
    {
        ret.bead_widths.resize(bead_count, thickness / bead_count);
        for (coord_t bead_idx = 0; bead_idx < bead_count; bead_idx++)
        {
            ret.toolpath_locations.emplace_back(thickness * (bead_idx * 2 + 1) / bead_count / 2);
        }
        ret.left_over = 0;
    }
    else
    {
        ret.left_over = thickness;
    }

    return ret;
}

coord_t DistributedBeadingStrategy::getOptimalThickness(coord_t bead_count) const
{
    return std::max(0LL, (bead_count - 2)) * optimal_width_inner + std::min(2LL, bead_count) * optimal_width_outer;
}

coord_t DistributedBeadingStrategy::getTransitionThickness(coord_t lower_bead_count) const
{
    // TODO: doesnt take min and max width into account
    const coord_t optimal_thickness = this->getOptimalThickness(lower_bead_count);
    return optimal_thickness + (optimal_thickness < 2 ? optimal_width_outer : optimal_width_inner) / 2;
}

coord_t DistributedBeadingStrategy::getOptimalBeadCount(coord_t thickness) const
{
    coord_t thickness_left = thickness;
    coord_t count = std::min(2LL, (thickness + optimal_width_outer / 2) / optimal_width_outer);
    thickness_left -= count * optimal_width_outer;
    if (thickness_left >= (optimal_width_inner / 2))
    {
        count += (thickness_left + optimal_width_inner / 2) / optimal_width_inner;
    }
    return count;
}

} // namespace cura
<|endoftext|>


<commit_before>/*******************************************************************************

Licensed to the OpenCOR team under one or more contributor license agreements.
See the NOTICE.txt file distributed with this work for additional information
regarding copyright ownership. The OpenCOR team licenses this file to you under
the Apache License, Version 2.0 (the "License"); you may not use this file
except in compliance with the License. You may obtain a copy of the License at

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

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

*******************************************************************************/

//==============================================================================
// CellMLSupport plugin
//==============================================================================

#include "cellmlfilemanager.h"
#include "cellmlsupportplugin.h"
#include "filemanager.h"

//==============================================================================

#include <QFile>
#include <QFileInfo>
#include <QIODevice>
#include <QXmlStreamReader>

//==============================================================================

namespace OpenCOR {
namespace CellMLSupport {

//==============================================================================

PLUGININFO_FUNC CellMLSupportPluginInfo()
{
    Descriptions descriptions;

    descriptions.insert("en", QString::fromUtf8("a plugin to support CellML."));
    descriptions.insert("fr", QString::fromUtf8("une extension pour supporter CellML."));

    return new PluginInfo(PluginInfo::Support, false,
                          QStringList() << "Core" << "CellMLAPI" << "Compiler" << "CoreSolver",
                          descriptions);
}

//==============================================================================
// Core interface
//==============================================================================

void CellMLSupportPlugin::initialize()
{
    // We don't handle this interface...
}

//==============================================================================

void CellMLSupportPlugin::finalize()
{
    // We don't handle this interface...
}

//==============================================================================

void CellMLSupportPlugin::initialized(const Plugins &pLoadedPlugins)
{
    Q_UNUSED(pLoadedPlugins);

    // Make a call to the instance of the CellML file manager so that it gets
    // properly set up before it actually gets used
    // Note: we do it here rather than in initialize() since we need the Core
    //       plugin to be initialised (so we can get access to our 'global' file
    //       manager)...

    CellmlFileManager::instance();
}

//==============================================================================

void CellMLSupportPlugin::loadSettings(QSettings *pSettings)
{
    Q_UNUSED(pSettings);

    // We don't handle this interface...
}

//==============================================================================

void CellMLSupportPlugin::saveSettings(QSettings *pSettings) const
{
    Q_UNUSED(pSettings);

    // We don't handle this interface...
}

//==============================================================================

void CellMLSupportPlugin::settingsLoaded(const Plugins &pLoadedPlugins)
{
    Q_UNUSED(pLoadedPlugins);

    // We don't handle this interface...
}

//==============================================================================

void CellMLSupportPlugin::handleArguments(const QStringList &pArguments)
{
    Q_UNUSED(pArguments);

    // We don't handle this interface...
}

//==============================================================================

void CellMLSupportPlugin::handleAction(const QUrl &pUrl)
{
    Q_UNUSED(pUrl);

    // We don't handle this interface...
}

//==============================================================================
// File interface
//==============================================================================

FileTypes CellMLSupportPlugin::fileTypes() const
{
    // Return the CellML file type that the CellMLSupport plugin supports

    return FileTypes() << FileType(qobject_cast<FileInterface *>(this),
                                   CellmlMimeType, CellmlFileExtension);
}

//==============================================================================

QString CellMLSupportPlugin::fileTypeDescription(const QString &pMimeType) const
{
    // Return the description for the requested MIME type, that is as long as it
    // is for the CellML MIME type

    if (!pMimeType.compare(CellmlMimeType))
        return tr("CellML File");
    else
        // Not a MIME type that we can recognise, so...

        return QString();
}

//==============================================================================
// GUI interface
//==============================================================================

void CellMLSupportPlugin::retranslateUi()
{
    // We don't handle this interface...
}

//==============================================================================
// Plugin specific
//==============================================================================

bool isCellmlFile(const QString &pFileName)
{
    // Return whether the file is a CellML file

    if (!QFileInfo(pFileName).completeSuffix().compare(CellmlFileExtension))
        // We are dealing with a file which file extension is that of a CellML
        // file, so...

        return true;

    // The file doesn't have the 'correct' file extension, so check whether it's
    // a new file

    if (Core::FileManager::instance()->isNew(pFileName))
        return true;

    // The file neither has the 'correct' file extension nor is a new file, so
    // quickly check its contents

    QFile file(pFileName);

    if (!file.open(QIODevice::ReadOnly))
        // We can't open the file, so...

        return false;

    // Try to read the file as if it was an XML file

    QXmlStreamReader xml(&file);

    bool res = false;

    while (!xml.atEnd() && !xml.hasError()) {
        xml.readNext();

        if (xml.isStartElement()) {
            // This is our root element, so for the file to be considered a
            // CellML file it should be a model element in either the CellML 1.0
            // or 1.1 namespace

            if (   !xml.name().toString().compare("model")
                &&  (   (!xml.namespaceUri().toString().compare("http://www.cellml.org/cellml/1.0#"))
                     || (!xml.namespaceUri().toString().compare("http://www.cellml.org/cellml/1.1#")))) {
                // All the requirements are gathered for the file to be
                // considered a CellML file, so...

                res = true;
            }

            break;
        }
    }

    file.close();

    // We are done, so...

    return res;
}

//==============================================================================

}   // namespace CellMLSupport
}   // namespace OpenCOR

//==============================================================================
// End of file
//==============================================================================
<commit_msg>Some minor cleaning up.<commit_after>/*******************************************************************************

Licensed to the OpenCOR team under one or more contributor license agreements.
See the NOTICE.txt file distributed with this work for additional information
regarding copyright ownership. The OpenCOR team licenses this file to you under
the Apache License, Version 2.0 (the "License"); you may not use this file
except in compliance with the License. You may obtain a copy of the License at

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

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

*******************************************************************************/

//==============================================================================
// CellMLSupport plugin
//==============================================================================

#include "cellmlfilemanager.h"
#include "cellmlsupportplugin.h"
#include "filemanager.h"

//==============================================================================

#include <QFile>
#include <QFileInfo>
#include <QIODevice>
#include <QXmlStreamReader>

//==============================================================================

namespace OpenCOR {
namespace CellMLSupport {

//==============================================================================

PLUGININFO_FUNC CellMLSupportPluginInfo()
{
    Descriptions descriptions;

    descriptions.insert("en", QString::fromUtf8("a plugin to support CellML."));
    descriptions.insert("fr", QString::fromUtf8("une extension pour supporter CellML."));

    return new PluginInfo(PluginInfo::Support, false,
                          QStringList() << "Core" << "CellMLAPI" << "Compiler" << "CoreSolver",
                          descriptions);
}

//==============================================================================
// Core interface
//==============================================================================

void CellMLSupportPlugin::initialize()
{
    // We don't handle this interface...
}

//==============================================================================

void CellMLSupportPlugin::finalize()
{
    // We don't handle this interface...
}

//==============================================================================

void CellMLSupportPlugin::initialized(const Plugins &pLoadedPlugins)
{
    Q_UNUSED(pLoadedPlugins);

    // Make a call to the instance of the CellML file manager so that it gets
    // properly set up before it actually gets used
    // Note: we do it here rather than in initialize() since we need the Core
    //       plugin to be initialised (so we can get access to our 'global' file
    //       manager)...

    CellmlFileManager::instance();
}

//==============================================================================

void CellMLSupportPlugin::loadSettings(QSettings *pSettings)
{
    Q_UNUSED(pSettings);

    // We don't handle this interface...
}

//==============================================================================

void CellMLSupportPlugin::saveSettings(QSettings *pSettings) const
{
    Q_UNUSED(pSettings);

    // We don't handle this interface...
}

//==============================================================================

void CellMLSupportPlugin::settingsLoaded(const Plugins &pLoadedPlugins)
{
    Q_UNUSED(pLoadedPlugins);

    // We don't handle this interface...
}

//==============================================================================

void CellMLSupportPlugin::handleArguments(const QStringList &pArguments)
{
    Q_UNUSED(pArguments);

    // We don't handle this interface...
}

//==============================================================================

void CellMLSupportPlugin::handleAction(const QUrl &pUrl)
{
    Q_UNUSED(pUrl);

    // We don't handle this interface...
}

//==============================================================================
// File interface
//==============================================================================

FileTypes CellMLSupportPlugin::fileTypes() const
{
    // Return the CellML file type that the CellMLSupport plugin supports

    return FileTypes() << FileType(qobject_cast<FileInterface *>(this),
                                   CellmlMimeType, CellmlFileExtension);
}

//==============================================================================

QString CellMLSupportPlugin::fileTypeDescription(const QString &pMimeType) const
{
    // Return the description for the requested MIME type, that is as long as it
    // is for the CellML MIME type

    if (!pMimeType.compare(CellmlMimeType))
        return tr("CellML File");
    else
        // Not a MIME type that we can recognise, so...

        return QString();
}

//==============================================================================
// GUI interface
//==============================================================================

void CellMLSupportPlugin::retranslateUi()
{
    // We don't handle this interface...
}

//==============================================================================
// Plugin specific
//==============================================================================

bool isCellmlFile(const QString &pFileName)
{
    // Return whether the file is a CellML file

    if (!QFileInfo(pFileName).completeSuffix().compare(CellmlFileExtension))
        // We are dealing with a file which file extension is that of a CellML
        // file, so...

        return true;

    // The file doesn't have the 'correct' file extension, so check whether it's
    // a new file

    if (Core::FileManager::instance()->isNew(pFileName))
        return true;

    // The file neither has the 'correct' file extension nor is a new file, so
    // quickly check its contents

    QFile file(pFileName);

    if (!file.open(QIODevice::ReadOnly))
        // We can't open the file, so...

        return false;

    // Try to read the file as if it was an XML file

    QXmlStreamReader xml(&file);

    bool res = false;

    xml.readNext();

    while (!xml.atEnd()) {
        if (xml.isStartElement()) {
            // This is our root element, so for the file to be considered a
            // CellML file it should be a model element in either the CellML 1.0
            // or 1.1 namespace

            if (   !xml.name().toString().compare("model")
                &&  (   (!xml.namespaceUri().toString().compare("http://www.cellml.org/cellml/1.0#"))
                     || (!xml.namespaceUri().toString().compare("http://www.cellml.org/cellml/1.1#")))) {
                // All the requirements are gathered for the file to be
                // considered a CellML file, so...

                res = true;
            }

            break;
        }

        xml.readNext();
    }

    file.close();

    // We are done, so...

    return res;
}

//==============================================================================

}   // namespace CellMLSupport
}   // namespace OpenCOR

//==============================================================================
// End of file
//==============================================================================
<|endoftext|>


<commit_before>/*ckwg +5
 * Copyright 2011 by Kitware, Inc. All Rights Reserved. Please refer to
 * KITWARE_LICENSE.TXT for licensing information, or contact General Counsel,
 * Kitware, Inc., 28 Corporate Drive, Clifton Park, NY 12065.
 */

#include "component_score_json_writer_process.h"

#include <vistk/pipeline/datum.h>
#include <vistk/pipeline/process_exception.h>

#include <vistk/scoring/scoring_result.h>
#include <vistk/scoring/scoring_statistics.h>
#include <vistk/scoring/statistics.h>

#include <vistk/utilities/path.h>

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

#include <fstream>
#include <string>

/**
 * \file component_score_json_writer_process.cxx
 *
 * \brief Implementation of a process which writes out component scores to a file in JSON.
 */

namespace vistk
{

class component_score_json_writer_process::priv
{
  public:
    typedef port_t tag_t;
    typedef std::vector<tag_t> tags_t;

    typedef std::map<tag_t, bool> tag_stat_map_t;

    priv();
    priv(path_t const& output_path, tags_t const& tags_);
    ~priv();

    path_t const path;

    std::ofstream fout;

    tags_t tags;
    tag_stat_map_t tag_stats;

    static config::key_t const config_path;
    static port_t const port_score_prefix;
    static port_t const port_stats_prefix;
};

config::key_t const component_score_json_writer_process::priv::config_path = "path";
process::port_t const component_score_json_writer_process::priv::port_score_prefix = process::port_t("score/");
process::port_t const component_score_json_writer_process::priv::port_stats_prefix = process::port_t("stats/");

component_score_json_writer_process
::component_score_json_writer_process(config_t const& config)
  : process(config)
  , d(new priv)
{
  declare_configuration_key(priv::config_path, boost::make_shared<conf_info>(
    config::value_t(),
    config::description_t("The path to output scores to.")));
}

component_score_json_writer_process
::~component_score_json_writer_process()
{
}

void
component_score_json_writer_process
::_configure()
{
  // Configure the process.
  {
    path_t const path = config_value<path_t>(priv::config_path);

    d.reset(new priv(path, d->tags));
  }

  path_t::string_type const path = d->path.native();

  if (path.empty())
  {
    static std::string const reason = "The path given was empty";
    config::value_t const value = config::value_t(path.begin(), path.end());

    throw invalid_configuration_value_exception(name(), priv::config_path, value, reason);
  }

  d->fout.open(path.c_str());

  if (!d->fout.good())
  {
    std::string const file_path(path.begin(), path.end());
    std::string const reason = "Failed to open the path: " + file_path;

    throw invalid_configuration_exception(name(), reason);
  }

  process::_configure();
}

void
component_score_json_writer_process
::_init()
{
  if (!d->tags.size())
  {
    static std::string const reason = "There must be at least one component score to write";

    throw invalid_configuration_exception(name(), reason);
  }

  BOOST_FOREACH (priv::tag_t const& tag, d->tags)
  {
    port_t const port_stat = priv::port_stats_prefix + tag;

    d->tag_stats[tag] = false;

    if (input_port_edge(port_stat))
    {
      d->tag_stats[tag] = true;
    }
  }

  process::_init();
}

void
component_score_json_writer_process
::_step()
{
#define JSON_KEY(key) \
  ("\"" key "\": ")
#define JSON_ATTR(key, value) \
  JSON_KEY(key) << value
#define JSON_SEP \
  "," << std::endl
#define JSON_OBJECT_BEGIN \
  "{" << std::endl
#define JSON_OBJECT_END \
  "}"

  d->fout << JSON_OBJECT_BEGIN;

  /// \todo Name runs.
  d->fout << JSON_ATTR("name", "\"(unnamed)\"");
  d->fout << JSON_SEP;
  /// \todo Insert date.
  d->fout << JSON_ATTR("date", "\"\"");
  d->fout << JSON_SEP;
  /// \todo Get git hash.
  d->fout << JSON_ATTR("hash", "\"\"");
  d->fout << JSON_SEP;
  d->fout << JSON_ATTR("config", "{}");
  d->fout << JSON_SEP;
  d->fout << JSON_KEY("results") << JSON_OBJECT_BEGIN;

  bool first = true;

  BOOST_FOREACH (priv::tag_t const& tag, d->tags)
  {
    if (!first)
    {
      d->fout << JSON_SEP;
    }

    first = false;

    d->fout << JSON_KEY(+ tag +);

    d->fout << JSON_OBJECT_BEGIN;

    scoring_result_t const result = grab_from_port_as<scoring_result_t>(priv::port_score_prefix + tag);

    d->fout << JSON_ATTR("true-positive", result->true_positives);
    d->fout << JSON_SEP;
    d->fout << JSON_ATTR("false-positive", result->false_positives);
    d->fout << JSON_SEP;
    d->fout << JSON_ATTR("total-true", result->total_trues);
    d->fout << JSON_SEP;
    d->fout << JSON_ATTR("total-possible", result->total_possible);
    d->fout << JSON_SEP;
    d->fout << JSON_ATTR("percent-detection", result->percent_detection());
    d->fout << JSON_SEP;
    d->fout << JSON_ATTR("precision", result->precision());
    d->fout << JSON_SEP;
    d->fout << JSON_ATTR("specificity", result->specificity());

    if (d->tag_stats[tag])
    {
      port_t const port_stats = priv::port_stats_prefix + tag;

      d->fout << JSON_SEP;

#define OUTPUT_STATISTICS(key, stats)                                        \
  do                                                                         \
  {                                                                          \
    d->fout << JSON_KEY(key);                                                \
    d->fout << JSON_OBJECT_BEGIN;                                            \
    d->fout << JSON_ATTR("count", stats->count());                           \
    d->fout << JSON_SEP;                                                     \
    d->fout << JSON_ATTR("min", stats->minimum());                           \
    d->fout << JSON_SEP;                                                     \
    d->fout << JSON_ATTR("max", stats->maximum());                           \
    d->fout << JSON_SEP;                                                     \
    d->fout << JSON_ATTR("mean", stats->mean());                             \
    d->fout << JSON_SEP;                                                     \
    d->fout << JSON_ATTR("median", stats->median());                         \
    d->fout << JSON_SEP;                                                     \
    d->fout << JSON_ATTR("standard-deviation", stats->standard_deviation()); \
    d->fout << JSON_OBJECT_END;                                              \
  } while (false)

      scoring_statistics_t const sc_stats = grab_from_port_as<scoring_statistics_t>(port_stats);

      statistics_t const pd_stats = sc_stats->percent_detection_stats();
      statistics_t const precision_stats = sc_stats->precision_stats();
      statistics_t const specificity_stats = sc_stats->specificity_stats();

      d->fout << JSON_KEY("statistics");
      d->fout << JSON_OBJECT_BEGIN;
      OUTPUT_STATISTICS("percent-detection", pd_stats);
      d->fout << JSON_SEP;
      OUTPUT_STATISTICS("precision", precision_stats);
      d->fout << JSON_SEP;
      OUTPUT_STATISTICS("specificity", specificity_stats);
      d->fout << JSON_OBJECT_END;

#undef OUTPUT_STATISTICS
    }

    d->fout << JSON_OBJECT_END;
  }

  d->fout << std::endl;
  d->fout << JSON_OBJECT_END;
  d->fout << std::endl;
  d->fout << JSON_OBJECT_END;
  d->fout << std::endl;

#undef JSON_OBJECT_END
#undef JSON_OBJECT_BEGIN
#undef JSON_SEP
#undef JSON_ATTR
#undef JSON_KEY

  process::_step();
}

process::port_info_t
component_score_json_writer_process
::_input_port_info(port_t const& port)
{
  if (boost::starts_with(port, priv::port_score_prefix))
  {
    priv::tag_t const tag = port.substr(priv::port_score_prefix.size());

    priv::tags_t::const_iterator const i = std::find(d->tags.begin(), d->tags.end(), tag);

    if (i == d->tags.end())
    {
      port_t const port_score = priv::port_score_prefix + tag;
      port_t const port_stats = priv::port_stats_prefix + tag;

      d->tags.push_back(tag);

      port_flags_t required;

      required.insert(flag_required);

      declare_input_port(port_score, boost::make_shared<port_info>(
        "score",
        required,
        port_description_t("The \'" + tag + "\' score component.")));
      declare_input_port(port_stats, boost::make_shared<port_info>(
        "statistics/score",
        port_flags_t(),
        port_description_t("The \'" + tag + "\' score statistics component.")));
    }
  }

  return process::_input_port_info(port);
}

component_score_json_writer_process::priv
::priv()
{
}

component_score_json_writer_process::priv
::priv(path_t const& output_path, tags_t const& tags_)
  : path(output_path)
  , tags(tags_)
{
}

component_score_json_writer_process::priv
::~priv()
{
}

}
<commit_msg>Factor out port name combining<commit_after>/*ckwg +5
 * Copyright 2011 by Kitware, Inc. All Rights Reserved. Please refer to
 * KITWARE_LICENSE.TXT for licensing information, or contact General Counsel,
 * Kitware, Inc., 28 Corporate Drive, Clifton Park, NY 12065.
 */

#include "component_score_json_writer_process.h"

#include <vistk/pipeline/datum.h>
#include <vistk/pipeline/process_exception.h>

#include <vistk/scoring/scoring_result.h>
#include <vistk/scoring/scoring_statistics.h>
#include <vistk/scoring/statistics.h>

#include <vistk/utilities/path.h>

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

#include <fstream>
#include <string>

/**
 * \file component_score_json_writer_process.cxx
 *
 * \brief Implementation of a process which writes out component scores to a file in JSON.
 */

namespace vistk
{

class component_score_json_writer_process::priv
{
  public:
    typedef port_t tag_t;
    typedef std::vector<tag_t> tags_t;

    typedef std::map<tag_t, bool> tag_stat_map_t;

    priv();
    priv(path_t const& output_path, tags_t const& tags_);
    ~priv();

    path_t const path;

    std::ofstream fout;

    tags_t tags;
    tag_stat_map_t tag_stats;

    static config::key_t const config_path;
    static port_t const port_score_prefix;
    static port_t const port_stats_prefix;
};

config::key_t const component_score_json_writer_process::priv::config_path = "path";
process::port_t const component_score_json_writer_process::priv::port_score_prefix = process::port_t("score/");
process::port_t const component_score_json_writer_process::priv::port_stats_prefix = process::port_t("stats/");

component_score_json_writer_process
::component_score_json_writer_process(config_t const& config)
  : process(config)
  , d(new priv)
{
  declare_configuration_key(priv::config_path, boost::make_shared<conf_info>(
    config::value_t(),
    config::description_t("The path to output scores to.")));
}

component_score_json_writer_process
::~component_score_json_writer_process()
{
}

void
component_score_json_writer_process
::_configure()
{
  // Configure the process.
  {
    path_t const path = config_value<path_t>(priv::config_path);

    d.reset(new priv(path, d->tags));
  }

  path_t::string_type const path = d->path.native();

  if (path.empty())
  {
    static std::string const reason = "The path given was empty";
    config::value_t const value = config::value_t(path.begin(), path.end());

    throw invalid_configuration_value_exception(name(), priv::config_path, value, reason);
  }

  d->fout.open(path.c_str());

  if (!d->fout.good())
  {
    std::string const file_path(path.begin(), path.end());
    std::string const reason = "Failed to open the path: " + file_path;

    throw invalid_configuration_exception(name(), reason);
  }

  process::_configure();
}

void
component_score_json_writer_process
::_init()
{
  if (!d->tags.size())
  {
    static std::string const reason = "There must be at least one component score to write";

    throw invalid_configuration_exception(name(), reason);
  }

  BOOST_FOREACH (priv::tag_t const& tag, d->tags)
  {
    port_t const port_stat = priv::port_stats_prefix + tag;

    d->tag_stats[tag] = false;

    if (input_port_edge(port_stat))
    {
      d->tag_stats[tag] = true;
    }
  }

  process::_init();
}

void
component_score_json_writer_process
::_step()
{
#define JSON_KEY(key) \
  ("\"" key "\": ")
#define JSON_ATTR(key, value) \
  JSON_KEY(key) << value
#define JSON_SEP \
  "," << std::endl
#define JSON_OBJECT_BEGIN \
  "{" << std::endl
#define JSON_OBJECT_END \
  "}"

  d->fout << JSON_OBJECT_BEGIN;

  /// \todo Name runs.
  d->fout << JSON_ATTR("name", "\"(unnamed)\"");
  d->fout << JSON_SEP;
  /// \todo Insert date.
  d->fout << JSON_ATTR("date", "\"\"");
  d->fout << JSON_SEP;
  /// \todo Get git hash.
  d->fout << JSON_ATTR("hash", "\"\"");
  d->fout << JSON_SEP;
  d->fout << JSON_ATTR("config", "{}");
  d->fout << JSON_SEP;
  d->fout << JSON_KEY("results") << JSON_OBJECT_BEGIN;

  bool first = true;

  BOOST_FOREACH (priv::tag_t const& tag, d->tags)
  {
    port_t const port_score = priv::port_score_prefix + tag;

    if (!first)
    {
      d->fout << JSON_SEP;
    }

    first = false;

    d->fout << JSON_KEY(+ tag +);

    d->fout << JSON_OBJECT_BEGIN;

    scoring_result_t const result = grab_from_port_as<scoring_result_t>(port_score);

    d->fout << JSON_ATTR("true-positive", result->true_positives);
    d->fout << JSON_SEP;
    d->fout << JSON_ATTR("false-positive", result->false_positives);
    d->fout << JSON_SEP;
    d->fout << JSON_ATTR("total-true", result->total_trues);
    d->fout << JSON_SEP;
    d->fout << JSON_ATTR("total-possible", result->total_possible);
    d->fout << JSON_SEP;
    d->fout << JSON_ATTR("percent-detection", result->percent_detection());
    d->fout << JSON_SEP;
    d->fout << JSON_ATTR("precision", result->precision());
    d->fout << JSON_SEP;
    d->fout << JSON_ATTR("specificity", result->specificity());

    if (d->tag_stats[tag])
    {
      port_t const port_stats = priv::port_stats_prefix + tag;

      d->fout << JSON_SEP;

#define OUTPUT_STATISTICS(key, stats)                                        \
  do                                                                         \
  {                                                                          \
    d->fout << JSON_KEY(key);                                                \
    d->fout << JSON_OBJECT_BEGIN;                                            \
    d->fout << JSON_ATTR("count", stats->count());                           \
    d->fout << JSON_SEP;                                                     \
    d->fout << JSON_ATTR("min", stats->minimum());                           \
    d->fout << JSON_SEP;                                                     \
    d->fout << JSON_ATTR("max", stats->maximum());                           \
    d->fout << JSON_SEP;                                                     \
    d->fout << JSON_ATTR("mean", stats->mean());                             \
    d->fout << JSON_SEP;                                                     \
    d->fout << JSON_ATTR("median", stats->median());                         \
    d->fout << JSON_SEP;                                                     \
    d->fout << JSON_ATTR("standard-deviation", stats->standard_deviation()); \
    d->fout << JSON_OBJECT_END;                                              \
  } while (false)

      scoring_statistics_t const sc_stats = grab_from_port_as<scoring_statistics_t>(port_stats);

      statistics_t const pd_stats = sc_stats->percent_detection_stats();
      statistics_t const precision_stats = sc_stats->precision_stats();
      statistics_t const specificity_stats = sc_stats->specificity_stats();

      d->fout << JSON_KEY("statistics");
      d->fout << JSON_OBJECT_BEGIN;
      OUTPUT_STATISTICS("percent-detection", pd_stats);
      d->fout << JSON_SEP;
      OUTPUT_STATISTICS("precision", precision_stats);
      d->fout << JSON_SEP;
      OUTPUT_STATISTICS("specificity", specificity_stats);
      d->fout << JSON_OBJECT_END;

#undef OUTPUT_STATISTICS
    }

    d->fout << JSON_OBJECT_END;
  }

  d->fout << std::endl;
  d->fout << JSON_OBJECT_END;
  d->fout << std::endl;
  d->fout << JSON_OBJECT_END;
  d->fout << std::endl;

#undef JSON_OBJECT_END
#undef JSON_OBJECT_BEGIN
#undef JSON_SEP
#undef JSON_ATTR
#undef JSON_KEY

  process::_step();
}

process::port_info_t
component_score_json_writer_process
::_input_port_info(port_t const& port)
{
  if (boost::starts_with(port, priv::port_score_prefix))
  {
    priv::tag_t const tag = port.substr(priv::port_score_prefix.size());

    priv::tags_t::const_iterator const i = std::find(d->tags.begin(), d->tags.end(), tag);

    if (i == d->tags.end())
    {
      port_t const port_score = priv::port_score_prefix + tag;
      port_t const port_stats = priv::port_stats_prefix + tag;

      d->tags.push_back(tag);

      port_flags_t required;

      required.insert(flag_required);

      declare_input_port(port_score, boost::make_shared<port_info>(
        "score",
        required,
        port_description_t("The \'" + tag + "\' score component.")));
      declare_input_port(port_stats, boost::make_shared<port_info>(
        "statistics/score",
        port_flags_t(),
        port_description_t("The \'" + tag + "\' score statistics component.")));
    }
  }

  return process::_input_port_info(port);
}

component_score_json_writer_process::priv
::priv()
{
}

component_score_json_writer_process::priv
::priv(path_t const& output_path, tags_t const& tags_)
  : path(output_path)
  , tags(tags_)
{
}

component_score_json_writer_process::priv
::~priv()
{
}

}
<|endoftext|>


<commit_before>#include <stan/math/error_handling/matrix/check_cov_matrix.hpp>
#include <gtest/gtest.h>

<commit_msg>moving check_cov_matrix tests out of math/matrix_error_handling_test.cpp<commit_after>#include <stan/math/error_handling/matrix/check_cov_matrix.hpp>
#include <gtest/gtest.h>

TEST(MathErrorHandlingMatrix, checkCovMatrix) {
  Eigen::Matrix<double,Eigen::Dynamic,Eigen::Dynamic> y;
  double result;

  y.resize(3,3);
  y << 2, -1, 0, -1, 2, -1, 0, -1, 2;
  EXPECT_TRUE(stan::math::check_cov_matrix("checkCovMatrix(%1%)",
                                           y, "y", &result));
  EXPECT_TRUE(stan::math::check_cov_matrix("checkCovMatrix(%1%)",
                                           y, "y"));

  y << 1, 2, 3, 2, 1, 2, 3, 2, 1;
  EXPECT_THROW(stan::math::check_cov_matrix("checkCovMatrix(%1%)", y, "y", &result),
               std::domain_error);
  EXPECT_THROW(stan::math::check_cov_matrix("checkCovMatrix(%1%)", y, "y"),
               std::domain_error);
}
<|endoftext|>


<commit_before>/*
 * The Apache Software License, Version 1.1
 *
 *
 * Copyright (c) 2000 The Apache Software Foundation.  All rights
 * reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in
 *    the documentation and/or other materials provided with the
 *    distribution.
 *
 * 3. The end-user documentation included with the redistribution,
 *    if any, must include the following acknowledgment:
 *       "This product includes software developed by the
 *        Apache Software Foundation (http://www.apache.org/)."
 *    Alternately, this acknowledgment may appear in the software itself,
 *    if and wherever such third-party acknowledgments normally appear.
 *
 * 4. The names "Xalan" and "Apache Software Foundation" must
 *    not be used to endorse or promote products derived from this
 *    software without prior written permission. For written
 *    permission, please contact apache@apache.org.
 *
 * 5. Products derived from this software may not be called "Apache",
 *    nor may "Apache" appear in their name, without prior written
 *    permission of the Apache Software Foundation.
 *
 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED.  IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
 * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
 * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 * ====================================================================
 *
 * This software consists of voluntary contributions made by many
 * individuals on behalf of the Apache Software Foundation and was
 * originally based on software copyright (c) 1999, International
 * Business Machines, Inc., http://www.ibm.com.  For more
 * information on the Apache Software Foundation, please see
 * <http://www.apache.org/>.
 */

#include "ICUBridgeCollationCompareFunctor.hpp"
#include "ICUBridge.hpp"

#include <PlatformSupport/DOMStringHelper.hpp>

#include <unicode/coll.h>

const StylesheetExecutionContextDefault::DefaultCollationCompareFunctor		ICUBridgeCollationCompareFunctor::s_defaultFunctor;

ICUBridgeCollationCompareFunctor::ICUBridgeCollationCompareFunctor() :
	m_isValid(false),
	m_collator(0)
{
	UErrorCode	theStatus = U_ZERO_ERROR;

	m_collator = Collator::createInstance(theStatus);

	if (theStatus == U_ZERO_ERROR || theStatus == U_USING_DEFAULT_ERROR)
	{
		m_isValid = true;
	}
}

ICUBridgeCollationCompareFunctor::~ICUBridgeCollationCompareFunctor()
{
	delete m_collator;
}

static UChar	dummy = 0;

int
ICUBridgeCollationCompareFunctor::operator()(
			const XalanDOMChar*		theLHS,
			const XalanDOMChar*		theRHS) const
{
	if (isValid() == false)
	{
		return s_defaultFunctor(theLHS, theRHS);
	}
	else
	{
		assert(m_collator != 0);

		return m_collator->compare(
					theLHS,
					length(theLHS),
					theRHS,
					length(theRHS));
	}
}
<commit_msg>Cast to (wchar_t*) for AIX.<commit_after>/*
 * The Apache Software License, Version 1.1
 *
 *
 * Copyright (c) 2000 The Apache Software Foundation.  All rights
 * reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in
 *    the documentation and/or other materials provided with the
 *    distribution.
 *
 * 3. The end-user documentation included with the redistribution,
 *    if any, must include the following acknowledgment:
 *       "This product includes software developed by the
 *        Apache Software Foundation (http://www.apache.org/)."
 *    Alternately, this acknowledgment may appear in the software itself,
 *    if and wherever such third-party acknowledgments normally appear.
 *
 * 4. The names "Xalan" and "Apache Software Foundation" must
 *    not be used to endorse or promote products derived from this
 *    software without prior written permission. For written
 *    permission, please contact apache@apache.org.
 *
 * 5. Products derived from this software may not be called "Apache",
 *    nor may "Apache" appear in their name, without prior written
 *    permission of the Apache Software Foundation.
 *
 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED.  IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
 * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
 * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 * ====================================================================
 *
 * This software consists of voluntary contributions made by many
 * individuals on behalf of the Apache Software Foundation and was
 * originally based on software copyright (c) 1999, International
 * Business Machines, Inc., http://www.ibm.com.  For more
 * information on the Apache Software Foundation, please see
 * <http://www.apache.org/>.
 */

#include "ICUBridgeCollationCompareFunctor.hpp"
#include "ICUBridge.hpp"

#include <PlatformSupport/DOMStringHelper.hpp>

#include <unicode/coll.h>

const StylesheetExecutionContextDefault::DefaultCollationCompareFunctor		ICUBridgeCollationCompareFunctor::s_defaultFunctor;

ICUBridgeCollationCompareFunctor::ICUBridgeCollationCompareFunctor() :
	m_isValid(false),
	m_collator(0)
{
	UErrorCode	theStatus = U_ZERO_ERROR;

	m_collator = Collator::createInstance(theStatus);

	if (theStatus == U_ZERO_ERROR || theStatus == U_USING_DEFAULT_ERROR)
	{
		m_isValid = true;
	}
}

ICUBridgeCollationCompareFunctor::~ICUBridgeCollationCompareFunctor()
{
	delete m_collator;
}

static UChar	dummy = 0;

int
ICUBridgeCollationCompareFunctor::operator()(
			const XalanDOMChar*		theLHS,
			const XalanDOMChar*		theRHS) const
{
	if (isValid() == false)
	{
		return s_defaultFunctor(theLHS, theRHS);
	}
	else
	{
		assert(m_collator != 0);

		return m_collator->compare(
					(wchar_t*)theLHS,
					length(theLHS),
					(wchar_t*)theRHS,
					length(theRHS));
	}
}
<|endoftext|>


<commit_before>#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include <math.h>

#include <SDL2/SDL.h>
#include <SDL2/SDL_image.h>
#include <SDL2/SDL_ttf.h>

#include "pong.hpp"
#include "util.hpp"

typedef struct {
	float x;
	float y;
	float vx;
	float vy;
} ball;

typedef struct {
	int x;
	int y;
	int width;
	int height;
	int score;
	int speed;
} player;

float calc_angle(float y1, float y2, int height) {
	float rely = y1 + height/2 - y2;
	rely /= height/2.0;   // Normalise
	return rely * MAX_ANGLE;
}

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

	std::cout << "Starting SDL Application..." << std::endl;
	SDL_Event e;
	SDL_Renderer *ren = nullptr;
	SDL_Window *win = nullptr;

	Initialise(&ren,&win);

	int board_width;
	int board_height;
	SDL_Texture *squareTex = IMG_LoadTexture(ren, "../img/pong_board.png");
	SDL_QueryTexture(squareTex, NULL, NULL, &board_width, &board_height);

	SDL_Color whiteColor = {255, 255, 255};
	SDL_Surface *fpsCounter;

	// Define Players
	player p1;
	player p2;

	// Define Ball
	ball b;
	b.x = SCREEN_WIDTH / 2;
	b.y = SCREEN_HEIGHT / 2;
	b.vx = (rand() % 2 == 0)? BALL_INIT_SPEED : -1 * BALL_INIT_SPEED;
	b.vy = -0.5f;

	p1.score = p2.score = 0;
	p1.width = p2.width = board_width;
	p1.height = p2.height = 150;
	p1.speed = p2.speed = 10;

	p1.x = board_width/2 + 10;
	p2.x = SCREEN_WIDTH - p2.width - 10 - p2.width/2;

	p1.y = SCREEN_HEIGHT/2 - p1.height/2;
	p2.y = SCREEN_HEIGHT/2 - p2.height/2;

	std::cout << "Starting Game Loop" << std::endl;

	uint prevTime = SDL_GetTicks();
	bool quit = false;
	int frames = 0;
	float fps;
	char buffer[512];
	const Uint8 *keystates = SDL_GetKeyboardState(NULL);

	while(!quit) {

		// FPS Calculation
		++frames;
		uint currTime = SDL_GetTicks();
		float elapsed = (currTime - prevTime);

		if(elapsed > 100) {
			fps = round(frames / (elapsed / 1000.0));
			frames = 0;
			prevTime = currTime;
		}

		while(SDL_PollEvent(&e)) {
			if(e.type == SDL_QUIT)  quit = true;
			if(e.type == SDL_KEYDOWN) {
				switch(e.key.keysym.scancode) {
					case SDL_SCANCODE_ESCAPE:
						quit = true;
						break;
				}
			}
		}

		// Player Movement
		if(keystates[SDL_SCANCODE_UP])
			p1.y -= p1.speed;
		if(keystates[SDL_SCANCODE_DOWN])
			p1.y += p1.speed;

		// Basic AI
		if(b.y < p2.y + p2.height/2) {
			p2.y -= p2.speed;
		}
		if(b.y > p2.y + p2.height/2) {
			p2.y += p2.speed;
		}

		// Update Ball coordinates
		b.x += b.vx;
		b.y += b.vy;

		// Boundary Collision
		if(b.y < 0) {
			b.y = 0;
			b.vy *= -1;
		}
		if(b.y >= SCREEN_HEIGHT) {
			b.y = SCREEN_HEIGHT - 1;
			b.vy *= -1;
		}

		if(b.x < 0) {
			p2.score += 1;
			b.x = p1.x + p1.width;
			b.y = p1.y + p1.height/2;
			b.vx = BALL_INIT_SPEED;
		}
		if(b.x >= SCREEN_WIDTH) {
			p1.score += 1;
			b.x = p2.x;
			b.y = p2.y + p2.height/2;
			b.vx = -1 * BALL_INIT_SPEED;
		}

		if(p1.y < 0) p1.y = 0;
		if(p1.y + p1.height > SCREEN_HEIGHT) p1.y = SCREEN_HEIGHT - p1.height;
		if(p2.y < 0) p2.y = 0;
		if(p2.y + p2.height > SCREEN_HEIGHT) p2.y = SCREEN_HEIGHT - p2.height;

		// Player Collision
		if(b.x > p1.x && b.x < p1.x + p1.width && b.y > p1.y && b.y < p1.y + p1.height) {
			b.x = p1.x + p1.width;

			float angle = calc_angle(p1.y, b.y, p1.height);
			b.vx = BALL_INIT_SPEED * cos(angle);
			b.vy = BALL_INIT_SPEED * -1 * sin(angle);
		}
		if(b.x > p2.x && b.x < p2.x + p2.width && b.y > p2.y && b.y < p2.y + p2.height) {
			b.x = p2.x;

			float angle = calc_angle(p2.y, b.y, p2.height);
			b.vx = -1 * BALL_INIT_SPEED * cos(angle);
			b.vy = BALL_INIT_SPEED * -1 * sin(angle);
		}

		SDL_RenderClear(ren);

		renderTexture(squareTex, ren, p1.x, p1.y, p1.width, p1.height);
		renderTexture(squareTex, ren, p2.x, p2.y, p1.width, p1.height);

		// Draw the center line
		renderTexture(squareTex, ren, SCREEN_WIDTH/2 - CENTER_WIDTH/2, 0, CENTER_WIDTH, SCREEN_HEIGHT);

		// Draw the Ball
		renderTexture(squareTex, ren, b.x - BALL_WIDTH/2, b.y - BALL_HEIGHT/2, BALL_WIDTH, BALL_HEIGHT);

		// Display the score
		sprintf(buffer, "%d", p1.score);
		SDL_Texture *p1score = renderText(buffer, "../fonts/sample.ttf", whiteColor, 40, ren);
		sprintf(buffer, "%d", p2.score);
		SDL_Texture *p2score = renderText(buffer, "../fonts/sample.ttf", whiteColor, 40, ren);

		int width;
		SDL_QueryTexture(p1score, NULL, NULL, &width, NULL);

		renderTexture(p1score, ren, SCREEN_WIDTH/2 - width - 10, 10);
		renderTexture(p2score, ren, SCREEN_WIDTH/2 + 10, 10);

		SDL_DestroyTexture(p1score);
		SDL_DestroyTexture(p2score);

		// Extremely ineffecient way of displaying text
		sprintf(buffer, "%.0f", fps);
		SDL_Texture *fpsCounter = renderText(buffer, "../fonts/sample.ttf", whiteColor, 20, ren);
		renderTexture(fpsCounter, ren, SCREEN_WIDTH - 20, 0);
		SDL_DestroyTexture(fpsCounter);

		SDL_RenderPresent(ren);
	}

	SDL_DestroyTexture(squareTex);
	Cleanup(&ren, &win);
	return 0;
}

 void Initialise(SDL_Renderer **ren, SDL_Window **win) {
		if(SDL_Init(SDL_INIT_EVERYTHING) == -1)
			sdl_bomb("Failed to Initialise SDL");

	 	 *win = SDL_CreateWindow(
	 			"SDL Pong by Michael Aquilina",
	 			SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED,
	 			SCREEN_WIDTH, SCREEN_HEIGHT,
	 			SDL_WINDOW_SHOWN
	 	);
	 	if(*win == nullptr)
	 		sdl_bomb("Failed to create SDL Window");

	 	*ren = SDL_CreateRenderer(*win, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC);
	 	if(*ren == nullptr)
	 		sdl_bomb("Failed to create SDL Renderer");

	 	const int flags = IMG_INIT_PNG | IMG_INIT_JPG;
		if(IMG_Init(flags) !=flags)
			sdl_bomb("Failed to load the Image loading extensions");

		if(TTF_Init() != 0)
			sdl_bomb("Failed to load TTF extension");
 }

 void Cleanup(SDL_Renderer **ren, SDL_Window **win) {
		SDL_DestroyRenderer(*ren);
		SDL_DestroyWindow(*win);

		TTF_Quit();
		IMG_Quit();
		SDL_Quit();
 }
<commit_msg>Improve change of y direction on collision<commit_after>#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include <math.h>

#include <SDL2/SDL.h>
#include <SDL2/SDL_image.h>
#include <SDL2/SDL_ttf.h>

#include "pong.hpp"
#include "util.hpp"

typedef struct {
	float x;
	float y;
	float vx;
	float vy;
} ball;

typedef struct {
	int x;
	int y;
	int width;
	int height;
	int score;
	int speed;
} player;

float calc_angle(float y1, float y2, int height) {
	float rely = y1 + height/2 - y2;
	rely /= height/2.0;   // Normalise
	return rely * MAX_ANGLE;
}

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

	std::cout << "Starting SDL Application..." << std::endl;
	SDL_Event e;
	SDL_Renderer *ren = nullptr;
	SDL_Window *win = nullptr;

	Initialise(&ren,&win);

	int board_width;
	int board_height;
	SDL_Texture *squareTex = IMG_LoadTexture(ren, "../img/pong_board.png");
	SDL_QueryTexture(squareTex, NULL, NULL, &board_width, &board_height);

	SDL_Color whiteColor = {255, 255, 255};
	SDL_Surface *fpsCounter;

	// Define Players
	player p1;
	player p2;

	// Define Ball
	ball b;
	b.x = SCREEN_WIDTH / 2;
	b.y = SCREEN_HEIGHT / 2;
	b.vx = (rand() % 2 == 0)? BALL_INIT_SPEED : -1 * BALL_INIT_SPEED;
	b.vy = -0.5f;

	p1.score = p2.score = 0;
	p1.width = p2.width = board_width;
	p1.height = p2.height = 150;
	p1.speed = p2.speed = 10;

	p1.x = board_width/2 + 10;
	p2.x = SCREEN_WIDTH - p2.width - 10 - p2.width/2;

	p1.y = SCREEN_HEIGHT/2 - p1.height/2;
	p2.y = SCREEN_HEIGHT/2 - p2.height/2;

	std::cout << "Starting Game Loop" << std::endl;

	uint prevTime = SDL_GetTicks();
	bool quit = false;
	int frames = 0;
	float fps;
	char buffer[512];
	const Uint8 *keystates = SDL_GetKeyboardState(NULL);

	while(!quit) {

		// FPS Calculation
		++frames;
		uint currTime = SDL_GetTicks();
		float elapsed = (currTime - prevTime);

		if(elapsed > 100) {
			fps = round(frames / (elapsed / 1000.0));
			frames = 0;
			prevTime = currTime;
		}

		while(SDL_PollEvent(&e)) {
			if(e.type == SDL_QUIT)  quit = true;
			if(e.type == SDL_KEYDOWN) {
				switch(e.key.keysym.scancode) {
					case SDL_SCANCODE_ESCAPE:
						quit = true;
						break;
				}
			}
		}

		// Player Movement
		if(keystates[SDL_SCANCODE_UP])
			p1.y -= p1.speed;
		if(keystates[SDL_SCANCODE_DOWN])
			p1.y += p1.speed;

		// Basic AI
		if(b.y < p2.y + p2.height/2) {
			p2.y -= p2.speed;
		}
		if(b.y > p2.y + p2.height/2) {
			p2.y += p2.speed;
		}

		// Update Ball coordinates
		b.x += b.vx;
		b.y += b.vy;

		// Boundary Collision
		if(b.y < 0) {
			b.y = 0;
			b.vy *= -1;
		}
		if(b.y >= SCREEN_HEIGHT) {
			b.y = SCREEN_HEIGHT - 1;
			b.vy *= -1;
		}

		if(b.x < 0) {
			p2.score += 1;
			b.x = p1.x + p1.width;
			b.y = p1.y + p1.height/2;
			b.vx = BALL_INIT_SPEED;
		}
		if(b.x >= SCREEN_WIDTH) {
			p1.score += 1;
			b.x = p2.x;
			b.y = p2.y + p2.height/2;
			b.vx = -1 * BALL_INIT_SPEED;
		}

		if(p1.y < 0) p1.y = 0;
		if(p1.y + p1.height > SCREEN_HEIGHT) p1.y = SCREEN_HEIGHT - p1.height;
		if(p2.y < 0) p2.y = 0;
		if(p2.y + p2.height > SCREEN_HEIGHT) p2.y = SCREEN_HEIGHT - p2.height;

		// Player Collision
		if(b.x > p1.x && b.x < p1.x + p1.width && b.y > p1.y && b.y < p1.y + p1.height) {
			b.x = p1.x + p1.width;

			float angle = calc_angle(p1.y, b.y, p1.height);
			b.vx = BALL_INIT_SPEED * cos(angle);
			b.vy = ((b.vy>0)? -1 : 1) * BALL_INIT_SPEED * sin(angle);
		}
		if(b.x > p2.x && b.x < p2.x + p2.width && b.y > p2.y && b.y < p2.y + p2.height) {
			b.x = p2.x;

			float angle = calc_angle(p2.y, b.y, p2.height);
			b.vx = -1 * BALL_INIT_SPEED * cos(angle);
			b.vy = ((b.vy>0)? -1 : 1) * BALL_INIT_SPEED * sin(angle);
		}

		SDL_RenderClear(ren);

		renderTexture(squareTex, ren, p1.x, p1.y, p1.width, p1.height);
		renderTexture(squareTex, ren, p2.x, p2.y, p1.width, p1.height);

		// Draw the center line
		renderTexture(squareTex, ren, SCREEN_WIDTH/2 - CENTER_WIDTH/2, 0, CENTER_WIDTH, SCREEN_HEIGHT);

		// Draw the Ball
		renderTexture(squareTex, ren, b.x - BALL_WIDTH/2, b.y - BALL_HEIGHT/2, BALL_WIDTH, BALL_HEIGHT);

		// Display the score
		sprintf(buffer, "%d", p1.score);
		SDL_Texture *p1score = renderText(buffer, "../fonts/sample.ttf", whiteColor, 40, ren);
		sprintf(buffer, "%d", p2.score);
		SDL_Texture *p2score = renderText(buffer, "../fonts/sample.ttf", whiteColor, 40, ren);

		int width;
		SDL_QueryTexture(p1score, NULL, NULL, &width, NULL);

		renderTexture(p1score, ren, SCREEN_WIDTH/2 - width - 10, 10);
		renderTexture(p2score, ren, SCREEN_WIDTH/2 + 10, 10);

		SDL_DestroyTexture(p1score);
		SDL_DestroyTexture(p2score);

		// Extremely ineffecient way of displaying text
		sprintf(buffer, "%.0f", fps);
		SDL_Texture *fpsCounter = renderText(buffer, "../fonts/sample.ttf", whiteColor, 20, ren);
		renderTexture(fpsCounter, ren, SCREEN_WIDTH - 20, 0);
		SDL_DestroyTexture(fpsCounter);

		SDL_RenderPresent(ren);
	}

	SDL_DestroyTexture(squareTex);
	Cleanup(&ren, &win);
	return 0;
}

 void Initialise(SDL_Renderer **ren, SDL_Window **win) {
		if(SDL_Init(SDL_INIT_EVERYTHING) == -1)
			sdl_bomb("Failed to Initialise SDL");

	 	 *win = SDL_CreateWindow(
	 			"SDL Pong by Michael Aquilina",
	 			SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED,
	 			SCREEN_WIDTH, SCREEN_HEIGHT,
	 			SDL_WINDOW_SHOWN
	 	);
	 	if(*win == nullptr)
	 		sdl_bomb("Failed to create SDL Window");

	 	*ren = SDL_CreateRenderer(*win, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC);
	 	if(*ren == nullptr)
	 		sdl_bomb("Failed to create SDL Renderer");

	 	const int flags = IMG_INIT_PNG | IMG_INIT_JPG;
		if(IMG_Init(flags) !=flags)
			sdl_bomb("Failed to load the Image loading extensions");

		if(TTF_Init() != 0)
			sdl_bomb("Failed to load TTF extension");
 }

 void Cleanup(SDL_Renderer **ren, SDL_Window **win) {
		SDL_DestroyRenderer(*ren);
		SDL_DestroyWindow(*win);

		TTF_Quit();
		IMG_Quit();
		SDL_Quit();
 }
<|endoftext|>


<commit_before>// Copyright (c) 2012 libmv authors.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.

#include <cstdio>

#include "libmv/logging/logging.h"
#include "libmv/simple_pipeline/modal_solver.h"
#include "libmv/simple_pipeline/rigid_registration.h"

#ifdef _MSC_VER
#  define snprintf _snprintf
#endif

namespace libmv {

static void ProjectMarkerOnSphere(Marker &marker, Vec3 &X) {
  X(0) = marker.x;
  X(1) = marker.y;
  X(2) = 1.0;

  X *= 5.0 / X.norm();
}

static void ModalSolverLogProress(ProgressUpdateCallback *update_callback,
    double progress)
{
  if (update_callback) {
    char message[256];

    snprintf(message, sizeof(message), "Solving progress %d%%", (int)(progress * 100));

    update_callback->invoke(progress, message);
  }
}

void ModalSolver(Tracks &tracks,
                 EuclideanReconstruction *reconstruction,
                 ProgressUpdateCallback *update_callback) {
  int max_image = tracks.MaxImage();
  int max_track = tracks.MaxTrack();

  LG << "Max image: " << max_image;
  LG << "Max track: " << max_track;

  Mat3 R = Mat3::Identity();

  for (int image = 0; image <= max_image; ++image) {
    vector<Marker> all_markers = tracks.MarkersInImage(image);

    ModalSolverLogProress(update_callback, (float) image / max_image);

    // Skip empty frames without doing anything
    if (all_markers.size() == 0) {
      LG << "Skipping frame: " << image;
      continue;
    }

    vector<Vec3> points, reference_points;

    // Cnstruct pairs of markers from current and previous image,
    // to reproject them and find rigid transformation between
    // previous and current image
    for (int track = 0; track <= max_track; ++track) {
      EuclideanPoint *point = reconstruction->PointForTrack(track);

      if (point) {
        Marker marker = tracks.MarkerInImageForTrack(image, track);

        if (marker.image == image) {
          Vec3 X;

          LG << "Use track " << track << " for rigid registration between image " <<
            image - 1 << " and " << image;

          ProjectMarkerOnSphere(marker, X);

          points.push_back(R * point->X);
          reference_points.push_back(X);
        }
      }
    }

    if (points.size()) {
      Mat3 dR = Mat3::Identity();

      // Find rigid delta transformation from previous image to current image
      RigidRegistration(reference_points, points, dR);

      R *= dR;
    }

    reconstruction->InsertCamera(image, R, Vec3::Zero());

    // Review if there's new tracks for which position might be reconstructed
    for (int track = 0; track <= max_track; ++track) {
      if (!reconstruction->PointForTrack(track)) {
        Marker marker = tracks.MarkerInImageForTrack(image, track);

        if (marker.image == image) {
          // New track appeared on this image, project it's position onto sphere

          LG << "Projecting track " << track << " at image " << image;

          Vec3 X;
          ProjectMarkerOnSphere(marker, X);
          reconstruction->InsertPoint(track, R.inverse() * X);
        }
      }
    }
  }
}

}  // namespace libmv
<commit_msg>Modal solver: Detect rigid transformation between initial frame and current instead of detecting it between two neighbour frames.<commit_after>// Copyright (c) 2012 libmv authors.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.

#include <cstdio>

#include "libmv/logging/logging.h"
#include "libmv/simple_pipeline/modal_solver.h"
#include "libmv/simple_pipeline/rigid_registration.h"

#ifdef _MSC_VER
#  define snprintf _snprintf
#endif

namespace libmv {

static void ProjectMarkerOnSphere(Marker &marker, Vec3 &X) {
  X(0) = marker.x;
  X(1) = marker.y;
  X(2) = 1.0;

  X *= 5.0 / X.norm();
}

static void ModalSolverLogProress(ProgressUpdateCallback *update_callback,
    double progress)
{
  if (update_callback) {
    char message[256];

    snprintf(message, sizeof(message), "Solving progress %d%%", (int)(progress * 100));

    update_callback->invoke(progress, message);
  }
}

void ModalSolver(Tracks &tracks,
                 EuclideanReconstruction *reconstruction,
                 ProgressUpdateCallback *update_callback) {
  int max_image = tracks.MaxImage();
  int max_track = tracks.MaxTrack();

  LG << "Max image: " << max_image;
  LG << "Max track: " << max_track;

  Mat3 R = Mat3::Identity();

  for (int image = 0; image <= max_image; ++image) {
    vector<Marker> all_markers = tracks.MarkersInImage(image);

    ModalSolverLogProress(update_callback, (float) image / max_image);

    // Skip empty frames without doing anything
    if (all_markers.size() == 0) {
      LG << "Skipping frame: " << image;
      continue;
    }

    vector<Vec3> points, reference_points;

    // Cnstruct pairs of markers from current and previous image,
    // to reproject them and find rigid transformation between
    // previous and current image
    for (int track = 0; track <= max_track; ++track) {
      EuclideanPoint *point = reconstruction->PointForTrack(track);

      if (point) {
        Marker marker = tracks.MarkerInImageForTrack(image, track);

        if (marker.image == image) {
          Vec3 X;

          LG << "Use track " << track << " for rigid registration between image " <<
            image - 1 << " and " << image;

          ProjectMarkerOnSphere(marker, X);

          points.push_back(point->X);
          reference_points.push_back(X);
        }
      }
    }

    if (points.size()) {
      // Find rigid delta transformation to current image
      RigidRegistration(reference_points, points, R);
    }

    reconstruction->InsertCamera(image, R, Vec3::Zero());

    // Review if there's new tracks for which position might be reconstructed
    for (int track = 0; track <= max_track; ++track) {
      if (!reconstruction->PointForTrack(track)) {
        Marker marker = tracks.MarkerInImageForTrack(image, track);

        if (marker.image == image) {
          // New track appeared on this image, project it's position onto sphere

          LG << "Projecting track " << track << " at image " << image;

          Vec3 X;
          ProjectMarkerOnSphere(marker, X);
          reconstruction->InsertPoint(track, R.inverse() * X);
        }
      }
    }
  }
}

}  // namespace libmv
<|endoftext|>


<commit_before>#include "InitState.hpp"

const int rd::InitState::LOGIN_SUCCESSFUL = 1;

rd::InitState::InitState(rd::RdNetworkManager *networkManager, rd::RdImageManager *imageManager,
                         rd::RdInputManager *inputManager, rd::RdMentalMap *mentalMap,
                         rd::RdRobotManager *robotManager, AudioManager *audioManager) :
    ManagerHub(networkManager, imageManager, inputManager, mentalMap, robotManager, audioManager)
{
    state_id = "InitState";
    login = false;
    logged_in = false;
}

rd::InitState::~InitState()
{

}

bool rd::InitState::setup()
{
    //-- Show Robot Devastation start screen:
    if( ! screen.init() )
        return false;

    screen.show();

    //-- Start Robot Devastation music theme:
    audioManager->start();
    audioManager->play("RD_THEME", -1);

    //-- Wait for input (set listener):
    inputManager->addInputEventListener(this);
    inputManager->start();

    //-- Setup network manager
    networkManager->addNetworkEventListener(mentalMap);
    mentalMap->addMentalMapEventListener((RdYarpNetworkManager *)networkManager);
    if( ! networkManager->start() )
        return false;

    return true;
}

bool rd::InitState::loop()
{
    if (login)
    {
        //-- Log in
        networkManager->login();
        if( ! robotManager->connect() )
            return false;
        robotManager->setEnabled(false);
        imageManager->start();
        logged_in = true;
    }

    return true;
}

bool rd::InitState::cleanup()
{
    RD_DEBUG("Cleanup!!\n");
    audioManager->stopMusic();
    inputManager->removeInputEventListeners();
    screen.cleanup();

    return true;
}

int rd::InitState::evaluateConditions()
{
    if (logged_in)
        return LOGIN_SUCCESSFUL;

    return -1;
}

bool rd::InitState::onKeyDown(rd::RdKey k)
{
    return true;
}

bool rd::InitState::onKeyUp(rd::RdKey k)
{
    if (k.getValue() == RdKey::KEY_ENTER)
    {
        RD_DEBUG("Enter was pressed!\n");
        login = true;
    }
}
<commit_msg>InitState check if imageManager->start() fails, #65<commit_after>#include "InitState.hpp"

const int rd::InitState::LOGIN_SUCCESSFUL = 1;

rd::InitState::InitState(rd::RdNetworkManager *networkManager, rd::RdImageManager *imageManager,
                         rd::RdInputManager *inputManager, rd::RdMentalMap *mentalMap,
                         rd::RdRobotManager *robotManager, AudioManager *audioManager) :
    ManagerHub(networkManager, imageManager, inputManager, mentalMap, robotManager, audioManager)
{
    state_id = "InitState";
    login = false;
    logged_in = false;
}

rd::InitState::~InitState()
{

}

bool rd::InitState::setup()
{
    //-- Show Robot Devastation start screen:
    if( ! screen.init() )
        return false;

    screen.show();

    //-- Start Robot Devastation music theme:
    audioManager->start();
    audioManager->play("RD_THEME", -1);

    //-- Wait for input (set listener):
    inputManager->addInputEventListener(this);
    inputManager->start();

    //-- Setup network manager
    networkManager->addNetworkEventListener(mentalMap);
    mentalMap->addMentalMapEventListener((RdYarpNetworkManager *)networkManager);
    if( ! networkManager->start() )
        return false;

    return true;
}

bool rd::InitState::loop()
{
    if (login)
    {
        //-- Log in
        networkManager->login();
        if( ! robotManager->connect() )
            return false;
        robotManager->setEnabled(false);
        if( ! imageManager->start() )
            return false;
        logged_in = true;
    }

    return true;
}

bool rd::InitState::cleanup()
{
    RD_DEBUG("Cleanup!!\n");
    audioManager->stopMusic();
    inputManager->removeInputEventListeners();
    screen.cleanup();

    return true;
}

int rd::InitState::evaluateConditions()
{
    if (logged_in)
        return LOGIN_SUCCESSFUL;

    return -1;
}

bool rd::InitState::onKeyDown(rd::RdKey k)
{
    return true;
}

bool rd::InitState::onKeyUp(rd::RdKey k)
{
    if (k.getValue() == RdKey::KEY_ENTER)
    {
        RD_DEBUG("Enter was pressed!\n");
        login = true;
    }
}
<|endoftext|>


<commit_before>/* This file is part of Strigi Desktop Search
 *
 * Copyright (C) 2006 Jos van den Oever <jos@vandenoever.info>
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Library General Public
 * License as published by the Free Software Foundation; either
 * version 2 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Library General Public License for more details.
 *
 * You should have received a copy of the GNU Library General Public License
 * along with this library; see the file COPYING.LIB.  If not, write to
 * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
 * Boston, MA 02110-1301, USA.
 */

#ifdef HAVE_CONFIG_H
# include <config.h>
#endif

#include "cluceneindexmanager.h"
#include <strigi/strigiconfig.h>
#include <CLucene.h>
#include <CLucene/store/RAMDirectory.h>
#include "cluceneindexwriter.h"
#include "cluceneindexreader.h"
#include "indexplugin.h"
#include <iostream>
#include <sys/types.h>
#include <sys/stat.h>
#include <time.h>
#include "timeofday.h"
#include "stgdirent.h" //our dirent compatibility header... uses native if available

using namespace std;

/* define and export the index factory */
REGISTER_STRIGI_INDEXMANAGER(CLuceneIndexManager)

using namespace lucene::index;
using lucene::analysis::standard::StandardAnalyzer;
using lucene::store::FSDirectory;

Strigi::IndexManager*
createCLuceneIndexManager(const char* path) {
    return new CLuceneIndexManager(path);
}

int CLuceneIndexManager::numberOfManagers = 0;

CLuceneIndexManager::CLuceneIndexManager(const std::string& path)
        {//: bitsets(this) {
    ++numberOfManagers;
    dbdir = path;
    indexwriter = 0;
    writer = new CLuceneIndexWriter(this);
    analyzer = new StandardAnalyzer();
    if (path == ":memory:") {
        ramdirectory = new lucene::store::RAMDirectory();
    } else {
        ramdirectory = 0;
    }
    gettimeofday(&mtime, 0);

    //remove any old segments lying around from crashes, etc
    //writer->cleanUp();
    // make sure there's at least an index
    openWriter();
}
CLuceneIndexManager::~CLuceneIndexManager() {
    // close the writer and analyzer
    delete writer;
    std::map<STRIGI_THREAD_TYPE, CLuceneIndexReader*>::iterator r;
    for (r = readers.begin(); r != readers.end(); ++r) {
        delete r->second;
        r->second = 0;
    }
    closeWriter();
    delete ramdirectory;
    delete analyzer;
    if (--numberOfManagers == 0) {
// temporarily commented out because of problem with clucene
//        _lucene_shutdown();
    }
}
Strigi::IndexReader*
CLuceneIndexManager::indexReader() {
    return luceneReader();
}
CLuceneIndexReader*
CLuceneIndexManager::luceneReader() {
    // TODO check if we should update/reopen the reader
    STRIGI_THREAD_TYPE self = STRIGI_THREAD_SELF();
    CLuceneIndexReader* r;
    lock.lock();
    r = readers[self];
    lock.unlock();
    if (r == 0) {
        r = new CLuceneIndexReader(this, dbdir);
        lock.lock();
        readers[self] = r;
        lock.unlock();
    }
    return r;
}
Strigi::IndexWriter*
CLuceneIndexManager::indexWriter() {
    return writer;
}
IndexWriter*
CLuceneIndexManager::refWriter() {
    writelock.lock();
    if (indexwriter == 0) {
        openWriter();
    }
    return indexwriter;
}
void
CLuceneIndexManager::derefWriter() {
    writelock.unlock();
}
void
CLuceneIndexManager::openWriter(bool truncate) {
    try {
        if (ramdirectory) {
            indexwriter = new IndexWriter(ramdirectory, analyzer, true);
        } else if (!truncate && IndexReader::indexExists(dbdir.c_str())) {
            if (IndexReader::isLocked(dbdir.c_str())) {
                IndexReader::unlock(dbdir.c_str());
            }
            indexwriter = new IndexWriter(dbdir.c_str(), analyzer, false);
        } else {
            indexwriter = new IndexWriter(dbdir.c_str(), analyzer, true);
        }
    } catch (CLuceneError& err) {
        fprintf(stderr, "could not create writer: %s\n", err.what());
        indexwriter = 0;
    }
}
void
CLuceneIndexManager::closeWriter() {
    refWriter();
    if (indexwriter == 0) {
        derefWriter();
        return;
    }
    // update the timestamp on the index, so that the readers will reopen
    try {
        indexwriter->close();
        delete indexwriter;
    } catch (CLuceneError& err) {
        printf("could not close writer: %s\n", err.what());
    }
    indexwriter = 0;
    // clear the cache
    //bitsets.clear();
    derefWriter();
    setIndexMTime();
}
int64_t
CLuceneIndexManager::indexSize() {
    // sum the sizes of the files in the index
    // loop over directory entries
    DIR* dir = opendir(dbdir.c_str());
    if (dir == 0) {
        fprintf(stderr, "could not open index directory %s (%s)\n", dbdir.c_str(), strerror(errno));
        return -1;
    }
    struct dirent* e = readdir(dir);
    int64_t size = 0;
    while (e != 0) {
        string filename = dbdir+'/'+e->d_name;
        struct stat s;
        int r = stat(filename.c_str(), &s);
        if (r == 0) {
            if ( S_ISREG(s.st_mode)) {
                size += s.st_size;
            }
        } else {
            fprintf(stderr, "could not open file %s (%s)\n", filename.c_str(), strerror(errno));
        }
        e = readdir(dir);
    }
    closedir(dir);
    return size;
}
void
CLuceneIndexManager::deleteIndex() {
    closeWriter();
    setIndexMTime();
    openWriter(true);
}
struct timeval
CLuceneIndexManager::indexMTime() {
    struct timeval t;
    lock.lock();
    t = mtime;
    lock.unlock();
    return t;
}
void
CLuceneIndexManager::setIndexMTime() {
    lock.lock();
    gettimeofday(&mtime, 0);
    lock.unlock();
}

<commit_msg>Do not recreate index in RAMDirectory every time.<commit_after>/* This file is part of Strigi Desktop Search
 *
 * Copyright (C) 2006 Jos van den Oever <jos@vandenoever.info>
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Library General Public
 * License as published by the Free Software Foundation; either
 * version 2 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Library General Public License for more details.
 *
 * You should have received a copy of the GNU Library General Public License
 * along with this library; see the file COPYING.LIB.  If not, write to
 * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
 * Boston, MA 02110-1301, USA.
 */

#ifdef HAVE_CONFIG_H
# include <config.h>
#endif

#include "cluceneindexmanager.h"
#include <strigi/strigiconfig.h>
#include <CLucene.h>
#include <CLucene/store/RAMDirectory.h>
#include "cluceneindexwriter.h"
#include "cluceneindexreader.h"
#include "indexplugin.h"
#include <iostream>
#include <sys/types.h>
#include <sys/stat.h>
#include <time.h>
#include "timeofday.h"
#include "stgdirent.h" //our dirent compatibility header... uses native if available

using namespace std;

/* define and export the index factory */
REGISTER_STRIGI_INDEXMANAGER(CLuceneIndexManager)

using namespace lucene::index;
using lucene::analysis::standard::StandardAnalyzer;
using lucene::store::FSDirectory;

Strigi::IndexManager*
createCLuceneIndexManager(const char* path) {
    return new CLuceneIndexManager(path);
}

int CLuceneIndexManager::numberOfManagers = 0;

CLuceneIndexManager::CLuceneIndexManager(const std::string& path)
        {//: bitsets(this) {
    ++numberOfManagers;
    dbdir = path;
    indexwriter = 0;
    writer = new CLuceneIndexWriter(this);
    analyzer = new StandardAnalyzer();
    if (path == ":memory:") {
        ramdirectory = new lucene::store::RAMDirectory();
    } else {
        ramdirectory = 0;
    }
    gettimeofday(&mtime, 0);

    //remove any old segments lying around from crashes, etc
    //writer->cleanUp();
    // make sure there's at least an index
    openWriter();
}
CLuceneIndexManager::~CLuceneIndexManager() {
    // close the writer and analyzer
    delete writer;
    std::map<STRIGI_THREAD_TYPE, CLuceneIndexReader*>::iterator r;
    for (r = readers.begin(); r != readers.end(); ++r) {
        delete r->second;
        r->second = 0;
    }
    closeWriter();
    delete ramdirectory;
    delete analyzer;
    if (--numberOfManagers == 0) {
// temporarily commented out because of problem with clucene
//        _lucene_shutdown();
    }
}
Strigi::IndexReader*
CLuceneIndexManager::indexReader() {
    return luceneReader();
}
CLuceneIndexReader*
CLuceneIndexManager::luceneReader() {
    // TODO check if we should update/reopen the reader
    STRIGI_THREAD_TYPE self = STRIGI_THREAD_SELF();
    CLuceneIndexReader* r;
    lock.lock();
    r = readers[self];
    lock.unlock();
    if (r == 0) {
        r = new CLuceneIndexReader(this, dbdir);
        lock.lock();
        readers[self] = r;
        lock.unlock();
    }
    return r;
}
Strigi::IndexWriter*
CLuceneIndexManager::indexWriter() {
    return writer;
}
IndexWriter*
CLuceneIndexManager::refWriter() {
    writelock.lock();
    if (indexwriter == 0) {
        openWriter();
    }
    return indexwriter;
}
void
CLuceneIndexManager::derefWriter() {
    writelock.unlock();
}
void
CLuceneIndexManager::openWriter(bool truncate) {
    try {
        if (ramdirectory) {
            indexwriter = new IndexWriter(ramdirectory, analyzer,
                !IndexReader::indexExists(ramdirectory));
        } else if (!truncate && IndexReader::indexExists(dbdir.c_str())) {
            if (IndexReader::isLocked(dbdir.c_str())) {
                IndexReader::unlock(dbdir.c_str());
            }
            indexwriter = new IndexWriter(dbdir.c_str(), analyzer, false);
        } else {
            indexwriter = new IndexWriter(dbdir.c_str(), analyzer, true);
        }
    } catch (CLuceneError& err) {
        fprintf(stderr, "could not create writer: %s\n", err.what());
        indexwriter = 0;
    }
}
void
CLuceneIndexManager::closeWriter() {
    refWriter();
    if (indexwriter == 0) {
        derefWriter();
        return;
    }
    // update the timestamp on the index, so that the readers will reopen
    try {
        indexwriter->close();
        delete indexwriter;
    } catch (CLuceneError& err) {
        printf("could not close writer: %s\n", err.what());
    }
    indexwriter = 0;
    // clear the cache
    //bitsets.clear();
    derefWriter();
    setIndexMTime();
}
int64_t
CLuceneIndexManager::indexSize() {
    // sum the sizes of the files in the index
    // loop over directory entries
    DIR* dir = opendir(dbdir.c_str());
    if (dir == 0) {
        fprintf(stderr, "could not open index directory %s (%s)\n", dbdir.c_str(), strerror(errno));
        return -1;
    }
    struct dirent* e = readdir(dir);
    int64_t size = 0;
    while (e != 0) {
        string filename = dbdir+'/'+e->d_name;
        struct stat s;
        int r = stat(filename.c_str(), &s);
        if (r == 0) {
            if ( S_ISREG(s.st_mode)) {
                size += s.st_size;
            }
        } else {
            fprintf(stderr, "could not open file %s (%s)\n", filename.c_str(), strerror(errno));
        }
        e = readdir(dir);
    }
    closedir(dir);
    return size;
}
void
CLuceneIndexManager::deleteIndex() {
    closeWriter();
    setIndexMTime();
    openWriter(true);
}
struct timeval
CLuceneIndexManager::indexMTime() {
    struct timeval t;
    lock.lock();
    t = mtime;
    lock.unlock();
    return t;
}
void
CLuceneIndexManager::setIndexMTime() {
    lock.lock();
    gettimeofday(&mtime, 0);
    lock.unlock();
}

<|endoftext|>


<commit_before>// __BEGIN_LICENSE__
//  Copyright (c) 2009-2013, United States Government as represented by the
//  Administrator of the National Aeronautics and Space Administration. All
//  rights reserved.
//
//  The NGT platform is licensed under the Apache License, Version 2.0 (the
//  "License"); you may not use this file except in compliance with the
//  License. You may obtain a copy of the License at
//  http://www.apache.org/licenses/LICENSE-2.0
//
//  Unless required by applicable law or agreed to in writing, software
//  distributed under the License is distributed on an "AS IS" BASIS,
//  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//  See the License for the specific language governing permissions and
//  limitations under the License.
// __END_LICENSE__

#include <vw/Stereo/StereoModel.h>
#include <vw/Cartography/Datum.h>
#include <asp/Camera/OpticalBarModel.h>

#include <boost/scoped_ptr.hpp>
#include <test/Helpers.h>

using namespace vw;
using namespace asp;
using namespace asp::camera;
using namespace vw::test;
using namespace vw::camera;

TEST(OpticalBarModel, CreateCamera) {

  vw::cartography::Datum d("WGS84");
  //Vector3 llh(-122.065046, 37.419733, 250000);
  Vector3 llh(0.0, 90.0, 250000);
  Vector3 angles(0,0,0); // Looking down at the north pole

  Vector3 gcc = d.geodetic_to_cartesian(llh);

  double   pixel_size         = 7*10e-6;
  Vector2i image_size(12000, 4000);
  Vector2  center_loc_pixels(-4.3, -1.2) + image_size/2;
  double   focal_length       = 609.602/1000.0;
  double   scan_angle_radians = 70  * M_PI/180;
  double   scan_rate_radians  = 192 * M_PI/180;
  Vector3  initial_position(gcc);
  Vector3  initial_orientation(angles);
  double   velocity = 7800;
  bool     use_motion_comp = true;

  OpticalBarModel* raw_ptr = new OpticalBarModel(image_size, center_loc_pixels, pixel_size,
                                                 focal_length, scan_angle_radians, scan_rate_radians,
                                                 initial_position, initial_orientation,
                                                 velocity, use_motion_comp);

  // Basic file I/O
  OpticalBarModel cpy;
  EXPECT_NO_THROW(raw_ptr->write("test.tsai"));
  EXPECT_NO_THROW(cpy.read ("test.tsai"));

  EXPECT_VECTOR_EQ(raw_ptr->get_image_size(), cpy.get_image_size());

  typedef boost::shared_ptr<vw::camera::CameraModel> CameraModelPtr;
  CameraModelPtr cam1;
  cam1 = CameraModelPtr(raw_ptr);

  ASSERT_TRUE( cam1.get() != 0 );

  // A more accurate test is just to project out and back into the same camera
  for ( size_t i = 0; i < 3000; i += 500 ) {
    for ( size_t j = 0; j < 2400; j += 500 ) {
      Vector2 pixel(i,j);
      Vector3 center = cam1->camera_center(pixel);
      EXPECT_VECTOR_NEAR( pixel,
                          cam1->point_to_pixel( center + 2e4*cam1->pixel_to_vector(pixel) ),
                          1e-1 /*pixels*/);
    }
  }

}

<commit_msg>Make TestOpticalBar complie<commit_after>// __BEGIN_LICENSE__
//  Copyright (c) 2009-2013, United States Government as represented by the
//  Administrator of the National Aeronautics and Space Administration. All
//  rights reserved.
//
//  The NGT platform is licensed under the Apache License, Version 2.0 (the
//  "License"); you may not use this file except in compliance with the
//  License. You may obtain a copy of the License at
//  http://www.apache.org/licenses/LICENSE-2.0
//
//  Unless required by applicable law or agreed to in writing, software
//  distributed under the License is distributed on an "AS IS" BASIS,
//  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//  See the License for the specific language governing permissions and
//  limitations under the License.
// __END_LICENSE__

#include <vw/Stereo/StereoModel.h>
#include <vw/Cartography/Datum.h>
#include <asp/Camera/OpticalBarModel.h>

#include <boost/scoped_ptr.hpp>
#include <test/Helpers.h>

using namespace vw;
using namespace asp;
using namespace asp::camera;
using namespace vw::test;
using namespace vw::camera;

TEST(OpticalBarModel, CreateCamera) {

  vw::cartography::Datum d("WGS84");
  //Vector3 llh(-122.065046, 37.419733, 250000);
  Vector3 llh(0.0, 90.0, 250000);
  Vector3 angles(0,0,0); // Looking down at the north pole

  Vector3 gcc = d.geodetic_to_cartesian(llh);

  double   pixel_size         = 7*10e-6;
  Vector2i image_size(12000, 4000);
  Vector2  center_loc_pixels = Vector2(-4.3, -1.2) + image_size/2;
  double   focal_length       = 609.602/1000.0;
  double   scan_angle_radians = 70  * M_PI/180;
  double   scan_rate_radians  = 192 * M_PI/180;
  Vector3  initial_position(gcc);
  Vector3  initial_orientation(angles);
  double   velocity = 7800;
  bool     use_motion_comp = true;

  OpticalBarModel* raw_ptr = new OpticalBarModel(image_size, center_loc_pixels, pixel_size,
                                                 focal_length, scan_angle_radians, scan_rate_radians,
                                                 initial_position, initial_orientation,
                                                 velocity, use_motion_comp);

  // Basic file I/O
  OpticalBarModel cpy;
  EXPECT_NO_THROW(raw_ptr->write("test.tsai"));
  EXPECT_NO_THROW(cpy.read ("test.tsai"));

  EXPECT_VECTOR_EQ(raw_ptr->get_image_size(), cpy.get_image_size());

  typedef boost::shared_ptr<vw::camera::CameraModel> CameraModelPtr;
  CameraModelPtr cam1;
  cam1 = CameraModelPtr(raw_ptr);

  ASSERT_TRUE( cam1.get() != 0 );

  // A more accurate test is just to project out and back into the same camera
  for ( size_t i = 0; i < 3000; i += 500 ) {
    for ( size_t j = 0; j < 2400; j += 500 ) {
      Vector2 pixel(i,j);
      Vector3 center = cam1->camera_center(pixel);
      EXPECT_VECTOR_NEAR( pixel,
                          cam1->point_to_pixel( center + 2e4*cam1->pixel_to_vector(pixel) ),
                          1e-1 /*pixels*/);
    }
  }

}

<|endoftext|>