<commit_before>/*
 * Copyright © 2011 Linaro Ltd.
 * Copyright © 2017 Collabora Ltd.
 *
 * This file is part of vkmark.
 *
 * vkmark 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.
 *
 * vkmark 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 vkmark.  If not, see <http://www.gnu.org/licenses/>.
 *
 * Authors:
 *   Alexandros Frantzis <alexandros.frantzis@collabora.com>
 */

#include <cstdio>
#include <getopt.h>
#include <algorithm>
#include <cctype>

#include "options.h"
#include "util.h"

namespace
{

struct option long_options[] = {
    {"benchmark", 1, 0, 0},
    {"size", 1, 0, 0},
    {"fullscreen", 0, 0, 0},
    {"present-mode", 1, 0, 0},
    {"pixel-format", 1, 0, 0},
    {"list-scenes", 0, 0, 0},
    {"show-all-options", 0, 0, 0},
    {"winsys-dir", 1, 0, 0},
    {"data-dir", 1, 0, 0},
    {"winsys", 1, 0, 0},
    {"winsys-options", 1, 0, 0},
    {"debug", 0, 0, 0},
    {"help", 0, 0, 0},
    {0, 0, 0, 0}
};

std::pair<int,int> parse_size(std::string const& str)
{
    std::pair<int,int> size;
    auto const dimensions = Util::split(str, 'x');

    size.first = Util::from_string<int>(dimensions[0]);

    /*
     * Parse the second element (height). If there is none, use the value
     * of the first element for the second (width = height)
     */
    if (dimensions.size() > 1)
        size.second = Util::from_string<int>(dimensions[1]);
    else
        size.second = size.first;

    return size;
}

vk::PresentModeKHR parse_present_mode(std::string const& str)
{
    if (str == "immediate")
        return vk::PresentModeKHR::eImmediate;
    else if (str == "mailbox")
        return vk::PresentModeKHR::eMailbox;
    else if (str == "fifo")
        return vk::PresentModeKHR::eFifo;
    else if (str == "fiforelaxed")
        return vk::PresentModeKHR::eFifoRelaxed;
    else
        return vk::PresentModeKHR::eMailbox;
}

std::string normalize_pixel_format(std::string str)
{
    str.erase(std::remove(str.begin(), str.end(), '_'), str.end());
    std::transform(str.begin(), str.end(), str.begin(),
                   [](auto c) { return std::toupper(c); });
    return str;
}

vk::Format parse_pixel_format(std::string const& str)
{
    for (auto e = static_cast<vk::Format>(VK_FORMAT_BEGIN_RANGE);
         e < static_cast<vk::Format>(VK_FORMAT_END_RANGE);
         e = static_cast<vk::Format>(static_cast<int>(e) + 1))
    {
        if (normalize_pixel_format(to_string(e)) == normalize_pixel_format(str))
            return e;
    }

    return vk::Format::eUndefined;
}

std::vector<Options::WindowSystemOption> parse_window_system_options(
    std::string const& options_str)
{
    std::vector<Options::WindowSystemOption> ret;

    auto const opts = Util::split(options_str, ':');

    for (auto const& opt : opts)
    {
        auto const kv = Util::split(opt, '=');
        if (kv.size() == 2)
            ret.push_back({kv[0], kv[1]});
        else
            throw std::runtime_error{"Invalid window system option '" + opt + "'"};
    }

    return ret;
}

}

Options::Options()
    : size{800, 600},
      present_mode{vk::PresentModeKHR::eMailbox},
      pixel_format{vk::Format::eUndefined},
      list_scenes{false},
      show_all_options{false},
      window_system_dir{VKMARK_WINDOW_SYSTEM_DIR},
      data_dir{VKMARK_DATA_DIR},
      show_debug{false},
      show_help{false}
{
}

std::string Options::help_string()
{
    std::string help =
        "A benchmark for Vulkan\n"
        "\n"
        "Options:\n"
        "  -b, --benchmark BENCH       A benchmark to run: 'scene(:opt1=val1)*'\n"
        "                              (the option can be used multiple times)\n"
        "  -s, --size WxH              Size of the output window (default: 800x600)\n"
        "      --fullscreen            Run fullscreen (equivalent to --size -1x-1)\n"
        "  -p, --present-mode PM       Vulkan present mode (default: mailbox)\n"
        "                              [immediate, mailbox, fifo, fiforelaxed]\n"
        "      --pixel-format PF       Vulkan pixel format (default: first reported)\n"
        "  -l, --list-scenes           Display information about the available scenes\n"
        "                              and their options\n"
        "      --show-all-options      Show all scene option values used for benchmarks\n"
        "                              (only explicitly set options are shown by default)\n"
        "      --winsys-dir DIR        Directory to search in for window system modules\n"
        "      --data-dir DIR          Directory to search in for scene data files\n"
        "      --winsys WS             Window system backend to use (xcb, wayland, kms)\n"
        "      --winsys-options OPTS   Window system options as 'opt1=val1(:opt2=val2)*'\n"
        "  -d, --debug                 Display debug messages\n"
        "  -h, --help                  Display help\n";

    for (auto const& wsh : window_system_help)
        help += wsh;

    return help;
}

bool Options::parse_args(int argc, char **argv)
{
    // Reset optind to allow multiple invocations of parse_args
    optind = 0;

    while (true)
    {
        int option_index = -1;
        int c;
        std::string optname;

        c = getopt_long(argc, argv, "b:s:p:ldh",
                        long_options, &option_index);
        if (c == -1)
            break;
        if (c == ':' || c == '?')
            return false;

        if (option_index != -1)
            optname = long_options[option_index].name;

        if (c == 'b' || optname == "benchmark")
            benchmarks.push_back(optarg);
        else if (c == 's' || optname == "size")
            size = parse_size(optarg);
        else if (optname == "fullscreen")
            size = {-1, -1};
        else if (c == 'p' || optname == "present-mode")
            present_mode = parse_present_mode(optarg);
        else if (optname == "pixel-format")
            pixel_format = parse_pixel_format(optarg);
        else if (c == 'l' || optname == "list-scenes")
            list_scenes = true;
        else if (optname == "show-all-options")
            show_all_options = true;
        else if (optname == "winsys-dir")
            window_system_dir = optarg;
        else if (optname == "data-dir")
            data_dir = optarg;
        else if (optname == "winsys")
            window_system = optarg;
        else if (optname == "winsys-options")
            window_system_options = parse_window_system_options(optarg);
        else if (c == 'd' || optname == "debug")
            show_debug = true;
        else if (c == 'h' || optname == "help")
            show_help = true;
    }

    return true;
}

void Options::add_window_system_help(std::string const& help)
{
    window_system_help.push_back(help);
}
<commit_msg>core: Update --help text<commit_after>/*
 * Copyright © 2011 Linaro Ltd.
 * Copyright © 2017 Collabora Ltd.
 *
 * This file is part of vkmark.
 *
 * vkmark 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.
 *
 * vkmark 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 vkmark.  If not, see <http://www.gnu.org/licenses/>.
 *
 * Authors:
 *   Alexandros Frantzis <alexandros.frantzis@collabora.com>
 */

#include <cstdio>
#include <getopt.h>
#include <algorithm>
#include <cctype>

#include "options.h"
#include "util.h"

namespace
{

struct option long_options[] = {
    {"benchmark", 1, 0, 0},
    {"size", 1, 0, 0},
    {"fullscreen", 0, 0, 0},
    {"present-mode", 1, 0, 0},
    {"pixel-format", 1, 0, 0},
    {"list-scenes", 0, 0, 0},
    {"show-all-options", 0, 0, 0},
    {"winsys-dir", 1, 0, 0},
    {"data-dir", 1, 0, 0},
    {"winsys", 1, 0, 0},
    {"winsys-options", 1, 0, 0},
    {"debug", 0, 0, 0},
    {"help", 0, 0, 0},
    {0, 0, 0, 0}
};

std::pair<int,int> parse_size(std::string const& str)
{
    std::pair<int,int> size;
    auto const dimensions = Util::split(str, 'x');

    size.first = Util::from_string<int>(dimensions[0]);

    /*
     * Parse the second element (height). If there is none, use the value
     * of the first element for the second (width = height)
     */
    if (dimensions.size() > 1)
        size.second = Util::from_string<int>(dimensions[1]);
    else
        size.second = size.first;

    return size;
}

vk::PresentModeKHR parse_present_mode(std::string const& str)
{
    if (str == "immediate")
        return vk::PresentModeKHR::eImmediate;
    else if (str == "mailbox")
        return vk::PresentModeKHR::eMailbox;
    else if (str == "fifo")
        return vk::PresentModeKHR::eFifo;
    else if (str == "fiforelaxed")
        return vk::PresentModeKHR::eFifoRelaxed;
    else
        return vk::PresentModeKHR::eMailbox;
}

std::string normalize_pixel_format(std::string str)
{
    str.erase(std::remove(str.begin(), str.end(), '_'), str.end());
    std::transform(str.begin(), str.end(), str.begin(),
                   [](auto c) { return std::toupper(c); });
    return str;
}

vk::Format parse_pixel_format(std::string const& str)
{
    for (auto e = static_cast<vk::Format>(VK_FORMAT_BEGIN_RANGE);
         e < static_cast<vk::Format>(VK_FORMAT_END_RANGE);
         e = static_cast<vk::Format>(static_cast<int>(e) + 1))
    {
        if (normalize_pixel_format(to_string(e)) == normalize_pixel_format(str))
            return e;
    }

    return vk::Format::eUndefined;
}

std::vector<Options::WindowSystemOption> parse_window_system_options(
    std::string const& options_str)
{
    std::vector<Options::WindowSystemOption> ret;

    auto const opts = Util::split(options_str, ':');

    for (auto const& opt : opts)
    {
        auto const kv = Util::split(opt, '=');
        if (kv.size() == 2)
            ret.push_back({kv[0], kv[1]});
        else
            throw std::runtime_error{"Invalid window system option '" + opt + "'"};
    }

    return ret;
}

}

Options::Options()
    : size{800, 600},
      present_mode{vk::PresentModeKHR::eMailbox},
      pixel_format{vk::Format::eUndefined},
      list_scenes{false},
      show_all_options{false},
      window_system_dir{VKMARK_WINDOW_SYSTEM_DIR},
      data_dir{VKMARK_DATA_DIR},
      show_debug{false},
      show_help{false}
{
}

std::string Options::help_string()
{
    std::string help =
        "A benchmark for Vulkan\n"
        "\n"
        "Options:\n"
        "  -b, --benchmark BENCH       A benchmark to run: 'scene(:opt1=val1)*'\n"
        "                              (the option can be used multiple times)\n"
        "  -s, --size WxH              Size of the output window (default: 800x600)\n"
        "      --fullscreen            Run fullscreen (equivalent to --size -1x-1)\n"
        "  -p, --present-mode PM       Vulkan present mode (default: mailbox)\n"
        "                              [immediate, mailbox, fifo, fiforelaxed]\n"
        "      --pixel-format PF       Vulkan pixel format (default: choose best)\n"
        "  -l, --list-scenes           Display information about the available scenes\n"
        "                              and their options\n"
        "      --show-all-options      Show all scene option values used for benchmarks\n"
        "                              (only explicitly set options are shown by default)\n"
        "      --winsys-dir DIR        Directory to search in for window system plugins\n"
        "      --data-dir DIR          Directory to search in for scene data files\n"
        "      --winsys WS             Window system plugin to use (default: choose best)\n"
        "                              [xcb, wayland, kms]\n"
        "      --winsys-options OPTS   Window system options as 'opt1=val1(:opt2=val2)*'\n"
        "  -d, --debug                 Display debug messages\n"
        "  -h, --help                  Display help\n";

    for (auto const& wsh : window_system_help)
        help += wsh;

    return help;
}

bool Options::parse_args(int argc, char **argv)
{
    // Reset optind to allow multiple invocations of parse_args
    optind = 0;

    while (true)
    {
        int option_index = -1;
        int c;
        std::string optname;

        c = getopt_long(argc, argv, "b:s:p:ldh",
                        long_options, &option_index);
        if (c == -1)
            break;
        if (c == ':' || c == '?')
            return false;

        if (option_index != -1)
            optname = long_options[option_index].name;

        if (c == 'b' || optname == "benchmark")
            benchmarks.push_back(optarg);
        else if (c == 's' || optname == "size")
            size = parse_size(optarg);
        else if (optname == "fullscreen")
            size = {-1, -1};
        else if (c == 'p' || optname == "present-mode")
            present_mode = parse_present_mode(optarg);
        else if (optname == "pixel-format")
            pixel_format = parse_pixel_format(optarg);
        else if (c == 'l' || optname == "list-scenes")
            list_scenes = true;
        else if (optname == "show-all-options")
            show_all_options = true;
        else if (optname == "winsys-dir")
            window_system_dir = optarg;
        else if (optname == "data-dir")
            data_dir = optarg;
        else if (optname == "winsys")
            window_system = optarg;
        else if (optname == "winsys-options")
            window_system_options = parse_window_system_options(optarg);
        else if (c == 'd' || optname == "debug")
            show_debug = true;
        else if (c == 'h' || optname == "help")
            show_help = true;
    }

    return true;
}

void Options::add_window_system_help(std::string const& help)
{
    window_system_help.push_back(help);
}
<|endoftext|>


<commit_before>#ifndef FSM11_OPTIONS_HPP
#define FSM11_OPTIONS_HPP

#include "statemachine_fwd.hpp"
#include "detail/options.hpp"

#include <deque>
#include <memory>

namespace fsm11
{
namespace fsm11_detail
{

struct default_options
{
    // Types
    using event_type = unsigned;
    using event_list_type = std::deque<unsigned>;
    using storage = type_list<>;
    using transition_allocator_type = std::allocator<Transition<void>>;

    // Multithreading
    static constexpr bool synchronous_dispatch = true;
    static constexpr bool multithreading_enable = true; // TODO: Have an option

    // Callbacks
    static constexpr bool event_callbacks_enable = false;
    static constexpr bool configuration_change_callbacks_enable = false;
    static constexpr bool state_callbacks_enable = false;

    // Callbacks for exeptions
    static constexpr bool state_exception_callbacks_enable = false;
};

} // namespace fsm11_detail

// ----=====================================================================----
//     Types
// ----=====================================================================----

template <typename TType>
struct EventType
{
    //! \cond
    template <typename TBase>
    struct pack : TBase
    {
        using event_type = TType;
    };
    //! \endcond
};

template <typename TType>
struct EventListType
{
    //! \cond
    template <typename TBase>
    struct pack : TBase
    {
        using event_list_type = TType;
    };
    //! \endcond
};

template <typename... TTypes>
struct Storage
{
    //! \cond
    template <typename TBase>
    struct pack : TBase
    {
        using storage = fsm11_detail::type_list<TTypes...>;
    };
    //! \endcond
};

template <typename TAllocator>
struct TransitionAllocator
{
    //! \cond
    template <typename TBase>
    struct pack : TBase
    {
        using transition_allocator_type = TAllocator;
    };
    //! \endcond
};

// ----=====================================================================----
//     Multithreading
// ----=====================================================================----

struct SynchronousEventDispatching
{
    //! \cond
    template <typename TBase>
    struct pack : TBase
    {
        static constexpr bool synchronous_dispatch = true;
    };
    //! \endcond
};

struct AsynchronousEventDispatching
{
    //! \cond
    template <typename TBase>
    struct pack : TBase
    {
        static constexpr bool synchronous_dispatch = false;
    };
    //! \endcond
};

// ----=====================================================================----
//     Callbacks
// ----=====================================================================----

template <bool TEnable>
struct EnableEventCallbacks
{
    //! \cond
    template <typename TBase>
    struct pack : TBase
    {
        static constexpr bool event_callbacks_enable = TEnable;
    };
    //! \endcond
};

template <bool TEnable>
struct EnableConfigurationChangeCallbacks
{
    //! \cond
    template <typename TBase>
    struct pack : TBase
    {
        static constexpr bool configuration_change_callbacks_enable = TEnable;
    };
    //! \endcond
};

template <bool TEnable>
struct EnableStateCallbacks
{
    //! \cond
    template <typename TBase>
    struct pack : TBase
    {
        static constexpr bool state_callbacks_enable = TEnable;
    };
    //! \endcond
};

// ----=====================================================================----
//     Exception callbacks
// ----=====================================================================----

template <bool TEnable>
struct EnableStateExceptionCallbacks
{
    //! \cond
    template <typename TBase>
    struct pack : TBase
    {
        static constexpr bool state_exception_callbacks_enable = TEnable;
    };
    //! \endcond
};

} // namespace fsm11

#endif // FSM11_OPTIONS_HPP
<commit_msg>An asynchronous statemachine has a multithread lock by default.<commit_after>#ifndef FSM11_OPTIONS_HPP
#define FSM11_OPTIONS_HPP

#include "statemachine_fwd.hpp"
#include "detail/options.hpp"

#include <deque>
#include <memory>

namespace fsm11
{
namespace fsm11_detail
{

struct default_options
{
    // Types
    using event_type = unsigned;
    using event_list_type = std::deque<unsigned>;
    using storage = type_list<>;
    using transition_allocator_type = std::allocator<Transition<void>>;

    // Multithreading
    static constexpr bool synchronous_dispatch = true;
    static constexpr bool multithreading_enable = true; // TODO: Have an option

    // Callbacks
    static constexpr bool event_callbacks_enable = false;
    static constexpr bool configuration_change_callbacks_enable = false;
    static constexpr bool state_callbacks_enable = false;

    // Callbacks for exeptions
    static constexpr bool state_exception_callbacks_enable = false;
};

} // namespace fsm11_detail

// ----=====================================================================----
//     Types
// ----=====================================================================----

template <typename TType>
struct EventType
{
    //! \cond
    template <typename TBase>
    struct pack : TBase
    {
        using event_type = TType;
    };
    //! \endcond
};

template <typename TType>
struct EventListType
{
    //! \cond
    template <typename TBase>
    struct pack : TBase
    {
        using event_list_type = TType;
    };
    //! \endcond
};

template <typename... TTypes>
struct Storage
{
    //! \cond
    template <typename TBase>
    struct pack : TBase
    {
        using storage = fsm11_detail::type_list<TTypes...>;
    };
    //! \endcond
};

template <typename TAllocator>
struct TransitionAllocator
{
    //! \cond
    template <typename TBase>
    struct pack : TBase
    {
        using transition_allocator_type = TAllocator;
    };
    //! \endcond
};

// ----=====================================================================----
//     Multithreading
// ----=====================================================================----

struct SynchronousEventDispatching
{
    //! \cond
    template <typename TBase>
    struct pack : TBase
    {
        static constexpr bool synchronous_dispatch = true;
    };
    //! \endcond
};

struct AsynchronousEventDispatching
{
    //! \cond
    template <typename TBase>
    struct pack : TBase
    {
        static constexpr bool synchronous_dispatch = false;
        static constexpr bool multithreading_enable = true;
    };
    //! \endcond
};

// ----=====================================================================----
//     Callbacks
// ----=====================================================================----

template <bool TEnable>
struct EnableEventCallbacks
{
    //! \cond
    template <typename TBase>
    struct pack : TBase
    {
        static constexpr bool event_callbacks_enable = TEnable;
    };
    //! \endcond
};

template <bool TEnable>
struct EnableConfigurationChangeCallbacks
{
    //! \cond
    template <typename TBase>
    struct pack : TBase
    {
        static constexpr bool configuration_change_callbacks_enable = TEnable;
    };
    //! \endcond
};

template <bool TEnable>
struct EnableStateCallbacks
{
    //! \cond
    template <typename TBase>
    struct pack : TBase
    {
        static constexpr bool state_callbacks_enable = TEnable;
    };
    //! \endcond
};

// ----=====================================================================----
//     Exception callbacks
// ----=====================================================================----

template <bool TEnable>
struct EnableStateExceptionCallbacks
{
    //! \cond
    template <typename TBase>
    struct pack : TBase
    {
        static constexpr bool state_exception_callbacks_enable = TEnable;
    };
    //! \endcond
};

} // namespace fsm11

#endif // FSM11_OPTIONS_HPP
<|endoftext|>


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

#include "xmxtrct.hxx"

#include <rtl/memory.h>
#include <tools/zcodec.hxx>
#include <unotools/streamhelper.hxx>
#include <so3/svstor.hxx>

// ----------------
// - XMXLockBytes -
// ----------------

class XMXLockBytes : public SvLockBytes
{
    REF( NMSP_IO::XInputStream )    mxIStm;
    SEQ( sal_Int8 )                 maSeq;

                                    XMXLockBytes();

public:

                                    XMXLockBytes( const REF( NMSP_IO::XInputStream )& rxIStm );
    virtual                         ~XMXLockBytes();

    virtual ErrCode                 ReadAt( sal_uInt32 nPos, void* pBuffer, sal_uInt32 nCount, sal_uInt32* pRead ) const;
    virtual ErrCode                 WriteAt( sal_uInt32 nPos, const void* pBuffer, sal_uInt32 nCount, sal_uInt32* pWritten );
    virtual ErrCode                 Flush() const;
    virtual ErrCode                 SetSize( sal_uInt32 nSize );
    virtual ErrCode                 Stat( SvLockBytesStat*, SvLockBytesStatFlag ) const;
};

// ------------------------------------------------------------------------

XMXLockBytes::XMXLockBytes( const REF( NMSP_IO::XInputStream )& rxIStm ) :
    mxIStm( rxIStm )
{
    if( mxIStm.is() )
    {
        const sal_uInt32    nBytesToRead = 65535;
        sal_uInt32          nRead;

        do
        {
            SEQ( sal_Int8 ) aReadSeq;

            nRead = mxIStm->readSomeBytes( aReadSeq, nBytesToRead );

            if( nRead )
            {
                const sal_uInt32 nOldLength = maSeq.getLength();
                maSeq.realloc( nOldLength + nRead );
                rtl_copyMemory( maSeq.getArray() + nOldLength, aReadSeq.getConstArray(), aReadSeq.getLength() );
            }
        }
        while( nBytesToRead == nRead );
    }
}

// ------------------------------------------------------------------------

XMXLockBytes::~XMXLockBytes()
{
}

// ------------------------------------------------------------------------

ErrCode XMXLockBytes::ReadAt( sal_uInt32 nPos, void* pBuffer, sal_uInt32 nCount, sal_uInt32* pRead ) const
{
    const sal_uInt32    nSeqLen = maSeq.getLength();
    ErrCode             nErr = ERRCODE_NONE;

    if( nPos < nSeqLen )
    {
        if( ( nPos + nCount ) > nSeqLen )
            nCount = nSeqLen - nPos;

        rtl_copyMemory( pBuffer, maSeq.getConstArray() + nPos, nCount );
        *pRead = nCount;
    }
    else
        *pRead = 0UL;

    return nErr;
}

// ------------------------------------------------------------------------

ErrCode XMXLockBytes::WriteAt( sal_uInt32 nPos, const void* pBuffer, sal_uInt32 nCount, sal_uInt32* pWritten )
{
    return ERRCODE_IO_CANTWRITE;
}

// ------------------------------------------------------------------------

ErrCode XMXLockBytes::Flush() const
{
    return ERRCODE_NONE;
}

// ------------------------------------------------------------------------

ErrCode XMXLockBytes::SetSize( sal_uInt32 nSize )
{
    return ERRCODE_IO_CANTWRITE;
}

// ------------------------------------------------------------------------

ErrCode XMXLockBytes::Stat( SvLockBytesStat* pStat, SvLockBytesStatFlag eFlag ) const
{
    pStat->nSize = maSeq.getLength();
    return ERRCODE_NONE;
}

// ----------------
// - XMLExtractor -
// ----------------

XMLExtractor::XMLExtractor( const REF( NMSP_LANG::XMultiServiceFactory )& rxMgr ) :
    mxFact( rxMgr )
{
}

// -----------------------------------------------------------------------------

XMLExtractor::~XMLExtractor()
{
}

// -----------------------------------------------------------------------------

REF( NMSP_IO::XInputStream ) SAL_CALL XMLExtractor::extract( const REF( NMSP_IO::XInputStream )& rxIStm ) throw( NMSP_UNO::RuntimeException )
{
    REF( NMSP_IO::XInputStream ) xRet;

    if( rxIStm.is() )
    {
        SvStream        aIStm( new XMXLockBytes( rxIStm ) );
        SvStorageRef    aStorage( new SvStorage( aIStm ) );
        String          aStmName;
        const String    aFormat1( String::CreateFromAscii( "XMLFormat" ) );
        const String    aFormat2( String::CreateFromAscii( "XMLFormat2" ) );

        if( aStorage->IsContained( aFormat2 ) )
            aStmName = aFormat2;
        else if( aStorage->IsContained( aFormat1 ) )
            aStmName = aFormat1;

        if( !aStorage->GetError() && aStmName.Len() && aStorage->IsStream( aStmName ) )
        {
            SvStorageStreamRef xStream( aStorage->OpenStream( aStmName ) );

            if( xStream.Is() )
            {
                SvMemoryStream* pMemStm = new SvMemoryStream( 65535, 65535 );
                ZCodec          aCodec;

                aCodec.BeginCompression( ZCODEC_BEST_COMPRESSION );
                aCodec.Decompress( *xStream, *pMemStm );
                aCodec.EndCompression();

                xRet = new ::utl::OInputStreamHelper( new SvLockBytes( pMemStm, TRUE ), 65535 );
            }
        }
    }

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

#include "xmxtrct.hxx"

#include <rtl/memory.h>
#include <tools/zcodec.hxx>
#include <unotools/streamhelper.hxx>
#include <sot/storage.hxx>

// ----------------
// - XMXLockBytes -
// ----------------

class XMXLockBytes : public SvLockBytes
{
    REF( NMSP_IO::XInputStream )    mxIStm;
    SEQ( sal_Int8 )                 maSeq;

                                    XMXLockBytes();

public:

                                    XMXLockBytes( const REF( NMSP_IO::XInputStream )& rxIStm );
    virtual                         ~XMXLockBytes();

    virtual ErrCode                 ReadAt( sal_uInt32 nPos, void* pBuffer, sal_uInt32 nCount, sal_uInt32* pRead ) const;
    virtual ErrCode                 WriteAt( sal_uInt32 nPos, const void* pBuffer, sal_uInt32 nCount, sal_uInt32* pWritten );
    virtual ErrCode                 Flush() const;
    virtual ErrCode                 SetSize( sal_uInt32 nSize );
    virtual ErrCode                 Stat( SvLockBytesStat*, SvLockBytesStatFlag ) const;
};

// ------------------------------------------------------------------------

XMXLockBytes::XMXLockBytes( const REF( NMSP_IO::XInputStream )& rxIStm ) :
    mxIStm( rxIStm )
{
    if( mxIStm.is() )
    {
        const sal_uInt32    nBytesToRead = 65535;
        sal_uInt32          nRead;

        do
        {
            SEQ( sal_Int8 ) aReadSeq;

            nRead = mxIStm->readSomeBytes( aReadSeq, nBytesToRead );

            if( nRead )
            {
                const sal_uInt32 nOldLength = maSeq.getLength();
                maSeq.realloc( nOldLength + nRead );
                rtl_copyMemory( maSeq.getArray() + nOldLength, aReadSeq.getConstArray(), aReadSeq.getLength() );
            }
        }
        while( nBytesToRead == nRead );
    }
}

// ------------------------------------------------------------------------

XMXLockBytes::~XMXLockBytes()
{
}

// ------------------------------------------------------------------------

ErrCode XMXLockBytes::ReadAt( sal_uInt32 nPos, void* pBuffer, sal_uInt32 nCount, sal_uInt32* pRead ) const
{
    const sal_uInt32    nSeqLen = maSeq.getLength();
    ErrCode             nErr = ERRCODE_NONE;

    if( nPos < nSeqLen )
    {
        if( ( nPos + nCount ) > nSeqLen )
            nCount = nSeqLen - nPos;

        rtl_copyMemory( pBuffer, maSeq.getConstArray() + nPos, nCount );
        *pRead = nCount;
    }
    else
        *pRead = 0UL;

    return nErr;
}

// ------------------------------------------------------------------------

ErrCode XMXLockBytes::WriteAt( sal_uInt32 nPos, const void* pBuffer, sal_uInt32 nCount, sal_uInt32* pWritten )
{
    return ERRCODE_IO_CANTWRITE;
}

// ------------------------------------------------------------------------

ErrCode XMXLockBytes::Flush() const
{
    return ERRCODE_NONE;
}

// ------------------------------------------------------------------------

ErrCode XMXLockBytes::SetSize( sal_uInt32 nSize )
{
    return ERRCODE_IO_CANTWRITE;
}

// ------------------------------------------------------------------------

ErrCode XMXLockBytes::Stat( SvLockBytesStat* pStat, SvLockBytesStatFlag eFlag ) const
{
    pStat->nSize = maSeq.getLength();
    return ERRCODE_NONE;
}

// ----------------
// - XMLExtractor -
// ----------------

XMLExtractor::XMLExtractor( const REF( NMSP_LANG::XMultiServiceFactory )& rxMgr ) :
    mxFact( rxMgr )
{
}

// -----------------------------------------------------------------------------

XMLExtractor::~XMLExtractor()
{
}

// -----------------------------------------------------------------------------

REF( NMSP_IO::XInputStream ) SAL_CALL XMLExtractor::extract( const REF( NMSP_IO::XInputStream )& rxIStm ) throw( NMSP_UNO::RuntimeException )
{
    REF( NMSP_IO::XInputStream ) xRet;

    if( rxIStm.is() )
    {
        SvStream        aIStm( new XMXLockBytes( rxIStm ) );
        SvStorageRef    aStorage( new SvStorage( aIStm ) );
        String          aStmName;
        const String    aFormat1( String::CreateFromAscii( "XMLFormat" ) );
        const String    aFormat2( String::CreateFromAscii( "XMLFormat2" ) );

        if( aStorage->IsContained( aFormat2 ) )
            aStmName = aFormat2;
        else if( aStorage->IsContained( aFormat1 ) )
            aStmName = aFormat1;

        if( !aStorage->GetError() && aStmName.Len() && aStorage->IsStream( aStmName ) )
        {
            SvStorageStreamRef xStream( aStorage->OpenSotStream( aStmName ) );

            if( xStream.Is() )
            {
                SvMemoryStream* pMemStm = new SvMemoryStream( 65535, 65535 );
                ZCodec          aCodec;

                aCodec.BeginCompression( ZCODEC_BEST_COMPRESSION );
                aCodec.Decompress( *xStream, *pMemStm );
                aCodec.EndCompression();

                xRet = new ::utl::OInputStreamHelper( new SvLockBytes( pMemStm, TRUE ), 65535 );
            }
        }
    }

    return xRet;
}
<|endoftext|>


<commit_before>#include "classui.h"
#include "listworker.h"
#include <iostream>
#include <string>
#include <algorithm>
#include <vector>
#include <time.h>

using namespace std;

ClassUI::ClassUI()
{

}

void ClassUI::run()
{
    bool runOn = true;
    int choice;

    cout << "\t" << "Welcome to the Amazing Database " << endl;
    cout << "-----------------------------------------------------------" << endl;
    cout << "\t" << "Quote of the day: " << endl;
    cout << getQuotes() << endl;
    do
    {

        cout << "-----------------------------------------------------------" << endl;
        cout << " (1) - Add" << "\t" << "Add a person to the database" << endl;
        cout << " (2) - Remove" << "\t" << "Remove a person from the database" << endl;
        cout << " (3) - View" << "\t" << "View the entire database" << endl;
        cout << " (4) - Save" << "\t" << "Save the database" << endl;
        cout << " (5) - Search" << "\t" << "Search the database" << endl;
        cout << " (6) - Sort" << "\t" << "Sort the database" << endl;
        cout << " (7) - Exit" << "\t" << "Exit" << endl;

        cout << "Enter your command: ";
        cin >> choice;
        if (choice != 7){
           select(choice);
        }
        else{
            list.saveFile();
            runOn = false;
        }
    }while(runOn == true);
}

void ClassUI::select(int ch)
{
    if(ch == 1){
        addPerson();
    }

    else if(ch == 3)
    {
        viewAll();
    }
    else if(ch == 6)
    {
        int sortcho;
        cout << "Enter your sort command" << endl;
        cout << "------------------------" << endl;
        cout << " (1) - Sort by alphabetical order" << endl;
        cout << " (2) - sort by chronological order" << endl;
        cin >> sortcho;

        if(sortcho == 1)
        {
            list.sortNames();
        }
        else if(sortcho == 2)
        {
            list.sortBirth();
        }
        viewAll();
    }
    else if(ch == 5){
        searching();
    }
    else if(ch == 2){
        remove();
    }
    else if(ch == 4){
        save();
    }
    else if(ch == 8)
    {
        yo();
    }
    else
    {
        cout << "Invalid input" << endl;
    }
}
void ClassUI::view(int i)
{
    int nameSize  = list.getNameSize(i);
    cout << endl;
    cout << "--------------------------------------------------------------" << endl;
    cout << "Name" << "\t" << "\t" << "\t" << "\t" << "|Gender " << "|Born " << "\t" << "|Death" << endl;
    cout << "--------------------------------|-------|-------|-------------" << endl;

    cout << list.getName(i);
    if(nameSize > 0 && nameSize <= 7)
    {
        cout << "\t" << "\t" << "\t" << "\t";
    }
    else if(nameSize > 7 && nameSize <= 15)
    {
        cout << "\t" << "\t" << "\t";
    }
    else if(nameSize > 15 && nameSize <= 23)
    {
        cout << "\t" << "\t";
    }
    else if(nameSize > 23 && nameSize <= 31)
    {
        cout << "\t";
    }

    if(list.getGender(i) == 'M' || list.getGender(i) == 'm')
    {
        cout << "|Male" << "\t";
    }
    else
    {
        cout << "|Female" << "\t";
    }
    cout  << "|" << list.getBirth(i);
    if(list.getDeath(i) == 0)
    {
        cout << "\t" << "| n/a"  << endl;
    }
    else
    {
        cout << "\t" << "|" << list.getDeath(i)  << endl;
    }
    cout << list.getComment(i) << endl;
    cout << "--------------------------------------------------------------" << endl;
    cout << endl;
}

void ClassUI::searching()
{

    cout << "----------Select any of the following commands----------" << endl;
    cout << "What do you want to search for? " << endl;
    cout << " (1) - Name -- Searches for a name" << endl;
    cout << " (2) - Gender -- Searches for a Gender" << endl;
    cout << " (3) - Year -- Searches for a year born" << endl;
    search();
}
void ClassUI::addPerson()
{
    string name;
    char gender;
    char yesOrNo;
    int yearOfBirth = 0;
    int yearOfDeath = 0;
    string comment;

    cout << "Input Name: ";
    cin.ignore();
    std::getline(std::cin,name);
    cout << "Input gender (M/F): ";
    cin >> gender;
    if (gender == 'm')
    {
        gender = 'M';
    }
    else if (gender == 'f')
    {
        gender = 'F';
    }
    if (gender == 'm' || gender == 'M' || gender == 'f' || gender == 'F')
    {
       cout << "Input year of birth: ";
       cin >> yearOfBirth;

       cout << "Is the individual deceased? (y/n)";
       cin >> yesOrNo;
       if (yesOrNo == 'Y' || yesOrNo == 'y')
       {
            cout << "Input year of death: ";
            cin >> yearOfDeath;
       }
        cout << "Input a comment about the individual: ";
        cin.ignore();
        std::getline(std::cin,comment);
    }
    else
    {
        cout << "Invalid gender! Try again." << endl;
        addPerson();
    }
    list.addNewPerson(name, gender, yearOfBirth, yearOfDeath, comment);

}

void ClassUI::search()
{
        int searchChoice;
        cin >> searchChoice;
        if (searchChoice == 1)
        {

            string namesearch;
            cout << "Enter a name you want to search for: ";
            cin.ignore();
            std::getline(std::cin,namesearch);

            for(int i = 0; i < list.getPersonsSize();++i)
            {
                std::size_t found = list.getName(i).find(namesearch);
                if (found!=std::string::npos)
                {
                    view(i);
                }

            }
            if(list.nameSearcher(namesearch) == false)
            {
                cout << "Sorry that name is not in our database, but you can add a new instance in the 'Add' section in the main menu" << endl;
            }
        }
        else if (searchChoice == 2)
        {
            char gendersearch;

            cout << "Enter a gender you want to search for: (M/F)";
            cin >> gendersearch;
            if(gendersearch == 'm')
                {
                     gendersearch = 'M';
                }
            else if (gendersearch == 'f')
                {
                     gendersearch = 'F';
                }

            for(int i = 0; i < list.getPersonsSize();++i)
            {
                if(gendersearch == list.getGender(i))
                {
                    gendersearch = list.getGender(i);
                    view(i);
                }
            }
            if(list.genderSearcher(gendersearch) == false)
            {
                cout << "Sorry that gender is not in our database, but you can add a new instance in the 'Add' section in the main menu" << endl;
            }
        }
        else if (searchChoice == 3)
        {
                int yearsearch;
                cout << "Enter a year you want to search for: ";
                cin >> yearsearch;

                for(int i = 0; i < list.getPersonsSize();++i)
                {
                    if(yearsearch == list.getBirth(i))
                    {
                        yearsearch = list.getBirth(i);
                        view(i);
                    }
                }
                if(list.yearSearcher(yearsearch) == false)
                {
                    cout << "Sorry that year is not in our database, but you can add a new instance in the 'Add' section in the main menu" << endl;
                }
        }
        else
        {
            cout << "Error reading input" << endl;
        }
}
void ClassUI::remove()
{
    string name;
    cout << "Enter a name of person that you want to remove: ";
    cin.ignore();
    std::getline(std::cin,name);
    if (list.removePerson(name) == true)
    {
        cout << "Person removed!" << endl;
    }
    else
    {
        cout << "Person not found!" << endl;
    }
}
void ClassUI::save()
{
    list.saveFile();
}
void ClassUI::viewAll()
{
    for(int i = 0; i < list.getPersonsSize(); i++)
    {
        view(i);
    }
}
void ClassUI::yo()
{
    cout << endl;
    cout << "`8.`8888.      ,8'     ,o888888o.     " << endl;
    cout << " `8.`8888.    ,8'   . 8888     `88.   " << endl;
    cout << "  `8.`8888.  ,8'   ,8 8888       `8b  " << endl;
    cout << "   `8.`8888.,8'    88 8888        `8b " << endl;
    cout << "    `8.`88888'     88 8888         88 " << endl;
    cout << "     `8. 8888      88 8888         88 " << endl;
    cout << "      `8 8888      88 8888        ,8P " << endl;
    cout << "       8 8888      `8 8888       ,8P  " << endl;
    cout << "       8 8888       ` 8888     ,88'   " << endl;
    cout << "       8 8888          `8888888P'     " << endl;
    cout << endl;
}

string ClassUI::getQuotes()
{
    string quotes[3] = {"\"A good programmer is someone who always looks both ways before crossing a one-way street.\" (Doug Linder)",
                        "\"Programming is like sex. One mistake and you have to support it for the rest of your life.\" (Michael Sinz)",
                        "\"Walking on water and developing software from a specification are easy if both are frozen.\" (Edward V Berard)"
                       };
    int v1 = 0;
    srand (time(NULL));
    v1 = rand() % 3;
    return quotes[v1];
}
<commit_msg>More quotes<commit_after>#include "classui.h"
#include "listworker.h"
#include <iostream>
#include <string>
#include <algorithm>
#include <vector>
#include <time.h>

using namespace std;

ClassUI::ClassUI()
{

}

void ClassUI::run()
{
    bool runOn = true;
    int choice;

    cout << "\t" << "Welcome to the Amazing Database " << endl;
    cout << "-----------------------------------------------------------" << endl;
    cout << "\t" << "Quote of the day: " << endl;
    cout << getQuotes() << endl;
    do
    {

        cout << "-----------------------------------------------------------" << endl;
        cout << " (1) - Add" << "\t" << "Add a person to the database" << endl;
        cout << " (2) - Remove" << "\t" << "Remove a person from the database" << endl;
        cout << " (3) - View" << "\t" << "View the entire database" << endl;
        cout << " (4) - Save" << "\t" << "Save the database" << endl;
        cout << " (5) - Search" << "\t" << "Search the database" << endl;
        cout << " (6) - Sort" << "\t" << "Sort the database" << endl;
        cout << " (7) - Exit" << "\t" << "Exit" << endl;

        cout << "Enter your command: ";
        cin >> choice;
        if (choice != 7){
           select(choice);
        }
        else{
            list.saveFile();
            runOn = false;
        }
    }while(runOn == true);
}

void ClassUI::select(int ch)
{
    if(ch == 1){
        addPerson();
    }

    else if(ch == 3)
    {
        viewAll();
    }
    else if(ch == 6)
    {
        int sortcho;
        cout << "Enter your sort command" << endl;
        cout << "------------------------" << endl;
        cout << " (1) - Sort by alphabetical order" << endl;
        cout << " (2) - sort by chronological order" << endl;
        cin >> sortcho;

        if(sortcho == 1)
        {
            list.sortNames();
        }
        else if(sortcho == 2)
        {
            list.sortBirth();
        }
        viewAll();
    }
    else if(ch == 5){
        searching();
    }
    else if(ch == 2){
        remove();
    }
    else if(ch == 4){
        save();
    }
    else if(ch == 8)
    {
        yo();
    }
    else
    {
        cout << "Invalid input" << endl;
    }
}
void ClassUI::view(int i)
{
    int nameSize  = list.getNameSize(i);
    cout << endl;
    cout << "--------------------------------------------------------------" << endl;
    cout << "Name" << "\t" << "\t" << "\t" << "\t" << "|Gender " << "|Born " << "\t" << "|Death" << endl;
    cout << "--------------------------------|-------|-------|-------------" << endl;

    cout << list.getName(i);
    if(nameSize > 0 && nameSize <= 7)
    {
        cout << "\t" << "\t" << "\t" << "\t";
    }
    else if(nameSize > 7 && nameSize <= 15)
    {
        cout << "\t" << "\t" << "\t";
    }
    else if(nameSize > 15 && nameSize <= 23)
    {
        cout << "\t" << "\t";
    }
    else if(nameSize > 23 && nameSize <= 31)
    {
        cout << "\t";
    }

    if(list.getGender(i) == 'M' || list.getGender(i) == 'm')
    {
        cout << "|Male" << "\t";
    }
    else
    {
        cout << "|Female" << "\t";
    }
    cout  << "|" << list.getBirth(i);
    if(list.getDeath(i) == 0)
    {
        cout << "\t" << "| n/a"  << endl;
    }
    else
    {
        cout << "\t" << "|" << list.getDeath(i)  << endl;
    }
    cout << list.getComment(i) << endl;
    cout << "--------------------------------------------------------------" << endl;
    cout << endl;
}

void ClassUI::searching()
{

    cout << "----------Select any of the following commands----------" << endl;
    cout << "What do you want to search for? " << endl;
    cout << " (1) - Name -- Searches for a name" << endl;
    cout << " (2) - Gender -- Searches for a Gender" << endl;
    cout << " (3) - Year -- Searches for a year born" << endl;
    search();
}
void ClassUI::addPerson()
{
    string name;
    char gender;
    char yesOrNo;
    int yearOfBirth = 0;
    int yearOfDeath = 0;
    string comment;

    cout << "Input Name: ";
    cin.ignore();
    std::getline(std::cin,name);
    cout << "Input gender (M/F): ";
    cin >> gender;
    if (gender == 'm')
    {
        gender = 'M';
    }
    else if (gender == 'f')
    {
        gender = 'F';
    }
    if (gender == 'm' || gender == 'M' || gender == 'f' || gender == 'F')
    {
       cout << "Input year of birth: ";
       cin >> yearOfBirth;

       cout << "Is the individual deceased? (y/n)";
       cin >> yesOrNo;
       if (yesOrNo == 'Y' || yesOrNo == 'y')
       {
            cout << "Input year of death: ";
            cin >> yearOfDeath;
       }
        cout << "Input a comment about the individual: ";
        cin.ignore();
        std::getline(std::cin,comment);
    }
    else
    {
        cout << "Invalid gender! Try again." << endl;
        addPerson();
    }
    list.addNewPerson(name, gender, yearOfBirth, yearOfDeath, comment);

}

void ClassUI::search()
{
        int searchChoice;
        cin >> searchChoice;
        if (searchChoice == 1)
        {

            string namesearch;
            cout << "Enter a name you want to search for: ";
            cin.ignore();
            std::getline(std::cin,namesearch);

            for(int i = 0; i < list.getPersonsSize();++i)
            {
                std::size_t found = list.getName(i).find(namesearch);
                if (found!=std::string::npos)
                {
                    view(i);
                }

            }
            if(list.nameSearcher(namesearch) == false)
            {
                cout << "Sorry that name is not in our database, but you can add a new instance in the 'Add' section in the main menu" << endl;
            }
        }
        else if (searchChoice == 2)
        {
            char gendersearch;

            cout << "Enter a gender you want to search for: (M/F)";
            cin >> gendersearch;
            if(gendersearch == 'm')
                {
                     gendersearch = 'M';
                }
            else if (gendersearch == 'f')
                {
                     gendersearch = 'F';
                }

            for(int i = 0; i < list.getPersonsSize();++i)
            {
                if(gendersearch == list.getGender(i))
                {
                    gendersearch = list.getGender(i);
                    view(i);
                }
            }
            if(list.genderSearcher(gendersearch) == false)
            {
                cout << "Sorry that gender is not in our database, but you can add a new instance in the 'Add' section in the main menu" << endl;
            }
        }
        else if (searchChoice == 3)
        {
                int yearsearch;
                cout << "Enter a year you want to search for: ";
                cin >> yearsearch;

                for(int i = 0; i < list.getPersonsSize();++i)
                {
                    if(yearsearch == list.getBirth(i))
                    {
                        yearsearch = list.getBirth(i);
                        view(i);
                    }
                }
                if(list.yearSearcher(yearsearch) == false)
                {
                    cout << "Sorry that year is not in our database, but you can add a new instance in the 'Add' section in the main menu" << endl;
                }
        }
        else
        {
            cout << "Error reading input" << endl;
        }
}
void ClassUI::remove()
{
    string name;
    cout << "Enter a name of person that you want to remove: ";
    cin.ignore();
    std::getline(std::cin,name);
    if (list.removePerson(name) == true)
    {
        cout << "Person removed!" << endl;
    }
    else
    {
        cout << "Person not found!" << endl;
    }
}
void ClassUI::save()
{
    list.saveFile();
}
void ClassUI::viewAll()
{
    for(int i = 0; i < list.getPersonsSize(); i++)
    {
        view(i);
    }
}
void ClassUI::yo()
{
    cout << endl;
    cout << "`8.`8888.      ,8'     ,o888888o.     " << endl;
    cout << " `8.`8888.    ,8'   . 8888     `88.   " << endl;
    cout << "  `8.`8888.  ,8'   ,8 8888       `8b  " << endl;
    cout << "   `8.`8888.,8'    88 8888        `8b " << endl;
    cout << "    `8.`88888'     88 8888         88 " << endl;
    cout << "     `8. 8888      88 8888         88 " << endl;
    cout << "      `8 8888      88 8888        ,8P " << endl;
    cout << "       8 8888      `8 8888       ,8P  " << endl;
    cout << "       8 8888       ` 8888     ,88'   " << endl;
    cout << "       8 8888          `8888888P'     " << endl;
    cout << endl;
}

string ClassUI::getQuotes()
{
    string quotes[5] = {"\"A good programmer is someone who always looks both ways before crossing a one-way street.\" (Doug Linder)",
                        "\"Programming is like sex. One mistake and you have to support it for the rest of your life.\" (Michael Sinz)",
                        "\"Walking on water and developing software from a specification are easy if both are frozen.\" (Edward V Berard)",
                        "\"One man's crappy software is another man's full time job.\" (Jessica Gaston)",
                        "\"A C program is like a fast dance on a newly waxed dance floor by people carrying razors.\" (Waldi Ravens)"
                       };
    int v1 = 0;
    srand (time(NULL));
    v1 = rand() % 5;
    return quotes[v1];
}
<|endoftext|>


<commit_before>// $Id: PoissonBoltzmann_test.C,v 1.3 2000/05/04 13:37:07 oliver Exp $
#include <BALL/CONCEPT/classTest.h>

#include <BALL/SOLVATION/poissonBoltzmann.h>

#undef PRECISION
#define PRECISION 0.005

START_TEST(FDPB, "$Id: PoissonBoltzmann_test.C,v 1.3 2000/05/04 13:37:07 oliver Exp $")

/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////

using namespace BALL;

System*		system = new System;
Atom*			atom = new Atom;
Molecule*	molecule = new Molecule;
molecule->insert(*atom);
system->insert(*molecule);
atom->setRadius( 2.0);
atom->setCharge(+1.0);

FDPB*		fdpb;

CHECK(default constructor)
	fdpb = new FDPB;
	TEST_NOT_EQUAL(fdpb, 0)
RESULT

CHECK(destructor)
	delete fdpb;
RESULT

CHECK(constructor/1)
	fdpb = new FDPB(*system);
	TEST_NOT_EQUAL(fdpb, 0)
RESULT

Options options;
CHECK(constructor/2)
	options = fdpb->options;
	delete fdpb;
	fdpb = new FDPB(options);
	TEST_NOT_EQUAL(fdpb, 0)
RESULT

CHECK(constructor/3)
	delete fdpb;
	options.destroy();
	options.setReal(FDPB::Option::SOLVENT_DC, 78.0);
	options.setReal(FDPB::Option::SOLUTE_DC, 1.0);
	options.setReal(FDPB::Option::SPACING, 0.4);
	options.setReal(FDPB::Option::BORDER, 10.0);
	options.set(FDPB::Option::CHARGE_DISTRIBUTION, FDPB::ChargeDistribution::UNIFORM);
	options.set(FDPB::Option::DIELECTRIC_SMOOTHING, FDPB::DielectricSmoothing::NONE);
	options[FDPB::Option::IONIC_STRENGTH] = 0.0;
	options[FDPB::Option::VERBOSITY] = 0;
	fdpb = new FDPB(*system, options);
	TEST_NOT_EQUAL(fdpb, 0)
RESULT

CHECK(solve)
	fdpb->solve();
	TEST_EQUAL(fdpb->results["converged"], "true")
RESULT

CHECK(energy - reaction field energy - and numerical accuracy)
	float E_water = fdpb->getEnergy();
	float E_RF_water = fdpb->getReactionFieldEnergy();

	fdpb->options.setReal(FDPB::Option::SOLVENT_DC, 1.0);
	fdpb->setup(*system);
	fdpb->solve();
	float E_vacuum = fdpb->getEnergy();
	float E_RF_vacuum = fdpb->getReactionFieldEnergy();

	TEST_REAL_EQUAL(E_water - E_vacuum, -357.68)
	TEST_REAL_EQUAL(E_RF_water, -342.897)
	TEST_REAL_EQUAL(E_RF_vacuum, 0.0)
	delete fdpb;
RESULT

/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////

END_TEST
<commit_msg>fixed: fixed PRECISION for solvation energy difference<commit_after>// $Id: PoissonBoltzmann_test.C,v 1.4 2000/05/04 19:57:47 oliver Exp $
#include <BALL/CONCEPT/classTest.h>

#include <BALL/SOLVATION/poissonBoltzmann.h>

#undef PRECISION
#define PRECISION 0.005

START_TEST(FDPB, "$Id: PoissonBoltzmann_test.C,v 1.4 2000/05/04 19:57:47 oliver Exp $")

/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////

using namespace BALL;

System*		system = new System;
Atom*			atom = new Atom;
Molecule*	molecule = new Molecule;
molecule->insert(*atom);
system->insert(*molecule);
atom->setRadius( 2.0);
atom->setCharge(+1.0);

FDPB*		fdpb;

CHECK(default constructor)
	fdpb = new FDPB;
	TEST_NOT_EQUAL(fdpb, 0)
RESULT

CHECK(destructor)
	delete fdpb;
RESULT

CHECK(constructor/1)
	fdpb = new FDPB(*system);
	TEST_NOT_EQUAL(fdpb, 0)
RESULT

Options options;
CHECK(constructor/2)
	options = fdpb->options;
	delete fdpb;
	fdpb = new FDPB(options);
	TEST_NOT_EQUAL(fdpb, 0)
RESULT

CHECK(constructor/3)
	delete fdpb;
	options.destroy();
	options.setReal(FDPB::Option::SOLVENT_DC, 78.0);
	options.setReal(FDPB::Option::SOLUTE_DC, 1.0);
	options.setReal(FDPB::Option::SPACING, 0.4);
	options.setReal(FDPB::Option::BORDER, 10.0);
	options.set(FDPB::Option::CHARGE_DISTRIBUTION, FDPB::ChargeDistribution::UNIFORM);
	options.set(FDPB::Option::DIELECTRIC_SMOOTHING, FDPB::DielectricSmoothing::NONE);
	options[FDPB::Option::IONIC_STRENGTH] = 0.0;
	options[FDPB::Option::VERBOSITY] = 0;
	fdpb = new FDPB(*system, options);
	TEST_NOT_EQUAL(fdpb, 0)
RESULT

CHECK(solve)
	fdpb->solve();
	TEST_EQUAL(fdpb->results["converged"], "true")
RESULT

CHECK(energy - reaction field energy - and numerical accuracy)
	float E_water = fdpb->getEnergy();
	float E_RF_water = fdpb->getReactionFieldEnergy();

	fdpb->options.setReal(FDPB::Option::SOLVENT_DC, 1.0);
	fdpb->setup(*system);
	fdpb->solve();
	float E_vacuum = fdpb->getEnergy();
	float E_RF_vacuum = fdpb->getReactionFieldEnergy();

#undef PRECISION
#define PRECISION 0.5
	TEST_REAL_EQUAL(E_water - E_vacuum, -357.68)
#undef PRECISION
#define PRECISION 0.005
	TEST_REAL_EQUAL(E_RF_water, -342.897)
	TEST_REAL_EQUAL(E_RF_vacuum, 0.0)
	delete fdpb;
RESULT

/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////

END_TEST
<|endoftext|>


<commit_before>#include "App.h"
using namespace std;

void *App::operator new (size_t n, Pool *pool) {
    return pool -> palloc(n);
}

string App::get_expression(string wrapEntity) {
    string result;

    // when leftFuntion is abstraction, application should be wrapped in brackets
    // but if it's the most outter function, it shouldn't
    // example: a ((\x.x) b) c
    if (wrapEntity != "none" && leftFunction->_entName == "Abs")
        result += '(';

    result += leftFunction -> get_expression(_entName) + ' ' +
        rightFunction -> get_expression(_entName);

    if (wrapEntity != "none" && leftFunction->_entName == "Abs")
        result += ')';

    return result;
}

vector<string> App::get_tree_view(int shift) {
    // newShift will point here:
    // App/--
    //        ^
    int newShift = shift + _entName.size() + _horizontalFirst.size() + 1;

    // process left function of abstraction
    vector<string> treeBegin = leftFunction->get_tree_view(newShift);

    //  add "/-- " to already processed left function
    //      "|   "
    //      ......
    //      "|   "
    treeBegin[0].replace(shift, _entName.size() + _horizontalFirst.size() + 1, _entName + _horizontalFirst + ' ');
    for (int i = 1; i < treeBegin.size(); i++)
        treeBegin[i].replace(shift + _entName.size(), _vertical.size(), _vertical);
    treeBegin.push_back(string(shift + _entName.size(), ' ') + _vertical);

    // process right function of abstraction
    vector<string> treeEnd = rightFunction->get_tree_view(newShift);

    // add "\__ " to already processed right function
    treeEnd[0].replace(shift + _entName.size(), _horizontalSecond.size(), _horizontalSecond);

    //merge parts of result
    treeBegin.insert(treeBegin.end(), treeEnd.begin(), treeEnd.end());

    return treeBegin;
}

Node *App::reduce(Pool *pool) {
    // if leftFunction is abstraction,
    // this abstraction will be the entry point of reduction
    if (leftFunction->_entName == "Abs") {
        return leftFunction->substitute(pool, rightFunction);
    } else {
        // this if used to ensure that it will be only one reduction at a time
        if (rightFunction->is_redex())
            return new(pool) App(leftFunction->copy(pool), rightFunction->reduce(pool));
        else
            return new(pool) App(leftFunction->reduce(pool), rightFunction->copy(pool));
    }
}

Node *App::substitute(Pool *pool, Node *substituteTo, Var *substituteThis) {
    // (\x.x) y
    //     ^  ^
    //     |  \_substituteTo
    //     |
    // substituteThis

    return new(pool) App(leftFunction -> substitute(pool, substituteTo, substituteThis),
                        rightFunction -> substitute(pool, substituteTo, substituteThis));
}

bool App::is_redex() {
    if (leftFunction->_entName == "Abs")
        return true;
    else
        return leftFunction->is_redex() || rightFunction->is_redex();
}

App *App::copy (Pool *pool) {
    return new(pool) App(leftFunction -> copy(pool), rightFunction -> copy(pool));
}
<commit_msg>Small change to provide normal-order lambda evaluation<commit_after>#include "App.h"
using namespace std;

void *App::operator new (size_t n, Pool *pool) {
    return pool -> palloc(n);
}

string App::get_expression(string wrapEntity) {
    string result;

    // when leftFuntion is abstraction, application should be wrapped in brackets
    // but if it's the most outter function, it shouldn't
    // example: a ((\x.x) b) c
    if (wrapEntity != "none" && leftFunction->_entName == "Abs")
        result += '(';

    result += leftFunction -> get_expression(_entName) + ' ' +
        rightFunction -> get_expression(_entName);

    if (wrapEntity != "none" && leftFunction->_entName == "Abs")
        result += ')';

    return result;
}

vector<string> App::get_tree_view(int shift) {
    // newShift will point here:
    // App/--
    //        ^
    int newShift = shift + _entName.size() + _horizontalFirst.size() + 1;

    // process left function of abstraction
    vector<string> treeBegin = leftFunction->get_tree_view(newShift);

    //  add "/-- " to already processed left function
    //      "|   "
    //      ......
    //      "|   "
    treeBegin[0].replace(shift, _entName.size() + _horizontalFirst.size() + 1, _entName + _horizontalFirst + ' ');
    for (int i = 1; i < treeBegin.size(); i++)
        treeBegin[i].replace(shift + _entName.size(), _vertical.size(), _vertical);
    treeBegin.push_back(string(shift + _entName.size(), ' ') + _vertical);

    // process right function of abstraction
    vector<string> treeEnd = rightFunction->get_tree_view(newShift);

    // add "\__ " to already processed right function
    treeEnd[0].replace(shift + _entName.size(), _horizontalSecond.size(), _horizontalSecond);

    //merge parts of result
    treeBegin.insert(treeBegin.end(), treeEnd.begin(), treeEnd.end());

    return treeBegin;
}

Node *App::reduce(Pool *pool) {
    // if leftFunction is abstraction,
    // this abstraction will be the entry point of reduction
    if (leftFunction->_entName == "Abs") {
        return leftFunction->substitute(pool, rightFunction);
    } else {
        // this if used to ensure that it will be only one reduction at a time
        if (leftFunction->is_redex())
            return new(pool) App(leftFunction->reduce(pool), rightFunction->copy(pool));
        else
            return new(pool) App(leftFunction->copy(pool), rightFunction->reduce(pool));
    }
}

Node *App::substitute(Pool *pool, Node *substituteTo, Var *substituteThis) {
    // (\x.x) y
    //     ^  ^
    //     |  \_substituteTo
    //     |
    // substituteThis

    return new(pool) App(leftFunction -> substitute(pool, substituteTo, substituteThis),
                        rightFunction -> substitute(pool, substituteTo, substituteThis));
}

bool App::is_redex() {
    if (leftFunction->_entName == "Abs")
        return true;
    else
        return leftFunction->is_redex() || rightFunction->is_redex();
}

App *App::copy (Pool *pool) {
    return new(pool) App(leftFunction -> copy(pool), rightFunction -> copy(pool));
}
<|endoftext|>


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

#ifndef _CONNECTIVITY_CALC_COLUMNS_HXX_
#define _CONNECTIVITY_CALC_COLUMNS_HXX_

#ifndef _CONNECTIVITY_FILE_COLUMNS_HXX_
#include "file/FColumns.hxx"
#endif

namespace connectivity
{
    namespace calc
    {
        class OCalcColumns : public file::OColumns
        {
        protected:
            virtual sdbcx::ObjectType createObject(const ::rtl::OUString& _rName);
        public:
            OCalcColumns(file::OFileTable* _pTable,
                            ::osl::Mutex& _rMutex,
                            const TStringVector &_rVector
                         ) : file::OColumns(_pTable,_rMutex,_rVector)
            {}

        };
    }
}

#endif // _CONNECTIVITY_CALC_COLUMNS_HXX_

<commit_msg>INTEGRATION: CWS ooo19126 (1.4.74); FILE MERGED 2005/09/05 17:25:10 rt 1.4.74.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: CColumns.hxx,v $
 *
 *  $Revision: 1.5 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-08 06:58:49 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#ifndef _CONNECTIVITY_CALC_COLUMNS_HXX_
#define _CONNECTIVITY_CALC_COLUMNS_HXX_

#ifndef _CONNECTIVITY_FILE_COLUMNS_HXX_
#include "file/FColumns.hxx"
#endif

namespace connectivity
{
    namespace calc
    {
        class OCalcColumns : public file::OColumns
        {
        protected:
            virtual sdbcx::ObjectType createObject(const ::rtl::OUString& _rName);
        public:
            OCalcColumns(file::OFileTable* _pTable,
                            ::osl::Mutex& _rMutex,
                            const TStringVector &_rVector
                         ) : file::OColumns(_pTable,_rMutex,_rVector)
            {}

        };
    }
}

#endif // _CONNECTIVITY_CALC_COLUMNS_HXX_

<|endoftext|>


<commit_before>//
// Created by david on 2019-11-07.
//
#include <algorithms/class_algorithm_status.h>
#include <complex>
#include <config/nmspc_settings.h>
#include <general/nmspc_exceptions.h>
#include <general/nmspc_tensor_extra.h>
#include <h5pp/h5pp.h>
#include <io/table_types.h>
#include <tensors/class_tensors_finite.h>
#include <tensors/model/class_model_finite.h>
#include <tensors/model/class_mpo_site.h>
#include <tensors/state/class_mps_site.h>
#include <tensors/state/class_state_finite.h>
#include <tools/common/io.h>
#include <tools/common/log.h>
#include <tools/finite/debug.h>
#include <tools/finite/env.h>
#include <tools/finite/io.h>
#include <tools/finite/mps.h>
#include <tools/finite/print.h>
#include <typeindex>

using Scalar = std::complex<double>;

// Load model, state and simulation status from HDF5
void tools::finite::io::h5resume::load_simulation(const h5pp::File &h5ppFile, const std::string &state_prefix, class_tensors_finite &tensors,
                                                  class_algorithm_status &status) {
    try {
        tensors.clear_measurements();
        tensors.clear_cache();
        if(h5ppFile.readAttribute<std::string>(state_prefix, "common/storage_level") != enum2str(StorageLevel::FULL))
            throw std::runtime_error("Given prefix to simulation data with StorageLevel < FULL. The simulation can only be resumed from FULL storage");
        tools::common::io::h5table::load_sim_status(h5ppFile, state_prefix, status);
        tools::common::io::h5table::load_profiling(h5ppFile, state_prefix);
        tools::finite::io::h5resume::load_model(h5ppFile, state_prefix, *tensors.model);
        tools::finite::io::h5resume::load_state(h5ppFile, state_prefix, *tensors.state, status);
        tools::finite::io::h5resume::validate(h5ppFile, state_prefix, tensors);
    } catch(const std::exception &ex) { throw except::load_error("Failed to load simulation from hdf5 file: " + std::string(ex.what())); }
}

void tools::finite::io::h5resume::load_model(const h5pp::File &h5ppFile, const std::string &state_prefix, class_model_finite &model) {
    if(h5ppFile.readAttribute<std::string>(state_prefix, "common/storage_level") != enum2str(StorageLevel::FULL))
        throw std::runtime_error("Given prefix to model data with StorageLevel < FULL. The model can only be resumed from FULL storage");

    // Find the path to the MPO
    auto model_prefix = h5ppFile.readAttribute<std::string>(state_prefix, "common/model_prefix");
    if(h5ppFile.linkExists(model_prefix)) {
        auto table_path = fmt::format("{}/hamiltonian", model_prefix);
        if(not h5ppFile.linkExists(table_path)) throw std::runtime_error(fmt::format("Hamiltonian table does not exist: [{}]",table_path));
        tools::log->info("Loading model data from hamiltonian table: [{}]", table_path);
        auto model_type = h5ppFile.readAttribute<std::string>("model_type", table_path);
        auto model_size = h5ppFile.readAttribute<size_t>("model_size", table_path);
        if(str2enum<ModelType>(model_type) != settings::model::model_type)
            throw std::runtime_error(fmt::format("Mismatch when loading model: model_type [{}] != settings::model::model_type [{}]", model_type,
                                                 enum2str(settings::model::model_type)));
        if(model_size != settings::model::model_size)
            throw std::runtime_error(
                fmt::format("Mismatch when loading model: model_size [{}] != settings::model::model_size [{}]", model_size, settings::model::model_size));
        for(const auto & mpo : model.MPO)
            mpo->load_hamiltonian(h5ppFile, model_prefix);
    } else {
        throw std::runtime_error(fmt::format("Could not find model data in [{}]", model_prefix));
    }
}

void tools::finite::io::h5resume::load_state(const h5pp::File &h5ppFile, const std::string &state_prefix, class_state_finite &state,
                                             const class_algorithm_status &status) {
    if(h5ppFile.readAttribute<std::string>(state_prefix, "common/storage_level") != enum2str(StorageLevel::FULL))
        throw std::runtime_error("Given prefix to MPS data with StorageLevel < FULL. The MPS's can only be resumed from FULL storage");
    auto mps_prefix = h5ppFile.readAttribute<std::string>(state_prefix, "common/mps_prefix");
    auto model_type = h5ppFile.readAttribute<std::string>(state_prefix, "common/model_type");
    auto model_size = h5ppFile.readAttribute<size_t>(state_prefix, "common/model_size");
    auto position   = h5ppFile.readAttribute<long>(state_prefix, "common/position");
    if(position != status.position)
        throw std::runtime_error(fmt::format("Mismatch when loading MPS: position [{}] != status.position [{}]", position, status.position));
    if(str2enum<ModelType>(model_type) != settings::model::model_type)
        throw std::runtime_error(
            fmt::format("Mismatch when loading MPS: model_type [{}] != settings::model::model_type [{}]", model_type, enum2str(settings::model::model_type)));
    if(model_size != settings::model::model_size)
        throw std::runtime_error(
            fmt::format("Mismatch when loading MPS: model_size [{}] != settings::model::model_size [{}]", model_size, settings::model::model_size));
    state.initialize(str2enum<ModelType>(model_type), model_size, static_cast<size_t>(position));
    tools::log->debug("Loading state data from MPS in [{}]", mps_prefix);
    for(const auto & mps : state.mps_sites) {
        auto pos = mps->get_position<long>();
        std::string pos_str     = std::to_string(pos);
        std::string dset_L_name = fmt::format("{}/{}_{}", mps_prefix, "L", pos);
        std::string dset_M_name = fmt::format("{}/{}_{}", mps_prefix, "M", pos);
        if(mps->isCenter()) {
            std::string dset_LC_name = fmt::format("{}/{}", mps_prefix, "L_C");
            if(not h5ppFile.linkExists(dset_LC_name)) throw std::runtime_error(fmt::format("Dataset does not exist: {}", dset_LC_name));
            auto LC          = h5ppFile.readDataset<Eigen::Tensor<Scalar, 1>>(dset_LC_name);
            auto pos_on_file = h5ppFile.readAttribute<size_t>("position", dset_LC_name);
            if(pos != pos_on_file) throw std::runtime_error(fmt::format("Center bond position mismatch: pos [{}] != pos on file [{}]", pos, pos_on_file));
            mps->set_LC(LC);
        }
        if(not h5ppFile.linkExists(dset_L_name)) throw std::runtime_error(fmt::format("Dataset does not exist: {} ", dset_L_name));
        if(not h5ppFile.linkExists(dset_M_name)) throw std::runtime_error(fmt::format("Dataset does not exist: {} ", dset_M_name));
        auto L = h5ppFile.readDataset<Eigen::Tensor<Scalar, 1>>(dset_L_name);
        auto M = h5ppFile.readDataset<Eigen::Tensor<Scalar, 3>>(dset_M_name);
        auto error = h5ppFile.readAttribute<double>("truncation_error", dset_L_name);
        auto label = h5ppFile.readAttribute<std::string>("label", dset_M_name);
        mps->set_mps(M, L, error, label);
        // Sanity checks
        if(static_cast<long>(pos) == position and not mps->isCenter())
            throw std::logic_error("Given position is not a a center. State may be wrongly initialized or something is wrong with the resumed file");
        if(static_cast<long>(pos) != position and mps->isCenter()) throw std::logic_error("A site not at current position claims to be a state center");
        //        if(passed_LC > 1) throw std::logic_error("Multiple centers encountered");
    }
}

void compare(double val1, double val2, double tol, const std::string &tag) {
    if(val2 == 0){
        tools::log->warn("Value mismatch after resume: {} = {:.16f} | expected {:.16f} | diff = {:.16f} | tol = {:.16f}", tag, val1, val2,
                                std::abs(val1 - val2), tol);
        tools::log->warn("Value 2 is zero: It may not have been initialized in the previous simulation");
        return;
    }
    if(std::abs(val1 - val2) > tol)
        throw std::runtime_error(fmt::format("Value mismatch after resume: {} = {:.16f} | expected {:.16f} | diff = {:.16f} | tol = {:.16f}", tag, val1, val2,
                                             std::abs(val1 - val2), tol));
    else
        tools::log->debug("{} matches measurement on file: {:.16f} == {:.16f} | diff = {:.16f} | tol = {:.16f}", tag, val1, val2, std::abs(val1 - val2), tol);
}

void tools::finite::io::h5resume::validate(const h5pp::File &h5ppFile, const std::string &state_prefix, class_tensors_finite &tensors) {
    tools::finite::debug::check_integrity(tensors);
//    tensors.activate_sites(settings::precision::max_size_full_diag, 1);
    tensors.activate_sites({0,1});
    tensors.reduce_mpo_energy();
    tools::log->debug("Validating resumed state [{}]", state_prefix);
    tools::log->debug("State labels:", tensors.state->get_labels());
    auto expected_measurements = h5ppFile.readTableRecords<h5pp_table_measurements_finite::table>(state_prefix + "/measurements");
    tensors.clear_measurements();
    tensors.do_all_measurements();
    compare(tensors.measurements.energy.value(), expected_measurements.energy, 1e-8, "Energy");
    compare(tensors.measurements.energy_variance.value(), expected_measurements.energy_variance, 1e-8, "Energy variance");

}
<commit_msg>Updated iterators<commit_after>//
// Created by david on 2019-11-07.
//
#include <algorithms/class_algorithm_status.h>
#include <complex>
#include <config/nmspc_settings.h>
#include <general/nmspc_exceptions.h>
#include <general/nmspc_tensor_extra.h>
#include <h5pp/h5pp.h>
#include <io/table_types.h>
#include <tensors/class_tensors_finite.h>
#include <tensors/model/class_model_finite.h>
#include <tensors/model/class_mpo_site.h>
#include <tensors/state/class_mps_site.h>
#include <tensors/state/class_state_finite.h>
#include <tools/common/io.h>
#include <tools/common/log.h>
#include <tools/finite/debug.h>
#include <tools/finite/env.h>
#include <tools/finite/io.h>
#include <tools/finite/mps.h>
#include <tools/finite/print.h>
#include <typeindex>

using Scalar = std::complex<double>;

// Load model, state and simulation status from HDF5
void tools::finite::io::h5resume::load_simulation(const h5pp::File &h5ppFile, const std::string &state_prefix, class_tensors_finite &tensors,
                                                  class_algorithm_status &status) {
    try {
        tensors.clear_measurements();
        tensors.clear_cache();
        if(h5ppFile.readAttribute<std::string>(state_prefix, "common/storage_level") != enum2str(StorageLevel::FULL))
            throw std::runtime_error("Given prefix to simulation data with StorageLevel < FULL. The simulation can only be resumed from FULL storage");
        tools::common::io::h5table::load_sim_status(h5ppFile, state_prefix, status);
        tools::common::io::h5table::load_profiling(h5ppFile, state_prefix);
        tools::finite::io::h5resume::load_model(h5ppFile, state_prefix, *tensors.model);
        tools::finite::io::h5resume::load_state(h5ppFile, state_prefix, *tensors.state, status);
        tools::finite::io::h5resume::validate(h5ppFile, state_prefix, tensors);
    } catch(const std::exception &ex) { throw except::load_error("Failed to load simulation from hdf5 file: " + std::string(ex.what())); }
}

void tools::finite::io::h5resume::load_model(const h5pp::File &h5ppFile, const std::string &state_prefix, class_model_finite &model) {
    if(h5ppFile.readAttribute<std::string>(state_prefix, "common/storage_level") != enum2str(StorageLevel::FULL))
        throw std::runtime_error("Given prefix to model data with StorageLevel < FULL. The model can only be resumed from FULL storage");

    // Find the path to the MPO
    auto model_prefix = h5ppFile.readAttribute<std::string>(state_prefix, "common/model_prefix");
    if(h5ppFile.linkExists(model_prefix)) {
        auto table_path = fmt::format("{}/hamiltonian", model_prefix);
        if(not h5ppFile.linkExists(table_path)) throw std::runtime_error(fmt::format("Hamiltonian table does not exist: [{}]",table_path));
        tools::log->info("Loading model data from hamiltonian table: [{}]", table_path);
        auto model_type = h5ppFile.readAttribute<std::string>("model_type", table_path);
        auto model_size = h5ppFile.readAttribute<size_t>("model_size", table_path);
        if(str2enum<ModelType>(model_type) != settings::model::model_type)
            throw std::runtime_error(fmt::format("Mismatch when loading model: model_type [{}] != settings::model::model_type [{}]", model_type,
                                                 enum2str(settings::model::model_type)));
        if(model_size != settings::model::model_size)
            throw std::runtime_error(
                fmt::format("Mismatch when loading model: model_size [{}] != settings::model::model_size [{}]", model_size, settings::model::model_size));
        for(const auto & mpo : model.MPO)
            mpo->load_hamiltonian(h5ppFile, model_prefix);
    } else {
        throw std::runtime_error(fmt::format("Could not find model data in [{}]", model_prefix));
    }
}

void tools::finite::io::h5resume::load_state(const h5pp::File &h5ppFile, const std::string &state_prefix, class_state_finite &state,
                                             const class_algorithm_status &status) {
    if(h5ppFile.readAttribute<std::string>(state_prefix, "common/storage_level") != enum2str(StorageLevel::FULL))
        throw std::runtime_error("Given prefix to MPS data with StorageLevel < FULL. The MPS's can only be resumed from FULL storage");
    auto mps_prefix = h5ppFile.readAttribute<std::string>(state_prefix, "common/mps_prefix");
    auto model_type = h5ppFile.readAttribute<std::string>(state_prefix, "common/model_type");
    auto model_size = h5ppFile.readAttribute<size_t>(state_prefix, "common/model_size");
    auto position   = h5ppFile.readAttribute<long>(state_prefix, "common/position");
    if(position != status.position)
        throw std::runtime_error(fmt::format("Mismatch when loading MPS: position [{}] != status.position [{}]", position, status.position));
    if(str2enum<ModelType>(model_type) != settings::model::model_type)
        throw std::runtime_error(
            fmt::format("Mismatch when loading MPS: model_type [{}] != settings::model::model_type [{}]", model_type, enum2str(settings::model::model_type)));
    if(model_size != settings::model::model_size)
        throw std::runtime_error(
            fmt::format("Mismatch when loading MPS: model_size [{}] != settings::model::model_size [{}]", model_size, settings::model::model_size));
    state.initialize(str2enum<ModelType>(model_type), model_size, position);
    tools::log->debug("Loading state data from MPS in [{}]", mps_prefix);
    for(const auto & mps : state.mps_sites) {
        auto pos = mps->get_position();
        std::string pos_str     = std::to_string(pos);
        std::string dset_L_name = fmt::format("{}/{}_{}", mps_prefix, "L", pos);
        std::string dset_M_name = fmt::format("{}/{}_{}", mps_prefix, "M", pos);
        if(mps->isCenter()) {
            std::string dset_LC_name = fmt::format("{}/{}", mps_prefix, "L_C");
            if(not h5ppFile.linkExists(dset_LC_name)) throw std::runtime_error(fmt::format("Dataset does not exist: {}", dset_LC_name));
            auto LC          = h5ppFile.readDataset<Eigen::Tensor<Scalar, 1>>(dset_LC_name);
            auto pos_on_file = h5ppFile.readAttribute<size_t>("position", dset_LC_name);
            if(pos != pos_on_file) throw std::runtime_error(fmt::format("Center bond position mismatch: pos [{}] != pos on file [{}]", pos, pos_on_file));
            state.get_mps_site(pos).set_LC(LC);
        }
        if(not h5ppFile.linkExists(dset_L_name)) throw std::runtime_error(fmt::format("Dataset does not exist: {} ", dset_L_name));
        if(not h5ppFile.linkExists(dset_M_name)) throw std::runtime_error(fmt::format("Dataset does not exist: {} ", dset_M_name));
        auto L = h5ppFile.readDataset<Eigen::Tensor<Scalar, 1>>(dset_L_name);
        auto M = h5ppFile.readDataset<Eigen::Tensor<Scalar, 3>>(dset_M_name);
        auto error = h5ppFile.readAttribute<double>("truncation_error", dset_L_name);
        auto label = h5ppFile.readAttribute<std::string>("label", dset_M_name);
        mps->set_mps(M, L, error, label);
        // Sanity checks
        if(static_cast<long>(pos) == position and not mps->isCenter())
            throw std::logic_error("Given position is not a a center. State may be wrongly initialized or something is wrong with the resumed file");
        if(static_cast<long>(pos) != position and mps->isCenter()) throw std::logic_error("A site not at current position claims to be a state center");
        //        if(passed_LC > 1) throw std::logic_error("Multiple centers encountered");
    }
}

void compare(double val1, double val2, double tol, const std::string &tag) {
    if(val2 == 0){
        tools::log->warn("Value mismatch after resume: {} = {:.16f} | expected {:.16f} | diff = {:.16f} | tol = {:.16f}", tag, val1, val2,
                                std::abs(val1 - val2), tol);
        tools::log->warn("Value 2 is zero: It may not have been initialized in the previous simulation");
        return;
    }
    if(std::abs(val1 - val2) > tol)
        throw std::runtime_error(fmt::format("Value mismatch after resume: {} = {:.16f} | expected {:.16f} | diff = {:.16f} | tol = {:.16f}", tag, val1, val2,
                                             std::abs(val1 - val2), tol));
    else
        tools::log->debug("{} matches measurement on file: {:.16f} == {:.16f} | diff = {:.16f} | tol = {:.16f}", tag, val1, val2, std::abs(val1 - val2), tol);
}

void tools::finite::io::h5resume::validate(const h5pp::File &h5ppFile, const std::string &state_prefix, class_tensors_finite &tensors) {
    tools::finite::debug::check_integrity(tensors);
//    tensors.activate_sites(settings::precision::max_size_full_diag, 1);
    tensors.activate_sites({0,1});
    tensors.reduce_mpo_energy();
    tools::log->debug("Validating resumed state [{}]", state_prefix);
    tools::log->debug("State labels:", tensors.state->get_labels());
    auto expected_measurements = h5ppFile.readTableRecords<h5pp_table_measurements_finite::table>(state_prefix + "/measurements");
    tensors.clear_measurements();
    tensors.do_all_measurements();
    compare(tensors.measurements.energy.value(), expected_measurements.energy, 1e-8, "Energy");
    compare(tensors.measurements.energy_variance.value(), expected_measurements.energy_variance, 1e-8, "Energy variance");

}
<|endoftext|>