<commit_before>/*
 * File:   SDFLoader.cpp
 * Author: Benedikt Vogler
 *
 * Created on 8. Juli 2014, 18:52
 */

#include <algorithm>
#include "SDFloader.hpp"
#include "Camera.hpp"
#include "Box.hpp"
#include "Sphere.hpp"
#include <iostream>
#include <fstream>
#include <string>
#include <sstream>
#include "Material.hpp"
#include "LightPoint.hpp"
#include "Composite.hpp"

using namespace std;

/**
 * Loads a scene file and reacts to the commands in it
 * @param scenefile the string to the file
 * @return
 */
Scene SDFLoader::load(std::string const& scenefile) {
    cout << "Loading file: " << scenefile << endl;
    Scene scene = Scene();

    std::map<std::string, Material> mMap;
    std::map<std::string, LightPoint> lMap;
    std::map<std::string, shared_ptr<RenderObject>> roMap;

    string line;
    ifstream file(scenefile);
    stringstream ss;
    //file.open(scenefile, ios::in);
    if (file.is_open()) {
        while (getline (file,line)){//get line
            ss = stringstream(line);//fill the line into stringstream
            string firstWord;
            ss >> firstWord;
            //is first string define?
            if (firstWord=="define"){
                cout << "defininig: ";

                ss >> firstWord;
                if (firstWord=="material"){
                    cout << "a material: "<<endl;
                    //extract name
                    string name;
                    ss>>name;

                    //extract color
                    float red, green, blue;
                    ss >> red;
                    ss >> green;
                    ss >> blue;
                    Color ca(red, green, blue);
                    ss >> red;
                    ss >> green;
                    ss >> blue;
                    Color cd(red, green, blue);
                    ss >> red;
                    ss >> green;
                    ss >> blue;
                    Color cs(red, green, blue);
                    float m;
                    ss >> m;
                    float opacity(0);
                    ss >> opacity;
                    float refr(0);
                    ss >> refr;
                    Material mat(ca, cd, cs,m,opacity,refr, name);
                    cout << "Material specs: "<<endl<<mat;
                    mMap[name]=mat;
                } else if (firstWord=="camera"){
                    string cameraname;
                    ss >> cameraname;
                    float fovX;
                    ss >> fovX;
                    scene.camera = Camera(cameraname,fovX);
                    cout << "camera: "<<cameraname<<"("<<fovX<<")"<<endl;

                    if (!ss.eof()){
                        glm::vec3 pos;
                        ss >> pos.x;
                        ss >> pos.y;
                        ss >> pos.z;
                        scene.camera.translate(pos);

                        //direction
                        if (!ss.eof()){
                            glm::vec3 dir;
                            ss >> dir.x;
                            ss >> dir.y;
                            ss >> dir.z;
                            auto regularDir = glm::vec3(0.0f,0.0f,-1.0f);
                            //angle between 0,0,-1 and dir
                            float angleXY =glm::dot(regularDir,dir)/(glm::length(regularDir)*glm::length(dir));
                            //rotate around y and x
                            scene.camera.rotate(angleXY,glm::vec3(1,1,0));

                            //up vector
                            if (!ss.eof()){
                                glm::vec3 up;
                                ss >> up.x;
                                ss >> up.y;
                                ss >> up.z;
                                auto regularUp = glm::vec3(0.0f,1.0f,0.0f);
                                //angle between 0,1,0 and up
                                float angleZ =glm::dot(regularUp,up)/(glm::length(regularUp)*glm::length(up));
                                //rotate around z
                                scene.camera.rotate(angleZ,glm::vec3(0,0,1));
                            }
                        }
                    }
                } else if (firstWord=="light"){
                    string type;
                    ss>>type;

                    if (type=="diffuse") {
                        string name;
                        ss >> name;

                        glm::vec3 pos;
                        ss >> pos.x;
                        ss >> pos.y;
                        ss >> pos.z;

                        float red, green, blue;
                        ss >> red;
                        ss >> green;
                        ss >> blue;
                        Color diff(red, green, blue);

                        LightPoint light = LightPoint(name, pos, diff);
                        cout << "light point: "<<name<<"("<<pos.x<<","<<pos.y<<","<<pos.z<<","<<diff<<")"<<endl;
                        lMap[name] = light;
                    }else if (type=="ambient") {
                        string lightname;
                        ss >> lightname;//name get's ignored

                        float red, green, blue;
                        ss >> red;
                        ss >> green;
                        ss >> blue;
                        Color amb(red, green, blue);

                        scene.amb = amb;
                        cout << "ambient light "<<amb<<endl;
                    } else {
                        cout << "type not supported yet."<<endl;
                    }
                } else if (firstWord=="shape"){
                    string classname;
                    ss >> classname;
                    transform(classname.begin(), classname.end(),classname.begin(), ::toupper);

                    string name;
                    ss >> name;

                    shared_ptr<RenderObject> rObject;
                    if (classname=="BOX"){
                        int edge1x, edge1y, edge1z;
                        ss>> edge1x;
                        ss>> edge1y;
                        ss>> edge1z;

                        int edge2x, edge2y, edge2z;
                        ss>> edge2x;
                        ss>> edge2y;
                        ss>> edge2z;

                        string materialName;
                        ss>>materialName;
                        Material material = mMap[materialName];
                        rObject = make_shared<Box>(
                            name,
                            glm::vec3(edge1x, edge1y, edge1z),
                            glm::vec3(edge2x, edge2y, edge2z),
                            material
                        );
                    } else if (classname=="SPHERE") {
                        int posX, posY, posZ;
                        ss>> posX;
                        ss>> posY;
                        ss>> posZ;
                        float radius;
                        ss>>radius;

                        string materialString;
                        ss>>materialString;

                        rObject = make_shared<Sphere>(
                            name,
                            glm::vec3(posX, posY, posZ),
                            radius,
                            mMap[materialString]
                        );
                        cout << "Sphere \""<< name << "\" aus Material "<<materialString<<" mit Radius: "<<radius<<"@("<<posX<<","<<posY<<","<<posZ<<")"<<endl;
                    } else if(classname=="COMPOSITE") {
                       rObject = make_shared<Composite>( Composite(name));
                        cout << "Composite \""<< name << "\" (" ;
                        string objectString;
                        while (!ss.eof()){
                            ss>>objectString;
                            auto linkedObject = roMap.find(objectString);
                            if (linkedObject == roMap.end()){
                                cout << "Error: "<<objectString <<" not found!";
                            } else {
                                ((Composite*)&*rObject)->add_child(&*linkedObject->second);
                                cout<<", "<<objectString;
                            }
                        }
                        cout<<")"<<endl;
                    } else cout << "ERROR: Shape \""<< classname << "\" not defined."<<endl;

                    if (rObject != nullptr)
                        roMap[name] = rObject;
                } else
                    cout << "object to define not implemented:"<<ss.str() <<endl;
            } else if (firstWord=="render"){
                ss >> scene.camname;
                ss >> scene.outputFile;
                ss >> scene.resX;
                ss >> scene.resY;
                ss >> scene.antialiase;
                string random;
                ss>>random;
                if (random.length()>0)
                    scene.random = (random=="random");

                //set default if not set
                if (scene.resX<=0) scene.resX=480;
                if (scene.resY<=0) scene.resY=320;
                cout << "Scene should be rendered from "<< scene.camname << " at resolution "<<scene.resX<<"x"<< scene.resY<<"with "<< scene.antialiase<<"x SSAA to "<<scene.outputFile<<endl;
            } else if (firstWord=="#" || firstWord.substr(0,1)=="#"){
                cout << line << endl;//just print comment lines

            } else if (firstWord == "transform"){
                string name, transform;
                float x, y, z;
                RenderObject* object;

                ss >> name;
                ss >> transform;

                cout << transform<<": " << name << ""<<endl;

                auto linkedObject = roMap.find(name);
                if (linkedObject == roMap.end()){//check if object can be found
                    cout << "Error: " << name << " not found!"<<endl;
                } else {
                    object = &*linkedObject->second;
                    if (transform == "scale") {
                        ss >> x;
                        ss >> y;
                        ss >> z;

                        glm::vec3 coords(x, y, z);
                        object->scale(coords);
                        cout << "Scaling:"<< x <<","<< y <<","<< z <<endl;
                    } else if (transform == "rotate") {

                        double angle;
                        ss >> angle;

                        ss >> x;
                        ss >> y;
                        ss >> z;

                        glm::vec3 coords(x, y, z);
                        object->rotate(angle,coords);
                        cout << "Rotating:"<< angle <<" axis:"<< x <<","<< y <<","<< z <<endl;

                    } else if (transform == "translate"){
                        ss >> x;
                        ss >> y;
                        ss >> z;

                        glm::vec3 coords(x, y, z);
                        object->translate(coords);
                        cout << "translating: "<< x <<","<< y <<","<< z <<endl;
                    } else {
                            cout << "Unknown transformation" << endl;
                    }
                }
            } else if (firstWord.length()<1){
            //empty lines
            } else cout << "???:"<<line <<endl;//print unknown lines
        }
        file.close();
    }else cout << "Unable to open file";

    //save collected data in scene
    scene.materials = mMap;
    scene.renderObjects = roMap;
    scene.lights = lMap;
    return scene;
}<commit_msg>using dynamic cast<commit_after>/*
 * File:   SDFLoader.cpp
 * Author: Benedikt Vogler
 *
 * Created on 8. Juli 2014, 18:52
 */

#include <algorithm>
#include "SDFloader.hpp"
#include "Camera.hpp"
#include "Box.hpp"
#include "Sphere.hpp"
#include <iostream>
#include <fstream>
#include <string>
#include <sstream>
#include "Material.hpp"
#include "LightPoint.hpp"
#include "Composite.hpp"

using namespace std;

/**
 * Loads a scene file and reacts to the commands in it
 * @param scenefile the string to the file
 * @return
 */
Scene SDFLoader::load(std::string const& scenefile) {
    cout << "Loading file: " << scenefile << endl;
    Scene scene = Scene();

    std::map<std::string, Material> mMap;
    std::map<std::string, LightPoint> lMap;
    std::map<std::string, shared_ptr<RenderObject>> roMap;

    string line;
    ifstream file(scenefile);
    stringstream ss;
    //file.open(scenefile, ios::in);
    if (file.is_open()) {
        while (getline (file,line)){//get line
            ss = stringstream(line);//fill the line into stringstream
            string firstWord;
            ss >> firstWord;
            //is first string define?
            if (firstWord=="define"){
                cout << "defininig: ";

                ss >> firstWord;
                if (firstWord=="material"){
                    cout << "a material: "<<endl;
                    //extract name
                    string name;
                    ss>>name;

                    //extract color
                    float red, green, blue;
                    ss >> red;
                    ss >> green;
                    ss >> blue;
                    Color ca(red, green, blue);
                    ss >> red;
                    ss >> green;
                    ss >> blue;
                    Color cd(red, green, blue);
                    ss >> red;
                    ss >> green;
                    ss >> blue;
                    Color cs(red, green, blue);
                    float m;
                    ss >> m;
                    float opacity(0);
                    ss >> opacity;
                    float refr(0);
                    ss >> refr;
                    Material mat(ca, cd, cs,m,opacity,refr, name);
                    cout << "Material specs: "<<endl<<mat;
                    mMap[name]=mat;
                } else if (firstWord=="camera"){
                    string cameraname;
                    ss >> cameraname;
                    float fovX;
                    ss >> fovX;
                    scene.camera = Camera(cameraname,fovX);
                    cout << "camera: "<<cameraname<<"("<<fovX<<")"<<endl;

                    if (!ss.eof()){
                        glm::vec3 pos;
                        ss >> pos.x;
                        ss >> pos.y;
                        ss >> pos.z;
                        scene.camera.translate(pos);

                        //direction
                        if (!ss.eof()){
                            glm::vec3 dir;
                            ss >> dir.x;
                            ss >> dir.y;
                            ss >> dir.z;
                            auto regularDir = glm::vec3(0.0f,0.0f,-1.0f);
                            //angle between 0,0,-1 and dir
                            float angleXY =glm::dot(regularDir,dir)/(glm::length(regularDir)*glm::length(dir));
                            //rotate around y and x
                            scene.camera.rotate(angleXY,glm::vec3(1,1,0));

                            //up vector
                            if (!ss.eof()){
                                glm::vec3 up;
                                ss >> up.x;
                                ss >> up.y;
                                ss >> up.z;
                                auto regularUp = glm::vec3(0.0f,1.0f,0.0f);
                                //angle between 0,1,0 and up
                                float angleZ =glm::dot(regularUp,up)/(glm::length(regularUp)*glm::length(up));
                                //rotate around z
                                scene.camera.rotate(angleZ,glm::vec3(0,0,1));
                            }
                        }
                    }
                } else if (firstWord=="light"){
                    string type;
                    ss>>type;

                    if (type=="diffuse") {
                        string name;
                        ss >> name;

                        glm::vec3 pos;
                        ss >> pos.x;
                        ss >> pos.y;
                        ss >> pos.z;

                        float red, green, blue;
                        ss >> red;
                        ss >> green;
                        ss >> blue;
                        Color diff(red, green, blue);

                        LightPoint light = LightPoint(name, pos, diff);
                        cout << "light point: "<<name<<"("<<pos.x<<","<<pos.y<<","<<pos.z<<","<<diff<<")"<<endl;
                        lMap[name] = light;
                    }else if (type=="ambient") {
                        string lightname;
                        ss >> lightname;//name get's ignored

                        float red, green, blue;
                        ss >> red;
                        ss >> green;
                        ss >> blue;
                        Color amb(red, green, blue);

                        scene.amb = amb;
                        cout << "ambient light "<<amb<<endl;
                    } else {
                        cout << "type not supported yet."<<endl;
                    }
                } else if (firstWord=="shape"){
                    string classname;
                    ss >> classname;
                    transform(classname.begin(), classname.end(),classname.begin(), ::toupper);

                    string name;
                    ss >> name;

                    shared_ptr<RenderObject> rObject;
                    if (classname=="BOX"){
                        int edge1x, edge1y, edge1z;
                        ss>> edge1x;
                        ss>> edge1y;
                        ss>> edge1z;

                        int edge2x, edge2y, edge2z;
                        ss>> edge2x;
                        ss>> edge2y;
                        ss>> edge2z;

                        string materialName;
                        ss>>materialName;
                        Material material = mMap[materialName];
                        rObject = make_shared<Box>(
                            name,
                            glm::vec3(edge1x, edge1y, edge1z),
                            glm::vec3(edge2x, edge2y, edge2z),
                            material
                        );
                    } else if (classname=="SPHERE") {
                        int posX, posY, posZ;
                        ss>> posX;
                        ss>> posY;
                        ss>> posZ;
                        float radius;
                        ss>>radius;

                        string materialString;
                        ss>>materialString;

                        rObject = make_shared<Sphere>(
                            name,
                            glm::vec3(posX, posY, posZ),
                            radius,
                            mMap[materialString]
                        );
                        cout << "Sphere \""<< name << "\" aus Material "<<materialString<<" mit Radius: "<<radius<<"@("<<posX<<","<<posY<<","<<posZ<<")"<<endl;
                    } else if(classname=="COMPOSITE") {
                       rObject = make_shared<Composite>( Composite(name));
                        cout << "Composite \""<< name << "\" (" ;
                        string objectString;
                        while (!ss.eof()){
                            ss>>objectString;
                            auto linkedObject = roMap.find(objectString);
                            if (linkedObject == roMap.end()){
                                cout << "Error: "<<objectString <<" not found!";
                            } else {
                                std::dynamic_pointer_cast<Composite>(rObject)->add_child(&*linkedObject->second);
                                cout<<", "<<objectString;
                            }
                        }
                        cout<<")"<<endl;
                    } else cout << "ERROR: Shape \""<< classname << "\" not defined."<<endl;

                    if (rObject != nullptr)
                        roMap[name] = rObject;
                } else
                    cout << "object to define not implemented:"<<ss.str() <<endl;
            } else if (firstWord=="render"){
                ss >> scene.camname;
                ss >> scene.outputFile;
                ss >> scene.resX;
                ss >> scene.resY;
                ss >> scene.antialiase;
                string random;
                ss>>random;
                if (random.length()>0)
                    scene.random = (random=="random");

                //set default if not set
                if (scene.resX<=0) scene.resX=480;
                if (scene.resY<=0) scene.resY=320;
                cout << "Scene should be rendered from "<< scene.camname << " at resolution "<<scene.resX<<"x"<< scene.resY<<"with "<< scene.antialiase<<"x SSAA to "<<scene.outputFile<<endl;
            } else if (firstWord=="#" || firstWord.substr(0,1)=="#"){
                cout << line << endl;//just print comment lines

            } else if (firstWord == "transform"){
                string name, transform;
                float x, y, z;
                RenderObject* object;

                ss >> name;
                ss >> transform;

                cout << transform<<": " << name << ""<<endl;

                auto linkedObject = roMap.find(name);
                if (linkedObject == roMap.end()){//check if object can be found
                    cout << "Error: " << name << " not found!"<<endl;
                } else {
                    object = &*linkedObject->second;
                    if (transform == "scale") {
                        ss >> x;
                        ss >> y;
                        ss >> z;

                        glm::vec3 coords(x, y, z);
                        object->scale(coords);
                        cout << "Scaling:"<< x <<","<< y <<","<< z <<endl;
                    } else if (transform == "rotate") {

                        double angle;
                        ss >> angle;

                        ss >> x;
                        ss >> y;
                        ss >> z;

                        glm::vec3 coords(x, y, z);
                        object->rotate(angle,coords);
                        cout << "Rotating:"<< angle <<" axis:"<< x <<","<< y <<","<< z <<endl;

                    } else if (transform == "translate"){
                        ss >> x;
                        ss >> y;
                        ss >> z;

                        glm::vec3 coords(x, y, z);
                        object->translate(coords);
                        cout << "translating: "<< x <<","<< y <<","<< z <<endl;
                    } else {
                            cout << "Unknown transformation" << endl;
                    }
                }
            } else if (firstWord.length()<1){
            //empty lines
            } else cout << "???:"<<line <<endl;//print unknown lines
        }
        file.close();
    }else cout << "Unable to open file";

    //save collected data in scene
    scene.materials = mMap;
    scene.renderObjects = roMap;
    scene.lights = lMap;
    return scene;
}<|endoftext|>


<commit_before>#include "ConfigDatabaseManager.h"
#include "System/FileSystem.h"
#include "Framework/Storage/FDGuard.h"
#include "Framework/Replication/Quorums/QuorumDatabase.h"
#include "Framework/Storage/StoragePageCache.h"
#include "Framework/Storage/StorageConfig.h"
#include "Framework/Storage/StorageDataPage.h"
#include "Application/Common/ContextTransport.h"
#include "System/Config.h"

void ConfigDatabaseManager::Init(bool restoreMode)
{
    Buffer          envpath;
    StorageConfig   sc;

    sc.SetChunkSize(            (uint64_t) configFile.GetInt64Value("database.chunkSize",				64*MiB  ));
    sc.SetLogSegmentSize(       (uint64_t) configFile.GetInt64Value("database.logSegmentSize",			64*MiB  ));
    sc.SetFileChunkCacheSize(   (uint64_t) configFile.GetInt64Value("database.fileChunkCacheSize",		256*MiB ));
    sc.SetMemoChunkCacheSize(   (uint64_t) configFile.GetInt64Value("database.memoChunkCacheSize",		1*GiB   ));
    sc.SetLogSize(              (uint64_t) configFile.GetInt64Value("database.logSize",					64*MiB  ));
    sc.SetMergeBufferSize(      (uint64_t) configFile.GetInt64Value("database.mergeBufferSize",			10*MiB  ));
    sc.SetMergeYieldFactor(     (uint64_t) configFile.GetInt64Value("database.mergeYieldFactor",        100     ));
    sc.SetSyncGranularity(      (uint64_t) configFile.GetInt64Value("database.syncGranularity",			16*MiB  ));
    sc.SetWriteGranularity(     (uint64_t) configFile.GetInt64Value("database.writeGranularity",		STORAGE_WRITE_GRANULARITY));
    sc.SetReplicatedLogSize(    (uint64_t) configFile.GetInt64Value("database.replicatedLogSize",		0       ));
    sc.SetAbortWaitingListsNum( (uint64_t) configFile.GetInt64Value("database.abortWaitingListsNum",	0       ));
    sc.SetListDataPageCacheSize((uint64_t) configFile.GetInt64Value("database.listDataPageCacheSize",   1*MB    ));
    sc.SetMaxChunkPerShard(     (unsigned) configFile.GetIntValue  ("database.maxChunkPerShard",        10      ));

    envpath.Writef("%s", configFile.GetValue("database.dir", "db"));
    environment.Open(envpath, sc);

    if (configFile.GetBoolValue("database.merge", true))
        environment.SetMergeEnabled(true);
    environment.SetMergeCpuThreshold(configFile.GetIntValue("database.mergeCpuThreshold", STORAGE_DEFAULT_MERGE_CPU_THRESHOLD));

    environment.CreateShard(1, QUORUM_DATABASE_SYSTEM_CONTEXT, 1, 0, "", "", true, STORAGE_SHARD_TYPE_STANDARD);
    environment.CreateShard(1, QUORUM_DATABASE_QUORUM_PAXOS_CONTEXT, 1, 0, "", "", true, STORAGE_SHARD_TYPE_DUMP);
    environment.CreateShard(1, QUORUM_DATABASE_QUORUM_LOG_CONTEXT, 1, 0, "", "", true, STORAGE_SHARD_TYPE_LOG);

    systemConfigShard.Init(&environment, QUORUM_DATABASE_SYSTEM_CONTEXT, 1);
    quorumPaxosShard.Init(&environment, QUORUM_DATABASE_QUORUM_PAXOS_CONTEXT, 1);
    quorumLogShard.Init(&environment, QUORUM_DATABASE_QUORUM_LOG_CONTEXT, 1);

    paxosID = 0;
    configState.Init();
    Read();

    if (restoreMode)
    {
        Log_Message("Attempting to read config state from file 'configState' in the db folder...");
        if (ReadConfigStateFromFile())
            Log_Message("Success.");
        else
            STOP_FAIL(1, "Failed to read config state from file 'configState' in the db folder...");
        Write();
    }

    SetControllers();
}

void ConfigDatabaseManager::Shutdown()
{
    environment.Close();
    StoragePageCache::Shutdown();
}

ConfigState* ConfigDatabaseManager::GetConfigState()
{
    return &configState;
}

StorageEnvironment* ConfigDatabaseManager::GetEnvironment()
{
    return &environment;
}

void ConfigDatabaseManager::SetPaxosID(uint64_t paxosID_)
{
    paxosID = paxosID_;
}

uint64_t ConfigDatabaseManager::GetPaxosID()
{
    return paxosID;
}

StorageShardProxy* ConfigDatabaseManager::GetSystemShard()
{
    return &systemConfigShard;
}

StorageShardProxy* ConfigDatabaseManager::GetQuorumPaxosShard()
{
    return &quorumPaxosShard;
}

StorageShardProxy* ConfigDatabaseManager::GetQuorumLogShard()
{
    return &quorumLogShard;
}

bool ConfigDatabaseManager::ShardExists(uint64_t tableID, ReadBuffer firstKey)
{
    ConfigShard* shard;

    FOREACH (shard, configState.shards)
    {
        if (shard->tableID == tableID && ReadBuffer::Cmp(firstKey, shard->firstKey) == 0)
            return true;
    }

    return false;
}

void ConfigDatabaseManager::Read()
{
    bool                ret;
    ReadBuffer          value;
    int                 read;

    ret =  true;

    if (!systemConfigShard.Get(ReadBuffer("state"), value))
    {
        Log_Message("Starting with empty database...");
        return;
    }

    read = value.Readf("%U:", &paxosID);
    if (read < 2)
        ASSERT_FAIL();

    value.Advance(read);

    if (!configState.Read(value))
        ASSERT_FAIL();

    Log_Trace("%R", &value);
}

void ConfigDatabaseManager::Write()
{
    writeBuffer.Writef("%U:", paxosID);
    configState.Write(writeBuffer);
    systemConfigShard.Set(ReadBuffer("state"), ReadBuffer(writeBuffer));
}

void ConfigDatabaseManager::SetControllers()
{
    unsigned            num;
    uint64_t            nodeID;
    ReadBuffer          rb;
    ConfigController*   controller;

    configState.controllers.DeleteList();

    num = configFile.GetListNum("controllers");
    for (nodeID = 0; nodeID < num; nodeID++)
    {
        controller = new ConfigController;
        controller->nodeID = nodeID;
        rb = configFile.GetListValue("controllers", nodeID, "");
        controller->endpoint.Set(rb, true);
        controller->isConnected = CONTEXT_TRANSPORT->IsConnected(controller->nodeID);
        configState.controllers.Append(controller);
    }
}

bool ConfigDatabaseManager::ReadConfigStateFromFile()
{
    FDGuard     fd;
    Buffer      configStateFile;
    Buffer      configStateBuffer;
    ReadBuffer  rb;
    int64_t     size;

    configStateFile.Write(environment.envPath);
    configStateFile.Append("configState");
    configStateFile.NullTerminate();

    if (fd.Open(configStateFile.GetBuffer(), FS_READONLY) == INVALID_FD)
    {
        Log_Message("Unable to open file 'configState'");
        return false;
    }
    size = FS_FileSize(fd.GetFD());
    if (size <= 0)
    {
        Log_Message("File 'configState' is corrupt or of zero length");
        return false;
    }
    configStateBuffer.Allocate(size);
    if (FS_FileRead(fd.GetFD(), configStateBuffer.GetBuffer(), size) != (ssize_t) size)
    {
        Log_Message("Unable to read from file 'configState'");
        return false;
    }
    configStateBuffer.SetLength(size);
    rb.Wrap(configStateBuffer);

    if (!configState.Read(rb, false))
    {
        Log_Message("Error parsing the contents of the config state");
        return false;
    }
    return true;
}
<commit_msg>Cleaned up unused variable.<commit_after>#include "ConfigDatabaseManager.h"
#include "System/FileSystem.h"
#include "Framework/Storage/FDGuard.h"
#include "Framework/Replication/Quorums/QuorumDatabase.h"
#include "Framework/Storage/StoragePageCache.h"
#include "Framework/Storage/StorageConfig.h"
#include "Framework/Storage/StorageDataPage.h"
#include "Application/Common/ContextTransport.h"
#include "System/Config.h"

void ConfigDatabaseManager::Init(bool restoreMode)
{
    Buffer          envpath;
    StorageConfig   sc;

    sc.SetChunkSize(            (uint64_t) configFile.GetInt64Value("database.chunkSize",				64*MiB  ));
    sc.SetLogSegmentSize(       (uint64_t) configFile.GetInt64Value("database.logSegmentSize",			64*MiB  ));
    sc.SetFileChunkCacheSize(   (uint64_t) configFile.GetInt64Value("database.fileChunkCacheSize",		256*MiB ));
    sc.SetMemoChunkCacheSize(   (uint64_t) configFile.GetInt64Value("database.memoChunkCacheSize",		1*GiB   ));
    sc.SetLogSize(              (uint64_t) configFile.GetInt64Value("database.logSize",					64*MiB  ));
    sc.SetMergeBufferSize(      (uint64_t) configFile.GetInt64Value("database.mergeBufferSize",			10*MiB  ));
    sc.SetMergeYieldFactor(     (uint64_t) configFile.GetInt64Value("database.mergeYieldFactor",        100     ));
    sc.SetSyncGranularity(      (uint64_t) configFile.GetInt64Value("database.syncGranularity",			16*MiB  ));
    sc.SetWriteGranularity(     (uint64_t) configFile.GetInt64Value("database.writeGranularity",		STORAGE_WRITE_GRANULARITY));
    sc.SetReplicatedLogSize(    (uint64_t) configFile.GetInt64Value("database.replicatedLogSize",		0       ));
    sc.SetAbortWaitingListsNum( (uint64_t) configFile.GetInt64Value("database.abortWaitingListsNum",	0       ));
    sc.SetListDataPageCacheSize((uint64_t) configFile.GetInt64Value("database.listDataPageCacheSize",   1*MB    ));
    sc.SetMaxChunkPerShard(     (unsigned) configFile.GetIntValue  ("database.maxChunkPerShard",        10      ));

    envpath.Writef("%s", configFile.GetValue("database.dir", "db"));
    environment.Open(envpath, sc);

    if (configFile.GetBoolValue("database.merge", true))
        environment.SetMergeEnabled(true);
    environment.SetMergeCpuThreshold(configFile.GetIntValue("database.mergeCpuThreshold", STORAGE_DEFAULT_MERGE_CPU_THRESHOLD));

    environment.CreateShard(1, QUORUM_DATABASE_SYSTEM_CONTEXT, 1, 0, "", "", true, STORAGE_SHARD_TYPE_STANDARD);
    environment.CreateShard(1, QUORUM_DATABASE_QUORUM_PAXOS_CONTEXT, 1, 0, "", "", true, STORAGE_SHARD_TYPE_DUMP);
    environment.CreateShard(1, QUORUM_DATABASE_QUORUM_LOG_CONTEXT, 1, 0, "", "", true, STORAGE_SHARD_TYPE_LOG);

    systemConfigShard.Init(&environment, QUORUM_DATABASE_SYSTEM_CONTEXT, 1);
    quorumPaxosShard.Init(&environment, QUORUM_DATABASE_QUORUM_PAXOS_CONTEXT, 1);
    quorumLogShard.Init(&environment, QUORUM_DATABASE_QUORUM_LOG_CONTEXT, 1);

    paxosID = 0;
    configState.Init();
    Read();

    if (restoreMode)
    {
        Log_Message("Attempting to read config state from file 'configState' in the db folder...");
        if (ReadConfigStateFromFile())
            Log_Message("Success.");
        else
            STOP_FAIL(1, "Failed to read config state from file 'configState' in the db folder...");
        Write();
    }

    SetControllers();
}

void ConfigDatabaseManager::Shutdown()
{
    environment.Close();
    StoragePageCache::Shutdown();
}

ConfigState* ConfigDatabaseManager::GetConfigState()
{
    return &configState;
}

StorageEnvironment* ConfigDatabaseManager::GetEnvironment()
{
    return &environment;
}

void ConfigDatabaseManager::SetPaxosID(uint64_t paxosID_)
{
    paxosID = paxosID_;
}

uint64_t ConfigDatabaseManager::GetPaxosID()
{
    return paxosID;
}

StorageShardProxy* ConfigDatabaseManager::GetSystemShard()
{
    return &systemConfigShard;
}

StorageShardProxy* ConfigDatabaseManager::GetQuorumPaxosShard()
{
    return &quorumPaxosShard;
}

StorageShardProxy* ConfigDatabaseManager::GetQuorumLogShard()
{
    return &quorumLogShard;
}

bool ConfigDatabaseManager::ShardExists(uint64_t tableID, ReadBuffer firstKey)
{
    ConfigShard* shard;

    FOREACH (shard, configState.shards)
    {
        if (shard->tableID == tableID && ReadBuffer::Cmp(firstKey, shard->firstKey) == 0)
            return true;
    }

    return false;
}

void ConfigDatabaseManager::Read()
{
    ReadBuffer          value;
    int                 read;

    if (!systemConfigShard.Get(ReadBuffer("state"), value))
    {
        Log_Message("Starting with empty database...");
        return;
    }

    read = value.Readf("%U:", &paxosID);
    if (read < 2)
        ASSERT_FAIL();

    value.Advance(read);

    if (!configState.Read(value))
        ASSERT_FAIL();

    Log_Trace("%R", &value);
}

void ConfigDatabaseManager::Write()
{
    writeBuffer.Writef("%U:", paxosID);
    configState.Write(writeBuffer);
    systemConfigShard.Set(ReadBuffer("state"), ReadBuffer(writeBuffer));
}

void ConfigDatabaseManager::SetControllers()
{
    unsigned            num;
    uint64_t            nodeID;
    ReadBuffer          rb;
    ConfigController*   controller;

    configState.controllers.DeleteList();

    num = configFile.GetListNum("controllers");
    for (nodeID = 0; nodeID < num; nodeID++)
    {
        controller = new ConfigController;
        controller->nodeID = nodeID;
        rb = configFile.GetListValue("controllers", nodeID, "");
        controller->endpoint.Set(rb, true);
        controller->isConnected = CONTEXT_TRANSPORT->IsConnected(controller->nodeID);
        configState.controllers.Append(controller);
    }
}

bool ConfigDatabaseManager::ReadConfigStateFromFile()
{
    FDGuard     fd;
    Buffer      configStateFile;
    Buffer      configStateBuffer;
    ReadBuffer  rb;
    int64_t     size;

    configStateFile.Write(environment.envPath);
    configStateFile.Append("configState");
    configStateFile.NullTerminate();

    if (fd.Open(configStateFile.GetBuffer(), FS_READONLY) == INVALID_FD)
    {
        Log_Message("Unable to open file 'configState'");
        return false;
    }
    size = FS_FileSize(fd.GetFD());
    if (size <= 0)
    {
        Log_Message("File 'configState' is corrupt or of zero length");
        return false;
    }
    configStateBuffer.Allocate(size);
    if (FS_FileRead(fd.GetFD(), configStateBuffer.GetBuffer(), size) != (ssize_t) size)
    {
        Log_Message("Unable to read from file 'configState'");
        return false;
    }
    configStateBuffer.SetLength(size);
    rb.Wrap(configStateBuffer);

    if (!configState.Read(rb, false))
    {
        Log_Message("Error parsing the contents of the config state");
        return false;
    }
    return true;
}
<|endoftext|>


<commit_before>/* CatenaBase_addLoRaWanCommands.cpp	Mon Dec 03 2018 13:33:11 chwon */

/*

Module:  CatenaBase_addLoRaWanCommands.cpp

Function:
	The command engine for lorawan commands on the Catena base platform

Version:
	V0.12.0	Mon Dec 03 2018 13:33:11 chwon	Edit level 1

Copyright notice:
	This file copyright (C) 2018 by

		MCCI Corporation
		3520 Krums Corners Road
		Ithaca, NY  14850

	An unpublished work.  All rights reserved.

	This file is proprietary information, and may not be disclosed or
	copied without the prior permission of MCCI Corporation

Author:
	ChaeHee Won, MCCI Corporation	December 2018

Revision history:
   0.12.0  Mon Dec 03 2018 13:33:11  chwon
	Module created.

*/

#include "CatenaBase.h"

#include <Arduino_LoRaWAN_lmic.h>

#include "Catena_Log.h"

#include <cstring>

using namespace McciCatena;

/****************************************************************************\
|
|	The command table
|
\****************************************************************************/

static cCommandStream::CommandFn doConfigure;
static cCommandStream::CommandFn doJoin;

static const cCommandStream::cEntry sDispatchEntries[] =
	{
	{ "configure", doConfigure },
	{ "join", doJoin },
	};

static cCommandStream::cDispatch
sDispatch(sDispatchEntries, sizeof(sDispatchEntries), "lorawan");

struct KeyMap
	{
	const char *pName;
	cFramStorage::StandardKeys uKey;
	};

static KeyMap sKeyMap[] =
	{
	{ "deveui", cFramStorage::StandardKeys::kDevEUI },
	{ "appeui", cFramStorage::StandardKeys::kAppEUI },
	{ "appkey", cFramStorage::StandardKeys::kAppKey, },
	{ "nwkskey", cFramStorage::StandardKeys::kNwkSKey, },
	{ "appskey", cFramStorage::StandardKeys::kAppSKey, },
	{ "devaddr", cFramStorage::StandardKeys::kDevAddr, },
	{ "netid", cFramStorage::StandardKeys::kNetID, },
	{ "fcntup", cFramStorage::StandardKeys::kFCntUp, },
	{ "fcntdown", cFramStorage::StandardKeys::kFCntDown, },
	{ "join", cFramStorage::StandardKeys::kJoin, },
	};

/*

Name:	CatenaBase::addLoRaWanCommands()

Function:
	Add the lorawan commands to the Catena command table.

Definition:
	private: bool CatenaBase::addLoRaWanCommands(void);

Description:
	All the commands are added to the system command table.

Returns:
	true for success.

*/

bool
CatenaBase::addLoRaWanCommands(
	void
	)
	{
	if (this->getFram() == nullptr)
		{
		gLog.printf(
			gLog.kError,
			"?CatenaBase::addLoRaWanCommands(): no FRAM\n"
			);
		return false;
		}

	gLog.printf(
		gLog.kTrace,
		"CatenaBase::addLoRaWanCommands(): adding\n"
		);
	this->addCommands(
		sDispatch,
		static_cast<void *>(this)
		);
	return true;
	}

/*

Name:	doConfigure()

Function:
	Implement the LoRaWAN value set/get commands

Definition:
	static cCommandStream::CommandFn doConfigure;

	static cCommandStream::CommandStatus
		doConfigure(
			cCommandStream *pThis,
			void *pContext,
			int argc,
			char **argv
			);

Description:
	This function dispatches the various commands, parsing the input
	parameters if any to set the corresponding value, or displaying
	the values.

	The parsed syntax:

	lorawan configure [ {param} [ {value} ] ]

Returns:
	Command status

*/

static cCommandStream::CommandStatus
doConfigure(
	cCommandStream *pThis,
	void *pContext,
	int argc,
	char **argv
	)
	{
	CatenaBase * const pCatena = static_cast<CatenaBase *>(pContext);
	uint8_t databuf[16];

	if (argc < 2)
		{
		// TODO(tmm@mcci.com) display values
		return cCommandStream::CommandStatus::kInvalidParameter;
		}

	const char * const pName = argv[1];
	cFram::Cursor cursor(pCatena->getFram());

	for (auto const & p : sKeyMap)
		{
		if (strcasecmp(p.pName, pName) == 0)
			{
			// matched!
			cursor.locate(p.uKey);
			}
		}

	if (! cursor.isbound())
		{
		pThis->printf(
			"%s: unknown\n",
			__func__,
			pName
			);
		return cCommandStream::CommandStatus::kInvalidParameter;
		}

	size_t size;

	size = cursor.getitemsize();
	if (size > sizeof(databuf))
		size = sizeof(databuf);

	// display
	if (argc <= 2)
		{
		if (! cursor.islocated())
			{
			pThis->printf("%s: not initialized\n", pName);
			return cCommandStream::CommandStatus::kNotInitialized;
			}
		else
			{
			char strbuf[64];

			if (! cursor.get(databuf, size))
				{
				pThis->printf("%s: read error\n", pName);
				return cCommandStream::CommandStatus::kReadError;
				}

			cursor.formatvalue(
				strbuf, sizeof(strbuf), 0,
				databuf, size
				);

			pThis->printf("%s\n", strbuf);
			return cCommandStream::CommandStatus::kSuccess;
			}
		}
	else
		{
		const char * const pValue = argv[2];

		// parse the argument according to the cursor (which
		// specifies what will receive it
		if (! cursor.parsevalue(
				pValue,
				databuf,
				size
				))
			{
			pThis->printf("%s: invalid parameter: %s\n",
				pName, pValue
				);
			return cCommandStream::CommandStatus::kInvalidParameter;
			}
		else if (! cursor.create())
			{
			pThis->printf("%s: could not create entry\n",
				pName
				);
			return cCommandStream::CommandStatus::kCreateError;
			}
		else
			{
			return cursor.put(databuf, size)
				? cCommandStream::CommandStatus::kSuccess
				: cCommandStream::CommandStatus::kWriteError
				;
			}
		}
	}

/*

Name:	doJoin()

Function:
	Implement the LoRaWAN join command

Definition:
	static cCommandStream::CommandFn doJoin;

	static cCommandStream::CommandStatus
		doJoin(
			cCommandStream *pThis,
			void *pContext,
			int argc,
			char **argv
			);

Description:
	This function checks arguments, then forces an unjoin, followed by
	a join. If the device is not configured for OTAA mode, it
	does nothing. FRAM is not reset unless the join succeeds.
	A `lorawan configure reset` may be more along the lines
	of what you want, if you want to ship a device.

	The parsed syntax:

	lorawan join

Returns:
	Command status

*/

static cCommandStream::CommandStatus
doJoin(
	cCommandStream *pThis,
	void *pContext,
	int argc,
	char **argv
	)
	{

	if (argc > 1)
		return cCommandStream::CommandStatus::kInvalidParameter;

	LMIC_unjoin();
	LMIC_startJoining();
	return cCommandStream::CommandStatus::kSuccess;
	}

/**** end of CatenaBase_addLoRaWanCommands.cpp ****/
<commit_msg>Adjust whitespace<commit_after>/* CatenaBase_addLoRaWanCommands.cpp	Mon Dec 03 2018 13:33:11 chwon */

/*

Module:  CatenaBase_addLoRaWanCommands.cpp

Function:
	The command engine for lorawan commands on the Catena base platform

Version:
	V0.12.0	Mon Dec 03 2018 13:33:11 chwon	Edit level 1

Copyright notice:
	This file copyright (C) 2018 by

		MCCI Corporation
		3520 Krums Corners Road
		Ithaca, NY  14850

	An unpublished work.  All rights reserved.

	This file is proprietary information, and may not be disclosed or
	copied without the prior permission of MCCI Corporation

Author:
	ChaeHee Won, MCCI Corporation	December 2018

Revision history:
   0.12.0  Mon Dec 03 2018 13:33:11  chwon
	Module created.

*/

#include "CatenaBase.h"

#include <Arduino_LoRaWAN_lmic.h>

#include "Catena_Log.h"

#include <cstring>

using namespace McciCatena;

/****************************************************************************\
|
|	The command table
|
\****************************************************************************/

static cCommandStream::CommandFn doConfigure;
static cCommandStream::CommandFn doJoin;

static const cCommandStream::cEntry sDispatchEntries[] =
	{
	{ "configure", doConfigure },
	{ "join", doJoin },
	};

static cCommandStream::cDispatch
sDispatch(sDispatchEntries, sizeof(sDispatchEntries), "lorawan");

struct KeyMap
	{
	const char *pName;
	cFramStorage::StandardKeys uKey;
	};

static KeyMap sKeyMap[] =
	{
	{ "deveui", cFramStorage::StandardKeys::kDevEUI },
	{ "appeui", cFramStorage::StandardKeys::kAppEUI },
	{ "appkey", cFramStorage::StandardKeys::kAppKey, },
	{ "nwkskey", cFramStorage::StandardKeys::kNwkSKey, },
	{ "appskey", cFramStorage::StandardKeys::kAppSKey, },
	{ "devaddr", cFramStorage::StandardKeys::kDevAddr, },
	{ "netid", cFramStorage::StandardKeys::kNetID, },
	{ "fcntup", cFramStorage::StandardKeys::kFCntUp, },
	{ "fcntdown", cFramStorage::StandardKeys::kFCntDown, },
	{ "join", cFramStorage::StandardKeys::kJoin, },
	};

/*

Name:	CatenaBase::addLoRaWanCommands()

Function:
	Add the lorawan commands to the Catena command table.

Definition:
	private: bool CatenaBase::addLoRaWanCommands(void);

Description:
	All the commands are added to the system command table.

Returns:
	true for success.

*/

bool
CatenaBase::addLoRaWanCommands(
	void
	)
	{
	if (this->getFram() == nullptr)
		{
		gLog.printf(
			gLog.kError,
			"?CatenaBase::addLoRaWanCommands(): no FRAM\n"
			);
		return false;
		}

	gLog.printf(
		gLog.kTrace,
		"CatenaBase::addLoRaWanCommands(): adding\n"
		);
	this->addCommands(
		sDispatch,
		static_cast<void *>(this)
		);
	return true;
	}

/*

Name:	doConfigure()

Function:
	Implement the LoRaWAN value set/get commands

Definition:
	static cCommandStream::CommandFn doConfigure;

	static cCommandStream::CommandStatus
		doConfigure(
			cCommandStream *pThis,
			void *pContext,
			int argc,
			char **argv
			);

Description:
	This function dispatches the various commands, parsing the input
	parameters if any to set the corresponding value, or displaying
	the values.

	The parsed syntax:

	lorawan configure [ {param} [ {value} ] ]

Returns:
	Command status

*/

static cCommandStream::CommandStatus
doConfigure(
	cCommandStream *pThis,
	void *pContext,
	int argc,
	char **argv
	)
	{
	CatenaBase * const pCatena = static_cast<CatenaBase *>(pContext);
	uint8_t databuf[16];

	if (argc < 2)
		{
		// TODO(tmm@mcci.com) display values
		return cCommandStream::CommandStatus::kInvalidParameter;
		}

	const char * const pName = argv[1];
	cFram::Cursor cursor(pCatena->getFram());

	for (auto const & p : sKeyMap)
		{
		if (strcasecmp(p.pName, pName) == 0)
			{
			// matched!
			cursor.locate(p.uKey);
			}
		}

	if (! cursor.isbound())
		{
		pThis->printf(
			"%s: unknown\n",
			__func__,
			pName
			);
		return cCommandStream::CommandStatus::kInvalidParameter;
		}

	size_t size;

	size = cursor.getitemsize();
	if (size > sizeof(databuf))
		size = sizeof(databuf);

	// display
	if (argc <= 2)
		{
		if (! cursor.islocated())
			{
			pThis->printf("%s: not initialized\n", pName);
			return cCommandStream::CommandStatus::kNotInitialized;
			}
		else
			{
			char strbuf[64];

			if (! cursor.get(databuf, size))
				{
				pThis->printf("%s: read error\n", pName);
				return cCommandStream::CommandStatus::kReadError;
				}

			cursor.formatvalue(
				strbuf, sizeof(strbuf), 0,
				databuf, size
				);

			pThis->printf("%s\n", strbuf);
			return cCommandStream::CommandStatus::kSuccess;
			}
		}
	else
		{
		const char * const pValue = argv[2];

		// parse the argument according to the cursor (which
		// specifies what will receive it
		if (! cursor.parsevalue(
				pValue,
				databuf,
				size
				))
			{
			pThis->printf("%s: invalid parameter: %s\n",
				pName, pValue
				);
			return cCommandStream::CommandStatus::kInvalidParameter;
			}
		else if (! cursor.create())
			{
			pThis->printf("%s: could not create entry\n",
				pName
				);
			return cCommandStream::CommandStatus::kCreateError;
			}
		else
			{
			return cursor.put(databuf, size)
				? cCommandStream::CommandStatus::kSuccess
				: cCommandStream::CommandStatus::kWriteError
				;
			}
		}
	}

/*

Name:	doJoin()

Function:
	Implement the LoRaWAN join command

Definition:
	static cCommandStream::CommandFn doJoin;

	static cCommandStream::CommandStatus
		doJoin(
			cCommandStream *pThis,
			void *pContext,
			int argc,
			char **argv
			);

Description:
	This function checks arguments, then forces an unjoin, followed by
	a join. If the device is not configured for OTAA mode, it
	does nothing. FRAM is not reset unless the join succeeds.
	A `lorawan configure reset` may be more along the lines
	of what you want, if you want to ship a device.

	The parsed syntax:

	lorawan join

Returns:
	Command status

*/

static cCommandStream::CommandStatus
doJoin(
	cCommandStream *pThis,
	void *pContext,
	int argc,
	char **argv
	)
	{

	if (argc > 1)
		return cCommandStream::CommandStatus::kInvalidParameter;

	LMIC_unjoin();
	LMIC_startJoining();
	return cCommandStream::CommandStatus::kSuccess;
	}

/**** end of CatenaBase_addLoRaWanCommands.cpp ****/
<|endoftext|>


<commit_before>//
// This file is part of the Marble Desktop Globe.
//
// This program is free software licensed under the GNU LGPL. You can
// find a copy of this license in LICENSE.txt in the top directory of
// the source code.
//
// Copyright 2004-2007 Torsten Rahn <tackat@kde.org>
// Copyright 2007      Inge Wallin  <ingwa@kde.org>
// Copyright 2008-2009      Patrick Spendrin <ps_ml@gmx.de>
//

// Own
#include "GeoDataPlacemark.h"

// Qt
#include <QtCore/QDataStream>
#include <QtCore/QDebug>

// Private
#include "GeoDataPlacemark_p.h"

namespace Marble
{

GeoDataPlacemark::GeoDataPlacemark( GeoDataObject* parent )
    : GeoDataFeature( new GeoDataPlacemarkPrivate )
{
}

GeoDataPlacemark::GeoDataPlacemark( const GeoDataPlacemark& other )
: GeoDataFeature( other )
{
}

GeoDataPlacemark::GeoDataPlacemark( const QString& name, GeoDataObject *parent )
    : GeoDataFeature( name, parent )
{
}

GeoDataPlacemark::~GeoDataPlacemark()
{
}

GeoDataPlacemarkPrivate* GeoDataPlacemark::p() const
{
    return static_cast<GeoDataPlacemarkPrivate*>(d);
}

GeoDataGeometry* GeoDataPlacemark::geometry() const
{
    if( p()->m_geometry )
        return p()->m_geometry;
    else
        return &( p()->m_coordinate );
}

GeoDataCoordinates GeoDataPlacemark::coordinate() const
{
    return static_cast<GeoDataCoordinates>( p()->m_coordinate );
}

void GeoDataPlacemark::coordinate( qreal& lon, qreal& lat, qreal& alt ) const
{
    p()->m_coordinate.geoCoordinates( lon, lat );
    alt = p()->m_coordinate.altitude();
}

void GeoDataPlacemark::setCoordinate( qreal lon, qreal lat, qreal alt )
{
    detach();
    p()->m_coordinate = GeoDataPoint( lon, lat, alt, this );
}

void GeoDataPlacemark::setCoordinate( const GeoDataPoint &point )
{
    detach();
    p()->m_coordinate = GeoDataPoint( point );
    p()->m_coordinate.setParent( this );
}

void GeoDataPlacemark::setGeometry( const GeoDataPoint& point )
{
    detach();
    delete p()->m_geometry;
    p()->m_geometry = new GeoDataPoint( point );
}

void GeoDataPlacemark::setGeometry( const GeoDataLineString& point )
{
    detach();
    delete p()->m_geometry;
    p()->m_geometry = new GeoDataLineString( point );
}

void GeoDataPlacemark::setGeometry( const GeoDataLinearRing& point )
{
    detach();
    delete p()->m_geometry;
    p()->m_geometry = new GeoDataLinearRing( point );
}

void GeoDataPlacemark::setGeometry( const GeoDataPolygon& point )
{
    detach();
    delete p()->m_geometry;
    p()->m_geometry = new GeoDataPolygon( point );
}

void GeoDataPlacemark::setGeometry( const GeoDataMultiGeometry& point )
{
    detach();
    delete p()->m_geometry;
    p()->m_geometry = new GeoDataMultiGeometry( point );
}

qreal GeoDataPlacemark::area() const
{
    return p()->m_area;
}

void GeoDataPlacemark::setArea( qreal area )
{
    detach();
    p()->m_area = area;
}

qint64 GeoDataPlacemark::population() const
{
    return p()->m_population;
}

void GeoDataPlacemark::setPopulation( qint64 population )
{
    detach();
    p()->m_population = population;
}

const QString GeoDataPlacemark::countryCode() const
{
    return p()->m_countrycode;
}

void GeoDataPlacemark::setCountryCode( const QString &countrycode )
{
    detach();
    p()->m_countrycode = countrycode;
}

void GeoDataPlacemark::pack( QDataStream& stream ) const
{
    GeoDataFeature::pack( stream );

    stream << p()->m_countrycode;
    stream << p()->m_area;
    stream << p()->m_population;

    stream << p()->m_geometry->geometryId();
    p()->m_geometry->pack( stream );
    p()->m_coordinate.pack( stream );
}

void GeoDataPlacemark::unpack( QDataStream& stream )
{
    detach();
    GeoDataFeature::unpack( stream );

    stream >> p()->m_countrycode;
    stream >> p()->m_area;
    stream >> p()->m_population;

    int geometryId;
    stream >> geometryId;
    switch( geometryId ) {
        case InvalidGeometryId:
            break;
        case GeoDataPointId:
            {
            GeoDataPoint* point = new GeoDataPoint( this );
            point->unpack( stream );
            delete p()->m_geometry;
            p()->m_geometry = point;
            }
            break;
        case GeoDataLineStringId:
            {
            GeoDataLineString* lineString = new GeoDataLineString( this );
            lineString->unpack( stream );
            delete p()->m_geometry;
            p()->m_geometry = lineString;
            }
            break;
        case GeoDataLinearRingId:
            {
            GeoDataLinearRing* linearRing = new GeoDataLinearRing( this );
            linearRing->unpack( stream );
            delete p()->m_geometry;
            p()->m_geometry = linearRing;
            }
            break;
        case GeoDataPolygonId:
            {
            GeoDataPolygon* polygon = new GeoDataPolygon( this );
            polygon->unpack( stream );
            delete p()->m_geometry;
            p()->m_geometry = polygon;
            }
            break;
        case GeoDataMultiGeometryId:
            {
            GeoDataMultiGeometry* multiGeometry = new GeoDataMultiGeometry( this );
            multiGeometry->unpack( stream );
            delete p()->m_geometry;
            p()->m_geometry = multiGeometry;
            }
            break;
        case GeoDataModelId:
            break;
        default: break;
    };
    p()->m_coordinate.unpack( stream );
}

}
<commit_msg>ignore parent<commit_after>//
// This file is part of the Marble Desktop Globe.
//
// This program is free software licensed under the GNU LGPL. You can
// find a copy of this license in LICENSE.txt in the top directory of
// the source code.
//
// Copyright 2004-2007 Torsten Rahn <tackat@kde.org>
// Copyright 2007      Inge Wallin  <ingwa@kde.org>
// Copyright 2008-2009      Patrick Spendrin <ps_ml@gmx.de>
//

// Own
#include "GeoDataPlacemark.h"

// Qt
#include <QtCore/QDataStream>
#include <QtCore/QDebug>

// Private
#include "GeoDataPlacemark_p.h"

namespace Marble
{

GeoDataPlacemark::GeoDataPlacemark( GeoDataObject* parent )
    : GeoDataFeature( new GeoDataPlacemarkPrivate )
{
}

GeoDataPlacemark::GeoDataPlacemark( const GeoDataPlacemark& other )
: GeoDataFeature( other )
{
}

GeoDataPlacemark::GeoDataPlacemark( const QString& name, GeoDataObject *parent )
    : GeoDataFeature( name )
{
}

GeoDataPlacemark::~GeoDataPlacemark()
{
}

GeoDataPlacemarkPrivate* GeoDataPlacemark::p() const
{
    return static_cast<GeoDataPlacemarkPrivate*>(d);
}

GeoDataGeometry* GeoDataPlacemark::geometry() const
{
    if( p()->m_geometry )
        return p()->m_geometry;
    else
        return &( p()->m_coordinate );
}

GeoDataCoordinates GeoDataPlacemark::coordinate() const
{
    return static_cast<GeoDataCoordinates>( p()->m_coordinate );
}

void GeoDataPlacemark::coordinate( qreal& lon, qreal& lat, qreal& alt ) const
{
    p()->m_coordinate.geoCoordinates( lon, lat );
    alt = p()->m_coordinate.altitude();
}

void GeoDataPlacemark::setCoordinate( qreal lon, qreal lat, qreal alt )
{
    detach();
    p()->m_coordinate = GeoDataPoint( lon, lat, alt, this );
}

void GeoDataPlacemark::setCoordinate( const GeoDataPoint &point )
{
    detach();
    p()->m_coordinate = GeoDataPoint( point );
    p()->m_coordinate.setParent( this );
}

void GeoDataPlacemark::setGeometry( const GeoDataPoint& point )
{
    detach();
    delete p()->m_geometry;
    p()->m_geometry = new GeoDataPoint( point );
}

void GeoDataPlacemark::setGeometry( const GeoDataLineString& point )
{
    detach();
    delete p()->m_geometry;
    p()->m_geometry = new GeoDataLineString( point );
}

void GeoDataPlacemark::setGeometry( const GeoDataLinearRing& point )
{
    detach();
    delete p()->m_geometry;
    p()->m_geometry = new GeoDataLinearRing( point );
}

void GeoDataPlacemark::setGeometry( const GeoDataPolygon& point )
{
    detach();
    delete p()->m_geometry;
    p()->m_geometry = new GeoDataPolygon( point );
}

void GeoDataPlacemark::setGeometry( const GeoDataMultiGeometry& point )
{
    detach();
    delete p()->m_geometry;
    p()->m_geometry = new GeoDataMultiGeometry( point );
}

qreal GeoDataPlacemark::area() const
{
    return p()->m_area;
}

void GeoDataPlacemark::setArea( qreal area )
{
    detach();
    p()->m_area = area;
}

qint64 GeoDataPlacemark::population() const
{
    return p()->m_population;
}

void GeoDataPlacemark::setPopulation( qint64 population )
{
    detach();
    p()->m_population = population;
}

const QString GeoDataPlacemark::countryCode() const
{
    return p()->m_countrycode;
}

void GeoDataPlacemark::setCountryCode( const QString &countrycode )
{
    detach();
    p()->m_countrycode = countrycode;
}

void GeoDataPlacemark::pack( QDataStream& stream ) const
{
    GeoDataFeature::pack( stream );

    stream << p()->m_countrycode;
    stream << p()->m_area;
    stream << p()->m_population;

    stream << p()->m_geometry->geometryId();
    p()->m_geometry->pack( stream );
    p()->m_coordinate.pack( stream );
}

void GeoDataPlacemark::unpack( QDataStream& stream )
{
    detach();
    GeoDataFeature::unpack( stream );

    stream >> p()->m_countrycode;
    stream >> p()->m_area;
    stream >> p()->m_population;

    int geometryId;
    stream >> geometryId;
    switch( geometryId ) {
        case InvalidGeometryId:
            break;
        case GeoDataPointId:
            {
            GeoDataPoint* point = new GeoDataPoint( this );
            point->unpack( stream );
            delete p()->m_geometry;
            p()->m_geometry = point;
            }
            break;
        case GeoDataLineStringId:
            {
            GeoDataLineString* lineString = new GeoDataLineString( this );
            lineString->unpack( stream );
            delete p()->m_geometry;
            p()->m_geometry = lineString;
            }
            break;
        case GeoDataLinearRingId:
            {
            GeoDataLinearRing* linearRing = new GeoDataLinearRing( this );
            linearRing->unpack( stream );
            delete p()->m_geometry;
            p()->m_geometry = linearRing;
            }
            break;
        case GeoDataPolygonId:
            {
            GeoDataPolygon* polygon = new GeoDataPolygon( this );
            polygon->unpack( stream );
            delete p()->m_geometry;
            p()->m_geometry = polygon;
            }
            break;
        case GeoDataMultiGeometryId:
            {
            GeoDataMultiGeometry* multiGeometry = new GeoDataMultiGeometry( this );
            multiGeometry->unpack( stream );
            delete p()->m_geometry;
            p()->m_geometry = multiGeometry;
            }
            break;
        case GeoDataModelId:
            break;
        default: break;
    };
    p()->m_coordinate.unpack( stream );
}

}
<|endoftext|>


<commit_before>/*
*
* Copyright 2016 Telefonica Investigacion y Desarrollo, S.A.U
*
* This file is part of Orion Context Broker.
*
* Orion Context Broker 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.
*
* Orion Context Broker 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 Orion Context Broker. If not, see http://www.gnu.org/licenses/.
*
* For those usages not covered by this license please contact with
* iot_support at tid dot es
*
* Author: Ken Zangelin
*/
#include "rapidjson/document.h"

#include "rest/ConnectionInfo.h"
#include "ngsi/ParseData.h"
#include "ngsi/Request.h"
#include "parse/forbiddenChars.h"
#include "jsonParseV2/jsonParseTypeNames.h"
#include "jsonParseV2/parseEntityObject.h"
#include "jsonParseV2/parseContextAttribute.h"

using namespace rapidjson;

/* ****************************************************************************
*
* parseEntityObject -
*/
std::string parseEntityObject(ConnectionInfo* ciP, Value::ConstValueIterator valueP, Entity* eP, bool attrsAllowed)
{
  std::string type  = jsonParseTypeNames[valueP->GetType()];

  if (type != "Object")
  {
    return "entity is not a JSON object";
  }

  if (valueP->HasMember("id") && valueP->HasMember("idPattern"))
  {
    return "both /id/ and /idPattern/ present";
  }

  if (!valueP->HasMember("id") && !valueP->HasMember("idPattern"))
  {
    return "nor /id/ nor /idPattern/ present";
  }

  for (Value::ConstMemberIterator iter = valueP->MemberBegin(); iter != valueP->MemberEnd(); ++iter)
  {
    std::string name  = iter->name.GetString();
    std::string type  = jsonParseTypeNames[iter->value.GetType()];

    if (name == "id")
    {
      if (type != "String")
      {
        return "invalid JSON type for entity id";
      }

      eP->id = iter->value.GetString();

      if (forbiddenChars(eP->id.c_str(), ""))
      {
        return "forbidden chars in entity id";
      }
    }
    else if (name == "idPattern")
    {
      if (type != "String")
      {
        return "invalid JSON type for entity idPattern";
      }

      regex_t re;
      if (regcomp(&re, iter->value.GetString(), REG_EXTENDED) != 0)
      {
        return "invalid regex for entity id pattern";
      }
      regfree(&re);  // If regcomp fails it frees up itself (see glibc sources for details)

      eP->id        = iter->value.GetString();
      eP->isPattern = "true";
    }
    else if (name == "type")
    {
      if (type != "String")
      {
        return "invalid JSON type for entity type";
      }

      eP->type      = iter->value.GetString();
      eP->typeGiven = true;

      if (forbiddenChars(eP->type.c_str(), ""))
      {
        return "forbidden chars in entity type";
      }
    }
    else if (name == "typePattern")
    {
      if (type != "String")
      {
        return "invalid JSON type for entity typePattern";
      }

      regex_t re;
      if (regcomp(&re, iter->value.GetString(), REG_EXTENDED) != 0)
      {
        return "invalid regex for entity type pattern";
      }
      regfree(&re);  // If regcomp fails it frees up itself (see glibc sources for details)

      eP->type          = iter->value.GetString();
      eP->isTypePattern = true;
    }
    else
    {
      std::string r;

      if (!attrsAllowed)
      {
        return "no attributes allowed in Entity in this payload";
      }

      ContextAttribute* caP = new ContextAttribute();
      r = parseContextAttribute(ciP, iter, caP);
      if (r == "OK")
      {
        eP->attributeVector.push_back(caP);
      }
      else
      {
        delete caP;
        return r;
      }
    }
  }

  return eP->check(ciP->apiVersion, ciP->requestType);
}
<commit_msg>changed the text for the forbidden chars error<commit_after>/*
*
* Copyright 2016 Telefonica Investigacion y Desarrollo, S.A.U
*
* This file is part of Orion Context Broker.
*
* Orion Context Broker 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.
*
* Orion Context Broker 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 Orion Context Broker. If not, see http://www.gnu.org/licenses/.
*
* For those usages not covered by this license please contact with
* iot_support at tid dot es
*
* Author: Ken Zangelin
*/
#include "rapidjson/document.h"

#include "rest/ConnectionInfo.h"
#include "ngsi/ParseData.h"
#include "ngsi/Request.h"
#include "parse/forbiddenChars.h"
#include "jsonParseV2/jsonParseTypeNames.h"
#include "jsonParseV2/parseEntityObject.h"
#include "jsonParseV2/parseContextAttribute.h"

using namespace rapidjson;

/* ****************************************************************************
*
* parseEntityObject -
*/
std::string parseEntityObject(ConnectionInfo* ciP, Value::ConstValueIterator valueP, Entity* eP, bool attrsAllowed)
{
  std::string type  = jsonParseTypeNames[valueP->GetType()];

  if (type != "Object")
  {
    return "entity is not a JSON object";
  }

  if (valueP->HasMember("id") && valueP->HasMember("idPattern"))
  {
    return "both /id/ and /idPattern/ present";
  }

  if (!valueP->HasMember("id") && !valueP->HasMember("idPattern"))
  {
    return "nor /id/ nor /idPattern/ present";
  }

  for (Value::ConstMemberIterator iter = valueP->MemberBegin(); iter != valueP->MemberEnd(); ++iter)
  {
    std::string name  = iter->name.GetString();
    std::string type  = jsonParseTypeNames[iter->value.GetType()];

    if (name == "id")
    {
      if (type != "String")
      {
        return "invalid JSON type for entity id";
      }

      eP->id = iter->value.GetString();

      if (forbiddenChars(eP->id.c_str(), ""))
      {
        return "Invalid characters in entity id";
      }
    }
    else if (name == "idPattern")
    {
      if (type != "String")
      {
        return "invalid JSON type for entity idPattern";
      }

      regex_t re;
      if (regcomp(&re, iter->value.GetString(), REG_EXTENDED) != 0)
      {
        return "invalid regex for entity id pattern";
      }
      regfree(&re);  // If regcomp fails it frees up itself (see glibc sources for details)

      eP->id        = iter->value.GetString();
      eP->isPattern = "true";
    }
    else if (name == "type")
    {
      if (type != "String")
      {
        return "invalid JSON type for entity type";
      }

      eP->type      = iter->value.GetString();
      eP->typeGiven = true;

      if (forbiddenChars(eP->type.c_str(), ""))
      {
        return "Invalid characters in entity type";
      }
    }
    else if (name == "typePattern")
    {
      if (type != "String")
      {
        return "invalid JSON type for entity typePattern";
      }

      regex_t re;
      if (regcomp(&re, iter->value.GetString(), REG_EXTENDED) != 0)
      {
        return "invalid regex for entity type pattern";
      }
      regfree(&re);  // If regcomp fails it frees up itself (see glibc sources for details)

      eP->type          = iter->value.GetString();
      eP->isTypePattern = true;
    }
    else
    {
      std::string r;

      if (!attrsAllowed)
      {
        return "no attributes allowed in Entity in this payload";
      }

      ContextAttribute* caP = new ContextAttribute();
      r = parseContextAttribute(ciP, iter, caP);
      if (r == "OK")
      {
        eP->attributeVector.push_back(caP);
      }
      else
      {
        delete caP;
        return r;
      }
    }
  }

  return eP->check(ciP->apiVersion, ciP->requestType);
}
<|endoftext|>


<commit_before>/*
Copyright (c) 2017 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.

Author: Leonardo de Moura
*/
#include "library/type_context.h"
#include "library/trace.h"
#include "library/constants.h"
#include "library/pp_options.h"
#include "library/app_builder.h"
#include "library/equations_compiler/pack_domain.h"
#include "library/equations_compiler/elim_match.h"
#include "library/equations_compiler/util.h"

namespace lean {
#define trace_wf(Code) lean_trace(name({"eqn_compiler", "wf_rec"}), type_context ctx = mk_type_context(); scope_trace_env _scope1(m_env, ctx); Code)

#define trace_debug_wf(Code) lean_trace(name({"debug", "eqn_compiler", "wf_rec"}), type_context ctx = mk_type_context(); scope_trace_env _scope1(m_env, ctx); Code)

struct wf_rec_fn {
    environment      m_env;
    options          m_opts;
    metavar_context  m_mctx;
    local_context    m_lctx;

    expr             m_ref;
    equations_header m_header;

    expr             m_R;
    expr             m_R_wf;

    wf_rec_fn(environment const & env, options const & opts,
              metavar_context const & mctx, local_context const & lctx):
        m_env(env), m_opts(opts), m_mctx(mctx), m_lctx(lctx) {
    }

    type_context mk_type_context(local_context const & lctx) {
        return type_context(m_env, m_opts, m_mctx, lctx, transparency_mode::Semireducible);
    }

    type_context mk_type_context() {
        return mk_type_context(m_lctx);
    }

    expr pack_domain(expr const & eqns) {
        type_context ctx = mk_type_context();
        return ::lean::pack_domain(ctx, eqns);
    }

    expr_pair mk_wf_relation(expr const & eqns) {
        lean_assert(get_equations_header(eqns).m_num_fns == 1);
        type_context ctx = mk_type_context();
        unpack_eqns ues(ctx, eqns);
        try {
            expr fn_type = ctx.relaxed_whnf(ctx.infer(ues.get_fn(0)));
            lean_assert(is_pi(fn_type));
            expr d       = binding_domain(fn_type);
            expr wf      = mk_app(ctx, get_has_well_founded_name(), d);
            if (auto inst = ctx.mk_class_instance(wf)) {
                bool mask[2] = {true, true};
                expr args[2] = {d, *inst};
                expr r   = mk_app(ctx, get_has_well_founded_r_name(), 2, mask, args);
                expr wf  = mk_app(ctx, get_has_well_founded_wf_name(), 2, mask, args);
                return expr_pair(r, wf);
            }
        } catch (exception & ex) {
            throw nested_exception(some_expr(m_ref),
                                   "failed to create well founded relation using type class resolution",
                                   ex);
        }
        throw generic_exception(m_ref, "failed to create well founded relation using type class resolution");
    }

    expr operator()(expr eqns) {
        m_ref    = eqns;
        m_header = get_equations_header(eqns);
        /* Make sure all functions are unary */
        eqns     = pack_domain(eqns);
        trace_debug_wf(tout() << "after pack_domain\n" << eqns << "\n";);

        equations_header const & header = get_equations_header(eqns);
        if (header.m_num_fns > 1) {
            // TODO(Leo): combine functions
            throw exception("support for mutual recursion has not been implemented yet");
        }

        if (is_wf_equations(eqns)) {
            m_R    = equations_wf_rel(eqns);
            m_R_wf = equations_wf_proof(eqns);
        } else {
            std::tie(m_R, m_R_wf) = mk_wf_relation(eqns);
        }

        {
            lean_trace_init_bool(name({"eqn_compiler", "wf_rec"}), get_pp_implicit_name(), true);
            trace_wf(tout() << "using well_founded relation\n" << m_R << "\n";);
        }

        // TODO(Leo):
        throw exception("support for well-founded recursion has not been implemented yet, "
                        "use 'set_option trace.eqn_compiler true' for additional information");
    }
};

/** \brief (Try to) eliminate "recursive calls" in the equations \c eqns by using well founded recursion.
    If successful, elim_match is used to compile pattern matching. */
expr wf_rec(environment & env, options const & opts,
            metavar_context & mctx, local_context const & lctx,
            expr const & eqns) {
    wf_rec_fn proc(env, opts, mctx, lctx);
    expr r = proc(eqns);
    env    = proc.m_env;
    mctx   = proc.m_mctx;
    return r;
}

void initialize_wf_rec() {
    register_trace_class({"eqn_compiler", "wf_rec"});
    register_trace_class({"debug", "eqn_compiler", "wf_rec"});
}

void finalize_wf_rec() {
}
}
<commit_msg>feat(library/equations_compiler/wf_rec): eliminate recursive calls using functional<commit_after>/*
Copyright (c) 2017 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.

Author: Leonardo de Moura
*/
#include "kernel/instantiate.h"
#include "library/type_context.h"
#include "library/trace.h"
#include "library/constants.h"
#include "library/pp_options.h"
#include "library/app_builder.h"
#include "library/sorry.h" // remove after we add tactic for proving recursive calls are decreasing
#include "library/replace_visitor_with_tc.h"
#include "library/equations_compiler/pack_domain.h"
#include "library/equations_compiler/elim_match.h"
#include "library/equations_compiler/util.h"

namespace lean {
#define trace_wf(Code) lean_trace(name({"eqn_compiler", "wf_rec"}), type_context ctx = mk_type_context(); scope_trace_env _scope1(m_env, ctx); Code)

#define trace_debug_wf(Code) lean_trace(name({"debug", "eqn_compiler", "wf_rec"}), type_context ctx = mk_type_context(); scope_trace_env _scope1(m_env, ctx); Code)

struct wf_rec_fn {
    environment      m_env;
    options          m_opts;
    metavar_context  m_mctx;
    local_context    m_lctx;

    expr             m_ref;
    equations_header m_header;

    expr             m_R;
    expr             m_R_wf;

    wf_rec_fn(environment const & env, options const & opts,
              metavar_context const & mctx, local_context const & lctx):
        m_env(env), m_opts(opts), m_mctx(mctx), m_lctx(lctx) {
    }

    type_context mk_type_context(local_context const & lctx) {
        return type_context(m_env, m_opts, m_mctx, lctx, transparency_mode::Semireducible);
    }

    type_context mk_type_context() {
        return mk_type_context(m_lctx);
    }

    expr pack_domain(expr const & eqns) {
        type_context ctx = mk_type_context();
        return ::lean::pack_domain(ctx, eqns);
    }

    expr_pair mk_wf_relation(expr const & eqns) {
        lean_assert(get_equations_header(eqns).m_num_fns == 1);
        type_context ctx = mk_type_context();
        unpack_eqns ues(ctx, eqns);
        try {
            expr fn_type = ctx.relaxed_whnf(ctx.infer(ues.get_fn(0)));
            lean_assert(is_pi(fn_type));
            expr d       = binding_domain(fn_type);
            expr wf      = mk_app(ctx, get_has_well_founded_name(), d);
            if (auto inst = ctx.mk_class_instance(wf)) {
                bool mask[2] = {true, true};
                expr args[2] = {d, *inst};
                expr r   = mk_app(ctx, get_has_well_founded_r_name(), 2, mask, args);
                expr wf  = mk_app(ctx, get_has_well_founded_wf_name(), 2, mask, args);
                return expr_pair(r, wf);
            }
        } catch (exception & ex) {
            throw nested_exception(some_expr(m_ref),
                                   "failed to create well founded relation using type class resolution",
                                   ex);
        }
        throw generic_exception(m_ref, "failed to create well founded relation using type class resolution");
    }

    /* Return the type of the new function. */
    expr mk_new_fn_type(type_context & ctx, unpack_eqns const & ues) {
        type_context::tmp_locals locals(ctx);
        expr fn        = ues.get_fn(0);
        expr fn_type   = ctx.relaxed_whnf(ctx.infer(fn));
        lean_assert(ues.get_arity_of(0) == 1);
        expr x         = locals.push_local("_x", binding_domain(fn_type));
        expr y         = locals.push_local("_y", binding_domain(fn_type));
        expr hlt       = mk_app(m_R, y, x);
        expr Cy        = instantiate(binding_body(fn_type), y);
        expr F_type    = ctx.mk_pi(y, mk_arrow(hlt, Cy));
        expr F         = locals.push_local("_F", F_type);
        expr Cx        = instantiate(binding_body(fn_type), x);
        return ctx.mk_pi(x, ctx.mk_pi(F, Cx));
    }

    struct elim_rec_apps_fn : public replace_visitor_with_tc {
        expr    m_fn;
        expr    m_R;
        expr    m_x;
        expr    m_F;

        elim_rec_apps_fn(type_context & ctx, expr const & fn, expr const & R, expr const & x, expr const & F):
            replace_visitor_with_tc(ctx), m_fn(fn), m_R(R), m_x(x), m_F(F) {}

        virtual expr visit_local(expr const & e) {
            if (mlocal_name(e) == mlocal_name(m_fn)) {
                /* unexpected occurrence of recursive function */
                throw generic_exception(e, "unexpected occurrence of recursive function\n");
            }
            return e;
        }

        /* Prove that y < x */
        expr mk_dec_proof(expr const & y) {
            expr y_R_x = mk_app(m_R, y, m_x);
            // TODO(Leo): invoke tactic, we use sorry for now
            return mk_sorry(y_R_x);
        }

        virtual expr visit_app(expr const & e) {
            expr const & fn = app_fn(e);
            if (is_local(fn) && mlocal_name(fn) == mlocal_name(m_fn)) {
                expr y   = visit(app_arg(e));
                expr hlt = mk_dec_proof(y);
                return mk_app(m_F, y, hlt);
            } else {
                return replace_visitor_with_tc::visit_app(e);
            }
        }
    };

    void update_eqs(type_context & ctx, unpack_eqns & ues, expr const & fn, expr const & new_fn) {
        buffer<expr> & eqns = ues.get_eqns_of(0);
        buffer<expr> new_eqns;
        for (expr const & eqn : eqns) {
            unpack_eqn ue(ctx, eqn);
            expr lhs = ue.lhs();
            expr rhs = ue.rhs();
            buffer<expr> lhs_args;
            get_app_args(lhs, lhs_args);
            lean_assert(lhs_args.size() == 1);
            expr new_lhs = mk_app(new_fn, lhs_args);
            expr type    = ctx.whnf(ctx.infer(new_lhs));
            lean_assert(is_pi(type));
            expr F       = ue.add_var(binding_name(type), binding_domain(type));
            new_lhs      = mk_app(new_lhs, F);
            ue.lhs()     = new_lhs;
            tout() << rhs << "\n";
            ue.rhs()     = elim_rec_apps_fn(ctx, fn, m_R, lhs_args[0], F)(rhs);
            new_eqns.push_back(ue.repack());
        }
        eqns = new_eqns;
    }

    expr elim_recursion(expr const & eqns) {
        type_context ctx = mk_type_context();
        unpack_eqns ues(ctx, eqns);
        lean_assert(ues.get_num_fns() == 1);
        expr fn      = ues.get_fn(0);
        expr fn_type = ctx.infer(fn);

        expr new_fn_type = mk_new_fn_type(ctx, ues);
        trace_debug_wf(tout() << "\n"; tout() << "new function type: " << new_fn_type << "\n";);
        expr new_fn      = ues.update_fn_type(0, new_fn_type);
        update_eqs(ctx, ues, fn, new_fn);
        expr new_eqns    = ues.repack();
        trace_debug_wf(tout() << "after well_founded elim_recursion:\n" << new_eqns << "\n";);
        m_mctx = ctx.mctx();
        return new_eqns;
    }

    expr operator()(expr eqns) {
        m_ref    = eqns;
        m_header = get_equations_header(eqns);
        /* Make sure all functions are unary */
        eqns     = pack_domain(eqns);
        trace_debug_wf(tout() << "after pack_domain\n" << eqns << "\n";);

        /* Make sure we have only one function */
        equations_header const & header = get_equations_header(eqns);
        if (header.m_num_fns > 1) {
            // TODO(Leo): combine functions
            throw exception("support for mutual recursion has not been implemented yet");
        }

        /* Retrieve well founded relation */
        if (is_wf_equations(eqns)) {
            m_R    = equations_wf_rel(eqns);
            m_R_wf = equations_wf_proof(eqns);
        } else {
            std::tie(m_R, m_R_wf) = mk_wf_relation(eqns);
        }
        {
            lean_trace_init_bool(name({"eqn_compiler", "wf_rec"}), get_pp_implicit_name(), true);
            trace_wf(tout() << "using well_founded relation\n" << m_R << " :\n  "
                     << mk_type_context().infer(m_R) << "\n";);
        }

        /* Eliminate recursion using functional. */
        eqns = elim_recursion(eqns);
        trace_debug_wf(tout() << "after elim_recursion\n" << eqns << "\n";);

        // TODO(Leo):
        throw exception("support for well-founded recursion has not been implemented yet, "
                        "use 'set_option trace.eqn_compiler true' for additional information");
    }
};

/** \brief (Try to) eliminate "recursive calls" in the equations \c eqns by using well founded recursion.
    If successful, elim_match is used to compile pattern matching. */
expr wf_rec(environment & env, options const & opts,
            metavar_context & mctx, local_context const & lctx,
            expr const & eqns) {
    wf_rec_fn proc(env, opts, mctx, lctx);
    expr r = proc(eqns);
    env    = proc.m_env;
    mctx   = proc.m_mctx;
    return r;
}

void initialize_wf_rec() {
    register_trace_class({"eqn_compiler", "wf_rec"});
    register_trace_class({"debug", "eqn_compiler", "wf_rec"});
}

void finalize_wf_rec() {
}
}
<|endoftext|>


<commit_before>//! \file
/*
**  Copyright (C) - Triton
**
**  This program is under the terms of the LGPLv3 License.
*/

#ifdef TRITON_PYTHON_BINDINGS

#ifndef TRITONPYTHONBINDINGS_H
#define TRITONPYTHONBINDINGS_H

#if defined(__unix__) || defined(__APPLE__)
  #include <python2.7/Python.h>
  #include <python2.7/longintrepr.h>
#elif _WIN32
  #include <Python.h>
#endif

//! \module The Triton namespace
namespace triton {
/*!
 *  \addtogroup triton
 *  @{
 */

  //! \module The Bindings namespace
  namespace bindings {
  /*!
   *  \ingroup triton
   *  \addtogroup bindings
   *  @{
   */

    //! \module The Python namespace
    namespace python {
    /*!
     *  \ingroup bindings
     *  \addtogroup python
     *  @{
     */

      //! Indicates if the python bindings is initialized.
      extern bool initialized;

      //! CPUSIZE python dict.
      extern PyObject* cpuSizeDict;

      //! OPCODE python dict.
      extern PyObject* opcodesDict;

      //! PREFIX python dict.
      extern PyObject* prefixesDict;

      //! REG python dict.
      extern PyObject* registersDict;

      #if defined(__unix__) || defined(__APPLE__)
      //! SYSCALL python dict.
      extern PyObject* syscallsDict;
      #endif

      //! ast python module.
      extern PyObject* astModule;

      //! triton python module.
      extern PyObject* tritonModule;

      //! triton python methods.
      extern PyMethodDef tritonCallbacks[];

      //! ast python methods.
      extern PyMethodDef astCallbacks[];

      //! Initializes the ARCH python namespace.
      void initArchNamespace(PyObject* archDict);

      //! Initializes the AST_NODE python namespace.
      void initAstNodeNamespace(PyObject* astNodeDict);

      //! Initializes the AST_REPRESENTATION python namespace.
      void initAstRepresentationNamespace(PyObject* astRepresentationDict);

      //! Initializes the CPUSIZE python namespace.
      void initCpuSizeNamespace(void);

      //! Initializes the REG python namespace.
      void initRegNamespace(void);

      //! Initializes the OPCODE python namespace.
      void initX86OpcodesNamespace(void);

      //! Initializes the PREFIX python namespace.
      void initX86PrefixesNamespace(void);

      //! Initializes the OPERAND python namespace.
      void initOperandNamespace(PyObject* operandDict);

      //! Initializes the OPTIMIZATION python namespace.
      void initSymOptiNamespace(PyObject* symOptiDict);

      //! Initializes the SYMEXPR python namespace.
      void initSymExprNamespace(PyObject* symExprDict);

      #if defined(__unix__) || defined(__APPLE__)
      //! Initializes the SYSCALL python namespace.
      void initSyscallNamespace(void);
      #endif

      //! Initializes the VERSION python namespace.
      void initVersionNamespace(PyObject* versionDict);

      //! Entry point python bindings.
      PyMODINIT_FUNC inittriton(void);

    /*! @} End of python namespace */
    };
  /*! @} End of bindings namespace */
  };
/*! @} End of triton namespace */
};

#endif /* TRITONPYTHONBINDINGS_H */
#endif /* TRITON_PYTHON_BINDINGS */
<commit_msg>Fix issue compiling with VS 2015<commit_after>//! \file
/*
**  Copyright (C) - Triton
**
**  This program is under the terms of the LGPLv3 License.
*/

#ifdef TRITON_PYTHON_BINDINGS

#ifndef TRITONPYTHONBINDINGS_H
#define TRITONPYTHONBINDINGS_H

#if defined(__unix__) || defined(__APPLE__)
  #include <python2.7/Python.h>
  #include <python2.7/longintrepr.h>
#elif _WIN32
  #include <Python.h>
  #include <longintrepr.h>
#endif

//! \module The Triton namespace
namespace triton {
/*!
 *  \addtogroup triton
 *  @{
 */

  //! \module The Bindings namespace
  namespace bindings {
  /*!
   *  \ingroup triton
   *  \addtogroup bindings
   *  @{
   */

    //! \module The Python namespace
    namespace python {
    /*!
     *  \ingroup bindings
     *  \addtogroup python
     *  @{
     */

      //! Indicates if the python bindings is initialized.
      extern bool initialized;

      //! CPUSIZE python dict.
      extern PyObject* cpuSizeDict;

      //! OPCODE python dict.
      extern PyObject* opcodesDict;

      //! PREFIX python dict.
      extern PyObject* prefixesDict;

      //! REG python dict.
      extern PyObject* registersDict;

      #if defined(__unix__) || defined(__APPLE__)
      //! SYSCALL python dict.
      extern PyObject* syscallsDict;
      #endif

      //! ast python module.
      extern PyObject* astModule;

      //! triton python module.
      extern PyObject* tritonModule;

      //! triton python methods.
      extern PyMethodDef tritonCallbacks[];

      //! ast python methods.
      extern PyMethodDef astCallbacks[];

      //! Initializes the ARCH python namespace.
      void initArchNamespace(PyObject* archDict);

      //! Initializes the AST_NODE python namespace.
      void initAstNodeNamespace(PyObject* astNodeDict);

      //! Initializes the AST_REPRESENTATION python namespace.
      void initAstRepresentationNamespace(PyObject* astRepresentationDict);

      //! Initializes the CPUSIZE python namespace.
      void initCpuSizeNamespace(void);

      //! Initializes the REG python namespace.
      void initRegNamespace(void);

      //! Initializes the OPCODE python namespace.
      void initX86OpcodesNamespace(void);

      //! Initializes the PREFIX python namespace.
      void initX86PrefixesNamespace(void);

      //! Initializes the OPERAND python namespace.
      void initOperandNamespace(PyObject* operandDict);

      //! Initializes the OPTIMIZATION python namespace.
      void initSymOptiNamespace(PyObject* symOptiDict);

      //! Initializes the SYMEXPR python namespace.
      void initSymExprNamespace(PyObject* symExprDict);

      #if defined(__unix__) || defined(__APPLE__)
      //! Initializes the SYSCALL python namespace.
      void initSyscallNamespace(void);
      #endif

      //! Initializes the VERSION python namespace.
      void initVersionNamespace(PyObject* versionDict);

      //! Entry point python bindings.
      PyMODINIT_FUNC inittriton(void);

    /*! @} End of python namespace */
    };
  /*! @} End of bindings namespace */
  };
/*! @} End of triton namespace */
};

#endif /* TRITONPYTHONBINDINGS_H */
#endif /* TRITON_PYTHON_BINDINGS */
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: migrateinstallpath.cxx,v $
 *
 *  $Revision: 1.7 $
 *
 *  last change: $Author: vg $ $Date: 2008-03-18 12:54:10 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#define _WIN32_WINDOWS 0x0410
#ifdef _MSC_VER
#pragma warning(push, 1) /* disable warnings within system headers */
#endif
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#include <msiquery.h>
#ifdef _MSC_VER
#pragma warning(pop)
#endif

#include <malloc.h>

#ifdef UNICODE
#define _UNICODE
#define _tstring    wstring
#else
#define _tstring    string
#endif
#include <tchar.h>
#include <string>

using namespace std;

namespace
{
    std::_tstring GetMsiProperty( MSIHANDLE handle, const std::_tstring& sProperty )
    {
        std::_tstring   result;
        TCHAR   szDummy[1] = TEXT("");
        DWORD   nChars = 0;

        if ( MsiGetProperty( handle, sProperty.c_str(), szDummy, &nChars ) == ERROR_MORE_DATA )
        {
            DWORD nBytes = ++nChars * sizeof(TCHAR);
            LPTSTR buffer = reinterpret_cast<LPTSTR>(_alloca(nBytes));
            ZeroMemory( buffer, nBytes );
            MsiGetProperty(handle, sProperty.c_str(), buffer, &nChars);
            result = buffer;
        }

        return  result;
    }
} // namespace

extern "C" UINT __stdcall MigrateInstallPath( MSIHANDLE handle )
{
    TCHAR   szValue[8192];
    DWORD   nValueSize = sizeof(szValue);
    HKEY    hKey;
    std::_tstring   sInstDir;

    std::_tstring   sManufacturer = GetMsiProperty( handle, TEXT("Manufacturer") );
    std::_tstring   sDefinedName = GetMsiProperty( handle, TEXT("DEFINEDPRODUCT") );
    std::_tstring   sUpdateVersion = GetMsiProperty( handle, TEXT("DEFINEDVERSION") );
    std::_tstring   sUpgradeCode = GetMsiProperty( handle, TEXT("UpgradeCode") );

    std::_tstring   sProductKey = "Software\\" + sManufacturer + "\\" + sDefinedName +
                                        "\\" + sUpdateVersion + "\\" + sUpgradeCode;

    std::_tstring   mystr;
    mystr = "ProductKey: " + sProductKey;
    // MessageBox( NULL, mystr.c_str(), "ProductKey", MB_OK );

    if ( ERROR_SUCCESS == RegOpenKey( HKEY_CURRENT_USER,  sProductKey.c_str(), &hKey ) )
    {
        if ( ERROR_SUCCESS == RegQueryValueEx( hKey, TEXT("OFFICEINSTALLLOCATION"), NULL, NULL, (LPBYTE)szValue, &nValueSize ) )
        {
            sInstDir = szValue;
            MsiSetProperty(handle, TEXT("OFFICEINSTALLLOCATION"), sInstDir.c_str());
            // MessageBox( NULL, sInstDir.c_str(), "Found in HKEY_CURRENT_USER", MB_OK );
        }
        RegCloseKey( hKey );
    }
    else if ( ERROR_SUCCESS == RegOpenKey( HKEY_LOCAL_MACHINE,  sProductKey.c_str(), &hKey ) )
    {
        if ( ERROR_SUCCESS == RegQueryValueEx( hKey, TEXT("OFFICEINSTALLLOCATION"), NULL, NULL, (LPBYTE)szValue, &nValueSize ) )
        {
            sInstDir = szValue;
            MsiSetProperty(handle, TEXT("OFFICEINSTALLLOCATION"), sInstDir.c_str());
            // MessageBox( NULL, sInstDir.c_str(), "Found in HKEY_LOCAL_MACHINE", MB_OK );
        }
        RegCloseKey( hKey );
    }

    return ERROR_SUCCESS;

}
<commit_msg>INTEGRATION: CWS changefileheader (1.7.4); FILE MERGED 2008/03/31 16:08:01 rt 1.7.4.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: migrateinstallpath.cxx,v $
 * $Revision: 1.8 $
 *
 * 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.
 *
 ************************************************************************/

#define _WIN32_WINDOWS 0x0410
#ifdef _MSC_VER
#pragma warning(push, 1) /* disable warnings within system headers */
#endif
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#include <msiquery.h>
#ifdef _MSC_VER
#pragma warning(pop)
#endif

#include <malloc.h>

#ifdef UNICODE
#define _UNICODE
#define _tstring    wstring
#else
#define _tstring    string
#endif
#include <tchar.h>
#include <string>

using namespace std;

namespace
{
    std::_tstring GetMsiProperty( MSIHANDLE handle, const std::_tstring& sProperty )
    {
        std::_tstring   result;
        TCHAR   szDummy[1] = TEXT("");
        DWORD   nChars = 0;

        if ( MsiGetProperty( handle, sProperty.c_str(), szDummy, &nChars ) == ERROR_MORE_DATA )
        {
            DWORD nBytes = ++nChars * sizeof(TCHAR);
            LPTSTR buffer = reinterpret_cast<LPTSTR>(_alloca(nBytes));
            ZeroMemory( buffer, nBytes );
            MsiGetProperty(handle, sProperty.c_str(), buffer, &nChars);
            result = buffer;
        }

        return  result;
    }
} // namespace

extern "C" UINT __stdcall MigrateInstallPath( MSIHANDLE handle )
{
    TCHAR   szValue[8192];
    DWORD   nValueSize = sizeof(szValue);
    HKEY    hKey;
    std::_tstring   sInstDir;

    std::_tstring   sManufacturer = GetMsiProperty( handle, TEXT("Manufacturer") );
    std::_tstring   sDefinedName = GetMsiProperty( handle, TEXT("DEFINEDPRODUCT") );
    std::_tstring   sUpdateVersion = GetMsiProperty( handle, TEXT("DEFINEDVERSION") );
    std::_tstring   sUpgradeCode = GetMsiProperty( handle, TEXT("UpgradeCode") );

    std::_tstring   sProductKey = "Software\\" + sManufacturer + "\\" + sDefinedName +
                                        "\\" + sUpdateVersion + "\\" + sUpgradeCode;

    std::_tstring   mystr;
    mystr = "ProductKey: " + sProductKey;
    // MessageBox( NULL, mystr.c_str(), "ProductKey", MB_OK );

    if ( ERROR_SUCCESS == RegOpenKey( HKEY_CURRENT_USER,  sProductKey.c_str(), &hKey ) )
    {
        if ( ERROR_SUCCESS == RegQueryValueEx( hKey, TEXT("OFFICEINSTALLLOCATION"), NULL, NULL, (LPBYTE)szValue, &nValueSize ) )
        {
            sInstDir = szValue;
            MsiSetProperty(handle, TEXT("OFFICEINSTALLLOCATION"), sInstDir.c_str());
            // MessageBox( NULL, sInstDir.c_str(), "Found in HKEY_CURRENT_USER", MB_OK );
        }
        RegCloseKey( hKey );
    }
    else if ( ERROR_SUCCESS == RegOpenKey( HKEY_LOCAL_MACHINE,  sProductKey.c_str(), &hKey ) )
    {
        if ( ERROR_SUCCESS == RegQueryValueEx( hKey, TEXT("OFFICEINSTALLLOCATION"), NULL, NULL, (LPBYTE)szValue, &nValueSize ) )
        {
            sInstDir = szValue;
            MsiSetProperty(handle, TEXT("OFFICEINSTALLLOCATION"), sInstDir.c_str());
            // MessageBox( NULL, sInstDir.c_str(), "Found in HKEY_LOCAL_MACHINE", MB_OK );
        }
        RegCloseKey( hKey );
    }

    return ERROR_SUCCESS;

}
<|endoftext|>