<commit_before>#include <iostream>
#include <windows.h>
#include <TlHelp32.h>
#include <TCHAR.h>
#include <string>
#include <sstream>

//Here is where the hax begin

using namespace std;

//FUNCTIONS
DWORD GetModuleBaseAddress(DWORD dwProcessIdentifier, TCHAR *lpszModuleName)
{
    HANDLE hSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPMODULE, dwProcessIdentifier);
    DWORD dwModuleBaseAddress = 0;
    if (hSnapshot != INVALID_HANDLE_VALUE)
    {
        MODULEENTRY32 ModuleEntry32 = { 0 };
        ModuleEntry32.dwSize = sizeof(MODULEENTRY32);
        if (Module32First(hSnapshot, &ModuleEntry32))
        {
            do
            {
                if (_tcscmp(ModuleEntry32.szModule, lpszModuleName) == 0)
                {
                    dwModuleBaseAddress = (DWORD)ModuleEntry32.modBaseAddr;
                    break;
                }
            } while (Module32Next(hSnapshot, &ModuleEntry32));
        }
        CloseHandle(hSnapshot);
    }
    return dwModuleBaseAddress;
}

int Main() {
//Here is where the magic starts

}

<commit_msg>Update main.cpp<commit_after>#include <iostream>
#include <windows.h>
#include <TlHelp32.h>
#include <TCHAR.h>
#include <string>
#include <sstream>

//Here is where the hax begin

using namespace std;

//FUNCTIONS
DWORD GetModuleBaseAddress(DWORD dwProcessIdentifier, TCHAR *lpszModuleName)
{
    HANDLE hSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPMODULE, dwProcessIdentifier);
    DWORD dwModuleBaseAddress = 0;
    if (hSnapshot != INVALID_HANDLE_VALUE)
    {
        MODULEENTRY32 ModuleEntry32 = { 0 };
        ModuleEntry32.dwSize = sizeof(MODULEENTRY32);
        if (Module32First(hSnapshot, &ModuleEntry32))
        {
            do
            {
                if (_tcscmp(ModuleEntry32.szModule, lpszModuleName) == 0)
                {
                    dwModuleBaseAddress = (DWORD)ModuleEntry32.modBaseAddr;
                    break;
                }
            } while (Module32Next(hSnapshot, &ModuleEntry32));
        }
        CloseHandle(hSnapshot);
    }
    return dwModuleBaseAddress;
}

//Costum function for you guys to sleep a thread
	int sleepthread(int amountoftime) {
		SetConsoleTitle("Thread is sleeping for " + amtTime + " ;*");
		Sleep(amountoftime);
	}

int Main() {
//Here is where the magic starts
HWND hWnd = FindWindow(0, "ROBLOX"); //Finding RBLX window this is a low quality process if you know how to code and use this i recommened you to change this
std::cout << "Waiting for Roblox...";
while (hWnd == 0) { // Waiting until found
        Sleep(250);
        hWnd = FindWindow(0, "ROBLOX");

    }

    system("cls");//making this better later
        //Definition of pId
        DWORD pId;
    //Get process id
    GetWindowThreadProcessId(hWnd, &pId);

    //Here is where we start getting the modulebase
     DWORD RBLXBASEAddr = GetModuleBaseAddress(pId, "RobloxPlayerBeta.exe"); // Getting base address of GD
     std::cout << "Base Address: " << hex << GetModuleBaseAddress(;

  return 0;

}

<|endoftext|>


<commit_before>// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.

#include "searchable_feed_view.h"
#include "forcecommitcontext.h"
#include "operationdonecontext.h"
#include "removedonecontext.h"
#include <vespa/searchcore/proton/feedoperation/compact_lid_space_operation.h>
#include <vespa/vespalib/util/isequencedtaskexecutor.h>
#include <vespa/document/fieldvalue/document.h>

#include <vespa/log/log.h>
LOG_SETUP(".proton.server.searchable_feed_view");

using document::BucketId;
using document::Document;
using document::DocumentId;
using document::DocumentTypeRepo;
using document::DocumentUpdate;
using search::index::Schema;
using storage::spi::BucketInfoResult;
using storage::spi::Timestamp;
using vespalib::makeLambdaTask;

namespace proton {

SearchableFeedView::Context::Context(const IIndexWriter::SP &indexWriter)
    : _indexWriter(indexWriter)
{}

SearchableFeedView::Context::~Context() = default;

SearchableFeedView::SearchableFeedView(StoreOnlyFeedView::Context storeOnlyCtx, const PersistentParams &params,
                                       const FastAccessFeedView::Context &fastUpdateCtx, Context ctx)
    : Parent(std::move(storeOnlyCtx), params, fastUpdateCtx),
      _indexWriter(ctx._indexWriter),
      _hasIndexedFields(_schema->getNumIndexFields() > 0)
{ }

SearchableFeedView::~SearchableFeedView() = default;

void
SearchableFeedView::putIndexedFields(SerialNum serialNum, search::DocumentIdT lid, const DocumentSP &newDoc,
                                     OnOperationDoneType onWriteDone)
{
    if (!hasIndexedFields()) {
        return;
    }
    _writeService.index().execute(
            makeLambdaTask([this, serialNum, lid, newDoc, onWriteDone] {
                performIndexPut(serialNum, lid, newDoc, onWriteDone);
            }));
}

void
SearchableFeedView::performIndexPut(SerialNum serialNum, search::DocumentIdT lid, const Document &doc, OnOperationDoneType onWriteDone)
{
    (void) onWriteDone;
    assert(_writeService.index().isCurrentThread());
    VLOG(getDebugLevel(lid, doc.getId()),
         "database(%s): performIndexPut: serialNum(%" PRIu64 "), docId(%s), lid(%d)",
         _params._docTypeName.toString().c_str(), serialNum, doc.getId().toString().c_str(), lid);

    _indexWriter->put(serialNum, doc, lid, onWriteDone);
}

void
SearchableFeedView::performIndexPut(SerialNum serialNum, search::DocumentIdT lid, const DocumentSP &doc, OnOperationDoneType onWriteDone)
{
    performIndexPut(serialNum, lid, *doc, onWriteDone);
}

void
SearchableFeedView::performIndexPut(SerialNum serialNum, search::DocumentIdT lid, FutureDoc futureDoc, OnOperationDoneType onWriteDone)
{
    const auto &doc = futureDoc.get();
    if (doc) {
        performIndexPut(serialNum, lid, *doc, onWriteDone);
    }
}

void
SearchableFeedView::heartBeatIndexedFields(SerialNum serialNum, DoneCallback onDone)
{
    _writeService.index().execute(makeLambdaTask([this, serialNum, onDone] {
        (void) onDone;
        performIndexHeartBeat(serialNum);
    }));
}

void
SearchableFeedView::performIndexHeartBeat(SerialNum serialNum)
{
    _indexWriter->heartBeat(serialNum);
}

void
SearchableFeedView::updateIndexedFields(SerialNum serialNum, search::DocumentIdT lid, FutureDoc futureDoc, OnOperationDoneType onWriteDone)
{
    _writeService.index().execute(
            makeLambdaTask([serialNum, lid, futureDoc = std::move(futureDoc),
                            onWriteDone = std::move(onWriteDone), this]() mutable {
                performIndexPut(serialNum, lid, std::move(futureDoc), std::move(onWriteDone));
            }));
}

void
SearchableFeedView::removeIndexedFields(SerialNum serialNum, search::DocumentIdT lid, OnRemoveDoneType onWriteDone)
{
    if (!hasIndexedFields()) {
        return;
    }
    _writeService.index().execute(
            makeLambdaTask([this, serialNum, lid, onWriteDone]() {
                performIndexRemove(serialNum, lid, onWriteDone);
            }));
}

void
SearchableFeedView::performIndexRemove(SerialNum serialNum, search::DocumentIdT lid, OnRemoveDoneType onWriteDone)
{
    (void) onWriteDone;
    assert(_writeService.index().isCurrentThread());
    VLOG(getDebugLevel(lid, nullptr),
        "database(%s): performIndexRemove: serialNum(%" PRIu64 "), lid(%d)",
         _params._docTypeName.toString().c_str(), serialNum, lid);

    _indexWriter->remove(serialNum, lid);
}

void
SearchableFeedView::performIndexRemove(SerialNum serialNum, const LidVector &lidsToRemove, OnWriteDoneType onWriteDone)
{
    (void) onWriteDone;
    assert(_writeService.index().isCurrentThread());
    for (const auto lid : lidsToRemove) {
        VLOG(getDebugLevel(lid, nullptr),
             "database(%s): performIndexRemove: serialNum(%" PRIu64 "), lid(%d)",
             _params._docTypeName.toString().c_str(), serialNum, lid);
    }

    _indexWriter->removeDocs(serialNum, lidsToRemove);
}

void
SearchableFeedView::removeIndexedFields(SerialNum serialNum, const LidVector &lidsToRemove,
                                        OnWriteDoneType onWriteDone)
{
    if (!hasIndexedFields())
        return;

    _writeService.index().execute(
            makeLambdaTask([this, serialNum, lidsToRemove, onWriteDone]() {
                performIndexRemove(serialNum, lidsToRemove, onWriteDone);
            }));
}

void
SearchableFeedView::internalDeleteBucket(const DeleteBucketOperation &delOp, DoneCallback onDone)
{
    Parent::internalDeleteBucket(delOp, onDone);
}

void
SearchableFeedView::performIndexForceCommit(SerialNum serialNum, OnForceCommitDoneType onCommitDone)
{
    assert(_writeService.index().isCurrentThread());
    _indexWriter->commit(serialNum, onCommitDone);
}

void
SearchableFeedView::handleCompactLidSpace(const CompactLidSpaceOperation &op, DoneCallback onDone)
{
    Parent::handleCompactLidSpace(op, onDone);
    vespalib::Gate gate;
    _writeService.index().execute(
            makeLambdaTask([this, &op, &gate]() {
                _indexWriter->compactLidSpace(op.getSerialNum(), op.getLidLimit());
                gate.countDown();
            }));
    gate.await();
}

void
SearchableFeedView::internalForceCommit(const CommitParam & param, OnForceCommitDoneType onCommitDone)
{
    Parent::internalForceCommit(param, onCommitDone);
    _writeService.index().execute(
            makeLambdaTask([this, serialNum=param.lastSerialNum(), onCommitDone]() {
                performIndexForceCommit(serialNum, onCommitDone);
            }));
    _writeService.index().wakeup();
}

} // namespace proton
<commit_msg>Remove noop std::move.<commit_after>// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.

#include "searchable_feed_view.h"
#include "forcecommitcontext.h"
#include "operationdonecontext.h"
#include "removedonecontext.h"
#include <vespa/searchcore/proton/feedoperation/compact_lid_space_operation.h>
#include <vespa/vespalib/util/isequencedtaskexecutor.h>
#include <vespa/document/fieldvalue/document.h>

#include <vespa/log/log.h>
LOG_SETUP(".proton.server.searchable_feed_view");

using document::BucketId;
using document::Document;
using document::DocumentId;
using document::DocumentTypeRepo;
using document::DocumentUpdate;
using search::index::Schema;
using storage::spi::BucketInfoResult;
using storage::spi::Timestamp;
using vespalib::makeLambdaTask;

namespace proton {

SearchableFeedView::Context::Context(const IIndexWriter::SP &indexWriter)
    : _indexWriter(indexWriter)
{}

SearchableFeedView::Context::~Context() = default;

SearchableFeedView::SearchableFeedView(StoreOnlyFeedView::Context storeOnlyCtx, const PersistentParams &params,
                                       const FastAccessFeedView::Context &fastUpdateCtx, Context ctx)
    : Parent(std::move(storeOnlyCtx), params, fastUpdateCtx),
      _indexWriter(ctx._indexWriter),
      _hasIndexedFields(_schema->getNumIndexFields() > 0)
{ }

SearchableFeedView::~SearchableFeedView() = default;

void
SearchableFeedView::putIndexedFields(SerialNum serialNum, search::DocumentIdT lid, const DocumentSP &newDoc,
                                     OnOperationDoneType onWriteDone)
{
    if (!hasIndexedFields()) {
        return;
    }
    _writeService.index().execute(
            makeLambdaTask([this, serialNum, lid, newDoc, onWriteDone] {
                performIndexPut(serialNum, lid, newDoc, onWriteDone);
            }));
}

void
SearchableFeedView::performIndexPut(SerialNum serialNum, search::DocumentIdT lid, const Document &doc, OnOperationDoneType onWriteDone)
{
    (void) onWriteDone;
    assert(_writeService.index().isCurrentThread());
    VLOG(getDebugLevel(lid, doc.getId()),
         "database(%s): performIndexPut: serialNum(%" PRIu64 "), docId(%s), lid(%d)",
         _params._docTypeName.toString().c_str(), serialNum, doc.getId().toString().c_str(), lid);

    _indexWriter->put(serialNum, doc, lid, onWriteDone);
}

void
SearchableFeedView::performIndexPut(SerialNum serialNum, search::DocumentIdT lid, const DocumentSP &doc, OnOperationDoneType onWriteDone)
{
    performIndexPut(serialNum, lid, *doc, onWriteDone);
}

void
SearchableFeedView::performIndexPut(SerialNum serialNum, search::DocumentIdT lid, FutureDoc futureDoc, OnOperationDoneType onWriteDone)
{
    const auto &doc = futureDoc.get();
    if (doc) {
        performIndexPut(serialNum, lid, *doc, onWriteDone);
    }
}

void
SearchableFeedView::heartBeatIndexedFields(SerialNum serialNum, DoneCallback onDone)
{
    _writeService.index().execute(makeLambdaTask([this, serialNum, onDone] {
        (void) onDone;
        performIndexHeartBeat(serialNum);
    }));
}

void
SearchableFeedView::performIndexHeartBeat(SerialNum serialNum)
{
    _indexWriter->heartBeat(serialNum);
}

void
SearchableFeedView::updateIndexedFields(SerialNum serialNum, search::DocumentIdT lid, FutureDoc futureDoc, OnOperationDoneType onWriteDone)
{
    _writeService.index().execute(
            makeLambdaTask([serialNum, lid, futureDoc = std::move(futureDoc),
                            onWriteDone, this]() mutable {
                performIndexPut(serialNum, lid, std::move(futureDoc), onWriteDone);
            }));
}

void
SearchableFeedView::removeIndexedFields(SerialNum serialNum, search::DocumentIdT lid, OnRemoveDoneType onWriteDone)
{
    if (!hasIndexedFields()) {
        return;
    }
    _writeService.index().execute(
            makeLambdaTask([this, serialNum, lid, onWriteDone]() {
                performIndexRemove(serialNum, lid, onWriteDone);
            }));
}

void
SearchableFeedView::performIndexRemove(SerialNum serialNum, search::DocumentIdT lid, OnRemoveDoneType onWriteDone)
{
    (void) onWriteDone;
    assert(_writeService.index().isCurrentThread());
    VLOG(getDebugLevel(lid, nullptr),
        "database(%s): performIndexRemove: serialNum(%" PRIu64 "), lid(%d)",
         _params._docTypeName.toString().c_str(), serialNum, lid);

    _indexWriter->remove(serialNum, lid);
}

void
SearchableFeedView::performIndexRemove(SerialNum serialNum, const LidVector &lidsToRemove, OnWriteDoneType onWriteDone)
{
    (void) onWriteDone;
    assert(_writeService.index().isCurrentThread());
    for (const auto lid : lidsToRemove) {
        VLOG(getDebugLevel(lid, nullptr),
             "database(%s): performIndexRemove: serialNum(%" PRIu64 "), lid(%d)",
             _params._docTypeName.toString().c_str(), serialNum, lid);
    }

    _indexWriter->removeDocs(serialNum, lidsToRemove);
}

void
SearchableFeedView::removeIndexedFields(SerialNum serialNum, const LidVector &lidsToRemove,
                                        OnWriteDoneType onWriteDone)
{
    if (!hasIndexedFields())
        return;

    _writeService.index().execute(
            makeLambdaTask([this, serialNum, lidsToRemove, onWriteDone]() {
                performIndexRemove(serialNum, lidsToRemove, onWriteDone);
            }));
}

void
SearchableFeedView::internalDeleteBucket(const DeleteBucketOperation &delOp, DoneCallback onDone)
{
    Parent::internalDeleteBucket(delOp, onDone);
}

void
SearchableFeedView::performIndexForceCommit(SerialNum serialNum, OnForceCommitDoneType onCommitDone)
{
    assert(_writeService.index().isCurrentThread());
    _indexWriter->commit(serialNum, onCommitDone);
}

void
SearchableFeedView::handleCompactLidSpace(const CompactLidSpaceOperation &op, DoneCallback onDone)
{
    Parent::handleCompactLidSpace(op, onDone);
    vespalib::Gate gate;
    _writeService.index().execute(
            makeLambdaTask([this, &op, &gate]() {
                _indexWriter->compactLidSpace(op.getSerialNum(), op.getLidLimit());
                gate.countDown();
            }));
    gate.await();
}

void
SearchableFeedView::internalForceCommit(const CommitParam & param, OnForceCommitDoneType onCommitDone)
{
    Parent::internalForceCommit(param, onCommitDone);
    _writeService.index().execute(
            makeLambdaTask([this, serialNum=param.lastSerialNum(), onCommitDone]() {
                performIndexForceCommit(serialNum, onCommitDone);
            }));
    _writeService.index().wakeup();
}

} // namespace proton
<|endoftext|>


<commit_before>#include <lua.hpp>

#include "brotli/dec/decode.h"
#include "brotli/enc/encode.h"
#include "brotli/enc/streams.h"

class MemReader : public brotli::BrotliIn
{
public:
  MemReader(const void *data, size_t len) : data_(data), len_(len) { }
  virtual ~MemReader() { }

  virtual const void* Read(size_t n, size_t* nread)
  {
    const void *d = data_;
    *nread = len_;
    data_ = NULL;
    len_ = 0;
    return d;
  }
private:
  const void *data_;
  size_t len_;
};

class LuaWriter : public brotli::BrotliOut
{
public:
  LuaWriter(luaL_Buffer *b_) : b(b_) { }
  virtual ~LuaWriter() { }

  virtual bool Write(const void *buf, size_t n)
  {
    luaL_addlstring(b, (const char *)buf, n);
    return true;
  }
private:
  luaL_Buffer *b;
};

int lb_compress(lua_State *L)
{
  size_t in_len;
  const char *in = luaL_checklstring(L, 1, &in_len);

  luaL_Buffer b;
#if LUA_VERSION_NUM >= 502
  luaL_buffinitsize(L, &b, in_len / 2);
#else
  luaL_buffinit(L, &b);
#endif

  brotli::BrotliParams params;
  MemReader input(in, in_len);
  LuaWriter output(&b);
  if (!brotli::BrotliCompress(params, &input, &output))
    return luaL_error(L, "compression failed");

  luaL_pushresult(&b);

  return 1;
}

int BrotliLuaOutputFunction(void *data, const uint8_t *buf, size_t count)
{
  luaL_Buffer *b = (luaL_Buffer *)data;
  luaL_addlstring(b, (const char *)buf, count);
  return (int)count;
}

BrotliOutput BrotliInitLuaOutput(luaL_Buffer *b)
{
  BrotliOutput output;
  output.cb_ = &BrotliLuaOutputFunction;
  output.data_ = b;
  return output;
}

int lb_decompress(lua_State *L)
{
  size_t in_len;
  const char *in = luaL_checklstring(L, 1, &in_len);

  luaL_Buffer b;
#if LUA_VERSION_NUM >= 502
  luaL_buffinitsize(L, &b, in_len);
#else
  luaL_buffinit(L, &b);
#endif

  BrotliMemInput mem_input;
  BrotliInput input = BrotliInitMemInput((const uint8_t *)in, in_len, &mem_input);
  BrotliOutput output = BrotliInitLuaOutput(&b);
  if (!BrotliDecompress(input, output))
    return luaL_error(L, "corrupt input");

  luaL_pushresult(&b);

  return 1;
}

extern "C"
{

static const luaL_Reg export_functions[] = {
  { "compress",   lb_compress   },
  { "decompress", lb_decompress },
  { NULL,         NULL          },
};

LUALIB_API int luaopen_brotli(lua_State *L)
{
#if LUA_VERSION_NUM >= 502
  luaL_newlib(L, export_functions);
#else
  lua_newtable(L);
  luaL_register(L, NULL, export_functions);
#endif
  return 1;
}

}
<commit_msg>fix read buffer bug<commit_after>#include <lua.hpp>

#include "brotli/dec/decode.h"
#include "brotli/enc/encode.h"
#include "brotli/enc/streams.h"

class MemReader : public brotli::BrotliIn
{
public:
  MemReader(const void *data, size_t len) : data_((const uint8_t *)data), len_(len) { }
  virtual ~MemReader() { }

  virtual const void* Read(size_t n, size_t* nread)
  {
    const void *d = data_;
    if (n >= len_)
    {
      *nread = len_;
      data_ = NULL;
      len_ = 0;
    }
    else
    {
      *nread = n;
      data_ += n;
      len_ -= n;
    }
    return d;
  }
private:
  const uint8_t *data_;
  size_t len_;
};

class LuaWriter : public brotli::BrotliOut
{
public:
  LuaWriter(luaL_Buffer *b_) : b(b_) { }
  virtual ~LuaWriter() { }

  virtual bool Write(const void *buf, size_t n)
  {
    luaL_addlstring(b, (const char *)buf, n);
    return true;
  }
private:
  luaL_Buffer *b;
};

static int lb_compress(lua_State *L)
{
  size_t in_len;
  const char *in = luaL_checklstring(L, 1, &in_len);

  luaL_Buffer b;
#if LUA_VERSION_NUM >= 502
  luaL_buffinitsize(L, &b, in_len / 2);
#else
  luaL_buffinit(L, &b);
#endif

  brotli::BrotliParams params;
  MemReader input(in, in_len);
  LuaWriter output(&b);
  if (!brotli::BrotliCompress(params, &input, &output))
    return luaL_error(L, "compression failed");

  luaL_pushresult(&b);

  return 1;
}

static int BrotliLuaOutputFunction(void *data, const uint8_t *buf, size_t count)
{
  luaL_Buffer *b = (luaL_Buffer *)data;
  luaL_addlstring(b, (const char *)buf, count);
  return (int)count;
}

static BrotliOutput BrotliInitLuaOutput(luaL_Buffer *b)
{
  BrotliOutput output;
  output.cb_ = &BrotliLuaOutputFunction;
  output.data_ = b;
  return output;
}

static int lb_decompress(lua_State *L)
{
  size_t in_len;
  const char *in = luaL_checklstring(L, 1, &in_len);

  luaL_Buffer b;
#if LUA_VERSION_NUM >= 502
  luaL_buffinitsize(L, &b, in_len);
#else
  luaL_buffinit(L, &b);
#endif

  BrotliMemInput mem_input;
  BrotliInput input = BrotliInitMemInput((const uint8_t *)in, in_len, &mem_input);
  BrotliOutput output = BrotliInitLuaOutput(&b);
  if (!BrotliDecompress(input, output))
    return luaL_error(L, "corrupt input");

  luaL_pushresult(&b);

  return 1;
}

extern "C"
{

static const luaL_Reg export_functions[] = {
  { "compress",   lb_compress   },
  { "decompress", lb_decompress },
  { NULL,         NULL          },
};

LUALIB_API int luaopen_brotli(lua_State *L)
{
#if LUA_VERSION_NUM >= 502
  luaL_newlib(L, export_functions);
#else
  lua_newtable(L);
  luaL_register(L, NULL, export_functions);
#endif
  return 1;
}

}
<|endoftext|>


<commit_before>/**
 * @file gaussian_kernel.hpp
 * @author Wei Guan
 * @author James Cline
 * @author Ryan Curtin
 *
 * Implementation of the Gaussian kernel (GaussianKernel).
 */
#ifndef __MLPACK_CORE_KERNELS_GAUSSIAN_KERNEL_HPP
#define __MLPACK_CORE_KERNELS_GAUSSIAN_KERNEL_HPP

#include <mlpack/core.hpp>
#include <mlpack/core/metrics/lmetric.hpp>

namespace mlpack {
namespace kernel {

/**
 * The standard Gaussian kernel.  Given two vectors @f$ x @f$, @f$ y @f$, and a
 * bandwidth @f$ \mu @f$ (set in the constructor),
 *
 * @f[
 * K(x, y) = \exp(-\frac{|| x - y ||^2}{2 \mu^2}).
 * @f]
 *
 * The implementation is all in the header file because it is so simple.
 */
class GaussianKernel
{
 public:
  /**
   * Default constructor; sets bandwidth to 1.0.
   */
  GaussianKernel() : bandwidth(1.0), gamma(-0.5)
  { }

  /**
   * Construct the Gaussian kernel with a custom bandwidth.
   *
   * @param bandwidth The bandwidth of the kernel (@f$\mu@f$).
   */
  GaussianKernel(double bandwidth) :
      bandwidth(bandwidth),
      gamma(-0.5 * pow(bandwidth, -2.0))
  { }

  /**
   * Evaluation of the Gaussian kernel.  This could be generalized to use any
   * distance metric, not the Euclidean distance, but for now, the Euclidean
   * distance is used.
   *
   * @tparam VecType Type of vector (likely arma::vec or arma::spvec).
   * @param a First vector.
   * @param b Second vector.
   * @return K(a, b) using the bandwidth (@f$\mu@f$) specified in the
   *   constructor.
   */
  template<typename VecType>
  double Evaluate(const VecType& a, const VecType& b) const
  {
    // The precalculation of gamma saves us a little computation time.
    return exp(gamma * metric::SquaredEuclideanDistance::Evaluate(a, b));
  }

  /**
   * Evaluation of the Gaussian kernel using a double precision argument.
   *
   * @param t double value.
   * @return K(t) using the bandwidth (@f$\mu@f$) specified in the
   *     constructor.
   */
  double Evaluate(double t) const
  {
    // The precalculation of gamma saves us a little computation time.
    return exp(gamma * t * t);
  }
  /**
   * Obtain the normalization constant of the Gaussian kernel.
   *
   * @param dimension
   * @return the normalization constant
   */
  double Normalizer(size_t dimension)
  {
    return pow(sqrt(2.0 * M_PI) * bandwidth, (double) dimension);
  }
  /**
   * Obtain a convolution integral of the Gaussian kernel.
   *
   * @param a, first vector
   * @param b, second vector
   * @return the convolution integral
   */
  template<typename VecType>
  double ConvolutionIntegral(const VecType& a, const VecType& b)
  {
    return Evaluate(sqrt(metric::SquaredEuclideanDistance::Evaluate(a, b) / 2.0)) /
      (Normalizer(a.n_rows) * pow(2.0, (double) a.n_rows / 2.0));
  }

  //! Get the bandwidth.
  double Bandwidth() const { return bandwidth; }
  //! Modify the bandwidth.  This takes an argument because we must update the
  //! precalculated constant (gamma).
  void Bandwidth(const double bandwidth)
  {
    this->bandwidth = bandwidth;
    this->gamma = -0.5 * pow(bandwidth, -2.0);
  }

  //! Get the precalculated constant.
  double Gamma() const { return gamma; }

 private:
  //! Kernel bandwidth.
  double bandwidth;

  //! Precalculated constant depending on the bandwidth;
  //! @f$ \gamma = -\frac{1}{2 \mu^2} @f$.
  double gamma;
};

class GaussianStaticKernel
{
 public:
  GaussianStaticKernel() { }

  template<typename VecType>
  static double Evaluate(const VecType& a, const VecType& b)
  {
    return exp(-0.5 * metric::SquaredEuclideanDistance::Evaluate(a, b));
  }
};

}; // namespace kernel
}; // namespace mlpack

#endif
<commit_msg>Remove static Gaussian kernel hack.<commit_after>/**
 * @file gaussian_kernel.hpp
 * @author Wei Guan
 * @author James Cline
 * @author Ryan Curtin
 *
 * Implementation of the Gaussian kernel (GaussianKernel).
 */
#ifndef __MLPACK_CORE_KERNELS_GAUSSIAN_KERNEL_HPP
#define __MLPACK_CORE_KERNELS_GAUSSIAN_KERNEL_HPP

#include <mlpack/core.hpp>
#include <mlpack/core/metrics/lmetric.hpp>

namespace mlpack {
namespace kernel {

/**
 * The standard Gaussian kernel.  Given two vectors @f$ x @f$, @f$ y @f$, and a
 * bandwidth @f$ \mu @f$ (set in the constructor),
 *
 * @f[
 * K(x, y) = \exp(-\frac{|| x - y ||^2}{2 \mu^2}).
 * @f]
 *
 * The implementation is all in the header file because it is so simple.
 */
class GaussianKernel
{
 public:
  /**
   * Default constructor; sets bandwidth to 1.0.
   */
  GaussianKernel() : bandwidth(1.0), gamma(-0.5)
  { }

  /**
   * Construct the Gaussian kernel with a custom bandwidth.
   *
   * @param bandwidth The bandwidth of the kernel (@f$\mu@f$).
   */
  GaussianKernel(double bandwidth) :
      bandwidth(bandwidth),
      gamma(-0.5 * pow(bandwidth, -2.0))
  { }

  /**
   * Evaluation of the Gaussian kernel.  This could be generalized to use any
   * distance metric, not the Euclidean distance, but for now, the Euclidean
   * distance is used.
   *
   * @tparam VecType Type of vector (likely arma::vec or arma::spvec).
   * @param a First vector.
   * @param b Second vector.
   * @return K(a, b) using the bandwidth (@f$\mu@f$) specified in the
   *   constructor.
   */
  template<typename VecType>
  double Evaluate(const VecType& a, const VecType& b) const
  {
    // The precalculation of gamma saves us a little computation time.
    return exp(gamma * metric::SquaredEuclideanDistance::Evaluate(a, b));
  }

  /**
   * Evaluation of the Gaussian kernel using a double precision argument.
   *
   * @param t double value.
   * @return K(t) using the bandwidth (@f$\mu@f$) specified in the
   *     constructor.
   */
  double Evaluate(double t) const
  {
    // The precalculation of gamma saves us a little computation time.
    return exp(gamma * t * t);
  }
  /**
   * Obtain the normalization constant of the Gaussian kernel.
   *
   * @param dimension
   * @return the normalization constant
   */
  double Normalizer(size_t dimension)
  {
    return pow(sqrt(2.0 * M_PI) * bandwidth, (double) dimension);
  }
  /**
   * Obtain a convolution integral of the Gaussian kernel.
   *
   * @param a, first vector
   * @param b, second vector
   * @return the convolution integral
   */
  template<typename VecType>
  double ConvolutionIntegral(const VecType& a, const VecType& b)
  {
    return Evaluate(sqrt(metric::SquaredEuclideanDistance::Evaluate(a, b) / 2.0)) /
      (Normalizer(a.n_rows) * pow(2.0, (double) a.n_rows / 2.0));
  }

  //! Get the bandwidth.
  double Bandwidth() const { return bandwidth; }

  //! Modify the bandwidth.  This takes an argument because we must update the
  //! precalculated constant (gamma).
  void Bandwidth(const double bandwidth)
  {
    this->bandwidth = bandwidth;
    this->gamma = -0.5 * pow(bandwidth, -2.0);
  }

  //! Get the precalculated constant.
  double Gamma() const { return gamma; }

 private:
  //! Kernel bandwidth.
  double bandwidth;

  //! Precalculated constant depending on the bandwidth;
  //! @f$ \gamma = -\frac{1}{2 \mu^2} @f$.
  double gamma;
};

}; // namespace kernel
}; // namespace mlpack

#endif
<|endoftext|>


<commit_before>//=======================================================================
// Copyright Baptiste Wicht 2011.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
//  http://www.boost.org/LICENSE_1_0.txt)
//=======================================================================

#include "assert.hpp"
#include "Variable.hpp"
#include "FunctionContext.hpp"
#include "Type.hpp"
#include "iterators.hpp"

#include "mtac/CommonSubexpressionElimination.hpp"
#include "mtac/Utils.hpp"

using namespace eddic;

typedef mtac::CommonSubexpressionElimination::ProblemDomain ProblemDomain;

std::ostream& mtac::operator<<(std::ostream& stream, Expression& /*expression*/){
    return stream << "Expression {expression = {}}";
}

inline bool are_equivalent(std::shared_ptr<mtac::Quadruple> first, std::shared_ptr<mtac::Quadruple> second){
    return first->op == second->op && *first->arg1 == *second->arg1 && *first->arg2 == *second->arg2;
}

ProblemDomain mtac::CommonSubexpressionElimination::meet(ProblemDomain& in, ProblemDomain& out){
    ASSERT(!in.top() || !out.top(), "At least one lattice should not be a top element");

    if(in.top()){
        return out;
    } else if(out.top()){
        return in;
    } else {
        typename ProblemDomain::Values values;

        for(auto& in_value : in.values()){
            for(auto& out_value : out.values()){
                if(are_equivalent(in_value.expression, out_value.expression)){
                    values.push_back(in_value);
                }
            }
        }

        ProblemDomain result(values);
        return result;
    }
}

ProblemDomain mtac::CommonSubexpressionElimination::transfer(std::shared_ptr<mtac::BasicBlock> basic_block, mtac::Statement& statement, ProblemDomain& in){
    auto out = in;

    if(auto* ptr = boost::get<std::shared_ptr<mtac::Quadruple>>(&statement)){
        auto op = (*ptr)->op;
        if(mtac::erase_result(op)){
            auto it = iterate(out.values());

            while(it.has_next()){
                auto& expression = (*it).expression;

                if(expression->arg1){
                    if(auto* var_ptr = boost::get<std::shared_ptr<Variable>>(&*expression->arg1)){
                        if(*var_ptr == (*ptr)->result){
                            it.erase();
                            continue;
                        }
                    }
                }

                if(expression->arg2){
                    if(auto* var_ptr = boost::get<std::shared_ptr<Variable>>(&*expression->arg2)){
                        if(*var_ptr == (*ptr)->result){
                            it.erase();
                            continue;
                        }
                    }
                }

                ++it;
            }
        }

        if(mtac::is_expression((*ptr)->op)){
            bool exists = false;
            for(auto& expression : out.values()){
                if(are_equivalent(*ptr, expression.expression)){
                    exists = true;
                    break;
                }
            }

            if(!exists){
                Expression expression;
                expression.expression = *ptr;
                expression.source = basic_block;

                out.values().push_back(expression);
            }
        }
    }

    return out;
}

ProblemDomain mtac::CommonSubexpressionElimination::Boundary(std::shared_ptr<mtac::Function> /*function*/){
    return default_element();
}

ProblemDomain mtac::CommonSubexpressionElimination::Init(std::shared_ptr<mtac::Function> function){
    if(init){
        ProblemDomain result(*init);
        return result;
    }

    typename ProblemDomain::Values values;

    for(auto& block : function->getBasicBlocks()){
        for(auto& statement : block->statements){
            if(auto* ptr = boost::get<std::shared_ptr<mtac::Quadruple>>(&statement)){
                if(mtac::is_expression((*ptr)->op)){
                    bool exists = false;
                    for(auto& expression : values){
                        if(are_equivalent(*ptr, expression.expression)){
                            exists = true;
                            break;
                        }
                    }

                    if(!exists){
                        Expression expression;
                        expression.expression = *ptr;
                        expression.source = block;

                        values.push_back(expression);
                    }
                }
            }
        }
    }

    init = values;

    ProblemDomain result(values);
    return result;
}

bool mtac::CommonSubexpressionElimination::optimize(mtac::Statement& statement, std::shared_ptr<mtac::DataFlowResults<ProblemDomain>>& global_results){
    auto& results = global_results->IN_S[statement];

    bool changes = false;

    if(auto* ptr = boost::get<std::shared_ptr<mtac::Quadruple>>(&statement)){
        if(mtac::is_expression((*ptr)->op)){
            for(auto& expression : results.values()){
                if(are_equivalent(expression.expression, *ptr)){
                    auto source_statement = expression.expression;

                    mtac::Operator assign_op;
                    if((*ptr)->op >= mtac::Operator::ADD && (*ptr)->op <= mtac::Operator::MOD){
                        assign_op = mtac::Operator::ASSIGN;
                    } else if((*ptr)->op >= mtac::Operator::FADD && (*ptr)->op <= mtac::Operator::FDIV){
                        assign_op = mtac::Operator::FASSIGN;
                    }

                    if(optimized.find(source_statement->result) == optimized.end()){
                        std::shared_ptr<Variable> temp;
                        if((*ptr)->op >= mtac::Operator::ADD && (*ptr)->op <= mtac::Operator::MOD){
                            temp = expression.source->context->new_temporary(INT);
                        } else if((*ptr)->op >= mtac::Operator::FADD && (*ptr)->op <= mtac::Operator::FDIV){
                            temp = expression.source->context->new_temporary(FLOAT);
                        }

                        auto it = expression.source->statements.begin();
                        auto end = expression.source->statements.end();

                        while(it != end){
                            if(boost::get<std::shared_ptr<Quadruple>>(&*it)){
                                auto target = boost::get<std::shared_ptr<Quadruple>>(*it);
                                if(target == source_statement){
                                    auto quadruple = std::make_shared<mtac::Quadruple>(source_statement->result, temp, assign_op);

                                    expression.source->statements.insert(it+1, quadruple);

                                    break;
                                }
                            }

                            ++it;
                        }

                        source_statement->result = temp;

                        (*ptr)->op = assign_op;
                        (*ptr)->arg1 = temp;

                        optimized[source_statement->result] = temp;
                    } else {
                        (*ptr)->op = assign_op;
                        (*ptr)->arg1 = source_statement->result;

                    }

                    changes = true;
                }
            }
        }
    }

    return changes;
}
<commit_msg>Fix the optimization<commit_after>//=======================================================================
// Copyright Baptiste Wicht 2011.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
//  http://www.boost.org/LICENSE_1_0.txt)
//=======================================================================

#include "assert.hpp"
#include "Variable.hpp"
#include "FunctionContext.hpp"
#include "Type.hpp"
#include "iterators.hpp"

#include "mtac/CommonSubexpressionElimination.hpp"
#include "mtac/Utils.hpp"
#include "mtac/Printer.hpp"

using namespace eddic;

typedef mtac::CommonSubexpressionElimination::ProblemDomain ProblemDomain;

std::ostream& mtac::operator<<(std::ostream& stream, Expression& /*expression*/){
    return stream << "Expression {expression = {}}";
}

inline bool are_equivalent(std::shared_ptr<mtac::Quadruple> first, std::shared_ptr<mtac::Quadruple> second){
    return first->op == second->op && *first->arg1 == *second->arg1 && *first->arg2 == *second->arg2;
}

ProblemDomain mtac::CommonSubexpressionElimination::meet(ProblemDomain& in, ProblemDomain& out){
    ASSERT(!in.top() || !out.top(), "At least one lattice should not be a top element");

    if(in.top()){
        return out;
    } else if(out.top()){
        return in;
    } else {
        typename ProblemDomain::Values values;

        for(auto& in_value : in.values()){
            for(auto& out_value : out.values()){
                if(are_equivalent(in_value.expression, out_value.expression)){
                    values.push_back(in_value);
                }
            }
        }

        ProblemDomain result(values);
        return result;
    }
}

ProblemDomain mtac::CommonSubexpressionElimination::transfer(std::shared_ptr<mtac::BasicBlock> basic_block, mtac::Statement& statement, ProblemDomain& in){
    auto out = in;

    if(auto* ptr = boost::get<std::shared_ptr<mtac::Quadruple>>(&statement)){
        auto op = (*ptr)->op;
        if(mtac::erase_result(op)){
            auto it = iterate(out.values());

            while(it.has_next()){
                auto& expression = (*it).expression;

                if(expression->arg1){
                    if(auto* var_ptr = boost::get<std::shared_ptr<Variable>>(&*expression->arg1)){
                        if(*var_ptr == (*ptr)->result){
                            it.erase();
                            continue;
                        }
                    }
                }

                if(expression->arg2){
                    if(auto* var_ptr = boost::get<std::shared_ptr<Variable>>(&*expression->arg2)){
                        if(*var_ptr == (*ptr)->result){
                            it.erase();
                            continue;
                        }
                    }
                }

                ++it;
            }
        }

        if(mtac::is_expression((*ptr)->op)){
            bool exists = false;
            for(auto& expression : out.values()){
                if(are_equivalent(*ptr, expression.expression)){
                    exists = true;
                    break;
                }
            }

            if(!exists){
                Expression expression;
                expression.expression = *ptr;
                expression.source = basic_block;

                out.values().push_back(expression);
            }
        }
    }

    return out;
}

ProblemDomain mtac::CommonSubexpressionElimination::Boundary(std::shared_ptr<mtac::Function> /*function*/){
    return default_element();
}

ProblemDomain mtac::CommonSubexpressionElimination::Init(std::shared_ptr<mtac::Function> function){
    if(init){
        ProblemDomain result(*init);
        return result;
    }

    typename ProblemDomain::Values values;

    for(auto& block : function->getBasicBlocks()){
        for(auto& statement : block->statements){
            if(auto* ptr = boost::get<std::shared_ptr<mtac::Quadruple>>(&statement)){
                if(mtac::is_expression((*ptr)->op)){
                    bool exists = false;
                    for(auto& expression : values){
                        if(are_equivalent(*ptr, expression.expression)){
                            exists = true;
                            break;
                        }
                    }

                    if(!exists){
                        Expression expression;
                        expression.expression = *ptr;
                        expression.source = block;

                        values.push_back(expression);
                    }
                }
            }
        }
    }

    init = values;

    ProblemDomain result(values);
    return result;
}

bool mtac::CommonSubexpressionElimination::optimize(mtac::Statement& statement, std::shared_ptr<mtac::DataFlowResults<ProblemDomain>>& global_results){
    auto& results = global_results->IN_S[statement];

    if(auto* ptr = boost::get<std::shared_ptr<mtac::Quadruple>>(&statement)){
        auto quadruple = *ptr;

        if(mtac::is_expression(quadruple->op)){
            for(auto& expression : results.values()){
                if(are_equivalent(expression.expression, quadruple)){
                    auto source_statement = expression.expression;

                    mtac::Operator assign_op;
                    if(quadruple->op >= mtac::Operator::ADD && quadruple->op <= mtac::Operator::MOD){
                        assign_op = mtac::Operator::ASSIGN;
                    } else if(quadruple->op >= mtac::Operator::FADD && quadruple->op <= mtac::Operator::FDIV){
                        assign_op = mtac::Operator::FASSIGN;
                    }

                    if(optimized.find(source_statement->result) == optimized.end()){
                        std::shared_ptr<Variable> temp;
                        if(quadruple->op >= mtac::Operator::ADD && quadruple->op <= mtac::Operator::MOD){
                            temp = expression.source->context->new_temporary(INT);
                        } else if(quadruple->op >= mtac::Operator::FADD && quadruple->op <= mtac::Operator::FDIV){
                            temp = expression.source->context->new_temporary(FLOAT);
                        }

                        auto it = expression.source->statements.begin();
                        auto end = expression.source->statements.end();

                        while(it != end){
                            if(boost::get<std::shared_ptr<Quadruple>>(&*it)){
                                auto target = boost::get<std::shared_ptr<Quadruple>>(*it);
                                if(target == source_statement){
                                    source_statement->result = temp;

                                    auto quadruple = std::make_shared<mtac::Quadruple>(source_statement->result, temp, assign_op);

                                    ++it;
                                    expression.source->statements.insert(it, quadruple);

                                    break;
                                }
                            }
                        }

                        quadruple->op = assign_op;
                        quadruple->arg1 = temp;
                        quadruple->arg2.reset();

                        optimized[source_statement->result] = temp;
                    }

                    quadruple->op = assign_op;
                    quadruple->arg1 = source_statement->result;
                    quadruple->arg2.reset();

                    return true;
                }
            }
        }
    }

    return false;
}
<|endoftext|>


<commit_before>#include <QApplication>
#include <QDebug>
#include <QSysInfo>
#include <QFile>
#include <QFont>
#include <QLibrary>

using namespace std;

#ifdef QT_OS_ANDROID
#include <jni.h>
extern "C" int state_run (int,char **,char *,bool,void *,void *);
extern "C" void javaOnLoad(JavaVM * vm, JNIEnv * env);
#else
typedef int (*Run)(int,char **,char *,bool,void *,void *);
extern "C" char * jepath1(char* arg);
#endif

int main(int argc, char *argv[])
{
#if defined(__MACH__) && !defined(QT50)
  if ( QSysInfo::MacintoshVersion > QSysInfo::MV_10_8 ) {
    // fix Mac OS X 10.9 (mavericks) font issue
    // https://bugreports.qt-project.org/browse/QTBUG-32789
    QFont::insertSubstitution(".Lucida Grande UI", "Lucida Grande");
  }
#endif
#ifdef QT_OS_ANDROID
  char path[1]= {'\0'};
#else
  char *path=jepath1(argv[0]);     // get path to JFE folder
#endif

  bool fhs = false;
#ifdef _WIN32
  QString s= QString::fromUtf8(path)+ "/jqt";
  if(!(QFile(s.append(".dll"))).exists()) {
    s= "jqt.dll";
    fhs = true;
  }
#else
  QString s= QString::fromUtf8(path)+ "/libjqt";
#if defined(__MACH__)
  if(!(QFile(s.append(".dylib"))).exists()) {
#else
  if(!(QFile(s.append(".so"))).exists()) {
#endif
#if defined(__MACH__)
    s= "libjqt.dylib";
#else
    s= "libjqt.so";
#endif
    fhs = true;
  }
#ifdef QT_OS_ANDROID
  return state_run(argc, argv, s.toUtf8().data(),fhs,0,(void *)-1);
#else
  QLibrary *lib=new QLibrary(s);
  Run state_run=(Run) lib->resolve("state_run");
  if (state_run)
    return state_run(argc, argv, lib->fileName().toUtf8().data(),fhs,0,(void *)-1);
#endif

#ifndef QT_OS_ANDROID
  qDebug() << lib->fileName();
  qDebug() << "could not resolve: state_run:\n\n" + lib->errorString();
#endif

  return -1;
#endif
}

#ifdef QT_OS_ANDROID
JNIEXPORT jint JNI_OnLoad(JavaVM* vm, void*)
{
  JNIEnv *jnienv;
  if (vm->GetEnv(reinterpret_cast<void**>(&jnienv), JNI_VERSION_1_6) != JNI_OK) {
    qCritical() << "JNI_OnLoad GetEnv Failed";
    return -1;
  }
  javaOnLoad(vm, jnienv);

  return JNI_VERSION_1_6;
}
#endif
<commit_msg>fix main.cpp #endif error<commit_after>#include <QApplication>
#include <QDebug>
#include <QSysInfo>
#include <QFile>
#include <QFont>
#include <QLibrary>

using namespace std;

#ifdef QT_OS_ANDROID
#include <jni.h>
extern "C" int state_run (int,char **,char *,bool,void *,void *);
extern "C" void javaOnLoad(JavaVM * vm, JNIEnv * env);
#else
typedef int (*Run)(int,char **,char *,bool,void *,void *);
extern "C" char * jepath1(char* arg);
#endif

int main(int argc, char *argv[])
{
#if defined(__MACH__) && !defined(QT50)
  if ( QSysInfo::MacintoshVersion > QSysInfo::MV_10_8 ) {
    // fix Mac OS X 10.9 (mavericks) font issue
    // https://bugreports.qt-project.org/browse/QTBUG-32789
    QFont::insertSubstitution(".Lucida Grande UI", "Lucida Grande");
  }
#endif
#ifdef QT_OS_ANDROID
  char path[1]= {'\0'};
#else
  char *path=jepath1(argv[0]);     // get path to JFE folder
#endif

  bool fhs = false;
#ifdef _WIN32
  QString s= QString::fromUtf8(path)+ "/jqt";
  if(!(QFile(s.append(".dll"))).exists()) {
    s= "jqt.dll";
    fhs = true;
  }
#else
  QString s= QString::fromUtf8(path)+ "/libjqt";
#if defined(__MACH__)
  if(!(QFile(s.append(".dylib"))).exists()) {
#else
  if(!(QFile(s.append(".so"))).exists()) {
#endif
#if defined(__MACH__)
    s= "libjqt.dylib";
#else
    s= "libjqt.so";
#endif
    fhs = true;
  }
#endif
#ifdef QT_OS_ANDROID
  return state_run(argc, argv, s.toUtf8().data(),fhs,0,(void *)-1);
#else
  QLibrary *lib=new QLibrary(s);
  Run state_run=(Run) lib->resolve("state_run");
  if (state_run)
    return state_run(argc, argv, lib->fileName().toUtf8().data(),fhs,0,(void *)-1);
#endif

#ifndef QT_OS_ANDROID
  qDebug() << lib->fileName();
  qDebug() << "could not resolve: state_run:\n\n" + lib->errorString();
#endif

  return -1;
}

#ifdef QT_OS_ANDROID
JNIEXPORT jint JNI_OnLoad(JavaVM* vm, void*)
{
  JNIEnv *jnienv;
  if (vm->GetEnv(reinterpret_cast<void**>(&jnienv), JNI_VERSION_1_6) != JNI_OK) {
    qCritical() << "JNI_OnLoad GetEnv Failed";
    return -1;
  }
  javaOnLoad(vm, jnienv);

  return JNI_VERSION_1_6;
}
#endif
<|endoftext|>


<commit_before>/****************************************************************************
**
** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of Qt Creator.
**
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia.  For licensing terms and
** conditions see http://qt.digia.com/licensing.  For further information
** use the contact form at http://qt.digia.com/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Digia gives you certain additional
** rights.  These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
****************************************************************************/

#include "documentmanager.h"
#include "qmldesignerplugin.h"

#include <modelnode.h>
#include <nodemetainfo.h>
#include <nodeproperty.h>
#include <bindingproperty.h>

namespace QmlDesigner {

static inline DesignDocument* currentDesignDocument()
{
    return QmlDesignerPlugin::instance()->documentManager().currentDesignDocument();
}

static inline void getProperties(const ModelNode node, QHash<PropertyName, QVariant> &propertyHash)
{
    if (QmlObjectNode::isValidQmlObjectNode(node)) {
        foreach (const AbstractProperty &abstractProperty, node.properties()) {
            if (abstractProperty.isVariantProperty()
                    || (abstractProperty.isBindingProperty()
                        && !abstractProperty.name().contains("anchors.")))
                propertyHash.insert(abstractProperty.name(), QmlObjectNode(node).instanceValue(abstractProperty.name()));
        }

        if (QmlItemNode::isValidQmlItemNode(node)) {
            QmlItemNode itemNode(node);

            propertyHash.insert("width", itemNode.instanceValue("width"));
            propertyHash.insert("height", itemNode.instanceValue("height"));
            propertyHash.remove("x");
            propertyHash.remove("y");
            propertyHash.remove("rotation");
            propertyHash.remove("opacity");
        }
    }
}

static inline void applyProperties(ModelNode &node, const QHash<PropertyName, QVariant> &propertyHash)
{
    QHash<PropertyName, QVariant> auxiliaryData  = node.auxiliaryData();

    foreach (const PropertyName &propertyName, auxiliaryData.keys()) {
        if (node.hasAuxiliaryData(propertyName))
            node.setAuxiliaryData(propertyName, QVariant());
    }

    QHashIterator<PropertyName, QVariant> propertyIterator(propertyHash);
    while (propertyIterator.hasNext()) {
        propertyIterator.next();
        const PropertyName propertyName = propertyIterator.key();
        if (propertyName == "width" || propertyName == "height") {
            node.setAuxiliaryData(propertyIterator.key(), propertyIterator.value());
        } else if (node.property(propertyIterator.key()).isDynamic() &&
                   node.property(propertyIterator.key()).dynamicTypeName() == "alias" &&
                   node.property(propertyIterator.key()).isBindingProperty()) {
            AbstractProperty targetProperty = node.bindingProperty(propertyIterator.key()).resolveToProperty();
            if (targetProperty.isValid())
                targetProperty.parentModelNode().setAuxiliaryData(targetProperty.name() + "@NodeInstance", propertyIterator.value());
        } else {
            node.setAuxiliaryData(propertyIterator.key() + "@NodeInstance", propertyIterator.value());
        }
    }
}

static inline void openFileForComponent(const ModelNode &node)
{
    QmlDesignerPlugin::instance()->viewManager().nextFileIsCalledInternally();

    //int width = 0;
    //int height = 0;
    QHash<PropertyName, QVariant> propertyHash;
    if (node.metaInfo().isFileComponent()) {
        //getWidthHeight(node, width, height);
        getProperties(node, propertyHash);
        Core::EditorManager::openEditor(node.metaInfo().componentFileName(), Core::Id(), Core::EditorManager::DoNotMakeVisible);
    } else if (node.metaInfo().isView() &&
               node.hasNodeProperty("delegate") &&
               node.nodeProperty("delegate").modelNode().metaInfo().isFileComponent()) {
        //getWidthHeight(node, width, height);
        getProperties(node, propertyHash);
        Core::EditorManager::openEditor(node.nodeProperty("delegate").modelNode().metaInfo().componentFileName(),
                                        Core::Id(), Core::EditorManager::DoNotMakeVisible);
    }
    ModelNode rootModelNode = currentDesignDocument()->rewriterView()->rootModelNode();
    applyProperties(rootModelNode, propertyHash);
    //rootModelNode.setAuxiliaryData("width", width);
    //rootModelNode.setAuxiliaryData("height", height);
}

static inline void openInlineComponent(const ModelNode &node)
{

    if (!node.isValid() || !node.metaInfo().isValid())
        return;

    if (!currentDesignDocument())
        return;

    QHash<PropertyName, QVariant> propertyHash;

    if (node.nodeSourceType() == ModelNode::NodeWithComponentSource) {
        //getWidthHeight(node, width, height);
        getProperties(node, propertyHash);
        currentDesignDocument()->changeToSubComponent(node);
    } else if (node.metaInfo().isView()
               && node.hasNodeProperty("delegate")
               && node.nodeProperty("delegate").modelNode().nodeSourceType() == ModelNode::NodeWithComponentSource) {
        //getWidthHeight(node, width, height);
        getProperties(node, propertyHash);
        currentDesignDocument()->changeToSubComponent(node.nodeProperty("delegate").modelNode());
    }

    ModelNode rootModelNode = currentDesignDocument()->rewriterView()->rootModelNode();
    applyProperties(rootModelNode, propertyHash);
    //rootModelNode.setAuxiliaryData("width", width);
    //rootModelNode.setAuxiliaryData("height", height);
}

static inline bool isFileComponent(const ModelNode &node)
{
    if (!node.isValid() || !node.metaInfo().isValid())
        return false;

    if (node.metaInfo().isFileComponent())
        return true;

    if (node.metaInfo().isView() &&
        node.hasNodeProperty("delegate")) {
        if (node.nodeProperty("delegate").modelNode().metaInfo().isFileComponent())
            return true;
    }

    return false;
}

DocumentManager::DocumentManager()
    : QObject()
{
}

DocumentManager::~DocumentManager()
{
    foreach (const QWeakPointer<DesignDocument> &designDocument, m_designDocumentHash)
        delete designDocument.data();
}

void DocumentManager::setCurrentDesignDocument(Core::IEditor *editor)
{
    if (editor) {
        m_currentDesignDocument = m_designDocumentHash.value(editor);
        if (m_currentDesignDocument == 0) {
            m_currentDesignDocument = new DesignDocument;
            m_designDocumentHash.insert(editor, m_currentDesignDocument);
            m_currentDesignDocument->setEditor(editor);
        }
    } else {
        m_currentDesignDocument->resetToDocumentModel();
        m_currentDesignDocument.clear();
    }
}

DesignDocument *DocumentManager::currentDesignDocument() const
{
    return m_currentDesignDocument.data();
}

bool DocumentManager::hasCurrentDesignDocument() const
{
    return m_currentDesignDocument.data();
}

void DocumentManager::removeEditors(QList<Core::IEditor *> editors)
{
    foreach (Core::IEditor *editor, editors)
        delete m_designDocumentHash.take(editor).data();
}

void DocumentManager::goIntoComponent(const ModelNode &modelNode)
{
    if (modelNode.isValid() && modelNode.isComponent()) {
        QmlDesignerPlugin::instance()->viewManager().setComponentNode(modelNode);
        if (isFileComponent(modelNode))
            openFileForComponent(modelNode);
        else
            openInlineComponent(modelNode);
    }
}

} // namespace QmlDesigner
<commit_msg>QmlDesigner: adding missing include<commit_after>/****************************************************************************
**
** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of Qt Creator.
**
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia.  For licensing terms and
** conditions see http://qt.digia.com/licensing.  For further information
** use the contact form at http://qt.digia.com/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Digia gives you certain additional
** rights.  These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
****************************************************************************/

#include "documentmanager.h"
#include "qmldesignerplugin.h"

#include <modelnode.h>
#include <qmlitemnode.h>
#include <nodemetainfo.h>
#include <nodeproperty.h>
#include <bindingproperty.h>

namespace QmlDesigner {

static inline DesignDocument* currentDesignDocument()
{
    return QmlDesignerPlugin::instance()->documentManager().currentDesignDocument();
}

static inline void getProperties(const ModelNode node, QHash<PropertyName, QVariant> &propertyHash)
{
    if (QmlObjectNode::isValidQmlObjectNode(node)) {
        foreach (const AbstractProperty &abstractProperty, node.properties()) {
            if (abstractProperty.isVariantProperty()
                    || (abstractProperty.isBindingProperty()
                        && !abstractProperty.name().contains("anchors.")))
                propertyHash.insert(abstractProperty.name(), QmlObjectNode(node).instanceValue(abstractProperty.name()));
        }

        if (QmlItemNode::isValidQmlItemNode(node)) {
            QmlItemNode itemNode(node);

            propertyHash.insert("width", itemNode.instanceValue("width"));
            propertyHash.insert("height", itemNode.instanceValue("height"));
            propertyHash.remove("x");
            propertyHash.remove("y");
            propertyHash.remove("rotation");
            propertyHash.remove("opacity");
        }
    }
}

static inline void applyProperties(ModelNode &node, const QHash<PropertyName, QVariant> &propertyHash)
{
    QHash<PropertyName, QVariant> auxiliaryData  = node.auxiliaryData();

    foreach (const PropertyName &propertyName, auxiliaryData.keys()) {
        if (node.hasAuxiliaryData(propertyName))
            node.setAuxiliaryData(propertyName, QVariant());
    }

    QHashIterator<PropertyName, QVariant> propertyIterator(propertyHash);
    while (propertyIterator.hasNext()) {
        propertyIterator.next();
        const PropertyName propertyName = propertyIterator.key();
        if (propertyName == "width" || propertyName == "height") {
            node.setAuxiliaryData(propertyIterator.key(), propertyIterator.value());
        } else if (node.property(propertyIterator.key()).isDynamic() &&
                   node.property(propertyIterator.key()).dynamicTypeName() == "alias" &&
                   node.property(propertyIterator.key()).isBindingProperty()) {
            AbstractProperty targetProperty = node.bindingProperty(propertyIterator.key()).resolveToProperty();
            if (targetProperty.isValid())
                targetProperty.parentModelNode().setAuxiliaryData(targetProperty.name() + "@NodeInstance", propertyIterator.value());
        } else {
            node.setAuxiliaryData(propertyIterator.key() + "@NodeInstance", propertyIterator.value());
        }
    }
}

static inline void openFileForComponent(const ModelNode &node)
{
    QmlDesignerPlugin::instance()->viewManager().nextFileIsCalledInternally();

    //int width = 0;
    //int height = 0;
    QHash<PropertyName, QVariant> propertyHash;
    if (node.metaInfo().isFileComponent()) {
        //getWidthHeight(node, width, height);
        getProperties(node, propertyHash);
        Core::EditorManager::openEditor(node.metaInfo().componentFileName(), Core::Id(), Core::EditorManager::DoNotMakeVisible);
    } else if (node.metaInfo().isView() &&
               node.hasNodeProperty("delegate") &&
               node.nodeProperty("delegate").modelNode().metaInfo().isFileComponent()) {
        //getWidthHeight(node, width, height);
        getProperties(node, propertyHash);
        Core::EditorManager::openEditor(node.nodeProperty("delegate").modelNode().metaInfo().componentFileName(),
                                        Core::Id(), Core::EditorManager::DoNotMakeVisible);
    }
    ModelNode rootModelNode = currentDesignDocument()->rewriterView()->rootModelNode();
    applyProperties(rootModelNode, propertyHash);
    //rootModelNode.setAuxiliaryData("width", width);
    //rootModelNode.setAuxiliaryData("height", height);
}

static inline void openInlineComponent(const ModelNode &node)
{

    if (!node.isValid() || !node.metaInfo().isValid())
        return;

    if (!currentDesignDocument())
        return;

    QHash<PropertyName, QVariant> propertyHash;

    if (node.nodeSourceType() == ModelNode::NodeWithComponentSource) {
        //getWidthHeight(node, width, height);
        getProperties(node, propertyHash);
        currentDesignDocument()->changeToSubComponent(node);
    } else if (node.metaInfo().isView()
               && node.hasNodeProperty("delegate")
               && node.nodeProperty("delegate").modelNode().nodeSourceType() == ModelNode::NodeWithComponentSource) {
        //getWidthHeight(node, width, height);
        getProperties(node, propertyHash);
        currentDesignDocument()->changeToSubComponent(node.nodeProperty("delegate").modelNode());
    }

    ModelNode rootModelNode = currentDesignDocument()->rewriterView()->rootModelNode();
    applyProperties(rootModelNode, propertyHash);
    //rootModelNode.setAuxiliaryData("width", width);
    //rootModelNode.setAuxiliaryData("height", height);
}

static inline bool isFileComponent(const ModelNode &node)
{
    if (!node.isValid() || !node.metaInfo().isValid())
        return false;

    if (node.metaInfo().isFileComponent())
        return true;

    if (node.metaInfo().isView() &&
        node.hasNodeProperty("delegate")) {
        if (node.nodeProperty("delegate").modelNode().metaInfo().isFileComponent())
            return true;
    }

    return false;
}

DocumentManager::DocumentManager()
    : QObject()
{
}

DocumentManager::~DocumentManager()
{
    foreach (const QWeakPointer<DesignDocument> &designDocument, m_designDocumentHash)
        delete designDocument.data();
}

void DocumentManager::setCurrentDesignDocument(Core::IEditor *editor)
{
    if (editor) {
        m_currentDesignDocument = m_designDocumentHash.value(editor);
        if (m_currentDesignDocument == 0) {
            m_currentDesignDocument = new DesignDocument;
            m_designDocumentHash.insert(editor, m_currentDesignDocument);
            m_currentDesignDocument->setEditor(editor);
        }
    } else {
        m_currentDesignDocument->resetToDocumentModel();
        m_currentDesignDocument.clear();
    }
}

DesignDocument *DocumentManager::currentDesignDocument() const
{
    return m_currentDesignDocument.data();
}

bool DocumentManager::hasCurrentDesignDocument() const
{
    return m_currentDesignDocument.data();
}

void DocumentManager::removeEditors(QList<Core::IEditor *> editors)
{
    foreach (Core::IEditor *editor, editors)
        delete m_designDocumentHash.take(editor).data();
}

void DocumentManager::goIntoComponent(const ModelNode &modelNode)
{
    if (modelNode.isValid() && modelNode.isComponent()) {
        QmlDesignerPlugin::instance()->viewManager().setComponentNode(modelNode);
        if (isFileComponent(modelNode))
            openFileForComponent(modelNode);
        else
            openInlineComponent(modelNode);
    }
}

} // namespace QmlDesigner
<|endoftext|>


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

///
/// @file exp_port.H
/// @brief Code to support ports
///
// *HWP HWP Owner: Stephen Glancy <sglancy@us.ibm.com>
// *HWP HWP Backup: Louis Stermole <stermole@us.ibm.com>
// *HWP Team: Memory
// *HWP Level: 3
// *HWP Consumed by: HB:FSP

#ifndef __MSS_EXP_PORT_H_
#define __MSS_EXP_PORT_H_

#include <fapi2.H>
#include <explorer_scom_addresses.H>
#include <explorer_scom_addresses_fld.H>
#include <explorer_scom_addresses_fld_fixes.H>
#include <lib/exp_attribute_accessors_manual.H>
#include <lib/utils/mss_exp_conversions.H>
#include <mss_explorer_attribute_getters.H>
#include <lib/shared/exp_consts.H>
#include <lib/dimm/exp_rank.H>
#include <generic/memory/lib/utils/mc/gen_mss_port.H>
#include <generic/memory/lib/utils/mc/gen_mss_restore_repairs.H>
#include <generic/memory/lib/utils/shared/mss_generic_consts.H>
#include <mss_generic_attribute_getters.H>

namespace mss
{

//////////////////////////////////////////////////////////////
// Traits values for EXPLORER
//////////////////////////////////////////////////////////////
///
/// @class Traits and policy class for port code - specialization for Explorer. The target of registers is TARGET_TYPE_OCMB_CHIP
///
template<>
class portTraits< mss::mc_type::EXPLORER >
{
    public:
        // MC_TYPE
        static constexpr fapi2::TargetType MC_TARGET_TYPE = fapi2::TARGET_TYPE_OCMB_CHIP;

        // PORT_TYPE
        static constexpr fapi2::TargetType PORT_TYPE = fapi2::TARGET_TYPE_MEM_PORT;

        // scom register definition
        static constexpr uint64_t MBARPC0Q_REG = EXPLR_SRQ_MBARPC0Q;

        static constexpr uint64_t FARB0Q_REG = EXPLR_SRQ_MBA_FARB0Q;
        static constexpr uint64_t FARB5Q_REG = EXPLR_SRQ_MBA_FARB5Q;
        static constexpr uint64_t FARB6Q_REG = EXPLR_SRQ_MBA_FARB6Q;
        static constexpr uint64_t FARB9Q_REG = EXPLR_SRQ_MBA_FARB9Q;
        static constexpr uint64_t PMU8Q_REG = EXPLR_SRQ_MBA_PMU8Q;
        static constexpr uint64_t REFRESH_REG = EXPLR_SRQ_MBAREF0Q;
        static constexpr uint64_t STR0Q_REG = EXPLR_SRQ_MBASTR0Q;
        static constexpr uint64_t ECC_REG = EXPLR_RDF_RECR;
        static constexpr uint64_t CTCR_REG = EXPLR_RDF_CTCR;
        static constexpr uint64_t DSM0Q_REG = EXPLR_SRQ_MBA_DSM0Q;
        static constexpr uint64_t FWMS_REG = EXPLR_RDF_FWMS0;

        static constexpr uint64_t RRQ_REG = EXPLR_SRQ_MBA_RRQ0Q;
        static constexpr uint64_t WRQ_REG = EXPLR_SRQ_MBA_WRQ0Q;

        static constexpr uint64_t MAGIC_NUMBER_SIM = 765;
        static constexpr uint64_t MAGIC_NUMBER_NOT_SIM = 196605;

        // This number includes the two spare nibbles, it is compared against
        // the actual nibble index we're at
        static constexpr uint8_t MAX_NIBBLE_IDX = 19;

        // scom register field definition
        enum
        {
            CFG_MIN_MAX_DOMAINS_ENABLE = EXPLR_SRQ_MBARPC0Q_CFG_MIN_MAX_DOMAINS_ENABLE,
            CFG_CCS_INST_RESET_ENABLE = EXPLR_SRQ_MBA_FARB5Q_CFG_CCS_INST_RESET_ENABLE,
            CFG_DDR_RESETN = EXPLR_SRQ_MBA_FARB5Q_CFG_DDR_RESETN,
            CFG_CCS_ADDR_MUX_SEL = EXPLR_SRQ_MBA_FARB5Q_CFG_CCS_ADDR_MUX_SEL,
            CFG_INIT_COMPLETE = EXPLR_SRQ_MBA_PMU8Q_CFG_INIT_COMPLETE,
            CFG_ZQ_PER_CAL_ENABLE = EXPLR_SRQ_MBA_FARB9Q_CFG_ZQ_PER_CAL_ENABLE,

            REFRESH_ENABLE = EXPLR_SRQ_MBAREF0Q_CFG_REFRESH_ENABLE,

            CFG_FORCE_STR = EXPLR_SRQ_MBASTR0Q_CFG_FORCE_STR,

            ECC_CHECK_DISABLE = EXPLR_RDF_RECR_MBSECCQ_DISABLE_MEMORY_ECC_CHECK_CORRECT,
            ECC_CORRECT_DISABLE = EXPLR_RDF_RECR_MBSECCQ_DISABLE_MEMORY_ECC_CORRECT,
            ECC_USE_ADDR_HASH = EXPLR_RDF_RECR_MBSECCQ_USE_ADDRESS_HASH,

            PORT_FAIL_DISABLE = EXPLR_SRQ_MBA_FARB0Q_CFG_PORT_FAIL_DISABLE,
            DFI_INIT_START = EXPLR_SRQ_MBA_FARB0Q_CFG_INIT_START,
            RCD_RECOVERY_DISABLE = EXPLR_SRQ_MBA_FARB0Q_CFG_DISABLE_RCD_RECOVERY,
            BW_WINDOW_SIZE = EXPLR_SRQ_MBA_FARB0Q_CFG_BW_WINDOW_SIZE,
            BW_WINDOW_SIZE_LEN = EXPLR_SRQ_MBA_FARB0Q_CFG_BW_WINDOW_SIZE_LEN,
            BW_SNAPSHOT = EXPLR_SRQ_MBA_FARB6Q_CFG_BW_SNAPSHOT,
            BW_SNAPSHOT_LEN = EXPLR_SRQ_MBA_FARB6Q_CFG_BW_SNAPSHOT_LEN,

            RECR_ENABLE_MPE_NOISE_WINDOW = EXPLR_RDF_RECR_MBSECCQ_ENABLE_MPE_NOISE_WINDOW,
            RECR_ENABLE_UE_NOISE_WINDOW = EXPLR_RDF_RECR_MBSECCQ_ENABLE_UE_NOISE_WINDOW,
            RECR_TCE_CORRECTION = EXPLR_RDF_RECR_MBSECCQ_ENABLE_TCE_CORRECTION,
            RECR_MBSECCQ_DATA_INVERSION = EXPLR_RDF_RECR_MBSECCQ_DATA_INVERSION,
            RECR_MBSECCQ_DATA_INVERSION_LEN = EXPLR_RDF_RECR_MBSECCQ_DATA_INVERSION_LEN,
            RECR_RETRY_UNMARKED_ERRORS = EXPLR_RDF_RECR_RETRY_UNMARKED_ERRORS,
            RECR_CFG_MAINT_USE_TIMERS = EXPLR_RDF_RECR_CFG_MAINT_USE_TIMERS,
            RECR_MBSECCQ_MAINT_NO_RETRY_UE = EXPLR_RDF_RECR_MBSECCQ_MAINT_NO_RETRY_UE,
            RECR_MBSECCQ_MAINT_NO_RETRY_MPE = EXPLR_RDF_RECR_MBSECCQ_MAINT_NO_RETRY_MPE,

            CFG_CTRLUPD_AFTER_ERR = EXPLR_SRQ_MBA_FARB9Q_CFG_CTRLUPD_AFTER_ERR,
            CFG_MC_PER_CAL_ENABLE = EXPLR_SRQ_MBA_FARB9Q_CFG_MC_PER_CAL_ENABLE,
            CFG_MC_PER_CAL_INTERVAL_TB = EXPLR_SRQ_MBA_FARB9Q_CFG_MC_PER_CAL_INTERVAL_TB,
            CFG_MC_PER_CAL_INTERVAL_TB_LEN = EXPLR_SRQ_MBA_FARB9Q_CFG_MC_PER_CAL_INTERVAL_TB_LEN,
            CFG_MC_PER_CAL_INTERVAL = EXPLR_SRQ_MBA_FARB9Q_CFG_MC_PER_CAL_INTERVAL,
            CFG_MC_PER_CAL_INTERVAL_LEN = EXPLR_SRQ_MBA_FARB9Q_CFG_MC_PER_CAL_INTERVAL_LEN,
            CFG_MC_PER_CAL_FIXED_RUN_LENGTH_EN = EXPLR_SRQ_MBA_FARB9Q_CFG_MC_PER_CAL_FIXED_RUN_LENGTH_EN,
            CFG_MC_PER_CAL_RUN_LENGTH = EXPLR_SRQ_MBA_FARB9Q_CFG_MC_PER_CAL_RUN_LENGTH,
            CFG_MC_PER_CAL_RUN_LENGTH_LEN = EXPLR_SRQ_MBA_FARB9Q_CFG_MC_PER_CAL_RUN_LENGTH_LEN,
            CFG_MC_PER_CAL_CTRLUPD_MIN = EXPLR_SRQ_MBA_FARB9Q_CFG_MC_PER_CAL_CTRLUPD_MIN,
            CFG_MC_PER_CAL_CTRLUPD_MIN_LEN = EXPLR_SRQ_MBA_FARB9Q_CFG_MC_PER_CAL_CTRLUPD_MIN_LEN,

            CTCR_MPE_TIMER = EXPLR_RDF_CTCR_MPE_TIMER,
            CTCR_MPE_TIMER_LEN = EXPLR_RDF_CTCR_MPE_TIMER_LEN,
            CTCR_MPE_TIMEBASE = EXPLR_RDF_CTCR_MPE_TIMEBASE,
            CTCR_MPE_TIMEBASE_LEN = EXPLR_RDF_CTCR_MPE_TIMEBASE_LEN,
            CTCR_UE_TIMER = EXPLR_RDF_CTCR_UE_TIMER,
            CTCR_UE_TIMER_LEN = EXPLR_RDF_CTCR_UE_TIMER_LEN,
            CTCR_UE_TIMEBASE = EXPLR_RDF_CTCR_UE_TIMEBASE,
            CTCR_UE_TIMEBASE_LEN = EXPLR_RDF_CTCR_UE_TIMEBASE_LEN,
            CTCR_UE_LOCKOUT_ENABLE = EXPLR_RDF_CTCR_UE_LOCKOUT_ENABLE,

            DSM0Q_RDTAG_DLY = EXPLR_SRQ_MBA_DSM0Q_CFG_RDTAG_DLY,
            DSM0Q_RDTAG_DLY_LEN = EXPLR_SRQ_MBA_DSM0Q_CFG_RDTAG_DLY_LEN,
            DSM0Q_WRDONE_DLY = EXPLR_SRQ_MBA_DSM0Q_CFG_WRDONE_DLY,
            DSM0Q_WRDONE_DLY_LEN = EXPLR_SRQ_MBA_DSM0Q_CFG_WRDONE_DLY_LEN,
            FARB0Q_RCD_PROTECTION_TIME = EXPLR_SRQ_MBA_FARB0Q_CFG_RCD_PROTECTION_TIME,
            FARB0Q_RCD_PROTECTION_TIME_LEN = EXPLR_SRQ_MBA_FARB0Q_CFG_RCD_PROTECTION_TIME_LEN,

            FWMS0_MARK = EXPLR_RDF_FWMS0_MARK,
            FWMS0_MARK_LEN = EXPLR_RDF_FWMS0_MARK_LEN,
            FWMS0_EXIT_1 = EXPLR_RDF_FWMS0_EXIT_1,

            RRQ_FIFO_MODE = EXPLR_SRQ_MBA_RRQ0Q_CFG_RRQ_FIFO_MODE,
            WRQ_FIFO_MODE = EXPLR_SRQ_MBA_WRQ0Q_CFG_WRQ_FIFO_MODE,
        };
};

/// @brief Get the attributes for the reorder queue setting
/// @param[in] const ref to the mc target
/// @param[out] uint8_t& reference to store the value
/// @return fapi2::ReturnCode - FAPI2_RC_SUCCESS iff get is OK
/// @note  Contains the settings for write/read reorder
/// queue
///
template< >
inline fapi2::ReturnCode reorder_queue_setting<mss::mc_type::EXPLORER>(
    const fapi2::Target<fapi2::TARGET_TYPE_OCMB_CHIP>& i_target,
    uint8_t& o_value)
{
    return mss::attr::get_reorder_queue_setting(i_target, o_value);
}

///
/// @brief ATTR_MEM_EFF_DIMM_SPARE getter
/// @param[in] const ref to the TARGET_TYPE_DIMM
/// @param[out] uint32_t&[] array reference to store the value
/// @return fapi2::ReturnCode - FAPI2_RC_SUCCESS iff get is OK
/// @note  Spare DRAM availability. Used in various locations and is computed in mss_eff_cnfg.
/// Array indexes are [DIMM][RANK]
///
template<>
inline fapi2::ReturnCode dimm_spare< mss::mc_type::EXPLORER >(
    const fapi2::Target<fapi2::TARGET_TYPE_DIMM>& i_target,
    uint8_t (&o_array)[mss::MAX_RANK_PER_DIMM_ATTR])
{
    return mss::attr::get_dimm_spare(i_target, o_array);
}

///
/// @brief Change the state of the force_str bit - mc_type::EXPLORER specialization
/// @tparam MC the memory controller type
/// @param[in] i_target the target
/// @param[in] i_state the state
/// @return FAPI2_RC_SUCCESS if and only if ok
///
template< >
inline fapi2::ReturnCode change_force_str<DEFAULT_MC_TYPE>(
    const fapi2::Target<fapi2::TARGET_TYPE_OCMB_CHIP>& i_target,
    const states i_state )
{
    using TT = portTraits<mss::mc_type::EXPLORER>;
    fapi2::buffer<uint64_t> l_data;

    FAPI_DBG("Change force_str to %s %s", (i_state == HIGH ? "high" : "low"), mss::c_str(i_target));
    FAPI_TRY( mss::getScom(i_target, TT::STR0Q_REG, l_data) );
    l_data.writeBit<TT::CFG_FORCE_STR>(i_state);
    FAPI_TRY( mss::putScom(i_target, TT::STR0Q_REG, l_data) );

fapi_try_exit:
    return fapi2::current_err;
}

///
/// @brief Round the symbol from dq_to_symbol to its base multiple of 4, for use with steering
/// @param[in] i_symbol symbol from dq_to_symbol
/// @return uint8_t rounded DQ symbol
///
uint8_t symbol_rounder(const uint8_t i_symbol);

///
/// @brief Configure clock stabilization time field
/// @param[in] i_target the OCMB target to operate on
/// @param[in] i_has_rcd flag to signify existence of RCD on DIMM
/// @return FAPI2_RC_SUCCESS iff ok
///
fapi2::ReturnCode configure_tstab(const fapi2::Target<fapi2::TARGET_TYPE_OCMB_CHIP>& i_target, const bool i_has_rcd);

}// mss

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

///
/// @file exp_port.H
/// @brief Code to support ports
///
// *HWP HWP Owner: Stephen Glancy <sglancy@us.ibm.com>
// *HWP HWP Backup: Louis Stermole <stermole@us.ibm.com>
// *HWP Team: Memory
// *HWP Level: 3
// *HWP Consumed by: HB:FSP

#ifndef __MSS_EXP_PORT_H_
#define __MSS_EXP_PORT_H_

#include <fapi2.H>
#include <explorer_scom_addresses.H>
#include <explorer_scom_addresses_fld.H>
#include <explorer_scom_addresses_fld_fixes.H>
#include <lib/exp_attribute_accessors_manual.H>
#include <lib/utils/mss_exp_conversions.H>
#include <mss_explorer_attribute_getters.H>
#include <lib/mc/exp_port_traits.H>
#include <lib/shared/exp_consts.H>
#include <lib/dimm/exp_rank.H>
#include <generic/memory/lib/utils/mc/gen_mss_port.H>
#include <generic/memory/lib/utils/mc/gen_mss_restore_repairs.H>
#include <generic/memory/lib/utils/shared/mss_generic_consts.H>
#include <mss_generic_attribute_getters.H>

namespace mss
{

///
/// @brief Round the symbol from dq_to_symbol to its base multiple of 4, for use with steering
/// @param[in] i_symbol symbol from dq_to_symbol
/// @return uint8_t rounded DQ symbol
///
uint8_t symbol_rounder(const uint8_t i_symbol);

///
/// @brief Configure clock stabilization time field
/// @param[in] i_target the OCMB target to operate on
/// @param[in] i_has_rcd flag to signify existence of RCD on DIMM
/// @return FAPI2_RC_SUCCESS iff ok
///
fapi2::ReturnCode configure_tstab(const fapi2::Target<fapi2::TARGET_TYPE_OCMB_CHIP>& i_target, const bool i_has_rcd);

}// mss

#endif
<|endoftext|>


<commit_before>/**
 * The Seeks proxy and plugin framework are part of the SEEKS project.
 * Copyright (C) 2009 Emmanuel Benazera, juban@free.fr
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301  USA
 **/

#include "query_interceptor.h"
#include "websearch.h"
#include "cgi.h"
#include "miscutil.h"
#include "errlog.h"

#include <iostream>

namespace seeks_plugins
{
   std::string query_interceptor::_p_filename = "websearch/patterns/qi_patterns";

   query_interceptor::query_interceptor(plugin *parent)
     :interceptor_plugin(std::string(plugin_manager::_plugin_repository
				     + query_interceptor::_p_filename).c_str(),parent)
       {
       }

   http_response* query_interceptor::plugin_response(client_state *csp)
     {
	// - parse intercepted query.
	hash_map<const char*,const char*,hash<const char*>,eqstr> *params
	  = parse_query(&csp->_http);

	if (!params)
	  {
	     errlog::log_error(LOG_LEVEL_ERROR, "No parameters to intercepted query: %s%s",
			       csp->_http._host, csp->_http._path);
	     return cgi::cgi_error_memory(); // ok, this is not a memory error, but this does the job for now.
	  }

	// debug
	/* std::cerr << "params size: " << params->size() << std::endl;
	hash_map<const char*, const char*, hash<const char*>, eqstr>::const_iterator hit
	  = params->begin();
	while(hit!=params->end())
	  {
	     std::cerr << (*hit).first << " --> " << (*hit).second << std::endl;
	     ++hit;
	  } */
	// debug

	// - send it to the generic search interface.
	http_response *rsp;
	if (NULL == (rsp = new http_response()))
	  {
	     return cgi::cgi_error_memory();
	  }

	// - return the response to the client.
	// default query detection.
	const char *intercepted_query = miscutil::lookup(params,"q");
	//if (!intercepted_query || strlen(intercepted_query) == 0)
	// otherwise fall back onto se specific translation tables.

	// std::cout << "intercepted query: " << intercepted_query << std::endl;

	// build up query to seeks proxy.
	char *q = strdup(CGI_PREFIX);
	miscutil::string_append(&q,"search?q=");
	miscutil::string_append(&q,intercepted_query);
	miscutil::string_append(&q,"&page=1");
	miscutil::string_append(&q,"&expansion=1");
	miscutil::string_append(&q,"&action=expand");
	cgi::cgi_redirect(rsp,q);

	return cgi::finish_http_response(csp,rsp);
     }

   hash_map<const char*,const char*,hash<const char*>,eqstr>* query_interceptor::parse_query(http_request *http) const
     {
	if (http->_path)
	  {
	     hash_map<const char*,const char*,hash<const char*>,eqstr> *search_params
	       = cgi::parse_cgi_parameters(http->_path);
	     return search_params;
	  }
	else return NULL;
     }

} /* end of namespace. */
<commit_msg>fix wrong interception cases in query interceptor<commit_after>/**
 * The Seeks proxy and plugin framework are part of the SEEKS project.
 * Copyright (C) 2009 Emmanuel Benazera, juban@free.fr
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301  USA
 **/

#include "query_interceptor.h"
#include "websearch.h"
#include "cgi.h"
#include "miscutil.h"
#include "errlog.h"

#include <iostream>

namespace seeks_plugins
{
   std::string query_interceptor::_p_filename = "websearch/patterns/qi_patterns";

   query_interceptor::query_interceptor(plugin *parent)
     :interceptor_plugin(std::string(plugin_manager::_plugin_repository
				     + query_interceptor::_p_filename).c_str(),parent)
       {
       }

   http_response* query_interceptor::plugin_response(client_state *csp)
     {
	// - parse intercepted query.
	hash_map<const char*,const char*,hash<const char*>,eqstr> *params
	  = parse_query(&csp->_http);

	if (!params)
	  {
	     errlog::log_error(LOG_LEVEL_ERROR, "No parameters to intercepted query: %s%s",
			       csp->_http._host, csp->_http._path);
	     return cgi::cgi_error_memory(); // ok, this is not a memory error, but this does the job for now.
	  }

	// debug
	/* std::cerr << "params size: " << params->size() << std::endl;
	hash_map<const char*, const char*, hash<const char*>, eqstr>::const_iterator hit
	  = params->begin();
	while(hit!=params->end())
	  {
	     std::cerr << (*hit).first << " --> " << (*hit).second << std::endl;
	     ++hit;
	  } */
	// debug

	// - send it to the generic search interface.
	http_response *rsp;
	if (NULL == (rsp = new http_response()))
	  {
	     return cgi::cgi_error_memory();
	  }

	// - return the response to the client.
	// default query detection.
	const char *intercepted_query = miscutil::lookup(params,"q");
	if (!intercepted_query)
	  {
	     return NULL; // wrong interception, cancel.
	  }

	// build up query to seeks proxy.
	char *q = strdup(CGI_PREFIX);
	miscutil::string_append(&q,"search?q=");
	miscutil::string_append(&q,intercepted_query);
	miscutil::string_append(&q,"&page=1");
	miscutil::string_append(&q,"&expansion=1");
	miscutil::string_append(&q,"&action=expand");
	cgi::cgi_redirect(rsp,q);

	return cgi::finish_http_response(csp,rsp);
     }

   hash_map<const char*,const char*,hash<const char*>,eqstr>* query_interceptor::parse_query(http_request *http) const
     {
	if (http->_path)
	  {
	     hash_map<const char*,const char*,hash<const char*>,eqstr> *search_params
	       = cgi::parse_cgi_parameters(http->_path);
	     return search_params;
	  }
	else return NULL;
     }

} /* end of namespace. */
<|endoftext|>


<commit_before>#ifndef HMLIB_MATH_ROOT_INC
#define HMLIB_MATH_ROOT_INC 100
#
#include<utility>
#include<iterator>
#include<boost/math/tools/roots.hpp>
namespace hmLib {
	namespace math {
		template<typename T>
		struct toms748_root_stepper {
			using value_type = T;
		private:
			value_type step;
			value_type error;
		public:
			toms748_root_stepper(value_type step_, value_type error_):step(step_),error(error_){}
			template<typename fn, typename ans_type>
			std::pair<value_type, value_typeT> operator()(fn Fn, value_type& start, ans_type& startFnVal, value_type end)const {
				value_type a = start;
				ans_type fa = startFnVal;

				while(a < end) {
					auto b = std::min(a + step, end);
					auto fb = Fn(b);

					if(fb == 0) {
						start = b;
						startFnVal = fb;
						return std::make_pair(b, b);
					} else if(fa * fb < 0.0) {
						boost::uintmax_t max_iter = 128;
						auto ans = boost::math::tools::toms748_solve(Fn, a, b, fa, fb, [error](ans_type v1, ans_type v2) {return v2 - v1 < error; }, max_iter);
						start = b;
						startFnVal = fb;
						return ans;
					}

					a = b;
					fa = fb;
				}

				start = a;
				startFnVal = fa;

				return std::make_pair(a, a);
			}
			void reset(value_type step_, value_type error_) {
				step = step_;
				error = error_;
			}
		};
		template<typename T>
		struct bisect_root_stepper {
			using value_type = T;
		private:
			value_type step;
			value_type error;
		public:
			bisect_root_stepper(value_type step_, value_type error_):step(step_), error(error_) {}
			template<typename fn, typename ans_type>
			std::pair<value_type, value_typeT> operator()(fn Fn, value_type& start, ans_type& startFnVal, value_type end)const {
				value_type a = start;
				ans_type fa = startFnVal;

				while(a < end) {
					auto b = std::min(a + step, end);
					auto fb = Fn(b);

					if(fb == 0) {
						start = b;
						startFnVal = fb;
						return std::make_pair(b, b);
					} else if(fa * fb < 0.0) {
						boost::uintmax_t max_iter = 128;
						auto ans = boost::math::tools::bisect(Fn, a, b, [error](ans_type v1, ans_type v2) {return v2 - v1 < error; });
						start = b;
						startFnVal = fb;
						return ans;
					}

					a = b;
					fa = fb;
				}

				start = a;
				startFnVal = fa;

				return std::make_pair(a, a);
			}
			void reset(value_type step_, value_type error_) {
				step = step_;
				error = error_;
			}
		};
		template<typename root_stepper, typename fn, typename T, typename output_iterator>
		output_iterator root(root_stepper Stepper, fn Fn, T minval, T maxval, output_iterator out) {
			auto FnVal = Fn(minval);
			while (minval<maxval) {
				auto Ans = Stepper(Fn, minval, FnVal, maxval);

				if (Ans.first < maxval) {
					*(out++) = (Ans.first + Ans.second) / 2.0;
				}
			}

			return out;
		}
		template<typename root_stepper, typename fn, typename T, typename output_iterator>
		output_iterator root_with_stability(root_stepper Stepper, fn Fn, T minval, T maxval, output_iterator out) {
			auto FnVal = Fn(minval);
			while(minval<maxval) {
				auto Ans = Stepper(Fn, minval, FnVal, maxval);

				if(Ans.first < maxval) {
					*(out++) = std::make_pair((Ans.first + Ans.second) / 2.0, FnVal<0);
				}
			}

			return out;
		}
		template<typename root_stepper, typename fn, typename T, typename output_iterator>
		output_iterator convergent_root(root_stepper Stepper, fn Fn, T minval, T maxval, output_iterator out) {
			auto FnVal = Fn(minval);
			while(minval<maxval) {
				auto Ans = Stepper(Fn, minval, FnVal);

				if(Ans.first < maxval && FnVal<0) {
					*(out++) = (Ans.first + Ans.second) / 2.0;
				}
			}

			return out;
		}
		template<typename fn, typename T, typename output_iterator>
		output_iterator root_toms748(fn Fn, T minval, T maxval, T step, T error, output_iterator out) {
			toms748_root_stepper<T> Stepper(step, error);
			return root(Stepper, Fn, minval, maxval, out);
		}
		template<typename root_stepper, typename fn, typename T, typename output_iterator>
		output_iterator root_with_stability_toms748(fn Fn, T minval, T maxval, T step, T error, output_iterator out) {
			toms748_root_stepper<T> Stepper(step, error);
			return root_with_stability(Stepper, Fn, minval, maxval, out);
		}
		template<typename root_stepper, typename fn, typename T, typename output_iterator>
		output_iterator convergent_root(fn Fn, T minval, T maxval, T step, T error, output_iterator out) {
			toms748_root_stepper<T> Stepper(step, error);
			return convergent_root(Stepper, Fn, minval, maxval, out);
		}
	}
}
#
#endif
<commit_msg>Fix: typo in root <commit_after>#ifndef HMLIB_MATH_ROOT_INC
#define HMLIB_MATH_ROOT_INC 100
#
#include<utility>
#include<iterator>
#include<boost/math/tools/roots.hpp>
namespace hmLib {
	namespace math {
		template<typename T>
		struct toms748_root_stepper {
			using value_type = T;
		private:
			value_type step;
			value_type error;
		public:
			toms748_root_stepper(value_type step_, value_type error_):step(step_),error(error_){}
			template<typename fn, typename ans_type>
			std::pair<value_type, value_type> operator()(fn Fn, value_type& start, ans_type& startFnVal, value_type end)const {
				value_type a = start;
				ans_type fa = startFnVal;

				while(a < end) {
					auto b = std::min(a + step, end);
					auto fb = Fn(b);

					if(fb == 0) {
						start = b;
						startFnVal = fb;
						return std::make_pair(b, b);
					} else if(fa * fb < 0.0) {
						boost::uintmax_t max_iter = 128;
						auto ans = boost::math::tools::toms748_solve(Fn, a, b, fa, fb, [error=error](ans_type v1, ans_type v2) {return v2 - v1 < error; }, max_iter);
						start = b;
						startFnVal = fb;
						return ans;
					}

					a = b;
					fa = fb;
				}

				start = a;
				startFnVal = fa;

				return std::make_pair(a, a);
			}
			void reset(value_type step_, value_type error_) {
				step = step_;
				error = error_;
			}
		};
		template<typename T>
		struct bisect_root_stepper {
			using value_type = T;
		private:
			value_type step;
			value_type error;
		public:
			bisect_root_stepper(value_type step_, value_type error_):step(step_), error(error_) {}
			template<typename fn, typename ans_type>
			std::pair<value_type, value_type> operator()(fn Fn, value_type& start, ans_type& startFnVal, value_type end)const {
				value_type a = start;
				ans_type fa = startFnVal;

				while(a < end) {
					auto b = std::min(a + step, end);
					auto fb = Fn(b);

					if(fb == 0) {
						start = b;
						startFnVal = fb;
						return std::make_pair(b, b);
					} else if(fa * fb < 0.0) {
						boost::uintmax_t max_iter = 128;
						auto ans = boost::math::tools::bisect(Fn, a, b, [error=error](ans_type v1, ans_type v2) {return v2 - v1 < error; });
						start = b;
						startFnVal = fb;
						return ans;
					}

					a = b;
					fa = fb;
				}

				start = a;
				startFnVal = fa;

				return std::make_pair(a, a);
			}
			void reset(value_type step_, value_type error_) {
				step = step_;
				error = error_;
			}
		};
		template<typename root_stepper, typename fn, typename T, typename output_iterator>
		output_iterator root(root_stepper Stepper, fn Fn, T minval, T maxval, output_iterator out) {
			auto FnVal = Fn(minval);
			while (minval<maxval) {
				auto Ans = Stepper(Fn, minval, FnVal, maxval);

				if (Ans.first < maxval) {
					*(out++) = (Ans.first + Ans.second) / 2.0;
				}
			}

			return out;
		}
		template<typename root_stepper, typename fn, typename T, typename output_iterator>
		output_iterator root_with_stability(root_stepper Stepper, fn Fn, T minval, T maxval, output_iterator out) {
			auto FnVal = Fn(minval);
			while(minval<maxval) {
				auto Ans = Stepper(Fn, minval, FnVal, maxval);

				if(Ans.first < maxval) {
					*(out++) = std::make_pair((Ans.first + Ans.second) / 2.0, FnVal<0);
				}
			}

			return out;
		}
		template<typename root_stepper, typename fn, typename T, typename output_iterator>
		output_iterator stable_root(root_stepper Stepper, fn Fn, T minval, T maxval, output_iterator out) {
			auto FnVal = Fn(minval);
			while(minval<maxval) {
				auto Ans = Stepper(Fn, minval, FnVal, maxval);

				if(Ans.first < maxval && FnVal<0) {
					*(out++) = (Ans.first + Ans.second) / 2.0;
				}
			}

			return out;
		}
		template<typename fn, typename T, typename output_iterator>
		output_iterator root_toms748(fn Fn, T minval, T maxval, T step, T error, output_iterator out) {
			toms748_root_stepper<T> Stepper(step, error);
			return root(Stepper, std::forward<fn>(Fn), minval, maxval, out);
		}
		template<typename fn, typename T, typename output_iterator>
		output_iterator root_with_stability_toms748(fn Fn, T minval, T maxval, T step, T error, output_iterator out) {
			toms748_root_stepper<T> Stepper(step, error);
			return root_with_stability(Stepper, std::forward<fn>(Fn), minval, maxval, out);
		}
		template<typename fn, typename T, typename output_iterator>
		output_iterator stable_root_toms748(fn Fn, T minval, T maxval, T step, T error, output_iterator out) {
			toms748_root_stepper<T> Stepper(step, error);
			return stable_root(Stepper, std::forward<fn>(Fn), minval, maxval, out);
		}
	}
}
#
#endif
<|endoftext|>