<commit_before>/*
 * DigitalWatch.cpp
 *
 *  Created on: 09.08.2017
 *      Author: alexander
 */

#include "DigitalWatch.h"
#include <iostream>
#include <time.h>
#include <string>
#include <unistd.h>

using namespace std;

DigitalWatch::DigitalWatch() {
	this->screen_p = 0;
	this->hour1 = 0;
	this->hour2 = 0;
	this->min1 = 0;
	this->min2 = 0;
}

void DigitalWatch::init() {
	seg_hour1.init(1, 4, 5, 7);
	seg_hour2.init(7, 4, 5, 7);
	seg_min1.init(16, 4, 5, 7);
	seg_min2.init(22, 4, 5, 7);
	seg_lowerLine.init(0, 1, COL_MAX, 1);
	seg_upperLine.init(0, 1, COL_MAX, 1);
	seg_doubleDots.init(12, 5, 2, 5);
	seg_complete.init(0, 0, COL_MAX, ROW_MAX);
}

void DigitalWatch::initDisplay() {
	seg_complete.changeAll(screen_p, false);
	// Obere Linie init.
	seg_upperLine.changeAll(screen_p, true);
	// Untere Linie init;
	seg_lowerLine.changeAll(screen_p, true);
	// Doppelpunkte init.
	seg_doubleDots.change(screen_p, 5, 12, true);
	seg_doubleDots.change(screen_p, 5, 13, true);
	seg_doubleDots.change(screen_p, 6, 12, true);
	seg_doubleDots.change(screen_p, 6, 13, true);
	seg_doubleDots.change(screen_p, 8, 12, true);
	seg_doubleDots.change(screen_p, 8, 13, true);
	seg_doubleDots.change(screen_p, 9, 12, true);
	seg_doubleDots.change(screen_p, 9, 13, true);
	// Ziffern komplett gelb zeigen
	seg_hour1.changeAll(screen_p, true);
	seg_hour2.changeAll(screen_p, true);
	seg_min1.changeAll(screen_p, true);
	seg_min2.changeAll(screen_p, true);
	screen_p->showScreen();
}

void DigitalWatch::runClock(Screen* screen_p) {
	this->screen_p = screen_p;
	init();
	initDisplay();
	time_t rawtime;
	struct tm* time_local;		// allg. Zeitstruct
	/*
	 * Zeit auslesen funktioniert!
	 * einzelne Segmente werden am falschen Ort falsch angezeigt
	 * -> liegt wahrscheinlich am noch nicht modifizierten Array
	 */
	while (1) {
		sleep(1);
		// Zeit holen und konvertieren
		time(&rawtime);
		time_local = localtime(&rawtime);
		// einzelne Ziffern extrahieren
		int hour1 = (time_local->tm_hour) / 10;
		int hour2 = (time_local->tm_hour) % 10;
		int min1 = (time_local->tm_min) / 10;
		int min2 = (time_local->tm_min) % 10;
		cout << "---Test---  Zeit: " << hour1 << hour2 << " : " << min1 << min2
				<< endl;
		/*
		 * Darstellen der Ziffern
		 */
		seg_hour1.choseNumber(screen_p, hour1);
		seg_hour2.choseNumber(screen_p, hour2);
		seg_min1.choseNumber(screen_p, min1);
		seg_min2.choseNumber(screen_p, min2);
		screen_p->showScreen();
	}
}
<commit_msg>erste Ansätze für die Implementierung der Digitaluhr: Array muss noch dynamisch modifizierbar gemacht werden! ChangeAll() gibt auch einen Fehler! // Jedoch sollte die Ziffernanzeige soweit laufen und auch die Einbindung der Zeit. Ich habe noch eine Vererbungsstrucktur eingebaut um Segment.cpp ein bisschen zu strukturieren<commit_after>/*
 * DigitalWatch.cpp
 *
 *  Created on: 09.08.2017
 *      Author: alexander
 */

#include "DigitalWatch.h"
#include <iostream>
#include <time.h>
#include <string>
#include <unistd.h>

using namespace std;

DigitalWatch::DigitalWatch() {
	this->screen_p = 0;
	this->hour1 = 0;
	this->hour2 = 0;
	this->min1 = 0;
	this->min2 = 0;
}

void DigitalWatch::init() {
	seg_hour1.init(1, 4, 5, 7);
	seg_hour2.init(7, 4, 5, 7);
	seg_min1.init(16, 4, 5, 7);
	seg_min2.init(22, 4, 5, 7);
	seg_lowerLine.init(0, 1, COL_MAX, 1);
	seg_upperLine.init(0, 1, COL_MAX, 1);
	seg_doubleDots.init(12, 5, 2, 5);
	seg_complete.init(0, 0, COL_MAX, ROW_MAX);
}

void DigitalWatch::initDisplay() {
	seg_complete.changeAll(screen_p, false);
	// Obere Linie init.
	seg_upperLine.changeAll(screen_p, true);
	// Untere Linie init;
	seg_lowerLine.changeAll(screen_p, true);
	// Doppelpunkte init.
	seg_doubleDots.change(screen_p, 5, 12, true);
	seg_doubleDots.change(screen_p, 5, 13, true);
	seg_doubleDots.change(screen_p, 6, 12, true);
	seg_doubleDots.change(screen_p, 6, 13, true);
	seg_doubleDots.change(screen_p, 8, 12, true);
	seg_doubleDots.change(screen_p, 8, 13, true);
	seg_doubleDots.change(screen_p, 9, 12, true);
	seg_doubleDots.change(screen_p, 9, 13, true);
	// Ziffern komplett gelb zeigen
	seg_hour1.changeAll(screen_p, true);
	seg_hour2.changeAll(screen_p, true);
	seg_min1.changeAll(screen_p, true);
	seg_min2.changeAll(screen_p, true);
	screen_p->showScreen();
}

void DigitalWatch::runClock(Screen* screen_p) {
	this->screen_p = screen_p;
	init();
	initDisplay();
	time_t rawtime;
	struct tm* time_local;		// allg. Zeitstruct
	/*
	 * Zeit auslesen funktioniert!
	 * einzelne Segmente werden am falschen Ort falsch angezeigt
	 * -> liegt wahrscheinlich am noch nicht modifizierten Array
	 */
	while (1) {
		sleep(1);
		// Zeit holen und konvertieren
		time(&rawtime);
		time_local = localtime(&rawtime);
		// einzelne Ziffern extrahieren
		int hour1 = (time_local->tm_hour) / 10;
		int hour2 = (time_local->tm_hour) % 10;
		int min1 = (time_local->tm_min) / 10;
		int min2 = (time_local->tm_min) % 10;
		cout << "---Test---  Zeit: " << hour1 << hour2 << " : " << min1 << min2
				<< endl;
		// Darstellen der Ziffern
		seg_hour1.choseNumber(screen_p, hour1);
		seg_hour2.choseNumber(screen_p, hour2);
		seg_min1.choseNumber(screen_p, min1);
		seg_min2.choseNumber(screen_p, min2);
		// Anzeigen auf Screen
		screen_p->showScreen();
	}
}
<|endoftext|>


<commit_before>/****************************************************************************
** libebml : parse EBML files, see http://embl.sourceforge.net/
**
** <file/class description>
**
** Copyright (C) 2002-2010 Steve Lhomme.  All rights reserved.
**
** This library is free software; you can redistribute it and/or
** modify it under the terms of the GNU Lesser General Public
** License as published by the Free Software Foundation; either
** version 2.1 of the License, or (at your option) any later version.
**
** This library is distributed in the hope that it will be useful,
** but WITHOUT ANY WARRANTY; without even the implied warranty of
** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
** Lesser General Public License for more details.
**
** You should have received a copy of the GNU Lesser General Public
** License along with this library; if not, write to the Free Software
** Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
**
** See http://www.gnu.org/licenses/lgpl-2.1.html for LGPL licensing information.
**
** Contact license@matroska.org if any conditions of this licensing are
** not clear to you.
**
**********************************************************************/

/*!
  \file
  \version \$Id$
  \author Steve Lhomme     <robux4 @ users.sf.net>
  \author Moritz Bunkus <moritz @ bunkus.org>
*/
#include <cassert>
#include <limits>

#include "ebml/EbmlSInteger.h"

// Converting unsigned int types to signed ints assuming the
// underlying bits in memory should represent the 2's complement of a
// signed integer. See https://stackoverflow.com/a/13208789/507077

namespace {

int64_t
ToSigned(uint64_t u) {
  if (u <= std::numeric_limits<int64_t>::max())
    return static_cast<int64_t>(u);

  return static_cast<int64_t>(u - std::numeric_limits<int64_t>::min()) + std::numeric_limits<int64_t>::min();
}

}

START_LIBEBML_NAMESPACE

EbmlSInteger::EbmlSInteger()
  :EbmlElement(DEFAULT_INT_SIZE, false)
{}

EbmlSInteger::EbmlSInteger(int64 aDefaultValue)
  :EbmlElement(DEFAULT_INT_SIZE, true), Value(aDefaultValue)
{
  SetDefaultIsSet();
}

EbmlSInteger::EbmlSInteger(const EbmlSInteger & ElementToClone)
  :EbmlElement(ElementToClone)
  ,Value(ElementToClone.Value)
  ,DefaultValue(ElementToClone.DefaultValue)
{
}

EbmlSInteger::operator int8() const {return  int8(Value);}
EbmlSInteger::operator int16() const {return int16(Value);}
EbmlSInteger::operator int32() const {return int32(Value);}
EbmlSInteger::operator int64() const {return Value;}

int64 EbmlSInteger::GetValue() const {return Value;}

EbmlSInteger & EbmlSInteger::SetValue(int64 NewValue) {
  return *this = NewValue;
}

/*!
  \todo handle exception on errors
*/
filepos_t EbmlSInteger::RenderData(IOCallback & output, bool /* bForceRender */, bool /* bWithDefault */)
{
  binary FinalData[8]; // we don't handle more than 64 bits integers
  unsigned int i;

  if (GetSizeLength() > 8)
    return 0; // integer bigger coded on more than 64 bits are not supported

  int64 TempValue = Value;
  for (i=0; i<GetSize();i++) {
    FinalData[GetSize()-i-1] = binary(TempValue & 0xFF);
    TempValue >>= 8;
  }

  output.writeFully(FinalData,GetSize());

  return GetSize();
}

uint64 EbmlSInteger::UpdateSize(bool bWithDefault, bool /* bForceRender */)
{
  if (!bWithDefault && IsDefaultValue())
    return 0;

  if (Value <= 0x7F && Value >= (-0x80)) {
    SetSize_(1);
  } else if (Value <= 0x7FFF && Value >= (-0x8000)) {
    SetSize_(2);
  } else if (Value <= 0x7FFFFF && Value >= (-0x800000)) {
    SetSize_(3);
  } else if (Value <= EBML_PRETTYLONGINT(0x7FFFFFFF) && Value >= (EBML_PRETTYLONGINT(-0x80000000))) {
    SetSize_(4);
  } else if (Value <= EBML_PRETTYLONGINT(0x7FFFFFFFFF) &&
             Value >= EBML_PRETTYLONGINT(-0x8000000000)) {
    SetSize_(5);
  } else if (Value <= EBML_PRETTYLONGINT(0x7FFFFFFFFFFF) &&
             Value >= EBML_PRETTYLONGINT(-0x800000000000)) {
    SetSize_(6);
  } else if (Value <= EBML_PRETTYLONGINT(0x7FFFFFFFFFFFFF) &&
             Value >= EBML_PRETTYLONGINT(-0x80000000000000)) {
    SetSize_(7);
  } else {
    SetSize_(8);
  }

  if (GetDefaultSize() > GetSize()) {
    SetSize_(GetDefaultSize());
  }

  return GetSize();
}

filepos_t EbmlSInteger::ReadData(IOCallback & input, ScopeMode ReadFully)
{
  if (ReadFully != SCOPE_NO_DATA) {
    binary Buffer[8];
    input.readFully(Buffer, GetSize());

    uint64_t TempValue = Buffer[0] & 0x80 ? std::numeric_limits<uint64_t>::max() : 0;

    for (unsigned int i=0; i<GetSize(); i++) {
      TempValue <<= 8;
      TempValue |= Buffer[i];
    }

    Value = ToSigned(TempValue);

    SetValueIsSet();
  }

  return GetSize();
}

bool EbmlSInteger::IsSmallerThan(const EbmlElement *Cmp) const
{
  if (EbmlId(*this) == EbmlId(*Cmp))
    return this->Value < static_cast<const EbmlSInteger *>(Cmp)->Value;
  else
    return false;
}

END_LIBEBML_NAMESPACE
<commit_msg>EbmlSInteger: use our internal integer types rather than the standard ones<commit_after>/****************************************************************************
** libebml : parse EBML files, see http://embl.sourceforge.net/
**
** <file/class description>
**
** Copyright (C) 2002-2010 Steve Lhomme.  All rights reserved.
**
** This library is free software; you can redistribute it and/or
** modify it under the terms of the GNU Lesser General Public
** License as published by the Free Software Foundation; either
** version 2.1 of the License, or (at your option) any later version.
**
** This library is distributed in the hope that it will be useful,
** but WITHOUT ANY WARRANTY; without even the implied warranty of
** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
** Lesser General Public License for more details.
**
** You should have received a copy of the GNU Lesser General Public
** License along with this library; if not, write to the Free Software
** Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
**
** See http://www.gnu.org/licenses/lgpl-2.1.html for LGPL licensing information.
**
** Contact license@matroska.org if any conditions of this licensing are
** not clear to you.
**
**********************************************************************/

/*!
  \file
  \version \$Id$
  \author Steve Lhomme     <robux4 @ users.sf.net>
  \author Moritz Bunkus <moritz @ bunkus.org>
*/
#include <cassert>
#include <limits>

#include "ebml/EbmlSInteger.h"

// Converting unsigned int types to signed ints assuming the
// underlying bits in memory should represent the 2's complement of a
// signed integer. See https://stackoverflow.com/a/13208789/507077

namespace {

int64
ToSigned(uint64 u) {
  if (u <= std::numeric_limits<int64>::max())
    return static_cast<int64>(u);

  return static_cast<int64>(u - std::numeric_limits<int64>::min()) + std::numeric_limits<int64>::min();
}

}

START_LIBEBML_NAMESPACE

EbmlSInteger::EbmlSInteger()
  :EbmlElement(DEFAULT_INT_SIZE, false)
{}

EbmlSInteger::EbmlSInteger(int64 aDefaultValue)
  :EbmlElement(DEFAULT_INT_SIZE, true), Value(aDefaultValue)
{
  SetDefaultIsSet();
}

EbmlSInteger::EbmlSInteger(const EbmlSInteger & ElementToClone)
  :EbmlElement(ElementToClone)
  ,Value(ElementToClone.Value)
  ,DefaultValue(ElementToClone.DefaultValue)
{
}

EbmlSInteger::operator int8() const {return  int8(Value);}
EbmlSInteger::operator int16() const {return int16(Value);}
EbmlSInteger::operator int32() const {return int32(Value);}
EbmlSInteger::operator int64() const {return Value;}

int64 EbmlSInteger::GetValue() const {return Value;}

EbmlSInteger & EbmlSInteger::SetValue(int64 NewValue) {
  return *this = NewValue;
}

/*!
  \todo handle exception on errors
*/
filepos_t EbmlSInteger::RenderData(IOCallback & output, bool /* bForceRender */, bool /* bWithDefault */)
{
  binary FinalData[8]; // we don't handle more than 64 bits integers
  unsigned int i;

  if (GetSizeLength() > 8)
    return 0; // integer bigger coded on more than 64 bits are not supported

  int64 TempValue = Value;
  for (i=0; i<GetSize();i++) {
    FinalData[GetSize()-i-1] = binary(TempValue & 0xFF);
    TempValue >>= 8;
  }

  output.writeFully(FinalData,GetSize());

  return GetSize();
}

uint64 EbmlSInteger::UpdateSize(bool bWithDefault, bool /* bForceRender */)
{
  if (!bWithDefault && IsDefaultValue())
    return 0;

  if (Value <= 0x7F && Value >= (-0x80)) {
    SetSize_(1);
  } else if (Value <= 0x7FFF && Value >= (-0x8000)) {
    SetSize_(2);
  } else if (Value <= 0x7FFFFF && Value >= (-0x800000)) {
    SetSize_(3);
  } else if (Value <= EBML_PRETTYLONGINT(0x7FFFFFFF) && Value >= (EBML_PRETTYLONGINT(-0x80000000))) {
    SetSize_(4);
  } else if (Value <= EBML_PRETTYLONGINT(0x7FFFFFFFFF) &&
             Value >= EBML_PRETTYLONGINT(-0x8000000000)) {
    SetSize_(5);
  } else if (Value <= EBML_PRETTYLONGINT(0x7FFFFFFFFFFF) &&
             Value >= EBML_PRETTYLONGINT(-0x800000000000)) {
    SetSize_(6);
  } else if (Value <= EBML_PRETTYLONGINT(0x7FFFFFFFFFFFFF) &&
             Value >= EBML_PRETTYLONGINT(-0x80000000000000)) {
    SetSize_(7);
  } else {
    SetSize_(8);
  }

  if (GetDefaultSize() > GetSize()) {
    SetSize_(GetDefaultSize());
  }

  return GetSize();
}

filepos_t EbmlSInteger::ReadData(IOCallback & input, ScopeMode ReadFully)
{
  if (ReadFully != SCOPE_NO_DATA) {
    binary Buffer[8];
    input.readFully(Buffer, GetSize());

    uint64 TempValue = Buffer[0] & 0x80 ? std::numeric_limits<uint64>::max() : 0;

    for (unsigned int i=0; i<GetSize(); i++) {
      TempValue <<= 8;
      TempValue |= Buffer[i];
    }

    Value = ToSigned(TempValue);

    SetValueIsSet();
  }

  return GetSize();
}

bool EbmlSInteger::IsSmallerThan(const EbmlElement *Cmp) const
{
  if (EbmlId(*this) == EbmlId(*Cmp))
    return this->Value < static_cast<const EbmlSInteger *>(Cmp)->Value;
  else
    return false;
}

END_LIBEBML_NAMESPACE
<|endoftext|>


<commit_before>#include "load_project_window.h"
#include "src/halley_editor.h"
#include "src/preferences.h"
using namespace Halley;

LoadProjectWindow::LoadProjectWindow(UIFactory& factory, HalleyEditor& editor, std::function<void(String)> callback)
	: UIWidget("load_project", {}, UISizer(UISizerType::Vertical))
	, editor(editor)
{
	UIWidget::add(factory.makeUI("ui/halley/load_project"), 1, {}, UISizerAlignFlags::CentreHorizontal | UISizerFillFlags::FillVertical);

	{
		auto logo = getWidgetAs<UIImage>("logo");
		auto col = factory.getColourScheme()->getColour("logo");

		auto halleyLogo = Sprite()
			.setImage(factory.getResources(), "halley/halley_logo_dist.png", "Halley/DistanceFieldSprite")
			.setColour(col)
			.setScale(Vector2f(2, 2))
			.setPos(Vector2f(640, 360));
		halleyLogo.getMutableMaterial()
			.set("u_smoothness", 20.0f)
			.set("u_outline", 0.0f)
			.set("u_outlineColour", col);

		logo->setSprite(halleyLogo);
	}

	setHandle(UIEventType::ListSelectionChanged, [=] (const UIEvent& event)
	{
		event.getCurWidget().getWidgetAs<UITextInput>("input")->setText(event.getStringData());
	});

	setHandle(UIEventType::ListAccept, [=] (const UIEvent& event)
	{
		auto result = event.getCurWidget().getWidgetAs<UITextInput>("input")->getText();
		callback(result);
	});

	setHandle(UIEventType::ButtonClicked, "ok", [=] (const UIEvent& event)
	{
		auto result = event.getCurWidget().getWidgetAs<UITextInput>("input")->getText();
		callback(result);
	});

	auto recent = getWidgetAs<UIList>("recent");
	recent->setSingleClickAccept(false);
	for (auto& r: editor.getPreferences().getRecents()) {
		auto p = Path(r).getNativeString();
		recent->addTextItem(p, LocalisedString::fromUserString(p));
	}
	recent->addTextItem("", LocalisedString::fromHardcodedString("New location..."));

	setAnchor(UIAnchor());
	setModal(false);
}

void LoadProjectWindow::onAddedToRoot(UIRoot& root)
{
	root.setFocus(getWidget("recent"));
}

void LoadProjectWindow::update(Time t, bool moved)
{
	const auto size = editor.getAPI().video->getWindow().getDefinition().getSize();
	setMinSize(Vector2f(size));
}
<commit_msg>Fix load project glitchiness<commit_after>#include "load_project_window.h"
#include "src/halley_editor.h"
#include "src/preferences.h"
using namespace Halley;

LoadProjectWindow::LoadProjectWindow(UIFactory& factory, HalleyEditor& editor, std::function<void(String)> callback)
	: UIWidget("load_project", {}, UISizer(UISizerType::Vertical))
	, editor(editor)
{
	UIWidget::add(factory.makeUI("ui/halley/load_project"), 1, {}, UISizerAlignFlags::CentreHorizontal | UISizerFillFlags::FillVertical);

	{
		auto logo = getWidgetAs<UIImage>("logo");
		auto col = factory.getColourScheme()->getColour("logo");

		auto halleyLogo = Sprite()
			.setImage(factory.getResources(), "halley/halley_logo_dist.png", "Halley/DistanceFieldSprite")
			.setColour(col)
			.setScale(Vector2f(2, 2))
			.setPos(Vector2f(640, 360));
		halleyLogo.getMutableMaterial()
			.set("u_smoothness", 20.0f)
			.set("u_outline", 0.0f)
			.set("u_outlineColour", col);

		logo->setSprite(halleyLogo);
	}

	setHandle(UIEventType::ListSelectionChanged, [=] (const UIEvent& event)
	{
		event.getCurWidget().getWidgetAs<UITextInput>("input")->setText(event.getStringData());
	});

	setHandle(UIEventType::ListAccept, [=] (const UIEvent& event)
	{
		auto result = event.getCurWidget().getWidgetAs<UITextInput>("input")->getText();
		callback(result);
	});

	setHandle(UIEventType::ButtonClicked, "ok", [=] (const UIEvent& event)
	{
		auto result = event.getCurWidget().getWidgetAs<UITextInput>("input")->getText();
		callback(result);
	});

	auto recent = getWidgetAs<UIList>("recent");
	recent->setSingleClickAccept(false);
	for (auto& r: editor.getPreferences().getRecents()) {
		auto p = Path(r).getNativeString();
		recent->addTextItem(p, LocalisedString::fromUserString(p));
	}
	recent->addTextItem("", LocalisedString::fromHardcodedString("New location..."));

	setAnchor(UIAnchor());

	update(0, true);
}

void LoadProjectWindow::onAddedToRoot(UIRoot& root)
{
	root.setFocus(getWidget("recent"));
}

void LoadProjectWindow::update(Time t, bool moved)
{
	const auto size = editor.getAPI().video->getWindow().getDefinition().getSize();
	setMinSize(Vector2f(size));
	layout();
}
<|endoftext|>


<commit_before>#include "EditorWindow.hpp"

/**
 * @brief EditorWindow::EditorWindow
 *
 * The constructor of the EditorWindow class.
 * Sets up the whole UI around the Editor,
 * including slots and signals.
 * Also loads the settings and loads the file
 * that was last displayed when closing the editor.
 * Also, it deals with platform-specific displaying quirks.
 */
EditorWindow::EditorWindow(const QHash<QString, QVariant> &settings, QWidget *parent) : QMainWindow(parent){
    codeEditor = new CodeEditor(this, settings.value("UseCompiler").toInt());
    setCentralWidget(codeEditor);

    addActions();
    addMenus();
    addToolBars();
    addStatusBar();

    connect(codeEditor->document(), SIGNAL(contentsChanged()), this, SLOT(docModified()));

    templateNum = settings.value("UseCompiler").toInt();
    applySettings(settings);

    // Mac quirks
    setUnifiedTitleAndToolBarOnMac(true);

    setWindowIcon(QIcon("Icon.icns"));
}

/**
 * @brief EditorWindow::~EditorWindow
 *
 * Destructor of the EditorWindow class.
 * Deletes all the GUI elements.
 */
EditorWindow::~EditorWindow(){
    delete codeEditor;
    delete newAction;
    delete openAction;
    delete saveAction;
    delete saveAsAction;
    delete exitAction;
    delete runAction;
    delete settingsAction;
    delete helpAction;
    delete fMenu;
    delete eMenu;
    delete hMenu;
    delete fileBar;
    delete editBar;
}

/**
 * @brief EditorWindow::closeEvent
 * @param event
 *
 * reacts to the close signal; saves the current preferences
 * if wanted and exits(SLOT).
 */
void EditorWindow::closeEvent(QCloseEvent *event){
    if(saveDialog()){
        saveSettings();
        emit closing(this);
        event->accept();
    }else
        event->ignore();
}

void EditorWindow::gotOpenHelp()
{
    emit openHelp(this);
}

void EditorWindow::gotCloseAll()
{
    emit closeAll(this);
}

/**
 * @brief EditorWindow::newFile
 *
 * opens a new, empty file in the editor(SLOT).
 */
void EditorWindow::newFile(){
    if(saveDialog()){
        codeEditor->clear();
        setAsCurrentFile("");
        if(templateNum == 0)
            loadFile(":/rc/template.py");
        else if(templateNum == 2)
            loadFile(":/rc/template.glsl");
    }
}

/**
 * @brief EditorWindow::openFile
 *
 * Opens a file choosing dialog and opens
 * the requested file(SLOT).
 */
void EditorWindow::openFile(){
    if(saveDialog()){
        QString fileName = QFileDialog::getOpenFileName(this);
        if (!fileName.isEmpty()){
            if(fileName.endsWith("py")){
                templateNum = 0;
                codeEditor->setHighlighting(0);
                emit changedSetting(this, "UseCompiler", 0);
            }else if(fileName.endsWith("qml")){
                templateNum = 1;
                codeEditor->setHighlighting(1);
                emit changedSetting(this, "UseCompiler", 1);
            }else if(fileName.endsWith("glsl")){
                templateNum = 2;
                codeEditor->setHighlighting(2);
                emit changedSetting(this, "UseCompiler", 2);
            }
            loadFile(fileName);
        }
    }
}

/**
 * @brief EditorWindow::saveFile
 * @return the return codes of the
 *         saveFileAs()/saveFile(filename) functions
 *
 * reacts to the saveFile SIGNAL and redirects to
 * either saveFileAs() (if there is no filename assgined
 * to the current file) or saveFile(filename) (if there is
 * a name to the current file)(SLOT).
 */
bool EditorWindow::saveFile(){
   if(currentFile.isEmpty()){
        return saveFileAs();
    }else{
        return saveFile(currentFile);
    }
}

/**
 * @brief EditorWindow::saveFileAs
 * @return bool - false if the file choosing dialog
 *         failed/return code of the saveFile(filename)
 *         function otherwise
 *
 * opens a file choosing dialog and saves the contents
 * of the text editor under the chosen name(SLOT).
 */
bool EditorWindow::saveFileAs(){
    QString fileName = QFileDialog::getSaveFileName(this);
    return !fileName.isEmpty() && saveFile(fileName);
}

/**
 * @brief EditorWindow::saveSettings
 *
 * saves own settings.
 */
void EditorWindow::saveSettings(){
    QHash<QString, QVariant> settings;
    settings.insert("pos", this->pos());
    settings.insert("size", this->size());
    if(!currentFile.contains("template."))
        settings.insert("file", currentFile);
    else
        settings.insert("file", "");
    emit changedSettings(this, settings);
}

/**
 * @brief EditorWindow::openSettings
 *
 * creates an instance of SettingsWindow and executes it.
 */
void EditorWindow::gotOpenSettings(){
    emit openSettings(this);
}

/**
 * @brief EditorWindow::docModified
 *
 * reacts to the contentsChanged() SIGNAL by setting the
 * window properties to modified/not modified( as shown by
 * the little * at the top of the window beside the name).
 */
void EditorWindow::docModified(){
    setWindowModified(codeEditor->document()->isModified());
}

/**
 * @brief EditorWindow::warningDisplay
 * @param message
 *
 * Displays a warning box containing message.
 */
void EditorWindow::warningDisplay(const QString &message){
    QMessageBox::warning(this, tr("VeToLC"), message);
}

/**
 * @brief EditorWindow::codeStopped
 *
 * Sets the icon back to normal.
 */
void EditorWindow::codeStopped()
{
    runAction->setIcon(QIcon(":/images/run.png"));
}

/**
 * @brief EditorWindow::highlightErroredLine
 * @param lineno
 *
 * Highlights a given line in red. Signifies an error in
 * that line.
 */
void EditorWindow::highlightErroredLine(int lineno){
    codeEditor->highlightErroredLine(lineno);
}

/**
 * @brief EditorWindow::apply‚Settings
 *
 * Reads the "persistent platform-independent
 * application settings" and gets the settings.
 */
void EditorWindow::applySettings(const QHash<QString, QVariant> &settings){
    if(settings.value("RememberSize").toBool()){
        const QPoint  pos  = settings.value("pos", QPoint(200,200)).toPoint();
        const QSize   size = settings.value("size", QSize(600, 600)).toSize();
        move(pos);
        resize(size);
    }
    const QString file = settings.value("file", "").toString();
    if(file.isEmpty()){
        if(templateNum == 0)
            loadFile(":/rc/template.py");
        else if(templateNum == 2)
            loadFile(":/rc/template.glsl");
        setAsCurrentFile("");
    } else
        loadFile(file);
}

/**
 * @brief EditorWindow:: runFile
 *
 * lets the backend run the file.
 */
void EditorWindow::runFile(){
    runAction->setIcon(QIcon(":/images/refresh.png"));
    runCode(this);
}

/**
 * @brief EditorWindow::showResults
 * @param returnedValue
 *
 * Is called after the execution of the interpreter thread has finished.
 * Shows its return code or an exception traceback.
 */
void EditorWindow::showResults(const QString &returnedValue){
    statusBar()->showMessage(returnedValue, 5000);
    runAction->setIcon(QIcon(":/images/run.png"));
}

/**
 * @brief EditorWindow::getSourceCode
 * @return plain text in editor
 *
 * returns code in editor.
 */
QString EditorWindow::getSourceCode() const{
    return codeEditor->toPlainText();
}

/**
 * @brief EditorWindow::getTitle
 * @return current file name as string.
 *
 * returns current file name.
 */
QString EditorWindow::getTitle() const{
    return currentFile;
}

/**
 * @brief EditorWindow::addActions
 *
 * adds signals(buttons, shortcuts) to the window.
 */
void EditorWindow::addActions(){
    newAction = new QAction(QIcon(":/images/new.png"), tr("&New File"), this);
    newAction->setShortcuts(QKeySequence::New);
    newAction->setStatusTip(tr("Create a new file"));
    connect(newAction, SIGNAL(triggered()), this, SLOT(newFile()));

    openAction = new QAction(QIcon(":/images/open.png"), tr("&Open..."), this);
    openAction->setShortcuts(QKeySequence::Open);
    openAction->setStatusTip(tr("Open an existing file"));
    connect(openAction, SIGNAL(triggered()), this, SLOT(openFile()));

    saveAction = new QAction(QIcon(":/images/save.png"), tr("&Save"), this);
    saveAction->setShortcuts(QKeySequence::Save);
    saveAction->setStatusTip(tr("Save the document to disk"));
    connect(saveAction, SIGNAL(triggered()), this, SLOT(saveFile()));

    saveAsAction = new QAction(tr("Save &As..."), this);
    saveAsAction->setShortcuts(QKeySequence::SaveAs);
    saveAsAction->setStatusTip(tr("Save the document under a new name"));
    connect(saveAsAction, SIGNAL(triggered()), this, SLOT(saveFileAs()));

    exitAction = new QAction(tr("E&xit"), this);
    exitAction->setShortcuts(QKeySequence::Quit);
    exitAction->setStatusTip(tr("Exit the application"));
    connect(exitAction, SIGNAL(triggered()), this, SLOT(gotCloseAll()));

    runAction = new QAction(QIcon(":/images/run.png"), tr("&Run"), this);
    runAction->setShortcuts(QKeySequence::Refresh);
    runAction->setStatusTip(tr("Runs the code in the editor"));
    connect(runAction, SIGNAL(triggered()), this, SLOT(runFile()));

    settingsAction = new QAction(QIcon(":/images/settings.png"), tr("Settings"), this);
    settingsAction->setShortcuts(QKeySequence::Preferences);
    settingsAction->setStatusTip(tr("Opens A Settings Window"));
    connect(settingsAction, SIGNAL(triggered()), this, SLOT(gotOpenSettings()));

    helpAction = new QAction(tr("About"), this);
    helpAction->setShortcuts(QKeySequence::HelpContents);
    helpAction->setStatusTip(tr("Opens the Help"));
    connect(helpAction, SIGNAL(triggered()), this, SLOT(gotOpenHelp()));
}

/**
 * @brief EditorWindow::addMenus
 *
 * adds the menus to the window(duh!) and fills them
 * with the corresponding actions.
 */
void EditorWindow::addMenus(){
    fMenu = menuBar()->addMenu(tr("&File"));
    fMenu->addAction(newAction);
    fMenu->addAction(openAction);
    fMenu->addAction(saveAction);
    fMenu->addAction(saveAsAction);
    fMenu->addSeparator();
    fMenu->addAction(exitAction);

    eMenu = menuBar()->addMenu(tr("&Edit"));
    eMenu->addAction(settingsAction);
    eMenu->addAction(runAction);
    menuBar()->addSeparator();

    hMenu = menuBar()->addMenu(tr("&Help"));
    hMenu->addAction(helpAction);
}

/**
 * @brief EditorWindow::addToolBars
 *
 * adds the toolbars to the window(duh!) and fills them
 * with the corresponding actions.
 */
void EditorWindow::addToolBars(){
    fileBar = addToolBar(tr("File"));
    fileBar->addAction(newAction);
    fileBar->addAction(openAction);
    fileBar->addAction(saveAction);

    editBar = addToolBar(tr("Edit"));
    fileBar->addAction(settingsAction);
    fileBar->addAction(runAction);
}

/**
 * @brief EditorWindow::addStatusBar
 *
 * Adds a status bar to the window(duh!) and shows a
 * message in it displaying it is ready to use.
 */
void EditorWindow::addStatusBar(){
    statusBar()->showMessage(tr("Ready"));
}

/**
 * @brief EditorWindow::saveDialog
 * @return bool - true if the user does not want to save or the
 *         document is saved in its current state/false if he
 *         cancels/return code of the saveFile() function
 *
 * Opens a dialog asking the user if he wants to save the changes.
 * Invoked when he exits the application/the current file unchanged.
 */
bool EditorWindow::saveDialog(){
    if(codeEditor->document()->isModified()){
        QMessageBox::StandardButton question;
        question = QMessageBox::warning(this, tr("VeToLC"),
                                tr("The document has been modified"
                                   " but is unsaved.\n"
                                "Do you want to save your changes?"),
                                QMessageBox::Save | QMessageBox::Discard
                                | QMessageBox::Cancel);
        if(question == QMessageBox::Save)
            return saveFile();
        else if(question == QMessageBox::Cancel)
            return false;
    }
    return true;
}

/**
 * @brief EditorWindow::loadFile
 * @param path
 *
 * loads a file of a given name
 */
void EditorWindow::loadFile(const QString &path){
    QFile file(path);
    //display an error message if the file cannot be opened and why
    if(!file.open(QFile::ReadOnly | QFile::Text)){
        QMessageBox::warning(this, tr("VeToLC"),
                             tr("Cannot read file %1:\n%2.")
                              .arg(path)
                              .arg(file.errorString()));
        return;
    }

    /*
     * while the application is busy loading,
     * set a waiting cursor. Real fancy, huh?
     */
    QTextStream in(&file);
#ifdef QT_NO_CURSOR
    codeEditor->setPlainText(in.readAll());
#else
    QApplication::setOverrideCursor(Qt::WaitCursor);
    codeEditor->setPlainText(in.readAll());
    QApplication::restoreOverrideCursor();
#endif

    //set current file and display a message in the status bar
    setAsCurrentFile(path);
    statusBar()->showMessage(tr("File was loaded"), 2000);
    emit changedSetting(this, "file", path);
}

/**
 * @brief EditorWindow::saveFile
 * @param name
 * @return bool - false if the file cannot be saved/
 *         true if everything went fine
 *
 * saves the current file under a provided name
 */
bool EditorWindow::saveFile(const QString &name){
    QFile file(name);
    //display an error message if the file cannot be saved and why
    if(!file.open(QFile::WriteOnly | QFile::Text)){
        warningDisplay(tr("Cannot write file %1:\n%2.")
                           .arg(name)
                           .arg(file.errorString()));
        return false;
    }

    /*
     * while the application is busy loading,
     * set a waiting cursor. Real fancy, huh?
     */
    QTextStream out(&file);
#ifdef QT_NO_CURSOR
    out << codeEditor->toPlainText();
#else
    QApplication::setOverrideCursor(Qt::WaitCursor);
    out << codeEditor->toPlainText();
    QApplication::restoreOverrideCursor();
#endif

    //set current file and display a message in the status bar
    setAsCurrentFile(name);
    statusBar()->showMessage(tr("File saved"), 2000);
    return true;
}

/**
 * @brief EditorWindow::setAsCurrentFile
 * @param name
 *
 * sets the file name and displays it at the top of the window
 */
void EditorWindow::setAsCurrentFile(const QString &name){
    currentFile = name;
    codeEditor->document()->setModified(false);

    setWindowModified(false);

    setWindowFilePath(currentFile);
    if(currentFile != "" && !currentFile.contains("template."))
        setWindowTitle("VeToLC | " + stripName(currentFile) + "[*]");
    else
        setWindowTitle("VeToLC [*]");
}

/**
 * @brief EditorWindow::stripName
 * @param fullName
 * @return return code of QFileInfo
 *
 * strips the fully qualified name of a file to the unqualified one
 */
QString EditorWindow::stripName(const QString &fullName){
    return QFileInfo(fullName).fileName();
}
<commit_msg>Fixed #12; Windows and OS X now have an icon<commit_after>#include "EditorWindow.hpp"

/**
 * @brief EditorWindow::EditorWindow
 *
 * The constructor of the EditorWindow class.
 * Sets up the whole UI around the Editor,
 * including slots and signals.
 * Also loads the settings and loads the file
 * that was last displayed when closing the editor.
 * Also, it deals with platform-specific displaying quirks.
 */
EditorWindow::EditorWindow(const QHash<QString, QVariant> &settings, QWidget *parent) : QMainWindow(parent){
    codeEditor = new CodeEditor(this, settings.value("UseCompiler").toInt());
    setCentralWidget(codeEditor);

    addActions();
    addMenus();
    addToolBars();
    addStatusBar();

    connect(codeEditor->document(), SIGNAL(contentsChanged()), this, SLOT(docModified()));

    templateNum = settings.value("UseCompiler").toInt();
    applySettings(settings);

    // Mac quirks
    setUnifiedTitleAndToolBarOnMac(true);

#if defined(Q_OS_MAC)
    setWindowIcon(QIcon("Icon.icns"));
#elif defined(Q_OS_WIN)
    setWindowIcon(QIcon("Icon.ico"));
#endif
}

/**
 * @brief EditorWindow::~EditorWindow
 *
 * Destructor of the EditorWindow class.
 * Deletes all the GUI elements.
 */
EditorWindow::~EditorWindow(){
    delete codeEditor;
    delete newAction;
    delete openAction;
    delete saveAction;
    delete saveAsAction;
    delete exitAction;
    delete runAction;
    delete settingsAction;
    delete helpAction;
    delete fMenu;
    delete eMenu;
    delete hMenu;
    delete fileBar;
    delete editBar;
}

/**
 * @brief EditorWindow::closeEvent
 * @param event
 *
 * reacts to the close signal; saves the current preferences
 * if wanted and exits(SLOT).
 */
void EditorWindow::closeEvent(QCloseEvent *event){
    if(saveDialog()){
        saveSettings();
        emit closing(this);
        event->accept();
    }else
        event->ignore();
}

void EditorWindow::gotOpenHelp()
{
    emit openHelp(this);
}

void EditorWindow::gotCloseAll()
{
    emit closeAll(this);
}

/**
 * @brief EditorWindow::newFile
 *
 * opens a new, empty file in the editor(SLOT).
 */
void EditorWindow::newFile(){
    if(saveDialog()){
        codeEditor->clear();
        setAsCurrentFile("");
        if(templateNum == 0)
            loadFile(":/rc/template.py");
        else if(templateNum == 2)
            loadFile(":/rc/template.glsl");
    }
}

/**
 * @brief EditorWindow::openFile
 *
 * Opens a file choosing dialog and opens
 * the requested file(SLOT).
 */
void EditorWindow::openFile(){
    if(saveDialog()){
        QString fileName = QFileDialog::getOpenFileName(this);
        if (!fileName.isEmpty()){
            if(fileName.endsWith("py")){
                templateNum = 0;
                codeEditor->setHighlighting(0);
                emit changedSetting(this, "UseCompiler", 0);
            }else if(fileName.endsWith("qml")){
                templateNum = 1;
                codeEditor->setHighlighting(1);
                emit changedSetting(this, "UseCompiler", 1);
            }else if(fileName.endsWith("glsl")){
                templateNum = 2;
                codeEditor->setHighlighting(2);
                emit changedSetting(this, "UseCompiler", 2);
            }
            loadFile(fileName);
        }
    }
}

/**
 * @brief EditorWindow::saveFile
 * @return the return codes of the
 *         saveFileAs()/saveFile(filename) functions
 *
 * reacts to the saveFile SIGNAL and redirects to
 * either saveFileAs() (if there is no filename assgined
 * to the current file) or saveFile(filename) (if there is
 * a name to the current file)(SLOT).
 */
bool EditorWindow::saveFile(){
   if(currentFile.isEmpty()){
        return saveFileAs();
    }else{
        return saveFile(currentFile);
    }
}

/**
 * @brief EditorWindow::saveFileAs
 * @return bool - false if the file choosing dialog
 *         failed/return code of the saveFile(filename)
 *         function otherwise
 *
 * opens a file choosing dialog and saves the contents
 * of the text editor under the chosen name(SLOT).
 */
bool EditorWindow::saveFileAs(){
    QString fileName = QFileDialog::getSaveFileName(this);
    return !fileName.isEmpty() && saveFile(fileName);
}

/**
 * @brief EditorWindow::saveSettings
 *
 * saves own settings.
 */
void EditorWindow::saveSettings(){
    QHash<QString, QVariant> settings;
    settings.insert("pos", this->pos());
    settings.insert("size", this->size());
    if(!currentFile.contains("template."))
        settings.insert("file", currentFile);
    else
        settings.insert("file", "");
    emit changedSettings(this, settings);
}

/**
 * @brief EditorWindow::openSettings
 *
 * creates an instance of SettingsWindow and executes it.
 */
void EditorWindow::gotOpenSettings(){
    emit openSettings(this);
}

/**
 * @brief EditorWindow::docModified
 *
 * reacts to the contentsChanged() SIGNAL by setting the
 * window properties to modified/not modified( as shown by
 * the little * at the top of the window beside the name).
 */
void EditorWindow::docModified(){
    setWindowModified(codeEditor->document()->isModified());
}

/**
 * @brief EditorWindow::warningDisplay
 * @param message
 *
 * Displays a warning box containing message.
 */
void EditorWindow::warningDisplay(const QString &message){
    QMessageBox::warning(this, tr("VeToLC"), message);
}

/**
 * @brief EditorWindow::codeStopped
 *
 * Sets the icon back to normal.
 */
void EditorWindow::codeStopped()
{
    runAction->setIcon(QIcon(":/images/run.png"));
}

/**
 * @brief EditorWindow::highlightErroredLine
 * @param lineno
 *
 * Highlights a given line in red. Signifies an error in
 * that line.
 */
void EditorWindow::highlightErroredLine(int lineno){
    codeEditor->highlightErroredLine(lineno);
}

/**
 * @brief EditorWindow::apply‚Settings
 *
 * Reads the "persistent platform-independent
 * application settings" and gets the settings.
 */
void EditorWindow::applySettings(const QHash<QString, QVariant> &settings){
    if(settings.value("RememberSize").toBool()){
        const QPoint  pos  = settings.value("pos", QPoint(200,200)).toPoint();
        const QSize   size = settings.value("size", QSize(600, 600)).toSize();
        move(pos);
        resize(size);
    }
    const QString file = settings.value("file", "").toString();
    if(file.isEmpty()){
        if(templateNum == 0)
            loadFile(":/rc/template.py");
        else if(templateNum == 2)
            loadFile(":/rc/template.glsl");
        setAsCurrentFile("");
    } else
        loadFile(file);
}

/**
 * @brief EditorWindow:: runFile
 *
 * lets the backend run the file.
 */
void EditorWindow::runFile(){
    runAction->setIcon(QIcon(":/images/refresh.png"));
    runCode(this);
}

/**
 * @brief EditorWindow::showResults
 * @param returnedValue
 *
 * Is called after the execution of the interpreter thread has finished.
 * Shows its return code or an exception traceback.
 */
void EditorWindow::showResults(const QString &returnedValue){
    statusBar()->showMessage(returnedValue, 5000);
    runAction->setIcon(QIcon(":/images/run.png"));
}

/**
 * @brief EditorWindow::getSourceCode
 * @return plain text in editor
 *
 * returns code in editor.
 */
QString EditorWindow::getSourceCode() const{
    return codeEditor->toPlainText();
}

/**
 * @brief EditorWindow::getTitle
 * @return current file name as string.
 *
 * returns current file name.
 */
QString EditorWindow::getTitle() const{
    return currentFile;
}

/**
 * @brief EditorWindow::addActions
 *
 * adds signals(buttons, shortcuts) to the window.
 */
void EditorWindow::addActions(){
    newAction = new QAction(QIcon(":/images/new.png"), tr("&New File"), this);
    newAction->setShortcuts(QKeySequence::New);
    newAction->setStatusTip(tr("Create a new file"));
    connect(newAction, SIGNAL(triggered()), this, SLOT(newFile()));

    openAction = new QAction(QIcon(":/images/open.png"), tr("&Open..."), this);
    openAction->setShortcuts(QKeySequence::Open);
    openAction->setStatusTip(tr("Open an existing file"));
    connect(openAction, SIGNAL(triggered()), this, SLOT(openFile()));

    saveAction = new QAction(QIcon(":/images/save.png"), tr("&Save"), this);
    saveAction->setShortcuts(QKeySequence::Save);
    saveAction->setStatusTip(tr("Save the document to disk"));
    connect(saveAction, SIGNAL(triggered()), this, SLOT(saveFile()));

    saveAsAction = new QAction(tr("Save &As..."), this);
    saveAsAction->setShortcuts(QKeySequence::SaveAs);
    saveAsAction->setStatusTip(tr("Save the document under a new name"));
    connect(saveAsAction, SIGNAL(triggered()), this, SLOT(saveFileAs()));

    exitAction = new QAction(tr("E&xit"), this);
    exitAction->setShortcuts(QKeySequence::Quit);
    exitAction->setStatusTip(tr("Exit the application"));
    connect(exitAction, SIGNAL(triggered()), this, SLOT(gotCloseAll()));

    runAction = new QAction(QIcon(":/images/run.png"), tr("&Run"), this);
    runAction->setShortcuts(QKeySequence::Refresh);
    runAction->setStatusTip(tr("Runs the code in the editor"));
    connect(runAction, SIGNAL(triggered()), this, SLOT(runFile()));

    settingsAction = new QAction(QIcon(":/images/settings.png"), tr("Settings"), this);
    settingsAction->setShortcuts(QKeySequence::Preferences);
    settingsAction->setStatusTip(tr("Opens A Settings Window"));
    connect(settingsAction, SIGNAL(triggered()), this, SLOT(gotOpenSettings()));

    helpAction = new QAction(tr("About"), this);
    helpAction->setShortcuts(QKeySequence::HelpContents);
    helpAction->setStatusTip(tr("Opens the Help"));
    connect(helpAction, SIGNAL(triggered()), this, SLOT(gotOpenHelp()));
}

/**
 * @brief EditorWindow::addMenus
 *
 * adds the menus to the window(duh!) and fills them
 * with the corresponding actions.
 */
void EditorWindow::addMenus(){
    fMenu = menuBar()->addMenu(tr("&File"));
    fMenu->addAction(newAction);
    fMenu->addAction(openAction);
    fMenu->addAction(saveAction);
    fMenu->addAction(saveAsAction);
    fMenu->addSeparator();
    fMenu->addAction(exitAction);

    eMenu = menuBar()->addMenu(tr("&Edit"));
    eMenu->addAction(settingsAction);
    eMenu->addAction(runAction);
    menuBar()->addSeparator();

    hMenu = menuBar()->addMenu(tr("&Help"));
    hMenu->addAction(helpAction);
}

/**
 * @brief EditorWindow::addToolBars
 *
 * adds the toolbars to the window(duh!) and fills them
 * with the corresponding actions.
 */
void EditorWindow::addToolBars(){
    fileBar = addToolBar(tr("File"));
    fileBar->addAction(newAction);
    fileBar->addAction(openAction);
    fileBar->addAction(saveAction);

    editBar = addToolBar(tr("Edit"));
    fileBar->addAction(settingsAction);
    fileBar->addAction(runAction);
}

/**
 * @brief EditorWindow::addStatusBar
 *
 * Adds a status bar to the window(duh!) and shows a
 * message in it displaying it is ready to use.
 */
void EditorWindow::addStatusBar(){
    statusBar()->showMessage(tr("Ready"));
}

/**
 * @brief EditorWindow::saveDialog
 * @return bool - true if the user does not want to save or the
 *         document is saved in its current state/false if he
 *         cancels/return code of the saveFile() function
 *
 * Opens a dialog asking the user if he wants to save the changes.
 * Invoked when he exits the application/the current file unchanged.
 */
bool EditorWindow::saveDialog(){
    if(codeEditor->document()->isModified()){
        QMessageBox::StandardButton question;
        question = QMessageBox::warning(this, tr("VeToLC"),
                                tr("The document has been modified"
                                   " but is unsaved.\n"
                                "Do you want to save your changes?"),
                                QMessageBox::Save | QMessageBox::Discard
                                | QMessageBox::Cancel);
        if(question == QMessageBox::Save)
            return saveFile();
        else if(question == QMessageBox::Cancel)
            return false;
    }
    return true;
}

/**
 * @brief EditorWindow::loadFile
 * @param path
 *
 * loads a file of a given name
 */
void EditorWindow::loadFile(const QString &path){
    QFile file(path);
    //display an error message if the file cannot be opened and why
    if(!file.open(QFile::ReadOnly | QFile::Text)){
        QMessageBox::warning(this, tr("VeToLC"),
                             tr("Cannot read file %1:\n%2.")
                              .arg(path)
                              .arg(file.errorString()));
        return;
    }

    /*
     * while the application is busy loading,
     * set a waiting cursor. Real fancy, huh?
     */
    QTextStream in(&file);
#ifdef QT_NO_CURSOR
    codeEditor->setPlainText(in.readAll());
#else
    QApplication::setOverrideCursor(Qt::WaitCursor);
    codeEditor->setPlainText(in.readAll());
    QApplication::restoreOverrideCursor();
#endif

    //set current file and display a message in the status bar
    setAsCurrentFile(path);
    statusBar()->showMessage(tr("File was loaded"), 2000);
    emit changedSetting(this, "file", path);
}

/**
 * @brief EditorWindow::saveFile
 * @param name
 * @return bool - false if the file cannot be saved/
 *         true if everything went fine
 *
 * saves the current file under a provided name
 */
bool EditorWindow::saveFile(const QString &name){
    QFile file(name);
    //display an error message if the file cannot be saved and why
    if(!file.open(QFile::WriteOnly | QFile::Text)){
        warningDisplay(tr("Cannot write file %1:\n%2.")
                           .arg(name)
                           .arg(file.errorString()));
        return false;
    }

    /*
     * while the application is busy loading,
     * set a waiting cursor. Real fancy, huh?
     */
    QTextStream out(&file);
#ifdef QT_NO_CURSOR
    out << codeEditor->toPlainText();
#else
    QApplication::setOverrideCursor(Qt::WaitCursor);
    out << codeEditor->toPlainText();
    QApplication::restoreOverrideCursor();
#endif

    //set current file and display a message in the status bar
    setAsCurrentFile(name);
    statusBar()->showMessage(tr("File saved"), 2000);
    return true;
}

/**
 * @brief EditorWindow::setAsCurrentFile
 * @param name
 *
 * sets the file name and displays it at the top of the window
 */
void EditorWindow::setAsCurrentFile(const QString &name){
    currentFile = name;
    codeEditor->document()->setModified(false);

    setWindowModified(false);

    setWindowFilePath(currentFile);
    if(currentFile != "" && !currentFile.contains("template."))
        setWindowTitle("VeToLC | " + stripName(currentFile) + "[*]");
    else
        setWindowTitle("VeToLC [*]");
}

/**
 * @brief EditorWindow::stripName
 * @param fullName
 * @return return code of QFileInfo
 *
 * strips the fully qualified name of a file to the unqualified one
 */
QString EditorWindow::stripName(const QString &fullName){
    return QFileInfo(fullName).fileName();
}
<|endoftext|>


<commit_before>//
//  EffectorNode.cpp
//  Cinder-Pipeline
//
//  Created by Jean-Pierre Mouilleseaux on 19 May 2014.
//  Copyright 2014-2015 Chorded Constructions. All rights reserved.
//

#include "EffectorNode.h"

namespace Cinder { namespace Pipeline {

using namespace ci;

const std::string EffectorNode::sVertexShaderPassThrough = R"(
    #version 150
    uniform mat4 ciModelViewProjection;

    in vec4 ciPosition;
    in vec4 ciTexCoord0;

    out highp vec2 TexCoord0;

    void main() {
        TexCoord0 = ciTexCoord0.st;
        gl_Position = ciModelViewProjection * ciPosition;
    }
)";

void EffectorNode::setupShader(const DataSourceRef& vertexShader, const DataSourceRef& fragmentShader) {
    std::string vert = vertexShader ? loadString(vertexShader) : sVertexShaderPassThrough;
    std::string frag = loadString(fragmentShader);
    setupShader(vert, frag);
}

void EffectorNode::setupShader(const std::string& vertexShader, const std::string& fragmentShader) {
    const char* vert = !vertexShader.empty() ? vertexShader.c_str() : sVertexShaderPassThrough.c_str();
    const char* frag = fragmentShader.c_str();
    mShader = gl::GlslProg::create(vert, frag);
}

}}
<commit_msg>use new string GlslProg constructor<commit_after>//
//  EffectorNode.cpp
//  Cinder-Pipeline
//
//  Created by Jean-Pierre Mouilleseaux on 19 May 2014.
//  Copyright 2014-2015 Chorded Constructions. All rights reserved.
//

#include "EffectorNode.h"

namespace Cinder { namespace Pipeline {

using namespace ci;

const std::string EffectorNode::sVertexShaderPassThrough = R"(
    #version 150
    uniform mat4 ciModelViewProjection;

    in vec4 ciPosition;
    in vec4 ciTexCoord0;

    out highp vec2 TexCoord0;

    void main() {
        TexCoord0 = ciTexCoord0.st;
        gl_Position = ciModelViewProjection * ciPosition;
    }
)";

void EffectorNode::setupShader(const DataSourceRef& vertexShader, const DataSourceRef& fragmentShader) {
    std::string vert = vertexShader ? loadString(vertexShader) : sVertexShaderPassThrough;
    std::string frag = loadString(fragmentShader);
    setupShader(vert, frag);
}

void EffectorNode::setupShader(const std::string& vertexShader, const std::string& fragmentShader) {
    std::string vert = !vertexShader.empty() ? vertexShader : sVertexShaderPassThrough;
    mShader = gl::GlslProg::create(vert, fragmentShader);
}

}}
<|endoftext|>


<commit_before>/* ---------------------------------------------------------------------
 * Numenta Platform for Intelligent Computing (NuPIC)
 * Copyright (C) 2015-2016, Numenta, Inc.  Unless you have an agreement
 * with Numenta, Inc., for a separate license for this software code, the
 * following terms and conditions apply:
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero Public License version 3 as
 * published by the Free Software Foundation.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU Affero Public License for more details.
 *
 * You should have received a copy of the GNU Affero Public License
 * along with this program.  If not, see http://www.gnu.org/licenses.
 *
 * http://numenta.org/licenses/
 * ---------------------------------------------------------------------
 */

#include "gtest/gtest.h"

/** @file
 * Implementation of performance tests for Connections
 */

#include <fstream>
#include <iostream>

#include <nupic/algorithms/Connections.hpp>
#include <nupic/algorithms/TemporalMemory.hpp>
#include <nupic/utils/Random.hpp>
#include <nupic/os/Timer.hpp>

namespace testing {

using namespace std;
using namespace nupic;
using ::nupic::algorithms::connections::Segment;
using ::nupic::algorithms::temporal_memory::TemporalMemory;

#define SEED 42

Random rng(SEED);

std::vector<UInt32> _randomSDR(UInt n, UInt w);
void _feedTM(TemporalMemory &tm, vector<CellIdx> sdr, bool learn = true);
std::vector<CellIdx> _computeSPWinnerCells(Connections &connections, UInt numCells,
                       const vector<UInt> &numActiveSynapsesForSegment);

float runTemporalMemoryTest(UInt numColumns, UInt w,   int numSequences,
                                                       int numElements,
                                                       string label) {
  Timer timer(true);

  // Initialize

  TemporalMemory tm;
  vector<UInt> columnDim;
  columnDim.push_back(numColumns);
  tm.initialize(columnDim);

  cout << (float)timer.getElapsed() << " in " << label << ": initialize"  << endl;

  // Learn

  vector<vector<vector<CellIdx>>> sequences;
  vector<vector<CellIdx>> sequence;
  vector<CellIdx> sdr;

  for (int i = 0; i < numSequences; i++) {
    for (int j = 0; j < numElements; j++) {
      sdr = _randomSDR(numColumns, w);
      sequence.push_back(sdr);
    }

    sequences.push_back(sequence);
  }

  for (int i = 0; i < 5; i++) {
    for (auto sequence : sequences) {
      for (auto sdr : sequence) {
        _feedTM(tm, sdr);
        tm.reset();
      }
    }
  }

  cout << (float)timer.getElapsed() << " in " << label << ": initialize + learn"  << endl;

  // Test

  for (auto sequence : sequences) {
    for (auto sdr : sequence) {
      _feedTM(tm, sdr, false);
      tm.reset();
    }
  }

  cout << (float)timer.getElapsed() << " in " << label << ": initialize + learn + test"  << endl;
  timer.stop();
  return timer.getElapsed();
}

float runSpatialPoolerTest(UInt numCells, UInt numInputs, UInt w,
                           UInt numWinners, string label) {
  Timer timer;
  timer.start();

  Connections connections(numCells);
  Segment segment;
  vector<CellIdx> sdr;

  // Initialize

  for (UInt c = 0; c < numCells; c++) {
    segment = connections.createSegment(c);

    for (UInt i = 0; i < numInputs; i++) {
      const Permanence permanence = (Permanence)rng.getReal64();
      connections.createSynapse(segment, i, permanence);
    }
  }

  cout << (float)timer.getElapsed() << " in " << label << ": initialize"  << endl;

  // Learn

  vector<CellIdx> winnerCells;
  Permanence permanence;

  for (int i = 0; i < 500; i++) {
    sdr = _randomSDR(numInputs, w);
    vector<UInt32> numActiveConnectedSynapsesForSegment(
        connections.segmentFlatListLength(), 0);
    vector<UInt32> numActivePotentialSynapsesForSegment(
        connections.segmentFlatListLength(), 0);
    connections.computeActivity(numActiveConnectedSynapsesForSegment,
                                numActivePotentialSynapsesForSegment, sdr, 0.5);
    winnerCells = _computeSPWinnerCells(connections, numWinners,
                                       numActiveConnectedSynapsesForSegment);

    for (CellIdx winnerCell : winnerCells) {
      segment = connections.getSegment(winnerCell, 0);

      const vector<Synapse> &synapses = connections.synapsesForSegment(segment);

      for (SynapseIdx i = 0; i < (SynapseIdx)synapses.size();) {
        const Synapse synapse = synapses[i];
        const SynapseData &synapseData = connections.dataForSynapse(synapse);
        permanence = synapseData.permanence;

        if (find(sdr.begin(), sdr.end(), synapseData.presynapticCell) !=
            sdr.end()) {
          permanence += 0.2;
        } else {
          permanence -= 0.1;
        }

        permanence = max(permanence, (Permanence)0);
        permanence = min(permanence, (Permanence)1);

        if (permanence == 0) {
          connections.destroySynapse(synapse);
          // The synapses list is updated in-place, so don't update `i`.
        } else {
          connections.updateSynapsePermanence(synapse, permanence);
          i++;
        }
      }
    }
  }

  cout << (float)timer.getElapsed() << " in " << label << ": initialize + learn"  << endl;

  // Test

  for (int i = 0; i < 500; i++) {
    sdr = _randomSDR(numInputs, w);
    vector<UInt32> numActiveConnectedSynapsesForSegment(
        connections.segmentFlatListLength(), 0);
    vector<UInt32> numActivePotentialSynapsesForSegment(
        connections.segmentFlatListLength(), 0);
    connections.computeActivity(numActiveConnectedSynapsesForSegment,
                                numActivePotentialSynapsesForSegment, sdr, 0.5);
    winnerCells = _computeSPWinnerCells(connections, numWinners,
                                       numActiveConnectedSynapsesForSegment);
  }

  cout << (float)timer.getElapsed() << " in " << label << ": initialize + learn + test"  << endl;
  timer.stop();
  return timer.getElapsed();
}

vector<CellIdx> _randomSDR(UInt n, UInt w) {
  set<UInt> sdrSet = set<UInt>();
  vector<CellIdx> sdr;

  for (UInt i = 0; i < w; i++) {
    sdrSet.insert(rng.getUInt32(n));
  }

  for (UInt c : sdrSet) {
    sdr.push_back(c);
  }

  return sdr;
}

void _feedTM(TemporalMemory &tm, vector<CellIdx> sdr, bool learn) {
  vector<UInt> activeColumns;

  for (auto c : sdr) {
    activeColumns.push_back(c);
  }

  tm.compute(activeColumns.size(), activeColumns.data(), learn);
}

vector<CellIdx> _computeSPWinnerCells(Connections &connections, UInt numCells,
    const vector<UInt> &numActiveSynapsesForSegment) {
  // Activate every segment, then choose the top few.
  vector<Segment> activeSegments;
  for (Segment segment = 0; segment < numActiveSynapsesForSegment.size();
       segment++) {
    activeSegments.push_back(segment);
  }

  set<CellIdx> winnerCells;
  std::sort(
      activeSegments.begin(), activeSegments.end(), [&](Segment a, Segment b) {
        return numActiveSynapsesForSegment[a] > numActiveSynapsesForSegment[b];
      });

  for (Segment segment : activeSegments) {
    winnerCells.insert(connections.cellForSegment(segment));
    if (winnerCells.size() >= numCells) {
      break;
    }
  }

  return vector<CellIdx>(winnerCells.begin(), winnerCells.end());
}

#ifdef NDEBUG //disable performance tests in debug mode
// TESTS
const UInt SEQ = 100; //number of sequences ran in tests
const UInt EPOCHS = 20; //epochs tests run
const UInt COLS = 2048; //standard num of columns in SP/TM

/**
 * Tests typical usage of Connections with Temporal Memory.
 * format is: COLS, W(bits), EPOCHS, SEQUENCES
 */
TEST(ConnectionsPerformanceTest, testTM) {
	auto tim = runTemporalMemoryTest(COLS, 40, EPOCHS, SEQ, "temporal memory");
	ASSERT_LE(tim, 3.5f); //there are times, we must be better. Bit underestimated for slow CI
}

/**
 * Tests typical usage of Connections with a large Temporal Memory.
 */
TEST(ConnectionsPerformanceTest, testTMLarge) {
  auto tim = runTemporalMemoryTest(2*COLS, 328, 10, SEQ, "temporal memory (large)");
  ASSERT_LE(tim, 7.0f);
}

/**
 * Tests typical usage of Connections with Spatial Pooler.
 */
TEST(ConnectionsPerformanceTest, testSP) {
  auto tim = runSpatialPoolerTest(COLS, COLS, EPOCHS, SEQ, "spatial pooler");
  ASSERT_LE(tim, 10.0f);
}

/**
 * Tests typical usage of Connections with Temporal Pooler.
 */
TEST(ConnectionsPerformanceTest, testTP) {
  auto tim = runSpatialPoolerTest(COLS, 16384, 10, SEQ, "temporal pooler");
  ASSERT_LE(tim, 80.0f);
}
#endif //DEBUG

} // end namespace
<commit_msg>ConnectionPerformanceTests: use relative times for threshold<commit_after>/* ---------------------------------------------------------------------
 * Numenta Platform for Intelligent Computing (NuPIC)
 * Copyright (C) 2015-2016, Numenta, Inc.  Unless you have an agreement
 * with Numenta, Inc., for a separate license for this software code, the
 * following terms and conditions apply:
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero Public License version 3 as
 * published by the Free Software Foundation.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU Affero Public License for more details.
 *
 * You should have received a copy of the GNU Affero Public License
 * along with this program.  If not, see http://www.gnu.org/licenses.
 *
 * http://numenta.org/licenses/
 * ---------------------------------------------------------------------
 */

#include "gtest/gtest.h"

/** @file
 * Implementation of performance tests for Connections
 */

#include <fstream>
#include <iostream>
#include <cmath> //for sin

#include <nupic/algorithms/Connections.hpp>
#include <nupic/algorithms/TemporalMemory.hpp>
#include <nupic/utils/Random.hpp>
#include <nupic/os/Timer.hpp>

namespace testing {

using namespace std;
using namespace nupic;
using ::nupic::algorithms::connections::Segment;
using ::nupic::algorithms::temporal_memory::TemporalMemory;

#define SEED 42

Random rng(SEED);

std::vector<UInt32> _randomSDR(UInt n, UInt w);
void _feedTM(TemporalMemory &tm, vector<CellIdx> sdr, bool learn = true);
std::vector<CellIdx> _computeSPWinnerCells(Connections &connections, UInt numCells,
                       const vector<UInt> &numActiveSynapsesForSegment);

float runTemporalMemoryTest(UInt numColumns, UInt w,   int numSequences,
                                                       int numElements,
                                                       string label) {
  Timer timer(true);

  // Initialize

  TemporalMemory tm;
  vector<UInt> columnDim;
  columnDim.push_back(numColumns);
  tm.initialize(columnDim);

  cout << (float)timer.getElapsed() << " in " << label << ": initialize"  << endl;

  // Learn

  vector<vector<vector<CellIdx>>> sequences;
  vector<vector<CellIdx>> sequence;
  vector<CellIdx> sdr;

  for (int i = 0; i < numSequences; i++) {
    for (int j = 0; j < numElements; j++) {
      sdr = _randomSDR(numColumns, w);
      sequence.push_back(sdr);
    }

    sequences.push_back(sequence);
  }

  for (int i = 0; i < 5; i++) {
    for (auto sequence : sequences) {
      for (auto sdr : sequence) {
        _feedTM(tm, sdr);
        tm.reset();
      }
    }
  }

  cout << (float)timer.getElapsed() << " in " << label << ": initialize + learn"  << endl;

  // Test

  for (auto sequence : sequences) {
    for (auto sdr : sequence) {
      _feedTM(tm, sdr, false);
      tm.reset();
    }
  }

  cout << (float)timer.getElapsed() << " in " << label << ": initialize + learn + test"  << endl;
  timer.stop();
  return timer.getElapsed();
}

float runSpatialPoolerTest(UInt numCells, UInt numInputs, UInt w,
                           UInt numWinners, string label) {
  Timer timer;
  timer.start();

  Connections connections(numCells);
  Segment segment;
  vector<CellIdx> sdr;

  // Initialize

  for (UInt c = 0; c < numCells; c++) {
    segment = connections.createSegment(c);

    for (UInt i = 0; i < numInputs; i++) {
      const Permanence permanence = (Permanence)rng.getReal64();
      connections.createSynapse(segment, i, permanence);
    }
  }

  cout << (float)timer.getElapsed() << " in " << label << ": initialize"  << endl;

  // Learn

  vector<CellIdx> winnerCells;
  Permanence permanence;

  for (int i = 0; i < 500; i++) {
    sdr = _randomSDR(numInputs, w);
    vector<UInt32> numActiveConnectedSynapsesForSegment(
        connections.segmentFlatListLength(), 0);
    vector<UInt32> numActivePotentialSynapsesForSegment(
        connections.segmentFlatListLength(), 0);
    connections.computeActivity(numActiveConnectedSynapsesForSegment,
                                numActivePotentialSynapsesForSegment, sdr, 0.5);
    winnerCells = _computeSPWinnerCells(connections, numWinners,
                                       numActiveConnectedSynapsesForSegment);

    for (CellIdx winnerCell : winnerCells) {
      segment = connections.getSegment(winnerCell, 0);

      const vector<Synapse> &synapses = connections.synapsesForSegment(segment);

      for (SynapseIdx i = 0; i < (SynapseIdx)synapses.size();) {
        const Synapse synapse = synapses[i];
        const SynapseData &synapseData = connections.dataForSynapse(synapse);
        permanence = synapseData.permanence;

        if (find(sdr.begin(), sdr.end(), synapseData.presynapticCell) !=
            sdr.end()) {
          permanence += 0.2;
        } else {
          permanence -= 0.1;
        }

        permanence = max(permanence, (Permanence)0);
        permanence = min(permanence, (Permanence)1);

        if (permanence == 0) {
          connections.destroySynapse(synapse);
          // The synapses list is updated in-place, so don't update `i`.
        } else {
          connections.updateSynapsePermanence(synapse, permanence);
          i++;
        }
      }
    }
  }

  cout << (float)timer.getElapsed() << " in " << label << ": initialize + learn"  << endl;

  // Test

  for (int i = 0; i < 500; i++) {
    sdr = _randomSDR(numInputs, w);
    vector<UInt32> numActiveConnectedSynapsesForSegment(
        connections.segmentFlatListLength(), 0);
    vector<UInt32> numActivePotentialSynapsesForSegment(
        connections.segmentFlatListLength(), 0);
    connections.computeActivity(numActiveConnectedSynapsesForSegment,
                                numActivePotentialSynapsesForSegment, sdr, 0.5);
    winnerCells = _computeSPWinnerCells(connections, numWinners,
                                       numActiveConnectedSynapsesForSegment);
  }

  cout << (float)timer.getElapsed() << " in " << label << ": initialize + learn + test"  << endl;
  timer.stop();
  return timer.getElapsed();
}

vector<CellIdx> _randomSDR(UInt n, UInt w) {
  set<UInt> sdrSet = set<UInt>();
  vector<CellIdx> sdr;

  for (UInt i = 0; i < w; i++) {
    sdrSet.insert(rng.getUInt32(n));
  }

  for (UInt c : sdrSet) {
    sdr.push_back(c);
  }

  return sdr;
}

void _feedTM(TemporalMemory &tm, vector<CellIdx> sdr, bool learn) {
  vector<UInt> activeColumns;

  for (auto c : sdr) {
    activeColumns.push_back(c);
  }

  tm.compute(activeColumns.size(), activeColumns.data(), learn);
}

vector<CellIdx> _computeSPWinnerCells(Connections &connections, UInt numCells,
    const vector<UInt> &numActiveSynapsesForSegment) {
  // Activate every segment, then choose the top few.
  vector<Segment> activeSegments;
  for (Segment segment = 0; segment < numActiveSynapsesForSegment.size();
       segment++) {
    activeSegments.push_back(segment);
  }

  set<CellIdx> winnerCells;
  std::sort(
      activeSegments.begin(), activeSegments.end(), [&](Segment a, Segment b) {
        return numActiveSynapsesForSegment[a] > numActiveSynapsesForSegment[b];
      });

  for (Segment segment : activeSegments) {
    winnerCells.insert(connections.cellForSegment(segment));
    if (winnerCells.size() >= numCells) {
      break;
    }
  }

  return vector<CellIdx>(winnerCells.begin(), winnerCells.end());
}

float _SPEED = -1;
/**
 * estimate speed (CPU & load) of the current system.
 * Tests must perform relative to this value
 */
float getSpeed() {
  if (_SPEED == -1) {
    Timer t(true);
    //this code just wastes CPU time to estimate speed
    vector<UInt> data(10000000);
    for(UInt i=0; i<data.size(); i++) {
      data[i]=rng.getUInt32(80085);
      auto t = data[i];
      data[i] = data[data.size()-i];
      data[data.size()-i]=t;
    }
    rng.shuffle(begin(data), end(data));
    vector<Real> sins;
    for (auto d : data) {
      sins.push_back(sin(d)/cos(d));
    }
    rng.sample(sins.data(), sins.size(), (float*)data.data(), 666);
    t.stop();
    _SPEED = t.getElapsed();
  }
  return _SPEED;
}

#ifdef NDEBUG //disable performance tests in debug mode
// TESTS
const UInt SEQ = 100; //number of sequences ran in tests
const UInt EPOCHS = 20; //epochs tests run
const UInt COLS = 2048; //standard num of columns in SP/TM

/**
 * Tests typical usage of Connections with Temporal Memory.
 * format is: COLS, W(bits), EPOCHS, SEQUENCES
 */
TEST(ConnectionsPerformanceTest, testTM) {
	auto tim = runTemporalMemoryTest(COLS, 40, EPOCHS, SEQ, "temporal memory");
	ASSERT_LE(tim, 1.8*getSpeed()); //there are times, we must be better. Bit underestimated for slow CI
}

/**
 * Tests typical usage of Connections with a large Temporal Memory.
 */
TEST(ConnectionsPerformanceTest, testTMLarge) {
  auto tim = runTemporalMemoryTest(2*COLS, 328, 10, SEQ, "temporal memory (large)");
  ASSERT_LE(tim, 3.6*getSpeed());
}

/**
 * Tests typical usage of Connections with Spatial Pooler.
 */
TEST(ConnectionsPerformanceTest, testSP) {
  auto tim = runSpatialPoolerTest(COLS, COLS, EPOCHS, SEQ, "spatial pooler");
  ASSERT_LE(tim, 6.3*getSpeed());
}

/**
 * Tests typical usage of Connections with Temporal Pooler.
 */
TEST(ConnectionsPerformanceTest, testTP) {
  auto tim = runSpatialPoolerTest(COLS, 16384, 10, SEQ, "temporal pooler");
  ASSERT_LE(tim, 77*getSpeed());
}
#endif //DEBUG

} // end namespace
<|endoftext|>


<commit_before>/* IBM_PROLOG_BEGIN_TAG                                                   */
/* This is an automatically generated prolog.                             */
/*                                                                        */
/* $Source: src/usr/hwpf/hwp/mvpd_accessors/getMBvpdSpareDramData.C $     */
/*                                                                        */
/* IBM CONFIDENTIAL                                                       */
/*                                                                        */
/* COPYRIGHT International Business Machines Corp. 2013                   */
/*                                                                        */
/* p1                                                                     */
/*                                                                        */
/* Object Code Only (OCO) source materials                                */
/* Licensed Internal Code Source Materials                                */
/* IBM HostBoot Licensed Internal Code                                    */
/*                                                                        */
/* The source code for this program is not published or otherwise         */
/* divested of its trade secrets, irrespective of what has been           */
/* deposited with the U.S. Copyright Office.                              */
/*                                                                        */
/* Origin: 30                                                             */
/*                                                                        */
/* IBM_PROLOG_END_TAG                                                     */
// $Id: getMBvpdSpareDramData.C,v 1.1 2013/08/13 20:35:13 mjjones Exp $
#include  <stdint.h>

//  fapi support
#include  <fapi.H>
#include  <dimmConsts.H>
#include  <getMBvpdSpareDramData.H>

extern "C"
{
using namespace fapi;

fapi::ReturnCode getMBvpdSpareDramData(const fapi::Target &i_mba,
                                       const fapi::Target &i_dimm,
                                       uint8_t &o_data)

{
    // AM keyword layout
    const uint8_t NUM_MBAS =  2; // Two MBAs per Centaur
    const uint8_t NUM_PORTS =  2; // Two ports per MBA
    const uint8_t NUM_DIMMS = 2; // Two DIMMS per port
    const uint8_t NUM_MIRR_BYTES = 4; // Size of address mirror data

    // Struct for AM Keyword buffer
    // Contains a simple array for the address mirror data and
    // a 2D array for the spare DRAM data.
    struct MirrorData
    {
        uint8_t iv_mirrorData[NUM_MIRR_BYTES];
    };
    struct DimmSpareData
    {
        // This contains information for all ranks and is returned in o_data
        uint8_t iv_dimmSpareData;
    };
    struct PortSpareData
    {
        DimmSpareData iv_dimmSpareData[NUM_DIMMS];
    };
    struct MbaSpareData
    {
        PortSpareData iv_portSpareData[NUM_PORTS];
    };
    struct AmKeyword
    {
        MirrorData mirrorData;
        MbaSpareData iv_mbaSpareData[NUM_MBAS];
    };

    // Old VPD without the Spare Data
    const uint8_t VPD_WITHOUT_SPARE_DATA_SIZE = sizeof(MirrorData);

    // Current VPD AM keyword size
    const uint32_t AM_KEYWORD_SIZE = sizeof(AmKeyword);
    fapi::ReturnCode l_rc;
    // Centaur target
    fapi::Target l_mbTarget;
    // MBvpd AM keyword buffer
    AmKeyword * l_pAmBuffer = NULL;
    uint32_t  l_AmBufSize = sizeof(AmKeyword);

    do
    {
        // Check to see if IS-DIMM
        uint8_t l_dimmType = 0;
        l_rc = FAPI_ATTR_GET(ATTR_SPD_CUSTOM, &i_dimm, l_dimmType);
        if (l_rc)
        {
            FAPI_ERR("getMBvpdSpareDramData: "
                     "Error getting ATTR_SPD_CUSTOM");
            break;
        }
        if (fapi::ENUM_ATTR_SPD_CUSTOM_NO == l_dimmType)
        {
            //IS-DIMM, return NO_SPARE
            o_data = fapi::ENUM_ATTR_VPD_DIMM_SPARE_NO_SPARE;
            break;
        }

        // find the Centaur memory buffer from the passed MBA
        l_rc = fapiGetParentChip (i_mba,l_mbTarget);
        if (l_rc)
        {
            FAPI_ERR("getMBvpdSpareDramData: Finding the parent mb failed ");
            break;
        }

        // Read AM keyword field
        l_pAmBuffer = new AmKeyword;
        l_rc = fapiGetMBvpdField(fapi::MBVPD_RECORD_VSPD,
                                 fapi::MBVPD_KEYWORD_AM,
                                 l_mbTarget,
                                 reinterpret_cast<uint8_t *>(l_pAmBuffer),
                                 l_AmBufSize);

        if (l_rc)
        {
            FAPI_ERR("getMBvpdSpareDramData: Read of AM keyword failed");
            break;
        }

        // Check correct amount of data returned
        if (l_AmBufSize < AM_KEYWORD_SIZE)
        {

            // If Old VPD
            if (VPD_WITHOUT_SPARE_DATA_SIZE == l_AmBufSize)
            {
                // Because prior VPD AM keyword does not contain
                // spare DRAM data, the ATTR_SPD_DRAM_WIDTH
                // attribute is used to determine spare DRAM availability.
                // If x4 configuration, assume LOW_NIBBLE.
                // Otherwise, FULL_BYTE.
                uint8_t l_dramWidth = 0;
                l_rc = FAPI_ATTR_GET(ATTR_SPD_DRAM_WIDTH, &i_dimm, l_dramWidth);
                if (l_rc)
                {
                    FAPI_ERR("getMBvpdSpareDramData: "
                             "Error getting DRAM spare data");
                    break;
                }
                // If x4 configuration, low nibble.
                if (fapi::ENUM_ATTR_SPD_DRAM_WIDTH_W4 == l_dramWidth)
                {
                    o_data = fapi::ENUM_ATTR_VPD_DIMM_SPARE_LOW_NIBBLE;
                    break;
                }
                // Else, full spare.
                else
                {
                    o_data = fapi::ENUM_ATTR_VPD_DIMM_SPARE_FULL_BYTE;
                    break;
                }
            }

            else
            {
                FAPI_ERR("getMBvpdSpareDramData: "
                         "Insufficient amount of data returned:"
                         " %u < %u", l_AmBufSize, AM_KEYWORD_SIZE);
                const uint32_t & KEYWORD = fapi::MBVPD_KEYWORD_AM;
                const uint32_t & RETURNED_SIZE = l_AmBufSize;
                FAPI_SET_HWP_ERROR(l_rc,
                                   RC_MBVPD_INSUFFICIENT_VPD_RETURNED);
                break;
            }
        }

        // Return the spare DRAM availability for particular dimm
        // Find the position of the passed mba on the centuar
        uint8_t l_mba = 0;
        l_rc = FAPI_ATTR_GET(ATTR_CHIP_UNIT_POS, &i_mba, l_mba);
        if (l_rc)
        {
            FAPI_ERR("getMBvpdSpareDramData: Get MBA position failed ");
            break;
        }
        // Find the mba port this dimm is connected to
        uint8_t l_mbaPort = 0;
        l_rc = FAPI_ATTR_GET(ATTR_MBA_PORT, &i_dimm, l_mbaPort);
        if (l_rc)
        {
            FAPI_ERR("getMBvpdSpareDramData: "
                     "Error getting MBA port number");
            break;
        }
        // Find the dimm number associated with this dimm
        uint8_t l_dimm = 0;
        l_rc = FAPI_ATTR_GET(ATTR_MBA_DIMM, &i_dimm, l_dimm);
        if (l_rc)
        {
            FAPI_ERR("getMBvpdSpareDramData: "
                     "Error getting dimm number");
            break;
        }

        o_data = l_pAmBuffer->iv_mbaSpareData[l_mba].\
                 iv_portSpareData[l_mbaPort].\
                 iv_dimmSpareData[l_dimm].iv_dimmSpareData;

    }while(0);

    delete l_pAmBuffer;
    l_pAmBuffer = NULL;
    return l_rc;
}

}  // extern "C"
<commit_msg>Temporary fix for C-DIMM VPD which does not contain AM Keyword<commit_after>/* IBM_PROLOG_BEGIN_TAG                                                   */
/* This is an automatically generated prolog.                             */
/*                                                                        */
/* $Source: src/usr/hwpf/hwp/mvpd_accessors/getMBvpdSpareDramData.C $     */
/*                                                                        */
/* IBM CONFIDENTIAL                                                       */
/*                                                                        */
/* COPYRIGHT International Business Machines Corp. 2013                   */
/*                                                                        */
/* p1                                                                     */
/*                                                                        */
/* Object Code Only (OCO) source materials                                */
/* Licensed Internal Code Source Materials                                */
/* IBM HostBoot Licensed Internal Code                                    */
/*                                                                        */
/* The source code for this program is not published or otherwise         */
/* divested of its trade secrets, irrespective of what has been           */
/* deposited with the U.S. Copyright Office.                              */
/*                                                                        */
/* Origin: 30                                                             */
/*                                                                        */
/* IBM_PROLOG_END_TAG                                                     */
// $Id: getMBvpdSpareDramData.C,v 1.3 2013/09/12 14:12:39 mjjones Exp $
#include  <stdint.h>

//  fapi support
#include  <fapi.H>
#include  <dimmConsts.H>
#include  <getMBvpdSpareDramData.H>

extern "C"
{
using namespace fapi;

fapi::ReturnCode getMBvpdSpareDramData(const fapi::Target &i_mba,
                                       const fapi::Target &i_dimm,
                                       uint8_t &o_data)

{
    // AM keyword layout
    const uint8_t NUM_MBAS =  2; // Two MBAs per Centaur
    const uint8_t NUM_PORTS =  2; // Two ports per MBA
    const uint8_t NUM_DIMMS = 2; // Two DIMMS per port
    const uint8_t NUM_MIRR_BYTES = 4; // Size of address mirror data

    // Struct for AM Keyword buffer
    // Contains a simple array for the address mirror data and
    // a 2D array for the spare DRAM data.
    struct MirrorData
    {
        uint8_t iv_mirrorData[NUM_MIRR_BYTES];
    };
    struct DimmSpareData
    {
        // This contains information for all ranks and is returned in o_data
        uint8_t iv_dimmSpareData;
    };
    struct PortSpareData
    {
        DimmSpareData iv_dimmSpareData[NUM_DIMMS];
    };
    struct MbaSpareData
    {
        PortSpareData iv_portSpareData[NUM_PORTS];
    };
    struct AmKeyword
    {
        MirrorData mirrorData;
        MbaSpareData iv_mbaSpareData[NUM_MBAS];
    };

    // Current VPD AM keyword size
    const uint32_t AM_KEYWORD_SIZE = sizeof(AmKeyword);
    fapi::ReturnCode l_rc;
    // Centaur target
    fapi::Target l_mbTarget;
    // MBvpd AM keyword buffer
    AmKeyword * l_pAmBuffer = NULL;
    uint32_t  l_AmBufSize = sizeof(AmKeyword);

    // For old VPD without spare DRAM data
    // Store data for all 4 ranks of this DIMM
    const uint8_t VPD_WITHOUT_SPARE_LOW_NIBBLE = 0x55;
    const uint8_t VPD_WITHOUT_SPARE_FULL_BYTE = 0xFF;

    do
    {
        // Check to see if IS-DIMM
        uint8_t l_dimmType = 0;
        l_rc = FAPI_ATTR_GET(ATTR_SPD_CUSTOM, &i_dimm, l_dimmType);
        if (l_rc)
        {
            FAPI_ERR("getMBvpdSpareDramData: "
                     "Error getting ATTR_SPD_CUSTOM");
            break;
        }
        if (fapi::ENUM_ATTR_SPD_CUSTOM_NO == l_dimmType)
        {
            //IS-DIMM, return NO_SPARE
            o_data = fapi::ENUM_ATTR_VPD_DIMM_SPARE_NO_SPARE;
            break;
        }

        // find the Centaur memory buffer from the passed MBA
        l_rc = fapiGetParentChip (i_mba,l_mbTarget);
        if (l_rc)
        {
            FAPI_ERR("getMBvpdSpareDramData: Finding the parent mb failed ");
            break;
        }

        // Read AM keyword field
        l_pAmBuffer = new AmKeyword;
        l_rc = fapiGetMBvpdField(fapi::MBVPD_RECORD_VSPD,
                                 fapi::MBVPD_KEYWORD_AM,
                                 l_mbTarget,
                                 reinterpret_cast<uint8_t *>(l_pAmBuffer),
                                 l_AmBufSize);

        // Check for error or incorrect amount of data returned
        if (l_rc || (l_AmBufSize < AM_KEYWORD_SIZE))
        {
            // This handles two scenarios:
            // 1. fapiGetMBvpdField has returned an error because
            //    the AM keyword is not present in this DIMM's
            //    VPD.
            // 2. This DIMM does have the AM Keyword, however it
            //    is in an old version of VPD and does not contain
            //    any spare DRAM information.
            // In both cases, the ATTR_SPD_DRAM_WIDTH
            // attribute is used to determine spare DRAM availability.
            // If x4 configuration, assume LOW_NIBBLE.
            // Otherwise, FULL_BYTE.
            // TODO RTC 84278: Undo the workaround for scenario 1 once the
            // C-DIMM VPD is updated on all DIMMs to the current version.
            uint8_t l_dramWidth = 0;
            l_rc = FAPI_ATTR_GET(ATTR_SPD_DRAM_WIDTH, &i_dimm, l_dramWidth);
            if (l_rc)
            {
                FAPI_ERR("getMBvpdSpareDramData: "
                         "Error getting DRAM spare data");
                break;
            }
            // If x4 configuration, low nibble.
            if (fapi::ENUM_ATTR_SPD_DRAM_WIDTH_W4 == l_dramWidth)
            {
                o_data = VPD_WITHOUT_SPARE_LOW_NIBBLE;
                break;
            }
            // Else, full spare.
            else
            {
                o_data = VPD_WITHOUT_SPARE_FULL_BYTE;
                break;
            }
        }

        // Return the spare DRAM availability for particular dimm
        // Find the position of the passed mba on the centuar
        uint8_t l_mba = 0;
        l_rc = FAPI_ATTR_GET(ATTR_CHIP_UNIT_POS, &i_mba, l_mba);
        if (l_rc)
        {
            FAPI_ERR("getMBvpdSpareDramData: Get MBA position failed ");
            break;
        }
        // Find the mba port this dimm is connected to
        uint8_t l_mbaPort = 0;
        l_rc = FAPI_ATTR_GET(ATTR_MBA_PORT, &i_dimm, l_mbaPort);
        if (l_rc)
        {
            FAPI_ERR("getMBvpdSpareDramData: "
                     "Error getting MBA port number");
            break;
        }
        // Find the dimm number associated with this dimm
        uint8_t l_dimm = 0;
        l_rc = FAPI_ATTR_GET(ATTR_MBA_DIMM, &i_dimm, l_dimm);
        if (l_rc)
        {
            FAPI_ERR("getMBvpdSpareDramData: "
                     "Error getting dimm number");
            break;
        }

        o_data = l_pAmBuffer->iv_mbaSpareData[l_mba].\
                 iv_portSpareData[l_mbaPort].\
                 iv_dimmSpareData[l_dimm].iv_dimmSpareData;

    }while(0);

    delete l_pAmBuffer;
    l_pAmBuffer = NULL;
    return l_rc;
}

}  // extern "C"
<|endoftext|>


<commit_before>/* Tariq ahmed khan - Daffodil */

#include <bits/stdc++.h>

/*####### Template Starts Here #######*/

#define pi 2*acos(0.0)
#define scan(x) scanf("%d",&x)
#define sf scanf
#define pf printf
#define pb push_back
#define memoclr(n,x) memset(n,x,sizeof(n) )
#define INF 1 << 30
#define foo(i,j,k) for(int (x)=(i);(x)<(j);(x)+=(k))
#define ffoo(i,j,k) for(int (x)=(i);(x)<=(j);(x)+=(k))

typedef long long LLI;
typedef unsigned long long LLU;

template<class T> T gcd(T x, T y){if (y==0) return x; return gcd(y,x%y);}
template<class T> T lcm(T x, T y){return ((x/gcd(x,y))*y);}
template<class T> T maxt(T x, T y){if (x > y) return x; else return y;}
template<class T> T mint(T x, T y){if (x < y) return x; else return y;}
template<class T> T power(T x, T y){T res=1,a = x; while(y){if(y&1){res*=a;}a*=a;y>>=1;}return res;}
template<class T> T bigmod(T x,T y,T mod){T res=1,a=x; while(y){if(y&1){res=(res*a)%mod;}a=((a%mod)*(a%mod))%mod;y>>=1;}return res;}

int dir[8][2]={{-1,0}
              ,{1,0}
              ,{0,-1}
              ,{0,1}
              ,{-1,-1}
              ,{-1,1}
              ,{1,-1}
              ,{1,1}};

using namespace std;

/*####### Template Ends Here #######*/

struct Card{
    char typ;
    int no;
};

struct Player{
    Card player_card[8];
};

struct Round{
    Card round_card[4];
    int Winner;
};

class Game{
    Player man[4];
    Round rnd[8];
    char Trump;

    public:

        void set_trump(char);
        void set_player_card(int, char*);
        void set_round_card(int, char*);
        void set_round_winner(int, char*);

        void card_draw_debug();
        void round_debug();
};

void Game::set_player_card(int P, char C[]){
    int itr = 0;
    for(int i=0; i<16; i+=2){                   // Total 8 Card for each player P
        man[P].player_card[itr].typ = C[i];
        man[P].player_card[itr++].no = C[i+1] - '0';
    }
}

void Game::set_round_card(int R, char C[]){
    int itr = 0;
    for(int i=0; i<8; i+=2){                    // Each Round R has total 4 cards from ecah player
        rnd[R].round_card[itr].typ = C[i];
        rnd[R].round_card[itr++].no = C[i+1] - '0';
    }
}

void Game::set_trump(char C){
    Trump = C;
}

void Game::set_round_winner(int R, char C[]){
    rnd[R].Winner = C[0] - '0';
}

void Game::card_draw_debug(){
    for(int i=0; i<4; i++){
        cout << "Player : " << i+1 << "\n";
        for(int j=0; j<8; j++){
            cout << "\t Card " << j+1 << " : " << man[i].player_card[j].typ << " - " << man[i].player_card[j].no << "\n";
        }
    }
}

void Game::round_debug(){
    for(int i=0; i<8; i++){
        cout << "Round : " << i+1 << "\n";
        for(int j=0; j<4; j++){
            cout << "\t Player " << j+1 << " Throws : " << rnd[i].round_card[j].typ << " - " << rnd[i].round_card[j].no << "\n";
        }
        cout << "\n\t This Round Winner is -> Player : " << rnd[i].Winner+1 << "\n";
    }
}

int main() {
    #ifdef partho222
        freopen("input.txt","r",stdin);
        //freopen("output.txt","w",stdout);
    #endif

    Game g;

    int n;
    char str[30];
    while(cin >> n >> str){
        int l = strlen(str);

        //cout << n << " " << str << endl;
        //cout << l << endl;

        if( l == 8 ){
            g.set_round_card(n, str);
        }
        else if(l == 16){
            g.set_player_card(n, str);
        }
        else if( l == 1){
            g.set_round_winner(n, str);
        }
    }

    g.card_draw_debug();
    g.round_debug();

    return 0;
}
<commit_msg>modify source.cpp in 29-game<commit_after>/* Tariq ahmed khan - Daffodil */

#include <bits/stdc++.h>

/*####### Template Starts Here #######*/

#define pi 2*acos(0.0)
#define scan(x) scanf("%d",&x)
#define sf scanf
#define pf printf
#define pb push_back
#define memoclr(n,x) memset(n,x,sizeof(n) )
#define INF 1 << 30
#define foo(i,j,k) for(int (x)=(i);(x)<(j);(x)+=(k))
#define ffoo(i,j,k) for(int (x)=(i);(x)<=(j);(x)+=(k))

typedef long long LLI;
typedef unsigned long long LLU;

template<class T> T gcd(T x, T y){if (y==0) return x; return gcd(y,x%y);}
template<class T> T lcm(T x, T y){return ((x/gcd(x,y))*y);}
template<class T> T maxt(T x, T y){if (x > y) return x; else return y;}
template<class T> T mint(T x, T y){if (x < y) return x; else return y;}
template<class T> T power(T x, T y){T res=1,a = x; while(y){if(y&1){res*=a;}a*=a;y>>=1;}return res;}
template<class T> T bigmod(T x,T y,T mod){T res=1,a=x; while(y){if(y&1){res=(res*a)%mod;}a=((a%mod)*(a%mod))%mod;y>>=1;}return res;}

using namespace std;

/*####### Template Ends Here #######*/

struct Card{
    char typ;
    int no;
};

struct Player{
    Card player_card[8];
};

struct Round{
    Card round_card[4];
    int Winner;
};

class Game{
    Player man[4];
    Round rnd[8];
    char Trump;

    public:

        void set_trump(char);
        void set_player_card(int, char*);
        void set_round_card(int, char*);
        void set_round_winner(int, char*);

        void card_draw_debug();
        void round_debug();
};

void Game::set_player_card(int P, char C[]){
    int itr = 0;
    for(int i=0; i<16; i+=2){                   // Total 8 Card for each player P
        man[P].player_card[itr].typ = C[i];
        man[P].player_card[itr++].no = C[i+1] - '0';
    }
}

void Game::set_round_card(int R, char C[]){
    int itr = 0;
    for(int i=0; i<8; i+=2){                    // Each Round R has total 4 cards from ecah player
        rnd[R].round_card[itr].typ = C[i];
        rnd[R].round_card[itr++].no = C[i+1] - '0';
    }
}

void Game::set_trump(char C){
    Trump = C;
}

void Game::set_round_winner(int R, char C[]){
    rnd[R].Winner = C[0] - '0';
}

void Game::card_draw_debug(){
    for(int i=0; i<4; i++){
        cout << "Player : " << i+1 << "\n";
        for(int j=0; j<8; j++){
            cout << "\t Card " << j+1 << " : " << man[i].player_card[j].typ << " - " << man[i].player_card[j].no << "\n";
        }
    }
}

void Game::round_debug(){
    for(int i=0; i<8; i++){
        cout << "Round : " << i+1 << "\n";
        for(int j=0; j<4; j++){
            cout << "\t Player " << j+1 << " Throws : " << rnd[i].round_card[j].typ << " - " << rnd[i].round_card[j].no << "\n";
        }
        cout << "\n\t This Round Winner is -> Player : " << rnd[i].Winner+1 << "\n";
    }
}

int main() {

        //freopen("input.txt","r",stdin);       // uncomment this to take input from "input.txt"
        //freopen("output.txt","w",stdout);     // uncomment this to write output to "output.txt"

    Game g;

    int n;
    char str[30];
    while(cin >> n >> str){
        int l = strlen(str);

        //cout << n << " " << str << endl;
        //cout << l << endl;

        if( l == 8 ){
            g.set_round_card(n, str);
        }
        else if(l == 16){
            g.set_player_card(n, str);
        }
        else if( l == 1){
            g.set_round_winner(n, str);
        }
    }

    g.card_draw_debug();
    g.round_debug();

    return 0;
}
<|endoftext|>