<commit_before>/*
*  SixTrack Wrapper for Pythia8
*  V.K. Berglyd Olsen, BE-ABP-HSS
*  Created: 2018-07-30
*  Updated: 2019-07-17
*/

#include "pythia_wrapper.h"

using namespace Pythia8;

extern "C" {

bool pythiaWrapper_init() {
  if(!pythia.init()) return false;
  pythia.settings.writeFile("pythia_settings.dat", true);
  std::cout << "PYTHIA> Done" << std::endl;
  return true;
}

bool pythiaWrapper_defaults() {
  std::cout << "PYTHIA> Setting defaults" << std::endl;
  pythia.settings.flag("Init:showChangedSettings", true);
  pythia.settings.flag("Init:showChangedParticleData", false);
  pythia.settings.flag("SigmaTotal:mode", 3);
  pythia.settings.flag("SigmaDiffractive:mode", 3);
  return true;
}

void pythiaWrapper_setProcess(bool sEL, bool sSD, bool sDD, bool sCD, bool sND) {
  std::cout << "PYTHIA> Setting processes" << std::endl;
  pythia.settings.flag("SoftQCD:elastic", sEL);
  pythia.settings.flag("SoftQCD:singleDiffractive", sSD);
  pythia.settings.flag("SoftQCD:doubleDiffractive", sDD);
  pythia.settings.flag("SoftQCD:centralDiffractive", sCD);
  pythia.settings.flag("SoftQCD:nonDiffractive", sND);
}

void pythiaWrapper_setCoulomb(bool sCMB, double tAbsMin) {
  pythia.settings.flag("SigmaElastic:Coulomb", sCMB);
  pythia.settings.parm("SigmaElastic:tAbsMin", tAbsMin);
}

void pythiaWrapper_setSeed(int rndSeed) {
  std::cout << "PYTHIA> Setting random seed" << std::endl;
  pythia.settings.mode("Random:seed", rndSeed);
}

void pythiaWrapper_setBeam(int frameType, int idA, int idB, double eA, double eB) {
  std::cout << "PYTHIA> Setting beam parameters" << std::endl;
  pythia.settings.mode("Beams:frameType", frameType);
  pythia.settings.mode("Beams:idA", idA);
  pythia.settings.mode("Beams:idB", idB);
  pythia.settings.parm("Beams:eA", eA);
  pythia.settings.parm("Beams:eB", eB);
  if(frameType == 3) {
    pythia.settings.flag("Beams:allowVariableEnergy", true);
  }
}

void pythiaWrapper_readFile(char* fileName) {
  std::cout << "PYTHIA> Loading settings from external file" << std::endl;
  pythia.readFile(std::string(fileName));
}

void pythiaWrapper_getInitial(double& sigTot, double& sigEl, double& m0) {
  // sigTot = pythia.info.sigmaGen(0);
  sigTot = pythia.parm("SigmaTotal:sigmaTot");
  sigEl  = pythia.parm("SigmaTotal:sigmaEl");

  // Generate one test event, and extract the particle mass
  pythia.next();
  m0 = sqrt(pythia.event[1].p().m2Calc());
}

/**
 *  SoftQCD Events
 * ================
 *  101 : Non-Diffrcative
 *  102 : Elastic             AB -> AB
 *  103 : Single Diffractive  AB -> XB
 *  104 : Single Diffractive  AB -> AX
 *  105 : Double Diffractive  AB -> XX
 *  106 : Central Diffractive AB -> AXB
 */

void pythiaWrapper_getEvent(bool& status, int& code, double& t, double& theta, double& dEE, double& dPP) {
  status = pythia.next();
  code   = pythia.info.code();
  if(!status) {
    code  = 0;
    t     = 0.0;
    theta = 0.0;
    dEE   = 0.0;
    dPP   = 0.0;
    return;
  }
  if(code == 101) {
    t     = 0.0;
    theta = 0.0;
    dEE   = 0.0;
    dPP   = 0.0;
  }
  else if(code == 102) { // Elastic
    t     =  pythia.info.tHat();
    theta =  pythia.event[3].theta();
    dEE   = (pythia.event[3].e()    - pythia.event[1].e())    / pythia.event[1].e();
    dPP   = (pythia.event[3].pAbs() - pythia.event[1].pAbs()) / pythia.event[1].pAbs();
  }
  else if(code == 104) { // Single Diffractive AB->AX
    t     =  pythia.info.tHat();
    theta =  pythia.event[3].theta();
    dEE   = (pythia.event[3].e()    - pythia.event[1].e())    / pythia.event[1].e();
    dPP   = (pythia.event[3].pAbs() - pythia.event[1].pAbs()) / pythia.event[1].pAbs();
  }
  else if(code == 106) { // Central Diffractive AB->AXB
    t     = (pythia.event[3].p()    - pythia.event[1].p()).m2Calc();
    theta =  pythia.event[3].theta();
    dEE   = (pythia.event[3].e()    - pythia.event[1].e())    / pythia.event[1].e();
    dPP   = (pythia.event[3].pAbs() - pythia.event[1].pAbs()) / pythia.event[1].pAbs();
  }
  else {
    t     = 0.0;
    theta = 0.0;
    dEE   = 0.0;
    dPP   = 0.0;
  }
}

void pythiaWrapper_getEventPVector(bool& status, int& code, double& t, double& theta, double& dEE, double& dPP, double* vecPin, double* vecPout) {

  status = pythia.next(vecPin[0],vecPin[1],vecPin[2],vecPin[3],vecPin[4],vecPin[5]);
  code   = pythia.info.code();

  t      = 0.0;
  theta  = 0.0;
  dEE    = 0.0;
  dPP    = 0.0;

  if(code == 102 || code == 104 || code == 106) {
    theta =  pythia.event[3].theta();
    dEE   = (pythia.event[3].e()    - pythia.event[1].e())    / pythia.event[1].e();
    dPP   = (pythia.event[3].pAbs() - pythia.event[1].pAbs()) / pythia.event[1].pAbs();
  }
  if(code == 102 || code == 104) {
    t = pythia.info.tHat();
  }
  if(code == 106) {
    t = (pythia.event[3].p() - pythia.event[1].p()).m2Calc();
  }

  vecPin[0]  = pythia.event[1].px();
  vecPin[1]  = pythia.event[1].py();
  vecPin[2]  = pythia.event[1].pz();
  vecPin[3]  = pythia.event[2].px();
  vecPin[4]  = pythia.event[2].py();
  vecPin[5]  = pythia.event[2].pz();
  vecPout[0] = pythia.event[3].px();
  vecPout[1] = pythia.event[3].py();
  vecPout[2] = pythia.event[3].pz();
  vecPout[3] = pythia.event[4].px();
  vecPout[4] = pythia.event[4].py();
  vecPout[5] = pythia.event[4].pz();

}

}
<commit_msg>No need to sqrt a square variable if we can get the un-squared one<commit_after>/*
*  SixTrack Wrapper for Pythia8
*  V.K. Berglyd Olsen, BE-ABP-HSS
*  Created: 2018-07-30
*  Updated: 2019-07-17
*/

#include "pythia_wrapper.h"

using namespace Pythia8;

extern "C" {

bool pythiaWrapper_init() {
  if(!pythia.init()) return false;
  pythia.settings.writeFile("pythia_settings.dat", true);
  std::cout << "PYTHIA> Done" << std::endl;
  return true;
}

bool pythiaWrapper_defaults() {
  std::cout << "PYTHIA> Setting defaults" << std::endl;
  pythia.settings.flag("Init:showChangedSettings", true);
  pythia.settings.flag("Init:showChangedParticleData", false);
  pythia.settings.flag("SigmaTotal:mode", 3);
  pythia.settings.flag("SigmaDiffractive:mode", 3);
  return true;
}

void pythiaWrapper_setProcess(bool sEL, bool sSD, bool sDD, bool sCD, bool sND) {
  std::cout << "PYTHIA> Setting processes" << std::endl;
  pythia.settings.flag("SoftQCD:elastic", sEL);
  pythia.settings.flag("SoftQCD:singleDiffractive", sSD);
  pythia.settings.flag("SoftQCD:doubleDiffractive", sDD);
  pythia.settings.flag("SoftQCD:centralDiffractive", sCD);
  pythia.settings.flag("SoftQCD:nonDiffractive", sND);
}

void pythiaWrapper_setCoulomb(bool sCMB, double tAbsMin) {
  pythia.settings.flag("SigmaElastic:Coulomb", sCMB);
  pythia.settings.parm("SigmaElastic:tAbsMin", tAbsMin);
}

void pythiaWrapper_setSeed(int rndSeed) {
  std::cout << "PYTHIA> Setting random seed" << std::endl;
  pythia.settings.mode("Random:seed", rndSeed);
}

void pythiaWrapper_setBeam(int frameType, int idA, int idB, double eA, double eB) {
  std::cout << "PYTHIA> Setting beam parameters" << std::endl;
  pythia.settings.mode("Beams:frameType", frameType);
  pythia.settings.mode("Beams:idA", idA);
  pythia.settings.mode("Beams:idB", idB);
  pythia.settings.parm("Beams:eA", eA);
  pythia.settings.parm("Beams:eB", eB);
  if(frameType == 3) {
    pythia.settings.flag("Beams:allowVariableEnergy", true);
  }
}

void pythiaWrapper_readFile(char* fileName) {
  std::cout << "PYTHIA> Loading settings from external file" << std::endl;
  pythia.readFile(std::string(fileName));
}

void pythiaWrapper_getInitial(double& sigTot, double& sigEl, double& m0) {
  // sigTot = pythia.info.sigmaGen(0);
  sigTot = pythia.parm("SigmaTotal:sigmaTot");
  sigEl  = pythia.parm("SigmaTotal:sigmaEl");

  // Generate one test event, and extract the particle mass
  pythia.next();
  m0 = pythia.event[1].p().mCalc();
}

/**
 *  SoftQCD Events
 * ================
 *  101 : Non-Diffrcative
 *  102 : Elastic             AB -> AB
 *  103 : Single Diffractive  AB -> XB
 *  104 : Single Diffractive  AB -> AX
 *  105 : Double Diffractive  AB -> XX
 *  106 : Central Diffractive AB -> AXB
 */

void pythiaWrapper_getEvent(bool& status, int& code, double& t, double& theta, double& dEE, double& dPP) {
  status = pythia.next();
  code   = pythia.info.code();
  if(!status) {
    code  = 0;
    t     = 0.0;
    theta = 0.0;
    dEE   = 0.0;
    dPP   = 0.0;
    return;
  }
  if(code == 101) {
    t     = 0.0;
    theta = 0.0;
    dEE   = 0.0;
    dPP   = 0.0;
  }
  else if(code == 102) { // Elastic
    t     =  pythia.info.tHat();
    theta =  pythia.event[3].theta();
    dEE   = (pythia.event[3].e()    - pythia.event[1].e())    / pythia.event[1].e();
    dPP   = (pythia.event[3].pAbs() - pythia.event[1].pAbs()) / pythia.event[1].pAbs();
  }
  else if(code == 104) { // Single Diffractive AB->AX
    t     =  pythia.info.tHat();
    theta =  pythia.event[3].theta();
    dEE   = (pythia.event[3].e()    - pythia.event[1].e())    / pythia.event[1].e();
    dPP   = (pythia.event[3].pAbs() - pythia.event[1].pAbs()) / pythia.event[1].pAbs();
  }
  else if(code == 106) { // Central Diffractive AB->AXB
    t     = (pythia.event[3].p()    - pythia.event[1].p()).m2Calc();
    theta =  pythia.event[3].theta();
    dEE   = (pythia.event[3].e()    - pythia.event[1].e())    / pythia.event[1].e();
    dPP   = (pythia.event[3].pAbs() - pythia.event[1].pAbs()) / pythia.event[1].pAbs();
  }
  else {
    t     = 0.0;
    theta = 0.0;
    dEE   = 0.0;
    dPP   = 0.0;
  }
}

void pythiaWrapper_getEventPVector(bool& status, int& code, double& t, double& theta, double& dEE, double& dPP, double* vecPin, double* vecPout) {

  status = pythia.next(vecPin[0],vecPin[1],vecPin[2],vecPin[3],vecPin[4],vecPin[5]);
  code   = pythia.info.code();

  t      = 0.0;
  theta  = 0.0;
  dEE    = 0.0;
  dPP    = 0.0;

  if(code == 102 || code == 104 || code == 106) {
    theta =  pythia.event[3].theta();
    dEE   = (pythia.event[3].e()    - pythia.event[1].e())    / pythia.event[1].e();
    dPP   = (pythia.event[3].pAbs() - pythia.event[1].pAbs()) / pythia.event[1].pAbs();
  }
  if(code == 102 || code == 104) {
    t = pythia.info.tHat();
  }
  if(code == 106) {
    t = (pythia.event[3].p() - pythia.event[1].p()).m2Calc();
  }

  vecPin[0]  = pythia.event[1].px();
  vecPin[1]  = pythia.event[1].py();
  vecPin[2]  = pythia.event[1].pz();
  vecPin[3]  = pythia.event[2].px();
  vecPin[4]  = pythia.event[2].py();
  vecPin[5]  = pythia.event[2].pz();
  vecPout[0] = pythia.event[3].px();
  vecPout[1] = pythia.event[3].py();
  vecPout[2] = pythia.event[3].pz();
  vecPout[3] = pythia.event[4].px();
  vecPout[4] = pythia.event[4].py();
  vecPout[5] = pythia.event[4].pz();

}

}
<|endoftext|>


<commit_before><commit_msg>fixed for compile<commit_after><|endoftext|>


<commit_before>/*
 * Distributed under the OSI-approved Apache License, Version 2.0.  See
 * accompanying file Copyright.txt for details.
 *
 * DataManBase.cpp
 *
 *  Created on: Apr 12, 2017
 *      Author: Jason Wang
 */

#include "DataManBase.h"

#include <sstream>

#include <adios2sys/DynamicLoader.hxx>

struct DataManBase::ManagerLibrary
{
    adios2sys::DynamicLoader::LibraryHandle m_LibraryHandle;
    DataManBase *(*m_getManFunc)();

    ManagerLibrary(std::string method)
    {
        std::vector<std::string> searchedLibs;
        std::string libName;

        std::vector<std::string> libPrefixes;
        libPrefixes.emplace_back("");
        libPrefixes.emplace_back("lib");
#ifdef __CYGWIN__
        libPrefixes.emplace_back("cyg");
#endif

        std::vector<std::string> libSuffixes;
#ifdef __APPLE__
        libSuffixes.emplace_back("man.dylib");
        libSuffixes.emplace_back("man.so");
#endif
#ifdef __hpux
        libSuffixes.emplace_back("man.sl");
#endif
#ifdef __unix__
        libSuffixes.emplace_back("man.so");
#endif
#ifdef _WIN32
        libSuffixes.emplace_back("man.dll");
#endif

        // Test the various combinations of library names
        for (const std::string &prefix : libPrefixes)
        {
            for (const std::string &suffix : libSuffixes)
            {
                libName = prefix + method + suffix;
                m_LibraryHandle =
                    adios2sys::DynamicLoader::OpenLibrary(libName);
                searchedLibs.push_back(libName);
                if (m_LibraryHandle)
                {
                    break;
                }
            }
            if (m_LibraryHandle)
            {
                break;
            }
        }
        if (!m_LibraryHandle)
        {
            std::stringstream errString;
            errString << "Unable to locate the " << method << " manager "
                      << "library; searched for ";
            std::copy(searchedLibs.begin(), searchedLibs.end(),
                      std::ostream_iterator<std::string>(errString, " "));

            throw std::runtime_error(errString.str());
        }

        // Bind to the getMan symbol
        adios2sys::DynamicLoader::SymbolPointer symbolHandle =
            adios2sys::DynamicLoader::GetSymbolAddress(m_LibraryHandle,
                                                       "getMan");
        if (!symbolHandle)
        {
            throw std::runtime_error("Unable to locate the getMan symbol in " +
                                     libName);
        }
        m_getManFunc = reinterpret_cast<DataManBase *(*)()>(symbolHandle);
    }

    ~ManagerLibrary()
    {
        if (m_LibraryHandle)
        {
            adios2sys::DynamicLoader::CloseLibrary(m_LibraryHandle);
        }
    }
};

DataManBase::DataManBase()
{
    m_profiling["total_manager_time"] = 0.0f;
    m_profiling["total_mb"] = 0.0f;
    m_start_time = std::chrono::system_clock::now();
}

int DataManBase::put(const void *p_data, std::string p_doid, std::string p_var,
                     std::string p_dtype, std::vector<size_t> p_putshape,
                     std::vector<size_t> p_varshape,
                     std::vector<size_t> p_offset, size_t p_timestep,
                     int p_tolerance, int p_priority)
{
    json msg;
    msg["doid"] = p_doid;
    msg["var"] = p_var;
    msg["dtype"] = p_dtype;
    msg["putshape"] = p_putshape;
    msg["putbytes"] = product(p_putshape, dsize(p_dtype));
    msg["varshape"] = p_varshape;
    msg["varbytes"] = product(p_varshape, dsize(p_dtype));
    msg["offset"] = p_offset;
    msg["timestep"] = p_timestep;
    msg["tolerance"] = p_tolerance;
    msg["priority"] = p_priority;
    return put(p_data, msg);
}

int DataManBase::put_begin(const void *p_data, json &p_jmsg)
{
    check_shape(p_jmsg);
    p_jmsg["profiling"] = m_profiling;
    m_step_time = std::chrono::system_clock::now();
    return 0;
}

int DataManBase::put_end(const void *p_data, json &p_jmsg)
{
    auto end = std::chrono::system_clock::now();
    std::chrono::duration<double> duration = end - m_step_time;
    m_profiling["total_manager_time"] =
        m_profiling["total_manager_time"].get<double>() + duration.count();
    m_profiling["total_mb"] =
        m_profiling["total_mb"].get<size_t>() +
        product(p_jmsg["varshape"], dsize(p_jmsg["dtype"])) / 1000000.0f;
    duration = end - m_start_time;
    m_profiling["total_workflow_time"] = duration.count();
    m_profiling["workflow_mbs"] =
        m_profiling["total_mb"].get<double>() /
        m_profiling["total_workflow_time"].get<double>();
    m_profiling["manager_mbs"] =
        m_profiling["total_mb"].get<double>() /
        m_profiling["total_manager_time"].get<double>();
    if (p_jmsg["compressed_size"] != nullptr)
        p_jmsg["putbytes"] = p_jmsg["compressed_size"].get<size_t>();
    put_next(p_data, p_jmsg);
    return 0;
}

int DataManBase::get(void *p_data, std::string p_doid, std::string p_var,
                     std::string p_dtype, std::vector<size_t> p_getshape,
                     std::vector<size_t> p_varshape,
                     std::vector<size_t> p_offset, size_t p_timestep)
{
    json msg;
    msg["doid"] = p_doid;
    msg["var"] = p_var;
    msg["dtype"] = p_dtype;
    msg["getshape"] = p_getshape;
    msg["varshape"] = p_varshape;
    msg["offset"] = p_offset;
    msg["timestep"] = p_timestep;
    return get(p_data, msg);
}

int DataManBase::get(void *p_data, std::string p_doid, std::string p_var,
                     std::string &p_dtype, std::vector<size_t> &p_varshape,
                     size_t &p_timestep)
{
    json msg;
    msg["doid"] = p_doid;
    msg["var"] = p_var;
    return get(p_data, msg);
}

void DataManBase::reg_callback(
    std::function<void(const void *, std::string, std::string, std::string,
                       std::vector<size_t>)>
        cb)
{
    if (m_next.size() == 0)
    {
        m_callback = cb;
    }
    else
    {
        for (auto i : m_next)
        {
            i.second->reg_callback(cb);
        }
    }
}

void DataManBase::dump(const void *p_data, json p_jmsg, std::ostream &out)
{
    std::vector<size_t> p_varshape =
        p_jmsg["varshape"].get<std::vector<size_t>>();
    std::string dtype = p_jmsg["dtype"];
    size_t length = p_jmsg["dumplength"].get<size_t>();
    size_t s = 0;
    for (size_t i = 0; i < product(p_varshape, 1); i++)
    {
        s++;
        out << ((float *)p_data)[i] << " ";
        if (s == length)
        {
            out << std::endl;
            s = 0;
        }
    }
    out << std::endl;
}

void DataManBase::add_next(std::string p_name,
                           std::shared_ptr<DataManBase> p_next)
{
    m_next[p_name] = p_next;
}

void DataManBase::remove_next(std::string p_name) { m_next.erase(p_name); }

bool DataManBase::have_next()
{
    if (m_next.size() == 0)
    {
        return false;
    }
    else
    {
        return true;
    }
}

void DataManBase::print_next(std::ostream &out)
{
    for (auto i : m_next)
    {
        out << i.second->name() << " -> ";
        i.second->print_next();
        out << std::endl;
    }
}

bool DataManBase::auto_transform(const void *p_in, void *p_out, json &p_jmsg)
{
    if (p_jmsg["compression_method"] != nullptr)
    {
        auto method = p_jmsg["compression_method"];
        auto man = get_man(method);
        if (man == nullptr)
        {
            logging("Library file for compression method " +
                    p_jmsg["compression_method"].dump() + " not found!");
            return false;
        }
        man->transform(p_in, p_out, p_jmsg);
        p_jmsg.erase("compression_method");
        p_jmsg.erase("compression_rate");
        p_jmsg.erase("compressed_size");
        return true;
    }
    else
    {
        return false;
    }
}

void DataManBase::add_man_to_path(std::string p_new, std::string p_path)
{
    if (m_next.count(p_path) > 0)
    {
        auto man = get_man(p_new);
        if (man)
        {
            man->add_next(p_path, m_next[p_path]);
            this->add_next(p_new, man);
            this->remove_next(p_path);
        }
    }
}

int DataManBase::flush_next()
{
    for (auto i : m_next)
    {
        i.second->flush();
    }
    return 0;
}

int DataManBase::put_next(const void *p_data, json p_jmsg)
{
    for (auto i : m_next)
    {
        i.second->put(p_data, p_jmsg);
    }
    return 0;
}

std::shared_ptr<DataManBase> DataManBase::get_man(std::string method)
{
    try
    {
        // Reuse already loaded libraries if possible
        auto libIt = m_LoadedManagers.find(method);
        if (libIt == m_LoadedManagers.end())
        {
            // This insertion will only fail if an entry for method already
            // exists, which this if block ensures that it doesn't.
            libIt =
                m_LoadedManagers.insert({method, new ManagerLibrary(method)})
                    .first;
        }
        return std::shared_ptr<DataManBase>(libIt->second->m_getManFunc());
    }
    catch (const std::runtime_error &ex)
    {
        logging(ex.what());
        return nullptr;
    }
}
<commit_msg>Add more verbose logging to dataman when loading manager libraries<commit_after>/*
 * Distributed under the OSI-approved Apache License, Version 2.0.  See
 * accompanying file Copyright.txt for details.
 *
 * DataManBase.cpp
 *
 *  Created on: Apr 12, 2017
 *      Author: Jason Wang
 */

#include "DataManBase.h"

#include <sstream>

#include <adios2sys/DynamicLoader.hxx>

struct DataManBase::ManagerLibrary
{
    std::string m_LibraryName;
    adios2sys::DynamicLoader::LibraryHandle m_LibraryHandle;
    DataManBase *(*m_getManFunc)();

    ManagerLibrary(std::string method)
    {
        std::vector<std::string> searchedLibs;
        std::string libName;

        std::vector<std::string> libPrefixes;
        libPrefixes.emplace_back("");
        libPrefixes.emplace_back("lib");
#ifdef __CYGWIN__
        libPrefixes.emplace_back("cyg");
#endif

        std::vector<std::string> libSuffixes;
#ifdef __APPLE__
        libSuffixes.emplace_back("man.dylib");
        libSuffixes.emplace_back("man.so");
#endif
#ifdef __hpux
        libSuffixes.emplace_back("man.sl");
#endif
#ifdef __unix__
        libSuffixes.emplace_back("man.so");
#endif
#ifdef _WIN32
        libSuffixes.emplace_back("man.dll");
#endif

        // Test the various combinations of library names
        for (const std::string &prefix : libPrefixes)
        {
            for (const std::string &suffix : libSuffixes)
            {
                libName = prefix + method + suffix;
                m_LibraryHandle =
                    adios2sys::DynamicLoader::OpenLibrary(libName);
                searchedLibs.push_back(libName);
                if (m_LibraryHandle)
                {
                    break;
                }
            }
            if (m_LibraryHandle)
            {
                break;
            }
        }
        if (!m_LibraryHandle)
        {
            std::stringstream errString;
            errString << "Unable to locate the " << method << " manager "
                      << "library; searched for ";
            std::copy(searchedLibs.begin(), searchedLibs.end(),
                      std::ostream_iterator<std::string>(errString, " "));

            throw std::runtime_error(errString.str());
        }

        // Bind to the getMan symbol
        adios2sys::DynamicLoader::SymbolPointer symbolHandle =
            adios2sys::DynamicLoader::GetSymbolAddress(m_LibraryHandle,
                                                       "getMan");
        if (!symbolHandle)
        {
            throw std::runtime_error("Unable to locate the getMan symbol in " +
                                     libName);
        }
        m_getManFunc = reinterpret_cast<DataManBase *(*)()>(symbolHandle);
        m_LibraryName = libName;
    }

    ~ManagerLibrary()
    {
        if (m_LibraryHandle)
        {
            adios2sys::DynamicLoader::CloseLibrary(m_LibraryHandle);
        }
    }
};

DataManBase::DataManBase()
{
    m_profiling["total_manager_time"] = 0.0f;
    m_profiling["total_mb"] = 0.0f;
    m_start_time = std::chrono::system_clock::now();
}

int DataManBase::put(const void *p_data, std::string p_doid, std::string p_var,
                     std::string p_dtype, std::vector<size_t> p_putshape,
                     std::vector<size_t> p_varshape,
                     std::vector<size_t> p_offset, size_t p_timestep,
                     int p_tolerance, int p_priority)
{
    json msg;
    msg["doid"] = p_doid;
    msg["var"] = p_var;
    msg["dtype"] = p_dtype;
    msg["putshape"] = p_putshape;
    msg["putbytes"] = product(p_putshape, dsize(p_dtype));
    msg["varshape"] = p_varshape;
    msg["varbytes"] = product(p_varshape, dsize(p_dtype));
    msg["offset"] = p_offset;
    msg["timestep"] = p_timestep;
    msg["tolerance"] = p_tolerance;
    msg["priority"] = p_priority;
    return put(p_data, msg);
}

int DataManBase::put_begin(const void *p_data, json &p_jmsg)
{
    check_shape(p_jmsg);
    p_jmsg["profiling"] = m_profiling;
    m_step_time = std::chrono::system_clock::now();
    return 0;
}

int DataManBase::put_end(const void *p_data, json &p_jmsg)
{
    auto end = std::chrono::system_clock::now();
    std::chrono::duration<double> duration = end - m_step_time;
    m_profiling["total_manager_time"] =
        m_profiling["total_manager_time"].get<double>() + duration.count();
    m_profiling["total_mb"] =
        m_profiling["total_mb"].get<size_t>() +
        product(p_jmsg["varshape"], dsize(p_jmsg["dtype"])) / 1000000.0f;
    duration = end - m_start_time;
    m_profiling["total_workflow_time"] = duration.count();
    m_profiling["workflow_mbs"] =
        m_profiling["total_mb"].get<double>() /
        m_profiling["total_workflow_time"].get<double>();
    m_profiling["manager_mbs"] =
        m_profiling["total_mb"].get<double>() /
        m_profiling["total_manager_time"].get<double>();
    if (p_jmsg["compressed_size"] != nullptr)
        p_jmsg["putbytes"] = p_jmsg["compressed_size"].get<size_t>();
    put_next(p_data, p_jmsg);
    return 0;
}

int DataManBase::get(void *p_data, std::string p_doid, std::string p_var,
                     std::string p_dtype, std::vector<size_t> p_getshape,
                     std::vector<size_t> p_varshape,
                     std::vector<size_t> p_offset, size_t p_timestep)
{
    json msg;
    msg["doid"] = p_doid;
    msg["var"] = p_var;
    msg["dtype"] = p_dtype;
    msg["getshape"] = p_getshape;
    msg["varshape"] = p_varshape;
    msg["offset"] = p_offset;
    msg["timestep"] = p_timestep;
    return get(p_data, msg);
}

int DataManBase::get(void *p_data, std::string p_doid, std::string p_var,
                     std::string &p_dtype, std::vector<size_t> &p_varshape,
                     size_t &p_timestep)
{
    json msg;
    msg["doid"] = p_doid;
    msg["var"] = p_var;
    return get(p_data, msg);
}

void DataManBase::reg_callback(
    std::function<void(const void *, std::string, std::string, std::string,
                       std::vector<size_t>)>
        cb)
{
    if (m_next.size() == 0)
    {
        m_callback = cb;
    }
    else
    {
        for (auto i : m_next)
        {
            i.second->reg_callback(cb);
        }
    }
}

void DataManBase::dump(const void *p_data, json p_jmsg, std::ostream &out)
{
    std::vector<size_t> p_varshape =
        p_jmsg["varshape"].get<std::vector<size_t>>();
    std::string dtype = p_jmsg["dtype"];
    size_t length = p_jmsg["dumplength"].get<size_t>();
    size_t s = 0;
    for (size_t i = 0; i < product(p_varshape, 1); i++)
    {
        s++;
        out << ((float *)p_data)[i] << " ";
        if (s == length)
        {
            out << std::endl;
            s = 0;
        }
    }
    out << std::endl;
}

void DataManBase::add_next(std::string p_name,
                           std::shared_ptr<DataManBase> p_next)
{
    m_next[p_name] = p_next;
}

void DataManBase::remove_next(std::string p_name) { m_next.erase(p_name); }

bool DataManBase::have_next()
{
    if (m_next.size() == 0)
    {
        return false;
    }
    else
    {
        return true;
    }
}

void DataManBase::print_next(std::ostream &out)
{
    for (auto i : m_next)
    {
        out << i.second->name() << " -> ";
        i.second->print_next();
        out << std::endl;
    }
}

bool DataManBase::auto_transform(const void *p_in, void *p_out, json &p_jmsg)
{
    if (p_jmsg["compression_method"] != nullptr)
    {
        auto method = p_jmsg["compression_method"];
        auto man = get_man(method);
        if (man == nullptr)
        {
            logging("Library file for compression method " +
                    p_jmsg["compression_method"].dump() + " not found!");
            return false;
        }
        man->transform(p_in, p_out, p_jmsg);
        p_jmsg.erase("compression_method");
        p_jmsg.erase("compression_rate");
        p_jmsg.erase("compressed_size");
        return true;
    }
    else
    {
        return false;
    }
}

void DataManBase::add_man_to_path(std::string p_new, std::string p_path)
{
    if (m_next.count(p_path) > 0)
    {
        auto man = get_man(p_new);
        if (man)
        {
            man->add_next(p_path, m_next[p_path]);
            this->add_next(p_new, man);
            this->remove_next(p_path);
        }
    }
}

int DataManBase::flush_next()
{
    for (auto i : m_next)
    {
        i.second->flush();
    }
    return 0;
}

int DataManBase::put_next(const void *p_data, json p_jmsg)
{
    for (auto i : m_next)
    {
        i.second->put(p_data, p_jmsg);
    }
    return 0;
}

std::shared_ptr<DataManBase> DataManBase::get_man(std::string method)
{
    try
    {
        // Reuse already loaded libraries if possible
        auto libIt = m_LoadedManagers.find(method);
        if (libIt == m_LoadedManagers.end())
        {
            // This insertion will only fail if an entry for method already
            // exists, which this if block ensures that it doesn't.
            libIt =
                m_LoadedManagers.insert({method, new ManagerLibrary(method)})
                    .first;
            logging("Loaded " + libIt->second->m_LibraryName);
        }
        else
        {
            logging("Using existing " + libIt->second->m_LibraryName + ".");
        }
        return std::shared_ptr<DataManBase>(libIt->second->m_getManFunc());
    }
    catch (const std::runtime_error &ex)
    {
        logging(ex.what());
        return nullptr;
    }
}
<|endoftext|>


<commit_before>#include "choiceview.h"

#include <QKeyEvent>
#include <QPaintEvent>
#include <QPainter>

Choice::Choice(const QString &title, const QString &id, const QStringList &params)
    : _id(id), _title(title), _params(params) {
}

const QString &Choice::id() const {
  return _id;
}

const QString &Choice::title() const {
  return _title;
}

const QStringList &Choice::params() const {
  return _params;
}

ChoiceView::ChoiceView(QWidget *parent)
    : QWidget(parent),
      _offset(0) {

  setFocusPolicy(Qt::StrongFocus);

  QFont myFont;
  myFont.setPointSize(20);
  setFont(myFont);
}

ChoiceView::~ChoiceView() { }

static const int arrowHeight = 8;

static char _hotkeys[] = { '1', '2', '3', '4', '5', '6', '7', '8', '9', '0' };
void ChoiceView::paintEvent(QPaintEvent *event) {
  QFontMetrics metrics(font());
  QPainter painter(this);

  int y = arrowHeight + 2;
  const int baseline = metrics.leading() + metrics.ascent() + 1;
  const int w = width(), h = height() - (y * 2);
  const int yInc = h / 10;
  const int labelWidth = w - yInc - 10;
  const int hotkeyCenter = w - (yInc / 2);

  // Top arrow
  const int center = w / 2;
  painter.eraseRect(0, 0, w, y);
  if (_offset > 0) {
    painter.drawLine(center, 0, center - arrowHeight, arrowHeight);
    painter.drawLine(center, 0, center + arrowHeight, arrowHeight);
    painter.drawLine(center - arrowHeight, arrowHeight, center + arrowHeight, arrowHeight);
  }

  // Bottom arrow
  painter.eraseRect(0, height() - y, w, y);
  if (_offset + 10 < _choices.size()) {
    painter.drawLine(center, height() - 1, center - arrowHeight, height() - arrowHeight - 1);
    painter.drawLine(center, height() - 1, center + arrowHeight, height() - arrowHeight - 1);
    painter.drawLine(center - arrowHeight, height() - arrowHeight - 1,
        center + arrowHeight, height() - arrowHeight - 1);
  }

  QLinearGradient fade(QPointF(0,0), QPointF(labelWidth, 0));
  fade.setColorAt(0, Qt::black);
  fade.setColorAt(0.95, Qt::black);
  fade.setColorAt(1.0, QColor(0xAA, 0xAA, 0xAA));

  QTextOption noWrap;
  noWrap.setWrapMode(QTextOption::NoWrap);

  // Choice area
  for (int row = 0; row < NUM_CHOICES; row++) {
    const int item = row + _offset;
    painter.eraseRect(0, y, w, yInc);
    if (item < _choices.size()) {
      const Choice &c = _choices[item];
      if (metrics.width(c.title()) > labelWidth) {
        painter.setPen(QPen(QBrush(fade), 1));
      } else {
        painter.setPen(QPen(Qt::black));
      }

      painter.drawText(QRectF(0, y, labelWidth, yInc), c.title(), noWrap);

      painter.save();
      if (row > 0) {
        painter.setPen(QColor(0xAA, 0xAA, 0xAA));
        painter.drawLine(50, y - 10, w - 50, y - 10);
      }

      painter.setPen(QColor(0x55, 0x55, 0x55));
      painter.drawRect(labelWidth + 10, y + metrics.leading(), yInc - 1, metrics.height());
      painter.drawText(hotkeyCenter - (metrics.width(_hotkeys[row]) / 2), y + baseline,
          QString(1, _hotkeys[row]));

      painter.restore();
    }
    y += yInc;
  }
}

void ChoiceView::keyPressEvent(QKeyEvent *event) {
  if (event->key() >= Qt::Key_0 && event->key() <= Qt::Key_9) {
    int chosen = event->key() - Qt::Key_0 + _offset - 1;
    if (chosen < _offset) chosen += 10;
    if (chosen < _choices.size()) {
      choose(chosen);
      return;
    }
  } else if (event->key() == Qt::Key_Escape) {
    goBack();
    return;
  } else if (event->key() == Qt::Key_Down) {
    pageDown();
    return;
  } else if (event->key() == Qt::Key_Up) {
    pageUp();
    return;
  }
  QWidget::keyPressEvent(event);
}

void ChoiceView::choose(int chosen) {
  emit choiceMade(_choices[chosen]);
}

void ChoiceView::goBack() {
  emit back();
}

void ChoiceView::setChoices(const QList<Choice> choices) {
  _choices = choices;
  if (_offset >= _choices.size()) {
    // Integer division floors here.
    _offset = (_choices.size() / 10) * 10;
  }
  emit morePages(_choices.size() / 10);
  refreshLabels();
}

void ChoiceView::pageDown() {
  if (_offset < _choices.size() - 10) {
    _offset += 10;
    refreshLabels();
  }
}

void ChoiceView::pageUp() {
  if (_offset >= 10) {
    _offset -= 10;
    refreshLabels();
  }
}

void ChoiceView::refreshLabels() {
  update();
  emit switchedToPage(_offset / 10);
}

bool operator<(Choice a, Choice b) {
  return a.title().compare(b.title(), Qt::CaseInsensitive) < 0;
}
<commit_msg>Rounded edges of hotkey mnemonics.<commit_after>#include "choiceview.h"

#include <QKeyEvent>
#include <QPaintEvent>
#include <QPainter>

Choice::Choice(const QString &title, const QString &id, const QStringList &params)
    : _id(id), _title(title), _params(params) {
}

const QString &Choice::id() const {
  return _id;
}

const QString &Choice::title() const {
  return _title;
}

const QStringList &Choice::params() const {
  return _params;
}

ChoiceView::ChoiceView(QWidget *parent)
    : QWidget(parent),
      _offset(0) {

  setFocusPolicy(Qt::StrongFocus);

  QFont myFont;
  myFont.setPointSize(20);
  setFont(myFont);
}

ChoiceView::~ChoiceView() { }

static const int arrowHeight = 8;

static char _hotkeys[] = { '1', '2', '3', '4', '5', '6', '7', '8', '9', '0' };
void ChoiceView::paintEvent(QPaintEvent *event) {
  QFontMetrics metrics(font());
  QPainter painter(this);

  int y = arrowHeight + 2;
  const int baseline = metrics.leading() + metrics.ascent() + 1;
  const int w = width(), h = height() - (y * 2);
  const int yInc = h / 10;
  const int labelWidth = w - yInc - 10;
  const int hotkeyCenter = w - (yInc / 2);

  // Top arrow
  const int center = w / 2;
  painter.eraseRect(0, 0, w, y);
  if (_offset > 0) {
    painter.drawLine(center, 0, center - arrowHeight, arrowHeight);
    painter.drawLine(center, 0, center + arrowHeight, arrowHeight);
    painter.drawLine(center - arrowHeight, arrowHeight, center + arrowHeight, arrowHeight);
  }

  // Bottom arrow
  painter.eraseRect(0, height() - y, w, y);
  if (_offset + 10 < _choices.size()) {
    painter.drawLine(center, height() - 1, center - arrowHeight, height() - arrowHeight - 1);
    painter.drawLine(center, height() - 1, center + arrowHeight, height() - arrowHeight - 1);
    painter.drawLine(center - arrowHeight, height() - arrowHeight - 1,
        center + arrowHeight, height() - arrowHeight - 1);
  }

  QLinearGradient fade(QPointF(0,0), QPointF(labelWidth, 0));
  fade.setColorAt(0, Qt::black);
  fade.setColorAt(0.95, Qt::black);
  fade.setColorAt(1.0, QColor(0xAA, 0xAA, 0xAA));

  QTextOption noWrap;
  noWrap.setWrapMode(QTextOption::NoWrap);

  // Choice area
  for (int row = 0; row < NUM_CHOICES; row++) {
    const int item = row + _offset;
    painter.eraseRect(0, y, w, yInc);
    if (item < _choices.size()) {
      const Choice &c = _choices[item];
      if (metrics.width(c.title()) > labelWidth) {
        painter.setPen(QPen(QBrush(fade), 1));
      } else {
        painter.setPen(QPen(Qt::black));
      }

      painter.drawText(QRectF(0, y, labelWidth, yInc), c.title(), noWrap);

      painter.save();
      if (row > 0) {
        painter.setPen(QColor(0xAA, 0xAA, 0xAA));
        painter.drawLine(50, y - 10, w - 50, y - 10);
      }

      painter.setPen(QColor(0x55, 0x55, 0x55));
      painter.drawRoundedRect(labelWidth + 10, y + metrics.leading(), yInc - 1, metrics.height(), 4, 4);
      painter.drawText(hotkeyCenter - (metrics.width(_hotkeys[row]) / 2), y + baseline,
          QString(1, _hotkeys[row]));

      painter.restore();
    }
    y += yInc;
  }
}

void ChoiceView::keyPressEvent(QKeyEvent *event) {
  if (event->key() >= Qt::Key_0 && event->key() <= Qt::Key_9) {
    int chosen = event->key() - Qt::Key_0 + _offset - 1;
    if (chosen < _offset) chosen += 10;
    if (chosen < _choices.size()) {
      choose(chosen);
      return;
    }
  } else if (event->key() == Qt::Key_Escape) {
    goBack();
    return;
  } else if (event->key() == Qt::Key_Down) {
    pageDown();
    return;
  } else if (event->key() == Qt::Key_Up) {
    pageUp();
    return;
  }
  QWidget::keyPressEvent(event);
}

void ChoiceView::choose(int chosen) {
  emit choiceMade(_choices[chosen]);
}

void ChoiceView::goBack() {
  emit back();
}

void ChoiceView::setChoices(const QList<Choice> choices) {
  _choices = choices;
  if (_offset >= _choices.size()) {
    // Integer division floors here.
    _offset = (_choices.size() / 10) * 10;
  }
  emit morePages(_choices.size() / 10);
  refreshLabels();
}

void ChoiceView::pageDown() {
  if (_offset < _choices.size() - 10) {
    _offset += 10;
    refreshLabels();
  }
}

void ChoiceView::pageUp() {
  if (_offset >= 10) {
    _offset -= 10;
    refreshLabels();
  }
}

void ChoiceView::refreshLabels() {
  update();
  emit switchedToPage(_offset / 10);
}

bool operator<(Choice a, Choice b) {
  return a.title().compare(b.title(), Qt::CaseInsensitive) < 0;
}
<|endoftext|>


<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2000, 2010 Oracle and/or its affiliates.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

#include <precomp.h>
#include <cosv/string.hxx>

// NOT FULLY DECLARED SERVICES
#include <string.h>
#include <cosv/comfunc.hxx>

namespace csv
{

inline const char *
str_from_StringOffset( const String &     i_rStr,
                       str::size       i_nOffset )
{
     return i_nOffset < i_rStr.size()
                ?   i_rStr.c_str() + i_nOffset
                :   "";
}

inline const char *
str_from_ptr( const char * i_str )
{

    return valid_str(i_str);
}

//*********************     String::S_Data    **********************//

inline String::
S_Data::S_Data()
    :   nCount(1)
{
}

String::
S_Data::S_Data( const char *        i_sData,
                size_type           i_nValidLength )
    :   aStr( str_from_ptr(i_sData),
              (i_nValidLength != str::maxsize
                    ?   i_nValidLength
                    :   strlen(i_sData)) ),
        nCount(1)
{
}

String::
S_Data::~S_Data()
{
    csv_assert( nCount == 0 );
}

const String::S_Data *
String::
S_Data::Acquire() const
{
#ifdef CSV_NO_MUTABLE
    ++ (const_cast< uintt& >(nCount));
#else
    ++nCount;
#endif
    return this;
}

void
String::
S_Data::Release() const
{
#ifdef CSV_NO_MUTABLE
    -- (const_cast< uintt& >(nCount));
#else
    --nCount;
#endif
    if (nCount == 0)
        delete (const_cast< S_Data* >(this));
}

//**************************     String    **************************//

String::String()
    :   pd( String::Null_().pd->Acquire() )
{
}

String::String( const char * i_str )
    :   pd( new S_Data(i_str) )
{
}

String::String( const char *        i_str,
                size_type           i_nLength )
    :   pd( new S_Data(i_str, i_nLength) )
{
}

String::String( const_iterator i_itBegin,
                const_iterator i_itEnd )
    :   pd( new S_Data(i_itBegin, size_type(i_itEnd - i_itBegin)) )
{
}

String::String( const self & i_rStr )
    :   pd( i_rStr.pd->Acquire() )
{
}

String::~String()
{
    pd->Release();
}

String &
String::operator=( const self & i_rStr )
{
    i_rStr.pd->Acquire();
    pd->Release();
    pd = i_rStr.pd;

    return *this;
}

String &
String::operator=( const char * i_str )
{
    const S_Data *
        pTemp = new S_Data(i_str);
    pd->Release();
    pd = pTemp;

    return *this;
}

void
String::assign( const char *        i_str,
                size_type           i_nLength )
{
    const S_Data *
        pTemp = new S_Data( i_str, i_nLength );
    pd->Release();
    pd = pTemp;
}

int
String::compare( const self & i_rStr ) const
{
    return strcmp( c_str(), i_rStr.c_str() );
}

int
String::compare( const CharOrder_Table & i_rOrder,
                 const self &            i_rStr ) const
{
    return csv::compare( i_rOrder, c_str(), i_rStr.c_str() );
}

const String &
String::Null_()
{
    // Must not use the default constructor! Because that one calls
    //   this function, which would create a circular dependency.
    static const String aNull_("");
    return aNull_;
}

const char &
String::Nulch_()
{
    static const char cNull_ = '\0';
    return cNull_;
}

int
compare( const String &      i_s1,
         csv::str::position        i_nStartPosition1,
         const char *              i_s2,
         csv::str::size            i_nLength )
{
    const char * pS1 = str_from_StringOffset( i_s1, i_nStartPosition1 );

    if ( i_nLength != csv::str::maxsize )
        return strncmp( pS1,
                        i_s2,
                        i_nLength );
    else
        return strcmp( pS1,
                       i_s2 );
}

int
compare( const CharOrder_Table &            i_rOrder,
         const char *                       i_s1,
         const char *                       i_s2 )
{
    const char * it1 = i_s1;
    const char * it2 = i_s2;
    for ( ; i_rOrder(*it1) == i_rOrder(*it2) AND *it1 != '\0'; ++it1, ++it2 )
    {}
    return int( i_rOrder(*it1) - i_rOrder(*it2) );
}

int
compare( const CharOrder_Table &            i_rOrder,
         const char *                       i_s1,
         const char *                       i_s2,
         csv::str::size                     i_nLength )
{
    const char * sEnd = i_s1 + i_nLength;

    const char * it1 = i_s1;
    const char * it2 = i_s2;
    for ( ; i_rOrder(*it1) == i_rOrder(*it2) AND *it1 != '\0' AND it1 != sEnd; ++it1, ++it2 )
    {}

    if ( it1 != sEnd )
        return int( i_rOrder(*it1) - i_rOrder(*it2) );
    else
        return 0;
}

}   // namespace csv

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<commit_msg>ditch unused compare<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2000, 2010 Oracle and/or its affiliates.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

#include <precomp.h>
#include <cosv/string.hxx>

// NOT FULLY DECLARED SERVICES
#include <string.h>
#include <cosv/comfunc.hxx>

namespace csv
{

inline const char *
str_from_StringOffset( const String &     i_rStr,
                       str::size       i_nOffset )
{
     return i_nOffset < i_rStr.size()
                ?   i_rStr.c_str() + i_nOffset
                :   "";
}

inline const char *
str_from_ptr( const char * i_str )
{

    return valid_str(i_str);
}

//*********************     String::S_Data    **********************//

inline String::
S_Data::S_Data()
    :   nCount(1)
{
}

String::
S_Data::S_Data( const char *        i_sData,
                size_type           i_nValidLength )
    :   aStr( str_from_ptr(i_sData),
              (i_nValidLength != str::maxsize
                    ?   i_nValidLength
                    :   strlen(i_sData)) ),
        nCount(1)
{
}

String::
S_Data::~S_Data()
{
    csv_assert( nCount == 0 );
}

const String::S_Data *
String::
S_Data::Acquire() const
{
#ifdef CSV_NO_MUTABLE
    ++ (const_cast< uintt& >(nCount));
#else
    ++nCount;
#endif
    return this;
}

void
String::
S_Data::Release() const
{
#ifdef CSV_NO_MUTABLE
    -- (const_cast< uintt& >(nCount));
#else
    --nCount;
#endif
    if (nCount == 0)
        delete (const_cast< S_Data* >(this));
}

//**************************     String    **************************//

String::String()
    :   pd( String::Null_().pd->Acquire() )
{
}

String::String( const char * i_str )
    :   pd( new S_Data(i_str) )
{
}

String::String( const char *        i_str,
                size_type           i_nLength )
    :   pd( new S_Data(i_str, i_nLength) )
{
}

String::String( const_iterator i_itBegin,
                const_iterator i_itEnd )
    :   pd( new S_Data(i_itBegin, size_type(i_itEnd - i_itBegin)) )
{
}

String::String( const self & i_rStr )
    :   pd( i_rStr.pd->Acquire() )
{
}

String::~String()
{
    pd->Release();
}

String &
String::operator=( const self & i_rStr )
{
    i_rStr.pd->Acquire();
    pd->Release();
    pd = i_rStr.pd;

    return *this;
}

String &
String::operator=( const char * i_str )
{
    const S_Data *
        pTemp = new S_Data(i_str);
    pd->Release();
    pd = pTemp;

    return *this;
}

void
String::assign( const char *        i_str,
                size_type           i_nLength )
{
    const S_Data *
        pTemp = new S_Data( i_str, i_nLength );
    pd->Release();
    pd = pTemp;
}

int
String::compare( const self & i_rStr ) const
{
    return strcmp( c_str(), i_rStr.c_str() );
}

int
String::compare( const CharOrder_Table & i_rOrder,
                 const self &            i_rStr ) const
{
    return csv::compare( i_rOrder, c_str(), i_rStr.c_str() );
}

const String &
String::Null_()
{
    // Must not use the default constructor! Because that one calls
    //   this function, which would create a circular dependency.
    static const String aNull_("");
    return aNull_;
}

const char &
String::Nulch_()
{
    static const char cNull_ = '\0';
    return cNull_;
}

int
compare( const String &      i_s1,
         csv::str::position        i_nStartPosition1,
         const char *              i_s2,
         csv::str::size            i_nLength )
{
    const char * pS1 = str_from_StringOffset( i_s1, i_nStartPosition1 );

    if ( i_nLength != csv::str::maxsize )
        return strncmp( pS1,
                        i_s2,
                        i_nLength );
    else
        return strcmp( pS1,
                       i_s2 );
}

int
compare( const CharOrder_Table &            i_rOrder,
         const char *                       i_s1,
         const char *                       i_s2 )
{
    const char * it1 = i_s1;
    const char * it2 = i_s2;
    for ( ; i_rOrder(*it1) == i_rOrder(*it2) AND *it1 != '\0'; ++it1, ++it2 )
    {}
    return int( i_rOrder(*it1) - i_rOrder(*it2) );
}

}   // namespace csv

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


<commit_before>
//!
//! This file implements the entire test catalog, by implementing all functions
//! required for a disir plugin that may serve configs generated from mold, and molds
//! defined programmatically. This is part of the extended disir library so that
//! it is easy to iterate and test new plugins.
//!

#include <map>
#include <utility>
#include <string.h>
#include <limits.h>

#include <disir/disir.h>
#include <disir/util.h>
#include <disir/plugin.h>
#include <disir/test.h>
#include <disir/fslib/util.h>

#include "mqueue.h"

// Include programmatic implementation of several molds
#include "basic_keyval.cc"
#include "basic_section.cc"
#include "json_test_mold.cc"
#include "restriction_keyval_numeric_types.cc"
#include "restriction_entries.cc"
#include "restriction_config_parent_keyval_min_entry.cc"
#include "restriction_config_parent_keyval_max_entry.cc"
#include "restriction_config_parent_section_max_entry.cc"
#include "restriction_section_parent_keyval_max_entry.cc"
#include "basic_version_difference.cc"
#include "complex_section.cc"
#include "config_query_permutations.cc"

typedef enum disir_status (*output_mold)(struct disir_mold **);

//! Internal static map to store test molds by id
static std::map<std::string, output_mold> molds = {
    std::make_pair ("basic_keyval", basic_keyval),
    std::make_pair ("basic_section", basic_section),
    std::make_pair ("json_test_mold", json_test_mold),
    std::make_pair ("restriction_keyval_numeric_types", restriction_keyval_numeric_types),
    std::make_pair ("restriction_entries", restriction_entries),
    std::make_pair ("restriction_config_parent_keyval_min_entry",
                    restriction_config_parent_keyval_min_entry),
    std::make_pair ("restriction_config_parent_keyval_max_entry",
                    restriction_config_parent_keyval_max_entry),
    std::make_pair ("restriction_config_parent_section_max_entry",
                    restriction_config_parent_section_max_entry),
    std::make_pair ("restriction_section_parent_keyval_max_entry",
                    restriction_section_parent_keyval_max_entry),
    std::make_pair ("basic_version_difference", basic_version_difference),
    std::make_pair ("complex_section", complex_section),
    std::make_pair ("config_query_permutations", config_query_permutations),
    std::make_pair ("nested/basic_keyval", basic_keyval),
    std::make_pair ("nested/", basic_keyval),
    std::make_pair ("super/", basic_keyval),
    std::make_pair ("super/nested/", basic_keyval),
    std::make_pair ("super/nested/basic_keyval", basic_keyval),
};

enum disir_status
dio_test_config_read (struct disir_instance *instance,
                      struct disir_register_plugin *plugin, const char *entry_id,
                      struct disir_mold *mold, struct disir_config **config)
{
    enum disir_status status;
    output_mold func_mold;
    char namespace_entry[PATH_MAX];

    (void) &instance;
    (void) &plugin;

    func_mold = molds[std::string(entry_id)];
    if (func_mold == NULL)
    {
        if (fslib_namespace_entry (entry_id, namespace_entry) == NULL)
            return DISIR_STATUS_INVALID_ARGUMENT;

        func_mold = molds[namespace_entry];
        if (func_mold == NULL)
            return DISIR_STATUS_INVALID_ARGUMENT;
    }

    status = func_mold (&mold);
    if (status != DISIR_STATUS_OK)
        return status;

    status = disir_generate_config_from_mold (mold, NULL, config);
    // We are finished with our allocated mold
    disir_mold_finished (&mold);
    return status;
}

enum disir_status
dio_test_config_entries (struct disir_instance *instance,
                         struct disir_register_plugin *plugin, struct disir_entry **entries)
{
    return dio_test_mold_entries (instance, plugin, entries);
}

enum disir_status
dio_test_config_query (struct disir_instance *instance, struct disir_register_plugin *plugin,
                       const char *entry_id, struct disir_entry **entry)
{
    (void) &instance;
    (void) &plugin;
    (void) &entry;

    if (molds[entry_id] == NULL)
        return DISIR_STATUS_NOT_EXIST;
    else
        return DISIR_STATUS_EXISTS;
}

enum disir_status
dio_test_mold_read (struct disir_instance *instance, struct disir_register_plugin *plugin,
                    const char *entry_id, struct disir_mold **mold)
{
    enum disir_status status;
    output_mold func_mold;
    char namespace_entry[PATH_MAX];

    (void) &instance;
    (void) &plugin;
    (void) &entry_id;

    func_mold = molds[entry_id];
    if (func_mold == NULL)
    {

        if (fslib_namespace_entry (entry_id, namespace_entry) == NULL)
            return DISIR_STATUS_INVALID_ARGUMENT;

        func_mold = molds[namespace_entry];
        if (func_mold == NULL)
        {
            return DISIR_STATUS_INVALID_ARGUMENT;
        }
    }

    status = func_mold (mold);
    if (status != DISIR_STATUS_OK)
        return status;

    return DISIR_STATUS_OK;;
}

enum disir_status
dio_test_mold_entries (struct disir_instance *instance,
                       struct disir_register_plugin *plugin, struct disir_entry **entries)
{
    struct disir_entry *queue;
    struct disir_entry *entry;

    (void) &instance;
    (void) &plugin;

    queue = NULL;

    for (auto i = molds.begin(); i != molds.end(); ++i)
    {
        entry  = (struct disir_entry *) calloc (1, sizeof (struct disir_entry));
        if (entry == NULL)
            continue;

        entry->de_entry_name = strdup (i->first.c_str());
        entry->flag.DE_READABLE = 1;
        entry->flag.DE_WRITABLE = 1;
        if (i->first.back() == '/')
        {
            entry->flag.DE_NAMESPACE_ENTRY = 1;
        }
        MQ_ENQUEUE (queue, entry);
    }

    *entries = queue;

    return DISIR_STATUS_OK;
}

enum disir_status
dio_test_mold_query (struct disir_instance *instance, struct disir_register_plugin *plugin,
                     const char *entry_id, struct disir_entry **entry)
{
    char namespace_entry[PATH_MAX];

    (void) &instance;
    (void) &plugin;

    if (entry_id == NULL)
        return DISIR_STATUS_INTERNAL_ERROR;;

    std::string name(entry_id);
    if (molds.count (name) == 0)
    {
        if (fslib_namespace_entry (entry_id, namespace_entry) == NULL)
            return DISIR_STATUS_INVALID_ARGUMENT;

        name = std::string (namespace_entry);
        // The namespace entry does not exist
        if (molds.count (name) == 0)
        {
            return DISIR_STATUS_NOT_EXIST;
        }
    }

    if (entry != NULL)
    {
        *entry  = (struct disir_entry *) calloc (1, sizeof (struct disir_entry));
        if (*entry == NULL)
            return DISIR_STATUS_NO_MEMORY;

        (*entry)->de_entry_name = strdup (name.c_str());
        (*entry)->flag.DE_READABLE = 1;
        (*entry)->flag.DE_WRITABLE = 1;
        if (name.back() == '/')
        {
            (*entry)->flag.DE_NAMESPACE_ENTRY = 1;
        }
    }

    return DISIR_STATUS_EXISTS;
}

<commit_msg>fix: correct error code in test plugin corner-case<commit_after>
//!
//! This file implements the entire test catalog, by implementing all functions
//! required for a disir plugin that may serve configs generated from mold, and molds
//! defined programmatically. This is part of the extended disir library so that
//! it is easy to iterate and test new plugins.
//!

#include <map>
#include <utility>
#include <string.h>
#include <limits.h>

#include <disir/disir.h>
#include <disir/util.h>
#include <disir/plugin.h>
#include <disir/test.h>
#include <disir/fslib/util.h>

#include "mqueue.h"

// Include programmatic implementation of several molds
#include "basic_keyval.cc"
#include "basic_section.cc"
#include "json_test_mold.cc"
#include "restriction_keyval_numeric_types.cc"
#include "restriction_entries.cc"
#include "restriction_config_parent_keyval_min_entry.cc"
#include "restriction_config_parent_keyval_max_entry.cc"
#include "restriction_config_parent_section_max_entry.cc"
#include "restriction_section_parent_keyval_max_entry.cc"
#include "basic_version_difference.cc"
#include "complex_section.cc"
#include "config_query_permutations.cc"

typedef enum disir_status (*output_mold)(struct disir_mold **);

//! Internal static map to store test molds by id
static std::map<std::string, output_mold> molds = {
    std::make_pair ("basic_keyval", basic_keyval),
    std::make_pair ("basic_section", basic_section),
    std::make_pair ("json_test_mold", json_test_mold),
    std::make_pair ("restriction_keyval_numeric_types", restriction_keyval_numeric_types),
    std::make_pair ("restriction_entries", restriction_entries),
    std::make_pair ("restriction_config_parent_keyval_min_entry",
                    restriction_config_parent_keyval_min_entry),
    std::make_pair ("restriction_config_parent_keyval_max_entry",
                    restriction_config_parent_keyval_max_entry),
    std::make_pair ("restriction_config_parent_section_max_entry",
                    restriction_config_parent_section_max_entry),
    std::make_pair ("restriction_section_parent_keyval_max_entry",
                    restriction_section_parent_keyval_max_entry),
    std::make_pair ("basic_version_difference", basic_version_difference),
    std::make_pair ("complex_section", complex_section),
    std::make_pair ("config_query_permutations", config_query_permutations),
    std::make_pair ("nested/basic_keyval", basic_keyval),
    std::make_pair ("nested/", basic_keyval),
    std::make_pair ("super/", basic_keyval),
    std::make_pair ("super/nested/", basic_keyval),
    std::make_pair ("super/nested/basic_keyval", basic_keyval),
};

enum disir_status
dio_test_config_read (struct disir_instance *instance,
                      struct disir_register_plugin *plugin, const char *entry_id,
                      struct disir_mold *mold, struct disir_config **config)
{
    enum disir_status status;
    output_mold func_mold;
    char namespace_entry[PATH_MAX];

    (void) &instance;
    (void) &plugin;

    func_mold = molds[std::string(entry_id)];
    if (func_mold == NULL)
    {
        if (fslib_namespace_entry (entry_id, namespace_entry) == NULL)
            return DISIR_STATUS_INVALID_ARGUMENT;

        func_mold = molds[namespace_entry];
        if (func_mold == NULL)
            return DISIR_STATUS_INVALID_ARGUMENT;
    }

    status = func_mold (&mold);
    if (status != DISIR_STATUS_OK)
        return status;

    status = disir_generate_config_from_mold (mold, NULL, config);
    // We are finished with our allocated mold
    disir_mold_finished (&mold);
    return status;
}

enum disir_status
dio_test_config_entries (struct disir_instance *instance,
                         struct disir_register_plugin *plugin, struct disir_entry **entries)
{
    return dio_test_mold_entries (instance, plugin, entries);
}

enum disir_status
dio_test_config_query (struct disir_instance *instance, struct disir_register_plugin *plugin,
                       const char *entry_id, struct disir_entry **entry)
{
    (void) &instance;
    (void) &plugin;
    (void) &entry;

    if (molds[entry_id] == NULL)
        return DISIR_STATUS_NOT_EXIST;
    else
        return DISIR_STATUS_EXISTS;
}

enum disir_status
dio_test_mold_read (struct disir_instance *instance, struct disir_register_plugin *plugin,
                    const char *entry_id, struct disir_mold **mold)
{
    enum disir_status status;
    output_mold func_mold;
    char namespace_entry[PATH_MAX];

    (void) &instance;
    (void) &plugin;
    (void) &entry_id;

    func_mold = molds[entry_id];
    if (func_mold == NULL)
    {

        if (fslib_namespace_entry (entry_id, namespace_entry) == NULL)
            return DISIR_STATUS_INVALID_ARGUMENT;

        func_mold = molds[namespace_entry];
        if (func_mold == NULL)
        {
            return DISIR_STATUS_INVALID_ARGUMENT;
        }
    }

    status = func_mold (mold);
    if (status != DISIR_STATUS_OK)
        return status;

    return DISIR_STATUS_OK;;
}

enum disir_status
dio_test_mold_entries (struct disir_instance *instance,
                       struct disir_register_plugin *plugin, struct disir_entry **entries)
{
    struct disir_entry *queue;
    struct disir_entry *entry;

    (void) &instance;
    (void) &plugin;

    queue = NULL;

    for (auto i = molds.begin(); i != molds.end(); ++i)
    {
        entry  = (struct disir_entry *) calloc (1, sizeof (struct disir_entry));
        if (entry == NULL)
            continue;

        entry->de_entry_name = strdup (i->first.c_str());
        entry->flag.DE_READABLE = 1;
        entry->flag.DE_WRITABLE = 1;
        if (i->first.back() == '/')
        {
            entry->flag.DE_NAMESPACE_ENTRY = 1;
        }
        MQ_ENQUEUE (queue, entry);
    }

    *entries = queue;

    return DISIR_STATUS_OK;
}

enum disir_status
dio_test_mold_query (struct disir_instance *instance, struct disir_register_plugin *plugin,
                     const char *entry_id, struct disir_entry **entry)
{
    char namespace_entry[PATH_MAX];

    (void) &instance;
    (void) &plugin;

    if (entry_id == NULL)
        return DISIR_STATUS_INTERNAL_ERROR;;

    std::string name(entry_id);
    if (molds.count (name) == 0)
    {
        if (fslib_namespace_entry (entry_id, namespace_entry) == NULL)
            return DISIR_STATUS_NOT_EXIST;

        name = std::string (namespace_entry);
        // The namespace entry does not exist
        if (molds.count (name) == 0)
        {
            return DISIR_STATUS_NOT_EXIST;
        }
    }

    if (entry != NULL)
    {
        *entry  = (struct disir_entry *) calloc (1, sizeof (struct disir_entry));
        if (*entry == NULL)
            return DISIR_STATUS_NO_MEMORY;

        (*entry)->de_entry_name = strdup (name.c_str());
        (*entry)->flag.DE_READABLE = 1;
        (*entry)->flag.DE_WRITABLE = 1;
        if (name.back() == '/')
        {
            (*entry)->flag.DE_NAMESPACE_ENTRY = 1;
        }
    }

    return DISIR_STATUS_EXISTS;
}

<|endoftext|>


<commit_before>/* Copyright © 2001-2014, Canal TP and/or its affiliates. All rights reserved.

This file is part of Navitia,
    the software to build cool stuff with public transport.

Hope you'll enjoy and contribute to this project,
    powered by Canal TP (www.canaltp.fr).
Help us simplify mobility and open public transport:
    a non ending quest to the responsive locomotion way of traveling!

LICENCE: This program is free software; you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.

You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.

Stay tuned using
twitter @navitia
IRC #navitia on freenode
https://groups.google.com/d/forum/navitia
www.navitia.io
*/

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "linenoise/linenoise.h"
#include "raptor.h"
#include "routing/raptor_api.h"
#include "type/data.h"
#include "utils/timer.h"
#include "type/response.pb.h"
#include "routing_cli_utils.h"
#include "ptreferential/ptreferential_api.h"
#include <boost/program_options.hpp>
#include <boost/algorithm/string.hpp>
#include "type/pb_converter.h"

namespace nr = navitia::routing;
namespace nt = navitia::type;
namespace bt = boost::posix_time;
namespace po = boost::program_options ;
namespace pb = pbnavitia;

void completion(const char *buf, linenoiseCompletions *lc) {
    if (buf[0] == 'j' || buf[0] == '\0') {
        linenoiseAddCompletion(lc,"journey");
    }
    if (buf[0] == 'p' || buf[0] == '\0') {
        linenoiseAddCompletion(lc,"ptref");
    }
}
/* This program takes a path to a nav.lz4 navitia's file
 * It will be loaded at the begginning of the program
 */
int main(int argc, char **argv) {
    if (argc < 2) {
        std::cerr << "A filename is needed" << std::endl;
        return 1;
    }

    navitia::cli::compute_options compute_opt;
    compute_opt.load(argv[1]);
    po::variables_map vm;
    char *line;
    /* Parse options, with --multiline we enable multi line editing. */
    linenoiseSetCompletionCallback(completion);
    linenoiseHistoryLoad("history.txt"); /* Load the history at startup */
    while((line = linenoise("hello> ")) != nullptr) {
        linenoiseHistoryAdd(line);
        linenoiseHistorySave("history.txt");
        std::string str_line(line);
        auto splitted_line = po::split_unix(str_line);
        if (splitted_line.empty()) {
            continue;
        }
        if (splitted_line[0] == "journey") {
            po::store(po::command_line_parser(splitted_line).options(compute_opt.desc).run(), compute_opt.vm);
            po::notify(compute_opt.vm);
            compute_opt.compute();
        } else if (splitted_line[0] == "ptref") {
            if (splitted_line.size() < 2) {
                std::cerr << "an ID is needed" << std::endl;
                continue;
            }
            const std::string id = splitted_line[1];
            #define SHOW_ID_CLI(type_name, collection_name) \
            auto collection_name##_map = compute_opt.data.pt_data->collection_name##_map;\
            if ( collection_name##_map.find(id) != collection_name##_map.end()) {\
                pbnavitia::type_name p;\
                navitia::fill_pb_object(collection_name##_map.at(id), compute_opt.data, &p);\
                std::cout << p.DebugString() << std::endl;}
            ITERATE_NAVITIA_PT_TYPES(SHOW_ID_CLI)
        }
    }
    return 0;
}
<commit_msg>Cli: clear the vm map<commit_after>/* Copyright © 2001-2014, Canal TP and/or its affiliates. All rights reserved.

This file is part of Navitia,
    the software to build cool stuff with public transport.

Hope you'll enjoy and contribute to this project,
    powered by Canal TP (www.canaltp.fr).
Help us simplify mobility and open public transport:
    a non ending quest to the responsive locomotion way of traveling!

LICENCE: This program is free software; you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.

You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.

Stay tuned using
twitter @navitia
IRC #navitia on freenode
https://groups.google.com/d/forum/navitia
www.navitia.io
*/

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "linenoise/linenoise.h"
#include "raptor.h"
#include "routing/raptor_api.h"
#include "type/data.h"
#include "utils/timer.h"
#include "type/response.pb.h"
#include "routing_cli_utils.h"
#include "ptreferential/ptreferential_api.h"
#include <boost/program_options.hpp>
#include <boost/algorithm/string.hpp>
#include "type/pb_converter.h"

namespace nr = navitia::routing;
namespace nt = navitia::type;
namespace bt = boost::posix_time;
namespace po = boost::program_options ;
namespace pb = pbnavitia;

void completion(const char *buf, linenoiseCompletions *lc) {
    if (buf[0] == 'j' || buf[0] == '\0') {
        linenoiseAddCompletion(lc,"journey");
    }
    if (buf[0] == 'p' || buf[0] == '\0') {
        linenoiseAddCompletion(lc,"ptref");
    }
}
/* This program takes a path to a nav.lz4 navitia's file
 * It will be loaded at the begginning of the program
 */
int main(int argc, char **argv) {
    if (argc < 2) {
        std::cerr << "A filename is needed" << std::endl;
        return 1;
    }

    navitia::cli::compute_options compute_opt;
    compute_opt.load(argv[1]);
    po::variables_map vm;
    char *line;
    /* Parse options, with --multiline we enable multi line editing. */
    linenoiseSetCompletionCallback(completion);
    linenoiseHistoryLoad("history.txt"); /* Load the history at startup */
    while((line = linenoise("hello> ")) != nullptr) {
        linenoiseHistoryAdd(line);
        linenoiseHistorySave("history.txt");
        std::string str_line(line);
        auto splitted_line = po::split_unix(str_line);
        if (splitted_line.empty()) {
            continue;
        }
        if (splitted_line[0] == "journey") {
            compute_opt.vm.clear();
            po::store(po::command_line_parser(splitted_line).options(compute_opt.desc).run(), compute_opt.vm);
            po::notify(compute_opt.vm);
            compute_opt.compute();
        } else if (splitted_line[0] == "ptref") {
            if (splitted_line.size() < 2) {
                std::cerr << "an ID is needed" << std::endl;
                continue;
            }
            const std::string id = splitted_line[1];
            #define SHOW_ID_CLI(type_name, collection_name) \
            auto collection_name##_map = compute_opt.data.pt_data->collection_name##_map;\
            if ( collection_name##_map.find(id) != collection_name##_map.end()) {\
                pbnavitia::type_name p;\
                navitia::fill_pb_object(collection_name##_map.at(id), compute_opt.data, &p);\
                std::cout << p.DebugString() << std::endl;}
            ITERATE_NAVITIA_PT_TYPES(SHOW_ID_CLI)
        }
    }
    return 0;
}
<|endoftext|>


<commit_before>#include <QSqlQuery>
#include <QSqlRecord>
#include <QSqlError>

#include "raster.h"
#include "symboltable.h"
#include "astnode.h"
#include "idnode.h"
#include "operationnode.h"
#include "expressionnode.h"
#include "symboltable.h"
#include "formatter.h"
#include "formatters.h"
#include "scriptnode.h"
#include "table.h"
#include "featurecoverage.h"
#include "feature.h"
#include "numericrange.h"
#include "numericdomain.h"
#include "connectorinterface.h"
#include "factory.h"
#include "abstractfactory.h"
#include "connectorfactory.h"
#include "catalog.h"
#include "mastercatalog.h"
#include "ilwiscontext.h"
#include "juliantime.h"
#include "selectnode.h"
#include "selectornode.h"
#include "outparametersnode.h"
#include "assignmentnode.h"

using namespace Ilwis;

AssignmentNode::AssignmentNode() : _defintion(false)
{
}

bool AssignmentNode::isDefinition() const
{
    return _defintion;
}

void AssignmentNode::setDefintion(bool yesno)
{
    _defintion= yesno;
}

void AssignmentNode::setExpression(ASTNode *node)
{
    _expression =QSharedPointer<ASTNode>(node);
}

QString AssignmentNode::nodeType() const
{
    return "assignment";
}

IIlwisObject AssignmentNode::getObject(const Symbol& sym) const {
    IlwisTypes tp = sym._type;
    if ( tp & itRASTER)
            return sym._var.value<Ilwis::IRasterCoverage>().as<IlwisObject>();
    if ( tp & itFEATURE)
            return sym._var.value<Ilwis::IFeatureCoverage>().as<IlwisObject>();
    return IIlwisObject();

}

void AssignmentNode::getFormat(QSharedPointer<ASTNode>& node, QString& format, QString& fnamespace) const {
    Formatter *fnode = static_cast<Formatter *>(node->child(0).data());
    format = fnode->format();
    fnamespace = fnode->fnamespace();

    if ( format == "" || format == sUNDEF) {
        Formatter *fnode = ScriptNode::activeFormat(itRASTER);
        if ( fnode) {
            format = fnode->format();
            fnamespace = fnode->fnamespace();
        }
    }
}

void AssignmentNode::store2Format(QSharedPointer<ASTNode>& node, const Symbol& sym, const QString& result) {
    QString format, fnamespace;
    getFormat(node, format, fnamespace);
    if ( format != "" && format != sUNDEF) {
        Ilwis::IIlwisObject object = getObject(sym);
        bool wasAnonymous = object->isAnonymous();
        QUrl url = context()->workingCatalog()->source().url().toString() + "/" + result;
        object->name(result);
        object->connectTo(url, format, fnamespace, Ilwis::IlwisObject::cmOUTPUT);
        object->createTime(Ilwis::Time::now());
        if ( wasAnonymous)
            mastercatalog()->addItems({object->source(IlwisObject::cmOUTPUT | IlwisObject::cmEXTENDED)});

        object->store({"storemode",Ilwis::IlwisObject::smMETADATA | Ilwis::IlwisObject::smBINARYDATA});

     }
}

bool AssignmentNode::evaluate(SymbolTable& symbols, int scope, ExecutionContext *ctx)
{
    if ( _expression.isNull())
        return false;

    bool res = _expression->evaluate(symbols, scope, ctx);
    if ( res) {
        NodeValue val = _expression->value();
        for(int i = 0; i < val.size(); ++i) {
            Symbol sym = symbols.getSymbol(val.id(i),SymbolTable::gaREMOVEIFANON);
            IlwisTypes tp = sym.isValid() ? sym._type : itUNKNOWN;
            QString result = _outParms->id(i);
            QSharedPointer<ASTNode> specifier = _outParms->specifier(result);
            if ( !specifier.isNull()) {
                if ( specifier->noOfChilderen()!= 1)
                    return ERROR2(ERR_NO_OBJECT_TYPE_FOR_2, "Output object", "expression");
                store2Format(specifier, sym, result);

            }
            if (  hasType(tp, itILWISOBJECT)) {
                bool ok;
                if ( hasType(tp, itRASTER)) {
                    ok = copyObject<RasterCoverage>(sym, result,symbols);
                }
                else if hasType(tp, itFEATURE)
                        ok = copyObject<FeatureCoverage>(sym, result,symbols);
                else if hasType(tp, itTABLE){
                    ok = copyObject<Table>(sym, result,symbols,true);
                    QSharedPointer<Selector> selector = _outParms->selector(result);
                    if (!selector.isNull()){
                        QString varName = selector->variable();
                        ITable source =  sym._var.value<ITable>();
                        QString oldColName = ctx->_additionalInfo[source->name()].toString();
                        QVariant newT= symbols.getValue(result);
                        ITable newTable = newT.value<ITable>();
                        ColumnDefinition coldef = newTable->columndefinition(oldColName);
                        if ( coldef.isValid()){
                            coldef.name(varName);
                            newTable->columndefinition(coldef);
                        }
                    }
                }

                if(!ok) {
                    throw ErrorObject(QString(TR(ERR_OPERATION_FAILID1).arg("assignment")));
                }
                ctx->clear(true);
                ctx->_results.push_back(result);
                return ok;

            } else {
                sym = symbols.getSymbol(result,SymbolTable::gaREMOVEIFANON);
                tp = sym.isValid() ? sym._type : itUNKNOWN;
                if ( tp == itUNKNOWN) {
                    tp = Domain::ilwType(val);
                }
            }
            ctx->clear();
           // symbols.addSymbol(result, scope, tp, _expression->value());
            ctx->addOutput(symbols,_expression->value(),result, tp, Resource());

            return true;
        }
    }
    return false;
}

void AssignmentNode::addOutputs(OutParametersNode *p)
{
    _outParms.reset(p);
}

void AssignmentNode::setOutId(IDNode *idnode)
{
    _outParms.reset(new OutParametersNode());
    _outParms->addResult(idnode);

}

<commit_msg>wierd syntax error that wasnt detected by the compiler<commit_after>#include <QSqlQuery>
#include <QSqlRecord>
#include <QSqlError>

#include "raster.h"
#include "symboltable.h"
#include "astnode.h"
#include "idnode.h"
#include "operationnode.h"
#include "expressionnode.h"
#include "symboltable.h"
#include "formatter.h"
#include "formatters.h"
#include "scriptnode.h"
#include "table.h"
#include "featurecoverage.h"
#include "feature.h"
#include "numericrange.h"
#include "numericdomain.h"
#include "connectorinterface.h"
#include "factory.h"
#include "abstractfactory.h"
#include "connectorfactory.h"
#include "catalog.h"
#include "mastercatalog.h"
#include "ilwiscontext.h"
#include "juliantime.h"
#include "selectnode.h"
#include "selectornode.h"
#include "outparametersnode.h"
#include "assignmentnode.h"

using namespace Ilwis;

AssignmentNode::AssignmentNode() : _defintion(false)
{
}

bool AssignmentNode::isDefinition() const
{
    return _defintion;
}

void AssignmentNode::setDefintion(bool yesno)
{
    _defintion= yesno;
}

void AssignmentNode::setExpression(ASTNode *node)
{
    _expression =QSharedPointer<ASTNode>(node);
}

QString AssignmentNode::nodeType() const
{
    return "assignment";
}

IIlwisObject AssignmentNode::getObject(const Symbol& sym) const {
    IlwisTypes tp = sym._type;
    if ( tp & itRASTER)
            return sym._var.value<Ilwis::IRasterCoverage>().as<IlwisObject>();
    if ( tp & itFEATURE)
            return sym._var.value<Ilwis::IFeatureCoverage>().as<IlwisObject>();
    return IIlwisObject();

}

void AssignmentNode::getFormat(QSharedPointer<ASTNode>& node, QString& format, QString& fnamespace) const {
    Formatter *fnode = static_cast<Formatter *>(node->child(0).data());
    format = fnode->format();
    fnamespace = fnode->fnamespace();

    if ( format == "" || format == sUNDEF) {
        Formatter *fnode = ScriptNode::activeFormat(itRASTER);
        if ( fnode) {
            format = fnode->format();
            fnamespace = fnode->fnamespace();
        }
    }
}

void AssignmentNode::store2Format(QSharedPointer<ASTNode>& node, const Symbol& sym, const QString& result) {
    QString format, fnamespace;
    getFormat(node, format, fnamespace);
    if ( format != "" && format != sUNDEF) {
        Ilwis::IIlwisObject object = getObject(sym);
        bool wasAnonymous = object->isAnonymous();
        QUrl url = context()->workingCatalog()->source().url().toString() + "/" + result;
        object->name(result);
        object->connectTo(url, format, fnamespace, Ilwis::IlwisObject::cmOUTPUT);
        object->createTime(Ilwis::Time::now());
        if ( wasAnonymous)
            mastercatalog()->addItems({object->source(IlwisObject::cmOUTPUT | IlwisObject::cmEXTENDED)});

        object->store({"storemode",Ilwis::IlwisObject::smMETADATA | Ilwis::IlwisObject::smBINARYDATA});

     }
}

bool AssignmentNode::evaluate(SymbolTable& symbols, int scope, ExecutionContext *ctx)
{
    if ( _expression.isNull())
        return false;

    bool res = _expression->evaluate(symbols, scope, ctx);
    if ( res) {
        NodeValue val = _expression->value();
        for(int i = 0; i < val.size(); ++i) {
            Symbol sym = symbols.getSymbol(val.id(i),SymbolTable::gaREMOVEIFANON);
            IlwisTypes tp = sym.isValid() ? sym._type : itUNKNOWN;
            QString result = _outParms->id(i);
            QSharedPointer<ASTNode> specifier = _outParms->specifier(result);
            if ( !specifier.isNull()) {
                if ( specifier->noOfChilderen()!= 1)
                    return ERROR2(ERR_NO_OBJECT_TYPE_FOR_2, "Output object", "expression");
                store2Format(specifier, sym, result);

            }
            if (  hasType(tp, itILWISOBJECT)) {
                bool ok;
                if ( hasType(tp, itRASTER)) {
                    ok = copyObject<RasterCoverage>(sym, result,symbols);
                }
                else if (hasType(tp, itFEATURE))
                        ok = copyObject<FeatureCoverage>(sym, result,symbols);
                else if (hasType(tp, itTABLE)){
                    ok = copyObject<Table>(sym, result,symbols,true);
                    QSharedPointer<Selector> selector = _outParms->selector(result);
                    if (!selector.isNull()){
                        QString varName = selector->variable();
                        ITable source =  sym._var.value<ITable>();
                        QString oldColName = ctx->_additionalInfo[source->name()].toString();
                        QVariant newT= symbols.getValue(result);
                        ITable newTable = newT.value<ITable>();
                        ColumnDefinition coldef = newTable->columndefinition(oldColName);
                        if ( coldef.isValid()){
                            coldef.name(varName);
                            newTable->columndefinition(coldef);
                        }
                    }
                }

                if(!ok) {
                    throw ErrorObject(QString(TR(ERR_OPERATION_FAILID1).arg("assignment")));
                }
                ctx->clear(true);
                ctx->_results.push_back(result);
                return ok;

            } else {
                sym = symbols.getSymbol(result,SymbolTable::gaREMOVEIFANON);
                tp = sym.isValid() ? sym._type : itUNKNOWN;
                if ( tp == itUNKNOWN) {
                    tp = Domain::ilwType(val);
                }
            }
            ctx->clear();
           // symbols.addSymbol(result, scope, tp, _expression->value());
            ctx->addOutput(symbols,_expression->value(),result, tp, Resource());

            return true;
        }
    }
    return false;
}

void AssignmentNode::addOutputs(OutParametersNode *p)
{
    _outParms.reset(p);
}

void AssignmentNode::setOutId(IDNode *idnode)
{
    _outParms.reset(new OutParametersNode());
    _outParms->addResult(idnode);

}

<|endoftext|>