<commit_before>/* IBM_PROLOG_BEGIN_TAG                                                   */
/* This is an automatically generated prolog.                             */
/*                                                                        */
/* $Source: src/import/chips/p9/procedures/hwp/pm/p9_pm_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_init.C
/// @brief Wrapper that initializes or resets the OCC complex.
///
// *HWP HWP Owner        : Greg Still <stillgs@us.ibm.com>
// *HWP HWP Backup Owner : Prasad BG Ranganath <prasadbgr@in.ibm.com>
// *HWP FW Owner         : Prem S Jha <premjha2@in.ibm.com>
// *HWP Team             : PM
// *HWP Level            : 3
// *HWP Consumed by      : HS

///
/// High-level procedure flow:
///
/// @verbatim
///
///  PM_INIT
///    Initialize Cores and Quads
///    Initialize OCB channels
///    Initialize PSS
///    Set the OCC FIR actions
///    Set the CME, PPM and PBA FIR actions
///    Initialize Stop GPE
///    Initialize Pstate GPE
///    Clear off pending Special Wakeup requests on all configured EX chiplets
///    Disable special wakeup of all the EX chiplets
///    Start OCC PPC405
///
///  PM_RESET
///    Invoke "p9_pm_reset()" to reset the PM OCC complex (Cores, Quads, CMEs,
///    OCB channels, PBA bus, PSS, PPC405 and GPEs)
///
/// @endverbatim
///

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

// -----------------------------------------------------------------------------
// Function prototypes
// -----------------------------------------------------------------------------

///
/// @brief Call underlying unit procedures to initialize the PM complex.
///
/// @param[in] i_target Chip target
///
/// @return FAPI2_RC_SUCCESS on success, else error code.
///
fapi2::ReturnCode pm_init(
    const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target,
    void* i_pHomerImage);

///
/// @brief Clears OCC special wake-up on all configured EX chiplets
///
/// @param[in] i_target   Chip target
///
/// @return FAPI2_RC_SUCCESS on success, else error code.
///
fapi2::ReturnCode clear_occ_special_wakeups(
    const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target);

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

fapi2::ReturnCode p9_pm_init(
    const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target,
    const p9pm::PM_FLOW_MODE i_mode,
    void* i_pHomerImage = NULL)
{
    FAPI_INF("Entering p9_pm_init ...");

    fapi2::ReturnCode l_rc;

    if (i_mode == p9pm::PM_INIT)
    {
        FAPI_DBG("Initialize the OCC Complex.");
        FAPI_TRY(pm_init(i_target, i_pHomerImage),
                 "ERROR: Failed to initialize OCC Complex");
    }
    else if (i_mode == p9pm::PM_RESET)
    {
        FAPI_DBG("Reset the OCC Complex.");
        FAPI_EXEC_HWP(l_rc, p9_pm_reset, i_target, i_pHomerImage);
        FAPI_TRY(l_rc, "ERROR: Failed to reset OCC complex");
    }
    else
    {
        FAPI_ASSERT(false, fapi2::PM_INIT_BAD_MODE().set_BADMODE(i_mode),
                    "ERROR; Unknown mode passed to p9_pm_init. Mode %x",
                    i_mode);
    }

fapi_try_exit:
    FAPI_INF("Exiting p9_pm_init...");
    return fapi2::current_err;
}

fapi2::ReturnCode pm_init(
    const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target,
    void* i_pHomerImage)
{
    FAPI_INF("Entering pm_init...");

    fapi2::ReturnCode l_rc;

    //  ************************************************************************
    //  Initialize Cores and Quads
    //  ************************************************************************
    FAPI_DBG("Executing p9_pm_corequad_init to initialize cores & quads");
    FAPI_EXEC_HWP(l_rc, p9_pm_corequad_init,
                  i_target,
                  p9pm::PM_INIT,
                  0,//CME FIR MASK for reset
                  0,//Core Error Mask for reset
                  0 //Quad Error Mask for reset
                 );
    FAPI_TRY(l_rc, "ERROR: Failed to initialize cores & quads");
    FAPI_TRY(p9_pm_glob_fir_trace(i_target, "After cores & quads init"));

    //  ************************************************************************
    //  Issue init to OCB
    //  ************************************************************************
    FAPI_DBG("Executing p9_pm_ocb_init to initialize OCB channels");
    FAPI_EXEC_HWP(l_rc, p9_pm_ocb_init,
                  i_target,
                  p9pm::PM_INIT,// Channel setup type
                  p9ocb::OCB_CHAN1,// Channel
                  p9ocb:: OCB_TYPE_NULL,// Channel type
                  0,// Channel base address
                  0,// Push/Pull queue length
                  p9ocb::OCB_Q_OUFLOW_NULL,// Channel flow control
                  p9ocb::OCB_Q_ITPTYPE_NULL// Channel interrupt control
                 );
    FAPI_TRY(l_rc,
             "ERROR: Failed to initialize channel 1");
    FAPI_TRY(p9_pm_glob_fir_trace(i_target, "After OCB channels init"));

    //  ************************************************************************
    //  Initializes P2S and HWC logic
    //  ************************************************************************
    FAPI_DBG("Executing p9_pm_pss_init to initialize P2S and HWC logic");
    FAPI_EXEC_HWP(l_rc, p9_pm_pss_init, i_target, p9pm::PM_INIT);
    FAPI_TRY(l_rc, "ERROR: Failed to initialize PSS & HWC");
    FAPI_TRY(p9_pm_glob_fir_trace(i_target, "After PSS & HWC init"));

    //  ************************************************************************
    //  Set the OCC FIR actions
    //  ************************************************************************
    FAPI_DBG("Executing p9_pm_occ_firinit to set FIR actions.");
    FAPI_EXEC_HWP(l_rc, p9_pm_occ_firinit, i_target, p9pm::PM_INIT);
    FAPI_TRY(l_rc, "ERROR: Failed to set OCC FIR actions.");
    FAPI_TRY(p9_pm_glob_fir_trace(i_target, "After setting FIRs"));

    //  ************************************************************************
    //  Set the FIR actions
    //  ************************************************************************
    FAPI_DBG("Executing p9_pm_firinit to set PBA, PPM, CME FIR actions");
    FAPI_EXEC_HWP(l_rc, p9_pm_firinit, i_target, p9pm::PM_INIT);
    FAPI_TRY(l_rc, "ERROR: Failed to set PPM, PBA & CME FIRs.");
    FAPI_TRY(p9_pm_glob_fir_trace(i_target, "After setting FIRs"));

    //  ************************************************************************
    //  Initialize the STOP GPE Engine
    //  ************************************************************************
    FAPI_DBG("Executing p9_pm_stop_gpe_init to initialize SGPE");
    FAPI_EXEC_HWP(l_rc, p9_pm_stop_gpe_init, i_target, p9pm::PM_INIT);
    FAPI_TRY(l_rc, "ERROR: Failed to initialize SGPE");
    FAPI_TRY(p9_pm_glob_fir_trace(i_target, "After SGPE initialization"));

    //  ************************************************************************
    //  Initialize the PSTATE GPE Engine
    //  ************************************************************************
    FAPI_DBG("Executing p9_pm_pstate_gpe_init to initialize PGPE");
    FAPI_EXEC_HWP(l_rc, p9_pm_pstate_gpe_init, i_target, p9pm::PM_INIT);
    FAPI_TRY(l_rc, "ERROR: Failed to initialize PGPE");
    FAPI_TRY(p9_pm_glob_fir_trace(i_target, "After PGPE initialization"));

    //  ************************************************************************
    //  Set up the configuration content in HOMER for the 24x7 function
    //  ************************************************************************
    if (i_pHomerImage != NULL)
    {
        FAPI_DBG("Executing p9_check_proc_config to create configuration settings for 24x7");
        FAPI_EXEC_HWP(l_rc, p9_check_proc_config, i_target, i_pHomerImage);
        FAPI_TRY(l_rc, "ERROR: Failed to initialize 24x7 configuration");
    }

    // ************************************************************************
    // Switch off OCC initiated special wakeup on EX to allowSTOP functionality
    // ************************************************************************
    FAPI_DBG("Clear off the wakeup");
    FAPI_TRY(clear_occ_special_wakeups(i_target),
             "ERROR: Failed to clear off the wakeup");
    FAPI_TRY(p9_pm_glob_fir_trace(i_target, "EX targets off special wakeup"));

    //  ************************************************************************
    //  Take all EX chiplets out of special wakeup
    //  ************************************************************************
    FAPI_DBG("Disable special wakeup for all functional  EX targets.");
    FAPI_TRY(special_wakeup_all(i_target,
                                false),//Disable splwkup
             "ERROR: Failed to remove EX chiplets from special wakeup");
    FAPI_TRY(p9_pm_glob_fir_trace(i_target, "After EX out of special wakeup"));

    //  ************************************************************************
    //  Start OCC PPC405
    //  ************************************************************************
    FAPI_DBG("Executing p9_pm_occ_control to start OCC PPC405");
    FAPI_EXEC_HWP(l_rc, p9_pm_occ_control, i_target,
                  p9occ_ctrl::PPC405_START,// Operation on PPC405
                  p9occ_ctrl::PPC405_BOOT_MEM // PPC405 boot location
                 );
    FAPI_TRY(l_rc, "ERROR: Failed to initialize OCC PPC405");
    FAPI_TRY(p9_pm_glob_fir_trace(i_target, "After OCC PPC405 init"));

fapi_try_exit:

    return fapi2::current_err;

}

fapi2::ReturnCode clear_occ_special_wakeups(
    const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target)
{
    FAPI_INF("Entering clear_occ_special_wakeups...");
    fapi2::buffer<uint64_t> l_data64;

    auto l_exChiplets = i_target.getChildren<fapi2::TARGET_TYPE_EX>
                        (fapi2::TARGET_STATE_FUNCTIONAL);

    FAPI_DBG("No. of functional EX chiplets: %u ", l_exChiplets.size());

    // Iterate through the EX chiplets
    for (auto l_ex_chplt : l_exChiplets)
    {
        FAPI_DBG("Clear OCC special wakeup on ex chiplet 0x%08X", l_ex_chplt);
        FAPI_TRY(fapi2::getScom(i_target, EX_PPM_SPWKUP_OCC, l_data64),
                 "ERROR: Failed to read OCC Spl wkup on EX 0x%08X", l_ex_chplt);
        l_data64.clearBit<0>();
        FAPI_TRY(fapi2::putScom(i_target, EX_PPM_SPWKUP_OCC, l_data64),
                 "ERROR: Failed to clear OCC Spl wkup on EX 0x%08X", l_ex_chplt);
    }

fapi_try_exit:
    return fapi2::current_err;
}
<commit_msg>IPL Time Checkstop Analysis: Bypass OCC Bootloader<commit_after>/* IBM_PROLOG_BEGIN_TAG                                                   */
/* This is an automatically generated prolog.                             */
/*                                                                        */
/* $Source: src/import/chips/p9/procedures/hwp/pm/p9_pm_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_init.C
/// @brief Wrapper that initializes or resets the OCC complex.
///
// *HWP HWP Owner        : Greg Still <stillgs@us.ibm.com>
// *HWP HWP Backup Owner : Prasad BG Ranganath <prasadbgr@in.ibm.com>
// *HWP FW Owner         : Prem S Jha <premjha2@in.ibm.com>
// *HWP Team             : PM
// *HWP Level            : 3
// *HWP Consumed by      : HS

///
/// High-level procedure flow:
///
/// @verbatim
///
///  PM_INIT
///    Initialize Cores and Quads
///    Initialize OCB channels
///    Initialize PSS
///    Set the OCC FIR actions
///    Set the CME, PPM and PBA FIR actions
///    Initialize Stop GPE
///    Initialize Pstate GPE
///    Clear off pending Special Wakeup requests on all configured EX chiplets
///    Disable special wakeup of all the EX chiplets
///    Start OCC PPC405
///
///  PM_RESET
///    Invoke "p9_pm_reset()" to reset the PM OCC complex (Cores, Quads, CMEs,
///    OCB channels, PBA bus, PSS, PPC405 and GPEs)
///
/// @endverbatim
///

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

// -----------------------------------------------------------------------------
// Function prototypes
// -----------------------------------------------------------------------------

///
/// @brief Call underlying unit procedures to initialize the PM complex.
///
/// @param[in] i_target Chip target
///
/// @return FAPI2_RC_SUCCESS on success, else error code.
///
fapi2::ReturnCode pm_init(
    const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target,
    void* i_pHomerImage);

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

fapi2::ReturnCode p9_pm_init(
    const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target,
    const p9pm::PM_FLOW_MODE i_mode,
    void* i_pHomerImage = NULL)
{
    FAPI_INF("Entering p9_pm_init ...");

    fapi2::ReturnCode l_rc;

    if (i_mode == p9pm::PM_INIT)
    {
        FAPI_DBG("Initialize the OCC Complex.");
        FAPI_TRY(pm_init(i_target, i_pHomerImage),
                 "ERROR: Failed to initialize OCC Complex");
    }
    else if (i_mode == p9pm::PM_RESET)
    {
        FAPI_DBG("Reset the OCC Complex.");
        FAPI_EXEC_HWP(l_rc, p9_pm_reset, i_target, i_pHomerImage);
        FAPI_TRY(l_rc, "ERROR: Failed to reset OCC complex");
    }
    else
    {
        FAPI_ASSERT(false, fapi2::PM_INIT_BAD_MODE().set_BADMODE(i_mode),
                    "ERROR; Unknown mode passed to p9_pm_init. Mode %x",
                    i_mode);
    }

fapi_try_exit:
    FAPI_INF("Exiting p9_pm_init...");
    return fapi2::current_err;
}

fapi2::ReturnCode pm_init(
    const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target,
    void* i_pHomerImage)
{
    FAPI_INF("Entering pm_init...");

    fapi2::ReturnCode l_rc;

    //  ************************************************************************
    //  Initialize Cores and Quads
    //  ************************************************************************
    FAPI_DBG("Executing p9_pm_corequad_init to initialize cores & quads");
    FAPI_EXEC_HWP(l_rc, p9_pm_corequad_init,
                  i_target,
                  p9pm::PM_INIT,
                  0,//CME FIR MASK for reset
                  0,//Core Error Mask for reset
                  0 //Quad Error Mask for reset
                 );
    FAPI_TRY(l_rc, "ERROR: Failed to initialize cores & quads");
    FAPI_TRY(p9_pm_glob_fir_trace(i_target, "After cores & quads init"));

    //  ************************************************************************
    //  Issue init to OCB
    //  ************************************************************************
    FAPI_DBG("Executing p9_pm_ocb_init to initialize OCB channels");
    FAPI_EXEC_HWP(l_rc, p9_pm_ocb_init,
                  i_target,
                  p9pm::PM_INIT,// Channel setup type
                  p9ocb::OCB_CHAN1,// Channel
                  p9ocb:: OCB_TYPE_NULL,// Channel type
                  0,// Channel base address
                  0,// Push/Pull queue length
                  p9ocb::OCB_Q_OUFLOW_NULL,// Channel flow control
                  p9ocb::OCB_Q_ITPTYPE_NULL// Channel interrupt control
                 );
    FAPI_TRY(l_rc,
             "ERROR: Failed to initialize channel 1");
    FAPI_TRY(p9_pm_glob_fir_trace(i_target, "After OCB channels init"));

    //  ************************************************************************
    //  Initializes P2S and HWC logic
    //  ************************************************************************
    FAPI_DBG("Executing p9_pm_pss_init to initialize P2S and HWC logic");
    FAPI_EXEC_HWP(l_rc, p9_pm_pss_init, i_target, p9pm::PM_INIT);
    FAPI_TRY(l_rc, "ERROR: Failed to initialize PSS & HWC");
    FAPI_TRY(p9_pm_glob_fir_trace(i_target, "After PSS & HWC init"));

    //  ************************************************************************
    //  Set the OCC FIR actions
    //  ************************************************************************
    FAPI_DBG("Executing p9_pm_occ_firinit to set FIR actions.");
    FAPI_EXEC_HWP(l_rc, p9_pm_occ_firinit, i_target, p9pm::PM_INIT);
    FAPI_TRY(l_rc, "ERROR: Failed to set OCC FIR actions.");
    FAPI_TRY(p9_pm_glob_fir_trace(i_target, "After setting FIRs"));

    //  ************************************************************************
    //  Set the FIR actions
    //  ************************************************************************
    FAPI_DBG("Executing p9_pm_firinit to set PBA, PPM, CME FIR actions");
    FAPI_EXEC_HWP(l_rc, p9_pm_firinit, i_target, p9pm::PM_INIT);
    FAPI_TRY(l_rc, "ERROR: Failed to set PPM, PBA & CME FIRs.");
    FAPI_TRY(p9_pm_glob_fir_trace(i_target, "After setting FIRs"));

    //  ************************************************************************
    //  Initialize the STOP GPE Engine
    //  ************************************************************************
    FAPI_DBG("Executing p9_pm_stop_gpe_init to initialize SGPE");
    FAPI_EXEC_HWP(l_rc, p9_pm_stop_gpe_init, i_target, p9pm::PM_INIT);
    FAPI_TRY(l_rc, "ERROR: Failed to initialize SGPE");
    FAPI_TRY(p9_pm_glob_fir_trace(i_target, "After SGPE initialization"));

    //  ************************************************************************
    //  Initialize the PSTATE GPE Engine
    //  ************************************************************************
    FAPI_DBG("Executing p9_pm_pstate_gpe_init to initialize PGPE");
    FAPI_EXEC_HWP(l_rc, p9_pm_pstate_gpe_init, i_target, p9pm::PM_INIT);
    FAPI_TRY(l_rc, "ERROR: Failed to initialize PGPE");
    FAPI_TRY(p9_pm_glob_fir_trace(i_target, "After PGPE initialization"));

    //  ************************************************************************
    //  Set up the configuration content in HOMER for the 24x7 function
    //  ************************************************************************
    if (i_pHomerImage != NULL)
    {
        FAPI_DBG("Executing p9_check_proc_config to create configuration settings for 24x7");
        FAPI_EXEC_HWP(l_rc, p9_check_proc_config, i_target, i_pHomerImage);
        FAPI_TRY(l_rc, "ERROR: Failed to initialize 24x7 configuration");
    }

    // ************************************************************************
    // Switch off OCC initiated special wakeup on EX to allowSTOP functionality
    // ************************************************************************
    FAPI_DBG("Clear off the wakeup");
    FAPI_TRY(clear_occ_special_wakeups(i_target),
             "ERROR: Failed to clear off the wakeup");
    FAPI_TRY(p9_pm_glob_fir_trace(i_target, "EX targets off special wakeup"));

    //  ************************************************************************
    //  Take all EX chiplets out of special wakeup
    //  ************************************************************************
    FAPI_DBG("Disable special wakeup for all functional  EX targets.");
    FAPI_TRY(special_wakeup_all(i_target,
                                false),//Disable splwkup
             "ERROR: Failed to remove EX chiplets from special wakeup");
    FAPI_TRY(p9_pm_glob_fir_trace(i_target, "After EX out of special wakeup"));

    //  ************************************************************************
    //  Start OCC PPC405
    //  ************************************************************************
    FAPI_DBG("Executing p9_pm_occ_control to start OCC PPC405");
    FAPI_EXEC_HWP(l_rc, p9_pm_occ_control, i_target,
                  p9occ_ctrl::PPC405_START,// Operation on PPC405
                  p9occ_ctrl::PPC405_BOOT_MEM, // PPC405 boot location
                  0 //Jump to 405 main instruction - not used here
                 );
    FAPI_TRY(l_rc, "ERROR: Failed to initialize OCC PPC405");
    FAPI_TRY(p9_pm_glob_fir_trace(i_target, "After OCC PPC405 init"));

fapi_try_exit:

    return fapi2::current_err;

}

fapi2::ReturnCode clear_occ_special_wakeups(
    const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target)
{
    FAPI_INF("Entering clear_occ_special_wakeups...");
    fapi2::buffer<uint64_t> l_data64;

    auto l_exChiplets = i_target.getChildren<fapi2::TARGET_TYPE_EX>
                        (fapi2::TARGET_STATE_FUNCTIONAL);

    FAPI_DBG("No. of functional EX chiplets: %u ", l_exChiplets.size());

    // Iterate through the EX chiplets
    for (auto l_ex_chplt : l_exChiplets)
    {
        FAPI_DBG("Clear OCC special wakeup on ex chiplet 0x%08X", l_ex_chplt);
        FAPI_TRY(fapi2::getScom(i_target, EX_PPM_SPWKUP_OCC, l_data64),
                 "ERROR: Failed to read OCC Spl wkup on EX 0x%08X", l_ex_chplt);
        l_data64.clearBit<0>();
        FAPI_TRY(fapi2::putScom(i_target, EX_PPM_SPWKUP_OCC, l_data64),
                 "ERROR: Failed to clear OCC Spl wkup on EX 0x%08X", l_ex_chplt);
    }

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


<commit_before><commit_msg>Fixed GEMM conversion (#4412)<commit_after><|endoftext|>


<commit_before><commit_msg>[localization] formatting<commit_after><|endoftext|>


<commit_before>#pragma once
//=====================================================================//
/*!	@file
	@brief	グラフィックス・カラー定義
    @author 平松邦仁 (hira@rvf-rc45.net)
	@copyright	Copyright (C) 2018 Kunihito Hiramatsu @n
				Released under the MIT license @n
				https://github.com/hirakuni45/RX/blob/master/LICENSE
*/
//=====================================================================//
#include <cstdint>

namespace graphics {

	//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
	/*!
		@brief	基本カラー定数
		@param[in]	T		ピクセル型（uint16_t、uint32_t）
	*/
	//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
	template <typename T>
	class base_color {

		static constexpr uint32_t rgb888_(uint8_t r, uint8_t g, uint8_t b)
		{
			return
				(static_cast<uint32_t>(r) << 16)
			  | (static_cast<uint32_t>(g) << 8)
			  | static_cast<uint32_t>(b);
		}

		static constexpr uint16_t rgb565_(uint8_t r, uint8_t g, uint8_t b)
		{
			return
				(static_cast<uint16_t>(r & 0xf8) << 8)
			  | (static_cast<uint16_t>(g & 0xfc) << 3)
			  | (static_cast<uint16_t>(b & 0xf8) >> 3);
		}

		static constexpr T rgb_(uint8_t r, uint8_t g, uint8_t b)
		{
			if(sizeof(T) == 1) {
				return (r & 0b11100000) | ((g & 0b11100000) >> 3) | ((b & 0b11000000) >> 6);
			} else if(sizeof(T) == 2) return rgb565_(r, g, b);
			else if(sizeof(T) == 4) return rgb888_(r, g, b);
			else return 0;
		}

	public:
		// https://jonasjacek.github.io/colors/
		static constexpr T Black   = rgb_(  0,   0,   0);
		static constexpr T Maroon  = rgb_(128,   0,   0);
		static constexpr T Green   = rgb_(  0, 128,   0);
		static constexpr T Olive   = rgb_(128, 128,   0);
		static constexpr T Navy    = rgb_(  0,   0, 128);
		static constexpr T Purple  = rgb_(128,   0, 128);
		static constexpr T Teal    = rgb_(  0, 128, 128);
		static constexpr T Silver  = rgb_(192, 192, 192);
		static constexpr T Grey    = rgb_(128, 128, 128);
		static constexpr T Red     = rgb_(255,   0,   0);
		static constexpr T Lime    = rgb_(  0, 255,   0);
		static constexpr T Yellow  = rgb_(255, 255,   0);
		static constexpr T Blue    = rgb_(  0,   0, 255);
		static constexpr T Fuchsi  = rgb_(255,   0, 255);
		static constexpr T Aqua    = rgb_(  0, 255, 255);
		static constexpr T White   = rgb_(255, 255, 255);
	};
}
<commit_msg>update: add API<commit_after>#pragma once
//=====================================================================//
/*!	@file
	@brief	グラフィックス・カラー定義
    @author 平松邦仁 (hira@rvf-rc45.net)
	@copyright	Copyright (C) 2018 Kunihito Hiramatsu @n
				Released under the MIT license @n
				https://github.com/hirakuni45/RX/blob/master/LICENSE
*/
//=====================================================================//
#include <cstdint>

namespace graphics {

	//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
	/*!
		@brief	基本カラー定数
		@param[in]	T		ピクセル型（uint16_t、uint32_t）
	*/
	//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
	template <typename T>
	class base_color {

		static constexpr uint32_t rgb888_(uint8_t r, uint8_t g, uint8_t b)
		{
			return
				(static_cast<uint32_t>(r) << 16)
			  | (static_cast<uint32_t>(g) << 8)
			  | static_cast<uint32_t>(b);
		}

		static constexpr uint16_t rgb565_(uint8_t r, uint8_t g, uint8_t b)
		{
			return
				(static_cast<uint16_t>(r & 0xf8) << 8)
			  | (static_cast<uint16_t>(g & 0xfc) << 3)
			  | (static_cast<uint16_t>(b & 0xf8) >> 3);
		}

		static constexpr T rgb_(uint8_t r, uint8_t g, uint8_t b)
		{
			if(sizeof(T) == 1) {
				return (r & 0b11100000) | ((g & 0b11100000) >> 3) | ((b & 0b11000000) >> 6);
			} else if(sizeof(T) == 2) return rgb565_(r, g, b);
			else if(sizeof(T) == 4) return rgb888_(r, g, b);
			else return 0;
		}

	public:
		//-----------------------------------------------------------------//
		/*!
			@brief	RGB 値から、パックされた RGB 値に変換
			@param[in]	r	R 値
			@param[in]	g	G 値
			@param[in]	b	B 値
			@return パックされた RGB 値
		*/
		//-----------------------------------------------------------------//
		T rgb(uint8_t r, uint8_t g, uint8_t b) const noexcept { return rgb_(r, g, b); }

		// https://jonasjacek.github.io/colors/
		static constexpr T Black   = rgb_(  0,   0,   0);
		static constexpr T Maroon  = rgb_(128,   0,   0);
		static constexpr T Green   = rgb_(  0, 128,   0);
		static constexpr T Olive   = rgb_(128, 128,   0);
		static constexpr T Navy    = rgb_(  0,   0, 128);
		static constexpr T Purple  = rgb_(128,   0, 128);
		static constexpr T Teal    = rgb_(  0, 128, 128);
		static constexpr T Silver  = rgb_(192, 192, 192);
		static constexpr T Gray    = rgb_(128, 128, 128);  // 米国
		static constexpr T Grey    = rgb_(128, 128, 128);  // 英国
		static constexpr T Red     = rgb_(255,   0,   0);
		static constexpr T Lime    = rgb_(  0, 255,   0);
		static constexpr T Yellow  = rgb_(255, 255,   0);
		static constexpr T Blue    = rgb_(  0,   0, 255);
		static constexpr T Fuchsi  = rgb_(255,   0, 255);
		static constexpr T Aqua    = rgb_(  0, 255, 255);
		static constexpr T White   = rgb_(255, 255, 255);
	};
}
<|endoftext|>


<commit_before><commit_msg>fix for compilation error on HPUX<commit_after><|endoftext|>


<commit_before>// Begin CVS Header
//   $Source: /Volumes/Home/Users/shoops/cvs/copasi_dev/copasi/layoutUI/CVisParameters.cpp,v $
//   $Revision: 1.9 $
//   $Name:  $
//   $Author: urost $
//   $Date: 2007/10/29 10:09:19 $
// End CVS Header

// Copyright (C) 2007 by Pedro Mendes, Virginia Tech Intellectual
// Properties, Inc. and EML Research, gGmbH.
// All rights reserved.

#include "CVisParameters.h"

const C_FLOAT64 CVisParameters::EPSILON = 1.2E-15f;

const C_INT16 CVisParameters::GLOBAL_SCALING = 0;
const C_INT16 CVisParameters::INDIVIDUAL_SCALING = 1;

const C_INT16 CVisParameters::COLOR_MODE = 0;
const C_INT16 CVisParameters::SIZE_DIAMETER_MODE = 1;
const C_INT16 CVisParameters::SIZE_AREA_MODE = 2;

CVisParameters::CVisParameters()
{
  init();
}

void CVisParameters::init()
{
  minNodeSize = 10.0;
  maxNodeSize = 100.0;
  //numberOfSteps = 0;
  stepsPerSecond = 10;
  scalingMode = CVisParameters::INDIVIDUAL_SCALING;
  mappingMode = CVisParameters::SIZE_DIAMETER_MODE;
  //mappingMode = CVisParameters::COLOR_MODE;
  animationRunning = false;
}
<commit_msg>*** empty log message ***<commit_after>// Begin CVS Header
//   $Source: /Volumes/Home/Users/shoops/cvs/copasi_dev/copasi/layoutUI/CVisParameters.cpp,v $
//   $Revision: 1.10 $
//   $Name:  $
//   $Author: urost $
//   $Date: 2007/10/29 10:19:14 $
// End CVS Header

// Copyright (C) 2007 by Pedro Mendes, Virginia Tech Intellectual
// Properties, Inc. and EML Research, gGmbH.
// All rights reserved.

#include "CVisParameters.h"

const C_FLOAT64 CVisParameters::EPSILON = 1.0E-15f;

const C_INT16 CVisParameters::GLOBAL_SCALING = 0;
const C_INT16 CVisParameters::INDIVIDUAL_SCALING = 1;

const C_INT16 CVisParameters::COLOR_MODE = 0;
const C_INT16 CVisParameters::SIZE_DIAMETER_MODE = 1;
const C_INT16 CVisParameters::SIZE_AREA_MODE = 2;

CVisParameters::CVisParameters()
{
  init();
}

void CVisParameters::init()
{
  minNodeSize = 10.0;
  maxNodeSize = 100.0;
  //numberOfSteps = 0;
  stepsPerSecond = 10;
  scalingMode = CVisParameters::INDIVIDUAL_SCALING;
  mappingMode = CVisParameters::SIZE_DIAMETER_MODE;
  //mappingMode = CVisParameters::COLOR_MODE;
  animationRunning = false;
}
<|endoftext|>


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

#ifdef SVX_DLLIMPLEMENTATION
#undef SVX_DLLIMPLEMENTATION
#endif

#ifndef _SVX_OPTACCESSIBILITY_HXX
#include <optaccessibility.hxx>
#endif
#include <optaccessibility.hrc>
#include <dialmgr.hxx>
#include "dialogs.hrc"
#ifndef INCLUDED_SVTOOLS_ACCESSIBILITYOPTIONS_HXX
#include <svtools/accessibilityoptions.hxx>
#endif
#ifndef _SV_SETTINGS_HXX
#include <vcl/settings.hxx>
#endif
#ifndef _SV_SVAPP_HXX
#include <vcl/svapp.hxx>
#endif

static void MovePosY( Window& _rWin, long _nDelta )
{
    Point   aPoint = _rWin.GetPosPixel();
    aPoint.Y() += _nDelta;

    _rWin.SetPosPixel( aPoint );
}

struct SvxAccessibilityOptionsTabPage_Impl
{
    SvtAccessibilityOptions     m_aConfig;
    SvxAccessibilityOptionsTabPage_Impl()
            : m_aConfig(){}
};

SvxAccessibilityOptionsTabPage::SvxAccessibilityOptionsTabPage( Window* pParent, const SfxItemSet& rSet )
    :SfxTabPage(pParent, ResId( RID_SVXPAGE_ACCESSIBILITYCONFIG, DIALOG_MGR() ), rSet)
    ,m_aMiscellaneousLabel      (this, ResId(FL_MISCELLANEOUS       ))
    ,m_aAccessibilityTool       (this, ResId(CB_ACCESSIBILITY_TOOL  ))
    ,m_aTextSelectionInReadonly (this, ResId(CB_TEXTSELECTION       ))
    ,m_aAnimatedGraphics        (this, ResId(CB_ANIMATED_GRAPHICS   ))
    ,m_aAnimatedTexts           (this, ResId(CB_ANIMATED_TEXTS      ))
    ,m_aTipHelpCB               (this, ResId(CB_TIPHELP             ))
    ,m_aTipHelpNF               (this, ResId(NF_TIPHELP             ))
    ,m_aTipHelpFT               (this, ResId(FT_TIPHELP             ))
    ,m_aHCOptionsLabel          (this, ResId(FL_HC_OPTIONS          ))
    ,m_aAutoDetectHC            (this, ResId(CB_AUTO_DETECT_HC      ))
    ,m_aAutomaticFontColor      (this, ResId(CB_AUTOMATIC_FONT_COLOR))
    ,m_aPagePreviews            (this, ResId(CB_PAGE_PREVIEWS       ))
    ,m_pImpl(new SvxAccessibilityOptionsTabPage_Impl)
{
    FreeResource();
    m_aTipHelpCB.SetClickHdl(LINK(this, SvxAccessibilityOptionsTabPage, TipHelpHdl));

    long nHeightDelta = 0;      // to correct positions _under_ m_aAccessibilityTool

#ifdef UNX
    {
        // UNIX: read the gconf2 setting instead to use the checkbox
        m_aAccessibilityTool.Hide();
        nHeightDelta = -( ROWA_2 - ROWA_1 );
    }
#else
    // calculate the height of the checkbox. Do we need two (default in resource) or only one line
    String aText = m_aAccessibilityTool.GetText();
    long nWidth = m_aAccessibilityTool.GetTextWidth( aText );
    long nCtrlWidth = m_aAccessibilityTool.GetSizePixel().Width() - ( COL2 - COL1 );
    if ( nWidth > nCtrlWidth )
    {
        long nDelta = 2 * RSC_CD_FIXEDLINE_HEIGHT + LINESPACE - RSC_CD_CHECKBOX_HEIGHT;
        nHeightDelta = nDelta;
        Size aSize = m_aAccessibilityTool.LogicToPixel( Size( 0, nDelta ), MAP_APPFONT );
        nDelta = aSize.Height();
        aSize = m_aAccessibilityTool.GetSizePixel();
        aSize.Height() += nDelta;
        m_aAccessibilityTool.SetSizePixel( aSize );
    }
#endif

    if( nHeightDelta )
    {   //adjust positions of controls under m_aAccessibilityTool
        Size aSize = m_aAccessibilityTool.LogicToPixel( Size( 0, nHeightDelta ), MAP_APPFONT );
        nHeightDelta = aSize.Height();

        MovePosY( m_aTextSelectionInReadonly, nHeightDelta );
        MovePosY( m_aAnimatedGraphics, nHeightDelta );
        MovePosY( m_aAnimatedTexts, nHeightDelta );
        MovePosY( m_aTipHelpCB, nHeightDelta );
        MovePosY( m_aTipHelpNF, nHeightDelta );
        MovePosY( m_aTipHelpFT, nHeightDelta );
        MovePosY( m_aHCOptionsLabel, nHeightDelta );
        MovePosY( m_aAutoDetectHC, nHeightDelta );
        MovePosY( m_aAutomaticFontColor, nHeightDelta );
        MovePosY( m_aPagePreviews, nHeightDelta );
    }
}

SvxAccessibilityOptionsTabPage::~SvxAccessibilityOptionsTabPage()
{
    delete m_pImpl;
}

SfxTabPage* SvxAccessibilityOptionsTabPage::Create( Window* pParent, const SfxItemSet& rAttrSet )
{
    return new SvxAccessibilityOptionsTabPage(pParent, rAttrSet);
}

BOOL SvxAccessibilityOptionsTabPage::FillItemSet( SfxItemSet& rSet )
{
    //aConfig.Set... from controls

    m_pImpl->m_aConfig.SetIsForPagePreviews( m_aPagePreviews.IsChecked() );
    m_pImpl->m_aConfig.SetIsHelpTipsDisappear( m_aTipHelpCB.IsChecked() );
    m_pImpl->m_aConfig.SetHelpTipSeconds( (short)m_aTipHelpNF.GetValue() );
    m_pImpl->m_aConfig.SetIsAllowAnimatedGraphics( m_aAnimatedGraphics.IsChecked() );
    m_pImpl->m_aConfig.SetIsAllowAnimatedText( m_aAnimatedTexts.IsChecked() );
    m_pImpl->m_aConfig.SetIsAutomaticFontColor( m_aAutomaticFontColor.IsChecked() );
    m_pImpl->m_aConfig.SetSelectionInReadonly( m_aTextSelectionInReadonly.IsChecked());
    m_pImpl->m_aConfig.SetAutoDetectSystemHC( m_aAutoDetectHC.IsChecked());

    if(m_pImpl->m_aConfig.IsModified())
        m_pImpl->m_aConfig.Commit();

#ifndef UNX
    AllSettings aAllSettings = Application::GetSettings();
    MiscSettings aMiscSettings = aAllSettings.GetMiscSettings();
    aMiscSettings.SetEnableATToolSupport( m_aAccessibilityTool.IsChecked() );
    aAllSettings.SetMiscSettings(aMiscSettings);
    Application::SetSettings(aAllSettings);
    Application::MergeSystemSettings( aAllSettings );
#endif

    return FALSE;
}

void SvxAccessibilityOptionsTabPage::Reset( const SfxItemSet& rSet )
{
    //set controls from aConfig.Get...

    m_aPagePreviews.Check(            m_pImpl->m_aConfig.GetIsForPagePreviews() );
    EnableTipHelp(                    m_pImpl->m_aConfig.GetIsHelpTipsDisappear() );
    m_aTipHelpNF.SetValue(            m_pImpl->m_aConfig.GetHelpTipSeconds() );
    m_aAnimatedGraphics.Check(        m_pImpl->m_aConfig.GetIsAllowAnimatedGraphics() );
    m_aAnimatedTexts.Check(           m_pImpl->m_aConfig.GetIsAllowAnimatedText() );
    m_aAutomaticFontColor.Check(      m_pImpl->m_aConfig.GetIsAutomaticFontColor() );
//  m_aSystemFont.Check(              m_pImpl->m_aConfig.GetIsSystemFont() );
    m_aTextSelectionInReadonly.Check( m_pImpl->m_aConfig.IsSelectionInReadonly() );
    m_aAutoDetectHC.Check(            m_pImpl->m_aConfig.GetAutoDetectSystemHC() );

    AllSettings aAllSettings = Application::GetSettings();
    MiscSettings aMiscSettings = aAllSettings.GetMiscSettings();
    m_aAccessibilityTool.Check( aMiscSettings.GetEnableATToolSupport() );
}

IMPL_LINK(SvxAccessibilityOptionsTabPage, TipHelpHdl, CheckBox*, pBox)
{
    sal_Bool bChecked = pBox->IsChecked();
    m_aTipHelpNF.Enable(bChecked);
    return 0;
}

void SvxAccessibilityOptionsTabPage::EnableTipHelp(sal_Bool bCheck)
{
    m_aTipHelpCB.Check(bCheck);
    m_aTipHelpNF.Enable(bCheck);
}
<commit_msg>INTEGRATION: CWS ooo19126 (1.4.430); FILE MERGED 2005/09/05 14:21:26 rt 1.4.430.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: optaccessibility.cxx,v $
 *
 *  $Revision: 1.5 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-08 21:38:50 $
 *
 *  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
 *
 ************************************************************************/

#ifdef SVX_DLLIMPLEMENTATION
#undef SVX_DLLIMPLEMENTATION
#endif

#ifndef _SVX_OPTACCESSIBILITY_HXX
#include <optaccessibility.hxx>
#endif
#include <optaccessibility.hrc>
#include <dialmgr.hxx>
#include "dialogs.hrc"
#ifndef INCLUDED_SVTOOLS_ACCESSIBILITYOPTIONS_HXX
#include <svtools/accessibilityoptions.hxx>
#endif
#ifndef _SV_SETTINGS_HXX
#include <vcl/settings.hxx>
#endif
#ifndef _SV_SVAPP_HXX
#include <vcl/svapp.hxx>
#endif

static void MovePosY( Window& _rWin, long _nDelta )
{
    Point   aPoint = _rWin.GetPosPixel();
    aPoint.Y() += _nDelta;

    _rWin.SetPosPixel( aPoint );
}

struct SvxAccessibilityOptionsTabPage_Impl
{
    SvtAccessibilityOptions     m_aConfig;
    SvxAccessibilityOptionsTabPage_Impl()
            : m_aConfig(){}
};

SvxAccessibilityOptionsTabPage::SvxAccessibilityOptionsTabPage( Window* pParent, const SfxItemSet& rSet )
    :SfxTabPage(pParent, ResId( RID_SVXPAGE_ACCESSIBILITYCONFIG, DIALOG_MGR() ), rSet)
    ,m_aMiscellaneousLabel      (this, ResId(FL_MISCELLANEOUS       ))
    ,m_aAccessibilityTool       (this, ResId(CB_ACCESSIBILITY_TOOL  ))
    ,m_aTextSelectionInReadonly (this, ResId(CB_TEXTSELECTION       ))
    ,m_aAnimatedGraphics        (this, ResId(CB_ANIMATED_GRAPHICS   ))
    ,m_aAnimatedTexts           (this, ResId(CB_ANIMATED_TEXTS      ))
    ,m_aTipHelpCB               (this, ResId(CB_TIPHELP             ))
    ,m_aTipHelpNF               (this, ResId(NF_TIPHELP             ))
    ,m_aTipHelpFT               (this, ResId(FT_TIPHELP             ))
    ,m_aHCOptionsLabel          (this, ResId(FL_HC_OPTIONS          ))
    ,m_aAutoDetectHC            (this, ResId(CB_AUTO_DETECT_HC      ))
    ,m_aAutomaticFontColor      (this, ResId(CB_AUTOMATIC_FONT_COLOR))
    ,m_aPagePreviews            (this, ResId(CB_PAGE_PREVIEWS       ))
    ,m_pImpl(new SvxAccessibilityOptionsTabPage_Impl)
{
    FreeResource();
    m_aTipHelpCB.SetClickHdl(LINK(this, SvxAccessibilityOptionsTabPage, TipHelpHdl));

    long nHeightDelta = 0;      // to correct positions _under_ m_aAccessibilityTool

#ifdef UNX
    {
        // UNIX: read the gconf2 setting instead to use the checkbox
        m_aAccessibilityTool.Hide();
        nHeightDelta = -( ROWA_2 - ROWA_1 );
    }
#else
    // calculate the height of the checkbox. Do we need two (default in resource) or only one line
    String aText = m_aAccessibilityTool.GetText();
    long nWidth = m_aAccessibilityTool.GetTextWidth( aText );
    long nCtrlWidth = m_aAccessibilityTool.GetSizePixel().Width() - ( COL2 - COL1 );
    if ( nWidth > nCtrlWidth )
    {
        long nDelta = 2 * RSC_CD_FIXEDLINE_HEIGHT + LINESPACE - RSC_CD_CHECKBOX_HEIGHT;
        nHeightDelta = nDelta;
        Size aSize = m_aAccessibilityTool.LogicToPixel( Size( 0, nDelta ), MAP_APPFONT );
        nDelta = aSize.Height();
        aSize = m_aAccessibilityTool.GetSizePixel();
        aSize.Height() += nDelta;
        m_aAccessibilityTool.SetSizePixel( aSize );
    }
#endif

    if( nHeightDelta )
    {   //adjust positions of controls under m_aAccessibilityTool
        Size aSize = m_aAccessibilityTool.LogicToPixel( Size( 0, nHeightDelta ), MAP_APPFONT );
        nHeightDelta = aSize.Height();

        MovePosY( m_aTextSelectionInReadonly, nHeightDelta );
        MovePosY( m_aAnimatedGraphics, nHeightDelta );
        MovePosY( m_aAnimatedTexts, nHeightDelta );
        MovePosY( m_aTipHelpCB, nHeightDelta );
        MovePosY( m_aTipHelpNF, nHeightDelta );
        MovePosY( m_aTipHelpFT, nHeightDelta );
        MovePosY( m_aHCOptionsLabel, nHeightDelta );
        MovePosY( m_aAutoDetectHC, nHeightDelta );
        MovePosY( m_aAutomaticFontColor, nHeightDelta );
        MovePosY( m_aPagePreviews, nHeightDelta );
    }
}

SvxAccessibilityOptionsTabPage::~SvxAccessibilityOptionsTabPage()
{
    delete m_pImpl;
}

SfxTabPage* SvxAccessibilityOptionsTabPage::Create( Window* pParent, const SfxItemSet& rAttrSet )
{
    return new SvxAccessibilityOptionsTabPage(pParent, rAttrSet);
}

BOOL SvxAccessibilityOptionsTabPage::FillItemSet( SfxItemSet& rSet )
{
    //aConfig.Set... from controls

    m_pImpl->m_aConfig.SetIsForPagePreviews( m_aPagePreviews.IsChecked() );
    m_pImpl->m_aConfig.SetIsHelpTipsDisappear( m_aTipHelpCB.IsChecked() );
    m_pImpl->m_aConfig.SetHelpTipSeconds( (short)m_aTipHelpNF.GetValue() );
    m_pImpl->m_aConfig.SetIsAllowAnimatedGraphics( m_aAnimatedGraphics.IsChecked() );
    m_pImpl->m_aConfig.SetIsAllowAnimatedText( m_aAnimatedTexts.IsChecked() );
    m_pImpl->m_aConfig.SetIsAutomaticFontColor( m_aAutomaticFontColor.IsChecked() );
    m_pImpl->m_aConfig.SetSelectionInReadonly( m_aTextSelectionInReadonly.IsChecked());
    m_pImpl->m_aConfig.SetAutoDetectSystemHC( m_aAutoDetectHC.IsChecked());

    if(m_pImpl->m_aConfig.IsModified())
        m_pImpl->m_aConfig.Commit();

#ifndef UNX
    AllSettings aAllSettings = Application::GetSettings();
    MiscSettings aMiscSettings = aAllSettings.GetMiscSettings();
    aMiscSettings.SetEnableATToolSupport( m_aAccessibilityTool.IsChecked() );
    aAllSettings.SetMiscSettings(aMiscSettings);
    Application::SetSettings(aAllSettings);
    Application::MergeSystemSettings( aAllSettings );
#endif

    return FALSE;
}

void SvxAccessibilityOptionsTabPage::Reset( const SfxItemSet& rSet )
{
    //set controls from aConfig.Get...

    m_aPagePreviews.Check(            m_pImpl->m_aConfig.GetIsForPagePreviews() );
    EnableTipHelp(                    m_pImpl->m_aConfig.GetIsHelpTipsDisappear() );
    m_aTipHelpNF.SetValue(            m_pImpl->m_aConfig.GetHelpTipSeconds() );
    m_aAnimatedGraphics.Check(        m_pImpl->m_aConfig.GetIsAllowAnimatedGraphics() );
    m_aAnimatedTexts.Check(           m_pImpl->m_aConfig.GetIsAllowAnimatedText() );
    m_aAutomaticFontColor.Check(      m_pImpl->m_aConfig.GetIsAutomaticFontColor() );
//  m_aSystemFont.Check(              m_pImpl->m_aConfig.GetIsSystemFont() );
    m_aTextSelectionInReadonly.Check( m_pImpl->m_aConfig.IsSelectionInReadonly() );
    m_aAutoDetectHC.Check(            m_pImpl->m_aConfig.GetAutoDetectSystemHC() );

    AllSettings aAllSettings = Application::GetSettings();
    MiscSettings aMiscSettings = aAllSettings.GetMiscSettings();
    m_aAccessibilityTool.Check( aMiscSettings.GetEnableATToolSupport() );
}

IMPL_LINK(SvxAccessibilityOptionsTabPage, TipHelpHdl, CheckBox*, pBox)
{
    sal_Bool bChecked = pBox->IsChecked();
    m_aTipHelpNF.Enable(bChecked);
    return 0;
}

void SvxAccessibilityOptionsTabPage::EnableTipHelp(sal_Bool bCheck)
{
    m_aTipHelpCB.Check(bCheck);
    m_aTipHelpNF.Enable(bCheck);
}
<|endoftext|>


<commit_before>//===-- safestack.cc ------------------------------------------------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file implements the runtime support for the safe stack protection
// mechanism. The runtime manages allocation/deallocation of the unsafe stack
// for the main thread, as well as all pthreads that are created/destroyed
// during program execution.
//
//===----------------------------------------------------------------------===//

#include <limits.h>
#include <pthread.h>
#include <stddef.h>
#include <stdint.h>
#include <sys/resource.h>
#include <sys/user.h>

#include "interception/interception.h"
#include "sanitizer_common/sanitizer_common.h"

// TODO: The runtime library does not currently protect the safe stack beyond
// relying on the system-enforced ASLR. The protection of the (safe) stack can
// be provided by three alternative features:
//
// 1) Protection via hardware segmentation on x86-32 and some x86-64
// architectures: the (safe) stack segment (implicitly accessed via the %ss
// segment register) can be separated from the data segment (implicitly
// accessed via the %ds segment register). Dereferencing a pointer to the safe
// segment would result in a segmentation fault.
//
// 2) Protection via software fault isolation: memory writes that are not meant
// to access the safe stack can be prevented from doing so through runtime
// instrumentation. One way to do it is to allocate the safe stack(s) in the
// upper half of the userspace and bitmask the corresponding upper bit of the
// memory addresses of memory writes that are not meant to access the safe
// stack.
//
// 3) Protection via information hiding on 64 bit architectures: the location
// of the safe stack(s) can be randomized through secure mechanisms, and the
// leakage of the stack pointer can be prevented. Currently, libc can leak the
// stack pointer in several ways (e.g. in longjmp, signal handling, user-level
// context switching related functions, etc.). These can be fixed in libc and
// in other low-level libraries, by either eliminating the escaping/dumping of
// the stack pointer (i.e., %rsp) when that's possible, or by using
// encryption/PTR_MANGLE (XOR-ing the dumped stack pointer with another secret
// we control and protect better, as is already done for setjmp in glibc.)
// Furthermore, a static machine code level verifier can be ran after code
// generation to make sure that the stack pointer is never written to memory,
// or if it is, its written on the safe stack.
//
// Finally, while the Unsafe Stack pointer is currently stored in a thread
// local variable, with libc support it could be stored in the TCB (thread
// control block) as well, eliminating another level of indirection and making
// such accesses faster. Alternatively, dedicating a separate register for
// storing it would also be possible.

/// Minimum stack alignment for the unsafe stack.
const unsigned kStackAlign = 16;

/// Default size of the unsafe stack. This value is only used if the stack
/// size rlimit is set to infinity.
const unsigned kDefaultUnsafeStackSize = 0x2800000;

// TODO: To make accessing the unsafe stack pointer faster, we plan to
// eventually store it directly in the thread control block data structure on
// platforms where this structure is pointed to by %fs or %gs. This is exactly
// the same mechanism as currently being used by the traditional stack
// protector pass to store the stack guard (see getStackCookieLocation()
// function above). Doing so requires changing the tcbhead_t struct in glibc
// on Linux and tcb struct in libc on FreeBSD.
//
// For now, store it in a thread-local variable.
extern "C" {
__attribute__((visibility(
    "default"))) __thread void *__safestack_unsafe_stack_ptr = nullptr;
}

// Per-thread unsafe stack information. It's not frequently accessed, so there
// it can be kept out of the tcb in normal thread-local variables.
static __thread void *unsafe_stack_start = nullptr;
static __thread size_t unsafe_stack_size = 0;
static __thread size_t unsafe_stack_guard = 0;

static inline void *unsafe_stack_alloc(size_t size, size_t guard) {
  CHECK_GE(size + guard, size);
  void *addr = MmapOrDie(size + guard, "unsafe_stack_alloc");
  MprotectNoAccess((uptr)addr, (uptr)guard);
  return (char *)addr + guard;
}

static inline void unsafe_stack_setup(void *start, size_t size, size_t guard) {
  CHECK_GE((char *)start + size, (char *)start);
  CHECK_GE((char *)start + guard, (char *)start);
  void *stack_ptr = (char *)start + size;
  CHECK_EQ((((size_t)stack_ptr) & (kStackAlign - 1)), 0);

  __safestack_unsafe_stack_ptr = stack_ptr;
  unsafe_stack_start = start;
  unsafe_stack_size = size;
  unsafe_stack_guard = guard;
}

static void unsafe_stack_free() {
  if (unsafe_stack_start) {
    UnmapOrDie((char *)unsafe_stack_start - unsafe_stack_guard,
               unsafe_stack_size + unsafe_stack_guard);
  }
  unsafe_stack_start = nullptr;
}

/// Thread data for the cleanup handler
static pthread_key_t thread_cleanup_key;

/// Safe stack per-thread information passed to the thread_start function
struct tinfo {
  void *(*start_routine)(void *);
  void *start_routine_arg;

  void *unsafe_stack_start;
  size_t unsafe_stack_size;
  size_t unsafe_stack_guard;
};

/// Wrap the thread function in order to deallocate the unsafe stack when the
/// thread terminates by returning from its main function.
static void *thread_start(void *arg) {
  struct tinfo *tinfo = (struct tinfo *)arg;

  void *(*start_routine)(void *) = tinfo->start_routine;
  void *start_routine_arg = tinfo->start_routine_arg;

  // Setup the unsafe stack; this will destroy tinfo content
  unsafe_stack_setup(tinfo->unsafe_stack_start, tinfo->unsafe_stack_size,
                     tinfo->unsafe_stack_guard);

  // Make sure out thread-specific destructor will be called
  // FIXME: we can do this only any other specific key is set by
  // intercepting the pthread_setspecific function itself
  pthread_setspecific(thread_cleanup_key, (void *)1);

  return start_routine(start_routine_arg);
}

/// Thread-specific data destructor
static void thread_cleanup_handler(void *_iter) {
  // We want to free the unsafe stack only after all other destructors
  // have already run. We force this function to be called multiple times.
  // User destructors that might run more then PTHREAD_DESTRUCTOR_ITERATIONS-1
  // times might still end up executing after the unsafe stack is deallocated.
  size_t iter = (size_t)_iter;
  if (iter < PTHREAD_DESTRUCTOR_ITERATIONS) {
    pthread_setspecific(thread_cleanup_key, (void *)(iter + 1));
  } else {
    // This is the last iteration
    unsafe_stack_free();
  }
}

/// Intercept thread creation operation to allocate and setup the unsafe stack
INTERCEPTOR(int, pthread_create, pthread_t *thread,
            const pthread_attr_t *attr,
            void *(*start_routine)(void*), void *arg) {

  size_t size = 0;
  size_t guard = 0;

  if (attr != NULL) {
    pthread_attr_getstacksize(attr, &size);
    pthread_attr_getguardsize(attr, &guard);
  } else {
    // get pthread default stack size
    pthread_attr_t tmpattr;
    pthread_attr_init(&tmpattr);
    pthread_attr_getstacksize(&tmpattr, &size);
    pthread_attr_getguardsize(&tmpattr, &guard);
    pthread_attr_destroy(&tmpattr);
  }

  CHECK_NE(size, 0);
  CHECK_EQ((size & (kStackAlign - 1)), 0);
  CHECK_EQ((guard & (PAGE_SIZE - 1)), 0);

  void *addr = unsafe_stack_alloc(size, guard);
  struct tinfo *tinfo =
      (struct tinfo *)(((char *)addr) + size - sizeof(struct tinfo));
  tinfo->start_routine = start_routine;
  tinfo->start_routine_arg = arg;
  tinfo->unsafe_stack_start = addr;
  tinfo->unsafe_stack_size = size;
  tinfo->unsafe_stack_guard = guard;

  return REAL(pthread_create)(thread, attr, thread_start, tinfo);
}

extern "C" __attribute__((visibility("default")))
#if !SANITIZER_CAN_USE_PREINIT_ARRAY
// On ELF platforms, the constructor is invoked using .preinit_array (see below)
__attribute__((constructor(0)))
#endif
void __safestack_init() {
  // Determine the stack size for the main thread.
  size_t size = kDefaultUnsafeStackSize;
  size_t guard = 4096;

  struct rlimit limit;
  if (getrlimit(RLIMIT_STACK, &limit) == 0 && limit.rlim_cur != RLIM_INFINITY)
    size = limit.rlim_cur;

  // Allocate unsafe stack for main thread
  void *addr = unsafe_stack_alloc(size, guard);

  unsafe_stack_setup(addr, size, guard);

  // Initialize pthread interceptors for thread allocation
  INTERCEPT_FUNCTION(pthread_create);

  // Setup the cleanup handler
  pthread_key_create(&thread_cleanup_key, thread_cleanup_handler);
}

#if SANITIZER_CAN_USE_PREINIT_ARRAY
// On ELF platforms, run safestack initialization before any other constructors.
// On other platforms we use the constructor attribute to arrange to run our
// initialization early.
extern "C" {
__attribute__((section(".preinit_array"),
               used)) void (*__safestack_preinit)(void) = __safestack_init;
}
#endif

extern "C"
    __attribute__((visibility("default"))) void *__get_unsafe_stack_start() {
  return unsafe_stack_start;
}

extern "C"
    __attribute__((visibility("default"))) void *__get_unsafe_stack_ptr() {
  return __safestack_unsafe_stack_ptr;
}
<commit_msg>SafeStack: Add another missing header to try to fix FreeBSD build.<commit_after>//===-- safestack.cc ------------------------------------------------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file implements the runtime support for the safe stack protection
// mechanism. The runtime manages allocation/deallocation of the unsafe stack
// for the main thread, as well as all pthreads that are created/destroyed
// during program execution.
//
//===----------------------------------------------------------------------===//

#include <limits.h>
#include <pthread.h>
#include <stddef.h>
#include <stdint.h>
#include <sys/resource.h>
#include <sys/types.h>
#include <sys/user.h>

#include "interception/interception.h"
#include "sanitizer_common/sanitizer_common.h"

// TODO: The runtime library does not currently protect the safe stack beyond
// relying on the system-enforced ASLR. The protection of the (safe) stack can
// be provided by three alternative features:
//
// 1) Protection via hardware segmentation on x86-32 and some x86-64
// architectures: the (safe) stack segment (implicitly accessed via the %ss
// segment register) can be separated from the data segment (implicitly
// accessed via the %ds segment register). Dereferencing a pointer to the safe
// segment would result in a segmentation fault.
//
// 2) Protection via software fault isolation: memory writes that are not meant
// to access the safe stack can be prevented from doing so through runtime
// instrumentation. One way to do it is to allocate the safe stack(s) in the
// upper half of the userspace and bitmask the corresponding upper bit of the
// memory addresses of memory writes that are not meant to access the safe
// stack.
//
// 3) Protection via information hiding on 64 bit architectures: the location
// of the safe stack(s) can be randomized through secure mechanisms, and the
// leakage of the stack pointer can be prevented. Currently, libc can leak the
// stack pointer in several ways (e.g. in longjmp, signal handling, user-level
// context switching related functions, etc.). These can be fixed in libc and
// in other low-level libraries, by either eliminating the escaping/dumping of
// the stack pointer (i.e., %rsp) when that's possible, or by using
// encryption/PTR_MANGLE (XOR-ing the dumped stack pointer with another secret
// we control and protect better, as is already done for setjmp in glibc.)
// Furthermore, a static machine code level verifier can be ran after code
// generation to make sure that the stack pointer is never written to memory,
// or if it is, its written on the safe stack.
//
// Finally, while the Unsafe Stack pointer is currently stored in a thread
// local variable, with libc support it could be stored in the TCB (thread
// control block) as well, eliminating another level of indirection and making
// such accesses faster. Alternatively, dedicating a separate register for
// storing it would also be possible.

/// Minimum stack alignment for the unsafe stack.
const unsigned kStackAlign = 16;

/// Default size of the unsafe stack. This value is only used if the stack
/// size rlimit is set to infinity.
const unsigned kDefaultUnsafeStackSize = 0x2800000;

// TODO: To make accessing the unsafe stack pointer faster, we plan to
// eventually store it directly in the thread control block data structure on
// platforms where this structure is pointed to by %fs or %gs. This is exactly
// the same mechanism as currently being used by the traditional stack
// protector pass to store the stack guard (see getStackCookieLocation()
// function above). Doing so requires changing the tcbhead_t struct in glibc
// on Linux and tcb struct in libc on FreeBSD.
//
// For now, store it in a thread-local variable.
extern "C" {
__attribute__((visibility(
    "default"))) __thread void *__safestack_unsafe_stack_ptr = nullptr;
}

// Per-thread unsafe stack information. It's not frequently accessed, so there
// it can be kept out of the tcb in normal thread-local variables.
static __thread void *unsafe_stack_start = nullptr;
static __thread size_t unsafe_stack_size = 0;
static __thread size_t unsafe_stack_guard = 0;

static inline void *unsafe_stack_alloc(size_t size, size_t guard) {
  CHECK_GE(size + guard, size);
  void *addr = MmapOrDie(size + guard, "unsafe_stack_alloc");
  MprotectNoAccess((uptr)addr, (uptr)guard);
  return (char *)addr + guard;
}

static inline void unsafe_stack_setup(void *start, size_t size, size_t guard) {
  CHECK_GE((char *)start + size, (char *)start);
  CHECK_GE((char *)start + guard, (char *)start);
  void *stack_ptr = (char *)start + size;
  CHECK_EQ((((size_t)stack_ptr) & (kStackAlign - 1)), 0);

  __safestack_unsafe_stack_ptr = stack_ptr;
  unsafe_stack_start = start;
  unsafe_stack_size = size;
  unsafe_stack_guard = guard;
}

static void unsafe_stack_free() {
  if (unsafe_stack_start) {
    UnmapOrDie((char *)unsafe_stack_start - unsafe_stack_guard,
               unsafe_stack_size + unsafe_stack_guard);
  }
  unsafe_stack_start = nullptr;
}

/// Thread data for the cleanup handler
static pthread_key_t thread_cleanup_key;

/// Safe stack per-thread information passed to the thread_start function
struct tinfo {
  void *(*start_routine)(void *);
  void *start_routine_arg;

  void *unsafe_stack_start;
  size_t unsafe_stack_size;
  size_t unsafe_stack_guard;
};

/// Wrap the thread function in order to deallocate the unsafe stack when the
/// thread terminates by returning from its main function.
static void *thread_start(void *arg) {
  struct tinfo *tinfo = (struct tinfo *)arg;

  void *(*start_routine)(void *) = tinfo->start_routine;
  void *start_routine_arg = tinfo->start_routine_arg;

  // Setup the unsafe stack; this will destroy tinfo content
  unsafe_stack_setup(tinfo->unsafe_stack_start, tinfo->unsafe_stack_size,
                     tinfo->unsafe_stack_guard);

  // Make sure out thread-specific destructor will be called
  // FIXME: we can do this only any other specific key is set by
  // intercepting the pthread_setspecific function itself
  pthread_setspecific(thread_cleanup_key, (void *)1);

  return start_routine(start_routine_arg);
}

/// Thread-specific data destructor
static void thread_cleanup_handler(void *_iter) {
  // We want to free the unsafe stack only after all other destructors
  // have already run. We force this function to be called multiple times.
  // User destructors that might run more then PTHREAD_DESTRUCTOR_ITERATIONS-1
  // times might still end up executing after the unsafe stack is deallocated.
  size_t iter = (size_t)_iter;
  if (iter < PTHREAD_DESTRUCTOR_ITERATIONS) {
    pthread_setspecific(thread_cleanup_key, (void *)(iter + 1));
  } else {
    // This is the last iteration
    unsafe_stack_free();
  }
}

/// Intercept thread creation operation to allocate and setup the unsafe stack
INTERCEPTOR(int, pthread_create, pthread_t *thread,
            const pthread_attr_t *attr,
            void *(*start_routine)(void*), void *arg) {

  size_t size = 0;
  size_t guard = 0;

  if (attr != NULL) {
    pthread_attr_getstacksize(attr, &size);
    pthread_attr_getguardsize(attr, &guard);
  } else {
    // get pthread default stack size
    pthread_attr_t tmpattr;
    pthread_attr_init(&tmpattr);
    pthread_attr_getstacksize(&tmpattr, &size);
    pthread_attr_getguardsize(&tmpattr, &guard);
    pthread_attr_destroy(&tmpattr);
  }

  CHECK_NE(size, 0);
  CHECK_EQ((size & (kStackAlign - 1)), 0);
  CHECK_EQ((guard & (PAGE_SIZE - 1)), 0);

  void *addr = unsafe_stack_alloc(size, guard);
  struct tinfo *tinfo =
      (struct tinfo *)(((char *)addr) + size - sizeof(struct tinfo));
  tinfo->start_routine = start_routine;
  tinfo->start_routine_arg = arg;
  tinfo->unsafe_stack_start = addr;
  tinfo->unsafe_stack_size = size;
  tinfo->unsafe_stack_guard = guard;

  return REAL(pthread_create)(thread, attr, thread_start, tinfo);
}

extern "C" __attribute__((visibility("default")))
#if !SANITIZER_CAN_USE_PREINIT_ARRAY
// On ELF platforms, the constructor is invoked using .preinit_array (see below)
__attribute__((constructor(0)))
#endif
void __safestack_init() {
  // Determine the stack size for the main thread.
  size_t size = kDefaultUnsafeStackSize;
  size_t guard = 4096;

  struct rlimit limit;
  if (getrlimit(RLIMIT_STACK, &limit) == 0 && limit.rlim_cur != RLIM_INFINITY)
    size = limit.rlim_cur;

  // Allocate unsafe stack for main thread
  void *addr = unsafe_stack_alloc(size, guard);

  unsafe_stack_setup(addr, size, guard);

  // Initialize pthread interceptors for thread allocation
  INTERCEPT_FUNCTION(pthread_create);

  // Setup the cleanup handler
  pthread_key_create(&thread_cleanup_key, thread_cleanup_handler);
}

#if SANITIZER_CAN_USE_PREINIT_ARRAY
// On ELF platforms, run safestack initialization before any other constructors.
// On other platforms we use the constructor attribute to arrange to run our
// initialization early.
extern "C" {
__attribute__((section(".preinit_array"),
               used)) void (*__safestack_preinit)(void) = __safestack_init;
}
#endif

extern "C"
    __attribute__((visibility("default"))) void *__get_unsafe_stack_start() {
  return unsafe_stack_start;
}

extern "C"
    __attribute__((visibility("default"))) void *__get_unsafe_stack_ptr() {
  return __safestack_unsafe_stack_ptr;
}
<|endoftext|>


<commit_before><commit_msg>tools: Fix small bug in ProtoFileToDotProto am: a5221eeff1 am: a9a2fd14c9 am: 7995163897<commit_after><|endoftext|>


<commit_before>/**
 * \file AddTaskHighPtReducedEventCreator.C
 * \brief Add macro for the reduced event creator task
 * \author Markus Fasel <markus.fasel@cern.ch>, Lawrence Berkeley National Laboratory
 * \date Apr 16, 2015
 */
# if !defined __CINT__ || defined __MAKECINT__
#include <TList.h>
#include <TROOT.h>
#include <TString.h>
#include <TSystem.h>
#include <TTree.h>

#include "AliAnalysisManager.h"
#include "AliAnalysisDataContainer.h"
#include "AliAODInputHandler.h"
#include "AliReducedHighPtEventCreator.h"
#endif

/**
 * Configure reduced event creator task and add it to the analysis manager
 * \param isMC Flag for MC analysis
 * \param isPythia Flag for pythia hard analysis
 * \param trackContainer Name of the track container
 * \param clusterContainer Name of the cluster container
 * \param triggerContainer Name of the trigger container
 * \return Fully configured tree selector task
 */
HighPtTracks::AliReducedHighPtEventCreator *AddTaskHighPtReducedEventCreator(
    Bool_t isMC = kFALSE,
    Bool_t isPythia = kFALSE,
    const char *trackContainer = "",
    const char *clusterContainer = "",
    const char *triggerContainer = "",
    const char *outputfilename = ""
    ){
  AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();

  // Create task, make event specific settings
  TString taskname = "ReducedEventCreator";
  TString outputname = outputfilename;
  if(outputname.Length){
    taskname = outputname(0, outputname.Index(".root"));
  }
  HighPtTracks::AliReducedHighPtEventCreator *reducedEventCreator = new HighPtTracks::AliReducedHighPtEventCreator(taskname.Data());
  if(isPythia) reducedEventCreator->SetIsPythia(kTRUE);
  if(isMC) reducedEventCreator->SetSwapTriggerThresholds(kTRUE);
  reducedEventCreator->AddParticleContainer(trackContainer);
  reducedEventCreator->AddClusterContainer(clusterContainer);
  reducedEventCreator->SetCaloTriggerPatchInfoName(triggerContainer);

  // Set kinematic range for tracks and particles
  reducedEventCreator->SetEtaRange(-0.8, 0.8);
  reducedEventCreator->SetPtRange(0.1,100);
  reducedEventCreator->SetClusterEnergyCut(2., 100.);

  // Handle track selection, outsourced to a different macro
  gROOT->LoadMacro(Form("%s/PWGJE/EMCALJetTasks/macros/ReducedEventCutVariation.C", gSystem->Getenv("ALICE_PHYSICS")));
  ReducedEventCutVariation(reducedEventCreator, mgr->GetInputEventHandler()->IsA() == AliAODInputHandler::Class());

  TString commonoutput = TString(mgr->GetCommonFileName()) + ":" + taskname;
  TString treeoutputfile = "ReducedHighPtEvent.root";
  if(outputname.Length()) treeoutputfile = outputname;
  mgr->ConnectInput(reducedEventCreator, 0, mgr->GetCommonInputContainer());
  mgr->ConnectOutput(reducedEventCreator, 1, mgr->CreateContainer(reducedEventCreator->GetName(), TList::Class(), AliAnalysisManager::kOutputContainer, commonoutput.Data()));
  mgr->ConnectOutput(reducedEventCreator, 2, mgr->CreateContainer("ReducedEvent", TTree::Class(), AliAnalysisManager::kOutputContainer, treeoutputfile.Data()));

  return reducedEventCreator;
}
<commit_msg>Fix typo<commit_after>/**
 * \file AddTaskHighPtReducedEventCreator.C
 * \brief Add macro for the reduced event creator task
 * \author Markus Fasel <markus.fasel@cern.ch>, Lawrence Berkeley National Laboratory
 * \date Apr 16, 2015
 */
# if !defined __CINT__ || defined __MAKECINT__
#include <TList.h>
#include <TROOT.h>
#include <TString.h>
#include <TSystem.h>
#include <TTree.h>

#include "AliAnalysisManager.h"
#include "AliAnalysisDataContainer.h"
#include "AliAODInputHandler.h"
#include "AliReducedHighPtEventCreator.h"
#endif

/**
 * Configure reduced event creator task and add it to the analysis manager
 * \param isMC Flag for MC analysis
 * \param isPythia Flag for pythia hard analysis
 * \param trackContainer Name of the track container
 * \param clusterContainer Name of the cluster container
 * \param triggerContainer Name of the trigger container
 * \return Fully configured tree selector task
 */
HighPtTracks::AliReducedHighPtEventCreator *AddTaskHighPtReducedEventCreator(
    Bool_t isMC = kFALSE,
    Bool_t isPythia = kFALSE,
    const char *trackContainer = "",
    const char *clusterContainer = "",
    const char *triggerContainer = "",
    const char *outputfilename = ""
    ){
  AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();

  // Create task, make event specific settings
  TString taskname = "ReducedEventCreator";
  TString outputname = outputfilename;
  if(outputname.Length()){
    taskname = outputname(0, outputname.Index(".root"));
  }
  HighPtTracks::AliReducedHighPtEventCreator *reducedEventCreator = new HighPtTracks::AliReducedHighPtEventCreator(taskname.Data());
  if(isPythia) reducedEventCreator->SetIsPythia(kTRUE);
  if(isMC) reducedEventCreator->SetSwapTriggerThresholds(kTRUE);
  reducedEventCreator->AddParticleContainer(trackContainer);
  reducedEventCreator->AddClusterContainer(clusterContainer);
  reducedEventCreator->SetCaloTriggerPatchInfoName(triggerContainer);

  // Set kinematic range for tracks and particles
  reducedEventCreator->SetEtaRange(-0.8, 0.8);
  reducedEventCreator->SetPtRange(0.1,100);
  reducedEventCreator->SetClusterEnergyCut(2., 100.);

  // Handle track selection, outsourced to a different macro
  gROOT->LoadMacro(Form("%s/PWGJE/EMCALJetTasks/macros/ReducedEventCutVariation.C", gSystem->Getenv("ALICE_PHYSICS")));
  ReducedEventCutVariation(reducedEventCreator, mgr->GetInputEventHandler()->IsA() == AliAODInputHandler::Class());

  TString commonoutput = TString(mgr->GetCommonFileName()) + ":" + taskname;
  TString treeoutputfile = "ReducedHighPtEvent.root";
  if(outputname.Length()) treeoutputfile = outputname;
  mgr->ConnectInput(reducedEventCreator, 0, mgr->GetCommonInputContainer());
  mgr->ConnectOutput(reducedEventCreator, 1, mgr->CreateContainer(reducedEventCreator->GetName(), TList::Class(), AliAnalysisManager::kOutputContainer, commonoutput.Data()));
  mgr->ConnectOutput(reducedEventCreator, 2, mgr->CreateContainer("ReducedEvent", TTree::Class(), AliAnalysisManager::kOutputContainer, treeoutputfile.Data()));

  return reducedEventCreator;
}
<|endoftext|>


<commit_before>// ParticleSwarmOptimization.h

#pragma once

#include "../Stdafx.h"
#include "Particle.hpp"
#include "Function.hpp"
using namespace ParticleSwarmOptimization;

namespace ParticleSwarmOptimization {

	class StandardParticle : public Particle {
	public:
	    explicit StandardParticle(int dimensions) : dimensions_(dimensions)
		{
			personal_best_ = make_tuple(std::vector<double>(2), std::numeric_limits<double>::infinity());
		}

		void init_location() override
		{
			std::vector<double> location(dimensions_);
			// this probably should go to static field or we should create ParticlesFactory responsible
			// for generating particles with proper distribution of location and in specific limits
			std::uniform_real_distribution<float> distribution(0.0f, 10.0f);
			std::mt19937 engine; // Mersenne twister MT19937
			auto generator = bind(distribution, engine);
			generate(location.begin(), location.end(), generator);
			// to remove after improving generation logic
			if (bounds_.size() == dimensions_) {
				transform(location.begin(), location.end(), bounds_.begin(), location.begin(), &clamp);
			}
			location_ = location;
		}

		void init_velocity() override
		{
			std::vector<double> velocity(dimensions_);
			std::uniform_real_distribution<float> distribution(0.0f, 2.0f); //Values between 0 and 2
			std::mt19937 engine; // Mersenne twister MT19937
			auto generator = std::bind(distribution, engine);
			generate(velocity.begin(), velocity.end(), generator);
			velocity_ = velocity;
		}

		std::tuple<std::vector<double>, double> update_personal_best(Function *function) override
		{
			auto value = function->evaluate(location_);
			return std::get<1>(personal_best_) > value ?
				(personal_best_ = make_tuple(location_, value)) : personal_best_;
		}

		void update_neighborhood(std::vector<Particle*> all_particles) override
		{
			if (neighborhood_.size() <= 0 )
			{
				neighborhood_ = all_particles;
			}
		}

		void update_velocity() override
		{
			std::tuple<std::vector<double>, double> global_best = personal_best_;

			for (int i = 0; i < neighborhood_.size(); ++i)
			{
				if (std::get<1>(neighborhood_[i]->get_personal_best()) > std::get<1>(global_best))
					global_best = neighborhood_[i]->get_personal_best();
			}

			std::vector<double> to_personal_best(dimensions_);
			std::vector<double> to_global_best(dimensions_);

			transform(std::get<0>(personal_best_).begin(), std::get<0>(personal_best_).end(),
				location_.begin(), to_personal_best.begin(), std::minus<double>());

			transform(std::get<0>(global_best).begin(), std::get<0>(global_best).end(), location_.begin(), to_global_best.begin(),
				std::minus<double>());

			std::random_device rd;
			std::default_random_engine e1(rd());
			std::uniform_real_distribution<float> uniform_dist(0.0f, 1.4f);
			double phi1 = uniform_dist(e1);
			double phi2 = uniform_dist(e1);
			double omega = 0.64;
			//1.4, 1.4, 0.64
			transform(to_personal_best.begin(), to_personal_best.end(), to_personal_best.begin(),
				bind1st(std::multiplies<double>(), phi1));

			transform(to_global_best.begin(), to_global_best.end(), to_global_best.begin(),
				bind1st(std::multiplies<double>(), phi2));
			//przemnozyc przez omege
			transform(velocity_.begin(), velocity_.end(), velocity_.begin(), bind1st(std::multiplies<double>(), omega));

			transform(velocity_.begin(), velocity_.end(), to_global_best.begin(), velocity_.begin(), std::plus<double>());
			transform(velocity_.begin(), velocity_.end(), to_personal_best.begin(), velocity_.begin(), std::plus<double>());
		}

		void translate() override
		{
			transform(location_.begin(), location_.end(), velocity_.begin(),
				location_.begin(), std::plus<double>());
			if (bounds_.size() == dimensions_) {
				transform(location_.begin(), location_.end(), bounds_.begin(), location_.begin(), &clamp);
			}
		}

	private:
		int dimensions_;
	};
}
<commit_msg>particle restart<commit_after>// ParticleSwarmOptimization.h

#pragma once

#include "../Stdafx.h"
#include "Particle.hpp"
#include "Function.hpp"
using namespace ParticleSwarmOptimization;

namespace ParticleSwarmOptimization {

	class StandardParticle : public Particle {
	private:
		int iters_from_last_best_change;
		const int restart_iters = 100;

	public:
	    explicit StandardParticle(int dimensions) : dimensions_(dimensions)
		{
			iters_from_last_best_change = 0;
			personal_best_ = make_tuple(std::vector<double>(2), std::numeric_limits<double>::infinity());
		}

		void init_location() override
		{
			std::vector<double> location(dimensions_);
			// this probably should go to static field or we should create ParticlesFactory responsible
			// for generating particles with proper distribution of location and in specific limits
			std::uniform_real_distribution<float> distribution(0.0f, 10.0f);
			std::mt19937 engine; // Mersenne twister MT19937
			auto generator = bind(distribution, engine);
			generate(location.begin(), location.end(), generator);
			// to remove after improving generation logic
			if (bounds_.size() == dimensions_) {
				transform(location.begin(), location.end(), bounds_.begin(), location.begin(), &clamp);
			}
			location_ = location;
		}

		void init_velocity() override
		{
			std::vector<double> velocity(dimensions_);
			std::uniform_real_distribution<float> distribution(0.0f, 2.0f); //Values between 0 and 2
			std::mt19937 engine; // Mersenne twister MT19937
			auto generator = std::bind(distribution, engine);
			generate(velocity.begin(), velocity.end(), generator);
			velocity_ = velocity;
		}

		std::tuple<std::vector<double>, double> update_personal_best(Function *function) override
		{
			auto value = function->evaluate(location_);

			if (std::get<1>(personal_best_)>value)
			{
				personal_best_ = make_tuple(location_, value);
				iters_from_last_best_change = 0;
			}
			else
			{
				if (++iters_from_last_best_change>restart_iters)
				{
					iters_from_last_best_change = 0;
					init_location();
					//init_velocity();
				}
			}

			return personal_best_;
		}

		void update_neighborhood(std::vector<Particle*> all_particles) override
		{
			if (neighborhood_.size() <= 0 )
			{
				neighborhood_ = all_particles;
			}
		}

		void update_velocity() override
		{
			std::tuple<std::vector<double>, double> global_best = personal_best_;

			for (int i = 0; i < neighborhood_.size(); ++i)
			{
				if (std::get<1>(neighborhood_[i]->get_personal_best()) > std::get<1>(global_best))
					global_best = neighborhood_[i]->get_personal_best();
			}

			std::vector<double> to_personal_best(dimensions_);
			std::vector<double> to_global_best(dimensions_);

			transform(std::get<0>(personal_best_).begin(), std::get<0>(personal_best_).end(),
				location_.begin(), to_personal_best.begin(), std::minus<double>());

			transform(std::get<0>(global_best).begin(), std::get<0>(global_best).end(), location_.begin(), to_global_best.begin(),
				std::minus<double>());

			std::random_device rd;
			std::default_random_engine e1(rd());
			std::uniform_real_distribution<float> uniform_dist(0.0f, 1.4f);
			double phi1 = uniform_dist(e1);
			double phi2 = uniform_dist(e1);
			double omega = 0.64;
			//1.4, 1.4, 0.64
			transform(to_personal_best.begin(), to_personal_best.end(), to_personal_best.begin(),
				bind1st(std::multiplies<double>(), phi1));

			transform(to_global_best.begin(), to_global_best.end(), to_global_best.begin(),
				bind1st(std::multiplies<double>(), phi2));
			//przemnozyc przez omege
			transform(velocity_.begin(), velocity_.end(), velocity_.begin(), bind1st(std::multiplies<double>(), omega));

			transform(velocity_.begin(), velocity_.end(), to_global_best.begin(), velocity_.begin(), std::plus<double>());
			transform(velocity_.begin(), velocity_.end(), to_personal_best.begin(), velocity_.begin(), std::plus<double>());
		}

		void translate() override
		{
			transform(location_.begin(), location_.end(), velocity_.begin(),
				location_.begin(), std::plus<double>());
			if (bounds_.size() == dimensions_) {
				transform(location_.begin(), location_.end(), bounds_.begin(), location_.begin(), &clamp);
			}
		}

	private:
		int dimensions_;
	};
}
<|endoftext|>


<commit_before>//$$ newmat1.cpp   Matrix type functions

// Copyright (C) 1991,2,3,4: R B Davies

//#define WANT_STREAM

#ifndef __GNUC__
#error fish
#elif defined(__APPLE__)
#error fish
#elif (__GNUC_MINOR__>0) && (__GNUC_MINOR__<3)
#error fish
#endif

#include "newmat.h"

#ifdef use_namespace
namespace NEWMAT {
#endif

#ifdef DO_REPORT
#define REPORT { static ExeCounter ExeCount(__LINE__,1); ++ExeCount; }
#else
#define REPORT {}
#endif

/************************* MatrixType functions *****************************/

// all operations to return MatrixTypes which correspond to valid types
// of matrices.
// Eg: if it has the Diagonal attribute, then it must also have
// Upper, Lower, Band and Symmetric.

MatrixType MatrixType::operator*(const MatrixType& mt) const
{
   REPORT
   int a = attribute & mt.attribute & ~Symmetric;
   a |= (a & Diagonal) * 31;                   // recognise diagonal
   return MatrixType(a);
}

MatrixType MatrixType::SP(const MatrixType& mt) const
// elementwise product
// Lower, Upper, Diag, Band if only one is
// Symmetric, Ones, Valid (and Real) if both are
// Need to include Lower & Upper => Diagonal
// Will need to include both Skew => Symmetric
{
   REPORT
   int a = ((attribute | mt.attribute) & ~(Symmetric + Valid + Ones))
      | (attribute & mt.attribute);
   if ((a & Lower) != 0  &&  (a & Upper) != 0) a |= Diagonal;
   a |= (a & Diagonal) * 31;                   // recognise diagonal
   return MatrixType(a);
}

MatrixType MatrixType::KP(const MatrixType& mt) const
// Kronecker product
// Lower, Upper, Diag, Symmetric, Band, Valid if both are
// Do not treat Band separately
// Ones is complicated so leave this out
{
   REPORT
   int a = (attribute & mt.attribute) & ~Ones;
   return MatrixType(a);
}

MatrixType MatrixType::i() const               // type of inverse
{
   REPORT
   int a = attribute & ~(Band+LUDeco);
   a |= (a & Diagonal) * 31;                   // recognise diagonal
   return MatrixType(a);
}

MatrixType MatrixType::t() const
// swap lower and upper attributes
// assume Upper is in bit above Lower
{
   REPORT
   int a = attribute;
   a ^= (((a >> 1) ^ a) & Lower) * 3;
   return MatrixType(a);
}

MatrixType MatrixType::MultRHS() const
{
   REPORT
   // remove symmetric attribute unless diagonal
   return (attribute >= Dg) ? attribute : (attribute & ~Symmetric);
}

bool Rectangular(MatrixType a, MatrixType b, MatrixType c)
{
   REPORT
   return
      ((a.attribute | b.attribute | c.attribute) & ~MatrixType::Valid) == 0;
}

const char* MatrixType::Value() const
{
// make a string with the name of matrix with the given attributes
   switch (attribute)
   {
   case Valid:                              REPORT return "Rect ";
   case Valid+Symmetric:                    REPORT return "Sym  ";
   case Valid+Band:                         REPORT return "Band ";
   case Valid+Symmetric+Band:               REPORT return "SmBnd";
   case Valid+Upper:                        REPORT return "UT   ";
   case Valid+Diagonal+Symmetric+Band+Upper+Lower:
                                            REPORT return "Diag ";
   case Valid+Diagonal+Symmetric+Band+Upper+Lower+Ones:
                                            REPORT return "Ident";
   case Valid+Band+Upper:                   REPORT return "UpBnd";
   case Valid+Lower:                        REPORT return "LT   ";
   case Valid+Band+Lower:                   REPORT return "LwBnd";
   default:
      REPORT
      if (!(attribute & Valid))             return "UnSp ";
      if (attribute & LUDeco)
         return (attribute & Band) ?     "BndLU" : "Crout";
                                            return "?????";
   }
}

GeneralMatrix* MatrixType::New(int nr, int nc, BaseMatrix* bm) const
{
// make a new matrix with the given attributes

   Tracer tr("New"); GeneralMatrix* gm=0;   // initialised to keep gnu happy
   switch (attribute)
   {
   case Valid:
      REPORT
      if (nc==1) { gm = new ColumnVector(nr); break; }
      if (nr==1) { gm = new RowVector(nc); break; }
      gm = new Matrix(nr, nc); break;

   case Valid+Symmetric:
      REPORT gm = new SymmetricMatrix(nr); break;

   case Valid+Band:
      {
         REPORT
         MatrixBandWidth bw = bm->BandWidth();
         gm = new BandMatrix(nr,bw.lower,bw.upper); break;
      }

   case Valid+Symmetric+Band:
      REPORT gm = new SymmetricBandMatrix(nr,bm->BandWidth().lower); break;

   case Valid+Upper:
      REPORT gm = new UpperTriangularMatrix(nr); break;

   case Valid+Diagonal+Symmetric+Band+Upper+Lower:
      REPORT gm = new DiagonalMatrix(nr); break;

   case Valid+Band+Upper:
      REPORT gm = new UpperBandMatrix(nr,bm->BandWidth().upper); break;

   case Valid+Lower:
      REPORT gm = new LowerTriangularMatrix(nr); break;

   case Valid+Band+Lower:
      REPORT gm = new LowerBandMatrix(nr,bm->BandWidth().lower); break;

   case Valid+Diagonal+Symmetric+Band+Upper+Lower+Ones:
      REPORT gm = new IdentityMatrix(nr); break;

   default:
      Throw(ProgramException("Invalid matrix type"));
   }

   MatrixErrorNoSpace(gm); gm->Protect(); return gm;
}

#ifdef use_namespace
}
#endif

<commit_msg>r4612/sofa-dev : <commit_after>//$$ newmat1.cpp   Matrix type functions

// Copyright (C) 1991,2,3,4: R B Davies

//#define WANT_STREAM

#error fish

#include "newmat.h"

#ifdef use_namespace
namespace NEWMAT {
#endif

#ifdef DO_REPORT
#define REPORT { static ExeCounter ExeCount(__LINE__,1); ++ExeCount; }
#else
#define REPORT {}
#endif

/************************* MatrixType functions *****************************/

// all operations to return MatrixTypes which correspond to valid types
// of matrices.
// Eg: if it has the Diagonal attribute, then it must also have
// Upper, Lower, Band and Symmetric.

MatrixType MatrixType::operator*(const MatrixType& mt) const
{
   REPORT
   int a = attribute & mt.attribute & ~Symmetric;
   a |= (a & Diagonal) * 31;                   // recognise diagonal
   return MatrixType(a);
}

MatrixType MatrixType::SP(const MatrixType& mt) const
// elementwise product
// Lower, Upper, Diag, Band if only one is
// Symmetric, Ones, Valid (and Real) if both are
// Need to include Lower & Upper => Diagonal
// Will need to include both Skew => Symmetric
{
   REPORT
   int a = ((attribute | mt.attribute) & ~(Symmetric + Valid + Ones))
      | (attribute & mt.attribute);
   if ((a & Lower) != 0  &&  (a & Upper) != 0) a |= Diagonal;
   a |= (a & Diagonal) * 31;                   // recognise diagonal
   return MatrixType(a);
}

MatrixType MatrixType::KP(const MatrixType& mt) const
// Kronecker product
// Lower, Upper, Diag, Symmetric, Band, Valid if both are
// Do not treat Band separately
// Ones is complicated so leave this out
{
   REPORT
   int a = (attribute & mt.attribute) & ~Ones;
   return MatrixType(a);
}

MatrixType MatrixType::i() const               // type of inverse
{
   REPORT
   int a = attribute & ~(Band+LUDeco);
   a |= (a & Diagonal) * 31;                   // recognise diagonal
   return MatrixType(a);
}

MatrixType MatrixType::t() const
// swap lower and upper attributes
// assume Upper is in bit above Lower
{
   REPORT
   int a = attribute;
   a ^= (((a >> 1) ^ a) & Lower) * 3;
   return MatrixType(a);
}

MatrixType MatrixType::MultRHS() const
{
   REPORT
   // remove symmetric attribute unless diagonal
   return (attribute >= Dg) ? attribute : (attribute & ~Symmetric);
}

bool Rectangular(MatrixType a, MatrixType b, MatrixType c)
{
   REPORT
   return
      ((a.attribute | b.attribute | c.attribute) & ~MatrixType::Valid) == 0;
}

const char* MatrixType::Value() const
{
// make a string with the name of matrix with the given attributes
   switch (attribute)
   {
   case Valid:                              REPORT return "Rect ";
   case Valid+Symmetric:                    REPORT return "Sym  ";
   case Valid+Band:                         REPORT return "Band ";
   case Valid+Symmetric+Band:               REPORT return "SmBnd";
   case Valid+Upper:                        REPORT return "UT   ";
   case Valid+Diagonal+Symmetric+Band+Upper+Lower:
                                            REPORT return "Diag ";
   case Valid+Diagonal+Symmetric+Band+Upper+Lower+Ones:
                                            REPORT return "Ident";
   case Valid+Band+Upper:                   REPORT return "UpBnd";
   case Valid+Lower:                        REPORT return "LT   ";
   case Valid+Band+Lower:                   REPORT return "LwBnd";
   default:
      REPORT
      if (!(attribute & Valid))             return "UnSp ";
      if (attribute & LUDeco)
         return (attribute & Band) ?     "BndLU" : "Crout";
                                            return "?????";
   }
}

GeneralMatrix* MatrixType::New(int nr, int nc, BaseMatrix* bm) const
{
// make a new matrix with the given attributes

   Tracer tr("New"); GeneralMatrix* gm=0;   // initialised to keep gnu happy
   switch (attribute)
   {
   case Valid:
      REPORT
      if (nc==1) { gm = new ColumnVector(nr); break; }
      if (nr==1) { gm = new RowVector(nc); break; }
      gm = new Matrix(nr, nc); break;

   case Valid+Symmetric:
      REPORT gm = new SymmetricMatrix(nr); break;

   case Valid+Band:
      {
         REPORT
         MatrixBandWidth bw = bm->BandWidth();
         gm = new BandMatrix(nr,bw.lower,bw.upper); break;
      }

   case Valid+Symmetric+Band:
      REPORT gm = new SymmetricBandMatrix(nr,bm->BandWidth().lower); break;

   case Valid+Upper:
      REPORT gm = new UpperTriangularMatrix(nr); break;

   case Valid+Diagonal+Symmetric+Band+Upper+Lower:
      REPORT gm = new DiagonalMatrix(nr); break;

   case Valid+Band+Upper:
      REPORT gm = new UpperBandMatrix(nr,bm->BandWidth().upper); break;

   case Valid+Lower:
      REPORT gm = new LowerTriangularMatrix(nr); break;

   case Valid+Band+Lower:
      REPORT gm = new LowerBandMatrix(nr,bm->BandWidth().lower); break;

   case Valid+Diagonal+Symmetric+Band+Upper+Lower+Ones:
      REPORT gm = new IdentityMatrix(nr); break;

   default:
      Throw(ProgramException("Invalid matrix type"));
   }

   MatrixErrorNoSpace(gm); gm->Protect(); return gm;
}

#ifdef use_namespace
}
#endif

<|endoftext|>


<commit_before><commit_msg>Avoid breaking up short lines<commit_after><|endoftext|>


<commit_before>//
//  quicksort.cpp
//  DataStructs_Practice
//
//  Created by Jay Patel on 2016-01-30.
//  Copyright © 2016 jay. All rights reserved.
//

#include <iostream>
#include <vector>
#include <stdlib.h>

long partitionStep(std::vector<int>&, long, long);

void recur(std::vector<int>&, long, long);

void printVector(std::vector<int>&);

int ctr(0);

int main() {

    srand(time(0));

    std::vector<int> structToSort {43,43,43453,-673474,352528,393,79,36,134,16,62,255,-3452,-51};

    recur(structToSort, 0, structToSort.size()-1);

    printVector(structToSort);

    return 0;

}

//the partition step
long partitionStep(std::vector<int>& a, long s, long e) {
    unsigned int pivotI = (rand()%(e - s)) + s, l(s), r(e);
    int pivotVal = a.at(pivotI);

    while(l < r) {
        bool lismet, rismet; lismet = rismet = false;
        while (!lismet) {
            if (a[l] >= pivotVal)
                lismet = true;
            else
                l++;
        };
        while (!rismet) {
            if (a[r] <= pivotVal)
                rismet = true;
            else
                r--;
        };

        if (a[l] == a[r])
            l++;
        else{
            //switch the two
            int tempLHolder = a.at(l);
            a[l] = a[r];
            a[r] = tempLHolder;
        };

    };

    return r;
};

//the recursive quicksort call
void recur(std::vector<int>& a, long s, long e) {
    if (s < e) {
        long pIndex = partitionStep(a, s, e);
        recur(a, s, pIndex-1);
        recur(a, pIndex+1, e);
    };
};

void printVector(std::vector<int>& v) {
    std::cout << "-----------------------------------------\n";
    for (long i = v.size(); i > 0; i--) {
        std::cout << v[i-1] << ", ";
    }
    std::cout << "Done\n-----------------------------------------\n";
};<commit_msg>Update quicksort.cpp<commit_after>//
//  quicksort.cpp
//  DataStructs_Practice
//
//  Created by Jay Patel on 2016-01-30.
//  Copyright © 2016 jay. All rights reserved.
//

#include <iostream>
#include <vector>
#include <stdlib.h>

long partitionStep(std::vector<int>&, long, long);

void recur(std::vector<int>&, long, long);

void printVector(std::vector<int>&);

int main() {

    srand(time(0));

    std::vector<int> structToSort {43,43,43453,-673474,352528,393,79,36,134,16,62,255,-3452,-51};

    recur(structToSort, 0, structToSort.size()-1);

    printVector(structToSort);

    return 0;

}

//the partition step
long partitionStep(std::vector<int>& a, long s, long e) {
    unsigned int pivotI = (rand()%(e - s)) + s, l(s), r(e);
    int pivotVal = a.at(pivotI);

    while(l < r) {
        bool lismet, rismet; lismet = rismet = false;
        while (!lismet) {
            if (a[l] >= pivotVal)
                lismet = true;
            else
                l++;
        };
        while (!rismet) {
            if (a[r] <= pivotVal)
                rismet = true;
            else
                r--;
        };

        if (a[l] == a[r])
            l++;
        else{
            //switch the two
            int tempLHolder = a.at(l);
            a[l] = a[r];
            a[r] = tempLHolder;
        };

    };

    return r;
};

//the recursive quicksort call
void recur(std::vector<int>& a, long s, long e) {
    if (s < e) {
        long pIndex = partitionStep(a, s, e);
        recur(a, s, pIndex-1);
        recur(a, pIndex+1, e);
    };
};

void printVector(std::vector<int>& v) {
    std::cout << "-----------------------------------------\n";
    for (long i = v.size(); i > 0; i--) {
        std::cout << v[i-1] << ", ";
    }
    std::cout << "Done\n-----------------------------------------\n";
};
<|endoftext|>