<commit_before>#include "condor_common.h"

#include <algorithm>
#include "ranger.h"

///// ranger insert/erase/find implementation /////

ranger::iterator ranger::insert(ranger::range r)
{
    // lower_bound here will coalesce an adjacent disjoint range;
    // can use upper_bound instead to avoid this and leave them fractured
    iterator it_start = lower_bound(r._start);
    iterator it = it_start;
    while (it != end() && it->_start <= r._end)  // '<' for no coalesce
        ++it;

    iterator it_end = it;
    if (it_start == it_end)
        return forest.insert(it_end, r);

    if (it_start->contains(r))
        return it_start;

    iterator it_back = --it;
    range rr_new = { std::min(it_start->_start, r._start),
                     std::max(it_back->_end, r._end) };

    // update back of affected range in-place
    it_back->_start = rr_new._start;
    it_back->_end = rr_new._end;

    return it_start == it_back ? it_back : forest.erase(it_start, it_back);
}

ranger::iterator ranger::erase(ranger::range r)
{
    iterator it_start = upper_bound(r._start);
    iterator it = it_start;
    while (it != end() && it->_start < r._end)
        ++it;

    iterator it_end = it;
    if (it_start == it_end)
        return it_start;

    iterator it_back = --it;
    range orig_back = *it_back;

    if (it_start->_start < r._start && r._end < it_start->_end) {
        // split a single range
        it_start->_end = r._start;
        return forest.insert(it_end, range(r._end, orig_back._end));
    }

    if (it_start->_start < r._start) {
        it_start->_end = r._start;
        ++it_start;
    }

    if (r._end < orig_back._end) {
        it_back->_start = r._end;
        --it_end;
    }

    return it_start == it_end ? it_end : forest.erase(it_start, it_end);
}

std::pair<ranger::iterator, bool>
ranger::find(element_type x) const
{
    iterator it = upper_bound(x);
    return {it, it != end() && it->_start <= x};
}

bool ranger::contains(element_type x) const
{
    return find(x).second;
}

ranger::ranger(const std::initializer_list<ranger::range> &il)
{
    for (const range &rr : il)
        insert(rr);
}

// specialize lower_bound / upper_bound based on forest type
static inline std::set<ranger::range>::const_iterator
lower_bounder(const std::set<ranger::range> &f, ranger::range rr)
{
    return f.lower_bound(rr);
}

static inline std::set<ranger::range>::const_iterator
upper_bounder(const std::set<ranger::range> &f, ranger::range rr)
{
    return f.upper_bound(rr);
}

static inline std::vector<ranger::range>::const_iterator
lower_bounder(const std::vector<ranger::range> &f, ranger::range rr)
{
    return std::lower_bound(f.begin(), f.end(), rr);
}

static inline std::vector<ranger::range>::const_iterator
upper_bounder(const std::vector<ranger::range> &f, ranger::range rr)
{
    return std::upper_bound(f.begin(), f.end(), rr);
}

ranger::iterator ranger::lower_bound(element_type x) const
{
    return lower_bounder(forest, x);
}

ranger::iterator ranger::upper_bound(element_type x) const
{
    return upper_bounder(forest, x);
}

///// ranger::elements::iterator implementation /////

/* This allows:
 *
 *      for (int i : myranger.get_elements())
 *          process_int(i);
 *
 *
 * Instead of the still-straightforward:
 *
 *      for (auto &rr : myranger)
 *          for (int i : rr)
 *              process_int(i);
 */

void ranger::elements::iterator::mk_valid()
{
    if (!rit_valid) {
        rit = sit->begin();
        rit_valid = true;
    }
}

ranger::element_type ranger::elements::iterator::operator*()
{
    mk_valid();
    return *rit;
}

ranger::elements::iterator &ranger::elements::iterator::operator++()
{
    mk_valid();
    if (++rit == sit->end()) {
        ++sit;
        rit_valid = false;
    }
    return *this;
}

ranger::elements::iterator &ranger::elements::iterator::operator--()
{
    mk_valid();
    if (rit == sit->begin()) {
        --sit;
        rit = sit->end();
        --rit;
    }
    return *this;
}

bool ranger::elements::iterator::operator==(iterator &it)
{
    if (sit != it.sit)
        return false;
    if (!rit_valid && !it.rit_valid)
        return true;
    // at this point neither sit nor it.sit points to the end() of its set,
    // thus it's OK to call mk_valid() on each, which may dereference *sit
    mk_valid();
    it.mk_valid();
    return rit == it.rit;
}

bool ranger::elements::iterator::operator!=(iterator &it)
{
    return !(*this == it);
}

///// ranger persist/load implementation /////

#include <stdlib.h> // strtol
#include <stdio.h>  // sprintf
#include <string>

/*  persist / load ranger objects
 *
 *  The serialized format is one or more sub-ranges, separated by semicolons,
 *  where each sub-range is either N-M (for inclusive N..M) or N for a single
 *  integer.  Eg, "2", "5-10", "4;7;10-20;44;50-60"
 */

static
void persist_range_single(std::string &s, const ranger::range &rr)
{
    char buf[64];
    int n;
    if (rr._start == rr._end - 1)
        n = sprintf(buf, "%d;", rr._start);
    else
        n = sprintf(buf, "%d-%d;", rr._start, rr._end - 1);
    s.append(buf, n);
}

void persist(std::string &s, const ranger &r)
{
    s.clear();
    if (r.empty())
        return;

    for (auto &rr : r)
        persist_range_single(s, rr);

    s.erase(s.size() - 1);
}

void persist_range(std::string &s, const ranger &r, const ranger::range &rr)
{
    s.clear();
    if (r.empty())
        return;

    auto rit = r.find(rr._start).first;
    for (; rit != r.end() && rit->_start < rr._end; ++rit) {
        ranger::range rr_new = { std::max(rit->_start, rr._start),
                                 std::min(rit->_end,   rr._end) };
        persist_range_single(s, rr_new);
    }

    s.erase(s.size() - 1);
}

void persist_slice(std::string &s, const ranger &r, int start, int back)
{
    persist_range(s, r, {start, back+1});
}

// return 0 on success, (-1 - (position in string)) on parse failure
int load(ranger &r, const char *s)
{
    const char *sstart = s;
    while (*s) {
        char *sp;
        int start = strtol(s, &sp, 10);
        int back;
        if (s == sp)
            // no int parsed is ok as long as we're at the end
            return *s ? -1 - int(s - sstart) : 0;
        s = sp;
        if (*sp == '-') {
            s++;
            back = strtol(s, &sp, 10);
            if (s == sp)
                // a number should have followed '-'
                return -1 - int(s - sstart);
            s = sp;
        } else {
            back = start;
        }
        if (*s == ';')
            s++;
        else if (*s)
            // expected either ';' or end of string
            return -1 - int(s - sstart);
        r.insert({start, back + 1});
    }
    return 0;
}

<commit_msg>only update the affected ends of a range for insert<commit_after>#include "condor_common.h"

#include <algorithm>
#include "ranger.h"

///// ranger insert/erase/find implementation /////

ranger::iterator ranger::insert(ranger::range r)
{
    // lower_bound here will coalesce an adjacent disjoint range;
    // can use upper_bound instead to avoid this and leave them fractured
    iterator it_start = lower_bound(r._start);
    iterator it = it_start;
    while (it != end() && it->_start <= r._end)  // '<' for no coalesce
        ++it;

    iterator it_end = it;
    if (it_start == it_end)
        return forest.insert(it_end, r);

    iterator it_back = --it;
    element_type min_start = std::min(it_start->_start, r._start);

    // update back of affected range in-place
    if (min_start < it_back->_start)
        it_back->_start = min_start;

    if (it_back->_end < r._end)
        it_back->_end = r._end;

    return it_start == it_back ? it_back : forest.erase(it_start, it_back);
}

ranger::iterator ranger::erase(ranger::range r)
{
    iterator it_start = upper_bound(r._start);
    iterator it = it_start;
    while (it != end() && it->_start < r._end)
        ++it;

    iterator it_end = it;
    if (it_start == it_end)
        return it_start;

    iterator it_back = --it;
    range orig_back = *it_back;

    if (it_start->_start < r._start && r._end < it_start->_end) {
        // split a single range
        it_start->_end = r._start;
        return forest.insert(it_end, range(r._end, orig_back._end));
    }

    if (it_start->_start < r._start) {
        it_start->_end = r._start;
        ++it_start;
    }

    if (r._end < orig_back._end) {
        it_back->_start = r._end;
        --it_end;
    }

    return it_start == it_end ? it_end : forest.erase(it_start, it_end);
}

std::pair<ranger::iterator, bool>
ranger::find(element_type x) const
{
    iterator it = upper_bound(x);
    return {it, it != end() && it->_start <= x};
}

bool ranger::contains(element_type x) const
{
    return find(x).second;
}

ranger::ranger(const std::initializer_list<ranger::range> &il)
{
    for (const range &rr : il)
        insert(rr);
}

// specialize lower_bound / upper_bound based on forest type
static inline std::set<ranger::range>::const_iterator
lower_bounder(const std::set<ranger::range> &f, ranger::range rr)
{
    return f.lower_bound(rr);
}

static inline std::set<ranger::range>::const_iterator
upper_bounder(const std::set<ranger::range> &f, ranger::range rr)
{
    return f.upper_bound(rr);
}

static inline std::vector<ranger::range>::const_iterator
lower_bounder(const std::vector<ranger::range> &f, ranger::range rr)
{
    return std::lower_bound(f.begin(), f.end(), rr);
}

static inline std::vector<ranger::range>::const_iterator
upper_bounder(const std::vector<ranger::range> &f, ranger::range rr)
{
    return std::upper_bound(f.begin(), f.end(), rr);
}

ranger::iterator ranger::lower_bound(element_type x) const
{
    return lower_bounder(forest, x);
}

ranger::iterator ranger::upper_bound(element_type x) const
{
    return upper_bounder(forest, x);
}

///// ranger::elements::iterator implementation /////

/* This allows:
 *
 *      for (int i : myranger.get_elements())
 *          process_int(i);
 *
 *
 * Instead of the still-straightforward:
 *
 *      for (auto &rr : myranger)
 *          for (int i : rr)
 *              process_int(i);
 */

void ranger::elements::iterator::mk_valid()
{
    if (!rit_valid) {
        rit = sit->begin();
        rit_valid = true;
    }
}

ranger::element_type ranger::elements::iterator::operator*()
{
    mk_valid();
    return *rit;
}

ranger::elements::iterator &ranger::elements::iterator::operator++()
{
    mk_valid();
    if (++rit == sit->end()) {
        ++sit;
        rit_valid = false;
    }
    return *this;
}

ranger::elements::iterator &ranger::elements::iterator::operator--()
{
    mk_valid();
    if (rit == sit->begin()) {
        --sit;
        rit = sit->end();
        --rit;
    }
    return *this;
}

bool ranger::elements::iterator::operator==(iterator &it)
{
    if (sit != it.sit)
        return false;
    if (!rit_valid && !it.rit_valid)
        return true;
    // at this point neither sit nor it.sit points to the end() of its set,
    // thus it's OK to call mk_valid() on each, which may dereference *sit
    mk_valid();
    it.mk_valid();
    return rit == it.rit;
}

bool ranger::elements::iterator::operator!=(iterator &it)
{
    return !(*this == it);
}

///// ranger persist/load implementation /////

#include <stdlib.h> // strtol
#include <stdio.h>  // sprintf
#include <string>

/*  persist / load ranger objects
 *
 *  The serialized format is one or more sub-ranges, separated by semicolons,
 *  where each sub-range is either N-M (for inclusive N..M) or N for a single
 *  integer.  Eg, "2", "5-10", "4;7;10-20;44;50-60"
 */

static
void persist_range_single(std::string &s, const ranger::range &rr)
{
    char buf[64];
    int n;
    if (rr._start == rr._end - 1)
        n = sprintf(buf, "%d;", rr._start);
    else
        n = sprintf(buf, "%d-%d;", rr._start, rr._end - 1);
    s.append(buf, n);
}

void persist(std::string &s, const ranger &r)
{
    s.clear();
    if (r.empty())
        return;

    for (auto &rr : r)
        persist_range_single(s, rr);

    s.erase(s.size() - 1);
}

void persist_range(std::string &s, const ranger &r, const ranger::range &rr)
{
    s.clear();
    if (r.empty())
        return;

    auto rit = r.find(rr._start).first;
    for (; rit != r.end() && rit->_start < rr._end; ++rit) {
        ranger::range rr_new = { std::max(rit->_start, rr._start),
                                 std::min(rit->_end,   rr._end) };
        persist_range_single(s, rr_new);
    }

    s.erase(s.size() - 1);
}

void persist_slice(std::string &s, const ranger &r, int start, int back)
{
    persist_range(s, r, {start, back+1});
}

// return 0 on success, (-1 - (position in string)) on parse failure
int load(ranger &r, const char *s)
{
    const char *sstart = s;
    while (*s) {
        char *sp;
        int start = strtol(s, &sp, 10);
        int back;
        if (s == sp)
            // no int parsed is ok as long as we're at the end
            return *s ? -1 - int(s - sstart) : 0;
        s = sp;
        if (*sp == '-') {
            s++;
            back = strtol(s, &sp, 10);
            if (s == sp)
                // a number should have followed '-'
                return -1 - int(s - sstart);
            s = sp;
        } else {
            back = start;
        }
        if (*s == ';')
            s++;
        else if (*s)
            // expected either ';' or end of string
            return -1 - int(s - sstart);
        r.insert({start, back + 1});
    }
    return 0;
}

<|endoftext|>


<commit_before>/*
   For more information, please see: http://software.sci.utah.edu

   The MIT License

   Copyright (c) 2008 Scientific Computing and Imaging Institute,
   University of Utah.

   Permission is hereby granted, free of charge, to any person obtaining a
   copy of this software and associated documentation files (the "Software"),
   to deal in the Software without restriction, including without limitation
   the rights to use, copy, modify, merge, publish, distribute, sublicense,
   and/or sell copies of the Software, and to permit persons to whom the
   Software is furnished to do so, subject to the following conditions:

   The above copyright notice and this permission notice shall be included
   in all copies or substantial portions of the Software.

   THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
   OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
   FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
   THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
   LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
   FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
   DEALINGS IN THE SOFTWARE.
*/

/**
  \file    VolumeDataset.cpp
  \author    Jens Krueger
        SCI Institute
        University of Utah
  \date    August 2008
*/

#include "VolumeDataset.h"

VolumeDataset::VolumeDataset(const std::string& strFilename) :
  m_strFilename(strFilename),
  m_pVolumeDatasetInfo(NULL),
  m_pHist1D(NULL),
  m_pHist2D(NULL)
{
  LoadDataset();
  ComputeHistogramms();
}

VolumeDataset::~VolumeDataset()
{
  delete m_pHist1D;
  delete m_pHist2D;
  delete m_pVolumeDatasetInfo;
}

bool VolumeDataset::IsLoaded() const
{
  // TODO
  return true;
}

void VolumeDataset::LoadDataset()
{
  // TODO
  m_pVolumeDatasetInfo = new VolumeDatasetInfo(8);
}

void VolumeDataset::ComputeHistogramms()
{
  // DEBUG CODE
  // generate a random 1D histogram
  m_pHist1D = new Histogram1D(1<<m_pVolumeDatasetInfo->GetBitwith());
  for (size_t i = 0;i<m_pHist1D->GetSize();i++) m_pHist1D->Set(i, (unsigned int)(i+(rand()*10) / RAND_MAX));
  // generate a random 2D histogram
  m_pHist2D = new Histogram2D(VECTOR2<size_t>(1<<m_pVolumeDatasetInfo->GetBitwith(),256));  // TODO: decide: always 8bit gradient ?
  for (size_t y = 0;y<m_pHist2D->GetSize().y;y++)
    for (size_t x = 0;x<m_pHist2D->GetSize().x;x++)
      m_pHist2D->Set(x,y,(unsigned int)(x+(rand()*10) / RAND_MAX)*(unsigned int)(y+(rand()*10) / RAND_MAX));
  // END DEBUG CODE
}
<commit_msg><commit_after>/*
   For more information, please see: http://software.sci.utah.edu

   The MIT License

   Copyright (c) 2008 Scientific Computing and Imaging Institute,
   University of Utah.

   Permission is hereby granted, free of charge, to any person obtaining a
   copy of this software and associated documentation files (the "Software"),
   to deal in the Software without restriction, including without limitation
   the rights to use, copy, modify, merge, publish, distribute, sublicense,
   and/or sell copies of the Software, and to permit persons to whom the
   Software is furnished to do so, subject to the following conditions:

   The above copyright notice and this permission notice shall be included
   in all copies or substantial portions of the Software.

   THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
   OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
   FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
   THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
   LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
   FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
   DEALINGS IN THE SOFTWARE.
*/

/**
  \file    VolumeDataset.cpp
  \author    Jens Krueger
        SCI Institute
        University of Utah
  \date    August 2008
*/

#include "VolumeDataset.h"
#include <cstdlib>

VolumeDataset::VolumeDataset(const std::string& strFilename) :
  m_strFilename(strFilename),
  m_pVolumeDatasetInfo(NULL),
  m_pHist1D(NULL),
  m_pHist2D(NULL)
{
  LoadDataset();
  ComputeHistogramms();
}

VolumeDataset::~VolumeDataset()
{
  delete m_pHist1D;
  delete m_pHist2D;
  delete m_pVolumeDatasetInfo;
}

bool VolumeDataset::IsLoaded() const
{
  // TODO
  return true;
}

void VolumeDataset::LoadDataset()
{
  // TODO
  m_pVolumeDatasetInfo = new VolumeDatasetInfo(8);
}

void VolumeDataset::ComputeHistogramms()
{
  // DEBUG CODE
  // generate a random 1D histogram
  m_pHist1D = new Histogram1D(1<<m_pVolumeDatasetInfo->GetBitwith());
  for (size_t i = 0;i<m_pHist1D->GetSize();i++) m_pHist1D->Set(i, (unsigned int)(i+(rand()*10) / RAND_MAX));
  // generate a random 2D histogram
  m_pHist2D = new Histogram2D(VECTOR2<size_t>(1<<m_pVolumeDatasetInfo->GetBitwith(),256));  // TODO: decide: always 8bit gradient ?
  for (size_t y = 0;y<m_pHist2D->GetSize().y;y++)
    for (size_t x = 0;x<m_pHist2D->GetSize().x;x++)
      m_pHist2D->Set(x,y,(unsigned int)(x+(rand()*10) / RAND_MAX)*(unsigned int)(y+(rand()*10) / RAND_MAX));
  // END DEBUG CODE
}
<|endoftext|>


<commit_before>// Steer TRD QA train for Reconstruction (Clusterizer, Tracking and PID).
//
// Usage:
//   run.C(tasks, files, entries)
//   tasks : "ALL" or one/more of the following:
//     "EFF"  : TRD Tracking Efficiency
//     "EFFC" : TRD Tracking Efficiency Combined (barrel + stand alone) - only in case of simulations
//     "RES"  : TRD tracking Resolution
//     "CAL"  : TRD calibration
//     "PID"  : TRD PID - pion efficiency
//     "PIDR" : TRD PID - reference data
//     "DET"  : Basic TRD Detector checks
//     "NOFR" : Data set does not have AliESDfriends.root
//     "NOMC" : Data set does not have Monte Carlo Informations (real data), so all tasks which rely
//              on MC information are switched off
//
// In compiled mode :
// Don't forget to load first the libraries
// gSystem->Load("libMemStat.so")
// gSystem->Load("libMemStatGui.so")
// gSystem->Load("libANALYSIS.so")
// gSystem->Load("libTRDqaRec.so")
//
// Authors:
//   Alex Bercuci (A.Bercuci@gsi.de)
//   Markus Fasel (m.Fasel@gsi.de)

#ifndef __CINT__
#include <Riostream.h>

#include "TStopwatch.h"
#include "TMemStat.h"
#include "TMemStatViewerGUI.h"

#include "TROOT.h"
#include "TSystem.h"
#include "TError.h"
#include "TChain.h"

#include "AliMagFMaps.h"
#include "AliTracker.h"
#include "AliLog.h"
#include "AliCDBManager.h"
#include "AliAnalysisManager.h"
#include "AliAnalysisDataContainer.h"
#include "AliMCEventHandler.h"
#include "AliESDInputHandler.h"

#include "TRD/AliTRDtrackerV1.h"
#include "TRD/AliTRDcalibDB.h"
#include "TRD/qaRec/AliTRDtrackInfo/AliTRDeventInfo.h"
#include "TRD/qaRec/AliTRDtrackInfoGen.h"
#include "TRD/qaRec/AliTRDtrackingEfficiency.h"
#include "TRD/qaRec/AliTRDtrackingEfficiencyCombined.h"
#include "TRD/qaRec/AliTRDtrackingResolution.h"
#include "TRD/qaRec/AliTRDcalibration.h"
#include "TRD/qaRec/AliTRDpidChecker.h"
#include "TRD/qaRec/AliTRDpidRefMaker.h"
#include "TRD/qaRec/AliTRDcheckDetector.h"
#endif

#include "run.h"

Bool_t MEM = kFALSE;

TChain* CreateESDChain(const char* filename = 0x0, Int_t nfiles=-1 );
void run(Char_t *tasks="ALL", const Char_t *files=0x0, Int_t nmax=-1)
{
  TMemStat *mem = 0x0;
  if(MEM){
    gSystem->Load("libMemStat.so");
    gSystem->Load("libMemStatGui.so");
    mem = new TMemStat("new, gnubuildin");
    mem->AddStamp("Start");
  }

  TStopwatch timer;
  timer.Start();

  if(gSystem->Load("libANALYSIS.so")<0) return;
  if(gSystem->Load("libTRDqaRec.so")<0) return;

  Bool_t fHasMCdata = kTRUE;
  Bool_t fHasFriends = kTRUE;
  TObjArray *tasksArray = TString(tasks).Tokenize(" ");

  Int_t fSteerTask = 0; SETBIT(fSteerTask, kInfoGen);
  for(Int_t isel = 0; isel < tasksArray->GetEntriesFast(); isel++){
    TString s = (dynamic_cast<TObjString *>(tasksArray->UncheckedAt(isel)))->String();
    if(s.CompareTo("ALL") == 0){
      for(Int_t itask = 1; itask < NTRDTASKS; itask++) SETBIT(fSteerTask, itask);
      continue;
    } else if(s.CompareTo("NOFR") == 0){
      fHasFriends = kFALSE;
    } else if(s.CompareTo("NOMC") == 0){
      fHasMCdata = kFALSE;
    } else {
      Bool_t foundOpt = kFALSE;
      for(Int_t itask = 1; itask < NTRDTASKS; itask++){
        if(s.CompareTo(fgkTRDtaskOpt[itask]) != 0) continue;
        SETBIT(fSteerTask, itask);
        foundOpt = kTRUE;
        break;
      }
      if(!foundOpt) Info("run.C", Form("Task %s not implemented (yet).", s.Data()));
    }
  }
  // define task list pointers;
  AliTRDrecoTask *taskPtr[NTRDTASKS], *task = 0x0;
  memset(taskPtr, 0, NTRDTASKS*sizeof(AliAnalysisTask*));

  //____________________________________________//
  //gROOT->LoadMacro(Form("%s/TRD/qaRec/CreateESDChain.C", gSystem->ExpandPathName("$ALICE_ROOT")));
  TChain *chain = CreateESDChain(files, nmax);
  //chain->SetBranchStatus("*", 0);
  chain->SetBranchStatus("*FMD*",0);
  chain->SetBranchStatus("*Calo*",0);
  chain->SetBranchStatus("Tracks", 1);
  chain->SetBranchStatus("ESDfriend*",1);
  chain->Lookup();
  chain->GetListOfFiles()->Print();
  printf("\n ----> CHAIN HAS %d ENTRIES <----\n\n", (Int_t)chain->GetEntries());

  AliLog::SetGlobalLogLevel(AliLog::kError);

  //____________________________________________
  // Make the analysis manager
  AliAnalysisManager *mgr = new AliAnalysisManager("TRD QA Reconstruction Manager");
  //mgr->SetSpecialOutputLocation(source); // To Be Changed
  AliVEventHandler *esdH = 0x0, *mcH = 0x0;
  mgr->SetInputEventHandler(esdH = new AliESDInputHandler);
  if(fHasMCdata) mgr->SetMCtruthEventHandler(mcH = new AliMCEventHandler());
  //mgr->SetDebugLevel(10);

  //____________________________________________
  // TRD track summary generator
  mgr->AddTask(task = new AliTRDtrackInfoGen());
  taskPtr[(Int_t)kInfoGen] = task;
  task->SetDebugLevel(1);
  task->SetMCdata(fHasMCdata);
  // Create containers for input/output
  AliAnalysisDataContainer *cinput1 = mgr->CreateContainer("data", TChain::Class(), AliAnalysisManager::kInputContainer);
  AliAnalysisDataContainer *coutput1 = mgr->CreateContainer("trackInfo", TObjArray::Class(), AliAnalysisManager::kExchangeContainer);
  AliAnalysisDataContainer *coutput1a = mgr->CreateContainer("eventInfo", AliTRDeventInfo::Class(), AliAnalysisManager::kExchangeContainer);
  mgr->ConnectInput( task, 0, cinput1);
  mgr->ConnectOutput(task, 0, coutput1);
  mgr->ConnectOutput(task, 1, coutput1a);

  //____________________________________________
  // TRD detector checker
	if(TESTBIT(fSteerTask, kCheckDetector)){
    mgr->AddTask(task = new AliTRDcheckDetector());
    taskPtr[(Int_t)kCheckDetector] = task;
    task->SetDebugLevel(4);
    task->SetMCdata(fHasMCdata);

    // Create containers for input/output
    mgr->ConnectInput( task, 0, coutput1);
    mgr->ConnectInput( task, 1, coutput1a);
    mgr->ConnectOutput(task, 0, mgr->CreateContainer(task->GetName(), TObjArray::Class(), AliAnalysisManager::kOutputContainer, Form("TRD.Task%s.root", task->GetName())));
  }

  //____________________________________________
  // TRD barrel tracking efficiency
  if(fHasMCdata && TESTBIT(fSteerTask, kTrackingEfficiency)){
    mgr->AddTask(task = new AliTRDtrackingEfficiency());
    taskPtr[(Int_t)kTrackingEfficiency] = task;
    task->SetDebugLevel(0);

    //Create containers for input/output
    mgr->ConnectInput( task, 0, coutput1);
    mgr->ConnectOutput(task, 0, mgr->CreateContainer(task->GetName(), TObjArray::Class(), AliAnalysisManager::kOutputContainer, Form("TRD.Task%s.root", task->GetName())));
  }

  //____________________________________________
  // TRD combined tracking efficiency
  if(fHasMCdata && TESTBIT(fSteerTask, kTrackingCombinedEfficiency)){
    mgr->AddTask(task = new AliTRDtrackingEfficiencyCombined());
    taskPtr[(Int_t)kTrackingCombinedEfficiency] = task;
    task->SetDebugLevel(0);

    // Create containers for input/output
    mgr->ConnectInput( task, 0, coutput1);
    mgr->ConnectOutput(task, 0, mgr->CreateContainer(task->GetName(), TObjArray::Class(), AliAnalysisManager::kOutputContainer, Form("TRD.Task%s.root", task->GetName())));
  }

  //____________________________________________
  // TRD tracking resolution
  if(TESTBIT(fSteerTask, kTrackingResolution)){
    mgr->AddTask(task = new AliTRDtrackingResolution());
    taskPtr[(Int_t)kTrackingResolution] = task;
    task->SetMCdata(fHasMCdata);
    task->SetPostProcess(kFALSE);
    task->SetDebugLevel(1);

    // Create containers for input/output
    mgr->ConnectInput( task, 0, coutput1);
    mgr->ConnectOutput(task, 0, mgr->CreateContainer(task->GetName(), TObjArray::Class(), AliAnalysisManager::kOutputContainer, Form("TRD.Task%s.root", task->GetName())));
  }

  //____________________________________________
  // TRD calibration
  if(TESTBIT(fSteerTask, kCalibration)){
    mgr->AddTask(task = new AliTRDcalibration());
    taskPtr[(Int_t)kCalibration] = task;
    ((AliTRDcalibration*)task)->SetLow(0);
    ((AliTRDcalibration*)task)->SetHigh(30);
    ((AliTRDcalibration*)task)->SetFillZero(kFALSE);
    task->SetDebugLevel(0);

    // Create containers for input/output
    mgr->ConnectInput(task, 0, coutput1);
    mgr->ConnectOutput(task, 0, mgr->CreateContainer(task->GetName(), TObjArray::Class(), AliAnalysisManager::kOutputContainer, Form("TRD.Task%s.root", task->GetName())));
  }

  //____________________________________________
  // TRD pid checker
  if(TESTBIT(fSteerTask, kPIDChecker)){
    mgr->AddTask(task = new AliTRDpidChecker());
    taskPtr[(Int_t)kPIDChecker] = task;
    task->SetDebugLevel(0);
    task->SetMCdata(fHasMCdata);

    // Create containers for input/output
    mgr->ConnectInput( task, 0, coutput1);
    mgr->ConnectOutput(task, 0, mgr->CreateContainer(task->GetName(), TObjArray::Class(), AliAnalysisManager::kOutputContainer, Form("TRD.Task%s.root", task->GetName())));
  }

  //____________________________________________
  // TRD pid reference
  if(TESTBIT(fSteerTask, kPIDRefMaker)){
    mgr->AddTask(task = new AliTRDpidRefMaker());
    taskPtr[(Int_t)kPIDRefMaker] = task;
    task->SetDebugLevel(0);
    task->SetMCdata(fHasMCdata);

    // Create containers for input/output
    mgr->ConnectInput( task, 0, coutput1);
    mgr->ConnectOutput(task, 0, mgr->CreateContainer(task->GetName(), TObjArray::Class(), AliAnalysisManager::kOutputContainer, Form("TRD.Task%s.root", task->GetName())));
    mgr->ConnectOutput(task, 1, mgr->CreateContainer(Form("%sNN", task->GetName()), TTree::Class(), AliAnalysisManager::kOutputContainer, Form("TRD.Task%sNN.root", task->GetName())));
    mgr->ConnectOutput(task, 2, mgr->CreateContainer(Form("%sLQ", task->GetName()), TTree::Class(), AliAnalysisManager::kOutputContainer, Form("TRD.Task%sLQ.root", task->GetName())));
  }

  if (!mgr->InitAnalysis()) return;
  printf("\n\tRUNNING TRAIN FOR TASKS:\n");
  for(Int_t itask = 1; itask < NTRDTASKS; itask++){
    if(TESTBIT(fSteerTask, itask)) printf("\t   %s [%s]\n", taskPtr[itask]->GetTitle(), taskPtr[itask]->GetName());
  }
  printf("\n\n");
  //mgr->PrintStatus();

  AliCDBManager *cdbManager = AliCDBManager::Instance();
  cdbManager->SetDefaultStorage("local://$ALICE_ROOT");
  //cdbManager->SetSpecificStorage("TRD/Calib/FEE","local:///u/bailhach/aliroot/database30head/database");
  cdbManager->SetRun(0);
  cdbManager->SetCacheFlag(kFALSE);

  // initialize TRD settings
  AliMagFMaps *field = new AliMagFMaps("Maps","Maps", 2, 1., 10., AliMagFMaps::k5kG);
  AliTracker::SetFieldMap(field, kTRUE);
  AliTRDcalibDB *cal = AliTRDcalibDB::Instance();
  AliTRDtrackerV1::SetNTimeBins(cal->GetNumberOfTimeBins());

  mgr->StartAnalysis("local",chain);

  timer.Stop();
  timer.Print();

  cal->Terminate();
  delete field;
  delete cdbManager;
  for(Int_t it=NTRDTASKS-1; it>=0; it--) if(taskPtr[it]) delete taskPtr[it];
  if(mcH) delete mcH;
  delete esdH;
  delete mgr;
  delete chain;
  if(MEM) delete mem;
  if(MEM) TMemStatViewerGUI::ShowGUI();
}

TChain* CreateESDChain(const char* filename, Int_t nfiles)
{
  // Create the chain
  TChain* chain = new TChain("esdTree");

  if(!filename){
    chain->Add(Form("%s/AliESDs.root", gSystem->pwd()));
    return chain;
  }

  // read ESD files from the input list.
  ifstream in;
  in.open(filename);
  TString esdfile;
  while(in.good() && (nfiles--) ) {
    in >> esdfile;
    if (!esdfile.Contains("root")) continue; // protection
    chain->Add(esdfile.Data());
  }

  in.close();

  return chain;
}
<commit_msg>move macro TESTBIT to TSTBIT<commit_after>// Steer TRD QA train for Reconstruction (Clusterizer, Tracking and PID).
//
// Usage:
//   run.C(tasks, files, entries)
//   tasks : "ALL" or one/more of the following:
//     "EFF"  : TRD Tracking Efficiency
//     "EFFC" : TRD Tracking Efficiency Combined (barrel + stand alone) - only in case of simulations
//     "RES"  : TRD tracking Resolution
//     "CAL"  : TRD calibration
//     "PID"  : TRD PID - pion efficiency
//     "PIDR" : TRD PID - reference data
//     "DET"  : Basic TRD Detector checks
//     "NOFR" : Data set does not have AliESDfriends.root
//     "NOMC" : Data set does not have Monte Carlo Informations (real data), so all tasks which rely
//              on MC information are switched off
//
// In compiled mode :
// Don't forget to load first the libraries
// gSystem->Load("libMemStat.so")
// gSystem->Load("libMemStatGui.so")
// gSystem->Load("libANALYSIS.so")
// gSystem->Load("libTRDqaRec.so")
//
// Authors:
//   Alex Bercuci (A.Bercuci@gsi.de)
//   Markus Fasel (m.Fasel@gsi.de)

#ifndef __CINT__
#include <Riostream.h>

#include "TStopwatch.h"
#include "TMemStat.h"
#include "TMemStatViewerGUI.h"

#include "TROOT.h"
#include "TSystem.h"
#include "TError.h"
#include "TChain.h"

#include "AliMagFMaps.h"
#include "AliTracker.h"
#include "AliLog.h"
#include "AliCDBManager.h"
#include "AliAnalysisManager.h"
#include "AliAnalysisDataContainer.h"
#include "AliMCEventHandler.h"
#include "AliESDInputHandler.h"

#include "TRD/AliTRDtrackerV1.h"
#include "TRD/AliTRDcalibDB.h"
#include "TRD/qaRec/AliTRDtrackInfo/AliTRDeventInfo.h"
#include "TRD/qaRec/AliTRDtrackInfoGen.h"
#include "TRD/qaRec/AliTRDtrackingEfficiency.h"
#include "TRD/qaRec/AliTRDtrackingEfficiencyCombined.h"
#include "TRD/qaRec/AliTRDtrackingResolution.h"
#include "TRD/qaRec/AliTRDcalibration.h"
#include "TRD/qaRec/AliTRDpidChecker.h"
#include "TRD/qaRec/AliTRDpidRefMaker.h"
#include "TRD/qaRec/AliTRDcheckDetector.h"
#endif

#include "run.h"

Bool_t MEM = kFALSE;

TChain* CreateESDChain(const char* filename = 0x0, Int_t nfiles=-1 );
void run(Char_t *tasks="ALL", const Char_t *files=0x0, Int_t nmax=-1)
{
  TMemStat *mem = 0x0;
  if(MEM){
    gSystem->Load("libMemStat.so");
    gSystem->Load("libMemStatGui.so");
    mem = new TMemStat("new, gnubuildin");
    mem->AddStamp("Start");
  }

  TStopwatch timer;
  timer.Start();

  if(gSystem->Load("libANALYSIS.so")<0) return;
  if(gSystem->Load("libTRDqaRec.so")<0) return;

  Bool_t fHasMCdata = kTRUE;
  Bool_t fHasFriends = kTRUE;
  TObjArray *tasksArray = TString(tasks).Tokenize(" ");

  Int_t fSteerTask = 0; SETBIT(fSteerTask, kInfoGen);
  for(Int_t isel = 0; isel < tasksArray->GetEntriesFast(); isel++){
    TString s = (dynamic_cast<TObjString *>(tasksArray->UncheckedAt(isel)))->String();
    if(s.CompareTo("ALL") == 0){
      for(Int_t itask = 1; itask < NTRDTASKS; itask++) SETBIT(fSteerTask, itask);
      continue;
    } else if(s.CompareTo("NOFR") == 0){
      fHasFriends = kFALSE;
    } else if(s.CompareTo("NOMC") == 0){
      fHasMCdata = kFALSE;
    } else {
      Bool_t foundOpt = kFALSE;
      for(Int_t itask = 1; itask < NTRDTASKS; itask++){
        if(s.CompareTo(fgkTRDtaskOpt[itask]) != 0) continue;
        SETBIT(fSteerTask, itask);
        foundOpt = kTRUE;
        break;
      }
      if(!foundOpt) Info("run.C", Form("Task %s not implemented (yet).", s.Data()));
    }
  }
  // define task list pointers;
  AliTRDrecoTask *taskPtr[NTRDTASKS], *task = 0x0;
  memset(taskPtr, 0, NTRDTASKS*sizeof(AliAnalysisTask*));

  //____________________________________________//
  //gROOT->LoadMacro(Form("%s/TRD/qaRec/CreateESDChain.C", gSystem->ExpandPathName("$ALICE_ROOT")));
  TChain *chain = CreateESDChain(files, nmax);
  //chain->SetBranchStatus("*", 0);
  chain->SetBranchStatus("*FMD*",0);
  chain->SetBranchStatus("*Calo*",0);
  chain->SetBranchStatus("Tracks", 1);
  chain->SetBranchStatus("ESDfriend*",1);
  chain->Lookup();
  chain->GetListOfFiles()->Print();
  printf("\n ----> CHAIN HAS %d ENTRIES <----\n\n", (Int_t)chain->GetEntries());

  AliLog::SetGlobalLogLevel(AliLog::kError);

  //____________________________________________
  // Make the analysis manager
  AliAnalysisManager *mgr = new AliAnalysisManager("TRD QA Reconstruction Manager");
  //mgr->SetSpecialOutputLocation(source); // To Be Changed
  AliVEventHandler *esdH = 0x0, *mcH = 0x0;
  mgr->SetInputEventHandler(esdH = new AliESDInputHandler);
  if(fHasMCdata) mgr->SetMCtruthEventHandler(mcH = new AliMCEventHandler());
  //mgr->SetDebugLevel(10);

  //____________________________________________
  // TRD track summary generator
  mgr->AddTask(task = new AliTRDtrackInfoGen());
  taskPtr[(Int_t)kInfoGen] = task;
  task->SetDebugLevel(1);
  task->SetMCdata(fHasMCdata);
  // Create containers for input/output
  AliAnalysisDataContainer *cinput1 = mgr->CreateContainer("data", TChain::Class(), AliAnalysisManager::kInputContainer);
  AliAnalysisDataContainer *coutput1 = mgr->CreateContainer("trackInfo", TObjArray::Class(), AliAnalysisManager::kExchangeContainer);
  AliAnalysisDataContainer *coutput1a = mgr->CreateContainer("eventInfo", AliTRDeventInfo::Class(), AliAnalysisManager::kExchangeContainer);
  mgr->ConnectInput( task, 0, cinput1);
  mgr->ConnectOutput(task, 0, coutput1);
  mgr->ConnectOutput(task, 1, coutput1a);

  //____________________________________________
  // TRD detector checker
	if(TSTBIT(fSteerTask, kCheckDetector)){
    mgr->AddTask(task = new AliTRDcheckDetector());
    taskPtr[(Int_t)kCheckDetector] = task;
    task->SetDebugLevel(4);
    task->SetMCdata(fHasMCdata);

    // Create containers for input/output
    mgr->ConnectInput( task, 0, coutput1);
    mgr->ConnectInput( task, 1, coutput1a);
    mgr->ConnectOutput(task, 0, mgr->CreateContainer(task->GetName(), TObjArray::Class(), AliAnalysisManager::kOutputContainer, Form("TRD.Task%s.root", task->GetName())));
  }

  //____________________________________________
  // TRD barrel tracking efficiency
  if(fHasMCdata && TSTBIT(fSteerTask, kTrackingEfficiency)){
    mgr->AddTask(task = new AliTRDtrackingEfficiency());
    taskPtr[(Int_t)kTrackingEfficiency] = task;
    task->SetDebugLevel(0);

    //Create containers for input/output
    mgr->ConnectInput( task, 0, coutput1);
    mgr->ConnectOutput(task, 0, mgr->CreateContainer(task->GetName(), TObjArray::Class(), AliAnalysisManager::kOutputContainer, Form("TRD.Task%s.root", task->GetName())));
  }

  //____________________________________________
  // TRD combined tracking efficiency
  if(fHasMCdata && TSTBIT(fSteerTask, kTrackingCombinedEfficiency)){
    mgr->AddTask(task = new AliTRDtrackingEfficiencyCombined());
    taskPtr[(Int_t)kTrackingCombinedEfficiency] = task;
    task->SetDebugLevel(0);

    // Create containers for input/output
    mgr->ConnectInput( task, 0, coutput1);
    mgr->ConnectOutput(task, 0, mgr->CreateContainer(task->GetName(), TObjArray::Class(), AliAnalysisManager::kOutputContainer, Form("TRD.Task%s.root", task->GetName())));
  }

  //____________________________________________
  // TRD tracking resolution
  if(TSTBIT(fSteerTask, kTrackingResolution)){
    mgr->AddTask(task = new AliTRDtrackingResolution());
    taskPtr[(Int_t)kTrackingResolution] = task;
    task->SetMCdata(fHasMCdata);
    task->SetPostProcess(kFALSE);
    task->SetDebugLevel(1);

    // Create containers for input/output
    mgr->ConnectInput( task, 0, coutput1);
    mgr->ConnectOutput(task, 0, mgr->CreateContainer(task->GetName(), TObjArray::Class(), AliAnalysisManager::kOutputContainer, Form("TRD.Task%s.root", task->GetName())));
  }

  //____________________________________________
  // TRD calibration
  if(TSTBIT(fSteerTask, kCalibration)){
    mgr->AddTask(task = new AliTRDcalibration());
    taskPtr[(Int_t)kCalibration] = task;
    ((AliTRDcalibration*)task)->SetLow(0);
    ((AliTRDcalibration*)task)->SetHigh(30);
    ((AliTRDcalibration*)task)->SetFillZero(kFALSE);
    task->SetDebugLevel(0);

    // Create containers for input/output
    mgr->ConnectInput(task, 0, coutput1);
    mgr->ConnectOutput(task, 0, mgr->CreateContainer(task->GetName(), TObjArray::Class(), AliAnalysisManager::kOutputContainer, Form("TRD.Task%s.root", task->GetName())));
  }

  //____________________________________________
  // TRD pid checker
  if(TSTBIT(fSteerTask, kPIDChecker)){
    mgr->AddTask(task = new AliTRDpidChecker());
    taskPtr[(Int_t)kPIDChecker] = task;
    task->SetDebugLevel(0);
    task->SetMCdata(fHasMCdata);

    // Create containers for input/output
    mgr->ConnectInput( task, 0, coutput1);
    mgr->ConnectOutput(task, 0, mgr->CreateContainer(task->GetName(), TObjArray::Class(), AliAnalysisManager::kOutputContainer, Form("TRD.Task%s.root", task->GetName())));
  }

  //____________________________________________
  // TRD pid reference
  if(TSTBIT(fSteerTask, kPIDRefMaker)){
    mgr->AddTask(task = new AliTRDpidRefMaker());
    taskPtr[(Int_t)kPIDRefMaker] = task;
    task->SetDebugLevel(0);
    task->SetMCdata(fHasMCdata);

    // Create containers for input/output
    mgr->ConnectInput( task, 0, coutput1);
    mgr->ConnectOutput(task, 0, mgr->CreateContainer(task->GetName(), TObjArray::Class(), AliAnalysisManager::kOutputContainer, Form("TRD.Task%s.root", task->GetName())));
    mgr->ConnectOutput(task, 1, mgr->CreateContainer(Form("%sNN", task->GetName()), TTree::Class(), AliAnalysisManager::kOutputContainer, Form("TRD.Task%sNN.root", task->GetName())));
    mgr->ConnectOutput(task, 2, mgr->CreateContainer(Form("%sLQ", task->GetName()), TTree::Class(), AliAnalysisManager::kOutputContainer, Form("TRD.Task%sLQ.root", task->GetName())));
  }

  if (!mgr->InitAnalysis()) return;
  printf("\n\tRUNNING TRAIN FOR TASKS:\n");
  for(Int_t itask = 1; itask < NTRDTASKS; itask++){
    if(TSTBIT(fSteerTask, itask)) printf("\t   %s [%s]\n", taskPtr[itask]->GetTitle(), taskPtr[itask]->GetName());
  }
  printf("\n\n");
  //mgr->PrintStatus();

  AliCDBManager *cdbManager = AliCDBManager::Instance();
  cdbManager->SetDefaultStorage("local://$ALICE_ROOT");
  //cdbManager->SetSpecificStorage("TRD/Calib/FEE","local:///u/bailhach/aliroot/database30head/database");
  cdbManager->SetRun(0);
  cdbManager->SetCacheFlag(kFALSE);

  // initialize TRD settings
  AliMagFMaps *field = new AliMagFMaps("Maps","Maps", 2, 1., 10., AliMagFMaps::k5kG);
  AliTracker::SetFieldMap(field, kTRUE);
  AliTRDcalibDB *cal = AliTRDcalibDB::Instance();
  AliTRDtrackerV1::SetNTimeBins(cal->GetNumberOfTimeBins());

  mgr->StartAnalysis("local",chain);

  timer.Stop();
  timer.Print();

  cal->Terminate();
  delete field;
  delete cdbManager;
  for(Int_t it=NTRDTASKS-1; it>=0; it--) if(taskPtr[it]) delete taskPtr[it];
  if(mcH) delete mcH;
  delete esdH;
  delete mgr;
  delete chain;
  if(MEM) delete mem;
  if(MEM) TMemStatViewerGUI::ShowGUI();
}

TChain* CreateESDChain(const char* filename, Int_t nfiles)
{
  // Create the chain
  TChain* chain = new TChain("esdTree");

  if(!filename){
    chain->Add(Form("%s/AliESDs.root", gSystem->pwd()));
    return chain;
  }

  // read ESD files from the input list.
  ifstream in;
  in.open(filename);
  TString esdfile;
  while(in.good() && (nfiles--) ) {
    in >> esdfile;
    if (!esdfile.Contains("root")) continue; // protection
    chain->Add(esdfile.Data());
  }

  in.close();

  return chain;
}
<|endoftext|>


<commit_before>#include <SDL.h>
#include <stdexcept>
#include <string>
#include <iostream>
#include "window.h"

/*
*  Lesson 7: Taking advantage of classes
*/
int main(int argc, char** argv){
    //Start our window
    try {
        Window::Init("Lesson 7");
    }
    catch (const std::runtime_error &e){
        std::cout << e.what() << std::endl;
    }

    //Load up an image
    SDL_Texture *img;
    try {
        std::string file = "../res/Lesson7/image.png";
        img = Window::LoadImage(file);
    }
    catch (const std::runtime_error &e){
        //Catch error and crash
        std::cout << e.what() << std::endl;
        Window::Quit();
        return -1;
    }
    //Set a position to draw it with
    SDL_Rect pos = { Window::Box().w / 2 - 100 / 2,
                     Window::Box().h / 2 - 100 / 2,
                     100, 100 };
    //The angle to draw at, so we can play with it
    int angle = 0;

    //Our event structure
	SDL_Event e;
	//For tracking if we want to quit
	bool quit = false;
	while (!quit){
		//Event Polling
		while (SDL_PollEvent(&e)){
			//If user closes he window
			if (e.type == SDL_QUIT)
				quit = true;
			//If user presses any key
			if (e.type == SDL_KEYDOWN){
				switch (e.key.keysym.sym){
                    //For rotating image
                    case SDLK_d:
                        angle += 2;
                        break;
                    case SDLK_a:
                        angle -= 2;
                        break;
					//For quitting, escape key
					case SDLK_ESCAPE:
						quit = true;
						break;
					default:
						break;
				}
			}
		}
        //RENDERING
        Window::Clear();
        //Draw our image with a 45 degree rotation
        Window::Draw(img, pos, NULL, angle);

        Window::Present();
	}

	return 0;
}<commit_msg>forgot to call Window::Quit() in L7<commit_after>#include <SDL.h>
#include <stdexcept>
#include <string>
#include <iostream>
#include "window.h"

/*
*  Lesson 7: Taking advantage of classes
*/
int main(int argc, char** argv){
    //Start our window
    try {
        Window::Init("Lesson 7");
    }
    catch (const std::runtime_error &e){
        std::cout << e.what() << std::endl;
    }

    //Load up an image
    SDL_Texture *img;
    try {
        std::string file = "../res/Lesson7/image.png";
        img = Window::LoadImage(file);
    }
    catch (const std::runtime_error &e){
        //Catch error and crash
        std::cout << e.what() << std::endl;
        Window::Quit();
        return -1;
    }
    //Set a position to draw it with
    SDL_Rect pos = { Window::Box().w / 2 - 100 / 2,
                     Window::Box().h / 2 - 100 / 2,
                     100, 100 };
    //The angle to draw at, so we can play with it
    int angle = 0;

    //Our event structure
	SDL_Event e;
	//For tracking if we want to quit
	bool quit = false;
	while (!quit){
		//Event Polling
		while (SDL_PollEvent(&e)){
			//If user closes he window
			if (e.type == SDL_QUIT)
				quit = true;
			//If user presses any key
			if (e.type == SDL_KEYDOWN){
				switch (e.key.keysym.sym){
                    //For rotating image
                    case SDLK_d:
                        angle += 2;
                        break;
                    case SDLK_a:
                        angle -= 2;
                        break;
					//For quitting, escape key
					case SDLK_ESCAPE:
						quit = true;
						break;
					default:
						break;
				}
			}
		}
        //RENDERING
        Window::Clear();
        //Draw our image with a 45 degree rotation
        Window::Draw(img, pos, NULL, angle);

        Window::Present();
	}
	Window::Quit();

	return 0;
}<|endoftext|>


<commit_before>/*******************************************************************************
*    ALMA - Atacama Large Millimiter Array
*    (c) European Southern Observatory, 2002
*    Copyright by ESO (in the framework of the ALMA collaboration),
*    All rights reserved
*
*    This library is free software; you can redistribute it and/or
*    modify it under the terms of the GNU Lesser General Public
*    License as published by the Free Software Foundation; either
*    version 2.1 of the License, or (at your option) any later version.
*
*    This library is distributed in the hope that it will be useful,
*    but WITHOUT ANY WARRANTY; without even the implied warranty of
*    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
*    Lesser General Public License for more details.
*
*    You should have received a copy of the GNU Lesser General Public
*    License along with this library; if not, write to the Free Software
*    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307  USA
*
* "@(#) $Id: baciTestServer.cpp,v 1.115 2006/06/21 10:34:11 bjeram Exp $"
*
* who       when      what
* --------  --------  ----------------------------------------------
* msekoran 2002-02-07 Fixed destruction.
* gchiozzi 2002-02-06 Fixed bug in call to DBConnector::initDB()
* gchiozzi 2001-12-19 Added initialisation of standard LoggingProxy fields
*/

static char *rcsId="@(#) $Id: baciTestServer.cpp,v 1.115 2006/06/21 10:34:11 bjeram Exp $";
static void *use_rcsId = ((void)&use_rcsId,(void *) &rcsId);

#include <vltPort.h>
#include <acsutil.h>
#include <acsutilPorts.h>

#include <baci.h>
#include <baciDB.h>

#include "baciTestClassImpl.h"
#include "baciTest.h"
#include "baciTestUtils.h"
#include "baciTestContainerServices.h"

#ifdef MAKE_VXWORKS
#	include <acsutilArgUnpack.h>
#endif

//--------------------------------------
// do not use ACS !
// ACS:: prefix is obligatory for VxWorks
// (for all CORBA objects, object declared in an IDL, e.g. ACS::Callback, maci::Manager)
// NAMESPACE_USE(ACS);
NAMESPACE_USE(baci);

/**
 * Hardcoded !
 */
static int   devCount = 2;
static char *devices[] = {"BACI1","BACI2"};
static bool shutting_down = false;
static bool signaled = false;
static TestContainerServices *cs_p[]={0, 0};
static LoggingProxy *g_logger = 0;

/// The mutual exclusion mechanism which is required to use the
/// <condition_>.
static ACE_SYNCH_MUTEX mutex;

/**
 * Condition used to wait until finalize method has finished
 */
static ACE_SYNCH_CONDITION condition(mutex);

void finalize()
{

    ACS_SHORT_LOG((LM_INFO,"baciTestServer: Destroying CharacteristicComponents."));

	for (int n=0; n < devCount; n++)
	  {

	  try
	    {

	      ACS_SHORT_LOG((LM_INFO,"baciTestServer: Destroying \"%s\"", devices[n]));

	      PortableServer::ObjectId_var id =
		PortableServer::string_to_ObjectId(devices[n]);

	      BACI_CORBA::getPOA()->deactivate_object(id.in());

	    }
	  catch(...)
	    {
	      ACS_SHORT_LOG((LM_INFO,
		     "baciTestServer: Exceptions raised while destroying Component"));
	      // do not bail out just because of one Component destruction failure
	      // ACE_CHECK_RETURN (-1);
	    }

	  }

    ACS_SHORT_LOG((LM_INFO,"baciTestServer: Closing CORBA."));

    try
	{
	  BACI_CORBA::getORB()->shutdown(false);

	}
    catch(CORBA::Exception &ex)
	{
	ACE_PRINT_EXCEPTION(ACE_ANY_EXCEPTION, "finalize");
	}

    if (CDBPropertySet::getInstance() != 0)
	{
	CDBPropertySet * propSet_p = CDBPropertySet::getInstance();
	delete propSet_p;
	}

    ACSError::done();
    DBConnector::closeDB();
    BACI_CORBA::DoneCORBA();

}

void finalizeOtherThread()
{
    if (shutting_down) return;
    shutting_down=true;

    // initialize logger (this is a new thread)
    if (g_logger)
      {
	LoggingProxy::init(g_logger);
	LoggingProxy::ThreadName("finalization");
	ACS_SHORT_LOG((LM_INFO, "Logging proxy successfully created !"));
      }

    finalize();

    sleep(2);
    LoggingProxy::done();
    std::cout << std::flush;

    signaled = true;
    condition.signal();
}

void TerminationSignalHandler(int)
{
    finalizeOtherThread();
}

int main(int argc, char* argv[])
{
    CORBAShutdown::setShutdownFunction(&finalizeOtherThread);
    bool monitoring=true;

    // create logging proxy
    g_logger = new LoggingProxy(0, 0, 31, 0);
    LoggingProxy::init(g_logger);
    LoggingProxy::ProcessName(argv[0]);
    LoggingProxy::ThreadName("main");
    ACS_SHORT_LOG((LM_INFO, "Logging proxy successfully created !"));

    ACS_SHORT_LOG((LM_INFO,"baciTestServer: Starting"));

    if ( argc>=2 )
	{
	monitoring = atoi(argv[1]);
	ACS_SHORT_LOG((LM_INFO,"baciTestServer: monitoring flag: %d passed from cmd line", monitoring));
	}

      // Installs termination signal handlers, to be able
    // to terminate cleanly
    ACS_SHORT_LOG((LM_INFO,"baciTestServer: Installing signal handlers"));
    ACE_OS::signal(SIGINT,  TerminationSignalHandler);  // Ctrl+C
    ACE_OS::signal(SIGTERM, TerminationSignalHandler);  // termination request

     ACS_SHORT_LOG((LM_INFO,"baciTestServer: CharacteristicComponent IDs ready"));
    if (devCount<1) {
       ACS_SHORT_LOG((LM_INFO,"No devices found for %s", argv[0]));
      return -1;
    }

    CORBA::String_var ior[devCount];
    CORBA::String_var name[devCount];
    CORBA::String_var type[devCount];

    int count = 0;

    try {

     BACI_CORBA::InitCORBA(argc, argv);

    if (!ACSError::init (BACI_CORBA::getORB()))
      {
	ACS_LOG(LM_RUNTIME_CONTEXT, "baciTestServer",
		(LM_INFO, "Failed to initialize ACSError."));
	return -1;
      }

    // read parameters
    ACS_SHORT_LOG((LM_INFO,"baciTestServer: Init DB"));
    if (!DBConnector::initDB(":Appl_data:alma", argc, argv, BACI_CORBA::getORB()))
      {
	ACS_SHORT_LOG((LM_INFO,"Error creating DB..."));
	return -1;
      }

     // Instantiate the CBDPropertySet singleton
     if (DBConnector::getDBTable())
	 CDBPropertySet::createInstance(BACI_CORBA::getORB(),
					BACI_CORBA::getPOAManager(),
					BACI_CORBA::getPOARoot());

     for (int n=0; n < devCount; n++) {

        ACS_SHORT_LOG((LM_INFO,"baciTestServer: Exporting \"%s\"", devices[n]));

	ACE_CString compName = devices[n];

	cs_p[n] = new TestContainerServices(compName,
					 BACI_CORBA::getPOA(), BACI_CORBA::getORB());

        BaciTestClassImpl* ps = new BaciTestClassImpl(devices[n],
						      cs_p[n],
						      monitoring);

	CORBA::Object_var ps_obj = BACI_CORBA::ActivateCORBAObject(ps, devices[n]);
	if (CORBA::is_nil(ps_obj.in()))
	  {
	    ACS_SHORT_LOG((LM_ERROR,"baciTestServer: Failed to activate \"%s\"", devices[n]));
	    delete ps;
	    delete cs_p[n];
	    finalize();
	    throw CORBA::NO_RESOURCES();
	  }

	// remove reference to servant, so that only POA nows owns it
	// when POA will release servent's reference, ref.
        // count will drop to 0 and servant will be deleted
	ps->_remove_ref();

        ior[count] = BACI_CORBA::getORB()->object_to_string (ps_obj.in());

        name[count] = CORBA::string_dup(devices[n]);
        type[count] = CORBA::string_dup("BaciTestClass");
        count++;

        ACS_SHORT_LOG((LM_INFO, "baciTestServer: %s exported", devices[n]));

      }
    }
    catch (...) {
      ACS_SHORT_LOG((LM_INFO, "baciTestServer: Exceptions raised while creating Component"));
      return -1;
      //ACE_CHECK_RETURN (-1);
    }
    ACS_SHORT_LOG((LM_INFO,"baciTestServer: Writing IORS to file..."));

    write_iors_to_file(count, name, type, ior);

    ACS_SHORT_LOG((LM_INFO,"baciTestServer: Running ORB."));
    BACI_CORBA::getORB()->run();

    // check if already shut down using signals
    if (shutting_down)
      {
        // "strange" thing, if server is killed using
        // 'killall SIGTERM baciTestServer' it causes call of signal handles,
        // but if CTRL-C is pressed all threads receive signal
        // (including CORBA ORB main thread) and run() method terminates
        // this makes the main program to terminate before initialization() is done
        if (!signaled) condition.wait();
      }
    else
	finalize();

    LoggingProxy::done();
    std::cout << std::flush;

    return 0;
}

#ifdef MAKE_VXWORKS

int startBaciTestServer(char *szCmdLn)
{
  int  argc;
  char *argv[100];

  ACE_OS_Object_Manager ace_os_object_manager;
  ACE_Object_Manager ace_object_manager;

  //ACE_MAIN_OBJECT_MANAGER
  argc = argUnpack(szCmdLn, argv);
  argv[0] = "baciTestServer";

  int retval = ace_main_i(argc, argv);

  return retval;
}

#endif

<commit_msg>made some modification for VxWorks<commit_after>/*******************************************************************************
*    ALMA - Atacama Large Millimiter Array
*    (c) European Southern Observatory, 2002
*    Copyright by ESO (in the framework of the ALMA collaboration),
*    All rights reserved
*
*    This library is free software; you can redistribute it and/or
*    modify it under the terms of the GNU Lesser General Public
*    License as published by the Free Software Foundation; either
*    version 2.1 of the License, or (at your option) any later version.
*
*    This library is distributed in the hope that it will be useful,
*    but WITHOUT ANY WARRANTY; without even the implied warranty of
*    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
*    Lesser General Public License for more details.
*
*    You should have received a copy of the GNU Lesser General Public
*    License along with this library; if not, write to the Free Software
*    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307  USA
*
* "@(#) $Id: baciTestServer.cpp,v 1.116 2006/06/26 15:55:13 bjeram Exp $"
*
* who       when      what
* --------  --------  ----------------------------------------------
* msekoran 2002-02-07 Fixed destruction.
* gchiozzi 2002-02-06 Fixed bug in call to DBConnector::initDB()
* gchiozzi 2001-12-19 Added initialisation of standard LoggingProxy fields
*/

static char *rcsId="@(#) $Id: baciTestServer.cpp,v 1.116 2006/06/26 15:55:13 bjeram Exp $";
static void *use_rcsId = ((void)&use_rcsId,(void *) &rcsId);

#include <vltPort.h>
#include <acsutil.h>
#include <acsutilPorts.h>

#include <baci.h>
#include <baciDB.h>

#include "baciTestClassImpl.h"
#include "baciTest.h"
#include "baciTestUtils.h"
#include "baciTestContainerServices.h"

#ifdef MAKE_VXWORKS
#	include <acsutilArgUnpack.h>
#endif

//--------------------------------------
// do not use ACS !
// ACS:: prefix is obligatory for VxWorks
// (for all CORBA objects, object declared in an IDL, e.g. ACS::Callback, maci::Manager)
// NAMESPACE_USE(ACS);
NAMESPACE_USE(baci);

/**
 * Hardcoded !
 */
static int   devCount = 2;
static char *devices[] = {"BACI1","BACI2"};
static bool shutting_down = false;
static bool signaled = false;
static TestContainerServices *cs_p[]={0, 0};
static LoggingProxy *g_logger = 0;

/// The mutual exclusion mechanism which is required to use the
/// <condition_>.
static ACE_SYNCH_MUTEX mutex;

/**
 * Condition used to wait until finalize method has finished
 */
static ACE_SYNCH_CONDITION condition(mutex);

void finalize()
{

    ACS_SHORT_LOG((LM_INFO,"baciTestServer: Destroying CharacteristicComponents."));

	for (int n=0; n < devCount; n++)
	  {

	  try
	    {

	      ACS_SHORT_LOG((LM_INFO,"baciTestServer: Destroying \"%s\"", devices[n]));

	      PortableServer::ObjectId_var id =
		PortableServer::string_to_ObjectId(devices[n]);

	      BACI_CORBA::getPOA()->deactivate_object(id.in());

	    }
	  catch(...)
	    {
	      ACS_SHORT_LOG((LM_INFO,
		     "baciTestServer: Exceptions raised while destroying Component"));
	      // do not bail out just because of one Component destruction failure
	      // ACE_CHECK_RETURN (-1);
	    }

	  }

    ACS_SHORT_LOG((LM_INFO,"baciTestServer: Closing CORBA."));

    try
	{
	  BACI_CORBA::getORB()->shutdown(false);

	}
    catch(CORBA::Exception &ex)
	{
	ACE_PRINT_EXCEPTION(ACE_ANY_EXCEPTION, "finalize");
	}

    if (CDBPropertySet::getInstance() != 0)
	{
	CDBPropertySet * propSet_p = CDBPropertySet::getInstance();
	delete propSet_p;
	}

    ACSError::done();
    DBConnector::closeDB();
    BACI_CORBA::DoneCORBA();

}

void finalizeOtherThread()
{
    if (shutting_down) return;
    shutting_down=true;

    // initialize logger (this is a new thread)
    if (g_logger)
      {
	LoggingProxy::init(g_logger);
	LoggingProxy::ThreadName("finalization");
	ACS_SHORT_LOG((LM_INFO, "Logging proxy successfully created !"));
      }

    finalize();

    sleep(2);
    LoggingProxy::done();
    std::cout << std::flush;

    signaled = true;
    condition.signal();
}

void TerminationSignalHandler(int)
{
    finalizeOtherThread();
}

#ifdef MAKE_VXWORKS

int startBaciTestServer(char *szCmdLn)
{
  int  argc;
  char *argv[100];

  ACE_OS_Object_Manager ace_os_object_manager;
  ACE_Object_Manager ace_object_manager;

  argc = argUnpack(szCmdLn, argv);
  argv[0] = "baciTestServer";

#else
int main(int argc, char* argv[])
{
#endif

    CORBAShutdown::setShutdownFunction(&finalizeOtherThread);
    bool monitoring=true;

    // create logging proxy
    g_logger = new LoggingProxy(0, 0, 31, 0);
    LoggingProxy::init(g_logger);
    LoggingProxy::ProcessName(argv[0]);
    LoggingProxy::ThreadName("main");
    ACS_SHORT_LOG((LM_INFO, "Logging proxy successfully created !"));

    ACS_SHORT_LOG((LM_INFO,"baciTestServer: Starting"));

    if ( argc>=2 )
	{
	monitoring = atoi(argv[1]);
	ACS_SHORT_LOG((LM_INFO,"baciTestServer: monitoring flag: %d passed from cmd line", monitoring));
	}

      // Installs termination signal handlers, to be able
    // to terminate cleanly
    ACS_SHORT_LOG((LM_INFO,"baciTestServer: Installing signal handlers"));
    ACE_OS::signal(SIGINT,  TerminationSignalHandler);  // Ctrl+C
    ACE_OS::signal(SIGTERM, TerminationSignalHandler);  // termination request

     ACS_SHORT_LOG((LM_INFO,"baciTestServer: CharacteristicComponent IDs ready"));
    if (devCount<1) {
       ACS_SHORT_LOG((LM_INFO,"No devices found for %s", argv[0]));
      return -1;
    }

    CORBA::String_var ior[devCount];
    CORBA::String_var name[devCount];
    CORBA::String_var type[devCount];

    int count = 0;

    try {

     BACI_CORBA::InitCORBA(argc, argv);

    if (!ACSError::init (BACI_CORBA::getORB()))
      {
	ACS_LOG(LM_RUNTIME_CONTEXT, "baciTestServer",
		(LM_INFO, "Failed to initialize ACSError."));
	return -1;
      }

    // read parameters
    ACS_SHORT_LOG((LM_INFO,"baciTestServer: Init DB"));
    if (!DBConnector::initDB(":Appl_data:alma", argc, argv, BACI_CORBA::getORB()))
      {
	ACS_SHORT_LOG((LM_INFO,"Error creating DB..."));
	return -1;
      }

     // Instantiate the CBDPropertySet singleton
     if (DBConnector::getDBTable())
	 CDBPropertySet::createInstance(BACI_CORBA::getORB(),
					BACI_CORBA::getPOAManager(),
					BACI_CORBA::getPOARoot());

     for (int n=0; n < devCount; n++) {

        ACS_SHORT_LOG((LM_INFO,"baciTestServer: Exporting \"%s\"", devices[n]));

	ACE_CString compName = devices[n];

	cs_p[n] = new TestContainerServices(compName,
					 BACI_CORBA::getPOA(), BACI_CORBA::getORB());

        BaciTestClassImpl* ps = new BaciTestClassImpl(devices[n],
						      cs_p[n],
						      monitoring);

	CORBA::Object_var ps_obj = BACI_CORBA::ActivateCORBAObject(ps, devices[n]);
	if (CORBA::is_nil(ps_obj.in()))
	  {
	    ACS_SHORT_LOG((LM_ERROR,"baciTestServer: Failed to activate \"%s\"", devices[n]));
	    delete ps;
	    delete cs_p[n];
	    finalize();
	    throw CORBA::NO_RESOURCES();
	  }

	// remove reference to servant, so that only POA nows owns it
	// when POA will release servent's reference, ref.
        // count will drop to 0 and servant will be deleted
	ps->_remove_ref();

        ior[count] = BACI_CORBA::getORB()->object_to_string (ps_obj.in());

        name[count] = CORBA::string_dup(devices[n]);
        type[count] = CORBA::string_dup("BaciTestClass");
        count++;

        ACS_SHORT_LOG((LM_INFO, "baciTestServer: %s exported", devices[n]));

      }
    }
    catch (...) {
      ACS_SHORT_LOG((LM_INFO, "baciTestServer: Exceptions raised while creating Component"));
      return -1;
      //ACE_CHECK_RETURN (-1);
    }
    ACS_SHORT_LOG((LM_INFO,"baciTestServer: Writing IORS to file..."));

    write_iors_to_file(count, name, type, ior);

    ACS_SHORT_LOG((LM_INFO,"baciTestServer: Running ORB."));
    BACI_CORBA::getORB()->run();

    // check if already shut down using signals
    if (shutting_down)
      {
        // "strange" thing, if server is killed using
        // 'killall SIGTERM baciTestServer' it causes call of signal handles,
        // but if CTRL-C is pressed all threads receive signal
        // (including CORBA ORB main thread) and run() method terminates
        // this makes the main program to terminate before initialization() is done
        if (!signaled) condition.wait();
      }
    else
	finalize();

    LoggingProxy::done();
    std::cout << std::flush;

    return 0;
}

<|endoftext|>


<commit_before>#include <iostream>
#include "LinearRegression.h"
#include "Utils.h"

using namespace std;

LinearRegression::LinearRegression(double x[], double y[], int m)
{
    this->x = x;
    this->y = y;
    this->m = m;
}

void LinearRegression::train(double alpha, int iterations)
{
    double *J = new double[iterations];
    this->theta = gradient_descent(x, y, alpha, iterations, J, m);

}

double LinearRegression::predict(double x)
{
    return h(x, theta);
}

double LinearRegression::compute_cost(double x[], double y[], double theta[], int m)
{
    double *predictions = calculate_predictions(x, theta, m);
    double *diff = Utils::array_diff(predictions, y, m);
    double *sq_errors = Utils::array_pow(diff, m, 2);
    return (1.0 / (2 * m)) * Utils::array_sum(sq_errors, m);
}

double LinearRegression::h(double x, double theta[])
{
    return theta[0] + theta[1] * x;
}

double *LinearRegression::calculate_predictions(double x[], double theta[], int m)
{
    double *predictions = new double[m];

    // calculate h for each training example
    for (int i = 0; i < m; ++i) {
        predictions[i] = h(x[i], theta);
    }

    return predictions;
}

double *LinearRegression::gradient_descent(double x[], double y[], double alpha, int iters, double *J, int m)
{
    double *theta = new double[2];
    theta[0] = 1;
    theta[1] = 1;

    for (int i = 0; i < iters; ++i)
    {
        double *predictions = calculate_predictions(x, theta, m);
        double *diff = Utils::array_diff(predictions, y, m);

        double *errors_x1 = diff;
        double *errors_x2 = Utils::array_multiplication(diff, x, m);

        theta[0] = theta[0] - alpha * (1.0 / m) * Utils::array_sum(errors_x1, m);
        theta[1] = theta[1] - alpha * (1.0 / m) * Utils::array_sum(errors_x2, m);

        J[i] = compute_cost(x, y, theta, m);
    }

    return theta;
}
<commit_msg>Memory Leaks Fixed for  Multiple Iterations<commit_after>#include <iostream>
#include "LinearRegression.h"
#include "Utils.h"

using namespace std;

LinearRegression::LinearRegression(double x[], double y[], int m)
{
    this->x = x;
    this->y = y;
    this->m = m;
}

void LinearRegression::train(double alpha, int iterations)
{
    double *J = new double[iterations];
    this->theta = gradient_descent(x, y, alpha, iterations, J, m);
    delete J;
}

double LinearRegression::predict(double x)
{
    return h(x, theta);
}

double LinearRegression::compute_cost(double x[], double y[], double theta[], int m)
{
    double *predictions = calculate_predictions(x, theta, m);
    double *diff = Utils::array_diff(predictions, y, m);
    double *sq_errors = Utils::array_pow(diff, m, 2);
    delete predictions,diff;
    return (1.0 / (2 * m)) * Utils::array_sum(sq_errors, m);
}

double LinearRegression::h(double x, double theta[])
{
    return theta[0] + theta[1] * x;
}

double *LinearRegression::calculate_predictions(double x[], double theta[], int m)
{
    double *predictions = new double[m];

    // calculate h for each training example
    for (int i = 0; i < m; ++i) {
        predictions[i] = h(x[i], theta);
    }

    return predictions;
}

double *LinearRegression::gradient_descent(double x[], double y[], double alpha, int iters, double *J, int m)
{
    double *theta = new double[2];
    theta[0] = 1;
    theta[1] = 1;

    for (int i = 0; i < iters; ++i)
    {
        double *predictions = calculate_predictions(x, theta, m);
        double *diff = Utils::array_diff(predictions, y, m);

        double *errors_x1 = diff;
        double *errors_x2 = Utils::array_multiplication(diff, x, m);

        theta[0] = theta[0] - alpha * (1.0 / m) * Utils::array_sum(errors_x1, m);
        theta[1] = theta[1] - alpha * (1.0 / m) * Utils::array_sum(errors_x2, m);

        J[i] = compute_cost(x, y, theta, m);
    }

    return theta;
}
<|endoftext|>


<commit_before>/*
 * Copyright 2001,2004 The Apache Software Foundation.
 *
 * 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.
 */

/*
 * $Id$
 * $Log$
 * Revision 1.12  2004/09/08 13:56:52  peiyongz
 * Apache License Version 2.0
 *
 * Revision 1.11  2003/12/23 21:50:36  peiyongz
 * Absorb exception thrown in getCanonicalRepresentation and return 0,
 * only validate when required
 *
 * Revision 1.10  2003/12/17 00:18:38  cargilld
 * Update to memory management so that the static memory manager (one used to call Initialize) is only for static data.
 *
 * Revision 1.9  2003/12/11 21:40:24  peiyongz
 * support for Canonical Representation for Datatype
 *
 * Revision 1.8  2003/11/28 18:53:07  peiyongz
 * Support for getCanonicalRepresentation
 *
 * Revision 1.7  2003/11/12 20:32:03  peiyongz
 * Statless Grammar: ValidationContext
 *
 * Revision 1.6  2003/10/02 19:21:06  peiyongz
 * Implementation of Serialization/Deserialization
 *
 * Revision 1.5  2003/05/15 18:53:26  knoaman
 * Partial implementation of the configurable memory manager.
 *
 * Revision 1.4  2003/02/02 23:55:40  peiyongz
 * getFormattedString() added to return original and converted value.
 *
 * Revision 1.3  2003/01/30 21:56:22  tng
 * Performance: call getRawData instead of toString
 *
 * Revision 1.2  2002/11/04 14:53:27  tng
 * C++ Namespace Support.
 *
 * Revision 1.1.1.1  2002/02/01 22:22:39  peiyongz
 * sane_include
 *
 * Revision 1.2  2001/10/09 21:16:31  peiyongz
 * . macro to simplify code
 *
 * Revision 1.1  2001/10/01 16:13:56  peiyongz
 * DTV Reorganization:new classes: AbstractNumericFactValidator/ AbstractNumericValidator
 *
 */

// ---------------------------------------------------------------------------
//  Includes
// ---------------------------------------------------------------------------
#include <xercesc/validators/datatype/AbstractNumericValidator.hpp>
#include <xercesc/validators/datatype/InvalidDatatypeValueException.hpp>
#include <xercesc/util/XMLAbstractDoubleFloat.hpp>

XERCES_CPP_NAMESPACE_BEGIN

#define  REPORT_VALUE_ERROR(val1, val2, except_code, manager)    \
  ThrowXMLwithMemMgr2(InvalidDatatypeValueException               \
          , except_code                                 \
          , val1->getFormattedString()                  \
          , val2->getFormattedString()                  \
          , manager);

// ---------------------------------------------------------------------------
//  Constructors and Destructor
// ---------------------------------------------------------------------------
AbstractNumericValidator::~AbstractNumericValidator()
{}

AbstractNumericValidator::AbstractNumericValidator(
                          DatatypeValidator*            const baseValidator
                        , RefHashTableOf<KVStringPair>* const facets
                        , const int                           finalSet
                        , const ValidatorType                 type
                        , MemoryManager* const                manager)
:AbstractNumericFacetValidator(baseValidator, facets, finalSet, type, manager)
{
    //do not invoke init() here !!!
}

void AbstractNumericValidator::validate(const XMLCh*             const content
                                       ,      ValidationContext* const context
                                       ,      MemoryManager*     const manager)
{
    checkContent(content, context, false, manager);
}

void AbstractNumericValidator::boundsCheck(const XMLNumber*         const theData
                                          ,      MemoryManager*     const manager)
{
    int thisFacetsDefined = getFacetsDefined();
    int result;

    try
    {

        // must be < MaxExclusive
        if ( (thisFacetsDefined & DatatypeValidator::FACET_MAXEXCLUSIVE) != 0 )
        {
            result = compareValues(theData, getMaxExclusive());
            if ( result != -1)
            {
                REPORT_VALUE_ERROR(theData
                                 , getMaxExclusive()
                                 , XMLExcepts::VALUE_exceed_maxExcl
                                 , manager)
            }
        }

        // must be <= MaxInclusive
        if ( (thisFacetsDefined & DatatypeValidator::FACET_MAXINCLUSIVE) != 0 )
        {
            result = compareValues(theData, getMaxInclusive());
            if (result == 1)
            {
                REPORT_VALUE_ERROR(theData
                                 , getMaxInclusive()
                                 , XMLExcepts::VALUE_exceed_maxIncl
                                 , manager)
            }
        }

        // must be >= MinInclusive
        if ( (thisFacetsDefined & DatatypeValidator::FACET_MININCLUSIVE) != 0 )
        {
            result = compareValues(theData, getMinInclusive());
            if (result == -1)
            {
                REPORT_VALUE_ERROR(theData
                                 , getMinInclusive()
                                 , XMLExcepts::VALUE_exceed_minIncl
                                 , manager)
            }
        }

        // must be > MinExclusive
        if ( (thisFacetsDefined & DatatypeValidator::FACET_MINEXCLUSIVE) != 0 )
        {
            result = compareValues(theData, getMinExclusive());
            if (result != 1)
            {
                REPORT_VALUE_ERROR(theData
                                 , getMinExclusive()
                                 , XMLExcepts::VALUE_exceed_minExcl
                                 , manager)
            }
        }
    }
    catch (XMLException &e)
    {
       ThrowXMLwithMemMgr1(InvalidDatatypeValueException, XMLExcepts::RethrowError, e.getMessage(), manager);
    }

}

const XMLCh* AbstractNumericValidator::getCanonicalRepresentation(const XMLCh*         const rawData
                                                                 ,      MemoryManager* const memMgr
                                                                 ,      bool                 toValidate) const
{
    MemoryManager* toUse = memMgr? memMgr : fMemoryManager;

    if (toValidate)
    {
        AbstractNumericValidator* temp = (AbstractNumericValidator*) this;

        try
        {
            temp->checkContent(rawData, 0, false, toUse);
        }
        catch (...)
        {
            return 0;
        }
    }

    // XMLAbstractDoubleFloat::getCanonicalRepresentation handles
    // exceptional cases
    return XMLAbstractDoubleFloat::getCanonicalRepresentation(rawData, toUse);

}

/***
 * Support for Serialization/De-serialization
 ***/

IMPL_XSERIALIZABLE_NOCREATE(AbstractNumericValidator)

void AbstractNumericValidator::serialize(XSerializeEngine& serEng)
{
    AbstractNumericFacetValidator::serialize(serEng);

    /***
     * Need not to do anything else here
     *
     * Note: its derivatives, Doubledv, Floatdv and Decimaldv writes
     *       number type info into the binary data stream to be read
     *       by AbstractNumericFacetVaildator during loading, therefore
     *       this class can NOT write/read anything into/from the binary
     *       data stream.
     *
     *       Later on, if this class has to write/read something into/from
     *       the binary data stream, we need to add a numberType data
     *       to XMLNumber and let AbstractNumericFacetValidator to write/read
     *       this number type info.
     ***/
}

XERCES_CPP_NAMESPACE_END

/**
  * End of file AbstractNumericValidator::cpp
  */

<commit_msg>Minor code cleanup.<commit_after>/*
 * Copyright 2001,2004 The Apache Software Foundation.
 *
 * 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.
 */

/*
 * $Id$
 * $Log$
 * Revision 1.13  2004/12/01 17:44:20  cargilld
 * Minor code cleanup.
 *
 * Revision 1.12  2004/09/08 13:56:52  peiyongz
 * Apache License Version 2.0
 *
 * Revision 1.11  2003/12/23 21:50:36  peiyongz
 * Absorb exception thrown in getCanonicalRepresentation and return 0,
 * only validate when required
 *
 * Revision 1.10  2003/12/17 00:18:38  cargilld
 * Update to memory management so that the static memory manager (one used to call Initialize) is only for static data.
 *
 * Revision 1.9  2003/12/11 21:40:24  peiyongz
 * support for Canonical Representation for Datatype
 *
 * Revision 1.8  2003/11/28 18:53:07  peiyongz
 * Support for getCanonicalRepresentation
 *
 * Revision 1.7  2003/11/12 20:32:03  peiyongz
 * Statless Grammar: ValidationContext
 *
 * Revision 1.6  2003/10/02 19:21:06  peiyongz
 * Implementation of Serialization/Deserialization
 *
 * Revision 1.5  2003/05/15 18:53:26  knoaman
 * Partial implementation of the configurable memory manager.
 *
 * Revision 1.4  2003/02/02 23:55:40  peiyongz
 * getFormattedString() added to return original and converted value.
 *
 * Revision 1.3  2003/01/30 21:56:22  tng
 * Performance: call getRawData instead of toString
 *
 * Revision 1.2  2002/11/04 14:53:27  tng
 * C++ Namespace Support.
 *
 * Revision 1.1.1.1  2002/02/01 22:22:39  peiyongz
 * sane_include
 *
 * Revision 1.2  2001/10/09 21:16:31  peiyongz
 * . macro to simplify code
 *
 * Revision 1.1  2001/10/01 16:13:56  peiyongz
 * DTV Reorganization:new classes: AbstractNumericFactValidator/ AbstractNumericValidator
 *
 */

// ---------------------------------------------------------------------------
//  Includes
// ---------------------------------------------------------------------------
#include <xercesc/validators/datatype/AbstractNumericValidator.hpp>
#include <xercesc/validators/datatype/InvalidDatatypeValueException.hpp>
#include <xercesc/util/XMLAbstractDoubleFloat.hpp>

XERCES_CPP_NAMESPACE_BEGIN

#define  REPORT_VALUE_ERROR(val1, val2, except_code, manager)    \
  ThrowXMLwithMemMgr2(InvalidDatatypeValueException               \
          , except_code                                 \
          , val1->getFormattedString()                  \
          , val2->getFormattedString()                  \
          , manager);

// ---------------------------------------------------------------------------
//  Constructors and Destructor
// ---------------------------------------------------------------------------
AbstractNumericValidator::~AbstractNumericValidator()
{}

AbstractNumericValidator::AbstractNumericValidator(
                          DatatypeValidator*            const baseValidator
                        , RefHashTableOf<KVStringPair>* const facets
                        , const int                           finalSet
                        , const ValidatorType                 type
                        , MemoryManager* const                manager)
:AbstractNumericFacetValidator(baseValidator, facets, finalSet, type, manager)
{
    //do not invoke init() here !!!
}

void AbstractNumericValidator::validate(const XMLCh*             const content
                                       ,      ValidationContext* const context
                                       ,      MemoryManager*     const manager)
{
    checkContent(content, context, false, manager);
}

void AbstractNumericValidator::boundsCheck(const XMLNumber*         const theData
                                          ,      MemoryManager*     const manager)
{
    int thisFacetsDefined = getFacetsDefined();
    int result;

    if (thisFacetsDefined == 0)
        return;

    try
    {

        // must be < MaxExclusive
        if ( (thisFacetsDefined & DatatypeValidator::FACET_MAXEXCLUSIVE) != 0 )
        {
            result = compareValues(theData, getMaxExclusive());
            if ( result != -1)
            {
                REPORT_VALUE_ERROR(theData
                                 , getMaxExclusive()
                                 , XMLExcepts::VALUE_exceed_maxExcl
                                 , manager)
            }
        }

        // must be <= MaxInclusive
        if ( (thisFacetsDefined & DatatypeValidator::FACET_MAXINCLUSIVE) != 0 )
        {
            result = compareValues(theData, getMaxInclusive());
            if (result == 1)
            {
                REPORT_VALUE_ERROR(theData
                                 , getMaxInclusive()
                                 , XMLExcepts::VALUE_exceed_maxIncl
                                 , manager)
            }
        }

        // must be >= MinInclusive
        if ( (thisFacetsDefined & DatatypeValidator::FACET_MININCLUSIVE) != 0 )
        {
            result = compareValues(theData, getMinInclusive());
            if (result == -1)
            {
                REPORT_VALUE_ERROR(theData
                                 , getMinInclusive()
                                 , XMLExcepts::VALUE_exceed_minIncl
                                 , manager)
            }
        }

        // must be > MinExclusive
        if ( (thisFacetsDefined & DatatypeValidator::FACET_MINEXCLUSIVE) != 0 )
        {
            result = compareValues(theData, getMinExclusive());
            if (result != 1)
            {
                REPORT_VALUE_ERROR(theData
                                 , getMinExclusive()
                                 , XMLExcepts::VALUE_exceed_minExcl
                                 , manager)
            }
        }
    }
    catch (XMLException &e)
    {
       ThrowXMLwithMemMgr1(InvalidDatatypeValueException, XMLExcepts::RethrowError, e.getMessage(), manager);
    }

}

const XMLCh* AbstractNumericValidator::getCanonicalRepresentation(const XMLCh*         const rawData
                                                                 ,      MemoryManager* const memMgr
                                                                 ,      bool                 toValidate) const
{
    MemoryManager* toUse = memMgr? memMgr : fMemoryManager;

    if (toValidate)
    {
        AbstractNumericValidator* temp = (AbstractNumericValidator*) this;

        try
        {
            temp->checkContent(rawData, 0, false, toUse);
        }
        catch (...)
        {
            return 0;
        }
    }

    // XMLAbstractDoubleFloat::getCanonicalRepresentation handles
    // exceptional cases
    return XMLAbstractDoubleFloat::getCanonicalRepresentation(rawData, toUse);

}

/***
 * Support for Serialization/De-serialization
 ***/

IMPL_XSERIALIZABLE_NOCREATE(AbstractNumericValidator)

void AbstractNumericValidator::serialize(XSerializeEngine& serEng)
{
    AbstractNumericFacetValidator::serialize(serEng);

    /***
     * Need not to do anything else here
     *
     * Note: its derivatives, Doubledv, Floatdv and Decimaldv writes
     *       number type info into the binary data stream to be read
     *       by AbstractNumericFacetVaildator during loading, therefore
     *       this class can NOT write/read anything into/from the binary
     *       data stream.
     *
     *       Later on, if this class has to write/read something into/from
     *       the binary data stream, we need to add a numberType data
     *       to XMLNumber and let AbstractNumericFacetValidator to write/read
     *       this number type info.
     ***/
}

XERCES_CPP_NAMESPACE_END

/**
  * End of file AbstractNumericValidator::cpp
  */

<|endoftext|>


<commit_before>/*******************************************************************************
 * Copyright (c) 2014 Niall Frederick Weedon and other Contributors
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 *    Niall Frederick Weedon - Initial Contribution
 *******************************************************************************/
#include "QuickstartClient.h"

// QuickstartClient (Constructor)
// Constructs the quickstart client, setting up an asynchronous
// MQTT client connection to the Quickstart service and the topic
// string to be used when publishing.
// @param deviceName 	- The name you wish to provide the service as an identifier.
// @param macAddress	- The MAC Address you wish to provide the service.
QuickstartClient::QuickstartClient(std::string deviceName, std::string macAddress) {
	client = std::unique_ptr<mqtt::async_client>(new mqtt::async_client("messaging.quickstart.internetofthings.ibmcloud.com:1883", "quickstart:" + macAddress));
	topic = std::string("iot-1/d/" + macAddress + "/evt/rpi-quickstart/json");
	myName = deviceName;

	if(client) {
		ClientCallback cb;
		client->set_callback(cb);

		connect();
	}
}

// QuickstartClient (Destructor)
// Destructs the Quickstart client, in this case, disconnecting
// the client if it is connected and releasing the resources used
// by it.
QuickstartClient::~QuickstartClient(void) {
	disconnect();
}

// connect
// Connects to the MQTT Service.
void QuickstartClient::connect(void) {
	if(client) {
		std::cout << "Connecting..." << std::flush;
		// Connect to the service asynchronously and wait
		// for the connection to complete.
		connectionToken = client->connect();
		connectionToken->wait_for_completion();
		std::cout << "\t\t\t[ OK ]" << std::endl;
	}
}

// disconnect
// Disconnects from the MQTT Service.
void QuickstartClient::disconnect(void) {
	if(client) {
		std::cout << "Disconnecting..." << std::flush;
		// Disconnect asynchronously and wait for its
		// completion.
		connectionToken = client->disconnect();
		connectionToken->wait_for_completion();
		std::cout << "\t\t[ OK ]" << std::endl;
	}
}

// publish
// Publish a Raspberry Pi quickstart message.
// @param cpuTemperature
// @param cpuLoad
// @param sine
void QuickstartClient::publish(double cpuTemperature, double cpuLoad, double sine) {
	if(client) {
		std::string payload = std::string("{\"d\":{ \"cputemp\":" + std::to_string(cpuTemperature));
		payload += std::string(", \"cpuload\":" + std::to_string(cpuLoad));
		payload += std::string(", \"sine\":" + std::to_string(sine));
		payload += std::string(", \"myName\": \"" + myName + "\" } }");

		mqtt::message_ptr pubmsg = std::make_shared<mqtt::message>(payload.c_str());
		pubmsg->set_qos(0);
		client->publish(topic, pubmsg)->wait_for_completion(TIMEOUT);
	}
}

// connection_lost
// Event fired when the client unexpectedly loses
// connection from the service.
void QuickstartClient::ClientCallback::connection_lost(const std::string& cause) {
	std::cout << "\nConnection lost." << std::endl;
	if (!cause.empty())
		std::cout << "\tCause: " << cause << std::endl;
}

// delivery_complete
// Event fired when the client successfully publishes
// a message.
void QuickstartClient::ClientCallback::delivery_complete(mqtt::idelivery_token_ptr tok) {

}

// message_arrived
// Event fired when the client receives a message.
void QuickstartClient::ClientCallback::message_arrived(const std::string& topic, mqtt::message_ptr msg) {

}<commit_msg>Connect to iot-2 Quickstart<commit_after>/*******************************************************************************
 * Copyright (c) 2014 Niall Frederick Weedon and other Contributors
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 *    Niall Frederick Weedon - Initial Contribution
 *******************************************************************************/
#include "QuickstartClient.h"

// QuickstartClient (Constructor)
// Constructs the quickstart client, setting up an asynchronous
// MQTT client connection to the Quickstart service and the topic
// string to be used when publishing.
// @param deviceName 	- The name you wish to provide the service as an identifier.
// @param macAddress	- The MAC Address you wish to provide the service.
QuickstartClient::QuickstartClient(std::string deviceName, std::string macAddress) {
	client = std::unique_ptr<mqtt::async_client>(new mqtt::async_client("quickstart.messaging.internetofthings.ibmcloud.com:1883",
																		"d:quickstart:iotsample-raspberrypi:" + macAddress));
	topic = std::string("iot-2/evt/status/fmt/json");
	myName = deviceName;

	if(client) {
		ClientCallback cb;
		client->set_callback(cb);

		connect();
	}
}

// QuickstartClient (Destructor)
// Destructs the Quickstart client, in this case, disconnecting
// the client if it is connected and releasing the resources used
// by it.
QuickstartClient::~QuickstartClient(void) {
	disconnect();
}

// connect
// Connects to the MQTT Service.
void QuickstartClient::connect(void) {
	if(client) {
		std::cout << "Connecting..." << std::flush;
		// Connect to the service asynchronously and wait
		// for the connection to complete.
		connectionToken = client->connect();
		connectionToken->wait_for_completion();
		std::cout << "\t\t\t[ OK ]" << std::endl;
	}
}

// disconnect
// Disconnects from the MQTT Service.
void QuickstartClient::disconnect(void) {
	if(client) {
		std::cout << "Disconnecting..." << std::flush;
		// Disconnect asynchronously and wait for its
		// completion.
		connectionToken = client->disconnect();
		connectionToken->wait_for_completion();
		std::cout << "\t\t[ OK ]" << std::endl;
	}
}

// publish
// Publish a Raspberry Pi quickstart message.
// @param cpuTemperature
// @param cpuLoad
// @param sine
void QuickstartClient::publish(double cpuTemperature, double cpuLoad, double sine) {
	if(client) {
		std::string payload = std::string("{\"d\":{ \"cputemp\":" + std::to_string(cpuTemperature));
		payload += std::string(", \"cpuload\":" + std::to_string(cpuLoad));
		payload += std::string(", \"sine\":" + std::to_string(sine));
		payload += std::string(", \"myName\": \"" + myName + "\" } }");

		mqtt::message_ptr pubmsg = std::make_shared<mqtt::message>(payload.c_str());
		pubmsg->set_qos(0);
		client->publish(topic, pubmsg)->wait_for_completion(TIMEOUT);
	}
}

// connection_lost
// Event fired when the client unexpectedly loses
// connection from the service.
void QuickstartClient::ClientCallback::connection_lost(const std::string& cause) {
	std::cout << "\nConnection lost." << std::endl;
	if (!cause.empty())
		std::cout << "\tCause: " << cause << std::endl;
}

// delivery_complete
// Event fired when the client successfully publishes
// a message.
void QuickstartClient::ClientCallback::delivery_complete(mqtt::idelivery_token_ptr tok) {

}

// message_arrived
// Event fired when the client receives a message.
void QuickstartClient::ClientCallback::message_arrived(const std::string& topic, mqtt::message_ptr msg) {

}<|endoftext|>


<commit_before>#include <iostream>
#include <GL/glew.h>
#include "glfw3.h"
#include <vector>

#include "Engine/Display.h"
#include "MB/Scene.h"
#include "MB/Scene1.h"
#include "MB/StartMenu.h"

Display* display;
Scene* scene;
Scene1* scene1;
StartMenu* startscene;

int main()
{
  display = new Display();
  startscene = new StartMenu(display->input);
  scene = new Scene(display->input);
  scene1 = new Scene1(display->input);
  display->addScene(startscene);
  display->addScene(scene);
  display->addScene(scene1);
  display->gameLoop();
  delete scene;
  delete scene1;
  delete startscene;
  delete display;
  std::cout << "Window closed" << std::endl;
  return 0;
}
<commit_msg>Update documentation<commit_after>#include <iostream>
#include <GL/glew.h>
#include "glfw3.h"
#include <vector>

#include "Engine/Display.h"
#include "MB/Scene.h"
#include "MB/Scene1.h"
#include "MB/StartMenu.h"

// Declare types
Display* display;
Scene* scene;
Scene1* scene1;
StartMenu* startscene;

int main()
{
  // Make a new Display, This will load all necessary framework related classes
  display = new Display();
  // Make the scenes we have and give them the input display created for us
  startscene = new StartMenu(display->input);
  scene = new Scene(display->input);
  scene1 = new Scene1(display->input);
  // Add those scenes to the scenemanager
  display->addScene(startscene);
  display->addScene(scene);
  display->addScene(scene1);
  // Start the main gameloop
  display->gameLoop();
  // If the gameloop stops we can delete everything we created here
  delete scene;
  delete scene1;
  delete startscene;
  delete display;
  std::cout << "Window closed" << std::endl;
  return 0;
}
<|endoftext|>