<commit_before>/*
  Q Light Controller Plus
  uartwidget.cpp

  Copyright (C) Massimo Callegari

  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.txt

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

#include <QDebug>
#include <QTime>
#include <math.h>

#include <stropts.h>
#include <asm/termios.h>

#include "uartwidget.h"

#define DMX_MAB 16
#define DMX_BREAK 110

UARTWidget::UARTWidget(QSerialPortInfo &info, QObject *parent)
    : QThread(parent)
    , m_running(false)
    , m_granularity(Unknown)
{
    m_serialInfo = info;
}

UARTWidget::~UARTWidget()
{
    stop();
}

QString UARTWidget::name() const
{
    return m_serialInfo.portName();
}

bool UARTWidget::open(UARTWidget::WidgetMode mode)
{
    if (mode == Output)
        m_outputBuffer.fill(0, 513);
    else if (mode == Input)
        m_inputBuffer.fill(0, 513);

    m_mode |= mode;
    updateMode();

    return true;
}

bool UARTWidget::close(UARTWidget::WidgetMode mode)
{
    m_mode &= ~mode;
    updateMode();

    return true;
}

void UARTWidget::updateMode()
{
    if(m_mode != Closed && m_running == false)
        start();
    else if (m_mode == Closed && m_running == true)
        stop();
}

void UARTWidget::writeUniverse(const QByteArray &data)
{
    m_outputBuffer.replace(1, qMin(data.size(), m_outputBuffer.size()), data);
}

void UARTWidget::stop()
{
    if (isRunning() == true)
    {
        m_running = false;
        wait();
    }
}

void UARTWidget::run()
{
    qDebug() << "[UARTWidget] Thread created.";
    m_serialPort = new QSerialPort(m_serialInfo);

    m_serialPort->setBaudRate(250000);
    m_serialPort->setDataBits(QSerialPort::Data8);
    m_serialPort->setStopBits(QSerialPort::TwoStop);
    m_serialPort->setParity(QSerialPort::NoParity);
    m_serialPort->setFlowControl(QSerialPort::NoFlowControl);

    if (!m_serialPort->open(QIODevice::ReadWrite))
    {
        qWarning() << QString("[UARTWidget] Failed to open port %1, error: %2")
                      .arg(m_serialInfo.portName()).arg(m_serialPort->errorString());
        return;
    }

    int fd = m_serialPort->handle();

// If the "new" custom baud rate method is available, then use it to
// make sure the baud rate is properly set to 250Kbps

#if defined(TCGETS2)
    static const int rate = 250000;

    struct termios2 tio;  // linux-specific terminal stuff

    if (ioctl(fd, TCGETS2, &tio) < 0)
    {
        qDebug() << "[UARTWidget] Error in getting termios2 data";
        return;
    }

    tio.c_cflag &= ~CBAUD;
    tio.c_cflag |= BOTHER;
    tio.c_ispeed = rate;
    tio.c_ospeed = rate;  // set custom speed directly
    if (ioctl(fd, TCSETS2, &tio) < 0)
    {
        qDebug() << "[UARTWidget] Error in setting termios2 data";
        return;
    }
#endif

    m_serialPort->clear();
    m_serialPort->setRequestToSend(false);

    // One "official" DMX frame can take (1s/44Hz) = 23ms
    int frameTime = (int) floor(((double)1000 / 30) + (double)0.5);
    m_granularity = Bad;

    QTime time;
    time.start();
    usleep(1000);
    if (time.elapsed() <= 3)
        m_granularity = Good;

    m_running = true;
    while (m_running == true)
    {
        time.restart();

        if (m_mode & Output)
        {
            m_serialPort->setBreakEnabled(true);
            if(m_granularity == Good)
                usleep(DMX_BREAK);
            m_serialPort->setBreakEnabled(false);
            if(m_granularity == Good)
                usleep(DMX_MAB);

            if (m_serialPort->write(m_outputBuffer) == 0)
                qDebug() << "[UARTWidget] Error in writing output buffer";
            m_serialPort->waitForBytesWritten(10);

            // Sleep for the rest of the DMX frame time
            if (m_granularity == Good)
                while (time.elapsed() < frameTime) { usleep(1000); }
            else
                while (time.elapsed() < frameTime) { /* Busy sleep */ }
        }
    }
}
<commit_msg>fix uart plugin compilation on fedora<commit_after>/*
  Q Light Controller Plus
  uartwidget.cpp

  Copyright (C) Massimo Callegari

  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.txt

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

#include <QDebug>
#include <QTime>
#include <math.h>

#include <sys/ioctl.h>
#include <asm/termbits.h>

#include "uartwidget.h"

#define DMX_MAB 16
#define DMX_BREAK 110

UARTWidget::UARTWidget(QSerialPortInfo &info, QObject *parent)
    : QThread(parent)
    , m_running(false)
    , m_granularity(Unknown)
{
    m_serialInfo = info;
}

UARTWidget::~UARTWidget()
{
    stop();
}

QString UARTWidget::name() const
{
    return m_serialInfo.portName();
}

bool UARTWidget::open(UARTWidget::WidgetMode mode)
{
    if (mode == Output)
        m_outputBuffer.fill(0, 513);
    else if (mode == Input)
        m_inputBuffer.fill(0, 513);

    m_mode |= mode;
    updateMode();

    return true;
}

bool UARTWidget::close(UARTWidget::WidgetMode mode)
{
    m_mode &= ~mode;
    updateMode();

    return true;
}

void UARTWidget::updateMode()
{
    if(m_mode != Closed && m_running == false)
        start();
    else if (m_mode == Closed && m_running == true)
        stop();
}

void UARTWidget::writeUniverse(const QByteArray &data)
{
    m_outputBuffer.replace(1, qMin(data.size(), m_outputBuffer.size()), data);
}

void UARTWidget::stop()
{
    if (isRunning() == true)
    {
        m_running = false;
        wait();
    }
}

void UARTWidget::run()
{
    qDebug() << "[UARTWidget] Thread created.";
    m_serialPort = new QSerialPort(m_serialInfo);

    m_serialPort->setBaudRate(250000);
    m_serialPort->setDataBits(QSerialPort::Data8);
    m_serialPort->setStopBits(QSerialPort::TwoStop);
    m_serialPort->setParity(QSerialPort::NoParity);
    m_serialPort->setFlowControl(QSerialPort::NoFlowControl);

    if (!m_serialPort->open(QIODevice::ReadWrite))
    {
        qWarning() << QString("[UARTWidget] Failed to open port %1, error: %2")
                      .arg(m_serialInfo.portName()).arg(m_serialPort->errorString());
        return;
    }

    int fd = m_serialPort->handle();

// If the "new" custom baud rate method is available, then use it to
// make sure the baud rate is properly set to 250Kbps

#if defined(TCGETS2)
    static const int rate = 250000;

    struct termios2 tio;  // linux-specific terminal stuff

    if (ioctl(fd, TCGETS2, &tio) < 0)
    {
        qDebug() << "[UARTWidget] Error in getting termios2 data";
        return;
    }

    tio.c_cflag &= ~CBAUD;
    tio.c_cflag |= BOTHER;
    tio.c_ispeed = rate;
    tio.c_ospeed = rate;  // set custom speed directly
    if (ioctl(fd, TCSETS2, &tio) < 0)
    {
        qDebug() << "[UARTWidget] Error in setting termios2 data";
        return;
    }
#endif

    m_serialPort->clear();
    m_serialPort->setRequestToSend(false);

    // One "official" DMX frame can take (1s/44Hz) = 23ms
    int frameTime = (int) floor(((double)1000 / 30) + (double)0.5);
    m_granularity = Bad;

    QTime time;
    time.start();
    usleep(1000);
    if (time.elapsed() <= 3)
        m_granularity = Good;

    m_running = true;
    while (m_running == true)
    {
        time.restart();

        if (m_mode & Output)
        {
            m_serialPort->setBreakEnabled(true);
            if(m_granularity == Good)
                usleep(DMX_BREAK);
            m_serialPort->setBreakEnabled(false);
            if(m_granularity == Good)
                usleep(DMX_MAB);

            if (m_serialPort->write(m_outputBuffer) == 0)
                qDebug() << "[UARTWidget] Error in writing output buffer";
            m_serialPort->waitForBytesWritten(10);

            // Sleep for the rest of the DMX frame time
            if (m_granularity == Good)
                while (time.elapsed() < frameTime) { usleep(1000); }
            else
                while (time.elapsed() < frameTime) { /* Busy sleep */ }
        }
    }
}
<|endoftext|>


<commit_before>#include <boost/interprocess/sync/named_upgradable_mutex.hpp>
#include <boost/interprocess/shared_memory_object.hpp>
#include <boost/interprocess/mapped_region.hpp>
#include <boost/interprocess/sync/sharable_lock.hpp>
#include <boost/interprocess/sync/scoped_lock.hpp>
#include <string>
#include <map>
#include <util/izene_serialization.h>
#include <iostream>
#include <glog/logging.h>
#include <signal.h>

using namespace std;
using namespace boost;

#define SF1R_PROCESS_MUTEX_NAME "sf1r_named_mutex_for_process"
#define SF1R_PROCESS_SHARED_MEM_NAME "sf1r_shared_mem_for_process"
#define MAX_SHARED_SIZE 1024*32
#define SLOW_THRESHOLD 10
typedef std::map<std::string, size_t> Sf1rSharedSlowCounterT;

static volatile bool s_stop = false;
static sigset_t maskset;
static void* sig_thread(void *arg)
{
    sigset_t *set = (sigset_t *)arg;
    int s,sig;
    for(;;){
        s = sigwait(set, &sig);
        if(s != 0)
        {
            exit(1);
        }
        switch(sig)
        {
        case SIGINT:
        case SIGHUP:
        case SIGQUIT:
        case SIGABRT:
        case SIGTERM:
            std::cout << "got interrupt signal, begin quit" << std::endl;
            s_stop = true;
            break;
        default:
            break;
        }
    }
}

void init_sig_env()
{
    sigemptyset(&maskset);
    sigaddset(&maskset, SIGINT);
    sigaddset(&maskset, SIGHUP);
    sigaddset(&maskset, SIGQUIT);
    sigaddset(&maskset, SIGABRT);
    sigaddset(&maskset, SIGTERM);

    int ret;
    ret = pthread_sigmask(SIG_BLOCK, &maskset, NULL);
    if(ret != 0)
    {
        perror("failed to block signal");
        exit(1);
    }

    pthread_t thread;
    ret = pthread_create(&thread, NULL, &sig_thread, (void*)&maskset);
    if(ret != 0)
    {
        perror("failed to create signal handle thread");
        exit(1);
    }
}

void decreSlowCounterForAll()
{
    // decrease the slow counter period.
    using namespace boost::interprocess;
    try
    {
        named_upgradable_mutex mutex(open_only, SF1R_PROCESS_MUTEX_NAME);
        LOG(INFO) << "write lock begin : ";
        scoped_lock<named_upgradable_mutex> lock(mutex);

        LOG(INFO) << "write lock success.";
        shared_memory_object shm_obj(open_only, SF1R_PROCESS_SHARED_MEM_NAME, read_write);
        mapped_region region(shm_obj, read_write);

        Sf1rSharedSlowCounterT cur_shared_data;
        void *addr = region.get_address();
        size_t data_size = (*(int*)addr);
        if (data_size == 0)
            return;
        if (data_size >= MAX_SHARED_SIZE - sizeof(int))
        {
            LOG(ERROR) << "the data_size is larger than shared memory size :" << data_size;
            (*(int*)addr) = 0;
            std::memset((char*)addr + sizeof(int), 0, region.get_size() - sizeof(int));
            region.flush(0, region.get_size());
            return;
        }
        izenelib::util::izene_deserialization<Sf1rSharedSlowCounterT> izdeserial((const char*)addr + sizeof(int), data_size);
        izdeserial.read_image(cur_shared_data);
        Sf1rSharedSlowCounterT::iterator it;
        it = cur_shared_data.begin();
        while(it != cur_shared_data.end())
        {
            if (it->second > 0)
                (it->second)--;
            ++it;
        }
        LOG(INFO) << "current slow counter size :" << cur_shared_data.size();

        char* buf;
        izenelib::util::izene_serialization<Sf1rSharedSlowCounterT> izs(cur_shared_data);
        izs.write_image(buf, data_size);
        if (data_size >= MAX_SHARED_SIZE - sizeof(int))
        {
            LOG(ERROR) << "shared data is too large to write." << std::endl;
            return;
        }
        (*(int*)addr) = (int)data_size;
        memcpy((char*)addr + sizeof(int), buf, data_size);
        region.flush(0, region.get_size());
    }
    catch(const std::exception& e)
    {
        LOG(ERROR) << "write shared memory failed : " << e.what() << std::endl;
        return;
    }
}

void checking_func()
{
    while(!s_stop)
    {
        struct timespec req, rem;
        req.tv_sec = 20;
        req.tv_nsec = 0;

        while(0 != nanosleep(&req, &rem))
        {
            if (errno == EINTR)
                req = rem;
            else
            {
                perror("sleep error.");
                break;
            }
        }
        LOG(INFO) << "decreasing slow counter period." << std::endl;
        decreSlowCounterForAll();
    }
}

int
main(int argc, char *argv[])
{
    init_sig_env();
    using namespace boost::interprocess;
    shared_memory_object::remove(SF1R_PROCESS_SHARED_MEM_NAME);
    named_upgradable_mutex::remove(SF1R_PROCESS_MUTEX_NAME);

    shared_memory_object shm_obj(create_only, SF1R_PROCESS_SHARED_MEM_NAME, read_write);
    shm_obj.truncate(MAX_SHARED_SIZE);

    {
        mapped_region region(shm_obj, read_write);
        LOG(INFO) << "init shared memory size : " << region.get_size();
    }
    named_upgradable_mutex mutex(create_only, SF1R_PROCESS_MUTEX_NAME);

    LOG(INFO) << "shared memory master started. ";
    boost::thread checking_thread(boost::bind(&checking_func));
    checking_thread.join();
    LOG(INFO) << "shared data master quiting." << std::endl;
    shared_memory_object::remove(SF1R_PROCESS_SHARED_MEM_NAME);
    named_upgradable_mutex::remove(SF1R_PROCESS_MUTEX_NAME);
    return 0;
}
<commit_msg>try to fix shared memory if it is corrupted.<commit_after>#include <boost/interprocess/sync/named_upgradable_mutex.hpp>
#include <boost/interprocess/shared_memory_object.hpp>
#include <boost/interprocess/mapped_region.hpp>
#include <boost/interprocess/sync/sharable_lock.hpp>
#include <boost/interprocess/sync/scoped_lock.hpp>
#include <string>
#include <map>
#include <util/izene_serialization.h>
#include <iostream>
#include <glog/logging.h>
#include <signal.h>

using namespace std;
using namespace boost;

#define SF1R_PROCESS_MUTEX_NAME "sf1r_named_mutex_for_process"
#define SF1R_PROCESS_SHARED_MEM_NAME "sf1r_shared_mem_for_process"
#define MAX_SHARED_SIZE 1024*32
#define SLOW_THRESHOLD 10
typedef std::map<std::string, size_t> Sf1rSharedSlowCounterT;

static volatile bool s_stop = false;
static sigset_t maskset;
static void* sig_thread(void *arg)
{
    sigset_t *set = (sigset_t *)arg;
    int s,sig;
    for(;;){
        s = sigwait(set, &sig);
        if(s != 0)
        {
            exit(1);
        }
        switch(sig)
        {
        case SIGINT:
        case SIGHUP:
        case SIGQUIT:
        case SIGABRT:
        case SIGTERM:
            std::cout << "got interrupt signal, begin quit" << std::endl;
            s_stop = true;
            break;
        default:
            break;
        }
    }
}

void init_sig_env()
{
    sigemptyset(&maskset);
    sigaddset(&maskset, SIGINT);
    sigaddset(&maskset, SIGHUP);
    sigaddset(&maskset, SIGQUIT);
    sigaddset(&maskset, SIGABRT);
    sigaddset(&maskset, SIGTERM);

    int ret;
    ret = pthread_sigmask(SIG_BLOCK, &maskset, NULL);
    if(ret != 0)
    {
        perror("failed to block signal");
        exit(1);
    }

    pthread_t thread;
    ret = pthread_create(&thread, NULL, &sig_thread, (void*)&maskset);
    if(ret != 0)
    {
        perror("failed to create signal handle thread");
        exit(1);
    }
}

void decreSlowCounterForAll()
{
    // decrease the slow counter period.
    using namespace boost::interprocess;
    bool is_locked = false;
    try
    {
        named_upgradable_mutex mutex(open_only, SF1R_PROCESS_MUTEX_NAME);
        LOG(INFO) << "write lock begin : ";
        scoped_lock<named_upgradable_mutex> lock(mutex);

        is_locked = true;
        LOG(INFO) << "write lock success.";
        shared_memory_object shm_obj(open_only, SF1R_PROCESS_SHARED_MEM_NAME, read_write);
        mapped_region region(shm_obj, read_write);

        Sf1rSharedSlowCounterT cur_shared_data;
        void *addr = region.get_address();
        size_t data_size = (*(int*)addr);
        if (data_size == 0)
            return;
        if (data_size >= MAX_SHARED_SIZE - sizeof(int))
        {
            LOG(ERROR) << "the data_size is larger than shared memory size :" << data_size;
            (*(int*)addr) = 0;
            std::memset((char*)addr + sizeof(int), 0, region.get_size() - sizeof(int));
            region.flush(0, region.get_size());
            return;
        }
        izenelib::util::izene_deserialization<Sf1rSharedSlowCounterT> izdeserial((const char*)addr + sizeof(int), data_size);
        izdeserial.read_image(cur_shared_data);
        Sf1rSharedSlowCounterT::iterator it;
        it = cur_shared_data.begin();
        while(it != cur_shared_data.end())
        {
            if (it->second > 0)
                (it->second)--;
            ++it;
        }
        LOG(INFO) << "current slow counter size :" << cur_shared_data.size();

        char* buf;
        izenelib::util::izene_serialization<Sf1rSharedSlowCounterT> izs(cur_shared_data);
        izs.write_image(buf, data_size);
        if (data_size >= MAX_SHARED_SIZE - sizeof(int))
        {
            LOG(ERROR) << "shared data is too large to write." << std::endl;
            return;
        }
        (*(int*)addr) = (int)data_size;
        memcpy((char*)addr + sizeof(int), buf, data_size);
        region.flush(0, region.get_size());
    }
    catch(const std::exception& e)
    {
        LOG(ERROR) << "write shared memory failed : " << e.what() << std::endl;
        try
        {
            if (!is_locked)
            {
                LOG(ERROR) << "the lock may corrupt!";
                named_upgradable_mutex::remove(SF1R_PROCESS_MUTEX_NAME);
                named_upgradable_mutex mutex(create_only, SF1R_PROCESS_MUTEX_NAME);
            }
            else
            {
                LOG(ERROR) << "the shared memory may corrupt!";
                shared_memory_object::remove(SF1R_PROCESS_SHARED_MEM_NAME);
                shared_memory_object shm_obj(create_only, SF1R_PROCESS_SHARED_MEM_NAME, read_write);
                shm_obj.truncate(MAX_SHARED_SIZE);
            }
        }catch(const std::exception& e2){
            LOG(ERROR) << "try fix shared memory failed: " << e2.what();
        }
        return;
    }
}

void checking_func()
{
    while(!s_stop)
    {
        struct timespec req, rem;
        req.tv_sec = 20;
        req.tv_nsec = 0;

        while(0 != nanosleep(&req, &rem))
        {
            if (errno == EINTR)
                req = rem;
            else
            {
                perror("sleep error.");
                break;
            }
        }
        LOG(INFO) << "decreasing slow counter period." << std::endl;
        decreSlowCounterForAll();
    }
}

int
main(int argc, char *argv[])
{
    init_sig_env();
    using namespace boost::interprocess;
    shared_memory_object::remove(SF1R_PROCESS_SHARED_MEM_NAME);
    named_upgradable_mutex::remove(SF1R_PROCESS_MUTEX_NAME);

    shared_memory_object shm_obj(create_only, SF1R_PROCESS_SHARED_MEM_NAME, read_write);
    shm_obj.truncate(MAX_SHARED_SIZE);

    {
        mapped_region region(shm_obj, read_write);
        LOG(INFO) << "init shared memory size : " << region.get_size();
    }
    named_upgradable_mutex mutex(create_only, SF1R_PROCESS_MUTEX_NAME);

    LOG(INFO) << "shared memory master started. ";
    boost::thread checking_thread(boost::bind(&checking_func));
    checking_thread.join();
    LOG(INFO) << "shared data master quiting." << std::endl;
    shared_memory_object::remove(SF1R_PROCESS_SHARED_MEM_NAME);
    named_upgradable_mutex::remove(SF1R_PROCESS_MUTEX_NAME);
    return 0;
}
<|endoftext|>


<commit_before>/*
 * LinkPredictionGTest.cpp
 *
 *  Created on: 07.12.2014
 *      Author: Kolja Esders (kolja.esders@student.kit.edu)
 */

#ifndef NOGTEST

#include <chrono>

#include "LinkPredictionGTest.h"
#include "../../io/METISGraphReader.h"
#include "../KatzIndex.h"
#include "../CommonNeighborsIndex.h"
#include "../JaccardIndex.h"
#include "../ROCMetric.h"
#include "../PrecisionRecallMetric.h"
#include "../RandomLinkSampler.h"
#include "../KFoldCrossValidator.h"
#include "../MissingLinksFinder.h"
#include "../UDegreeIndex.h"
#include "../VDegreeIndex.h"
#include "../LinkThresholder.h"
#include "../TotalNeighborsIndex.h"
#include "../NeighborsMeasureIndex.h"
#include "../SameCommunityIndex.h"
#include "../PredictionsSorter.h"

namespace NetworKit {

LinkPredictionGTest::LinkPredictionGTest() : G(7) {
}

void LinkPredictionGTest::SetUp() {
  G.addEdge(0, 1);
  G.addEdge(0, 3);
  G.addEdge(1, 2);
  G.addEdge(1, 4);
  G.addEdge(2, 3);
  G.addEdge(2, 4);
  G.addEdge(2, 5);
  G.addEdge(3, 4);
  G.addEdge(3, 5);
  G.addEdge(4, 5);
  trainingGraph = G;
  trainingGraph.removeEdge(0, 1);
  trainingGraph.removeEdge(2, 4);
  trainingGraph.removeEdge(3, 5);
  missingLinks = MissingLinksFinder(trainingGraph).findAtDistance(2);
  CommonNeighborsIndex cn(trainingGraph);
  predictions = cn.runOn(missingLinks);
  PredictionsSorter::sortByScore(predictions);
}

TEST_F(LinkPredictionGTest, testCommonNeighborsIndexRunOn) {
  EXPECT_EQ(6, predictions.size());
  EXPECT_EQ(2, predictions[0].first.first); EXPECT_EQ(4, predictions[0].first.second); EXPECT_EQ(3, predictions[0].second);
  EXPECT_EQ(1, predictions[1].first.first); EXPECT_EQ(3, predictions[1].first.second); EXPECT_EQ(2, predictions[1].second);
  EXPECT_EQ(1, predictions[2].first.first); EXPECT_EQ(5, predictions[2].first.second); EXPECT_EQ(2, predictions[2].second);
  EXPECT_EQ(3, predictions[3].first.first); EXPECT_EQ(5, predictions[3].first.second); EXPECT_EQ(2, predictions[3].second);
  EXPECT_EQ(0, predictions[4].first.first); EXPECT_EQ(2, predictions[4].first.second); EXPECT_EQ(1, predictions[4].second);
  EXPECT_EQ(0, predictions[5].first.first); EXPECT_EQ(4, predictions[5].first.second); EXPECT_EQ(1, predictions[5].second);
}

TEST_F(LinkPredictionGTest, testMissingLinksFinderDistanceTwo) {
  EXPECT_EQ(6, missingLinks.size());
  EXPECT_EQ(0, missingLinks[0].first); EXPECT_EQ(2, missingLinks[0].second);
  EXPECT_EQ(0, missingLinks[1].first); EXPECT_EQ(4, missingLinks[1].second);
  EXPECT_EQ(1, missingLinks[2].first); EXPECT_EQ(3, missingLinks[2].second);
  EXPECT_EQ(1, missingLinks[3].first); EXPECT_EQ(5, missingLinks[3].second);
  EXPECT_EQ(2, missingLinks[4].first); EXPECT_EQ(4, missingLinks[4].second);
  EXPECT_EQ(3, missingLinks[5].first); EXPECT_EQ(5, missingLinks[5].second);
}

TEST_F(LinkPredictionGTest, testMissingLinksFinderDistanceThree) {
  std::vector<std::pair<node, node>> hopThreeMissingLinks = MissingLinksFinder(trainingGraph).findAtDistance(3);
  EXPECT_EQ(2, hopThreeMissingLinks.size());
  EXPECT_EQ(0, hopThreeMissingLinks[0].first); EXPECT_EQ(1, hopThreeMissingLinks[0].second);
  EXPECT_EQ(0, hopThreeMissingLinks[1].first); EXPECT_EQ(5, hopThreeMissingLinks[1].second);
}

TEST_F(LinkPredictionGTest, testLinkThresholderByScore) {
  std::vector<std::pair<node, node>> selectedLinks;
  selectedLinks = LinkThresholder::byScore(predictions, 2);
  EXPECT_EQ(4, selectedLinks.size());
  EXPECT_EQ(1, selectedLinks[0].first); EXPECT_EQ(3, selectedLinks[0].second);
  EXPECT_EQ(1, selectedLinks[1].first); EXPECT_EQ(5, selectedLinks[1].second);
  EXPECT_EQ(2, selectedLinks[2].first); EXPECT_EQ(4, selectedLinks[2].second);
  EXPECT_EQ(3, selectedLinks[3].first); EXPECT_EQ(5, selectedLinks[3].second);
}

TEST_F(LinkPredictionGTest, testLinkThresholderByCount) {
  std::vector<std::pair<node, node>> selectedLinks;
  selectedLinks = LinkThresholder::byCount(predictions, 5);
  EXPECT_EQ(5, selectedLinks.size());
  EXPECT_EQ(0, selectedLinks[0].first); EXPECT_EQ(2, selectedLinks[0].second);
  EXPECT_EQ(1, selectedLinks[1].first); EXPECT_EQ(3, selectedLinks[1].second);
  EXPECT_EQ(1, selectedLinks[2].first); EXPECT_EQ(5, selectedLinks[2].second);
  EXPECT_EQ(2, selectedLinks[3].first); EXPECT_EQ(4, selectedLinks[3].second);
  EXPECT_EQ(3, selectedLinks[4].first); EXPECT_EQ(5, selectedLinks[4].second);
}

TEST_F(LinkPredictionGTest, testLinkThresholderByPercentage) {
  std::vector<std::pair<node, node>> selectedLinks;
  selectedLinks = LinkThresholder::byPercentage(predictions, 0.5);
  EXPECT_EQ(3, selectedLinks.size());
  EXPECT_EQ(1, selectedLinks[0].first); EXPECT_EQ(3, selectedLinks[0].second);
  EXPECT_EQ(1, selectedLinks[1].first); EXPECT_EQ(5, selectedLinks[1].second);
  EXPECT_EQ(2, selectedLinks[2].first); EXPECT_EQ(4, selectedLinks[2].second);
}

TEST_F(LinkPredictionGTest, testTrainingGraphGenerator) {
  Graph trainingGraph = RandomLinkSampler::byPercentage(G, 0.7);
  EXPECT_EQ(7, trainingGraph.numberOfEdges());
}

TEST_F(LinkPredictionGTest, testUDegreeIndexRun) {
  UDegreeIndex uDegreeIndex(G);
  EXPECT_EQ(2, uDegreeIndex.run(0, 3));
  EXPECT_EQ(3, uDegreeIndex.run(1, 0));
  EXPECT_EQ(4, uDegreeIndex.run(2, 3));
  EXPECT_EQ(4, uDegreeIndex.run(3, 4));
  EXPECT_EQ(4, uDegreeIndex.run(4, 5));
  EXPECT_EQ(3, uDegreeIndex.run(5, 4));
}

TEST_F(LinkPredictionGTest, testVDegreeIndexRun) {
  VDegreeIndex vDegreeIndex(G);
  EXPECT_EQ(2, vDegreeIndex.run(3, 0));
  EXPECT_EQ(3, vDegreeIndex.run(0, 1));
  EXPECT_EQ(4, vDegreeIndex.run(3, 2));
  EXPECT_EQ(4, vDegreeIndex.run(4, 3));
  EXPECT_EQ(4, vDegreeIndex.run(5, 4));
  EXPECT_EQ(3, vDegreeIndex.run(4, 5));
}

TEST_F(LinkPredictionGTest, testTotalNeighborsIndexRun) {
  TotalNeighborsIndex totalNeighborsIndex(trainingGraph);
  EXPECT_EQ(3, totalNeighborsIndex.run(0, 2));
  EXPECT_EQ(3, totalNeighborsIndex.run(0, 4));
  EXPECT_EQ(3, totalNeighborsIndex.run(1, 3));
  EXPECT_EQ(2, totalNeighborsIndex.run(1, 5));
  EXPECT_EQ(3, totalNeighborsIndex.run(2, 4));
  EXPECT_EQ(3, totalNeighborsIndex.run(3, 5));
}

TEST_F(LinkPredictionGTest, testNeighborsMeasureIndexRun) {
  NeighborsMeasureIndex neighborsMeasureIndex(trainingGraph);
  EXPECT_EQ(1, neighborsMeasureIndex.run(0, 2));
  EXPECT_EQ(1, neighborsMeasureIndex.run(0, 4));
  EXPECT_EQ(2, neighborsMeasureIndex.run(1, 3));
  EXPECT_EQ(2, neighborsMeasureIndex.run(1, 5));
  EXPECT_EQ(3, neighborsMeasureIndex.run(2, 4));
  EXPECT_EQ(2, neighborsMeasureIndex.run(3, 5));
}

TEST_F(LinkPredictionGTest, testROCMetric) {
  ROCMetric roc(G);
  std::pair<std::vector<double>, std::vector<double>> curve = roc.getCurve(predictions);
  double auc = roc.getAreaUnderCurve();
  EXPECT_EQ(auc, 0.8125);
  EXPECT_EQ(0, curve.first[0]); EXPECT_EQ(0.5, curve.second[0]);
  EXPECT_EQ(0.25, curve.first[1]); EXPECT_EQ(0.5, curve.second[1]);
  EXPECT_EQ(0.5, curve.first[2]); EXPECT_EQ(1, curve.second[2]);
  EXPECT_EQ(0.75, curve.first[3]); EXPECT_EQ(1, curve.second[3]);
  EXPECT_EQ(1, curve.first[4]); EXPECT_EQ(1, curve.second[4]);
}

TEST_F(LinkPredictionGTest, testPRMetric) {
  PrecisionRecallMetric pr(G);
  std::pair<std::vector<double>, std::vector<double>> curve = pr.getCurve(predictions);
  double auc = pr.getAreaUnderCurve();
  EXPECT_EQ(auc, 0.5);
  EXPECT_EQ(0, curve.first[0]); EXPECT_EQ(1, curve.second[0]);
  EXPECT_EQ(0.5, curve.first[1]); EXPECT_EQ(1.0 / 3, curve.second[1]);
  EXPECT_EQ(1, curve.first[2]); EXPECT_EQ(1.0 / 3, curve.second[2]);
}

TEST_F(LinkPredictionGTest, testTenFoldCrossValidation) {
  METISGraphReader graphReader;
  Graph newG = graphReader.read("input/jazz.graph");
  ROCMetric roc(newG);
  CommonNeighborsIndex cn;
  KFoldCrossValidator validator(newG, &cn, &roc);
  double averageAUC = validator.crossValidate(10);
  EXPECT_NEAR(0.89, averageAUC, 0.05);
}

TEST_F(LinkPredictionGTest, testKatzRunOnOrdering) {
  METISGraphReader graphReader;
  Graph newG = graphReader.read("input/jazz.graph");
  KatzIndex katz(newG);
  Graph trainingGraph = RandomLinkSampler::byPercentage(newG, 0.7);
  std::vector<std::pair<node, node>> nodePairs = MissingLinksFinder(trainingGraph).findAtDistance(2);
  std::vector<std::pair<std::pair<node, node>, double>> preds = katz.runOn(missingLinks);
  for (index i = 0; i < preds.size() - 1; ++i) {
    EXPECT_TRUE(preds[i].first.first < preds[i+1].first.first || preds[i].first.second < preds[i+1].first.second);
  }
}

} // namespace NetworKit

#endif /* NOGTEST */<commit_msg>Removed deprecated test<commit_after>/*
 * LinkPredictionGTest.cpp
 *
 *  Created on: 07.12.2014
 *      Author: Kolja Esders (kolja.esders@student.kit.edu)
 */

#ifndef NOGTEST

#include <chrono>

#include "LinkPredictionGTest.h"
#include "../../io/METISGraphReader.h"
#include "../KatzIndex.h"
#include "../CommonNeighborsIndex.h"
#include "../JaccardIndex.h"
#include "../ROCMetric.h"
#include "../PrecisionRecallMetric.h"
#include "../RandomLinkSampler.h"
#include "../MissingLinksFinder.h"
#include "../UDegreeIndex.h"
#include "../VDegreeIndex.h"
#include "../LinkThresholder.h"
#include "../TotalNeighborsIndex.h"
#include "../NeighborsMeasureIndex.h"
#include "../SameCommunityIndex.h"
#include "../PredictionsSorter.h"

namespace NetworKit {

LinkPredictionGTest::LinkPredictionGTest() : G(7) {
}

void LinkPredictionGTest::SetUp() {
  G.addEdge(0, 1);
  G.addEdge(0, 3);
  G.addEdge(1, 2);
  G.addEdge(1, 4);
  G.addEdge(2, 3);
  G.addEdge(2, 4);
  G.addEdge(2, 5);
  G.addEdge(3, 4);
  G.addEdge(3, 5);
  G.addEdge(4, 5);
  trainingGraph = G;
  trainingGraph.removeEdge(0, 1);
  trainingGraph.removeEdge(2, 4);
  trainingGraph.removeEdge(3, 5);
  missingLinks = MissingLinksFinder(trainingGraph).findAtDistance(2);
  CommonNeighborsIndex cn(trainingGraph);
  predictions = cn.runOn(missingLinks);
  PredictionsSorter::sortByScore(predictions);
}

TEST_F(LinkPredictionGTest, testCommonNeighborsIndexRunOn) {
  EXPECT_EQ(6, predictions.size());
  EXPECT_EQ(2, predictions[0].first.first); EXPECT_EQ(4, predictions[0].first.second); EXPECT_EQ(3, predictions[0].second);
  EXPECT_EQ(1, predictions[1].first.first); EXPECT_EQ(3, predictions[1].first.second); EXPECT_EQ(2, predictions[1].second);
  EXPECT_EQ(1, predictions[2].first.first); EXPECT_EQ(5, predictions[2].first.second); EXPECT_EQ(2, predictions[2].second);
  EXPECT_EQ(3, predictions[3].first.first); EXPECT_EQ(5, predictions[3].first.second); EXPECT_EQ(2, predictions[3].second);
  EXPECT_EQ(0, predictions[4].first.first); EXPECT_EQ(2, predictions[4].first.second); EXPECT_EQ(1, predictions[4].second);
  EXPECT_EQ(0, predictions[5].first.first); EXPECT_EQ(4, predictions[5].first.second); EXPECT_EQ(1, predictions[5].second);
}

TEST_F(LinkPredictionGTest, testMissingLinksFinderDistanceTwo) {
  EXPECT_EQ(6, missingLinks.size());
  EXPECT_EQ(0, missingLinks[0].first); EXPECT_EQ(2, missingLinks[0].second);
  EXPECT_EQ(0, missingLinks[1].first); EXPECT_EQ(4, missingLinks[1].second);
  EXPECT_EQ(1, missingLinks[2].first); EXPECT_EQ(3, missingLinks[2].second);
  EXPECT_EQ(1, missingLinks[3].first); EXPECT_EQ(5, missingLinks[3].second);
  EXPECT_EQ(2, missingLinks[4].first); EXPECT_EQ(4, missingLinks[4].second);
  EXPECT_EQ(3, missingLinks[5].first); EXPECT_EQ(5, missingLinks[5].second);
}

TEST_F(LinkPredictionGTest, testMissingLinksFinderDistanceThree) {
  std::vector<std::pair<node, node>> hopThreeMissingLinks = MissingLinksFinder(trainingGraph).findAtDistance(3);
  EXPECT_EQ(2, hopThreeMissingLinks.size());
  EXPECT_EQ(0, hopThreeMissingLinks[0].first); EXPECT_EQ(1, hopThreeMissingLinks[0].second);
  EXPECT_EQ(0, hopThreeMissingLinks[1].first); EXPECT_EQ(5, hopThreeMissingLinks[1].second);
}

TEST_F(LinkPredictionGTest, testLinkThresholderByScore) {
  std::vector<std::pair<node, node>> selectedLinks;
  selectedLinks = LinkThresholder::byScore(predictions, 2);
  EXPECT_EQ(4, selectedLinks.size());
  EXPECT_EQ(1, selectedLinks[0].first); EXPECT_EQ(3, selectedLinks[0].second);
  EXPECT_EQ(1, selectedLinks[1].first); EXPECT_EQ(5, selectedLinks[1].second);
  EXPECT_EQ(2, selectedLinks[2].first); EXPECT_EQ(4, selectedLinks[2].second);
  EXPECT_EQ(3, selectedLinks[3].first); EXPECT_EQ(5, selectedLinks[3].second);
}

TEST_F(LinkPredictionGTest, testLinkThresholderByCount) {
  std::vector<std::pair<node, node>> selectedLinks;
  selectedLinks = LinkThresholder::byCount(predictions, 5);
  EXPECT_EQ(5, selectedLinks.size());
  EXPECT_EQ(0, selectedLinks[0].first); EXPECT_EQ(2, selectedLinks[0].second);
  EXPECT_EQ(1, selectedLinks[1].first); EXPECT_EQ(3, selectedLinks[1].second);
  EXPECT_EQ(1, selectedLinks[2].first); EXPECT_EQ(5, selectedLinks[2].second);
  EXPECT_EQ(2, selectedLinks[3].first); EXPECT_EQ(4, selectedLinks[3].second);
  EXPECT_EQ(3, selectedLinks[4].first); EXPECT_EQ(5, selectedLinks[4].second);
}

TEST_F(LinkPredictionGTest, testLinkThresholderByPercentage) {
  std::vector<std::pair<node, node>> selectedLinks;
  selectedLinks = LinkThresholder::byPercentage(predictions, 0.5);
  EXPECT_EQ(3, selectedLinks.size());
  EXPECT_EQ(1, selectedLinks[0].first); EXPECT_EQ(3, selectedLinks[0].second);
  EXPECT_EQ(1, selectedLinks[1].first); EXPECT_EQ(5, selectedLinks[1].second);
  EXPECT_EQ(2, selectedLinks[2].first); EXPECT_EQ(4, selectedLinks[2].second);
}

TEST_F(LinkPredictionGTest, testTrainingGraphGenerator) {
  Graph trainingGraph = RandomLinkSampler::byPercentage(G, 0.7);
  EXPECT_EQ(7, trainingGraph.numberOfEdges());
}

TEST_F(LinkPredictionGTest, testUDegreeIndexRun) {
  UDegreeIndex uDegreeIndex(G);
  EXPECT_EQ(2, uDegreeIndex.run(0, 3));
  EXPECT_EQ(3, uDegreeIndex.run(1, 0));
  EXPECT_EQ(4, uDegreeIndex.run(2, 3));
  EXPECT_EQ(4, uDegreeIndex.run(3, 4));
  EXPECT_EQ(4, uDegreeIndex.run(4, 5));
  EXPECT_EQ(3, uDegreeIndex.run(5, 4));
}

TEST_F(LinkPredictionGTest, testVDegreeIndexRun) {
  VDegreeIndex vDegreeIndex(G);
  EXPECT_EQ(2, vDegreeIndex.run(3, 0));
  EXPECT_EQ(3, vDegreeIndex.run(0, 1));
  EXPECT_EQ(4, vDegreeIndex.run(3, 2));
  EXPECT_EQ(4, vDegreeIndex.run(4, 3));
  EXPECT_EQ(4, vDegreeIndex.run(5, 4));
  EXPECT_EQ(3, vDegreeIndex.run(4, 5));
}

TEST_F(LinkPredictionGTest, testTotalNeighborsIndexRun) {
  TotalNeighborsIndex totalNeighborsIndex(trainingGraph);
  EXPECT_EQ(3, totalNeighborsIndex.run(0, 2));
  EXPECT_EQ(3, totalNeighborsIndex.run(0, 4));
  EXPECT_EQ(3, totalNeighborsIndex.run(1, 3));
  EXPECT_EQ(2, totalNeighborsIndex.run(1, 5));
  EXPECT_EQ(3, totalNeighborsIndex.run(2, 4));
  EXPECT_EQ(3, totalNeighborsIndex.run(3, 5));
}

TEST_F(LinkPredictionGTest, testNeighborsMeasureIndexRun) {
  NeighborsMeasureIndex neighborsMeasureIndex(trainingGraph);
  EXPECT_EQ(1, neighborsMeasureIndex.run(0, 2));
  EXPECT_EQ(1, neighborsMeasureIndex.run(0, 4));
  EXPECT_EQ(2, neighborsMeasureIndex.run(1, 3));
  EXPECT_EQ(2, neighborsMeasureIndex.run(1, 5));
  EXPECT_EQ(3, neighborsMeasureIndex.run(2, 4));
  EXPECT_EQ(2, neighborsMeasureIndex.run(3, 5));
}

TEST_F(LinkPredictionGTest, testROCMetric) {
  ROCMetric roc(G);
  std::pair<std::vector<double>, std::vector<double>> curve = roc.getCurve(predictions);
  double auc = roc.getAreaUnderCurve();
  EXPECT_EQ(auc, 0.8125);
  EXPECT_EQ(0, curve.first[0]); EXPECT_EQ(0.5, curve.second[0]);
  EXPECT_EQ(0.25, curve.first[1]); EXPECT_EQ(0.5, curve.second[1]);
  EXPECT_EQ(0.5, curve.first[2]); EXPECT_EQ(1, curve.second[2]);
  EXPECT_EQ(0.75, curve.first[3]); EXPECT_EQ(1, curve.second[3]);
  EXPECT_EQ(1, curve.first[4]); EXPECT_EQ(1, curve.second[4]);
}

TEST_F(LinkPredictionGTest, testPRMetric) {
  PrecisionRecallMetric pr(G);
  std::pair<std::vector<double>, std::vector<double>> curve = pr.getCurve(predictions);
  double auc = pr.getAreaUnderCurve();
  EXPECT_EQ(auc, 0.5);
  EXPECT_EQ(0, curve.first[0]); EXPECT_EQ(1, curve.second[0]);
  EXPECT_EQ(0.5, curve.first[1]); EXPECT_EQ(1.0 / 3, curve.second[1]);
  EXPECT_EQ(1, curve.first[2]); EXPECT_EQ(1.0 / 3, curve.second[2]);
}

TEST_F(LinkPredictionGTest, testKatzRunOnOrdering) {
  METISGraphReader graphReader;
  Graph newG = graphReader.read("input/jazz.graph");
  KatzIndex katz(newG);
  Graph trainingGraph = RandomLinkSampler::byPercentage(newG, 0.7);
  std::vector<std::pair<node, node>> nodePairs = MissingLinksFinder(trainingGraph).findAtDistance(2);
  std::vector<std::pair<std::pair<node, node>, double>> preds = katz.runOn(missingLinks);
  for (index i = 0; i < preds.size() - 1; ++i) {
    EXPECT_TRUE(preds[i].first.first < preds[i+1].first.first || preds[i].first.second < preds[i+1].first.second);
  }
}

} // namespace NetworKit

#endif /* NOGTEST */<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: XMLTableShapesContext.hxx,v $
 *
 *  $Revision: 1.2 $
 *
 *  last change: $Author: nn $ $Date: 2001-03-16 14:16:30 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (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.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#ifndef _SC_XMLTABLESHAPESCONTEXT_HXX
#define _SC_XMLTABLESHAPESCONTEXT_HXX

#ifndef _XMLOFF_XMLICTXT_HXX
#include <xmloff/xmlictxt.hxx>
#endif

class ScXMLImport;

class ScXMLTableShapesContext : public SvXMLImportContext
{
    const ScXMLImport& GetScImport() const { return (const ScXMLImport&)GetImport(); }
    ScXMLImport& GetScImport() { return (ScXMLImport&)GetImport(); }
public:
    ScXMLTableShapesContext( ScXMLImport& rImport, USHORT nPrfx,
                        const ::rtl::OUString& rLName,
                        const ::com::sun::star::uno::Reference<
                                        ::com::sun::star::xml::sax::XAttributeList>& xAttrList);

    virtual ~ScXMLTableShapesContext();

    virtual SvXMLImportContext *CreateChildContext( USHORT nPrefix,
                                     const ::rtl::OUString& rLocalName,
                                     const ::com::sun::star::uno::Reference<
                                          ::com::sun::star::xml::sax::XAttributeList>& xAttrList );

    virtual void EndElement();
};

#endif
<commit_msg>INTEGRATION: CWS ooo19126 (1.2.932); FILE MERGED 2005/09/05 15:03:29 rt 1.2.932.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: XMLTableShapesContext.hxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-08 20:00:33 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#ifndef _SC_XMLTABLESHAPESCONTEXT_HXX
#define _SC_XMLTABLESHAPESCONTEXT_HXX

#ifndef _XMLOFF_XMLICTXT_HXX
#include <xmloff/xmlictxt.hxx>
#endif

class ScXMLImport;

class ScXMLTableShapesContext : public SvXMLImportContext
{
    const ScXMLImport& GetScImport() const { return (const ScXMLImport&)GetImport(); }
    ScXMLImport& GetScImport() { return (ScXMLImport&)GetImport(); }
public:
    ScXMLTableShapesContext( ScXMLImport& rImport, USHORT nPrfx,
                        const ::rtl::OUString& rLName,
                        const ::com::sun::star::uno::Reference<
                                        ::com::sun::star::xml::sax::XAttributeList>& xAttrList);

    virtual ~ScXMLTableShapesContext();

    virtual SvXMLImportContext *CreateChildContext( USHORT nPrefix,
                                     const ::rtl::OUString& rLocalName,
                                     const ::com::sun::star::uno::Reference<
                                          ::com::sun::star::xml::sax::XAttributeList>& xAttrList );

    virtual void EndElement();
};

#endif
<|endoftext|>


<commit_before>/*******************************************************
 * Copyright (c) 2014, ArrayFire
 * All rights reserved.
 *
 * This file is distributed under 3-clause BSD license.
 * The complete license agreement can be obtained at:
 * http://arrayfire.com/licenses/BSD-3-Clause
 ********************************************************/

#include <type_traits>
#include <af/array.h>
#include <Array.hpp>
#include <copy.hpp>
#include <cstring>
#include <algorithm>
#include <complex>
#include <vector>
#include <cassert>
#include <err_cpu.hpp>
#include <math.hpp>
#include <debug_cpu.hpp>
#include <kernel/copy.hpp>

namespace cpu
{

template<typename T>
void copyData(T *to, const Array<T> &from)
{
    from.eval();
    getQueue().sync();
    if(from.isOwner()) {
        // FIXME: Check for errors / exceptions
        memcpy(to, from.get(), from.elements()*sizeof(T));
    } else {
        dim4 ostrides = calcStrides(from.dims());
        kernel::stridedCopy<T>(to, ostrides, from.get(), from.dims(), from.strides(), from.ndims() - 1);
    }
}

template<typename T>
Array<T> copyArray(const Array<T> &A)
{
    Array<T> out = createEmptyArray<T>(A.dims());
    copyData(out.get(), A);
    return out;
}

template<typename T>
void multiply_inplace(Array<T> &in, double val)
{
    in.eval();
    ENQUEUE(kernel::copy<T, T>, in, in, 0, val);
}

template<typename inType, typename outType>
Array<outType> padArray(Array<inType> const &in, dim4 const &dims,
                        outType default_value, double factor)
{
    Array<outType> ret = createValueArray<outType>(dims, default_value);
    ret.eval();
    in.eval();
    // FIXME:
    getQueue().sync();
    ENQUEUE(kernel::copy<outType, inType>, ret, in, outType(default_value), factor);
    return ret;
}

template<typename inType, typename outType>
void copyArray(Array<outType> &out, Array<inType> const &in)
{
    out.eval();
    in.eval();
    ENQUEUE(kernel::copy<outType, inType>, out, in, scalar<outType>(0), 1.0);
}

#define INSTANTIATE(T)                                                  \
    template void      copyData<T> (T *data, const Array<T> &from);     \
    template Array<T>  copyArray<T>(const Array<T> &A);                 \
    template void      multiply_inplace<T> (Array<T> &in, double norm); \

INSTANTIATE(float  )
INSTANTIATE(double )
INSTANTIATE(cfloat )
INSTANTIATE(cdouble)
INSTANTIATE(int    )
INSTANTIATE(uint   )
INSTANTIATE(uchar  )
INSTANTIATE(char   )
INSTANTIATE(intl   )
INSTANTIATE(uintl  )
INSTANTIATE(short  )
INSTANTIATE(ushort )

#define INSTANTIATE_PAD_ARRAY(SRC_T)                                    \
    template Array<float  > padArray<SRC_T, float  >(Array<SRC_T> const &src, dim4 const &dims, float   default_value, double factor); \
    template Array<double > padArray<SRC_T, double >(Array<SRC_T> const &src, dim4 const &dims, double  default_value, double factor); \
    template Array<cfloat > padArray<SRC_T, cfloat >(Array<SRC_T> const &src, dim4 const &dims, cfloat  default_value, double factor); \
    template Array<cdouble> padArray<SRC_T, cdouble>(Array<SRC_T> const &src, dim4 const &dims, cdouble default_value, double factor); \
    template Array<int    > padArray<SRC_T, int    >(Array<SRC_T> const &src, dim4 const &dims, int     default_value, double factor); \
    template Array<uint   > padArray<SRC_T, uint   >(Array<SRC_T> const &src, dim4 const &dims, uint    default_value, double factor); \
    template Array<intl   > padArray<SRC_T, intl   >(Array<SRC_T> const &src, dim4 const &dims, intl    default_value, double factor); \
    template Array<uintl  > padArray<SRC_T, uintl  >(Array<SRC_T> const &src, dim4 const &dims, uintl   default_value, double factor); \
    template Array<short  > padArray<SRC_T, short  >(Array<SRC_T> const &src, dim4 const &dims, short   default_value, double factor); \
    template Array<ushort > padArray<SRC_T, ushort >(Array<SRC_T> const &src, dim4 const &dims, ushort  default_value, double factor); \
    template Array<uchar  > padArray<SRC_T, uchar  >(Array<SRC_T> const &src, dim4 const &dims, uchar   default_value, double factor); \
    template Array<char   > padArray<SRC_T, char   >(Array<SRC_T> const &src, dim4 const &dims, char    default_value, double factor); \
    template void copyArray<SRC_T, float  >(Array<float  > &dst, Array<SRC_T> const &src);  \
    template void copyArray<SRC_T, double >(Array<double > &dst, Array<SRC_T> const &src);  \
    template void copyArray<SRC_T, cfloat >(Array<cfloat > &dst, Array<SRC_T> const &src);  \
    template void copyArray<SRC_T, cdouble>(Array<cdouble> &dst, Array<SRC_T> const &src);  \
    template void copyArray<SRC_T, int    >(Array<int    > &dst, Array<SRC_T> const &src);  \
    template void copyArray<SRC_T, uint   >(Array<uint   > &dst, Array<SRC_T> const &src);  \
    template void copyArray<SRC_T, intl   >(Array<intl   > &dst, Array<SRC_T> const &src);  \
    template void copyArray<SRC_T, uintl  >(Array<uintl  > &dst, Array<SRC_T> const &src);  \
    template void copyArray<SRC_T, short  >(Array<short  > &dst, Array<SRC_T> const &src);  \
    template void copyArray<SRC_T, ushort >(Array<ushort > &dst, Array<SRC_T> const &src);  \
    template void copyArray<SRC_T, uchar  >(Array<uchar  > &dst, Array<SRC_T> const &src);  \
    template void copyArray<SRC_T, char   >(Array<char   > &dst, Array<SRC_T> const &src);

INSTANTIATE_PAD_ARRAY(float )
INSTANTIATE_PAD_ARRAY(double)
INSTANTIATE_PAD_ARRAY(int   )
INSTANTIATE_PAD_ARRAY(uint  )
INSTANTIATE_PAD_ARRAY(intl  )
INSTANTIATE_PAD_ARRAY(uintl )
INSTANTIATE_PAD_ARRAY(uchar )
INSTANTIATE_PAD_ARRAY(char  )
INSTANTIATE_PAD_ARRAY(ushort)
INSTANTIATE_PAD_ARRAY(short )

#define INSTANTIATE_PAD_ARRAY_COMPLEX(SRC_T)                            \
    template Array<cfloat > padArray<SRC_T, cfloat >(Array<SRC_T> const &src, dim4 const &dims, cfloat  default_value, double factor); \
    template Array<cdouble> padArray<SRC_T, cdouble>(Array<SRC_T> const &src, dim4 const &dims, cdouble default_value, double factor); \
    template void copyArray<SRC_T, cfloat  >(Array<cfloat  > &dst, Array<SRC_T> const &src);    \
    template void copyArray<SRC_T, cdouble   >(Array<cdouble > &dst, Array<SRC_T> const &src);

INSTANTIATE_PAD_ARRAY_COMPLEX(cfloat )
INSTANTIATE_PAD_ARRAY_COMPLEX(cdouble)

#define SPECILIAZE_UNUSED_COPYARRAY(SRC_T, DST_T) \
    template<> void copyArray<SRC_T, DST_T>(Array<DST_T> &out, Array<SRC_T> const &in) \
    {\
        CPU_NOT_SUPPORTED();\
    }

SPECILIAZE_UNUSED_COPYARRAY(cfloat , double)
SPECILIAZE_UNUSED_COPYARRAY(cfloat , float)
SPECILIAZE_UNUSED_COPYARRAY(cfloat , uchar)
SPECILIAZE_UNUSED_COPYARRAY(cfloat , char)
SPECILIAZE_UNUSED_COPYARRAY(cfloat , uint)
SPECILIAZE_UNUSED_COPYARRAY(cfloat , int)
SPECILIAZE_UNUSED_COPYARRAY(cfloat , intl)
SPECILIAZE_UNUSED_COPYARRAY(cfloat , uintl)
SPECILIAZE_UNUSED_COPYARRAY(cfloat , short)
SPECILIAZE_UNUSED_COPYARRAY(cfloat , ushort)
SPECILIAZE_UNUSED_COPYARRAY(cdouble, double)
SPECILIAZE_UNUSED_COPYARRAY(cdouble, float)
SPECILIAZE_UNUSED_COPYARRAY(cdouble, uchar)
SPECILIAZE_UNUSED_COPYARRAY(cdouble, char)
SPECILIAZE_UNUSED_COPYARRAY(cdouble, uint)
SPECILIAZE_UNUSED_COPYARRAY(cdouble, int)
SPECILIAZE_UNUSED_COPYARRAY(cdouble, intl)
SPECILIAZE_UNUSED_COPYARRAY(cdouble, uintl)
SPECILIAZE_UNUSED_COPYARRAY(cdouble, short)
SPECILIAZE_UNUSED_COPYARRAY(cdouble, ushort)

}
<commit_msg>Removed obsolete queue sync in cpu::padArray fn<commit_after>/*******************************************************
 * Copyright (c) 2014, ArrayFire
 * All rights reserved.
 *
 * This file is distributed under 3-clause BSD license.
 * The complete license agreement can be obtained at:
 * http://arrayfire.com/licenses/BSD-3-Clause
 ********************************************************/

#include <type_traits>
#include <af/array.h>
#include <Array.hpp>
#include <copy.hpp>
#include <cstring>
#include <algorithm>
#include <complex>
#include <vector>
#include <cassert>
#include <err_cpu.hpp>
#include <math.hpp>
#include <debug_cpu.hpp>
#include <kernel/copy.hpp>

namespace cpu
{

template<typename T>
void copyData(T *to, const Array<T> &from)
{
    from.eval();
    getQueue().sync();
    if(from.isOwner()) {
        // FIXME: Check for errors / exceptions
        memcpy(to, from.get(), from.elements()*sizeof(T));
    } else {
        dim4 ostrides = calcStrides(from.dims());
        kernel::stridedCopy<T>(to, ostrides, from.get(), from.dims(), from.strides(), from.ndims() - 1);
    }
}

template<typename T>
Array<T> copyArray(const Array<T> &A)
{
    Array<T> out = createEmptyArray<T>(A.dims());
    copyData(out.get(), A);
    return out;
}

template<typename T>
void multiply_inplace(Array<T> &in, double val)
{
    in.eval();
    ENQUEUE(kernel::copy<T, T>, in, in, 0, val);
}

template<typename inType, typename outType>
Array<outType> padArray(Array<inType> const &in, dim4 const &dims,
                        outType default_value, double factor)
{
    Array<outType> ret = createValueArray<outType>(dims, default_value);
    ret.eval();
    in.eval();
    ENQUEUE(kernel::copy<outType, inType>, ret, in, outType(default_value), factor);
    return ret;
}

template<typename inType, typename outType>
void copyArray(Array<outType> &out, Array<inType> const &in)
{
    out.eval();
    in.eval();
    ENQUEUE(kernel::copy<outType, inType>, out, in, scalar<outType>(0), 1.0);
}

#define INSTANTIATE(T)                                                  \
    template void      copyData<T> (T *data, const Array<T> &from);     \
    template Array<T>  copyArray<T>(const Array<T> &A);                 \
    template void      multiply_inplace<T> (Array<T> &in, double norm); \

INSTANTIATE(float  )
INSTANTIATE(double )
INSTANTIATE(cfloat )
INSTANTIATE(cdouble)
INSTANTIATE(int    )
INSTANTIATE(uint   )
INSTANTIATE(uchar  )
INSTANTIATE(char   )
INSTANTIATE(intl   )
INSTANTIATE(uintl  )
INSTANTIATE(short  )
INSTANTIATE(ushort )

#define INSTANTIATE_PAD_ARRAY(SRC_T)                                    \
    template Array<float  > padArray<SRC_T, float  >(Array<SRC_T> const &src, dim4 const &dims, float   default_value, double factor); \
    template Array<double > padArray<SRC_T, double >(Array<SRC_T> const &src, dim4 const &dims, double  default_value, double factor); \
    template Array<cfloat > padArray<SRC_T, cfloat >(Array<SRC_T> const &src, dim4 const &dims, cfloat  default_value, double factor); \
    template Array<cdouble> padArray<SRC_T, cdouble>(Array<SRC_T> const &src, dim4 const &dims, cdouble default_value, double factor); \
    template Array<int    > padArray<SRC_T, int    >(Array<SRC_T> const &src, dim4 const &dims, int     default_value, double factor); \
    template Array<uint   > padArray<SRC_T, uint   >(Array<SRC_T> const &src, dim4 const &dims, uint    default_value, double factor); \
    template Array<intl   > padArray<SRC_T, intl   >(Array<SRC_T> const &src, dim4 const &dims, intl    default_value, double factor); \
    template Array<uintl  > padArray<SRC_T, uintl  >(Array<SRC_T> const &src, dim4 const &dims, uintl   default_value, double factor); \
    template Array<short  > padArray<SRC_T, short  >(Array<SRC_T> const &src, dim4 const &dims, short   default_value, double factor); \
    template Array<ushort > padArray<SRC_T, ushort >(Array<SRC_T> const &src, dim4 const &dims, ushort  default_value, double factor); \
    template Array<uchar  > padArray<SRC_T, uchar  >(Array<SRC_T> const &src, dim4 const &dims, uchar   default_value, double factor); \
    template Array<char   > padArray<SRC_T, char   >(Array<SRC_T> const &src, dim4 const &dims, char    default_value, double factor); \
    template void copyArray<SRC_T, float  >(Array<float  > &dst, Array<SRC_T> const &src);  \
    template void copyArray<SRC_T, double >(Array<double > &dst, Array<SRC_T> const &src);  \
    template void copyArray<SRC_T, cfloat >(Array<cfloat > &dst, Array<SRC_T> const &src);  \
    template void copyArray<SRC_T, cdouble>(Array<cdouble> &dst, Array<SRC_T> const &src);  \
    template void copyArray<SRC_T, int    >(Array<int    > &dst, Array<SRC_T> const &src);  \
    template void copyArray<SRC_T, uint   >(Array<uint   > &dst, Array<SRC_T> const &src);  \
    template void copyArray<SRC_T, intl   >(Array<intl   > &dst, Array<SRC_T> const &src);  \
    template void copyArray<SRC_T, uintl  >(Array<uintl  > &dst, Array<SRC_T> const &src);  \
    template void copyArray<SRC_T, short  >(Array<short  > &dst, Array<SRC_T> const &src);  \
    template void copyArray<SRC_T, ushort >(Array<ushort > &dst, Array<SRC_T> const &src);  \
    template void copyArray<SRC_T, uchar  >(Array<uchar  > &dst, Array<SRC_T> const &src);  \
    template void copyArray<SRC_T, char   >(Array<char   > &dst, Array<SRC_T> const &src);

INSTANTIATE_PAD_ARRAY(float )
INSTANTIATE_PAD_ARRAY(double)
INSTANTIATE_PAD_ARRAY(int   )
INSTANTIATE_PAD_ARRAY(uint  )
INSTANTIATE_PAD_ARRAY(intl  )
INSTANTIATE_PAD_ARRAY(uintl )
INSTANTIATE_PAD_ARRAY(uchar )
INSTANTIATE_PAD_ARRAY(char  )
INSTANTIATE_PAD_ARRAY(ushort)
INSTANTIATE_PAD_ARRAY(short )

#define INSTANTIATE_PAD_ARRAY_COMPLEX(SRC_T)                            \
    template Array<cfloat > padArray<SRC_T, cfloat >(Array<SRC_T> const &src, dim4 const &dims, cfloat  default_value, double factor); \
    template Array<cdouble> padArray<SRC_T, cdouble>(Array<SRC_T> const &src, dim4 const &dims, cdouble default_value, double factor); \
    template void copyArray<SRC_T, cfloat  >(Array<cfloat  > &dst, Array<SRC_T> const &src);    \
    template void copyArray<SRC_T, cdouble   >(Array<cdouble > &dst, Array<SRC_T> const &src);

INSTANTIATE_PAD_ARRAY_COMPLEX(cfloat )
INSTANTIATE_PAD_ARRAY_COMPLEX(cdouble)

#define SPECILIAZE_UNUSED_COPYARRAY(SRC_T, DST_T) \
    template<> void copyArray<SRC_T, DST_T>(Array<DST_T> &out, Array<SRC_T> const &in) \
    {\
        CPU_NOT_SUPPORTED();\
    }

SPECILIAZE_UNUSED_COPYARRAY(cfloat , double)
SPECILIAZE_UNUSED_COPYARRAY(cfloat , float)
SPECILIAZE_UNUSED_COPYARRAY(cfloat , uchar)
SPECILIAZE_UNUSED_COPYARRAY(cfloat , char)
SPECILIAZE_UNUSED_COPYARRAY(cfloat , uint)
SPECILIAZE_UNUSED_COPYARRAY(cfloat , int)
SPECILIAZE_UNUSED_COPYARRAY(cfloat , intl)
SPECILIAZE_UNUSED_COPYARRAY(cfloat , uintl)
SPECILIAZE_UNUSED_COPYARRAY(cfloat , short)
SPECILIAZE_UNUSED_COPYARRAY(cfloat , ushort)
SPECILIAZE_UNUSED_COPYARRAY(cdouble, double)
SPECILIAZE_UNUSED_COPYARRAY(cdouble, float)
SPECILIAZE_UNUSED_COPYARRAY(cdouble, uchar)
SPECILIAZE_UNUSED_COPYARRAY(cdouble, char)
SPECILIAZE_UNUSED_COPYARRAY(cdouble, uint)
SPECILIAZE_UNUSED_COPYARRAY(cdouble, int)
SPECILIAZE_UNUSED_COPYARRAY(cdouble, intl)
SPECILIAZE_UNUSED_COPYARRAY(cdouble, uintl)
SPECILIAZE_UNUSED_COPYARRAY(cdouble, short)
SPECILIAZE_UNUSED_COPYARRAY(cdouble, ushort)

}
<|endoftext|>


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

#ifndef SC_CELLLISTSOURCE_HXX
#define SC_CELLLISTSOURCE_HXX

#ifndef _COM_SUN_STAR_FORM_BINDING_XLISTENTRYSOURCE_HPP_
#include <com/sun/star/form/binding/XListEntrySource.hpp>
#endif
#ifndef _CPPUHELPER_COMPBASE4_HXX_
#include <cppuhelper/compbase4.hxx>
#endif
#ifndef _COMPHELPER_PROPERTYCONTAINER_HXX_
#include <comphelper/propertycontainer.hxx>
#endif
#ifndef _COMPHELPER_UNO3_HXX_
#include <comphelper/uno3.hxx>
#endif
#ifndef _COMPHELPER_BROADCASTHELPER_HXX_
#include <comphelper/broadcasthelper.hxx>
#endif
#ifndef _COMPHELPER_PROPERTY_ARRAY_HELPER_HXX_
#include <comphelper/proparrhlp.hxx>
#endif
#ifndef _COM_SUN_STAR_TABLE_XCELLRANGE_HPP_
#include <com/sun/star/table/XCellRange.hpp>
#endif
#ifndef _COM_SUN_STAR_TABLE_CELLRANGEADDRESS_HPP_
#include <com/sun/star/table/CellRangeAddress.hpp>
#endif
#ifndef _COM_SUN_STAR_SHEET_XSPREADSHEETDOCUMENT_HPP_
#include <com/sun/star/sheet/XSpreadsheetDocument.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_DISPOSEDEXCEPTION_HPP_
#include <com/sun/star/lang/DisposedException.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XSERVICEINFO_HPP_
#include <com/sun/star/lang/XServiceInfo.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XINITIALIZATION_HPP_
#include <com/sun/star/lang/XInitialization.hpp>
#endif
#ifndef _COM_SUN_STAR_UTIL_XMODIFYLISTENER_HPP_
#include <com/sun/star/util/XModifyListener.hpp>
#endif

//.........................................................................
namespace calc
{
//.........................................................................

    //=====================================================================
    //= OCellListSource
    //=====================================================================
    class OCellListSource;
    // the base for our interfaces
    typedef ::cppu::WeakAggComponentImplHelper4 <   ::com::sun::star::form::binding::XListEntrySource
                                                ,   ::com::sun::star::util::XModifyListener
                                                ,   ::com::sun::star::lang::XServiceInfo
                                                ,   ::com::sun::star::lang::XInitialization
                                                >   OCellListSource_Base;
    // the base for the property handling
    typedef ::comphelper::OPropertyContainer        OCellListSource_PBase;
    // the second base for property handling
    typedef ::comphelper::OPropertyArrayUsageHelper< OCellListSource >
                                                    OCellListSource_PABase;

    class OCellListSource :public ::comphelper::OBaseMutex
                            ,public OCellListSource_Base      // order matters! before OCellListSource_PBase, so rBHelper gets initialized
                            ,public OCellListSource_PBase
                            ,public OCellListSource_PABase
    {
    private:
        ::com::sun::star::uno::Reference< ::com::sun::star::sheet::XSpreadsheetDocument >
                    m_xDocument;            /// the document where our cell lives
        ::com::sun::star::uno::Reference< ::com::sun::star::table::XCellRange >
                    m_xRange;               /// the range of cells we're bound to
        ::cppu::OInterfaceContainerHelper
                    m_aListEntryListeners;  /// our listeners
        sal_Bool    m_bInitialized;         /// has XInitialization::initialize been called?

    public:
        OCellListSource(
            const ::com::sun::star::uno::Reference< ::com::sun::star::sheet::XSpreadsheetDocument >& _rxDocument
        );

    protected:
        ~OCellListSource( );

    protected:
        // XInterface
        DECLARE_XINTERFACE()

        // XTypeProvider
        DECLARE_XTYPEPROVIDER()

        // XListEntrySource
        virtual sal_Int32 SAL_CALL getListEntryCount(  ) throw (::com::sun::star::uno::RuntimeException);
        virtual ::rtl::OUString SAL_CALL getListEntry( sal_Int32 Position ) throw (::com::sun::star::lang::IndexOutOfBoundsException, ::com::sun::star::uno::RuntimeException);
        virtual ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL getAllListEntries(  ) throw (::com::sun::star::uno::RuntimeException);
        virtual void SAL_CALL addListEntryListener( const ::com::sun::star::uno::Reference< ::com::sun::star::form::binding::XListEntryListener >& Listener ) throw (::com::sun::star::lang::NullPointerException, ::com::sun::star::uno::RuntimeException);
        virtual void SAL_CALL removeListEntryListener( const ::com::sun::star::uno::Reference< ::com::sun::star::form::binding::XListEntryListener >& Listener ) throw (::com::sun::star::lang::NullPointerException, ::com::sun::star::uno::RuntimeException);

        // OComponentHelper/XComponent
        virtual void SAL_CALL disposing();

        // XServiceInfo
        virtual ::rtl::OUString SAL_CALL getImplementationName(  ) throw (::com::sun::star::uno::RuntimeException);
        virtual sal_Bool SAL_CALL supportsService( const ::rtl::OUString& ServiceName ) throw (::com::sun::star::uno::RuntimeException);
        virtual ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL getSupportedServiceNames(  ) throw (::com::sun::star::uno::RuntimeException);

        // XPropertySet
        virtual ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySetInfo > SAL_CALL getPropertySetInfo(  ) throw(::com::sun::star::uno::RuntimeException);

        // OPropertySetHelper
        virtual ::cppu::IPropertyArrayHelper& SAL_CALL getInfoHelper();
        virtual void SAL_CALL getFastPropertyValue( ::com::sun::star::uno::Any& _rValue, sal_Int32 _nHandle ) const;

        // ::comphelper::OPropertyArrayUsageHelper
        virtual ::cppu::IPropertyArrayHelper* createArrayHelper( ) const;

        // XModifyListener
        virtual void SAL_CALL modified( const ::com::sun::star::lang::EventObject& aEvent ) throw (::com::sun::star::uno::RuntimeException);
        virtual void SAL_CALL disposing( const ::com::sun::star::lang::EventObject& Source ) throw (::com::sun::star::uno::RuntimeException);

        // XInitialization
        virtual void SAL_CALL initialize( const ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Any >& aArguments ) throw (::com::sun::star::uno::Exception, ::com::sun::star::uno::RuntimeException);

    private:
        void    checkDisposed( ) const
                    SAL_THROW( ( ::com::sun::star::lang::DisposedException ) );
        void    checkInitialized()
                    SAL_THROW( ( ::com::sun::star::uno::RuntimeException ) );

        /** retrieves the actual address of our cell range
            @precond
                our m_xRange is not <NULL/>
        */
        ::com::sun::star::table::CellRangeAddress
                getRangeAddress( ) const;

        /** retrievs the text of a cell within our range
            @param _nRangeRelativeColumn
                the relative column index of the cell within our range
            @param _nRangeRelativeRow
                the relative row index of the cell within our range
            @precond
                our m_xRange is not <NULL/>
        */
        ::rtl::OUString
                getCellTextContent_noCheck(
                    sal_Int32 _nRangeRelativeColumn,
                    sal_Int32 _nRangeRelativeRow
                );

        void    notifyModified();

    private:
        OCellListSource();                                      // never implemented
        OCellListSource( const OCellListSource& );              // never implemented
        OCellListSource& operator=( const OCellListSource& );   // never implemented

#ifdef DBG_UTIL
    private:
        static  const char* checkConsistency_static( const void* _pThis );
                const char* checkConsistency( ) const;
#endif
    };

//.........................................................................
}   // namespace calc
//.........................................................................

#endif // SC_CELLLISTSOURCE_HXX
<commit_msg>INTEGRATION: CWS calcwarnings (1.4.324); FILE MERGED 2006/12/14 17:57:15 nn 1.4.324.1: #i69284# warning-free: ui, unxsols4<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: celllistsource.hxx,v $
 *
 *  $Revision: 1.5 $
 *
 *  last change: $Author: vg $ $Date: 2007-02-27 13:41:08 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#ifndef SC_CELLLISTSOURCE_HXX
#define SC_CELLLISTSOURCE_HXX

#ifndef _COM_SUN_STAR_FORM_BINDING_XLISTENTRYSOURCE_HPP_
#include <com/sun/star/form/binding/XListEntrySource.hpp>
#endif
#ifndef _CPPUHELPER_COMPBASE4_HXX_
#include <cppuhelper/compbase4.hxx>
#endif
#ifndef _COMPHELPER_PROPERTYCONTAINER_HXX_
#include <comphelper/propertycontainer.hxx>
#endif
#ifndef _COMPHELPER_UNO3_HXX_
#include <comphelper/uno3.hxx>
#endif
#ifndef _COMPHELPER_BROADCASTHELPER_HXX_
#include <comphelper/broadcasthelper.hxx>
#endif
#ifndef _COMPHELPER_PROPERTY_ARRAY_HELPER_HXX_
#include <comphelper/proparrhlp.hxx>
#endif
#ifndef _COM_SUN_STAR_TABLE_XCELLRANGE_HPP_
#include <com/sun/star/table/XCellRange.hpp>
#endif
#ifndef _COM_SUN_STAR_TABLE_CELLRANGEADDRESS_HPP_
#include <com/sun/star/table/CellRangeAddress.hpp>
#endif
#ifndef _COM_SUN_STAR_SHEET_XSPREADSHEETDOCUMENT_HPP_
#include <com/sun/star/sheet/XSpreadsheetDocument.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_DISPOSEDEXCEPTION_HPP_
#include <com/sun/star/lang/DisposedException.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XSERVICEINFO_HPP_
#include <com/sun/star/lang/XServiceInfo.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XINITIALIZATION_HPP_
#include <com/sun/star/lang/XInitialization.hpp>
#endif
#ifndef _COM_SUN_STAR_UTIL_XMODIFYLISTENER_HPP_
#include <com/sun/star/util/XModifyListener.hpp>
#endif

//.........................................................................
namespace calc
{
//.........................................................................

    //=====================================================================
    //= OCellListSource
    //=====================================================================
    class OCellListSource;
    // the base for our interfaces
    typedef ::cppu::WeakAggComponentImplHelper4 <   ::com::sun::star::form::binding::XListEntrySource
                                                ,   ::com::sun::star::util::XModifyListener
                                                ,   ::com::sun::star::lang::XServiceInfo
                                                ,   ::com::sun::star::lang::XInitialization
                                                >   OCellListSource_Base;
    // the base for the property handling
    typedef ::comphelper::OPropertyContainer        OCellListSource_PBase;
    // the second base for property handling
    typedef ::comphelper::OPropertyArrayUsageHelper< OCellListSource >
                                                    OCellListSource_PABase;

    class OCellListSource :public ::comphelper::OBaseMutex
                            ,public OCellListSource_Base      // order matters! before OCellListSource_PBase, so rBHelper gets initialized
                            ,public OCellListSource_PBase
                            ,public OCellListSource_PABase
    {
    private:
        ::com::sun::star::uno::Reference< ::com::sun::star::sheet::XSpreadsheetDocument >
                    m_xDocument;            /// the document where our cell lives
        ::com::sun::star::uno::Reference< ::com::sun::star::table::XCellRange >
                    m_xRange;               /// the range of cells we're bound to
        ::cppu::OInterfaceContainerHelper
                    m_aListEntryListeners;  /// our listeners
        sal_Bool    m_bInitialized;         /// has XInitialization::initialize been called?

    public:
        OCellListSource(
            const ::com::sun::star::uno::Reference< ::com::sun::star::sheet::XSpreadsheetDocument >& _rxDocument
        );

        using OCellListSource_PBase::getFastPropertyValue;

    protected:
        ~OCellListSource( );

    protected:
        // XInterface
        DECLARE_XINTERFACE()

        // XTypeProvider
        DECLARE_XTYPEPROVIDER()

        // XListEntrySource
        virtual sal_Int32 SAL_CALL getListEntryCount(  ) throw (::com::sun::star::uno::RuntimeException);
        virtual ::rtl::OUString SAL_CALL getListEntry( sal_Int32 Position ) throw (::com::sun::star::lang::IndexOutOfBoundsException, ::com::sun::star::uno::RuntimeException);
        virtual ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL getAllListEntries(  ) throw (::com::sun::star::uno::RuntimeException);
        virtual void SAL_CALL addListEntryListener( const ::com::sun::star::uno::Reference< ::com::sun::star::form::binding::XListEntryListener >& Listener ) throw (::com::sun::star::lang::NullPointerException, ::com::sun::star::uno::RuntimeException);
        virtual void SAL_CALL removeListEntryListener( const ::com::sun::star::uno::Reference< ::com::sun::star::form::binding::XListEntryListener >& Listener ) throw (::com::sun::star::lang::NullPointerException, ::com::sun::star::uno::RuntimeException);

        // OComponentHelper/XComponent
        virtual void SAL_CALL disposing();

        // XServiceInfo
        virtual ::rtl::OUString SAL_CALL getImplementationName(  ) throw (::com::sun::star::uno::RuntimeException);
        virtual sal_Bool SAL_CALL supportsService( const ::rtl::OUString& ServiceName ) throw (::com::sun::star::uno::RuntimeException);
        virtual ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL getSupportedServiceNames(  ) throw (::com::sun::star::uno::RuntimeException);

        // XPropertySet
        virtual ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySetInfo > SAL_CALL getPropertySetInfo(  ) throw(::com::sun::star::uno::RuntimeException);

        // OPropertySetHelper
        virtual ::cppu::IPropertyArrayHelper& SAL_CALL getInfoHelper();
        virtual void SAL_CALL getFastPropertyValue( ::com::sun::star::uno::Any& _rValue, sal_Int32 _nHandle ) const;

        // ::comphelper::OPropertyArrayUsageHelper
        virtual ::cppu::IPropertyArrayHelper* createArrayHelper( ) const;

        // XModifyListener
        virtual void SAL_CALL modified( const ::com::sun::star::lang::EventObject& aEvent ) throw (::com::sun::star::uno::RuntimeException);
        virtual void SAL_CALL disposing( const ::com::sun::star::lang::EventObject& Source ) throw (::com::sun::star::uno::RuntimeException);

        // XInitialization
        virtual void SAL_CALL initialize( const ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Any >& aArguments ) throw (::com::sun::star::uno::Exception, ::com::sun::star::uno::RuntimeException);

    private:
        void    checkDisposed( ) const
                    SAL_THROW( ( ::com::sun::star::lang::DisposedException ) );
        void    checkInitialized()
                    SAL_THROW( ( ::com::sun::star::uno::RuntimeException ) );

        /** retrieves the actual address of our cell range
            @precond
                our m_xRange is not <NULL/>
        */
        ::com::sun::star::table::CellRangeAddress
                getRangeAddress( ) const;

        /** retrievs the text of a cell within our range
            @param _nRangeRelativeColumn
                the relative column index of the cell within our range
            @param _nRangeRelativeRow
                the relative row index of the cell within our range
            @precond
                our m_xRange is not <NULL/>
        */
        ::rtl::OUString
                getCellTextContent_noCheck(
                    sal_Int32 _nRangeRelativeColumn,
                    sal_Int32 _nRangeRelativeRow
                );

        void    notifyModified();

    private:
        OCellListSource();                                      // never implemented
        OCellListSource( const OCellListSource& );              // never implemented
        OCellListSource& operator=( const OCellListSource& );   // never implemented

#ifdef DBG_UTIL
    private:
        static  const char* checkConsistency_static( const void* _pThis );
                const char* checkConsistency( ) const;
#endif
    };

//.........................................................................
}   // namespace calc
//.........................................................................

#endif // SC_CELLLISTSOURCE_HXX
<|endoftext|>


<commit_before>///////////////////////////////////////////////////////////////////////////////
//
// File: MatrixOperations.hpp
//
// For more information, please see: http://www.nektar.info
//
// The MIT License
//
// Copyright (c) 2006 Division of Applied Mathematics, Brown University (USA),
// Department of Aeronautics, Imperial College London (UK), and Scientific
// Computing and Imaging Institute, University of Utah (USA).
//
// License for the specific language governing rights and limitations under
// 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.
//
// Description: Defines the global functions needed for matrix operations.
//
///////////////////////////////////////////////////////////////////////////////

#ifndef NEKTAR_LIB_UTILITIES_LINEAR_ALGEBRA_MATRIX_OPERATIONS_HPP
#define NEKTAR_LIB_UTILITIES_LINEAR_ALGEBRA_MATRIX_OPERATIONS_HPP

// Since this file defines all of the operations for all combination of matrix types,
// we have to include all matrix specializations first.
#include <LibUtilities/LinearAlgebra/NormalMatrix.hpp>
#include <LibUtilities/LinearAlgebra/BlockMatrix.hpp>
#include <LibUtilities/LinearAlgebra/ScaledMatrix.hpp>
#include <LibUtilities/LinearAlgebra/Blas.hpp>

namespace Nektar
{
    template<typename DataType, typename LhsDataType, typename LhsMatrixType, typename RhsDataType, typename RhsMatrixType>
    void NekAdd(NekMatrix<DataType, FullMatrixTag, StandardMatrixTag>& result,
                const NekMatrix<LhsDataType, FullMatrixTag, LhsMatrixType>& lhs,
                const NekMatrix<RhsDataType, FullMatrixTag, RhsMatrixType>& rhs)
    {
        ASSERTL0(lhs.GetRows() == rhs.GetRows(), std::string("Matrices with different row counts  ") +
            boost::lexical_cast<std::string>(lhs.GetRows()) + std::string(" and ") +
            boost::lexical_cast<std::string>(rhs.GetRows()) + std::string(" can't be added."));
        ASSERTL0(lhs.GetColumns() == rhs.GetColumns(), std::string("Matrices with different column counts  ") +
            boost::lexical_cast<std::string>(lhs.GetColumns()) + std::string(" and ") +
            boost::lexical_cast<std::string>(rhs.GetColumns()) + std::string(" can't be added."));

        result = NekMatrix<DataType, FullMatrixTag, StandardMatrixTag>(lhs.GetRows(), lhs.GetColumns());
        typename NekMatrix<DataType, FullMatrixTag, StandardMatrixTag>::iterator result_iter = result.begin();
        typename NekMatrix<RhsDataType, FullMatrixTag, RhsMatrixType>::const_iterator rhs_iter = rhs.begin();
        typename NekMatrix<LhsDataType, FullMatrixTag, LhsMatrixType>::const_iterator lhs_iter = lhs.begin();
        while( result_iter != result.end() )
        {
            (*result_iter) = (*lhs_iter) + (*rhs_iter);
            ++result_iter;
            ++rhs_iter;
            ++lhs_iter;
        }
    }

    template<typename DataType, typename LhsDataType, typename LhsMatrixType, typename RhsDataType, typename RhsMatrixType>
    void NekAdd(NekMatrix<DataType, FullMatrixTag, StandardMatrixTag>& result,
                        const NekMatrix<LhsDataType, FullMatrixTag, LhsMatrixType>& lhs,
                        const NekMatrix<RhsDataType, DiagonalMatrixTag, RhsMatrixType>& rhs)
    {
        ASSERTL0(lhs.GetRows() == rhs.GetRows(), std::string("Matrices with different row counts  ") +
            boost::lexical_cast<std::string>(lhs.GetRows()) + std::string(" and ") +
            boost::lexical_cast<std::string>(rhs.GetRows()) + std::string(" can't be added."));
        ASSERTL0(lhs.GetColumns() == rhs.GetColumns(), std::string("Matrices with different column counts  ") +
            boost::lexical_cast<std::string>(lhs.GetColumns()) + std::string(" and ") +
            boost::lexical_cast<std::string>(rhs.GetColumns()) + std::string(" can't be added."));

        result = NekMatrix<DataType, FullMatrixTag, StandardMatrixTag>(lhs);
        for(unsigned int i = 0; i < result.GetRows(); ++i)
        {
            result(i,i) += rhs(i,i);
        }
    }

    template<typename DataType, typename LhsDataType, typename LhsMatrixType, typename RhsDataType, typename RhsMatrixType>
    void NekAdd(NekMatrix<DataType, FullMatrixTag, StandardMatrixTag>& result,
                        const NekMatrix<LhsDataType, DiagonalMatrixTag, LhsMatrixType>& lhs,
                        const NekMatrix<RhsDataType, FullMatrixTag, RhsMatrixType>& rhs)
    {
        ASSERTL0(lhs.GetRows() == rhs.GetRows(), std::string("Matrices with different row counts  ") +
            boost::lexical_cast<std::string>(lhs.GetRows()) + std::string(" and ") +
            boost::lexical_cast<std::string>(rhs.GetRows()) + std::string(" can't be added."));
        ASSERTL0(lhs.GetColumns() == rhs.GetColumns(), std::string("Matrices with different column counts  ") +
            boost::lexical_cast<std::string>(lhs.GetColumns()) + std::string(" and ") +
            boost::lexical_cast<std::string>(rhs.GetColumns()) + std::string(" can't be added."));

        result = NekMatrix<DataType, FullMatrixTag, StandardMatrixTag>(rhs);
        for(unsigned int i = 0; i < result.GetRows(); ++i)
        {
            result(i,i) += lhs(i,i);
        }
    }

    template<typename DataType>
    void NekMultiply(NekMatrix<DataType, FullMatrixTag, StandardMatrixTag>& result,
                            const NekMatrix<DataType, FullMatrixTag, StandardMatrixTag>& lhs,
                            const NekMatrix<DataType, FullMatrixTag, StandardMatrixTag>& rhs)
    {
        ASSERTL0(lhs.GetColumns() == rhs.GetRows(), std::string("A left side matrix with column count ") +
            boost::lexical_cast<std::string>(lhs.GetColumns()) +
            std::string(" and a right side matrix with row count ") +
            boost::lexical_cast<std::string>(rhs.GetRows()) + std::string(" can't be multiplied."));

        result = NekMatrix<DataType, FullMatrixTag, StandardMatrixTag>(lhs.GetRows(), rhs.GetColumns());

        for(unsigned int i = 0; i < result.GetRows(); ++i)
        {
            for(unsigned int j = 0; j < result.GetColumns(); ++j)
            {
                DataType t = DataType(0);

                // Set the result(i,j) element.
                for(unsigned int k = 0; k < lhs.GetColumns(); ++k)
                {
                    t += lhs(i,k)*rhs(k,j);
                }
                result(i,j) = t;
            }
        }
    }

    #ifdef NEKTAR_USING_BLAS
    /// \brief Floating point specialization when blas is in use.
    ///
    /// The signature of this function should match the unspecialized NekMultiply.
    void NekMultiply(NekMatrix<NekDouble, FullMatrixTag, StandardMatrixTag>& result,
                            const NekMatrix<NekDouble, FullMatrixTag, StandardMatrixTag>& lhs,
                            const NekMatrix<NekDouble, FullMatrixTag, StandardMatrixTag>& rhs);
    #endif //NEKTAR_USING_BLAS
}
#endif //NEKTAR_LIB_UTILITIES_LINEAR_ALGEBRA_MATRIX_OPERATIONS_HPP

<commit_msg>*** empty log message ***<commit_after>///////////////////////////////////////////////////////////////////////////////
//
// File: MatrixOperations.hpp
//
// For more information, please see: http://www.nektar.info
//
// The MIT License
//
// Copyright (c) 2006 Division of Applied Mathematics, Brown University (USA),
// Department of Aeronautics, Imperial College London (UK), and Scientific
// Computing and Imaging Institute, University of Utah (USA).
//
// License for the specific language governing rights and limitations under
// 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.
//
// Description: Defines the global functions needed for matrix operations.
//
///////////////////////////////////////////////////////////////////////////////

#ifndef NEKTAR_LIB_UTILITIES_LINEAR_ALGEBRA_MATRIX_OPERATIONS_HPP
#define NEKTAR_LIB_UTILITIES_LINEAR_ALGEBRA_MATRIX_OPERATIONS_HPP

// Since this file defines all of the operations for all combination of matrix types,
// we have to include all matrix specializations first.
#include <LibUtilities/LinearAlgebra/NormalMatrix.hpp>
#include <LibUtilities/LinearAlgebra/BlockMatrix.hpp>
#include <LibUtilities/LinearAlgebra/ScaledMatrix.hpp>
#include <LibUtilities/LinearAlgebra/Blas.hpp>

namespace Nektar
{
    template<typename DataType, typename LhsDataType, typename LhsMatrixType, typename RhsDataType, typename RhsMatrixType>
    void NekAdd(NekMatrix<DataType, FullMatrixTag, StandardMatrixTag>& result,
                const NekMatrix<LhsDataType, FullMatrixTag, LhsMatrixType>& lhs,
                const NekMatrix<RhsDataType, FullMatrixTag, RhsMatrixType>& rhs)
    {
        ASSERTL0(lhs.GetRows() == rhs.GetRows(), std::string("Matrices with different row counts  ") +
            boost::lexical_cast<std::string>(lhs.GetRows()) + std::string(" and ") +
            boost::lexical_cast<std::string>(rhs.GetRows()) + std::string(" can't be added."));
        ASSERTL0(lhs.GetColumns() == rhs.GetColumns(), std::string("Matrices with different column counts  ") +
            boost::lexical_cast<std::string>(lhs.GetColumns()) + std::string(" and ") +
            boost::lexical_cast<std::string>(rhs.GetColumns()) + std::string(" can't be added."));

        result = NekMatrix<DataType, FullMatrixTag, StandardMatrixTag>(lhs.GetRows(), lhs.GetColumns());
        typename NekMatrix<DataType, FullMatrixTag, StandardMatrixTag>::iterator result_iter = result.begin();
        typename NekMatrix<RhsDataType, FullMatrixTag, RhsMatrixType>::const_iterator rhs_iter = rhs.begin();
        typename NekMatrix<LhsDataType, FullMatrixTag, LhsMatrixType>::const_iterator lhs_iter = lhs.begin();
        while( result_iter != result.end() )
        {
            (*result_iter) = (*lhs_iter) + (*rhs_iter);
            ++result_iter;
            ++rhs_iter;
            ++lhs_iter;
        }
    }

    template<typename DataType, typename LhsDataType, typename LhsMatrixType, typename RhsDataType, typename RhsMatrixType>
    void NekAdd(NekMatrix<DataType, FullMatrixTag, StandardMatrixTag>& result,
                        const NekMatrix<LhsDataType, FullMatrixTag, LhsMatrixType>& lhs,
                        const NekMatrix<RhsDataType, DiagonalMatrixTag, RhsMatrixType>& rhs)
    {
        ASSERTL0(lhs.GetRows() == rhs.GetRows(), std::string("Matrices with different row counts  ") +
            boost::lexical_cast<std::string>(lhs.GetRows()) + std::string(" and ") +
            boost::lexical_cast<std::string>(rhs.GetRows()) + std::string(" can't be added."));
        ASSERTL0(lhs.GetColumns() == rhs.GetColumns(), std::string("Matrices with different column counts  ") +
            boost::lexical_cast<std::string>(lhs.GetColumns()) + std::string(" and ") +
            boost::lexical_cast<std::string>(rhs.GetColumns()) + std::string(" can't be added."));

        result = NekMatrix<DataType, FullMatrixTag, StandardMatrixTag>(lhs);
        for(unsigned int i = 0; i < result.GetRows(); ++i)
        {
            result(i,i) += rhs(i,i);
        }
    }

    template<typename DataType, typename LhsDataType, typename LhsMatrixType, typename RhsDataType, typename RhsMatrixType>
    void NekAdd(NekMatrix<DataType, FullMatrixTag, StandardMatrixTag>& result,
                        const NekMatrix<LhsDataType, DiagonalMatrixTag, LhsMatrixType>& lhs,
                        const NekMatrix<RhsDataType, FullMatrixTag, RhsMatrixType>& rhs)
    {
        ASSERTL0(lhs.GetRows() == rhs.GetRows(), std::string("Matrices with different row counts  ") +
            boost::lexical_cast<std::string>(lhs.GetRows()) + std::string(" and ") +
            boost::lexical_cast<std::string>(rhs.GetRows()) + std::string(" can't be added."));
        ASSERTL0(lhs.GetColumns() == rhs.GetColumns(), std::string("Matrices with different column counts  ") +
            boost::lexical_cast<std::string>(lhs.GetColumns()) + std::string(" and ") +
            boost::lexical_cast<std::string>(rhs.GetColumns()) + std::string(" can't be added."));

        result = NekMatrix<DataType, FullMatrixTag, StandardMatrixTag>(rhs);
        for(unsigned int i = 0; i < result.GetRows(); ++i)
        {
            result(i,i) += lhs(i,i);
        }
    }

    template<typename DataType>
    void NekMultiply(NekMatrix<DataType, FullMatrixTag, StandardMatrixTag>& result,
                            const NekMatrix<DataType, FullMatrixTag, StandardMatrixTag>& lhs,
                            const NekMatrix<DataType, FullMatrixTag, StandardMatrixTag>& rhs)
    {
        ASSERTL0(lhs.GetColumns() == rhs.GetRows(), std::string("A left side matrix with column count ") +
            boost::lexical_cast<std::string>(lhs.GetColumns()) +
            std::string(" and a right side matrix with row count ") +
            boost::lexical_cast<std::string>(rhs.GetRows()) + std::string(" can't be multiplied."));

        result = NekMatrix<DataType, FullMatrixTag, StandardMatrixTag>(lhs.GetRows(), rhs.GetColumns());

        for(unsigned int i = 0; i < result.GetRows(); ++i)
        {
            for(unsigned int j = 0; j < result.GetColumns(); ++j)
            {
                DataType t = DataType(0);

                // Set the result(i,j) element.
                for(unsigned int k = 0; k < lhs.GetColumns(); ++k)
                {
                    t += lhs(i,k)*rhs(k,j);
                }
                result(i,j) = t;
            }
        }
    }

    #ifdef NEKTAR_USING_BLAS
    /// \brief Floating point specialization when blas is in use.
    ///
    /// The signature of this function should match the unspecialized NekMultiply.
    void NekMultiply(NekMatrix<NekDouble, FullMatrixTag, StandardMatrixTag>& result,
                            const NekMatrix<NekDouble, FullMatrixTag, StandardMatrixTag>& lhs,
                            const NekMatrix<NekDouble, FullMatrixTag, StandardMatrixTag>& rhs);
    #endif //NEKTAR_USING_BLAS

    //template<typename DataType, typename LhsDataType, typename MatrixType, unsigned int dim, unsigned int space>
    //void NekMultiply(NekVector<DataType, dim, space>& result,
    //                 const NekMatrix<LhsDataType, FullMatrixTag, MatrixType>& lhs,
    //                 const NekVector<DataType, dim, space>& rhs)
    //{
    //    ASSERTL0(lhs.GetColumns() == rhs.GetRows(), std::string("A left side matrix with column count ") +
    //        boost::lexical_cast<std::string>(lhs.GetColumns()) +
    //        std::string(" and a right side vector with row count ") +
    //        boost::lexical_cast<std::string>(rhs.GetRows()) + std::string(" can't be multiplied."));

    //    result = NekVector<DataType, dim, space>(lhs.GetRows());
    //    for(unsigned int i = 0; i < lhs.GetRows(); ++i)
    //    {
    //        DataType accum = DataType(0);
    //        for(unsigned int j = 0; j < lhs.GetColumns(); ++j)
    //        {
    //            accum += lhs(i,j)*rhs(j);
    //        }
    //        result[i] = accum;
    //    }
    //}

    //template<typename DataType, typename LhsDataType, typename MatrixType, unsigned int dim, unsigned int space>
    //void NekMultiply(NekVector<DataType, dim, space>& result,
    //                 const NekMatrix<LhsDataType, DiagonalMatrixTag, MatrixType>& lhs,
    //                 const NekVector<DataType, dim, space>& rhs)
    //{
    //    ASSERTL0(lhs.GetColumns() == rhs.GetRows(), std::string("A left side matrix with column count ") +
    //        boost::lexical_cast<std::string>(lhs.GetColumns()) +
    //        std::string(" and a right side vector with row count ") +
    //        boost::lexical_cast<std::string>(rhs.GetRows()) + std::string(" can't be multiplied."));

    //    result = NekVector<DataType, dim, space>(lhs.GetRows());
    //    for(unsigned int i = 0; i < lhs.GetRows(); ++i)
    //    {
    //        result[i] = lhs(i,i)*rhs(i);
    //    }
    //}
}
#endif //NEKTAR_LIB_UTILITIES_LINEAR_ALGEBRA_MATRIX_OPERATIONS_HPP

<|endoftext|>