<commit_before>/*

  Copyright 2009 University of Helsinki

  Licensed under the Apache License, Version 2.0 (the "License");
  you may not use this file except in compliance with the License.
  You may obtain a copy of the License at

  http://www.apache.org/licenses/LICENSE-2.0

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

*/

/*
  This is a toy commandline utility for testing spellers on standard io.
 */

#if HAVE_CONFIG_H
#  include <config.h>
#endif
#if HAVE_GETOPT_H
#  include <getopt.h>
#endif
#include "ol-exceptions.h"
#include "ospell.h"
#include "ZHfstOspeller.h"

using hfst_ol::ZHfstOspeller;
using hfst_ol::Transducer;

static bool quiet = false;
static bool verbose = false;

bool print_usage(void)
{
    std::cerr <<
    "\n" <<
    "Usage: " << PACKAGE_NAME << " [OPTIONS] ERRORSOURCE LEXICON\n" <<
    "       " << PACKAGE_NAME << " [OPTIONS] ZHFST-ARCHIVE\n" <<
    "Run a composition of ERRORSOURCE and LEXICON on standard input and\n" <<
    "print corrected output\n" <<
    "Second form seeks error sources and lexicons from the ZHFST-ARCHIVE\n"
    "\n" <<
    "  -h, --help                  Print this help message\n" <<
    "  -V, --version               Print version information\n" <<
    "  -v, --verbose               Be verbose\n" <<
    "  -q, --quiet                 Don't be verbose (default)\n" <<
    "  -s, --silent                Same as quiet\n" <<
    "\n" <<
    "\n" <<
    "Report bugs to " << PACKAGE_BUGREPORT << "\n" <<
    "\n";
    return true;
}

bool print_version(void)
{
    std::cerr <<
    "\n" <<
    PACKAGE_STRING << std::endl <<
    __DATE__ << " " __TIME__ << std::endl <<
    "copyright (C) 2009 - 2011 University of Helsinki\n";
    return true;
}

bool print_short_help(void)
{
    print_usage();
    return true;
}

int
legacy_spell(const char* errmodel_filename, const char* acceptor_filename)
{
    FILE* mutator_file = fopen(errmodel_filename, "r");
    if (mutator_file == NULL) {
        std::cerr << "Could not open file " << errmodel_filename
              << std::endl;
        return EXIT_FAILURE;
    }
    FILE* lexicon_file = fopen(acceptor_filename, "r");
    if (lexicon_file == NULL) {
        std::cerr << "Could not open file " << acceptor_filename
              << std::endl;
        return EXIT_FAILURE;
    }
    hfst_ol::Transducer * mutator;
    hfst_ol::Transducer * lexicon;
    mutator = new hfst_ol::Transducer(mutator_file);
    if (!mutator->is_weighted()) {
        std::cerr << "Error source was unweighted, exiting\n\n";
        return EXIT_FAILURE;
    }
    lexicon = new hfst_ol::Transducer(lexicon_file);
    if (!lexicon->is_weighted()) {
        std::cerr << "Lexicon was unweighted, exiting\n\n";
        return EXIT_FAILURE;
    }

    hfst_ol::Speller * speller;

    try {
        speller = new hfst_ol::Speller(mutator, lexicon);
    } catch (hfst_ol::AlphabetTranslationException& e) {
        std::cerr <<
        "Unable to build speller - symbol " << e.what() << " not "
        "present in lexicon's alphabet\n";
        return EXIT_FAILURE;
    }
    std::cout << "This is basic HFST spellchecker read in legacy "
        "mode; use zhfst version to test new format" << std::endl;
    char * str = (char*) malloc(2000);

    while (!std::cin.eof()) {
        std::cin.getline(str, 2000);
        if (str[0] == '\0')
          {
            std::cerr << "Skipping empty lines" << std::endl;
            continue;
          }
        if (str[strlen(str) - 1] == '\r')
          {
            std::cerr << "There is a WINDOWS linebreak in this file" <<
                std::endl <<
                "Please convert with dos2unix or fromdos" << std::endl;
            exit(1);
          }
        if (speller->check(str)) {
        std::cout << "\"" << str << "\" is in the lexicon\n\n";
        } else {
        hfst_ol::CorrectionQueue corrections = speller->correct(str, 5);
        if (corrections.size() > 0) {
            std::cout << "Corrections for \"" << str << "\":\n";
            while (corrections.size() > 0)
            {
            std::cout << corrections.top().first << "    " << corrections.top().second << std::endl;
            corrections.pop();
            }
            std::cout << std::endl;
        } else {
            std::cout << "Unable to correct \"" << str << "\"!\n\n";
        }
        }
    }
    return EXIT_SUCCESS;

}

int
zhfst_spell(char* zhfst_filename)
{
  ZHfstOspeller speller;
  try
    {
      speller.read_zhfst(zhfst_filename);
    }
  catch (hfst_ol::ZHfstMetaDataParsingError zhmdpe)
    {
      std::cerr << "cannot finish reading zhfst archive " << zhfst_filename <<
                   ":" << zhmdpe.what() << "." << std::endl;
      return EXIT_FAILURE;
    }
  catch (hfst_ol::ZHfstZipReadingError zhzre)
    {
      std::cerr << "cannot read zhfst archive " << zhfst_filename << ":"
          << zhzre.what() << "." << std::endl
          << "trying to read as legacy automata directory" << std::endl;
      try
        {
          speller.read_legacy(zhfst_filename);
        }
      catch (hfst_ol::ZHfstLegacyReadingError zhlre)
        {
          std::cerr << "cannot fallback to read legacy hfst speller dir "
              << zhfst_filename
              << ":" << std::endl
              << zhlre.what() << "." << std::endl;
          return EXIT_FAILURE;
        }
    }
  catch (hfst_ol::ZHfstXmlParsingError zhxpe)
    {
      std::cerr << "Cannot finish reading index.xml from "
        << zhfst_filename << ":" << std::endl
        << zhxpe.what() << "." << std::endl;
      return EXIT_FAILURE;
    }
  if (verbose)
    {
      std::cout << "Following metadata was read from ZHFST archive:" << std::endl
                << speller.metadata_dump() << std::endl;
    }
  char * str = (char*) malloc(2000);

    while (!std::cin.eof()) {
        std::cin.getline(str, 2000);
        if (str[0] == '\0') {
        break;
        }
        if (str[strlen(str) - 1] == '\r')
          {
            std::cerr << "There is a WINDOWS linebreak in this file" <<
                std::endl <<
                "Please convert with dos2unix or fromdos" << std::endl;
            exit(1);
          }
        if (speller.spell(str)) {
        std::cout << "\"" << str << "\" is in the lexicon\n\n";
        } else {
        hfst_ol::CorrectionQueue corrections = speller.suggest(str);
        if (corrections.size() > 0) {
            std::cout << "Corrections for \"" << str << "\":\n";
            while (corrections.size() > 0)
            {
            std::cout << corrections.top().first << "    " << corrections.top().second << std::endl;
            corrections.pop();
            }
            std::cout << std::endl;
        } else {
            std::cout << "Unable to correct \"" << str << "\"!\n\n";
        }
        }
    }
    free(str);
    return EXIT_SUCCESS;
  return EXIT_SUCCESS;
}

int main(int argc, char **argv)
{

    int c;
    //std::locale::global(std::locale(""));

#if HAVE_GETOPT_H
    while (true) {
        static struct option long_options[] =
            {
            // first the hfst-mandated options
            {"help",         no_argument,       0, 'h'},
            {"version",      no_argument,       0, 'V'},
            {"verbose",      no_argument,       0, 'v'},
            {"quiet",        no_argument,       0, 'q'},
            {"silent",       no_argument,       0, 's'},
            {0,              0,                 0,  0 }
            };

        int option_index = 0;
        c = getopt_long(argc, argv, "hVvqs", long_options, &option_index);

        if (c == -1) // no more options to look at
            break;

        switch (c) {
        case 'h':
            print_usage();
            return EXIT_SUCCESS;
            break;

        case 'V':
            print_version();
            return EXIT_SUCCESS;
            break;

        case 'v':
            verbose = true;
            quiet = false;
            break;

        case 'q': // fallthrough
        case 's':
            quiet = true;
            verbose = false;
            break;

        default:
            std::cerr << "Invalid option\n\n";
            print_short_help();
            return EXIT_FAILURE;
            break;
        }
    }
#else
    int optind = 1;
#endif
    // no more options, we should now be at the input filenames
    if (optind == (argc - 2))
      {
        return legacy_spell(argv[optind], argv[optind+1]);
      }
    else if (optind == (argc - 1))
      {
        return zhfst_spell(argv[optind]);
      }
    else if (optind < (argc - 2))
      {
        std::cerr << "No more than two free parameters allowed" << std::endl;
        print_short_help();
        return EXIT_FAILURE;
      }
    else if (optind >= argc)
      {
        std::cerr << "Give full path to zhfst spellers or two automata"
            << std::endl;
        print_short_help();
        return EXIT_FAILURE;
      }
    return EXIT_SUCCESS;
  }
<commit_msg>Added newline before error cause.<commit_after>/*

  Copyright 2009 University of Helsinki

  Licensed under the Apache License, Version 2.0 (the "License");
  you may not use this file except in compliance with the License.
  You may obtain a copy of the License at

  http://www.apache.org/licenses/LICENSE-2.0

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

*/

/*
  This is a toy commandline utility for testing spellers on standard io.
 */

#if HAVE_CONFIG_H
#  include <config.h>
#endif
#if HAVE_GETOPT_H
#  include <getopt.h>
#endif
#include "ol-exceptions.h"
#include "ospell.h"
#include "ZHfstOspeller.h"

using hfst_ol::ZHfstOspeller;
using hfst_ol::Transducer;

static bool quiet = false;
static bool verbose = false;

bool print_usage(void)
{
    std::cerr <<
    "\n" <<
    "Usage: " << PACKAGE_NAME << " [OPTIONS] ERRORSOURCE LEXICON\n" <<
    "       " << PACKAGE_NAME << " [OPTIONS] ZHFST-ARCHIVE\n" <<
    "Run a composition of ERRORSOURCE and LEXICON on standard input and\n" <<
    "print corrected output\n" <<
    "Second form seeks error sources and lexicons from the ZHFST-ARCHIVE\n"
    "\n" <<
    "  -h, --help                  Print this help message\n" <<
    "  -V, --version               Print version information\n" <<
    "  -v, --verbose               Be verbose\n" <<
    "  -q, --quiet                 Don't be verbose (default)\n" <<
    "  -s, --silent                Same as quiet\n" <<
    "\n" <<
    "\n" <<
    "Report bugs to " << PACKAGE_BUGREPORT << "\n" <<
    "\n";
    return true;
}

bool print_version(void)
{
    std::cerr <<
    "\n" <<
    PACKAGE_STRING << std::endl <<
    __DATE__ << " " __TIME__ << std::endl <<
    "copyright (C) 2009 - 2011 University of Helsinki\n";
    return true;
}

bool print_short_help(void)
{
    print_usage();
    return true;
}

int
legacy_spell(const char* errmodel_filename, const char* acceptor_filename)
{
    FILE* mutator_file = fopen(errmodel_filename, "r");
    if (mutator_file == NULL) {
        std::cerr << "Could not open file " << errmodel_filename
              << std::endl;
        return EXIT_FAILURE;
    }
    FILE* lexicon_file = fopen(acceptor_filename, "r");
    if (lexicon_file == NULL) {
        std::cerr << "Could not open file " << acceptor_filename
              << std::endl;
        return EXIT_FAILURE;
    }
    hfst_ol::Transducer * mutator;
    hfst_ol::Transducer * lexicon;
    mutator = new hfst_ol::Transducer(mutator_file);
    if (!mutator->is_weighted()) {
        std::cerr << "Error source was unweighted, exiting\n\n";
        return EXIT_FAILURE;
    }
    lexicon = new hfst_ol::Transducer(lexicon_file);
    if (!lexicon->is_weighted()) {
        std::cerr << "Lexicon was unweighted, exiting\n\n";
        return EXIT_FAILURE;
    }

    hfst_ol::Speller * speller;

    try {
        speller = new hfst_ol::Speller(mutator, lexicon);
    } catch (hfst_ol::AlphabetTranslationException& e) {
        std::cerr <<
        "Unable to build speller - symbol " << e.what() << " not "
        "present in lexicon's alphabet\n";
        return EXIT_FAILURE;
    }
    std::cout << "This is basic HFST spellchecker read in legacy "
        "mode; use zhfst version to test new format" << std::endl;
    char * str = (char*) malloc(2000);

    while (!std::cin.eof()) {
        std::cin.getline(str, 2000);
        if (str[0] == '\0')
          {
            std::cerr << "Skipping empty lines" << std::endl;
            continue;
          }
        if (str[strlen(str) - 1] == '\r')
          {
            std::cerr << "There is a WINDOWS linebreak in this file" <<
                std::endl <<
                "Please convert with dos2unix or fromdos" << std::endl;
            exit(1);
          }
        if (speller->check(str)) {
        std::cout << "\"" << str << "\" is in the lexicon\n\n";
        } else {
        hfst_ol::CorrectionQueue corrections = speller->correct(str, 5);
        if (corrections.size() > 0) {
            std::cout << "Corrections for \"" << str << "\":\n";
            while (corrections.size() > 0)
            {
            std::cout << corrections.top().first << "    " << corrections.top().second << std::endl;
            corrections.pop();
            }
            std::cout << std::endl;
        } else {
            std::cout << "Unable to correct \"" << str << "\"!\n\n";
        }
        }
    }
    return EXIT_SUCCESS;

}

int
zhfst_spell(char* zhfst_filename)
{
  ZHfstOspeller speller;
  try
    {
      speller.read_zhfst(zhfst_filename);
    }
  catch (hfst_ol::ZHfstMetaDataParsingError zhmdpe)
    {
      std::cerr << "cannot finish reading zhfst archive " << zhfst_filename <<
                   ":\n" << zhmdpe.what() << "." << std::endl;
      return EXIT_FAILURE;
    }
  catch (hfst_ol::ZHfstZipReadingError zhzre)
    {
      std::cerr << "cannot read zhfst archive " << zhfst_filename << ":\n"
          << zhzre.what() << "." << std::endl
          << "trying to read as legacy automata directory" << std::endl;
      try
        {
          speller.read_legacy(zhfst_filename);
        }
      catch (hfst_ol::ZHfstLegacyReadingError zhlre)
        {
          std::cerr << "cannot fallback to read legacy hfst speller dir "
              << zhfst_filename
              << ":\n" << std::endl
              << zhlre.what() << "." << std::endl;
          return EXIT_FAILURE;
        }
    }
  catch (hfst_ol::ZHfstXmlParsingError zhxpe)
    {
      std::cerr << "Cannot finish reading index.xml from "
        << zhfst_filename << ":" << std::endl
        << zhxpe.what() << "." << std::endl;
      return EXIT_FAILURE;
    }
  if (verbose)
    {
      std::cout << "Following metadata was read from ZHFST archive:" << std::endl
                << speller.metadata_dump() << std::endl;
    }
  char * str = (char*) malloc(2000);

    while (!std::cin.eof()) {
        std::cin.getline(str, 2000);
        if (str[0] == '\0') {
        break;
        }
        if (str[strlen(str) - 1] == '\r')
          {
            std::cerr << "There is a WINDOWS linebreak in this file" <<
                std::endl <<
                "Please convert with dos2unix or fromdos" << std::endl;
            exit(1);
          }
        if (speller.spell(str)) {
        std::cout << "\"" << str << "\" is in the lexicon\n\n";
        } else {
        hfst_ol::CorrectionQueue corrections = speller.suggest(str);
        if (corrections.size() > 0) {
            std::cout << "Corrections for \"" << str << "\":\n";
            while (corrections.size() > 0)
            {
            std::cout << corrections.top().first << "    " << corrections.top().second << std::endl;
            corrections.pop();
            }
            std::cout << std::endl;
        } else {
            std::cout << "Unable to correct \"" << str << "\"!\n\n";
        }
        }
    }
    free(str);
    return EXIT_SUCCESS;
  return EXIT_SUCCESS;
}

int main(int argc, char **argv)
{

    int c;
    //std::locale::global(std::locale(""));

#if HAVE_GETOPT_H
    while (true) {
        static struct option long_options[] =
            {
            // first the hfst-mandated options
            {"help",         no_argument,       0, 'h'},
            {"version",      no_argument,       0, 'V'},
            {"verbose",      no_argument,       0, 'v'},
            {"quiet",        no_argument,       0, 'q'},
            {"silent",       no_argument,       0, 's'},
            {0,              0,                 0,  0 }
            };

        int option_index = 0;
        c = getopt_long(argc, argv, "hVvqs", long_options, &option_index);

        if (c == -1) // no more options to look at
            break;

        switch (c) {
        case 'h':
            print_usage();
            return EXIT_SUCCESS;
            break;

        case 'V':
            print_version();
            return EXIT_SUCCESS;
            break;

        case 'v':
            verbose = true;
            quiet = false;
            break;

        case 'q': // fallthrough
        case 's':
            quiet = true;
            verbose = false;
            break;

        default:
            std::cerr << "Invalid option\n\n";
            print_short_help();
            return EXIT_FAILURE;
            break;
        }
    }
#else
    int optind = 1;
#endif
    // no more options, we should now be at the input filenames
    if (optind == (argc - 2))
      {
        return legacy_spell(argv[optind], argv[optind+1]);
      }
    else if (optind == (argc - 1))
      {
        return zhfst_spell(argv[optind]);
      }
    else if (optind < (argc - 2))
      {
        std::cerr << "No more than two free parameters allowed" << std::endl;
        print_short_help();
        return EXIT_FAILURE;
      }
    else if (optind >= argc)
      {
        std::cerr << "Give full path to zhfst spellers or two automata"
            << std::endl;
        print_short_help();
        return EXIT_FAILURE;
      }
    return EXIT_SUCCESS;
  }
<|endoftext|>


<commit_before>// Copyright 2010-2014 RethinkDB, all rights reserved.
#include "clustering/administration/main/version_check.hpp"

#include <map>
#include <math.h>

#include "logger.hpp"

#include "clustering/administration/metadata.hpp"
#include "extproc/http_runner.hpp"
#include "rdb_protocol/env.hpp"

namespace ql {
void dispatch_http(ql::env_t *env,
                   const http_opts_t &opts,
                   http_runner_t *runner,
                   http_result_t *res_out,
                   const ql::pb_rcheckable_t *parent);
};

static const int64_t day_in_ms = 24 * 60 * 60 * 1000;

version_checker_t::version_checker_t(rdb_context_t *_rdb_ctx,
                                     version_checker_t::metadata_ptr_t _metadata,
                                     const std::string &_uname) :
    rdb_ctx(_rdb_ctx),
    seen_version(),
    metadata(_metadata),
    uname(_uname),
    timer(day_in_ms, this) {
    rassert(rdb_ctx != NULL);
    coro_t::spawn_sometime(std::bind(&version_checker_t::do_check,
                                     this, true, drainer.lock()));
}

template <typename K, typename V>
size_t count_not_deleted(std::map<K, deletable_t<V> > const &map) {
    size_t count = 0;

    for (const auto &pair : map) {
        if (!pair.second.is_deleted()) {
            count++;
        }
    }

    return count;
}

void version_checker_t::do_check(bool is_initial, auto_drainer_t::lock_t keepalive) {
    const cluster_semilattice_metadata_t snapshot = metadata->get();
    ql::env_t env(rdb_ctx,
                  ql::return_empty_normal_batches_t::NO,
                  keepalive.get_drain_signal(),
                  std::map<std::string, ql::wire_func_t>(),
                  nullptr);
    http_opts_t opts;
    opts.limits = env.limits();
    opts.result_format = http_result_format_t::JSON;
    if (is_initial) {
        opts.url = strprintf("http://update.rethinkdb.com/update_for/%s",
                             RETHINKDB_VERSION);
    } else {
        opts.method = http_method_t::POST;
        opts.url = "http://update.rethinkdb.com/checkin";
        opts.header.push_back("Content-Type: application/x-www-form-urlencoded");
        opts.form_data["Version"] = RETHINKDB_VERSION;
        opts.form_data["Number-Of-Servers"]
            = strprintf("%zu", count_not_deleted(snapshot.servers.servers));
        opts.form_data["Uname"] = uname;
        opts.form_data["Cooked-Number-Of-Tables"]
            = strprintf("%" PR_RECONSTRUCTABLE_DOUBLE,
                        cook(count_not_deleted(snapshot.rdb_namespaces->namespaces)));
        //opts.form_data["Cooked-Size-Of-Shards"]
        //    = strprintf("%" PR_RECONSTRUCTABLE_DOUBLE, cook(0.0)); // XXX
    }

    http_runner_t runner(env.get_extproc_pool());
    http_result_t result;

    try {
        dispatch_http(&env, opts, &runner, &result, nullptr);
    } catch (const ql::base_exc_t &ex) {
        logWRN("Problem when checking for new versions of RethinkDB: HTTP request to "
            "update.rethinkdb.com failed.");
        logDBG("%s", ex.what());
        return;
    }

    try {
        process_result(result);
    } catch (const ql::base_exc_t &ex) {
        logWRN("Problem when checking for new versions of RethinkDB: "
            "update.rethinkdb.com returned an invalid result.");
        logDBG("Result body: %s\nHeaders: %s\nError message: %s",
            result.body.trunc_print().c_str(), result.header.trunc_print().c_str(),
            ex.what());
    }
}

// sort of anonymize the input; specifically we want $2^(round(log_2(n)))$
double version_checker_t::cook(double n) {
    return exp2(round(log2(n)));
}

void version_checker_t::process_result(const http_result_t &result) {
    rcheck_datum(result.error.empty(), ql::base_exc_t::GENERIC,
        strprintf("protocol error: %s", result.error.c_str()));
    rcheck_datum(result.body.has(), ql::base_exc_t::GENERIC,
        "no body returned");

    ql::datum_t status = result.body.get_field("status", ql::THROW);
    const datum_string_t &str = status.as_str();
    if (str == "ok") {
        logDBG("Finished checking for newer versions of RethinkDB. We are already "
            "running the most up-to-date version.");
    } else if (str == "error") {
        ql::datum_t reason = result.body.get_field("error", ql::THROW);
        rfail_datum(ql::base_exc_t::GENERIC,
            "update server reports error: %s", reason.as_str().to_std().c_str());
    } else if (str == "need_update") {
        ql::datum_t new_version_datum = result.body.get_field("last_version", ql::THROW);
        datum_string_t new_version = new_version_datum.as_str();
        if (seen_version != new_version) {
            ql::datum_t changelog = result.body.get_field("link_changelog", ql::NOTHROW);
            std::string changelog_msg;
            if (changelog.has() && changelog.get_type() == ql::datum_t::R_STR) {
                changelog_msg = strprintf(" You can read the changelog at <%s>.",
                    changelog.as_str().to_std().c_str());
            }
            logNTC("A newer version of the RethinkDB server is available: %s.%s",
                new_version.to_std().c_str(), changelog_msg.c_str());
            seen_version = new_version;
        } else {
            // already logged an update for that version, so no point
            // in spamming them.
            logDBG("Finished checking for newer versions of RethinkDB. No new versions "
                "are available since we last checked.");
        }
    } else {
        rfail_datum(ql::base_exc_t::GENERIC, "unexpected status code");
    }
}
<commit_msg>Fixes review feedback<commit_after>// Copyright 2010-2014 RethinkDB, all rights reserved.
#include "clustering/administration/main/version_check.hpp"

#include <map>
#include <math.h>

#include "logger.hpp"

#include "clustering/administration/metadata.hpp"
#include "extproc/http_runner.hpp"
#include "rdb_protocol/env.hpp"

namespace ql {
void dispatch_http(ql::env_t *env,
                   const http_opts_t &opts,
                   http_runner_t *runner,
                   http_result_t *res_out,
                   const ql::pb_rcheckable_t *parent);
};

static const int64_t day_in_ms = 24 * 60 * 60 * 1000;

version_checker_t::version_checker_t(rdb_context_t *_rdb_ctx,
                                     version_checker_t::metadata_ptr_t _metadata,
                                     const std::string &_uname) :
    rdb_ctx(_rdb_ctx),
    seen_version(),
    metadata(_metadata),
    uname(_uname),
    timer(day_in_ms, this) {
    rassert(rdb_ctx != NULL);
    coro_t::spawn_sometime(std::bind(&version_checker_t::do_check,
                                     this, true, drainer.lock()));
}

template <typename K, typename V>
size_t count_non_deleted(std::map<K, deletable_t<V> > const &map) {
    size_t count = 0;

    for (const auto &pair : map) {
        if (!pair.second.is_deleted()) {
            count++;
        }
    }

    return count;
}

void version_checker_t::do_check(bool is_initial, auto_drainer_t::lock_t keepalive) {
    const cluster_semilattice_metadata_t snapshot = metadata->get();
    ql::env_t env(rdb_ctx,
                  ql::return_empty_normal_batches_t::NO,
                  keepalive.get_drain_signal(),
                  std::map<std::string, ql::wire_func_t>(),
                  nullptr);
    http_opts_t opts;
    opts.limits = env.limits();
    opts.result_format = http_result_format_t::JSON;
    if (is_initial) {
        opts.url = strprintf("http://update.rethinkdb.com/update_for/%s",
                             RETHINKDB_VERSION);
    } else {
        opts.method = http_method_t::POST;
        opts.url = "http://update.rethinkdb.com/checkin";
        opts.header.push_back("Content-Type: application/x-www-form-urlencoded");
        opts.form_data["Version"] = RETHINKDB_VERSION;
        opts.form_data["Number-Of-Servers"]
            = strprintf("%zu", count_non_deleted(snapshot.servers.servers));
        opts.form_data["Uname"] = uname;
        opts.form_data["Cooked-Number-Of-Tables"]
            = strprintf("%" PR_RECONSTRUCTABLE_DOUBLE,
                        cook(count_non_deleted(snapshot.rdb_namespaces->namespaces)));
        //opts.form_data["Cooked-Size-Of-Shards"]
        //    = strprintf("%" PR_RECONSTRUCTABLE_DOUBLE, cook(0.0)); // XXX
    }

    http_runner_t runner(env.get_extproc_pool());
    http_result_t result;

    try {
        dispatch_http(&env, opts, &runner, &result, nullptr);
    } catch (const ql::base_exc_t &ex) {
        logWRN("Problem when checking for new versions of RethinkDB: HTTP request to "
            "update.rethinkdb.com failed.");
        logDBG("%s", ex.what());
        return;
    }

    try {
        process_result(result);
    } catch (const ql::base_exc_t &ex) {
        logWRN("Problem when checking for new versions of RethinkDB: "
            "update.rethinkdb.com returned an invalid result.");
        logDBG("Result body: %s\nHeaders: %s\nError message: %s",
            result.body.trunc_print().c_str(), result.header.trunc_print().c_str(),
            ex.what());
    }
}

// sort of anonymize the input; specifically we want $2^(round(log_2(n)))$
double version_checker_t::cook(double n) {
    return exp2(round(log2(n)));
}

void version_checker_t::process_result(const http_result_t &result) {
    rcheck_datum(result.error.empty(), ql::base_exc_t::GENERIC,
        strprintf("protocol error: %s", result.error.c_str()));
    rcheck_datum(result.body.has(), ql::base_exc_t::GENERIC,
        "no body returned");

    ql::datum_t status = result.body.get_field("status", ql::THROW);
    const datum_string_t &str = status.as_str();
    if (str == "ok") {
        logDBG("Finished checking for newer versions of RethinkDB. We are already "
            "running the most up-to-date version.");
    } else if (str == "error") {
        ql::datum_t reason = result.body.get_field("error", ql::THROW);
        rfail_datum(ql::base_exc_t::GENERIC,
            "update server reports error: %s", reason.as_str().to_std().c_str());
    } else if (str == "need_update") {
        ql::datum_t new_version_datum = result.body.get_field("last_version", ql::THROW);
        datum_string_t new_version = new_version_datum.as_str();
        if (seen_version != new_version) {
            ql::datum_t changelog = result.body.get_field("link_changelog", ql::NOTHROW);
            std::string changelog_msg;
            if (changelog.has() && changelog.get_type() == ql::datum_t::R_STR) {
                changelog_msg = strprintf(" You can read the changelog at <%s>.",
                    changelog.as_str().to_std().c_str());
            }
            logNTC("A newer version of the RethinkDB server is available: %s.%s",
                new_version.to_std().c_str(), changelog_msg.c_str());
            seen_version = new_version;
        } else {
            // already logged an update for that version, so no point
            // in spamming them.
            logDBG("Finished checking for newer versions of RethinkDB. No new versions "
                "are available since we last checked.");
        }
    } else {
        rfail_datum(ql::base_exc_t::GENERIC, "unexpected status code");
    }
}
<|endoftext|>


<commit_before>// ConsoleRPG.cpp : Defines the entry point for the console application.
// Created by Nick Mullally a.k.a. thakyZ / Nire Inicana
//

#include "stdafx.h"
#include <iostream>
#include <cstdlib>
#include "time.h"
using namespace std;

// Roll the dice.
int diceRoll(int qty, int sides)
{
	int subTotal = 0; // Dice addition subtotal.
	// Roll the dice.

	// Loop to roll the dice
	for (int i = 0; i < qty; i++)
	{
		int currentRoll = rand() % sides + 1;
		subTotal += currentRoll;
	}

	return subTotal;
}

// Race Choices
enum RACE {HUMAN, ELF, DARKELF, ANGEL, MONGREL, SHAMANI, NIBELUNG, UNDEAD};

// Stats Tree
struct ATTRIBUTES
{
	unsigned int strength;
	unsigned int faith;
	unsigned int dexterity;
	unsigned int insperation;
	unsigned int cleverness;
	unsigned int focus;
};

// Startup
int _tmain(int argc, _TCHAR* argv[])
{
	srand(time(NULL));

	RACE inputRace; // The race that is chosen.
	char inputs; // The input to choose the race.
	ATTRIBUTES tempStats; // The stats the player gets by random.

	cout << diceRoll(20, 86) << "\n";

	cout << "Welcome to Zoro\n";

	cout << "Please Select a Race:\n";
	cout << "[H]uman [E]lf [D]ark elf [A]ngel [M]ongrel [S]hamani [N]ibelung [U]ndead\n";

	// The input for the chosen race.
	cin >> inputs;

	switch (inputs)
	{
		case 'h':
		case 'H':
			cout << "Human\n";
			inputRace = HUMAN;
			break;
		case 'e':
		case 'E':
			cout << "Elf\n";
			inputRace = ELF;
			break;
		case 'd':
		case 'D':
			cout << "Dark Elf\n";
			inputRace = DARKELF;
			break;
		case 'a':
		case 'A':
			cout << "Angel\n";
			inputRace = ANGEL;
			break;
		case 'm':
		case 'M':
			cout << "Mongrel\n";
			inputRace = MONGREL;
			break;
		case 's':
		case 'S':
			cout << "Shamani\n";
			inputRace = SHAMANI;
			break;
		case 'n':
		case 'N':
			cout << "Nibelung\n";
			inputRace = NIBELUNG;
			break;
		case 'u':
		case 'U':
			cout << "Undead\n";
			inputRace = UNDEAD;
			break;
		default:
			break;
	}

	return 0;
}<commit_msg>Changed name of village<commit_after>// ConsoleRPG.cpp : Defines the entry point for the console application.
// Created by Nick Mullally a.k.a. thakyZ / Nire Inicana
//

#include "stdafx.h"
#include <iostream>
#include <cstdlib>
#include "time.h"
using namespace std;

// Roll the dice.
int diceRoll(int qty, int sides)
{
	int subTotal = 0; // Dice addition subtotal.
	// Roll the dice.

	// Loop to roll the dice
	for (int i = 0; i < qty; i++)
	{
		int currentRoll = rand() % sides + 1;
		subTotal += currentRoll;
	}

	return subTotal;
}

// Race Choices
enum RACE {HUMAN, ELF, DARKELF, ANGEL, MONGREL, SHAMANI, NIBELUNG, UNDEAD};

// Stats Tree
struct ATTRIBUTES
{
	unsigned int strength;
	unsigned int faith;
	unsigned int dexterity;
	unsigned int insperation;
	unsigned int cleverness;
	unsigned int focus;
};

// Startup
int _tmain(int argc, _TCHAR* argv[])
{
	srand(time(NULL));

	RACE inputRace; // The race that is chosen.
	char inputs; // The input to choose the race.
	ATTRIBUTES tempStats; // The stats the player gets by random.

	cout << diceRoll(20, 86) << "\n";

	cout << "Welcome to Zorcan\n";

	cout << "Please Select a Race:\n";
	cout << "[H]uman [E]lf [D]ark elf [A]ngel [M]ongrel [S]hamani [N]ibelung [U]ndead\n";

	// The input for the chosen race.
	cin >> inputs;

	switch (inputs)
	{
		case 'h':
		case 'H':
			cout << "Human\n";
			inputRace = HUMAN;
			break;
		case 'e':
		case 'E':
			cout << "Elf\n";
			inputRace = ELF;
			break;
		case 'd':
		case 'D':
			cout << "Dark Elf\n";
			inputRace = DARKELF;
			break;
		case 'a':
		case 'A':
			cout << "Angel\n";
			inputRace = ANGEL;
			break;
		case 'm':
		case 'M':
			cout << "Mongrel\n";
			inputRace = MONGREL;
			break;
		case 's':
		case 'S':
			cout << "Shamani\n";
			inputRace = SHAMANI;
			break;
		case 'n':
		case 'N':
			cout << "Nibelung\n";
			inputRace = NIBELUNG;
			break;
		case 'u':
		case 'U':
			cout << "Undead\n";
			inputRace = UNDEAD;
			break;
		default:
			break;
	}

	return 0;
}<|endoftext|>


<commit_before>#ifndef STAN_MATH_REV_FUN_NORM2_HPP
#define STAN_MATH_REV_FUN_NORM2_HPP

#include <stan/math/rev/meta.hpp>
#include <stan/math/rev/core.hpp>
#include <stan/math/rev/core/typedefs.hpp>
#include <stan/math/prim/err.hpp>
#include <stan/math/prim/fun/Eigen.hpp>
#include <stan/math/prim/fun/sign.hpp>

namespace stan {
namespace math {

/**
 * Returns the L2 norm of a vector of var.
 *
 * @tparam T type of the vector (must have one compile-time dimension equal to
 * 1)
 * @param[in] v Vector.
 * @return L2 norm of v.
 */
template <typename T, require_eigen_vector_vt<is_var, T>* = nullptr>
inline var norm2(const T& v) {
  arena_t<T> arena_v = v;
  var res = norm2(arena_v.val());
  reverse_pass_callback([res, arena_v]() mutable {
    arena_v.adj().array() += res.adj() * (arena_v.val().array() / res.val());
  });
  return res;
}

/**
 * Returns the L2 norm of a `var_value<Vector>`.
 *
 * @tparam A `var_value<>` whose inner type has one compile-time row or column.
 * @param[in] v Vector.
 * @return L2 norm of v.
 */
template <typename T, require_var_matrix_t<T>* = nullptr>
inline var norm2(const T& v) {
  return make_callback_vari(norm2(v.val()), [v](const auto& res) mutable{
    v.adj().array() += res.adj() * (v.val().array() / res.val());
  });
}

}  // namespace math
}  // namespace stan
#endif
<commit_msg>[Jenkins] auto-formatting by clang-format version 6.0.0-1ubuntu2~16.04.1 (tags/RELEASE_600/final)<commit_after>#ifndef STAN_MATH_REV_FUN_NORM2_HPP
#define STAN_MATH_REV_FUN_NORM2_HPP

#include <stan/math/rev/meta.hpp>
#include <stan/math/rev/core.hpp>
#include <stan/math/rev/core/typedefs.hpp>
#include <stan/math/prim/err.hpp>
#include <stan/math/prim/fun/Eigen.hpp>
#include <stan/math/prim/fun/sign.hpp>

namespace stan {
namespace math {

/**
 * Returns the L2 norm of a vector of var.
 *
 * @tparam T type of the vector (must have one compile-time dimension equal to
 * 1)
 * @param[in] v Vector.
 * @return L2 norm of v.
 */
template <typename T, require_eigen_vector_vt<is_var, T>* = nullptr>
inline var norm2(const T& v) {
  arena_t<T> arena_v = v;
  var res = norm2(arena_v.val());
  reverse_pass_callback([res, arena_v]() mutable {
    arena_v.adj().array() += res.adj() * (arena_v.val().array() / res.val());
  });
  return res;
}

/**
 * Returns the L2 norm of a `var_value<Vector>`.
 *
 * @tparam A `var_value<>` whose inner type has one compile-time row or column.
 * @param[in] v Vector.
 * @return L2 norm of v.
 */
template <typename T, require_var_matrix_t<T>* = nullptr>
inline var norm2(const T& v) {
  return make_callback_vari(norm2(v.val()), [v](const auto& res) mutable {
    v.adj().array() += res.adj() * (v.val().array() / res.val());
  });
}

}  // namespace math
}  // namespace stan
#endif
<|endoftext|>


<commit_before>#pragma once
//=====================================================================//
/*!	@file
	@brief	RX600 グループ・TPU I/O 制御
    @author 平松邦仁 (hira@rvf-rc45.net)
	@copyright	Copyright (C) 2017 Kunihito Hiramatsu @n
				Released under the MIT license @n
				https://github.com/hirakuni45/RX/blob/master/LICENSE
*/
//=====================================================================//
#include "common/renesas.hpp"
#include "common/intr_utils.hpp"
#include "common/vect.h"

/// F_PCLKB は周期パラメーター計算で必要で、設定が無いとエラーにします。
#ifndef F_PCLKB
#  error "tpu_io.hpp requires F_PCLKB to be defined"
#endif

namespace device {

	//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
	/*!
		@brief  TPU I/O クラス
		@param[in]	TPU	チャネルクラス
		@param[in]	TASK	タイマー動作クラス
	*/
	//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
	template <class TPU, class TASK = utils::null_task>
	class tpu_io {

		uint8_t		level_;

		static volatile uint32_t counter_;

		static TASK	task_;

		static INTERRUPT_FUNC void tpu_task_() {
			if(TPU::TSR.TGFA()) TPU::TSR.TGFA = 0;
			++counter_;
			task_();
		}

		void sleep_() const { asm("nop"); }

	public:
		//-----------------------------------------------------------------//
		/*!
			@brief  コンストラクター
		*/
		//-----------------------------------------------------------------//
		tpu_io() : level_(0) { }

		//-----------------------------------------------------------------//
		/*!
			@brief  動作開始
			@param[in]	freq	タイマー周波数
			@param[in]	level	割り込みレベル（０ならポーリング）
			@return レンジオーバーなら「false」を返す
		*/
		//-----------------------------------------------------------------//
		bool start(uint32_t freq, uint8_t level = 0)
		{
			if(freq == 0) return false;

			level_ = level;

			uint32_t cmt = F_PCLKB / freq;

			uint8_t cks = 0;
			while(cmt > 65536) {
				cmt >>= 1;
				++cks;
			}

			// プリスケーラーの算出 cks
			// 1: 1/2, 2: 1/4, 3: 1/8, ...
			// TPU0: 1/1(0), 1/4(2), 1/16(4), 1/64(6)
			uint8_t prs = 0;
			switch(cks) {
			case 0:
				break;
			case 1:
				cmt >>= 1;
			case 2:
				prs = 1;
				break;
			case 3:
				cmt >>= 1;
			case 4:
				prs = 2;
				break;
			case 5:
				cmt >>= 1;
			case 6:
				prs = 3;
				break;
			default:
				return false;
				break;
			}

			power_cfg::turn(TPU::get_peripheral());

			TPU::TCR = TPU::TCR.CCLR.b(1) | TPU::TCR.TPSC.b(prs);  // TGRA のコンペアマッチ
			if(cmt > 0) cmt--;
			TPU::TGRA = cmt;
			TPU::TCNT = 0x0000;

			if(level_ > 0) {  // 割り込み設定
#if (defined(SIG_RX64M) || defined(SIG_RX71M))
				set_interrupt_task(tpu_task_, static_cast<uint32_t>(ICU::VECTOR::INTB128));
				ICU::SLIBXR128 = TPU::get_TGIA();
				ICU::IPR.INTB128 = level_;
				ICU::IER.INTB128 = true;
#endif
				TPU::TIER.TGIEA = 1;  // TGRA interrupt
			} else {
				TPU::TIER.TGIEA = 0;
			}

			TPU::enable();

			return true;
		}

		//-----------------------------------------------------------------//
		/*!
			@brief  タイマー同期
		*/
		//-----------------------------------------------------------------//
		void sync() const
		{
			if(level_ > 0) {
				volatile uint32_t cnt = counter_;
				while(cnt == counter_) sleep_();
			} else {
				while(TPU::TSR.TGFA() == 0) sleep_();
				TPU::TSR.TGFA = 0;
				task_();
				++counter_;
			}
		}

		//-----------------------------------------------------------------//
		/*!
			@brief  割り込みカウンターの値を取得
			@return 割り込みカウンターの値
		*/
		//-----------------------------------------------------------------//
		uint32_t get_counter() const { return counter_; }

		//-----------------------------------------------------------------//
		/*!
			@brief  TCNT レジスターの値を取得
			@return TCNT レジスター
		*/
		//-----------------------------------------------------------------//
		uint16_t get_tcnt_count() const { return TPU::TCNT(); }

		//-----------------------------------------------------------------//
		/*!
			@brief  TASK クラスの参照
			@return TASK クラス
		*/
		//-----------------------------------------------------------------//
		static TASK& at_task() { return task_; }
	};

	template <class TPU, class TASK> volatile uint32_t tpu_io<TPU, TASK>::counter_ = 0;
	template <class TPU, class TASK> TASK tpu_io<TPU, TASK>::task_;
}
<commit_msg>add destroy API<commit_after>#pragma once
//=====================================================================//
/*!	@file
	@brief	RX600 グループ・TPU I/O 制御
    @author 平松邦仁 (hira@rvf-rc45.net)
	@copyright	Copyright (C) 2017 Kunihito Hiramatsu @n
				Released under the MIT license @n
				https://github.com/hirakuni45/RX/blob/master/LICENSE
*/
//=====================================================================//
#include "common/renesas.hpp"
#include "common/intr_utils.hpp"
#include "common/vect.h"

/// F_PCLKB は周期パラメーター計算で必要で、設定が無いとエラーにします。
#ifndef F_PCLKB
#  error "tpu_io.hpp requires F_PCLKB to be defined"
#endif

namespace device {

	//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
	/*!
		@brief  TPU I/O クラス
		@param[in]	TPU	チャネルクラス
		@param[in]	TASK	タイマー動作クラス
	*/
	//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
	template <class TPU, class TASK = utils::null_task>
	class tpu_io {

		uint8_t		level_;

		static volatile uint32_t counter_;

		static TASK	task_;

		static INTERRUPT_FUNC void tpu_task_() {
			if(TPU::TSR.TGFA()) TPU::TSR.TGFA = 0;
			++counter_;
			task_();
		}

		void sleep_() const { asm("nop"); }

	public:
		//-----------------------------------------------------------------//
		/*!
			@brief  コンストラクター
		*/
		//-----------------------------------------------------------------//
		tpu_io() : level_(0) { }

		//-----------------------------------------------------------------//
		/*!
			@brief  動作開始
			@param[in]	freq	タイマー周波数
			@param[in]	level	割り込みレベル（０ならポーリング）
			@return レンジオーバーなら「false」を返す
		*/
		//-----------------------------------------------------------------//
		bool start(uint32_t freq, uint8_t level = 0)
		{
			if(freq == 0) return false;

			level_ = level;

			uint32_t cmt = F_PCLKB / freq;

			uint8_t shift = 0;
			while(cmt > 65536) {
				cmt >>= 1;
				++shift;
			}

			// プリスケーラーの算出と指定 (shift)
			// 1: 1/2, 2: 1/4, 3: 1/8, ...
			// TPU0: 1/1(0), 1/4(2), 1/16(4), 1/64(6)
			// TPU1: 1/1(0), 1/4(2), 1/16(4), 1/64(6), 1/256(8)
 			// TPU2: 1/1(0), 1/4(2), 1/16(4), 1/64(6), 1/1024(10)
 			// TPU3: 1/1(0), 1/4(2), 1/16(4), 1/64(6), 1/256(8), 1/1024(10), 1/4096(12)
			// TPU4: 1/1(0), 1/4(2), 1/16(4), 1/64(6), 1/1024(10)
			// TPU5: 1/1(0), 1/4(2), 1/16(4), 1/64(6), 1/256(8)
			uint8_t tpsc = 0;
			switch(shift) {
			case 0:
				break;
			case 1:
				cmt >>= 1;
			case 2:
				tpsc = 1;
				break;
			case 3:
				cmt >>= 1;
			case 4:
				tpsc = 2;
				break;
			case 5:
				cmt >>= 1;
			case 6:
				tpsc = 3;
				break;
			default:
				return false;
				break;
			}

			power_cfg::turn(TPU::get_peripheral());

			TPU::TCR = TPU::TCR.CCLR.b(1) | TPU::TCR.TPSC.b(tpsc);  // TGRA のコンペアマッチ
			if(cmt > 0) cmt--;
			TPU::TGRA = cmt;
			TPU::TCNT = 0x0000;

			if(level_ > 0) {  // 割り込み設定
#if (defined(SIG_RX64M) || defined(SIG_RX71M))
				set_interrupt_task(tpu_task_, static_cast<uint32_t>(ICU::VECTOR::INTB128));
				ICU::SLIBXR128 = TPU::get_TGIA();
				ICU::IPR.INTB128 = level_;
				ICU::IER.INTB128 = true;
#endif
				TPU::TIER.TGIEA = 1;  // TGRA interrupt
			} else {
				TPU::TIER.TGIEA = 0;
			}

			TPU::enable();

			return true;
		}

		//-----------------------------------------------------------------//
		/*!
			@brief  廃棄
		*/
		//-----------------------------------------------------------------//
		void destroy()
		{
			TPU::TIER = 0;
			TPU::enable(false);
			power_cfg::turn(TPU::get_peripheral(), false);
		}

		//-----------------------------------------------------------------//
		/*!
			@brief  タイマー同期
		*/
		//-----------------------------------------------------------------//
		void sync() const
		{
			if(level_ > 0) {
				volatile uint32_t cnt = counter_;
				while(cnt == counter_) sleep_();
			} else {
				while(TPU::TSR.TGFA() == 0) sleep_();
				TPU::TSR.TGFA = 0;
				task_();
				++counter_;
			}
		}

		//-----------------------------------------------------------------//
		/*!
			@brief  割り込みカウンターの値を取得
			@return 割り込みカウンターの値
		*/
		//-----------------------------------------------------------------//
		uint32_t get_counter() const { return counter_; }

		//-----------------------------------------------------------------//
		/*!
			@brief  TCNT レジスターの値を取得
			@return TCNT レジスター
		*/
		//-----------------------------------------------------------------//
		uint16_t get_tcnt_count() const { return TPU::TCNT(); }

		//-----------------------------------------------------------------//
		/*!
			@brief  TASK クラスの参照
			@return TASK クラス
		*/
		//-----------------------------------------------------------------//
		static TASK& at_task() { return task_; }
	};

	template <class TPU, class TASK> volatile uint32_t tpu_io<TPU, TASK>::counter_ = 0;
	template <class TPU, class TASK> TASK tpu_io<TPU, TASK>::task_;
}
<|endoftext|>


<commit_before>/*

DAcase2.c

This program connects to the DAQ data source passed as argument
and populates local "./result.txt" file with the ids of events received
during the run.

The program exits when being asked to shut down (daqDA_checkshutdown)
or End of Run event.

Messages on stdout are exported to DAQ log system.

contact: alice-datesupport@cern.ch

*/

#include "event.h"
#include "monitor.h"
extern "C" {
#include "daqDA.h"
}

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

#include <TSystem.h>

#include "AliRawReader.h"
#include "AliRawReaderDate.h"
#include "AliPHOSDA2.h"
#include "AliPHOSRawDecoderv1.h"
#include "AliCaloAltroMapping.h"

/* Main routine
      Arguments:
      1- monitoring data source
*/
int main(int argc, char **argv) {

  int status;

  if (argc!=2) {
    printf("Wrong number of arguments\n");
    return -1;
  }

  /* open result file */
  FILE *fp=NULL;
  fp=fopen("./result.txt","a");
  if (fp==NULL) {
    printf("Failed to open file\n");
    return -1;
  }

  /* Open mapping files */
  AliAltroMapping *mapping[4];
  TString path = gSystem->Getenv("ALICE_ROOT");
  path += "/PHOS/mapping/RCU";
  TString path2;
  for(Int_t i = 0; i < 4; i++) {
    path2 = path;
    path2 += i;
    path2 += ".data";
    mapping[i] = new AliCaloAltroMapping(path2.Data());
  }

  /* define data source : this is argument 1 */
  status=monitorSetDataSource( argv[1] );
  if (status!=0) {
    printf("monitorSetDataSource() failed : %s\n",monitorDecodeError(status));
    return -1;
  }

  /* declare monitoring program */
  status=monitorDeclareMp( __FILE__ );
  if (status!=0) {
    printf("monitorDeclareMp() failed : %s\n",monitorDecodeError(status));
    return -1;
  }

  /* define wait event timeout - 1s max */
  monitorSetNowait();
  monitorSetNoWaitNetworkTimeout(1000);

  /* log start of process */
  printf("DA2 (bad channels finding) started.\n");

  /* init some counters */
  int nevents_physics=0;
  int nevents_total=0;

  AliRawReader *rawReader = NULL;

  AliPHOSDA2 da2(2); // DA2 ("Checking for bad channels") for module2

  Float_t q[64][56][2];

  Int_t gain = -1;
  Int_t X = -1;
  Int_t Z = -1;

  /* main loop (infinite) */
  for(;;) {
    struct eventHeaderStruct *event;
    eventTypeType eventT;

    /* check shutdown condition */
    if (daqDA_checkShutdown()) {break;}

    /* get next event (blocking call until timeout) */
    status=monitorGetEventDynamic((void **)&event);
    if (status==MON_ERR_EOF) {
      printf ("End of File detected\n");
      break; /* end of monitoring file has been reached */
    }

    if (status!=0) {
      printf("monitorGetEventDynamic() failed : %s\n",monitorDecodeError(status));
      break;
    }

    /* retry if got no event */
    if (event==NULL) {
      continue;
    }

    /* use event - here, just write event id to result file */
    eventT=event->eventType;

    if (eventT==PHYSICS_EVENT) {
      fprintf(fp,"Run #%lu, event size: %lu, BC:%u, Orbit:%u, Period:%u\n",
	  (unsigned long)event->eventRunNb,
        (unsigned long)event->eventSize,
        EVENT_ID_GET_BUNCH_CROSSING(event->eventId),
        EVENT_ID_GET_ORBIT(event->eventId),
        EVENT_ID_GET_PERIOD(event->eventId)
      );

      for(Int_t iX=0; iX<64; iX++) {
	for(Int_t iZ=0; iZ<56; iZ++) {
	  for(Int_t iGain=0; iGain<2; iGain++) {
	    q[iX][iZ][iGain] = 0.;
	  }
	}
      }

      rawReader = new AliRawReaderDate((void*)event);
      AliPHOSRawDecoderv1 dc(rawReader,mapping);
      dc.SubtractPedestals(kTRUE);

      while(dc.NextDigit()) {

	X = dc.GetRow() - 1;
	Z = dc.GetColumn() - 1;

	if(dc.IsLowGain()) gain = 0;
	else
	  gain = 1;

	q[X][Z][gain] = dc.GetSampleQuality();

      }

      da2.FillQualityHistograms(q);
      //da1.UpdateHistoFile();

      delete rawReader;
      nevents_physics++;
    }

    nevents_total++;

    /* free resources */
    free(event);

    /* exit when last event received, no need to wait for TERM signal */
    if (eventT==END_OF_RUN) {
      printf("EOR event detected\n");
      break;
    }
  }

  for(Int_t i = 0; i < 4; i++) delete mapping[i];

  /* write report */
  fprintf(fp,"Run #%s, received %d physics events out of %d\n",getenv("DATE_RUN_NUMBER"),nevents_physics,nevents_total);

  /* close result file */
  fclose(fp);

  return status;
}
<commit_msg>PHOSda2.cxx is renamed to PHOSDA2da.cxx<commit_after><|endoftext|>


<commit_before>/*
 * DistSCM.cc
 *
 * Copyright (C) 2015 OpenCog Foundation
 *
 * Author: Mandeep Singh Bhatia, September 2015
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License v3 as
 * published by the Free Software Foundation and including the exceptions
 * at http://opencog.org/wiki/Licenses
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program; if not, write to:
 * Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
 */

#include <string>
#include <libgearman/gearman.h>

#include <opencog/guile/SchemeEval.h>
#include <opencog/guile/SchemeModule.h>
#include <opencog/guile/SchemePrimitive.h>
#include <opencog/guile/SchemeSmob.h>

namespace opencog {

class DistSCM : public ModuleWrap
{
private:
	void init(void);

	/// All threads will keep handling work until this is set to false.
	static bool keep_working;
	void exit_all_workers(void);

	std::string start_work_handler(const std::string& ipaddr_string,
	                               const std::string& workerID);
	std::string dist_eval(const std::string& work_string,
	                      const std::string& clientID);

	// XXX FIXME -- a single client and worker? This cannot be right!
	gearman_client_st client;
	gearman_worker_st *worker;
	static gearman_return_t worker_function(gearman_job_st *job, void *context);

public:
	DistSCM(void);
	~DistSCM();
};

} // namespace opencog

#define DEBUG 1
using namespace opencog;

bool DistSCM::keep_working = true;

DistSCM::DistSCM(void) : ModuleWrap("opencog dist-gearman")
{}

void DistSCM::init(void)
{
	// Enter Blocking slave mode
	define_scheme_primitive("start-work-handler", &DistSCM::start_work_handler,
	                        this, "dist-gearman");

	// Exits the slave mode after last request is served
	define_scheme_primitive("exit-all-workers", &DistSCM::exit_all_workers,
	                        this, "dist-gearman");

	// Sends scheme string to worker and block until a result arrives.
	// Returns resulting scheme string.
	define_scheme_primitive("dist-eval", &DistSCM::dist_eval,
	                        this, "dist-gearman");
}

/// This method causes all worker threads to return to thier callers
/// after completing whatever work they are doing.
void DistSCM::exit_all_workers(void)
{
	keep_working = false;
}

gearman_return_t DistSCM::worker_function(gearman_job_st *job, void *context)
{
	const char *workload = (const char *)gearman_job_workload(job);

#ifdef DEBUG
	const size_t workload_size = gearman_job_workload_size(job);
	std::cout << "Dist worker recieved " << workload_size << " bytes" << std::endl;
	std::cout << "Dist worker job string is " << workload << std::endl;
#endif

	// All worker threads are sharing the same atomspace.
	// This seems like the right thing to do, I guess.
	AtomSpace* atomspace = (AtomSpace*) context;
	SchemeEval* evl = SchemeEval::get_evaluator(atomspace);
	Handle result = evl->eval_h(workload);

#ifdef DEBUG
	std::cout << "Dist worker work result is " << result;
#endif

	std::string reply = result->to_string();
	gearman_return_t rc = gearman_job_send_data(job, reply.c_str(), reply.length());

	if (gearman_failed(rc))
	{
		// On gearman error return, no result is sent to the client,
		// and the job request stays in queue.
		std::cerr << "Error: Gearman worker: Unable to send result\n";
		return GEARMAN_ERROR;
	}
	return GEARMAN_SUCCESS;
}

std::string false_string = "Oh Noooo, Mr. Bill!";

/// This method causes the current thread to enter an infinite
/// loop, waiting for job requests from clients.  This method
/// will not return, unless there is a Gearman error, or unless
/// the exit_all_handlers() method is called.
///
/// `ipaddr_string` is the IP address of the gearmand server to contact.
/// The default port number will be used.
std::string DistSCM::start_work_handler(const std::string& ipaddr_string,
                                        const std::string& workerID)
{
#ifdef DEBUG
	std::cout << "Dist start-work-handler ip=" <<  ipaddr_string
	          << " worker ID=" << workerID << std::endl;
#endif
	worker = gearman_worker_create(nullptr);
	if (nullptr == worker)
	{
		std::cerr << "Memory allocation failure on worker creation." << std::endl;
		throw RuntimeException(TRACE_INFO,
			"Gearman: Memory allocation failure on worker creation.");
	}

	gearman_worker_add_options(worker, GEARMAN_WORKER_GRAB_UNIQ);

	gearman_return_t rc;
	rc = gearman_worker_add_server(worker, ipaddr_string.c_str(),
	                               GEARMAN_DEFAULT_TCP_PORT);

	if (gearman_failed(rc))
	{
		std::cerr << gearman_worker_error(worker) << std::endl;
		throw RuntimeException(TRACE_INFO,
			"Gearman: %s", gearman_worker_error(worker));
	}

	rc = gearman_worker_set_identifier(worker,
                      workerID.c_str(), workerID.length());

	if (gearman_failed(rc))
	{
		std::cerr << gearman_worker_error(worker) << std::endl;
		throw RuntimeException(TRACE_INFO,
			"Gearman: %s", gearman_worker_error(worker));
	}

	gearman_function_t worker_fn = gearman_function_create(worker_function);

	// Get the atomspace for this thread.
	AtomSpace* atomspace = SchemeSmob::ss_get_env_as("start-work-handler");

	rc = gearman_worker_define_function(worker,
	                                    gearman_literal_param("make_call"),
	                                    worker_fn,
	                                    0,
	                                    atomspace);

	if (gearman_failed(rc))
	{
		std::cerr << gearman_worker_error(worker) << std::endl;
		throw RuntimeException(TRACE_INFO,
			"Gearman: %s", gearman_worker_error(worker));
	}

#ifdef DEBUG
	std::cout << "Dist start-work-handler enter main loop\n";
#endif
	// Timeout is in milliseconds. Set it to 1000 millsecs.
	// As a result, we will poll, once a second, and then
	// pop to back to the main loop, to see if we should halt,
	// or not.
	gearman_worker_set_timeout(worker, 1000);
	while (keep_working)
	{
		gearman_return_t rc = gearman_worker_work(worker);
		if (rc == GEARMAN_TIMEOUT) continue;

		if (gearman_failed(rc))
		{
			std::cerr << "Dist error: " << gearman_worker_error(worker) << std::endl;
			gearman_worker_free(worker);
			return false_string;
		}
	}

	gearman_worker_free(worker);

	return ipaddr_string;
}

/// Send the string `scm_string` (assumed to be a valid scheme expression)
/// to the gearmand server.  Wait for a reply, which will be (should be)
/// a valid scheme expression.
std::string DistSCM::dist_eval(const std::string& scm_string,
                               const std::string& clientID)
{
	gearman_client_st* clr;

	clr = gearman_client_create(&client);
	if (nullptr == clr)
	{
		std::cerr << "Memory allocation failure on client creation" << std::endl;
		throw RuntimeException(TRACE_INFO,
			"Gearman: Memory allocation failure on client creation");
	}

	int timeout=-1;
	if (timeout >= 0)
	{
		gearman_client_set_timeout(&client, timeout);
	}

	gearman_return_t rc = gearman_client_add_server(&client,
                              "localhost", GEARMAN_DEFAULT_TCP_PORT);
	if (rc != GEARMAN_SUCCESS)
	{
		std::cerr << gearman_client_error(&client);
		throw RuntimeException(TRACE_INFO,
			"Gearman: %s", gearman_client_error(&client));
	}

	rc = gearman_client_set_identifier(&client,
                               clientID.c_str(), clientID.length());
	if (gearman_failed(rc))
	{
		std::cerr << gearman_client_error(&client);
		throw RuntimeException(TRACE_INFO,
			"Gearman: %s", gearman_client_error(&client));
	}

	int exit_code = EXIT_SUCCESS;
	size_t result_size;
	char* result = (char*) gearman_client_do(&client, "make_call", NULL,
	                              scm_string.c_str(), scm_string.length()+1,
	                              &result_size, &rc);
	std::string work_result;
	if (rc == GEARMAN_WORK_DATA or rc == GEARMAN_SUCCESS)
	{
		work_result = result;
		free(result);
	}
	else if (rc == GEARMAN_WORK_STATUS)
	{
		uint32_t numerator;
		uint32_t denominator;

		gearman_client_do_status(&client, &numerator, &denominator);
		std::clog << "Status: " << numerator << "/" << denominator << std::endl;
	}
	else if (rc == GEARMAN_WORK_FAIL)
	{
		std::cerr << "Work failed";
		exit_code = EXIT_FAILURE;
	}
	else
	{
		std::cerr << gearman_client_error(&client);
		exit_code = EXIT_FAILURE;
	}

	gearman_client_free(&client);

	if (exit_code == EXIT_FAILURE) return "";

	return work_result;
}

DistSCM::~DistSCM()
{
}

extern "C" {
void opencog_dist_init(void);
};

void opencog_dist_init(void)
{
	static DistSCM gearman_dist;
	gearman_dist.module_init();
}
<commit_msg>gearman: fix uninited workers in DistSCM ctor<commit_after>/*
 * DistSCM.cc
 *
 * Copyright (C) 2015 OpenCog Foundation
 *
 * Author: Mandeep Singh Bhatia, September 2015
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License v3 as
 * published by the Free Software Foundation and including the exceptions
 * at http://opencog.org/wiki/Licenses
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program; if not, write to:
 * Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
 */

#include <string>
#include <libgearman/gearman.h>

#include <opencog/guile/SchemeEval.h>
#include <opencog/guile/SchemeModule.h>
#include <opencog/guile/SchemePrimitive.h>
#include <opencog/guile/SchemeSmob.h>

namespace opencog {

class DistSCM : public ModuleWrap
{
private:
	void init(void);

	/// All threads will keep handling work until this is set to false.
	static bool keep_working;
	void exit_all_workers(void);

	std::string start_work_handler(const std::string& ipaddr_string,
	                               const std::string& workerID);
	std::string dist_eval(const std::string& work_string,
	                      const std::string& clientID);

	// XXX FIXME -- a single client and worker? This cannot be right!
	gearman_client_st client;
	gearman_worker_st *worker;
	static gearman_return_t worker_function(gearman_job_st *job, void *context);

public:
	DistSCM(void);
	~DistSCM();
};

} // namespace opencog

#define DEBUG 1
using namespace opencog;

bool DistSCM::keep_working = true;

DistSCM::DistSCM(void) :
    ModuleWrap("opencog dist-gearman"),
    worker(nullptr)
{}

void DistSCM::init(void)
{
	// Enter Blocking slave mode
	define_scheme_primitive("start-work-handler", &DistSCM::start_work_handler,
	                        this, "dist-gearman");

	// Exits the slave mode after last request is served
	define_scheme_primitive("exit-all-workers", &DistSCM::exit_all_workers,
	                        this, "dist-gearman");

	// Sends scheme string to worker and block until a result arrives.
	// Returns resulting scheme string.
	define_scheme_primitive("dist-eval", &DistSCM::dist_eval,
	                        this, "dist-gearman");
}

/// This method causes all worker threads to return to thier callers
/// after completing whatever work they are doing.
void DistSCM::exit_all_workers(void)
{
	keep_working = false;
}

gearman_return_t DistSCM::worker_function(gearman_job_st *job, void *context)
{
	const char *workload = (const char *)gearman_job_workload(job);

#ifdef DEBUG
	const size_t workload_size = gearman_job_workload_size(job);
	std::cout << "Dist worker recieved " << workload_size << " bytes" << std::endl;
	std::cout << "Dist worker job string is " << workload << std::endl;
#endif

	// All worker threads are sharing the same atomspace.
	// This seems like the right thing to do, I guess.
	AtomSpace* atomspace = (AtomSpace*) context;
	SchemeEval* evl = SchemeEval::get_evaluator(atomspace);
	Handle result = evl->eval_h(workload);

#ifdef DEBUG
	std::cout << "Dist worker work result is " << result;
#endif

	std::string reply = result->to_string();
	gearman_return_t rc = gearman_job_send_data(job, reply.c_str(), reply.length());

	if (gearman_failed(rc))
	{
		// On gearman error return, no result is sent to the client,
		// and the job request stays in queue.
		std::cerr << "Error: Gearman worker: Unable to send result\n";
		return GEARMAN_ERROR;
	}
	return GEARMAN_SUCCESS;
}

std::string false_string = "Oh Noooo, Mr. Bill!";

/// This method causes the current thread to enter an infinite
/// loop, waiting for job requests from clients.  This method
/// will not return, unless there is a Gearman error, or unless
/// the exit_all_handlers() method is called.
///
/// `ipaddr_string` is the IP address of the gearmand server to contact.
/// The default port number will be used.
std::string DistSCM::start_work_handler(const std::string& ipaddr_string,
                                        const std::string& workerID)
{
#ifdef DEBUG
	std::cout << "Dist start-work-handler ip=" <<  ipaddr_string
	          << " worker ID=" << workerID << std::endl;
#endif
	worker = gearman_worker_create(nullptr);
	if (nullptr == worker)
	{
		std::cerr << "Memory allocation failure on worker creation." << std::endl;
		throw RuntimeException(TRACE_INFO,
			"Gearman: Memory allocation failure on worker creation.");
	}

	gearman_worker_add_options(worker, GEARMAN_WORKER_GRAB_UNIQ);

	gearman_return_t rc;
	rc = gearman_worker_add_server(worker, ipaddr_string.c_str(),
	                               GEARMAN_DEFAULT_TCP_PORT);

	if (gearman_failed(rc))
	{
		std::cerr << gearman_worker_error(worker) << std::endl;
		throw RuntimeException(TRACE_INFO,
			"Gearman: %s", gearman_worker_error(worker));
	}

	rc = gearman_worker_set_identifier(worker,
                      workerID.c_str(), workerID.length());

	if (gearman_failed(rc))
	{
		std::cerr << gearman_worker_error(worker) << std::endl;
		throw RuntimeException(TRACE_INFO,
			"Gearman: %s", gearman_worker_error(worker));
	}

	gearman_function_t worker_fn = gearman_function_create(worker_function);

	// Get the atomspace for this thread.
	AtomSpace* atomspace = SchemeSmob::ss_get_env_as("start-work-handler");

	rc = gearman_worker_define_function(worker,
	                                    gearman_literal_param("make_call"),
	                                    worker_fn,
	                                    0,
	                                    atomspace);

	if (gearman_failed(rc))
	{
		std::cerr << gearman_worker_error(worker) << std::endl;
		throw RuntimeException(TRACE_INFO,
			"Gearman: %s", gearman_worker_error(worker));
	}

#ifdef DEBUG
	std::cout << "Dist start-work-handler enter main loop\n";
#endif
	// Timeout is in milliseconds. Set it to 1000 millsecs.
	// As a result, we will poll, once a second, and then
	// pop to back to the main loop, to see if we should halt,
	// or not.
	gearman_worker_set_timeout(worker, 1000);
	while (keep_working)
	{
		gearman_return_t rc = gearman_worker_work(worker);
		if (rc == GEARMAN_TIMEOUT) continue;

		if (gearman_failed(rc))
		{
			std::cerr << "Dist error: " << gearman_worker_error(worker) << std::endl;
			gearman_worker_free(worker);
			return false_string;
		}
	}

	gearman_worker_free(worker);

	return ipaddr_string;
}

/// Send the string `scm_string` (assumed to be a valid scheme expression)
/// to the gearmand server.  Wait for a reply, which will be (should be)
/// a valid scheme expression.
std::string DistSCM::dist_eval(const std::string& scm_string,
                               const std::string& clientID)
{
	gearman_client_st* clr;

	clr = gearman_client_create(&client);
	if (nullptr == clr)
	{
		std::cerr << "Memory allocation failure on client creation" << std::endl;
		throw RuntimeException(TRACE_INFO,
			"Gearman: Memory allocation failure on client creation");
	}

	int timeout=-1;
	if (timeout >= 0)
	{
		gearman_client_set_timeout(&client, timeout);
	}

	gearman_return_t rc = gearman_client_add_server(&client,
                              "localhost", GEARMAN_DEFAULT_TCP_PORT);
	if (rc != GEARMAN_SUCCESS)
	{
		std::cerr << gearman_client_error(&client);
		throw RuntimeException(TRACE_INFO,
			"Gearman: %s", gearman_client_error(&client));
	}

	rc = gearman_client_set_identifier(&client,
                               clientID.c_str(), clientID.length());
	if (gearman_failed(rc))
	{
		std::cerr << gearman_client_error(&client);
		throw RuntimeException(TRACE_INFO,
			"Gearman: %s", gearman_client_error(&client));
	}

	int exit_code = EXIT_SUCCESS;
	size_t result_size;
	char* result = (char*) gearman_client_do(&client, "make_call", NULL,
	                              scm_string.c_str(), scm_string.length()+1,
	                              &result_size, &rc);
	std::string work_result;
	if (rc == GEARMAN_WORK_DATA or rc == GEARMAN_SUCCESS)
	{
		work_result = result;
		free(result);
	}
	else if (rc == GEARMAN_WORK_STATUS)
	{
		uint32_t numerator;
		uint32_t denominator;

		gearman_client_do_status(&client, &numerator, &denominator);
		std::clog << "Status: " << numerator << "/" << denominator << std::endl;
	}
	else if (rc == GEARMAN_WORK_FAIL)
	{
		std::cerr << "Work failed";
		exit_code = EXIT_FAILURE;
	}
	else
	{
		std::cerr << gearman_client_error(&client);
		exit_code = EXIT_FAILURE;
	}

	gearman_client_free(&client);

	if (exit_code == EXIT_FAILURE) return "";

	return work_result;
}

DistSCM::~DistSCM()
{
}

extern "C" {
void opencog_dist_init(void);
};

void opencog_dist_init(void)
{
	static DistSCM gearman_dist;
	gearman_dist.module_init();
}
<|endoftext|>


<commit_before>#ifndef BUW_SHAPE_HPP
#define BUW_SHAPE_HPP
#include <iostream>
#include <string>
#include "color.hpp"
#include "ray.hpp"
#include "material.hpp"

class Shape
{
public:
	/*
	Shape(): name_{""}, color_{0.0f, 0.0f, 0.0f}{}
	Shape(std::string name, Color const& color): name_{name}, color_{color} {}
	virtual ~Shape(){std::cout << "Shape Destructor" << std::endl;}
	~Shape(){std::cout << "Shape Destructor" << std::endl;}

	Shape(): name_{""}, material_{}{}
	Shape(std::string name, Material const& mat): name_{name}, material_{mat} {}
	Shape(std::string name, std::string name_mat, Color const& ka, Color const& kd, Color const& ks, float m): name_{name},
	material_{name_mat, ka, kd, ks, m} {}*/

	Shape(): name_{""}, matname_{""}{}
	Shape(std::string name, std::string material): name_{name}, matname_{material} {}

	virtual std::ostream& print(std::ostream& os) const{
		os << "Name: " << name_ << " Material: " << matname_ << std::endl;;
		return os;
	}

	std::string const& get_name()const{
		return name_;
	}

	std::string const& get_material()const{
		return matname_;
	}
	/*Material const& get_material() const{
		return material_;
	}*/

	bool solveQuadratic(const float &a, const float &b, const float &c, float &x0, float &x1){ //abc Formel, x0, x1 geben t0,t1 Auftreffpunkte
		float discr = b * b - 4 * a * c;
		if (discr < 0){
			return false;
		}
		else if (discr == 0) {
		x0 = - 0.5 * b / a;
		x1 = - 0.5 * b / a;
		}
		else {
			float q = (b > 0) ?
				-0.5 * (b + sqrt(discr)) :
				-0.5 * (b - sqrt(discr));
			x0 = q / a;
			x1 = c / q;
		}
		if (x0 > x1) {
			std::swap(x0, x1);
		}
		return true;
	}

	friend std::ostream& operator<<(std::ostream& os, Shape const& s){
		return s.print(os);
	}

	virtual bool intersect(Ray const& ray, float& distance) const = 0;
	virtual bool intersect(Ray const& ray, float& distance, glm::vec3& intersection,
	glm::vec3& normal) const = 0;

private:
	std::string name_;
	//Color color_;
	//Material material_;
	std::string matname_;
};

#endif // #ifndef BUW_SHAPE_HPP
<commit_msg>Methode zum Lösen von Quadratgleichungen<commit_after>#ifndef BUW_SHAPE_HPP
#define BUW_SHAPE_HPP
#include <iostream>
#include <string>
#include "color.hpp"
#include "ray.hpp"
#include "material.hpp"

class Shape
{
public:
	/*
	Shape(): name_{""}, color_{0.0f, 0.0f, 0.0f}{}
	Shape(std::string name, Color const& color): name_{name}, color_{color} {}
	virtual ~Shape(){std::cout << "Shape Destructor" << std::endl;}
	~Shape(){std::cout << "Shape Destructor" << std::endl;}

	Shape(): name_{""}, material_{}{}
	Shape(std::string name, Material const& mat): name_{name}, material_{mat} {}
	Shape(std::string name, std::string name_mat, Color const& ka, Color const& kd, Color const& ks, float m): name_{name},
	material_{name_mat, ka, kd, ks, m} {}*/

	Shape(): name_{""}, matname_{""}{}
	Shape(std::string name, std::string material): name_{name}, matname_{material} {}

	virtual std::ostream& print(std::ostream& os) const{
		os << "Name: " << name_ << " Material: " << matname_ << std::endl;;
		return os;
	}

	std::string const& get_name()const{
		return name_;
	}

	std::string const& get_material()const{
		return matname_;
	}
	/*Material const& get_material() const{
		return material_;
	}*/

	//Ausgangsgleichung: ax^2 + bx + c = 0
	bool solveQuadratic(const float &a, const float &b, const float &c, float &x0, float &x1){ //x0, x1 geben t0,t1 Auftreffpunkte
		float discr = b * b - 4 * a * c;
		if (discr < 0){
			return false;
		}
		else if (discr == 0) {
		x0 = - 0.5 * b / a;
		x1 = - 0.5 * b / a;
		}
		else {
			float q = (b > 0) ?
				-0.5 * (b + sqrt(discr)) :
				-0.5 * (b - sqrt(discr));
			x0 = q / a;
			x1 = c / q;
		}
		if (x0 > x1) {
			std::swap(x0, x1);
		}
		return true;
	}

	friend std::ostream& operator<<(std::ostream& os, Shape const& s){
		return s.print(os);
	}

	virtual bool intersect(Ray const& ray, float& distance) const = 0;
	virtual bool intersect(Ray const& ray, float& distance, glm::vec3& intersection,
	glm::vec3& normal) const = 0;

private:
	std::string name_;
	//Color color_;
	//Material material_;
	std::string matname_;
};

#endif // #ifndef BUW_SHAPE_HPP
<|endoftext|>


<commit_before>/**
 *	@file		integral.hpp
 *	@brief		Implementation of integral image
 *	@author		seonho.oh@gmail.com
 *	@date		2013-07-01
 *	@version	1.0
 *
 *	@section	LICENSE
 *
 *		Copyright (c) 2007-2014, Seonho Oh
 *		All rights reserved.
 *
 *		Redistribution and use in source and binary forms, with or without
 *		modification, are permitted provided that the following conditions are
 *		met:
 *
 *		    * Redistributions of source code must retain the above copyright
 *		    notice, this list of conditions and the following disclaimer.
 *		    * Redistributions in binary form must reproduce the above copyright
 *		    notice, this list of conditions and the following disclaimer in the
 *		    documentation and/or other materials provided with the distribution.
 *		    * Neither the name of the <ORGANIZATION> nor the names of its
 *		    contributors may be used to endorse or promote products derived from
 *		    this software without specific prior written permission.
 *
 *		THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
 *		IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
 *		TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
 *		PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER
 *		OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 *		EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 *		PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
 *		PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
 *		LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 *		NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 *		SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */
#pragma once

namespace auxiliary
{
	/**
	 *	@brief	Compute integral images
	 *	@param [in] img		input image
	 *	@param [out] sum	integral image
	 *	@param [out] sqsum	squared integral image
	*/
	template <typename T1, typename T2, typename T3>
	void integral(const Image<T1>& img, Image<T2>& sum, Image<T3>& sqsum)
	{
		typedef typename Image<T1>::size_type	size_type;

		// allocate images
		sum.resize(img.width(), img.height());
		sqsum.resize(img.width(), img.height());

		// simplest implementation
		const T1* ptr = img.memptr();
		T2* sumptr = sum.memptr();
		T3* sqsumptr = sqsum.memptr();

		T2 s = 0;
		T3 sq = 0;

		// image is column major,
		// 0-th column accumulated
		for (size_type y = 0 ; y < img.height() ; y++) {
			const T1 it = ptr[y];
			s += it;
			sq += (T3)it * it;
			sumptr[y] = s;
			sqsumptr[y] = sq;
		}

		s = sumptr[0];
		sq = sqsumptr[0];
		// 0-th row accumulated
		for (size_type x = 1 ; x < img.width() ; x++) {
			T2 it = img(0, x);
			s += it;
			sq += (T3)it * it;
			sum.at(0, x) = s;
			sqsum.at(0, x) = sq;
		}

		T2* sptr0 = sum.colptr(0);
		T3* sqptr0 = sqsum.colptr(0);

		for (size_type x = 1 ; x < img.width() ; x++) {
			T2 s = 0;
			T3 sq = 0;

			T2* sptr1 = sum.colptr(x);
			T3* sqptr1 = sqsum.colptr(x);

			for (size_type y = 0 ; y < img.height() ; y++) {
				T2 it = img(y, x);
				s += it;
				sq += (T3)it * it;
				//sum.at(y, x) = sum.at(y, x - 1) + s;
				sptr1[y] = sptr0[y] + s;
				//sqsum.at(y, x) = sqsum.at(y, x - 1) + sq;
				sqptr1[y] = sqptr0[y] + sq;
			}

			sptr0 = sptr1;
			sqptr0 = sqptr1;
		}
	}
}<commit_msg>Add overloaded version of integral function<commit_after>/**
 *	@file		integral.hpp
 *	@brief		Implementation of integral image
 *	@author		seonho.oh@gmail.com
 *	@date		2013-07-01
 *	@version	1.0
 *
 *	@section	LICENSE
 *
 *		Copyright (c) 2007-2014, Seonho Oh
 *		All rights reserved.
 *
 *		Redistribution and use in source and binary forms, with or without
 *		modification, are permitted provided that the following conditions are
 *		met:
 *
 *		    * Redistributions of source code must retain the above copyright
 *		    notice, this list of conditions and the following disclaimer.
 *		    * Redistributions in binary form must reproduce the above copyright
 *		    notice, this list of conditions and the following disclaimer in the
 *		    documentation and/or other materials provided with the distribution.
 *		    * Neither the name of the <ORGANIZATION> nor the names of its
 *		    contributors may be used to endorse or promote products derived from
 *		    this software without specific prior written permission.
 *
 *		THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
 *		IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
 *		TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
 *		PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER
 *		OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 *		EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 *		PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
 *		PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
 *		LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 *		NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 *		SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */
#pragma once

namespace auxiliary
{
    //! Compute integral
    template <typename T1, typename T2>
    void integral(const arma::Mat<T1>& A, arma::Mat<T2>& I)
    {
        typedef typename arma::uword size_type;

        // set size
        I.set_size(A.n_rows, A.n_cols);

        // Naive implementation
        const T1* ptr = A.memptr();
        T2* iptr = I.memptr();

        iptr[0] = static_cast<T2>(ptr[0]);

        // 0-th column
        for (size_type y = 1 ; y < A.n_rows ; y++)
            iptr[y] = iptr[y - 1] + static_cast<T2>(ptr[y]);

        // 0-th row
        for (size_type x = 1 ; x < A.n_cols ; x++)
            I.at(0, x) = I.at(0, x - 1) + static_cast<T2>(A.at(0, x));

        const T2* iptr0 = iptr;
        for (size_type x = 1 ; x < A.n_cols ; x++) {
            ptr = A.colptr(x);
            T2* iptr1 = I.colptr(x);
            T2 s = 0;
            for (size_type y = 1 ; y < A.n_rows ; y++) {
                s += static_cast<T2>(ptr[y]);
                iptr1[y] = iptr0[y] + s;
            }
        }
    }

	/**
	 *	@brief	Compute integral images
	 *	@param [in] img		input image
	 *	@param [out] sum	integral image
	 *	@param [out] sqsum	squared integral image
	*/
	template <typename T1, typename T2, typename T3>
	void integral(const Image<T1>& img, Image<T2>& sum, Image<T3>& sqsum)
	{
		typedef typename Image<T1>::size_type	size_type;

		// allocate images
		sum.resize(img.width(), img.height());
		sqsum.resize(img.width(), img.height());

		// simplest implementation
		const T1* ptr = img.memptr();
		T2* sumptr = sum.memptr();
		T3* sqsumptr = sqsum.memptr();

		T2 s = 0;
		T3 sq = 0;

		// image is column major,
		// 0-th column accumulated
		for (size_type y = 0 ; y < img.height() ; y++) {
			const T1 it = ptr[y];
			s += it;
			sq += (T3)it * it;
			sumptr[y] = s;
			sqsumptr[y] = sq;
		}

		s = sumptr[0];
		sq = sqsumptr[0];
		// 0-th row accumulated
		for (size_type x = 1 ; x < img.width() ; x++) {
			T2 it = img(0, x);
			s += it;
			sq += (T3)it * it;
			sum.at(0, x) = s;
			sqsum.at(0, x) = sq;
		}

		T2* sptr0 = sum.colptr(0);
		T3* sqptr0 = sqsum.colptr(0);

		for (size_type x = 1 ; x < img.width() ; x++) {
			T2 s = 0;
			T3 sq = 0;

			T2* sptr1 = sum.colptr(x);
			T3* sqptr1 = sqsum.colptr(x);

			for (size_type y = 0 ; y < img.height() ; y++) {
				T2 it = img(y, x);
				s += it;
				sq += (T3)it * it;
				//sum.at(y, x) = sum.at(y, x - 1) + s;
				sptr1[y] = sptr0[y] + s;
				//sqsum.at(y, x) = sqsum.at(y, x - 1) + sq;
				sqptr1[y] = sqptr0[y] + sq;
			}

			sptr0 = sptr1;
			sqptr0 = sqptr1;
		}
	}
}<|endoftext|>


<commit_before>#ifndef IMPORTER_NODESTORE_HPP
#define IMPORTER_NODESTORE_HPP

class Nodestore {
public:
    struct Nodeinfo {
        // MEMORY: may remove the version, it's not really required
        osm_version_t version;
        double lat;
        double lon;
    };

private:
    typedef std::map< time_t, Nodeinfo > timemap;
    typedef std::pair< time_t, Nodeinfo > timepair;
    typedef std::map< time_t, Nodeinfo >::iterator timemap_it;
    typedef std::map< time_t, Nodeinfo >::const_iterator timemap_cit;

    typedef std::map< osm_object_id_t, timemap* > nodemap;
    typedef std::pair< osm_object_id_t, timemap* > nodepair;
    typedef std::map< osm_object_id_t, timemap* >::iterator nodemap_it;
    typedef std::map< osm_object_id_t, timemap* >::const_iterator nodemap_cit;
    nodemap m_nodemap;

public:
    Nodestore() : m_nodemap() {}
    ~Nodestore() {
        nodemap_cit end = m_nodemap.end();
        for(nodemap_cit it = m_nodemap.begin(); it != end; ++it) {
            delete it->second;
        }
    }

    void record(osm_object_id_t id, osm_version_t v, time_t t, double lon, double lat) {
        Nodeinfo info = {v, lon, lat};

        nodemap_it it = m_nodemap.find(id);
        timemap *tmap;

        if(it == m_nodemap.end()) {
            if(Osmium::debug()) {
                std::cerr << "no timemap for node #" << id << ", creating new" << std::endl;
            }

            tmap = new timemap();
            m_nodemap.insert(nodepair(id, tmap));
        } else {
            tmap = it->second;
        }

        tmap->insert(timepair(t, info));
        if(Osmium::debug()) {
            std::cerr << "adding timepair for node #" << id << " v" << v << " at tstamp " << t << std::endl;
        }
    }

    Nodeinfo lookup(osm_object_id_t id, time_t t) {
        Nodeinfo nullinfo = {0, 0, 0};

        if(Osmium::debug()) {
            std::cerr << "looking up information of node #" << id << " at tstamp " << t << std::endl;
        }

        nodemap_it nit = m_nodemap.find(id);
        if(nit == m_nodemap.end()) {
            std::cerr << "no timemap for node #" << id << ", skipping node" << std::endl;
            return nullinfo;
        }

        timemap *tmap = nit->second;
        timemap_it tit = tmap->upper_bound(t);

        if(tit == tmap->begin()) {
            std::cerr << "reference to node #" << id << " at tstamp " << t << " which is before the youngest available version of that node, using version " << tit->second.version << std::endl;
        } else {
            tit--;
        }

        return tit->second;
    }

    geos::geom::Geometry* forgeGeometry(Osmium::OSM::WayNodeList &nodes, time_t t, bool looksLikePolygon) {
        // shorthand to the geometry factory
        geos::geom::GeometryFactory *f = Osmium::Geometry::geos_geometry_factory();

        // pointer to coordinate vector
        std::vector<geos::geom::Coordinate> *c = new std::vector<geos::geom::Coordinate>();

        Osmium::OSM::WayNodeList::const_iterator end = nodes.end();
        for(Osmium::OSM::WayNodeList::const_iterator it = nodes.begin(); it != end; ++it) {
            osm_object_id_t id = it->ref();

            Nodeinfo info = lookup(id, t);
            if(info.version == 0)
                continue;

            if(Osmium::debug()) {
                std::cerr << "node #" << id << " at tstamp " << t << " references version " << info.version << std::endl;
            }

            c->push_back(geos::geom::Coordinate(info.lat, info.lon, DoubleNotANumber));
        }

        if(c->size() < 2) {
            std::cerr << "found only " << c->size() << " valid coordinates, skipping way" << std::endl;
            delete c;
            return NULL;
        }

        geos::geom::Geometry* geom;

        try {
            // tags say it could be a polygon and the way is closed
            if(looksLikePolygon && c->front() == c->back()) {
                // build a polygon
                geom = f->createPolygon(
                    f->createLinearRing(
                        f->getCoordinateSequenceFactory()->create(c)
                    ),
                    NULL
                );
            } else {
                // build a linestring
                geom = f->createLineString(
                    f->getCoordinateSequenceFactory()->create(c)
                );
            }
        } catch(geos::util::GEOSException e) {
            std::cerr << "error creating polygon: " << e.what() << std::endl;
            delete c;
            return NULL;
        }

        geom->setSRID(900913);
        return geom;
    }

    std::vector<time_t> *calculateMinorTimes(Osmium::OSM::WayNodeList &nodes, time_t from, time_t to) {
        std::vector<time_t> *minor_times = new std::vector<time_t>();

        for(Osmium::OSM::WayNodeList::const_iterator nodeit = nodes.begin(); nodeit != nodes.end(); nodeit++) {
            osm_object_id_t id = nodeit->ref();

            nodemap_it nit = m_nodemap.find(id);
            if(nit == m_nodemap.end()) {
                std::cerr << "no timemap for node #" << id << ", skipping node" << std::endl;
                continue;
            }

            timemap *tmap = nit->second;
            timemap_cit lower = tmap->lower_bound(from);
            timemap_cit upper = to == 0 ? tmap->end() : tmap->upper_bound(to);
            for(timemap_cit it = lower; it != upper; it++) {
                minor_times->push_back(it->first);
            }
        }

        std::sort(minor_times->begin(), minor_times->end());
        std::unique(minor_times->begin(), minor_times->end());

        return minor_times;
    }

    std::vector<time_t> *calculateMinorTimes(Osmium::OSM::WayNodeList &nodes, time_t from) {
        return calculateMinorTimes(nodes, from, 0);
    }
};

#endif // IMPORTER_NODESTORE_HPP
<commit_msg>remove version from stored info<commit_after>#ifndef IMPORTER_NODESTORE_HPP
#define IMPORTER_NODESTORE_HPP

class Nodestore {
public:
    struct Nodeinfo {
        double lat;
        double lon;
    };

private:
    typedef std::map< time_t, Nodeinfo > timemap;
    typedef std::pair< time_t, Nodeinfo > timepair;
    typedef std::map< time_t, Nodeinfo >::iterator timemap_it;
    typedef std::map< time_t, Nodeinfo >::const_iterator timemap_cit;

    typedef std::map< osm_object_id_t, timemap* > nodemap;
    typedef std::pair< osm_object_id_t, timemap* > nodepair;
    typedef std::map< osm_object_id_t, timemap* >::iterator nodemap_it;
    typedef std::map< osm_object_id_t, timemap* >::const_iterator nodemap_cit;
    nodemap m_nodemap;

public:
    Nodestore() : m_nodemap() {}
    ~Nodestore() {
        nodemap_cit end = m_nodemap.end();
        for(nodemap_cit it = m_nodemap.begin(); it != end; ++it) {
            delete it->second;
        }
    }

    void record(osm_object_id_t id, osm_version_t v, time_t t, double lon, double lat) {
        Nodeinfo info = {lon, lat};

        nodemap_it it = m_nodemap.find(id);
        timemap *tmap;

        if(it == m_nodemap.end()) {
            if(Osmium::debug()) {
                std::cerr << "no timemap for node #" << id << ", creating new" << std::endl;
            }

            tmap = new timemap();
            m_nodemap.insert(nodepair(id, tmap));
        } else {
            tmap = it->second;
        }

        tmap->insert(timepair(t, info));
        if(Osmium::debug()) {
            std::cerr << "adding timepair for node #" << id << " v" << v << " at tstamp " << t << std::endl;
        }
    }

    Nodeinfo lookup(osm_object_id_t id, time_t t, bool &found) {
        if(Osmium::debug()) {
            std::cerr << "looking up information of node #" << id << " at tstamp " << t << std::endl;
        }

        nodemap_it nit = m_nodemap.find(id);
        if(nit == m_nodemap.end()) {
            std::cerr << "no timemap for node #" << id << ", skipping node" << std::endl;
            found = false;
            Nodeinfo nullinfo = {0, 0};
            return nullinfo;
        }

        timemap *tmap = nit->second;
        timemap_it tit = tmap->upper_bound(t);

        if(tit == tmap->begin()) {
            std::cerr << "reference to node #" << id << " at tstamp " << t << " which is before the youngest available version of that node, using first version" << std::endl;
        } else {
            tit--;
        }

        found = true;
        return tit->second;
    }

    geos::geom::Geometry* forgeGeometry(Osmium::OSM::WayNodeList &nodes, time_t t, bool looksLikePolygon) {
        // shorthand to the geometry factory
        geos::geom::GeometryFactory *f = Osmium::Geometry::geos_geometry_factory();

        // pointer to coordinate vector
        std::vector<geos::geom::Coordinate> *c = new std::vector<geos::geom::Coordinate>();

        Osmium::OSM::WayNodeList::const_iterator end = nodes.end();
        for(Osmium::OSM::WayNodeList::const_iterator it = nodes.begin(); it != end; ++it) {
            osm_object_id_t id = it->ref();

            bool found;
            Nodeinfo info = lookup(id, t, found);
            if(!found)
                continue;

            if(Osmium::debug()) {
                std::cerr << "node #" << id << " at tstamp " << t << " references node at POINT(" << std::setprecision(8) << info.lat << ' ' << info.lon << ')' << std::endl;
            }

            c->push_back(geos::geom::Coordinate(info.lat, info.lon, DoubleNotANumber));
        }

        if(c->size() < 2) {
            std::cerr << "found only " << c->size() << " valid coordinates, skipping way" << std::endl;
            delete c;
            return NULL;
        }

        geos::geom::Geometry* geom;

        try {
            // tags say it could be a polygon and the way is closed
            if(looksLikePolygon && c->front() == c->back()) {
                // build a polygon
                geom = f->createPolygon(
                    f->createLinearRing(
                        f->getCoordinateSequenceFactory()->create(c)
                    ),
                    NULL
                );
            } else {
                // build a linestring
                geom = f->createLineString(
                    f->getCoordinateSequenceFactory()->create(c)
                );
            }
        } catch(geos::util::GEOSException e) {
            std::cerr << "error creating polygon: " << e.what() << std::endl;
            delete c;
            return NULL;
        }

        geom->setSRID(900913);
        return geom;
    }

    std::vector<time_t> *calculateMinorTimes(Osmium::OSM::WayNodeList &nodes, time_t from, time_t to) {
        std::vector<time_t> *minor_times = new std::vector<time_t>();

        for(Osmium::OSM::WayNodeList::const_iterator nodeit = nodes.begin(); nodeit != nodes.end(); nodeit++) {
            osm_object_id_t id = nodeit->ref();

            nodemap_it nit = m_nodemap.find(id);
            if(nit == m_nodemap.end()) {
                std::cerr << "no timemap for node #" << id << ", skipping node" << std::endl;
                continue;
            }

            timemap *tmap = nit->second;
            timemap_cit lower = tmap->lower_bound(from);
            timemap_cit upper = to == 0 ? tmap->end() : tmap->upper_bound(to);
            for(timemap_cit it = lower; it != upper; it++) {
                minor_times->push_back(it->first);
            }
        }

        std::sort(minor_times->begin(), minor_times->end());
        std::unique(minor_times->begin(), minor_times->end());

        return minor_times;
    }

    std::vector<time_t> *calculateMinorTimes(Osmium::OSM::WayNodeList &nodes, time_t from) {
        return calculateMinorTimes(nodes, from, 0);
    }
};

#endif // IMPORTER_NODESTORE_HPP
<|endoftext|>


<commit_before>#include <stan/math/fwd/arr.hpp>
#include <gtest/gtest.h>
#include <vector>

TEST(MetaTraitsMixArr, partials_return_type) {
  using stan::math::fvar;
  using stan::partials_return_type;

  partials_return_type<double, fvar<double>, std::vector<fvar<double> > >::type
      a(5.0);
  EXPECT_EQ(5.0, a);
}
<commit_msg>Update test/unit/math/fwd/arr/meta/partials_return_type_test.cpp<commit_after>#include <stan/math/fwd/arr.hpp>
#include <gtest/gtest.h>
#include <vector>

TEST(MetaTraitsFwdArr, partials_return_type) {
  using stan::math::fvar;
  using stan::partials_return_type;

  partials_return_type<double, fvar<double>, std::vector<fvar<double> > >::type
      a(5.0);
  EXPECT_EQ(5.0, a);
}
<|endoftext|>