<commit_before>//ibnu.yahya@toroo.org
#include "fs.h"
#include <QDebug>

fs::fs(QObject *parent) :
    QObject(parent)
{

}

bool fs::fileRemove(const QString &path){
    QFile file(path);
    return file.remove();
}

bool fs::fileWrite(const QString &path, const QString &data){
    QFile file(path);
    if (file.open(QIODevice::WriteOnly | QIODevice::Text)){
        QTextStream out(&file);
        out << data;
        file.close();
        return true;
    }
    else {
        return false;
    }
}

QString fs::fileRead(const QString &path){
    //QStringList fields;
    QFile file(path);
    if (file.open(QIODevice::ReadOnly | QIODevice::Text)){
        QTextStream out(&file);

        /*while(!out.atEnd()){
            fields.append(out.readLine());

        }*/
        QString data = out.readAll();
        /*foreach (const QString text, fields){
            qDebug() << text.toUtf8();
        }*/
        file.close();
        //return fields;
        return data;
    }
    else {
        qDebug()<< "Err : File not found";
        return "";
    }
}

QString fs::appPath(){
    return QApplication::applicationDirPath();
}

QString fs::homePath(){
    QString home = QDir::homePath();
    return home;
}

bool fs::dir(const QString &opt, const QString &path){
    QDir dir;
    if(opt == "create"){
        return dir.mkdir(path);
    }
    else if(opt == "remove"){
        return dir.rmdir(path);
    }
    else{
        return false;
    }
}

bool fs::isExist(const QString &path)
{
    return QFile::exists(path);
}

bool fs::isDirectory(const QString &path)
{
    return QFileInfo(path).isDir();
}

bool fs::isFile(const QString &path)
{
    return QFileInfo(path).isFile();
}

bool fs::isAbsolute(const QString &path)
{
   return QFileInfo(path).isAbsolute();
}

bool fs::isExecutable(const QString &path)
{
   return QFileInfo(path).isExecutable();
}

bool fs::isSymlink(const QString &path)
{
   return QFileInfo(path).isSymLink();
}

bool fs::isReadable(const QString &path)
{
   return QFileInfo(path).isReadable();
}

bool fs::isWritable(const QString &path)
{
   return QFileInfo(path).isWritable();
}

bool fs::copy(const QString &src, const QString &des){
    if(QFile::exists(des)){
        QFile::remove(des);
    }
    return QFile::copy(src,des);
}

QString fs::openFileDialog(){
    QFileDialog *fd = new QFileDialog;
    int result = fd->exec();
    if (result)
    {
        QString directory = fd->selectedFiles()[0];
        return directory;
    }
    else {
        return "";
    }
}

QString fs::openDirDialog(){
    QFileDialog *fd = new QFileDialog;
#ifdef Linux
    QTreeView *tree = fd->findChild <QTreeView*>();
    tree->setRootIsDecorated(true);
    tree->setItemsExpandable(true);
#endif
    fd->setFileMode(QFileDialog::Directory);
    fd->setOption(QFileDialog::ShowDirsOnly);
    fd->setViewMode(QFileDialog::Detail);
    int result = fd->exec();
    QString directory;
    if (result)
    {
        directory = fd->selectedFiles()[0];
        return directory;
    }
    else {
        return "";
    }
}

QString fs::saveFileDialog(){
    QFileDialog *fd = new QFileDialog;
    QString directory = fd->getSaveFileName();
    return directory;
}

QString fs::saveFileDialog(const QVariant &config){
    QVariantMap conf = json->jsonParser(config).toVariantMap();
    QString title = "Save File",
            path = this->homePath(),
            ext = "";
    if(conf["title"].toString() != ""){
        title = conf["title"].toString();
    }

    if(conf["path"].toString() != ""){
        path = conf["path"].toString();
    }

    if(conf["info"].toString() != ""){
        ext = conf["info"].toString();
    }

    QFileDialog *fd = new QFileDialog;
    QWidget *widget = new QWidget();
    QString directory = fd->getSaveFileName(widget, title,path,ext);
    return directory;
}

QStringList fs::list(const QString &path){
    QDirIterator dirIt(path,QDirIterator::Subdirectories);
    QStringList list;
    while (dirIt.hasNext()) {
        dirIt.next();
        list.push_front(dirIt.filePath());
    }
    return list;
}

QVariant fs::info(const QString &path){
    QVariantMap map;
    QFileInfo info(path);
    QVariant size = info.size();
    QVariant absoluteFilePath = info.absoluteFilePath();
    QVariant baseName = info.baseName();
    QVariant isSymlink = info.isSymLink();
    QVariant isAbsolute = info.isAbsolute();
    QVariant isBundle = info.isBundle();
    QVariant isDir = info.isDir();
    QVariant isExecutable = info.isExecutable();
    QVariant isFile = info.isFile();
    QVariant isHidden = info.isHidden();
    QVariant isReadable = info.isReadable();
    QVariant isRelative = info.isRelative();
    QVariant isRoot = info.isRoot();
    QVariant isWritable = info.isWritable();
    QVariant bundleName = info.bundleName();
    QVariant exists = info.exists();
    QVariant fileName = info.fileName();
    QVariant filePath = info.filePath();
    QVariant group = info.group();
    QVariant lastModified = info.lastModified();
    QVariant lastRead = info.lastRead();
    map.insert("size",size);
    map.insert("absoluteFilePath",absoluteFilePath);
    map.insert("baseName",baseName);
    map.insert("isSymlink",isSymlink);
    map.insert("isAbsolute",isAbsolute);
    map.insert("isBundle",isBundle);
    map.insert("isDir",isDir);
    map.insert("isExecutable",isExecutable);
    map.insert("isFile",isFile);
    map.insert("isHidden",isHidden);
    map.insert("isReadable",isReadable);
    map.insert("isRelative",isRelative);
    map.insert("isRoot",isRoot);
    map.insert("isWritable",isWritable);
    map.insert("filePath",filePath);
    map.insert("bundleName",bundleName);
    map.insert("exists",exists);
    map.insert("fileName",fileName);
    map.insert("group",group);
    map.insert("lastModified",lastModified);
    map.insert("lastRead",lastRead);
    QJsonDocument json_enc = QJsonDocument::fromVariant(map);
    return json_enc.toVariant();
}
<commit_msg>CHANGE: info object to type #161<commit_after>//ibnu.yahya@toroo.org
#include "fs.h"
#include <QDebug>

fs::fs(QObject *parent) :
    QObject(parent)
{

}

bool fs::fileRemove(const QString &path){
    QFile file(path);
    return file.remove();
}

bool fs::fileWrite(const QString &path, const QString &data){
    QFile file(path);
    if (file.open(QIODevice::WriteOnly | QIODevice::Text)){
        QTextStream out(&file);
        out << data;
        file.close();
        return true;
    }
    else {
        return false;
    }
}

QString fs::fileRead(const QString &path){
    //QStringList fields;
    QFile file(path);
    if (file.open(QIODevice::ReadOnly | QIODevice::Text)){
        QTextStream out(&file);

        /*while(!out.atEnd()){
            fields.append(out.readLine());

        }*/
        QString data = out.readAll();
        /*foreach (const QString text, fields){
            qDebug() << text.toUtf8();
        }*/
        file.close();
        //return fields;
        return data;
    }
    else {
        qDebug()<< "Err : File not found";
        return "";
    }
}

QString fs::appPath(){
    return QApplication::applicationDirPath();
}

QString fs::homePath(){
    QString home = QDir::homePath();
    return home;
}

bool fs::dir(const QString &opt, const QString &path){
    QDir dir;
    if(opt == "create"){
        return dir.mkdir(path);
    }
    else if(opt == "remove"){
        return dir.rmdir(path);
    }
    else{
        return false;
    }
}

bool fs::isExist(const QString &path)
{
    return QFile::exists(path);
}

bool fs::isDirectory(const QString &path)
{
    return QFileInfo(path).isDir();
}

bool fs::isFile(const QString &path)
{
    return QFileInfo(path).isFile();
}

bool fs::isAbsolute(const QString &path)
{
   return QFileInfo(path).isAbsolute();
}

bool fs::isExecutable(const QString &path)
{
   return QFileInfo(path).isExecutable();
}

bool fs::isSymlink(const QString &path)
{
   return QFileInfo(path).isSymLink();
}

bool fs::isReadable(const QString &path)
{
   return QFileInfo(path).isReadable();
}

bool fs::isWritable(const QString &path)
{
   return QFileInfo(path).isWritable();
}

bool fs::copy(const QString &src, const QString &des){
    if(QFile::exists(des)){
        QFile::remove(des);
    }
    return QFile::copy(src,des);
}

QString fs::openFileDialog(){
    QFileDialog *fd = new QFileDialog;
    int result = fd->exec();
    if (result)
    {
        QString directory = fd->selectedFiles()[0];
        return directory;
    }
    else {
        return "";
    }
}

QString fs::openDirDialog(){
    QFileDialog *fd = new QFileDialog;
#ifdef Linux
    QTreeView *tree = fd->findChild <QTreeView*>();
    tree->setRootIsDecorated(true);
    tree->setItemsExpandable(true);
#endif
    fd->setFileMode(QFileDialog::Directory);
    fd->setOption(QFileDialog::ShowDirsOnly);
    fd->setViewMode(QFileDialog::Detail);
    int result = fd->exec();
    QString directory;
    if (result)
    {
        directory = fd->selectedFiles()[0];
        return directory;
    }
    else {
        return "";
    }
}

QString fs::saveFileDialog(){
    QFileDialog *fd = new QFileDialog;
    QString directory = fd->getSaveFileName();
    return directory;
}

QString fs::saveFileDialog(const QVariant &config){
    QVariantMap conf = json->jsonParser(config).toVariantMap();
    QString title = "Save File",
            path = this->homePath(),
            ext = "";
    if(conf["title"].toString() != ""){
        title = conf["title"].toString();
    }

    if(conf["path"].toString() != ""){
        path = conf["path"].toString();
    }

    if(conf["type"].toString() != ""){
        ext = conf["type"].toString();
    }

    QFileDialog *fd = new QFileDialog;
    QWidget *widget = new QWidget();
    QString directory = fd->getSaveFileName(widget, title,path,ext);
    return directory;
}

QStringList fs::list(const QString &path){
    QDirIterator dirIt(path,QDirIterator::Subdirectories);
    QStringList list;
    while (dirIt.hasNext()) {
        dirIt.next();
        list.push_front(dirIt.filePath());
    }
    return list;
}

QVariant fs::info(const QString &path){
    QVariantMap map;
    QFileInfo info(path);
    QVariant size = info.size();
    QVariant absoluteFilePath = info.absoluteFilePath();
    QVariant baseName = info.baseName();
    QVariant isSymlink = info.isSymLink();
    QVariant isAbsolute = info.isAbsolute();
    QVariant isBundle = info.isBundle();
    QVariant isDir = info.isDir();
    QVariant isExecutable = info.isExecutable();
    QVariant isFile = info.isFile();
    QVariant isHidden = info.isHidden();
    QVariant isReadable = info.isReadable();
    QVariant isRelative = info.isRelative();
    QVariant isRoot = info.isRoot();
    QVariant isWritable = info.isWritable();
    QVariant bundleName = info.bundleName();
    QVariant exists = info.exists();
    QVariant fileName = info.fileName();
    QVariant filePath = info.filePath();
    QVariant group = info.group();
    QVariant lastModified = info.lastModified();
    QVariant lastRead = info.lastRead();
    map.insert("size",size);
    map.insert("absoluteFilePath",absoluteFilePath);
    map.insert("baseName",baseName);
    map.insert("isSymlink",isSymlink);
    map.insert("isAbsolute",isAbsolute);
    map.insert("isBundle",isBundle);
    map.insert("isDir",isDir);
    map.insert("isExecutable",isExecutable);
    map.insert("isFile",isFile);
    map.insert("isHidden",isHidden);
    map.insert("isReadable",isReadable);
    map.insert("isRelative",isRelative);
    map.insert("isRoot",isRoot);
    map.insert("isWritable",isWritable);
    map.insert("filePath",filePath);
    map.insert("bundleName",bundleName);
    map.insert("exists",exists);
    map.insert("fileName",fileName);
    map.insert("group",group);
    map.insert("lastModified",lastModified);
    map.insert("lastRead",lastRead);
    QJsonDocument json_enc = QJsonDocument::fromVariant(map);
    return json_enc.toVariant();
}
<|endoftext|>


<commit_before>/*
Copyright 2015 Esri
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.
A local copy of the license and additional notices are located with the
source distribution at:
http://github.com/Esri/lerc/
Contributors:  Thomas Maurer
*/

//
// BitMask2.cpp
//

#include "BitMask2.h"
#include <algorithm>
#include <cstring>
#include <iostream>
#include <cassert>

NAMESPACE_MRF_START

// -------------------------------------------------------------------------- ;

BitMask2::BitMask2() : m_pBits(NULL), m_nCols(0), m_nRows(0)
{
}

// -------------------------------------------------------------------------- ;

BitMask2::BitMask2(int nCols, int nRows) : m_pBits(NULL)
{
  SetSize(nCols, nRows);
}

// -------------------------------------------------------------------------- ;

BitMask2::BitMask2(const BitMask2& src) : m_pBits(NULL)
{
  SetSize(src.m_nCols, src.m_nRows);
  if (m_pBits && src.m_pBits)
    memcpy(m_pBits, src.m_pBits, Size());
}

// -------------------------------------------------------------------------- ;

BitMask2& BitMask2::operator= (const BitMask2& src)
{
  if (this == &src) return *this;

  SetSize(src.m_nCols, src.m_nRows);
  if (src.m_pBits)
    memcpy(m_pBits, src.m_pBits, Size());

  return *this;
}

// -------------------------------------------------------------------------- ;

bool BitMask2::SetSize(int nCols, int nRows)
{
  if (nCols != m_nCols || nRows != m_nRows)
  {
    Clear();
    m_nCols = nCols;
    m_nRows = nRows;
    m_pBits = new Byte[Size()];
  }
  return m_pBits != NULL;
}

// -------------------------------------------------------------------------- ;
//
// Count of set bits in a byte, done in 7 32bit instructions
// Adds every two bits sideways, makes four copies, masks each of the four results
// the last multiplication adds the four results together in the top nibble
// This is potentially slower for input data
//
static inline int csb(unsigned int v) {
    return ((((v - ((v >> 1) & 0x55)) * 0x1010101) & 0x30c00c03) * 0x10040041) >> 0x1c;
}

// Number of bits set.
// We really only need to know if full, empty or inbetween
int BitMask2::CountValidBits() const
{
  assert(Size());
  const Byte* ptr = m_pBits;
  int sum = 0;

  // The first loop is in multiples of four, to let the compiler optimize
  for (int i = 0; i < (Size()/4) * 4; i++)
      sum += csb(*ptr++);
  // Second loop for the leftover bytes, up to three
  for (int i = 0; i < Size() % 4; i++)
      sum += csb(*ptr++);

  // Subtract the defined bits potentially contained in the last byte
  // Number of undefined bytes is (C*R)%8
  // The undefined bits are at the low bit position, use a mask for them
  sum -= csb((*--ptr) & ((1 << ((m_nCols * m_nRows) % 8)) -1));

  return sum;
}

// -------------------------------------------------------------------------- ;

void BitMask2::Clear()
{
  delete[] m_pBits;
  m_pBits = NULL;
  m_nCols = 0;
  m_nRows = 0;
}

// -------------------------------------------------------------------------- ;

NAMESPACE_MRF_END
<commit_msg>GDAL integration #44<commit_after>/*
Copyright 2015 Esri
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.
A local copy of the license and additional notices are located with the
source distribution at:
http://github.com/Esri/lerc/
Contributors:  Thomas Maurer
*/

//
// BitMask2.cpp
//

#include "BitMask2.h"
#include <algorithm>
#include <cstring>
#include <iostream>
#include <cassert>

NAMESPACE_MRF_START

// -------------------------------------------------------------------------- ;

BitMask2::BitMask2() : m_pBits(NULL), m_nCols(0), m_nRows(0)
{
}

// -------------------------------------------------------------------------- ;

BitMask2::BitMask2(int nCols, int nRows) : m_pBits(NULL), m_nCols(0), m_nRows(0)
{
  SetSize(nCols, nRows);
}

// -------------------------------------------------------------------------- ;

BitMask2::BitMask2(const BitMask2& src) : m_pBits(NULL), m_nCols(0), m_nRows(0)
{
  SetSize(src.m_nCols, src.m_nRows);
  if (m_pBits && src.m_pBits)
    memcpy(m_pBits, src.m_pBits, Size());
}

// -------------------------------------------------------------------------- ;

BitMask2& BitMask2::operator= (const BitMask2& src)
{
  if (this == &src) return *this;

  SetSize(src.m_nCols, src.m_nRows);
  if (src.m_pBits)
    memcpy(m_pBits, src.m_pBits, Size());

  return *this;
}

// -------------------------------------------------------------------------- ;

bool BitMask2::SetSize(int nCols, int nRows)
{
  if (nCols != m_nCols || nRows != m_nRows)
  {
    Clear();
    m_nCols = nCols;
    m_nRows = nRows;
    m_pBits = new Byte[Size()];
  }
  return m_pBits != NULL;
}

// -------------------------------------------------------------------------- ;
//
// Count of set bits in a byte, done in 7 32bit instructions
// Adds every two bits sideways, makes four copies, masks each of the four results
// the last multiplication adds the four results together in the top nibble
// This is potentially slower for input data
//
static inline int csb(unsigned int v) {
    return ((((v - ((v >> 1) & 0x55)) * 0x1010101) & 0x30c00c03) * 0x10040041) >> 0x1c;
}

// Number of bits set.
// We really only need to know if full, empty or inbetween
int BitMask2::CountValidBits() const
{
  assert(Size());
  const Byte* ptr = m_pBits;
  int sum = 0;

  // The first loop is in multiples of four, to let the compiler optimize
  for (int i = 0; i < (Size()/4) * 4; i++)
      sum += csb(*ptr++);
  // Second loop for the leftover bytes, up to three
  for (int i = 0; i < Size() % 4; i++)
      sum += csb(*ptr++);

  // Subtract the defined bits potentially contained in the last byte
  // Number of undefined bytes is (C*R)%8
  // The undefined bits are at the low bit position, use a mask for them
  sum -= csb((*--ptr) & ((1 << ((m_nCols * m_nRows) % 8)) -1));

  return sum;
}

// -------------------------------------------------------------------------- ;

void BitMask2::Clear()
{
  delete[] m_pBits;
  m_pBits = NULL;
  m_nCols = 0;
  m_nRows = 0;
}

// -------------------------------------------------------------------------- ;

NAMESPACE_MRF_END
<|endoftext|>


<commit_before>//_________________________________________________________________________
//  Utility Class for transverse energy studies
//  Base class for ESD & MC analysis
//  - cuts for reconstruction and MonteCarlo
// implementation file
//
//*-- Authors: Oystein Djuvsland (Bergen), David Silvermyr (ORNL)
//_________________________________________________________________________

#include "AliAnalysisEtCuts.h"

#include <iostream>
#include "TNamed.h"

using namespace std;

ClassImp(AliAnalysisEtCuts);

AliAnalysisEtCuts::AliAnalysisEtCuts() :
  TNamed()
				    //
  ,fCommonEtaCut(0.5)
  ,fCommonClusterEnergyCut(0.15)
  ,fCommonTrackPtCut(0.0)
  ,fCommonSingleCell(1)
  ,fEmcalTrackDistanceCut(15.0)
  ,fEmcalTrackDxCut(5.0)
  ,fEmcalTrackDzCut(5.0)
  ,fPhosTrackDistanceCut(10.0)
  ,fPhosTrackDxCut(8.0)
  ,fPhosTrackDzCut(3.0)
  ,fPhosTrackRCut(5.0)
  ,fPhosBadDistanceCut(3.0)

  ,fGeometryPhosEtaAccCut(0.12)
  ,fGeometryPhosPhiAccMinCut(-100)//260.0)
  ,fGeometryPhosPhiAccMaxCut(-40)//320.0)
  ,fGeometryPhosDetectorRadius(460.0)
				    //
  ,fGeometryEmcalEtaAccCut(0.6)
  ,fGeometryEmcalPhiAccMinCut(80.0) // rad 1.4
  ,fGeometryEmcalPhiAccMaxCut(120.0) // rad 2.1
				    //,fGeometryEmcalPhiAccMaxCut(180.0) // rad 3.14
  ,fGeometryEmcalDetectorRadius(440.0)
				    //
  ,fReconstructedVertexXCut(0.5)
  ,fReconstructedVertexYCut(0.5)
  ,fReconstructedVertexZCut(12.0)
  ,fReconstructedIPxyCut(1.5)
  ,fReconstructedIPzCut(1.5)
  ,fReconstructedNTpcClustersCut(30)
  ,fReconstructedNItsClustersCut(3)
  ,fReconstructedPidCut(0.0)
				    //
  ,fReconstructedPhosClusterType(-1)
  ,fReconstructedPhosClusterEnergyCut(0.25)// GeV
  ,fReconstructedPhosSingleCellEnergyCut(0.5)
  ,fReconstructedPhosTrackDistanceTightCut(3.0)
  ,fReconstructedPhosTrackDistanceMediumCut(5.0)
  ,fReconstructedPhosTrackDistanceLooseCut(15.0)
				    //
  ,fReconstructedEmcalClusterType(1)
  ,fReconstructedEmcalClusterEnergyCut(0.30) // GeV
  ,fReconstructedEmcalSingleCellEnergyCut(0.5)
  ,fReconstructedEmcalTrackDistanceTightCut(5.0)
  ,fReconstructedEmcalTrackDistanceMediumCut(10.0)
  ,fReconstructedEmcalTrackDistanceLooseCut(15.0)

  ,fMonteCarloSingleChargedParticle(3)
  ,fMonteCarloNeutralParticle(0)

  ,fHistMakeTree(kFALSE)
  ,fHistMakeTreeDeposit(kFALSE)
  ,fHistNbinsMult(2000)
  ,fHistMinMult(-0.5)
  ,fHistMaxMult(1999.5)
  ,fHistNbinsTotEt(10000)
  ,fHistMinTotEt(0.000)
  ,fHistMaxTotEt(1000)
  ,fHistNbinsParticleEt(5000)
  ,fHistMinParticleEt(0)
  ,fHistMaxParticleEt(500)
  ,fHistNbinsParticlePt(200)
  ,fHistMinParticlePt(0)
  ,fHistMaxParticlePt(20)

  ,fPrimaryVertexCutXY(4.0)
  ,fPrimaryVertexCutZ(20.0)
{ // ctor
}

AliAnalysisEtCuts::~AliAnalysisEtCuts()
{ // dtor
}

void AliAnalysisEtCuts::SetPbPbDefaults()
{ // just increase seom histogram max values for now
  // enough to multiply conservative p+p defaults by a factor 100?
  fHistMaxMult = 20000;
  fHistMaxTotEt = 10000;
}

<commit_msg>slightly reducing PHOS acceptance used<commit_after>//_________________________________________________________________________
//  Utility Class for transverse energy studies
//  Base class for ESD & MC analysis
//  - cuts for reconstruction and MonteCarlo
// implementation file
//
//*-- Authors: Oystein Djuvsland (Bergen), David Silvermyr (ORNL)
//_________________________________________________________________________

#include "AliAnalysisEtCuts.h"

#include <iostream>
#include "TNamed.h"

using namespace std;

ClassImp(AliAnalysisEtCuts);

AliAnalysisEtCuts::AliAnalysisEtCuts() :
  TNamed()
				    //
  ,fCommonEtaCut(0.5)
  ,fCommonClusterEnergyCut(0.15)
  ,fCommonTrackPtCut(0.0)
  ,fCommonSingleCell(1)
  ,fEmcalTrackDistanceCut(15.0)
  ,fEmcalTrackDxCut(5.0)
  ,fEmcalTrackDzCut(5.0)
  ,fPhosTrackDistanceCut(10.0)
  ,fPhosTrackDxCut(8.0)
  ,fPhosTrackDzCut(3.0)
  ,fPhosTrackRCut(5.0)
  ,fPhosBadDistanceCut(3.0)

  ,fGeometryPhosEtaAccCut(0.1)//gives wiggle room
  ,fGeometryPhosPhiAccMinCut(-100)//260.0)
  ,fGeometryPhosPhiAccMaxCut(-40)//320.0)
  ,fGeometryPhosDetectorRadius(460.0)
				    //
  ,fGeometryEmcalEtaAccCut(0.6)
  ,fGeometryEmcalPhiAccMinCut(80.0) // rad 1.4
  ,fGeometryEmcalPhiAccMaxCut(120.0) // rad 2.1
				    //,fGeometryEmcalPhiAccMaxCut(180.0) // rad 3.14
  ,fGeometryEmcalDetectorRadius(440.0)
				    //
  ,fReconstructedVertexXCut(0.5)
  ,fReconstructedVertexYCut(0.5)
  ,fReconstructedVertexZCut(12.0)
  ,fReconstructedIPxyCut(1.5)
  ,fReconstructedIPzCut(1.5)
  ,fReconstructedNTpcClustersCut(30)
  ,fReconstructedNItsClustersCut(3)
  ,fReconstructedPidCut(0.0)
				    //
  ,fReconstructedPhosClusterType(-1)
  ,fReconstructedPhosClusterEnergyCut(0.25)// GeV
  ,fReconstructedPhosSingleCellEnergyCut(0.5)
  ,fReconstructedPhosTrackDistanceTightCut(3.0)
  ,fReconstructedPhosTrackDistanceMediumCut(5.0)
  ,fReconstructedPhosTrackDistanceLooseCut(15.0)
				    //
  ,fReconstructedEmcalClusterType(1)
  ,fReconstructedEmcalClusterEnergyCut(0.30) // GeV
  ,fReconstructedEmcalSingleCellEnergyCut(0.5)
  ,fReconstructedEmcalTrackDistanceTightCut(5.0)
  ,fReconstructedEmcalTrackDistanceMediumCut(10.0)
  ,fReconstructedEmcalTrackDistanceLooseCut(15.0)

  ,fMonteCarloSingleChargedParticle(3)
  ,fMonteCarloNeutralParticle(0)

  ,fHistMakeTree(kFALSE)
  ,fHistMakeTreeDeposit(kFALSE)
  ,fHistNbinsMult(2000)
  ,fHistMinMult(-0.5)
  ,fHistMaxMult(1999.5)
  ,fHistNbinsTotEt(10000)
  ,fHistMinTotEt(0.000)
  ,fHistMaxTotEt(1000)
  ,fHistNbinsParticleEt(5000)
  ,fHistMinParticleEt(0)
  ,fHistMaxParticleEt(500)
  ,fHistNbinsParticlePt(200)
  ,fHistMinParticlePt(0)
  ,fHistMaxParticlePt(20)

  ,fPrimaryVertexCutXY(4.0)
  ,fPrimaryVertexCutZ(20.0)
{ // ctor
}

AliAnalysisEtCuts::~AliAnalysisEtCuts()
{ // dtor
}

void AliAnalysisEtCuts::SetPbPbDefaults()
{ // just increase seom histogram max values for now
  // enough to multiply conservative p+p defaults by a factor 100?
  fHistMaxMult = 20000;
  fHistMaxTotEt = 10000;
}

<|endoftext|>


<commit_before>// Time:  O(1), per operation.
// Space: O(k), k is the capacity of cache.

class LFUCache {
public:
    LFUCache(int capacity) : capa_(capacity), size_(0) {
    }

    int get(int key) {
        if (!key_to_nodeit_.count(key)) {
            return -1;
        }

        auto new_node = *key_to_nodeit_[key];
        auto& freq = std::get<FREQ>(new_node);
        freq_to_nodes_[freq].erase(key_to_nodeit_[key]);
        if (freq_to_nodes_[freq].empty()) {
            freq_to_nodes_.erase(freq);
            if (min_freq_ == freq) {
                ++min_freq_;
            }
        }
        ++freq;
        freq_to_nodes_[freq].emplace_back(new_node);
        key_to_nodeit_[key] = prev(freq_to_nodes_[freq].end());

        return std::get<VAL>(*key_to_nodeit_[key]);
    }

   void put(int key, int value) {
        if (capa_ <= 0) {
            return;
        }

        if (get(key) != -1) {
            std::get<1>(*key_to_nodeit_[key]) = value;
            return;
        }

        if (size_ == capa_) {
            key_to_nodeit_.erase(std::get<KEY>(freq_to_nodes_[min_freq_].front()));
            freq_to_nodes_[min_freq_].pop_front();
            if (freq_to_nodes_[min_freq_].empty()) {
                freq_to_nodes_.erase(min_freq_);
            }
            --size_;
        }

        min_freq_ = 1;
        freq_to_nodes_[min_freq_].emplace_back(make_tuple(key, value, min_freq_));
        key_to_nodeit_[key] = prev(freq_to_nodes_[min_freq_].end());
        ++size_;
    }

private:
    enum Data {KEY, VAL, FREQ};
    int capa_;
    int size_;
    int min_freq_;
    unordered_map<int, list<tuple<int, int, int>>> freq_to_nodes_;            // freq to list of {key, val, freq}
    unordered_map<int, list<tuple<int, int, int>>::iterator> key_to_nodeit_;  // key to list iterator
};

/**
 * Your LFUCache object will be instantiated and called as such:
 * LFUCache obj = new LFUCache(capacity);
 * int param_1 = obj.get(key);
 * obj.put(key,value);
 */
<commit_msg>Update lfu-cache.cpp<commit_after>// Time:  O(1), per operation.
// Space: O(k), k is the capacity of cache.

class LFUCache {
public:
    LFUCache(int capacity) : capa_(capacity), size_(0) {
    }

    int get(int key) {
        if (!key_to_nodeit_.count(key)) {
            return -1;
        }

        auto new_node = *key_to_nodeit_[key];
        auto& freq = std::get<FREQ>(new_node);
        freq_to_nodes_[freq].erase(key_to_nodeit_[key]);
        if (freq_to_nodes_[freq].empty()) {
            freq_to_nodes_.erase(freq);
            if (min_freq_ == freq) {
                ++min_freq_;
            }
        }
        ++freq;
        freq_to_nodes_[freq].emplace_back(new_node);
        key_to_nodeit_[key] = prev(freq_to_nodes_[freq].end());

        return std::get<VAL>(*key_to_nodeit_[key]);
    }

   void put(int key, int value) {
        if (capa_ <= 0) {
            return;
        }

        if (get(key) != -1) {
            std::get<VAL>(*key_to_nodeit_[key]) = value;
            return;
        }

        if (size_ == capa_) {
            key_to_nodeit_.erase(std::get<KEY>(freq_to_nodes_[min_freq_].front()));
            freq_to_nodes_[min_freq_].pop_front();
            if (freq_to_nodes_[min_freq_].empty()) {
                freq_to_nodes_.erase(min_freq_);
            }
            --size_;
        }

        min_freq_ = 1;
        freq_to_nodes_[min_freq_].emplace_back(make_tuple(key, value, min_freq_));
        key_to_nodeit_[key] = prev(freq_to_nodes_[min_freq_].end());
        ++size_;
    }

private:
    enum Data {KEY, VAL, FREQ};
    int capa_;
    int size_;
    int min_freq_;
    unordered_map<int, list<tuple<int, int, int>>> freq_to_nodes_;            // freq to list of {key, val, freq}
    unordered_map<int, list<tuple<int, int, int>>::iterator> key_to_nodeit_;  // key to list iterator
};

/**
 * Your LFUCache object will be instantiated and called as such:
 * LFUCache obj = new LFUCache(capacity);
 * int param_1 = obj.get(key);
 * obj.put(key,value);
 */
<|endoftext|>


<commit_before>#include "NNConfig.h"
#include "NNApplication.h"
#include "NNLabel.h"

#include "UImanager.h"

#include "Maincharacter.h"

UImanager* UImanager::m_pInstance = nullptr;

UImanager* UImanager::GetInstance()
{
	if ( m_pInstance == nullptr )
	{
		m_pInstance = new UImanager();
	}

	return m_pInstance;
}

void UImanager::ReleaseInstance()
{
	if ( m_pInstance != nullptr )
	{
		delete m_pInstance;
		m_pInstance = nullptr;
	}
}

UImanager::UImanager(void)
{
	m_UINum = 0;		// UI  īƮ

	// FPS
	m_FPSLabel = NNLabel::Create( L"FPS : ", L" ", 20.f );
	m_FPSLabel->SetPosition( 0.f, 0.f );
	m_UIList[m_UINum++] = m_FPSLabel;

	// cost
	m_Player1CostLabel = NNLabel::Create( L"Player1's Cost : ", L" ", 20.f );
	m_Player1CostLabel->SetPosition( 0.f, 700.f );
	m_UIList[m_UINum++] = m_Player1CostLabel;

	m_Player2CostLabel = NNLabel::Create( L"Player2's Cost : ", L" ", 20.f );
	m_Player2CostLabel->SetPosition( 0.f, 100.f );
	m_UIList[m_UINum++] = m_Player2CostLabel;
}

UImanager::~UImanager(void)
{
	for (int i = 0; i < m_UINum; ++i)
	{
		delete m_UIList[i];
	}
}

void UImanager::Update( float dTime, CMaincharacter* Player1, CMaincharacter* Player2 )
{
	// FPS
	swprintf_s( m_FPSBuffer, _countof(m_FPSBuffer), L"FPS : %0.3f", NNApplication::GetInstance()->GetFPS() );
	m_FPSLabel->SetString( m_FPSBuffer );

	// cost
	swprintf_s( m_Player1CostBuffer, _countof(m_Player1CostBuffer), L"Player1's Cost : %d", (int)(Player1->GetCost()) );
	m_Player1CostLabel->SetString( m_Player1CostBuffer );
	swprintf_s( m_Player2CostBuffer, _countof(m_Player2CostBuffer), L"Player2's Cost : %d", (int)(Player2->GetCost()) );
	m_Player2CostLabel->SetString( m_Player2CostBuffer );
}

void UImanager::SetAllVisible( bool visible )
{
	for (int i = 0; i < m_UINum; ++i)
	{
		m_UIList[i]->SetVisible( visible );
	}
}

void UImanager::Render()
{
	for (int i = 0; i < m_UINum; ++i)
	{
		m_UIList[i]->Render();
	}
}
<commit_msg>!! delete -> SafeDelete<commit_after>#include "NNConfig.h"
#include "NNApplication.h"
#include "NNLabel.h"

#include "UImanager.h"

#include "Maincharacter.h"

UImanager* UImanager::m_pInstance = nullptr;

UImanager* UImanager::GetInstance()
{
	if ( m_pInstance == nullptr )
	{
		m_pInstance = new UImanager();
	}

	return m_pInstance;
}

void UImanager::ReleaseInstance()
{
	if ( m_pInstance != nullptr )
	{
		delete m_pInstance;
		m_pInstance = nullptr;
	}
}

UImanager::UImanager(void)
{
	m_UINum = 0;		// UI  īƮ

	// FPS
	m_FPSLabel = NNLabel::Create( L"FPS : ", L" ", 20.f );
	m_FPSLabel->SetPosition( 0.f, 0.f );
	m_UIList[m_UINum++] = m_FPSLabel;

	// cost
	m_Player1CostLabel = NNLabel::Create( L"Player1's Cost : ", L" ", 20.f );
	m_Player1CostLabel->SetPosition( 0.f, 700.f );
	m_UIList[m_UINum++] = m_Player1CostLabel;

	m_Player2CostLabel = NNLabel::Create( L"Player2's Cost : ", L" ", 20.f );
	m_Player2CostLabel->SetPosition( 0.f, 100.f );
	m_UIList[m_UINum++] = m_Player2CostLabel;
}

UImanager::~UImanager(void)
{
	for (int i = 0; i < m_UINum; ++i)
	{
		SafeDelete(m_UIList[i]);
	}
}

void UImanager::Update( float dTime, CMaincharacter* Player1, CMaincharacter* Player2 )
{
	// FPS
	swprintf_s( m_FPSBuffer, _countof(m_FPSBuffer), L"FPS : %0.3f", NNApplication::GetInstance()->GetFPS() );
	m_FPSLabel->SetString( m_FPSBuffer );

	// cost
	swprintf_s( m_Player1CostBuffer, _countof(m_Player1CostBuffer), L"Player1's Cost : %d", (int)(Player1->GetCost()) );
	m_Player1CostLabel->SetString( m_Player1CostBuffer );
	swprintf_s( m_Player2CostBuffer, _countof(m_Player2CostBuffer), L"Player2's Cost : %d", (int)(Player2->GetCost()) );
	m_Player2CostLabel->SetString( m_Player2CostBuffer );
}

void UImanager::SetAllVisible( bool visible )
{
	for (int i = 0; i < m_UINum; ++i)
	{
		m_UIList[i]->SetVisible( visible );
	}
}

void UImanager::Render()
{
	for (int i = 0; i < m_UINum; ++i)
	{
		m_UIList[i]->Render();
	}
}
<|endoftext|>


<commit_before>/* ------------------------------------------------------------------------ */
/* Copyright 2002-2020, OpenNebula Project, OpenNebula Systems              */
/*                                                                          */
/* 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.                                           */
/* -------------------------------------------------------------------------*/

// -----------------------------------------------------------------------------
// This file includes the SQL schema defintion for OpenNebula objects
// -----------------------------------------------------------------------------
namespace one_db
{
    /* ---------------------------------------------------------------------- */
    /* HOST TABLES                                                            */
    /* ---------------------------------------------------------------------- */
    const char * host_table = "host_pool";

    const char * host_db_names = "oid, name, body, state, uid, gid, owner_u, "
        "group_u, other_u, cid";

    const char * host_db_bootstrap =
        "CREATE TABLE IF NOT EXISTS host_pool ("
        "   oid INTEGER PRIMARY KEY, "
        "   name VARCHAR(128),"
        "   body MEDIUMTEXT,"
        "   state INTEGER,"
        "   uid INTEGER,"
        "   gid INTEGER,"
        "   owner_u INTEGER,"
        "   group_u INTEGER,"
        "   other_u INTEGER,"
        "   cid INTEGER)";

    const char * host_monitor_table = "host_monitoring";

    const char * host_monitor_db_names = "hid, last_mon_time, body";

    const char * host_monitor_db_bootstrap =
        "CREATE TABLE IF NOT EXISTS host_monitoring ("
        "   hid INTEGER,"
        "   last_mon_time INTEGER,"
        "   body MEDIUMTEXT,"
        "   PRIMARY KEY(hid, last_mon_time))";

    /* ---------------------------------------------------------------------- */
    /* VM TABLES                                                              */
    /* ---------------------------------------------------------------------- */
    const char * vm_table = "vm_pool";

    const char * vm_db_names =
        "oid, name, body, uid, gid, state, lcm_state, "
        "owner_u, group_u, other_u, short_body, search_token";

    const char * vm_db_bootstrap = "CREATE TABLE IF NOT EXISTS "
        "vm_pool (oid INTEGER PRIMARY KEY, name VARCHAR(128), body MEDIUMTEXT, "
        "uid INTEGER, gid INTEGER, state INTEGER, "
        "lcm_state INTEGER, owner_u INTEGER, group_u INTEGER, other_u INTEGER, "
        "short_body MEDIUMTEXT, search_token MEDIUMTEXT";

    const char * vm_monitor_table = "vm_monitoring";

    const char * vm_monitor_db_names = "vmid, last_poll, body";

    const char * vm_monitor_db_bootstrap = "CREATE TABLE IF NOT EXISTS "
        "vm_monitoring (vmid INTEGER, last_poll INTEGER, body MEDIUMTEXT, "
        "PRIMARY KEY(vmid, last_poll))";

    const char * vm_showback_table = "vm_showback";

    const char * vm_showback_db_names = "vmid, year, month, body";

    const char * vm_showback_db_bootstrap =
        "CREATE TABLE IF NOT EXISTS vm_showback "
        "(vmid INTEGER, year INTEGER, month INTEGER, body MEDIUMTEXT, "
        "PRIMARY KEY(vmid, year, month))";

    const char * vm_import_table = "vm_import";

    const char * vm_import_db_names = "deploy_id, vmid";

    const char * vm_import_db_bootstrap =
        "CREATE TABLE IF NOT EXISTS vm_import "
        "(deploy_id VARCHAR(128), vmid INTEGER, PRIMARY KEY(deploy_id))";

    const char * vm_group_table = "vmgroup_pool";

    const char * vm_group_db_names = "oid, name, body, uid, gid, owner_u, group_u, "
        "other_u";

    const char * vm_group_db_bootstrap = "CREATE TABLE IF NOT EXISTS vmgroup_pool "
        "(oid INTEGER PRIMARY KEY, name VARCHAR(128), body MEDIUMTEXT, "
        "uid INTEGER, gid INTEGER, owner_u INTEGER, group_u INTEGER, "
        "other_u INTEGER, UNIQUE(name,uid))";

    const char * vm_template_table = "template_pool";

    const char * vm_template_db_names =
            "oid, name, body, uid, gid, owner_u, group_u, other_u";

    const char * vm_template_db_bootstrap =
        "CREATE TABLE IF NOT EXISTS template_pool (oid INTEGER PRIMARY KEY, "
        "name VARCHAR(128), body MEDIUMTEXT, uid INTEGER, gid INTEGER, "
        "owner_u INTEGER, group_u INTEGER, other_u INTEGER)";

    /* ---------------------------------------------------------------------- */
    /* Cluster tables                                                         */
    /* ---------------------------------------------------------------------- */
    const char * cluster_table = "cluster_pool";

    const char * cluster_db_names =
        "oid, name, body, uid, gid, owner_u, group_u, other_u";

    const char * cluster_db_bootstrap = "CREATE TABLE IF NOT EXISTS cluster_pool ("
        "oid INTEGER PRIMARY KEY, name VARCHAR(128), body MEDIUMTEXT, uid INTEGER, "
        "gid INTEGER, owner_u INTEGER, group_u INTEGER, other_u INTEGER, "
        "UNIQUE(name))";

    const char * cluster_datastore_table = "cluster_datastore_relation";
    const char * cluster_datastore_db_names = "cid, oid";
    const char * cluster_datastore_db_bootstrap =
        "CREATE TABLE IF NOT EXISTS cluster_datastore_relation ("
        "cid INTEGER, oid INTEGER, PRIMARY KEY(cid, oid))";

    const char * cluster_network_table = "cluster_network_relation";
    const char * cluster_network_db_names = "cid, oid";
    const char * cluster_network_db_bootstrap =
        "CREATE TABLE IF NOT EXISTS cluster_network_relation ("
        "cid INTEGER, oid INTEGER, PRIMARY KEY(cid, oid))";

    const char * cluster_bitmap_table = "cluster_vnc_bitmap";

    /* ---------------------------------------------------------------------- */
    /* ACL tables                                                             */
    /* ---------------------------------------------------------------------- */
    const char * acl_table = "acl";

    const char * acl_db_names = "oid, user, resource, rights, zone";

    const char * acl_db_bootstrap = "CREATE TABLE IF NOT EXISTS "
        "acl (oid INT PRIMARY KEY, user BIGINT, resource BIGINT, "
        "rights BIGINT, zone BIGINT, UNIQUE(user, resource, rights, zone))";

    /* ---------------------------------------------------------------------- */
    /* Datastore tables                                                       */
    /* ---------------------------------------------------------------------- */
    const char * ds_table = "datastore_pool";

    const char * ds_db_names =
            "oid, name, body, uid, gid, owner_u, group_u, other_u";

    const char * ds_db_bootstrap =
        "CREATE TABLE IF NOT EXISTS datastore_pool ("
        "oid INTEGER PRIMARY KEY, name VARCHAR(128), body MEDIUMTEXT, uid INTEGER, "
        "gid INTEGER, owner_u INTEGER, group_u INTEGER, other_u INTEGER)";

    /* ---------------------------------------------------------------------- */
    /* Document tables                                                        */
    /* ---------------------------------------------------------------------- */
    const char * doc_table = "document_pool";

    const char * doc_db_names =
            "oid, name, body, type, uid, gid, owner_u, group_u, other_u";

    const char * doc_db_bootstrap =
        "CREATE TABLE IF NOT EXISTS document_pool (oid INTEGER PRIMARY KEY, "
        "name VARCHAR(128), body MEDIUMTEXT, type INTEGER, uid INTEGER, gid INTEGER, "
        "owner_u INTEGER, group_u INTEGER, other_u INTEGER)";

    /* ---------------------------------------------------------------------- */
    /* Group tables                                                           */
    /* ---------------------------------------------------------------------- */
    const char * group_table = "group_pool";

    const char * group_db_names =
            "oid, name, body, uid, gid, owner_u, group_u, other_u";

    const char * group_db_bootstrap = "CREATE TABLE IF NOT EXISTS group_pool ("
        "oid INTEGER PRIMARY KEY, name VARCHAR(128), body MEDIUMTEXT, uid INTEGER, "
        "gid INTEGER, owner_u INTEGER, group_u INTEGER, other_u INTEGER, "
        "UNIQUE(name))";

    /* ---------------------------------------------------------------------- */
    /* History tables                                                         */
    /* ---------------------------------------------------------------------- */
    const char * history_table = "history";

    const char * history_db_names = "vid, seq, body, stime, etime";

    const char * history_db_bootstrap = "CREATE TABLE IF NOT EXISTS "
        "history (vid INTEGER, seq INTEGER, body MEDIUMTEXT, "
        "stime INTEGER, etime INTEGER,PRIMARY KEY(vid,seq))";

    /* ---------------------------------------------------------------------- */
    /* Hook tables                                                            */
    /* ---------------------------------------------------------------------- */
    const char * hook_table = "hook_pool";

    const char * hook_db_names =
        "oid, name, body, uid, gid, owner_u, group_u, other_u, type";

    const char * hook_db_bootstrap = "CREATE TABLE IF NOT EXISTS hook_pool ("
        "oid INTEGER PRIMARY KEY, name VARCHAR(128), body MEDIUMTEXT, uid INTEGER,"
        "gid INTEGER, owner_u INTEGER, group_u INTEGER, other_u INTEGER, type INTEGER)";

    const char * hook_log_table = "hook_log";

    const char * hook_log_db_names = "hkid, exeid, timestamp, rc, body";

    const char * hook_log_db_bootstrap = "CREATE TABLE IF NOT EXISTS hook_log"
        " (hkid INTEGER, exeid INTEGER, timestamp INTEGER, rc INTEGER,"
        " body MEDIUMTEXT,PRIMARY KEY(hkid, exeid))";

    /* ---------------------------------------------------------------------- */
    /* Image tables                                                           */
    /* ---------------------------------------------------------------------- */
    const char * image_table = "image_pool";

    const char * image_db_names =
            "oid, name, body, uid, gid, owner_u, group_u, other_u";

    const char * image_db_bootstrap = "CREATE TABLE IF NOT EXISTS image_pool ("
        "oid INTEGER PRIMARY KEY, name VARCHAR(128), body MEDIUMTEXT, uid INTEGER, "
        "gid INTEGER, owner_u INTEGER, group_u INTEGER, other_u INTEGER, "
        "UNIQUE(name,uid) )";

    /* ---------------------------------------------------------------------- */
    /* Log tables                                                             */
    /* ---------------------------------------------------------------------- */
    const char * log_table = "logdb";

    const char * log_db_names = "log_index, term, sqlcmd, timestamp, fed_index, applied";

    const char * log_db_bootstrap = "CREATE TABLE IF NOT EXISTS "
        "logdb (log_index BIGINT UNSIGNED PRIMARY KEY, term INTEGER, sqlcmd MEDIUMTEXT, "
        "timestamp INTEGER, fed_index BIGINT UNSIGNED, applied BOOLEAN)";

    /* ---------------------------------------------------------------------- */
    /* Marketplace tables                                                     */
    /* ---------------------------------------------------------------------- */
    const char * mp_table = "marketplace_pool";

    const char * mp_db_names =
            "oid, name, body, uid, gid, owner_u, group_u, other_u";

    const char * mp_db_bootstrap =
        "CREATE TABLE IF NOT EXISTS marketplace_pool (oid INTEGER PRIMARY KEY, "
        "name VARCHAR(128), body MEDIUMTEXT, uid INTEGER, gid INTEGER, "
        "owner_u INTEGER, group_u INTEGER, other_u INTEGER)";

    const char * mp_app_table = "marketplaceapp_pool";

    const char * mp_app_db_names =
            "oid, name, body, uid, gid, owner_u, group_u, other_u";

    const char * mp_app_db_bootstrap =
        "CREATE TABLE IF NOT EXISTS marketplaceapp_pool (oid INTEGER PRIMARY KEY, "
        "name VARCHAR(128), body MEDIUMTEXT, uid INTEGER, gid INTEGER, "
        "owner_u INTEGER, group_u INTEGER, other_u INTEGER, UNIQUE(name,uid))";

    /* ---------------------------------------------------------------------- */
    /* Quotas tables                                                          */
    /* ---------------------------------------------------------------------- */
    const char * group_quotas_db_table = "group_quotas";
    const char * group_quotas_db_names = "group_oid, body";
    const char * group_quotas_db_oid_column = "group_oid";
    const char * group_quotas_db_bootstrap =
        "CREATE TABLE IF NOT EXISTS group_quotas ("
        "group_oid INTEGER PRIMARY KEY, body MEDIUMTEXT)";

    const char * user_quotas_db_table = "user_quotas";
    const char * user_quotas_db_names = "user_oid, body";
    const char * user_quotas_db_oid_column = "user_oid";
    const char * user_quotas_db_bootstrap =
        "CREATE TABLE IF NOT EXISTS user_quotas ("
        "user_oid INTEGER PRIMARY KEY, body MEDIUMTEXT)";

    /* ---------------------------------------------------------------------- */
    /* Security Group tables                                                  */
    /* ---------------------------------------------------------------------- */
    const char * sg_table = "secgroup_pool";

    const char * sg_db_names =
            "oid, name, body, uid, gid, owner_u, group_u, other_u";

    const char * sg_db_bootstrap = "CREATE TABLE IF NOT EXISTS secgroup_pool ("
        "oid INTEGER PRIMARY KEY, name VARCHAR(128), body MEDIUMTEXT, uid INTEGER, "
        "gid INTEGER, owner_u INTEGER, group_u INTEGER, other_u INTEGER, "
        "UNIQUE(name,uid))";

    /* ---------------------------------------------------------------------- */
    /* User tables                                                            */
    /* ---------------------------------------------------------------------- */
    const char * user_table = "user_pool";

    const char * user_db_names =
            "oid, name, body, uid, gid, owner_u, group_u, other_u";

    const char * user_db_bootstrap = "CREATE TABLE IF NOT EXISTS user_pool ("
        "oid INTEGER PRIMARY KEY, name VARCHAR(128), body MEDIUMTEXT, uid INTEGER, "
        "gid INTEGER, owner_u INTEGER, group_u INTEGER, other_u INTEGER, "
        "UNIQUE(name))";

    /* ---------------------------------------------------------------------- */
    /* VDC tables                                                             */
    /* ---------------------------------------------------------------------- */
    const char * vdc_table = "vdc_pool";

    const char * vdc_db_names =
            "oid, name, body, uid, gid, owner_u, group_u, other_u";

    const char * vdc_db_bootstrap = "CREATE TABLE IF NOT EXISTS vdc_pool ("
        "oid INTEGER PRIMARY KEY, name VARCHAR(128), body MEDIUMTEXT, uid INTEGER, "
        "gid INTEGER, owner_u INTEGER, group_u INTEGER, other_u INTEGER, "
        "UNIQUE(name))";

    /* ---------------------------------------------------------------------- */
    /* Virtual Network tables                                                 */
    /* ---------------------------------------------------------------------- */
    const char * vn_table    = "network_pool";

    const char * vn_db_names =
            "oid, name, body, uid, gid, owner_u, group_u, other_u, pid";

    const char * vn_db_bootstrap = "CREATE TABLE IF NOT EXISTS"
        " network_pool (oid INTEGER PRIMARY KEY, name VARCHAR(128),"
        " body MEDIUMTEXT, uid INTEGER, gid INTEGER,"
        " owner_u INTEGER, group_u INTEGER, other_u INTEGER,"
        " pid INTEGER, UNIQUE(name,uid))";

    const char * vn_template_table = "vn_template_pool";

    const char * vn_template_db_names =
            "oid, name, body, uid, gid, owner_u, group_u, other_u";

    const char * vn_template_db_bootstrap =
        "CREATE TABLE IF NOT EXISTS vn_template_pool (oid INTEGER PRIMARY KEY, "
        "name VARCHAR(128), body MEDIUMTEXT, uid INTEGER, gid INTEGER, "
        "owner_u INTEGER, group_u INTEGER, other_u INTEGER)";

    /* ---------------------------------------------------------------------- */
    /* Virtual Router tables                                                  */
    /* ---------------------------------------------------------------------- */
    const char * vr_table = "vrouter_pool";

    const char * vr_db_names =
            "oid, name, body, uid, gid, owner_u, group_u, other_u";

    const char * vr_db_bootstrap =
        "CREATE TABLE IF NOT EXISTS vrouter_pool (oid INTEGER PRIMARY KEY, "
        "name VARCHAR(128), body MEDIUMTEXT, uid INTEGER, gid INTEGER, "
        "owner_u INTEGER, group_u INTEGER, other_u INTEGER)";

    /* ---------------------------------------------------------------------- */
    /* Zone tables                                                            */
    /* ---------------------------------------------------------------------- */
    const char * zone_table = "zone_pool";

    const char * zone_db_names =
            "oid, name, body, uid, gid, owner_u, group_u, other_u";

    const char * zone_db_bootstrap = "CREATE TABLE IF NOT EXISTS zone_pool ("
        "oid INTEGER PRIMARY KEY, name VARCHAR(128), body MEDIUMTEXT, uid INTEGER, "
        "gid INTEGER, owner_u INTEGER, group_u INTEGER, other_u INTEGER, "
        "UNIQUE(name))";
}
<commit_msg>B #5025: Use user_oid column in acl table (#147)<commit_after>/* ------------------------------------------------------------------------ */
/* Copyright 2002-2020, OpenNebula Project, OpenNebula Systems              */
/*                                                                          */
/* 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.                                           */
/* -------------------------------------------------------------------------*/

// -----------------------------------------------------------------------------
// This file includes the SQL schema defintion for OpenNebula objects
// -----------------------------------------------------------------------------
namespace one_db
{
    /* ---------------------------------------------------------------------- */
    /* HOST TABLES                                                            */
    /* ---------------------------------------------------------------------- */
    const char * host_table = "host_pool";

    const char * host_db_names = "oid, name, body, state, uid, gid, owner_u, "
        "group_u, other_u, cid";

    const char * host_db_bootstrap =
        "CREATE TABLE IF NOT EXISTS host_pool ("
        "   oid INTEGER PRIMARY KEY, "
        "   name VARCHAR(128),"
        "   body MEDIUMTEXT,"
        "   state INTEGER,"
        "   uid INTEGER,"
        "   gid INTEGER,"
        "   owner_u INTEGER,"
        "   group_u INTEGER,"
        "   other_u INTEGER,"
        "   cid INTEGER)";

    const char * host_monitor_table = "host_monitoring";

    const char * host_monitor_db_names = "hid, last_mon_time, body";

    const char * host_monitor_db_bootstrap =
        "CREATE TABLE IF NOT EXISTS host_monitoring ("
        "   hid INTEGER,"
        "   last_mon_time INTEGER,"
        "   body MEDIUMTEXT,"
        "   PRIMARY KEY(hid, last_mon_time))";

    /* ---------------------------------------------------------------------- */
    /* VM TABLES                                                              */
    /* ---------------------------------------------------------------------- */
    const char * vm_table = "vm_pool";

    const char * vm_db_names =
        "oid, name, body, uid, gid, state, lcm_state, "
        "owner_u, group_u, other_u, short_body, search_token";

    const char * vm_db_bootstrap = "CREATE TABLE IF NOT EXISTS "
        "vm_pool (oid INTEGER PRIMARY KEY, name VARCHAR(128), body MEDIUMTEXT, "
        "uid INTEGER, gid INTEGER, state INTEGER, "
        "lcm_state INTEGER, owner_u INTEGER, group_u INTEGER, other_u INTEGER, "
        "short_body MEDIUMTEXT, search_token MEDIUMTEXT";

    const char * vm_monitor_table = "vm_monitoring";

    const char * vm_monitor_db_names = "vmid, last_poll, body";

    const char * vm_monitor_db_bootstrap = "CREATE TABLE IF NOT EXISTS "
        "vm_monitoring (vmid INTEGER, last_poll INTEGER, body MEDIUMTEXT, "
        "PRIMARY KEY(vmid, last_poll))";

    const char * vm_showback_table = "vm_showback";

    const char * vm_showback_db_names = "vmid, year, month, body";

    const char * vm_showback_db_bootstrap =
        "CREATE TABLE IF NOT EXISTS vm_showback "
        "(vmid INTEGER, year INTEGER, month INTEGER, body MEDIUMTEXT, "
        "PRIMARY KEY(vmid, year, month))";

    const char * vm_import_table = "vm_import";

    const char * vm_import_db_names = "deploy_id, vmid";

    const char * vm_import_db_bootstrap =
        "CREATE TABLE IF NOT EXISTS vm_import "
        "(deploy_id VARCHAR(128), vmid INTEGER, PRIMARY KEY(deploy_id))";

    const char * vm_group_table = "vmgroup_pool";

    const char * vm_group_db_names = "oid, name, body, uid, gid, owner_u, group_u, "
        "other_u";

    const char * vm_group_db_bootstrap = "CREATE TABLE IF NOT EXISTS vmgroup_pool "
        "(oid INTEGER PRIMARY KEY, name VARCHAR(128), body MEDIUMTEXT, "
        "uid INTEGER, gid INTEGER, owner_u INTEGER, group_u INTEGER, "
        "other_u INTEGER, UNIQUE(name,uid))";

    const char * vm_template_table = "template_pool";

    const char * vm_template_db_names =
            "oid, name, body, uid, gid, owner_u, group_u, other_u";

    const char * vm_template_db_bootstrap =
        "CREATE TABLE IF NOT EXISTS template_pool (oid INTEGER PRIMARY KEY, "
        "name VARCHAR(128), body MEDIUMTEXT, uid INTEGER, gid INTEGER, "
        "owner_u INTEGER, group_u INTEGER, other_u INTEGER)";

    /* ---------------------------------------------------------------------- */
    /* Cluster tables                                                         */
    /* ---------------------------------------------------------------------- */
    const char * cluster_table = "cluster_pool";

    const char * cluster_db_names =
        "oid, name, body, uid, gid, owner_u, group_u, other_u";

    const char * cluster_db_bootstrap = "CREATE TABLE IF NOT EXISTS cluster_pool ("
        "oid INTEGER PRIMARY KEY, name VARCHAR(128), body MEDIUMTEXT, uid INTEGER, "
        "gid INTEGER, owner_u INTEGER, group_u INTEGER, other_u INTEGER, "
        "UNIQUE(name))";

    const char * cluster_datastore_table = "cluster_datastore_relation";
    const char * cluster_datastore_db_names = "cid, oid";
    const char * cluster_datastore_db_bootstrap =
        "CREATE TABLE IF NOT EXISTS cluster_datastore_relation ("
        "cid INTEGER, oid INTEGER, PRIMARY KEY(cid, oid))";

    const char * cluster_network_table = "cluster_network_relation";
    const char * cluster_network_db_names = "cid, oid";
    const char * cluster_network_db_bootstrap =
        "CREATE TABLE IF NOT EXISTS cluster_network_relation ("
        "cid INTEGER, oid INTEGER, PRIMARY KEY(cid, oid))";

    const char * cluster_bitmap_table = "cluster_vnc_bitmap";

    /* ---------------------------------------------------------------------- */
    /* ACL tables                                                             */
    /* ---------------------------------------------------------------------- */
    const char * acl_table = "acl";

    const char * acl_db_names = "oid, user_oid, resource, rights, zone";

    const char * acl_db_bootstrap = "CREATE TABLE IF NOT EXISTS "
        "acl (oid INT PRIMARY KEY, user_oid BIGINT, resource BIGINT, "
        "rights BIGINT, zone BIGINT, UNIQUE(user_oid, resource, rights, zone))";

    /* ---------------------------------------------------------------------- */
    /* Datastore tables                                                       */
    /* ---------------------------------------------------------------------- */
    const char * ds_table = "datastore_pool";

    const char * ds_db_names =
            "oid, name, body, uid, gid, owner_u, group_u, other_u";

    const char * ds_db_bootstrap =
        "CREATE TABLE IF NOT EXISTS datastore_pool ("
        "oid INTEGER PRIMARY KEY, name VARCHAR(128), body MEDIUMTEXT, uid INTEGER, "
        "gid INTEGER, owner_u INTEGER, group_u INTEGER, other_u INTEGER)";

    /* ---------------------------------------------------------------------- */
    /* Document tables                                                        */
    /* ---------------------------------------------------------------------- */
    const char * doc_table = "document_pool";

    const char * doc_db_names =
            "oid, name, body, type, uid, gid, owner_u, group_u, other_u";

    const char * doc_db_bootstrap =
        "CREATE TABLE IF NOT EXISTS document_pool (oid INTEGER PRIMARY KEY, "
        "name VARCHAR(128), body MEDIUMTEXT, type INTEGER, uid INTEGER, gid INTEGER, "
        "owner_u INTEGER, group_u INTEGER, other_u INTEGER)";

    /* ---------------------------------------------------------------------- */
    /* Group tables                                                           */
    /* ---------------------------------------------------------------------- */
    const char * group_table = "group_pool";

    const char * group_db_names =
            "oid, name, body, uid, gid, owner_u, group_u, other_u";

    const char * group_db_bootstrap = "CREATE TABLE IF NOT EXISTS group_pool ("
        "oid INTEGER PRIMARY KEY, name VARCHAR(128), body MEDIUMTEXT, uid INTEGER, "
        "gid INTEGER, owner_u INTEGER, group_u INTEGER, other_u INTEGER, "
        "UNIQUE(name))";

    /* ---------------------------------------------------------------------- */
    /* History tables                                                         */
    /* ---------------------------------------------------------------------- */
    const char * history_table = "history";

    const char * history_db_names = "vid, seq, body, stime, etime";

    const char * history_db_bootstrap = "CREATE TABLE IF NOT EXISTS "
        "history (vid INTEGER, seq INTEGER, body MEDIUMTEXT, "
        "stime INTEGER, etime INTEGER,PRIMARY KEY(vid,seq))";

    /* ---------------------------------------------------------------------- */
    /* Hook tables                                                            */
    /* ---------------------------------------------------------------------- */
    const char * hook_table = "hook_pool";

    const char * hook_db_names =
        "oid, name, body, uid, gid, owner_u, group_u, other_u, type";

    const char * hook_db_bootstrap = "CREATE TABLE IF NOT EXISTS hook_pool ("
        "oid INTEGER PRIMARY KEY, name VARCHAR(128), body MEDIUMTEXT, uid INTEGER,"
        "gid INTEGER, owner_u INTEGER, group_u INTEGER, other_u INTEGER, type INTEGER)";

    const char * hook_log_table = "hook_log";

    const char * hook_log_db_names = "hkid, exeid, timestamp, rc, body";

    const char * hook_log_db_bootstrap = "CREATE TABLE IF NOT EXISTS hook_log"
        " (hkid INTEGER, exeid INTEGER, timestamp INTEGER, rc INTEGER,"
        " body MEDIUMTEXT,PRIMARY KEY(hkid, exeid))";

    /* ---------------------------------------------------------------------- */
    /* Image tables                                                           */
    /* ---------------------------------------------------------------------- */
    const char * image_table = "image_pool";

    const char * image_db_names =
            "oid, name, body, uid, gid, owner_u, group_u, other_u";

    const char * image_db_bootstrap = "CREATE TABLE IF NOT EXISTS image_pool ("
        "oid INTEGER PRIMARY KEY, name VARCHAR(128), body MEDIUMTEXT, uid INTEGER, "
        "gid INTEGER, owner_u INTEGER, group_u INTEGER, other_u INTEGER, "
        "UNIQUE(name,uid) )";

    /* ---------------------------------------------------------------------- */
    /* Log tables                                                             */
    /* ---------------------------------------------------------------------- */
    const char * log_table = "logdb";

    const char * log_db_names = "log_index, term, sqlcmd, timestamp, fed_index, applied";

    const char * log_db_bootstrap = "CREATE TABLE IF NOT EXISTS "
        "logdb (log_index BIGINT UNSIGNED PRIMARY KEY, term INTEGER, sqlcmd MEDIUMTEXT, "
        "timestamp INTEGER, fed_index BIGINT UNSIGNED, applied BOOLEAN)";

    /* ---------------------------------------------------------------------- */
    /* Marketplace tables                                                     */
    /* ---------------------------------------------------------------------- */
    const char * mp_table = "marketplace_pool";

    const char * mp_db_names =
            "oid, name, body, uid, gid, owner_u, group_u, other_u";

    const char * mp_db_bootstrap =
        "CREATE TABLE IF NOT EXISTS marketplace_pool (oid INTEGER PRIMARY KEY, "
        "name VARCHAR(128), body MEDIUMTEXT, uid INTEGER, gid INTEGER, "
        "owner_u INTEGER, group_u INTEGER, other_u INTEGER)";

    const char * mp_app_table = "marketplaceapp_pool";

    const char * mp_app_db_names =
            "oid, name, body, uid, gid, owner_u, group_u, other_u";

    const char * mp_app_db_bootstrap =
        "CREATE TABLE IF NOT EXISTS marketplaceapp_pool (oid INTEGER PRIMARY KEY, "
        "name VARCHAR(128), body MEDIUMTEXT, uid INTEGER, gid INTEGER, "
        "owner_u INTEGER, group_u INTEGER, other_u INTEGER, UNIQUE(name,uid))";

    /* ---------------------------------------------------------------------- */
    /* Quotas tables                                                          */
    /* ---------------------------------------------------------------------- */
    const char * group_quotas_db_table = "group_quotas";
    const char * group_quotas_db_names = "group_oid, body";
    const char * group_quotas_db_oid_column = "group_oid";
    const char * group_quotas_db_bootstrap =
        "CREATE TABLE IF NOT EXISTS group_quotas ("
        "group_oid INTEGER PRIMARY KEY, body MEDIUMTEXT)";

    const char * user_quotas_db_table = "user_quotas";
    const char * user_quotas_db_names = "user_oid, body";
    const char * user_quotas_db_oid_column = "user_oid";
    const char * user_quotas_db_bootstrap =
        "CREATE TABLE IF NOT EXISTS user_quotas ("
        "user_oid INTEGER PRIMARY KEY, body MEDIUMTEXT)";

    /* ---------------------------------------------------------------------- */
    /* Security Group tables                                                  */
    /* ---------------------------------------------------------------------- */
    const char * sg_table = "secgroup_pool";

    const char * sg_db_names =
            "oid, name, body, uid, gid, owner_u, group_u, other_u";

    const char * sg_db_bootstrap = "CREATE TABLE IF NOT EXISTS secgroup_pool ("
        "oid INTEGER PRIMARY KEY, name VARCHAR(128), body MEDIUMTEXT, uid INTEGER, "
        "gid INTEGER, owner_u INTEGER, group_u INTEGER, other_u INTEGER, "
        "UNIQUE(name,uid))";

    /* ---------------------------------------------------------------------- */
    /* User tables                                                            */
    /* ---------------------------------------------------------------------- */
    const char * user_table = "user_pool";

    const char * user_db_names =
            "oid, name, body, uid, gid, owner_u, group_u, other_u";

    const char * user_db_bootstrap = "CREATE TABLE IF NOT EXISTS user_pool ("
        "oid INTEGER PRIMARY KEY, name VARCHAR(128), body MEDIUMTEXT, uid INTEGER, "
        "gid INTEGER, owner_u INTEGER, group_u INTEGER, other_u INTEGER, "
        "UNIQUE(name))";

    /* ---------------------------------------------------------------------- */
    /* VDC tables                                                             */
    /* ---------------------------------------------------------------------- */
    const char * vdc_table = "vdc_pool";

    const char * vdc_db_names =
            "oid, name, body, uid, gid, owner_u, group_u, other_u";

    const char * vdc_db_bootstrap = "CREATE TABLE IF NOT EXISTS vdc_pool ("
        "oid INTEGER PRIMARY KEY, name VARCHAR(128), body MEDIUMTEXT, uid INTEGER, "
        "gid INTEGER, owner_u INTEGER, group_u INTEGER, other_u INTEGER, "
        "UNIQUE(name))";

    /* ---------------------------------------------------------------------- */
    /* Virtual Network tables                                                 */
    /* ---------------------------------------------------------------------- */
    const char * vn_table    = "network_pool";

    const char * vn_db_names =
            "oid, name, body, uid, gid, owner_u, group_u, other_u, pid";

    const char * vn_db_bootstrap = "CREATE TABLE IF NOT EXISTS"
        " network_pool (oid INTEGER PRIMARY KEY, name VARCHAR(128),"
        " body MEDIUMTEXT, uid INTEGER, gid INTEGER,"
        " owner_u INTEGER, group_u INTEGER, other_u INTEGER,"
        " pid INTEGER, UNIQUE(name,uid))";

    const char * vn_template_table = "vn_template_pool";

    const char * vn_template_db_names =
            "oid, name, body, uid, gid, owner_u, group_u, other_u";

    const char * vn_template_db_bootstrap =
        "CREATE TABLE IF NOT EXISTS vn_template_pool (oid INTEGER PRIMARY KEY, "
        "name VARCHAR(128), body MEDIUMTEXT, uid INTEGER, gid INTEGER, "
        "owner_u INTEGER, group_u INTEGER, other_u INTEGER)";

    /* ---------------------------------------------------------------------- */
    /* Virtual Router tables                                                  */
    /* ---------------------------------------------------------------------- */
    const char * vr_table = "vrouter_pool";

    const char * vr_db_names =
            "oid, name, body, uid, gid, owner_u, group_u, other_u";

    const char * vr_db_bootstrap =
        "CREATE TABLE IF NOT EXISTS vrouter_pool (oid INTEGER PRIMARY KEY, "
        "name VARCHAR(128), body MEDIUMTEXT, uid INTEGER, gid INTEGER, "
        "owner_u INTEGER, group_u INTEGER, other_u INTEGER)";

    /* ---------------------------------------------------------------------- */
    /* Zone tables                                                            */
    /* ---------------------------------------------------------------------- */
    const char * zone_table = "zone_pool";

    const char * zone_db_names =
            "oid, name, body, uid, gid, owner_u, group_u, other_u";

    const char * zone_db_bootstrap = "CREATE TABLE IF NOT EXISTS zone_pool ("
        "oid INTEGER PRIMARY KEY, name VARCHAR(128), body MEDIUMTEXT, uid INTEGER, "
        "gid INTEGER, owner_u INTEGER, group_u INTEGER, other_u INTEGER, "
        "UNIQUE(name))";
}
<|endoftext|>


<commit_before>#pragma once

#include <iostream>

#include "binary.hxx"
#include "bitnode.hxx"

namespace despairagus {
	namespace bitwisetrie {
		using std::cout;
		using std::ostream;

		template <typename A>
		class bitwisetrie final {
			template<typename B>
			using conref = const B &;

			using bitA = std::bitset<sizeof(A) << 3>;
			using byte = unsigned char;
			using bit = bool;

			constexpr static const size_t limit{sizeof(A) << 3};

		public:
			explicit bitwisetrie(void) = delete;

		private:
			bitnode<A>* root;
		};
	}
}<commit_msg>insert functionality<commit_after>#pragma once

#include <iostream>

#include "binary.hxx"
#include "bitnode.hxx"

namespace despairagus {
	namespace bitwisetrie {
		using std::cout;
		using std::ostream;

		template <typename A>
		class bitwisetrie final {
			template<typename B>
			using conref = const B &;

			using bitA = std::bitset<sizeof(A) << 3>;
			using byte = unsigned char;
			using bit = bool;

			constexpr static const size_t limit{sizeof(A) << 3};

			static inline bitnode<A>* navigate(bitnode<A>* currNode, conref<A> data) {
				return bitwisetrie<A>::navigate(currNode, data, 0);
			}

			static inline bitnode<A>* navigate(bitnode<A>* currNode, conref<A> data, conref<size_t> idx) {
				binary<A> bitHolder{data};

				return bitwisetrie<A>::navigate(currNode, data, bitHolder, idx);
			}

			static bitnode<A>* navigate(bitnode<A>* currNode, conref<A> data, conref<binary<A>> bits, conref<size_t> idx) {
				if (idx < limit) {
					if (bits.getBit(idx)) {
						if (currNode->getOne() == nullptr) {
							currNode->setOne(new bitnode<A>);
						}

						return bitwisetrie<A>::navigate(currNode->getOne(), data, bits, idx + 1);
					} else {
						if (currNode->getZero() == nullptr) {
							currNode->setZero(new bitnode<A>);
						}

						return bitwisetrie<A>::navigate(currNode->getZero(), data, bits, idx + 1);
					}
				}

				return currNode;
			}

		public:
			explicit bitwisetrie(void) : root{nullptr} {}

			bool insert(conref<A> a) noexcept {
				bitnode<A>* leafNode = bitwisetrie<A>::navigate(root, a);

				if (leafNode->isNotEmpty()) {
					leafNode->setData(a);
				}

				return leafNode->isEmpty();
			}

		private:
			bitnode<A>* root;
		};
	}
}<|endoftext|>


<commit_before>#pragma once

#include <iostream>

#include "binary.hxx"
#include "bitnode.hxx"

namespace despairagus {
	namespace bitwisetrie {
		using std::cout;
		using std::ostream;

		template <typename A>
		class bitwisetrie final {
			template<typename B>
			using conref = const B &;

			using bitA = std::bitset<sizeof(A) << 3>;
			using byte = unsigned char;
			using bit = bool;

			constexpr static const size_t limit{sizeof(A) << 3};

			static inline bitnode<A>* navigate(bitnode<A>* currNode, conref<A> data) {
				return bitwisetrie<A>::navigate(currNode, data, 0);
			}

			static inline bitnode<A>* navigate(bitnode<A>* currNode, conref<A> data, conref<size_t> idx) {
				binary<A> bitHolder{data};

				return bitwisetrie<A>::navigate(currNode, data, bitHolder, idx);
			}

			static bitnode<A>* navigate(bitnode<A>* currNode, conref<A> data, conref<binary<A>> bits, conref<size_t> idx) {
				if (idx < limit) {
					if (bits.getBit(idx)) {
						if (currNode->getOne() == nullptr) {
							currNode->setOne(new bitnode<A>);
						}

						return bitwisetrie<A>::navigate(currNode->getOne(), data, bits, idx + 1);
					} else {
						if (currNode->getZero() == nullptr) {
							currNode->setZero(new bitnode<A>);
						}

						return bitwisetrie<A>::navigate(currNode->getZero(), data, bits, idx + 1);
					}
				}

				return currNode;
			}

		public:
			explicit bitwisetrie(void) : root{new bitnode<A>} {}

			bool insertOnEmpty(conref<A> a) noexcept {
				bitnode<A>* leafNode = bitwisetrie<A>::navigate(root, a);

				if (leafNode->isEmpty()) {
					leafNode->setData(a);

					return true;
				}

				return false;
			}

		private:
			bitnode<A>* root;
		};
	}
}<commit_msg>do not pass data since its not needed<commit_after>#pragma once

#include <iostream>

#include "binary.hxx"
#include "bitnode.hxx"

namespace despairagus {
	namespace bitwisetrie {
		using std::cout;
		using std::ostream;

		template <typename A>
		class bitwisetrie final {
			template<typename B>
			using conref = const B &;

			using bitA = std::bitset<sizeof(A) << 3>;
			using byte = unsigned char;
			using bit = bool;

			constexpr static const size_t limit{sizeof(A) << 3};

			static inline bitnode<A>* navigate(bitnode<A>* currNode, conref<A> data) {
				return bitwisetrie<A>::navigate(currNode, data, 0);
			}

			static inline bitnode<A>* navigate(bitnode<A>* currNode, conref<A> data, conref<size_t> idx) {
				binary<A> bitHolder{data};

				return bitwisetrie<A>::navigate(currNode, bitHolder, idx);
			}

			static bitnode<A>* navigate(bitnode<A>* currNode, conref<binary<A>> bits, conref<size_t> idx) {
				if (idx < limit) {
					if (bits.getBit(idx)) {
						if (currNode->getOne() == nullptr) {
							currNode->setOne(new bitnode<A>);
						}

						return bitwisetrie<A>::navigate(currNode->getOne(), data, bits, idx + 1);
					} else {
						if (currNode->getZero() == nullptr) {
							currNode->setZero(new bitnode<A>);
						}

						return bitwisetrie<A>::navigate(currNode->getZero(), data, bits, idx + 1);
					}
				}

				return currNode;
			}

		public:
			explicit bitwisetrie(void) : root{new bitnode<A>} {}

			bool insertOnEmpty(conref<A> a) noexcept {
				bitnode<A>* leafNode = bitwisetrie<A>::navigate(root, a);

				if (leafNode->isEmpty()) {
					leafNode->setData(a);

					return true;
				}

				return false;
			}

		private:
			bitnode<A>* root;
		};
	}
}<|endoftext|>


<commit_before>#include "application.h"
using namespace AhoViewer;

#include "booru/site.h"
#include "config.h"
#include "imagelist.h"
#include "mainwindow.h"
#include "settings.h"

#ifdef HAVE_LIBPEAS
#include "plugin/manager.h"
#endif // HAVE_LIBPEAS

#include <curl/curl.h>
// This can be removed once it's implemented in C++20
#include <date/tz.h>
#include <gtkmm.h>
#include <iostream>
#include <libxml/parser.h>

#ifdef USE_OPENSSL
#include <openssl/opensslv.h>
#if (OPENSSL_VERSION_NUMBER < 0x10100000L)
#include <deque>
#include <openssl/crypto.h>
#include <shared_mutex>

std::deque<std::shared_mutex> locks;

static void lock_callback(int mode, int type, const char*, int)
{
    if ((mode & CRYPTO_LOCK))
    {
        if ((mode & CRYPTO_READ))
            locks[type].lock_shared();
        else
            locks[type].lock();
    }
    else
    {
        if ((mode & CRYPTO_READ))
            locks[type].unlock_shared();
        else
            locks[type].unlock();
    }
}

static unsigned long thread_id()
{
    return static_cast<unsigned long>(pthread_self());
}

static void init_openssl_locks()
{
    locks.resize(CRYPTO_num_locks());
    CRYPTO_set_id_callback(&thread_id);
    CRYPTO_set_locking_callback(&lock_callback);
}
#endif // OPENSSL_VERSION_NUMBER < 0x10100000L
#endif // USE_OPENSSL

#ifdef USE_GNUTLS
#include <gcrypt.h>
#if (GCRYPT_VERSION_NUMBER < 0x010600)
GCRY_THREAD_OPTION_PTHREAD_IMPL;

void init_gnutls_locks()
{
    gcry_control(GCRYCTL_SET_THREAD_CBS, &gcry_threads_pthread);
}
#endif // GCRYPT_VERSION_NUMBER < 0x010600
#endif // USE_GNUTLS

#ifdef HAVE_GSTREAMER
#include <gst/gst.h>
#endif // HAVE_GSTREAMER

Application::Application()
    : Gtk::Application("com.github.ahodesuka.ahoviewer", Gio::APPLICATION_HANDLES_OPEN)
#ifdef HAVE_LIBPEAS
      ,
      m_PluginManager
{
    std::make_unique<Plugin::Manager>()
}
#endif // HAVE_LIBPEAS
{
    // Disgusting win32 api to start dbus-daemon and make it close when
    // the ahoviewer process ends
#ifdef _WIN32
    HANDLE job                                = CreateJobObject(NULL, NULL);
    JOBOBJECT_EXTENDED_LIMIT_INFORMATION jeli = { 0 };
    PROCESS_INFORMATION pi                    = { 0 };
    STARTUPINFO si                            = { 0 };
    char cmd[]                                = "dbus-daemon.exe --session";

    jeli.BasicLimitInformation.LimitFlags = JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE;
    SetInformationJobObject(job, JobObjectExtendedLimitInformation, &jeli, sizeof(jeli));
    si.cb = sizeof(si);

    if (CreateProcess(NULL,
                      cmd,
                      NULL,
                      NULL,
                      FALSE,
                      CREATE_NO_WINDOW | CREATE_SUSPENDED | CREATE_BREAKAWAY_FROM_JOB,
                      NULL,
                      NULL,
                      &si,
                      &pi))
    {
        AssignProcessToJobObject(job, pi.hProcess);
        ResumeThread(pi.hThread);
    }
#endif // _WIN32
    // The ImageBox needs this, disabling it is silly unless proven otherwise
    Glib::setenv("GTK_OVERLAY_SCROLLING", "", true);
    Glib::set_application_name(PACKAGE);

    signal_shutdown().connect(sigc::mem_fun(*this, &Application::on_shutdown));
}

Application& Application::get_instance()
{
    static Application app;
    return app;
}

MainWindow* Application::create_window()
{
    Glib::RefPtr<Gtk::Builder> builder{ Gtk::Builder::create() };

    try
    {
        builder->add_from_resource("/ui/ahoviewer.ui");
    }
    catch (const Glib::Error& ex)
    {
        std::cerr << "Gtk::Builder::add_from_resource: " << ex.what() << std::endl;
        return nullptr;
    }

    MainWindow* w{ nullptr };
    builder->get_widget_derived("MainWindow", w);

    if (!w)
        throw std::runtime_error("Failed to create window");

    auto window{ static_cast<Gtk::Window*>(w) };
    add_window(*window);

    return w;
}

int Application::run(int argc, char** argv)
{
    register_application();

    if (!is_remote())
    {
        gtk_init(&argc, &argv);
#ifdef HAVE_GSTREAMER
        gst_init(&argc, &argv);
#endif // HAVE_GSTREAMER
    }

    return Gtk::Application::run(argc, argv);
}

void Application::on_activate()
{
    auto w{ create_window() };

    if (get_windows().size() == 1)
        w->restore_last_file();

    Gtk::Application::on_activate();
}

// Finds the first window with no local image list or creates a
// new window and then opens the file
void Application::on_open(const std::vector<Glib::RefPtr<Gio::File>>& f, const Glib::ustring&)
{
    auto windows{ get_windows() };
    auto it{ std::find_if(windows.cbegin(), windows.cend(), [](Gtk::Window* w) {
        return static_cast<MainWindow*>(w)->m_LocalImageList->empty();
    }) };

    if (it == windows.cend())
    {
        auto w{ create_window() };
        w->open_file(f.front()->get_path());
    }
    else
    {
        static_cast<MainWindow*>(*it)->open_file(f.front()->get_path());
    }
}

void Application::on_startup()
{
    LIBXML_TEST_VERSION

    curl_global_init(CURL_GLOBAL_DEFAULT);

    curl_version_info_data* ver_info{ curl_version_info(CURLVERSION_NOW) };
    std::string ssl_lib{ ver_info->ssl_version };

#if defined(USE_OPENSSL) && (OPENSSL_VERSION_NUMBER < 0x10100000L)
    if (ssl_lib.find("OpenSSL") != std::string::npos)
        init_openssl_locks();
#endif // defined(USE_OPENSSL) && (OPENSSL_VERSION_NUMBER < 0x10100000L)

#if defined(USE_GNUTLS) && GCRYPT_VERSION_NUMBER < 0x010600
    if (ssl_lib.find("GnuTLS") != std::string::npos)
        init_gnutls_locks();
#endif // defined(USE_GNUTLS) && GCRYPT_VERSION_NUMBER < 0x010600

    Gtk::Main::init_gtkmm_internals();

    Gtk::Application::on_startup();

    date::set_install(Glib::build_filename(Glib::get_user_cache_dir(), PACKAGE, "tzdata"));
    std::thread{ []() {
        try
        {
            date::get_tzdb();
        }
        catch (const std::runtime_error& e)
        {
            std::cerr << "Failed to fetch IANA timezone database, times will be displayed in UTC"
                      << std::endl;
        }
    } }.detach();

    // Load this after plugins have been loaded so the active plugins can have their keybindings set
    Settings.load_keybindings();
}

void Application::on_window_added(Gtk::Window* w)
{
    if (get_windows().size() == 0)
        static_cast<MainWindow*>(w)->m_OriginalWindow = true;

    Gtk::Application::on_window_added(w);
}

void Application::on_window_removed(Gtk::Window* w)
{
    Gtk::Application::on_window_removed(w);
    delete w;

    auto windows{ get_windows() };

    // Set a new original window if the previous was closed
    if (windows.size() > 0)
    {
        auto it{ std::find_if(windows.cbegin(), windows.cend(), [](Gtk::Window* mw) {
            return static_cast<MainWindow*>(mw)->m_OriginalWindow;
        }) };

        if (it == windows.cend())
            static_cast<MainWindow*>(windows.front())->m_OriginalWindow = true;
    }
}

void Application::on_shutdown()
{
    for (const std::shared_ptr<Booru::Site>& site : Settings.get_sites())
        site->save_tags();
}
<commit_msg>application: Remove CreateProcess call for dbus-daemon<commit_after>#include "application.h"
using namespace AhoViewer;

#include "booru/site.h"
#include "config.h"
#include "imagelist.h"
#include "mainwindow.h"
#include "settings.h"

#ifdef HAVE_LIBPEAS
#include "plugin/manager.h"
#endif // HAVE_LIBPEAS

#include <curl/curl.h>
// This can be removed once it's implemented in C++20
#include <date/tz.h>
#include <gtkmm.h>
#include <iostream>
#include <libxml/parser.h>

#ifdef USE_OPENSSL
#include <openssl/opensslv.h>
#if (OPENSSL_VERSION_NUMBER < 0x10100000L)
#include <deque>
#include <openssl/crypto.h>
#include <shared_mutex>

std::deque<std::shared_mutex> locks;

static void lock_callback(int mode, int type, const char*, int)
{
    if ((mode & CRYPTO_LOCK))
    {
        if ((mode & CRYPTO_READ))
            locks[type].lock_shared();
        else
            locks[type].lock();
    }
    else
    {
        if ((mode & CRYPTO_READ))
            locks[type].unlock_shared();
        else
            locks[type].unlock();
    }
}

static unsigned long thread_id()
{
    return static_cast<unsigned long>(pthread_self());
}

static void init_openssl_locks()
{
    locks.resize(CRYPTO_num_locks());
    CRYPTO_set_id_callback(&thread_id);
    CRYPTO_set_locking_callback(&lock_callback);
}
#endif // OPENSSL_VERSION_NUMBER < 0x10100000L
#endif // USE_OPENSSL

#ifdef USE_GNUTLS
#include <gcrypt.h>
#if (GCRYPT_VERSION_NUMBER < 0x010600)
GCRY_THREAD_OPTION_PTHREAD_IMPL;

void init_gnutls_locks()
{
    gcry_control(GCRYCTL_SET_THREAD_CBS, &gcry_threads_pthread);
}
#endif // GCRYPT_VERSION_NUMBER < 0x010600
#endif // USE_GNUTLS

#ifdef HAVE_GSTREAMER
#include <gst/gst.h>
#endif // HAVE_GSTREAMER

Application::Application()
    : Gtk::Application("com.github.ahodesuka.ahoviewer", Gio::APPLICATION_HANDLES_OPEN)
#ifdef HAVE_LIBPEAS
      ,
      m_PluginManager
{
    std::make_unique<Plugin::Manager>()
}
#endif // HAVE_LIBPEAS
{
    // The ImageBox needs this, disabling it is silly unless proven otherwise
    Glib::setenv("GTK_OVERLAY_SCROLLING", "", true);
    Glib::set_application_name(PACKAGE);

    signal_shutdown().connect(sigc::mem_fun(*this, &Application::on_shutdown));
}

Application& Application::get_instance()
{
    static Application app;
    return app;
}

MainWindow* Application::create_window()
{
    Glib::RefPtr<Gtk::Builder> builder{ Gtk::Builder::create() };

    try
    {
        builder->add_from_resource("/ui/ahoviewer.ui");
    }
    catch (const Glib::Error& ex)
    {
        std::cerr << "Gtk::Builder::add_from_resource: " << ex.what() << std::endl;
        return nullptr;
    }

    MainWindow* w{ nullptr };
    builder->get_widget_derived("MainWindow", w);

    if (!w)
        throw std::runtime_error("Failed to create window");

    auto window{ static_cast<Gtk::Window*>(w) };
    add_window(*window);

    return w;
}

int Application::run(int argc, char** argv)
{
    register_application();

    if (!is_remote())
    {
        gtk_init(&argc, &argv);
#ifdef HAVE_GSTREAMER
        gst_init(&argc, &argv);
#endif // HAVE_GSTREAMER
    }

    return Gtk::Application::run(argc, argv);
}

void Application::on_activate()
{
    auto w{ create_window() };

    if (get_windows().size() == 1)
        w->restore_last_file();

    Gtk::Application::on_activate();
}

// Finds the first window with no local image list or creates a
// new window and then opens the file
void Application::on_open(const std::vector<Glib::RefPtr<Gio::File>>& f, const Glib::ustring&)
{
    auto windows{ get_windows() };
    auto it{ std::find_if(windows.cbegin(), windows.cend(), [](Gtk::Window* w) {
        return static_cast<MainWindow*>(w)->m_LocalImageList->empty();
    }) };

    if (it == windows.cend())
    {
        auto w{ create_window() };
        w->open_file(f.front()->get_path());
    }
    else
    {
        static_cast<MainWindow*>(*it)->open_file(f.front()->get_path());
    }
}

void Application::on_startup()
{
    LIBXML_TEST_VERSION

    curl_global_init(CURL_GLOBAL_DEFAULT);

    curl_version_info_data* ver_info{ curl_version_info(CURLVERSION_NOW) };
    std::string ssl_lib{ ver_info->ssl_version };

#if defined(USE_OPENSSL) && (OPENSSL_VERSION_NUMBER < 0x10100000L)
    if (ssl_lib.find("OpenSSL") != std::string::npos)
        init_openssl_locks();
#endif // defined(USE_OPENSSL) && (OPENSSL_VERSION_NUMBER < 0x10100000L)

#if defined(USE_GNUTLS) && GCRYPT_VERSION_NUMBER < 0x010600
    if (ssl_lib.find("GnuTLS") != std::string::npos)
        init_gnutls_locks();
#endif // defined(USE_GNUTLS) && GCRYPT_VERSION_NUMBER < 0x010600

    Gtk::Main::init_gtkmm_internals();

    Gtk::Application::on_startup();

    date::set_install(Glib::build_filename(Glib::get_user_cache_dir(), PACKAGE, "tzdata"));
    std::thread{ []() {
        try
        {
            date::get_tzdb();
        }
        catch (const std::runtime_error& e)
        {
            std::cerr << "Failed to fetch IANA timezone database, times will be displayed in UTC"
                      << std::endl;
        }
    } }.detach();

    // Load this after plugins have been loaded so the active plugins can have their keybindings set
    Settings.load_keybindings();
}

void Application::on_window_added(Gtk::Window* w)
{
    if (get_windows().size() == 0)
        static_cast<MainWindow*>(w)->m_OriginalWindow = true;

    Gtk::Application::on_window_added(w);
}

void Application::on_window_removed(Gtk::Window* w)
{
    Gtk::Application::on_window_removed(w);
    delete w;

    auto windows{ get_windows() };

    // Set a new original window if the previous was closed
    if (windows.size() > 0)
    {
        auto it{ std::find_if(windows.cbegin(), windows.cend(), [](Gtk::Window* mw) {
            return static_cast<MainWindow*>(mw)->m_OriginalWindow;
        }) };

        if (it == windows.cend())
            static_cast<MainWindow*>(windows.front())->m_OriginalWindow = true;
    }
}

void Application::on_shutdown()
{
    for (const std::shared_ptr<Booru::Site>& site : Settings.get_sites())
        site->save_tags();
}
<|endoftext|>


<commit_before>#include "hdfscpp.h"

#include <iostream>

#include <assert.h>

#include "filebuf.h"
#include <vector>

#include <zlib.h>
/**********************************************************************/

/** Reads a int written by java's DataOutput#writeInt
 *
 * FIXME Move to propper namespace
 */
inline int32_t ReadInt(tmacam::filebuf* data) {
	assert(sizeof(int32_t) == 4);
	const char* bytes = data->read(sizeof(int32_t));
	return (((bytes[0] & 0xff) << 24) | ((bytes[1] & 0xff) << 16) |
		 ((bytes[2] & 0xff) << 8) | (bytes[3] & 0xff));
}

/**********************************************************************/
/*
class HdfsDumpReader {
private:
    // No copy, no atribution and no default constructor for this class
    DISALLOW_COPY_AND_ASSIGN(HdfsDumpReader);
    HdfsDumpReader();
};
*/

/**********************************************************************/

void ShowUsage()
{
    std::cerr << "Usage: hdfsls <path> " << std::endl;
}

int main(int argc, char* argv[])
{
    using namespace tmacam;

    // Check command line arguments
    if ( argc != 2) {
        std::cerr << "Wrong number of arguments" << std::endl;
        ShowUsage();
        exit(EXIT_FAILURE);
    }
    const char* path = argv[1];

    // Connect to HDFS / get filesystem handle
    hdfs::FileSystem fs;

    // Path is a file, right?
    if (!fs.Exists(path)) {
        std::cerr << "Path '" << path << "' does not exist." << std::endl;
        exit(EXIT_FAILURE);
    }
    hdfs::FileInfoList path_info;
    fs.GetPathInfo(path, &path_info);
    if (path_info->mKind != kObjectKindFile ) {
        std::cerr << "Path '" << path << "' is not a regular file."
                  << std::endl;
        exit(EXIT_FAILURE);
    }

    /// BEGIN reader code
    const size_t buff_size = 1<<20; // 1 MB
    std::vector<char> buff(buff_size);

    size_t data_left_len = 0;

    hdfs::File file(fs, path, O_RDONLY, buff_size, 0, 0);
    for (size_t bytes_read = 0; bytes_read < path_info->mSize;) {
        tSize read_length = file.Pread(bytes_read, &buff[0], buff_size);
        bytes_read += read_length;

        tmacam::filebuf available_data(&buff[0], read_length);

        std::cout << "READ " << read_length << std::endl;

        try {
            while (!available_data.eof()) {
                // Save current progress
                data_left_len = available_data.len();

                int32_t payload_len = ReadInt(&available_data);
                const char* payload_data = available_data.read(payload_len);
                assert(payload_len + 2*sizeof(int32_t) < buff_size);
                int32_t expected_checksum = ReadInt(&available_data);

#ifndef DUMPREADER_FAST_PASS
                // Calc CRC32
                uLong crc = crc32(0L, (const Bytef*)payload_data, payload_len);
                if (expected_checksum != static_cast<int32_t>(crc)) {
                    std::cerr << "CRC MISSMATCH -- found " << crc <<
                        " expected" << expected_checksum <<
                        std::endl;
                    exit(EXIT_FAILURE);
                }
#endif

                std::cout << "P: " <<  payload_len << std::endl;
            }
        } catch(std::out_of_range) {
            std::cout << "ooops " <<  std::endl;
            // not enough data...
            // rewind reading position
            bytes_read -= data_left_len;
        }
    }

    /// END reader code

	return 0;
}

// vim: et ai sts=4 ts=4 sw=4
<commit_msg>minor fix<commit_after>#include "hdfscpp.h"

#include <iostream>

#include <assert.h>

#include "filebuf.h"
#include <vector>

#include <zlib.h>
/**********************************************************************/

/** Reads a int written by java's DataOutput#writeInt
 *
 * FIXME Move to propper namespace
 */
inline int32_t ReadInt(tmacam::filebuf* data) {
	assert(sizeof(int32_t) == 4);
	const char* bytes = data->read(sizeof(int32_t));
	return (((bytes[0] & 0xff) << 24) | ((bytes[1] & 0xff) << 16) |
		 ((bytes[2] & 0xff) << 8) | (bytes[3] & 0xff));
}

/**********************************************************************/
/*
class HdfsDumpReader {
private:
    // No copy, no atribution and no default constructor for this class
    DISALLOW_COPY_AND_ASSIGN(HdfsDumpReader);
    HdfsDumpReader();
};
*/

/**********************************************************************/

void ShowUsage()
{
    std::cerr << "Usage: hdfsls <path> " << std::endl;
}

int main(int argc, char* argv[])
{
    using namespace tmacam;

    // Check command line arguments
    if ( argc != 2) {
        std::cerr << "Wrong number of arguments" << std::endl;
        ShowUsage();
        exit(EXIT_FAILURE);
    }
    const char* path = argv[1];

    // Connect to HDFS / get filesystem handle
    hdfs::FileSystem fs;

    // Path is a file, right?
    if (!fs.Exists(path)) {
        std::cerr << "Path '" << path << "' does not exist." << std::endl;
        exit(EXIT_FAILURE);
    }
    hdfs::FileInfoList path_info;
    fs.GetPathInfo(path, &path_info);
    if (path_info->mKind != kObjectKindFile ) {
        std::cerr << "Path '" << path << "' is not a regular file."
                  << std::endl;
        exit(EXIT_FAILURE);
    }

    /// BEGIN reader code
    const size_t buff_size = 1<<20; // 1 MB
    std::vector<char> buff(buff_size);

    size_t data_left_len = 0;

    hdfs::File file(fs, path, O_RDONLY, buff_size, 0, 0);
    for (size_t bytes_read = 0; bytes_read < path_info->mSize;) {
        /* Using Pread() and exceptions for doing this is ugly and lame.
         * We should have used Read() and proper tests but, you know what,
         * this works and is easy to understand -- and this scores +1 in
         * my book.
         */
        tSize read_length = file.Pread(bytes_read, &buff[0], buff_size);
        bytes_read += read_length;

        tmacam::filebuf available_data(&buff[0], read_length);

        std::cout << "READ " << read_length << std::endl;

        try {
            while (!available_data.eof()) {
                // Save current progress
                data_left_len = available_data.len();
                // Read header, payload and CRC. Abort if payload is too big
                int32_t payload_len = ReadInt(&available_data);
                assert(payload_len + 2*sizeof(int32_t) < buff_size);
                const char* payload_data = available_data.read(payload_len);
                int32_t expected_checksum = ReadInt(&available_data);
#ifndef DUMPREADER_FAST_PASS
                // Calc CRC32
                uLong crc = crc32(0L, (const Bytef*)payload_data, payload_len);
                if (expected_checksum != static_cast<int32_t>(crc)) {
                    std::cerr << "CRC MISSMATCH -- found " << crc <<
                        " expected" << expected_checksum <<
                        std::endl;
                    exit(EXIT_FAILURE);
                }
#endif
                std::cout << "P: " <<  payload_len << std::endl;
            }
        } catch(std::out_of_range) {
            std::cout << "ooops " <<  std::endl;
            // not enough data...
            // rewind reading position
            bytes_read -= data_left_len;
        }
    }

    /// END reader code

	return 0;
}

// vim: et ai sts=4 ts=4 sw=4
<|endoftext|>