<commit_before>#include "terminalscreen.hpp"
#include "logging.h"

using namespace bb::cascades;

TerminalScreen::TerminalScreen( term_t handle, int argc, char *argv[], AbstractPane *pane) : terminal(handle)
{
    int ret = 0;
    QObject *pObj;

    term_get_grid_size( handle, &width, &height );
    slog2f(buffer_handle, 0, SLOG2_INFO, "TerminalScreen start %dx%d", width, height);
    mStringListModel = new QStringListDataModel;
    term_set_user_data( terminal, this );
    term_register_update( terminal, term_update );
    pObj = pane->findChild<QObject *>("terminalLines");
    mStringList = (ListView *) pObj;
    mStringList->setDataModel( mStringListModel );

    notifier = new QSocketNotifier( term_get_file_descriptor(terminal), QSocketNotifier::Read );
    QObject::connect(notifier, SIGNAL(activated(int)), this, SLOT(terminal_data()));
}

TerminalScreen::~TerminalScreen()
{
    delete notifier;
}

void TerminalScreen::term_update( term_t term, int x, int y, int width, int height )
{
    TerminalScreen *ts = (TerminalScreen *)term_get_user_data( term );
    slog2c(buffer_handle, 0, SLOG2_INFO, "terminal update");
    for( int i = 0; i < height; i ++ ) {
        *ts->mStringListModel << QString(term_get_line(ts->terminal, i));
    }
}

void TerminalScreen::terminal_data()
{
    if( !term_process_child( terminal ) ) {
        exit(0);
    }
}
<commit_msg>Update list entries on term_update instead of appending more<commit_after>#include "terminalscreen.hpp"
#include "logging.h"

using namespace bb::cascades;

TerminalScreen::TerminalScreen( term_t handle, int argc, char *argv[], AbstractPane *pane) : terminal(handle)
{
    int ret = 0;
    QObject *pObj;

    term_get_grid_size( handle, &width, &height );
    slog2f(buffer_handle, 0, SLOG2_INFO, "TerminalScreen start %dx%d", width, height);
    mStringListModel = new QStringListDataModel;
    term_set_user_data( terminal, this );
    term_register_update( terminal, term_update );
    pObj = pane->findChild<QObject *>("terminalLines");
    mStringList = (ListView *) pObj;
    mStringList->setDataModel( mStringListModel );

    for( int i = 0; i < height; i ++ ) {
        *mStringListModel << QString(term_get_line(terminal, i));
    }

    notifier = new QSocketNotifier( term_get_file_descriptor(terminal), QSocketNotifier::Read );
    QObject::connect(notifier, SIGNAL(activated(int)), this, SLOT(terminal_data()));
}

TerminalScreen::~TerminalScreen()
{
    delete notifier;
}

void TerminalScreen::term_update( term_t term, int x, int y, int width, int height )
{
    TerminalScreen *ts = (TerminalScreen *)term_get_user_data( term );
    slog2c(buffer_handle, 0, SLOG2_INFO, "terminal update");
    for( int i = 0; i < height; i ++ ) {
        ts->mStringListModel->replace(i, QString(term_get_line(ts->terminal, i)));
    }
}

void TerminalScreen::terminal_data()
{
    if( !term_process_child( terminal ) ) {
        exit(0);
    }
}
<|endoftext|>


<commit_before>#include <product.hpp>

#include "helpers.hpp"

#include <vector>
#include <string>
#include <iterator>

#include "catch.hpp"

using iter::product;
using Vec = const std::vector<int>;

TEST_CASE("product: basic test, two vectors", "[product]") {
    using ResType = std::vector<std::tuple<int, int>>;
    using TP = std::tuple<int, int>;

    Vec n1 = {0, 1};
    Vec n2 = {0, 1, 2};

    auto p = product(n1, n2);
    ResType v(std::begin(p), std::end(p));
    ResType vc = {TP{0,0}, TP{0,1}, TP{0,2}, TP{1,0}, TP{1,1}, TP{1,2}};

    REQUIRE( v == vc );
}

<commit_msg>tests product with empty sequences<commit_after>#include <product.hpp>

#include "helpers.hpp"

#include <vector>
#include <string>
#include <iterator>

#include "catch.hpp"

using iter::product;
using Vec = const std::vector<int>;

TEST_CASE("product: basic test, two vectors", "[product]") {
    using ResType = std::vector<std::tuple<int, int>>;
    using TP = std::tuple<int, int>;

    Vec n1 = {0, 1};
    Vec n2 = {0, 1, 2};

    auto p = product(n1, n2);
    ResType v(std::begin(p), std::end(p));
    ResType vc = {TP{0,0}, TP{0,1}, TP{0,2}, TP{1,0}, TP{1,1}, TP{1,2}};

    REQUIRE( v == vc );
}

TEST_CASE("product: empty when any iterable is empty", "[product]") {
    Vec n1 = {0, 1};
    Vec n2 = {0, 1, 2};
    Vec emp = {};

    SECTION("first iterable is empty") {
        auto p = product(emp, n1, n2);
        REQUIRE( std::begin(p) == std::end(p) );
    }

    SECTION("middle iterable is empty") {
        auto p = product(n1, emp, n2);
        REQUIRE( std::begin(p) == std::end(p) );
    }

    SECTION("last iterable is empty") {
        auto p = product(n1, n2, emp);
        REQUIRE( std::begin(p) == std::end(p) );
    }
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: targethelper.cxx,v $
 *
 *  $Revision: 1.5 $
 *
 *  last change: $Author: obo $ $Date: 2006-09-16 14:05:40 $
 *
 *  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
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_framework.hxx"

//_______________________________________________
// own includes

#ifndef __FRAMEWORK_LOADENV_TARGETHELPER_HXX_
#include <loadenv/targethelper.hxx>
#endif

//_______________________________________________
// namespace

namespace framework{

//_______________________________________________
// declarations

/*-----------------------------------------------
    05.08.2003 09:12
-----------------------------------------------*/
TargetHelper::ESpecialTarget TargetHelper::classifyTarget(const ::rtl::OUString& sTarget)
{
    if (
        (!sTarget.getLength()              ) ||
        (sTarget.equals(SPECIALTARGET_SELF))
       )
        return E_SELF;

    if (sTarget.equals(SPECIALTARGET_PARENT))
        return E_PARENT;

    if (sTarget.equals(SPECIALTARGET_TOP))
        return E_TOP;

    if (sTarget.equals(SPECIALTARGET_BLANK))
        return E_BLANK;

    if (sTarget.equals(SPECIALTARGET_DEFAULT))
        return E_DEFAULT;

    if (sTarget.equals(SPECIALTARGET_BEAMER))
        return E_BEAMER;

    if (sTarget.equals(SPECIALTARGET_MENUBAR))
        return E_MENUBAR;

    if (sTarget.equals(SPECIALTARGET_HELPAGENT))
        return E_HELPAGENT;

    if (sTarget.equals(SPECIALTARGET_HELPTASK))
        return E_HELPTASK;

    return E_NOT_SPECIAL;
}

/*-----------------------------------------------
    05.08.2003 09:08
-----------------------------------------------*/
sal_Bool TargetHelper::matchSpecialTarget(const ::rtl::OUString& sCheckTarget  ,
                                                ESpecialTarget   eSpecialTarget)
{
    switch(eSpecialTarget)
    {
        case E_SELF :
            return (
                    (!sCheckTarget.getLength()              ) ||
                    (sCheckTarget.equals(SPECIALTARGET_SELF))
                   );

        case E_PARENT :
            return (sCheckTarget.equals(SPECIALTARGET_PARENT));

        case E_TOP :
            return (sCheckTarget.equals(SPECIALTARGET_TOP));

        case E_BLANK :
            return (sCheckTarget.equals(SPECIALTARGET_BLANK));

        case E_DEFAULT :
            return (sCheckTarget.equals(SPECIALTARGET_DEFAULT));

        case E_BEAMER :
            return (sCheckTarget.equals(SPECIALTARGET_BEAMER));

        case E_MENUBAR :
            return (sCheckTarget.equals(SPECIALTARGET_MENUBAR));

        case E_HELPAGENT :
            return (sCheckTarget.equals(SPECIALTARGET_HELPAGENT));

        case E_HELPTASK :
            return (sCheckTarget.equals(SPECIALTARGET_HELPTASK));
        default:
            return sal_False;
    }

    return sal_False;
}

/*-----------------------------------------------
    05.08.2003 09:17
-----------------------------------------------*/
sal_Bool TargetHelper::isValidNameForFrame(const ::rtl::OUString& sName)
{
    // some special targets are realy special ones :-)
    // E.g. the are realy used to locate one frame inside the frame tree.
    if (
        (!sName.getLength()                                 ) ||
        (TargetHelper::matchSpecialTarget(sName, E_HELPTASK)) ||
        (TargetHelper::matchSpecialTarget(sName, E_BEAMER)  )
       )
        return sal_True;

    // all other names must be checked more general
    // special targets starts with a "_".
    return (sName.indexOf('_') != 0);
}

} // namespace framework
<commit_msg>INTEGRATION: CWS changefileheader (1.5.262); FILE MERGED 2008/03/28 15:35:23 rt 1.5.262.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: targethelper.cxx,v $
 * $Revision: 1.6 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org 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 version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_framework.hxx"

//_______________________________________________
// own includes

#ifndef __FRAMEWORK_LOADENV_TARGETHELPER_HXX_
#include <loadenv/targethelper.hxx>
#endif

//_______________________________________________
// namespace

namespace framework{

//_______________________________________________
// declarations

/*-----------------------------------------------
    05.08.2003 09:12
-----------------------------------------------*/
TargetHelper::ESpecialTarget TargetHelper::classifyTarget(const ::rtl::OUString& sTarget)
{
    if (
        (!sTarget.getLength()              ) ||
        (sTarget.equals(SPECIALTARGET_SELF))
       )
        return E_SELF;

    if (sTarget.equals(SPECIALTARGET_PARENT))
        return E_PARENT;

    if (sTarget.equals(SPECIALTARGET_TOP))
        return E_TOP;

    if (sTarget.equals(SPECIALTARGET_BLANK))
        return E_BLANK;

    if (sTarget.equals(SPECIALTARGET_DEFAULT))
        return E_DEFAULT;

    if (sTarget.equals(SPECIALTARGET_BEAMER))
        return E_BEAMER;

    if (sTarget.equals(SPECIALTARGET_MENUBAR))
        return E_MENUBAR;

    if (sTarget.equals(SPECIALTARGET_HELPAGENT))
        return E_HELPAGENT;

    if (sTarget.equals(SPECIALTARGET_HELPTASK))
        return E_HELPTASK;

    return E_NOT_SPECIAL;
}

/*-----------------------------------------------
    05.08.2003 09:08
-----------------------------------------------*/
sal_Bool TargetHelper::matchSpecialTarget(const ::rtl::OUString& sCheckTarget  ,
                                                ESpecialTarget   eSpecialTarget)
{
    switch(eSpecialTarget)
    {
        case E_SELF :
            return (
                    (!sCheckTarget.getLength()              ) ||
                    (sCheckTarget.equals(SPECIALTARGET_SELF))
                   );

        case E_PARENT :
            return (sCheckTarget.equals(SPECIALTARGET_PARENT));

        case E_TOP :
            return (sCheckTarget.equals(SPECIALTARGET_TOP));

        case E_BLANK :
            return (sCheckTarget.equals(SPECIALTARGET_BLANK));

        case E_DEFAULT :
            return (sCheckTarget.equals(SPECIALTARGET_DEFAULT));

        case E_BEAMER :
            return (sCheckTarget.equals(SPECIALTARGET_BEAMER));

        case E_MENUBAR :
            return (sCheckTarget.equals(SPECIALTARGET_MENUBAR));

        case E_HELPAGENT :
            return (sCheckTarget.equals(SPECIALTARGET_HELPAGENT));

        case E_HELPTASK :
            return (sCheckTarget.equals(SPECIALTARGET_HELPTASK));
        default:
            return sal_False;
    }

    return sal_False;
}

/*-----------------------------------------------
    05.08.2003 09:17
-----------------------------------------------*/
sal_Bool TargetHelper::isValidNameForFrame(const ::rtl::OUString& sName)
{
    // some special targets are realy special ones :-)
    // E.g. the are realy used to locate one frame inside the frame tree.
    if (
        (!sName.getLength()                                 ) ||
        (TargetHelper::matchSpecialTarget(sName, E_HELPTASK)) ||
        (TargetHelper::matchSpecialTarget(sName, E_BEAMER)  )
       )
        return sal_True;

    // all other names must be checked more general
    // special targets starts with a "_".
    return (sName.indexOf('_') != 0);
}

} // namespace framework
<|endoftext|>


<commit_before>#include <map>
#include <array>
#include <cmath>

#include "acmacs-base/stream.hh"
#include "acmacs-base/enumerate.hh"
#include "acmacs-base/string.hh"
#include "acmacs-map-draw/mod-connection-lines.hh"
#include "acmacs-map-draw/select.hh"

static std::pair<acmacs::chart::Indexes, acmacs::chart::Indexes> select_antigens_sera_for_connection_lines(ChartDraw& aChartDraw, const rjson::value& select_antigens, const rjson::value& select_sera);

// ----------------------------------------------------------------------

void ModConnectionLines::apply(ChartDraw& aChartDraw, const rjson::value& /*aModData*/)
{
    const auto [antigen_indexes, serum_indexes] = select_antigens_sera_for_connection_lines(aChartDraw, args()["antigens"], args()["sera"]);

    const Color line_color{rjson::get_or(args(), "color", "black")};
    const double line_width{rjson::get_or(args(), "line_width", 1.0)};

    auto layout = aChartDraw.transformed_layout();
    auto titers = aChartDraw.chart().titers();
    for (const auto ag_no : antigen_indexes) {
        for (const auto sr_no : serum_indexes) {
            if (const auto titer = titers->titer(ag_no, sr_no); !titer.is_dont_care()) {
                // std::cerr << "DEBUG: " << ag_no << ' ' << sr_no << ' ' << titer << '\n';
                if (const auto from = layout->get(ag_no), to = layout->get(sr_no + aChartDraw.number_of_antigens()); from.exists() && to.exists())
                    aChartDraw.line(from, to).color(line_color).line_width(line_width);
            }
        }
    }

} // ModConnectionLines::apply

// ----------------------------------------------------------------------

void ModColorByNumberOfConnectionLines::apply(ChartDraw& aChartDraw, const rjson::value& /*aModData*/)
{
    // ['#ffffcc','#ffeda0','#fed976','#feb24c','#fd8d3c','#fc4e2a','#e31a1c','#bd0026','#800026']

    // const std::array<Color, 11> colors{0x313695,0x4575b4,0x74add1,0xabd9e9,0xe0f3f8,0xffffbf,0xfee090,0xfdae61,0xf46d43,0xd73027,0xa50026};
    // const std::array<Color, 9> colors{0xfff5f0,0xfee0d2,0xfcbba1,0xfc9272,0xfb6a4a,0xef3b2c,0xcb181d,0xa50f15,0x67000d};
    const std::array<Color, 9> colors{0x313695,0x74add1,0xfcbba1,0xfc9272,0xfb6a4a,0xef3b2c,0xcb181d,0xa50f15,0x67000d};
    const auto [antigen_indexes, serum_indexes] = select_antigens_sera_for_connection_lines(aChartDraw, args()["antigens"], args()["sera"]);

    std::map<size_t, size_t> antigens_titers, sera_titers;
    auto titers = aChartDraw.chart().titers();
    for (const auto ag_no : antigen_indexes) {
        for (const auto sr_no : serum_indexes) {
            if (const auto titer = titers->titer(ag_no, sr_no); !titer.is_dont_care()) {
                ++antigens_titers[ag_no];
                ++sera_titers[sr_no];
            }
        }
    }
    // std::cerr << "DEBUG: antigens: " << antigens_titers << '\n';
    // std::cerr << "DEBUG: sera: " << sera_titers << '\n';

    const auto max_antigen_titers = std::max_element(std::begin(antigens_titers), std::end(antigens_titers), [](const auto& e1, const auto& e2) { return e1.second < e2.second; })->second;
    const auto bin_size = static_cast<size_t>(std::ceil(double(max_antigen_titers + 1) / colors.size()));
    // std::cerr << "DEBUG: max_antigen_titers: " << max_antigen_titers << '\n';

    std::vector<acmacs::chart::Indexes> antigens_per_bin(colors.size());
    for (const auto& [ag_no, num_titers] : antigens_titers)
        antigens_per_bin.at(num_titers / bin_size).insert(ag_no);
    for (auto [color_no, antigens] : acmacs::enumerate(antigens_per_bin)) {
        acmacs::PointStyle style;
        // style.outline = BLACK;
        style.fill = style.outline = colors.at(color_no);
        aChartDraw.modify(antigens, style, PointDrawingOrder::Raise);
        add_legend(aChartDraw, antigens, style, string::concat(color_no * bin_size, "-", (color_no + 1) * bin_size - 1, " titrations"), rjson::object{});
    }

} // ModColorByNumberOfConnectionLines::apply

// ----------------------------------------------------------------------

void ModErrorLines::apply(ChartDraw& aChartDraw, const rjson::value& /*aModData*/)
{
    const auto [antigen_indexes, serum_indexes] = select_antigens_sera_for_connection_lines(aChartDraw, args()["antigens"], args()["sera"]);

    const Color  line_color_td_more{rjson::get_or(args(), "color", "red")};
    const Color  line_color_td_less{rjson::get_or(args(), "color", "blue")};
    const double line_width{rjson::get_or(args(), "line_width", 1.0)};
    const bool   report{rjson::get_or(args(), "report", false)};
    const auto error_lines = aChartDraw.projection().error_lines();

    auto layout = aChartDraw.transformed_layout();
    auto titers = aChartDraw.chart().titers();
    auto antigens = aChartDraw.chart().antigens();
    auto sera = aChartDraw.chart().sera();
    const auto number_of_antigens = antigens->size();
    for (const auto ag_no : antigen_indexes) {
        for (const auto sr_no : serum_indexes) {
            const auto p2_no = sr_no + number_of_antigens;
            if (const auto found =
                    std::find_if(std::begin(error_lines), std::end(error_lines), [p1_no=ag_no,p2_no](const auto& erl) { return erl.point_1 == p1_no && erl.point_2 == p2_no; });
                found != std::end(error_lines)) {
                if (const auto p1 = layout->get(ag_no), p2 = layout->get(p2_no); p1.exists() && p2.exists()) {
                    if (report)
                        fmt::print("INFO: error line {} {} -- {} {} : {}\n", ag_no, antigens->at(ag_no)->full_name(), sr_no, sera->at(sr_no)->full_name(), found->error_line);
                    //aChartDraw.line(p1, p2).color(GREY).line_width(line_width * 3);
                    const auto v3 = (p2 - p1) / distance(p1, p2) * (- found->error_line) / 2.0;
                    const auto& color = found->error_line > 0 ? line_color_td_more : line_color_td_less;
                    aChartDraw.line(p1, p1 + v3).color(color).line_width(line_width);
                    aChartDraw.line(p2, p2 - v3).color(color).line_width(line_width);
                    // std::cerr << "DEBUG: " << found->point_1 << ' ' << sr_no << ' ' << found->error_line << ' ' << v3 << '\n';
                }
            }
        }
    }

} // ModErrorLines::apply

// ----------------------------------------------------------------------

std::pair<acmacs::chart::Indexes, acmacs::chart::Indexes> select_antigens_sera_for_connection_lines(ChartDraw& aChartDraw, const rjson::value& select_antigens, const rjson::value& select_sera)
{
    acmacs::chart::Indexes antigen_indexes, serum_indexes;
    if (!select_antigens.is_null())
        antigen_indexes = SelectAntigens(SelectAntigens::verbose::no, 100).select(aChartDraw, select_antigens);
    else
        antigen_indexes = aChartDraw.chart().antigens()->all_indexes();
    if (!select_sera.is_null())
        serum_indexes = SelectSera(SelectSera::verbose::no, 100).select(aChartDraw, select_sera);
    else
        serum_indexes = aChartDraw.chart().sera()->all_indexes();
    // std::cerr << "DEBUG: antigens: " << antigen_indexes << '\n';
    // std::cerr << "DEBUG: sera: " << serum_indexes << '\n';
    return {antigen_indexes, serum_indexes};

} // select_antigens_sera_for_connection_lines

// ----------------------------------------------------------------------

// ----------------------------------------------------------------------
/// Local Variables:
/// eval: (if (fboundp 'eu-rename-buffer) (eu-rename-buffer))
/// End:
<commit_msg>debugging<commit_after>#include <map>
#include <array>
#include <cmath>

#include "acmacs-base/stream.hh"
#include "acmacs-base/enumerate.hh"
#include "acmacs-base/string.hh"
#include "acmacs-map-draw/mod-connection-lines.hh"
#include "acmacs-map-draw/select.hh"

static std::pair<acmacs::chart::Indexes, acmacs::chart::Indexes> select_antigens_sera_for_connection_lines(ChartDraw& aChartDraw, const rjson::value& select_antigens, const rjson::value& select_sera);

// ----------------------------------------------------------------------

void ModConnectionLines::apply(ChartDraw& aChartDraw, const rjson::value& /*aModData*/)
{
    const auto [antigen_indexes, serum_indexes] = select_antigens_sera_for_connection_lines(aChartDraw, args()["antigens"], args()["sera"]);

    const Color line_color{rjson::get_or(args(), "color", "black")};
    const double line_width{rjson::get_or(args(), "line_width", 1.0)};

    auto layout = aChartDraw.transformed_layout();
    auto titers = aChartDraw.chart().titers();
    for (const auto ag_no : antigen_indexes) {
        for (const auto sr_no : serum_indexes) {
            if (const auto titer = titers->titer(ag_no, sr_no); !titer.is_dont_care()) {
                // std::cerr << "DEBUG: " << ag_no << ' ' << sr_no << ' ' << titer << '\n';
                if (const auto from = layout->get(ag_no), to = layout->get(sr_no + aChartDraw.number_of_antigens()); from.exists() && to.exists())
                    aChartDraw.line(from, to).color(line_color).line_width(line_width);
            }
        }
    }

} // ModConnectionLines::apply

// ----------------------------------------------------------------------

void ModColorByNumberOfConnectionLines::apply(ChartDraw& aChartDraw, const rjson::value& /*aModData*/)
{
    // ['#ffffcc','#ffeda0','#fed976','#feb24c','#fd8d3c','#fc4e2a','#e31a1c','#bd0026','#800026']

    // const std::array<Color, 11> colors{0x313695,0x4575b4,0x74add1,0xabd9e9,0xe0f3f8,0xffffbf,0xfee090,0xfdae61,0xf46d43,0xd73027,0xa50026};
    // const std::array<Color, 9> colors{0xfff5f0,0xfee0d2,0xfcbba1,0xfc9272,0xfb6a4a,0xef3b2c,0xcb181d,0xa50f15,0x67000d};
    const std::array<Color, 9> colors{0x313695,0x74add1,0xfcbba1,0xfc9272,0xfb6a4a,0xef3b2c,0xcb181d,0xa50f15,0x67000d};
    const auto [antigen_indexes, serum_indexes] = select_antigens_sera_for_connection_lines(aChartDraw, args()["antigens"], args()["sera"]);

    std::map<size_t, size_t> antigens_titers, sera_titers;
    auto titers = aChartDraw.chart().titers();
    for (const auto ag_no : antigen_indexes) {
        for (const auto sr_no : serum_indexes) {
            if (const auto titer = titers->titer(ag_no, sr_no); !titer.is_dont_care()) {
                ++antigens_titers[ag_no];
                ++sera_titers[sr_no];
            }
        }
    }
    // std::cerr << "DEBUG: antigens: " << antigens_titers << '\n';
    // std::cerr << "DEBUG: sera: " << sera_titers << '\n';

    const auto max_antigen_titers = std::max_element(std::begin(antigens_titers), std::end(antigens_titers), [](const auto& e1, const auto& e2) { return e1.second < e2.second; })->second;
    const auto bin_size = static_cast<size_t>(std::ceil(double(max_antigen_titers + 1) / colors.size()));
    // std::cerr << "DEBUG: max_antigen_titers: " << max_antigen_titers << '\n';

    std::vector<acmacs::chart::Indexes> antigens_per_bin(colors.size());
    for (const auto& [ag_no, num_titers] : antigens_titers)
        antigens_per_bin.at(num_titers / bin_size).insert(ag_no);
    for (auto [color_no, antigens] : acmacs::enumerate(antigens_per_bin)) {
        acmacs::PointStyle style;
        // style.outline = BLACK;
        style.fill = style.outline = colors.at(color_no);
        aChartDraw.modify(antigens, style, PointDrawingOrder::Raise);
        add_legend(aChartDraw, antigens, style, string::concat(color_no * bin_size, "-", (color_no + 1) * bin_size - 1, " titrations"), rjson::object{});
    }

} // ModColorByNumberOfConnectionLines::apply

// ----------------------------------------------------------------------

void ModErrorLines::apply(ChartDraw& aChartDraw, const rjson::value& /*aModData*/)
{
    const auto [antigen_indexes, serum_indexes] = select_antigens_sera_for_connection_lines(aChartDraw, args()["antigens"], args()["sera"]);

    const Color  line_color_td_more{rjson::get_or(args(), "color", "red")};
    const Color  line_color_td_less{rjson::get_or(args(), "color", "blue")};
    const double line_width{rjson::get_or(args(), "line_width", 1.0)};
    const bool   report{rjson::get_or(args(), "report", false)};
    const auto error_lines = aChartDraw.projection().error_lines();

    // if (report) {
    //     fmt::print("INFO: antigens for error lines: {}\nINFO: sera for error lines: {}\n", antigen_indexes, serum_indexes);
    //     for (const auto& errl : error_lines)
    //         fmt::print("INFO: error line {} {} : {}\n", errl.point_1, errl.point_2, errl.error_line);
    // }

    auto layout = aChartDraw.transformed_layout();
    auto titers = aChartDraw.chart().titers();
    auto antigens = aChartDraw.chart().antigens();
    auto sera = aChartDraw.chart().sera();
    const auto number_of_antigens = antigens->size();
    for (const auto ag_no : antigen_indexes) {
        for (const auto sr_no : serum_indexes) {
            const auto p2_no = sr_no + number_of_antigens;
            if (const auto found =
                    std::find_if(std::begin(error_lines), std::end(error_lines), [p1_no=ag_no,p2_no](const auto& erl) { return erl.point_1 == p1_no && erl.point_2 == p2_no; });
                found != std::end(error_lines)) {
                if (const auto p1 = layout->get(ag_no), p2 = layout->get(p2_no); p1.exists() && p2.exists()) {
                    if (report)
                        fmt::print("INFO: error line {} {} -- {} {} : {}\n", ag_no, antigens->at(ag_no)->full_name(), sr_no, sera->at(sr_no)->full_name(), found->error_line);
                    //aChartDraw.line(p1, p2).color(GREY).line_width(line_width * 3);
                    const auto v3 = (p2 - p1) / distance(p1, p2) * (- found->error_line) / 2.0;
                    const auto& color = found->error_line > 0 ? line_color_td_more : line_color_td_less;
                    aChartDraw.line(p1, p1 + v3).color(color).line_width(line_width);
                    aChartDraw.line(p2, p2 - v3).color(color).line_width(line_width);
                    // std::cerr << "DEBUG: " << found->point_1 << ' ' << sr_no << ' ' << found->error_line << ' ' << v3 << '\n';
                }
            }
        }
    }

} // ModErrorLines::apply

// ----------------------------------------------------------------------

std::pair<acmacs::chart::Indexes, acmacs::chart::Indexes> select_antigens_sera_for_connection_lines(ChartDraw& aChartDraw, const rjson::value& select_antigens, const rjson::value& select_sera)
{
    acmacs::chart::Indexes antigen_indexes, serum_indexes;
    if (!select_antigens.is_null())
        antigen_indexes = SelectAntigens(SelectAntigens::verbose::no, 100).select(aChartDraw, select_antigens);
    else
        antigen_indexes = aChartDraw.chart().antigens()->all_indexes();
    if (!select_sera.is_null())
        serum_indexes = SelectSera(SelectSera::verbose::no, 100).select(aChartDraw, select_sera);
    else
        serum_indexes = aChartDraw.chart().sera()->all_indexes();
    // std::cerr << "DEBUG: antigens: " << antigen_indexes << '\n';
    // std::cerr << "DEBUG: sera: " << serum_indexes << '\n';
    return {antigen_indexes, serum_indexes};

} // select_antigens_sera_for_connection_lines

// ----------------------------------------------------------------------

// ----------------------------------------------------------------------
/// Local Variables:
/// eval: (if (fboundp 'eu-rename-buffer) (eu-rename-buffer))
/// End:
<|endoftext|>


<commit_before>/***********************************************************************
    filename:   CEGUIIrrlichtTextureTarget.cpp
    created:    Tue Mar 3 2009
    author:     Paul D Turner (parts based on original code by Thomas Suter)
*************************************************************************/
/***************************************************************************
 *   Copyright (C) 2004 - 2009 Paul D Turner & The CEGUI Development Team
 *
 *   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 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.
 ***************************************************************************/
#ifdef HAVE_CONFIG_H
# include "config.h"
#endif

#include "CEGUIIrrlichtTextureTarget.h"
#include "CEGUIIrrlichtTexture.h"

// Start of CEGUI namespace section
namespace CEGUI
{
//----------------------------------------------------------------------------//
const float IrrlichtTextureTarget::DEFAULT_SIZE = 128.0f;

//----------------------------------------------------------------------------//
IrrlichtTextureTarget::IrrlichtTextureTarget(IrrlichtRenderer& owner,
                                             irr::video::IVideoDriver& driver) :
    IrrlichtRenderTarget(owner, driver),
    d_texture(0),
    d_CEGUITexture(static_cast<IrrlichtTexture*>(&d_owner.createTexture()))
{
    // setup area and cause the initial texture to be generated.
    declareRenderSize(Size(DEFAULT_SIZE, DEFAULT_SIZE));
}

//----------------------------------------------------------------------------//
IrrlichtTextureTarget::~IrrlichtTextureTarget()
{
    cleanupTargetTexture();
    d_owner.destroyTexture(*d_CEGUITexture);
}

//----------------------------------------------------------------------------//
void IrrlichtTextureTarget::activate()
{
    d_driver.setRenderTarget(d_texture, false, false);
    IrrlichtRenderTarget::activate();
}

//----------------------------------------------------------------------------//
void IrrlichtTextureTarget::deactivate()
{
    IrrlichtRenderTarget::deactivate();
    d_driver.setRenderTarget(0);
}

//----------------------------------------------------------------------------//
bool IrrlichtTextureTarget::isImageryCache() const
{
    return true;
}

//----------------------------------------------------------------------------//
void IrrlichtTextureTarget::clear()
{
    d_driver.setRenderTarget(d_texture, true, false,
                             irr::video::SColor(0, 0, 0, 0));
    d_driver.setRenderTarget(0);
}

//----------------------------------------------------------------------------//
Texture& IrrlichtTextureTarget::getTexture() const
{
    return *d_CEGUITexture;
}

//----------------------------------------------------------------------------//
void IrrlichtTextureTarget::declareRenderSize(const Size& sz)
{
    const bool realloc =
                !d_texture ||
                static_cast<float>(d_texture->getSize().Width) < sz.d_width ||
                static_cast<float>(d_texture->getSize().Height) < sz.d_height;

    // update area to render into.
    setArea(Rect(d_area.getPosition(), sz));

    // exit if current texture size is large enough
    if (!realloc)
        return;

    // get adjusted size - to account for device capabilities
    const Size final_sz(d_owner.getAdjustedTextureSize(sz));

    cleanupTargetTexture();

    #if CEGUI_IRR_SDK_VERSION >= 16
        const irr::core::dimension2d<irr::u32> irr_sz(
            static_cast<irr::u32>(final_sz.d_width),
            static_cast<irr::u32>(final_sz.d_height));
    #else
        const irr::core::dimension2d<irr::s32> irr_sz(
            static_cast<irr::s32>(final_sz.d_width),
            static_cast<irr::s32>(final_sz.d_height));
    #endif

    d_texture = d_driver.addRenderTargetTexture(
        irr_sz, IrrlichtTexture::getUniqueName().c_str());

    d_CEGUITexture->setIrrlichtTexture(d_texture);
    d_CEGUITexture->setOriginalDataSize(d_area.getSize());

    clear();
}

//----------------------------------------------------------------------------//
bool IrrlichtTextureTarget::isRenderingInverted() const
{
    return false;
}

//----------------------------------------------------------------------------//
void IrrlichtTextureTarget::cleanupTargetTexture()
{
    if (d_texture)
    {
        d_CEGUITexture->setIrrlichtTexture(0);
        d_driver.removeTexture(d_texture);
        d_texture = 0;
    }
}

//----------------------------------------------------------------------------//

} // End of  CEGUI namespace section
<commit_msg>FIX: IrrlichtRenderer would incorrectly clear the main render target (screen) during render to texture operations.  Thanks to Timo.  See: http://www.cegui.org.uk/mantis/view.php?id=348<commit_after>/***********************************************************************
    filename:   CEGUIIrrlichtTextureTarget.cpp
    created:    Tue Mar 3 2009
    author:     Paul D Turner (parts based on original code by Thomas Suter)
*************************************************************************/
/***************************************************************************
 *   Copyright (C) 2004 - 2009 Paul D Turner & The CEGUI Development Team
 *
 *   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 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.
 ***************************************************************************/
#ifdef HAVE_CONFIG_H
# include "config.h"
#endif

#include "CEGUIIrrlichtTextureTarget.h"
#include "CEGUIIrrlichtTexture.h"

// Start of CEGUI namespace section
namespace CEGUI
{
//----------------------------------------------------------------------------//
const float IrrlichtTextureTarget::DEFAULT_SIZE = 128.0f;

//----------------------------------------------------------------------------//
IrrlichtTextureTarget::IrrlichtTextureTarget(IrrlichtRenderer& owner,
                                             irr::video::IVideoDriver& driver) :
    IrrlichtRenderTarget(owner, driver),
    d_texture(0),
    d_CEGUITexture(static_cast<IrrlichtTexture*>(&d_owner.createTexture()))
{
    // setup area and cause the initial texture to be generated.
    declareRenderSize(Size(DEFAULT_SIZE, DEFAULT_SIZE));
}

//----------------------------------------------------------------------------//
IrrlichtTextureTarget::~IrrlichtTextureTarget()
{
    cleanupTargetTexture();
    d_owner.destroyTexture(*d_CEGUITexture);
}

//----------------------------------------------------------------------------//
void IrrlichtTextureTarget::activate()
{
    d_driver.setRenderTarget(d_texture, false, false);
    IrrlichtRenderTarget::activate();
}

//----------------------------------------------------------------------------//
void IrrlichtTextureTarget::deactivate()
{
    IrrlichtRenderTarget::deactivate();
    d_driver.setRenderTarget(0, false, false);
}

//----------------------------------------------------------------------------//
bool IrrlichtTextureTarget::isImageryCache() const
{
    return true;
}

//----------------------------------------------------------------------------//
void IrrlichtTextureTarget::clear()
{
    d_driver.setRenderTarget(d_texture, true, false,
                             irr::video::SColor(0, 0, 0, 0));
    d_driver.setRenderTarget(0, false, false);
}

//----------------------------------------------------------------------------//
Texture& IrrlichtTextureTarget::getTexture() const
{
    return *d_CEGUITexture;
}

//----------------------------------------------------------------------------//
void IrrlichtTextureTarget::declareRenderSize(const Size& sz)
{
    const bool realloc =
                !d_texture ||
                static_cast<float>(d_texture->getSize().Width) < sz.d_width ||
                static_cast<float>(d_texture->getSize().Height) < sz.d_height;

    // update area to render into.
    setArea(Rect(d_area.getPosition(), sz));

    // exit if current texture size is large enough
    if (!realloc)
        return;

    // get adjusted size - to account for device capabilities
    const Size final_sz(d_owner.getAdjustedTextureSize(sz));

    cleanupTargetTexture();

    #if CEGUI_IRR_SDK_VERSION >= 16
        const irr::core::dimension2d<irr::u32> irr_sz(
            static_cast<irr::u32>(final_sz.d_width),
            static_cast<irr::u32>(final_sz.d_height));
    #else
        const irr::core::dimension2d<irr::s32> irr_sz(
            static_cast<irr::s32>(final_sz.d_width),
            static_cast<irr::s32>(final_sz.d_height));
    #endif

    d_texture = d_driver.addRenderTargetTexture(
        irr_sz, IrrlichtTexture::getUniqueName().c_str());

    d_CEGUITexture->setIrrlichtTexture(d_texture);
    d_CEGUITexture->setOriginalDataSize(d_area.getSize());

    clear();
}

//----------------------------------------------------------------------------//
bool IrrlichtTextureTarget::isRenderingInverted() const
{
    return false;
}

//----------------------------------------------------------------------------//
void IrrlichtTextureTarget::cleanupTargetTexture()
{
    if (d_texture)
    {
        d_CEGUITexture->setIrrlichtTexture(0);
        d_driver.removeTexture(d_texture);
        d_texture = 0;
    }
}

//----------------------------------------------------------------------------//

} // End of  CEGUI namespace section
<|endoftext|>


<commit_before>/*
 * HypothesisColl.cpp
 *
 *  Created on: 26 Feb 2016
 *      Author: hieu
 */
#include <iostream>
#include <sstream>
#include <algorithm>
#include <boost/foreach.hpp>
#include "HypothesisColl.h"
#include "ManagerBase.h"
#include "System.h"
#include "MemPoolAllocator.h"

using namespace std;

namespace Moses2
{

HypothesisColl::HypothesisColl(const ManagerBase &mgr)
  :m_coll(MemPoolAllocator<const HypothesisBase*>(mgr.GetPool()))
  ,m_sortedHypos(NULL)
{
  m_bestScore = -std::numeric_limits<float>::infinity();
  m_worstScore = std::numeric_limits<float>::infinity();
}

const HypothesisBase *HypothesisColl::GetBestHypo() const
{
  if (GetSize() == 0) {
    return NULL;
  }
  if (m_sortedHypos) {
    return (*m_sortedHypos)[0];
  }

  SCORE bestScore = -std::numeric_limits<SCORE>::infinity();
  const HypothesisBase *bestHypo;
  BOOST_FOREACH(const HypothesisBase *hypo, m_coll) {
    if (hypo->GetFutureScore() > bestScore) {
      bestScore = hypo->GetFutureScore();
      bestHypo = hypo;
    }
  }
  return bestHypo;
}

void HypothesisColl::Add(
  const ManagerBase &mgr,
  HypothesisBase *hypo,
  Recycler<HypothesisBase*> &hypoRecycle,
  ArcLists &arcLists)
{
  size_t maxStackSize = mgr.system.options.search.stack_size;

  if (GetSize() > maxStackSize * 2) {
    //cerr << "maxStackSize=" << maxStackSize << " " << GetSize() << endl;
    PruneHypos(mgr, mgr.arcLists);
  }

  SCORE futureScore = hypo->GetFutureScore();

  /*
  cerr << "scores:"
      << futureScore << " "
      << m_bestScore << " "
      << GetSize() << " "
      << endl;
  */
  if (GetSize() >= maxStackSize && futureScore < m_worstScore) {
    // beam threshold or really bad hypo that won't make the pruning cut
    // as more hypos are added, the m_worstScore stat gets out of date and isn't the optimum cut-off point
    //cerr << "Discard, really bad score:" << hypo->Debug(mgr.system) << endl;
    hypoRecycle.Recycle(hypo);
    return;
  }

  StackAdd added = Add(hypo);

  size_t nbestSize = mgr.system.options.nbest.nbest_size;
  if (nbestSize) {
    arcLists.AddArc(added.added, hypo, added.other);
  } else {
    if (added.added) {
      if (added.other) {
        hypoRecycle.Recycle(added.other);
      }
    } else {
      hypoRecycle.Recycle(hypo);
    }
  }

  // update beam variables
  if (added.added) {
    if (futureScore > m_bestScore) {
      m_bestScore = futureScore;
      float beamWidth = mgr.system.options.search.beam_width;
      if ( m_bestScore + beamWidth > m_worstScore ) {
        m_worstScore = m_bestScore + beamWidth;
      }
    } else if (GetSize() <= maxStackSize && futureScore < m_worstScore) {
      m_worstScore = futureScore;
    }
  }
}

StackAdd HypothesisColl::Add(const HypothesisBase *hypo)
{
  std::pair<_HCType::iterator, bool> addRet = m_coll.insert(hypo);
  //cerr << endl << "new=" << hypo->Debug(hypo->GetManager().system) << endl;

  // CHECK RECOMBINATION
  if (addRet.second) {
    // equiv hypo doesn't exists
    //cerr << "Added " << hypo << endl;
    return StackAdd(true, NULL);
  } else {
    HypothesisBase *hypoExisting = const_cast<HypothesisBase*>(*addRet.first);
    //cerr << "hypoExisting=" << hypoExisting->Debug(hypo->GetManager().system) << endl;

    if (hypo->GetFutureScore() > hypoExisting->GetFutureScore()) {
      // incoming hypo is better than the one we have
      const HypothesisBase * const &hypoExisting1 = *addRet.first;
      const HypothesisBase *&hypoExisting2 =
        const_cast<const HypothesisBase *&>(hypoExisting1);
      hypoExisting2 = hypo;

      //cerr << "Added " << hypo << " dicard existing " << hypoExisting2 << endl;
      return StackAdd(true, hypoExisting);
    } else {
      // already storing the best hypo. discard incoming hypo
      //cerr << "Keep existing " << hypoExisting << " dicard new " << hypo << endl;
      return StackAdd(false, hypoExisting);
    }
  }

  //assert(false);
}

const Hypotheses &HypothesisColl::GetSortedAndPrunedHypos(
  const ManagerBase &mgr,
  ArcLists &arcLists) const
{
  if (m_sortedHypos == NULL) {
    // create sortedHypos first
    MemPool &pool = mgr.GetPool();
    m_sortedHypos = new (pool.Allocate<Hypotheses>()) Hypotheses(pool,
        m_coll.size());

    SortHypos(mgr, m_sortedHypos->GetArray());

    // prune
    Recycler<HypothesisBase*> &recycler = mgr.GetHypoRecycle();

    size_t maxStackSize = mgr.system.options.search.stack_size;
    if (maxStackSize && m_sortedHypos->size() > maxStackSize) {
      for (size_t i = maxStackSize; i < m_sortedHypos->size(); ++i) {
        HypothesisBase *hypo = const_cast<HypothesisBase*>((*m_sortedHypos)[i]);
        recycler.Recycle(hypo);

        // delete from arclist
        if (mgr.system.options.nbest.nbest_size) {
          arcLists.Delete(hypo);
        }
      }
      m_sortedHypos->resize(maxStackSize);
    }

  }

  return *m_sortedHypos;
}

void HypothesisColl::PruneHypos(const ManagerBase &mgr, ArcLists &arcLists)
{
  size_t maxStackSize = mgr.system.options.search.stack_size;

  Recycler<HypothesisBase*> &recycler = mgr.GetHypoRecycle();

  const HypothesisBase **sortedHypos = (const HypothesisBase **) alloca(GetSize() * sizeof(const HypothesisBase *));
  SortHypos(mgr, sortedHypos);

  // update worse score
  m_worstScore = sortedHypos[maxStackSize - 1]->GetFutureScore();

  // prune
  for (size_t i = maxStackSize; i < GetSize(); ++i) {
    HypothesisBase *hypo = const_cast<HypothesisBase*>(sortedHypos[i]);

    // delete from arclist
    if (mgr.system.options.nbest.nbest_size) {
      arcLists.Delete(hypo);
    }

    // delete from collection
    Delete(hypo);

    recycler.Recycle(hypo);
  }

}

void HypothesisColl::SortHypos(const ManagerBase &mgr, const HypothesisBase **sortedHypos) const
{
  size_t maxStackSize = mgr.system.options.search.stack_size;
  //assert(maxStackSize); // can't do stack=0 - unlimited stack size. No-one ever uses that
  //assert(GetSize() > maxStackSize);
  //assert(sortedHypos.size() == GetSize());

  /*
   cerr << "UNSORTED hypos: ";
   BOOST_FOREACH(const HypothesisBase *hypo, m_coll) {
     cerr << hypo << "(" << hypo->GetFutureScore() << ")" << " ";
   }
   cerr << endl;
   */
  size_t ind = 0;
  BOOST_FOREACH(const HypothesisBase *hypo, m_coll) {
    sortedHypos[ind] = hypo;
    ++ind;
  }

  size_t indMiddle;
  if (maxStackSize == 0) {
    indMiddle = GetSize();
  } else if (GetSize() > maxStackSize) {
    indMiddle = maxStackSize;
  } else {
    // GetSize() <= maxStackSize
    indMiddle = GetSize();
  }

  const HypothesisBase **iterMiddle = sortedHypos + indMiddle;

  std::partial_sort(
    sortedHypos,
    iterMiddle,
    sortedHypos + GetSize(),
    HypothesisFutureScoreOrderer());

  /*
   cerr << "sorted hypos: ";
   for (size_t i = 0; i < sortedHypos.size(); ++i) {
     const HypothesisBase *hypo = sortedHypos[i];
     cerr << hypo << " ";
   }
   cerr << endl;
   */
}

void HypothesisColl::Delete(const HypothesisBase *hypo)
{
  //cerr << "hypo=" << hypo << " " << m_coll.size() << endl;

  size_t erased = m_coll.erase(hypo);
  UTIL_THROW_IF2(erased != 1, "couldn't erase hypo " << hypo);
}

void HypothesisColl::Clear()
{
  m_sortedHypos = NULL;
  m_coll.clear();

  m_bestScore = -std::numeric_limits<float>::infinity();
  m_worstScore = std::numeric_limits<float>::infinity();
}

std::string HypothesisColl::Debug(const System &system) const
{
  stringstream out;
  BOOST_FOREACH (const HypothesisBase *hypo, m_coll) {
    out << hypo->Debug(system);
    out << std::endl << std::endl;
  }

  return out.str();
}

} /* namespace Moses2 */
<commit_msg>debug<commit_after>/*
 * HypothesisColl.cpp
 *
 *  Created on: 26 Feb 2016
 *      Author: hieu
 */
#include <iostream>
#include <sstream>
#include <algorithm>
#include <boost/foreach.hpp>
#include "HypothesisColl.h"
#include "ManagerBase.h"
#include "System.h"
#include "MemPoolAllocator.h"

using namespace std;

namespace Moses2
{

HypothesisColl::HypothesisColl(const ManagerBase &mgr)
  :m_coll(MemPoolAllocator<const HypothesisBase*>(mgr.GetPool()))
  ,m_sortedHypos(NULL)
{
  m_bestScore = -std::numeric_limits<float>::infinity();
  m_worstScore = std::numeric_limits<float>::infinity();
}

const HypothesisBase *HypothesisColl::GetBestHypo() const
{
  if (GetSize() == 0) {
    return NULL;
  }
  if (m_sortedHypos) {
    return (*m_sortedHypos)[0];
  }

  SCORE bestScore = -std::numeric_limits<SCORE>::infinity();
  const HypothesisBase *bestHypo;
  BOOST_FOREACH(const HypothesisBase *hypo, m_coll) {
    if (hypo->GetFutureScore() > bestScore) {
      bestScore = hypo->GetFutureScore();
      bestHypo = hypo;
    }
  }
  return bestHypo;
}

void HypothesisColl::Add(
  const ManagerBase &mgr,
  HypothesisBase *hypo,
  Recycler<HypothesisBase*> &hypoRecycle,
  ArcLists &arcLists)
{
  size_t maxStackSize = mgr.system.options.search.stack_size;

  if (GetSize() > maxStackSize * 2) {
    //cerr << "maxStackSize=" << maxStackSize << " " << GetSize() << endl;
    PruneHypos(mgr, mgr.arcLists);
  }

  SCORE futureScore = hypo->GetFutureScore();

  /*
  cerr << "scores:"
      << futureScore << " "
      << m_bestScore << " "
      << GetSize() << " "
      << endl;
  */
  if (GetSize() >= maxStackSize && futureScore < m_worstScore) {
    // beam threshold or really bad hypo that won't make the pruning cut
    // as more hypos are added, the m_worstScore stat gets out of date and isn't the optimum cut-off point
    //cerr << "Discard, really bad score:" << hypo->Debug(mgr.system) << endl;
    hypoRecycle.Recycle(hypo);
    return;
  }

  StackAdd added = Add(hypo);

  size_t nbestSize = mgr.system.options.nbest.nbest_size;
  if (nbestSize) {
    arcLists.AddArc(added.added, hypo, added.other);
  } else {
    if (added.added) {
      if (added.other) {
        hypoRecycle.Recycle(added.other);
      }
    } else {
      hypoRecycle.Recycle(hypo);
    }
  }

  // update beam variables
  if (added.added) {
    if (futureScore > m_bestScore) {
      m_bestScore = futureScore;
      float beamWidth = mgr.system.options.search.beam_width;
      if ( m_bestScore + beamWidth > m_worstScore ) {
        m_worstScore = m_bestScore + beamWidth;
      }
    } else if (GetSize() <= maxStackSize && futureScore < m_worstScore) {
      m_worstScore = futureScore;
    }
  }
}

StackAdd HypothesisColl::Add(const HypothesisBase *hypo)
{
  std::pair<_HCType::iterator, bool> addRet = m_coll.insert(hypo);
  //cerr << endl << "new=" << hypo->Debug(hypo->GetManager().system) << endl;

  // CHECK RECOMBINATION
  if (addRet.second) {
    // equiv hypo doesn't exists
    //cerr << "Added " << hypo << endl;
    return StackAdd(true, NULL);
  } else {
    HypothesisBase *hypoExisting = const_cast<HypothesisBase*>(*addRet.first);
    //cerr << "hypoExisting=" << hypoExisting->Debug(hypo->GetManager().system) << endl;

    if (hypo->GetFutureScore() > hypoExisting->GetFutureScore()) {
      // incoming hypo is better than the one we have
      const HypothesisBase * const &hypoExisting1 = *addRet.first;
      const HypothesisBase *&hypoExisting2 =
        const_cast<const HypothesisBase *&>(hypoExisting1);
      hypoExisting2 = hypo;

      cerr << "Added " << hypo << "(" << hypo->hash() << ")"
    		  << " discard existing " << hypoExisting << "(" << hypoExisting->hash() << ")"
			  << endl;

      return StackAdd(true, hypoExisting);
    } else {
      // already storing the best hypo. discard incoming hypo
      cerr << "Keep existing " << hypoExisting << "(" << hypoExisting->hash() << ")"
    		  << " discard new " << hypo << "(" << hypo->hash() << ")"
			  << endl;
      return StackAdd(false, hypoExisting);
    }
  }

  //assert(false);
}

const Hypotheses &HypothesisColl::GetSortedAndPrunedHypos(
  const ManagerBase &mgr,
  ArcLists &arcLists) const
{
  if (m_sortedHypos == NULL) {
    // create sortedHypos first
    MemPool &pool = mgr.GetPool();
    m_sortedHypos = new (pool.Allocate<Hypotheses>()) Hypotheses(pool,
        m_coll.size());

    SortHypos(mgr, m_sortedHypos->GetArray());

    // prune
    Recycler<HypothesisBase*> &recycler = mgr.GetHypoRecycle();

    size_t maxStackSize = mgr.system.options.search.stack_size;
    if (maxStackSize && m_sortedHypos->size() > maxStackSize) {
      for (size_t i = maxStackSize; i < m_sortedHypos->size(); ++i) {
        HypothesisBase *hypo = const_cast<HypothesisBase*>((*m_sortedHypos)[i]);
        recycler.Recycle(hypo);

        // delete from arclist
        if (mgr.system.options.nbest.nbest_size) {
          arcLists.Delete(hypo);
        }
      }
      m_sortedHypos->resize(maxStackSize);
    }

  }

  return *m_sortedHypos;
}

void HypothesisColl::PruneHypos(const ManagerBase &mgr, ArcLists &arcLists)
{
  size_t maxStackSize = mgr.system.options.search.stack_size;

  Recycler<HypothesisBase*> &recycler = mgr.GetHypoRecycle();

  const HypothesisBase **sortedHypos = (const HypothesisBase **) alloca(GetSize() * sizeof(const HypothesisBase *));
  SortHypos(mgr, sortedHypos);

  // update worse score
  m_worstScore = sortedHypos[maxStackSize - 1]->GetFutureScore();

  // prune
  for (size_t i = maxStackSize; i < GetSize(); ++i) {
    HypothesisBase *hypo = const_cast<HypothesisBase*>(sortedHypos[i]);

    // delete from arclist
    if (mgr.system.options.nbest.nbest_size) {
      arcLists.Delete(hypo);
    }

    // delete from collection
    Delete(hypo);

    recycler.Recycle(hypo);
  }

}

void HypothesisColl::SortHypos(const ManagerBase &mgr, const HypothesisBase **sortedHypos) const
{
  size_t maxStackSize = mgr.system.options.search.stack_size;
  //assert(maxStackSize); // can't do stack=0 - unlimited stack size. No-one ever uses that
  //assert(GetSize() > maxStackSize);
  //assert(sortedHypos.size() == GetSize());

  /*
   cerr << "UNSORTED hypos: ";
   BOOST_FOREACH(const HypothesisBase *hypo, m_coll) {
     cerr << hypo << "(" << hypo->GetFutureScore() << ")" << " ";
   }
   cerr << endl;
   */
  size_t ind = 0;
  BOOST_FOREACH(const HypothesisBase *hypo, m_coll) {
    sortedHypos[ind] = hypo;
    ++ind;
  }

  size_t indMiddle;
  if (maxStackSize == 0) {
    indMiddle = GetSize();
  } else if (GetSize() > maxStackSize) {
    indMiddle = maxStackSize;
  } else {
    // GetSize() <= maxStackSize
    indMiddle = GetSize();
  }

  const HypothesisBase **iterMiddle = sortedHypos + indMiddle;

  std::partial_sort(
    sortedHypos,
    iterMiddle,
    sortedHypos + GetSize(),
    HypothesisFutureScoreOrderer());

  /*
   cerr << "sorted hypos: ";
   for (size_t i = 0; i < sortedHypos.size(); ++i) {
     const HypothesisBase *hypo = sortedHypos[i];
     cerr << hypo << " ";
   }
   cerr << endl;
   */
}

void HypothesisColl::Delete(const HypothesisBase *hypo)
{
  cerr << " Delete hypo=" << hypo << "(" << hypo->hash() << ")"
		<< " m_coll=" << m_coll.size() << endl;

  size_t erased = m_coll.erase(hypo);
  UTIL_THROW_IF2(erased != 1, "couldn't erase hypo " << hypo);
}

void HypothesisColl::Clear()
{
  m_sortedHypos = NULL;
  m_coll.clear();

  m_bestScore = -std::numeric_limits<float>::infinity();
  m_worstScore = std::numeric_limits<float>::infinity();
}

std::string HypothesisColl::Debug(const System &system) const
{
  stringstream out;
  BOOST_FOREACH (const HypothesisBase *hypo, m_coll) {
    out << hypo->Debug(system);
    out << std::endl << std::endl;
  }

  return out.str();
}

} /* namespace Moses2 */
<|endoftext|>


<commit_before>#include <iostream>
#include "elevator.h"
#include "log.h"

Elevator::Elevator(int idnum) {
    id = idnum;

    current_floor = 1;
    requested_floor = 1;
    next_floor = 1;
    direction_arrived = UP;
    elevator_state = INITIALIZING;

    pthread_cond_init(&elevator_wait, NULL);
    pthread_mutex_init(&elevator_mutex, NULL);

    pthread_create(&elevator_thread, NULL, elevator_run, this);
}

void *Elevator::elevator_run(void *arg) {
    Elevator *me = static_cast<Elevator *>(arg);

    if (me == NULL)
        return NULL;

    while (1) {
        pthread_mutex_lock(&me->elevator_mutex);
        me->elevator_state = READY;
        while (me->schedule_next_request() == false) {
            eprintf("%s:%s Waiting...\n", __func__, __FILE__);
            pthread_cond_wait(&me->elevator_wait, &me->elevator_mutex);
            eprintf("%s:%s Scheduer kicking in...\n", __func__, __FILE__);
        }
        me->elevator_state = RUNNING;

        eprintf("%s:%s Elevator RUNNING dest %d\n", __func__, __FILE__, me->requested_floor);
        me->process_request();

        pthread_mutex_unlock(&me->elevator_mutex);
    }

    return NULL;
}

void Elevator::process_request() {
    next_floor = requested_floor;
    if (requested_floor > current_floor)
        direction_arrived = UP;
    else
        direction_arrived = DOWN;

    current_floor = next_floor;
}

bool Elevator::queue_next_request(int floor) {

    while (elevator_state != READY);
    requested_floor = floor;

    return true;
}

bool Elevator::queue_pending_request(int floor, displacement d) {
    pthread_mutex_lock(&elevator_mutex);

    requests.push_back(make_pair(floor, d));
    eprintf("%s:%s queue request floor:%d direction:%d sz %lu\n",
            __func__, __FILE__, floor, d, requests.size());
    pthread_cond_signal(&elevator_wait);

    pthread_mutex_unlock(&elevator_mutex);

    return true;
}

bool Elevator::schedule_next_request() {

    eprintf("%s:%s Called... %lu\n", __func__, __FILE__, requests.size());
    if (requests.size() == 0) {
        eprintf("%s:%s Queue is empty\n", __func__, __FILE__);
        return false;
    }

    if (requests.size() == 1) {
        queue_next_request(requests[0].first);
        eprintf("%s:%s q size 1, next floor %d\n",
               __func__, __FILE__, requests[0].first);
        requests.erase(requests.begin());
        return true;
    }

    int size = requests.size();

    if (direction_arrived == UP) {
        int same_d_floor = MAX_FLOORS + 1, same_d_min_index;
        int opp_d_floor = MAX_FLOORS + 1, opp_d_min_index;

        int same_d_low_floor = -1, same_d_low_max_index;
        int opp_d_low_floor = -1, opp_d_low_max_index;

        pair<int, displacement> p;

        for (int i = 0; i < size; i++) {
            p = requests[i];
            if (p.first > current_floor) {
                if (p.second == direction_arrived) {
                    same_d_floor = min(same_d_floor, p.first);
                    same_d_min_index = i;
                } else {
                    opp_d_floor = min(opp_d_floor, p.first);
                    opp_d_min_index = i;
                }
            } else {
                if (p.second != direction_arrived) {
                    opp_d_low_floor = max(opp_d_low_floor, p.first);
                    opp_d_low_max_index = i;
                } else {
                    same_d_low_floor = max(same_d_low_floor, p.first);
                    same_d_low_max_index = i;
                }
            }
        }

        if (same_d_floor != MAX_FLOORS + 1) {
            queue_next_request(requests[same_d_min_index].first);
            eprintf("%s:%s q size %d, next floor %d\n",
                __func__, __FILE__, size, requests[0].first);
            requests.erase(requests.begin() + same_d_min_index);
            return true;
        }

        if (opp_d_floor != MAX_FLOORS + 1) {
            queue_next_request(requests[opp_d_min_index].first);
            eprintf("%s:%s q size %d, next floor %d\n",
                __func__, __FILE__, size, requests[0].first);
            requests.erase(requests.begin() + opp_d_min_index);
            return true;
        }

        if (opp_d_low_floor != - 1) {
            queue_next_request(requests[opp_d_low_max_index].first);
            eprintf("%s:%s q size %d, next floor %d\n",
                __func__, __FILE__, size, requests[0].first);
            requests.erase(requests.begin() + opp_d_low_max_index);
            return true;
        }

        if (same_d_low_floor != - 1) {
            queue_next_request(requests[same_d_low_max_index].first);
            eprintf("%s:%s q size %d, next floor %d\n",
                __func__, __FILE__, size, requests[0].first);
            requests.erase(requests.begin() + same_d_low_max_index);
            return true;
        }

    } else {
        int same_d_floor = -1, same_d_max_index;
        int opp_d_floor = -1, opp_d_max_index;

        int same_d_high_floor = MAX_FLOORS + 1, same_d_high_min_index;
        int opp_d_high_floor = MAX_FLOORS + 1, opp_d_high_min_index;

        pair<int, displacement> p;

        for (int i = 0; i < size; i++) {
            p = requests[i];
            if (p.first < current_floor) {
                if (p.second == direction_arrived) {
                    same_d_floor = max(same_d_floor, p.first);
                    same_d_max_index = i;
                } else {
                    opp_d_floor = max(opp_d_floor, p.first);
                    opp_d_max_index = i;
                }
            } else {
                if (p.second != direction_arrived) {
                    opp_d_high_floor = min(opp_d_high_floor, p.first);
                    opp_d_high_min_index = i;
                } else {
                    same_d_high_floor = min(same_d_high_floor, p.first);
                    same_d_high_min_index = i;
                }
            }
        }

        if (same_d_floor != -1) {
            queue_next_request(requests[same_d_max_index].first);
            eprintf("%s:%s q size %d, next floor %d\n",
                __func__, __FILE__, size, requests[0].first);
            requests.erase(requests.begin() + same_d_max_index);
            return true;
        }

        if (opp_d_floor != -1) {
            queue_next_request(requests[opp_d_max_index].first);
            eprintf("%s:%s q size %d, next floor %d\n",
                __func__, __FILE__, size, requests[0].first);
            requests.erase(requests.begin() + opp_d_max_index);
            return true;
        }

        if (opp_d_high_floor != MAX_FLOORS + 1) {
            queue_next_request(requests[opp_d_high_min_index].first);
            eprintf("%s:%s q size %d, next floor %d\n",
                __func__, __FILE__, size, requests[0].first);
            requests.erase(requests.begin() + opp_d_high_min_index);
            return true;
        }

        if (same_d_high_floor != MAX_FLOORS + 1) {
            queue_next_request(requests[same_d_high_min_index].first);
            eprintf("%s:%s q size %d, next floor %d\n",
                __func__, __FILE__, size, requests[0].first);
            requests.erase(requests.begin() + same_d_high_min_index);
            return true;
        }
    }

    eprintf("%s:%s Error! cannot process queue (%lu)\n",
            __func__, __FILE__, requests.size());
    return false;
}

int Elevator::get_current_floor() {
    pthread_mutex_lock(&elevator_mutex);

    while (elevator_state != READY);
    return current_floor;

    pthread_mutex_unlock(&elevator_mutex);
}

displacement Elevator::get_displacement() {
    pthread_mutex_lock(&elevator_mutex);

    while (elevator_state != READY);
    return direction_arrived;

    pthread_mutex_unlock(&elevator_mutex);
}
<commit_msg>elevator: modify elevator algorithm<commit_after>#include <iostream>
#include "elevator.h"
#include "log.h"

Elevator::Elevator(int idnum) {
    id = idnum;

    current_floor = 1;
    requested_floor = 1;
    next_floor = 1;
    direction_arrived = UP;
    elevator_state = INITIALIZING;

    pthread_cond_init(&elevator_wait, NULL);
    pthread_mutex_init(&elevator_mutex, NULL);

    pthread_create(&elevator_thread, NULL, elevator_run, this);
}

void *Elevator::elevator_run(void *arg) {
    Elevator *me = static_cast<Elevator *>(arg);

    if (me == NULL)
        return NULL;

    while (1) {
        pthread_mutex_lock(&me->elevator_mutex);
        me->elevator_state = READY;
        while (me->schedule_next_request() == false) {
            eprintf("%s:%s Waiting...\n", __func__, __FILE__);
            pthread_cond_wait(&me->elevator_wait, &me->elevator_mutex);
            eprintf("%s:%s Scheduer kicking in...\n", __func__, __FILE__);
        }
        me->elevator_state = RUNNING;

        eprintf("%s:%s Elevator RUNNING dest %d\n", __func__, __FILE__, me->requested_floor);
        me->process_request();

        pthread_mutex_unlock(&me->elevator_mutex);
    }

    return NULL;
}

void Elevator::process_request() {
    next_floor = requested_floor;
    if (requested_floor > current_floor)
        direction_arrived = UP;
    else
        direction_arrived = DOWN;

    current_floor = next_floor;
}

bool Elevator::queue_next_request(int floor) {

    while (elevator_state != READY);
    requested_floor = floor;

    return true;
}

bool Elevator::queue_pending_request(int floor, displacement d) {
    pthread_mutex_lock(&elevator_mutex);

    requests.push_back(make_pair(floor, d));
    eprintf("%s:%s queue request floor:%d direction:%d sz %lu\n",
            __func__, __FILE__, floor, d, requests.size());
    pthread_cond_signal(&elevator_wait);

    pthread_mutex_unlock(&elevator_mutex);

    return true;
}

bool Elevator::schedule_next_request() {

    eprintf("%s:%s Called... %lu\n", __func__, __FILE__, requests.size());
    if (requests.size() == 0) {
        eprintf("%s:%s Queue is empty\n", __func__, __FILE__);
        return false;
    }

    if (requests.size() == 1) {
        queue_next_request(requests[0].first);
        eprintf("%s:%s q size 1, next floor %d\n",
               __func__, __FILE__, requests[0].first);
        requests.erase(requests.begin());
        return true;
    }

    int size = requests.size();

    if (direction_arrived == UP) {
        int same_d_floor = MAX_FLOORS + 1, same_d_min_index;
        int opp_d_floor = -1, opp_d_max_index;

        int same_d_low_floor = MAX_FLOORS + 1, same_d_low_min_index;
        int opp_d_low_floor = -1, opp_d_low_max_index;

        pair<int, displacement> p;

        for (int i = 0; i < size; i++) {
            p = requests[i];
            if (p.first > current_floor) {
                if (p.second == direction_arrived) {
                    same_d_floor = min(same_d_floor, p.first);
                    same_d_min_index = i;
                } else {
                    opp_d_floor = max(opp_d_floor, p.first);
                    opp_d_max_index = i;
                }
            } else {
                if (p.second != direction_arrived) {
                    opp_d_low_floor = max(opp_d_low_floor, p.first);
                    opp_d_low_max_index = i;
                } else {
                    same_d_low_floor = min(same_d_low_floor, p.first);
                    same_d_low_min_index = i;
                }
            }
        }

        if (same_d_floor != MAX_FLOORS + 1) {
            queue_next_request(requests[same_d_min_index].first);
            eprintf("%s:%s q size %d, next floor %d\n",
                __func__, __FILE__, size, requests[0].first);
            requests.erase(requests.begin() + same_d_min_index);
            return true;
        }

        if (opp_d_floor != MAX_FLOORS + 1) {
            queue_next_request(requests[opp_d_max_index].first);
            eprintf("%s:%s q size %d, next floor %d\n",
                __func__, __FILE__, size, requests[0].first);
            requests.erase(requests.begin() + opp_d_max_index);
            return true;
        }

        if (opp_d_low_floor != - 1) {
            queue_next_request(requests[opp_d_low_max_index].first);
            eprintf("%s:%s q size %d, next floor %d\n",
                __func__, __FILE__, size, requests[0].first);
            requests.erase(requests.begin() + opp_d_low_max_index);
            return true;
        }

        if (same_d_low_floor != - 1) {
            queue_next_request(requests[same_d_low_min_index].first);
            eprintf("%s:%s q size %d, next floor %d\n",
                __func__, __FILE__, size, requests[0].first);
            requests.erase(requests.begin() + same_d_low_min_index);
            return true;
        }

    } else {
        int same_d_floor = -1, same_d_max_index;
        int opp_d_floor = MAX_FLOORS + 1, opp_d_min_index;

        int same_d_high_floor = MAX_FLOORS + 1, same_d_high_min_index;
        int opp_d_high_floor = -1, opp_d_high_max_index;

        pair<int, displacement> p;

        for (int i = 0; i < size; i++) {
            p = requests[i];
            if (p.first < current_floor) {
                if (p.second == direction_arrived) {
                    same_d_floor = max(same_d_floor, p.first);
                    same_d_max_index = i;
                } else {
                    opp_d_floor = min(opp_d_floor, p.first);
                    opp_d_min_index = i;
                }
            } else {
                if (p.second != direction_arrived) {
                    opp_d_high_floor = min(opp_d_high_floor, p.first);
                    opp_d_high_max_index = i;
                } else {
                    same_d_high_floor = max(same_d_high_floor, p.first);
                    same_d_high_min_index = i;
                }
            }
        }

        if (same_d_floor != -1) {
            queue_next_request(requests[same_d_max_index].first);
            eprintf("%s:%s q size %d, next floor %d\n",
                __func__, __FILE__, size, requests[0].first);
            requests.erase(requests.begin() + same_d_max_index);
            return true;
        }

        if (opp_d_floor != -1) {
            queue_next_request(requests[opp_d_min_index].first);
            eprintf("%s:%s q size %d, next floor %d\n",
                __func__, __FILE__, size, requests[0].first);
            requests.erase(requests.begin() + opp_d_min_index);
            return true;
        }

        if (opp_d_high_floor != MAX_FLOORS + 1) {
            queue_next_request(requests[opp_d_high_max_index].first);
            eprintf("%s:%s q size %d, next floor %d\n",
                __func__, __FILE__, size, requests[0].first);
            requests.erase(requests.begin() + opp_d_high_max_index);
            return true;
        }

        if (same_d_high_floor != MAX_FLOORS + 1) {
            queue_next_request(requests[same_d_high_min_index].first);
            eprintf("%s:%s q size %d, next floor %d\n",
                __func__, __FILE__, size, requests[0].first);
            requests.erase(requests.begin() + same_d_high_min_index);
            return true;
        }
    }

    eprintf("%s:%s Error! cannot process queue (%lu)\n",
            __func__, __FILE__, requests.size());
    return false;
}

int Elevator::get_current_floor() {
    pthread_mutex_lock(&elevator_mutex);

    while (elevator_state != READY);
    return current_floor;

    pthread_mutex_unlock(&elevator_mutex);
}

displacement Elevator::get_displacement() {
    pthread_mutex_lock(&elevator_mutex);

    while (elevator_state != READY);
    return direction_arrived;

    pthread_mutex_unlock(&elevator_mutex);
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: WrappedScaleProperty.hxx,v $
 *
 *  $Revision: 1.2 $
 *
 *  last change: $Author: vg $ $Date: 2007-05-22 17:22:52 $
 *
 *  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 CHART_WRAPPED_SCALE_PROPERTY_HXX
#define CHART_WRAPPED_SCALE_PROPERTY_HXX

#include "WrappedProperty.hxx"
#include "Chart2ModelContact.hxx"

#include <boost/shared_ptr.hpp>
#include <vector>

//.............................................................................
namespace chart
{
namespace wrapper
{

class WrappedScaleProperty : public WrappedProperty
{
public:
    enum tScaleProperty
    {
          SCALE_PROP_MAX
        , SCALE_PROP_MIN
        , SCALE_PROP_ORIGIN
        , SCALE_PROP_STEPMAIN
        , SCALE_PROP_STEPHELP
        , SCALE_PROP_AUTO_MAX
        , SCALE_PROP_AUTO_MIN
        , SCALE_PROP_AUTO_ORIGIN
        , SCALE_PROP_AUTO_STEPMAIN
        , SCALE_PROP_AUTO_STEPHELP
        , SCALE_PROP_LOGARITHMIC
    };

public:
    WrappedScaleProperty( tScaleProperty eScaleProperty, ::boost::shared_ptr< Chart2ModelContact > spChart2ModelContact );
    virtual ~WrappedScaleProperty();

    static void addWrappedProperties( std::vector< WrappedProperty* >& rList, ::boost::shared_ptr< Chart2ModelContact > spChart2ModelContact );

    virtual void setPropertyValue( const ::com::sun::star::uno::Any& rOuterValue, const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet >& xInnerPropertySet ) const
                        throw (::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::beans::PropertyVetoException, ::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException);

    virtual ::com::sun::star::uno::Any getPropertyValue( const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet >& xInnerPropertySet ) const
                        throw (::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException);

protected: //methods
    void setPropertyValue( tScaleProperty eScaleProperty, const ::com::sun::star::uno::Any& rOuterValue, const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet >& xInnerPropertySet ) const
                        throw (::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::beans::PropertyVetoException, ::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException);
    ::com::sun::star::uno::Any getPropertyValue( tScaleProperty eScaleProperty, const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet >& xInnerPropertySet ) const
                        throw (::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException);

private: //member
    ::boost::shared_ptr< Chart2ModelContact >   m_spChart2ModelContact;
    tScaleProperty          m_eScaleProperty;

    mutable ::com::sun::star::uno::Any m_aOuterValue;
};

} //  namespace wrapper
} //  namespace chart
//.............................................................................

// CHART_WRAPPED_SCALE_PROPERTY_HXX
#endif
<commit_msg>INTEGRATION: CWS chart14 (1.2.48); FILE MERGED 2007/09/20 11:22:12 iha 1.2.48.1: #i24614# enable reverse scales<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: WrappedScaleProperty.hxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: vg $ $Date: 2007-10-22 16:42:56 $
 *
 *  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 CHART_WRAPPED_SCALE_PROPERTY_HXX
#define CHART_WRAPPED_SCALE_PROPERTY_HXX

#include "WrappedProperty.hxx"
#include "Chart2ModelContact.hxx"

#include <boost/shared_ptr.hpp>
#include <vector>

//.............................................................................
namespace chart
{
namespace wrapper
{

class WrappedScaleProperty : public WrappedProperty
{
public:
    enum tScaleProperty
    {
          SCALE_PROP_MAX
        , SCALE_PROP_MIN
        , SCALE_PROP_ORIGIN
        , SCALE_PROP_STEPMAIN
        , SCALE_PROP_STEPHELP
        , SCALE_PROP_AUTO_MAX
        , SCALE_PROP_AUTO_MIN
        , SCALE_PROP_AUTO_ORIGIN
        , SCALE_PROP_AUTO_STEPMAIN
        , SCALE_PROP_AUTO_STEPHELP
        , SCALE_PROP_LOGARITHMIC
        , SCALE_PROP_REVERSEDIRECTION
    };

public:
    WrappedScaleProperty( tScaleProperty eScaleProperty, ::boost::shared_ptr< Chart2ModelContact > spChart2ModelContact );
    virtual ~WrappedScaleProperty();

    static void addWrappedProperties( std::vector< WrappedProperty* >& rList, ::boost::shared_ptr< Chart2ModelContact > spChart2ModelContact );

    virtual void setPropertyValue( const ::com::sun::star::uno::Any& rOuterValue, const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet >& xInnerPropertySet ) const
                        throw (::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::beans::PropertyVetoException, ::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException);

    virtual ::com::sun::star::uno::Any getPropertyValue( const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet >& xInnerPropertySet ) const
                        throw (::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException);

protected: //methods
    void setPropertyValue( tScaleProperty eScaleProperty, const ::com::sun::star::uno::Any& rOuterValue, const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet >& xInnerPropertySet ) const
                        throw (::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::beans::PropertyVetoException, ::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException);
    ::com::sun::star::uno::Any getPropertyValue( tScaleProperty eScaleProperty, const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet >& xInnerPropertySet ) const
                        throw (::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException);

private: //member
    ::boost::shared_ptr< Chart2ModelContact >   m_spChart2ModelContact;
    tScaleProperty          m_eScaleProperty;

    mutable ::com::sun::star::uno::Any m_aOuterValue;
};

} //  namespace wrapper
} //  namespace chart
//.............................................................................

// CHART_WRAPPED_SCALE_PROPERTY_HXX
#endif
<|endoftext|>