<commit_before>/***************************************************************************
 *   Copyright (C) 2006 by Ingo Kloecker <kloecker@kde.org>                *
 *                                                                         *
 *   This program is free software; you can redistribute it and/or modify  *
 *   it under the terms of the GNU Library General Public License as       *
 *   published by the Free Software Foundation; either version 2 of the    *
 *   License, or (at your option) any later version.                       *
 *                                                                         *
 *   This program is distributed in the hope that it will be useful,       *
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
 *   GNU General Public License for more details.                          *
 *                                                                         *
 *   You should have received a copy of the GNU Library General Public     *
 *   License along with this program; if not, write to the                 *
 *   Free Software Foundation, Inc.,                                       *
 *   51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.         *
 ***************************************************************************/
#include <QDebug>

#include "akonadi.h"
#include "akonadiconnection.h"
#include "storagebackend.h"
#include "storage/datastore.h"
#include "storage/entity.h"

#include "create.h"
#include "response.h"

using namespace Akonadi;

Create::Create(): Handler()
{
}

Create::~Create()
{
}

bool Create::handleLine(const QByteArray& line )
{
    // parse out the reference name and mailbox name
    const int startOfCommand = line.indexOf( ' ' ) + 1;
    const int startOfMailbox = line.indexOf( ' ', startOfCommand ) + 1;
    QByteArray mailbox = stripQuotes( line.right( line.size() - startOfMailbox ) );

    // strip off a trailing '/'
    if ( !mailbox.isEmpty() && mailbox[0] == '/' )
      mailbox = mailbox.right( mailbox.size() - 1 );

    // Responses:
    // OK - create completed
    // NO - create failure: can't create mailbox with that name
    // BAD - command unknown or arguments invalid
    Response response;
    response.setTag( tag() );

    if ( mailbox.isEmpty() || mailbox.contains( "//" ) ) {
        response.setError();
        response.setString( "Invalid argument" );
        emit responseAvailable( response );
    }
    else {
        DataStore *db = connection()->storageBackend();
        const int startOfLocation = mailbox.indexOf( '/' ) + 1;
        const QByteArray resourceName = mailbox.left( startOfLocation - 1 );
        const QByteArray locationName = mailbox.mid( startOfLocation );
        qDebug() << "Create: " << locationName
                 << " in resource: " << resourceName;
        Resource resource = db->getResourceByName( resourceName );
        // first check whether location already exists
        if ( db->getLocationByName( resource, locationName ).isValid() ) {
            response.setFailure();
            response.setString( "A folder with that name does already exist");
            emit responseAvailable( response );
        }
        // we have to create all superior hierarchical folders, so look for the
        // starting point
        QList<QByteArray> foldersToCreate;
        foldersToCreate.append( locationName );
        for ( int endOfSupFolder = locationName.lastIndexOf( '/', locationName.size() - 1 );
              endOfSupFolder > 0;
              endOfSupFolder = locationName.lastIndexOf( '/', endOfSupFolder - 2 ) ) {
            // check whether the superior hierarchical folder exists
            qDebug() << "Does " << locationName.left( endOfSupFolder )
                     << " exist in " << resourceName << "?";
            if ( !db->getLocationByName( resource, locationName.left( endOfSupFolder ) ).isValid() ) {
                // the superior folder does not exist, so it has to be created
                qDebug() << "No, it has to be created";
                foldersToCreate.prepend( locationName.left( endOfSupFolder ) );
            }
            else {
                // the superior folder exists, so we can stop here
                qDebug() << "Yes, it exists";
                break;
            }
        }
        // now we try to create all necessary folders
        // first check whether the existing superior folder can contain subfolders
        const int endOfSupFolder = foldersToCreate[0].lastIndexOf( '/' );
        if ( endOfSupFolder > 0 ) {
            bool canContainSubfolders = false;
            const QList<MimeType> mimeTypes = db->getMimeTypesForLocation( db->getLocationByName( resource, locationName.left( endOfSupFolder ) ).getId() );
            foreach ( MimeType m, mimeTypes ) {
                if ( m.getMimeType().toLower() == "directory/inode" ) {
                    canContainSubfolders = true;
                    break;
                }
            }
            if ( !canContainSubfolders ) {
                response.setFailure();
                response.setString( "Superior folder cannot contain subfolders" );
                emit responseAvailable( response );
                deleteLater();
                return true;
            }
        }
        // everything looks good, now we create the folders
        foreach ( QByteArray folderName, foldersToCreate ) {
            int locationId = 0;
            db->appendLocation( folderName, resource, &locationId );
            //db->appendMimeTypeForLocation( locationId, MimeType( "directory/inode" ) );
        }
    }

    response.setSuccess();
    response.setString( "Completed" );
    emit responseAvailable( response );

    deleteLater();
    return true;
}

<commit_msg>Keep the trailing '/' in the location name.<commit_after>/***************************************************************************
 *   Copyright (C) 2006 by Ingo Kloecker <kloecker@kde.org>                *
 *                                                                         *
 *   This program is free software; you can redistribute it and/or modify  *
 *   it under the terms of the GNU Library General Public License as       *
 *   published by the Free Software Foundation; either version 2 of the    *
 *   License, or (at your option) any later version.                       *
 *                                                                         *
 *   This program is distributed in the hope that it will be useful,       *
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
 *   GNU General Public License for more details.                          *
 *                                                                         *
 *   You should have received a copy of the GNU Library General Public     *
 *   License along with this program; if not, write to the                 *
 *   Free Software Foundation, Inc.,                                       *
 *   51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.         *
 ***************************************************************************/
#include <QDebug>

#include "akonadi.h"
#include "akonadiconnection.h"
#include "storagebackend.h"
#include "storage/datastore.h"
#include "storage/entity.h"

#include "create.h"
#include "response.h"

using namespace Akonadi;

Create::Create(): Handler()
{
}

Create::~Create()
{
}

bool Create::handleLine(const QByteArray& line )
{
    // parse out the reference name and mailbox name
    const int startOfCommand = line.indexOf( ' ' ) + 1;
    const int startOfMailbox = line.indexOf( ' ', startOfCommand ) + 1;
    QByteArray mailbox = stripQuotes( line.right( line.size() - startOfMailbox ) );

    // strip off a trailing '/'
    if ( !mailbox.isEmpty() && mailbox[0] == '/' )
      mailbox = mailbox.right( mailbox.size() - 1 );

    // Responses:
    // OK - create completed
    // NO - create failure: can't create mailbox with that name
    // BAD - command unknown or arguments invalid
    Response response;
    response.setTag( tag() );

    if ( mailbox.isEmpty() || mailbox.contains( "//" ) ) {
        response.setError();
        response.setString( "Invalid argument" );
        emit responseAvailable( response );
    }
    else {
        DataStore *db = connection()->storageBackend();
        const int startOfLocation = mailbox.indexOf( '/' );
        const QByteArray resourceName = mailbox.left( startOfLocation );
        const QByteArray locationName = mailbox.mid( startOfLocation );
        qDebug() << "Create: " << locationName
                 << " in resource: " << resourceName;
        Resource resource = db->getResourceByName( resourceName );
        // first check whether location already exists
        if ( db->getLocationByName( resource, locationName ).isValid() ) {
            response.setFailure();
            response.setString( "A folder with that name does already exist");
            emit responseAvailable( response );
        }
        // we have to create all superior hierarchical folders, so look for the
        // starting point
        QList<QByteArray> foldersToCreate;
        foldersToCreate.append( locationName );
        for ( int endOfSupFolder = locationName.lastIndexOf( '/', locationName.size() - 1 );
              endOfSupFolder > 0;
              endOfSupFolder = locationName.lastIndexOf( '/', endOfSupFolder - 2 ) ) {
            // check whether the superior hierarchical folder exists
            qDebug() << "Does " << locationName.left( endOfSupFolder )
                     << " exist in " << resourceName << "?";
            if ( ! db->getLocationByName( resource, locationName.left( endOfSupFolder ) ).isValid() ) {
                // the superior folder does not exist, so it has to be created
                qDebug() << "No, it has to be created";
                foldersToCreate.prepend( locationName.left( endOfSupFolder ) );
            }
            else {
                // the superior folder exists, so we can stop here
                qDebug() << "Yes, it exists";
                break;
            }
        }
        // now we try to create all necessary folders
        // first check whether the existing superior folder can contain subfolders
        const int endOfSupFolder = foldersToCreate[0].lastIndexOf( '/' );
        if ( endOfSupFolder > 0 ) {
            bool canContainSubfolders = false;
            const QList<MimeType> mimeTypes = db->getMimeTypesForLocation( db->getLocationByName( resource, locationName.left( endOfSupFolder ) ).getId() );
            foreach ( MimeType m, mimeTypes ) {
                if ( m.getMimeType().toLower() == "directory/inode" ) {
                    canContainSubfolders = true;
                    break;
                }
            }
            if ( !canContainSubfolders ) {
                response.setFailure();
                response.setString( "Superior folder cannot contain subfolders" );
                emit responseAvailable( response );
                deleteLater();
                return true;
            }
        }
        // everything looks good, now we create the folders
        foreach ( QByteArray folderName, foldersToCreate ) {
            int locationId = 0;
            db->appendLocation( folderName, resource, &locationId );
            //db->appendMimeTypeForLocation( locationId, MimeType( "directory/inode" ) );
        }
    }

    response.setSuccess();
    response.setString( "Completed" );
    emit responseAvailable( response );

    deleteLater();
    return true;
}

<|endoftext|>


<commit_before>/* Copyright (c) 2012, STANISLAW ADASZEWSKI
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
    * Redistributions of source code must retain the above copyright
      notice, this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright
      notice, this list of conditions and the following disclaimer in the
      documentation and/or other materials provided with the distribution.
    * Neither the name of STANISLAW ADASZEWSKI nor the
      names of its contributors may be used to endorse or promote products
      derived from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL STANISLAW ADASZEWSKI BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */

#include "qneport.h"
#include "qneconnection.h"

#include <QGraphicsScene>
#include <QFontMetrics>

#include <QPen>
#include <QtCore/QRect>
#include <QtGui/QPalette>

QNEPort::QNEPort(QGraphicsItem *parent):
    QGraphicsPathItem(parent)
{
    label = new QGraphicsTextItem(this);

    radius_ = radius();
    margin = 2;

    setFlag(QGraphicsItem::ItemSendsScenePositionChanges);

    m_portFlags = QNEPort::StandardPort;
    m_position = QNEPort::LeftPosition;
    setIsOutput(false);
}

QNEPort::~QNEPort()
{
    Q_FOREACH(QNEConnection *conn, m_connections) {
        delete conn;
    }
}

void QNEPort::setNEBlock(QNEBlock *b)
{
    m_block = b;
}

void QNEPort::setName(const QString &n)
{
    name = n;
    label->setPlainText(n);
}

void QNEPort::setIsOutput(bool o)
{
    isOutput_ = o;
    updatePath();
}

void QNEPort::updatePath()
{
    QPainterPath p;
    if(m_portFlags & NamePort || m_portFlags & TypePort) {
        // don't do anything, as we want an empty path for these
    }
    else if(isOutput_) {
        p.addEllipse(-radius_, -radius_, 2*radius_, 2*radius_);
    }
    else {
        p.addRect(-radius_, -radius_, 2*radius_, 2*radius_);
    }
    setPath(p);

    QPalette palette = scene()->palette();
    setPen(palette.buttonText().color());
    setBrush(palette.link());
}

void QNEPort::setPosition(QNEPort::Position position)
{
    m_position = position;

    switch(position)
    {
        case QNEPort::RightPosition:
            label->setPos(-radius_ - margin - label->boundingRect().width(), -label->boundingRect().height()/2);
            setRotation(0);
            break;
        case QNEPort::TopPosition:
            label->setPos(radius_ + margin, -label->boundingRect().height()/2);
            setRotation(90);
            break;
        case QNEPort::BottomPosition:
            label->setPos(radius_ + margin, -label->boundingRect().height()/2);
            setRotation(-90);
            break;
        case QNEPort::LeftPosition:
            label->setPos(radius_ + margin, -label->boundingRect().height()/2);
            setRotation(0);
            break;
        default:
            // Nuh! Bad position! Bad! Go to your room and think about what you've done.
            break;
    }
}

QNEPort::Position QNEPort::position() const
{
    return m_position;
}

int QNEPort::radius()
{
    return 5;
}

bool QNEPort::isOutput()
{
    return isOutput_;
}

QVector<QNEConnection*>& QNEPort::connections()
{
    return m_connections;
}

void QNEPort::setPortFlags(int f)
{
    m_portFlags = f;

    // If the flaf is type or name, then it's not really
    // a port and consequently is given a non-path, and
    // different font options
    if (m_portFlags & TypePort)
    {
        QFont font(scene()->font());
        font.setItalic(true);
        label->setFont(font);
    } else if (m_portFlags & NamePort)
    {
        QFont font(scene()->font());
        font.setBold(true);
        label->setFont(font);
    }
    updatePath();
}

QNEBlock* QNEPort::block() const
{
    return m_block;
}

quint64 QNEPort::ptr()
{
    return m_ptr;
}

void QNEPort::setPtr(quint64 p)
{
    m_ptr = p;
}

bool QNEPort::isConnected(QNEPort *other)
{
    Q_FOREACH(QNEConnection *conn, m_connections) {
        if (conn->port1() == other || conn->port2() == other)
            return true;
    }

    return false;
}

QVariant QNEPort::itemChange(GraphicsItemChange change, const QVariant &value)
{
    if (change == ItemScenePositionHasChanged)
    {
        Q_FOREACH(QNEConnection *conn, m_connections)
        {
            conn->updatePosFromPorts();
            conn->updatePath();
        }
    }
    return value;
}
<commit_msg>Arrows for port symbols (signifying in/out status), not circles and squares<commit_after>/* Copyright (c) 2012, STANISLAW ADASZEWSKI
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
    * Redistributions of source code must retain the above copyright
      notice, this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright
      notice, this list of conditions and the following disclaimer in the
      documentation and/or other materials provided with the distribution.
    * Neither the name of STANISLAW ADASZEWSKI nor the
      names of its contributors may be used to endorse or promote products
      derived from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL STANISLAW ADASZEWSKI BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */

#include "qneport.h"
#include "qneconnection.h"

#include <QGraphicsScene>
#include <QFontMetrics>

#include <QPen>
#include <QtCore/QRect>
#include <QtGui/QPalette>

QNEPort::QNEPort(QGraphicsItem *parent):
    QGraphicsPathItem(parent)
{
    label = new QGraphicsTextItem(this);

    radius_ = radius();
    margin = 2;

    setFlag(QGraphicsItem::ItemSendsScenePositionChanges);

    m_portFlags = QNEPort::StandardPort;
    m_position = QNEPort::LeftPosition;
    setIsOutput(false);
}

QNEPort::~QNEPort()
{
    Q_FOREACH(QNEConnection *conn, m_connections) {
        delete conn;
    }
}

void QNEPort::setNEBlock(QNEBlock *b)
{
    m_block = b;
}

void QNEPort::setName(const QString &n)
{
    name = n;
    label->setPlainText(n);
}

void QNEPort::setIsOutput(bool o)
{
    isOutput_ = o;
    updatePath();
}

void QNEPort::updatePath()
{
    QPainterPath p;
    if(m_portFlags & NamePort || m_portFlags & TypePort) {
        // don't do anything, as we want an empty path for these
    }
    else if((isOutput_ && position() != QNEPort::RightPosition) || (!isOutput_ && position() == QNEPort::RightPosition)) {
        QPolygon polygon;
        polygon << QPoint(radius_ * 0.7, radius_) << QPoint(radius_ * 0.7, -radius_) << QPoint(-radius_, 0);
        p.addPolygon(polygon);
    }
    else {
        QPolygon polygon;
        polygon << QPoint(-radius_ * 0.7, -radius_) << QPoint(-radius_ * 0.7, radius_) << QPoint(radius_, 0);
        p.addPolygon(polygon);
    }
    setPath(p);

    QPalette palette = scene()->palette();
    setPen(palette.buttonText().color());
    setBrush(palette.link());
}

void QNEPort::setPosition(QNEPort::Position position)
{
    m_position = position;

    switch(position)
    {
        case QNEPort::RightPosition:
            label->setPos(-radius_ - margin - label->boundingRect().width(), -label->boundingRect().height()/2);
            setRotation(0);
            break;
        case QNEPort::TopPosition:
            label->setPos(radius_ + margin, -label->boundingRect().height()/2);
            setRotation(90);
            break;
        case QNEPort::BottomPosition:
            label->setPos(radius_ + margin, -label->boundingRect().height()/2);
            setRotation(-90);
            break;
        case QNEPort::LeftPosition:
            label->setPos(radius_ + margin, -label->boundingRect().height()/2);
            setRotation(0);
            break;
        default:
            // Nuh! Bad position! Bad! Go to your room and think about what you've done.
            break;
    }
    updatePath();
}

QNEPort::Position QNEPort::position() const
{
    return m_position;
}

int QNEPort::radius()
{
    return 5;
}

bool QNEPort::isOutput()
{
    return isOutput_;
}

QVector<QNEConnection*>& QNEPort::connections()
{
    return m_connections;
}

void QNEPort::setPortFlags(int f)
{
    m_portFlags = f;

    // If the flaf is type or name, then it's not really
    // a port and consequently is given a non-path, and
    // different font options
    if (m_portFlags & TypePort)
    {
        QFont font(scene()->font());
        font.setItalic(true);
        label->setFont(font);
    } else if (m_portFlags & NamePort)
    {
        QFont font(scene()->font());
        font.setBold(true);
        label->setFont(font);
    }
    updatePath();
}

QNEBlock* QNEPort::block() const
{
    return m_block;
}

quint64 QNEPort::ptr()
{
    return m_ptr;
}

void QNEPort::setPtr(quint64 p)
{
    m_ptr = p;
}

bool QNEPort::isConnected(QNEPort *other)
{
    Q_FOREACH(QNEConnection *conn, m_connections) {
        if (conn->port1() == other || conn->port2() == other)
            return true;
    }

    return false;
}

QVariant QNEPort::itemChange(GraphicsItemChange change, const QVariant &value)
{
    if (change == ItemScenePositionHasChanged)
    {
        Q_FOREACH(QNEConnection *conn, m_connections)
        {
            conn->updatePosFromPorts();
            conn->updatePath();
        }
    }
    return value;
}
<|endoftext|>


<commit_before>/*=========================================================================

  Program: DICOM for VTK

  Copyright (c) 2012-2013 David Gobbi
  All rights reserved.
  See Copyright.txt or http://www.cognitive-antics.net/bsd3.txt for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notice for more information.

=========================================================================*/

#include "vtkDICOMParser.h"
#include "vtkDICOMMetaData.h"
#include "vtkDICOMDictionary.h"
#include "vtkDICOMItem.h"

#include <vtkSmartPointer.h>

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

#define MAX_INDENT 24
#define INDENT_SIZE 2
#define MAX_LENGTH 78

// remove path portion of filename
const char *basename(const char *filename)
{
  const char *cp = filename + strlen(filename);
  while (cp != filename && cp[-1] != '\\' && cp[-1] != '/') { --cp; }
  return cp;
}

// Print out one data element
void printElement(const vtkDICOMDataElementIterator &iter, int depth)
{
  vtkDICOMTag tag = iter->GetTag();
  int g = tag.GetGroup();
  int e = tag.GetElement();
  vtkDICOMValue v = iter->GetValue();
  unsigned int vl = v.GetVL();
  const char *vr = v.GetVR().GetText();
  const char *name = "";
  vtkDICOMDictEntry d = vtkDICOMDictionary::FindDictEntry(tag);
  if (d.IsValid())
    {
    name = d.GetName();
    }

  // make an indentation string
  if (INDENT_SIZE*depth > MAX_INDENT)
    {
    depth = MAX_INDENT/INDENT_SIZE;
    }
  static const char spaces[MAX_INDENT+1] = "                        ";
  const char *indent = spaces + (MAX_INDENT - INDENT_SIZE*depth);

  std::string s;
  if (v.GetVR() == vtkDICOMVR::UN ||
      v.GetVR() == vtkDICOMVR::SQ)
    {
    // sequences are printed later
    s = (vl > 0 ? "..." : "");
    }
  else if (v.GetVR() == vtkDICOMVR::LT ||
           v.GetVR() == vtkDICOMVR::ST ||
           v.GetVR() == vtkDICOMVR::UT)
    {
    // replace breaks with "\\", cap length to MAX_LENGTH
    const char *cp = v.GetCharData();
    unsigned int j = 0;
    while (j < vl && cp[j] != '\0')
      {
      unsigned int k = j;
      unsigned int m = j;
      for (; j < vl && cp[j] != '\0'; j++)
        {
        m = j;
        if (cp[j] == '\r' || cp[j] == '\n' || cp[j] == '\f')
          {
          do { j++; }
          while (j < vl && (cp[j] == '\r' || cp[j] == '\n' || cp[j] == '\f'));
          break;
          }
        m++;
        }
      if (j == vl)
        {
        while (m > 0 && cp[m-1] == ' ') { m--; }
        }
      if (k != 0)
        {
        s.append("\\\\");
        }
      s.append(&cp[k], m-k);
      if (s.size() > MAX_LENGTH)
        {
        s.resize(MAX_LENGTH-4);
        s.append("...");
        break;
        }
      }
    }
  else
    {
    // print any other VR via conversion to string
    unsigned int n = v.GetNumberOfValues();
    for (unsigned int i = 0; i < n; i++)
      {
      size_t pos = 0;
      v.AppendValueToString(s, i);
      if (i < n - 1)
        {
        s.append("\\");
        }
      if (s.size() > MAX_LENGTH-4)
        {
        s.resize(pos);
        s.append("...");
        break;
        }
      pos = s.size();
      }
    }

  printf("%s(%04X,%04X) %s \"%s\" %u : [%s]\n",
    indent, g, e, vr, name, vl, s.c_str());

  if (v.GetVR() == vtkDICOMVR::SQ)
    {
    unsigned int m = v.GetNumberOfValues();
    const vtkDICOMItem *items = v.GetSequenceData();
    for (unsigned int j = 0; j < m; j++)
      {
      printf("%s%s---- SQ Item %04u ----\n",
        indent, spaces+(MAX_INDENT - INDENT_SIZE), j+1);
      vtkDICOMDataElementIterator siter =
        items[j].GetDataElementIterator();
      vtkDICOMDataElementIterator siterEnd =
        items[j].GetDataElementIteratorEnd();

      for (; siter != siterEnd; ++siter)
        {
        printElement(siter, depth+1);
        }
      }
    }
}

// This program will dump all the metadata in the given file
int main(int argc, char *argv[])
{
  int rval = 0;

  if (argc < 2)
    {
    printf("usage: %s file1.dcm [file2.dcm ...]\n", basename(argv[0]));
    return rval;
    }

  vtkSmartPointer<vtkDICOMParser> parser =
    vtkSmartPointer<vtkDICOMParser>::New();

  for (int argi = 1; argi < argc; argi++)
    {
    const char *filename = argv[argi];
    printf("=========== %s =========\n", basename(filename));

    vtkSmartPointer<vtkDICOMMetaData> data =
      vtkSmartPointer<vtkDICOMMetaData>::New();

    parser->SetFileName(filename);
    parser->SetMetaData(data);

    parser->Update();

    vtkDICOMDataElementIterator iter =
      data->GetDataElementIterator();
    vtkDICOMDataElementIterator iterEnd =
      data->GetDataElementIteratorEnd();

    for (; iter != iterEnd; ++iter)
      {
      printElement(iter, 0);
      }
    }

  return rval;
}
<commit_msg>Make dicomdump dump once per series, not once per file.<commit_after>/*=========================================================================

  Program: DICOM for VTK

  Copyright (c) 2012-2013 David Gobbi
  All rights reserved.
  See Copyright.txt or http://www.cognitive-antics.net/bsd3.txt for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notice for more information.

=========================================================================*/

#include "vtkDICOMParser.h"
#include "vtkDICOMSorter.h"
#include "vtkDICOMMetaData.h"
#include "vtkDICOMDictionary.h"
#include "vtkDICOMItem.h"

#include <vtkStringArray.h>
#include <vtkSmartPointer.h>

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

#define MAX_INDENT 24
#define INDENT_SIZE 2
#define MAX_LENGTH 78

// remove path portion of filename
const char *basename(const char *filename)
{
  const char *cp = filename + strlen(filename);
  while (cp != filename && cp[-1] != '\\' && cp[-1] != '/') { --cp; }
  return cp;
}

// Print out one data element
void printElement(const vtkDICOMDataElementIterator &iter, int depth)
{
  vtkDICOMTag tag = iter->GetTag();
  int g = tag.GetGroup();
  int e = tag.GetElement();
  vtkDICOMValue v = iter->GetValue();
  unsigned int vl = v.GetVL();
  const char *vr = v.GetVR().GetText();
  const char *name = "";
  vtkDICOMDictEntry d = vtkDICOMDictionary::FindDictEntry(tag);
  if (d.IsValid())
    {
    name = d.GetName();
    }

  // allow multiple values (i.e. for each image in series)
  unsigned int vn = v.GetNumberOfValues();
  vtkDICOMValue *vp = v.GetMultiplexData();
  if (vp == 0)
    {
    vp = &v;
    vn = 1;
    }

  // make an indentation string
  if (INDENT_SIZE*depth > MAX_INDENT)
    {
    depth = MAX_INDENT/INDENT_SIZE;
    }
  static const char spaces[MAX_INDENT+1] = "                        ";
  const char *indent = spaces + (MAX_INDENT - INDENT_SIZE*depth);

  for (unsigned int vi = 0; vi < vn; vi++)
    {
    v = vp[vi];
    std::string s;
    if (v.GetVR() == vtkDICOMVR::UN ||
        v.GetVR() == vtkDICOMVR::SQ)
      {
      // sequences are printed later
      s = (vl > 0 ? "..." : "");
      }
    else if (v.GetVR() == vtkDICOMVR::LT ||
             v.GetVR() == vtkDICOMVR::ST ||
             v.GetVR() == vtkDICOMVR::UT)
      {
      // replace breaks with "\\", cap length to MAX_LENGTH
      const char *cp = v.GetCharData();
      unsigned int j = 0;
      while (j < vl && cp[j] != '\0')
        {
        unsigned int k = j;
        unsigned int m = j;
        for (; j < vl && cp[j] != '\0'; j++)
          {
          m = j;
          if (cp[j] == '\r' || cp[j] == '\n' || cp[j] == '\f')
            {
            do { j++; }
            while (j < vl && (cp[j] == '\r' || cp[j] == '\n' || cp[j] == '\f'));
            break;
            }
          m++;
          }
        if (j == vl)
          {
          while (m > 0 && cp[m-1] == ' ') { m--; }
          }
        if (k != 0)
          {
          s.append("\\\\");
          }
        s.append(&cp[k], m-k);
        if (s.size() > MAX_LENGTH)
          {
          s.resize(MAX_LENGTH-4);
          s.append("...");
          break;
          }
        }
      }
    else
      {
      // print any other VR via conversion to string
      unsigned int n = v.GetNumberOfValues();
      for (unsigned int i = 0; i < n; i++)
        {
        size_t pos = 0;
        v.AppendValueToString(s, i);
        if (i < n - 1)
          {
          s.append("\\");
          }
        if (s.size() > MAX_LENGTH-4)
          {
          s.resize(pos);
          s.append("...");
          break;
          }
        pos = s.size();
        }
      }

    if (vi == 0)
      {
      printf("%s(%04X,%04X) %s \"%s\" :", indent, g, e, vr, name);
      }
    if (vn > 1)
      {
      printf("%s%s  %4.4u",
        (vi == 0 ? " (multiple values)\n" : ""), indent, vi + 1);
      }
    printf(" [%s] (%u bytes)\n", s.c_str(), v.GetVL());

    if (v.GetVR() == vtkDICOMVR::SQ)
      {
      unsigned int m = v.GetNumberOfValues();
      const vtkDICOMItem *items = v.GetSequenceData();
      for (unsigned int j = 0; j < m; j++)
        {
        printf("%s%s---- SQ Item %04u ----\n",
          indent, spaces+(MAX_INDENT - INDENT_SIZE), j+1);
        vtkDICOMDataElementIterator siter =
          items[j].GetDataElementIterator();
        vtkDICOMDataElementIterator siterEnd =
          items[j].GetDataElementIteratorEnd();

        for (; siter != siterEnd; ++siter)
          {
          printElement(siter, depth+1);
          }
        }
      }
    }
}

// This program will dump all the metadata in the given file
int main(int argc, char *argv[])
{
  int rval = 0;

  if (argc < 2)
    {
    printf("usage: %s file1.dcm [file2.dcm ...]\n", basename(argv[0]));
    return rval;
    }

  vtkSmartPointer<vtkStringArray> files =
    vtkSmartPointer<vtkStringArray>::New();

  for (int argi = 1; argi < argc; argi++)
    {
    files->InsertNextValue(argv[argi]);
    }

  // sort the files by study and series
  vtkSmartPointer<vtkDICOMSorter> sorter =
    vtkSmartPointer<vtkDICOMSorter>::New();
  sorter->SetInputFileNames(files);
  sorter->Update();

  vtkSmartPointer<vtkDICOMParser> parser =
    vtkSmartPointer<vtkDICOMParser>::New();

  vtkSmartPointer<vtkDICOMMetaData> data =
    vtkSmartPointer<vtkDICOMMetaData>::New();
  parser->SetMetaData(data);

  int m = sorter->GetNumberOfStudies();
  for (int j = 0; j < m; j++)
    {
    int k = sorter->GetFirstSeriesInStudy(j);
    int n = sorter->GetNumberOfSeriesInStudy(j);
    n += k;
    for (; k < n; k++)
      {
      vtkStringArray *a = sorter->GetFileNamesForSeries(k);
      vtkIdType l = a->GetNumberOfValues();
      std::string fname = a->GetValue(0);
      printf("=========== %s =========\n", basename(fname.c_str()));

      data->Clear();
      data->SetNumberOfInstances(static_cast<int>(l));

      for (vtkIdType i = 0; i < l; i++)
        {
        fname = a->GetValue(i);
        parser->SetIndex(i);
        parser->SetFileName(fname.c_str());
        parser->Update();
        }

      vtkDICOMDataElementIterator iter =
        data->GetDataElementIterator();
      vtkDICOMDataElementIterator iterEnd =
        data->GetDataElementIteratorEnd();

      for (; iter != iterEnd; ++iter)
        {
        printElement(iter, 0);
        }
      }
    }

  return rval;
}
<|endoftext|>


<commit_before>// $Id: AliHLTCaloConstantsHandler.cxx 34223 2009-08-12 07:55:37Z richterm $

//**************************************************************************
//* This file is property of and copyright by the ALICE HLT Project        *
//* ALICE Experiment at CERN, All rights reserved.                         *
//*                                                                        *
//* Primary Authors: Svein Lindal <slindal@fys.uio.no>
//*                  for The ALICE HLT Project.                            *
//*                                                                        *
//* Permission to use, copy, modify and distribute this software and its   *
//* documentation strictly for non-commercial purposes is hereby granted   *
//* without fee, provided that the above copyright notice appears in all   *
//* copies and that both the copyright notice and this permission notice   *
//* appear in the supporting documentation. The authors make no claims     *
//* about the suitability of this software for any purpose. It is          *
//* provided "as is" without express or implied warranty.                  *
//**************************************************************************

/// @file   AliHLTCaloConstantsHandler.h
/// @author Svein Lindal
/// @date   2009-10-21
/// @brief  Handler class that helps create an instance of the right
///         AliHLTCaloConstants child class
///         (e.g. AliHLTPHOSConstants or AliHLTEMCALConstants)

#include "TString.h"
#include "AliHLTCaloConstantsHandler.h"
#include "AliHLTCaloConstants.h"
#include "AliHLTMisc.h"
#include "AliHLTLogging.h"

ClassImp(AliHLTCaloConstantsHandler)

AliHLTCaloConstantsHandler::AliHLTCaloConstantsHandler(TString det):
  fCaloConstants(0)
{
  if (det.CompareTo("PHOS") == 0) {
    fCaloConstants = AliHLTMisc::LoadInstance( ( AliHLTCaloConstants*  ) NULL,
					       "AliHLTPHOSConstants", "libAliHLTPHOS.so");
  }
  else
    {
      fCaloConstants = AliHLTMisc::LoadInstance( ( AliHLTCaloConstants* ) NULL,
						 "AliHLTEMCALConstants" , "libAliHLTEMCAL.so");
    }

  if( fCaloConstants == 0 )
    {
      AliHLTLogging *log = new AliHLTLogging();
      log->Logging(kHLTLogFatal, __FILE__, "fCaloConstants == ZERO ",  "fCaloConstants == ZERO " );
      delete log;
    }
}

AliHLTCaloConstantsHandler::~AliHLTCaloConstantsHandler()
{
  //Default destructor
}
<commit_msg>changed kHLTLogFatal into kHLTLogDebug<commit_after>// $Id: AliHLTCaloConstantsHandler.cxx 34223 2009-08-12 07:55:37Z richterm $

//**************************************************************************
//* This file is property of and copyright by the ALICE HLT Project        *
//* ALICE Experiment at CERN, All rights reserved.                         *
//*                                                                        *
//* Primary Authors: Svein Lindal <slindal@fys.uio.no>
//*                  for The ALICE HLT Project.                            *
//*                                                                        *
//* Permission to use, copy, modify and distribute this software and its   *
//* documentation strictly for non-commercial purposes is hereby granted   *
//* without fee, provided that the above copyright notice appears in all   *
//* copies and that both the copyright notice and this permission notice   *
//* appear in the supporting documentation. The authors make no claims     *
//* about the suitability of this software for any purpose. It is          *
//* provided "as is" without express or implied warranty.                  *
//**************************************************************************

/// @file   AliHLTCaloConstantsHandler.h
/// @author Svein Lindal
/// @date   2009-10-21
/// @brief  Handler class that helps create an instance of the right
///         AliHLTCaloConstants child class
///         (e.g. AliHLTPHOSConstants or AliHLTEMCALConstants)

#include "TString.h"
#include "AliHLTCaloConstantsHandler.h"
#include "AliHLTCaloConstants.h"
#include "AliHLTMisc.h"
#include "AliHLTLogging.h"

ClassImp(AliHLTCaloConstantsHandler)

AliHLTCaloConstantsHandler::AliHLTCaloConstantsHandler(TString det):
  fCaloConstants(0)
{

  if (det.CompareTo("PHOS") == 0) {
    fCaloConstants = AliHLTMisc::LoadInstance( ( AliHLTCaloConstants*  ) NULL,
					       "AliHLTPHOSConstants", "libAliHLTPHOS.so");
  }
  else
    {
      fCaloConstants = AliHLTMisc::LoadInstance( ( AliHLTCaloConstants* ) NULL,
						 "AliHLTEMCALConstants" , "libAliHLTEMCAL.so");
    }

  if( fCaloConstants == 0 )
    {
      AliHLTLogging *log = new AliHLTLogging();
      log->Logging(kHLTLogDebug, __FILE__, "fCaloConstants == ZERO ",  "fCaloConstants == ZERO " );
      delete log;
    }
}

AliHLTCaloConstantsHandler::~AliHLTCaloConstantsHandler()
{
  //Default destructor
}
<|endoftext|>


<commit_before>/** Copyright 2008, 2009, 2010, 2011, 2012 Roland Olbricht
*
* This file is part of Overpass_API.
*
* Overpass_API is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Overpass_API 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Overpass_API.  If not, see <http://www.gnu.org/licenses/>.
*/

#include <iomanip>
#include <iostream>
#include <sstream>
#include <string>

#include "statement.h"

using namespace std;

map< string, Statement::Statement_Maker* >& Statement::maker_by_name()
{
  static map< string, Statement::Statement_Maker* > makers;
  return makers;
}

void Statement::eval_attributes_array(string element, map< string, string >& attributes,
				      const map< string, string >& input)
{
  for (map< string, string >::const_iterator it = input.begin(); it != input.end(); ++it)
  {
    map< string, string >::iterator ait(attributes.find(it->first));
    if (ait != attributes.end())
      ait->second = it->second;
    else
    {
      ostringstream temp;
      temp<<"Unknown attribute \""<<it->first<<"\" in element \""<<element<<"\".";
      add_static_error(temp.str());
    }
  }
}

void Statement::assure_no_text(string text, string name)
{
  for (unsigned int i(0); i < text.size(); ++i)
  {
    if (!isspace(text[i]))
    {
      ostringstream temp;
      temp<<"Element \""<<name<<"\" must not contain text.";
      add_static_error(temp.str());
      break;
    }
  }
}

void Statement::substatement_error(string parent, Statement* child)
{
  ostringstream temp;
  temp<<"Element \""<<child->get_name()<<"\" cannot be subelement of element \""<<parent<<"\".";
  add_static_error(temp.str());

  delete child;
}

void Statement::add_statement(Statement* statement, string text)
{
  assure_no_text(text, this->get_name());
  substatement_error(get_name(), statement);
}

void Statement::add_final_text(string text)
{
  assure_no_text(text, this->get_name());
}

void Statement::display_full()
{
  //display_verbatim(get_source(startpos, endpos - startpos));
}

void Statement::display_starttag()
{
  //display_verbatim(get_source(startpos, tagendpos - startpos));
}

Statement::Factory::~Factory()
{
  for (vector< Statement* >::const_iterator it = created_statements.begin();
      it != created_statements.end(); ++it)
    delete *it;
}

Statement* Statement::Factory::create_statement
    (string element, int line_number, const map< string, string >& attributes)
{
  Statement* statement = 0;

  map< string, Statement::Statement_Maker* >::iterator maker_it =
      Statement::maker_by_name().find(element);

  if (maker_it != Statement::maker_by_name().end())
    statement = maker_it->second->create_statement(line_number, attributes);

  if (statement)
    created_statements.push_back(statement);
  else
  {
    ostringstream temp;
    temp<<"Unknown tag \""<<element<<"\" in line "<<line_number<<'.';
    if (error_output_)
      error_output_->add_static_error(temp.str(), line_number);
  }

  return statement;
}

Error_Output* Statement::error_output = 0;

void Statement::add_static_error(string error)
{
  if (error_output)
    error_output->add_static_error(error, line_number);
}

void Statement::add_static_remark(string remark)
{
  if (error_output)
    error_output->add_static_remark(remark, line_number);
}

void Statement::runtime_remark(string error) const
{
  if (error_output)
    error_output->runtime_remark(error);
}

map< string, string > convert_c_pairs(const char** attr)
{
  map< string, string > result;
  for (int i = 0; attr[i]; i+=2)
    result[attr[i]] = attr[i+1];
  return result;
}
<commit_msg>Fixed a bug in the statement management.<commit_after>/** Copyright 2008, 2009, 2010, 2011, 2012 Roland Olbricht
*
* This file is part of Overpass_API.
*
* Overpass_API is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Overpass_API 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Overpass_API.  If not, see <http://www.gnu.org/licenses/>.
*/

#include <iomanip>
#include <iostream>
#include <sstream>
#include <string>

#include "statement.h"

using namespace std;

map< string, Statement::Statement_Maker* >& Statement::maker_by_name()
{
  static map< string, Statement::Statement_Maker* > makers;
  return makers;
}

void Statement::eval_attributes_array(string element, map< string, string >& attributes,
				      const map< string, string >& input)
{
  for (map< string, string >::const_iterator it = input.begin(); it != input.end(); ++it)
  {
    map< string, string >::iterator ait(attributes.find(it->first));
    if (ait != attributes.end())
      ait->second = it->second;
    else
    {
      ostringstream temp;
      temp<<"Unknown attribute \""<<it->first<<"\" in element \""<<element<<"\".";
      add_static_error(temp.str());
    }
  }
}

void Statement::assure_no_text(string text, string name)
{
  for (unsigned int i(0); i < text.size(); ++i)
  {
    if (!isspace(text[i]))
    {
      ostringstream temp;
      temp<<"Element \""<<name<<"\" must not contain text.";
      add_static_error(temp.str());
      break;
    }
  }
}

void Statement::substatement_error(string parent, Statement* child)
{
  ostringstream temp;
  temp<<"Element \""<<child->get_name()<<"\" cannot be subelement of element \""<<parent<<"\".";
  add_static_error(temp.str());
}

void Statement::add_statement(Statement* statement, string text)
{
  assure_no_text(text, this->get_name());
  substatement_error(get_name(), statement);
}

void Statement::add_final_text(string text)
{
  assure_no_text(text, this->get_name());
}

void Statement::display_full()
{
  //display_verbatim(get_source(startpos, endpos - startpos));
}

void Statement::display_starttag()
{
  //display_verbatim(get_source(startpos, tagendpos - startpos));
}

Statement::Factory::~Factory()
{
  for (vector< Statement* >::const_iterator it = created_statements.begin();
      it != created_statements.end(); ++it)
    delete *it;
}

Statement* Statement::Factory::create_statement
    (string element, int line_number, const map< string, string >& attributes)
{
  Statement* statement = 0;

  map< string, Statement::Statement_Maker* >::iterator maker_it =
      Statement::maker_by_name().find(element);

  if (maker_it != Statement::maker_by_name().end())
    statement = maker_it->second->create_statement(line_number, attributes);

  if (statement)
    created_statements.push_back(statement);
  else
  {
    ostringstream temp;
    temp<<"Unknown tag \""<<element<<"\" in line "<<line_number<<'.';
    if (error_output_)
      error_output_->add_static_error(temp.str(), line_number);
  }

  return statement;
}

Error_Output* Statement::error_output = 0;

void Statement::add_static_error(string error)
{
  if (error_output)
    error_output->add_static_error(error, line_number);
}

void Statement::add_static_remark(string remark)
{
  if (error_output)
    error_output->add_static_remark(remark, line_number);
}

void Statement::runtime_remark(string error) const
{
  if (error_output)
    error_output->runtime_remark(error);
}

map< string, string > convert_c_pairs(const char** attr)
{
  map< string, string > result;
  for (int i = 0; attr[i]; i+=2)
    result[attr[i]] = attr[i+1];
  return result;
}
<|endoftext|>


<commit_before>/**
 *  @copyright Copyright 2017 The J-PET Framework Authors. All rights reserved.
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may find a copy of the License in the LICENCE file.
 *
 * 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.
 *
 *  @file SinogramCreator.cpp
 */

#include "SinogramCreator.h"
#include <TH2I.h>
#include <TH2F.h>
#include <TH1I.h>
using namespace jpet_options_tools;

SinogramCreator::SinogramCreator(const char* name) : JPetUserTask(name) {}

SinogramCreator::~SinogramCreator() {}

bool SinogramCreator::init()
{
  setUpOptions();
  fOutputEvents = new JPetTimeWindow("JPetEvent");

  getStatistics().createHistogram(new TH2I("reconstuction_histogram",
                                  "reconstuction_histogram",
                                  std::ceil(fReconstructionLayerRadius * 2 * (1.f / fReconstructionDistanceAccuracy)) + 1, -fReconstructionLayerRadius, fReconstructionLayerRadius,
                                  std::ceil((fReconstructionEndAngle - fReconstructionStartAngle) / fReconstructionAngleStep), fReconstructionStartAngle, fReconstructionEndAngle));

  getStatistics().createHistogram(new TH2I("reconstuction_histogram_monte",
                                  "reconstuction_histogram_monte",
                                  std::ceil(fReconstructionLayerRadius * 2 * (1.f / fReconstructionDistanceAccuracy)) + 1, -fReconstructionLayerRadius, fReconstructionLayerRadius,
                                  std::ceil((fReconstructionEndAngle - fReconstructionStartAngle) / fReconstructionAngleStep), fReconstructionStartAngle, fReconstructionEndAngle));

  getStatistics().createHistogram(new TH1F("pos_x", "Position x monte carlo", fReconstructionLayerRadius * 2 * 10 * 5, -fReconstructionLayerRadius, fReconstructionLayerRadius)); //10cm * 2 sides * 10mm * 5, 0.2mm acc;
  getStatistics().createHistogram(new TH1F("pos_y", "Position y monte carlo", fReconstructionLayerRadius * 2 * 10 * 5, -fReconstructionLayerRadius, fReconstructionLayerRadius)); //10cm * 2 sides * 10mm * 5, 0.2mm acc;
  getStatistics().createHistogram(new TH2F("pos_xvsy", "Position x vs y monte carlo", 10 * 2 * 10 * 5, -10., 10., 10 * 2 * 10 * 5, -10., 10.)); //10cm * 2 sides * 10mm * 5, 0.2mm acc;

  getStatistics().createHistogram(new TH1F("pos_r_1", "Position r real data", (fReconstructionLayerRadius + 15.) * 2 * 10 * 5, -fReconstructionLayerRadius, fReconstructionLayerRadius)); //10cm * 2 sides * 10mm * 5, 0.2mm acc;
  getStatistics().createHistogram(new TH1F("pos_r_2", "Position r real data", fReconstructionLayerRadius * 2 * 10 * 5, -fReconstructionLayerRadius, fReconstructionLayerRadius));
  getStatistics().createHistogram(new TH1F("pos_r_3", "Position r real data", fReconstructionLayerRadius * 2 * 10 * 5, -fReconstructionLayerRadius, fReconstructionLayerRadius));

  getStatistics().createHistogram(new TH2F("pos_xvsy_real", "Position x vs y real", fReconstructionLayerRadius * 2 * 10 * 5, -fReconstructionLayerRadius, fReconstructionLayerRadius, fReconstructionLayerRadius * 2 * 10 * 5, fReconstructionLayerRadius, fReconstructionLayerRadius)); //10cm * 2 sides * 10mm * 5, 0.2mm acc;

  getStatistics().createHistogram(new TH1F("pos_r_1_monte", "Position r monte data", (fReconstructionLayerRadius + 15.) * 2 * 10 * 5, -fReconstructionLayerRadius, fReconstructionLayerRadius)); //10cm * 2 sides * 10mm * 5, 0.2mm acc;
  getStatistics().createHistogram(new TH1F("pos_r_2_monte", "Position r monte data", fReconstructionLayerRadius * 2 * 10 * 5, -fReconstructionLayerRadius, fReconstructionLayerRadius));
  getStatistics().createHistogram(new TH1F("pos_r_3_monte", "Position r monte data", fReconstructionLayerRadius * 2 * 10 * 5, -fReconstructionLayerRadius, fReconstructionLayerRadius));
  return true;
}

bool SinogramCreator::exec()
{
  std::vector<std::pair<SinogramCreatorTools::Point, SinogramCreatorTools::Point>> hitsVector;
  std::ifstream in("20_scin_455_radius.txt");
  float x1, y1, x2, y2;
  while (in.peek() != EOF) {
    in >> x1 >> y1 >> x2 >> y2;
    getStatistics().getObject<TH1F>("pos_x")->Fill(x1);
    getStatistics().getObject<TH1F>("pos_x")->Fill(x2);
    getStatistics().getObject<TH1F>("pos_y")->Fill(y1);
    getStatistics().getObject<TH1F>("pos_y")->Fill(y2);
    getStatistics().getObject<TH2F>("pos_xvsy")->Fill(x1, y1);
    getStatistics().getObject<TH2F>("pos_xvsy")->Fill(x2, y2);
    hitsVector.push_back(std::make_pair(std::make_pair(x1, y1), std::make_pair(x2, y2)));
  }
  int j = 0;
  unsigned int currentValueInSinogram = 0; // holds current bin value of sinogram
  float reconstructionAngleDiff = std::abs(fReconstructionEndAngle - fReconstructionStartAngle); // should be always positive

  unsigned int maxThetaNumber = std::ceil(reconstructionAngleDiff / fReconstructionAngleStep);
  unsigned int maxDistanceNumber = std::ceil(fReconstructionLayerRadius * 2 * (1.f / fReconstructionDistanceAccuracy)) + 1;
  if (fSinogram == nullptr) {
    fSinogram = new SinogramResultType(maxDistanceNumber, (std::vector<unsigned int>(maxThetaNumber)));
  }
  if (const auto& timeWindow = dynamic_cast<const JPetTimeWindow* const>(fEvent)) {
    unsigned int numberOfEventsInTimeWindow = timeWindow->getNumberOfEvents();
    for (unsigned int i = 0; i < numberOfEventsInTimeWindow; i++) {
      auto event = dynamic_cast<const JPetEvent&>(timeWindow->operator[](static_cast<int>(i)));
      auto hits = event.getHits();
      if (hits.size() == 2) {
        const auto& firstHit = hits[0];
        const auto& secondHit = hits[1];
        if (checkLayer(firstHit) && checkLayer(secondHit)) {
          for (float theta = fReconstructionStartAngle; theta < fReconstructionEndAngle; theta += fReconstructionAngleStep) {
            float x = fReconstructionLayerRadius * std::cos(theta * (M_PI / 180.f)); // calculate x,y positon of line with theta angle from line (0,0) = theta
            float y = fReconstructionLayerRadius * std::sin(theta * (M_PI / 180.f));
            getStatistics().getObject<TH2F>("pos_xvsy_real")->Fill(x, y);
            std::pair<float, float> intersectionPoint = SinogramCreatorTools::lineIntersection(std::make_pair(-x, -y), std::make_pair(x, y),
                std::make_pair(firstHit.getPosX(), firstHit.getPosY()), std::make_pair(secondHit.getPosX(), secondHit.getPosY())); //find intersection point
            if (intersectionPoint.first != std::numeric_limits<float>::max() && intersectionPoint.second != std::numeric_limits<float>::max()) { // check is there is intersection point
              float distance = SinogramCreatorTools::length2D(intersectionPoint.first, intersectionPoint.second);
              getStatistics().getObject<TH1F>("pos_r_1")->Fill(distance);
              if (distance >= fReconstructionLayerRadius) // if distance is greather then our max reconstuction layer radius, it cant be placed in sinogram
                continue;
              getStatistics().getObject<TH1F>("pos_r_2")->Fill(distance);
              if (intersectionPoint.first < 0.f)
                distance = -distance;
              getStatistics().getObject<TH1F>("pos_r_3")->Fill(distance);
              int distanceRound = std::floor((fReconstructionLayerRadius / fReconstructionDistanceAccuracy)
                                             + fReconstructionDistanceAccuracy)
                                  + std::floor((distance / fReconstructionDistanceAccuracy) + fReconstructionDistanceAccuracy); //clever way of rounding to nearest multipicity of accuracy digit and change it to int
              int thetaNumber = std::round(theta / fReconstructionAngleStep);                                                   // round because of floating point
              currentValueInSinogram = ++fSinogram->at(distanceRound).at(thetaNumber); // add to sinogram
              if (currentValueInSinogram >= fMaxValueInSinogram)
                fMaxValueInSinogram = currentValueInSinogram; // save max value of sinogram
              getStatistics().getObject<TH2I>("reconstuction_histogram")->Fill(distance, theta); //add to histogram
            }

            std::pair<float, float> intersectionPointMonteCarlo = SinogramCreatorTools::lineIntersection(std::make_pair(-x, -y), std::make_pair(x, y), hitsVector[j].first, hitsVector[j].second); //find intersection point
            if (intersectionPointMonteCarlo.first != std::numeric_limits<float>::max() && intersectionPointMonteCarlo.second != std::numeric_limits<float>::max()) {
              // check is there is intersection point
              float distance = SinogramCreatorTools::length2D(intersectionPointMonteCarlo.first, intersectionPointMonteCarlo.second);
              getStatistics().getObject<TH1F>("pos_r_1_monte")->Fill(distance);
              if (distance >= fReconstructionLayerRadius) // if distance is greather then our max reconstuction layer radius, it cant be placed in sinogram
                continue;
              getStatistics().getObject<TH1F>("pos_r_2_monte")->Fill(distance);
              if (intersectionPointMonteCarlo.first < 0.f)
                distance = -distance;
              getStatistics().getObject<TH1F>("pos_r_3_monte")->Fill(distance);
              int distanceRound = std::floor((fReconstructionLayerRadius / fReconstructionDistanceAccuracy) + fReconstructionDistanceAccuracy) + std::floor((distance / fReconstructionDistanceAccuracy) + fReconstructionDistanceAccuracy); //clever way of rounding to nearest multipicity of accuracy digit and change it to int
              int thetaNumber = std::round(theta / fReconstructionAngleStep);                                                                                // round because of floating point
              currentValueInSinogram = ++fSinogram->at(distanceRound).at(thetaNumber);                                                                                // add to sinogram
              if (currentValueInSinogram >= fMaxValueInSinogram)
                fMaxValueInSinogram = currentValueInSinogram;                                    // save max value of sinogram
              getStatistics().getObject<TH2I>("reconstuction_histogram_monte")->Fill(distance, theta); //add to histogram
            }
            j++;
          }
        }
      }
    }
  } else {
    ERROR("Returned event is not TimeWindow");
    return false;
  }
  return true;
}

bool SinogramCreator::checkLayer(const JPetHit& hit)
{
  return hit.getBarrelSlot().getLayer().getID() == 1;
}

bool SinogramCreator::terminate()
{
  std::ofstream res(fOutFileName);
  res << "P2" << std::endl;
  res << (*fSinogram)[0].size() << " " << fSinogram->size() << std::endl;
  res << fMaxValueInSinogram << std::endl;
  for (unsigned int i = 0; i < fSinogram->size(); i++) {
    for (unsigned int j = 0; j < (*fSinogram)[0].size(); j++) {
      res << (*fSinogram)[i][j] << " ";
    }
    res << std::endl;
  }
  res.close();
  return true;
}

void SinogramCreator::setUpOptions()
{
  auto opts = getOptions();
  if (isOptionSet(opts, kOutFileNameKey)) {
    fOutFileName = getOptionAsString(opts, kOutFileNameKey);
  }

  if (isOptionSet(opts, kReconstructionLayerRadiusKey)) {
    fReconstructionLayerRadius = getOptionAsFloat(opts, kReconstructionLayerRadiusKey);
  }

  if (isOptionSet(opts, kReconstructionStartAngle)) {
    fReconstructionStartAngle = getOptionAsFloat(opts, kReconstructionStartAngle);
  }

  if (isOptionSet(opts, kReconstructionEndAngle)) {
    fReconstructionEndAngle = getOptionAsFloat(opts, kReconstructionEndAngle);
  }

  if (isOptionSet(opts, kReconstructionDistanceAccuracy)) {
    fReconstructionDistanceAccuracy = getOptionAsFloat(opts, kReconstructionDistanceAccuracy);
  }

  if (isOptionSet(opts, kReconstructionAngleStep)) {
    fReconstructionAngleStep = getOptionAsFloat(opts, kReconstructionAngleStep);
  }
}
<commit_msg>Change distanceRound to SinogramCreatorTools' roundToNearestMultiplicity<commit_after>/**
 *  @copyright Copyright 2017 The J-PET Framework Authors. All rights reserved.
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may find a copy of the License in the LICENCE file.
 *
 * 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.
 *
 *  @file SinogramCreator.cpp
 */

#include "SinogramCreator.h"
#include <TH2I.h>
#include <TH2F.h>
#include <TH1I.h>
using namespace jpet_options_tools;

SinogramCreator::SinogramCreator(const char* name) : JPetUserTask(name) {}

SinogramCreator::~SinogramCreator() {}

bool SinogramCreator::init()
{
  setUpOptions();
  fOutputEvents = new JPetTimeWindow("JPetEvent");

  getStatistics().createHistogram(new TH2I("reconstuction_histogram",
                                  "reconstuction_histogram",
                                  std::ceil(fReconstructionLayerRadius * 2 * (1.f / fReconstructionDistanceAccuracy)) + 1, -fReconstructionLayerRadius, fReconstructionLayerRadius,
                                  std::ceil((fReconstructionEndAngle - fReconstructionStartAngle) / fReconstructionAngleStep), fReconstructionStartAngle, fReconstructionEndAngle));

  getStatistics().createHistogram(new TH2I("reconstuction_histogram_monte",
                                  "reconstuction_histogram_monte",
                                  std::ceil(fReconstructionLayerRadius * 2 * (1.f / fReconstructionDistanceAccuracy)) + 1, -fReconstructionLayerRadius, fReconstructionLayerRadius,
                                  std::ceil((fReconstructionEndAngle - fReconstructionStartAngle) / fReconstructionAngleStep), fReconstructionStartAngle, fReconstructionEndAngle));

  getStatistics().createHistogram(new TH1F("pos_x", "Position x monte carlo", fReconstructionLayerRadius * 2 * 10 * 5, -fReconstructionLayerRadius, fReconstructionLayerRadius)); //10cm * 2 sides * 10mm * 5, 0.2mm acc;
  getStatistics().createHistogram(new TH1F("pos_y", "Position y monte carlo", fReconstructionLayerRadius * 2 * 10 * 5, -fReconstructionLayerRadius, fReconstructionLayerRadius)); //10cm * 2 sides * 10mm * 5, 0.2mm acc;
  getStatistics().createHistogram(new TH2F("pos_xvsy", "Position x vs y monte carlo", 10 * 2 * 10 * 5, -10., 10., 10 * 2 * 10 * 5, -10., 10.)); //10cm * 2 sides * 10mm * 5, 0.2mm acc;

  getStatistics().createHistogram(new TH1F("pos_r_1", "Position r real data", (fReconstructionLayerRadius + 15.) * 2 * 10 * 5, -fReconstructionLayerRadius, fReconstructionLayerRadius)); //10cm * 2 sides * 10mm * 5, 0.2mm acc;
  getStatistics().createHistogram(new TH1F("pos_r_2", "Position r real data", fReconstructionLayerRadius * 2 * 10 * 5, -fReconstructionLayerRadius, fReconstructionLayerRadius));
  getStatistics().createHistogram(new TH1F("pos_r_3", "Position r real data", fReconstructionLayerRadius * 2 * 10 * 5, -fReconstructionLayerRadius, fReconstructionLayerRadius));

  getStatistics().createHistogram(new TH2F("pos_xvsy_real", "Position x vs y real", fReconstructionLayerRadius * 2 * 10 * 5, -fReconstructionLayerRadius, fReconstructionLayerRadius, fReconstructionLayerRadius * 2 * 10 * 5, fReconstructionLayerRadius, fReconstructionLayerRadius)); //10cm * 2 sides * 10mm * 5, 0.2mm acc;

  getStatistics().createHistogram(new TH1F("pos_r_1_monte", "Position r monte data", (fReconstructionLayerRadius + 15.) * 2 * 10 * 5, -fReconstructionLayerRadius, fReconstructionLayerRadius)); //10cm * 2 sides * 10mm * 5, 0.2mm acc;
  getStatistics().createHistogram(new TH1F("pos_r_2_monte", "Position r monte data", fReconstructionLayerRadius * 2 * 10 * 5, -fReconstructionLayerRadius, fReconstructionLayerRadius));
  getStatistics().createHistogram(new TH1F("pos_r_3_monte", "Position r monte data", fReconstructionLayerRadius * 2 * 10 * 5, -fReconstructionLayerRadius, fReconstructionLayerRadius));
  return true;
}

bool SinogramCreator::exec()
{
  std::vector<std::pair<SinogramCreatorTools::Point, SinogramCreatorTools::Point>> hitsVector;
  std::ifstream in("20_scin_455_radius.txt");
  float x1, y1, x2, y2;
  while (in.peek() != EOF) {
    in >> x1 >> y1 >> x2 >> y2;
    getStatistics().getObject<TH1F>("pos_x")->Fill(x1);
    getStatistics().getObject<TH1F>("pos_x")->Fill(x2);
    getStatistics().getObject<TH1F>("pos_y")->Fill(y1);
    getStatistics().getObject<TH1F>("pos_y")->Fill(y2);
    getStatistics().getObject<TH2F>("pos_xvsy")->Fill(x1, y1);
    getStatistics().getObject<TH2F>("pos_xvsy")->Fill(x2, y2);
    hitsVector.push_back(std::make_pair(std::make_pair(x1, y1), std::make_pair(x2, y2)));
  }
  int j = 0;
  unsigned int currentValueInSinogram = 0; // holds current bin value of sinogram
  float reconstructionAngleDiff = std::abs(fReconstructionEndAngle - fReconstructionStartAngle); // should be always positive

  unsigned int maxThetaNumber = std::ceil(reconstructionAngleDiff / fReconstructionAngleStep);
  unsigned int maxDistanceNumber = std::ceil(fReconstructionLayerRadius * 2 * (1.f / fReconstructionDistanceAccuracy)) + 1;
  if (fSinogram == nullptr) {
    fSinogram = new SinogramResultType(maxDistanceNumber, (std::vector<unsigned int>(maxThetaNumber)));
  }
  if (const auto& timeWindow = dynamic_cast<const JPetTimeWindow* const>(fEvent)) {
    unsigned int numberOfEventsInTimeWindow = timeWindow->getNumberOfEvents();
    for (unsigned int i = 0; i < numberOfEventsInTimeWindow; i++) {
      auto event = dynamic_cast<const JPetEvent&>(timeWindow->operator[](static_cast<int>(i)));
      auto hits = event.getHits();
      if (hits.size() == 2) {
        const auto& firstHit = hits[0];
        const auto& secondHit = hits[1];
        if (checkLayer(firstHit) && checkLayer(secondHit)) {
          for (float theta = fReconstructionStartAngle; theta < fReconstructionEndAngle; theta += fReconstructionAngleStep) {
            float x = fReconstructionLayerRadius * std::cos(theta * (M_PI / 180.f)); // calculate x,y positon of line with theta angle from line (0,0) = theta
            float y = fReconstructionLayerRadius * std::sin(theta * (M_PI / 180.f));
            getStatistics().getObject<TH2F>("pos_xvsy_real")->Fill(x, y);
            std::pair<float, float> intersectionPoint = SinogramCreatorTools::lineIntersection(std::make_pair(-x, -y), std::make_pair(x, y),
                std::make_pair(firstHit.getPosX(), firstHit.getPosY()), std::make_pair(secondHit.getPosX(), secondHit.getPosY())); //find intersection point
            if (intersectionPoint.first != std::numeric_limits<float>::max() && intersectionPoint.second != std::numeric_limits<float>::max()) { // check is there is intersection point
              float distance = SinogramCreatorTools::length2D(intersectionPoint.first, intersectionPoint.second);
              getStatistics().getObject<TH1F>("pos_r_1")->Fill(distance);
              if (distance >= fReconstructionLayerRadius) // if distance is greather then our max reconstuction layer radius, it cant be placed in sinogram
                continue;
              getStatistics().getObject<TH1F>("pos_r_2")->Fill(distance);
              if (intersectionPoint.first < 0.f)
                distance = -distance;
              getStatistics().getObject<TH1F>("pos_r_3")->Fill(distance);
              int distanceRound = SinogramCreatorTools::roundToNearesMultiplicity(distance, fReconstructionDistanceAccuracy, fReconstructionLayerRadius);
              int thetaNumber = std::round(theta / fReconstructionAngleStep);                                                   // round because of floating point
              currentValueInSinogram = ++fSinogram->at(distanceRound).at(thetaNumber); // add to sinogram
              if (currentValueInSinogram >= fMaxValueInSinogram)
                fMaxValueInSinogram = currentValueInSinogram; // save max value of sinogram
              getStatistics().getObject<TH2I>("reconstuction_histogram")->Fill(distance, theta); //add to histogram
            }

            std::pair<float, float> intersectionPointMonteCarlo = SinogramCreatorTools::lineIntersection(std::make_pair(-x, -y), std::make_pair(x, y), hitsVector[j].first, hitsVector[j].second); //find intersection point
            if (intersectionPointMonteCarlo.first != std::numeric_limits<float>::max() && intersectionPointMonteCarlo.second != std::numeric_limits<float>::max()) {
              // check is there is intersection point
              float distance = SinogramCreatorTools::length2D(intersectionPointMonteCarlo.first, intersectionPointMonteCarlo.second);
              getStatistics().getObject<TH1F>("pos_r_1_monte")->Fill(distance);
              if (distance >= fReconstructionLayerRadius) // if distance is greather then our max reconstuction layer radius, it cant be placed in sinogram
                continue;
              getStatistics().getObject<TH1F>("pos_r_2_monte")->Fill(distance);
              if (intersectionPointMonteCarlo.first < 0.f)
                distance = -distance;
              getStatistics().getObject<TH1F>("pos_r_3_monte")->Fill(distance);
              int distanceRound = SinogramCreatorTools::roundToNearesMultiplicity(distance, fReconstructionDistanceAccuracy, fReconstructionLayerRadius);
              int thetaNumber = std::round(theta / fReconstructionAngleStep);                                                                                // round because of floating point
              currentValueInSinogram = ++fSinogram->at(distanceRound).at(thetaNumber);                                                                                // add to sinogram
              if (currentValueInSinogram >= fMaxValueInSinogram)
                fMaxValueInSinogram = currentValueInSinogram;                                    // save max value of sinogram
              getStatistics().getObject<TH2I>("reconstuction_histogram_monte")->Fill(distance, theta); //add to histogram
            }
            j++;
          }
        }
      }
    }
  } else {
    ERROR("Returned event is not TimeWindow");
    return false;
  }
  return true;
}

bool SinogramCreator::checkLayer(const JPetHit& hit)
{
  return hit.getBarrelSlot().getLayer().getID() == 1;
}

bool SinogramCreator::terminate()
{
  std::ofstream res(fOutFileName);
  res << "P2" << std::endl;
  res << (*fSinogram)[0].size() << " " << fSinogram->size() << std::endl;
  res << fMaxValueInSinogram << std::endl;
  for (unsigned int i = 0; i < fSinogram->size(); i++) {
    for (unsigned int j = 0; j < (*fSinogram)[0].size(); j++) {
      res << (*fSinogram)[i][j] << " ";
    }
    res << std::endl;
  }
  res.close();
  return true;
}

void SinogramCreator::setUpOptions()
{
  auto opts = getOptions();
  if (isOptionSet(opts, kOutFileNameKey)) {
    fOutFileName = getOptionAsString(opts, kOutFileNameKey);
  }

  if (isOptionSet(opts, kReconstructionLayerRadiusKey)) {
    fReconstructionLayerRadius = getOptionAsFloat(opts, kReconstructionLayerRadiusKey);
  }

  if (isOptionSet(opts, kReconstructionStartAngle)) {
    fReconstructionStartAngle = getOptionAsFloat(opts, kReconstructionStartAngle);
  }

  if (isOptionSet(opts, kReconstructionEndAngle)) {
    fReconstructionEndAngle = getOptionAsFloat(opts, kReconstructionEndAngle);
  }

  if (isOptionSet(opts, kReconstructionDistanceAccuracy)) {
    fReconstructionDistanceAccuracy = getOptionAsFloat(opts, kReconstructionDistanceAccuracy);
  }

  if (isOptionSet(opts, kReconstructionAngleStep)) {
    fReconstructionAngleStep = getOptionAsFloat(opts, kReconstructionAngleStep);
  }
}
<|endoftext|>


<commit_before>#include "ribbonanalysis.h"
#include "ui_ribbonanalysis.h"

#include <QMenu>
#include <QDebug>

RibbonAnalysis::RibbonAnalysis(QWidget *parent) :
	RibbonWidget(parent),
	ui(new Ui::RibbonAnalysis)
{
	ui->setupUi(this);

	ui->bayesianPanel->hide();
	//ui->bayesianSeparator->hide();

	connect(ui->Descriptives, SIGNAL(clicked()), this, SLOT(itemSelected()));

	QMenu *menu;

	menu = new QMenu(this);
	menu->addAction(QString("Independent Samples T-Test"), this, SLOT(itemSelected()))->setObjectName("TTestIndependentSamples");
	menu->addAction(QString("Paired Samples T-Test"), this, SLOT(itemSelected()))->setObjectName("TTestPairedSamples");
	menu->addAction(QString("One Sample T-Test"), this, SLOT(itemSelected()))->setObjectName("TTestOneSample");

	menu->addSeparator();

	menu->addAction(QString("Bayesian Independent Samples T-Test"), this, SLOT(itemSelected()))->setObjectName("TTestBayesianIndependentSamples");
	menu->addAction(QString("Bayesian Paired Samples T-Test"), this, SLOT(itemSelected()))->setObjectName("TTestBayesianPairedSamples");
	menu->addAction(QString("Bayesian One Sample T-Test"), this, SLOT(itemSelected()))->setObjectName("TTestBayesianOneSample");

	ui->classicalTTestButton->setMenu(menu);

	menu = new QMenu(this);

	menu->addAction(QString("ANOVA"), this, SLOT(itemSelected()))->setObjectName("Anova");
	menu->addAction(QString("Repeated Measures ANOVA"), this, SLOT(itemSelected()))->setObjectName("AnovaRepeatedMeasuresShort");
	menu->addAction(QString("ANCOVA"), this, SLOT(itemSelected()))->setObjectName("Ancova");

	menu->addSeparator();

	menu->addAction(QString("Bayesian ANOVA"), this, SLOT(itemSelected()))->setObjectName("AnovaBayesian");
	menu->addAction(QString("Bayesian Repeated Measures ANOVA"), this, SLOT(itemSelected()))->setObjectName("AnovaRepeatedMeasuresBayesian");
	menu->addAction(QString("Bayesian ANCOVA"), this, SLOT(itemSelected()))->setObjectName("AncovaBayesian");

	ui->classicalAnovaButton->setMenu(menu);

	menu = new QMenu(this);

	menu->addAction(QString("Correlation Matrix"), this, SLOT(itemSelected()))->setObjectName("Correlation");
	menu->addAction(QString("Partial Correlation"), this, SLOT(itemSelected()))->setObjectName("CorrelationPartial");
	menu->addAction(QString("Linear Regression"), this, SLOT(itemSelected()))->setObjectName("RegressionLinear");

	menu->addSeparator();

	menu->addAction(QString("Bayesian Correlation Matrix"), this, SLOT(itemSelected()))->setObjectName("CorrelationBayesian");
	menu->addAction(QString("Bayesian Correlation Pairs"), this, SLOT(itemSelected()))->setObjectName("CorrelationBayesianPairs");
	menu->addAction(QString("Bayesian Linear Regression"), this, SLOT(itemSelected()))->setObjectName("RegressionLinearBayesian");

	ui->classicalRegressionButton->setMenu(menu);

	menu = new QMenu(this);

	menu->addAction(QString("Contingency Tables"), this, SLOT(itemSelected()))->setObjectName("Crosstabs");
	menu->addSeparator();
	menu->addAction(QString("Bayesian Contingency Tables"), this, SLOT(itemSelected()))->setObjectName("CrosstabsBayesian");

	ui->classicalCrosstabsButton->setMenu(menu);
}

RibbonAnalysis::~RibbonAnalysis()
{
	delete ui;
}
<commit_msg>Hiding unimplemented analyses<commit_after>#include "ribbonanalysis.h"
#include "ui_ribbonanalysis.h"

#include <QMenu>
#include <QDebug>

RibbonAnalysis::RibbonAnalysis(QWidget *parent) :
	RibbonWidget(parent),
	ui(new Ui::RibbonAnalysis)
{
	ui->setupUi(this);

	ui->bayesianPanel->hide();
	//ui->bayesianSeparator->hide();

	connect(ui->Descriptives, SIGNAL(clicked()), this, SLOT(itemSelected()));

	QMenu *menu;

	menu = new QMenu(this);
	menu->addAction(QString("Independent Samples T-Test"), this, SLOT(itemSelected()))->setObjectName("TTestIndependentSamples");
	menu->addAction(QString("Paired Samples T-Test"), this, SLOT(itemSelected()))->setObjectName("TTestPairedSamples");
	menu->addAction(QString("One Sample T-Test"), this, SLOT(itemSelected()))->setObjectName("TTestOneSample");

	menu->addSeparator();

	menu->addAction(QString("Bayesian Independent Samples T-Test"), this, SLOT(itemSelected()))->setObjectName("TTestBayesianIndependentSamples");
	menu->addAction(QString("Bayesian Paired Samples T-Test"), this, SLOT(itemSelected()))->setObjectName("TTestBayesianPairedSamples");
	menu->addAction(QString("Bayesian One Sample T-Test"), this, SLOT(itemSelected()))->setObjectName("TTestBayesianOneSample");

	ui->classicalTTestButton->setMenu(menu);

	menu = new QMenu(this);

	menu->addAction(QString("ANOVA"), this, SLOT(itemSelected()))->setObjectName("Anova");
	menu->addAction(QString("Repeated Measures ANOVA"), this, SLOT(itemSelected()))->setObjectName("AnovaRepeatedMeasuresShort");
	menu->addAction(QString("ANCOVA"), this, SLOT(itemSelected()))->setObjectName("Ancova");

	menu->addSeparator();

	menu->addAction(QString("Bayesian ANOVA"), this, SLOT(itemSelected()))->setObjectName("AnovaBayesian");
	menu->addAction(QString("Bayesian Repeated Measures ANOVA"), this, SLOT(itemSelected()))->setObjectName("AnovaRepeatedMeasuresBayesian");
	menu->addAction(QString("Bayesian ANCOVA"), this, SLOT(itemSelected()))->setObjectName("AncovaBayesian");

	ui->classicalAnovaButton->setMenu(menu);

	menu = new QMenu(this);

	menu->addAction(QString("Correlation Matrix"), this, SLOT(itemSelected()))->setObjectName("Correlation");
#ifdef QT_DEBUG
	menu->addAction(QString("Partial Correlation"), this, SLOT(itemSelected()))->setObjectName("CorrelationPartial");
#endif
	menu->addAction(QString("Linear Regression"), this, SLOT(itemSelected()))->setObjectName("RegressionLinear");

	menu->addSeparator();

	menu->addAction(QString("Bayesian Correlation Matrix"), this, SLOT(itemSelected()))->setObjectName("CorrelationBayesian");
#ifdef QT_DEBUG
	menu->addAction(QString("Bayesian Correlation Pairs"), this, SLOT(itemSelected()))->setObjectName("CorrelationBayesianPairs");
#endif
	menu->addAction(QString("Bayesian Linear Regression"), this, SLOT(itemSelected()))->setObjectName("RegressionLinearBayesian");

	ui->classicalRegressionButton->setMenu(menu);

	menu = new QMenu(this);

	menu->addAction(QString("Contingency Tables"), this, SLOT(itemSelected()))->setObjectName("Crosstabs");
	menu->addSeparator();
	menu->addAction(QString("Bayesian Contingency Tables"), this, SLOT(itemSelected()))->setObjectName("CrosstabsBayesian");

	ui->classicalCrosstabsButton->setMenu(menu);
}

RibbonAnalysis::~RibbonAnalysis()
{
	delete ui;
}
<|endoftext|>


<commit_before>/*
    Copyright (C) 2011  Lasath Fernando <kde@lasath.org>

    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., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
*/

#include "conversations-model.h"
#include "conversation.h"
#include "telepathy-text-observer.h"
#include <KDebug>
#include "conversation-target.h"
#include "messages-model.h"

class ConversationsModel::ConversationsModelPrivate
{
public:
    TelepathyTextObserver watcher;
    QList<Conversation*> conversations;
};

QVariant ConversationsModel::data ( const QModelIndex& index, int role ) const
{
    QVariant result;
    if(index.row() >= 0 && index.row() < d->conversations.count()) {
        Q_ASSERT(role == ConversationRole);
        result = QVariant::fromValue<Conversation*>(d->conversations[index.row()]);
        kDebug() << "returning value " << result;
    }
    return result;
}

int ConversationsModel::rowCount ( const QModelIndex& parent ) const
{
    return d->conversations.count();
}

ConversationsModel::ConversationsModel() :
    d(new ConversationsModelPrivate)
{
    QHash<int, QByteArray> roles;
    roles[ConversationRole] = "conversation";
    setRoleNames(roles);

    QObject::connect(&d->watcher, SIGNAL(newConversation(Conversation*)), SLOT(onInconmingConversation(Conversation*)));
}

void ConversationsModel::onInconmingConversation ( Conversation* newConvo )
{
    //check if conversation's channel is already being handled, if so replace it
    bool handled = false;
    Tp::TextChannelPtr newChannel = newConvo->model()->textChannel();
    if (!newChannel->targetHandleType() == Tp::HandleTypeNone) {

        //loop through all conversations checking for matches
        Q_FOREACH(Conversation *convo, d->conversations) {
            if (convo->target()->id() == newChannel->targetId() &&
                convo->model()->textChannel()->targetHandleType() == newChannel->targetHandleType()) {

                convo->model()->setTextChannel(newChannel);
                newConvo->deleteLater();
                handled = true;
                break;
            }
        }
    }

    if(!handled) {
        beginInsertRows(QModelIndex(), rowCount(), rowCount());
        d->conversations.append(newConvo);
        endInsertRows();
    }
}

ConversationsModel::~ConversationsModel()
{
    delete d;
}
<commit_msg>Fixed some more formatting.<commit_after>/*
    Copyright (C) 2011  Lasath Fernando <kde@lasath.org>

    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., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
*/

#include "conversations-model.h"
#include "conversation.h"
#include "telepathy-text-observer.h"
#include <KDebug>
#include "conversation-target.h"
#include "messages-model.h"

class ConversationsModel::ConversationsModelPrivate
{
public:
    TelepathyTextObserver watcher;
    QList<Conversation*> conversations;
};

QVariant ConversationsModel::data(const QModelIndex& index, int role) const
{
    QVariant result;
    if (index.row() >= 0 && index.row() < d->conversations.count()) {
        Q_ASSERT(role == ConversationRole);
        result = QVariant::fromValue<Conversation*>(d->conversations[index.row()]);
        kDebug() << "returning value " << result;
    }
    return result;
}

int ConversationsModel::rowCount(const QModelIndex& parent) const
{
    return d->conversations.count();
}

ConversationsModel::ConversationsModel() :
        d(new ConversationsModelPrivate)
{
    QHash<int, QByteArray> roles;
    roles[ConversationRole] = "conversation";
    setRoleNames(roles);

    QObject::connect(&d->watcher, SIGNAL(newConversation(Conversation*)), SLOT(onInconmingConversation(Conversation*)));
}

void ConversationsModel::onInconmingConversation(Conversation* newConvo)
{
    //check if conversation's channel is already being handled, if so replace it
    bool handled = false;
    Tp::TextChannelPtr newChannel = newConvo->model()->textChannel();
    if (!newChannel->targetHandleType() == Tp::HandleTypeNone) {

        //loop through all conversations checking for matches
        Q_FOREACH(Conversation *convo, d->conversations) {
            if (convo->target()->id() == newChannel->targetId() &&
                    convo->model()->textChannel()->targetHandleType() == newChannel->targetHandleType()) {

                convo->model()->setTextChannel(newChannel);
                newConvo->deleteLater();
                handled = true;
                break;
            }
        }
    }

    if (!handled) {
        beginInsertRows(QModelIndex(), rowCount(), rowCount());
        d->conversations.append(newConvo);
        endInsertRows();
    }
}

ConversationsModel::~ConversationsModel()
{
    delete d;
}
<|endoftext|>