<commit_before>#include "tangram.h"

#include <memory>
#include <utility>
#include <cmath>
#include <set>

#include "platform.h"
#include "tile/tileManager.h"
#include "view/view.h"
#include "data/mapzenVectorTileJson.h"

#include "style/polygonStyle.h"
#include "style/polylineStyle.h"
#include "scene/scene.h"
#include "scene/lights.h"
#include "util/error.h"

namespace Tangram {

std::unique_ptr<TileManager> m_tileManager;
std::shared_ptr<Scene> m_scene;
std::shared_ptr<View> m_view;

static float g_time = 0.0;

void initialize() {

    logMsg("initialize\n");

    // Create view
    if (!m_view) {
        m_view = std::make_shared<View>();

        // Move the view to coordinates in Manhattan so we have something interesting to test
        glm::dvec2 target = m_view->getMapProjection().LonLatToMeters(glm::dvec2(-74.00796, 40.70361));
        m_view->setPosition(target.x, target.y);
    }

    // Create a scene object
    if (!m_scene) {
        m_scene = std::make_shared<Scene>();

        // Load style(s); hard-coded for now
        std::unique_ptr<Style> polyStyle(new PolygonStyle("Polygon"));
        polyStyle->addLayers({
            "buildings",
            "water",
            "earth",
            "landuse"
        });
        m_scene->addStyle(std::move(polyStyle));

        std::unique_ptr<Style> linesStyle(new PolylineStyle("Polyline"));
        linesStyle->addLayers({"roads"});
        m_scene->addStyle(std::move(linesStyle));

        //  Directional light with white diffuse color pointing Northeast and down
        auto directionalLight = std::make_shared<DirectionalLight>("dLight");
        directionalLight->setAmbientColor({0.3, 0.3, 0.3, 1.0});
        directionalLight->setDiffuseColor({0.7, 0.7, 0.7, 1.0});
        directionalLight->setDirection({1.0, 1.0, -1.0});
        m_scene->addLight(directionalLight);

    }

    // Create a tileManager
    if (!m_tileManager) {
        m_tileManager = TileManager::GetInstance();

        // Pass references to the view and scene into the tile manager
        m_tileManager->setView(m_view);
        m_tileManager->setScene(m_scene);

        // Add a tile data source
        std::unique_ptr<DataSource> dataSource(new MapzenVectorTileJson());
        m_tileManager->addDataSource(std::move(dataSource));
    }

    // Set up openGL state
    glDisable(GL_BLEND);
    glDisable(GL_STENCIL_TEST);
    glEnable(GL_DEPTH_TEST);
    glClearDepthf(1.0);
    glDepthRangef(0.0, 1.0);
    glDepthMask(GL_TRUE);
    glDepthFunc(GL_LEQUAL);
    glEnable(GL_CULL_FACE);
    glFrontFace(GL_CCW);
    glCullFace(GL_BACK);
    glClearColor(0.3f, 0.3f, 0.3f, 1.0f);

    while (Error::hadGlError("Tangram::initialize()")) {}

    logMsg("finish initialize\n");

}

void resize(int _newWidth, int _newHeight) {

    logMsg("resize: %d x %d\n", _newWidth, _newHeight);

    glViewport(0, 0, _newWidth, _newHeight);

    if (m_view) {
        m_view->setSize(_newWidth, _newHeight);
    }

    while (Error::hadGlError("Tangram::resize()")) {}

}

void update(float _dt) {

    g_time += _dt;

    if (m_view) {
        m_view->update();
    }

    if (m_tileManager) {
        m_tileManager->updateTileSet();
    }

    if(m_scene) {
        // Update lights and styles
    }
}

void render() {

    // Set up openGL for new frame
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

    // Loop over all styles
    for (const auto& style : m_scene->getStyles()) {

        style->setupFrame(m_scene);

        // Loop over all tiles in m_tileSet
        for (const auto& mapIDandTile : m_tileManager->getVisibleTiles()) {
            const std::shared_ptr<MapTile>& tile = mapIDandTile.second;
            if (tile->hasGeometry()) {
                // Draw tile!
                style->setupTile(tile);
                tile->draw(*style, *m_view);
            }
        }
    }

    while (Error::hadGlError("Tangram::render()")) {}

}

void setPixelScale(float _pixelsPerPoint) {

    if (m_view) {
        m_view->setPixelScale(_pixelsPerPoint);
    }

}

void handleTapGesture(float _posX, float _posY) {

    float dx = m_view->toWorldDistance(_posX - 0.5 * m_view->getWidth());
    float dy = m_view->toWorldDistance(_posY - 0.5 * m_view->getHeight());

    // Flip y displacement to change from screen coordinates to world coordinates
    m_view->translate(dx, -dy);

}

void handleDoubleTapGesture(float _posX, float _posY) {

    m_view->zoom(1.0);
}

void handlePanGesture(float _dX, float _dY) {

    float dx = m_view->toWorldDistance(_dX);
    float dy = m_view->toWorldDistance(_dY);

    // We flip the signs of dx and dy to move the camera in the opposite direction
    // of the intended "world movement", but dy gets flipped once more because screen
    // coordinates have y pointing down and our world coordinates have y pointing up
    m_view->translate(-dx, dy);

}

void handlePinchGesture(float _posX, float _posY, float _scale) {
    m_view->zoom(log2f(_scale));
}

void teardown() {
    // Release resources!
    logMsg("teardown\n");
    m_tileManager.reset();
    m_scene.reset();
    m_view.reset();
}

void onContextDestroyed() {

    logMsg("context destroyed\n");

    // The OpenGL context has been destroyed since the last time resources were created,
    // so we invalidate all data that depends on OpenGL object handles.

    // ShaderPrograms are invalidated and immediately rebuilt
    ShaderProgram::invalidateAllPrograms();

    // Buffer objects are invalidated and re-uploaded the next time they are used
    VboMesh::invalidateAllVBOs();

}

}
<commit_msg>Using protobuf tile sources by default<commit_after>#include "tangram.h"

#include <memory>
#include <utility>
#include <cmath>
#include <set>

#include "platform.h"
#include "tile/tileManager.h"
#include "view/view.h"
#include "data/mapzenVectorTileJson.h"
#include "data/protobufSrc.h"

#include "style/polygonStyle.h"
#include "style/polylineStyle.h"
#include "scene/scene.h"
#include "scene/lights.h"
#include "util/error.h"

namespace Tangram {

std::unique_ptr<TileManager> m_tileManager;
std::shared_ptr<Scene> m_scene;
std::shared_ptr<View> m_view;

static float g_time = 0.0;

void initialize() {

    logMsg("initialize\n");

    // Create view
    if (!m_view) {
        m_view = std::make_shared<View>();

        // Move the view to coordinates in Manhattan so we have something interesting to test
        glm::dvec2 target = m_view->getMapProjection().LonLatToMeters(glm::dvec2(-74.00796, 40.70361));
        m_view->setPosition(target.x, target.y);
    }

    // Create a scene object
    if (!m_scene) {
        m_scene = std::make_shared<Scene>();

        // Load style(s); hard-coded for now
        std::unique_ptr<Style> polyStyle(new PolygonStyle("Polygon"));
        polyStyle->addLayers({
            "buildings",
            "water",
            "earth",
            "landuse"
        });
        m_scene->addStyle(std::move(polyStyle));

        std::unique_ptr<Style> linesStyle(new PolylineStyle("Polyline"));
        linesStyle->addLayers({"roads"});
        m_scene->addStyle(std::move(linesStyle));

        //  Directional light with white diffuse color pointing Northeast and down
        auto directionalLight = std::make_shared<DirectionalLight>("dLight");
        directionalLight->setAmbientColor({0.3, 0.3, 0.3, 1.0});
        directionalLight->setDiffuseColor({0.7, 0.7, 0.7, 1.0});
        directionalLight->setDirection({1.0, 1.0, -1.0});
        m_scene->addLight(directionalLight);

    }

    // Create a tileManager
    if (!m_tileManager) {
        m_tileManager = TileManager::GetInstance();

        // Pass references to the view and scene into the tile manager
        m_tileManager->setView(m_view);
        m_tileManager->setScene(m_scene);

        // Add a tile data source
        // json tile source
        std::unique_ptr<DataSource> dataSource(new MapzenVectorTileJson());
        // protobuf tile source
        //std::unique_ptr<DataSource> dataSource(new MapboxProtoBuffSrc());
        m_tileManager->addDataSource(std::move(dataSource));
    }

    // Set up openGL state
    glDisable(GL_BLEND);
    glDisable(GL_STENCIL_TEST);
    glEnable(GL_DEPTH_TEST);
    glClearDepthf(1.0);
    glDepthRangef(0.0, 1.0);
    glDepthMask(GL_TRUE);
    glDepthFunc(GL_LEQUAL);
    glEnable(GL_CULL_FACE);
    glFrontFace(GL_CCW);
    glCullFace(GL_BACK);
    glClearColor(0.3f, 0.3f, 0.3f, 1.0f);

    while (Error::hadGlError("Tangram::initialize()")) {}

    logMsg("finish initialize\n");

}

void resize(int _newWidth, int _newHeight) {

    logMsg("resize: %d x %d\n", _newWidth, _newHeight);

    glViewport(0, 0, _newWidth, _newHeight);

    if (m_view) {
        m_view->setSize(_newWidth, _newHeight);
    }

    while (Error::hadGlError("Tangram::resize()")) {}

}

void update(float _dt) {

    g_time += _dt;

    if (m_view) {
        m_view->update();
    }

    if (m_tileManager) {
        m_tileManager->updateTileSet();
    }

    if(m_scene) {
        // Update lights and styles
    }
}

void render() {

    // Set up openGL for new frame
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

    // Loop over all styles
    for (const auto& style : m_scene->getStyles()) {

        style->setupFrame(m_scene);

        // Loop over all tiles in m_tileSet
        for (const auto& mapIDandTile : m_tileManager->getVisibleTiles()) {
            const std::shared_ptr<MapTile>& tile = mapIDandTile.second;
            if (tile->hasGeometry()) {
                // Draw tile!
                style->setupTile(tile);
                tile->draw(*style, *m_view);
            }
        }
    }

    while (Error::hadGlError("Tangram::render()")) {}

}

void setPixelScale(float _pixelsPerPoint) {

    if (m_view) {
        m_view->setPixelScale(_pixelsPerPoint);
    }

}

void handleTapGesture(float _posX, float _posY) {

    float dx = m_view->toWorldDistance(_posX - 0.5 * m_view->getWidth());
    float dy = m_view->toWorldDistance(_posY - 0.5 * m_view->getHeight());

    // Flip y displacement to change from screen coordinates to world coordinates
    m_view->translate(dx, -dy);

}

void handleDoubleTapGesture(float _posX, float _posY) {

    m_view->zoom(1.0);
}

void handlePanGesture(float _dX, float _dY) {

    float dx = m_view->toWorldDistance(_dX);
    float dy = m_view->toWorldDistance(_dY);

    // We flip the signs of dx and dy to move the camera in the opposite direction
    // of the intended "world movement", but dy gets flipped once more because screen
    // coordinates have y pointing down and our world coordinates have y pointing up
    m_view->translate(-dx, dy);

}

void handlePinchGesture(float _posX, float _posY, float _scale) {
    m_view->zoom(log2f(_scale));
}

void teardown() {
    // Release resources!
    logMsg("teardown\n");
    m_tileManager.reset();
    m_scene.reset();
    m_view.reset();
}

void onContextDestroyed() {

    logMsg("context destroyed\n");

    // The OpenGL context has been destroyed since the last time resources were created,
    // so we invalidate all data that depends on OpenGL object handles.

    // ShaderPrograms are invalidated and immediately rebuilt
    ShaderProgram::invalidateAllPrograms();

    // Buffer objects are invalidated and re-uploaded the next time they are used
    VboMesh::invalidateAllVBOs();

}

}
<|endoftext|>


<commit_before>#pragma once

#include <algorithm>
#include <complex>
#include <iostream>
#include <queue>
#include <string>
#include <vector>

using namespace std;

using ll = long long;
using ld = long double;

template<typename T> T inf;
template<> constexpr int inf<int> = 1e9;
template<> constexpr ll inf<ll> = 1e18;
template<> constexpr ld inf<ld> = 1e30;
<commit_msg>add more includes<commit_after>#pragma once

#include <algorithm>
#include <complex>
#include <cstdio>
#include <cstring>
#include <iostream>
#include <queue>
#include <string>
#include <vector>

using namespace std;

using ll = long long;
using ld = long double;

template<typename T> T inf;
template<> constexpr int inf<int> = 1e9;
template<> constexpr ll inf<ll> = 1e18;
template<> constexpr ld inf<ld> = 1e30;
<|endoftext|>


<commit_before>/** \file rss_harvester.cc
 *  \brief Downloads and evaluates RSS updates.
 *  \author Dr. Johannes Ruscheinski (johannes.ruscheinski@uni-tuebingen.de)
 *
 *  \copyright 2018 Universitätsbibliothek Tübingen.  All rights reserved.
 *
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU Affero General Public License as
 *  published by the Free Software Foundation, either version 3 of the
 *  License, or (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU Affero General Public License for more details.
 *
 *  You should have received a copy of the GNU Affero General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
#include <iostream>
#include <cstring>
#include "DbConnection.h"
#include "DbResultSet.h"
#include "Downloader.h"
#include "FileUtil.h"
#include "IniFile.h"
#include "SyndicationFormat.h"
#include "util.h"
#include "Zotero.h"

namespace {

[[noreturn]] void Usage() {
    std::cerr << "Usage: " << ::progname
              << " [--verbose] [--proxy=<proxy_host_and_port>] rss_url_list_filename zts_server_url map_directory marc_output\n";
    std::exit(EXIT_FAILURE);
}

unsigned ProcessSyndicationURL(const bool verbose, const std::string &url,
                               const std::shared_ptr<Zotero::HarvestParams> harvest_params,
                               const std::shared_ptr<const Zotero::HarvestMaps> harvest_maps,
                               DbConnection * const db_connection)
{
    unsigned successfully_processed_count(0);

    if (verbose)
        std::cerr << "Processing URL: " << url << '\n';

    Downloader downloader(url);
    if (downloader.anErrorOccurred()) {
        WARNING("Download problem for \"" + url + "\": " + downloader.getLastErrorMessage());
        return successfully_processed_count;
    }

    std::string err_msg;
    std::unique_ptr<SyndicationFormat> syndication_format(SyndicationFormat::Factory(downloader.getMessageBody(), &err_msg));
    if (syndication_format == nullptr) {
        WARNING("Problem parsing XML document for \"" + url + "\": " + err_msg);
        return successfully_processed_count;
    }

    std::cout << url << " (" << syndication_format->getFormatName() << "):\n";
    if (verbose) {
        std::cout << "\tTitle: " << syndication_format->getTitle() << '\n';
        std::cout << "\tLink: " << syndication_format->getLink() << '\n';
        std::cout << "\tDescription: " << syndication_format->getDescription() << '\n';
    }

    for (const auto &item : *syndication_format) {
        db_connection->queryOrDie("SELECT creation_datetime FROM rss WHERE server_url='" + db_connection->escapeString(url)
                                  + "' AND item_id='" + db_connection->escapeString(item.getId()) + "'");
        DbResultSet result_set(db_connection->getLastResultSet());
        if (not result_set.empty()) {
            if (verbose) {
                const DbRow first_row(result_set.getNextRow());
                std::cout << "Previously retrieved item w/ ID \"" << item.getId() + "\" at " << first_row["creation_datetime"]
                          << ".\n";
            }
            continue;
        }

        const std::string title(item.getTitle());
        if (not title.empty() and verbose)
            std::cout << "\t\tTitle: " << title << '\n';
        const std::unordered_map<std::string, std::string> &dc_and_prism_data(item.getDCAndPrismData());
        if (dc_and_prism_data.empty()) {
            const auto record_count_and_previously_downloaded_count(
                Zotero::Harvest(item.getLink(), "", harvest_params, harvest_maps));
            successfully_processed_count += record_count_and_previously_downloaded_count.first;
        }

        db_connection->queryOrDie("INSERT INTO rss SET server_url='" + db_connection->escapeString(url) + "',item_id='"
                                  + db_connection->escapeString(item.getId()) + "'");

    }

    return successfully_processed_count;
}

void LoadServerURLs(const std::string &path, std::vector<std::string> * const server_urls) {
    std::unique_ptr<File> input(FileUtil::OpenInputFileOrDie(path));
    while (not input->eof()) {
        std::string line;
        input->getline(&line);
        StringUtil::TrimWhite(&line);
        if (not line.empty())
            server_urls->emplace_back(line);
    }
}

std::string GetMarcFormat(const std::string &output_filename) {
    if (StringUtil::EndsWith(output_filename, ".mrc") or StringUtil::EndsWith(output_filename, ".marc"))
        return "marc21";
    if (StringUtil::EndsWith(output_filename, ".xml"))
        return "marcxml";
    ERROR("can't determine output format from MARC output filename \"" + output_filename + "\"!");
}

const std::string CONF_FILE_PATH("/usr/local/var/lib/tuelib/rss_client.conf");

} // unnamed namespace

int main(int argc, char *argv[]) {
    ::progname = argv[0];

    if (argc < 5)
        Usage();

    bool verbose(false);
    if (std::strcmp(argv[1], "--verbose") == 0) {
        verbose = true;
        --argc, ++argv;
    }

    std::string proxy_host_and_port;
    const std::string PROXY_FLAG_PREFIX("--proxy=");
    if (StringUtil::StartsWith(argv[1], PROXY_FLAG_PREFIX)) {
        proxy_host_and_port = argv[1] + PROXY_FLAG_PREFIX.length();
        --argc, ++argv;
    }

    if (argc != 5)
        Usage();

    try {
        std::vector<std::string> server_urls;
        LoadServerURLs(argv[1], &server_urls);

        std::shared_ptr<Zotero::HarvestParams> harvest_params(new Zotero::HarvestParams);
        harvest_params->zts_server_url_ = Url(argv[2]);

        std::string map_directory_path(argv[3]);
        if (not StringUtil::EndsWith(map_directory_path, '/'))
            map_directory_path += '/';

        std::shared_ptr<Zotero::HarvestMaps> harvest_maps(Zotero::LoadMapFilesFromDirectory(map_directory_path));
        const std::shared_ptr<RegexMatcher> supported_urls_regex(Zotero::LoadSupportedURLsRegex(map_directory_path));

        const std::string PREVIOUSLY_DOWNLOADED_HASHES_PATH(map_directory_path + "previously_downloaded.hashes");
        Zotero::PreviouslyDownloadedHashesManager previously_downloaded_hashes_manager(PREVIOUSLY_DOWNLOADED_HASHES_PATH,
                                                                                &harvest_maps->previously_downloaded_);
        const std::string MARC_OUTPUT_FILE(argv[4]);
        harvest_params->format_handler_ = Zotero::FormatHandler::Factory(GetMarcFormat(MARC_OUTPUT_FILE), MARC_OUTPUT_FILE,
                                                                         harvest_maps, harvest_params);

        const IniFile ini_file(CONF_FILE_PATH);
        const std::string sql_database(ini_file.getString("Database", "sql_database"));
        const std::string sql_username(ini_file.getString("Database", "sql_username"));
        const std::string sql_password(ini_file.getString("Database", "sql_password"));
        DbConnection db_connection(sql_database, sql_username, sql_password);

        harvest_params->format_handler_->prepareProcessing();

        unsigned download_count(0);
        for (const auto &server_url : server_urls)
            download_count += ProcessSyndicationURL(verbose, server_url, harvest_params, harvest_maps, &db_connection);

        harvest_params->format_handler_->finishProcessing();

        logger->info("Extracted metadata from " + std::to_string(download_count) + " pages.");
    } catch (const std::exception &x) {
        ERROR("caught exception: " + std::string(x.what()));
    }

}
<commit_msg>Added an error if we get the metadata on a platter.<commit_after>/** \file rss_harvester.cc
 *  \brief Downloads and evaluates RSS updates.
 *  \author Dr. Johannes Ruscheinski (johannes.ruscheinski@uni-tuebingen.de)
 *
 *  \copyright 2018 Universitätsbibliothek Tübingen.  All rights reserved.
 *
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU Affero General Public License as
 *  published by the Free Software Foundation, either version 3 of the
 *  License, or (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU Affero General Public License for more details.
 *
 *  You should have received a copy of the GNU Affero General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
#include <iostream>
#include <cstring>
#include "DbConnection.h"
#include "DbResultSet.h"
#include "Downloader.h"
#include "FileUtil.h"
#include "IniFile.h"
#include "SyndicationFormat.h"
#include "util.h"
#include "Zotero.h"

namespace {

[[noreturn]] void Usage() {
    std::cerr << "Usage: " << ::progname
              << " [--verbose] [--proxy=<proxy_host_and_port>] rss_url_list_filename zts_server_url map_directory marc_output\n";
    std::exit(EXIT_FAILURE);
}

unsigned ProcessSyndicationURL(const bool verbose, const std::string &url,
                               const std::shared_ptr<Zotero::HarvestParams> harvest_params,
                               const std::shared_ptr<const Zotero::HarvestMaps> harvest_maps,
                               DbConnection * const db_connection)
{
    unsigned successfully_processed_count(0);

    if (verbose)
        std::cerr << "Processing URL: " << url << '\n';

    Downloader downloader(url);
    if (downloader.anErrorOccurred()) {
        WARNING("Download problem for \"" + url + "\": " + downloader.getLastErrorMessage());
        return successfully_processed_count;
    }

    std::string err_msg;
    std::unique_ptr<SyndicationFormat> syndication_format(SyndicationFormat::Factory(downloader.getMessageBody(), &err_msg));
    if (syndication_format == nullptr) {
        WARNING("Problem parsing XML document for \"" + url + "\": " + err_msg);
        return successfully_processed_count;
    }

    std::cout << url << " (" << syndication_format->getFormatName() << "):\n";
    if (verbose) {
        std::cout << "\tTitle: " << syndication_format->getTitle() << '\n';
        std::cout << "\tLink: " << syndication_format->getLink() << '\n';
        std::cout << "\tDescription: " << syndication_format->getDescription() << '\n';
    }

    for (const auto &item : *syndication_format) {
        db_connection->queryOrDie("SELECT creation_datetime FROM rss WHERE server_url='" + db_connection->escapeString(url)
                                  + "' AND item_id='" + db_connection->escapeString(item.getId()) + "'");
        DbResultSet result_set(db_connection->getLastResultSet());
        if (not result_set.empty()) {
            if (verbose) {
                const DbRow first_row(result_set.getNextRow());
                std::cout << "Previously retrieved item w/ ID \"" << item.getId() + "\" at " << first_row["creation_datetime"]
                          << ".\n";
            }
            continue;
        }

        const std::string title(item.getTitle());
        if (not title.empty() and verbose)
            std::cout << "\t\tTitle: " << title << '\n';
        const std::unordered_map<std::string, std::string> &dc_and_prism_data(item.getDCAndPrismData());
        if (dc_and_prism_data.empty()) {
            const auto record_count_and_previously_downloaded_count(
                Zotero::Harvest(item.getLink(), "", harvest_params, harvest_maps));
            successfully_processed_count += record_count_and_previously_downloaded_count.first;
        } else
            ERROR("create a MARC record from the RSS DC and PRISM metadata!");

        db_connection->queryOrDie("INSERT INTO rss SET server_url='" + db_connection->escapeString(url) + "',item_id='"
                                  + db_connection->escapeString(item.getId()) + "'");

    }

    return successfully_processed_count;
}

void LoadServerURLs(const std::string &path, std::vector<std::string> * const server_urls) {
    std::unique_ptr<File> input(FileUtil::OpenInputFileOrDie(path));
    while (not input->eof()) {
        std::string line;
        input->getline(&line);
        StringUtil::TrimWhite(&line);
        if (not line.empty())
            server_urls->emplace_back(line);
    }
}

std::string GetMarcFormat(const std::string &output_filename) {
    if (StringUtil::EndsWith(output_filename, ".mrc") or StringUtil::EndsWith(output_filename, ".marc"))
        return "marc21";
    if (StringUtil::EndsWith(output_filename, ".xml"))
        return "marcxml";
    ERROR("can't determine output format from MARC output filename \"" + output_filename + "\"!");
}

const std::string CONF_FILE_PATH("/usr/local/var/lib/tuelib/rss_client.conf");

} // unnamed namespace

int main(int argc, char *argv[]) {
    ::progname = argv[0];

    if (argc < 5)
        Usage();

    bool verbose(false);
    if (std::strcmp(argv[1], "--verbose") == 0) {
        verbose = true;
        --argc, ++argv;
    }

    std::string proxy_host_and_port;
    const std::string PROXY_FLAG_PREFIX("--proxy=");
    if (StringUtil::StartsWith(argv[1], PROXY_FLAG_PREFIX)) {
        proxy_host_and_port = argv[1] + PROXY_FLAG_PREFIX.length();
        --argc, ++argv;
    }

    if (argc != 5)
        Usage();

    try {
        std::vector<std::string> server_urls;
        LoadServerURLs(argv[1], &server_urls);

        std::shared_ptr<Zotero::HarvestParams> harvest_params(new Zotero::HarvestParams);
        harvest_params->zts_server_url_ = Url(argv[2]);

        std::string map_directory_path(argv[3]);
        if (not StringUtil::EndsWith(map_directory_path, '/'))
            map_directory_path += '/';

        std::shared_ptr<Zotero::HarvestMaps> harvest_maps(Zotero::LoadMapFilesFromDirectory(map_directory_path));
        const std::shared_ptr<RegexMatcher> supported_urls_regex(Zotero::LoadSupportedURLsRegex(map_directory_path));

        const std::string PREVIOUSLY_DOWNLOADED_HASHES_PATH(map_directory_path + "previously_downloaded.hashes");
        Zotero::PreviouslyDownloadedHashesManager previously_downloaded_hashes_manager(PREVIOUSLY_DOWNLOADED_HASHES_PATH,
                                                                                &harvest_maps->previously_downloaded_);
        const std::string MARC_OUTPUT_FILE(argv[4]);
        harvest_params->format_handler_ = Zotero::FormatHandler::Factory(GetMarcFormat(MARC_OUTPUT_FILE), MARC_OUTPUT_FILE,
                                                                         harvest_maps, harvest_params);

        const IniFile ini_file(CONF_FILE_PATH);
        const std::string sql_database(ini_file.getString("Database", "sql_database"));
        const std::string sql_username(ini_file.getString("Database", "sql_username"));
        const std::string sql_password(ini_file.getString("Database", "sql_password"));
        DbConnection db_connection(sql_database, sql_username, sql_password);

        harvest_params->format_handler_->prepareProcessing();

        unsigned download_count(0);
        for (const auto &server_url : server_urls)
            download_count += ProcessSyndicationURL(verbose, server_url, harvest_params, harvest_maps, &db_connection);

        harvest_params->format_handler_->finishProcessing();

        logger->info("Extracted metadata from " + std::to_string(download_count) + " pages.");
    } catch (const std::exception &x) {
        ERROR("caught exception: " + std::string(x.what()));
    }

}
<|endoftext|>


<commit_before>//=======================================================================
// Copyright Baptiste Wicht 2011.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
//  http://www.boost.org/LICENSE_1_0.txt)
//=======================================================================

#include <iostream>
#include <cstdio>

#include "Timer.hpp"
#include "Options.hpp"
#include "StringPool.hpp"
#include "Variables.hpp"
#include "Compiler.hpp"
#include "Nodes.hpp"
#include "Parser.hpp"

using std::string;
using std::cout;
using std::endl;

using namespace eddic;

void execCommand(string command);

int Compiler::compile(string file) {
    cout << "Compile " << file << endl;

    Timer timer;

    string output = Options::get(OUTPUT);

    int code = 0;
    try {
        lexer.lex(file);

        Parser parser(lexer);

        Program* program = parser.parse();

        Variables variables;
        StringPool* pool = new StringPool();

        //Semantical analysis
        check(program, variables);
        checkStrings(program, *pool);

        //Optimize the parse tree
        program->optimize();

        writer.open("output.asm");
        compile(program, *pool);

        variables.write(writer);

        delete program;
        delete pool;

        string asCommand = "as --32 -o output.o output.asm";

        execCommand(asCommand);

        string ldCommand = "ld -m elf_i386 -s -o ";
        ldCommand += output;
        ldCommand += " output.o";

        execCommand(ldCommand);

        //Remove temporary files
        remove("output.asm");
        remove("output.o");
    } catch (CompilerException e) {
        cout << e.what() << endl;
        code = 1;
    }

    lexer.close();
    writer.close();

    if(code != 0) {
        remove(output.c_str());
    }

    cout << "Compilation took " << timer.elapsed() << "ms" << endl;

    return code;
}

void execCommand(string command) {
    char buffer[1024];

    FILE* stream = popen(command.c_str(), "r");

    while(fgets(buffer, 1024, stream) != NULL) {
        cout << buffer;
    }

    pclose(stream);
}

void Compiler::compile(Program* program, StringPool& pool) {
    writer.writeHeader();

    program->write(writer);

    writer.writeEnd();

    pool.write(writer);
}

void Compiler::check(Program* program, Variables& variables) {
    NodeIterator it = program->begin();
    NodeIterator end = program->end();

    for( ; it != end; ++it) {
        ParseNode* node = *it;

        node->checkVariables(variables);
    }
}

void Compiler::checkStrings(Program* program, StringPool& pool) {
    NodeIterator it = program->begin();
    NodeIterator end = program->end();

    for( ; it != end; ++it) {
        ParseNode* node = *it;

        node->checkStrings(pool);
    }
}
<commit_msg>Link with libc in order to have malloc usable from the assembly<commit_after>//=======================================================================
// Copyright Baptiste Wicht 2011.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
//  http://www.boost.org/LICENSE_1_0.txt)
//=======================================================================

#include <iostream>
#include <cstdio>

#include "Timer.hpp"
#include "Options.hpp"
#include "StringPool.hpp"
#include "Variables.hpp"
#include "Compiler.hpp"
#include "Nodes.hpp"
#include "Parser.hpp"

using std::string;
using std::cout;
using std::endl;

using namespace eddic;

void execCommand(string command);

int Compiler::compile(string file) {
    cout << "Compile " << file << endl;

    Timer timer;

    string output = Options::get(OUTPUT);

    int code = 0;
    try {
        lexer.lex(file);

        Parser parser(lexer);

        Program* program = parser.parse();

        Variables variables;
        StringPool* pool = new StringPool();

        //Semantical analysis
        check(program, variables);
        checkStrings(program, *pool);

        //Optimize the parse tree
        program->optimize();

        writer.open("output.asm");
        compile(program, *pool);

        variables.write(writer);

        delete program;
        delete pool;

        string asCommand = "as --32 -o output.o output.asm";

        execCommand(asCommand);

        string ldCommand = "ld -static -m elf_i386 -o ";
        ldCommand += output;
        ldCommand += " output.o -lc";

        execCommand(ldCommand);

        //Remove temporary files
        remove("output.asm");
        remove("output.o");
    } catch (CompilerException e) {
        cout << e.what() << endl;
        code = 1;
    }

    lexer.close();
    writer.close();

    if(code != 0) {
        remove(output.c_str());
    }

    cout << "Compilation took " << timer.elapsed() << "ms" << endl;

    return code;
}

void execCommand(string command) {
    cout << "Exec command : " << command << endl;

    char buffer[1024];

    FILE* stream = popen(command.c_str(), "r");

    while(fgets(buffer, 1024, stream) != NULL) {
        cout << buffer;
    }

    pclose(stream);
}

void Compiler::compile(Program* program, StringPool& pool) {
    writer.writeHeader();

    program->write(writer);

    writer.writeEnd();

    pool.write(writer);
}

void Compiler::check(Program* program, Variables& variables) {
    NodeIterator it = program->begin();
    NodeIterator end = program->end();

    for( ; it != end; ++it) {
        ParseNode* node = *it;

        node->checkVariables(variables);
    }
}

void Compiler::checkStrings(Program* program, StringPool& pool) {
    NodeIterator it = program->begin();
    NodeIterator end = program->end();

    for( ; it != end; ++it) {
        ParseNode* node = *it;

        node->checkStrings(pool);
    }
}
<|endoftext|>


<commit_before>#include "Contract.hpp"

#ifdef __ABI_ENABLED__

namespace Ethereum{namespace Connector{

Contract::Contract(Provider &provider, const std::string &address) :
    Base(address, ContractInvoker(provider))
{}

ContractInvoker::ContractInvoker(Provider &provider) :
    _provider(provider)
{}

std::string ContractInvoker::execute(const std::string &to, const std::string &code)
{
    return execute(getDefaultAddress(), to, code);
}

std::string ContractInvoker::execute(const std::string &from, const std::string &to, const std::string &code)
{
    GasEstimator estimator(_provider);
    BigInt gas = estimator.estimate(from, to, BigInt(0), code);
    Json::Value result = _provider.request("eth_sendTransaction", TransactionParamsFactory::makeParams(from.c_str(), to.c_str(), BigInt(0), code.c_str(), gas, 0));
    return result.asString();
}

std::string ContractInvoker::execute(const std::string &to, const std::string &code, const BigInt &gas)
{
    return execute(getDefaultAddress(), to, code, gas);
}

std::string ContractInvoker::execute(const std::string &from, const std::string &to, const std::string &code, const BigInt &gas)
{
    Json::Value result = _provider.request("eth_sendTransaction", TransactionParamsFactory::makeParams(from.c_str(), to.c_str(), BigInt(0), code.c_str(), gas, 0));
    return result.asString();
}

std::string ContractInvoker::call(const std::string &to, const std::string &code)
{
    return call(getDefaultAddress(), to, code);
}

std::string ContractInvoker::call(const std::string &from, const std::string &to, const std::string &code)
{
    Json::Value result = _provider.request("eth_call", TransactionParamsFactory::makeParams(from.c_str(), to.c_str(), BigInt(0), code.c_str(), 0));
    return result.asString();
}

std::string ContractInvoker::getDefaultAddress()
{
    Json::Value result = _provider.request("eth_coinbase");
    return result.asString();
}

}}

#endif
<commit_msg>simplified contract class<commit_after>#include "Contract.hpp"

#ifdef __ABI_ENABLED__

namespace Ethereum{namespace Connector{

Contract::Contract(Provider &provider, const std::string &address) :
    Base(address, ContractInvoker(provider))
{}

void Contract::setSenderAddress(const std::string &sender)
{
    getInvoker().setSenderAddress(sender);
}

ContractInvoker::ContractInvoker(Provider &provider) :
    _provider(provider)
{}

void ContractInvoker::setSenderAddress(const std::string &sender)
{
    _sender = sender;
}

std::string ContractInvoker::execute(const std::string &from, const std::string &to, const std::string &code)
{
    GasEstimator estimator(_provider);
    BigInt gas = estimator.estimate(from, to, BigInt(0), code);
    Json::Value result = _provider.request("eth_sendTransaction", TransactionParamsFactory::makeParams(from.c_str(), to.c_str(), BigInt(0), code.c_str(), gas, 0));
    return result.asString();
}

std::string ContractInvoker::execute(const std::string &to, const std::string &code)
{
    return execute(_sender.size()?_sender:getDefaultAddress(), to, code);
}

std::string ContractInvoker::call(const std::string &to, const std::string &code)
{
    return call(_sender.size()?_sender:getDefaultAddress(), to, code);
}

std::string ContractInvoker::call(const std::string &from, const std::string &to, const std::string &code)
{
    Json::Value result = _provider.request("eth_call", TransactionParamsFactory::makeParams(from.c_str(), to.c_str(), BigInt(0), code.c_str(), 0));
    return result.asString();
}

std::string ContractInvoker::getDefaultAddress()
{
    Json::Value result = _provider.request("eth_coinbase");
    return result.asString();
}

}}

#endif
<|endoftext|>


<commit_before>/*The MIT License (MIT)

Copyright (c) 2015 k-brac

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

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

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

#include <string>
#include <vector>
#include <iostream>

#ifdef WIN32
#pragma warning( push )
#pragma warning( disable : 4251 )
#endif

#if __MACH__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wpadded"
#pragma clang diagnostic ignored "-Wweak-vtables"
#pragma clang diagnostic ignored "-Wextra-semi"
#pragma clang diagnostic ignored "-Wdocumentation"
#pragma clang diagnostic ignored "-Wreserved-id-macro"
#pragma clang diagnostic ignored "-Wdocumentation-unknown-command"
#define CPPUNIT_STD_NEED_ALLOCATOR 0
#endif

#include "cppunit/extensions/TestFactoryRegistry.h"
#include "cppunit/CompilerOutputter.h"
#include "cppunit/XmlOutputter.h"
#include "cppunit/TestResult.h"
#include "cppunit/TestResultCollector.h"
#include "cppunit/TestRunner.h"
#include "cppunit/BriefTestProgressListener.h"
#include "cppunit/plugin/PlugInManager.h"
#include <chrono>

class TimedBriefTestProgressListener : public CppUnit::BriefTestProgressListener {
private:
    std::chrono::time_point<std::chrono::high_resolution_clock> mTimer;
public:

    void startTest(CppUnit::Test *test)
    {
        CppUnit::BriefTestProgressListener::startTest(test);
        mTimer = std::chrono::high_resolution_clock::now();
    }

    void endTest(CppUnit::Test *test)
    {
        const std::chrono::duration<float, std::milli> elapsed = std::chrono::high_resolution_clock::now() - mTimer;
        CppUnit::stdCOut() << " (" << std::to_string(elapsed.count()) << " ms elapsed)";
#if defined(WIN32)
        CppUnit::stdCOut().flush();
#endif
        CppUnit::BriefTestProgressListener::endTest(test);
    }
};

#if __MACH__
#pragma clang diagnostic pop
#endif

#ifdef WIN32
#pragma warning( pop )
#endif

struct CommandLineParser {
    std::string xmlOutputFile;
    std::string plugName;
    std::vector<std::string> testPaths;

    void parseArgs(int argc, char* argv[]) {
        for (int i = 1; i < argc; i++) {
            std::string arg = argv[i];
            if (arg.size() >= 2 && arg.front() == '-') {
                auto it = arg.find("=");
                if (it != std::string::npos) {
                    auto key = arg.substr(0, it);
                    auto val = arg.substr(it + 1, arg.size());
                    if (val.empty()) {
                        continue;
                    }
                    if (key == "-x" || key == "--xml") {
                        xmlOutputFile = val;
                    }
                    else if (key == "-t" || key == "--test") {
                        testPaths.emplace_back(val);
                    }
                    else {
                        std::cerr << "Unknow arguments " << key << " with value : " << val << std::endl;
                    }
                }
            }
            else {
                plugName = arg;
            }
        }

    }
};

bool runPlugin(const CommandLineParser &arguments) {
	CppUnit::PlugInManager pluginManager;
	pluginManager.load(arguments.plugName);

	// Create the event manager and test controller
	CppUnit::TestResult controller;

	// Add a listener that collects test result
	CppUnit::TestResultCollector result;
	controller.addListener(&result);

	// Add a listener
    TimedBriefTestProgressListener progress;
	controller.addListener(&progress);

	pluginManager.addListener(&controller);

	// Add the top suite to the test runner
	CppUnit::TestRunner runner;
	runner.addTest(CppUnit::TestFactoryRegistry::getRegistry().makeTest());
	try
	{
		if (arguments.testPaths.empty()) {
			std::cout << "Running " << std::endl;
			runner.run(controller);
		}
		else {
			for (const auto & p : arguments.testPaths) {
				std::cout << "Running " << p << std::endl;
				runner.run(controller, p);
			}
		}
		std::cerr << std::endl;

		// Print test in a compiler compatible format.
		CppUnit::CompilerOutputter outputter(&result, std::cerr);
		outputter.write();

        if (!arguments.xmlOutputFile.empty()) {
            std::ofstream file(arguments.xmlOutputFile);
            CppUnit::XmlOutputter xOutputter(&result, file);
            xOutputter.write();
        }
	}
	catch (std::invalid_argument &e)  // Test path not resolved
	{
		std::cerr << std::endl
			<< "ERROR: " << e.what()
			<< std::endl;
		return false;
	}
	return result.wasSuccessful();
}

int main(int argc, char* argv[])
{
	std::cout << "usage : " << argv[0] << "{-x | -xml=file} {-t | --test=test_path} test_plugin_path" << std::endl << std::endl;
	if (argc < 2)
		return 1;

	bool result = false;
	try {
        CommandLineParser command;
        command.parseArgs(argc, argv);
		result = runPlugin(command);
	}
	catch (std::exception &e) {
		std::cerr << std::endl
			<< "ERROR: " << e.what()
			<< std::endl;

	}
	return result ? 0 : 1;
}
<commit_msg>internal: explained command line syntax's slightly more explicitly in help<commit_after>/*The MIT License (MIT)

Copyright (c) 2015 k-brac

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

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

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

#include <string>
#include <vector>
#include <iostream>

#ifdef WIN32
#pragma warning( push )
#pragma warning( disable : 4251 )
#endif

#if __MACH__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wpadded"
#pragma clang diagnostic ignored "-Wweak-vtables"
#pragma clang diagnostic ignored "-Wextra-semi"
#pragma clang diagnostic ignored "-Wdocumentation"
#pragma clang diagnostic ignored "-Wreserved-id-macro"
#pragma clang diagnostic ignored "-Wdocumentation-unknown-command"
#define CPPUNIT_STD_NEED_ALLOCATOR 0
#endif

#include "cppunit/extensions/TestFactoryRegistry.h"
#include "cppunit/CompilerOutputter.h"
#include "cppunit/XmlOutputter.h"
#include "cppunit/TestResult.h"
#include "cppunit/TestResultCollector.h"
#include "cppunit/TestRunner.h"
#include "cppunit/BriefTestProgressListener.h"
#include "cppunit/plugin/PlugInManager.h"
#include <chrono>

class TimedBriefTestProgressListener : public CppUnit::BriefTestProgressListener {
private:
    std::chrono::time_point<std::chrono::high_resolution_clock> mTimer;
public:

    void startTest(CppUnit::Test *test)
    {
        CppUnit::BriefTestProgressListener::startTest(test);
        mTimer = std::chrono::high_resolution_clock::now();
    }

    void endTest(CppUnit::Test *test)
    {
        const std::chrono::duration<float, std::milli> elapsed = std::chrono::high_resolution_clock::now() - mTimer;
        CppUnit::stdCOut() << " (" << std::to_string(elapsed.count()) << " ms elapsed)";
#if defined(WIN32)
        CppUnit::stdCOut().flush();
#endif
        CppUnit::BriefTestProgressListener::endTest(test);
    }
};

#if __MACH__
#pragma clang diagnostic pop
#endif

#ifdef WIN32
#pragma warning( pop )
#endif

struct CommandLineParser {
    std::string xmlOutputFile;
    std::string plugName;
    std::vector<std::string> testPaths;

    void parseArgs(int argc, char* argv[]) {
        for (int i = 1; i < argc; i++) {
            std::string arg = argv[i];
            if (arg.size() >= 2 && arg.front() == '-') {
                auto it = arg.find("=");
                if (it != std::string::npos) {
                    auto key = arg.substr(0, it);
                    auto val = arg.substr(it + 1, arg.size());
                    if (val.empty()) {
                        continue;
                    }
                    if (key == "-x" || key == "--xml") {
                        xmlOutputFile = val;
                    }
                    else if (key == "-t" || key == "--test") {
                        testPaths.emplace_back(val);
                    }
                    else {
                        std::cerr << "Unknow arguments " << key << " with value : " << val << std::endl;
                    }
                }
            }
            else {
                plugName = arg;
            }
        }

    }
};

bool runPlugin(const CommandLineParser &arguments) {
	CppUnit::PlugInManager pluginManager;
	pluginManager.load(arguments.plugName);

	// Create the event manager and test controller
	CppUnit::TestResult controller;

	// Add a listener that collects test result
	CppUnit::TestResultCollector result;
	controller.addListener(&result);

	// Add a listener
    TimedBriefTestProgressListener progress;
	controller.addListener(&progress);

	pluginManager.addListener(&controller);

	// Add the top suite to the test runner
	CppUnit::TestRunner runner;
	runner.addTest(CppUnit::TestFactoryRegistry::getRegistry().makeTest());
	try
	{
		if (arguments.testPaths.empty()) {
			std::cout << "Running " << std::endl;
			runner.run(controller);
		}
		else {
			for (const auto & p : arguments.testPaths) {
				std::cout << "Running " << p << std::endl;
				runner.run(controller, p);
			}
		}
		std::cerr << std::endl;

		// Print test in a compiler compatible format.
		CppUnit::CompilerOutputter outputter(&result, std::cerr);
		outputter.write();

        if (!arguments.xmlOutputFile.empty()) {
            std::ofstream file(arguments.xmlOutputFile);
            CppUnit::XmlOutputter xOutputter(&result, file);
            xOutputter.write();
        }
	}
	catch (std::invalid_argument &e)  // Test path not resolved
	{
		std::cerr << std::endl
			<< "ERROR: " << e.what()
			<< std::endl;
		return false;
	}
	return result.wasSuccessful();
}

int main(int argc, char* argv[])
{
	std::cout << "usage : " << argv[0] << "{-x | -xml=file} {-t | --test=Namespace::ClassName::TestName} test_plugin_path" << std::endl << std::endl;
	if (argc < 2)
		return 1;

	bool result = false;
	try {
        CommandLineParser command;
        command.parseArgs(argc, argv);
		result = runPlugin(command);
	}
	catch (std::exception &e) {
		std::cerr << std::endl
			<< "ERROR: " << e.what()
			<< std::endl;

	}
	return result ? 0 : 1;
}
<|endoftext|>


<commit_before>// implementation of MathTL::Polynomial inline functions

#include <cassert>
#include <cmath>
#include <numerics/gauss_data.h>
#include <utils/tiny_tools.h>

namespace MathTL
{
  template <class C>
  Polynomial<C>::Polynomial()
    : Vector<C>(1), Function<1,C>()
  {
  }

  template <class C>
  Polynomial<C>::Polynomial(const Polynomial<C>& p)
    : Vector<C>(p)
  {
  }

  template <class C>
  Polynomial<C>::Polynomial(const Vector<C>& coeffs)
    : Vector<C>(coeffs)
  {
  }

  template <class C>
  Polynomial<C>::Polynomial(const C c)
    : Vector<C>(1)
  {
    set_coefficient(0, c);
  }

  template <class C>
  Polynomial<C>::~Polynomial()
  {
  }

  template <class C>
  inline
  unsigned int Polynomial<C>::degree() const
  {
    return Vector<C>::size()-1;
  }

  template <class C>
  inline
  C Polynomial<C>::get_coefficient(const unsigned int k) const
  {
    return Vector<C>::operator [] (k);
  }

  template <class C>
  inline
  void Polynomial<C>::get_coefficients(Vector<C>& coeffs) const
  {
    coeffs = *this;
  }

  template <class C>
  void Polynomial<C>::set_coefficient(const unsigned int k,
				      const C coeff)
  {
    if (k > degree())
      {
	Vector<C> help;
	help.swap(*this);
	Vector<C>::resize(k+1);
	std::copy(help.begin(), help.end(), Vector<C>::begin());
      }

    Vector<C>::operator [] (k) = coeff;

    trim();
  }

  template <class C>
  void Polynomial<C>::set_coefficients(const Vector<C>& coeffs)
  {
    assert(coeffs.size() > 0);
    Vector<C>::operator = (coeffs);

    trim();
  }

  template <class C>
  C Polynomial<C>::value(const C x) const
  {
    C value(Vector<C>::operator [] (degree()));

    for (unsigned int k(degree()); k > 0; k--)
      value = value * x + get_coefficient(k-1);

    return value;
  }

  template <class C>
  C Polynomial<C>::value(const C x, const unsigned int derivative) const
  {
    // storage for full Horner scheme
    Vector<C> horner(*this);

    for (unsigned row(0); row <= derivative; row++)
      {
	for (unsigned n(degree()); n > row; n--)
	  horner[n-1] += x*horner[n];
      }

    return horner[derivative] * faculty(derivative);
  }

  template <class C>
  inline
  C Polynomial<C>::value(const Point<1>& p,
			 const unsigned int component) const
  {
    return value(p[0]);
  }

  template <class C>
  inline
  void Polynomial<C>::vector_value(const Point<1> &p,
				   Vector<C>& values) const
  {
    values.resize(1, false);
    values[0] = value(p[0]);
  }

  template <class C>
  void Polynomial<C>::scale(const C s)
  {
    C factor(1.0);
    for (typename Vector<C>::iterator it(Vector<C>::begin()), itend(Vector<C>::end());
	 it != itend; ++it)
      {
	*it *= factor;
	factor *= s;
      }

    trim(); // TODO: check s=0
  }

  template <class C>
  void Polynomial<C>::shift(const C s)
  {
    Vector<C> new_coeffs(*this);

    for (unsigned int d(1); d < new_coeffs.size(); d++)
      {
	unsigned int n(d);
	unsigned int binomial(1);
	C s_power(s);
	for (unsigned int k(0); k < d; k++)
	  {
	    binomial = (binomial*(n-k))/(k+1);
	    new_coeffs[d-k-1] +=
	      new_coeffs[d] * binomial * s_power;
	    s_power *= s;
	  }
      }

    Vector<C>::swap(new_coeffs);

    // no trimming necessary
  }

  template <class C>
  void Polynomial<C>::chain(const Polynomial<C>& p)
  {
    if (degree() > 0)
      {
	// maybe the following can be optimized

  	Polynomial<C> q;
  	C a0(get_coefficient(0)); // not changed by substitution

  	Polynomial<C> r;
  	for (unsigned int expo = 1; expo <= degree(); expo++)
  	  {
  	    if (get_coefficient(expo) != 0)
  	      {
  		q = p;
  		for (unsigned int l = 2; l <= expo; l++)
  		  q *= p;
  		q *= get_coefficient(expo);

  		r += q;
  	      }
  	  }

 	Vector<C>::swap(r);
 	set_coefficient(0, get_coefficient(0) + a0);
      }

    // no trimming necessary
  }

  template <class C>
  Polynomial<C> Polynomial<C>::substitute_into(const Polynomial<C>& p) const
  {
    Polynomial r(*this);
    r.chain(p);

    return r;
  }

  template <class C>
  Polynomial<C>& Polynomial<C>::operator = (const Polynomial<C>& p)
  {
    Vector<C>::operator = (p);
    trim();
    return *this;
  }

  template <class C>
  Polynomial<C>& Polynomial<C>::operator = (const C c)
  {
    Vector<C>::resize(1, false);
    set_coefficient(0, c);
    return *this; // no trimming necessary
  }

  template <class C>
  void Polynomial<C>::add(const Polynomial<C>& p)
  {
    Vector<C> help(std::max(degree(), p.degree())+1);
    if (degree()+1 == help.size())
      {
	std::copy(p.begin(), p.end(), help.begin());
	help.add(*this);
      }
    else
      {
	std::copy(Vector<C>::begin(), Vector<C>::end(), help.begin());
	help.add(p);
      }
    Vector<C>::swap(help);

    trim();
  }

  template <class C>
  void Polynomial<C>::add(const C s, const Polynomial<C>& p)
  {
    Vector<C> help(std::max(degree(), p.degree())+1);
    if (degree()+1 == help.size())
      {
	std::copy(p.begin(), p.end(), help.begin());
	help.sadd(s, *this); // help <- s*help + *this
      }
    else
      {
	std::copy(Vector<C>::begin(), Vector<C>::end(), help.begin());
	help.add(s, p); // help <- help + s*p
      }
    Vector<C>::swap(help);

    trim();
  }

  template <class C>
  void Polynomial<C>::sadd(const C s, const Polynomial<C>& p)
  {
    Vector<C> help(std::max(degree(), p.degree())+1);
    if (degree()+1 == help.size())
      {
	std::copy(p.begin(), p.end(), help.begin());
	help.add(s, *this); // help <- help + s*(*this)
      }
    else
      {
	std::copy(Vector<C>::begin(), Vector<C>::end(), help.begin());
	help.sadd(s, p); // help <- s*help + p
      }
    Vector<C>::swap(help);

    trim();
  }

  template <class C>
  inline
  Polynomial<C>& Polynomial<C>::operator += (const Polynomial<C>& p)
  {
    add(p); // trims
    return *this;
  }

  template <class C>
  inline
  Polynomial<C> Polynomial<C>::operator + (const Polynomial<C>& p) const
  {
    return (Polynomial<C>(*this) += p); // trims
  }

  template <class C>
  void Polynomial<C>::subtract(const Polynomial<C>& p)
  {
    Vector<C> help(std::max(degree(), p.degree())+1);
    if (degree()+1 == help.size())
      {
	std::copy(p.begin(), p.end(), help.begin());
	help.sadd(C(-1), *this);
      }
    else
      {
	std::copy(Vector<C>::begin(), Vector<C>::end(), help.begin());
	help.add(C(-1), p);
      }
    Vector<C>::swap(help);

    trim();
  }

  template <class C>
  inline
  Polynomial<C>& Polynomial<C>::operator -= (const Polynomial<C>& p)
  {
    subtract(p); // trims
    return *this;
  }

  template <class C>
  inline
  Polynomial<C> Polynomial<C>::operator - () const
  {
    return (Polynomial<C>() -= *this); // trims
  }

  template <class C>
  inline
  Polynomial<C> Polynomial<C>::operator - (const Polynomial<C>& p) const
  {
    return (Polynomial<C>(*this) -= p);
  }

  template <class C>
  Polynomial<C>& Polynomial<C>::operator *= (const C c)
  {
    if (c == C(0))
      Vector<C>::resize(1); // p(x)=0, degree changes
    else
      Vector<C>::operator *= (c);

    return *this;
  }

  template <class C>
  inline
  Polynomial<C> Polynomial<C>::operator * (const C c) const
  {
    return (Polynomial(*this) *= c);
  }

  template <class C>
  void
  Polynomial<C>::multiply(const Polynomial<C>& p)
  {
    Vector<C> coeffs(degree()+p.degree()+1);
    for (unsigned int n(0); n <= degree(); n++)
      for (unsigned int m(0); m <= p.degree(); m++)
	coeffs[n+m] += Vector<C>::operator [] (n) * p.get_coefficient(m);

    Vector<C>::swap(coeffs);

    trim(); // for safety
  }

  template <class C>
  inline
  Polynomial<C>& Polynomial<C>::operator *= (const Polynomial<C>& p)
  {
    multiply(p); // trims
    return *this;
  }

  template <class C>
  inline
  Polynomial<C> Polynomial<C>::operator * (const Polynomial<C>& p)
  {
    return (Polynomial(*this) *= p); // trims
  }

  template <class C>
  Polynomial<C> Polynomial<C>::power(const unsigned int k) const
  {
    Polynomial<C> r(1);

    for (unsigned int i(0); i < k; i++)
      r.multiply(*this);

    return r;
  }

  template <class C>
  void Polynomial<C>::divide(const Polynomial<C>& q,
			     Polynomial<C>& p, Polynomial<C>& r) const
  {
    assert(degree() >= q.degree());

    r = *this;
    p = 0;
    for (int k(r.degree() - q.degree());
	 k >= 0; k = r.degree() - q.degree())
      {
 	double factor = r.get_coefficient(r.degree()) / q.get_coefficient(q.degree());
 	p.set_coefficient(k, factor);
 	Polynomial monom;
 	monom.set_coefficient(k, factor);
 	r.subtract(monom * q);
      }
  }

  template <class C>
  void Polynomial<C>::divide(const Polynomial<C>& q, Polynomial<C>& p) const
  {
    Polynomial<C> r;
    divide(q, p, r);
  }

  template <class C>
  Polynomial<C> Polynomial<C>::differentiate() const
  {
    Vector<C> coeffs(std::max(degree(),(unsigned int)1));

    for (unsigned int n(1); n <= degree(); n++)
      coeffs[n-1] = n * get_coefficient(n);

    return Polynomial<C>(coeffs);
  }

  template <class C>
  Polynomial<C> Polynomial<C>::integrate() const
  {
    Vector<C> coeffs(degree()+2);

    for (unsigned int n(0); n <= degree(); n++)
      coeffs[n+1] = get_coefficient(n) / (n + 1.0);

    return Polynomial<C>(coeffs);
  }

  template <class C>
  double Polynomial<C>::integrate(const double a,
                                  const double b,
                                  const bool quadrature) const
  {
    assert(a <= b);

    double r = 0;

    if (quadrature)
      {
	const unsigned int N = (unsigned int)ceil((degree()+1)/2.0); // ensures 2*N-1>=degree()

 	for(unsigned int i(0); i < N; i++)
    	  r += GaussWeights[N-1][i] * value((a+b + (b-a)*GaussPoints[N-1][i])/2.0);

	r *= b-a;
      }
    else
      {
	Polynomial<C> P(integrate());
	r = P.value(b)-P.value(a);
      }

    return r;
  }

  template <class C>
  double Polynomial<C>::inner_product(Polynomial<C> p2, double a, double b)
  {
    Polynomial<C> t(this);
    t *= p2;
    return t.integrate(t, a, b);
  }

  template <class C>
  Polynomial<C> operator * (const C c, const Polynomial<C>& p)
  {
    return (Polynomial<C>(p) *= c);
  }

  template <class C>
  void Polynomial<C>::trim()
  {
    // determine "true" degree
    unsigned int deg(0);
    for(unsigned int i(1); i <= degree(); i++)
      {
	if (get_coefficient(i) != 0)
	  deg = i;
      }

    if (deg < degree())
      {
	Vector<C> trimmed(std::max(1u, deg+1));
	for (unsigned int i(0); i < trimmed.size(); i++)
	  trimmed[i] = get_coefficient(i);
	Vector<C>::swap(trimmed);
      }
  }

  template <class C>
  std::ostream& operator << (std::ostream &s, const Polynomial<C> &p)
  {
    double c;
    int oldprecision = s.precision();
    std::ios::fmtflags oldflags = s.flags();
    //  s.setf(ios::scientific, ios::floatfield);
    s.precision(12);

    bool first = true;
    for (unsigned int k = p.degree(); k >= 1; k--)
      {
	c = p.get_coefficient(k);
	if (c != 0)
	  {
	    if (!first)
	      {
		if (c >= 0)
		  s << "+";
	      }
	    if (fabs(c) != 1)
	      s << c;
	    else
	      if (c == -1)
		s << "-";
	    s << "x";
	    if (k > 1)
	      s << "^" << k;
	    first = false;
	  }
      }

    c = p.get_coefficient(0);

    if ((c!=0)||(p.degree()==0))
      {
	if (!first)
	  {
	    if (c >= 0)
	      s << "+";
	  }
	s << c;
      }

    s.setf(oldflags);
    s.precision(oldprecision);

    return s;
  }
}
<commit_msg>Fixed a bug in Polynomial::inner_product<commit_after>// implementation of MathTL::Polynomial inline functions

#include <cassert>
#include <cmath>
#include <numerics/gauss_data.h>
#include <utils/tiny_tools.h>

namespace MathTL
{
  template <class C>
  Polynomial<C>::Polynomial()
    : Vector<C>(1), Function<1,C>()
  {
  }

  template <class C>
  Polynomial<C>::Polynomial(const Polynomial<C>& p)
    : Vector<C>(p)
  {
  }

  template <class C>
  Polynomial<C>::Polynomial(const Vector<C>& coeffs)
    : Vector<C>(coeffs)
  {
  }

  template <class C>
  Polynomial<C>::Polynomial(const C c)
    : Vector<C>(1)
  {
    set_coefficient(0, c);
  }

  template <class C>
  Polynomial<C>::~Polynomial()
  {
  }

  template <class C>
  inline
  unsigned int Polynomial<C>::degree() const
  {
    return Vector<C>::size()-1;
  }

  template <class C>
  inline
  C Polynomial<C>::get_coefficient(const unsigned int k) const
  {
    return Vector<C>::operator [] (k);
  }

  template <class C>
  inline
  void Polynomial<C>::get_coefficients(Vector<C>& coeffs) const
  {
    coeffs = *this;
  }

  template <class C>
  void Polynomial<C>::set_coefficient(const unsigned int k,
				      const C coeff)
  {
    if (k > degree())
      {
	Vector<C> help;
	help.swap(*this);
	Vector<C>::resize(k+1);
	std::copy(help.begin(), help.end(), Vector<C>::begin());
      }

    Vector<C>::operator [] (k) = coeff;

    trim();
  }

  template <class C>
  void Polynomial<C>::set_coefficients(const Vector<C>& coeffs)
  {
    assert(coeffs.size() > 0);
    Vector<C>::operator = (coeffs);

    trim();
  }

  template <class C>
  C Polynomial<C>::value(const C x) const
  {
    C value(Vector<C>::operator [] (degree()));

    for (unsigned int k(degree()); k > 0; k--)
      value = value * x + get_coefficient(k-1);

    return value;
  }

  template <class C>
  C Polynomial<C>::value(const C x, const unsigned int derivative) const
  {
    // storage for full Horner scheme
    Vector<C> horner(*this);

    for (unsigned row(0); row <= derivative; row++)
      {
	for (unsigned n(degree()); n > row; n--)
	  horner[n-1] += x*horner[n];
      }

    return horner[derivative] * faculty(derivative);
  }

  template <class C>
  inline
  C Polynomial<C>::value(const Point<1>& p,
			 const unsigned int component) const
  {
    return value(p[0]);
  }

  template <class C>
  inline
  void Polynomial<C>::vector_value(const Point<1> &p,
				   Vector<C>& values) const
  {
    values.resize(1, false);
    values[0] = value(p[0]);
  }

  template <class C>
  void Polynomial<C>::scale(const C s)
  {
    C factor(1.0);
    for (typename Vector<C>::iterator it(Vector<C>::begin()), itend(Vector<C>::end());
	 it != itend; ++it)
      {
	*it *= factor;
	factor *= s;
      }

    trim(); // TODO: check s=0
  }

  template <class C>
  void Polynomial<C>::shift(const C s)
  {
    Vector<C> new_coeffs(*this);

    for (unsigned int d(1); d < new_coeffs.size(); d++)
      {
	unsigned int n(d);
	unsigned int binomial(1);
	C s_power(s);
	for (unsigned int k(0); k < d; k++)
	  {
	    binomial = (binomial*(n-k))/(k+1);
	    new_coeffs[d-k-1] +=
	      new_coeffs[d] * binomial * s_power;
	    s_power *= s;
	  }
      }

    Vector<C>::swap(new_coeffs);

    // no trimming necessary
  }

  template <class C>
  void Polynomial<C>::chain(const Polynomial<C>& p)
  {
    if (degree() > 0)
      {
	// maybe the following can be optimized

  	Polynomial<C> q;
  	C a0(get_coefficient(0)); // not changed by substitution

  	Polynomial<C> r;
  	for (unsigned int expo = 1; expo <= degree(); expo++)
  	  {
  	    if (get_coefficient(expo) != 0)
  	      {
  		q = p;
  		for (unsigned int l = 2; l <= expo; l++)
  		  q *= p;
  		q *= get_coefficient(expo);

  		r += q;
  	      }
  	  }

 	Vector<C>::swap(r);
 	set_coefficient(0, get_coefficient(0) + a0);
      }

    // no trimming necessary
  }

  template <class C>
  Polynomial<C> Polynomial<C>::substitute_into(const Polynomial<C>& p) const
  {
    Polynomial r(*this);
    r.chain(p);

    return r;
  }

  template <class C>
  Polynomial<C>& Polynomial<C>::operator = (const Polynomial<C>& p)
  {
    Vector<C>::operator = (p);
    trim();
    return *this;
  }

  template <class C>
  Polynomial<C>& Polynomial<C>::operator = (const C c)
  {
    Vector<C>::resize(1, false);
    set_coefficient(0, c);
    return *this; // no trimming necessary
  }

  template <class C>
  void Polynomial<C>::add(const Polynomial<C>& p)
  {
    Vector<C> help(std::max(degree(), p.degree())+1);
    if (degree()+1 == help.size())
      {
	std::copy(p.begin(), p.end(), help.begin());
	help.add(*this);
      }
    else
      {
	std::copy(Vector<C>::begin(), Vector<C>::end(), help.begin());
	help.add(p);
      }
    Vector<C>::swap(help);

    trim();
  }

  template <class C>
  void Polynomial<C>::add(const C s, const Polynomial<C>& p)
  {
    Vector<C> help(std::max(degree(), p.degree())+1);
    if (degree()+1 == help.size())
      {
	std::copy(p.begin(), p.end(), help.begin());
	help.sadd(s, *this); // help <- s*help + *this
      }
    else
      {
	std::copy(Vector<C>::begin(), Vector<C>::end(), help.begin());
	help.add(s, p); // help <- help + s*p
      }
    Vector<C>::swap(help);

    trim();
  }

  template <class C>
  void Polynomial<C>::sadd(const C s, const Polynomial<C>& p)
  {
    Vector<C> help(std::max(degree(), p.degree())+1);
    if (degree()+1 == help.size())
      {
	std::copy(p.begin(), p.end(), help.begin());
	help.add(s, *this); // help <- help + s*(*this)
      }
    else
      {
	std::copy(Vector<C>::begin(), Vector<C>::end(), help.begin());
	help.sadd(s, p); // help <- s*help + p
      }
    Vector<C>::swap(help);

    trim();
  }

  template <class C>
  inline
  Polynomial<C>& Polynomial<C>::operator += (const Polynomial<C>& p)
  {
    add(p); // trims
    return *this;
  }

  template <class C>
  inline
  Polynomial<C> Polynomial<C>::operator + (const Polynomial<C>& p) const
  {
    return (Polynomial<C>(*this) += p); // trims
  }

  template <class C>
  void Polynomial<C>::subtract(const Polynomial<C>& p)
  {
    Vector<C> help(std::max(degree(), p.degree())+1);
    if (degree()+1 == help.size())
      {
	std::copy(p.begin(), p.end(), help.begin());
	help.sadd(C(-1), *this);
      }
    else
      {
	std::copy(Vector<C>::begin(), Vector<C>::end(), help.begin());
	help.add(C(-1), p);
      }
    Vector<C>::swap(help);

    trim();
  }

  template <class C>
  inline
  Polynomial<C>& Polynomial<C>::operator -= (const Polynomial<C>& p)
  {
    subtract(p); // trims
    return *this;
  }

  template <class C>
  inline
  Polynomial<C> Polynomial<C>::operator - () const
  {
    return (Polynomial<C>() -= *this); // trims
  }

  template <class C>
  inline
  Polynomial<C> Polynomial<C>::operator - (const Polynomial<C>& p) const
  {
    return (Polynomial<C>(*this) -= p);
  }

  template <class C>
  Polynomial<C>& Polynomial<C>::operator *= (const C c)
  {
    if (c == C(0))
      Vector<C>::resize(1); // p(x)=0, degree changes
    else
      Vector<C>::operator *= (c);

    return *this;
  }

  template <class C>
  inline
  Polynomial<C> Polynomial<C>::operator * (const C c) const
  {
    return (Polynomial(*this) *= c);
  }

  template <class C>
  void
  Polynomial<C>::multiply(const Polynomial<C>& p)
  {
    Vector<C> coeffs(degree()+p.degree()+1);
    for (unsigned int n(0); n <= degree(); n++)
      for (unsigned int m(0); m <= p.degree(); m++)
	coeffs[n+m] += Vector<C>::operator [] (n) * p.get_coefficient(m);

    Vector<C>::swap(coeffs);

    trim(); // for safety
  }

  template <class C>
  inline
  Polynomial<C>& Polynomial<C>::operator *= (const Polynomial<C>& p)
  {
    multiply(p); // trims
    return *this;
  }

  template <class C>
  inline
  Polynomial<C> Polynomial<C>::operator * (const Polynomial<C>& p)
  {
    return (Polynomial(*this) *= p); // trims
  }

  template <class C>
  Polynomial<C> Polynomial<C>::power(const unsigned int k) const
  {
    Polynomial<C> r(1);

    for (unsigned int i(0); i < k; i++)
      r.multiply(*this);

    return r;
  }

  template <class C>
  void Polynomial<C>::divide(const Polynomial<C>& q,
			     Polynomial<C>& p, Polynomial<C>& r) const
  {
    assert(degree() >= q.degree());

    r = *this;
    p = 0;
    for (int k(r.degree() - q.degree());
	 k >= 0; k = r.degree() - q.degree())
      {
 	double factor = r.get_coefficient(r.degree()) / q.get_coefficient(q.degree());
 	p.set_coefficient(k, factor);
 	Polynomial monom;
 	monom.set_coefficient(k, factor);
 	r.subtract(monom * q);
      }
  }

  template <class C>
  void Polynomial<C>::divide(const Polynomial<C>& q, Polynomial<C>& p) const
  {
    Polynomial<C> r;
    divide(q, p, r);
  }

  template <class C>
  Polynomial<C> Polynomial<C>::differentiate() const
  {
    Vector<C> coeffs(std::max(degree(),(unsigned int)1));

    for (unsigned int n(1); n <= degree(); n++)
      coeffs[n-1] = n * get_coefficient(n);

    return Polynomial<C>(coeffs);
  }

  template <class C>
  Polynomial<C> Polynomial<C>::integrate() const
  {
    Vector<C> coeffs(degree()+2);

    for (unsigned int n(0); n <= degree(); n++)
      coeffs[n+1] = get_coefficient(n) / (n + 1.0);

    return Polynomial<C>(coeffs);
  }

  template <class C>
  double Polynomial<C>::integrate(const double a,
                                  const double b,
                                  const bool quadrature) const
  {
    assert(a <= b);

    double r = 0;

    if (quadrature)
      {
	const unsigned int N = (unsigned int)ceil((degree()+1)/2.0); // ensures 2*N-1>=degree()

 	for(unsigned int i(0); i < N; i++)
    	  r += GaussWeights[N-1][i] * value((a+b + (b-a)*GaussPoints[N-1][i])/2.0);

	r *= b-a;
      }
    else
      {
	Polynomial<C> P(integrate());
	r = P.value(b)-P.value(a);
      }

    return r;
  }

  template <class C>
  double Polynomial<C>::inner_product(Polynomial<C> p2, double a, double b)
  {
    Polynomial<C> t(*this);
    t *= p2;
    return t.integrate(a, b, true);
  }

  template <class C>
  Polynomial<C> operator * (const C c, const Polynomial<C>& p)
  {
    return (Polynomial<C>(p) *= c);
  }

  template <class C>
  void Polynomial<C>::trim()
  {
    // determine "true" degree
    unsigned int deg(0);
    for(unsigned int i(1); i <= degree(); i++)
      {
	if (get_coefficient(i) != 0)
	  deg = i;
      }

    if (deg < degree())
      {
	Vector<C> trimmed(std::max(1u, deg+1));
	for (unsigned int i(0); i < trimmed.size(); i++)
	  trimmed[i] = get_coefficient(i);
	Vector<C>::swap(trimmed);
      }
  }

  template <class C>
  std::ostream& operator << (std::ostream &s, const Polynomial<C> &p)
  {
    double c;
    int oldprecision = s.precision();
    std::ios::fmtflags oldflags = s.flags();
    //  s.setf(ios::scientific, ios::floatfield);
    s.precision(12);

    bool first = true;
    for (unsigned int k = p.degree(); k >= 1; k--)
      {
	c = p.get_coefficient(k);
	if (c != 0)
	  {
	    if (!first)
	      {
		if (c >= 0)
		  s << "+";
	      }
	    if (fabs(c) != 1)
	      s << c;
	    else
	      if (c == -1)
		s << "-";
	    s << "x";
	    if (k > 1)
	      s << "^" << k;
	    first = false;
	  }
      }

    c = p.get_coefficient(0);

    if ((c!=0)||(p.degree()==0))
      {
	if (!first)
	  {
	    if (c >= 0)
	      s << "+";
	  }
	s << c;
      }

    s.setf(oldflags);
    s.precision(oldprecision);

    return s;
  }
}
<|endoftext|>


<commit_before>#include "mitkOperationEvent.h"

//##ModelId=3E9B07B40374
int mitk::OperationEvent::m_CurrObjectEventId = 0;
//##ModelId=3E9B07B5002B
int mitk::OperationEvent::m_CurrGroupEventId = 0;

//##ModelId=3E5F610D00BB
mitk::Operation* mitk::OperationEvent::GetOperation()
{
	return m_Operation;
}

//##ModelId=3E957AE700E6
mitk::OperationEvent::OperationEvent(OperationActor* destination,
									 Operation* operation, Operation* undoOperation,
									 int objectEventId, int groupEventId)
: m_Destination(destination), m_Operation(operation), m_UndoOperation(undoOperation),
  m_ObjectEventId(objectEventId), m_GroupEventId(groupEventId), m_Swaped(false)
{
}

//##ModelId=3F0451960212
mitk::OperationEvent::~OperationEvent()
{
}

//##ModelId=3E957C1102E3
//##Documentation
//##  swaps the Undo and Redo- operation and changes m_Swaped
void mitk::OperationEvent::SwapOperations()
{
    if (m_Operation == NULL)
        return;

	Operation *tempOperation = m_Operation;
	m_Operation = m_UndoOperation;
	m_UndoOperation = tempOperation;
	if (m_Swaped)
		m_Swaped = false;
	else
		m_Swaped = true;
}

//##ModelId=3E9B07B50220
int mitk::OperationEvent::GetCurrGroupEventId()
{
	return m_CurrGroupEventId;
}

//##ModelId=3E9B07B501A7
int mitk::OperationEvent::GetCurrObjectEventId()
{
	return m_CurrObjectEventId;
}

//##ModelId=3EF099E90269
int mitk::OperationEvent::IncCurrGroupEventId()
{
	return m_CurrGroupEventId++;
}

//##ModelId=3EF099E90289
int mitk::OperationEvent::IncCurrObjectEventId()
{
	return m_CurrObjectEventId++;
}

//##ModelId=3E9B07B502AC
mitk::OperationActor* mitk::OperationEvent::GetDestination()
{
	return m_Destination;
}

//##ModelId=3EF099E90249
int mitk::OperationEvent::GetGroupEventId()
{
	return m_GroupEventId;
}

//##ModelId=3EF099E90259
int mitk::OperationEvent::GetObjectEventId()
{
	return m_ObjectEventId;
}
<commit_msg>changed increase of Group and ObjectEventId<commit_after>#include "mitkOperationEvent.h"

//##ModelId=3E9B07B40374
int mitk::OperationEvent::m_CurrObjectEventId = 0;
//##ModelId=3E9B07B5002B
int mitk::OperationEvent::m_CurrGroupEventId = 0;

//##ModelId=3E5F610D00BB
mitk::Operation* mitk::OperationEvent::GetOperation()
{
	return m_Operation;
}

//##ModelId=3E957AE700E6
mitk::OperationEvent::OperationEvent(OperationActor* destination,
									 Operation* operation, Operation* undoOperation,
									 int objectEventId, int groupEventId)
: m_Destination(destination), m_Operation(operation), m_UndoOperation(undoOperation),
  m_ObjectEventId(objectEventId), m_GroupEventId(groupEventId), m_Swaped(false)
{
}

//##ModelId=3F0451960212
mitk::OperationEvent::~OperationEvent()
{
}

//##ModelId=3E957C1102E3
//##Documentation
//##  swaps the Undo and Redo- operation and changes m_Swaped
void mitk::OperationEvent::SwapOperations()
{
    if (m_Operation == NULL)
        return;

	Operation *tempOperation = m_Operation;
	m_Operation = m_UndoOperation;
	m_UndoOperation = tempOperation;
	if (m_Swaped)
		m_Swaped = false;
	else
		m_Swaped = true;
}

//##ModelId=3E9B07B50220
int mitk::OperationEvent::GetCurrGroupEventId()
{
	return m_CurrGroupEventId;
}

//##ModelId=3E9B07B501A7
int mitk::OperationEvent::GetCurrObjectEventId()
{
	return m_CurrObjectEventId;
}

//##ModelId=3EF099E90269
int mitk::OperationEvent::IncCurrGroupEventId()
{
	return ++m_CurrGroupEventId;
}

//##ModelId=3EF099E90289
int mitk::OperationEvent::IncCurrObjectEventId()
{
	return ++m_CurrObjectEventId;
}

//##ModelId=3E9B07B502AC
mitk::OperationActor* mitk::OperationEvent::GetDestination()
{
	return m_Destination;
}

//##ModelId=3EF099E90249
int mitk::OperationEvent::GetGroupEventId()
{
	return m_GroupEventId;
}

//##ModelId=3EF099E90259
int mitk::OperationEvent::GetObjectEventId()
{
	return m_ObjectEventId;
}
<|endoftext|>


<commit_before>#include "MediaSessionManager.h"
#include "types/MediaSessionImpl.h"

using namespace ::com::kurento::kms;
using namespace ::com::kurento::kms::api;

void task() {
}

MediaSessionManager::MediaSessionManager() {
}

MediaSessionManager::~MediaSessionManager() {
}

MediaSessionManager *MediaSessionManager::getInstance() {
	static MediaSessionManager *instance = new MediaSessionManager();
	return instance;
}

void MediaSessionManager::releaseInstance(MediaSessionManager* manager) {
	// As instance is a singleton no action is needed
}

MediaSessionImpl &MediaSessionManager::createMediaSession() {
	MediaSessionImpl *session = new MediaSessionImpl();

	mutex.lock();
	sessions.push_back(session);
	mutex.unlock();

	return *session;
}

void MediaSessionManager::deleteMediaSession(const MediaSession &session) {
	std::list<MediaSessionImpl *>::iterator it;
	bool found = FALSE;

	mutex.lock();
	for (it=sessions.begin(); !found && (it!=sessions.end()); it++) {
		if (session == *(*it)) {
			found = true;
			delete *it;
			sessions.erase(it);
		}
	}
	mutex.unlock();

	if (!found) {
		MediaSessionNotFoundException exception;
		throw exception;
	}
}

MediaSessionImpl&
MediaSessionManager::getMediaSession(const MediaSession& session) {
	std::list<MediaSessionImpl *>::iterator it;
	MediaSessionImpl *ms;
	bool found = FALSE;

	mutex.lock();
	for (it=sessions.begin(); !found && (it!=sessions.end()); it++) {
		if (session == *(*it)) {
			found = true;
			ms = *it;
		}
	}
	mutex.unlock();

	if (!found) {
		throw MediaSessionNotFoundException();
	}

	return *ms;
}
<commit_msg>Remove dummy function<commit_after>#include "MediaSessionManager.h"
#include "types/MediaSessionImpl.h"

using namespace ::com::kurento::kms;
using namespace ::com::kurento::kms::api;

MediaSessionManager::MediaSessionManager() {
}

MediaSessionManager::~MediaSessionManager() {
}

MediaSessionManager *MediaSessionManager::getInstance() {
	static MediaSessionManager *instance = new MediaSessionManager();
	return instance;
}

void MediaSessionManager::releaseInstance(MediaSessionManager* manager) {
	// As instance is a singleton no action is needed
}

MediaSessionImpl &MediaSessionManager::createMediaSession() {
	MediaSessionImpl *session = new MediaSessionImpl();

	mutex.lock();
	sessions.push_back(session);
	mutex.unlock();

	return *session;
}

void MediaSessionManager::deleteMediaSession(const MediaSession &session) {
	std::list<MediaSessionImpl *>::iterator it;
	bool found = FALSE;

	mutex.lock();
	for (it=sessions.begin(); !found && (it!=sessions.end()); it++) {
		if (session == *(*it)) {
			found = true;
			delete *it;
			sessions.erase(it);
		}
	}
	mutex.unlock();

	if (!found) {
		MediaSessionNotFoundException exception;
		throw exception;
	}
}

MediaSessionImpl&
MediaSessionManager::getMediaSession(const MediaSession& session) {
	std::list<MediaSessionImpl *>::iterator it;
	MediaSessionImpl *ms;
	bool found = FALSE;

	mutex.lock();
	for (it=sessions.begin(); !found && (it!=sessions.end()); it++) {
		if (session == *(*it)) {
			found = true;
			ms = *it;
		}
	}
	mutex.unlock();

	if (!found) {
		throw MediaSessionNotFoundException();
	}

	return *ms;
}
<|endoftext|>