<commit_before>/*************************************************************************
 *
 *  $RCSfile: image.cxx,v $
 *
 *  $Revision: 1.1.1.1 $
 *
 *  last change: $Author: hr $ $Date: 2000-09-18 16:12:09 $
 *
 *  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 _STREAM_HXX //autogen
#include <tools/stream.hxx>
#endif
#pragma hdrstop
#include <svtools/sbx.hxx>
#include "sb.hxx"
#include <string.h>     // memset() etc
#include "image.hxx"
#include "filefmt.hxx"

#include "segmentc.hxx"
#pragma SW_SEGMENT_CLASS( SBASIC, SBASIC_CODE )

SbiImage::SbiImage()
{
    rTypes     = new SbxArray;
    pStringOff = NULL;
    pStrings   = NULL;
    pCode      = NULL;
    nFlags     =
    nStrings   =
    nStringSize=
    nCodeSize  =
    nDimBase   = 0;
    bInit      =
    bError     = FALSE;
    eCharSet   = gsl_getSystemTextEncoding();
}

SbiImage::~SbiImage()
{
    Clear();
}

void SbiImage::Clear()
{
    delete pStringOff;
    delete pStrings;
    delete pCode;
    pStringOff = NULL;
    pStrings   = NULL;
    pCode      = NULL;
    nFlags     =
    nStrings   =
    nStringSize=
    nCodeSize  = 0;
    eCharSet   = gsl_getSystemTextEncoding();
    nDimBase   = 0;
    bError     = FALSE;
}

/**************************************************************************
*
*   Service-Routinen fuer das Laden und Speichern
*
**************************************************************************/

BOOL SbiGood( SvStream& r )
{
    return BOOL( !r.IsEof() && r.GetError() == SVSTREAM_OK );
}

// Oeffnen eines Records

ULONG SbiOpenRecord( SvStream& r, UINT16 nSignature, UINT16 nElem )
{
    ULONG nPos = r.Tell();
    r << nSignature << (INT32) 0 << nElem;
    return nPos;
}

// Schliessen eines Records

void SbiCloseRecord( SvStream& r, ULONG nOff )
{
    ULONG nPos = r.Tell();
    r.Seek( nOff + 2 );
    r << (INT32) ( nPos - nOff - 8 );
    r.Seek( nPos );
}

/**************************************************************************
*
*   Laden und Speichern
*
**************************************************************************/

// Falls die Versionsnummer nicht passt, werden die binaeren Teile
// nicht geladen, wohl aber Source, Kommentar und Name.

BOOL SbiImage::Load( SvStream& r )
{
    UINT16 nSign, nCount;
    UINT32 nLen, nOff;

    Clear();
    ULONG nStart = r.Tell();
    // Master-Record einlesen
    r >> nSign >> nLen >> nCount;
    ULONG nLast = r.Tell() + nLen;
    UINT32 nVersion = 0;            // Versionsnummer
    UINT32 nCharSet;                // System-Zeichensatz
    UINT32 lDimBase;
    UINT16 nReserved1;
    UINT32 nReserved2;
    UINT32 nReserved3;
    BOOL bBadVer = FALSE;
    if( nSign == B_MODULE )
    {
        r >> nVersion >> nCharSet >> lDimBase
          >> nFlags >> nReserved1 >> nReserved2 >> nReserved3;
        eCharSet = (CharSet) nCharSet;
        bBadVer  = BOOL( nVersion != B_CURVERSION );
        nDimBase = (USHORT) lDimBase;
    }

    ULONG nNext;
    while( ( nNext = r.Tell() ) < nLast )
    {
        short i;

        r >> nSign >> nLen >> nCount;
        nNext += nLen + 8;
        if( r.GetError() == SVSTREAM_OK )
          switch( nSign )
        {
            case B_NAME:
                r.ReadByteString( aName, eCharSet );
                //r >> aName;
                break;
            case B_COMMENT:
                r.ReadByteString( aComment, eCharSet );
                //r >> aComment;
                break;
            case B_SOURCE:
                r.ReadByteString( aSource, eCharSet );
                //r >> aSource;
                break;
            case B_PCODE:
                if( bBadVer ) break;
                pCode = new char[ nLen ];
                nCodeSize = (USHORT) nLen;
                r.Read( pCode, nCodeSize );
                break;
            case B_PUBLICS:
            case B_POOLDIR:
            case B_SYMPOOL:
            case B_LINERANGES:
                break;
            case B_STRINGPOOL:
                if( bBadVer ) break;
                MakeStrings( nCount );
                for( i = 0; i < nStrings && SbiGood( r ); i++ )
                {
                    r >> nOff;
                    pStringOff[ i ] = (USHORT) nOff;
                }
                r >> nLen;
                if( SbiGood( r ) )
                {
                    delete pStrings;
                    pStrings = new sal_Unicode[ nLen ];
                    nStringSize = (USHORT) nLen;

                    char* pByteStrings = new char[ nLen ];
                    r.Read( pByteStrings, nStringSize );
                    for( short i = 0; i < nStrings; i++ )
                    {
                        USHORT nOff = pStringOff[ i ];
                        String aStr( pByteStrings + nOff, eCharSet );
                        memcpy( pStrings + nOff, aStr.GetBuffer(), (aStr.Len() + 1) * sizeof( sal_Unicode ) );
                    }
                    delete pByteStrings;
                } break;
            case B_MODEND:
                goto done;
            default:
                break;
        }
        else
            break;
        r.Seek( nNext );
    }
done:
    r.Seek( nLast );
    //if( eCharSet != ::GetSystemCharSet() )
        //ConvertStrings();
    if( !SbiGood( r ) )
        bError = TRUE;
    return BOOL( !bError );
}

BOOL SbiImage::Save( SvStream& r )
{
    // Erst mal der Header:
    ULONG nStart = SbiOpenRecord( r, B_MODULE, 1 );
    ULONG nPos;
    r << (INT32) B_CURVERSION
      << (INT32) eCharSet
      << (INT32) nDimBase
      << (INT16) nFlags
      << (INT16) 0
      << (INT32) 0
      << (INT32) 0;

    // Name?
    if( aName.Len() && SbiGood( r ) )
    {
        nPos = SbiOpenRecord( r, B_NAME, 1 );
        r.WriteByteString( aName, eCharSet );
        //r << aName;
        SbiCloseRecord( r, nPos );
    }
    // Kommentar?
    if( aComment.Len() && SbiGood( r ) )
    {
        nPos = SbiOpenRecord( r, B_COMMENT, 1 );
        r.WriteByteString( aComment, eCharSet );
        //r << aComment;
        SbiCloseRecord( r, nPos );
    }
    // Source?
    if( aSource.Len() && SbiGood( r ) )
    {
        nPos = SbiOpenRecord( r, B_SOURCE, 1 );
        r.WriteByteString( aSource, eCharSet );
        //r << aSource;
        SbiCloseRecord( r, nPos );
    }
    // Binaere Daten?
    if( pCode && SbiGood( r ) )
    {
        nPos = SbiOpenRecord( r, B_PCODE, 1 );
        r.Write( pCode, nCodeSize );
        SbiCloseRecord( r, nPos );
    }
    // String-Pool?
    if( nStrings )
    {
        nPos = SbiOpenRecord( r, B_STRINGPOOL, nStrings );
        // Fuer jeden String:
        //  UINT32 Offset des Strings im Stringblock
        for( short i = 0; i < nStrings && SbiGood( r ); i++ )
            r << (UINT32) pStringOff[ i ];

        // Danach der String-Block
        char* pByteStrings = new char[ nStringSize ];
        for( i = 0; i < nStrings; i++ )
        {
            USHORT nOff = pStringOff[ i ];
            ByteString aStr( pStrings + nOff, eCharSet );
            memcpy( pByteStrings + nOff, aStr.GetBuffer(), (aStr.Len() + 1) * sizeof( char ) );
        }
        r << (UINT32) nStringSize;
        r.Write( pByteStrings, nStringSize );
        delete pByteStrings;
        SbiCloseRecord( r, nPos );
    }
    // Und die Gesamtlaenge setzen
    SbiCloseRecord( r, nStart );
    if( !SbiGood( r ) )
        bError = TRUE;
    return BOOL( !bError );
}

/**************************************************************************
*
*   Routinen, die auch vom Compiler gerufen werden
*
**************************************************************************/

void SbiImage::MakeStrings( short nSize )
{
    nStrings = nStringIdx = nStringOff = 0;
    nStringSize = 1024;
    pStrings = new sal_Unicode[ nStringSize ];
    pStringOff = new UINT16[ nSize ];
    if( pStrings && pStringOff )
    {
        nStrings = nSize;
        memset( pStringOff, 0, nSize * sizeof( UINT16 ) );
        memset( pStrings, 0, nStringSize * sizeof( sal_Unicode ) );
    }
    else
        bError = TRUE;
}

// Hinzufuegen eines Strings an den StringPool. Der String-Puffer
// waechst dynamisch in 1K-Schritten

// AB 12.5.2000 Aus Zeitgruenden vorerst weiter auf char-Basis
// TODO: Auch hier auf Unicode umstellen, d.h. sal_Unicode-Array
void SbiImage::AddString( const String& r )
{
    if( nStringIdx >= nStrings )
        bError = TRUE;
    if( !bError )
    {
        UINT16 len = r.Len() + 1;
        long needed = (long) nStringOff + len;
        if( needed > 0xFF00L )
            bError = TRUE;  // out of mem!
        else if( (USHORT) needed > nStringSize )
        {
            sal_Unicode* p = new sal_Unicode[ nStringSize + 1024 ];
            if( p )
            {
                memcpy( p, pStrings, nStringSize * sizeof( sal_Unicode ) );
                delete pStrings;
                pStrings = p;
                nStringSize += 1024;
            }
            else
                bError = TRUE;
        }
        if( !bError )
        {
            pStringOff[ nStringIdx++ ] = nStringOff;
            //ByteString aByteStr( r, eCharSet );
            memcpy( pStrings + nStringOff, r.GetBuffer(), len * sizeof( sal_Unicode ) );
            nStringOff += len;
            // war das der letzte String? Dann die Groesse
            // des Puffers aktualisieren
            if( nStringIdx >= nStrings )
                nStringSize = nStringOff;
        }
    }
}

// Codeblock hinzufuegen
// Der Block wurde vom Compiler aus der Klasse SbBuffer herausgeholt
// und ist bereits per new angelegt. Ausserdem enthaelt er alle Integers
// im Big Endian-Format, kann also direkt gelesen/geschrieben werden.

void SbiImage::AddCode( char* p, USHORT s )
{
    pCode = p;
    nCodeSize = s;
}

void SbiImage::AddType(SbxObject* pObject) // User-Type mit aufnehmen
{
    SbxObject *pCopyObject = new SbxObject(*pObject);
    rTypes->Insert (pCopyObject,rTypes->Count());
}

/**************************************************************************
*
*   Zugriffe auf das Image
*
**************************************************************************/

// IDs zaehlen ab 1!!

String SbiImage::GetString( short nId ) const
{
    if( nId && nId <= nStrings )
    {
        USHORT nOff = pStringOff[ --nId ];
        String aStr( pStrings + nOff );
        return aStr;
    }
    return String();
}

const SbxObject* SbiImage::FindType (String aTypeName) const
{
        return (SbxObject *)rTypes->Find(aTypeName,SbxCLASS_OBJECT);
}

<commit_msg>#90481# Use GetSOLoad/StoreTextEncoding()<commit_after>/*************************************************************************
 *
 *  $RCSfile: image.cxx,v $
 *
 *  $Revision: 1.2 $
 *
 *  last change: $Author: ab $ $Date: 2001-08-07 11:20:11 $
 *
 *  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 _STREAM_HXX //autogen
#include <tools/stream.hxx>
#endif
#include <tools/tenccvt.hxx>
#pragma hdrstop
#include <svtools/sbx.hxx>
#include "sb.hxx"
#include <string.h>     // memset() etc
#include "image.hxx"
#include "filefmt.hxx"

#include "segmentc.hxx"
#pragma SW_SEGMENT_CLASS( SBASIC, SBASIC_CODE )

SbiImage::SbiImage()
{
    rTypes     = new SbxArray;
    pStringOff = NULL;
    pStrings   = NULL;
    pCode      = NULL;
    nFlags     =
    nStrings   =
    nStringSize=
    nCodeSize  =
    nDimBase   = 0;
    bInit      =
    bError     = FALSE;
    eCharSet   = gsl_getSystemTextEncoding();
}

SbiImage::~SbiImage()
{
    Clear();
}

void SbiImage::Clear()
{
    delete pStringOff;
    delete pStrings;
    delete pCode;
    pStringOff = NULL;
    pStrings   = NULL;
    pCode      = NULL;
    nFlags     =
    nStrings   =
    nStringSize=
    nCodeSize  = 0;
    eCharSet   = gsl_getSystemTextEncoding();
    nDimBase   = 0;
    bError     = FALSE;
}

/**************************************************************************
*
*   Service-Routinen fuer das Laden und Speichern
*
**************************************************************************/

BOOL SbiGood( SvStream& r )
{
    return BOOL( !r.IsEof() && r.GetError() == SVSTREAM_OK );
}

// Oeffnen eines Records

ULONG SbiOpenRecord( SvStream& r, UINT16 nSignature, UINT16 nElem )
{
    ULONG nPos = r.Tell();
    r << nSignature << (INT32) 0 << nElem;
    return nPos;
}

// Schliessen eines Records

void SbiCloseRecord( SvStream& r, ULONG nOff )
{
    ULONG nPos = r.Tell();
    r.Seek( nOff + 2 );
    r << (INT32) ( nPos - nOff - 8 );
    r.Seek( nPos );
}

/**************************************************************************
*
*   Laden und Speichern
*
**************************************************************************/

// Falls die Versionsnummer nicht passt, werden die binaeren Teile
// nicht geladen, wohl aber Source, Kommentar und Name.

BOOL SbiImage::Load( SvStream& r )
{
    UINT16 nSign, nCount;
    UINT32 nLen, nOff;

    Clear();
    ULONG nStart = r.Tell();
    // Master-Record einlesen
    r >> nSign >> nLen >> nCount;
    ULONG nLast = r.Tell() + nLen;
    UINT32 nVersion = 0;            // Versionsnummer
    UINT32 nCharSet;                // System-Zeichensatz
    UINT32 lDimBase;
    UINT16 nReserved1;
    UINT32 nReserved2;
    UINT32 nReserved3;
    BOOL bBadVer = FALSE;
    if( nSign == B_MODULE )
    {
        r >> nVersion >> nCharSet >> lDimBase
          >> nFlags >> nReserved1 >> nReserved2 >> nReserved3;
        eCharSet = (CharSet) nCharSet;
        eCharSet = GetSOLoadTextEncoding( eCharSet );
        bBadVer  = BOOL( nVersion != B_CURVERSION );
        nDimBase = (USHORT) lDimBase;
    }

    ULONG nNext;
    while( ( nNext = r.Tell() ) < nLast )
    {
        short i;

        r >> nSign >> nLen >> nCount;
        nNext += nLen + 8;
        if( r.GetError() == SVSTREAM_OK )
          switch( nSign )
        {
            case B_NAME:
                r.ReadByteString( aName, eCharSet );
                //r >> aName;
                break;
            case B_COMMENT:
                r.ReadByteString( aComment, eCharSet );
                //r >> aComment;
                break;
            case B_SOURCE:
                r.ReadByteString( aSource, eCharSet );
                //r >> aSource;
                break;
            case B_PCODE:
                if( bBadVer ) break;
                pCode = new char[ nLen ];
                nCodeSize = (USHORT) nLen;
                r.Read( pCode, nCodeSize );
                break;
            case B_PUBLICS:
            case B_POOLDIR:
            case B_SYMPOOL:
            case B_LINERANGES:
                break;
            case B_STRINGPOOL:
                if( bBadVer ) break;
                MakeStrings( nCount );
                for( i = 0; i < nStrings && SbiGood( r ); i++ )
                {
                    r >> nOff;
                    pStringOff[ i ] = (USHORT) nOff;
                }
                r >> nLen;
                if( SbiGood( r ) )
                {
                    delete pStrings;
                    pStrings = new sal_Unicode[ nLen ];
                    nStringSize = (USHORT) nLen;

                    char* pByteStrings = new char[ nLen ];
                    r.Read( pByteStrings, nStringSize );
                    for( short i = 0; i < nStrings; i++ )
                    {
                        USHORT nOff = pStringOff[ i ];
                        String aStr( pByteStrings + nOff, eCharSet );
                        memcpy( pStrings + nOff, aStr.GetBuffer(), (aStr.Len() + 1) * sizeof( sal_Unicode ) );
                    }
                    delete pByteStrings;
                } break;
            case B_MODEND:
                goto done;
            default:
                break;
        }
        else
            break;
        r.Seek( nNext );
    }
done:
    r.Seek( nLast );
    //if( eCharSet != ::GetSystemCharSet() )
        //ConvertStrings();
    if( !SbiGood( r ) )
        bError = TRUE;
    return BOOL( !bError );
}

BOOL SbiImage::Save( SvStream& r )
{
    // Erst mal der Header:
    ULONG nStart = SbiOpenRecord( r, B_MODULE, 1 );
    ULONG nPos;

    eCharSet = GetSOStoreTextEncoding( eCharSet );

    r << (INT32) B_CURVERSION
      << (INT32) eCharSet
      << (INT32) nDimBase
      << (INT16) nFlags
      << (INT16) 0
      << (INT32) 0
      << (INT32) 0;

    // Name?
    if( aName.Len() && SbiGood( r ) )
    {
        nPos = SbiOpenRecord( r, B_NAME, 1 );
        r.WriteByteString( aName, eCharSet );
        //r << aName;
        SbiCloseRecord( r, nPos );
    }
    // Kommentar?
    if( aComment.Len() && SbiGood( r ) )
    {
        nPos = SbiOpenRecord( r, B_COMMENT, 1 );
        r.WriteByteString( aComment, eCharSet );
        //r << aComment;
        SbiCloseRecord( r, nPos );
    }
    // Source?
    if( aSource.Len() && SbiGood( r ) )
    {
        nPos = SbiOpenRecord( r, B_SOURCE, 1 );
        r.WriteByteString( aSource, eCharSet );
        //r << aSource;
        SbiCloseRecord( r, nPos );
    }
    // Binaere Daten?
    if( pCode && SbiGood( r ) )
    {
        nPos = SbiOpenRecord( r, B_PCODE, 1 );
        r.Write( pCode, nCodeSize );
        SbiCloseRecord( r, nPos );
    }
    // String-Pool?
    if( nStrings )
    {
        nPos = SbiOpenRecord( r, B_STRINGPOOL, nStrings );
        // Fuer jeden String:
        //  UINT32 Offset des Strings im Stringblock
        for( short i = 0; i < nStrings && SbiGood( r ); i++ )
            r << (UINT32) pStringOff[ i ];

        // Danach der String-Block
        char* pByteStrings = new char[ nStringSize ];
        for( i = 0; i < nStrings; i++ )
        {
            USHORT nOff = pStringOff[ i ];
            ByteString aStr( pStrings + nOff, eCharSet );
            memcpy( pByteStrings + nOff, aStr.GetBuffer(), (aStr.Len() + 1) * sizeof( char ) );
        }
        r << (UINT32) nStringSize;
        r.Write( pByteStrings, nStringSize );
        delete pByteStrings;
        SbiCloseRecord( r, nPos );
    }
    // Und die Gesamtlaenge setzen
    SbiCloseRecord( r, nStart );
    if( !SbiGood( r ) )
        bError = TRUE;
    return BOOL( !bError );
}

/**************************************************************************
*
*   Routinen, die auch vom Compiler gerufen werden
*
**************************************************************************/

void SbiImage::MakeStrings( short nSize )
{
    nStrings = nStringIdx = nStringOff = 0;
    nStringSize = 1024;
    pStrings = new sal_Unicode[ nStringSize ];
    pStringOff = new UINT16[ nSize ];
    if( pStrings && pStringOff )
    {
        nStrings = nSize;
        memset( pStringOff, 0, nSize * sizeof( UINT16 ) );
        memset( pStrings, 0, nStringSize * sizeof( sal_Unicode ) );
    }
    else
        bError = TRUE;
}

// Hinzufuegen eines Strings an den StringPool. Der String-Puffer
// waechst dynamisch in 1K-Schritten

// AB 12.5.2000 Aus Zeitgruenden vorerst weiter auf char-Basis
// TODO: Auch hier auf Unicode umstellen, d.h. sal_Unicode-Array
void SbiImage::AddString( const String& r )
{
    if( nStringIdx >= nStrings )
        bError = TRUE;
    if( !bError )
    {
        UINT16 len = r.Len() + 1;
        long needed = (long) nStringOff + len;
        if( needed > 0xFF00L )
            bError = TRUE;  // out of mem!
        else if( (USHORT) needed > nStringSize )
        {
            sal_Unicode* p = new sal_Unicode[ nStringSize + 1024 ];
            if( p )
            {
                memcpy( p, pStrings, nStringSize * sizeof( sal_Unicode ) );
                delete pStrings;
                pStrings = p;
                nStringSize += 1024;
            }
            else
                bError = TRUE;
        }
        if( !bError )
        {
            pStringOff[ nStringIdx++ ] = nStringOff;
            //ByteString aByteStr( r, eCharSet );
            memcpy( pStrings + nStringOff, r.GetBuffer(), len * sizeof( sal_Unicode ) );
            nStringOff += len;
            // war das der letzte String? Dann die Groesse
            // des Puffers aktualisieren
            if( nStringIdx >= nStrings )
                nStringSize = nStringOff;
        }
    }
}

// Codeblock hinzufuegen
// Der Block wurde vom Compiler aus der Klasse SbBuffer herausgeholt
// und ist bereits per new angelegt. Ausserdem enthaelt er alle Integers
// im Big Endian-Format, kann also direkt gelesen/geschrieben werden.

void SbiImage::AddCode( char* p, USHORT s )
{
    pCode = p;
    nCodeSize = s;
}

void SbiImage::AddType(SbxObject* pObject) // User-Type mit aufnehmen
{
    SbxObject *pCopyObject = new SbxObject(*pObject);
    rTypes->Insert (pCopyObject,rTypes->Count());
}

/**************************************************************************
*
*   Zugriffe auf das Image
*
**************************************************************************/

// IDs zaehlen ab 1!!

String SbiImage::GetString( short nId ) const
{
    if( nId && nId <= nStrings )
    {
        USHORT nOff = pStringOff[ --nId ];
        String aStr( pStrings + nOff );
        return aStr;
    }
    return String();
}

const SbxObject* SbiImage::FindType (String aTypeName) const
{
        return (SbxObject *)rTypes->Find(aTypeName,SbxCLASS_OBJECT);
}

<|endoftext|>


<commit_before>
#ifndef __CLIENT_HPP__
#define __CLIENT_HPP__

#include <pthread.h>
#include "protocol.hpp"

using namespace std;

/* Information shared between clients */
struct shared_t {
public:
    typedef protocol_t*(*protocol_factory_t)(void);

public:
    shared_t(config_t *_config, protocol_factory_t _protocol_factory)
        : config(_config),
          qps_offset(0), latencies_offset(0),
          qps_fd(NULL), latencies_fd(NULL),
          protocol_factory(_protocol_factory)
        {
            pthread_mutex_init(&mutex, NULL);

            if(config->qps_file[0] != 0) {
                qps_fd = fopen(config->qps_file, "wa");
            }
            if(config->latency_file[0] != 0) {
                latencies_fd = fopen(config->latency_file, "wa");
            }
        }

    ~shared_t() {
        if(qps_fd) {
            fwrite(qps, 1, qps_offset, qps_fd);
            fclose(qps_fd);
        }
        if(latencies_fd) {
            fwrite(latencies, 1, latencies_offset, latencies_fd);
            fclose(latencies_fd);
        }

        pthread_mutex_destroy(&mutex);
    }

    void push_qps(int _qps, int tick) {
        if(!qps_fd)
            return;

        lock();

        // Collect qps info from all clients before attempting to print
        int qps_count = 0, agg_qps = 0;
        map<int, pair<int, int> >::iterator op = qps_map.find(tick);
        if(op != qps_map.end()) {
            qps_count = op->second.first;
            agg_qps = op->second.second;
        }

        qps_count += 1;
        agg_qps += _qps;

        if(qps_count == config->clients) {
            _qps = agg_qps;
            qps_map.erase(op);
        } else {
            qps_map[tick] = pair<int, int>(qps_count, agg_qps);
            unlock();
            return;
        }

        int _off = snprintf(qps + qps_offset, sizeof(qps) - qps_offset, "%d\n", _qps);
        if(_off >= sizeof(qps) - qps_offset) {
            // Couldn't write everything, flush
            fwrite(qps, 1, qps_offset, qps_fd);

            // Write again
            qps_offset = 0;
            _off = snprintf(qps + qps_offset, sizeof(qps) - qps_offset, "%d\n", _qps);
        }
        qps_offset += _off;

        unlock();
    }

    void push_latency(float latency) {
        if(!latencies_fd)
            return;

        lock();

        int _off = snprintf(latencies + latencies_offset, sizeof(latencies) - latencies_offset, "%.2f\n", latency);
        if(_off >= sizeof(latencies) - latencies_offset) {
            // Couldn't write everything, flush
            fwrite(latencies, 1, latencies_offset, latencies_fd);

            // Write again
            latencies_offset = 0;
            _off = snprintf(latencies + latencies_offset, sizeof(latencies) - latencies_offset, "%.2f\n", latency);
        }
        latencies_offset += _off;

        unlock();
    }

public:
    protocol_factory_t protocol_factory;

private:
    config_t *config;
    map<int, pair<int, int> > qps_map;
    char qps[40960], latencies[40960];
    int qps_offset, latencies_offset;
    FILE *qps_fd, *latencies_fd;
    pthread_mutex_t mutex;

private:
    void lock() {
        pthread_mutex_lock(&mutex);
    }
    void unlock() {
        pthread_mutex_unlock(&mutex);
    }
};

/* Communication structure for main thread and clients */
struct client_data_t {
    config_t *config;
    shared_t *shared;
};

/* The function that does the work */
void* run_client(void* data) {
    // Grab the config
    client_data_t *client_data = (client_data_t*)data;
    config_t *config = client_data->config;
    shared_t *shared = client_data->shared;
    shared_t::protocol_factory_t pf = shared->protocol_factory;
    protocol_t *proto = (*pf)();

    // Connect to the server
    proto->connect(config->host, config->port);

    // Store the keys so we can run updates and deletes.
    vector<payload_t> keys;

    // Perform the ops
    ticks_t last_time = get_ticks(), last_qps_time = last_time, now_time;
    int qps = 0, tick = 0;
    for(int i = 0; i < config->duration / config->clients; i++) {
        // Generate the command
        load_t::load_op_t cmd = config->load.toss();

        int _val;
        payload_t key, value;

        switch(cmd) {
        case load_t::delete_op:
            // Find the key
            if(keys.empty())
                break;
            _val = random(0, keys.size() - 1);
            key = keys[_val];
            // Delete it from the server
            proto->remove(key.first, key.second);
            // Our own bookkeeping
            free(key.first);
            keys[_val] = keys[keys.size() - 1];
            keys.erase(keys.begin() + _val);
            break;

        case load_t::update_op:
            // Find the key and generate the payload
            if(keys.empty())
                break;
            key = keys[random(0, keys.size() - 1)];
            config->values.toss(&value);
            // Send it to server
            proto->update(key.first, key.second, value.first, value.second);
            // Free the value
            free(value.first);
            break;

        case load_t::insert_op:
            // Generate the payload
            config->keys.toss(&key);
            config->values.toss(&value);
            // Send it to server
            proto->insert(key.first, key.second, value.first, value.second);
            // Free the value and save the key
            free(value.first);
            keys.push_back(key);
            break;

        case load_t::read_op:
            // Find the key
            if(keys.empty())
                break;
            key = keys[random(0, keys.size() - 1)];
            // Read it from the server
            proto->read(key.first, key.second);
            break;
        };
        now_time = get_ticks();
        qps++;

        // Deal with individual op latency
        ticks_t latency = now_time - last_time;
        shared->push_latency(ticks_to_us(latency));
        last_time = now_time;

        // Deal with QPS
        if(ticks_to_secs(now_time - last_qps_time) >= 1.0f) {
            shared->push_qps(qps, tick);

            last_qps_time = now_time;
            qps = 0;
            tick++;
        }
    }

    delete proto;

    // Free all the keys
    for(vector<payload_t>::iterator i = keys.begin(); i != keys.end(); i++) {
        free(i->first);
    }
}

#endif // __CLIENT_HPP__

<commit_msg>Changing the client to report seconds for each number<commit_after>
#ifndef __CLIENT_HPP__
#define __CLIENT_HPP__

#include <pthread.h>
#include "protocol.hpp"

using namespace std;

/* Information shared between clients */
struct shared_t {
public:
    typedef protocol_t*(*protocol_factory_t)(void);

public:
    shared_t(config_t *_config, protocol_factory_t _protocol_factory)
        : config(_config),
          qps_offset(0), latencies_offset(0),
          qps_fd(NULL), latencies_fd(NULL),
          protocol_factory(_protocol_factory),
          n_op(1), n_tick(1)
        {
            pthread_mutex_init(&mutex, NULL);

            if(config->qps_file[0] != 0) {
                qps_fd = fopen(config->qps_file, "wa");
            }
            if(config->latency_file[0] != 0) {
                latencies_fd = fopen(config->latency_file, "wa");
            }
        }

    ~shared_t() {
        if(qps_fd) {
            fwrite(qps, 1, qps_offset, qps_fd);
            fclose(qps_fd);
        }
        if(latencies_fd) {
            fwrite(latencies, 1, latencies_offset, latencies_fd);
            fclose(latencies_fd);
        }

        pthread_mutex_destroy(&mutex);
    }

    void push_qps(int _qps, int tick) {
        if(!qps_fd)
            return;

        lock();

        // Collect qps info from all clients before attempting to print
        int qps_count = 0, agg_qps = 0;
        map<int, pair<int, int> >::iterator op = qps_map.find(tick);
        if(op != qps_map.end()) {
            qps_count = op->second.first;
            agg_qps = op->second.second;
        }

        qps_count += 1;
        agg_qps += _qps;

        if(qps_count == config->clients) {
            _qps = agg_qps;
            qps_map.erase(op);
        } else {
            qps_map[tick] = pair<int, int>(qps_count, agg_qps);
            unlock();
            return;
        }

        int _off = snprintf(qps + qps_offset, sizeof(qps) - qps_offset, "%d\t\t%d\n", n_tick, _qps);
        if(_off >= sizeof(qps) - qps_offset) {
            // Couldn't write everything, flush
            fwrite(qps, 1, qps_offset, qps_fd);

            // Write again
            qps_offset = 0;
            _off = snprintf(qps + qps_offset, sizeof(qps) - qps_offset, "%d\t\t%d\n", n_tick, _qps);
        }
        qps_offset += _off;

        n_tick++;

        unlock();
    }

    void push_latency(float latency) {
        if(!latencies_fd)
            return;

        lock();

        int _off = snprintf(latencies + latencies_offset, sizeof(latencies) - latencies_offset, "%ld\t\t%.2f\n", n_op, latency);
        if(_off >= sizeof(latencies) - latencies_offset) {
            // Couldn't write everything, flush
            fwrite(latencies, 1, latencies_offset, latencies_fd);

            // Write again
            latencies_offset = 0;
            _off = snprintf(latencies + latencies_offset, sizeof(latencies) - latencies_offset, "%ld\t\t%.2f\n", n_op, latency);
        }
        latencies_offset += _off;

        n_op++;

        unlock();
    }

public:
    protocol_factory_t protocol_factory;

private:
    config_t *config;
    map<int, pair<int, int> > qps_map;
    char qps[40960], latencies[40960];
    int qps_offset, latencies_offset;
    FILE *qps_fd, *latencies_fd;
    pthread_mutex_t mutex;

    long n_op;
    int n_tick;

private:
    void lock() {
        pthread_mutex_lock(&mutex);
    }
    void unlock() {
        pthread_mutex_unlock(&mutex);
    }
};

/* Communication structure for main thread and clients */
struct client_data_t {
    config_t *config;
    shared_t *shared;
};

/* The function that does the work */
void* run_client(void* data) {
    // Grab the config
    client_data_t *client_data = (client_data_t*)data;
    config_t *config = client_data->config;
    shared_t *shared = client_data->shared;
    shared_t::protocol_factory_t pf = shared->protocol_factory;
    protocol_t *proto = (*pf)();

    // Connect to the server
    proto->connect(config->host, config->port);

    // Store the keys so we can run updates and deletes.
    vector<payload_t> keys;

    // Perform the ops
    ticks_t last_time = get_ticks(), last_qps_time = last_time, now_time;
    int qps = 0, tick = 0;
    for(int i = 0; i < config->duration / config->clients; i++) {
        // Generate the command
        load_t::load_op_t cmd = config->load.toss();

        int _val;
        payload_t key, value;

        switch(cmd) {
        case load_t::delete_op:
            // Find the key
            if(keys.empty())
                break;
            _val = random(0, keys.size() - 1);
            key = keys[_val];
            // Delete it from the server
            proto->remove(key.first, key.second);
            // Our own bookkeeping
            free(key.first);
            keys[_val] = keys[keys.size() - 1];
            keys.erase(keys.begin() + _val);
            break;

        case load_t::update_op:
            // Find the key and generate the payload
            if(keys.empty())
                break;
            key = keys[random(0, keys.size() - 1)];
            config->values.toss(&value);
            // Send it to server
            proto->update(key.first, key.second, value.first, value.second);
            // Free the value
            free(value.first);
            break;

        case load_t::insert_op:
            // Generate the payload
            config->keys.toss(&key);
            config->values.toss(&value);
            // Send it to server
            proto->insert(key.first, key.second, value.first, value.second);
            // Free the value and save the key
            free(value.first);
            keys.push_back(key);
            break;

        case load_t::read_op:
            // Find the key
            if(keys.empty())
                break;
            key = keys[random(0, keys.size() - 1)];
            // Read it from the server
            proto->read(key.first, key.second);
            break;
        };
        now_time = get_ticks();
        qps++;

        // Deal with individual op latency
        ticks_t latency = now_time - last_time;
        shared->push_latency(ticks_to_us(latency));
        last_time = now_time;

        // Deal with QPS
        if(ticks_to_secs(now_time - last_qps_time) >= 1.0f) {
            shared->push_qps(qps, tick);

            last_qps_time = now_time;
            qps = 0;
            tick++;
        }
    }

    delete proto;

    // Free all the keys
    for(vector<payload_t>::iterator i = keys.begin(); i != keys.end(); i++) {
        free(i->first);
    }
}

#endif // __CLIENT_HPP__

<|endoftext|>


<commit_before>#include <nan.h>

// toys used in testing
#include <cmath>
#include <time.h>

//==============================================================================
// Implementation sketch
//==============================================================================

namespace NanIntern { // scnr

template <typename T> struct FactoryBase { typedef v8::Local<T> return_t; };

template <typename T> struct Factory;

template <>
struct Factory<v8::Array> : public FactoryBase<v8::Array> {
    static inline return_t New() {
        return v8::Array::New(v8::Isolate::GetCurrent());
    }
    static inline return_t New(int length) {
        return v8::Array::New(v8::Isolate::GetCurrent(), length);
    }
};

template <>
struct Factory<v8::Boolean> : public FactoryBase<v8::Boolean> {
    static inline return_t New(bool value) {
        return v8::Boolean::New(v8::Isolate::GetCurrent(), value);
    }
};

template <>
struct Factory<v8::External> : public FactoryBase<v8::External> {
    static inline return_t New(void *value) {
        return v8::External::New(v8::Isolate::GetCurrent(), value);
    }
};

template <>
struct Factory<v8::Date> : public FactoryBase<v8::Date> {
    static inline return_t New(double value) {
        return v8::Date::New(v8::Isolate::GetCurrent(), value).As<v8::Date>();
    }
};

template <>
struct Factory<v8::String> : public FactoryBase<v8::String> {
    static inline return_t New(const char * value) {
        return v8::String::NewFromUtf8(v8::Isolate::GetCurrent(), value);
    }
    static inline return_t New(const char * value, int length) {
        return v8::String::NewFromUtf8(v8::Isolate::GetCurrent(), value,
                v8::String::kNormalString, length);
    }
    static inline return_t New(std::string const & value) {
        return v8::String::NewFromUtf8(v8::Isolate::GetCurrent(),
                &*value.begin(), v8::String::kNormalString, value.size());
    }
};

//=== Numeric Types ============================================================

template <>
struct Factory<v8::Number> : public FactoryBase<v8::Number> {
    static inline return_t New(double value) {
        return v8::Number::New(v8::Isolate::GetCurrent(), value);
    }
};

template <typename T> v8::Local<T> To(v8::Handle<v8::Integer> i);

template <>
v8::Local<v8::Integer>
To<v8::Integer>(v8::Handle<v8::Integer> i) { return i; }

template <>
v8::Local<v8::Int32>
To<v8::Int32>(v8::Handle<v8::Integer> i)   { return i->ToInt32(); }

template <>
v8::Local<v8::Uint32>
To<v8::Uint32>(v8::Handle<v8::Integer> i)  { return i->ToUint32(); }

template <typename T>
struct IntegerFactory : public FactoryBase<T>{
    typedef typename FactoryBase<T>::return_t return_t;
    static inline return_t New(int32_t value)  {
        return To<T>(T::New(v8::Isolate::GetCurrent(), value));
    }
    static inline return_t New(uint32_t value) {
        return To<T>(T::NewFromUnsigned(v8::Isolate::GetCurrent(), value));
    }
};

template <>
struct Factory<v8::Integer> : public IntegerFactory<v8::Integer> {};

template <>
struct Factory<v8::Int32> : public IntegerFactory<v8::Int32> {};

template <>
struct Factory<v8::Uint32> : public IntegerFactory<v8::Uint32> {};

} // end of namespace NanIntern

//=== API ======================================================================

template <typename T>
typename NanIntern::Factory<T>::return_t
NanNew2() {
    return NanIntern::Factory<T>::New();
}

template <typename T, typename A0>
typename NanIntern::Factory<T>::return_t
NanNew2(A0 arg0) {
    return NanIntern::Factory<T>::New(arg0);
}

template <typename T, typename A0, typename A1>
typename NanIntern::Factory<T>::return_t
NanNew2(A0 arg0, A1 arg1) {
    return NanIntern::Factory<T>::New(arg0, arg1);
}

void
NanExport(v8::Handle<v8::Object> target, const char * name,
        NanFunctionCallback f)
{
    target->Set(NanNew<v8::String>(name),
            NanNew<v8::FunctionTemplate>(f)->GetFunction());
}

#define return_NanValue(v) NanReturnValue(v)
#define NAN_EXPORT(target, function) NanExport(target, #function, function)

//==============================================================================
// Sample Module
//==============================================================================

NAN_METHOD(newIntegerWithValue) {
    NanScope();
    return_NanValue(NanNew2<v8::Integer>(args[0]->Int32Value()));
}

NAN_METHOD(newNumberWithValue) {
    NanScope();
    return_NanValue(NanNew2<v8::Number>(args[0]->NumberValue()));
}

NAN_METHOD(newUint32WithValue) {
    NanScope();
    return_NanValue(NanNew2<v8::Uint32>(args[0]->Uint32Value()));
}

NAN_METHOD(newStringFromChars) {
    NanScope();
    return_NanValue(NanNew2<v8::String>("hello?"));
}

NAN_METHOD(newStringFromCharsWithLength) {
    NanScope();
    return_NanValue(NanNew2<v8::String>("hello?", 4));
}

NAN_METHOD(newStringFromStdString) {
    NanScope();
    return_NanValue(NanNew2<v8::String>(std::string("hello!")));
}

NAN_METHOD(demoDateAndNumber) {
    NanScope();
    v8::Local<v8::Value> number = NanNew<v8::Number>(M_PI);
    v8::Local<v8::Value> date   = NanNew<v8::Date>(double(time(NULL)));
    (void)number; (void)date; // unused
    NanReturnUndefined();
}

int ttt = 23;

NAN_METHOD(newExternal) {
    NanScope();
    return_NanValue(NanNew2<v8::External>(&ttt));
}
void Init(v8::Handle<v8::Object> exports) {
    NanExport(exports, "newIntegerWithValue", newIntegerWithValue);
    NAN_EXPORT(exports, newNumberWithValue);
    NAN_EXPORT(exports, newUint32WithValue);
    NAN_EXPORT(exports, newStringFromChars);
    NAN_EXPORT(exports, newStringFromCharsWithLength);
    NAN_EXPORT(exports, newStringFromStdString);
    NAN_EXPORT(exports, demoDateAndNumber);

    NAN_EXPORT(exports, newExternal);
}

NODE_MODULE(nan_sketch, Init)

<commit_msg>Fixed indentation.<commit_after>#include <nan.h>

// toys used in testing
#include <cmath>
#include <time.h>

//==============================================================================
// Implementation sketch
//==============================================================================

//namespace NanIntern { // scnr

template <typename T> struct FactoryBase { typedef v8::Local<T> return_t; };

template <typename T> struct Factory;

template <>
struct Factory<v8::Array> : public FactoryBase<v8::Array> {
  static inline return_t New() {
    return v8::Array::New(v8::Isolate::GetCurrent());
  }
  static inline return_t New(int length) {
    return v8::Array::New(v8::Isolate::GetCurrent(), length);
  }
};

template <>
struct Factory<v8::Boolean> : public FactoryBase<v8::Boolean> {
  static inline return_t New(bool value) {
    return v8::Boolean::New(v8::Isolate::GetCurrent(), value);
  }
};

template <>
struct Factory<v8::External> : public FactoryBase<v8::External> {
  static inline return_t New(void *value) {
    return v8::External::New(v8::Isolate::GetCurrent(), value);
  }
};

template <>
struct Factory<v8::Date> : public FactoryBase<v8::Date> {
  static inline return_t New(double value) {
    return v8::Date::New(v8::Isolate::GetCurrent(), value).As<v8::Date>();
  }
};

template <>
struct Factory<v8::String> : public FactoryBase<v8::String> {
  static inline return_t New(const char * value) {
    return v8::String::NewFromUtf8(v8::Isolate::GetCurrent(), value);
  }
  static inline return_t New(const char * value, int length) {
    return v8::String::NewFromUtf8(v8::Isolate::GetCurrent(), value,
        v8::String::kNormalString, length);
  }
  static inline return_t New(std::string const & value) {
    return v8::String::NewFromUtf8(v8::Isolate::GetCurrent(),
        &*value.begin(), v8::String::kNormalString, value.size());
  }
};

//=== Numeric Types ============================================================

template <>
struct Factory<v8::Number> : public FactoryBase<v8::Number> {
  static inline return_t New(double value) {
    return v8::Number::New(v8::Isolate::GetCurrent(), value);
  }
};

template <typename T> v8::Local<T> To(v8::Handle<v8::Integer> i);

template <>
v8::Local<v8::Integer>
To<v8::Integer>(v8::Handle<v8::Integer> i) { return i; }

template <>
v8::Local<v8::Int32>
To<v8::Int32>(v8::Handle<v8::Integer> i)   { return i->ToInt32(); }

template <>
v8::Local<v8::Uint32>
To<v8::Uint32>(v8::Handle<v8::Integer> i)  { return i->ToUint32(); }

template <typename T>
struct IntegerFactory : public FactoryBase<T>{
  typedef typename FactoryBase<T>::return_t return_t;
  static inline return_t New(int32_t value)  {
    return To<T>(T::New(v8::Isolate::GetCurrent(), value));
  }
  static inline return_t New(uint32_t value) {
    return To<T>(T::NewFromUnsigned(v8::Isolate::GetCurrent(), value));
  }
};

template <>
struct Factory<v8::Integer> : public IntegerFactory<v8::Integer> {};

template <>
struct Factory<v8::Int32> : public IntegerFactory<v8::Int32> {};

template <>
struct Factory<v8::Uint32> : public IntegerFactory<v8::Uint32> {};

//} // end of namespace NanIntern

//=== API ======================================================================

template <typename T>
typename NanIntern::Factory<T>::return_t
NanNew2() {
  return NanIntern::Factory<T>::New();
}

template <typename T, typename A0>
typename NanIntern::Factory<T>::return_t
NanNew2(A0 arg0) {
  return NanIntern::Factory<T>::New(arg0);
}

template <typename T, typename A0, typename A1>
typename NanIntern::Factory<T>::return_t
NanNew2(A0 arg0, A1 arg1) {
  return NanIntern::Factory<T>::New(arg0, arg1);
}

  void
NanExport(v8::Handle<v8::Object> target, const char * name,
    NanFunctionCallback f)
{
  target->Set(NanNew<v8::String>(name),
      NanNew<v8::FunctionTemplate>(f)->GetFunction());
}

#define return_NanValue(v) NanReturnValue(v)
#define NAN_EXPORT(target, function) NanExport(target, #function, function)

//==============================================================================
// Sample Module
//==============================================================================

NAN_METHOD(newIntegerWithValue) {
  NanScope();
  return_NanValue(NanNew2<v8::Integer>(args[0]->Int32Value()));
}

NAN_METHOD(newNumberWithValue) {
  NanScope();
  return_NanValue(NanNew2<v8::Number>(args[0]->NumberValue()));
}

NAN_METHOD(newUint32WithValue) {
  NanScope();
  return_NanValue(NanNew2<v8::Uint32>(args[0]->Uint32Value()));
}

NAN_METHOD(newStringFromChars) {
  NanScope();
  return_NanValue(NanNew2<v8::String>("hello?"));
}

NAN_METHOD(newStringFromCharsWithLength) {
  NanScope();
  return_NanValue(NanNew2<v8::String>("hello?", 4));
}

NAN_METHOD(newStringFromStdString) {
  NanScope();
  return_NanValue(NanNew2<v8::String>(std::string("hello!")));
}

NAN_METHOD(demoDateAndNumber) {
  NanScope();
  v8::Local<v8::Value> number = NanNew<v8::Number>(M_PI);
  v8::Local<v8::Value> date   = NanNew<v8::Date>(double(time(NULL)));
  (void)number; (void)date; // unused
  NanReturnUndefined();
}

int ttt = 23;

NAN_METHOD(newExternal) {
  NanScope();
  return_NanValue(NanNew2<v8::External>(&ttt));
}
void Init(v8::Handle<v8::Object> exports) {
  NanExport(exports, "newIntegerWithValue", newIntegerWithValue);
  NAN_EXPORT(exports, newNumberWithValue);
  NAN_EXPORT(exports, newUint32WithValue);
  NAN_EXPORT(exports, newStringFromChars);
  NAN_EXPORT(exports, newStringFromCharsWithLength);
  NAN_EXPORT(exports, newStringFromStdString);
  NAN_EXPORT(exports, demoDateAndNumber);

  NAN_EXPORT(exports, newExternal);
}

NODE_MODULE(nan_sketch, Init)

<|endoftext|>


<commit_before>#ifndef __RANK_FILTER__
#define __RANK_FILTER__

#include <list>
#include <set>
#include <cmath>
#include <cassert>
#include <iostream>
#include <iterator>
#include <type_traits>
#include <utility>

#include <vigra/multi_array.hxx>
#include <vigra/linear_algebra.hxx>

namespace vigra
{

template<unsigned int N,
        class T1, class S1,
        class T2, class S2,
        typename std::enable_if<(N == 1), int>::type = 0>
inline void lineRankOrderFilterND(const vigra::MultiArrayView <N, T1, S1> &src,
        vigra::MultiArrayView <N, T2, S2> dest,
        unsigned int half_length, float rank, unsigned int axis = 0)
{
    // Will ignore boundaries initially.
    // Then will try adding reflection.

    // Rank must be in the range 0 to 1
    assert((0 <= rank) && (rank <= 1));

    const int rank_pos = round(rank * (2 * half_length));

    // The position of the
    typename vigra::MultiArrayView<N, T1, S1>::difference_type_1 window_begin(0);
    std::multiset<T1> sorted_window;
    std::list< typename std::multiset<T1>::iterator > window_iters;

    // Get the initial sorted window.
    // Include the reflection.
    for (typename vigra::MultiArrayView<N, T1, S1>::difference_type_1 j(half_length); j > 0; j--)
    {
        window_iters.push_back(sorted_window.insert(src[window_begin + j]));
    }
    for (typename vigra::MultiArrayView<N, T1, S1>::difference_type_1 j(0); j <= half_length; j++)
    {
        window_iters.push_back(sorted_window.insert(src[window_begin + j]));
    }

    typename std::multiset<T1>::iterator rank_point = sorted_window.begin();

    for (int i = 0; i < rank_pos; i++)
    {
        rank_point++;
    }

    typename std::multiset<T1>::iterator prev_iter;
    T1 prev_value;
    T1 next_value;
    while ( window_begin < src.size() )
    {
        dest[window_begin] = *rank_point;

        prev_iter = window_iters.front();
        prev_value = *prev_iter;
        window_iters.pop_front();

        window_begin++;

        if ( window_begin < (src.size() - half_length) )
        {
            next_value = src[window_begin + half_length];
        }
        else
        {
            next_value = src[2 * src.size() - (window_begin + half_length + 2)];
        }

        if ( ( *rank_point < prev_value ) && ( *rank_point <= next_value ) )
        {
            sorted_window.erase(prev_iter);
            window_iters.push_back(sorted_window.insert(next_value));
        }
        else if ( ( *rank_point >= prev_value ) && ( *rank_point > next_value ) )
        {
            if ( rank_point == prev_iter )
            {
                window_iters.push_back(sorted_window.insert(next_value));
                rank_point--;

                sorted_window.erase(prev_iter);
            }
            else
            {
                sorted_window.erase(prev_iter);
                window_iters.push_back(sorted_window.insert(next_value));
            }
        }
        else if ( ( *rank_point < prev_value ) && ( *rank_point > next_value ) )
        {
            sorted_window.erase(prev_iter);
            window_iters.push_back(sorted_window.insert(next_value));

            rank_point--;
        }
        else if ( ( *rank_point >= prev_value ) && ( *rank_point <= next_value ) )
        {
            if (rank_point == prev_iter)
            {
                window_iters.push_back(sorted_window.insert(next_value));
                rank_point++;

                sorted_window.erase(prev_iter);
            }
            else
            {
                sorted_window.erase(prev_iter);
                window_iters.push_back(sorted_window.insert(next_value));

                rank_point++;
            }
        }
    }
}

template<unsigned int N,
        class T1, class S1,
        class T2, class S2,
        typename std::enable_if<(N > 1), int>::type = 0>
inline void lineRankOrderFilterND(const vigra::MultiArrayView <N, T1, S1> &src,
        vigra::MultiArrayView <N, T2, S2> dest,
        unsigned int half_length, float rank, unsigned int axis = 0)
{
    typename vigra::MultiArrayView<N, T1, S1>::difference_type transposed_axes;

    for (unsigned int i = 0; i < N; i++)
    {
        transposed_axes[i] = i;
    }

    std::swap(transposed_axes[0], transposed_axes[axis]);

    vigra::MultiArray<N, T1> src_transposed(src.transpose(transposed_axes));

    vigra::MultiArrayView<N, T1, S1> dest_transposed(dest.transpose(transposed_axes));

    typename vigra::MultiArrayView<N - 1, T1, S1>::difference_type pos;
    pos = 0;

    bool done = false;
    bool carry = true;
    while (!done)
    {
        lineRankOrderFilterND(src_transposed.bindOuter(pos), dest_transposed.bindOuter(pos), half_length, rank);

        carry = true;
        for (unsigned int i = 1; ( carry && (i < N) ); i++)
        {
            if ( (++pos[i]) < src_transposed.shape(i) )
            {
                carry = false;
            }
            else
            {
                pos[i] = 0;
                carry = true;
            }
        }

        done = carry;
    }
}

template<unsigned int N,
        class T1, class S1,
        class T2, class S2>
inline void lineRankOrderFilter(const vigra::MultiArrayView <N, T1, S1> &src,
        vigra::MultiArrayView <N, T2, S2> dest,
        unsigned int half_length, float rank, unsigned int axis = 0)
{
    lineRankOrderFilterND(src, dest, half_length, rank, axis);
}

}

#endif //__RANK_FILTER__
<commit_msg>rank_filter.hxx: Switch to using deque instead of a list.<commit_after>#ifndef __RANK_FILTER__
#define __RANK_FILTER__

#include <deque>
#include <set>
#include <cmath>
#include <cassert>
#include <iostream>
#include <iterator>
#include <type_traits>
#include <utility>

#include <vigra/multi_array.hxx>
#include <vigra/linear_algebra.hxx>

namespace vigra
{

template<unsigned int N,
        class T1, class S1,
        class T2, class S2,
        typename std::enable_if<(N == 1), int>::type = 0>
inline void lineRankOrderFilterND(const vigra::MultiArrayView <N, T1, S1> &src,
        vigra::MultiArrayView <N, T2, S2> dest,
        unsigned int half_length, float rank, unsigned int axis = 0)
{
    // Will ignore boundaries initially.
    // Then will try adding reflection.

    // Rank must be in the range 0 to 1
    assert((0 <= rank) && (rank <= 1));

    const int rank_pos = round(rank * (2 * half_length));

    // The position of the
    typename vigra::MultiArrayView<N, T1, S1>::difference_type_1 window_begin(0);
    std::multiset<T1> sorted_window;
    std::deque< typename std::multiset<T1>::iterator > window_iters;

    // Get the initial sorted window.
    // Include the reflection.
    for (typename vigra::MultiArrayView<N, T1, S1>::difference_type_1 j(half_length); j > 0; j--)
    {
        window_iters.push_back(sorted_window.insert(src[window_begin + j]));
    }
    for (typename vigra::MultiArrayView<N, T1, S1>::difference_type_1 j(0); j <= half_length; j++)
    {
        window_iters.push_back(sorted_window.insert(src[window_begin + j]));
    }

    typename std::multiset<T1>::iterator rank_point = sorted_window.begin();

    for (int i = 0; i < rank_pos; i++)
    {
        rank_point++;
    }

    typename std::multiset<T1>::iterator prev_iter;
    T1 prev_value;
    T1 next_value;
    while ( window_begin < src.size() )
    {
        dest[window_begin] = *rank_point;

        prev_iter = window_iters.front();
        prev_value = *prev_iter;
        window_iters.pop_front();

        window_begin++;

        if ( window_begin < (src.size() - half_length) )
        {
            next_value = src[window_begin + half_length];
        }
        else
        {
            next_value = src[2 * src.size() - (window_begin + half_length + 2)];
        }

        if ( ( *rank_point < prev_value ) && ( *rank_point <= next_value ) )
        {
            sorted_window.erase(prev_iter);
            window_iters.push_back(sorted_window.insert(next_value));
        }
        else if ( ( *rank_point >= prev_value ) && ( *rank_point > next_value ) )
        {
            if ( rank_point == prev_iter )
            {
                window_iters.push_back(sorted_window.insert(next_value));
                rank_point--;

                sorted_window.erase(prev_iter);
            }
            else
            {
                sorted_window.erase(prev_iter);
                window_iters.push_back(sorted_window.insert(next_value));
            }
        }
        else if ( ( *rank_point < prev_value ) && ( *rank_point > next_value ) )
        {
            sorted_window.erase(prev_iter);
            window_iters.push_back(sorted_window.insert(next_value));

            rank_point--;
        }
        else if ( ( *rank_point >= prev_value ) && ( *rank_point <= next_value ) )
        {
            if (rank_point == prev_iter)
            {
                window_iters.push_back(sorted_window.insert(next_value));
                rank_point++;

                sorted_window.erase(prev_iter);
            }
            else
            {
                sorted_window.erase(prev_iter);
                window_iters.push_back(sorted_window.insert(next_value));

                rank_point++;
            }
        }
    }
}

template<unsigned int N,
        class T1, class S1,
        class T2, class S2,
        typename std::enable_if<(N > 1), int>::type = 0>
inline void lineRankOrderFilterND(const vigra::MultiArrayView <N, T1, S1> &src,
        vigra::MultiArrayView <N, T2, S2> dest,
        unsigned int half_length, float rank, unsigned int axis = 0)
{
    typename vigra::MultiArrayView<N, T1, S1>::difference_type transposed_axes;

    for (unsigned int i = 0; i < N; i++)
    {
        transposed_axes[i] = i;
    }

    std::swap(transposed_axes[0], transposed_axes[axis]);

    vigra::MultiArray<N, T1> src_transposed(src.transpose(transposed_axes));

    vigra::MultiArrayView<N, T1, S1> dest_transposed(dest.transpose(transposed_axes));

    typename vigra::MultiArrayView<N - 1, T1, S1>::difference_type pos;
    pos = 0;

    bool done = false;
    bool carry = true;
    while (!done)
    {
        lineRankOrderFilterND(src_transposed.bindOuter(pos), dest_transposed.bindOuter(pos), half_length, rank);

        carry = true;
        for (unsigned int i = 1; ( carry && (i < N) ); i++)
        {
            if ( (++pos[i]) < src_transposed.shape(i) )
            {
                carry = false;
            }
            else
            {
                pos[i] = 0;
                carry = true;
            }
        }

        done = carry;
    }
}

template<unsigned int N,
        class T1, class S1,
        class T2, class S2>
inline void lineRankOrderFilter(const vigra::MultiArrayView <N, T1, S1> &src,
        vigra::MultiArrayView <N, T2, S2> dest,
        unsigned int half_length, float rank, unsigned int axis = 0)
{
    lineRankOrderFilterND(src, dest, half_length, rank, axis);
}

}

#endif //__RANK_FILTER__
<|endoftext|>


<commit_before>#include <cmd_classbook_localization_add_record_handler.h>
#include <QJsonArray>
#include <QSqlError>
#include <log.h>
#include <QUuid>
#include <QCryptographicHash>

CmdClassbookLocalizationAddRecordHandler::CmdClassbookLocalizationAddRecordHandler(){
    m_vInputs.push_back(CmdInputDef("classbookid").required().integer_().description("Classbookid for article localization"));
    m_vInputs.push_back(CmdInputDef("lang").required().string_().description("Language"));
    m_vInputs.push_back(CmdInputDef("name").required().string_().description("Article name"));
    m_vInputs.push_back(CmdInputDef("content").required().string_().description("The content of the article"));
}

QString CmdClassbookLocalizationAddRecordHandler::cmd(){
    return "classbook_localization_add_record";
}

bool CmdClassbookLocalizationAddRecordHandler::accessUnauthorized(){
    return false;
}

bool CmdClassbookLocalizationAddRecordHandler::accessUser(){
    return false;
}

bool CmdClassbookLocalizationAddRecordHandler::accessTester(){
    return false;
}

bool CmdClassbookLocalizationAddRecordHandler::accessAdmin(){
    return true;
}

const QVector<CmdInputDef> &CmdClassbookLocalizationAddRecordHandler::inputs(){
    return m_vInputs;
};

QString CmdClassbookLocalizationAddRecordHandler::description(){
    return "Add a new article localization for the English version";
}

QStringList CmdClassbookLocalizationAddRecordHandler::errors(){
    QStringList	list;
    return list;
}

void CmdClassbookLocalizationAddRecordHandler::handle(QWebSocket *pClient, IWebSocketServer *pWebSocketServer, QString m, QJsonObject obj){

    int classbookid = obj["classbookid"].toInt();

    QSqlDatabase db = *(pWebSocketServer->database());

    QJsonObject data;

    QSqlQuery query(db);
    QString lang = obj["lang"].toString().trimmed();
    query.prepare("SELECT lang FROM classbook_localization WHERE lang = :lang");
    query.bindValue(":lang", obj["lang"].toString().trimmed());
    if(!query.exec()){
        pWebSocketServer->sendMessageError(pClient, cmd(), m, Error(500, query.lastError().text()));
        return;
    }
    if(query.next()){
        pWebSocketServer->sendMessageError(pClient, cmd(), m, Error(403, "This lang already exist"));
        return;
    }

    QString name = obj["name"].toString().trimmed();
    QString content = obj["content"].toString().trimmed();

    //Set md5_content hash
    QString md5_content = QString(QCryptographicHash::hash(content.toUtf8(), QCryptographicHash::Md5).toHex());

    //generate uuid
    QString uuid = QUuid::createUuid().toString().replace("{", "").replace("}", "");

    query.prepare("INSERT INTO classbook_localization("
                  "classbookid,"
                  "uuid,"
                  "lang,"
                  "name,"
                  "content,"
                  "md5_content,"
                  "created,"
                  "updated"
                  ") "
                  "VALUES("
                  ":classbookid,"
                  ":uuid,"
                  ":lang,"
                  ":name,"
                  ":content,"
                  ":md5_content,"
                  "NOW(),"
                  "NOW()"
                  ")");
    query.bindValue(":classbookid", classbookid);
    query.bindValue(":uuid", uuid);
    query.bindValue(":lang", lang);
    query.bindValue(":name", name);
    query.bindValue(":content", content);
    query.bindValue(":md5_content", md5_content);
    if(!query.exec()){
        pWebSocketServer->sendMessageError(pClient, cmd(), m, Error(500, query.lastError().text()));
        return;
    }
    int rowid = query.lastInsertId().toInt();
    data["classbookid"] = classbookid;
    data["classbook_localizationid"] = QJsonValue(rowid);
    data["lang"] = lang;
    data["name"] = name;
    data["content"] = content;
    data["md5_content"] = md5_content;

    QJsonObject jsonData;
    jsonData["cmd"] = QJsonValue(cmd());
    jsonData["m"] = QJsonValue(m);
    jsonData["result"] = QJsonValue("DONE");
    jsonData["data"] = data;
    pWebSocketServer->sendMessage(pClient, jsonData);
}
<commit_msg>Fix add localization<commit_after>#include <cmd_classbook_localization_add_record_handler.h>
#include <QJsonArray>
#include <QSqlError>
#include <log.h>
#include <QUuid>
#include <QCryptographicHash>

CmdClassbookLocalizationAddRecordHandler::CmdClassbookLocalizationAddRecordHandler(){
    m_vInputs.push_back(CmdInputDef("classbookid").required().integer_().description("Classbookid for article localization"));
    m_vInputs.push_back(CmdInputDef("lang").required().string_().description("Language"));
    m_vInputs.push_back(CmdInputDef("name").required().string_().description("Article name"));
    m_vInputs.push_back(CmdInputDef("content").required().string_().description("The content of the article"));
}

QString CmdClassbookLocalizationAddRecordHandler::cmd(){
    return "classbook_localization_add_record";
}

bool CmdClassbookLocalizationAddRecordHandler::accessUnauthorized(){
    return false;
}

bool CmdClassbookLocalizationAddRecordHandler::accessUser(){
    return false;
}

bool CmdClassbookLocalizationAddRecordHandler::accessTester(){
    return false;
}

bool CmdClassbookLocalizationAddRecordHandler::accessAdmin(){
    return true;
}

const QVector<CmdInputDef> &CmdClassbookLocalizationAddRecordHandler::inputs(){
    return m_vInputs;
};

QString CmdClassbookLocalizationAddRecordHandler::description(){
    return "Add a new article localization for the English version";
}

QStringList CmdClassbookLocalizationAddRecordHandler::errors(){
    QStringList	list;
    return list;
}

void CmdClassbookLocalizationAddRecordHandler::handle(QWebSocket *pClient, IWebSocketServer *pWebSocketServer, QString m, QJsonObject obj){

    int classbookid = obj["classbookid"].toInt();

    QSqlDatabase db = *(pWebSocketServer->database());

    QJsonObject data;

    QSqlQuery query(db);
    QString lang = obj["lang"].toString().trimmed();
    query.prepare("SELECT lang FROM classbook_localization WHERE lang = :lang AND classbookid=:classbookid");
    query.bindValue(":lang", obj["lang"].toString().trimmed());
    query.bindValue(":classbookid", classbookid);
    if(!query.exec()){
        pWebSocketServer->sendMessageError(pClient, cmd(), m, Error(500, query.lastError().text()));
        return;
    }
    if(query.next()){
        pWebSocketServer->sendMessageError(pClient, cmd(), m, Error(403, "This lang already exist"));
        return;
    }

    QString name = obj["name"].toString().trimmed();
    QString content = obj["content"].toString().trimmed();

    //Set md5_content hash
    QString md5_content = QString(QCryptographicHash::hash(content.toUtf8(), QCryptographicHash::Md5).toHex());

    //generate uuid
    QString uuid = QUuid::createUuid().toString().replace("{", "").replace("}", "");

    query.prepare("INSERT INTO classbook_localization("
                  "classbookid,"
                  "uuid,"
                  "lang,"
                  "name,"
                  "content,"
                  "md5_content,"
                  "created,"
                  "updated"
                  ") "
                  "VALUES("
                  ":classbookid,"
                  ":uuid,"
                  ":lang,"
                  ":name,"
                  ":content,"
                  ":md5_content,"
                  "NOW(),"
                  "NOW()"
                  ")");
    query.bindValue(":classbookid", classbookid);
    query.bindValue(":uuid", uuid);
    query.bindValue(":lang", lang);
    query.bindValue(":name", name);
    query.bindValue(":content", content);
    query.bindValue(":md5_content", md5_content);
    if(!query.exec()){
        pWebSocketServer->sendMessageError(pClient, cmd(), m, Error(500, query.lastError().text()));
        return;
    }
    int rowid = query.lastInsertId().toInt();
    data["classbookid"] = classbookid;
    data["classbook_localizationid"] = QJsonValue(rowid);
    data["lang"] = lang;
    data["name"] = name;
    data["content"] = content;
    data["md5_content"] = md5_content;

    QJsonObject jsonData;
    jsonData["cmd"] = QJsonValue(cmd());
    jsonData["m"] = QJsonValue(m);
    jsonData["result"] = QJsonValue("DONE");
    jsonData["data"] = data;
    pWebSocketServer->sendMessage(pClient, jsonData);
}
<|endoftext|>


<commit_before>#include "mpi_common.h"
#include <iostream>
#include "phonons.h"
#include "timer.h"
#include "parsephon.h"
#include "memory.h"
#include "error.h"
#include "gruneisen.h"
#include "system.h"
#include "symmetry_core.h"
#include "kpoint.h"
#include "fcs_phonon.h"
#include "dynamical.h"
#include "phonon_velocity.h"
#include "phonon_thermodynamics.h"
#include "write_phonons.h"
#include "phonon_dos.h"
#include "integration.h"
#include "relaxation.h"
#include "conductivity.h"
#include <omp.h>

using namespace PHON_NS;

PHON::PHON(int narg, char **arg, MPI_Comm comm)
{
    mympi = new MyMPI(this, comm);
	input = new Input(this);

	restart_flag = false;

    create_pointers();

    if (mympi->my_rank == 0) {
		std::cout << "Phonons program version 1.0 (MPI)" << std::endl;
        std::cout << std::endl << "Job started at " << timer->DataAndTime() <<  std::endl << std::endl;

		std::cout << "The number of MPI threads: " << mympi->nprocs << std::endl;
		std::cout << "The number of OpenMP threads: " << omp_get_num_threads() << std::endl;
		std::cout << std::endl;

	    input->parce_input(narg, arg);
    }

    mympi->MPI_Bcast_string(input->job_title, 0, MPI_COMM_WORLD);
    mympi->MPI_Bcast_string(mode, 0, MPI_COMM_WORLD);

    if (mode == "phonons") {

        system->setup();
        symmetry->setup_symmetry();
        kpoint->kpoint_setups();

        fcs_phonon->setup(mode);
        dynamical->setup_dynamical(mode);
        dos->setup();

        dynamical->diagonalize_dynamical_all();

        // Calculate the group velocity of phonons along given direction in
        // the reciprocal space.

        if (kpoint->kpoint_mode == 1)  {
            phonon_velocity->calc_phonon_vel_band();
        }

        if (dos->flag_dos) {
            integration->setup_integration();
            dos->calc_dos();
        }

        if (mympi->my_rank == 0) {
            writes->write_phonon_info();
        }

        memory->deallocate(dynamical->evec_phonon);
        memory->deallocate(dynamical->eval_phonon);

        if (kpoint->kpoint_mode == 1) {
            memory->deallocate(phonon_velocity->phvel);
        }

        if (dos->flag_dos) {
            integration->finish_integration();
        }

    } else if (mode == "boltzmann") {

        system->setup();
        symmetry->setup_symmetry();
        kpoint->kpoint_setups();
		dos->setup();
        fcs_phonon->setup(mode);
        dynamical->setup_dynamical(mode);
        dynamical->diagonalize_dynamical_all();

        integration->setup_integration();
		relaxation->setup_relaxation();

        //     dos->calc_tdos();

       // relaxation->calc_selfenergy();

	//	relaxation->v3_test();

        conductivity->setup_kl();
        conductivity->calc_kl();

        integration->finish_integration();
        relaxation->finish_relaxation();
        conductivity->finish_kl();

    } else if (mode == "gruneisen") {
        system->setup();

        kpoint->kpoint_setups();
		dos->setup();
        fcs_phonon->setup(mode);
        dynamical->setup_dynamical(mode);
        dynamical->diagonalize_dynamical_all();
        gruneisen->setup();
        gruneisen->calc_gruneisen();
     //   gruneisen->calc_gruneisen2();
        writes->write_gruneisen();
        gruneisen->finish_gruneisen();

    } else {
        error->exit("phonons", "invalid mode");
    }

    if (mympi->my_rank == 0) {
        std::cout << std::endl << "Job finished at " << timer->DataAndTime() << std::endl;
	    std::cout << "Bye! :)" << std::endl;
    }
	   destroy_pointers();
}

PHON::~PHON(){
    delete input;
	delete mympi;
}

void PHON::create_pointers()
{
    memory = new Memory(this);
    timer = new Timer(this);
    error = new Error(this);
    system = new System(this);
    symmetry = new Symmetry(this);
    kpoint = new Kpoint(this);
    fcs_phonon = new Fcs_phonon(this);
    dynamical = new Dynamical(this);
    integration = new Integration(this);
    phonon_velocity = new Phonon_velocity(this);
    phonon_thermodynamics = new Phonon_thermodynamics(this);
    relaxation = new Relaxation(this);
    conductivity = new Conductivity(this);
    writes = new Writes(this);
    dos = new Dos(this);
    gruneisen = new Gruneisen(this);
}

void PHON::destroy_pointers()
{
    delete memory;
    delete timer;
    delete error;
    delete system;
    delete symmetry;
    delete kpoint;
    delete fcs_phonon;
    delete dynamical;
    delete integration;
    delete phonon_velocity;
    delete phonon_thermodynamics;
    delete relaxation;
    delete conductivity;
    delete writes;
    delete dos;
    delete gruneisen;
}
<commit_msg>Formatted.<commit_after>#include "mpi_common.h"
#include <iostream>
#include "phonons.h"
#include "timer.h"
#include "parsephon.h"
#include "memory.h"
#include "error.h"
#include "gruneisen.h"
#include "system.h"
#include "symmetry_core.h"
#include "kpoint.h"
#include "fcs_phonon.h"
#include "dynamical.h"
#include "phonon_velocity.h"
#include "phonon_thermodynamics.h"
#include "write_phonons.h"
#include "phonon_dos.h"
#include "integration.h"
#include "relaxation.h"
#include "conductivity.h"
#include <omp.h>

using namespace PHON_NS;

PHON::PHON(int narg, char **arg, MPI_Comm comm)
{
	mympi = new MyMPI(this, comm);
	input = new Input(this);

	restart_flag = false;

	create_pointers();

	if (mympi->my_rank == 0) {
		std::cout << "Phonons program version 1.0 (MPI)" << std::endl;
		std::cout << std::endl << "Job started at " << timer->DataAndTime() <<  std::endl << std::endl;

		std::cout << "The number of MPI threads: " << mympi->nprocs << std::endl;
		std::cout << "The number of OpenMP threads: " << omp_get_num_threads() << std::endl;
		std::cout << std::endl;

		input->parce_input(narg, arg);
	}

	mympi->MPI_Bcast_string(input->job_title, 0, MPI_COMM_WORLD);
	mympi->MPI_Bcast_string(mode, 0, MPI_COMM_WORLD);

	if (mode == "phonons") {

		system->setup();
		symmetry->setup_symmetry();
		kpoint->kpoint_setups();

		fcs_phonon->setup(mode);
		dynamical->setup_dynamical(mode);
		dos->setup();

		dynamical->diagonalize_dynamical_all();

		// Calculate the group velocity of phonons along given direction in
		// the reciprocal space.

		if (kpoint->kpoint_mode == 1)  {
			phonon_velocity->calc_phonon_vel_band();
		}

		if (dos->flag_dos) {
			integration->setup_integration();
			dos->calc_dos();
		}

		if (mympi->my_rank == 0) {
			writes->write_phonon_info();
		}

		memory->deallocate(dynamical->evec_phonon);
		memory->deallocate(dynamical->eval_phonon);

		if (kpoint->kpoint_mode == 1) {
			memory->deallocate(phonon_velocity->phvel);
		}

		if (dos->flag_dos) {
			integration->finish_integration();
		}

	} else if (mode == "boltzmann") {

		system->setup();
		symmetry->setup_symmetry();
		kpoint->kpoint_setups();
		dos->setup();
		fcs_phonon->setup(mode);
		dynamical->setup_dynamical(mode);
		dynamical->diagonalize_dynamical_all();

		integration->setup_integration();
		relaxation->setup_relaxation();

		//     dos->calc_tdos();

		// relaxation->calc_selfenergy();

		//	relaxation->v3_test();

		conductivity->setup_kl();
		conductivity->calc_kl();

		integration->finish_integration();
		relaxation->finish_relaxation();
		conductivity->finish_kl();

	} else if (mode == "gruneisen") {
		system->setup();

		kpoint->kpoint_setups();
		dos->setup();
		fcs_phonon->setup(mode);
		dynamical->setup_dynamical(mode);
		dynamical->diagonalize_dynamical_all();
		gruneisen->setup();
		gruneisen->calc_gruneisen();
		//   gruneisen->calc_gruneisen2();
		writes->write_gruneisen();
		gruneisen->finish_gruneisen();

	} else {
		error->exit("phonons", "invalid mode");
	}

	if (mympi->my_rank == 0) {
		std::cout << std::endl << "Job finished at " << timer->DataAndTime() << std::endl;
		std::cout << "Bye! :)" << std::endl;
	}
	destroy_pointers();
}

PHON::~PHON(){
	delete input;
	delete mympi;
}

void PHON::create_pointers()
{
	memory = new Memory(this);
	timer = new Timer(this);
	error = new Error(this);
	system = new System(this);
	symmetry = new Symmetry(this);
	kpoint = new Kpoint(this);
	fcs_phonon = new Fcs_phonon(this);
	dynamical = new Dynamical(this);
	integration = new Integration(this);
	phonon_velocity = new Phonon_velocity(this);
	phonon_thermodynamics = new Phonon_thermodynamics(this);
	relaxation = new Relaxation(this);
	conductivity = new Conductivity(this);
	writes = new Writes(this);
	dos = new Dos(this);
	gruneisen = new Gruneisen(this);
}

void PHON::destroy_pointers()
{
	delete memory;
	delete timer;
	delete error;
	delete system;
	delete symmetry;
	delete kpoint;
	delete fcs_phonon;
	delete dynamical;
	delete integration;
	delete phonon_velocity;
	delete phonon_thermodynamics;
	delete relaxation;
	delete conductivity;
	delete writes;
	delete dos;
	delete gruneisen;
}
<|endoftext|>


<commit_before>#include <iostream>
#include <settings_class.h>
#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/xml_parser.hpp>

void Settings_Profile::test_function(int a){
	std::cout << a;
	return;
}

Settings_Profile::Settings_Profile(){
}

Settings_Profile::Settings_Profile(std::string filename){
	try{
		boost::property_tree::ptree data;
		boost::property_tree::xml_parser::read_xml(filename, data);
		std::string inputs = data.get<std::string>("db.profile.img_name");
		this->addImgName(inputs);
		inputs = data.get<std::string>("db.profile.config_name");
		this->setConfigName(inputs);
		inputs = data.get<std::string>("db.profile.base_dir");
		this->setBaseDir(inputs);
		float coord = data.get<float>("db.profile.x");
		this->addX(coord);
		coord = data.get<float>("db.profile.y");
		this->addY(coord);
		this->default_res_x = data.get<int>("db.profile.default_res_x");
		this->default_res_y = data.get<int>("db.profile.default_res_y");
	}catch(const std::exception &e){
		std::cerr << e.what();
		exit(1);
	}
}
/*
void Settings_Profile::printableContents(std::string* file_contents){
	file_contents->clear();
	return;

}
*/

int Settings_Profile::writeToFile(){
	std::string content = this->img_names.at(0);
	std::cout << content;
	return 1;
}

void Settings_Profile::setConfigName(std::string name){
	this->config_name = name;
	return;
}
void Settings_Profile::setBaseDir(std::string name){
	this->base_dir = name;
	return;
}
void Settings_Profile::addImgName(std::string name){
	this->img_names.push_back(name);
	return;
}
void Settings_Profile::addX(float x){
	this->x.push_back(x);
	return;
}
void Settings_Profile::addY(float y){
	this->y.push_back(y);
	return;
}

void Settings_Profile::printInfo(){
	std::cout << "Config Name: " << this->config_name << "\nBase Dir: " << this->base_dir << "\nImage Names: " << img_names.at(0) << "\nX: " << this->x.at(0) << "\nY: " << this->y.at(0) << "\n";
}
std::string Settings_Profile::getImgName(int a){
	return this->img_names.at(a);
}
std::string Settings_Profile::getConfigName(){
	return this->config_name;
}
std::string Settings_Profile::getBaseDir(){
	return this->base_dir;
}
float Settings_Profile::getX(int a){
	return this->x.at(a);
}
float Settings_Profile::getY(int a){
	return this->y.at(a);
}
std::string Settings_Profile::getProcessName(){
	return this->process_name;
}
void Settings_Profile::setProcessName(std::string name){
	this->process_name = name;
}
int Settings_Profile::getImgCount(){
	return this->img_names.size();
}

void Settings_Profile::setDefaultRes(int x, int y){
	this->default_res_x = x;
	this->default_res_y = y;
}

int Settings_Profile::getDresY(){
	return this->default_res_y;
}

int Settings_Profile::getDResX(){
	return this->default_res_x;
}<commit_msg>removed ptree loading for simple line loading using ifstreams<commit_after>#include "settings_class.h"

Settings_Profile::Settings_Profile(){
}
/**
 * Takes a filename as a string. Opens file, and streams in the following format:
 * Set config name
 * Process Title
 * base directory - assumed ./ or current directory
 * button's image name
 * Default X resolution
 * Default Y resolution
 * Offset x of button - button's distance from top left corner of window
 * Offset y of button - button's distance from top left corner of window
 * threshold for image

 *
 *
 */
Settings_Profile::Settings_Profile(std::string filename = "lol.txt"){
	char* line;

	try{
		//parse file into settings profile
		std::ifstream input_file(filename);
		int resx, resy;
		float threshold;
		// Do parsing here
		line = (char*) calloc(256, sizeof(char));

		// Start populating object.
		// Implement easier way but using function pointer array and while loop
		input_file.getline(line, 256);
		this->setConfigName(line);
		memset(line, 0, 256);

		input_file.getline(line, 256);
		this->setProcessName(line);
		memset(line, 0, 256);

		input_file.getline(line,256);
		this->setBaseDir(line);

		input_file.getline(line, 256);
		this->addImgName(line);
		memset(line, 0, 256);

		input_file >> resx;
		input_file >> resy;
		this->setDefaultRes(resx, resy);

		input_file >> resx;
		input_file >> resy;
		this->addX(resx);
		this->addY(resy);

		input_file >> threshold;
		this->addThreshold(threshold);

		input_file.close();
	}catch(const std::exception &e){
		std::cerr << e.what();
		free(line); // necessary?
	}
	free(line);
}
/*
void Settings_Profile::printableContents(std::string* file_contents){
	file_contents->clear();
	return;

}
*/

int Settings_Profile::writeToFile(){
	std::string content = this->img_names.at(0);
	std::cout << content;
	return 1;
}

void Settings_Profile::setConfigName(std::string name){
	this->config_name = name;
	return;
}
void Settings_Profile::setBaseDir(std::string name){
	this->base_dir = name;
	return;
}
void Settings_Profile::addImgName(std::string name){
	this->img_names.push_back(name);
	return;
}
void Settings_Profile::addX(float x){
	this->x.push_back(x);
	return;
}
void Settings_Profile::addY(float y){
	this->y.push_back(y);
	return;
}

void Settings_Profile::printInfo(){
	std::cout << "Config Name: " << this->config_name << "\nExecutable: " << this->process_name << "\nBase Dir: ";
	std::cout << this->base_dir << "\nImage Names: " << img_names.at(0);
	std::cout << "\nX: " << this->x.at(0) << "\nY: " << this->y.at(0) << "\n";
}
std::string Settings_Profile::getImgName(int a){
	return this->img_names.at(a);
}
std::string Settings_Profile::getConfigName(){
	return this->config_name;
}
std::string Settings_Profile::getBaseDir(){
	return this->base_dir;
}
float Settings_Profile::getX(int a){
	return this->x.at(a);
}
float Settings_Profile::getY(int a){
	return this->y.at(a);
}
std::string Settings_Profile::getProcessName(){
	return this->process_name;
}
void Settings_Profile::setProcessName(std::string name){
	this->process_name = name;
}
int Settings_Profile::getImgCount(){
	return this->img_names.size();
}

void Settings_Profile::setDefaultRes(int x, int y){
	this->default_res_x = x;
	this->default_res_y = y;
}

int Settings_Profile::getDresY(){
	return this->default_res_y;
}

int Settings_Profile::getDResX(){
	return this->default_res_x;
}

void Settings_Profile::addThreshold(float threshold){
	this->threshold.push_back(threshold);
}

float Settings_Profile::getThresholdAt(int a){
	return this->threshold.at(a);
}<|endoftext|>


<commit_before>#include <opencv2/highgui/highgui.hpp>
#include <opencv2/opencv.hpp>
#include <iostream>
#include <string>
using namespace std;

int main()
{
  while(1)
  {
    string path;
    getline(cin, path);
    cv::Mat input = cv::imread(path+".jpg");
    cv::Mat hsv_filtered15;//画像の初期化
    cv::Mat hsv_filtered180;//画像の初期化
    cv::Mat hsv;
    cv::Mat output;
    cv::cvtColor(input,hsv,CV_BGR2HSV);//入力画像(src)をhsv色空間(dst)に変換
    //inRange(入力画像,下界画像,上界画像,出力画像)
    //「HSV」は、色を色相(Hue)・彩度(Saturation)・明度(Value)
    cv::inRange(hsv,cv::Scalar(0,120,97),cv::Scalar(13,255,255),hsv_filtered15);
    cv::inRange(hsv,cv::Scalar(175,120,97),cv::Scalar(180,255,255),hsv_filtered180);
    cv::add(hsv_filtered15,hsv_filtered180,output);
    cv::imwrite(path+"BINARY"+".jpg",output);
  }
return 0;
}
<commit_msg>dbeug<commit_after>#include <opencv2/highgui/highgui.hpp>
#include <opencv2/opencv.hpp>
#include <iostream>
#include <string>
using namespace std;

int main()
{
  while(1)
  {
    string path;
    getline(cin, path);
    cv::Mat input = cv::imread(path+".jpg");
    cv::Mat hsv_filtered15;//画像の初期化
    cv::Mat hsv_filtered180;//画像の初期化
    cv::Mat hsv;
    cv::Mat output;
    cv::cvtColor(input,hsv,CV_BGR2HSV);//入力画像(src)をhsv色空間(dst)に変換
    //inRange(入力画像,下界画像,上界画像,出力画像)
    //「HSV」は、色を色相(Hue)・彩度(Saturation)・明度(Value)
    cv::inRange(hsv,cv::Scalar(0,89,97),cv::Scalar(13,255,255),hsv_filtered15);
    cv::inRange(hsv,cv::Scalar(175,89,97),cv::Scalar(180,255,255),hsv_filtered180);
    cv::add(hsv_filtered15,hsv_filtered180,output);
    cv::imwrite(path+"BINARY"+".jpg",output);
  }
return 0;
}
<|endoftext|>