<commit_before>#include "script/Script.h"

#include "SDL.h"

#include "AmityContext.h"
#include "assets.h"
#include "log.h"
#include "script/TextureHandle.h"

static JSRuntime* rt = NULL;

static JSClass classGlobal = {
    "global", JSCLASS_GLOBAL_FLAGS,
    JS_PropertyStub, JS_PropertyStub, JS_PropertyStub, JS_PropertyStub,
    JS_EnumerateStub, JS_ResolveStub, JS_ConvertStub, JS_FinalizeStub,
    JSCLASS_NO_OPTIONAL_MEMBERS
};

template <class T, JSBool (T::*fn)(JSContext*, uintN, jsval*)>
static JSBool bindFunction (JSContext* jsCtx, uintN argc, jsval* vp)
{
    T* self = static_cast<T*>(JS_GetContextPrivate(jsCtx));
    return (self->*fn)(jsCtx, argc, vp);
}

template <class T, JSBool (T::*fn)(JSContext*, JSObject*, jsid, jsval*)>
static JSBool bindProperty (JSContext* jsCtx, JSObject* obj, jsid id, jsval* vp)
{
    T* self = static_cast<T*>(JS_GetContextPrivate(jsCtx));
    return (self->*fn)(jsCtx, obj, id, vp);
}

static void scriptReportError (JSContext* jsCtx, const char* message, JSErrorReport* report)
{
    LOGW("%s:%u:%s\n",
        report->filename ? report->filename : "<no filename>",
        (unsigned int) report->lineno,
        message);
}

static JSBool amity_log (JSContext* jsCtx, uintN argc, jsval* vp)
{
    const char* message;
    if (!JS_ConvertArguments(jsCtx, argc, JS_ARGV(jsCtx, vp), "s", &message)) {
        return JS_FALSE;
    }

    LOGI("--> %s", message);
    return JS_TRUE;
}

SCRIPT_PROPERTY (Script::amity_setOnEnterFrame, jsCtx, obj, id, vp)
{
    JSFunction* fn = JS_ValueToFunction(jsCtx, vp[0]);
    if (fn == NULL) {
        return JS_FALSE;
    }

    _onEnterFrame = fn;
    return JS_TRUE;
}

SCRIPT_PROPERTY (Script::amity_setOnMouseMove, jsCtx, obj, id, vp)
{
    JSFunction* fn = JS_ValueToFunction(jsCtx, vp[0]);
    if (fn == NULL) {
        return JS_FALSE;
    }

    _onMouseMove = fn;
    return JS_TRUE;
}

SCRIPT_FUNCTION (Script::amity_canvas_save, jsCtx, argc, vp)
{
    _amityCtx->canvas.save();
    return JS_TRUE;
}

SCRIPT_FUNCTION (Script::amity_canvas_restore, jsCtx, argc, vp)
{
    _amityCtx->canvas.restore();
    return JS_TRUE;
}

SCRIPT_FUNCTION (Script::amity_canvas_rotate, jsCtx, argc, vp)
{
    jsdouble angle;
    if (!JS_ConvertArguments(jsCtx, 1, JS_ARGV(jsCtx, vp), "d", &angle)) {
        return JS_FALSE;
    }

    _amityCtx->canvas.rotate(angle);
    return JS_TRUE;
}

SCRIPT_FUNCTION (Script::amity_canvas_translate, jsCtx, argc, vp)
{
    jsdouble x, y;
    if (!JS_ConvertArguments(jsCtx, 2, JS_ARGV(jsCtx, vp), "dd", &x, &y)) {
        return JS_FALSE;
    }

    _amityCtx->canvas.translate(x, y);
    return JS_TRUE;
}

SCRIPT_FUNCTION (Script::amity_canvas_scale, jsCtx, argc, vp)
{
    jsdouble x, y;
    if (!JS_ConvertArguments(jsCtx, 2, JS_ARGV(jsCtx, vp), "dd", &x, &y)) {
        return JS_FALSE;
    }

    _amityCtx->canvas.scale(x, y);
    return JS_TRUE;
}

SCRIPT_FUNCTION (Script::amity_canvas_drawTexture, jsCtx, argc, vp)
{
    JSObject* textureObj;
    jsdouble x, y;
    if (!JS_ConvertArguments(jsCtx, 3, JS_ARGV(jsCtx, vp), "odd", &textureObj, &x, &y)) {
        return JS_FALSE;
    }

    TextureHandle* textureHandle = TextureHandle::getFrom(jsCtx, textureObj);
    if (textureHandle == NULL) {
        return JS_FALSE;
    }
    _amityCtx->canvas.drawTexture(textureHandle->getTexture(), x, y);
    return JS_TRUE;
}

SCRIPT_PROPERTY (Script::amity_canvas_setAlpha, jsCtx, obj, id, vp)
{
    jsdouble alpha;
    if (!JS_ConvertArguments(jsCtx, 1, JS_ARGV(jsCtx, vp), "d", &alpha)) {
        return JS_FALSE;
    }

    _amityCtx->canvas.setAlpha(alpha);
    return JS_TRUE;
}

void Script::initAmityClasses ()
{
    JSObject* global = JS_GetGlobalObject(_jsCtx);

    JSObject* amity = JS_NewObject(_jsCtx, NULL, NULL, NULL);
    JSFunctionSpec amityFunctions[] = {
        JS_FS("log", amity_log, 1, 0),
        JS_FS("createTexture", amity_createTexture, 1, 0),
        JS_FS_END
    };
    JS_DefineFunctions(_jsCtx, amity, amityFunctions);

    JS_DefineProperty(_jsCtx, amity, "onEnterFrame", JSVAL_NULL,
        JS_PropertyStub, bindProperty<Script, &Script::amity_setOnEnterFrame>, 0);
    JS_DefineProperty(_jsCtx, amity, "onMouseMove", JSVAL_NULL,
        JS_PropertyStub, bindProperty<Script, &Script::amity_setOnMouseMove>, 0);

    JSObject* canvas = JS_NewObject(_jsCtx, NULL, NULL, NULL);
    int screenWidth, screenHeight;
    SDL_GetWindowSize(_amityCtx->window, &screenWidth, &screenHeight);
    JSConstDoubleSpec amityConstants[] = {
        { screenWidth, "WIDTH", 0, { 0, 0, 0 } },
        { screenHeight, "HEIGHT", 0, { 0, 0, 0 } },
        { 0, NULL, 0, { 0, 0, 0 } },
    };
    JS_DefineConstDoubles(_jsCtx, canvas, amityConstants);
    JSFunctionSpec canvasFunctions[] = {
        JS_FS("save", (bindFunction<Script, &Script::amity_canvas_save>), 1, 0),
        JS_FS("restore", (bindFunction<Script, &Script::amity_canvas_restore>), 1, 0),
        JS_FS("rotate", (bindFunction<Script, &Script::amity_canvas_rotate>), 1, 0),
        JS_FS("translate", (bindFunction<Script, &Script::amity_canvas_translate>), 2, 0),
        JS_FS("scale", (bindFunction<Script, &Script::amity_canvas_scale>), 2, 0),
        JS_FS("drawTexture", (bindFunction<Script, &Script::amity_canvas_drawTexture>), 3, 0),
        JS_FS_END
    };
    JS_DefineFunctions(_jsCtx, canvas, canvasFunctions);
    JS_DefineProperty(_jsCtx, canvas, "alpha", JSVAL_NULL,
        JS_PropertyStub, bindProperty<Script, &Script::amity_canvas_setAlpha>, 0);
    JS_DefineProperty(_jsCtx, amity, "canvas", OBJECT_TO_JSVAL(canvas), NULL, NULL, 0);

    JS_DefineProperty(_jsCtx, global, "$amity", OBJECT_TO_JSVAL(amity), NULL, NULL, 0);

    TextureHandle::init(_jsCtx);
}

Script::~Script ()
{
    if (_jsCtx != NULL) {
        JS_DestroyContext(_jsCtx);
    }
}

int Script::parse (const char* filename, const char* source)
{
    if (rt == NULL) {
        rt = JS_NewRuntime(8L * 1024L * 1024L);
        if (rt == NULL) {
            return 1;
        }
    }

    _jsCtx = JS_NewContext(rt, 8192);
    if (_jsCtx == NULL) {
        return 1;
    }

    // Attach 'this' to the context so we can look it up in bound functions
    JS_SetContextPrivate(_jsCtx, this);

    // TODO: Re-enable JSOPTION_JIT and JSOPTION_METHODJIT when they stop crashing my emulator
    JS_SetOptions(_jsCtx,
        JSOPTION_WERROR |
        JSOPTION_VAROBJFIX |
        JSOPTION_NO_SCRIPT_RVAL);
    JS_SetVersion(_jsCtx, JSVERSION_ECMA_5);
    JS_SetErrorReporter(_jsCtx, scriptReportError);

    JSObject* global = JS_NewGlobalObject(_jsCtx, &classGlobal);
    if (global == NULL) {
       return 1;
    }

    if (!JS_InitStandardClasses(_jsCtx, global)) {
       return 1;
    }
    initAmityClasses();

    JSBool success = JS_EvaluateScript(_jsCtx, global, source, strlen(source),
        filename, 0, NULL);

    return !success;
}

void Script::onEnterFrame (unsigned int dt)
{
    if (_onEnterFrame != NULL) {
        jsval argv[] = { INT_TO_JSVAL(dt) };
        jsval rval;
        JS_CallFunction(_jsCtx, JS_GetGlobalObject(_jsCtx), _onEnterFrame, 1, argv, &rval);
    }

    // TODO: Put this in a separate method?
    JS_MaybeGC(_jsCtx);
}

void Script::onEvent (const SDL_Event* event)
{
    JSFunction* handler;
    JSObject* obj;

    switch (event->type) {
        case SDL_MOUSEMOTION:
            handler = _onMouseMove;
            // TODO: Make a TouchEvent JS class
            obj = JS_NewObject(_jsCtx, NULL, NULL, JS_GetGlobalObject(_jsCtx));
            JS_DefineProperty(_jsCtx, obj, "x", INT_TO_JSVAL(event->motion.x),
                JS_PropertyStub, JS_PropertyStub, 0);
            JS_DefineProperty(_jsCtx, obj, "y", INT_TO_JSVAL(event->motion.y),
                JS_PropertyStub, JS_PropertyStub, 0);
            break;
        default:
            // Unhandled event
            return;
    }

    jsval argv = OBJECT_TO_JSVAL(obj);
    jsval rval;
    JS_CallFunction(_jsCtx, JS_GetGlobalObject(_jsCtx), handler, 1, &argv, &rval);
}
<commit_msg>Turned JIT back on.<commit_after>#include "script/Script.h"

#include "SDL.h"

#include "AmityContext.h"
#include "assets.h"
#include "log.h"
#include "script/TextureHandle.h"

static JSRuntime* rt = NULL;

static JSClass classGlobal = {
    "global", JSCLASS_GLOBAL_FLAGS,
    JS_PropertyStub, JS_PropertyStub, JS_PropertyStub, JS_PropertyStub,
    JS_EnumerateStub, JS_ResolveStub, JS_ConvertStub, JS_FinalizeStub,
    JSCLASS_NO_OPTIONAL_MEMBERS
};

template <class T, JSBool (T::*fn)(JSContext*, uintN, jsval*)>
static JSBool bindFunction (JSContext* jsCtx, uintN argc, jsval* vp)
{
    T* self = static_cast<T*>(JS_GetContextPrivate(jsCtx));
    return (self->*fn)(jsCtx, argc, vp);
}

template <class T, JSBool (T::*fn)(JSContext*, JSObject*, jsid, jsval*)>
static JSBool bindProperty (JSContext* jsCtx, JSObject* obj, jsid id, jsval* vp)
{
    T* self = static_cast<T*>(JS_GetContextPrivate(jsCtx));
    return (self->*fn)(jsCtx, obj, id, vp);
}

static void scriptReportError (JSContext* jsCtx, const char* message, JSErrorReport* report)
{
    LOGW("%s:%u:%s\n",
        report->filename ? report->filename : "<no filename>",
        (unsigned int) report->lineno,
        message);
}

static JSBool amity_log (JSContext* jsCtx, uintN argc, jsval* vp)
{
    const char* message;
    if (!JS_ConvertArguments(jsCtx, argc, JS_ARGV(jsCtx, vp), "s", &message)) {
        return JS_FALSE;
    }

    LOGI("--> %s", message);
    return JS_TRUE;
}

SCRIPT_PROPERTY (Script::amity_setOnEnterFrame, jsCtx, obj, id, vp)
{
    JSFunction* fn = JS_ValueToFunction(jsCtx, vp[0]);
    if (fn == NULL) {
        return JS_FALSE;
    }

    _onEnterFrame = fn;
    return JS_TRUE;
}

SCRIPT_PROPERTY (Script::amity_setOnMouseMove, jsCtx, obj, id, vp)
{
    JSFunction* fn = JS_ValueToFunction(jsCtx, vp[0]);
    if (fn == NULL) {
        return JS_FALSE;
    }

    _onMouseMove = fn;
    return JS_TRUE;
}

SCRIPT_FUNCTION (Script::amity_canvas_save, jsCtx, argc, vp)
{
    _amityCtx->canvas.save();
    return JS_TRUE;
}

SCRIPT_FUNCTION (Script::amity_canvas_restore, jsCtx, argc, vp)
{
    _amityCtx->canvas.restore();
    return JS_TRUE;
}

SCRIPT_FUNCTION (Script::amity_canvas_rotate, jsCtx, argc, vp)
{
    jsdouble angle;
    if (!JS_ConvertArguments(jsCtx, 1, JS_ARGV(jsCtx, vp), "d", &angle)) {
        return JS_FALSE;
    }

    _amityCtx->canvas.rotate(angle);
    return JS_TRUE;
}

SCRIPT_FUNCTION (Script::amity_canvas_translate, jsCtx, argc, vp)
{
    jsdouble x, y;
    if (!JS_ConvertArguments(jsCtx, 2, JS_ARGV(jsCtx, vp), "dd", &x, &y)) {
        return JS_FALSE;
    }

    _amityCtx->canvas.translate(x, y);
    return JS_TRUE;
}

SCRIPT_FUNCTION (Script::amity_canvas_scale, jsCtx, argc, vp)
{
    jsdouble x, y;
    if (!JS_ConvertArguments(jsCtx, 2, JS_ARGV(jsCtx, vp), "dd", &x, &y)) {
        return JS_FALSE;
    }

    _amityCtx->canvas.scale(x, y);
    return JS_TRUE;
}

SCRIPT_FUNCTION (Script::amity_canvas_drawTexture, jsCtx, argc, vp)
{
    JSObject* textureObj;
    jsdouble x, y;
    if (!JS_ConvertArguments(jsCtx, 3, JS_ARGV(jsCtx, vp), "odd", &textureObj, &x, &y)) {
        return JS_FALSE;
    }

    TextureHandle* textureHandle = TextureHandle::getFrom(jsCtx, textureObj);
    if (textureHandle == NULL) {
        return JS_FALSE;
    }
    _amityCtx->canvas.drawTexture(textureHandle->getTexture(), x, y);
    return JS_TRUE;
}

SCRIPT_PROPERTY (Script::amity_canvas_setAlpha, jsCtx, obj, id, vp)
{
    jsdouble alpha;
    if (!JS_ConvertArguments(jsCtx, 1, JS_ARGV(jsCtx, vp), "d", &alpha)) {
        return JS_FALSE;
    }

    _amityCtx->canvas.setAlpha(alpha);
    return JS_TRUE;
}

void Script::initAmityClasses ()
{
    JSObject* global = JS_GetGlobalObject(_jsCtx);

    JSObject* amity = JS_NewObject(_jsCtx, NULL, NULL, NULL);
    JSFunctionSpec amityFunctions[] = {
        JS_FS("log", amity_log, 1, 0),
        JS_FS("createTexture", amity_createTexture, 1, 0),
        JS_FS_END
    };
    JS_DefineFunctions(_jsCtx, amity, amityFunctions);

    JS_DefineProperty(_jsCtx, amity, "onEnterFrame", JSVAL_NULL,
        JS_PropertyStub, bindProperty<Script, &Script::amity_setOnEnterFrame>, 0);
    JS_DefineProperty(_jsCtx, amity, "onMouseMove", JSVAL_NULL,
        JS_PropertyStub, bindProperty<Script, &Script::amity_setOnMouseMove>, 0);

    JSObject* canvas = JS_NewObject(_jsCtx, NULL, NULL, NULL);
    int screenWidth, screenHeight;
    SDL_GetWindowSize(_amityCtx->window, &screenWidth, &screenHeight);
    JSConstDoubleSpec amityConstants[] = {
        { screenWidth, "WIDTH", 0, { 0, 0, 0 } },
        { screenHeight, "HEIGHT", 0, { 0, 0, 0 } },
        { 0, NULL, 0, { 0, 0, 0 } },
    };
    JS_DefineConstDoubles(_jsCtx, canvas, amityConstants);
    JSFunctionSpec canvasFunctions[] = {
        JS_FS("save", (bindFunction<Script, &Script::amity_canvas_save>), 1, 0),
        JS_FS("restore", (bindFunction<Script, &Script::amity_canvas_restore>), 1, 0),
        JS_FS("rotate", (bindFunction<Script, &Script::amity_canvas_rotate>), 1, 0),
        JS_FS("translate", (bindFunction<Script, &Script::amity_canvas_translate>), 2, 0),
        JS_FS("scale", (bindFunction<Script, &Script::amity_canvas_scale>), 2, 0),
        JS_FS("drawTexture", (bindFunction<Script, &Script::amity_canvas_drawTexture>), 3, 0),
        JS_FS_END
    };
    JS_DefineFunctions(_jsCtx, canvas, canvasFunctions);
    JS_DefineProperty(_jsCtx, canvas, "alpha", JSVAL_NULL,
        JS_PropertyStub, bindProperty<Script, &Script::amity_canvas_setAlpha>, 0);
    JS_DefineProperty(_jsCtx, amity, "canvas", OBJECT_TO_JSVAL(canvas), NULL, NULL, 0);

    JS_DefineProperty(_jsCtx, global, "$amity", OBJECT_TO_JSVAL(amity), NULL, NULL, 0);

    TextureHandle::init(_jsCtx);
}

Script::~Script ()
{
    if (_jsCtx != NULL) {
        JS_DestroyContext(_jsCtx);
    }
}

int Script::parse (const char* filename, const char* source)
{
    if (rt == NULL) {
        rt = JS_NewRuntime(8L * 1024L * 1024L);
        if (rt == NULL) {
            return 1;
        }
    }

    _jsCtx = JS_NewContext(rt, 8192);
    if (_jsCtx == NULL) {
        return 1;
    }

    // Attach 'this' to the context so we can look it up in bound functions
    JS_SetContextPrivate(_jsCtx, this);

    JS_SetOptions(_jsCtx,
        JSOPTION_WERROR |
        JSOPTION_VAROBJFIX |
        JSOPTION_JIT | JSOPTION_METHODJIT |
        JSOPTION_NO_SCRIPT_RVAL);
    JS_SetVersion(_jsCtx, JSVERSION_ECMA_5);
    JS_SetErrorReporter(_jsCtx, scriptReportError);

    JSObject* global = JS_NewGlobalObject(_jsCtx, &classGlobal);
    if (global == NULL) {
       return 1;
    }

    if (!JS_InitStandardClasses(_jsCtx, global)) {
       return 1;
    }
    initAmityClasses();

    JSBool success = JS_EvaluateScript(_jsCtx, global, source, strlen(source),
        filename, 0, NULL);

    return !success;
}

void Script::onEnterFrame (unsigned int dt)
{
    if (_onEnterFrame != NULL) {
        jsval argv[] = { INT_TO_JSVAL(dt) };
        jsval rval;
        JS_CallFunction(_jsCtx, JS_GetGlobalObject(_jsCtx), _onEnterFrame, 1, argv, &rval);
    }

    // TODO: Put this in a separate method?
    JS_MaybeGC(_jsCtx);
}

void Script::onEvent (const SDL_Event* event)
{
    JSFunction* handler;
    JSObject* obj;

    switch (event->type) {
        case SDL_MOUSEMOTION:
            handler = _onMouseMove;
            // TODO: Make a TouchEvent JS class
            obj = JS_NewObject(_jsCtx, NULL, NULL, JS_GetGlobalObject(_jsCtx));
            JS_DefineProperty(_jsCtx, obj, "x", INT_TO_JSVAL(event->motion.x),
                JS_PropertyStub, JS_PropertyStub, 0);
            JS_DefineProperty(_jsCtx, obj, "y", INT_TO_JSVAL(event->motion.y),
                JS_PropertyStub, JS_PropertyStub, 0);
            break;
        default:
            // Unhandled event
            return;
    }

    jsval argv = OBJECT_TO_JSVAL(obj);
    jsval rval;
    JS_CallFunction(_jsCtx, JS_GetGlobalObject(_jsCtx), handler, 1, &argv, &rval);
}
<|endoftext|>


<commit_before>void rec(const char *filename="data.root")
{
  gSystem->Load("libXrdClient.so");
  gSystem->Load("libNetX.so");
  //
  // First version of the reconstruction
  // script for the FDR'07

  // Set the CDB storage location
  // AliLog::SetModuleDebugLevel("STEER",2);
  AliCDBManager * man = AliCDBManager::Instance();
  //man->SetDefaultStorage("alien://folder=/alice/data/2007/LHC07w/OCDB/");
  man->SetDefaultStorage("/data/test2007/OCDB");
  man->SetSpecificStorage("GRP/GRP/Data","local://$ALICE_ROOT");
  man->SetSpecificStorage("ITS/Calib/DDLMapSDD","local://$ALICE_ROOT");
  man->SetSpecificStorage("MUON/Calib/Mapping","local://$ALICE_ROOT");
  man->SetSpecificStorage("MUON/Calib/DDLStore","local://$ALICE_ROOT");

  // TPC settings
  AliLog::SetClassDebugLevel("AliTPCclustererMI",2);
  AliTPCRecoParam * tpcRecoParam = AliTPCRecoParam::GetCosmicTestParam(kTRUE);
  tpcRecoParam->SetTimeInterval(60,940);
  tpcRecoParam->Dump();
  AliTPCReconstructor::SetRecoParam(tpcRecoParam);
  AliTPCReconstructor::SetStreamLevel(1);

  // PHOS settings
  AliPHOSRecoParam* recEmc = new AliPHOSRecoParamEmc();
  recEmc->SetSubtractPedestals(kTRUE);
  recEmc->SetMinE(0.05);
  recEmc->SetClusteringThreshold(0.10);
  AliPHOSReconstructor::SetRecoParamEmc(recEmc);

  // T0 settings
  AliLog::SetModuleDebugLevel("T0", 10);

  // MUON settings
  AliLog::SetClassDebugLevel("AliMUONRawStreamTracker",3);

  // Tracking settings
  //  AliMagFMaps* field = new AliMagFMaps("Maps","Maps", 2, 1., 10., 1);
  AliMagFMaps* field = new AliMagFMaps("Maps","Maps", 2, 0., 10., 2);
  AliTracker::SetFieldMap(field,1);

  // AliReconstruction settings
  AliReconstruction rec;
  rec.SetUniformFieldTracking(kFALSE);

  rec.SetWriteESDfriend(kTRUE);
  rec.SetWriteAlignmentData();
  rec.SetInput(filename);
  //
  //rec.SetRunLocalReconstruction("");
  rec.SetRunReconstruction("TPC");
  rec.SetFillESD("TPC");
  rec.SetRunVertexFinder(kFALSE);
  rec.SetRunQA(kFALSE);
  //
  //rec.SetEventRange(1,5);

  // In case some detectors have to be switched off...
  //  rec.SetRunLocalReconstruction("ALL");
  //  rec.SetRunTracking("ALL");
  //  rec.SetFillESD("ALL");
  // Disable vertex finder for the moment
  //  rec.SetRunVertexFinder(kFALSE);

  // To be enabled if some equipment IDs are not set correctly by DAQ
  //  rec.SetEquipmentIdMap("EquipmentIdMap.data");

  // Detector options if any
  rec.SetOption("MUON","SAVEDIGITS");
  rec.SetOption("TPC","OldRCUFormat");
  rec.SetOption("PHOS","OldRCUFormat");

  // To be enabled when CTP readout starts
  rec.SetFillTriggerESD(kFALSE);

  // all events in one single file
  rec.SetNumberOfEventsPerFile(-1);

  // switch off cleanESD
  rec.SetCleanESD(kFALSE);

  //AliLog::SetGlobalDebugLevel(2);
  rec.Run();

  cout << "-----------------------------------------------------------------" << endl;
  cout << "-----------------------------------------------------------------" << endl;
  cout << "--------- Reconstruction Completed. Start merging QAs -----------" << endl;
  cout << "-----------------------------------------------------------------" << endl;
  cout << "-----------------------------------------------------------------" << endl;
  AliQADataMakerSteer qas;
  qas.Merge();
}
<commit_msg>TPC reconstruction macro - according Marco Meoni<commit_after>void rec(const char *filename="data.root", const char *ocdbpath = "alien://folder=/alice/data/2007/LHC07w/OCDB/")
{
  gSystem->Load("libXrdClient.so");
  gSystem->Load("libNetx.so");
  AliLog::SetClassDebugLevel("AliTPCRawStream",-5);
  AliLog::SetClassDebugLevel("AliRawReaderDate",-5);
  AliLog::SetClassDebugLevel("AliTPCAltroMapping",-5);
  AliLog::SetModuleDebugLevel("RAW",-5);
  AliLog::SetGlobalLogLevel(3);
  //
  // First version of the reconstruction
  // script for the FDR'07

  // Set the CDB storage location
  // AliLog::SetModuleDebugLevel("STEER",2);
  AliCDBManager * man = AliCDBManager::Instance();
  //man->SetDefaultStorage("alien://folder=/alice/data/2007/LHC07w/OCDB/");
  man->SetDefaultStorage(ocdbpath);
  //  man->SetSpecificStorage("TPC/Calib/Parameters","local:///data/test2007/");
  // man->SetSpecificStorage("TPC/Calib/PadNoise","local:///data/test2007/");
  //   man->SetSpecificStorage("ITS/Calib/DDLMapSDD","local://$ALICE_ROOT");
  //   man->SetSpecificStorage("MUON/Calib/Mapping","local://$ALICE_ROOT");
  //   man->SetSpecificStorage("MUON/Calib/DDLStore","local://$ALICE_ROOT");

  // TPC settings
  AliLog::SetClassDebugLevel("AliTPCclustererMI",2);
  AliTPCRecoParam * tpcRecoParam = AliTPCRecoParam::GetCosmicTestParam(kFALSE);
  tpcRecoParam->SetTimeInterval(60,940);
  tpcRecoParam->Dump();
  AliTPCReconstructor::SetRecoParam(tpcRecoParam);
  AliTPCReconstructor::SetStreamLevel(1);

  // PHOS settings
  AliPHOSRecoParam* recEmc = new AliPHOSRecoParamEmc();
  recEmc->SetSubtractPedestals(kTRUE);
  recEmc->SetMinE(0.05);
  recEmc->SetClusteringThreshold(0.10);
  AliPHOSReconstructor::SetRecoParamEmc(recEmc);

  // T0 settings
  AliLog::SetModuleDebugLevel("T0", 10);

  // MUON settings
  AliLog::SetClassDebugLevel("AliMUONRawStreamTracker",3);

  // Tracking settings
  //  AliMagFMaps* field = new AliMagFMaps("Maps","Maps", 2, 1., 10., 1);
  AliMagFMaps* field = new AliMagFMaps("Maps","Maps", 2, 0., 10., 2);
  AliTracker::SetFieldMap(field,1);

  // AliReconstruction settings
  AliReconstruction rec;
  rec.SetUniformFieldTracking(kFALSE);
  rec.SetWriteESDfriend(kTRUE);
  rec.SetWriteAlignmentData();
  rec.SetInput(filename);
  //
  //rec.SetRunLocalReconstruction("");
  rec.SetRunReconstruction("TPC");
  rec.SetFillESD("TPC");
  rec.SetRunV0Finder(kFALSE);
  rec.SetRunVertexFinder(kFALSE);

  rec.SetRunQA(kTRUE);

  // Detector options if any
  rec.SetOption("MUON","SAVEDIGITS");
  rec.SetOption("TPC","OldRCUFormat");
  rec.SetOption("PHOS","OldRCUFormat");

  // To be enabled when CTP readout starts
  rec.SetFillTriggerESD(kFALSE);

  // all events in one single file
  rec.SetNumberOfEventsPerFile(-1);

  // switch off cleanESD
  rec.SetCleanESD(kFALSE);

  //AliLog::SetGlobalDebugLevel(2);
  rec.Run();

  cout << "-----------------------------------------------------------------" << endl;
  cout << "-----------------------------------------------------------------" << endl;
  cout << "--------- Reconstruction Completed. Start merging QAs -----------" << endl;
  cout << "-----------------------------------------------------------------" << endl;
  cout << "-----------------------------------------------------------------" << endl;
  AliQADataMakerSteer qas;
  qas.Merge();
}
<|endoftext|>


<commit_before>#ifdef WIN32
/////////////////////////////////////////////////////////////////////////////
// Disable unavoidable warning messages:

//  4103: used #pragma pack to change alignment
//  4114: same type qualifier used more than once
//  4201: nonstandard extension used : nameless struct/union
//  4237: "keyword" reserved for future use
//  4251: class needs to have dll-interface to export class
//  4275: non DLL-interface class used as base for DLL-interface class
//  4290: C++ Exception Specification ignored
//  4503: decorated name length exceeded, name was truncated
//  4786: string too long - truncated to 255 characters

#pragma warning(disable : 4103 4114 4201 4237 4251 4275 4290 4503 4335 4786)

#endif // WIN32

#include <osgProducer/Viewer>

#include <osg/Group>
#include <osg/Geode>
#include <osg/ShapeDrawable>
#include <osg/Texture2D>
#include <osg/PositionAttitudeTransform>
#include <osg/MatrixTransform>
#include <osg/CoordinateSystemNode>

#include <osgDB/FileUtils>
#include <osgDB/ReadFile>

#include <osgText/Text>

#include <osgTerrain/DataSet>

#include <osgGA/NodeTrackerManipulator>

class GraphicsContext {
    public:
        GraphicsContext()
        {
            rs = new Producer::RenderSurface;
            rs->setWindowRectangle(0,0,1,1);
            rs->useBorder(false);
            rs->useConfigEventThread(false);
            rs->realize();
        }

        virtual ~GraphicsContext()
        {
        }

    private:
        Producer::ref_ptr<Producer::RenderSurface> rs;
};

osg::Node* createEarth()
{
    osg::ref_ptr<osg::Node> scene;

    {
        std::string filename = osgDB::findDataFile("Images/land_shallow_topo_2048.jpg");

        // make osgTerrain::DataSet quieter..
        osgTerrain::DataSet::setNotifyOffset(1);

        osg::ref_ptr<osgTerrain::DataSet> dataSet = new osgTerrain::DataSet;

        // register the source imagery
        {
            osgTerrain::DataSet::Source* source = new osgTerrain::DataSet::Source(osgTerrain::DataSet::Source::IMAGE, filename);

	    source->setCoordinateSystemPolicy(osgTerrain::DataSet::Source::PREFER_CONFIG_SETTINGS);
            source->setCoordinateSystem(osgTerrain::DataSet::coordinateSystemStringToWTK("WGS84"));

 	    source->setGeoTransformPolicy(osgTerrain::DataSet::Source::PREFER_CONFIG_SETTINGS_BUT_SCALE_BY_FILE_RESOLUTION);
            source->setGeoTransformFromRange(-180.0, 180.0, -90.0, 90.0);

            dataSet->addSource(source);
        }

        // set up destination database paramters.
        dataSet->setDatabaseType(osgTerrain::DataSet::LOD_DATABASE);
        dataSet->setConvertFromGeographicToGeocentric(true);
        dataSet->setDestinationName("test.osg");

        // load the source data and record sizes.
        dataSet->loadSources();

        GraphicsContext context;
        dataSet->createDestination(30);

        if (dataSet->getDatabaseType()==osgTerrain::DataSet::LOD_DATABASE) dataSet->buildDestination();
        else dataSet->writeDestination();

        scene = dataSet->getDestinationRootNode();
    }

    return scene.release();

}

class ModelPositionCallback : public osg::NodeCallback
{
public:

    ModelPositionCallback():
        _latitude(0.0),
        _longitude(0.0),
        _height(100000.0)
    {
        _rotation.makeRotate(osg::DegreesToRadians(90.0),0.0,0.0,1.0);
    }

    void updateParameters()
    {
        _longitude += ((2.0*osg::PI)/360.0)/20.0;
    }

    virtual void operator()(osg::Node* node, osg::NodeVisitor* nv)
    {
        updateParameters();

        osg::NodePath nodePath = nv->getNodePath();

        osg::MatrixTransform* mt = nodePath.empty() ? 0 : dynamic_cast<osg::MatrixTransform*>(nodePath.back());
        if (mt)
        {
            osg::CoordinateSystemNode* csn = 0;

            // find coordinate system node from our parental chain
            unsigned int i;
            for(i=0; i<nodePath.size() && csn==0; ++i)
            {
                csn = dynamic_cast<osg::CoordinateSystemNode*>(nodePath[i]);
            }

            if (csn)
            {

                osg::EllipsoidModel* ellipsoid = csn->getEllipsoidModel();
                if (ellipsoid)
                {
                    osg::Matrixd matrix;
                    for(i+=1; i<nodePath.size()-1; ++i)
                    {
                        osg::Transform* transform = nodePath[i]->asTransform();
                        if (transform) transform->computeLocalToWorldMatrix(matrix, nv);
                    }

                    //osg::Matrixd matrix;
                    ellipsoid->computeLocalToWorldTransformFromLatLongHeight(_latitude,_longitude,_height,matrix);
                    matrix.preMult(osg::Matrixd::rotate(_rotation));

                    mt->setMatrix(matrix);
                }

            }
        }

        traverse(node,nv);
    }

    double                  _latitude;
    double                  _longitude;
    double                  _height;
    osg::Quat               _rotation;
};

class FindNamedNodeVisitor : public osg::NodeVisitor
{
public:
    FindNamedNodeVisitor(const std::string& name):
        osg::NodeVisitor(osg::NodeVisitor::TRAVERSE_ALL_CHILDREN),
        _name(name) {}

    virtual void apply(osg::Node& node)
    {
        if (node.getName()==_name)
        {
            _foundNodes.push_back(&node);
        }
        traverse(node);
    }

    typedef std::vector< osg::ref_ptr<osg::Node> > NodeList;

    std::string _name;
    NodeList _foundNodes;
};

int main(int argc, char **argv)
{
    // use an ArgumentParser object to manage the program arguments.
    osg::ArgumentParser arguments(&argc,argv);

    // set up the usage document, in case we need to print out how to use this program.
    arguments.getApplicationUsage()->setDescription(arguments.getApplicationName()+" is the example which demonstrates use of particle systems.");
    arguments.getApplicationUsage()->setCommandLineUsage(arguments.getApplicationName()+" [options] image_file_left_eye image_file_right_eye");
    arguments.getApplicationUsage()->addCommandLineOption("-h or --help","Display this information");

    // construct the viewer.
    osgProducer::Viewer viewer(arguments);

    // set up the value with sensible default event handlers.
    viewer.setUpViewer(osgProducer::Viewer::STANDARD_SETTINGS);

    viewer.getCullSettings().setComputeNearFarMode(osg::CullSettings::COMPUTE_NEAR_FAR_USING_PRIMITIVES);
    viewer.getCullSettings().setNearFarRatio(0.00001f);

    // get details on keyboard and mouse bindings used by the viewer.
    viewer.getUsage(*arguments.getApplicationUsage());

    osg::Quat rotation;
    osg::Vec4 vec4;
    while (arguments.read("--rotate-model",vec4[0],vec4[1],vec4[2],vec4[3]))
    {
        osg::Quat local_rotate;
        local_rotate.makeRotate(osg::DegreesToRadians(vec4[0]),vec4[1],vec4[2],vec4[3]);

        rotation = rotation * local_rotate;
    }

    osg::NodeCallback* nc = 0;
    std::string flightpath_filename;
    while (arguments.read("--flight-path",flightpath_filename))
    {
        std::ifstream fin(flightpath_filename.c_str());
        if (fin)
        {
            osg::AnimationPath* path = new osg::AnimationPath;
            path->read(fin);
            nc = new osg::AnimationPathCallback(path);
        }
    }

    osgGA::NodeTrackerManipulator::TrackerMode trackerMode = osgGA::NodeTrackerManipulator::NODE_CENTER_AND_ROTATION;
    std::string mode;
    while (arguments.read("--tracker-mode",mode))
    {
        if (mode=="NODE_CENTER_AND_ROTATION") trackerMode = osgGA::NodeTrackerManipulator::NODE_CENTER_AND_ROTATION;
        else if (mode=="NODE_CENTER_AND_AZIM") trackerMode = osgGA::NodeTrackerManipulator::NODE_CENTER_AND_AZIM;
        else if (mode=="NODE_CENTER") trackerMode = osgGA::NodeTrackerManipulator::NODE_CENTER;
        else
        {
            std::cout<<"Unrecognized --tracker-mode option "<<mode<<", valid options are:"<<std::endl;
            std::cout<<"    NODE_CENTER_AND_ROTATION"<<std::endl;
            std::cout<<"    NODE_CENTER_AND_AZIM"<<std::endl;
            std::cout<<"    NODE_CENTER"<<std::endl;
            return 1;
        }
    }

    osgGA::NodeTrackerManipulator::RotationMode rotationMode = osgGA::NodeTrackerManipulator::TRACKBALL;
    while (arguments.read("--rotation-mode",mode))
    {
        if (mode=="TRACKBALL") rotationMode = osgGA::NodeTrackerManipulator::TRACKBALL;
        else if (mode=="ELEVATION_AZIM") rotationMode = osgGA::NodeTrackerManipulator::ELEVATION_AZIM;
        else
        {
            std::cout<<"Unrecognized --rotation-mode option "<<mode<<", valid options are:"<<std::endl;
            std::cout<<"    TRACKBALL"<<std::endl;
            std::cout<<"    ELEVATION_AZIM"<<std::endl;
            return 1;
        }
    }

    // if user request help write it out to cout.
    if (arguments.read("-h") || arguments.read("--help"))
    {
        arguments.getApplicationUsage()->write(std::cout);
        return 1;
    }

    // any option left unread are converted into errors to write out later.
    arguments.reportRemainingOptionsAsUnrecognized();

    // report any errors if they have occured when parsing the program aguments.
    if (arguments.errors())
    {
        arguments.writeErrorMessages(std::cout);
        return 1;
    }

    osg::ref_ptr<osg::Node> root = createEarth();

    if (!root) return 0;

    // add a viewport to the viewer and attach the scene graph.
    viewer.setSceneData(root.get());

    osg::CoordinateSystemNode* csn = dynamic_cast<osg::CoordinateSystemNode*>(root.get());
    if (csn)
    {
        osg::Node* cessna = osgDB::readNodeFile("cessna.osg");
        if (cessna)
        {
            double s = 30000.0 / cessna->getBound().radius();

            osg::MatrixTransform* scaler = new osg::MatrixTransform;
            scaler->addChild(cessna);
            scaler->setMatrix(osg::Matrixd::scale(s,s,s)*osg::Matrixd::rotate(rotation));
            scaler->getOrCreateStateSet()->setMode(GL_RESCALE_NORMAL,osg::StateAttribute::ON);

            osg::MatrixTransform* mt = new osg::MatrixTransform;
            mt->addChild(scaler);

            if (!nc) nc = new ModelPositionCallback;

            mt->setUpdateCallback(nc);

            csn->addChild(mt);

            osgGA::NodeTrackerManipulator* tm = new osgGA::NodeTrackerManipulator;
            tm->setTrackerMode(trackerMode);
            tm->setRotationMode(rotationMode);
            tm->setTrackNode(scaler);

            unsigned int num = viewer.addCameraManipulator(tm);
            viewer.selectCameraManipulator(num);
        }
        else
        {
             std::cout<<"Failed to read cessna.osg"<<std::endl;
        }
    }

    // create the windows and run the threads.
    viewer.realize();

    while( !viewer.done() )
    {
        // wait for all cull and draw threads to complete.
        viewer.sync();

        // update the scene by traversing it with the the update visitor which will
        // call all node update callbacks and animations.
        viewer.update();

        // fire off the cull and draw traversals of the scene.
        viewer.frame();

    }

    // wait for all cull and draw threads to complete before exit.
    viewer.sync();

    return 0;
}
<commit_msg>Introduced a flight path that goes around the earth going into the north and sound hemisphere's with heading and roll adjustment.<commit_after>#ifdef WIN32
/////////////////////////////////////////////////////////////////////////////
// Disable unavoidable warning messages:

//  4103: used #pragma pack to change alignment
//  4114: same type qualifier used more than once
//  4201: nonstandard extension used : nameless struct/union
//  4237: "keyword" reserved for future use
//  4251: class needs to have dll-interface to export class
//  4275: non DLL-interface class used as base for DLL-interface class
//  4290: C++ Exception Specification ignored
//  4503: decorated name length exceeded, name was truncated
//  4786: string too long - truncated to 255 characters

#pragma warning(disable : 4103 4114 4201 4237 4251 4275 4290 4503 4335 4786)

#endif // WIN32

#include <osgProducer/Viewer>

#include <osg/Group>
#include <osg/Geode>
#include <osg/ShapeDrawable>
#include <osg/Texture2D>
#include <osg/PositionAttitudeTransform>
#include <osg/MatrixTransform>
#include <osg/CoordinateSystemNode>

#include <osgDB/FileUtils>
#include <osgDB/ReadFile>

#include <osgText/Text>

#include <osgTerrain/DataSet>

#include <osgGA/NodeTrackerManipulator>

class GraphicsContext {
    public:
        GraphicsContext()
        {
            rs = new Producer::RenderSurface;
            rs->setWindowRectangle(0,0,1,1);
            rs->useBorder(false);
            rs->useConfigEventThread(false);
            rs->realize();
        }

        virtual ~GraphicsContext()
        {
        }

    private:
        Producer::ref_ptr<Producer::RenderSurface> rs;
};

osg::Node* createEarth()
{
    osg::ref_ptr<osg::Node> scene;

    {
        std::string filename = osgDB::findDataFile("Images/land_shallow_topo_2048.jpg");

        // make osgTerrain::DataSet quieter..
        osgTerrain::DataSet::setNotifyOffset(1);

        osg::ref_ptr<osgTerrain::DataSet> dataSet = new osgTerrain::DataSet;

        // register the source imagery
        {
            osgTerrain::DataSet::Source* source = new osgTerrain::DataSet::Source(osgTerrain::DataSet::Source::IMAGE, filename);

	    source->setCoordinateSystemPolicy(osgTerrain::DataSet::Source::PREFER_CONFIG_SETTINGS);
            source->setCoordinateSystem(osgTerrain::DataSet::coordinateSystemStringToWTK("WGS84"));

 	    source->setGeoTransformPolicy(osgTerrain::DataSet::Source::PREFER_CONFIG_SETTINGS_BUT_SCALE_BY_FILE_RESOLUTION);
            source->setGeoTransformFromRange(-180.0, 180.0, -90.0, 90.0);

            dataSet->addSource(source);
        }

        // set up destination database paramters.
        dataSet->setDatabaseType(osgTerrain::DataSet::LOD_DATABASE);
        dataSet->setConvertFromGeographicToGeocentric(true);
        dataSet->setDestinationName("test.osg");

        // load the source data and record sizes.
        dataSet->loadSources();

        GraphicsContext context;
        dataSet->createDestination(30);

        if (dataSet->getDatabaseType()==osgTerrain::DataSet::LOD_DATABASE) dataSet->buildDestination();
        else dataSet->writeDestination();

        scene = dataSet->getDestinationRootNode();
    }

    return scene.release();

}

class ModelPositionCallback : public osg::NodeCallback
{
public:

    ModelPositionCallback():
        _latitude(0.0),
        _longitude(0.0),
        _height(100000.0)
    {
        _rotation.makeRotate(osg::DegreesToRadians(90.0),0.0,0.0,1.0);
    }

    void updateParameters()
    {
        _longitude += ((2.0*osg::PI)/360.0)/20.0;
        _latitude = sin(_longitude);

        // adjust the heading and roll to roughly look ok,
        // but bearing no reality to physics..
        osg::Quat heading;
        heading.makeRotate(osg::DegreesToRadians(90.0)+cos(_longitude),0.0,0.0,1.0);

        osg::Quat roll;
        roll.makeRotate(-_latitude*0.5f,0.0,1.0,0.0);

        _rotation = roll*heading;
    }

    virtual void operator()(osg::Node* node, osg::NodeVisitor* nv)
    {
        updateParameters();

        osg::NodePath nodePath = nv->getNodePath();

        osg::MatrixTransform* mt = nodePath.empty() ? 0 : dynamic_cast<osg::MatrixTransform*>(nodePath.back());
        if (mt)
        {
            osg::CoordinateSystemNode* csn = 0;

            // find coordinate system node from our parental chain
            unsigned int i;
            for(i=0; i<nodePath.size() && csn==0; ++i)
            {
                csn = dynamic_cast<osg::CoordinateSystemNode*>(nodePath[i]);
            }

            if (csn)
            {

                osg::EllipsoidModel* ellipsoid = csn->getEllipsoidModel();
                if (ellipsoid)
                {
                    osg::Matrixd matrix;
                    for(i+=1; i<nodePath.size()-1; ++i)
                    {
                        osg::Transform* transform = nodePath[i]->asTransform();
                        if (transform) transform->computeLocalToWorldMatrix(matrix, nv);
                    }

                    //osg::Matrixd matrix;
                    ellipsoid->computeLocalToWorldTransformFromLatLongHeight(_latitude,_longitude,_height,matrix);
                    matrix.preMult(osg::Matrixd::rotate(_rotation));

                    mt->setMatrix(matrix);
                }

            }
        }

        traverse(node,nv);
    }

    double                  _latitude;
    double                  _longitude;
    double                  _height;
    osg::Quat               _rotation;
};

class FindNamedNodeVisitor : public osg::NodeVisitor
{
public:
    FindNamedNodeVisitor(const std::string& name):
        osg::NodeVisitor(osg::NodeVisitor::TRAVERSE_ALL_CHILDREN),
        _name(name) {}

    virtual void apply(osg::Node& node)
    {
        if (node.getName()==_name)
        {
            _foundNodes.push_back(&node);
        }
        traverse(node);
    }

    typedef std::vector< osg::ref_ptr<osg::Node> > NodeList;

    std::string _name;
    NodeList _foundNodes;
};

int main(int argc, char **argv)
{
    // use an ArgumentParser object to manage the program arguments.
    osg::ArgumentParser arguments(&argc,argv);

    // set up the usage document, in case we need to print out how to use this program.
    arguments.getApplicationUsage()->setDescription(arguments.getApplicationName()+" is the example which demonstrates use of particle systems.");
    arguments.getApplicationUsage()->setCommandLineUsage(arguments.getApplicationName()+" [options] image_file_left_eye image_file_right_eye");
    arguments.getApplicationUsage()->addCommandLineOption("-h or --help","Display this information");
    arguments.getApplicationUsage()->addCommandLineOption("--rotate-model angle x y z","Rotate model");
    arguments.getApplicationUsage()->addCommandLineOption("--flight-path","");
    arguments.getApplicationUsage()->addCommandLineOption("--tracker-mode","NODE_CENTER_AND_ROTATION | NODE_CENTER_AND_AZIM | NODE_CENTER");
    arguments.getApplicationUsage()->addCommandLineOption("--rotation-mode","TRACKBALL | ELEVATION_AZIM");

    // construct the viewer.
    osgProducer::Viewer viewer(arguments);

    // set up the value with sensible default event handlers.
    viewer.setUpViewer(osgProducer::Viewer::STANDARD_SETTINGS);

    viewer.getCullSettings().setComputeNearFarMode(osg::CullSettings::COMPUTE_NEAR_FAR_USING_PRIMITIVES);
    viewer.getCullSettings().setNearFarRatio(0.00001f);

    // get details on keyboard and mouse bindings used by the viewer.
    viewer.getUsage(*arguments.getApplicationUsage());

    osg::Quat rotation;
    osg::Vec4 vec4;
    while (arguments.read("--rotate-model",vec4[0],vec4[1],vec4[2],vec4[3]))
    {
        osg::Quat local_rotate;
        local_rotate.makeRotate(osg::DegreesToRadians(vec4[0]),vec4[1],vec4[2],vec4[3]);

        rotation = rotation * local_rotate;
    }

    osg::NodeCallback* nc = 0;
    std::string flightpath_filename;
    while (arguments.read("--flight-path",flightpath_filename))
    {
        std::ifstream fin(flightpath_filename.c_str());
        if (fin)
        {
            osg::AnimationPath* path = new osg::AnimationPath;
            path->read(fin);
            nc = new osg::AnimationPathCallback(path);
        }
    }

    osgGA::NodeTrackerManipulator::TrackerMode trackerMode = osgGA::NodeTrackerManipulator::NODE_CENTER_AND_ROTATION;
    std::string mode;
    while (arguments.read("--tracker-mode",mode))
    {
        if (mode=="NODE_CENTER_AND_ROTATION") trackerMode = osgGA::NodeTrackerManipulator::NODE_CENTER_AND_ROTATION;
        else if (mode=="NODE_CENTER_AND_AZIM") trackerMode = osgGA::NodeTrackerManipulator::NODE_CENTER_AND_AZIM;
        else if (mode=="NODE_CENTER") trackerMode = osgGA::NodeTrackerManipulator::NODE_CENTER;
        else
        {
            std::cout<<"Unrecognized --tracker-mode option "<<mode<<", valid options are:"<<std::endl;
            std::cout<<"    NODE_CENTER_AND_ROTATION"<<std::endl;
            std::cout<<"    NODE_CENTER_AND_AZIM"<<std::endl;
            std::cout<<"    NODE_CENTER"<<std::endl;
            return 1;
        }
    }

    osgGA::NodeTrackerManipulator::RotationMode rotationMode = osgGA::NodeTrackerManipulator::TRACKBALL;
    while (arguments.read("--rotation-mode",mode))
    {
        if (mode=="TRACKBALL") rotationMode = osgGA::NodeTrackerManipulator::TRACKBALL;
        else if (mode=="ELEVATION_AZIM") rotationMode = osgGA::NodeTrackerManipulator::ELEVATION_AZIM;
        else
        {
            std::cout<<"Unrecognized --rotation-mode option "<<mode<<", valid options are:"<<std::endl;
            std::cout<<"    TRACKBALL"<<std::endl;
            std::cout<<"    ELEVATION_AZIM"<<std::endl;
            return 1;
        }
    }

    // if user request help write it out to cout.
    if (arguments.read("-h") || arguments.read("--help"))
    {
        arguments.getApplicationUsage()->write(std::cout);
        return 1;
    }

    // any option left unread are converted into errors to write out later.
    arguments.reportRemainingOptionsAsUnrecognized();

    // report any errors if they have occured when parsing the program aguments.
    if (arguments.errors())
    {
        arguments.writeErrorMessages(std::cout);
        return 1;
    }

    osg::ref_ptr<osg::Node> root = createEarth();

    if (!root) return 0;

    // add a viewport to the viewer and attach the scene graph.
    viewer.setSceneData(root.get());

    osg::CoordinateSystemNode* csn = dynamic_cast<osg::CoordinateSystemNode*>(root.get());
    if (csn)
    {
        osg::Node* cessna = osgDB::readNodeFile("cessna.osg");
        if (cessna)
        {
            double s = 30000.0 / cessna->getBound().radius();

            osg::MatrixTransform* scaler = new osg::MatrixTransform;
            scaler->addChild(cessna);
            scaler->setMatrix(osg::Matrixd::scale(s,s,s)*osg::Matrixd::rotate(rotation));
            scaler->getOrCreateStateSet()->setMode(GL_RESCALE_NORMAL,osg::StateAttribute::ON);

            osg::MatrixTransform* mt = new osg::MatrixTransform;
            mt->addChild(scaler);

            if (!nc) nc = new ModelPositionCallback;

            mt->setUpdateCallback(nc);

            csn->addChild(mt);

            osgGA::NodeTrackerManipulator* tm = new osgGA::NodeTrackerManipulator;
            tm->setTrackerMode(trackerMode);
            tm->setRotationMode(rotationMode);
            tm->setTrackNode(scaler);

            unsigned int num = viewer.addCameraManipulator(tm);
            viewer.selectCameraManipulator(num);
        }
        else
        {
             std::cout<<"Failed to read cessna.osg"<<std::endl;
        }
    }

    // create the windows and run the threads.
    viewer.realize();

    while( !viewer.done() )
    {
        // wait for all cull and draw threads to complete.
        viewer.sync();

        // update the scene by traversing it with the the update visitor which will
        // call all node update callbacks and animations.
        viewer.update();

        // fire off the cull and draw traversals of the scene.
        viewer.frame();

    }

    // wait for all cull and draw threads to complete before exit.
    viewer.sync();

    return 0;
}
<|endoftext|>


<commit_before>// $Id$

AliHadCorrTask* AddTaskHadCorr(
  const char *nTracks        = "Tracks",
  const char *nClusters      = "CaloClusters",
  const char *outClusName    = "CaloClustersCorr",
  const Double_t hadcorr     = 1,
  const Double_t minPt       = 0.15,
  const Double_t phiMatch    = 0.050,
  const Double_t etaMatch    = 0.025,
  const char *outputname     = "AnalysisResults.root",
  const Bool_t   histo       = kFALSE
)
{
  // Get the pointer to the existing analysis manager via the static access method.
  //==============================================================================
  AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
  if (!mgr)
  {
    ::Error("AddTaskHadCorr", "No analysis manager to connect to.");
    return NULL;
  }

  // Check the analysis type using the event handlers connected to the analysis manager.
  //==============================================================================
  if (!mgr->GetInputEventHandler())
  {
    ::Error("AddTaskHadCorr", "This task requires an input event handler");
    return NULL;
  }

  //-------------------------------------------------------
  // Init the task and do settings
  //-------------------------------------------------------

  TString name(Form("HadCorr_%s", outClusName));
  AliHadCorrTask *hcor = new AliHadCorrTask(name, histo);
  hcor->SetTracksName(nTracks);
  hcor->SetClusName(nClusters);
  hcor->SetOutClusName(outClusName);
  hcor->SetPhiMatch(phiMatch);
  hcor->SetEtaMatch(etaMatch);
  hcor->SetHadCorr(hadcorr);
  hcor->SetMinPt(minPt);

  //-------------------------------------------------------
  // Final settings, pass to manager and set the containers
  //-------------------------------------------------------

  mgr->AddTask(hcor);

  // Create containers for input/output
  mgr->ConnectInput (hcor, 0, mgr->GetCommonInputContainer() );

  if (histo) {
    AliAnalysisDataContainer *cohcor = mgr->CreateContainer(name,
							    TList::Class(),
							    AliAnalysisManager::kOutputContainer,
							    outputname);
    mgr->ConnectOutput(hcor,1,cohcor);
  }

  return hcor;
}
<commit_msg>adjust<commit_after>// $Id$

AliHadCorrTask* AddTaskHadCorr(
  const char *nTracks        = "Tracks",
  const char *nClusters      = "CaloClusters",
  const char *outClusName    = "CaloClustersCorr",
  const Double_t hadcorr     = 1,
  const Double_t minPt       = 0.15,
  const Double_t phiMatch    = 0.050,
  const Double_t etaMatch    = 0.025,
  const Double_t Eexcl       = 0,
  const Bool_t trackClus     = kTRUE,
  const Bool_t   histo       = kFALSE,
  const char *outputname     = "AnalysisResults.root"
)
{
  // Get the pointer to the existing analysis manager via the static access method.
  //==============================================================================
  AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
  if (!mgr)
  {
    ::Error("AddTaskHadCorr", "No analysis manager to connect to.");
    return NULL;
  }

  // Check the analysis type using the event handlers connected to the analysis manager.
  //==============================================================================
  if (!mgr->GetInputEventHandler())
  {
    ::Error("AddTaskHadCorr", "This task requires an input event handler");
    return NULL;
  }

  //-------------------------------------------------------
  // Init the task and do settings
  //-------------------------------------------------------

  TString name(Form("HadCorr_%s", outClusName));
  AliHadCorrTask *hcor = new AliHadCorrTask(name, histo);
  hcor->SetTracksName(nTracks);
  hcor->SetClusName(nClusters);
  hcor->SetOutClusName(outClusName);
  hcor->SetPhiMatch(phiMatch);
  hcor->SetEtaMatch(etaMatch);
  hcor->SetHadCorr(hadcorr);
  hcor->SetPtCut(minPt);
  hcor->SetEexcl(Eexcl);
  hcor->SetTrackClus(trackClus);
  hcor->SetAnaType(AliAnalysisTaskEmcal::kEMCAL);

  //-------------------------------------------------------
  // Final settings, pass to manager and set the containers
  //-------------------------------------------------------

  mgr->AddTask(hcor);

  // Create containers for input/output
  mgr->ConnectInput (hcor, 0, mgr->GetCommonInputContainer() );

  if (histo) {
    AliAnalysisDataContainer *cohcor = mgr->CreateContainer(name,
							    TList::Class(),
							    AliAnalysisManager::kOutputContainer,
							    outputname);
    mgr->ConnectOutput(hcor,1,cohcor);
  }

  return hcor;
}
<|endoftext|>


<commit_before>//
// Created by sancar koyunlu on 9/18/13.
// Copyright (c) 2013 hazelcast. All rights reserved.

#include "ClientTxnMapTest.h"
#include "HazelcastInstanceFactory.h"
#include "HazelcastClient.h"
#include "Employee.h"
#include "SimpleTnxTask.h"

namespace hazelcast {
    namespace client {

        class HazelcastClient;

        namespace test {
            using namespace iTest;

            ClientTxnMapTest::ClientTxnMapTest(HazelcastInstanceFactory &hazelcastInstanceFactory)
            :hazelcastInstanceFactory(hazelcastInstanceFactory)
            , instance(hazelcastInstanceFactory)
            , client(new HazelcastClient(clientConfig.addAddress(Address("localhost", 5701)))) {
            };

            ClientTxnMapTest::~ClientTxnMapTest() {
            }

            void ClientTxnMapTest::addTests() {
                //addTest(&ClientTxnMapTest::testPutGet, "testPutGet");
                //addTest(&ClientTxnMapTest::testKeySetValues, "testKeySetValues");
                //addTest(&ClientTxnMapTest::testKeySetAndValuesWithPredicates, "testKeysetAndValuesWithPredicates");

                addTest(&ClientTxnMapTest::simple_executeTransaction_test, "simple_executeTransaction_test");
                addTest(&ClientTxnMapTest::simple_executeTransactionException_test, "simple_executeTransactionException_test");

            };

            void ClientTxnMapTest::beforeClass() {
            };

            void ClientTxnMapTest::afterClass() {
                client.reset();
                instance.shutdown();
            };

            void ClientTxnMapTest::beforeTest() {
            };

            void ClientTxnMapTest::afterTest() {
            };

            void ClientTxnMapTest::testPutGet() {
                std::string name = "defMap";

                TransactionContext context = client->newTransactionContext();
                context.beginTransaction();

                TransactionalMap<std::string, std::string> map = context.getMap<std::string, std::string>(name);

                assertEqual("", map.put("key1", "value1"));
                assertEqual("value1", map.get("key1"));
                assertEqual("", client->getMap<std::string, std::string>(name).get("key1"));

                context.commitTransaction();

                assertEqual("value1", client->getMap<std::string, std::string>(name).get("key1"));
            }

//            @Test
//            public void testGetForUpdate() throws TransactionException {
//            final IMap<String, Integer> map = hz.getMap("testTxnGetForUpdate");
//            final CountDownLatch latch1 = new CountDownLatch(1);
//            final CountDownLatch latch2 = new CountDownLatch(1);
//            map.put("var", 0);
//            final AtomicBoolean pass = new AtomicBoolean(true);
//
//
//            Runnable incrementor = new Runnable() {
//                public void run() {
//                    try {
//                        latch1.await(100, TimeUnit.SECONDS);
//                        pass.set(map.tryPut("var", 1, 0, TimeUnit.SECONDS) == false);
//                        latch2.countDown();
//                    } catch (Exception e) {
//                    }
//                }
//            };
//            new Thread(incrementor).start();
//            boolean b = hz.executeTransaction(new TransactionalTask<Boolean>() {
//                public Boolean execute(TransactionalTaskContext context) throws TransactionException {
//                    try {
//                        final TransactionalMap<String, Integer> txMap = context.getMap("testTxnGetForUpdate");
//                        txMap.getForUpdate("var");
//                        latch1.countDown();
//                        latch2.await(100, TimeUnit.SECONDS);
//                    } catch (Exception e) {
//                    }
//                    return true;
//                }
//            });
//            assertTrue(b);
//            assertTrue(pass.get());
//            assertTrue(map.tryPut("var", 1, 0, TimeUnit.SECONDS));
//        }

            void ClientTxnMapTest::testKeySetValues() {
                std::string name = "testKeySetValues";
                IMap<std::string, std::string> map = client->getMap<std::string, std::string>(name);
                map.put("key1", "value1");
                map.put("key2", "value2");

                TransactionContext context = client->newTransactionContext();
                context.beginTransaction();
                TransactionalMap<std::string, std::string> txMap = context.getMap<std::string, std::string>(name);
                assertEqual("", txMap.put("key3", "value3"));

                assertEqual(3, txMap.size());
                assertEqual(3, txMap.keySet().size());
                assertEqual(3, txMap.values().size());
                context.commitTransaction();

                assertEqual(3, map.size());
                assertEqual(3, map.keySet().size());
                assertEqual(3, map.values().size());

            }

            void ClientTxnMapTest::testKeySetAndValuesWithPredicates() {
                std::string name = "testKeysetAndValuesWithPredicates";
                IMap<Employee, Employee> map = client->getMap<Employee, Employee>(name);

                Employee emp1("abc-123-xvz", 34);
                Employee emp2("abc-123-xvz", 20);

                map.put(emp1, emp1);

                TransactionContext context = client->newTransactionContext();
                context.beginTransaction();

                Employee empty;
                TransactionalMap<Employee, Employee> txMap = context.getMap<Employee, Employee>(name);
                assertEqual(empty, txMap.put(emp2, emp2));

                assertEqual(2, txMap.size());
                assertEqual(2, txMap.keySet().size());
                assertEqual(0, txMap.keySet("age = 10").size());
                assertEqual(0, txMap.values("age = 10").size());
                assertEqual(2, txMap.keySet("age >= 10").size());
                assertEqual(2, txMap.values("age >= 10").size());

                context.commitTransaction();

                assertEqual(2, map.size());
                assertEqual(2, map.values().size());

            }

            void ClientTxnMapTest::simple_executeTransaction_test() {

                SimpleTnxTask task;

                bool res = client->executeTransaction<bool, SimpleTnxTask>(task);

                IMap<string, string> map = client->getMap<string, string>(SimpleTnxTask::mapName);

                assertTrue(res);

                assertEqual(SimpleTnxTask::expected, map.get(SimpleTnxTask::key) );
                assertEqual(SimpleTnxTask::expectedSZ, map.size());
            }

            void ClientTxnMapTest::simple_executeTransactionException_test() {

                SimpleTnxTaskFail task;

                try{
                    client->executeTransaction<bool, SimpleTnxTaskFail>(task);
                }catch(std::exception &e){}

                IMap<string, string> map = client->getMap<string, string>(SimpleTnxTaskFail::mapName);

                assertEqual(nullptr, map.get(SimpleTnxTask::key) );
                assertEqual(SimpleTnxTaskFail::expectedSZ, map.size());
            }

        }
    }
}<commit_msg>add commit add tests<commit_after>//
// Created by sancar koyunlu on 9/18/13.
// Copyright (c) 2013 hazelcast. All rights reserved.

#include "ClientTxnMapTest.h"
#include "HazelcastInstanceFactory.h"
#include "HazelcastClient.h"
#include "Employee.h"
#include "SimpleTnxTask.h"

namespace hazelcast {
    namespace client {

        class HazelcastClient;

        namespace test {
            using namespace iTest;

            ClientTxnMapTest::ClientTxnMapTest(HazelcastInstanceFactory &hazelcastInstanceFactory)
            :hazelcastInstanceFactory(hazelcastInstanceFactory)
            , instance(hazelcastInstanceFactory)
            , client(new HazelcastClient(clientConfig.addAddress(Address("localhost", 5701)))) {
            };

            ClientTxnMapTest::~ClientTxnMapTest() {
            }

            void ClientTxnMapTest::addTests() {
                //addTest(&ClientTxnMapTest::testPutGet, "testPutGet");
                //addTest(&ClientTxnMapTest::testKeySetValues, "testKeySetValues");
                //addTest(&ClientTxnMapTest::testKeySetAndValuesWithPredicates, "testKeysetAndValuesWithPredicates");

                addTest(&ClientTxnMapTest::simple_executeTransaction_test, "simple_executeTransaction_test");
                addTest(&ClientTxnMapTest::simple_executeTransactionException_test, "simple_executeTransactionException_test");

            };

            void ClientTxnMapTest::beforeClass() {
            };

            void ClientTxnMapTest::afterClass() {
                client.reset();
                instance.shutdown();
            };

            void ClientTxnMapTest::beforeTest() {
            };

            void ClientTxnMapTest::afterTest() {
            };

            void ClientTxnMapTest::testPutGet() {
                std::string name = "defMap";

                TransactionContext context = client->newTransactionContext();
                context.beginTransaction();

                TransactionalMap<std::string, std::string> map = context.getMap<std::string, std::string>(name);

                assertEqual("", map.put("key1", "value1"));
                assertEqual("value1", map.get("key1"));
                assertEqual("", client->getMap<std::string, std::string>(name).get("key1"));

                context.commitTransaction();

                assertEqual("value1", client->getMap<std::string, std::string>(name).get("key1"));
            }

//            @Test
//            public void testGetForUpdate() throws TransactionException {
//            final IMap<String, Integer> map = hz.getMap("testTxnGetForUpdate");
//            final CountDownLatch latch1 = new CountDownLatch(1);
//            final CountDownLatch latch2 = new CountDownLatch(1);
//            map.put("var", 0);
//            final AtomicBoolean pass = new AtomicBoolean(true);
//
//
//            Runnable incrementor = new Runnable() {
//                public void run() {
//                    try {
//                        latch1.await(100, TimeUnit.SECONDS);
//                        pass.set(map.tryPut("var", 1, 0, TimeUnit.SECONDS) == false);
//                        latch2.countDown();
//                    } catch (Exception e) {
//                    }
//                }
//            };
//            new Thread(incrementor).start();
//            boolean b = hz.executeTransaction(new TransactionalTask<Boolean>() {
//                public Boolean execute(TransactionalTaskContext context) throws TransactionException {
//                    try {
//                        final TransactionalMap<String, Integer> txMap = context.getMap("testTxnGetForUpdate");
//                        txMap.getForUpdate("var");
//                        latch1.countDown();
//                        latch2.await(100, TimeUnit.SECONDS);
//                    } catch (Exception e) {
//                    }
//                    return true;
//                }
//            });
//            assertTrue(b);
//            assertTrue(pass.get());
//            assertTrue(map.tryPut("var", 1, 0, TimeUnit.SECONDS));
//        }

            void ClientTxnMapTest::testKeySetValues() {
                std::string name = "testKeySetValues";
                IMap<std::string, std::string> map = client->getMap<std::string, std::string>(name);
                map.put("key1", "value1");
                map.put("key2", "value2");

                TransactionContext context = client->newTransactionContext();
                context.beginTransaction();
                TransactionalMap<std::string, std::string> txMap = context.getMap<std::string, std::string>(name);
                assertEqual("", txMap.put("key3", "value3"));

                assertEqual(3, txMap.size());
                assertEqual(3, txMap.keySet().size());
                assertEqual(3, txMap.values().size());
                context.commitTransaction();

                assertEqual(3, map.size());
                assertEqual(3, map.keySet().size());
                assertEqual(3, map.values().size());

            }

            void ClientTxnMapTest::testKeySetAndValuesWithPredicates() {
                std::string name = "testKeysetAndValuesWithPredicates";
                IMap<Employee, Employee> map = client->getMap<Employee, Employee>(name);

                Employee emp1("abc-123-xvz", 34);
                Employee emp2("abc-123-xvz", 20);

                map.put(emp1, emp1);

                TransactionContext context = client->newTransactionContext();
                context.beginTransaction();

                Employee empty;
                TransactionalMap<Employee, Employee> txMap = context.getMap<Employee, Employee>(name);
                assertEqual(empty, txMap.put(emp2, emp2));

                assertEqual(2, txMap.size());
                assertEqual(2, txMap.keySet().size());
                assertEqual(0, txMap.keySet("age = 10").size());
                assertEqual(0, txMap.values("age = 10").size());
                assertEqual(2, txMap.keySet("age >= 10").size());
                assertEqual(2, txMap.values("age >= 10").size());

                context.commitTransaction();

                assertEqual(2, map.size());
                assertEqual(2, map.values().size());

            }

            void ClientTxnMapTest::simple_executeTransaction_test() {

                SimpleTnxTask task;

                bool res = client->executeTransaction<bool, SimpleTnxTask>(task);

                IMap<string, string> map = client->getMap<string, string>(SimpleTnxTask::mapName);

                assertTrue(res);

                assertEqual(SimpleTnxTask::expected, map.get(SimpleTnxTask::key) );
                assertEqual(SimpleTnxTask::expectedSZ, map.size());
            }

            void ClientTxnMapTest::simple_executeTransactionException_test() {

                SimpleTnxTaskFail task;

                try{
                    client->executeTransaction<bool, SimpleTnxTaskFail>(task);
                }catch(std::exception &e){}

                IMap<string, string> map = client->getMap<string, string>(SimpleTnxTaskFail::mapName);

                assertEqual("", map.get(SimpleTnxTask::key) );
                assertEqual(SimpleTnxTaskFail::expectedSZ, map.size());
            }

        }
    }
}<|endoftext|>


<commit_before>// meta_programming.cpp: playground to experiment with meta programming techniques to generalize functions and algorithms
//
// Copyright (C) 2017-2020 Stillwater Supercomputing, Inc.
//
// This file is part of the universal numbers project, which is released under an MIT Open Source license.
#include "common.hpp"
#include <complex>

// when you define POSIT_VERBOSE_OUTPUT executing an ADD the code will print intermediate results
//#define POSIT_VERBOSE_OUTPUT
#define POSIT_TRACE_CONVERSION
// enable posit arithmetic exceptions
#define POSIT_THROW_ARITHMETIC_EXCEPTION 1
#include <universal/posit/posit>

template<typename T>
struct hasSerialize {
	typedef char yes[1];
	typedef char no[2];

	// helper to determine if serialize is a function
	template<typename T, T function>
	struct reallyHas;

	template<typename T> static yes& test(reallyHas<std::string(T::*)(), &T::serialize>* /*unused*/) {}
	template<typename T> static yes& test(reallyHas<std::string(T::*)() const, &T::serialize>* /*unused*/) {}

	template<typename T> static no& test(...) {}

	// constant used as return value for the test
	static const bool value = sizeof(test<T>(0)) == sizeof(yes);
};

struct A {};

std::string to_string(const A& a) {
	return "I am an A";
}

struct B {
	std::string serialize() const {
		return "I am a B";
	}
};

struct C {
	std::string serialize;
};

std::string to_string(const C& c) {
	return "I am a C";
}

namespace sw {
	// typeless struct, will always fail substitution
	template<bool b, typename T = void>
	struct enable_if {};

	// specialization for type T
	template<typename T>
	struct enable_if<true, T> {
		using type = T;
	};

	template<typename T>
	typename enable_if<hasSerialize<T>::value, std::string>::type serialize(const T& obj) {
		return obj.serialize();
	}
	template<typename T>
	typename enable_if<!hasSerialize<T>::value, std::string>::type serialize(const T& obj) {
		return to_string(obj);
	}
}

int main(int argc, char** argv)
try {
	using namespace std;
	bool bSuccess = true;

	A a;
	B b;
	C c;

	/* goal
	cout << serialize(a) << endl;
	cout << serialize(b) << endl;
	cout << serialize(c) << endl;
	*/

	cout << hasSerialize<A>::value << endl;
	cout << hasSerialize<B>::value << endl;
	cout << hasSerialize<C>::value << endl;

	// pedantic
	sw::enable_if<true, int>::type t1; // type t1 is an int
	sw::enable_if<hasSerialize<B>::value, int>::type t2; // t2 is an int
	// enable_if<false, int>::type t3;  doesn't compile as enable_if<false, ...> doesn't have a type type
	// enable_if<hasSerialize<A>::value, int>::type t4; doesn't compile as enable_if<false, ...> doesn't have a type type

	// with enable_if we have the indirection to dispatch the right function: serialize or to_string
	cout << sw::serialize(a) << endl;
	cout << sw::serialize(b) << endl;
	cout << sw::serialize(c) << endl;

	return (bSuccess ? EXIT_SUCCESS : EXIT_FAILURE);
}
catch (char const* msg) {
	std::cerr << msg << std::endl;
	return EXIT_FAILURE;
}
catch (const posit_arithmetic_exception& err) {
	std::cerr << "Uncaught posit arithmetic exception: " << err.what() << std::endl;
	return EXIT_FAILURE;
}
catch (const quire_exception& err) {
	std::cerr << "Uncaught quire exception: " << err.what() << std::endl;
	return EXIT_FAILURE;
}
catch (const posit_internal_exception& err) {
	std::cerr << "Uncaught posit internal exception: " << err.what() << std::endl;
	return EXIT_FAILURE;
}
catch (const std::runtime_error& err) {
	std::cerr << "Uncaught runtime exception: " << err.what() << std::endl;
	return EXIT_FAILURE;
}
catch (...) {
	std::cerr << "Caught unknown exception" << std::endl;
	return EXIT_FAILURE;
}
<commit_msg>compilation fix for g++<commit_after>// meta_programming.cpp: playground to experiment with meta programming techniques to generalize functions and algorithms
//
// Copyright (C) 2017-2020 Stillwater Supercomputing, Inc.
//
// This file is part of the universal numbers project, which is released under an MIT Open Source license.
#include "common.hpp"
#include <complex>

// when you define POSIT_VERBOSE_OUTPUT executing an ADD the code will print intermediate results
//#define POSIT_VERBOSE_OUTPUT
#define POSIT_TRACE_CONVERSION
// enable posit arithmetic exceptions
#define POSIT_THROW_ARITHMETIC_EXCEPTION 1
#include <universal/posit/posit>

template<typename T>
struct hasSerialize {
	typedef char yes[1];
	typedef char no[2];

	// helper to determine if serialize is a function
	template<typename U, U function>
	struct reallyHas;

	template<typename S> static yes& test(reallyHas<std::string(S::*)(), &S::serialize>* /*unused*/) {return ' '; }
	template<typename S> static yes& test(reallyHas<std::string(S::*)() const, &S::serialize>* /*unused*/) {return ' '; }

	template<typename> static no& test(...) { return ' ';}

	// constant used as return value for the test
	static const bool value = sizeof(test<T>(0)) == sizeof(yes);
};

struct A {};

std::string to_string(const A& a) {
	return "I am an A";
}

struct B {
	std::string serialize() const {
		return "I am a B";
	}
};

struct C {
	std::string serialize;
};

std::string to_string(const C& c) {
	return "I am a C";
}

namespace sw {
	// typeless struct, will always fail substitution
	template<bool b, typename T = void>
	struct enable_if {};

	// specialization for type T
	template<typename T>
	struct enable_if<true, T> {
		using type = T;
	};

	template<typename T>
	typename enable_if<hasSerialize<T>::value, std::string>::type serialize(const T& obj) {
		return obj.serialize();
	}
	template<typename T>
	typename enable_if<!hasSerialize<T>::value, std::string>::type serialize(const T& obj) {
		return to_string(obj);
	}
}

int main(int argc, char** argv)
try {
	using namespace std;
	bool bSuccess = true;

	A a;
	B b;
	C c;

	/* goal
	cout << serialize(a) << endl;
	cout << serialize(b) << endl;
	cout << serialize(c) << endl;
	*/

	cout << hasSerialize<A>::value << endl;
	cout << hasSerialize<B>::value << endl;
	cout << hasSerialize<C>::value << endl;

	// pedantic
	sw::enable_if<true, int>::type t1; // type t1 is an int
	sw::enable_if<hasSerialize<B>::value, int>::type t2; // t2 is an int
	// to get rid of warnings in g++
	t1 = t2 = 1;
	cout << t1 << t2 << endl;
	// enable_if<false, int>::type t3;  doesn't compile as enable_if<false, ...> doesn't have a type type
	// enable_if<hasSerialize<A>::value, int>::type t4; doesn't compile as enable_if<false, ...> doesn't have a type type

	// with enable_if we have the indirection to dispatch the right function: serialize or to_string
	cout << sw::serialize(a) << endl;
	cout << sw::serialize(b) << endl;
	cout << sw::serialize(c) << endl;

	return (bSuccess ? EXIT_SUCCESS : EXIT_FAILURE);
}
catch (char const* msg) {
	std::cerr << msg << std::endl;
	return EXIT_FAILURE;
}
catch (const posit_arithmetic_exception& err) {
	std::cerr << "Uncaught posit arithmetic exception: " << err.what() << std::endl;
	return EXIT_FAILURE;
}
catch (const quire_exception& err) {
	std::cerr << "Uncaught quire exception: " << err.what() << std::endl;
	return EXIT_FAILURE;
}
catch (const posit_internal_exception& err) {
	std::cerr << "Uncaught posit internal exception: " << err.what() << std::endl;
	return EXIT_FAILURE;
}
catch (const std::runtime_error& err) {
	std::cerr << "Uncaught runtime exception: " << err.what() << std::endl;
	return EXIT_FAILURE;
}
catch (...) {
	std::cerr << "Caught unknown exception" << std::endl;
	return EXIT_FAILURE;
}
<|endoftext|>


<commit_before>#include <ros/ros.h>

//ROS libraries
#include <tf/transform_datatypes.h>

//ROS messages
#include <std_msgs/String.h>
#include <geometry_msgs/Quaternion.h>
#include <geometry_msgs/Twist.h>
#include <sensor_msgs/Imu.h>
#include <sensor_msgs/Range.h>

//Package include
#include <usbSerial.h>

using namespace std;

//aBridge functions
void cmdHandler(const geometry_msgs::Twist::ConstPtr& message);
void serialActivityTimer(const ros::TimerEvent& e);
void publishRosTopics();
void parseData(string data);

//Globals
sensor_msgs::Imu imu;
sensor_msgs::Range sonarLeft;
sensor_msgs::Range sonarCenter;
sensor_msgs::Range sonarRight;
USBSerial usb;
const int baud = 115200;
char dataCmd[] = "d\n";
char moveCmd[16];
char host[128];
char delimiter = ',';
vector<string> dataSet;
float linearSpeed = 0.;
float turnSpeed = 0.;
const float deltaTime = 0.25;

//Publishers
ros::Publisher imuPublish;
ros::Publisher sonarLeftPublish;
ros::Publisher sonarCenterPublish;
ros::Publisher sonarRightPublish;

//Subscribers
ros::Subscriber moveSubscriber;

//Timers
ros::Timer publishTimer;

int main(int argc, char **argv) {

    gethostname(host, sizeof (host));
    string hostname(host);
    string publishedName;
    ros::init(argc, argv, (hostname + "_ABRIDGE"));

    ros::NodeHandle param("~");
    string devicePath;
    param.param("device", devicePath, string("/dev/ttyUSB0"));
    usb.openUSBPort(devicePath, baud);

    sleep(5);

    ros::NodeHandle aNH;

    if (argc >= 2) {
        publishedName = argv[1];
        cout << "Welcome to the world of tomorrow " << publishedName << "!  ABridge module started." << endl;
    } else {
        publishedName = hostname;
        cout << "No Name Selected. Default is: " << publishedName << endl;
    }

    imuPublish = aNH.advertise<sensor_msgs::Imu>((publishedName + "/imu"), 10);
    sonarLeftPublish = aNH.advertise<sensor_msgs::Range>((publishedName + "/sonarLeft"), 10);
    sonarCenterPublish = aNH.advertise<sensor_msgs::Range>((publishedName + "/sonarCenter"), 10);
    sonarRightPublish = aNH.advertise<sensor_msgs::Range>((publishedName + "/sonarRight"), 10);

    moveSubscriber = aNH.subscribe((publishedName + "/mobility"), 10, cmdHandler);

    publishTimer = aNH.createTimer(ros::Duration(deltaTime), serialActivityTimer);

    ros::spin();

    return EXIT_SUCCESS;
}

void cmdHandler(const geometry_msgs::Twist::ConstPtr& message) {
    // remove artificial factor that was multiplied for simulation. this scales it back down to -1.0 to +1.0
    linearSpeed = (message->linear.x) / 1.5;
    turnSpeed = (message->angular.z) / 8;

    if (linearSpeed != 0.) {
        sprintf(moveCmd, "m,%d\n", (int) (linearSpeed * 255));
        usb.sendData(moveCmd);
    } else if (turnSpeed != 0.) {
        sprintf(moveCmd, "t,%d\n", (int) (turnSpeed * 255));
        usb.sendData(moveCmd);
    } else {
        sprintf(moveCmd, "s\n");
        usb.sendData(moveCmd);
    }

    memset(&moveCmd, '\0', sizeof (moveCmd));
}

void serialActivityTimer(const ros::TimerEvent& e) {
    usb.sendData(dataCmd);
    parseData(usb.readData());
    publishRosTopics();
}

void publishRosTopics() {
    sonarLeftPublish.publish(sonarLeft);
    sonarCenterPublish.publish(sonarCenter);
    sonarRightPublish.publish(sonarRight);
    imuPublish.publish(imu);
}

void parseData(string str) {
    istringstream oss(str);
    string word;
    while (getline(oss, word, delimiter)) {
        dataSet.push_back(word);
    }
    if (dataSet.size() == 12) {
        imu.linear_acceleration.x = atof(dataSet.at(0).c_str());
        imu.linear_acceleration.y = atof(dataSet.at(1).c_str());
        imu.linear_acceleration.z = atof(dataSet.at(2).c_str());
        imu.angular_velocity.x = atof(dataSet.at(3).c_str());
        imu.angular_velocity.y = atof(dataSet.at(4).c_str());
        imu.angular_velocity.z = atof(dataSet.at(5).c_str());
        imu.orientation = tf::createQuaternionMsgFromRollPitchYaw(atof(dataSet.at(6).c_str()), atof(dataSet.at(7).c_str()), atof(dataSet.at(8).c_str()));
        sonarLeft.range = atof(dataSet.at(9).c_str()) / 100.0;
        sonarCenter.range = atof(dataSet.at(10).c_str()) / 100.0;
        sonarRight.range = atof(dataSet.at(11).c_str()) / 100.0;
    }

    dataSet.clear();
}
<commit_msg>Implement odometry sensor data processing in abridge package<commit_after>#include <ros/ros.h>

//ROS libraries
#include <tf/transform_datatypes.h>

//ROS messages
#include <std_msgs/String.h>
#include <geometry_msgs/Quaternion.h>
#include <geometry_msgs/Twist.h>
#include <nav_msgs/Odometry.h>
#include <sensor_msgs/Imu.h>
#include <sensor_msgs/Range.h>

//Package include
#include <usbSerial.h>

using namespace std;

//aBridge functions
void cmdHandler(const geometry_msgs::Twist::ConstPtr& message);
void serialActivityTimer(const ros::TimerEvent& e);
void publishRosTopics();
void parseData(string data);

//Globals
sensor_msgs::Imu imu;
nav_msgs::Odometry odom;
sensor_msgs::Range sonarLeft;
sensor_msgs::Range sonarCenter;
sensor_msgs::Range sonarRight;
USBSerial usb;
const int baud = 115200;
char dataCmd[] = "d\n";
char moveCmd[16];
char host[128];
char delimiter = ',';
vector<string> dataSet;
float linearSpeed = 0.;
float turnSpeed = 0.;
const float deltaTime = 0.25;

//Publishers
ros::Publisher imuPublish;
ros::Publisher odomPublish;
ros::Publisher sonarLeftPublish;
ros::Publisher sonarCenterPublish;
ros::Publisher sonarRightPublish;

//Subscribers
ros::Subscriber moveSubscriber;

//Timers
ros::Timer publishTimer;

int main(int argc, char **argv) {

    gethostname(host, sizeof (host));
    string hostname(host);
    string publishedName;
    ros::init(argc, argv, (hostname + "_ABRIDGE"));

    ros::NodeHandle param("~");
    string devicePath;
    param.param("device", devicePath, string("/dev/ttyUSB0"));
    usb.openUSBPort(devicePath, baud);

    sleep(5);

    ros::NodeHandle aNH;

    if (argc >= 2) {
        publishedName = argv[1];
        cout << "Welcome to the world of tomorrow " << publishedName << "!  ABridge module started." << endl;
    } else {
        publishedName = hostname;
        cout << "No Name Selected. Default is: " << publishedName << endl;
    }

    imuPublish = aNH.advertise<sensor_msgs::Imu>((publishedName + "/imu"), 10);
    odomPublish = aNH.advertise<nav_msgs::Odometry>((publishedName + "/odom"), 10);
    sonarLeftPublish = aNH.advertise<sensor_msgs::Range>((publishedName + "/sonarLeft"), 10);
    sonarCenterPublish = aNH.advertise<sensor_msgs::Range>((publishedName + "/sonarCenter"), 10);
    sonarRightPublish = aNH.advertise<sensor_msgs::Range>((publishedName + "/sonarRight"), 10);

    moveSubscriber = aNH.subscribe((publishedName + "/mobility"), 10, cmdHandler);

    publishTimer = aNH.createTimer(ros::Duration(deltaTime), serialActivityTimer);

    ros::spin();

    return EXIT_SUCCESS;
}

void cmdHandler(const geometry_msgs::Twist::ConstPtr& message) {
    // remove artificial factor that was multiplied for simulation. this scales it back down to -1.0 to +1.0
    linearSpeed = (message->linear.x) / 1.5;
    turnSpeed = (message->angular.z) / 8;

    if (linearSpeed != 0.) {
        sprintf(moveCmd, "m,%d\n", (int) (linearSpeed * 255));
        usb.sendData(moveCmd);
    } else if (turnSpeed != 0.) {
        sprintf(moveCmd, "t,%d\n", (int) (turnSpeed * 255));
        usb.sendData(moveCmd);
    } else {
        sprintf(moveCmd, "s\n");
        usb.sendData(moveCmd);
    }

    memset(&moveCmd, '\0', sizeof (moveCmd));
}

void serialActivityTimer(const ros::TimerEvent& e) {
    usb.sendData(dataCmd);
    parseData(usb.readData());
    publishRosTopics();
}

void publishRosTopics() {
	imuPublish.publish(imu);
	odomPublish.publish(odom);
	sonarLeftPublish.publish(sonarLeft);
	sonarCenterPublish.publish(sonarCenter);
	sonarRightPublish.publish(sonarRight);
}

void parseData(string str) {
    istringstream oss(str);
    string word;
    while (getline(oss, word, delimiter)) {
        dataSet.push_back(word);
    }
    if (dataSet.size() == 14) {
        imu.linear_acceleration.x = atof(dataSet.at(0).c_str());
        imu.linear_acceleration.y = atof(dataSet.at(1).c_str());
        imu.linear_acceleration.z = atof(dataSet.at(2).c_str());
        imu.angular_velocity.x = atof(dataSet.at(3).c_str());
        imu.angular_velocity.y = atof(dataSet.at(4).c_str());
        imu.angular_velocity.z = atof(dataSet.at(5).c_str());
        imu.orientation = tf::createQuaternionMsgFromRollPitchYaw(atof(dataSet.at(6).c_str()), atof(dataSet.at(7).c_str()), atof(dataSet.at(8).c_str()));
        odom.pose.pose.position.x = atof(dataSet.at(9).c_str());
        odom.pose.pose.position.y = atof(dataSet.at(10).c_str());
        sonarLeft.range = atof(dataSet.at(11).c_str()) / 100.0;
        sonarCenter.range = atof(dataSet.at(12).c_str()) / 100.0;
        sonarRight.range = atof(dataSet.at(13).c_str()) / 100.0;
    }

    dataSet.clear();
}
<|endoftext|>


<commit_before>/*

Copyright 2015 Armağan Salman

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.

*/

#include <iostream>
#include <stack>
#include <cstdlib>
#include <sstream>
#include <string>

#include "MathematicalExpression.h"

using namespace std;

MathematicalExpression::MathematicalExpression()
{
    this->expression = "";
    this->isResultCalculated = false;
    this->result = 0.0;
}

MathematicalExpression::MathematicalExpression(string expression)
{
    this->expression = expression;
    this->isResultCalculated = false;
    this->result = 0.0;
}

double MathematicalExpression::getResult()
{
    return this->result;
}

void MathematicalExpression::setExpression(string expression)
{
    this->expression = expression;
    this->isResultCalculated = false;
    this->result = 0;
}

double MathematicalExpression::evaluateTerm(char op, double operand1, double operand2)
{
    switch(op)
    {
    case '+':
        return operand1 + operand2;
        break;
    case '-':
        return operand1 - operand2;
        break;
    case '*':
        return operand1 * operand2;
        break;
    case '/':
        return operand1 / operand2;
        break;
    default:
        return 0.0;
    }
}

double MathematicalExpression::evaluate()
{
    string errorMessage = expressionErrorMessage(this->expression);
    if(errorMessage.empty()) // Hata mesaji bossa ifade hatasiz demektir. İslemler gerceklestirilmeli.
    {
        if(isResultCalculated)
        {
            cout << this->expression << " = " << this->result << endl;
            return this->result;
        }
        else
        {
            this->result = this->evaluate(this->expression);
            this->isResultCalculated = true;
            return this->result;
        }
    }
    else // Hata varsa bas.
    {
        cout << errorMessage;
    }
}

double MathematicalExpression::evaluate(string expression)
{
    string errorMessage = expressionErrorMessage(expression);
    if(!errorMessage.empty())
    {
        cout << errorMessage << endl;
        return 0;
    }

    stack<char> symbols;
    stack<double> operands;

    int index = 0;
    char current = 0;
    char *charAfterDouble = NULL;

    char op=0;
    double d1=0,d2=0;
    string temp = "";

    // Her bir karakter icin:
    // Bosluksa atla,
    // '(' ise bir sonraki indisteki operatoru stack'e at,
    // ')' ise sayi stack'inden iki sayi, operator stack'inden bir operator al. Islemi hesapla.
    // Usttekilerden biri degilse sayinin baslangici olmak zorundadır. Sayiyi strtod ile al. strtod'un ikinci parametresi ile sayidan sonraki karaktere eris. Onun indisini bul. Ana indisi bulunan deger yap.
    while(index < expression.length())
    {
        index = skipBlankChars(expression, index);
        current = expression.at(index);
        if(current == '(')
        {
            index++; // reach operand
            symbols.push(expression.at(index));
            index++; // go over operand
            index = this->skipBlankChars(expression, index);
        }
        else if(current == ')')
        {
            op = symbols.top();
            symbols.pop();

            d2 = operands.top();
            operands.pop();

            d1 = operands.top();
            operands.pop();

            operands.push(evaluateTerm(op,d1,d2));

            index++;
        }
        else // Burada sayi oldugunu biliyoruz.
        {
            temp = expression.substr(index);
            operands.push( strtod(temp.c_str(), &charAfterDouble) ); // Find what comes after double value.

            index = expression.find(*charAfterDouble,index); // Go to whatever comes after double value. Could be a space character or ')'
        }
    }
    cout << expression << " = " << operands.top() << endl;
    return operands.top();
}

int MathematicalExpression::skipBlankChars(std::string str, int idx)
{
    for(; isspace(str.at(idx)); idx++)
        ;
    return idx;
}

string MathematicalExpression::expressionErrorMessage(string expr)
{
    int parans = 0;
    int operators = 0;
    int operands = 0;
    const int LENGTH = expr.length();

    char * charAfterNumber;
    ostringstream errorMessage;

    for(int i = 0; i < LENGTH;)
    {
        if(isspace(expr.at(i)))
        {
            i++;
            continue;
        }
        else if(expr.at(i) == '(')
        {
            parans++;
            if( i+1 >= LENGTH || !isOperator(expr.at(i+1)) ) // parantez acimindan sonra operator olmali.
            {
                errorMessage << "Hesaplanamayan expression :\"" << expr << "\" " << i+1 << " indisinde operator yok.";
                return errorMessage.str();
            }

            operators++; // Ustteki return'de cikmadi. Demekki operator var.

            if( i+2 >= LENGTH || !isspace(expr.at(i+2)) ) // parantez acimindan iki karakter sonra bosluk olmali. Standart isspace fonksiyonu kullanildi.
            {
                errorMessage << "Hesaplanamayan expression :\"" << expr << "\" " << i+2 << " indisinde bosluk yok.";
                return errorMessage.str();
            }

            i += 2;
        }
        else if(expr.at(i) == ')')
        {
            parans--;
            operators--;
            operands--; // ki deger kullanip bir deger yazildigindan bir azalmali.
            i++;
        }
        else // Sayi olmali
        {
            if(isOperator(expr.at(i))) // Buraya girerse operatorden once '(' yok demektir.
            {
                errorMessage << "Hesaplanamayan expression :\"" << expr << "\" " << i << " indisindeki operatorden once '(' bekleniyor.";
                return errorMessage.str();
            }

            if( i-1 >= 0 && !isspace(expr.at(i-1))) // Sayidan once bosluk olmali
            {
                errorMessage << "Hesaplanamayan expression :\"" << expr << "\" " << i << " indisindeki sayidan once bosluk bekleniyor.";
                return errorMessage.str();
            }

            strtod(expr.substr(i).c_str(), &charAfterNumber); // Sayiyi parse etmeye calis. Sayidan sonraki karakteri charAfterNumber gostersin.
            if(!isspace(*charAfterNumber) && *charAfterNumber != ')') // Sayidan sonra bosluk veya ')' yoksa hata ver.
            {
                errorMessage << "Hesaplanamayan expression :\"" << expr << "\" " << i << " indisindeki sayidan sonra bosluk veya ')' bekleniyor.";
                return errorMessage.str();
            }
            operands++;
            i = expr.find(*charAfterNumber, i); // Sayidan sonra ilk bulunan bosluk veya ')' ise oraya atla.
        }
    }

    if(parans != 0)
    {
        errorMessage << "Hesaplanamayan expression :\"" << expr << "\" parantez acildigi kadar kapatilmamis.";
        return errorMessage.str();
    }
    else if(operators != 0)
    {
        errorMessage << "Hesaplanamayan expression :\"" << expr << "\" operatorler sifirlanamamis.";
        return errorMessage.str();
    }
    else if(operands != 1) // En sonda stack'te 1 eleman kalmali. O da ifadenin sonuc degeri.
    {
        errorMessage << "Hesaplanamayan expression :\"" << expr << "\" operandlar beklenen sayida degil.";
        return errorMessage.str();
    }
    else // Hata saptanmadi. Bos string don.
    {
        return "";
    }
}

bool MathematicalExpression::isOperator(char c)
{
    return c == '+' || c == '-' || c == '*' || c == '/';
}
<commit_msg>Update MathematicalExpression.cpp<commit_after>/*

Copyright 2015 ArmaÄŸan Salman

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.

*/

#include <iostream>
#include <stack>
#include <cstdlib>
#include <sstream>
#include <string>

#include "MathematicalExpression.h"

using namespace std;

MathematicalExpression::MathematicalExpression()
{
    this->expression = "";
    this->isResultCalculated = false;
    this->result = 0.0;
}

MathematicalExpression::MathematicalExpression(string expression)
{
    this->expression = expression;
    this->isResultCalculated = false;
    this->result = 0.0;
}

double MathematicalExpression::getResult()
{
    return this->result;
}

void MathematicalExpression::setExpression(string expression)
{
    this->expression = expression;
    this->isResultCalculated = false;
    this->result = 0;
}

double MathematicalExpression::evaluateTerm(char op, double operand1, double operand2)
{
    switch(op)
    {
    case '+':
        return operand1 + operand2;
        break;
    case '-':
        return operand1 - operand2;
        break;
    case '*':
        return operand1 * operand2;
        break;
    case '/':
        return operand1 / operand2;
        break;
    default:
        return 0.0;
    }
}

double MathematicalExpression::evaluate()
{
    string errorMessage = expressionErrorMessage(this->expression);
    if(errorMessage.empty()) // Hata mesaji bossa ifade hatasiz demektir. Ä°slemler gerceklestirilmeli.
    {
        if(isResultCalculated)
        {
            cout << this->expression << " = " << this->result << endl;
            return this->result;
        }
        else
        {
            this->result = this->evaluate(this->expression);
            this->isResultCalculated = true;
            return this->result;
        }
    }
    else // Hata varsa bas.
    {
        cout << errorMessage;
    }
}

double MathematicalExpression::evaluate(string expression)
{
    string errorMessage = expressionErrorMessage(expression);
    if(!errorMessage.empty())
    {
        cout << errorMessage << endl;
        return 0;
    }

    stack<char> symbols;
    stack<double> operands;

    int index = 0;
    char current = 0;
    char *charAfterDouble = NULL;

    char op=0;
    double d1=0,d2=0;
    string temp = "";

    // Her bir karakter icin:
    // Bosluksa atla,
    // '(' ise bir sonraki indisteki operatoru stack'e at,
    // ')' ise sayi stack'inden iki sayi, operator stack'inden bir operator al. Islemi hesapla.
    // Usttekilerden biri degilse sayinin baslangici olmak zorundadÄ±r. Sayiyi strtod ile al. strtod'un ikinci parametresi ile sayidan sonraki karaktere eris. Onun indisini bul. Ana indisi bulunan deger yap.
    while(index < expression.length())
    {
        index = skipBlankChars(expression, index);
        current = expression.at(index);
        if(current == '(')
        {
            index++; // reach operand
            symbols.push(expression.at(index));
            index++; // go over operand
            index = this->skipBlankChars(expression, index);
        }
        else if(current == ')')
        {
            op = symbols.top();
            symbols.pop();

            d2 = operands.top();
            operands.pop();

            d1 = operands.top();
            operands.pop();

            operands.push(evaluateTerm(op,d1,d2));

            index++;
        }
        else // Burada sayi oldugunu biliyoruz.
        {
            temp = expression.substr(index);
            operands.push( strtod(temp.c_str(), &charAfterDouble) ); // Find what comes after double value.

            index = expression.find(*charAfterDouble,index); // Go to whatever comes after double value. Could be a space character or ')'
        }
    }
    cout << expression << " = " << operands.top() << endl;
    return operands.top();
}

int MathematicalExpression::skipBlankChars(std::string str, int idx)
{
    for(; isspace(str.at(idx)); idx++)
        ;
    return idx;
}

string MathematicalExpression::expressionErrorMessage(string expr)
{
    int parans = 0;
    int operators = 0;
    int operands = 0;
    const int LENGTH = expr.length();

    char * charAfterNumber;
    ostringstream errorMessage;

    for(int i = 0; i < LENGTH;)
    {
        if(isspace(expr.at(i)))
        {
            i++;
            continue;
        }
        else if(expr.at(i) == '(')
        {
            parans++;
            if( i+1 >= LENGTH || !isOperator(expr.at(i+1)) ) // parantez acimindan sonra operator olmali.
            {
                errorMessage << "Hesaplanamayan expression :\"" << expr << "\" " << i+1 << " indisinde operator yok.";
                return errorMessage.str();
            }

            operators++; // Ustteki return'de cikmadi. Demekki operator var.

            if( i+2 >= LENGTH || !isspace(expr.at(i+2)) ) // parantez acimindan iki karakter sonra bosluk olmali. Standart isspace fonksiyonu kullanildi.
            {
                errorMessage << "Hesaplanamayan expression :\"" << expr << "\" " << i+2 << " indisinde bosluk yok.";
                return errorMessage.str();
            }

            i += 2;
        }
        else if(expr.at(i) == ')')
        {
            parans--;
            operators--;
            operands--; // Ýki deger kullanip bir deger yazildigindan bir azalmali.
            i++;
        }
        else // Sayi olmali
        {
            if(isOperator(expr.at(i))) // Buraya girerse operatorden once '(' yok demektir.
            {
                errorMessage << "Hesaplanamayan expression :\"" << expr << "\" " << i << " indisindeki operatorden once '(' bekleniyor.";
                return errorMessage.str();
            }

            if( i-1 >= 0 && !isspace(expr.at(i-1))) // Sayidan once bosluk olmali
            {
                errorMessage << "Hesaplanamayan expression :\"" << expr << "\" " << i << " indisindeki sayidan once bosluk bekleniyor.";
                return errorMessage.str();
            }

            strtod(expr.substr(i).c_str(), &charAfterNumber); // Sayiyi parse etmeye calis. Sayidan sonraki karakteri charAfterNumber gostersin.
            if(!isspace(*charAfterNumber) && *charAfterNumber != ')') // Sayidan sonra bosluk veya ')' yoksa hata ver.
            {
                errorMessage << "Hesaplanamayan expression :\"" << expr << "\" " << i << " indisindeki sayidan sonra bosluk veya ')' bekleniyor.";
                return errorMessage.str();
            }
            operands++;
            i = expr.find(*charAfterNumber, i); // Sayidan sonra ilk bulunan bosluk veya ')' ise oraya atla.
        }
    }

    if(parans != 0)
    {
        errorMessage << "Hesaplanamayan expression :\"" << expr << "\" parantez acildigi kadar kapatilmamis.";
        return errorMessage.str();
    }
    else if(operators != 0)
    {
        errorMessage << "Hesaplanamayan expression :\"" << expr << "\" operatorler sifirlanamamis.";
        return errorMessage.str();
    }
    else if(operands != 1) // En sonda stack'te 1 eleman kalmali. O da ifadenin sonuc degeri.
    {
        errorMessage << "Hesaplanamayan expression :\"" << expr << "\" operandlar beklenen sayida degil.";
        return errorMessage.str();
    }
    else // Hata saptanmadi. Bos string don.
    {
        return "";
    }
}

bool MathematicalExpression::isOperator(char c)
{
    return c == '+' || c == '-' || c == '*' || c == '/';
}
<|endoftext|>