text:
/*
 * rsxgltest - textured cube
 */

#define GL3_PROTOTYPES
#include <GL3/gl3.h>
#include <GL3/gl3ext.h>

#include "rsxgltest.h"
#include "math3d.h"
#include "sine_wave.h"

#include <stddef.h>
#include "texcube_vert.h"
#include "texcube_frag.h"

#include <io/pad.h>

#include <math.h>
#include <Eigen/Geometry>

#include "texture.h"
#include "nagel_bin.h"
#include "face_png.h"
#include "gradient_png.h"

const char * rsxgltest_name = "texcube";

struct sine_wave_t rgb_waves[3] = {
  { 0.5f,
    0.5f,
    1.0f
  },
  { 0.5f,
    0.5f,
    1.5f
  },
  { 0.5f,
    0.5f,
    2.5f
  }
};

struct sine_wave_t xyz_waves[3] = {
  { 0.5f,
    0.5f,
    1.0f / 4.0f
  },
  { 0.5f,
    0.5f,
    1.5f / 4.0f
  },
  { 0.5f,
    0.5f,
    2.5f / 4.0f
  }
};

GLuint vao = 0;
GLuint buffers[2] = { 0,0 };
GLuint shaders[2] = { 0,0 };

Image nagel_image, face_image, gradient_image;
GLuint textures[3] = { 0,0,0 };
GLuint program = 0;

GLint ProjMatrix_location = -1, TransMatrix_location = -1, vertex_location = -1, tc_location = -1, image_location = -1, gradient_location = -1;

const float geometry[] = {
    // -X
    -0.5,-0.5,-0.5,
    0,0,

    -0.5,0.5,-0.5,
    1,0,

    -0.5,0.5,0.5,
    1,1,

    -0.5,-0.5,0.5,
    0,1,

    // +X
    0.5,-0.5,-0.5,
    0,0,

    0.5,-0.5,0.5,
    1,0,

    0.5,0.5,0.5,
    1,1,

    0.5,0.5,-0.5,
    0,1,

    // -Y
    -0.5,-0.5,-0.5,
    0,0,

    -0.5,-0.5,0.5,
    1,0,

    0.5,-0.5,0.5,
    1,1,

    0.5,-0.5,-0.5,
    0,1,

    // +Y
    -0.5,0.5,-0.5,
    0,0,

    0.5,0.5,-0.5,
    1,0,

    0.5,0.5,0.5,
    1,1,

    -0.5,0.5,0.5,
    0,1,

    // -Z
    -0.5,-0.5,-0.5,
    0,0,

    -0.5,0.5,-0.5,
    1,0,

    0.5,0.5,-0.5,
    1,1,

    0.5,-0.5,-0.5,
    0,1,

    // +Z
    -0.5,-0.5,0.5,
    0,0,

    -0.5,0.5,0.5,
    1,0,

    0.5,0.5,0.5,
    1,1,

    0.5,-0.5,0.5,
    0,1
  };

  const GLuint indices[] = {
    // -X
    0, 1, 2,
    2, 3, 0,

    // +X
    4, 5, 6,
    6, 7, 4,

    // -Y
    8, 9, 10,
    10, 11, 8,

    // +Y
    12, 13, 14,
    14, 15, 12,

    // -Z
    16, 17, 18,
    18, 19, 16,

    // +Z
    20, 21, 22,
    22, 23, 20
  };

GLuint * client_indices = 0;

#define DTOR(X) ((X)*0.01745329f)
#define RTOD(d) ((d)*57.295788f)

Eigen::Projective3f ProjMatrix(perspective(DTOR(54.3),1920.0 / 1080.0,0.1,1000.0));

Eigen::Affine3f ViewMatrixInv =
  Eigen::Affine3f(Eigen::Affine3f::Identity() *
		  (
		   Eigen::Translation3f(1.779,2.221,4.034) *
		   (
		    Eigen::AngleAxisf(DTOR(0),Eigen::Vector3f::UnitZ()) *
		    Eigen::AngleAxisf(DTOR(23.8),Eigen::Vector3f::UnitY()) *
		    Eigen::AngleAxisf(DTOR(-26.738),Eigen::Vector3f::UnitX())
		    )
		   )
		  ).inverse();

extern "C"
void
rsxgltest_pad(unsigned int,const padData * paddata)
{
  if(paddata -> BTN_UP) {
    tcp_printf("up\n");
  }
  else if(paddata -> BTN_DOWN) {
    tcp_printf("down\n");
  }
}

extern "C"
void
rsxgltest_init(int argc,const char ** argv)
{
  tcp_printf("%s\n",__PRETTY_FUNCTION__);

  glEnable(GL_DEPTH_TEST);
  glDepthFunc(GL_LEQUAL);

  // Set up us the program:
  shaders[0] = glCreateShader(GL_VERTEX_SHADER);
  shaders[1] = glCreateShader(GL_FRAGMENT_SHADER);

  program = glCreateProgram();

  glAttachShader(program,shaders[0]);
  glAttachShader(program,shaders[1]);

  // Supply shader SOURCES!
  const GLchar * shader_srcs[] = { (const GLchar *)texcube_vert, (const GLchar *)texcube_frag };
  GLint shader_srcs_lengths[] = { texcube_vert_len, texcube_frag_len };
  GLint compiled = 0;

  glShaderSource(shaders[0],1,shader_srcs,shader_srcs_lengths);
  glCompileShader(shaders[0]);

  glGetShaderiv(shaders[0],GL_COMPILE_STATUS,&compiled);
  tcp_printf("shader compile status: %i\n",compiled);

  glShaderSource(shaders[1],1,shader_srcs + 1,shader_srcs_lengths + 1);
  glCompileShader(shaders[1]);

  glGetShaderiv(shaders[1],GL_COMPILE_STATUS,&compiled);
  tcp_printf("shader compile status: %i\n",compiled);

  // Link the program for real:
  glLinkProgram(program);

  glValidateProgram(program);

  summarize_program("draw",program);

  vertex_location = glGetAttribLocation(program,"vertex");
  tc_location = glGetAttribLocation(program,"uv");

  ProjMatrix_location = glGetUniformLocation(program,"ProjMatrix");
  TransMatrix_location = glGetUniformLocation(program,"TransMatrix");
  image_location = glGetUniformLocation(program,"image");
  gradient_location = glGetUniformLocation(program,"gradient");

  tcp_printf("vertex_location: %i\n",vertex_location);
  tcp_printf("tc_location: %i\n",tc_location);
  tcp_printf("ProjMatrix_location: %i TransMatrix_location: %i\n",
	     ProjMatrix_location,TransMatrix_location);
  tcp_printf("image_location: %i gradient_location: %i\n",image_location,gradient_location);

  glUseProgram(program);

  glUniformMatrix4fv(ProjMatrix_location,1,GL_FALSE,ProjMatrix.data());

  glUniform1i(image_location,0);
  glUniform1i(gradient_location,2);

  // Set up us the vertex data:
  glGenBuffers(2,buffers);

  glBindBuffer(GL_ARRAY_BUFFER,buffers[0]);
  glBufferData(GL_ARRAY_BUFFER,sizeof(float) * 6 * 4 * 5,geometry,GL_STATIC_DRAW);

  glEnableVertexAttribArray(vertex_location);
  glEnableVertexAttribArray(tc_location);
  glVertexAttribPointer(vertex_location,3,GL_FLOAT,GL_FALSE,sizeof(float) * 5,0);
  glVertexAttribPointer(tc_location,2,GL_FLOAT,GL_FALSE,sizeof(float) * 5,(const GLvoid *)(sizeof(float) * 3));

  client_indices = (GLuint *)malloc(sizeof(GLuint) * 6 * 2 * 3);
  memcpy(client_indices,indices,sizeof(GLuint) * 6 * 2 * 3);

  // Texture map:
  nagel_image = loadPng(nagel_bin);
  face_image = loadPng(face_png);
  gradient_image = loadPng(gradient_png);

  glGenTextures(3,textures);

  //
  glActiveTexture(GL_TEXTURE0);

  glBindTexture(GL_TEXTURE_2D,textures[0]);
  glTexStorage2D(GL_TEXTURE_2D,1,GL_RGBA,nagel_image.width,nagel_image.height);
  glTexSubImage2D(GL_TEXTURE_2D,0,0,0,nagel_image.width,nagel_image.height,GL_RGBA,GL_UNSIGNED_BYTE,nagel_image.data);

  glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_LINEAR);
  glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_LINEAR);

  //
  GLuint face_buffer = 0;
  glGenBuffers(1,&face_buffer);
  glBindBuffer(GL_PIXEL_UNPACK_BUFFER,face_buffer);
  glBufferData(GL_PIXEL_UNPACK_BUFFER,face_image.width * face_image.height * 4 * sizeof(GL_UNSIGNED_BYTE),face_image.data,GL_STATIC_DRAW);

  glActiveTexture(GL_TEXTURE1);

  glBindTexture(GL_TEXTURE_2D,textures[1]);
  glTexImage2D(GL_TEXTURE_2D,0,GL_RGBA,face_image.width,face_image.height,0,GL_RGBA,GL_UNSIGNED_BYTE,0);
  //glTexSubImage2D(GL_TEXTURE_2D,0,0,0,face_image.width,face_image.height,GL_RGBA,GL_UNSIGNED_BYTE,face_image.data);
  //glTexSubImage2D(GL_TEXTURE_2D,0,0,0,face_image.width,face_image.height,GL_RGBA,GL_UNSIGNED_BYTE,0);

  glBindBuffer(GL_PIXEL_UNPACK_BUFFER,0);

  glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_LINEAR);
  glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_LINEAR);

  //
  glActiveTexture(GL_TEXTURE2);

  glBindTexture(GL_TEXTURE_2D,textures[2]);
  glTexImage2D(GL_TEXTURE_2D,0,GL_RGBA,gradient_image.width,gradient_image.height,0,GL_RGBA,GL_UNSIGNED_BYTE,gradient_image.data);

  glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_LINEAR);
  glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_LINEAR);
}

extern "C"
int
rsxgltest_draw()
{
#if 0
  float rgb[3] = {
    compute_sine_wave(rgb_waves,rsxgltest_elapsed_time),
    compute_sine_wave(rgb_waves + 1,rsxgltest_elapsed_time),
    compute_sine_wave(rgb_waves + 2,rsxgltest_elapsed_time)
  };
#endif

  float rgb[3] = {
    1,0,0
  };

  glClearColor(rgb[0],rgb[1],rgb[2],1.0);
  glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

  float xyz[3] = {
    compute_sine_wave(xyz_waves,rsxgltest_elapsed_time),
    compute_sine_wave(xyz_waves + 1,rsxgltest_elapsed_time),
    compute_sine_wave(xyz_waves + 2,rsxgltest_elapsed_time)
  };

  Eigen::Affine3f rotmat =
    Eigen::Affine3f::Identity() *
    Eigen::AngleAxisf(DTOR(xyz[2]) * 360.0f,Eigen::Vector3f::UnitZ()) *
    Eigen::AngleAxisf(DTOR(xyz[1]) * 360.0f,Eigen::Vector3f::UnitY()) *
    Eigen::AngleAxisf(DTOR(xyz[0]) * 360.0f,Eigen::Vector3f::UnitX());

  {
    glActiveTexture(GL_TEXTURE0);
    glBindTexture(GL_TEXTURE_2D,textures[0]);
    //glUniform1i(image_location,0);

    Eigen::Affine3f modelview = ViewMatrixInv * (Eigen::Affine3f::Identity() * Eigen::Translation3f(-5,0,0) * rotmat * Eigen::UniformScaling< float >(3.0));
    //Eigen::Affine3f modelview = ViewMatrixInv;
    //Eigen::Affine3f modelview(Eigen::Affine3f::Identity());
    glUniformMatrix4fv(TransMatrix_location,1,GL_FALSE,modelview.data());

    glDrawElements(GL_TRIANGLES,36,GL_UNSIGNED_INT,client_indices);
  }

  {
    glActiveTexture(GL_TEXTURE0);
    glBindTexture(GL_TEXTURE_2D,textures[1]);
    //glUniform1i(image_location,1);

    Eigen::Affine3f modelview = ViewMatrixInv * (Eigen::Affine3f::Identity() * Eigen::Translation3f(5,0,0) * rotmat * Eigen::UniformScaling< float >(3.0));
    //Eigen::Affine3f modelview = ViewMatrixInv;
    //Eigen::Affine3f modelview(Eigen::Affine3f::Identity());
    glUniformMatrix4fv(TransMatrix_location,1,GL_FALSE,modelview.data());

    glDrawElements(GL_TRIANGLES,36,GL_UNSIGNED_INT,client_indices);
  }

  return 1;
}

extern "C"
void
rsxgltest_exit()
{
#if 0
  glBindBuffer(GL_ARRAY_BUFFER,0);

  glVertexAttribPointer(vertex_location,3,GL_FLOAT,GL_FALSE,0,0);
  glVertexAttribPointer(tc_location,2,GL_FLOAT,GL_FALSE,0,0);

  glDeleteBuffers(2,buffers);

  glDeleteShader(shaders[0]);
  glDeleteProgram(program);
  glDeleteShader(shaders[1]);
#endif
}

max_stars_repo_name: MauroArgentino/RSXGL

max_issues_repo_name: MauroArgentino/RSXGL

max_forks_repo_name: MauroArgentino/RSXGL


text:
/*
    This file is part of cpp-ethereum.
    cpp-ethereum is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.
    cpp-ethereum is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.
    You should have received a copy of the GNU General Public License
    along with cpp-ethereum.  If not, see <http://www.gnu.org/licenses/>.
*/

#include "Executive.h"

#include "ExtVM.h"
#include "State.h"
#include <LegacyVM.h>
#include <VMFactory.h>

#include <boost/timer.hpp>

#include <numeric>
#include "SealEngine.h"

using namespace std;
using namespace dev;
using namespace dev::eth;

Executive::Executive(State& io_s, unsigned _txIndex, unsigned _level):
    m_s(io_s),
    m_depth(_level)
{
}

void Executive::accrueSubState(SubState& _parentContext)
{
    if (m_ext)
        _parentContext += m_ext->sub;
}

void Executive::initialize(Transaction const& _transaction)
{
   m_t = _transaction;
}

bool Executive::execute()
{
    if (m_t.isCreation())
        return create(m_t.sender(), m_t.value(), &m_t.data(), m_t.sender());
    else
        return call(m_t.receiveAddress(), m_t.sender(), m_t.value(), bytesConstRef(&m_t.data()));
}

bool Executive::call(Address const& _receiveAddress, Address const& _senderAddress, u256 const& _value, bytesConstRef _data)
{
    CallParameters params{_senderAddress, _receiveAddress, _receiveAddress, _value, _value, 0, _data, {}};
    return call(params, _senderAddress);
}

bool Executive::call(CallParameters const& _p, Address const& _origin)
{
    if (SealEngine::get().isPrecompiled(_p.codeAddress, m_envInfo.number()))
    {
         bytes output;
         bool success;
         tie(success, output) = SealEngine::get().executePrecompiled(_p.codeAddress, _p.data, m_envInfo.number());
         size_t outputSize = output.size();
         m_output = owning_bytes_ref{std::move(output), 0, outputSize};
         if (!success)
         {
             m_gas = 0;
             m_excepted = TransactionException::OutOfGas;
             return true;  // true means no need to run go().
         }
    }
    else
    {
        m_gas = _p.gas;
        if (m_s.addressHasCode(_p.codeAddress))
        {
            bytes c = m_s.code(_p.codeAddress);
            h256 codeHash = m_s.codeHash(_p.codeAddress);
            m_ext = make_shared<ExtVM>(m_s, m_envInfo, _p.receiveAddress,
                _p.senderAddress, _origin, _p.apparentValue, 0, _p.data, &c, codeHash,
                m_depth, false, _p.staticCall);
        }
    }

    // Transfer ether.
    m_s.transferBalance(_p.senderAddress, _p.receiveAddress, _p.valueTransfer);
    return !m_ext;
}

bool Executive::create(Address const& _txSender, u256 const& _endowment, bytesConstRef _init, Address const& _origin)
{
    // Contract creation by an external account is the same as CREATE opcode
    return createOpcode(_txSender, _endowment, _init, _origin);
}

bool Executive::createOpcode(Address const& _sender, u256 const& _endowment, bytesConstRef _init, Address const& _origin)
{
    m_newAddress = _sender;//right160(sha3(rlpList(_sender, nonce)));
    return executeCreate(_sender, _endowment, _init, _origin);
}

bool Executive::create2Opcode(Address const& _sender, u256 const& _endowment, bytesConstRef _init, Address const& _origin, u256 const& _salt)
{
    m_newAddress = _sender;//right160(sha3(bytes{0xff} +_sender.asBytes() + toBigEndian(_salt) + sha3(_init)));
    return executeCreate(_sender, _endowment, _init, _origin);
}

bool Executive::executeCreate(Address const& _sender, u256 const& _endowment, bytesConstRef _init, Address const& _origin)
{
    m_isCreation = true;

    // We can allow for the reverted state (i.e. that with which m_ext is constructed) to contain the m_orig.address, since
    // we delete it explicitly if we decide we need to revert.
#if 0
    bool accountAlreadyExist = m_s.addressHasCode(m_newAddress);
    if (accountAlreadyExist)
    {
//        LOG(m_detailsLogger) << "Address already used: " << m_newAddress;
        m_gas = 0;
        m_excepted = TransactionException::AddressAlreadyUsed;
        revert();
        m_ext = {}; // cancel the _init execution if there are any scheduled.
        return !m_ext;
    }
    // Transfer ether before deploying the code. This will also create new
    // account if it does not exist yet.
    m_s.transferBalance(_sender, m_newAddress, _endowment);
#endif

    // Schedule _init execution if not empty.
    if (!_init.empty())
        m_ext = make_shared<ExtVM>(m_s, m_envInfo, m_newAddress, _sender, _origin,
              _endowment, 0,         bytesConstRef(), _init, u256(0), m_depth, true, false);
//FIXME sha3  _endowment, _gasPrice, bytesConstRef(), _init, sha3(_init), m_depth, true, false);

    return !m_ext;
}

bool Executive::go(OnOpFunc const& _onOp)
{
   if (!m_ext)
   {
      return true;
   }
   try
   {
      // Create VM instance. Force Interpreter if tracing requested.
      auto vm = VMFactory::create();
      if (m_isCreation)
      {
          m_s.clearStorage(m_ext->myAddress);
          auto out = vm->exec(m_gas, *m_ext, _onOp);
          m_s.setCode(m_ext->myAddress, out.toVector());
      }
      else
          m_output = vm->exec(m_gas, *m_ext, _onOp);
   }
   catch (RevertInstruction& _e)
   {
      revert();
      m_output = _e.output();
      m_excepted = TransactionException::RevertInstruction;
   }
   catch (VMException const& _e)
   {
//      LOG(m_detailsLogger) << "Safe VM Exception. " << diagnostic_information(_e);
      m_gas = 0;
      m_excepted = toTransactionException(_e);
      revert();
   }
   catch (InternalVMError const& _e)
   {
   //            cwarn << "Internal VM Error (" << *boost::get_error_info<errinfo_evmcStatusCode>(_e) << ")\n" << diagnostic_information(_e);
      revert();
      throw;
   }
   catch (Exception const& _e)
   {
      // TODO: AUDIT: check that this can never reasonably happen. Consider what to do if it does.
      //cwarn << "Unexpected exception in VM. There may be a bug in this implementation. " << diagnostic_information(_e);
      exit(1);
      // Another solution would be to reject this transaction, but that also
      // has drawbacks. Essentially, the amount of ram has to be increased here.
   }
   catch (std::exception const& _e)
   {
      // TODO: AUDIT: check that this can never reasonably happen. Consider what to do if it does.
      //cwarn << "Unexpected std::exception in VM. Not enough RAM? " << _e.what();
      exit(1);
      // Another solution would be to reject this transaction, but that also
      // has drawbacks. Essentially, the amount of ram has to be increased here.
   }
   return true;
}

bool Executive::finalize()
{
    // Suicides...
    if (m_ext)
        for (auto a: m_ext->sub.suicides)
            m_s.kill(a);

    return (m_excepted == TransactionException::None);
}

void Executive::revert()
{
    if (m_ext)
        m_ext->sub.clear();

    // Set result address to the null one.
    m_newAddress = {};
}

ext: cpp

max_stars_repo_name: learnforpractice/pyeos

max_issues_repo_name: openchatproject/safeos

max_forks_repo_name: learnforpractice/pyeos


text:
/**
 * Copyright (c) 2017 Melown Technologies SE
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * *  Redistributions of source code must retain the above copyright notice,
 *    this list of conditions and the following disclaimer.
 *
 * *  Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 */
/*
 * @file mask.cpp
 */

#include <cstdlib>
#include <algorithm>
#include <vector>
#include <iterator>

#include <boost/filesystem/path.hpp>
#include <boost/logic/tribool_io.hpp>

#include <opencv2/core/core.hpp>
#include <opencv2/imgproc/imgproc.hpp>

#include "dbglog/dbglog.hpp"

#include "utility/streams.hpp"
#include "utility/binaryio.hpp"
#include "imgproc/rastermask/quadtree.hpp"
#include "imgproc/fillrect.hpp"

#include "mask.hpp"

namespace fs = boost::filesystem;
namespace bin = utility::binaryio;

namespace gdal_drivers {

namespace {
    const char IO_MAGIC[6] = { 'G', 'D', 'A', 'L', 'Q', 'M' };
} // namespace

/**
 * @brief BorderedAreaRasterBand
 */

class MaskDataset::RasterBand : public GDALRasterBand {
public:
    RasterBand(MaskDataset *dset, unsigned int depth);

    virtual CPLErr IReadBlock(int blockCol, int blockRow, void *image);

    virtual ~RasterBand() {};

    virtual double GetNoDataValue(int *success = nullptr) {
        if (success) { *success = 1; }
        return 0.0;
    }

    virtual GDALColorInterp GetColorInterpretation() { return GCI_GrayIndex; }

    virtual int GetOverviewCount() {
        const auto &overviews(static_cast<MaskDataset*>(poDS)->overviews_);
        return overviews.size();
    }

    virtual GDALRasterBand* GetOverview(int index) {
        const auto &overviews(static_cast<MaskDataset*>(poDS)->overviews_);
        if (index >= int(overviews.size())) { return nullptr; }
        return overviews[index].get();
    }

private:
    unsigned int depth_;
    unsigned int tail_;
    cv::Rect tileBounds_;
};

GDALDataset* MaskDataset::Open(GDALOpenInfo *openInfo)
{
    ::CPLErrorReset();

    // try to open
    utility::ifstreambuf f;
    try {
        f.open(openInfo->pszFilename);
        char magic[6];
        bin::read(f, magic);
        if (std::memcmp(magic, IO_MAGIC, sizeof(IO_MAGIC))) {
            return nullptr;
        }
    } catch (...) { return nullptr; }

    // file belongs to us, we can continue

    // no updates
    if (openInfo->eAccess == GA_Update) {
        CPLError(CE_Failure, CPLE_NotSupported,
                 "The Quadtree Mask driver does not support update "
                 "access to existing datasets.\n");
        return nullptr;
    }

    // initialize dataset
    try {
        return new MaskDataset(openInfo->pszFilename, f);
    } catch (const std::runtime_error & e) {
        CPLError(CE_Failure, CPLE_IllegalArg
                 , "Dataset initialization failure (%s).\n", e.what());
        return nullptr;
    }
}

MaskDataset::MaskDataset(const fs::path &path, std::ifstream &f)
    : tileSize_(256, 256)
{
    auto maskOffset([&]() -> std::size_t
    {
        // load reserved
        {
            std::uint8_t reserved;
            bin::read(f, reserved);
            bin::read(f, reserved);
        }

        {
            // load srs
            std::uint32_t size;
            bin::read(f, size);
            std::vector<char> tmp(size, 0);
            bin::read(f, tmp.data(), tmp.size());
            srs_.assign(tmp.data(), tmp.size());
        }

        // read extents
        bin::read(f, extents_.ll(0));
        bin::read(f, extents_.ll(1));
        bin::read(f, extents_.ur(0));
        bin::read(f, extents_.ur(1));

        auto end(f.tellg());
        f.close();
        return end;
    }());

    // load mask
    mask_ = Mask(path, maskOffset);

    nRasterXSize = mask_.size().width;
    nRasterYSize = mask_.size().height;

    SetBand(1, new RasterBand(this, mask_.depth()));

    auto depth(mask_.depth());
    while (depth) {
        --depth;
        overviews_.push_back(std::make_shared<RasterBand>(this, depth));
    }
}

CPLErr MaskDataset::GetGeoTransform(double *padfTransform)
{
    auto es(math::size(extents_));

    padfTransform[0] = extents_.ll(0);
    padfTransform[1] = es.width / nRasterXSize;
    padfTransform[2] = 0.0;

    padfTransform[3] = extents_.ur(1);
    padfTransform[4] = 0.0;
    padfTransform[5] = -es.height / nRasterYSize;;

    return CE_None;
}

const char* MaskDataset::GetProjectionRef()
{
    return srs_.c_str();
}

/* RasterBand */

MaskDataset::RasterBand::RasterBand(MaskDataset *dset, unsigned int depth)
    : depth_(depth), tail_(dset->mask_.depth() - depth_)
    , tileBounds_(0, 0, dset->tileSize_.width, dset->tileSize_.height)
{
    poDS = dset;
    nBand = 1;
    nBlockXSize = dset->tileSize_.width;
    nBlockYSize = dset->tileSize_.height;
    eDataType = GDT_Byte;

    nRasterXSize = dset->mask_.size().width >> tail_;
    nRasterYSize = dset->mask_.size().height >> tail_;
}

namespace color {
    cv::Scalar black(0x00);
    cv::Scalar white(0xff);
    cv::Scalar gray(0x80);
} // namespace color

CPLErr MaskDataset::RasterBand::IReadBlock(int blockCol, int blockRow
                                           , void *rawImage)
{
    const auto &dset(*static_cast<MaskDataset*>(poDS));

    const auto &ts(dset.tileSize_);
    int xShift(blockCol * ts.width);
    int yShift(blockRow * ts.height);

    // setup constraints
    Mask::Constraints con(depth_);
    con.extents.ll(0) = (xShift << tail_);
    con.extents.ll(1) = (yShift << tail_);
    con.extents.ur(0) = con.extents.ll(0) + (ts.width << tail_);
    con.extents.ur(1) = con.extents.ll(1) + (ts.height << tail_);

    try {
        // wrap tile into matrix and reset to to zero
        cv::Mat tile(ts.height, ts.width, CV_8UC1, rawImage);
        tile = cv::Scalar(color::black);

        auto draw([&](Mask::Node node, boost::tribool value)
        {
            // black -> nothing
            if (!value) { return; }

            // update to match level grid
            node.shift(tail_);

            node.x -= xShift;
            node.y -= yShift;

            // construct rectangle and intersect it with bounds
            cv::Rect r(node.x, node.y, node.size, node.size);
            auto rr(r & tileBounds_);
            imgproc::fillRectangle
                (tile, rr, (value ? color::white : color::gray));
        });

        dset.mask_.forEachQuad(draw, con);
    } catch (const std::exception &e) {
        CPLError(CE_Failure, CPLE_FileIO, "%s\n", e.what());
        return CE_Failure;
    }
    return CE_None;
}

void MaskDataset::create(const boost::filesystem::path &path
                         , const imgproc::quadtree::RasterMask &mask
                         , const math::Extents2 &extents
                         , const geo::SrsDefinition &srs
                         , unsigned int depth, unsigned int x, unsigned int y)
{
    utility::ofstreambuf f(path.string());

    bin::write(f, IO_MAGIC); // 6 bytes
    bin::write(f, uint8_t(0)); // reserved
    bin::write(f, uint8_t(0)); // reserved

    // write SRS
    {
        auto srsWkt(srs.as(geo::SrsDefinition::Type::wkt).srs);
        bin::write(f, std::uint32_t(srsWkt.size()));
        bin::write(f, srsWkt.data(), srsWkt.size());
    }

    // update extents to to square
    auto sExtents(extents);
    {
        // input raster size
        auto mSize(mask.size());
        // square raster size
        auto sSize(1 << mask.depth());
        // extents size
        auto es(math::size(extents));
        // update extents to be square
        sExtents.ur(0) = sExtents.ll(0) + ((es.width * sSize) / mSize.width);
        sExtents.ll(1) = sExtents.ur(1) - ((es.height * sSize) / mSize.height);
    }

    // write extents
    bin::write(f, double(sExtents.ll(0)));
    bin::write(f, double(sExtents.ll(1)));
    bin::write(f, double(sExtents.ur(0)));
    bin::write(f, double(sExtents.ur(1)));

    // write mask
    imgproc::mappedqtree::RasterMask::write(f, mask, depth, x, y);
    f.close();
}

} // namespace gdal_drivers

/* GDALRegister_MaskDataset */

void GDALRegister_MaskDataset()
{
    if (!GDALGetDriverByName("QuadtreeMask")) {
        std::unique_ptr<GDALDriver> driver(new GDALDriver());

        driver->SetDescription("QuadtreeMask");
        driver->SetMetadataItem
            (GDAL_DMD_LONGNAME
             , "Support for mask defined as quadtree mask.");
        driver->SetMetadataItem(GDAL_DMD_EXTENSION, "");

        driver->pfnOpen = gdal_drivers::MaskDataset::Open;

        GetGDALDriverManager()->RegisterDriver(driver.release());
    }
}

max_stars_repo_name: melowntech/gdal-drivers

max_issues_repo_name: melowntech/gdal-drivers

max_forks_repo_name: Melown/gdal-drivers


text:
#pragma once

#include "IServer.hpp"
#include "RequestHandler.hpp"
#include "ConnectionManager.hpp"
#include "ResponseBuilder.hpp"
#include "RequestParser.hpp"

#include <string>
#include <boost/asio/io_service.hpp>
#include <boost/asio/ip/tcp.hpp>

namespace web
{
	using namespace boost::asio;
	using namespace boost::asio::ip;

	class Server : public IServer
	{
	public:
		Server(std::string_view address, uint32_t port, std::string_view root_dir);
		Server(const Server&) = delete;
		Server& operator=(const Server&) = delete;

		void start() override;
		void stop() override;
		void reset() override;

	private:
		io_service service_io;
		tcp::acceptor tcp_acceptor;
		tcp::socket tcp_socket;
		ResponseBuilder response_builder;
		RequestHandler request_handler;
		RequestParser request_parser;
		ConnectionManager connection_manager;

		void accept();
	};

}

ext: hpp


text:
#include <boost/algorithm/string.hpp>
#include <string>
#include <iostream>

using namespace std;
using namespace boost::algorithm;

int main()
{
  string s = "Boost C++ Libraries";
  cout << to_upper_copy(s) << endl;
}


text:
#ifndef BIGGLES_TOOL_DEBUG_HPP___
#define BIGGLES_TOOL_DEBUG_HPP___

#include <iostream>
#include <boost/timer.hpp>
#include <boost/shared_ptr.hpp>

#define OK(a) std::cerr << "OK " << #a << " = " << (a) << std::endl
#define OK1(a) std::cerr << "OK " << #a << " = " << std::endl << (a) << std::endl

struct TimeObserver {
    double t0, t1, t2, t3, t4;
    boost::timer timer;
    TimeObserver() : t0(0.0), t1(0.0), t2(0.0), t3(0.0), t4(0.0) {}
};

typedef boost::shared_ptr<TimeObserver> time_observer_ptr;

#endif //BIGGLES_TOOL_DEBUG_HPP___

max_stars_repo_name: fbi-octopus/biggles

max_issues_repo_name: fbi-octopus/biggles

max_forks_repo_name: fbi-octopus/biggles


text:
#ifndef INVINDEX_H_
#define INVINDEX_H_

#include <types.h>
#include <list>
#include <string>
#include <vector>
#include <algorithm>
#include <queue>
#include <utility>
#include <map>
#include <boost/unordered_map.hpp>
#include <boost/unordered_set.hpp>
#include <sstream>
#include "IDMapper.hpp"
#include "AVMapper.hpp"
#include "DNF.hpp"
#include "SimpleSerialization.hpp"
#include <3rdparty/json/json.h>

namespace izenelib { namespace ir { namespace be_index {

class ConjunctionInvIndex {
public:
    typedef std::map<uint32_t, boost::unordered_map<std::pair<uint32_t, uint32_t>, std::vector<std::pair<uint32_t, bool> > > > OuterT;
    typedef boost::unordered_map<std::pair<uint32_t, uint32_t>, std::vector<std::pair<uint32_t, bool> > > InnerT;

    // assumes number of attributes are not too large, use std::map to keep K ordered.
    std::map<uint32_t, boost::unordered_map<std::pair<uint32_t, uint32_t>, std::vector<std::pair<uint32_t, bool> > > > index;
    std::vector<std::pair<uint32_t, bool> > zeroConjunctionList;
    AVMapper avMapper;

    ConjunctionInvIndex()
    {
    }

    ~ConjunctionInvIndex()
    {
    }

    void addConjunction(uint32_t conjunctionID, const Conjunction & conjunction)
    {
        int K = conjunction.getK();

        if (K == 0) {
            zeroConjunctionList.push_back(std::make_pair(conjunctionID, true));
        }

        for (std::size_t i = 0; i != conjunction.assignments.size(); ++i) {
            for(std::size_t j = 0; j != conjunction.assignments[i].values.size(); ++j) {
                std::pair<std::pair<uint32_t, bool>, std::pair<uint32_t, bool> > avResult = avMapper.insert(conjunction.assignments[i].attribute, conjunction.assignments[i].values[j]);
                index[K][std::make_pair(avResult.first.first, avResult.second.first)].push_back(std::make_pair(conjunctionID, conjunction.assignments[i].belongsTo));
            }
        }
    }

    // special case: assignment has some nonexistent a v pair.
    void retrieve(const std::vector<std::pair<std::string, std::string> > & assignment, std::vector<uint32_t> & conjunctionIDs)
    {
        for (OuterT::iterator i = index.begin(); i != index.end() && i->first <= assignment.size(); ++i) {
            std::list<std::vector<std::pair<uint32_t, bool> > *> lists;
            std::list<std::size_t> positions;
            if (i->first == 0) {
                lists.push_back(&zeroConjunctionList);
                positions.push_back(0);
            }
            initPostingLists(lists, positions, assignment, i->second);

            uint32_t K = i->first;
            if (K == 0) {
                K = 1;
            }

            while (lists.size() >= K) {
                std::priority_queue<uint32_t> pq;
                uint32_t min = (*lists.front())[positions.front()].first;
                uint32_t minCnt = 0;
                bool invalid = false;

                std::list<std::vector<std::pair<uint32_t, bool> > *>::iterator j = lists.begin();
                std::list<std::size_t>::iterator k = positions.begin();
                while (j != lists.end()) {
                    uint32_t cid = (*(*j))[*k].first;
                    bool belongsTo = (*(*j))[*k].second;

                    if (pq.size() < K) {
                        pq.push(cid);
                    } else if (cid < pq.top()) {
                        pq.pop();
                        pq.push(cid);
                    }

                    if (cid < min) {
                        min = cid;
                        minCnt = 1;
                        invalid = !belongsTo;
                    } else if (cid == min) {
                        ++minCnt;
                        if (!belongsTo) {
                            invalid = true;
                        }
                    }

                    ++j;
                    ++k;
                }

                if (minCnt == K && !invalid) {
                    conjunctionIDs.push_back(min);
                }

                if (min == pq.top()) {
                    skipTo(lists, positions, min + 1);
                } else {
                    skipTo(lists, positions, pq.top());
                }
            }
        }
    }

    void skipTo(std::list<std::vector<std::pair<uint32_t, bool> > *> & lists, std::list<std::size_t> & positions, uint32_t cid)
    {
        std::list<std::vector<std::pair<uint32_t, bool> > *>::iterator i = lists.begin();
        std::list<std::size_t>::iterator j = positions.begin();
        while (i != lists.end()) {
            while (*j != (*(*i)).size() && (*(*i))[*j].first < cid) {
                ++(*j);
            }

            if (*j == (*(*i)).size()) {
                i = lists.erase(i);
                j = positions.erase(j);
            } else {
                ++i;
                ++j;
            }
        }
    }

    void initPostingLists(std::list<std::vector<std::pair<uint32_t, bool> > *> & lists, std::list<std::size_t> & positions, const std::vector<std::pair<std::string, std::string> > & assignment, InnerT & indexInner)
    {
        for (std::size_t i = 0; i != assignment.size(); ++i) {
            std::pair<std::pair<uint32_t, bool>, std::pair<uint32_t, bool> > avResult = avMapper.insert(assignment[i].first, assignment[i].second);
            InnerT::iterator p = indexInner.find(std::make_pair(avResult.first.first, avResult.second.first));
            if (p != indexInner.end()) {
                lists.push_back(&(p->second));
                positions.push_back(0);
            }
        }
    }

    void show()
    {
        for (OuterT::iterator i = index.begin(); i != index.end(); ++i) {
            std::cout << "K = " << i->first << std::endl;
            for (InnerT::iterator j = i->second.begin(); j != i->second.end(); ++j) {
                std::cout << "attribute = " << j->first.first << ", value = " << j->first.second << ":" << std::endl;
                for (std::size_t k = 0; k != j->second.size(); ++k) {
                    std::cout << "conjunction id = " << j->second[k].first << ", belongsTo = " << (j->second[k].second ? "true" : "false") << std::endl;
                }
            }
        }

        std::cout << "zeroConjunctionList:" << std::endl;
        for (std::size_t i = 0; i != zeroConjunctionList.size(); ++i) {
            std::cout << "conjunction id = " << zeroConjunctionList[i].first << ", belongsTo = " << (zeroConjunctionList[i].second ? "true" : "false") << std::endl;
        }
    }

    void toJson(Json::Value & root)
    {
        indexToJson(root["index"]);
        zeroConjunctionListToJson(root["zeroConjunctionList"]);
        avMapper.toJson(root["avMapper"]);
    }

    void indexToJson(Json::Value & root)
    {
        for (OuterT::iterator i = index.begin(); i != index.end(); ++i) {
            std::ostringstream out;
            out << i->first;
            innerToJson(root[out.str()], i->second);
        }
    }

    void innerToJson(Json::Value & root, InnerT & inner)
    {
        for (InnerT::iterator i = inner.begin(); i != inner.end(); ++i) {
            std::ostringstream out;
            out << i->first.first << ' ' << i->first.second;
            postingListToJson(root[out.str()], i->second);
        }
    }

    void postingListToJson(Json::Value & root, std::vector<std::pair<uint32_t, bool> > & postingList)
    {
        for (std::size_t i = 0; i != postingList.size(); ++i) {
            conjunctionPairToJson(root[i], postingList[i]);
        }
    }

    void conjunctionPairToJson(Json::Value & root, std::pair<uint32_t, bool> & conjunctionPair)
    {
        root[Json::Value::UInt(0U)] = Json::Value::UInt(conjunctionPair.first);
        root[Json::Value::UInt(1U)] = conjunctionPair.second;
    }

    void zeroConjunctionListToJson(Json::Value & root)
    {
        for (std::size_t i = 0; i != zeroConjunctionList.size(); ++i) {
            conjunctionPairToJson(root[i], zeroConjunctionList[i]);
        }
    }

    void fromJson(Json::Value & root)
    {
        indexFromJson(root["index"]);
        zeroConjunctionListFromJson(root["zeroConjunctionList"]);
        avMapper.fromJson(root["avMapper"]);
    }

    void indexFromJson(Json::Value & root)
    {
        for (Json::ValueIterator i = root.begin(); i != root.end(); ++i) {
            std::istringstream in(i.key().asString());
            uint32_t K;
            in >> K;
            innerFromJson(*i, index[K]);
        }
    }

    void innerFromJson(Json::Value & root, InnerT & inner)
    {
        for (Json::ValueIterator i = root.begin(); i != root.end(); ++i) {
            std::istringstream in(i.key().asString());
            uint32_t attrID, valueID;
            in >> attrID >> valueID;
            postingListFromJson(*i, inner[std::make_pair(attrID, valueID)]);
        }
    }

    void postingListFromJson(Json::Value & root, std::vector<std::pair<uint32_t, bool> > & postingList)
    {
        postingList.resize(root.size());
        for (std::size_t i = 0; i != root.size(); ++i) {
            conjunctionPairFromJson(root[i], postingList[i]);
        }
    }

    void conjunctionPairFromJson(Json::Value & root, std::pair<uint32_t, bool> & conjunctionPair)
    {
        conjunctionPair.first = root[Json::Value::UInt(0U)].asUInt();
        conjunctionPair.second = root[Json::Value::UInt(1U)].asBool();
    }

    void zeroConjunctionListFromJson(Json::Value & root)
    {
        zeroConjunctionList.resize(root.size());
        for (std::size_t i = 0; i != root.size(); ++i) {
            conjunctionPairFromJson(root[i], zeroConjunctionList[i]);
        }
    }

    void save_binary(std::ostream & os)
    {
        serialize(index.size(), os);
        for (OuterT::iterator i = index.begin(); i != index.end(); ++i) {
            serialize(i->first, os);

            serialize(i->second.size(), os);
            std::vector<std::pair<std::pair<uint32_t, uint32_t>, std::vector<std::pair<uint32_t, bool> > > > temp(i->second.begin(), i->second.end());
            std::sort(temp.begin(), temp.end());
            for (std::size_t j = 0; j != temp.size(); ++j) {
                serialize(temp[j].first.first, os);
                serialize(temp[j].first.second, os);

                serialize(temp[j].second.size(), os);
                for (std::size_t k = 0; k != temp[j].second.size(); ++k) {
                    serialize(temp[j].second[k].first, os);
                    serialize(temp[j].second[k].second, os);
                }
            }
        }

        serialize(zeroConjunctionList.size(), os);
        for (std::size_t i = 0; i != zeroConjunctionList.size(); ++i) {
            serialize(zeroConjunctionList[i].first, os);
            serialize(zeroConjunctionList[i].second, os);
        }

        avMapper.save_binary(os);
    }

    void load_binary(std::istream & is)
    {
        index.clear();
        std::size_t OuterSize;
        deserialize(is, OuterSize);
        for (std::size_t i = 0; i != OuterSize; ++i) {
            uint32_t K;
            deserialize(is, K);

            std::size_t InnerSize;
            deserialize(is, InnerSize);
            InnerT innerIndex;
            for (std::size_t j = 0; j != InnerSize; ++j) {
                uint32_t attrID;
                deserialize(is, attrID);
                uint32_t valueID;
                deserialize(is, valueID);

                std::size_t conjunctionListSize;
                deserialize(is, conjunctionListSize);
                std::vector<std::pair<uint32_t, bool> > conjunctionList(conjunctionListSize);
                for (std::size_t k = 0; k != conjunctionListSize; ++k) {
                    deserialize(is, conjunctionList[k].first);
                    deserialize(is, conjunctionList[k].second);
                }

                innerIndex[std::make_pair(attrID, valueID)] = conjunctionList;
            }

            index[K] = innerIndex;
        }

        std::size_t zeroConjunctionListSize;
        deserialize(is, zeroConjunctionListSize);
        zeroConjunctionList.resize(zeroConjunctionListSize);
        for (std::size_t i = 0; i != zeroConjunctionListSize; ++i) {
            deserialize(is, zeroConjunctionList[i].first);
            deserialize(is, zeroConjunctionList[i].second);
        }

        avMapper.load_binary(is);
    }
};

class DNFInvIndex {
public:
    ConjunctionInvIndex conjIndex;
    boost::unordered_map<uint32_t, std::vector<uint32_t> > index;
    IDMapper conjunctionMapper;
    uint32_t numDNF;

    DNFInvIndex(): numDNF(0)
    {
    }

    ~DNFInvIndex()
    {
    }

    // interface addDNF:
    // add a dnf which stands for an advertiser's targeting requirement.
    void addDNF(uint32_t dnfID, const DNF & dnf)
    {
        for (std::size_t i = 0; i != dnf.conjunctions.size(); ++i) {
            std::pair<uint32_t, bool> conjunctionResult = conjunctionMapper.insert(dnf.conjunctions[i].toString());
            if (conjunctionResult.second == true) {
                conjIndex.addConjunction(conjunctionResult.first, dnf.conjunctions[i]);
            }
            index[conjunctionResult.first].push_back(dnfID);
        }

        ++numDNF;
    }

    // interface retrieve:
    // read in a given assignment, and returns the valid dnf's.
    void retrieve(const std::vector<std::pair<std::string, std::string> > & assignment, boost::unordered_set<uint32_t> & dnfIDs)
    {
        std::vector<uint32_t> conjunctionIDs;
        conjIndex.retrieve(assignment, conjunctionIDs);
        for (std::size_t i = 0; i != conjunctionIDs.size(); ++i) {
            for (std::size_t j = 0; j != index[conjunctionIDs[i]].size(); ++j) {
                dnfIDs.insert(index[conjunctionIDs[i]][j]);
            }
        }
    }

    // interface totalNumDNF:
    // returns the total number of indexed dnf's.
    uint32_t totalNumDNF() const
    {
        return numDNF;
    }

    // interface save:
    // serialize the index in json text format.
    void save(std::ostream & os)
    {
        Json::FastWriter writer;
        Json::Value root;
        this->toJson(root);
        os << writer.write(root);
    }

    // interface load:
    // deserialize the index in json text format.
    void load(std::istream & is)
    {
        Json::Reader reader;
        Json::Value root;
        bool successful = reader.parse(is, root);
        if (!successful) {
            std::cout << "json parse error" << std::endl;
            return;
        }
        fromJson(root);
    }

    // interface save_binary:
    // serialize the index in binary format(for size consideration).
    void save_binary(std::ostream & os)
    {
        conjIndex.save_binary(os);

        serialize(index.size(), os);
        std::vector<std::pair<uint32_t, std::vector<uint32_t> > > temp(index.begin(), index.end());
        std::sort(temp.begin(), temp.end());
        for (std::size_t i = 0; i != temp.size(); ++i) {
            serialize(temp[i].first, os);

            serialize(temp[i].second.size(), os);
            for (std::size_t j = 0; j != temp[i].second.size(); ++j) {
                serialize(temp[i].second[j], os);
            }
        }

        conjunctionMapper.save_binary(os);

        serialize(numDNF, os);
    }

    // interface load_binary:
    // deserialize the index in binary format(for size consideration).
    void load_binary(std::istream & is)
    {
        conjIndex.load_binary(is);

        index.clear();
        std::size_t indexSize;
        deserialize(is, indexSize);
        for (std::size_t i = 0; i != indexSize; ++i) {
            uint32_t conjunctionID;
            deserialize(is, conjunctionID);

            std::size_t dnfListSize;
            deserialize(is, dnfListSize);
            std::vector<uint32_t> dnfList(dnfListSize);
            for (std::size_t j = 0; j != dnfListSize; ++j) {
                deserialize(is, dnfList[j]);
            }

            index[conjunctionID] = dnfList;
        }

        conjunctionMapper.load_binary(is);

        deserialize(is, numDNF);
    }

    // interface show:
    // show the index in human readable format(mainly for debug purpose).
    void show()
    {
        conjIndex.show();

        std::cout << std::endl;

        for (boost::unordered_map<uint32_t, std::vector<uint32_t> >::iterator i = index.begin(); i != index.end(); ++i) {
            std::cout << "conjunction id = " << i->first << ":" << std::endl;
            for (std::size_t j = 0; j != i->second.size(); ++j) {
                std::cout << "DNF id = " << i->second[j] << std::endl;
            }
        }
    }

    void toJson(Json::Value & root)
    {
        conjIndex.toJson(root["conjIndex"]);
        indexToJson(root["index"]);
        conjunctionMapper.toJson(root["conjunctionMapper"]);
        root["numDNF"] = Json::Value::UInt(numDNF);
    }

    void indexToJson(Json::Value & root)
    {
        for (boost::unordered_map<uint32_t, std::vector<uint32_t> >::iterator i = index.begin(); i != index.end(); ++i) {
            std::ostringstream out;
            out << i->first;
            postingListToJson(root[out.str()], i->second);
        }
    }

    void postingListToJson(Json::Value & root, std::vector<uint32_t> & postingList)
    {
        for (std::size_t i = 0; i != postingList.size(); ++i) {
            root[i] = Json::Value::UInt(postingList[i]);
        }
    }

    void fromJson(Json::Value & root)
    {
        conjIndex.fromJson(root["conjIndex"]);
        indexFromJson(root["index"]);
        conjunctionMapper.fromJson(root["conjunctionMapper"]);
        numDNF = root["numDNF"].asUInt();
    }

    void indexFromJson(Json::Value & root)
    {
        for (Json::ValueIterator i = root.begin(); i != root.end(); ++i) {
            std::istringstream in(i.key().asString());
            uint32_t conjunctionID;
            in >> conjunctionID;
            postingListFromJson(*i, index[conjunctionID]);
        }
    }

    void postingListFromJson(Json::Value & root, std::vector<uint32_t> & postingList)
    {
        for (std::size_t i = 0; i != root.size(); ++i) {
            postingList.push_back(root[i].asUInt());
        }
    }
};

}}}

#endif

max_stars_repo_name: izenecloud/izenelib

max_issues_repo_name: izenecloud/izenelib

max_forks_repo_name: izenecloud/izenelib


text:
/*
 *  Copyright (C) 2021 FISCO BCOS.
 *  SPDX-License-Identifier: Apache-2.0
 *  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.
 *
 * @brief WasmTransactionExecutor
 * @file WasmTransactionExecutor.cpp
 * @author: jimmyshi
 * @date: 2022-01-18
 */

#include "WasmTransactionExecutor.h"
#include "../Common.h"
#include "../dag/Abi.h"
#include "../dag/ClockCache.h"
#include "../dag/CriticalFields.h"
#include "../dag/ScaleUtils.h"
#include "../dag/TxDAG.h"
#include "../dag/TxDAG2.h"
#include "../precompiled/ConsensusPrecompiled.h"
#include "../precompiled/CryptoPrecompiled.h"
#include "../precompiled/FileSystemPrecompiled.h"
#include "../precompiled/KVTableFactoryPrecompiled.h"
#include "../precompiled/SystemConfigPrecompiled.h"
#include "../precompiled/extension/ContractAuthPrecompiled.h"
#include "../precompiled/extension/DagTransferPrecompiled.h"
#include "../vm/gas_meter/GasInjector.h"
#include "bcos-codec/abi/ContractABIType.h"
#include "bcos-framework/interfaces/executor/ExecutionMessage.h"
#include "bcos-framework/interfaces/executor/PrecompiledTypeDef.h"
#include "bcos-framework/interfaces/protocol/ProtocolTypeDef.h"
#include "bcos-framework/interfaces/protocol/TransactionReceipt.h"
#include "bcos-framework/interfaces/storage/StorageInterface.h"
#include "bcos-table/src/StateStorage.h"
#include "bcos-utilities/Error.h"
#include <tbb/parallel_for.h>
#include <tbb/spin_mutex.h>
#include <boost/algorithm/hex.hpp>
#include <boost/exception/diagnostic_information.hpp>
#include <boost/format/format_fwd.hpp>
#include <boost/lexical_cast.hpp>
#include <boost/throw_exception.hpp>
#include <cassert>
#include <exception>
#include <functional>
#include <iterator>
#include <mutex>
#include <shared_mutex>
#include <string>
#include <vector>

using namespace bcos;
using namespace std;
using namespace bcos::executor;
using namespace bcos::executor::critical;
using namespace bcos::wasm;
using namespace bcos::protocol;
using namespace bcos::storage;
using namespace bcos::precompiled;

BlockContext::Ptr WasmTransactionExecutor::createBlockContext(
    const protocol::BlockHeader::ConstPtr& currentHeader, storage::StateStorage::Ptr storage,
    storage::StorageInterface::Ptr lastStorage)
{
    BlockContext::Ptr context = make_shared<BlockContext>(
        storage, lastStorage, m_hashImpl, currentHeader, BCOSWASMSchedule, true, m_isAuthCheck);

    return context;
}

std::shared_ptr<BlockContext> WasmTransactionExecutor::createBlockContext(
    bcos::protocol::BlockNumber blockNumber, h256 blockHash, uint64_t timestamp,
    int32_t blockVersion, storage::StateStorage::Ptr storage)
{
    BlockContext::Ptr context = make_shared<BlockContext>(storage, m_hashImpl, blockNumber,
        blockHash, timestamp, blockVersion, BCOSWASMSchedule, true, m_isAuthCheck);

    return context;
}

void WasmTransactionExecutor::initPrecompiled()
{
    m_builtInPrecompiled = std::make_shared<std::set<std::string>>();
    m_constantPrecompiled =
        std::make_shared<std::map<std::string, std::shared_ptr<precompiled::Precompiled>>>();

    auto sysConfig = std::make_shared<precompiled::SystemConfigPrecompiled>(m_hashImpl);
    auto consensusPrecompiled = std::make_shared<precompiled::ConsensusPrecompiled>(m_hashImpl);
    // FIXME: not support crud now
    // auto tableFactoryPrecompiled =
    // std::make_shared<precompiled::TableFactoryPrecompiled>(m_hashImpl);
    auto kvTableFactoryPrecompiled =
        std::make_shared<precompiled::KVTableFactoryPrecompiled>(m_hashImpl);

    // in WASM
    m_constantPrecompiled->insert({SYS_CONFIG_NAME, sysConfig});
    m_constantPrecompiled->insert({CONSENSUS_NAME, consensusPrecompiled});
    // FIXME: not support crud now
    // m_constantPrecompiled.insert({TABLE_NAME, tableFactoryPrecompiled});
    m_constantPrecompiled->insert({KV_TABLE_NAME, kvTableFactoryPrecompiled});
    m_constantPrecompiled->insert(
        {DAG_TRANSFER_NAME, std::make_shared<precompiled::DagTransferPrecompiled>(m_hashImpl)});
    m_constantPrecompiled->insert({CRYPTO_NAME, std::make_shared<CryptoPrecompiled>(m_hashImpl)});
    m_constantPrecompiled->insert(
        {BFS_NAME, std::make_shared<precompiled::FileSystemPrecompiled>(m_hashImpl)});
    m_constantPrecompiled->insert(
        {CONTRACT_AUTH_NAME, std::make_shared<precompiled::ContractAuthPrecompiled>(m_hashImpl)});

    set<string> builtIn = {CRYPTO_NAME};
    m_builtInPrecompiled = make_shared<set<string>>(builtIn);
}

max_stars_repo_name: contropist/FISCO-BCOS

max_issues_repo_name: contropist/FISCO-BCOS

max_forks_repo_name: contropist/FISCO-BCOS


text:
/*
    Copyright 2013 "Paul" <http://stackoverflow.com/users/858219/paul>

    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.
*/

#include "relativepath.hpp"

#include <boost/filesystem.hpp>
#include <boost/algorithm/string.hpp>

namespace fs = boost::filesystem;

fs::path fs::relative(const fs::path &path, const fs::path &relative_to )
{
	// create absolute paths
	fs::path p = fs::absolute(path);
	fs::path r = fs::absolute(relative_to);

	// if root paths are different, return absolute path
	if( p.root_path() != r.root_path() )
		return p;

	// initialize relative path
	fs::path result;

	// find out where the two paths diverge
	fs::path::const_iterator itr_path = p.begin();
	fs::path::const_iterator itr_relative_to = r.begin();
	while( *itr_path == *itr_relative_to && itr_path != p.end() && itr_relative_to != r.end() ) {
		++itr_path;
		++itr_relative_to;
	}

	// add "../" for each remaining token in relative_to
	while( itr_relative_to != r.end() ) {
		result /= "..";
		++itr_relative_to;
	}

	// add remaining path
	while( itr_path != p.end() ) {
		result /= *itr_path;
		++itr_path;
	}

	return result;
}

void fs::create_relative_symlink(const fs::path& to, const fs::path& new_symlink)
{
	fs::create_symlink(fs::relative(to, new_symlink.parent_path()), new_symlink);
}

bool fs::path_is_in ( const fs::path& path, const fs::path& folder ) {
	return boost::starts_with(path, folder);
}

max_stars_repo_name: zidz/bithorde

max_issues_repo_name: zidz/bithorde

max_forks_repo_name: zidz/bithorde


text:
/**
 * @file mtl_test.cpp
 * Test script for interfacing with MTL4 and it's linear solvers.
 */

// HW3: Need to install/include Boost and MTL in Makefile
#include <boost/numeric/mtl/mtl.hpp>
#include <boost/numeric/itl/itl.hpp>

// HW3: YOUR CODE HERE
// Define a IdentityMatrix that interfaces with MTL

int main()
{
  // HW3: YOUR CODE HERE
  // Construct an IdentityMatrix and "solve" Ix = b
  // using MTL's conjugate gradient solver

  return 0;
}