<commit_before>// Filename: binaryXml.cxx
// Created by:  drose (13Jul09)
//
////////////////////////////////////////////////////////////////////
//
// PANDA 3D SOFTWARE
// Copyright (c) Carnegie Mellon University.  All rights reserved.
//
// All use of this software is subject to the terms of the revised BSD
// license.  You should have received a copy of this license along
// with this source code in a file named "LICENSE."
//
////////////////////////////////////////////////////////////////////

#include "binaryXml.h"
#include <sstream>

static const bool debug_xml_output = true;

#define DO_BINARY_XML 1

enum NodeType {
  NT_unknown,
  NT_document,
  NT_element,
  NT_text,
};

////////////////////////////////////////////////////////////////////
//     Function: write_xml_node
//  Description: Recursively writes a node and all of its children to
//               the given stream.
////////////////////////////////////////////////////////////////////
static void
write_xml_node(ostream &out, TiXmlNode *xnode) {
  NodeType type = NT_element;
  if (xnode->ToDocument() != NULL) {
    type = NT_document;
  } else if (xnode->ToElement() != NULL) {
    type = NT_element;
  } else if (xnode->ToText() != NULL) {
    type = NT_text;
  } else {
    type = NT_unknown;
  }

  out.put((char)type);
  // We don't bother to write any data for the unknown types.
  if (type == NT_unknown) {
    return;
  }

  const string &value = xnode->ValueStr();
  size_t value_length = value.length();
  out.write((char *)&value_length, sizeof(value_length));
  out.write(value.data(), value_length);

  if (type == NT_element) {
    // Write the element attributes.
    TiXmlElement *xelement = xnode->ToElement();
    assert(xelement != NULL);
    const TiXmlAttribute *xattrib = xelement->FirstAttribute();

    while (xattrib != NULL) {
      // We have an attribute.
      out.put((char)true);

      string name = xattrib->Name();
      size_t name_length = name.length();
      out.write((char *)&name_length, sizeof(name_length));
      out.write(name.data(), name_length);

      const string &value = xattrib->ValueStr();
      size_t value_length = value.length();
      out.write((char *)&value_length, sizeof(value_length));
      out.write(value.data(), value_length);

      xattrib = xattrib->Next();
    }

    // The end of the attributes list.
    out.put((char)false);
  }

  // Now write all of the children.
  TiXmlNode *xchild = xnode->FirstChild();
  while (xchild != NULL) {
    // We have a child.
    out.put((char)true);
    write_xml_node(out, xchild);
    xchild = xchild->NextSibling();
  }

  // The end of the children list.
  out.put((char)false);
}

////////////////////////////////////////////////////////////////////
//     Function: read_xml_node
//  Description: Recursively reads a node and all of its children to
//               the given stream.  Returns the newly-allocated node.
//               The caller is responsible for eventually deleting the
//               return value.  Returns NULL on error.
////////////////////////////////////////////////////////////////////
static TiXmlNode *
read_xml_node(istream &in, char *&buffer, size_t &buffer_length) {
  NodeType type = (NodeType)in.get();
  if (type == NT_unknown) {
    return NULL;
  }

  size_t value_length;
  in.read((char *)&value_length, sizeof(value_length));
  if (in.gcount() != sizeof(value_length)) {
    return NULL;
  }

  if (value_length > buffer_length) {
    delete[] buffer;
    buffer_length = value_length;
    buffer = new char[buffer_length];
  }

  in.read(buffer, value_length);
  string value(buffer, value_length);

  TiXmlNode *xnode = NULL;
  if (type == NT_element) {
    xnode = new TiXmlElement(value);
  } else if (type == NT_document) {
    xnode = new TiXmlDocument;
  } else if (type == NT_text) {
    xnode = new TiXmlText(value);
  } else {
    assert(false);
  }

  if (type == NT_element) {
    // Read the element attributes.
    TiXmlElement *xelement = xnode->ToElement();
    assert(xelement != NULL);
    bool got_attrib = (bool)(in.get() != 0);

    while (got_attrib && in && !in.eof()) {
      // We have an attribute.
      size_t name_length;
      in.read((char *)&name_length, sizeof(name_length));
      if (in.gcount() != sizeof(name_length)) {
        delete xnode;
        return NULL;
      }

      if (name_length > buffer_length) {
        delete[] buffer;
        buffer_length = name_length;
        buffer = new char[buffer_length];
      }

      in.read(buffer, name_length);
      string name(buffer, name_length);

      size_t value_length;
      in.read((char *)&value_length, sizeof(value_length));
      if (in.gcount() != sizeof(value_length)) {
        delete xnode;
        return NULL;
      }

      if (value_length > buffer_length) {
        delete[] buffer;
        buffer_length = value_length;
        buffer = new char[buffer_length];
      }

      in.read(buffer, value_length);
      string value(buffer, value_length);

      xelement->SetAttribute(name, value);

      got_attrib = (bool)(in.get() != 0);
    }
  }

  // Now read all of the children.
  bool got_child = (bool)(in.get() != 0);

  while (got_child && in && !in.eof()) {
    // We have a child.
    TiXmlNode *xchild = read_xml_node(in, buffer, buffer_length);
    if (xchild != NULL) {
      xnode->LinkEndChild(xchild);
    }

    got_child = (bool)(in.get() != 0);
  }

  return xnode;
}

////////////////////////////////////////////////////////////////////
//     Function: write_xml
//  Description: Writes the indicated TinyXml document to the given
//               stream.
////////////////////////////////////////////////////////////////////
void
write_xml(ostream &out, TiXmlDocument *doc, ostream &logfile) {
#ifdef DO_BINARY_XML
  // Binary write.
  write_xml_node(out, doc);

#else
  // Formatted ASCII write.

  // We need a declaration to write it safely.
  TiXmlDeclaration decl("1.0", "utf-8", "");
  doc->InsertBeforeChild(doc->FirstChild(), decl);

  out << *doc;
#endif

  out << flush;

  if (debug_xml_output) {
    // Write via ostringstream, so it all goes in one operation, to
    // help out the interleaving from multiple threads.
    ostringstream logout;
    logout << "sent: " << *doc << "\n";
    logfile << logout.str() << flush;
  }
}

////////////////////////////////////////////////////////////////////
//     Function: read_xml
//  Description: Reads a TinyXml document from the given stream, and
//               returns it.  If the document is not yet available,
//               blocks until it is, or until there is an error
//               condition on the input.
//
//               The return value is NULL if there is an error, or the
//               newly-allocated document if it is successfully read.
//               If not NULL, the document has been allocated with
//               new, and should be eventually freed by the caller
//               with delete.
////////////////////////////////////////////////////////////////////
TiXmlDocument *
read_xml(istream &in, ostream &logfile) {
#if DO_BINARY_XML
  // binary read.
  size_t buffer_length = 128;
  char *buffer = new char[buffer_length];
  TiXmlNode *xnode = read_xml_node(in, buffer, buffer_length);
  delete[] buffer;
  if (xnode == NULL) {
    return NULL;
  }

  TiXmlDocument *doc = xnode->ToDocument();
  assert(doc != NULL);

#else
  // standard ASCII read.
  TiXmlDocument *doc = new TiXmlDocument;
  in >> *doc;
#endif

  if (debug_xml_output) {
    // Write via ostringstream, so it all goes in one operation, to
    // help out the interleaving from multiple threads.
    ostringstream logout;
    logout << "received: " << *doc << "\n";
    logfile << logout.str() << flush;
  }

  return doc;
}
<commit_msg>oops, debug output<commit_after>// Filename: binaryXml.cxx
// Created by:  drose (13Jul09)
//
////////////////////////////////////////////////////////////////////
//
// PANDA 3D SOFTWARE
// Copyright (c) Carnegie Mellon University.  All rights reserved.
//
// All use of this software is subject to the terms of the revised BSD
// license.  You should have received a copy of this license along
// with this source code in a file named "LICENSE."
//
////////////////////////////////////////////////////////////////////

#include "binaryXml.h"
#include <sstream>

static const bool debug_xml_output = false;

#define DO_BINARY_XML 1

enum NodeType {
  NT_unknown,
  NT_document,
  NT_element,
  NT_text,
};

////////////////////////////////////////////////////////////////////
//     Function: write_xml_node
//  Description: Recursively writes a node and all of its children to
//               the given stream.
////////////////////////////////////////////////////////////////////
static void
write_xml_node(ostream &out, TiXmlNode *xnode) {
  NodeType type = NT_element;
  if (xnode->ToDocument() != NULL) {
    type = NT_document;
  } else if (xnode->ToElement() != NULL) {
    type = NT_element;
  } else if (xnode->ToText() != NULL) {
    type = NT_text;
  } else {
    type = NT_unknown;
  }

  out.put((char)type);
  // We don't bother to write any data for the unknown types.
  if (type == NT_unknown) {
    return;
  }

  const string &value = xnode->ValueStr();
  size_t value_length = value.length();
  out.write((char *)&value_length, sizeof(value_length));
  out.write(value.data(), value_length);

  if (type == NT_element) {
    // Write the element attributes.
    TiXmlElement *xelement = xnode->ToElement();
    assert(xelement != NULL);
    const TiXmlAttribute *xattrib = xelement->FirstAttribute();

    while (xattrib != NULL) {
      // We have an attribute.
      out.put((char)true);

      string name = xattrib->Name();
      size_t name_length = name.length();
      out.write((char *)&name_length, sizeof(name_length));
      out.write(name.data(), name_length);

      const string &value = xattrib->ValueStr();
      size_t value_length = value.length();
      out.write((char *)&value_length, sizeof(value_length));
      out.write(value.data(), value_length);

      xattrib = xattrib->Next();
    }

    // The end of the attributes list.
    out.put((char)false);
  }

  // Now write all of the children.
  TiXmlNode *xchild = xnode->FirstChild();
  while (xchild != NULL) {
    // We have a child.
    out.put((char)true);
    write_xml_node(out, xchild);
    xchild = xchild->NextSibling();
  }

  // The end of the children list.
  out.put((char)false);
}

////////////////////////////////////////////////////////////////////
//     Function: read_xml_node
//  Description: Recursively reads a node and all of its children to
//               the given stream.  Returns the newly-allocated node.
//               The caller is responsible for eventually deleting the
//               return value.  Returns NULL on error.
////////////////////////////////////////////////////////////////////
static TiXmlNode *
read_xml_node(istream &in, char *&buffer, size_t &buffer_length) {
  NodeType type = (NodeType)in.get();
  if (type == NT_unknown) {
    return NULL;
  }

  size_t value_length;
  in.read((char *)&value_length, sizeof(value_length));
  if (in.gcount() != sizeof(value_length)) {
    return NULL;
  }

  if (value_length > buffer_length) {
    delete[] buffer;
    buffer_length = value_length;
    buffer = new char[buffer_length];
  }

  in.read(buffer, value_length);
  string value(buffer, value_length);

  TiXmlNode *xnode = NULL;
  if (type == NT_element) {
    xnode = new TiXmlElement(value);
  } else if (type == NT_document) {
    xnode = new TiXmlDocument;
  } else if (type == NT_text) {
    xnode = new TiXmlText(value);
  } else {
    assert(false);
  }

  if (type == NT_element) {
    // Read the element attributes.
    TiXmlElement *xelement = xnode->ToElement();
    assert(xelement != NULL);
    bool got_attrib = (bool)(in.get() != 0);

    while (got_attrib && in && !in.eof()) {
      // We have an attribute.
      size_t name_length;
      in.read((char *)&name_length, sizeof(name_length));
      if (in.gcount() != sizeof(name_length)) {
        delete xnode;
        return NULL;
      }

      if (name_length > buffer_length) {
        delete[] buffer;
        buffer_length = name_length;
        buffer = new char[buffer_length];
      }

      in.read(buffer, name_length);
      string name(buffer, name_length);

      size_t value_length;
      in.read((char *)&value_length, sizeof(value_length));
      if (in.gcount() != sizeof(value_length)) {
        delete xnode;
        return NULL;
      }

      if (value_length > buffer_length) {
        delete[] buffer;
        buffer_length = value_length;
        buffer = new char[buffer_length];
      }

      in.read(buffer, value_length);
      string value(buffer, value_length);

      xelement->SetAttribute(name, value);

      got_attrib = (bool)(in.get() != 0);
    }
  }

  // Now read all of the children.
  bool got_child = (bool)(in.get() != 0);

  while (got_child && in && !in.eof()) {
    // We have a child.
    TiXmlNode *xchild = read_xml_node(in, buffer, buffer_length);
    if (xchild != NULL) {
      xnode->LinkEndChild(xchild);
    }

    got_child = (bool)(in.get() != 0);
  }

  return xnode;
}

////////////////////////////////////////////////////////////////////
//     Function: write_xml
//  Description: Writes the indicated TinyXml document to the given
//               stream.
////////////////////////////////////////////////////////////////////
void
write_xml(ostream &out, TiXmlDocument *doc, ostream &logfile) {
#ifdef DO_BINARY_XML
  // Binary write.
  write_xml_node(out, doc);

#else
  // Formatted ASCII write.

  // We need a declaration to write it safely.
  TiXmlDeclaration decl("1.0", "utf-8", "");
  doc->InsertBeforeChild(doc->FirstChild(), decl);

  out << *doc;
#endif

  out << flush;

  if (debug_xml_output) {
    // Write via ostringstream, so it all goes in one operation, to
    // help out the interleaving from multiple threads.
    ostringstream logout;
    logout << "sent: " << *doc << "\n";
    logfile << logout.str() << flush;
  }
}

////////////////////////////////////////////////////////////////////
//     Function: read_xml
//  Description: Reads a TinyXml document from the given stream, and
//               returns it.  If the document is not yet available,
//               blocks until it is, or until there is an error
//               condition on the input.
//
//               The return value is NULL if there is an error, or the
//               newly-allocated document if it is successfully read.
//               If not NULL, the document has been allocated with
//               new, and should be eventually freed by the caller
//               with delete.
////////////////////////////////////////////////////////////////////
TiXmlDocument *
read_xml(istream &in, ostream &logfile) {
#if DO_BINARY_XML
  // binary read.
  size_t buffer_length = 128;
  char *buffer = new char[buffer_length];
  TiXmlNode *xnode = read_xml_node(in, buffer, buffer_length);
  delete[] buffer;
  if (xnode == NULL) {
    return NULL;
  }

  TiXmlDocument *doc = xnode->ToDocument();
  assert(doc != NULL);

#else
  // standard ASCII read.
  TiXmlDocument *doc = new TiXmlDocument;
  in >> *doc;
#endif

  if (debug_xml_output) {
    // Write via ostringstream, so it all goes in one operation, to
    // help out the interleaving from multiple threads.
    ostringstream logout;
    logout << "received: " << *doc << "\n";
    logfile << logout.str() << flush;
  }

  return doc;
}
<|endoftext|>


<commit_before>#include <SFML/Graphics.hpp>
#include <cmath>
#include <iostream>
int main()
{
	sf::RenderWindow okno(sf::VideoMode(400, 400), "2048", sf::Style::Close);
	sf::Clock stoper;

	sf::Texture textura;
	textura.loadFromFile("klocek.png");

	sf::Sprite obraz;
	obraz.setTexture(textura);
	while (okno.isOpen())
	{
		sf::Event event;
		while (okno.pollEvent(event))
		{
			if (event.type == sf::Event::Closed)
				okno.close();
			if (sf::Keyboard::isKeyPressed(sf::Keyboard::Right)) {
				if(obraz.getPosition().x != 300.0)
					obraz.move(100, 0);
			}
			if (sf::Keyboard::isKeyPressed(sf::Keyboard::Left)) {
				if (obraz.getPosition().x != 0.0)
					obraz.move(-100, 0);
			}
			if (sf::Keyboard::isKeyPressed(sf::Keyboard::Up)) {
				if (obraz.getPosition().y != 0.0)
					obraz.move(0, -100);
			}
			if (sf::Keyboard::isKeyPressed(sf::Keyboard::Down)) {
				if (obraz.getPosition().y != 300.0)
					obraz.move(0, 100);
			}
		}
		okno.clear(sf::Color::Green);
		okno.draw(obraz);
		okno.display();

	}
	return 0;
}<commit_msg>Working on random appearance of block<commit_after>#include <SFML/Graphics.hpp>
#include <cmath>
#include <iostream>
#include <cstdlib>
#include <vector>

int main()
{

	srand(time(NULL));

	float pozX, pozY = 0.0;
	//std::vector <float,float> currentPositions;

	sf::RenderWindow okno(sf::VideoMode(400, 400), "2048", sf::Style::Close);
	//pojedynczy klocek
	sf::Texture textura;
	textura.loadFromFile("klocek.png");

	sf::Sprite obraz;
	obraz.setTexture(textura);

	while (okno.isOpen())
	{
		sf::Event event;
		while (okno.pollEvent(event))
		{
			if (event.type == sf::Event::Closed)
				okno.close();
		}
		/*if (event.type == sf::Event::KeyPressed) {

			pozX = rand() % 4 + 0;
			pozY = rand() % 4 + 0;
			okno.draw(obraz);
			obraz.setPosition(pozX*100, pozY*100);

			currentPositions.emplace_back(pozX, pozY);
	}*/

		if (sf::Keyboard::isKeyPressed(sf::Keyboard::Right)) {
			if (obraz.getPosition().x != 300.0)
				obraz.move(0.25, 0);
		}
		if (sf::Keyboard::isKeyPressed(sf::Keyboard::Left)) {
			if (obraz.getPosition().x != 0.0)
				obraz.move(-0.25, 0);
		}
		if (sf::Keyboard::isKeyPressed(sf::Keyboard::Up)) {
			if (obraz.getPosition().y != 0.0)
				obraz.move(0, -0.25);
		}
		if (sf::Keyboard::isKeyPressed(sf::Keyboard::Down)) {
			if (obraz.getPosition().y != 300.0)
				obraz.move(0, 0.25);
		}

		okno.clear(sf::Color::Green);
		okno.draw(obraz);
		okno.display();

	}
	return 0;
}<|endoftext|>


<commit_before>#ifndef WIGWAG_SIGNAL_POLICIES_HPP
#define WIGWAG_SIGNAL_POLICIES_HPP

// Copyright (c) 2016, Dmitry Koplyarov <koplyarov.da@gmail.com>
//
// Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted,
// provided that the above copyright notice and this permission notice appear in all copies.
//
// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS.
// IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
// WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.

#include <wigwag/detail/enabler.hpp>
#include <wigwag/life_token.hpp>

#include <list>
#include <memory>
#include <mutex>
#include <vector>

#include <stdio.h>

namespace wigwag
{

	namespace exception_handling
	{
		struct rethrow
		{
			void handle_std_exception(const std::exception& ex) const { throw; }
			void handle_unknown_exception() const { throw; }
		};

		struct print_to_stderr
		{
			void handle_std_exception(const std::exception& ex) const { fprintf(stderr, "std::exception in signal handler: %s\n", ex.what()); }
			void handle_unknown_exception() const { fprintf(stderr, "Unknown exception in signal handler!\n"); }
		};
	}

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

	namespace threading
	{
		struct own_recursive_mutex
		{
			class lock_primitive
			{
			private:
				mutable std::recursive_mutex	_mutex;

			public:
				std::recursive_mutex& get_primitive() const { return _mutex; }

				void lock_connect() const { _mutex.lock(); }
				void unlock_connect() const { _mutex.unlock(); }

				void lock_invoke() const { _mutex.lock(); }
				void unlock_invoke() const { _mutex.unlock(); }
			};
		};

		struct own_mutex
		{
			class lock_primitive
			{
			private:
				mutable std::mutex		_mutex;

			public:
				std::mutex& get_primitive() const { return _mutex; }

				void lock_connect() const { _mutex.lock(); }
				void unlock_connect() const { _mutex.unlock(); }

				void lock_invoke() const
				{
					if (_mutex.try_lock())
					{
						_mutex.unlock();
						throw std::runtime_error("A nonrecursive mutex should be locked outside of signal::operator()!");

					}
				}

				void unlock_invoke() const { }
			};
		};

		struct none
		{
			class lock_primitive
			{
			public:
				void get_primitive() const { }

				void lock_connect() const { }
				void unlock_connect() const { }

				void lock_invoke() const { }
				void unlock_invoke() const { }
			};
		};
	}

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

	namespace state_populating
	{
		struct populator_only
		{
			template < typename Signature_ >
			class handler_processor
			{
				using handler_processor_func = std::function<void(const std::function<Signature_>&)>;

			private:
				handler_processor_func		_populator;

			public:
				handler_processor(handler_processor_func populator = &populator_only::handler_processor<Signature_>::empty_handler)
					: _populator(populator)
				{ }

				void populate_state(const std::function<Signature_>& handler) const { _populator(handler); }
				void withdraw_state(const std::function<Signature_>& handler) const { }

				static void empty_handler(const std::function<Signature_>&) { }
			};
		};

		struct populator_and_withdrawer
		{
			template < typename Signature_ >
			class handler_processor
			{
				using handler_processor_func = std::function<void(const std::function<Signature_>&)>;

			private:
				handler_processor_func		_populator;
				handler_processor_func		_withdrawer;

			public:
				handler_processor(handler_processor_func populator = &populator_only::handler_processor<Signature_>::empty_handler,
							handler_processor_func withdrawer = &populator_only::handler_processor<Signature_>::empty_handler)
					: _populator(populator), _withdrawer(withdrawer)
				{ }

				void populate_state(const std::function<Signature_>& handler) const { _populator(handler); }
				void withdraw_state(const std::function<Signature_>& handler) const { _withdrawer(handler); }

				static void empty_handler(const std::function<Signature_>&) { }
			};
		};

		struct none
		{
			template < typename Signature_ >
			struct handler_processor
			{
				void populate_state(const std::function<Signature_>& handler) const { }
				void withdraw_state(const std::function<Signature_>& handler) const { }
			};
		};
	}

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

	namespace handlers_stack_container
	{
		struct vector
		{
			template < typename HandlerInfo_ >
			using handlers_stack_container = std::vector<HandlerInfo_>;
		};
	}

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

	namespace life_assurance
	{
		struct life_tokens
		{
			struct life_checker
			{
				life_token::checker		checker;
				life_checker(const life_token::checker& c) : checker(c) { }
			};

			struct execution_guard
			{
				life_token::execution_guard		guard;
				execution_guard(const life_checker& c) : guard(c.checker) { }
				bool is_alive() const { return guard.is_alive(); }
			};

			class life_assurance
			{
				union life_token_storage
				{
					life_token		token;

					life_token_storage(life_token_storage&& other) noexcept
					{
						new(&token) life_token(std::move(other.token));
						other.token.~life_token();
					}

					life_token_storage() { new(&token) life_token(); }
					~life_token_storage() { }
				};

				life_token_storage		_token_storage;

			public:
				life_checker get_life_checker() const { return life_checker(_token_storage.token); }
				void release() { _token_storage.token.~life_token(); }
			};
		};

		struct none
		{
			struct life_checker
			{ };

			struct execution_guard
			{
				execution_guard(const life_checker&) { }
				bool is_alive() const { return true; }
			};

			struct life_assurance
			{
				life_checker get_life_checker() const { return life_checker(); }
				void release() { }
			};
		};
	}

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

	namespace impl_storage
	{
		struct inplace
		{
			template < typename ExceptionHandler_, typename LockPrimitive_, typename HandlerProcessor_, typename HandlersContainer_ >
			class storage : private ExceptionHandler_, private LockPrimitive_, private HandlerProcessor_, private HandlersContainer_
			{
				template< typename T_, typename... Args_ >
				using con = std::is_constructible<T_, Args_...>;

			public:
				storage() { }

#define DETAIL_WIGWAG_STORAGE_CTOR_ENABLER(...) typename std::enable_if<__VA_ARGS__, detail::enabler>::type e = detail::enabler()

				template < typename T_ > storage(T_ eh, DETAIL_WIGWAG_STORAGE_CTOR_ENABLER(con<ExceptionHandler_, T_&&>::value)) : ExceptionHandler_(std::move(eh)) { }
				template < typename T_ > storage(T_ lp, DETAIL_WIGWAG_STORAGE_CTOR_ENABLER(con<LockPrimitive_, T_&&>::value)) : LockPrimitive_(std::move(lp)) { }
				template < typename T_ > storage(T_ hp, DETAIL_WIGWAG_STORAGE_CTOR_ENABLER(con<HandlerProcessor_, T_&&>::value)) : HandlerProcessor_(std::move(hp)) { }
				template < typename T_ > storage(T_ hc, DETAIL_WIGWAG_STORAGE_CTOR_ENABLER(con<HandlersContainer_, T_&&>::value)) : HandlersContainer_(std::move(hc)) { }

				template < typename T_, typename U_ >
				storage(T_ eh, U_ lp, DETAIL_WIGWAG_STORAGE_CTOR_ENABLER(con<ExceptionHandler_, T_&&>::value && con<LockPrimitive_, U_&&>::value))
					: ExceptionHandler_(std::move(eh)), LockPrimitive_(std::move(lp))
				{ }

				template < typename T_, typename U_ >
				storage(T_ eh, U_ hp, DETAIL_WIGWAG_STORAGE_CTOR_ENABLER(con<ExceptionHandler_, T_&&>::value && con<HandlerProcessor_, U_&&>::value))
					: ExceptionHandler_(std::move(eh)), HandlerProcessor_(std::move(hp))
				{ }

				template < typename T_, typename U_ >
				storage(T_ eh, U_ hc, DETAIL_WIGWAG_STORAGE_CTOR_ENABLER(con<ExceptionHandler_, T_&&>::value && con<HandlersContainer_, U_&&>::value))
					: ExceptionHandler_(std::move(eh)), LockPrimitive_(std::move(hc))
				{ }

				template < typename T_, typename U_ >
				storage(T_ lp, U_ hp, DETAIL_WIGWAG_STORAGE_CTOR_ENABLER(con<LockPrimitive_, T_&&>::value && con<HandlerProcessor_, U_&&>::value))
					: LockPrimitive_(std::move(lp)), HandlerProcessor_(std::move(hp))
				{ }

				template < typename T_, typename U_ >
				storage(T_ lp, U_ hc, DETAIL_WIGWAG_STORAGE_CTOR_ENABLER(con<LockPrimitive_, T_&&>::value && con<HandlersContainer_, U_&&>::value))
					: LockPrimitive_(std::move(lp)), HandlersContainer_(std::move(hc))
				{ }

				template < typename T_, typename U_ >
				storage(T_ hp, U_ hc, DETAIL_WIGWAG_STORAGE_CTOR_ENABLER(con<HandlerProcessor_, T_&&>::value && con<HandlersContainer_, U_&&>::value))
					: HandlerProcessor_(std::move(hp)), HandlersContainer_(std::move(hc))
				{ }

				template < typename T_, typename U_, typename V_ >
				storage(T_ lp, U_ hp, V_ hc, DETAIL_WIGWAG_STORAGE_CTOR_ENABLER(con<LockPrimitive_, T_&&>::value && con<HandlerProcessor_, U_&&>::value && con<HandlersContainer_, V_&&>::value))
					: LockPrimitive_(std::move(lp)), HandlerProcessor_(std::move(hp)), HandlersContainer_(std::move(hc))
				{ }

				template < typename T_, typename U_, typename V_ >
				storage(T_ eh, U_ hp, V_ hc, DETAIL_WIGWAG_STORAGE_CTOR_ENABLER(con<ExceptionHandler_, T_&&>::value && con<HandlerProcessor_, U_&&>::value && con<HandlersContainer_, V_&&>::value))
					: ExceptionHandler_(std::move(eh)), HandlerProcessor_(std::move(hp)), HandlersContainer_(std::move(hc))
				{ }

				template < typename T_, typename U_, typename V_ >
				storage(T_ eh, U_ lp, V_ hc, DETAIL_WIGWAG_STORAGE_CTOR_ENABLER(con<ExceptionHandler_, T_&&>::value && con<LockPrimitive_, U_&&>::value && con<HandlersContainer_, V_&&>::value))
					: ExceptionHandler_(std::move(eh)), LockPrimitive_(std::move(lp)), HandlersContainer_(std::move(hc))
				{ }

				template < typename T_, typename U_, typename V_ >
				storage(T_ eh, U_ lp, V_ hp, DETAIL_WIGWAG_STORAGE_CTOR_ENABLER(con<ExceptionHandler_, T_&&>::value && con<LockPrimitive_, U_&&>::value && con<HandlerProcessor_, V_&&>::value))
					: ExceptionHandler_(std::move(eh)), LockPrimitive_(std::move(lp)), HandlerProcessor_(std::move(hp))
				{ }

#undef DETAIL_WIGWAG_STORAGE_CTOR_ENABLER

				storage(ExceptionHandler_ eh, LockPrimitive_ lp, HandlerProcessor_ hp, HandlersContainer_ hc) : ExceptionHandler_(std::move(eh)), LockPrimitive_(std::move(lp)), HandlerProcessor_(std::move(hp)), HandlersContainer_(std::move(hc)) { }

				HandlersContainer_& get_handlers_container() { return *this; }
				const HandlersContainer_& get_handlers_container() const { return *this; }

				const LockPrimitive_& get_lock_primitive() const { return *this; }
				const ExceptionHandler_& get_exception_handler() const { return *this; }
				const HandlerProcessor_& get_handler_processor() const { return *this; }
			};
		};

		struct shared
		{
			template < typename ExceptionHandler_, typename LockPrimitive_, typename HandlerProcessor_, typename HandlersContainer_ >
			class storage
			{
			private:
				using impl = inplace::storage<ExceptionHandler_, LockPrimitive_, HandlerProcessor_, HandlersContainer_>;

				std::shared_ptr<impl>	_impl;

			public:
				template < typename... Args_ >
				storage(Args_... args)
					: _impl(new impl(std::forward<Args_>(args)...))
				{ }

				HandlersContainer_& get_handlers_container() { return _impl->get_handlers_container(); }
				const HandlersContainer_& get_handlers_container() const { return _impl->get_handlers_container(); }

				const LockPrimitive_& get_lock_primitive() const { return _impl->get_lock_primitive(); }
				const ExceptionHandler_& get_exception_handler() const { return _impl->get_exception_handler(); }
				const HandlerProcessor_& get_handler_processor() const { return _impl->get_handler_processor(); }
			};

			template < typename ExceptionHandlingPolicy_, typename LockPrimitive_, typename HandlerProcessor_,typename HandlersContainer_ >
			using storage_ref = storage<ExceptionHandlingPolicy_, LockPrimitive_, HandlerProcessor_, HandlersContainer_>;
		};
	}

}

#endif
<commit_msg>Removed empty line<commit_after>#ifndef WIGWAG_SIGNAL_POLICIES_HPP
#define WIGWAG_SIGNAL_POLICIES_HPP

// Copyright (c) 2016, Dmitry Koplyarov <koplyarov.da@gmail.com>
//
// Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted,
// provided that the above copyright notice and this permission notice appear in all copies.
//
// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS.
// IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
// WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.

#include <wigwag/detail/enabler.hpp>
#include <wigwag/life_token.hpp>

#include <list>
#include <memory>
#include <mutex>
#include <vector>

#include <stdio.h>

namespace wigwag
{

	namespace exception_handling
	{
		struct rethrow
		{
			void handle_std_exception(const std::exception& ex) const { throw; }
			void handle_unknown_exception() const { throw; }
		};

		struct print_to_stderr
		{
			void handle_std_exception(const std::exception& ex) const { fprintf(stderr, "std::exception in signal handler: %s\n", ex.what()); }
			void handle_unknown_exception() const { fprintf(stderr, "Unknown exception in signal handler!\n"); }
		};
	}

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

	namespace threading
	{
		struct own_recursive_mutex
		{
			class lock_primitive
			{
			private:
				mutable std::recursive_mutex	_mutex;

			public:
				std::recursive_mutex& get_primitive() const { return _mutex; }

				void lock_connect() const { _mutex.lock(); }
				void unlock_connect() const { _mutex.unlock(); }

				void lock_invoke() const { _mutex.lock(); }
				void unlock_invoke() const { _mutex.unlock(); }
			};
		};

		struct own_mutex
		{
			class lock_primitive
			{
			private:
				mutable std::mutex		_mutex;

			public:
				std::mutex& get_primitive() const { return _mutex; }

				void lock_connect() const { _mutex.lock(); }
				void unlock_connect() const { _mutex.unlock(); }

				void lock_invoke() const
				{
					if (_mutex.try_lock())
					{
						_mutex.unlock();
						throw std::runtime_error("A nonrecursive mutex should be locked outside of signal::operator()!");
					}
				}

				void unlock_invoke() const { }
			};
		};

		struct none
		{
			class lock_primitive
			{
			public:
				void get_primitive() const { }

				void lock_connect() const { }
				void unlock_connect() const { }

				void lock_invoke() const { }
				void unlock_invoke() const { }
			};
		};
	}

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

	namespace state_populating
	{
		struct populator_only
		{
			template < typename Signature_ >
			class handler_processor
			{
				using handler_processor_func = std::function<void(const std::function<Signature_>&)>;

			private:
				handler_processor_func		_populator;

			public:
				handler_processor(handler_processor_func populator = &populator_only::handler_processor<Signature_>::empty_handler)
					: _populator(populator)
				{ }

				void populate_state(const std::function<Signature_>& handler) const { _populator(handler); }
				void withdraw_state(const std::function<Signature_>& handler) const { }

				static void empty_handler(const std::function<Signature_>&) { }
			};
		};

		struct populator_and_withdrawer
		{
			template < typename Signature_ >
			class handler_processor
			{
				using handler_processor_func = std::function<void(const std::function<Signature_>&)>;

			private:
				handler_processor_func		_populator;
				handler_processor_func		_withdrawer;

			public:
				handler_processor(handler_processor_func populator = &populator_only::handler_processor<Signature_>::empty_handler,
							handler_processor_func withdrawer = &populator_only::handler_processor<Signature_>::empty_handler)
					: _populator(populator), _withdrawer(withdrawer)
				{ }

				void populate_state(const std::function<Signature_>& handler) const { _populator(handler); }
				void withdraw_state(const std::function<Signature_>& handler) const { _withdrawer(handler); }

				static void empty_handler(const std::function<Signature_>&) { }
			};
		};

		struct none
		{
			template < typename Signature_ >
			struct handler_processor
			{
				void populate_state(const std::function<Signature_>& handler) const { }
				void withdraw_state(const std::function<Signature_>& handler) const { }
			};
		};
	}

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

	namespace handlers_stack_container
	{
		struct vector
		{
			template < typename HandlerInfo_ >
			using handlers_stack_container = std::vector<HandlerInfo_>;
		};
	}

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

	namespace life_assurance
	{
		struct life_tokens
		{
			struct life_checker
			{
				life_token::checker		checker;
				life_checker(const life_token::checker& c) : checker(c) { }
			};

			struct execution_guard
			{
				life_token::execution_guard		guard;
				execution_guard(const life_checker& c) : guard(c.checker) { }
				bool is_alive() const { return guard.is_alive(); }
			};

			class life_assurance
			{
				union life_token_storage
				{
					life_token		token;

					life_token_storage(life_token_storage&& other) noexcept
					{
						new(&token) life_token(std::move(other.token));
						other.token.~life_token();
					}

					life_token_storage() { new(&token) life_token(); }
					~life_token_storage() { }
				};

				life_token_storage		_token_storage;

			public:
				life_checker get_life_checker() const { return life_checker(_token_storage.token); }
				void release() { _token_storage.token.~life_token(); }
			};
		};

		struct none
		{
			struct life_checker
			{ };

			struct execution_guard
			{
				execution_guard(const life_checker&) { }
				bool is_alive() const { return true; }
			};

			struct life_assurance
			{
				life_checker get_life_checker() const { return life_checker(); }
				void release() { }
			};
		};
	}

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

	namespace impl_storage
	{
		struct inplace
		{
			template < typename ExceptionHandler_, typename LockPrimitive_, typename HandlerProcessor_, typename HandlersContainer_ >
			class storage : private ExceptionHandler_, private LockPrimitive_, private HandlerProcessor_, private HandlersContainer_
			{
				template< typename T_, typename... Args_ >
				using con = std::is_constructible<T_, Args_...>;

			public:
				storage() { }

#define DETAIL_WIGWAG_STORAGE_CTOR_ENABLER(...) typename std::enable_if<__VA_ARGS__, detail::enabler>::type e = detail::enabler()

				template < typename T_ > storage(T_ eh, DETAIL_WIGWAG_STORAGE_CTOR_ENABLER(con<ExceptionHandler_, T_&&>::value)) : ExceptionHandler_(std::move(eh)) { }
				template < typename T_ > storage(T_ lp, DETAIL_WIGWAG_STORAGE_CTOR_ENABLER(con<LockPrimitive_, T_&&>::value)) : LockPrimitive_(std::move(lp)) { }
				template < typename T_ > storage(T_ hp, DETAIL_WIGWAG_STORAGE_CTOR_ENABLER(con<HandlerProcessor_, T_&&>::value)) : HandlerProcessor_(std::move(hp)) { }
				template < typename T_ > storage(T_ hc, DETAIL_WIGWAG_STORAGE_CTOR_ENABLER(con<HandlersContainer_, T_&&>::value)) : HandlersContainer_(std::move(hc)) { }

				template < typename T_, typename U_ >
				storage(T_ eh, U_ lp, DETAIL_WIGWAG_STORAGE_CTOR_ENABLER(con<ExceptionHandler_, T_&&>::value && con<LockPrimitive_, U_&&>::value))
					: ExceptionHandler_(std::move(eh)), LockPrimitive_(std::move(lp))
				{ }

				template < typename T_, typename U_ >
				storage(T_ eh, U_ hp, DETAIL_WIGWAG_STORAGE_CTOR_ENABLER(con<ExceptionHandler_, T_&&>::value && con<HandlerProcessor_, U_&&>::value))
					: ExceptionHandler_(std::move(eh)), HandlerProcessor_(std::move(hp))
				{ }

				template < typename T_, typename U_ >
				storage(T_ eh, U_ hc, DETAIL_WIGWAG_STORAGE_CTOR_ENABLER(con<ExceptionHandler_, T_&&>::value && con<HandlersContainer_, U_&&>::value))
					: ExceptionHandler_(std::move(eh)), LockPrimitive_(std::move(hc))
				{ }

				template < typename T_, typename U_ >
				storage(T_ lp, U_ hp, DETAIL_WIGWAG_STORAGE_CTOR_ENABLER(con<LockPrimitive_, T_&&>::value && con<HandlerProcessor_, U_&&>::value))
					: LockPrimitive_(std::move(lp)), HandlerProcessor_(std::move(hp))
				{ }

				template < typename T_, typename U_ >
				storage(T_ lp, U_ hc, DETAIL_WIGWAG_STORAGE_CTOR_ENABLER(con<LockPrimitive_, T_&&>::value && con<HandlersContainer_, U_&&>::value))
					: LockPrimitive_(std::move(lp)), HandlersContainer_(std::move(hc))
				{ }

				template < typename T_, typename U_ >
				storage(T_ hp, U_ hc, DETAIL_WIGWAG_STORAGE_CTOR_ENABLER(con<HandlerProcessor_, T_&&>::value && con<HandlersContainer_, U_&&>::value))
					: HandlerProcessor_(std::move(hp)), HandlersContainer_(std::move(hc))
				{ }

				template < typename T_, typename U_, typename V_ >
				storage(T_ lp, U_ hp, V_ hc, DETAIL_WIGWAG_STORAGE_CTOR_ENABLER(con<LockPrimitive_, T_&&>::value && con<HandlerProcessor_, U_&&>::value && con<HandlersContainer_, V_&&>::value))
					: LockPrimitive_(std::move(lp)), HandlerProcessor_(std::move(hp)), HandlersContainer_(std::move(hc))
				{ }

				template < typename T_, typename U_, typename V_ >
				storage(T_ eh, U_ hp, V_ hc, DETAIL_WIGWAG_STORAGE_CTOR_ENABLER(con<ExceptionHandler_, T_&&>::value && con<HandlerProcessor_, U_&&>::value && con<HandlersContainer_, V_&&>::value))
					: ExceptionHandler_(std::move(eh)), HandlerProcessor_(std::move(hp)), HandlersContainer_(std::move(hc))
				{ }

				template < typename T_, typename U_, typename V_ >
				storage(T_ eh, U_ lp, V_ hc, DETAIL_WIGWAG_STORAGE_CTOR_ENABLER(con<ExceptionHandler_, T_&&>::value && con<LockPrimitive_, U_&&>::value && con<HandlersContainer_, V_&&>::value))
					: ExceptionHandler_(std::move(eh)), LockPrimitive_(std::move(lp)), HandlersContainer_(std::move(hc))
				{ }

				template < typename T_, typename U_, typename V_ >
				storage(T_ eh, U_ lp, V_ hp, DETAIL_WIGWAG_STORAGE_CTOR_ENABLER(con<ExceptionHandler_, T_&&>::value && con<LockPrimitive_, U_&&>::value && con<HandlerProcessor_, V_&&>::value))
					: ExceptionHandler_(std::move(eh)), LockPrimitive_(std::move(lp)), HandlerProcessor_(std::move(hp))
				{ }

#undef DETAIL_WIGWAG_STORAGE_CTOR_ENABLER

				storage(ExceptionHandler_ eh, LockPrimitive_ lp, HandlerProcessor_ hp, HandlersContainer_ hc) : ExceptionHandler_(std::move(eh)), LockPrimitive_(std::move(lp)), HandlerProcessor_(std::move(hp)), HandlersContainer_(std::move(hc)) { }

				HandlersContainer_& get_handlers_container() { return *this; }
				const HandlersContainer_& get_handlers_container() const { return *this; }

				const LockPrimitive_& get_lock_primitive() const { return *this; }
				const ExceptionHandler_& get_exception_handler() const { return *this; }
				const HandlerProcessor_& get_handler_processor() const { return *this; }
			};
		};

		struct shared
		{
			template < typename ExceptionHandler_, typename LockPrimitive_, typename HandlerProcessor_, typename HandlersContainer_ >
			class storage
			{
			private:
				using impl = inplace::storage<ExceptionHandler_, LockPrimitive_, HandlerProcessor_, HandlersContainer_>;

				std::shared_ptr<impl>	_impl;

			public:
				template < typename... Args_ >
				storage(Args_... args)
					: _impl(new impl(std::forward<Args_>(args)...))
				{ }

				HandlersContainer_& get_handlers_container() { return _impl->get_handlers_container(); }
				const HandlersContainer_& get_handlers_container() const { return _impl->get_handlers_container(); }

				const LockPrimitive_& get_lock_primitive() const { return _impl->get_lock_primitive(); }
				const ExceptionHandler_& get_exception_handler() const { return _impl->get_exception_handler(); }
				const HandlerProcessor_& get_handler_processor() const { return _impl->get_handler_processor(); }
			};

			template < typename ExceptionHandlingPolicy_, typename LockPrimitive_, typename HandlerProcessor_,typename HandlersContainer_ >
			using storage_ref = storage<ExceptionHandlingPolicy_, LockPrimitive_, HandlerProcessor_, HandlersContainer_>;
		};
	}

}

#endif
<|endoftext|>


<commit_before>/*
 * yafdb - Yet Another Face Detection and Bluring
 *
 * Copyright (c) 2014 FOXEL SA - http://foxel.ch
 * Please read <http://foxel.ch/license> for more information.
 *
 *
 * Author(s):
 *
 * Antony Ducommun <nitro@tmsrv.org>
 *
 *
 * This file is part of the FOXEL project <http://foxel.ch>.
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) 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 Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 *
 *
 * Additional Terms:
 *
 * You are required to preserve legal notices and author attributions in
 * that material or in the Appropriate Legal Notices displayed by works
 * containing it.
 *
 * You are required to attribute the work as explained in the "Usage and
 * Attribution" section of <http://foxel.ch/license>.
 */

#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <errno.h>
#include <getopt.h>

#include <string>
#include <list>
#include <vector>

#include <opencv2/opencv.hpp>
#include <opencv2/highgui/highgui.hpp>

/*
 * Program arguments.
 *
 */

static const char *source_file = NULL;
static const char *mask_file = NULL;
static const char *objects_file = NULL;

static struct option options[] = {
    {"algorithm",           required_argument, 0,                 'a'},
    {0, 0, 0, 0}
};

/**
 * Display program usage.
 *
 */
void usage() {
    printf("yafdb-test input-image.tiff mask-image.tiff input-objects.txt\n\n");

    printf("Compute the detection error rate by comparing optimal area given in\n");
    printf("reference bitmap mask (black=none, white=object) to the detected area\n");
    printf("given in input text file.\n\n");
}

/**
 * Program entry-point.
 *
 */
int main(int argc, char **argv) {
    // parse arguments
    while (true) {
        int index = -1;

        getopt_long(argc, argv, "", options, &index);
        if (index == -1) {
            if (argc != optind + 3) {
                usage();
                return 1;
            }
            source_file = argv[optind++];
            if (access(source_file, R_OK)) {
                fprintf(stderr, "Error: source file not readable: %s\n", source_file);
                return 2;
            }

            mask_file = argv[optind++];
            if (access(mask_file, R_OK)) {
                fprintf(stderr, "Error: mask file not readable: %s\n", mask_file);
                return 2;
            }

            objects_file = argv[optind++];
            if (access(objects_file, R_OK)) {
                fprintf(stderr, "Error: detected objects file not readable: %s\n", objects_file);
                return 2;
            }
          	break;
        }

        usage();
        return 1;
    }

    // read source file
    cv::Mat source = cv::imread(source_file);

    if (source.rows <= 0 || source.cols <= 0) {
        fprintf(stderr, "Error: cannot read image in source file: %s\n", source_file);
        return 2;
    }

    // read mask file
    cv::Mat mask = cv::imread(mask_file);

    if (mask.rows != source.rows || mask.cols != source.cols) {
        fprintf(stderr, "Error: cannot read image in mask file or mask is incompatible: %s\n", mask_file);
        return 2;
    }

    // TODO: read detected objects

    // TODO: compute error rate
    return 0;
}
<commit_msg>Fixed yafdb-test args<commit_after>/*
 * yafdb - Yet Another Face Detection and Bluring
 *
 * Copyright (c) 2014 FOXEL SA - http://foxel.ch
 * Please read <http://foxel.ch/license> for more information.
 *
 *
 * Author(s):
 *
 * Antony Ducommun <nitro@tmsrv.org>
 *
 *
 * This file is part of the FOXEL project <http://foxel.ch>.
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) 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 Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 *
 *
 * Additional Terms:
 *
 * You are required to preserve legal notices and author attributions in
 * that material or in the Appropriate Legal Notices displayed by works
 * containing it.
 *
 * You are required to attribute the work as explained in the "Usage and
 * Attribution" section of <http://foxel.ch/license>.
 */

#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <errno.h>
#include <getopt.h>

#include <string>
#include <list>
#include <vector>

#include <opencv2/opencv.hpp>
#include <opencv2/highgui/highgui.hpp>

/*
 * Program arguments.
 *
 */

static const char *source_file = NULL;
static const char *mask_file = NULL;
static const char *objects_file = NULL;

static struct option options[] = {
    {0, 0, 0, 0}
};

/**
 * Display program usage.
 *
 */
void usage() {
    printf("yafdb-test input-image.tiff mask-image.tiff input-objects.txt\n\n");

    printf("Compute the detection error rate by comparing optimal area given in\n");
    printf("reference bitmap mask (black=none, white=object) to the detected area\n");
    printf("given in input text file.\n\n");
}

/**
 * Program entry-point.
 *
 */
int main(int argc, char **argv) {
    // parse arguments
    while (true) {
        int index = -1;

        getopt_long(argc, argv, "", options, &index);
        if (index == -1) {
            if (argc != optind + 3) {
                usage();
                return 1;
            }
            source_file = argv[optind++];
            if (access(source_file, R_OK)) {
                fprintf(stderr, "Error: source file not readable: %s\n", source_file);
                return 2;
            }

            mask_file = argv[optind++];
            if (access(mask_file, R_OK)) {
                fprintf(stderr, "Error: mask file not readable: %s\n", mask_file);
                return 2;
            }

            objects_file = argv[optind++];
            if (access(objects_file, R_OK)) {
                fprintf(stderr, "Error: detected objects file not readable: %s\n", objects_file);
                return 2;
            }
          	break;
        }

        usage();
        return 1;
    }

    // read source file
    cv::Mat source = cv::imread(source_file);

    if (source.rows <= 0 || source.cols <= 0) {
        fprintf(stderr, "Error: cannot read image in source file: %s\n", source_file);
        return 2;
    }

    // read mask file
    cv::Mat mask = cv::imread(mask_file);

    if (mask.rows != source.rows || mask.cols != source.cols) {
        fprintf(stderr, "Error: cannot read image in mask file or mask is incompatible: %s\n", mask_file);
        return 2;
    }

    // TODO: read detected objects

    // TODO: compute error rate
    return 0;
}
<|endoftext|>


<commit_before>#include "CD.H"

#include "GAMEWAD.H"
#include "SPECIFIC.H"

#include <stdio.h>
#include <assert.h>

//Number of XA files on disc (XA1-17.XA)
#define NUM_XA_FILES 17

#ifdef PSX
	#define XA_FILE_NAME "\XA%d.XA;1"
#else
	#define XA_FILE_NAME "XA%d.XA"
#endif

unsigned short XATrackClip[136];
short XAFadeRate;
int current_cd_mode;
int XACurPos;
int XAEndPos;
short XAVolume;
short XAReqVolume;
short XAMasterVolume;
short XATrack;
short XAReqTrack;
char XAFlag;
char XAWait;
static char XARepeat;
int XAStartPos;
static int XATrackList[17][2];

#ifdef PSX
	#include <sys/types.h>
	#include <LIBCD.H>
	#include <LIBSPU.H>
#endif

void cbvsync()//5D884(<), 5DD00(<)
{
	int ret;//$a1
	unsigned char io[8];//$sp-16
	int cnt;//$v0

	switch (XAFlag - 1)
	{
	case 0:
	{
		if (XAVolume == 0)
		{
			XAFlag++;
		}

		goto dflt;
		break;
	}
	case 1:
	{
		cnt = XATrack = XAReqTrack;
		if (XAReqTrack < 0)
		{
			cnt += 7;
		}

		//loc_5D8F8
		io[0] = 1;
		io[1] = XATrack & 7;

		XAStartPos = XATrackList[cnt][0];
		XAEndPos = XATrackList[cnt][1] + XATrackClip[XAReqTrack];
		XACurPos = XAStartPos;

#ifdef PSX
		CdControlF(0xD, &io);
#endif
		XAFlag++;

		//loc_5D8D8
		goto dflt;

		break;
	}
	case 2:
	{
		//loc_5D980
		XAReplay();
		XAReqVolume = XAMasterVolume;
		XAFlag++;

		goto dflt;

		break;
	}
	case 3:
	{
		//loc_5D9AC
		if (XAVolume == XAMasterVolume)
		{
			XAFlag++;
			XAWait = 60;
		}

		goto dflt;

		break;
	}
	case 4:
	{
		//loc_5D9E0
		if (XAWait == 0)
		{
			XAFlag++;
		}

		XAWait--;

		goto dflt;

		break;
	}
	case 5:
	{
		//loc_5DA18
#ifdef PSX
		VSync(-1);
#endif
		if (XAFlag & 7)
		{
#ifdef PSX
			ret = CdSync(0, &io[0]);
			if (ret == 5)
			{
				XAReplay();
			}
			else if (ret == 2)
			{
				if (XACurPos < XAEndPos)
				{
					//loc_5DAEC
					if (CdLastCom() == 0x11);
					{
						cnt = CdPosToInt(&io[5]);

						if (cnt > 0)
						{
							XACurPos = cnt;
						}

						CdControlF(&io[5], 0);
					}
				}
				else if (XARepeat == 0)
				{
					//loc_5DA84
					if (CurrentAtmosphere == 0)
					{
						CdControlB(9, 0, 0);
						XAFlag = 7;
					}
					else
					{
						//loc_5DAB8
						XAVolume = 0;
						XARepeat = 1;
						XAFlag = ret;
						XAReqTrack = CurrentAtmosphere;
						CDDA_SetVolume(0);
						IsAtmospherePlaying = 1;
					}
				}
				else
				{
					XAReplay();
				}
			}

			goto dflt;
#endif
		}

		break;
	}
	default:

	dflt:
		//def_5D8B8
		if (XAVolume < XAReqVolume)
		{
			XAVolume += XAFadeRate;
			if (XAVolume < XAReqVolume)
			{
				XAVolume = XAReqVolume;
			}//loc_5DB78

			CDDA_SetVolume(XAVolume);
		}
		else
		{
			//loc_5DB94
			if (XAReqVolume < XAVolume)
			{
				XAVolume -= XAFadeRate;
				if (!(XAReqVolume < XAVolume))
				{
					XAVolume = XAReqVolume;
				}

				//loc_5DBEC
				CDDA_SetVolume(XAVolume);

			}//loc_5DC00
		}

		//loc_5DC00
		break;
	}

	//loc_5DC00
	return;
}

void InitNewCDSystem()//5DDE8, 5E264(<)
{
#ifdef PSX
	struct CdlFILE fp;
	int test;
	unsigned char param[8];//FIXME incorrect
	DEL_ChangeCDMode(0);

	if (CdSearchFile(&fp, GAMEWAD_FILENAME))
	{
		printf("FOUND:%s\n", GAMEWAD_FILENAME);
	}

	CdControlB(CdlSetloc, &param, 0);//6956C
	CdRead(1, &gwHeader, 0x80); //69C4C
	//..
	//jal sub_5F6AC //memcpy(&gwHeader, sizeof(GAMEWAD_header);

	test = 0xDEAD;
	test++;
#else
	FILE* fileHandle = fopen(GAMEWAD_FILENAME, "rb");
	assert(fileHandle);
	fread(&gwHeader, sizeof(GAMEWAD_header), 1, fileHandle);
	fclose(fileHandle);

	//FIXME: CdPosToInt(); returns LBA for GAMEWAD.OBJ on disc.
	gwLba = 24;

#ifdef PSX
	//jal sub_66270 //CdPosToInt();
#endif

	char buf[10];//FIXME
	for (int i = 0; i < NUM_XA_FILES; i++)
	{
		sprintf(buf, XA_FILE_NAME, i + 1);

#ifdef PSX
		//jal sub_662F0 //CdSearchFile(&fp, buf);
#endif
		FILE* fileHandle = fopen(buf, "rb");
		assert(fileHandle);
		fseek(fileHandle, 0, SEEK_END);

		XATrackList[i][0] = -1;//FIXME: This value is returned by CdPosToInt(); register is v0. It returns the LBA of the XA file on disc.
		XATrackList[i][1] = XATrackList[i][0] + ((ftell(fileHandle) + 0x7FF) / CD_SECTOR_SIZE);

		fclose(fileHandle);
	}

	XAFlag = 0;
	XAVolume = 0;
	XAReqTrack = -1;
	XATrack = -1;
#endif

}

void DEL_ChangeCDMode(int mode)//5DEB0(<), ?
{
	unsigned char param[4];

	if (mode == 0 && current_cd_mode != 0)
	{
		current_cd_mode = 0;
		//param[0] = 0x80;
		//CdControlB(0xE, &param[0], 0);
		//VSync(3);
	}
	else if (mode == 1 && current_cd_mode != mode)
	{
		//loc_5DEF8
		current_cd_mode = mode;
	}
	else if (mode == 2 && current_cd_mode != mode)
	{
		//loc_5DF20
		current_cd_mode = mode;
		//param[0] = 0x80;
		//CdControlB(0xE, &param[0], 0);
		//VSync(3);
	}

	//loc_5DF58
	return;
}

//Play audio track
void S_CDPlay(short track, int mode)
{
	//unsigned char param[4];
	S_Warn("[S_CDPlay] - unimplemented!\n");
}

void S_CDStop()
{
	S_Warn("[S_CDStop] - unimplemented!\n");
}

void CDDA_SetMasterVolume(int nVolume)//5DDC4(<), 5E240(<) (F)
{
	XAMasterVolume = nVolume;
	CDDA_SetVolume(nVolume);
}

void CDDA_SetVolume(int nVolume)//5D7FC(<), 5DC78(<) (F)
{
	struct SpuCommonAttr attr;

	attr.cd.volume.left = nVolume * 64;
	attr.cd.volume.right = nVolume * 64;

#ifdef PSX
	attr.mask = SPU_COMMON_CDVOLL | SPU_COMMON_CDVOLR | SPU_COMMON_CDMIX;
	attr.cd.mix = SPU_ON;
	SpuSetCommonAttr(&attr);
#endif
}

void XAReplay()//5D838, ?
{
	struct CdlLOC loc;
	S_Warn("[XAReplay] - unimplemented!\n");
}<commit_msg>InitNewCDSystem() PSX Support.<commit_after>#include "CD.H"

#include "CONTROL.H"
#include "GAMEWAD.H"
#include "SPECIFIC.H"

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

//Number of XA files on disc (XA1-17.XA)
#define NUM_XA_FILES 17

#ifdef PSX
	#define XA_FILE_NAME "\\XA%d.XA;1"
#else
	#define XA_FILE_NAME "XA%d.XA"
#endif

unsigned short XATrackClip[136];
short XAFadeRate;
int current_cd_mode;
int XACurPos;
int XAEndPos;
short XAVolume;
short XAReqVolume;
short XAMasterVolume;
short XATrack;
short XAReqTrack;
char XAFlag;
char XAWait;
static char XARepeat;
int XAStartPos;
static int XATrackList[17][2];

#ifdef PSX
	#include <sys/types.h>
	#include <LIBCD.H>
	#include <LIBSPU.H>
#endif

void cbvsync()//5D884(<), 5DD00(<)
{
	int ret;//$a1
	unsigned char io[8];//$sp-16
	int cnt;//$v0

	switch (XAFlag - 1)
	{
	case 0:
	{
		if (XAVolume == 0)
		{
			XAFlag++;
		}

		goto dflt;
		break;
	}
	case 1:
	{
		cnt = XATrack = XAReqTrack;
		if (XAReqTrack < 0)
		{
			cnt += 7;
		}

		//loc_5D8F8
		io[0] = 1;
		io[1] = XATrack & 7;

		XAStartPos = XATrackList[cnt][0];
		XAEndPos = XATrackList[cnt][1] + XATrackClip[XAReqTrack];
		XACurPos = XAStartPos;

#ifdef PSX
		CdControlF(0xD, &io);
#endif
		XAFlag++;

		//loc_5D8D8
		goto dflt;

		break;
	}
	case 2:
	{
		//loc_5D980
		XAReplay();
		XAReqVolume = XAMasterVolume;
		XAFlag++;

		goto dflt;

		break;
	}
	case 3:
	{
		//loc_5D9AC
		if (XAVolume == XAMasterVolume)
		{
			XAFlag++;
			XAWait = 60;
		}

		goto dflt;

		break;
	}
	case 4:
	{
		//loc_5D9E0
		if (XAWait == 0)
		{
			XAFlag++;
		}

		XAWait--;

		goto dflt;

		break;
	}
	case 5:
	{
		//loc_5DA18
#ifdef PSX
		VSync(-1);
#endif
		if (XAFlag & 7)
		{
#ifdef PSX
			ret = CdSync(0, &io[0]);
			if (ret == 5)
			{
				XAReplay();
			}
			else if (ret == 2)
			{
				if (XACurPos < XAEndPos)
				{
					//loc_5DAEC
					if (CdLastCom() == 0x11);
					{
						cnt = CdPosToInt(&io[5]);

						if (cnt > 0)
						{
							XACurPos = cnt;
						}

						CdControlF(&io[5], 0);
					}
				}
				else if (XARepeat == 0)
				{
					//loc_5DA84
					if (CurrentAtmosphere == 0)
					{
						CdControlB(9, 0, 0);
						XAFlag = 7;
					}
					else
					{
						//loc_5DAB8
						XAVolume = 0;
						XARepeat = 1;
						XAFlag = ret;
						XAReqTrack = CurrentAtmosphere;
						CDDA_SetVolume(0);
						IsAtmospherePlaying = 1;
					}
				}
				else
				{
					XAReplay();
				}
			}

			goto dflt;
#endif
		}

		break;
	}
	default:

	dflt:
		//def_5D8B8
		if (XAVolume < XAReqVolume)
		{
			XAVolume += XAFadeRate;
			if (XAVolume < XAReqVolume)
			{
				XAVolume = XAReqVolume;
			}//loc_5DB78

			CDDA_SetVolume(XAVolume);
		}
		else
		{
			//loc_5DB94
			if (XAReqVolume < XAVolume)
			{
				XAVolume -= XAFadeRate;
				if (!(XAReqVolume < XAVolume))
				{
					XAVolume = XAReqVolume;
				}

				//loc_5DBEC
				CDDA_SetVolume(XAVolume);

			}//loc_5DC00
		}

		//loc_5DC00
		break;
	}

	//loc_5DC00
	return;
}

#ifdef PSX
	struct CdlFILE fp;
#endif

void InitNewCDSystem()//5DDE8, 5E264(<) (F)
{
	char buf[10];
	int i = 0;
	long local_wadfile_header[512];
#ifdef PSX

	DEL_ChangeCDMode(0);

	CdSearchFile(&fp, GAMEWAD_FILENAME);
	CdControlB(CdlSetloc, &fp, 0);//6956C
	CdRead(1, &local_wadfile_header, 0x80); //69C4C

	while (CdReadSync(1, 0) > 0)
	{
		VSync(0);
	}

	memcpy(&gwHeader, &local_wadfile_header, 512);//5F6AC

	gwLba = CdPosToInt(&fp.pos);//66270

#else

	FILE* fileHandle = fopen(GAMEWAD_FILENAME, "rb");
	assert(fileHandle);
	fread(&local_wadfile_header, sizeof(GAMEWAD_header), 1, fileHandle);
	fclose(fileHandle);

	memcpy(&gwHeader, &local_wadfile_header, sizeof(GAMEWAD_header));//5F6AC

	//FIXME: CdPosToInt(); returns LBA for GAMEWAD.OBJ on disc.
	gwLba = 24;

#endif

	//loc_5E2E8
	for (i = 0; i < NUM_XA_FILES; i++)
	{
		sprintf(buf, XA_FILE_NAME, i + 1);

#ifdef PSX
		CdSearchFile(&fp, buf);

		XATrackList[i][0] = CdPosToInt(&fp.pos);
		XATrackList[i][1] = XATrackList[i][0] + ((fp.size + 0x7FF) / CD_SECTOR_SIZE);
#else
		FILE* fileHandle = fopen(buf, "rb");
		assert(fileHandle);
		fseek(fileHandle, 0, SEEK_END);

		XATrackList[i][0] = -1;//FIXME: This value is returned by CdPosToInt(); register is v0. It returns the LBA of the XA file on disc.
		XATrackList[i][1] = XATrackList[i][0] + ((ftell(fileHandle) + 0x7FF) / CD_SECTOR_SIZE);

		fclose(fileHandle);
#endif
	}

	XAFlag = 0;
	XAVolume = 0;
	XAReqTrack = -1;
	XATrack = -1;
}

void DEL_ChangeCDMode(int mode)//5DEB0(<), ?
{
	unsigned char param[4];

	if (mode == 0 && current_cd_mode != 0)
	{
		current_cd_mode = 0;
#ifdef PSX
		param[0] = CdlModeSpeed;
		CdControlB(CdlSetmode, param, 0);
		VSync(3);
#endif
	}
	else if (mode == 1 && current_cd_mode != mode)
	{
		//loc_5DEF8
		current_cd_mode = mode;
	}
	else if (mode == 2 && current_cd_mode != mode)
	{
		//loc_5DF20
		current_cd_mode = mode;
#ifdef PSX
		param[0] = CdlModeSpeed;
		CdControlB(CdlSetmode, param, 0);
		VSync(3);
#endif
	}

	//loc_5DF58
	return;
}

//Play audio track
void S_CDPlay(short track, int mode)
{
	//unsigned char param[4];
	S_Warn("[S_CDPlay] - unimplemented!\n");
}

void S_CDStop()
{
	S_Warn("[S_CDStop] - unimplemented!\n");
}

void CDDA_SetMasterVolume(int nVolume)//5DDC4(<), 5E240(<) (F)
{
	XAMasterVolume = nVolume;
	CDDA_SetVolume(nVolume);
}

void CDDA_SetVolume(int nVolume)//5D7FC(<), 5DC78(<) (F)
{
	struct SpuCommonAttr attr;

	attr.cd.volume.left = nVolume * 64;
	attr.cd.volume.right = nVolume * 64;

#ifdef PSX
	attr.mask = SPU_COMMON_CDVOLL | SPU_COMMON_CDVOLR | SPU_COMMON_CDMIX;
	attr.cd.mix = SPU_ON;
	SpuSetCommonAttr(&attr);
#endif
}

void XAReplay()//5D838, ?
{
	struct CdlLOC loc;
	S_Warn("[XAReplay] - unimplemented!\n");
}<|endoftext|>


<commit_before>#include<iostream>
#define _USE_MATH_DEFINES
#include<cmath>
#include<cassert>
#include<thread>
#include<chrono>

#include "ics3/ics"

int main(int argc, char **argv) {
  {
    ics::ID id(2);
    ics::Angle degree = ics::Angle::newDegree();
    try {
      ics::ICS3 ics("/dev/ttyUSB0", ics::ICSBaudrate::RATE115200);
      assert(7500 == degree.getRaw());
      ics::Angle nowPos = ics.move(id, degree);
      std::cout << nowPos.get() << std::endl;
      std::this_thread::sleep_for(std::chrono::milliseconds(1000));
      degree.set(50);
      nowPos = ics.move(id, degree);
      std::cout << nowPos.get() << std::endl;
      std::this_thread::sleep_for(std::chrono::milliseconds(1000));
      degree.set(-50);
      nowPos = ics.move(id, degree);
      std::cout << nowPos.get() << std::endl;
      std::this_thread::sleep_for(std::chrono::milliseconds(1000));
      degree.set(0);
      nowPos = ics.move(id, degree);
      std::cout << nowPos.get() << std::endl;
      nowPos = ics.free(id);
      std::cout << nowPos.get() << std::endl;
    } catch (std::runtime_error& e) {
      std::cout << e.what() << std::endl;
    }
  }
  {
    std::cout << std::endl << "ID test section" << std::endl;
    ics::ID id {0};
    assert(id == 0);
    assert(id == 0);
    ics::ID id31 {31};
    assert(id31 == 31);
    assert(id31.get() == 31);
    try {
      ics::ID id32 {32};
      assert(false);
    } catch (std::invalid_argument& e) {
      std::cout << e.what() << std::endl;
    }
  }
  {
    std::cout << std::endl << "EepParam test section" << std::endl;
    ics::EepParam speed = ics::EepParam::speed();
    assert(127 == speed.get());
    speed.set(100);
    assert(100 == speed.get());
    try {
      speed.set(200);
      std::cerr << "Never run this" << std::endl;
    } catch (std::invalid_argument& e) {
      std::cout << e.what() << std::endl;
    }
  }
  {
    std::cout << std::endl << "angle test section" << std::endl;
    ics::Angle degree = ics::Angle::newDegree();
    ics::Angle radian = ics::Angle::newRadian();
    assert(degree.getRaw() == radian.getRaw());
    degree.set(0);
    radian.set(0);
    assert(degree.getRaw() == radian.getRaw());
    degree.set(90);
    radian.set(M_PI / 2);
    assert(degree.getRaw() == radian.getRaw());
    degree.set(60);
    radian.set(M_PI / 3);
    assert(degree.getRaw() == radian.getRaw());
    try {
      degree.set(150);
      std::cerr << "Never run this" << std::endl;
    } catch (const std::invalid_argument& e) {
      std::cout << e.what() << std::endl;
    }
    try {
      radian.set(M_PI);
      std::cerr << "Never run this" << std::endl;
    } catch (const std::invalid_argument& e) {
      std::cout << e.what() << std::endl;
    }
  }
  {
    std::cout << std::endl << "angle factory test section" << std::endl;
    ics::Angle degree = ics::Angle::newDegree(90);
    ics::Angle radian = ics::Angle::newRadian(M_PI / 2);
    assert(degree.getRaw() == radian.getRaw());
  }
  {
    std::cout << std::endl << "parameter test section" << std::endl;
    ics::Parameter current = ics::Parameter::current();
    assert(63 == current.get());
    current.set(30);
    assert(30 == current.get());
    try {
      current.set(70);
      std::cerr << "Never run this" << std::endl;
    } catch (const std::invalid_argument& e) {
      std::cout << e.what() << std::endl;
    }
  }
  return 0;
}
<commit_msg>Update testcode for readability<commit_after>#include<iostream>
#define _USE_MATH_DEFINES
#include<cmath>
#include<cassert>
#include<thread>
#include<chrono>

#include "ics3/ics"

int main(int argc, char **argv) {
  {
    std::cout << std::endl << "ICS3 test section" << std::endl;
    ics::ID id(2);
    ics::Angle degree = ics::Angle::newDegree();
    try {
      ics::ICS3 ics("/dev/ttyUSB0");
      assert(7500 == degree.getRaw());
      ics::Angle nowPos = ics.move(id, degree);
      std::cout << nowPos.get() << std::endl;
      std::this_thread::sleep_for(std::chrono::milliseconds(1000));
      degree.set(50);
      nowPos = ics.move(id, degree);
      std::cout << nowPos.get() << std::endl;
      std::this_thread::sleep_for(std::chrono::milliseconds(1000));
      degree.set(-50);
      nowPos = ics.move(id, degree);
      std::cout << nowPos.get() << std::endl;
      std::this_thread::sleep_for(std::chrono::milliseconds(1000));
      degree.set(0);
      nowPos = ics.move(id, degree);
      std::cout << nowPos.get() << std::endl;
      nowPos = ics.free(id);
      std::cout << nowPos.get() << std::endl;
    } catch (std::runtime_error& e) {
      std::cout << e.what() << std::endl;
    }
  }
  {
    std::cout << std::endl << "ID test section" << std::endl;
    ics::ID id {0};
    assert(id == 0);
    assert(id == 0);
    ics::ID id31 {31};
    assert(id31 == 31);
    assert(id31.get() == 31);
    try {
      ics::ID id32 {32};
      assert(false);
    } catch (std::invalid_argument& e) {
      std::cout << e.what() << std::endl;
    }
  }
  {
    std::cout << std::endl << "EepParam test section" << std::endl;
    ics::EepParam speed = ics::EepParam::speed();
    assert(127 == speed.get());
    speed.set(100);
    assert(100 == speed.get());
    try {
      speed.set(200);
      std::cerr << "Never run this" << std::endl;
    } catch (std::invalid_argument& e) {
      std::cout << e.what() << std::endl;
    }
  }
  {
    std::cout << std::endl << "angle test section" << std::endl;
    ics::Angle degree = ics::Angle::newDegree();
    ics::Angle radian = ics::Angle::newRadian();
    assert(degree.getRaw() == radian.getRaw());
    degree.set(0);
    radian.set(0);
    assert(degree.getRaw() == radian.getRaw());
    degree.set(90);
    radian.set(M_PI / 2);
    assert(degree.getRaw() == radian.getRaw());
    degree.set(60);
    radian.set(M_PI / 3);
    assert(degree.getRaw() == radian.getRaw());
    try {
      degree.set(150);
      std::cerr << "Never run this" << std::endl;
    } catch (const std::invalid_argument& e) {
      std::cout << e.what() << std::endl;
    }
    try {
      radian.set(M_PI);
      std::cerr << "Never run this" << std::endl;
    } catch (const std::invalid_argument& e) {
      std::cout << e.what() << std::endl;
    }
  }
  {
    std::cout << std::endl << "angle factory test section" << std::endl;
    ics::Angle degree = ics::Angle::newDegree(90);
    ics::Angle radian = ics::Angle::newRadian(M_PI / 2);
    assert(degree.getRaw() == radian.getRaw());
  }
  {
    std::cout << std::endl << "parameter test section" << std::endl;
    ics::Parameter current = ics::Parameter::current();
    assert(63 == current.get());
    current.set(30);
    assert(30 == current.get());
    try {
      current.set(70);
      std::cerr << "Never run this" << std::endl;
    } catch (const std::invalid_argument& e) {
      std::cout << e.what() << std::endl;
    }
  }
  return 0;
}
<|endoftext|>


<commit_before>#include <primecount.h>
#include <primesieve/soe/ParallelPrimeSieve.h>

#include <stdint.h>
#include <iostream>
#include <cstdlib>
#include <string>
#include <iomanip>
#include <ctime>

using namespace std;

namespace primecount {

void assert_equal(const std::string& f1_name, int64_t x, int64_t f1_res, int64_t f2_res)
{
  if (f1_res != f2_res)
  {
    cerr << endl << f1_name << "(" << x << ") = "  << f1_res
         << " is an error, the correct result is " << f2_res << std::endl;
    exit(1);
  }
}

/// 0 <= get_rand() < 10^7
int get_rand()
{
  return (rand() % 10000) * 1000;
}

template <typename F>
void check_for_equality(const std::string& f1_name, F f1, F f2, int64_t iters)
{
  cout << left;
  cout << "Testing " << setw(15) << (f1_name + "(x)") << flush;

  // test for 0 <= x < iters
  for (int64_t x = 0; x < iters; x++)
    assert_equal(f1_name, x, f1(x, MAX_THREADS), f2(x, MAX_THREADS));

  int64_t x = 0;
  // test using random increment
  for (int64_t i = 0; i < iters; i++, x += get_rand())
    assert_equal(f1_name, x, f1(x, MAX_THREADS), f2(x, MAX_THREADS));

  cout << "OK" << endl;
}

int64_t pps_nth_prime(int64_t x, int)
{
  ParallelPrimeSieve pps;
  int64_t prime = pps.nthPrime(x);
  return prime;
}

void test()
{
  srand(static_cast<unsigned int>(time(0)));

  check_for_equality("pi_legendre", pi_legendre, pi_primesieve, 100);
  check_for_equality("pi_meissel",  pi_meissel,  pi_legendre,   500);
  check_for_equality("pi_lehmer",   pi_lehmer,   pi_meissel,    500);
  check_for_equality("nth_prime",   nth_prime,   pps_nth_prime, 100);

  cout << "All tests passed successfully!" << endl;
  exit(0);
}

} // namespace primecount
<commit_msg>get_rand() % 2 == 0 is not good for testing<commit_after>#include <primecount.h>
#include <primesieve/soe/ParallelPrimeSieve.h>

#include <stdint.h>
#include <iostream>
#include <cstdlib>
#include <string>
#include <iomanip>
#include <ctime>

using namespace std;

namespace primecount {

void assert_equal(const std::string& f1_name, int64_t x, int64_t f1_res, int64_t f2_res)
{
  if (f1_res != f2_res)
  {
    cerr << endl << f1_name << "(" << x << ") = "  << f1_res
         << " is an error, the correct result is " << f2_res << std::endl;
    exit(1);
  }
}

/// 0 <= get_rand() < 10^7
int get_rand()
{
  return (rand() % 10000) * 1000 + 1;
}

template <typename F>
void check_for_equality(const std::string& f1_name, F f1, F f2, int64_t iters)
{
  cout << left;
  cout << "Testing " << setw(15) << (f1_name + "(x)") << flush;

  // test for 0 <= x < iters
  for (int64_t x = 0; x < iters; x++)
    assert_equal(f1_name, x, f1(x, MAX_THREADS), f2(x, MAX_THREADS));

  int64_t x = 0;
  // test using random increment
  for (int64_t i = 0; i < iters; i++, x += get_rand())
    assert_equal(f1_name, x, f1(x, MAX_THREADS), f2(x, MAX_THREADS));

  cout << "OK" << endl;
}

int64_t pps_nth_prime(int64_t x, int)
{
  ParallelPrimeSieve pps;
  int64_t prime = pps.nthPrime(x);
  return prime;
}

void test()
{
  srand(static_cast<unsigned int>(time(0)));

  check_for_equality("pi_legendre", pi_legendre, pi_primesieve, 100);
  check_for_equality("pi_meissel",  pi_meissel,  pi_legendre,   500);
  check_for_equality("pi_lehmer",   pi_lehmer,   pi_meissel,    500);
  check_for_equality("nth_prime",   nth_prime,   pps_nth_prime, 100);

  cout << "All tests passed successfully!" << endl;
  exit(0);
}

} // namespace primecount
<|endoftext|>


<commit_before>#include "testApp.h"
#include "CursorFeedback.hpp"
#include "FigureFeedback.hpp"
#include "TapFeedback.hpp"
#include "Calibrator.hpp"

//--------------------------------------------------------------
void testApp::Setup(){
    new CursorFeedback();
    new FigureFeedback();
    new TapFeedback();
    new CalibratorObject(1);
}

//--------------------------------------------------------------
void testApp::Update(){

}

//--------------------------------------------------------------
void testApp::Draw(){

}

//--------------------------------------------------------------
void testApp::WindowResized(int w, int h){

}
<commit_msg>Since Calibration Object doesn't work properly I remove it from the example project<commit_after>#include "testApp.h"
#include "CursorFeedback.hpp"
#include "FigureFeedback.hpp"
#include "TapFeedback.hpp"
#include "Calibrator.hpp"

//--------------------------------------------------------------
void testApp::Setup(){
    new CursorFeedback();
    new FigureFeedback();
    new TapFeedback();
}

//--------------------------------------------------------------
void testApp::Update(){

}

//--------------------------------------------------------------
void testApp::Draw(){

}

//--------------------------------------------------------------
void testApp::WindowResized(int w, int h){

}
<|endoftext|>


<commit_before>
/*
 *  client.cpp
 *
 *  Handles the client env.
 *
 *  Created by Ryan Faulkner on 2014-06-08
 *  Copyright (c) 2014. All rights reserved.
 */

#include <iostream>
#include <string>
#include <vector>
#include <regex>
#include <assert.h>

#include "column_types.h"
#include "redis.h"
#include "md5.h"
#include "index.h"
#include "bayes.h"
#include "model.h"

#define REDISHOST "127.0.0.1"
#define REDISPORT 6379

using namespace std;

/** Test to ensure that redis keys are correctly returned */
void testRedisSet() {
    RedisHandler r;
    r.connect();
    r.write("foo", "bar");
}

/** Test to ensure that redis keys are correctly returned */
void testRedisGet() {
    RedisHandler r;
    r.connect();
    cout << endl << "VALUE FOR KEY foo" << endl;
    cout << r.read("foo") << endl << endl;
}

/** Test to ensure that redis keys are correctly returned */
void testRedisKeys() {
    RedisHandler r;
    std::vector<std::string> vec;

    r.connect();
    vec = r.keys("*");
    cout << "KEY LIST FOR *" << endl;
    for (std::vector<std::string>::iterator it = vec.begin() ; it != vec.end(); ++it) {
        cout << *it << endl;
    }
    cout << endl;
}

/** Test to ensure that redis keys are correctly returned */
void testRedisIO() {
    RedisHandler r;
    std::vector<string>* vec;
    std::string outTrue, outFalse = "";

    r.connect();
    r.write("test_key", "test value");
    outTrue = r.read("test_key");
    assert(std::strcmp(outTrue.c_str(), "test value") == 0);
    r.deleteKey("test_key");
    assert(!r.exists("test_key"));
}

/** Test to ensure that md5 hashing works */
void testMd5Hashing() {
    cout << endl << "md5 of 'mykey': " << md5("mykey") << endl;
}

/** Test to ensure that md5 hashing works */
void testRegexForTypes() {
    IntegerColumn ic;
    FloatColumn fc;
    assert(ic.validate("1981"));
    assert(fc.validate("5.2"));
    cout << "Passed regex tests." << endl;
}

/** Test to ensure that md5 hashing works */
void testOrderPairAlphaNumeric() {
    IndexHandler ih;
    assert(std::strcmp(ih.orderPairAlphaNumeric("b", "a").c_str(), "a_b") == 0);
    cout << "Passed orderPairAlphaNumeric tests." << endl;
}

/**
 * Test to ensure that relation entities are encoded properly
 */
void testJSONEntityEncoding() {

    IndexHandler ih;
    Json::Value json;
    std::vector<std::pair<ColumnBase, std::string>> fields_ent;

    fields_ent.push_back(std::make_pair(getColumnType("integer"), "a"));   // Create fields
    Entity e("test", fields_ent);
    ih.writeEntity(e);     // Create the entity
    ih.fetchEntity("test", json);           // Fetch the entity representation
    cout << "TEST ENTITY:" << endl << endl << json.toStyledString() << endl;

    // Assert that entity as read matches definition
    assert(std::strcmp(json["entity"].asCString(), "test") == 0 &&
            std::strcmp(json["fields"]["a"].asCString(), "integer") == 0 &&
            json["fields"]["_itemcount"].asInt() == 1
    );
    ih.removeEntity("test");                // Remove the entity
}

/**
 * Test to ensure that relation fields are encoded properly
 */
void testJSONRelationEncoding() {
    IndexHandler ih;
    std::vector<Json::Value> ret;
    std::vector<std::pair<ColumnBase, std::string>> fields_ent_1;
    std::vector<std::pair<ColumnBase, std::string>> fields_ent_2;
    std::vector<std::pair<std::string, std::string>> fields_rel_1;
    std::vector<std::pair<std::string, std::string>> fields_rel_2;

    // Popualate fields
    fields_ent_1.push_back(std::make_pair(getColumnType("integer"), "a"));
    fields_ent_2.push_back(std::make_pair(getColumnType("string"), "b"));
    fields_rel_1.push_back(std::make_pair("a", "1"));
    fields_rel_2.push_back(std::make_pair("b", "hello"));

    // Create entities
    Entity e1("test_1", fields_ent_1), e2("test_2", fields_ent_2);
    ih.writeEntity(e1);
    ih.writeEntity(e2);

    // Create relation in redis
    Relation r("test_1", "test_2", fields_rel_1, fields_rel_2);
    ih.writeRelation(r);

    // Fetch the entity representation
    ret = ih.fetchRelationPrefix("test_1", "test_2");
    cout << "TEST RELATION:" << endl << endl << ret[0].toStyledString() << endl;

    // Assert that entity as read matches definition
    assert(
        std::strcmp(ret[0]["entity_left"].asCString(), "test_1") == 0 &&
        std::strcmp(ret[0]["entity_right"].asCString(), "test_2") == 0 &&
        std::strcmp(ret[0]["fields_left"]["a"].asCString(), "1") == 0 &&
        std::strcmp(ret[0]["fields_right"]["b"].asCString(), "hello") == 0 &&
        ret[0]["fields_left"]["_itemcount"].asInt() == 1 &&
        ret[0]["fields_right"]["_itemcount"].asInt() == 1
    );
    ih.removeEntity("test_1");                // Remove the entity
    ih.removeEntity("test_2");                // Remove the entity
    ih.removeRelation(r);    // Remove the relation
}

/**
 *  Tests that parseEntityAssignField correctly flags invalid assignments to integer fields
 */
void testFieldAssignTypeMismatchInteger() {
    IndexHandler ih;
    Json::Value json;
    std::vector<std::pair<ColumnBase, std::string>> fields_ent;
    fields_ent.push_back(std::make_pair(getColumnType("integer"), "a"));   // Create fields
    Entity e("test", fields_ent);

    ih.writeEntity(e);     // Create the entity
    assert(
        ih.validateEntityFieldType("test", "a", "1") &&
        ih.validateEntityFieldType("test", "a", "12345") &&
        !ih.validateEntityFieldType("test", "a", "1.0") &&
        !ih.validateEntityFieldType("test", "a", "string")
    );
    ih.removeEntity("test");
}

/**
 *  Tests that parseEntityAssignField correctly flags invalid assignments to float fields
 */
void testFieldAssignTypeMismatchFloat() {
    IndexHandler ih;
    Json::Value json;
    std::vector<std::pair<ColumnBase, std::string>> fields_ent;
    fields_ent.push_back(std::make_pair(getColumnType("float"), "a"));   // Create fields
    Entity e("test", fields_ent);     // Create the entity

    ih.writeEntity(e);     // Create the entity
    assert(
        ih.validateEntityFieldType("test", "a", "1.2") &&
        ih.validateEntityFieldType("test", "a", "12.5") &&
        !ih.validateEntityFieldType("test", "a", "string")
    );
    ih.removeEntity("test");
}

/**
 *  Tests that parseEntityAssignField correctly flags invalid assignments to string fields
 */
void testFieldAssignTypeMismatchString() {
    IndexHandler ih;
    Json::Value json;
    std::vector<std::pair<ColumnBase, std::string>> fields_ent;
    fields_ent.push_back(std::make_pair(getColumnType("string"), "a"));   // Create fields
    Entity e("test", fields_ent);
    ih.writeEntity(e);     // Create the entity
    assert(
        ih.validateEntityFieldType("test", "a", "1") &&
        ih.validateEntityFieldType("test", "a", "12345") &&
        ih.validateEntityFieldType("test", "a", "string")
    );
    ih.removeEntity("test");
}

/**
 *  Tests Bayes::countRelations - ensure relation counting is functioning correctly
 */
void testCountRelations() {
    Bayes bayes;
    IndexHandler ih;
    std::vector<Json::Value> ret;
    std::vector<std::pair<ColumnBase*, std::string>> fields_ent;
    std::vector<std::pair<std::string, std::string>> fields_rel;

    // declare three entities
    Entity e1("_w", fields_ent), e2("_x", fields_ent), e3("_y", fields_ent), e4("_z", fields_ent);

    // construct a number of relations
    Relation r1("_x", "_y", fields_rel, fields_rel);
    Relation r2("_x", "_y", fields_rel, fields_rel);
    Relation r3("_x", "_z", fields_rel, fields_rel);
    Relation r4("_x", "_z", fields_rel, fields_rel);
    Relation r5("_w", "_y", fields_rel, fields_rel);

    ih.removeEntity("_w");
    ih.removeEntity("_x");
    ih.removeEntity("_y");
    ih.removeEntity("_z");

    ih.writeEntity(e1);
    ih.writeEntity(e2);
    ih.writeEntity(e3);
    ih.writeEntity(e4);

    ih.removeRelation(r1);
    ih.removeRelation(r2);
    ih.removeRelation(r3);
    ih.removeRelation(r4);
    ih.removeRelation(r5);

    ih.writeRelation(r1);
    ih.writeRelation(r2);
    ih.writeRelation(r3);
    ih.writeRelation(r4);
    ih.writeRelation(r5);

    AttributeBucket attrs; // empty set of filters

    assert(bayes.countEntityInRelations(e1.name, attrs) == 1);
    assert(bayes.countEntityInRelations(e2.name, attrs) == 4);
    assert(bayes.countEntityInRelations(e3.name, attrs) == 3);
    assert(bayes.countEntityInRelations(e4.name, attrs) == 2);
}

/**
 *  Tests that existsEntityField correctly flags when entity does not contain a field
 */
void testEntityDoesNotContainField() {
    // TODO - implement
}

/**
 *  Tests Bayes::computeMarginal function - ensure the marginal likelihood is correct
 */
void testComputeMarginal() {

    Bayes bayes;
    IndexHandler ih;
    std::vector<Json::Value> ret;
    std::vector<std::pair<ColumnBase*, std::string>> fields_ent;
    std::vector<std::pair<std::string, std::string>> fields_rel;

    ih.setRelationCountTotal(0);

    // declare three entities
    Entity e1("_w", fields_ent), e2("_x", fields_ent), e3("_y", fields_ent), e4("_z", fields_ent);

    // construct a number of relations
    Relation r1("_x", "_y", fields_rel, fields_rel);
    Relation r2("_x", "_y", fields_rel, fields_rel);
    Relation r3("_x", "_z", fields_rel, fields_rel);
    Relation r4("_x", "_z", fields_rel, fields_rel);
    Relation r5("_w", "_y", fields_rel, fields_rel);

    ih.removeEntity("_w");
    ih.removeEntity("_x");
    ih.removeEntity("_y");
    ih.removeEntity("_z");

    ih.writeEntity(e1);
    ih.writeEntity(e2);
    ih.writeEntity(e3);
    ih.writeEntity(e4);

    ih.removeRelation(r1);
    ih.removeRelation(r2);
    ih.removeRelation(r3);
    ih.removeRelation(r4);
    ih.removeRelation(r5);

    ih.writeRelation(r1);
    ih.writeRelation(r2);
    ih.writeRelation(r3);
    ih.writeRelation(r4);
    ih.writeRelation(r5);

    ih.setRelationCountTotal(ih.computeRelationsCount("*", "*"));

    // Ensure marginal likelihood reflects the number of relations that contain each entity
    AttributeBucket attrs;

    assert(bayes.computeMarginal(e1.name, attrs) == (float)0.2);
    assert(bayes.computeMarginal(e2.name, attrs) == (float)0.8);
    assert(bayes.computeMarginal(e3.name, attrs) == (float)0.6);
    assert(bayes.computeMarginal(e4.name, attrs) == (float)0.4);

}

/**
 *  Tests that removal of entities functions properly
 */
void testEntityRemoval() {
    // TODO - implement
}

/**
 *  Tests that removal of relations functions properly
 */
void testRelationRemoval() {
    // TODO - implement
}

/**
 *  Tests that removal of relations cascading on entities functions properly
 */
void testEntityCascadeRemoval() {
    // TODO - implement
}

/**
 *  Tests that the correct relations are filtered from a set
 */
void testRelationFiltering() {
    // TODO - implement
}

/**
 *  Tests that the correct relations are filtered from a set
 */
void testRelation_toJson() {
    valpair left, right;
    left.push_back(std::make_pair("x", "1"));
    right.push_back(std::make_pair("y", "2"));
    Relation rel("x", "y", left, right);
    Json::Value json = rel.toJson();
    assert(std::atoi(json[JSON_ATTR_REL_FIELDSL]["x"].asCString()) == 1 && std::atoi(json[JSON_ATTR_REL_FIELDSR]["y"].asCString()) == 2);
}

/**
 *  Ensure sample marginal returns a valid sample
 */
void testSampleMarginal() {
    // Define entities and relations
    // Generate a sample
    // specify filter criteria
    // test sample to ensure that it meets criteria
}

/**
 *  Ensure sample marginal returns a valid sample
 */
void testSamplePairwise() {
    // Define entities and relations
    // Generate a sample
    // specify filter criteria
    // test sample to ensure that it meets criteria
}

/**
 *  Ensure sample marginal returns a valid sample
 */
void testSamplePairwiseCausal() {
    // Define entities and relations
    // Generate a sample
    // specify filter criteria
    // test sample to ensure that it meets criteria
}

int main() {
    cout << "-- TESTS BEGIN --" << endl << endl;

//    testRedisSet();
//    testRedisGet();
//    testRedisKeys();
//    md5Hashing();
//    testRedisIO();
//    testRegexForTypes();
//    testOrderPairAlphaNumeric();

    // testJSONEntityEncoding();
    // testJSONRelationEncoding();
    // testFieldAssignTypeMismatchInteger();
    // testFieldAssignTypeMismatchFloat();
    // testFieldAssignTypeMismatchString();
    // testCountRelations();
    testComputeMarginal();
    // testRelation_toJson();

    cout << endl << "-- TESTS END --" << endl;

    return 0;
}
<commit_msg>update tests to be consistent with new relation model<commit_after>
/*
 *  client.cpp
 *
 *  Handles the client env.
 *
 *  Created by Ryan Faulkner on 2014-06-08
 *  Copyright (c) 2014. All rights reserved.
 */

#include <iostream>
#include <string>
#include <vector>
#include <regex>
#include <assert.h>

#include "column_types.h"
#include "redis.h"
#include "md5.h"
#include "index.h"
#include "bayes.h"
#include "model.h"

#define REDISHOST "127.0.0.1"
#define REDISPORT 6379

using namespace std;

/** Test to ensure that redis keys are correctly returned */
void testRedisSet() {
    RedisHandler r;
    r.connect();
    r.write("foo", "bar");
}

/** Test to ensure that redis keys are correctly returned */
void testRedisGet() {
    RedisHandler r;
    r.connect();
    cout << endl << "VALUE FOR KEY foo" << endl;
    cout << r.read("foo") << endl << endl;
}

/** Test to ensure that redis keys are correctly returned */
void testRedisKeys() {
    RedisHandler r;
    std::vector<std::string> vec;

    r.connect();
    vec = r.keys("*");
    cout << "KEY LIST FOR *" << endl;
    for (std::vector<std::string>::iterator it = vec.begin() ; it != vec.end(); ++it) {
        cout << *it << endl;
    }
    cout << endl;
}

/** Test to ensure that redis keys are correctly returned */
void testRedisIO() {
    RedisHandler r;
    std::vector<string>* vec;
    std::string outTrue, outFalse = "";

    r.connect();
    r.write("test_key", "test value");
    outTrue = r.read("test_key");
    assert(std::strcmp(outTrue.c_str(), "test value") == 0);
    r.deleteKey("test_key");
    assert(!r.exists("test_key"));
}

/** Test to ensure that md5 hashing works */
void testMd5Hashing() {
    cout << endl << "md5 of 'mykey': " << md5("mykey") << endl;
}

/** Test to ensure that md5 hashing works */
void testRegexForTypes() {
    IntegerColumn ic;
    FloatColumn fc;
    assert(ic.validate("1981"));
    assert(fc.validate("5.2"));
    cout << "Passed regex tests." << endl;
}

/** Test to ensure that md5 hashing works */
void testOrderPairAlphaNumeric() {
    IndexHandler ih;
    assert(std::strcmp(ih.orderPairAlphaNumeric("b", "a").c_str(), "a_b") == 0);
    cout << "Passed orderPairAlphaNumeric tests." << endl;
}

/**
 * Test to ensure that relation entities are encoded properly
 */
void testJSONEntityEncoding() {

    IndexHandler ih;
    Json::Value json;
    std::vector<std::pair<ColumnBase, std::string>> fields_ent;

    fields_ent.push_back(std::make_pair(getColumnType("integer"), "a"));   // Create fields
    Entity e("test", fields_ent);
    ih.writeEntity(e);     // Create the entity
    ih.fetchEntity("test", json);           // Fetch the entity representation
    cout << "TEST ENTITY:" << endl << endl << json.toStyledString() << endl;

    // Assert that entity as read matches definition
    assert(std::strcmp(json["entity"].asCString(), "test") == 0 &&
            std::strcmp(json["fields"]["a"].asCString(), "integer") == 0 &&
            json["fields"]["_itemcount"].asInt() == 1
    );
    ih.removeEntity("test");                // Remove the entity
}

/**
 * Test to ensure that relation fields are encoded properly
 */
void testJSONRelationEncoding() {
    IndexHandler ih;
    std::vector<Json::Value> ret;
    std::vector<std::pair<ColumnBase, std::string>> fields_ent_1;
    std::vector<std::pair<ColumnBase, std::string>> fields_ent_2;
    std::vector<std::pair<std::string, std::string>> fields_rel_1;
    std::vector<std::pair<std::string, std::string>> fields_rel_2;

    // Popualate fields
    fields_ent_1.push_back(std::make_pair(getColumnType("integer"), "a"));
    fields_ent_2.push_back(std::make_pair(getColumnType("string"), "b"));
    fields_rel_1.push_back(std::make_pair("a", "1"));
    fields_rel_2.push_back(std::make_pair("b", "hello"));

    // Create entities
    Entity e1("test_1", fields_ent_1), e2("test_2", fields_ent_2);
    ih.writeEntity(e1);
    ih.writeEntity(e2);

    // Create relation in redis
    Relation r("test_1", "test_2", fields_rel_1, fields_rel_2);
    ih.writeRelation(r);

    // Fetch the entity representation
    ret = ih.fetchRelationPrefix("test_1", "test_2");
    cout << "TEST RELATION:" << endl << endl << ret[0].toStyledString() << endl;

    // Assert that entity as read matches definition
    assert(
        std::strcmp(ret[0]["entity_left"].asCString(), "test_1") == 0 &&
        std::strcmp(ret[0]["entity_right"].asCString(), "test_2") == 0 &&
        std::strcmp(ret[0]["fields_left"]["a"].asCString(), "1") == 0 &&
        std::strcmp(ret[0]["fields_right"]["b"].asCString(), "hello") == 0 &&
        ret[0]["fields_left"]["_itemcount"].asInt() == 1 &&
        ret[0]["fields_right"]["_itemcount"].asInt() == 1
    );
    ih.removeEntity("test_1");                // Remove the entity
    ih.removeEntity("test_2");                // Remove the entity
    ih.removeRelation(r);    // Remove the relation
}

/**
 *  Tests that parseEntityAssignField correctly flags invalid assignments to integer fields
 */
void testFieldAssignTypeMismatchInteger() {
    IndexHandler ih;
    Json::Value json;
    std::vector<std::pair<ColumnBase, std::string>> fields_ent;
    fields_ent.push_back(std::make_pair(getColumnType("integer"), "a"));   // Create fields
    Entity e("test", fields_ent);

    ih.writeEntity(e);     // Create the entity
    assert(
        ih.validateEntityFieldType("test", "a", "1") &&
        ih.validateEntityFieldType("test", "a", "12345") &&
        !ih.validateEntityFieldType("test", "a", "1.0") &&
        !ih.validateEntityFieldType("test", "a", "string")
    );
    ih.removeEntity("test");
}

/**
 *  Tests that parseEntityAssignField correctly flags invalid assignments to float fields
 */
void testFieldAssignTypeMismatchFloat() {
    IndexHandler ih;
    Json::Value json;
    std::vector<std::pair<ColumnBase, std::string>> fields_ent;
    fields_ent.push_back(std::make_pair(getColumnType("float"), "a"));   // Create fields
    Entity e("test", fields_ent);     // Create the entity

    ih.writeEntity(e);     // Create the entity
    assert(
        ih.validateEntityFieldType("test", "a", "1.2") &&
        ih.validateEntityFieldType("test", "a", "12.5") &&
        !ih.validateEntityFieldType("test", "a", "string")
    );
    ih.removeEntity("test");
}

/**
 *  Tests that parseEntityAssignField correctly flags invalid assignments to string fields
 */
void testFieldAssignTypeMismatchString() {
    IndexHandler ih;
    Json::Value json;
    std::vector<std::pair<ColumnBase, std::string>> fields_ent;
    fields_ent.push_back(std::make_pair(getColumnType("string"), "a"));   // Create fields
    Entity e("test", fields_ent);
    ih.writeEntity(e);     // Create the entity
    assert(
        ih.validateEntityFieldType("test", "a", "1") &&
        ih.validateEntityFieldType("test", "a", "12345") &&
        ih.validateEntityFieldType("test", "a", "string")
    );
    ih.removeEntity("test");
}

/**
 *  Tests Bayes::countRelations - ensure relation counting is functioning correctly
 */
void testCountRelations() {
    Bayes bayes;
    IndexHandler ih;
    std::vector<Json::Value> ret;
    std::vector<std::pair<ColumnBase*, std::string>> fields_ent;
    std::vector<std::pair<std::string, std::string>> fields_rel;
    std::unordered_map<std::string, std::string> types;

    // declare three entities
    Entity e1("_w", fields_ent), e2("_x", fields_ent), e3("_y", fields_ent), e4("_z", fields_ent);

    // construct a number of relations
    Relation r1("_x", "_y", fields_rel, fields_rel, types, types);
    Relation r2("_x", "_y", fields_rel, fields_rel, types, types);
    Relation r3("_x", "_z", fields_rel, fields_rel, types, types);
    Relation r4("_x", "_z", fields_rel, fields_rel, types, types);
    Relation r5("_w", "_y", fields_rel, fields_rel, types, types);

    ih.removeEntity("_w");
    ih.removeEntity("_x");
    ih.removeEntity("_y");
    ih.removeEntity("_z");

    ih.writeEntity(e1);
    ih.writeEntity(e2);
    ih.writeEntity(e3);
    ih.writeEntity(e4);

    ih.removeRelation(r1);
    ih.removeRelation(r2);
    ih.removeRelation(r3);
    ih.removeRelation(r4);
    ih.removeRelation(r5);

    ih.writeRelation(r1);
    ih.writeRelation(r2);
    ih.writeRelation(r3);
    ih.writeRelation(r4);
    ih.writeRelation(r5);

    AttributeBucket attrs; // empty set of filters

    assert(bayes.countEntityInRelations(e1.name, attrs) == 1);
    assert(bayes.countEntityInRelations(e2.name, attrs) == 4);
    assert(bayes.countEntityInRelations(e3.name, attrs) == 3);
    assert(bayes.countEntityInRelations(e4.name, attrs) == 2);
}

/**
 *  Tests that existsEntityField correctly flags when entity does not contain a field
 */
void testEntityDoesNotContainField() {
    // TODO - implement
}

/**
 *  Tests Bayes::computeMarginal function - ensure the marginal likelihood is correct
 */
void testComputeMarginal() {

    Bayes bayes;
    IndexHandler ih;
    std::vector<Json::Value> ret;
    std::vector<std::pair<ColumnBase*, std::string>> fields_ent;
    std::vector<std::pair<std::string, std::string>> fields_rel;
    std::unordered_map<std::string, std::string> types;

    ih.setRelationCountTotal(0);

    // declare three entities
    Entity e1("_w", fields_ent), e2("_x", fields_ent), e3("_y", fields_ent), e4("_z", fields_ent);

    // construct a number of relations
    Relation r1("_x", "_y", fields_rel, fields_rel, types, types);
    Relation r2("_x", "_y", fields_rel, fields_rel, types, types);
    Relation r3("_x", "_z", fields_rel, fields_rel, types, types);
    Relation r4("_x", "_z", fields_rel, fields_rel, types, types);
    Relation r5("_w", "_y", fields_rel, fields_rel, types, types);

    ih.removeEntity("_w");
    ih.removeEntity("_x");
    ih.removeEntity("_y");
    ih.removeEntity("_z");

    ih.writeEntity(e1);
    ih.writeEntity(e2);
    ih.writeEntity(e3);
    ih.writeEntity(e4);

    ih.removeRelation(r1);
    ih.removeRelation(r2);
    ih.removeRelation(r3);
    ih.removeRelation(r4);
    ih.removeRelation(r5);

    ih.writeRelation(r1);
    ih.writeRelation(r2);
    ih.writeRelation(r3);
    ih.writeRelation(r4);
    ih.writeRelation(r5);

    ih.setRelationCountTotal(ih.computeRelationsCount("*", "*"));

    // Ensure marginal likelihood reflects the number of relations that contain each entity
    AttributeBucket attrs;

    assert(bayes.computeMarginal(e1.name, attrs) == (float)0.2);
    assert(bayes.computeMarginal(e2.name, attrs) == (float)0.8);
    assert(bayes.computeMarginal(e3.name, attrs) == (float)0.6);
    assert(bayes.computeMarginal(e4.name, attrs) == (float)0.4);

}

/**
 *  Tests that removal of entities functions properly
 */
void testEntityRemoval() {
    // TODO - implement
}

/**
 *  Tests that removal of relations functions properly
 */
void testRelationRemoval() {
    // TODO - implement
}

/**
 *  Tests that removal of relations cascading on entities functions properly
 */
void testEntityCascadeRemoval() {
    // TODO - implement
}

/**
 *  Tests that the correct relations are filtered from a set
 */
void testRelationFiltering() {
    // TODO - implement
}

/**
 *  Tests that the correct relations are filtered from a set
 */
void testRelation_toJson() {
    valpair left, right;
    std::unordered_map<std::string, std::string> typesL, typesR;

    left.push_back(std::make_pair("x", "1"));
    right.push_back(std::make_pair("y", "2"));
    typesL.insert(std::make_pair("x", COLTYPE_NAME_INT));
    typesR.insert(std::make_pair("y", COLTYPE_NAME_INT));
    Relation rel("x", "y", left, right);
    Json::Value json = rel.toJson();
    assert(std::atoi(json[JSON_ATTR_REL_FIELDSL]["x"].asCString()) == 1 && std::atoi(json[JSON_ATTR_REL_FIELDSR]["y"].asCString()) == 2);
}

/**
 *  Ensure sample marginal returns a valid sample
 */
void testSampleMarginal() {
    // Define entities and relations
    // Generate a sample
    // specify filter criteria
    // test sample to ensure that it meets criteria
}

/**
 *  Ensure sample marginal returns a valid sample
 */
void testSamplePairwise() {
    // Define entities and relations
    // Generate a sample
    // specify filter criteria
    // test sample to ensure that it meets criteria
}

/**
 *  Ensure sample marginal returns a valid sample
 */
void testSamplePairwiseCausal() {
    // Define entities and relations
    // Generate a sample
    // specify filter criteria
    // test sample to ensure that it meets criteria
}

int main() {
    cout << "-- TESTS BEGIN --" << endl << endl;

//    testRedisSet();
//    testRedisGet();
//    testRedisKeys();
//    md5Hashing();
//    testRedisIO();
//    testRegexForTypes();
//    testOrderPairAlphaNumeric();

    // testJSONEntityEncoding();
    // testJSONRelationEncoding();
    // testFieldAssignTypeMismatchInteger();
    // testFieldAssignTypeMismatchFloat();
    // testFieldAssignTypeMismatchString();
    // testCountRelations();
    testComputeMarginal();
    // testRelation_toJson();

    cout << endl << "-- TESTS END --" << endl;

    return 0;
}
<|endoftext|>