<commit_before>/**
 * @file
 *
 * @brief
 *
 * @copyright BSD License (see doc/COPYING or http://www.libelektra.org)
 */

#include <info.hpp>

#include <cmdline.hpp>
#include <kdb.hpp>
#include <modules.hpp>
#include <plugin.hpp>

#include <iostream>

using namespace std;
using namespace kdb;
using namespace kdb::tools;

InfoCommand::InfoCommand ()
{
}

int InfoCommand::execute (Cmdline const & cl)
{
	std::string subkey;
	if (cl.arguments.size () == 1)
	{
	}
	else if (cl.arguments.size () == 2)
	{
		subkey = cl.arguments[1];
	}
	else
	{
		throw invalid_argument ("Need at 1 or 2 argument(s)");
	}
	std::string name = cl.arguments[0];

	KeySet conf;
	Key parentKey (std::string ("system/elektra/modules/") + name, KEY_END);

	if (!cl.load)
	{
		kdb.get (conf, parentKey);
	}

	if (!conf.lookup (parentKey))
	{
		if (!cl.load)
		{
			cerr << "Module does not seem to be loaded." << endl;
			cerr << "Now in fallback code. Will directly load config from plugin." << endl;
		}

		Modules modules;
		KeySet ks = cl.getPluginsConfig ();
		PluginPtr plugin;
		if (ks.size () == 0)
		{
			plugin = modules.load (name);
		}
		else
		{
			plugin = modules.load (name, ks);
		}
		conf.append (plugin->getInfo ());
	}

	Key root (std::string ("system/elektra/modules/") + name + "/exports", KEY_END);

	if (!subkey.empty ())
	{
		root.setName (std::string ("system/elektra/modules/") + name + "/infos/" + subkey);
		Key k = conf.lookup (root);
		if (k)
		{
			cout << k.getString () << std::endl;
			return 0;
		}
		else
		{
			cerr << "clause not found" << std::endl;
			return 1;
		}
	}

	root.setName (std::string ("system/elektra/modules/") + name + "/exports");
	Key k = conf.lookup (root);

	if (k)
	{
		cout << "Exported symbols: ";
		while ((k = conf.next ()) && k.isBelow (root))
		{
			cout << k.getBaseName () << " ";
		}
		cout << endl;
	}
	else
		cout << "no exported symbols found" << endl;

	root.setName (std::string ("system/elektra/modules/") + name + "/infos");
	k = conf.lookup (root);

	if (k)
	{
		while ((k = conf.next ()) && k.isBelow (root))
		{
			cout << k.getBaseName () << ": " << k.getString () << endl;
		}
	}
	else
		cout << "no information found" << endl;

	return 0;
}

InfoCommand::~InfoCommand ()
{
}
<commit_msg>fix name for virtual plugins<commit_after>/**
 * @file
 *
 * @brief
 *
 * @copyright BSD License (see doc/COPYING or http://www.libelektra.org)
 */

#include <info.hpp>

#include <cmdline.hpp>
#include <kdb.hpp>
#include <modules.hpp>
#include <plugin.hpp>

#include <iostream>

using namespace std;
using namespace kdb;
using namespace kdb::tools;

InfoCommand::InfoCommand ()
{
}

int InfoCommand::execute (Cmdline const & cl)
{
	std::string subkey;
	if (cl.arguments.size () == 1)
	{
	}
	else if (cl.arguments.size () == 2)
	{
		subkey = cl.arguments[1];
	}
	else
	{
		throw invalid_argument ("Need at 1 or 2 argument(s)");
	}
	std::string name = cl.arguments[0];

	KeySet conf;
	Key parentKey (std::string ("system/elektra/modules/") + name, KEY_END);

	if (!cl.load)
	{
		kdb.get (conf, parentKey);
	}

	if (!conf.lookup (parentKey))
	{
		if (!cl.load)
		{
			cerr << "Module does not seem to be loaded." << endl;
			cerr << "Now in fallback code. Will directly load config from plugin." << endl;
		}

		Modules modules;
		KeySet ks = cl.getPluginsConfig ();
		PluginPtr plugin;
		if (ks.size () == 0)
		{
			plugin = modules.load (name);
		}
		else
		{
			plugin = modules.load (name, ks);
		}

		// fix name for virtual plugins
		if (name != plugin->name ())
		{
			std::cerr << "Will use name " << plugin->name () << " for virtual plugin named " << name << std::endl;
			name = plugin->name ();
		}
		conf.append (plugin->getInfo ());
	}

	Key root (std::string ("system/elektra/modules/") + name + "/exports", KEY_END);

	if (!subkey.empty ())
	{
		root.setName (std::string ("system/elektra/modules/") + name + "/infos/" + subkey);
		Key k = conf.lookup (root);
		if (k)
		{
			cout << k.getString () << std::endl;
			return 0;
		}
		else
		{
			cerr << "clause not found" << std::endl;
			return 1;
		}
	}

	root.setName (std::string ("system/elektra/modules/") + name + "/exports");
	Key k = conf.lookup (root);

	if (k)
	{
		cout << "Exported symbols: ";
		while ((k = conf.next ()) && k.isBelow (root))
		{
			cout << k.getBaseName () << " ";
		}
		cout << endl;
	}
	else
		cout << "no exported symbols found" << endl;

	root.setName (std::string ("system/elektra/modules/") + name + "/infos");
	k = conf.lookup (root);

	if (k)
	{
		while ((k = conf.next ()) && k.isBelow (root))
		{
			cout << k.getBaseName () << ": " << k.getString () << endl;
		}
	}
	else
		cout << "no information found" << endl;

	return 0;
}

InfoCommand::~InfoCommand ()
{
}
<|endoftext|>


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

#ifndef OOX_DRAWINGML_FILLPROPERTIESGROUPCONTEXT_HPP
#define OOX_DRAWINGML_FILLPROPERTIESGROUPCONTEXT_HPP

#ifndef _COM_SUN_STAR_DRAWING_FILLSTYLE_HPP_
#include <com/sun/star/drawing/FillStyle.hpp>
#endif

#ifndef OOX_CORE_CONTEXT_HXX
#include "oox/core/context.hxx"
#endif
#include "oox/drawingml/fillproperties.hxx"
#include <com/sun/star/drawing/BitmapMode.hpp>

namespace oox { namespace core {
    class PropertyMap;
} }

namespace oox { namespace drawingml {

// ---------------------------------------------------------------------

class FillPropertiesGroupContext : public ::oox::core::Context
{
public:
    FillPropertiesGroupContext( const oox::core::FragmentHandlerRef& xHandler, ::com::sun::star::drawing::FillStyle eFillStyle, ::oox::drawingml::FillProperties& rFillProperties ) throw();

    static ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XFastContextHandler > StaticCreateContext( const oox::core::FragmentHandlerRef& xHandler,
        ::sal_Int32 Element, const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XFastAttributeList >& Attribs, ::oox::drawingml::FillProperties& rFillProperties )
            throw (::com::sun::star::xml::sax::SAXException, ::com::sun::star::uno::RuntimeException );

protected:
    FillProperties& mrFillProperties;
};

// ---------------------------------------------------------------------

class BlipFillPropertiesContext : public FillPropertiesGroupContext
{
public:
    BlipFillPropertiesContext( const oox::core::FragmentHandlerRef& xHandler,
        const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XFastAttributeList >& xAttributes,
            ::oox::drawingml::FillProperties& rFillProperties ) throw();

    virtual void SAL_CALL endFastElement( sal_Int32 aElementToken )
        throw (::com::sun::star::xml::sax::SAXException, ::com::sun::star::uno::RuntimeException);
    virtual ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XFastContextHandler > SAL_CALL createFastChildContext( sal_Int32 aElementToken,
        const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XFastAttributeList >& xAttribs )
            throw ( ::com::sun::star::xml::sax::SAXException, ::com::sun::star::uno::RuntimeException);

private:
    ::com::sun::star::drawing::BitmapMode   meBitmapMode;
    sal_Int32       mnWidth, mnHeight;
    rtl::OUString   msEmbed;
    rtl::OUString   msLink;
};

} }

#endif // OOX_DRAWINGML_FILLPROPERTIESGROUPCONTEXT_HPP
<commit_msg>INTEGRATION: CWS xmlfilter03_DEV300 (1.2.4); FILE MERGED 2008/02/14 18:47:59 sj 1.2.4.3: completet gradient/tile fill 2008/02/12 17:40:58 sj 1.2.4.2: added gradient fillstyle 2008/02/04 13:31:33 dr 1.2.4.1: rework of fragment handler/context handler base classes<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: fillpropertiesgroupcontext.hxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: kz $ $Date: 2008-03-05 17:40:41 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#ifndef OOX_DRAWINGML_FILLPROPERTIESGROUPCONTEXT_HPP
#define OOX_DRAWINGML_FILLPROPERTIESGROUPCONTEXT_HPP

#include "oox/core/contexthandler.hxx"
#include "oox/drawingml/fillproperties.hxx"

namespace oox { namespace core {
    class PropertyMap;
} }

namespace oox { namespace drawingml {

// ---------------------------------------------------------------------

class FillPropertiesGroupContext : public ::oox::core::ContextHandler
{
public:
    FillPropertiesGroupContext( oox::core::ContextHandler& rParent, ::com::sun::star::drawing::FillStyle eFillStyle, FillProperties& rFillProperties ) throw();

    static ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XFastContextHandler > StaticCreateContext( oox::core::ContextHandler& rParent,
        ::sal_Int32 Element, const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XFastAttributeList >& Attribs, FillProperties& rFillProperties )
            throw (::com::sun::star::xml::sax::SAXException, ::com::sun::star::uno::RuntimeException );

protected:
    FillProperties& mrFillProperties;
};

// ---------------------------------------------------------------------

class BlipFillPropertiesContext : public FillPropertiesGroupContext
{
public:
    BlipFillPropertiesContext( oox::core::ContextHandler& rParent,
        const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XFastAttributeList >& xAttributes,
            FillProperties& rFillProperties ) throw();

    virtual void SAL_CALL endFastElement( sal_Int32 aElementToken )
        throw (::com::sun::star::xml::sax::SAXException, ::com::sun::star::uno::RuntimeException);
    virtual ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XFastContextHandler > SAL_CALL createFastChildContext( sal_Int32 aElementToken,
        const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XFastAttributeList >& xAttribs )
            throw ( ::com::sun::star::xml::sax::SAXException, ::com::sun::star::uno::RuntimeException);

private:
    ::com::sun::star::drawing::BitmapMode   meBitmapMode;
    rtl::OUString   msEmbed;
    rtl::OUString   msLink;
};

} }

#endif // OOX_DRAWINGML_FILLPROPERTIESGROUPCONTEXT_HPP
<|endoftext|>


<commit_before>/* IBM_PROLOG_BEGIN_TAG                                                   */
/* This is an automatically generated prolog.                             */
/*                                                                        */
/* $Source: src/import/chips/p9/procedures/hwp/initfiles/p9_fbc_ioe_dl_scom.C $ */
/*                                                                        */
/* OpenPOWER HostBoot Project                                             */
/*                                                                        */
/* Contributors Listed Below - COPYRIGHT 2016,2019                        */
/* [+] International Business Machines Corp.                              */
/*                                                                        */
/*                                                                        */
/* Licensed under the Apache License, Version 2.0 (the "License");        */
/* you may not use this file except in compliance with the License.       */
/* You may obtain a copy of the License at                                */
/*                                                                        */
/*     http://www.apache.org/licenses/LICENSE-2.0                         */
/*                                                                        */
/* Unless required by applicable law or agreed to in writing, software    */
/* distributed under the License is distributed on an "AS IS" BASIS,      */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or        */
/* implied. See the License for the specific language governing           */
/* permissions and limitations under the License.                         */
/*                                                                        */
/* IBM_PROLOG_END_TAG                                                     */
#include "p9_fbc_ioe_dl_scom.H"
#include <stdint.h>
#include <stddef.h>
#include <fapi2.H>

using namespace fapi2;

constexpr uint64_t literal_1 = 1;
constexpr uint64_t literal_0x0B = 0x0B;
constexpr uint64_t literal_0xF = 0xF;
constexpr uint64_t literal_0b111 = 0b111;
constexpr uint64_t literal_0x6 = 0x6;
constexpr uint64_t literal_0x7 = 0x7;

fapi2::ReturnCode p9_fbc_ioe_dl_scom(const fapi2::Target<fapi2::TARGET_TYPE_XBUS>& TGT0,
                                     const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& TGT1)
{
    {
        fapi2::ATTR_EC_Type   l_chip_ec;
        fapi2::ATTR_NAME_Type l_chip_id;
        FAPI_TRY(FAPI_ATTR_GET_PRIVILEGED(fapi2::ATTR_NAME, TGT1, l_chip_id));
        FAPI_TRY(FAPI_ATTR_GET_PRIVILEGED(fapi2::ATTR_EC, TGT1, l_chip_ec));
        fapi2::ATTR_LINK_TRAIN_Type l_TGT0_ATTR_LINK_TRAIN;
        FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_LINK_TRAIN, TGT0, l_TGT0_ATTR_LINK_TRAIN));
        fapi2::buffer<uint64_t> l_scom_buffer;
        {
            FAPI_TRY(fapi2::getScom( TGT0, 0x601180aull, l_scom_buffer ));

            if ((l_TGT0_ATTR_LINK_TRAIN == fapi2::ENUM_ATTR_LINK_TRAIN_BOTH))
            {
                constexpr auto l_PB_IOE_LL1_CONFIG_LINK_PAIR_ON = 0x1;
                l_scom_buffer.insert<0, 1, 63, uint64_t>(l_PB_IOE_LL1_CONFIG_LINK_PAIR_ON );
            }
            else if (literal_1)
            {
                constexpr auto l_PB_IOE_LL1_CONFIG_LINK_PAIR_OFF = 0x0;
                l_scom_buffer.insert<0, 1, 63, uint64_t>(l_PB_IOE_LL1_CONFIG_LINK_PAIR_OFF );
            }

            constexpr auto l_PB_IOE_LL1_CONFIG_CRC_LANE_ID_ON = 0x1;
            l_scom_buffer.insert<2, 1, 63, uint64_t>(l_PB_IOE_LL1_CONFIG_CRC_LANE_ID_ON );

            if (((l_chip_id == 0x5) && (l_chip_ec == 0x10)) )
            {
                l_scom_buffer.insert<12, 4, 60, uint64_t>(literal_0x0B );
            }
            else if (((l_chip_id == 0x5) && (l_chip_ec == 0x20)) || ((l_chip_id == 0x5) && (l_chip_ec == 0x21))
                     || ((l_chip_id == 0x5) && (l_chip_ec == 0x22)) || ((l_chip_id == 0x5) && (l_chip_ec == 0x23)) || ((l_chip_id == 0x6)
                             && (l_chip_ec == 0x10)) || ((l_chip_id == 0x6) && (l_chip_ec == 0x11)) || ((l_chip_id == 0x6) && (l_chip_ec == 0x12))
                     || ((l_chip_id == 0x6) && (l_chip_ec == 0x13)) || ((l_chip_id == 0x7) && (l_chip_ec == 0x10)) )
            {
                l_scom_buffer.insert<11, 5, 59, uint64_t>(literal_0x0B );
            }

            l_scom_buffer.insert<28, 4, 60, uint64_t>(literal_0xF );
            constexpr auto l_PB_IOE_LL1_CONFIG_SL_UE_CRC_ERR_ON = 0x1;
            l_scom_buffer.insert<4, 1, 63, uint64_t>(l_PB_IOE_LL1_CONFIG_SL_UE_CRC_ERR_ON );
            FAPI_TRY(fapi2::putScom(TGT0, 0x601180aull, l_scom_buffer));
        }
        {
            FAPI_TRY(fapi2::getScom( TGT0, 0x6011818ull, l_scom_buffer ));

            l_scom_buffer.insert<8, 3, 61, uint64_t>(literal_0b111 );
            l_scom_buffer.insert<4, 4, 60, uint64_t>(literal_0xF );
            l_scom_buffer.insert<0, 4, 60, uint64_t>(literal_0x6 );
            FAPI_TRY(fapi2::putScom(TGT0, 0x6011818ull, l_scom_buffer));
        }
        {
            FAPI_TRY(fapi2::getScom( TGT0, 0x6011819ull, l_scom_buffer ));

            if (((l_chip_id == 0x5) && (l_chip_ec == 0x10)) )
            {
                l_scom_buffer.insert<8, 2, 62, uint64_t>(literal_0b111 );
            }
            else if (((l_chip_id == 0x5) && (l_chip_ec == 0x20)) || ((l_chip_id == 0x5) && (l_chip_ec == 0x21))
                     || ((l_chip_id == 0x5) && (l_chip_ec == 0x22)) || ((l_chip_id == 0x5) && (l_chip_ec == 0x23)) || ((l_chip_id == 0x6)
                             && (l_chip_ec == 0x10)) || ((l_chip_id == 0x6) && (l_chip_ec == 0x11)) || ((l_chip_id == 0x6) && (l_chip_ec == 0x12))
                     || ((l_chip_id == 0x6) && (l_chip_ec == 0x13)) || ((l_chip_id == 0x7) && (l_chip_ec == 0x10)) )
            {
                l_scom_buffer.insert<8, 3, 61, uint64_t>(literal_0b111 );
            }

            l_scom_buffer.insert<4, 4, 60, uint64_t>(literal_0xF );
            l_scom_buffer.insert<0, 4, 60, uint64_t>(literal_0x7 );
            FAPI_TRY(fapi2::putScom(TGT0, 0x6011819ull, l_scom_buffer));
        }

    };
fapi_try_exit:
    return fapi2::current_err;
}
<commit_msg>initCompiler updates<commit_after>/* IBM_PROLOG_BEGIN_TAG                                                   */
/* This is an automatically generated prolog.                             */
/*                                                                        */
/* $Source: src/import/chips/p9/procedures/hwp/initfiles/p9_fbc_ioe_dl_scom.C $ */
/*                                                                        */
/* OpenPOWER HostBoot Project                                             */
/*                                                                        */
/* Contributors Listed Below - COPYRIGHT 2016,2019                        */
/* [+] International Business Machines Corp.                              */
/*                                                                        */
/*                                                                        */
/* Licensed under the Apache License, Version 2.0 (the "License");        */
/* you may not use this file except in compliance with the License.       */
/* You may obtain a copy of the License at                                */
/*                                                                        */
/*     http://www.apache.org/licenses/LICENSE-2.0                         */
/*                                                                        */
/* Unless required by applicable law or agreed to in writing, software    */
/* distributed under the License is distributed on an "AS IS" BASIS,      */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or        */
/* implied. See the License for the specific language governing           */
/* permissions and limitations under the License.                         */
/*                                                                        */
/* IBM_PROLOG_END_TAG                                                     */
#include "p9_fbc_ioe_dl_scom.H"
#include <stdint.h>
#include <stddef.h>
#include <fapi2.H>

using namespace fapi2;

constexpr uint64_t literal_1 = 1;
constexpr uint64_t literal_0x0B = 0x0B;
constexpr uint64_t literal_0xF = 0xF;
constexpr uint64_t literal_0b111 = 0b111;
constexpr uint64_t literal_0x6 = 0x6;
constexpr uint64_t literal_0x7 = 0x7;

fapi2::ReturnCode p9_fbc_ioe_dl_scom(const fapi2::Target<fapi2::TARGET_TYPE_XBUS>& TGT0,
                                     const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& TGT1)
{
    {
        fapi2::ATTR_EC_Type   l_chip_ec;
        fapi2::ATTR_NAME_Type l_chip_id;
        FAPI_TRY(FAPI_ATTR_GET_PRIVILEGED(fapi2::ATTR_NAME, TGT1, l_chip_id));
        FAPI_TRY(FAPI_ATTR_GET_PRIVILEGED(fapi2::ATTR_EC, TGT1, l_chip_ec));
        fapi2::ATTR_LINK_TRAIN_Type l_TGT0_ATTR_LINK_TRAIN;
        FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_LINK_TRAIN, TGT0, l_TGT0_ATTR_LINK_TRAIN));
        fapi2::buffer<uint64_t> l_scom_buffer;
        {
            FAPI_TRY(fapi2::getScom( TGT0, 0x601180aull, l_scom_buffer ));

            if ((l_TGT0_ATTR_LINK_TRAIN == fapi2::ENUM_ATTR_LINK_TRAIN_BOTH))
            {
                constexpr auto l_PB_IOE_LL1_CONFIG_LINK_PAIR_ON = 0x1;
                l_scom_buffer.insert<0, 1, 63, uint64_t>(l_PB_IOE_LL1_CONFIG_LINK_PAIR_ON );
            }
            else if (literal_1)
            {
                constexpr auto l_PB_IOE_LL1_CONFIG_LINK_PAIR_OFF = 0x0;
                l_scom_buffer.insert<0, 1, 63, uint64_t>(l_PB_IOE_LL1_CONFIG_LINK_PAIR_OFF );
            }

            constexpr auto l_PB_IOE_LL1_CONFIG_CRC_LANE_ID_ON = 0x1;
            l_scom_buffer.insert<2, 1, 63, uint64_t>(l_PB_IOE_LL1_CONFIG_CRC_LANE_ID_ON );

            if (((l_chip_id == 0x5) && (l_chip_ec == 0x20)) || ((l_chip_id == 0x5) && (l_chip_ec == 0x21)) || ((l_chip_id == 0x5)
                    && (l_chip_ec == 0x22)) || ((l_chip_id == 0x5) && (l_chip_ec == 0x23)) || ((l_chip_id == 0x6) && (l_chip_ec == 0x10))
                || ((l_chip_id == 0x6) && (l_chip_ec == 0x11)) || ((l_chip_id == 0x6) && (l_chip_ec == 0x12)) || ((l_chip_id == 0x6)
                        && (l_chip_ec == 0x13)) || ((l_chip_id == 0x7) && (l_chip_ec == 0x10)) )
            {
                l_scom_buffer.insert<11, 5, 59, uint64_t>(literal_0x0B );
            }

            if (((l_chip_id == 0x5) && (l_chip_ec == 0x10)) )
            {
                l_scom_buffer.insert<12, 4, 60, uint64_t>(literal_0x0B );
            }

            l_scom_buffer.insert<28, 4, 60, uint64_t>(literal_0xF );
            constexpr auto l_PB_IOE_LL1_CONFIG_SL_UE_CRC_ERR_ON = 0x1;
            l_scom_buffer.insert<4, 1, 63, uint64_t>(l_PB_IOE_LL1_CONFIG_SL_UE_CRC_ERR_ON );
            FAPI_TRY(fapi2::putScom(TGT0, 0x601180aull, l_scom_buffer));
        }
        {
            FAPI_TRY(fapi2::getScom( TGT0, 0x6011818ull, l_scom_buffer ));

            l_scom_buffer.insert<8, 3, 61, uint64_t>(literal_0b111 );
            l_scom_buffer.insert<4, 4, 60, uint64_t>(literal_0xF );
            l_scom_buffer.insert<0, 4, 60, uint64_t>(literal_0x6 );
            FAPI_TRY(fapi2::putScom(TGT0, 0x6011818ull, l_scom_buffer));
        }
        {
            FAPI_TRY(fapi2::getScom( TGT0, 0x6011819ull, l_scom_buffer ));

            if (((l_chip_id == 0x5) && (l_chip_ec == 0x20)) || ((l_chip_id == 0x5) && (l_chip_ec == 0x21)) || ((l_chip_id == 0x5)
                    && (l_chip_ec == 0x22)) || ((l_chip_id == 0x5) && (l_chip_ec == 0x23)) || ((l_chip_id == 0x6) && (l_chip_ec == 0x10))
                || ((l_chip_id == 0x6) && (l_chip_ec == 0x11)) || ((l_chip_id == 0x6) && (l_chip_ec == 0x12)) || ((l_chip_id == 0x6)
                        && (l_chip_ec == 0x13)) || ((l_chip_id == 0x7) && (l_chip_ec == 0x10)) )
            {
                l_scom_buffer.insert<8, 3, 61, uint64_t>(literal_0b111 );
            }

            if (((l_chip_id == 0x5) && (l_chip_ec == 0x10)) )
            {
                l_scom_buffer.insert<8, 2, 62, uint64_t>(literal_0b111 );
            }

            l_scom_buffer.insert<4, 4, 60, uint64_t>(literal_0xF );
            l_scom_buffer.insert<0, 4, 60, uint64_t>(literal_0x7 );
            FAPI_TRY(fapi2::putScom(TGT0, 0x6011819ull, l_scom_buffer));
        }

    };
fapi_try_exit:
    return fapi2::current_err;
}
<|endoftext|>


<commit_before><commit_msg>endo prezi 100%<commit_after><|endoftext|>


<commit_before>// RUN: %clangxx_tsan -O1 %s -o %t && not %t 2>&1 | FileCheck %s
#include <pthread.h>
#include <semaphore.h>
#include <stdio.h>
#include <unistd.h>

struct A {
  A() {
    sem_init(&sem_, 0, 0);
  }
  virtual void F() {
  }
  void Done() {
    sem_post(&sem_);
  }
  virtual ~A() {
    sem_wait(&sem_);
    sem_destroy(&sem_);
  }
  sem_t sem_;
};

struct B : A {
  virtual void F() {
  }
  virtual ~B() { }
};

static A *obj = new B;
static void (A::*fn)() = &A::F;

void *Thread1(void *x) {
  sleep(1);
  (obj->*fn)();
  obj->Done();
  return NULL;
}

void *Thread2(void *x) {
  delete obj;
  return NULL;
}

int main() {
  pthread_t t[2];
  pthread_create(&t[0], NULL, Thread1, NULL);
  pthread_create(&t[1], NULL, Thread2, NULL);
  pthread_join(t[0], NULL);
  pthread_join(t[1], NULL);
}

// CHECK: WARNING: ThreadSanitizer: data race

// but should be:
// WARNING: ThreadSanitizer: data race on vptr
// see http://llvm.org/bugs/show_bug.cgi?id=19113

<commit_msg>tsan: update the test since the bug is fixed http://llvm.org/bugs/show_bug.cgi?id=19113 is fixed, so enable the better CHECK<commit_after>// RUN: %clangxx_tsan -O1 %s -o %t && not %t 2>&1 | FileCheck %s
#include <pthread.h>
#include <semaphore.h>
#include <stdio.h>
#include <unistd.h>

struct A {
  A() {
    sem_init(&sem_, 0, 0);
  }
  virtual void F() {
  }
  void Done() {
    sem_post(&sem_);
  }
  virtual ~A() {
    sem_wait(&sem_);
    sem_destroy(&sem_);
  }
  sem_t sem_;
};

struct B : A {
  virtual void F() {
  }
  virtual ~B() { }
};

static A *obj = new B;
static void (A::*fn)() = &A::F;

void *Thread1(void *x) {
  sleep(1);
  (obj->*fn)();
  obj->Done();
  return NULL;
}

void *Thread2(void *x) {
  delete obj;
  return NULL;
}

int main() {
  pthread_t t[2];
  pthread_create(&t[0], NULL, Thread1, NULL);
  pthread_create(&t[1], NULL, Thread2, NULL);
  pthread_join(t[0], NULL);
  pthread_join(t[1], NULL);
}

// CHECK: WARNING: ThreadSanitizer: data race on vptr

<|endoftext|>


<commit_before>/** \brief Utility for updating SQL schemata etc.
 *  \author Dr. Johannes Ruscheinski (johannes.ruscheinski@uni-tuebingen.de)
 *
 *  \copyright 2019 Universitätsbibliothek Tübingen.  All rights reserved.
 *
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU Affero General Public License as
 *  published by the Free Software Foundation, either version 3 of the
 *  License, or (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU Affero General Public License for more details.
 *
 *  You should have received a copy of the GNU Affero General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

#include <algorithm>
#include <iostream>
#include <stdexcept>
#include <vector>
#include <cstdio>
#include <cstdlib>
#include "Compiler.h"
#include "FileUtil.h"
#include "DbConnection.h"
#include "StringUtil.h"
#include "util.h"

namespace {

void SplitIntoDatabaseTableAndVersion(const std::string &update_filename, std::string * const database, std::string * const table,
                                      unsigned * const version)
{
    std::vector<std::string> parts;
    if (unlikely(StringUtil::Split(update_filename, '.', &parts) != 3))
        LOG_ERROR("failed to split \"" + update_filename + "\" into \"database.table.version\"!");
    *database = parts[0];
    *table    = parts[1];
    *version  = StringUtil::ToUnsigned(parts[2]);
}

__attribute__((__const__)) inline std::string GetFirstTableName(const std::string &compound_table_name) {
    const auto first_plus_pos(compound_table_name.find('+'));
    return (first_plus_pos == std::string::npos) ? compound_table_name : compound_table_name.substr(0, first_plus_pos);
}

// The filenames being compared are assumed to have the "structure database.table.version"
bool FileNameCompare(const std::string &filename1, const std::string &filename2) {
    std::string database1, table1;
    unsigned version1;
    SplitIntoDatabaseTableAndVersion(filename1, &database1, &table1, &version1);

    std::string database2, table2;
    unsigned version2;
    SplitIntoDatabaseTableAndVersion(filename2, &database2, &table2, &version2);

    // Compare database names:
    if (database1 < database2)
        return true;
    if (database1 > database2)
        return false;

    // Compare table names:
    if (GetFirstTableName(table1) < GetFirstTableName(table2))
        return true;
    if (GetFirstTableName(table1) > GetFirstTableName(table2))
        return false;

    return version1 < version2;
}

void LoadAndSortUpdateFilenames(const std::string &directory_path, std::vector<std::string> * const update_filenames) {
    FileUtil::Directory directory(directory_path, "[^.]+\\.[^.]+\\.\\d+");
    for (const auto &entry : directory)
        update_filenames->emplace_back(entry.getName());

    std::sort(update_filenames->begin(), update_filenames->end(), FileNameCompare);
}

std::vector<std::string> GetAllTableNames(const std::string &compound_table_name) {
    std::vector<std::string> all_table_names;
    StringUtil::Split(compound_table_name, '+', &all_table_names);
    return all_table_names;
}

void ApplyUpdate(DbConnection * const db_connection, const std::string &update_directory_path, const std::string &update_filename) {
    std::string database, tables;
    unsigned update_version;
    SplitIntoDatabaseTableAndVersion(update_filename, &database, &tables, &update_version);

    db_connection->queryOrDie("START TRANSACTION");

    db_connection->queryFileOrDie(update_directory_path + "/" + update_filename);

    bool can_update(true);
    for (const auto &table : GetAllTableNames(tables)) {
        unsigned current_version(0);
        db_connection->queryOrDie("SELECT version FROM ub_tools.table_versions WHERE database_name='"
                                  + db_connection->escapeString(database) + "' AND table_name='" + db_connection->escapeString(table) + "'");
        DbResultSet result_set(db_connection->getLastResultSet());
        if (result_set.empty()) {
            db_connection->queryOrDie("INSERT INTO ub_tools.table_versions (database_name,table_name,version) VALUES ('"
                                      + db_connection->escapeString(database) + "','" + db_connection->escapeString(table) + "',0)");
            LOG_INFO("Created a new entry for " + database + "." + table + " in ub_tools.table_versions.");
        } else
            current_version = StringUtil::ToUnsigned(result_set.getNextRow()["version"]);
        if (update_version <= current_version) {
            if (unlikely(not can_update))
                LOG_ERROR("inconsistent updates for tables \"" + tables + "\"!");
            can_update = false;
            continue;
        }

        db_connection->queryOrDie("UPDATE ub_tools.table_versions SET version=" + std::to_string(update_version)
                                  + " WHERE database_name='" + db_connection->escapeString(database) + "' AND table_name='"
                                  + db_connection->escapeString(table) + "'");

        if (unlikely(update_version != current_version + 1))
            LOG_ERROR("update version is " + std::to_string(update_version) + ", current version is " + std::to_string(current_version)
                      + " for table \"" + database + "." + table + "\"!");

        LOG_INFO("applying update \"" + database + "." + table + "." + std::to_string(update_version) + "\".");
    }

    db_connection->queryOrDie("COMMIT");
}

} // unnamed namespace

int Main(int argc, char *argv[]) {
    if (argc != 2)
        ::Usage("[--verbose] update_directory_path");

    std::vector<std::string> update_filenames;
    const std::string update_directory_path(argv[1]);
    LoadAndSortUpdateFilenames(update_directory_path, &update_filenames);

    DbConnection db_connection;
    if (not db_connection.tableExists("ub_tools", "table_versions")) {
        db_connection.queryOrDie("CREATE TABLE ub_tools.table_versions (version INT UNSIGNED NOT NULL, database_name VARCHAR(64) NOT NULL, "
                                 "table_name VARCHAR(64) NOT NULL, UNIQUE(database_name,table_name)) "
                                 "CHARACTER SET utf8mb4 COLLATE utf8mb4_bin");
        LOG_INFO("Created the ub_tools.table_versions table.");
    }

    for (const auto &update_filename : update_filenames)
        ApplyUpdate(&db_connection, update_directory_path, update_filename);

    return EXIT_SUCCESS;
}
<commit_msg>Fixed ordering problem.<commit_after>/** \brief Utility for updating SQL schemata etc.
 *  \author Dr. Johannes Ruscheinski (johannes.ruscheinski@uni-tuebingen.de)
 *
 *  \copyright 2019 Universitätsbibliothek Tübingen.  All rights reserved.
 *
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU Affero General Public License as
 *  published by the Free Software Foundation, either version 3 of the
 *  License, or (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU Affero General Public License for more details.
 *
 *  You should have received a copy of the GNU Affero General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

#include <algorithm>
#include <iostream>
#include <stdexcept>
#include <vector>
#include <cstdio>
#include <cstdlib>
#include "Compiler.h"
#include "FileUtil.h"
#include "DbConnection.h"
#include "StringUtil.h"
#include "util.h"

namespace {

void SplitIntoDatabaseTableAndVersion(const std::string &update_filename, std::string * const database, std::string * const table,
                                      unsigned * const version)
{
    std::vector<std::string> parts;
    if (unlikely(StringUtil::Split(update_filename, '.', &parts) != 3))
        LOG_ERROR("failed to split \"" + update_filename + "\" into \"database.table.version\"!");
    *database = parts[0];
    *table    = parts[1];
    *version  = StringUtil::ToUnsigned(parts[2]);
}

__attribute__((__const__)) inline std::string GetFirstTableName(const std::string &compound_table_name) {
    const auto first_plus_pos(compound_table_name.find('+'));
    return (first_plus_pos == std::string::npos) ? compound_table_name : compound_table_name.substr(0, first_plus_pos);
}

// The filenames being compared are assumed to have the "structure database.table.version"
bool FileNameCompare(const std::string &filename1, const std::string &filename2) {
    std::string database1, table1;
    unsigned version1;
    SplitIntoDatabaseTableAndVersion(filename1, &database1, &table1, &version1);

    std::string database2, table2;
    unsigned version2;
    SplitIntoDatabaseTableAndVersion(filename2, &database2, &table2, &version2);

    // Compare database names:
    if (database1 < database2)
        return true;
    if (database1 > database2)
        return false;

    // Compare table names:
    if (GetFirstTableName(table1) < GetFirstTableName(table2))
        return true;
    if (GetFirstTableName(table1) > GetFirstTableName(table2))
        return false;

    return version1 < version2;
}

void LoadAndSortUpdateFilenames(const std::string &directory_path, std::vector<std::string> * const update_filenames) {
    FileUtil::Directory directory(directory_path, "[^.]+\\.[^.]+\\.\\d+");
    for (const auto &entry : directory)
        update_filenames->emplace_back(entry.getName());

    std::sort(update_filenames->begin(), update_filenames->end(), FileNameCompare);
}

std::vector<std::string> GetAllTableNames(const std::string &compound_table_name) {
    std::vector<std::string> all_table_names;
    StringUtil::Split(compound_table_name, '+', &all_table_names);
    return all_table_names;
}

void ApplyUpdate(DbConnection * const db_connection, const std::string &update_directory_path, const std::string &update_filename) {
    std::string database, tables;
    unsigned update_version;
    SplitIntoDatabaseTableAndVersion(update_filename, &database, &tables, &update_version);

    db_connection->queryOrDie("START TRANSACTION");

    bool can_update(true);
    for (const auto &table : GetAllTableNames(tables)) {
        unsigned current_version(0);
        db_connection->queryOrDie("SELECT version FROM ub_tools.table_versions WHERE database_name='"
                                  + db_connection->escapeString(database) + "' AND table_name='" + db_connection->escapeString(table) + "'");
        DbResultSet result_set(db_connection->getLastResultSet());
        if (result_set.empty()) {
            db_connection->queryOrDie("INSERT INTO ub_tools.table_versions (database_name,table_name,version) VALUES ('"
                                      + db_connection->escapeString(database) + "','" + db_connection->escapeString(table) + "',0)");
            LOG_INFO("Created a new entry for " + database + "." + table + " in ub_tools.table_versions.");
        } else
            current_version = StringUtil::ToUnsigned(result_set.getNextRow()["version"]);
        if (update_version <= current_version) {
            if (unlikely(not can_update))
                LOG_ERROR("inconsistent updates for tables \"" + tables + "\"!");
            can_update = false;
            continue;
        }

        db_connection->queryOrDie("UPDATE ub_tools.table_versions SET version=" + std::to_string(update_version)
                                  + " WHERE database_name='" + db_connection->escapeString(database) + "' AND table_name='"
                                  + db_connection->escapeString(table) + "'");

        if (unlikely(update_version != current_version + 1))
            LOG_ERROR("update version is " + std::to_string(update_version) + ", current version is " + std::to_string(current_version)
                      + " for table \"" + database + "." + table + "\"!");

        LOG_INFO("applying update \"" + database + "." + table + "." + std::to_string(update_version) + "\".");
    }

    if (can_update) {
        db_connection->queryFileOrDie(update_directory_path + "/" + update_filename);
        db_connection->queryOrDie("COMMIT");
    } else
        db_connection->queryOrDie("ROLLBACK");
}

} // unnamed namespace

int Main(int argc, char *argv[]) {
    if (argc != 2)
        ::Usage("[--verbose] update_directory_path");

    std::vector<std::string> update_filenames;
    const std::string update_directory_path(argv[1]);
    LoadAndSortUpdateFilenames(update_directory_path, &update_filenames);

    DbConnection db_connection;
    if (not db_connection.tableExists("ub_tools", "table_versions")) {
        db_connection.queryOrDie("CREATE TABLE ub_tools.table_versions (version INT UNSIGNED NOT NULL, database_name VARCHAR(64) NOT NULL, "
                                 "table_name VARCHAR(64) NOT NULL, UNIQUE(database_name,table_name)) "
                                 "CHARACTER SET utf8mb4 COLLATE utf8mb4_bin");
        LOG_INFO("Created the ub_tools.table_versions table.");
    }

    for (const auto &update_filename : update_filenames)
        ApplyUpdate(&db_connection, update_directory_path, update_filename);

    return EXIT_SUCCESS;
}
<|endoftext|>


<commit_before>/*************************************************************************
 * libjson-rpc-cpp
 *************************************************************************
 * @file    test_client.cpp
 * @date    28.09.2013
 * @author  Peter Spiess-Knafl <peter.knafl@gmail.com>
 * @license See attached LICENSE.txt
 ************************************************************************/

#define BOOST_TEST_MODULE

#include <boost/test/unit_test.hpp>
#include <jsonrpccpp/client.h>
#include "mockclientconnector.h"

using namespace jsonrpc;
using namespace std;

bool check_exception1(JsonRpcException const&ex)
{
    return ex.GetCode() == Errors::ERROR_RPC_JSON_PARSE_ERROR;
}

bool check_exception2(JsonRpcException const&ex)
{
    return ex.GetCode() == Errors::ERROR_CLIENT_INVALID_RESPONSE;
}

bool check_exception3(JsonRpcException const&ex)
{
    return ex.GetCode() == Errors::ERROR_RPC_INVALID_REQUEST;
}

BOOST_AUTO_TEST_SUITE(client)

BOOST_AUTO_TEST_CASE(test_client_method_success)
{
    MockClientConnector c;
    Client client(c);

    Json::Value params;
    params.append(23);
    c.SetResponse("{\"jsonrpc\":\"2.0\", \"id\": 1, \"result\": 23}");

    Json::Value response = client.CallMethod("abcd", params);
    Json::Value v = c.GetJsonRequest();

    BOOST_CHECK_EQUAL(v["method"].asString(), "abcd");
    BOOST_CHECK_EQUAL(v["params"][0].asInt(), 23);
    BOOST_CHECK_EQUAL(v["jsonrpc"].asString(), "2.0");
    BOOST_CHECK_EQUAL(v["id"].asInt(), 1);

    BOOST_CHECK_EQUAL(response.asInt(),23);
}

BOOST_AUTO_TEST_CASE(test_client_notification_success)
{
    MockClientConnector c;
    Client client(c);

    Json::Value params;
    params.append(23);

    client.CallNotification("abcd", params);

    Json::Value v = c.GetJsonRequest();

    BOOST_CHECK_EQUAL(v["method"].asString(), "abcd");
    BOOST_CHECK_EQUAL(v["params"][0].asInt(), 23);
    BOOST_CHECK_EQUAL(v["jsonrpc"].asString(), "2.0");
    BOOST_CHECK_EQUAL(v.isMember("id"), false);
}

BOOST_AUTO_TEST_CASE(test_client_error)
{
    MockClientConnector c;
    Client client(c);

    c.SetResponse("{\"jsonrpc\":\"2.0\", \"error\": {\"code\": -32600, \"message\": \"Invalid Request\"}, \"id\": null}");
    BOOST_CHECK_EXCEPTION(client.CallMethod("abcd", Json::nullValue), JsonRpcException, check_exception3);
}

BOOST_AUTO_TEST_CASE(test_client_invalidjson)
{
    MockClientConnector c;
    Client client(c);
    c.SetResponse("{\"method\":234");
    BOOST_CHECK_EXCEPTION(client.CallMethod("abcd", Json::nullValue), JsonRpcException, check_exception1);
}

BOOST_AUTO_TEST_CASE(test_client_invalidresponse)
{
    MockClientConnector c;
    Client client(c);

    c.SetResponse("{\"jsonrpc\":\"2.0\", \"id\": 1, \"resulto\": 23}");
    BOOST_CHECK_EXCEPTION(client.CallMethod("abcd", Json::nullValue), JsonRpcException, check_exception2);
    c.SetResponse("{\"jsonrpc\":\"2.0\", \"id2\": 1, \"result\": 23}");
    BOOST_CHECK_EXCEPTION(client.CallMethod("abcd", Json::nullValue), JsonRpcException, check_exception2);
    c.SetResponse("{\"jsonrpc\":\"1.0\", \"id\": 1, \"result\": 23}");
    BOOST_CHECK_EXCEPTION(client.CallMethod("abcd", Json::nullValue), JsonRpcException, check_exception2);
    c.SetResponse("{\"id\": 1, \"result\": 23}");
    BOOST_CHECK_EXCEPTION(client.CallMethod("abcd", Json::nullValue), JsonRpcException, check_exception2);
    c.SetResponse("{\"jsonrpc\":\"2.0\", \"result\": 23}");
    BOOST_CHECK_EXCEPTION(client.CallMethod("abcd", Json::nullValue), JsonRpcException, check_exception2);
    c.SetResponse("{}");
    BOOST_CHECK_EXCEPTION(client.CallMethod("abcd", Json::nullValue), JsonRpcException, check_exception2);
    c.SetResponse("[]");
    BOOST_CHECK_EXCEPTION(client.CallMethod("abcd", Json::nullValue), JsonRpcException, check_exception2);
    c.SetResponse("23");
    BOOST_CHECK_EXCEPTION(client.CallMethod("abcd", Json::nullValue), JsonRpcException, check_exception2);
}

BOOST_AUTO_TEST_CASE(test_client_batchcall_success)
{
    MockClientConnector c;
    Client client(c);

    BatchCall bc;
    BOOST_CHECK_EQUAL(bc.addCall("abc", Json::nullValue, false),1);
    BOOST_CHECK_EQUAL(bc.addCall("def", Json::nullValue, true), -1);
    BOOST_CHECK_EQUAL(bc.addCall("abc", Json::nullValue, false),2);

    c.SetResponse("[{\"jsonrpc\":\"2.0\", \"id\": 1, \"result\": 23},{\"jsonrpc\":\"2.0\", \"id\": 2, \"result\": 24}]");

    BatchResponse response = client.CallProcedures(bc);

    BOOST_CHECK_EQUAL(response.hasErrors(), false);
    BOOST_CHECK_EQUAL(response.getResult(1).asInt(), 23);
    BOOST_CHECK_EQUAL(response.getResult(2).asInt(), 24);
    BOOST_CHECK_EQUAL(response.getResult(3).isNull(),true);
}

BOOST_AUTO_TEST_CASE(test_client_batchcall_error)
{
    MockClientConnector c;
    Client client(c);

    BatchCall bc;
    BOOST_CHECK_EQUAL(bc.addCall("abc", Json::nullValue, false),1);
    BOOST_CHECK_EQUAL(bc.addCall("def", Json::nullValue, false),2);
    BOOST_CHECK_EQUAL(bc.addCall("abc", Json::nullValue, false),3);

    c.SetResponse("[{\"jsonrpc\":\"2.0\", \"id\": 1, \"result\": 23},{\"jsonrpc\":\"2.0\", \"id\": 2, \"error\": {\"code\": -32001, \"message\": \"error1\"}},{\"jsonrpc\":\"2.0\", \"id\": null, \"error\": {\"code\": -32002, \"message\": \"error2\"}}]");

    BatchResponse response = client.CallProcedures(bc);

    BOOST_CHECK_EQUAL(response.hasErrors(), true);
    BOOST_CHECK_EQUAL(response.getResult(1).asInt(), 23);
    BOOST_CHECK_EQUAL(response.getResult(2).isNull(), true);
    BOOST_CHECK_EQUAL(response.getResult(3).isNull(),true);
}

BOOST_AUTO_TEST_SUITE_END()
<commit_msg>extended batchcall testcases<commit_after>/*************************************************************************
 * libjson-rpc-cpp
 *************************************************************************
 * @file    test_client.cpp
 * @date    28.09.2013
 * @author  Peter Spiess-Knafl <peter.knafl@gmail.com>
 * @license See attached LICENSE.txt
 ************************************************************************/

#define BOOST_TEST_MODULE

#include <boost/test/unit_test.hpp>
#include <jsonrpccpp/client.h>
#include "mockclientconnector.h"

using namespace jsonrpc;
using namespace std;

bool check_exception1(JsonRpcException const&ex)
{
    return ex.GetCode() == Errors::ERROR_RPC_JSON_PARSE_ERROR;
}

bool check_exception2(JsonRpcException const&ex)
{
    return ex.GetCode() == Errors::ERROR_CLIENT_INVALID_RESPONSE;
}

bool check_exception3(JsonRpcException const&ex)
{
    return ex.GetCode() == Errors::ERROR_RPC_INVALID_REQUEST;
}

BOOST_AUTO_TEST_SUITE(client)

BOOST_AUTO_TEST_CASE(test_client_method_success)
{
    MockClientConnector c;
    Client client(c);

    Json::Value params;
    params.append(23);
    c.SetResponse("{\"jsonrpc\":\"2.0\", \"id\": 1, \"result\": 23}");

    Json::Value response = client.CallMethod("abcd", params);
    Json::Value v = c.GetJsonRequest();

    BOOST_CHECK_EQUAL(v["method"].asString(), "abcd");
    BOOST_CHECK_EQUAL(v["params"][0].asInt(), 23);
    BOOST_CHECK_EQUAL(v["jsonrpc"].asString(), "2.0");
    BOOST_CHECK_EQUAL(v["id"].asInt(), 1);

    BOOST_CHECK_EQUAL(response.asInt(),23);
}

BOOST_AUTO_TEST_CASE(test_client_notification_success)
{
    MockClientConnector c;
    Client client(c);

    Json::Value params;
    params.append(23);

    client.CallNotification("abcd", params);

    Json::Value v = c.GetJsonRequest();

    BOOST_CHECK_EQUAL(v["method"].asString(), "abcd");
    BOOST_CHECK_EQUAL(v["params"][0].asInt(), 23);
    BOOST_CHECK_EQUAL(v["jsonrpc"].asString(), "2.0");
    BOOST_CHECK_EQUAL(v.isMember("id"), false);
}

BOOST_AUTO_TEST_CASE(test_client_error)
{
    MockClientConnector c;
    Client client(c);

    c.SetResponse("{\"jsonrpc\":\"2.0\", \"error\": {\"code\": -32600, \"message\": \"Invalid Request\"}, \"id\": null}");
    BOOST_CHECK_EXCEPTION(client.CallMethod("abcd", Json::nullValue), JsonRpcException, check_exception3);
}

BOOST_AUTO_TEST_CASE(test_client_invalidjson)
{
    MockClientConnector c;
    Client client(c);
    c.SetResponse("{\"method\":234");
    BOOST_CHECK_EXCEPTION(client.CallMethod("abcd", Json::nullValue), JsonRpcException, check_exception1);
}

BOOST_AUTO_TEST_CASE(test_client_invalidresponse)
{
    MockClientConnector c;
    Client client(c);

    c.SetResponse("{\"jsonrpc\":\"2.0\", \"id\": 1, \"resulto\": 23}");
    BOOST_CHECK_EXCEPTION(client.CallMethod("abcd", Json::nullValue), JsonRpcException, check_exception2);
    c.SetResponse("{\"jsonrpc\":\"2.0\", \"id2\": 1, \"result\": 23}");
    BOOST_CHECK_EXCEPTION(client.CallMethod("abcd", Json::nullValue), JsonRpcException, check_exception2);
    c.SetResponse("{\"jsonrpc\":\"1.0\", \"id\": 1, \"result\": 23}");
    BOOST_CHECK_EXCEPTION(client.CallMethod("abcd", Json::nullValue), JsonRpcException, check_exception2);
    c.SetResponse("{\"id\": 1, \"result\": 23}");
    BOOST_CHECK_EXCEPTION(client.CallMethod("abcd", Json::nullValue), JsonRpcException, check_exception2);
    c.SetResponse("{\"jsonrpc\":\"2.0\", \"result\": 23}");
    BOOST_CHECK_EXCEPTION(client.CallMethod("abcd", Json::nullValue), JsonRpcException, check_exception2);
    c.SetResponse("{}");
    BOOST_CHECK_EXCEPTION(client.CallMethod("abcd", Json::nullValue), JsonRpcException, check_exception2);
    c.SetResponse("[]");
    BOOST_CHECK_EXCEPTION(client.CallMethod("abcd", Json::nullValue), JsonRpcException, check_exception2);
    c.SetResponse("23");
    BOOST_CHECK_EXCEPTION(client.CallMethod("abcd", Json::nullValue), JsonRpcException, check_exception2);
}

BOOST_AUTO_TEST_CASE(test_client_batchcall_success)
{
    MockClientConnector c;
    Client client(c);

    BatchCall bc;
    BOOST_CHECK_EQUAL(bc.addCall("abc", Json::nullValue, false),1);
    BOOST_CHECK_EQUAL(bc.addCall("def", Json::nullValue, true), -1);
    BOOST_CHECK_EQUAL(bc.addCall("abc", Json::nullValue, false),2);

    c.SetResponse("[{\"jsonrpc\":\"2.0\", \"id\": 1, \"result\": 23},{\"jsonrpc\":\"2.0\", \"id\": 2, \"result\": 24}]");

    BatchResponse response = client.CallProcedures(bc);

    BOOST_CHECK_EQUAL(response.hasErrors(), false);
    BOOST_CHECK_EQUAL(response.getResult(1).asInt(), 23);
    BOOST_CHECK_EQUAL(response.getResult(2).asInt(), 24);
    BOOST_CHECK_EQUAL(response.getResult(3).isNull(),true);

    Json::Value request = c.GetJsonRequest();
    BOOST_CHECK_EQUAL(request.size(), 3);
    BOOST_CHECK_EQUAL(request[0]["method"].asString(), "abc");
    BOOST_CHECK_EQUAL(request[0]["id"].asInt(), 1);
    BOOST_CHECK_EQUAL(request[1]["method"].asString(), "def");
    BOOST_CHECK_EQUAL(request[1]["id"].isNull(), true);
    BOOST_CHECK_EQUAL(request[2]["id"].asInt(), 2);
}

BOOST_AUTO_TEST_CASE(test_client_batchcall_error)
{
    MockClientConnector c;
    Client client(c);

    BatchCall bc;
    BOOST_CHECK_EQUAL(bc.addCall("abc", Json::nullValue, false),1);
    BOOST_CHECK_EQUAL(bc.addCall("def", Json::nullValue, false),2);
    BOOST_CHECK_EQUAL(bc.addCall("abc", Json::nullValue, false),3);

    c.SetResponse("[{\"jsonrpc\":\"2.0\", \"id\": 1, \"result\": 23},{\"jsonrpc\":\"2.0\", \"id\": 2, \"error\": {\"code\": -32001, \"message\": \"error1\"}},{\"jsonrpc\":\"2.0\", \"id\": null, \"error\": {\"code\": -32002, \"message\": \"error2\"}}]");

    BatchResponse response = client.CallProcedures(bc);

    BOOST_CHECK_EQUAL(response.hasErrors(), true);
    BOOST_CHECK_EQUAL(response.getResult(1).asInt(), 23);
    BOOST_CHECK_EQUAL(response.getResult(2).isNull(), true);
    BOOST_CHECK_EQUAL(response.getResult(3).isNull(),true);
}

BOOST_AUTO_TEST_SUITE_END()
<|endoftext|>


<commit_before>#include <iostream>
#include <vector>

using namespace std;

struct Input {
	int r, c, l, h;
	vector<vector<bool>> tomatoes;
};

struct Slice {
	int r1, c1, r2, c2;
};

struct Output {
	vector<Slice> slices;
};

void solveSimple(Input& input, Output& output) {
	//TODO add code here
}

void solveDP(Input& input, Output& output) {
	//TODO add code here
}

int main() {
	ios::sync_with_stdio(false);

	//read input
	Input input;
	cin >> input.r >> input.c >> input.l >> input.h;
	for(int i = 0; i < input.r; i++) {
		vector<bool> row(input.c);
		for(int j = 0; j < input.c; j++) {
			char cell;
			cin >> cell;
			row[j] = cell == 'T';
		}
		input.tomatoes.push_back(row);
		//TODO do we read line breaks?
	}

	//solve problem
	Output output;
	solve(input, output);

	//print output
	cout << output.slices.size() << endl;

};
<commit_msg>Added simple slice function that cuts pizza row by row with stencil size dimension 1 x H<commit_after>#include <iostream>
#include <vector>

using namespace std;

struct Input {
	int r, c, l, h;
	vector<vector<bool>> tomatoes;
};

struct Slice {
	int r1, c1, r2, c2;
};

struct Output {
	vector<Slice> slices;
};

void solveSimple(Input& input, Output& output) {
	for (int i = 0; i < input.r; i++)
	{
		for (int j = 0; j < input.c; j += input.h)
		{
			Slice s;
			s.r1 = i;
			s.c1 = j;
			s.r2 = i;
			s.c2 = min(j+input.h-1, input.c-1);
			output.slices.push_back(s);
		}
	}
}

void solveDP(Input& input, Output& output) {
	//TODO add code here
}

int main() {
	ios::sync_with_stdio(false);

	//read input
	Input input;
	cin >> input.r >> input.c >> input.l >> input.h;
	for(int i = 0; i < input.r; i++) {
		vector<bool> row(input.c);
		for(int j = 0; j < input.c; j++) {
			char cell;
			cin >> cell;
			row[j] = cell == 'T';
		}
		input.tomatoes.push_back(row);
		//TODO do we read line breaks?
	}

	//solve problem
	Output output;
	solve(input, output);

	//print output
	cout << output.slices.size() << endl;

};
<|endoftext|>


<commit_before>/* IBM_PROLOG_BEGIN_TAG                                                   */
/* This is an automatically generated prolog.                             */
/*                                                                        */
/* $Source: src/import/chips/p9/procedures/hwp/pm/p9_pm_occ_sram_init.C $ */
/*                                                                        */
/* OpenPOWER HostBoot Project                                             */
/*                                                                        */
/* Contributors Listed Below - COPYRIGHT 2016,2019                        */
/* [+] International Business Machines Corp.                              */
/*                                                                        */
/*                                                                        */
/* Licensed under the Apache License, Version 2.0 (the "License");        */
/* you may not use this file except in compliance with the License.       */
/* You may obtain a copy of the License at                                */
/*                                                                        */
/*     http://www.apache.org/licenses/LICENSE-2.0                         */
/*                                                                        */
/* Unless required by applicable law or agreed to in writing, software    */
/* distributed under the License is distributed on an "AS IS" BASIS,      */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or        */
/* implied. See the License for the specific language governing           */
/* permissions and limitations under the License.                         */
/*                                                                        */
/* IBM_PROLOG_END_TAG                                                     */
///
/// @file  p9_pm_occ_sram_init.C
/// @brief Initialize the SRAM in the OCC
///
// *HWP HWP Owner: Greg Still <stillgs@us.ibm.com>
// *HWP FW Owner: Sangeetha T S <sangeet2@in.ibm.com>
// *HWP Team: PM
// *HWP Level: 1
// *HWP Consumed by: FSP:HS
//

// -----------------------------------------------------------------------------
// Includes
// -----------------------------------------------------------------------------
#include <p9_pm_occ_sram_init.H>

// -----------------------------------------------------------------------------
// Function definitions
// -----------------------------------------------------------------------------

fapi2::ReturnCode p9_pm_occ_sram_init(
    const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target,
    const p9pm::PM_FLOW_MODE i_mode)
{
    FAPI_INF("Entering p9_pm_occ_sram_init...");

    // Initialization:  perform order or dynamic operations to initialize
    // the OCC SRAM using necessary Platform or Feature attributes.
    if (i_mode == p9pm::PM_INIT)
    {
        FAPI_INF("OCC SRAM initialization...");
    }
    // Reset:  perform reset of OCC SRAM so that it can reconfigured and
    // reinitialized
    else if (i_mode == p9pm::PM_RESET)
    {
        FAPI_INF("OCC SRAM reset...");
    }
    // Unsupported Mode
    else
    {
        FAPI_ASSERT(false, fapi2::PM_OCCSRAM_BAD_MODE().set_MODE(i_mode),
                    "ERROR; Unknown mode passed to p9_pm_occ_sram_init. Mode %x",
                    i_mode);
    }

fapi_try_exit:
    return fapi2::current_err;
}
<commit_msg>Level 3 : OCB & OCC procedures<commit_after>/* IBM_PROLOG_BEGIN_TAG                                                   */
/* This is an automatically generated prolog.                             */
/*                                                                        */
/* $Source: src/import/chips/p9/procedures/hwp/pm/p9_pm_occ_sram_init.C $ */
/*                                                                        */
/* OpenPOWER HostBoot Project                                             */
/*                                                                        */
/* Contributors Listed Below - COPYRIGHT 2016,2019                        */
/* [+] International Business Machines Corp.                              */
/*                                                                        */
/*                                                                        */
/* Licensed under the Apache License, Version 2.0 (the "License");        */
/* you may not use this file except in compliance with the License.       */
/* You may obtain a copy of the License at                                */
/*                                                                        */
/*     http://www.apache.org/licenses/LICENSE-2.0                         */
/*                                                                        */
/* Unless required by applicable law or agreed to in writing, software    */
/* distributed under the License is distributed on an "AS IS" BASIS,      */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or        */
/* implied. See the License for the specific language governing           */
/* permissions and limitations under the License.                         */
/*                                                                        */
/* IBM_PROLOG_END_TAG                                                     */
///
/// @file  p9_pm_occ_sram_init.C
/// @brief Initialize the SRAM in the OCC
///
// *HWP HWP Owner: Greg Still <stillgs@us.ibm.com>
// *HWP HWP Backup Owner: Amit Kumar <akumar3@us.ibm.com>
// *HWP FW Owner: Sangeetha T S <sangeet2@in.ibm.com>
// *HWP Team: PM
// *HWP Level: 3
// *HWP Consumed by: HS
//

// -----------------------------------------------------------------------------
// Includes
// -----------------------------------------------------------------------------
#include <p9_pm_occ_sram_init.H>

// -----------------------------------------------------------------------------
// Function definitions
// -----------------------------------------------------------------------------

fapi2::ReturnCode p9_pm_occ_sram_init(
    const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target,
    const p9pm::PM_FLOW_MODE i_mode)
{
    FAPI_INF("Entering p9_pm_occ_sram_init...");

    // Initialization:  perform order or dynamic operations to initialize
    // the OCC SRAM using necessary Platform or Feature attributes.
    if (i_mode == p9pm::PM_INIT)
    {
        FAPI_INF("OCC SRAM initialization...");
    }
    // Reset:  perform reset of OCC SRAM so that it can reconfigured and
    // reinitialized
    else if (i_mode == p9pm::PM_RESET)
    {
        FAPI_INF("OCC SRAM reset...");
    }
    // Unsupported Mode
    else
    {
        FAPI_ASSERT(false, fapi2::PM_OCCSRAM_BAD_MODE().set_MODE(i_mode),
                    "ERROR; Unknown mode passed to p9_pm_occ_sram_init. Mode %x",
                    i_mode);
    }

fapi_try_exit:
    return fapi2::current_err;
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: Legend.cxx,v $
 *
 *  $Revision: 1.5 $
 *
 *  last change: $Author: bm $ $Date: 2003-10-20 09:59:31 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2003 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/
#include "Legend.hxx"
#include "macros.hxx"
#include "algohelper.hxx"
#include "LineProperties.hxx"
#include "FillProperties.hxx"
#include "CharacterProperties.hxx"
#include "UserDefinedProperties.hxx"
#include "LegendHelper.hxx"
#include "LayoutDefaults.hxx"

#ifndef CHART_PROPERTYHELPER_HXX
#include "PropertyHelper.hxx"
#endif
#ifndef _COM_SUN_STAR_BEANS_PROPERTYATTRIBUTE_HPP_
#include <com/sun/star/beans/PropertyAttribute.hpp>
#endif

#ifndef _DRAFTS_COM_SUN_STAR_LAYOUT_ALIGNMENT_HPP_
#include <drafts/com/sun/star/layout/Alignment.hpp>
#endif
#ifndef _DRAFTS_COM_SUN_STAR_LAYOUT_STRETCHMODE_HPP_
#include <drafts/com/sun/star/layout/StretchMode.hpp>
#endif
#ifndef _DRAFTS_COM_SUN_STAR_CHART2_LEGENDPOSITION_HPP_
#include <drafts/com/sun/star/chart2/LegendPosition.hpp>
#endif
#ifndef _DRAFTS_COM_SUN_STAR_CHART2_LEGENDEXPANSION_HPP_
#include <drafts/com/sun/star/chart2/LegendExpansion.hpp>
#endif

#include <algorithm>

using namespace ::com::sun::star;
using namespace ::com::sun::star::beans::PropertyAttribute;
using namespace ::drafts::com::sun::star;

using ::com::sun::star::beans::Property;

namespace
{

static const ::rtl::OUString lcl_aServiceName(
    RTL_CONSTASCII_USTRINGPARAM( "com.sun.star.comp.chart2.Legend" ));

enum
{
    PROP_LEGEND_POSITION,
    PROP_LEGEND_PREFERRED_EXPANSION,
    PROP_LEGEND_SHOW
};

void lcl_AddPropertiesToVector(
    ::std::vector< Property > & rOutProperties )
{
    rOutProperties.push_back(
        Property( C2U( "Position" ),
                  PROP_LEGEND_POSITION,
                  ::getCppuType( reinterpret_cast< const chart2::LegendPosition * >(0)),
                  beans::PropertyAttribute::BOUND
                  | beans::PropertyAttribute::MAYBEDEFAULT ));

    rOutProperties.push_back(
        Property( C2U( "Expansion" ),
                  PROP_LEGEND_PREFERRED_EXPANSION,
                  ::getCppuType( reinterpret_cast< const chart2::LegendExpansion * >(0)),
                  beans::PropertyAttribute::BOUND
                  | beans::PropertyAttribute::MAYBEDEFAULT ));

    rOutProperties.push_back(
        Property( C2U( "Show" ),
                  PROP_LEGEND_SHOW,
                  ::getBooleanCppuType(),
                  beans::PropertyAttribute::BOUND
                  | beans::PropertyAttribute::MAYBEDEFAULT ));
}

void lcl_AddDefaultsToMap(
    ::chart::helper::tPropertyValueMap & rOutMap )
{
    OSL_ASSERT( rOutMap.end() == rOutMap.find( PROP_LEGEND_POSITION ));
    rOutMap[ PROP_LEGEND_POSITION ] =
        uno::makeAny( chart2::LegendPosition_LINE_END );

    OSL_ASSERT( rOutMap.end() == rOutMap.find( PROP_LEGEND_SHOW ));
    rOutMap[ PROP_LEGEND_SHOW ] =
        uno::makeAny( sal_True );
}

const uno::Sequence< Property > & lcl_GetPropertySequence()
{
    static uno::Sequence< Property > aPropSeq;

    // /--
    ::osl::MutexGuard aGuard( ::osl::Mutex::getGlobalMutex() );
    if( 0 == aPropSeq.getLength() )
    {
        // get properties
        ::std::vector< ::com::sun::star::beans::Property > aProperties;
        lcl_AddPropertiesToVector( aProperties );
        ::chart::LineProperties::AddPropertiesToVector(
            aProperties, /* bIncludeStyleProperties = */ false );
        ::chart::FillProperties::AddPropertiesToVector(
            aProperties, /* bIncludeStyleProperties = */ false );
        ::chart::CharacterProperties::AddPropertiesToVector(
            aProperties, /* bIncludeStyleProperties = */ false );
        ::chart::UserDefinedProperties::AddPropertiesToVector( aProperties );

        // and sort them for access via bsearch
        ::std::sort( aProperties.begin(), aProperties.end(),
                     ::chart::helper::PropertyNameLess() );

        // transfer result to static Sequence
        aPropSeq = ::chart::helper::VectorToSequence( aProperties );
    }

    return aPropSeq;
}

::cppu::IPropertyArrayHelper & lcl_getInfoHelper()
{
    static ::cppu::OPropertyArrayHelper aArrayHelper(
        lcl_GetPropertySequence(),
        /* bSorted = */ sal_True );

    return aArrayHelper;
}

} // anonymous namespace

namespace chart
{

Legend::Legend( uno::Reference< uno::XComponentContext > const & xContext ) :
        ::property::OPropertySet( m_aMutex ),
        m_aIdentifier( LegendHelper::getIdentifierForLegend() )
{
    setAnchorAndRelposFromProperty( GetDefaultValue( PROP_LEGEND_POSITION ));
}

Legend::~Legend()
{
}

// ____ XLegend ____
void SAL_CALL Legend::registerEntry( const uno::Reference< chart2::XLegendEntry >& xEntry )
    throw (lang::IllegalArgumentException,
           uno::RuntimeException)
{
    if( ::std::find( m_aLegendEntries.begin(),
                     m_aLegendEntries.end(),
                     xEntry ) != m_aLegendEntries.end())
        throw lang::IllegalArgumentException();

    m_aLegendEntries.push_back( xEntry );
}

void SAL_CALL Legend::revokeEntry( const uno::Reference< chart2::XLegendEntry >& xEntry )
    throw (container::NoSuchElementException,
           uno::RuntimeException)
{
    tLegendEntries::iterator aIt(
        ::std::find( m_aLegendEntries.begin(),
                     m_aLegendEntries.end(),
                     xEntry ));

    if( aIt == m_aLegendEntries.end())
        throw container::NoSuchElementException();

    m_aLegendEntries.erase( aIt );
}

uno::Sequence< uno::Reference< chart2::XLegendEntry > > SAL_CALL Legend::getEntries()
    throw (uno::RuntimeException)
{
    return ::chart::helper::VectorToSequence( m_aLegendEntries );
}

::rtl::OUString SAL_CALL Legend::getIdentifier()
    throw (uno::RuntimeException)
{
    return m_aIdentifier;
}

// ____ XAnchoredObject ____
void SAL_CALL Legend::setAnchor( const layout::AnchorPoint& aAnchor )
    throw (uno::RuntimeException)
{
    m_aAnchor = aAnchor;
}

layout::AnchorPoint SAL_CALL Legend::getAnchor()
    throw (uno::RuntimeException)
{
    return m_aAnchor;
}

void SAL_CALL Legend::setRelativePosition( const layout::RelativePoint& aPosition )
    throw (uno::RuntimeException)
{
    m_aRelativePosition = aPosition;
}

layout::RelativePoint SAL_CALL Legend::getRelativePosition()
    throw (uno::RuntimeException)
{
    return m_aRelativePosition;
}

// private
void Legend::setAnchorAndRelposFromProperty( const uno::Any & rValue )
{
    chart2::LegendPosition ePos;
    if( rValue >>= ePos )
    {
        m_aAnchor.AnchorHolder = uno::Reference< layout::XAnchor >();

        // shift legend about 2% into the primary direction
        m_aRelativePosition.Primary   = 0.02;
        m_aRelativePosition.Secondary = 0.0;

        switch( ePos )
        {
            case chart2::LegendPosition_LINE_START:
                m_aAnchor.Alignment = ::layout_defaults::const_aLineStart;
                m_aAnchor.EscapeDirection = 0.0;
                break;
            case chart2::LegendPosition_LINE_END:
                m_aAnchor.Alignment = ::layout_defaults::const_aLineEnd;
                m_aAnchor.EscapeDirection = 180.0;
                break;
            case chart2::LegendPosition_PAGE_START:
                m_aAnchor.Alignment = ::layout_defaults::const_aPageStart;
                m_aAnchor.EscapeDirection = 270.0;
                break;
            case chart2::LegendPosition_PAGE_END:
                m_aAnchor.Alignment = ::layout_defaults::const_aPageEnd;
                m_aAnchor.EscapeDirection = 90.0;
                break;

            case chart2::LegendPosition_CUSTOM:
            // to avoid warning
            case chart2::LegendPosition_MAKE_FIXED_SIZE:
                // nothing to be set
                break;
        }
    }
}

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

uno::Sequence< ::rtl::OUString > Legend::getSupportedServiceNames_Static()
{
    uno::Sequence< ::rtl::OUString > aServices( 5 );
    aServices[ 0 ] = C2U( "drafts.com.sun.star.chart2.Legend" );
    aServices[ 1 ] = C2U( "com.sun.star.beans.PropertySet" );
    aServices[ 2 ] = C2U( "com.sun.star.drawing.FillProperties" );
    aServices[ 3 ] = C2U( "com.sun.star.drawing.LineProperties" );
    aServices[ 4 ] = C2U( "drafts.com.sun.star.layout.LayoutElement" );
    return aServices;
}

// ____ OPropertySet ____
uno::Any Legend::GetDefaultValue( sal_Int32 nHandle ) const
    throw(beans::UnknownPropertyException)
{
    static helper::tPropertyValueMap aStaticDefaults;

    // /--
    ::osl::MutexGuard aGuard( ::osl::Mutex::getGlobalMutex() );
    if( 0 == aStaticDefaults.size() )
    {
        lcl_AddDefaultsToMap( aStaticDefaults );
        LineProperties::AddDefaultsToMap(
            aStaticDefaults,
            /* bIncludeStyleProperties = */ false );
        FillProperties::AddDefaultsToMap(
            aStaticDefaults,
            /* bIncludeStyleProperties = */ false );
        CharacterProperties::AddDefaultsToMap(
            aStaticDefaults,
            /* bIncludeStyleProperties = */ false );
    }

    helper::tPropertyValueMap::const_iterator aFound(
        aStaticDefaults.find( nHandle ));

    if( aFound == aStaticDefaults.end())
        return uno::Any();

    return (*aFound).second;
    // \--
}

::cppu::IPropertyArrayHelper & SAL_CALL Legend::getInfoHelper()
{
    return lcl_getInfoHelper();
}

// ____ XPropertySet ____
uno::Reference< beans::XPropertySetInfo > SAL_CALL
    Legend::getPropertySetInfo()
    throw (uno::RuntimeException)
{
    static uno::Reference< beans::XPropertySetInfo > xInfo;

    // /--
    ::osl::MutexGuard aGuard( ::osl::Mutex::getGlobalMutex() );
    if( !xInfo.is())
    {
        xInfo = ::cppu::OPropertySetHelper::createPropertySetInfo(
            getInfoHelper());
    }

    return xInfo;
    // \--
}

void SAL_CALL Legend::setFastPropertyValue_NoBroadcast
    ( sal_Int32 nHandle, const uno::Any& rValue )
    throw (uno::Exception)
{
    if( nHandle == PROP_LEGEND_POSITION )
        setAnchorAndRelposFromProperty( rValue );

    OPropertySet::setFastPropertyValue_NoBroadcast( nHandle, rValue );
}

// implement XServiceInfo methods basing upon getSupportedServiceNames_Static
APPHELPER_XSERVICEINFO_IMPL( Legend, lcl_aServiceName );

// needed by MSC compiler
using impl::Legend_Base;

IMPLEMENT_FORWARD_XINTERFACE2( Legend, Legend_Base, ::property::OPropertySet )
IMPLEMENT_FORWARD_XTYPEPROVIDER2( Legend, Legend_Base, ::property::OPropertySet )

} //  namespace chart
<commit_msg>XAnchor removed from AnchorPoint<commit_after>/*************************************************************************
 *
 *  $RCSfile: Legend.cxx,v $
 *
 *  $Revision: 1.6 $
 *
 *  last change: $Author: bm $ $Date: 2003-10-29 09:49:09 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2003 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/
#include "Legend.hxx"
#include "macros.hxx"
#include "algohelper.hxx"
#include "LineProperties.hxx"
#include "FillProperties.hxx"
#include "CharacterProperties.hxx"
#include "UserDefinedProperties.hxx"
#include "LegendHelper.hxx"
#include "LayoutDefaults.hxx"

#ifndef CHART_PROPERTYHELPER_HXX
#include "PropertyHelper.hxx"
#endif
#ifndef _COM_SUN_STAR_BEANS_PROPERTYATTRIBUTE_HPP_
#include <com/sun/star/beans/PropertyAttribute.hpp>
#endif

#ifndef _DRAFTS_COM_SUN_STAR_LAYOUT_ALIGNMENT_HPP_
#include <drafts/com/sun/star/layout/Alignment.hpp>
#endif
#ifndef _DRAFTS_COM_SUN_STAR_LAYOUT_STRETCHMODE_HPP_
#include <drafts/com/sun/star/layout/StretchMode.hpp>
#endif
#ifndef _DRAFTS_COM_SUN_STAR_CHART2_LEGENDPOSITION_HPP_
#include <drafts/com/sun/star/chart2/LegendPosition.hpp>
#endif
#ifndef _DRAFTS_COM_SUN_STAR_CHART2_LEGENDEXPANSION_HPP_
#include <drafts/com/sun/star/chart2/LegendExpansion.hpp>
#endif

#include <algorithm>

using namespace ::com::sun::star;
using namespace ::com::sun::star::beans::PropertyAttribute;
using namespace ::drafts::com::sun::star;

using ::com::sun::star::beans::Property;

namespace
{

static const ::rtl::OUString lcl_aServiceName(
    RTL_CONSTASCII_USTRINGPARAM( "com.sun.star.comp.chart2.Legend" ));

enum
{
    PROP_LEGEND_POSITION,
    PROP_LEGEND_PREFERRED_EXPANSION,
    PROP_LEGEND_SHOW
};

void lcl_AddPropertiesToVector(
    ::std::vector< Property > & rOutProperties )
{
    rOutProperties.push_back(
        Property( C2U( "Position" ),
                  PROP_LEGEND_POSITION,
                  ::getCppuType( reinterpret_cast< const chart2::LegendPosition * >(0)),
                  beans::PropertyAttribute::BOUND
                  | beans::PropertyAttribute::MAYBEDEFAULT ));

    rOutProperties.push_back(
        Property( C2U( "Expansion" ),
                  PROP_LEGEND_PREFERRED_EXPANSION,
                  ::getCppuType( reinterpret_cast< const chart2::LegendExpansion * >(0)),
                  beans::PropertyAttribute::BOUND
                  | beans::PropertyAttribute::MAYBEDEFAULT ));

    rOutProperties.push_back(
        Property( C2U( "Show" ),
                  PROP_LEGEND_SHOW,
                  ::getBooleanCppuType(),
                  beans::PropertyAttribute::BOUND
                  | beans::PropertyAttribute::MAYBEDEFAULT ));
}

void lcl_AddDefaultsToMap(
    ::chart::helper::tPropertyValueMap & rOutMap )
{
    OSL_ASSERT( rOutMap.end() == rOutMap.find( PROP_LEGEND_POSITION ));
    rOutMap[ PROP_LEGEND_POSITION ] =
        uno::makeAny( chart2::LegendPosition_LINE_END );

    OSL_ASSERT( rOutMap.end() == rOutMap.find( PROP_LEGEND_SHOW ));
    rOutMap[ PROP_LEGEND_SHOW ] =
        uno::makeAny( sal_True );
}

const uno::Sequence< Property > & lcl_GetPropertySequence()
{
    static uno::Sequence< Property > aPropSeq;

    // /--
    ::osl::MutexGuard aGuard( ::osl::Mutex::getGlobalMutex() );
    if( 0 == aPropSeq.getLength() )
    {
        // get properties
        ::std::vector< ::com::sun::star::beans::Property > aProperties;
        lcl_AddPropertiesToVector( aProperties );
        ::chart::LineProperties::AddPropertiesToVector(
            aProperties, /* bIncludeStyleProperties = */ false );
        ::chart::FillProperties::AddPropertiesToVector(
            aProperties, /* bIncludeStyleProperties = */ false );
        ::chart::CharacterProperties::AddPropertiesToVector(
            aProperties, /* bIncludeStyleProperties = */ false );
        ::chart::UserDefinedProperties::AddPropertiesToVector( aProperties );

        // and sort them for access via bsearch
        ::std::sort( aProperties.begin(), aProperties.end(),
                     ::chart::helper::PropertyNameLess() );

        // transfer result to static Sequence
        aPropSeq = ::chart::helper::VectorToSequence( aProperties );
    }

    return aPropSeq;
}

::cppu::IPropertyArrayHelper & lcl_getInfoHelper()
{
    static ::cppu::OPropertyArrayHelper aArrayHelper(
        lcl_GetPropertySequence(),
        /* bSorted = */ sal_True );

    return aArrayHelper;
}

} // anonymous namespace

namespace chart
{

Legend::Legend( uno::Reference< uno::XComponentContext > const & xContext ) :
        ::property::OPropertySet( m_aMutex ),
        m_aIdentifier( LegendHelper::getIdentifierForLegend() )
{
    setAnchorAndRelposFromProperty( GetDefaultValue( PROP_LEGEND_POSITION ));
}

Legend::~Legend()
{
}

// ____ XLegend ____
void SAL_CALL Legend::registerEntry( const uno::Reference< chart2::XLegendEntry >& xEntry )
    throw (lang::IllegalArgumentException,
           uno::RuntimeException)
{
    if( ::std::find( m_aLegendEntries.begin(),
                     m_aLegendEntries.end(),
                     xEntry ) != m_aLegendEntries.end())
        throw lang::IllegalArgumentException();

    m_aLegendEntries.push_back( xEntry );
}

void SAL_CALL Legend::revokeEntry( const uno::Reference< chart2::XLegendEntry >& xEntry )
    throw (container::NoSuchElementException,
           uno::RuntimeException)
{
    tLegendEntries::iterator aIt(
        ::std::find( m_aLegendEntries.begin(),
                     m_aLegendEntries.end(),
                     xEntry ));

    if( aIt == m_aLegendEntries.end())
        throw container::NoSuchElementException();

    m_aLegendEntries.erase( aIt );
}

uno::Sequence< uno::Reference< chart2::XLegendEntry > > SAL_CALL Legend::getEntries()
    throw (uno::RuntimeException)
{
    return ::chart::helper::VectorToSequence( m_aLegendEntries );
}

::rtl::OUString SAL_CALL Legend::getIdentifier()
    throw (uno::RuntimeException)
{
    return m_aIdentifier;
}

// ____ XAnchoredObject ____
void SAL_CALL Legend::setAnchor( const layout::AnchorPoint& aAnchor )
    throw (uno::RuntimeException)
{
    m_aAnchor = aAnchor;
}

layout::AnchorPoint SAL_CALL Legend::getAnchor()
    throw (uno::RuntimeException)
{
    return m_aAnchor;
}

void SAL_CALL Legend::setRelativePosition( const layout::RelativePoint& aPosition )
    throw (uno::RuntimeException)
{
    m_aRelativePosition = aPosition;
}

layout::RelativePoint SAL_CALL Legend::getRelativePosition()
    throw (uno::RuntimeException)
{
    return m_aRelativePosition;
}

// private
void Legend::setAnchorAndRelposFromProperty( const uno::Any & rValue )
{
    chart2::LegendPosition ePos;
    if( rValue >>= ePos )
    {
        // shift legend about 2% into the primary direction
        m_aRelativePosition.Primary   = 0.02;
        m_aRelativePosition.Secondary = 0.0;

        switch( ePos )
        {
            case chart2::LegendPosition_LINE_START:
                m_aAnchor.Alignment = ::layout_defaults::const_aLineStart;
                m_aAnchor.EscapeDirection = 0.0;
                break;
            case chart2::LegendPosition_LINE_END:
                m_aAnchor.Alignment = ::layout_defaults::const_aLineEnd;
                m_aAnchor.EscapeDirection = 180.0;
                break;
            case chart2::LegendPosition_PAGE_START:
                m_aAnchor.Alignment = ::layout_defaults::const_aPageStart;
                m_aAnchor.EscapeDirection = 270.0;
                break;
            case chart2::LegendPosition_PAGE_END:
                m_aAnchor.Alignment = ::layout_defaults::const_aPageEnd;
                m_aAnchor.EscapeDirection = 90.0;
                break;

            case chart2::LegendPosition_CUSTOM:
            // to avoid warning
            case chart2::LegendPosition_MAKE_FIXED_SIZE:
                // nothing to be set
                break;
        }
    }
}

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

uno::Sequence< ::rtl::OUString > Legend::getSupportedServiceNames_Static()
{
    uno::Sequence< ::rtl::OUString > aServices( 5 );
    aServices[ 0 ] = C2U( "drafts.com.sun.star.chart2.Legend" );
    aServices[ 1 ] = C2U( "com.sun.star.beans.PropertySet" );
    aServices[ 2 ] = C2U( "com.sun.star.drawing.FillProperties" );
    aServices[ 3 ] = C2U( "com.sun.star.drawing.LineProperties" );
    aServices[ 4 ] = C2U( "drafts.com.sun.star.layout.LayoutElement" );
    return aServices;
}

// ____ OPropertySet ____
uno::Any Legend::GetDefaultValue( sal_Int32 nHandle ) const
    throw(beans::UnknownPropertyException)
{
    static helper::tPropertyValueMap aStaticDefaults;

    // /--
    ::osl::MutexGuard aGuard( ::osl::Mutex::getGlobalMutex() );
    if( 0 == aStaticDefaults.size() )
    {
        lcl_AddDefaultsToMap( aStaticDefaults );
        LineProperties::AddDefaultsToMap(
            aStaticDefaults,
            /* bIncludeStyleProperties = */ false );
        FillProperties::AddDefaultsToMap(
            aStaticDefaults,
            /* bIncludeStyleProperties = */ false );
        CharacterProperties::AddDefaultsToMap(
            aStaticDefaults,
            /* bIncludeStyleProperties = */ false );
    }

    helper::tPropertyValueMap::const_iterator aFound(
        aStaticDefaults.find( nHandle ));

    if( aFound == aStaticDefaults.end())
        return uno::Any();

    return (*aFound).second;
    // \--
}

::cppu::IPropertyArrayHelper & SAL_CALL Legend::getInfoHelper()
{
    return lcl_getInfoHelper();
}

// ____ XPropertySet ____
uno::Reference< beans::XPropertySetInfo > SAL_CALL
    Legend::getPropertySetInfo()
    throw (uno::RuntimeException)
{
    static uno::Reference< beans::XPropertySetInfo > xInfo;

    // /--
    ::osl::MutexGuard aGuard( ::osl::Mutex::getGlobalMutex() );
    if( !xInfo.is())
    {
        xInfo = ::cppu::OPropertySetHelper::createPropertySetInfo(
            getInfoHelper());
    }

    return xInfo;
    // \--
}

void SAL_CALL Legend::setFastPropertyValue_NoBroadcast
    ( sal_Int32 nHandle, const uno::Any& rValue )
    throw (uno::Exception)
{
    if( nHandle == PROP_LEGEND_POSITION )
        setAnchorAndRelposFromProperty( rValue );

    OPropertySet::setFastPropertyValue_NoBroadcast( nHandle, rValue );
}

// implement XServiceInfo methods basing upon getSupportedServiceNames_Static
APPHELPER_XSERVICEINFO_IMPL( Legend, lcl_aServiceName );

// needed by MSC compiler
using impl::Legend_Base;

IMPLEMENT_FORWARD_XINTERFACE2( Legend, Legend_Base, ::property::OPropertySet )
IMPLEMENT_FORWARD_XTYPEPROVIDER2( Legend, Legend_Base, ::property::OPropertySet )

} //  namespace chart
<|endoftext|>