<commit_before>// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License

#include <string>
#include <vector>

#include <gtest/gtest.h>

#include <stout/gtest.hpp>
#include <stout/linkedhashmap.hpp>

using std::string;
using std::vector;

TEST(LinkedHashmapTest, Put)
{
  LinkedHashMap<string, int> map;

  map["foo"] = 1;
  ASSERT_SOME_EQ(1, map.get("foo"));
  ASSERT_EQ(1u, map.size());

  map["bar"] = 2;
  ASSERT_SOME_EQ(2, map.get("bar"));
  ASSERT_EQ(2u, map.size());

  map["foo"] = 3;
  ASSERT_SOME_EQ(3, map.get("foo"));
  ASSERT_EQ(2u, map.size());
}

TEST(LinkedHashmapTest, Contains)
{
  LinkedHashMap<string, int> map;
  map["foo"] = 1;
  map["bar"] = 2;
  ASSERT_TRUE(map.contains("foo"));
  ASSERT_TRUE(map.contains("bar"));
  ASSERT_FALSE(map.contains("caz"));
}

TEST(LinkedHashmapTest, Erase)
{
  LinkedHashMap<string, int> map;

  map["foo"] = 1;
  map["bar"] = 2;
  ASSERT_EQ(2u, map.size());

  ASSERT_EQ(1u, map.erase("foo"));
  ASSERT_EQ(0u, map.erase("caz")); // Non-existent key.
  ASSERT_NONE(map.get("foo"));
  ASSERT_EQ(1u, map.size());
  ASSERT_SOME_EQ(2, map.get("bar"));
}

TEST(LinkedHashmapTest, Keys)
{
  LinkedHashMap<string, int> map;

  vector<string> keys = {"foo", "bar", "food", "rad", "cat"};

  // Insert keys into the map.
  foreach (const string& key, keys) {
    map[key] = 1;
  }
  map["foo"] = 1; // Re-insert a key.

  // Ensure the keys returned are the same as insertion order.
  ASSERT_EQ(keys, map.keys());
}

TEST(LinkedHashmapTest, Values)
{
  LinkedHashMap<string, int> map;

  map["foo"] = 1;
  map["bar"] = 2;
  map["caz"] = 3;

  int val = 0;
  foreach (int value, map.values()) {
    ++val;
    ASSERT_EQ(val, value);
  }
}

TEST(LinkedHashMapTest, Foreach)
{
  LinkedHashMap<string, int> map;

  map["foo"] = 1;
  map["bar"] = 2;
  map["caz"] = 3;

  map["foo"] = 4; // Re-insert a key.

  vector<string> keyList = map.keys();
  vector<int> valueList = map.values();

  vector<string> keys{keyList.begin(), keyList.end()};
  vector<int> values{valueList.begin(), valueList.end()};

  {
    int i = 0;
    foreachpair (const string& key, int value, map) {
      EXPECT_EQ(keys[i], key);
      EXPECT_EQ(values[i], value);
      i++;
    }
  }

  {
    int i = 0;
    foreachkey (const string& key, map) {
      EXPECT_EQ(keys[i], key);
      i++;
    }
  }

  {
    int i = 0;
    foreachvalue (int value, map) {
      EXPECT_EQ(values[i], value);
      i++;
    }
  }
}

// Check that `foreach`-style loops can be used with a const ref to
// LinkedHashMap.
TEST(LinkedHashMapTest, ForeachConst)
{
  LinkedHashMap<string, int> map;

  map["foo"] = 1;
  map["bar"] = 2;
  map["caz"] = 3;

  const LinkedHashMap<string, int>& constMap = map;

  foreachkey (const string& key, constMap) {
    EXPECT_NE("qux", key);
  }
  foreachvalue (int value, constMap) {
    EXPECT_NE(0, value);
  }
}

TEST(LinkedHashMapTest, ForeachMutate)
{
  LinkedHashMap<int, string> map;

  map[1] = "foo";
  map[2] = "bar";
  map[3] = "caz";

  foreachpair (int key, string& value, map) {
    if (key == 2) {
      value = "qux";
    }
  }

  vector<string> values = {"foo", "qux", "caz"};
  EXPECT_EQ(values, map.values());
}

// TODO(bmahler): Simplify this test once LinkedHashMap
// has equality operators.
TEST(LinkedHashMapTest, CopyConstruction)
{
  LinkedHashMap<int, string> map;

  map[1] = "1";
  map[2] = "2";
  map[3] = "3";

  LinkedHashMap<int, string> copy(map);

  EXPECT_EQ(map.keys(), copy.keys());
  EXPECT_EQ(map.values(), copy.values());

  EXPECT_EQ(1u, map.erase(1));
  EXPECT_EQ(1u, copy.erase(1));

  EXPECT_EQ(map.keys(), copy.keys());
  EXPECT_EQ(map.values(), copy.values());

  copy[4] = "4";

  EXPECT_NE(map.keys(), copy.keys());
  EXPECT_NE(map.values(), copy.values());
}

// TODO(bmahler): Simplify this test once LinkedHashMap
// has equality operators.
TEST(LinkedHashMapTest, Assignment)
{
  LinkedHashMap<int, string> map;

  map[1] = "1";
  map[2] = "2";
  map[3] = "3";

  LinkedHashMap<int, string> copy;
  copy = map;

  EXPECT_EQ(map.keys(), copy.keys());
  EXPECT_EQ(map.values(), copy.values());

  EXPECT_EQ(1u, map.erase(1));
  EXPECT_EQ(1u, copy.erase(1));

  EXPECT_EQ(map.keys(), copy.keys());
  EXPECT_EQ(map.values(), copy.values());

  copy[4] = "4";

  EXPECT_NE(map.keys(), copy.keys());
  EXPECT_NE(map.values(), copy.values());

  // Test self-assignment.
  copy = map;
  map = map;

  EXPECT_EQ(copy.keys(), map.keys());
  EXPECT_EQ(copy.values(), map.values());
}
<commit_msg>Fixed some clang-tidy warnings: disable lint for self-assignment test.<commit_after>// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License

#include <string>
#include <vector>

#include <gtest/gtest.h>

#include <stout/gtest.hpp>
#include <stout/linkedhashmap.hpp>

using std::string;
using std::vector;

TEST(LinkedHashmapTest, Put)
{
  LinkedHashMap<string, int> map;

  map["foo"] = 1;
  ASSERT_SOME_EQ(1, map.get("foo"));
  ASSERT_EQ(1u, map.size());

  map["bar"] = 2;
  ASSERT_SOME_EQ(2, map.get("bar"));
  ASSERT_EQ(2u, map.size());

  map["foo"] = 3;
  ASSERT_SOME_EQ(3, map.get("foo"));
  ASSERT_EQ(2u, map.size());
}

TEST(LinkedHashmapTest, Contains)
{
  LinkedHashMap<string, int> map;
  map["foo"] = 1;
  map["bar"] = 2;
  ASSERT_TRUE(map.contains("foo"));
  ASSERT_TRUE(map.contains("bar"));
  ASSERT_FALSE(map.contains("caz"));
}

TEST(LinkedHashmapTest, Erase)
{
  LinkedHashMap<string, int> map;

  map["foo"] = 1;
  map["bar"] = 2;
  ASSERT_EQ(2u, map.size());

  ASSERT_EQ(1u, map.erase("foo"));
  ASSERT_EQ(0u, map.erase("caz")); // Non-existent key.
  ASSERT_NONE(map.get("foo"));
  ASSERT_EQ(1u, map.size());
  ASSERT_SOME_EQ(2, map.get("bar"));
}

TEST(LinkedHashmapTest, Keys)
{
  LinkedHashMap<string, int> map;

  vector<string> keys = {"foo", "bar", "food", "rad", "cat"};

  // Insert keys into the map.
  foreach (const string& key, keys) {
    map[key] = 1;
  }
  map["foo"] = 1; // Re-insert a key.

  // Ensure the keys returned are the same as insertion order.
  ASSERT_EQ(keys, map.keys());
}

TEST(LinkedHashmapTest, Values)
{
  LinkedHashMap<string, int> map;

  map["foo"] = 1;
  map["bar"] = 2;
  map["caz"] = 3;

  int val = 0;
  foreach (int value, map.values()) {
    ++val;
    ASSERT_EQ(val, value);
  }
}

TEST(LinkedHashMapTest, Foreach)
{
  LinkedHashMap<string, int> map;

  map["foo"] = 1;
  map["bar"] = 2;
  map["caz"] = 3;

  map["foo"] = 4; // Re-insert a key.

  vector<string> keyList = map.keys();
  vector<int> valueList = map.values();

  vector<string> keys{keyList.begin(), keyList.end()};
  vector<int> values{valueList.begin(), valueList.end()};

  {
    int i = 0;
    foreachpair (const string& key, int value, map) {
      EXPECT_EQ(keys[i], key);
      EXPECT_EQ(values[i], value);
      i++;
    }
  }

  {
    int i = 0;
    foreachkey (const string& key, map) {
      EXPECT_EQ(keys[i], key);
      i++;
    }
  }

  {
    int i = 0;
    foreachvalue (int value, map) {
      EXPECT_EQ(values[i], value);
      i++;
    }
  }
}

// Check that `foreach`-style loops can be used with a const ref to
// LinkedHashMap.
TEST(LinkedHashMapTest, ForeachConst)
{
  LinkedHashMap<string, int> map;

  map["foo"] = 1;
  map["bar"] = 2;
  map["caz"] = 3;

  const LinkedHashMap<string, int>& constMap = map;

  foreachkey (const string& key, constMap) {
    EXPECT_NE("qux", key);
  }
  foreachvalue (int value, constMap) {
    EXPECT_NE(0, value);
  }
}

TEST(LinkedHashMapTest, ForeachMutate)
{
  LinkedHashMap<int, string> map;

  map[1] = "foo";
  map[2] = "bar";
  map[3] = "caz";

  foreachpair (int key, string& value, map) {
    if (key == 2) {
      value = "qux";
    }
  }

  vector<string> values = {"foo", "qux", "caz"};
  EXPECT_EQ(values, map.values());
}

// TODO(bmahler): Simplify this test once LinkedHashMap
// has equality operators.
TEST(LinkedHashMapTest, CopyConstruction)
{
  LinkedHashMap<int, string> map;

  map[1] = "1";
  map[2] = "2";
  map[3] = "3";

  LinkedHashMap<int, string> copy(map);

  EXPECT_EQ(map.keys(), copy.keys());
  EXPECT_EQ(map.values(), copy.values());

  EXPECT_EQ(1u, map.erase(1));
  EXPECT_EQ(1u, copy.erase(1));

  EXPECT_EQ(map.keys(), copy.keys());
  EXPECT_EQ(map.values(), copy.values());

  copy[4] = "4";

  EXPECT_NE(map.keys(), copy.keys());
  EXPECT_NE(map.values(), copy.values());
}

// TODO(bmahler): Simplify this test once LinkedHashMap
// has equality operators.
TEST(LinkedHashMapTest, Assignment)
{
  LinkedHashMap<int, string> map;

  map[1] = "1";
  map[2] = "2";
  map[3] = "3";

  LinkedHashMap<int, string> copy;
  copy = map;

  EXPECT_EQ(map.keys(), copy.keys());
  EXPECT_EQ(map.values(), copy.values());

  EXPECT_EQ(1u, map.erase(1));
  EXPECT_EQ(1u, copy.erase(1));

  EXPECT_EQ(map.keys(), copy.keys());
  EXPECT_EQ(map.values(), copy.values());

  copy[4] = "4";

  EXPECT_NE(map.keys(), copy.keys());
  EXPECT_NE(map.values(), copy.values());

  // Test self-assignment.
  copy = map;
  map = map;  // NOLINT(clang-diagnostic-self-assign-overloaded)

  EXPECT_EQ(copy.keys(), map.keys());
  EXPECT_EQ(copy.values(), map.values());
}
<|endoftext|>


<commit_before>/***************************************************************************
*   Copyright © 2003 Unai Garro <ugarro@gmail.com>                        *
*                                                                         *
*   This program is free software; you can redistribute it and/or modify  *
*   it under the terms of the GNU General Public License as published by  *
*   the Free Software Foundation; either version 2 of the License, or     *
*   (at your option) any later version.                                   *
***************************************************************************/
#include "paneldeco.h"

#include <QPainter>
#include <qpoint.h>
#include <QRect>
//Added by qt3to4:
#include <QChildEvent>
#include <QPaintEvent>
#include <QVBoxLayout>

#include <kiconloader.h>
#include <kvbox.h>

// Panel decoration

PanelDeco::PanelDeco( QWidget *parent, const char *name, const QString &title, const QString &iconName ):
	QWidget( parent )
{
	QVBoxLayout * lay = new QVBoxLayout;

	tDeco = new TopDeco( this, "TopDecoration", title, iconName );
	lay->addWidget( tDeco );

	stack = new QStackedWidget;
	lay->addWidget( stack );

	stack->setSizePolicy( QSizePolicy( QSizePolicy::MinimumExpanding, QSizePolicy::MinimumExpanding ) );
	setLayout( lay );
}

PanelDeco::~PanelDeco()
{
}

void PanelDeco::addStackWidget( QWidget *w )
{
	stack->addWidget( w );
}

int PanelDeco::id( QWidget* w )
{
	return ( stack->indexOf( w ) );
}

void PanelDeco::raise( QWidget *w )
{
	QWidget * old_w = visiblePanel();

	stack->setCurrentWidget( w );

	if ( old_w != w )
		emit panelRaised( w, old_w );
}

QWidget* PanelDeco::visiblePanel( void )
{
	return ( stack->currentWidget() );
}

void PanelDeco::setHeader( const QString &title, const QString &icon )
{
	tDeco->setHeader( title, icon );
}

// Top part of the decoration

TopDeco::TopDeco( QWidget *parent, const char *name, const QString &title, const QString &iconName ) :
	QWidget( parent, Qt::WNoAutoErase )
{
	setObjectName( name );
	setMinimumHeight( 30 );
	panelTitle = QString();
	if ( !iconName.isEmpty() ) {
		icon = KIconLoader::global()->loadIcon( iconName, KIconLoader::NoGroup, 22 );
	}

	if ( !title.isEmpty() ) {
		panelTitle = title;
	}
}

TopDeco::~TopDeco()
{
}

void TopDeco::paintEvent( QPaintEvent * )
{
	// Get gradient colors
	QColor c1 = palette().color( QPalette::Light );
	QColor c2 = palette().color(backgroundRole());

	// Add a line on top
	QPainter painter(this );
	painter.setPen( palette().color( QPalette::Dark ));
	painter.drawLine( 0, 0, width(), 0 );

	QLinearGradient linearGrad(QPointF(0, 0), QPointF(0, height()) );
	linearGrad.setColorAt(0, c1);
	linearGrad.setColorAt(1, c2);
	QBrush brush( linearGrad );
	painter.fillRect( QRect( 0, 0, width(), height() ),brush );

	// Now Add the iconName
	int xpos = 0, ypos = 0;
	if ( !icon.isNull() ) {
		xpos = 20;
		ypos = ( height() - icon.height() ) / 2 - 1;
		painter.drawPixmap( xpos, ypos, icon );
		xpos += icon.width(); // Move it so that later we can easily place the text
	}

	// Finally, draw the text besides the icon
	if ( !panelTitle.isEmpty() ) {
		xpos += 15;
		QRect r = rect();
		r.setLeft( xpos );
		painter.setPen( palette().color( QPalette::WindowText  ));
		QFont ft = font();
		ft.setBold( true );
		painter.setFont( ft );
		painter.drawText( r, Qt::AlignVCenter, panelTitle );
	}
	painter.end();
}

void TopDeco::setHeader( const QString &title, const QString &iconName )
{
	if ( !title.isEmpty() )
		panelTitle = title;
	if ( !iconName.isEmpty() ) {
		icon = KIconLoader::global()->loadIcon( iconName, KIconLoader::NoGroup, 22 );
	}
	if ( !title.isEmpty() || !iconName.isEmpty() )
		update();
}

QSize TopDeco::sizeHint( void ) const
{
	return ( QSize( parentWidget() ->width(), 30 ) );
}

#include "paneldeco.moc"

<commit_msg>Fix Krazy warnings: nullstrassign - src/widgets/paneldeco.cpp<commit_after>/***************************************************************************
*   Copyright © 2003 Unai Garro <ugarro@gmail.com>                        *
*                                                                         *
*   This program is free software; you can redistribute it and/or modify  *
*   it under the terms of the GNU General Public License as published by  *
*   the Free Software Foundation; either version 2 of the License, or     *
*   (at your option) any later version.                                   *
***************************************************************************/
#include "paneldeco.h"

#include <QPainter>
#include <qpoint.h>
#include <QRect>
//Added by qt3to4:
#include <QChildEvent>
#include <QPaintEvent>
#include <QVBoxLayout>

#include <kiconloader.h>
#include <kvbox.h>

// Panel decoration

PanelDeco::PanelDeco( QWidget *parent, const char *name, const QString &title, const QString &iconName ):
	QWidget( parent )
{
	QVBoxLayout * lay = new QVBoxLayout;

	tDeco = new TopDeco( this, "TopDecoration", title, iconName );
	lay->addWidget( tDeco );

	stack = new QStackedWidget;
	lay->addWidget( stack );

	stack->setSizePolicy( QSizePolicy( QSizePolicy::MinimumExpanding, QSizePolicy::MinimumExpanding ) );
	setLayout( lay );
}

PanelDeco::~PanelDeco()
{
}

void PanelDeco::addStackWidget( QWidget *w )
{
	stack->addWidget( w );
}

int PanelDeco::id( QWidget* w )
{
	return ( stack->indexOf( w ) );
}

void PanelDeco::raise( QWidget *w )
{
	QWidget * old_w = visiblePanel();

	stack->setCurrentWidget( w );

	if ( old_w != w )
		emit panelRaised( w, old_w );
}

QWidget* PanelDeco::visiblePanel( void )
{
	return ( stack->currentWidget() );
}

void PanelDeco::setHeader( const QString &title, const QString &icon )
{
	tDeco->setHeader( title, icon );
}

// Top part of the decoration

TopDeco::TopDeco( QWidget *parent, const char *name, const QString &title, const QString &iconName ) :
	QWidget( parent, Qt::WNoAutoErase )
{
	setObjectName( name );
	setMinimumHeight( 30 );
	panelTitle.clear();
	if ( !iconName.isEmpty() ) {
		icon = KIconLoader::global()->loadIcon( iconName, KIconLoader::NoGroup, 22 );
	}

	if ( !title.isEmpty() ) {
		panelTitle = title;
	}
}

TopDeco::~TopDeco()
{
}

void TopDeco::paintEvent( QPaintEvent * )
{
	// Get gradient colors
	QColor c1 = palette().color( QPalette::Light );
	QColor c2 = palette().color(backgroundRole());

	// Add a line on top
	QPainter painter(this );
	painter.setPen( palette().color( QPalette::Dark ));
	painter.drawLine( 0, 0, width(), 0 );

	QLinearGradient linearGrad(QPointF(0, 0), QPointF(0, height()) );
	linearGrad.setColorAt(0, c1);
	linearGrad.setColorAt(1, c2);
	QBrush brush( linearGrad );
	painter.fillRect( QRect( 0, 0, width(), height() ),brush );

	// Now Add the iconName
	int xpos = 0, ypos = 0;
	if ( !icon.isNull() ) {
		xpos = 20;
		ypos = ( height() - icon.height() ) / 2 - 1;
		painter.drawPixmap( xpos, ypos, icon );
		xpos += icon.width(); // Move it so that later we can easily place the text
	}

	// Finally, draw the text besides the icon
	if ( !panelTitle.isEmpty() ) {
		xpos += 15;
		QRect r = rect();
		r.setLeft( xpos );
		painter.setPen( palette().color( QPalette::WindowText  ));
		QFont ft = font();
		ft.setBold( true );
		painter.setFont( ft );
		painter.drawText( r, Qt::AlignVCenter, panelTitle );
	}
	painter.end();
}

void TopDeco::setHeader( const QString &title, const QString &iconName )
{
	if ( !title.isEmpty() )
		panelTitle = title;
	if ( !iconName.isEmpty() ) {
		icon = KIconLoader::global()->loadIcon( iconName, KIconLoader::NoGroup, 22 );
	}
	if ( !title.isEmpty() || !iconName.isEmpty() )
		update();
}

QSize TopDeco::sizeHint( void ) const
{
	return ( QSize( parentWidget() ->width(), 30 ) );
}

#include "paneldeco.moc"

<|endoftext|>


<commit_before>/**
 * \file nblock_graph.cc
 *
 *
 *
 * \author Ethan Burns
 * \date 2008-10-20
 */

#include <assert.h>
#include <pthread.h>
#include <errno.h>

#include <limits>
#include <iostream>
#include <list>
#include <map>
#include <vector>

#include "../closed_list.h"
#include "../pq_open_list.h"
#include "../open_list.h"
#include "../projection.h"
#include "nblock.h"
#include "nblock_graph.h"

using namespace std;
using namespace WPBNF;

/**
 * Create the nblock with the given ID.
 */
NBlock *NBlockGraph::create_nblock(unsigned int id)
{
	NBlock *n = new NBlock(project, id);

	nblocks_created += 1;

	return n;
}

/**
 * Apparently gdb can't single step inside a c++ constructor... so we
 * just call this function in the constructor so that we can see what
 * is going on.
 */
void NBlockGraph::cpp_is_a_bad_language(const Projection *p, State *initial)
{
	unsigned int init_nblock = p->project(initial);

	nblocks_created = 0;
	project = p;
	num_sigma_zero = num_nblocks = p->get_num_nblocks();
	assert(init_nblock < num_nblocks);

	map.set_observer(this);

	NBlock *n = map.get(init_nblock);
	n->open.add(initial);
	free_list.add(n);

	done = false;

	pthread_mutex_init(&mutex, NULL);
	pthread_cond_init(&cond, NULL);

	nblocks_assigned = 0;
	nblocks_assigned_max = 0;
}

/**
 * Create a new NBlock graph.
 * \param p The projection function.
 */
NBlockGraph::NBlockGraph(const Projection *p, State *initial)
	: map(p)
{
	cpp_is_a_bad_language(p, initial);
}

/**
 * Destroy an NBlock graph.
 */
NBlockGraph::~NBlockGraph()
{
}

/**
 * Get the next nblock for expansion, possibly release a finished
 * nblock.  The next nblock is the one with the minimum f-value.
 *
 * \note This call will block if there are currently no free nblocks.
 * \param finished If non-NULL, the finished nblock will be released
 *        into the next level's free_list.
 * \param trylock Set to true if a trylock should be attempted instead
 *                of a lock.
 * \return The next NBlock to expand or NULL if there is nothing left
 *         to do.
 */
NBlock *NBlockGraph::next_nblock(NBlock *finished, bool trylock)
{
	NBlock *n = NULL;

	// Take the lock, but if someone else already has it, just
	// keep going.
	if (trylock && finished && !finished->open.empty()) {
		if (pthread_mutex_trylock(&mutex) == EBUSY)
			return finished;
	} else if(pthread_mutex_trylock(&mutex) == EBUSY)
		pthread_mutex_lock(&mutex);

	if (finished) {		// Release an NBlock
		// Sanity check.
		if (finished->sigma != 0) {
			cerr << "A proc had an NBlock with sigma != 0" << endl;
			finished->print(cerr);
			cerr << endl << endl << endl;
			__print(cerr);
		}
		assert(finished->sigma == 0);

		// Re-sort the nblock PQ so that we can get the f_min value.
		if (nblock_pq.peek() == finished) {
			// if we were looking at the best block, we
			// need to update the successors too incase we
			// are no longer the best block but one of
			// them are.
			set<unsigned int>::iterator iter;
			for (iter = finished->succs.begin(); iter != finished->succs.end(); iter++) {
				NBlock *n = map.find(*iter);
				if (n)
					nblock_pq.elem_changed(n->pq_index);
			}
		}
		nblock_pq.elem_changed(finished->pq_index);
		f_min.set(nblock_pq.peek()->open.get_best_f());

		// Test if this nblock is still worse than the front
		// of the free list.  If not, then just keep searching
		// it.
		if (!finished->open.empty()) {
			fp_type cur_f = finished->open.get_best_f();
			fp_type new_f;
			if (free_list.empty())
				new_f = fp_infinity;
			else
				new_f = free_list.best_f();
			if (cur_f <= new_f) {
				n = finished;
				goto out;
			}
		}

		nblocks_assigned -= 1;

		// Possibly add this block back to the free list.
		if (is_free(finished)) {
			free_list.add(finished);
			pthread_cond_broadcast(&cond);
		}
		finished->inuse = false;
		update_scope_sigmas(finished->id, -1);

		if (free_list.empty() && num_sigma_zero == num_nblocks) {
			__set_done();
//			__print(cerr);
			goto out;
		}

	}

	while (!done && free_list.empty())
		pthread_cond_wait(&cond, &mutex);

	if (done)
		goto out;

	n = free_list.take();
	nblocks_assigned += 1;
	if (nblocks_assigned > nblocks_assigned_max)
		nblocks_assigned_max = nblocks_assigned;
	n->inuse = true;
	update_scope_sigmas(n->id, 1);

/*
  for (set<NBlock *>::iterator iter = n->interferes.begin();
  iter != n->interferes.end();
  iter++)
  assert((*iter)->sigma > 0);
*/
out:
	pthread_mutex_unlock(&mutex);

	return n;
}

/**
 * Get the best NBlock in the interference scope of b which is not free.
 */
NBlock *NBlockGraph::best_in_scope(NBlock *b)
{
	NBlock *best_b = NULL;
	fp_type best_f = fp_infinity;
	set<unsigned int>::iterator i;

//	pthread_mutex_lock(&mutex);

	for (i = b->interferes.begin(); i != b->interferes.end(); i++) {
		NBlock *b = map.find(*i);
		if (!b)
			continue;
		if (b->open.empty())
			continue;
		if (!best_b || b->open.get_best_f() < best_f) {
			best_f = b->open.get_best_f();
			best_b = b;
		}
	}

//	pthread_mutex_unlock(&mutex);

	// best_b => best_f != fp_infinity
//	assert(best_f != fp_infinity || !best_b);

	return best_b;
}

/**
 * Get the NBlock given by the hash value.
 */
NBlock *NBlockGraph::get_nblock(unsigned int hash)
{
	return map.get(hash);
}

/**
 * Get the statistics on the maximum number of NBlocks assigned at one time.
 */
unsigned int NBlockGraph::get_max_assigned_nblocks(void) const
{

	return nblocks_assigned_max;
}

/**
 * Get the value of the best nblock on the free list.
 */
fp_type NBlockGraph::best_free_f(void){
	if (free_list.empty())
		return 0.0;
	else
		return free_list.best_f();
}

/**
 * Get the global f_min value.
 */
fp_type NBlockGraph::get_f_min(void)
{
	return f_min.read();
}

/**
 * Print an NBlock, but don't take the lock.
 */
void NBlockGraph::__print(ostream &o)
{

	o << "Number of NBlocks: " << num_nblocks << endl;
	o << "Number of NBlocks with sigma zero: " << num_sigma_zero << endl;
	o << "--------------------" << endl;
	o << "Free Blocks:" << endl;
	free_list.print(o);
	o << "--------------------" << endl;
	o << "All Blocks:" << endl;
	for (unsigned int i = 0; i < num_nblocks; i += 1)
		if (map.find(i))
			map.find(i)->print(o);
}

/**
 * Print an NBlockGraph to the given stream.
 */
void NBlockGraph::print(ostream &o)
{
	pthread_mutex_lock(&mutex);
	__print(o);
	pthread_mutex_unlock(&mutex);
}

/**
 * Update the sigmas by delta for all of the predecessors of y and all
 * of the predecessors of the successors of y.
 */
void NBlockGraph::update_scope_sigmas(unsigned int y, int delta)
{
	set<unsigned int>::iterator iter;
	NBlock *n = map.get(y);

	assert(n->sigma == 0);

	/*
	  \A y' \in predecessors(y) /\ y' /= y,
	  \sigma(y') <- \sigma(y') +- 1

	  \A y' \in successors(y),
	  \A y'' \in predecessors(y'), /\ y'' /= y,
	  \sigma(y'') <- \sigma(y'') +- 1
	*/

	for (iter = n->interferes.begin();
	     iter != n->interferes.end();
	     iter++) {
		NBlock *m = map.get(*iter);
		if (m->sigma == 0) {
			assert(delta > 0);
			if (is_free(m))
				free_list.remove(m);
			num_sigma_zero -= 1;
		}
		m->sigma += delta;
		if (m->sigma == 0) {
			if (m->hot)
				set_cold(m);
			if (is_free(m)) {
				free_list.add(m);
				pthread_cond_broadcast(&cond);
			}
			num_sigma_zero += 1;
		}
	}
}

/**
 * Get the f-value of the next best NBlock.
 */
fp_type NBlockGraph::next_nblock_f_value(void)
{
	// this is atomic
	return free_list.best_f();
}

/**
 * Sets the done flag with out taking the lock.
 */
void NBlockGraph::__set_done(void)
{
	done = true;
	pthread_cond_broadcast(&cond);
}

/**
 * Sets the done flag.
 */
void NBlockGraph::set_done(void)
{
	pthread_mutex_lock(&mutex);
	__set_done();
	pthread_mutex_unlock(&mutex);
}

/**
 * Test if an NBlock is free.
 */
bool NBlockGraph::is_free(NBlock *b)
{
	return !b->inuse
		&& b->sigma == 0
		&& b->sigma_hot == 0
		&& !b->open.empty();
}

/**
 * Mark an NBlock as hot, we want this one.
 */
void NBlockGraph::set_hot(NBlock *b)
{
	set<unsigned int>::iterator i;
	fp_type f = b->open.get_best_f();

	if(pthread_mutex_trylock(&mutex) == EBUSY)
		pthread_mutex_lock(&mutex);

	if (!b->hot && b->sigma > 0) {
		for (i = b->interferes.begin(); i != b->interferes.end(); i++) {
			assert(b->id != *i);
			NBlock *m = map.get(*i);
			if (m->hot && m->open.get_best_f() < f)
				goto out;
		}

		b->hot = true;
		for (i = b->interferes.begin(); i != b->interferes.end(); i++) {
			assert(b->id != *i);
			NBlock *m = map.get(*i);
			if (is_free(m))
				free_list.remove(m);
			if (m->hot)
				set_cold(m);
			m->sigma_hot += 1;
		}
	}
out:
	pthread_mutex_unlock(&mutex);
}

/**
 * Mark an NBlock as cold.  The mutex must be held *before* this
 * function is called.n
 */
void NBlockGraph::set_cold(NBlock *b)
{
	set<unsigned int>::iterator i;

	b->hot = false;
	for (i = b->interferes.begin(); i != b->interferes.end(); i++) {
		assert(b->id != *i);
		NBlock *m = map.get(*i);
		m->sigma_hot -= 1;
		if (is_free(m)) {
			free_list.add(m);
			pthread_cond_broadcast(&cond);
		}
	}
}

/**
 * We won't release block b, so set all hot blocks in its interference
 * scope back to cold.
 */
void NBlockGraph::wont_release(NBlock *b)
{
	set<unsigned int>::iterator iter;

	if(pthread_mutex_trylock(&mutex) == EBUSY)
		pthread_mutex_lock(&mutex);

	for (iter = b->interferes.begin();
	     iter != b->interferes.end();
	     iter++) {
		NBlock *m = map.find(*iter);
		if (!m)
			continue;
		if (m->hot)
			set_cold(m);
	}

	pthread_mutex_unlock(&mutex);
}

/**
 * Get the number of nblocks which were actually created.
 */
unsigned int NBlockGraph::get_ncreated_nblocks(void)
{
	return map.get_num_created();;
}

/**
 * This is where the NBlockMap notifies us of the creation of a new nblock.
 */
void NBlockGraph::observe(NBlock *b)
{
	nblock_pq.add(b);
}
<commit_msg>When releasing an nblock: reheapify the block and its successors.<commit_after>/**
 * \file nblock_graph.cc
 *
 *
 *
 * \author Ethan Burns
 * \date 2008-10-20
 */

#include <assert.h>
#include <pthread.h>
#include <errno.h>

#include <limits>
#include <iostream>
#include <list>
#include <map>
#include <vector>

#include "../closed_list.h"
#include "../pq_open_list.h"
#include "../open_list.h"
#include "../projection.h"
#include "nblock.h"
#include "nblock_graph.h"

using namespace std;
using namespace WPBNF;

/**
 * Create the nblock with the given ID.
 */
NBlock *NBlockGraph::create_nblock(unsigned int id)
{
	NBlock *n = new NBlock(project, id);

	nblocks_created += 1;

	return n;
}

/**
 * Apparently gdb can't single step inside a c++ constructor... so we
 * just call this function in the constructor so that we can see what
 * is going on.
 */
void NBlockGraph::cpp_is_a_bad_language(const Projection *p, State *initial)
{
	unsigned int init_nblock = p->project(initial);

	nblocks_created = 0;
	project = p;
	num_sigma_zero = num_nblocks = p->get_num_nblocks();
	assert(init_nblock < num_nblocks);

	map.set_observer(this);

	NBlock *n = map.get(init_nblock);
	n->open.add(initial);
	free_list.add(n);

	done = false;

	pthread_mutex_init(&mutex, NULL);
	pthread_cond_init(&cond, NULL);

	nblocks_assigned = 0;
	nblocks_assigned_max = 0;
}

/**
 * Create a new NBlock graph.
 * \param p The projection function.
 */
NBlockGraph::NBlockGraph(const Projection *p, State *initial)
	: map(p)
{
	cpp_is_a_bad_language(p, initial);
}

/**
 * Destroy an NBlock graph.
 */
NBlockGraph::~NBlockGraph()
{
}

/**
 * Get the next nblock for expansion, possibly release a finished
 * nblock.  The next nblock is the one with the minimum f-value.
 *
 * \note This call will block if there are currently no free nblocks.
 * \param finished If non-NULL, the finished nblock will be released
 *        into the next level's free_list.
 * \param trylock Set to true if a trylock should be attempted instead
 *                of a lock.
 * \return The next NBlock to expand or NULL if there is nothing left
 *         to do.
 */
NBlock *NBlockGraph::next_nblock(NBlock *finished, bool trylock)
{
	NBlock *n = NULL;

	// Take the lock, but if someone else already has it, just
	// keep going.
	if (trylock && finished && !finished->open.empty()) {
		if (pthread_mutex_trylock(&mutex) == EBUSY)
			return finished;
	} else if(pthread_mutex_trylock(&mutex) == EBUSY)
		pthread_mutex_lock(&mutex);

	if (finished) {		// Release an NBlock
		// Sanity check.
		if (finished->sigma != 0) {
			cerr << "A proc had an NBlock with sigma != 0" << endl;
			finished->print(cerr);
			cerr << endl << endl << endl;
			__print(cerr);
		}
		assert(finished->sigma == 0);

		// Re-sort the nblock PQ so that we can get the f_min value.
		set<unsigned int>::iterator iter;
		for (iter = finished->succs.begin(); iter != finished->succs.end(); iter++) {
			NBlock *n = map.find(*iter);
			if (n)
					nblock_pq.elem_changed(n->pq_index);
		}
		nblock_pq.elem_changed(finished->pq_index);
		f_min.set(nblock_pq.peek()->open.get_best_f());

		// Test if this nblock is still worse than the front
		// of the free list.  If not, then just keep searching
		// it.
		if (!finished->open.empty()) {
			fp_type cur_f = finished->open.get_best_f();
			fp_type new_f;
			if (free_list.empty())
				new_f = fp_infinity;
			else
				new_f = free_list.best_f();
			if (cur_f <= new_f) {
				n = finished;
				goto out;
			}
		}

		nblocks_assigned -= 1;

		// Possibly add this block back to the free list.
		if (is_free(finished)) {
			free_list.add(finished);
			pthread_cond_broadcast(&cond);
		}
		finished->inuse = false;
		update_scope_sigmas(finished->id, -1);

		if (free_list.empty() && num_sigma_zero == num_nblocks) {
			__set_done();
//			__print(cerr);
			goto out;
		}

	}

	while (!done && free_list.empty())
		pthread_cond_wait(&cond, &mutex);

	if (done)
		goto out;

	n = free_list.take();
	nblocks_assigned += 1;
	if (nblocks_assigned > nblocks_assigned_max)
		nblocks_assigned_max = nblocks_assigned;
	n->inuse = true;
	update_scope_sigmas(n->id, 1);

/*
  for (set<NBlock *>::iterator iter = n->interferes.begin();
  iter != n->interferes.end();
  iter++)
  assert((*iter)->sigma > 0);
*/
out:
	pthread_mutex_unlock(&mutex);

	return n;
}

/**
 * Get the best NBlock in the interference scope of b which is not free.
 */
NBlock *NBlockGraph::best_in_scope(NBlock *b)
{
	NBlock *best_b = NULL;
	fp_type best_f = fp_infinity;
	set<unsigned int>::iterator i;

//	pthread_mutex_lock(&mutex);

	for (i = b->interferes.begin(); i != b->interferes.end(); i++) {
		NBlock *b = map.find(*i);
		if (!b)
			continue;
		if (b->open.empty())
			continue;
		if (!best_b || b->open.get_best_f() < best_f) {
			best_f = b->open.get_best_f();
			best_b = b;
		}
	}

//	pthread_mutex_unlock(&mutex);

	// best_b => best_f != fp_infinity
//	assert(best_f != fp_infinity || !best_b);

	return best_b;
}

/**
 * Get the NBlock given by the hash value.
 */
NBlock *NBlockGraph::get_nblock(unsigned int hash)
{
	return map.get(hash);
}

/**
 * Get the statistics on the maximum number of NBlocks assigned at one time.
 */
unsigned int NBlockGraph::get_max_assigned_nblocks(void) const
{

	return nblocks_assigned_max;
}

/**
 * Get the value of the best nblock on the free list.
 */
fp_type NBlockGraph::best_free_f(void){
	if (free_list.empty())
		return 0.0;
	else
		return free_list.best_f();
}

/**
 * Get the global f_min value.
 */
fp_type NBlockGraph::get_f_min(void)
{
	return f_min.read();
}

/**
 * Print an NBlock, but don't take the lock.
 */
void NBlockGraph::__print(ostream &o)
{

	o << "Number of NBlocks: " << num_nblocks << endl;
	o << "Number of NBlocks with sigma zero: " << num_sigma_zero << endl;
	o << "--------------------" << endl;
	o << "Free Blocks:" << endl;
	free_list.print(o);
	o << "--------------------" << endl;
	o << "All Blocks:" << endl;
	for (unsigned int i = 0; i < num_nblocks; i += 1)
		if (map.find(i))
			map.find(i)->print(o);
}

/**
 * Print an NBlockGraph to the given stream.
 */
void NBlockGraph::print(ostream &o)
{
	pthread_mutex_lock(&mutex);
	__print(o);
	pthread_mutex_unlock(&mutex);
}

/**
 * Update the sigmas by delta for all of the predecessors of y and all
 * of the predecessors of the successors of y.
 */
void NBlockGraph::update_scope_sigmas(unsigned int y, int delta)
{
	set<unsigned int>::iterator iter;
	NBlock *n = map.get(y);

	assert(n->sigma == 0);

	/*
	  \A y' \in predecessors(y) /\ y' /= y,
	  \sigma(y') <- \sigma(y') +- 1

	  \A y' \in successors(y),
	  \A y'' \in predecessors(y'), /\ y'' /= y,
	  \sigma(y'') <- \sigma(y'') +- 1
	*/

	for (iter = n->interferes.begin();
	     iter != n->interferes.end();
	     iter++) {
		NBlock *m = map.get(*iter);
		if (m->sigma == 0) {
			assert(delta > 0);
			if (is_free(m))
				free_list.remove(m);
			num_sigma_zero -= 1;
		}
		m->sigma += delta;
		if (m->sigma == 0) {
			if (m->hot)
				set_cold(m);
			if (is_free(m)) {
				free_list.add(m);
				pthread_cond_broadcast(&cond);
			}
			num_sigma_zero += 1;
		}
	}
}

/**
 * Get the f-value of the next best NBlock.
 */
fp_type NBlockGraph::next_nblock_f_value(void)
{
	// this is atomic
	return free_list.best_f();
}

/**
 * Sets the done flag with out taking the lock.
 */
void NBlockGraph::__set_done(void)
{
	done = true;
	pthread_cond_broadcast(&cond);
}

/**
 * Sets the done flag.
 */
void NBlockGraph::set_done(void)
{
	pthread_mutex_lock(&mutex);
	__set_done();
	pthread_mutex_unlock(&mutex);
}

/**
 * Test if an NBlock is free.
 */
bool NBlockGraph::is_free(NBlock *b)
{
	return !b->inuse
		&& b->sigma == 0
		&& b->sigma_hot == 0
		&& !b->open.empty();
}

/**
 * Mark an NBlock as hot, we want this one.
 */
void NBlockGraph::set_hot(NBlock *b)
{
	set<unsigned int>::iterator i;
	fp_type f = b->open.get_best_f();

	if(pthread_mutex_trylock(&mutex) == EBUSY)
		pthread_mutex_lock(&mutex);

	if (!b->hot && b->sigma > 0) {
		for (i = b->interferes.begin(); i != b->interferes.end(); i++) {
			assert(b->id != *i);
			NBlock *m = map.get(*i);
			if (m->hot && m->open.get_best_f() < f)
				goto out;
		}

		b->hot = true;
		for (i = b->interferes.begin(); i != b->interferes.end(); i++) {
			assert(b->id != *i);
			NBlock *m = map.get(*i);
			if (is_free(m))
				free_list.remove(m);
			if (m->hot)
				set_cold(m);
			m->sigma_hot += 1;
		}
	}
out:
	pthread_mutex_unlock(&mutex);
}

/**
 * Mark an NBlock as cold.  The mutex must be held *before* this
 * function is called.n
 */
void NBlockGraph::set_cold(NBlock *b)
{
	set<unsigned int>::iterator i;

	b->hot = false;
	for (i = b->interferes.begin(); i != b->interferes.end(); i++) {
		assert(b->id != *i);
		NBlock *m = map.get(*i);
		m->sigma_hot -= 1;
		if (is_free(m)) {
			free_list.add(m);
			pthread_cond_broadcast(&cond);
		}
	}
}

/**
 * We won't release block b, so set all hot blocks in its interference
 * scope back to cold.
 */
void NBlockGraph::wont_release(NBlock *b)
{
	set<unsigned int>::iterator iter;

	if(pthread_mutex_trylock(&mutex) == EBUSY)
		pthread_mutex_lock(&mutex);

	for (iter = b->interferes.begin();
	     iter != b->interferes.end();
	     iter++) {
		NBlock *m = map.find(*iter);
		if (!m)
			continue;
		if (m->hot)
			set_cold(m);
	}

	pthread_mutex_unlock(&mutex);
}

/**
 * Get the number of nblocks which were actually created.
 */
unsigned int NBlockGraph::get_ncreated_nblocks(void)
{
	return map.get_num_created();;
}

/**
 * This is where the NBlockMap notifies us of the creation of a new nblock.
 */
void NBlockGraph::observe(NBlock *b)
{
	nblock_pq.add(b);
}
<|endoftext|>


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

#include <Eigen/Core>
#include <Eigen/Geometry>
using namespace Eigen;

#include <pangolin/pangolin.h>

int main( int argc, char** argv )
{
    pangolin::CreateWindowAndBind("main", 640, 480);
    glEnable(GL_DEPTH_TEST);

        pangolin::OpenGlRenderState s_cam(
        pangolin::ProjectionMatrix(640,480,420,420,320,240,0.2,100),
        pangolin::ModelViewLookAt(-2,2,-2, 0,0,0, pangolin::AxisY)
    );

    // Create Interactive View in window
    pangolin::Handler3D handler(s_cam);
    pangolin::View& d_cam = pangolin::CreateDisplay()
            .SetBounds(0.0, 1.0, 0.0, 1.0, -640.0f/480.0f)
            .SetHandler(&handler);

    while( !pangolin::ShouldQuit() )
    {
        // Clear screen and activate view to render into
        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
        d_cam.Activate(s_cam);

        // Render OpenGL Cube
        pangolin::glDrawColouredCube();

        // Swap frames and Process Events
        pangolin::FinishFrame();
    }
    return 0;
}<commit_msg>ch3 visualize geometry<commit_after>#include <iostream>
#include <iomanip>
using namespace std;

#include <Eigen/Core>
#include <Eigen/Geometry>
using namespace Eigen;

#include <pangolin/pangolin.h>

struct RotationMatrix
{
    Matrix3d matrix = Matrix3d::Identity();
};

ostream& operator << ( ostream& out, const RotationMatrix& r )
{
    out.setf(ios::fixed);
    Matrix3d matrix = r.matrix;
    out<<'=';
    out<<"["<<setprecision(2)<<matrix(0,0)<<","<<matrix(0,1)<<","<<matrix(0,2)<<"],"
    << "["<<matrix(1,0)<<","<<matrix(1,1)<<","<<matrix(1,2)<<"],"
    << "["<<matrix(2,0)<<","<<matrix(2,1)<<","<<matrix(2,2)<<"]";
    return out;
}

istream& operator >> (istream& in, RotationMatrix& r )
{
    return in;
}

struct TranslationVector
{
    Vector3d trans = Vector3d(0,0,0);
};

ostream& operator << (ostream& out, const TranslationVector& t)
{
    out<<"=["<<t.trans(0)<<','<<t.trans(1)<<','<<t.trans(2)<<"]";
    return out;
}

istream& operator >> ( istream& in, TranslationVector& t)
{
    return in;
}

struct QuaternionDraw
{
    Quaterniond q;
};

ostream& operator << (ostream& out, const QuaternionDraw quat )
{
    auto c = quat.q.coeffs();
    out<<"=["<<c[0]<<","<<c[1]<<","<<c[2]<<","<<c[3]<<"]";
    return out;
}

istream& operator >> (istream& in, const QuaternionDraw quat)
{
    return in;
}

int main ( int argc, char** argv )
{
    pangolin::CreateWindowAndBind ( "visualize geometry", 1000, 600 );
    glEnable ( GL_DEPTH_TEST );
    pangolin::OpenGlRenderState s_cam (
        pangolin::ProjectionMatrix ( 1000, 600, 420, 420, 500, 300, 0.1, 1000 ),
        pangolin::ModelViewLookAt ( 3,3,3,0,0,0,pangolin::AxisY )
    );

    const int UI_WIDTH = 500;

    pangolin::View& d_cam = pangolin::CreateDisplay().SetBounds(0.0, 1.0, pangolin::Attach::Pix(UI_WIDTH), 1.0, -1000.0f/600.0f).SetHandler(new pangolin::Handler3D(s_cam));

    // ui
    pangolin::Var<RotationMatrix> rotation_matrix("ui.R", RotationMatrix());
    pangolin::Var<TranslationVector> translation_vector("ui.t", TranslationVector());
    pangolin::Var<TranslationVector> euler_angles("ui.rpy", TranslationVector());
    pangolin::Var<QuaternionDraw> quaternion("ui.q", QuaternionDraw());
    pangolin::CreatePanel("ui")
        .SetBounds(0.0, 1.0, 0.0, pangolin::Attach::Pix(UI_WIDTH));

    while ( !pangolin::ShouldQuit() )
    {
        glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT );

        d_cam.Activate( s_cam );

        pangolin::OpenGlMatrix matrix = s_cam.GetModelViewMatrix();
        Matrix<double,4,4> m = matrix;
        // m = m.inverse();
        RotationMatrix R;
        for (int i=0; i<3; i++)
            for (int j=0; j<3; j++)
                R.matrix(i,j) = m(j,i);
        // R.matrix = R.matrix.transpose();
        rotation_matrix = R;

        TranslationVector t;
        t.trans = Vector3d(m(0,3), m(1,3), m(2,3));
        t.trans = -R.matrix*t.trans;
        translation_vector = t;

        TranslationVector euler;
        euler.trans = R.matrix.eulerAngles(2,0,1);
        euler_angles = euler;

        QuaternionDraw quat;
        quat.q = Quaterniond(R.matrix);
        quaternion = quat;

        glColor3f(1.0,1.0,1.0);

        pangolin::glDrawColouredCube();
        // draw the original axis
        glLineWidth(3);
        glColor3f ( 0.8f,0.f,0.f );
        glBegin ( GL_LINES );
        glVertex3f( 0,0,0 );
        glVertex3f( 10,0,0 );
        glColor3f( 0.f,0.8f,0.f);
        glVertex3f( 0,0,0 );
        glVertex3f( 0,10,0 );
        glColor3f( 0.2f,0.2f,1.f);
        glVertex3f( 0,0,0 );
        glVertex3f( 0,0,10 );
        glEnd();

        pangolin::FinishFrame();
    }
}
<|endoftext|>


<commit_before>#include "writer/exp_writer.h"

#include "iroha/i_design.h"
#include "iroha/logging.h"
#include "iroha/resource_class.h"
#include "iroha/resource_params.h"

namespace iroha {

ExpWriter::ExpWriter(const IDesign *design, ostream &os)
  : design_(design), os_(os) {
}

void ExpWriter::Write() {
  WriteResourceParams(*design_->GetParams(), "");
  for (auto *ch : design_->channels_) {
    WriteChannel(*ch);
  }
  for (auto *im : design_->array_images_) {
    WriteArrayImage(*im);
  }
  for (auto *mod : design_->modules_) {
    WriteModule(*mod);
  }
}

void ExpWriter::WriteModule(const IModule &mod) {
  os_ << "(MODULE " << mod.GetId() << " " << mod.GetName() << "\n";
  IModule *parent = mod.GetParentModule();
  if (parent != nullptr) {
    os_ << "  (PARENT " << parent->GetId() << ")\n";
  }
  WriteResourceParams(*mod.GetParams(), "  ");
  for (auto *tab : mod.tables_) {
    WriteTable(*tab);
  }
  os_ << ")\n";
}

void ExpWriter::WriteTable(const ITable &tab) {
  os_ << "  (TABLE " << tab.GetId();
  string name = tab.GetName();
  if (name.empty()) {
    os_ << " ()";
  } else {
    os_ << " " << name;
  }
  os_ << "\n";
  WriteRegisters(tab);
  WriteResources(tab);
  WriteInitialState(tab);
  for (auto *st : tab.states_) {
    WriteState(*st);
  }
  os_ << "  )\n";
}

void ExpWriter::WriteResources(const ITable &tab) {
  os_ << "    (RESOURCES\n";
  for (auto *res : tab.resources_) {
    WriteResource(*res);
  }
  os_ << "    )\n";
}

void ExpWriter::WriteResource(const IResource &res) {
  const IResourceClass &rc = *(res.GetClass());
  os_ << "      (RESOURCE " << res.GetId()
      << " " << res.GetClass()->GetName() << "\n";
  os_ << "        ";
  WriteResourceTypes(res.input_types_);
  os_ << " ";
  WriteResourceTypes(res.output_types_);
  os_ << "\n";
  ResourceParams *params = res.GetParams();
  WriteResourceParams(*params, "        ");
  if (resource::IsArray(rc) || res.GetArray() != nullptr) {
    WriteArrayDesc(res);
  }
  if (resource::IsForeignRegister(rc)) {
    WriteForeignRegDesc(res);
  }
  if (resource::IsSiblingTaskCall(rc) ||
      resource::IsSubModuleTaskCall(rc)) {
    WriteCalleeTaskDesc(res);
  }
  if (resource::IsPortInput(rc)) {
    WritePortInputDesc(res);
  }
  os_ << "      )\n";
}

void ExpWriter::WriteArrayDesc(const IResource &res) {
  const IArray *array = res.GetArray();
  os_ << "        (ARRAY ";
  os_ << array->GetAddressWidth();
  os_ << " ";
  WriteValueType(array->GetDataType());
  if (array->IsExternal()) {
    os_ << " EXTERNAL";
  } else {
    os_ << " INTERNAL";
  }
  if (array->IsRam()) {
    os_ << " RAM";
  } else {
    os_ << " ROM";
  }
  IArrayImage *im = array->GetArrayImage();
  if (im != nullptr) {
    os_ << " " << im->GetId();
  }
  os_ << ")\n";
}

void ExpWriter::WriteForeignRegDesc(const IResource &res) {
  os_ << "        (FOREIGN-REG ";
  IRegister *foreign_reg = res.GetForeignRegister();
  IModule *foreign_mod = foreign_reg->GetTable()->GetModule();
  os_ << " " << foreign_mod->GetId();
  os_ << res.GetTable()->GetId();
  os_ << " ";
  os_ << foreign_reg->GetId();
  os_ << ")\n";
}

void ExpWriter::WriteCalleeTaskDesc(const IResource &res) {
  const ITable *table = res.GetCalleeTable();
  CHECK(table) << "callee table isn't specified";
  const IModule *mod = table->GetModule();
  os_ << "        (CALLEE-TABLE " << mod->GetId() << " "
      << table->GetId() << ")\n";
}

void ExpWriter::WritePortInputDesc(const IResource &res) {
  const IResource *writer = res.GetPortInput();
  const ITable *table = writer->GetTable();
  const IModule *mod = table->GetModule();
  os_ << "        (PORT-INPUT " <<  mod->GetId() << " "
      << table->GetId() << " " << writer->GetId() << ")\n";
}

void ExpWriter::WriteInitialState(const ITable &tab) {
  IState *st = tab.GetInitialState();
  if (st) {
    os_ << "    (INITIAL " << st->GetId() << ")\n";
  }
}

void ExpWriter::WriteRegisters(const ITable &tab) {
  os_ << "    (REGISTERS\n";
  for (auto *reg : tab.registers_) {
    os_ << "      (REGISTER " << reg->GetId() << " ";
    const string &name = reg->GetName();
    if (name.empty()) {
      os_ << "()";
    } else {
      os_ << name;
    }
    os_ << "\n";
    os_ << "        ";
    if (reg->IsConst()) {
      os_ << "CONST";
    } else if (reg->IsStateLocal()) {
      os_ << "WIRE";
    } else {
      os_ << "REG";
    }
    os_ << " ";
    WriteValueType(reg->value_type_);
    os_ << " ";
    if (reg->HasInitialValue()) {
      WriteValue(reg->GetInitialValue());
    } else {
      os_ << "()";
    }
    os_ << "\n";
    os_ << "      )\n";
  }
  os_ << "    )\n";
}

void ExpWriter::WriteValueType(const IValueType &type) {
  os_ << "(";
  if (type.IsSigned()) {
    os_ << "INT";
  } else {
    os_ << "UINT";
  }
  os_ << " " << type.GetWidth() << ")";
}

void ExpWriter::WriteValue(const IValue &value) {
  os_ << value.value_;
}

void ExpWriter::WriteState(const IState &st) {
  os_ << "    (STATE " << st.GetId() << "\n";
  for (auto *insn : st.insns_) {
    WriteInsn(*insn);
  }
  os_ << "    )\n";
}

void ExpWriter::WriteInsn(const IInsn &insn) {
  os_ << "      (INSN " << insn.GetId() << " ";
  const IResource *res = insn.GetResource();
  os_ << res->GetClass()->GetName() << " " << res->GetId();
  // Details.
  os_ << " (" << insn.GetOperand() << ")";
  // Targets.
  os_ << " (";
  bool is_first = true;
  for (IState *st : insn.target_states_) {
    if (!is_first) {
      os_ << " ";
    }
    is_first = false;
    os_ << st->GetId();
  }
  os_ << ")";
  // Inputs.
  WriteInsnParams(insn.inputs_);
  // Outputs.
  WriteInsnParams(insn.outputs_);
  os_ << ")\n";
}

void ExpWriter::WriteInsnParams(const vector<IRegister *> &regs) {
  os_ << " (";
  bool is_first = true;
  for (auto &reg : regs) {
    if (!is_first) {
      os_ << " ";
    }
    os_ << reg->GetId();
    is_first = false;
  }
  os_ << ")";
}

void ExpWriter::WriteResourceTypes(const vector<IValueType> &types) {
  os_ << "(";
  bool is_first = true;
  for (auto &type : types) {
    if (!is_first) {
      os_ << " ";
    }
    WriteValueType(type);
    is_first = false;
  }
  os_ << ")";
}

void ExpWriter::WriteResourceParams(const ResourceParams &params,
				    const char *indent) {
  os_ << indent << "(PARAMS";
  vector<string> keys = params.GetParamKeys();
  if (!keys.empty()) {
    os_ << "\n";
  }
  bool is_first = true;
  for (string &key : keys) {
    if (!is_first) {
      os_ << "\n";
    }
    os_ << indent << " (" << key;
    vector<string> values = params.GetValues(key);
    for (string &value : values) {
      os_ << " ";
      WriteStr(value);
    }
    os_ << ")";
    is_first = false;
  }
  os_ << ")\n";
}

void ExpWriter::WriteChannel(const IChannel &ch) {
  os_ << "(CHANNEL " << ch.GetId() << " ";
  WriteValueType(ch.GetValueType());
  os_ << " ";
  IResource *reader = ch.GetReader();
  if (reader == nullptr) {
    os_ << "()";
  } else {
    WriteResourceDesc(*reader);
  }
  os_ << " ";
  IResource *writer = ch.GetWriter();
  if (writer == nullptr) {
    os_ << "()";
  } else {
    WriteResourceDesc(*writer);
  }
  os_ << "\n";
  WriteResourceParams(*(ch.GetParams()), "  ");
  os_ << ")\n";
}

void ExpWriter::WriteArrayImage(const IArrayImage &im) {
  os_ << "(ARRAY-IMAGE " << im.GetId() << " " << im.GetName() << "\n"
      << " (";
  bool f = true;
  for (auto &v : im.values_) {
    if (!f) {
      os_ << " ";
    }
    os_ << v;
    f = false;
  }
  os_ << "))\n";
}

void ExpWriter::WriteResourceDesc(const IResource &res) {
  ITable *tab = res.GetTable();
  IModule *mod = tab->GetModule();
  os_ << "(" << mod->GetId() << " " << tab->GetId() << " "
      << res.GetId() << ")";
}

void ExpWriter::WriteStr(const string &str) {
  bool need_quote = false;
  if (str.find(" ") != string::npos) {
    need_quote = true;
  }
  if (need_quote) {
    os_ << "\"";
  }
  os_ << str;
  if (need_quote) {
    os_ << "\"";
  }
}

}  // namespace iroha
<commit_msg>Fix to write () for empty array image name.<commit_after>#include "writer/exp_writer.h"

#include "iroha/i_design.h"
#include "iroha/logging.h"
#include "iroha/resource_class.h"
#include "iroha/resource_params.h"

namespace iroha {

ExpWriter::ExpWriter(const IDesign *design, ostream &os)
  : design_(design), os_(os) {
}

void ExpWriter::Write() {
  WriteResourceParams(*design_->GetParams(), "");
  for (auto *ch : design_->channels_) {
    WriteChannel(*ch);
  }
  for (auto *im : design_->array_images_) {
    WriteArrayImage(*im);
  }
  for (auto *mod : design_->modules_) {
    WriteModule(*mod);
  }
}

void ExpWriter::WriteModule(const IModule &mod) {
  os_ << "(MODULE " << mod.GetId() << " " << mod.GetName() << "\n";
  IModule *parent = mod.GetParentModule();
  if (parent != nullptr) {
    os_ << "  (PARENT " << parent->GetId() << ")\n";
  }
  WriteResourceParams(*mod.GetParams(), "  ");
  for (auto *tab : mod.tables_) {
    WriteTable(*tab);
  }
  os_ << ")\n";
}

void ExpWriter::WriteTable(const ITable &tab) {
  os_ << "  (TABLE " << tab.GetId();
  string name = tab.GetName();
  if (name.empty()) {
    os_ << " ()";
  } else {
    os_ << " " << name;
  }
  os_ << "\n";
  WriteRegisters(tab);
  WriteResources(tab);
  WriteInitialState(tab);
  for (auto *st : tab.states_) {
    WriteState(*st);
  }
  os_ << "  )\n";
}

void ExpWriter::WriteResources(const ITable &tab) {
  os_ << "    (RESOURCES\n";
  for (auto *res : tab.resources_) {
    WriteResource(*res);
  }
  os_ << "    )\n";
}

void ExpWriter::WriteResource(const IResource &res) {
  const IResourceClass &rc = *(res.GetClass());
  os_ << "      (RESOURCE " << res.GetId()
      << " " << res.GetClass()->GetName() << "\n";
  os_ << "        ";
  WriteResourceTypes(res.input_types_);
  os_ << " ";
  WriteResourceTypes(res.output_types_);
  os_ << "\n";
  ResourceParams *params = res.GetParams();
  WriteResourceParams(*params, "        ");
  if (resource::IsArray(rc) || res.GetArray() != nullptr) {
    WriteArrayDesc(res);
  }
  if (resource::IsForeignRegister(rc)) {
    WriteForeignRegDesc(res);
  }
  if (resource::IsSiblingTaskCall(rc) ||
      resource::IsSubModuleTaskCall(rc)) {
    WriteCalleeTaskDesc(res);
  }
  if (resource::IsPortInput(rc)) {
    WritePortInputDesc(res);
  }
  os_ << "      )\n";
}

void ExpWriter::WriteArrayDesc(const IResource &res) {
  const IArray *array = res.GetArray();
  os_ << "        (ARRAY ";
  os_ << array->GetAddressWidth();
  os_ << " ";
  WriteValueType(array->GetDataType());
  if (array->IsExternal()) {
    os_ << " EXTERNAL";
  } else {
    os_ << " INTERNAL";
  }
  if (array->IsRam()) {
    os_ << " RAM";
  } else {
    os_ << " ROM";
  }
  IArrayImage *im = array->GetArrayImage();
  if (im != nullptr) {
    os_ << " " << im->GetId();
  }
  os_ << ")\n";
}

void ExpWriter::WriteForeignRegDesc(const IResource &res) {
  os_ << "        (FOREIGN-REG ";
  IRegister *foreign_reg = res.GetForeignRegister();
  IModule *foreign_mod = foreign_reg->GetTable()->GetModule();
  os_ << " " << foreign_mod->GetId();
  os_ << res.GetTable()->GetId();
  os_ << " ";
  os_ << foreign_reg->GetId();
  os_ << ")\n";
}

void ExpWriter::WriteCalleeTaskDesc(const IResource &res) {
  const ITable *table = res.GetCalleeTable();
  CHECK(table) << "callee table isn't specified";
  const IModule *mod = table->GetModule();
  os_ << "        (CALLEE-TABLE " << mod->GetId() << " "
      << table->GetId() << ")\n";
}

void ExpWriter::WritePortInputDesc(const IResource &res) {
  const IResource *writer = res.GetPortInput();
  const ITable *table = writer->GetTable();
  const IModule *mod = table->GetModule();
  os_ << "        (PORT-INPUT " <<  mod->GetId() << " "
      << table->GetId() << " " << writer->GetId() << ")\n";
}

void ExpWriter::WriteInitialState(const ITable &tab) {
  IState *st = tab.GetInitialState();
  if (st) {
    os_ << "    (INITIAL " << st->GetId() << ")\n";
  }
}

void ExpWriter::WriteRegisters(const ITable &tab) {
  os_ << "    (REGISTERS\n";
  for (auto *reg : tab.registers_) {
    os_ << "      (REGISTER " << reg->GetId() << " ";
    const string &name = reg->GetName();
    if (name.empty()) {
      os_ << "()";
    } else {
      os_ << name;
    }
    os_ << "\n";
    os_ << "        ";
    if (reg->IsConst()) {
      os_ << "CONST";
    } else if (reg->IsStateLocal()) {
      os_ << "WIRE";
    } else {
      os_ << "REG";
    }
    os_ << " ";
    WriteValueType(reg->value_type_);
    os_ << " ";
    if (reg->HasInitialValue()) {
      WriteValue(reg->GetInitialValue());
    } else {
      os_ << "()";
    }
    os_ << "\n";
    os_ << "      )\n";
  }
  os_ << "    )\n";
}

void ExpWriter::WriteValueType(const IValueType &type) {
  os_ << "(";
  if (type.IsSigned()) {
    os_ << "INT";
  } else {
    os_ << "UINT";
  }
  os_ << " " << type.GetWidth() << ")";
}

void ExpWriter::WriteValue(const IValue &value) {
  os_ << value.value_;
}

void ExpWriter::WriteState(const IState &st) {
  os_ << "    (STATE " << st.GetId() << "\n";
  for (auto *insn : st.insns_) {
    WriteInsn(*insn);
  }
  os_ << "    )\n";
}

void ExpWriter::WriteInsn(const IInsn &insn) {
  os_ << "      (INSN " << insn.GetId() << " ";
  const IResource *res = insn.GetResource();
  os_ << res->GetClass()->GetName() << " " << res->GetId();
  // Details.
  os_ << " (" << insn.GetOperand() << ")";
  // Targets.
  os_ << " (";
  bool is_first = true;
  for (IState *st : insn.target_states_) {
    if (!is_first) {
      os_ << " ";
    }
    is_first = false;
    os_ << st->GetId();
  }
  os_ << ")";
  // Inputs.
  WriteInsnParams(insn.inputs_);
  // Outputs.
  WriteInsnParams(insn.outputs_);
  os_ << ")\n";
}

void ExpWriter::WriteInsnParams(const vector<IRegister *> &regs) {
  os_ << " (";
  bool is_first = true;
  for (auto &reg : regs) {
    if (!is_first) {
      os_ << " ";
    }
    os_ << reg->GetId();
    is_first = false;
  }
  os_ << ")";
}

void ExpWriter::WriteResourceTypes(const vector<IValueType> &types) {
  os_ << "(";
  bool is_first = true;
  for (auto &type : types) {
    if (!is_first) {
      os_ << " ";
    }
    WriteValueType(type);
    is_first = false;
  }
  os_ << ")";
}

void ExpWriter::WriteResourceParams(const ResourceParams &params,
				    const char *indent) {
  os_ << indent << "(PARAMS";
  vector<string> keys = params.GetParamKeys();
  if (!keys.empty()) {
    os_ << "\n";
  }
  bool is_first = true;
  for (string &key : keys) {
    if (!is_first) {
      os_ << "\n";
    }
    os_ << indent << " (" << key;
    vector<string> values = params.GetValues(key);
    for (string &value : values) {
      os_ << " ";
      WriteStr(value);
    }
    os_ << ")";
    is_first = false;
  }
  os_ << ")\n";
}

void ExpWriter::WriteChannel(const IChannel &ch) {
  os_ << "(CHANNEL " << ch.GetId() << " ";
  WriteValueType(ch.GetValueType());
  os_ << " ";
  IResource *reader = ch.GetReader();
  if (reader == nullptr) {
    os_ << "()";
  } else {
    WriteResourceDesc(*reader);
  }
  os_ << " ";
  IResource *writer = ch.GetWriter();
  if (writer == nullptr) {
    os_ << "()";
  } else {
    WriteResourceDesc(*writer);
  }
  os_ << "\n";
  WriteResourceParams(*(ch.GetParams()), "  ");
  os_ << ")\n";
}

void ExpWriter::WriteArrayImage(const IArrayImage &im) {
  os_ << "(ARRAY-IMAGE " << im.GetId() << " ";
  if (im.GetName().empty()) {
    os_ << "()";
  } else {
    os_ << im.GetName();
  }
  os_ << "\n"
      << " (";
  bool f = true;
  for (auto &v : im.values_) {
    if (!f) {
      os_ << " ";
    }
    os_ << v;
    f = false;
  }
  os_ << "))\n";
}

void ExpWriter::WriteResourceDesc(const IResource &res) {
  ITable *tab = res.GetTable();
  IModule *mod = tab->GetModule();
  os_ << "(" << mod->GetId() << " " << tab->GetId() << " "
      << res.GetId() << ")";
}

void ExpWriter::WriteStr(const string &str) {
  bool need_quote = false;
  if (str.find(" ") != string::npos) {
    need_quote = true;
  }
  if (need_quote) {
    os_ << "\"";
  }
  os_ << str;
  if (need_quote) {
    os_ << "\"";
  }
}

}  // namespace iroha
<|endoftext|>


<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
 * This file is part of the LibreOffice project.
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 *
 * This file incorporates work covered by the following license notice:
 *
 *   Licensed to the Apache Software Foundation (ASF) under one or more
 *   contributor license agreements. See the NOTICE file distributed
 *   with this work for additional information regarding copyright
 *   ownership. The ASF licenses this file to you under the Apache
 *   License, Version 2.0 (the "License"); you may not use this file
 *   except in compliance with the License. You may obtain a copy of
 *   the License at http://www.apache.org/licenses/LICENSE-2.0 .
 */
#ifndef INCLUDED_CHART2_SOURCE_INC_REGRESSIONCURVEHELPER_HXX
#define INCLUDED_CHART2_SOURCE_INC_REGRESSIONCURVEHELPER_HXX

#include <com/sun/star/chart2/XRegressionCurve.hpp>
#include <com/sun/star/chart2/XRegressionCurveCalculator.hpp>
#include <com/sun/star/chart2/XRegressionCurveContainer.hpp>
#include <com/sun/star/chart2/data/XDataSource.hpp>
#include <com/sun/star/chart2/XDataSeries.hpp>
#include <com/sun/star/chart2/XDiagram.hpp>
#include <com/sun/star/uno/XComponentContext.hpp>
#include <com/sun/star/frame/XModel.hpp>
#include "charttoolsdllapi.hxx"

#include <vector>

namespace chart
{

class OOO_DLLPUBLIC_CHARTTOOLS RegressionCurveHelper
{
public:
    /// returns a model mean-value line
    SAL_DLLPRIVATE static ::com::sun::star::uno::Reference<
            ::com::sun::star::chart2::XRegressionCurve >
        createMeanValueLine(
            const ::com::sun::star::uno::Reference<
                ::com::sun::star::uno::XComponentContext > & xContext );

    /// returns a model regression curve
    SAL_DLLPRIVATE static ::com::sun::star::uno::Reference<
            ::com::sun::star::chart2::XRegressionCurve >
        createRegressionCurveByServiceName(
            const ::com::sun::star::uno::Reference<
                ::com::sun::star::uno::XComponentContext > & xContext,
            OUString aServiceName );

    static bool hasMeanValueLine(
        const ::com::sun::star::uno::Reference<
            ::com::sun::star::chart2::XRegressionCurveContainer > & xRegCnt );

    static bool isMeanValueLine(
        const ::com::sun::star::uno::Reference<
            ::com::sun::star::chart2::XRegressionCurve > & xRegCurve );

    static ::com::sun::star::uno::Reference<
            ::com::sun::star::chart2::XRegressionCurve >
        getMeanValueLine(
            const ::com::sun::star::uno::Reference<
                ::com::sun::star::chart2::XRegressionCurveContainer > & xRegCnt );

    /** creates a mean-value line and adds it to the container.

         @param xSeriesProp
             If set, this property-set will be used to apply a line color
     */
    static void addMeanValueLine(
        ::com::sun::star::uno::Reference<
            ::com::sun::star::chart2::XRegressionCurveContainer > & xRegCnt,
        const ::com::sun::star::uno::Reference<
            ::com::sun::star::uno::XComponentContext > & xContext,
        const ::com::sun::star::uno::Reference<
            ::com::sun::star::beans::XPropertySet > & xSeriesProp );

    static void removeMeanValueLine(
        ::com::sun::star::uno::Reference<
            ::com::sun::star::chart2::XRegressionCurveContainer > & xRegCnt );

    enum tRegressionType
    {
        REGRESSION_TYPE_NONE,
        REGRESSION_TYPE_LINEAR,
        REGRESSION_TYPE_LOG,
        REGRESSION_TYPE_EXP,
        REGRESSION_TYPE_POWER,
        REGRESSION_TYPE_POLYNOMIAL,
        REGRESSION_TYPE_MOVING_AVERAGE,
        REGRESSION_TYPE_MEAN_VALUE,
        REGRESSION_TYPE_UNKNOWN
    };

    /** Returns the first regression curve found that is not of type
        mean-value line
     */
    static com::sun::star::uno::Reference<com::sun::star::chart2::XRegressionCurve >
        getFirstCurveNotMeanValueLine(
            const com::sun::star::uno::Reference<
                com::sun::star::chart2::XRegressionCurveContainer >& xCurveContainer );

    /** Returns the regression curve found at the index provided.
     */
    static com::sun::star::uno::Reference<com::sun::star::chart2::XRegressionCurve >
        getRegressionCurveAtIndex(
            const com::sun::star::uno::Reference<com::sun::star::chart2::XRegressionCurveContainer >& xCurveContainer,
            sal_Int32 aIndex);

    /** Returns the type of the first regression curve found that is not of type
        mean-value line
     */
    static tRegressionType getFirstRegressTypeNotMeanValueLine(
        const com::sun::star::uno::Reference<
            com::sun::star::chart2::XRegressionCurveContainer >& xCurveContainer );

    static tRegressionType getRegressionType(
        const com::sun::star::uno::Reference<
            com::sun::star::chart2::XRegressionCurve >& xCurve );

    /** @param xPropertySource is taken as source to copy all properties from if
               not null
        @param xEquationProperties is set at the new regression curve as
               equation properties if not null
    */
    static com::sun::star::uno::Reference< com::sun::star::chart2::XRegressionCurve >
        addRegressionCurve(
            tRegressionType eType,
            com::sun::star::uno::Reference<
                com::sun::star::chart2::XRegressionCurveContainer >& xCurveContainer,
            const com::sun::star::uno::Reference<
                com::sun::star::uno::XComponentContext >& xContext,
            const com::sun::star::uno::Reference<
                com::sun::star::beans::XPropertySet >& xPropertySource =
                    com::sun::star::uno::Reference< com::sun::star::beans::XPropertySet >(),
            const com::sun::star::uno::Reference<
                com::sun::star::beans::XPropertySet >& xEquationProperties =
                    com::sun::star::uno::Reference< com::sun::star::beans::XPropertySet >() );

    static bool removeAllExceptMeanValueLine(
        com::sun::star::uno::Reference<
            com::sun::star::chart2::XRegressionCurveContainer >& xCurveContainer );

    static void removeEquations(
        com::sun::star::uno::Reference<
            com::sun::star::chart2::XRegressionCurveContainer >& xCurveContainer );

    static com::sun::star::uno::Reference< com::sun::star::chart2::XRegressionCurve >
        changeRegressionCurveType(
            tRegressionType eType,
            com::sun::star::uno::Reference<
                com::sun::star::chart2::XRegressionCurveContainer > & xRegressionCurveContainer,
            com::sun::star::uno::Reference<
                com::sun::star::chart2::XRegressionCurve > & xRegressionCurve,
            const com::sun::star::uno::Reference<
                com::sun::star::uno::XComponentContext > & xContext );

    /// returns a calculator object for regression curves (used by the view)
    static com::sun::star::uno::Reference< com::sun::star::chart2::XRegressionCurveCalculator >
        createRegressionCurveCalculatorByServiceName( OUString aServiceName );

    /** recalculates the regression parameters according to the data given in
        the data source.

        A sequence having the role "values-x" will be used as x-values for the
        calculation if found.  Otherwise a sequence (1, 2, 3, ...) of category
        indexes will be used for the recalculateRegression() method of the
        regression curve.

        The first sequence having the role "values-y" will be used as y-values
        for the recalculateRegression() method of the regression curve.

        @param bUseXValuesIfAvailable
            If false, the sequence (1, 2, 3, ...) will always be used, even if
            there is a data-sequence with role "values-x"
     */
    SAL_DLLPRIVATE static void initializeCurveCalculator(
        const ::com::sun::star::uno::Reference<
            ::com::sun::star::chart2::XRegressionCurveCalculator > & xOutCurveCalculator,
        const ::com::sun::star::uno::Reference<
            ::com::sun::star::chart2::data::XDataSource > & xSource,
        bool bUseXValuesIfAvailable = true );

    /** Same method as above, but uses the given XModel to determine the
        parameter bUseXValuesIfAvailable in the above function.  It is also
        necessary that the data::XDataSource is an XDataSeries, thus this parameter
        also changed.
     */
    static void initializeCurveCalculator(
        const ::com::sun::star::uno::Reference<
            ::com::sun::star::chart2::XRegressionCurveCalculator > & xOutCurveCalculator,
        const ::com::sun::star::uno::Reference<
            ::com::sun::star::chart2::XDataSeries > & xSeries,
        const ::com::sun::star::uno::Reference<
            ::com::sun::star::frame::XModel > & xModel );

    static OUString getUINameForRegressionCurve( const ::com::sun::star::uno::Reference<
            ::com::sun::star::chart2::XRegressionCurve >& xCurve );

    static OUString getRegressionCurveName(
        const ::com::sun::star::uno::Reference<
            ::com::sun::star::chart2::XRegressionCurve >& xCurve );

    static OUString getRegressionCurveGenericName(
        const ::com::sun::star::uno::Reference<
            ::com::sun::star::chart2::XRegressionCurve >& xCurve );

    static OUString getRegressionCurveSpecificName(
        const ::com::sun::star::uno::Reference<
            ::com::sun::star::chart2::XRegressionCurve >& xCurve );

    static ::std::vector< ::com::sun::star::uno::Reference<
            ::com::sun::star::chart2::XRegressionCurve > > getAllRegressionCurvesNotMeanValueLine(
                const ::com::sun::star::uno::Reference<
                    ::com::sun::star::chart2::XDiagram > & xDiagram );

    static void resetEquationPosition( const ::com::sun::star::uno::Reference<
                                       ::com::sun::star::chart2::XRegressionCurve > & xCurve );

    /// @return the index of the given curve in the given container. -1 if not contained
    static sal_Int32 getRegressionCurveIndex(
        const ::com::sun::star::uno::Reference<
            ::com::sun::star::chart2::XRegressionCurveContainer > & xContainer,
        const ::com::sun::star::uno::Reference<
            ::com::sun::star::chart2::XRegressionCurve > & xCurve );

    static bool hasEquation(
        const ::com::sun::star::uno::Reference<
            ::com::sun::star::chart2::XRegressionCurve > & xCurve );

private:
    // not implemented
    RegressionCurveHelper();
};

} //  namespace chart

// INCLUDED_CHART2_SOURCE_INC_REGRESSIONCURVEHELPER_HXX
#endif

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<commit_msg>Make RegressionCurveHelper more readable (com::sun::star -> css)<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
 * This file is part of the LibreOffice project.
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 *
 * This file incorporates work covered by the following license notice:
 *
 *   Licensed to the Apache Software Foundation (ASF) under one or more
 *   contributor license agreements. See the NOTICE file distributed
 *   with this work for additional information regarding copyright
 *   ownership. The ASF licenses this file to you under the Apache
 *   License, Version 2.0 (the "License"); you may not use this file
 *   except in compliance with the License. You may obtain a copy of
 *   the License at http://www.apache.org/licenses/LICENSE-2.0 .
 */
#ifndef INCLUDED_CHART2_SOURCE_INC_REGRESSIONCURVEHELPER_HXX
#define INCLUDED_CHART2_SOURCE_INC_REGRESSIONCURVEHELPER_HXX

#include <com/sun/star/chart2/XRegressionCurve.hpp>
#include <com/sun/star/chart2/XRegressionCurveCalculator.hpp>
#include <com/sun/star/chart2/XRegressionCurveContainer.hpp>
#include <com/sun/star/chart2/data/XDataSource.hpp>
#include <com/sun/star/chart2/XDataSeries.hpp>
#include <com/sun/star/chart2/XDiagram.hpp>
#include <com/sun/star/uno/XComponentContext.hpp>
#include <com/sun/star/frame/XModel.hpp>
#include "charttoolsdllapi.hxx"

#include <vector>

namespace chart
{

class OOO_DLLPUBLIC_CHARTTOOLS RegressionCurveHelper
{
public:
    /// returns a model mean-value line
    SAL_DLLPRIVATE static css::uno::Reference<css::chart2::XRegressionCurve>
        createMeanValueLine(const css::uno::Reference<css::uno::XComponentContext> & xContext );

    /// returns a model regression curve
    SAL_DLLPRIVATE static css::uno::Reference<css::chart2::XRegressionCurve>
        createRegressionCurveByServiceName(
            const css::uno::Reference<css::uno::XComponentContext> & xContext,
            OUString aServiceName );

    static bool hasMeanValueLine(
        const css::uno::Reference<css::chart2::XRegressionCurveContainer> & xRegCnt );

    static bool isMeanValueLine(
        const css::uno::Reference<css::chart2::XRegressionCurve> & xRegCurve );

    static css::uno::Reference<css::chart2::XRegressionCurve>
        getMeanValueLine(
            const css::uno::Reference<css::chart2::XRegressionCurveContainer> & xRegCnt );

    /** creates a mean-value line and adds it to the container.

         @param xSeriesProp
             If set, this property-set will be used to apply a line color
     */
    static void addMeanValueLine(
        css::uno::Reference<css::chart2::XRegressionCurveContainer>& xRegCnt,
        const css::uno::Reference<css::uno::XComponentContext>& xContext,
        const css::uno::Reference<css::beans::XPropertySet>& xSeriesProp );

    static void removeMeanValueLine(
        css::uno::Reference<css::chart2::XRegressionCurveContainer>& xRegCnt );

    enum tRegressionType
    {
        REGRESSION_TYPE_NONE,
        REGRESSION_TYPE_LINEAR,
        REGRESSION_TYPE_LOG,
        REGRESSION_TYPE_EXP,
        REGRESSION_TYPE_POWER,
        REGRESSION_TYPE_POLYNOMIAL,
        REGRESSION_TYPE_MOVING_AVERAGE,
        REGRESSION_TYPE_MEAN_VALUE,
        REGRESSION_TYPE_UNKNOWN
    };

    /** Returns the first regression curve found that is not of type
        mean-value line
     */
    static css::uno::Reference<com::sun::star::chart2::XRegressionCurve>
        getFirstCurveNotMeanValueLine(
            const css::uno::Reference<css::chart2::XRegressionCurveContainer>& xCurveContainer );

    /** Returns the regression curve found at the index provided.
     */
    static css::uno::Reference<css::chart2::XRegressionCurve>
        getRegressionCurveAtIndex(
            const css::uno::Reference<css::chart2::XRegressionCurveContainer>& xCurveContainer,
            sal_Int32 aIndex);

    /** Returns the type of the first regression curve found that is not of type
        mean-value line
     */
    static tRegressionType getFirstRegressTypeNotMeanValueLine(
        const css::uno::Reference<css::chart2::XRegressionCurveContainer>& xCurveContainer );

    static tRegressionType getRegressionType(
        const css::uno::Reference<css::chart2::XRegressionCurve>& xCurve );

    /** @param xPropertySource is taken as source to copy all properties from if
               not null
        @param xEquationProperties is set at the new regression curve as
               equation properties if not null
    */
    static css::uno::Reference<css::chart2::XRegressionCurve>
        addRegressionCurve(
            tRegressionType eType,
            css::uno::Reference<css::chart2::XRegressionCurveContainer>& xCurveContainer,
            const css::uno::Reference<css::uno::XComponentContext>& xContext,
            const css::uno::Reference<css::beans::XPropertySet >& xPropertySource =
                    css::uno::Reference<css::beans::XPropertySet>(),
            const css::uno::Reference<css::beans::XPropertySet>& xEquationProperties =
                    css::uno::Reference<css::beans::XPropertySet>() );

    static bool removeAllExceptMeanValueLine(
        css::uno::Reference<css::chart2::XRegressionCurveContainer>& xCurveContainer );

    static void removeEquations(
        css::uno::Reference<css::chart2::XRegressionCurveContainer>& xCurveContainer );

    static css::uno::Reference<css::chart2::XRegressionCurve>
        changeRegressionCurveType(
            tRegressionType eType,
            css::uno::Reference<css::chart2::XRegressionCurveContainer>& xRegressionCurveContainer,
            css::uno::Reference<css::chart2::XRegressionCurve>& xRegressionCurve,
            const css::uno::Reference<css::uno::XComponentContext>& xContext );

    /// returns a calculator object for regression curves (used by the view)
    static css::uno::Reference<css::chart2::XRegressionCurveCalculator>
        createRegressionCurveCalculatorByServiceName( OUString aServiceName );

    /** recalculates the regression parameters according to the data given in
        the data source.

        A sequence having the role "values-x" will be used as x-values for the
        calculation if found.  Otherwise a sequence (1, 2, 3, ...) of category
        indexes will be used for the recalculateRegression() method of the
        regression curve.

        The first sequence having the role "values-y" will be used as y-values
        for the recalculateRegression() method of the regression curve.

        @param bUseXValuesIfAvailable
            If false, the sequence (1, 2, 3, ...) will always be used, even if
            there is a data-sequence with role "values-x"
     */
    SAL_DLLPRIVATE static void initializeCurveCalculator(
        const css::uno::Reference<css::chart2::XRegressionCurveCalculator>& xOutCurveCalculator,
        const css::uno::Reference<css::chart2::data::XDataSource>& xSource,
        bool bUseXValuesIfAvailable = true );

    /** Same method as above, but uses the given XModel to determine the
        parameter bUseXValuesIfAvailable in the above function.  It is also
        necessary that the data::XDataSource is an XDataSeries, thus this parameter
        also changed.
     */
    static void initializeCurveCalculator(
        const css::uno::Reference<css::chart2::XRegressionCurveCalculator>& xOutCurveCalculator,
        const css::uno::Reference<css::chart2::XDataSeries>& xSeries,
        const css::uno::Reference<css::frame::XModel>& xModel );

    static OUString getUINameForRegressionCurve(
        const css::uno::Reference<css::chart2::XRegressionCurve>& xCurve );

    static OUString getRegressionCurveName(
        const css::uno::Reference<css::chart2::XRegressionCurve>& xCurve );

    static OUString getRegressionCurveGenericName(
        const css::uno::Reference<css::chart2::XRegressionCurve>& xCurve );

    static OUString getRegressionCurveSpecificName(
        const css::uno::Reference<css::chart2::XRegressionCurve>& xCurve );

    static std::vector<css::uno::Reference<css::chart2::XRegressionCurve> >
        getAllRegressionCurvesNotMeanValueLine(
                const css::uno::Reference<css::chart2::XDiagram>& xDiagram );

    static void resetEquationPosition(
        const css::uno::Reference<css::chart2::XRegressionCurve>& xCurve );

    /// @return the index of the given curve in the given container. -1 if not contained
    static sal_Int32 getRegressionCurveIndex(
        const css::uno::Reference<css::chart2::XRegressionCurveContainer>& xContainer,
        const css::uno::Reference<css::chart2::XRegressionCurve>& xCurve );

    static bool hasEquation(const css::uno::Reference<css::chart2::XRegressionCurve>& xCurve );

private:
    // instatiation not allowed
    RegressionCurveHelper();
};

} //  namespace chart

#endif // INCLUDED_CHART2_SOURCE_INC_REGRESSIONCURVEHELPER_HXX

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<|endoftext|>


<commit_before>#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <sys/resource.h>
#include <asm/errno.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netinet/tcp.h>
#include <malloc.h>
#include <string.h>
#include <utility>
#include <map>
#include <sys/types.h>
#include <netdb.h>
#include <string.h>
#include <unistd.h>
#include <assert.h>

#include <tins/tins.h>
#include "HostMapping.h"
#include "AITF_packet.h"
#include "AITF_connect_state.h"
//#include "AITF_identity_hash.h"

using namespace Tins;
using namespace std;

extern HostMapping hosts;

map<AITF_identity, AITF_connect_state> ostate_table;
map<AITF_identity, AITF_connect_state> istate_table;

typedef enum{
	ENFORCE, REQUEST, VERIFY, CORRECT, BLOCK, CEASE
} AITF_type;

typedef struct thread_data{
	IP::address_type addr;
	char buff[1500];
	ssize_t size;
} thread_data;

void AITF_escalation(AITF_packet pack){
	return;
}

uint64_t generateNonce(){
	return 1232;
}

void send_AITF_message(AITF_packet pack, IP::address_type addr){

	cout << "SENDING PACKET: DEST: " << addr.to_string();
	cout << pack.to_string();

	uint8_t* data = (uint8_t*)malloc(pack.packet_size());
	pack.serialize(data, pack.packet_size());

	int status, sd, len, s, r;
	struct addrinfo hints;
	struct addrinfo *servinfo, *p; // will point to the results

	const char *url, *port;

	port = "11467";
	url = addr.to_string().c_str();

	memset(&hints, 0 , sizeof(hints)); // make sure the stuct is empty
	hints.ai_family = AF_INET; // only IPv4
	hints.ai_socktype = SOCK_DGRAM; // Use a UDP connection
	// getaddrinfo() - fills out an address structure for us with the destination server's info
	if((status = getaddrinfo(url, port, &hints, &servinfo)) != 0) {
		fprintf(stderr, "getaddrinfo error: %s\n", gai_strerror(status));
		return;
	}

	// loop through all results and connect to the first one we can
	for(p = servinfo; p != NULL; p = p->ai_next)
	{
		if ((sd = socket(p->ai_family, p->ai_socktype, p->ai_protocol)) == -1) {
	 	 perror("client: socket");
	 	 continue;
		}
		if((connect(sd, servinfo->ai_addr, servinfo->ai_addrlen)) < 0) {
		  close(sd);
	 	 	perror("client: connect");
		  continue;
		}
		break;
	}
	if (p == NULL) {
		fprintf(stderr, "client: failed to connect\n");
		return;
	}
	freeaddrinfo(servinfo);

	s = send(sd, data, pack.packet_size(), 0);

	close(sd);

	return;
}

uint64_t generateRandomValue(IP::address_type addr, int x){
	return 12345;
}

void AITF_enforce(AITF_packet pack, IP::address_type addr){
	if (hosts.isEnabledHost(addr)){
		if (ostate_table.count(pack.identity())){
			AITF_escalation(pack);
		}else{
			AITF_connect_state cstate(0,0,0);
			ostate_table.insert(std::make_pair(pack.identity(), cstate));
			AITF_packet request((uint8_t)REQUEST, generateNonce(), (uint64_t)0, pack.identity());

			if (request.identity().filters().size() >= 2){
				send_AITF_message(request, request.identity().filters()[1].address());
			}else{
				ostate_table.erase(request.identity());
			}
		}
	}
	return;
}

void AITF_request(AITF_packet pack){
	vector<NetworkInterface> ip_addrs = NetworkInterface::all();
	IP::address_type addr;
	int x;
	int y;
	for (x = ip_addrs.size()-1; x >= 0; x--){
		if (ip_addrs[x].addresses().ip_addr == pack.identity().filters()[pack.identity().pointer()].address()){
			addr = ip_addrs[x].addresses().ip_addr;
			break;
		}
	}

	RRFilter &rent = pack.idRef().filters()[pack.idRef().pointer()];

	//Check the random numbers
	if (generateRandomValue(pack.identity().victim(),1) == rent.random_number_1() || generateRandomValue(pack.identity().victim(),1) == rent.random_number_2()){
		// SEND VERIFY
		AITF_connect_state cstate(0,0,0);
		istate_table[pack.identity()] = cstate;
		AITF_packet verify((uint8_t)VERIFY, pack.nonce1(), generateNonce(), pack.identity());

		send_AITF_message(verify, verify.identity().victim());
	}else{
		// SEND CORRECT
		rent.set_random_number_1(1234);//generateRandomValue(pack.identity().victim(), 1));
		rent.set_random_number_2(generateRandomValue(pack.identity().victim(), 2));
		printf("Rent rand val: %Ld, rand val in list: %Ld\n", rent.random_number_1(), pack.idRef().filters()[pack.idRef().pointer()].random_number_1());
		AITF_packet correct = AITF_packet((uint8_t)CORRECT, pack.nonce1(), 0, pack.identity());

		send_AITF_message(correct, correct.identity().victim());
	}

	return;
}

void AITF_verify(AITF_packet pack){
	if (ostate_table.count(pack.identity())){
		AITF_connect_state cstate = ostate_table.at(pack.identity());
		if (cstate.nonce1() == pack.nonce1()){
			AITF_packet block((uint8_t)BLOCK, (uint64_t)0, pack.nonce2(), pack.identity());

			send_AITF_message(block, pack.identity().filters()[cstate.currentRoute()].address());
		}
	}
	return;
}

void AITF_correct(AITF_packet pack){
	if (ostate_table.count(pack.identity())){
		AITF_connect_state cstate = ostate_table.at(pack.identity());
		if (cstate.nonce1() == pack.nonce1()){
			RRFilter rent = pack.identity().filters()[cstate.currentRoute()];
			rent.set_match_type(2);
			AITF_enforce(pack, pack.identity().victim());
		}
	}
	return;
}

void AITF_block(AITF_packet pack){
	return;
}

void AITF_cease(AITF_packet pack){
	// NEVER CEASE! MARCH FORWARDS!
	return;
}

void AITF_action(thread_data* data){

	AITF_packet apacket = AITF_packet((uint8_t*)data->buff, data->size);

	cout << apacket.to_string();

	switch(apacket.packet_type())
	{
		case 0:
			AITF_enforce(apacket, data->addr);
			break;
		case 1:
			AITF_request(apacket);
			break;
		case 2:
			AITF_verify(apacket);
			break;
		case 3:
			AITF_correct(apacket);
			break;
		case 4:
			AITF_block(apacket);
			break;
		case 5:
		default:
			AITF_cease(apacket);
	}
	free(data);
}

void AITF_daemon(void* data){
	int portNumber = 11467;

	struct sockaddr_in serv_addr, client_addr;
	int fd = 0;
	int fdlisten = 0;
	int fdconn = 0;
	int out = 0;
	unsigned int client = sizeof(client_addr);

	// Establish the socket that will be used for listening
	fd = socket(AF_INET, SOCK_DGRAM, 0);
	printf("Socket: %d\n", fd);

	// Do a bind of that socket
	serv_addr.sin_family = AF_INET;
	serv_addr.sin_port = htons(portNumber);
	serv_addr.sin_addr.s_addr = htonl(INADDR_ANY);
	bind( fd, (struct sockaddr*)&serv_addr, sizeof(serv_addr));

	// Set up to listen
	listen( fd, 10);
	fdlisten = fd;

	ssize_t tsdata;
	thread_data* buff;
	while(1)
	{
		buff = (thread_data*) malloc(sizeof(thread_data));
		tsdata =  recvfrom(fdlisten, buff->buff, 1500, 0, (struct sockaddr *)&client_addr, &client);

		if (tsdata > 0){
			uint32_t conn_addr = client_addr.sin_addr.s_addr;
			buff->addr = IP::address_type(conn_addr);
			buff->size = tsdata;
			pthread_t helper;
			pthread_create(&helper, NULL, (void*(*)(void*))AITF_action, buff);
		}else{
			free(buff);
		}
	}
}

int intializeAITF(void* filtertable){
	int aitf_thread = 0;
	pthread_t helper;
	pthread_create(&helper, NULL, (void*(*)(void*))AITF_daemon, filtertable);

}<commit_msg>Add a few missing lines<commit_after>#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <sys/resource.h>
#include <asm/errno.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netinet/tcp.h>
#include <malloc.h>
#include <string.h>
#include <utility>
#include <map>
#include <sys/types.h>
#include <netdb.h>
#include <string.h>
#include <unistd.h>
#include <assert.h>

#include <tins/tins.h>
#include "HostMapping.h"
#include "AITF_packet.h"
#include "AITF_connect_state.h"
//#include "AITF_identity_hash.h"

using namespace Tins;
using namespace std;

extern HostMapping hosts;

map<AITF_identity, AITF_connect_state> ostate_table;
map<AITF_identity, AITF_connect_state> istate_table;

typedef enum{
	ENFORCE, REQUEST, VERIFY, CORRECT, BLOCK, CEASE
} AITF_type;

typedef struct thread_data{
	IP::address_type addr;
	char buff[1500];
	ssize_t size;
} thread_data;

void AITF_escalation(AITF_packet pack){
	return;
}

uint64_t generateNonce(){
	return 1232;
}

void send_AITF_message(AITF_packet pack, IP::address_type addr){

	cout << "SENDING PACKET: DEST: " << addr.to_string();
	cout << pack.to_string();

	uint8_t* data = (uint8_t*)malloc(pack.packet_size());
	pack.serialize(data, pack.packet_size());

	int status, sd, len, s, r;
	struct addrinfo hints;
	struct addrinfo *servinfo, *p; // will point to the results

	const char *url, *port;

	port = "11467";
	url = addr.to_string().c_str();

	memset(&hints, 0 , sizeof(hints)); // make sure the stuct is empty
	hints.ai_family = AF_INET; // only IPv4
	hints.ai_socktype = SOCK_DGRAM; // Use a UDP connection
	// getaddrinfo() - fills out an address structure for us with the destination server's info
	if((status = getaddrinfo(url, port, &hints, &servinfo)) != 0) {
		fprintf(stderr, "getaddrinfo error: %s\n", gai_strerror(status));
		return;
	}

	// loop through all results and connect to the first one we can
	for(p = servinfo; p != NULL; p = p->ai_next)
	{
		if ((sd = socket(p->ai_family, p->ai_socktype, p->ai_protocol)) == -1) {
	 	 perror("client: socket");
	 	 continue;
		}
		if((connect(sd, servinfo->ai_addr, servinfo->ai_addrlen)) < 0) {
		  close(sd);
	 	 	perror("client: connect");
		  continue;
		}
		break;
	}
	if (p == NULL) {
		fprintf(stderr, "client: failed to connect\n");
		return;
	}
	freeaddrinfo(servinfo);

	s = send(sd, data, pack.packet_size(), 0);

	close(sd);

	return;
}

uint64_t generateRandomValue(IP::address_type addr, int x){
	return 12345;
}

void AITF_enforce(AITF_packet pack, IP::address_type addr){
	if (hosts.isEnabledHost(addr)){
		if (ostate_table.count(pack.identity())){
			AITF_escalation(pack);
		}else{
			AITF_connect_state cstate(0,0,0);
			ostate_table.insert(std::make_pair(pack.identity(), cstate));
			AITF_packet request((uint8_t)REQUEST, generateNonce(), (uint64_t)0, pack.identity());

			if (request.identity().filters().size() >= 2){
				send_AITF_message(request, request.identity().filters()[1].address());
			}else{
				ostate_table.erase(request.identity());
			}
		}
	}
	return;
}

void AITF_request(AITF_packet pack){
	vector<NetworkInterface> ip_addrs = NetworkInterface::all();
	IP::address_type addr;
	int x;
	int y;
	for (x = ip_addrs.size()-1; x >= 0; x--){
		if (ip_addrs[x].addresses().ip_addr == pack.identity().filters()[pack.identity().pointer()].address()){
			addr = ip_addrs[x].addresses().ip_addr;
			break;
		}
	}

	RRFilter &rent = pack.identity().filters()[pack.identity().pointer()];

	//Check the random numbers
	if (generateRandomValue(pack.identity().victim(),1) == rent.random_number_1() || generateRandomValue(pack.identity().victim(),1) == rent.random_number_2()){
		// SEND VERIFY
		AITF_connect_state cstate(0,0,0);
		istate_table[pack.identity()] = cstate;
		AITF_packet verify((uint8_t)VERIFY, pack.nonce1(), generateNonce(), pack.identity());

		send_AITF_message(verify, verify.identity().victim());
	}else{
		// SEND CORRECT
		rent.set_random_number_1(generateRandomValue(pack.identity().victim(), 1));
		rent.set_random_number_2(generateRandomValue(pack.identity().victim(), 2));
		AITF_packet correct = AITF_packet((uint8_t)CORRECT, pack.nonce1(), 0, pack.identity());

		send_AITF_message(correct, correct.identity().victim());
	}

	return;
}

void AITF_verify(AITF_packet pack){
	if (ostate_table.count(pack.identity())){
		AITF_connect_state cstate = ostate_table.at(pack.identity());
		if (cstate.nonce1() == pack.nonce1()){
			AITF_packet block((uint8_t)BLOCK, (uint64_t)0, pack.nonce2(), pack.identity());

			send_AITF_message(block, pack.identity().filters()[cstate.currentRoute()].address());
		}
	}
	return;
}

void AITF_correct(AITF_packet pack){
	if (ostate_table.count(pack.identity())){
		AITF_connect_state cstate = ostate_table.at(pack.identity());
		if (cstate.nonce1() == pack.nonce1()){
			RRFilter rent = pack.identity().filters()[cstate.currentRoute()];
			rent.set_match_type(2);
			AITF_enforce(pack, pack.identity().victim());
		}
	}
	return;
}

void AITF_block(AITF_packet pack){
	return;
}

void AITF_cease(AITF_packet pack){
	// NEVER CEASE! MARCH FORWARDS!
	return;
}

void AITF_action(thread_data* data){

	AITF_packet apacket = AITF_packet((uint8_t*)data->buff, data->size);

	cout << apacket.to_string();

	switch(apacket.packet_type())
	{
		case 0:
			AITF_enforce(apacket, data->addr);
			break;
		case 1:
			AITF_request(apacket);
			break;
		case 2:
			AITF_verify(apacket);
			break;
		case 3:
			AITF_correct(apacket);
			break;
		case 4:
			AITF_block(apacket);
			break;
		case 5:
		default:
			AITF_cease(apacket);
	}
	free(data);
}

void AITF_daemon(void* data){
	int portNumber = 11467;

	struct sockaddr_in serv_addr, client_addr;
	int fd = 0;
	int fdlisten = 0;
	int fdconn = 0;
	int out = 0;
	unsigned int client = sizeof(client_addr);

	// Establish the socket that will be used for listening
	fd = socket(AF_INET, SOCK_DGRAM, 0);
	printf("Socket: %d\n", fd);

	// Do a bind of that socket
	serv_addr.sin_family = AF_INET;
	serv_addr.sin_port = htons(portNumber);
	serv_addr.sin_addr.s_addr = htonl(INADDR_ANY);
	bind( fd, (struct sockaddr*)&serv_addr, sizeof(serv_addr));

	// Set up to listen
	listen( fd, 10);
	fdlisten = fd;

	ssize_t tsdata;
	thread_data* buff;
	while(1)
	{
		buff = (thread_data*) malloc(sizeof(thread_data));
		tsdata =  recvfrom(fdlisten, buff->buff, 1500, 0, (struct sockaddr *)&client_addr, &client);

		if (tsdata > 0){
			uint32_t conn_addr = client_addr.sin_addr.s_addr;
			buff->addr = IP::address_type(conn_addr);
			buff->size = tsdata;
			pthread_t helper;
			pthread_create(&helper, NULL, (void*(*)(void*))AITF_action, buff);
		}else{
			free(buff);
		}
	}
}

int intializeAITF(void* filtertable){
	int aitf_thread = 0;
	pthread_t helper;
	pthread_create(&helper, NULL, (void*(*)(void*))AITF_daemon, filtertable);

}<|endoftext|>


<commit_before>// -*- C++ -*-

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

#include <gtest/gtest.h>
#include "math.hpp"

template<unsigned N>
void sysslv(double a[N][N], double b[N])
{
    unsigned n = N;
    double biga,save;
    int i,j,k,imax;

    for (j=0;j<n;j++) {
        biga=0.0;
        for(i=j;i<n;i++)
        if (std::fabs(biga) < std::fabs(a[i][j])) {
            biga=a[i][j];
            imax=i;
        }
        if (std::fabs(biga) == 0.0) {
            throw std::logic_error("Very singular matrix...");
        }
        for (k=j;k<n;k++) {
            save=a[imax][k];
            a[imax][k]=a[j][k];
            a[j][k]=save/biga;
        }
        save=b[imax];
        b[imax]=b[j];
        b[j]=save/biga;
        for (i=j+1;i<n;i++) {
            for(k=j+1;k<n;k++)
                a[i][k] -= a[i][j]*a[j][k];
            b[i] -= b[j]*a[i][j];
        }
    }
    for (k=n-2;k>=0;k--)
        for(j=n-1;j>k;j--)
            b[k] -= a[k][j]*b[j];
}

TEST(cftSuite, test_cosfft1)
{
    RowVectorXd x(3), x_inv(3);

    x     << 1.,  2., 3.;
    x_inv << 6., -2., 2.;

    cosfft1(x, 2);

    EXPECT_DOUBLE_EQ((x - x_inv).norm(), 0.0);
}

TEST(cftSuite, test_cf2)
{
    RowMatrixXd m(3, 3), m_inv(3, 3);

    m << 1., 2., 3.,
         4., 5., 6.,
         7., 8., 9.;
    m_inv << 6.,  4., 10.,
            18., 10., 22.,
            30., 16., 34.;

    cft2(m, 2);

    EXPECT_DOUBLE_EQ((m - m_inv).norm(), 0.0);
}

TEST(bsSuite, test_gauss_elim)
{
    // https://mxncalc.com/gaussian-elimination-calculator
    double A[4][4] = {{1.,  2., 3.,  4.},
                      {5.,  6., 8.,  5.},
                      {4., 15., 2., 12.},
                      {3.,  2., 5.,  6.},};
    double b[4] = {11., 12., 3., 7.,};
    double x[4] = { -7.127'853'881'278'5,
                     1.237'442'922'374'4,
                     4.858'447'488'584'5,
                     0.269'406'392'694'06,
                  };
    sysslv(A, b);
    Eigen::Vector4d bb(b), xx(x);

    EXPECT_DOUBLE_EQ((bb - xx).norm(), 0.0);
    // Expected equality of these values:
    //   (bb - xx).norm()
    //     Which is: 5.3413613165043815e-14
    //   0.0
    //     Which is: 0

}
<commit_msg>pass Gaussian elimination test using eps for comparison.<commit_after>// -*- C++ -*-

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

#include <gtest/gtest.h>
#include "math.hpp"

template<unsigned N>
void sysslv(double a[N][N], double b[N])
{
    unsigned n = N;
    double biga,save;
    int i,j,k,imax;

    for (j=0;j<n;j++) {
        biga=0.0;
        for(i=j;i<n;i++)
        if (std::fabs(biga) < std::fabs(a[i][j])) {
            biga=a[i][j];
            imax=i;
        }
        if (std::fabs(biga) == 0.0) {
            throw std::logic_error("Very singular matrix...");
        }
        for (k=j;k<n;k++) {
            save=a[imax][k];
            a[imax][k]=a[j][k];
            a[j][k]=save/biga;
        }
        save=b[imax];
        b[imax]=b[j];
        b[j]=save/biga;
        for (i=j+1;i<n;i++) {
            for(k=j+1;k<n;k++)
                a[i][k] -= a[i][j]*a[j][k];
            b[i] -= b[j]*a[i][j];
        }
    }
    for (k=n-2;k>=0;k--)
        for(j=n-1;j>k;j--)
            b[k] -= a[k][j]*b[j];
}

TEST(cftSuite, test_cosfft1)
{
    RowVectorXd x(3), x_inv(3);

    x     << 1.,  2., 3.;
    x_inv << 6., -2., 2.;

    cosfft1(x, 2);

    EXPECT_DOUBLE_EQ((x - x_inv).norm(), 0.0);
}

TEST(cftSuite, test_cf2)
{
    RowMatrixXd m(3, 3), m_inv(3, 3);

    m << 1., 2., 3.,
         4., 5., 6.,
         7., 8., 9.;
    m_inv << 6.,  4., 10.,
            18., 10., 22.,
            30., 16., 34.;

    cft2(m, 2);

    EXPECT_DOUBLE_EQ((m - m_inv).norm(), 0.0);
}

TEST(bsSuite, test_gauss_elim)
{
    // https://mxncalc.com/gaussian-elimination-calculator
    double A[4][4] = {{1.,  2., 3.,  4.},
                      {5.,  6., 8.,  5.},
                      {4., 15., 2., 12.},
                      {3.,  2., 5.,  6.},};
    double b[4] = {11., 12., 3., 7.,};
    double x[4] = { -7.127'853'881'278'5,
                     1.237'442'922'374'4,
                     4.858'447'488'584'5,
                     0.269'406'392'694'06,
                  };
    sysslv(A, b);
    Eigen::Vector4d bb(b), xx(x);

    //EXPECT_DOUBLE_EQ((bb - xx).norm(), 0.0);
    // Expected equality of these values:
    //   (bb - xx).norm()
    //     Which is: 5.3413613165043815e-14
    //   0.0
    //     Which is: 0
    EXPECT_NEAR((bb - xx).norm(), 0.0, 1e-12);
}
<|endoftext|>