<commit_before>#include <boo/boo.hpp>
#include "logvisor/logvisor.hpp"
#include "hecl/Console.hpp"
#include "hecl/CVarManager.hpp"
#include "athena/MemoryWriter.hpp"
#include "hecl/Runtime.hpp"
#include "hecl/Backend/Backend.hpp"
#include "hecl/HMDLMeta.hpp"
#include "hecl/Pipeline.hpp"
#include <cmath>
#include <thread>
#include <mutex>
#include <condition_variable>

using namespace std::literals;

struct HECLWindowCallback : boo::IWindowCallback
{
    bool m_sizeDirty = false;
    boo::SWindowRect m_latestSize;
    virtual ~HECLWindowCallback();
    void resized(const boo::SWindowRect& rect, bool /*sync*/)
    {
        m_sizeDirty = true;
        m_latestSize = rect;
    }

    bool m_destroyed = false;
    void destroyed()
    {
        m_destroyed = true;
    }

    void charKeyDown(unsigned long charCode, boo::EModifierKey mods, bool isRepeat)
    {
        hecl::Console::instance()->handleCharCode(charCode, mods, isRepeat);
    }
    void specialKeyDown(boo::ESpecialKey key, boo::EModifierKey mods, bool isRepeat)
    {
        hecl::Console::instance()->handleSpecialKeyDown(key, mods, isRepeat);
    }
    void specialKeyUp(boo::ESpecialKey key, boo::EModifierKey mods)
    {
        hecl::Console::instance()->hecl::Console::handleSpecialKeyUp(key, mods);
    }
};

HECLWindowCallback::~HECLWindowCallback()
{

}

struct HECLApplicationCallback : boo::IApplicationCallback
{
    HECLWindowCallback m_windowCb;
    hecl::Runtime::FileStoreManager m_fileStoreMgr;
    hecl::CVarManager m_cvarManager;
    hecl::Console m_console;
    std::shared_ptr<boo::IWindow> m_mainWindow;
    bool m_running = true;

    HECLApplicationCallback()
        : m_fileStoreMgr(_SYS_STR("heclTest")),
          m_cvarManager(m_fileStoreMgr),
          m_console(&m_cvarManager)
    {
        m_console.registerCommand("quit"sv, "Quits application"sv, "",
            std::bind(&HECLApplicationCallback::quit, this, std::placeholders::_1, std::placeholders::_2));
    }

    virtual ~HECLApplicationCallback();

    int appMain(boo::IApplication* app)
    {
        hecl::VerbosityLevel = 2;

        /* Setup boo window */
        m_mainWindow = app->newWindow(_SYS_STR("HECL Test"));
        m_mainWindow->setCallback(&m_windowCb);

        boo::ObjToken<boo::ITextureR> renderTex;
        boo::ObjToken<boo::IGraphicsBuffer> vubo;
        boo::ObjToken<boo::IShaderPipeline> pipeline, pipeline2;
        boo::ObjToken<boo::IShaderDataBinding> binding, binding2;

        struct VertexUBO
        {
            float modelview[4][4] = {};
            float modelviewInv[4][4] = {};
            float projection[4][4] = {};
            VertexUBO()
            {
                modelview[0][0] = 1.0;
                modelview[1][1] = 1.0;
                modelview[2][2] = 1.0;
                modelview[3][3] = 1.0;
                modelviewInv[0][0] = 1.0;
                modelviewInv[1][1] = 1.0;
                modelviewInv[2][2] = 1.0;
                modelviewInv[3][3] = 1.0;
                projection[0][0] = 1.0;
                projection[1][1] = 1.0;
                projection[2][2] = 1.0;
                projection[3][3] = 1.0;
            }
        } vuboData;

        /* Make ramp texture */
        using Pixel = uint8_t[4];
        static Pixel tex[256][256];
        for (int i=0 ; i<256 ; ++i)
            for (int j=0 ; j<256 ; ++j)
            {
                tex[i][j][0] = uint8_t(i);
                tex[i][j][1] = uint8_t(j);
                tex[i][j][2] = 0;
                tex[i][j][3] = 0xff;
            }

        boo::IGraphicsDataFactory* gfxF = m_mainWindow->getMainContextDataFactory();
        if (gfxF->platform() == boo::IGraphicsDataFactory::Platform::Vulkan)
            vuboData.modelview[1][1] = -1.f;

        /* Pipeline converter */
        std::unique_ptr<hecl::PipelineConverterBase> conv = hecl::NewPipelineConverter(gfxF);

        /* Compile HECL shader */
        static std::string testShader = "HECLOpaque(Texture(0, UV(0)))";
        //static std::string testShader = "HECLOpaque(vec3(1.0,1.0,1.0),1.0)";
        hecl::Backend::ShaderTag testShaderTag(testShader, 0, 1, 0, 0, boo::Primitive::TriStrips,
                                               hecl::Backend::ReflectionType::None, false, false, false);
        hecl::Frontend::Frontend FE;
        hecl::Frontend::IR ir = FE.compileSource(testShader, "booTest");
        hecl::HECLIR irObj(ir, testShaderTag, 0);

        gfxF->commitTransaction([&](boo::IGraphicsDataFactory::Context& ctx)
        {
            pipeline = conv->convert(ctx, irObj);
            pipeline2 = conv->convert(ctx, Shader_test{});

            boo::SWindowRect mainWindowRect = m_mainWindow->getWindowFrame();
            renderTex = ctx.newRenderTexture(size_t(mainWindowRect.size[0]), size_t(mainWindowRect.size[1]),
                                             boo::TextureClampMode::Repeat, 1, 0);

            /* Generate meta structure (usually statically serialized) */
            hecl::HMDLMeta testMeta;
            testMeta.topology = hecl::HMDLTopology::TriStrips;
            testMeta.vertStride = 32;
            testMeta.vertCount = 4;
            testMeta.indexCount = 4;
            testMeta.colorCount = 0;
            testMeta.uvCount = 1;
            testMeta.weightCount = 0;
            testMeta.bankCount = 0;

            /* Binary form of meta structure */
            atUint8 testMetaBuf[HECL_HMDL_META_SZ];
            athena::io::MemoryWriter testMetaWriter(testMetaBuf, HECL_HMDL_META_SZ);
            testMeta.write(testMetaWriter);

            /* Make Tri-strip VBO */
            struct Vert
            {
                float pos[3];
                float norm[3];
                float uv[2];
            };
            static const Vert quad[4] =
            {
                {{0.5,0.5},{},{1.0,1.0}},
                {{-0.5,0.5},{},{0.0,1.0}},
                {{0.5,-0.5},{},{1.0,0.0}},
                {{-0.5,-0.5},{},{0.0,0.0}}
            };

            /* Now simple IBO */
            static const uint32_t ibo[4] = {0,1,2,3};

            /* Construct quad mesh against boo factory */
            hecl::Runtime::HMDLData testData(ctx, testMetaBuf, quad, ibo);

            boo::ObjToken<boo::ITexture> texture =
            ctx.newStaticTexture(256, 256, 1, boo::TextureFormat::RGBA8, boo::TextureClampMode::Repeat, tex, 256*256*4).get();

            /* Make vertex uniform buffer */
            vubo = ctx.newDynamicBuffer(boo::BufferUse::Uniform, sizeof(VertexUBO), 1).get();

            /* Assemble data binding */
            binding = testData.newShaderDataBindng(ctx, pipeline, 1, &vubo, nullptr, 1, &texture);
            binding2 = testData.newShaderDataBindng(ctx, pipeline2, 1, &vubo, nullptr, 1, &texture);
            return true;
        } BooTrace);

        m_mainWindow->showWindow();
        m_windowCb.m_latestSize = m_mainWindow->getWindowFrame();
        boo::IGraphicsCommandQueue* gfxQ = m_mainWindow->getCommandQueue();

        size_t frameIdx = 0;
        while (m_running)
        {
            m_mainWindow->waitForRetrace();

            if (m_windowCb.m_destroyed)
            {
                m_running = false;
                break;
            }

            if (m_windowCb.m_sizeDirty)
            {
                gfxQ->resizeRenderTexture(renderTex,
                                          size_t(m_windowCb.m_latestSize.size[0]),
                                          size_t(m_windowCb.m_latestSize.size[1]));
                m_windowCb.m_sizeDirty = false;
            }

            m_console.proc();

            gfxQ->setRenderTarget(renderTex);
            boo::SWindowRect r = m_windowCb.m_latestSize;
            r.location[0] = 0;
            r.location[1] = 0;
            gfxQ->setViewport(r);
            gfxQ->setScissor(r);
            float rgba[] = {sinf(frameIdx / 60.0f), cosf(frameIdx / 60.0f), 0.0f, 1.0f};
            gfxQ->setClearColor(rgba);
            gfxQ->clearTarget();

            vuboData.modelview[3][0] = sinf(frameIdx / 60.0f) * 0.5f;
            vuboData.modelview[3][1] = cosf(frameIdx / 60.0f) * 0.5f;
            vubo.cast<boo::IGraphicsBufferD>()->load(&vuboData, sizeof(vuboData));

            gfxQ->setShaderDataBinding(binding2);
            gfxQ->drawIndexed(0, 4);
            gfxQ->resolveDisplay(renderTex);
            m_console.draw(gfxQ);
            gfxQ->execute();

            ++frameIdx;
        }

        m_cvarManager.serialize();
        gfxQ->stopRenderer();
        return 0;
    }
    void appQuitting(boo::IApplication* /*app*/)
    {
        m_running = false;
    }

    void quit(hecl::Console* /*con*/, const std::vector<std::string>& /*args*/)
    {
        m_running = false;
    }
};

void AthenaExcHandler(athena::error::Level level,
                      const char* file, const char* /*function*/,
                      int line, const char* fmt, ...)
{
    static logvisor::Module Log("heclTest::AthenaExcHandler");
    va_list ap;
    va_start(ap, fmt);
    Log.reportSource(logvisor::Level(level), file, uint32_t(line), fmt, ap);
    va_end(ap);
}

#if !WINDOWS_STORE
#if _WIN32
int wmain(int argc, const boo::SystemChar** argv)
#else
int main(int argc, const boo::SystemChar** argv)
#endif
{
    atSetExceptionHandler(AthenaExcHandler);
    logvisor::RegisterStandardExceptions();
    logvisor::RegisterConsoleLogger();
    HECLApplicationCallback appCb;
    int ret = boo::ApplicationRun(boo::IApplication::EPlatformType::Auto,
        appCb, _SYS_STR("heclTest"), _SYS_STR("HECL Test"), argc, argv);
    printf("IM DYING!!\n");
    return ret;
}
#else
using namespace Windows::ApplicationModel::Core;

[Platform::MTAThread]
int WINAPIV main(Platform::Array<Platform::String^>^ params)
{
    logvisor::RegisterStandardExceptions();
    logvisor::RegisterConsoleLogger();
    HECLApplicationCallback appCb;
    boo::ViewProvider^ viewProvider =
        ref new boo::ViewProvider(appCb, _SYS_STR("heclTest"), _SYS_STR("HECL Test"), _SYS_STR("heclTest"), params, false);
    CoreApplication::Run(viewProvider);
    return 0;
}
#endif

#if _WIN32 && !WINDOWS_STORE
int APIENTRY wWinMain(HINSTANCE hInstance, HINSTANCE, LPWSTR lpCmdLine, int)
{
    int argc = 0;
    const boo::SystemChar** argv;
    if (lpCmdLine[0])
        argv = (const wchar_t**)(CommandLineToArgvW(lpCmdLine, &argc));
    static boo::SystemChar selfPath[1024];
    GetModuleFileNameW(nullptr, selfPath, 1024);
    static const boo::SystemChar* booArgv[32] = {};
    booArgv[0] = selfPath;
    for (int i=0 ; i<argc ; ++i)
        booArgv[i+1] = argv[i];

    logvisor::CreateWin32Console();
    return wmain(argc + 1, booArgv);
}
#endif

HECLApplicationCallback::~HECLApplicationCallback()
{

}
<commit_msg>Fix heclTest build<commit_after>#include <boo/boo.hpp>
#include "logvisor/logvisor.hpp"
#include "hecl/Console.hpp"
#include "hecl/CVarManager.hpp"
#include "athena/MemoryWriter.hpp"
#include "hecl/Runtime.hpp"
#include "hecl/Backend/Backend.hpp"
#include "hecl/HMDLMeta.hpp"
#include "hecl/Pipeline.hpp"
#include <cmath>
#include <thread>
#include <mutex>
#include <condition_variable>

using namespace std::literals;

struct HECLWindowCallback : boo::IWindowCallback
{
    bool m_sizeDirty = false;
    boo::SWindowRect m_latestSize;
    virtual ~HECLWindowCallback();
    void resized(const boo::SWindowRect& rect, bool /*sync*/)
    {
        m_sizeDirty = true;
        m_latestSize = rect;
    }

    bool m_destroyed = false;
    void destroyed()
    {
        m_destroyed = true;
    }

    void charKeyDown(unsigned long charCode, boo::EModifierKey mods, bool isRepeat)
    {
        hecl::Console::instance()->handleCharCode(charCode, mods, isRepeat);
    }
    void specialKeyDown(boo::ESpecialKey key, boo::EModifierKey mods, bool isRepeat)
    {
        hecl::Console::instance()->handleSpecialKeyDown(key, mods, isRepeat);
    }
    void specialKeyUp(boo::ESpecialKey key, boo::EModifierKey mods)
    {
        hecl::Console::instance()->hecl::Console::handleSpecialKeyUp(key, mods);
    }
};

HECLWindowCallback::~HECLWindowCallback()
{

}

struct HECLApplicationCallback : boo::IApplicationCallback
{
    HECLWindowCallback m_windowCb;
    hecl::Runtime::FileStoreManager m_fileStoreMgr;
    hecl::CVarManager m_cvarManager;
    hecl::Console m_console;
    std::shared_ptr<boo::IWindow> m_mainWindow;
    bool m_running = true;

    HECLApplicationCallback()
        : m_fileStoreMgr(_SYS_STR("heclTest")),
          m_cvarManager(m_fileStoreMgr),
          m_console(&m_cvarManager)
    {
        m_console.registerCommand("quit"sv, "Quits application"sv, "",
            std::bind(&HECLApplicationCallback::quit, this, std::placeholders::_1, std::placeholders::_2));
    }

    virtual ~HECLApplicationCallback();

    int appMain(boo::IApplication* app)
    {
        hecl::VerbosityLevel = 2;

        /* Setup boo window */
        m_mainWindow = app->newWindow(_SYS_STR("HECL Test"));
        m_mainWindow->setCallback(&m_windowCb);

        boo::ObjToken<boo::ITextureR> renderTex;
        boo::ObjToken<boo::IGraphicsBuffer> vubo;
        boo::ObjToken<boo::IShaderPipeline> pipeline, pipeline2;
        boo::ObjToken<boo::IShaderDataBinding> binding, binding2;

        struct VertexUBO
        {
            float modelview[4][4] = {};
            float modelviewInv[4][4] = {};
            float projection[4][4] = {};
            VertexUBO()
            {
                modelview[0][0] = 1.0;
                modelview[1][1] = 1.0;
                modelview[2][2] = 1.0;
                modelview[3][3] = 1.0;
                modelviewInv[0][0] = 1.0;
                modelviewInv[1][1] = 1.0;
                modelviewInv[2][2] = 1.0;
                modelviewInv[3][3] = 1.0;
                projection[0][0] = 1.0;
                projection[1][1] = 1.0;
                projection[2][2] = 1.0;
                projection[3][3] = 1.0;
            }
        } vuboData;

        /* Make ramp texture */
        using Pixel = uint8_t[4];
        static Pixel tex[256][256];
        for (int i=0 ; i<256 ; ++i)
            for (int j=0 ; j<256 ; ++j)
            {
                tex[i][j][0] = uint8_t(i);
                tex[i][j][1] = uint8_t(j);
                tex[i][j][2] = 0;
                tex[i][j][3] = 0xff;
            }

        boo::IGraphicsDataFactory* gfxF = m_mainWindow->getMainContextDataFactory();
        if (gfxF->platform() == boo::IGraphicsDataFactory::Platform::Vulkan)
            vuboData.modelview[1][1] = -1.f;

        /* Pipeline converter */
        std::unique_ptr<hecl::PipelineConverterBase> conv = hecl::NewPipelineConverter(gfxF);

        /* Compile HECL shader */
        static std::string testShader = "HECLOpaque(Texture(0, UV(0)))";
        //static std::string testShader = "HECLOpaque(vec3(1.0,1.0,1.0),1.0)";
        hecl::Backend::ShaderTag testShaderTag(testShader, 0, 1, 0, 0, boo::Primitive::TriStrips,
                                               hecl::Backend::ReflectionType::None, false, false, false, false);
        hecl::Frontend::Frontend FE;
        hecl::Frontend::IR ir = FE.compileSource(testShader, "booTest");
        hecl::HECLIR irObj(ir, testShaderTag, 0);

        gfxF->commitTransaction([&](boo::IGraphicsDataFactory::Context& ctx)
        {
            pipeline = conv->convert(ctx, irObj);
            pipeline2 = conv->convert(ctx, Shader_test{});

            boo::SWindowRect mainWindowRect = m_mainWindow->getWindowFrame();
            renderTex = ctx.newRenderTexture(size_t(mainWindowRect.size[0]), size_t(mainWindowRect.size[1]),
                                             boo::TextureClampMode::Repeat, 1, 0);

            /* Generate meta structure (usually statically serialized) */
            hecl::HMDLMeta testMeta;
            testMeta.topology = hecl::HMDLTopology::TriStrips;
            testMeta.vertStride = 32;
            testMeta.vertCount = 4;
            testMeta.indexCount = 4;
            testMeta.colorCount = 0;
            testMeta.uvCount = 1;
            testMeta.weightCount = 0;
            testMeta.bankCount = 0;

            /* Binary form of meta structure */
            atUint8 testMetaBuf[HECL_HMDL_META_SZ];
            athena::io::MemoryWriter testMetaWriter(testMetaBuf, HECL_HMDL_META_SZ);
            testMeta.write(testMetaWriter);

            /* Make Tri-strip VBO */
            struct Vert
            {
                float pos[3];
                float norm[3];
                float uv[2];
            };
            static const Vert quad[4] =
            {
                {{0.5,0.5},{},{1.0,1.0}},
                {{-0.5,0.5},{},{0.0,1.0}},
                {{0.5,-0.5},{},{1.0,0.0}},
                {{-0.5,-0.5},{},{0.0,0.0}}
            };

            /* Now simple IBO */
            static const uint32_t ibo[4] = {0,1,2,3};

            /* Construct quad mesh against boo factory */
            hecl::Runtime::HMDLData testData(ctx, testMetaBuf, quad, ibo);

            boo::ObjToken<boo::ITexture> texture =
            ctx.newStaticTexture(256, 256, 1, boo::TextureFormat::RGBA8, boo::TextureClampMode::Repeat, tex, 256*256*4).get();

            /* Make vertex uniform buffer */
            vubo = ctx.newDynamicBuffer(boo::BufferUse::Uniform, sizeof(VertexUBO), 1).get();

            /* Assemble data binding */
            binding = testData.newShaderDataBindng(ctx, pipeline, 1, &vubo, nullptr, 1, &texture);
            binding2 = testData.newShaderDataBindng(ctx, pipeline2, 1, &vubo, nullptr, 1, &texture);
            return true;
        } BooTrace);

        m_mainWindow->showWindow();
        m_windowCb.m_latestSize = m_mainWindow->getWindowFrame();
        boo::IGraphicsCommandQueue* gfxQ = m_mainWindow->getCommandQueue();

        size_t frameIdx = 0;
        while (m_running)
        {
            m_mainWindow->waitForRetrace();

            if (m_windowCb.m_destroyed)
            {
                m_running = false;
                break;
            }

            if (m_windowCb.m_sizeDirty)
            {
                gfxQ->resizeRenderTexture(renderTex,
                                          size_t(m_windowCb.m_latestSize.size[0]),
                                          size_t(m_windowCb.m_latestSize.size[1]));
                m_windowCb.m_sizeDirty = false;
            }

            m_console.proc();

            gfxQ->setRenderTarget(renderTex);
            boo::SWindowRect r = m_windowCb.m_latestSize;
            r.location[0] = 0;
            r.location[1] = 0;
            gfxQ->setViewport(r);
            gfxQ->setScissor(r);
            float rgba[] = {sinf(frameIdx / 60.0f), cosf(frameIdx / 60.0f), 0.0f, 1.0f};
            gfxQ->setClearColor(rgba);
            gfxQ->clearTarget();

            vuboData.modelview[3][0] = sinf(frameIdx / 60.0f) * 0.5f;
            vuboData.modelview[3][1] = cosf(frameIdx / 60.0f) * 0.5f;
            vubo.cast<boo::IGraphicsBufferD>()->load(&vuboData, sizeof(vuboData));

            gfxQ->setShaderDataBinding(binding2);
            gfxQ->drawIndexed(0, 4);
            gfxQ->resolveDisplay(renderTex);
            m_console.draw(gfxQ);
            gfxQ->execute();

            ++frameIdx;
        }

        m_cvarManager.serialize();
        gfxQ->stopRenderer();
        return 0;
    }
    void appQuitting(boo::IApplication* /*app*/)
    {
        m_running = false;
    }

    void quit(hecl::Console* /*con*/, const std::vector<std::string>& /*args*/)
    {
        m_running = false;
    }
};

void AthenaExcHandler(athena::error::Level level,
                      const char* file, const char* /*function*/,
                      int line, const char* fmt, ...)
{
    static logvisor::Module Log("heclTest::AthenaExcHandler");
    va_list ap;
    va_start(ap, fmt);
    Log.reportSource(logvisor::Level(level), file, uint32_t(line), fmt, ap);
    va_end(ap);
}

#if !WINDOWS_STORE
#if _WIN32
int wmain(int argc, const boo::SystemChar** argv)
#else
int main(int argc, const boo::SystemChar** argv)
#endif
{
    atSetExceptionHandler(AthenaExcHandler);
    logvisor::RegisterStandardExceptions();
    logvisor::RegisterConsoleLogger();
    HECLApplicationCallback appCb;
    int ret = boo::ApplicationRun(boo::IApplication::EPlatformType::Auto,
        appCb, _SYS_STR("heclTest"), _SYS_STR("HECL Test"), argc, argv);
    printf("IM DYING!!\n");
    return ret;
}
#else
using namespace Windows::ApplicationModel::Core;

[Platform::MTAThread]
int WINAPIV main(Platform::Array<Platform::String^>^ params)
{
    logvisor::RegisterStandardExceptions();
    logvisor::RegisterConsoleLogger();
    HECLApplicationCallback appCb;
    boo::ViewProvider^ viewProvider =
        ref new boo::ViewProvider(appCb, _SYS_STR("heclTest"), _SYS_STR("HECL Test"), _SYS_STR("heclTest"), params, false);
    CoreApplication::Run(viewProvider);
    return 0;
}
#endif

#if _WIN32 && !WINDOWS_STORE
int APIENTRY wWinMain(HINSTANCE hInstance, HINSTANCE, LPWSTR lpCmdLine, int)
{
    int argc = 0;
    const boo::SystemChar** argv;
    if (lpCmdLine[0])
        argv = (const wchar_t**)(CommandLineToArgvW(lpCmdLine, &argc));
    static boo::SystemChar selfPath[1024];
    GetModuleFileNameW(nullptr, selfPath, 1024);
    static const boo::SystemChar* booArgv[32] = {};
    booArgv[0] = selfPath;
    for (int i=0 ; i<argc ; ++i)
        booArgv[i+1] = argv[i];

    logvisor::CreateWin32Console();
    return wmain(argc + 1, booArgv);
}
#endif

HECLApplicationCallback::~HECLApplicationCallback()
{

}
<|endoftext|>


<commit_before>/*
   Copyright (c) 2009-2014, Jack Poulson
   All rights reserved.

   This file is part of Elemental and is under the BSD 2-Clause License,
   which can be found in the LICENSE file in the root directory, or at
   http://opensource.org/licenses/BSD-2-Clause
*/
#include "El-lite.hpp"
#include "El/matrices/Ones.hpp"
#include "El-C.h"
using namespace El;

#define CATCH \
  catch( std::bad_alloc& e ) \
  { ReportException(e); return EL_ALLOC_ERROR; } \
  catch( ArgException& e ) \
  { ReportException(e); return EL_ARG_ERROR; } \
  catch( std::logic_error& e ) \
  { ReportException(e); return EL_LOGIC_ERROR; } \
  catch( std::runtime_error& e ) \
  { ReportException(e); return EL_RUNTIME_ERROR; } \
  catch( std::exception& e ) \
  { ReportException(e); return EL_ERROR; }

extern "C" {

ElError ElOnesMatrix_s( ElMatrix_s A, ElInt m, ElInt n )
{
    try { Ones( *Reinterpret(A), m, n ); }
    CATCH
    return EL_SUCCESS;
}

ElError ElOnesMatrix_d( ElMatrix_d A, ElInt m, ElInt n )
{
    try { Ones( *Reinterpret(A), m, n ); }
    CATCH
    return EL_SUCCESS;
}

ElError ElOnesMatrix_c( ElMatrix_c A, ElInt m, ElInt n )
{
    try { Ones( *Reinterpret(A), m, n ); }
    CATCH
    return EL_SUCCESS;
}

ElError ElOnesMatrix_z( ElMatrix_z A, ElInt m, ElInt n )
{
    try { Ones( *Reinterpret(A), m, n ); }
    CATCH
    return EL_SUCCESS;
}

ElError ElOnesDistMatrix_s( ElDistMatrix_s A, ElInt m, ElInt n )
{
    try { Ones( *Reinterpret(A), m, n ); }
    CATCH
    return EL_SUCCESS;
}

ElError ElOnesDistMatrix_d( ElDistMatrix_d A, ElInt m, ElInt n )
{
    try { Ones( *Reinterpret(A), m, n ); }
    CATCH
    return EL_SUCCESS;
}

ElError ElOnesDistMatrix_c( ElDistMatrix_c A, ElInt m, ElInt n )
{
    try { Ones( *Reinterpret(A), m, n ); }
    CATCH
    return EL_SUCCESS;
}

ElError ElOnesDistMatrix_z( ElDistMatrix_z A, ElInt m, ElInt n )
{
    try { Ones( *Reinterpret(A), m, n ); }
    CATCH
    return EL_SUCCESS;
}

} // extern "C"
<commit_msg>Avoiding yet another build error.<commit_after>/*
   Copyright (c) 2009-2014, Jack Poulson
   All rights reserved.

   This file is part of Elemental and is under the BSD 2-Clause License,
   which can be found in the LICENSE file in the root directory, or at
   http://opensource.org/licenses/BSD-2-Clause
*/
#include "El-lite.hpp"
#include "El-C.h"
using namespace El;

#define CATCH \
  catch( std::bad_alloc& e ) \
  { ReportException(e); return EL_ALLOC_ERROR; } \
  catch( ArgException& e ) \
  { ReportException(e); return EL_ARG_ERROR; } \
  catch( std::logic_error& e ) \
  { ReportException(e); return EL_LOGIC_ERROR; } \
  catch( std::runtime_error& e ) \
  { ReportException(e); return EL_RUNTIME_ERROR; } \
  catch( std::exception& e ) \
  { ReportException(e); return EL_ERROR; }

extern "C" {

ElError ElOnesMatrix_s( ElMatrix_s A, ElInt m, ElInt n )
{
    try { Ones( *Reinterpret(A), m, n ); }
    CATCH
    return EL_SUCCESS;
}

ElError ElOnesMatrix_d( ElMatrix_d A, ElInt m, ElInt n )
{
    try { Ones( *Reinterpret(A), m, n ); }
    CATCH
    return EL_SUCCESS;
}

ElError ElOnesMatrix_c( ElMatrix_c A, ElInt m, ElInt n )
{
    try { Ones( *Reinterpret(A), m, n ); }
    CATCH
    return EL_SUCCESS;
}

ElError ElOnesMatrix_z( ElMatrix_z A, ElInt m, ElInt n )
{
    try { Ones( *Reinterpret(A), m, n ); }
    CATCH
    return EL_SUCCESS;
}

ElError ElOnesDistMatrix_s( ElDistMatrix_s A, ElInt m, ElInt n )
{
    try { Ones( *Reinterpret(A), m, n ); }
    CATCH
    return EL_SUCCESS;
}

ElError ElOnesDistMatrix_d( ElDistMatrix_d A, ElInt m, ElInt n )
{
    try { Ones( *Reinterpret(A), m, n ); }
    CATCH
    return EL_SUCCESS;
}

ElError ElOnesDistMatrix_c( ElDistMatrix_c A, ElInt m, ElInt n )
{
    try { Ones( *Reinterpret(A), m, n ); }
    CATCH
    return EL_SUCCESS;
}

ElError ElOnesDistMatrix_z( ElDistMatrix_z A, ElInt m, ElInt n )
{
    try { Ones( *Reinterpret(A), m, n ); }
    CATCH
    return EL_SUCCESS;
}

} // extern "C"
<|endoftext|>


<commit_before>#include <maximus/scraper.hpp>

#include <iostream>
#include <deque>
#include <fstream>
#include <boost/locale.hpp>

#include <supermarx/util/stubborn.hpp>

#include <maximus/parsers/product_parser.hpp>
#include <maximus/parsers/category_parser.hpp>

namespace supermarx
{
	scraper::scraper(callback_t _callback, size_t _ratelimit, bool _cache, bool)
	: callback(_callback)
	, dl("supermarx maximus/1.0", _ratelimit, _cache ? boost::optional<std::string>("./cache") : boost::none)
	{}

	void scraper::scrape()
	{
		const std::string base_uri = "http://www.jumbo.com";

		category_parser cp([&](category_parser::category_uri_t const& _curi)
		{
			static const boost::regex match_category_uri("^(.+)/[^/]*$");
			boost::smatch what;

			if(!boost::regex_match(_curi, what, match_category_uri))
				return;

			std::string curi = what[1];

			for(size_t i = 0; i < 100; ++i)
			{
				std::string puri = curi + "?PageNumber=" + boost::lexical_cast<std::string>(i);

				size_t product_i = 0;
				product_parser pp([&](const message::product_base& p, boost::optional<std::string> const& _image_uri, datetime retrieved_on, confidence conf, problems_t probs)
				{
					boost::optional<std::string> image_uri;
					if(_image_uri)
						image_uri = base_uri + *_image_uri;

					callback(puri, image_uri, p, {}, retrieved_on, conf, probs);

					++product_i;
				});
				pp.parse(dl.fetch(puri).body);

				if(product_i == 0)
					return;
			}
		});

		cp.parse(dl.fetch(base_uri + "/producten").body);
	}

	raw scraper::download_image(const std::string& uri)
	{
		std::string buf(dl.fetch(uri).body);
		return raw(buf.data(), buf.length());
	}
}
<commit_msg>Removed (currently) superfluous qualification of image_uri's<commit_after>#include <maximus/scraper.hpp>

#include <iostream>
#include <deque>
#include <fstream>
#include <boost/locale.hpp>

#include <supermarx/util/stubborn.hpp>

#include <maximus/parsers/product_parser.hpp>
#include <maximus/parsers/category_parser.hpp>

namespace supermarx
{
	scraper::scraper(callback_t _callback, size_t _ratelimit, bool _cache, bool)
	: callback(_callback)
	, dl("supermarx maximus/1.0", _ratelimit, _cache ? boost::optional<std::string>("./cache") : boost::none)
	{}

	void scraper::scrape()
	{
		const std::string base_uri = "http://www.jumbo.com";

		category_parser cp([&](category_parser::category_uri_t const& _curi)
		{
			static const boost::regex match_category_uri("^(.+)/[^/]*$");
			boost::smatch what;

			if(!boost::regex_match(_curi, what, match_category_uri))
				return;

			std::string curi = what[1];

			for(size_t i = 0; i < 100; ++i)
			{
				std::string puri = curi + "?PageNumber=" + boost::lexical_cast<std::string>(i);

				size_t product_i = 0;
				product_parser pp([&](const message::product_base& p, boost::optional<std::string> const& image_uri, datetime retrieved_on, confidence conf, problems_t probs)
				{
					callback(puri, image_uri, p, {}, retrieved_on, conf, probs);

					++product_i;
				});
				pp.parse(dl.fetch(puri).body);

				if(product_i == 0)
					return;
			}
		});

		cp.parse(dl.fetch(base_uri + "/producten").body);
	}

	raw scraper::download_image(const std::string& uri)
	{
		std::string buf(dl.fetch(uri).body);
		return raw(buf.data(), buf.length());
	}
}
<|endoftext|>


<commit_before>/*
 * Copyright (c) 2011-2013 ARM Limited
 * All rights reserved
 *
 * The license below extends only to copyright in the software and shall
 * not be construed as granting a license to any other intellectual
 * property including but not limited to intellectual property relating
 * to a hardware implementation of the functionality of the software
 * licensed hereunder.  You may use the software subject to the license
 * terms below provided that you ensure that this notice is replicated
 * unmodified and in its entirety in all distributions of the software,
 * modified or unmodified, in source code or in binary form.
 *
 * Copyright (c) 2002-2005 The Regents of The University of Michigan
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are
 * met: redistributions of source code must retain the above copyright
 * notice, this list of conditions and the following disclaimer;
 * redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the distribution;
 * neither the name of the copyright holders nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 * Authors: Ron Dreslinski
 *          Ali Saidi
 *          Andreas Hansson
 *          William Wang
 */

/**
 * @file
 * Declaration of a coherent bus.
 */

#ifndef __MEM_COHERENT_BUS_HH__
#define __MEM_COHERENT_BUS_HH__

#include "base/hashmap.hh"
#include "mem/bus.hh"
#include "params/CoherentBus.hh"

/**
 * A coherent bus connects a number of (potentially) snooping masters
 * and slaves, and routes the request and response packets based on
 * the address, and also forwards all requests to the snoopers and
 * deals with the snoop responses.
 *
 * The coherent bus can be used as a template for modelling QPI,
* HyperTransport, ACE and coherent OCP buses, and is typically used
 * for the L1-to-L2 buses and as the main system interconnect.
 * @sa  \ref gem5MemorySystem "gem5 Memory System"
 */
class CoherentBus : public BaseBus
{

  protected:

    /**
     * Declare the layers of this bus, one vector for requests, one
     * for responses, and one for snoop responses
     */
    typedef Layer<SlavePort,MasterPort> ReqLayer;
    typedef Layer<MasterPort,SlavePort> RespLayer;
    typedef Layer<SlavePort,MasterPort> SnoopLayer;
    std::vector<ReqLayer*> reqLayers;
    std::vector<RespLayer*> respLayers;
    std::vector<SnoopLayer*> snoopLayers;

    /**
     * Declaration of the coherent bus slave port type, one will be
     * instantiated for each of the master ports connecting to the
     * bus.
     */
    class CoherentBusSlavePort : public SlavePort
    {

      private:

        /** A reference to the bus to which this port belongs. */
        CoherentBus &bus;

      public:

        CoherentBusSlavePort(const std::string &_name,
                             CoherentBus &_bus, PortID _id)
            : SlavePort(_name, &_bus, _id), bus(_bus)
        { }

      protected:

        /**
         * When receiving a timing request, pass it to the bus.
         */
        virtual bool recvTimingReq(PacketPtr pkt)
        { return bus.recvTimingReq(pkt, id); }

        /**
         * When receiving a timing snoop response, pass it to the bus.
         */
        virtual bool recvTimingSnoopResp(PacketPtr pkt)
        { return bus.recvTimingSnoopResp(pkt, id); }

        /**
         * When receiving an atomic request, pass it to the bus.
         */
        virtual Tick recvAtomic(PacketPtr pkt)
        { return bus.recvAtomic(pkt, id); }

        /**
         * When receiving a functional request, pass it to the bus.
         */
        virtual void recvFunctional(PacketPtr pkt)
        { bus.recvFunctional(pkt, id); }

        /**
         * When receiving a retry, pass it to the bus.
         */
        virtual void recvRetry()
        { panic("Bus slave ports always succeed and should never retry.\n"); }

        /**
         * Return the union of all adress ranges seen by this bus.
         */
        virtual AddrRangeList getAddrRanges() const
        { return bus.getAddrRanges(); }

        /**
         * Get the maximum block size as seen by the bus.
         */
        virtual unsigned deviceBlockSize() const
        { return bus.deviceBlockSize(); }

    };

    /**
     * Declaration of the coherent bus master port type, one will be
     * instantiated for each of the slave interfaces connecting to the
     * bus.
     */
    class CoherentBusMasterPort : public MasterPort
    {
      private:
        /** A reference to the bus to which this port belongs. */
        CoherentBus &bus;

      public:

        CoherentBusMasterPort(const std::string &_name,
                              CoherentBus &_bus, PortID _id)
            : MasterPort(_name, &_bus, _id), bus(_bus)
        { }

      protected:

        /**
         * Determine if this port should be considered a snooper. For
         * a coherent bus master port this is always true.
         *
         * @return a boolean that is true if this port is snooping
         */
        virtual bool isSnooping() const
        { return true; }

        /**
         * When receiving a timing response, pass it to the bus.
         */
        virtual bool recvTimingResp(PacketPtr pkt)
        { return bus.recvTimingResp(pkt, id); }

        /**
         * When receiving a timing snoop request, pass it to the bus.
         */
        virtual void recvTimingSnoopReq(PacketPtr pkt)
        { return bus.recvTimingSnoopReq(pkt, id); }

        /**
         * When receiving an atomic snoop request, pass it to the bus.
         */
        virtual Tick recvAtomicSnoop(PacketPtr pkt)
        { return bus.recvAtomicSnoop(pkt, id); }

        /**
         * When receiving a functional snoop request, pass it to the bus.
         */
        virtual void recvFunctionalSnoop(PacketPtr pkt)
        { bus.recvFunctionalSnoop(pkt, id); }

        /** When reciving a range change from the peer port (at id),
            pass it to the bus. */
        virtual void recvRangeChange()
        { bus.recvRangeChange(id); }

        /** When reciving a retry from the peer port (at id),
            pass it to the bus. */
        virtual void recvRetry()
        { bus.recvRetry(id); }

        // Ask the bus to ask everyone on the bus what their block size is and
        // take the max of it. This might need to be changed a bit if we ever
        // support multiple block sizes.
        virtual unsigned deviceBlockSize() const
        { return bus.deviceBlockSize(); }

    };

    /**
     * Internal class to bridge between an incoming snoop response
     * from a slave port and forwarding it through an outgoing slave
     * port. It is effectively a dangling master port.
     */
    class SnoopRespPort : public MasterPort
    {

      private:

        /** The port which we mirror internally. */
        SlavePort& slavePort;

        /** The bus to which this port belongs. */
        CoherentBus &bus;

      public:

        /**
         * Create a snoop response port that mirrors a given slave port.
         */
        SnoopRespPort(SlavePort& slave_port, CoherentBus& _bus) :
            MasterPort(slave_port.name() + ".snoopRespPort", &_bus),
            slavePort(slave_port), bus(_bus) { }

        /**
         * Override the sending of retries and pass them on through
         * the mirrored slave port.
         */
        void sendRetry() {
            slavePort.sendRetry();
        }

        /**
         * Provided as necessary.
         */
        void recvRetry() { panic("SnoopRespPort should never see retry\n"); }

        /**
         * Provided as necessary.
         */
        bool recvTimingResp(PacketPtr pkt)
        {
            panic("SnoopRespPort should never see timing response\n");
            return false;
        }

    };

    std::vector<SnoopRespPort*> snoopRespPorts;

    std::vector<SlavePort*> snoopPorts;

    /**
     * Store the outstanding requests so we can determine which ones
     * we generated and which ones were merely forwarded. This is used
     * in the coherent bus when coherency responses come back.
     */
    m5::hash_set<RequestPtr> outstandingReq;

    /**
     * Keep a pointer to the system to be allow to querying memory system
     * properties.
     */
    System *system;

    /** Function called by the port when the bus is recieving a Timing
      request packet.*/
    virtual bool recvTimingReq(PacketPtr pkt, PortID slave_port_id);

    /** Function called by the port when the bus is recieving a Timing
      response packet.*/
    virtual bool recvTimingResp(PacketPtr pkt, PortID master_port_id);

    /** Function called by the port when the bus is recieving a timing
        snoop request.*/
    virtual void recvTimingSnoopReq(PacketPtr pkt, PortID master_port_id);

    /** Function called by the port when the bus is recieving a timing
        snoop response.*/
    virtual bool recvTimingSnoopResp(PacketPtr pkt, PortID slave_port_id);

    /** Timing function called by port when it is once again able to process
     * requests. */
    void recvRetry(PortID master_port_id);

    /**
     * Forward a timing packet to our snoopers, potentially excluding
     * one of the connected coherent masters to avoid sending a packet
     * back to where it came from.
     *
     * @param pkt Packet to forward
     * @param exclude_slave_port_id Id of slave port to exclude
     */
    void forwardTiming(PacketPtr pkt, PortID exclude_slave_port_id);

    /** Function called by the port when the bus is recieving a Atomic
      transaction.*/
    Tick recvAtomic(PacketPtr pkt, PortID slave_port_id);

    /** Function called by the port when the bus is recieving an
        atomic snoop transaction.*/
    Tick recvAtomicSnoop(PacketPtr pkt, PortID master_port_id);

    /**
     * Forward an atomic packet to our snoopers, potentially excluding
     * one of the connected coherent masters to avoid sending a packet
     * back to where it came from.
     *
     * @param pkt Packet to forward
     * @param exclude_slave_port_id Id of slave port to exclude
     *
     * @return a pair containing the snoop response and snoop latency
     */
    std::pair<MemCmd, Tick> forwardAtomic(PacketPtr pkt,
                                          PortID exclude_slave_port_id);

    /** Function called by the port when the bus is recieving a Functional
        transaction.*/
    void recvFunctional(PacketPtr pkt, PortID slave_port_id);

    /** Function called by the port when the bus is recieving a functional
        snoop transaction.*/
    void recvFunctionalSnoop(PacketPtr pkt, PortID master_port_id);

    /**
     * Forward a functional packet to our snoopers, potentially
     * excluding one of the connected coherent masters to avoid
     * sending a packet back to where it came from.
     *
     * @param pkt Packet to forward
     * @param exclude_slave_port_id Id of slave port to exclude
     */
    void forwardFunctional(PacketPtr pkt, PortID exclude_slave_port_id);

    Stats::Scalar dataThroughBus;
    Stats::Scalar snoopDataThroughBus;

  public:

    virtual void init();

    CoherentBus(const CoherentBusParams *p);

    virtual ~CoherentBus();

    unsigned int drain(DrainManager *dm);

    virtual void regStats();
};

#endif //__MEM_COHERENT_BUS_HH__
<commit_msg>mem: Remove CoherentBus snoop port unused private member<commit_after>/*
 * Copyright (c) 2011-2013 ARM Limited
 * All rights reserved
 *
 * The license below extends only to copyright in the software and shall
 * not be construed as granting a license to any other intellectual
 * property including but not limited to intellectual property relating
 * to a hardware implementation of the functionality of the software
 * licensed hereunder.  You may use the software subject to the license
 * terms below provided that you ensure that this notice is replicated
 * unmodified and in its entirety in all distributions of the software,
 * modified or unmodified, in source code or in binary form.
 *
 * Copyright (c) 2002-2005 The Regents of The University of Michigan
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are
 * met: redistributions of source code must retain the above copyright
 * notice, this list of conditions and the following disclaimer;
 * redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the distribution;
 * neither the name of the copyright holders nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 * Authors: Ron Dreslinski
 *          Ali Saidi
 *          Andreas Hansson
 *          William Wang
 */

/**
 * @file
 * Declaration of a coherent bus.
 */

#ifndef __MEM_COHERENT_BUS_HH__
#define __MEM_COHERENT_BUS_HH__

#include "base/hashmap.hh"
#include "mem/bus.hh"
#include "params/CoherentBus.hh"

/**
 * A coherent bus connects a number of (potentially) snooping masters
 * and slaves, and routes the request and response packets based on
 * the address, and also forwards all requests to the snoopers and
 * deals with the snoop responses.
 *
 * The coherent bus can be used as a template for modelling QPI,
* HyperTransport, ACE and coherent OCP buses, and is typically used
 * for the L1-to-L2 buses and as the main system interconnect.
 * @sa  \ref gem5MemorySystem "gem5 Memory System"
 */
class CoherentBus : public BaseBus
{

  protected:

    /**
     * Declare the layers of this bus, one vector for requests, one
     * for responses, and one for snoop responses
     */
    typedef Layer<SlavePort,MasterPort> ReqLayer;
    typedef Layer<MasterPort,SlavePort> RespLayer;
    typedef Layer<SlavePort,MasterPort> SnoopLayer;
    std::vector<ReqLayer*> reqLayers;
    std::vector<RespLayer*> respLayers;
    std::vector<SnoopLayer*> snoopLayers;

    /**
     * Declaration of the coherent bus slave port type, one will be
     * instantiated for each of the master ports connecting to the
     * bus.
     */
    class CoherentBusSlavePort : public SlavePort
    {

      private:

        /** A reference to the bus to which this port belongs. */
        CoherentBus &bus;

      public:

        CoherentBusSlavePort(const std::string &_name,
                             CoherentBus &_bus, PortID _id)
            : SlavePort(_name, &_bus, _id), bus(_bus)
        { }

      protected:

        /**
         * When receiving a timing request, pass it to the bus.
         */
        virtual bool recvTimingReq(PacketPtr pkt)
        { return bus.recvTimingReq(pkt, id); }

        /**
         * When receiving a timing snoop response, pass it to the bus.
         */
        virtual bool recvTimingSnoopResp(PacketPtr pkt)
        { return bus.recvTimingSnoopResp(pkt, id); }

        /**
         * When receiving an atomic request, pass it to the bus.
         */
        virtual Tick recvAtomic(PacketPtr pkt)
        { return bus.recvAtomic(pkt, id); }

        /**
         * When receiving a functional request, pass it to the bus.
         */
        virtual void recvFunctional(PacketPtr pkt)
        { bus.recvFunctional(pkt, id); }

        /**
         * When receiving a retry, pass it to the bus.
         */
        virtual void recvRetry()
        { panic("Bus slave ports always succeed and should never retry.\n"); }

        /**
         * Return the union of all adress ranges seen by this bus.
         */
        virtual AddrRangeList getAddrRanges() const
        { return bus.getAddrRanges(); }

        /**
         * Get the maximum block size as seen by the bus.
         */
        virtual unsigned deviceBlockSize() const
        { return bus.deviceBlockSize(); }

    };

    /**
     * Declaration of the coherent bus master port type, one will be
     * instantiated for each of the slave interfaces connecting to the
     * bus.
     */
    class CoherentBusMasterPort : public MasterPort
    {
      private:
        /** A reference to the bus to which this port belongs. */
        CoherentBus &bus;

      public:

        CoherentBusMasterPort(const std::string &_name,
                              CoherentBus &_bus, PortID _id)
            : MasterPort(_name, &_bus, _id), bus(_bus)
        { }

      protected:

        /**
         * Determine if this port should be considered a snooper. For
         * a coherent bus master port this is always true.
         *
         * @return a boolean that is true if this port is snooping
         */
        virtual bool isSnooping() const
        { return true; }

        /**
         * When receiving a timing response, pass it to the bus.
         */
        virtual bool recvTimingResp(PacketPtr pkt)
        { return bus.recvTimingResp(pkt, id); }

        /**
         * When receiving a timing snoop request, pass it to the bus.
         */
        virtual void recvTimingSnoopReq(PacketPtr pkt)
        { return bus.recvTimingSnoopReq(pkt, id); }

        /**
         * When receiving an atomic snoop request, pass it to the bus.
         */
        virtual Tick recvAtomicSnoop(PacketPtr pkt)
        { return bus.recvAtomicSnoop(pkt, id); }

        /**
         * When receiving a functional snoop request, pass it to the bus.
         */
        virtual void recvFunctionalSnoop(PacketPtr pkt)
        { bus.recvFunctionalSnoop(pkt, id); }

        /** When reciving a range change from the peer port (at id),
            pass it to the bus. */
        virtual void recvRangeChange()
        { bus.recvRangeChange(id); }

        /** When reciving a retry from the peer port (at id),
            pass it to the bus. */
        virtual void recvRetry()
        { bus.recvRetry(id); }

        // Ask the bus to ask everyone on the bus what their block size is and
        // take the max of it. This might need to be changed a bit if we ever
        // support multiple block sizes.
        virtual unsigned deviceBlockSize() const
        { return bus.deviceBlockSize(); }

    };

    /**
     * Internal class to bridge between an incoming snoop response
     * from a slave port and forwarding it through an outgoing slave
     * port. It is effectively a dangling master port.
     */
    class SnoopRespPort : public MasterPort
    {

      private:

        /** The port which we mirror internally. */
        SlavePort& slavePort;

      public:

        /**
         * Create a snoop response port that mirrors a given slave port.
         */
        SnoopRespPort(SlavePort& slave_port, CoherentBus& _bus) :
            MasterPort(slave_port.name() + ".snoopRespPort", &_bus),
            slavePort(slave_port) { }

        /**
         * Override the sending of retries and pass them on through
         * the mirrored slave port.
         */
        void sendRetry() {
            slavePort.sendRetry();
        }

        /**
         * Provided as necessary.
         */
        void recvRetry() { panic("SnoopRespPort should never see retry\n"); }

        /**
         * Provided as necessary.
         */
        bool recvTimingResp(PacketPtr pkt)
        {
            panic("SnoopRespPort should never see timing response\n");
            return false;
        }

    };

    std::vector<SnoopRespPort*> snoopRespPorts;

    std::vector<SlavePort*> snoopPorts;

    /**
     * Store the outstanding requests so we can determine which ones
     * we generated and which ones were merely forwarded. This is used
     * in the coherent bus when coherency responses come back.
     */
    m5::hash_set<RequestPtr> outstandingReq;

    /**
     * Keep a pointer to the system to be allow to querying memory system
     * properties.
     */
    System *system;

    /** Function called by the port when the bus is recieving a Timing
      request packet.*/
    virtual bool recvTimingReq(PacketPtr pkt, PortID slave_port_id);

    /** Function called by the port when the bus is recieving a Timing
      response packet.*/
    virtual bool recvTimingResp(PacketPtr pkt, PortID master_port_id);

    /** Function called by the port when the bus is recieving a timing
        snoop request.*/
    virtual void recvTimingSnoopReq(PacketPtr pkt, PortID master_port_id);

    /** Function called by the port when the bus is recieving a timing
        snoop response.*/
    virtual bool recvTimingSnoopResp(PacketPtr pkt, PortID slave_port_id);

    /** Timing function called by port when it is once again able to process
     * requests. */
    void recvRetry(PortID master_port_id);

    /**
     * Forward a timing packet to our snoopers, potentially excluding
     * one of the connected coherent masters to avoid sending a packet
     * back to where it came from.
     *
     * @param pkt Packet to forward
     * @param exclude_slave_port_id Id of slave port to exclude
     */
    void forwardTiming(PacketPtr pkt, PortID exclude_slave_port_id);

    /** Function called by the port when the bus is recieving a Atomic
      transaction.*/
    Tick recvAtomic(PacketPtr pkt, PortID slave_port_id);

    /** Function called by the port when the bus is recieving an
        atomic snoop transaction.*/
    Tick recvAtomicSnoop(PacketPtr pkt, PortID master_port_id);

    /**
     * Forward an atomic packet to our snoopers, potentially excluding
     * one of the connected coherent masters to avoid sending a packet
     * back to where it came from.
     *
     * @param pkt Packet to forward
     * @param exclude_slave_port_id Id of slave port to exclude
     *
     * @return a pair containing the snoop response and snoop latency
     */
    std::pair<MemCmd, Tick> forwardAtomic(PacketPtr pkt,
                                          PortID exclude_slave_port_id);

    /** Function called by the port when the bus is recieving a Functional
        transaction.*/
    void recvFunctional(PacketPtr pkt, PortID slave_port_id);

    /** Function called by the port when the bus is recieving a functional
        snoop transaction.*/
    void recvFunctionalSnoop(PacketPtr pkt, PortID master_port_id);

    /**
     * Forward a functional packet to our snoopers, potentially
     * excluding one of the connected coherent masters to avoid
     * sending a packet back to where it came from.
     *
     * @param pkt Packet to forward
     * @param exclude_slave_port_id Id of slave port to exclude
     */
    void forwardFunctional(PacketPtr pkt, PortID exclude_slave_port_id);

    Stats::Scalar dataThroughBus;
    Stats::Scalar snoopDataThroughBus;

  public:

    virtual void init();

    CoherentBus(const CoherentBusParams *p);

    virtual ~CoherentBus();

    unsigned int drain(DrainManager *dm);

    virtual void regStats();
};

#endif //__MEM_COHERENT_BUS_HH__
<|endoftext|>


<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2000, 2010 Oracle and/or its affiliates.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org 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 version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/
#ifndef _SVX_SPLWRAP_HXX
#define _SVX_SPLWRAP_HXX

// include ---------------------------------------------------------------

#include <editeng/svxenum.hxx>
#include <tools/string.hxx>
#include <com/sun/star/uno/Reference.hxx>
#include "editeng/editengdllapi.h"

// forward ---------------------------------------------------------------

namespace com { namespace sun { namespace star { namespace linguistic2 {
    class XDictionary;
    class XSpellChecker1;
    class XHyphenator;
}}}}

class Window;

// misc functions ---------------------------------------------------------------

void EDITENG_DLLPUBLIC SvxPrepareAutoCorrect( String &rOldText, String &rNewText );

/*--------------------------------------------------------------------
     Description: The SpellWrapper
 --------------------------------------------------------------------*/

class EDITENG_DLLPUBLIC SvxSpellWrapper {
private:
    friend class SvxSpellCheckDialog;
    friend class SvxHyphenWordDialog;
    friend class SvxHyphenWordDialog_Impl;

    Window*     pWin;
    ::com::sun::star::uno::Reference<
        ::com::sun::star::uno::XInterface >             xLast;  // result of last spelling/hyphenation attempt
    ::com::sun::star::uno::Reference<
        ::com::sun::star::linguistic2::XSpellChecker1 > xSpell;
    ::com::sun::star::uno::Reference<
        ::com::sun::star::linguistic2::XHyphenator >    xHyph;
    sal_uInt16  nOldLang;        // Set Language, only call SetLanguage on changes
    sal_Bool    bOtherCntnt : 1; // set => Check special sections initially
    sal_Bool    bDialog     : 1; // Is pWin the Svx...Dialog?
    sal_Bool    bHyphen     : 1; // Split instead of spell checking
    sal_Bool    bAuto       : 1; // AutoCorrect available?
    sal_Bool    bReverse    : 1; // Reverse spell check
    sal_Bool    bStartDone  : 1; // Beginning already corrected
    sal_Bool    bEndDone    : 1; // End part already corrected
    sal_Bool    bStartChk   : 1; // Examine the beginning
    sal_Bool    bRevAllowed : 1; // Reverse spell check prohibited
    sal_Bool    bAllRight   : 1; // Record wrong words in the dedicated
                                 // dictionary and do not start the dialog.

    EDITENG_DLLPRIVATE sal_Bool     SpellNext();        // select next area
    sal_Bool    FindSpellError();   // Check for errors (over areas)

public:
    SvxSpellWrapper( Window* pWn,
                     ::com::sun::star::uno::Reference<
                         ::com::sun::star::linguistic2::XSpellChecker1 >  &xSpellChecker,
                     const sal_Bool bStart = sal_False, const sal_Bool bIsAllRight = sal_False,
                     const sal_Bool bOther = sal_False, const sal_Bool bRevAllow = sal_True );
    SvxSpellWrapper( Window* pWn,
                     ::com::sun::star::uno::Reference<
                         ::com::sun::star::linguistic2::XHyphenator >  &xHyphenator,
                     const sal_Bool bStart = sal_False, const sal_Bool bOther = sal_False );

    virtual ~SvxSpellWrapper();

    static sal_Int16    CheckSpellLang(
                            ::com::sun::star::uno::Reference<
                                ::com::sun::star::linguistic2::XSpellChecker1 >  xSpell,
                            sal_Int16 nLang );
    static sal_Int16    CheckHyphLang(
                            ::com::sun::star::uno::Reference<
                                ::com::sun::star::linguistic2::XHyphenator >  xHyph,
                            sal_Int16 nLang );

    static void         ShowLanguageErrors();

    void            SpellDocument();        // Perform Spell Checking
    inline sal_Bool IsStartDone(){ return bStartDone; }
    inline sal_Bool IsEndDone(){ return bEndDone; }
    inline sal_Bool IsReverse(){ return bReverse; }
    inline sal_Bool IsDialog(){ return bDialog; } // SvxSpellCheckDialog OnScreen
    inline sal_Bool IsHyphen(){ return bHyphen; } // Split instead of Spell check
    inline void     SetHyphen( const sal_Bool bNew = sal_True ){ bHyphen = bNew; }
    inline ::com::sun::star::uno::Reference<
        ::com::sun::star::linguistic2::XSpellChecker1 >
                    GetXSpellChecker() { return xSpell; }
    inline ::com::sun::star::uno::Reference<
        ::com::sun::star::linguistic2::XHyphenator >
                    GetXHyphenator()    { return xHyph; }
    inline sal_Bool             IsAllRight()        { return bAllRight; }
    inline Window*  GetWin() { return pWin; }
    // can possibly be omitted in ONE_LINGU:
    inline void     SetOldLang( const sal_uInt16 nNew ){ nOldLang = nNew; }
    // can possibly be omitted in ONE_LINGU:
    inline void     ChangeLanguage( const sal_uInt16 nNew ) // call SetLanguage if needed.
        { if ( nNew != nOldLang ) { SetLanguage( nNew ); nOldLang = nNew; } }
    inline void     EnableAutoCorrect() { bAuto = sal_True; }

protected:
    ::com::sun::star::uno::Reference<
        ::com::sun::star::uno::XInterface >
                     GetLast()      { return xLast; }
    void             SetLast(const ::com::sun::star::uno::Reference<
                                ::com::sun::star::uno::XInterface >  &xNewLast)
                            { xLast = xNewLast; }
    virtual sal_Bool SpellMore();               // examine further documents?
    virtual sal_Bool HasOtherCnt();             // Are there any special areas?
    virtual void     SpellStart( SvxSpellArea eSpell ); // Preparing the area
    virtual sal_Bool SpellContinue();     // Check Areas
                                          // Result avaliable through GetLast
    virtual void ReplaceAll( const String &rNewText, sal_Int16 nLanguage ); //Replace word from the replace list
    virtual void StartThesaurus( const String &rWord, sal_uInt16 nLang );
    virtual ::com::sun::star::uno::Reference<
        ::com::sun::star::linguistic2::XDictionary >
                 GetAllRightDic() const;
    virtual void SpellEnd();                        // Finish area
    virtual void ScrollArea();                      // Set ScrollArea
    // Replace word
    virtual void ChangeWord( const String& rNewWord, const sal_uInt16 nLang );
    virtual String GetThesWord();
    // Wort via Thesaurus ersetzen
    virtual void ChangeThesWord( const String& rNewWord );
    virtual void SetLanguage( const sal_uInt16 nLang ); // Change Language
    virtual void AutoCorrect( const String& rAktStr, const String& rNewStr );
    virtual void InsertHyphen( const sal_uInt16 nPos ); // Insert hyphen

};

#endif

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<commit_msg>WaE: class vs struct<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2000, 2010 Oracle and/or its affiliates.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org 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 version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/
#ifndef _SVX_SPLWRAP_HXX
#define _SVX_SPLWRAP_HXX

// include ---------------------------------------------------------------

#include <editeng/svxenum.hxx>
#include <tools/string.hxx>
#include <com/sun/star/uno/Reference.hxx>
#include "editeng/editengdllapi.h"

// forward ---------------------------------------------------------------

namespace com { namespace sun { namespace star { namespace linguistic2 {
    class XDictionary;
    class XSpellChecker1;
    class XHyphenator;
}}}}

class Window;

// misc functions ---------------------------------------------------------------

void EDITENG_DLLPUBLIC SvxPrepareAutoCorrect( String &rOldText, String &rNewText );

/*--------------------------------------------------------------------
     Description: The SpellWrapper
 --------------------------------------------------------------------*/

class EDITENG_DLLPUBLIC SvxSpellWrapper {
private:
    friend class SvxSpellCheckDialog;
    friend class SvxHyphenWordDialog;
    friend struct SvxHyphenWordDialog_Impl;

    Window*     pWin;
    ::com::sun::star::uno::Reference<
        ::com::sun::star::uno::XInterface >             xLast;  // result of last spelling/hyphenation attempt
    ::com::sun::star::uno::Reference<
        ::com::sun::star::linguistic2::XSpellChecker1 > xSpell;
    ::com::sun::star::uno::Reference<
        ::com::sun::star::linguistic2::XHyphenator >    xHyph;
    sal_uInt16  nOldLang;        // Set Language, only call SetLanguage on changes
    sal_Bool    bOtherCntnt : 1; // set => Check special sections initially
    sal_Bool    bDialog     : 1; // Is pWin the Svx...Dialog?
    sal_Bool    bHyphen     : 1; // Split instead of spell checking
    sal_Bool    bAuto       : 1; // AutoCorrect available?
    sal_Bool    bReverse    : 1; // Reverse spell check
    sal_Bool    bStartDone  : 1; // Beginning already corrected
    sal_Bool    bEndDone    : 1; // End part already corrected
    sal_Bool    bStartChk   : 1; // Examine the beginning
    sal_Bool    bRevAllowed : 1; // Reverse spell check prohibited
    sal_Bool    bAllRight   : 1; // Record wrong words in the dedicated
                                 // dictionary and do not start the dialog.

    EDITENG_DLLPRIVATE sal_Bool     SpellNext();        // select next area
    sal_Bool    FindSpellError();   // Check for errors (over areas)

public:
    SvxSpellWrapper( Window* pWn,
                     ::com::sun::star::uno::Reference<
                         ::com::sun::star::linguistic2::XSpellChecker1 >  &xSpellChecker,
                     const sal_Bool bStart = sal_False, const sal_Bool bIsAllRight = sal_False,
                     const sal_Bool bOther = sal_False, const sal_Bool bRevAllow = sal_True );
    SvxSpellWrapper( Window* pWn,
                     ::com::sun::star::uno::Reference<
                         ::com::sun::star::linguistic2::XHyphenator >  &xHyphenator,
                     const sal_Bool bStart = sal_False, const sal_Bool bOther = sal_False );

    virtual ~SvxSpellWrapper();

    static sal_Int16    CheckSpellLang(
                            ::com::sun::star::uno::Reference<
                                ::com::sun::star::linguistic2::XSpellChecker1 >  xSpell,
                            sal_Int16 nLang );
    static sal_Int16    CheckHyphLang(
                            ::com::sun::star::uno::Reference<
                                ::com::sun::star::linguistic2::XHyphenator >  xHyph,
                            sal_Int16 nLang );

    static void         ShowLanguageErrors();

    void            SpellDocument();        // Perform Spell Checking
    inline sal_Bool IsStartDone(){ return bStartDone; }
    inline sal_Bool IsEndDone(){ return bEndDone; }
    inline sal_Bool IsReverse(){ return bReverse; }
    inline sal_Bool IsDialog(){ return bDialog; } // SvxSpellCheckDialog OnScreen
    inline sal_Bool IsHyphen(){ return bHyphen; } // Split instead of Spell check
    inline void     SetHyphen( const sal_Bool bNew = sal_True ){ bHyphen = bNew; }
    inline ::com::sun::star::uno::Reference<
        ::com::sun::star::linguistic2::XSpellChecker1 >
                    GetXSpellChecker() { return xSpell; }
    inline ::com::sun::star::uno::Reference<
        ::com::sun::star::linguistic2::XHyphenator >
                    GetXHyphenator()    { return xHyph; }
    inline sal_Bool             IsAllRight()        { return bAllRight; }
    inline Window*  GetWin() { return pWin; }
    // can possibly be omitted in ONE_LINGU:
    inline void     SetOldLang( const sal_uInt16 nNew ){ nOldLang = nNew; }
    // can possibly be omitted in ONE_LINGU:
    inline void     ChangeLanguage( const sal_uInt16 nNew ) // call SetLanguage if needed.
        { if ( nNew != nOldLang ) { SetLanguage( nNew ); nOldLang = nNew; } }
    inline void     EnableAutoCorrect() { bAuto = sal_True; }

protected:
    ::com::sun::star::uno::Reference<
        ::com::sun::star::uno::XInterface >
                     GetLast()      { return xLast; }
    void             SetLast(const ::com::sun::star::uno::Reference<
                                ::com::sun::star::uno::XInterface >  &xNewLast)
                            { xLast = xNewLast; }
    virtual sal_Bool SpellMore();               // examine further documents?
    virtual sal_Bool HasOtherCnt();             // Are there any special areas?
    virtual void     SpellStart( SvxSpellArea eSpell ); // Preparing the area
    virtual sal_Bool SpellContinue();     // Check Areas
                                          // Result avaliable through GetLast
    virtual void ReplaceAll( const String &rNewText, sal_Int16 nLanguage ); //Replace word from the replace list
    virtual void StartThesaurus( const String &rWord, sal_uInt16 nLang );
    virtual ::com::sun::star::uno::Reference<
        ::com::sun::star::linguistic2::XDictionary >
                 GetAllRightDic() const;
    virtual void SpellEnd();                        // Finish area
    virtual void ScrollArea();                      // Set ScrollArea
    // Replace word
    virtual void ChangeWord( const String& rNewWord, const sal_uInt16 nLang );
    virtual String GetThesWord();
    // Wort via Thesaurus ersetzen
    virtual void ChangeThesWord( const String& rNewWord );
    virtual void SetLanguage( const sal_uInt16 nLang ); // Change Language
    virtual void AutoCorrect( const String& rAktStr, const String& rNewStr );
    virtual void InsertHyphen( const sal_uInt16 nPos ); // Insert hyphen

};

#endif

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<|endoftext|>


<commit_before>// HeisenbergDiffuse.cpp -- WangLandau sampling of the Heisenberg model
//
// Greg Brown (gbrown@fsu.edu,browngrg@comcast.net)
//
// History
//
// HiesenbergDiffuse.cpp -- Added Meas_Diffusion object to measure diffusion of walkers.
// Aug 5, 2015
//
// Heisenberg2.cpp -- Changed from WL update to TM update
// Aug 29, 2014
//
// Heisenberg1.cpp -- WangLandau sampling of Heisenberg model
// Aug 15, 2014
//
// Mfia2.cpp -- WangLandau sampling of Mfia model (Borrows heavily from Latgas3.cpp)
// August 7, 2014
//
// Mfia1.cpp -- Generate the Metropolis trajectory of one Mfia Monte Carlo walker
// June 28, 2014  Copied from Wham3.cpp
//
// Wham3.cpp -- Generate the trajectory of one Metropolis Monte Carlo walker
// June 4, 2014    Refactored for larger MC scheme
// Greg Brown (gbrown@fsu.edu,browngrg@comcast.net)
//

#include"MC_WangLandau.hpp"
#include"WL_Walker.hpp"
#include"Heisenberg_Hamiltonian.hpp"
#include"Meas_Diffusion.hpp"
#include"Random.hpp"
#include"ProgramOptions.hpp"

#include<stdio.h>

void ReadLngEst(std::string lng_est_fn, std::vector<double>& energy, std::vector<double>& lng_est)
{
      if( lng_est_fn[0]==0 ) return;
      if( true )
      {
         energy.resize(0);
         lng_est.resize(0);
         double E,lng;
         std::string buff;
         std::ifstream fin(lng_est_fn);
         while( fin && fin.is_open() && !fin.eof() )
         {
            std::getline(fin,buff);
            if( buff.size()>0 && buff[0]!='#' )
            {
               sscanf( buff.c_str(),"%lf %lf",&E,&lng);
               energy.push_back(E);
               lng_est.push_back(lng);
            }
         }
      }
}

void TrimLng(double Elo, double Ehi, std::vector<double>& energy, std::vector<double>& lng_est)
{
      if( Elo<std::numeric_limits<double>::max() )
      {
         int i=0;
         while( i<energy.size() && energy[i]<Elo ) i++;
         if( i<energy.size() )
         {
            std::cout << "Elo = " << Elo << std::endl;
            std::cout << "Triming energy from " << energy.front() << " with " << energy.size() << " elements" << std::endl;
            energy.erase(energy.begin(),energy.begin()+i);
            lng_est.erase(lng_est.begin(),lng_est.begin()+i);
            energy[0] = Elo;
            std::cout << "To energy from " << energy.front() << " with " << energy.size() << " elements" << std::endl;
         }
      }
      if( Ehi>-std::numeric_limits<double>::max() )
      {
         int i=0;
         while( i<energy.size() && energy[i]<Ehi ) i++;
         if( i<energy.size() )
         {
            std::cout << "Ehi = " << Ehi << std::endl;
            std::cout << "Triming energy ending at " << energy.back() << " with " << energy.size() << " elements" << std::endl;
            energy.erase(energy.begin()+i,energy.end());
            lng_est.erase(lng_est.begin()+i,lng_est.end());
            energy[i-1] = Ehi;
            std::cout << "To energy ending at " << energy.back() << " with " << energy.size() << " elements" << std::endl;
         }
      }
}

void DoHeisenberg(int& argc, char* argv[])
{

   //  Get basic MPI information
   int iproc = 0;
   int nproc = 1;
#  ifdef USE_MPI
   MPI_Comm_rank(MPI_COMM_WORLD,&iproc);
   MPI_Comm_size(MPI_COMM_WORLD,&nproc);
#  endif

   using namespace std;
   ProgramOptions options("Heisenberg","Wang-Landau Sampling.");

   // Construct a hamiltonian object
   typedef Heisenberg_Hamiltonian HAMILTONIAN;
   HAMILTONIAN hamilton;
   hamilton.L     = 64;
   hamilton.H     = 0;
   options.add_option("length", "extent of lattice in each dim", 'L', &(hamilton.L) );
   options.add_option("H",      "magnitude of magnetic field",   'H', &(hamilton.H) );

   // Construct the simulation object
   MC_WangLandau wanglandau;
   options.add_option( "Elo",     "lower side of energy window",    ' ', &(wanglandau.Elo));
   options.add_option( "Ehi",     "lower side of energy window",    ' ', &(wanglandau.Ehi));
   options.add_option( "Ebin",    "width of energy bins",           ' ', &(wanglandau.Ebin));
   options.add_option( "numwin",  "number of windows",              ' ', &(wanglandau.NWindow));
   options.add_option( "numwalk", "number of walkers per window",   ' ', &(wanglandau.NWalkPerProcess));
   options.add_option( "overlap", "fractional overlap of windows",  ' ', &(wanglandau.fwinover));
   options.add_option( "nchunk",  "number of steps per iteration",  ' ', &(wanglandau.NChunk));
   options.add_option( "maxupdate","maximum number of iterations",  ' ', &(wanglandau.MaxUpdate));
   options.add_option( "dosinterp","linear interpolation of dos",   ' ', &(wanglandau.LinearInterp));
   options.add_option( "wleta",    "weighting between WL and ITTM", ' ', &(wanglandau.wleta));
   options.add_option( "wlgamma",  "starting value of WL parameter",' ', &(wanglandau.wlgamma_start));
   options.add_option( "Q",        "target convergence factor",     ' ', &(wanglandau.Qquit));
   options.add_option( "configout","output configurations to disk", ' ', &(wanglandau.output_configs));

   Meas_Diffusion measure;
   options.add_option( "delay",    "target convergence factor",     ' ', &(measure.delay));

   // Local options
   char lng_est_fn[512]; lng_est_fn[0]=0;
   options.add_option( "estdos",   "estimated dos file",            ' ', lng_est_fn);

   // Get parameters
   options.parse_command_line(argc,argv);
   if( options.get_value<bool>("help") ) return;
   bool verbose = options.get_value<bool>("verbose") && (iproc==0);

   // Re-initialize objects
   if(verbose) cout << __FILE__ << ":" << __LINE__ << " Reinitialize begun" << endl;
   hamilton.init(verbose);
   const int NGrid = hamilton.nspin;
   if(verbose) cout << __FILE__ << ":" << __LINE__ << " NGrid=" << NGrid << endl;
   //simulator.NStep = static_cast<int>( static_cast<float>(NGrid)*NStep_MCSS );

   // seed the random number geneator
   wanglandau.urng.seed( ParallelSeed(SeedFromClock()) );
   bool rng_output = false;
   bool rng_failed = RNGTestMoments(wanglandau.urng,rng_output,std::cout);
   if( rng_failed )
   {
      cout << "Problem detected with random number generator" << endl;
      return;
   }
   if(verbose) cout << __FILE__ << ":" << __LINE__ << " Random number generator created" << endl;

   // Construct a representation of the model
   // This includes the "microscopic" configuration sigma_i
   // and the macroscopic quantities like magnetization and energy
   if(verbose) cout << __FILE__ << ":" << __LINE__ << " Create one walker" << endl;
   typedef WL_Walker<HAMILTONIAN::Config,HAMILTONIAN::Observables> Walker;
   std::vector<Walker> walkerpool(1);
   walkerpool[0].sigma.resize(NGrid);
   hamilton.initial_ferro(walkerpool[0].sigma);
   hamilton.calc_observable(walkerpool[0].sigma,walkerpool[0].now);
   wanglandau.verbose = options.get_value<bool>("verbose");
   wanglandau.partition_windows();
   wanglandau.init_pool(walkerpool);
   std::vector<double> energy;
   std::vector<double> est_lng;
   ReadLngEst(std::string(lng_est_fn),energy,est_lng);
   if( energy.size()>0 )
   {
      TrimLng(wanglandau.Elo,wanglandau.Ehi,energy,est_lng);
      wanglandau.partition_windows(energy,est_lng);
      for(int iwalk=0; iwalk<walkerpool.size(); iwalk++)
         walkerpool[iwalk].set_fixed(energy,est_lng);
   }

   measure.init(wanglandau.Elo,wanglandau.Ehi,wanglandau.Ebin);

   wanglandau.DoConverge(hamilton,walkerpool,measure);
}

int main(int argc, char* argv[])
{
   if( true )
   {
      std::cout << "cmdline:";
      for(int i=0; i<argc; i++) std::cout << " " << argv[i];
      std::cout << std::endl;
   }

#  ifdef USE_MPI
   MPI_Init(&argc,&argv);
#  endif
   DoHeisenberg(argc,argv);
#  ifdef USE_MPI
   MPI_Finalize();
#  endif

}

<commit_msg>Updated HeisenbergDiffusion.cpp for new MPI_Struct<commit_after>// HeisenbergDiffuse.cpp -- Measure diffusion properties of WangLandau walkers
//
// Greg Brown (gbrown@fsu.edu,browngrg@comcast.net)

#include"MC_WangLandau.hpp"
#include"WL_Walker.hpp"
#include"MPI_Struct.hpp"
#include"Heisenberg_Hamiltonian.hpp"
#include"Meas_Diffusion.hpp"
#include"Random.hpp"
#include"ProgramOptions.hpp"

#include<stdio.h>

void ReadLngEst(std::string lng_est_fn, std::vector<double>& energy, std::vector<double>& lng_est)
{
      if( lng_est_fn[0]==0 ) return;
      if( true )
      {
         energy.resize(0);
         lng_est.resize(0);
         double E,lng;
         std::string buff;
         std::ifstream fin(lng_est_fn);
         while( fin && fin.is_open() && !fin.eof() )
         {
            std::getline(fin,buff);
            if( buff.size()>0 && buff[0]!='#' )
            {
               sscanf( buff.c_str(),"%lf %lf",&E,&lng);
               energy.push_back(E);
               lng_est.push_back(lng);
            }
         }
      }
}

void TrimLng(double Elo, double Ehi, std::vector<double>& energy, std::vector<double>& lng_est)
{
      if( Elo<std::numeric_limits<double>::max() )
      {
         int i=0;
         while( i<energy.size() && energy[i]<Elo ) i++;
         if( i<energy.size() )
         {
            std::cout << "Elo = " << Elo << std::endl;
            std::cout << "Triming energy from " << energy.front() << " with " << energy.size() << " elements" << std::endl;
            energy.erase(energy.begin(),energy.begin()+i);
            lng_est.erase(lng_est.begin(),lng_est.begin()+i);
            energy[0] = Elo;
            std::cout << "To energy from " << energy.front() << " with " << energy.size() << " elements" << std::endl;
         }
      }
      if( Ehi>-std::numeric_limits<double>::max() )
      {
         int i=0;
         while( i<energy.size() && energy[i]<Ehi ) i++;
         if( i<energy.size() )
         {
            std::cout << "Ehi = " << Ehi << std::endl;
            std::cout << "Triming energy ending at " << energy.back() << " with " << energy.size() << " elements" << std::endl;
            energy.erase(energy.begin()+i,energy.end());
            lng_est.erase(lng_est.begin()+i,lng_est.end());
            energy[i-1] = Ehi;
            std::cout << "To energy ending at " << energy.back() << " with " << energy.size() << " elements" << std::endl;
         }
      }
}

void DoHeisenberg(int& argc, char* argv[])
{

   //  Get basic MPI information
   int iproc = 0;
   int nproc = 1;
#  ifdef USE_MPI
   MPI_Comm_rank(MPI_COMM_WORLD,&iproc);
   MPI_Comm_size(MPI_COMM_WORLD,&nproc);
#  endif

   using namespace std;
   ProgramOptions options("Heisenberg","Wang-Landau Sampling.");

   // Construct a hamiltonian object
   typedef Heisenberg_Hamiltonian HAMILTONIAN;
   HAMILTONIAN hamilton;
   hamilton.L     = 64;
   hamilton.H     = 0;
   options.add_option("length", "extent of lattice in each dim", 'L', &(hamilton.L) );
   options.add_option("H",      "magnitude of magnetic field",   'H', &(hamilton.H) );

   // Construct the simulation object
   MC_WangLandau wanglandau;
   options.add_option( "Elo",     "lower side of energy window",    ' ', &(wanglandau.Elo));
   options.add_option( "Ehi",     "lower side of energy window",    ' ', &(wanglandau.Ehi));
   options.add_option( "Ebin",    "width of energy bins",           ' ', &(wanglandau.Ebin));
   options.add_option( "numwin",  "number of windows",              ' ', &(wanglandau.NWindow));
   options.add_option( "numwalk", "number of walkers per window",   ' ', &(wanglandau.NWalkPerProcess));
   options.add_option( "overlap", "fractional overlap of windows",  ' ', &(wanglandau.fwinover));
   options.add_option( "nchunk",  "number of steps per iteration",  ' ', &(wanglandau.NChunk));
   options.add_option( "maxupdate","maximum number of iterations",  ' ', &(wanglandau.MaxUpdate));
   options.add_option( "dosinterp","linear interpolation of dos",   ' ', &(wanglandau.LinearInterp));
   options.add_option( "wleta",    "weighting between WL and ITTM", ' ', &(wanglandau.wleta));
   options.add_option( "wlgamma",  "starting value of WL parameter",' ', &(wanglandau.wlgamma_start));
   options.add_option( "Q",        "target convergence factor",     ' ', &(wanglandau.Qquit));
   options.add_option( "configout","output configurations to disk", ' ', &(wanglandau.output_configs));

   Meas_Diffusion measure;
   options.add_option( "diff_delay","delay in measuring diffusion", ' ', &(measure.delay));

   // Local options
   char lng_est_fn[512]; lng_est_fn[0]=0;
   options.add_option( "estdos",   "estimated dos file",            ' ', lng_est_fn);

   // Get parameters
   options.parse_command_line(argc,argv);
   if( options.get_value<bool>("help") ) return;
   bool verbose = options.get_value<bool>("verbose") && (iproc==0);

   // Re-initialize objects
   if(verbose) cout << __FILE__ << ":" << __LINE__ << " Reinitialize begun" << endl;
   hamilton.init(verbose);
   const int NGrid = hamilton.nspin;
   if(verbose) cout << __FILE__ << ":" << __LINE__ << " NGrid=" << NGrid << endl;
   //simulator.NStep = static_cast<int>( static_cast<float>(NGrid)*NStep_MCSS );

   // seed the random number geneator
   wanglandau.urng.seed( ParallelSeed(SeedFromClock()) );
   bool rng_output = false;
   bool rng_failed = RNGTestMoments(wanglandau.urng,rng_output,std::cout);
   if( rng_failed )
   {
      cout << "Problem detected with random number generator" << endl;
      return;
   }
   if(verbose) cout << __FILE__ << ":" << __LINE__ << " Random number generator created" << endl;

   // Construct a representation of the model
   // This includes the "microscopic" configuration sigma_i
   // and the macroscopic quantities like magnetization and energy
   if(verbose) cout << __FILE__ << ":" << __LINE__ << " Create one walker" << endl;
   typedef WL_Walker<HAMILTONIAN::Config,HAMILTONIAN::Observables> Walker;
   std::vector<Walker> walkerpool(1);
   walkerpool[0].sigma.resize(NGrid);
   hamilton.initial_ferro(walkerpool[0].sigma);
   hamilton.calc_observable(walkerpool[0].sigma,walkerpool[0].now);
   wanglandau.verbose = verbose;
   wanglandau.mp_window.pool = MPI_Struct::world();
   wanglandau.partition_windows();
   wanglandau.init_pool(walkerpool);
   std::vector<double> energy;
   std::vector<double> est_lng;
   ReadLngEst(std::string(lng_est_fn),energy,est_lng);
   if( energy.size()>0 )
   {
      TrimLng(wanglandau.Elo,wanglandau.Ehi,energy,est_lng);
      wanglandau.partition_windows(energy,est_lng);
      for(int iwalk=0; iwalk<walkerpool.size(); iwalk++)
         walkerpool[iwalk].set_fixed(energy,est_lng);
   }
   if(verbose) cout << __FILE__ << ":" << __LINE__ << " Done create one walker" << endl;

   measure.init(wanglandau.Elo,wanglandau.Ehi,wanglandau.Ebin);
   if(verbose) cout << __FILE__ << ":" << __LINE__ << " Measurement object initialized" << endl;

   wanglandau.DoConverge(hamilton,walkerpool,measure);

   options.write();
}

int main(int argc, char* argv[])
{

   int iproc = 0;
#  ifdef USE_MPI
   MPI_Init(&argc,&argv);
   MPI_Comm_rank(MPI_COMM_WORLD,&iproc);
#  endif
   if( iproc==0 )
   {
      std::cout << "cmdline:";
      for(int i=0; i<argc; i++) std::cout << " " << argv[i];
      std::cout << std::endl;
   }
   DoHeisenberg(argc,argv);
#  ifdef USE_MPI
   MPI_Finalize();
#  endif

}

<|endoftext|>


<commit_before>#ifndef STAN_MATH_HPP
#define STAN_MATH_HPP

/**
 * \defgroup prob_dists Probability Distributions
 */

/**
 * \ingroup prob_dists
 * \defgroup multivar_dists Multivariate Distributions
 * Distributions with Matrix inputs
 */
/**
 * \ingroup prob_dists
 * \defgroup univar_dists Univariate Distributions
 * Distributions with scalar, vector, or array input.
 */

#include <stan/math/rev.hpp>

#endif<commit_msg>Added newline to stan/math.hpp<commit_after>#ifndef STAN_MATH_HPP
#define STAN_MATH_HPP

/**
 * \defgroup prob_dists Probability Distributions
 */

/**
 * \ingroup prob_dists
 * \defgroup multivar_dists Multivariate Distributions
 * Distributions with Matrix inputs
 */
/**
 * \ingroup prob_dists
 * \defgroup univar_dists Univariate Distributions
 * Distributions with scalar, vector, or array input.
 */

#include <stan/math/rev.hpp>

#endif
<|endoftext|>


<commit_before>#ifndef STAN_MATH_HPP
#define STAN_MATH_HPP

#include <stan/math/rev/mat.hpp>

#endif
<commit_msg>Commit bad formatting to test<commit_after>#ifndef STAN_MATH_HPP
#define STAN_MATH_HPP

  #include <stan/math/rev/mat.hpp>

#endif
<|endoftext|>


<commit_before>/*  \brief Functionality referring to the Upload functionality of BSZ
 *
 *  \copyright 2019 Universitätsbibliothek Tübingen.  All rights reserved.
 *
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU Affero General Public License as
 *  published by the Free Software Foundation, either version 3 of the
 *  License, or (at your option) any later version.
 *
 *  This program 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 Affero General Public License for more details.
 *
 *  You should have received a copy of the GNU Affero General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

#include "BSZUpload.h"
#include "RegexMatcher.h"
#include "StringUtil.h"
#include "TimeUtil.h"
#include <memory>

namespace BSZUpload {

inline static void UpdateDeliveryTrackerEntryFromDbRow(const DbRow &row, DeliveryTracker::Entry * const entry) {
    if (row.empty())
        LOG_ERROR("Couldn't extract DeliveryTracker entry from empty DbRow");

    entry->url_ = row["url"];
    entry->delivered_at_ = SqlUtil::DatetimeToTimeT(row["delivered_at"]);
    entry->journal_name_ = row["journal_name"];
    entry->hash_ = row["hash"];
}

bool DeliveryTracker::urlAlreadyDelivered(const std::string &url, Entry * const entry) const {
    std::string truncated_url(url);
    truncateURL(&truncated_url);

    db_connection_->queryOrDie("SELECT url, delivered_at, journal_name, hash FROM delivered_marc_records WHERE url='"
                               + db_connection_->escapeString(truncated_url) + "'");
    auto result_set(db_connection_->getLastResultSet());
    if (result_set.empty())
        return false;

    const auto first_row(result_set.getNextRow());
    UpdateDeliveryTrackerEntryFromDbRow(first_row, entry);
    return true;
}

bool DeliveryTracker::hashAlreadyDelivered(const std::string &hash, Entry * const entry) const {
    db_connection_->queryOrDie("SELECT url, delivered_at, journal_name, hash FROM delivered_marc_records WHERE hash='"
                               + db_connection_->escapeString(hash) + "'");
    auto result_set(db_connection_->getLastResultSet());
    if (result_set.empty())
        return false;

    const auto first_row(result_set.getNextRow());
    UpdateDeliveryTrackerEntryFromDbRow(first_row, entry);
    return true;
}

size_t DeliveryTracker::listOutdatedJournals(const unsigned cutoff_days, std::unordered_map<std::string, time_t> * const outdated_journals) {
    db_connection_->queryOrDie("SELECT url, delivered_at, journal_name, hash FROM harvested_urls"
                               "WHERE last_harvest_time < DATEADD(day, -" + std::to_string(cutoff_days) + ", GETDATE())");
    auto result_set(db_connection_->getLastResultSet());
    Entry temp_entry;
    while (const DbRow row = result_set.getNextRow()) {
        UpdateDeliveryTrackerEntryFromDbRow(row, &temp_entry);

        auto match(outdated_journals->find(temp_entry.journal_name_));
        if (match != outdated_journals->end()) {
            // save the most recent timestamp
            if (match->second < temp_entry.delivered_at_)
               match->second = temp_entry.delivered_at_;
        } else
            (*outdated_journals)[temp_entry.journal_name_] = temp_entry.delivered_at_;
    }

    return outdated_journals->size();
}

time_t DeliveryTracker::getLastDeliveryTime(const std::string &journal_name) const {
    db_connection_->queryOrDie("SELECT delivered_at FROM delivered_marc_records WHERE journal_name='" +
                                db_connection_->escapeString(journal_name) + "' ORDER BY delivered_at DESC");
    auto result_set(db_connection_->getLastResultSet());
    if (result_set.empty())
        return TimeUtil::BAD_TIME_T;

    return SqlUtil::DatetimeToTimeT(result_set.getNextRow()["delivered_at"]);
}

} // namespace BSZUpload
<commit_msg>Null pointer check<commit_after>/*  \brief Functionality referring to the Upload functionality of BSZ
 *
 *  \copyright 2019 Universitätsbibliothek Tübingen.  All rights reserved.
 *
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU Affero General Public License as
 *  published by the Free Software Foundation, either version 3 of the
 *  License, or (at your option) any later version.
 *
 *  This program 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 Affero General Public License for more details.
 *
 *  You should have received a copy of the GNU Affero General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

#include "BSZUpload.h"
#include "RegexMatcher.h"
#include "StringUtil.h"
#include "TimeUtil.h"
#include <memory>

namespace BSZUpload {

inline static void UpdateDeliveryTrackerEntryFromDbRow(const DbRow &row, DeliveryTracker::Entry * const entry) {
    if (row.empty())
        LOG_ERROR("Couldn't extract DeliveryTracker entry from empty DbRow");

    entry->url_ = row["url"];
    entry->delivered_at_ = SqlUtil::DatetimeToTimeT(row["delivered_at"]);
    entry->journal_name_ = row["journal_name"];
    entry->hash_ = row["hash"];
}

bool DeliveryTracker::urlAlreadyDelivered(const std::string &url, Entry * const entry) const {
    std::string truncated_url(url);
    truncateURL(&truncated_url);

    db_connection_->queryOrDie("SELECT url, delivered_at, journal_name, hash FROM delivered_marc_records WHERE url='"
                               + db_connection_->escapeString(truncated_url) + "'");
    auto result_set(db_connection_->getLastResultSet());
    if (result_set.empty())
        return false;

    const auto first_row(result_set.getNextRow());
    if (entry != nullptr)
        UpdateDeliveryTrackerEntryFromDbRow(first_row, entry);
    return true;
}

bool DeliveryTracker::hashAlreadyDelivered(const std::string &hash, Entry * const entry) const {
    db_connection_->queryOrDie("SELECT url, delivered_at, journal_name, hash FROM delivered_marc_records WHERE hash='"
                               + db_connection_->escapeString(hash) + "'");
    auto result_set(db_connection_->getLastResultSet());
    if (result_set.empty())
        return false;

    const auto first_row(result_set.getNextRow());
    if (entry != nullptr)
        UpdateDeliveryTrackerEntryFromDbRow(first_row, entry);
    return true;
}

size_t DeliveryTracker::listOutdatedJournals(const unsigned cutoff_days, std::unordered_map<std::string, time_t> * const outdated_journals) {
    db_connection_->queryOrDie("SELECT url, delivered_at, journal_name, hash FROM harvested_urls"
                               "WHERE last_harvest_time < DATEADD(day, -" + std::to_string(cutoff_days) + ", GETDATE())");
    auto result_set(db_connection_->getLastResultSet());
    Entry temp_entry;
    while (const DbRow row = result_set.getNextRow()) {
        UpdateDeliveryTrackerEntryFromDbRow(row, &temp_entry);

        auto match(outdated_journals->find(temp_entry.journal_name_));
        if (match != outdated_journals->end()) {
            // save the most recent timestamp
            if (match->second < temp_entry.delivered_at_)
               match->second = temp_entry.delivered_at_;
        } else
            (*outdated_journals)[temp_entry.journal_name_] = temp_entry.delivered_at_;
    }

    return outdated_journals->size();
}

time_t DeliveryTracker::getLastDeliveryTime(const std::string &journal_name) const {
    db_connection_->queryOrDie("SELECT delivered_at FROM delivered_marc_records WHERE journal_name='" +
                                db_connection_->escapeString(journal_name) + "' ORDER BY delivered_at DESC");
    auto result_set(db_connection_->getLastResultSet());
    if (result_set.empty())
        return TimeUtil::BAD_TIME_T;

    return SqlUtil::DatetimeToTimeT(result_set.getNextRow()["delivered_at"]);
}

} // namespace BSZUpload
<|endoftext|>