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

///
/// @file p9_mss_ddr_phy_reset.C
/// @brief Reset the DDR PHY
///
// *HWP HWP Owner: Brian Silver <bsilver@us.ibm.com>
// *HWP HWP Backup: Andre Marin <aamarin@us.ibm.com>
// *HWP Team: Memory
// *HWP Level: 2
// *HWP Consumed by: FSP:HB

#include <stdint.h>
#include <string.h>

#include <fapi2.H>
#include <mss.H>

#include <p9_mss_ddr_phy_reset.H>
#include <lib/utils/count_dimm.H>
#include <lib/phy/adr32s.H>
#include <lib/workarounds/dp16_workarounds.H>
#include <lib/fir/check.H>
#include <lib/fir/unmask.H>

using fapi2::TARGET_TYPE_MCBIST;

extern "C"
{

///
/// @brief Perform a phy reset on all the PHY related to this half-chip (mcbist)
/// @param[in] the mcbist representing the PHY
/// @return FAPI2_RC_SUCCESS iff OK
///
    fapi2::ReturnCode p9_mss_ddr_phy_reset(const fapi2::Target<fapi2::TARGET_TYPE_MCBIST>& i_target)
    {

        // If there are no DIMM we don't need to bother. In fact, we can't as we didn't setup
        // attributes for the PHY, etc.
        if (mss::count_dimm(i_target) == 0)
        {
            FAPI_INF("... skipping ddr_phy_reset %s - no DIMM ...", mss::c_str(i_target));
            return fapi2::FAPI2_RC_SUCCESS;
        }

        FAPI_TRY(mss::change_force_mclk_low(i_target, mss::LOW),
                 "force_mclk_low (set high) Failed rc = 0x%08X", uint64_t(fapi2::current_err) );

        // New for Nimbus - perform duty cycle clock distortion calibration
#ifdef RUN_DCD
        FAPI_TRY( mss::adr32s::duty_cycle_distortion_calibration(i_target) );
#endif

        // 1. Drive all control signals to the PHY to their inactive state, idle state, or inactive value.
        FAPI_TRY( mss::dp16::reset_sysclk(i_target) );

        //    (Note: The chip should already be in this state.)
        FAPI_DBG("All control signals to the PHYs should be set to their inactive state, idle state, or inactive values");

        // 2. Assert reset to PHY for 32 memory clocks
        FAPI_TRY( mss::change_resetn(i_target, mss::HIGH), "change_resetn for %s failed", mss::c_str(i_target) );
        fapi2::delay(mss::cycles_to_ns(i_target, 32), mss::cycles_to_simcycles(32));

        // 3. Deassert reset_n
        FAPI_TRY( mss::change_resetn(i_target, mss::LOW), "change_resetn for %s failed", mss::c_str(i_target) );

        //
        // Flush output drivers
        //

        // 8. Set FLUSH=1 and INIT_IO=1 in the DDRPHY_ADR_OUTPUT_FORCE_ATEST_CNTL and DDRPHY_DP16_DATA_BIT_DIR1 register
        // 9. Wait at least 32 dphy_gckn clock cycles.
        // 10. Set FLUSH=0 and INIT_IO=0 in the DDRPHY_ADR_OUTPUT_FORCE_ATEST_CNTL register
        FAPI_TRY( mss::flush_output_drivers(i_target), "unable to flush output drivers for %s", mss::c_str(i_target) );

        //
        // ZCTL Enable
        //

        // 11. Assert the ZCNTL enable to the internal impedance controller in DDRPHY_PC_RESETS register
        // 12. Wait at least 1024 dphy_gckn cycles
        // 13. Deassert the ZCNTL impedance controller enable, Check for DONE in DDRPHY_PC_DLL_ZCAL
        FAPI_TRY( mss::enable_zctl(i_target), "enable_zctl for %s failed", mss::c_str(i_target) );

        //
        // DLL calibration
        //

        // 14. Begin DLL calibrations by setting INIT_RXDLL_CAL_RESET=0 in the DDRPHY_DP16_DLL_CNTL{0:1} registers
        // and DDRPHY_ADR_DLL_CNTL registers
        // 15. Monitor the DDRPHY_PC_DLL_ZCAL_CAL_STATUS register to determine when calibration is
        // complete. One of the 3 bits will be asserted for ADR and DP16.
        FAPI_INF( "starting DLL calibration %s", mss::c_str(i_target) );
        FAPI_TRY( mss::dll_calibration(i_target) );

        //
        // Start bang-bang-lock
        //

        // 16. Take dphy_nclk/SysClk alignment circuits out of reset and put into continuous update mode,
        FAPI_INF("set up of phase rotator controls %s", mss::c_str(i_target) );
        FAPI_TRY( mss::setup_phase_rotator_control_registers(i_target, mss::ON) );

        // 17. Wait at least 5932 dphy_nclk clock cycles to allow the dphy_nclk/SysClk alignment circuit to
        // perform initial alignment.
        FAPI_INF("Wait at least 5932 memory clock cycles for clock alignment circuit to perform initial alignment %s",
                 mss::c_str(i_target));
        FAPI_TRY( fapi2::delay(mss::cycles_to_ns(i_target, 5932), 2000) );

        // 18. Check for LOCK in DDRPHY_DP16_SYSCLK_PR_VALUE registers and DDRPHY_ADR_SYSCLK_PR_VALUE
        FAPI_INF("Checking for bang-bang lock %s ...", mss::c_str(i_target));
        FAPI_TRY( mss::check_bang_bang_lock(i_target) );

        // 19. Write 0b0 into the DDRPHY_PC_RESETS register bit 1. This write de-asserts the SYSCLK_RESET.
        FAPI_INF("deassert sysclk reset %s", mss::c_str(i_target));
        FAPI_TRY( mss::deassert_sysclk_reset(i_target), "deassert_sysclk_reset failed for %s", mss::c_str(i_target) );

        // 20. Write 8020h into the DDRPHY_ADR_SYSCLK_CNTL_PR Registers and
        // DDRPHY_DP16_SYSCLK_PR0/1 registers This write takes the dphy_nclk/
        // SysClk alignment circuit out of the Continuous Update mode.
        FAPI_INF("take sysclk alignment out of cont update mode %s", mss::c_str(i_target));
        FAPI_TRY( mss::setup_phase_rotator_control_registers(i_target, mss::OFF),
                  "set up of phase rotator controls failed (out of cont update) %s", mss::c_str(i_target) );

        // 21. Wait at least 32 dphy_nclk clock cycles.
        FAPI_DBG("Wait at least 32 memory clock cycles %s", mss::c_str(i_target));
        FAPI_TRY( fapi2::delay(mss::cycles_to_ns(i_target, 32), mss::cycles_to_simcycles(32)) );

        //
        // Done bang-bang-lock
        //

        // Per J. Bialas, force_mclk_low can be dasserted.
        FAPI_TRY(mss::change_force_mclk_low(i_target, mss::HIGH),
                 "force_mclk_low (set low) Failed rc = 0x%08X", uint64_t(fapi2::current_err) );

        // Workarounds
        FAPI_TRY( mss::workarounds::dp16::after_phy_reset(i_target) );

        // Unmask the FIR we want unmasked after phy reset is complete. Note this is the "good path."
        // The algorithm is 'good path do after_phy_reset, all paths (error or not) perform the checks
        // which are defined in during_phy_reset'. We won't run after_phy_reset (unmask of FIR) unless
        // we're done with a success.
        FAPI_TRY( mss::unmask::after_phy_reset(i_target) );

    fapi_try_exit:

        // mss::check::during_phy_reset handles the error/no error case internally. All we need to do is
        // return the ReturnCode it hands us - it's taken care of commiting anything it needed to.
        return mss::check::during_phy_reset(i_target);

    }

}
<commit_msg>Reflow ddr phy FIR checking/unmasking to not unmask if FIR are set<commit_after>/* IBM_PROLOG_BEGIN_TAG                                                   */
/* This is an automatically generated prolog.                             */
/*                                                                        */
/* $Source: src/import/chips/p9/procedures/hwp/memory/p9_mss_ddr_phy_reset.C $ */
/*                                                                        */
/* OpenPOWER HostBoot Project                                             */
/*                                                                        */
/* Contributors Listed Below - COPYRIGHT 2015,2019                        */
/* [+] International Business Machines Corp.                              */
/*                                                                        */
/*                                                                        */
/* Licensed under the Apache License, Version 2.0 (the "License");        */
/* you may not use this file except in compliance with the License.       */
/* You may obtain a copy of the License at                                */
/*                                                                        */
/*     http://www.apache.org/licenses/LICENSE-2.0                         */
/*                                                                        */
/* Unless required by applicable law or agreed to in writing, software    */
/* distributed under the License is distributed on an "AS IS" BASIS,      */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or        */
/* implied. See the License for the specific language governing           */
/* permissions and limitations under the License.                         */
/*                                                                        */
/* IBM_PROLOG_END_TAG                                                     */

///
/// @file p9_mss_ddr_phy_reset.C
/// @brief Reset the DDR PHY
///
// *HWP HWP Owner: Brian Silver <bsilver@us.ibm.com>
// *HWP HWP Backup: Andre Marin <aamarin@us.ibm.com>
// *HWP Team: Memory
// *HWP Level: 2
// *HWP Consumed by: FSP:HB

#include <stdint.h>
#include <string.h>

#include <fapi2.H>
#include <mss.H>

#include <p9_mss_ddr_phy_reset.H>
#include <lib/utils/count_dimm.H>
#include <lib/phy/adr32s.H>
#include <lib/workarounds/dp16_workarounds.H>
#include <lib/fir/check.H>
#include <lib/fir/unmask.H>

using fapi2::TARGET_TYPE_MCBIST;

extern "C"
{

///
/// @brief Perform a phy reset on all the PHY related to this half-chip (mcbist)
/// @param[in] the mcbist representing the PHY
/// @return FAPI2_RC_SUCCESS iff OK
///
    fapi2::ReturnCode p9_mss_ddr_phy_reset(const fapi2::Target<fapi2::TARGET_TYPE_MCBIST>& i_target)
    {

        // If there are no DIMM we don't need to bother. In fact, we can't as we didn't setup
        // attributes for the PHY, etc.
        if (mss::count_dimm(i_target) == 0)
        {
            FAPI_INF("... skipping ddr_phy_reset %s - no DIMM ...", mss::c_str(i_target));
            return fapi2::FAPI2_RC_SUCCESS;
        }

        FAPI_TRY(mss::change_force_mclk_low(i_target, mss::LOW),
                 "force_mclk_low (set high) Failed rc = 0x%08X", uint64_t(fapi2::current_err) );

        // New for Nimbus - perform duty cycle clock distortion calibration
#ifdef RUN_DCD
        FAPI_TRY( mss::adr32s::duty_cycle_distortion_calibration(i_target) );
#endif

        // 1. Drive all control signals to the PHY to their inactive state, idle state, or inactive value.
        FAPI_TRY( mss::dp16::reset_sysclk(i_target) );

        //    (Note: The chip should already be in this state.)
        FAPI_DBG("All control signals to the PHYs should be set to their inactive state, idle state, or inactive values");

        // 2. Assert reset to PHY for 32 memory clocks
        FAPI_TRY( mss::change_resetn(i_target, mss::HIGH), "change_resetn for %s failed", mss::c_str(i_target) );
        fapi2::delay(mss::cycles_to_ns(i_target, 32), mss::cycles_to_simcycles(32));

        // 3. Deassert reset_n
        FAPI_TRY( mss::change_resetn(i_target, mss::LOW), "change_resetn for %s failed", mss::c_str(i_target) );

        //
        // Flush output drivers
        //

        // 8. Set FLUSH=1 and INIT_IO=1 in the DDRPHY_ADR_OUTPUT_FORCE_ATEST_CNTL and DDRPHY_DP16_DATA_BIT_DIR1 register
        // 9. Wait at least 32 dphy_gckn clock cycles.
        // 10. Set FLUSH=0 and INIT_IO=0 in the DDRPHY_ADR_OUTPUT_FORCE_ATEST_CNTL register
        FAPI_TRY( mss::flush_output_drivers(i_target), "unable to flush output drivers for %s", mss::c_str(i_target) );

        //
        // ZCTL Enable
        //

        // 11. Assert the ZCNTL enable to the internal impedance controller in DDRPHY_PC_RESETS register
        // 12. Wait at least 1024 dphy_gckn cycles
        // 13. Deassert the ZCNTL impedance controller enable, Check for DONE in DDRPHY_PC_DLL_ZCAL
        FAPI_TRY( mss::enable_zctl(i_target), "enable_zctl for %s failed", mss::c_str(i_target) );

        //
        // DLL calibration
        //

        // 14. Begin DLL calibrations by setting INIT_RXDLL_CAL_RESET=0 in the DDRPHY_DP16_DLL_CNTL{0:1} registers
        // and DDRPHY_ADR_DLL_CNTL registers
        // 15. Monitor the DDRPHY_PC_DLL_ZCAL_CAL_STATUS register to determine when calibration is
        // complete. One of the 3 bits will be asserted for ADR and DP16.
        FAPI_INF( "starting DLL calibration %s", mss::c_str(i_target) );
        FAPI_TRY( mss::dll_calibration(i_target) );

        //
        // Start bang-bang-lock
        //

        // 16. Take dphy_nclk/SysClk alignment circuits out of reset and put into continuous update mode,
        FAPI_INF("set up of phase rotator controls %s", mss::c_str(i_target) );
        FAPI_TRY( mss::setup_phase_rotator_control_registers(i_target, mss::ON) );

        // 17. Wait at least 5932 dphy_nclk clock cycles to allow the dphy_nclk/SysClk alignment circuit to
        // perform initial alignment.
        FAPI_INF("Wait at least 5932 memory clock cycles for clock alignment circuit to perform initial alignment %s",
                 mss::c_str(i_target));
        FAPI_TRY( fapi2::delay(mss::cycles_to_ns(i_target, 5932), 2000) );

        // 18. Check for LOCK in DDRPHY_DP16_SYSCLK_PR_VALUE registers and DDRPHY_ADR_SYSCLK_PR_VALUE
        FAPI_INF("Checking for bang-bang lock %s ...", mss::c_str(i_target));
        FAPI_TRY( mss::check_bang_bang_lock(i_target) );

        // 19. Write 0b0 into the DDRPHY_PC_RESETS register bit 1. This write de-asserts the SYSCLK_RESET.
        FAPI_INF("deassert sysclk reset %s", mss::c_str(i_target));
        FAPI_TRY( mss::deassert_sysclk_reset(i_target), "deassert_sysclk_reset failed for %s", mss::c_str(i_target) );

        // 20. Write 8020h into the DDRPHY_ADR_SYSCLK_CNTL_PR Registers and
        // DDRPHY_DP16_SYSCLK_PR0/1 registers This write takes the dphy_nclk/
        // SysClk alignment circuit out of the Continuous Update mode.
        FAPI_INF("take sysclk alignment out of cont update mode %s", mss::c_str(i_target));
        FAPI_TRY( mss::setup_phase_rotator_control_registers(i_target, mss::OFF),
                  "set up of phase rotator controls failed (out of cont update) %s", mss::c_str(i_target) );

        // 21. Wait at least 32 dphy_nclk clock cycles.
        FAPI_DBG("Wait at least 32 memory clock cycles %s", mss::c_str(i_target));
        FAPI_TRY( fapi2::delay(mss::cycles_to_ns(i_target, 32), mss::cycles_to_simcycles(32)) );

        //
        // Done bang-bang-lock
        //

        // Per J. Bialas, force_mclk_low can be dasserted.
        FAPI_TRY(mss::change_force_mclk_low(i_target, mss::HIGH),
                 "force_mclk_low (set low) Failed rc = 0x%08X", uint64_t(fapi2::current_err) );

        // Workarounds
        FAPI_TRY( mss::workarounds::dp16::after_phy_reset(i_target) );

        // mss::check::during_phy_reset checks to see if there are any FIR. We do this 'twice' once here
        // (as part of the good-path) and once if we jump to the fapi_try label.
        if ((fapi2::current_err = mss::check::during_phy_reset(i_target)) != fapi2::FAPI2_RC_SUCCESS)
        {
            goto leave_for_real;
        }

        // Unmask the FIR we want unmasked after phy reset is complete. Note this is the "good path."
        // The algorithm is 'good path do after_phy_reset, all paths (error or not) perform the checks
        // which are defined in during_phy_reset'. We won't run after_phy_reset (unmask of FIR) unless
        // we're done with a success.
        FAPI_TRY( mss::unmask::after_phy_reset(i_target) );

        // Leave as we're all good and checked the FIR already ...
        return fapi2::current_err;

        // ... here on a bad-path, check FIR and leave ...
    fapi_try_exit:

        // mss::check::during_phy_reset handles the error/no error case internally. All we need to do is
        // return the ReturnCode it hands us - it's taken care of commiting anything it needed to.
        return mss::check::during_phy_reset(i_target);

        // ... here if the good-path FIR check found an error. We jumped over the unmasking and are
        // returning an error to the caller.
    leave_for_real:
        return fapi2::current_err;

    }

}
<|endoftext|>


<commit_before>#include <Сomplex_t.hpp>
#include <catch.hpp>
SCENARIO("def constructor")
{
	complex_t Complex;
	REQUIRE(Complex.a_() == 0);
	REQUIRE(Complex.b_() == 0);
}

SCENARIO("param constructor")
{
	complex_t Complex(1, 2);
	REQUIRE(Complex.a_() == 1);
	REQUIRE(Complex.b_() == 2);
}

SCENARIO("copy constructor")
{
	complex_t Complex(1, 2);
	complex_t cop(Complex);
	REQUIRE(cop.a_() == 1);
	REQUIRE(cop.b_() == 2);
}

SCENARIO("operator *")
{
	complex_t c1(3, 2);
	complex_t c2(5, 4);
	complex_t c3(15, 8);
	REQUIRE((c1*c2) == c3);
}

SCENARIO("operator /")
{
	complex_t c1(4, 5);
	complex_t c2(4, 5);
	complex_t c3(1, 0);
	REQUIRE((c1 / c2) == c3);
}

SCENARIO("operator +=")
{
	complex_t c1(11, 1);
	complex_t c2(8, 3);
	complex_t c3(19, 4);
	REQUIRE((c1 += c2) == c3);
}

SCENARIO("operator -=")
{
	complex_t c1(6, 10);
	complex_t c2(3, 6);
	complex_t c3(3, 4);
	REQUIRE((c1 -= c2) == c3);
}

SCENARIO("operator *=")
{
	complex_t c1(7, 6);
	complex_t c2(5, 4);
	complex_t c3(11, 58);
	REQUIRE((c1 *= c2) == c3);
}

SCENARIO("operator /=")
{
	complex_t c1(2, 1);
	complex_t c2(2, 1);
	complex_t c3(1, 0);
	REQUIRE((c1 /= c2) == c3);
}

SCENARIO("operator =")
{
	complex_t c1(5, 7);
	complex_t c2 = c1;
	REQUIRE(c2 == c1);
}

SCENARIO("operator ==")
{
	complex_t c1(2, 5);
	complex_t c2(2, 5);
	REQUIRE(c1 == c2);
}
<commit_msg>Update init.cpp<commit_after>#include <сomplex_t.hpp>
#include <catch.hpp>
SCENARIO("def constructor")
{
	complex_t Complex;
	REQUIRE(Complex.a_() == 0);
	REQUIRE(Complex.b_() == 0);
}

SCENARIO("param constructor")
{
	complex_t Complex(1, 2);
	REQUIRE(Complex.a_() == 1);
	REQUIRE(Complex.b_() == 2);
}

SCENARIO("copy constructor")
{
	complex_t Complex(1, 2);
	complex_t cop(Complex);
	REQUIRE(cop.a_() == 1);
	REQUIRE(cop.b_() == 2);
}

SCENARIO("operator *")
{
	complex_t c1(3, 2);
	complex_t c2(5, 4);
	complex_t c3(15, 8);
	REQUIRE((c1*c2) == c3);
}

SCENARIO("operator /")
{
	complex_t c1(4, 5);
	complex_t c2(4, 5);
	complex_t c3(1, 0);
	REQUIRE((c1 / c2) == c3);
}

SCENARIO("operator +=")
{
	complex_t c1(11, 1);
	complex_t c2(8, 3);
	complex_t c3(19, 4);
	REQUIRE((c1 += c2) == c3);
}

SCENARIO("operator -=")
{
	complex_t c1(6, 10);
	complex_t c2(3, 6);
	complex_t c3(3, 4);
	REQUIRE((c1 -= c2) == c3);
}

SCENARIO("operator *=")
{
	complex_t c1(7, 6);
	complex_t c2(5, 4);
	complex_t c3(11, 58);
	REQUIRE((c1 *= c2) == c3);
}

SCENARIO("operator /=")
{
	complex_t c1(2, 1);
	complex_t c2(2, 1);
	complex_t c3(1, 0);
	REQUIRE((c1 /= c2) == c3);
}

SCENARIO("operator =")
{
	complex_t c1(5, 7);
	complex_t c2 = c1;
	REQUIRE(c2 == c1);
}

SCENARIO("operator ==")
{
	complex_t c1(2, 5);
	complex_t c2(2, 5);
	REQUIRE(c1 == c2);
}
<|endoftext|>


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

  Program:   ORFEO Toolbox
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

  Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.
  See OTBCopyright.txt for details.

  This software is distributed WITHOUT ANY WARRANTY; without even
  the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
  PURPOSE.  See the above copyright notices for more information.

=========================================================================*/

#include "otbVectorDataDSValidation.h"

#include "otbVectorDataToDSValidatedVectorDataFilter.h"

#include "otbVectorData.h"
#include "otbVectorDataFileReader.h"
#include "otbVectorDataFileWriter.h"
#include "otbFuzzyDescriptorsModelManager.h"

namespace otb
{
int VectorDataDSValidation::Describe(ApplicationDescriptor* descriptor)
{
  descriptor->SetName("Vector data validation");
  descriptor->SetDescription("Vector data validation using Classifier fusion.");
  descriptor->AddOption("InputShapeFileName", "Input Shape file name",
                        "in", 1, true, ApplicationDescriptor::FileName);
  descriptor->AddOption("OutputShapeFileName", "Output Shape file name",
                        "out", 1, true, ApplicationDescriptor::FileName);

  descriptor->AddOption("DescriptorsModelFileName", "Fuzzy descriptors model xml file",
                        "descMod", 1, true, ApplicationDescriptor::FileName);
  descriptor->AddOptionNParams("BeliefSupport", "Dempster Shafer study hypothesis to compute Belief",
                               "BelSup", true, ApplicationDescriptor::StringList);
  descriptor->AddOptionNParams("PlausibilitySupport", "Dempster Shafer study hypothesis to compute Plausibility",
                               "PlaSup", true, ApplicationDescriptor::StringList);

  descriptor->AddOption("CriterionFormula", "Criterion formula expression (default: ((Belief + Plausibility)/2) >= 0.5)",
                        "Cri", 1, false, ApplicationDescriptor::String);
  descriptor->AddOption("CriterionThreshold", "Criterion threshold (by default 0.5)",
                        "thd", 1, false, ApplicationDescriptor::Real);
  return EXIT_SUCCESS;
}

int VectorDataDSValidation::Execute(otb::ApplicationOptionsResult* parseResult)
{
  typedef float                           PrecisionType;
  typedef otb::VectorData<PrecisionType>  VectorDataType;
  typedef otb::VectorDataFileReader<VectorDataType>
                                          VectorDataReaderType;
  typedef otb::VectorDataFileWriter<VectorDataType>
                                          VectorDataWriterType;

  typedef otb::VectorDataToDSValidatedVectorDataFilter<VectorDataType, PrecisionType>
                                          VectorDataValidationFilterType;
  typedef VectorDataValidationFilterType::LabelSetType
                                          LabelSetType;

  typedef FuzzyDescriptorsModelManager::DescriptorsModelType DescriptorsModelType;

  // Read the vector data
  VectorDataReaderType::Pointer vdReader = VectorDataReaderType::New();
  vdReader->SetFileName(parseResult->GetParameterString("InputShapeFileName"));
  vdReader->Update();

  // Load the descriptors model
  std::string descModFile = parseResult->GetParameterString("DescriptorsModelFileName");
  DescriptorsModelType descMod = FuzzyDescriptorsModelManager::Read( descModFile.c_str() );

  // Load the hypothesis
  LabelSetType Bhyp, Phyp;
  unsigned int nbSet = parseResult->GetNumberOfParameters("BeliefSupport");
  for (unsigned int i = 0; i < nbSet; i++)
    {
    Bhyp.insert(parseResult->GetParameterString("BeliefSupport", i));
    }
  nbSet = parseResult->GetNumberOfParameters("PlausibilitySupport");
  for (unsigned int i = 0; i < nbSet; i++)
    {
    Phyp.insert(parseResult->GetParameterString("PlausibilitySupport", i));
    }

  // Process
  VectorDataValidationFilterType::Pointer filter = VectorDataValidationFilterType::New();
  filter->SetInput(vdReader->GetOutput());
  filter->SetDescriptorModels(descMod);
  filter->SetBeliefHypothesis(Bhyp);
  filter->SetPlausibilityHypothesis(Phyp);
  if (parseResult->IsOptionPresent("CriterionFormula"))
    {
    filter->SetCriterionFormula(parseResult->GetParameterString("CriterionFormula"));
    }
  if (parseResult->IsOptionPresent("CriterionThreshold"))
    {
    filter->SetCriterionThreshold(parseResult->GetParameterDouble("CriterionThreshold"));
    }

  // Write the output
  VectorDataWriterType::Pointer vdWriter = VectorDataWriterType::New();
  vdWriter->SetFileName(parseResult->GetParameterString("OutputShapeFileName"));
  vdWriter->SetInput(filter->GetOutput());
  vdWriter->Update();

  return EXIT_SUCCESS;
}
}
<commit_msg>DOC:improve documentation of cartographic db validation framework applications<commit_after>/*=========================================================================

  Program:   ORFEO Toolbox
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

  Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.
  See OTBCopyright.txt for details.

  This software is distributed WITHOUT ANY WARRANTY; without even
  the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
  PURPOSE.  See the above copyright notices for more information.

=========================================================================*/

#include "otbVectorDataDSValidation.h"

#include "otbVectorDataToDSValidatedVectorDataFilter.h"

#include "otbVectorData.h"
#include "otbVectorDataFileReader.h"
#include "otbVectorDataFileWriter.h"
#include "otbFuzzyDescriptorsModelManager.h"

namespace otb
{
int VectorDataDSValidation::Describe(ApplicationDescriptor* descriptor)
{
  descriptor->SetName("Vector data validation");
  descriptor->SetDescription("Vector data validation based on the fusion of features in teh framework of Dempster-Shafer evidence theory.");
  descriptor->AddOption("InputShapeFileName", "Input vector data for validation",
                        "in", 1, true, ApplicationDescriptor::FileName);
  descriptor->AddOption("OutputShapeFileName", "Output validated vector data",
                        "out", 1, true, ApplicationDescriptor::FileName);

  descriptor->AddOption("DescriptorsModelFileName", "Fuzzy descriptors model(xml file)",
                        "descMod", 1, true, ApplicationDescriptor::FileName);
  descriptor->AddOptionNParams("BeliefSupport", "Dempster Shafer study hypothesis to compute belief",
                               "BelSup", true, ApplicationDescriptor::StringList);
  descriptor->AddOptionNParams("PlausibilitySupport", "Dempster Shafer study hypothesis to compute plausibility",
                               "PlaSup", true, ApplicationDescriptor::StringList);

  descriptor->AddOption("CriterionFormula", "Criterion formula expression (default: ((belief + plausibility)/2) >= 0.5)",
                        "Cri", 1, false, ApplicationDescriptor::String);
  descriptor->AddOption("CriterionThreshold", "Criterion threshold (default 0.5)",
                        "thd", 1, false, ApplicationDescriptor::Real);
  return EXIT_SUCCESS;
}

int VectorDataDSValidation::Execute(otb::ApplicationOptionsResult* parseResult)
{
  typedef float                           PrecisionType;
  typedef otb::VectorData<PrecisionType>  VectorDataType;
  typedef otb::VectorDataFileReader<VectorDataType>
                                          VectorDataReaderType;
  typedef otb::VectorDataFileWriter<VectorDataType>
                                          VectorDataWriterType;

  typedef otb::VectorDataToDSValidatedVectorDataFilter<VectorDataType, PrecisionType>
                                          VectorDataValidationFilterType;
  typedef VectorDataValidationFilterType::LabelSetType
                                          LabelSetType;

  typedef FuzzyDescriptorsModelManager::DescriptorsModelType DescriptorsModelType;

  // Read the vector data
  VectorDataReaderType::Pointer vdReader = VectorDataReaderType::New();
  vdReader->SetFileName(parseResult->GetParameterString("InputShapeFileName"));
  vdReader->Update();

  // Load the descriptors model
  std::string descModFile = parseResult->GetParameterString("DescriptorsModelFileName");
  DescriptorsModelType descMod = FuzzyDescriptorsModelManager::Read( descModFile.c_str() );

  // Load the hypothesis
  LabelSetType Bhyp, Phyp;
  unsigned int nbSet = parseResult->GetNumberOfParameters("BeliefSupport");
  for (unsigned int i = 0; i < nbSet; i++)
    {
    Bhyp.insert(parseResult->GetParameterString("BeliefSupport", i));
    }
  nbSet = parseResult->GetNumberOfParameters("PlausibilitySupport");
  for (unsigned int i = 0; i < nbSet; i++)
    {
    Phyp.insert(parseResult->GetParameterString("PlausibilitySupport", i));
    }

  // Process
  VectorDataValidationFilterType::Pointer filter = VectorDataValidationFilterType::New();
  filter->SetInput(vdReader->GetOutput());
  filter->SetDescriptorModels(descMod);
  filter->SetBeliefHypothesis(Bhyp);
  filter->SetPlausibilityHypothesis(Phyp);
  if (parseResult->IsOptionPresent("CriterionFormula"))
    {
    filter->SetCriterionFormula(parseResult->GetParameterString("CriterionFormula"));
    }
  if (parseResult->IsOptionPresent("CriterionThreshold"))
    {
    filter->SetCriterionThreshold(parseResult->GetParameterDouble("CriterionThreshold"));
    }

  // Write the output
  VectorDataWriterType::Pointer vdWriter = VectorDataWriterType::New();
  vdWriter->SetFileName(parseResult->GetParameterString("OutputShapeFileName"));
  vdWriter->SetInput(filter->GetOutput());
  vdWriter->Update();

  return EXIT_SUCCESS;
}
}
<|endoftext|>


<commit_before>/* Siconos-Kernel, Copyright INRIA 2005-2010.
 * Siconos is a program dedicated to modeling, simulation and control
 * of non smooth dynamical systems.
 * Siconos is a free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 * Siconos is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with Siconos; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 *
 * Contact: Vincent ACARY, siconos-team@lists.gforge.inria.fr
 */

#include "TimeStepping.hpp"

#include "TimeSteppingProjectOnConstraints.hpp"
#include "NewtonEulerDS.hpp"

using namespace std;

//#define TSPROJ_DEBUG
TimeSteppingProjectOnConstraints::TimeSteppingProjectOnConstraints(SP::TimeDiscretisation td,
    SP::OneStepIntegrator osi,
    SP::OneStepNSProblem osnspb_velo,
    SP::OneStepNSProblem osnspb_pos)
  : TimeStepping(td, osi, osnspb_velo)
{
  (*_allNSProblems).resize(SICONOS_NB_OSNSP_TSP);
  insertNonSmoothProblem(osnspb_pos, SICONOS_OSNSP_TS_POS);
}

// --- Destructor ---
TimeSteppingProjectOnConstraints::~TimeSteppingProjectOnConstraints()
{
}

void TimeSteppingProjectOnConstraints::newtonSolve(double criterion, unsigned int maxStep)
{
#ifdef TSPROJ_DEBUG
  cout << "TimeStepping::newtonSolve begin :\n";
#endif
  TimeStepping::newtonSolve(criterion, maxStep);
#ifdef TSPROJ_DEBUG
  cout << "TimeStepping::newtonSolve end :\n";
#endif

  int info = 0;
#ifdef TSPROJ_DEBUG
  cout << "TimeSteppingProjectOnConstraints::newtonSolve begin projection:\n";
#endif
  SP::InteractionsSet allInteractions = model()->nonSmoothDynamicalSystem()->interactions();
  for (InteractionsIterator it = allInteractions->begin(); it != allInteractions->end(); it++)
  {
    (*it)->relation()->computeJach(getTkp1());
    (*it)->relation()->computeh(getTkp1());
  }
  SP::DynamicalSystemsGraph dsGraph = model()->nonSmoothDynamicalSystem()->dynamicalSystems();
  for (DynamicalSystemsGraph::VIterator vi = dsGraph->begin(); vi != dsGraph->end(); ++vi)
  {
    SP::DynamicalSystem ds = dsGraph->bundle(*vi);
    Type::Siconos dsType = Type::value(*ds);
    if (dsType != Type::NewtonEulerDS)
      RuntimeException::selfThrow("TS:: - ds is not from NewtonEulerDS.");
    SP::NewtonEulerDS neds = boost::static_pointer_cast<NewtonEulerDS>(ds);
    *(neds->deltaq()) = *(neds->q());
  }
  info = computeOneStepNSProblem(SICONOS_OSNSP_TS_POS);
  //cout<<"||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||  Z:"<<endl;
  //(*_allNSProblems)[SICONOS_OSNSP_TS_POS]->display();
  //(boost::static_pointer_cast<LinearOSNS>((*_allNSProblems)[SICONOS_OSNSP_TS_POS]))->z()->display();
  if (info)
    cout << "TimeSteppingProjectOnConstraints project on constraints failed." << endl ;
  //cout<<"during projection before normalizing of q:\n";
  //for (InteractionsIterator it = allInteractions->begin(); it != allInteractions->end(); it++)
  //{
  //  (*it)->relation()->computeh(getTkp1());
  //}

  for (DynamicalSystemsGraph::VIterator vi = dsGraph->begin(); vi != dsGraph->end(); ++vi)
  {
    SP::DynamicalSystem ds = dsGraph->bundle(*vi);
    Type::Siconos dsType = Type::value(*ds);
    if (dsType != Type::NewtonEulerDS)
      RuntimeException::selfThrow("TS:: - ds is not from NewtonEulerDS.");
    SP::NewtonEulerDS neds = boost::static_pointer_cast<NewtonEulerDS>(ds);
    neds->normalizeq();
    // SP::SiconosVector dotq = neds->dotq();
    // SP::SiconosVector q = neds->q();
    // SP::SiconosVector qold = neds->qMemory()->getSiconosVector(0);
    // double h = timeStep();
    // dotq->setValue(3,(q->getValue(3)-qold->getValue(3))/h);
    // dotq->setValue(4,(q->getValue(4)-qold->getValue(4))/h);
    // dotq->setValue(5,(q->getValue(5)-qold->getValue(5))/h);
    // dotq->setValue(6,(q->getValue(6)-qold->getValue(6))/h);
    neds->updateT();

    /*compute the new velocity seeing the work of fext*/
    *(neds->deltaq()) -= *(neds->q());
    SP::SimpleVector FextNorm(new SimpleVector(3));
    FextNorm->setValue(0, neds->fExt()->getValue(0));
    FextNorm->setValue(1, neds->fExt()->getValue(1));
    FextNorm->setValue(2, neds->fExt()->getValue(2));
    double n2 = FextNorm->norm2();
    if (n2 > 1e-7)
    {
      (*FextNorm) *= (1. / n2);
      /*work of external forces.*/
      double workFext = neds->fExt()->getValue(0) * neds->deltaq()->getValue(0) +
                        neds->fExt()->getValue(1) * neds->deltaq()->getValue(1) +
                        neds->fExt()->getValue(2) * neds->deltaq()->getValue(2);
      //workFext*=2.0;
      double VkFNorm = FextNorm->getValue(0) * neds->velocity()->getValue(0) +
                       FextNorm->getValue(1) * neds->velocity()->getValue(1) +
                       FextNorm->getValue(2) * neds->velocity()->getValue(2);
      double VkcFNorm = VkFNorm;
      if (VkFNorm >= 0 && workFext > 0)
      {
        VkcFNorm = sqrt(2 * workFext / (neds->massValue()) + VkFNorm * VkFNorm);
      }
      else if (VkFNorm <= 0 && workFext < 0)
      {
        VkcFNorm = -sqrt(fabs(2 * workFext / (neds->massValue()) + VkFNorm * VkFNorm));
      }
      else if (VkFNorm > 0 && workFext < 0)
      {
        VkcFNorm = VkFNorm * VkFNorm + 2 * workFext / (neds->massValue());
        if (VkcFNorm > 0)
          VkcFNorm = sqrt(VkcFNorm);
        else
          VkcFNorm = 0;
      }
      else if (VkFNorm < 0 && workFext > 0)
      {
        VkcFNorm = VkFNorm * VkFNorm - 2 * workFext / (neds->massValue());
        if (VkcFNorm > 0)
          VkcFNorm = -sqrt(VkcFNorm);
        else
          VkcFNorm = 0;
      }
#ifdef TSPROJ_DEBUG
      cout << "TimeSteppingProjectOnConstraints::newtonSolve velocity before update\n";
      neds->velocity()->display();
#endif
      neds->velocity()->setValue(0, neds->velocity()->getValue(0) + (VkcFNorm - VkFNorm)*FextNorm->getValue(0));
      neds->velocity()->setValue(1, neds->velocity()->getValue(1) + (VkcFNorm - VkFNorm)*FextNorm->getValue(1));
      neds->velocity()->setValue(2, neds->velocity()->getValue(2) + (VkcFNorm - VkFNorm)*FextNorm->getValue(2));
#ifdef TSPROJ_DEBUG
      cout << "TimeSteppingProjectOnConstraints::newtonSolve velocity updated\n";
      neds->velocity()->display();
#endif
      SP::SiconosMatrix T = neds->T();
      SP::SiconosVector dotq = neds->dotq();
      prod(*T, *neds->velocity(), *dotq, true);
      if (!_allNSProblems->empty())
      {
        updateOutput(0, _levelMax);
      }
    }
  }
#ifdef TSPROJ_DEBUG
  cout << "TimeSteppingProjectOnConstraints::newtonSolve end projection:\n";
#endif

}
bool TimeSteppingProjectOnConstraints::predictorDeactivate(SP::UnitaryRelation ur, unsigned int i)
{
  double h = timeStep();
  double y = ur->getYRef(i - 1);
  double yDot = ur->getYRef(1);
#ifdef TSPROJ_DEBUG
  printf("TSProjectOnConstraints::predictorDeactivate yref=%e, yDot=%e\n", y, yDot);
#endif
  y += 0.5 * h * yDot;
  assert(!isnan(y));
  bool res = (y > 1e-7);
#ifdef TSPROJ_DEBUG
  if (res)
  {
    printf("TimeSteppingProjectOnConstraints::predictorDeactivate\n");
  }
#endif

  return res;
}

bool TimeSteppingProjectOnConstraints::predictorActivate(SP::UnitaryRelation ur, unsigned int i)
{
  return TimeStepping::predictorActivate(ur, i);
  double h = timeStep();
  double y = ur->getYRef(i - 1);
  double yDot = ur->getYRef(1);
#ifdef TSPROJ_DEBUG
  printf("TSProjectOnConstraints::predictorActivate yref=%e, yDot=%e\n", y, yDot);
#endif
  y += h * yDot;
  assert(!isnan(y));
#ifdef TSPROJ_DEBUG
  if (y <= 0)
  {
    printf("TimeSteppingProjectOnConstraints::predictorActivate y=%e\n", y);
  }
#endif
  //printf("TS::predictorActivate y=%e\n",y);
  return (y <= 0);
}
<commit_msg>Avoid to increase velocity during projection<commit_after>/* Siconos-Kernel, Copyright INRIA 2005-2010.
 * Siconos is a program dedicated to modeling, simulation and control
 * of non smooth dynamical systems.
 * Siconos is a free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 * Siconos is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with Siconos; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 *
 * Contact: Vincent ACARY, siconos-team@lists.gforge.inria.fr
 */

#include "TimeStepping.hpp"

#include "TimeSteppingProjectOnConstraints.hpp"
#include "NewtonEulerDS.hpp"

using namespace std;

//#define TSPROJ_DEBUG
TimeSteppingProjectOnConstraints::TimeSteppingProjectOnConstraints(SP::TimeDiscretisation td,
    SP::OneStepIntegrator osi,
    SP::OneStepNSProblem osnspb_velo,
    SP::OneStepNSProblem osnspb_pos)
  : TimeStepping(td, osi, osnspb_velo)
{
  (*_allNSProblems).resize(SICONOS_NB_OSNSP_TSP);
  insertNonSmoothProblem(osnspb_pos, SICONOS_OSNSP_TS_POS);
}

// --- Destructor ---
TimeSteppingProjectOnConstraints::~TimeSteppingProjectOnConstraints()
{
}

void TimeSteppingProjectOnConstraints::newtonSolve(double criterion, unsigned int maxStep)
{
#ifdef TSPROJ_DEBUG
  cout << "TimeStepping::newtonSolve begin :\n";
#endif
  TimeStepping::newtonSolve(criterion, maxStep);
#ifdef TSPROJ_DEBUG
  cout << "TimeStepping::newtonSolve end :\n";
#endif

  int info = 0;
#ifdef TSPROJ_DEBUG
  cout << "TimeSteppingProjectOnConstraints::newtonSolve begin projection:\n";
#endif
  SP::InteractionsSet allInteractions = model()->nonSmoothDynamicalSystem()->interactions();
  for (InteractionsIterator it = allInteractions->begin(); it != allInteractions->end(); it++)
  {
    (*it)->relation()->computeJach(getTkp1());
    (*it)->relation()->computeh(getTkp1());
  }
  SP::DynamicalSystemsGraph dsGraph = model()->nonSmoothDynamicalSystem()->dynamicalSystems();
  for (DynamicalSystemsGraph::VIterator vi = dsGraph->begin(); vi != dsGraph->end(); ++vi)
  {
    SP::DynamicalSystem ds = dsGraph->bundle(*vi);
    Type::Siconos dsType = Type::value(*ds);
    if (dsType != Type::NewtonEulerDS)
      RuntimeException::selfThrow("TS:: - ds is not from NewtonEulerDS.");
    SP::NewtonEulerDS neds = boost::static_pointer_cast<NewtonEulerDS>(ds);
    *(neds->deltaq()) = *(neds->q());
  }
  info = computeOneStepNSProblem(SICONOS_OSNSP_TS_POS);
  //cout<<"||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||  Z:"<<endl;
  //(*_allNSProblems)[SICONOS_OSNSP_TS_POS]->display();
  //(boost::static_pointer_cast<LinearOSNS>((*_allNSProblems)[SICONOS_OSNSP_TS_POS]))->z()->display();
  if (info)
    cout << "TimeSteppingProjectOnConstraints project on constraints failed." << endl ;
  //cout<<"during projection before normalizing of q:\n";
  //for (InteractionsIterator it = allInteractions->begin(); it != allInteractions->end(); it++)
  //{
  //  (*it)->relation()->computeh(getTkp1());
  //}

  for (DynamicalSystemsGraph::VIterator vi = dsGraph->begin(); vi != dsGraph->end(); ++vi)
  {
    SP::DynamicalSystem ds = dsGraph->bundle(*vi);
    Type::Siconos dsType = Type::value(*ds);
    if (dsType != Type::NewtonEulerDS)
      RuntimeException::selfThrow("TS:: - ds is not from NewtonEulerDS.");
    SP::NewtonEulerDS neds = boost::static_pointer_cast<NewtonEulerDS>(ds);
    neds->normalizeq();
    // SP::SiconosVector dotq = neds->dotq();
    // SP::SiconosVector q = neds->q();
    // SP::SiconosVector qold = neds->qMemory()->getSiconosVector(0);
    // double h = timeStep();
    // dotq->setValue(3,(q->getValue(3)-qold->getValue(3))/h);
    // dotq->setValue(4,(q->getValue(4)-qold->getValue(4))/h);
    // dotq->setValue(5,(q->getValue(5)-qold->getValue(5))/h);
    // dotq->setValue(6,(q->getValue(6)-qold->getValue(6))/h);
    neds->updateT();

    /*compute the new velocity seeing the work of fext*/
    *(neds->deltaq()) -= *(neds->q());
    SP::SimpleVector FextNorm(new SimpleVector(3));
    FextNorm->setValue(0, neds->fExt()->getValue(0));
    FextNorm->setValue(1, neds->fExt()->getValue(1));
    FextNorm->setValue(2, neds->fExt()->getValue(2));
#ifdef TSPROJ_DEBUG
    cout << "TimeSteppingProjectOnConstraints::newtonSolve deltaQ :\n";
    neds->deltaq()->display();
    cout << "TimeSteppingProjectOnConstraints::newtonSolve Fext :\n";
    FextNorm->display();
#endif
    double n2 = FextNorm->norm2();
    if (n2 > 1e-7)
    {
      (*FextNorm) *= (1. / n2);
      /*work of external forces.*/
      double workFext = neds->fExt()->getValue(0) * neds->deltaq()->getValue(0) +
                        neds->fExt()->getValue(1) * neds->deltaq()->getValue(1) +
                        neds->fExt()->getValue(2) * neds->deltaq()->getValue(2);
      //workFext*=2.0;
      double VkFNorm = FextNorm->getValue(0) * neds->velocity()->getValue(0) +
                       FextNorm->getValue(1) * neds->velocity()->getValue(1) +
                       FextNorm->getValue(2) * neds->velocity()->getValue(2);
      double VkcFNorm = VkFNorm;
      if (VkFNorm >= 0 && workFext > 0)
      {
        ;//VkcFNorm=sqrt (2*workFext/(neds->massValue())+VkFNorm*VkFNorm);
      }
      else if (VkFNorm <= 0 && workFext < 0)
      {
        ;//VkcFNorm=-sqrt (fabs(2*workFext/(neds->massValue())+VkFNorm*VkFNorm));
      }
      else if (VkFNorm > 0 && workFext < 0)
      {
        VkcFNorm = VkFNorm * VkFNorm + 2 * workFext / (neds->massValue());
        if (VkcFNorm > 0)
          VkcFNorm = sqrt(VkcFNorm);
        else
          VkcFNorm = 0;
      }
      else if (VkFNorm < 0 && workFext > 0)
      {
        VkcFNorm = VkFNorm * VkFNorm - 2 * workFext / (neds->massValue());
        if (VkcFNorm > 0)
          VkcFNorm = -sqrt(VkcFNorm);
        else
          VkcFNorm = 0;
      }
#ifdef TSPROJ_DEBUG
      cout << "TimeSteppingProjectOnConstraints::newtonSolve velocity before update\n";
      neds->velocity()->display();
#endif
      neds->velocity()->setValue(0, neds->velocity()->getValue(0) + (VkcFNorm - VkFNorm)*FextNorm->getValue(0));
      neds->velocity()->setValue(1, neds->velocity()->getValue(1) + (VkcFNorm - VkFNorm)*FextNorm->getValue(1));
      neds->velocity()->setValue(2, neds->velocity()->getValue(2) + (VkcFNorm - VkFNorm)*FextNorm->getValue(2));
#ifdef TSPROJ_DEBUG
      cout << "TimeSteppingProjectOnConstraints::newtonSolve velocity updated\n";
      neds->velocity()->display();
#endif
      SP::SiconosMatrix T = neds->T();
      SP::SiconosVector dotq = neds->dotq();
      prod(*T, *neds->velocity(), *dotq, true);
      if (!_allNSProblems->empty())
      {
        updateOutput(0, _levelMax);
      }
    }
  }
#ifdef TSPROJ_DEBUG
  cout << "TimeSteppingProjectOnConstraints::newtonSolve end projection:\n";
#endif

}
bool TimeSteppingProjectOnConstraints::predictorDeactivate(SP::UnitaryRelation ur, unsigned int i)
{
  double h = timeStep();
  double y = ur->getYRef(i - 1);
  double yDot = ur->getYRef(1);
#ifdef TSPROJ_DEBUG
  printf("TSProjectOnConstraints::predictorDeactivate yref=%e, yDot=%e\n", y, yDot);
#endif
  y += 0.5 * h * yDot;
  assert(!isnan(y));
  bool res = (y > 1e-7);
#ifdef TSPROJ_DEBUG
  if (res)
  {
    printf("TimeSteppingProjectOnConstraints::predictorDeactivate\n");
  }
#endif

  return res;
}

bool TimeSteppingProjectOnConstraints::predictorActivate(SP::UnitaryRelation ur, unsigned int i)
{
  return TimeStepping::predictorActivate(ur, i);
  double h = timeStep();
  double y = ur->getYRef(i - 1);
  double yDot = ur->getYRef(1);
#ifdef TSPROJ_DEBUG
  printf("TSProjectOnConstraints::predictorActivate yref=%e, yDot=%e\n", y, yDot);
#endif
  y += h * yDot;
  assert(!isnan(y));
#ifdef TSPROJ_DEBUG
  if (y <= 0)
  {
    printf("TimeSteppingProjectOnConstraints::predictorActivate y=%e\n", y);
  }
#endif
  //printf("TS::predictorActivate y=%e\n",y);
  return (y <= 0);
}
<|endoftext|>


<commit_before>#include <BST.hpp>
#include <catch.hpp>
#include <fstream>
//#include "File1.txt"

SCENARIO ("init", "[init]")

{

  BST<int> test;

  REQUIRE(test.getroot() == nullptr);
  REQUIRE(test.getcount() == 0);

}

SCENARIO("insert", "[init]")

{

  BST<int> test;

  test.add(10);

  REQUIRE(test.search(10, test.getroot()) != 0);

}

SCENARIO("find_node", "[init]")

{

  BST<int> test;

  test.add(10);

  REQUIRE(test.search(10, test.getroot()) != 0);

  REQUIRE(test.search(10, test.getroot()) != 0);

}

SCENARIO("get root", "[init]")

{

  BST<int> test;

  test.add(10);

  REQUIRE(test.getcount() == 1);

  REQUIRE(test.getroot() != 0);

}

SCENARIO ("test1", "[init]")
{
	BST<int> test;
	test.input("File1.txt");
	REQUIRE(test.getcount() == 3);

}

/*

SCENARIO("del", "[init]")

{

  BST<int> test;

  test.add(1);

  test.add(2);

  test.add(3);

  test.del(test.getroot(), 1);

  test.del(test.getroot(), 2);

  REQUIRE(test.search(1, test.getroot()) != 0);
  REQUIRE(test.search(2, test.getroot()) == 0);

  REQUIRE(test.search(3, test.getroot())!= 0);

}

*/

<commit_msg>Create init.cpp<commit_after>#include <BST.hpp>
#include <catch.hpp>
#include <fstream>
#include "File1.txt"

SCENARIO ("init", "[init]")

{

  BST<int> test;

  REQUIRE(test.getroot() == nullptr);
  REQUIRE(test.getcount() == 0);

}

SCENARIO("insert", "[init]")

{

  BST<int> test;

  test.add(10);

  REQUIRE(test.search(10, test.getroot()) != 0);

}

SCENARIO("find_node", "[init]")

{

  BST<int> test;

  test.add(10);

  REQUIRE(test.search(10, test.getroot()) != 0);

  REQUIRE(test.search(10, test.getroot()) != 0);

}

SCENARIO("get root", "[init]")

{

  BST<int> test;

  test.add(10);

  REQUIRE(test.getcount() == 1);

  REQUIRE(test.getroot() != 0);

}

SCENARIO ("test1", "[init]")
{
	BST<int> test;
	test.input("File1.txt");
	REQUIRE(test.getcount() == 3);

}

/*

SCENARIO("del", "[init]")

{

  BST<int> test;

  test.add(1);

  test.add(2);

  test.add(3);

  test.del(test.getroot(), 1);

  test.del(test.getroot(), 2);

  REQUIRE(test.search(1, test.getroot()) != 0);
  REQUIRE(test.search(2, test.getroot()) == 0);

  REQUIRE(test.search(3, test.getroot())!= 0);

}

*/

<|endoftext|>


<commit_before>#include <tree.h>
#include <catch.hpp>

SCENARIO ("init", "[init]")

{

  Tree<int> test;

  REQUIRE(test.root_() == nullptr);

  REQUIRE(test.get_count() == 0);

}

SCENARIO("insert", "[init]")

{

  Tree<int> test;

  test.insnode(5);

  REQUIRE(test.get_count() == 1);

  REQUIRE(test.find_node(5, test.root_())->key == 5);

}

SCENARIO("find_node", "[init]")

{

  Tree<int> test;

  test.insnode(4);

  REQUIRE(test.find_node(4, test.root_()) != nullptr);

  REQUIRE(test.find_node(4, test.root_())->key == 4);

}

SCENARIO("get root", "[init]")

{

  Tree<int> test;

  test.insnode(4);

  REQUIRE(test.root_() != 0);

}

SCENARIO("insert equal elements", "[insert]")

 {

   Tree<int> test;

   test.insnode(4);

   test.insnode(4);

   REQUIRE(test.get_count() == 1);

 }

SCENARIO ("read/write", "[init]")

{

  Tree<int> test1;

  test1.write("file2.txt");
  bool isCatched = false;

  try
    {
    test1.write("~,  , *");

    catch(isCatched)
     {
      isCatched = true;
    }
    REQUIRE(isCatched == false);

  Tree<int> test2;

  test2.read("file2.txt");

  REQUIRE(test2.find_node(4, test2.root_())!= nullptr);

  REQUIRE(test2.find_node(3, test2.root_())!= nullptr);

  REQUIRE(test1.get_count() == test2.get_count());

}

SCENARIO("deleteX")

{

  Tree<int> test;

  test.insnode(6);

  test.insnode(7);

  test.insnode(9);

  test.deleteVal(6);

  test.deleteVal(9);

  REQUIRE(test.find_node(9, test.root_())== nullptr);

  REQUIRE(test.find_node(7, test.root_())== test.root_());

  REQUIRE(test.root_() != nullptr);

  REQUIRE(test.get_count() == 1);

}
<commit_msg>Update init.cpp<commit_after>#include <tree.h>
#include <catch.hpp>
#include <fstream.h>

SCENARIO ("init", "[init]")

{

  Tree<int> test;

  REQUIRE(test.root_() == nullptr);

  REQUIRE(test.get_count() == 0);

}

SCENARIO("insert", "[init]")

{

  Tree<int> test;

  test.insnode(5);

  REQUIRE(test.get_count() == 1);

  REQUIRE(test.find_node(5, test.root_())->key == 5);

}

SCENARIO("find_node", "[init]")

{

  Tree<int> test;

  test.insnode(4);

  REQUIRE(test.find_node(4, test.root_()) != nullptr);

  REQUIRE(test.find_node(4, test.root_())->key == 4);

}

SCENARIO("get root", "[init]")

{

  Tree<int> test;

  test.insnode(4);

  REQUIRE(test.root_() != 0);

}

SCENARIO("insert equal elements", "[insert]")

 {

   Tree<int> test;

   test.insnode(4);

   test.insnode(4);

   REQUIRE(test.get_count() == 1);

 }

SCENARIO ("read/write", "[init]")

{

  Tree<int> test1;
  try
    {
  ofstream& file1 = open("file2.txt", out);
  test1.write(file1);
  bool isCatched = false;
   // test1.write("~,  , *"); //

    catch(isCatched)
     {
      isCatched = true;
    }

  REQUIRE(isCatched == false);

  Tree<int> test2;

  test2.read("file2.txt");

  REQUIRE(test2.find_node(4, test2.root_())!= nullptr);

  REQUIRE(test2.find_node(3, test2.root_())!= nullptr);

  REQUIRE(test1.get_count() == test2.get_count());

}

SCENARIO("deleteX")

{

  Tree<int> test;

  test.insnode(6);

  test.insnode(7);

  test.insnode(9);

  test.deleteVal(6);

  test.deleteVal(9);

  REQUIRE(test.find_node(9, test.root_())== nullptr);

  REQUIRE(test.find_node(7, test.root_())== test.root_());

  REQUIRE(test.root_() != nullptr);

  REQUIRE(test.get_count() == 1);

}
<|endoftext|>


<commit_before>#include "stdafx.h"
#include "CommandHelp.h"

CommandHelp::CommandHelp()
{
}

CommandHelp::~CommandHelp()
{
}

bool CommandHelp::ShouldRunThisCommand(ParsedCommand* Parsed)
{
	string *b = Parsed->Words->at(0);
	Console->WriteLine(&to_string(Parsed->Words->size()));
	const char* a = b->c_str();
	Console->WriteLine(a);
	return (a == "help");
}

void CommandHelp::Run(ParsedCommand * Parsed)
{
	string help = "";

	size_t length = Commands->size();
	for (size_t i = 0; i < length; i++)
	{
		help = "";
		help.append(*Commands->at(i)->GetName());
		help.append(": ");
		help.append(*Commands->at(i)->GetHelp());
		Console->WriteLine(&help);
	}
}

string * CommandHelp::GetName()
{
	return new string("Help");
}

string * CommandHelp::GetHelp()
{
	return new string("Shows some help information about all known commands.");
}
<commit_msg>Failing at pointers.<commit_after>#include "stdafx.h"
#include "CommandHelp.h"

CommandHelp::CommandHelp()
{
}

CommandHelp::~CommandHelp()
{
}

bool CommandHelp::ShouldRunThisCommand(ParsedCommand* Parsed)
{
	string *b = Parsed->Words->at(0);
	Console->WriteLine(&to_string(Parsed->Words->size()));
	const char* a = b->c_str();
	Console->WriteLine(a);
	return (a == "help");
}

void CommandHelp::Run(ParsedCommand * Parsed)
{
	string help = "";
	size_t length = Commands->size();
	for (size_t i = 0; i < length; i++)
	{
		help = "";
		help.append(*Commands->at(i)->GetName());
		help.append(": ");
		help.append(*Commands->at(i)->GetHelp());
		Console->WriteLine(&help);
	}
}

string * CommandHelp::GetName()
{
	return new string("Help");
}

string * CommandHelp::GetHelp()
{
	return new string("Shows some help information about all known commands.");
}
<|endoftext|>


<commit_before>#include <iostream>
#include <vector>
#include <array>
#include <valarray>

#include "gal.hpp"

#include "test_construction.hpp"
#include "test_construction_from_std.hpp"
#include "test_arithmetic.hpp"

#include "test_geometry.hpp"

/*
* Lgg till transpose-funktion.

* sliced_array, med stride, lgg till. Finns det nn kort bokstav fr det?
  Vill man bara ha strided fr pointer arrays? Kan heta spsarray och spdarray.

Frgor
* copy-construction frn samma typ. Hanteras det av de templatiserade konstruktrerna?
* Single-dimensional construction from:
  - Eigen::Matrix

* Implicit konvertering? Fr gande arrayer: Nej. Fr pekare ?

* Hur ska nullptr hanteras? Ska man krva att size()==0 d?

* make_pdarray({1,2,4}, data); // S man slipper redundanta template argument.
  make_darray({1,2}, 0.f);
  make_sarray({1, 2}, 1.f);

* Hur ska multiplikation och division hanteras? Vill kunna hantera fallen:
  - Elementvis
  - Matriser
  - Komplexa tal
  - Kvaternioner
  - Expression templates
* Ha mnga elementvisa operationer i annan modul: * / % < <= > >= && ! ||.
* implementera som allmnna funktioner: add, subtract, multiply, divide.

* storage order fr matriser.
- Skulle kunna ha allmn default-templatiserad flagga i class-signature.
-  Eller kan lta den bara pverka operator() !.
D kan man stta den typ:
using matrix23f = sarray<float,2,3,ROW_MAJOR>
- Skapa matris-klass som rver frn sarray? Vore ju bttre om man inte behvde rva frn den.
- Skapa tv fria funktioner fr operator(), som kan vlja mellan att plocka ut i row-major eller column major.
at_cm(matrix, 3, 2)
at_rm(matrix, 2, 3)
at_cm<3,2>(matrix)
at_rm<2,3>(matrix)

* Hur ska konstruktorerna vara fr att dom ska vara konsekventa fr alla arrayer?
  - typ, dimension, storlek, vrden.

auto a = sarray<int, 2, 3>(1, 2, 3, 4, 5, 6);   // <- funkar nog inte det bra fr matriser i den column/row-order som vi har?
auto a = sarray<int, 2, 3>({1, 2, 3, 4, 5, 6}); // <-
auto a = sarray<int, 2, 3>({{1, 2, 3}, {4, 5, 6}}); // <-
auto a = sarray<int, 2, 3>(data_iterator);
auto a = sarray<int, 2, 3>(data_value);
auto a = sarray<int, 2, 3>(data_array);

auto a = darray<int, 2>({2, 3}, data_iterator); // Tillt iterator istllet fr pekare?
auto a = darray<int, 2>({2, 3}, data_value);
auto a = darray<int, 2>({2, 3});
auto a = darray<int, 2>(data_array);

auto a = pdarray<int, 2>({2, 3}, data_iterator);
auto a = pdarray<int, 2>(data_array);

auto a = psarray<int, 2, 3>(data_iterator);
auto a = psarray<int, 2, 3>(data_array);

auto a = std::array<int, 2>({1, 2})
auto a = std::vector<int>(size)
auto a = std::vector<int>(size, data_value)
auto a = std::valarray<int>(size)
auto a = std::valarray<int>(data_value, size) <- exception

assert(extents(array1) == extents(array2))
*/

void f(pdarray<int> a)
{
	for (auto& x : a)
	{
		++x;
	}
}

void h(pdarray<const int> a)
{
	using namespace std;
	for (auto& x : a)
	{
		cout << x << " ";
	}
	cout << endl;
}

void g(pdarray<int, 2> a)
{
	for (auto& x : a)
	{
		++x;
	}

	for (size_t y = 0; y < a.extent1(); ++y)
	{
		for (size_t x = 0; x < a.extent0(); ++x)
		{
			std::cout << a(x, y) << " ";
		}
		std::cout << std::endl;
	}
}

template<typename Array2d>
void fill_and_print_array2d(Array2d& array)
{
    assert(array.rank() == 2);

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

    for (auto& element : array)
    {
        element += 10;
    }

    using namespace std;

    for (int y = 0; y < array.extent1(); ++y)
    {
        for (int x = 0; x < array.extent0(); ++x)
        {
            cout << array(x, y) << " ";
        }
        cout << endl;
    }
    cout << endl;
}

int main()
{
	using namespace std;

	cout << "total_size: " << details::total_size<1, 2, 3>::value << endl;

	const auto W = size_t(4);
	const auto H = size_t(3);
	const auto N = W * H;

	auto a = vector<int>(N);
	//auto b = valarray<int>(N);
	auto c = array<int, N>();

	f(pdarray<int>(a));
	//f(b);
	f(pdarray<int>(c));

	h(pdarray<const int>(a));
	h(pdarray<const int>(c));

	g(pdarray<int, 2>({W, H}, a.data()));
	g(pdarray<int, 2>({W, H}, c.data()));

	auto d = darray<int>();
	auto e = sarray<int, 5>();
	auto M = sarray<int, 2, 3>();

	std::array<size_t, 2> sizes = {2, 3};
    auto f = darray<float, 2>({2, 3});
	auto g = f;

	begin(e);
	end(e);
	data(e);
	size(e);

	begin(f);
	end(f);
	data(f);
	size(f);

    cout << "print array" << endl;
    auto static_array2d = sarray<float, 3, 2>();
    auto dynamic_array2d = darray<int, 2>({ 8, 4 });
    fill_and_print_array2d(static_array2d);
    fill_and_print_array2d(dynamic_array2d);

	for (auto x : f)
	{
		std::ignore = x;
	}

	for (size_t y = 0; y < f.extent1(); ++y)
		for (size_t x = 0; x < f.extent0(); ++x)
			f(x, y);

    for (size_t i = 0; i < f.size(); ++i)
        f[i];

	M.size();
	M.rank();
	M.extent0();
	M.extent1();

	// Row-major order for images.
	for (size_t y = 0; y < M.extent1(); ++y)
		for (size_t x = 0; x < M.extent0(); ++x)
			M(x, y);

	// Column-major order for matrices.
	for (size_t col = 0; col < M.extent1(); ++col)
		for (size_t row = 0; row < M.extent0(); ++row)
			M(row, col);

	testVectors();
    testMatrices();
	/*
	testArithmeticStaticArrays();
	testArithmeticDynamicArrays();
	testArithmeticPointerArrays();
	testArithmeticMixedArrays();
	*/
	cout << "Press enter to quit." << endl;
	cin.get();

	//sarray<int, 3, 3, 3, 3, 6> magnus;
	//magnus.get_element(magnus, 1, 1, 1, 1, 1);
}
<commit_msg>Fix. Compiler warnings.<commit_after>#include <iostream>
#include <vector>
#include <array>
#include <valarray>

#include "gal.hpp"

#include "test_construction.hpp"
#include "test_construction_from_std.hpp"
#include "test_arithmetic.hpp"

#include "test_geometry.hpp"

/*
* Lgg till transpose-funktion.

* sliced_array, med stride, lgg till. Finns det nn kort bokstav fr det?
  Vill man bara ha strided fr pointer arrays? Kan heta spsarray och spdarray.

Frgor
* copy-construction frn samma typ. Hanteras det av de templatiserade konstruktrerna?
* Single-dimensional construction from:
  - Eigen::Matrix

* Implicit konvertering? Fr gande arrayer: Nej. Fr pekare ?

* Hur ska nullptr hanteras? Ska man krva att size()==0 d?

* make_pdarray({1,2,4}, data); // S man slipper redundanta template argument.
  make_darray({1,2}, 0.f);
  make_sarray({1, 2}, 1.f);

* Hur ska multiplikation och division hanteras? Vill kunna hantera fallen:
  - Elementvis
  - Matriser
  - Komplexa tal
  - Kvaternioner
  - Expression templates
* Ha mnga elementvisa operationer i annan modul: * / % < <= > >= && ! ||.
* implementera som allmnna funktioner: add, subtract, multiply, divide.

* storage order fr matriser.
- Skulle kunna ha allmn default-templatiserad flagga i class-signature.
-  Eller kan lta den bara pverka operator() !.
D kan man stta den typ:
using matrix23f = sarray<float,2,3,ROW_MAJOR>
- Skapa matris-klass som rver frn sarray? Vore ju bttre om man inte behvde rva frn den.
- Skapa tv fria funktioner fr operator(), som kan vlja mellan att plocka ut i row-major eller column major.
at_cm(matrix, 3, 2)
at_rm(matrix, 2, 3)
at_cm<3,2>(matrix)
at_rm<2,3>(matrix)

* Hur ska konstruktorerna vara fr att dom ska vara konsekventa fr alla arrayer?
  - typ, dimension, storlek, vrden.

auto a = sarray<int, 2, 3>(1, 2, 3, 4, 5, 6);   // <- funkar nog inte det bra fr matriser i den column/row-order som vi har?
auto a = sarray<int, 2, 3>({1, 2, 3, 4, 5, 6}); // <-
auto a = sarray<int, 2, 3>({{1, 2, 3}, {4, 5, 6}}); // <-
auto a = sarray<int, 2, 3>(data_iterator);
auto a = sarray<int, 2, 3>(data_value);
auto a = sarray<int, 2, 3>(data_array);

auto a = darray<int, 2>({2, 3}, data_iterator); // Tillt iterator istllet fr pekare?
auto a = darray<int, 2>({2, 3}, data_value);
auto a = darray<int, 2>({2, 3});
auto a = darray<int, 2>(data_array);

auto a = pdarray<int, 2>({2, 3}, data_iterator);
auto a = pdarray<int, 2>(data_array);

auto a = psarray<int, 2, 3>(data_iterator);
auto a = psarray<int, 2, 3>(data_array);

auto a = std::array<int, 2>({1, 2})
auto a = std::vector<int>(size)
auto a = std::vector<int>(size, data_value)
auto a = std::valarray<int>(size)
auto a = std::valarray<int>(data_value, size) <- exception

assert(extents(array1) == extents(array2))
*/

void f(pdarray<int> a)
{
	for (auto& x : a)
	{
		++x;
	}
}

void h(pdarray<const int> a)
{
	using namespace std;
	for (auto& x : a)
	{
		cout << x << " ";
	}
	cout << endl;
}

void g(pdarray<int, 2> a)
{
	for (auto& x : a)
	{
		++x;
	}

	for (size_t y = 0; y < a.extent1(); ++y)
	{
		for (size_t x = 0; x < a.extent0(); ++x)
		{
			std::cout << a(x, y) << " ";
		}
		std::cout << std::endl;
	}
}

template<typename Array2d>
void fill_and_print_array2d(Array2d& array)
{
    assert(array.rank() == 2);
    using value_type = typename Array2d::value_type;

    for (size_t i = 0; i < array.size(); ++i)
    {
        array[i] = static_cast<value_type>(i);
    }

    for (auto& element : array)
    {
        element += 10;
    }

    using namespace std;

    for (size_t y = 0; y < array.extent1(); ++y)
    {
        for (size_t x = 0; x < array.extent0(); ++x)
        {
            cout << array(x, y) << " ";
        }
        cout << endl;
    }
    cout << endl;
}

int main()
{
	using namespace std;

	cout << "total_size: " << details::total_size<1, 2, 3>::value << endl;

	const auto W = size_t(4);
	const auto H = size_t(3);
	const auto N = W * H;

	auto a = vector<int>(N);
	//auto b = valarray<int>(N);
	auto c = array<int, N>();

	f(pdarray<int>(a));
	//f(b);
	f(pdarray<int>(c));

	h(pdarray<const int>(a));
	h(pdarray<const int>(c));

	g(pdarray<int, 2>({W, H}, a.data()));
	g(pdarray<int, 2>({W, H}, c.data()));

	auto d = darray<int>();
	auto e = sarray<int, 5>();
	auto M = sarray<int, 2, 3>();

	std::array<size_t, 2> sizes = {2, 3};
    auto f = darray<float, 2>({2, 3});
	auto g = f;

	begin(e);
	end(e);
	data(e);
	size(e);

	begin(f);
	end(f);
	data(f);
	size(f);

    cout << "print array" << endl;
    auto static_array2d = sarray<float, 3, 2>();
    auto dynamic_array2d = darray<int, 2>({ 8, 4 });
    fill_and_print_array2d(static_array2d);
    fill_and_print_array2d(dynamic_array2d);

	for (auto x : f)
	{
		std::ignore = x;
	}

	for (size_t y = 0; y < f.extent1(); ++y)
		for (size_t x = 0; x < f.extent0(); ++x)
			f(x, y);

    for (size_t i = 0; i < f.size(); ++i)
        f[i];

	M.size();
	M.rank();
	M.extent0();
	M.extent1();

	// Row-major order for images.
	for (size_t y = 0; y < M.extent1(); ++y)
		for (size_t x = 0; x < M.extent0(); ++x)
			M(x, y);

	// Column-major order for matrices.
	for (size_t col = 0; col < M.extent1(); ++col)
		for (size_t row = 0; row < M.extent0(); ++row)
			M(row, col);

	testVectors();
    testMatrices();
	/*
	testArithmeticStaticArrays();
	testArithmeticDynamicArrays();
	testArithmeticPointerArrays();
	testArithmeticMixedArrays();
	*/
	cout << "Press enter to quit." << endl;
	cin.get();

	//sarray<int, 3, 3, 3, 3, 6> magnus;
	//magnus.get_element(magnus, 1, 1, 1, 1, 1);
}
<|endoftext|>


<commit_before>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/chromeos/dom_ui/stats_options_handler.h"

#include "base/basictypes.h"
#include "base/callback.h"
#include "base/utf_string_conversions.h"
#include "base/values.h"
#include "chrome/browser/chromeos/cros_settings_names.h"
#include "chrome/browser/chromeos/cros_settings_provider_stats.h"
#include "chrome/browser/metrics/user_metrics.h"

namespace chromeos {

StatsOptionsHandler::StatsOptionsHandler()
    : CrosOptionsPageUIHandler(new MetricsCrosSettingsProvider()) {
}

// OptionsUIHandler implementation.
void StatsOptionsHandler::GetLocalizedValues(
    DictionaryValue* localized_strings) {
}
void StatsOptionsHandler::Initialize() {
  SetupMetricsReportingCheckbox(false);
}

// DOMMessageHandler implementation.
void StatsOptionsHandler::RegisterMessages() {
  dom_ui_->RegisterMessageCallback(
      "metricsReportingCheckboxAction",
      NewCallback(this, &StatsOptionsHandler::HandleMetricsReportingCheckbox));
}

MetricsCrosSettingsProvider* StatsOptionsHandler::provider() const {
  return static_cast<MetricsCrosSettingsProvider*>(settings_provider_.get());
}

void StatsOptionsHandler::HandleMetricsReportingCheckbox(
    const ListValue* args) {
#if defined(GOOGLE_CHROME_BUILD)
  const std::string checked_str = WideToUTF8(ExtractStringValue(args));
  const bool enabled = (checked_str == "true");
  UserMetricsRecordAction(
      enabled ?
      UserMetricsAction("Options_MetricsReportingCheckbox_Enable") :
      UserMetricsAction("Options_MetricsReportingCheckbox_Disable"));
  const bool is_enabled = GetCurrentStatus();
  SetupMetricsReportingCheckbox(enabled == is_enabled);
#endif
}

void StatsOptionsHandler::SetupMetricsReportingCheckbox(bool user_changed) {
#if defined(GOOGLE_CHROME_BUILD)
  FundamentalValue checked(GetCurrentStatus());
  FundamentalValue disabled(false);
  FundamentalValue user_has_changed(user_changed);
  dom_ui_->CallJavascriptFunction(
      L"options.AdvancedOptions.SetMetricsReportingCheckboxState", checked,
      disabled, user_has_changed);
#endif
}

}  // namespace chromeos
<commit_msg>Fix build break on Official ChromeOS builder caused by r61684. TBR=glotov<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/chromeos/dom_ui/stats_options_handler.h"

#include "base/basictypes.h"
#include "base/callback.h"
#include "base/utf_string_conversions.h"
#include "base/values.h"
#include "chrome/browser/chromeos/cros_settings_names.h"
#include "chrome/browser/chromeos/cros_settings_provider_stats.h"
#include "chrome/browser/metrics/user_metrics.h"

namespace chromeos {

StatsOptionsHandler::StatsOptionsHandler()
    : CrosOptionsPageUIHandler(new MetricsCrosSettingsProvider()) {
}

// OptionsUIHandler implementation.
void StatsOptionsHandler::GetLocalizedValues(
    DictionaryValue* localized_strings) {
}
void StatsOptionsHandler::Initialize() {
  SetupMetricsReportingCheckbox(false);
}

// DOMMessageHandler implementation.
void StatsOptionsHandler::RegisterMessages() {
  dom_ui_->RegisterMessageCallback(
      "metricsReportingCheckboxAction",
      NewCallback(this, &StatsOptionsHandler::HandleMetricsReportingCheckbox));
}

MetricsCrosSettingsProvider* StatsOptionsHandler::provider() const {
  return static_cast<MetricsCrosSettingsProvider*>(settings_provider_.get());
}

void StatsOptionsHandler::HandleMetricsReportingCheckbox(
    const ListValue* args) {
#if defined(GOOGLE_CHROME_BUILD)
  const std::string checked_str = WideToUTF8(ExtractStringValue(args));
  const bool enabled = (checked_str == "true");
  UserMetricsRecordAction(
      enabled ?
      UserMetricsAction("Options_MetricsReportingCheckbox_Enable") :
      UserMetricsAction("Options_MetricsReportingCheckbox_Disable"));
  const bool is_enabled = MetricsCrosSettingsProvider::GetMetricsStatus();
  SetupMetricsReportingCheckbox(enabled == is_enabled);
#endif
}

void StatsOptionsHandler::SetupMetricsReportingCheckbox(bool user_changed) {
#if defined(GOOGLE_CHROME_BUILD)
  FundamentalValue checked(MetricsCrosSettingsProvider::GetMetricsStatus());
  FundamentalValue disabled(false);
  FundamentalValue user_has_changed(user_changed);
  dom_ui_->CallJavascriptFunction(
      L"options.AdvancedOptions.SetMetricsReportingCheckboxState", checked,
      disabled, user_has_changed);
#endif
}

}  // namespace chromeos
<|endoftext|>


<commit_before>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include <algorithm>

#include "base/file_util.h"
#include "base/path_service.h"
#include "base/scoped_temp_dir.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/common/extensions/extension.h"
#include "chrome/common/extensions/extension_l10n_util.h"
#include "chrome/common/extensions/extension_resource.h"
#include "chrome/common/extensions/extension_test_util.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "ui/base/l10n/l10n_util.h"

TEST(ExtensionResourceTest, CreateEmptyResource) {
  ExtensionResource resource;

  EXPECT_TRUE(resource.extension_root().empty());
  EXPECT_TRUE(resource.relative_path().empty());
  EXPECT_TRUE(resource.GetFilePath().empty());
}

const FilePath::StringType ToLower(const FilePath::StringType& in_str) {
  FilePath::StringType str(in_str);
  std::transform(str.begin(), str.end(), str.begin(), tolower);
  return str;
}

TEST(ExtensionResourceTest, CreateWithMissingResourceOnDisk) {
  FilePath root_path;
  ASSERT_TRUE(PathService::Get(chrome::DIR_TEST_DATA, &root_path));
  FilePath relative_path;
  relative_path = relative_path.AppendASCII("cira.js");
  std::string extension_id = extension_test_util::MakeId("test");
  ExtensionResource resource(extension_id, root_path, relative_path);

  // The path doesn't exist on disk, we will be returned an empty path.
  EXPECT_EQ(root_path.value(), resource.extension_root().value());
  EXPECT_EQ(relative_path.value(), resource.relative_path().value());
  EXPECT_TRUE(resource.GetFilePath().empty());
}

TEST(ExtensionResourceTest, CreateWithAllResourcesOnDisk) {
  ScopedTempDir temp;
  ASSERT_TRUE(temp.CreateUniqueTempDir());

  // Create resource in the extension root.
  const char* filename = "res.ico";
  FilePath root_resource = temp.path().AppendASCII(filename);
  std::string data = "some foo";
  ASSERT_TRUE(file_util::WriteFile(root_resource, data.c_str(), data.length()));

  // Create l10n resources (for current locale and its parents).
  FilePath l10n_path = temp.path().Append(Extension::kLocaleFolder);
  ASSERT_TRUE(file_util::CreateDirectory(l10n_path));

  std::vector<std::string> locales;
  l10n_util::GetParentLocales(l10n_util::GetApplicationLocale(""), &locales);
  ASSERT_FALSE(locales.empty());
  for (size_t i = 0; i < locales.size(); i++) {
    FilePath make_path;
    make_path = l10n_path.AppendASCII(locales[i]);
    ASSERT_TRUE(file_util::CreateDirectory(make_path));
    ASSERT_TRUE(file_util::WriteFile(make_path.AppendASCII(filename),
        data.c_str(), data.length()));
  }

  FilePath path;
  std::string extension_id = extension_test_util::MakeId("test");
  ExtensionResource resource(extension_id, temp.path(),
                             FilePath().AppendASCII(filename));
  FilePath resolved_path = resource.GetFilePath();

  FilePath expected_path;
  // Expect default path only, since fallback logic is disabled.
  // See http://crbug.com/27359.
  expected_path = root_resource;
  ASSERT_TRUE(file_util::AbsolutePath(&expected_path));

  EXPECT_EQ(ToLower(expected_path.value()), ToLower(resolved_path.value()));
  EXPECT_EQ(ToLower(temp.path().value()),
            ToLower(resource.extension_root().value()));
  EXPECT_EQ(ToLower(FilePath().AppendASCII(filename).value()),
            ToLower(resource.relative_path().value()));
}
<commit_msg>Disable flakily crashing ExtensionResourceTest.CreateWithAllResourcesOnDisk on Windows.<commit_after>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include <algorithm>

#include "base/file_util.h"
#include "base/path_service.h"
#include "base/scoped_temp_dir.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/common/extensions/extension.h"
#include "chrome/common/extensions/extension_l10n_util.h"
#include "chrome/common/extensions/extension_resource.h"
#include "chrome/common/extensions/extension_test_util.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "ui/base/l10n/l10n_util.h"

TEST(ExtensionResourceTest, CreateEmptyResource) {
  ExtensionResource resource;

  EXPECT_TRUE(resource.extension_root().empty());
  EXPECT_TRUE(resource.relative_path().empty());
  EXPECT_TRUE(resource.GetFilePath().empty());
}

const FilePath::StringType ToLower(const FilePath::StringType& in_str) {
  FilePath::StringType str(in_str);
  std::transform(str.begin(), str.end(), str.begin(), tolower);
  return str;
}

TEST(ExtensionResourceTest, CreateWithMissingResourceOnDisk) {
  FilePath root_path;
  ASSERT_TRUE(PathService::Get(chrome::DIR_TEST_DATA, &root_path));
  FilePath relative_path;
  relative_path = relative_path.AppendASCII("cira.js");
  std::string extension_id = extension_test_util::MakeId("test");
  ExtensionResource resource(extension_id, root_path, relative_path);

  // The path doesn't exist on disk, we will be returned an empty path.
  EXPECT_EQ(root_path.value(), resource.extension_root().value());
  EXPECT_EQ(relative_path.value(), resource.relative_path().value());
  EXPECT_TRUE(resource.GetFilePath().empty());
}

// crbug.com/108721. Disabled on Windows due to crashing on Vista.
#if defined(OS_WIN)
#define CreateWithAllResourcesOnDisk DISABLED_CreateWithAllResourcesOnDisk
#endif
TEST(ExtensionResourceTest, CreateWithAllResourcesOnDisk) {
  ScopedTempDir temp;
  ASSERT_TRUE(temp.CreateUniqueTempDir());

  // Create resource in the extension root.
  const char* filename = "res.ico";
  FilePath root_resource = temp.path().AppendASCII(filename);
  std::string data = "some foo";
  ASSERT_TRUE(file_util::WriteFile(root_resource, data.c_str(), data.length()));

  // Create l10n resources (for current locale and its parents).
  FilePath l10n_path = temp.path().Append(Extension::kLocaleFolder);
  ASSERT_TRUE(file_util::CreateDirectory(l10n_path));

  std::vector<std::string> locales;
  l10n_util::GetParentLocales(l10n_util::GetApplicationLocale(""), &locales);
  ASSERT_FALSE(locales.empty());
  for (size_t i = 0; i < locales.size(); i++) {
    FilePath make_path;
    make_path = l10n_path.AppendASCII(locales[i]);
    ASSERT_TRUE(file_util::CreateDirectory(make_path));
    ASSERT_TRUE(file_util::WriteFile(make_path.AppendASCII(filename),
        data.c_str(), data.length()));
  }

  FilePath path;
  std::string extension_id = extension_test_util::MakeId("test");
  ExtensionResource resource(extension_id, temp.path(),
                             FilePath().AppendASCII(filename));
  FilePath resolved_path = resource.GetFilePath();

  FilePath expected_path;
  // Expect default path only, since fallback logic is disabled.
  // See http://crbug.com/27359.
  expected_path = root_resource;
  ASSERT_TRUE(file_util::AbsolutePath(&expected_path));

  EXPECT_EQ(ToLower(expected_path.value()), ToLower(resolved_path.value()));
  EXPECT_EQ(ToLower(temp.path().value()),
            ToLower(resource.extension_root().value()));
  EXPECT_EQ(ToLower(FilePath().AppendASCII(filename).value()),
            ToLower(resource.relative_path().value()));
}
<|endoftext|>


<commit_before>#pragma once

#include "routing/turns_sound_settings.hpp"
#include "routing/turns_tts_text.hpp"

#include "platform/settings.hpp"

#include "std/string.hpp"

namespace location
{
class FollowingInfo;
}

namespace routing
{
namespace turns
{
namespace sound
{
/// \brief The PronouncedNotification enum represents which sound notifications
/// for turns were heard.
enum class PronouncedNotification
{
  Nothing,
  First,
  Second /** The second notification just before the turn was pronounced. */
};

string DebugPrint(PronouncedNotification const notificationProgress);

/// \brief The TurnsSound class is responsible for all route turn sound notifications functionality.
/// To be able to generate turn sound notification the class needs to have correct Settings
/// and relevant speed.
class TurnsSound
{
  friend void UnitTest_TurnsSoundMetersTest();
  friend void UnitTest_TurnsSoundMetersTwoTurnsTest();
  friend void UnitTest_TurnsSoundFeetTest();
  friend void UnitTest_TurnsSoundComposedTurnTest();
  friend void UnitTest_TurnsSoundRoundaboutTurnTest();

  /// \brief The private contructor is used only for testing.
  TurnsSound(uint32_t startBeforeSeconds, uint32_t minStartBeforeMeters,
             uint32_t maxStartBeforeMeters, uint32_t minDistToSayNotificationMeters)
    : m_enabled(false), m_speedMetersPerSecond(0.), m_settings(),
      m_nextTurnNotificationProgress(PronouncedNotification::Nothing),
      m_turnNotificationWithThen(false),  m_nextTurnIndex(0),
      m_startBeforeSeconds(startBeforeSeconds), m_minStartBeforeMeters(minStartBeforeMeters),
      m_maxStartBeforeMeters(maxStartBeforeMeters),
      m_minDistToSayNotificationMeters(minDistToSayNotificationMeters) {}

  /// m_enabled == true when tts is turned on.
  /// Important! Clients (iOS/Android) implies that m_enabled is false by default.
  bool m_enabled;
  /// In m_speedMetersPerSecond is intended for some speed which will be used for
  /// convertion a distance in seconds to distance in meters. It could be a current
  /// an end user speed or an average speed for last several seconds.
  /// @TODO(vbykoianko) It's better to use an average speed
  /// for last several seconds instead of the current speed here.
  double m_speedMetersPerSecond;
  Settings m_settings;
  /// m_nextTurnNotificationProgress keeps a status which is being changing while
  /// an end user is coming to the closest (the next) turn along the route.
  /// When an end user is far from the next turn
  /// m_nextTurnNotificationProgress == Nothing.
  /// After the first turn notification has been pronounced
  /// m_nextTurnNotificationProgress == First.
  /// After the second notification has been pronounced
  /// m_nextTurnNotificationProgress == Second.
  PronouncedNotification m_nextTurnNotificationProgress;
  /// The flag is set to true if notification about the second turn was pronounced.
  /// It could happen in expressions like "Turn right. Then turn left."
  /// This flag is used to pass the information if second turn notification was pronounced
  /// between two calls of GenerateTurnSound() method.
  bool m_turnNotificationWithThen;
  uint32_t m_nextTurnIndex;
  /// getTtsText is a convector form turn notification information and locale to
  /// notification string.
  GetTtsText m_getTtsText;

  string GenerateTurnText(uint32_t distanceUnits, uint8_t exitNum, bool useThenInsteadOfDistance,
                          TurnDirection turnDir, ::Settings::Units lengthUnits) const;
  /// Generates turn sound notification for the nearest to the current position turn.
  string GenerateFirstTurnSound(TurnItem const & turn, double distanceToTurnMeters);
  /// Changes the state of the class to emulate that first turn notification is pronouned
  /// without pronunciation.
  void FastForwardFirstTurnNotification();

  // To inform an end user about the next turn with the help of an voice information message
  // an operation system needs:
  // - to launch TTS subsystem;
  // - to pronounce the message.
  // So to inform the user in time it's necessary to start
  // m_startBeforeSeconds before the time. It is used in the following way:
  // we start playing voice notice in m_startBeforeSeconds * TurnsSound::m_speedMetersPerSecond
  // meters before the turn (for the second voice notification).
  // When m_startBeforeSeconds * TurnsSound::m_speedMetersPerSecond  is too small or too large
  // we use m_minStartBeforeMeters or m_maxStartBeforeMeters correspondingly.
  uint32_t const m_startBeforeSeconds;
  uint32_t const m_minStartBeforeMeters;
  uint32_t const m_maxStartBeforeMeters;

  // m_minDistToSayNotificationMeters is minimum distance between two turns
  // when pronouncing the first notification about the second turn makes sense.
  uint32_t const m_minDistToSayNotificationMeters;

public:
  TurnsSound() : m_enabled(false), m_speedMetersPerSecond(0.), m_settings(),
      m_nextTurnNotificationProgress(PronouncedNotification::Nothing),
      m_turnNotificationWithThen(false),  m_nextTurnIndex(0),
      m_startBeforeSeconds(5), m_minStartBeforeMeters(25), m_maxStartBeforeMeters(150),
      m_minDistToSayNotificationMeters(170) {}

  bool IsEnabled() const { return m_enabled; }
  void Enable(bool enable);
  void SetLengthUnits(::Settings::Units units);
  inline ::Settings::Units GetLengthUnits() const { return m_settings.GetLengthUnits(); }
  inline void SetLocale(string const & locale) { m_getTtsText.SetLocale(locale); }
  inline string GetLocale() const { return m_getTtsText.GetLocale(); }
  void SetSpeedMetersPerSecond(double speed);

   /// \brief GenerateTurnSound updates information about the next turn notification.
   /// It also fills turnNotifications when it's necessary.
   /// If this TurnsSound wants to play a sound message once it should push one item to
   /// the vector turnNotifications once when GenerateTurnSound is called.
   /// \param turn contains information about the next turn.
   /// \param distanceToTurnMeters is distance to the next turn in meters.
   /// \param turnNotifications is a parameter to fill it if it's necessary.
   /// \note The client implies turnNotifications does not contain empty strings.
  void GenerateTurnSound(vector<TurnItemDist> const & turns, vector<string> & turnNotifications);
  /// Reset states which reflects current route position.
  /// The method shall be called after creating a new route or after rerouting.
  void Reset();
};
}  // namespace sound
}  // namespace turns
}  // namespace routing
<commit_msg>Corrections after colleagues comments.<commit_after>#pragma once

#include "routing/turns_sound_settings.hpp"
#include "routing/turns_tts_text.hpp"

#include "platform/settings.hpp"

#include "std/string.hpp"

namespace location
{
class FollowingInfo;
}

namespace routing
{
namespace turns
{
namespace sound
{
/// \brief The PronouncedNotification enum represents which sound notifications
/// for turns were heard.
enum class PronouncedNotification
{
  Nothing,
  First,
  Second /** The second notification just before the turn was pronounced. */
};

string DebugPrint(PronouncedNotification const notificationProgress);

/// \brief The TurnsSound class is responsible for all route turn sound notifications functionality.
/// To be able to generate turn sound notification the class needs to have correct Settings
/// and relevant speed.
class TurnsSound
{
  friend void UnitTest_TurnsSoundMetersTest();
  friend void UnitTest_TurnsSoundMetersTwoTurnsTest();
  friend void UnitTest_TurnsSoundFeetTest();
  friend void UnitTest_TurnsSoundComposedTurnTest();
  friend void UnitTest_TurnsSoundRoundaboutTurnTest();

  /// \brief The private contructor is used only for testing.
  TurnsSound(uint32_t startBeforeSeconds, uint32_t minStartBeforeMeters,
             uint32_t maxStartBeforeMeters, uint32_t minDistToSayNotificationMeters)
    : m_enabled(false), m_speedMetersPerSecond(0.), m_settings(),
      m_nextTurnNotificationProgress(PronouncedNotification::Nothing),
      m_turnNotificationWithThen(false),  m_nextTurnIndex(0),
      m_startBeforeSeconds(startBeforeSeconds), m_minStartBeforeMeters(minStartBeforeMeters),
      m_maxStartBeforeMeters(maxStartBeforeMeters),
      m_minDistToSayNotificationMeters(minDistToSayNotificationMeters)
  {
    ASSERT_LESS_OR_EQUAL(m_minStartBeforeMeters, m_maxStartBeforeMeters, ());
  }

  /// m_enabled == true when tts is turned on.
  /// Important! Clients (iOS/Android) implies that m_enabled is false by default.
  bool m_enabled;
  /// In m_speedMetersPerSecond is intended for some speed which will be used for
  /// convertion a distance in seconds to distance in meters. It could be a current
  /// an end user speed or an average speed for last several seconds.
  /// @TODO(vbykoianko) It's better to use an average speed
  /// for last several seconds instead of the current speed here.
  double m_speedMetersPerSecond;
  Settings m_settings;
  /// m_nextTurnNotificationProgress keeps a status which is being changing while
  /// an end user is coming to the closest (the next) turn along the route.
  /// When an end user is far from the next turn
  /// m_nextTurnNotificationProgress == Nothing.
  /// After the first turn notification has been pronounced
  /// m_nextTurnNotificationProgress == First.
  /// After the second notification has been pronounced
  /// m_nextTurnNotificationProgress == Second.
  PronouncedNotification m_nextTurnNotificationProgress;
  /// The flag is set to true if notification about the second turn was pronounced.
  /// It could happen in expressions like "Turn right. Then turn left."
  /// This flag is used to pass the information if second turn notification was pronounced
  /// between two calls of GenerateTurnSound() method.
  bool m_turnNotificationWithThen;
  uint32_t m_nextTurnIndex;
  /// getTtsText is a convector form turn notification information and locale to
  /// notification string.
  GetTtsText m_getTtsText;

  string GenerateTurnText(uint32_t distanceUnits, uint8_t exitNum, bool useThenInsteadOfDistance,
                          TurnDirection turnDir, ::Settings::Units lengthUnits) const;
  /// Generates turn sound notification for the nearest to the current position turn.
  string GenerateFirstTurnSound(TurnItem const & turn, double distanceToTurnMeters);
  /// Changes the state of the class to emulate that first turn notification is pronouned
  /// without pronunciation.
  void FastForwardFirstTurnNotification();

  // To inform an end user about the next turn with the help of an voice information message
  // an operation system needs:
  // - to launch TTS subsystem;
  // - to pronounce the message.
  // So to inform the user in time it's necessary to start
  // m_startBeforeSeconds before the time. It is used in the following way:
  // we start playing voice notice in m_startBeforeSeconds * TurnsSound::m_speedMetersPerSecond
  // meters before the turn (for the second voice notification).
  // When m_startBeforeSeconds * TurnsSound::m_speedMetersPerSecond  is too small or too large
  // we use m_minStartBeforeMeters or m_maxStartBeforeMeters correspondingly.
  uint32_t const m_startBeforeSeconds;
  uint32_t const m_minStartBeforeMeters;
  uint32_t const m_maxStartBeforeMeters;

  // m_minDistToSayNotificationMeters is minimum distance between two turns
  // when pronouncing the first notification about the second turn makes sense.
  uint32_t const m_minDistToSayNotificationMeters;

public:
  TurnsSound() : m_enabled(false), m_speedMetersPerSecond(0.), m_settings(),
      m_nextTurnNotificationProgress(PronouncedNotification::Nothing),
      m_turnNotificationWithThen(false),  m_nextTurnIndex(0),
      m_startBeforeSeconds(5), m_minStartBeforeMeters(25), m_maxStartBeforeMeters(150),
      m_minDistToSayNotificationMeters(170)
  {
    ASSERT_LESS_OR_EQUAL(m_minStartBeforeMeters, m_maxStartBeforeMeters, ());
  }

  bool IsEnabled() const { return m_enabled; }
  void Enable(bool enable);
  void SetLengthUnits(::Settings::Units units);
  inline ::Settings::Units GetLengthUnits() const { return m_settings.GetLengthUnits(); }
  inline void SetLocale(string const & locale) { m_getTtsText.SetLocale(locale); }
  inline string GetLocale() const { return m_getTtsText.GetLocale(); }
  void SetSpeedMetersPerSecond(double speed);

   /// \brief GenerateTurnSound updates information about the next turn notification.
   /// It also fills turnNotifications when it's necessary.
   /// If this TurnsSound wants to play a sound message once it should push one item to
   /// the vector turnNotifications once when GenerateTurnSound is called.
   /// \param turn contains information about the next turn.
   /// \param distanceToTurnMeters is distance to the next turn in meters.
   /// \param turnNotifications is a parameter to fill it if it's necessary.
   /// \note The client implies turnNotifications does not contain empty strings.
  void GenerateTurnSound(vector<TurnItemDist> const & turns, vector<string> & turnNotifications);
  /// Reset states which reflects current route position.
  /// The method shall be called after creating a new route or after rerouting.
  void Reset();
};
}  // namespace sound
}  // namespace turns
}  // namespace routing
<|endoftext|>


<commit_before>//
// Created by monty on 26/09/16.
//
#include <string>
#include <iterator>
#include <iostream>
#include <sstream>
#include <vector>

#include "Common.h"

namespace Knights {
	float floatFrom(std::string str) {
		std::istringstream buffer(str);
		float temp;
		buffer >> temp;

		return temp;
	}

	int intFrom(std::string str) {
		std::istringstream buffer(str);
		int temp;
		buffer >> temp;

		return temp;
	}

	std::string filterComments(std::string input) {
		bool reading = true;
		std::stringstream output;

		for (auto &character : input) {

			if (character == '/') {
				reading = false;
			} else if (character == '\n') {
				reading = true;
			}

			if (reading) {
				output << character;
			}
		}

		return output.str();
	}

	std::vector<char> readToBuffer(FILE *fileDescriptor) {
		const unsigned N = 1024;

		fseek(fileDescriptor, 0, SEEK_END);
		auto endPos = ftell( fileDescriptor );
		rewind(fileDescriptor);
		std::vector<char> total(endPos);
		auto writeHead = std::begin( total );

		for ( int c = 0; c < endPos; ++c ) {
			char buffer[N];
			size_t read = fread((void *) &buffer[0], 1, N, fileDescriptor);
			if (read) {
				for (int c = 0; c < read; ++c) {
					*writeHead = (buffer[c]);
					writeHead = std::next(writeHead);
				}
			}
			if (read < N) {
				break;
			}
		}

		return total;
	}

	std::string readToString(FILE *fileDescriptor) {

		fseek(fileDescriptor, 0, SEEK_END);
		long fileSize = ftell(fileDescriptor);
		rewind(fileDescriptor);
		std::string total;
		total.assign(fileSize, 0);

		for (auto pos = 0; pos < fileSize; ++pos) {
			char buffer[1];
			size_t read = fread((void *) &buffer[0], 1, 1, fileDescriptor);
			if (read) {
				for (int c = 0; c < read; ++c) {
					total[pos] = buffer[c];
				}
			}
			if (read < 1) {
				return "total not met";
			}
		}

		return total;
	}
}<commit_msg>Add missing header<commit_after>//
// Created by monty on 26/09/16.
//
#include <functional>
#include <string>
#include <iterator>
#include <iostream>
#include <sstream>
#include <vector>

#include "Common.h"

namespace Knights {
	float floatFrom(std::string str) {
		std::istringstream buffer(str);
		float temp;
		buffer >> temp;

		return temp;
	}

	int intFrom(std::string str) {
		std::istringstream buffer(str);
		int temp;
		buffer >> temp;

		return temp;
	}

	std::string filterComments(std::string input) {
		bool reading = true;
		std::stringstream output;

		for (auto &character : input) {

			if (character == '/') {
				reading = false;
			} else if (character == '\n') {
				reading = true;
			}

			if (reading) {
				output << character;
			}
		}

		return output.str();
	}

	std::vector<char> readToBuffer(FILE *fileDescriptor) {
		const unsigned N = 1024;

		fseek(fileDescriptor, 0, SEEK_END);
		auto endPos = ftell( fileDescriptor );
		rewind(fileDescriptor);
		std::vector<char> total(endPos);
		auto writeHead = std::begin( total );

		for ( int c = 0; c < endPos; ++c ) {
			char buffer[N];
			size_t read = fread((void *) &buffer[0], 1, N, fileDescriptor);
			if (read) {
				for (int c = 0; c < read; ++c) {
					*writeHead = (buffer[c]);
					writeHead = std::next(writeHead);
				}
			}
			if (read < N) {
				break;
			}
		}

		return total;
	}

	std::string readToString(FILE *fileDescriptor) {

		fseek(fileDescriptor, 0, SEEK_END);
		long fileSize = ftell(fileDescriptor);
		rewind(fileDescriptor);
		std::string total;
		total.assign(fileSize, 0);

		for (auto pos = 0; pos < fileSize; ++pos) {
			char buffer[1];
			size_t read = fread((void *) &buffer[0], 1, 1, fileDescriptor);
			if (read) {
				for (int c = 0; c < read; ++c) {
					total[pos] = buffer[c];
				}
			}
			if (read < 1) {
				return "total not met";
			}
		}

		return total;
	}
}<|endoftext|>