<commit_before>/*
    Copyright 2008 Brain Research Institute, Melbourne, Australia

    Written by J-Donald Tournier, 27/06/08.

    This file is part of MRtrix.

    MRtrix is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    MRtrix is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with MRtrix.  If not, see <http://www.gnu.org/licenses/>.

*/

#include "file/config.h"
#include "file/ofstream.h"
#include "file/path.h"
#include "file/utils.h"
#include "file/mmap.h"
#include "image/utils.h"
#include "image/format/list.h"
#include "image/header.h"
#include "image/handler/default.h"
#include "get_set.h"

/*
 MRI format:
     Magic number:              MRI#         (4 bytes)
     Byte order specifier:    uint16_t = 1     (2 bytes)
     ...
     Elements:
       ID specifier:            uint32_t       (4 bytes)
       size:                    uint32_t       (4 bytes)
       contents:              unspecified  ('size' bytes)
     ...

*/

#define MRI_DATA       0x01
#define MRI_DIMENSIONS 0x02
#define MRI_ORDER      0x03
#define MRI_VOXELSIZE  0x04
#define MRI_COMMENT    0x05
#define MRI_TRANSFORM  0x06
#define MRI_DWSCHEME   0x07

namespace MR
{
  namespace Image
  {
    namespace Format
    {

      namespace
      {

        inline size_t char2order (char item, bool& forward)
        {
          switch (item) {
            case 'L':
              forward = true;
              return (0);
            case 'R':
              forward = false;
              return (0);
            case 'P':
              forward = true;
              return (1);
            case 'A':
              forward = false;
              return (1);
            case 'I':
              forward = true;
              return (2);
            case 'S':
              forward = false;
              return (2);
            case 'B':
              forward = true;
              return (3);
            case 'E':
              forward = false;
              return (3);
          }
          return (std::numeric_limits<size_t>::max());
        }

        inline char order2char (size_t axis, bool forward)
        {
          switch (axis) {
            case 0:
              if (forward) return ('L');
              else return ('R');
            case 1:
              if (forward) return ('P');
              else return ('A');
            case 2:
              if (forward) return ('I');
              else return ('S');
            case 3:
              if (forward) return ('B');
              else return ('E');
          }
          return ('\0');
        }

        inline size_t type (const uint8_t* pos, bool is_BE)
        {
          return (get<uint32_t> (pos, is_BE));
        }
        inline size_t size (const uint8_t* pos, bool is_BE)
        {
          return (get<uint32_t> (pos + sizeof (uint32_t), is_BE));
        }
        inline const uint8_t* data (const uint8_t* pos)
        {
          return (pos + 2*sizeof (uint32_t));
        }

        inline const uint8_t* next (const uint8_t* current_pos, bool is_BE)
        {
          return (current_pos + 2*sizeof (uint32_t) + size (current_pos, is_BE));
        }

        inline void write_tag (std::ostream& out, uint32_t Type, uint32_t Size, bool is_BE)
        {
          Type = ByteOrder::swap<uint32_t> (Type, is_BE);
          out.write ( (const char*) &Type, sizeof (uint32_t));
          Size = ByteOrder::swap<uint32_t> (Size, is_BE);
          out.write ( (const char*) &Size, sizeof (uint32_t));
        }

        template <typename T> inline void write (std::ostream& out, T val, bool is_BE)
        {
          val = ByteOrder::swap<T> (val, is_BE);
          out.write ( (const char*) &val, sizeof (T));
        }

      }

      std::shared_ptr<Handler::Base> MRI::read (Header& H) const
      {
        if (!Path::has_suffix (H.name(), ".mri"))
          return std::shared_ptr<Handler::Base>();

        File::MMap fmap (H.name());

        if (memcmp (fmap.address(), "MRI#", 4))
          throw Exception ("file \"" + H.name() + "\" is not in MRI format (unrecognised magic number)");

        bool is_BE = false;
        if (get<uint16_t> (fmap.address() + sizeof (int32_t), is_BE) == 0x0100U) is_BE = true;
        else if (get<uint16_t> (fmap.address() + sizeof (uint32_t), is_BE) != 0x0001U)
          throw Exception ("MRI file \"" + H.name() + "\" is badly formed (invalid byte order specifier)");

        H.set_ndim (4);

        size_t data_offset = 0;
        char* c;
        const uint8_t* current = fmap.address() + sizeof (int32_t) + sizeof (uint16_t);
        const uint8_t* last = fmap.address() + fmap.size() - 2*sizeof (uint32_t);

        while (current <= last) {
          switch (type (current, is_BE)) {
            case MRI_DATA:
              H.datatype() = (reinterpret_cast<const char*> (data (current))) [-4];
              data_offset = current + 5 - (uint8_t*) fmap.address();
              break;
            case MRI_DIMENSIONS:
              H.dim(0) = get<uint32_t> (data (current), is_BE);
              H.dim(1) = get<uint32_t> (data (current) + sizeof (uint32_t), is_BE);
              H.dim(2) = get<uint32_t> (data (current) + 2*sizeof (uint32_t), is_BE);
              H.dim(3) = get<uint32_t> (data (current) + 3*sizeof (uint32_t), is_BE);
              break;
            case MRI_ORDER:
              c = (char*) data (current);
              for (size_t n = 0; n < 4; n++) {
                bool forward = true;
                size_t ax = char2order (c[n], forward);
                if (ax == std::numeric_limits<size_t>::max())
                  throw Exception ("invalid order specifier in MRI image \"" + H.name() + "\"");
                H.stride(ax) = n+1;
                if (!forward)
                  H.stride(ax) = -H.stride (ax);
              }
              break;
            case MRI_VOXELSIZE:
              H.vox(0) = get<float32> (data (current), is_BE);
              H.vox(1) = get<float32> (data (current) + sizeof (float32), is_BE);
              H.vox(2) = get<float32> (data (current) + 2*sizeof (float32), is_BE);
              break;
            case MRI_COMMENT:
              H.comments().push_back (std::string (reinterpret_cast<const char*> (data (current)), size (current, is_BE)));
              break;
            case MRI_TRANSFORM:
              H.transform().allocate (4,4);
              for (size_t i = 0; i < 4; ++i)
                for (size_t j = 0; j < 4; ++j)
                  H.transform() (i,j) = get<float32> (data (current) + (i*4 + j) *sizeof (float32), is_BE);
              break;
            case MRI_DWSCHEME:
              H.DW_scheme().allocate (size (current, is_BE) / (4*sizeof (float32)), 4);
              for (size_t i = 0; i < H.DW_scheme().rows(); ++i)
                for (size_t j = 0; j < 4; ++j)
                  H.DW_scheme() (i,j) = get<float32> (data (current) + (i*4 + j) *sizeof (float32), is_BE);
              break;
            default:
              WARN ("unknown header entity (" + str (type (current, is_BE))
                     + ", offset " + str (current - fmap.address())
                     + ") in image \"" + H.name() + "\" - ignored");
              break;
          }

          if (data_offset)
            break;

          current = next (current, is_BE);
        }

        if (!data_offset)
          throw Exception ("no data field found in MRI image \"" + H.name() + "\"");

        std::shared_ptr<Handler::Base> handler (new Handler::Default (H));
        handler->files.push_back (File::Entry (H.name(), data_offset));

        return handler;
      }

      bool MRI::check (Header& H, size_t num_axes) const
      {
        if (!Path::has_suffix (H.name(), ".mri"))
          return false;

        if (H.ndim() > num_axes && num_axes != 4)
          throw Exception ("MRTools format can only support 4 dimensions");

        H.set_ndim (num_axes);

        return true;
      }

      std::shared_ptr<Handler::Base> MRI::create (Header& H) const
      {
        File::OFStream out (H.name());

#ifdef MRTRIX_BYTE_ORDER_BIG_ENDIAN
        bool is_BE = true;
#else
        bool is_BE = false;
#endif

        out.write ("MRI#", 4);
        write<uint16_t> (out, 0x01U, is_BE);

        write_tag (out, MRI_DIMENSIONS, 4*sizeof (uint32_t), is_BE);
        write<uint32_t> (out, H.dim (0), is_BE);
        write<uint32_t> (out, (H.ndim() > 1 ? H.dim (1) : 1), is_BE);
        write<uint32_t> (out, (H.ndim() > 2 ? H.dim (2) : 1), is_BE);
        write<uint32_t> (out, (H.ndim() > 3 ? H.dim (3) : 1), is_BE);

        write_tag (out, MRI_ORDER, 4*sizeof (uint8_t), is_BE);
        size_t n;
        char order[4];
        for (n = 0; n < H.ndim(); ++n)
          order[std::abs (H.stride (n))-1] = order2char (n, H.stride (n) >0);
        for (; n < 4; ++n)
          order[n] = order2char (n, true);
        out.write (order, 4);

        write_tag (out, MRI_VOXELSIZE, 3*sizeof (float32), is_BE);
        write<float> (out, H.vox (0), is_BE);
        write<float> (out, (H.ndim() > 1 ? H.vox (1) : 2.0f), is_BE);
        write<float> (out, (H.ndim() > 2 ? H.vox (2) : 2.0f), is_BE);

        for (size_t n = 0; n < H.comments().size(); n++) {
          size_t l = H.comments() [n].size();
          if (l) {
            write_tag (out, MRI_COMMENT, l, is_BE);
            out.write (H.comments() [n].c_str(), l);
          }
        }

        if (H.transform().is_set()) {
          write_tag (out, MRI_TRANSFORM, 16*sizeof (float32), is_BE);
          for (size_t i = 0; i < 4; ++i)
            for (size_t j = 0; j < 4; ++j)
              write<float> (out, H.transform() (i,j), is_BE);
        }

        if (H.DW_scheme().is_set()) {
          write_tag (out, MRI_DWSCHEME, 4*H.DW_scheme().rows() *sizeof (float32), is_BE);
          for (size_t i = 0; i < H.DW_scheme().rows(); ++i)
            for (size_t j = 0; j < 4; ++j)
              write<float> (out, H.DW_scheme() (i,j), is_BE);
        }

        write_tag (out, MRI_DATA, 1, is_BE);
        out.write (reinterpret_cast<const char*> (&H.datatype()()), 1);

        size_t data_offset = out.tellp();
        out.close();

        std::shared_ptr<Handler::Base> handler (new Handler::Default (H));
        File::resize (H.name(), data_offset + Image::footprint(H));
        handler->files.push_back (File::Entry (H.name(), data_offset));

        return handler;
      }

    }
  }
}

<commit_msg>fix bug in handling of (ancient and deprecated) MRI format<commit_after>/*
    Copyright 2008 Brain Research Institute, Melbourne, Australia

    Written by J-Donald Tournier, 27/06/08.

    This file is part of MRtrix.

    MRtrix is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    MRtrix is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with MRtrix.  If not, see <http://www.gnu.org/licenses/>.

*/

#include "file/config.h"
#include "file/ofstream.h"
#include "file/path.h"
#include "file/utils.h"
#include "file/mmap.h"
#include "image/utils.h"
#include "image/format/list.h"
#include "image/header.h"
#include "image/handler/default.h"
#include "get_set.h"

/*
 MRI format:
     Magic number:              MRI#         (4 bytes)
     Byte order specifier:    uint16_t = 1     (2 bytes)
     ...
     Elements:
       ID specifier:            uint32_t       (4 bytes)
       size:                    uint32_t       (4 bytes)
       contents:              unspecified  ('size' bytes)
     ...

*/

#define MRI_DATA       0x01
#define MRI_DIMENSIONS 0x02
#define MRI_ORDER      0x03
#define MRI_VOXELSIZE  0x04
#define MRI_COMMENT    0x05
#define MRI_TRANSFORM  0x06
#define MRI_DWSCHEME   0x07

namespace MR
{
  namespace Image
  {
    namespace Format
    {

      namespace
      {

        inline size_t char2order (char item, bool& forward)
        {
          switch (item) {
            case 'L':
              forward = true;
              return (0);
            case 'R':
              forward = false;
              return (0);
            case 'P':
              forward = true;
              return (1);
            case 'A':
              forward = false;
              return (1);
            case 'I':
              forward = true;
              return (2);
            case 'S':
              forward = false;
              return (2);
            case 'B':
              forward = true;
              return (3);
            case 'E':
              forward = false;
              return (3);
          }
          return (std::numeric_limits<size_t>::max());
        }

        inline char order2char (size_t axis, bool forward)
        {
          switch (axis) {
            case 0:
              if (forward) return ('L');
              else return ('R');
            case 1:
              if (forward) return ('P');
              else return ('A');
            case 2:
              if (forward) return ('I');
              else return ('S');
            case 3:
              if (forward) return ('B');
              else return ('E');
          }
          return ('\0');
        }

        inline size_t type (const uint8_t* pos, bool is_BE)
        {
          return (get<uint32_t> (pos, is_BE));
        }
        inline size_t size (const uint8_t* pos, bool is_BE)
        {
          return (get<uint32_t> (pos + sizeof (uint32_t), is_BE));
        }
        inline const uint8_t* data (const uint8_t* pos)
        {
          return (pos + 2*sizeof (uint32_t));
        }

        inline const uint8_t* next (const uint8_t* current_pos, bool is_BE)
        {
          return (current_pos + 2*sizeof (uint32_t) + size (current_pos, is_BE));
        }

        inline void write_tag (std::ostream& out, uint32_t Type, uint32_t Size, bool is_BE)
        {
          Type = ByteOrder::swap<uint32_t> (Type, is_BE);
          out.write ( (const char*) &Type, sizeof (uint32_t));
          Size = ByteOrder::swap<uint32_t> (Size, is_BE);
          out.write ( (const char*) &Size, sizeof (uint32_t));
        }

        template <typename T> inline void write (std::ostream& out, T val, bool is_BE)
        {
          val = ByteOrder::swap<T> (val, is_BE);
          out.write ( (const char*) &val, sizeof (T));
        }

        // needed to get around changes in hard-coded enum types in datatype.h:
        DataType fetch_datatype (uint8_t c) {
          uint8_t d = c & 0x07U;
          uint8_t t = c & ~(0x07U);
          if (d >= 0x05U) ++d;
          return { uint8_t (d | t) };
        }

        uint8_t store_datatype (DataType& dt) {
          uint8_t d = dt() & 0x07U;
          uint8_t t = dt() & ~(0x07U);
          if (d >= 0x05U) --d;
          return (d | t);
        }

      }

      std::shared_ptr<Handler::Base> MRI::read (Header& H) const
      {
        if (!Path::has_suffix (H.name(), ".mri"))
          return std::shared_ptr<Handler::Base>();

        File::MMap fmap (H.name());

        if (memcmp (fmap.address(), "MRI#", 4))
          throw Exception ("file \"" + H.name() + "\" is not in MRI format (unrecognised magic number)");

        bool is_BE = false;
        if (get<uint16_t> (fmap.address() + sizeof (int32_t), is_BE) == 0x0100U) is_BE = true;
        else if (get<uint16_t> (fmap.address() + sizeof (uint32_t), is_BE) != 0x0001U)
          throw Exception ("MRI file \"" + H.name() + "\" is badly formed (invalid byte order specifier)");

        H.set_ndim (4);

        size_t data_offset = 0;
        char* c;
        const uint8_t* current = fmap.address() + sizeof (int32_t) + sizeof (uint16_t);
        const uint8_t* last = fmap.address() + fmap.size() - 2*sizeof (uint32_t);

        while (current <= last) {
          switch (type (current, is_BE)) {
            case MRI_DATA:
              H.datatype() = fetch_datatype (data(current)[-4]);
              data_offset = current + 5 - (uint8_t*) fmap.address();
              break;
            case MRI_DIMENSIONS:
              H.dim(0) = get<uint32_t> (data (current), is_BE);
              H.dim(1) = get<uint32_t> (data (current) + sizeof (uint32_t), is_BE);
              H.dim(2) = get<uint32_t> (data (current) + 2*sizeof (uint32_t), is_BE);
              H.dim(3) = get<uint32_t> (data (current) + 3*sizeof (uint32_t), is_BE);
              break;
            case MRI_ORDER:
              c = (char*) data (current);
              for (size_t n = 0; n < 4; n++) {
                bool forward = true;
                size_t ax = char2order (c[n], forward);
                if (ax == std::numeric_limits<size_t>::max())
                  throw Exception ("invalid order specifier in MRI image \"" + H.name() + "\"");
                H.stride(ax) = n+1;
                if (!forward)
                  H.stride(ax) = -H.stride (ax);
              }
              break;
            case MRI_VOXELSIZE:
              H.vox(0) = get<float32> (data (current), is_BE);
              H.vox(1) = get<float32> (data (current) + sizeof (float32), is_BE);
              H.vox(2) = get<float32> (data (current) + 2*sizeof (float32), is_BE);
              break;
            case MRI_COMMENT:
              H.comments().push_back (std::string (reinterpret_cast<const char*> (data (current)), size (current, is_BE)));
              break;
            case MRI_TRANSFORM:
              H.transform().allocate (4,4);
              for (size_t i = 0; i < 4; ++i)
                for (size_t j = 0; j < 4; ++j)
                  H.transform() (i,j) = get<float32> (data (current) + (i*4 + j) *sizeof (float32), is_BE);
              break;
            case MRI_DWSCHEME:
              H.DW_scheme().allocate (size (current, is_BE) / (4*sizeof (float32)), 4);
              for (size_t i = 0; i < H.DW_scheme().rows(); ++i)
                for (size_t j = 0; j < 4; ++j)
                  H.DW_scheme() (i,j) = get<float32> (data (current) + (i*4 + j) *sizeof (float32), is_BE);
              break;
            default:
              WARN ("unknown header entity (" + str (type (current, is_BE))
                     + ", offset " + str (current - fmap.address())
                     + ") in image \"" + H.name() + "\" - ignored");
              break;
          }

          if (data_offset)
            break;

          current = next (current, is_BE);
        }

        if (!data_offset)
          throw Exception ("no data field found in MRI image \"" + H.name() + "\"");

        std::shared_ptr<Handler::Base> handler (new Handler::Default (H));
        handler->files.push_back (File::Entry (H.name(), data_offset));

        return handler;
      }

      bool MRI::check (Header& H, size_t num_axes) const
      {
        if (!Path::has_suffix (H.name(), ".mri"))
          return false;

        if (H.ndim() > num_axes && num_axes != 4)
          throw Exception ("MRTools format can only support 4 dimensions");

        H.set_ndim (num_axes);

        return true;
      }

      std::shared_ptr<Handler::Base> MRI::create (Header& H) const
      {
        File::OFStream out (H.name());

#ifdef MRTRIX_BYTE_ORDER_BIG_ENDIAN
        bool is_BE = true;
#else
        bool is_BE = false;
#endif

        out.write ("MRI#", 4);
        write<uint16_t> (out, 0x01U, is_BE);

        write_tag (out, MRI_DIMENSIONS, 4*sizeof (uint32_t), is_BE);
        write<uint32_t> (out, H.dim (0), is_BE);
        write<uint32_t> (out, (H.ndim() > 1 ? H.dim (1) : 1), is_BE);
        write<uint32_t> (out, (H.ndim() > 2 ? H.dim (2) : 1), is_BE);
        write<uint32_t> (out, (H.ndim() > 3 ? H.dim (3) : 1), is_BE);

        write_tag (out, MRI_ORDER, 4*sizeof (uint8_t), is_BE);
        size_t n;
        char order[4];
        for (n = 0; n < H.ndim(); ++n)
          order[std::abs (H.stride (n))-1] = order2char (n, H.stride (n) >0);
        for (; n < 4; ++n)
          order[n] = order2char (n, true);
        out.write (order, 4);

        write_tag (out, MRI_VOXELSIZE, 3*sizeof (float32), is_BE);
        write<float> (out, H.vox (0), is_BE);
        write<float> (out, (H.ndim() > 1 ? H.vox (1) : 2.0f), is_BE);
        write<float> (out, (H.ndim() > 2 ? H.vox (2) : 2.0f), is_BE);

        for (size_t n = 0; n < H.comments().size(); n++) {
          size_t l = H.comments() [n].size();
          if (l) {
            write_tag (out, MRI_COMMENT, l, is_BE);
            out.write (H.comments() [n].c_str(), l);
          }
        }

        if (H.transform().is_set()) {
          write_tag (out, MRI_TRANSFORM, 16*sizeof (float32), is_BE);
          for (size_t i = 0; i < 4; ++i)
            for (size_t j = 0; j < 4; ++j)
              write<float> (out, H.transform() (i,j), is_BE);
        }

        if (H.DW_scheme().is_set()) {
          write_tag (out, MRI_DWSCHEME, 4*H.DW_scheme().rows() *sizeof (float32), is_BE);
          for (size_t i = 0; i < H.DW_scheme().rows(); ++i)
            for (size_t j = 0; j < 4; ++j)
              write<float> (out, H.DW_scheme() (i,j), is_BE);
        }

        write_tag (out, MRI_DATA, 1, is_BE);
        out.put (store_datatype (H.datatype()));

        size_t data_offset = out.tellp();
        out.close();

        std::shared_ptr<Handler::Base> handler (new Handler::Default (H));
        File::resize (H.name(), data_offset + Image::footprint(H));
        handler->files.push_back (File::Entry (H.name(), data_offset));

        return handler;
      }

    }
  }
}

<|endoftext|>


<commit_before>#include <btBulletDynamicsCommon.h>
#include "../Physics/GlmConversion.hpp"
#include "RigidBody.hpp"

namespace Component {
    RigidBody::~RigidBody() {
        Destroy();
    }

    Json::Value RigidBody::Save() const {
        Json::Value component;
        component["mass"] = mass;
        component["friction"] = friction;
        component["rollingFriction"] = rollingFriction;
        component["spinningFriction"] = spinningFriction;
        component["cor"] = restitution;
        component["kinematic"] = kinematic;
        return component;
    }

    bool RigidBody::IsKinematic() const {
        return kinematic;
    }

    float RigidBody::GetFriction() const {
        return friction;
    }

    float RigidBody::GetRollingFriction() const {
        return rollingFriction;
    }

    float RigidBody::GetSpinningFriction() const {
        return spinningFriction;
    }

    float RigidBody::GetRestitution() const {
        return restitution;
    }

    float RigidBody::GetLinearDamping() const {
        return linearDamping;
    }

    btRigidBody* RigidBody::GetBulletRigidBody() {
        return rigidBody;
    }

    void RigidBody::NewBulletRigidBody(float mass) {
        Destroy();

        this->mass = mass;

        // Motion states inform us of movement caused by physics so that we can
        // deal with those changes as needed.
        btDefaultMotionState* motionState = new btDefaultMotionState(btTransform(btQuaternion(0, 0, 0, 1), btVector3(0, 0, 0)));

        // Bullet treats zero mass as infinite, resulting in immovable objects.
        btRigidBody::btRigidBodyConstructionInfo constructionInfo(mass, motionState, nullptr, btVector3(0, 0, 0));
        rigidBody = new btRigidBody(constructionInfo);
        rigidBody->setUserPointer(this);
    }

    void RigidBody::Destroy() {
        if (rigidBody) {
            delete rigidBody->getMotionState();
            delete rigidBody;
        }
    }

    glm::vec3 RigidBody::GetPosition() const {
        btTransform trans;
        if (IsKinematic())
            rigidBody->getMotionState()->getWorldTransform(trans);
        else
            trans = rigidBody->getWorldTransform();

        return Physics::btToGlm(trans.getOrigin());
    }

    void RigidBody::SetPosition(const glm::vec3& pos) {
        if (IsKinematic()) {
            btTransform trans;
            rigidBody->getMotionState()->getWorldTransform(trans);
            trans.setOrigin(Physics::glmToBt(pos));
            rigidBody->getMotionState()->setWorldTransform(trans);
        } else {
            btTransform trans = rigidBody->getWorldTransform();
            trans.setOrigin(Physics::glmToBt(pos));
            rigidBody->setWorldTransform(trans);
        }
    }

    glm::quat RigidBody::GetOrientation() const {
        btTransform trans;
        if (IsKinematic())
            rigidBody->getMotionState()->getWorldTransform(trans);
        else
            trans = rigidBody->getWorldTransform();

        return Physics::btToGlm(trans.getRotation());
    }

    void RigidBody::SetOrientation(const glm::quat& rotation) {
        if (IsKinematic()) {
            btTransform trans;
            rigidBody->getMotionState()->getWorldTransform(trans);
            trans.setRotation(Physics::glmToBt(rotation));
            rigidBody->getMotionState()->setWorldTransform(trans);
        } else {
            btTransform trans = rigidBody->getWorldTransform();
            trans.setRotation(Physics::glmToBt(rotation));
            rigidBody->setWorldTransform(trans);
        }
    }

    float RigidBody::GetMass() {
        return mass;
    }

    void RigidBody::SetMass(float mass) {
        // Bullet provides a method on the shape that we can use to calculate
        // inertia.
        btVector3 inertia;
        rigidBody->getCollisionShape()->calculateLocalInertia(mass, inertia);
        rigidBody->setMassProps(mass, inertia);
        this->mass = mass;
    }

    void RigidBody::SetFriction(float friction) {
        rigidBody->setFriction(friction);
        this->friction = friction;
    }

    void RigidBody::SetRollingFriction(float friction) {
        rigidBody->setRollingFriction(friction);
        this->rollingFriction = friction;
    }

    void RigidBody::SetSpinningFriction(float friction) {
        rigidBody->setSpinningFriction(friction);
        this->spinningFriction = friction;
    }

    void RigidBody::SetRestitution(float cor) {
        rigidBody->setRestitution(cor);
        this->restitution = cor;
    }

    void RigidBody::SetLinearDamping(float damping) {
        rigidBody->setDamping(linearDamping, 0.0f);
        this->linearDamping = damping;
    }

    void RigidBody::MakeKinematic() {
        rigidBody->setCollisionFlags(rigidBody->getCollisionFlags() | btCollisionObject::CF_KINEMATIC_OBJECT);
        kinematic = true;
    }

    void RigidBody::MakeDynamic() {
        rigidBody->setCollisionFlags(rigidBody->getCollisionFlags() & ~btCollisionObject::CF_KINEMATIC_OBJECT);
        kinematic = false;
    }

    bool RigidBody::GetForceTransformSync() const {
        return forceTransformSync;
    }

    void RigidBody::SetForceTransformSync(bool sync) {
        forceTransformSync = sync;
    }
}
<commit_msg>Save linear damping to JSON.<commit_after>#include <btBulletDynamicsCommon.h>
#include "../Physics/GlmConversion.hpp"
#include "RigidBody.hpp"

namespace Component {
    RigidBody::~RigidBody() {
        Destroy();
    }

    Json::Value RigidBody::Save() const {
        Json::Value component;
        component["mass"] = mass;
        component["friction"] = friction;
        component["rollingFriction"] = rollingFriction;
        component["spinningFriction"] = spinningFriction;
        component["cor"] = restitution;
        component["linearDamping"] = linearDamping;
        component["kinematic"] = kinematic;
        return component;
    }

    bool RigidBody::IsKinematic() const {
        return kinematic;
    }

    float RigidBody::GetFriction() const {
        return friction;
    }

    float RigidBody::GetRollingFriction() const {
        return rollingFriction;
    }

    float RigidBody::GetSpinningFriction() const {
        return spinningFriction;
    }

    float RigidBody::GetRestitution() const {
        return restitution;
    }

    float RigidBody::GetLinearDamping() const {
        return linearDamping;
    }

    btRigidBody* RigidBody::GetBulletRigidBody() {
        return rigidBody;
    }

    void RigidBody::NewBulletRigidBody(float mass) {
        Destroy();

        this->mass = mass;

        // Motion states inform us of movement caused by physics so that we can
        // deal with those changes as needed.
        btDefaultMotionState* motionState = new btDefaultMotionState(btTransform(btQuaternion(0, 0, 0, 1), btVector3(0, 0, 0)));

        // Bullet treats zero mass as infinite, resulting in immovable objects.
        btRigidBody::btRigidBodyConstructionInfo constructionInfo(mass, motionState, nullptr, btVector3(0, 0, 0));
        rigidBody = new btRigidBody(constructionInfo);
        rigidBody->setUserPointer(this);
    }

    void RigidBody::Destroy() {
        if (rigidBody) {
            delete rigidBody->getMotionState();
            delete rigidBody;
        }
    }

    glm::vec3 RigidBody::GetPosition() const {
        btTransform trans;
        if (IsKinematic())
            rigidBody->getMotionState()->getWorldTransform(trans);
        else
            trans = rigidBody->getWorldTransform();

        return Physics::btToGlm(trans.getOrigin());
    }

    void RigidBody::SetPosition(const glm::vec3& pos) {
        if (IsKinematic()) {
            btTransform trans;
            rigidBody->getMotionState()->getWorldTransform(trans);
            trans.setOrigin(Physics::glmToBt(pos));
            rigidBody->getMotionState()->setWorldTransform(trans);
        } else {
            btTransform trans = rigidBody->getWorldTransform();
            trans.setOrigin(Physics::glmToBt(pos));
            rigidBody->setWorldTransform(trans);
        }
    }

    glm::quat RigidBody::GetOrientation() const {
        btTransform trans;
        if (IsKinematic())
            rigidBody->getMotionState()->getWorldTransform(trans);
        else
            trans = rigidBody->getWorldTransform();

        return Physics::btToGlm(trans.getRotation());
    }

    void RigidBody::SetOrientation(const glm::quat& rotation) {
        if (IsKinematic()) {
            btTransform trans;
            rigidBody->getMotionState()->getWorldTransform(trans);
            trans.setRotation(Physics::glmToBt(rotation));
            rigidBody->getMotionState()->setWorldTransform(trans);
        } else {
            btTransform trans = rigidBody->getWorldTransform();
            trans.setRotation(Physics::glmToBt(rotation));
            rigidBody->setWorldTransform(trans);
        }
    }

    float RigidBody::GetMass() {
        return mass;
    }

    void RigidBody::SetMass(float mass) {
        // Bullet provides a method on the shape that we can use to calculate
        // inertia.
        btVector3 inertia;
        rigidBody->getCollisionShape()->calculateLocalInertia(mass, inertia);
        rigidBody->setMassProps(mass, inertia);
        this->mass = mass;
    }

    void RigidBody::SetFriction(float friction) {
        rigidBody->setFriction(friction);
        this->friction = friction;
    }

    void RigidBody::SetRollingFriction(float friction) {
        rigidBody->setRollingFriction(friction);
        this->rollingFriction = friction;
    }

    void RigidBody::SetSpinningFriction(float friction) {
        rigidBody->setSpinningFriction(friction);
        this->spinningFriction = friction;
    }

    void RigidBody::SetRestitution(float cor) {
        rigidBody->setRestitution(cor);
        this->restitution = cor;
    }

    void RigidBody::SetLinearDamping(float damping) {
        rigidBody->setDamping(linearDamping, 0.0f);
        this->linearDamping = damping;
    }

    void RigidBody::MakeKinematic() {
        rigidBody->setCollisionFlags(rigidBody->getCollisionFlags() | btCollisionObject::CF_KINEMATIC_OBJECT);
        kinematic = true;
    }

    void RigidBody::MakeDynamic() {
        rigidBody->setCollisionFlags(rigidBody->getCollisionFlags() & ~btCollisionObject::CF_KINEMATIC_OBJECT);
        kinematic = false;
    }

    bool RigidBody::GetForceTransformSync() const {
        return forceTransformSync;
    }

    void RigidBody::SetForceTransformSync(bool sync) {
        forceTransformSync = sync;
    }
}
<|endoftext|>


<commit_before>#include <iostream>
#include <fstream>
#include <cstdlib>
#include <math.h>

using namespace std;

int main(int argc, char *argv[])
{
	ofstream outfile;
        outfile.open("config");
        bool cont = true;
	int prefix = atoi(argv[1]);
	if (prefix < 9) {
		int a = 0;
		while(cont) {
			outfile << a << ".0.0.0/" << prefix << "\t" <<
				argv[2] << endl;
			a = a + pow(2, (8 - prefix));
			if (a == 256)
				cont = false;
		}
	}
	else if (prefix < 17) {
		int a = 0;
		int b = 0;
		while(cont) {
			outfile << a << "." << b << ".0.0/" << prefix << "\t" << argv[2] << endl;
			b = b + pow(2, (16 - prefix));
			if (b == 256) {
				b = 0;
				a++;
				if (a == 256)
					cont = false;
			}
		}
	}
	else if (prefix < 25) {
		int a = 0;
		int b = 0;
		int c = 0;
		while(cont) {
			outfile << a << "." << b << "." << c << ".0/" << prefix << "\t" << argv[2] << endl;
			c = c + pow(2, (24 - prefix));
			if (c == 256) {
				c = 0;
				b++;
				if (b == 256) {
					b = 0;
					a++;
					if (a == 256)
						cont = false;
				}
			}
		}
	}
	else {
		int a = 0;
		int b = 0;
		int c = 0;
		int d = 0;
		while(cont) {
			outfile << a << "." << b << "." << c << "." << d << "/" << prefix << "\t" << argv[2] << endl;
			d = d + pow(2, (32 - prefix));
			if (d == 256) {
				d = 0;
				c++;
				if (c == 256) {
					c = 0;
					b++;
					if (b == 256) {
						b = 0;
						a++;
						if (a == 256)
							cont = false;
					}
				}
			}
		}
	}
	outfile.close();
	return 0;
}
<commit_msg>update configgen.cpp<commit_after>#include <iostream>
#include <fstream>
#include <cstdlib>
#include <math.h>

using namespace std;

int main(int argc, char *argv[])
{
	ofstream outfile;
        outfile.open("config");
        bool cont = true;
	int prefix = atoi(argv[1]);
	if (prefix < 9) {
		int a = 0;
		while(cont) {
			outfile << a << ".0.0.0/" << prefix << "\t" <<
				argv[2] << endl;
			a = a + pow(2, (8 - prefix));
			if (a == 256)
				cont = false;
		}
	}
	else if (prefix < 17) {
		int a = 0;
		int b = 0;
		while(cont) {
			outfile << a << "." << b << ".0.0/" << prefix <<
				"\t" << argv[2] << endl;
			b = b + pow(2, (16 - prefix));
			if (b == 256) {
				b = 0;
				a++;
				if (a == 256)
					cont = false;
			}
		}
	}
	else if (prefix < 25) {
		int a = 0;
		int b = 0;
		int c = 0;
		while(cont) {
			outfile << a << "." << b << "." << c << ".0/" <<
				prefix << "\t" << argv[2] << endl;
			c = c + pow(2, (24 - prefix));
			if (c == 256) {
				c = 0;
				b++;
				if (b == 256) {
					b = 0;
					a++;
					if (a == 256)
						cont = false;
				}
			}
		}
	}
	else {
		int a = 0;
		int b = 0;
		int c = 0;
		int d = 0;
		while(cont) {
			outfile << a << "." << b << "." << c << "." << d <<
				"/" << prefix << "\t" << argv[2] << endl;
			d = d + pow(2, (32 - prefix));
			if (d == 256) {
				d = 0;
				c++;
				if (c == 256) {
					c = 0;
					b++;
					if (b == 256) {
						b = 0;
						a++;
						if (a == 256)
							cont = false;
					}
				}
			}
		}
	}
	outfile.close();
	return 0;
}

<|endoftext|>


<commit_before>// Time:  O(n)
// Space: O(1)

class Solution {
public:
    bool isValidSerialization(string preorder) {
        if (preorder.empty()) {
            return false;
        }
        Tokenizer tokens(preorder);
        int depth = 0;
        int i = 0;
        for (; i < tokens.size(); ++i) {
            if (tokens.get_next() == "#") {
                --depth;
                if (depth < 0) {
                    break;
                }
            } else {
                ++depth;
            }
        }
        return i == tokens.size() - 1;
    }

    class Tokenizer {
    public:
        Tokenizer(const string& str) : str_(str), i_(0), cnt_(0) {
            size_ = count(str_.cbegin(), str_.cend(), ',') + 1;
        }

        string get_next() {
            string next;
            if (cnt_ < size_) {
                size_t j =  str_.find(",", i_);
                next = str_.substr(i_, j - i_);
                i_ = j + 1;
                ++cnt_;
            }
            return next;
        }

        size_t size() {
            return size_;
        }

    private:
        const string& str_;
        size_t size_;
        size_t cnt_;
        size_t i_;
    };

};
<commit_msg>Update verify-preorder-serialization-of-a-binary-tree.cpp<commit_after>// Time:  O(n)
// Space: O(1)

class Solution {
public:
    bool isValidSerialization(string preorder) {
        if (preorder.empty()) {
            return false;
        }
        Tokenizer tokens(preorder);
        int depth = 0;
        int i = 0;
        for (; i < tokens.size() && depth >= 0; ++i) {
            if (tokens.get_next() == "#") {
                --depth;
            } else {
                ++depth;
            }
        }
        return i == tokens.size() && depth < 0;
    }

    class Tokenizer {
    public:
        Tokenizer(const string& str) : str_(str), i_(0), cnt_(0) {
            size_ = count(str_.cbegin(), str_.cend(), ',') + 1;
        }

        string get_next() {
            string next;
            if (cnt_ < size_) {
                size_t j =  str_.find(",", i_);
                next = str_.substr(i_, j - i_);
                i_ = j + 1;
                ++cnt_;
            }
            return next;
        }

        size_t size() {
            return size_;
        }

    private:
        const string& str_;
        size_t size_;
        size_t cnt_;
        size_t i_;
    };

};
<|endoftext|>


<commit_before><commit_msg>Deleting 'test.cpp'<commit_after><|endoftext|>


<commit_before>#include "mitkImageStatisticsHolder.h"

#include "mitkHistogramGenerator.h"
#include "mitkImageTimeSelector.h"

mitk::ImageStatisticsHolder::ImageStatisticsHolder( mitk::Image::Pointer image)
  : m_Image(NULL), m_TimeSelectorForExtremaObject(NULL)
{
  m_CountOfMinValuedVoxels.resize(1, 0);
  m_CountOfMaxValuedVoxels.resize(1, 0);
  m_ScalarMin.resize(1, itk::NumericTraits<ScalarType>::max());
  m_ScalarMax.resize(1, itk::NumericTraits<ScalarType>::NonpositiveMin());
  m_Scalar2ndMin.resize(1, itk::NumericTraits<ScalarType>::max());
  m_Scalar2ndMax.resize(1, itk::NumericTraits<ScalarType>::NonpositiveMin());

  mitk::HistogramGenerator::Pointer generator = mitk::HistogramGenerator::New();
  m_HistogramGeneratorObject = generator;

  m_Image = image;

  // create time selector
  this->GetTimeSelector();

}

mitk::ImageStatisticsHolder::~ImageStatisticsHolder()
{
  m_HistogramGeneratorObject = NULL;
  m_TimeSelectorForExtremaObject = NULL;
}

const mitk::ImageStatisticsHolder::HistogramType* mitk::ImageStatisticsHolder::GetScalarHistogram(int t)
{
  mitk::ImageTimeSelector* timeSelector = this->GetTimeSelector();
  if(timeSelector!=NULL)
  {
    timeSelector->SetTimeNr(t);
    timeSelector->UpdateLargestPossibleRegion();

    mitk::HistogramGenerator* generator = static_cast<mitk::HistogramGenerator*>(m_HistogramGeneratorObject.GetPointer());
    generator->SetImage(timeSelector->GetOutput());
    generator->ComputeHistogram();
    return static_cast<const mitk::ImageStatisticsHolder::HistogramType*>(generator->GetHistogram());
  }
  return NULL;
}

bool mitk::ImageStatisticsHolder::IsValidTimeStep( int t) const
{
    return m_Image->IsValidTimeStep(t);
}

mitk::ImageTimeSelector* mitk::ImageStatisticsHolder::GetTimeSelector()
{
  if(m_TimeSelectorForExtremaObject.IsNull())
  {
    m_TimeSelectorForExtremaObject = ImageTimeSelector::New();

    ImageTimeSelector* timeSelector = static_cast<mitk::ImageTimeSelector*>( m_TimeSelectorForExtremaObject.GetPointer() );
    timeSelector->SetInput(m_Image);
    m_Image->UnRegister();
  }

  return static_cast<ImageTimeSelector*>( m_TimeSelectorForExtremaObject.GetPointer() );
}

void mitk::ImageStatisticsHolder::Expand( unsigned int timeSteps )
{
  if(! m_Image->IsValidTimeStep(timeSteps - 1) ) return;

  // The BaseData needs to be expanded, call the mitk::Image::Expand() method
  m_Image->Expand(timeSteps);

  if(timeSteps > m_ScalarMin.size() )
  {
    m_ScalarMin.resize(timeSteps, itk::NumericTraits<ScalarType>::max());
    m_ScalarMax.resize(timeSteps, itk::NumericTraits<ScalarType>::NonpositiveMin());
    m_Scalar2ndMin.resize(timeSteps, itk::NumericTraits<ScalarType>::max());
    m_Scalar2ndMax.resize(timeSteps, itk::NumericTraits<ScalarType>::NonpositiveMin());
    m_CountOfMinValuedVoxels.resize(timeSteps, 0);
    m_CountOfMaxValuedVoxels.resize(timeSteps, 0);
  }
}

void mitk::ImageStatisticsHolder::ResetImageStatistics()
{
  m_ScalarMin.assign(1, itk::NumericTraits<ScalarType>::max());
  m_ScalarMax.assign(1, itk::NumericTraits<ScalarType>::NonpositiveMin());
  m_Scalar2ndMin.assign(1, itk::NumericTraits<ScalarType>::max());
  m_Scalar2ndMax.assign(1, itk::NumericTraits<ScalarType>::NonpositiveMin());
  m_CountOfMinValuedVoxels.assign(1, 0);
  m_CountOfMaxValuedVoxels.assign(1, 0);
}

#include "mitkImageAccessByItk.h"

//#define BOUNDINGOBJECT_IGNORE

template < typename ItkImageType >
void mitk::_ComputeExtremaInItkImage( const ItkImageType* itkImage, mitk::ImageStatisticsHolder* statisticsHolder, int t)
{
  typename ItkImageType::RegionType region;
  region = itkImage->GetBufferedRegion();
  if(region.Crop(itkImage->GetRequestedRegion()) == false) return;
  if(region != itkImage->GetRequestedRegion()) return;

  itk::ImageRegionConstIterator<ItkImageType> it(itkImage, region);
  typedef typename ItkImageType::PixelType TPixel;
  TPixel value = 0;

  if ( statisticsHolder == NULL || !statisticsHolder->IsValidTimeStep( t ) ) return;
  statisticsHolder->Expand(t+1); // make sure we have initialized all arrays
  statisticsHolder->m_CountOfMinValuedVoxels[t] = 0;
  statisticsHolder->m_CountOfMaxValuedVoxels[t] = 0;

  statisticsHolder->m_Scalar2ndMin[t]=
      statisticsHolder->m_ScalarMin[t] = itk::NumericTraits<ScalarType>::max();
  statisticsHolder->m_Scalar2ndMax[t]=
      statisticsHolder->m_ScalarMax[t] = itk::NumericTraits<ScalarType>::NonpositiveMin();

  while( !it.IsAtEnd() )
  {
    value = it.Get();
    //  if ( (value > mitkImage->m_ScalarMin) && (value < mitkImage->m_Scalar2ndMin) )        mitkImage->m_Scalar2ndMin = value;
    //  else if ( (value < mitkImage->m_ScalarMax) && (value > mitkImage->m_Scalar2ndMax) )   mitkImage->m_Scalar2ndMax = value;
    //  else if (value > mitkImage->m_ScalarMax)                                              mitkImage->m_ScalarMax = value;
    //  else if (value < mitkImage->m_ScalarMin)                                              mitkImage->m_ScalarMin = value;

    // if numbers start with 2ndMin or 2ndMax and never have that value again, the previous above logic failed
#ifdef BOUNDINGOBJECT_IGNORE
    if( value > -32765)
    {
#endif
      // update min
      if ( value < statisticsHolder->m_ScalarMin[t] )
      {
        statisticsHolder->m_Scalar2ndMin[t] =
            statisticsHolder->m_ScalarMin[t];    statisticsHolder->m_ScalarMin[t] = value;
        statisticsHolder->m_CountOfMinValuedVoxels[t] = 1;
      }
      else if ( value == statisticsHolder->m_ScalarMin[t] )
      {
        ++statisticsHolder->m_CountOfMinValuedVoxels[t];
      }
      else if ( value < statisticsHolder->m_Scalar2ndMin[t] )
      {
        statisticsHolder->m_Scalar2ndMin[t] = value;
      }

      // update max
      if ( value > statisticsHolder->m_ScalarMax[t] )
      {
        statisticsHolder->m_Scalar2ndMax[t] =
            statisticsHolder->m_ScalarMax[t];    statisticsHolder->m_ScalarMax[t] = value;
        statisticsHolder->m_CountOfMaxValuedVoxels[t] = 1;
      }
      else if ( value == statisticsHolder->m_ScalarMax[t] )
      {
        ++statisticsHolder->m_CountOfMaxValuedVoxels[t];
      }
      else if ( value > statisticsHolder->m_Scalar2ndMax[t] )
      {
        statisticsHolder->m_Scalar2ndMax[t] = value;
      }
#ifdef BOUNDINGOBJECT_IGNORE
    }
#endif

    ++it;
  }

  //// guard for wrong 2dMin/Max on single constant value images
  if (statisticsHolder->m_ScalarMax[t] == statisticsHolder->m_ScalarMin[t])
  {
    statisticsHolder->m_Scalar2ndMax[t] = statisticsHolder->m_Scalar2ndMin[t] = statisticsHolder->m_ScalarMax[t];
  }
  statisticsHolder->m_LastRecomputeTimeStamp.Modified();
  //MITK_DEBUG <<"extrema "<<itk::NumericTraits<TPixel>::NonpositiveMin()<<" "<<mitkImage->m_ScalarMin<<" "<<mitkImage->m_Scalar2ndMin<<" "<<mitkImage->m_Scalar2ndMax<<" "<<mitkImage->m_ScalarMax<<" "<<itk::NumericTraits<TPixel>::max();
}

void mitk::ImageStatisticsHolder::ComputeImageStatistics(int t)
{
  // timestep valid?
  if (!m_Image->IsValidTimeStep(t)) return;

  // image modified?
  if (this->m_Image->GetMTime() > m_LastRecomputeTimeStamp.GetMTime())
    this->ResetImageStatistics();

  Expand(t+1);

  // do we have valid information already?
  if( m_ScalarMin[t] != itk::NumericTraits<ScalarType>::max() ||
      m_Scalar2ndMin[t] != itk::NumericTraits<ScalarType>::max() ) return; // Values already calculated before...

  const mitk::PixelType pType = m_Image->GetPixelType(0);
  if(pType.GetNumberOfComponents() == 1)
  {
    // recompute
    mitk::ImageTimeSelector* timeSelector = this->GetTimeSelector();
    if(timeSelector!=NULL)
    {
      timeSelector->SetTimeNr(t);
      timeSelector->UpdateLargestPossibleRegion();
      mitk::Image* image = timeSelector->GetOutput();
      AccessByItk_2( image, _ComputeExtremaInItkImage, this, t );
    }
  }
  else if(pType.GetNumberOfComponents() > 1)
  {
    m_ScalarMin[t] = 0;
    m_ScalarMax[t] = 255;
  }
}

mitk::ScalarType mitk::ImageStatisticsHolder::GetScalarValueMin(int t)
{
  ComputeImageStatistics(t);
  return m_ScalarMin[t];
}

mitk::ScalarType mitk::ImageStatisticsHolder::GetScalarValueMax(int t)
{
  ComputeImageStatistics(t);
  return m_ScalarMax[t];
}

mitk::ScalarType mitk::ImageStatisticsHolder::GetScalarValue2ndMin(int t)
{
  ComputeImageStatistics(t);
  return m_Scalar2ndMin[t];
}

mitk::ScalarType mitk::ImageStatisticsHolder::GetScalarValue2ndMax(int t)
{
  ComputeImageStatistics(t);
  return m_Scalar2ndMax[t];
}

mitk::ScalarType mitk::ImageStatisticsHolder::GetCountOfMinValuedVoxels(int t)
{
  ComputeImageStatistics(t);
  return m_CountOfMinValuedVoxels[t];
}

mitk::ScalarType mitk::ImageStatisticsHolder::GetCountOfMaxValuedVoxels(int t)
{
  ComputeImageStatistics(t);
  return m_CountOfMaxValuedVoxels[t];
}

<commit_msg>added default values for m_Scalar2ndMin and Max<commit_after>#include "mitkImageStatisticsHolder.h"

#include "mitkHistogramGenerator.h"
#include "mitkImageTimeSelector.h"

mitk::ImageStatisticsHolder::ImageStatisticsHolder( mitk::Image::Pointer image)
  : m_Image(NULL), m_TimeSelectorForExtremaObject(NULL)
{
  m_CountOfMinValuedVoxels.resize(1, 0);
  m_CountOfMaxValuedVoxels.resize(1, 0);
  m_ScalarMin.resize(1, itk::NumericTraits<ScalarType>::max());
  m_ScalarMax.resize(1, itk::NumericTraits<ScalarType>::NonpositiveMin());
  m_Scalar2ndMin.resize(1, itk::NumericTraits<ScalarType>::max());
  m_Scalar2ndMax.resize(1, itk::NumericTraits<ScalarType>::NonpositiveMin());

  mitk::HistogramGenerator::Pointer generator = mitk::HistogramGenerator::New();
  m_HistogramGeneratorObject = generator;

  m_Image = image;

  // create time selector
  this->GetTimeSelector();

}

mitk::ImageStatisticsHolder::~ImageStatisticsHolder()
{
  m_HistogramGeneratorObject = NULL;
  m_TimeSelectorForExtremaObject = NULL;
}

const mitk::ImageStatisticsHolder::HistogramType* mitk::ImageStatisticsHolder::GetScalarHistogram(int t)
{
  mitk::ImageTimeSelector* timeSelector = this->GetTimeSelector();
  if(timeSelector!=NULL)
  {
    timeSelector->SetTimeNr(t);
    timeSelector->UpdateLargestPossibleRegion();

    mitk::HistogramGenerator* generator = static_cast<mitk::HistogramGenerator*>(m_HistogramGeneratorObject.GetPointer());
    generator->SetImage(timeSelector->GetOutput());
    generator->ComputeHistogram();
    return static_cast<const mitk::ImageStatisticsHolder::HistogramType*>(generator->GetHistogram());
  }
  return NULL;
}

bool mitk::ImageStatisticsHolder::IsValidTimeStep( int t) const
{
    return m_Image->IsValidTimeStep(t);
}

mitk::ImageTimeSelector* mitk::ImageStatisticsHolder::GetTimeSelector()
{
  if(m_TimeSelectorForExtremaObject.IsNull())
  {
    m_TimeSelectorForExtremaObject = ImageTimeSelector::New();

    ImageTimeSelector* timeSelector = static_cast<mitk::ImageTimeSelector*>( m_TimeSelectorForExtremaObject.GetPointer() );
    timeSelector->SetInput(m_Image);
    m_Image->UnRegister();
  }

  return static_cast<ImageTimeSelector*>( m_TimeSelectorForExtremaObject.GetPointer() );
}

void mitk::ImageStatisticsHolder::Expand( unsigned int timeSteps )
{
  if(! m_Image->IsValidTimeStep(timeSteps - 1) ) return;

  // The BaseData needs to be expanded, call the mitk::Image::Expand() method
  m_Image->Expand(timeSteps);

  if(timeSteps > m_ScalarMin.size() )
  {
    m_ScalarMin.resize(timeSteps, itk::NumericTraits<ScalarType>::max());
    m_ScalarMax.resize(timeSteps, itk::NumericTraits<ScalarType>::NonpositiveMin());
    m_Scalar2ndMin.resize(timeSteps, itk::NumericTraits<ScalarType>::max());
    m_Scalar2ndMax.resize(timeSteps, itk::NumericTraits<ScalarType>::NonpositiveMin());
    m_CountOfMinValuedVoxels.resize(timeSteps, 0);
    m_CountOfMaxValuedVoxels.resize(timeSteps, 0);
  }
}

void mitk::ImageStatisticsHolder::ResetImageStatistics()
{
  m_ScalarMin.assign(1, itk::NumericTraits<ScalarType>::max());
  m_ScalarMax.assign(1, itk::NumericTraits<ScalarType>::NonpositiveMin());
  m_Scalar2ndMin.assign(1, itk::NumericTraits<ScalarType>::max());
  m_Scalar2ndMax.assign(1, itk::NumericTraits<ScalarType>::NonpositiveMin());
  m_CountOfMinValuedVoxels.assign(1, 0);
  m_CountOfMaxValuedVoxels.assign(1, 0);
}

#include "mitkImageAccessByItk.h"

//#define BOUNDINGOBJECT_IGNORE

template < typename ItkImageType >
void mitk::_ComputeExtremaInItkImage( const ItkImageType* itkImage, mitk::ImageStatisticsHolder* statisticsHolder, int t)
{
  typename ItkImageType::RegionType region;
  region = itkImage->GetBufferedRegion();
  if(region.Crop(itkImage->GetRequestedRegion()) == false) return;
  if(region != itkImage->GetRequestedRegion()) return;

  itk::ImageRegionConstIterator<ItkImageType> it(itkImage, region);
  typedef typename ItkImageType::PixelType TPixel;
  TPixel value = 0;

  if ( statisticsHolder == NULL || !statisticsHolder->IsValidTimeStep( t ) ) return;
  statisticsHolder->Expand(t+1); // make sure we have initialized all arrays
  statisticsHolder->m_CountOfMinValuedVoxels[t] = 0;
  statisticsHolder->m_CountOfMaxValuedVoxels[t] = 0;

  statisticsHolder->m_Scalar2ndMin[t]=
      statisticsHolder->m_ScalarMin[t] = itk::NumericTraits<ScalarType>::max();
  statisticsHolder->m_Scalar2ndMax[t]=
      statisticsHolder->m_ScalarMax[t] = itk::NumericTraits<ScalarType>::NonpositiveMin();

  while( !it.IsAtEnd() )
  {
    value = it.Get();
    //  if ( (value > mitkImage->m_ScalarMin) && (value < mitkImage->m_Scalar2ndMin) )        mitkImage->m_Scalar2ndMin = value;
    //  else if ( (value < mitkImage->m_ScalarMax) && (value > mitkImage->m_Scalar2ndMax) )   mitkImage->m_Scalar2ndMax = value;
    //  else if (value > mitkImage->m_ScalarMax)                                              mitkImage->m_ScalarMax = value;
    //  else if (value < mitkImage->m_ScalarMin)                                              mitkImage->m_ScalarMin = value;

    // if numbers start with 2ndMin or 2ndMax and never have that value again, the previous above logic failed
#ifdef BOUNDINGOBJECT_IGNORE
    if( value > -32765)
    {
#endif
      // update min
      if ( value < statisticsHolder->m_ScalarMin[t] )
      {
        statisticsHolder->m_Scalar2ndMin[t] =
            statisticsHolder->m_ScalarMin[t];    statisticsHolder->m_ScalarMin[t] = value;
        statisticsHolder->m_CountOfMinValuedVoxels[t] = 1;
      }
      else if ( value == statisticsHolder->m_ScalarMin[t] )
      {
        ++statisticsHolder->m_CountOfMinValuedVoxels[t];
      }
      else if ( value < statisticsHolder->m_Scalar2ndMin[t] )
      {
        statisticsHolder->m_Scalar2ndMin[t] = value;
      }

      // update max
      if ( value > statisticsHolder->m_ScalarMax[t] )
      {
        statisticsHolder->m_Scalar2ndMax[t] =
            statisticsHolder->m_ScalarMax[t];    statisticsHolder->m_ScalarMax[t] = value;
        statisticsHolder->m_CountOfMaxValuedVoxels[t] = 1;
      }
      else if ( value == statisticsHolder->m_ScalarMax[t] )
      {
        ++statisticsHolder->m_CountOfMaxValuedVoxels[t];
      }
      else if ( value > statisticsHolder->m_Scalar2ndMax[t] )
      {
        statisticsHolder->m_Scalar2ndMax[t] = value;
      }
#ifdef BOUNDINGOBJECT_IGNORE
    }
#endif

    ++it;
  }

  //// guard for wrong 2dMin/Max on single constant value images
  if (statisticsHolder->m_ScalarMax[t] == statisticsHolder->m_ScalarMin[t])
  {
    statisticsHolder->m_Scalar2ndMax[t] = statisticsHolder->m_Scalar2ndMin[t] = statisticsHolder->m_ScalarMax[t];
  }
  statisticsHolder->m_LastRecomputeTimeStamp.Modified();
  //MITK_DEBUG <<"extrema "<<itk::NumericTraits<TPixel>::NonpositiveMin()<<" "<<mitkImage->m_ScalarMin<<" "<<mitkImage->m_Scalar2ndMin<<" "<<mitkImage->m_Scalar2ndMax<<" "<<mitkImage->m_ScalarMax<<" "<<itk::NumericTraits<TPixel>::max();
}

void mitk::ImageStatisticsHolder::ComputeImageStatistics(int t)
{
  // timestep valid?
  if (!m_Image->IsValidTimeStep(t)) return;

  // image modified?
  if (this->m_Image->GetMTime() > m_LastRecomputeTimeStamp.GetMTime())
    this->ResetImageStatistics();

  Expand(t+1);

  // do we have valid information already?
  if( m_ScalarMin[t] != itk::NumericTraits<ScalarType>::max() ||
      m_Scalar2ndMin[t] != itk::NumericTraits<ScalarType>::max() ) return; // Values already calculated before...

  const mitk::PixelType pType = m_Image->GetPixelType(0);
  if(pType.GetNumberOfComponents() == 1)
  {
    // recompute
    mitk::ImageTimeSelector* timeSelector = this->GetTimeSelector();
    if(timeSelector!=NULL)
    {
      timeSelector->SetTimeNr(t);
      timeSelector->UpdateLargestPossibleRegion();
      mitk::Image* image = timeSelector->GetOutput();
      AccessByItk_2( image, _ComputeExtremaInItkImage, this, t );
    }
  }
  else if(pType.GetNumberOfComponents() > 1)
  {
    m_ScalarMin[t] = 0;
    m_ScalarMax[t] = 255;
    m_Scalar2ndMin[t] = 0;
    m_Scalar2ndMax[t] = 255;
  }
}

mitk::ScalarType mitk::ImageStatisticsHolder::GetScalarValueMin(int t)
{
  ComputeImageStatistics(t);
  return m_ScalarMin[t];
}

mitk::ScalarType mitk::ImageStatisticsHolder::GetScalarValueMax(int t)
{
  ComputeImageStatistics(t);
  return m_ScalarMax[t];
}

mitk::ScalarType mitk::ImageStatisticsHolder::GetScalarValue2ndMin(int t)
{
  ComputeImageStatistics(t);
  return m_Scalar2ndMin[t];
}

mitk::ScalarType mitk::ImageStatisticsHolder::GetScalarValue2ndMax(int t)
{
  ComputeImageStatistics(t);
  return m_Scalar2ndMax[t];
}

mitk::ScalarType mitk::ImageStatisticsHolder::GetCountOfMinValuedVoxels(int t)
{
  ComputeImageStatistics(t);
  return m_CountOfMinValuedVoxels[t];
}

mitk::ScalarType mitk::ImageStatisticsHolder::GetCountOfMaxValuedVoxels(int t)
{
  ComputeImageStatistics(t);
  return m_CountOfMaxValuedVoxels[t];
}

<|endoftext|>


<commit_before>#include "consoleui.h"

using namespace std;

ConsoleUI::ConsoleUI()
{

}

void ConsoleUI::run()
{
    bool run = true;
    while (run)
    {
       cout << " ================================" << endl;
       cout << " Press 1 to add" << endl;
       cout << " Press 2 to sort" << endl;
       cout << " Press 3 to list" << endl;
       cout << " Press 4 to search"  << endl;
       cout << " Press 5 to remove scientist"     << endl;
       cout << " Press 6 to exit"     << endl;
       cout << " ================================" << endl;

       char input = '0';
       cin >> input;
       cin.clear();
       fflush(stdin);
       int choice = input - '0';

            switch (choice)
            {
            case 1:
                addData();
                break;
            case 2:
                sortData();
                break;
            case 3:
                showData();
                break;
            case 4:
                searchData();
                break;
            case 5:
                removeData();
            case 6:
                run = false;
                break;
            default:
                cout << "Error! Invalid Input" << endl;
            }
    }
}

void ConsoleUI::addData()
{

    string name;
    char gender;
    int birthYear;
    int deathYear;

    cout << "Enter Name: ";
    cin >> ws;
    getline(cin,name);

    if(!isupper(name[0]))
    {
        name[0] = toupper(name[0]);
    }
    cout << "Enter gender (M/F): ";
    cin >> gender;
    cin.clear();
    fflush(stdin);
    if(genderCheck(gender) == false)
    {
        if(check() == false)
        {
            return;
        }
    }
    cout << "Enter birth year: ";
    cin >> birthYear;
    cout << "Enter death year (0 for living person): ";
    cin >> deathYear;
    if(birthChecks(birthYear, deathYear) == false)
    {
        check();    // Checks if you want to try to input again.
    }
    else
    {
        Persons newPerson(name, gender, birthYear, deathYear);
        serve.add(newPerson);
    }
}
bool ConsoleUI::genderCheck(char& gender)
{

   if(gender == 'm' || gender == 'M' || gender == 'f' || gender == 'F')
   {
        if(gender == 'm')
        {
            gender = 'M';
        }
        if(gender == 'f')
        {
            gender = 'F';
        }

       return true;
   }
   else
   {
       cout << "Wrong input for gender!" << endl;
       return false;
   }
}

bool ConsoleUI::check()
{
    char continuel;
    cout << "Do you want to try again? (Y for yes and N for No)" ;
    cin  >> continuel;
    if(continuel == 'Y' || continuel == 'y')
    {
        addData();
        return true;
    }
    else
    {
       return false;
    }
}

bool ConsoleUI::birthChecks(int birthYear, int deathYear)
{

    if(birthYear < 0 )
    {
        cout << "You can not be born before the year zero." << endl;
        return false;

    }
    if(birthYear > 2016)
    {
        cout << "You can not be born after the year 2016" << endl;

        return false;

    }
    if(deathYear < birthYear && deathYear != 0)
    {
        cout << "You cannot die before you are born!" << endl;
        return false;

    }
    if(deathYear > 2016 )
    {

        cout << "You are Still alive.";
        return false;
    }

    return true;
}

void ConsoleUI::showData()
{
    cout << endl;
    printLine();
    for(size_t i = 0; i < serve.list().size();i++)
    {
        cout << serve.list()[i];
    }
     cout << "_____________________________________________________" << endl;

}

void ConsoleUI::searchData()
{
    bool error = false;
    do
    {
        cout << "How would you like to search the data?" << endl;
        cout << " =====================================" << endl;
        cout << " Press 1 to search by name" << endl;
        cout << " Press 2 to search by birth year" << endl;
        cout << " Press 3 to search for gender" << endl;
        cout << " Press 4 to search by birth year range" << endl;
        cout << " Press 5 to cancel" << endl;
        cout << " ======================================"  << endl;

        char input = '0';
        cin >> input;
        int choice = input - '0';

        switch(choice)
        {
            case 1:
            {
                string n = " ";
                cout << "Enter name: ";
                cin >> ws;
                getline(cin, n);
                vector<int> v_n = serve.searchByName(n);
                if (v_n.size() == 0) {
                    cout << "No results found\n";
                }
                else {
                    printLine();
                    for (unsigned int i = 0; i < v_n.size(); i++)
                    {
                        cout << serve.list()[v_n[i]];
                    }
                }
                error = false;
                break;
            }
            case 2:
            {
                int y = 0;
                cout << "Enter year: ";
                cin >> y;
                vector<int> v_y = serve.searchByYear(y);
                if (v_y.size() == 0) {
                    cout << "No results found\n";
                }
                else {
                    printLine();
                    for (unsigned int i = 0; i < v_y.size(); i++)
                    {
                        cout << serve.list()[v_y[i]];
                    }
                }
                error = false;
                break;
            }
            case 3:
            {
                char gender;
                cout << "Enter gender (M/F): ";
                cin >> gender;
                vector<int> v_g = serve.searchByGender(gender);
                if (v_g.size() == 0)
                {
                    cout << "No results found" << endl;
                }
                else
                {
                    printLine();
                    for (unsigned int i = 0; i < v_g.size(); i++)
                    {
                        cout << serve.list()[v_g[i]];
                    }
                }
                break;
            }
            case 4:
            {
                int f = 0, l = 0;
                cout << "Enter first year in range: ";
                cin >> f;
                cout << "Enter last yar in range: ";
                cin >> l;

                vector<int> v_r = serve.searchByRange(f,l);
                if (v_r.size() == 0)
                {
                    cout << "No results found" << endl;
                }
                else
                {
                    printLine();
                    for (unsigned int i = 0; i < v_r.size(); i++)
                    {
                        cout << serve.list()[v_r[i]];
                    }
                }
                break;
            }

            case 5:
                error = false;
                break;
            default:
            {
                cout << "Error! invalid input" << endl;
                error = true;
            }
        }
    } while (error);
}

void ConsoleUI::sortData()
{
    char input = '0';
    int choice = 0;
    int choice2 = 0;
    bool error = false;

    do
    {

        cout << "How would you like to sort the list?" << endl;
        cout << " ================================" << endl;
        cout << " Press 1 for Name" << endl;
        cout << " Press 2 for Birth Year" << endl;
        cout << " Press 3 for Death Year " << endl;
        cout << " Press 4 for Gender" << endl;
        cout << " Press 5 to cancel" << endl;
        cout << " ================================" << endl;

        cin >> input;
        choice = input - '0';
        choice2 = 0;
        input = '1';

            switch (choice)
                 {
                 case 1:
                    do
                    {
                        if (input != '1' && input != '2' && input != '3')
                        {
                            cout << "Error! Invalid input" << endl;
                        }
                        cout << "Regular or Reversed sorting?" << endl;
                        cout << " ================================" << endl;
                        cout << "Press 1 for regular sorting" << endl;
                        cout << "Press 2 for reversed sorting" << endl;
                        cout << "Press 3 to cancel" << endl;
                        cout << " ================================" << endl;

                        cin >> input;
                    }
                    while (input != '1' && input != '2' && input != '3');
                    choice2 = input - '0';

                    if (choice2 == 1 || choice2 == 2)
                    {
                        serve.sorting(choice, choice2);
                        error = false;
                    }
                    else
                    {
                        error = true;
                    }
                    break;
                 case 2:
                    do
                    {
                        if (input != '1' && input != '2' && input != '3')
                        {
                            cout << "Error! Invalid input" << endl;
                        }
                        cout << "Regular or Reversed sorting?" << endl;
                        cout << " ================================" << endl;
                        cout << "Press 1 for regular sorting" << endl;
                        cout << "Press 2 for reversed sorting" << endl;
                        cout << "Press 3 to cancel" << endl;
                        cout << " ================================" << endl;

                        cin >> input;
                    }
                    while (input != '1' && input != '2' && input != '3');
                    choice2 = input - '0';

                    if (choice2 == 1 || choice2 == 2)
                    {
                        serve.sorting(choice, choice2);
                        error = false;
                    }
                    else
                    {
                        error = true;
                    }
                    break;
                 case 3:
                    do
                    {
                        if (input != '1' && input != '2' && input != '3')
                        {
                            cout << "Error! Invalid input" << endl;
                        }
                        cout << "Regular or Reversed sorting?" << endl;
                        cout << " ================================" << endl;
                        cout << "Press 1 for regular sorting" << endl;
                        cout << "Press 2 for reversed sorting" << endl;
                        cout << "Press 3 to cancel" << endl;
                        cout << " ================================" << endl;

                        cin >> input;
                    }
                    while (input != '1' && input != '2' && input != '3');
                    choice2 = input - '0';

                    if (choice2 == 1 || choice2 == 2)
                    {
                        serve.sorting(choice, choice2);
                        error = false;
                    }
                    else
                    {
                        error = true;
                    }
                    break;
                 case 4:
                    do
                    {
                        if (input != '1' && input != '2' && input != '3')
                        {
                            cout << "Error! Invalid input" << endl;
                        }
                        cout << "Sort by Males or Females?" << endl;
                        cout << " ================================" << endl;
                        cout << "Press 1 for sorting by Females first" << endl;
                        cout << "Press 2 for sorting by Males first" << endl;
                        cout << "Press 3 to cancel" << endl;
                        cout << " ================================" << endl;

                        cin >> input;
                    }
                    while (input != '1' && input != '2' && input != '3');
                    choice2 = input - '0';

                    if (choice2 == 1 || choice2 == 2)
                    {
                        serve.sorting(choice, choice2);
                        error = false;
                    }
                    else
                    {
                        error = true;
                    }
                    break;
                 case 5:
                    error = false;
                    break;
                 default:
                     cout << "Error! Invalid input!" << endl;
                     error = true;
                 }
    }
    while (error);

    if (choice != 5) //if you press cancel, you don't want to see the list, do you?
    {
        showData();
    }
}

void ConsoleUI::printLine()
{
    cout.width(16);
    cout << left << "Name";
    cout <<  "\tGender\tBorn\tDied" << endl;
    cout << "_____________________________________________________" << endl;
}
void ConsoleUI::removeData()
{
    string str;
    cout << "Enter the name of the scientist you want to remove: " << endl;
}
<commit_msg> corrected search by gender<commit_after>#include "consoleui.h"

using namespace std;

ConsoleUI::ConsoleUI()
{

}

void ConsoleUI::run()
{
    bool run = true;
    while (run)
    {
       cout << " ================================" << endl;
       cout << " Press 1 to add" << endl;
       cout << " Press 2 to sort" << endl;
       cout << " Press 3 to list" << endl;
       cout << " Press 4 to search"  << endl;
       cout << " Press 5 to remove scientist"     << endl;
       cout << " Press 6 to exit"     << endl;
       cout << " ================================" << endl;

       char input = '0';
       cin >> input;
       cin.clear();
       fflush(stdin);
       int choice = input - '0';

            switch (choice)
            {
            case 1:
                addData();
                break;
            case 2:
                sortData();
                break;
            case 3:
                showData();
                break;
            case 4:
                searchData();
                break;
            case 5:
                removeData();
            case 6:
                run = false;
                break;
            default:
                cout << "Error! Invalid Input" << endl;
            }
    }
}

void ConsoleUI::addData()
{

    string name;
    char gender;
    int birthYear;
    int deathYear;

    cout << "Enter Name: ";
    cin >> ws;
    getline(cin,name);

    if(!isupper(name[0]))
    {
        name[0] = toupper(name[0]);
    }
    cout << "Enter gender (M/F): ";
    cin >> gender;
    cin.clear();
    fflush(stdin);
    if(genderCheck(gender) == false)
    {
        if(check() == false)
        {
            return;
        }
    }
    cout << "Enter birth year: ";
    cin >> birthYear;
    cout << "Enter death year (0 for living person): ";
    cin >> deathYear;
    if(birthChecks(birthYear, deathYear) == false)
    {
        check();    // Checks if you want to try to input again.
    }
    else
    {
        Persons newPerson(name, gender, birthYear, deathYear);
        serve.add(newPerson);
    }
}
bool ConsoleUI::genderCheck(char& gender)
{

   if(gender == 'm' || gender == 'M' || gender == 'f' || gender == 'F')
   {
        if(gender == 'm')
        {
            gender = 'M';
        }
        if(gender == 'f')
        {
            gender = 'F';
        }

       return true;
   }
   else
   {
       cout << "Wrong input for gender!" << endl;
       return false;
   }
}

bool ConsoleUI::check()
{
    char continuel;
    cout << "Do you want to try again? (Y for yes and N for No)" ;
    cin  >> continuel;
    if(continuel == 'Y' || continuel == 'y')
    {
        addData();
        return true;
    }
    else
    {
       return false;
    }
}

bool ConsoleUI::birthChecks(int birthYear, int deathYear)
{

    if(birthYear < 0 )
    {
        cout << "You can not be born before the year zero." << endl;
        return false;

    }
    if(birthYear > 2016)
    {
        cout << "You can not be born after the year 2016" << endl;

        return false;

    }
    if(deathYear < birthYear && deathYear != 0)
    {
        cout << "You cannot die before you are born!" << endl;
        return false;

    }
    if(deathYear > 2016 )
    {

        cout << "You are Still alive.";
        return false;
    }

    return true;
}

void ConsoleUI::showData()
{
    cout << endl;
    printLine();
    for(size_t i = 0; i < serve.list().size();i++)
    {
        cout << serve.list()[i];
    }
     cout << "_____________________________________________________" << endl;

}

void ConsoleUI::searchData()
{
    bool error = false;
    do
    {
        cout << "How would you like to search the data?" << endl;
        cout << " =====================================" << endl;
        cout << " Press 1 to search by name" << endl;
        cout << " Press 2 to search by birth year" << endl;
        cout << " Press 3 to search for gender" << endl;
        cout << " Press 4 to search by birth year range" << endl;
        cout << " Press 5 to cancel" << endl;
        cout << " ======================================"  << endl;

        char input = '0';
        cin >> input;
        int choice = input - '0';

        switch(choice)
        {
            case 1:
            {
                string n = " ";
                cout << "Enter name: ";
                cin >> ws;
                getline(cin, n);
                vector<int> v_n = serve.searchByName(n);
                if (v_n.size() == 0) {
                    cout << "No results found\n";
                }
                else {
                    printLine();
                    for (unsigned int i = 0; i < v_n.size(); i++)
                    {
                        cout << serve.list()[v_n[i]];
                    }
                }
                error = false;
                break;
            }
            case 2:
            {
                int y = 0;
                cout << "Enter year: ";
                cin >> y;
                vector<int> v_y = serve.searchByYear(y);
                if (v_y.size() == 0) {
                    cout << "No results found\n";
                }
                else {
                    printLine();
                    for (unsigned int i = 0; i < v_y.size(); i++)
                    {
                        cout << serve.list()[v_y[i]];
                    }
                }
                error = false;
                break;
            }
            case 3:
            {
                char gender;
                cout << "Enter gender (M/F): ";
                cin >> gender;
                if(genderCheck(gender) == false)
                {
                    searchData();
                }
                vector<int> v_g = serve.searchByGender(gender);
                if (v_g.size() == 0)
                {
                    cout << "No results found" << endl;
                }
                else
                {
                    printLine();
                    for (unsigned int i = 0; i < v_g.size(); i++)
                    {
                        cout << serve.list()[v_g[i]];
                    }
                }
                break;
            }
            case 4:
            {
                int f = 0, l = 0;
                cout << "Enter first year in range: ";
                cin >> f;
                cout << "Enter last yar in range: ";
                cin >> l;

                vector<int> v_r = serve.searchByRange(f,l);
                if (v_r.size() == 0)
                {
                    cout << "No results found" << endl;
                }
                else
                {
                    printLine();
                    for (unsigned int i = 0; i < v_r.size(); i++)
                    {
                        cout << serve.list()[v_r[i]];
                    }
                }
                break;
            }

            case 5:
                error = false;
                break;
            default:
            {
                cout << "Error! invalid input" << endl;
                error = true;
            }
        }
    } while (error);
}

void ConsoleUI::sortData()
{
    char input = '0';
    int choice = 0;
    int choice2 = 0;
    bool error = false;

    do
    {

        cout << "How would you like to sort the list?" << endl;
        cout << " ================================" << endl;
        cout << " Press 1 for Name" << endl;
        cout << " Press 2 for Birth Year" << endl;
        cout << " Press 3 for Death Year " << endl;
        cout << " Press 4 for Gender" << endl;
        cout << " Press 5 to cancel" << endl;
        cout << " ================================" << endl;

        cin >> input;
        choice = input - '0';
        choice2 = 0;
        input = '1';

            switch (choice)
                 {
                 case 1:
                    do
                    {
                        if (input != '1' && input != '2' && input != '3')
                        {
                            cout << "Error! Invalid input" << endl;
                        }
                        cout << "Regular or Reversed sorting?" << endl;
                        cout << " ================================" << endl;
                        cout << "Press 1 for regular sorting" << endl;
                        cout << "Press 2 for reversed sorting" << endl;
                        cout << "Press 3 to cancel" << endl;
                        cout << " ================================" << endl;

                        cin >> input;
                    }
                    while (input != '1' && input != '2' && input != '3');
                    choice2 = input - '0';

                    if (choice2 == 1 || choice2 == 2)
                    {
                        serve.sorting(choice, choice2);
                        error = false;
                    }
                    else
                    {
                        error = true;
                    }
                    break;
                 case 2:
                    do
                    {
                        if (input != '1' && input != '2' && input != '3')
                        {
                            cout << "Error! Invalid input" << endl;
                        }
                        cout << "Regular or Reversed sorting?" << endl;
                        cout << " ================================" << endl;
                        cout << "Press 1 for regular sorting" << endl;
                        cout << "Press 2 for reversed sorting" << endl;
                        cout << "Press 3 to cancel" << endl;
                        cout << " ================================" << endl;

                        cin >> input;
                    }
                    while (input != '1' && input != '2' && input != '3');
                    choice2 = input - '0';

                    if (choice2 == 1 || choice2 == 2)
                    {
                        serve.sorting(choice, choice2);
                        error = false;
                    }
                    else
                    {
                        error = true;
                    }
                    break;
                 case 3:
                    do
                    {
                        if (input != '1' && input != '2' && input != '3')
                        {
                            cout << "Error! Invalid input" << endl;
                        }
                        cout << "Regular or Reversed sorting?" << endl;
                        cout << " ================================" << endl;
                        cout << "Press 1 for regular sorting" << endl;
                        cout << "Press 2 for reversed sorting" << endl;
                        cout << "Press 3 to cancel" << endl;
                        cout << " ================================" << endl;

                        cin >> input;
                    }
                    while (input != '1' && input != '2' && input != '3');
                    choice2 = input - '0';

                    if (choice2 == 1 || choice2 == 2)
                    {
                        serve.sorting(choice, choice2);
                        error = false;
                    }
                    else
                    {
                        error = true;
                    }
                    break;
                 case 4:
                    do
                    {
                        if (input != '1' && input != '2' && input != '3')
                        {
                            cout << "Error! Invalid input" << endl;
                        }
                        cout << "Sort by Males or Females?" << endl;
                        cout << " ================================" << endl;
                        cout << "Press 1 for sorting by Females first" << endl;
                        cout << "Press 2 for sorting by Males first" << endl;
                        cout << "Press 3 to cancel" << endl;
                        cout << " ================================" << endl;

                        cin >> input;
                    }
                    while (input != '1' && input != '2' && input != '3');
                    choice2 = input - '0';

                    if (choice2 == 1 || choice2 == 2)
                    {
                        serve.sorting(choice, choice2);
                        error = false;
                    }
                    else
                    {
                        error = true;
                    }
                    break;
                 case 5:
                    error = false;
                    break;
                 default:
                     cout << "Error! Invalid input!" << endl;
                     error = true;
                 }
    }
    while (error);

    if (choice != 5) //if you press cancel, you don't want to see the list, do you?
    {
        showData();
    }
}

void ConsoleUI::printLine()
{
    cout.width(16);
    cout << left << "Name";
    cout <<  "\tGender\tBorn\tDied" << endl;
    cout << "_____________________________________________________" << endl;
}
void ConsoleUI::removeData()
{
    string str;
    cout << "Enter the name of the scientist you want to remove: " << endl;
}
<|endoftext|>


<commit_before>#include "consoleui.h"
#include "servicelayer.h"
#include <fstream>
#include <string>
#include <iostream>

using namespace std;

ConsoleUI::ConsoleUI()
{

}

void ConsoleUI::run()
{
    bool run = true;
    while (run)
    {
       cout << " ================================" << endl;
       cout << " Press 1 to add" << endl;
       cout << " Press 2 to sort" << endl;
       cout << " Press 3 to list" << endl;
       cout << " Press 4 to search"  << endl;
       cout << " Press 5 to exit"     << endl;
       cout << " ================================" << endl;

       char input = '0';
       cin >> input;
       int choice = input - '0';

            switch (choice)
            {
            case 1:
                addData();
                break;
            case 2:
                sortData();
                break;
            case 3:
                showData();
                break;
            case 4:
                searchData();
                break;
            case 5:
                run = false;
                break;
            default:
                cout << "Error! Invalid Input" << endl;
            }

    }

}

void ConsoleUI::addData()
{
    string name;
    char gender;
    int birthYear;
    int deathYear;

    cout << "Enter Name: ";
    cin >> ws;
    getline(cin,name);
    cout << "Enter gender (M/F): ";
    cin >> gender;
    cout << "Enter birth year: ";
    cin >> birthYear;
    cout << "Enter death year (0 for living person): ";
    cin >> deathYear;

    Persons newPerson(name, gender, birthYear, deathYear);
    serve.add(newPerson);
}

void ConsoleUI::showData()
{
    printLine();
    for(size_t i = 0; i < serve.list().size();i++)
    {
        cout << serve.list()[i].getName() << "\t " << serve.list()[i].getGender() << "\t" << serve.list()[i].getBirthYear() << "\t";
        if (serve.list()[i].getAlive()) {
            cout << "Alive\n";
        }
        else {
            cout << serve.list()[i].getDeathYear() << endl;
        }
    }

}

void ConsoleUI::searchData()
{
    bool error = false;
    do
    {
        cout << "How would you like to search the data?" << endl;
        cout << " =====================================" << endl;
        cout << " Press 1 to search by name" << endl;
        cout << " Press 2 to search by birth year" << endl;
        cout << " Press 3 to cancel" << endl;
        cout << "======================================"  << endl;

        char input = '0';
        cin >> input;
        int choice = input - '0';

        switch(choice)
        {
            case 1:
            {
                string n = " ";
                cout << "Enter name: ";
                cin >> n;
                vector<int> v_n = serve.searchByName(n);
                if (v_n.size() == 0) {
                    cout << "No results found\n";
                }
                else {
                    printLine();
                    for (unsigned int i = 0; i < v_n.size(); i++)
                    {
                        cout << serve.list()[v_n[i]].getName() << "\t " << serve.list()[v_n[i]].getGender() << "\t" << serve.list()[v_n[i]].getBirthYear() << "\t";
                        if (serve.list()[v_n[i]].getAlive())
                        {
                                    cout << "Alive\n";
                        }
                        else
                        {
                            cout << serve.list()[v_n[i]].getDeathYear() << endl;
                        }
                    }
                }
                error = false;
                break;
            }
            case 2:
            {
                int y = 0;
                cout << "Enter year: ";
                cin >> y;
                vector<int> v_y = serve.searchByYear(y);
                if (v_y.size() == 0) {
                    cout << "No results found\n";
                }
                else {
                    printLine();
                    for (unsigned int i = 0; i < v_y.size(); i++)
                    {
                        cout << serve.list()[v_y[i]].getName() << "\t " << serve.list()[v_y[i]].getGender() << "\t" << serve.list()[v_y[i]].getBirthYear() << "\t";
                        if (serve.list()[v_y[i]].getAlive())
                        {
                                    cout << "Alive\n";
                        }
                        else
                        {
                            cout << serve.list()[v_y[i]].getDeathYear() << endl;
                        }
                    }
                }
                error = false;
                break;
            }
            case 3:
                error = false;
                break;
            default:
            {
                cout << "Error! invalid input" << endl;
                error = true;
            }
        }
    } while (error);
}

void ConsoleUI::sortData()
{

    bool error = false;

    do
    {

    cout << "How would you like to sort the list?" << endl;
    cout << " ================================" << endl;
    cout << "Press 1 for Name" << endl;
    cout << "Press 2 for Birth Year" << endl;
    cout << "Press 3 for Death Year " << endl;
    cout << "Press 4 for Gender" << endl;
    cout << "Press 5 to cancel" << endl;
    cout << " ================================" << endl;

    char input = '0';
    cin >> input;
    int choice = input - '0';

    switch (choice)
         {
         case 1:
            serve.sort(choice);
            error = false;
            break;
         case 2:
            serve.sort(choice);
            error = false;
            break;
         case 3:
            serve.sort(choice);
            error = false;
            break;
         case 4:
            serve.sort(choice);
            error = false;
            break;
         case 5:
            error = false;
            break;
         default:
             cout << "Error! Invalid input!" << endl;
             error = true;
         }
    }

    while (error);

    showData();
}

void ConsoleUI::printLine()
{
    cout.width(16);
    cout << left << "Name";
    cout <<  "\tGender" << "\t" << "Born" << "\t" << "Died" << endl;
    cout << "_____________________________________________________" << endl;
}
<commit_msg>search fallið<commit_after>#include "consoleui.h"
#include "servicelayer.h"
#include <fstream>
#include <string>
#include <iostream>

using namespace std;

ConsoleUI::ConsoleUI()
{

}

void ConsoleUI::run()
{
    bool run = true;
    while (run)
    {
       cout << " ================================" << endl;
       cout << " Press 1 to add" << endl;
       cout << " Press 2 to sort" << endl;
       cout << " Press 3 to list" << endl;
       cout << " Press 4 to search"  << endl;
       cout << " Press 5 to exit"     << endl;
       cout << " ================================" << endl;

       char input = '0';
       cin >> input;
       int choice = input - '0';

            switch (choice)
            {
            case 1:
                addData();
                break;
            case 2:
                sortData();
                break;
            case 3:
                showData();
                break;
            case 4:
                searchData();
                break;
            case 5:
                run = false;
                break;
            default:
                cout << "Error! Invalid Input" << endl;
            }

    }

}

void ConsoleUI::addData()
{
    string name;
    char gender;
    int birthYear;
    int deathYear;

    cout << "Enter Name: ";
    cin >> ws;
    getline(cin,name);
    cout << "Enter gender (M/F): ";
    cin >> gender;
    cout << "Enter birth year: ";
    cin >> birthYear;
    cout << "Enter death year (0 for living person): ";
    cin >> deathYear;

    Persons newPerson(name, gender, birthYear, deathYear);
    serve.add(newPerson);
}

void ConsoleUI::showData()
{
    printLine();
    for(size_t i = 0; i < serve.list().size();i++)
    {
        cout << serve.list()[i].getName() << "\t " << serve.list()[i].getGender() << "\t" << serve.list()[i].getBirthYear() << "\t";
        if (serve.list()[i].getAlive()) {
            cout << "Alive\n";
        }
        else {
            cout << serve.list()[i].getDeathYear() << endl;
        }
    }

}

void ConsoleUI::searchData()
{
    bool error = false;
    do
    {
        cout << "How would you like to search the data?" << endl;
        cout << " =====================================" << endl;
        cout << " Press 1 to search by name" << endl;
        cout << " Press 2 to search by birth year" << endl;
        cout << " Press 3 to cancel" << endl;
        cout << "======================================"  << endl;

        char input = '0';
        cin >> input;
        int choice = input - '0';

        switch(choice)
        {
            case 1:
            {
                string n = " ";
                cout << "Enter name: ";
                cin >> n;
                vector<int> v_n = serve.searchByName(n);
                if (v_n.size() == 0) {
                    cout << "No results found\n";
                }
                else {
                    printLine();
                    for (unsigned int i = 0; i < v_n.size(); i++)
                    {
                        cout << serve.list()[v_n[i]].getName() << "\t " << serve.list()[v_n[i]].getGender() << "\t" << serve.list()[v_n[i]].getBirthYear() << "\t";
                        if (serve.list()[v_n[i]].getAlive())
                        {
                                    cout << "Alive\n";
                        }
                        else
                        {
                            cout << serve.list()[v_n[i]].getDeathYear() << endl;
                        }
                    }
                }
                error = false;
                break;
            }
            case 2:
            {
                int y = 0;
                cout << "Enter year: ";
                cin >> y;
                vector<int> v_y = serve.searchByYear(y);
                if (v_y.size() == 0) {
                    cout << "No results found\n";
                }
                else {
                    printLine();
                    for (unsigned int i = 0; i < v_y.size(); i++)
                    {
                        cout << serve.list()[v_y[i]].getName() << "\t " << serve.list()[v_y[i]].getGender() << "\t" << serve.list()[v_y[i]].getBirthYear() << "\t";
                        if (serve.list()[v_y[i]].getAlive())
                        {
                                    cout << "Alive\n";
                        }
                        else
                        {
                            cout << serve.list()[v_y[i]].getDeathYear() << endl;
                        }
                    }
                }
                error = false;
                break;
            }
            case 3:
                error = false;
                break;
            default:
            {
                cout << "Error! invalid input" << endl;
                error = true;
            }
        }
    } while (error);
}

void ConsoleUI::sortData()
{

    bool error = false;

    do
    {

    cout << "How would you like to sort the list?" << endl;
    cout << " ================================" << endl;
    cout << "Press 1 for Name" << endl;
    cout << "Press 2 for Birth Year" << endl;
    cout << "Press 3 for Death Year " << endl;
    cout << "Press 4 for Gender" << endl;
    cout << "Press 5 to cancel" << endl;
    cout << " ================================" << endl;

    char input = '0';
    cin >> input;
    int choice = input - '0';

    switch (choice)
         {
         case 1:
            serve.sort(choice);
            error = false;
            break;
         case 2:
            serve.sort(choice);
            error = false;
            break;
         case 3:
            serve.sort(choice);
            error = false;
            break;
         case 4:
            serve.sort(choice);
            error = false;
            break;
         case 5:
            error = false;
            break;
         default:
             cout << "Error! Invalid input!" << endl;
             error = true;
         }
    }

    while (error);

    showData();
}

void ConsoleUI::printLine()
{
    cout.width(16);
    cout << left << "Name\t";
    cout <<  "\tGender" << "\t" << "Born" << "\t" << "Died" << endl;
    cout << "_____________________________________________________" << endl;
}
<|endoftext|>