<commit_before>/***************************************************************************
                          msnfiletransfersocket.cpp  -  description
                             -------------------
    begin                : mer jui 31 2002
    copyright            : (C) 2002 by Olivier Goffart
    email                : ogoffart@tiscalinet.be
 ***************************************************************************/

/***************************************************************************
 *                                                                         *
 *   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 "msnfiletransfersocket.h"

#include <math.h>

//qt
#include <qfile.h>
#include <qregexp.h>
#include <qtimer.h>

// kde
#include <kdebug.h>
#include <kextendedsocket.h>
#include <kfiledialog.h>
#include <klocale.h>
#include <kmessagebox.h>
#include <ksockaddr.h>

#include "kopetetransfermanager.h"
#include "msnprotocol.h"

MSNFileTransferSocket::MSNFileTransferSocket(bool incoming, QObject* parent) : MSNSocket(parent)
{
	m_kopeteTransfer=0l;
	m_incoming=incoming;
	m_file=0L;
	m_server=0L;
	ready=true;

	QObject::connect( this, SIGNAL( socketClosed( int ) ), this, SLOT( slotSocketClosed( ) ) );
	QObject::connect( this, SIGNAL( blockRead( const QByteArray & ) ), this, SLOT(slotReadBlock( const QByteArray & ) ) );
}

MSNFileTransferSocket::~MSNFileTransferSocket()
{
	delete m_file;
	delete m_server;
	kdDebug() << "MSNFileTransferSocket::~MSNFileTransferSocket" <<endl;
}

void MSNFileTransferSocket::parseCommand(const QString & cmd, uint id, const QString & data)
{
	if( cmd == "VER" )
	{
		if(data.section( ' ', 0, 0 ) != "MSNFTP")
		{
			kdDebug() << "MSNFileTransferSocket::parseCommand (VER): bad version: disconnect" <<endl;
			disconnect();
		}
		else
		{
			if( m_incoming )
				sendCommand( "USR", m_protocol->myself()->contactId() + " " + m_authcook, false );
			else
				sendCommand( "VER", "MSNFTP" , false );
		}
	}
	else if( cmd == "FIL" )
	{
		m_size=id; //data.toUInt(); //BUG: the size is take as id bye MSNSocket because it is a number

		m_downsize=0;
		m_file=new QFile(m_fileName);

		if( m_file->open( IO_WriteOnly ))
			sendCommand( "TFR" ,NULL,false);
		else
		{
			kdDebug() << "MSNFileTransferSocket::parseCommand: ERROR: unable to open file - disconnect " <<endl;
			disconnect();
		}
	}
	else if( cmd == "BYE" )
	{
		kdDebug() << "MSNFileTransferSocket::parseCommand : end of transfer " <<endl;
		disconnect();
	}
	else if( cmd == "USR" )
	{
		if(data.section( ' ', 1, 1 )!= m_authcook)
		{
			kdDebug() << "MSNFileTransferSocket::parseCommand (USR): bad auth" <<endl;
			disconnect();
		}
		else
			sendCommand("FIL" , QString::number(size()) , false);
	}
	else if( cmd == "TFR" )
	{
		m_downsize=0;
		ready=true;
		QTimer::singleShot( 0, this, SLOT(slotSendFile()) );
	}
	else if( cmd == "CCL" )
	{
		disconnect();
	}
	else
		kdDebug() << "MSNFileTransferSocket::parseCommand : unknown command " <<cmd <<endl;

//	kdDebug() << "MSNFileTransferSocket::parseCommand : done " <<cmd <<endl;
}

void MSNFileTransferSocket::doneConnect()
{
	if(m_incoming)
		sendCommand( "VER", "MSNFTP", false );
	MSNSocket::doneConnect();
}

void MSNFileTransferSocket::bytesReceived(const QByteArray & head)
{
	if(head[0]!='\0')
	{
		kdDebug() << "MSNFileTransferSocket::bytesReceived: transfer aborted" <<endl;
		disconnect();
	}
	unsigned int sz=(int)((unsigned char)head.data()[2])*256+(int)((unsigned char)head.data()[1]);
//	kdDebug() << "MSNFileTransferSocket::bytesReceived: " << sz <<endl;
	readBlock(sz);
}

void MSNFileTransferSocket::slotSocketClosed()
{
	kdDebug() << "MSNFileTransferSocket::slotSocketClose "<<  endl;
	if(m_file)
		m_file->close();
	delete m_file;
	m_file=0L;
	delete m_server;
	m_server=0L;
	if(m_kopeteTransfer && (m_downsize!=m_size  || m_downsize==0 ) )
		m_kopeteTransfer->setError(KopeteTransfer::Other);
	emit done(this);
}

void MSNFileTransferSocket::slotReadBlock(const QByteArray &block)
{
	m_file->writeBlock( block.data(), block.size() );      // write to file
	m_downsize+=block.size();
	int percent=0;
	if(m_size!=0)   percent=100*m_downsize/m_size;

	if(m_kopeteTransfer) m_kopeteTransfer->slotPercentCompleted(percent);
	kdDebug() << "MSNFileTransferSocket  -  " <<percent <<"% done"<<endl;

	if(m_downsize==m_size)
		sendCommand( "BYE" ,"16777989",false);
}

void MSNFileTransferSocket::setKopeteTransfer(KopeteTransfer *kt)
{
	m_kopeteTransfer=kt;
	if(kt)
		QObject::connect(kt , SIGNAL(transferCanceled()), this, SLOT(abort()));
}

void MSNFileTransferSocket::listen(int port)
{
	m_server = new KExtendedSocket();

	QObject::connect( m_server, SIGNAL(readyAccept()), this,  SLOT(slotAcceptConnection()));
	m_server->setPort(port);
	m_server->setSocketFlags(  KExtendedSocket::noResolve
                            | KExtendedSocket::passiveSocket
                            | KExtendedSocket::anySocket);
	int listenResult = m_server->listen(1);

	kdDebug() << "MSNFileTransferSocket::listen: result: "<<  listenResult <<endl;
	m_server->setBlockingMode(true);
	QTimer::singleShot( 60000, this, SLOT(slotTimer()) );
	kdDebug() << "MSNFileTransferSocket::listen done" <<endl;
}

void MSNFileTransferSocket::slotAcceptConnection()
{
	kdDebug() << "MSNFileTransferSocket::slotAcceptConnection" <<endl;
	if(!accept(m_server))
	{
		if( m_kopeteTransfer)
			m_kopeteTransfer->setError(KopeteTransfer::Other);
		emit done(this);
	}
}

void MSNFileTransferSocket::slotTimer()
{
	if(onlineStatus() != Disconnected)
		return;
	kdDebug() << "MSNFileTransferSocket::slotTimer: timeout "<<  endl;
	if( m_kopeteTransfer)
	{
		m_kopeteTransfer->setError(KopeteTransfer::Timeout);
	}
	emit done(this);
}

void MSNFileTransferSocket::abort()
{
	if(m_incoming)
		sendCommand( "CCL" , NULL ,false);
	disconnect();
//	emit done(this);
}

void MSNFileTransferSocket::setFile(const QString &fn, long unsigned int fileSize = 0L)
{
	m_fileName=fn;
	if(!m_incoming)
	{
		if(m_file)
		{
			kdDebug() << "MSNFileTransferSocket::setFileName: WARNING m_file already exists" << endl;
			delete m_file;
		}
		m_file = new QFile( fn );
		if(!m_file->open(IO_ReadOnly))
		{
			//FIXME: abort transfer here
			kdDebug() << "MSNFileTransferSocket::setFileName: WARNING unable to open the file" << endl;
		}

		//If the fileSize is 0 it was not given, we are to get it from the file
		if(fileSize == 0L)
			m_size = m_file->size();
		else
			m_size = fileSize;
	}
}

void MSNFileTransferSocket::slotSendFile()
{
//	kdDebug() <<"MSNFileTransferSocket::slotSendFile()" <<endl;
	if( m_downsize >= m_size)
		return;

	if(ready)
	{
		char data[2046];
		int bytesRead = m_file->readBlock( data, 2045 );

		QByteArray block(bytesRead+3);
//		char i1= (char)fmod( bytesRead, 256 ) ;
//		char i2= (char)floor( bytesRead / 256 ) ;
//		kdDebug() << "MSNFileTransferSocket::slotSendFile: " << (int)i1 <<" + 256* "<< (int)i2 <<" = " << bytesRead <<endl;
		block[0]='\0';
		block[1]= (char)fmod( bytesRead, 256 );
		block[2]= (char)floor( bytesRead / 256 );

		for (  int f = 0; f < bytesRead; f++ )
		{
			block[f+3] = data[f];
		}

		sendBytes(block);

		int percent=0;
		m_downsize+=bytesRead;
		if(m_size!=0)   percent=100*m_downsize/m_size;
		if(m_kopeteTransfer)
			 m_kopeteTransfer->slotPercentCompleted(percent);
		kdDebug() << "MSNFileTransferSocket::slotSendFile:  " <<percent <<"% done"<<endl;
	}
	ready=false;

	QTimer::singleShot( 10, this, SLOT(slotSendFile()) );
}

void MSNFileTransferSocket::slotReadyWrite()
{
	ready=true;
	MSNSocket::slotReadyWrite();
}

#include "msnfiletransfersocket.moc"

<commit_msg>no default args in a .cpp file, they are already in the .h file<commit_after>/***************************************************************************
                          msnfiletransfersocket.cpp  -  description
                             -------------------
    begin                : mer jui 31 2002
    copyright            : (C) 2002 by Olivier Goffart
    email                : ogoffart@tiscalinet.be
 ***************************************************************************/

/***************************************************************************
 *                                                                         *
 *   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 "msnfiletransfersocket.h"

#include <math.h>

//qt
#include <qfile.h>
#include <qregexp.h>
#include <qtimer.h>

// kde
#include <kdebug.h>
#include <kextendedsocket.h>
#include <kfiledialog.h>
#include <klocale.h>
#include <kmessagebox.h>
#include <ksockaddr.h>

#include "kopetetransfermanager.h"
#include "msnprotocol.h"

MSNFileTransferSocket::MSNFileTransferSocket(bool incoming, QObject* parent) : MSNSocket(parent)
{
	m_kopeteTransfer=0l;
	m_incoming=incoming;
	m_file=0L;
	m_server=0L;
	ready=true;

	QObject::connect( this, SIGNAL( socketClosed( int ) ), this, SLOT( slotSocketClosed( ) ) );
	QObject::connect( this, SIGNAL( blockRead( const QByteArray & ) ), this, SLOT(slotReadBlock( const QByteArray & ) ) );
}

MSNFileTransferSocket::~MSNFileTransferSocket()
{
	delete m_file;
	delete m_server;
	kdDebug() << "MSNFileTransferSocket::~MSNFileTransferSocket" <<endl;
}

void MSNFileTransferSocket::parseCommand(const QString & cmd, uint id, const QString & data)
{
	if( cmd == "VER" )
	{
		if(data.section( ' ', 0, 0 ) != "MSNFTP")
		{
			kdDebug() << "MSNFileTransferSocket::parseCommand (VER): bad version: disconnect" <<endl;
			disconnect();
		}
		else
		{
			if( m_incoming )
				sendCommand( "USR", m_protocol->myself()->contactId() + " " + m_authcook, false );
			else
				sendCommand( "VER", "MSNFTP" , false );
		}
	}
	else if( cmd == "FIL" )
	{
		m_size=id; //data.toUInt(); //BUG: the size is take as id bye MSNSocket because it is a number

		m_downsize=0;
		m_file=new QFile(m_fileName);

		if( m_file->open( IO_WriteOnly ))
			sendCommand( "TFR" ,NULL,false);
		else
		{
			kdDebug() << "MSNFileTransferSocket::parseCommand: ERROR: unable to open file - disconnect " <<endl;
			disconnect();
		}
	}
	else if( cmd == "BYE" )
	{
		kdDebug() << "MSNFileTransferSocket::parseCommand : end of transfer " <<endl;
		disconnect();
	}
	else if( cmd == "USR" )
	{
		if(data.section( ' ', 1, 1 )!= m_authcook)
		{
			kdDebug() << "MSNFileTransferSocket::parseCommand (USR): bad auth" <<endl;
			disconnect();
		}
		else
			sendCommand("FIL" , QString::number(size()) , false);
	}
	else if( cmd == "TFR" )
	{
		m_downsize=0;
		ready=true;
		QTimer::singleShot( 0, this, SLOT(slotSendFile()) );
	}
	else if( cmd == "CCL" )
	{
		disconnect();
	}
	else
		kdDebug() << "MSNFileTransferSocket::parseCommand : unknown command " <<cmd <<endl;

//	kdDebug() << "MSNFileTransferSocket::parseCommand : done " <<cmd <<endl;
}

void MSNFileTransferSocket::doneConnect()
{
	if(m_incoming)
		sendCommand( "VER", "MSNFTP", false );
	MSNSocket::doneConnect();
}

void MSNFileTransferSocket::bytesReceived(const QByteArray & head)
{
	if(head[0]!='\0')
	{
		kdDebug() << "MSNFileTransferSocket::bytesReceived: transfer aborted" <<endl;
		disconnect();
	}
	unsigned int sz=(int)((unsigned char)head.data()[2])*256+(int)((unsigned char)head.data()[1]);
//	kdDebug() << "MSNFileTransferSocket::bytesReceived: " << sz <<endl;
	readBlock(sz);
}

void MSNFileTransferSocket::slotSocketClosed()
{
	kdDebug() << "MSNFileTransferSocket::slotSocketClose "<<  endl;
	if(m_file)
		m_file->close();
	delete m_file;
	m_file=0L;
	delete m_server;
	m_server=0L;
	if(m_kopeteTransfer && (m_downsize!=m_size  || m_downsize==0 ) )
		m_kopeteTransfer->setError(KopeteTransfer::Other);
	emit done(this);
}

void MSNFileTransferSocket::slotReadBlock(const QByteArray &block)
{
	m_file->writeBlock( block.data(), block.size() );      // write to file
	m_downsize+=block.size();
	int percent=0;
	if(m_size!=0)   percent=100*m_downsize/m_size;

	if(m_kopeteTransfer) m_kopeteTransfer->slotPercentCompleted(percent);
	kdDebug() << "MSNFileTransferSocket  -  " <<percent <<"% done"<<endl;

	if(m_downsize==m_size)
		sendCommand( "BYE" ,"16777989",false);
}

void MSNFileTransferSocket::setKopeteTransfer(KopeteTransfer *kt)
{
	m_kopeteTransfer=kt;
	if(kt)
		QObject::connect(kt , SIGNAL(transferCanceled()), this, SLOT(abort()));
}

void MSNFileTransferSocket::listen(int port)
{
	m_server = new KExtendedSocket();

	QObject::connect( m_server, SIGNAL(readyAccept()), this,  SLOT(slotAcceptConnection()));
	m_server->setPort(port);
	m_server->setSocketFlags(  KExtendedSocket::noResolve
                            | KExtendedSocket::passiveSocket
                            | KExtendedSocket::anySocket);
	int listenResult = m_server->listen(1);

	kdDebug() << "MSNFileTransferSocket::listen: result: "<<  listenResult <<endl;
	m_server->setBlockingMode(true);
	QTimer::singleShot( 60000, this, SLOT(slotTimer()) );
	kdDebug() << "MSNFileTransferSocket::listen done" <<endl;
}

void MSNFileTransferSocket::slotAcceptConnection()
{
	kdDebug() << "MSNFileTransferSocket::slotAcceptConnection" <<endl;
	if(!accept(m_server))
	{
		if( m_kopeteTransfer)
			m_kopeteTransfer->setError(KopeteTransfer::Other);
		emit done(this);
	}
}

void MSNFileTransferSocket::slotTimer()
{
	if(onlineStatus() != Disconnected)
		return;
	kdDebug() << "MSNFileTransferSocket::slotTimer: timeout "<<  endl;
	if( m_kopeteTransfer)
	{
		m_kopeteTransfer->setError(KopeteTransfer::Timeout);
	}
	emit done(this);
}

void MSNFileTransferSocket::abort()
{
	if(m_incoming)
		sendCommand( "CCL" , NULL ,false);
	disconnect();
//	emit done(this);
}

void MSNFileTransferSocket::setFile( const QString &fn, long unsigned int fileSize )
{
	m_fileName=fn;
	if(!m_incoming)
	{
		if(m_file)
		{
			kdDebug() << "MSNFileTransferSocket::setFileName: WARNING m_file already exists" << endl;
			delete m_file;
		}
		m_file = new QFile( fn );
		if(!m_file->open(IO_ReadOnly))
		{
			//FIXME: abort transfer here
			kdDebug() << "MSNFileTransferSocket::setFileName: WARNING unable to open the file" << endl;
		}

		//If the fileSize is 0 it was not given, we are to get it from the file
		if(fileSize == 0L)
			m_size = m_file->size();
		else
			m_size = fileSize;
	}
}

void MSNFileTransferSocket::slotSendFile()
{
//	kdDebug() <<"MSNFileTransferSocket::slotSendFile()" <<endl;
	if( m_downsize >= m_size)
		return;

	if(ready)
	{
		char data[2046];
		int bytesRead = m_file->readBlock( data, 2045 );

		QByteArray block(bytesRead+3);
//		char i1= (char)fmod( bytesRead, 256 ) ;
//		char i2= (char)floor( bytesRead / 256 ) ;
//		kdDebug() << "MSNFileTransferSocket::slotSendFile: " << (int)i1 <<" + 256* "<< (int)i2 <<" = " << bytesRead <<endl;
		block[0]='\0';
		block[1]= (char)fmod( bytesRead, 256 );
		block[2]= (char)floor( bytesRead / 256 );

		for (  int f = 0; f < bytesRead; f++ )
		{
			block[f+3] = data[f];
		}

		sendBytes(block);

		int percent=0;
		m_downsize+=bytesRead;
		if(m_size!=0)   percent=100*m_downsize/m_size;
		if(m_kopeteTransfer)
			 m_kopeteTransfer->slotPercentCompleted(percent);
		kdDebug() << "MSNFileTransferSocket::slotSendFile:  " <<percent <<"% done"<<endl;
	}
	ready=false;

	QTimer::singleShot( 10, this, SLOT(slotSendFile()) );
}

void MSNFileTransferSocket::slotReadyWrite()
{
	ready=true;
	MSNSocket::slotReadyWrite();
}

#include "msnfiletransfersocket.moc"

<|endoftext|>


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

The Medical Imaging Interaction Toolkit (MITK)

Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics.
All rights reserved.

This software is distributed WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE.

See LICENSE.txt or http://www.mitk.org for details.

===================================================================*/

//#define _USE_MATH_DEFINES
#include <QmitkUSDeviceManagerWidget.h>

const std::string QmitkUSDeviceManagerWidget::VIEW_ID = "org.mitk.views.QmitkUSDeviceManagerWidget";

QmitkUSDeviceManagerWidget::QmitkUSDeviceManagerWidget(QWidget* parent, Qt::WindowFlags f): QWidget(parent, f)
{
  m_Controls = NULL;
  CreateQtPartControl(this);
}

QmitkUSDeviceManagerWidget::~QmitkUSDeviceManagerWidget()
{
}

//////////////////// INITIALIZATION /////////////////////

void QmitkUSDeviceManagerWidget::CreateQtPartControl(QWidget *parent)
{
  if (!m_Controls)
  {
    // create GUI widgets
    m_Controls = new Ui::QmitkUSDeviceManagerWidgetControls;
    m_Controls->setupUi(parent);
    this->CreateConnections();
  }

  // Initializations
  std::string empty = "";
  m_Controls->m_ConnectedDevices->Initialize<mitk::USDevice>(mitk::USDevice::US_PROPKEY_LABEL, empty);
}

void QmitkUSDeviceManagerWidget::CreateConnections()
{
  if ( m_Controls )
  {
    connect( m_Controls->m_BtnActivate,   SIGNAL( clicked() ), this, SLOT(OnClickedActivateDevice()) );
    connect( m_Controls->m_BtnDisconnect, SIGNAL( clicked() ), this, SLOT(OnClickedDisconnectDevice()) );
    connect( m_Controls->m_ConnectedDevices, SIGNAL( ServiceSelectionChanged(mitk::ServiceReference) ), this, SLOT(OnDeviceSelectionChanged(mitk::ServiceReference)) );
  }
}

///////////// Methods & Slots Handling Direct Interaction /////////////////

void QmitkUSDeviceManagerWidget::OnClickedActivateDevice()
{
  mitk::USDevice::Pointer device = m_Controls->m_ConnectedDevices->GetSelectedServiceAsClass<mitk::USDevice>();
  if (device.IsNull()) return;
  if (device->GetIsActive()) device->Deactivate();
  else device->Activate();

  // Manually reevaluate Button logic
  OnDeviceSelectionChanged(m_Controls->m_ConnectedDevices->GetSelectedService());
}

void QmitkUSDeviceManagerWidget::OnClickedDisconnectDevice(){
  mitk::USDevice::Pointer device = m_Controls->m_ConnectedDevices->GetSelectedServiceAsClass<mitk::USDevice>();
  if (device.IsNull()) return;
  device->Disconnect();
}

void QmitkUSDeviceManagerWidget::OnDeviceSelectionChanged(mitk::ServiceReference reference){
  if (! reference)
  {
    m_Controls->m_BtnActivate->setEnabled(false);
    m_Controls->m_BtnDisconnect->setEnabled(false);
    return;
  }
  std::string isActive = reference.GetProperty( mitk::USDevice::US_PROPKEY_ISACTIVE ).ToString();
  if (isActive.compare("true") == 0)
  {
    m_Controls->m_BtnActivate->setEnabled(true);
    m_Controls->m_BtnDisconnect->setEnabled(false);
    m_Controls->m_BtnActivate->setText("Deactivate");
  }
  else
  {
    m_Controls->m_BtnActivate->setEnabled(true);
    m_Controls->m_BtnDisconnect->setEnabled(true);
    m_Controls->m_BtnActivate->setText("Activate");
  }
}

<commit_msg>COMP: Fixed Wrong Method Names in GUI Classes<commit_after>/*===================================================================

The Medical Imaging Interaction Toolkit (MITK)

Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics.
All rights reserved.

This software is distributed WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE.

See LICENSE.txt or http://www.mitk.org for details.

===================================================================*/

//#define _USE_MATH_DEFINES
#include <QmitkUSDeviceManagerWidget.h>

const std::string QmitkUSDeviceManagerWidget::VIEW_ID = "org.mitk.views.QmitkUSDeviceManagerWidget";

QmitkUSDeviceManagerWidget::QmitkUSDeviceManagerWidget(QWidget* parent, Qt::WindowFlags f): QWidget(parent, f)
{
  m_Controls = NULL;
  CreateQtPartControl(this);
}

QmitkUSDeviceManagerWidget::~QmitkUSDeviceManagerWidget()
{
}

//////////////////// INITIALIZATION /////////////////////

void QmitkUSDeviceManagerWidget::CreateQtPartControl(QWidget *parent)
{
  if (!m_Controls)
  {
    // create GUI widgets
    m_Controls = new Ui::QmitkUSDeviceManagerWidgetControls;
    m_Controls->setupUi(parent);
    this->CreateConnections();
  }

  // Initializations
  std::string empty = "";
  m_Controls->m_ConnectedDevices->Initialize<mitk::USDevice>(mitk::USDevice::US_PROPKEY_LABEL, empty);
}

void QmitkUSDeviceManagerWidget::CreateConnections()
{
  if ( m_Controls )
  {
    connect( m_Controls->m_BtnActivate,   SIGNAL( clicked() ), this, SLOT(OnClickedActivateDevice()) );
    connect( m_Controls->m_BtnDisconnect, SIGNAL( clicked() ), this, SLOT(OnClickedDisconnectDevice()) );
    connect( m_Controls->m_ConnectedDevices, SIGNAL( ServiceSelectionChanged(mitk::ServiceReference) ), this, SLOT(OnDeviceSelectionChanged(mitk::ServiceReference)) );
  }
}

///////////// Methods & Slots Handling Direct Interaction /////////////////

void QmitkUSDeviceManagerWidget::OnClickedActivateDevice()
{
  mitk::USDevice::Pointer device = m_Controls->m_ConnectedDevices->GetSelectedService<mitk::USDevice>();
  if (device.IsNull()) return;
  if (device->GetIsActive()) device->Deactivate();
  else device->Activate();

  // Manually reevaluate Button logic
  OnDeviceSelectionChanged(m_Controls->m_ConnectedDevices->GetSelectedServiceReference());
}

void QmitkUSDeviceManagerWidget::OnClickedDisconnectDevice(){
  mitk::USDevice::Pointer device = m_Controls->m_ConnectedDevices->GetSelectedService<mitk::USDevice>();
  if (device.IsNull()) return;
  device->Disconnect();
}

void QmitkUSDeviceManagerWidget::OnDeviceSelectionChanged(mitk::ServiceReference reference){
  if (! reference)
  {
    m_Controls->m_BtnActivate->setEnabled(false);
    m_Controls->m_BtnDisconnect->setEnabled(false);
    return;
  }
  std::string isActive = reference.GetProperty( mitk::USDevice::US_PROPKEY_ISACTIVE ).ToString();
  if (isActive.compare("true") == 0)
  {
    m_Controls->m_BtnActivate->setEnabled(true);
    m_Controls->m_BtnDisconnect->setEnabled(false);
    m_Controls->m_BtnActivate->setText("Deactivate");
  }
  else
  {
    m_Controls->m_BtnActivate->setEnabled(true);
    m_Controls->m_BtnDisconnect->setEnabled(true);
    m_Controls->m_BtnActivate->setText("Activate");
  }
}

<|endoftext|>


<commit_before>#include <vector>
#include <iostream>

#include <SFML/Graphics.hpp>

#include "Body.hpp"

#define MASS 1
#define BASE_LINE 2

using namespace sf;
using namespace std;

int main()
{
	RenderWindow window(VideoMode(800, 600), "Gravity Simulation by Johan");

	// Drawable elements
	vector<Body> planets;
	VertexArray line(Lines, 2);
	CircleShape base_line(BASE_LINE);

	// Logic vars
	Clock timer;
	float delta_t(0);
	int mass(MASS);
	bool running = true;
	bool is_placing = false;
	bool trace = false;

	// Some inits
	line[0].color = Color::Blue;
	line[1].color = Color::Green;
	base_line.setFillColor(Color::Blue);

	while (running)
	{
		Event evt;
		while (window.pollEvent(evt))
		{
			if (evt.type == Event::Closed)
			{
				running = false;
			}

			if (evt.type == Event::KeyPressed)
			{
				if (evt.key.code == Keyboard::Escape)
				{
					running = false;
				}

				switch (evt.key.code) // TODO: +- mass; toggle "clear()"; pause;
				{
                case Keyboard::PageUp:
				case Keyboard::Add:
					mass += (mass == 1 ? 99 : 100);
					cout << "Mass is now " << mass << endl;
					break;
                case Keyboard::PageDown:
				case Keyboard::Subtract:
					mass -= (mass > 0 ? 100 : 0);
					if (mass < 0)
					{
						mass = 1;
					}
					cout << "Mass is now " << mass << endl;
					break;
				case Keyboard::T:
					trace = !trace;
					cout << "Trace mode activated" << endl;
					break;
				case Keyboard::Space:
                    if (is_placing)
                    {
                        cout << "Planet placement cancelled" << endl;
                    }
                    is_placing = false;
                    break;
				default:
					break;
				}
			}

			if (evt.type == Event::MouseButtonPressed)
			{
				is_placing = true;

				line[0].position = Vector2f(evt.mouseButton.x, evt.mouseButton.y);
				line[1].position = Vector2f(evt.mouseButton.x, evt.mouseButton.y);
				base_line.setPosition(evt.mouseButton.x - BASE_LINE, evt.mouseButton.y - BASE_LINE);
			}

			if (evt.type == Event::MouseMoved)
			{
				if (is_placing)
				{
					line[1].position = Vector2f(evt.mouseMove.x, evt.mouseMove.y);
				}
			}

			if (evt.type == Event::MouseButtonReleased)
			{
				if (is_placing)
				{
					Vector2f position(line[0].position.x - MASS,
							line[0].position.y - MASS);
					Body p(position, mass, line[1].position - line[0].position);

					planets.push_back(p);
				}

				is_placing = false;
			}
		}

		if (!trace)
		{
			window.clear();
		}

		// Delta T
		delta_t = timer.restart().asSeconds();

		// Vector Preview - wow - need an arrow - hard
		if (is_placing)
		{
			window.draw(line);
			window.draw(base_line);
		}

		// Planets
		if (planets.size() > 1)
		{
			for (unsigned int i = 0; i < planets.size(); i++)
			{
				for (unsigned int j = 0; j < planets.size();j++)
				{
					if (i != j)
					{
						if (planets[i].collideWith(planets[j]))
						{
							Body p(planets[i].getPosition(), planets[i].getMass()+planets[j].getMass(),
								   planets[i].getDirection()+planets[j].getDirection());
							planets.erase(planets.begin()+i);
							planets.erase(planets.begin()+j);
							planets.push_back(p);
						}

						planets[i].applyGravityOf(planets[j], delta_t);
					}
				}
			}
		}

		if (planets.size())
		{
			for (Body& b : planets)
			{
				b.move(delta_t);
				b.draw(window);
			}
		}

		window.display();
	}

	return 0;
}
<commit_msg>added momentum conservation when collision happens<commit_after>#include <vector>
#include <iostream>

#include <SFML/Graphics.hpp>

#include "Body.hpp"

#define MASS 1
#define BASE_LINE 2

using namespace sf;
using namespace std;

int main()
{
	RenderWindow window(VideoMode(800, 600), "Gravity Simulation by Johan");

	// Drawable elements
	vector<Body> planets;
	VertexArray line(Lines, 2);
	CircleShape base_line(BASE_LINE);

	// Logic vars
	Clock timer;
	float delta_t(0);
	int mass(MASS);
	bool running = true;
	bool is_placing = false;
	bool trace = false;

	// Some inits
	line[0].color = Color::Blue;
	line[1].color = Color::Green;
	base_line.setFillColor(Color::Blue);

	while (running)
	{
		Event evt;
		while (window.pollEvent(evt))
		{
			if (evt.type == Event::Closed)
			{
				running = false;
			}

			if (evt.type == Event::KeyPressed)
			{
				if (evt.key.code == Keyboard::Escape)
				{
					running = false;
				}

				switch (evt.key.code) // TODO: +- mass; toggle "clear()"; pause;
				{
                case Keyboard::PageUp:
				case Keyboard::Add:
					mass += (mass == 1 ? 99 : 100);
					cout << "Mass is now " << mass << endl;
					break;
                case Keyboard::PageDown:
				case Keyboard::Subtract:
					mass -= (mass > 0 ? 100 : 0);
					if (mass < 0)
					{
						mass = 1;
					}
					cout << "Mass is now " << mass << endl;
					break;
				case Keyboard::T:
					trace = !trace;
					cout << "Trace mode activated" << endl;
					break;
				case Keyboard::Space:
                    if (is_placing)
                    {
                        cout << "Planet placement cancelled" << endl;
                    }
                    is_placing = false;
                    break;
				default:
					break;
				}
			}

			if (evt.type == Event::MouseButtonPressed)
			{
				is_placing = true;

				line[0].position = Vector2f(evt.mouseButton.x, evt.mouseButton.y);
				line[1].position = Vector2f(evt.mouseButton.x, evt.mouseButton.y);
				base_line.setPosition(evt.mouseButton.x - BASE_LINE, evt.mouseButton.y - BASE_LINE);
			}

			if (evt.type == Event::MouseMoved)
			{
				if (is_placing)
				{
					line[1].position = Vector2f(evt.mouseMove.x, evt.mouseMove.y);
				}
			}

			if (evt.type == Event::MouseButtonReleased)
			{
				if (is_placing)
				{
					Vector2f position(line[0].position.x - MASS,
							line[0].position.y - MASS);
					Body p(position, mass, line[1].position - line[0].position);

					planets.push_back(p);
				}

				is_placing = false;
			}
		}

		if (!trace)
		{
			window.clear();
		}

		// Delta T
		delta_t = timer.restart().asSeconds();

		// Vector Preview - wow - need an arrow - hard
		if (is_placing)
		{
			window.draw(line);
			window.draw(base_line);
		}

		// Planets
		if (planets.size() > 1)
		{
			for (unsigned int i = 0; i < planets.size(); i++)
			{
				for (unsigned int j = 0; j < planets.size();j++)
				{
					if (i != j)
					{
						if (planets[i].collideWith(planets[j]))
						{
                            Vector2f p1m1 = planets[i].mass*planets[i].direction;
                            Vector2f p2m2 = planets[j].mass*planets[j].direction;

                            Vector2f Pt = p1m1+p2m2;
                            float Mt = planets[i].mass+planets[j].mass;
                            Vector2f Df = Pt / Mt;

                            planets[i].direction = Df;
                            planets.erase(planets.begin()+j);
						}

						planets[i].applyGravityOf(planets[j], delta_t);
					}
				}
			}
		}

		if (planets.size())
		{
			for (Body& b : planets)
			{
				b.move(delta_t);
				b.draw(window);
			}
		}

		window.display();
	}

	return 0;
}
<|endoftext|>


<commit_before>#include <string.h>
#include <iostream.h>
#include <stdlib.h>
#include <string>
using namespace std;

int main()
{
	string SizeE;
	int SizeA, SizeB, SizeD, SizeC;

	cout << "The Breast Measurer v2.0" << endl << "by endura29@hotmail.com" << endl;
	cout << "Enter the Measurement (in inches) just below the breast: ";
	cin >> SizeA;
	cout << "Enter the Measurement (in inches) at the Nipple: ";
	cin >> SizeB;
	//SizeD = (SizeA + 5);
	//SizeC = (SizeB - SizeD);
	SizeC = SizeB - SizeA;

	//if (SizeD % 2)
	//	SizeD++;
	if (SizeC < 0) {
		cout << "\n" << "Now, that's less than a mouthful!!" << endl;
		return 0;
	}

	switch (SizeC)
	{
		case 0:
			SizeE = "AA";
			break;
		case 1:
			SizeE = "A";
			break;
		case 2:
			SizeE = "B";
			break;
		case 3:
			SizeE = "C";
			break;
		case 4:
			SizeE = "D";
			break;
		case 5:
			SizeE = "DD";
			break;
		case 6:
			SizeE = "F";
			break;
		case 7:
			SizeE = "G";
			break;
		case 8:
			SizeE = "H";
			break;
		case 9:
			SizeE = "I";
			break;
		default:
			cout << "Damn, that's a lotta boobs!" << endl;
			return 0;
	}

	cout << "Bra Size: " << SizeA << SizeE.c_str() << endl;

	return 0;
}
<commit_msg>Removed<commit_after><|endoftext|>


<commit_before>//
//  GridMesh.cpp
//
//  Created by Soso Limited on 5/15/15.
//
//

#include "GridMesh.h"
#include "cinder/gl/gl.h"
#include "cinder/Log.h"

using namespace cinder;
using namespace soso;

namespace {
  struct Vertex
	{
		ci::vec3	position;
		ci::vec2	tex_coord;
		float			time_offset;
	};

	// Since we are supporting ES2, we can't use shape instancing.
	// On ES3 hardware, we could use a single cross shape and instance it.
	void appendCross( std::vector<Vertex> &iVertices, const ci::vec3 &iCenter, const ci::vec2 &iTexCoord, float iTimeOffset )
	{
		iVertices.push_back( Vertex{ iCenter - vec3( 0.1, 0, 0 ), iTexCoord, iTimeOffset } );
		iVertices.push_back( Vertex{ iCenter + vec3( 0.1, 0, 0 ), iTexCoord, iTimeOffset } );

		iVertices.push_back( Vertex{ iCenter - vec3( 0, 0, 0.1 ), iTexCoord, iTimeOffset } );
		iVertices.push_back( Vertex{ iCenter + vec3( 0, 0, 0.1 ), iTexCoord, iTimeOffset } );

		iVertices.push_back( Vertex{ iCenter - vec3( 0, 0.1, 0 ), iTexCoord, iTimeOffset } );
		iVertices.push_back( Vertex{ iCenter + vec3( 0, 0.1, 0 ), iTexCoord, iTimeOffset } );
	}
} // namespace

void GridMesh::setup()
{
	CI_LOG_I("Building GridMesh");
	std::vector<Vertex> vertices;

	const auto dims = ivec3( 50, 8, 50 );
	auto offset = vec3( -dims ) * vec3( 0.5f, 0.025f, 0.5f );

	for( auto y = 0; y < dims.y; y += 1 ) {
		auto time_offset = (float) y / dims.y;
		time_offset *= dims.y / 32.0f;
		for( auto x = 0; x < dims.x; x += 1 ) {
			for( auto z = 0; z < dims.z; z += 1 ) {
				appendCross( vertices, vec3( x, y, z ) + offset, vec2( x, z ) / vec2( dims.x, dims.z ), time_offset );
			}
		}
	}

	auto vbo = gl::Vbo::create( GL_ARRAY_BUFFER, vertices );
	auto layout = geom::BufferLayout();
	layout.append( geom::Attrib::POSITION, 3, sizeof(Vertex), offsetof(Vertex, position) );
	layout.append( geom::Attrib::TEX_COORD_0, 2, sizeof(Vertex), offsetof(Vertex, tex_coord) );
	layout.append( geom::Attrib::CUSTOM_0, 1, sizeof(Vertex), offsetof(Vertex, time_offset) );
	auto mesh = gl::VboMesh::create( vertices.size(), GL_LINES, {{ layout, vbo }} );
	auto shader = gl::GlslProg::create( app::loadAsset("grid_mesh.vs"), app::loadAsset("grid_mesh.fs") );

	batch = gl::Batch::create( mesh, shader, {{ geom::Attrib::CUSTOM_0, "FrameIndex" }} );
}

void GridMesh::draw( float iCurrentFrame ) const
{
	batch->getGlslProg()->uniform( "uFrameIndex", iCurrentFrame );
	batch->draw();
};
<commit_msg>Move grid back up.<commit_after>//
//  GridMesh.cpp
//
//  Created by Soso Limited on 5/15/15.
//
//

#include "GridMesh.h"
#include "cinder/gl/gl.h"
#include "cinder/Log.h"

using namespace cinder;
using namespace soso;

namespace {
  struct Vertex
	{
		ci::vec3	position;
		ci::vec2	tex_coord;
		float			time_offset;
	};

	// Since we are supporting ES2, we can't use shape instancing.
	// On ES3 hardware, we could use a single cross shape and instance it.
	void appendCross( std::vector<Vertex> &iVertices, const ci::vec3 &iCenter, const ci::vec2 &iTexCoord, float iTimeOffset )
	{
		iVertices.push_back( Vertex{ iCenter - vec3( 0.1, 0, 0 ), iTexCoord, iTimeOffset } );
		iVertices.push_back( Vertex{ iCenter + vec3( 0.1, 0, 0 ), iTexCoord, iTimeOffset } );

		iVertices.push_back( Vertex{ iCenter - vec3( 0, 0, 0.1 ), iTexCoord, iTimeOffset } );
		iVertices.push_back( Vertex{ iCenter + vec3( 0, 0, 0.1 ), iTexCoord, iTimeOffset } );

		iVertices.push_back( Vertex{ iCenter - vec3( 0, 0.1, 0 ), iTexCoord, iTimeOffset } );
		iVertices.push_back( Vertex{ iCenter + vec3( 0, 0.1, 0 ), iTexCoord, iTimeOffset } );
	}
} // namespace

void GridMesh::setup()
{
	CI_LOG_I("Building GridMesh");
	std::vector<Vertex> vertices;

	const auto dims = ivec3( 50, 8, 50 );
	auto offset = vec3( -dims ) * vec3( 0.5f, -0.025f, 0.5f );

	for( auto y = 0; y < dims.y; y += 1 ) {
		auto time_offset = (float) y / dims.y;
		time_offset *= dims.y / 32.0f;
		for( auto x = 0; x < dims.x; x += 1 ) {
			for( auto z = 0; z < dims.z; z += 1 ) {
				appendCross( vertices, vec3( x, y, z ) + offset, vec2( x, z ) / vec2( dims.x, dims.z ), time_offset );
			}
		}
	}

	auto vbo = gl::Vbo::create( GL_ARRAY_BUFFER, vertices );
	auto layout = geom::BufferLayout();
	layout.append( geom::Attrib::POSITION, 3, sizeof(Vertex), offsetof(Vertex, position) );
	layout.append( geom::Attrib::TEX_COORD_0, 2, sizeof(Vertex), offsetof(Vertex, tex_coord) );
	layout.append( geom::Attrib::CUSTOM_0, 1, sizeof(Vertex), offsetof(Vertex, time_offset) );
	auto mesh = gl::VboMesh::create( vertices.size(), GL_LINES, {{ layout, vbo }} );
	auto shader = gl::GlslProg::create( app::loadAsset("grid_mesh.vs"), app::loadAsset("grid_mesh.fs") );

	batch = gl::Batch::create( mesh, shader, {{ geom::Attrib::CUSTOM_0, "FrameIndex" }} );
}

void GridMesh::draw( float iCurrentFrame ) const
{
	batch->getGlslProg()->uniform( "uFrameIndex", iCurrentFrame );
	batch->draw();
};
<|endoftext|>


<commit_before>//
// Name:		BuildingDlg3d.cpp
//
// Copyright (c) 2001-2003 Virtual Terrain Project
// Free for all uses, see license.txt for details.
//

#ifdef __GNUG__
	#pragma implementation "BuildingDlg3d.cpp"
#endif

// For compilers that support precompilation, includes "wx/wx.h".
#include "wx/wxprec.h"
#include "wx/image.h"

#ifndef WX_PRECOMP
#include "wx/wx.h"
#endif

#include "vtlib/vtlib.h"
#include "vtlib/core/Terrain.h"
#include "BuildingDlg3d.h"
#include "../Enviro.h"	// for GetCurrentTerrain
#include "vtlib/core/Building3d.h"

extern void EnableContinuousRendering(bool bTrue);

// WDR: class implementations

//----------------------------------------------------------------------------
// BuildingDlg3d
//----------------------------------------------------------------------------

BuildingDlg3d::BuildingDlg3d( wxWindow *parent, wxWindowID id, const wxString &title,
	const wxPoint &position, const wxSize& size, long style ) :
	BuildingDlg( parent, id, title, position, size, style )
{
}

void BuildingDlg3d::Setup(vtBuilding3d *bld3d)
{
	vtTerrain *pTerr = GetCurrentTerrain();
	m_pStructure3d = bld3d;
	m_pSA = &pTerr->GetStructures();
	m_pBuilding = bld3d;
}

void BuildingDlg3d::OnOK( wxCommandEvent &event )
{
	BuildingDlg::OnOK(event);

	vtTerrain *pTerr = GetCurrentTerrain();
	pTerr->GetStructures().ConstructStructure(m_pStructure3d);
}

void BuildingDlg3d::EnableRendering(bool bEnable)
{
	EnableContinuousRendering(bEnable);
}

void BuildingDlg3d::Modified()
{
	vtTerrain *pTerr = GetCurrentTerrain();
	pTerr->GetStructures().ConstructStructure(m_pStructure3d);
}
<commit_msg>added support for building elevation attribute<commit_after>//
// Name:		BuildingDlg3d.cpp
//
// Copyright (c) 2001-2003 Virtual Terrain Project
// Free for all uses, see license.txt for details.
//

#ifdef __GNUG__
	#pragma implementation "BuildingDlg3d.cpp"
#endif

// For compilers that support precompilation, includes "wx/wx.h".
#include "wx/wxprec.h"
#include "wx/image.h"

#ifndef WX_PRECOMP
#include "wx/wx.h"
#endif

#include "vtlib/vtlib.h"
#include "vtlib/core/Terrain.h"
#include "BuildingDlg3d.h"
#include "../Enviro.h"	// for GetCurrentTerrain
#include "vtlib/core/Building3d.h"

extern void EnableContinuousRendering(bool bTrue);

// WDR: class implementations

//----------------------------------------------------------------------------
// BuildingDlg3d
//----------------------------------------------------------------------------

BuildingDlg3d::BuildingDlg3d( wxWindow *parent, wxWindowID id, const wxString &title,
	const wxPoint &position, const wxSize& size, long style ) :
	BuildingDlg( parent, id, title, position, size, style )
{
}

void BuildingDlg3d::Setup(vtBuilding3d *bld3d)
{
	vtTerrain *pTerr = GetCurrentTerrain();
	m_pStructure3d = bld3d;
	BuildingDlg::Setup(&pTerr->GetStructures(), bld3d);
}

void BuildingDlg3d::OnOK( wxCommandEvent &event )
{
	BuildingDlg::OnOK(event);

	vtTerrain *pTerr = GetCurrentTerrain();
	pTerr->GetStructures().ConstructStructure(m_pStructure3d);
}

void BuildingDlg3d::EnableRendering(bool bEnable)
{
	EnableContinuousRendering(bEnable);
}

void BuildingDlg3d::Modified()
{
	vtTerrain *pTerr = GetCurrentTerrain();
	pTerr->GetStructures().ConstructStructure(m_pStructure3d);
}
<|endoftext|>


<commit_before>/**********************************************************************
 *
 * GEOS - Geometry Engine Open Source
 * http://geos.osgeo.org
 *
 * Copyright (C) 2019 Paul Ramsey <pramsey@cleverelephant.ca>
 *
 * This is free software; you can redistribute and/or modify it under
 * the terms of the GNU Lesser General Public Licence as published
 * by the Free Software Foundation.
 * See the COPYING file for more information.
 *
 **********************************************************************/

#include <geos/operation/union/OverlapUnion.h>

#include <geos/geom/Coordinate.h>
#include <geos/geom/CoordinateSequence.h>
#include <geos/geom/CoordinateSequenceFilter.h>
#include <geos/geom/Envelope.h>
#include <geos/geom/GeometryFactory.h>
#include <geos/geom/LineSegment.h>
#include <geos/geom/util/GeometryCombiner.h>
#include <geos/util/TopologyException.h>

namespace geos {
namespace operation {
namespace geounion {

// https://github.com/locationtech/jts/blob/master/modules/core/src/main/java/org/locationtech/jts/operation/union/OverlapUnion.java

using namespace geom;
using namespace geom::util;

/* public */
std::unique_ptr<Geometry>
OverlapUnion::doUnion()
{
    Envelope overlapEnv = overlapEnvelope(g0, g1);
    /**
     * If no overlap, can just combine the geometries
     */
    if (overlapEnv.isNull()) {
        // Geometry* g0Copy = g0->clone().get();
        // Geometry* g1Copy = g1->clone().get();
        return GeometryCombiner::combine(g0, g1);
    }

    std::vector<std::unique_ptr<Geometry>> disjointPolys;

    std::unique_ptr<Geometry> g0Overlap = extractByEnvelope(overlapEnv, g0, disjointPolys);
    std::unique_ptr<Geometry> g1Overlap = extractByEnvelope(overlapEnv, g1, disjointPolys);

    // std::out << "# geoms in common: " << intersectingPolys.size() << std::endl;
    std::unique_ptr<Geometry> theUnion(unionFull(g0Overlap.get(), g1Overlap.get()));
    isUnionSafe = isBorderSegmentsSame(theUnion.get(), overlapEnv);
    if (!isUnionSafe) {
        // overlap union changed border segments... need to do full union
        // std::out <<  "OverlapUnion: Falling back to full union" << std::endl;
        return unionFull(g0, g1);
    }
    else {
        // std::out << "OverlapUnion: fast path" << std::endl;
        return combine(theUnion, disjointPolys);
    }
}

/* private */
Envelope
OverlapUnion::overlapEnvelope(const Geometry* geom0, const Geometry* geom1)
{
    const Envelope* g0Env = geom0->getEnvelopeInternal();
    const Envelope* g1Env = geom1->getEnvelopeInternal();
    Envelope overlapEnv;
    g0Env->intersection(*g1Env, overlapEnv);
    return overlapEnv;
}

/* private */
std::unique_ptr<Geometry>
OverlapUnion::combine(std::unique_ptr<Geometry>& unionGeom, std::vector<std::unique_ptr<Geometry>>& disjointPolys)
{
    if (disjointPolys.size() <= 0)
        return std::move(unionGeom);

    disjointPolys.push_back(std::move(unionGeom));
    return GeometryCombiner::combine(disjointPolys);
}

/* private */
std::unique_ptr<Geometry>
OverlapUnion::extractByEnvelope(const Envelope& env, const Geometry* geom, std::vector<std::unique_ptr<Geometry>>& disjointGeoms)
{
    std::vector<const Geometry*> intersectingGeoms;
    for (std::size_t i = 0; i < geom->getNumGeometries(); i++) {
        const Geometry* elem = geom->getGeometryN(i);
        if (elem->getEnvelopeInternal()->intersects(env)) {
            intersectingGeoms.push_back(elem);
        }
        else {
            disjointGeoms.push_back(elem->clone());
        }
    }
    std::unique_ptr<Geometry> intersectingGeom(geomFactory->buildGeometry(intersectingGeoms));
    return std::move(intersectingGeom);
}

/* private */
std::unique_ptr<Geometry>
OverlapUnion::unionFull(const Geometry* geom0, const Geometry* geom1)
{
    try {
        return geom0->Union(geom1);
    }
    catch (geos::util::TopologyException ex) {
        /**
         * If the overlay union fails,
         * try a buffer union, which often succeeds
         */
        return unionBuffer(geom0, geom1);
    }
}

/* private */
std::unique_ptr<Geometry>
OverlapUnion::unionBuffer(const Geometry* geom0, const Geometry* geom1)
{
    std::unique_ptr<Geometry> copy0 = geom0->clone();
    std::unique_ptr<Geometry> copy1 = geom1->clone();
    std::vector<std::unique_ptr<Geometry>> geoms;
    geoms.push_back(std::move(copy0));
    geoms.push_back(std::move(copy1));
    const GeometryFactory* factory = copy0->getFactory();
    std::unique_ptr<GeometryCollection> gColl(factory->createGeometryCollection(std::move(geoms)));
    return gColl->buffer(0.0);
}

/* private */
bool
OverlapUnion::isBorderSegmentsSame(const Geometry* result, const Envelope& env)
{
    std::vector<LineSegment*> segsBefore = extractBorderSegments(g0, g1, env);
    std::vector<LineSegment*> segsAfter;
    extractBorderSegments(result, env, segsAfter);
    //std::cout << ("# seg before: " << segsBefore.size() << " - # seg after: " << segsAfter.size() << std::endl;
    bool eq = isEqual(segsBefore, segsAfter);

    // Clean up temporary segment arrays
    for (auto seg : segsBefore) delete seg;
    for (auto seg : segsAfter) delete seg;

    return eq;
}

static bool lineSegmentPtrCmp(const LineSegment* a, const LineSegment* b)
{
    return a->compareTo(*b) < 0;
}

/* private */
bool
OverlapUnion::isEqual(std::vector<LineSegment*>& segs0, std::vector<LineSegment*>& segs1)
{
    if (segs0.size() != segs1.size())
        return false;

    std::sort(segs0.begin(), segs0.end(), lineSegmentPtrCmp);
    std::sort(segs1.begin(), segs1.end(), lineSegmentPtrCmp);

    size_t sz = segs0.size();
    for (std::size_t i = 0; i < sz; i++) {
        if (segs0[i]->p0.x != segs1[i]->p0.x ||
            segs0[i]->p0.y != segs1[i]->p0.y ||
            segs0[i]->p1.x != segs1[i]->p1.x ||
            segs0[i]->p1.y != segs1[i]->p1.y)
        {
            return false;
        }
    }

    return true;
}

/* private */
std::vector<LineSegment*>
OverlapUnion::extractBorderSegments(const Geometry* geom0, const Geometry* geom1, const Envelope& env)
{
    std::vector<LineSegment*> segs;
    extractBorderSegments(geom0, env, segs);
    if (geom1 != nullptr)
        extractBorderSegments(geom1, env, segs);
    return segs;
}

/* static */
static bool
intersects(const Envelope& env, const Coordinate& p0, const Coordinate& p1)
{
    return env.intersects(p0) || env.intersects(p1);
}

/* static */
static bool
containsProperly(const Envelope& env, const Coordinate& p)
{
    if (env.isNull()) return false;
    return p.x > env.getMinX() &&
           p.x < env.getMaxX() &&
           p.y > env.getMinY() &&
           p.y < env.getMaxY();
}

/* static */
static bool
containsProperly(const Envelope& env, const Coordinate& p0, const Coordinate& p1)
{
    return containsProperly(env, p0) && containsProperly(env, p1);
}

/* privatef */
void
OverlapUnion::extractBorderSegments(const Geometry* geom, const Envelope& penv, std::vector<LineSegment*>& psegs)
{
    class BorderSegmentFilter : public CoordinateSequenceFilter {

    private:
        std::vector<LineSegment*>* segs;
        const Envelope env;

    public:

        BorderSegmentFilter(const Envelope& penv, std::vector<LineSegment*>* psegs)
            : env(penv),
              segs(psegs) {};

        bool
        isDone() const override { return false; }

        bool
        isGeometryChanged() const override  { return false; }

        void
        filter_ro(const CoordinateSequence& seq, std::size_t i) override
        {
            if (i <= 0) return;

            // extract LineSegment
            const Coordinate& p0 = seq.getAt(i-1);
            const Coordinate& p1 = seq.getAt(i  );
            bool isBorder = intersects(env, p0, p1) && ! containsProperly(env, p0, p1);
            if (isBorder) {
                segs->push_back(new LineSegment(p0, p1));
            }
        };

    };

    BorderSegmentFilter bsf(penv, &psegs);
    geom->apply_ro(bsf);

}

}
}
}
<commit_msg>Reorder members to fix initialization order warning issues by GCC<commit_after>/**********************************************************************
 *
 * GEOS - Geometry Engine Open Source
 * http://geos.osgeo.org
 *
 * Copyright (C) 2019 Paul Ramsey <pramsey@cleverelephant.ca>
 *
 * This is free software; you can redistribute and/or modify it under
 * the terms of the GNU Lesser General Public Licence as published
 * by the Free Software Foundation.
 * See the COPYING file for more information.
 *
 **********************************************************************/

#include <geos/operation/union/OverlapUnion.h>

#include <geos/geom/Coordinate.h>
#include <geos/geom/CoordinateSequence.h>
#include <geos/geom/CoordinateSequenceFilter.h>
#include <geos/geom/Envelope.h>
#include <geos/geom/GeometryFactory.h>
#include <geos/geom/LineSegment.h>
#include <geos/geom/util/GeometryCombiner.h>
#include <geos/util/TopologyException.h>

namespace geos {
namespace operation {
namespace geounion {

// https://github.com/locationtech/jts/blob/master/modules/core/src/main/java/org/locationtech/jts/operation/union/OverlapUnion.java

using namespace geom;
using namespace geom::util;

/* public */
std::unique_ptr<Geometry>
OverlapUnion::doUnion()
{
    Envelope overlapEnv = overlapEnvelope(g0, g1);
    /**
     * If no overlap, can just combine the geometries
     */
    if (overlapEnv.isNull()) {
        // Geometry* g0Copy = g0->clone().get();
        // Geometry* g1Copy = g1->clone().get();
        return GeometryCombiner::combine(g0, g1);
    }

    std::vector<std::unique_ptr<Geometry>> disjointPolys;

    std::unique_ptr<Geometry> g0Overlap = extractByEnvelope(overlapEnv, g0, disjointPolys);
    std::unique_ptr<Geometry> g1Overlap = extractByEnvelope(overlapEnv, g1, disjointPolys);

    // std::out << "# geoms in common: " << intersectingPolys.size() << std::endl;
    std::unique_ptr<Geometry> theUnion(unionFull(g0Overlap.get(), g1Overlap.get()));
    isUnionSafe = isBorderSegmentsSame(theUnion.get(), overlapEnv);
    if (!isUnionSafe) {
        // overlap union changed border segments... need to do full union
        // std::out <<  "OverlapUnion: Falling back to full union" << std::endl;
        return unionFull(g0, g1);
    }
    else {
        // std::out << "OverlapUnion: fast path" << std::endl;
        return combine(theUnion, disjointPolys);
    }
}

/* private */
Envelope
OverlapUnion::overlapEnvelope(const Geometry* geom0, const Geometry* geom1)
{
    const Envelope* g0Env = geom0->getEnvelopeInternal();
    const Envelope* g1Env = geom1->getEnvelopeInternal();
    Envelope overlapEnv;
    g0Env->intersection(*g1Env, overlapEnv);
    return overlapEnv;
}

/* private */
std::unique_ptr<Geometry>
OverlapUnion::combine(std::unique_ptr<Geometry>& unionGeom, std::vector<std::unique_ptr<Geometry>>& disjointPolys)
{
    if (disjointPolys.size() <= 0)
        return std::move(unionGeom);

    disjointPolys.push_back(std::move(unionGeom));
    return GeometryCombiner::combine(disjointPolys);
}

/* private */
std::unique_ptr<Geometry>
OverlapUnion::extractByEnvelope(const Envelope& env, const Geometry* geom, std::vector<std::unique_ptr<Geometry>>& disjointGeoms)
{
    std::vector<const Geometry*> intersectingGeoms;
    for (std::size_t i = 0; i < geom->getNumGeometries(); i++) {
        const Geometry* elem = geom->getGeometryN(i);
        if (elem->getEnvelopeInternal()->intersects(env)) {
            intersectingGeoms.push_back(elem);
        }
        else {
            disjointGeoms.push_back(elem->clone());
        }
    }
    std::unique_ptr<Geometry> intersectingGeom(geomFactory->buildGeometry(intersectingGeoms));
    return std::move(intersectingGeom);
}

/* private */
std::unique_ptr<Geometry>
OverlapUnion::unionFull(const Geometry* geom0, const Geometry* geom1)
{
    try {
        return geom0->Union(geom1);
    }
    catch (geos::util::TopologyException ex) {
        /**
         * If the overlay union fails,
         * try a buffer union, which often succeeds
         */
        return unionBuffer(geom0, geom1);
    }
}

/* private */
std::unique_ptr<Geometry>
OverlapUnion::unionBuffer(const Geometry* geom0, const Geometry* geom1)
{
    std::unique_ptr<Geometry> copy0 = geom0->clone();
    std::unique_ptr<Geometry> copy1 = geom1->clone();
    std::vector<std::unique_ptr<Geometry>> geoms;
    geoms.push_back(std::move(copy0));
    geoms.push_back(std::move(copy1));
    const GeometryFactory* factory = copy0->getFactory();
    std::unique_ptr<GeometryCollection> gColl(factory->createGeometryCollection(std::move(geoms)));
    return gColl->buffer(0.0);
}

/* private */
bool
OverlapUnion::isBorderSegmentsSame(const Geometry* result, const Envelope& env)
{
    std::vector<LineSegment*> segsBefore = extractBorderSegments(g0, g1, env);
    std::vector<LineSegment*> segsAfter;
    extractBorderSegments(result, env, segsAfter);
    //std::cout << ("# seg before: " << segsBefore.size() << " - # seg after: " << segsAfter.size() << std::endl;
    bool eq = isEqual(segsBefore, segsAfter);

    // Clean up temporary segment arrays
    for (auto seg : segsBefore) delete seg;
    for (auto seg : segsAfter) delete seg;

    return eq;
}

static bool lineSegmentPtrCmp(const LineSegment* a, const LineSegment* b)
{
    return a->compareTo(*b) < 0;
}

/* private */
bool
OverlapUnion::isEqual(std::vector<LineSegment*>& segs0, std::vector<LineSegment*>& segs1)
{
    if (segs0.size() != segs1.size())
        return false;

    std::sort(segs0.begin(), segs0.end(), lineSegmentPtrCmp);
    std::sort(segs1.begin(), segs1.end(), lineSegmentPtrCmp);

    size_t sz = segs0.size();
    for (std::size_t i = 0; i < sz; i++) {
        if (segs0[i]->p0.x != segs1[i]->p0.x ||
            segs0[i]->p0.y != segs1[i]->p0.y ||
            segs0[i]->p1.x != segs1[i]->p1.x ||
            segs0[i]->p1.y != segs1[i]->p1.y)
        {
            return false;
        }
    }

    return true;
}

/* private */
std::vector<LineSegment*>
OverlapUnion::extractBorderSegments(const Geometry* geom0, const Geometry* geom1, const Envelope& env)
{
    std::vector<LineSegment*> segs;
    extractBorderSegments(geom0, env, segs);
    if (geom1 != nullptr)
        extractBorderSegments(geom1, env, segs);
    return segs;
}

/* static */
static bool
intersects(const Envelope& env, const Coordinate& p0, const Coordinate& p1)
{
    return env.intersects(p0) || env.intersects(p1);
}

/* static */
static bool
containsProperly(const Envelope& env, const Coordinate& p)
{
    if (env.isNull()) return false;
    return p.x > env.getMinX() &&
           p.x < env.getMaxX() &&
           p.y > env.getMinY() &&
           p.y < env.getMaxY();
}

/* static */
static bool
containsProperly(const Envelope& env, const Coordinate& p0, const Coordinate& p1)
{
    return containsProperly(env, p0) && containsProperly(env, p1);
}

/* privatef */
void
OverlapUnion::extractBorderSegments(const Geometry* geom, const Envelope& penv, std::vector<LineSegment*>& psegs)
{
    class BorderSegmentFilter : public CoordinateSequenceFilter {

    private:
        const Envelope env;
        std::vector<LineSegment*>* segs;

    public:

        BorderSegmentFilter(const Envelope& penv, std::vector<LineSegment*>* psegs)
            : env(penv),
              segs(psegs) {};

        bool
        isDone() const override { return false; }

        bool
        isGeometryChanged() const override  { return false; }

        void
        filter_ro(const CoordinateSequence& seq, std::size_t i) override
        {
            if (i <= 0) return;

            // extract LineSegment
            const Coordinate& p0 = seq.getAt(i-1);
            const Coordinate& p1 = seq.getAt(i  );
            bool isBorder = intersects(env, p0, p1) && ! containsProperly(env, p0, p1);
            if (isBorder) {
                segs->push_back(new LineSegment(p0, p1));
            }
        };

    };

    BorderSegmentFilter bsf(penv, &psegs);
    geom->apply_ro(bsf);

}

}
}
}
<|endoftext|>


<commit_before>
/*
The MIT License (MIT)

Copyright (c) 2016 Lancaster University, UK.

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 "MicroBit.h"
#include "MicroBitQuiz.h"

#ifdef MICROBIT_SAMPLE_VOTER_STUDENT

MicroBit uBit;

// Sets the permanent serial number for identification purposes

ManagedString serial = uBit.getSerial();

// Sets a flag to see if this micro:bit is connected to the master

bool connectedFlag = 0 ;
bool voted = true;

// Sets the current session number

ManagedString quizID;

// Sets the number of the current question of the session

int questionID;

// Number of questions available answers in the current session

int alternatives;

// Number of the letter displayed so that char letter = 32 + letterNumber

int letterNumber;

//

ManagedString answer;

//The image of a tick

MicroBitImage tickImage("0,0,0,0,0\n0,0,0,0,1\n0,0,0,1,0\n1,0,1,0,0\n0,1,0,0,0\n");

//The image of a cross

MicroBitImage crossImage("1,0,0,0,1\n0,1,0,1,0\n0,0,1,0,0\n0,1,0,1,0\n1,0,0,0,1\n");

MicroBitImage smileyImage("\
    000,255,000,255,000\n\
    000,000,000,000,000\n\
    000,000,000,000,000\n\
    255,000,000,000,255\n\
    000,255,255,255,000\n");

/*

	This method triggers when a datagram is received.

	The three expected messages are:

	A) "set:<quizID>:<questionID>:<alternatives>;"

	B) "ack:<quizID>:<questionID>:<serial>:<answer>;"

	C) "stp;"

*/

void onData(MicroBitEvent)
{
    ManagedString message = uBit.radio.datagram.recv();

	int counter = 0;

	if(message.substring(0,3) == "set"){
		ManagedString incomingQuizID = message.substring(4,4);
		ManagedString incomingQuestionID;
		ManagedString incomingAlternatives;

		while(message.charAt(9 + counter) != 58){ // 58 is the ASCII value of ":"
			incomingQuestionID = incomingQuestionID + message.charAt(9 + counter);
			counter++;
		}
		while(message.charAt(10 + counter) != 59){
			incomingAlternatives = incomingAlternatives + message.charAt(10 + counter);
			counter++;
		}

		if(!((incomingQuizID == quizID) && (incomingQuestionID == questionID))){
			quizID = incomingQuizID;
			questionID = atoi(incomingQuestionID.toCharArray());
			alternatives = atoi(incomingAlternatives.toCharArray());
			letterNumber = 0;
            voted = false;
			uBit.display.print(char(65 + letterNumber));
		}
	} else if (message == ("ack:" + answer) ){
		connectedFlag = 1;
	} else if (message == "stp;"){
		uBit.display.scrollAsync("FINISHED!");
	}
}

/*

	This method triggers when a button is clicked.

	A and B are used to navigate between the available answers, AB is used to
	send the answer currently appearing on the screen and then display the 'tick' image.

*/

void onButton(MicroBitEvent e)
{
    // if we've already voted in this round, then ignore user input until a new question is announced.
    if (voted)
        return;

    if (e.source == MICROBIT_ID_BUTTON_A){
		if(letterNumber == 0)
			letterNumber = alternatives-1;
		else
			letterNumber--;

		uBit.display.print(char(65+letterNumber));
	}

    if (e.source == MICROBIT_ID_BUTTON_B){
		if(letterNumber == alternatives-1)
			letterNumber = 0;
		else
			letterNumber++;

		uBit.display.print(char(65+letterNumber));
	}

	if (e.source == MICROBIT_ID_BUTTON_AB){
		answer = quizID + ":" + questionID + ":" + serial + ":" + letterNumber + ";";
		ManagedString message = "ans:" + answer;
		int counter = 1;

		while (!connectedFlag && counter <= 5)
		{
			uBit.radio.datagram.send(message);
		    uBit.display.printAsync("^");
			uBit.sleep(counter * 200);
		    uBit.display.clear();
			uBit.sleep(200);
			counter++;
		}
		if(connectedFlag){
			connectedFlag = 0;
            voted = true;
			uBit.display.print(tickImage);
			uBit.sleep(2000);
            uBit.display.print(smileyImage);
		} else {
			uBit.display.print(crossImage);
			uBit.sleep(2000);
			uBit.display.clear();
			uBit.display.print(char(65+letterNumber));
		}
	}
}

int main()
{
     // Initialise the micro:bit runtime.
    uBit.init();
	uBit.radio.enable();

	// Initialise the micro:bit listeners for radio datagrams and button events.
	uBit.messageBus.listen(MICROBIT_ID_RADIO, MICROBIT_RADIO_EVT_DATAGRAM, onData);
	uBit.messageBus.listen(MICROBIT_ID_BUTTON_A, MICROBIT_BUTTON_EVT_CLICK, onButton);
    uBit.messageBus.listen(MICROBIT_ID_BUTTON_B, MICROBIT_BUTTON_EVT_CLICK, onButton);
    uBit.messageBus.listen(MICROBIT_ID_BUTTON_AB, MICROBIT_BUTTON_EVT_CLICK, onButton);

	// Sets the group to an arbitrary number (59 in this case) to avoid interference
	uBit.radio.setGroup(64);

    // Use the highest output put level on the radio, to increase range and reliability.
    uBit.radio.setTransmitPower(7);

    uBit.display.print(smileyImage);

	// Get into powersaving sleep mode
	while(1)
		uBit.sleep(10000);

}

#endif
<commit_msg>set radio group to original fixed number; 59<commit_after>
/*
The MIT License (MIT)

Copyright (c) 2016 Lancaster University, UK.

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 "MicroBit.h"
#include "MicroBitQuiz.h"

#ifdef MICROBIT_SAMPLE_VOTER_STUDENT

MicroBit uBit;

// Sets the permanent serial number for identification purposes

ManagedString serial = uBit.getSerial();

// Sets a flag to see if this micro:bit is connected to the master

bool connectedFlag = 0 ;
bool voted = true;

// Sets the current session number

ManagedString quizID;

// Sets the number of the current question of the session

int questionID;

// Number of questions available answers in the current session

int alternatives;

// Number of the letter displayed so that char letter = 32 + letterNumber

int letterNumber;

//

ManagedString answer;

//The image of a tick

MicroBitImage tickImage("0,0,0,0,0\n0,0,0,0,1\n0,0,0,1,0\n1,0,1,0,0\n0,1,0,0,0\n");

//The image of a cross

MicroBitImage crossImage("1,0,0,0,1\n0,1,0,1,0\n0,0,1,0,0\n0,1,0,1,0\n1,0,0,0,1\n");

MicroBitImage smileyImage("\
    000,255,000,255,000\n\
    000,000,000,000,000\n\
    000,000,000,000,000\n\
    255,000,000,000,255\n\
    000,255,255,255,000\n");

/*

	This method triggers when a datagram is received.

	The three expected messages are:

	A) "set:<quizID>:<questionID>:<alternatives>;"

	B) "ack:<quizID>:<questionID>:<serial>:<answer>;"

	C) "stp;"

*/

void onData(MicroBitEvent)
{
    ManagedString message = uBit.radio.datagram.recv();

	int counter = 0;

	if(message.substring(0,3) == "set"){
		ManagedString incomingQuizID = message.substring(4,4);
		ManagedString incomingQuestionID;
		ManagedString incomingAlternatives;

		while(message.charAt(9 + counter) != 58){ // 58 is the ASCII value of ":"
			incomingQuestionID = incomingQuestionID + message.charAt(9 + counter);
			counter++;
		}
		while(message.charAt(10 + counter) != 59){
			incomingAlternatives = incomingAlternatives + message.charAt(10 + counter);
			counter++;
		}

		if(!((incomingQuizID == quizID) && (incomingQuestionID == questionID))){
			quizID = incomingQuizID;
			questionID = atoi(incomingQuestionID.toCharArray());
			alternatives = atoi(incomingAlternatives.toCharArray());
			letterNumber = 0;
            voted = false;
			uBit.display.print(char(65 + letterNumber));
		}
	} else if (message == ("ack:" + answer) ){
		connectedFlag = 1;
	} else if (message == "stp;"){
		uBit.display.scrollAsync("FINISHED!");
	}
}

/*

	This method triggers when a button is clicked.

	A and B are used to navigate between the available answers, AB is used to
	send the answer currently appearing on the screen and then display the 'tick' image.

*/

void onButton(MicroBitEvent e)
{
    // if we've already voted in this round, then ignore user input until a new question is announced.
    if (voted)
        return;

    if (e.source == MICROBIT_ID_BUTTON_A){
		if(letterNumber == 0)
			letterNumber = alternatives-1;
		else
			letterNumber--;

		uBit.display.print(char(65+letterNumber));
	}

    if (e.source == MICROBIT_ID_BUTTON_B){
		if(letterNumber == alternatives-1)
			letterNumber = 0;
		else
			letterNumber++;

		uBit.display.print(char(65+letterNumber));
	}

	if (e.source == MICROBIT_ID_BUTTON_AB){
		answer = quizID + ":" + questionID + ":" + serial + ":" + letterNumber + ";";
		ManagedString message = "ans:" + answer;
		int counter = 1;

		while (!connectedFlag && counter <= 5)
		{
			uBit.radio.datagram.send(message);
		    uBit.display.printAsync("^");
			uBit.sleep(counter * 200);
		    uBit.display.clear();
			uBit.sleep(200);
			counter++;
		}
		if(connectedFlag){
			connectedFlag = 0;
            voted = true;
			uBit.display.print(tickImage);
			uBit.sleep(2000);
            uBit.display.print(smileyImage);
		} else {
			uBit.display.print(crossImage);
			uBit.sleep(2000);
			uBit.display.clear();
			uBit.display.print(char(65+letterNumber));
		}
	}
}

int main()
{
     // Initialise the micro:bit runtime.
    uBit.init();
	uBit.radio.enable();

	// Initialise the micro:bit listeners for radio datagrams and button events.
	uBit.messageBus.listen(MICROBIT_ID_RADIO, MICROBIT_RADIO_EVT_DATAGRAM, onData);
	uBit.messageBus.listen(MICROBIT_ID_BUTTON_A, MICROBIT_BUTTON_EVT_CLICK, onButton);
    uBit.messageBus.listen(MICROBIT_ID_BUTTON_B, MICROBIT_BUTTON_EVT_CLICK, onButton);
    uBit.messageBus.listen(MICROBIT_ID_BUTTON_AB, MICROBIT_BUTTON_EVT_CLICK, onButton);

	// Sets the group to an arbitrary number (59 in this case) to avoid interference
	uBit.radio.setGroup(59);

    // Use the highest output put level on the radio, to increase range and reliability.
    uBit.radio.setTransmitPower(7);

    uBit.display.print(smileyImage);

	// Get into powersaving sleep mode
	while(1)
		uBit.sleep(10000);

}

#endif
<|endoftext|>


<commit_before>
//===----------------------------------------------------------------------===//
//
//                         PelotonDB
//
// abstract_optimizer.cpp
//
// Identification: /peloton/src/optimizer/abstract_optimizer.cpp
//
// Copyright (c) 2016, Carnegie Mellon University Database Group
//
//===----------------------------------------------------------------------===//

#pragma once

#include "optimizer/abstract_optimizer.h"

namespace peloton{
namespace optimizer{

	AbstractOptimizer::AbstractOptimizer() {}

	AbstractOptimizer::~AbstractOptimizer() {}

}
}

<commit_msg>Simple modification<commit_after>
//===----------------------------------------------------------------------===//
//
//                         PelotonDB
//
// abstract_optimizer.cpp
//
// Identification: /peloton/src/optimizer/abstract_optimizer.cpp
//
// Copyright (c) 2016, Carnegie Mellon University Database Group
//
//===----------------------------------------------------------------------===//

#include "optimizer/abstract_optimizer.h"

namespace peloton{
namespace optimizer{

	AbstractOptimizer::AbstractOptimizer() {}

	AbstractOptimizer::~AbstractOptimizer() {}

} // namespace optimizer
} // namespace peloton

<|endoftext|>


<commit_before>// -*- mode:c++;tab-width:2;indent-tabs-mode:t;show-trailing-whitespace:t;rm-trailing-spaces:t -*-
// vi: set ts=2 noet:
//
// Copyright (c) 2016 Sergey Lyskov <sergey.lyskov@jhu.edu>
//
// All rights reserved. Use of this source code is governed by a
// MIT license that can be found in the LICENSE file.

/// @file   binder/binder.cpp
/// @brief  Main
/// @author Sergey Lyskov

#include <binder.hpp>

// Declares clang::SyntaxOnlyAction.
#include "clang/Frontend/FrontendActions.h"
#include "clang/Tooling/CommonOptionsParser.h"
#include "clang/Tooling/Tooling.h"

#include <clang/AST/RecursiveASTVisitor.h>
#include <clang/Basic/SourceLocation.h>
#include <clang/Frontend/CompilerInstance.h>
#include <clang/AST/Comment.h>

// Declares llvm::cl::extrahelp.
#include "llvm/Support/CommandLine.h"

#include <context.hpp>
#include <enum.hpp>
#include <function.hpp>
#include <class.hpp>
#include <util.hpp>

using namespace clang::tooling;
using namespace llvm;

// Apply a custom category to all command-line options so that they are the
// only ones displayed.
static llvm::cl::OptionCategory BinderToolCategory("Binder options");

// CommonOptionsParser declares HelpMessage with a description of the common
// command-line options related to the compilation database and input files.
// It's nice to have this help message in all tools.
static cl::extrahelp CommonHelp(CommonOptionsParser::HelpMessage);

// A help message for this specific tool can be added afterwards.
static cl::extrahelp MoreHelp("\nMore help text...\n");

using binder::Config;

using namespace clang;

using std::string;

cl::opt<std::string> O_root_module("root-module", cl::desc("Name of root module"), /*cl::init("example"),*/ cl::cat(BinderToolCategory));

cl::opt<int> O_max_file_size("max-file-size", cl::desc("Specify maximum length of generated source files"), cl::init(1024*16), cl::cat(BinderToolCategory));

cl::opt<std::string> O_prefix("prefix", cl::desc("Output prefix for all generated files. Might contain directories."), cl::init(""), cl::cat(BinderToolCategory));

cl::list<std::string> O_bind("bind", cl::desc("Namespace to bind, could be specified more then once. Specify \"\" to bind all namespaces."), cl::cat(BinderToolCategory)); // , cl::OneOrMore
cl::list<std::string> O_skip("skip", cl::desc("Namespace to skip, could be specified more then once"), cl::cat(BinderToolCategory)); // , cl::OneOrMore

cl::opt<std::string> O_config("config", cl::desc("Specify config file from which bindings setting will be read"), cl::init(""), cl::cat(BinderToolCategory));

cl::opt<bool> O_annotate_includes("annotate-includes", cl::desc("Annotate each includes in generated code with type name that trigger it inclusion"), cl::init(false), cl::cat(BinderToolCategory));

cl::opt<bool> O_single_file("single-file", cl::desc("Concatenate all binder output into single file with name: root-module-name + '.cpp'. Use this for a small projects and for testing."), cl::init(false), cl::cat(BinderToolCategory));

cl::opt<bool> O_trace("trace", cl::desc("Add tracer output for each binded object (i.e. for debugging)"), cl::init(false), cl::cat(BinderToolCategory));

cl::opt<bool> O_verbose("v", cl::desc("Increase verbosity of output"), cl::init(false), cl::cat(BinderToolCategory));

class ClassVisitor : public RecursiveASTVisitor<ClassVisitor>
{
public:
    explicit ClassVisitor(DeclContext *dc) /*: decl_context(dc)*/ {}

	virtual ~ClassVisitor() {}

	virtual bool VisitEnumDecl(EnumDecl *record) {
		errs() << "ClassVisitor EnumDecl: " << record->getQualifiedNameAsString() << "\n";
		record->dump();
        return true;
	}

private:
    //DeclContext *decl_context;
};

string wrap_CXXRecordDecl(CXXRecordDecl *R)
{
	ClassVisitor v{R};
	v.TraverseDecl( R );
	//R->dump();
	return "";
}

class BinderVisitor : public RecursiveASTVisitor<BinderVisitor>
{
public:
    explicit BinderVisitor(CompilerInstance *ci) : ast_context( &( ci->getASTContext() ) )
	{
		Config & config = Config::get();

		config.root_module = O_root_module;
		config.prefix = O_prefix;
		config.maximum_file_length = O_max_file_size;

		config.namespaces_to_bind = O_bind;
		config.namespaces_to_skip = O_skip;

		if( O_config.size() ) config.read(O_config);
	}

	virtual ~BinderVisitor() {}

	bool shouldVisitTemplateInstantiations () const { return true; }

	virtual bool VisitFunctionDecl(FunctionDecl *F)
	{
		if( F->isCXXInstanceMember() or isa<CXXMethodDecl>(F) ) return true;

		if( binder::is_bindable(F) ) {
			binder::BinderOP b = std::make_shared<binder::FunctionBinder>(F);
			context.add(b);
		} else if( F->isOverloadedOperator()  and  F->getNameAsString() == "operator<<" ) {
			//outs() << "Adding insertion operator: " << binder::function_pointer_type(F) << "\n";
			context.add_insertion_operator(F);
		}

        return true;
    }

	virtual bool VisitCXXRecordDecl(CXXRecordDecl *C) {
		if( C->isCXXInstanceMember()  or  C->isCXXClassMember() ) return true;

		if( binder::is_bindable(C) ) {
			binder::BinderOP b = std::make_shared<binder::ClassBinder>(C);
			context.add(b);
		}

        return true;
    }

	// virtual bool VisitClassTemplateSpecializationDecl(ClassTemplateSpecializationDecl *C) {
	// 	if( FullSourceLoc(C->getLocation(), ast_context->getSourceManager() ).isInSystemHeader() ) return true;
	// 	errs() << "Visit ClassTemplateSpecializationDecl:" << C->getQualifiedNameAsString() << binder::template_specialization(C) << "\n";
	// 	C->dump();
    //     return true;
	// }

	// virtual bool VisitTemplateDecl(TemplateDecl *record) {
	// 	//if( FullSourceLoc(record->getLocation(), ast_context->getSourceManager() ).isInSystemHeader() ) return true;
	// 	errs() << "Visit TemplateDecl: " << record->getQualifiedNameAsString() << "\n";
	// 	//record->dump();
    //     return true;
	// }

	// virtual bool VisitClassTemplateDecl(ClassTemplateDecl *record) {
	// 	//if( FullSourceLoc(record->getLocation(), ast_context->getSourceManager() ).isInSystemHeader() ) return true;
	// 	errs() << "Visit ClassTemplateDecl: " << record->getQualifiedNameAsString() << binder::template_specialization( record->getTemplatedDecl() ) << "\n";
	// 	//record->dump();
    //     return true;
	// }

	// virtual bool VisitTypedefDecl(TypedefDecl *T) {
	// 	if( FullSourceLoc(T->getLocation(), ast_context->getSourceManager() ).isInSystemHeader() ) return true;
	// 	//errs() << "Visit TypedefDecl: " << T->getQualifiedNameAsString() << "  Type: " << T->getUnderlyingType()->getCanonicalTypeInternal()/*getCanonicalType()*/.getAsString() << "\n";
	// 	// record->dump();
    //     return true;
	// }

	// virtual bool VisitNamedDecl(NamedDecl *record) {
	// 	errs() << "Visit NamedRecord: " << record->getQualifiedNameAsString() << "\n";
    //     return true;
	// }

	// virtual bool VisitFieldDecl(FieldDecl *record) {
	// 	errs() << "Visit FieldDecl: " << record->getQualifiedNameAsString() << "\n";
	// 	record->dump();
    //     return true;
	// }

	virtual bool VisitEnumDecl(EnumDecl *E) {
		if( E->isCXXInstanceMember()  or  E->isCXXClassMember() ) return true;

		binder::BinderOP b = std::make_shared<binder::EnumBinder>( E/*->getCanonicalDecl()*/ );
		context.add(b);

        return true;
	}

	void generate(void) {
		context.generate( Config::get() );
	}

private:
    ASTContext *ast_context;

	binder::Context context;
};

class BinderASTConsumer : public ASTConsumer
{
private:
    std::unique_ptr<BinderVisitor> visitor;

public:
    // override the constructor in order to pass CI
    explicit BinderASTConsumer(CompilerInstance *ci) : visitor(new BinderVisitor(ci)) {}

    // override this to call our ExampleVisitor on the entire source file
    virtual void HandleTranslationUnit(ASTContext &context)
	{
        visitor->TraverseDecl( context.getTranslationUnitDecl() );
		visitor->generate();
    }
};

class BinderFrontendAction : public ASTFrontendAction {
public:
    virtual std::unique_ptr<clang::ASTConsumer> CreateASTConsumer(CompilerInstance &ci, StringRef file) {
        return std::unique_ptr<ASTConsumer>( new BinderASTConsumer(&ci) );
    }
};

int main(int argc, const char **argv)
{
	CommonOptionsParser op(argc, argv, BinderToolCategory);

	ClangTool tool(op.getCompilations(), op.getSourcePathList());

	//outs() << "Root module: " << O_root_module << "\n";
	//for(auto &s : O_bind) outs() << "Binding: '" << s << "'\n";

	return tool.run(newFrontendActionFactory<BinderFrontendAction>().get());
}
<commit_msg>a way to suppress errors if the not-found included headers are not useful in generating bindings and you are sure that the bindings are still correct and you want to suppress ugly fatal errors then you can use --suppress-errors=true as argument to get rid of them.<commit_after>// -*- mode:c++;tab-width:2;indent-tabs-mode:t;show-trailing-whitespace:t;rm-trailing-spaces:t -*-
// vi: set ts=2 noet:
//
// Copyright (c) 2016 Sergey Lyskov <sergey.lyskov@jhu.edu>
//
// All rights reserved. Use of this source code is governed by a
// MIT license that can be found in the LICENSE file.

/// @file   binder/binder.cpp
/// @brief  Main
/// @author Sergey Lyskov

#include <binder.hpp>

// Declares clang::SyntaxOnlyAction.
#include "clang/Frontend/FrontendActions.h"
#include "clang/Tooling/CommonOptionsParser.h"
#include "clang/Tooling/Tooling.h"

#include <clang/AST/RecursiveASTVisitor.h>
#include <clang/Basic/SourceLocation.h>
#include <clang/Frontend/CompilerInstance.h>
#include <clang/AST/Comment.h>

// Declares llvm::cl::extrahelp.
#include "llvm/Support/CommandLine.h"

#include <context.hpp>
#include <enum.hpp>
#include <function.hpp>
#include <class.hpp>
#include <util.hpp>

#include <clang/Basic/Diagnostic.h>

using namespace clang::tooling;
using namespace llvm;

// Apply a custom category to all command-line options so that they are the
// only ones displayed.
static llvm::cl::OptionCategory BinderToolCategory("Binder options");

// CommonOptionsParser declares HelpMessage with a description of the common
// command-line options related to the compilation database and input files.
// It's nice to have this help message in all tools.
static cl::extrahelp CommonHelp(CommonOptionsParser::HelpMessage);

// A help message for this specific tool can be added afterwards.
static cl::extrahelp MoreHelp("\nMore help text...\n");

using binder::Config;

using namespace clang;

using std::string;

cl::opt<std::string> O_root_module("root-module", cl::desc("Name of root module"), /*cl::init("example"),*/ cl::cat(BinderToolCategory));

cl::opt<int> O_max_file_size("max-file-size", cl::desc("Specify maximum length of generated source files"), cl::init(1024*16), cl::cat(BinderToolCategory));

cl::opt<std::string> O_prefix("prefix", cl::desc("Output prefix for all generated files. Might contain directories."), cl::init(""), cl::cat(BinderToolCategory));

cl::list<std::string> O_bind("bind", cl::desc("Namespace to bind, could be specified more then once. Specify \"\" to bind all namespaces."), cl::cat(BinderToolCategory)); // , cl::OneOrMore
cl::list<std::string> O_skip("skip", cl::desc("Namespace to skip, could be specified more then once"), cl::cat(BinderToolCategory)); // , cl::OneOrMore

cl::opt<std::string> O_config("config", cl::desc("Specify config file from which bindings setting will be read"), cl::init(""), cl::cat(BinderToolCategory));

cl::opt<bool> O_annotate_includes("annotate-includes", cl::desc("Annotate each includes in generated code with type name that trigger it inclusion"), cl::init(false), cl::cat(BinderToolCategory));

cl::opt<bool> O_single_file("single-file", cl::desc("Concatenate all binder output into single file with name: root-module-name + '.cpp'. Use this for a small projects and for testing."), cl::init(false), cl::cat(BinderToolCategory));

cl::opt<bool> O_trace("trace", cl::desc("Add tracer output for each binded object (i.e. for debugging)"), cl::init(false), cl::cat(BinderToolCategory));

cl::opt<bool> O_verbose("v", cl::desc("Increase verbosity of output"), cl::init(false), cl::cat(BinderToolCategory));

cl::opt<bool> O_suppress_errors("suppress-errors", cl::desc("Suppres all the compilers errors when you are sure about your code and the errors are in private parts of your class."), cl::init(false), cl::cat(BinderToolCategory));

class ClassVisitor : public RecursiveASTVisitor<ClassVisitor>
{
public:
    explicit ClassVisitor(DeclContext *dc) /*: decl_context(dc)*/ {}

	virtual ~ClassVisitor() {}

	virtual bool VisitEnumDecl(EnumDecl *record) {
		errs() << "ClassVisitor EnumDecl: " << record->getQualifiedNameAsString() << "\n";
		record->dump();
        return true;
	}

private:
    //DeclContext *decl_context;
};

string wrap_CXXRecordDecl(CXXRecordDecl *R)
{
	ClassVisitor v{R};
	v.TraverseDecl( R );
	//R->dump();
	return "";
}

class BinderVisitor : public RecursiveASTVisitor<BinderVisitor>
{
public:
    explicit BinderVisitor(CompilerInstance *ci) : ast_context( &( ci->getASTContext() ) )
	{
		Config & config = Config::get();

		config.root_module = O_root_module;
		config.prefix = O_prefix;
		config.maximum_file_length = O_max_file_size;

		config.namespaces_to_bind = O_bind;
		config.namespaces_to_skip = O_skip;

		if( O_config.size() ) config.read(O_config);
		if(O_suppress_errors)
		{
			clang::DiagnosticsEngine& di = ci->getDiagnostics();
			di.setSuppressAllDiagnostics();
		}
	}

	virtual ~BinderVisitor() {}

	bool shouldVisitTemplateInstantiations () const { return true; }

	virtual bool VisitFunctionDecl(FunctionDecl *F)
	{
		if( F->isCXXInstanceMember() or isa<CXXMethodDecl>(F) ) return true;

		if( binder::is_bindable(F) ) {
			binder::BinderOP b = std::make_shared<binder::FunctionBinder>(F);
			context.add(b);
		} else if( F->isOverloadedOperator()  and  F->getNameAsString() == "operator<<" ) {
			//outs() << "Adding insertion operator: " << binder::function_pointer_type(F) << "\n";
			context.add_insertion_operator(F);
		}

        return true;
    }

	virtual bool VisitCXXRecordDecl(CXXRecordDecl *C) {
		if( C->isCXXInstanceMember()  or  C->isCXXClassMember() ) return true;

		if( binder::is_bindable(C) ) {
			binder::BinderOP b = std::make_shared<binder::ClassBinder>(C);
			context.add(b);
		}

        return true;
    }

	// virtual bool VisitClassTemplateSpecializationDecl(ClassTemplateSpecializationDecl *C) {
	// 	if( FullSourceLoc(C->getLocation(), ast_context->getSourceManager() ).isInSystemHeader() ) return true;
	// 	errs() << "Visit ClassTemplateSpecializationDecl:" << C->getQualifiedNameAsString() << binder::template_specialization(C) << "\n";
	// 	C->dump();
    //     return true;
	// }

	// virtual bool VisitTemplateDecl(TemplateDecl *record) {
	// 	//if( FullSourceLoc(record->getLocation(), ast_context->getSourceManager() ).isInSystemHeader() ) return true;
	// 	errs() << "Visit TemplateDecl: " << record->getQualifiedNameAsString() << "\n";
	// 	//record->dump();
    //     return true;
	// }

	// virtual bool VisitClassTemplateDecl(ClassTemplateDecl *record) {
	// 	//if( FullSourceLoc(record->getLocation(), ast_context->getSourceManager() ).isInSystemHeader() ) return true;
	// 	errs() << "Visit ClassTemplateDecl: " << record->getQualifiedNameAsString() << binder::template_specialization( record->getTemplatedDecl() ) << "\n";
	// 	//record->dump();
    //     return true;
	// }

	// virtual bool VisitTypedefDecl(TypedefDecl *T) {
	// 	if( FullSourceLoc(T->getLocation(), ast_context->getSourceManager() ).isInSystemHeader() ) return true;
	// 	//errs() << "Visit TypedefDecl: " << T->getQualifiedNameAsString() << "  Type: " << T->getUnderlyingType()->getCanonicalTypeInternal()/*getCanonicalType()*/.getAsString() << "\n";
	// 	// record->dump();
    //     return true;
	// }

	// virtual bool VisitNamedDecl(NamedDecl *record) {
	// 	errs() << "Visit NamedRecord: " << record->getQualifiedNameAsString() << "\n";
    //     return true;
	// }

	// virtual bool VisitFieldDecl(FieldDecl *record) {
	// 	errs() << "Visit FieldDecl: " << record->getQualifiedNameAsString() << "\n";
	// 	record->dump();
    //     return true;
	// }

	virtual bool VisitEnumDecl(EnumDecl *E) {
		if( E->isCXXInstanceMember()  or  E->isCXXClassMember() ) return true;

		binder::BinderOP b = std::make_shared<binder::EnumBinder>( E/*->getCanonicalDecl()*/ );
		context.add(b);

        return true;
	}

	void generate(void) {
		context.generate( Config::get() );
	}

private:
    ASTContext *ast_context;

	binder::Context context;
};

class BinderASTConsumer : public ASTConsumer
{
private:
    std::unique_ptr<BinderVisitor> visitor;

public:
    // override the constructor in order to pass CI
    explicit BinderASTConsumer(CompilerInstance *ci) : visitor(new BinderVisitor(ci)) {}

    // override this to call our ExampleVisitor on the entire source file
    virtual void HandleTranslationUnit(ASTContext &context)
	{
        visitor->TraverseDecl( context.getTranslationUnitDecl() );
		visitor->generate();
    }
};

class BinderFrontendAction : public ASTFrontendAction {
public:
    virtual std::unique_ptr<clang::ASTConsumer> CreateASTConsumer(CompilerInstance &ci, StringRef file) {
        return std::unique_ptr<ASTConsumer>( new BinderASTConsumer(&ci) );
    }
};

int main(int argc, const char **argv)
{
	CommonOptionsParser op(argc, argv, BinderToolCategory);

	ClangTool tool(op.getCompilations(), op.getSourcePathList());
	//outs() << "Root module: " << O_root_module << "\n";
	//for(auto &s : O_bind) outs() << "Binding: '" << s << "'\n";

	return tool.run(newFrontendActionFactory<BinderFrontendAction>().get());
}
<|endoftext|>