<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2000, 2010 Oracle and/or its affiliates.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org 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 version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

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

#include <svunx.h>
#include <tools/prex.h>
#include <X11/Xatom.h>
#include <tools/postx.h>

#include "vcl/dllapi.h"

#include "rtl/ustrbuf.hxx"
#include "osl/module.h"
#include "osl/process.h"
#include "osl/thread.h"

#include <unistd.h>

using namespace rtl;

enum {
    DESKTOP_NONE = 0,
    DESKTOP_UNKNOWN,
    DESKTOP_GNOME,
    DESKTOP_KDE,
    DESKTOP_KDE4,
    DESKTOP_CDE
};

static const char * desktop_strings[] = { "none", "unknown", "GNOME", "KDE", "KDE4", "CDE" };

static bool is_gnome_desktop( Display* pDisplay )
{
    bool ret = false;

    // warning: these checks are coincidental, GNOME does not
    // explicitly advertise itself

    if ( NULL != getenv( "GNOME_DESKTOP_SESSION_ID" ) )
        ret = true;

    if( ! ret )
    {
        Atom nAtom1 = XInternAtom( pDisplay, "GNOME_SM_PROXY", True );
        Atom nAtom2 = XInternAtom( pDisplay, "NAUTILUS_DESKTOP_WINDOW_ID", True );
        if( nAtom1 || nAtom2 )
        {
            int nProperties = 0;
            Atom* pProperties = XListProperties( pDisplay, DefaultRootWindow( pDisplay ), &nProperties );
            if( pProperties && nProperties )
            {
                for( int i = 0; i < nProperties; i++ )
                    if( pProperties[ i ] == nAtom1 ||
                        pProperties[ i ] == nAtom2 )
                {
                    ret = true;
                }
                XFree( pProperties );
            }
        }
    }

    if( ! ret )
    {
        Atom nUTFAtom       = XInternAtom( pDisplay, "UTF8_STRING", True );
        Atom nNetWMNameAtom = XInternAtom( pDisplay, "_NET_WM_NAME", True );
        if( nUTFAtom && nNetWMNameAtom )
        {
            // another, more expensive check: search for a gnome-panel
            XLIB_Window aRoot, aParent, *pChildren = NULL;
            unsigned int nChildren = 0;
            XQueryTree( pDisplay, DefaultRootWindow( pDisplay ),
                        &aRoot, &aParent, &pChildren, &nChildren );
            if( pChildren && nChildren )
            {
                for( unsigned int i = 0; i < nChildren && ! ret; i++ )
                {
                    Atom nType = None;
                    int nFormat = 0;
                    unsigned long nItems = 0, nBytes = 0;
                    unsigned char* pProp = NULL;
                    XGetWindowProperty( pDisplay,
                                        pChildren[i],
                                        nNetWMNameAtom,
                                        0, 8,
                                        False,
                                        nUTFAtom,
                                        &nType,
                                        &nFormat,
                                        &nItems,
                                        &nBytes,
                                        &pProp );
                    if( pProp && nType == nUTFAtom )
                    {
                        OString aWMName( (sal_Char*)pProp );
                        if( aWMName.equalsIgnoreAsciiCase( "gnome-panel" ) )
                            ret = true;
                    }
                    if( pProp )
                        XFree( pProp );
                }
                XFree( pChildren );
            }
        }
    }

    return ret;
}

static bool bWasXError = false;

static inline bool WasXError()
{
    bool bRet = bWasXError;
    bWasXError = false;
    return bRet;
}

extern "C"
{
    static int autodect_error_handler( Display*, XErrorEvent* )
    {
        bWasXError = true;
        return 0;
    }

    typedef int(* XErrorHandler)(Display*,XErrorEvent*);
}

static int KDEVersion( Display* pDisplay )
{
    int nRet = 0;

    Atom nFullSession = XInternAtom( pDisplay, "KDE_FULL_SESSION", True );
    Atom nKDEVersion  = XInternAtom( pDisplay, "KDE_SESSION_VERSION", True );

    if( nFullSession )
    {
        if( !nKDEVersion )
            return 3;

        Atom                aRealType   = None;
        int                 nFormat     = 8;
        unsigned long       nItems      = 0;
        unsigned long       nBytesLeft  = 0;
        unsigned char*  pProperty   = NULL;
        XGetWindowProperty( pDisplay,
                            DefaultRootWindow( pDisplay ),
                            nKDEVersion,
                            0, 1,
                            False,
                            AnyPropertyType,
                            &aRealType,
                            &nFormat,
                            &nItems,
                            &nBytesLeft,
                            &pProperty );
        if( !WasXError() && nItems != 0 && pProperty )
        {
            nRet = *reinterpret_cast< sal_Int32* >( pProperty );
        }
        if( pProperty )
        {
            XFree( pProperty );
            pProperty = NULL;
        }
    }
    return nRet;
}

static bool is_kde_desktop( Display* pDisplay )
{
    if ( NULL != getenv( "KDE_FULL_SESSION" ) )
    {
        const char *pVer = getenv( "KDE_SESSION_VERSION" );
        if ( !pVer || pVer[0] == '0' )
        {
            return true; // does not exist => KDE3
        }

        rtl::OUString aVer( RTL_CONSTASCII_USTRINGPARAM( "3" ) );
        if ( aVer.equalsIgnoreAsciiCaseAscii( pVer ) )
        {
            return true;
        }
    }

    if ( KDEVersion( pDisplay ) == 3 )
        return true;

    return false;
}

static bool is_kde4_desktop( Display* pDisplay )
{
    if ( NULL != getenv( "KDE_FULL_SESSION" ) )
    {
        rtl::OUString aVer( RTL_CONSTASCII_USTRINGPARAM( "4" ) );

        const char *pVer = getenv( "KDE_SESSION_VERSION" );
        if ( pVer && aVer.equalsIgnoreAsciiCaseAscii( pVer ) )
            return true;
    }

    if ( KDEVersion( pDisplay ) == 4 )
        return true;

    return false;
}

static bool is_cde_desktop( Display* pDisplay )
{
    void* pLibrary = NULL;

    Atom nDtAtom = XInternAtom( pDisplay, "_DT_WM_READY", True );
    OUString aPathName( RTL_CONSTASCII_USTRINGPARAM( "file:///usr/dt/lib/libDtSvc.so" ) );
    if( nDtAtom && ( pLibrary = osl_loadModule( aPathName.pData, SAL_LOADMODULE_DEFAULT ) ) )
    {
        osl_unloadModule( (oslModule)pLibrary );
        return true;
    }

    return false;
}

extern "C"
{

VCL_DLLPUBLIC rtl::OUString get_desktop_environment()
{
    rtl::OUStringBuffer aRet( 8 );
    static const char *pOverride = getenv( "OOO_FORCE_DESKTOP" );

    if ( pOverride && *pOverride )
    {
        OString aOver( pOverride );

        if ( aOver.equalsIgnoreAsciiCase( "cde" ) )
            aRet.appendAscii( desktop_strings[DESKTOP_CDE] );
        if ( aOver.equalsIgnoreAsciiCase( "kde4" ) )
            aRet.appendAscii( desktop_strings[DESKTOP_KDE4] );
        if ( aOver.equalsIgnoreAsciiCase( "gnome" ) )
            aRet.appendAscii( desktop_strings[DESKTOP_GNOME] );
        if ( aOver.equalsIgnoreAsciiCase( "kde" ) )
            aRet.appendAscii( desktop_strings[DESKTOP_KDE] );
        if ( aOver.equalsIgnoreAsciiCase( "none" ) )
            aRet.appendAscii( desktop_strings[DESKTOP_UNKNOWN] );
    }

    if( aRet.getLength() == 0 )
    {
        // get display to connect to
        const char* pDisplayStr = getenv( "DISPLAY" );
        int nParams = osl_getCommandArgCount();
        OUString aParam;
        OString aBParm;
        for( int i = 0; i < nParams; i++ )
        {
            osl_getCommandArg( i, &aParam.pData );
            if( aParam.equalsAscii( "-headless" ) )
            {
                pDisplayStr = NULL;
                break;
            }
            if( i < nParams-1 && (aParam.equalsAscii( "-display" ) || aParam.equalsAscii( "--display" )) )
            {
                osl_getCommandArg( i+1, &aParam.pData );
                aBParm = OUStringToOString( aParam, osl_getThreadTextEncoding() );
                pDisplayStr = aBParm.getStr();
                break;
            }
        }

        // no server at all
        if( ! pDisplayStr || !*pDisplayStr )
            aRet.appendAscii( desktop_strings[DESKTOP_NONE] );
        else
        {
            /* #i92121# workaround deadlocks in the X11 implementation
            */
            static const char* pNoXInitThreads = getenv( "SAL_NO_XINITTHREADS" );
            /* #i90094#
               from now on we know that an X connection will be
               established, so protect X against itself
            */
            if( ! ( pNoXInitThreads && *pNoXInitThreads ) )
                XInitThreads();

            Display* pDisplay = XOpenDisplay( pDisplayStr );
            if( pDisplay )
            {
                XErrorHandler pOldHdl = XSetErrorHandler( autodect_error_handler );

                if ( is_kde4_desktop( pDisplay ) )
                    aRet.appendAscii( desktop_strings[DESKTOP_KDE4] );
                else if ( is_gnome_desktop( pDisplay ) )
                    aRet.appendAscii( desktop_strings[DESKTOP_GNOME] );
                else if ( is_cde_desktop( pDisplay ) )
                    aRet.appendAscii( desktop_strings[DESKTOP_CDE] );
                else if ( is_kde_desktop( pDisplay ) )
                    aRet.appendAscii( desktop_strings[DESKTOP_KDE] );
                else
                    aRet.appendAscii( desktop_strings[DESKTOP_UNKNOWN] );

                // set the default handler again
                XSetErrorHandler( pOldHdl );

                XCloseDisplay( pDisplay );
            }
        }
    }

    return aRet.makeStringAndClear();
}

}

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<commit_msg>check for env variable of headless plugin in desktop detect<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2000, 2010 Oracle and/or its affiliates.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org 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 version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

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

#include <svunx.h>
#include <tools/prex.h>
#include <X11/Xatom.h>
#include <tools/postx.h>

#include "vcl/dllapi.h"

#include "rtl/ustrbuf.hxx"
#include "osl/module.h"
#include "osl/process.h"
#include "osl/thread.h"

#include <unistd.h>
#include <string.h>

using namespace rtl;

enum {
    DESKTOP_NONE = 0,
    DESKTOP_UNKNOWN,
    DESKTOP_GNOME,
    DESKTOP_KDE,
    DESKTOP_KDE4,
    DESKTOP_CDE
};

static const char * desktop_strings[] = { "none", "unknown", "GNOME", "KDE", "KDE4", "CDE" };

static bool is_gnome_desktop( Display* pDisplay )
{
    bool ret = false;

    // warning: these checks are coincidental, GNOME does not
    // explicitly advertise itself

    if ( NULL != getenv( "GNOME_DESKTOP_SESSION_ID" ) )
        ret = true;

    if( ! ret )
    {
        Atom nAtom1 = XInternAtom( pDisplay, "GNOME_SM_PROXY", True );
        Atom nAtom2 = XInternAtom( pDisplay, "NAUTILUS_DESKTOP_WINDOW_ID", True );
        if( nAtom1 || nAtom2 )
        {
            int nProperties = 0;
            Atom* pProperties = XListProperties( pDisplay, DefaultRootWindow( pDisplay ), &nProperties );
            if( pProperties && nProperties )
            {
                for( int i = 0; i < nProperties; i++ )
                    if( pProperties[ i ] == nAtom1 ||
                        pProperties[ i ] == nAtom2 )
                {
                    ret = true;
                }
                XFree( pProperties );
            }
        }
    }

    if( ! ret )
    {
        Atom nUTFAtom       = XInternAtom( pDisplay, "UTF8_STRING", True );
        Atom nNetWMNameAtom = XInternAtom( pDisplay, "_NET_WM_NAME", True );
        if( nUTFAtom && nNetWMNameAtom )
        {
            // another, more expensive check: search for a gnome-panel
            XLIB_Window aRoot, aParent, *pChildren = NULL;
            unsigned int nChildren = 0;
            XQueryTree( pDisplay, DefaultRootWindow( pDisplay ),
                        &aRoot, &aParent, &pChildren, &nChildren );
            if( pChildren && nChildren )
            {
                for( unsigned int i = 0; i < nChildren && ! ret; i++ )
                {
                    Atom nType = None;
                    int nFormat = 0;
                    unsigned long nItems = 0, nBytes = 0;
                    unsigned char* pProp = NULL;
                    XGetWindowProperty( pDisplay,
                                        pChildren[i],
                                        nNetWMNameAtom,
                                        0, 8,
                                        False,
                                        nUTFAtom,
                                        &nType,
                                        &nFormat,
                                        &nItems,
                                        &nBytes,
                                        &pProp );
                    if( pProp && nType == nUTFAtom )
                    {
                        OString aWMName( (sal_Char*)pProp );
                        if( aWMName.equalsIgnoreAsciiCase( "gnome-panel" ) )
                            ret = true;
                    }
                    if( pProp )
                        XFree( pProp );
                }
                XFree( pChildren );
            }
        }
    }

    return ret;
}

static bool bWasXError = false;

static inline bool WasXError()
{
    bool bRet = bWasXError;
    bWasXError = false;
    return bRet;
}

extern "C"
{
    static int autodect_error_handler( Display*, XErrorEvent* )
    {
        bWasXError = true;
        return 0;
    }

    typedef int(* XErrorHandler)(Display*,XErrorEvent*);
}

static int KDEVersion( Display* pDisplay )
{
    int nRet = 0;

    Atom nFullSession = XInternAtom( pDisplay, "KDE_FULL_SESSION", True );
    Atom nKDEVersion  = XInternAtom( pDisplay, "KDE_SESSION_VERSION", True );

    if( nFullSession )
    {
        if( !nKDEVersion )
            return 3;

        Atom                aRealType   = None;
        int                 nFormat     = 8;
        unsigned long       nItems      = 0;
        unsigned long       nBytesLeft  = 0;
        unsigned char*  pProperty   = NULL;
        XGetWindowProperty( pDisplay,
                            DefaultRootWindow( pDisplay ),
                            nKDEVersion,
                            0, 1,
                            False,
                            AnyPropertyType,
                            &aRealType,
                            &nFormat,
                            &nItems,
                            &nBytesLeft,
                            &pProperty );
        if( !WasXError() && nItems != 0 && pProperty )
        {
            nRet = *reinterpret_cast< sal_Int32* >( pProperty );
        }
        if( pProperty )
        {
            XFree( pProperty );
            pProperty = NULL;
        }
    }
    return nRet;
}

static bool is_kde_desktop( Display* pDisplay )
{
    if ( NULL != getenv( "KDE_FULL_SESSION" ) )
    {
        const char *pVer = getenv( "KDE_SESSION_VERSION" );
        if ( !pVer || pVer[0] == '0' )
        {
            return true; // does not exist => KDE3
        }

        rtl::OUString aVer( RTL_CONSTASCII_USTRINGPARAM( "3" ) );
        if ( aVer.equalsIgnoreAsciiCaseAscii( pVer ) )
        {
            return true;
        }
    }

    if ( KDEVersion( pDisplay ) == 3 )
        return true;

    return false;
}

static bool is_kde4_desktop( Display* pDisplay )
{
    if ( NULL != getenv( "KDE_FULL_SESSION" ) )
    {
        rtl::OUString aVer( RTL_CONSTASCII_USTRINGPARAM( "4" ) );

        const char *pVer = getenv( "KDE_SESSION_VERSION" );
        if ( pVer && aVer.equalsIgnoreAsciiCaseAscii( pVer ) )
            return true;
    }

    if ( KDEVersion( pDisplay ) == 4 )
        return true;

    return false;
}

static bool is_cde_desktop( Display* pDisplay )
{
    void* pLibrary = NULL;

    Atom nDtAtom = XInternAtom( pDisplay, "_DT_WM_READY", True );
    OUString aPathName( RTL_CONSTASCII_USTRINGPARAM( "file:///usr/dt/lib/libDtSvc.so" ) );
    if( nDtAtom && ( pLibrary = osl_loadModule( aPathName.pData, SAL_LOADMODULE_DEFAULT ) ) )
    {
        osl_unloadModule( (oslModule)pLibrary );
        return true;
    }

    return false;
}

extern "C"
{

VCL_DLLPUBLIC rtl::OUString get_desktop_environment()
{
    rtl::OUStringBuffer aRet( 8 );
    static const char *pOverride = getenv( "OOO_FORCE_DESKTOP" );

    if ( pOverride && *pOverride )
    {
        OString aOver( pOverride );

        if ( aOver.equalsIgnoreAsciiCase( "cde" ) )
            aRet.appendAscii( desktop_strings[DESKTOP_CDE] );
        if ( aOver.equalsIgnoreAsciiCase( "kde4" ) )
            aRet.appendAscii( desktop_strings[DESKTOP_KDE4] );
        if ( aOver.equalsIgnoreAsciiCase( "gnome" ) )
            aRet.appendAscii( desktop_strings[DESKTOP_GNOME] );
        if ( aOver.equalsIgnoreAsciiCase( "kde" ) )
            aRet.appendAscii( desktop_strings[DESKTOP_KDE] );
        if ( aOver.equalsIgnoreAsciiCase( "none" ) )
            aRet.appendAscii( desktop_strings[DESKTOP_UNKNOWN] );
    }

    if( aRet.getLength() == 0 )
    {
        // get display to connect to
        const char* pDisplayStr = getenv( "DISPLAY" );

        const char* pUsePlugin = getenv( "SAL_USE_VCLPLUGIN" );

        if (pUsePlugin && (strcmp(pUsePlugin, "svp") == 0))
            pDisplayStr = NULL;
        else
        {
            int nParams = osl_getCommandArgCount();
            OUString aParam;
            OString aBParm;
            for( int i = 0; i < nParams; i++ )
            {
                osl_getCommandArg( i, &aParam.pData );
                if( aParam.equalsAscii( "-headless" ) )
                {
                    pDisplayStr = NULL;
                    break;
                }
                if( i < nParams-1 && (aParam.equalsAscii( "-display" ) || aParam.equalsAscii( "--display" )) )
                {
                    osl_getCommandArg( i+1, &aParam.pData );
                    aBParm = OUStringToOString( aParam, osl_getThreadTextEncoding() );
                    pDisplayStr = aBParm.getStr();
                    break;
                }
            }
        }

        // no server at all
        if( ! pDisplayStr || !*pDisplayStr )
            aRet.appendAscii( desktop_strings[DESKTOP_NONE] );
        else
        {
            /* #i92121# workaround deadlocks in the X11 implementation
            */
            static const char* pNoXInitThreads = getenv( "SAL_NO_XINITTHREADS" );
            /* #i90094#
               from now on we know that an X connection will be
               established, so protect X against itself
            */
            if( ! ( pNoXInitThreads && *pNoXInitThreads ) )
                XInitThreads();

            Display* pDisplay = XOpenDisplay( pDisplayStr );
            if( pDisplay )
            {
                XErrorHandler pOldHdl = XSetErrorHandler( autodect_error_handler );

                if ( is_kde4_desktop( pDisplay ) )
                    aRet.appendAscii( desktop_strings[DESKTOP_KDE4] );
                else if ( is_gnome_desktop( pDisplay ) )
                    aRet.appendAscii( desktop_strings[DESKTOP_GNOME] );
                else if ( is_cde_desktop( pDisplay ) )
                    aRet.appendAscii( desktop_strings[DESKTOP_CDE] );
                else if ( is_kde_desktop( pDisplay ) )
                    aRet.appendAscii( desktop_strings[DESKTOP_KDE] );
                else
                    aRet.appendAscii( desktop_strings[DESKTOP_UNKNOWN] );

                // set the default handler again
                XSetErrorHandler( pOldHdl );

                XCloseDisplay( pDisplay );
            }
        }
    }

    return aRet.makeStringAndClear();
}

}

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<|endoftext|>


<commit_before>#pragma once
/*
**  Copyright (C) 2013 Aldebaran Robotics
**  See COPYING for the license
*/

#ifndef _QI_SIGNAL_HPP_
#define _QI_SIGNAL_HPP_

#include <qi/atomic.hpp>
#include <qi/eventloop.hpp>

#include <qi/anyfunction.hpp>
#include <qi/type/typeobject.hpp>

#include <boost/thread/thread.hpp>
#include <boost/thread/mutex.hpp>
#include <boost/thread/condition.hpp>
#include <boost/enable_shared_from_this.hpp>

#ifdef _MSC_VER
#  pragma warning( push )
#  pragma warning( disable: 4251 )
#endif

// Macro to be more expressive when emitting a signal. Does nothing, it's normal.
#define QI_EMIT

namespace qi {

  class ManageablePrivate;
  class SignalSubscriber;
  class EventLoop;

  class SignalBasePrivate;

  typedef qi::uint64_t SignalLink;

  //Signal are not copyable, they belong to a class.
  class QI_API SignalBase : boost::noncopyable
  {
  public:
    typedef boost::function<void(bool)> OnSubscribers;
    explicit SignalBase(const Signature &signature, OnSubscribers onSubscribers = OnSubscribers());
    SignalBase(OnSubscribers onSubscribers=OnSubscribers());
    virtual ~SignalBase();
    virtual qi::Signature signature() const;
    template<typename F>
    SignalSubscriber& connect(const boost::function<F>& func);
    SignalSubscriber& connect(const SignalSubscriber& s);
    SignalSubscriber& connect(AnyObject object, const unsigned int slot);
    SignalSubscriber& connect(AnyObject object, const std::string& slot);
    bool disconnectAll();

    /** Disconnect a SignalHandler. The associated callback will not be called
     * anymore as soon as this function returns, but might be called in an
     * other thread while this function runs.
     */
    bool disconnect(const SignalLink& link);

    /** Trigger the signal with given type-erased parameters.
    * @param params the signal arguments
    * @param callType specify how to invoke subscribers.
    *        Used in combination with each subscriber's MetaCallType to
    *        chose between synchronous and asynchronous call.
    *        The combination rule is to honor subscriber's override, then \p callType,
    *        then signal's callType and default to asynchronous
    */
    virtual void trigger(const GenericFunctionParameters& params, MetaCallType callType = MetaCallType_Auto);
    /// Set the MetaCallType used by operator()().
    void setCallType(MetaCallType callType);
    /// Trigger the signal with given arguments, and call type set by setCallType()
    void operator()(
      qi::AutoAnyReference p1 = qi::AutoAnyReference(),
      qi::AutoAnyReference p2 = qi::AutoAnyReference(),
      qi::AutoAnyReference p3 = qi::AutoAnyReference(),
      qi::AutoAnyReference p4 = qi::AutoAnyReference(),
      qi::AutoAnyReference p5 = qi::AutoAnyReference(),
      qi::AutoAnyReference p6 = qi::AutoAnyReference(),
      qi::AutoAnyReference p7 = qi::AutoAnyReference(),
      qi::AutoAnyReference p8 = qi::AutoAnyReference());

    std::vector<SignalSubscriber> subscribers();
    bool hasSubscribers();
    static const SignalLink invalidSignalLink;
  protected:
    typedef boost::function<void(const GenericFunctionParameters& params, MetaCallType callType)> Trigger;
    void callSubscribers(const GenericFunctionParameters& params, MetaCallType callType = MetaCallType_Auto);
    void setTriggerOverride(Trigger trigger);
    void setOnSubscribers(OnSubscribers onSubscribers);
    void callOnSubscribe(bool v);
    void createNewTrackLink(int& id, SignalLink*& trackLink);
    void disconnectTrackLink(int id);
  public:
    void _setSignature(const Signature &s);
    // C4251
    boost::shared_ptr<SignalBasePrivate> _p;
    friend class SignalBasePrivate;
  };

#define QI_SIGNAL_TEMPLATE_DECL typename P0, typename P1, typename P2, typename P3, typename P4, typename P5, typename P6, typename P7
#define QI_SIGNAL_TEMPLATE P0,P1,P2,P3,P4,P5,P6,P7

template<QI_SIGNAL_TEMPLATE_DECL> class Signal;

  template<typename T>
  class SignalF: public SignalBase, public boost::function<T>
  {
  public:
    /** Signal constructor
     * @param onSubscribers invoked each time number of subscribers switch
     * between 0 and 1, with argument '!subscribers.empty()'
     * Will not be called when destructor is invoked and all subscribers are removed
    */
    SignalF(OnSubscribers onSubscribers = OnSubscribers());
    typedef T FunctionType;
    virtual qi::Signature signature() const;
    using boost::function<T>::operator();

#ifdef DOXYGEN
    /** Connect a subscriber to this signal.
    *
    * Multiple forms can be used:
    * - connect(function, argOrPlaceholder1, argOrPlaceholder2, ...)
    *   Where function is a function or callable object (such as a boost::function).
    *   If the first argument is a weak ptr or inherits qi::Trackable, the slot
    *   will automatically disconnect if object is no longuer available.
    * - connect(AnyObject target, unsigned int slot)
    * - connect(AnyObject target, const std::string& slotName)
    * - connect(AnyFunction func)
    * - connect(const SignalSubscriber&)
    * - connect(qi::Signal<U>& otherSignal)
    *
    * @return a SignalSubscriber object. This object can be implicitly
    * converted to a SignalLink.
    * @throw runtime_error if the connection could not be made (because of invalid callback
    * arity or argument type)
    */
    SignalSubscriber& connect(...);
#else

   template<typename CALLABLE> SignalSubscriber& connect(CALLABLE c);
   SignalSubscriber& connect(AnyFunction func);
   SignalSubscriber& connect(const SignalSubscriber& sub);
   SignalSubscriber& connect(const boost::function<T>& func);
   template<typename U> SignalSubscriber&  connect(SignalF<U>& signal);
   template<QI_SIGNAL_TEMPLATE_DECL> SignalSubscriber&  connect(Signal<QI_SIGNAL_TEMPLATE>& signal);

   #define genConnect(n, ATYPEDECL, ATYPES, ADECL, AUSE, comma) \
     template<typename F, typename P comma ATYPEDECL>           \
     SignalSubscriber& connect(F func, P p comma ADECL);
   QI_GEN(genConnect)
   #undef genConnect

   SignalSubscriber& connect(const AnyObject &obj, unsigned int slot);
   SignalSubscriber& connect(const AnyObject &obj, const std::string& slot);
#endif
  };

namespace detail
{
  template<typename P0, typename P1, typename P2, typename P3, typename P4, typename P5, typename P6, typename P7> struct VoidFunctionType                                           { typedef void(type)(P0, P1, P2, P3, P4, P5, P6, P7); };
  template<typename P0, typename P1, typename P2, typename P3, typename P4, typename P5, typename P6> struct VoidFunctionType<P0, P1, P2, P3, P4, P5, P6, void>                     { typedef void(type)(P0, P1, P2, P3, P4, P5, P6); };
  template<typename P0, typename P1, typename P2, typename P3, typename P4, typename P5             > struct VoidFunctionType<P0, P1, P2, P3, P4, P5, void, void>             { typedef void(type)(P0, P1, P2, P3, P4, P5); };
  template<typename P0, typename P1, typename P2, typename P3, typename P4                          > struct VoidFunctionType<P0, P1, P2, P3, P4, void, void, void>           { typedef void(type)(P0, P1, P2, P3, P4); };
  template<typename P0, typename P1, typename P2, typename P3                                       > struct VoidFunctionType<P0, P1, P2, P3, void, void, void, void>         { typedef void(type)(P0, P1, P2, P3); };
  template<typename P0, typename P1, typename P2                                                    > struct VoidFunctionType<P0, P1, P2, void, void, void, void, void>       { typedef void(type)(P0, P1, P2); };
  template<typename P0, typename P1                                                                 > struct VoidFunctionType<P0, P1, void, void, void, void, void, void>     { typedef void(type)(P0, P1); };
  template<typename P0                                                                              > struct VoidFunctionType<P0, void, void, void, void, void, void, void>   { typedef void(type)(P0); };
  template<                                                                                > struct VoidFunctionType<void, void, void, void, void, void, void, void> { typedef void(type)(); };

}
template<
  typename P0 = void,
  typename P1 = void,
  typename P2 = void,
  typename P3 = void,
  typename P4 = void,
  typename P5 = void,
  typename P6 = void,
  typename P7 = void
  >
  class Signal: public SignalF<typename detail::VoidFunctionType<P0, P1, P2, P3, P4, P5, P6, P7>::type>
  {
  public:
    typedef typename detail::VoidFunctionType<P0, P1, P2, P3, P4, P5, P6, P7>::type FunctionType;
    typedef SignalF<FunctionType> ParentType;
    typedef typename ParentType::OnSubscribers OnSubscribers;
    Signal(OnSubscribers onSubscribers = OnSubscribers())
      : ParentType(onSubscribers) {}
    using boost::function<FunctionType>::operator();
  };

  /** Event subscriber info.
   *
   * Only one of handler or target must be set.
   */
  class QI_API SignalSubscriber
  : public boost::enable_shared_from_this<SignalSubscriber>
  {
  public:
    SignalSubscriber()
      : source(0), linkId(SignalBase::invalidSignalLink), target(0), method(0), enabled(true)
    {}

    SignalSubscriber(AnyFunction func, MetaCallType callType = MetaCallType_Auto);
    SignalSubscriber(const AnyObject& target, unsigned int method);

    SignalSubscriber(const SignalSubscriber& b);

    ~SignalSubscriber();

    void operator = (const SignalSubscriber& b);

    /* Perform the call.
     * Threading rules in order:
     * - Honor threadingModel if set (not auto)
     * - Honor callTypoe if set (not auto)
     * - Be asynchronous
     */
    void call(const GenericFunctionParameters& args, MetaCallType callType);

    SignalSubscriber& setCallType(MetaCallType ct);

    //wait till all threads are inactive except the current thread.
    void waitForInactive();

    void addActive(bool acquireLock, boost::thread::id tid = boost::this_thread::get_id());
    void removeActive(bool acquireLock, boost::thread::id tid = boost::this_thread::get_id());
    operator SignalLink() const
    {
      return linkId;
    }
    /** Try to extract exact signature of this subscriber.
    * @return the signature, or an invalid signature if extraction is impossible
    */
    Signature signature() const;
  public:
    // Source information
    SignalBase* source;
    /// Uid that can be passed to GenericObject::disconnect()
    SignalLink  linkId;

    // Target information, kept here to be able to introspect a Subscriber
    //   Mode 1: Direct functor call
    AnyFunction       handler;
    MetaCallType      threadingModel;

    //  Mode 2: metaCall
    AnyWeakObject*    target;
    unsigned int      method;

    boost::mutex      mutex;
    // Fields below are protected by lock

    // If enabled is set to false while lock is acquired,
    // No more callback will trigger (activeThreads will se no push-back)
    bool                         enabled;
    // Number of calls in progress.
    // Each entry there is a subscriber call that can no longuer be aborted
    std::vector<boost::thread::id> activeThreads; // order not preserved

    boost::condition               inactiveThread;
  };
  typedef boost::shared_ptr<SignalSubscriber> SignalSubscriberPtr;
}

#ifdef _MSC_VER
#  pragma warning( pop )
#endif

#include <qi/type/detail/signal.hxx>

QI_NO_TYPE(qi::SignalBase)

#endif  // _QITYPE_SIGNAL_HPP_
<commit_msg>doc: signal<commit_after>#pragma once
/*
**  Copyright (C) 2013 Aldebaran Robotics
**  See COPYING for the license
*/

#ifndef _QI_SIGNAL_HPP_
#define _QI_SIGNAL_HPP_

#include <qi/atomic.hpp>
#include <qi/eventloop.hpp>

#include <qi/anyfunction.hpp>
#include <qi/type/typeobject.hpp>

#include <boost/thread/thread.hpp>
#include <boost/thread/mutex.hpp>
#include <boost/thread/condition.hpp>
#include <boost/enable_shared_from_this.hpp>

#ifdef _MSC_VER
#  pragma warning( push )
#  pragma warning( disable: 4251 )
#endif

// Macro to be more expressive when emitting a signal. Does nothing, it's normal.
#define QI_EMIT

namespace qi {

  class ManageablePrivate;
  class SignalSubscriber;
  class EventLoop;

  class SignalBasePrivate;

  typedef qi::uint64_t SignalLink;

  //Signal are not copyable, they belong to a class.
  class QI_API SignalBase : boost::noncopyable
  {
  public:
    typedef boost::function<void(bool)> OnSubscribers;
    explicit SignalBase(const Signature &signature, OnSubscribers onSubscribers = OnSubscribers());
    SignalBase(OnSubscribers onSubscribers=OnSubscribers());
    virtual ~SignalBase();
    virtual qi::Signature signature() const;
    template<typename F>
    SignalSubscriber& connect(const boost::function<F>& func);
    SignalSubscriber& connect(const SignalSubscriber& s);
    SignalSubscriber& connect(AnyObject object, const unsigned int slot);
    SignalSubscriber& connect(AnyObject object, const std::string& slot);
    bool disconnectAll();

    /** Disconnect a SignalHandler. The associated callback will not be called
     * anymore as soon as this function returns, but might be called in an
     * other thread while this function runs.
     */
    bool disconnect(const SignalLink& link);

    /** Trigger the signal with given type-erased parameters.
    * @param params the signal arguments
    * @param callType specify how to invoke subscribers.
    *        Used in combination with each subscriber's MetaCallType to
    *        chose between synchronous and asynchronous call.
    *        The combination rule is to honor subscriber's override, then \p callType,
    *        then signal's callType and default to asynchronous
    */
    virtual void trigger(const GenericFunctionParameters& params, MetaCallType callType = MetaCallType_Auto);
    /// Set the MetaCallType used by operator()().
    void setCallType(MetaCallType callType);
    /// Trigger the signal with given arguments, and call type set by setCallType()
    void operator()(
      qi::AutoAnyReference p1 = qi::AutoAnyReference(),
      qi::AutoAnyReference p2 = qi::AutoAnyReference(),
      qi::AutoAnyReference p3 = qi::AutoAnyReference(),
      qi::AutoAnyReference p4 = qi::AutoAnyReference(),
      qi::AutoAnyReference p5 = qi::AutoAnyReference(),
      qi::AutoAnyReference p6 = qi::AutoAnyReference(),
      qi::AutoAnyReference p7 = qi::AutoAnyReference(),
      qi::AutoAnyReference p8 = qi::AutoAnyReference());

    std::vector<SignalSubscriber> subscribers();
    bool hasSubscribers();
    static const SignalLink invalidSignalLink;
  protected:
    typedef boost::function<void(const GenericFunctionParameters& params, MetaCallType callType)> Trigger;
    void callSubscribers(const GenericFunctionParameters& params, MetaCallType callType = MetaCallType_Auto);
    void setTriggerOverride(Trigger trigger);
    void setOnSubscribers(OnSubscribers onSubscribers);
    void callOnSubscribe(bool v);
    void createNewTrackLink(int& id, SignalLink*& trackLink);
    void disconnectTrackLink(int id);
  public:
    void _setSignature(const Signature &s);
    // C4251
    boost::shared_ptr<SignalBasePrivate> _p;
    friend class SignalBasePrivate;
  };

#define QI_SIGNAL_TEMPLATE_DECL typename P0, typename P1, typename P2, typename P3, typename P4, typename P5, typename P6, typename P7
#define QI_SIGNAL_TEMPLATE P0,P1,P2,P3,P4,P5,P6,P7

  template<QI_SIGNAL_TEMPLATE_DECL> class Signal;

  template<typename T>
  class SignalF: public SignalBase, public boost::function<T>
  {
  public:
    /** Signal constructor
     * @param onSubscribers invoked each time number of subscribers switch
     * between 0 and 1, with argument '!subscribers.empty()'
     * Will not be called when destructor is invoked and all subscribers are removed
    */
    SignalF(OnSubscribers onSubscribers = OnSubscribers());
    typedef T FunctionType;
    virtual qi::Signature signature() const;
    using boost::function<T>::operator();

#ifdef DOXYGEN
    /** Connect a subscriber to this signal.
    *
    * Multiple forms can be used:
    * - connect(function, argOrPlaceholder1, argOrPlaceholder2, ...)
    *   Where function is a function or callable object (such as a boost::function).
    *   If the first argument is a weak ptr or inherits qi::Trackable, the slot
    *   will automatically disconnect if object is no longuer available.
    * - connect(AnyObject target, unsigned int slot)
    * - connect(AnyObject target, const std::string& slotName)
    * - connect(AnyFunction func)
    * - connect(const SignalSubscriber&)
    * - connect(qi::Signal<U>& otherSignal)
    *
    * @return a SignalSubscriber object. This object can be implicitly
    * converted to a SignalLink.
    * @throw runtime_error if the connection could not be made (because of invalid callback
    * arity or argument type)
    */
    SignalSubscriber& connect(...);
#else

   template<typename CALLABLE> SignalSubscriber& connect(CALLABLE c);
   SignalSubscriber& connect(AnyFunction func);
   SignalSubscriber& connect(const SignalSubscriber& sub);
   SignalSubscriber& connect(const boost::function<T>& func);
   template<typename U> SignalSubscriber&  connect(SignalF<U>& signal);
   template<QI_SIGNAL_TEMPLATE_DECL> SignalSubscriber&  connect(Signal<QI_SIGNAL_TEMPLATE>& signal);

   #define genConnect(n, ATYPEDECL, ATYPES, ADECL, AUSE, comma) \
     template<typename F, typename P comma ATYPEDECL>           \
     SignalSubscriber& connect(F func, P p comma ADECL);
   QI_GEN(genConnect)
   #undef genConnect

   SignalSubscriber& connect(const AnyObject &obj, unsigned int slot);
   SignalSubscriber& connect(const AnyObject &obj, const std::string& slot);
#endif
  };

  namespace detail
  {
    template<typename P0, typename P1, typename P2, typename P3, typename P4, typename P5, typename P6, typename P7> struct VoidFunctionType                                           { typedef void(type)(P0, P1, P2, P3, P4, P5, P6, P7); };
    template<typename P0, typename P1, typename P2, typename P3, typename P4, typename P5, typename P6> struct VoidFunctionType<P0, P1, P2, P3, P4, P5, P6, void>                     { typedef void(type)(P0, P1, P2, P3, P4, P5, P6); };
    template<typename P0, typename P1, typename P2, typename P3, typename P4, typename P5             > struct VoidFunctionType<P0, P1, P2, P3, P4, P5, void, void>             { typedef void(type)(P0, P1, P2, P3, P4, P5); };
    template<typename P0, typename P1, typename P2, typename P3, typename P4                          > struct VoidFunctionType<P0, P1, P2, P3, P4, void, void, void>           { typedef void(type)(P0, P1, P2, P3, P4); };
    template<typename P0, typename P1, typename P2, typename P3                                       > struct VoidFunctionType<P0, P1, P2, P3, void, void, void, void>         { typedef void(type)(P0, P1, P2, P3); };
    template<typename P0, typename P1, typename P2                                                    > struct VoidFunctionType<P0, P1, P2, void, void, void, void, void>       { typedef void(type)(P0, P1, P2); };
    template<typename P0, typename P1                                                                 > struct VoidFunctionType<P0, P1, void, void, void, void, void, void>     { typedef void(type)(P0, P1); };
    template<typename P0                                                                              > struct VoidFunctionType<P0, void, void, void, void, void, void, void>   { typedef void(type)(P0); };
    template<                                                                                > struct VoidFunctionType<void, void, void, void, void, void, void, void> { typedef void(type)(); };

  }

  /** Class that represent an event to which function can subscribe.
   *
   * \includename{qi/signal.hpp}
   */
  template<
    typename P0 = void,
    typename P1 = void,
    typename P2 = void,
    typename P3 = void,
    typename P4 = void,
    typename P5 = void,
    typename P6 = void,
    typename P7 = void
    >
  class Signal: public SignalF<typename detail::VoidFunctionType<P0, P1, P2, P3, P4, P5, P6, P7>::type>
  {
  public:
    typedef typename detail::VoidFunctionType<P0, P1, P2, P3, P4, P5, P6, P7>::type FunctionType;
    typedef SignalF<FunctionType> ParentType;
    typedef typename ParentType::OnSubscribers OnSubscribers;
    Signal(OnSubscribers onSubscribers = OnSubscribers())
      : ParentType(onSubscribers) {}
    using boost::function<FunctionType>::operator();
  };

  /** Event subscriber info.
   *
   * Only one of handler or target must be set.
   *
   * \includename{qi/signal.hpp}
   */
  class QI_API SignalSubscriber
  : public boost::enable_shared_from_this<SignalSubscriber>
  {
  public:
    SignalSubscriber()
      : source(0)
      , linkId(SignalBase::invalidSignalLink)
      , target(0)
      , method(0)
      , enabled(true)
    {}

    SignalSubscriber(AnyFunction func, MetaCallType callType = MetaCallType_Auto);
    SignalSubscriber(const AnyObject& target, unsigned int method);

    SignalSubscriber(const SignalSubscriber& b);

    ~SignalSubscriber();

    void operator = (const SignalSubscriber& b);

    /** Perform the call.
     *
     * Threading rules in order:
     * - Honor threadingModel if set (not auto)
     * - Honor callTypoe if set (not auto)
     * - Be asynchronous
     */
    void call(const GenericFunctionParameters& args, MetaCallType callType);

    SignalSubscriber& setCallType(MetaCallType ct);

    /// Wait until all threads are inactive except the current thread.
    void waitForInactive();

    void addActive(bool acquireLock, boost::thread::id tid = boost::this_thread::get_id());
    void removeActive(bool acquireLock, boost::thread::id tid = boost::this_thread::get_id());
    operator SignalLink() const
    {
      return linkId;
    }
    /** Try to extract exact signature of this subscriber.
    * @return the signature, or an invalid signature if extraction is impossible
    */
    Signature signature() const;
  public:
    // Source information
    SignalBase* source;
    /// Uid that can be passed to GenericObject::disconnect()
    SignalLink  linkId;

    // Target information, kept here to be able to introspect a Subscriber
    //   Mode 1: Direct functor call
    AnyFunction       handler;
    MetaCallType      threadingModel;

    //   Mode 2: metaCall
    AnyWeakObject*    target;
    unsigned int      method;

    boost::mutex      mutex;
    // Fields below are protected by lock

    // If enabled is set to false while lock is acquired,
    // No more callback will trigger (activeThreads will se no push-back)
    bool                         enabled;
    // Number of calls in progress.
    // Each entry there is a subscriber call that can no longuer be aborted
    std::vector<boost::thread::id> activeThreads; // order not preserved

    boost::condition               inactiveThread;
  };
  typedef boost::shared_ptr<SignalSubscriber> SignalSubscriberPtr;
}

#ifdef _MSC_VER
#  pragma warning( pop )
#endif

#include <qi/type/detail/signal.hxx>

QI_NO_TYPE(qi::SignalBase)

#endif  // _QITYPE_SIGNAL_HPP_
<|endoftext|>


<commit_before>#include <iostream>
#include <algorithm>
#include <map>
#include <string>
#include <cstring>
#include <fstream>
#include <cmath>
#include <getopt.h>
#include <vector>
#include <unordered_map>

#include <boost/config.hpp>

#include <boost/graph/adjacency_list.hpp>
#include <boost/graph/undirected_graph.hpp>
#include <boost/graph/graph_traits.hpp>
#include <boost/graph/connected_components.hpp>
#include <boost/graph/iteration_macros.hpp>
#include <boost/graph/dijkstra_shortest_paths.hpp>

using namespace std;

typedef float Weight;
typedef boost::property<boost::edge_weight_t, Weight> WeightProperty;
typedef boost::property<boost::vertex_name_t, std::string> NameProperty;

typedef boost::adjacency_list < boost::listS, boost::vecS, boost::directedS,NameProperty, WeightProperty > Graph;

typedef boost::graph_traits < Graph >::vertex_descriptor Vertex;

typedef boost::property_map < Graph, boost::vertex_index_t >::type IndexMap;
typedef boost::property_map < Graph, boost::vertex_name_t >::type NameMap;

typedef boost::iterator_property_map < Vertex*, IndexMap, Vertex, Vertex& > PredecessorMap;
typedef boost::iterator_property_map < Weight*, IndexMap, Weight, Weight& > DistanceMap;

// typedef boost::property<boost::edge_weight_t, double> EdgeWeightProperty;
// typedef boost::adjacency_list<boost::listS, boost::vecS,boost::bidirectionalS,boost::no_property,EdgeWeightProperty> Graph;

// typedef boost::adjacency_list<boost::vecS, boost::vecS, boost::undirectedS> Graph;

std::vector<std::string> split(std::string const & s, size_t count)
{
  vector<string> ret;
  for(int i = 0;i < s.length();i+=count)
  {
    ret.push_back(s.substr(i,count));
  }
return ret;
}

char* getCharExpr(string s)
{
    char *a=new char[s.size()+1];
    a[s.size()]=0;
    memcpy(a,s.c_str(),s.size());
    return a;
}

void print_usage()
{
	printf("Usage: misasm -g gfa -l hic_links\n");
}

int main(int argc, char* argv[])
{
	int option = 0;
	string gfa="", hic_links="";
	while((option = getopt(argc,argv,"g:l:")) != -1)
	{
		switch(option)
		{
			case 'l':
			{
				//cout<<optarg<<endl;
				hic_links = optarg;
				break;
			}
			case 'g':
			{
				//cout<<optarg<<endl;
				gfa = optarg;
				break;
			}
			default:
			{
				//cout<<"here"<<endl;
				print_usage();
				exit(EXIT_FAILURE);
			}
		}
	}

	if(gfa == "" || hic_links == "")
	{
		print_usage();
		exit(EXIT_FAILURE);
	}

	//unordered_map<string,string> sequences = read_fasta(getCharExpr(assembly));

	/*
	First read the mappings and store them for each contig. Mapping is stored as a pair of (starting_pos,unitig-name)
	*/
	// unordered_map<string,vector<pair<pair<int,int>,string> > > contig2unitig;
	// ifstream mapping(getCharExpr(unitig_mapping));
	// string line;
	// while(getline(mapping,line))
	// {
	// 	int a,b,c,d,e,f;
	// 	double g,j,k;
	// 	int h,i;
	// 	string contig,unitig;
	// 	istringstream iss(line);
	// 	//cout<<line<<endl;
	// 	if(!(iss >> a >> b >> c >> d >> e >>f >> g >> h >> i >> j >> k >> contig >> unitig))
	// 		break;
	// 	if(contig2unitig.find(contig) == contig2unitig.end())
	// 	{
	// 		vector<pair<pair<int,int>,string> > val;
	// 		contig2unitig[contig] = val;
	// 	}
	// 	contig2unitig[contig].push_back(make_pair(make_pair(a,b),unitig));
	// }
	// mapping.close();

	/*
	Now load links. Store them as a boost graph.
	*/
	//cout<<"loading links now"<<endl;
	unordered_map<string,int> unitig2id;
	unordered_map<int,string> id2unitig;
	int id = 0;
	Graph g;
	string line;
	ifstream edges(getCharExpr(gfa));
	while(getline(edges,line))
	{
		string u,v,y,z,a,b;
		double w = 1.0;
		istringstream iss(line);
		/*
		S       tig00000042     *       LN:i:30165
		*/
		if(line[0] == 'S')
		{
			iss >> u >> v >> y >> z;
			if(unitig2id.find(v+":FOW") == unitig2id.end())
			{
				unitig2id[v+":FOW"] = id;
				id2unitig[id] = v+":FOW";
				id++;
			}
			if(unitig2id.find(v+":REV") == unitig2id.end())
			{
				unitig2id[v+":REV"] = id;
				id2unitig[id] = v+":REV";
				id++;
			}
		}
		/*
		L       tig00000014     -       tig00000001     -       5I1M5I
		*/
		if(line[0] == 'L')
		{
			iss >> u >> v >> y >> z >> a >> b;
			string contig1 = v;
			string contig2 = z;
			string or1 = y;
			string or2 = a;
			string v1,v2,v3,v4;
			//cout<<or1<<"\t"<<or2<<endl;
			if(or1 == "+" && or2 == "+")
			{
				v1 = contig1 + ":FOW";
				v2 = contig2 + ":FOW";
				v3 = contig2 + ":REV";
				v4 = contig1 + ":REV";
			}
			if(or1 == "+" && or2 == "-")
			{
				v1 = contig1 + ":FOW";
				v2 = contig2 + ":REV";
				v3 = contig2 + ":FOW";
				v4 = contig1 + ":REV";
			}
			if(or1 == "-" && or2 == "+")
			{
				v1 = contig1 + ":REV";
				v2 = contig2 + ":FOW";
				v3 = contig2 + ":REV";
				v4 = contig1 + ":FOW";
			}
			if(or1 == "-" && or2 == "-")
			{
				v1 = contig1 + ":REV";
				v2 = contig2 + ":REV";
				v3 = contig2 + ":FOW";
				v4 = contig1 + ":FOW";
			}
			boost::add_edge(unitig2id[v1],unitig2id[v2],w,g);
			boost::add_edge(unitig2id[v3],unitig2id[v4],w,g);
		}
	}
	edges.close();
	// cout<<"Done loading links"<<endl;
	// cout<<"Number of Nodes = "<<boost::num_vertices(g)<<endl;
	// cout<<"Number of Edges = "<<boost::num_edges(g)<<endl;

	/*
	Assume that HiC links are given with in the decreasing order of weights.
	Also, process only those shortest path queries for which no link is added before.
	This would reduce tons of computation time
	*/
	// ofstream hiingraph("hi_in_graph.txt");
	// ofstream graphinhic("graph_in_hic.txt");
	unordered_map<string,bool> added;
	ifstream hic(getCharExpr(hic_links));
	while(getline(hic,line))
	{
		string a,b,x,h;
		double c,d,e,f;
		istringstream iss(line);
		iss >> a >> b >> c >> d >> e >> f >> x >> h;
		if(e < 1)
		{
			cout<<line<<endl;
		}
		string u = a.substr(0,a.length()-2);
		string v = b.substr(0,b.length()-2);

		// Create things for Dijkstra
		std::vector<Vertex> predecessorsFOW(boost::num_vertices(g)); // To store parents
		std::vector<Weight> distancesFOW(boost::num_vertices(g)); // To store distances

		IndexMap indexMap = boost::get(boost::vertex_index, g);
		PredecessorMap predecessorMapFOW(&predecessorsFOW[0], indexMap);
		DistanceMap distanceMapFOW(&distancesFOW[0], indexMap);

		boost::dijkstra_shortest_paths(g, unitig2id[u + ":FOW"], boost::distance_map(distanceMapFOW).predecessor_map(predecessorMapFOW));

		std::vector<Vertex> predecessorsREV(boost::num_vertices(g)); // To store parents
		std::vector<Weight> distancesREV(boost::num_vertices(g)); // To store distances

		PredecessorMap predecessorMapREV(&predecessorsREV[0], indexMap);
		DistanceMap distanceMapREV(&distancesREV[0], indexMap);

		boost::dijkstra_shortest_paths(g, unitig2id[u + ":REV"], boost::distance_map(distanceMapREV).predecessor_map(predecessorMapREV));

		long minpath = -1;
		string ori;
		double ratio;

		vector<string> orientations;
		orientations.push_back("BB");
		orientations.push_back("BE");
		orientations.push_back("EB");
		orientations.push_back("EE");
		bool done = false;
		for(int i = 0;i < orientations.size();i++)
		{
			string orientation = orientations[i];
			string v1,v2;
			if(orientation == "BB")
			{
				v1 = u + ":REV";
				v2 = v + ":FOW";
			}
			if(orientation == "BE")
			{
				v1 = u + ":REV";
				v2 = v + ":REV";
			}
			if(orientation == "EB")
			{
				v1 = u + ":FOW";
				v2 = v + ":FOW";
			}
			if(orientation == "EE")
			{
				v1 = u + ":FOW";
				v2 = v + ":REV";
			}
			// cout<<boost::edge(unitig2id[v1],unitig2id[v2],g).second<<endl;
			if(added.find(a) == added.end() && added.find(b) == added.end())
			{
				if(boost::edge(unitig2id[v1],unitig2id[v2],g).second)
				{
					//cout<<line<<endl;
					added[u] = true;
					added[v] = true;
					cout<<u<<":"<<orientation[0]<<"\t"<<v<<":"<<orientation[1]<<"\t"<<c<<"\t"<<d<<"\t"<<e<<"\t"<<f<<"\t"<<x<<"\t"<<h<<endl;
					done = true;
					break;
				}
				else
				{

					//string linkorient = string(a[a.length()-1]) + string(b[b.length()-1]);
					//extract contig name

					long path_len;
					if(orientation == "BB" || orientation == "BE")
					{
						path_len = distanceMapREV[unitig2id[v2]];
					}
					else
					{
						path_len = distanceMapFOW[unitig2id[v2]];
					}
					if(minpath < INT_MAX && minpath > INT_MIN)
					{
						if(minpath == -1)
						{
							minpath = path_len;
							ori = orientation;
						}
						else
						{
							if(path_len < minpath)
							{
								ratio = 1.0*path_len/minpath;
								minpath = path_len;
								ori = orientation;
							}
						}
					}
				}
			}
		}
		// if(!done &&  minpath < INT_MAX && minpath > INT_MIN)
		// {
		// 	cout<<ratio<<"\t"<<minpath<<endl;
		// }
		if(ratio > 0 && ratio < 1 && minpath < INT_MAX && minpath > INT_MIN && !done)
		{
			//cout<<ratio<<"\t"<<minpath<<endl;
			cout<<u+":"+ori[0]<<'\t'<<v+":"+ori[1]<<'\t'<<c<<"\t"<<d<<"\t"<<e<<"\t"<<f<<"\t"<<x<<"\t"<<h<<endl;
			//cout << line << endl;
			added[a] = true;
			added[b] = true;
		}
		else
		{
			cout<<line<<endl;
			added[a] = true;
			added[b] = true;
		}
	}

	// BGL_FORALL_VERTICES(v, g, Graph)
 //  	{
 //  		cout<<id2unitig[1]<<"\t"<<id2unitig[v]<<"\t"<<distanceMap[v]<<endl;
 //  	}
	return 0;
}<commit_msg>graph bug removed<commit_after>#include <iostream>
#include <algorithm>
#include <map>
#include <string>
#include <cstring>
#include <fstream>
#include <cmath>
#include <getopt.h>
#include <vector>
#include <unordered_map>

#include <boost/config.hpp>

#include <boost/graph/adjacency_list.hpp>
#include <boost/graph/undirected_graph.hpp>
#include <boost/graph/graph_traits.hpp>
#include <boost/graph/connected_components.hpp>
#include <boost/graph/iteration_macros.hpp>
#include <boost/graph/dijkstra_shortest_paths.hpp>

using namespace std;

typedef float Weight;
typedef boost::property<boost::edge_weight_t, Weight> WeightProperty;
typedef boost::property<boost::vertex_name_t, std::string> NameProperty;

typedef boost::adjacency_list < boost::listS, boost::vecS, boost::directedS,NameProperty, WeightProperty > Graph;

typedef boost::graph_traits < Graph >::vertex_descriptor Vertex;

typedef boost::property_map < Graph, boost::vertex_index_t >::type IndexMap;
typedef boost::property_map < Graph, boost::vertex_name_t >::type NameMap;

typedef boost::iterator_property_map < Vertex*, IndexMap, Vertex, Vertex& > PredecessorMap;
typedef boost::iterator_property_map < Weight*, IndexMap, Weight, Weight& > DistanceMap;

// typedef boost::property<boost::edge_weight_t, double> EdgeWeightProperty;
// typedef boost::adjacency_list<boost::listS, boost::vecS,boost::bidirectionalS,boost::no_property,EdgeWeightProperty> Graph;

// typedef boost::adjacency_list<boost::vecS, boost::vecS, boost::undirectedS> Graph;

std::vector<std::string> split(std::string const & s, size_t count)
{
  vector<string> ret;
  for(int i = 0;i < s.length();i+=count)
  {
    ret.push_back(s.substr(i,count));
  }
return ret;
}

char* getCharExpr(string s)
{
    char *a=new char[s.size()+1];
    a[s.size()]=0;
    memcpy(a,s.c_str(),s.size());
    return a;
}

void print_usage()
{
	printf("Usage: misasm -g gfa -l hic_links\n");
}

int main(int argc, char* argv[])
{
	int option = 0;
	string gfa="", hic_links="";
	while((option = getopt(argc,argv,"g:l:")) != -1)
	{
		switch(option)
		{
			case 'l':
			{
				//cout<<optarg<<endl;
				hic_links = optarg;
				break;
			}
			case 'g':
			{
				//cout<<optarg<<endl;
				gfa = optarg;
				break;
			}
			default:
			{
				//cout<<"here"<<endl;
				print_usage();
				exit(EXIT_FAILURE);
			}
		}
	}

	if(gfa == "" || hic_links == "")
	{
		print_usage();
		exit(EXIT_FAILURE);
	}

	//unordered_map<string,string> sequences = read_fasta(getCharExpr(assembly));

	/*
	First read the mappings and store them for each contig. Mapping is stored as a pair of (starting_pos,unitig-name)
	*/
	// unordered_map<string,vector<pair<pair<int,int>,string> > > contig2unitig;
	// ifstream mapping(getCharExpr(unitig_mapping));
	// string line;
	// while(getline(mapping,line))
	// {
	// 	int a,b,c,d,e,f;
	// 	double g,j,k;
	// 	int h,i;
	// 	string contig,unitig;
	// 	istringstream iss(line);
	// 	//cout<<line<<endl;
	// 	if(!(iss >> a >> b >> c >> d >> e >>f >> g >> h >> i >> j >> k >> contig >> unitig))
	// 		break;
	// 	if(contig2unitig.find(contig) == contig2unitig.end())
	// 	{
	// 		vector<pair<pair<int,int>,string> > val;
	// 		contig2unitig[contig] = val;
	// 	}
	// 	contig2unitig[contig].push_back(make_pair(make_pair(a,b),unitig));
	// }
	// mapping.close();

	/*
	Now load links. Store them as a boost graph.
	*/
	//cout<<"loading links now"<<endl;
	unordered_map<string,int> unitig2id;
	unordered_map<int,string> id2unitig;
	int id = 0;
	Graph g;
	string line;
	ifstream edges(getCharExpr(gfa));
	while(getline(edges,line))
	{
		string u,v,y,z,a,b;
		double w = 1.0;
		istringstream iss(line);
		/*
		S       tig00000042     *       LN:i:30165
		*/
		if(line[0] == 'S')
		{
			iss >> u >> v >> y >> z;
			if(unitig2id.find(v+":FOW") == unitig2id.end())
			{
				unitig2id[v+":FOW"] = id;
				id2unitig[id] = v+":FOW";
				id++;
			}
			if(unitig2id.find(v+":REV") == unitig2id.end())
			{
				unitig2id[v+":REV"] = id;
				id2unitig[id] = v+":REV";
				id++;
			}
		}
		/*
		L       tig00000014     -       tig00000001     -       5I1M5I
		*/
		if(line[0] == 'L')
		{
			iss >> u >> v >> y >> z >> a >> b;
			string contig1 = v;
			string contig2 = z;
			string or1 = y;
			string or2 = a;
			string v1,v2,v3,v4;
			//cout<<or1<<"\t"<<or2<<endl;
			if(or1 == "+" && or2 == "+")
			{
				v1 = contig1 + ":FOW";
				v2 = contig2 + ":FOW";
				v3 = contig2 + ":REV";
				v4 = contig1 + ":REV";
			}
			if(or1 == "+" && or2 == "-")
			{
				v1 = contig1 + ":FOW";
				v2 = contig2 + ":REV";
				v3 = contig2 + ":FOW";
				v4 = contig1 + ":REV";
			}
			if(or1 == "-" && or2 == "+")
			{
				v1 = contig1 + ":REV";
				v2 = contig2 + ":FOW";
				v3 = contig2 + ":REV";
				v4 = contig1 + ":FOW";
			}
			if(or1 == "-" && or2 == "-")
			{
				v1 = contig1 + ":REV";
				v2 = contig2 + ":REV";
				v3 = contig2 + ":FOW";
				v4 = contig1 + ":FOW";
			}
			boost::add_edge(unitig2id[v1],unitig2id[v2],w,g);
			boost::add_edge(unitig2id[v3],unitig2id[v4],w,g);
		}
	}
	edges.close();
	// cout<<"Done loading links"<<endl;
	// cout<<"Number of Nodes = "<<boost::num_vertices(g)<<endl;
	// cout<<"Number of Edges = "<<boost::num_edges(g)<<endl;

	/*
	Assume that HiC links are given with in the decreasing order of weights.
	Also, process only those shortest path queries for which no link is added before.
	This would reduce tons of computation time
	*/
	// ofstream hiingraph("hi_in_graph.txt");
	// ofstream graphinhic("graph_in_hic.txt");
	unordered_map<string,bool> added;
	ifstream hic(getCharExpr(hic_links));
	while(getline(hic,line))
	{
		string a,b,x,h;
		double c,d,e,f;
		istringstream iss(line);
		iss >> a >> b >> c >> d >> e >> f >> x >> h;
		if(e < 1)
		{
			cout<<line<<endl;
            continue;
		}
		string u = a.substr(0,a.length()-2);
		string v = b.substr(0,b.length()-2);
        if(u[0] == 'K' || v[0] == 'K')
        {
            continue;
        }

		// Create things for Dijkstra
		std::vector<Vertex> predecessorsFOW(boost::num_vertices(g)); // To store parents
		std::vector<Weight> distancesFOW(boost::num_vertices(g)); // To store distances

		IndexMap indexMap = boost::get(boost::vertex_index, g);
		PredecessorMap predecessorMapFOW(&predecessorsFOW[0], indexMap);
		DistanceMap distanceMapFOW(&distancesFOW[0], indexMap);

		boost::dijkstra_shortest_paths(g, unitig2id[u + ":FOW"], boost::distance_map(distanceMapFOW).predecessor_map(predecessorMapFOW));

		std::vector<Vertex> predecessorsREV(boost::num_vertices(g)); // To store parents
		std::vector<Weight> distancesREV(boost::num_vertices(g)); // To store distances

		PredecessorMap predecessorMapREV(&predecessorsREV[0], indexMap);
		DistanceMap distanceMapREV(&distancesREV[0], indexMap);

		boost::dijkstra_shortest_paths(g, unitig2id[u + ":REV"], boost::distance_map(distanceMapREV).predecessor_map(predecessorMapREV));

		long minpath = -1;
		string ori;
		double ratio = 0.1;
		vector<string> orientations;
		orientations.push_back("BB");
		orientations.push_back("BE");
		orientations.push_back("EB");
		orientations.push_back("EE");
		bool done = false;
		bool printed = false;
        bool inlimits = false;
        for(int i = 0;i < orientations.size();i++)
		{
            printed = false;
			string orientation = orientations[i];
			string v1,v2;
			if(orientation == "BB")
			{
				v1 = u + ":REV";
				v2 = v + ":FOW";
			}
			if(orientation == "BE")
			{
				v1 = u + ":REV";
				v2 = v + ":REV";
			}
			if(orientation == "EB")
			{
				v1 = u + ":FOW";
				v2 = v + ":FOW";
			}
			if(orientation == "EE")
			{
				v1 = u + ":FOW";
				v2 = v + ":REV";
			}
			// cout<<boost::edge(unitig2id[v1],unitig2id[v2],g).second<<endl;
			if(added.find(a) == added.end() && added.find(b) == added.end())
			{
				if(boost::edge(unitig2id[v1],unitig2id[v2],g).second)
				{
					//cout<<line<<endl;
					//cout<<"EDGE exists"<<endl;
                    added[u] = true;
					added[v] = true;
					cout<<u<<":"<<orientation[0]<<"\t"<<v<<":"<<orientation[1]<<"\t"<<c<<"\t"<<d<<"\t"<<e<<"\t"<<f<<"\t"<<x<<"\t"<<h<<endl;
					done = true;
					printed = true;
                    break;
				}
				else
				{

					//string linkorient = string(a[a.length()-1]) + string(b[b.length()-1]);
					//extract contig name
				    //cout<<"here"<<endl;
					long path_len;
					if(orientation == "BB" || orientation == "BE")
					{
						path_len = distanceMapREV[unitig2id[v2]];
					    //cout<<"PATH LENGTH = "<<path_len<<endl;
                    }
					else
					{
						path_len = distanceMapFOW[unitig2id[v2]];
                        //cout<<"PATH LENGTH = "<<path_len<<endl;
					}
					if(path_len < INT_MAX && path_len > INT_MIN)
					{
                        //cout<<"in limits"<<endl;
                        inlimits=true;
						if(minpath == -1)
						{
                            //cout<<"setting"<<endl;
                            //cout<<line<<endl;
                            //cout<<orientation<<endl;
							minpath = path_len;
							ori = orientation;
						}
						else
						{
							if(path_len < minpath)
							{
								ratio = 1.0*path_len/minpath;
								minpath = path_len;
								ori = orientation;
							}
						}
					}
				}
			}
		}
		//if(!done &&  minpath < INT_MAX && minpath > INT_MIN)
		//{
		// 	cout<<ratio<<"\t"<<minpath<<endl;
		//}
        if(!inlimits)
        {
            continue;
        }
		if(ratio > 0 && ratio < 1 && minpath < INT_MAX && minpath > INT_MIN && !done)
		{
			//cout<<ratio<<"\t"<<minpath<<endl;
			//cout<<"here"<<endl;
            cout<<u+":"+ori[0]<<'\t'<<v+":"+ori[1]<<'\t'<<c<<"\t"<<d<<"\t"<<e<<"\t"<<f<<"\t"<<x<<"\t"<<h<<endl;
			//cout << line << endl;
			added[a] = true;
			added[b] = true;
		}
		else
		{
			if(!printed)
            {
                cout<<line<<endl;
			    added[a] = true;
			    added[b] = true;
            }
		}
	}

	// BGL_FORALL_VERTICES(v, g, Graph)
 //  	{
 //  		cout<<id2unitig[1]<<"\t"<<id2unitig[v]<<"\t"<<distanceMap[v]<<endl;
 //  	}
	return 0;
}
<|endoftext|>


<commit_before>/*************************************************************************
         BarriereEntree  -  Gère une barrière d'entrée du parking
                             -------------------
    début                : 18/03/2016
    copyright            : (C) 2016 par Arnaud Favier & Marc Gagné
    e-mail               : arnaud.favier@insa-lyon.fr
                           marc.gagne@insa-lyon.fr
*************************************************************************/

//-- Réalisation de la tâche <BarriereEntree> (fichier BarriereEntree.cpp)

/////////////////////////////////////////////////////////////////  INCLUDE
//-------------------------------------------------------- Include système
#include <signal.h>

//------------------------------------------------------ Include personnel
#include "BarriereEntree.h"

///////////////////////////////////////////////////////////////////  PRIVE
//------------------------------------------------------------- Constantes

//------------------------------------------------------------------ Types

//---------------------------------------------------- Variables statiques
static size_t nbVoituriers;
static pid_t voituriers[NB_PLACES];

//------------------------------------------------------ Fonctions privées
//static type nom ( liste de paramètres )
// Mode d'emploi :
//
// Contrat :
//
// Algorithme :
//
//{
//} //----- fin de nom

static void DetruireBarriereEntree(int noSignal)
// Mode d'emploi :
//
// Contrat :
//
// Algorithme :
//
{
    if (noSignal == SIGUSR2)
    {
        // Tuer tous les voituriers qui tournent encore.
        for (size_t i = 0; i < nbVoituriers; i++)
        {
            kill(voituriers[i], SIGUSR2);
        }

        exit(0);
    }
} //----- fin de DetruireBarriereEntree

static int InitialiserBarriereEntree ( enum TypeBarriere barriere )
// Mode d'emploi :
//
// Contrat :
//
// Algorithme :
//
{
    // Gérer le signal de destruction de la tâche.
    struct sigaction actionDetruire;
    actionDetruire.sa_handler = DetruireBarriereEntree;
    sigemptyset(&actionDetruire.sa_mask);
    actionDetruire.sa_flags = 0;
    sigaction(SIGUSR2, &actionDetruire, NULL);

    switch(barriere)
    {
        case PROF_BLAISE_PASCAL:
            return msgget(CLE_BARRIERE_PBP, 0600);
        case AUTRE_BLAISE_PASCAL:
            return msgget(CLE_BARRIERE_ABP, 0600);
        case ENTREE_GASTON_BERGER:
            return msgget(CLE_BARRIERE_EGB, 0600);
        default:
            return 0;
    }
} //----- fin de InitialiserBarriereEntree

//////////////////////////////////////////////////////////////////  PUBLIC
//---------------------------------------------------- Fonctions publiques
//type Nom ( liste de paramètres )
// Algorithme :
//
//{
//} //----- fin de Nom

void BarriereEntree(enum TypeBarriere barriere)
// Algorithme :
//
{
    int boite = InitialiserBarriereEntree(barriere);

    for(;;)
    {
        msg_voiture_t msg;
        msgrcv(boite, &msg, sizeof(msg) - sizeof(msg.mtype), MSG_ENTREE, 0);
        DessinerVoitureBarriere(barriere, msg.usager);
    }

//    DetruireBarriereEntree();
} //----- fin de BarriereEntree

<commit_msg>Modify BarriereEntree: add Voiturier<commit_after>/*************************************************************************
         BarriereEntree  -  Gère une barrière d'entrée du parking
                             -------------------
    début                : 18/03/2016
    copyright            : (C) 2016 par Arnaud Favier & Marc Gagné
    e-mail               : arnaud.favier@insa-lyon.fr
                           marc.gagne@insa-lyon.fr
*************************************************************************/

//-- Réalisation de la tâche <BarriereEntree> (fichier BarriereEntree.cpp)

/////////////////////////////////////////////////////////////////  INCLUDE
//-------------------------------------------------------- Include système
#include <signal.h>
#include <sys/wait.h>
#include <time.h>

//------------------------------------------------------ Include personnel
#include "BarriereEntree.h"

///////////////////////////////////////////////////////////////////  PRIVE
//------------------------------------------------------------- Constantes

//------------------------------------------------------------------ Types

//---------------------------------------------------- Variables statiques
static size_t nbVoituriers;
static pid_t voituriers[NB_PLACES];

//------------------------------------------------------ Fonctions privées
//static type nom ( liste de paramètres )
// Mode d'emploi :
//
// Contrat :
//
// Algorithme :
//
//{
//} //----- fin de nom

static void DetruireBarriereEntree(int noSignal)
// Mode d'emploi :
//
// Contrat :
//
// Algorithme :
//
{
    if (noSignal == SIGUSR2)
    {
        // Tuer tous les voituriers qui tournent encore
        for (size_t i = 0; i < nbVoituriers; i++)
        {
            kill(voituriers[i], SIGUSR2);
        }

        exit(0);
    }
} //----- fin de DetruireBarriereEntree

static void GererFinVoiturier ( int noSignal )
// Mode d'emploi :
//
// Contrat :
//
// Algorithme :
//
{
    if(noSignal == SIGCHLD)
    {
        int status;
        int place = WEXITSTATUS(status);

        AfficherPlace(place, PROF, 1, time(NULL));

        --nbVoituriers;
    }
}

static int InitialiserBarriereEntree ( enum TypeBarriere barriere )
// Mode d'emploi :
//
// Contrat :
//
// Algorithme :
//
{
    // Gérer le signal de destruction de la tâche.
    struct sigaction actionDetruire;
    actionDetruire.sa_handler = DetruireBarriereEntree;
    sigemptyset(&actionDetruire.sa_mask);
    actionDetruire.sa_flags = 0;
    sigaction(SIGUSR2, &actionDetruire, NULL);

    // Gérer le signal de fin d'un voiturier.
    struct sigaction actionFinVoiturier;
    actionFinVoiturier.sa_handler = GererFinVoiturier;
    sigemptyset(&actionFinVoiturier.sa_mask);
    actionFinVoiturier.sa_flags = 0;
    sigaction(SIGCHLD, &actionFinVoiturier, NULL);

    switch(barriere)
    {
        case PROF_BLAISE_PASCAL:
            return msgget(CLE_BARRIERE_PBP, 0600);
        case AUTRE_BLAISE_PASCAL:
            return msgget(CLE_BARRIERE_ABP, 0600);
        case ENTREE_GASTON_BERGER:
            return msgget(CLE_BARRIERE_EGB, 0600);
        default:
            return 0;
    }
} //----- fin de InitialiserBarriereEntree

//////////////////////////////////////////////////////////////////  PUBLIC
//---------------------------------------------------- Fonctions publiques
//type Nom ( liste de paramètres )
// Algorithme :
//
//{
//} //----- fin de Nom

void BarriereEntree(enum TypeBarriere barriere)
// Algorithme :
//
{
    int boite = InitialiserBarriereEntree(barriere);

    for(;;)
    {
        msg_voiture_t msg;
        msgrcv(boite, &msg, sizeof(msg) - sizeof(msg.mtype), MSG_ENTREE, 0);
        DessinerVoitureBarriere(barriere, msg.usager);

        voituriers[nbVoituriers++] = GarerVoiture(barriere);
    }

//    DetruireBarriereEntree();
} //----- fin de BarriereEntree

<|endoftext|>


<commit_before> //  Yigit Suoglu Jul 28, 2016
// Encode and decode ASCII between char and bool array

#include "encode_decode.h"

void encodeASCII(char in, bool & out0, bool & out1, bool & out2, bool & out3, bool & out4, bool & out5, bool & out6, bool & out7)
{
   bool out[8];
    for(int j = 0; j < 8; j++)
        out[j] = 0;

   // int in = inC;
    out[0] = 0;
    if(in % 2)
        out[7] = 1;
    in = in / 2;
    if(in % 2)
        out[6] = 1;
    in = in / 2;
    if(in % 2)
        out[5] = 1;
    in = in / 2;
    if(in % 2)
        out[4] = 1;
    in = in / 2;
    if(in % 2)
        out[3] = 1;
    in = in / 2;
    if(in % 2)
        out[2] = 1;
    in = in / 2;
    if(in % 2)
        out[1] = 1;
    in = in / 2;

   out0 = out[0];
   out1 = out[1];
   out2 = out[2];
   out3 = out[3];
   out4 = out[4];
   out5 = out[5];
   out6 = out[6];
   out7 = out[7];
}

char decodeASCII(bool in0, bool in1, bool in2, bool in3, bool in4, bool in5, bool in6, bool in7)
{

    bool in[8];
    in[0] = in0;
    in[1] = in1;
    in[2] = in2;
    in[3] = in3;
    in[4] = in4;
    in[5] = in5;
    in[6] = in6;
    in[7] = in7;

    int out = 0;
    for(int j = 1; j < 8; j++)
    {
        out = out * 2;
        if(in[j])
            out = out + 1;
    }
    return (char) out;
}

<commit_msg>Update encode_decode.cpp<commit_after> //  Yigit Suoglu Jul 28, 2016
// Encode and decode ASCII between char and bool array

#include "encode_decode.h"

void encodeASCII(char in, bool & out0, bool & out1, bool & out2, bool & out3, bool & out4, bool & out5, bool & out6, bool & out7)
{
   out0=0;
   out0=0;
   out0=0;
   out0=0;
   out0=0;
   out0=0;

   // int in = inC;
    out[0] = 0;
    if(in % 2)
        out[7] = 1;
    in = in / 2;
    if(in % 2)
        out[6] = 1;
    in = in / 2;
    if(in % 2)
        out[5] = 1;
    in = in / 2;
    if(in % 2)
        out[4] = 1;
    in = in / 2;
    if(in % 2)
        out[3] = 1;
    in = in / 2;
    if(in % 2)
        out[2] = 1;
    in = in / 2;
    if(in % 2)
        out[1] = 1;
    in = in / 2;

   out0 = out[0];
   out1 = out[1];
   out2 = out[2];
   out3 = out[3];
   out4 = out[4];
   out5 = out[5];
   out6 = out[6];
   out7 = out[7];
}

char decodeASCII(bool in0, bool in1, bool in2, bool in3, bool in4, bool in5, bool in6, bool in7)
{

    bool in[8];
    in[0] = in0;
    in[1] = in1;
    in[2] = in2;
    in[3] = in3;
    in[4] = in4;
    in[5] = in5;
    in[6] = in6;
    in[7] = in7;

    int out = 0;
    for(int j = 1; j < 8; j++)
    {
        out = out * 2;
        if(in[j])
            out = out + 1;
    }
    return (char) out;
}

<|endoftext|>


<commit_before>#define HAS_VTK 1

/* The Circle class (All source codes in one file) (CircleAIO.cpp) */
#include <iostream>    // using IO functions
#include <string>      // using string
#include "../include/LaShellShellDisplacement.h"

using namespace std;

LaShellShellDisplacement::LaShellShellDisplacement()
{
	_source_la = new LaShell();
	_target_la = new LaShell();
	_output_la = new LaShell();
	_SourcePolyData = vtkSmartPointer<vtkPolyData>::New();
	_num_targets = ONE_TARGET;
	_num_targets_read = 0;
	_aggregate_method = AGGREGATE_MEDIAN;
	_total_targets = 0;
}

LaShellShellDisplacement::~LaShellShellDisplacement() {

}

void LaShellShellDisplacement::SetInputMultipleTargets(char* name_list)
{
	stringstream ss;
	ss << name_list;
	_multiple_target_fn = ss.str();
	_num_targets = MULTIPLE_TARGETS;
	_num_targets_read = 0;
}

void LaShellShellDisplacement::SetInputData(LaShell* shell) {
	_source_la = shell;
	_source_la->GetMesh3D(_SourcePolyData);

}

void LaShellShellDisplacement::SetInputData2(LaShell* shell) {
	cout << "Fatal warning: Functionality not implemented yet!" << endl;
}

void LaShellShellDisplacement::SetAggregateMethodToMedian()
{
	_aggregate_method = AGGREGATE_MEDIAN;
}

void LaShellShellDisplacement::SetAggregateMethodToMean()
{
	_aggregate_method = AGGREGATE_MEAN;
}

LaShell* LaShellShellDisplacement::GetOutput() {
	return _output_la;
}

double LaShellShellDisplacement::GetEuclidean(double* p1, double* p2)
{
	double sum;
	sum = ((p1[0] - p2[0])*(p1[0] - p2[0])) + ((p1[1] - p2[1])*(p1[1] - p2[1])) + ((p1[2] - p2[2])*(p1[2] - p2[2]));
	return sqrt(sum);
}

bool LaShellShellDisplacement::ReadShellNameList(const char* fn)
{
	ifstream infile(fn);
	cout << "Reading mutliple target filename list .. \n";
	std::string line;

	while (getline(infile, line))
	{
		istringstream iss(line);
		string filename;
		if (!(iss >> filename)) {
			cout << "Error reading file containing filenames, check format" << endl;
			return false;
		} // error
		else {
			cout << "Found " << filename << endl;
			_filename_list.push_back(filename);
			_total_targets++;
		}

		// process pair (a,b)
	}
	return true;
}

// take a small step inside shell, compare distance to test_point to small step outside shell
int LaShellShellDisplacement::IsPointOutsideOrInsideShell(vtkIdType shell_point, double* test_point)
{
	double normal_vec[3], shell_point_xyz[3];
	double small_step = 0.1;

	_SourcePolyData->GetPoint(shell_point, shell_point_xyz);
	_SourcePolyNormals->GetTuple(shell_point, normal_vec);

	double small_step_inside_shell[3], small_step_outside_shell[3];

	small_step_outside_shell[0] = shell_point_xyz[0] + (small_step*normal_vec[0]);
	small_step_outside_shell[1] = shell_point_xyz[1] + (small_step*normal_vec[1]);
	small_step_outside_shell[2] = shell_point_xyz[2] + (small_step*normal_vec[2]);

	small_step_inside_shell[0] = shell_point_xyz[0] + (-1*small_step*normal_vec[0]);
	small_step_inside_shell[1] = shell_point_xyz[1] + (-1*small_step*normal_vec[1]);
	small_step_inside_shell[2] = shell_point_xyz[2] + (-1*small_step*normal_vec[2]);

	double test_to_inside_point = GetEuclidean(test_point, small_step_inside_shell);
	double test_to_outside_point = GetEuclidean(test_point, small_step_outside_shell);

	if (test_to_inside_point < test_to_outside_point)
	{
		// inside point is closer to test point
		return -1;
	}
	else if (test_to_inside_point >= test_to_outside_point)
	{
		return 1;
	}

}

void LaShellShellDisplacement::ReadShellComputeDisplacement(string poly_data_fn)
{
	vtkSmartPointer<vtkPolyDataReader> reader1 = vtkSmartPointer<vtkPolyDataReader>::New();
	reader1->SetFileName(poly_data_fn.c_str());
	reader1->Update();

	cout << "Processing next file for displacment: " << poly_data_fn << " ... ";
	vtkSmartPointer<vtkPolyData> TargetPolyData = vtkSmartPointer<vtkPolyData>::New();
	TargetPolyData = reader1->GetOutput();

	vtkSmartPointer<vtkPointLocator> Target_Poly_PointLocator = vtkSmartPointer<vtkPointLocator>::New();
	Target_Poly_PointLocator->SetDataSet(TargetPolyData);
	Target_Poly_PointLocator->AutomaticOn();
	Target_Poly_PointLocator->BuildLocator();

	// compute normals for finding direction of displacement
	vtkSmartPointer<vtkPolyDataNormals> Source_Poly_Normals = vtkSmartPointer<vtkPolyDataNormals>::New();
	Source_Poly_Normals->ComputeCellNormalsOn();
	Source_Poly_Normals->SetInputData(_SourcePolyData);
	Source_Poly_Normals->Update();

	_SourcePolyNormals = vtkFloatArray::SafeDownCast(_SourcePolyData->GetPointData()->GetNormals());

	_displacements.resize(_SourcePolyData->GetNumberOfPoints(), vector<double>(_total_targets));

	//_displacement_direction.resize(_SourcePolyData->GetNumberOfPoints(), vector<double>(_total_targets));

	double source_vertex[3], target_vertex[3];

	for (vtkIdType i = 0; i < _SourcePolyData->GetNumberOfPoints(); ++i) {

		_SourcePolyData->GetPoint(i, source_vertex);

		vtkIdType id_on_target = Target_Poly_PointLocator->FindClosestPoint(source_vertex);

		TargetPolyData->GetPoint(id_on_target, target_vertex);
		double displacement = GetEuclidean(source_vertex, target_vertex);

		if (i < _displacements.size() && _num_targets_read < _displacements[i].size())
		{

			// check direction of displacement
			int displacement_direction = IsPointOutsideOrInsideShell(i, target_vertex);
			_displacements[i][_num_targets_read] = displacement_direction*displacement;
		}

	}

	_num_targets_read++;

	cout << "completed!" << endl;
}

void LaShellShellDisplacement::AggregateAllDisplacements()
{

	vtkSmartPointer<vtkPolyData> shell_poly = vtkSmartPointer<vtkPolyData>::New();
	_source_la->GetMesh3D(shell_poly);

	cout << "Aggregating displacements .. " << endl;

	cout << "Size of 2D container = " << _displacements.size();

	/*for (int i = 0; i < _displacements.size(); ++i) {
		cout << "\ni=" << i << ", size=" << _displacements[i].size() << endl;
	}*/

	// prepare output
	vtkSmartPointer<vtkPolyData> OutputPoly = vtkSmartPointer<vtkPolyData>::New();
	OutputPoly->DeepCopy(shell_poly);

	vtkSmartPointer<vtkFloatArray> output_scalars = vtkSmartPointer<vtkFloatArray>::New();
	output_scalars->SetNumberOfComponents(1);

	for (int i = 0; i < shell_poly->GetNumberOfPoints(); ++i) {

		double atlas_value = -1;
		if (_aggregate_method == AGGREGATE_MEDIAN)
		{
			// computing mean
			double median = MathBox::CalcMedian(_displacements[i]);
			atlas_value = median;
		}
		else if (_aggregate_method == AGGREGATE_MEAN)
		{
			// compute median
			double mean = MathBox::CalcMean(_displacements[i]);
			atlas_value = mean;
		}

		output_scalars->InsertNextTuple1(atlas_value);
	}

	OutputPoly->GetPointData()->SetScalars(output_scalars);

	_output_la->SetMesh3D(OutputPoly);
}

void LaShellShellDisplacement::Update() {

	// VTK error logging
	vtkSmartPointer<vtkFileOutputWindow> fileOutputWindow = vtkSmartPointer<vtkFileOutputWindow>::New();
	fileOutputWindow->SetFileName("vtkLog.txt");
	vtkOutputWindow* outputWindow = vtkOutputWindow::GetInstance();
	if (outputWindow)
	{
		outputWindow->SetInstance(fileOutputWindow);
	}

	if (_num_targets == MULTIPLE_TARGETS)
	{
		ReadShellNameList(_multiple_target_fn.c_str());

		for (int i = 1; i < _filename_list.size(); i++)
		{
			ReadShellComputeDisplacement(_filename_list[i]);
		}

		AggregateAllDisplacements();
	}

}

<commit_msg>test cases passed<commit_after>#define HAS_VTK 1

/* The Circle class (All source codes in one file) (CircleAIO.cpp) */
#include <iostream>    // using IO functions
#include <string>      // using string
#include "../include/LaShellShellDisplacement.h"

using namespace std;

LaShellShellDisplacement::LaShellShellDisplacement()
{
	_source_la = new LaShell();
	_target_la = new LaShell();
	_output_la = new LaShell();
	_SourcePolyData = vtkSmartPointer<vtkPolyData>::New();
	_num_targets = ONE_TARGET;
	_num_targets_read = 0;
	_aggregate_method = AGGREGATE_MEDIAN;
	_total_targets = 0;
}

LaShellShellDisplacement::~LaShellShellDisplacement() {

}

void LaShellShellDisplacement::SetInputMultipleTargets(char* name_list)
{
	stringstream ss;
	ss << name_list;
	_multiple_target_fn = ss.str();
	_num_targets = MULTIPLE_TARGETS;
	_num_targets_read = 0;
}

void LaShellShellDisplacement::SetInputData(LaShell* shell) {
	_source_la = shell;
	_source_la->GetMesh3D(_SourcePolyData);

}

void LaShellShellDisplacement::SetInputData2(LaShell* shell) {
	cout << "Fatal warning: Functionality not implemented yet!" << endl;
}

void LaShellShellDisplacement::SetAggregateMethodToMedian()
{
	_aggregate_method = AGGREGATE_MEDIAN;
}

void LaShellShellDisplacement::SetAggregateMethodToMean()
{
	_aggregate_method = AGGREGATE_MEAN;
}

LaShell* LaShellShellDisplacement::GetOutput() {
	return _output_la;
}

double LaShellShellDisplacement::GetEuclidean(double* p1, double* p2)
{
	double sum;
	sum = ((p1[0] - p2[0])*(p1[0] - p2[0])) + ((p1[1] - p2[1])*(p1[1] - p2[1])) + ((p1[2] - p2[2])*(p1[2] - p2[2]));
	return sqrt(sum);
}

bool LaShellShellDisplacement::ReadShellNameList(const char* fn)
{
	ifstream infile(fn);
	cout << "Reading mutliple target filename list .. \n";
	std::string line;

	while (getline(infile, line))
	{
		istringstream iss(line);
		string filename;
		if (!(iss >> filename)) {
			cout << "Error reading file containing filenames, check format" << endl;
			return false;
		} // error
		else {
			cout << "Found " << filename << endl;
			_filename_list.push_back(filename);
			_total_targets++;
		}

		// process pair (a,b)
	}
	return true;
}

// take a small step inside shell, compare distance to test_point to small step outside shell
int LaShellShellDisplacement::IsPointOutsideOrInsideShell(vtkIdType shell_point, double* test_point)
{
	double normal_vec[3], shell_point_xyz[3];
	double small_step = 0.1;

	_SourcePolyData->GetPoint(shell_point, shell_point_xyz);
	_SourcePolyNormals->GetTuple(shell_point, normal_vec);

	double small_step_inside_shell[3], small_step_outside_shell[3];

	small_step_outside_shell[0] = shell_point_xyz[0] + (small_step*normal_vec[0]);
	small_step_outside_shell[1] = shell_point_xyz[1] + (small_step*normal_vec[1]);
	small_step_outside_shell[2] = shell_point_xyz[2] + (small_step*normal_vec[2]);

	small_step_inside_shell[0] = shell_point_xyz[0] + (-1*small_step*normal_vec[0]);
	small_step_inside_shell[1] = shell_point_xyz[1] + (-1*small_step*normal_vec[1]);
	small_step_inside_shell[2] = shell_point_xyz[2] + (-1*small_step*normal_vec[2]);

	double test_to_inside_point = GetEuclidean(test_point, small_step_inside_shell);
	double test_to_outside_point = GetEuclidean(test_point, small_step_outside_shell);

	if (test_to_inside_point < test_to_outside_point)
	{
		// inside point is closer to test point
		return -1;
	}
	else if (test_to_inside_point >= test_to_outside_point)
	{
		return 1;
	}

}

void LaShellShellDisplacement::ReadShellComputeDisplacement(string poly_data_fn)
{
	vtkSmartPointer<vtkPolyDataReader> reader1 = vtkSmartPointer<vtkPolyDataReader>::New();
	reader1->SetFileName(poly_data_fn.c_str());
	reader1->Update();

	cout << "Processing next file for displacment: " << poly_data_fn << " ... ";
	vtkSmartPointer<vtkPolyData> TargetPolyData = vtkSmartPointer<vtkPolyData>::New();
	TargetPolyData = reader1->GetOutput();

	vtkSmartPointer<vtkPointLocator> Target_Poly_PointLocator = vtkSmartPointer<vtkPointLocator>::New();
	Target_Poly_PointLocator->SetDataSet(TargetPolyData);
	Target_Poly_PointLocator->AutomaticOn();
	Target_Poly_PointLocator->BuildLocator();

	// compute normals for finding direction of displacement
	vtkSmartPointer<vtkPolyDataNormals> Source_Poly_Normals = vtkSmartPointer<vtkPolyDataNormals>::New();
	Source_Poly_Normals->ComputeCellNormalsOn();
	Source_Poly_Normals->SetInputData(_SourcePolyData);
	Source_Poly_Normals->Update();

	_SourcePolyNormals = vtkFloatArray::SafeDownCast(_SourcePolyData->GetPointData()->GetNormals());

	_displacements.resize(_SourcePolyData->GetNumberOfPoints(), vector<double>(_total_targets));

	//_displacement_direction.resize(_SourcePolyData->GetNumberOfPoints(), vector<double>(_total_targets));

	double source_vertex[3], target_vertex[3];

	for (vtkIdType i = 0; i < _SourcePolyData->GetNumberOfPoints(); ++i) {

		_SourcePolyData->GetPoint(i, source_vertex);

		vtkIdType id_on_target = Target_Poly_PointLocator->FindClosestPoint(source_vertex);

		TargetPolyData->GetPoint(id_on_target, target_vertex);
		double displacement = GetEuclidean(source_vertex, target_vertex);

		if (i < _displacements.size() && _num_targets_read < _displacements[i].size())
		{

			// check direction of displacement
			int displacement_direction = IsPointOutsideOrInsideShell(i, target_vertex);
			//int displacement_direction = 1;
			_displacements[i][_num_targets_read] = displacement_direction*displacement;
		}

	}

	_num_targets_read++;

	cout << "completed!" << endl;
}

void LaShellShellDisplacement::AggregateAllDisplacements()
{

	vtkSmartPointer<vtkPolyData> shell_poly = vtkSmartPointer<vtkPolyData>::New();
	_source_la->GetMesh3D(shell_poly);

	cout << "Aggregating displacements .. " << endl;

	cout << "Size of 2D container = " << _displacements.size();

	/*for (int i = 0; i < _displacements.size(); ++i) {
		cout << "\ni=" << i << ", size=" << _displacements[i].size() << endl;
	}*/

	// prepare output
	vtkSmartPointer<vtkPolyData> OutputPoly = vtkSmartPointer<vtkPolyData>::New();
	OutputPoly->DeepCopy(shell_poly);

	vtkSmartPointer<vtkFloatArray> output_scalars = vtkSmartPointer<vtkFloatArray>::New();
	output_scalars->SetNumberOfComponents(1);

	for (int i = 0; i < shell_poly->GetNumberOfPoints(); ++i) {

		double atlas_value = -1;
		if (_aggregate_method == AGGREGATE_MEDIAN)
		{
			// computing mean
			double median = MathBox::CalcMedian(_displacements[i]);
			atlas_value = median;
		}
		else if (_aggregate_method == AGGREGATE_MEAN)
		{
			// compute median
			double mean = MathBox::CalcMean(_displacements[i]);
			atlas_value = mean;
		}

		output_scalars->InsertNextTuple1(atlas_value);
	}

	OutputPoly->GetPointData()->SetScalars(output_scalars);

	_output_la->SetMesh3D(OutputPoly);
}

void LaShellShellDisplacement::Update() {

	// VTK error logging
	vtkSmartPointer<vtkFileOutputWindow> fileOutputWindow = vtkSmartPointer<vtkFileOutputWindow>::New();
	fileOutputWindow->SetFileName("vtkLog.txt");
	vtkOutputWindow* outputWindow = vtkOutputWindow::GetInstance();
	if (outputWindow)
	{
		outputWindow->SetInstance(fileOutputWindow);
	}

	if (_num_targets == MULTIPLE_TARGETS)
	{
		ReadShellNameList(_multiple_target_fn.c_str());

		for (int i = 0; i < _filename_list.size(); i++)
		{
			ReadShellComputeDisplacement(_filename_list[i]);
		}

		AggregateAllDisplacements();
	}

}

<|endoftext|>


<commit_before><commit_msg>Late addressing<commit_after><|endoftext|>


<commit_before>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: QNameToString.hxx,v $
 * $Revision: 1.6 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org 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 version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/
#ifndef INCLUDED_QNAME_TO_STRING_HXX
#define INCLUDED_QNAME_TO_STRING_HXX

#include <boost/shared_ptr.hpp>
#include <map>
#include <string>
#include <iostream>
#include <resourcemodel/WW8ResourceModel.hxx>
#include <com/sun/star/beans/XPropertySet.hpp>

namespace writerfilter
{
using namespace ::std;

class WRITERFILTER_DLLPUBLIC QNameToString
{
    typedef boost::shared_ptr<QNameToString> Pointer_t;
    typedef map < Id, string > Map;

    static Pointer_t pInstance;

    void init_doctok();
    void init_ooxml();

    Map mMap;

protected:
    /**
       Generated.
     */
    QNameToString();

public:
    static Pointer_t Instance();

    string operator()(Id qName);
};

class WRITERFILTER_DLLPUBLIC SprmIdToString
{
    typedef boost::shared_ptr<SprmIdToString> Pointer_t;

    static Pointer_t pInstance;

    map<sal_uInt32, string> mMap;

protected:
    /**
       Generated automatically.
    */
    SprmIdToString();

public:
    static Pointer_t Instance();
    string operator()(sal_uInt32 nId);
};

string WRITERFILTER_DLLPUBLIC xmlify(const string & str);

string WRITERFILTER_DLLPUBLIC propertysetToString
(uno::Reference<beans::XPropertySet> const & rProps);

struct XMLAttribute
{
    string mName;
    string mValue;
public:
    XMLAttribute(string sName, string sValue)
    : mName(sName), mValue(sValue)
    {
    }

};

class WRITERFILTER_DLLPUBLIC XMLTag
{
public:
    enum eMode { START, END, COMPLETE };
    typedef boost::shared_ptr<XMLTag> Pointer_t;

private:
    string mTag;
    string mChars;
    vector<XMLAttribute> mAttrs;
    vector<XMLTag::Pointer_t> mTags;
    eMode mMode;

public:
    XMLTag(string sTag, eMode mode = COMPLETE) : mTag(sTag), mMode(mode) {}

    void addAttr(string name, string value);
    void addTag(Pointer_t pTag);
    void chars(const string & rChars);
    string toString() const;
};

}

#endif // INCLUDED_QNAME_TO_STRING_HXX
<commit_msg>INTEGRATION: CWS xmlfilter06 (1.6.6); FILE MERGED 2008/05/30 12:09:40 hbrinkm 1.6.6.2: Moved some classes/functions to util.hxx 2008/05/27 11:36:05 dr 1.6.6.1: joined changes from CWS xmlfilter05<commit_after>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: QNameToString.hxx,v $
 * $Revision: 1.7 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org 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 version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/
#ifndef INCLUDED_QNAME_TO_STRING_HXX
#define INCLUDED_QNAME_TO_STRING_HXX

#include <boost/shared_ptr.hpp>
#include <map>
#include <string>
#include <iostream>
#include <resourcemodel/WW8ResourceModel.hxx>
#include <com/sun/star/beans/XPropertySet.hpp>

namespace writerfilter
{
using namespace ::std;

class WRITERFILTER_DLLPUBLIC QNameToString
{
    typedef boost::shared_ptr<QNameToString> Pointer_t;
    typedef map < Id, string > Map;

    static Pointer_t pInstance;

    void init_doctok();
    void init_ooxml();

    Map mMap;

protected:
    /**
       Generated.
     */
    QNameToString();

public:
    static Pointer_t Instance();

    string operator()(Id qName);
};

class WRITERFILTER_DLLPUBLIC SprmIdToString
{
    typedef boost::shared_ptr<SprmIdToString> Pointer_t;

    static Pointer_t pInstance;

    map<sal_uInt32, string> mMap;

protected:
    /**
       Generated automatically.
    */
    SprmIdToString();

public:
    static Pointer_t Instance();
    string operator()(sal_uInt32 nId);
};

}

#endif // INCLUDED_QNAME_TO_STRING_HXX
<|endoftext|>


<commit_before>/* notes

The only hard part about this will be the ace. Could be 1 or 11.

The deck is suit-less, however, it would be a good idea to use an array to pick from
	where it would be like [1,2,3,...10,10,10,1,2,... repeat]. The reason for this is
	there are three 10s so the chance of getting one should be higher. Use at least 4
	copies each number to represent the deck.

The user gets dealt two, and the dealer one. The dealer asks if you want more until
	you say no. Then it is the dealers turn. They must keep going until they have
	more than or equal 17. so if they had 16, they'd have to get another card, knowing
	that a 10 would bust them. If the users first two cards = 10 or 9, the game is worth
	two. Each game won is normally worth 1 point, and the game needs to repeat 10 times.

*/

#include <iostream>
using namespace std;

int main()
{
	const int cardsDeck[52] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 1, 2, 3, 4, 5, 6, 7, 8, 9,
	10, 10, 10, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 1, 2, 3, 4,
	5, 6, 7, 8, 9, 10, 10, 10, }; // 52 cards, with 10 being face card
	int dealerWins;
	int playerWins;
	int dealerHand[10];
	int playerHand[10];
	int dealRand(int);
}

<commit_msg>setup random and dealing functions<commit_after>/*

*/

#include <iostream>
#include <time.h>
using namespace std;

// global card deck variable
const int cardsDeck[52] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 1, 2, 3, 4, 5, 6, 7, 8, 9,
10, 10, 10, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 1, 2, 3, 4,
5, 6, 7, 8, 9, 10, 10, 10, }; // 52 cards, with 10 being face card

// functions
void random(); // random number setup
int deal(); // function to deal a card
int ace(int); // function to decide an ace's value
int handValue(int[]); // sums the value of a given hand

int main()
{
	// enum
	enum gameStatus // what is the status of the game
	{
		inProgress,win,bust
	};

	// structs
	struct player
	{
		int hand[10];
		gameStatus status;
		int winCounter;
	};
	player user/*, dealer*/;

	// variables
	int hands = 0; // counter for hands played

	// random set up
	random();

	// game
	while (hands < 10)
	{
		user.hand[0] = deal();
		user.hand[1] = deal();

		cout << "Let's play a hand.\n";
		cout << "Your hand: \n";
		cout << user.hand[0] << " " << user.hand[1] << endl;

		cin >> hands;
	}

	return 0;
}

int deal()
{
	int cardIndex = 0; // random index value
	int card = 0; // actual card value to return

	cardIndex = rand() % 52;
	//cout << "Random index picked:" << cardIndex << endl; // testing output

	card = cardsDeck[cardIndex];
	//cout << "Card is " << card << endl;

	return card;
}

void random()
{
	long seed;
	time_t *storage;
	storage = 0;
	seed = time(storage); // use the system clock to produce an initial time
	srand(seed);  // to seed the random number generator
}<|endoftext|>