<commit_before>#include <catch.hpp>
#include <memory>

#include "GCodeWriter.hpp"
#include "test_options.hpp"

using namespace Slic3r;
using namespace std::literals::string_literals;

SCENARIO("lift() is not ignored after unlift() at large values of Z", "[!mayfail]") {
    GIVEN("A config from a file and a single extruder.") {
        GCodeWriter writer;
        auto& config {writer.config};
        config.set_defaults();
        config.load(std::string(testfile_dir) + "test_gcodewriter/config_lift_unlift.ini"s);

        std::vector<unsigned int> extruder_ids {0};
        writer.set_extruders(extruder_ids);
        writer.set_extruder(0);

        WHEN("Z is set to 9007199254740992") {
            double trouble_Z = 9007199254740992;
            writer.travel_to_z(trouble_Z);
            AND_WHEN("GcodeWriter::Lift() is called") {
                REQUIRE(writer.lift().size() > 0);
                AND_WHEN("Z is moved post-lift to the same delta as the config Z lift") {
                    REQUIRE(writer.travel_to_z(trouble_Z + config.retract_lift.values[0]).size() == 0);
                    AND_WHEN("GCodeWriter::Lift() is called after GCodeWriter::Unlift()") {
                        REQUIRE(writer.unlift().size() == 0); // we're the same height so no additional move happens.
                        THEN("GCodeWriter::Lift() emits gcode.") {
                            REQUIRE(writer.lift().size() > 0);
                        }
                    }
                }
            }
        }
    }
}
<commit_msg>Set the large Z as shouldfail, added normal range tests.<commit_after>#include <catch.hpp>
#include <memory>

#include "GCodeWriter.hpp"
#include "test_options.hpp"

using namespace Slic3r;
using namespace std::literals::string_literals;

SCENARIO("lift() and unlift() behavior with large values of Z", "[!shouldfail]") {
    GIVEN("A config from a file and a single extruder.") {
        GCodeWriter writer;
        auto& config {writer.config};
        config.set_defaults();
        config.load(std::string(testfile_dir) + "test_gcodewriter/config_lift_unlift.ini"s);

        std::vector<unsigned int> extruder_ids {0};
        writer.set_extruders(extruder_ids);
        writer.set_extruder(0);

        WHEN("Z is set to 9007199254740992") {
            double trouble_Z = 9007199254740992;
            writer.travel_to_z(trouble_Z);
            AND_WHEN("GcodeWriter::Lift() is called") {
                REQUIRE(writer.lift().size() > 0);
                AND_WHEN("Z is moved post-lift to the same delta as the config Z lift") {
                    REQUIRE(writer.travel_to_z(trouble_Z + config.retract_lift.values[0]).size() == 0);
                    AND_WHEN("GCodeWriter::Unlift() is called") {
                        REQUIRE(writer.unlift().size() == 0); // we're the same height so no additional move happens.
                        THEN("GCodeWriter::Lift() emits gcode.") {
                            REQUIRE(writer.lift().size() > 0);
                        }
                    }
                }
            }
        }
    }
}

SCENARIO("lift() is not ignored after unlift() at normal values of Z") {
    GIVEN("A config from a file and a single extruder.") {
        GCodeWriter writer;
        auto& config {writer.config};
        config.set_defaults();
        config.load(std::string(testfile_dir) + "test_gcodewriter/config_lift_unlift.ini"s);

        std::vector<unsigned int> extruder_ids {0};
        writer.set_extruders(extruder_ids);
        writer.set_extruder(0);

        WHEN("Z is set to 203") {
            double trouble_Z = 203;
            writer.travel_to_z(trouble_Z);
            AND_WHEN("GcodeWriter::Lift() is called") {
                REQUIRE(writer.lift().size() > 0);
                AND_WHEN("Z is moved post-lift to the same delta as the config Z lift") {
                    REQUIRE(writer.travel_to_z(trouble_Z + config.retract_lift.values[0]).size() == 0);
                    AND_WHEN("GCodeWriter::Unlift() is called") {
                        REQUIRE(writer.unlift().size() == 0); // we're the same height so no additional move happens.
                        THEN("GCodeWriter::Lift() emits gcode.") {
                            REQUIRE(writer.lift().size() > 0);
                        }
                    }
                }
            }
        }
        WHEN("Z is set to 500003") {
            double trouble_Z = 500003;
            writer.travel_to_z(trouble_Z);
            AND_WHEN("GcodeWriter::Lift() is called") {
                REQUIRE(writer.lift().size() > 0);
                AND_WHEN("Z is moved post-lift to the same delta as the config Z lift") {
                    REQUIRE(writer.travel_to_z(trouble_Z + config.retract_lift.values[0]).size() == 0);
                    AND_WHEN("GCodeWriter::Unlift() is called") {
                        REQUIRE(writer.unlift().size() == 0); // we're the same height so no additional move happens.
                        THEN("GCodeWriter::Lift() emits gcode.") {
                            REQUIRE(writer.lift().size() > 0);
                        }
                    }
                }
            }
        }
        WHEN("Z is set to 10.3") {
            double trouble_Z = 10.3;
            writer.travel_to_z(trouble_Z);
            AND_WHEN("GcodeWriter::Lift() is called") {
                REQUIRE(writer.lift().size() > 0);
                AND_WHEN("Z is moved post-lift to the same delta as the config Z lift") {
                    REQUIRE(writer.travel_to_z(trouble_Z + config.retract_lift.values[0]).size() == 0);
                    AND_WHEN("GCodeWriter::Unlift() is called") {
                        REQUIRE(writer.unlift().size() == 0); // we're the same height so no additional move happens.
                        THEN("GCodeWriter::Lift() emits gcode.") {
                            REQUIRE(writer.lift().size() > 0);
                        }
                    }
                }
            }
        }
    }
}
<|endoftext|>


<commit_before>// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements.  See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.  The ASF licenses this file
// to you 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.

#include <string>
#include <vector>

#include <gtest/gtest.h>

#include <stout/check.hpp>
#include <stout/gtest.hpp>
#include <stout/try.hpp>

#include <mesos/values.hpp>

#include "common/resource_quantities.hpp"

using std::pair;
using std::string;
using std::vector;

using mesos::internal::ResourceQuantities;

namespace mesos {
namespace internal {
namespace tests {

TEST(QuantitiesTest, FromStringValid)
{
  // A single resource.
  ResourceQuantities resourceQuantities =
    CHECK_NOTERROR(ResourceQuantities::fromString("cpus:10"));
  EXPECT_EQ(1u, resourceQuantities.size());
  EXPECT_EQ("cpus", resourceQuantities.begin()->first);
  EXPECT_DOUBLE_EQ(10, resourceQuantities.begin()->second.value());

  resourceQuantities =
    CHECK_NOTERROR(ResourceQuantities::fromString("cpus:3.14"));
  EXPECT_EQ(1u, resourceQuantities.size());
  EXPECT_EQ("cpus", resourceQuantities.begin()->first);
  EXPECT_DOUBLE_EQ(3.14, resourceQuantities.begin()->second.value());

  // Whitespace is trimmed.
  resourceQuantities =
    CHECK_NOTERROR(ResourceQuantities::fromString(" cpus : 3.14 ; disk : 10 "));
  EXPECT_EQ(2u, resourceQuantities.size());
  auto it = resourceQuantities.begin();
  EXPECT_EQ("cpus", it->first);
  EXPECT_DOUBLE_EQ(3.14, it->second.value());
  ++it;
  EXPECT_EQ("disk", it->first);
  EXPECT_DOUBLE_EQ(10, it->second.value());

  // Zero value.
  resourceQuantities = CHECK_NOTERROR(ResourceQuantities::fromString("cpus:0"));
  EXPECT_EQ(0u, resourceQuantities.size());

  // Two resources.
  resourceQuantities =
    CHECK_NOTERROR(ResourceQuantities::fromString("cpus:10.5;ports:1"));
  EXPECT_EQ(2u, resourceQuantities.size());
  it = resourceQuantities.begin();
  EXPECT_EQ("cpus", it->first);
  EXPECT_DOUBLE_EQ(10.5, it->second.value());
  ++it;
  EXPECT_EQ("ports", it->first);
  EXPECT_DOUBLE_EQ(1, it->second.value());

  // Two resources with names out of alphabetical order.
  resourceQuantities =
    CHECK_NOTERROR(ResourceQuantities::fromString("ports:3;cpus:10.5"));
  EXPECT_EQ(2u, resourceQuantities.size());
  it = resourceQuantities.begin();
  EXPECT_EQ("cpus", it->first);
  EXPECT_DOUBLE_EQ(10.5, it->second.value());
  ++it;
  EXPECT_EQ("ports", it->first);
  EXPECT_DOUBLE_EQ(3, it->second.value());

  // Duplicate resource names.
  resourceQuantities =
    CHECK_NOTERROR(ResourceQuantities::fromString("ports:3;cpus:1;cpus:10.5"));
  EXPECT_EQ(2u, resourceQuantities.size());
  it = resourceQuantities.begin();
  EXPECT_EQ("cpus", it->first);
  EXPECT_DOUBLE_EQ(11.5, it->second.value());
  ++it;
  EXPECT_EQ("ports", it->first);
  EXPECT_DOUBLE_EQ(3, it->second.value());
}

TEST(QuantitiesTest, FromStringInvalid)
{
  // Invalid scalar.
  Try<ResourceQuantities> resourceQuantities =
    ResourceQuantities::fromString("cpus:a10");
  EXPECT_ERROR(resourceQuantities);

  resourceQuantities = ResourceQuantities::fromString("cpus:3.14c");
  EXPECT_ERROR(resourceQuantities);

  // Missing semicolon.
  resourceQuantities = ResourceQuantities::fromString("ports:3,cpus:1");
  EXPECT_ERROR(resourceQuantities);

  // Negative value.
  resourceQuantities = ResourceQuantities::fromString("ports:3,cpus:-1");
  EXPECT_ERROR(resourceQuantities);

  resourceQuantities = ResourceQuantities::fromString("cpus:nan");
  EXPECT_ERROR(resourceQuantities);

  resourceQuantities = ResourceQuantities::fromString("cpus:-nan");
  EXPECT_ERROR(resourceQuantities);

  resourceQuantities = ResourceQuantities::fromString("cpus:inf");
  EXPECT_ERROR(resourceQuantities);

  resourceQuantities = ResourceQuantities::fromString("cpus:-inf");
  EXPECT_ERROR(resourceQuantities);

  resourceQuantities = ResourceQuantities::fromString("cpus:infinity");
  EXPECT_ERROR(resourceQuantities);

  resourceQuantities = ResourceQuantities::fromString("cpus:-infinity");
  EXPECT_ERROR(resourceQuantities);
}

TEST(QuantitiesTest, FromScalarResources)
{
  // Empty resources.
  ResourceQuantities quantities =
    ResourceQuantities::fromScalarResources(Resources());
  EXPECT_EQ(0u, quantities.size());

  // Result entries are ordered alphabetically.
  quantities = ResourceQuantities::fromScalarResources(
    CHECK_NOTERROR(Resources::parse("cpus:1;mem:512;disk:800")));
  EXPECT_EQ(3u, quantities.size());
  auto it = quantities.begin();
  EXPECT_EQ("cpus", it->first);
  EXPECT_DOUBLE_EQ(1, it->second.value());
  ++it;
  EXPECT_EQ("disk", it->first);
  EXPECT_DOUBLE_EQ(800, it->second.value());
  ++it;
  EXPECT_EQ("mem", it->first);
  EXPECT_DOUBLE_EQ(512, it->second.value());
}

} // namespace tests {
} // namespace internal {
} // namespace mesos {
<commit_msg>Improved `ResourceQuantities` test's readability.<commit_after>// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements.  See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.  The ASF licenses this file
// to you 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.

#include <string>
#include <vector>

#include <gtest/gtest.h>

#include <stout/check.hpp>
#include <stout/gtest.hpp>
#include <stout/try.hpp>

#include <mesos/values.hpp>

#include "common/resource_quantities.hpp"

using std::pair;
using std::string;
using std::vector;

using mesos::internal::ResourceQuantities;

namespace mesos {
namespace internal {
namespace tests {

static vector<pair<string, double>> toVector(
  const ResourceQuantities& quantities)
{
  vector<pair<string, double>> result;

  foreach (auto&& quantity, quantities) {
    result.push_back(std::make_pair(quantity.first, quantity.second.value()));
  }

  return result;
}

TEST(QuantitiesTest, FromStringValid)
{
  // A single resource.
  ResourceQuantities resourceQuantities =
    CHECK_NOTERROR(ResourceQuantities::fromString("cpus:10"));
  vector<pair<string, double>> expected = {{"cpus", 10}};
  EXPECT_EQ(expected, toVector(resourceQuantities));

  resourceQuantities =
    CHECK_NOTERROR(ResourceQuantities::fromString("cpus:3.14"));
  expected = {{"cpus", 3.14}};
  EXPECT_EQ(expected, toVector(resourceQuantities));

  // Whitespace is trimmed.
  resourceQuantities =
    CHECK_NOTERROR(ResourceQuantities::fromString(" cpus : 3.14 ; disk : 10 "));
  expected = {{"cpus", 3.14}, {"disk", 10}};
  EXPECT_EQ(expected, toVector(resourceQuantities));

  // Zero value.
  resourceQuantities = CHECK_NOTERROR(ResourceQuantities::fromString("cpus:0"));
  EXPECT_EQ(0u, resourceQuantities.size());

  // Two resources.
  resourceQuantities =
    CHECK_NOTERROR(ResourceQuantities::fromString("cpus:10.5;ports:1"));
  expected = {{"cpus", 10.5}, {"ports", 1}};
  EXPECT_EQ(expected, toVector(resourceQuantities));

  // Two resources with names out of alphabetical order.
  resourceQuantities =
    CHECK_NOTERROR(ResourceQuantities::fromString("ports:3;cpus:10.5"));
  expected = {{"cpus", 10.5}, {"ports", 3}};
  EXPECT_EQ(expected, toVector(resourceQuantities));

  // Duplicate resource names.
  resourceQuantities =
    CHECK_NOTERROR(ResourceQuantities::fromString("ports:3;cpus:1;cpus:10.5"));
  expected = {{"cpus", 11.5}, {"ports", 3}};
  EXPECT_EQ(expected, toVector(resourceQuantities));
}

TEST(QuantitiesTest, FromStringInvalid)
{
  // Invalid scalar.
  Try<ResourceQuantities> resourceQuantities =
    ResourceQuantities::fromString("cpus:a10");
  EXPECT_ERROR(resourceQuantities);

  resourceQuantities = ResourceQuantities::fromString("cpus:3.14c");
  EXPECT_ERROR(resourceQuantities);

  // Missing semicolon.
  resourceQuantities = ResourceQuantities::fromString("ports:3,cpus:1");
  EXPECT_ERROR(resourceQuantities);

  // Negative value.
  resourceQuantities = ResourceQuantities::fromString("ports:3,cpus:-1");
  EXPECT_ERROR(resourceQuantities);

  resourceQuantities = ResourceQuantities::fromString("cpus:nan");
  EXPECT_ERROR(resourceQuantities);

  resourceQuantities = ResourceQuantities::fromString("cpus:-nan");
  EXPECT_ERROR(resourceQuantities);

  resourceQuantities = ResourceQuantities::fromString("cpus:inf");
  EXPECT_ERROR(resourceQuantities);

  resourceQuantities = ResourceQuantities::fromString("cpus:-inf");
  EXPECT_ERROR(resourceQuantities);

  resourceQuantities = ResourceQuantities::fromString("cpus:infinity");
  EXPECT_ERROR(resourceQuantities);

  resourceQuantities = ResourceQuantities::fromString("cpus:-infinity");
  EXPECT_ERROR(resourceQuantities);
}

TEST(QuantitiesTest, FromScalarResources)
{
  // Empty resources.
  ResourceQuantities quantities =
    ResourceQuantities::fromScalarResources(Resources());
  EXPECT_EQ(0u, quantities.size());

  // Result entries are ordered alphabetically.
  quantities = ResourceQuantities::fromScalarResources(
    CHECK_NOTERROR(Resources::parse("cpus:1;mem:512;disk:800")));
  vector<pair<string, double>> expected = {
    {"cpus", 1}, {"disk", 800}, {"mem", 512}};
  EXPECT_EQ(expected, toVector(quantities));
}

} // namespace tests {
} // namespace internal {
} // namespace mesos {
<|endoftext|>


<commit_before>/*
 * Copyright(c) Sophist Solutions, Inc. 1990-2012.  All rights reserved
 */
#include    "../StroikaPreComp.h"

#include    <cstdarg>
#include    <cstdlib>
#include    <iomanip>
#include    <sstream>

#include    "../Containers/Common.h"
#include    "../Debug/Assertions.h"
#include    "../Debug/Trace.h"
#include    "../Math/Common.h"
#include    "../Memory/SmallStackBuffer.h"
#include    "CodePage.h"

#include    "Format.h"

using   namespace   Stroika::Foundation;
using   namespace   Stroika::Foundation::Characters;
using   namespace   Stroika::Foundation::Memory;

/*
 ********************************************************************************
 ************************************* Format ***********************************
 ********************************************************************************
 */
string  Characters::FormatV (const char* format, va_list argsList)
{
    RequireNotNull (format);
    Memory::SmallStackBuffer<char, 10* 1024> msgBuf (10 * 1024);
#if     qSupportValgrindQuirks
    // Makes little sense - even msgBuf[0] not sufficient - but this silences lots of warnings.
    // -- LGP 2012-05-19
    memset (msgBuf, 0, sizeof (msgBuf[0]) * msgBuf.GetSize());
#endif
#if     __STDC_WANT_SECURE_LIB__
    while (::vsnprintf_s (msgBuf, msgBuf.GetSize (), msgBuf.GetSize () - 1, format, argsList) < 0) {
        msgBuf.GrowToSize (msgBuf.GetSize () * 2);
    }
#else
    while (::vsnprintf (msgBuf, msgBuf.GetSize (), format, argsList) < 0) {
        msgBuf.GrowToSize (msgBuf.GetSize () * 2);
    }
#endif
    Assert (::strlen (msgBuf.begin ()) < msgBuf.GetSize ());
    return string (msgBuf);
}

string  Characters::Format (const char* format, ...)
{
    va_list     argsList;
    va_start (argsList, format);
    string  tmp = FormatV (format, argsList);
    va_end (argsList);
    return tmp;
}

wstring Characters::FormatV (const wchar_t* format, va_list argsList)
{
    RequireNotNull (format);
    Memory::SmallStackBuffer<wchar_t, 10* 1024>  msgBuf (10 * 1024);
    const   wchar_t*    useFormat   =   format;
#if     !qStdLibSprintfAssumesPctSIsWideInFormatIfWideFormat
    wchar_t     newFormat[5 * 1024];
    {
        size_t  origFormatLen   =   wcslen (format);
        Require (origFormatLen < NEltsOf (newFormat) / 2);  // just to be sure safe - this is already crazy-big for format string...
        // Could use Memory::SmallStackBuffer<> but I doubt this will ever get triggered
        bool lookingAtFmtCvt = false;
        size_t  newFormatIdx    =   0;
        for (size_t i = 0; i < origFormatLen; ++i) {
            if (lookingAtFmtCvt) {
                switch (format[i]) {
                    case    '%': {
                            lookingAtFmtCvt = false;
                        }
                        break;
                    case    's': {
                            newFormat[newFormatIdx] = 'l';
                            newFormatIdx++;
                        }
                        break;
                    case    '.': {
                            // could still be part for format string
                        }
                        break;
                    default: {
                            if (isdigit (format[i])) {
                                // could still be part for format string
                            }
                            else {
                                lookingAtFmtCvt = false;    // DONE
                            }
                        }
                        break;
                }
            }
            else {
                if (format[i] == '%') {
                    lookingAtFmtCvt = true;
                }
            }
            newFormat[newFormatIdx] = format[i];
            newFormatIdx++;
        }
        Assert (newFormatIdx >= origFormatLen);
        if (newFormatIdx > origFormatLen) {
            newFormat[newFormatIdx] = '\0';
            useFormat   =   newFormat;
        }
    }
#endif

#if     qSupportValgrindQuirks
    // Makes little sense - even msgBuf[0] not sufficient - but this silences lots of warnings.
    // -- LGP 2012-05-19
    memset (msgBuf, 0, sizeof (msgBuf[0]) * msgBuf.GetSize());
#endif

    // Assume only reason for failure is not enuf bytes, so allocate more.
    // If I'm wrong, we'll just runout of memory and throw out...
    while (::vswprintf (msgBuf, msgBuf.GetSize (), useFormat, argsList) < 0) {
        msgBuf.GrowToSize (msgBuf.GetSize () * 2);
    }
    Assert (::wcslen (msgBuf) < msgBuf.GetSize ());
    return wstring (msgBuf);
}

wstring Characters::Format (const wchar_t* format, ...)
{
    va_list     argsList;
    va_start (argsList, format);
    wstring tmp = FormatV (format, argsList);
    va_end (argsList);
    return tmp;
}

/*
 ********************************************************************************
 ****************************** HexString2Int ***********************************
 ********************************************************************************
 */
int Characters::HexString2Int (const string& s)
{
    return ::strtol (s.c_str (), nullptr, 16);
}

int Characters::HexString2Int (const wstring& s)
{
    // http://msdn.microsoft.com/en-us/library/w4z2wdyc(v=vs.80).aspx
    // http://pubs.opengroup.org/onlinepubs/009695399/functions/wcstol.html
    return ::wcstol (s.c_str (), nullptr, 16);
}

/*
 ********************************************************************************
 ********************************* String2Int ***********************************
 ********************************************************************************
 */
int Characters::String2Int (const string& s)
{
    return ::atol (s.c_str ());
}

int Characters::String2Int (const wstring& s)
{
#if     defined (_MSC_VER)
    return ::_wtol (s.c_str ());
#else
    // unclear if this is good/safe - cuz of - for example - funky wide japanese numbers etc... probaby must do better
    // Also note use WideStringToNarrowSDKString() instead of WideStringToASCII - cuz the later asserts all valid ascii chars which may not be true here...
    //      -- LGP 2011-08-18
    return String2Int (WideStringToNarrowSDKString (s));
#endif
}

/*
 ********************************************************************************
 ********************************* String2Float *********************************
 ********************************************************************************
 */
double  Characters::String2Float (const wstring& s)
{
    static  const   double  kBADVAL =   static_cast<double> (Math::nan ());
    return String2Float (s, kBADVAL);
}

double  Characters::String2Float (const wstring& s, double returnValIfInvalidString)
{
    double  num =   returnValIfInvalidString;
#pragma warning (push)
#pragma warning (4 : 4996)      // MSVC SILLY WARNING ABOUT USING swscanf_s
    if (::swscanf (s.c_str (), L"%lf", &num) == 1) {
        return num;
    }
#pragma warning (pop)
    return returnValIfInvalidString;
}

/*
 ********************************************************************************
 ********************************* Float2String *********************************
 ********************************************************************************
 */
wstring Characters::Float2String (double f, unsigned int precision)
{
    if (std::isnan (f)) {
        return wstring ();
    }
    stringstream s;
    s << setprecision (precision) << f;
    wstring r = ASCIIStringToWide (s.str ());
    return r;
}

<commit_msg>Fixed Characters/Format Assert<commit_after>/*
 * Copyright(c) Sophist Solutions, Inc. 1990-2012.  All rights reserved
 */
#include    "../StroikaPreComp.h"

#include    <cstdarg>
#include    <cstdlib>
#include    <iomanip>
#include    <sstream>

#include    "../Containers/Common.h"
#include    "../Debug/Assertions.h"
#include    "../Debug/Trace.h"
#include    "../Math/Common.h"
#include    "../Memory/SmallStackBuffer.h"
#include    "CodePage.h"

#include    "Format.h"

using   namespace   Stroika::Foundation;
using   namespace   Stroika::Foundation::Characters;
using   namespace   Stroika::Foundation::Memory;

/*
 ********************************************************************************
 ************************************* Format ***********************************
 ********************************************************************************
 */
string  Characters::FormatV (const char* format, va_list argsList)
{
    RequireNotNull (format);
    Memory::SmallStackBuffer<char, 10* 1024> msgBuf (10 * 1024);
#if     qSupportValgrindQuirks
    // Makes little sense - even msgBuf[0] not sufficient - but this silences lots of warnings.
    // -- LGP 2012-05-19
    memset (msgBuf, 0, sizeof (msgBuf[0]) * msgBuf.GetSize());
#endif
#if     __STDC_WANT_SECURE_LIB__
    while (::vsnprintf_s (msgBuf, msgBuf.GetSize (), msgBuf.GetSize () - 1, format, argsList) < 0) {
        msgBuf.GrowToSize (msgBuf.GetSize () * 2);
    }
#else
    while (::vsnprintf (msgBuf, msgBuf.GetSize (), format, argsList) < 0) {
        msgBuf.GrowToSize (msgBuf.GetSize () * 2);
    }
#endif
    Assert (::strlen (msgBuf) < msgBuf.GetSize ());
    return string (msgBuf);
}

string  Characters::Format (const char* format, ...)
{
    va_list     argsList;
    va_start (argsList, format);
    string  tmp = FormatV (format, argsList);
    va_end (argsList);
    return tmp;
}

wstring Characters::FormatV (const wchar_t* format, va_list argsList)
{
    RequireNotNull (format);
    Memory::SmallStackBuffer<wchar_t, 10* 1024>  msgBuf (10 * 1024);
    const   wchar_t*    useFormat   =   format;
#if     !qStdLibSprintfAssumesPctSIsWideInFormatIfWideFormat
    wchar_t     newFormat[5 * 1024];
    {
        size_t  origFormatLen   =   wcslen (format);
        Require (origFormatLen < NEltsOf (newFormat) / 2);  // just to be sure safe - this is already crazy-big for format string...
        // Could use Memory::SmallStackBuffer<> but I doubt this will ever get triggered
        bool lookingAtFmtCvt = false;
        size_t  newFormatIdx    =   0;
        for (size_t i = 0; i < origFormatLen; ++i) {
            if (lookingAtFmtCvt) {
                switch (format[i]) {
                    case    '%': {
                            lookingAtFmtCvt = false;
                        }
                        break;
                    case    's': {
                            newFormat[newFormatIdx] = 'l';
                            newFormatIdx++;
                        }
                        break;
                    case    '.': {
                            // could still be part for format string
                        }
                        break;
                    default: {
                            if (isdigit (format[i])) {
                                // could still be part for format string
                            }
                            else {
                                lookingAtFmtCvt = false;    // DONE
                            }
                        }
                        break;
                }
            }
            else {
                if (format[i] == '%') {
                    lookingAtFmtCvt = true;
                }
            }
            newFormat[newFormatIdx] = format[i];
            newFormatIdx++;
        }
        Assert (newFormatIdx >= origFormatLen);
        if (newFormatIdx > origFormatLen) {
            newFormat[newFormatIdx] = '\0';
            useFormat   =   newFormat;
        }
    }
#endif

#if     qSupportValgrindQuirks
    // Makes little sense - even msgBuf[0] not sufficient - but this silences lots of warnings.
    // -- LGP 2012-05-19
    memset (msgBuf, 0, sizeof (msgBuf[0]) * msgBuf.GetSize());
#endif

    // Assume only reason for failure is not enuf bytes, so allocate more.
    // If I'm wrong, we'll just runout of memory and throw out...
    while (::vswprintf (msgBuf, msgBuf.GetSize (), useFormat, argsList) < 0) {
        msgBuf.GrowToSize (msgBuf.GetSize () * 2);
    }
    Assert (::wcslen (msgBuf) < msgBuf.GetSize ());
    return wstring (msgBuf);
}

wstring Characters::Format (const wchar_t* format, ...)
{
    va_list     argsList;
    va_start (argsList, format);
    wstring tmp = FormatV (format, argsList);
    va_end (argsList);
    return tmp;
}

/*
 ********************************************************************************
 ****************************** HexString2Int ***********************************
 ********************************************************************************
 */
int Characters::HexString2Int (const string& s)
{
    return ::strtol (s.c_str (), nullptr, 16);
}

int Characters::HexString2Int (const wstring& s)
{
    // http://msdn.microsoft.com/en-us/library/w4z2wdyc(v=vs.80).aspx
    // http://pubs.opengroup.org/onlinepubs/009695399/functions/wcstol.html
    return ::wcstol (s.c_str (), nullptr, 16);
}

/*
 ********************************************************************************
 ********************************* String2Int ***********************************
 ********************************************************************************
 */
int Characters::String2Int (const string& s)
{
    return ::atol (s.c_str ());
}

int Characters::String2Int (const wstring& s)
{
#if     defined (_MSC_VER)
    return ::_wtol (s.c_str ());
#else
    // unclear if this is good/safe - cuz of - for example - funky wide japanese numbers etc... probaby must do better
    // Also note use WideStringToNarrowSDKString() instead of WideStringToASCII - cuz the later asserts all valid ascii chars which may not be true here...
    //      -- LGP 2011-08-18
    return String2Int (WideStringToNarrowSDKString (s));
#endif
}

/*
 ********************************************************************************
 ********************************* String2Float *********************************
 ********************************************************************************
 */
double  Characters::String2Float (const wstring& s)
{
    static  const   double  kBADVAL =   static_cast<double> (Math::nan ());
    return String2Float (s, kBADVAL);
}

double  Characters::String2Float (const wstring& s, double returnValIfInvalidString)
{
    double  num =   returnValIfInvalidString;
#pragma warning (push)
#pragma warning (4 : 4996)      // MSVC SILLY WARNING ABOUT USING swscanf_s
    if (::swscanf (s.c_str (), L"%lf", &num) == 1) {
        return num;
    }
#pragma warning (pop)
    return returnValIfInvalidString;
}

/*
 ********************************************************************************
 ********************************* Float2String *********************************
 ********************************************************************************
 */
wstring Characters::Float2String (double f, unsigned int precision)
{
    if (std::isnan (f)) {
        return wstring ();
    }
    stringstream s;
    s << setprecision (precision) << f;
    wstring r = ASCIIStringToWide (s.str ());
    return r;
}

<|endoftext|>


<commit_before>#include "pch.h"
#include "BlockBurstMain.h"
#include "Common\DirectXHelper.h"

using namespace BlockBurst;

using namespace DirectX;
using namespace Windows::Foundation;
using namespace Windows::System::Threading;
using namespace Concurrency;

// Loads and initializes application assets when the application is loaded.
BlockBurstMain::BlockBurstMain(const std::shared_ptr<DX::DeviceResources>& deviceResources) :
	m_deviceResources(deviceResources)
{
	// Register to be notified if the Device is lost or recreated
	m_deviceResources->RegisterDeviceNotify(this);

	// TODO: Replace this with your app's content initialization.
	m_sceneRenderer = std::unique_ptr<Sample3DSceneRenderer>(new Sample3DSceneRenderer(m_deviceResources));

	m_fpsTextRenderer = std::unique_ptr<SampleFpsTextRenderer>(new SampleFpsTextRenderer(m_deviceResources));

	// TODO: Change the timer settings if you want something other than the default variable timestep mode.
	// e.g. for 60 FPS fixed timestep update logic, call:
	/*
	m_timer.SetFixedTimeStep(true);
	m_timer.SetTargetElapsedSeconds(1.0 / 60);
	*/

	this->blocks = std::make_shared<std::vector<Block>>();
}

BlockBurstMain::~BlockBurstMain()
{
	// Deregister device notification
	m_deviceResources->RegisterDeviceNotify(nullptr);
}

// Updates application state when the window size changes (e.g. device orientation change)
void BlockBurstMain::CreateWindowSizeDependentResources()
{
	// TODO: Replace this with the size-dependent initialization of your app's content.
	m_sceneRenderer->CreateWindowSizeDependentResources();
}

// Updates the application state once per frame.
void BlockBurstMain::Update()
{
	if (!this->initialized)
	{
		if (this->m_sceneRenderer->IsInitialized())
		{
			this->CreateBlock(-3.0f, 0.0f, 0.0f);
			this->CreateBlock(3.0f, 0.0f, 0.0f);

			this->m_sceneRenderer->BuildGPUBuffers(this->blocks);

			this->initialized = true;
		}

		return;
	}

	// Update scene objects.
	m_timer.Tick([&]()
	{
		// Convert degrees to radians, then convert seconds to rotation angle
		float radiansPerSecond = XMConvertToRadians(45);
		double totalRotation = m_timer.GetTotalSeconds() * radiansPerSecond;
		float radians = static_cast<float>(fmod(totalRotation, XM_2PI));

		for (auto it = this->blocks->begin(); it != this->blocks->end(); ++it)
		{
			Block& block = *it;
			block.rotation = radians;
		}

		// TODO: Replace this with your app's content update functions.
		m_sceneRenderer->Update(m_timer);
		m_fpsTextRenderer->Update(m_timer);
	});
}

// Renders the current frame according to the current application state.
// Returns true if the frame was rendered and is ready to be displayed.
bool BlockBurstMain::Render()
{
	// Don't try to render anything before the first Update.
	if (m_timer.GetFrameCount() == 0)
	{
		return false;
	}

	auto context = m_deviceResources->GetD3DDeviceContext();

	// Reset the viewport to target the whole screen.
	auto viewport = m_deviceResources->GetScreenViewport();
	context->RSSetViewports(1, &viewport);

	// Reset render targets to the screen.
	ID3D11RenderTargetView *const targets[1] = { m_deviceResources->GetBackBufferRenderTargetView() };
	context->OMSetRenderTargets(1, targets, m_deviceResources->GetDepthStencilView());

	// Clear the back buffer and depth stencil view.
	context->ClearRenderTargetView(m_deviceResources->GetBackBufferRenderTargetView(), DirectX::Colors::CornflowerBlue);
	context->ClearDepthStencilView(m_deviceResources->GetDepthStencilView(), D3D11_CLEAR_DEPTH | D3D11_CLEAR_STENCIL, 1.0f, 0);

	// Render the scene objects.
	// TODO: Replace this with your app's content rendering functions.
	m_sceneRenderer->Render();
	m_fpsTextRenderer->Render();

	return true;
}

void BlockBurstMain::OnTap(float screenPositionX, float screenPositionY)
{
}

// Notifies renderers that device resources need to be released.
void BlockBurstMain::OnDeviceLost()
{
	m_sceneRenderer->ReleaseDeviceDependentResources();
	m_fpsTextRenderer->ReleaseDeviceDependentResources();
}

// Notifies renderers that device resources may now be recreated.
void BlockBurstMain::OnDeviceRestored()
{
	m_sceneRenderer->CreateDeviceDependentResources();
	m_fpsTextRenderer->CreateDeviceDependentResources();
	CreateWindowSizeDependentResources();
}

void BlockBurstMain::CreateBlock(float posX, float posY, float posZ)
{
	auto block = Block();

	block.posX = posX;
	block.posY = posY;
	block.posZ = posZ;

	block.vertices[0] = VertexPositionColor{ XMFLOAT3(-0.5f, -0.5f, -0.5f), XMFLOAT3(0.0f, 0.0f, 0.0f) };
	block.vertices[1] = VertexPositionColor{ XMFLOAT3(-0.5f, -0.5f, +0.5f), XMFLOAT3(0.0f, 0.0f, 1.0f) };
	block.vertices[2] = VertexPositionColor{ XMFLOAT3(-0.5f, +0.5f, -0.5f), XMFLOAT3(0.0f, 1.0f, 0.0f) };
	block.vertices[3] = VertexPositionColor{ XMFLOAT3(-0.5f, +0.5f, +0.5f), XMFLOAT3(0.0f, 1.0f, 1.0f) };
	block.vertices[4] = VertexPositionColor{ XMFLOAT3(+0.5f, -0.5f, -0.5f), XMFLOAT3(1.0f, 0.0f, 0.0f) };
	block.vertices[5] = VertexPositionColor{ XMFLOAT3(+0.5f, -0.5f, +0.5f), XMFLOAT3(1.0f, 0.0f, 1.0f) };
	block.vertices[6] = VertexPositionColor{ XMFLOAT3(+0.5f, +0.5f, -0.5f), XMFLOAT3(1.0f, 1.0f, 0.0f) };
	block.vertices[7] = VertexPositionColor{ XMFLOAT3(+0.5f, +0.5f, +0.5f), XMFLOAT3(1.0f, 1.0f, 1.0f) };

	this->blocks->push_back(block);
}<commit_msg>ADDED: Blocks - Removing closest block on tap and adding two new ones.<commit_after>#include "pch.h"
#include "BlockBurstMain.h"
#include "Common\DirectXHelper.h"

using namespace BlockBurst;

using namespace DirectX;
using namespace Windows::Foundation;
using namespace Windows::System::Threading;
using namespace Concurrency;

// Loads and initializes application assets when the application is loaded.
BlockBurstMain::BlockBurstMain(const std::shared_ptr<DX::DeviceResources>& deviceResources) :
	m_deviceResources(deviceResources)
{
	// Register to be notified if the Device is lost or recreated
	m_deviceResources->RegisterDeviceNotify(this);

	// TODO: Replace this with your app's content initialization.
	m_sceneRenderer = std::unique_ptr<Sample3DSceneRenderer>(new Sample3DSceneRenderer(m_deviceResources));

	m_fpsTextRenderer = std::unique_ptr<SampleFpsTextRenderer>(new SampleFpsTextRenderer(m_deviceResources));

	// TODO: Change the timer settings if you want something other than the default variable timestep mode.
	// e.g. for 60 FPS fixed timestep update logic, call:
	/*
	m_timer.SetFixedTimeStep(true);
	m_timer.SetTargetElapsedSeconds(1.0 / 60);
	*/

	this->blocks = std::make_shared<std::vector<Block>>();
}

BlockBurstMain::~BlockBurstMain()
{
	// Deregister device notification
	m_deviceResources->RegisterDeviceNotify(nullptr);
}

// Updates application state when the window size changes (e.g. device orientation change)
void BlockBurstMain::CreateWindowSizeDependentResources()
{
	// TODO: Replace this with the size-dependent initialization of your app's content.
	m_sceneRenderer->CreateWindowSizeDependentResources();
}

// Updates the application state once per frame.
void BlockBurstMain::Update()
{
	if (!this->initialized)
	{
		if (this->m_sceneRenderer->IsInitialized())
		{
			this->CreateBlock(-3.0f, 0.0f, 0.0f);
			this->CreateBlock(3.0f, 0.0f, 0.0f);

			this->m_sceneRenderer->BuildGPUBuffers(this->blocks);

			this->initialized = true;
		}

		return;
	}

	// Update scene objects.
	m_timer.Tick([&]()
	{
		// Convert degrees to radians, then convert seconds to rotation angle
		float radiansPerSecond = XMConvertToRadians(45);
		double totalRotation = m_timer.GetTotalSeconds() * radiansPerSecond;
		float radians = static_cast<float>(fmod(totalRotation, XM_2PI));

		for (auto it = this->blocks->begin(); it != this->blocks->end(); ++it)
		{
			Block& block = *it;
			block.rotation = radians;
		}

		// TODO: Replace this with your app's content update functions.
		m_sceneRenderer->Update(m_timer);
		m_fpsTextRenderer->Update(m_timer);
	});
}

// Renders the current frame according to the current application state.
// Returns true if the frame was rendered and is ready to be displayed.
bool BlockBurstMain::Render()
{
	// Don't try to render anything before the first Update.
	if (m_timer.GetFrameCount() == 0)
	{
		return false;
	}

	auto context = m_deviceResources->GetD3DDeviceContext();

	// Reset the viewport to target the whole screen.
	auto viewport = m_deviceResources->GetScreenViewport();
	context->RSSetViewports(1, &viewport);

	// Reset render targets to the screen.
	ID3D11RenderTargetView *const targets[1] = { m_deviceResources->GetBackBufferRenderTargetView() };
	context->OMSetRenderTargets(1, targets, m_deviceResources->GetDepthStencilView());

	// Clear the back buffer and depth stencil view.
	context->ClearRenderTargetView(m_deviceResources->GetBackBufferRenderTargetView(), DirectX::Colors::CornflowerBlue);
	context->ClearDepthStencilView(m_deviceResources->GetDepthStencilView(), D3D11_CLEAR_DEPTH | D3D11_CLEAR_STENCIL, 1.0f, 0);

	// Render the scene objects.
	// TODO: Replace this with your app's content rendering functions.
	m_sceneRenderer->Render();
	m_fpsTextRenderer->Render();

	return true;
}

void BlockBurstMain::OnTap(float screenPositionX, float screenPositionY)
{
	if (this->blocks->empty())
	{
		return;
	}

	auto closestBlockIt = this->blocks->begin();

	// Find closest block.
	for (auto it = this->blocks->begin(); it != this->blocks->end(); ++it)
	{
		if ((*it).posZ < (*closestBlockIt).posZ)
		{
			closestBlockIt = it;
		}
	}

	// Get spawn position for new block.
	Block& closestBlock = *closestBlockIt;
	auto x = closestBlock.posX;
	auto y = closestBlock.posY;
	auto z = closestBlock.posZ;

	// Remove closest block.
	this->blocks->erase(closestBlockIt);

	// Add two new blocks.
	this->CreateBlock(x - 1, y, z);
	this->CreateBlock(x + 1, y, z);

	// Rebuild vertex and index buffers.
	this->m_sceneRenderer->BuildGPUBuffers(this->blocks);
}

// Notifies renderers that device resources need to be released.
void BlockBurstMain::OnDeviceLost()
{
	m_sceneRenderer->ReleaseDeviceDependentResources();
	m_fpsTextRenderer->ReleaseDeviceDependentResources();
}

// Notifies renderers that device resources may now be recreated.
void BlockBurstMain::OnDeviceRestored()
{
	m_sceneRenderer->CreateDeviceDependentResources();
	m_fpsTextRenderer->CreateDeviceDependentResources();
	CreateWindowSizeDependentResources();
}

void BlockBurstMain::CreateBlock(float posX, float posY, float posZ)
{
	auto block = Block();

	block.posX = posX;
	block.posY = posY;
	block.posZ = posZ;

	block.vertices[0] = VertexPositionColor{ XMFLOAT3(-0.5f, -0.5f, -0.5f), XMFLOAT3(0.0f, 0.0f, 0.0f) };
	block.vertices[1] = VertexPositionColor{ XMFLOAT3(-0.5f, -0.5f, +0.5f), XMFLOAT3(0.0f, 0.0f, 1.0f) };
	block.vertices[2] = VertexPositionColor{ XMFLOAT3(-0.5f, +0.5f, -0.5f), XMFLOAT3(0.0f, 1.0f, 0.0f) };
	block.vertices[3] = VertexPositionColor{ XMFLOAT3(-0.5f, +0.5f, +0.5f), XMFLOAT3(0.0f, 1.0f, 1.0f) };
	block.vertices[4] = VertexPositionColor{ XMFLOAT3(+0.5f, -0.5f, -0.5f), XMFLOAT3(1.0f, 0.0f, 0.0f) };
	block.vertices[5] = VertexPositionColor{ XMFLOAT3(+0.5f, -0.5f, +0.5f), XMFLOAT3(1.0f, 0.0f, 1.0f) };
	block.vertices[6] = VertexPositionColor{ XMFLOAT3(+0.5f, +0.5f, -0.5f), XMFLOAT3(1.0f, 1.0f, 0.0f) };
	block.vertices[7] = VertexPositionColor{ XMFLOAT3(+0.5f, +0.5f, +0.5f), XMFLOAT3(1.0f, 1.0f, 1.0f) };

	this->blocks->push_back(block);
}<|endoftext|>


<commit_before>/*
 * Copyright(c) Sophist Solutions, Inc. 1990-2019.  All rights reserved
 */
#include "../StroikaPreComp.h"

#include <algorithm>
#include <cstdlib>

#include "../../Foundation/Characters/Format.h"
#include "../../Foundation/Characters/String2Int.h"
#include "../../Foundation/Characters/StringBuilder.h"
#include "../../Foundation/Characters/ToString.h"
#include "../../Foundation/Containers/Common.h"
#include "../../Foundation/DataExchange/BadFormatException.h"
#include "../../Foundation/Debug/Assertions.h"
#include "../../Foundation/Debug/Trace.h"
#include "../../Foundation/Execution/Throw.h"
#include "../../Foundation/IO/Network/HTTP/Headers.h"
#include "../../Foundation/IO/Network/HTTP/Versions.h"
#include "../../Foundation/Memory/SmallStackBuffer.h"
#include "../../Foundation/Streams/InputSubStream.h"
#include "../../Foundation/Streams/MemoryStream.h"

#include "Request.h"

using std::byte;

using namespace Stroika::Foundation;
using namespace Stroika::Foundation::Characters;
using namespace Stroika::Foundation::Containers;
using namespace Stroika::Foundation::Memory;
using namespace Stroika::Foundation::Streams;

using namespace Stroika::Frameworks;
using namespace Stroika::Frameworks::WebServer;

// Comment this in to turn on aggressive noisy DbgTrace in this module
//#define   USE_NOISY_TRACE_IN_THIS_MODULE_       1

/*
 ********************************************************************************
 ************************* WebServer::Request ***********************************
 ********************************************************************************
 */
Request::Request (const Streams::InputStream<byte>::Ptr& inStream)
    : fInputStream_ (inStream)
    , fHTTPVersion_ ()
    , fURL_ ()
    , fHeaders_ ()
{
}

void Request::SetHTTPVersion (const String& versionOrVersionLabel)
{
    lock_guard<const AssertExternallySynchronizedLock> critSec{*this};
    static const String_Constant                       kLabeled_10_{L"HTTP/1.0"};
    static const String_Constant                       kLabeled_11_{L"HTTP/1.1"};
    auto                                               versionStringComparer = String::EqualsComparer{Characters::CompareOptions::eCaseInsensitive};
    if (versionOrVersionLabel == kLabeled_11_ or versionOrVersionLabel == IO::Network::HTTP::Versions::kOnePointOne or versionStringComparer (versionOrVersionLabel, kLabeled_11_)) {
        fHTTPVersion_ = IO::Network::HTTP::Versions::kOnePointOne;
    }
    else if (versionOrVersionLabel == kLabeled_10_ or versionOrVersionLabel == IO::Network::HTTP::Versions::kOnePointZero or versionStringComparer (versionOrVersionLabel, kLabeled_10_)) {
        fHTTPVersion_ = IO::Network::HTTP::Versions::kOnePointZero;
    }
    else if (versionOrVersionLabel.StartsWith (L"HTTP/", Characters::CompareOptions::eCaseInsensitive)) {
        fHTTPVersion_ = versionOrVersionLabel.SubString (5);
    }
    else {
        fHTTPVersion_ = versionOrVersionLabel;
    }
}

bool Request::GetKeepAliveRequested () const
{
    if (auto connectionHdr = this->fHeaders_.Lookup (IO::Network::HTTP::HeaderName::kConnection)) {
        return connectionHdr->Equals (L"Keep-Alive", Characters::CompareOptions::eCaseInsensitive);
    }
    // @todo convert version to number and compare that way
    return fHTTPVersion_ == IO::Network::HTTP::Versions::kOnePointOne;
}

Memory::BLOB Request::GetBody ()
{
#if USE_NOISY_TRACE_IN_THIS_MODULE_
    Debug::TraceContextBumper ctx (L"Request::GetBody");
#endif
    lock_guard<const AssertExternallySynchronizedLock> critSec{*this};
    if (not fBody_.has_value ()) {
        fBody_ = GetBodyStream ().ReadAll ();
    }
    return *fBody_;
}

optional<uint64_t> Request::GetContentLength () const
{
    shared_lock<const AssertExternallySynchronizedLock> critSec{*this};
    if (auto ci = fHeaders_.Lookup (IO::Network::HTTP::HeaderName::kContentLength)) {
        return Characters::String2Int<uint64_t> (*ci);
    }
    else {
        return nullopt;
    }
}

optional<InternetMediaType> Request::GetContentType () const
{
    shared_lock<const AssertExternallySynchronizedLock> critSec{*this};
    if (auto ci = fHeaders_.Lookup (IO::Network::HTTP::HeaderName::kContentType)) {
        return InternetMediaType{*ci};
    }
    else {
        return nullopt;
    }
}

Streams::InputStream<byte>::Ptr Request::GetBodyStream ()
{
#if USE_NOISY_TRACE_IN_THIS_MODULE_
    Debug::TraceContextBumper ctx (L"Request::GetBodyStream");
#endif
    lock_guard<const AssertExternallySynchronizedLock> critSec{*this};
    if (fBodyInputStream_ == nullptr) {
        /*
         *  According to https://www.w3.org/Protocols/rfc2616/rfc2616-sec4.html:
         *      The presence of a message-body in a request is signaled by the inclusion of
         *      a Content-Length or Transfer-Encoding header field in the request's message-headers
         */
        // if we have a content-length, read that many bytes.
        if (optional<uint64_t> contentLength = GetContentLength ()) {
            fBodyInputStream_ = InputSubStream<byte>::New (fInputStream_, {}, fInputStream_.GetOffset () + static_cast<size_t> (*contentLength));
        }
        else {
            /*
             *  @todo FIX - WRONG!!!! - MUST SUPPORT TRANSFER ENCODING IN THIS CASE OR NOTHING
             *
             *  https://www.w3.org/Protocols/rfc2616/rfc2616-sec4.html
             *      The rules for when a message-body is allowed in a message differ for requests and responses.
             *
             *      The presence of a message-body in a request is signaled by the inclusion of a Content-Length
             *      or Transfer-Encoding header field in the request's message-headers/
             *
             *  For now - EMPTY is a better failure mode than reading everything and hanging...
             */
            fBodyInputStream_ = MemoryStream<byte>::New ();
        }
    }
    return fBodyInputStream_;
}

String Request::ToString () const
{
    shared_lock<const AssertExternallySynchronizedLock> critSec{*this};
    StringBuilder                                       sb;
    sb += L"{";
    sb += L"HTTPVersion: " + fHTTPVersion_ + L", ";
    sb += L"Method: " + fMethod_ + L", ";
    sb += L"URL: '" + Characters::ToString (fURL_) + L"', ";
    sb += L"Headers: " + Characters::ToString (fHeaders_) + L", ";
    sb += L"}";
    return sb.str ();
}
<commit_msg>more String::EqualsComparer cleanups<commit_after>/*
 * Copyright(c) Sophist Solutions, Inc. 1990-2019.  All rights reserved
 */
#include "../StroikaPreComp.h"

#include <algorithm>
#include <cstdlib>

#include "../../Foundation/Characters/Format.h"
#include "../../Foundation/Characters/String2Int.h"
#include "../../Foundation/Characters/StringBuilder.h"
#include "../../Foundation/Characters/ToString.h"
#include "../../Foundation/Containers/Common.h"
#include "../../Foundation/DataExchange/BadFormatException.h"
#include "../../Foundation/Debug/Assertions.h"
#include "../../Foundation/Debug/Trace.h"
#include "../../Foundation/Execution/Throw.h"
#include "../../Foundation/IO/Network/HTTP/Headers.h"
#include "../../Foundation/IO/Network/HTTP/Versions.h"
#include "../../Foundation/Memory/SmallStackBuffer.h"
#include "../../Foundation/Streams/InputSubStream.h"
#include "../../Foundation/Streams/MemoryStream.h"

#include "Request.h"

using std::byte;

using namespace Stroika::Foundation;
using namespace Stroika::Foundation::Characters;
using namespace Stroika::Foundation::Containers;
using namespace Stroika::Foundation::Memory;
using namespace Stroika::Foundation::Streams;

using namespace Stroika::Frameworks;
using namespace Stroika::Frameworks::WebServer;

// Comment this in to turn on aggressive noisy DbgTrace in this module
//#define   USE_NOISY_TRACE_IN_THIS_MODULE_       1

/*
 ********************************************************************************
 ************************* WebServer::Request ***********************************
 ********************************************************************************
 */
Request::Request (const Streams::InputStream<byte>::Ptr& inStream)
    : fInputStream_ (inStream)
    , fHTTPVersion_ ()
    , fURL_ ()
    , fHeaders_ ()
{
}

void Request::SetHTTPVersion (const String& versionOrVersionLabel)
{
    lock_guard<const AssertExternallySynchronizedLock> critSec{*this};
    static const String_Constant                       kLabeled_10_{L"HTTP/1.0"};
    static const String_Constant                       kLabeled_11_{L"HTTP/1.1"};
    auto                                               versionStringComparer = String::EqualsComparer{Characters::CompareOptions::eCaseInsensitive};
    if (versionOrVersionLabel == kLabeled_11_ or versionOrVersionLabel == IO::Network::HTTP::Versions::kOnePointOne or versionStringComparer (versionOrVersionLabel, kLabeled_11_)) {
        fHTTPVersion_ = IO::Network::HTTP::Versions::kOnePointOne;
    }
    else if (versionOrVersionLabel == kLabeled_10_ or versionOrVersionLabel == IO::Network::HTTP::Versions::kOnePointZero or versionStringComparer (versionOrVersionLabel, kLabeled_10_)) {
        fHTTPVersion_ = IO::Network::HTTP::Versions::kOnePointZero;
    }
    else if (versionOrVersionLabel.StartsWith (L"HTTP/", Characters::CompareOptions::eCaseInsensitive)) {
        fHTTPVersion_ = versionOrVersionLabel.SubString (5);
    }
    else {
        fHTTPVersion_ = versionOrVersionLabel;
    }
}

bool Request::GetKeepAliveRequested () const
{
    if (auto connectionHdr = this->fHeaders_.Lookup (IO::Network::HTTP::HeaderName::kConnection)) {
        return String::EqualsComparer{CompareOptions::eCaseInsensitive}(*connectionHdr, L"Keep-Alive");
    }
    // @todo convert version to number and compare that way
    return fHTTPVersion_ == IO::Network::HTTP::Versions::kOnePointOne;
}

Memory::BLOB Request::GetBody ()
{
#if USE_NOISY_TRACE_IN_THIS_MODULE_
    Debug::TraceContextBumper ctx (L"Request::GetBody");
#endif
    lock_guard<const AssertExternallySynchronizedLock> critSec{*this};
    if (not fBody_.has_value ()) {
        fBody_ = GetBodyStream ().ReadAll ();
    }
    return *fBody_;
}

optional<uint64_t> Request::GetContentLength () const
{
    shared_lock<const AssertExternallySynchronizedLock> critSec{*this};
    if (auto ci = fHeaders_.Lookup (IO::Network::HTTP::HeaderName::kContentLength)) {
        return Characters::String2Int<uint64_t> (*ci);
    }
    else {
        return nullopt;
    }
}

optional<InternetMediaType> Request::GetContentType () const
{
    shared_lock<const AssertExternallySynchronizedLock> critSec{*this};
    if (auto ci = fHeaders_.Lookup (IO::Network::HTTP::HeaderName::kContentType)) {
        return InternetMediaType{*ci};
    }
    else {
        return nullopt;
    }
}

Streams::InputStream<byte>::Ptr Request::GetBodyStream ()
{
#if USE_NOISY_TRACE_IN_THIS_MODULE_
    Debug::TraceContextBumper ctx (L"Request::GetBodyStream");
#endif
    lock_guard<const AssertExternallySynchronizedLock> critSec{*this};
    if (fBodyInputStream_ == nullptr) {
        /*
         *  According to https://www.w3.org/Protocols/rfc2616/rfc2616-sec4.html:
         *      The presence of a message-body in a request is signaled by the inclusion of
         *      a Content-Length or Transfer-Encoding header field in the request's message-headers
         */
        // if we have a content-length, read that many bytes.
        if (optional<uint64_t> contentLength = GetContentLength ()) {
            fBodyInputStream_ = InputSubStream<byte>::New (fInputStream_, {}, fInputStream_.GetOffset () + static_cast<size_t> (*contentLength));
        }
        else {
            /*
             *  @todo FIX - WRONG!!!! - MUST SUPPORT TRANSFER ENCODING IN THIS CASE OR NOTHING
             *
             *  https://www.w3.org/Protocols/rfc2616/rfc2616-sec4.html
             *      The rules for when a message-body is allowed in a message differ for requests and responses.
             *
             *      The presence of a message-body in a request is signaled by the inclusion of a Content-Length
             *      or Transfer-Encoding header field in the request's message-headers/
             *
             *  For now - EMPTY is a better failure mode than reading everything and hanging...
             */
            fBodyInputStream_ = MemoryStream<byte>::New ();
        }
    }
    return fBodyInputStream_;
}

String Request::ToString () const
{
    shared_lock<const AssertExternallySynchronizedLock> critSec{*this};
    StringBuilder                                       sb;
    sb += L"{";
    sb += L"HTTPVersion: " + fHTTPVersion_ + L", ";
    sb += L"Method: " + fMethod_ + L", ";
    sb += L"URL: '" + Characters::ToString (fURL_) + L"', ";
    sb += L"Headers: " + Characters::ToString (fHeaders_) + L", ";
    sb += L"}";
    return sb.str ();
}
<|endoftext|>


<commit_before>/* IBM_PROLOG_BEGIN_TAG                                                   */
/* This is an automatically generated prolog.                             */
/*                                                                        */
/* $Source: src/import/chips/p9/procedures/hwp/pm/p9_pm_recovery_ffdc_sgpe.H $ */
/*                                                                        */
/* 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                                                     */
#ifndef __PM_RECOVERY_FFDC_SGPE_
#define __PM_RECOVERY_FFDC_SGPE_

///
/// @file   p9_pm_recovery_ffdc_sgpe.H
/// @brief  Models SGPE platform for the FFDC collection of PM complex
///
/// *HWP HWP Owner:      Greg Still <stillgs@us.ibm.com>
/// *HWP FW Owner:       Prem S Jha <premjha2@in.ibm.com>
/// *HWP Team:           PM
/// *HWP Level:          2
/// *HWP Consumed by:    Hostboot
//
// *INDENT-OFF*
//--------------------------------------------------------------------------
// Includes
//--------------------------------------------------------------------------
#include <fapi2.H>
#include <stdint.h>
#include <p9_pm_recovery_ffdc_base.H>

namespace p9_stop_recov_ffdc
{

    class PlatSgpe : public PlatPmComplex
    {
            public:
            /// @brief  constructor
            PlatSgpe( const fapi2::Target< fapi2::TARGET_TYPE_PROC_CHIP > i_procChipTgt );

            /// @brief  destructor
            virtual ~PlatSgpe() { };

            /// @brief      collects FFDC pertaining to all functional SGPEs in the chip.
            /// @param[in]  i_pHomerBuf     points to base of P9 HOMER.
            /// @return     fapi2 return code.
            fapi2::ReturnCode collectFfdc( void* i_pHomerBuf );

        private:
            /// @brief      collects trace info from SGPE's SRAM buffer.
            /// @param[in]  i_pHomerBuf     points to location of HOMER meant for SGPE Trace info.
            /// @return     fapi2 return code.
            fapi2::ReturnCode  collectTrace( uint8_t * i_pHomerBuf );

            /// @brief      collects  global variables from SGPE's's SRAM.
            /// @param[in]  i_pHomerBuf     points to location of HOMER meant for SGPE's global variable
            /// @return     fapi2 return code.
            fapi2::ReturnCode  collectGlobals( uint8_t * i_pHomerBuf );

            /// @brief      collects internal register info for a SGPE
            /// @param[in]  i_pHomerBuf     points to location of HOMER meant for SGPE internal register.
            /// @return     fapi2 return code.
            fapi2::ReturnCode  collectInternalReg( uint8_t * i_pHomerBuf );

            /// @brief      collects SGPE Image Header info from SGPE SRAM buffer.
            /// @param[in]  i_pHomerBuf     points to location of HOMER meant for SGPE's header.
            /// @return     fapi2 return code.
            fapi2::ReturnCode  collectImageHeader( uint8_t * i_pHomerBuf );

            /// @brief updates the SGPE FFDC Header
            ///@param[in]   i_pHomerBuf     points to a location in HOMER meant for SGPE FFDC Header
            ///param[in]    i_ffdcValid     bit vector summarizing FFDC validity
            ///@param[in]   i_haltCondition hlat state of SGPE
            ///@return      fapi2 return code.
            ///@note        refer to PPE Spec for details on halt state.

            fapi2::ReturnCode updateSgpeFfdcHeader( uint8_t * i_pHomerBuf,
                                                    uint8_t i_ffdcValid, uint8_t i_haltCondition );

            ///@brief returns type of platform
            PmComplexPlatId getPlatType() { return iv_plat; }

        private:
            PmComplexPlatId iv_plat;
    };

extern "C"
{
    typedef fapi2::ReturnCode( *p9_pm_recovery_ffdc_sgpe_FP_t )
            ( const fapi2::Target< fapi2::TARGET_TYPE_PROC_CHIP > & i_procChipTgt,
              void * i_sgpeFfdcBuf );
}

} //namespace p9_stop_recov_ffdc ends

#endif //__PM_RECOVERY_FFDC_SGPE_
<commit_msg>STOP Recovery: Misc infra. updates to enable PM FFDC in HOMER<commit_after>/* IBM_PROLOG_BEGIN_TAG                                                   */
/* This is an automatically generated prolog.                             */
/*                                                                        */
/* $Source: src/import/chips/p9/procedures/hwp/pm/p9_pm_recovery_ffdc_sgpe.H $ */
/*                                                                        */
/* 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                                                     */
#ifndef __PM_RECOVERY_FFDC_SGPE_
#define __PM_RECOVERY_FFDC_SGPE_

///
/// @file   p9_pm_recovery_ffdc_sgpe.H
/// @brief  Models SGPE platform for the FFDC collection of PM complex
///
/// *HWP HWP Owner:      Greg Still <stillgs@us.ibm.com>
/// *HWP FW Owner:       Prem S Jha <premjha2@in.ibm.com>
/// *HWP Team:           PM
/// *HWP Level:          2
/// *HWP Consumed by:    Hostboot
//
// *INDENT-OFF*
//--------------------------------------------------------------------------
// Includes
//--------------------------------------------------------------------------
#include <fapi2.H>
#include <stdint.h>
#include <p9_pm_recovery_ffdc_base.H>

namespace p9_stop_recov_ffdc
{

    class PlatSgpe : public PlatPmComplex
    {
            public:
            /// @brief  constructor
            PlatSgpe( const fapi2::Target< fapi2::TARGET_TYPE_PROC_CHIP > i_procChipTgt );

            /// @brief  destructor
            virtual ~PlatSgpe() { };

            /// @brief      Initializes the SGPE FFDC Sub-Section in HOMER with default header
            /// @param[in]  i_pHomerBuf  points to base of P9 HOMER.
            ///  @return     fapi2 return code
            fapi2::ReturnCode init ( void* i_pHomerBuf );

            /// @brief      collects FFDC pertaining to all functional SGPEs in the chip.
            /// @param[in]  i_pHomerBuf   points to base of P9 HOMER.
            /// @param[in]  i_ffdcType    indicates the content type to collect
            /// @return     fapi2 return code.
            fapi2::ReturnCode collectFfdc( void*   i_pHomerBuf,
                                           uint8_t i_ffdcType = ALL );

        private:
            /// @brief      collects trace info from SGPE's SRAM buffer.
            /// @param[in]  i_pHomerBuf     points to location of HOMER meant for SGPE Trace info.
            /// @return     fapi2 return code.
            fapi2::ReturnCode  collectTrace( uint8_t * i_pHomerBuf );

            /// @brief      collects  global variables from SGPE's's SRAM.
            /// @param[in]  i_pHomerBuf     points to location of HOMER meant for SGPE's global variable
            /// @return     fapi2 return code.
            fapi2::ReturnCode  collectGlobals( uint8_t * i_pHomerBuf );

            /// @brief      collects internal register info for a SGPE
            /// @param[in]  i_pHomerBuf     points to location of HOMER meant for SGPE internal register.
            /// @return     fapi2 return code.
            fapi2::ReturnCode  collectInternalReg( uint8_t * i_pHomerBuf );

            /// @brief      collects SGPE Image Header info from SGPE SRAM buffer.
            /// @param[in]  i_pHomerBuf     points to location of HOMER meant for SGPE's header.
            /// @return     fapi2 return code.
            fapi2::ReturnCode  collectImageHeader( uint8_t * i_pHomerBuf );

            /// @brief updates the SGPE FFDC Header
            ///@param[in]   i_pHomerBuf     points to a location in HOMER meant for SGPE FFDC Header
            ///param[in]    i_sectionsValid bit vector summarizing FFDC validity
            ///@return      fapi2 return code.
            fapi2::ReturnCode updateSgpeFfdcHeader( uint8_t* i_pHomerBuf,
                                                    uint16_t i_sectionsValid );

            ///@brief returns type of platform
            PmComplexPlatId getPlatType() { return iv_plat; }

        private:
            PmComplexPlatId iv_plat;
    };

extern "C"
{
    typedef fapi2::ReturnCode( *p9_pm_recovery_ffdc_sgpe_FP_t )
            ( const fapi2::Target< fapi2::TARGET_TYPE_PROC_CHIP > & i_procChipTgt,
              void * i_sgpeFfdcBuf );
}

} //namespace p9_stop_recov_ffdc ends

#endif //__PM_RECOVERY_FFDC_SGPE_
<|endoftext|>


<commit_before>#pragma once
#include <bts/blockchain/types.hpp>

namespace bts { namespace blockchain {

static std::map<uint32_t, bts::blockchain::block_id_type> CHECKPOINT_BLOCKS
{
    {       1, bts::blockchain::block_id_type( "8523e28fde6eed4eb749a84e28c9c7b56870c9cc" ) },
    {   25001, bts::blockchain::block_id_type( "f5bbb4c5728d809e3d0877354964ea24e9961904" ) },
    {  120001, bts::blockchain::block_id_type( "1557fee97884c893aaebba9a1fed803e7fd005d9" ) },
    {  129601, bts::blockchain::block_id_type( "18bcec3430d35538470d7fddc2a51a28cb71fcde" ) },
    {  172718, bts::blockchain::block_id_type( "e452dd44902bc86110923285da03ac12e8cfbe6f" ) },
    {  173585, bts::blockchain::block_id_type( "1d1695bc8ebd3ebae0168007afb2912269adbef1" ) },
    {  187001, bts::blockchain::block_id_type( "72d06a6ba3e79c02327d8048852f9e51b6c8ea71" ) },
    {  237501, bts::blockchain::block_id_type( "42d7bb317f51082f7faffee3f7c79bf59f47acac" ) },
    {  597000, bts::blockchain::block_id_type( "305ac6a968da84ea53889a5661f0decf5e6dc96b" ) }
};

// Initialized in load_checkpoints()
static uint32_t LAST_CHECKPOINT_BLOCK_NUM = 0;

} } // bts::blockchain
<commit_msg>Update checkpoint<commit_after>#pragma once
#include <bts/blockchain/types.hpp>

namespace bts { namespace blockchain {

static std::map<uint32_t, bts::blockchain::block_id_type> CHECKPOINT_BLOCKS
{
    {       1, bts::blockchain::block_id_type( "8523e28fde6eed4eb749a84e28c9c7b56870c9cc" ) },
    {   25001, bts::blockchain::block_id_type( "f5bbb4c5728d809e3d0877354964ea24e9961904" ) },
    {  120001, bts::blockchain::block_id_type( "1557fee97884c893aaebba9a1fed803e7fd005d9" ) },
    {  129601, bts::blockchain::block_id_type( "18bcec3430d35538470d7fddc2a51a28cb71fcde" ) },
    {  172718, bts::blockchain::block_id_type( "e452dd44902bc86110923285da03ac12e8cfbe6f" ) },
    {  173585, bts::blockchain::block_id_type( "1d1695bc8ebd3ebae0168007afb2912269adbef1" ) },
    {  187001, bts::blockchain::block_id_type( "72d06a6ba3e79c02327d8048852f9e51b6c8ea71" ) },
    {  237501, bts::blockchain::block_id_type( "42d7bb317f51082f7faffee3f7c79bf59f47acac" ) },
    {  616500, bts::blockchain::block_id_type( "68daf28e026c5dea32ba6603045060fa94eac229" ) }
};

// Initialized in load_checkpoints()
static uint32_t LAST_CHECKPOINT_BLOCK_NUM = 0;

} } // bts::blockchain
<|endoftext|>


<commit_before>#pragma once
#include <bts/blockchain/types.hpp>
#include <map>

static std::map<uint32_t, bts::blockchain::block_id_type> CHECKPOINT_BLOCKS
{
    {       1, bts::blockchain::block_id_type( "8abcfb93c52f999e3ef5288c4f837f4f15af5521" ) },
    {  100000, bts::blockchain::block_id_type( "96f98d49722848a6a47ad04aece8b9f93c9e9c23" ) },
    {  200000, bts::blockchain::block_id_type( "222ddc49db592103c51ad22cdc4140185ef564d9" ) },
    {  300000, bts::blockchain::block_id_type( "0d1d0b8f7f1f4590f8e083edc03869383ed74e3e" ) },
    {  400000, bts::blockchain::block_id_type( "053d398b6597d5c61365afd100d87b824bf49f65" ) },
    {  500000, bts::blockchain::block_id_type( "f02910a7115fb826984ce3a432cb371d5d7a99b8" ) },
    {  600000, bts::blockchain::block_id_type( "f278db8722235343c9db9f077fe67c54a5f25f3b" ) },
    {  700000, bts::blockchain::block_id_type( "f120ff9b159661b9ac084a0a69c58dcbd79cbb49" ) },
    {  800000, bts::blockchain::block_id_type( "0e94ad17c598e42e5ec2f522a05bf4df6a1778da" ) },
    {  900000, bts::blockchain::block_id_type( "a78e09bf1fd13bcd7b0959bc0764fe45db0a652d" ) },
    { 1000000, bts::blockchain::block_id_type( "20da1352f86f0fc7d5b42f5e96be86ea5b219b6f" ) },
    { 1100000, bts::blockchain::block_id_type( "bec7da4758ad453a49a9d9d4128acb92a1fdfd04" ) },
    { 1200000, bts::blockchain::block_id_type( "9e514e0f0a17d78be7c0045f9f22a253812c6c92" ) },
    { 1246469, bts::blockchain::block_id_type( "68b7e003ca08d50843faaddcf696cfff1954ede3" ) },
    { 1246900, bts::blockchain::block_id_type( "b5214c1bc914ea5da6c1bb8f774d07f12b85dbe2" ) },
    { 1270000, bts::blockchain::block_id_type( "0bf6c38a0e15265e52bf18ee7266b2855364976a" ) },
    { 1271000, bts::blockchain::block_id_type( "a6778f36cd2714b1a1498b24276e50ae21522383" ) },
    { 1272000, bts::blockchain::block_id_type( "08385a807785da92a123e294eb55658582ed0e2d" ) },
    { 1273000, bts::blockchain::block_id_type( "aefc68ea63cbf9918d99dc5f78d51538e6f81403" ) },
    { 1274000, bts::blockchain::block_id_type( "a32c3e159b6c2dadd86c5bb653bcb82ea9ba4c4f" ) },
    { 1275000, bts::blockchain::block_id_type( "886fcc85c93ac82975001c8004b1fdd546a12830" ) },
    { 1276000, bts::blockchain::block_id_type( "d896248d4954d3c9a99da3c3d8df95a67b2b086d" ) },
    { 1277000, bts::blockchain::block_id_type( "f0781378e5bad23db3d63d441d4122bb20916c46" ) },
    { 1278000, bts::blockchain::block_id_type( "fada9cce13dfd25b562bbd3423e963e42d31adbc" ) },
    { 1279000, bts::blockchain::block_id_type( "038095014c69b1a08e001b499851f17939812b74" ) },
    { 1279500, bts::blockchain::block_id_type( "488313d2c1c85bdec117bac0379f7b17f7cfbed3" ) },
    { 1280000, bts::blockchain::block_id_type( "b65127afd78332cd3d3ce16bb0283d1f172eca7e" ) },
    { 1281000, bts::blockchain::block_id_type( "1227d40a5255928da71870287de910de220bb988" ) },
    { 1282000, bts::blockchain::block_id_type( "5b36e414a65f86c3b98c6d6a6ca9f4de8b04e7af" ) },
    { 1283000, bts::blockchain::block_id_type( "8a680579dc870cff37e2d5e85c6bdb1f63f692ba" ) },
    { 1284000, bts::blockchain::block_id_type( "174621251aea239d512f6228457317dbe0e0537c" ) },
    { 1285000, bts::blockchain::block_id_type( "c55e49c761f3e954b5c3d58f22ae8430dc81a85c" ) },
    { 1286000, bts::blockchain::block_id_type( "d28053c6744cadf39286a9d2a184b8c2493f8d11" ) },
    { 1286500, bts::blockchain::block_id_type( "beef02cfa9d363c33a4d83a8688871b78820f42c" ) }
};
<commit_msg>Add checkpoint<commit_after>#pragma once
#include <bts/blockchain/types.hpp>
#include <map>

static std::map<uint32_t, bts::blockchain::block_id_type> CHECKPOINT_BLOCKS
{
    {       1, bts::blockchain::block_id_type( "8abcfb93c52f999e3ef5288c4f837f4f15af5521" ) },
    {  100000, bts::blockchain::block_id_type( "96f98d49722848a6a47ad04aece8b9f93c9e9c23" ) },
    {  200000, bts::blockchain::block_id_type( "222ddc49db592103c51ad22cdc4140185ef564d9" ) },
    {  300000, bts::blockchain::block_id_type( "0d1d0b8f7f1f4590f8e083edc03869383ed74e3e" ) },
    {  400000, bts::blockchain::block_id_type( "053d398b6597d5c61365afd100d87b824bf49f65" ) },
    {  500000, bts::blockchain::block_id_type( "f02910a7115fb826984ce3a432cb371d5d7a99b8" ) },
    {  600000, bts::blockchain::block_id_type( "f278db8722235343c9db9f077fe67c54a5f25f3b" ) },
    {  700000, bts::blockchain::block_id_type( "f120ff9b159661b9ac084a0a69c58dcbd79cbb49" ) },
    {  800000, bts::blockchain::block_id_type( "0e94ad17c598e42e5ec2f522a05bf4df6a1778da" ) },
    {  900000, bts::blockchain::block_id_type( "a78e09bf1fd13bcd7b0959bc0764fe45db0a652d" ) },
    { 1000000, bts::blockchain::block_id_type( "20da1352f86f0fc7d5b42f5e96be86ea5b219b6f" ) },
    { 1100000, bts::blockchain::block_id_type( "bec7da4758ad453a49a9d9d4128acb92a1fdfd04" ) },
    { 1200000, bts::blockchain::block_id_type( "9e514e0f0a17d78be7c0045f9f22a253812c6c92" ) },
    { 1246469, bts::blockchain::block_id_type( "68b7e003ca08d50843faaddcf696cfff1954ede3" ) },
    { 1246900, bts::blockchain::block_id_type( "b5214c1bc914ea5da6c1bb8f774d07f12b85dbe2" ) },
    { 1270000, bts::blockchain::block_id_type( "0bf6c38a0e15265e52bf18ee7266b2855364976a" ) },
    { 1271000, bts::blockchain::block_id_type( "a6778f36cd2714b1a1498b24276e50ae21522383" ) },
    { 1272000, bts::blockchain::block_id_type( "08385a807785da92a123e294eb55658582ed0e2d" ) },
    { 1273000, bts::blockchain::block_id_type( "aefc68ea63cbf9918d99dc5f78d51538e6f81403" ) },
    { 1274000, bts::blockchain::block_id_type( "a32c3e159b6c2dadd86c5bb653bcb82ea9ba4c4f" ) },
    { 1275000, bts::blockchain::block_id_type( "886fcc85c93ac82975001c8004b1fdd546a12830" ) },
    { 1276000, bts::blockchain::block_id_type( "d896248d4954d3c9a99da3c3d8df95a67b2b086d" ) },
    { 1277000, bts::blockchain::block_id_type( "f0781378e5bad23db3d63d441d4122bb20916c46" ) },
    { 1278000, bts::blockchain::block_id_type( "fada9cce13dfd25b562bbd3423e963e42d31adbc" ) },
    { 1279000, bts::blockchain::block_id_type( "038095014c69b1a08e001b499851f17939812b74" ) },
    { 1279500, bts::blockchain::block_id_type( "488313d2c1c85bdec117bac0379f7b17f7cfbed3" ) },
    { 1280000, bts::blockchain::block_id_type( "b65127afd78332cd3d3ce16bb0283d1f172eca7e" ) },
    { 1281000, bts::blockchain::block_id_type( "1227d40a5255928da71870287de910de220bb988" ) },
    { 1282000, bts::blockchain::block_id_type( "5b36e414a65f86c3b98c6d6a6ca9f4de8b04e7af" ) },
    { 1283000, bts::blockchain::block_id_type( "8a680579dc870cff37e2d5e85c6bdb1f63f692ba" ) },
    { 1284000, bts::blockchain::block_id_type( "174621251aea239d512f6228457317dbe0e0537c" ) },
    { 1285000, bts::blockchain::block_id_type( "c55e49c761f3e954b5c3d58f22ae8430dc81a85c" ) },
    { 1286000, bts::blockchain::block_id_type( "d28053c6744cadf39286a9d2a184b8c2493f8d11" ) },
    { 1286500, bts::blockchain::block_id_type( "beef02cfa9d363c33a4d83a8688871b78820f42c" ) },
    { 1304000, bts::blockchain::block_id_type( "45a5d9bcc91401db56612d9d8b5d5df6f9f4e94c" ) }
};
<|endoftext|>


<commit_before>// Copyright (c) 2014, Cloudera, inc.

#include "util/resettable_heartbeater.h"

#include <boost/bind/bind.hpp>
#include <boost/thread/locks.hpp>
#include <gtest/gtest.h>
#include <string>

#include "gutil/gscoped_ptr.h"
#include "util/countdown_latch.h"
#include "util/locks.h"
#include "util/monotime.h"
#include "util/status.h"
#include "util/test_util.h"

namespace kudu {

static const int64_t kSleepPeriodMsecs = 100;
static const int kNumPeriodsToWait = 3;
// Wait triple the required time before we time out, should be enough to avoid test flakiness.
static const uint64_t kMaxWaitMsecs = kSleepPeriodMsecs * kNumPeriodsToWait * 3;

class ResettableHeartbeaterTest : public KuduTest {
 public:
  ResettableHeartbeaterTest()
    : KuduTest(),
      latch_(kNumPeriodsToWait) {
  }

 protected:
  void CreateHeartbeater(const MonoDelta period, const std::string& name) {
    heartbeater_.reset(
        new ResettableHeartbeater(name,
                                  period,
                                  boost::bind(&ResettableHeartbeaterTest::HeartbeatFunction,
                                              this)));
  }

  Status HeartbeatFunction() {
    latch_.CountDown();
    return Status::OK();
  }

  void WaitForCountDown() {
    CHECK(latch_.TimedWait(boost::posix_time::milliseconds(kMaxWaitMsecs)))
        << "Failed to count down " << kNumPeriodsToWait << " times in " << kMaxWaitMsecs
        << " ms: latch count == " << latch_.count();
  }

  CountDownLatch latch_;
  gscoped_ptr<ResettableHeartbeater> heartbeater_;
};

// Tests that if Reset() is not called the heartbeat method is called
// the expected number of times.
TEST_F(ResettableHeartbeaterTest, TestRegularHeartbeats) {
  CreateHeartbeater(MonoDelta::FromMilliseconds(kSleepPeriodMsecs), CURRENT_TEST_NAME());
  ASSERT_STATUS_OK(heartbeater_->Start());
  WaitForCountDown();
  ASSERT_STATUS_OK(heartbeater_->Stop());
}

// Tests that if we Reset() the heartbeater in a period smaller than
// the heartbeat period the heartbeat method never gets called.
// After we stop resetting heartbeats should resume as normal
TEST_F(ResettableHeartbeaterTest, TestResetHeartbeats) {
  CreateHeartbeater(MonoDelta::FromMilliseconds(kSleepPeriodMsecs), CURRENT_TEST_NAME());
  ASSERT_STATUS_OK(heartbeater_->Start());
  for (int i = 0; i < 10; i++) {
    usleep(kSleepPeriodMsecs / 4 * 1000);
    heartbeater_->Reset();
    ASSERT_EQ(kNumPeriodsToWait, latch_.count());
  }
  WaitForCountDown();
  ASSERT_STATUS_OK(heartbeater_->Stop());
}

}  // namespace kudu
<commit_msg>Increase max wait time in resettable_heartbeater-test<commit_after>// Copyright (c) 2014, Cloudera, inc.

#include "util/resettable_heartbeater.h"

#include <boost/bind/bind.hpp>
#include <boost/thread/locks.hpp>
#include <gtest/gtest.h>
#include <string>

#include "gutil/gscoped_ptr.h"
#include "util/countdown_latch.h"
#include "util/locks.h"
#include "util/monotime.h"
#include "util/status.h"
#include "util/test_util.h"

namespace kudu {

static const int64_t kSleepPeriodMsecs = 100;
static const int kNumPeriodsToWait = 3;
// Wait a large multiple (in the worst case) of the required time before we
// time out to avoid test flakiness.
static const uint64_t kMaxWaitMsecs = kSleepPeriodMsecs * kNumPeriodsToWait * 20;

class ResettableHeartbeaterTest : public KuduTest {
 public:
  ResettableHeartbeaterTest()
    : KuduTest(),
      latch_(kNumPeriodsToWait) {
  }

 protected:
  void CreateHeartbeater(const MonoDelta period, const std::string& name) {
    heartbeater_.reset(
        new ResettableHeartbeater(name,
                                  period,
                                  boost::bind(&ResettableHeartbeaterTest::HeartbeatFunction,
                                              this)));
  }

  Status HeartbeatFunction() {
    latch_.CountDown();
    return Status::OK();
  }

  void WaitForCountDown() {
    CHECK(latch_.TimedWait(boost::posix_time::milliseconds(kMaxWaitMsecs)))
        << "Failed to count down " << kNumPeriodsToWait << " times in " << kMaxWaitMsecs
        << " ms: latch count == " << latch_.count();
  }

  CountDownLatch latch_;
  gscoped_ptr<ResettableHeartbeater> heartbeater_;
};

// Tests that if Reset() is not called the heartbeat method is called
// the expected number of times.
TEST_F(ResettableHeartbeaterTest, TestRegularHeartbeats) {
  CreateHeartbeater(MonoDelta::FromMilliseconds(kSleepPeriodMsecs), CURRENT_TEST_NAME());
  ASSERT_STATUS_OK(heartbeater_->Start());
  WaitForCountDown();
  ASSERT_STATUS_OK(heartbeater_->Stop());
}

// Tests that if we Reset() the heartbeater in a period smaller than
// the heartbeat period the heartbeat method never gets called.
// After we stop resetting heartbeats should resume as normal
TEST_F(ResettableHeartbeaterTest, TestResetHeartbeats) {
  CreateHeartbeater(MonoDelta::FromMilliseconds(kSleepPeriodMsecs), CURRENT_TEST_NAME());
  ASSERT_STATUS_OK(heartbeater_->Start());
  for (int i = 0; i < 10; i++) {
    usleep(kSleepPeriodMsecs / 4 * 1000);
    heartbeater_->Reset();
    ASSERT_EQ(kNumPeriodsToWait, latch_.count());
  }
  WaitForCountDown();
  ASSERT_STATUS_OK(heartbeater_->Stop());
}

}  // namespace kudu
<|endoftext|>


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

  Program:   Insight Segmentation & Registration Toolkit
  Module:    itkCenteredVersorTransformInitializerTest.cxx
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

  Copyright (c) Insight Software Consortium. All rights reserved.
  See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm 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.

=========================================================================*/
#if defined(_MSC_VER)
#pragma warning ( disable : 4786 )
#endif

#include "itkVersorRigid3DTransform.h"
#include "itkCenteredVersorTransformInitializer.h"
#include "itkImage.h"

#include "itkImageRegionIterator.h"

/**
 *  This program tests the use of the CenteredVersorTransformInitializer class
 *
 *
 */

int itkCenteredVersorTransformInitializerTest(int , char* [] )
{

  bool pass = true;

  const unsigned int Dimension = 3;

  // Fixed Image Type
  typedef itk::Image<unsigned char, Dimension>      FixedImageType;

  // Moving Image Type
  typedef itk::Image<unsigned char, Dimension>       MovingImageType;

  // Size Type
  typedef FixedImageType::SizeType                 SizeType;
  typedef FixedImageType::SpacingType              SpacingType;
  typedef FixedImageType::PointType                PointType;
  typedef FixedImageType::IndexType                IndexType;
  typedef FixedImageType::RegionType               RegionType;

  // Transform Type
  typedef itk::VersorRigid3DTransform< double >     TransformType;
  typedef TransformType::ParametersType             ParametersType;

  SizeType size;
  size[0] = 100;
  size[1] = 100;
  size[2] =  60;

  PointType fixedOrigin;
  fixedOrigin[0] = 0.0;
  fixedOrigin[1] = 0.0;
  fixedOrigin[2] = 0.0;

  PointType movingOrigin;
  movingOrigin[0] = 29.0;
  movingOrigin[1] = 17.0;
  movingOrigin[2] = 13.0;

  SpacingType spacing;
  spacing[0] = 1.5;
  spacing[1] = 1.5;
  spacing[2] = 2.5;

  IndexType index;
  index[0] = 0;
  index[1] = 0;
  index[2] = 0;

  RegionType region;
  region.SetSize( size );
  region.SetIndex( index );

  FixedImageType::Pointer     fixedImage    = FixedImageType::New();
  MovingImageType::Pointer    movingImage   = MovingImageType::New();

  fixedImage->SetRegions( region );
  fixedImage->SetSpacing( spacing );
  fixedImage->SetOrigin(  fixedOrigin );
  fixedImage->Allocate();
  fixedImage->FillBuffer( 0 );

  movingImage->SetRegions( region );
  movingImage->SetSpacing( spacing );
  movingImage->SetOrigin(  movingOrigin );
  movingImage->Allocate();
  movingImage->FillBuffer( 0 );

  RegionType internalRegion;
  SizeType  internalSize;
  IndexType internalIndex;

  internalIndex[0] = index[0] + 20;
  internalIndex[1] = index[1] + 30;
  internalIndex[2] = index[2] + 40;

  internalSize[0]  = size[0] - 2 * 20;
  internalSize[1]  = size[1] - 2 * 30;
  internalSize[2]  = size[2] - 2 * 40;

  internalRegion.SetSize(  internalSize  );
  internalRegion.SetIndex( internalIndex );

  typedef itk::ImageRegionIterator< FixedImageType > FixedIterator;
  FixedIterator fi( fixedImage, internalRegion );

  fi.GoToBegin();
  while( !fi.IsAtEnd() )
    {
    fi.Set( 200 );
    ++fi;
    }

  internalIndex[0] = index[0] + 40;
  internalIndex[1] = index[1] + 20;
  internalIndex[2] = index[2] + 30;

  internalSize[0]  = size[0] - 2 * 40;
  internalSize[1]  = size[1] - 2 * 20;
  internalSize[2]  = size[2] - 2 * 30;

  internalRegion.SetSize(  internalSize  );
  internalRegion.SetIndex( internalIndex );

  typedef itk::ImageRegionIterator< MovingImageType > MovingIterator;
  MovingIterator mi( movingImage, internalRegion );

  mi.GoToBegin();
  while( !mi.IsAtEnd() )
    {
    mi.Set( 200 );
    ++mi;
    }

  TransformType::Pointer transform = TransformType::New();

  typedef itk::CenteredVersorTransformInitializer<
                                  FixedImageType,
                                  MovingImageType >
                                            InitializerType;

  InitializerType::Pointer initializer = InitializerType::New();

  initializer->SetFixedImage( fixedImage );
  initializer->SetMovingImage( movingImage );
  initializer->SetTransform( transform );

  transform->SetIdentity();
  initializer->GeometryOn();
  initializer->InitializeTransform();

  std::cout << std::endl << std::endl;
  std::cout << "Testing Geometric Mode " << std::endl;
  transform->Print( std::cout );

  TransformType::InputPointType   center1      = transform->GetCenter();
  TransformType::OutputVectorType translation1 = transform->GetTranslation();
  TransformType::OffsetType       offset1      = transform->GetOffset();

  const double tolerance = 1e-3;

  { // Verfications for the Geometry Mode
  TransformType::InputPointType   fixedCenter;
  TransformType::InputPointType   movingCenter;

  for(unsigned int j=0; j < Dimension; j++ )
    {
    fixedCenter[j]  = fixedOrigin[j]  + size[j] * spacing[j] / 2.0 ;
    movingCenter[j] = movingOrigin[j] + size[j] * spacing[j] / 2.0 ;
    }

  TransformType::InputVectorType relativeCenter = movingCenter - fixedCenter;

  for(unsigned int k=0; k < Dimension; k++ )
    {
    if( fabs( translation1[k] - relativeCenter[k] ) > tolerance )
      {
      std::cerr << "Translation differs from expected value" << std::endl;
      std::cerr << "It should be " << relativeCenter << std::endl;
      std::cerr << "but it is    " << translation1 << std::endl;
      pass = false;
      break;
      }
    if( fabs( offset1[k] - relativeCenter[k] ) > tolerance )
      {
      std::cerr << "Offset differs from expected value" << std::endl;
      std::cerr << "It should be " << relativeCenter << std::endl;
      std::cerr << "but it is    " << offset1 << std::endl;
      pass = false;
      break;
      }
    }
  }

  transform->SetIdentity();
  initializer->MomentsOn();
  initializer->InitializeTransform();

  std::cout << std::endl << std::endl;
  std::cout << "Testing Moments Mode " << std::endl;
  transform->Print( std::cout );

  TransformType::InputPointType   center2      = transform->GetCenter();
  TransformType::OutputVectorType translation2 = transform->GetTranslation();
  TransformType::OffsetType       offset2      = transform->GetOffset();

  { // Verfications for the Moments Mode
  TransformType::InputPointType   fixedCenter;
  TransformType::InputPointType   movingCenter;

  for(unsigned int j=0; j < Dimension; j++ )
    {
    fixedCenter[j]  = fixedOrigin[j]  + size[j] * spacing[j] / 2.0 ;
    movingCenter[j] = movingOrigin[j] + size[j] * spacing[j] / 2.0 ;
    }

  TransformType::InputVectorType relativeCenter = movingCenter - fixedCenter;

  for(unsigned int k=0; k < Dimension; k++ )
    {
    if( fabs( translation2[k] - relativeCenter[k] ) > tolerance )
      {
      std::cerr << "Translation differs from expected value" << std::endl;
      std::cerr << "It should be " << relativeCenter << std::endl;
      std::cerr << "but it is    " << translation2 << std::endl;
      pass = false;
      break;
      }
    if( fabs( offset2[k] - relativeCenter[k] ) > tolerance )
      {
      std::cerr << "Offset differs from expected value" << std::endl;
      std::cerr << "It should be " << relativeCenter << std::endl;
      std::cerr << "but it is    " << offset2 << std::endl;
      pass = false;
      break;
      }
    }
  }

  if( !pass )
    {
    std::cout << "Test FAILED." << std::endl;
    return EXIT_FAILURE;
    }

  std::cout << "Test PASSED." << std::endl;
  return EXIT_SUCCESS;

}

<commit_msg>FIX: This initializer only have the MomentsOn() case.<commit_after>/*=========================================================================

  Program:   Insight Segmentation & Registration Toolkit
  Module:    itkCenteredVersorTransformInitializerTest.cxx
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

  Copyright (c) Insight Software Consortium. All rights reserved.
  See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm 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.

=========================================================================*/
#if defined(_MSC_VER)
#pragma warning ( disable : 4786 )
#endif

#include "itkVersorRigid3DTransform.h"
#include "itkCenteredVersorTransformInitializer.h"
#include "itkImage.h"

#include "itkImageRegionIterator.h"

/**
 *  This program tests the use of the CenteredVersorTransformInitializer class
 *
 *
 */

int itkCenteredVersorTransformInitializerTest(int , char* [] )
{

  bool pass = true;

  const unsigned int Dimension = 3;

  // Fixed Image Type
  typedef itk::Image<unsigned char, Dimension>      FixedImageType;

  // Moving Image Type
  typedef itk::Image<unsigned char, Dimension>       MovingImageType;

  // Size Type
  typedef FixedImageType::SizeType                 SizeType;
  typedef FixedImageType::SpacingType              SpacingType;
  typedef FixedImageType::PointType                PointType;
  typedef FixedImageType::IndexType                IndexType;
  typedef FixedImageType::RegionType               RegionType;

  // Transform Type
  typedef itk::VersorRigid3DTransform< double >     TransformType;
  typedef TransformType::ParametersType             ParametersType;

  SizeType size;
  size[0] = 100;
  size[1] = 100;
  size[2] =  60;

  PointType fixedOrigin;
  fixedOrigin[0] = 0.0;
  fixedOrigin[1] = 0.0;
  fixedOrigin[2] = 0.0;

  PointType movingOrigin;
  movingOrigin[0] = 29.0;
  movingOrigin[1] = 17.0;
  movingOrigin[2] = 13.0;

  SpacingType spacing;
  spacing[0] = 1.5;
  spacing[1] = 1.5;
  spacing[2] = 2.5;

  IndexType index;
  index[0] = 0;
  index[1] = 0;
  index[2] = 0;

  RegionType region;
  region.SetSize( size );
  region.SetIndex( index );

  FixedImageType::Pointer     fixedImage    = FixedImageType::New();
  MovingImageType::Pointer    movingImage   = MovingImageType::New();

  fixedImage->SetRegions( region );
  fixedImage->SetSpacing( spacing );
  fixedImage->SetOrigin(  fixedOrigin );
  fixedImage->Allocate();
  fixedImage->FillBuffer( 0 );

  movingImage->SetRegions( region );
  movingImage->SetSpacing( spacing );
  movingImage->SetOrigin(  movingOrigin );
  movingImage->Allocate();
  movingImage->FillBuffer( 0 );

  RegionType internalRegion;
  SizeType  internalSize;
  IndexType internalIndex;

  internalIndex[0] = index[0] + 20;
  internalIndex[1] = index[1] + 30;
  internalIndex[2] = index[2] + 10;

  internalSize[0]  = size[0] - 2 * 20;
  internalSize[1]  = size[1] - 2 * 30;
  internalSize[2]  = size[2] - 2 * 10;

  internalRegion.SetSize(  internalSize  );
  internalRegion.SetIndex( internalIndex );

  typedef itk::ImageRegionIterator< FixedImageType > FixedIterator;
  FixedIterator fi( fixedImage, internalRegion );

  fi.GoToBegin();
  while( !fi.IsAtEnd() )
    {
    fi.Set( 200 );
    ++fi;
    }

  internalIndex[0] = index[0] + 10;
  internalIndex[1] = index[1] + 20;
  internalIndex[2] = index[2] + 30;

  internalSize[0]  = size[0] - 2 * 10;
  internalSize[1]  = size[1] - 2 * 20;
  internalSize[2]  = size[2] - 2 * 30;

  internalRegion.SetSize(  internalSize  );
  internalRegion.SetIndex( internalIndex );

  typedef itk::ImageRegionIterator< MovingImageType > MovingIterator;
  MovingIterator mi( movingImage, internalRegion );

  mi.GoToBegin();
  while( !mi.IsAtEnd() )
    {
    mi.Set( 200 );
    ++mi;
    }

  TransformType::Pointer transform = TransformType::New();
  transform->SetIdentity();

  typedef itk::CenteredVersorTransformInitializer<
                                  FixedImageType,
                                  MovingImageType >
                                            InitializerType;

  InitializerType::Pointer initializer = InitializerType::New();

  initializer->SetFixedImage( fixedImage );
  initializer->SetMovingImage( movingImage );
  initializer->SetTransform( transform );

  initializer->InitializeTransform();

  TransformType::InputPointType   center2      = transform->GetCenter();
  TransformType::OutputVectorType translation2 = transform->GetTranslation();
  TransformType::OffsetType       offset2      = transform->GetOffset();

  { // Verfications
  TransformType::InputPointType   fixedCenter;
  TransformType::InputPointType   movingCenter;

  for(unsigned int j=0; j < Dimension; j++ )
    {
    fixedCenter[j]  = fixedOrigin[j]  + size[j] * spacing[j] / 2.0 ;
    movingCenter[j] = movingOrigin[j] + size[j] * spacing[j] / 2.0 ;
    }

  TransformType::InputVectorType relativeCenter = movingCenter - fixedCenter;

  const double tolerance = 1e-3;

  for(unsigned int k=0; k < Dimension; k++ )
    {
    if( fabs( translation2[k] - relativeCenter[k] ) > tolerance )
      {
      std::cerr << "Translation differs from expected value" << std::endl;
      std::cerr << "It should be " << relativeCenter << std::endl;
      std::cerr << "but it is    " << translation2 << std::endl;
      pass = false;
      break;
      }
    if( fabs( offset2[k] - relativeCenter[k] ) > tolerance )
      {
      std::cerr << "Offset differs from expected value" << std::endl;
      std::cerr << "It should be " << relativeCenter << std::endl;
      std::cerr << "but it is    " << offset2 << std::endl;
      pass = false;
      break;
      }
    }
  }

  if( !pass )
    {
    std::cout << "Test FAILED." << std::endl;
    return EXIT_FAILURE;
    }

  std::cout << "Test PASSED." << std::endl;
  return EXIT_SUCCESS;

}

<|endoftext|>