<commit_before>#include <cstring> // for memcpy
#include <algorithm> // for std::remove_if
#include <cstdint>  // for uint8_t type
#include <cassert>

#include "TimeWarpMPICommunicationManager.hpp"
#include "TimeWarpEventDispatcher.hpp"          // for EventMessage
#include "utility/memory.hpp"
#include "utility/warnings.hpp"

namespace warped {

unsigned int TimeWarpMPICommunicationManager::initialize() {

    // MPI_Init requires command line arguments, but doesn't use them. Just give
    // it an empty vector.
    int argc = 0;
    char** argv = new char*[1];
    argv[0] = NULL;
    int provided;

    MPI_Init_thread(&argc, &argv, MPI_THREAD_FUNNELED, &provided);

    delete [] argv;

    if (provided == MPI_THREAD_SINGLE) {
        std::cout << "Warning: Your MPI Implementation only supports single-threaded applications"
                  << std::endl;
    }

    send_queue_ = std::make_shared<MessageQueue>(max_buffer_size_);
    recv_queue_ = std::make_shared<MessageQueue>(max_buffer_size_);

    MPI_Comm_size(MPI_COMM_WORLD, &num_processes_);
    MPI_Comm_rank(MPI_COMM_WORLD, &my_rank_);

    aggregate_message_count_by_receiver_ = make_unique<unsigned int[]>(num_processes_);
    std::memset(aggregate_message_count_by_receiver_.get(), 0, num_processes_*sizeof(unsigned int));

    aggregate_messages_ = make_unique<std::list<std::unique_ptr<TimeWarpKernelMessage>>[]>(num_processes_);

    return getNumProcesses();
}

void TimeWarpMPICommunicationManager::finalize() {
    assert(isInitiatingThread());
    MPI_Finalize();
}

unsigned int TimeWarpMPICommunicationManager::getNumProcesses() {
    return num_processes_;
}

unsigned int TimeWarpMPICommunicationManager::getID() {
    return my_rank_;
}

int TimeWarpMPICommunicationManager::waitForAllProcesses() {
    assert(isInitiatingThread());
    return MPI_Barrier(MPI_COMM_WORLD);
}

bool TimeWarpMPICommunicationManager::isInitiatingThread() {
    int flag = 0;
    MPI_Is_thread_main(&flag);
    return flag;
}

int
TimeWarpMPICommunicationManager::sumReduceUint64(uint64_t *send_local, uint64_t *recv_global) {
    assert(isInitiatingThread());
    return MPI_Reduce(send_local, recv_global, 1, MPI_UINT64_T, MPI_SUM, 0, MPI_COMM_WORLD);
}

int
TimeWarpMPICommunicationManager::gatherUint64(uint64_t *send_local, uint64_t *recv_root) {
    assert(isInitiatingThread());
    return MPI_Gather(send_local, 1, MPI_UINT64_T, recv_root, 1, MPI_UINT64_T, 0, MPI_COMM_WORLD);
}

int TimeWarpMPICommunicationManager::sumAllReduceInt64(int64_t* send_local, int64_t* recv_global) {
    assert(isInitiatingThread());
    return MPI_Allreduce(send_local, recv_global, 1, MPI_INT64_T, MPI_SUM, MPI_COMM_WORLD);
}

int TimeWarpMPICommunicationManager::minAllReduceUint(unsigned int* send_local, unsigned int* recv_global) {
    assert(isInitiatingThread());
    return MPI_Allreduce(send_local, recv_global, 1, MPI_UNSIGNED, MPI_MIN, MPI_COMM_WORLD);
}

void TimeWarpMPICommunicationManager::insertMessage(std::unique_ptr<TimeWarpKernelMessage> msg) {
    send_queue_->msg_list_lock_.lock();
    send_queue_->msg_list_.push_back(std::move(msg));
    send_queue_->msg_list_lock_.unlock();
}

void TimeWarpMPICommunicationManager::handleMessages() {
    testReceiveRequests();
    testSendRequests();
    startReceiveRequests();
    startSendRequests();
}

void TimeWarpMPICommunicationManager::flushMessages() {
    for (unsigned int receiver_id = 0; receiver_id < getNumProcesses(); receiver_id++) {
        packAndSend(receiver_id);
    }
}

unsigned int TimeWarpMPICommunicationManager::startSendRequests() {
    unsigned int requests = 0;

    send_queue_->msg_list_lock_.lock();

    while (!send_queue_->msg_list_.empty()) {

        auto msg = std::move(send_queue_->msg_list_.front());
        send_queue_->msg_list_.pop_front();

        unsigned int receiver_id = msg->receiver_id;
        auto msg_type = msg->get_type();

        aggregate_messages_[receiver_id].push_back(std::move(msg));

        if ((++aggregate_message_count_by_receiver_[receiver_id] >= max_aggregate_) ||
            (msg_type != MessageType::EventMessage)) {

            packAndSend(receiver_id);

            requests++;
        }
    }

    send_queue_->msg_list_lock_.unlock();

    return requests;
}

void TimeWarpMPICommunicationManager::packAndSend(unsigned int receiver_id) {

    int position = 0;
    uint8_t* message_buffer = new uint8_t[max_buffer_size_];
    int num_messages = aggregate_messages_[receiver_id].size();
    int header_size = sizeof(int)*(num_messages+1);
    int message_position = header_size;

    MPI_Pack(&num_messages, 1, MPI_INT, message_buffer, max_buffer_size_, &position, MPI_COMM_WORLD);
    for (auto& m : aggregate_messages_[receiver_id]) {
        std::ostringstream oss;
        cereal::PortableBinaryOutputArchive oarchive(oss);
        oarchive(m);

        int length = oss.str().length();
        MPI_Pack(&length, 1, MPI_INT, message_buffer, max_buffer_size_, &position, MPI_COMM_WORLD);
        MPI_Pack(const_cast<char*>(oss.str().c_str()), length, MPI_BYTE, message_buffer,
                 max_buffer_size_, &message_position, MPI_COMM_WORLD);
    }

    auto new_request = make_unique<PendingRequest>(std::unique_ptr<uint8_t[]>(message_buffer), message_position);
    send_queue_->pending_request_list_.push_back(std::move(new_request));

    if (MPI_Isend(
            send_queue_->pending_request_list_.back()->buffer_.get(),
            send_queue_->pending_request_list_.back()->count_,
            MPI_PACKED,
            receiver_id,
            MPI_DATA_TAG,
            MPI_COMM_WORLD,
            &send_queue_->pending_request_list_.back()->request_) != MPI_SUCCESS) {
        throw std::runtime_error("MPI_Isend failed");
    }

    aggregate_messages_[receiver_id].clear();
    aggregate_message_count_by_receiver_[receiver_id] = 0;
}

unsigned int TimeWarpMPICommunicationManager::startReceiveRequests() {
    int flag = 0;
    MPI_Status status;
    unsigned int requests = 0;

    while (true) {

        MPI_Iprobe(
            MPI_ANY_SOURCE,
            MPI_ANY_TAG,
            MPI_COMM_WORLD,
            &flag,
            &status);

        if (flag) {

            int count;
            MPI_Get_count(&status, MPI_BYTE, &count);
            auto new_request = make_unique<PendingRequest>(make_unique<uint8_t[]>(count), count);
            recv_queue_->pending_request_list_.push_back(std::move(new_request));

            if (MPI_Irecv(
                    recv_queue_->pending_request_list_.back()->buffer_.get(),
                    recv_queue_->pending_request_list_.back()->count_,
                    MPI_PACKED,
                    MPI_ANY_SOURCE,
                    MPI_DATA_TAG,
                    MPI_COMM_WORLD,
                    &recv_queue_->pending_request_list_.back()->request_) != MPI_SUCCESS) {

                return requests;
            }
        } else {
            break;
        }

        requests++;
    }

    return requests;
}

unsigned int TimeWarpMPICommunicationManager::testSendRequests() {
    unsigned int count = 0;

    for (auto &pr : send_queue_->pending_request_list_) {
        MPI_Test(&pr->request_, &pr->flag_, &pr->status_);
        if (pr->flag_) count++;
    }

    send_queue_->pending_request_list_.erase(
        std::remove_if(
            send_queue_->pending_request_list_.begin(),
            send_queue_->pending_request_list_.end(),
            [&](const std::unique_ptr<PendingRequest>& pr) { return pr->flag_; }),
        send_queue_->pending_request_list_.end());

    return count;
}

unsigned int TimeWarpMPICommunicationManager::testReceiveRequests() {
    unsigned int count = 0;

    for (auto &pr : recv_queue_->pending_request_list_) {
        MPI_Test(&pr->request_, &pr->flag_, &pr->status_);
        if (pr->flag_) {
            count++;

            int num_messages;
            char* message_buffer = reinterpret_cast<char*>(pr->buffer_.get());
            int message_length = pr->count_;
            int position = 0;

            MPI_Unpack(message_buffer, message_length, &position, &num_messages, 1, MPI_INT, MPI_COMM_WORLD);
            int header_length = (num_messages+1)*sizeof(int);
            int msg_position = header_length;

            for (int i = 0; i < num_messages; i++) {
                std::unique_ptr<TimeWarpKernelMessage> msg = nullptr;

                // Unpack from aggregate buffer
                int msg_length = reinterpret_cast<int*>(message_buffer)[i + 1];
                auto msg_buffer = make_unique<char[]>(msg_length);
                MPI_Unpack(message_buffer, message_length, &msg_position, msg_buffer.get(), msg_length,
                           MPI_BYTE, MPI_COMM_WORLD);

                // Deserialize
                std::istringstream iss(std::string(msg_buffer.get(), msg_length));
                cereal::PortableBinaryInputArchive iarchive(iss);
                iarchive(msg);

                MessageType msg_type = msg->get_type();
                int msg_type_int = static_cast<int>(msg_type);
                msg_handler_by_msg_type_[msg_type_int](std::move(msg));
            }
        }
    }

    recv_queue_->pending_request_list_.erase(
        std::remove_if(
            recv_queue_->pending_request_list_.begin(),
            recv_queue_->pending_request_list_.end(),
            [&](const std::unique_ptr<PendingRequest>& pr) { return pr->flag_; }),
        recv_queue_->pending_request_list_.end());

    return count;

}

} // namespace warped

<commit_msg>Increase receive buffer to avoid message truncation with OpenMPI<commit_after>#include <cstring> // for memcpy
#include <algorithm> // for std::remove_if
#include <cstdint>  // for uint8_t type
#include <cassert>

#include "TimeWarpMPICommunicationManager.hpp"
#include "TimeWarpEventDispatcher.hpp"          // for EventMessage
#include "utility/memory.hpp"
#include "utility/warnings.hpp"

namespace warped {

unsigned int TimeWarpMPICommunicationManager::initialize() {

    // MPI_Init requires command line arguments, but doesn't use them. Just give
    // it an empty vector.
    int argc = 0;
    char** argv = new char*[1];
    argv[0] = NULL;
    int provided;

    MPI_Init_thread(&argc, &argv, MPI_THREAD_FUNNELED, &provided);

    delete [] argv;

    if (provided == MPI_THREAD_SINGLE) {
        std::cout << "Warning: Your MPI Implementation only supports single-threaded applications"
                  << std::endl;
    }

    send_queue_ = std::make_shared<MessageQueue>(max_buffer_size_);
    recv_queue_ = std::make_shared<MessageQueue>(max_buffer_size_);

    MPI_Comm_size(MPI_COMM_WORLD, &num_processes_);
    MPI_Comm_rank(MPI_COMM_WORLD, &my_rank_);

    aggregate_message_count_by_receiver_ = make_unique<unsigned int[]>(num_processes_);
    std::memset(aggregate_message_count_by_receiver_.get(), 0, num_processes_*sizeof(unsigned int));

    aggregate_messages_ = make_unique<std::list<std::unique_ptr<TimeWarpKernelMessage>>[]>(num_processes_);

    return getNumProcesses();
}

void TimeWarpMPICommunicationManager::finalize() {
    assert(isInitiatingThread());
    MPI_Finalize();
}

unsigned int TimeWarpMPICommunicationManager::getNumProcesses() {
    return num_processes_;
}

unsigned int TimeWarpMPICommunicationManager::getID() {
    return my_rank_;
}

int TimeWarpMPICommunicationManager::waitForAllProcesses() {
    assert(isInitiatingThread());
    return MPI_Barrier(MPI_COMM_WORLD);
}

bool TimeWarpMPICommunicationManager::isInitiatingThread() {
    int flag = 0;
    MPI_Is_thread_main(&flag);
    return flag;
}

int
TimeWarpMPICommunicationManager::sumReduceUint64(uint64_t *send_local, uint64_t *recv_global) {
    assert(isInitiatingThread());
    return MPI_Reduce(send_local, recv_global, 1, MPI_UINT64_T, MPI_SUM, 0, MPI_COMM_WORLD);
}

int
TimeWarpMPICommunicationManager::gatherUint64(uint64_t *send_local, uint64_t *recv_root) {
    assert(isInitiatingThread());
    return MPI_Gather(send_local, 1, MPI_UINT64_T, recv_root, 1, MPI_UINT64_T, 0, MPI_COMM_WORLD);
}

int TimeWarpMPICommunicationManager::sumAllReduceInt64(int64_t* send_local, int64_t* recv_global) {
    assert(isInitiatingThread());
    return MPI_Allreduce(send_local, recv_global, 1, MPI_INT64_T, MPI_SUM, MPI_COMM_WORLD);
}

int TimeWarpMPICommunicationManager::minAllReduceUint(unsigned int* send_local, unsigned int* recv_global) {
    assert(isInitiatingThread());
    return MPI_Allreduce(send_local, recv_global, 1, MPI_UNSIGNED, MPI_MIN, MPI_COMM_WORLD);
}

void TimeWarpMPICommunicationManager::insertMessage(std::unique_ptr<TimeWarpKernelMessage> msg) {
    send_queue_->msg_list_lock_.lock();
    send_queue_->msg_list_.push_back(std::move(msg));
    send_queue_->msg_list_lock_.unlock();
}

void TimeWarpMPICommunicationManager::handleMessages() {
    testReceiveRequests();
    testSendRequests();
    startReceiveRequests();
    startSendRequests();
}

void TimeWarpMPICommunicationManager::flushMessages() {
    for (unsigned int receiver_id = 0; receiver_id < getNumProcesses(); receiver_id++) {
        packAndSend(receiver_id);
    }
}

unsigned int TimeWarpMPICommunicationManager::startSendRequests() {
    unsigned int requests = 0;

    send_queue_->msg_list_lock_.lock();

    while (!send_queue_->msg_list_.empty()) {

        auto msg = std::move(send_queue_->msg_list_.front());
        send_queue_->msg_list_.pop_front();

        unsigned int receiver_id = msg->receiver_id;
        auto msg_type = msg->get_type();

        aggregate_messages_[receiver_id].push_back(std::move(msg));

        if ((++aggregate_message_count_by_receiver_[receiver_id] >= max_aggregate_) ||
            (msg_type != MessageType::EventMessage)) {

            packAndSend(receiver_id);

            requests++;
        }
    }

    send_queue_->msg_list_lock_.unlock();

    return requests;
}

void TimeWarpMPICommunicationManager::packAndSend(unsigned int receiver_id) {

    int position = 0;
    uint8_t* message_buffer = new uint8_t[max_buffer_size_];
    int num_messages = aggregate_messages_[receiver_id].size();
    int header_size = sizeof(int)*(num_messages+1);
    int message_position = header_size;

    MPI_Pack(&num_messages, 1, MPI_INT, message_buffer, max_buffer_size_, &position, MPI_COMM_WORLD);
    for (auto& m : aggregate_messages_[receiver_id]) {
        std::ostringstream oss;
        cereal::PortableBinaryOutputArchive oarchive(oss);
        oarchive(m);

        int length = oss.str().length();
        MPI_Pack(&length, 1, MPI_INT, message_buffer, max_buffer_size_, &position, MPI_COMM_WORLD);
        MPI_Pack(const_cast<char*>(oss.str().c_str()), length, MPI_BYTE, message_buffer,
                 max_buffer_size_, &message_position, MPI_COMM_WORLD);
    }

    auto new_request = make_unique<PendingRequest>(std::unique_ptr<uint8_t[]>(message_buffer), message_position);
    send_queue_->pending_request_list_.push_back(std::move(new_request));

    if (MPI_Isend(
            send_queue_->pending_request_list_.back()->buffer_.get(),
            send_queue_->pending_request_list_.back()->count_,
            MPI_PACKED,
            receiver_id,
            MPI_DATA_TAG,
            MPI_COMM_WORLD,
            &send_queue_->pending_request_list_.back()->request_) != MPI_SUCCESS) {
        throw std::runtime_error("MPI_Isend failed");
    }

    aggregate_messages_[receiver_id].clear();
    aggregate_message_count_by_receiver_[receiver_id] = 0;
}

unsigned int TimeWarpMPICommunicationManager::startReceiveRequests() {
    int flag = 0;
    MPI_Status status;
    unsigned int requests = 0;

    while (true) {

        MPI_Iprobe(
            MPI_ANY_SOURCE,
            MPI_ANY_TAG,
            MPI_COMM_WORLD,
            &flag,
            &status);

        if (flag) {

            auto new_request = make_unique<PendingRequest>(make_unique<uint8_t[]>(max_buffer_size_), max_buffer_size_);
            recv_queue_->pending_request_list_.push_back(std::move(new_request));

            if (MPI_Irecv(
                    recv_queue_->pending_request_list_.back()->buffer_.get(),
                    recv_queue_->pending_request_list_.back()->count_,
                    MPI_PACKED,
                    MPI_ANY_SOURCE,
                    MPI_DATA_TAG,
                    MPI_COMM_WORLD,
                    &recv_queue_->pending_request_list_.back()->request_) != MPI_SUCCESS) {

                return requests;
            }
        } else {
            break;
        }

        requests++;
    }

    return requests;
}

unsigned int TimeWarpMPICommunicationManager::testSendRequests() {
    unsigned int count = 0;

    for (auto &pr : send_queue_->pending_request_list_) {
        if (MPI_Test(&pr->request_, &pr->flag_, &pr->status_) != MPI_SUCCESS) {
            throw std::runtime_error("MPI_Test failed in testSendRequest");
        }
        if (pr->flag_) count++;
    }

    send_queue_->pending_request_list_.erase(
        std::remove_if(
            send_queue_->pending_request_list_.begin(),
            send_queue_->pending_request_list_.end(),
            [&](const std::unique_ptr<PendingRequest>& pr) { return pr->flag_; }),
        send_queue_->pending_request_list_.end());

    return count;
}

unsigned int TimeWarpMPICommunicationManager::testReceiveRequests() {
    unsigned int count = 0;

    for (auto &pr : recv_queue_->pending_request_list_) {
        if (MPI_Test(&pr->request_, &pr->flag_, &pr->status_) != MPI_SUCCESS) {
            throw std::runtime_error("MPI_Test failed in testSendRequest");
        }
        if (pr->flag_) {
            count++;

            int num_messages;
            char* message_buffer = reinterpret_cast<char*>(pr->buffer_.get());
            int message_length = pr->count_;;
            int position = 0;

            MPI_Unpack(message_buffer, message_length, &position, &num_messages, 1, MPI_INT, MPI_COMM_WORLD);
            int header_length = (num_messages+1)*sizeof(int);
            int msg_position = header_length;

            for (int i = 0; i < num_messages; i++) {
                std::unique_ptr<TimeWarpKernelMessage> msg = nullptr;

                // Unpack from aggregate buffer
                int msg_length = reinterpret_cast<int*>(message_buffer)[i + 1];
                auto msg_buffer = make_unique<char[]>(msg_length);
                MPI_Unpack(message_buffer, message_length, &msg_position, msg_buffer.get(), msg_length,
                           MPI_BYTE, MPI_COMM_WORLD);

                // Deserialize
                std::istringstream iss(std::string(msg_buffer.get(), msg_length));
                cereal::PortableBinaryInputArchive iarchive(iss);
                iarchive(msg);

                MessageType msg_type = msg->get_type();
                int msg_type_int = static_cast<int>(msg_type);
                msg_handler_by_msg_type_[msg_type_int](std::move(msg));
            }
        }
    }

    recv_queue_->pending_request_list_.erase(
        std::remove_if(
            recv_queue_->pending_request_list_.begin(),
            recv_queue_->pending_request_list_.end(),
            [&](const std::unique_ptr<PendingRequest>& pr) { return pr->flag_; }),
        recv_queue_->pending_request_list_.end());

    return count;

}

} // namespace warped

<|endoftext|>


<commit_before>/*
 * File:  static_context.cpp
 * Copyright (C) 2010 The Institute for System Programming of the Russian Academy of Sciences (ISP RAS)
 */

#include "tr/executor/base/static_context.h"
#include "tr/executor/base/xs_uri.h"
#include "tr/executor/base/PPBase.h"
#include "tr/executor/base/xs_helper.h"

CollationManager static_context::collation_manager;

static_context::static_context()
{
    /* Initialize default values for prolog defined values */
    prolog_set_fields = 0;
    boundary_space = xq_boundary_space_strip;
    default_collation_uri = NULL;
    base_uri = NULL;
    preserve_type = false;
    ordering_mode = xq_ordering_mode_ordered;
    empty_order = xq_empty_order_least;
    cn_preserve = false;
    cn_inherit = false;

    /*
     * Set codepoint collation as the default one.
     * static_context::set_default_collation() is too complex to be called from constructor.
     * Probably it's better to make default value NULL?
     */
    const char* codepoint_collation_uri = "http://www.w3.org/2005/xpath-functions/collation/codepoint";
    default_collation_uri = new char[strlen(codepoint_collation_uri) + 1];
    strcpy(default_collation_uri, codepoint_collation_uri);
    default_collation_handler = collation_manager.get_collation_handler(codepoint_collation_uri);

    /* Default serialization options */
    serializationOptions.indent = true;
    serializationOptions.indentSequence = "  ";
    serializationOptions.separateTuples = true;
    serializationOptions.useCharmap = true;
}

static_context::~static_context()
{
    if (base_uri != NULL)
    {
        delete[] base_uri;
        base_uri = NULL;
    }

    if (default_collation_uri != NULL)
    {
        delete[] default_collation_uri;
        default_collation_uri = NULL;
    }
}

void static_context::set_base_uri(const char * _base_uri_)
{
    /* Check constraints on URILiteral. */
    bool valid;
    const char * _base_uri = _base_uri_;
    Uri::Information nfo;
    Uri::check_constraints(_base_uri, &valid, &nfo);
    if (!valid) throw XQUERY_EXCEPTION2(XQST0046, "Prolog base-uri property contains invalid URI.");

    /* Delete old value if any. */
    if(base_uri != NULL)
    {
        delete base_uri;
        base_uri = NULL;
    }

    /* If provided URI is relative considering this property as undefined */
    if (nfo.type == Uri::UT_RELATIVE) {
        stmt_str_buf resolved_uri(1);
        Uri::resolve(_base_uri, "sedna://", resolved_uri);
        _base_uri = resolved_uri.get_str();
    }

    /* Normalize URI if needed and create new value. */
    if(!nfo.normalized)
    {
        stmt_str_buf result;
        collapse_string_normalization(_base_uri, result);
        tuple_cell tc = result.get_tuple_cell();
        tc = tuple_cell::make_sure_light_atomic(tc);
        base_uri = new char[tc.get_strlen_mem() + 1];
        strcpy(base_uri, tc.get_str_mem());
    }
    else
    {
        base_uri = new char[strlen(_base_uri) + 1];
        strcpy(base_uri, _base_uri);
    }
    set_field_flag(SC_BASE_URI);
}

void static_context::set_default_collation_uri(const char* _default_collation_uri_)
{
    tuple_cell tc;

    /* Check constraints on URILiteral. */
    bool valid;
    Uri::Information nfo;
    Uri::check_constraints(_default_collation_uri_, &valid, &nfo);
    if (!valid) throw XQUERY_EXCEPTION2(XQST0046, "Prolog default-collation property contains invalid URI.");

    if (nfo.type == Uri::UT_RELATIVE && base_uri == NULL)
        throw XQUERY_EXCEPTION2(XQST0038, "Unknown collation in prolog (it could not be relative while base-uri is not defined).");

    const char* normalized_value = _default_collation_uri_;

    /* Normalize URI if needed. */
    if(!nfo.normalized)
    {
        stmt_str_buf result;
        collapse_string_normalization(_default_collation_uri_, result);
        tc = tuple_cell::make_sure_light_atomic(result.get_tuple_cell());
        normalized_value = tc.get_str_mem();
    }

    /* And try to resolve it over base-uri property if it is relative. */
    if(nfo.type == Uri::UT_RELATIVE)
    {
       try
       {
           stmt_str_buf result;
           if(!Uri::resolve(normalized_value, base_uri, result))
               throw USER_EXCEPTION2(SE1003, "Unexpected URI resolving error in set_default_collation.");
           tc = tuple_cell::make_sure_light_atomic(result.get_tuple_cell());
           normalized_value = tc.get_str_mem();
       }
       catch(SednaUserException &e)
       {
           if(e.get_code() == FORG0009) throw XQUERY_EXCEPTION2(XQST0038, "Unknown collation in prolog (possibly, base-uri contains relative URI).");
           throw;
       }
    }

    default_collation_handler = collation_manager.get_collation_handler(normalized_value);
    if(default_collation_handler == NULL) throw XQUERY_EXCEPTION2(XQST0038, "Unknown collation in prolog (statically unknown collation).");

    if (default_collation_uri != NULL) delete[] default_collation_uri;
    default_collation_uri = new char[strlen(normalized_value) + 1];
    strcpy(default_collation_uri, normalized_value);
    set_field_flag(SC_DEFAULT_COLLATION_URI);
}

int static_context::get_collation(const char *uri, /* out */ CollationHandler** handler)
{
    if ( !uri )
    {
        *handler = get_default_collation();
        return 0;
    }

    /* 1. Check constraints on the given URI. */
    bool valid;
    Uri::Information nfo;
    Uri::check_constraints(uri, &valid, &nfo);
    if ( !valid ) return COLLATION_INVALID_URI;

    if(nfo.type == Uri::UT_RELATIVE && base_uri == NULL)
        return COLLATION_RESOLVE_ERR;

    tuple_cell tc;
    const char *normalized_value = uri;

    /* 2. Normalize URI if needed. */
    if(!nfo.normalized)
    {
        stmt_str_buf result;
        collapse_string_normalization(normalized_value, result);
        tc = tuple_cell::make_sure_light_atomic(result.get_tuple_cell());
        normalized_value = tc.get_str_mem();
    }

    /* 3. And try to resolve it over base-uri property if it is relative. */
    if(nfo.type == Uri::UT_RELATIVE)
    {
       try
       {
           stmt_str_buf result;
           if(!Uri::resolve(normalized_value, base_uri, result))
               throw USER_EXCEPTION2(SE1003, "Unexpected URI resolving error in get_collation.");
           tc = tuple_cell::make_sure_light_atomic(result.get_tuple_cell());
           normalized_value = tc.get_str_mem();
       }
       catch(SednaUserException &e)
       {
           if(e.get_code() == FORG0009) return COLLATION_RESOLVE_ERR;
           throw;
       }
    }

    /// 4. Get handler from the resolved and normalized value.
    *handler = collation_manager.get_collation_handler(normalized_value);
    if (!*handler) return COLLATION_MISS;
    return 0;
}
<commit_msg>base uri in static context leak and logic fixed<commit_after>/*
 * File:  static_context.cpp
 * Copyright (C) 2010 The Institute for System Programming of the Russian Academy of Sciences (ISP RAS)
 */

#include "tr/executor/base/static_context.h"
#include "tr/executor/base/xs_uri.h"
#include "tr/executor/base/PPBase.h"
#include "tr/executor/base/xs_helper.h"

CollationManager static_context::collation_manager;

static_context::static_context()
{
    /* Initialize default values for prolog defined values */
    prolog_set_fields = 0;
    boundary_space = xq_boundary_space_strip;
    default_collation_uri = NULL;
    base_uri = NULL;
    preserve_type = false;
    ordering_mode = xq_ordering_mode_ordered;
    empty_order = xq_empty_order_least;
    cn_preserve = false;
    cn_inherit = false;

    /*
     * Set codepoint collation as the default one.
     * static_context::set_default_collation() is too complex to be called from constructor.
     * Probably it's better to make default value NULL?
     */
    const char* codepoint_collation_uri = "http://www.w3.org/2005/xpath-functions/collation/codepoint";
    default_collation_uri = new char[strlen(codepoint_collation_uri) + 1];
    strcpy(default_collation_uri, codepoint_collation_uri);
    default_collation_handler = collation_manager.get_collation_handler(codepoint_collation_uri);

    /* Default serialization options */
    serializationOptions.indent = true;
    serializationOptions.indentSequence = "  ";
    serializationOptions.separateTuples = true;
    serializationOptions.useCharmap = true;
}

static_context::~static_context()
{
    if (base_uri != NULL)
    {
        delete[] base_uri;
        base_uri = NULL;
    }

    if (default_collation_uri != NULL)
    {
        delete[] default_collation_uri;
        default_collation_uri = NULL;
    }
}

void static_context::set_base_uri(const char * _base_uri_)
{
    /* Check constraints on URILiteral. */
    bool valid;
    bool free_memory = false;
    const char * _base_uri = _base_uri_;
    Uri::Information nfo;
    Uri::check_constraints(_base_uri, &valid, &nfo);
    if (!valid) throw XQUERY_EXCEPTION2(XQST0046, "Prolog base-uri property contains invalid URI.");

    /* Delete old value if any. */
    if(base_uri != NULL)
    {
        delete base_uri;
        base_uri = NULL;
    }

    /* Normalize URI if needed and create new value. */
    if(!nfo.normalized)
    {
        stmt_str_buf result(1);
        collapse_string_normalization(_base_uri, result);
        _base_uri = result.get_str();
        free_memory = true;
    }

    /* If provided URI is relative resolve it with implementation defined schema */
    if (nfo.type == Uri::UT_RELATIVE) {
        stmt_str_buf resolved_uri(1);
        Uri::resolve(_base_uri, "sedna://", resolved_uri);
        if(free_memory)
        {
            delete [] _base_uri;
        }
        _base_uri = resolved_uri.get_str();
        free_memory = true;
    }

    if(!free_memory)
    {
        base_uri = new char[strlen(_base_uri) + 1];
        strcpy(base_uri, _base_uri);
    }
    else
    {
        base_uri = (char*)_base_uri;
    }

    set_field_flag(SC_BASE_URI);
}

void static_context::set_default_collation_uri(const char* _default_collation_uri_)
{
    tuple_cell tc;

    /* Check constraints on URILiteral. */
    bool valid;
    Uri::Information nfo;
    Uri::check_constraints(_default_collation_uri_, &valid, &nfo);
    if (!valid) throw XQUERY_EXCEPTION2(XQST0046, "Prolog default-collation property contains invalid URI.");

    if (nfo.type == Uri::UT_RELATIVE && base_uri == NULL)
        throw XQUERY_EXCEPTION2(XQST0038, "Unknown collation in prolog (it could not be relative while base-uri is not defined).");

    const char* normalized_value = _default_collation_uri_;

    /* Normalize URI if needed. */
    if(!nfo.normalized)
    {
        stmt_str_buf result;
        collapse_string_normalization(_default_collation_uri_, result);
        tc = tuple_cell::make_sure_light_atomic(result.get_tuple_cell());
        normalized_value = tc.get_str_mem();
    }

    /* And try to resolve it over base-uri property if it is relative. */
    if(nfo.type == Uri::UT_RELATIVE)
    {
       try
       {
           stmt_str_buf result;
           if(!Uri::resolve(normalized_value, base_uri, result))
               throw USER_EXCEPTION2(SE1003, "Unexpected URI resolving error in set_default_collation.");
           tc = tuple_cell::make_sure_light_atomic(result.get_tuple_cell());
           normalized_value = tc.get_str_mem();
       }
       catch(SednaUserException &e)
       {
           if(e.get_code() == FORG0009) throw XQUERY_EXCEPTION2(XQST0038, "Unknown collation in prolog (possibly, base-uri contains relative URI).");
           throw;
       }
    }

    default_collation_handler = collation_manager.get_collation_handler(normalized_value);
    if(default_collation_handler == NULL) throw XQUERY_EXCEPTION2(XQST0038, "Unknown collation in prolog (statically unknown collation).");

    if (default_collation_uri != NULL) delete[] default_collation_uri;
    default_collation_uri = new char[strlen(normalized_value) + 1];
    strcpy(default_collation_uri, normalized_value);
    set_field_flag(SC_DEFAULT_COLLATION_URI);
}

int static_context::get_collation(const char *uri, /* out */ CollationHandler** handler)
{
    if ( !uri )
    {
        *handler = get_default_collation();
        return 0;
    }

    /* 1. Check constraints on the given URI. */
    bool valid;
    Uri::Information nfo;
    Uri::check_constraints(uri, &valid, &nfo);
    if ( !valid ) return COLLATION_INVALID_URI;

    if(nfo.type == Uri::UT_RELATIVE && base_uri == NULL)
        return COLLATION_RESOLVE_ERR;

    tuple_cell tc;
    const char *normalized_value = uri;

    /* 2. Normalize URI if needed. */
    if(!nfo.normalized)
    {
        stmt_str_buf result;
        collapse_string_normalization(normalized_value, result);
        tc = tuple_cell::make_sure_light_atomic(result.get_tuple_cell());
        normalized_value = tc.get_str_mem();
    }

    /* 3. And try to resolve it over base-uri property if it is relative. */
    if(nfo.type == Uri::UT_RELATIVE)
    {
       try
       {
           stmt_str_buf result;
           if(!Uri::resolve(normalized_value, base_uri, result))
               throw USER_EXCEPTION2(SE1003, "Unexpected URI resolving error in get_collation.");
           tc = tuple_cell::make_sure_light_atomic(result.get_tuple_cell());
           normalized_value = tc.get_str_mem();
       }
       catch(SednaUserException &e)
       {
           if(e.get_code() == FORG0009) return COLLATION_RESOLVE_ERR;
           throw;
       }
    }

    /// 4. Get handler from the resolved and normalized value.
    *handler = collation_manager.get_collation_handler(normalized_value);
    if (!*handler) return COLLATION_MISS;
    return 0;
}
<|endoftext|>


<commit_before>#include <iostream>
#include <iterator>
#include <algorithm>
#include <fstream>
#include <list>
#include <string>
#include <vector>
#include <set>
#include<utility>

bool GT6(const std::string &s)
{
    return s.size() >6;
}

class GT_cls
{
    public:
      GT_cls(std::size_t val = 0):bound(val) {}
      bool operator() (const std::string & s) { return s.size() >= bound;}
    private:
      std::string::size_type bound;
};

class equal_cls
{
    public:
        equal_cls(int i = 0):val(i) {}
        bool operator() (const int & i ) { return  i==val; }
    private:
       int val;
};

//test code
int main()
{

    std::vector<std::string> words;
    std::string word;
    while(std::cin>>word)
    {
        words.push_back(word);
    }

    std::vector<std::string>::size_type wc = std::count_if(words.begin(),words.end(),GT6);
    std::cout<<wc<<std::endl;

    std::vector<std::string>::size_type wc1 = std::count_if(words.begin(),words.end(),GT_cls(6));
    std::cout<<wc1<<std::endl;

    std::vector<std::string>::size_type wc2 = std::count_if(words.begin(),words.end(),GT_cls(2));
    std::cout<<wc2<<std::endl;

    std::vector<std::string>::iterator i = std::find_if(words.begin(), words.end(),GT_cls(2));
    std::cout<<*i<<std::endl;

    //test equal_cls
    std::vector<int> ivec(10);
    std::vector<int>::size_type cn = std::count_if(ivec.begin(), ivec.end(),equal_cls());
    std::cout<<cn<<std::endl;
    std::vector<int>::size_type cn1 = std::count_if(ivec.begin(),ivec.end(),equal_cls(10));
    std::cout<<cn1<<std::endl;
    return 0;

}

<commit_msg>Update functionObejectAndAlgorithm.cpp<commit_after>#include <iostream>
#include <iterator>
#include <algorithm>
#include <fstream>
#include <list>
#include <string>
#include <vector>
#include <set>
#include<utility>

bool GT6(const std::string &s)
{
    return s.size() >6;
}

class GT_cls
{
    public:
      GT_cls(std::size_t val = 0):bound(val) {}
      bool operator() (const std::string & s) { return s.size() >= bound;}
    private:
      std::string::size_type bound;
};

class equal_cls
{
    public:
        equal_cls(int i = 0):val(i) {}
        bool operator() (const int & i ) { return  i==val; }
    private:
       int val;
};

//test code
int main()
{

    std::vector<std::string> words;
    std::string word;
    while(std::cin>>word)
    {
        words.push_back(word);
    }

    std::vector<std::string>::size_type wc = std::count_if(words.begin(),words.end(),GT6);
    std::cout<<wc<<std::endl;

    std::vector<std::string>::size_type wc1 = std::count_if(words.begin(),words.end(),GT_cls(6));
    std::cout<<wc1<<std::endl;

    std::vector<std::string>::size_type wc2 = std::count_if(words.begin(),words.end(),GT_cls(2));
    std::cout<<wc2<<std::endl;

    std::vector<std::string>::iterator i = std::find_if(words.begin(), words.end(),GT_cls(2));
    std::cout<<*i<<std::endl;

    //test equal_cls
    std::vector<int> ivec(10);
    std::vector<int>::size_type cn = std::count_if(ivec.begin(), ivec.end(),equal_cls());
    std::cout<<cn<<std::endl;
    std::vector<int>::size_type cn1 = std::count_if(ivec.begin(),ivec.end(),equal_cls(10));
    std::cout<<cn1<<std::endl;

    //use std::functional  and function adapter

    std::vector<int> ivec;
    ivec.reserve(1030);
    for(int i = 0 ; i <1030 ;++i)
    {
        ivec.push_back(i);
    }

    //find all value that is greater than 1024
    std::vector<int>::iterator result = std::find_if(ivec.begin() ,  ivec.end() , std::bind2nd(std::greater<int>() ,1024) );

    while(result != ivec.end())
    {
        std::cout<<*result<<std::endl;
        result = std::find_if( ++result ,  ivec.end() , std::bind2nd(std::greater<int>() ,1024) );
    }

    std::vector<std::string> svec;
    svec.push_back("hello world");
    svec.push_back("test");
    svec.push_back("huqijun");
    svec.push_back("pooh");

    //find all value that is not equal to "pooh"
    std::vector<std::string>::iterator ret = std::find_if(svec.begin(),svec.end(),std::bind2nd(std::not_equal_to<std::string>(),"pooh") );
    while(ret != svec.end())
    {
        std::cout<<*ret<<std::endl;
        ret = std::find_if(++ret,svec.end(),std::bind2nd(std::not_equal_to<std::string>(),"pooh") );
    }

    //double every value
    std::vector<int> ivec2;
    ivec2.reserve(12);
    for(int i = 0; i<12 ; ++i)
    {
        ivec2.push_back(i);
    }

    std::for_each(ivec2.begin(),ivec2.end(),std::bind2nd(std::multiplies<int>(),2) );

    for(std::vector<int>::iterator i = ivec2.begin() ;  i!= ivec2.end()  ; ++i)
    {
        std::cout<<*i<<std::endl;
    }

    return 0;

}

<|endoftext|>


<commit_before>/* This file is part of Strigi Desktop Search
 *
 * Copyright (C) 2006 Jos van den Oever <jos@vandenoever.info>
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Library General Public
 * License as published by the Free Software Foundation; either
 * version 2 of the License, or (at your option) any later version.
 *
 * This 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
 * Library General Public License for more details.
 *
 * You should have received a copy of the GNU Library General Public License
 * along with this library; see the file COPYING.LIB.  If not, write to
 * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
 * Boston, MA 02110-1301, USA.
 */
#include <strigi/strigiconfig.h>
#include "dummyindexwriter.h"
#include "streamanalyzer.h"
#include "analyzerconfiguration.h"
#include "streamendanalyzer.h"
#include "diranalyzer.h"
using namespace Strigi;
using namespace std;

/**
 * Special indexer that indexes only the filenames.
 **/
class FindIndexerConfiguration : public AnalyzerConfiguration {
public:
    bool useFactory(StreamEndAnalyzerFactory* e) const {
        return e->analyzesSubStreams();
    }
    bool useFactory(StreamThroughAnalyzerFactory*) const {return false;}
    bool indexMore() const {return true;}
    bool addMoreText() const {return false;}
    FieldType indexType(const string& fieldname) const {
        return None;
    }
};

void
printUsage(char** argv) {
    fprintf(stderr, "Usage: %s [dir-or-file-to-find]\n", argv[0]);
}
bool
containsHelp(int argc, char **argv) {
    for (int i=1; i<argc; ++i) {
         if (strcmp(argv[i], "--help") == 0
             || strcmp(argv[i], "-h") == 0) return true;
    }
    return false;
}

int
main(int argc, char **argv) {
    const char* path = ".";
    if (containsHelp(argc, argv) || argc > 2) {
        printUsage(argv);
        return -1;
    }
    if (argc == 2) {
        path = argv[1];
    }

    DummyIndexManager manager(0);
    FindIndexerConfiguration conf;
    DirAnalyzer analyzer(manager, conf);
    analyzer.analyzeDir(path);
    return 0;
}
<commit_msg>Make sure deepfind actually prints the names of the files.<commit_after>/* This file is part of Strigi Desktop Search
 *
 * Copyright (C) 2006 Jos van den Oever <jos@vandenoever.info>
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Library General Public
 * License as published by the Free Software Foundation; either
 * version 2 of the License, or (at your option) any later version.
 *
 * This 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
 * Library General Public License for more details.
 *
 * You should have received a copy of the GNU Library General Public License
 * along with this library; see the file COPYING.LIB.  If not, write to
 * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
 * Boston, MA 02110-1301, USA.
 */
#include <strigi/strigiconfig.h>
#include "dummyindexwriter.h"
#include "streamanalyzer.h"
#include "analyzerconfiguration.h"
#include "streamendanalyzer.h"
#include "diranalyzer.h"
using namespace Strigi;
using namespace std;

/**
 * Special indexer that indexes only the filenames.
 **/
class FindIndexerConfiguration : public AnalyzerConfiguration {
public:
    bool useFactory(StreamEndAnalyzerFactory* e) const {
        return e->analyzesSubStreams();
    }
    bool useFactory(StreamThroughAnalyzerFactory*) const {return false;}
    bool indexMore() const {return true;}
    bool addMoreText() const {return false;}
    FieldType indexType(const string& fieldname) const {
        return None;
    }
};

void
printUsage(char** argv) {
    fprintf(stderr, "Usage: %s [dir-or-file-to-find]\n", argv[0]);
}
bool
containsHelp(int argc, char **argv) {
    for (int i=1; i<argc; ++i) {
         if (strcmp(argv[i], "--help") == 0
             || strcmp(argv[i], "-h") == 0) return true;
    }
    return false;
}

int
main(int argc, char **argv) {
    const char* path = ".";
    if (containsHelp(argc, argv) || argc > 2) {
        printUsage(argv);
        return -1;
    }
    if (argc == 2) {
        path = argv[1];
    }

    DummyIndexManager manager(1);
    FindIndexerConfiguration conf;
    DirAnalyzer analyzer(manager, conf);
    analyzer.analyzeDir(path);
    return 0;
}
<|endoftext|>


<commit_before>/*
    kopeteonlinestatus.cpp - Kopete Online Status

    Copyright (c) 2002-2004 by Olivier Goffart       <ogoffart@tiscalinet.be>
    Copyright (c) 2003      by Martijn Klingens      <klingens@kde.org>

    Kopete    (c) 2002-2004 by the Kopete developers <kopete-devel@kde.org>

    *************************************************************************
    *                                                                       *
    * This program is free software; you can redistribute it and/or modify  *
    * it under the terms of the GNU General Public License as published by  *
    * the Free Software Foundation; either version 2 of the License, or     *
    * (at your option) any later version.                                   *
    *                                                                       *
    *************************************************************************
*/

#include <qpainter.h>

#include <klocale.h>
#include <kiconloader.h>
#include <kdebug.h>
#include <kapplication.h>

#include "kopetecontactlistview.h"
#include "kopetegroupviewitem.h"
#include "kopetegroup.h"
#include "kopeteonlinestatus.h"
#include "kopeteprefs.h"
#include "kopetemetacontactlvi.h"
#include "kopetemetacontact.h"

#include <memory>

using namespace Kopete::UI;

class KopeteGroupViewItem::Private
{
public:
	ListView::ImageComponent *image;
	ListView::TextComponent *name;
	ListView::TextComponent *count;
	std::auto_ptr<ListView::ToolTipSource> toolTipSource;
};

namespace Kopete {
namespace UI {
namespace ListView {

class GroupToolTipSource : public ToolTipSource
{
public:
	GroupToolTipSource( KopeteGroupViewItem *gp )
	 : group( gp )
	{
	}
	QString operator()( ComponentBase *, const QPoint &, QRect & )
	{
		return group->toolTip();
	}
private:
	KopeteGroupViewItem *group;
};

} // END namespace ListView
} // END namespace UI
} // END namespace Kopete

KopeteGroupViewItem::KopeteGroupViewItem( Kopete::Group *group_, QListView *parent, const char *name )
: Kopete::UI::ListView::Item( parent, group_, name )
{
	m_group = group_;
	initLVI();
}

KopeteGroupViewItem::KopeteGroupViewItem( Kopete::Group *group_, QListViewItem *parent, const char *name )
 : Kopete::UI::ListView::Item( parent, group_, name )
{
	m_group = group_;
	initLVI();
}

KopeteGroupViewItem::~KopeteGroupViewItem()
{
	delete d;
}

void KopeteGroupViewItem::initLVI()
{
	d = new Private;

	d->toolTipSource.reset( new ListView::GroupToolTipSource( this ) );

	using namespace ListView;
	Component *hbox = new BoxComponent( this, BoxComponent::Horizontal );
	d->image = new ImageComponent( hbox );
	d->name = new TextComponent( hbox );
	d->count = new TextComponent( hbox );

	d->image->setToolTipSource( d->toolTipSource.get() );
	d->name->setToolTipSource( d->toolTipSource.get() );
	d->count->setToolTipSource( d->toolTipSource.get() );

	connect( m_group, SIGNAL( displayNameChanged( Kopete::Group*, const QString& ) ),
		this, SLOT( refreshDisplayName() ) );

	connect( KopetePrefs::prefs(), SIGNAL( contactListAppearanceChanged() ),
		SLOT( slotConfigChanged() ) );
	connect( kapp, SIGNAL( appearanceChanged() ),  SLOT( slotConfigChanged() ) );

	connect( m_group, SIGNAL( iconAppearanceChanged() ), SLOT( updateIcon() ) );

	refreshDisplayName();
	slotConfigChanged();
}

Kopete::Group* KopeteGroupViewItem::group() const
{
	return m_group;
}

QString KopeteGroupViewItem::toolTip() const
{
	// TODO: add icon, and some more information than that which
	// is already displayed in the list view item
	// FIXME: post-KDE-3.3, make this better i18n-able
	//  currently it can't cause more problems than the contact list itself, at least.
	return "" + d->name->text() + " " + d->count->text();
}

void KopeteGroupViewItem::slotConfigChanged()
{
	updateIcon();
	updateVisibility();

	d->name->setColor( KopetePrefs::prefs()->contactListGroupNameColor() );

	QFont font = listView()->font();
	if ( KopetePrefs::prefs()->contactListUseCustomFonts() )
		font = KopetePrefs::prefs()->contactListCustomNormalFont();
	d->name->setFont( font );

	d->count->setFont( KopetePrefs::prefs()->contactListSmallFont() );
}

void KopeteGroupViewItem::refreshDisplayName()
{
	totalMemberCount = 0;
	onlineMemberCount = 0;

	for ( QListViewItem *lvi = firstChild(); lvi; lvi = lvi->nextSibling() )
	{
		if ( KopeteMetaContactLVI *kc = dynamic_cast<KopeteMetaContactLVI*>( lvi ) )
		{
			totalMemberCount++;
			if ( kc->metaContact()->isOnline() )
				onlineMemberCount++;
		}
	}

	d->name->setText( m_group->displayName() );
	d->count->setText( i18n( "(NUMBER OF ONLINE CONTACTS/NUMBER OF CONTACTS IN GROUP)", "(%1/%2)" )
	                  .arg( QString::number( onlineMemberCount ), QString::number( totalMemberCount ) ) );

	updateVisibility();

	// Sorting in this slot is extremely expensive as it's called dozens of times and
	// the sorting itself is rather slow. Therefore we call delayedSort, which tries
	// to group multiple sort requests into one.
	if ( ListView::ListView *lv = dynamic_cast<ListView::ListView *>( listView() ) )
		lv->delayedSort();
	else
		listView()->sort();
}

QString KopeteGroupViewItem::key( int, bool ) const
{
	//Groups are placed after topLevel contact.
	//Exepted Temporary group which is the first group
	if ( group()->type() != Kopete::Group::Normal )
		return "0" + d->name->text();
	return "M" + d->name->text();
}

void KopeteGroupViewItem::startRename( int /*col*/ )
{
	//kdDebug(14000) << k_funcinfo << endl;
	KListViewItem::startRename( 0 );
}

void KopeteGroupViewItem::okRename( int col )
{
	//kdDebug(14000) << k_funcinfo << endl;
	KListViewItem::okRename(col);
	setRenameEnabled( 0, false );
}

void KopeteGroupViewItem::cancelRename( int col )
{
	//kdDebug(14000) << k_funcinfo << endl;
	KListViewItem::cancelRename(col);
	setRenameEnabled( 0, false );
}

void KopeteGroupViewItem::updateVisibility()
{
	//FIXME: A contact can ve visible if he has a unknwon status (it's not online)
	//       or if he has an event (blinking icon).  If such as contact is not with
	//       others inline contact in the group. the group will stay hidden.
	int visibleUsers = onlineMemberCount;
	if ( KopetePrefs::prefs()->showOffline() )
		visibleUsers = totalMemberCount;

	bool visible = KopetePrefs::prefs()->showEmptyGroups() || ( visibleUsers > 0 );

	if ( isVisible() != visible )
	{
		setTargetVisibility( visible );
		if ( visible )
		{
			// When calling setVisible(true) EVERY child item will be shown,
			// even if they should be hidden.
			// We just re-update the visibility of all child items
			for ( QListViewItem *lvi = firstChild(); lvi; lvi = lvi->nextSibling() )
			{
				if ( KopeteMetaContactLVI *kmc = dynamic_cast<KopeteMetaContactLVI *>( lvi ) )
					kmc->updateVisibility();
			}
		}
	}
}

void KopeteGroupViewItem::updateIcon()
{
	// TODO: clever caching
	if ( isOpen() )
	{
		if ( group()->useCustomIcon() && !group()->icon( Kopete::ContactListElement::Open ).isEmpty() )
			open = SmallIcon( group()->icon( Kopete::ContactListElement::Open ) );
		else
			open = SmallIcon( KOPETE_GROUP_DEFAULT_OPEN_ICON );

		d->image->setPixmap( open );
	}
	else
	{
		if ( group()->useCustomIcon() && !group()->icon( Kopete::ContactListElement::Closed ).isEmpty() )
			closed = SmallIcon( group()->icon( Kopete::ContactListElement::Closed ) );
		else
			closed = SmallIcon( KOPETE_GROUP_DEFAULT_CLOSED_ICON );

		d->image->setPixmap( closed );
	}
}

QString KopeteGroupViewItem::text( int column ) const
{
	if ( column == 0 )
		return d->name->text();
	else
		return KListViewItem::text( column );
}

void KopeteGroupViewItem::setText( int column, const QString &text )
{
	if ( column == 0 )
	{
		KopeteContactListView *lv = dynamic_cast<KopeteContactListView *>( listView() );
		if ( lv )
		{
			KopeteContactListView::UndoItem *u=new KopeteContactListView::UndoItem(KopeteContactListView::UndoItem::GroupRename, 0L, m_group);
			u->args << m_group->displayName();
			lv->insertUndoItem(u);
		}
		group()->setDisplayName( text );
	}
	else
		KListViewItem::setText( column, text );
}

#include "kopetegroupviewitem.moc"
// vim: set noet ts=4 sts=4 sw=4:

<commit_msg><commit_after>/*
    kopeteonlinestatus.cpp - Kopete Online Status

    Copyright (c) 2002-2004 by Olivier Goffart       <ogoffart@tiscalinet.be>
    Copyright (c) 2003      by Martijn Klingens      <klingens@kde.org>

    Kopete    (c) 2002-2004 by the Kopete developers <kopete-devel@kde.org>

    *************************************************************************
    *                                                                       *
    * This program is free software; you can redistribute it and/or modify  *
    * it under the terms of the GNU General Public License as published by  *
    * the Free Software Foundation; either version 2 of the License, or     *
    * (at your option) any later version.                                   *
    *                                                                       *
    *************************************************************************
*/

#include <qpainter.h>

#include <klocale.h>
#include <kiconloader.h>
#include <kdebug.h>
#include <kapplication.h>

#include "kopetecontactlistview.h"
#include "kopetegroupviewitem.h"
#include "kopetegroup.h"
#include "kopeteonlinestatus.h"
#include "kopeteprefs.h"
#include "kopetemetacontactlvi.h"
#include "kopetemetacontact.h"

#include <memory>

//using namespace Kopete::UI;

class KopeteGroupViewItem::Private
{
public:
	Kopete::UI::ListView::ImageComponent *image;
	Kopete::UI::ListView::TextComponent *name;
	Kopete::UI::ListView::TextComponent *count;
	std::auto_ptr<Kopete::UI::ListView::ToolTipSource> toolTipSource;
};

namespace Kopete {
namespace UI {
namespace ListView {

class GroupToolTipSource : public ToolTipSource
{
public:
	GroupToolTipSource( KopeteGroupViewItem *gp )
	 : group( gp )
	{
	}
	QString operator()( ComponentBase *, const QPoint &, QRect & )
	{
		return group->toolTip();
	}
private:
	KopeteGroupViewItem *group;
};

} // END namespace ListView
} // END namespace UI
} // END namespace Kopete

KopeteGroupViewItem::KopeteGroupViewItem( Kopete::Group *group_, QListView *parent, const char *name )
: Kopete::UI::ListView::Item( parent, group_, name )
{
	m_group = group_;
	initLVI();
}

KopeteGroupViewItem::KopeteGroupViewItem( Kopete::Group *group_, QListViewItem *parent, const char *name )
 : Kopete::UI::ListView::Item( parent, group_, name )
{
	m_group = group_;
	initLVI();
}

KopeteGroupViewItem::~KopeteGroupViewItem()
{
	delete d;
}

void KopeteGroupViewItem::initLVI()
{
	d = new Private;

	d->toolTipSource.reset( new Kopete::UI::ListView::GroupToolTipSource( this ) );

	using namespace Kopete::UI::ListView;
	Component *hbox = new BoxComponent( this, BoxComponent::Horizontal );
	d->image = new ImageComponent( hbox );
	d->name = new TextComponent( hbox );
	d->count = new TextComponent( hbox );

	d->image->setToolTipSource( d->toolTipSource.get() );
	d->name->setToolTipSource( d->toolTipSource.get() );
	d->count->setToolTipSource( d->toolTipSource.get() );

	connect( m_group, SIGNAL( displayNameChanged( Kopete::Group*, const QString& ) ),
		this, SLOT( refreshDisplayName() ) );

	connect( KopetePrefs::prefs(), SIGNAL( contactListAppearanceChanged() ),
		SLOT( slotConfigChanged() ) );
	connect( kapp, SIGNAL( appearanceChanged() ),  SLOT( slotConfigChanged() ) );

	connect( m_group, SIGNAL( iconAppearanceChanged() ), SLOT( updateIcon() ) );

	refreshDisplayName();
	slotConfigChanged();
}

Kopete::Group* KopeteGroupViewItem::group() const
{
	return m_group;
}

QString KopeteGroupViewItem::toolTip() const
{
	// TODO: add icon, and some more information than that which
	// is already displayed in the list view item
	// FIXME: post-KDE-3.3, make this better i18n-able
	//  currently it can't cause more problems than the contact list itself, at least.
	return "" + d->name->text() + " " + d->count->text();
}

void KopeteGroupViewItem::slotConfigChanged()
{
	updateIcon();
	updateVisibility();

	d->name->setColor( KopetePrefs::prefs()->contactListGroupNameColor() );

	QFont font = listView()->font();
	if ( KopetePrefs::prefs()->contactListUseCustomFonts() )
		font = KopetePrefs::prefs()->contactListCustomNormalFont();
	d->name->setFont( font );

	d->count->setFont( KopetePrefs::prefs()->contactListSmallFont() );
}

void KopeteGroupViewItem::refreshDisplayName()
{
	totalMemberCount = 0;
	onlineMemberCount = 0;

	for ( QListViewItem *lvi = firstChild(); lvi; lvi = lvi->nextSibling() )
	{
		if ( KopeteMetaContactLVI *kc = dynamic_cast<KopeteMetaContactLVI*>( lvi ) )
		{
			totalMemberCount++;
			if ( kc->metaContact()->isOnline() )
				onlineMemberCount++;
		}
	}

	d->name->setText( m_group->displayName() );
	d->count->setText( i18n( "(NUMBER OF ONLINE CONTACTS/NUMBER OF CONTACTS IN GROUP)", "(%1/%2)" )
	                  .arg( QString::number( onlineMemberCount ), QString::number( totalMemberCount ) ) );

	updateVisibility();

	// Sorting in this slot is extremely expensive as it's called dozens of times and
	// the sorting itself is rather slow. Therefore we call delayedSort, which tries
	// to group multiple sort requests into one.
	using namespace Kopete::UI::ListView;
	if ( ListView::ListView *lv = dynamic_cast<ListView::ListView *>( listView() ) )
		lv->delayedSort();
	else
		listView()->sort();
}

QString KopeteGroupViewItem::key( int, bool ) const
{
	//Groups are placed after topLevel contact.
	//Exepted Temporary group which is the first group
	if ( group()->type() != Kopete::Group::Normal )
		return "0" + d->name->text();
	return "M" + d->name->text();
}

void KopeteGroupViewItem::startRename( int /*col*/ )
{
	//kdDebug(14000) << k_funcinfo << endl;
	KListViewItem::startRename( 0 );
}

void KopeteGroupViewItem::okRename( int col )
{
	//kdDebug(14000) << k_funcinfo << endl;
	KListViewItem::okRename(col);
	setRenameEnabled( 0, false );
}

void KopeteGroupViewItem::cancelRename( int col )
{
	//kdDebug(14000) << k_funcinfo << endl;
	KListViewItem::cancelRename(col);
	setRenameEnabled( 0, false );
}

void KopeteGroupViewItem::updateVisibility()
{
	//FIXME: A contact can ve visible if he has a unknwon status (it's not online)
	//       or if he has an event (blinking icon).  If such as contact is not with
	//       others inline contact in the group. the group will stay hidden.
	int visibleUsers = onlineMemberCount;
	if ( KopetePrefs::prefs()->showOffline() )
		visibleUsers = totalMemberCount;

	bool visible = KopetePrefs::prefs()->showEmptyGroups() || ( visibleUsers > 0 );

	if ( isVisible() != visible )
	{
		setTargetVisibility( visible );
		if ( visible )
		{
			// When calling setVisible(true) EVERY child item will be shown,
			// even if they should be hidden.
			// We just re-update the visibility of all child items
			for ( QListViewItem *lvi = firstChild(); lvi; lvi = lvi->nextSibling() )
			{
				if ( KopeteMetaContactLVI *kmc = dynamic_cast<KopeteMetaContactLVI *>( lvi ) )
					kmc->updateVisibility();
			}
		}
	}
}

void KopeteGroupViewItem::updateIcon()
{
	// TODO: clever caching
	if ( isOpen() )
	{
		if ( group()->useCustomIcon() && !group()->icon( Kopete::ContactListElement::Open ).isEmpty() )
			open = SmallIcon( group()->icon( Kopete::ContactListElement::Open ) );
		else
			open = SmallIcon( KOPETE_GROUP_DEFAULT_OPEN_ICON );

		d->image->setPixmap( open );
	}
	else
	{
		if ( group()->useCustomIcon() && !group()->icon( Kopete::ContactListElement::Closed ).isEmpty() )
			closed = SmallIcon( group()->icon( Kopete::ContactListElement::Closed ) );
		else
			closed = SmallIcon( KOPETE_GROUP_DEFAULT_CLOSED_ICON );

		d->image->setPixmap( closed );
	}
}

QString KopeteGroupViewItem::text( int column ) const
{
	if ( column == 0 )
		return d->name->text();
	else
		return KListViewItem::text( column );
}

void KopeteGroupViewItem::setText( int column, const QString &text )
{
	if ( column == 0 )
	{
		KopeteContactListView *lv = dynamic_cast<KopeteContactListView *>( listView() );
		if ( lv )
		{
			KopeteContactListView::UndoItem *u=new KopeteContactListView::UndoItem(KopeteContactListView::UndoItem::GroupRename, 0L, m_group);
			u->args << m_group->displayName();
			lv->insertUndoItem(u);
		}
		group()->setDisplayName( text );
	}
	else
		KListViewItem::setText( column, text );
}

#include "kopetegroupviewitem.moc"
// vim: set noet ts=4 sts=4 sw=4:

<|endoftext|>


<commit_before>// RUN: %clangxx -O0 -g %s -o %t && %run %t 2>&1 | FileCheck %s

// UNSUPPORTED: solaris

#include <stdio.h>

void print_something() {
  for (size_t i = 0; i < 10 * BUFSIZ; i++)
    printf("Hello world %zu\n", i);
}

// setbuffer/setlinebuf/setbuf uses setvbuf
// internally on NetBSD
#if defined(__NetBSD__)
void test_setbuf() {
  char buf[BUFSIZ];

  setbuf(stdout, NULL);

  print_something();

  setbuf(stdout, buf);

  print_something();
}

void test_setbuffer() {
  char buf[BUFSIZ];

  setbuffer(stdout, NULL, 0);

  print_something();

  setbuffer(stdout, buf, BUFSIZ);

  print_something();
}

void test_setlinebuf() {
  setlinebuf(stdout);

  print_something();
}
#endif

void test_setvbuf() {
  char buf[BUFSIZ];

  setvbuf(stdout, NULL, _IONBF, 0);

  print_something();

  setvbuf(stdout, buf, _IOLBF, BUFSIZ);

  print_something();

  setvbuf(stdout, buf, _IOFBF, BUFSIZ);

  print_something();
}

int main(void) {
  printf("setvbuf\n");

  test_setbuf();
  test_setbuffer();
  test_setlinebuf();
  test_setvbuf();

  // CHECK: setvbuf

  return 0;
}
<commit_msg>[Sanitizer] Unbreak non NetBSD builds.<commit_after>// RUN: %clangxx -O0 -g %s -o %t && %run %t 2>&1 | FileCheck %s

// UNSUPPORTED: solaris

#include <stdio.h>

void print_something() {
  for (size_t i = 0; i < 10 * BUFSIZ; i++)
    printf("Hello world %zu\n", i);
}

// setbuffer/setlinebuf/setbuf uses setvbuf
// internally on NetBSD
#if defined(__NetBSD__)
void test_setbuf() {
  char buf[BUFSIZ];

  setbuf(stdout, NULL);

  print_something();

  setbuf(stdout, buf);

  print_something();
}

void test_setbuffer() {
  char buf[BUFSIZ];

  setbuffer(stdout, NULL, 0);

  print_something();

  setbuffer(stdout, buf, BUFSIZ);

  print_something();
}

void test_setlinebuf() {
  setlinebuf(stdout);

  print_something();
}
#endif

void test_setvbuf() {
  char buf[BUFSIZ];

  setvbuf(stdout, NULL, _IONBF, 0);

  print_something();

  setvbuf(stdout, buf, _IOLBF, BUFSIZ);

  print_something();

  setvbuf(stdout, buf, _IOFBF, BUFSIZ);

  print_something();
}

int main(void) {
  printf("setvbuf\n");

#if defined(__NetBSD__)
  test_setbuf();
  test_setbuffer();
  test_setlinebuf();
#endif
  test_setvbuf();

  // CHECK: setvbuf

  return 0;
}
<|endoftext|>


<commit_before>#include "./object.hpp"

#include <iostream>

using namespace json;

regex ObjectVector::tokenRgx = regex ("^(?:\\[)?(\\d+)(:?\\])?(:?\\.)?");
regex ObjectMap::tokenRgx = regex    ("^(?:\\[')?(\\w+)(:?'\\])?(:?\\.)?");

void AbstractObject::txtIndent(string &txt, int indentLvl) {
  for (int i = 0; i < indentLvl; i++)
    txt.append(INDENT);
}

void ObjectFinalBool::replaceValue (string value) {
  if (value == "true")
    boolean = true;
  else
    boolean = false;
}

void ObjectFinalNumberFloat::replaceValue (string value) {
  number = stod (value);
}

void ObjectFinalNumberInt::replaceValue (string value) {
  number = atol (value.c_str());
}

void ObjectFinalString::replaceValue (string value) {
  text = value;
}

AbstractObject* ObjectVector::operator[] (unsigned index) {
  if (index >= array.size()) // changed to unsigned
    return nullptr;
  else
    return array [index];
}

AbstractObject* ObjectMap::operator[](string key) {
  if (hash.count (key))
    return hash[key];
  else
    return nullptr;
}

bool ObjectVector::insert (string key, AbstractObject* obj) {
  if (key == "") {
    array.push_back (obj);
    return true;
  } else {
    return false;
  }
}

bool ObjectMap::insert (string key, AbstractObject* obj) {
  if (key != "" && !hash.count (key)) {
    keys.push_back (key);
    hash.insert(pair <string, AbstractObject*> (key, obj));
    return true;
  } else {
    return false;
  }
}

bool ObjectMap::replace (string key, AbstractObject* obj) {
  if (!hash.count (key))
    return false;
  keys.erase(std::remove(keys.begin(), keys.end(), key), keys.end());
  hash.erase (key);
  return insert (key, obj);
}

bool ObjectMap::set (string key, AbstractObject* obj) {
  if (!hash.count (key))
    return insert (key, obj);
  else
    return replace (key, obj);
}

AbstractObject* ObjectVector::get (string path) {
  smatch matcher;
  if (path.size() == 0)
    return this;
  if (regex_search (path, matcher, tokenRgx)) {
    AbstractObject* son = operator[](stoi (matcher[1]));
    path = path.substr(matcher[0].length(), path.size());
    if (son != nullptr) {
      return son->get (path);
    }
  }
  return nullptr;
}

AbstractObject* ObjectMap::get (string path) {
  smatch matcher;
  if (path.empty() || path == ".")
    return this;
  if (regex_search (path, matcher, tokenRgx)) {
    AbstractObject* son = operator[](matcher[1]);
    path = path.substr(matcher[0].length(), path.size());
    if (son != nullptr)
      return son->get (path);
  }
  return nullptr;
}

AbstractObject* ObjectFinal::get (string path) {
  if (path.size () == 0)
    return this;
  else
    return nullptr;
}

bool ObjectMap::remove (string key) {
  AbstractObject* aux = operator[](key);
  if (aux == nullptr)
    return true;
  keys.erase(std::remove(keys.begin(), keys.end(), key), keys.end());
  hash.erase (key);
  delete aux;
  return true;
}

bool ObjectMap::erase (string key) {
  if (!hash.count (key))
    return false;
  else
    return remove (key);
}

bool ObjectMap::add (string path,  AbstractObject* obj) {
  smatch matcher;
  if (regex_search (path, matcher, tokenRgx)) {
    AbstractObject* son = operator[](matcher[1]);
    string newPath = path.substr(matcher[0].length(), path.size());
    if (son != nullptr) {
      if (!newPath.empty() || son->getType() == VECTOR)
        return son->add (newPath, obj);
      else
        return false;
    } else {
      if (!newPath.empty()) {
        son = new ObjectMap();
        insert (matcher[1], son);
        return son->add (newPath, obj);
      } else {
        return insert (path, obj);
      }
    }
  }
  return false;
}

bool ObjectVector::add (string path,  AbstractObject* obj) {
  smatch matcher;
  AbstractObject* son;
  if (regex_search (path, matcher, tokenRgx)) {
    son = operator[](stoi (matcher[1]));
    string newPath = path.substr(matcher[0].length(), path.size());
    if (son != nullptr)
      return son->add (newPath, obj);
    else
      return false;
  } else if (path.empty()) {
    return insert ("", obj);
  } else {
    son = new ObjectMap();
    insert ("", son);
    return son->add (path, obj);
  }
  return false;
}

bool ObjectFinal::add (string path,  AbstractObject* obj) {
  return false;
}

void ObjectVector::toTxt (string& txt, int indentLvl) {
  txt.append("[");
  indentLvl++;
  AbstractObject* obj = this;
  for (int i = 0; i < size(); i++) {
    if (obj->getType() != NUMBER_INT) {
      txt.append(END_LINE);
      txtIndent (txt, indentLvl);
    } else {
      txt.append(" ");
    }
    obj = operator[](i);
    obj->toTxt(txt, indentLvl);
    txt.append(COMMA);
  }
  if (size() > 0)
    txt.pop_back();
  indentLvl--;
  txt.append(END_LINE);
  txtIndent (txt, indentLvl);
  txt.append("]");
}

void ObjectMap::toTxt (string& txt, int indentLvl) {
  txt.append("{");
  indentLvl++;
  for (int i = 0; i < getKeys().size(); i++) {
    txt.append(END_LINE);
    txtIndent (txt, indentLvl);
    txt.append(QUOTE).append(getKeys()[i]).append(QUOTE).append(POINTS);
    operator[](getKeys()[i])->toTxt(txt, indentLvl);
    txt.append(COMMA);
  }
  if (getKeys().size() > 0)
    txt.pop_back();
  indentLvl--;
  txt.append(END_LINE);
  txtIndent (txt, indentLvl);
  txt.append("}");
}

void ObjectFinalBool::toTxt (string& txt, int indentLvl) {
  if (getContent())
    txt.append("true");
  else
    txt.append("false");
}

void ObjectFinalNumberFloat::toTxt (string& txt, int indentLvl) {
  txt.append(to_string(getContent()));
}

void ObjectFinalNumberInt::toTxt (string& txt, int indentLvl) {
  txt.append(to_string(getContent()));
}

void ObjectFinalString::toTxt (string& txt, int indentLvl) {
  txt.append(QUOTE).append(getContent()).append(QUOTE);
}

ObjectVector::~ObjectVector () {
  array.clear();
}

ObjectMap::~ObjectMap () {
  hash.clear();
}

ObjectFinalBool::~ObjectFinalBool () {

}

ObjectFinalNumberFloat::~ObjectFinalNumberFloat () {

}

ObjectFinalNumberInt::~ObjectFinalNumberInt () {

}

ObjectFinalString::~ObjectFinalString () {

}

AbstractObject::~AbstractObject() {}

ObjectContainer::~ObjectContainer() {}

ObjectFinal::~ObjectFinal() {}

<commit_msg>Memory leaks solved<commit_after>#include "./object.hpp"

#include <iostream>

using namespace json;

regex ObjectVector::tokenRgx = regex ("^(?:\\[)?(\\d+)(:?\\])?(:?\\.)?");
regex ObjectMap::tokenRgx = regex    ("^(?:\\[')?(\\w+)(:?'\\])?(:?\\.)?");

void AbstractObject::txtIndent(string &txt, int indentLvl) {
  for (int i = 0; i < indentLvl; i++)
    txt.append(INDENT);
}

void ObjectFinalBool::replaceValue (string value) {
  if (value == "true")
    boolean = true;
  else
    boolean = false;
}

void ObjectFinalNumberFloat::replaceValue (string value) {
  number = stod (value);
}

void ObjectFinalNumberInt::replaceValue (string value) {
  number = atol (value.c_str());
}

void ObjectFinalString::replaceValue (string value) {
  text = value;
}

AbstractObject* ObjectVector::operator[] (unsigned index) {
  if (index >= array.size()) // changed to unsigned
    return nullptr;
  else
    return array [index];
}

AbstractObject* ObjectMap::operator[](string key) {
  if (hash.count (key))
    return hash[key];
  else
    return nullptr;
}

bool ObjectVector::insert (string key, AbstractObject* obj) {
  if (key == "") {
    array.push_back (obj);
    return true;
  } else {
    return false;
  }
}

bool ObjectMap::insert (string key, AbstractObject* obj) {
  if (key != "" && !hash.count (key)) {
    keys.push_back (key);
    hash.insert(pair <string, AbstractObject*> (key, obj));
    return true;
  } else {
    return false;
  }
}

bool ObjectMap::replace (string key, AbstractObject* obj) {
  if (!hash.count (key))
    return false;
  keys.erase(std::remove(keys.begin(), keys.end(), key), keys.end());
  hash.erase (key);
  return insert (key, obj);
}

bool ObjectMap::set (string key, AbstractObject* obj) {
  if (!hash.count (key))
    return insert (key, obj);
  else
    return replace (key, obj);
}

AbstractObject* ObjectVector::get (string path) {
  smatch matcher;
  if (path.size() == 0)
    return this;
  if (regex_search (path, matcher, tokenRgx)) {
    AbstractObject* son = operator[](stoi (matcher[1]));
    path = path.substr(matcher[0].length(), path.size());
    if (son != nullptr) {
      return son->get (path);
    }
  }
  return nullptr;
}

AbstractObject* ObjectMap::get (string path) {
  smatch matcher;
  if (path.empty() || path == ".")
    return this;
  if (regex_search (path, matcher, tokenRgx)) {
    AbstractObject* son = operator[](matcher[1]);
    path = path.substr(matcher[0].length(), path.size());
    if (son != nullptr)
      return son->get (path);
  }
  return nullptr;
}

AbstractObject* ObjectFinal::get (string path) {
  if (path.size () == 0)
    return this;
  else
    return nullptr;
}

bool ObjectMap::remove (string key) {
  AbstractObject* aux = operator[](key);
  if (aux == nullptr)
    return true;
  keys.erase(std::remove(keys.begin(), keys.end(), key), keys.end());
  hash.erase (key);
  delete aux;
  return true;
}

bool ObjectMap::erase (string key) {
  if (!hash.count (key))
    return false;
  else
    return remove (key);
}

bool ObjectMap::add (string path,  AbstractObject* obj) {
  smatch matcher;
  if (regex_search (path, matcher, tokenRgx)) {
    AbstractObject* son = operator[](matcher[1]);
    string newPath = path.substr(matcher[0].length(), path.size());
    if (son != nullptr) {
      if (!newPath.empty() || son->getType() == VECTOR)
        return son->add (newPath, obj);
      else
        return false;
    } else {
      if (!newPath.empty()) {
        son = new ObjectMap();
        insert (matcher[1], son);
        if(son->add (newPath, obj))
          return true;
        delete son;
        return false;
      } else {
        return insert (path, obj);
      }
    }
  }
  return false;
}

bool ObjectVector::add (string path,  AbstractObject* obj) {
  smatch matcher;
  AbstractObject* son;
  if (regex_search (path, matcher, tokenRgx)) {
    son = operator[](stoi (matcher[1]));
    string newPath = path.substr(matcher[0].length(), path.size());
    if (son != nullptr)
      return son->add (newPath, obj);
    else
      return false;
  } else if (path.empty()) {
    return insert ("", obj);
  } else {
    son = new ObjectMap();
    insert ("", son);
    return son->add (path, obj);
  }
  return false;
}

bool ObjectFinal::add (string path,  AbstractObject* obj) {
  return false;
}

void ObjectVector::toTxt (string& txt, int indentLvl) {
  txt.append("[");
  indentLvl++;
  AbstractObject* obj = this;
  for (int i = 0; i < size(); i++) {
    if (obj->getType() != NUMBER_INT) {
      txt.append(END_LINE);
      txtIndent (txt, indentLvl);
    } else {
      txt.append(" ");
    }
    obj = operator[](i);
    obj->toTxt(txt, indentLvl);
    txt.append(COMMA);
  }
  if (size() > 0)
    txt.pop_back();
  indentLvl--;
  txt.append(END_LINE);
  txtIndent (txt, indentLvl);
  txt.append("]");
}

void ObjectMap::toTxt (string& txt, int indentLvl) {
  txt.append("{");
  indentLvl++;
  for (int i = 0; i < getKeys().size(); i++) {
    txt.append(END_LINE);
    txtIndent (txt, indentLvl);
    txt.append(QUOTE).append(getKeys()[i]).append(QUOTE).append(POINTS);
    operator[](getKeys()[i])->toTxt(txt, indentLvl);
    txt.append(COMMA);
  }
  if (getKeys().size() > 0)
    txt.pop_back();
  indentLvl--;
  txt.append(END_LINE);
  txtIndent (txt, indentLvl);
  txt.append("}");
}

void ObjectFinalBool::toTxt (string& txt, int indentLvl) {
  if (getContent())
    txt.append("true");
  else
    txt.append("false");
}

void ObjectFinalNumberFloat::toTxt (string& txt, int indentLvl) {
  txt.append(to_string(getContent()));
}

void ObjectFinalNumberInt::toTxt (string& txt, int indentLvl) {
  txt.append(to_string(getContent()));
}

void ObjectFinalString::toTxt (string& txt, int indentLvl) {
  txt.append(QUOTE).append(getContent()).append(QUOTE);
}

ObjectVector::~ObjectVector () {
  array.clear();
}

ObjectMap::~ObjectMap () {
  hash.clear();
}

ObjectFinalBool::~ObjectFinalBool () {

}

ObjectFinalNumberFloat::~ObjectFinalNumberFloat () {

}

ObjectFinalNumberInt::~ObjectFinalNumberInt () {

}

ObjectFinalString::~ObjectFinalString () {

}

AbstractObject::~AbstractObject() {}

ObjectContainer::~ObjectContainer() {}

ObjectFinal::~ObjectFinal() {}

<|endoftext|>


<commit_before>/*=========================================================================
 *
 *  Copyright RTK Consortium
 *
 *  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.
 *
 *=========================================================================*/
#ifndef __rtkWarpFourDToProjectionStackImageFilter_hxx
#define __rtkWarpFourDToProjectionStackImageFilter_hxx

#include "rtkWarpFourDToProjectionStackImageFilter.h"

namespace rtk
{

template< typename VolumeSeriesType, typename ProjectionStackType>
WarpFourDToProjectionStackImageFilter< VolumeSeriesType, ProjectionStackType>::WarpFourDToProjectionStackImageFilter()
{
  this->SetNumberOfRequiredInputs(3);

#ifdef RTK_USE_CUDA
  this->m_ForwardProjectionFilter = rtk::CudaWarpForwardProjectionImageFilter::New();
#else
  this->m_ForwardProjectionFilter = rtk::JosephForwardProjectionImageFilter<ProjectionStackType, ProjectionStackType>::New();
  itkWarningMacro("The warp Forward project image filter exists only in CUDA. Ignoring the displacement vector field and using CPU Joseph forward projection")
#endif
}

template< typename VolumeSeriesType, typename ProjectionStackType>
void
WarpFourDToProjectionStackImageFilter< VolumeSeriesType, ProjectionStackType>::SetDisplacementField(const DVFSequenceImageType* DisplacementField)
{
  this->SetNthInput(2, const_cast<DVFSequenceImageType*>(DisplacementField));
}

template< typename VolumeSeriesType, typename ProjectionStackType>
typename WarpFourDToProjectionStackImageFilter< VolumeSeriesType, ProjectionStackType>::DVFSequenceImageType::ConstPointer
WarpFourDToProjectionStackImageFilter< VolumeSeriesType, ProjectionStackType>::GetDisplacementField()
{
  return static_cast< const DVFSequenceImageType * >
          ( this->itk::ProcessObject::GetInput(2) );
}

template< typename VolumeSeriesType, typename ProjectionStackType>
void
WarpFourDToProjectionStackImageFilter< VolumeSeriesType, ProjectionStackType>
::SetSignal(const std::vector<double> signal)
{
  this->m_Signal = signal;
  this->Modified();
}

template< typename VolumeSeriesType, typename ProjectionStackType>
void
WarpFourDToProjectionStackImageFilter< VolumeSeriesType, ProjectionStackType>
::GenerateOutputInformation()
{
  m_DVFInterpolatorFilter = DVFInterpolatorType::New();
#ifdef RTK_USE_CUDA
  if (m_UseCudaCyclicDeformation)
    m_DVFInterpolatorFilter = rtk::CudaCyclicDeformationImageFilter::New();
#endif
  m_DVFInterpolatorFilter->SetSignalVector(m_Signal);
  m_DVFInterpolatorFilter->SetInput(this->GetDisplacementField());
  m_DVFInterpolatorFilter->SetFrame(0);

#ifdef RTK_USE_CUDA
  dynamic_cast<rtk::CudaWarpForwardProjectionImageFilter* >
      (this->m_ForwardProjectionFilter.GetPointer())->SetDisplacementField(m_DVFInterpolatorFilter->GetOutput());
#endif

  Superclass::GenerateOutputInformation();
}

template< typename VolumeSeriesType, typename ProjectionStackType>
void
WarpFourDToProjectionStackImageFilter< VolumeSeriesType, ProjectionStackType>
::GenerateInputRequestedRegion()
{
  // Input 0 is the stack of projections we update
  typename ProjectionStackType::Pointer  inputPtr0 = const_cast< ProjectionStackType * >( this->GetInput(0) );
  if ( !inputPtr0 )
    {
    return;
    }
  inputPtr0->SetRequestedRegion( this->GetOutput()->GetRequestedRegion() );

  // Input 1 is the volume series
  typename VolumeSeriesType::Pointer inputPtr1 = static_cast< VolumeSeriesType * >
            ( this->itk::ProcessObject::GetInput(1) );
  inputPtr1->SetRequestedRegionToLargestPossibleRegion();

  // Input 2 is the sequence of DVFs
  typename DVFSequenceImageType::Pointer inputPtr2 = static_cast< DVFSequenceImageType * >
            ( this->itk::ProcessObject::GetInput(2) );
  inputPtr2->SetRequestedRegionToLargestPossibleRegion();
}

template< typename VolumeSeriesType, typename ProjectionStackType>
void
WarpFourDToProjectionStackImageFilter< VolumeSeriesType, ProjectionStackType>
::GenerateData()
{
  int ProjectionStackDimension = ProjectionStackType::ImageDimension;

  int NumberProjs = this->GetInputProjectionStack()->GetRequestedRegion().GetSize(ProjectionStackDimension-1);
  int FirstProj = this->GetInputProjectionStack()->GetRequestedRegion().GetIndex(ProjectionStackDimension-1);

  bool firstProjectionProcessed = false;

  // Process the projections in order
  for (unsigned int proj = FirstProj; proj < FirstProj+NumberProjs; proj++)
    {
    // After the first update, we need to use the output as input.
    if(firstProjectionProcessed)
      {
      typename ProjectionStackType::Pointer pimg = this->m_PasteFilter->GetOutput();
      pimg->DisconnectPipeline();
      this->m_PasteFilter->SetDestinationImage( pimg );
      }

    // Update the paste region
    this->m_PasteRegion.SetIndex(ProjectionStackDimension-1, proj);

    // Set the projection stack source
    this->m_ConstantProjectionStackSource->SetIndex(this->m_PasteRegion.GetIndex());

    // Set the Paste Filter. Since its output has been disconnected
    // we need to set its RequestedRegion manually (it will never
    // be updated by a downstream filter)
    this->m_PasteFilter->SetSourceRegion(this->m_PasteRegion);
    this->m_PasteFilter->SetDestinationIndex(this->m_PasteRegion.GetIndex());
    this->m_PasteFilter->GetOutput()->SetRequestedRegion(this->m_PasteFilter->GetDestinationImage()->GetLargestPossibleRegion());

    // Set the Interpolation filter
    this->m_InterpolationFilter->SetProjectionNumber(proj);

    // Set the DVF interpolator
    m_DVFInterpolatorFilter->SetFrame(proj);

    // Update the last filter
    this->m_PasteFilter->Update();

    // Update condition
    firstProjectionProcessed = true;
    }

  // Graft its output
  this->GraftOutput( this->m_PasteFilter->GetOutput() );

  // Release the data in internal filters
  this->m_DVFInterpolatorFilter->GetOutput()->ReleaseData();
}

}// end namespace

#endif
<commit_msg>Fix uninitialized memory conditional<commit_after>/*=========================================================================
 *
 *  Copyright RTK Consortium
 *
 *  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.
 *
 *=========================================================================*/
#ifndef __rtkWarpFourDToProjectionStackImageFilter_hxx
#define __rtkWarpFourDToProjectionStackImageFilter_hxx

#include "rtkWarpFourDToProjectionStackImageFilter.h"

namespace rtk
{

template< typename VolumeSeriesType, typename ProjectionStackType>
WarpFourDToProjectionStackImageFilter< VolumeSeriesType, ProjectionStackType>::WarpFourDToProjectionStackImageFilter():
    m_UseCudaCyclicDeformation(false)
{
  this->SetNumberOfRequiredInputs(3);

#ifdef RTK_USE_CUDA
  this->m_ForwardProjectionFilter = rtk::CudaWarpForwardProjectionImageFilter::New();
#else
  this->m_ForwardProjectionFilter = rtk::JosephForwardProjectionImageFilter<ProjectionStackType, ProjectionStackType>::New();
  itkWarningMacro("The warp Forward project image filter exists only in CUDA. Ignoring the displacement vector field and using CPU Joseph forward projection")
#endif
}

template< typename VolumeSeriesType, typename ProjectionStackType>
void
WarpFourDToProjectionStackImageFilter< VolumeSeriesType, ProjectionStackType>::SetDisplacementField(const DVFSequenceImageType* DisplacementField)
{
  this->SetNthInput(2, const_cast<DVFSequenceImageType*>(DisplacementField));
}

template< typename VolumeSeriesType, typename ProjectionStackType>
typename WarpFourDToProjectionStackImageFilter< VolumeSeriesType, ProjectionStackType>::DVFSequenceImageType::ConstPointer
WarpFourDToProjectionStackImageFilter< VolumeSeriesType, ProjectionStackType>::GetDisplacementField()
{
  return static_cast< const DVFSequenceImageType * >
          ( this->itk::ProcessObject::GetInput(2) );
}

template< typename VolumeSeriesType, typename ProjectionStackType>
void
WarpFourDToProjectionStackImageFilter< VolumeSeriesType, ProjectionStackType>
::SetSignal(const std::vector<double> signal)
{
  this->m_Signal = signal;
  this->Modified();
}

template< typename VolumeSeriesType, typename ProjectionStackType>
void
WarpFourDToProjectionStackImageFilter< VolumeSeriesType, ProjectionStackType>
::GenerateOutputInformation()
{
  m_DVFInterpolatorFilter = DVFInterpolatorType::New();
#ifdef RTK_USE_CUDA
  if (m_UseCudaCyclicDeformation)
    m_DVFInterpolatorFilter = rtk::CudaCyclicDeformationImageFilter::New();
#endif
  m_DVFInterpolatorFilter->SetSignalVector(m_Signal);
  m_DVFInterpolatorFilter->SetInput(this->GetDisplacementField());
  m_DVFInterpolatorFilter->SetFrame(0);

#ifdef RTK_USE_CUDA
  dynamic_cast<rtk::CudaWarpForwardProjectionImageFilter* >
      (this->m_ForwardProjectionFilter.GetPointer())->SetDisplacementField(m_DVFInterpolatorFilter->GetOutput());
#endif

  Superclass::GenerateOutputInformation();
}

template< typename VolumeSeriesType, typename ProjectionStackType>
void
WarpFourDToProjectionStackImageFilter< VolumeSeriesType, ProjectionStackType>
::GenerateInputRequestedRegion()
{
  // Input 0 is the stack of projections we update
  typename ProjectionStackType::Pointer  inputPtr0 = const_cast< ProjectionStackType * >( this->GetInput(0) );
  if ( !inputPtr0 )
    {
    return;
    }
  inputPtr0->SetRequestedRegion( this->GetOutput()->GetRequestedRegion() );

  // Input 1 is the volume series
  typename VolumeSeriesType::Pointer inputPtr1 = static_cast< VolumeSeriesType * >
            ( this->itk::ProcessObject::GetInput(1) );
  inputPtr1->SetRequestedRegionToLargestPossibleRegion();

  // Input 2 is the sequence of DVFs
  typename DVFSequenceImageType::Pointer inputPtr2 = static_cast< DVFSequenceImageType * >
            ( this->itk::ProcessObject::GetInput(2) );
  inputPtr2->SetRequestedRegionToLargestPossibleRegion();
}

template< typename VolumeSeriesType, typename ProjectionStackType>
void
WarpFourDToProjectionStackImageFilter< VolumeSeriesType, ProjectionStackType>
::GenerateData()
{
  int ProjectionStackDimension = ProjectionStackType::ImageDimension;

  int NumberProjs = this->GetInputProjectionStack()->GetRequestedRegion().GetSize(ProjectionStackDimension-1);
  int FirstProj = this->GetInputProjectionStack()->GetRequestedRegion().GetIndex(ProjectionStackDimension-1);

  bool firstProjectionProcessed = false;

  // Process the projections in order
  for (unsigned int proj = FirstProj; proj < FirstProj+NumberProjs; proj++)
    {
    // After the first update, we need to use the output as input.
    if(firstProjectionProcessed)
      {
      typename ProjectionStackType::Pointer pimg = this->m_PasteFilter->GetOutput();
      pimg->DisconnectPipeline();
      this->m_PasteFilter->SetDestinationImage( pimg );
      }

    // Update the paste region
    this->m_PasteRegion.SetIndex(ProjectionStackDimension-1, proj);

    // Set the projection stack source
    this->m_ConstantProjectionStackSource->SetIndex(this->m_PasteRegion.GetIndex());

    // Set the Paste Filter. Since its output has been disconnected
    // we need to set its RequestedRegion manually (it will never
    // be updated by a downstream filter)
    this->m_PasteFilter->SetSourceRegion(this->m_PasteRegion);
    this->m_PasteFilter->SetDestinationIndex(this->m_PasteRegion.GetIndex());
    this->m_PasteFilter->GetOutput()->SetRequestedRegion(this->m_PasteFilter->GetDestinationImage()->GetLargestPossibleRegion());

    // Set the Interpolation filter
    this->m_InterpolationFilter->SetProjectionNumber(proj);

    // Set the DVF interpolator
    m_DVFInterpolatorFilter->SetFrame(proj);

    // Update the last filter
    this->m_PasteFilter->Update();

    // Update condition
    firstProjectionProcessed = true;
    }

  // Graft its output
  this->GraftOutput( this->m_PasteFilter->GetOutput() );

  // Release the data in internal filters
  this->m_DVFInterpolatorFilter->GetOutput()->ReleaseData();
}

}// end namespace

#endif
<|endoftext|>