<commit_before>/*************************************************************************
 *
 *  $RCSfile: MDatabaseMetaDataHelper.hxx,v $
 *
 *  $Revision: 1.5 $
 *
 *  last change: $Author: hjs $ $Date: 2004-06-25 18:31:40 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  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., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#ifndef _CONNECTIVITY_MAB_DATABASEMETADATAHELPER_HXX_
#define _CONNECTIVITY_MAB_DATABASEMETADATAHELPER_HXX_

 /*
#ifndef _COM_SUN_STAR_SDBC_XRESULTSET_HPP_
#include <com/sun/star/sdbc/XResultSet.hpp>
#endif
#ifndef _COM_SUN_STAR_SDBC_XROW_HPP_
#include <com/sun/star/sdbc/XRow.hpp>
#endif
#ifndef _COM_SUN_STAR_SDBC_XRESULTSETMETADATASUPPLIER_HPP_
#include <com/sun/star/sdbc/XResultSetMetaDataSupplier.hpp>
#endif
#ifndef _COM_SUN_STAR_SDBC_XCLOSEABLE_HPP_
#include <com/sun/star/sdbc/XCloseable.hpp>
#endif
#ifndef _COM_SUN_STAR_SDBC_XCOLUMNLOCATE_HPP_
#include <com/sun/star/sdbc/XColumnLocate.hpp>
#endif
#ifndef _COM_SUN_STAR_UTIL_XCANCELLABLE_HPP_
#include <com/sun/star/util/XCancellable.hpp>
#endif
#ifndef _COM_SUN_STAR_SDBC_XWARNINGSSUPPLIER_HPP_
#include <com/sun/star/sdbc/XWarningsSupplier.hpp>
#endif
#ifndef _COM_SUN_STAR_SDBC_XRESULTSETUPDATE_HPP_
#include <com/sun/star/sdbc/XResultSetUpdate.hpp>
#endif
#ifndef _COM_SUN_STAR_SDBC_XROWUPDATE_HPP_
#include <com/sun/star/sdbc/XRowUpdate.hpp>
#endif
#ifndef _CPPUHELPER_COMPBASE7_HXX_
#include <cppuhelper/compbase7.hxx>
#endif
*/
#ifndef _COMPHELPER_PROPERTY_ARRAY_HELPER_HXX_
#include <comphelper/proparrhlp.hxx>
#endif
 /*
#ifndef _CONNECTIVITY_FILE_ASTATEMENT_HXX_
#include "file/FStatement.hxx"
#endif
#ifndef _CONNECTIVITY_COMMONTOOLS_HXX_
#include "connectivity/CommonTools.hxx"
#endif
*/
#ifndef _COMPHELPER_PROPERTYCONTAINER_HXX_
#include <comphelper/propertycontainer.hxx>
#endif

#ifndef _CONNECTIVITY_FDATABASEMETADATARESULTSET_HXX_
#include "FDatabaseMetaDataResultSet.hxx"
#endif

#ifndef _CONNECTIVITY_MAB_CONNECTION_HXX_
#include <MConnection.hxx>
#endif
#ifndef _COM_SUN_STAR_UNO_SEQUENCE_HXX_
#include <com/sun/star/uno/Sequence.hxx>
#endif

namespace connectivity
{
    namespace mozab
    {
        class MDatabaseMetaDataHelper
        {
        public:
            MDatabaseMetaDataHelper( );
            ~MDatabaseMetaDataHelper();

            //PROXIED_FUNCTION
            sal_Bool getTableStrings( OConnection*                        _pCon,
                                      ::std::vector< ::rtl::OUString >&   _rStrings,
                                      ::std::vector< ::rtl::OUString >&   _rTypes);

            sal_Bool getTables( OConnection* _pCon,
                                const ::rtl::OUString& tableNamePattern,
                                const ::com::sun::star::uno::Sequence< ::rtl::OUString >& types,
                                ODatabaseMetaDataResultSet::ORows& _rRows);

            const ::rtl::OUString& getErrorString() { return m_aErrorString; }

            sal_Bool   testLDAPConnection( OConnection* _pCon );
            sal_Bool   NewAddressBook( OConnection* _pCon,const ::rtl::OUString & aTableName);

        private:
            sal_Bool                            m_bProfileExists ;
            ::std::vector< ::rtl::OUString >    m_aTableNames;
            ::std::vector< ::rtl::OUString >    m_aTableTypes;
            ::rtl::OUString                     m_aErrorString;
            void setAbSpecificError( OConnection* _pCon, sal_Bool bGivenURI );
        };
    }

}
#endif // _CONNECTIVITY_MAB_DATABASEMETADATAHELPER_HXX_

<commit_msg>INTEGRATION: CWS mozab05 (1.5.46); FILE MERGED 2005/01/27 11:30:11 windly 1.5.46.2: #i41444# mozab crash on solaris sparc 2005/01/17 05:30:54 windly 1.5.46.1: #i20088# Detect Mozilla Thunderbird Address Book: patchs for connectivity<commit_after>/*************************************************************************
 *
 *  $RCSfile: MDatabaseMetaDataHelper.hxx,v $
 *
 *  $Revision: 1.6 $
 *
 *  last change: $Author: vg $ $Date: 2005-02-21 12:30:29 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  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., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#ifndef _CONNECTIVITY_MAB_DATABASEMETADATAHELPER_HXX_
#define _CONNECTIVITY_MAB_DATABASEMETADATAHELPER_HXX_

 /*
#ifndef _COM_SUN_STAR_SDBC_XRESULTSET_HPP_
#include <com/sun/star/sdbc/XResultSet.hpp>
#endif
#ifndef _COM_SUN_STAR_SDBC_XROW_HPP_
#include <com/sun/star/sdbc/XRow.hpp>
#endif
#ifndef _COM_SUN_STAR_SDBC_XRESULTSETMETADATASUPPLIER_HPP_
#include <com/sun/star/sdbc/XResultSetMetaDataSupplier.hpp>
#endif
#ifndef _COM_SUN_STAR_SDBC_XCLOSEABLE_HPP_
#include <com/sun/star/sdbc/XCloseable.hpp>
#endif
#ifndef _COM_SUN_STAR_SDBC_XCOLUMNLOCATE_HPP_
#include <com/sun/star/sdbc/XColumnLocate.hpp>
#endif
#ifndef _COM_SUN_STAR_UTIL_XCANCELLABLE_HPP_
#include <com/sun/star/util/XCancellable.hpp>
#endif
#ifndef _COM_SUN_STAR_SDBC_XWARNINGSSUPPLIER_HPP_
#include <com/sun/star/sdbc/XWarningsSupplier.hpp>
#endif
#ifndef _COM_SUN_STAR_SDBC_XRESULTSETUPDATE_HPP_
#include <com/sun/star/sdbc/XResultSetUpdate.hpp>
#endif
#ifndef _COM_SUN_STAR_SDBC_XROWUPDATE_HPP_
#include <com/sun/star/sdbc/XRowUpdate.hpp>
#endif
#ifndef _CPPUHELPER_COMPBASE7_HXX_
#include <cppuhelper/compbase7.hxx>
#endif
*/
#ifndef _COMPHELPER_PROPERTY_ARRAY_HELPER_HXX_
#include <comphelper/proparrhlp.hxx>
#endif
 /*
#ifndef _CONNECTIVITY_FILE_ASTATEMENT_HXX_
#include "file/FStatement.hxx"
#endif
#ifndef _CONNECTIVITY_COMMONTOOLS_HXX_
#include "connectivity/CommonTools.hxx"
#endif
*/
#ifndef _COMPHELPER_PROPERTYCONTAINER_HXX_
#include <comphelper/propertycontainer.hxx>
#endif

#ifndef _CONNECTIVITY_FDATABASEMETADATARESULTSET_HXX_
#include "FDatabaseMetaDataResultSet.hxx"
#endif

#ifndef _CONNECTIVITY_MAB_CONNECTION_HXX_
#include <MConnection.hxx>
#endif
#ifndef _COM_SUN_STAR_UNO_SEQUENCE_HXX_
#include <com/sun/star/uno/Sequence.hxx>
#endif
#ifndef _COM_SUN_STAR_MOZILLA_MOZILLPRODUCTTYPE_HPP_
#include <com/sun/star/mozilla/MozillaProductType.hpp>
#endif

namespace connectivity
{
    namespace mozab
    {
        class MDatabaseMetaDataHelper
        {
        public:
            MDatabaseMetaDataHelper( );
            ~MDatabaseMetaDataHelper();

            //
            sal_Bool getTableStrings( OConnection*                        _pCon,
                                      ::std::vector< ::rtl::OUString >&   _rStrings,
                                      ::std::vector< ::rtl::OUString >&   _rTypes);

            sal_Bool getTables( OConnection* _pCon,
                                const ::rtl::OUString& tableNamePattern,
                                const ::com::sun::star::uno::Sequence< ::rtl::OUString >& types,
                                ODatabaseMetaDataResultSet::ORows& _rRows);

            const ::rtl::OUString& getErrorString() { return m_aErrorString; }

            sal_Bool   testLDAPConnection( OConnection* _pCon );
            sal_Bool   NewAddressBook( OConnection* _pCon,const ::rtl::OUString & aTableName);

        private:
            sal_Bool                            m_bProfileExists ;
            ::std::vector< ::rtl::OUString >    m_aTableNames;
            ::std::vector< ::rtl::OUString >    m_aTableTypes;
            ::rtl::OUString                     m_aErrorString;
            void setAbSpecificError( OConnection* _pCon, sal_Bool bGivenURI );
            ::com::sun::star::mozilla::MozillaProductType m_ProductType;
            ::rtl::OUString                               m_ProfileName;
        };
    }

}
#endif // _CONNECTIVITY_MAB_DATABASEMETADATAHELPER_HXX_

<|endoftext|>


<commit_before>#include "output.hpp"
#include <cmath>
#include <cstdint>
#include <vector>
#include <ctime>
#include <cstdio>
#include "math/vec.hpp"
#include "stb_image_write.h"
#include "util.hpp"
#include "./srgb.hpp"

namespace yks {

static std::vector<uint8_t> encode_srgb(const std::vector<yks::vec3> fdata) {
	std::vector<uint8_t> bdata(fdata.size() * 3);
	for (size_t i = 0; i < fdata.size(); ++i) {
		bdata[i*3 + 0] = byte_from_linear(clamp(0.0f, fdata[i][0], 1.0f));
		bdata[i*3 + 1] = byte_from_linear(clamp(0.0f, fdata[i][1], 1.0f));
		bdata[i*3 + 2] = byte_from_linear(clamp(0.0f, fdata[i][2], 1.0f));
	}
	return bdata;
}

void save_srgb_image(const std::vector<yks::vec3>& pixels, int width, int height) {
	std::vector<uint8_t> image_byte_data = encode_srgb(pixels);

	std::time_t t = std::time(nullptr);
	std::tm* tm = std::localtime(&t);

	char buffer[64];
	std::sprintf(buffer, "%04d-%02d-%02d_%02d-%02d_output.png", tm->tm_year + 1900, tm->tm_mon + 1, tm->tm_mday, tm->tm_hour, tm->tm_min);

	stbi_write_png(buffer, width, height, 3, image_byte_data.data(), 0);
}

}
<commit_msg>Add second to the file timestamp too.<commit_after>#include "output.hpp"
#include <cmath>
#include <cstdint>
#include <vector>
#include <ctime>
#include <cstdio>
#include "math/vec.hpp"
#include "stb_image_write.h"
#include "util.hpp"
#include "./srgb.hpp"

namespace yks {

static std::vector<uint8_t> encode_srgb(const std::vector<yks::vec3> fdata) {
	std::vector<uint8_t> bdata(fdata.size() * 3);
	for (size_t i = 0; i < fdata.size(); ++i) {
		bdata[i*3 + 0] = byte_from_linear(clamp(0.0f, fdata[i][0], 1.0f));
		bdata[i*3 + 1] = byte_from_linear(clamp(0.0f, fdata[i][1], 1.0f));
		bdata[i*3 + 2] = byte_from_linear(clamp(0.0f, fdata[i][2], 1.0f));
	}
	return bdata;
}

void save_srgb_image(const std::vector<yks::vec3>& pixels, int width, int height) {
	std::vector<uint8_t> image_byte_data = encode_srgb(pixels);

	std::time_t t = std::time(nullptr);
	std::tm* tm = std::localtime(&t);

	char buffer[64];
	std::sprintf(buffer, "%04d-%02d-%02d_%02d-%02d-%02d_output.png", tm->tm_year + 1900, tm->tm_mon + 1, tm->tm_mday, tm->tm_hour, tm->tm_min, tm->tm_sec);

	stbi_write_png(buffer, width, height, 3, image_byte_data.data(), 0);
}

}
<|endoftext|>


<commit_before>

#include "util.hpp"

#include "DiscoveryVisitor.hpp"
#include "Export.hpp"

#include <clang/Frontend/FrontendPluginRegistry.h>

using namespace autobind;

class AutobindPluginAction: public clang::PluginASTAction
{
protected:
	clang::ASTConsumer *CreateASTConsumer(clang::CompilerInstance &ci,
	                                      llvm::StringRef path)
	{
		return newASTConsumer([path, &ci](clang::ASTContext &ctx) {
			ModuleManager mgr;
			discoverTranslationUnit(mgr, *ctx.getTranslationUnitDecl(), ci);

			for(const auto &item : mgr.moduleStream())
			{
				mgr.module(item.first).setSourceTUPath(path);
			}

			mgr.codegen(std::cout);
		});
	}

	bool ParseArgs(const clang::CompilerInstance &ci,
	               const std::vector<std::string> &args)
	{
		return true;
	}

};

static clang::FrontendPluginRegistry::Add<AutobindPluginAction> registration("autobind",
                                                                             "automatically generate "
                                                                             "Python bindings");

<commit_msg>Make the plugin, which can now be loaded, somewhat functional.<commit_after>
#include <string>
#include <fstream>

#include "util.hpp"

#include "DiscoveryVisitor.hpp"
#include "Export.hpp"

#include <clang/Frontend/FrontendPluginRegistry.h>

using namespace autobind;

class AutobindPluginAction: public clang::PluginASTAction
{
protected:
	clang::ASTConsumer *CreateASTConsumer(clang::CompilerInstance &ci,
	                                      llvm::StringRef path)
	{
// 		return nullptr;
		std::string pathString = path;
		return newASTConsumer([pathString, &ci](clang::ASTContext &ctx) {
			ModuleManager mgr;
			discoverTranslationUnit(mgr, *ctx.getTranslationUnitDecl(), ci);

			for(const auto &item : mgr.moduleStream())
			{
				mgr.module(item.first).setSourceTUPath(pathString);
			}

			std::ofstream outStream("/tmp/output.cpp");
			mgr.codegen(outStream);
// 			mgr.codegen(std::cout);
		});
	}

	bool ParseArgs(const clang::CompilerInstance &ci,
	               const std::vector<std::string> &args)
	{
		return true;
	}

};

static clang::FrontendPluginRegistry::Add<AutobindPluginAction> registration("autobind",
                                                                             "automatically generate "
                                                                             "Python bindings");

<|endoftext|>


<commit_before>//
// This file is part of the Marble Virtual Globe.
//
// This program is free software licensed under the GNU LGPL. You can
// find a copy of this license in LICENSE.txt in the top directory of
// the source code.
//
// Copyright 2006-2007 Torsten Rahn <tackat@kde.org>
// Copyright 2007      Inge Wallin  <ingwa@kde.org>
//

#include <QtGui/QApplication>
#include <QtCore/QFile>
#include <QtCore/QDir>
#include <QtCore/QLocale>
#include <QtCore/QSettings>
#include <QtCore/QTranslator>
#include <QtCore/QProcessEnvironment>

#include "QtMainWindow.h"

#include "MarbleDirs.h"
#include "MarbleDebug.h"
#include "MarbleTest.h"
#include "MarbleLocale.h"

#ifdef STATIC_BUILD
 #include <QtCore/QtPlugin>
 Q_IMPORT_PLUGIN(qjpeg)
 Q_IMPORT_PLUGIN(qsvg)
#endif

#ifdef Q_OS_MACX
//for getting app bundle path
#include <ApplicationServices/ApplicationServices.h>
#endif

using namespace Marble;

int main(int argc, char *argv[])
{
    // The GraphicsSystem needs to be set before the instantiation of the
    // QApplication. Therefore we need to parse the current setting
    // in this unusual place :-/
    QSettings * graphicsSettings = new QSettings("kde.org", "Marble Desktop Globe");
    QString graphicsString = graphicsSettings->value("View/graphicsSystem", "raster").toString();
    delete graphicsSettings;
    QApplication::setGraphicsSystem( graphicsString );

    QApplication app(argc, argv);
    // Widget translation

#ifdef Q_WS_MAEMO_5
    // Work around http://bugreports.qt.nokia.com/browse/QTBUG-1313
    QProcessEnvironment env = QProcessEnvironment::systemEnvironment();
    QString lang( "C" );
    QStringList const locales = QStringList() << "LC_ALL" << "LC_MESSAGES" << "LANG" << "LANGUAGE";
    foreach( const QString &locale, locales ) {
        if ( env.contains( locale ) && !env.value( locale ).isEmpty() ) {
            lang = env.value( locale, "C" );
            break;
        }
    }

    lang = lang.section( '_', 0, 0 );
#else
    QString      lang = QLocale::system().name().section('_', 0, 0);
#endif
    QTranslator  translator;
    translator.load( "marble-" + lang, MarbleDirs::path(QString("lang") ) );
    app.installTranslator(&translator);

    // For non static builds on mac and win
    // we need to be sure we can find the qt image
    // plugins. In mac be sure to look in the
    // application bundle...

#ifdef Q_WS_WIN
    QApplication::addLibraryPath( QApplication::applicationDirPath()
        + QDir::separator() + "plugins" );
#endif
#ifdef Q_OS_MACX
    QApplication::instance()->setAttribute(Qt::AA_DontShowIconsInMenus);
    qDebug("Adding qt image plugins to plugin search path...");
    CFURLRef myBundleRef = CFBundleCopyBundleURL(CFBundleGetMainBundle());
    CFStringRef myMacPath = CFURLCopyFileSystemPath(myBundleRef, kCFURLPOSIXPathStyle);
    const char *mypPathPtr = CFStringGetCStringPtr(myMacPath,CFStringGetSystemEncoding());
    CFRelease(myBundleRef);
    CFRelease(myMacPath);
    QString myPath(mypPathPtr);
    // if we are not in a bundle assume that the app is built
    // as a non bundle app and that image plugins will be
    // in system Qt frameworks. If the app is a bundle
    // lets try to set the qt plugin search path...
    if (myPath.contains(".app"))
    {
      myPath += "/Contents/plugins";
      QApplication::addLibraryPath( myPath );
      qDebug( "Added %s to plugin search path", qPrintable( myPath ) );
    }
#endif

    QString marbleDataPath;
    int dataPathIndex=0;
    MarbleGlobal::Profiles profiles = MarbleGlobal::detectProfiles();

    QStringList args = QApplication::arguments();

    for ( int i = 1; i < args.count(); ++i ) {
        const QString arg = args.at(i);

        if ( arg == "--debug-info" )
        {
            MarbleDebug::enable = true;
        }
        else if ( arg.startsWith( "--marbledatapath=", Qt::CaseInsensitive ) )
        {
            marbleDataPath = args.at(i).mid(17);
        }
        else if ( arg.compare( "--marbledatapath", Qt::CaseInsensitive ) == 0 ) {
            dataPathIndex = i + 1;
            marbleDataPath = args.value( dataPathIndex );
            ++i;
        }
        else if ( arg == "--smallscreen" ) {
            profiles |= MarbleGlobal::SmallScreen;
        }
        else if ( arg == "--nosmallscreen" ) {
            profiles &= ~MarbleGlobal::SmallScreen;
        }
        else if ( arg == "--highresolution" ) {
            profiles |= MarbleGlobal::HighResolution;
        }
        else if ( arg == "--nohighresolution" ) {
            profiles &= ~MarbleGlobal::HighResolution;
        }
    }
    MarbleGlobal::getInstance()->setProfiles( profiles );

    QLocale::MeasurementSystem const measurement = QLocale::system().measurementSystem();
    Marble::MeasureSystem const marbleMeasurement = measurement == QLocale::ImperialSystem ? Marble::Imperial : Marble::Metric;
    MarbleGlobal::getInstance()->locale()->setMeasureSystem( marbleMeasurement );

    MainWindow *window = new MainWindow( marbleDataPath );
    window->setAttribute( Qt::WA_DeleteOnClose, true );

    MarbleTest *marbleTest = new MarbleTest( window->marbleWidget() );

//    window->marbleWidget()->rotateTo( 0, 0, -90 );
//    window->show();

    for ( int i = 1; i < args.count(); ++i ) {
        const QString arg = args.at(i);
        if ( arg == "--timedemo" )
        {
            window->resize(900, 640);
            marbleTest->timeDemo();
            return 0;
        }
        else if( arg == "--gpsdemo" ) {
            window->resize( 900, 640 );
            marbleTest->gpsDemo();
            return 0;
        }
        else if( arg == "--fps" ) {
            window->marbleControl()->marbleWidget()->setShowFrameRate( true );
        }
        else if( arg == "--enableCurrentLocation" )
        {
            window->marbleControl()->setCurrentLocationTabShown(true);
        }
        else if( arg == "--enableFileView" )
        {
            window->marbleControl()->setFileViewTabShown(true);
        }
        else if ( arg == "--tile-id" )
        {
	    window->marbleControl()->marbleWidget()->setShowTileId(true);
        }
        else if ( i != dataPathIndex && QFile::exists( arg ) )
            ( window->marbleControl() )->addGeoDataFile( arg );
    }

    delete marbleTest;

    return app.exec();
}
<commit_msg>Implement -h/--help.<commit_after>//
// This file is part of the Marble Virtual Globe.
//
// This program is free software licensed under the GNU LGPL. You can
// find a copy of this license in LICENSE.txt in the top directory of
// the source code.
//
// Copyright 2006-2007 Torsten Rahn <tackat@kde.org>
// Copyright 2007      Inge Wallin  <ingwa@kde.org>
//

#include <QtGui/QApplication>
#include <QtCore/QFile>
#include <QtCore/QDir>
#include <QtCore/QLocale>
#include <QtCore/QSettings>
#include <QtCore/QTranslator>
#include <QtCore/QProcessEnvironment>

#include "QtMainWindow.h"

#include "MarbleDirs.h"
#include "MarbleDebug.h"
#include "MarbleTest.h"
#include "MarbleLocale.h"

#ifdef STATIC_BUILD
 #include <QtCore/QtPlugin>
 Q_IMPORT_PLUGIN(qjpeg)
 Q_IMPORT_PLUGIN(qsvg)
#endif

#ifdef Q_OS_MACX
//for getting app bundle path
#include <ApplicationServices/ApplicationServices.h>
#endif

using namespace Marble;

int main(int argc, char *argv[])
{
    // The GraphicsSystem needs to be set before the instantiation of the
    // QApplication. Therefore we need to parse the current setting
    // in this unusual place :-/
    QSettings * graphicsSettings = new QSettings("kde.org", "Marble Desktop Globe");
    QString graphicsString = graphicsSettings->value("View/graphicsSystem", "raster").toString();
    delete graphicsSettings;
    QApplication::setGraphicsSystem( graphicsString );

    QApplication app(argc, argv);
    // Widget translation

#ifdef Q_WS_MAEMO_5
    // Work around http://bugreports.qt.nokia.com/browse/QTBUG-1313
    QProcessEnvironment env = QProcessEnvironment::systemEnvironment();
    QString lang( "C" );
    QStringList const locales = QStringList() << "LC_ALL" << "LC_MESSAGES" << "LANG" << "LANGUAGE";
    foreach( const QString &locale, locales ) {
        if ( env.contains( locale ) && !env.value( locale ).isEmpty() ) {
            lang = env.value( locale, "C" );
            break;
        }
    }

    lang = lang.section( '_', 0, 0 );
#else
    QString      lang = QLocale::system().name().section('_', 0, 0);
#endif
    QTranslator  translator;
    translator.load( "marble-" + lang, MarbleDirs::path(QString("lang") ) );
    app.installTranslator(&translator);

    // For non static builds on mac and win
    // we need to be sure we can find the qt image
    // plugins. In mac be sure to look in the
    // application bundle...

#ifdef Q_WS_WIN
    QApplication::addLibraryPath( QApplication::applicationDirPath()
        + QDir::separator() + "plugins" );
#endif
#ifdef Q_OS_MACX
    QApplication::instance()->setAttribute(Qt::AA_DontShowIconsInMenus);
    qDebug("Adding qt image plugins to plugin search path...");
    CFURLRef myBundleRef = CFBundleCopyBundleURL(CFBundleGetMainBundle());
    CFStringRef myMacPath = CFURLCopyFileSystemPath(myBundleRef, kCFURLPOSIXPathStyle);
    const char *mypPathPtr = CFStringGetCStringPtr(myMacPath,CFStringGetSystemEncoding());
    CFRelease(myBundleRef);
    CFRelease(myMacPath);
    QString myPath(mypPathPtr);
    // if we are not in a bundle assume that the app is built
    // as a non bundle app and that image plugins will be
    // in system Qt frameworks. If the app is a bundle
    // lets try to set the qt plugin search path...
    if (myPath.contains(".app"))
    {
      myPath += "/Contents/plugins";
      QApplication::addLibraryPath( myPath );
      qDebug( "Added %s to plugin search path", qPrintable( myPath ) );
    }
#endif

    QString marbleDataPath;
    int dataPathIndex=0;
    MarbleGlobal::Profiles profiles = MarbleGlobal::detectProfiles();

    QStringList args = QApplication::arguments();

    if ( args.contains( "-h" ) || args.contains( "--help" ) ) {
        qWarning() << "Usage: marble [options] [files]";
        qWarning();
        qWarning() << "[files] can be zero, one or more .kml and/or .gpx files to load and show.";
        qWarning();
        qWarning() << "general options:";
        qWarning() << "  --marbledatapath=<path> .... Overwrite the compile-time path to map themes and other data";
        qWarning() << "  --enableFileView ........... Add a tab on the left showing detailed information about loaded files";
        qWarning();
        qWarning() << "debug options:";
        qWarning() << "  --debug-info ............... write (more) debugging information to the console";
        qWarning() << "  --fps ...................... Show the paint performance (paint rate) in the top left corner";
        qWarning() << "  --tile-id................... Write the identifier of texture tiles on top of them";
        qWarning() << "  --timedemo ................. Measure the paint performance while moving the map and quit";
        qWarning();
        qWarning() << "profile options (note that marble should automatically detect which profile to use. Override that with the options below):";
        qWarning() << "  --smallscreen .............. Enforce the profile for devices with small screens (e.g. smartphones)";
        qWarning() << "  --highresolution ........... Enforce the profile for devices with high resolution (e.g. desktop computers)";
        qWarning() << "  --nosmallscreen ............ Deactivate the profile for devices with small screens (e.g. smartphones)";
        qWarning() << "  --nohighresolution ......... Deactivate the profile for devices with high resolution (e.g. desktop computers)";

        return 0;
    }

    for ( int i = 1; i < args.count(); ++i ) {
        const QString arg = args.at(i);

        if ( arg == "--debug-info" )
        {
            MarbleDebug::enable = true;
        }
        else if ( arg.startsWith( "--marbledatapath=", Qt::CaseInsensitive ) )
        {
            marbleDataPath = args.at(i).mid(17);
        }
        else if ( arg.compare( "--marbledatapath", Qt::CaseInsensitive ) == 0 ) {
            dataPathIndex = i + 1;
            marbleDataPath = args.value( dataPathIndex );
            ++i;
        }
        else if ( arg == "--smallscreen" ) {
            profiles |= MarbleGlobal::SmallScreen;
        }
        else if ( arg == "--nosmallscreen" ) {
            profiles &= ~MarbleGlobal::SmallScreen;
        }
        else if ( arg == "--highresolution" ) {
            profiles |= MarbleGlobal::HighResolution;
        }
        else if ( arg == "--nohighresolution" ) {
            profiles &= ~MarbleGlobal::HighResolution;
        }
    }
    MarbleGlobal::getInstance()->setProfiles( profiles );

    QLocale::MeasurementSystem const measurement = QLocale::system().measurementSystem();
    Marble::MeasureSystem const marbleMeasurement = measurement == QLocale::ImperialSystem ? Marble::Imperial : Marble::Metric;
    MarbleGlobal::getInstance()->locale()->setMeasureSystem( marbleMeasurement );

    MainWindow *window = new MainWindow( marbleDataPath );
    window->setAttribute( Qt::WA_DeleteOnClose, true );

    MarbleTest *marbleTest = new MarbleTest( window->marbleWidget() );

//    window->marbleWidget()->rotateTo( 0, 0, -90 );
//    window->show();

    for ( int i = 1; i < args.count(); ++i ) {
        const QString arg = args.at(i);
        if ( arg == "--timedemo" )
        {
            window->resize(900, 640);
            marbleTest->timeDemo();
            return 0;
        }
        else if( arg == "--gpsdemo" ) {
            window->resize( 900, 640 );
            marbleTest->gpsDemo();
            return 0;
        }
        else if( arg == "--fps" ) {
            window->marbleControl()->marbleWidget()->setShowFrameRate( true );
        }
        else if( arg == "--enableCurrentLocation" )
        {
            window->marbleControl()->setCurrentLocationTabShown(true);
        }
        else if( arg == "--enableFileView" )
        {
            window->marbleControl()->setFileViewTabShown(true);
        }
        else if ( arg == "--tile-id" )
        {
	    window->marbleControl()->marbleWidget()->setShowTileId(true);
        }
        else if ( i != dataPathIndex && QFile::exists( arg ) )
            ( window->marbleControl() )->addGeoDataFile( arg );
    }

    delete marbleTest;

    return app.exec();
}
<|endoftext|>


<commit_before>#include <iostream>                                         /* allows to perform standard input and output operations */
#include <fstream>
#include <stdio.h>                                          /* Standard input/output definitions */
#include <stdint.h>                                         /* Standard input/output definitions */
#include <stdlib.h>                                         /* defines several general purpose functions */
#include <unistd.h>                                         /* UNIX standard function definitions */
#include <fcntl.h>                                          /* File control definitions */
#include <ctype.h>                                          /* isxxx() */
#include <ros/ros.h>                                        /* ROS */
#include <geometry_msgs/Twist.h>                            /* ROS Twist message */
#include <base_controller/encoders.h>                       /* Custom message /encoders */
#include <base_controller/md49data.h>                       /* Custom message /encoders */

#include <serialport/serialport.h>
#define REPLY_SIZE 18
#define TIMEOUT 1000

int32_t EncoderL;                                           /* stores encoder value left read from md49 */
int32_t EncoderR;                                           /* stores encoder value right read from md49 */
char reply[REPLY_SIZE];
unsigned char speed_l=128, speed_r=128;                     /* speed to set for MD49 */
unsigned char last_speed_l=128, last_speed_r=128;           /* speed to set for MD49 */
double vr = 0.0;
double vl = 0.0;
double max_vr = 0.2;
double max_vl = 0.2;
double min_vr = 0.2;
double min_vl = 0.2;
double base_width = 0.4;                                    /* Base width in meters */

//unsigned char serialBuffer[18];                             /* Serial buffer to store uart data */
void read_MD49_Data (void);
void set_MD49_speed (unsigned char speed_l, unsigned char speed_r);
char* itoa(int value, char* result, int base);

using namespace std;
cereal::CerealPort device;
base_controller::encoders encoders;
base_controller::md49data md49data;

void cmd_vel_callback(const geometry_msgs::Twist& vel_cmd){

        if (vel_cmd.linear.x>0){
            speed_l = 255;
            speed_r = 255;
        }
        if (vel_cmd.linear.x<0){
            speed_l = 0;
            speed_r = 0;
        }
        if (vel_cmd.linear.x==0 && vel_cmd.angular.z==0){
            speed_l = 128;
            speed_r = 128;
        }
        if (vel_cmd.angular.z>0){
            speed_l = 0;
            speed_r = 255;
        }
        if (vel_cmd.angular.z<0){
            speed_l = 255;
            speed_r = 0;
        }
        if ((speed_l != last_speed_l) || (speed_r != last_speed_r)){
            //set_MD49_speed(speed_l,speed_r);
            last_speed_l=speed_l;
            last_speed_r=speed_r;
        }

    /*
        //ANFANG Alternative
        if (vel_cmd.linear.x==0 && vel_cmd.angular.z==0){vl=0;vr=0;}
        else if(vel_cmd.linear.x == 0){
            // turning
            vr = vel_cmd.angular.z * base_width / 2.0;
            vl = (-1) * vr;
        }
        else if(vel_cmd.angular.z == 0){
            // forward / backward
            vl = vr = vel_cmd.linear.x;
        }
        else{
            // moving doing arcs
            vl = vel_cmd.linear.x - vel_cmd.angular.z * base_width / 2.0;
            if (vl > max_vl) {vl=max_vl;}
            if (vl < min_vl) {vl=min_vl;}
            vr = vel_cmd.linear.x + vel_cmd.angular.z * base_width / 2.0;
            if (vr > max_vr) {vr=max_vr;}
            if (vr < min_vr) {vr=min_vr;}
        }
        //ENDE Alternative
    */
}

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

    ros::init(argc, argv, "base_controller" );
    ros::NodeHandle n;
    ros::Subscriber sub = n.subscribe("/cmd_vel", 10, cmd_vel_callback);
    ros::Publisher encoders_pub = n.advertise<base_controller::encoders>("encoders",10);
    ros::Publisher md49data_pub = n.advertise<base_controller::md49data>("md49data",10);

    // Init node
    // *********
    ros::Rate loop_rate(10);
    ROS_INFO("base_controller running...");
    ROS_INFO("=============================");
    ROS_INFO("Subscribing to topic /cmd_vel");
    ROS_INFO("Publishing to topic /encoders");
    ROS_INFO("Publishing to topic /md49data");
    sleep(2);

    // Open serial port
    // ****************
    try{ device.open("/dev/ttyAMA0", 38400); }
    catch(cereal::Exception& e)
    {
      ROS_FATAL("Failed to open the serial port!!!");
      ROS_BREAK();
    }
    ROS_INFO("The serial port is opened.");

    while(n.ok())
    {
        // Read encoder and other data from MD49
        // (data is read from serial_controller_node
        //  and avaiable through md49_data.txt)
        // *****************************************
        read_MD49_Data();

        // Publish encoder values to topic /encoders (custom message)
        // **********************************************************
        encoders.encoder_l=EncoderL;
        encoders.encoder_r=EncoderR;
        encoders_pub.publish(encoders);

        // Publish MD49 data to topic /md49data (custom message)
        // *****************************************************
        md49data.speed_l = reply[8];
        md49data.speed_r = reply[9];
        md49data.volt = reply[10];
        md49data.current_l = reply[11];
        md49data.current_r = reply[12];
        md49data.error = reply[13];
        md49data.acceleration = reply[14];
        md49data.mode = reply[15];
        md49data.regulator = reply[16];
        md49data.timeout = reply[17];
        md49data_pub.publish(md49data);

        // ****
        ros::spinOnce();
        loop_rate.sleep();

    }// end.mainloop

    return 1;
} // end.main

void read_MD49_Data (void){

    // Send 'R' over the serial port
    device.write("R");
    // Get the reply, the last value is the timeout in ms
    try{ device.read(reply, REPLY_SIZE, TIMEOUT); }
    catch(cereal::TimeoutException& e)
    {
      ROS_ERROR("Timeout on serialport! No data read");
    }
    //ROS_INFO("Received MD49 data");

    // Put toghether new encodervalues
    // *******************************
    EncoderL = reply[0] << 24;                        // Put together first encoder value
    EncoderL |= (reply[1] << 16);
    EncoderL |= (reply[2] << 8);
    EncoderL |= (reply[3]);
    EncoderR = reply[4] << 24;                        // Put together second encoder value
    EncoderR |= (reply[5] << 16);
    EncoderR |= (reply[6] << 8);
    EncoderR |= (reply[7]);

/*
    // Output MD49 data on screen
    // **************************
    printf("\033[2J");                                      //  clear the screen
    printf("\033[H");                                       //  position cursor at top-left corner
    printf ("MD49-Data read from AVR-Master: \n");
    printf("========================================\n");
    printf("Encoder1 Byte1: %i ",reply[0]);
    printf("Byte2: %i ",reply[1]);
    printf("Byte3: % i ",reply[2]);
    printf("Byte4: %i \n",reply[3]);
    printf("Encoder2 Byte1: %i ",reply[4]);
    printf("Byte2: %i ",reply[5]);
    printf("Byte3: %i ",reply[6]);
    printf("Byte4: %i \n",reply[7]);
    printf("EncoderL: %i ",EncoderL);
    printf("EncoderR: %i \n",EncoderR);
    printf("========================================\n");
    printf("Speed1: %i ",reply[8]);
    printf("Speed2: %i \n",reply[9]);
    printf("Volts: %i \n",reply[10]);
    printf("Current1: %i ",reply[11]);
    printf("Current2: %i \n",reply[12]);
    printf("Error: %i \n",reply[13]);
    printf("Acceleration: %i \n",reply[14]);
    printf("Mode: %i \n",reply[15]);
    printf("Regulator: %i \n",reply[16]);
    printf("Timeout: %i \n",reply[17]);
*/

}

void set_MD49_speed (unsigned char speed_l, unsigned char speed_r){

/*
    char buffer[33];
    ofstream myfile;
    myfile.open ("md49_commands.txt");
    //myfile << "Writing this to a file.\n";
    if (speed_l==0){
        myfile << "000";
        myfile << "\n";
    }
    else if (speed_l<10){
        myfile << "00";
        myfile << itoa(speed_l,buffer,10);
        myfile << "\n";
    }
    else if (speed_l<100){
        myfile << "0";
        myfile << itoa(speed_l,buffer,10);
        myfile << "\n";
    }
    else{
        myfile << itoa(speed_l,buffer,10);
        myfile << "\n";
    }

    if (speed_r==0){
        myfile << "000";
        myfile << "\n";
    }
    else if (speed_r<10){
        myfile << "00";
        myfile << itoa(speed_r,buffer,10);
        myfile << "\n";
    }
    else if (speed_r<100){
        myfile << "0";
        myfile << itoa(speed_r,buffer,10);
        myfile << "\n";
    }
    else{
        myfile << itoa(speed_r,buffer,10);
        myfile << "\n";
    }
    myfile.close();
*/

}

char* itoa(int value, char* result, int base) {
        // check that the base if valid
        if (base < 2 || base > 36) { *result = '\0'; return result; }

        char* ptr = result, *ptr1 = result, tmp_char;
        int tmp_value;

        do {
            tmp_value = value;
            value /= base;
            *ptr++ = "zyxwvutsrqponmlkjihgfedcba9876543210123456789abcdefghijklmnopqrstuvwxyz" [35 + (tmp_value - value * base)];
        } while ( value );

        // Apply negative sign
        if (tmp_value < 0) *ptr++ = '-';
        *ptr-- = '\0';
        while(ptr1 < ptr) {
            tmp_char = *ptr;
            *ptr--= *ptr1;
            *ptr1++ = tmp_char;
        }
        return result;
    }
<commit_msg>Update code<commit_after>#include <iostream>                                         /* allows to perform standard input and output operations */
#include <fstream>
#include <stdio.h>                                          /* Standard input/output definitions */
#include <stdint.h>                                         /* Standard input/output definitions */
#include <stdlib.h>                                         /* defines several general purpose functions */
#include <unistd.h>                                         /* UNIX standard function definitions */
#include <fcntl.h>                                          /* File control definitions */
#include <ctype.h>                                          /* isxxx() */
#include <ros/ros.h>                                        /* ROS */
#include <geometry_msgs/Twist.h>                            /* ROS Twist message */
#include <base_controller/encoders.h>                       /* Custom message /encoders */
#include <base_controller/md49data.h>                       /* Custom message /encoders */

#include <serialport/serialport.h>
#define REPLY_SIZE 18
#define TIMEOUT 1000

int32_t EncoderL;                                           /* stores encoder value left read from md49 */
int32_t EncoderR;                                           /* stores encoder value right read from md49 */
char reply[REPLY_SIZE];
unsigned char speed_l=128, speed_r=128;                     /* speed to set for MD49 */
unsigned char last_speed_l=128, last_speed_r=128;           /* speed to set for MD49 */
double vr = 0.0;
double vl = 0.0;
double max_vr = 0.2;
double max_vl = 0.2;
double min_vr = 0.2;
double min_vl = 0.2;
double base_width = 0.4;                                    /* Base width in meters */

//unsigned char serialBuffer[18];                             /* Serial buffer to store uart data */
void read_MD49_Data (void);
void set_MD49_speed (unsigned char speed_l, unsigned char speed_r);
char* itoa(int value, char* result, int base);

using namespace std;
cereal::CerealPort device;
base_controller::encoders encoders;
base_controller::md49data md49data;

void cmd_vel_callback(const geometry_msgs::Twist& vel_cmd){

        if (vel_cmd.linear.x>0){
            speed_l = 255;
            speed_r = 255;
        }
        if (vel_cmd.linear.x<0){
            speed_l = 0;
            speed_r = 0;
        }
        if (vel_cmd.linear.x==0 && vel_cmd.angular.z==0){
            speed_l = 128;
            speed_r = 128;
        }
        if (vel_cmd.angular.z>0){
            speed_l = 0;
            speed_r = 255;
        }
        if (vel_cmd.angular.z<0){
            speed_l = 255;
            speed_r = 0;
        }
        if ((speed_l != last_speed_l) || (speed_r != last_speed_r)){
            //set_MD49_speed(speed_l,speed_r);
            last_speed_l=speed_l;
            last_speed_r=speed_r;
        }

    /*
        //ANFANG Alternative
        if (vel_cmd.linear.x==0 && vel_cmd.angular.z==0){vl=0;vr=0;}
        else if(vel_cmd.linear.x == 0){
            // turning
            vr = vel_cmd.angular.z * base_width / 2.0;
            vl = (-1) * vr;
        }
        else if(vel_cmd.angular.z == 0){
            // forward / backward
            vl = vr = vel_cmd.linear.x;
        }
        else{
            // moving doing arcs
            vl = vel_cmd.linear.x - vel_cmd.angular.z * base_width / 2.0;
            if (vl > max_vl) {vl=max_vl;}
            if (vl < min_vl) {vl=min_vl;}
            vr = vel_cmd.linear.x + vel_cmd.angular.z * base_width / 2.0;
            if (vr > max_vr) {vr=max_vr;}
            if (vr < min_vr) {vr=min_vr;}
        }
        //ENDE Alternative
    */
}

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

    ros::init(argc, argv, "base_controller" );
    ros::NodeHandle n;
    ros::Subscriber sub = n.subscribe("/cmd_vel", 10, cmd_vel_callback);
    ros::Publisher encoders_pub = n.advertise<base_controller::encoders>("encoders",10);
    ros::Publisher md49data_pub = n.advertise<base_controller::md49data>("md49data",10);

    // Init node
    // *********
    ros::Rate loop_rate(10);
    ROS_INFO("base_controller running...");
    ROS_INFO("=============================");
    ROS_INFO("Subscribing to topic /cmd_vel");
    ROS_INFO("Publishing to topic /encoders");
    ROS_INFO("Publishing to topic /md49data");

    // Open serial port
    // ****************
    try{ device.open("/dev/ttyAMA0", 38400); }
    catch(cereal::Exception& e)
    {
      ROS_FATAL("Failed to open the serial port!!!");
      ROS_BREAK();
    }
    ROS_INFO("The serial port is opened.");

    while(n.ok())
    {
        // Read encoder and other data from MD49
        // (data is read from serial_controller_node
        //  and avaiable through md49_data.txt)
        // *****************************************
        read_MD49_Data();

        // Publish encoder values to topic /encoders (custom message)
        // **********************************************************
        encoders.encoder_l=EncoderL;
        encoders.encoder_r=EncoderR;
        encoders_pub.publish(encoders);

        // Publish MD49 data to topic /md49data (custom message)
        // *****************************************************
        md49data.speed_l = reply[8];
        md49data.speed_r = reply[9];
        md49data.volt = reply[10];
        md49data.current_l = reply[11];
        md49data.current_r = reply[12];
        md49data.error = reply[13];
        md49data.acceleration = reply[14];
        md49data.mode = reply[15];
        md49data.regulator = reply[16];
        md49data.timeout = reply[17];
        md49data_pub.publish(md49data);

        // ****
        ros::spinOnce();
        loop_rate.sleep();

    }// end.mainloop

    return 1;
} // end.main

void read_MD49_Data (void){

    // Send 'R' over the serial port
    device.write("R");
    // Get the reply, the last value is the timeout in ms
    try{ device.read(reply, REPLY_SIZE, TIMEOUT); }
    catch(cereal::TimeoutException& e)
    {
      ROS_ERROR("Timeout on serialport! No data read");
    }
    //ROS_INFO("Received MD49 data");

    // Put toghether new encodervalues
    // *******************************
    EncoderL = reply[0] << 24;                        // Put together first encoder value
    EncoderL |= (reply[1] << 16);
    EncoderL |= (reply[2] << 8);
    EncoderL |= (reply[3]);
    EncoderR = reply[4] << 24;                        // Put together second encoder value
    EncoderR |= (reply[5] << 16);
    EncoderR |= (reply[6] << 8);
    EncoderR |= (reply[7]);

/*
    // Output MD49 data on screen
    // **************************
    printf("\033[2J");                                      //  clear the screen
    printf("\033[H");                                       //  position cursor at top-left corner
    printf ("MD49-Data read from AVR-Master: \n");
    printf("========================================\n");
    printf("Encoder1 Byte1: %i ",reply[0]);
    printf("Byte2: %i ",reply[1]);
    printf("Byte3: % i ",reply[2]);
    printf("Byte4: %i \n",reply[3]);
    printf("Encoder2 Byte1: %i ",reply[4]);
    printf("Byte2: %i ",reply[5]);
    printf("Byte3: %i ",reply[6]);
    printf("Byte4: %i \n",reply[7]);
    printf("EncoderL: %i ",EncoderL);
    printf("EncoderR: %i \n",EncoderR);
    printf("========================================\n");
    printf("Speed1: %i ",reply[8]);
    printf("Speed2: %i \n",reply[9]);
    printf("Volts: %i \n",reply[10]);
    printf("Current1: %i ",reply[11]);
    printf("Current2: %i \n",reply[12]);
    printf("Error: %i \n",reply[13]);
    printf("Acceleration: %i \n",reply[14]);
    printf("Mode: %i \n",reply[15]);
    printf("Regulator: %i \n",reply[16]);
    printf("Timeout: %i \n",reply[17]);
*/

}

void set_MD49_speed (unsigned char speed_l, unsigned char speed_r){

/*
    char buffer[33];
    ofstream myfile;
    myfile.open ("md49_commands.txt");
    //myfile << "Writing this to a file.\n";
    if (speed_l==0){
        myfile << "000";
        myfile << "\n";
    }
    else if (speed_l<10){
        myfile << "00";
        myfile << itoa(speed_l,buffer,10);
        myfile << "\n";
    }
    else if (speed_l<100){
        myfile << "0";
        myfile << itoa(speed_l,buffer,10);
        myfile << "\n";
    }
    else{
        myfile << itoa(speed_l,buffer,10);
        myfile << "\n";
    }

    if (speed_r==0){
        myfile << "000";
        myfile << "\n";
    }
    else if (speed_r<10){
        myfile << "00";
        myfile << itoa(speed_r,buffer,10);
        myfile << "\n";
    }
    else if (speed_r<100){
        myfile << "0";
        myfile << itoa(speed_r,buffer,10);
        myfile << "\n";
    }
    else{
        myfile << itoa(speed_r,buffer,10);
        myfile << "\n";
    }
    myfile.close();
*/

}

char* itoa(int value, char* result, int base) {
        // check that the base if valid
        if (base < 2 || base > 36) { *result = '\0'; return result; }

        char* ptr = result, *ptr1 = result, tmp_char;
        int tmp_value;

        do {
            tmp_value = value;
            value /= base;
            *ptr++ = "zyxwvutsrqponmlkjihgfedcba9876543210123456789abcdefghijklmnopqrstuvwxyz" [35 + (tmp_value - value * base)];
        } while ( value );

        // Apply negative sign
        if (tmp_value < 0) *ptr++ = '-';
        *ptr-- = '\0';
        while(ptr1 < ptr) {
            tmp_char = *ptr;
            *ptr--= *ptr1;
            *ptr1++ = tmp_char;
        }
        return result;
    }
<|endoftext|>


<commit_before>/*
 * This file is part of the UnTech Editor Suite.
 * Copyright (c) 2016 - 2019, Marcus Rowe <undisbeliever@gmail.com>.
 * Distributed under The MIT License: https://opensource.org/licenses/MIT
 */

#include "cartridge.h"
#include <array>
#include <cassert>
#include <climits>
#include <fstream>
#include <stdexcept>

using namespace UnTech::Snes;
using namespace UnTech::Snes::Cartridge;

constexpr size_t HEADER_ADDR = 0xffb0;
constexpr size_t CHECKSUM_COMPLEMENT_ADDR = 0xffdc;
constexpr size_t CHECKSUM_ADDR = 0xffde;

constexpr unsigned MIN_ROM_SIZE = 64 * 1024;
constexpr unsigned MAX_ROM_SIZE = 4 * 1024 * 1024;

#define MIN_ROM_STRING "64 KiB"
#define MAX_ROM_STRING "4 MiB"

size_t Cartridge::headerAddress(MemoryMap memoryMap)
{
    switch (memoryMap) {
    case MemoryMap::LOROM:
        return HEADER_ADDR - 0x8000;

    case MemoryMap::HIROM:
        return HEADER_ADDR;
    }

    throw std::invalid_argument("invalid MemoryMap");
}

static inline size_t checksumCompelementAddress(MemoryMap memoryMap)
{
    constexpr size_t offset = CHECKSUM_COMPLEMENT_ADDR - HEADER_ADDR;
    return headerAddress(memoryMap) + offset;
}

static inline size_t checksumAddress(MemoryMap memoryMap)
{
    constexpr size_t offset = CHECKSUM_ADDR - HEADER_ADDR;
    return headerAddress(memoryMap) + offset;
}

bool Cartridge::isHeaderValid(const std::vector<uint8_t>& rom, MemoryMap memoryMap)
{
    static const std::array<uint8_t, 2 + 4 + 7> EXPECTED(
        { { 'F', 'F', 'S', 'N', 'E', 'S', 0, 0, 0, 0, 0, 0, 0 } });

    // addresses of blank words in the interrupt vector
    static const std::array<size_t, 6> BLANK_INTERRUPT_VECTORS(
        { { 0xffe0, 0xffe2, 0xffec,
            0xfff0, 0xfff2, 0xfff6 } });

    if (rom.size() < MIN_ROM_SIZE) {
        return false;
    }

    size_t addr = headerAddress(memoryMap);

    if (!std::equal(EXPECTED.begin(), EXPECTED.end(), rom.begin() + addr)) {
        return false;
    }

    for (size_t v : BLANK_INTERRUPT_VECTORS) {
        size_t a = addr + v - HEADER_ADDR;

        if (rom[a] != 0 || rom[a + 1] != 0) {
            return false;
        }
    }

    return true;
}

uint16_t Cartridge::readChecksum(const std::vector<uint8_t>& rom, MemoryMap memoryMap)
{
    unsigned addr = checksumAddress(memoryMap);

    return rom.at(addr) | rom.at(addr + 1) << 8;
}

uint16_t Cartridge::calculateChecksum(const std::vector<uint8_t>& rom, MemoryMap memoryMap)
{
    static_assert(sizeof(int) > sizeof(uint16_t) + 1, "int too small");
    static_assert(INT_MAX > MAX_ROM_SIZE * 256, "int too small");

    if (rom.size() < MIN_ROM_SIZE) {
        throw std::runtime_error("ROM is to small (minimum " MIN_ROM_STRING ").");
    }
    if (rom.size() > MAX_ROM_SIZE) {
        throw std::runtime_error("ROM is to large (maximum " MAX_ROM_STRING ").");
    }

    unsigned part1Size = 1;
    while (part1Size <= rom.size()) {
        part1Size <<= 1;
    }
    part1Size >>= 1;

    int part1 = 0;
    assert(part1Size <= rom.size());
    for (unsigned i = 0; i < part1Size; i++) {
        part1 += rom[i];
    }

    int part2 = 0;
    unsigned part2Count = 0;
    if (part1Size != rom.size()) {
        unsigned part2Size = rom.size() - part1Size;

        part2Count = part1Size / part2Size;
        if (part1Size % part2Size != 0) {
            throw std::runtime_error("Invalid ROM size.");
        }

        for (unsigned i = part1Size; i < rom.size(); i++) {
            part2 += rom[i];
        }
    }

    int oldSum = 0;
    static_assert(CHECKSUM_ADDR == CHECKSUM_COMPLEMENT_ADDR + 2, "assumption failed");
    unsigned ccAddr = checksumCompelementAddress(memoryMap);
    for (unsigned i = 0; i < 4; i++) {
        oldSum += rom[i + ccAddr];
    }

    int checkSum = part1 + part2 * part2Count - oldSum + 0xff * 2;
    while (checkSum < 0) {
        checkSum += 0x10000;
    }

    return checkSum & 0xffff;
}

void Cartridge::writeChecksum(const std::string& filename, uint16_t checksum, MemoryMap memoryMap)
{
    unsigned checksumAddr = checksumAddress(memoryMap);
    unsigned complementAddr = checksumCompelementAddress(memoryMap);

    uint16_t complement = 0xffff ^ checksum;

    std::ofstream out(filename, std::ios::out | std::ios::in | std::ios::binary);
    if (!out) {
        throw std::runtime_error("Error opening file: " + filename);
    }

    out.exceptions(std::ios::failbit | std::ios::badbit);

    out.seekp(complementAddr);
    out.put(complement & 0xff);
    out.put(complement >> 8 & 0xff);

    assert(checksumAddr == complementAddr + 2);
    out.put(checksum & 0xff);
    out.put(checksum >> 8 & 0xff);

    out.close();
}
<commit_msg>Remove Maker Code and Game Code from the SNES header<commit_after>/*
 * This file is part of the UnTech Editor Suite.
 * Copyright (c) 2016 - 2019, Marcus Rowe <undisbeliever@gmail.com>.
 * Distributed under The MIT License: https://opensource.org/licenses/MIT
 */

#include "cartridge.h"
#include <array>
#include <cassert>
#include <climits>
#include <fstream>
#include <stdexcept>

using namespace UnTech::Snes;
using namespace UnTech::Snes::Cartridge;

constexpr size_t HEADER_ADDR = 0xffb0;
constexpr size_t CHECKSUM_COMPLEMENT_ADDR = 0xffdc;
constexpr size_t CHECKSUM_ADDR = 0xffde;

constexpr unsigned MIN_ROM_SIZE = 64 * 1024;
constexpr unsigned MAX_ROM_SIZE = 4 * 1024 * 1024;

#define MIN_ROM_STRING "64 KiB"
#define MAX_ROM_STRING "4 MiB"

size_t Cartridge::headerAddress(MemoryMap memoryMap)
{
    switch (memoryMap) {
    case MemoryMap::LOROM:
        return HEADER_ADDR - 0x8000;

    case MemoryMap::HIROM:
        return HEADER_ADDR;
    }

    throw std::invalid_argument("invalid MemoryMap");
}

static inline size_t checksumCompelementAddress(MemoryMap memoryMap)
{
    constexpr size_t offset = CHECKSUM_COMPLEMENT_ADDR - HEADER_ADDR;
    return headerAddress(memoryMap) + offset;
}

static inline size_t checksumAddress(MemoryMap memoryMap)
{
    constexpr size_t offset = CHECKSUM_ADDR - HEADER_ADDR;
    return headerAddress(memoryMap) + offset;
}

bool Cartridge::isHeaderValid(const std::vector<uint8_t>& rom, MemoryMap memoryMap)
{
    // Blank Maker Code and Game Code as my homebrew stuff is unlicensed.
    static const std::array<uint8_t, 2 + 4 + 7> EXPECTED(
        { { ' ', ' ', ' ', ' ', ' ', ' ', 0, 0, 0, 0, 0, 0, 0 } });

    // addresses of blank words in the interrupt vector
    static const std::array<size_t, 6> BLANK_INTERRUPT_VECTORS(
        { { 0xffe0, 0xffe2, 0xffec,
            0xfff0, 0xfff2, 0xfff6 } });

    if (rom.size() < MIN_ROM_SIZE) {
        return false;
    }

    size_t addr = headerAddress(memoryMap);

    if (!std::equal(EXPECTED.begin(), EXPECTED.end(), rom.begin() + addr)) {
        return false;
    }

    for (size_t v : BLANK_INTERRUPT_VECTORS) {
        size_t a = addr + v - HEADER_ADDR;

        if (rom[a] != 0 || rom[a + 1] != 0) {
            return false;
        }
    }

    return true;
}

uint16_t Cartridge::readChecksum(const std::vector<uint8_t>& rom, MemoryMap memoryMap)
{
    unsigned addr = checksumAddress(memoryMap);

    return rom.at(addr) | rom.at(addr + 1) << 8;
}

uint16_t Cartridge::calculateChecksum(const std::vector<uint8_t>& rom, MemoryMap memoryMap)
{
    static_assert(sizeof(int) > sizeof(uint16_t) + 1, "int too small");
    static_assert(INT_MAX > MAX_ROM_SIZE * 256, "int too small");

    if (rom.size() < MIN_ROM_SIZE) {
        throw std::runtime_error("ROM is to small (minimum " MIN_ROM_STRING ").");
    }
    if (rom.size() > MAX_ROM_SIZE) {
        throw std::runtime_error("ROM is to large (maximum " MAX_ROM_STRING ").");
    }

    unsigned part1Size = 1;
    while (part1Size <= rom.size()) {
        part1Size <<= 1;
    }
    part1Size >>= 1;

    int part1 = 0;
    assert(part1Size <= rom.size());
    for (unsigned i = 0; i < part1Size; i++) {
        part1 += rom[i];
    }

    int part2 = 0;
    unsigned part2Count = 0;
    if (part1Size != rom.size()) {
        unsigned part2Size = rom.size() - part1Size;

        part2Count = part1Size / part2Size;
        if (part1Size % part2Size != 0) {
            throw std::runtime_error("Invalid ROM size.");
        }

        for (unsigned i = part1Size; i < rom.size(); i++) {
            part2 += rom[i];
        }
    }

    int oldSum = 0;
    static_assert(CHECKSUM_ADDR == CHECKSUM_COMPLEMENT_ADDR + 2, "assumption failed");
    unsigned ccAddr = checksumCompelementAddress(memoryMap);
    for (unsigned i = 0; i < 4; i++) {
        oldSum += rom[i + ccAddr];
    }

    int checkSum = part1 + part2 * part2Count - oldSum + 0xff * 2;
    while (checkSum < 0) {
        checkSum += 0x10000;
    }

    return checkSum & 0xffff;
}

void Cartridge::writeChecksum(const std::string& filename, uint16_t checksum, MemoryMap memoryMap)
{
    unsigned checksumAddr = checksumAddress(memoryMap);
    unsigned complementAddr = checksumCompelementAddress(memoryMap);

    uint16_t complement = 0xffff ^ checksum;

    std::ofstream out(filename, std::ios::out | std::ios::in | std::ios::binary);
    if (!out) {
        throw std::runtime_error("Error opening file: " + filename);
    }

    out.exceptions(std::ios::failbit | std::ios::badbit);

    out.seekp(complementAddr);
    out.put(complement & 0xff);
    out.put(complement >> 8 & 0xff);

    assert(checksumAddr == complementAddr + 2);
    out.put(checksum & 0xff);
    out.put(checksum >> 8 & 0xff);

    out.close();
}
<|endoftext|>


<commit_before>/*
 * LinearAverageProbe.cpp
 *
 *  Created on: Apr 22, 2009
 *      Author: rasmussn
 */

#include "LinearAverageProbe.hpp"
#include "io.h"
#include <assert.h>
#include <string.h>  // strdup

namespace PV {

/**
 * @hc
 * @dim
 * @f
 * @gifFile
 */
LinearAverageProbe::LinearAverageProbe(HyPerCol * hc, PVDimType dim, int f, const char * gifFile)
   : LinearActivityProbe(hc, dim, 0, f)
{
   this->gifFile = strdup(gifFile);
   this->fpGif   = NULL;
}

/**
 * @filename
 * @hc
 * @dim
 * @f
 * @char
 */
LinearAverageProbe::LinearAverageProbe(const char * filename, HyPerCol * hc, PVDimType dim, int f, const char * gifFile)
    : LinearActivityProbe(filename, hc, dim, 0, f)
{
   this->gifFile = strdup(gifFile);
   this->fpGif   = NULL;
}

LinearAverageProbe::~LinearAverageProbe()
{
   if (fpGif != NULL) {
      fclose(fpGif);
   }
}

/**
 * @time
 * @l
 */
int LinearAverageProbe::outputState(float time, PVLayer * l)
{
   int nk, sk;
   float * line;

   if (fpGif == NULL) {
      int numOnLines = 0;
      char path[PV_PATH_MAX];
      sprintf(path, "%s%s", OUTPUT_PATH, gifFile);
//      fpGif = fopen(path, "r");

      int nx = l->loc.nxGlobal;
      int ny = l->loc.nyGlobal;
      int nf = l->numFeatures;

      int sx = strideX(nx, ny, nf);
      int sy = strideY(nx, ny, nf);

      float * buf = (float *) malloc(nx * ny * sizeof(float));
      assert(buf != NULL);

      int err = readFile(path, buf, &nx, &ny);
      if (err == 0) {
         assert(nx <= l->loc.nxGlobal);
         assert(ny <= l->loc.nyGlobal);
         if (nx < l->loc.nxGlobal || ny < l->loc.nyGlobal) {
            err = pv_center_image(buf, nx, ny, l->loc.nxGlobal, l->loc.nyGlobal);
         }
      }

      nx = l->loc.nxGlobal;
      ny = l->loc.nyGlobal;

      if (dim == DimX) {
         nk = nx;
         sk = nf;
         for (int j = 0; j < ny; j++) {
            for (int i = 0; i < nx; i++) {
               if (buf[i*sx + j*sy] > 0.0) {
                  numOnLines += 1;
                  break;
               }
            }
         }

         line = l->activity->data + nf * nk * loc;
      }
      else {
         nk = l->activity->loc.ny;
         sk = nf * l->activity->loc.nx;
         line = l->activity->data + nf * loc;
      }

      // get list of locations
   }

   float dt = parent->getDeltaTime();
   int nf = l->numFeatures;

   if (dim == DimX) {
      nk = l->activity->loc.nx;
      sk = nf;
      line = l->activity->data + nf * nk * loc;
   }
   else {
      nk = l->activity->loc.ny;
      sk = nf * l->activity->loc.nx;
      line = l->activity->data + nf * loc;
   }

   double sum = 0.0;
   for (int k = 0; k < nk; k++) {
      float a = line[f + k * sk];
      sum += a;
   }

   float freq = sum / (nk * dt * 0.001);
   fprintf(fp, "t=%4d sum=%3d f=%6.1f Hz :", (int)time, (int)sum, freq);

   for (int k = 0; k < nk; k++) {
      float a = line[f + k * sk];
      if (a > 0.0) fprintf(fp, "*");
      else         fprintf(fp, " ");
   }

   fprintf(fp, ":\n");
   fflush(fp);

   return 0;
}

}
<commit_msg>Marian and Craig's fixes for extended activity buffers and STDP.<commit_after>/*
 * LinearAverageProbe.cpp
 *
 *  Created on: Apr 22, 2009
 *      Author: rasmussn
 */

#include "LinearAverageProbe.hpp"
#include "io.h"
#include <assert.h>
#include <string.h>  // strdup

namespace PV {

/**
 * @hc
 * @dim
 * @f
 * @gifFile
 */
LinearAverageProbe::LinearAverageProbe(HyPerCol * hc, PVDimType dim, int f, const char * gifFile)
   : LinearActivityProbe(hc, dim, 0, f)
{
   this->gifFile = strdup(gifFile);
   this->fpGif   = NULL;
}

/**
 * @filename
 * @hc
 * @dim
 * @f
 * @char
 */
LinearAverageProbe::LinearAverageProbe(const char * filename, HyPerCol * hc, PVDimType dim, int f, const char * gifFile)
    : LinearActivityProbe(filename, hc, dim, 0, f)
{
   this->gifFile = strdup(gifFile);
   this->fpGif   = NULL;
}

LinearAverageProbe::~LinearAverageProbe()
{
   if (fpGif != NULL) {
      fclose(fpGif);
   }
}

/**
 * @time
 * @l
 */
int LinearAverageProbe::outputState(float time, PVLayer * l)
{
   int nk, sk;
   float * line;

   if (fpGif == NULL) {
      int numOnLines = 0;
      char path[PV_PATH_MAX];
      sprintf(path, "%s%s", OUTPUT_PATH, gifFile);
//      fpGif = fopen(path, "r");

      int nx = l->loc.nxGlobal;
      int ny = l->loc.nyGlobal;
      int nf = l->numFeatures;

      int sx = strideX(nx, ny, nf);
      int sy = strideY(nx, ny, nf);

      float * buf = (float *) malloc(nx * ny * sizeof(float));
      assert(buf != NULL);

      int err = readFile(path, buf, &nx, &ny);
      if (err == 0) {
         assert(nx <= l->loc.nxGlobal);
         assert(ny <= l->loc.nyGlobal);
         if (nx < l->loc.nxGlobal || ny < l->loc.nyGlobal) {
            err = pv_center_image(buf, nx, ny, l->loc.nxGlobal, l->loc.nyGlobal);
         }
      }

      nx = l->loc.nxGlobal;
      ny = l->loc.nyGlobal;

      if (dim == DimX) {
         nk = nx;
         sk = nf;
         for (int j = 0; j < ny; j++) {
            for (int i = 0; i < nx; i++) {
               if (buf[i*sx + j*sy] > 0.0) {
                  numOnLines += 1;
                  break;
               }
            }
         }

         line = l->activity->data + nf * nk * linePos;
      }
      else {
         nk = l->activity->loc.ny;
         sk = nf * l->activity->loc.nx;
         line = l->activity->data + nf * linePos;
      }

      // get list of locations
   }

   float dt = parent->getDeltaTime();
   int nf = l->numFeatures;

   if (dim == DimX) {
      nk = l->activity->loc.nx;
      sk = nf;
      line = l->activity->data + nf * nk * linePos;
   }
   else {
      nk = l->activity->loc.ny;
      sk = nf * l->activity->loc.nx;
      line = l->activity->data + nf * linePos;
   }

   double sum = 0.0;
   for (int k = 0; k < nk; k++) {
      float a = line[f + k * sk];
      sum += a;
   }

   float freq = sum / (nk * dt * 0.001);
   fprintf(fp, "t=%4d sum=%3d f=%6.1f Hz :", (int)time, (int)sum, freq);

   for (int k = 0; k < nk; k++) {
      float a = line[f + k * sk];
      if (a > 0.0) fprintf(fp, "*");
      else         fprintf(fp, " ");
   }

   fprintf(fp, ":\n");
   fflush(fp);

   return 0;
}

}
<|endoftext|>


<commit_before>#include "HSBoundarySpecifiedTemperature.h"
#include "HeatConductionModel.h"

registerMooseObject("THMApp", HSBoundarySpecifiedTemperature);

InputParameters
HSBoundarySpecifiedTemperature::validParams()
{
  InputParameters params = HSBoundary::validParams();

  params.addRequiredParam<FunctionName>("T", "Prescribed temperature [K]");

  return params;
}

HSBoundarySpecifiedTemperature::HSBoundarySpecifiedTemperature(const InputParameters & params)
  : HSBoundary(params),

    _T_func(getParam<FunctionName>("T"))
{
}

void
HSBoundarySpecifiedTemperature::addMooseObjects()
{
  {
    std::string class_name = "FunctionDirichletBC";
    InputParameters pars = _factory.getValidParams(class_name);
    pars.set<NonlinearVariableName>("variable") = HeatConductionModel::TEMPERATURE;
    pars.set<std::vector<BoundaryName>>("boundary") = _boundary;
    pars.set<FunctionName>("function") = _T_func;
    _sim.addBoundaryCondition(class_name, genName(name(), "bc"), pars);
    makeFunctionControllableIfConstant(_T_func, "T");
  }
}
<commit_msg>Converting HSBoundarySpecifiedTemperature to AD<commit_after>#include "HSBoundarySpecifiedTemperature.h"
#include "HeatConductionModel.h"

registerMooseObject("THMApp", HSBoundarySpecifiedTemperature);

InputParameters
HSBoundarySpecifiedTemperature::validParams()
{
  InputParameters params = HSBoundary::validParams();

  params.addRequiredParam<FunctionName>("T", "Prescribed temperature [K]");

  return params;
}

HSBoundarySpecifiedTemperature::HSBoundarySpecifiedTemperature(const InputParameters & params)
  : HSBoundary(params),

    _T_func(getParam<FunctionName>("T"))
{
}

void
HSBoundarySpecifiedTemperature::addMooseObjects()
{
  {
    std::string class_name = "ADFunctionDirichletBC";
    InputParameters pars = _factory.getValidParams(class_name);
    pars.set<NonlinearVariableName>("variable") = HeatConductionModel::TEMPERATURE;
    pars.set<std::vector<BoundaryName>>("boundary") = _boundary;
    pars.set<FunctionName>("function") = _T_func;
    _sim.addBoundaryCondition(class_name, genName(name(), "bc"), pars);
    makeFunctionControllableIfConstant(_T_func, "T");
  }
}
<|endoftext|>


<commit_before>//
// Created by Sam on 11/18/2017.
//

#include "../../../build/catch-src/include/catch.hpp"
#include "../../../include/Game/Python/Factory.h"

TEST_CASE("Create factory")
{
    auto* factory = new Factory();
    delete factory;
//
//    SECTION("Verify creation")
//    {
//        REQUIRE_FALSE(factory == nullptr);
//    }
//
//    SECTION("Verify minimum python version")
//    {
//        std::string minimumVersion = "2.7";
//        bool versionCheck = Version(minimumVersion) < factory->version;
//        REQUIRE(versionCheck);
//    }
//
//    SECTION("Verify expected python version")
//    {
//        std::string expectedVersion = "3.6.3";
//        bool versionCheck = Version(expectedVersion) == factory->version;
//
//        if (!versionCheck)
//        {
//            FAIL_CHECK("Unexpected python version, expected " + expectedVersion +
//                               " but factory's interpreter is running " + factory->version.toString());
//        }
//    }
}<commit_msg>Use a shared ptr and uncomment unit tests<commit_after>//
// Created by Sam on 11/18/2017.
//

#include "../../../build/catch-src/include/catch.hpp"
#include "../../../include/Game/Python/Factory.h"

TEST_CASE("Create factory")
{
    std::shared_ptr<Factory> factory = std::make_shared<Factory>();

    SECTION("Verify creation")
    {
        REQUIRE_FALSE(factory == nullptr);
    }

    SECTION("Verify minimum python version")
    {
        std::string minimumVersion = "2.7";
        bool versionCheck = Version(minimumVersion) < factory->version;
        REQUIRE(versionCheck);
    }

    SECTION("Verify expected python version")
    {
        std::string expectedVersion = "3.6.3";
        bool versionCheck = Version(expectedVersion) == factory->version;

        if (!versionCheck)
        {
            FAIL_CHECK("Unexpected python version, expected " + expectedVersion +
                               " but factory's interpreter is running " + factory->version.toString());
        }
    }
}<|endoftext|>


<commit_before>/**
 * Copyright (c) 2011-2015 libbitcoin developers (see AUTHORS)
 *
 * This file is part of libbitcoin.
 *
 * libbitcoin is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License with
 * additional permissions to the one published by the Free Software
 * Foundation, either version 3 of the License, or (at your option)
 * any later version. For more information see LICENSE.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 */
#include <bitcoin/bitcoin/network/protocol_seed.hpp>

#include <functional>
#include <bitcoin/bitcoin/config/authority.hpp>
#include <bitcoin/bitcoin/error.hpp>
#include <bitcoin/bitcoin/message/address.hpp>
#include <bitcoin/bitcoin/message/get_address.hpp>
#include <bitcoin/bitcoin/message/network_address.hpp>
#include <bitcoin/bitcoin/network/channel.hpp>
#include <bitcoin/bitcoin/network/protocol_base.hpp>
#include <bitcoin/bitcoin/utility/assert.hpp>
#include <bitcoin/bitcoin/utility/deadline.hpp>
#include <bitcoin/bitcoin/utility/dispatcher.hpp>
#include <bitcoin/bitcoin/utility/synchronizer.hpp>
#include <bitcoin/bitcoin/utility/threadpool.hpp>

INITIALIZE_TRACK(bc::network::protocol_seed);

namespace libbitcoin {
namespace network {

using namespace bc::message;
using std::placeholders::_1;
using std::placeholders::_2;
#define CLASS protocol_seed

// Require three callbacks (or any error) before calling complete.
protocol_seed::protocol_seed(channel::ptr peer, threadpool& pool,
    const asio::duration& timeout, handler complete, hosts& hosts,
    const config::authority& self)
  : hosts_(hosts), self_(self),
    protocol_base(peer, pool, timeout, synchronize(complete, 3, "seed")),
    track<protocol_seed>("protocol_seed", LOG_NETWORK)
{
}

void protocol_seed::start()
{
    protocol_base::start();

    if (self_.port() == 0)
    {
        callback(error::success);
    }
    else
    {
        address self({ { self_.to_network_address() } });
        SEND1(self, handle_send_address, _1);
    }

    if (hosts_.capacity() == 0)
    {
        // Error return ends synchronized completion callback.
        callback(error::not_found);
        return;
    }

    SUBSCRIBE2(address, handle_receive_address, _1, _2);
    SEND1(get_address(), handle_send_get_address, _1);
}

void protocol_seed::handle_receive_address(const code& ec,
    const address& message)
{
    if (stopped())
        return;

    if (ec)
    {
        log_debug(LOG_PROTOCOL)
            << "Failure receiving addresses from seed [" << authority() << "] "
            << ec.message();
        callback(error::bad_stream);
        return;
    }

    log_debug(LOG_PROTOCOL)
        << "Storing addresses from seed [" << authority() << "] ("
        << message.addresses.size() << ")";

    // TODO: manage timestamps (active peers are connected < 3 hours ago).
    hosts_.store(message.addresses, BIND1(handle_store_addresses, _1));
}

void protocol_seed::handle_send_address(const code& ec) const
{
    if (stopped())
        return;

    if (ec)
        log_debug(LOG_PROTOCOL)
            << "Failure sending address to seed [" << authority() << "] "
            << ec.message();

    // 1 of 3
    callback(ec);
}

void protocol_seed::handle_send_get_address(const code& ec) const
{
    if (stopped())
        return;

    if (ec)
        log_debug(LOG_PROTOCOL)
            << "Failure sending get_address to seed [" << authority() << "] "
            << ec.message();

    // 2 of 3
    callback(ec);
}

void protocol_seed::handle_store_addresses(const code& ec) const
{
    if (stopped())
        return;

    if (ec)
        log_error(LOG_PROTOCOL)
            << "Failure storing addresses from seed [" << authority() << "] "
            << ec.message();

    // 3 of 3
    callback(ec);
}

#undef CLASS

} // namespace network
} // namespace libbitcoin
<commit_msg>Comment and correct returned error code.<commit_after>/**
 * Copyright (c) 2011-2015 libbitcoin developers (see AUTHORS)
 *
 * This file is part of libbitcoin.
 *
 * libbitcoin is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License with
 * additional permissions to the one published by the Free Software
 * Foundation, either version 3 of the License, or (at your option)
 * any later version. For more information see LICENSE.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 */
#include <bitcoin/bitcoin/network/protocol_seed.hpp>

#include <functional>
#include <bitcoin/bitcoin/config/authority.hpp>
#include <bitcoin/bitcoin/error.hpp>
#include <bitcoin/bitcoin/message/address.hpp>
#include <bitcoin/bitcoin/message/get_address.hpp>
#include <bitcoin/bitcoin/message/network_address.hpp>
#include <bitcoin/bitcoin/network/channel.hpp>
#include <bitcoin/bitcoin/network/protocol_base.hpp>
#include <bitcoin/bitcoin/utility/assert.hpp>
#include <bitcoin/bitcoin/utility/deadline.hpp>
#include <bitcoin/bitcoin/utility/dispatcher.hpp>
#include <bitcoin/bitcoin/utility/synchronizer.hpp>
#include <bitcoin/bitcoin/utility/threadpool.hpp>

INITIALIZE_TRACK(bc::network::protocol_seed);

namespace libbitcoin {
namespace network {

using namespace bc::message;
using std::placeholders::_1;
using std::placeholders::_2;
#define CLASS protocol_seed

// Require three callbacks (or any error) before calling complete.
protocol_seed::protocol_seed(channel::ptr peer, threadpool& pool,
    const asio::duration& timeout, handler complete, hosts& hosts,
    const config::authority& self)
  : hosts_(hosts), self_(self),
    protocol_base(peer, pool, timeout, synchronize(complete, 3, "seed")),
    track<protocol_seed>("protocol_seed", LOG_NETWORK)
{
}

void protocol_seed::start()
{
    protocol_base::start();

    if (self_.port() == 0)
    {
        callback(error::success);
    }
    else
    {
        address self({ { self_.to_network_address() } });
        SEND1(self, handle_send_address, _1);
    }

    if (hosts_.capacity() == 0)
    {
        // Error return ends synchronized completion callback.
        callback(error::not_found);
        return;
    }

    SUBSCRIBE2(address, handle_receive_address, _1, _2);
    SEND1(get_address(), handle_send_get_address, _1);
}

void protocol_seed::handle_receive_address(const code& ec,
    const address& message)
{
    if (stopped())
        return;

    if (ec)
    {
        // We are getting here with channel stopped because this session
        // doesn't register a stop handler. We may be getting stopped due to
        // failure to handle ping on this session.
        log_debug(LOG_PROTOCOL)
            << "Failure receiving addresses from seed [" << authority() << "] "
            << ec.message();
        callback(ec);
        return;
    }

    log_debug(LOG_PROTOCOL)
        << "Storing addresses from seed [" << authority() << "] ("
        << message.addresses.size() << ")";

    // TODO: manage timestamps (active peers are connected < 3 hours ago).
    hosts_.store(message.addresses, BIND1(handle_store_addresses, _1));
}

void protocol_seed::handle_send_address(const code& ec) const
{
    if (stopped())
        return;

    if (ec)
        log_debug(LOG_PROTOCOL)
            << "Failure sending address to seed [" << authority() << "] "
            << ec.message();

    // 1 of 3
    callback(ec);
}

void protocol_seed::handle_send_get_address(const code& ec) const
{
    if (stopped())
        return;

    if (ec)
        log_debug(LOG_PROTOCOL)
            << "Failure sending get_address to seed [" << authority() << "] "
            << ec.message();

    // 2 of 3
    callback(ec);
}

void protocol_seed::handle_store_addresses(const code& ec) const
{
    if (stopped())
        return;

    if (ec)
        log_error(LOG_PROTOCOL)
            << "Failure storing addresses from seed [" << authority() << "] "
            << ec.message();

    // 3 of 3
    callback(ec);
}

#undef CLASS

} // namespace network
} // namespace libbitcoin
<|endoftext|>


<commit_before>#include "NodeAlbum.h"
#include "NodeTrack.h"
#include "NodeArtist.h"
#include "../spotify/Track.h"

NodeAlbum::NodeAlbum(std::unique_ptr<Album> _album) : album(std::move(_album)) {
  album->nodeObject = this;
};

NodeAlbum::~NodeAlbum() {
  if(album->nodeObject == this) {
    album->nodeObject = nullptr;
  }
}

NAN_GETTER(NodeAlbum::getName) {
  NodeAlbum* nodeAlbum = node::ObjectWrap::Unwrap<NodeAlbum>(info.This());
  NanReturnValue(Nan::New<String>(nodeAlbum->album->name().c_str()).ToLocalChecked());
}

NAN_GETTER(NodeAlbum::getLink) {
  NodeAlbum* nodeAlbum = node::ObjectWrap::Unwrap<NodeAlbum>(info.This());
  NanReturnValue(Nan::New<String>(nodeAlbum->album->link().c_str()).ToLocalChecked());
}

NAN_METHOD(NodeAlbum::getCoverBase64) {
  NodeAlbum* nodeAlbum = node::ObjectWrap::Unwrap<NodeAlbum>(info.This());
  NanReturnValue(Nan::New<String>(nodeAlbum->album->coverBase64().c_str()).ToLocalChecked());
}

NAN_METHOD(NodeAlbum::browse) {
  NodeAlbum* nodeAlbum = node::ObjectWrap::Unwrap<NodeAlbum>(info.This());
  if(nodeAlbum->album->albumBrowse == nullptr) {
    nodeAlbum->makePersistent();
    nodeAlbum->browseCompleteCallback.SetFunction(args[0].As<Function>());

    //Mutate the V8 object.
    Handle<Object> nodeAlbumV8 = NanObjectWrapHandle(nodeAlbum);
    nodeAlbumV8->SetAccessor(Nan::New<String>("tracks").ToLocalChecked(), getTracks);
    nodeAlbumV8->SetAccessor(Nan::New<String>("review").ToLocalChecked(), getReview);
    nodeAlbumV8->SetAccessor(Nan::New<String>("copyrights").ToLocalChecked(), getCopyrights);
    nodeAlbumV8->SetAccessor(Nan::New<String>("artist").ToLocalChecked(), getArtist);

    nodeAlbum->album->browse();
  } else {
    nodeAlbum->callBrowseComplete();
  }
  NanReturnUndefined();
}

NAN_GETTER(NodeAlbum::getTracks) {
  NodeAlbum* nodeAlbum = node::ObjectWrap::Unwrap<NodeAlbum>(info.This());
  std::vector<std::shared_ptr<Track>> tracks = nodeAlbum->album->tracks();
  Handle<Array> nodeTracks = NanNew<Array>(tracks.size());
  for(int i = 0; i < (int)tracks.size(); i++) {
    NodeTrack* nodeTrack = new NodeTrack(tracks[i]);
    nodeTracks->Set(Nan::New<Number>(i), nodeTrack->createInstance());
  }
  NanReturnValue(nodeTracks);
}

NAN_GETTER(NodeAlbum::getReview) {
  NodeAlbum* nodeAlbum = node::ObjectWrap::Unwrap<NodeAlbum>(info.This());
  NanReturnValue(Nan::New<String>(nodeAlbum->album->review().c_str()).ToLocalChecked());
}

NAN_GETTER(NodeAlbum::getCopyrights) {
  NodeAlbum* nodeAlbum = node::ObjectWrap::Unwrap<NodeAlbum>(info.This());
  std::vector<std::string> copyrights = nodeAlbum->album->copyrights();
  Handle<Array> nodeCopyrights = NanNew<Array>(copyrights.size());
  for(int i = 0; i < (int)copyrights.size(); i++) {
    nodeCopyrights->Set(Nan::New<Number>(i), Nan::New<String>(copyrights[i].c_str()).ToLocalChecked());
  }
  NanReturnValue(nodeCopyrights);
}

NAN_GETTER(NodeAlbum::getArtist) {
  NodeAlbum* nodeAlbum = node::ObjectWrap::Unwrap<NodeAlbum>(info.This());
  NodeArtist* nodeArtist = new NodeArtist(nodeAlbum->album->artist());
  NanReturnValue(nodeArtist->createInstance());
}

NAN_GETTER(NodeAlbum::isLoaded) {
  NodeAlbum* nodeAlbum = node::ObjectWrap::Unwrap<NodeAlbum>(info.This());
  NanReturnValue(NanNew<Boolean>(nodeAlbum->album->isLoaded()));
}

void NodeAlbum::init() {
  NanScope();
  Handle<FunctionTemplate> constructorTemplate = NodeWrapped::init("Album");
  constructorTemplate->InstanceTemplate()->SetAccessor(Nan::New<String>("name").ToLocalChecked(), getName);
  constructorTemplate->InstanceTemplate()->SetAccessor(Nan::New<String>("link").ToLocalChecked(), getLink);
  constructorTemplate->InstanceTemplate()->SetAccessor(Nan::New<String>("isLoaded").ToLocalChecked(), isLoaded);
  NODE_SET_PROTOTYPE_METHOD(constructorTemplate, "getCoverBase64", getCoverBase64);
  NODE_SET_PROTOTYPE_METHOD(constructorTemplate, "browse", browse);
  NanAssignPersistent(NodeAlbum::constructorTemplate, constructorTemplate);
}
<commit_msg>Fix NodeAlbum return values and init method.<commit_after>#include "NodeAlbum.h"
#include "NodeTrack.h"
#include "NodeArtist.h"
#include "../spotify/Track.h"

NodeAlbum::NodeAlbum(std::unique_ptr<Album> _album) : album(std::move(_album)) {
  album->nodeObject = this;
};

NodeAlbum::~NodeAlbum() {
  if(album->nodeObject == this) {
    album->nodeObject = nullptr;
  }
}

NAN_GETTER(NodeAlbum::getName) {
  NodeAlbum* nodeAlbum = node::ObjectWrap::Unwrap<NodeAlbum>(info.This());
  info.GetReturnValue().Set(Nan::New<String>(nodeAlbum->album->name().c_str()).ToLocalChecked());
}

NAN_GETTER(NodeAlbum::getLink) {
  NodeAlbum* nodeAlbum = node::ObjectWrap::Unwrap<NodeAlbum>(info.This());
  info.GetReturnValue().Set(Nan::New<String>(nodeAlbum->album->link().c_str()).ToLocalChecked());
}

NAN_METHOD(NodeAlbum::getCoverBase64) {
  NodeAlbum* nodeAlbum = node::ObjectWrap::Unwrap<NodeAlbum>(info.This());
  info.GetReturnValue().Set(Nan::New<String>(nodeAlbum->album->coverBase64().c_str()).ToLocalChecked());
}

NAN_METHOD(NodeAlbum::browse) {
  NodeAlbum* nodeAlbum = node::ObjectWrap::Unwrap<NodeAlbum>(info.This());
  if(nodeAlbum->album->albumBrowse == nullptr) {
    nodeAlbum->makePersistent();
    nodeAlbum->browseCompleteCallback.SetFunction(info[0].As<Function>());

    //Mutate the V8 object.
    Handle<Object> nodeAlbumV8 = nodeAlbum->handle();
    Nan::SetAccessor(nodeAlbumV8, Nan::New<String>("tracks").ToLocalChecked(), getTracks);
    Nan::SetAccessor(nodeAlbumV8, Nan::New<String>("review").ToLocalChecked(), getReview);
    Nan::SetAccessor(nodeAlbumV8, Nan::New<String>("copyrights").ToLocalChecked(), getCopyrights);
    Nan::SetAccessor(nodeAlbumV8, Nan::New<String>("artist").ToLocalChecked(), getArtist);

    nodeAlbum->album->browse();
  } else {
    nodeAlbum->callBrowseComplete();
  }
  info.GetReturnValue().SetUndefined();
}

NAN_GETTER(NodeAlbum::getTracks) {
  NodeAlbum* nodeAlbum = node::ObjectWrap::Unwrap<NodeAlbum>(info.This());
  std::vector<std::shared_ptr<Track>> tracks = nodeAlbum->album->tracks();
  Handle<Array> nodeTracks = Nan::New<Array>(tracks.size());
  for(int i = 0; i < (int)tracks.size(); i++) {
    NodeTrack* nodeTrack = new NodeTrack(tracks[i]);
    nodeTracks->Set(Nan::New<Number>(i), nodeTrack->createInstance());
  }
  info.GetReturnValue().Set(nodeTracks);
}

NAN_GETTER(NodeAlbum::getReview) {
  NodeAlbum* nodeAlbum = node::ObjectWrap::Unwrap<NodeAlbum>(info.This());
  info.GetReturnValue().Set(Nan::New<String>(nodeAlbum->album->review().c_str()).ToLocalChecked());
}

NAN_GETTER(NodeAlbum::getCopyrights) {
  NodeAlbum* nodeAlbum = node::ObjectWrap::Unwrap<NodeAlbum>(info.This());
  std::vector<std::string> copyrights = nodeAlbum->album->copyrights();
  Handle<Array> nodeCopyrights = Nan::New<Array>(copyrights.size());
  for(int i = 0; i < (int)copyrights.size(); i++) {
    nodeCopyrights->Set(Nan::New<Number>(i), Nan::New<String>(copyrights[i].c_str()).ToLocalChecked());
  }
  info.GetReturnValue().Set(nodeCopyrights);
}

NAN_GETTER(NodeAlbum::getArtist) {
  NodeAlbum* nodeAlbum = node::ObjectWrap::Unwrap<NodeAlbum>(info.This());
  NodeArtist* nodeArtist = new NodeArtist(nodeAlbum->album->artist());
  info.GetReturnValue().Set(nodeArtist->createInstance());
}

NAN_GETTER(NodeAlbum::isLoaded) {
  NodeAlbum* nodeAlbum = node::ObjectWrap::Unwrap<NodeAlbum>(info.This());
  info.GetReturnValue().Set(Nan::New<Boolean>(nodeAlbum->album->isLoaded()));
}

void NodeAlbum::init() {
  Handle<FunctionTemplate> constructorTemplate = NodeWrapped::init("Album");
  Nan::SetAccessor(constructorTemplate->InstanceTemplate(), Nan::New<String>("name").ToLocalChecked(), getName);
  Nan::SetAccessor(constructorTemplate->InstanceTemplate(), Nan::New<String>("link").ToLocalChecked(), getLink);
  Nan::SetAccessor(constructorTemplate->InstanceTemplate(), Nan::New<String>("isLoaded").ToLocalChecked(), isLoaded);
  Nan::SetMethod(constructorTemplate, "getCoverBase64", getCoverBase64);
  Nan::SetMethod(constructorTemplate, "browse", browse);
  NodeAlbum::constructorTemplate.Reset(constructorTemplate);
}
<|endoftext|>


<commit_before>#include <hop_bits/optimisationAlgorithm.hpp>

#include <limits>

namespace hop {
  OptimisationAlgorithm::OptimisationAlgorithm(const std::shared_ptr<OptimisationProblem> optimisationProblem)
    : optimisationProblem_(optimisationProblem) {
    setMaximalNumberOfIterations(1000);
  }

  void OptimisationAlgorithm::optimise() {
    bestObjectiveValue_ = std::numeric_limits<double>::infinity();
    bestSolution_ = arma::Col<double>({});
    numberOfIterations_ = 0;
    optimisationProblem_->reset();

    return optimiseImplementation();
  }

  double OptimisationAlgorithm::getBestObjectiveValue() const {
    return bestObjectiveValue_;
  }

  arma::Col<double> OptimisationAlgorithm::getBestSolution() const {
    return bestSolution_;
  }

  bool OptimisationAlgorithm::isFinished() const {
    return (bestObjectiveValue_ <= optimisationProblem_->getAcceptableObjectiveValue());
  }

  bool OptimisationAlgorithm::isTerminated() const {
    return (numberOfIterations_ >= maximalNumberOfIterations_);
  }

  unsigned int OptimisationAlgorithm::getNumberOfIterations() const {
    return numberOfIterations_;
  }

  void OptimisationAlgorithm::setMaximalNumberOfIterations(const unsigned int& maximalNumberOfIterations) {
    maximalNumberOfIterations_ = maximalNumberOfIterations;
  }
}
<commit_msg>feat: Added reset function<commit_after>#include <hop_bits/optimisationAlgorithm.hpp>

// C++ STL
#include <limits>

namespace hop {
  OptimisationAlgorithm::OptimisationAlgorithm(const std::shared_ptr<OptimisationProblem> optimisationProblem)
    : optimisationProblem_(optimisationProblem) {
    setMaximalNumberOfIterations(1000);
    reset();
  }

  void OptimisationAlgorithm::optimise() {
    reset();
    return optimiseImplementation();
  }

  double OptimisationAlgorithm::getBestObjectiveValue() const {
    return bestObjectiveValue_;
  }

  arma::Col<double> OptimisationAlgorithm::getBestSolution() const {
    return bestSolution_;
  }

  bool OptimisationAlgorithm::isFinished() const {
    return (bestObjectiveValue_ <= optimisationProblem_->getAcceptableObjectiveValue());
  }

  bool OptimisationAlgorithm::isTerminated() const {
    return (numberOfIterations_ >= maximalNumberOfIterations_);
  }

  unsigned int OptimisationAlgorithm::getNumberOfIterations() const {
    return numberOfIterations_;
  }

  void OptimisationAlgorithm::setMaximalNumberOfIterations(const unsigned int& maximalNumberOfIterations) {
    maximalNumberOfIterations_ = maximalNumberOfIterations;
  }

  void OptimisationAlgorithm::reset() {
    bestObjectiveValue_ = std::numeric_limits<double>::infinity();
    bestSolution_.fill(arma::datum::nan);
    numberOfIterations_ = 0;
    optimisationProblem_->reset();
  }
}
<|endoftext|>