<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: DescriptionGenerator.cxx,v $
 *
 *  $Revision: 1.12 $
 *
 *  last change: $Author: hr $ $Date: 2007-06-27 16:41:22 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

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

#include "DescriptionGenerator.hxx"

#ifndef _COM_SUN_STAR_BEANS_PROPERTYSTATE_HPP_
#include <com/sun/star/beans/PropertyState.hpp>
#endif
#ifndef _COM_SUN_STAR_BEANS_XPROPERTYSET_HPP_
#include <com/sun/star/beans/XPropertySet.hpp>
#endif
#ifndef _COM_SUN_STAR_BEANS_XPROPERTYSTATE_HPP_
#include <com/sun/star/beans/XPropertyState.hpp>
#endif
#ifndef _COM_SUN_STAR_CONTAINER_XCHILD_HPP_
#include <com/sun/star/container/XChild.hpp>
#endif
#ifndef _COM_SUN_STAR_CONTAINER_XNAMECONTAINER_HPP_
#include <com/sun/star/container/XNameContainer.hpp>
#endif
#ifndef _COM_SUN_STAR_CONTAINER_XNAMEACCESS_HPP_
#include <com/sun/star/container/XNameAccess.hpp>
#endif
#ifndef _COM_SUN_STAR_CONTAINER_XNAMED_HPP_
#include <com/sun/star/container/XNamed.hpp>
#endif
#ifndef _COM_SUN_STAR_DRAWING_FILLSTYLE_HPP_
#include <com/sun/star/drawing/FillStyle.hpp>
#endif
#ifndef _COM_SUN_STAR_DRAWING_XSHAPES_HPP_
#include <com/sun/star/drawing/XShapes.hpp>
#endif
#ifndef _COM_SUN_STAR_DRAWING_XSHAPEDESCRIPTOR_HPP_
#include <com/sun/star/drawing/XShapeDescriptor.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_INDEXOUTOFBOUNDSEXCEPTION_HPP_
#include <com/sun/star/lang/IndexOutOfBoundsException.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#endif
#ifndef _COM_SUN_STAR_STYLE_XSTYLE_HPP_
#include <com/sun/star/style/XStyle.hpp>
#endif

#ifndef _COMPHELPER_PROCESSFACTORY_HXX_
#include <comphelper/processfactory.hxx>
#endif
#ifndef _VOS_MUTEX_HXX_
#include <vos/mutex.hxx>
#endif
#ifndef _SV_SVAPP_HXX
#include <vcl/svapp.hxx>
#endif

#include <com/sun/star/uno/Exception.hpp>

// Includes for string resources.
#ifndef _SVX_ACCESSIBILITY_HRC
#include "accessibility.hrc"
#endif
#include "svdstr.hrc"
#ifndef _SVX_DIALMGR_HXX
#include <svx/dialmgr.hxx>
#endif
#ifndef _STRING_HXX
#include <tools/string.hxx>
#endif

#include <svx/xdef.hxx>
#include "unoapi.hxx"
#include "accessibility.hrc"
#include "DGColorNameLookUp.hxx"

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

void SvxUnogetInternalNameForItem( const sal_Int16 nWhich, const rtl::OUString& rApiName, String& rInternalName ) throw();

namespace accessibility {

DescriptionGenerator::DescriptionGenerator (
    const uno::Reference<drawing::XShape>& xShape)
    : mxShape (xShape),
      mxSet (mxShape, uno::UNO_QUERY),
      mbIsFirstProperty (true)
{
}

DescriptionGenerator::~DescriptionGenerator (void)
{
}

void DescriptionGenerator::Initialize (sal_Int32 nResourceId)
{
    // Get the string from the resource for the specified id.
    OUString sPrefix;
    {
        ::vos::OGuard aGuard (::Application::GetSolarMutex());
        sPrefix = OUString (SVX_RESSTR (nResourceId));
    }

    // Forward the call with the resulting string.
    Initialize (sPrefix);
}

void DescriptionGenerator::Initialize (::rtl::OUString sPrefix)
{
    msDescription = sPrefix;
    if (mxSet.is())
    {
        {
            ::vos::OGuard aGuard (::Application::GetSolarMutex());

            msDescription.append (sal_Unicode (' '));
            msDescription.append (OUString (SVX_RESSTR(RID_SVXSTR_A11Y_WITH)));
            msDescription.append (sal_Unicode (' '));

            msDescription.append (OUString (SVX_RESSTR (RID_SVXSTR_A11Y_STYLE)));
            msDescription.append (sal_Unicode ('='));
        }

        try
        {
            if (mxSet.is())
            {
                uno::Any aValue = mxSet->getPropertyValue (OUString::createFromAscii ("Style"));
                uno::Reference<container::XNamed> xStyle (aValue, uno::UNO_QUERY);
                if (xStyle.is())
                    msDescription.append (xStyle->getName());
            }
            else
                msDescription.append (
                    OUString::createFromAscii("<no style>"));
        }
        catch (::com::sun::star::beans::UnknownPropertyException)
        {
            msDescription.append (
                OUString::createFromAscii("<unknown>"));
        }
    }
}

::rtl::OUString DescriptionGenerator::operator() (void)
{
    msDescription.append (sal_Unicode ('.'));
    return msDescription.makeStringAndClear();
}

void DescriptionGenerator::AddProperty (
    const OUString& sPropertyName,
    PropertyType aType,
    const sal_Int32 nLocalizedNameId,
    long nWhichId)
{
    OUString sLocalizedName;
    {
        ::vos::OGuard aGuard (::Application::GetSolarMutex());
        sLocalizedName = SVX_RESSTR (nLocalizedNameId);
    }
    AddProperty (sPropertyName, aType, sLocalizedName, nWhichId);
}

void DescriptionGenerator::AddProperty (const OUString& sPropertyName,
    PropertyType aType, const OUString& sLocalizedName, long nWhichId)
{
    uno::Reference<beans::XPropertyState> xState (mxShape, uno::UNO_QUERY);
    if (xState.is()
        && xState->getPropertyState(sPropertyName)!=beans::PropertyState_DEFAULT_VALUE)
        if (mxSet.is())
        {
            // Append a seperator from previous Properties.
            if ( ! mbIsFirstProperty)
                msDescription.append (sal_Unicode (','));
            else
            {
                ::vos::OGuard aGuard (::Application::GetSolarMutex());

                msDescription.append (sal_Unicode (' '));
                msDescription.append (OUString (SVX_RESSTR(RID_SVXSTR_A11Y_AND)));
                msDescription.append (sal_Unicode (' '));
                mbIsFirstProperty = false;
            }

            // Delegate to type specific property handling.
            switch (aType)
            {
                case COLOR:
                    AddColor (sPropertyName, sLocalizedName);
                    break;
                case INTEGER:
                    AddInteger (sPropertyName, sLocalizedName);
                    break;
                case STRING:
                    AddString (sPropertyName, sLocalizedName, nWhichId);
                    break;
                case FILL_STYLE:
                    AddFillStyle (sPropertyName, sLocalizedName);
                    break;
            }
        }
}

void DescriptionGenerator::AppendString (const ::rtl::OUString& sString)
{
    msDescription.append (sString);
}

void DescriptionGenerator::AddLineProperties (void)
{
    AddProperty (OUString::createFromAscii ("LineColor"),
        DescriptionGenerator::COLOR,
        SIP_XA_LINECOLOR);
    AddProperty (OUString::createFromAscii ("LineDashName"),
        DescriptionGenerator::STRING,
        SIP_XA_LINEDASH,
        XATTR_LINEDASH);
    AddProperty (OUString::createFromAscii ("LineWidth"),
        DescriptionGenerator::INTEGER,
        SIP_XA_LINEWIDTH);
}

/** The fill style is described by the property "FillStyle".  Depending on
    its value a hatch-, gradient-, or bitmap name is appended.
*/
void DescriptionGenerator::AddFillProperties (void)
{
    AddProperty (OUString::createFromAscii ("FillStyle"),
        DescriptionGenerator::FILL_STYLE,
        SIP_XA_FILLSTYLE);
}

void DescriptionGenerator::Add3DProperties (void)
{
    AddProperty (OUString::createFromAscii ("D3DMaterialColor"),
        DescriptionGenerator::COLOR,
        RID_SVXSTR_A11Y_3D_MATERIAL_COLOR);
    AddLineProperties ();
    AddFillProperties ();
}

void DescriptionGenerator::AddTextProperties (void)
{
    AddProperty (OUString::createFromAscii ("CharColor"),
        DescriptionGenerator::COLOR);
    AddFillProperties ();
}

/** Search for the given color in the global color table.  If found append
    its name to the description.  Otherwise append its RGB tuple.
*/
void DescriptionGenerator::AddColor (const OUString& sPropertyName,
    const OUString& sLocalizedName)
{
    msDescription.append (sLocalizedName);
    msDescription.append (sal_Unicode('='));

    try
    {

        long nValue(0);
        if (mxSet.is())
        {
            uno::Any aValue = mxSet->getPropertyValue (sPropertyName);
            aValue >>= nValue;
        }

        msDescription.append (DGColorNameLookUp::Instance().LookUpColor (nValue));
    }
    catch (::com::sun::star::beans::UnknownPropertyException)
    {
        msDescription.append (
            OUString::createFromAscii("<unknown>"));
    }
}

void DescriptionGenerator::AddUnknown (const OUString& /*sPropertyName*/,
    const OUString& sLocalizedName)
{
    //        uno::Any aValue = mxSet->getPropertyValue (sPropertyName);
    msDescription.append (sLocalizedName);
}

void DescriptionGenerator::AddInteger (const OUString& sPropertyName,
    const OUString& sLocalizedName)
{
    msDescription.append (sLocalizedName);
    msDescription.append (sal_Unicode('='));

    try
    {
        if (mxSet.is())
        {
            uno::Any aValue = mxSet->getPropertyValue (sPropertyName);
            long nValue = 0;
            aValue >>= nValue;
            msDescription.append (nValue);
        }
    }
    catch (::com::sun::star::beans::UnknownPropertyException)
    {
        msDescription.append (
            OUString::createFromAscii("<unknown>"));
    }
}

void DescriptionGenerator::AddString (const OUString& sPropertyName,
    const OUString& sLocalizedName, long nWhichId)
{
    msDescription.append (sLocalizedName);
    msDescription.append (sal_Unicode('='));

    try
    {
        if (mxSet.is())
        {
            uno::Any aValue = mxSet->getPropertyValue (sPropertyName);
            OUString sValue;
            aValue >>= sValue;

            if (nWhichId >= 0)
            {
                ::vos::OGuard aGuard (::Application::GetSolarMutex());
                String sLocalizedValue;
                SvxUnogetInternalNameForItem (sal::static_int_cast<sal_Int16>(nWhichId),
                                              sValue, sLocalizedValue);
                msDescription.append (sLocalizedValue);
            }
            else
                msDescription.append (sValue);
        }
    }
    catch (::com::sun::star::beans::UnknownPropertyException)
    {
        msDescription.append (
            OUString::createFromAscii("<unknown>"));
    }
}

void DescriptionGenerator::AddFillStyle (const OUString& sPropertyName,
    const OUString& sLocalizedName)
{
    msDescription.append (sLocalizedName);
    msDescription.append (sal_Unicode('='));

    try
    {
        if (mxSet.is())
        {
            uno::Any aValue = mxSet->getPropertyValue (sPropertyName);
            drawing::FillStyle aFillStyle;
            aValue >>= aFillStyle;

            // Get the fill style name from the resource.
            OUString sFillStyleName;
            {
                ::vos::OGuard aGuard (::Application::GetSolarMutex());
                switch (aFillStyle)
                {
                    case drawing::FillStyle_NONE:
                        sFillStyleName = SVX_RESSTR(RID_SVXSTR_A11Y_FILLSTYLE_NONE);
                        break;
                    case drawing::FillStyle_SOLID:
                        sFillStyleName = SVX_RESSTR(RID_SVXSTR_A11Y_FILLSTYLE_SOLID);
                        break;
                    case drawing::FillStyle_GRADIENT:
                        sFillStyleName = SVX_RESSTR(RID_SVXSTR_A11Y_FILLSTYLE_GRADIENT);
                        break;
                    case drawing::FillStyle_HATCH:
                        sFillStyleName = SVX_RESSTR(RID_SVXSTR_A11Y_FILLSTYLE_HATCH);
                        break;
                    case drawing::FillStyle_BITMAP:
                        sFillStyleName = SVX_RESSTR(RID_SVXSTR_A11Y_FILLSTYLE_BITMAP);
                        break;
                    case drawing::FillStyle_MAKE_FIXED_SIZE:
                        break;
                }
            }
            msDescription.append (sFillStyleName);

            // Append the appropriate properties.
            switch (aFillStyle)
            {
                case drawing::FillStyle_NONE:
                    break;
                case drawing::FillStyle_SOLID:
                    AddProperty (OUString::createFromAscii ("FillColor"),
                        COLOR,
                        SIP_XA_FILLCOLOR);
                    break;
                case drawing::FillStyle_GRADIENT:
                    AddProperty (OUString::createFromAscii ("FillGradientName"),
                        STRING,
                        SIP_XA_FILLGRADIENT,
                        XATTR_FILLGRADIENT);
                    break;
                case drawing::FillStyle_HATCH:
                    AddProperty (OUString::createFromAscii ("FillColor"),
                        COLOR,
                        SIP_XA_FILLCOLOR);
                    AddProperty (OUString::createFromAscii ("FillHatchName"),
                        STRING,
                        SIP_XA_FILLHATCH,
                        XATTR_FILLHATCH);
                    break;
                case drawing::FillStyle_BITMAP:
                    AddProperty (OUString::createFromAscii ("FillBitmapName"),
                        STRING,
                        SIP_XA_FILLBITMAP,
                        XATTR_FILLBITMAP);
                    break;
                case drawing::FillStyle_MAKE_FIXED_SIZE:
                    break;
            }
        }
    }
    catch (::com::sun::star::beans::UnknownPropertyException)
    {
        msDescription.append (
            OUString::createFromAscii("<unknown>"));
    }
}

void DescriptionGenerator::AddPropertyNames (void)
{
    if (mxSet.is())
    {
        uno::Reference<beans::XPropertySetInfo> xInfo (mxSet->getPropertySetInfo());
        if (xInfo.is())
        {
            uno::Sequence<beans::Property> aPropertyList (xInfo->getProperties ());
            for (int i=0; i<aPropertyList.getLength(); i++)
            {
                msDescription.append (aPropertyList[i].Name);
                msDescription.append (sal_Unicode(','));
            }
        }
    }
}

} // end of namespace accessibility
<commit_msg>INTEGRATION: CWS changefileheader (1.12.368); FILE MERGED 2008/04/01 15:50:09 thb 1.12.368.3: #i85898# Stripping all external header guards 2008/04/01 12:48:00 thb 1.12.368.2: #i85898# Stripping all external header guards 2008/03/31 14:19:12 rt 1.12.368.1: #i87441# Change license header to LPGL v3.<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: DescriptionGenerator.cxx,v $
 * $Revision: 1.13 $
 *
 * 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_svx.hxx"

#include "DescriptionGenerator.hxx"
#include <com/sun/star/beans/PropertyState.hpp>
#include <com/sun/star/beans/XPropertySet.hpp>
#include <com/sun/star/beans/XPropertyState.hpp>
#include <com/sun/star/container/XChild.hpp>
#include <com/sun/star/container/XNameContainer.hpp>
#include <com/sun/star/container/XNameAccess.hpp>
#include <com/sun/star/container/XNamed.hpp>
#include <com/sun/star/drawing/FillStyle.hpp>
#include <com/sun/star/drawing/XShapes.hpp>
#include <com/sun/star/drawing/XShapeDescriptor.hpp>
#include <com/sun/star/lang/IndexOutOfBoundsException.hpp>
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#include <com/sun/star/style/XStyle.hpp>
#include <comphelper/processfactory.hxx>
#include <vos/mutex.hxx>
#include <vcl/svapp.hxx>

#include <com/sun/star/uno/Exception.hpp>

// Includes for string resources.
#ifndef _SVX_ACCESSIBILITY_HRC
#include "accessibility.hrc"
#endif
#include "svdstr.hrc"
#include <svx/dialmgr.hxx>
#include <tools/string.hxx>

#include <svx/xdef.hxx>
#include "unoapi.hxx"
#include "accessibility.hrc"
#include "DGColorNameLookUp.hxx"

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

void SvxUnogetInternalNameForItem( const sal_Int16 nWhich, const rtl::OUString& rApiName, String& rInternalName ) throw();

namespace accessibility {

DescriptionGenerator::DescriptionGenerator (
    const uno::Reference<drawing::XShape>& xShape)
    : mxShape (xShape),
      mxSet (mxShape, uno::UNO_QUERY),
      mbIsFirstProperty (true)
{
}

DescriptionGenerator::~DescriptionGenerator (void)
{
}

void DescriptionGenerator::Initialize (sal_Int32 nResourceId)
{
    // Get the string from the resource for the specified id.
    OUString sPrefix;
    {
        ::vos::OGuard aGuard (::Application::GetSolarMutex());
        sPrefix = OUString (SVX_RESSTR (nResourceId));
    }

    // Forward the call with the resulting string.
    Initialize (sPrefix);
}

void DescriptionGenerator::Initialize (::rtl::OUString sPrefix)
{
    msDescription = sPrefix;
    if (mxSet.is())
    {
        {
            ::vos::OGuard aGuard (::Application::GetSolarMutex());

            msDescription.append (sal_Unicode (' '));
            msDescription.append (OUString (SVX_RESSTR(RID_SVXSTR_A11Y_WITH)));
            msDescription.append (sal_Unicode (' '));

            msDescription.append (OUString (SVX_RESSTR (RID_SVXSTR_A11Y_STYLE)));
            msDescription.append (sal_Unicode ('='));
        }

        try
        {
            if (mxSet.is())
            {
                uno::Any aValue = mxSet->getPropertyValue (OUString::createFromAscii ("Style"));
                uno::Reference<container::XNamed> xStyle (aValue, uno::UNO_QUERY);
                if (xStyle.is())
                    msDescription.append (xStyle->getName());
            }
            else
                msDescription.append (
                    OUString::createFromAscii("<no style>"));
        }
        catch (::com::sun::star::beans::UnknownPropertyException)
        {
            msDescription.append (
                OUString::createFromAscii("<unknown>"));
        }
    }
}

::rtl::OUString DescriptionGenerator::operator() (void)
{
    msDescription.append (sal_Unicode ('.'));
    return msDescription.makeStringAndClear();
}

void DescriptionGenerator::AddProperty (
    const OUString& sPropertyName,
    PropertyType aType,
    const sal_Int32 nLocalizedNameId,
    long nWhichId)
{
    OUString sLocalizedName;
    {
        ::vos::OGuard aGuard (::Application::GetSolarMutex());
        sLocalizedName = SVX_RESSTR (nLocalizedNameId);
    }
    AddProperty (sPropertyName, aType, sLocalizedName, nWhichId);
}

void DescriptionGenerator::AddProperty (const OUString& sPropertyName,
    PropertyType aType, const OUString& sLocalizedName, long nWhichId)
{
    uno::Reference<beans::XPropertyState> xState (mxShape, uno::UNO_QUERY);
    if (xState.is()
        && xState->getPropertyState(sPropertyName)!=beans::PropertyState_DEFAULT_VALUE)
        if (mxSet.is())
        {
            // Append a seperator from previous Properties.
            if ( ! mbIsFirstProperty)
                msDescription.append (sal_Unicode (','));
            else
            {
                ::vos::OGuard aGuard (::Application::GetSolarMutex());

                msDescription.append (sal_Unicode (' '));
                msDescription.append (OUString (SVX_RESSTR(RID_SVXSTR_A11Y_AND)));
                msDescription.append (sal_Unicode (' '));
                mbIsFirstProperty = false;
            }

            // Delegate to type specific property handling.
            switch (aType)
            {
                case COLOR:
                    AddColor (sPropertyName, sLocalizedName);
                    break;
                case INTEGER:
                    AddInteger (sPropertyName, sLocalizedName);
                    break;
                case STRING:
                    AddString (sPropertyName, sLocalizedName, nWhichId);
                    break;
                case FILL_STYLE:
                    AddFillStyle (sPropertyName, sLocalizedName);
                    break;
            }
        }
}

void DescriptionGenerator::AppendString (const ::rtl::OUString& sString)
{
    msDescription.append (sString);
}

void DescriptionGenerator::AddLineProperties (void)
{
    AddProperty (OUString::createFromAscii ("LineColor"),
        DescriptionGenerator::COLOR,
        SIP_XA_LINECOLOR);
    AddProperty (OUString::createFromAscii ("LineDashName"),
        DescriptionGenerator::STRING,
        SIP_XA_LINEDASH,
        XATTR_LINEDASH);
    AddProperty (OUString::createFromAscii ("LineWidth"),
        DescriptionGenerator::INTEGER,
        SIP_XA_LINEWIDTH);
}

/** The fill style is described by the property "FillStyle".  Depending on
    its value a hatch-, gradient-, or bitmap name is appended.
*/
void DescriptionGenerator::AddFillProperties (void)
{
    AddProperty (OUString::createFromAscii ("FillStyle"),
        DescriptionGenerator::FILL_STYLE,
        SIP_XA_FILLSTYLE);
}

void DescriptionGenerator::Add3DProperties (void)
{
    AddProperty (OUString::createFromAscii ("D3DMaterialColor"),
        DescriptionGenerator::COLOR,
        RID_SVXSTR_A11Y_3D_MATERIAL_COLOR);
    AddLineProperties ();
    AddFillProperties ();
}

void DescriptionGenerator::AddTextProperties (void)
{
    AddProperty (OUString::createFromAscii ("CharColor"),
        DescriptionGenerator::COLOR);
    AddFillProperties ();
}

/** Search for the given color in the global color table.  If found append
    its name to the description.  Otherwise append its RGB tuple.
*/
void DescriptionGenerator::AddColor (const OUString& sPropertyName,
    const OUString& sLocalizedName)
{
    msDescription.append (sLocalizedName);
    msDescription.append (sal_Unicode('='));

    try
    {

        long nValue(0);
        if (mxSet.is())
        {
            uno::Any aValue = mxSet->getPropertyValue (sPropertyName);
            aValue >>= nValue;
        }

        msDescription.append (DGColorNameLookUp::Instance().LookUpColor (nValue));
    }
    catch (::com::sun::star::beans::UnknownPropertyException)
    {
        msDescription.append (
            OUString::createFromAscii("<unknown>"));
    }
}

void DescriptionGenerator::AddUnknown (const OUString& /*sPropertyName*/,
    const OUString& sLocalizedName)
{
    //        uno::Any aValue = mxSet->getPropertyValue (sPropertyName);
    msDescription.append (sLocalizedName);
}

void DescriptionGenerator::AddInteger (const OUString& sPropertyName,
    const OUString& sLocalizedName)
{
    msDescription.append (sLocalizedName);
    msDescription.append (sal_Unicode('='));

    try
    {
        if (mxSet.is())
        {
            uno::Any aValue = mxSet->getPropertyValue (sPropertyName);
            long nValue = 0;
            aValue >>= nValue;
            msDescription.append (nValue);
        }
    }
    catch (::com::sun::star::beans::UnknownPropertyException)
    {
        msDescription.append (
            OUString::createFromAscii("<unknown>"));
    }
}

void DescriptionGenerator::AddString (const OUString& sPropertyName,
    const OUString& sLocalizedName, long nWhichId)
{
    msDescription.append (sLocalizedName);
    msDescription.append (sal_Unicode('='));

    try
    {
        if (mxSet.is())
        {
            uno::Any aValue = mxSet->getPropertyValue (sPropertyName);
            OUString sValue;
            aValue >>= sValue;

            if (nWhichId >= 0)
            {
                ::vos::OGuard aGuard (::Application::GetSolarMutex());
                String sLocalizedValue;
                SvxUnogetInternalNameForItem (sal::static_int_cast<sal_Int16>(nWhichId),
                                              sValue, sLocalizedValue);
                msDescription.append (sLocalizedValue);
            }
            else
                msDescription.append (sValue);
        }
    }
    catch (::com::sun::star::beans::UnknownPropertyException)
    {
        msDescription.append (
            OUString::createFromAscii("<unknown>"));
    }
}

void DescriptionGenerator::AddFillStyle (const OUString& sPropertyName,
    const OUString& sLocalizedName)
{
    msDescription.append (sLocalizedName);
    msDescription.append (sal_Unicode('='));

    try
    {
        if (mxSet.is())
        {
            uno::Any aValue = mxSet->getPropertyValue (sPropertyName);
            drawing::FillStyle aFillStyle;
            aValue >>= aFillStyle;

            // Get the fill style name from the resource.
            OUString sFillStyleName;
            {
                ::vos::OGuard aGuard (::Application::GetSolarMutex());
                switch (aFillStyle)
                {
                    case drawing::FillStyle_NONE:
                        sFillStyleName = SVX_RESSTR(RID_SVXSTR_A11Y_FILLSTYLE_NONE);
                        break;
                    case drawing::FillStyle_SOLID:
                        sFillStyleName = SVX_RESSTR(RID_SVXSTR_A11Y_FILLSTYLE_SOLID);
                        break;
                    case drawing::FillStyle_GRADIENT:
                        sFillStyleName = SVX_RESSTR(RID_SVXSTR_A11Y_FILLSTYLE_GRADIENT);
                        break;
                    case drawing::FillStyle_HATCH:
                        sFillStyleName = SVX_RESSTR(RID_SVXSTR_A11Y_FILLSTYLE_HATCH);
                        break;
                    case drawing::FillStyle_BITMAP:
                        sFillStyleName = SVX_RESSTR(RID_SVXSTR_A11Y_FILLSTYLE_BITMAP);
                        break;
                    case drawing::FillStyle_MAKE_FIXED_SIZE:
                        break;
                }
            }
            msDescription.append (sFillStyleName);

            // Append the appropriate properties.
            switch (aFillStyle)
            {
                case drawing::FillStyle_NONE:
                    break;
                case drawing::FillStyle_SOLID:
                    AddProperty (OUString::createFromAscii ("FillColor"),
                        COLOR,
                        SIP_XA_FILLCOLOR);
                    break;
                case drawing::FillStyle_GRADIENT:
                    AddProperty (OUString::createFromAscii ("FillGradientName"),
                        STRING,
                        SIP_XA_FILLGRADIENT,
                        XATTR_FILLGRADIENT);
                    break;
                case drawing::FillStyle_HATCH:
                    AddProperty (OUString::createFromAscii ("FillColor"),
                        COLOR,
                        SIP_XA_FILLCOLOR);
                    AddProperty (OUString::createFromAscii ("FillHatchName"),
                        STRING,
                        SIP_XA_FILLHATCH,
                        XATTR_FILLHATCH);
                    break;
                case drawing::FillStyle_BITMAP:
                    AddProperty (OUString::createFromAscii ("FillBitmapName"),
                        STRING,
                        SIP_XA_FILLBITMAP,
                        XATTR_FILLBITMAP);
                    break;
                case drawing::FillStyle_MAKE_FIXED_SIZE:
                    break;
            }
        }
    }
    catch (::com::sun::star::beans::UnknownPropertyException)
    {
        msDescription.append (
            OUString::createFromAscii("<unknown>"));
    }
}

void DescriptionGenerator::AddPropertyNames (void)
{
    if (mxSet.is())
    {
        uno::Reference<beans::XPropertySetInfo> xInfo (mxSet->getPropertySetInfo());
        if (xInfo.is())
        {
            uno::Sequence<beans::Property> aPropertyList (xInfo->getProperties ());
            for (int i=0; i<aPropertyList.getLength(); i++)
            {
                msDescription.append (aPropertyList[i].Name);
                msDescription.append (sal_Unicode(','));
            }
        }
    }
}

} // end of namespace accessibility
<|endoftext|>


<commit_before>// @(#)root/thread:$Id$
// Author: Xavier Valls March 2016

/*************************************************************************
 * Copyright (C) 1995-2006, Rene Brun and Fons Rademakers.               *
 * All rights reserved.                                                  *
 *                                                                       *
 * For the licensing terms see $ROOTSYS/LICENSE.                         *
 * For the list of contributors see $ROOTSYS/README/CREDITS.             *
 *************************************************************************/

#ifndef ROOT_TExecutor
#define ROOT_TExecutor

#include "ROOT/TSeq.hxx"
#include "TList.h"
#include <vector>

namespace ROOT {

template<class subc>
class TExecutor {
public:
   explicit TExecutor() = default;
   explicit TExecutor(size_t /* nThreads */ ){};

   template< class F, class... T>
   using noReferenceCond = typename std::enable_if<"Function can't return a reference" && !(std::is_reference<typename std::result_of<F(T...)>::type>::value)>::type;

   // // Map
   // //these late return types allow for a compile-time check of compatibility between function signatures and args,
   // //and a compile-time check that the argument list implements a front() method (all STL sequence containers have it)
   template<class F, class Cond = noReferenceCond<F>>
   auto Map(F func, unsigned nTimes) -> std::vector<typename std::result_of<F()>::type>;
   // /// \cond doxygen should ignore these methods
   template<class F, class INTEGER, class Cond = noReferenceCond<F, INTEGER>>
   auto Map(F func, ROOT::TSeq<INTEGER> args) -> std::vector<typename std::result_of<F(INTEGER)>::type>;
   template<class F, class T, class Cond = noReferenceCond<F, T>>
   auto Map(F func, std::initializer_list<T> args) -> std::vector<typename std::result_of<F(T)>::type>;
   template<class F, class T, class Cond = noReferenceCond<F, T>>
   auto Map(F func, std::vector<T> &args) -> std::vector<typename std::result_of<F(T)>::type>;
   // // // / \endcond

   // // MapReduce
   // // the late return types also check at compile-time whether redfunc is compatible with func,
   // // other than checking that func is compatible with the type of arguments.
   // // a static_assert check in TExecutor<subc>::Reduce is used to check that redfunc is compatible with the type returned by func
   template<class F, class R, class Cond = noReferenceCond<F>>
   auto MapReduce(F func, unsigned nTimes, R redfunc) -> typename std::result_of<F()>::type;
   template<class F, class INTEGER, class R, class Cond = noReferenceCond<F, INTEGER>>
   auto MapReduce(F func, ROOT::TSeq<INTEGER> args, R redfunc) -> typename std::result_of<F(INTEGER)>::type;
   // /// \cond doxygen should ignore these methods
   template<class F, class T, class R, class Cond = noReferenceCond<F, T>>
   auto MapReduce(F func, std::initializer_list<T> args, R redfunc) -> typename std::result_of<F(T)>::type;
   template<class F, class T, class R, class Cond = noReferenceCond<F, T>>
   auto MapReduce(F func, std::vector<T> &args, R redfunc) -> typename std::result_of<F(T)>::type;
   template<class F, class T, class Cond = noReferenceCond<F, T>>
   T* MapReduce(F func, std::vector<T*> &args);
   // /// \endcond

   template<class T, class R> T Reduce(const std::vector<T> &objs, R redfunc);
   template<class T> T* Reduce(const std::vector<T*> &mergeObjs);

private:
  inline subc & Derived()
  {
    return *static_cast<subc*>(this);
  }
};

//////////////////////////////////////////////////////////////////////////
/// Execute func (with no arguments) nTimes in parallel.
/// A vector containg executions' results is returned.
/// Functions that take more than zero arguments can be executed (with
/// fixed arguments) by wrapping them in a lambda or with std::bind.
template<class subc> template<class F, class Cond>
auto TExecutor<subc>::Map(F func, unsigned nTimes) -> std::vector<typename std::result_of<F()>::type>
{
   return Derived().Map(func, nTimes);
}

// //////////////////////////////////////////////////////////////////////////
// /// Execute func in parallel distributing the elements of the args collection between the workers.
// /// See class description for the valid types of collections and containers that can be used.
// /// A vector containing each execution's result is returned. The user is responsible of deleting
// /// objects that might be created upon the execution of func, returned objects included.
// /// **Note:** the collection of arguments is modified by Map and should be considered empty or otherwise
// /// invalidated after Map's execution (std::move might be applied to it).

// tell doxygen to ignore this (\endcond closes the statement)
/// \cond
template<class subc> template<class F, class INTEGER, class Cond>
auto TExecutor<subc>::Map(F func, ROOT::TSeq<INTEGER> args) -> std::vector<typename std::result_of<F(INTEGER)>::type>
{
  return Derived().Map(func, args);
}

template<class subc> template<class F, class T, class Cond>
auto TExecutor<subc>::Map(F func, std::initializer_list<T> args) -> std::vector<typename std::result_of<F(T)>::type>
{
   std::vector<T> vargs(std::move(args));
   const auto &reslist = Map(func, vargs);
   return reslist;
}

// actual implementation of the Map method. all other calls with arguments eventually
// call this one

template<class subc> template<class F, class T, class Cond>
auto TExecutor<subc>::Map(F func, std::vector<T> &args) -> std::vector<typename std::result_of<F(T)>::type>
{
   return Derived().Map(func, args);
}

// //////////////////////////////////////////////////////////////////////////
// /// This method behaves just like Map, but an additional redfunc function
// /// must be provided. redfunc is applied to the vector Map would return and
// /// must return the same type as func. In practice, redfunc can be used to
// /// "squash" the vector returned by Map into a single object by merging,
// /// adding, mixing the elements of the vector.
template<class subc> template<class F, class R, class Cond>
auto TExecutor<subc>::MapReduce(F func, unsigned nTimes, R redfunc) -> typename std::result_of<F()>::type
{
   return Reduce(Map(func, nTimes), redfunc);
}

//////////////////////////////////////////////////////////////////////////
/// This method behaves just like Map, but an additional redfunc function
/// must be provided. redfunc is applied to the vector Map would return and
/// must return the same type as func. In practice, redfunc can be used to
/// "squash" the vector returned by Map into a single object by merging,
/// adding, mixing the elements of the vector.

/// \cond doxygen should ignore these methods
template<class subc> template<class F, class INTEGER, class R, class Cond>
auto TExecutor<subc>::MapReduce(F func, ROOT::TSeq<INTEGER> args, R redfunc) -> typename std::result_of<F(INTEGER)>::type
{
  return Reduce(Map(func, args), redfunc);
}

template<class subc> template<class F, class T, class R, class Cond>
auto TExecutor<subc>::MapReduce(F func, std::initializer_list<T> args, R redfunc) -> typename std::result_of<F(T)>::type
{
   return Reduce(Map(func, args), redfunc);
}

template<class subc> template<class F, class T, class R, class Cond>
auto TExecutor<subc>::MapReduce(F func, std::vector<T> &args, R redfunc) -> typename std::result_of<F(T)>::type
{
   return Reduce(Map(func, args), redfunc);
}

template<class subc> template<class F, class T, class Cond>
T* TExecutor<subc>::MapReduce(F func, std::vector<T*> &args)
{
   return Reduce(Map(func, args));
}

/// \endcond

/// Check that redfunc has the right signature and call it on objs
template<class subc> template<class T, class R>
T TExecutor<subc>::Reduce(const std::vector<T> &objs, R redfunc)
{
  return Derived().Reduce(objs, redfunc);
}

//Reduction for objects with the Merge() method
template<class subc> template<class T>
T* TExecutor<subc>::Reduce(const std::vector<T*> &mergeObjs)
{
  TList *l = new TList();
  for(unsigned i =1; i<mergeObjs.size(); i++){
    l->Add(mergeObjs[i]);
  }
  auto retHist = mergeObjs.front();
  retHist->Merge(l);
  return retHist;
}

} // end namespace ROOT

#endif
<commit_msg>Fix TList constructor and returned a new copy of the merged histogram<commit_after>// @(#)root/thread:$Id$
// Author: Xavier Valls March 2016

/*************************************************************************
 * Copyright (C) 1995-2006, Rene Brun and Fons Rademakers.               *
 * All rights reserved.                                                  *
 *                                                                       *
 * For the licensing terms see $ROOTSYS/LICENSE.                         *
 * For the list of contributors see $ROOTSYS/README/CREDITS.             *
 *************************************************************************/

#ifndef ROOT_TExecutor
#define ROOT_TExecutor

#include "ROOT/TSeq.hxx"
#include "TList.h"
#include <vector>

namespace ROOT {

template<class subc>
class TExecutor {
public:
   explicit TExecutor() = default;
   explicit TExecutor(size_t /* nThreads */ ){};

   template< class F, class... T>
   using noReferenceCond = typename std::enable_if<"Function can't return a reference" && !(std::is_reference<typename std::result_of<F(T...)>::type>::value)>::type;

   // // Map
   // //these late return types allow for a compile-time check of compatibility between function signatures and args,
   // //and a compile-time check that the argument list implements a front() method (all STL sequence containers have it)
   template<class F, class Cond = noReferenceCond<F>>
   auto Map(F func, unsigned nTimes) -> std::vector<typename std::result_of<F()>::type>;
   // /// \cond doxygen should ignore these methods
   template<class F, class INTEGER, class Cond = noReferenceCond<F, INTEGER>>
   auto Map(F func, ROOT::TSeq<INTEGER> args) -> std::vector<typename std::result_of<F(INTEGER)>::type>;
   template<class F, class T, class Cond = noReferenceCond<F, T>>
   auto Map(F func, std::initializer_list<T> args) -> std::vector<typename std::result_of<F(T)>::type>;
   template<class F, class T, class Cond = noReferenceCond<F, T>>
   auto Map(F func, std::vector<T> &args) -> std::vector<typename std::result_of<F(T)>::type>;
   // // // / \endcond

   // // MapReduce
   // // the late return types also check at compile-time whether redfunc is compatible with func,
   // // other than checking that func is compatible with the type of arguments.
   // // a static_assert check in TExecutor<subc>::Reduce is used to check that redfunc is compatible with the type returned by func
   template<class F, class R, class Cond = noReferenceCond<F>>
   auto MapReduce(F func, unsigned nTimes, R redfunc) -> typename std::result_of<F()>::type;
   template<class F, class INTEGER, class R, class Cond = noReferenceCond<F, INTEGER>>
   auto MapReduce(F func, ROOT::TSeq<INTEGER> args, R redfunc) -> typename std::result_of<F(INTEGER)>::type;
   // /// \cond doxygen should ignore these methods
   template<class F, class T, class R, class Cond = noReferenceCond<F, T>>
   auto MapReduce(F func, std::initializer_list<T> args, R redfunc) -> typename std::result_of<F(T)>::type;
   template<class F, class T, class R, class Cond = noReferenceCond<F, T>>
   auto MapReduce(F func, std::vector<T> &args, R redfunc) -> typename std::result_of<F(T)>::type;
   template<class F, class T, class Cond = noReferenceCond<F, T>>
   T* MapReduce(F func, std::vector<T*> &args);
   // /// \endcond

   template<class T, class R> T Reduce(const std::vector<T> &objs, R redfunc);
   template<class T> T* Reduce(const std::vector<T*> &mergeObjs);

private:
  inline subc & Derived()
  {
    return *static_cast<subc*>(this);
  }
};

//////////////////////////////////////////////////////////////////////////
/// Execute func (with no arguments) nTimes in parallel.
/// A vector containg executions' results is returned.
/// Functions that take more than zero arguments can be executed (with
/// fixed arguments) by wrapping them in a lambda or with std::bind.
template<class subc> template<class F, class Cond>
auto TExecutor<subc>::Map(F func, unsigned nTimes) -> std::vector<typename std::result_of<F()>::type>
{
   return Derived().Map(func, nTimes);
}

// //////////////////////////////////////////////////////////////////////////
// /// Execute func in parallel distributing the elements of the args collection between the workers.
// /// See class description for the valid types of collections and containers that can be used.
// /// A vector containing each execution's result is returned. The user is responsible of deleting
// /// objects that might be created upon the execution of func, returned objects included.
// /// **Note:** the collection of arguments is modified by Map and should be considered empty or otherwise
// /// invalidated after Map's execution (std::move might be applied to it).

// tell doxygen to ignore this (\endcond closes the statement)
/// \cond
template<class subc> template<class F, class INTEGER, class Cond>
auto TExecutor<subc>::Map(F func, ROOT::TSeq<INTEGER> args) -> std::vector<typename std::result_of<F(INTEGER)>::type>
{
  return Derived().Map(func, args);
}

template<class subc> template<class F, class T, class Cond>
auto TExecutor<subc>::Map(F func, std::initializer_list<T> args) -> std::vector<typename std::result_of<F(T)>::type>
{
   std::vector<T> vargs(std::move(args));
   const auto &reslist = Map(func, vargs);
   return reslist;
}

// actual implementation of the Map method. all other calls with arguments eventually
// call this one

template<class subc> template<class F, class T, class Cond>
auto TExecutor<subc>::Map(F func, std::vector<T> &args) -> std::vector<typename std::result_of<F(T)>::type>
{
   return Derived().Map(func, args);
}

// //////////////////////////////////////////////////////////////////////////
// /// This method behaves just like Map, but an additional redfunc function
// /// must be provided. redfunc is applied to the vector Map would return and
// /// must return the same type as func. In practice, redfunc can be used to
// /// "squash" the vector returned by Map into a single object by merging,
// /// adding, mixing the elements of the vector.
template<class subc> template<class F, class R, class Cond>
auto TExecutor<subc>::MapReduce(F func, unsigned nTimes, R redfunc) -> typename std::result_of<F()>::type
{
   return Reduce(Map(func, nTimes), redfunc);
}

//////////////////////////////////////////////////////////////////////////
/// This method behaves just like Map, but an additional redfunc function
/// must be provided. redfunc is applied to the vector Map would return and
/// must return the same type as func. In practice, redfunc can be used to
/// "squash" the vector returned by Map into a single object by merging,
/// adding, mixing the elements of the vector.

/// \cond doxygen should ignore these methods
template<class subc> template<class F, class INTEGER, class R, class Cond>
auto TExecutor<subc>::MapReduce(F func, ROOT::TSeq<INTEGER> args, R redfunc) -> typename std::result_of<F(INTEGER)>::type
{
  return Reduce(Map(func, args), redfunc);
}

template<class subc> template<class F, class T, class R, class Cond>
auto TExecutor<subc>::MapReduce(F func, std::initializer_list<T> args, R redfunc) -> typename std::result_of<F(T)>::type
{
   return Reduce(Map(func, args), redfunc);
}

template<class subc> template<class F, class T, class R, class Cond>
auto TExecutor<subc>::MapReduce(F func, std::vector<T> &args, R redfunc) -> typename std::result_of<F(T)>::type
{
   return Reduce(Map(func, args), redfunc);
}

template<class subc> template<class F, class T, class Cond>
T* TExecutor<subc>::MapReduce(F func, std::vector<T*> &args)
{
   return Reduce(Map(func, args));
}

/// \endcond

/// Check that redfunc has the right signature and call it on objs
template<class subc> template<class T, class R>
T TExecutor<subc>::Reduce(const std::vector<T> &objs, R redfunc)
{
  return Derived().Reduce(objs, redfunc);
}

//Reduction for objects with the Merge() method
template<class subc> template<class T>
T* TExecutor<subc>::Reduce(const std::vector<T*> &mergeObjs)
{
   TList l;
  for(unsigned i =1; i<mergeObjs.size(); i++){
    l.Add(mergeObjs[i]);
  }
  // use clone to return a new object
  auto retHist = (mergeObjs.front())->Clone();
  retHist->Merge(&l);
  return retHist;
}

} // end namespace ROOT

#endif
<|endoftext|>


<commit_before><commit_msg>Add check for error to ask query api test<commit_after><|endoftext|>


<commit_before>#include <cstdio>  // for sprintf
#include <cstring> // for strcmp

#include <sampgdk/a_players.h>
#include <sampgdk/a_samp.h>
#include <sampgdk/core.h>
#include <sampgdk/plugin.h>

static ThisPlugin helloworld;

static void SAMPGDK_TIMER_CALL RepeatingTimer(int, void *) {
  ServerLog::Printf("RepeatingTimer");
}

PLUGIN_EXPORT bool PLUGIN_CALL OnGameModeInit() {
  SetGameModeText("Hello, World!");

  AddPlayerClass(0, 1958.3783f, 1343.1572f, 15.3746f, 269.1425f, 0, 0, 0, 0, 0, 0);

  ServerLog::Printf("------------------------------------------\n");
  ServerLog::Printf("      HelloWorld gamemode got loaded.     \n");
  ServerLog::Printf("------------------------------------------\n");

  SetTimer(1000, true, RepeatingTimer, 0);

  return true;
}

PLUGIN_EXPORT bool PLUGIN_CALL OnPlayerConnect(int playerid) {
  SendClientMessage(playerid, 0xFFFFFFFF, "Welcome to the HelloWorld server!");
  return true;
}

PLUGIN_EXPORT bool PLUGIN_CALL OnPlayerRequestClass(int playerid, int classid) {
  SetPlayerPos(playerid, 1958.3783f, 1343.1572f, 15.3746f);
  SetPlayerCameraPos(playerid, 1958.3783f, 1343.1572f, 15.3746f);
  SetPlayerCameraLookAt(playerid, 1958.3783f, 1343.1572f, 15.3746f, CAMERA_CUT);
  return true;
}

PLUGIN_EXPORT bool PLUGIN_CALL OnPlayerCommandText(int playerid, const char *cmdtext) {
  if (std::strcmp(cmdtext, "/hello") == 0) {
    char name[MAX_PLAYER_NAME];
    GetPlayerName(playerid, name);

    char message[128];
    std::sprintf(message, "Hello, %s!", name);

    SendClientMessage(playerid, 0x00FF00FF, message);
    return true;
  }

  if (std::strcmp(cmdtext, "/pos") == 0) {
    float x, y, z;
    GetPlayerPos(playerid, &x, &y, &z);

    char message[128];
    std::sprintf(message, "You are at (%f, %f, %f)", x, y, z);

    SendClientMessage(playerid, 0xFFFFFFFF, message);
    return true;
  }

  return false;
}

PLUGIN_EXPORT unsigned int PLUGIN_CALL Supports() {
  return SUPPORTS_VERSION | SUPPORTS_PROCESS_TICK;
}

PLUGIN_EXPORT bool PLUGIN_CALL Load(void **ppData) {
  return helloworld.Load(ppData) >= 0;
}

PLUGIN_EXPORT void PLUGIN_CALL Unload() {
  helloworld.Unload();
}

PLUGIN_EXPORT void PLUGIN_CALL ProcessTick() {
  helloworld.ProcessTimers();
}
<commit_msg>Slightly simplify helloworld code<commit_after>#include <cstdio>
#include <cstring>
#include <sampgdk/a_players.h>
#include <sampgdk/a_samp.h>
#include <sampgdk/core.h>
#include <sampgdk/plugin.h>

static ThisPlugin helloworld;

static void SAMPGDK_TIMER_CALL RepeatingTimer(int, void *) {
  ServerLog::Printf("RepeatingTimer");
}

PLUGIN_EXPORT bool PLUGIN_CALL OnGameModeInit() {
  SetGameModeText("Hello, World!");
  AddPlayerClass(0, 1958.3783f, 1343.1572f, 15.3746f, 269.1425f, 0, 0, 0, 0, 0, 0);
  SetTimer(1000, true, RepeatingTimer, 0);
  return true;
}

PLUGIN_EXPORT bool PLUGIN_CALL OnPlayerConnect(int playerid) {
  SendClientMessage(playerid, 0xFFFFFFFF, "Welcome to the HelloWorld server!");
  return true;
}

PLUGIN_EXPORT bool PLUGIN_CALL OnPlayerRequestClass(int playerid, int classid) {
  SetPlayerPos(playerid, 1958.3783f, 1343.1572f, 15.3746f);
  SetPlayerCameraPos(playerid, 1958.3783f, 1343.1572f, 15.3746f);
  SetPlayerCameraLookAt(playerid, 1958.3783f, 1343.1572f, 15.3746f, CAMERA_CUT);
  return true;
}

PLUGIN_EXPORT bool PLUGIN_CALL OnPlayerCommandText(int playerid, const char *cmdtext) {
  if (std::strcmp(cmdtext, "/hello") == 0) {
    char name[MAX_PLAYER_NAME];
    GetPlayerName(playerid, name);
    char message[128];
    std::sprintf(message, "Hello, %s!", name);
    SendClientMessage(playerid, 0x00FF00FF, message);
    return true;
  }
  return false;
}

PLUGIN_EXPORT unsigned int PLUGIN_CALL Supports() {
  return SUPPORTS_VERSION | SUPPORTS_PROCESS_TICK;
}

PLUGIN_EXPORT bool PLUGIN_CALL Load(void **ppData) {
  return helloworld.Load(ppData) >= 0;
}

PLUGIN_EXPORT void PLUGIN_CALL Unload() {
  helloworld.Unload();
}

PLUGIN_EXPORT void PLUGIN_CALL ProcessTick() {
  helloworld.ProcessTimers();
}
<|endoftext|>


<commit_before>/*******************************************************
 * Copyright (c) 2014, ArrayFire
 * All rights reserved.
 *
 * This file is distributed under 3-clause BSD license.
 * The complete license agreement can be obtained at:
 * http://arrayfire.com/licenses/BSD-3-Clause
 ********************************************************/

#include <arrayfire.h>
#include <climits>
#include <cstring>
#include <cstdio>

using namespace af;
static const float DefaultTopFittest = 0.5;

array update(const array& searchSpace, const array& sampleX, const array& sampleY, const int n)
{
    return searchSpace(sampleY*n + sampleX);
}

array selectFittest(const array& sampleZ, const int nSamples,
        const float topFit = DefaultTopFittest)
{
    //pick top fittest
    array indices, values;
    sort(values, indices, sampleZ);
    int topFitElem = topFit*nSamples;
    int n = indices.elements();
    return (n > topFitElem) ? indices(seq(n - topFitElem, n-1)) : indices;
}

void reproduce(array& searchSpace, array& sampleX, array& sampleY, array& sampleZ, const int nSamples, const int n)
{
    //Get fittest parents
    array selection = selectFittest(sampleZ, nSamples);
    array parentsX = sampleX(selection);
    array parentsY = sampleY(selection);
    int bits = (int)log2(n);

    //Divide selection in two
    array parentsX1 = parentsX.rows(0, parentsX.elements() / 2 - 1);
    array parentsX2 = parentsX.rows(parentsX.elements() / 2, parentsX.elements() - 1);
    array parentsY1 = parentsY.rows(0, parentsY.elements() / 2 - 1);
    array parentsY2 = parentsY.rows(parentsY.elements() / 2, parentsY.elements() - 1);

    //Get crossover points (at which bit to crossover) and construct bit masks from them
    array crossover = randu(nSamples / 4, u32) % bits;
    array lowermask = (1 << crossover) - 1;
    array uppermask = INT_MAX - lowermask;

    //Create children as the cross between two parents
    array childrenX1 = (parentsX1 & uppermask) + (parentsX2 & lowermask);
    array childrenY1 = (parentsY1 & uppermask) + (parentsY2 & lowermask);

    array childrenX2 = (parentsX2 & uppermask) + (parentsX1 & lowermask);
    array childrenY2 = (parentsY2 & uppermask) + (parentsY1 & lowermask);

    //Join two new sets
    sampleX = join(0, childrenX1, childrenX2);
    sampleY = join(0, childrenY1, childrenY2);

    //Create mutant children
    array mutantX = sampleX;
    array mutantY = sampleY;

    //Flip a random bit to vary the gene pool
    mutantX = mutantX ^ (1 << (randu(nSamples / 2, u32) % bits));
    mutantY = mutantY ^ (1 << (randu(nSamples / 2, u32) % bits));

    sampleX = join(0, sampleX, mutantX);
    sampleY = join(0, sampleY, mutantY);

    //Update the value of each sample with the new coordinates
    sampleZ = update(searchSpace, sampleX, sampleY, n);
}

void initSamples(array& searchSpace, array& sampleX, array& sampleY, array& sampleZ, const int nSamples, const int n)
{
    setSeed(time(NULL));
    sampleX = randu(nSamples, u32) % n;
    sampleY = randu(nSamples, u32) % n;
    sampleZ = update(searchSpace, sampleX, sampleY, n);
}

void init(array& searchSpace, array& searchSpaceXDisplay, array& searchSpaceYDisplay, array& sampleX, array& sampleY, array& sampleZ, const int nSamples, const int n)
{
    //initialize space
    searchSpace = range(dim4(n/2, n/2), 0) + range(dim4(n/2, n/2), 1);
    searchSpace = join(0, searchSpace, flip(searchSpace, 0));
    searchSpace = join(1, searchSpace, flip(searchSpace, 1));

    //initialize display data
    searchSpaceXDisplay = iota(dim4(n, 1), dim4(1, n));
    searchSpaceYDisplay = iota(dim4(1, n), dim4(n, 1));

    //initalize searchers
    initSamples(searchSpace, sampleX, sampleY, sampleZ, nSamples, n);
}

void reproducePrint(float& currentMax,
        array& searchSpace, array& sampleX, array& sampleY, array& sampleZ,
        const float trueMax, const int nSamples, const int n)
{
    if (currentMax < trueMax * 0.99) {
        float maximum = max<float>(sampleZ);
        array whereM = where(sampleZ == maximum);
        if (maximum < trueMax * 0.99) {
            printf("Current max at ");
        } else {
            printf("\nMax found at ");
        }
        printf("(%d,%d): %f (trueMax %f)\n",
                sampleX(whereM).scalar<unsigned int>(),
                sampleY(whereM).scalar<unsigned int>(), maximum, trueMax);
        currentMax = maximum;
        reproduce(searchSpace, sampleX, sampleY, sampleZ, nSamples, n);
    }
}

void geneticSearch(bool console, const int nSamples, const int n)
{
    array searchSpaceXDisplay = 0;
    array searchSpaceYDisplay = 0;
    array searchSpace;
    array sampleX;
    array sampleY;
    array sampleZ;

    init(searchSpace, searchSpaceXDisplay, searchSpaceYDisplay,
            sampleX, sampleY, sampleZ, nSamples, n);
    float trueMax = max<float>(searchSpace);
    float maximum = -trueMax;

    if (!console) {
        af::Window win(1600, 800, "Arrayfire Genetic Algorithm Search Demo");
        win.grid(1, 2);
        do {
            reproducePrint(maximum, searchSpace, sampleX, sampleY, sampleZ,
                    trueMax, nSamples, n);
            win(0,0).setAxesTitles("IdX", "IdY", "Search Space");
            win(0,1).setAxesTitles("IdX", "IdY", "Search Space");
            win(0,0).surface(searchSpaceXDisplay, searchSpaceYDisplay, searchSpace);
            win(0,1).scatter(sampleX.as(f32), sampleY.as(f32), sampleZ.as(f32), AF_MARKER_CIRCLE);
            win.show();
        } while (!win.close());
    } else {
        do {
            reproducePrint(maximum, searchSpace, sampleX, sampleY, sampleZ,
                    trueMax, nSamples, n);
        } while (maximum < trueMax * 0.99);
    }
}

int main(int argc, char** argv)
{
    bool console = false;
    const int n = 32;
    const int nSamples = 16;
    if (argc > 2 || (argc == 2 && strcmp(argv[1], "-"))) {
        printf("usage: %s [-]\n", argv[0]);
        return -1;
    } else if (argc == 2 && argv[1][0] == '-') {
        console = true;
    }

    try {
        af::info();
        printf("** ArrayFire Genetic Algorithm Search Demo **\n\n");
        printf("Search for trueMax in a search space where the objective function is defined as :\n\n");
        printf("SS(x ,y) = min(x, n - (x + 1)) + min(y, n - (y + 1))\n\n");
        printf("(x, y) belongs to RxR; R = [0, n); n = %d\n\n", n);
        if (!console) {
            printf("The left figure shows the objective function.\n");
            printf("The figure on the right shows current generation's parameters and function values.\n\n");
        }
        geneticSearch(console, nSamples, n);
    } catch (af::exception& e) {
        fprintf(stderr, "%s\n", e.what());
    }

    return 0;
}
<commit_msg>Added ctime header file<commit_after>/*******************************************************
 * Copyright (c) 2014, ArrayFire
 * All rights reserved.
 *
 * This file is distributed under 3-clause BSD license.
 * The complete license agreement can be obtained at:
 * http://arrayfire.com/licenses/BSD-3-Clause
 ********************************************************/

#include <arrayfire.h>
#include <climits>
#include <cstring>
#include <ctime>
#include <cstdio>

using namespace af;
static const float DefaultTopFittest = 0.5;

array update(const array& searchSpace, const array& sampleX, const array& sampleY, const int n)
{
    return searchSpace(sampleY*n + sampleX);
}

array selectFittest(const array& sampleZ, const int nSamples,
        const float topFit = DefaultTopFittest)
{
    //pick top fittest
    array indices, values;
    sort(values, indices, sampleZ);
    int topFitElem = topFit*nSamples;
    int n = indices.elements();
    return (n > topFitElem) ? indices(seq(n - topFitElem, n-1)) : indices;
}

void reproduce(array& searchSpace, array& sampleX, array& sampleY, array& sampleZ, const int nSamples, const int n)
{
    //Get fittest parents
    array selection = selectFittest(sampleZ, nSamples);
    array parentsX = sampleX(selection);
    array parentsY = sampleY(selection);
    int bits = (int)log2(n);

    //Divide selection in two
    array parentsX1 = parentsX.rows(0, parentsX.elements() / 2 - 1);
    array parentsX2 = parentsX.rows(parentsX.elements() / 2, parentsX.elements() - 1);
    array parentsY1 = parentsY.rows(0, parentsY.elements() / 2 - 1);
    array parentsY2 = parentsY.rows(parentsY.elements() / 2, parentsY.elements() - 1);

    //Get crossover points (at which bit to crossover) and construct bit masks from them
    array crossover = randu(nSamples / 4, u32) % bits;
    array lowermask = (1 << crossover) - 1;
    array uppermask = INT_MAX - lowermask;

    //Create children as the cross between two parents
    array childrenX1 = (parentsX1 & uppermask) + (parentsX2 & lowermask);
    array childrenY1 = (parentsY1 & uppermask) + (parentsY2 & lowermask);

    array childrenX2 = (parentsX2 & uppermask) + (parentsX1 & lowermask);
    array childrenY2 = (parentsY2 & uppermask) + (parentsY1 & lowermask);

    //Join two new sets
    sampleX = join(0, childrenX1, childrenX2);
    sampleY = join(0, childrenY1, childrenY2);

    //Create mutant children
    array mutantX = sampleX;
    array mutantY = sampleY;

    //Flip a random bit to vary the gene pool
    mutantX = mutantX ^ (1 << (randu(nSamples / 2, u32) % bits));
    mutantY = mutantY ^ (1 << (randu(nSamples / 2, u32) % bits));

    sampleX = join(0, sampleX, mutantX);
    sampleY = join(0, sampleY, mutantY);

    //Update the value of each sample with the new coordinates
    sampleZ = update(searchSpace, sampleX, sampleY, n);
}

void initSamples(array& searchSpace, array& sampleX, array& sampleY, array& sampleZ, const int nSamples, const int n)
{
    setSeed(time(NULL));
    sampleX = randu(nSamples, u32) % n;
    sampleY = randu(nSamples, u32) % n;
    sampleZ = update(searchSpace, sampleX, sampleY, n);
}

void init(array& searchSpace, array& searchSpaceXDisplay, array& searchSpaceYDisplay, array& sampleX, array& sampleY, array& sampleZ, const int nSamples, const int n)
{
    //initialize space
    searchSpace = range(dim4(n/2, n/2), 0) + range(dim4(n/2, n/2), 1);
    searchSpace = join(0, searchSpace, flip(searchSpace, 0));
    searchSpace = join(1, searchSpace, flip(searchSpace, 1));

    //initialize display data
    searchSpaceXDisplay = iota(dim4(n, 1), dim4(1, n));
    searchSpaceYDisplay = iota(dim4(1, n), dim4(n, 1));

    //initalize searchers
    initSamples(searchSpace, sampleX, sampleY, sampleZ, nSamples, n);
}

void reproducePrint(float& currentMax,
        array& searchSpace, array& sampleX, array& sampleY, array& sampleZ,
        const float trueMax, const int nSamples, const int n)
{
    if (currentMax < trueMax * 0.99) {
        float maximum = max<float>(sampleZ);
        array whereM = where(sampleZ == maximum);
        if (maximum < trueMax * 0.99) {
            printf("Current max at ");
        } else {
            printf("\nMax found at ");
        }
        printf("(%d,%d): %f (trueMax %f)\n",
                sampleX(whereM).scalar<unsigned int>(),
                sampleY(whereM).scalar<unsigned int>(), maximum, trueMax);
        currentMax = maximum;
        reproduce(searchSpace, sampleX, sampleY, sampleZ, nSamples, n);
    }
}

void geneticSearch(bool console, const int nSamples, const int n)
{
    array searchSpaceXDisplay = 0;
    array searchSpaceYDisplay = 0;
    array searchSpace;
    array sampleX;
    array sampleY;
    array sampleZ;

    init(searchSpace, searchSpaceXDisplay, searchSpaceYDisplay,
            sampleX, sampleY, sampleZ, nSamples, n);
    float trueMax = max<float>(searchSpace);
    float maximum = -trueMax;

    if (!console) {
        af::Window win(1600, 800, "Arrayfire Genetic Algorithm Search Demo");
        win.grid(1, 2);
        do {
            reproducePrint(maximum, searchSpace, sampleX, sampleY, sampleZ,
                    trueMax, nSamples, n);
            win(0,0).setAxesTitles("IdX", "IdY", "Search Space");
            win(0,1).setAxesTitles("IdX", "IdY", "Search Space");
            win(0,0).surface(searchSpaceXDisplay, searchSpaceYDisplay, searchSpace);
            win(0,1).scatter(sampleX.as(f32), sampleY.as(f32), sampleZ.as(f32), AF_MARKER_CIRCLE);
            win.show();
        } while (!win.close());
    } else {
        do {
            reproducePrint(maximum, searchSpace, sampleX, sampleY, sampleZ,
                    trueMax, nSamples, n);
        } while (maximum < trueMax * 0.99);
    }
}

int main(int argc, char** argv)
{
    bool console = false;
    const int n = 32;
    const int nSamples = 16;
    if (argc > 2 || (argc == 2 && strcmp(argv[1], "-"))) {
        printf("usage: %s [-]\n", argv[0]);
        return -1;
    } else if (argc == 2 && argv[1][0] == '-') {
        console = true;
    }

    try {
        af::info();
        printf("** ArrayFire Genetic Algorithm Search Demo **\n\n");
        printf("Search for trueMax in a search space where the objective function is defined as :\n\n");
        printf("SS(x ,y) = min(x, n - (x + 1)) + min(y, n - (y + 1))\n\n");
        printf("(x, y) belongs to RxR; R = [0, n); n = %d\n\n", n);
        if (!console) {
            printf("The left figure shows the objective function.\n");
            printf("The figure on the right shows current generation's parameters and function values.\n\n");
        }
        geneticSearch(console, nSamples, n);
    } catch (af::exception& e) {
        fprintf(stderr, "%s\n", e.what());
    }

    return 0;
}
<|endoftext|>


<commit_before>#include "socketutils.h"
#include <math.h>
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
//BSD socket stuff
#ifndef WIN32
#include <unistd.h>
#include <sys/types.h>
#include <fcntl.h>
#include <netinet/in.h>
#include <netdb.h>
#endif

#ifdef WIN32
typedef int socklen_t;

struct WSASocketGlobal
{
public:
  bool started,failed;
  WSASocketGlobal() : started(false),failed(false) {}
  ~WSASocketGlobal() {
    if(started) {
      printf("Shutting down the Winsock 2.2 dll\n");
      WSACleanup();
    }
  }
  bool Init() {
    WORD wVersionRequested;
    WSADATA wsaData;
    int err;

/* Use the MAKEWORD(lowbyte, highbyte) macro declared in Windef.h */
    wVersionRequested = MAKEWORD(2, 2);

    err = WSAStartup(wVersionRequested, &wsaData);
    if (err != 0) {
        /* Tell the user that we could not find a usable */
        /* Winsock DLL.                                  */
        printf("WSAStartup failed with error: %d\n", err);
		failed = true;
        return false;
    }

/* Confirm that the WinSock DLL supports 2.2.*/
/* Note that if the DLL supports versions greater    */
/* than 2.2 in addition to 2.2, it will still return */
/* 2.2 in wVersion since that is the version we      */
/* requested.                                        */

    if (LOBYTE(wsaData.wVersion) != 2 || HIBYTE(wsaData.wVersion) != 2) {
        /* Tell the user that we could not find a usable */
        /* WinSock DLL.                                  */
        printf("Could not find a usable version of Winsock.dll\n");
        WSACleanup();
		failed = true;
        return false;
    }
    else {
        printf("The Winsock 2.2 dll was found successfully\n");
	started = true;
	return true;
    }
  }
};

static WSASocketGlobal gWSASocketObject;

bool EnsureSocketStarted()
{
  if(gWSASocketObject.failed) return false;
  if(gWSASocketObject.started) return true;
  return gWSASocketObject.Init();
}

#else

bool EnsureSocketStarted() { return true; }

#endif //WIN32

///Caller must ensure that protocol and host are large enough to handle the
///items.  Simple way of doing this is to allocate to size strlen(addr)
bool ParseAddr(const char* addr,char* protocol,char* host,int& port)
{
  const char* pos=strstr(addr,"://");
  if(pos == NULL) return false;
  //parse protocol
  int spos = pos-addr;
  strncpy(protocol,addr,spos);
  protocol[spos] = 0;
  //parse address and port
  pos += 3;
  spos += 3;
  const char* colonpos = strstr(pos,":");
  if(colonpos==NULL) {
    strcpy(host,pos);
  }
  else {
    strncpy(host,pos,colonpos-pos);
    host[colonpos-pos]=0;
  }
  port = -1;
  //default http port
  if(strcmp(protocol,"http")==0)
    port = 80;
  //default ftp port
  if(strcmp(protocol,"ftp")==0)
    port = 21;

  if(colonpos != NULL) {
    //parse port
    colonpos ++;
    char* endptr;
    long int res = strtol(colonpos,&endptr,0);
    if(res==0 && endptr==colonpos) {
      fprintf(stderr,"ParseAddr: address did not contain valid port\n");
      return false;
    }
    if(res < 0 || res > 0xffff) {
      fprintf(stderr,"ParseAddr: address did not contain valid port\n");
      return false;
    }
    port = (int)res;
  }

  if(port < 0) {
    fprintf(stderr,"ParseAddr: address did not contain valid port\n");
    return false;
  }
  return true;
}

SOCKET Connect(const char* addr)
{
  if(!EnsureSocketStarted()) return INVALID_SOCKET;

  char* protocol = new char[strlen(addr)];
  char* host = new char[strlen(addr)];
  int port;
  if(!ParseAddr(addr,protocol,host,port)) {
    fprintf(stderr,"Connect: Error parsing address %s\n",addr);
    delete [] protocol;
    delete [] host;
    return INVALID_SOCKET;
  }

  struct sockaddr_in serv_addr;
  struct hostent *server;

  int sockettype = SOCK_STREAM;
  if(0==strcmp(protocol,"udp")) {
    sockettype = SOCK_DGRAM;
  }
  delete [] protocol;

  SOCKET sockfd = socket(AF_INET, sockettype, 0);
  if (sockfd == INVALID_SOCKET) {
    fprintf(stderr,"Connect: Error creating socket\n");
    delete [] host;
    return INVALID_SOCKET;
  }
  server = gethostbyname(host);
  if (server == NULL) {
    fprintf(stderr,"Connect: Error, no such host %s:%d\n",host,port);
    CloseSocket(sockfd);
    delete [] host;
    return INVALID_SOCKET;
  }
  memset(&serv_addr, 0, sizeof(serv_addr));
  serv_addr.sin_family = AF_INET;
  memcpy(&serv_addr.sin_addr.s_addr,
	 server->h_addr,
	 server->h_length);
  serv_addr.sin_port = htons(port);

  if (connect(sockfd,(sockaddr*)&serv_addr,sizeof(serv_addr)) < 0) {
    fprintf(stderr,"Connect: Connect to server %s:%d failed\n",host,port);
    perror("  Connect error");
    CloseSocket(sockfd);
    delete [] host;
    return INVALID_SOCKET;
  }

  return sockfd;
}

SOCKET Bind(const char* addr,bool block)
{
  if(!EnsureSocketStarted()) return INVALID_SOCKET;

  char* protocol = new char[strlen(addr)];
  char* host = new char[strlen(addr)];
  int port;
  if(!ParseAddr(addr,protocol,host,port)) {
    fprintf(stderr,"Error parsing address %s\n",addr);
    delete [] protocol;
    delete [] host;
    return INVALID_SOCKET;
  }

  struct sockaddr_in serv_addr;
  struct hostent *server;

  int sockettype = SOCK_STREAM;
  if(0==strcmp(protocol,"udp")) {
    sockettype = SOCK_DGRAM;
  }
  delete [] protocol;

  SOCKET sockfd = socket(AF_INET, sockettype, 0);
  if (sockfd == INVALID_SOCKET) {
    fprintf(stderr,"File::Open: Error creating socket\n");
    delete [] host;
    return INVALID_SOCKET;
  }
  if(!block)  {
	  SetNonblock(sockfd);
  }

  server = gethostbyname(host);
  if (server == NULL) {
    fprintf(stderr,"File::Open: Error, no such host %s:%d\n",host,port);
    CloseSocket(sockfd);
    delete [] host;
    return INVALID_SOCKET;
  }
  memset(&serv_addr, 0, sizeof(serv_addr));
  serv_addr.sin_family = AF_INET;
  memcpy(&serv_addr.sin_addr.s_addr,
	 server->h_addr,
	 server->h_length);
  serv_addr.sin_port = htons(port);

  if (bind(sockfd,(sockaddr*)&serv_addr,sizeof(serv_addr)) < 0) {
    fprintf(stderr,"File::Open: Bind server to %s:%d failed\n",host,port);
    perror("");
    CloseSocket(sockfd);
    delete [] host;
    return INVALID_SOCKET ;
  }
  delete [] host;
  return sockfd;
}

SOCKET Accept(SOCKET sockfd)
{
  if(!EnsureSocketStarted()) return INVALID_SOCKET;

  struct sockaddr_in cli_addr;
  socklen_t clilen = sizeof(cli_addr);
  SOCKET clientsocket = accept(sockfd, (struct sockaddr *)&cli_addr,
			    &clilen);
  return clientsocket;
}

SOCKET Accept(SOCKET sockfd,double timeout)
{
  if(!EnsureSocketStarted()) return INVALID_SOCKET;

  fd_set rfds;
  FD_ZERO(&rfds);
  FD_SET(sockfd, &rfds);

  timeval tv;
  double secs = floor(timeout);
  tv.tv_sec = (int)secs;
  tv.tv_usec = (timeout-secs)*1000000;

  int result = select(sockfd + 1, &rfds, (fd_set *) 0, (fd_set *) 0, &tv);
  if(result > 0) {
    struct sockaddr_in cli_addr;
    socklen_t clilen = sizeof(cli_addr);
    SOCKET clientsocket = accept(sockfd, (struct sockaddr *)&cli_addr,
				 &clilen);
    return clientsocket;
  }
  else  {
    if(result < 0) {
      printf("Error using select()\n");
    }
     //always here, even if i connect from another application
    return INVALID_SOCKET;
  }
}

void SetNonblock(SOCKET sockfd)
{
#ifdef WIN32
	u_long iMode=1;
	ioctlsocket(sockfd,FIONBIO,&iMode);
#else
    fcntl(sockfd,F_SETFL,FNDELAY);
#endif //WIN32
}

void CloseSocket(SOCKET sockfd)
{
#ifdef WIN32
	shutdown(sockfd,SD_BOTH);
	closesocket(sockfd);
#else
	shutdown(sockfd,SHUT_RDWR);
	close(sockfd);
#endif
}

bool ReadAvailable(SOCKET socketfd)
{
  fd_set fds;
  timeval tv;
  // clear the set ahead of time
  FD_ZERO(&fds);

  // add our descriptors to the set
  FD_SET(socketfd, &fds);

#ifdef WIN32
  int n = 0; //this parameter is ignored
#else
  int n = socketfd + 1;
#endif

  // wait until either socket has data ready to be recv()d (timeout 10.5 secs)
  tv.tv_sec = 0;
  tv.tv_usec = 0;
  int rv = select(n, &fds, NULL, NULL, &tv);

  if (rv == -1) {
    perror("select"); // error occurred in select()
    return false;
  } else if (rv == 0) {
    return false;
  } else {
    return true;
  }
}

bool WriteAvailable(SOCKET socketfd)
{
  fd_set fds;
  timeval tv;
  // clear the set ahead of time
  FD_ZERO(&fds);

  // add our descriptors to the set
  FD_SET(socketfd, &fds);

#ifdef WIN32
  int n = 0; //this parameter is ignored
#else
  int n = socketfd + 1;
#endif

  // wait until either socket has data ready to be recv()d (timeout 10.5 secs)
  tv.tv_sec = 0;
  tv.tv_usec = 0;
  int rv = select(n, NULL, &fds, NULL, &tv);

  if (rv == -1) {
    perror("select"); // error occurred in select()
    return false;
  } else if (rv == 0) {
    return false;
  } else {
    return true;
  }
}

bool HasException(SOCKET socketfd)
{
  fd_set fds;
  timeval tv;
  // clear the set ahead of time
  FD_ZERO(&fds);

  // add our descriptors to the set
  FD_SET(socketfd, &fds);

#ifdef WIN32
  int n = 0; //this parameter is ignored
#else
  int n = socketfd + 1;
#endif

  // wait until either socket has data ready to be recv()d (timeout 10.5 secs)
  tv.tv_sec = 0;
  tv.tv_usec = 0;
  int rv = select(n, NULL, NULL, &fds, &tv);

  if (rv == -1) {
    perror("select"); // error occurred in select()
    return false;
  } else if (rv == 0) {
    return false;
  } else {
    return true;
  }
}
<commit_msg>More error checking on ReadAvailable/WriteAvailable<commit_after>#include "socketutils.h"
#include <math.h>
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
//BSD socket stuff
#ifndef WIN32
#include <unistd.h>
#include <sys/types.h>
#include <fcntl.h>
#include <netinet/in.h>
#include <netdb.h>
#endif

#ifdef WIN32
typedef int socklen_t;

struct WSASocketGlobal
{
public:
  bool started,failed;
  WSASocketGlobal() : started(false),failed(false) {}
  ~WSASocketGlobal() {
    if(started) {
      printf("Shutting down the Winsock 2.2 dll\n");
      WSACleanup();
    }
  }
  bool Init() {
    WORD wVersionRequested;
    WSADATA wsaData;
    int err;

/* Use the MAKEWORD(lowbyte, highbyte) macro declared in Windef.h */
    wVersionRequested = MAKEWORD(2, 2);

    err = WSAStartup(wVersionRequested, &wsaData);
    if (err != 0) {
        /* Tell the user that we could not find a usable */
        /* Winsock DLL.                                  */
        printf("WSAStartup failed with error: %d\n", err);
		failed = true;
        return false;
    }

/* Confirm that the WinSock DLL supports 2.2.*/
/* Note that if the DLL supports versions greater    */
/* than 2.2 in addition to 2.2, it will still return */
/* 2.2 in wVersion since that is the version we      */
/* requested.                                        */

    if (LOBYTE(wsaData.wVersion) != 2 || HIBYTE(wsaData.wVersion) != 2) {
        /* Tell the user that we could not find a usable */
        /* WinSock DLL.                                  */
        printf("Could not find a usable version of Winsock.dll\n");
        WSACleanup();
		failed = true;
        return false;
    }
    else {
        printf("The Winsock 2.2 dll was found successfully\n");
	started = true;
	return true;
    }
  }
};

static WSASocketGlobal gWSASocketObject;

bool EnsureSocketStarted()
{
  if(gWSASocketObject.failed) return false;
  if(gWSASocketObject.started) return true;
  return gWSASocketObject.Init();
}

#else

bool EnsureSocketStarted() { return true; }

#endif //WIN32

///Caller must ensure that protocol and host are large enough to handle the
///items.  Simple way of doing this is to allocate to size strlen(addr)
bool ParseAddr(const char* addr,char* protocol,char* host,int& port)
{
  const char* pos=strstr(addr,"://");
  if(pos == NULL) return false;
  //parse protocol
  int spos = pos-addr;
  strncpy(protocol,addr,spos);
  protocol[spos] = 0;
  //parse address and port
  pos += 3;
  spos += 3;
  const char* colonpos = strstr(pos,":");
  if(colonpos==NULL) {
    strcpy(host,pos);
  }
  else {
    strncpy(host,pos,colonpos-pos);
    host[colonpos-pos]=0;
  }
  port = -1;
  //default http port
  if(strcmp(protocol,"http")==0)
    port = 80;
  //default ftp port
  if(strcmp(protocol,"ftp")==0)
    port = 21;

  if(colonpos != NULL) {
    //parse port
    colonpos ++;
    char* endptr;
    long int res = strtol(colonpos,&endptr,0);
    if(res==0 && endptr==colonpos) {
      fprintf(stderr,"ParseAddr: address did not contain valid port\n");
      return false;
    }
    if(res < 0 || res > 0xffff) {
      fprintf(stderr,"ParseAddr: address did not contain valid port\n");
      return false;
    }
    port = (int)res;
  }

  if(port < 0) {
    fprintf(stderr,"ParseAddr: address did not contain valid port\n");
    return false;
  }
  return true;
}

SOCKET Connect(const char* addr)
{
  if(!EnsureSocketStarted()) return INVALID_SOCKET;

  char* protocol = new char[strlen(addr)];
  char* host = new char[strlen(addr)];
  int port;
  if(!ParseAddr(addr,protocol,host,port)) {
    fprintf(stderr,"Connect: Error parsing address %s\n",addr);
    delete [] protocol;
    delete [] host;
    return INVALID_SOCKET;
  }

  struct sockaddr_in serv_addr;
  struct hostent *server;

  int sockettype = SOCK_STREAM;
  if(0==strcmp(protocol,"udp")) {
    sockettype = SOCK_DGRAM;
  }
  delete [] protocol;

  SOCKET sockfd = socket(AF_INET, sockettype, 0);
  if (sockfd == INVALID_SOCKET) {
    fprintf(stderr,"Connect: Error creating socket\n");
    delete [] host;
    return INVALID_SOCKET;
  }
  server = gethostbyname(host);
  if (server == NULL) {
    fprintf(stderr,"Connect: Error, no such host %s:%d\n",host,port);
    CloseSocket(sockfd);
    delete [] host;
    return INVALID_SOCKET;
  }
  memset(&serv_addr, 0, sizeof(serv_addr));
  serv_addr.sin_family = AF_INET;
  memcpy(&serv_addr.sin_addr.s_addr,
	 server->h_addr,
	 server->h_length);
  serv_addr.sin_port = htons(port);

  if (connect(sockfd,(sockaddr*)&serv_addr,sizeof(serv_addr)) < 0) {
    fprintf(stderr,"Connect: Connect to server %s:%d failed\n",host,port);
    perror("  Connect error");
    CloseSocket(sockfd);
    delete [] host;
    return INVALID_SOCKET;
  }

  return sockfd;
}

SOCKET Bind(const char* addr,bool block)
{
  if(!EnsureSocketStarted()) return INVALID_SOCKET;

  char* protocol = new char[strlen(addr)];
  char* host = new char[strlen(addr)];
  int port;
  if(!ParseAddr(addr,protocol,host,port)) {
    fprintf(stderr,"Error parsing address %s\n",addr);
    delete [] protocol;
    delete [] host;
    return INVALID_SOCKET;
  }

  struct sockaddr_in serv_addr;
  struct hostent *server;

  int sockettype = SOCK_STREAM;
  if(0==strcmp(protocol,"udp")) {
    sockettype = SOCK_DGRAM;
  }
  delete [] protocol;

  SOCKET sockfd = socket(AF_INET, sockettype, 0);
  if (sockfd == INVALID_SOCKET) {
    fprintf(stderr,"File::Open: Error creating socket\n");
    delete [] host;
    return INVALID_SOCKET;
  }
  if(!block)  {
	  SetNonblock(sockfd);
  }

  server = gethostbyname(host);
  if (server == NULL) {
    fprintf(stderr,"File::Open: Error, no such host %s:%d\n",host,port);
    CloseSocket(sockfd);
    delete [] host;
    return INVALID_SOCKET;
  }
  memset(&serv_addr, 0, sizeof(serv_addr));
  serv_addr.sin_family = AF_INET;
  memcpy(&serv_addr.sin_addr.s_addr,
	 server->h_addr,
	 server->h_length);
  serv_addr.sin_port = htons(port);

  if (bind(sockfd,(sockaddr*)&serv_addr,sizeof(serv_addr)) < 0) {
    fprintf(stderr,"File::Open: Bind server to %s:%d failed\n",host,port);
    perror("");
    CloseSocket(sockfd);
    delete [] host;
    return INVALID_SOCKET ;
  }
  delete [] host;
  return sockfd;
}

SOCKET Accept(SOCKET sockfd)
{
  if(!EnsureSocketStarted()) return INVALID_SOCKET;

  struct sockaddr_in cli_addr;
  socklen_t clilen = sizeof(cli_addr);
  SOCKET clientsocket = accept(sockfd, (struct sockaddr *)&cli_addr,
			    &clilen);
  return clientsocket;
}

SOCKET Accept(SOCKET sockfd,double timeout)
{
  if(!EnsureSocketStarted()) return INVALID_SOCKET;

  fd_set rfds;
  FD_ZERO(&rfds);
  FD_SET(sockfd, &rfds);

  timeval tv;
  double secs = floor(timeout);
  tv.tv_sec = (int)secs;
  tv.tv_usec = (timeout-secs)*1000000;

  int result = select(sockfd + 1, &rfds, (fd_set *) 0, (fd_set *) 0, &tv);
  if(result > 0) {
    struct sockaddr_in cli_addr;
    socklen_t clilen = sizeof(cli_addr);
    SOCKET clientsocket = accept(sockfd, (struct sockaddr *)&cli_addr,
				 &clilen);
    return clientsocket;
  }
  else  {
    if(result < 0) {
      printf("Error using select()\n");
    }
     //always here, even if i connect from another application
    return INVALID_SOCKET;
  }
}

void SetNonblock(SOCKET sockfd)
{
#ifdef WIN32
	u_long iMode=1;
	ioctlsocket(sockfd,FIONBIO,&iMode);
#else
    fcntl(sockfd,F_SETFL,FNDELAY);
#endif //WIN32
}

void CloseSocket(SOCKET sockfd)
{
#ifdef WIN32
	shutdown(sockfd,SD_BOTH);
	closesocket(sockfd);
#else
	shutdown(sockfd,SHUT_RDWR);
	close(sockfd);
#endif
}

bool ReadAvailable(SOCKET socketfd)
{
  fd_set fds;
  timeval tv;
  // clear the set ahead of time
  FD_ZERO(&fds);

  // add our descriptors to the set
  FD_SET(socketfd, &fds);

#ifdef WIN32
  int n = 0; //this parameter is ignored
#else
  int n = socketfd + 1;
#endif

  // wait until either socket has data ready to be recv()d (timeout 10.5 secs)
  tv.tv_sec = 0;
  tv.tv_usec = 0;
  int rv = select(n, &fds, NULL, NULL, &tv);

  if (rv == -1) {
    perror("select"); // error occurred in select()
    return false;
  } else if (rv == 0) {
    return false;
  } else {
    if(FD_ISSET(socketfd, &fds))
      return true;
    else
      printf("ReadAvailable: weird, select returned 1 but the FD set is not set\n");
    return false;
  }
}

bool WriteAvailable(SOCKET socketfd)
{
  fd_set fds;
  timeval tv;
  // clear the set ahead of time
  FD_ZERO(&fds);

  // add our descriptors to the set
  FD_SET(socketfd, &fds);

#ifdef WIN32
  int n = 0; //this parameter is ignored
#else
  int n = socketfd + 1;
#endif

  // wait until either socket has data ready to be recv()d (timeout 10.5 secs)
  tv.tv_sec = 0;
  tv.tv_usec = 0;
  int rv = select(n, NULL, &fds, NULL, &tv);

  if (rv == -1) {
    perror("select"); // error occurred in select()
    return false;
  } else if (rv == 0) {
    return false;
  } else {
    if(FD_ISSET(socketfd, &fds))
      return true;
    else
      printf("WriteAvailable: weird, select returned 1 but the FD set is not set\n");
    return false;
  }
}

bool HasException(SOCKET socketfd)
{
  fd_set fds;
  timeval tv;
  // clear the set ahead of time
  FD_ZERO(&fds);

  // add our descriptors to the set
  FD_SET(socketfd, &fds);

#ifdef WIN32
  int n = 0; //this parameter is ignored
#else
  int n = socketfd + 1;
#endif

  // wait until either socket has data ready to be recv()d (timeout 10.5 secs)
  tv.tv_sec = 0;
  tv.tv_usec = 0;
  int rv = select(n, NULL, NULL, &fds, &tv);

  if (rv == -1) {
    perror("select"); // error occurred in select()
    return false;
  } else if (rv == 0) {
    return false;
  } else {
    if(FD_ISSET(socketfd, &fds))
      return true;
    else
      printf("HasException: weird, select returned 1 but the FD set is not set\n");
    return false;
  }
}
<|endoftext|>


<commit_before>/***********************************************************************
 * Joystick                                                            *
 * read joystick data, normalize from -90 to +90, write data to serial *
 *                                                                     *
 * @author: Navid Kalaei <navidkalaie@gmail.com>                       *
 * @github: @navid-kalaei                                              *
 * @license: MIT                                                       *
 ***********************************************************************/

#include "Arduino.h"
#include <custom_joystick>

// time to wait in millis
#define DELAY_TIME 1000

#define SERIAL_RATE 9600
#define JOY_PIN_X 0
#define JOY_PIN_Y 1

custom_joystick joy;

void setup(){
  joy.attach_pin_x(JOY_PIN_X);
  joy.attach_pin_y(JOY_PIN_Y);

  joy.calibrate();

  joyXOriginNormalized = normalize(joyXOrigin);

  joyYOriginNormalized = normalize(joyYOrigin);

  // wait until Serail is not available
  while(!Serial);
  Serial.begin(SERIAL_RATE);
}

void loop(){
  joyValueX = analogRead(JOY_PIN_X);
  joyValueXNormalized = normalize(joyValueX) - joyXOriginNormalized;
  checkBoundries(joyValueXNormalized);

  joyValueY =  analogRead(JOY_PIN_Y);
  joyValueYNormalized = normalize(joyValueY) - joyYOriginNormalized;
  checkBoundries(joyValueYNormalized);

  Serial.print(joyValueX);
  Serial.print(' ');
  Serial.print(joyValueXNormalized);
  Serial.print(" - ");
  Serial.print(joyValueY);
  Serial.print(' ');
  Serial.println(joyValueYNormalized);

  delay(DELAY_TIME);
}
<commit_msg>fix includings joystick/main.cpp<commit_after>/***********************************************************************
 * Joystick                                                            *
 * read joystick data, normalize from -90 to +90, write data to serial *
 *                                                                     *
 * @author: Navid Kalaei <navidkalaie@gmail.com>                       *
 * @github: @navid-kalaei                                              *
 * @license: MIT                                                       *
 ***********************************************************************/

#include "Arduino.h"
#include <custom_joystick.h>

// time to wait in millis
#define DELAY_TIME 1000

#define SERIAL_RATE 9600
#define JOY_PIN_X 0
#define JOY_PIN_Y 1

custom_joystick joy;

void setup(){
  joy.attach_pin_x(JOY_PIN_X);
  joy.attach_pin_y(JOY_PIN_Y);

  joy.colibrate();

  // wait until Serail is not available
  while(!Serial);
  Serial.begin(SERIAL_RATE);
}

void loop(){
  joyValueX = analogRead(JOY_PIN_X);
  joyValueXNormalized = normalize(joyValueX) - joyXOriginNormalized;
  checkBoundries(joyValueXNormalized);

  joyValueY =  analogRead(JOY_PIN_Y);
  joyValueYNormalized = normalize(joyValueY) - joyYOriginNormalized;
  checkBoundries(joyValueYNormalized);

  Serial.print(joyValueX);
  Serial.print(' ');
  Serial.print(joyValueXNormalized);
  Serial.print(" - ");
  Serial.print(joyValueY);
  Serial.print(' ');
  Serial.println(joyValueYNormalized);

  delay(DELAY_TIME);
}
<|endoftext|>


<commit_before>/**************************************************************************
 * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
 *                                                                        *
 * Author: The ALICE Off-line Project.                                    *
 * Contributors are mentioned in the code where appropriate.              *
 *                                                                        *
 * Permission to use, copy, modify and distribute this software and its   *
 * documentation strictly for non-commercial purposes is hereby granted   *
 * without fee, provided that the above copyright notice appears in all   *
 * copies and that both the copyright notice and this permission notice   *
 * appear in the supporting documentation. The authors make no claims     *
 * about the suitability of this software for any purpose. It is          *
 * provided "as is" without express or implied warranty.                  *
 **************************************************************************/

/* $Id$ */

/*
  Base Class
  Produces the data needed to calculate the quality assurance.
  All data must be mergeable objects.
  Y. Schutz CERN July 2007
*/

// --- ROOT system ---
#include <TSystem.h>
#include <TFile.h>
#include <TList.h>
#include <TTree.h>
#include <TClonesArray.h>

// --- Standard library ---

// --- AliRoot header files ---
#include "AliLog.h"
#include "AliQADataMaker.h"
#include "AliQAChecker.h"
#include "AliESDEvent.h"
#include "AliRawReader.h"

ClassImp(AliQADataMaker)

//____________________________________________________________________________
AliQADataMaker::AliQADataMaker(const char * name, const char * title) :
  TNamed(name, title),
  fOutput(0x0),
  fDetectorDir(0x0),
  fDetectorDirName(""),
  fCurrentCycle(-1),
  fCycle(9999999),
  fCycleCounter(0),
  fRun(0)
{
  // ctor
  fDetectorDirName = GetName() ;
}

//____________________________________________________________________________
AliQADataMaker::AliQADataMaker(const AliQADataMaker& qadm) :
  TNamed(qadm.GetName(), qadm.GetTitle()),
  fOutput(qadm.fOutput),
  fDetectorDir(qadm.fDetectorDir),
  fDetectorDirName(qadm.fDetectorDirName),
  fCurrentCycle(qadm.fCurrentCycle),
  fCycle(qadm.fCycle),
  fCycleCounter(qadm.fCycleCounter),
  fRun(qadm.fRun)
{
  //copy ctor
  fDetectorDirName = GetName() ;
}

//____________________________________________________________________________
Int_t AliQADataMaker::Add2List(TH1 * hist, const Int_t index, TObjArray * list)
{
	// Set histograms memory resident and add to the list
	// Maximm allowed is 100
	if ( index > 100 ) {
		AliError("Max number of authorized QA objects is 100") ;
		return -1 ;
	} else {
		hist->SetDirectory(0) ;
		list->AddAtAndExpand(hist, index) ;
		return list->GetLast() ;
	}
}

//____________________________________________________________________________
void AliQADataMaker::Finish() const
{
  // write to the output File
  fOutput->Close() ;
}

//____________________________________________________________________________
TObject * AliQADataMaker::GetData(TObjArray * list, const Int_t index)
{
	// Returns the QA object at index. Limit is 100.
	if ( index > 100 ) {
		AliError("Max number of authorized QA objects is 100") ;
		return NULL;
	} else {
		return list->At(index) ;
	}
}

//____________________________________________________________________________
void AliQADataMaker::Reset()
{
  // Resets defaut value of data members
  fCurrentCycle = -1 ;
  fCycleCounter = 0 ;
}
<commit_msg>increased the number of allowed histos to an unreasonable number<commit_after>/**************************************************************************
 * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
 *                                                                        *
 * Author: The ALICE Off-line Project.                                    *
 * Contributors are mentioned in the code where appropriate.              *
 *                                                                        *
 * Permission to use, copy, modify and distribute this software and its   *
 * documentation strictly for non-commercial purposes is hereby granted   *
 * without fee, provided that the above copyright notice appears in all   *
 * copies and that both the copyright notice and this permission notice   *
 * appear in the supporting documentation. The authors make no claims     *
 * about the suitability of this software for any purpose. It is          *
 * provided "as is" without express or implied warranty.                  *
 **************************************************************************/

/* $Id$ */

/*
  Base Class
  Produces the data needed to calculate the quality assurance.
  All data must be mergeable objects.
  Y. Schutz CERN July 2007
*/

// --- ROOT system ---
#include <TSystem.h>
#include <TFile.h>
#include <TList.h>
#include <TTree.h>
#include <TClonesArray.h>

// --- Standard library ---

// --- AliRoot header files ---
#include "AliLog.h"
#include "AliQADataMaker.h"
#include "AliQAChecker.h"
#include "AliESDEvent.h"
#include "AliRawReader.h"

ClassImp(AliQADataMaker)

//____________________________________________________________________________
AliQADataMaker::AliQADataMaker(const char * name, const char * title) :
  TNamed(name, title),
  fOutput(0x0),
  fDetectorDir(0x0),
  fDetectorDirName(""),
  fCurrentCycle(-1),
  fCycle(9999999),
  fCycleCounter(0),
  fRun(0)
{
  // ctor
  fDetectorDirName = GetName() ;
}

//____________________________________________________________________________
AliQADataMaker::AliQADataMaker(const AliQADataMaker& qadm) :
  TNamed(qadm.GetName(), qadm.GetTitle()),
  fOutput(qadm.fOutput),
  fDetectorDir(qadm.fDetectorDir),
  fDetectorDirName(qadm.fDetectorDirName),
  fCurrentCycle(qadm.fCurrentCycle),
  fCycle(qadm.fCycle),
  fCycleCounter(qadm.fCycleCounter),
  fRun(qadm.fRun)
{
  //copy ctor
  fDetectorDirName = GetName() ;
}

//____________________________________________________________________________
Int_t AliQADataMaker::Add2List(TH1 * hist, const Int_t index, TObjArray * list)
{
	// Set histograms memory resident and add to the list
	// Maximm allowed is 10000
	if ( index > 10000 ) {
		AliError("Max number of authorized QA objects is 10000") ;
		return -1 ;
	} else {
		hist->SetDirectory(0) ;
		list->AddAtAndExpand(hist, index) ;
		return list->GetLast() ;
	}
}

//____________________________________________________________________________
void AliQADataMaker::Finish() const
{
  // write to the output File
  fOutput->Close() ;
}

//____________________________________________________________________________
TObject * AliQADataMaker::GetData(TObjArray * list, const Int_t index)
{
	// Returns the QA object at index. Limit is 100.
	if ( index > 100 ) {
		AliError("Max number of authorized QA objects is 100") ;
		return NULL;
	} else {
		return list->At(index) ;
	}
}

//____________________________________________________________________________
void AliQADataMaker::Reset()
{
  // Resets defaut value of data members
  fCurrentCycle = -1 ;
  fCycleCounter = 0 ;
}
<|endoftext|>