<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: OOXMLDocumentImpl.cxx,v $
 *
 *  $Revision: 1.2 $
 *
 *  last change: $Author: hbrinkm $ $Date: 2007-02-21 15:06:33 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 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
 *
 ************************************************************************/

#ifndef _COM_SUN_STAR_XML_SAX_XPARSER_HPP_
#include <com/sun/star/xml/sax/XParser.hpp>
#endif

#include "OOXMLDocumentImpl.hxx"
#include "OOXMLSaxHandler.hxx"

namespace ooxml
{

OOXMLDocumentImpl::OOXMLDocumentImpl
(OOXMLStream::Pointer_t pStream)
: mpStream(pStream)
{
}

OOXMLDocumentImpl::~OOXMLDocumentImpl()
{
}

void OOXMLDocumentImpl::resolve(Stream & rStream)
{
    uno::Reference < xml::sax::XParser > oSaxParser = mpStream->getParser();

    if (oSaxParser.is())
    {
        uno::Reference<xml::sax::XDocumentHandler>
            xDocumentHandler
            (static_cast<cppu::OWeakObject *>
             (new OOXMLSaxHandler(rStream)), uno::UNO_QUERY);
        oSaxParser->setDocumentHandler( xDocumentHandler );

        uno::Reference<io::XInputStream> xInputStream =
            mpStream->getInputStream();

        struct xml::sax::InputSource oInputSource;
        oInputSource.aInputStream = xInputStream;
        oSaxParser->parseStream(oInputSource);

        xInputStream->closeInput();
    }

    rStream.info("Test");
}

string OOXMLDocumentImpl::getType() const
{
    return "OOXMLDocumentImpl";
}

OOXMLDocument *
OOXMLDocumentFactory::createDocument
(OOXMLStream::Pointer_t pStream)
{
    return new OOXMLDocumentImpl(pStream);
}

}
<commit_msg>resolve styles stream<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: OOXMLDocumentImpl.cxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: hbrinkm $ $Date: 2007-03-16 12:48:46 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 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
 *
 ************************************************************************/

#ifndef _COM_SUN_STAR_XML_SAX_XPARSER_HPP_
#include <com/sun/star/xml/sax/XParser.hpp>
#endif

#include "OOXMLDocumentImpl.hxx"
#include "OOXMLSaxHandler.hxx"

#include <iostream>

namespace ooxml
{

using namespace ::std;

OOXMLDocumentImpl::OOXMLDocumentImpl
(OOXMLStream::Pointer_t pStream)
: mpStream(pStream)
{
}

OOXMLDocumentImpl::~OOXMLDocumentImpl()
{
}

void OOXMLDocumentImpl::resolve(Stream & rStream)
{
    {
        uno::Reference < xml::sax::XParser > oSaxParser = mpStream->getParser();

        if (oSaxParser.is())
        {
            uno::Reference<xml::sax::XDocumentHandler>
                xDocumentHandler
                (static_cast<cppu::OWeakObject *>
                 (new OOXMLSaxHandler(rStream)), uno::UNO_QUERY);
            oSaxParser->setDocumentHandler( xDocumentHandler );

            OOXMLStream::Pointer_t pStylesStream
                (OOXMLDocumentFactory::createStream(mpStream,
                                                    OOXMLStream::TYPES));

            uno::Reference < xml::sax::XParser > oStylesSaxParser =
                pStylesStream->getParser();

            if (oStylesSaxParser.is())
            {
                uno::Reference<xml::sax::XDocumentHandler>
                    xStylesDocumentHandler
                    (static_cast<cppu::OWeakObject *>
                     (new OOXMLSaxHandler(rStream)), uno::UNO_QUERY);
                oStylesSaxParser->setDocumentHandler( xStylesDocumentHandler );

                uno::Reference<io::XInputStream> xStylesInputStream =
                    pStylesStream->getInputStream();

//                 uno::Sequence<sal_Int8> aSeq(1024);
//                 while (xStylesInputStream->readBytes(aSeq, 1024) > 0)
//                 {
//                     string tmpStr(reinterpret_cast<char *>(&aSeq[0]));

//                     clog << tmpStr;
//                 }
                struct xml::sax::InputSource oStylesInputSource;
                oStylesInputSource.aInputStream = xStylesInputStream;
                oStylesSaxParser->parseStream(oStylesInputSource);

                xStylesInputStream->closeInput();

            }

            uno::Reference<io::XInputStream> xInputStream =
                mpStream->getInputStream();

            struct xml::sax::InputSource oInputSource;
            oInputSource.aInputStream = xInputStream;
            oSaxParser->parseStream(oInputSource);

            xInputStream->closeInput();
        }
    }
}

string OOXMLDocumentImpl::getType() const
{
    return "OOXMLDocumentImpl";
}

OOXMLDocument *
OOXMLDocumentFactory::createDocument
(OOXMLStream::Pointer_t pStream)
{
    return new OOXMLDocumentImpl(pStream);
}

}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: xmllib_export.cxx,v $
 *
 *  $Revision: 1.9 $
 *
 *  last change: $Author: hr $ $Date: 2004-11-09 12:36:32 $
 *
 *  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): _______________________________________
 *
 *
 ************************************************************************/

#include <xmlscript/xmllib_imexp.hxx>
#include <xmlscript/xml_helper.hxx>

using namespace com::sun::star::uno;
using namespace com::sun::star;
using namespace rtl;

namespace xmlscript
{

static OUString aTrueStr ( RTL_CONSTASCII_USTRINGPARAM("true") );
static OUString aFalseStr( RTL_CONSTASCII_USTRINGPARAM("false") );

//##################################################################################################

//==================================================================================================

void
SAL_CALL exportLibraryContainer(
    Reference< xml::sax::XExtendedDocumentHandler > const & xOut,
    const LibDescriptorArray* pLibArray )
        SAL_THROW( (Exception) )
{
    xOut->startDocument();

    OUString aDocTypeStr( RTL_CONSTASCII_USTRINGPARAM(
        "<!DOCTYPE library:libraries PUBLIC \"-//OpenOffice.org//DTD OfficeDocument 1.0//EN\""
        " \"libraries.dtd\">" ) );
    xOut->unknown( aDocTypeStr );
    xOut->ignorableWhitespace( OUString() );

    OUString aLibrariesName( RTL_CONSTASCII_USTRINGPARAM(XMLNS_LIBRARY_PREFIX ":libraries") );
    XMLElement* pLibsElement = new XMLElement( aLibrariesName );
    Reference< xml::sax::XAttributeList > xAttributes( pLibsElement );

    pLibsElement->addAttribute( OUString( RTL_CONSTASCII_USTRINGPARAM("xmlns:" XMLNS_LIBRARY_PREFIX) ),
                                OUString( RTL_CONSTASCII_USTRINGPARAM(XMLNS_LIBRARY_URI) ) );
    pLibsElement->addAttribute( OUString( RTL_CONSTASCII_USTRINGPARAM("xmlns:" XMLNS_XLINK_PREFIX) ),
                                OUString( RTL_CONSTASCII_USTRINGPARAM(XMLNS_XLINK_URI) ) );

    xOut->ignorableWhitespace( OUString() );
    xOut->startElement( aLibrariesName, xAttributes );

    int nLibCount = pLibArray->mnLibCount;
    for( sal_Int32 i = 0 ; i < nLibCount ; i++ )
    {
        LibDescriptor& rLib = pLibArray->mpLibs[i];

        OUString aLibraryName( RTL_CONSTASCII_USTRINGPARAM(XMLNS_LIBRARY_PREFIX ":library") );
        XMLElement* pLibElement = new XMLElement( aLibraryName );
        Reference< xml::sax::XAttributeList > xLibElementAttribs;
        xLibElementAttribs = static_cast< xml::sax::XAttributeList* >( pLibElement );

        pLibElement->addAttribute( OUString( RTL_CONSTASCII_USTRINGPARAM(XMLNS_LIBRARY_PREFIX ":name") ),
                                    rLib.aName );

        if( rLib.aStorageURL.getLength() )
        {
            pLibElement->addAttribute( OUString( RTL_CONSTASCII_USTRINGPARAM(XMLNS_XLINK_PREFIX ":href") ),
                                        rLib.aStorageURL );
            pLibElement->addAttribute( OUString( RTL_CONSTASCII_USTRINGPARAM(XMLNS_XLINK_PREFIX ":type") ),
                                        OUString( RTL_CONSTASCII_USTRINGPARAM("simple") ) );
        }

        pLibElement->addAttribute( OUString( RTL_CONSTASCII_USTRINGPARAM(XMLNS_LIBRARY_PREFIX ":link") ),
                                    rLib.bLink ? aTrueStr : aFalseStr );

        if( rLib.bLink )
        {
            pLibElement->addAttribute( OUString( RTL_CONSTASCII_USTRINGPARAM(XMLNS_LIBRARY_PREFIX ":readonly") ),
                                        rLib.bReadOnly ? aTrueStr : aFalseStr );
        }

        pLibElement->dump( xOut.get() );
    }

    xOut->ignorableWhitespace( OUString() );
    xOut->endElement( aLibrariesName );

    xOut->endDocument();
}

//==================================================================================================

void
SAL_CALL exportLibrary(
    ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XExtendedDocumentHandler > const & xOut,
    const LibDescriptor& rLib )
        SAL_THROW( (::com::sun::star::uno::Exception) )
{
    xOut->startDocument();

    OUString aDocTypeStr( RTL_CONSTASCII_USTRINGPARAM(
        "<!DOCTYPE library:library PUBLIC \"-//OpenOffice.org//DTD OfficeDocument 1.0//EN\""
        " \"library.dtd\">" ) );
    xOut->unknown( aDocTypeStr );
    xOut->ignorableWhitespace( OUString() );

    OUString aLibraryName( RTL_CONSTASCII_USTRINGPARAM(XMLNS_LIBRARY_PREFIX ":library") );
    XMLElement* pLibElement = new XMLElement( aLibraryName );
    Reference< xml::sax::XAttributeList > xAttributes( pLibElement );

    pLibElement->addAttribute( OUString( RTL_CONSTASCII_USTRINGPARAM("xmlns:" XMLNS_LIBRARY_PREFIX) ),
                                OUString( RTL_CONSTASCII_USTRINGPARAM(XMLNS_LIBRARY_URI) ) );

    pLibElement->addAttribute( OUString( RTL_CONSTASCII_USTRINGPARAM(XMLNS_LIBRARY_PREFIX ":name") ),
                                rLib.aName );

    pLibElement->addAttribute( OUString( RTL_CONSTASCII_USTRINGPARAM(XMLNS_LIBRARY_PREFIX ":readonly") ),
                                rLib.bReadOnly ? aTrueStr : aFalseStr );

    pLibElement->addAttribute( OUString( RTL_CONSTASCII_USTRINGPARAM(XMLNS_LIBRARY_PREFIX ":passwordprotected") ),
                                rLib.bPasswordProtected ? aTrueStr : aFalseStr );

    if( rLib.bPreload )
        pLibElement->addAttribute( OUString( RTL_CONSTASCII_USTRINGPARAM(XMLNS_LIBRARY_PREFIX ":preload") ), aTrueStr );

    sal_Int32 nElementCount = rLib.aElementNames.getLength();
    if( nElementCount )
    {
        const OUString* pElementNames = rLib.aElementNames.getConstArray();
        for( sal_Int32 i = 0 ; i < nElementCount ; i++ )
        {
            XMLElement* pElement = new XMLElement( OUString( RTL_CONSTASCII_USTRINGPARAM(XMLNS_LIBRARY_PREFIX ":element" ) ) );
            Reference< xml::sax::XAttributeList > xElementAttribs;
            xElementAttribs = static_cast< xml::sax::XAttributeList* >( pElement );

            pElement->addAttribute( OUString( RTL_CONSTASCII_USTRINGPARAM(XMLNS_LIBRARY_PREFIX ":name") ),
                                        pElementNames[i] );

            pLibElement->addSubElement( pElement );
        }
    }

    pLibElement->dump( xOut.get() );

    xOut->endDocument();
}

};

<commit_msg>INTEGRATION: CWS ooo19126 (1.9.8); FILE MERGED 2005/09/05 18:40:24 rt 1.9.8.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: xmllib_export.cxx,v $
 *
 *  $Revision: 1.10 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-09 16:16:31 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 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
 *
 ************************************************************************/

#include <xmlscript/xmllib_imexp.hxx>
#include <xmlscript/xml_helper.hxx>

using namespace com::sun::star::uno;
using namespace com::sun::star;
using namespace rtl;

namespace xmlscript
{

static OUString aTrueStr ( RTL_CONSTASCII_USTRINGPARAM("true") );
static OUString aFalseStr( RTL_CONSTASCII_USTRINGPARAM("false") );

//##################################################################################################

//==================================================================================================

void
SAL_CALL exportLibraryContainer(
    Reference< xml::sax::XExtendedDocumentHandler > const & xOut,
    const LibDescriptorArray* pLibArray )
        SAL_THROW( (Exception) )
{
    xOut->startDocument();

    OUString aDocTypeStr( RTL_CONSTASCII_USTRINGPARAM(
        "<!DOCTYPE library:libraries PUBLIC \"-//OpenOffice.org//DTD OfficeDocument 1.0//EN\""
        " \"libraries.dtd\">" ) );
    xOut->unknown( aDocTypeStr );
    xOut->ignorableWhitespace( OUString() );

    OUString aLibrariesName( RTL_CONSTASCII_USTRINGPARAM(XMLNS_LIBRARY_PREFIX ":libraries") );
    XMLElement* pLibsElement = new XMLElement( aLibrariesName );
    Reference< xml::sax::XAttributeList > xAttributes( pLibsElement );

    pLibsElement->addAttribute( OUString( RTL_CONSTASCII_USTRINGPARAM("xmlns:" XMLNS_LIBRARY_PREFIX) ),
                                OUString( RTL_CONSTASCII_USTRINGPARAM(XMLNS_LIBRARY_URI) ) );
    pLibsElement->addAttribute( OUString( RTL_CONSTASCII_USTRINGPARAM("xmlns:" XMLNS_XLINK_PREFIX) ),
                                OUString( RTL_CONSTASCII_USTRINGPARAM(XMLNS_XLINK_URI) ) );

    xOut->ignorableWhitespace( OUString() );
    xOut->startElement( aLibrariesName, xAttributes );

    int nLibCount = pLibArray->mnLibCount;
    for( sal_Int32 i = 0 ; i < nLibCount ; i++ )
    {
        LibDescriptor& rLib = pLibArray->mpLibs[i];

        OUString aLibraryName( RTL_CONSTASCII_USTRINGPARAM(XMLNS_LIBRARY_PREFIX ":library") );
        XMLElement* pLibElement = new XMLElement( aLibraryName );
        Reference< xml::sax::XAttributeList > xLibElementAttribs;
        xLibElementAttribs = static_cast< xml::sax::XAttributeList* >( pLibElement );

        pLibElement->addAttribute( OUString( RTL_CONSTASCII_USTRINGPARAM(XMLNS_LIBRARY_PREFIX ":name") ),
                                    rLib.aName );

        if( rLib.aStorageURL.getLength() )
        {
            pLibElement->addAttribute( OUString( RTL_CONSTASCII_USTRINGPARAM(XMLNS_XLINK_PREFIX ":href") ),
                                        rLib.aStorageURL );
            pLibElement->addAttribute( OUString( RTL_CONSTASCII_USTRINGPARAM(XMLNS_XLINK_PREFIX ":type") ),
                                        OUString( RTL_CONSTASCII_USTRINGPARAM("simple") ) );
        }

        pLibElement->addAttribute( OUString( RTL_CONSTASCII_USTRINGPARAM(XMLNS_LIBRARY_PREFIX ":link") ),
                                    rLib.bLink ? aTrueStr : aFalseStr );

        if( rLib.bLink )
        {
            pLibElement->addAttribute( OUString( RTL_CONSTASCII_USTRINGPARAM(XMLNS_LIBRARY_PREFIX ":readonly") ),
                                        rLib.bReadOnly ? aTrueStr : aFalseStr );
        }

        pLibElement->dump( xOut.get() );
    }

    xOut->ignorableWhitespace( OUString() );
    xOut->endElement( aLibrariesName );

    xOut->endDocument();
}

//==================================================================================================

void
SAL_CALL exportLibrary(
    ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XExtendedDocumentHandler > const & xOut,
    const LibDescriptor& rLib )
        SAL_THROW( (::com::sun::star::uno::Exception) )
{
    xOut->startDocument();

    OUString aDocTypeStr( RTL_CONSTASCII_USTRINGPARAM(
        "<!DOCTYPE library:library PUBLIC \"-//OpenOffice.org//DTD OfficeDocument 1.0//EN\""
        " \"library.dtd\">" ) );
    xOut->unknown( aDocTypeStr );
    xOut->ignorableWhitespace( OUString() );

    OUString aLibraryName( RTL_CONSTASCII_USTRINGPARAM(XMLNS_LIBRARY_PREFIX ":library") );
    XMLElement* pLibElement = new XMLElement( aLibraryName );
    Reference< xml::sax::XAttributeList > xAttributes( pLibElement );

    pLibElement->addAttribute( OUString( RTL_CONSTASCII_USTRINGPARAM("xmlns:" XMLNS_LIBRARY_PREFIX) ),
                                OUString( RTL_CONSTASCII_USTRINGPARAM(XMLNS_LIBRARY_URI) ) );

    pLibElement->addAttribute( OUString( RTL_CONSTASCII_USTRINGPARAM(XMLNS_LIBRARY_PREFIX ":name") ),
                                rLib.aName );

    pLibElement->addAttribute( OUString( RTL_CONSTASCII_USTRINGPARAM(XMLNS_LIBRARY_PREFIX ":readonly") ),
                                rLib.bReadOnly ? aTrueStr : aFalseStr );

    pLibElement->addAttribute( OUString( RTL_CONSTASCII_USTRINGPARAM(XMLNS_LIBRARY_PREFIX ":passwordprotected") ),
                                rLib.bPasswordProtected ? aTrueStr : aFalseStr );

    if( rLib.bPreload )
        pLibElement->addAttribute( OUString( RTL_CONSTASCII_USTRINGPARAM(XMLNS_LIBRARY_PREFIX ":preload") ), aTrueStr );

    sal_Int32 nElementCount = rLib.aElementNames.getLength();
    if( nElementCount )
    {
        const OUString* pElementNames = rLib.aElementNames.getConstArray();
        for( sal_Int32 i = 0 ; i < nElementCount ; i++ )
        {
            XMLElement* pElement = new XMLElement( OUString( RTL_CONSTASCII_USTRINGPARAM(XMLNS_LIBRARY_PREFIX ":element" ) ) );
            Reference< xml::sax::XAttributeList > xElementAttribs;
            xElementAttribs = static_cast< xml::sax::XAttributeList* >( pElement );

            pElement->addAttribute( OUString( RTL_CONSTASCII_USTRINGPARAM(XMLNS_LIBRARY_PREFIX ":name") ),
                                        pElementNames[i] );

            pLibElement->addSubElement( pElement );
        }
    }

    pLibElement->dump( xOut.get() );

    xOut->endDocument();
}

};

<|endoftext|>


<commit_before><commit_msg>Broken code<commit_after><|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: saltimer.cxx,v $
 *
 *  $Revision: 1.11 $
 *
 *  last change: $Author: hr $ $Date: 2006-08-11 17:50:28 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 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
 *
 ************************************************************************/

#include <stdio.h>
#if defined(IRIX)
#include <ctime>
#endif
#include <sys/time.h>
#include <sys/times.h>
#include <time.h>
#include <unistd.h>

#include <salunx.h>

#ifndef _SV_SALDATA_HXX
#include <saldata.hxx>
#endif
#ifndef _SV_SALDISP_HXX
#include <saldisp.hxx>
#endif
#ifndef _SV_SALTIMER_H
#include <saltimer.h>
#endif
#ifndef _SV_SALINST_H
#include <salinst.h>
#endif

// -=-= SalData =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
// -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
void X11SalData::Timeout() const
{
    ImplSVData* pSVData = ImplGetSVData();
    if( pSVData->mpSalTimer )
        pSVData->mpSalTimer->CallCallback();
}

// -=-= SalXLib =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
// -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
void SalXLib::StopTimer()
{
    m_aTimeout.tv_sec   = 0;
    m_aTimeout.tv_usec  = 0;
    m_nTimeoutMS        = 0;
}

void SalXLib::StartTimer( ULONG nMS )
{
    timeval Timeout (m_aTimeout); // previous timeout.
    gettimeofday (&m_aTimeout, 0);

    m_nTimeoutMS  = nMS;
    m_aTimeout    += m_nTimeoutMS;

    if ((Timeout > m_aTimeout) || (Timeout.tv_sec == 0))
    {
        // Wakeup from previous timeout (or stopped timer).
        Wakeup();
    }
}

// -=-= SalTimer -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
// -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
SalTimer* X11SalInstance::CreateSalTimer()
{
    return new X11SalTimer();
}

X11SalTimer::~X11SalTimer()
{
}

void X11SalTimer::Stop()
{
    GetX11SalData()->GetLib()->StopTimer();
}

void X11SalTimer::Start( ULONG nMS )
{
    GetX11SalData()->GetLib()->StartTimer( nMS );
}

<commit_msg>INTEGRATION: CWS pchfix02 (1.11.4); FILE MERGED 2006/09/01 17:58:06 kaib 1.11.4.1: #i68856# Added header markers and pch files<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: saltimer.cxx,v $
 *
 *  $Revision: 1.12 $
 *
 *  last change: $Author: obo $ $Date: 2006-09-17 12:35:56 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 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
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_vcl.hxx"

#include <stdio.h>
#if defined(IRIX)
#include <ctime>
#endif
#include <sys/time.h>
#include <sys/times.h>
#include <time.h>
#include <unistd.h>

#include <salunx.h>

#ifndef _SV_SALDATA_HXX
#include <saldata.hxx>
#endif
#ifndef _SV_SALDISP_HXX
#include <saldisp.hxx>
#endif
#ifndef _SV_SALTIMER_H
#include <saltimer.h>
#endif
#ifndef _SV_SALINST_H
#include <salinst.h>
#endif

// -=-= SalData =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
// -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
void X11SalData::Timeout() const
{
    ImplSVData* pSVData = ImplGetSVData();
    if( pSVData->mpSalTimer )
        pSVData->mpSalTimer->CallCallback();
}

// -=-= SalXLib =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
// -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
void SalXLib::StopTimer()
{
    m_aTimeout.tv_sec   = 0;
    m_aTimeout.tv_usec  = 0;
    m_nTimeoutMS        = 0;
}

void SalXLib::StartTimer( ULONG nMS )
{
    timeval Timeout (m_aTimeout); // previous timeout.
    gettimeofday (&m_aTimeout, 0);

    m_nTimeoutMS  = nMS;
    m_aTimeout    += m_nTimeoutMS;

    if ((Timeout > m_aTimeout) || (Timeout.tv_sec == 0))
    {
        // Wakeup from previous timeout (or stopped timer).
        Wakeup();
    }
}

// -=-= SalTimer -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
// -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
SalTimer* X11SalInstance::CreateSalTimer()
{
    return new X11SalTimer();
}

X11SalTimer::~X11SalTimer()
{
}

void X11SalTimer::Stop()
{
    GetX11SalData()->GetLib()->StopTimer();
}

void X11SalTimer::Start( ULONG nMS )
{
    GetX11SalData()->GetLib()->StartTimer( nMS );
}

<|endoftext|>


<commit_before>
#include <iostream>
#include <fstream>
#include <list>
#include <vector>
#include <typeinfo>

#include <boost/numeric/ublas/io.hpp>
#include <boost/program_options.hpp>
#include <boost/foreach.hpp>
#include <boost/call_traits.hpp>
#include <boost/lexical_cast.hpp>

#include <scsi/base.h>
#include <scsi/state/vector.h>
#include <scsi/state/matrix.h>
#include <scsi/h5writer.h>

namespace po = boost::program_options;

namespace {

typedef std::vector<std::string> strvect;

strvect tokenize(const std::string& inp)
{
    strvect ret;
    size_t pos = 0;
    while(true) {
        size_t sep = inp.find_first_of(',', pos);
        if(sep==inp.npos) {
            ret.push_back(inp.substr(pos));
            break;
        } else if(sep!=pos) {
            ret.push_back(inp.substr(pos, sep-pos));
        } else {
            // ignore empty
        }
        pos = sep+1;
    }
    return ret;
}

static
void getargs(int argc, char *argv[], po::variables_map& args)
{
    std::ostringstream caption;
    caption<<argv[0]<<" [options] <lattice file>";
    po::options_description opts(caption.str());
    opts.add_options()
            ("help,h", "Display this message")
            ("verbose,v", po::value<std::string>()->default_value("0")->value_name("NUM"),
                "Make some noise")
            ("define,D", po::value<std::vector<std::string> >()->composing()->value_name("name=val"),
                "Override variable value (\"-Dname=value\")")
            ("lattice", po::value<std::string>()->value_name("FILE"),
                "Input lattice file")
            ("max,M", po::value<std::string>()->value_name("NUM"),
                "Maximum number of elements propagate through. (default is all)")
            ("format,F", po::value<std::string>()->value_name("FMT")->default_value("txt"),
                "output format (txt or hdf5)")
            ("select-all,A", "Select all elements for output")
            ("select-type,T", po::value<std::string>()->value_name("ETYPE"),
                "Select all elements of the given type for output")
            ("select-last,L", "Select last element for output")
            ;

    po::positional_options_description pos;
    pos.add("lattice", 1);

    po::store(po::command_line_parser(argc, argv).options(opts).positional(pos).run(), args);
    po::notify(args);

    if(args.count("help") || !args.count("lattice")) {
        std::cout<<opts<<"\n";
        exit(1);
    }
}

struct update_define : boost::static_visitor<Config::value_t>
{
    const std::string& value;
    update_define(const std::string& val) : value(val) {}

    Config::value_t operator()(double v) const
    {
        return boost::lexical_cast<double>(value);
    }
    Config::value_t operator()(const std::string& v) const
    {
        return value;
    }
    Config::value_t operator()(const std::vector<double>& v) const
    {
        throw std::runtime_error("-D can't set vector values");
    }
    Config::value_t operator()(const Config::vector_t& v) const
    {
        throw std::runtime_error("-D can't set Config values");
    }
};

struct ObserverFactory
{
    virtual ~ObserverFactory() {}
    virtual Observer *observe(Machine& M, ElementVoid* E) = 0;
    virtual void before_sim(Machine&) {}
    virtual void after_sim(Machine&) {}
};

struct StreamObserver : public Observer
{
    std::ostream *strm;
    StreamObserver(std::ostream& strm) :strm(&strm) {}
    virtual ~StreamObserver() {}
    virtual void view(const ElementVoid* elem, const StateBase* state)
    {
        (*strm)<<elem->index<<" "<<*state;
    }

    struct Factory : public ObserverFactory
    {
        std::auto_ptr<std::ostream> owned_strm;
        std::ostream *strm;
        Factory(const strvect& fmt) :strm(&std::cout)
        {
            assert(!fmt.empty() && fmt[0]=="txt");

            for(strvect::const_iterator it=fmt.begin()+1, end=fmt.end(); it!=end; ++it)
            {
                const std::string& cmd = *it;
                if(cmd.substr(0,5)=="file=") {
                    owned_strm.reset(new std::ofstream(cmd.substr(5).c_str()));
                    strm = owned_strm.get();
                } else {
                    std::cerr<<"Warning: -F "<<fmt[0]<<" includes unknown option "<<cmd<<"\n";
                }
            }
        }
        virtual ~Factory() {}
        virtual Observer *observe(Machine& M, ElementVoid* E)
        {
            return new StreamObserver(*strm);
        }

        virtual void after_sim(Machine&)
        {
            strm->flush();
        }
    };
};

struct H5Observer : public Observer
{
    H5StateWriter *writer;
    H5Observer(H5StateWriter *writer) : writer(writer) {}
    virtual ~H5Observer() {}

    struct Factory : public ObserverFactory
    {
        virtual ~Factory() {}
        std::auto_ptr<H5StateWriter> writer;
        Factory(const strvect& fmt)
        {
            assert(!fmt.empty() && fmt[0]=="hdf5");

            for(strvect::const_iterator it=fmt.begin()+1, end=fmt.end(); it!=end; ++it)
            {
                const std::string& cmd = *it;
                if(cmd.substr(0,5)=="file=") {
                    writer.reset(new H5StateWriter(cmd.substr(5)));
                } else {
                    std::cerr<<"Warning: -F "<<fmt[0]<<" includes unknown option "<<cmd<<"\n";
                }
            }
            if(!writer.get()) {
                std::cerr<<"Warning: hdf5 output format requires file=...\n";
            }
        }
        virtual Observer *observe(Machine &M, ElementVoid *E)
        {
            if(!writer.get()) return NULL;
            else              return new H5Observer(writer.get());
        }
        virtual void before_sim(Machine & M)
        {
            if(writer.get()) writer->setAttr("sim_type", M.simtype());
        }
        virtual void after_sim(Machine&)
        {
            if(writer.get()) writer->close();
            writer.reset();
        }
    };

    virtual void view(const ElementVoid *, const StateBase *state)
    {
        writer->append(state);
    }
};

} // namespace

int main(int argc, char *argv[])
{
try {
    po::variables_map args;
    getargs(argc, argv, args);

    std::auto_ptr<Config> conf;

    size_t verb = boost::lexical_cast<size_t>(args["verbose"].as<std::string>());
    if(verb<=2)
        H5StateWriter::dontPrint();

    try {
        GLPSParser P;
        conf.reset(P.parse_file(args["lattice"].as<std::string>().c_str()));
    }catch(std::exception& e){
        std::cerr<<"Parse error: "<<e.what()<<"\n";
        return 1;
    }

    if(args.count("define")) {
        const std::vector<std::string>& defs = args["define"].as<std::vector<std::string> >();

        BOOST_FOREACH(const std::string& def, defs) {
            size_t sep = def.find_first_of('=');
            if(sep==def.npos) {
                std::cerr<<"-D "<<def<<" missing '='\n";
                exit(1);
            } else if(sep==0) {
                std::cerr<<"-D "<<def<<" missing variable name\n";
                exit(1);
            }

            std::string name(def.substr(0,sep));

            Config::value_t curval;
            try {
                curval = conf->getAny(name);
            } catch(key_error& e) {
                std::cerr<<"-D "<<def<<" variable "<<name<<" does not exist.  -D may only redefine existing variables\n";
                exit(1);
            }

            conf->setAny(name, boost::apply_visitor(update_define(def.substr(sep+1)), curval));
        }
    }

    if(verb) {
        std::cout<<"# Reduced lattice\n";
        GLPSPrint(std::cout, *conf);
        std::cout<<"\n";
    }

    size_t maxelem = (size_t)-1;
    if(args.count("max")) {
        maxelem = boost::lexical_cast<size_t>(args["max"].as<std::string>());
    }

    // register state and element types
    registerLinear();
    registerMoment();
    registerMoment2();

    std::auto_ptr<ObserverFactory> ofact;

    {
        const std::string& ofactname = args["format"].as<std::string>();
        strvect fmt(tokenize(ofactname));

        if(fmt.empty()) {
            std::cerr<<"Empty output format\n";
            exit(1);
        } else if(fmt[0]=="txt") {
            ofact.reset(new StreamObserver::Factory(fmt));
        } else if(fmt[0]=="hdf5") {
            ofact.reset(new H5Observer::Factory(fmt));
        } else {
            std::cerr<<"Unknown output format \""<<ofactname<<"\"\n";
            exit(1);
        }
    }

    Machine sim(*conf);

    if(args.count("select-all")) {
        BOOST_FOREACH(ElementVoid *elem, sim) {
            assert(elem->observer()==NULL);
            elem->set_observer(ofact->observe(sim, elem));
        }
    }
    if(args.count("select-type")) {
        const std::string& etype = args["select-type"].as<std::string>();

        std::pair<Machine::lookup_iterator, Machine::lookup_iterator> S(sim.equal_range_type(etype));

        if(S.first==S.second) {
            std::cerr<<"Warning: --select-type "<<etype<<" does not match any elements\n";
        } else {
            for(; S.first!=S.second; ++S.first) {
                ElementVoid *elem = *S.first;

                if(elem->observer()==NULL) {
                    // don't replace existing Observer
                    elem->set_observer(ofact->observe(sim, elem));
                }
            }
        }
    }
    if(args.count("select-last") && sim.size()>0) {
        ElementVoid *elem = sim[sim.size()-1];

        if(elem->observer()==NULL) {
            // don't replace existing Observer
            elem->set_observer(ofact->observe(sim, elem));
        }
    }

    ofact->before_sim(sim);

    if(verb) {
        sim.set_trace(&std::cout);

        std::cout<<"# Machine configuration\n"<<sim<<"\n\n";
    }

    std::auto_ptr<StateBase> state(sim.allocState());
    sim.propagate(state.get(), 0, maxelem);

    ofact->after_sim(sim);

    if(verb) {
        std::cout << "\n# Final " << *state << "\n";
    }

    Machine::registeryCleanup();

    return 0;
}catch(std::exception& e){
    std::cerr<<"Error "<<typeid(e).name()<<" : "<<e.what()<<"\n";
    return 1;
}
}
<commit_msg>more online help for run_flame<commit_after>
#include <iostream>
#include <fstream>
#include <list>
#include <vector>
#include <typeinfo>

#include <boost/numeric/ublas/io.hpp>
#include <boost/program_options.hpp>
#include <boost/foreach.hpp>
#include <boost/call_traits.hpp>
#include <boost/lexical_cast.hpp>

#include <scsi/base.h>
#include <scsi/state/vector.h>
#include <scsi/state/matrix.h>
#include <scsi/h5writer.h>

namespace po = boost::program_options;

namespace {

typedef std::vector<std::string> strvect;

strvect tokenize(const std::string& inp)
{
    strvect ret;
    size_t pos = 0;
    while(true) {
        size_t sep = inp.find_first_of(',', pos);
        if(sep==inp.npos) {
            ret.push_back(inp.substr(pos));
            break;
        } else if(sep!=pos) {
            ret.push_back(inp.substr(pos, sep-pos));
        } else {
            // ignore empty
        }
        pos = sep+1;
    }
    return ret;
}

static
void getargs(int argc, char *argv[], po::variables_map& args)
{
    std::ostringstream caption;
    caption<<argv[0]<<" [options] <lattice file>";
    po::options_description opts(caption.str());
    opts.add_options()
            ("help,h", "Display this message")
            ("verbose,v", po::value<std::string>()->default_value("0")->value_name("NUM"),
                "Make some noise")
            ("define,D", po::value<std::vector<std::string> >()->composing()->value_name("name=val"),
                "Override variable value (\"-Dname=value\")")
            ("lattice", po::value<std::string>()->value_name("FILE"),
                "Input lattice file")
            ("max,M", po::value<std::string>()->value_name("NUM"),
                "Maximum number of elements propagate through. (default is all)")
            ("format,F", po::value<std::string>()->value_name("FMT")->default_value("txt"),
                "output format (txt or hdf5)")
            ("select-all,A", "Select all elements for output")
            ("select-type,T", po::value<std::string>()->value_name("ETYPE"),
                "Select all elements of the given type for output")
            ("select-last,L", "Select last element for output")
            ;

    po::positional_options_description pos;
    pos.add("lattice", 1);

    po::store(po::command_line_parser(argc, argv).options(opts).positional(pos).run(), args);
    po::notify(args);

    if(args.count("help") || !args.count("lattice")) {
        std::cout<<opts<<"\n\n"
                   "Output formats:\n\n"
                   " txt  - Print selected outputs states to screen ('--format txt' the default default)\n"
                   "        or file ('--format txt,file=out.txt')\n"
                   "\n"
                   " hdf5 - Write selected output states to an HDF5 file.\n"
                   "        eg. '--format hdf5,file=out.h5'\n";
        exit(1);
    }
}

struct update_define : boost::static_visitor<Config::value_t>
{
    const std::string& value;
    update_define(const std::string& val) : value(val) {}

    Config::value_t operator()(double v) const
    {
        return boost::lexical_cast<double>(value);
    }
    Config::value_t operator()(const std::string& v) const
    {
        return value;
    }
    Config::value_t operator()(const std::vector<double>& v) const
    {
        throw std::runtime_error("-D can't set vector values");
    }
    Config::value_t operator()(const Config::vector_t& v) const
    {
        throw std::runtime_error("-D can't set Config values");
    }
};

struct ObserverFactory
{
    virtual ~ObserverFactory() {}
    virtual Observer *observe(Machine& M, ElementVoid* E) = 0;
    virtual void before_sim(Machine&) {}
    virtual void after_sim(Machine&) {}
};

struct StreamObserver : public Observer
{
    std::ostream *strm;
    StreamObserver(std::ostream& strm) :strm(&strm) {}
    virtual ~StreamObserver() {}
    virtual void view(const ElementVoid* elem, const StateBase* state)
    {
        (*strm)<<"After Element ["<<elem->index<<"] "<<elem->name<<" "<<*state<<"\n";
    }

    struct Factory : public ObserverFactory
    {
        std::auto_ptr<std::ostream> owned_strm;
        std::ostream *strm;
        Factory(const strvect& fmt) :strm(&std::cout)
        {
            assert(!fmt.empty() && fmt[0]=="txt");

            for(strvect::const_iterator it=fmt.begin()+1, end=fmt.end(); it!=end; ++it)
            {
                const std::string& cmd = *it;
                if(cmd.substr(0,5)=="file=") {
                    owned_strm.reset(new std::ofstream(cmd.substr(5).c_str()));
                    strm = owned_strm.get();
                } else {
                    std::cerr<<"Warning: -F "<<fmt[0]<<" includes unknown option "<<cmd<<"\n";
                }
            }
        }
        virtual ~Factory() {}
        virtual Observer *observe(Machine& M, ElementVoid* E)
        {
            return new StreamObserver(*strm);
        }

        virtual void after_sim(Machine&)
        {
            strm->flush();
        }
    };
};

struct H5Observer : public Observer
{
    H5StateWriter *writer;
    H5Observer(H5StateWriter *writer) : writer(writer) {}
    virtual ~H5Observer() {}

    struct Factory : public ObserverFactory
    {
        virtual ~Factory() {}
        std::auto_ptr<H5StateWriter> writer;
        Factory(const strvect& fmt)
        {
            assert(!fmt.empty() && fmt[0]=="hdf5");

            for(strvect::const_iterator it=fmt.begin()+1, end=fmt.end(); it!=end; ++it)
            {
                const std::string& cmd = *it;
                if(cmd.substr(0,5)=="file=") {
                    writer.reset(new H5StateWriter(cmd.substr(5)));
                } else {
                    std::cerr<<"Warning: -F "<<fmt[0]<<" includes unknown option "<<cmd<<"\n";
                }
            }
            if(!writer.get()) {
                std::cerr<<"Warning: hdf5 output format requires file=...\n";
            }
        }
        virtual Observer *observe(Machine &M, ElementVoid *E)
        {
            if(!writer.get()) return NULL;
            else              return new H5Observer(writer.get());
        }
        virtual void before_sim(Machine & M)
        {
            if(writer.get()) writer->setAttr("sim_type", M.simtype());
        }
        virtual void after_sim(Machine&)
        {
            if(writer.get()) writer->close();
            writer.reset();
        }
    };

    virtual void view(const ElementVoid *, const StateBase *state)
    {
        writer->append(state);
    }
};

} // namespace

int main(int argc, char *argv[])
{
try {
    po::variables_map args;
    getargs(argc, argv, args);

    std::auto_ptr<Config> conf;

    size_t verb = boost::lexical_cast<size_t>(args["verbose"].as<std::string>());
    if(verb<=2)
        H5StateWriter::dontPrint();

    try {
        GLPSParser P;
        conf.reset(P.parse_file(args["lattice"].as<std::string>().c_str()));
    }catch(std::exception& e){
        std::cerr<<"Parse error: "<<e.what()<<"\n";
        return 1;
    }

    if(args.count("define")) {
        const std::vector<std::string>& defs = args["define"].as<std::vector<std::string> >();

        BOOST_FOREACH(const std::string& def, defs) {
            size_t sep = def.find_first_of('=');
            if(sep==def.npos) {
                std::cerr<<"-D "<<def<<" missing '='\n";
                exit(1);
            } else if(sep==0) {
                std::cerr<<"-D "<<def<<" missing variable name\n";
                exit(1);
            }

            std::string name(def.substr(0,sep));

            Config::value_t curval;
            try {
                curval = conf->getAny(name);
            } catch(key_error& e) {
                std::cerr<<"-D "<<def<<" variable "<<name<<" does not exist.  -D may only redefine existing variables\n";
                exit(1);
            }

            conf->setAny(name, boost::apply_visitor(update_define(def.substr(sep+1)), curval));
        }
    }

    if(verb) {
        std::cout<<"# Reduced lattice\n";
        GLPSPrint(std::cout, *conf);
        std::cout<<"\n";
    }

    size_t maxelem = (size_t)-1;
    if(args.count("max")) {
        maxelem = boost::lexical_cast<size_t>(args["max"].as<std::string>());
    }

    // register state and element types
    registerLinear();
    registerMoment();
    registerMoment2();

    std::auto_ptr<ObserverFactory> ofact;

    {
        const std::string& ofactname = args["format"].as<std::string>();
        strvect fmt(tokenize(ofactname));

        if(fmt.empty()) {
            std::cerr<<"Empty output format\n";
            exit(1);
        } else if(fmt[0]=="txt") {
            ofact.reset(new StreamObserver::Factory(fmt));
        } else if(fmt[0]=="hdf5") {
            ofact.reset(new H5Observer::Factory(fmt));
        } else {
            std::cerr<<"Unknown output format \""<<ofactname<<"\"\n";
            exit(1);
        }
    }

    Machine sim(*conf);

    if(args.count("select-all")) {
        BOOST_FOREACH(ElementVoid *elem, sim) {
            assert(elem->observer()==NULL);
            elem->set_observer(ofact->observe(sim, elem));
        }
    }
    if(args.count("select-type")) {
        const std::string& etype = args["select-type"].as<std::string>();

        std::pair<Machine::lookup_iterator, Machine::lookup_iterator> S(sim.equal_range_type(etype));

        if(S.first==S.second) {
            std::cerr<<"Warning: --select-type "<<etype<<" does not match any elements\n";
        } else {
            for(; S.first!=S.second; ++S.first) {
                ElementVoid *elem = *S.first;

                if(elem->observer()==NULL) {
                    // don't replace existing Observer
                    elem->set_observer(ofact->observe(sim, elem));
                }
            }
        }
    }
    if(args.count("select-last") && sim.size()>0) {
        ElementVoid *elem = sim[sim.size()-1];

        if(elem->observer()==NULL) {
            // don't replace existing Observer
            elem->set_observer(ofact->observe(sim, elem));
        }
    }

    ofact->before_sim(sim);

    if(verb) {
        sim.set_trace(&std::cout);

        std::cout<<"# Machine configuration\n"<<sim<<"\n\n";
    }

    std::auto_ptr<StateBase> state(sim.allocState());
    sim.propagate(state.get(), 0, maxelem);

    ofact->after_sim(sim);

    if(verb) {
        std::cout << "\n# Final " << *state << "\n";
    }

    Machine::registeryCleanup();

    return 0;
}catch(std::exception& e){
    std::cerr<<"Error "<<typeid(e).name()<<" : "<<e.what()<<"\n";
    return 1;
}
}
<|endoftext|>


<commit_before>// Range-based algorithms
// C++11

#include <iterator>
#include <utility>

template <typename ForwardRange>
void algorithm(ForwardRange& range)
{
	using std::begin;
	using std::end;

	using iterator = decltype(begin(range));

	iterator it_begin = begin(range);
	iterator it_end = end(range);

	// Now perform algorithm on elements between begin and end
}

// Implement algorithms that can be applied to any generic range of
// elements.
//
// **Note**: The existing algorithms in the standard library are not
// range-based but iterator-based. However, the Ranges Technical
// Specification is experimenting with introducing ranges and
// range-based algorithms to the standard, which are more flexible and
// provide a simpler interface to client code.
//
// [!7-19] define a function template representing a range-based
// algorithm. It takes a single range argument, which is
// any type that supports `begin` and `end` functions that provide
// iterators to the beginning and end of the range. A range may
// be classified depending on the iterators that it provides:
//
// - *Forward Range* - provides
//   [Forward Iterators](cpp/concept/ForwardIterator)
// - *Bidirectional Range* - provides
//   [Bidirectional Iterators](cpp/concept/BidirectionalIterator)
// - *Random Access Range* - provides
//   [Random Access Iterators](cpp/concept/RandomAccessIterator)
//
// For this sample, we assume that the algorithm requires only Forward
// Iterators, so can be applied to any Forward Range. We therefore
// name the template parameter `ForwardRange` on [7] to illustrate
// this.
//
// On [15-16], we call `begin` and `end` on the range to get the
// respective iterators to the beginning and end of the range.
// We use using-declarations on [10-11] to
// allow these calls to be found via [argument-dependent
// lookup](http://en.wikipedia.org/wiki/Argument-dependent_name_lookup)
// before using the standard [`std::begin`](cpp/iterator/begin) and
// [`std::end`](cpp/iterator/end) functions. With these iterators, we
// can now implement the algorithm over the elements between them.
//
// If the iterators are not necessary to implement the algorithm, we
// may instead be able to use a simple
// [range-based `for` loop](/common-tasks/range-iteration.cpp).

#include <forward_list>

int main()
{
	std::forward_list<int> arr = {6, 12, 5, 2, 3};
	algorithm(arr);
}
<commit_msg>Correct comment in range-based algorithm code<commit_after>// Range-based algorithms
// C++11

#include <iterator>
#include <utility>

template <typename ForwardRange>
void algorithm(ForwardRange& range)
{
	using std::begin;
	using std::end;

	using iterator = decltype(begin(range));

	iterator it_begin = begin(range);
	iterator it_end = end(range);

	// Now use it_begin and it_end to implement algorithm
}

// Implement algorithms that can be applied to any generic range of
// elements.
//
// **Note**: The existing algorithms in the standard library are not
// range-based but iterator-based. However, the Ranges Technical
// Specification is experimenting with introducing ranges and
// range-based algorithms to the standard, which are more flexible and
// provide a simpler interface to client code.
//
// [!7-19] define a function template representing a range-based
// algorithm. It takes a single range argument, which is
// any type that supports `begin` and `end` functions that provide
// iterators to the beginning and end of the range. A range may
// be classified depending on the iterators that it provides:
//
// - *Forward Range* - provides
//   [Forward Iterators](cpp/concept/ForwardIterator)
// - *Bidirectional Range* - provides
//   [Bidirectional Iterators](cpp/concept/BidirectionalIterator)
// - *Random Access Range* - provides
//   [Random Access Iterators](cpp/concept/RandomAccessIterator)
//
// For this sample, we assume that the algorithm requires only Forward
// Iterators, so can be applied to any Forward Range. We therefore
// name the template parameter `ForwardRange` on [7] to illustrate
// this.
//
// On [15-16], we call `begin` and `end` on the range to get the
// respective iterators to the beginning and end of the range.
// We use using-declarations on [10-11] to
// allow these calls to be found via [argument-dependent
// lookup](http://en.wikipedia.org/wiki/Argument-dependent_name_lookup)
// before using the standard [`std::begin`](cpp/iterator/begin) and
// [`std::end`](cpp/iterator/end) functions. With these iterators, we
// can now implement the algorithm over the elements between them.
//
// If the iterators are not necessary to implement the algorithm, we
// may instead be able to use a simple
// [range-based `for` loop](/common-tasks/range-iteration.cpp).

#include <forward_list>

int main()
{
	std::forward_list<int> arr = {6, 12, 5, 2, 3};
	algorithm(arr);
}
<|endoftext|>


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

Program:   Medical Imaging & Interaction Toolkit
Module:    $RCSfile$
Language:  C++
Date:      $Date$
Version:   $Revision: -1 $

Copyright (c) German Cancer Research Center, Division of Medical and
Biological Informatics. All rights reserved.
See MITKCopyright.txt or http://www.mitk.org/copyright.html for details.

This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE.  See the above copyright notices for more information.

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

#include <qvalidator.h>
#include <mitkImageCast.h>
#include <stdio.h>
#include <stdlib.h>
#include <mitkLevelWindowProperty.h>
#include <mitkRenderingManager.h>
#include "itkRegularStepGradientDescentOptimizer.h"
#include <qfiledialog.h>
#include <qmessagebox.h>
#include "QmitkDemonsRegistrationView.h"
#include "ui_QmitkDemonsRegistrationViewControls.h"
#include "mitkITKImageImport.h"

QmitkDemonsRegistrationView::QmitkDemonsRegistrationView(QWidget* parent, Qt::WindowFlags f ) : QWidget( parent, f ),
m_FixedNode(NULL), m_MovingNode(NULL), m_ResultImage(NULL), m_ResultDeformationField(NULL)
{
  m_Controls.setupUi(parent);

  QValidator* validatorHistogramLevels = new QIntValidator(1, 20000000, this);
  m_Controls.m_NumberOfHistogramLevels->setValidator(validatorHistogramLevels);

  QValidator* validatorMatchPoints = new QIntValidator(1, 20000000, this);
  m_Controls.m_NumberOfMatchPoints->setValidator(validatorMatchPoints);

  QValidator* validatorIterations = new QIntValidator(1, 20000000, this);
  m_Controls.m_Iterations->setValidator(validatorIterations);

  QValidator* validatorStandardDeviation = new QDoubleValidator(0, 20000000, 2, this);
  m_Controls.m_StandardDeviation->setValidator(validatorStandardDeviation);
}

QmitkDemonsRegistrationView::~QmitkDemonsRegistrationView()
{
}

int QmitkDemonsRegistrationView::GetNumberOfIterations()
{
  return atoi(m_Controls.m_Iterations->text().toLatin1());
}

float QmitkDemonsRegistrationView::GetStandardDeviation()
{
  return atof(m_Controls.m_StandardDeviation->text().toLatin1());
}

mitk::Image::Pointer QmitkDemonsRegistrationView::GetResultImage()
{
  return m_ResultImage;
}

mitk::Image::Pointer QmitkDemonsRegistrationView::GetResultDeformationfield()
{
  return m_ResultDeformationField;
}

void QmitkDemonsRegistrationView::CalculateTransformation()
{
  if (m_FixedNode.IsNotNull() && m_MovingNode.IsNotNull())
  {
    mitk::Image::Pointer fimage = dynamic_cast<mitk::Image*>(m_FixedNode->GetData());
    mitk::Image::Pointer mimage = dynamic_cast<mitk::Image*>(m_MovingNode->GetData());
    if ( m_Controls.m_RegistrationSelection->currentIndex() == 0)
    {
      mitk::DemonsRegistration::Pointer registration = mitk::DemonsRegistration::New();
      registration->SetSaveDeformationField(false);
      registration->SetSaveResult(false);
      registration->SetReferenceImage(fimage);
      registration->SetNumberOfIterations(atoi(m_Controls.m_Iterations->text().toLatin1()));
      registration->SetStandardDeviation(atof(m_Controls.m_StandardDeviation->text().toLatin1()));
      if (m_Controls.m_UseHistogramMatching->isChecked())
      {
        mitk::HistogramMatching::Pointer histogramMatching = mitk::HistogramMatching::New();
        histogramMatching->SetReferenceImage(fimage);
        histogramMatching->SetInput(mimage);
        histogramMatching->SetNumberOfHistogramLevels(atoi(m_Controls.m_NumberOfHistogramLevels->text().toLatin1()));
        histogramMatching->SetNumberOfMatchPoints(atoi(m_Controls.m_NumberOfMatchPoints->text().toLatin1()));
        histogramMatching->SetThresholdAtMeanIntensity(m_Controls.m_ThresholdAtMeanIntensity->isChecked());
        histogramMatching->Update();
        mitk::Image::Pointer histimage = histogramMatching->GetOutput();
        if (histimage.IsNotNull())
        {
          registration->SetInput(histimage);
        }
        else
        {
          registration->SetInput(mimage);
        }
      }
      else
      {
        registration->SetInput(mimage);
      }
      try
      {
        registration->Update();
      }
      catch (itk::ExceptionObject& excpt)
      {
        QMessageBox::information( this, "Registration exception", excpt.GetDescription(), QMessageBox::Ok );
      }
      m_ResultImage = registration->GetOutput();
      typedef itk::Image<itk::Vector<float,3>, 3> VectorImageType;
      VectorImageType::Pointer deformationField = registration->GetDeformationField();
      m_ResultDeformationField = mitk::ImportItkImage(deformationField);
    }
    else if(m_Controls.m_RegistrationSelection->currentIndex() == 1)
    {
      mitk::SymmetricForcesDemonsRegistration::Pointer registration = mitk::SymmetricForcesDemonsRegistration::New();
      registration->SetSaveDeformationField(false);
      registration->SetSaveResult(false);
      registration->SetReferenceImage(fimage);
      registration->SetNumberOfIterations(atoi(m_Controls.m_Iterations->text().toLatin1()));
      registration->SetStandardDeviation(atof(m_Controls.m_StandardDeviation->text().toLatin1()));
      if (m_Controls.m_UseHistogramMatching->isChecked())
      {
        mitk::HistogramMatching::Pointer histogramMatching = mitk::HistogramMatching::New();
        histogramMatching->SetReferenceImage(fimage);
        histogramMatching->SetInput(mimage);
        histogramMatching->SetNumberOfHistogramLevels(atoi(m_Controls.m_NumberOfHistogramLevels->text().toLatin1()));
        histogramMatching->SetNumberOfMatchPoints(atoi(m_Controls.m_NumberOfMatchPoints->text().toLatin1()));
        histogramMatching->SetThresholdAtMeanIntensity(m_Controls.m_ThresholdAtMeanIntensity->isChecked());
        histogramMatching->Update();
        mitk::Image::Pointer histimage = histogramMatching->GetOutput();
        if (histimage.IsNotNull())
        {
          registration->SetInput(histimage);
        }
        else
        {
          registration->SetInput(mimage);
        }
      }
      else
      {
        registration->SetInput(mimage);
      }
      try
      {
        registration->Update();
      }
      catch (itk::ExceptionObject& excpt)
      {
        QMessageBox::information( this, "Registration exception", excpt.GetDescription(), QMessageBox::Ok );
      }
      m_ResultImage = registration->GetOutput();
      typedef itk::Image<itk::Vector<float,3>, 3> VectorImageType;
      VectorImageType::Pointer deformationField = registration->GetDeformationField();
      m_ResultDeformationField = mitk::ImportItkImage(deformationField);
    }
  }
}

void QmitkDemonsRegistrationView::SetFixedNode( mitk::DataTreeNode * fixedNode )
{
  m_FixedNode = fixedNode;
}

void QmitkDemonsRegistrationView::SetMovingNode( mitk::DataTreeNode * movingNode )
{
  m_MovingNode = movingNode;
}

void QmitkDemonsRegistrationView::UseHistogramMatching( bool useHM )
{
  if (useHM)
  {
    m_Controls.numberOfHistogramLevels->setEnabled(true);
    m_Controls.m_NumberOfHistogramLevels->setEnabled(true);
    m_Controls.numberOfMatchPoints->setEnabled(true);
    m_Controls.m_NumberOfMatchPoints->setEnabled(true);
    m_Controls.thresholdAtMeanIntensity->setEnabled(true);
    m_Controls.m_ThresholdAtMeanIntensity->setEnabled(true);
  }
  else
  {
    m_Controls.numberOfHistogramLevels->setEnabled(false);
    m_Controls.m_NumberOfHistogramLevels->setEnabled(false);
    m_Controls.numberOfMatchPoints->setEnabled(false);
    m_Controls.m_NumberOfMatchPoints->setEnabled(false);
    m_Controls.thresholdAtMeanIntensity->setEnabled(false);
    m_Controls.m_ThresholdAtMeanIntensity->setEnabled(false);
  }
}
<commit_msg>FIX (#3020): added workaround to check if fixed image is bigger than moving image<commit_after>/*=========================================================================

Program:   Medical Imaging & Interaction Toolkit
Module:    $RCSfile$
Language:  C++
Date:      $Date$
Version:   $Revision: -1 $

Copyright (c) German Cancer Research Center, Division of Medical and
Biological Informatics. All rights reserved.
See MITKCopyright.txt or http://www.mitk.org/copyright.html for details.

This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE.  See the above copyright notices for more information.

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

#include <qvalidator.h>
#include <mitkImageCast.h>
#include <stdio.h>
#include <stdlib.h>
#include <mitkLevelWindowProperty.h>
#include <mitkRenderingManager.h>
#include "itkRegularStepGradientDescentOptimizer.h"
#include <qfiledialog.h>
#include <qmessagebox.h>
#include "QmitkDemonsRegistrationView.h"
#include "ui_QmitkDemonsRegistrationViewControls.h"
#include "mitkITKImageImport.h"

QmitkDemonsRegistrationView::QmitkDemonsRegistrationView(QWidget* parent, Qt::WindowFlags f ) : QWidget( parent, f ),
m_FixedNode(NULL), m_MovingNode(NULL), m_ResultImage(NULL), m_ResultDeformationField(NULL)
{
  m_Controls.setupUi(parent);

  QValidator* validatorHistogramLevels = new QIntValidator(1, 20000000, this);
  m_Controls.m_NumberOfHistogramLevels->setValidator(validatorHistogramLevels);

  QValidator* validatorMatchPoints = new QIntValidator(1, 20000000, this);
  m_Controls.m_NumberOfMatchPoints->setValidator(validatorMatchPoints);

  QValidator* validatorIterations = new QIntValidator(1, 20000000, this);
  m_Controls.m_Iterations->setValidator(validatorIterations);

  QValidator* validatorStandardDeviation = new QDoubleValidator(0, 20000000, 2, this);
  m_Controls.m_StandardDeviation->setValidator(validatorStandardDeviation);
}

QmitkDemonsRegistrationView::~QmitkDemonsRegistrationView()
{
}

int QmitkDemonsRegistrationView::GetNumberOfIterations()
{
  return atoi(m_Controls.m_Iterations->text().toLatin1());
}

float QmitkDemonsRegistrationView::GetStandardDeviation()
{
  return atof(m_Controls.m_StandardDeviation->text().toLatin1());
}

mitk::Image::Pointer QmitkDemonsRegistrationView::GetResultImage()
{
  return m_ResultImage;
}

mitk::Image::Pointer QmitkDemonsRegistrationView::GetResultDeformationfield()
{
  return m_ResultDeformationField;
}

void QmitkDemonsRegistrationView::CalculateTransformation()
{
  if (m_FixedNode.IsNotNull() && m_MovingNode.IsNotNull())
  {
    mitk::Image::Pointer fimage = dynamic_cast<mitk::Image*>(m_FixedNode->GetData());
    mitk::Image::Pointer mimage = dynamic_cast<mitk::Image*>(m_MovingNode->GetData());
    // workaround to ensure that fimage covers a bigger region than mimage
    mitk::Image::RegionType fimageRegion = fimage->GetLargestPossibleRegion();
    mitk::Image::RegionType mimageRegion = mimage->GetLargestPossibleRegion();
    if (!((fimageRegion.GetSize(0)>=mimageRegion.GetSize(0))&&(fimageRegion.GetSize(1)>=mimageRegion.GetSize(1))
        &&(fimageRegion.GetSize(2)>=mimageRegion.GetSize(2))))
    {
      QMessageBox::information(NULL,"Registration","Fixed image must be equal or bigger in size than moving image");
      return;
    }
    if ( m_Controls.m_RegistrationSelection->currentIndex() == 0)
    {
      mitk::DemonsRegistration::Pointer registration = mitk::DemonsRegistration::New();
      registration->SetSaveDeformationField(false);
      registration->SetSaveResult(false);
      registration->SetReferenceImage(fimage);
      registration->SetNumberOfIterations(atoi(m_Controls.m_Iterations->text().toLatin1()));
      registration->SetStandardDeviation(atof(m_Controls.m_StandardDeviation->text().toLatin1()));
      if (m_Controls.m_UseHistogramMatching->isChecked())
      {
        mitk::HistogramMatching::Pointer histogramMatching = mitk::HistogramMatching::New();
        histogramMatching->SetReferenceImage(fimage);
        histogramMatching->SetInput(mimage);
        histogramMatching->SetNumberOfHistogramLevels(atoi(m_Controls.m_NumberOfHistogramLevels->text().toLatin1()));
        histogramMatching->SetNumberOfMatchPoints(atoi(m_Controls.m_NumberOfMatchPoints->text().toLatin1()));
        histogramMatching->SetThresholdAtMeanIntensity(m_Controls.m_ThresholdAtMeanIntensity->isChecked());
        histogramMatching->Update();
        mitk::Image::Pointer histimage = histogramMatching->GetOutput();
        if (histimage.IsNotNull())
        {
          registration->SetInput(histimage);
        }
        else
        {
          registration->SetInput(mimage);
        }
      }
      else
      {
        registration->SetInput(mimage);
      }
      try
      {
        registration->Update();
      }
      catch (itk::ExceptionObject& excpt)
      {
        QMessageBox::information( this, "Registration exception", excpt.GetDescription(), QMessageBox::Ok );
        return;
      }
      m_ResultImage = registration->GetOutput();
      typedef itk::Image<itk::Vector<float,3>, 3> VectorImageType;
      VectorImageType::Pointer deformationField = registration->GetDeformationField();
      m_ResultDeformationField = mitk::ImportItkImage(deformationField);
    }
    else if(m_Controls.m_RegistrationSelection->currentIndex() == 1)
    {
      mitk::SymmetricForcesDemonsRegistration::Pointer registration = mitk::SymmetricForcesDemonsRegistration::New();
      registration->SetSaveDeformationField(false);
      registration->SetSaveResult(false);
      registration->SetReferenceImage(fimage);
      registration->SetNumberOfIterations(atoi(m_Controls.m_Iterations->text().toLatin1()));
      registration->SetStandardDeviation(atof(m_Controls.m_StandardDeviation->text().toLatin1()));
      if (m_Controls.m_UseHistogramMatching->isChecked())
      {
        mitk::HistogramMatching::Pointer histogramMatching = mitk::HistogramMatching::New();
        histogramMatching->SetReferenceImage(fimage);
        histogramMatching->SetInput(mimage);
        histogramMatching->SetNumberOfHistogramLevels(atoi(m_Controls.m_NumberOfHistogramLevels->text().toLatin1()));
        histogramMatching->SetNumberOfMatchPoints(atoi(m_Controls.m_NumberOfMatchPoints->text().toLatin1()));
        histogramMatching->SetThresholdAtMeanIntensity(m_Controls.m_ThresholdAtMeanIntensity->isChecked());
        histogramMatching->Update();
        mitk::Image::Pointer histimage = histogramMatching->GetOutput();
        if (histimage.IsNotNull())
        {
          registration->SetInput(histimage);
        }
        else
        {
          registration->SetInput(mimage);
        }
      }
      else
      {
        registration->SetInput(mimage);
      }
      try
      {
        registration->Update();
      }
      catch (itk::ExceptionObject& excpt)
      {
        QMessageBox::information( this, "Registration exception", excpt.GetDescription(), QMessageBox::Ok );
      }
      m_ResultImage = registration->GetOutput();
      typedef itk::Image<itk::Vector<float,3>, 3> VectorImageType;
      VectorImageType::Pointer deformationField = registration->GetDeformationField();
      m_ResultDeformationField = mitk::ImportItkImage(deformationField);
    }
  }
}

void QmitkDemonsRegistrationView::SetFixedNode( mitk::DataTreeNode * fixedNode )
{
  m_FixedNode = fixedNode;
}

void QmitkDemonsRegistrationView::SetMovingNode( mitk::DataTreeNode * movingNode )
{
  m_MovingNode = movingNode;
}

void QmitkDemonsRegistrationView::UseHistogramMatching( bool useHM )
{
  if (useHM)
  {
    m_Controls.numberOfHistogramLevels->setEnabled(true);
    m_Controls.m_NumberOfHistogramLevels->setEnabled(true);
    m_Controls.numberOfMatchPoints->setEnabled(true);
    m_Controls.m_NumberOfMatchPoints->setEnabled(true);
    m_Controls.thresholdAtMeanIntensity->setEnabled(true);
    m_Controls.m_ThresholdAtMeanIntensity->setEnabled(true);
  }
  else
  {
    m_Controls.numberOfHistogramLevels->setEnabled(false);
    m_Controls.m_NumberOfHistogramLevels->setEnabled(false);
    m_Controls.numberOfMatchPoints->setEnabled(false);
    m_Controls.m_NumberOfMatchPoints->setEnabled(false);
    m_Controls.thresholdAtMeanIntensity->setEnabled(false);
    m_Controls.m_ThresholdAtMeanIntensity->setEnabled(false);
  }
}
<|endoftext|>


<commit_before>/**
 * Copyright (c) 2008 Will Roberts
 * All Rights Reserved.
 *
 * Name:          count
 *
 * Author:        wildwilhelm@gmail.com (WKR)
 * Creation Date: 11 November 2008
 *
 * Purpose:       Standard input line counter
 *
 * Description:
 *    count counts the number of unique lines on the standard input,
 *    outputting the counts after all the input is read.  The output
 *    of the program can be piped through sort -nr to sort it in order
 *    of descending frequency.
 *
 * Revision Information:
 *
 *    (WKR) 11 November 2008
 *          - Initial version.
 *
 * \file count.cpp
 */

#include <unistd.h>
#include <string>
#include <iostream>
#include <iomanip>
#include <map>
using namespace std;

void
printHelp()
{
    cout << "Counts unique lines on standard input, outputting the counts after all" << endl;
    cout << "input is read.  Output is sorted in alphabetical order of lines.  The" << endl;
    cout << "output of the program can be sort it in order of descending frequency" << endl;
    cout << "using the -f option or by piping through sort -nr." << endl;
    cout << endl;
    cout << "Syntax:" << endl;
    cout << endl;
    cout << "   count [OPTIONS]" << endl;
    cout << endl;
    cout << "Options:" << endl;
    cout << endl;
    cout << "   -e      always count the last line of the input, even if it is" << endl;
    cout << "           empty" << endl;
    cout << "           -f      sort output in order of descending frequency" << endl;
    cout << "   -?      display this help message and exit" << endl;
}

template<typename A, typename B>
pair<B,A> flip_pair(const pair<A,B> &p)
{
    return pair<B,A>(p.second, p.first);
}

template<typename A, typename B>
map<B,A> flip_map(const map<A,B> &src)
{
    map<B,A> dst;
    transform(src.begin(), src.end(), inserter(dst, dst.begin()),
              flip_pair<A,B>);
    return dst;
}

int
main ( int    argc,
       char **argv )
{
    bool       fIncludeLastLine    = false;
    bool       fSortDecreasingFreq = false;
    int        c;
    while ((c = getopt(argc, argv, "ef?")) != -1)
    {
        switch(c)
        {
        case 'e':
            fIncludeLastLine = true;
            break;
        case 'f':
            fSortDecreasingFreq = true;
            break;
        case '?':
            printHelp();
            exit(1);
            break;
        default:
            break;
        }
    }

    int             nNumLines = 0;
    map<string,int> LineDict;
    while ( cin.good() )
    {
        string sLine;
        getline ( cin, sLine );
        if (fIncludeLastLine || !cin.eof() || sLine.length() != 0)
        {
            LineDict[sLine] += 1;
        }
        nNumLines       += 1;
    }
    //int nWidth = 0;
    //while ( nNumLines > 0 )
    //{
    //    nWidth++;
    //    nNumLines /= 10;
    //}
    if (fSortDecreasingFreq)
    {
        map<int,string> FlippedLineDict = flip_map(LineDict);
        for ( map<int,string>::reverse_iterator iterator =
                  FlippedLineDict.rbegin();
              iterator != FlippedLineDict.rend(); iterator++ )
        {
            cout << iterator->first << "\t" << iterator->second << endl;
        }
    }
    else
    {
        for ( map<string,int>::iterator iterator = LineDict.begin();
              iterator != LineDict.end(); iterator++ )
        {
            cout << iterator->second << "\t" << iterator->first << endl;
        }
    }
    return 0;
}
<commit_msg>count.cpp: fix -? output<commit_after>/**
 * Copyright (c) 2008 Will Roberts
 * All Rights Reserved.
 *
 * Name:          count
 *
 * Author:        wildwilhelm@gmail.com (WKR)
 * Creation Date: 11 November 2008
 *
 * Purpose:       Standard input line counter
 *
 * Description:
 *    count counts the number of unique lines on the standard input,
 *    outputting the counts after all the input is read.  The output
 *    of the program can be piped through sort -nr to sort it in order
 *    of descending frequency.
 *
 * Revision Information:
 *
 *    (WKR) 11 November 2008
 *          - Initial version.
 *
 * \file count.cpp
 */

#include <unistd.h>
#include <string>
#include <iostream>
#include <iomanip>
#include <map>
using namespace std;

void
printHelp()
{
    cout << "Counts unique lines on standard input, outputting the counts after all" << endl;
    cout << "input is read.  Output is sorted in alphabetical order of lines.  The" << endl;
    cout << "output of the program can be sort it in order of descending frequency" << endl;
    cout << "using the -f option or by piping through sort -nr." << endl;
    cout << endl;
    cout << "Syntax:" << endl;
    cout << endl;
    cout << "   count [OPTIONS]" << endl;
    cout << endl;
    cout << "Options:" << endl;
    cout << endl;
    cout << "   -e      always count the last line of the input, even if it is" << endl;
    cout << "           empty" << endl;
    cout << "   -f      sort output in order of descending frequency" << endl;
    cout << "   -?      display this help message and exit" << endl;
}

template<typename A, typename B>
pair<B,A> flip_pair(const pair<A,B> &p)
{
    return pair<B,A>(p.second, p.first);
}

template<typename A, typename B>
map<B,A> flip_map(const map<A,B> &src)
{
    map<B,A> dst;
    transform(src.begin(), src.end(), inserter(dst, dst.begin()),
              flip_pair<A,B>);
    return dst;
}

int
main ( int    argc,
       char **argv )
{
    bool       fIncludeLastLine    = false;
    bool       fSortDecreasingFreq = false;
    int        c;
    while ((c = getopt(argc, argv, "ef?")) != -1)
    {
        switch(c)
        {
        case 'e':
            fIncludeLastLine = true;
            break;
        case 'f':
            fSortDecreasingFreq = true;
            break;
        case '?':
            printHelp();
            exit(1);
            break;
        default:
            break;
        }
    }

    int             nNumLines = 0;
    map<string,int> LineDict;
    while ( cin.good() )
    {
        string sLine;
        getline ( cin, sLine );
        if (fIncludeLastLine || !cin.eof() || sLine.length() != 0)
        {
            LineDict[sLine] += 1;
        }
        nNumLines       += 1;
    }
    //int nWidth = 0;
    //while ( nNumLines > 0 )
    //{
    //    nWidth++;
    //    nNumLines /= 10;
    //}
    if (fSortDecreasingFreq)
    {
        map<int,string> FlippedLineDict = flip_map(LineDict);
        for ( map<int,string>::reverse_iterator iterator =
                  FlippedLineDict.rbegin();
              iterator != FlippedLineDict.rend(); iterator++ )
        {
            cout << iterator->first << "\t" << iterator->second << endl;
        }
    }
    else
    {
        for ( map<string,int>::iterator iterator = LineDict.begin();
              iterator != LineDict.end(); iterator++ )
        {
            cout << iterator->second << "\t" << iterator->first << endl;
        }
    }
    return 0;
}
<|endoftext|>


<commit_before>// Copyright 2015 The Subzone Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "crypto/p256_key_exchange.h"

#include "base/logging.h"
#include "gtest/gtest.h"

namespace crypto {
namespace test {

// SharedKeyX509 tests that the basic key exchange identity holds: that both
// parties end up with the same key, exchanged in the X.509 network format.
TEST(P256KeyExchange, SharedKeyX509) {
  for (int i = 0; i < 5; i++) {
    scoped_ptr<P256KeyExchange> alice(new P256KeyExchange());
    scoped_ptr<P256KeyExchange> bob(new P256KeyExchange());
    ASSERT_TRUE(alice.get() != nullptr);
    ASSERT_TRUE(bob.get() != nullptr);

    const base::StringPiece alice_public_x509(alice->GetX509Public());
    const base::StringPiece bob_public_x509(bob->GetX509Public());

    ASSERT_FALSE(alice_public_x509.empty());
    ASSERT_FALSE(bob_public_x509.empty());
    ASSERT_NE(alice_public_x509, bob_public_x509);

    // Convert X.509 format to public key value
    std::string alice_public, bob_public;
    ASSERT_TRUE(P256KeyExchange::GetPublicValueFromX509(alice_public_x509,
        &alice_public));
    ASSERT_TRUE(P256KeyExchange::GetPublicValueFromX509(bob_public_x509,
        &bob_public));

    // These public keys must match
    ASSERT_EQ(alice_public, alice->public_value());
    ASSERT_EQ(bob_public, bob->public_value());
  }
}

// The signature test generates a key exchange (public/private key pair) and
// takes the public key value and signs it. Finally it verifies that the
// signature matches with the public key signature. We repeat this test 5 times.
TEST(P256KeyExchange, Signature) {
  for (int i = 0; i < 5; i++) {
    P256KeyExchange alice;
    const base::StringPiece alice_sig(alice.GetSignature());
    ASSERT_FALSE(alice_sig.empty());

    // Take the public key in DER format. This is the string that is going to be
    // passed through the SHA256 and then signed.
    const base::StringPiece public_x509(alice.GetX509Public());
    ASSERT_FALSE(public_x509.empty());

    // Verify the signature against it's public key.
    ASSERT_TRUE(P256KeyExchange::VerifySignature(public_x509, alice_sig));
  }
}

}  // namespace test
}  // namespace crypto

<commit_msg>Verify test with values coming from fred<commit_after>// Copyright 2015 The Subzone Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "crypto/p256_key_exchange.h"

#include "base/logging.h"
#include "gtest/gtest.h"

namespace crypto {
namespace test {

// SharedKeyX509 tests that the basic key exchange identity holds: that both
// parties end up with the same key, exchanged in the X.509 network format.
TEST(P256KeyExchange, SharedKeyX509) {
  for (int i = 0; i < 5; i++) {
    scoped_ptr<P256KeyExchange> alice(new P256KeyExchange());
    scoped_ptr<P256KeyExchange> bob(new P256KeyExchange());
    ASSERT_TRUE(alice.get() != nullptr);
    ASSERT_TRUE(bob.get() != nullptr);

    const base::StringPiece alice_public_x509(alice->GetX509Public());
    const base::StringPiece bob_public_x509(bob->GetX509Public());

    ASSERT_FALSE(alice_public_x509.empty());
    ASSERT_FALSE(bob_public_x509.empty());
    ASSERT_NE(alice_public_x509, bob_public_x509);

    // Convert X.509 format to public key value
    std::string alice_public, bob_public;
    ASSERT_TRUE(P256KeyExchange::GetPublicValueFromX509(alice_public_x509,
        &alice_public));
    ASSERT_TRUE(P256KeyExchange::GetPublicValueFromX509(bob_public_x509,
        &bob_public));

    // These public keys must match
    ASSERT_EQ(alice_public, alice->public_value());
    ASSERT_EQ(bob_public, bob->public_value());
  }
}

// The SignAndVerify test generates a key exchange (public/private key pair) and
// takes the public key value and signs it. Finally it verifies that the
// signature matches with the public key signature. We repeat this test 5 times.
TEST(P256KeyExchange, SignAndVerify) {
  for (int i = 0; i < 5; i++) {
    P256KeyExchange alice;
    const base::StringPiece alice_sig(alice.GetSignature());
    ASSERT_FALSE(alice_sig.empty());

    // Take the public key in DER format. This is the string that is going to be
    // passed through the SHA256 and then signed.
    const base::StringPiece public_x509(alice.GetX509Public());
    ASSERT_FALSE(public_x509.empty());

    // Verify the signature against it's public key.
    ASSERT_TRUE(P256KeyExchange::VerifySignature(public_x509, alice_sig));
  }
}

// The Verify test takes a public key sample value from the Freenet reference
// implementation with a valid signature and checks that our implementation
// can verify the signature appropriatelly.
TEST(P256KeyExchange, Verify) {
  // Public key in X509 network format.
  const uint8_t pubx509[P256KeyExchange::kP256PublicKeyX509Bytes] = {
    0x30, 0x59, 0x30, 0x13, 0x06, 0x07, 0x2a, 0x86, 0x48, 0xce, 0x3d, 0x02,
    0x01, 0x06, 0x08, 0x2a, 0x86, 0x48, 0xce, 0x3d, 0x03, 0x01, 0x07, 0x03,
    0x42, 0x00, 0x04, 0xb3, 0x74, 0x41, 0xcc, 0x7e, 0x36, 0x76, 0xe1, 0x3f,
    0x13, 0xd9, 0x8c, 0x50, 0x8f, 0xb9, 0x53, 0x6e, 0xae, 0x01, 0xe5, 0x2b,
    0x20, 0x8f, 0x44, 0x1a, 0x58, 0xc3, 0x85, 0xf8, 0x58, 0x82, 0x79, 0x0a,
    0xf8, 0xae, 0xb2, 0xdb, 0xa7, 0x30, 0x88, 0x36, 0x10, 0xd2, 0x20, 0x3c,
    0xb6, 0xa8, 0xab, 0x2f, 0x76, 0xfe, 0x50, 0xc3, 0x2c, 0xc4, 0xa8, 0xb8,
    0xc3, 0xbb, 0x52, 0xa7, 0x5b, 0x9b, 0x6d
  };

  // Signature in DER export format.
  const uint8_t sig[] = {
    0x30, 0x45, 0x02, 0x20, 0x6c, 0x0c, 0x5b, 0x93, 0x30, 0xb9, 0x59, 0xf8,
    0xcb, 0x23, 0x38, 0xec, 0x13, 0xc3, 0x51, 0xb9, 0x72, 0x61, 0x14, 0xa9,
    0xc2, 0xf5, 0x59, 0x97, 0x23, 0x09, 0x00, 0x52, 0x57, 0xab, 0x49, 0x22,
    0x02, 0x21, 0x00, 0x95, 0xe3, 0xd4, 0xa1, 0xcd, 0x7e, 0xe3, 0x84, 0x48,
    0x5f, 0x56, 0x23, 0xd3, 0x2b, 0x0b, 0x15, 0x43, 0xce, 0x3a, 0x35, 0x68,
    0xc6, 0xaa, 0x2a, 0xf2, 0x80, 0x0a, 0x0d, 0x22, 0x38, 0xb2, 0x38
  };

  // Convert the byte arrays to strings to be able to call VerifySignature()
  const base::StringPiece pubx509_str(reinterpret_cast<const char *>(pubx509),
                                      sizeof(pubx509));
  const base::StringPiece sig_str(reinterpret_cast<const char *>(sig),
                                  sizeof(sig));

  // It must return true, as this is a valid signature from the public key above
  ASSERT_TRUE(P256KeyExchange::VerifySignature(pubx509_str, sig_str));
}

}  // namespace test
}  // namespace crypto

<|endoftext|>