<commit_before>#include "../test.h"

#if HAS_BOOST && (!defined(_MSC_VER) || _MSC_VER >= 1900) // VS2015

#include "json-voorhees/src/jsonv/algorithm_map.cpp"
#include "json-voorhees/src/jsonv/algorithm_traverse.cpp"
#include "json-voorhees/src/jsonv/array.cpp"
#include "json-voorhees/src/jsonv/char_convert.cpp"
#include "json-voorhees/src/jsonv/coerce.cpp"
#include "json-voorhees/src/jsonv/demangle.cpp"
#include "json-voorhees/src/jsonv/detail.cpp"
#include "json-voorhees/src/jsonv/encode.cpp"
#include "json-voorhees/src/jsonv/object.cpp"
#include "json-voorhees/src/jsonv/parse.cpp"
#include "json-voorhees/src/jsonv/path.cpp"
#include "json-voorhees/src/jsonv/serialization.cpp"
#include "json-voorhees/src/jsonv/serialization_builder.cpp"
#include "json-voorhees/src/jsonv/tokenizer.cpp"
#include "json-voorhees/src/jsonv/util.cpp"
#include "json-voorhees/src/jsonv/value.cpp"
#include "json-voorhees/src/jsonv/detail/token_patterns.cpp"

using namespace jsonv;

static void GenStat(Stat& stat, const value& v) {
    switch (v.kind()) {
    case kind::array:
        {
            for (value::const_array_iterator itr = v.begin_array(); itr != v.end_array(); ++itr)
                GenStat(stat, *itr);
            stat.arrayCount++;
            stat.elementCount += v.size();
        }
        break;

    case kind::object:
        {
            for (value::const_object_iterator itr = v.begin_object(); itr != v.end_object(); ++itr) {
                GenStat(stat, itr->second);
                stat.stringLength += itr->first.size();
            }
            stat.objectCount++;
            stat.memberCount += v.size();
            stat.stringCount += v.size();
        }
        break;

    case kind::string:
        stat.stringCount++;
        stat.stringLength += v.size();
        break;

    case kind::integer:
    case kind::decimal:
        stat.numberCount++;
        break;

    case kind::boolean:
        if (v.as_boolean())
            stat.trueCount++;
        else
            stat.falseCount++;
        break;

    case kind::null:
        stat.nullCount++;
        break;
    }
}

class VoorheesParseResult : public ParseResultBase {
public:
    value root;
};

class VoorheesStringResult : public StringResultBase {
public:
    virtual const char* c_str() const { return s.c_str(); }

    std::string s;
};
class VoorheesTest : public TestBase {
public:
#if TEST_INFO
    virtual const char* GetName() const { return "JSON Voorhees (C++)"; }
    virtual const char* GetFilename() const { return __FILE__; }
#endif

#if TEST_PARSE
    virtual ParseResultBase* Parse(const char* json, size_t length) const {
        (void)length;
        VoorheesParseResult* pr = new VoorheesParseResult;
        try {
            pr->root = parse(json);
        }
        catch (...) {
            delete pr;
            return 0;
        }
    	return pr;
    }
#endif

#if TEST_STRINGIFY
    virtual StringResultBase* Stringify(const ParseResultBase* parseResult) const {
        const VoorheesParseResult* pr = static_cast<const VoorheesParseResult*>(parseResult);
        VoorheesStringResult* sr = new VoorheesStringResult;
        sr->s = to_string(pr->root);
        return sr;
    }
#endif

#if TEST_PRETTIFY
    virtual StringResultBase* Prettify(const ParseResultBase* parseResult) const {
        const VoorheesParseResult* pr = static_cast<const VoorheesParseResult*>(parseResult);
        VoorheesStringResult* sr = new VoorheesStringResult;
        std::ostringstream os;
        ostream_pretty_encoder e(os, 4);
        e.encode(pr->root);
        sr->s = os.str();
        return sr;
    }
#endif

#if TEST_STATISTICS
    virtual bool Statistics(const ParseResultBase* parseResult, Stat* stat) const {
        const VoorheesParseResult* pr = static_cast<const VoorheesParseResult*>(parseResult);
        memset(stat, 0, sizeof(Stat));
        GenStat(*stat, pr->root);
        return true;
    }
#endif

#if TEST_CONFORMANCE
    virtual bool ParseDouble(const char* json, double* d) const {
        try {
            value v = parse(json);
            *d = v[0].as_decimal();
            return true;
        }
        catch (...) {
        }
        return false;
    }

    virtual bool ParseString(const char* json, std::string& s) const {
        try {
            value v = parse(json);
            s = v[0].as_string();
            return true;
        }
        catch (...) {
        }
        return false;
    }
#endif
};

REGISTER_TEST(VoorheesTest);

#endif<commit_msg>Ignore voorhees on x64 32-bit<commit_after>#include "../test.h"

#if HAS_BOOST && (!defined(_MSC_VER) || _MSC_VER >= 1900) && !defined(__i386__) // VS2015, and works on 64-bit only

#include "json-voorhees/src/jsonv/algorithm_map.cpp"
#include "json-voorhees/src/jsonv/algorithm_traverse.cpp"
#include "json-voorhees/src/jsonv/array.cpp"
#include "json-voorhees/src/jsonv/char_convert.cpp"
#include "json-voorhees/src/jsonv/coerce.cpp"
#include "json-voorhees/src/jsonv/demangle.cpp"
#include "json-voorhees/src/jsonv/detail.cpp"
#include "json-voorhees/src/jsonv/encode.cpp"
#include "json-voorhees/src/jsonv/object.cpp"
#include "json-voorhees/src/jsonv/parse.cpp"
#include "json-voorhees/src/jsonv/path.cpp"
#include "json-voorhees/src/jsonv/serialization.cpp"
#include "json-voorhees/src/jsonv/serialization_builder.cpp"
#include "json-voorhees/src/jsonv/tokenizer.cpp"
#include "json-voorhees/src/jsonv/util.cpp"
#include "json-voorhees/src/jsonv/value.cpp"
#include "json-voorhees/src/jsonv/detail/token_patterns.cpp"

using namespace jsonv;

static void GenStat(Stat& stat, const value& v) {
    switch (v.kind()) {
    case kind::array:
        {
            for (value::const_array_iterator itr = v.begin_array(); itr != v.end_array(); ++itr)
                GenStat(stat, *itr);
            stat.arrayCount++;
            stat.elementCount += v.size();
        }
        break;

    case kind::object:
        {
            for (value::const_object_iterator itr = v.begin_object(); itr != v.end_object(); ++itr) {
                GenStat(stat, itr->second);
                stat.stringLength += itr->first.size();
            }
            stat.objectCount++;
            stat.memberCount += v.size();
            stat.stringCount += v.size();
        }
        break;

    case kind::string:
        stat.stringCount++;
        stat.stringLength += v.size();
        break;

    case kind::integer:
    case kind::decimal:
        stat.numberCount++;
        break;

    case kind::boolean:
        if (v.as_boolean())
            stat.trueCount++;
        else
            stat.falseCount++;
        break;

    case kind::null:
        stat.nullCount++;
        break;
    }
}

class VoorheesParseResult : public ParseResultBase {
public:
    value root;
};

class VoorheesStringResult : public StringResultBase {
public:
    virtual const char* c_str() const { return s.c_str(); }

    std::string s;
};
class VoorheesTest : public TestBase {
public:
#if TEST_INFO
    virtual const char* GetName() const { return "JSON Voorhees (C++)"; }
    virtual const char* GetFilename() const { return __FILE__; }
#endif

#if TEST_PARSE
    virtual ParseResultBase* Parse(const char* json, size_t length) const {
        (void)length;
        VoorheesParseResult* pr = new VoorheesParseResult;
        try {
            pr->root = parse(json);
        }
        catch (...) {
            delete pr;
            return 0;
        }
    	return pr;
    }
#endif

#if TEST_STRINGIFY
    virtual StringResultBase* Stringify(const ParseResultBase* parseResult) const {
        const VoorheesParseResult* pr = static_cast<const VoorheesParseResult*>(parseResult);
        VoorheesStringResult* sr = new VoorheesStringResult;
        sr->s = to_string(pr->root);
        return sr;
    }
#endif

#if TEST_PRETTIFY
    virtual StringResultBase* Prettify(const ParseResultBase* parseResult) const {
        const VoorheesParseResult* pr = static_cast<const VoorheesParseResult*>(parseResult);
        VoorheesStringResult* sr = new VoorheesStringResult;
        std::ostringstream os;
        ostream_pretty_encoder e(os, 4);
        e.encode(pr->root);
        sr->s = os.str();
        return sr;
    }
#endif

#if TEST_STATISTICS
    virtual bool Statistics(const ParseResultBase* parseResult, Stat* stat) const {
        const VoorheesParseResult* pr = static_cast<const VoorheesParseResult*>(parseResult);
        memset(stat, 0, sizeof(Stat));
        GenStat(*stat, pr->root);
        return true;
    }
#endif

#if TEST_CONFORMANCE
    virtual bool ParseDouble(const char* json, double* d) const {
        try {
            value v = parse(json);
            *d = v[0].as_decimal();
            return true;
        }
        catch (...) {
        }
        return false;
    }

    virtual bool ParseString(const char* json, std::string& s) const {
        try {
            value v = parse(json);
            s = v[0].as_string();
            return true;
        }
        catch (...) {
        }
        return false;
    }
#endif
};

REGISTER_TEST(VoorheesTest);

#endif<|endoftext|>


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

namespace mss
{

// Proposed DDR4 Full spec update(79-4A)
// Item No. 1716.78C
// pg.46
// Table 24 - tREFI and tRFC parameters
static const std::vector<std::pair<uint8_t, uint64_t> > TREFI_BASE =
{
    // { density in GBs, tREFI(base) in nanoseconds }
    {2, 7800},
    {4, 7800},
    {8, 7800},
    // 16Gb - TBD
};

// Proposed DDR4 Full spec update(79-4A)
// Item No. 1716.78C
// pg.46
// Table 24 - tREFI and tRFC parameters
static const std::vector<std::pair<uint8_t, uint64_t> > TRFC1_MIN =
{
    // { density in GBs, tRFC1(min) in nanoseconds }
    {2, 160},
    {4, 260},
    {8, 350},
    // 16Gb - TBD
};

// Proposed DDR4 Full spec update(79-4A)
// Item No. 1716.78C
// pg.46
// Table 24 - tREFI and tRFC parameters
static const std::vector<std::pair<uint8_t, uint64_t> > TRFC2_MIN =
{
    // { density in GBs, tRFC2(min) in nanoseconds }
    {2, 110},
    {4, 160},
    {8, 260},
    // 16Gb - TBD
};

// Proposed DDR4 Full spec update(79-4A)
// Item No. 1716.78C
// pg.46
// Table 24 - tREFI and tRFC parameters
static const std::vector<std::pair<uint8_t, uint64_t> > TRFC4_MIN =
{
    // { density in GBs, tRFC4(min) in nanoseconds }
    {2, 90},
    {4, 110},
    {8, 160},
    // 16Gb - TBD
};

/// @brief Calculates refresh interval time 1 (tREFI 1)
/// @param[in] i_target FAPI2 target
/// @param[out] o_value timing val in ps
/// @return fapi2::ReturnCode
///
fapi2::ReturnCode calc_trefi1(const fapi2::Target<fapi2::TARGET_TYPE_DIMM>& i_target,
                              uint64_t& o_value)
{
    uint8_t  l_quotient = 0;
    uint8_t l_remainder = 0;
    uint64_t l_output = 0;
    uint8_t l_temp_ref_range = 0;
    uint8_t l_dram_density = 0;
    bool l_found_value = true;

    FAPI_TRY(mss::eff_dram_density(i_target, l_dram_density));

    switch(l_temp_ref_range)
    {
        case fapi2::ENUM_ATTR_EFF_TEMP_REF_RANGE_NORMAL:
            l_found_value = mss::find_value_from_key(TREFI_BASE, l_dram_density, o_value);
            FAPI_TRY( check::fail_for_invalid_map(i_target,
                                                  l_found_value,
                                                  l_dram_density,
                                                  l_temp_ref_range,
                                                  "Could not find sdram density given"
                                                  "normal temp_ref_range.") );
            break;

        case fapi2::ENUM_ATTR_EFF_TEMP_REF_RANGE_EXTEND:
            l_found_value = mss::find_value_from_key(TREFI_BASE, l_dram_density, l_output);
            FAPI_TRY( check::fail_for_invalid_map(i_target,
                                                  l_found_value,
                                                  l_dram_density,
                                                  l_temp_ref_range,
                                                  "Could not find sdram density given"
                                                  "extended temp_ref_range.") );
            l_quotient = l_output / 2;
            l_remainder = l_output % 2;
            o_value = l_quotient + (l_remainder == 0 ? 0 : 1);
            break;

        default:
            // l_temp_ref_range will be a platform attribute set by the MRW,
            // which they "shouldn't" mess up as long as use "attribute" enums.
            // if openpower messes this up we can at least catch it
            FAPI_ASSERT(false,
                        fapi2::MSS_INVALID_TEMP_REF_RANGE().
                        set_TEMP_REF_RANGE(l_temp_ref_range),
                        "%s Incorrect Temperature Ref. Range received: %d ",
                        mss::c_str(i_target),
                        l_temp_ref_range);

            break;
    }

fapi_try_exit:
    return fapi2::current_err;
}

/// @brief Calculates refresh interval time 2 (tREFI 2)
/// @param[in] i_target FAPI2 target
/// @param[out] o_value timing val in ps
/// @return fapi2::ReturnCode
///
fapi2::ReturnCode calc_trefi2(const fapi2::Target<fapi2::TARGET_TYPE_DIMM>& i_target,
                              uint64_t& o_value)
{
    uint8_t l_quotient = 0;
    uint8_t l_remainder = 0;
    uint64_t l_output = 0;
    uint8_t l_temp_ref_range = 0;
    uint8_t l_dram_density = 0;
    bool l_found_value = true;

    FAPI_TRY(mss::eff_temp_ref_range(i_target, l_temp_ref_range));
    FAPI_TRY(mss::eff_dram_density(i_target, l_dram_density));

    switch(l_temp_ref_range)
    {
        case fapi2::ENUM_ATTR_EFF_TEMP_REF_RANGE_NORMAL:
            l_found_value = mss::find_value_from_key(TREFI_BASE, l_dram_density, l_output);
            FAPI_TRY( check::fail_for_invalid_map(i_target,
                                                  l_found_value,
                                                  l_dram_density,
                                                  l_temp_ref_range,
                                                  "Could not find sdram density given"
                                                  "normal temp_ref_range.") );

            l_remainder = l_output % 2;
            o_value = l_quotient + (l_remainder == 0 ? 0 : 1);
            break;

        case fapi2::ENUM_ATTR_EFF_TEMP_REF_RANGE_EXTEND:
            l_found_value = mss::find_value_from_key(TREFI_BASE, l_dram_density, l_output);
            FAPI_TRY( check::fail_for_invalid_map(i_target,
                                                  l_found_value,
                                                  l_dram_density,
                                                  l_temp_ref_range,
                                                  "Could not find sdram density given"
                                                  "extended temp_ref_range.") );
            l_quotient = l_output / 4;
            l_remainder = l_output % 4;
            o_value = l_quotient + (l_remainder == 0 ? 0 : 1);
            break;

        default:
            // l_temp_ref_range will be a platform attribute set by the MRW,
            // which they "shouldn't" mess up as long as use "attribute" enums.
            // if openpower messes this up we can at least catch it
            FAPI_ASSERT(false,
                        fapi2::MSS_INVALID_TEMP_REF_RANGE().
                        set_TEMP_REF_RANGE(l_temp_ref_range),
                        "%s Incorrect Temperature Ref. Range received: %d ",
                        mss::c_str(i_target),
                        l_temp_ref_range);

            break;
    }

fapi_try_exit:
    return fapi2::current_err;
}

/// @brief Calculates refresh interval time 4 (tREFI 4)
/// @param[in] i_target FAPI2 target
/// @param[out] o_value timing val in ps
/// @return fapi2::ReturnCode
///
fapi2::ReturnCode calc_trefi4( const fapi2::Target<fapi2::TARGET_TYPE_DIMM>& i_target,
                               uint64_t& o_value)
{
    uint8_t l_quotient = 0;
    uint8_t l_remainder = 0;
    uint64_t l_output = 0;
    uint8_t l_temp_ref_range = 0;
    uint8_t l_dram_density = 0;
    bool l_found_value = true;

    FAPI_TRY(mss::eff_temp_ref_range(i_target, l_temp_ref_range));
    FAPI_TRY(mss::eff_dram_density(i_target, l_dram_density));

    switch(l_temp_ref_range)
    {
        case fapi2::ENUM_ATTR_EFF_TEMP_REF_RANGE_NORMAL:
            l_found_value = mss::find_value_from_key(TREFI_BASE, l_dram_density, l_output);
            FAPI_TRY( check::fail_for_invalid_map(i_target,
                                                  l_found_value,
                                                  l_dram_density,
                                                  l_temp_ref_range,
                                                  "Could not find sdram density given"
                                                  "normal temp_ref_range.") );
            l_quotient = l_output / 4;
            l_remainder = l_output % 4;
            o_value = l_quotient + (l_remainder == 0 ? 0 : 1);
            break;

        case fapi2::ENUM_ATTR_EFF_TEMP_REF_RANGE_EXTEND:
            l_found_value = mss::find_value_from_key(TREFI_BASE, l_dram_density, l_output);
            FAPI_TRY( check::fail_for_invalid_map(i_target,
                                                  l_found_value,
                                                  l_dram_density,
                                                  l_temp_ref_range,
                                                  "Could not find sdram density given"
                                                  "extended temp_ref_range.") );
            l_quotient = l_output / 8;
            l_remainder = l_output % 8;
            o_value = l_quotient + (l_remainder == 0 ? 0 : 1);
            break;

        default:
            // l_temp_ref_range will be a platform attribute set by the MRW,
            // which they "shouldn't" mess up as long as use "attribute" enums.
            // if openpower messes this up we can at least catch it
            FAPI_ASSERT(false,
                        fapi2::MSS_INVALID_TEMP_REF_RANGE().
                        set_TEMP_REF_RANGE(l_temp_ref_range),
                        "%s Incorrect Temperature Ref. Range received: %d ",
                        mss::c_str(i_target),
                        l_temp_ref_range);

            break;
    }

fapi_try_exit:
    return fapi2::current_err;
}

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

namespace mss
{

// Proposed DDR4 Full spec update(79-4A)
// Item No. 1716.78C
// pg.46
// Table 24 - tREFI and tRFC parameters
static const std::vector<std::pair<uint8_t, uint64_t> > TREFI_BASE =
{
    // { density in GBs, tREFI(base) in nanoseconds }
    {2, 7800},
    {4, 7800},
    {8, 7800},
    // 16Gb - TBD
};

// Proposed DDR4 Full spec update(79-4A)
// Item No. 1716.78C
// pg.46
// Table 24 - tREFI and tRFC parameters
static const std::vector<std::pair<uint8_t, uint64_t> > TRFC1_MIN =
{
    // { density in GBs, tRFC1(min) in nanoseconds }
    {2, 160},
    {4, 260},
    {8, 350},
    // 16Gb - TBD
};

// Proposed DDR4 Full spec update(79-4A)
// Item No. 1716.78C
// pg.46
// Table 24 - tREFI and tRFC parameters
static const std::vector<std::pair<uint8_t, uint64_t> > TRFC2_MIN =
{
    // { density in GBs, tRFC2(min) in nanoseconds }
    {2, 110},
    {4, 160},
    {8, 260},
    // 16Gb - TBD
};

// Proposed DDR4 Full spec update(79-4A)
// Item No. 1716.78C
// pg.46
// Table 24 - tREFI and tRFC parameters
static const std::vector<std::pair<uint8_t, uint64_t> > TRFC4_MIN =
{
    // { density in GBs, tRFC4(min) in nanoseconds }
    {2, 90},
    {4, 110},
    {8, 160},
    // 16Gb - TBD
};

// Proposed DDR4 3DS Addendum
// Item No. 1727.58A
// pg. 69 - 71
// Table 42 - Refresh parameters by logical rank density
static const std::vector<std::pair<uint8_t, uint64_t> > TRFC_DLR1 =
{
    // { density in GBs, tRFC4(min) in nanoseconds }
    {4, 90},
    {8, 120},
    // 16Gb - TBD
};

// Proposed DDR4 3DS Addendum
// Item No. 1727.58A
// pg. 69 - 71
// Table 42 - Refresh parameters by logical rank density
static const std::vector<std::pair<uint8_t, uint64_t> > TRFC_DLR2 =
{
    // { density in GBs, tRFC4(min) in nanoseconds }
    {4, 55},
    {8, 90}
    // 16Gb - TBD
};

// Proposed DDR4 3DS Addendum
// Item No. 1727.58A
// pg. 69 - 71
// Table 42 - Refresh parameters by logical rank density
static const std::vector<std::pair<uint8_t, uint64_t> > TRFC_DLR4 =
{
    // { density in GBs, tRFC4(min) in nanoseconds }
    {4, 40},
    {8, 55}
    // 16Gb - TBD
};

/// @brief Calculates refresh interval time 1 (tREFI 1)
/// @param[in] i_target FAPI2 target
/// @param[out] o_value timing val in ps
/// @return fapi2::ReturnCode
///
fapi2::ReturnCode calc_trefi1(const fapi2::Target<fapi2::TARGET_TYPE_DIMM>& i_target,
                              uint64_t& o_value)
{
    uint8_t  l_quotient = 0;
    uint8_t l_remainder = 0;
    uint64_t l_output = 0;
    uint8_t l_temp_ref_range = 0;
    uint8_t l_dram_density = 0;
    bool l_found_value = true;

    FAPI_TRY( mss::eff_dram_density(i_target, l_dram_density) );
    FAPI_TRY( mss::mrw_temp_ref_range(l_temp_ref_range) );

    switch(l_temp_ref_range)
    {
        case fapi2::ENUM_ATTR_MRW_TEMP_REF_RANGE_NORMAL:
            l_found_value = mss::find_value_from_key(TREFI_BASE, l_dram_density, l_output);
            FAPI_TRY( check::fail_for_invalid_map(i_target,
                                                  l_found_value,
                                                  l_dram_density,
                                                  l_temp_ref_range,
                                                  "Could not find sdram density given"
                                                  "normal temp_ref_range.") );
            break;

        case fapi2::ENUM_ATTR_MRW_TEMP_REF_RANGE_EXTEND:
            l_found_value = mss::find_value_from_key(TREFI_BASE, l_dram_density, l_output);
            FAPI_TRY( check::fail_for_invalid_map(i_target,
                                                  l_found_value,
                                                  l_dram_density,
                                                  l_temp_ref_range,
                                                  "Could not find sdram density given"
                                                  "extended temp_ref_range.") );
            l_quotient = l_output / 2;
            l_remainder = l_output % 2;
            o_value = l_quotient + (l_remainder == 0 ? 0 : 1);
            break;

        default:
            // l_temp_ref_range will be a platform attribute set by the MRW,
            // which they "shouldn't" mess up as long as use "attribute" enums.
            // if openpower messes this up we can at least catch it
            FAPI_ASSERT(false,
                        fapi2::MSS_INVALID_TEMP_REF_RANGE().
                        set_TEMP_REF_RANGE(l_temp_ref_range),
                        "%s Incorrect Temperature Ref. Range received: %d ",
                        mss::c_str(i_target),
                        l_temp_ref_range);

            break;
    }

fapi_try_exit:
    return fapi2::current_err;
}

/// @brief Calculates refresh interval time 2 (tREFI 2)
/// @param[in] i_target FAPI2 target
/// @param[out] o_value timing val in ps
/// @return fapi2::ReturnCode
///
fapi2::ReturnCode calc_trefi2(const fapi2::Target<fapi2::TARGET_TYPE_DIMM>& i_target,
                              uint64_t& o_value)
{
    uint8_t l_quotient = 0;
    uint8_t l_remainder = 0;
    uint64_t l_output = 0;
    uint8_t l_temp_ref_range = 0;
    uint8_t l_dram_density = 0;
    bool l_found_value = true;

    FAPI_TRY( mss::mrw_temp_ref_range(l_temp_ref_range) );
    FAPI_TRY( mss::eff_dram_density(i_target, l_dram_density) );

    switch(l_temp_ref_range)
    {
        case fapi2::ENUM_ATTR_MRW_TEMP_REF_RANGE_NORMAL:
            l_found_value = mss::find_value_from_key(TREFI_BASE, l_dram_density, l_output);
            FAPI_TRY( check::fail_for_invalid_map(i_target,
                                                  l_found_value,
                                                  l_dram_density,
                                                  l_temp_ref_range,
                                                  "Could not find sdram density given"
                                                  "normal temp_ref_range.") );

            l_remainder = l_output % 2;
            o_value = l_quotient + (l_remainder == 0 ? 0 : 1);
            break;

        case fapi2::ENUM_ATTR_MRW_TEMP_REF_RANGE_EXTEND:
            l_found_value = mss::find_value_from_key(TREFI_BASE, l_dram_density, l_output);
            FAPI_TRY( check::fail_for_invalid_map(i_target,
                                                  l_found_value,
                                                  l_dram_density,
                                                  l_temp_ref_range,
                                                  "Could not find sdram density given"
                                                  "extended temp_ref_range.") );
            l_quotient = l_output / 4;
            l_remainder = l_output % 4;
            o_value = l_quotient + (l_remainder == 0 ? 0 : 1);
            break;

        default:
            // l_temp_ref_range will be a platform attribute set by the MRW,
            // which they "shouldn't" mess up as long as use "attribute" enums.
            // if openpower messes this up we can at least catch it
            FAPI_ASSERT(false,
                        fapi2::MSS_INVALID_TEMP_REF_RANGE().
                        set_TEMP_REF_RANGE(l_temp_ref_range),
                        "%s Incorrect Temperature Ref. Range received: %d ",
                        mss::c_str(i_target),
                        l_temp_ref_range);

            break;
    }

fapi_try_exit:
    return fapi2::current_err;
}

/// @brief Calculates refresh interval time 4 (tREFI 4)
/// @param[in] i_target FAPI2 target
/// @param[out] o_value timing val in ps
/// @return fapi2::ReturnCode
///
fapi2::ReturnCode calc_trefi4( const fapi2::Target<fapi2::TARGET_TYPE_DIMM>& i_target,
                               uint64_t& o_value)
{
    uint8_t l_quotient = 0;
    uint8_t l_remainder = 0;
    uint64_t l_output = 0;
    uint8_t l_temp_ref_range = 0;
    uint8_t l_dram_density = 0;
    bool l_found_value = true;

    FAPI_TRY( mss::mrw_temp_ref_range(l_temp_ref_range) );
    FAPI_TRY( mss::eff_dram_density(i_target, l_dram_density) );

    switch(l_temp_ref_range)
    {
        case fapi2::ENUM_ATTR_MRW_TEMP_REF_RANGE_NORMAL:
            l_found_value = mss::find_value_from_key(TREFI_BASE, l_dram_density, l_output);
            FAPI_TRY( check::fail_for_invalid_map(i_target,
                                                  l_found_value,
                                                  l_dram_density,
                                                  l_temp_ref_range,
                                                  "Could not find sdram density given"
                                                  "normal temp_ref_range.") );
            l_quotient = l_output / 4;
            l_remainder = l_output % 4;
            o_value = l_quotient + (l_remainder == 0 ? 0 : 1);
            break;

        case fapi2::ENUM_ATTR_MRW_TEMP_REF_RANGE_EXTEND:
            l_found_value = mss::find_value_from_key(TREFI_BASE, l_dram_density, l_output);
            FAPI_TRY( check::fail_for_invalid_map(i_target,
                                                  l_found_value,
                                                  l_dram_density,
                                                  l_temp_ref_range,
                                                  "Could not find sdram density given"
                                                  "extended temp_ref_range.") );
            l_quotient = l_output / 8;
            l_remainder = l_output % 8;
            o_value = l_quotient + (l_remainder == 0 ? 0 : 1);
            break;

        default:
            // l_temp_ref_range will be a platform attribute set by the MRW,
            // which they "shouldn't" mess up as long as use "attribute" enums.
            // if openpower messes this up we can at least catch it
            FAPI_ASSERT(false,
                        fapi2::MSS_INVALID_TEMP_REF_RANGE().
                        set_TEMP_REF_RANGE(l_temp_ref_range),
                        "%s Incorrect Temperature Ref. Range received: %d ",
                        mss::c_str(i_target),
                        l_temp_ref_range);

            break;
    }

fapi_try_exit:
    return fapi2::current_err;
}

}// mss
<|endoftext|>


<commit_before>/****************************************************************************

This file is part of the QtMediaHub project on http://www.qtmediahub.com

Copyright (c) 2011 Nokia Corporation and/or its subsidiary(-ies).*
All rights reserved.

Contact:  Girish Ramakrishnan girish@forwardbias.in
Contact:  Nokia Corporation donald.carr@nokia.com
Contact:  Nokia Corporation johannes.zellner@nokia.com

You may use this file under the terms of the BSD license as follows:

Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
* Neither the name of Nokia Corporation and its Subsidiary(-ies) nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

****************************************************************************/

#include "radioparser.h"

#include "scopedtransaction.h"
#include <QtSql>

#define DEBUG if (0) qDebug() << __PRETTY_FUNCTION__

bool RadioParser::canRead(const QFileInfo &info) const
{
    static QStringList extensions
            = QStringList() << "pls"
                            << "asx";

    return extensions.contains(info.suffix());
}

QString cleanString(QString str)
{
    str = str.simplified();
    if (!str.isEmpty())
        str[0] = str[0].toUpper();
    return str;
}

struct RadioInfo {
    QUrl uri;
    QString title;
    QString thumbnail;
    int length;
};

static RadioInfo *readPLS(QFileInfo fileInfo)
{
    QSettings settings(fileInfo.filePath(), QSettings::IniFormat);
    QStringList keys = settings.allKeys();

    if (!keys.contains("playlist/NumberOfEntries", Qt::CaseInsensitive))
        return 0;

    if (settings.value("playlist/NumberOfEntries", 0).toInt() <= 0)
        return 0;

    // currently only choose first title
    if (    !keys.contains("playlist/File1", Qt::CaseInsensitive) ||
            !keys.contains("playlist/Title1", Qt::CaseInsensitive) ||
            !keys.contains("playlist/Length1", Qt::CaseInsensitive) )
        return 0;

    QString file = settings.value("playlist/File1", "").toString();
    QString title = settings.value("playlist/Title1", "").toString();
    int length = settings.value("playlist/Length1", "").toInt();

    RadioInfo *info = new RadioInfo();
    info->uri = QUrl(file);
    info->title = title;
    info->length = length;

    QRegExp e("\\(#[0-9]+ - [0-9]+/[0-9]+\\) ");
    int regExpIndex = e.indexIn(title);
    int regExpLenght = e.matchedLength();

    if(regExpIndex == 0)
        info->title = title.right(title.length() - regExpLenght);

    return info;
}

static RadioInfo *readASX(QFileInfo fileInfo)
{
    QFile file(fileInfo.filePath());
    if (!file.open(QIODevice::ReadOnly | QIODevice::Text))
        return 0;

    QString title;
    QUrl uri;
    QString banner;

    QXmlStreamReader reader(&file);
    while(!reader.atEnd() && !reader.hasError()) {
        QXmlStreamReader::TokenType token = reader.readNext();
        if (token == QXmlStreamReader::StartDocument)
            continue;

        if (token == QXmlStreamReader::StartElement) {
            if (reader.name() == "entry") {
                continue;
            }

            if (reader.name() == "Banner" && reader.attributes().hasAttribute("href")) {
                banner = reader.attributes().value("href").toString();
                continue;
            }

            if (reader.name() == "title") {
                reader.readNext();
                if (reader.tokenType() == QXmlStreamReader::Characters)
                    title = reader.text().toString();
                continue;
            }
            if (reader.name() == "ref" && reader.attributes().hasAttribute("href")) {
                uri = reader.attributes().value("href").toString();
                continue;
            }
        }

        if (title != "" && uri.isEmpty())
            break;
    }

    if (reader.hasError() || title == "" || uri.isEmpty()) {
        reader.clear();
        return 0;
    }

    reader.clear();

    RadioInfo *info = new RadioInfo();
    info->uri = QUrl(uri);
    info->title = title;
    info->thumbnail = banner;

    return info;
}

// ## See if DELETE+INSERT is the best approach. Sqlite3 supports INSERT OR IGNORE which could aslo be used
// ## Also check other upsert methods
QList<QSqlRecord> RadioParser::updateMediaInfos(const QList<QFileInfo> &fis, const QString &searchPath, QSqlDatabase db)
{
    Q_UNUSED(searchPath);
    QList<QSqlRecord> records;
    QSqlQuery query(db);
    ScopedTransaction transaction(db);

    foreach(const QFileInfo &fi, fis) {
        DEBUG << "Updating " << fi.absoluteFilePath();

        RadioInfo *info = 0;
        if (fi.suffix() == "pls")
            info = readPLS(fi);
        else if (fi.suffix() == "asx")
            info = readASX(fi);

        if (!info)
            continue;

        query.prepare("DELETE FROM music WHERE filepath=:filepath");
        query.bindValue(":filepath", fi.absoluteFilePath());
        if (!query.exec())
            qWarning() << query.lastError().text();

        if (!query.prepare("INSERT INTO radio (filepath, title, thumbnail, length, uri, directory, mtime, ctime, filesize) "
                           " VALUES (:filepath, :title, :thumbnail, :length, :uri, :directory, :mtime, :ctime, :filesize)")) {
            qWarning() << query.lastError().text();
            if (info)
                delete info;
            return records;
        }

        query.bindValue(":filepath", fi.absoluteFilePath());
        query.bindValue(":title", info->title);
        query.bindValue(":thumbnail", info->thumbnail);

        query.bindValue(":length", info->length);
        query.bindValue(":uri", info->uri.toEncoded());

        query.bindValue(":directory", fi.absolutePath() + '/');
        query.bindValue(":mtime", fi.lastModified().toTime_t());
        query.bindValue(":ctime", fi.created().toTime_t());
        query.bindValue(":filesize", fi.size());

        if (!query.exec())
            qWarning() << query.lastError().text();

        QSqlRecord record;
        record.append(QSqlField("id", QVariant::Int));
        record.setValue(0, query.lastInsertId());
        QMap<QString, QVariant> boundValues = query.boundValues();
        for (QMap<QString, QVariant>::const_iterator it = boundValues.constBegin(); it != boundValues.constEnd(); ++it) {
            QString key = it.key().mid(1); // remove the ':'
            record.append(QSqlField(key, (QVariant::Type) it.value().type()));
            record.setValue(key, it.value());
        }
        records.append(record);

        if (info)
            delete info;
    }

    emit databaseUpdated(records);
    return records;
}

<commit_msg>small sql fix in radioparser.cpp<commit_after>/****************************************************************************

This file is part of the QtMediaHub project on http://www.qtmediahub.com

Copyright (c) 2011 Nokia Corporation and/or its subsidiary(-ies).*
All rights reserved.

Contact:  Girish Ramakrishnan girish@forwardbias.in
Contact:  Nokia Corporation donald.carr@nokia.com
Contact:  Nokia Corporation johannes.zellner@nokia.com

You may use this file under the terms of the BSD license as follows:

Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
* Neither the name of Nokia Corporation and its Subsidiary(-ies) nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

****************************************************************************/

#include "radioparser.h"

#include "scopedtransaction.h"
#include <QtSql>

#define DEBUG if (0) qDebug() << __PRETTY_FUNCTION__

bool RadioParser::canRead(const QFileInfo &info) const
{
    static QStringList extensions
            = QStringList() << "pls"
                            << "asx";

    return extensions.contains(info.suffix());
}

QString cleanString(QString str)
{
    str = str.simplified();
    if (!str.isEmpty())
        str[0] = str[0].toUpper();
    return str;
}

struct RadioInfo {
    QUrl uri;
    QString title;
    QString thumbnail;
    int length;
};

static RadioInfo *readPLS(QFileInfo fileInfo)
{
    QSettings settings(fileInfo.filePath(), QSettings::IniFormat);
    QStringList keys = settings.allKeys();

    if (!keys.contains("playlist/NumberOfEntries", Qt::CaseInsensitive))
        return 0;

    if (settings.value("playlist/NumberOfEntries", 0).toInt() <= 0)
        return 0;

    // currently only choose first title
    if (    !keys.contains("playlist/File1", Qt::CaseInsensitive) ||
            !keys.contains("playlist/Title1", Qt::CaseInsensitive) ||
            !keys.contains("playlist/Length1", Qt::CaseInsensitive) )
        return 0;

    QString file = settings.value("playlist/File1", "").toString();
    QString title = settings.value("playlist/Title1", "").toString();
    int length = settings.value("playlist/Length1", "").toInt();

    RadioInfo *info = new RadioInfo();
    info->uri = QUrl(file);
    info->title = title;
    info->length = length;

    QRegExp e("\\(#[0-9]+ - [0-9]+/[0-9]+\\) ");
    int regExpIndex = e.indexIn(title);
    int regExpLenght = e.matchedLength();

    if(regExpIndex == 0)
        info->title = title.right(title.length() - regExpLenght);

    return info;
}

static RadioInfo *readASX(QFileInfo fileInfo)
{
    QFile file(fileInfo.filePath());
    if (!file.open(QIODevice::ReadOnly | QIODevice::Text))
        return 0;

    QString title;
    QUrl uri;
    QString banner;

    QXmlStreamReader reader(&file);
    while(!reader.atEnd() && !reader.hasError()) {
        QXmlStreamReader::TokenType token = reader.readNext();
        if (token == QXmlStreamReader::StartDocument)
            continue;

        if (token == QXmlStreamReader::StartElement) {
            if (reader.name() == "entry") {
                continue;
            }

            if (reader.name() == "Banner" && reader.attributes().hasAttribute("href")) {
                banner = reader.attributes().value("href").toString();
                continue;
            }

            if (reader.name() == "title") {
                reader.readNext();
                if (reader.tokenType() == QXmlStreamReader::Characters)
                    title = reader.text().toString();
                continue;
            }
            if (reader.name() == "ref" && reader.attributes().hasAttribute("href")) {
                uri = reader.attributes().value("href").toString();
                continue;
            }
        }

        if (title != "" && uri.isEmpty())
            break;
    }

    if (reader.hasError() || title == "" || uri.isEmpty()) {
        reader.clear();
        return 0;
    }

    reader.clear();

    RadioInfo *info = new RadioInfo();
    info->uri = QUrl(uri);
    info->title = title;
    info->thumbnail = banner;

    return info;
}

// ## See if DELETE+INSERT is the best approach. Sqlite3 supports INSERT OR IGNORE which could aslo be used
// ## Also check other upsert methods
QList<QSqlRecord> RadioParser::updateMediaInfos(const QList<QFileInfo> &fis, const QString &searchPath, QSqlDatabase db)
{
    Q_UNUSED(searchPath);
    QList<QSqlRecord> records;
    QSqlQuery query(db);
    ScopedTransaction transaction(db);

    foreach(const QFileInfo &fi, fis) {
        DEBUG << "Updating " << fi.absoluteFilePath();

        RadioInfo *info = 0;
        if (fi.suffix() == "pls")
            info = readPLS(fi);
        else if (fi.suffix() == "asx")
            info = readASX(fi);

        if (!info)
            continue;

        query.prepare("DELETE FROM radio WHERE filepath=:filepath");
        query.bindValue(":filepath", fi.absoluteFilePath());
        if (!query.exec())
            qWarning() << query.lastError().text();

        if (!query.prepare("INSERT INTO radio (filepath, title, thumbnail, length, uri, directory, mtime, ctime, filesize) "
                           " VALUES (:filepath, :title, :thumbnail, :length, :uri, :directory, :mtime, :ctime, :filesize)")) {
            qWarning() << query.lastError().text();
            if (info)
                delete info;
            return records;
        }

        query.bindValue(":filepath", fi.absoluteFilePath());
        query.bindValue(":title", info->title);
        query.bindValue(":thumbnail", info->thumbnail);

        query.bindValue(":length", info->length);
        query.bindValue(":uri", info->uri.toEncoded());

        query.bindValue(":directory", fi.absolutePath() + '/');
        query.bindValue(":mtime", fi.lastModified().toTime_t());
        query.bindValue(":ctime", fi.created().toTime_t());
        query.bindValue(":filesize", fi.size());

        if (!query.exec())
            qWarning() << query.lastError().text();

        QSqlRecord record;
        record.append(QSqlField("id", QVariant::Int));
        record.setValue(0, query.lastInsertId());
        QMap<QString, QVariant> boundValues = query.boundValues();
        for (QMap<QString, QVariant>::const_iterator it = boundValues.constBegin(); it != boundValues.constEnd(); ++it) {
            QString key = it.key().mid(1); // remove the ':'
            record.append(QSqlField(key, (QVariant::Type) it.value().type()));
            record.setValue(key, it.value());
        }
        records.append(record);

        if (info)
            delete info;
    }

    emit databaseUpdated(records);
    return records;
}

<|endoftext|>


<commit_before>/*M///////////////////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2015, Youssef Kashef
// Copyright (c) 2015, ELM Library Project
// 3-clause BSD License
//
//M*/
#include "elm/ts/mat_assertions.h"

#if _MSC_VER && !__INTEL_COMPILER
#include <stdint.h>
#endif // _MSC_VER && !__INTEL_COMPILER

#include "elm/core/exception.h"
#include "elm/core/cv/mat_utils.h"
#include "elm/core/cv/mat_type_utils.h"

using namespace std;
using namespace testing;
using namespace cv;

template class cv::Mat_<uchar>;

AssertionResult IsType(const Mat &a, int mat_type)
{
    if((a.type() & CV_MAT_DEPTH_MASK) == (mat_type & CV_MAT_DEPTH_MASK)) {
        return AssertionSuccess();
    }
    else { return AssertionFailure() << MatTypeFailureMessage(a, mat_type); }
}

string MatTypeFailureMessage(const Mat& a, int mat_type) {

    stringstream failure_msg;

    failure_msg << "Mat of type " <<
                   elm::MatTypeToString(a) <<
                   " != " << elm::MatTypeToString(Mat(1, 1, mat_type));
    failure_msg << std::endl;
    return failure_msg.str();
}

AssertionResult EqualDims(const Mat &a, const Mat &b) {

    return EqualDims(a, b.size());
}

AssertionResult EqualDims(const Mat &a, const Size2i &s) {

    if(a.rows != s.height) return AssertionFailure() << "No. of rows do not match (" <<
                                                      a.rows << ") (" <<
                                                      s.height << ")";
    if(a.cols != s.width) return AssertionFailure() << "No. of columns do not match (" <<
                                                      a.cols << ") (" <<
                                                      s.width << ")";
    return AssertionSuccess();
}

AssertionResult EqualDims(const Mat &a, const SparseMat &b) {

    if(a.dims > 2 || b.dims() > 2) {

        ELM_THROW_NOT_IMPLEMENTED_WMSG("Assertion with > 2 dimensional Mat not yet supported.");
    }

    if(a.dims != b.dims()) {

        return AssertionFailure() << "No. of dimensions do not match (" <<
                                     a.dims << ") (" <<
                                     b.dims() << ")";
    }

    return EqualDims(a, Size2i(b.size(1), b.size(0)));
}

AssertionResult EqualDims(const SparseMat &a, const Mat &b)
{
    if(a.dims() > 2 || b.dims > 2) {

        ELM_THROW_NOT_IMPLEMENTED_WMSG("Assertion with > 2 dimensional Mat not yet supported.");
    }

    if(a.dims() != b.dims) {

        return AssertionFailure() << "No. of dimensions do not match (" <<
                                     a.dims() << ") (" <<
                                     b.dims << ")";
    }

    return EqualDims(a, Size2i(b.cols, b.rows));
}

AssertionResult EqualDims(const SparseMat &a, const SparseMat &b)
{
    if(a.dims() != b.dims()) {

        return AssertionFailure() << "No. of dimensions do not match (" <<
                                     a.dims() << ") (" <<
                                     b.dims() << ")";
    }

    for(int d=0; d<a.dims(); d++) {

        if(a.size(d) != b.size(d)) {

            stringstream d_str;
            switch(d) {

            case 0:
                d_str << "rows";
                break;
            case 1:
                d_str << "cols";
                break;
            default:
                d_str << "dim-" << d;
            }

            return AssertionFailure() << d_str.str() << " does not match (" <<
                                         a.size(d) << ") (" <<
                                         b.size(d) << ")";
        }
    }

    return AssertionSuccess();
}

AssertionResult EqualDims(const SparseMat &a, const Size2i &s)
{
    if(a.size()==NULL) {

        if(0 != s.height) return AssertionFailure() << "No. of rows do not match (" <<
                                                          0 << ") (" <<
                                                          s.height << ")";
        if(0 != s.width) return AssertionFailure() << "No. of columns do not match (" <<
                                                          0 << ") (" <<
                                                          s.width << ")";
        return AssertionSuccess();
    }

    ELM_THROW_BAD_DIMS_IF(a.dims() != 2, "Assertion only applicable to 2-dimensional SparseMat.");

    if(a.size(0) != s.height) return AssertionFailure() << "No. of rows do not match (" <<
                                                      a.size(0) << ") (" <<
                                                      s.height << ")";
    if(a.size(1) != s.width) return AssertionFailure() << "No. of columns do not match (" <<
                                                      a.size(1) << ") (" <<
                                                      s.width << ")";
    return AssertionSuccess();
}

string MatFailureMessageNonZero(const Mat& a, const Mat& b, const Mat& cmp) {

    stringstream failure_msg;
    for(int r=0; r<cmp.rows; r++) {

        for(int c=0; c<cmp.cols; c++) {

            if( cmp.at<uchar>(r, c) != 0 ) {

                failure_msg << "at (" << r << "," << c <<") ";

                uchar depth = a.type() & CV_MAT_DEPTH_MASK;

                switch ( depth ) {
                  case CV_8U:   failure_msg << "(" << a.at<uchar>(r, c)     << ") (" << b.at<uchar>(r, c)   << ")" ; break;
                  case CV_8S:   failure_msg << "(" << a.at<char>(r, c)      << ") (" << b.at<char>(r, c)    << ")" ; break;
                  case CV_16U:  failure_msg << "(" << a.at<uint16_t>(r, c)  << ") (" << b.at<uint16_t>(r, c) << ")" ; break;
                  case CV_16S:  failure_msg << "(" << a.at<int16_t>(r, c)   << ") (" << b.at<int16_t>(r, c) << ")" ; break;
                  case CV_32S:  failure_msg << "(" << a.at<int32_t>(r, c)   << ") (" << b.at<int32_t>(r, c) << ")" ; break;
                  case CV_32F:  failure_msg << "(" << a.at<float>(r, c)     << ") (" << b.at<float>(r, c)   << ")" ; break;
                  case CV_64F:  failure_msg << "(" << a.at<double>(r, c)    << ") (" << b.at<double>(r, c)  << ")" ; break;
                  default: break;
                }
                failure_msg << std::endl;
            }
        }
    }
    return failure_msg.str();
}

string MatFailureMessageNonZero(const Mat& a, const Mat& cmp) {

    stringstream failure_msg;
    for(int r=0; r<cmp.rows; r++) {

        for(int c=0; c<cmp.cols; c++) {

            if( cmp.at<uchar>(r, c) != 0 ) {

                failure_msg << "at (" << r << "," << c <<") ";

                uchar depth = a.type() & CV_MAT_DEPTH_MASK;

                switch ( depth ) {
                  case CV_8U:   failure_msg << "(" << a.at<uchar>(r, c)     << ")"; break;
                  case CV_8S:   failure_msg << "(" << a.at<char>(r, c)      << ")"; break;
                  case CV_16U:  failure_msg << "(" << a.at<uint16_t>(r, c)  << ")"; break;
                  case CV_16S:  failure_msg << "(" << a.at<int16_t>(r, c)   << ")"; break;
                  case CV_32S:  failure_msg << "(" << a.at<int32_t>(r, c)   << ")"; break;
                  case CV_32F:  failure_msg << "(" << a.at<float>(r, c)     << ")"; break;
                  case CV_64F:  failure_msg << "(" << a.at<double>(r, c)    << ")"; break;
                  default: break;
                }
                failure_msg << std::endl;
            }
        }
    }
    return failure_msg.str();
}

AssertionResult Equal(const Mat& a, const Mat& b) {

    AssertionResult equal_dims = EqualDims(a, b);
    if(equal_dims != AssertionSuccess()) { return equal_dims; }

    Mat cmp_out;
    compare(a, b, cmp_out, CMP_NE);

    Mat a_isnan = elm::isnan(a);
    Mat b_isnan = elm::isnan(b);
    Mat both_nan;
    cv::bitwise_and(a_isnan, b_isnan, both_nan);

    cmp_out.setTo(Scalar(0), both_nan);

    int n = countNonZero(cmp_out);
    if(n == 0) { return AssertionSuccess(); }
    else {
        return AssertionFailure() << MatFailureMessageNonZero(a, b, cmp_out);
    }
}

AssertionResult Equal(const SparseMat& a, const Mat& b) {

    Mat a_dense;
    a.convertTo(a_dense, a.type());
    return Equal(a_dense, b);
}

AssertionResult Equal(const Mat &a, const SparseMat &b)
{
    Mat b_dense;
    b.convertTo(b_dense, a.type());
    return Equal(a, b_dense);
}

AssertionResult Equal(const SparseMat &a, const SparseMat &b)
{
    Mat a_dense;
    a.convertTo(a_dense, a.type());
    return Equal(a_dense, b);
}

AssertionResult Near(const Mat& a, const Mat& b, float tolerance) {

    AssertionResult equal_dims = EqualDims(a, b);
    if(equal_dims != AssertionSuccess()) { return equal_dims; }

    Mat cmp_out;
    Mat diff;
    absdiff(a, b, diff);
    compare(diff, tolerance, cmp_out, CMP_GT);
    int n = countNonZero(cmp_out);
    if(n == 0) { return AssertionSuccess(); }
    else { return AssertionFailure() << MatFailureMessageNonZero(a, b, cmp_out); }
}

AssertionResult LT(const Mat& a, const Mat& b) {

    AssertionResult equal_dims = EqualDims(a, b);
    if(equal_dims != AssertionSuccess()) { return equal_dims; }

    Mat cmp_out;
    compare(a, b, cmp_out, CMP_GE);
    int n = countNonZero(cmp_out);
    if(n == 0) { return AssertionSuccess(); }
    else {
        return AssertionFailure() << MatFailureMessageNonZero(a, b, cmp_out);
    }
}

AssertionResult Empty(const Mat &mat)
{
    if(mat.empty()) { return AssertionSuccess(); }
    else {
        return AssertionFailure()
                << "Mat is not empty and contains"
                << mat.total() << " elements.";
    }
}
<commit_msg>remove redundant template instantiation<commit_after>/*M///////////////////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2015, Youssef Kashef
// Copyright (c) 2015, ELM Library Project
// 3-clause BSD License
//
//M*/
#include "elm/ts/mat_assertions.h"

#if _MSC_VER && !__INTEL_COMPILER
#include <stdint.h>
#endif // _MSC_VER && !__INTEL_COMPILER

#include "elm/core/exception.h"
#include "elm/core/cv/mat_utils.h"
#include "elm/core/cv/mat_type_utils.h"

using namespace std;
using namespace testing;
using namespace cv;

AssertionResult IsType(const Mat &a, int mat_type)
{
    if((a.type() & CV_MAT_DEPTH_MASK) == (mat_type & CV_MAT_DEPTH_MASK)) {
        return AssertionSuccess();
    }
    else { return AssertionFailure() << MatTypeFailureMessage(a, mat_type); }
}

string MatTypeFailureMessage(const Mat& a, int mat_type) {

    stringstream failure_msg;

    failure_msg << "Mat of type " <<
                   elm::MatTypeToString(a) <<
                   " != " << elm::MatTypeToString(Mat(1, 1, mat_type));
    failure_msg << std::endl;
    return failure_msg.str();
}

AssertionResult EqualDims(const Mat &a, const Mat &b) {

    return EqualDims(a, b.size());
}

AssertionResult EqualDims(const Mat &a, const Size2i &s) {

    if(a.rows != s.height) return AssertionFailure() << "No. of rows do not match (" <<
                                                      a.rows << ") (" <<
                                                      s.height << ")";
    if(a.cols != s.width) return AssertionFailure() << "No. of columns do not match (" <<
                                                      a.cols << ") (" <<
                                                      s.width << ")";
    return AssertionSuccess();
}

AssertionResult EqualDims(const Mat &a, const SparseMat &b) {

    if(a.dims > 2 || b.dims() > 2) {

        ELM_THROW_NOT_IMPLEMENTED_WMSG("Assertion with > 2 dimensional Mat not yet supported.");
    }

    if(a.dims != b.dims()) {

        return AssertionFailure() << "No. of dimensions do not match (" <<
                                     a.dims << ") (" <<
                                     b.dims() << ")";
    }

    return EqualDims(a, Size2i(b.size(1), b.size(0)));
}

AssertionResult EqualDims(const SparseMat &a, const Mat &b)
{
    if(a.dims() > 2 || b.dims > 2) {

        ELM_THROW_NOT_IMPLEMENTED_WMSG("Assertion with > 2 dimensional Mat not yet supported.");
    }

    if(a.dims() != b.dims) {

        return AssertionFailure() << "No. of dimensions do not match (" <<
                                     a.dims() << ") (" <<
                                     b.dims << ")";
    }

    return EqualDims(a, Size2i(b.cols, b.rows));
}

AssertionResult EqualDims(const SparseMat &a, const SparseMat &b)
{
    if(a.dims() != b.dims()) {

        return AssertionFailure() << "No. of dimensions do not match (" <<
                                     a.dims() << ") (" <<
                                     b.dims() << ")";
    }

    for(int d=0; d<a.dims(); d++) {

        if(a.size(d) != b.size(d)) {

            stringstream d_str;
            switch(d) {

            case 0:
                d_str << "rows";
                break;
            case 1:
                d_str << "cols";
                break;
            default:
                d_str << "dim-" << d;
            }

            return AssertionFailure() << d_str.str() << " does not match (" <<
                                         a.size(d) << ") (" <<
                                         b.size(d) << ")";
        }
    }

    return AssertionSuccess();
}

AssertionResult EqualDims(const SparseMat &a, const Size2i &s)
{
    if(a.size()==NULL) {

        if(0 != s.height) return AssertionFailure() << "No. of rows do not match (" <<
                                                          0 << ") (" <<
                                                          s.height << ")";
        if(0 != s.width) return AssertionFailure() << "No. of columns do not match (" <<
                                                          0 << ") (" <<
                                                          s.width << ")";
        return AssertionSuccess();
    }

    ELM_THROW_BAD_DIMS_IF(a.dims() != 2, "Assertion only applicable to 2-dimensional SparseMat.");

    if(a.size(0) != s.height) return AssertionFailure() << "No. of rows do not match (" <<
                                                      a.size(0) << ") (" <<
                                                      s.height << ")";
    if(a.size(1) != s.width) return AssertionFailure() << "No. of columns do not match (" <<
                                                      a.size(1) << ") (" <<
                                                      s.width << ")";
    return AssertionSuccess();
}

string MatFailureMessageNonZero(const Mat& a, const Mat& b, const Mat& cmp) {

    stringstream failure_msg;
    for(int r=0; r<cmp.rows; r++) {

        for(int c=0; c<cmp.cols; c++) {

            if( cmp.at<uchar>(r, c) != 0 ) {

                failure_msg << "at (" << r << "," << c <<") ";

                uchar depth = a.type() & CV_MAT_DEPTH_MASK;

                switch ( depth ) {
                  case CV_8U:   failure_msg << "(" << a.at<uchar>(r, c)     << ") (" << b.at<uchar>(r, c)   << ")" ; break;
                  case CV_8S:   failure_msg << "(" << a.at<char>(r, c)      << ") (" << b.at<char>(r, c)    << ")" ; break;
                  case CV_16U:  failure_msg << "(" << a.at<uint16_t>(r, c)  << ") (" << b.at<uint16_t>(r, c) << ")" ; break;
                  case CV_16S:  failure_msg << "(" << a.at<int16_t>(r, c)   << ") (" << b.at<int16_t>(r, c) << ")" ; break;
                  case CV_32S:  failure_msg << "(" << a.at<int32_t>(r, c)   << ") (" << b.at<int32_t>(r, c) << ")" ; break;
                  case CV_32F:  failure_msg << "(" << a.at<float>(r, c)     << ") (" << b.at<float>(r, c)   << ")" ; break;
                  case CV_64F:  failure_msg << "(" << a.at<double>(r, c)    << ") (" << b.at<double>(r, c)  << ")" ; break;
                  default: break;
                }
                failure_msg << std::endl;
            }
        }
    }
    return failure_msg.str();
}

string MatFailureMessageNonZero(const Mat& a, const Mat& cmp) {

    stringstream failure_msg;
    for(int r=0; r<cmp.rows; r++) {

        for(int c=0; c<cmp.cols; c++) {

            if( cmp.at<uchar>(r, c) != 0 ) {

                failure_msg << "at (" << r << "," << c <<") ";

                uchar depth = a.type() & CV_MAT_DEPTH_MASK;

                switch ( depth ) {
                  case CV_8U:   failure_msg << "(" << a.at<uchar>(r, c)     << ")"; break;
                  case CV_8S:   failure_msg << "(" << a.at<char>(r, c)      << ")"; break;
                  case CV_16U:  failure_msg << "(" << a.at<uint16_t>(r, c)  << ")"; break;
                  case CV_16S:  failure_msg << "(" << a.at<int16_t>(r, c)   << ")"; break;
                  case CV_32S:  failure_msg << "(" << a.at<int32_t>(r, c)   << ")"; break;
                  case CV_32F:  failure_msg << "(" << a.at<float>(r, c)     << ")"; break;
                  case CV_64F:  failure_msg << "(" << a.at<double>(r, c)    << ")"; break;
                  default: break;
                }
                failure_msg << std::endl;
            }
        }
    }
    return failure_msg.str();
}

AssertionResult Equal(const Mat& a, const Mat& b) {

    AssertionResult equal_dims = EqualDims(a, b);
    if(equal_dims != AssertionSuccess()) { return equal_dims; }

    Mat cmp_out;
    compare(a, b, cmp_out, CMP_NE);

    Mat a_isnan = elm::isnan(a);
    Mat b_isnan = elm::isnan(b);
    Mat both_nan;
    cv::bitwise_and(a_isnan, b_isnan, both_nan);

    cmp_out.setTo(Scalar(0), both_nan);

    int n = countNonZero(cmp_out);
    if(n == 0) { return AssertionSuccess(); }
    else {
        return AssertionFailure() << MatFailureMessageNonZero(a, b, cmp_out);
    }
}

AssertionResult Equal(const SparseMat& a, const Mat& b) {

    Mat a_dense;
    a.convertTo(a_dense, a.type());
    return Equal(a_dense, b);
}

AssertionResult Equal(const Mat &a, const SparseMat &b)
{
    Mat b_dense;
    b.convertTo(b_dense, a.type());
    return Equal(a, b_dense);
}

AssertionResult Equal(const SparseMat &a, const SparseMat &b)
{
    Mat a_dense;
    a.convertTo(a_dense, a.type());
    return Equal(a_dense, b);
}

AssertionResult Near(const Mat& a, const Mat& b, float tolerance) {

    AssertionResult equal_dims = EqualDims(a, b);
    if(equal_dims != AssertionSuccess()) { return equal_dims; }

    Mat cmp_out;
    Mat diff;
    absdiff(a, b, diff);
    compare(diff, tolerance, cmp_out, CMP_GT);
    int n = countNonZero(cmp_out);
    if(n == 0) { return AssertionSuccess(); }
    else { return AssertionFailure() << MatFailureMessageNonZero(a, b, cmp_out); }
}

AssertionResult LT(const Mat& a, const Mat& b) {

    AssertionResult equal_dims = EqualDims(a, b);
    if(equal_dims != AssertionSuccess()) { return equal_dims; }

    Mat cmp_out;
    compare(a, b, cmp_out, CMP_GE);
    int n = countNonZero(cmp_out);
    if(n == 0) { return AssertionSuccess(); }
    else {
        return AssertionFailure() << MatFailureMessageNonZero(a, b, cmp_out);
    }
}

AssertionResult Empty(const Mat &mat)
{
    if(mat.empty()) { return AssertionSuccess(); }
    else {
        return AssertionFailure()
                << "Mat is not empty and contains"
                << mat.total() << " elements.";
    }
}
<|endoftext|>


<commit_before>// This file is part of the "x0" project, http://github.com/christianparpart/x0>
//   (c) 2009-2016 Christian Parpart <trapni@gmail.com>
//
// Licensed under the MIT License (the "License"); you may not use this
// file except in compliance with the License. You may obtain a copy of
// the License at: http://opensource.org/licenses/MIT

#include <xzero/BufferUtil.h>
#include <xzero/inspect.h>

namespace xzero {

void BufferUtil::stripTrailingBytes(Buffer* buf, unsigned char byte) {
  auto begin = (const unsigned char*) buf->data();
  auto cur = begin + buf->size();

  while (cur > begin && *(cur - 1) == byte) {
    cur--;
  }

  buf->truncate(cur - begin);
}

void BufferUtil::stripTrailingSlashes(Buffer* buf) {
  stripTrailingBytes(buf, '/');
}

std::string BufferUtil::hexPrint(
    Buffer* buf,
    bool sep /* = true */,
    bool reverse /* = fase */) {
  static const char hexTable[] = "0123456789abcdef";
  auto data = (const unsigned char*) buf->data();
  auto size = buf->size();
  std::string str;

  if (reverse) {
    for (int i = size - 1; i >= 0; --i) {
      if (sep && i < size - 1) { str += " "; }
      auto byte = data[i];
      str += hexTable[(byte & 0xf0) >> 4];
      str += hexTable[byte & 0x0f];
    }
  } else {
    for (int i = 0; i < size; ++i) {
      if (sep && i > 0) { str += " "; }
      auto byte = data[i];
      str += hexTable[(byte & 0xf0) >> 4];
      str += hexTable[byte & 0x0f];
    }
  }

  return str;
}
} // namespace xzero

<commit_msg>compile warning fixes<commit_after>// This file is part of the "x0" project, http://github.com/christianparpart/x0>
//   (c) 2009-2016 Christian Parpart <trapni@gmail.com>
//
// Licensed under the MIT License (the "License"); you may not use this
// file except in compliance with the License. You may obtain a copy of
// the License at: http://opensource.org/licenses/MIT

#include <xzero/BufferUtil.h>
#include <xzero/inspect.h>

namespace xzero {

void BufferUtil::stripTrailingBytes(Buffer* buf, unsigned char byte) {
  auto begin = (const unsigned char*) buf->data();
  auto cur = begin + buf->size();

  while (cur > begin && *(cur - 1) == byte) {
    cur--;
  }

  buf->truncate(cur - begin);
}

void BufferUtil::stripTrailingSlashes(Buffer* buf) {
  stripTrailingBytes(buf, '/');
}

std::string BufferUtil::hexPrint(
    Buffer* buf,
    bool sep /* = true */,
    bool reverse /* = fase */) {
  static const char hexTable[] = "0123456789abcdef";
  auto data = (const unsigned char*) buf->data();
  int size = static_cast<int>(buf->size());
  std::string str;

  if (!reverse) {
    for (int i = 0; i < size; ++i) {
      if (sep && i > 0) { str += " "; }
      auto byte = data[i];
      str += hexTable[(byte & 0xf0) >> 4];
      str += hexTable[byte & 0x0f];
    }
  } else {
    for (int i = size - 1; i >= 0; --i) {
      if (sep && i < size - 1) { str += " "; }
      auto byte = data[i];
      str += hexTable[(byte & 0xf0) >> 4];
      str += hexTable[byte & 0x0f];
    }
  }

  return str;
}

} // namespace xzero
<|endoftext|>


<commit_before>////////////////////////////////////////////////////////////////////////////////
//                                                                            //
// AliFemtoCutMonitorParticleEtCorr - the cut monitor for particles           //
// which saves particles' et histogram and makes the bin-by-bin correlation   //
//                                                                            //
// Author: Adam.Kisiel@cern.ch                                                //
//                                                                            //
////////////////////////////////////////////////////////////////////////////////
#include "AliFemtoCutMonitorParticleEtCorr.h"
#include "AliFemtoModelHiddenInfo.h"
#include <TH1D.h>
#include <TH2D.h>
#include <TList.h>
#include <TMath.h>

AliFemtoCutMonitorParticleEtCorr::AliFemtoCutMonitorParticleEtCorr():
  AliFemtoCutMonitor(),
  fPhiBins(60),
  fPtPerPhi(0),
  fPtCovPerPhi(0),
  fPtMultPerPhi(0),
  fNEventsProcessed(0)
{
  // Default constructor
}

AliFemtoCutMonitorParticleEtCorr::AliFemtoCutMonitorParticleEtCorr(const char *aName, int aPhiBins):
  AliFemtoCutMonitor(),
  fPhiBins(aPhiBins),
  fPtPerPhi(0),
  fPtCovPerPhi(0),
  fPtMultPerPhi(0),
  fNEventsProcessed(0)
{
  // Normal constructor
  char name[200];
  snprintf(name, 200, "EtCorrAvgPt%s", aName);
  fPtPerPhi = new TH1D(name, "Average Pt Per Phi", aPhiBins, -0.5, aPhiBins-0.5);
  snprintf(name, 200, "EtCorrMult%s", aName);
  fPtMultPerPhi = new TH2D(name, "Multiplicity Per Phi", aPhiBins, -0.5, aPhiBins-0.5, aPhiBins, -0.5, aPhiBins-0.5);
  snprintf(name, 200, "EtCorrAvgPtCov%s", aName);
  fPtCovPerPhi = new TH2D(name, "Covariance of Average Pt Per Phi", aPhiBins, -0.5, aPhiBins-0.5, aPhiBins, -0.5, aPhiBins-0.5);

  fPtPerPhi->Sumw2();
  fPtCovPerPhi->Sumw2();
  fPtMultPerPhi->Sumw2();
  fPhiBins = aPhiBins;
}

AliFemtoCutMonitorParticleEtCorr::AliFemtoCutMonitorParticleEtCorr(const AliFemtoCutMonitorParticleEtCorr &aCut):
  AliFemtoCutMonitor(),
  fPhiBins(0),
  fPtPerPhi(0),
  fPtCovPerPhi(0),
  fPtMultPerPhi(0),
  fNEventsProcessed(0)
{
  // copy constructor
  if (fPtCovPerPhi) delete fPtCovPerPhi;
  fPtCovPerPhi = new TH2D(*aCut.fPtCovPerPhi);
  if (fPtPerPhi) delete fPtPerPhi;
  fPtPerPhi = new TH1D(*aCut.fPtPerPhi);
  if (fPtMultPerPhi) delete fPtMultPerPhi;
  fPtMultPerPhi = new TH2D(*aCut.fPtMultPerPhi);
  fPhiBins = aCut.fPhiBins;
  fNEventsProcessed = aCut.fNEventsProcessed;
}

AliFemtoCutMonitorParticleEtCorr::~AliFemtoCutMonitorParticleEtCorr()
{
  // Destructor
  delete fPtPerPhi;
  delete fPtMultPerPhi;
  delete fPtCovPerPhi;
}

AliFemtoCutMonitorParticleEtCorr& AliFemtoCutMonitorParticleEtCorr::operator=(const AliFemtoCutMonitorParticleEtCorr& aCut)
{
  // assignment operator
  if (this == &aCut)
    return *this;

  if (fPtCovPerPhi) delete fPtCovPerPhi;
  fPtCovPerPhi = new TH2D(*aCut.fPtCovPerPhi);
  if (fPtPerPhi) delete fPtPerPhi;
  fPtPerPhi = new TH1D(*aCut.fPtPerPhi);
  if (fPtMultPerPhi) delete fPtMultPerPhi;
  fPtMultPerPhi = new TH2D(*aCut.fPtMultPerPhi);
  fPhiBins = aCut.fPhiBins;
  fNEventsProcessed = aCut.fNEventsProcessed;

  return *this;
}

AliFemtoString AliFemtoCutMonitorParticleEtCorr::Report(){
  // Prepare report from the execution
  string stemp = "*** AliFemtoCutMonitorParticleEtCorr report";
  AliFemtoString returnThis = stemp;
  return returnThis;
}

void AliFemtoCutMonitorParticleEtCorr::Fill(const AliFemtoTrack* aTrack)
{
  // Fill in the monitor histograms with the values from the current track
  //  float tEnergy = ::sqrt(aTrack->P().mag2()+fMass*fMass);
  //  float tRapidity = 0.5*::log((tEnergy+aTrack->P().z())/(tEnergy-aTrack->P().z()));
  float tPt = ::sqrt((aTrack->P().x())*(aTrack->P().x())+(aTrack->P().y())*(aTrack->P().y()));
  //  float tEta = -TMath::Log(TMath::Tan(aTrack->P().theta()/2.0));
  float tPhi = aTrack->P().Phi();
  Double_t tPiTwo = TMath::Pi()*2;

  while (tPhi > tPiTwo) tPhi -= tPiTwo;
  while (tPhi < 0) tPhi += tPiTwo;

  int nbin = (int) floor(tPhi * fPhiBins / tPiTwo);
  fPtSumEvent[nbin] += tPt;
  fMultSumEvent[nbin] += 1;
}

void AliFemtoCutMonitorParticleEtCorr::Write()
{
  // Write out the relevant histograms
  fPtPerPhi->Write();
  fPtCovPerPhi->Write();
  fPtMultPerPhi->Write();
}

TList *AliFemtoCutMonitorParticleEtCorr::GetOutputList()
{
  TList *tOutputList = new TList();
  tOutputList->Add(fPtPerPhi);
  tOutputList->Add(fPtCovPerPhi);
  tOutputList->Add(fPtMultPerPhi);

  return tOutputList;
}

void AliFemtoCutMonitorParticleEtCorr::EventBegin(const AliFemtoEvent* aEvent)
{
  if (aEvent)
    for (int iter=0; iter<fPhiBins; iter++) {
      fPtSumEvent[iter] = 0;
      fMultSumEvent[iter] = 0;
    }
}

void AliFemtoCutMonitorParticleEtCorr::EventEnd(const AliFemtoEvent* aEvent)
{
  if (aEvent) {
    for (int ispt=0; ispt<fPhiBins; ispt++) {
      fPtPerPhi->Fill(ispt, fPtSumEvent[ispt]);
      for (int ispt2=0; ispt2<fPhiBins; ispt2++) {
	fPtCovPerPhi->Fill(ispt, ispt2, fPtSumEvent[ispt]*fPtSumEvent[ispt2]);
	fPtMultPerPhi->Fill(ispt, ispt2, fMultSumEvent[ispt]*fMultSumEvent[ispt2]);
      }
    }
    fNEventsProcessed++;
  }
}

<commit_msg>Fix Coverity 15466-8<commit_after>////////////////////////////////////////////////////////////////////////////////
//                                                                            //
// AliFemtoCutMonitorParticleEtCorr - the cut monitor for particles           //
// which saves particles' et histogram and makes the bin-by-bin correlation   //
//                                                                            //
// Author: Adam.Kisiel@cern.ch                                                //
//                                                                            //
////////////////////////////////////////////////////////////////////////////////
#include "AliFemtoCutMonitorParticleEtCorr.h"
#include "AliFemtoModelHiddenInfo.h"
#include <TH1D.h>
#include <TH2D.h>
#include <TList.h>
#include <TMath.h>

AliFemtoCutMonitorParticleEtCorr::AliFemtoCutMonitorParticleEtCorr():
  AliFemtoCutMonitor(),
  fPhiBins(60),
  fPtPerPhi(0),
  fPtCovPerPhi(0),
  fPtMultPerPhi(0),
  fNEventsProcessed(0)
{
  // Default constructor
  for (int ib=0; ib<200; ib++) {
    fPtSumEvent[ib] = 0;
    fMultSumEvent[ib] = 0;
  }
}

AliFemtoCutMonitorParticleEtCorr::AliFemtoCutMonitorParticleEtCorr(const char *aName, int aPhiBins):
  AliFemtoCutMonitor(),
  fPhiBins(aPhiBins),
  fPtPerPhi(0),
  fPtCovPerPhi(0),
  fPtMultPerPhi(0),
  fNEventsProcessed(0)
{
  // Normal constructor
  char name[200];
  snprintf(name, 200, "EtCorrAvgPt%s", aName);
  fPtPerPhi = new TH1D(name, "Average Pt Per Phi", aPhiBins, -0.5, aPhiBins-0.5);
  snprintf(name, 200, "EtCorrMult%s", aName);
  fPtMultPerPhi = new TH2D(name, "Multiplicity Per Phi", aPhiBins, -0.5, aPhiBins-0.5, aPhiBins, -0.5, aPhiBins-0.5);
  snprintf(name, 200, "EtCorrAvgPtCov%s", aName);
  fPtCovPerPhi = new TH2D(name, "Covariance of Average Pt Per Phi", aPhiBins, -0.5, aPhiBins-0.5, aPhiBins, -0.5, aPhiBins-0.5);

  fPtPerPhi->Sumw2();
  fPtCovPerPhi->Sumw2();
  fPtMultPerPhi->Sumw2();
  fPhiBins = aPhiBins;

  for (int ib=0; ib<200; ib++) {
    fPtSumEvent[ib] = 0;
    fMultSumEvent[ib] = 0;
  }

}

AliFemtoCutMonitorParticleEtCorr::AliFemtoCutMonitorParticleEtCorr(const AliFemtoCutMonitorParticleEtCorr &aCut):
  AliFemtoCutMonitor(),
  fPhiBins(0),
  fPtPerPhi(0),
  fPtCovPerPhi(0),
  fPtMultPerPhi(0),
  fNEventsProcessed(0)
{
  // copy constructor
  if (fPtCovPerPhi) delete fPtCovPerPhi;
  fPtCovPerPhi = new TH2D(*aCut.fPtCovPerPhi);
  if (fPtPerPhi) delete fPtPerPhi;
  fPtPerPhi = new TH1D(*aCut.fPtPerPhi);
  if (fPtMultPerPhi) delete fPtMultPerPhi;
  fPtMultPerPhi = new TH2D(*aCut.fPtMultPerPhi);
  fPhiBins = aCut.fPhiBins;
  fNEventsProcessed = aCut.fNEventsProcessed;

  for (int ib=0; ib<200; ib++) {
    fPtSumEvent[ib] = 0;
    fMultSumEvent[ib] = 0;
  }
}

AliFemtoCutMonitorParticleEtCorr::~AliFemtoCutMonitorParticleEtCorr()
{
  // Destructor
  delete fPtPerPhi;
  delete fPtMultPerPhi;
  delete fPtCovPerPhi;
}

AliFemtoCutMonitorParticleEtCorr& AliFemtoCutMonitorParticleEtCorr::operator=(const AliFemtoCutMonitorParticleEtCorr& aCut)
{
  // assignment operator
  if (this == &aCut)
    return *this;

  if (fPtCovPerPhi) delete fPtCovPerPhi;
  fPtCovPerPhi = new TH2D(*aCut.fPtCovPerPhi);
  if (fPtPerPhi) delete fPtPerPhi;
  fPtPerPhi = new TH1D(*aCut.fPtPerPhi);
  if (fPtMultPerPhi) delete fPtMultPerPhi;
  fPtMultPerPhi = new TH2D(*aCut.fPtMultPerPhi);
  fPhiBins = aCut.fPhiBins;
  fNEventsProcessed = aCut.fNEventsProcessed;

  return *this;
}

AliFemtoString AliFemtoCutMonitorParticleEtCorr::Report(){
  // Prepare report from the execution
  string stemp = "*** AliFemtoCutMonitorParticleEtCorr report";
  AliFemtoString returnThis = stemp;
  return returnThis;
}

void AliFemtoCutMonitorParticleEtCorr::Fill(const AliFemtoTrack* aTrack)
{
  // Fill in the monitor histograms with the values from the current track
  //  float tEnergy = ::sqrt(aTrack->P().mag2()+fMass*fMass);
  //  float tRapidity = 0.5*::log((tEnergy+aTrack->P().z())/(tEnergy-aTrack->P().z()));
  float tPt = ::sqrt((aTrack->P().x())*(aTrack->P().x())+(aTrack->P().y())*(aTrack->P().y()));
  //  float tEta = -TMath::Log(TMath::Tan(aTrack->P().theta()/2.0));
  float tPhi = aTrack->P().Phi();
  Double_t tPiTwo = TMath::Pi()*2;

  while (tPhi > tPiTwo) tPhi -= tPiTwo;
  while (tPhi < 0) tPhi += tPiTwo;

  int nbin = (int) floor(tPhi * fPhiBins / tPiTwo);
  fPtSumEvent[nbin] += tPt;
  fMultSumEvent[nbin] += 1;
}

void AliFemtoCutMonitorParticleEtCorr::Write()
{
  // Write out the relevant histograms
  fPtPerPhi->Write();
  fPtCovPerPhi->Write();
  fPtMultPerPhi->Write();
}

TList *AliFemtoCutMonitorParticleEtCorr::GetOutputList()
{
  TList *tOutputList = new TList();
  tOutputList->Add(fPtPerPhi);
  tOutputList->Add(fPtCovPerPhi);
  tOutputList->Add(fPtMultPerPhi);

  return tOutputList;
}

void AliFemtoCutMonitorParticleEtCorr::EventBegin(const AliFemtoEvent* aEvent)
{
  if (aEvent)
    for (int iter=0; iter<fPhiBins; iter++) {
      fPtSumEvent[iter] = 0;
      fMultSumEvent[iter] = 0;
    }
}

void AliFemtoCutMonitorParticleEtCorr::EventEnd(const AliFemtoEvent* aEvent)
{
  if (aEvent) {
    for (int ispt=0; ispt<fPhiBins; ispt++) {
      fPtPerPhi->Fill(ispt, fPtSumEvent[ispt]);
      for (int ispt2=0; ispt2<fPhiBins; ispt2++) {
	fPtCovPerPhi->Fill(ispt, ispt2, fPtSumEvent[ispt]*fPtSumEvent[ispt2]);
	fPtMultPerPhi->Fill(ispt, ispt2, fMultSumEvent[ispt]*fMultSumEvent[ispt2]);
      }
    }
    fNEventsProcessed++;
  }
}

<|endoftext|>


<commit_before>/*
 * Copyright © 2012 Intel Corporation
 *
 * Permission is hereby granted, free of charge, to any person obtaining a
 * copy of this software and associated documentation files (the "Software"),
 * to deal in the Software without restriction, including without limitation
 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
 * and/or sell copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice (including the next
 * paragraph) shall be included in all copies or substantial portions of the
 * Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
 * IN THE SOFTWARE.
 */

#include "intel_fbo.h"

#include "brw_blorp.h"
#include "brw_defines.h"
#include "gen6_blorp.h"
#include "gen7_blorp.h"

brw_blorp_mip_info::brw_blorp_mip_info()
   : mt(NULL),
     width(0),
     height(0),
     x_offset(0),
     y_offset(0)
{
}

brw_blorp_surface_info::brw_blorp_surface_info()
   : map_stencil_as_y_tiled(false),
     num_samples(0)
{
}

void
brw_blorp_mip_info::set(struct intel_mipmap_tree *mt,
                        unsigned int level, unsigned int layer)
{
   intel_miptree_check_level_layer(mt, level, layer);

   this->mt = mt;
   this->width = mt->level[level].width;
   this->height = mt->level[level].height;

   /* Construct a dummy renderbuffer just to extract tile offsets. */
   struct intel_renderbuffer rb;
   rb.mt = mt;
   rb.mt_level = level;
   rb.mt_layer = layer;
   intel_renderbuffer_set_draw_offset(&rb);
   x_offset = rb.draw_x;
   y_offset = rb.draw_y;
}

void
brw_blorp_surface_info::set(struct brw_context *brw,
                            struct intel_mipmap_tree *mt,
                            unsigned int level, unsigned int layer)
{
   brw_blorp_mip_info::set(mt, level, layer);
   this->num_samples = mt->num_samples;
   this->array_spacing_lod0 = mt->array_spacing_lod0;
   this->map_stencil_as_y_tiled = false;
   this->msaa_layout = mt->msaa_layout;

   switch (mt->format) {
   case MESA_FORMAT_S8:
      /* The miptree is a W-tiled stencil buffer.  Surface states can't be set
       * up for W tiling, so we'll need to use Y tiling and have the WM
       * program swizzle the coordinates.
       */
      this->map_stencil_as_y_tiled = true;
      this->brw_surfaceformat = BRW_SURFACEFORMAT_R8_UNORM;
      break;
   case MESA_FORMAT_X8_Z24:
   case MESA_FORMAT_Z32_FLOAT:
      /* The miptree consists of 32 bits per pixel, arranged either as 24-bit
       * depth values interleaved with 8 "don't care" bits, or as 32-bit
       * floating point depth values.  Since depth values don't require any
       * blending, it doesn't matter how we interpret the bit pattern as long
       * as we copy the right amount of data, so just map it as 8-bit BGRA.
       */
      this->brw_surfaceformat = BRW_SURFACEFORMAT_B8G8R8A8_UNORM;
      break;
   case MESA_FORMAT_Z16:
      /* The miptree consists of 16 bits per pixel of depth data.  Since depth
       * values don't require any blending, it doesn't matter how we interpret
       * the bit pattern as long as we copy the right amount of data, so just
       * map is as 8-bit RG.
       */
      this->brw_surfaceformat = BRW_SURFACEFORMAT_R8G8_UNORM;
      break;
   default:
      /* Blorp blits don't support any sort of format conversion, so we can
       * safely assume that the same format is being used for the source and
       * destination.  Therefore the format must be supported as a render
       * target, even if this is the source image.  So we can convert to a
       * surface format using brw->render_target_format.
       */
      assert(brw->format_supported_as_render_target[mt->format]);
      this->brw_surfaceformat = brw->render_target_format[mt->format];
      break;
   }
}

brw_blorp_params::brw_blorp_params()
   : x0(0),
     y0(0),
     x1(0),
     y1(0),
     depth_format(0),
     hiz_op(GEN6_HIZ_OP_NONE),
     num_samples(0),
     use_wm_prog(false)
{
}

extern "C" {
void
intel_hiz_exec(struct intel_context *intel, struct intel_mipmap_tree *mt,
	       unsigned int level, unsigned int layer, gen6_hiz_op op)
{
   brw_hiz_op_params params(mt, level, layer, op);
   brw_blorp_exec(intel, &params);
}

} /* extern "C" */

void
brw_blorp_exec(struct intel_context *intel, const brw_blorp_params *params)
{
   switch (intel->gen) {
   case 6:
      gen6_blorp_exec(intel, params);
      break;
   case 7:
      gen7_blorp_exec(intel, params);
      break;
   default:
      /* BLORP is not supported before Gen6. */
      assert(false);
      break;
   }
}

brw_hiz_op_params::brw_hiz_op_params(struct intel_mipmap_tree *mt,
                                     unsigned int level,
                                     unsigned int layer,
                                     gen6_hiz_op op)
{
   this->hiz_op = op;

   depth.set(mt, level, layer);
   x1 = depth.width;
   y1 = depth.height;

   assert(mt->hiz_mt != NULL);

   switch (mt->format) {
   case MESA_FORMAT_Z16:       depth_format = BRW_DEPTHFORMAT_D16_UNORM; break;
   case MESA_FORMAT_Z32_FLOAT: depth_format = BRW_DEPTHFORMAT_D32_FLOAT; break;
   case MESA_FORMAT_X8_Z24:    depth_format = BRW_DEPTHFORMAT_D24_UNORM_X8_UINT; break;
   default:                    assert(0); break;
   }
}

uint32_t
brw_hiz_op_params::get_wm_prog(struct brw_context *brw,
                               brw_blorp_prog_data **prog_data) const
{
   return 0;
}
<commit_msg>i965/blorp: Don't create a dummy renderbuffer just to fetch image offsets.<commit_after>/*
 * Copyright © 2012 Intel Corporation
 *
 * Permission is hereby granted, free of charge, to any person obtaining a
 * copy of this software and associated documentation files (the "Software"),
 * to deal in the Software without restriction, including without limitation
 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
 * and/or sell copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice (including the next
 * paragraph) shall be included in all copies or substantial portions of the
 * Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
 * IN THE SOFTWARE.
 */

#include "intel_fbo.h"

#include "brw_blorp.h"
#include "brw_defines.h"
#include "gen6_blorp.h"
#include "gen7_blorp.h"

brw_blorp_mip_info::brw_blorp_mip_info()
   : mt(NULL),
     width(0),
     height(0),
     x_offset(0),
     y_offset(0)
{
}

brw_blorp_surface_info::brw_blorp_surface_info()
   : map_stencil_as_y_tiled(false),
     num_samples(0)
{
}

void
brw_blorp_mip_info::set(struct intel_mipmap_tree *mt,
                        unsigned int level, unsigned int layer)
{
   intel_miptree_check_level_layer(mt, level, layer);

   this->mt = mt;
   this->width = mt->level[level].width;
   this->height = mt->level[level].height;

   intel_miptree_get_image_offset(mt, level, 0, layer, &x_offset, &y_offset);
}

void
brw_blorp_surface_info::set(struct brw_context *brw,
                            struct intel_mipmap_tree *mt,
                            unsigned int level, unsigned int layer)
{
   brw_blorp_mip_info::set(mt, level, layer);
   this->num_samples = mt->num_samples;
   this->array_spacing_lod0 = mt->array_spacing_lod0;
   this->map_stencil_as_y_tiled = false;
   this->msaa_layout = mt->msaa_layout;

   switch (mt->format) {
   case MESA_FORMAT_S8:
      /* The miptree is a W-tiled stencil buffer.  Surface states can't be set
       * up for W tiling, so we'll need to use Y tiling and have the WM
       * program swizzle the coordinates.
       */
      this->map_stencil_as_y_tiled = true;
      this->brw_surfaceformat = BRW_SURFACEFORMAT_R8_UNORM;
      break;
   case MESA_FORMAT_X8_Z24:
   case MESA_FORMAT_Z32_FLOAT:
      /* The miptree consists of 32 bits per pixel, arranged either as 24-bit
       * depth values interleaved with 8 "don't care" bits, or as 32-bit
       * floating point depth values.  Since depth values don't require any
       * blending, it doesn't matter how we interpret the bit pattern as long
       * as we copy the right amount of data, so just map it as 8-bit BGRA.
       */
      this->brw_surfaceformat = BRW_SURFACEFORMAT_B8G8R8A8_UNORM;
      break;
   case MESA_FORMAT_Z16:
      /* The miptree consists of 16 bits per pixel of depth data.  Since depth
       * values don't require any blending, it doesn't matter how we interpret
       * the bit pattern as long as we copy the right amount of data, so just
       * map is as 8-bit RG.
       */
      this->brw_surfaceformat = BRW_SURFACEFORMAT_R8G8_UNORM;
      break;
   default:
      /* Blorp blits don't support any sort of format conversion, so we can
       * safely assume that the same format is being used for the source and
       * destination.  Therefore the format must be supported as a render
       * target, even if this is the source image.  So we can convert to a
       * surface format using brw->render_target_format.
       */
      assert(brw->format_supported_as_render_target[mt->format]);
      this->brw_surfaceformat = brw->render_target_format[mt->format];
      break;
   }
}

brw_blorp_params::brw_blorp_params()
   : x0(0),
     y0(0),
     x1(0),
     y1(0),
     depth_format(0),
     hiz_op(GEN6_HIZ_OP_NONE),
     num_samples(0),
     use_wm_prog(false)
{
}

extern "C" {
void
intel_hiz_exec(struct intel_context *intel, struct intel_mipmap_tree *mt,
	       unsigned int level, unsigned int layer, gen6_hiz_op op)
{
   brw_hiz_op_params params(mt, level, layer, op);
   brw_blorp_exec(intel, &params);
}

} /* extern "C" */

void
brw_blorp_exec(struct intel_context *intel, const brw_blorp_params *params)
{
   switch (intel->gen) {
   case 6:
      gen6_blorp_exec(intel, params);
      break;
   case 7:
      gen7_blorp_exec(intel, params);
      break;
   default:
      /* BLORP is not supported before Gen6. */
      assert(false);
      break;
   }
}

brw_hiz_op_params::brw_hiz_op_params(struct intel_mipmap_tree *mt,
                                     unsigned int level,
                                     unsigned int layer,
                                     gen6_hiz_op op)
{
   this->hiz_op = op;

   depth.set(mt, level, layer);
   x1 = depth.width;
   y1 = depth.height;

   assert(mt->hiz_mt != NULL);

   switch (mt->format) {
   case MESA_FORMAT_Z16:       depth_format = BRW_DEPTHFORMAT_D16_UNORM; break;
   case MESA_FORMAT_Z32_FLOAT: depth_format = BRW_DEPTHFORMAT_D32_FLOAT; break;
   case MESA_FORMAT_X8_Z24:    depth_format = BRW_DEPTHFORMAT_D24_UNORM_X8_UINT; break;
   default:                    assert(0); break;
   }
}

uint32_t
brw_hiz_op_params::get_wm_prog(struct brw_context *brw,
                               brw_blorp_prog_data **prog_data) const
{
   return 0;
}
<|endoftext|>