<commit_before>#include "stdsneezy.h"
#include "obj_tool.h"
#include "obj_plant.h"

void TBeing::doPlant(string arg)
{
  TThing *t;
  TTool *flintsteel;
  int count, found=0;

  if ((t = searchLinkedListVis(this, arg.c_str(), getStuff(), &count))){
    if((flintsteel=dynamic_cast<TTool *>(t))){
      if(flintsteel->getToolType() == TOOL_SEED){
	found=1;
      }
    }
  }
  if(!found){
    sendTo("You need to specify some seeds to plant.\n\r");
    return;
  }

  if(roomp->isFallSector() || roomp->isWaterSector() ||
     roomp->isIndoorSector()){
    sendTo("You can't plant anything here.\n\r");
    return;
  }

  TThing *tcount;
  for(tcount=roomp->getStuff(),count=0;tcount;tcount=tcount->nextThing){
    if(dynamic_cast<TPlant *>(tcount))
      ++count;
  }
  if(count>=8){
    sendTo("There isn't any room for more plants in here.\n\r");
    return;
  }

  sendTo("You begin to plant some seeds.\n\r");
  start_task(this, t, NULL, TASK_PLANT, "", 2, inRoom(), 0, 0, 5);
}

int task_plant(TBeing *ch, cmdTypeT cmd, const char *, int pulse, TRoom *, TObj *obj)
{
  TTool *tt;

  if (ch->utilityTaskCommand(cmd) ||
      ch->nobrainerTaskCommand(cmd))
    return FALSE;

  // basic tasky safechecking
  if (ch->isLinkdead() || (ch->in_room != ch->task->wasInRoom) || !obj){
    act("You stop planting your seeds.",
        FALSE, ch, 0, 0, TO_CHAR);
    act("$n stops planting seeds.",
        TRUE, ch, 0, 0, TO_ROOM);
    ch->stopTask();
    return FALSE; // returning FALSE lets command be interpreted
  }

  tt=dynamic_cast<TTool *>(obj);

  if (ch->task->timeLeft < 0){
    act("You finish planting $p.",
	FALSE, ch, obj, 0, TO_CHAR);
    act("$n finishes planting $p.",
	TRUE, ch, obj, 0, TO_ROOM);
    ch->stopTask();

    TObj *tp;
    TPlant *tplant;
    tp = read_object(OBJ_GENERIC_PLANT, VIRTUAL);
    if((tplant=dynamic_cast<TPlant *>(tp))){
      tplant->setType(tt->objVnum()-13880);
      tplant->updateDesc();
    }

    *ch->roomp += *tp;

    if (tt->getToolUses() <= 0) {
      act("You disgard $p because it is empty.",
	  FALSE, ch, tt, 0, TO_CHAR);
      delete tt;
    }

    return FALSE;
  }

  switch (cmd) {
    case CMD_TASK_CONTINUE:
      ch->task->calcNextUpdate(pulse, PULSE_MOBACT * 3);

      switch (ch->task->timeLeft) {
	case 2:
          act("You dig a little hole for some seeds from $p.",
              FALSE, ch, obj, 0, TO_CHAR);
          act("$n digs a little hole.",
              TRUE, ch, obj, 0, TO_ROOM);
          ch->task->timeLeft--;
          break;
	case 1:
          act("You put some seeds from $p into your hole.",
              FALSE, ch, tt, 0, TO_CHAR);
          act("$n puts some seeds from $p into the hole.",
              TRUE, ch, tt, 0, TO_ROOM);
          ch->task->timeLeft--;

	  tt->addToToolUses(-1);

          break;
	case 0:
	  act("You cover up the hole.",
              FALSE, ch, obj, 0, TO_CHAR);
	  act("$n covers up the hole.",
	      TRUE, ch, obj, 0, TO_ROOM);
	  ch->task->timeLeft--;
	  break;
      }
      break;
    case CMD_ABORT:
    case CMD_STOP:
      act("You stop planting seeds.",
          FALSE, ch, 0, 0, TO_CHAR);
      act("$n stops planting seeds.",
          TRUE, ch, 0, 0, TO_ROOM);
      ch->stopTask();
      break;
    case CMD_TASK_FIGHTING:
      ch->sendTo("You can't properly plant seeds while under attack.\n\r");
      ch->stopTask();
      break;
  default:
      if (cmd < MAX_CMD_LIST)
        warn_busy(ch);
      break;                    // eat the command
  }
  return TRUE;

}

<commit_msg>was called searchLinkListVis with an uninitialized count variable<commit_after>#include "stdsneezy.h"
#include "obj_tool.h"
#include "obj_plant.h"

void TBeing::doPlant(string arg)
{
  TThing *t;
  TTool *seeds;
  int found=0;

  if ((t = searchLinkedListVis(this, arg.c_str(), getStuff(), NULL))){
    if((seeds=dynamic_cast<TTool *>(t))){
      if(seeds->getToolType() == TOOL_SEED){
	found=1;
      }
    }
  }
  if(!found){
    sendTo("You need to specify some seeds to plant.\n\r");
    return;
  }

  if(roomp->isFallSector() || roomp->isWaterSector() ||
     roomp->isIndoorSector()){
    sendTo("You can't plant anything here.\n\r");
    return;
  }

  TThing *tcount;
  for(tcount=roomp->getStuff(),count=0;tcount;tcount=tcount->nextThing){
    if(dynamic_cast<TPlant *>(tcount))
      ++count;
  }
  if(count>=8){
    sendTo("There isn't any room for more plants in here.\n\r");
    return;
  }

  sendTo("You begin to plant some seeds.\n\r");
  start_task(this, t, NULL, TASK_PLANT, "", 2, inRoom(), 0, 0, 5);
}

int task_plant(TBeing *ch, cmdTypeT cmd, const char *, int pulse, TRoom *, TObj *obj)
{
  TTool *tt;

  if (ch->utilityTaskCommand(cmd) ||
      ch->nobrainerTaskCommand(cmd))
    return FALSE;

  // basic tasky safechecking
  if (ch->isLinkdead() || (ch->in_room != ch->task->wasInRoom) || !obj){
    act("You stop planting your seeds.",
        FALSE, ch, 0, 0, TO_CHAR);
    act("$n stops planting seeds.",
        TRUE, ch, 0, 0, TO_ROOM);
    ch->stopTask();
    return FALSE; // returning FALSE lets command be interpreted
  }

  tt=dynamic_cast<TTool *>(obj);

  if (ch->task->timeLeft < 0){
    act("You finish planting $p.",
	FALSE, ch, obj, 0, TO_CHAR);
    act("$n finishes planting $p.",
	TRUE, ch, obj, 0, TO_ROOM);
    ch->stopTask();

    TObj *tp;
    TPlant *tplant;
    tp = read_object(OBJ_GENERIC_PLANT, VIRTUAL);
    if((tplant=dynamic_cast<TPlant *>(tp))){
      tplant->setType(tt->objVnum()-13880);
      tplant->updateDesc();
    }

    *ch->roomp += *tp;

    if (tt->getToolUses() <= 0) {
      act("You disgard $p because it is empty.",
	  FALSE, ch, tt, 0, TO_CHAR);
      delete tt;
    }

    return FALSE;
  }

  switch (cmd) {
    case CMD_TASK_CONTINUE:
      ch->task->calcNextUpdate(pulse, PULSE_MOBACT * 3);

      switch (ch->task->timeLeft) {
	case 2:
          act("You dig a little hole for some seeds from $p.",
              FALSE, ch, obj, 0, TO_CHAR);
          act("$n digs a little hole.",
              TRUE, ch, obj, 0, TO_ROOM);
          ch->task->timeLeft--;
          break;
	case 1:
          act("You put some seeds from $p into your hole.",
              FALSE, ch, tt, 0, TO_CHAR);
          act("$n puts some seeds from $p into the hole.",
              TRUE, ch, tt, 0, TO_ROOM);
          ch->task->timeLeft--;

	  tt->addToToolUses(-1);

          break;
	case 0:
	  act("You cover up the hole.",
              FALSE, ch, obj, 0, TO_CHAR);
	  act("$n covers up the hole.",
	      TRUE, ch, obj, 0, TO_ROOM);
	  ch->task->timeLeft--;
	  break;
      }
      break;
    case CMD_ABORT:
    case CMD_STOP:
      act("You stop planting seeds.",
          FALSE, ch, 0, 0, TO_CHAR);
      act("$n stops planting seeds.",
          TRUE, ch, 0, 0, TO_ROOM);
      ch->stopTask();
      break;
    case CMD_TASK_FIGHTING:
      ch->sendTo("You can't properly plant seeds while under attack.\n\r");
      ch->stopTask();
      break;
  default:
      if (cmd < MAX_CMD_LIST)
        warn_busy(ch);
      break;                    // eat the command
  }
  return TRUE;

}

<|endoftext|>


<commit_before>/*
 *  Copyright(C) 2021 hikyuu.org
 *
 *  Create on: 2021-02-28
 *     Author: fasiondog
 */

#include <string_view>
#include <hikyuu/utilities/arithmetic.h>
#include <hikyuu/datetime/Datetime.h>
#include "gzip/compress.hpp"
#include "gzip/decompress.hpp"
#include "gzip/utils.hpp"
#include "url.h"
#include "HttpHandle.h"

namespace hku {

HttpHandle::HttpHandle(nng_aio* aio) : m_http_aio(aio) {}

void HttpHandle::operator()() {
    CLS_FATAL_IF_RETURN(!m_http_aio, void(), "http aio is null!");
    int rv = nng_http_res_alloc(&m_nng_res);
    if (rv != 0) {
        CLS_FATAL("Failed nng_http_res_alloc! {}", nng_strerror(rv));
        nng_aio_finish(m_http_aio, 0);
        return;
    }

    try {
        m_nng_req = (nng_http_req*)nng_aio_get_input(m_http_aio, 0);
        m_nng_conn = (nng_http_conn*)nng_aio_get_input(m_http_aio, 2);

        for (auto& filter : m_filters) {
            filter(this);
        }

        std::string encodings = getReqHeader("Accept-Encoding");
        size_t pos = encodings.find("gzip");
        if (pos != std::string::npos) {
            setResHeader("Content-Encoding", "gzip");
        }

        before_run();
        run();
        after_run();

        // nng_http_res_set_status(m_nng_res, NNG_HTTP_STATUS_OK);
        nng_aio_set_output(m_http_aio, 0, m_nng_res);

    } catch (nlohmann::json::exception& e) {
        CLS_WARN("HttpBadRequestError({}): {}", INVALID_JSON_REQUEST, e.what());
        processException(NNG_HTTP_STATUS_BAD_REQUEST, INVALID_JSON_REQUEST, e.what());

    } catch (HttpError& e) {
        CLS_WARN("{}({}): {}", e.name(), e.errcode(), e.what());
        processException(e.status(), e.errcode(), e.what());

    } catch (std::exception& e) {
        CLS_ERROR("HttpError({}): {}", NNG_HTTP_STATUS_INTERNAL_SERVER_ERROR, e.what());
        processException(NNG_HTTP_STATUS_INTERNAL_SERVER_ERROR,
                         NNG_HTTP_STATUS_INTERNAL_SERVER_ERROR, e.what());

    } catch (...) {
        CLS_ERROR("HttpError({}): {}", NNG_HTTP_STATUS_INTERNAL_SERVER_ERROR, "Unknown error");
        processException(NNG_HTTP_STATUS_INTERNAL_SERVER_ERROR,
                         NNG_HTTP_STATUS_INTERNAL_SERVER_ERROR, "Unknown error");
    }

    if (ms_enable_trace) {
        printTraceInfo();
    }

    nng_aio_finish(m_http_aio, 0);
}

void HttpHandle::printTraceInfo() {
    std::string url = getReqUrl();
    std::string traceid = getReqHeader("traceid");
    if (ms_enable_only_traceid && traceid.empty()) {
        return;
    }
    Datetime now = Datetime::now();
    std::string str = fmt::format(
      "{:>4d}-{:>02d}-{:>02d} {:>02d}:{:>02d}:{:>02d}.{:<03d} [HttpHandle-T] - ", now.year(),
      now.month(), now.day(), now.hour(), now.minute(), now.second(), now.millisecond());
    if (traceid.empty()) {
        CLS_TRACE(
          "╔════════════════════════════════════════════════════════════\n{}║  url:{}\n{}║  "
          "request: "
          "{}\n{}║  response: {}\n{}╚════════════════════════════════════════",
          str, url, str, getReqData(), str, getResData(), str);
    } else {
        CLS_TRACE(
          "╔════════════════════════════════════════════════════════════\n{}║  url:{}\n{}║  "
          "traceid: {}\n{}║  "
          "request: "
          "{}\n{}║  response: {}\n{}╚════════════════════════════════════════",
          str, url, str, traceid, str, getReqData(), str, getResData(), str);
    }
}

void HttpHandle::processException(int http_status, int errcode, std::string_view err_msg) {
    try {
        nng_http_res_set_header(m_nng_res, "Content-Type", "application/json; charset=UTF-8");
        nng_http_res_set_status(m_nng_res, http_status);
        nng_http_res_set_reason(m_nng_res, err_msg.data());
        setResData(
          fmt::format(R"({{"result":false,"errcode":{},"errmsg":"{}"}})", errcode, err_msg));
        nng_aio_set_output(m_http_aio, 0, m_nng_res);
    } catch (std::exception& e) {
        CLS_ERROR(e.what());
    } catch (...) {
        CLS_FATAL("unknown error in finished!");
    }
}

std::string HttpHandle::getReqUrl() const {
    std::string result;
    const char* url = nng_http_req_get_uri(m_nng_req);
    if (url) {
        result = std::string(url);
    }
    return result;
}

std::string HttpHandle::getReqHeader(const char* name) const {
    std::string result;
    const char* head = nng_http_req_get_header(m_nng_req, name);
    if (head) {
        result = std::string(head);
    }
    return result;
}

std::string HttpHandle::getReqData() {
    std::string result;
    void* data = nullptr;
    size_t len = 0;
    nng_http_req_get_data(m_nng_req, &data, &len);
    if (!data || len == 0) {
        return result;
    }

    std::string encoding = getReqHeader("Content-Encoding");
    if (encoding.empty()) {
        result = std::string((char*)data, len);

    } else if (encoding == "gzip") {
        gzip::Decompressor decomp;
        decomp.decompress(result, (char*)data, len);

    } else {
        throw HttpNotAcceptableError(
          HttpNotAcceptableError::UNSUPPORT_CONTENT_ENCODING,
          fmt::format(_ctr("HttpHandle", "Unsupported Content-Encoding format: {}"), encoding));
    }

    return result;
}

std::string HttpHandle::getResData() const {
    std::string result;
    char* data = nullptr;
    size_t len = 0;
    nng_http_res_get_data(m_nng_res, (void**)&data, &len);
    if (!data || len == 0) {
        return result;
    }

    if (!gzip::is_compressed(data, len)) {
        result = std::string(data, len);
        return result;
    }

    gzip::Decompressor decomp;
    decomp.decompress(result, data, len);
    return result;
}

json HttpHandle::getReqJson() {
    std::string data = getReqData();
    json result;
    try {
        if (!data.empty()) {
            result = json::parse(data);
        }
    } catch (json::exception& e) {
        APP_ERROR("Failed parse json: {}", data);
        throw HttpBadRequestError(BadRequestErrorCode::INVALID_JSON_REQUEST, e.what());
    }
    return result;
}

bool HttpHandle::haveQueryParams() {
    const char* url = nng_http_req_get_uri(m_nng_req);
    return !url ? false : strchr(url, '?') != nullptr;
}

bool HttpHandle::getQueryParams(QueryParams& query_params) {
    const char* url = nng_http_req_get_uri(m_nng_req);
    CLS_IF_RETURN(!url, false);

    const char* p = strchr(url, '?');
    CLS_IF_RETURN(!p, false);

    p = p + 1;

    enum {
        s_key,
        s_value,
    } state = s_key;

    const char* key = p;
    const char* value = NULL;
    int key_len = 0;
    int value_len = 0;
    while (*p != '\0') {
        if (*p == '&') {
            if (key_len && value_len) {
                std::string strkey = std::string(key, key_len);
                std::string strvalue = std::string(value, value_len);
                query_params[url_unescape(strkey.c_str())] = url_unescape(strvalue.c_str());
                key_len = value_len = 0;
            }
            state = s_key;
            key = p + 1;
        } else if (*p == '=') {
            state = s_value;
            value = p + 1;
        } else {
            state == s_key ? ++key_len : ++value_len;
        }
        ++p;
    }
    if (key_len && value_len) {
        std::string strkey = std::string(key, key_len);
        std::string strvalue = std::string(value, value_len);
        query_params[url_unescape(strkey.c_str())] = url_unescape(strvalue.c_str());
        key_len = value_len = 0;
    }

    return query_params.size() != 0;
}

void HttpHandle::setResData(const char* content) {
    const char* encoding = nng_http_res_get_header(m_nng_res, "Content-Encoding");
    if (!encoding) {
        NNG_CHECK(nng_http_res_copy_data(m_nng_res, content, strlen(content)));
    } else {
        gzip::Compressor comp(Z_DEFAULT_COMPRESSION);
        std::string output;
        comp.compress(output, content, strlen(content));
        NNG_CHECK(nng_http_res_copy_data(m_nng_res, output.c_str(), output.size()));
    }
}

std::string HttpHandle::getLanguage() const {
    std::string lang = getReqHeader("Accept-Language");
    auto pos = lang.find_first_of(',');
    if (pos != std::string::npos) {
        lang = lang.substr(0, pos);
    }
    if (!lang.empty()) {
        to_lower(lang);
    }
    return lang;
}

}  // namespace hku<commit_msg>改进http traceinfo 打印<commit_after>/*
 *  Copyright(C) 2021 hikyuu.org
 *
 *  Create on: 2021-02-28
 *     Author: fasiondog
 */

#include <string_view>
#include <hikyuu/utilities/arithmetic.h>
#include <hikyuu/datetime/Datetime.h>
#include "gzip/compress.hpp"
#include "gzip/decompress.hpp"
#include "gzip/utils.hpp"
#include "url.h"
#include "HttpHandle.h"

namespace hku {

HttpHandle::HttpHandle(nng_aio* aio) : m_http_aio(aio) {}

void HttpHandle::operator()() {
    CLS_FATAL_IF_RETURN(!m_http_aio, void(), "http aio is null!");
    int rv = nng_http_res_alloc(&m_nng_res);
    if (rv != 0) {
        CLS_FATAL("Failed nng_http_res_alloc! {}", nng_strerror(rv));
        nng_aio_finish(m_http_aio, 0);
        return;
    }

    try {
        m_nng_req = (nng_http_req*)nng_aio_get_input(m_http_aio, 0);
        m_nng_conn = (nng_http_conn*)nng_aio_get_input(m_http_aio, 2);

        for (auto& filter : m_filters) {
            filter(this);
        }

        std::string encodings = getReqHeader("Accept-Encoding");
        size_t pos = encodings.find("gzip");
        if (pos != std::string::npos) {
            setResHeader("Content-Encoding", "gzip");
        }

        before_run();
        run();
        after_run();

        // nng_http_res_set_status(m_nng_res, NNG_HTTP_STATUS_OK);
        nng_aio_set_output(m_http_aio, 0, m_nng_res);

    } catch (nlohmann::json::exception& e) {
        CLS_WARN("HttpBadRequestError({}): {}", INVALID_JSON_REQUEST, e.what());
        processException(NNG_HTTP_STATUS_BAD_REQUEST, INVALID_JSON_REQUEST, e.what());

    } catch (HttpError& e) {
        CLS_WARN("{}({}): {}", e.name(), e.errcode(), e.what());
        processException(e.status(), e.errcode(), e.what());

    } catch (std::exception& e) {
        CLS_ERROR("HttpError({}): {}", NNG_HTTP_STATUS_INTERNAL_SERVER_ERROR, e.what());
        processException(NNG_HTTP_STATUS_INTERNAL_SERVER_ERROR,
                         NNG_HTTP_STATUS_INTERNAL_SERVER_ERROR, e.what());

    } catch (...) {
        CLS_ERROR("HttpError({}): {}", NNG_HTTP_STATUS_INTERNAL_SERVER_ERROR, "Unknown error");
        processException(NNG_HTTP_STATUS_INTERNAL_SERVER_ERROR,
                         NNG_HTTP_STATUS_INTERNAL_SERVER_ERROR, "Unknown error");
    }

    if (ms_enable_trace) {
        printTraceInfo();
    }

    nng_aio_finish(m_http_aio, 0);
}

void HttpHandle::printTraceInfo() {
    std::string url = getReqUrl();
    std::string traceid = getReqHeader("traceid");
    if (ms_enable_only_traceid && traceid.empty()) {
        return;
    }
    Datetime now = Datetime::now();
    std::string str = fmt::format(
      "{:>4d}-{:>02d}-{:>02d} {:>02d}:{:>02d}:{:>02d}.{:<03d} [HttpHandle-T] - ", now.year(),
      now.month(), now.day(), now.hour(), now.minute(), now.second(), now.millisecond());
    if (traceid.empty()) {
        CLS_TRACE(
          "╔════════════════════════════════════════════════════════════\n"
          "{}║  url: {}\n"
          "{}║  method: {}\n"
          "{}║  request: {}\n"
          "{}║  response: {}\n"
          "{}╚════════════════════════════════════════",
          str, url, str, nng_http_req_get_method(m_nng_req), str, getReqData(), str, getResData(),
          str);
    } else {
        CLS_TRACE(
          "╔════════════════════════════════════════════════════════════\n"
          "{}║  url:{}\n"
          "{}║  method: {}\n"
          "{}║  traceid: {}\n"
          "{}║  request: {}\n"
          "{}║  response: {}\n{}╚════════════════════════════════════════",
          str, url, str, nng_http_req_get_method(m_nng_req), str, traceid, str, getReqData(), str,
          getResData(), str);
    }
}

void HttpHandle::processException(int http_status, int errcode, std::string_view err_msg) {
    try {
        nng_http_res_set_header(m_nng_res, "Content-Type", "application/json; charset=UTF-8");
        nng_http_res_set_status(m_nng_res, http_status);
        nng_http_res_set_reason(m_nng_res, err_msg.data());
        setResData(
          fmt::format(R"({{"result":false,"errcode":{},"errmsg":"{}"}})", errcode, err_msg));
        nng_aio_set_output(m_http_aio, 0, m_nng_res);
    } catch (std::exception& e) {
        CLS_ERROR(e.what());
    } catch (...) {
        CLS_FATAL("unknown error in finished!");
    }
}

std::string HttpHandle::getReqUrl() const {
    std::string result;
    const char* url = nng_http_req_get_uri(m_nng_req);
    if (url) {
        result = std::string(url);
    }
    return result;
}

std::string HttpHandle::getReqHeader(const char* name) const {
    std::string result;
    const char* head = nng_http_req_get_header(m_nng_req, name);
    if (head) {
        result = std::string(head);
    }
    return result;
}

std::string HttpHandle::getReqData() {
    std::string result;
    void* data = nullptr;
    size_t len = 0;
    nng_http_req_get_data(m_nng_req, &data, &len);
    if (!data || len == 0) {
        return result;
    }

    std::string encoding = getReqHeader("Content-Encoding");
    if (encoding.empty()) {
        result = std::string((char*)data, len);

    } else if (encoding == "gzip") {
        gzip::Decompressor decomp;
        decomp.decompress(result, (char*)data, len);

    } else {
        throw HttpNotAcceptableError(
          HttpNotAcceptableError::UNSUPPORT_CONTENT_ENCODING,
          fmt::format(_ctr("HttpHandle", "Unsupported Content-Encoding format: {}"), encoding));
    }

    return result;
}

std::string HttpHandle::getResData() const {
    std::string result;
    char* data = nullptr;
    size_t len = 0;
    nng_http_res_get_data(m_nng_res, (void**)&data, &len);
    if (!data || len == 0) {
        return result;
    }

    if (!gzip::is_compressed(data, len)) {
        result = std::string(data, len);
        return result;
    }

    gzip::Decompressor decomp;
    decomp.decompress(result, data, len);
    return result;
}

json HttpHandle::getReqJson() {
    std::string data = getReqData();
    json result;
    try {
        if (!data.empty()) {
            result = json::parse(data);
        }
    } catch (json::exception& e) {
        APP_ERROR("Failed parse json: {}", data);
        throw HttpBadRequestError(BadRequestErrorCode::INVALID_JSON_REQUEST, e.what());
    }
    return result;
}

bool HttpHandle::haveQueryParams() {
    const char* url = nng_http_req_get_uri(m_nng_req);
    return !url ? false : strchr(url, '?') != nullptr;
}

bool HttpHandle::getQueryParams(QueryParams& query_params) {
    const char* url = nng_http_req_get_uri(m_nng_req);
    CLS_IF_RETURN(!url, false);

    const char* p = strchr(url, '?');
    CLS_IF_RETURN(!p, false);

    p = p + 1;

    enum {
        s_key,
        s_value,
    } state = s_key;

    const char* key = p;
    const char* value = NULL;
    int key_len = 0;
    int value_len = 0;
    while (*p != '\0') {
        if (*p == '&') {
            if (key_len && value_len) {
                std::string strkey = std::string(key, key_len);
                std::string strvalue = std::string(value, value_len);
                query_params[url_unescape(strkey.c_str())] = url_unescape(strvalue.c_str());
                key_len = value_len = 0;
            }
            state = s_key;
            key = p + 1;
        } else if (*p == '=') {
            state = s_value;
            value = p + 1;
        } else {
            state == s_key ? ++key_len : ++value_len;
        }
        ++p;
    }
    if (key_len && value_len) {
        std::string strkey = std::string(key, key_len);
        std::string strvalue = std::string(value, value_len);
        query_params[url_unescape(strkey.c_str())] = url_unescape(strvalue.c_str());
        key_len = value_len = 0;
    }

    return query_params.size() != 0;
}

void HttpHandle::setResData(const char* content) {
    const char* encoding = nng_http_res_get_header(m_nng_res, "Content-Encoding");
    if (!encoding) {
        NNG_CHECK(nng_http_res_copy_data(m_nng_res, content, strlen(content)));
    } else {
        gzip::Compressor comp(Z_DEFAULT_COMPRESSION);
        std::string output;
        comp.compress(output, content, strlen(content));
        NNG_CHECK(nng_http_res_copy_data(m_nng_res, output.c_str(), output.size()));
    }
}

std::string HttpHandle::getLanguage() const {
    std::string lang = getReqHeader("Accept-Language");
    auto pos = lang.find_first_of(',');
    if (pos != std::string::npos) {
        lang = lang.substr(0, pos);
    }
    if (!lang.empty()) {
        to_lower(lang);
    }
    return lang;
}

}  // namespace hku<|endoftext|>


<commit_before>#ifndef DEFINE_HH
#define DEFINE_HH

#include <vector>
#include <opencv2/highgui.hpp>
#include <vpp/vpp.hh>
#include <Eigen/Core>

using namespace Eigen;

using namespace vpp;

double execution_time = 0;
double execution_t= 0;

enum class Theta_max : int32_t { XXSMALL = 67 , XSMALL = 127 , SMALL = 255, MEDIUM = 500, LARGE = 1000 , XLARGE = 1500};
enum class Sclare_rho : int32_t { ONE_QUART = 3, HALF = 2 , THREE_QUART = 1 , SAME = 0};
enum class Type_video_hough : int8_t { ONLY_CLUSTERS = 1 , ALL_POINTS = 2 };
enum class Type_capture : int16_t { webcam = 0 , photo = 1 , video = 3 } ;
enum class Type_tracking : int16_t { no_tracking = 0 , lucas_kanade = 1 , kalman_track = 2 , video_extruder_vid = 3};
enum class Type_output : int16_t { VIDEO_HOUGH = 0 , ORIGINAL_VIDEO = 1 , GRADIENT_VIDEO = 2,ORIGINAL_AND_HOUGH_VIDEO = 3   };
enum class Type_Lines : int8_t { EXTREMITE = 0 , ALL_POINTS = 1 , ONLY_POLAR = 2 };
enum class Frequence : int8_t { ALL_FRAME = 0 , NOT_ALL = 1 };
enum class Mode : int8_t { ONLY_VPP = 0 , OPTIMIZED = 1 };
enum class With_Kalman_Filter : int8_t { YES = 1 , NO = 0 };
enum class With_Transparency : int8_t { YES = 1 , NO = 0 };

float  motion_threshold = 100;
#define hough_sequentiel 1
#define hough_parallel 2
#define hough_modified_kmeans 3
#define hough_parallel_map 7
#define hough_test 8
#define mode_capture_webcam 1
#define mode_capture_photo 2
#define mode_capture_video 3
#define video_extruder_video 4
#define mode_capture_vid_try 5
#define mode_capture_kalman 6
#define feature_matching_video 7
Matrix<float,3,3> GySobel3x3;
Matrix<float,3,3> GxSobel3x3;
Matrix<float,5,5> GySobel5x5;
Matrix<float,5,5> GxSobel5x5;
Matrix<float,7,7> GySobel7x7;
Matrix<float,7,7> GxSobel7x7;
Matrix<float,9,9> GySobel9x9;
Matrix<float,9,9> GxSobel9x9;

#endif // DEFINE_HH
<commit_msg>Update define.hh<commit_after>#ifndef DEFINE_HH
#define DEFINE_HH

#include <vector>
#include <opencv2/highgui.hpp>
#include <vpp/vpp.hh>
#include <Eigen/Core>

using namespace Eigen;

using namespace vpp;

double execution_time = 0;
double execution_t= 0;

enum class Theta_max : int32_t { XXSMALL = 67 , XSMALL = 127 , SMALL = 255, MEDIUM = 500, LARGE = 1000 , XLARGE = 1500};
enum class Sclare_rho : int32_t { ONE_QUART = 3, HALF = 2 , THREE_QUART = 1 , SAME = 0};
enum class Type_video_hough : int8_t { ONLY_CLUSTERS = 1 , ALL_POINTS = 2 };
enum class Type_capture : int16_t { webcam = 0 , photo = 1 , video = 3 } ;
enum class Type_tracking : int16_t { no_tracking = 0 , lucas_kanade = 1 , kalman_track = 2 , video_extruder_vid = 3};
enum class Type_output : int16_t { VIDEO_HOUGH = 0 , ORIGINAL_VIDEO = 1 , GRADIENT_VIDEO = 2,ORIGINAL_AND_HOUGH_VIDEO = 3   };
enum class Type_Lines : int8_t { EXTREMITE = 0 , ALL_POINTS = 1 , ONLY_POLAR = 2 };
enum class Frequence : int8_t { ALL_FRAME = 0 , NOT_ALL = 1 };
enum class Mode : int8_t { ONLY_VPP = 0 , OPTIMIZED = 1 };
enum class With_Kalman_Filter : int8_t { YES = 1 , NO = 0 };
enum class With_Transparency : int8_t { YES = 1 , NO = 0 };
enum class With_Entries : int8_t { YES = 1 , NO = 0 };

float  motion_threshold = 100;
#define dense_ht 2
#define feature_matching 7
Matrix<float,3,3> GySobel3x3;
Matrix<float,3,3> GxSobel3x3;
Matrix<float,5,5> GySobel5x5;
Matrix<float,5,5> GxSobel5x5;
Matrix<float,7,7> GySobel7x7;
Matrix<float,7,7> GxSobel7x7;
Matrix<float,9,9> GySobel9x9;
Matrix<float,9,9> GxSobel9x9;

#endif // DEFINE_HH
<|endoftext|>


<commit_before>/*****************************************************************************/
// Prácticas de Sistemas Concurrentes y Distribuidos
// Por David Vargas Carrillo, 2016
/*****************************************************************************/

#include <iostream>
#include <time.h>      // incluye "time"
#include <unistd.h>    // incluye "usleep"
#include <stdlib.h>    // incluye "rand" y "srand"
#include <mpi.h>

#define CAMARERO 10

using namespace std;

void Filosofo (int id, int nprocesos);
void Tenedor (int id, int nprocesos);
void Camarero (int id, int nprocesos);

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

int main (int argc, char* argv[])
{
   int rank, size;

   srand(time(0));
   MPI_Init (&argc, &argv);
   MPI_Comm_rank (MPI_COMM_WORLD, &rank);
   MPI_Comm_size (MPI_COMM_WORLD, &size);

   if (size != 11)
   {
      if (rank == 0)
         cout << "El numero de procesos debe ser de 11" << endl << flush ;
      MPI_Finalize( );
      return 0;
   }

   if (rank == CAMARERO)
    Camarero(rank, size);
   else if ((rank % 2) == 0)
      Filosofo(rank, size);    // Los pares son Filosofos
   else
      Tenedor(rank, size);     // Los impares son Tenedores

   MPI_Finalize();
   return 0;
}
// ---------------------------------------------------------------------

void Filosofo (int id, int nprocesos)
{
   int izq = (id + 1) % nprocesos;                       // Tenedor izquierdo
   int der = ((id + nprocesos) - 1) % nprocesos;         // Tenedor derecho

   MPI_Status status;

   int peticion = 1;          // Valor que se envía para pedir el tenedor
   int depositar = 0;         // Valor que se envía para depositar el tenedor

   while (true)
   {
      // Pide permiso y espera a que el camarero le llame para sentarse (tag 1)
      MPI_Ssend(&peticion, 1, MPI_INT, CAMARERO, 1, MPI_COMM_WORLD);
      cout << "Filosofo " << id << " se sienta" << endl << flush;

      // A la hora de solicitar y depositar los tenedores enviará los mensajes con tag 0
      // Solicita tenedor izquierdo
      cout << "Filosofo " << id << " solicita tenedor izquierdo " << izq << endl << flush;
      MPI_Ssend(&peticion, 1, MPI_INT, izq, 0, MPI_COMM_WORLD);

      // Solicita tenedor derecho
      cout << "Filosofo " << id << " solicita tenedor derecho " << der << endl << flush;
      MPI_Ssend(&peticion, 1, MPI_INT, der, 0, MPI_COMM_WORLD);

      // Come
      cout << "Filosofo " << id << " COMIENDO..." << endl << flush;
      sleep((rand() % 3) + 1);

      // Suelta el tenedor izquierdo
      cout << "Filosofo " << id << " suelta tenedor izquierdo " << izq << endl << flush;
      MPI_Ssend(&depositar, 1, MPI_INT, izq, 0, MPI_COMM_WORLD);

      // Suelta el tenedor derecho
      cout << "Filosofo " << id << " suelta tenedor derecho " << der << endl << flush;
      MPI_Ssend(&depositar, 1, MPI_INT, der, 0, MPI_COMM_WORLD);

      // Piensa (espera bloqueada aleatorio del proceso)
      cout << "Filosofo " << id << " PENSANDO..." << endl << flush;

      // espera bloqueado durante un intervalo de tiempo aleatorio
      // (entre una décima de segundo y un segundo)
      usleep (1000U * (100U + (rand() % 900U)));

      // Pide permiso para levantarse y espera a que el camarero lo permita (tag 2)
      MPI_Ssend(&peticion, 1, MPI_INT, CAMARERO, 2, MPI_COMM_WORLD);
      cout << "Filosofo " << id << " se levanta" << endl << flush;
 }
}

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

void Tenedor (int id, int nprocesos)
{
  int buf;
  MPI_Status status;
  int Filo;

  while (true)
  {
    // Espera un peticion desde cualquier filosofo vecino
    MPI_Probe(MPI_ANY_SOURCE, MPI_ANY_TAG, MPI_COMM_WORLD, &status);

    // Recibe la peticion del filosofo
    Filo = status.MPI_SOURCE;
    MPI_Recv(&buf, 1, MPI_INT, Filo, 0, MPI_COMM_WORLD, &status);
    cout << "Tenedor " << id << " recibe peticion de " << Filo << endl << flush;

    // Espera a que el filosofo suelte el tenedor...
    MPI_Recv(&buf, 1, MPI_INT, Filo, 0, MPI_COMM_WORLD, &status);
    cout << "Tenedor " << id << " recibe liberacion de " << Filo << endl << flush;
  }
}

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

void Camarero (int id, int nprocesos)
{
  MPI_Status status;

  int Filo;
  int buf;
  int num_sentados = 0;

  while (true)
  {
    MPI_Probe(MPI_ANY_SOURCE, MPI_ANY_TAG, MPI_COMM_WORLD, &status);

    // Si ya hay 4 filosofos sentados, esperar a que alguno se levante
    if (num_sentados == 4)
    {
      MPI_Recv(&buf, 1, MPI_INT, MPI_ANY_SOURCE, 2, MPI_COMM_WORLD, &status);
      Filo = status.MPI_SOURCE;
      cout << "Camarero recibe la peticion de levantarse del filosofo " << Filo << endl << flush;
      num_sentados--;
    }

    else
    {
      MPI_Recv(&buf, 1, MPI_INT, MPI_ANY_SOURCE, 1, MPI_COMM_WORLD, &status);
      Filo = status.MPI_SOURCE;
      cout << "Camarero recibe la peticion de sentarse del filosofo " << Filo << endl << flush;
      num_sentados++;
    }
  }
}
<commit_msg>Updated<commit_after>/*****************************************************************************/
// Prácticas de Sistemas Concurrentes y Distribuidos
// Por David Vargas Carrillo, 2016
/*****************************************************************************/

#include <iostream>
#include <time.h>      // incluye "time"
#include <unistd.h>    // incluye "usleep"
#include <stdlib.h>    // incluye "rand" y "srand"
#include <mpi.h>

#define CAMARERO 10

using namespace std;

void Filosofo (int id, int nprocesos);
void Tenedor (int id, int nprocesos);
void Camarero (int id, int nprocesos);

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

int main (int argc, char* argv[])
{
   int rank, size;

   srand(time(0));
   MPI_Init (&argc, &argv);
   MPI_Comm_rank (MPI_COMM_WORLD, &rank);
   MPI_Comm_size (MPI_COMM_WORLD, &size);

   if (size != 11)
   {
      if (rank == 0)
         cout << "El numero de procesos debe ser de 11" << endl << flush ;
      MPI_Finalize( );
      return 0;
   }

   if (rank == CAMARERO)
    Camarero(rank, size);
   else if ((rank % 2) == 0)
      Filosofo(rank, size);    // Los pares son Filosofos
   else
      Tenedor(rank, size);     // Los impares son Tenedores

   MPI_Finalize();
   return 0;
}
// ---------------------------------------------------------------------

void Filosofo (int id, int nprocesos)
{
   int izq = (id + 1) % nprocesos;                       // Tenedor izquierdo
   int der = ((id + nprocesos) - 1) % nprocesos;         // Tenedor derecho

   MPI_Status status;

   int peticion = 1;          // Valor que se envía para pedir el tenedor
   int depositar = 0;         // Valor que se envía para depositar el tenedor

   while (true)
   {
      // Pide permiso y espera a que el camarero le llame para sentarse (tag 1)
      MPI_Ssend(&peticion, 1, MPI_INT, CAMARERO, 1, MPI_COMM_WORLD);
      cout << "Filosofo " << id << " se sienta" << endl << flush;

      // A la hora de solicitar y depositar los tenedores enviará los mensajes con tag 0
      // Solicita tenedor izquierdo
      cout << "Filosofo " << id << " solicita tenedor izquierdo " << izq << endl << flush;
      MPI_Ssend(&peticion, 1, MPI_INT, izq, 0, MPI_COMM_WORLD);

      // Solicita tenedor derecho
      cout << "Filosofo " << id << " solicita tenedor derecho " << der << endl << flush;
      MPI_Ssend(&peticion, 1, MPI_INT, der, 0, MPI_COMM_WORLD);

      // Come
      cout << "Filosofo " << id << " COMIENDO..." << endl << flush;
      sleep((rand() % 3) + 1);

      // Suelta el tenedor izquierdo
      cout << "Filosofo " << id << " suelta tenedor izquierdo " << izq << endl << flush;
      MPI_Ssend(&depositar, 1, MPI_INT, izq, 0, MPI_COMM_WORLD);

      // Suelta el tenedor derecho
      cout << "Filosofo " << id << " suelta tenedor derecho " << der << endl << flush;
      MPI_Ssend(&depositar, 1, MPI_INT, der, 0, MPI_COMM_WORLD);

      // Piensa (espera bloqueada aleatorio del proceso)
      cout << "Filosofo " << id << " PENSANDO..." << endl << flush;

      // espera bloqueado durante un intervalo de tiempo aleatorio
      // (entre una décima de segundo y un segundo)
      usleep (1000U * (100U + (rand() % 900U)));

      // Pide permiso para levantarse y espera a que el camarero lo permita (tag 2)
      MPI_Ssend(&peticion, 1, MPI_INT, CAMARERO, 2, MPI_COMM_WORLD);
      cout << "Filosofo " << id << " se levanta" << endl << flush;
 }
}

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

void Tenedor (int id, int nprocesos)
{
  int buf;
  MPI_Status status;
  int Filo;

  while (true)
  {
    // Espera un peticion desde cualquier filosofo vecino
    MPI_Probe(MPI_ANY_SOURCE, MPI_ANY_TAG, MPI_COMM_WORLD, &status);

    // Recibe la peticion del filosofo
    Filo = status.MPI_SOURCE;
    MPI_Recv(&buf, 1, MPI_INT, Filo, 0, MPI_COMM_WORLD, &status);
    cout << "Tenedor " << id << " recibe peticion de " << Filo << endl << flush;

    // Espera a que el filosofo suelte el tenedor...
    MPI_Recv(&buf, 1, MPI_INT, Filo, 0, MPI_COMM_WORLD, &status);
    cout << "Tenedor " << id << " recibe liberacion de " << Filo << endl << flush;
  }
}

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

void Camarero (int id, int nprocesos)
{
  MPI_Status status;

  int Filo;
  int buf;
  int num_sentados = 0;

  while (true)
  {
    // Si ya hay 4 filosofos sentados, esperar a que alguno se levante
    if (num_sentados == 4)
    {
      MPI_Recv(&buf, 1, MPI_INT, MPI_ANY_SOURCE, 2, MPI_COMM_WORLD, &status);
      Filo = status.MPI_SOURCE;
      cout << "Camarero recibe la peticion de levantarse del filosofo " << Filo << endl << flush;
      num_sentados--;
    }

    else
    {
      MPI_Recv(&buf, 1, MPI_INT, MPI_ANY_SOURCE, 1, MPI_COMM_WORLD, &status);
      Filo = status.MPI_SOURCE;
      cout << "Camarero recibe la peticion de sentarse del filosofo " << Filo << endl << flush;
      num_sentados++;
    }
  }
}
<|endoftext|>


<commit_before>/**************************************************************************
 * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
 *                                                                        *
 * Author: The ALICE Off-line Project.                                    *
 * Contributors are mentioned in the code where appropriate.              *
 *                                                                        *
 * Permission to use, copy, modify and distribute this software and its   *
 * documentation strictly for non-commercial purposes is hereby granted   *
 * without fee, provided that the above copyright notice appears in all   *
 * copies and that both the copyright notice and this permission notice   *
 * appear in the supporting documentation. The authors make no claims     *
 * about the suitability of this software for any purpose. It is          *
 * provided "as is" without express or implied warranty.                  *
 **************************************************************************/

/// \class AliMUONPayloadTrigger
/// Class Payload
///
/// Decodes rawdata from buffer and stores in TClonesArray.
///
/// First version implement for Trigger
///
/// \author Christian Finck

#include "AliMUONPayloadTrigger.h"

#include "AliMUONDarcHeader.h"
#include "AliMUONRegHeader.h"
#include "AliMUONLocalStruct.h"
#include "AliMUONDDLTrigger.h"

#include "AliLog.h"

/// \cond CLASSIMP
ClassImp(AliMUONPayloadTrigger)
/// \endcond

AliMUONPayloadTrigger::AliMUONPayloadTrigger()
  : TObject(),
    fMaxReg(8),
    fMaxLoc(16),
    fDDLTrigger(new AliMUONDDLTrigger()),
    fRegHeader(new AliMUONRegHeader()),
    fLocalStruct(new AliMUONLocalStruct())
{
  ///
  /// create an object to read MUON raw digits
  /// Default ctor for monitoring purposes
  ///

}

//___________________________________
AliMUONPayloadTrigger::~AliMUONPayloadTrigger()
{
  ///
  /// clean up
  ///
  delete fDDLTrigger;
  delete fLocalStruct;
  delete fRegHeader;
}

//______________________________________________________
Bool_t AliMUONPayloadTrigger::Decode(UInt_t *buffer)
{
  /// decode trigger DDL
  /// store only notified cards

 // reading DDL for trigger

  AliMUONDarcHeader* darcHeader = fDDLTrigger->GetDarcHeader();

  static Int_t kGlobalHeaderSize = darcHeader->GetGlobalHeaderLength();
  static Int_t kDarcHeaderSize   = darcHeader->GetDarcHeaderLength();
  static Int_t kRegHeaderSize    = fRegHeader->GetHeaderLength();

  Bool_t scalerEvent = kFALSE;

  Int_t index = 0;

  memcpy(darcHeader->GetHeader(), &buffer[index], (kDarcHeaderSize)*4);
  index += kDarcHeaderSize;

  if(darcHeader->GetEventType() == 0) {
    scalerEvent = kTRUE;
  } else
    scalerEvent = kFALSE;

  if(scalerEvent) {
    // 6 DARC scaler words
    memcpy(darcHeader->GetDarcScalers(), &buffer[index], darcHeader->GetDarcScalerLength()*4);
    index += darcHeader->GetDarcScalerLength();
  }

  if (buffer[index++] != darcHeader->GetEndOfDarc())

      AliWarning(Form("Wrong end of Darc word %x instead of %x\n",
		    buffer[index-1], darcHeader->GetEndOfDarc()));

  // 4 words of global board input + Global board output
  memcpy(darcHeader->GetGlobalInput(), &buffer[index], (kGlobalHeaderSize)*4);
  index += kGlobalHeaderSize;

  if(scalerEvent) {
    // 10 Global scaler words
    memcpy(darcHeader->GetGlobalScalers(), &buffer[index], darcHeader->GetGlobalScalerLength()*4);
    index += darcHeader->GetGlobalScalerLength();
  }

  if (buffer[index++] != darcHeader->GetEndOfGlobal())

  AliWarning(Form("Wrong end of Global word %x instead of %x\n",
		buffer[index-1], darcHeader->GetEndOfGlobal()));

  // 8 regional boards
  for (Int_t iReg = 0; iReg < fMaxReg; iReg++) {           //loop over regeonal card

    memcpy(fRegHeader->GetHeader(), &buffer[index], kRegHeaderSize*4);
    index += kRegHeaderSize;

    fDDLTrigger->AddRegHeader(*fRegHeader);
    // 11 regional scaler word
    if(scalerEvent) {
      memcpy(fRegHeader->GetScalers(), &buffer[index], fRegHeader->GetScalerLength()*4);
      index += fRegHeader->GetScalerLength();
    }

    if (buffer[index++] != fRegHeader->GetEndOfReg())

      AliWarning(Form("Wrong end of Reg word %x instead of %x\n",
		    buffer[index-1], fRegHeader->GetEndOfReg()));

    // 16 local cards per regional board
    for (Int_t iLoc = 0; iLoc < fMaxLoc; iLoc++) {         //loop over local card

      Int_t dataSize = fLocalStruct->GetLength();;

      // 5 word trigger information
      memcpy(fLocalStruct->GetData(), &buffer[index], dataSize*4);
      index += dataSize;

      // 45 regional scaler word
      if(scalerEvent) {
	memcpy(fLocalStruct->GetScalers(), &buffer[index], fLocalStruct->GetScalerLength()*4);
	index += fLocalStruct->GetScalerLength();
      }

      if (buffer[index++] != fLocalStruct->GetEndOfLocal())

      AliWarning(Form("Wrong end of local word %x instead of %x\n",
		    buffer[index-1], fLocalStruct->GetEndOfLocal()));

      // fill only if card notified
      if (fLocalStruct->GetData(0) == fLocalStruct->GetDisableWord())
	  continue;

      fDDLTrigger->AddLocStruct(*fLocalStruct, iReg);

    } // local card loop

  } // regional card loop

  return kTRUE;
}

//______________________________________________________
void AliMUONPayloadTrigger::ResetDDL()
{
  /// reseting TClonesArray
  /// after each DDL
  ///
  AliMUONDarcHeader* darcHeader = fDDLTrigger->GetDarcHeader();
  darcHeader->GetRegHeaderArray()->Delete();
}

//______________________________________________________
void AliMUONPayloadTrigger::SetMaxReg(Int_t reg)
{
  /// set regional card number
  if (reg > 8) reg = 8;
  fMaxReg = reg;
}

//______________________________________________________
void AliMUONPayloadTrigger::SetMaxLoc(Int_t loc)
{
  /// set local card number
  if (loc > 16) loc = 16;
  fMaxLoc = loc;
}
<commit_msg>Increment the error counters & reset them (Christian)<commit_after>/**************************************************************************
 * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
 *                                                                        *
 * Author: The ALICE Off-line Project.                                    *
 * Contributors are mentioned in the code where appropriate.              *
 *                                                                        *
 * Permission to use, copy, modify and distribute this software and its   *
 * documentation strictly for non-commercial purposes is hereby granted   *
 * without fee, provided that the above copyright notice appears in all   *
 * copies and that both the copyright notice and this permission notice   *
 * appear in the supporting documentation. The authors make no claims     *
 * about the suitability of this software for any purpose. It is          *
 * provided "as is" without express or implied warranty.                  *
 **************************************************************************/

/// \class AliMUONPayloadTrigger
/// Class Payload
///
/// Decodes rawdata from buffer and stores in TClonesArray.
///
/// First version implement for Trigger
///
/// \author Christian Finck

#include "AliMUONPayloadTrigger.h"

#include "AliMUONDarcHeader.h"
#include "AliMUONRegHeader.h"
#include "AliMUONLocalStruct.h"
#include "AliMUONDDLTrigger.h"

#include "AliLog.h"

/// \cond CLASSIMP
ClassImp(AliMUONPayloadTrigger)
/// \endcond

AliMUONPayloadTrigger::AliMUONPayloadTrigger()
  : TObject(),
    fMaxReg(8),
    fMaxLoc(16),
    fDDLTrigger(new AliMUONDDLTrigger()),
    fRegHeader(new AliMUONRegHeader()),
    fLocalStruct(new AliMUONLocalStruct()),
    fDarcEoWErrors(0),
    fGlobalEoWErrors(0),
    fRegEoWErrors(0),
    fLocalEoWErrors(0)
{
  ///
  /// create an object to read MUON raw digits
  /// Default ctor for monitoring purposes
  ///

}

//___________________________________
AliMUONPayloadTrigger::~AliMUONPayloadTrigger()
{
  ///
  /// clean up
  ///
  delete fDDLTrigger;
  delete fLocalStruct;
  delete fRegHeader;
}

//______________________________________________________
Bool_t AliMUONPayloadTrigger::Decode(UInt_t *buffer)
{
  /// decode trigger DDL
  /// store only notified cards

 // reading DDL for trigger

  AliMUONDarcHeader* darcHeader = fDDLTrigger->GetDarcHeader();

  static Int_t kGlobalHeaderSize = darcHeader->GetGlobalHeaderLength();
  static Int_t kDarcHeaderSize   = darcHeader->GetDarcHeaderLength();
  static Int_t kRegHeaderSize    = fRegHeader->GetHeaderLength();

  Bool_t scalerEvent = kFALSE;

  Int_t index = 0;

  memcpy(darcHeader->GetHeader(), &buffer[index], (kDarcHeaderSize)*4);
  index += kDarcHeaderSize;

  if(darcHeader->GetEventType() == 0) {
    scalerEvent = kTRUE;
  } else
    scalerEvent = kFALSE;

  if(scalerEvent) {
    // 6 DARC scaler words
    memcpy(darcHeader->GetDarcScalers(), &buffer[index], darcHeader->GetDarcScalerLength()*4);
    index += darcHeader->GetDarcScalerLength();
  }

  if (buffer[index++] != darcHeader->GetEndOfDarc()) {

      AliWarning(Form("Wrong end of Darc word %x instead of %x\n",
		    buffer[index-1], darcHeader->GetEndOfDarc()));
      fDarcEoWErrors++;
  }
  // 4 words of global board input + Global board output
  memcpy(darcHeader->GetGlobalInput(), &buffer[index], (kGlobalHeaderSize)*4);
  index += kGlobalHeaderSize;

  if(scalerEvent) {
    // 10 Global scaler words
    memcpy(darcHeader->GetGlobalScalers(), &buffer[index], darcHeader->GetGlobalScalerLength()*4);
    index += darcHeader->GetGlobalScalerLength();
  }

  if (buffer[index++] != darcHeader->GetEndOfGlobal()) {

      AliWarning(Form("Wrong end of Global word %x instead of %x\n",
		      buffer[index-1], darcHeader->GetEndOfGlobal()));
      fGlobalEoWErrors++;
  }
  // 8 regional boards
  for (Int_t iReg = 0; iReg < fMaxReg; iReg++) {           //loop over regeonal card

    memcpy(fRegHeader->GetHeader(), &buffer[index], kRegHeaderSize*4);
    index += kRegHeaderSize;

    fDDLTrigger->AddRegHeader(*fRegHeader);
    // 11 regional scaler word
    if(scalerEvent) {
      memcpy(fRegHeader->GetScalers(), &buffer[index], fRegHeader->GetScalerLength()*4);
      index += fRegHeader->GetScalerLength();
    }

    if (buffer[index++] != fRegHeader->GetEndOfReg()) {

      AliWarning(Form("Wrong end of Reg word %x instead of %x\n",
		    buffer[index-1], fRegHeader->GetEndOfReg()));
      fRegEoWErrors++;
    }
    // 16 local cards per regional board
    for (Int_t iLoc = 0; iLoc < fMaxLoc; iLoc++) {         //loop over local card

      Int_t dataSize = fLocalStruct->GetLength();;

      // 5 word trigger information
      memcpy(fLocalStruct->GetData(), &buffer[index], dataSize*4);
      index += dataSize;

      // 45 regional scaler word
      if(scalerEvent) {
	memcpy(fLocalStruct->GetScalers(), &buffer[index], fLocalStruct->GetScalerLength()*4);
	index += fLocalStruct->GetScalerLength();
      }

      if (buffer[index++] != fLocalStruct->GetEndOfLocal()) {

	AliWarning(Form("Wrong end of local word %x instead of %x\n",
			buffer[index-1], fLocalStruct->GetEndOfLocal()));
	fLocalEoWErrors++;
      }
      // fill only if card notified
      if (fLocalStruct->GetData(0) == fLocalStruct->GetDisableWord())
	  continue;

      fDDLTrigger->AddLocStruct(*fLocalStruct, iReg);

    } // local card loop

  } // regional card loop

  return kTRUE;
}

//______________________________________________________
void AliMUONPayloadTrigger::ResetDDL()
{
  /// reseting TClonesArray
  /// after each DDL
  ///
  AliMUONDarcHeader* darcHeader = fDDLTrigger->GetDarcHeader();
  darcHeader->GetRegHeaderArray()->Delete();
  fDarcEoWErrors   = 0;
  fGlobalEoWErrors = 0;
  fRegEoWErrors    = 0;
  fLocalEoWErrors  = 0;
}

//______________________________________________________
void AliMUONPayloadTrigger::SetMaxReg(Int_t reg)
{
  /// set regional card number
  if (reg > 8) reg = 8;
  fMaxReg = reg;
}

//______________________________________________________
void AliMUONPayloadTrigger::SetMaxLoc(Int_t loc)
{
  /// set local card number
  if (loc > 16) loc = 16;
  fMaxLoc = loc;
}
<|endoftext|>


<commit_before>/*-------------------------------------------------------------------------
 * drawElements Quality Program Tester Core
 * ----------------------------------------
 *
 * Copyright 2014 The Android Open Source Project
 *
 * 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.
 *
 *//*!
 * \file
 * \brief X11 utilities.
 *//*--------------------------------------------------------------------*/

#include "tcuX11.hpp"
#include "gluRenderConfig.hpp"
#include "deMemory.h"

#include <X11/Xutil.h>

namespace tcu
{
namespace x11
{

EventState::EventState (void)
	: m_quit(false)
{
}

EventState::~EventState (void)
{
}

void EventState::setQuitFlag (bool quit)
{
	de::ScopedLock lock(m_mutex);
	m_quit = quit;
}

bool EventState::getQuitFlag (void)
{
	de::ScopedLock lock(m_mutex);
	return m_quit;
}

DisplayBase::DisplayBase (EventState& platform)
	: m_eventState	(platform)
{
}

DisplayBase::~DisplayBase (void)
{
}

WindowBase::WindowBase ()
	: m_visible	(false)
{
}

WindowBase::~WindowBase (void)
{
}

XlibDisplay::XlibDisplay (EventState& eventState, const char* name)
	: DisplayBase	(eventState)
{
	m_display = XOpenDisplay((char*)name); // Won't modify argument string.
	if (!m_display)
		throw ResourceError("Failed to open display", name, __FILE__, __LINE__);

	m_deleteAtom	= XInternAtom(m_display, "WM_DELETE_WINDOW", False);
}

XlibDisplay::~XlibDisplay (void)
{
	XCloseDisplay(m_display);
}

void XlibDisplay::processEvent (XEvent& event)
{
	switch (event.type)
	{
		case ClientMessage:
			if ((unsigned)event.xclient.data.l[0] == m_deleteAtom)
				m_eventState.setQuitFlag(true);
			break;
		// note: ConfigureNotify for window is handled in setDimensions()
		default:
			break;
	}
}

void XlibDisplay::processEvents (void)
{
	XEvent	event;

	while (XPending(m_display))
	{
		XNextEvent(m_display, &event);
		processEvent(event);
	}
}

bool XlibDisplay::getVisualInfo (VisualID visualID, XVisualInfo& dst)
{
	XVisualInfo		query;
	query.visualid = visualID;
	int				numVisuals	= 0;
	XVisualInfo*	response	= XGetVisualInfo(m_display, VisualIDMask, &query, &numVisuals);
	bool			succ		= false;

	if (response != DE_NULL)
	{
		if (numVisuals > 0) // should be 1, but you never know...
		{
			dst = response[0];
			succ = true;
		}
		XFree(response);
	}

	return succ;
}

::Visual* XlibDisplay::getVisual (VisualID visualID)
{
	XVisualInfo		info;

	if (getVisualInfo(visualID, info))
		return info.visual;

	return DE_NULL;
}

XlibWindow::XlibWindow (XlibDisplay& display, int width, int height, ::Visual* visual)
	: WindowBase	()
	, m_display		(display)
	, m_colormap	(None)
	, m_window		(None)
{
	XSetWindowAttributes	swa;
	::Display* const		dpy					= m_display.getXDisplay();
	::Window				root				= DefaultRootWindow(dpy);
	unsigned long			mask				= CWBorderPixel | CWEventMask;

	// If redirect is enabled, window size can't be guaranteed and it is up to
	// the window manager to decide whether to honor sizing requests. However,
	// overriding that causes window to appear as an overlay, which causes
	// other issues, so this is disabled by default.
	const bool				overrideRedirect	= false;

	if (overrideRedirect)
	{
		mask |= CWOverrideRedirect;
		swa.override_redirect = true;
	}

	if (visual == DE_NULL)
		visual = CopyFromParent;
	else
	{
		XVisualInfo	info	= XVisualInfo();
		bool		succ	= display.getVisualInfo(XVisualIDFromVisual(visual), info);

		TCU_CHECK_INTERNAL(succ);

		root				= RootWindow(dpy, info.screen);
		m_colormap			= XCreateColormap(dpy, root, visual, AllocNone);
		swa.colormap		= m_colormap;
		mask |= CWColormap;
	}

	swa.border_pixel	= 0;
	swa.event_mask		= ExposureMask|KeyPressMask|KeyReleaseMask|StructureNotifyMask;

	if (width == glu::RenderConfig::DONT_CARE)
		width = DEFAULT_WINDOW_WIDTH;
	if (height == glu::RenderConfig::DONT_CARE)
		height = DEFAULT_WINDOW_HEIGHT;

	m_window = XCreateWindow(dpy, root, 0, 0, width, height, 0,
							 CopyFromParent, InputOutput, visual, mask, &swa);
	TCU_CHECK(m_window);

	Atom deleteAtom = m_display.getDeleteAtom();
	XSetWMProtocols(dpy, m_window, &deleteAtom, 1);
	XSync(dpy,false);
}

void XlibWindow::setVisibility (bool visible)
{
	::Display*	dpy			= m_display.getXDisplay();
	int			eventType	= None;
	XEvent		event;

	if (visible == m_visible)
		return;

	if (visible)
	{
		XMapWindow(dpy, m_window);
		eventType = MapNotify;
	}
	else
	{
		XUnmapWindow(dpy, m_window);
		eventType = UnmapNotify;
	}

	// We are only interested about exposure/structure notify events, not user input
	XSelectInput(dpy, m_window, ExposureMask | StructureNotifyMask);

	do
	{
		XNextEvent(dpy, &event);
	} while (event.type != eventType);

	m_visible = visible;
}

void XlibWindow::getDimensions (int* width, int* height) const
{
	int x, y;
	::Window root;
	unsigned width_, height_, borderWidth, depth;

	XGetGeometry(m_display.getXDisplay(), m_window, &root, &x, &y, &width_, &height_, &borderWidth, &depth);
	if (width != DE_NULL)
		*width = static_cast<int>(width_);
	if (height != DE_NULL)
		*height = static_cast<int>(height_);
}

void XlibWindow::setDimensions (int width, int height)
{
	const unsigned int	mask		= CWWidth | CWHeight;
	XWindowChanges		changes;
	::Display*			dpy			= m_display.getXDisplay();
	XEvent				myevent;
	changes.width	= width;
	changes.height	= height;
	XConfigureWindow(dpy, m_window, mask, &changes);
	XFlush(dpy);

	for(;;)
	{
		XNextEvent(dpy, &myevent);
		if (myevent.type == ConfigureNotify) {
			XConfigureEvent e = myevent.xconfigure;
			if (e.width == width && e.height == height)
				break;
		}
		else
			m_display.processEvent(myevent);
	}
}

void XlibWindow::processEvents (void)
{
	// A bit of a hack, since we don't really handle all the events.
	m_display.processEvents();
}

XlibWindow::~XlibWindow (void)
{
	XDestroyWindow(m_display.getXDisplay(), m_window);
	if (m_colormap != None)
		XFreeColormap(m_display.getXDisplay(), m_colormap);
}

} // x11
} // tcu
<commit_msg>x11: Fix deadlock am: 5e863331b2<commit_after>/*-------------------------------------------------------------------------
 * drawElements Quality Program Tester Core
 * ----------------------------------------
 *
 * Copyright 2014 The Android Open Source Project
 *
 * 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.
 *
 *//*!
 * \file
 * \brief X11 utilities.
 *//*--------------------------------------------------------------------*/

#include "tcuX11.hpp"
#include "gluRenderConfig.hpp"
#include "deMemory.h"

#include <X11/Xutil.h>

namespace tcu
{
namespace x11
{

EventState::EventState (void)
	: m_quit(false)
{
}

EventState::~EventState (void)
{
}

void EventState::setQuitFlag (bool quit)
{
	de::ScopedLock lock(m_mutex);
	m_quit = quit;
}

bool EventState::getQuitFlag (void)
{
	de::ScopedLock lock(m_mutex);
	return m_quit;
}

DisplayBase::DisplayBase (EventState& platform)
	: m_eventState	(platform)
{
}

DisplayBase::~DisplayBase (void)
{
}

WindowBase::WindowBase ()
	: m_visible	(false)
{
}

WindowBase::~WindowBase (void)
{
}

XlibDisplay::XlibDisplay (EventState& eventState, const char* name)
	: DisplayBase	(eventState)
{
	m_display = XOpenDisplay((char*)name); // Won't modify argument string.
	if (!m_display)
		throw ResourceError("Failed to open display", name, __FILE__, __LINE__);

	m_deleteAtom	= XInternAtom(m_display, "WM_DELETE_WINDOW", False);
}

XlibDisplay::~XlibDisplay (void)
{
	XCloseDisplay(m_display);
}

void XlibDisplay::processEvent (XEvent& event)
{
	switch (event.type)
	{
		case ClientMessage:
			if ((unsigned)event.xclient.data.l[0] == m_deleteAtom)
				m_eventState.setQuitFlag(true);
			break;
		// note: ConfigureNotify for window is handled in setDimensions()
		default:
			break;
	}
}

void XlibDisplay::processEvents (void)
{
	XEvent	event;

	while (XPending(m_display))
	{
		XNextEvent(m_display, &event);
		processEvent(event);
	}
}

bool XlibDisplay::getVisualInfo (VisualID visualID, XVisualInfo& dst)
{
	XVisualInfo		query;
	query.visualid = visualID;
	int				numVisuals	= 0;
	XVisualInfo*	response	= XGetVisualInfo(m_display, VisualIDMask, &query, &numVisuals);
	bool			succ		= false;

	if (response != DE_NULL)
	{
		if (numVisuals > 0) // should be 1, but you never know...
		{
			dst = response[0];
			succ = true;
		}
		XFree(response);
	}

	return succ;
}

::Visual* XlibDisplay::getVisual (VisualID visualID)
{
	XVisualInfo		info;

	if (getVisualInfo(visualID, info))
		return info.visual;

	return DE_NULL;
}

XlibWindow::XlibWindow (XlibDisplay& display, int width, int height, ::Visual* visual)
	: WindowBase	()
	, m_display		(display)
	, m_colormap	(None)
	, m_window		(None)
{
	XSetWindowAttributes	swa;
	::Display* const		dpy					= m_display.getXDisplay();
	::Window				root				= DefaultRootWindow(dpy);
	unsigned long			mask				= CWBorderPixel | CWEventMask;

	// If redirect is enabled, window size can't be guaranteed and it is up to
	// the window manager to decide whether to honor sizing requests. However,
	// overriding that causes window to appear as an overlay, which causes
	// other issues, so this is disabled by default.
	const bool				overrideRedirect	= false;

	if (overrideRedirect)
	{
		mask |= CWOverrideRedirect;
		swa.override_redirect = true;
	}

	if (visual == DE_NULL)
		visual = CopyFromParent;
	else
	{
		XVisualInfo	info	= XVisualInfo();
		bool		succ	= display.getVisualInfo(XVisualIDFromVisual(visual), info);

		TCU_CHECK_INTERNAL(succ);

		root				= RootWindow(dpy, info.screen);
		m_colormap			= XCreateColormap(dpy, root, visual, AllocNone);
		swa.colormap		= m_colormap;
		mask |= CWColormap;
	}

	swa.border_pixel	= 0;
	swa.event_mask		= ExposureMask|KeyPressMask|KeyReleaseMask|StructureNotifyMask;

	if (width == glu::RenderConfig::DONT_CARE)
		width = DEFAULT_WINDOW_WIDTH;
	if (height == glu::RenderConfig::DONT_CARE)
		height = DEFAULT_WINDOW_HEIGHT;

	m_window = XCreateWindow(dpy, root, 0, 0, width, height, 0,
							 CopyFromParent, InputOutput, visual, mask, &swa);
	TCU_CHECK(m_window);

	Atom deleteAtom = m_display.getDeleteAtom();
	XSetWMProtocols(dpy, m_window, &deleteAtom, 1);
	XSync(dpy,false);
}

void XlibWindow::setVisibility (bool visible)
{
	::Display*	dpy			= m_display.getXDisplay();
	int			eventType	= None;
	XEvent		event;

	if (visible == m_visible)
		return;

	if (visible)
	{
		XMapWindow(dpy, m_window);
		eventType = MapNotify;
	}
	else
	{
		XUnmapWindow(dpy, m_window);
		eventType = UnmapNotify;
	}

	// We are only interested about exposure/structure notify events, not user input
	XSelectInput(dpy, m_window, ExposureMask | StructureNotifyMask);

	do
	{
		XWindowEvent(dpy, m_window, ExposureMask | StructureNotifyMask, &event);
	} while (event.type != eventType);

	m_visible = visible;
}

void XlibWindow::getDimensions (int* width, int* height) const
{
	int x, y;
	::Window root;
	unsigned width_, height_, borderWidth, depth;

	XGetGeometry(m_display.getXDisplay(), m_window, &root, &x, &y, &width_, &height_, &borderWidth, &depth);
	if (width != DE_NULL)
		*width = static_cast<int>(width_);
	if (height != DE_NULL)
		*height = static_cast<int>(height_);
}

void XlibWindow::setDimensions (int width, int height)
{
	const unsigned int	mask		= CWWidth | CWHeight;
	XWindowChanges		changes;
	::Display*			dpy			= m_display.getXDisplay();
	XEvent				myevent;
	changes.width	= width;
	changes.height	= height;
	XConfigureWindow(dpy, m_window, mask, &changes);
	XFlush(dpy);

	for(;;)
	{
		XNextEvent(dpy, &myevent);
		if (myevent.type == ConfigureNotify) {
			XConfigureEvent e = myevent.xconfigure;
			if (e.width == width && e.height == height)
				break;
		}
		else
			m_display.processEvent(myevent);
	}
}

void XlibWindow::processEvents (void)
{
	// A bit of a hack, since we don't really handle all the events.
	m_display.processEvents();
}

XlibWindow::~XlibWindow (void)
{
	XDestroyWindow(m_display.getXDisplay(), m_window);
	if (m_colormap != None)
		XFreeColormap(m_display.getXDisplay(), m_colormap);
}

} // x11
} // tcu
<|endoftext|>


<commit_before>// Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "components/nacl/browser/nacl_host_message_filter.h"

#include "base/sys_info.h"
#include "components/nacl/browser/nacl_browser.h"
#include "components/nacl/browser/nacl_file_host.h"
#include "components/nacl/browser/nacl_process_host.h"
#include "components/nacl/browser/pnacl_host.h"
#include "components/nacl/common/nacl_host_messages.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/plugin_service.h"
#include "content/public/browser/render_process_host.h"
#include "content/public/browser/web_contents.h"
#include "ipc/ipc_platform_file.h"
#include "net/url_request/url_request_context.h"
#include "net/url_request/url_request_context_getter.h"
#include "ppapi/shared_impl/ppapi_permissions.h"
#include "url/gurl.h"

namespace nacl {

namespace {

ppapi::PpapiPermissions GetNaClPermissions(
    uint32 permission_bits,
    content::BrowserContext* browser_context,
    const GURL& document_url) {
  // Only allow NaCl plugins to request certain permissions. We don't want
  // a compromised renderer to be able to start a nacl plugin with e.g. Flash
  // permissions which may expand the surface area of the sandbox.
  uint32 masked_bits = permission_bits & ppapi::PERMISSION_DEV;
  if (content::PluginService::GetInstance()->PpapiDevChannelSupported(
          browser_context, document_url))
    masked_bits |= ppapi::PERMISSION_DEV_CHANNEL;
  return ppapi::PpapiPermissions::GetForCommandLine(masked_bits);
}

ppapi::PpapiPermissions GetPpapiPermissions(uint32 permission_bits,
                                            int render_process_id,
                                            int render_view_id) {
  // We get the URL from WebContents from the RenderViewHost, since we don't
  // have a BrowserPpapiHost yet.
  content::RenderProcessHost* host =
      content::RenderProcessHost::FromID(render_process_id);
  content::RenderViewHost* view_host =
      content::RenderViewHost::FromID(render_process_id, render_view_id);
  GURL document_url;
  content::WebContents* contents =
      content::WebContents::FromRenderViewHost(view_host);
  if (contents)
    document_url = contents->GetLastCommittedURL();
  return GetNaClPermissions(permission_bits,
                            host->GetBrowserContext(),
                            document_url);
}

}  // namespace

NaClHostMessageFilter::NaClHostMessageFilter(
    int render_process_id,
    bool is_off_the_record,
    const base::FilePath& profile_directory,
    net::URLRequestContextGetter* request_context)
    : BrowserMessageFilter(NaClHostMsgStart),
      render_process_id_(render_process_id),
      off_the_record_(is_off_the_record),
      profile_directory_(profile_directory),
      request_context_(request_context),
      weak_ptr_factory_(this) {
}

NaClHostMessageFilter::~NaClHostMessageFilter() {
}

void NaClHostMessageFilter::OnChannelClosing() {
  pnacl::PnaclHost::GetInstance()->RendererClosing(render_process_id_);
}

bool NaClHostMessageFilter::OnMessageReceived(const IPC::Message& message) {
  bool handled = true;
  IPC_BEGIN_MESSAGE_MAP(NaClHostMessageFilter, message)
#if !defined(DISABLE_NACL)
    IPC_MESSAGE_HANDLER_DELAY_REPLY(NaClHostMsg_LaunchNaCl, OnLaunchNaCl)
    IPC_MESSAGE_HANDLER_DELAY_REPLY(NaClHostMsg_GetReadonlyPnaclFD,
                                    OnGetReadonlyPnaclFd)
    IPC_MESSAGE_HANDLER_DELAY_REPLY(NaClHostMsg_NaClCreateTemporaryFile,
                                    OnNaClCreateTemporaryFile)
    IPC_MESSAGE_HANDLER(NaClHostMsg_NexeTempFileRequest,
                        OnGetNexeFd)
    IPC_MESSAGE_HANDLER(NaClHostMsg_ReportTranslationFinished,
                        OnTranslationFinished)
    IPC_MESSAGE_HANDLER(NaClHostMsg_MissingArchError,
                        OnMissingArchError)
    IPC_MESSAGE_HANDLER_DELAY_REPLY(NaClHostMsg_OpenNaClExecutable,
                                    OnOpenNaClExecutable)
    IPC_MESSAGE_HANDLER(NaClHostMsg_NaClGetNumProcessors,
                        OnNaClGetNumProcessors)
    IPC_MESSAGE_HANDLER(NaClHostMsg_NaClDebugEnabledForURL,
                        OnNaClDebugEnabledForURL)
#endif
    IPC_MESSAGE_UNHANDLED(handled = false)
  IPC_END_MESSAGE_MAP()

  return handled;
}

net::HostResolver* NaClHostMessageFilter::GetHostResolver() {
  return request_context_->GetURLRequestContext()->host_resolver();
}

void NaClHostMessageFilter::OnLaunchNaCl(
    const nacl::NaClLaunchParams& launch_params,
    IPC::Message* reply_msg) {
  // PNaCl hack
  if (!launch_params.enable_dyncode_syscalls) {
    uint32 perms = launch_params.permission_bits & ppapi::PERMISSION_DEV;
    LaunchNaClContinuation(
        launch_params,
        reply_msg,
        ppapi::PpapiPermissions(perms));
    return;
  }
  content::BrowserThread::PostTaskAndReplyWithResult(
      content::BrowserThread::UI,
      FROM_HERE,
      base::Bind(&GetPpapiPermissions,
                 launch_params.permission_bits,
                 render_process_id_,
                 launch_params.render_view_id),
      base::Bind(&NaClHostMessageFilter::LaunchNaClContinuation,
                 this,
                 launch_params,
                 reply_msg));
}

void NaClHostMessageFilter::LaunchNaClContinuation(
    const nacl::NaClLaunchParams& launch_params,
    IPC::Message* reply_msg,
    ppapi::PpapiPermissions permissions) {
  NaClProcessHost* host = new NaClProcessHost(
      GURL(launch_params.manifest_url),
      base::File(
          IPC::PlatformFileForTransitToPlatformFile(launch_params.nexe_file)),
      permissions,
      launch_params.render_view_id,
      launch_params.permission_bits,
      launch_params.uses_irt,
      launch_params.uses_nonsfi_mode,
      launch_params.enable_dyncode_syscalls,
      launch_params.enable_exception_handling,
      launch_params.enable_crash_throttling,
      off_the_record_,
      profile_directory_);
  GURL manifest_url(launch_params.manifest_url);
  base::FilePath manifest_path;
  // We're calling MapUrlToLocalFilePath with the non-blocking API
  // because we're running in the I/O thread. Ideally we'd use the other path,
  // which would cover more cases.
  nacl::NaClBrowser::GetDelegate()->MapUrlToLocalFilePath(
      manifest_url,
      false /* use_blocking_api */,
      profile_directory_,
      &manifest_path);
  host->Launch(this, reply_msg, manifest_path);
}

void NaClHostMessageFilter::OnGetReadonlyPnaclFd(
    const std::string& filename, bool is_executable, IPC::Message* reply_msg) {
  // This posts a task to another thread, but the renderer will
  // block until the reply is sent.
  nacl_file_host::GetReadonlyPnaclFd(this, filename, is_executable, reply_msg);

  // This is the first message we receive from the renderer once it knows we
  // want to use PNaCl, so start the translation cache initialization here.
  pnacl::PnaclHost::GetInstance()->Init();
}

// Return the temporary file via a reply to the
// NaClHostMsg_NaClCreateTemporaryFile sync message.
void NaClHostMessageFilter::SyncReturnTemporaryFile(
    IPC::Message* reply_msg,
    base::File file) {
  if (file.IsValid()) {
    NaClHostMsg_NaClCreateTemporaryFile::WriteReplyParams(
        reply_msg,
        IPC::TakeFileHandleForProcess(file.Pass(), PeerHandle()));
  } else {
    reply_msg->set_reply_error();
  }
  Send(reply_msg);
}

void NaClHostMessageFilter::OnNaClCreateTemporaryFile(
    IPC::Message* reply_msg) {
  pnacl::PnaclHost::GetInstance()->CreateTemporaryFile(
      base::Bind(&NaClHostMessageFilter::SyncReturnTemporaryFile,
                 this,
                 reply_msg));
}

void NaClHostMessageFilter::AsyncReturnTemporaryFile(
    int pp_instance,
    const base::File& file,
    bool is_hit) {
  IPC::PlatformFileForTransit fd = IPC::InvalidPlatformFileForTransit();
  if (file.IsValid()) {
    // Don't close our copy of the handle, because PnaclHost will use it
    // when the translation finishes.
    fd = IPC::GetFileHandleForProcess(file.GetPlatformFile(), PeerHandle(),
                                      false);
  }
  Send(new NaClViewMsg_NexeTempFileReply(pp_instance, is_hit, fd));
}

void NaClHostMessageFilter::OnNaClGetNumProcessors(int* num_processors) {
  *num_processors = base::SysInfo::NumberOfProcessors();
}

void NaClHostMessageFilter::OnGetNexeFd(
    int render_view_id,
    int pp_instance,
    const nacl::PnaclCacheInfo& cache_info) {
  if (!cache_info.pexe_url.is_valid()) {
    LOG(ERROR) << "Bad URL received from GetNexeFd: " <<
        cache_info.pexe_url.possibly_invalid_spec();
    BadMessageReceived();
    return;
  }

  pnacl::PnaclHost::GetInstance()->GetNexeFd(
      render_process_id_,
      render_view_id,
      pp_instance,
      off_the_record_,
      cache_info,
      base::Bind(&NaClHostMessageFilter::AsyncReturnTemporaryFile,
                 this,
                 pp_instance));
}

void NaClHostMessageFilter::OnTranslationFinished(int instance, bool success) {
  pnacl::PnaclHost::GetInstance()->TranslationFinished(
      render_process_id_, instance, success);
}

void NaClHostMessageFilter::OnMissingArchError(int render_view_id) {
  nacl::NaClBrowser::GetDelegate()->
      ShowMissingArchInfobar(render_process_id_, render_view_id);
}

void NaClHostMessageFilter::OnOpenNaClExecutable(int render_view_id,
                                                 const GURL& file_url,
                                                 IPC::Message* reply_msg) {
  nacl_file_host::OpenNaClExecutable(this, render_view_id, file_url,
                                     reply_msg);
}

void NaClHostMessageFilter::OnNaClDebugEnabledForURL(const GURL& nmf_url,
                                                     bool* should_debug) {
  *should_debug =
      nacl::NaClBrowser::GetDelegate()->URLMatchesDebugPatterns(nmf_url);
}

}  // namespace nacl
<commit_msg>Fix NULL segv in nacl::GetPpapiPermissions() if bad render_view_id.<commit_after>// Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "components/nacl/browser/nacl_host_message_filter.h"

#include "base/sys_info.h"
#include "components/nacl/browser/nacl_browser.h"
#include "components/nacl/browser/nacl_file_host.h"
#include "components/nacl/browser/nacl_process_host.h"
#include "components/nacl/browser/pnacl_host.h"
#include "components/nacl/common/nacl_host_messages.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/plugin_service.h"
#include "content/public/browser/render_process_host.h"
#include "content/public/browser/web_contents.h"
#include "ipc/ipc_platform_file.h"
#include "net/url_request/url_request_context.h"
#include "net/url_request/url_request_context_getter.h"
#include "ppapi/shared_impl/ppapi_permissions.h"
#include "url/gurl.h"

namespace nacl {

namespace {

ppapi::PpapiPermissions GetNaClPermissions(
    uint32 permission_bits,
    content::BrowserContext* browser_context,
    const GURL& document_url) {
  // Only allow NaCl plugins to request certain permissions. We don't want
  // a compromised renderer to be able to start a nacl plugin with e.g. Flash
  // permissions which may expand the surface area of the sandbox.
  uint32 masked_bits = permission_bits & ppapi::PERMISSION_DEV;
  if (content::PluginService::GetInstance()->PpapiDevChannelSupported(
          browser_context, document_url))
    masked_bits |= ppapi::PERMISSION_DEV_CHANNEL;
  return ppapi::PpapiPermissions::GetForCommandLine(masked_bits);
}

ppapi::PpapiPermissions GetPpapiPermissions(uint32 permission_bits,
                                            int render_process_id,
                                            int render_view_id) {
  // We get the URL from WebContents from the RenderViewHost, since we don't
  // have a BrowserPpapiHost yet.
  content::RenderProcessHost* host =
      content::RenderProcessHost::FromID(render_process_id);
  content::RenderViewHost* view_host =
      content::RenderViewHost::FromID(render_process_id, render_view_id);
  if (!view_host)
    return ppapi::PpapiPermissions();
  GURL document_url;
  content::WebContents* contents =
      content::WebContents::FromRenderViewHost(view_host);
  if (contents)
    document_url = contents->GetLastCommittedURL();
  return GetNaClPermissions(permission_bits,
                            host->GetBrowserContext(),
                            document_url);
}

}  // namespace

NaClHostMessageFilter::NaClHostMessageFilter(
    int render_process_id,
    bool is_off_the_record,
    const base::FilePath& profile_directory,
    net::URLRequestContextGetter* request_context)
    : BrowserMessageFilter(NaClHostMsgStart),
      render_process_id_(render_process_id),
      off_the_record_(is_off_the_record),
      profile_directory_(profile_directory),
      request_context_(request_context),
      weak_ptr_factory_(this) {
}

NaClHostMessageFilter::~NaClHostMessageFilter() {
}

void NaClHostMessageFilter::OnChannelClosing() {
  pnacl::PnaclHost::GetInstance()->RendererClosing(render_process_id_);
}

bool NaClHostMessageFilter::OnMessageReceived(const IPC::Message& message) {
  bool handled = true;
  IPC_BEGIN_MESSAGE_MAP(NaClHostMessageFilter, message)
#if !defined(DISABLE_NACL)
    IPC_MESSAGE_HANDLER_DELAY_REPLY(NaClHostMsg_LaunchNaCl, OnLaunchNaCl)
    IPC_MESSAGE_HANDLER_DELAY_REPLY(NaClHostMsg_GetReadonlyPnaclFD,
                                    OnGetReadonlyPnaclFd)
    IPC_MESSAGE_HANDLER_DELAY_REPLY(NaClHostMsg_NaClCreateTemporaryFile,
                                    OnNaClCreateTemporaryFile)
    IPC_MESSAGE_HANDLER(NaClHostMsg_NexeTempFileRequest,
                        OnGetNexeFd)
    IPC_MESSAGE_HANDLER(NaClHostMsg_ReportTranslationFinished,
                        OnTranslationFinished)
    IPC_MESSAGE_HANDLER(NaClHostMsg_MissingArchError,
                        OnMissingArchError)
    IPC_MESSAGE_HANDLER_DELAY_REPLY(NaClHostMsg_OpenNaClExecutable,
                                    OnOpenNaClExecutable)
    IPC_MESSAGE_HANDLER(NaClHostMsg_NaClGetNumProcessors,
                        OnNaClGetNumProcessors)
    IPC_MESSAGE_HANDLER(NaClHostMsg_NaClDebugEnabledForURL,
                        OnNaClDebugEnabledForURL)
#endif
    IPC_MESSAGE_UNHANDLED(handled = false)
  IPC_END_MESSAGE_MAP()

  return handled;
}

net::HostResolver* NaClHostMessageFilter::GetHostResolver() {
  return request_context_->GetURLRequestContext()->host_resolver();
}

void NaClHostMessageFilter::OnLaunchNaCl(
    const nacl::NaClLaunchParams& launch_params,
    IPC::Message* reply_msg) {
  // PNaCl hack
  if (!launch_params.enable_dyncode_syscalls) {
    uint32 perms = launch_params.permission_bits & ppapi::PERMISSION_DEV;
    LaunchNaClContinuation(
        launch_params,
        reply_msg,
        ppapi::PpapiPermissions(perms));
    return;
  }
  content::BrowserThread::PostTaskAndReplyWithResult(
      content::BrowserThread::UI,
      FROM_HERE,
      base::Bind(&GetPpapiPermissions,
                 launch_params.permission_bits,
                 render_process_id_,
                 launch_params.render_view_id),
      base::Bind(&NaClHostMessageFilter::LaunchNaClContinuation,
                 this,
                 launch_params,
                 reply_msg));
}

void NaClHostMessageFilter::LaunchNaClContinuation(
    const nacl::NaClLaunchParams& launch_params,
    IPC::Message* reply_msg,
    ppapi::PpapiPermissions permissions) {
  NaClProcessHost* host = new NaClProcessHost(
      GURL(launch_params.manifest_url),
      base::File(
          IPC::PlatformFileForTransitToPlatformFile(launch_params.nexe_file)),
      permissions,
      launch_params.render_view_id,
      launch_params.permission_bits,
      launch_params.uses_irt,
      launch_params.uses_nonsfi_mode,
      launch_params.enable_dyncode_syscalls,
      launch_params.enable_exception_handling,
      launch_params.enable_crash_throttling,
      off_the_record_,
      profile_directory_);
  GURL manifest_url(launch_params.manifest_url);
  base::FilePath manifest_path;
  // We're calling MapUrlToLocalFilePath with the non-blocking API
  // because we're running in the I/O thread. Ideally we'd use the other path,
  // which would cover more cases.
  nacl::NaClBrowser::GetDelegate()->MapUrlToLocalFilePath(
      manifest_url,
      false /* use_blocking_api */,
      profile_directory_,
      &manifest_path);
  host->Launch(this, reply_msg, manifest_path);
}

void NaClHostMessageFilter::OnGetReadonlyPnaclFd(
    const std::string& filename, bool is_executable, IPC::Message* reply_msg) {
  // This posts a task to another thread, but the renderer will
  // block until the reply is sent.
  nacl_file_host::GetReadonlyPnaclFd(this, filename, is_executable, reply_msg);

  // This is the first message we receive from the renderer once it knows we
  // want to use PNaCl, so start the translation cache initialization here.
  pnacl::PnaclHost::GetInstance()->Init();
}

// Return the temporary file via a reply to the
// NaClHostMsg_NaClCreateTemporaryFile sync message.
void NaClHostMessageFilter::SyncReturnTemporaryFile(
    IPC::Message* reply_msg,
    base::File file) {
  if (file.IsValid()) {
    NaClHostMsg_NaClCreateTemporaryFile::WriteReplyParams(
        reply_msg,
        IPC::TakeFileHandleForProcess(file.Pass(), PeerHandle()));
  } else {
    reply_msg->set_reply_error();
  }
  Send(reply_msg);
}

void NaClHostMessageFilter::OnNaClCreateTemporaryFile(
    IPC::Message* reply_msg) {
  pnacl::PnaclHost::GetInstance()->CreateTemporaryFile(
      base::Bind(&NaClHostMessageFilter::SyncReturnTemporaryFile,
                 this,
                 reply_msg));
}

void NaClHostMessageFilter::AsyncReturnTemporaryFile(
    int pp_instance,
    const base::File& file,
    bool is_hit) {
  IPC::PlatformFileForTransit fd = IPC::InvalidPlatformFileForTransit();
  if (file.IsValid()) {
    // Don't close our copy of the handle, because PnaclHost will use it
    // when the translation finishes.
    fd = IPC::GetFileHandleForProcess(file.GetPlatformFile(), PeerHandle(),
                                      false);
  }
  Send(new NaClViewMsg_NexeTempFileReply(pp_instance, is_hit, fd));
}

void NaClHostMessageFilter::OnNaClGetNumProcessors(int* num_processors) {
  *num_processors = base::SysInfo::NumberOfProcessors();
}

void NaClHostMessageFilter::OnGetNexeFd(
    int render_view_id,
    int pp_instance,
    const nacl::PnaclCacheInfo& cache_info) {
  if (!cache_info.pexe_url.is_valid()) {
    LOG(ERROR) << "Bad URL received from GetNexeFd: " <<
        cache_info.pexe_url.possibly_invalid_spec();
    BadMessageReceived();
    return;
  }

  pnacl::PnaclHost::GetInstance()->GetNexeFd(
      render_process_id_,
      render_view_id,
      pp_instance,
      off_the_record_,
      cache_info,
      base::Bind(&NaClHostMessageFilter::AsyncReturnTemporaryFile,
                 this,
                 pp_instance));
}

void NaClHostMessageFilter::OnTranslationFinished(int instance, bool success) {
  pnacl::PnaclHost::GetInstance()->TranslationFinished(
      render_process_id_, instance, success);
}

void NaClHostMessageFilter::OnMissingArchError(int render_view_id) {
  nacl::NaClBrowser::GetDelegate()->
      ShowMissingArchInfobar(render_process_id_, render_view_id);
}

void NaClHostMessageFilter::OnOpenNaClExecutable(int render_view_id,
                                                 const GURL& file_url,
                                                 IPC::Message* reply_msg) {
  nacl_file_host::OpenNaClExecutable(this, render_view_id, file_url,
                                     reply_msg);
}

void NaClHostMessageFilter::OnNaClDebugEnabledForURL(const GURL& nmf_url,
                                                     bool* should_debug) {
  *should_debug =
      nacl::NaClBrowser::GetDelegate()->URLMatchesDebugPatterns(nmf_url);
}

}  // namespace nacl
<|endoftext|>


<commit_before>#include "tabulator.h"
#include <cassert>
#include <numeric>

namespace ncv
{
        tabulator_t::tabulator_t(const string_t& title)
                :       m_title(title)
        {
        }

        tabulator_t::header_t& tabulator_t::header()
        {
                clear();
                return m_header;
        }

        void tabulator_t::clear()
        {
                m_rows.clear();
        }

        tabulator_t::row_t& tabulator_t::append(const string_t& name)
        {
                m_rows.emplace_back(name);
                return *m_rows.rbegin();
        }

        bool tabulator_t::sort(size_t col, comparator_t comp)
        {
                if (col < cols())
                {
                        std::sort(m_rows.begin(), m_rows.end(), [&] (const row_t& row1, const row_t& row2)
                        {
                                assert(col < row1.size());
                                assert(row1.size() == cols());

                                assert(col < row2.size());
                                assert(row2.size() == cols());

                                return comp(row1.values()[col], row2.values()[col]);
                        });

                        return true;
                }

                else
                {
                        // invalid index
                        return false;
                }
        }

        std::size_t tabulator_t::border() const
        {
                return 4;
        }

        size_t tabulator_t::name_colsize() const
        {
                size_t colsize = 0;
                for (const row_t& row : m_rows)
                {
                        colsize = std::max(colsize, row.name().size());
                }
                colsize = std::max(colsize, m_title.size()) + border();

                return colsize;
        }

        std::vector<std::size_t> tabulator_t::value_colsizes() const
        {
                std::vector<std::size_t> colsizes(cols(), 0);
                for (size_t c = 0; c < cols(); c ++)
                {
                        colsizes[c] = std::max(colsizes[c], m_header[c].size());
                }
                for (const row_t& row : m_rows)
                {
                        for (size_t c = 0; c < std::min(cols(), row.size()); c ++)
                        {
                                colsizes[c] = std::max(colsizes[c], row[c].size());
                        }
                }
                for (size_t& colsize : colsizes)
                {
                        colsize += border();
                }

                return colsizes;
        }

        bool tabulator_t::print(std::ostream& os,
                const char table_delim,
                const char row_delim, bool use_row_delim) const
        {
                const char col_delim = ' ';

                // size of name & value columns (in characters)
                const auto ncolsize = this->name_colsize();
                const auto vcolsizes = this->value_colsizes();

                const auto rowsize = ncolsize + std::accumulate(vcolsizes.begin(), vcolsizes.end(), size_t(0));

                // display header
                os << string_t(rowsize, table_delim) << std::endl;

                os << text::resize(m_title, ncolsize);
                for (size_t c = 0; c < cols(); c ++)
                {
                        os << text::resize(col_delim + m_header[c], vcolsizes[c]);
                }
                os << std::endl;

                os << string_t(rowsize, row_delim) << std::endl;

                // display rows
                for (size_t r = 0; r < m_rows.size(); r ++)
                {
                        const row_t& row = m_rows[r];

                        if (r > 0 && r < m_rows.size() && use_row_delim)
                        {
                                os << string_t(rowsize, row_delim) << std::endl;
                        }

                        os << text::resize(row.name(), ncolsize);
                        for (size_t c = 0; c < std::min(cols(), row.size()); c ++)
                        {
                                os << text::resize(col_delim + row[c], vcolsizes[c]);
                        }
                        os << std::endl;
                }

                os << string_t(rowsize, table_delim) << std::endl;

                return true;
        }
}
<commit_msg>stable-sort table to concatenate sorting<commit_after>#include "tabulator.h"
#include <cassert>
#include <numeric>

namespace ncv
{
        tabulator_t::tabulator_t(const string_t& title)
                :       m_title(title)
        {
        }

        tabulator_t::header_t& tabulator_t::header()
        {
                clear();
                return m_header;
        }

        void tabulator_t::clear()
        {
                m_rows.clear();
        }

        tabulator_t::row_t& tabulator_t::append(const string_t& name)
        {
                m_rows.emplace_back(name);
                return *m_rows.rbegin();
        }

        bool tabulator_t::sort(size_t col, comparator_t comp)
        {
                if (col < cols())
                {
                        std::stable_sort(m_rows.begin(), m_rows.end(), [&] (const row_t& row1, const row_t& row2)
                        {
                                assert(col < row1.size());
                                assert(row1.size() == cols());

                                assert(col < row2.size());
                                assert(row2.size() == cols());

                                return comp(row1.values()[col], row2.values()[col]);
                        });

                        return true;
                }

                else
                {
                        // invalid index
                        return false;
                }
        }

        std::size_t tabulator_t::border() const
        {
                return 4;
        }

        size_t tabulator_t::name_colsize() const
        {
                size_t colsize = 0;
                for (const row_t& row : m_rows)
                {
                        colsize = std::max(colsize, row.name().size());
                }
                colsize = std::max(colsize, m_title.size()) + border();

                return colsize;
        }

        std::vector<std::size_t> tabulator_t::value_colsizes() const
        {
                std::vector<std::size_t> colsizes(cols(), 0);
                for (size_t c = 0; c < cols(); c ++)
                {
                        colsizes[c] = std::max(colsizes[c], m_header[c].size());
                }
                for (const row_t& row : m_rows)
                {
                        for (size_t c = 0; c < std::min(cols(), row.size()); c ++)
                        {
                                colsizes[c] = std::max(colsizes[c], row[c].size());
                        }
                }
                for (size_t& colsize : colsizes)
                {
                        colsize += border();
                }

                return colsizes;
        }

        bool tabulator_t::print(std::ostream& os,
                const char table_delim,
                const char row_delim, bool use_row_delim) const
        {
                const char col_delim = ' ';

                // size of name & value columns (in characters)
                const auto ncolsize = this->name_colsize();
                const auto vcolsizes = this->value_colsizes();

                const auto rowsize = ncolsize + std::accumulate(vcolsizes.begin(), vcolsizes.end(), size_t(0));

                // display header
                os << string_t(rowsize, table_delim) << std::endl;

                os << text::resize(m_title, ncolsize);
                for (size_t c = 0; c < cols(); c ++)
                {
                        os << text::resize(col_delim + m_header[c], vcolsizes[c]);
                }
                os << std::endl;

                os << string_t(rowsize, row_delim) << std::endl;

                // display rows
                for (size_t r = 0; r < m_rows.size(); r ++)
                {
                        const row_t& row = m_rows[r];

                        if (r > 0 && r < m_rows.size() && use_row_delim)
                        {
                                os << string_t(rowsize, row_delim) << std::endl;
                        }

                        os << text::resize(row.name(), ncolsize);
                        for (size_t c = 0; c < std::min(cols(), row.size()); c ++)
                        {
                                os << text::resize(col_delim + row[c], vcolsizes[c]);
                        }
                        os << std::endl;
                }

                os << string_t(rowsize, table_delim) << std::endl;

                return true;
        }
}
<|endoftext|>


<commit_before>//----------------------------  mapping_q4_3d.cc  ---------------------------
//    $Id$
//    Version: $Name$
//
//    Copyright (C) 2003 by the deal.II authors
//
//    This file is subject to QPL and may not be  distributed
//    without copyright and license information. Please refer
//    to the file deal.II/doc/license.html for the  text  and
//    further information on this license.
//
//----------------------------  mapping_q4_3d.cc  ---------------------------

// this test used to fail somewhere in the 3d parts of MappingQ for
// fourth order mappings

#include <base/logstream.h>
#include <base/quadrature_lib.h>
#include <grid/tria.h>
#include <grid/tria_accessor.h>
#include <grid/tria_iterator.h>
#include <grid/grid_generator.h>
#include <dofs/dof_handler.h>
#include <fe/fe_q.h>
#include <fe/fe_values.h>
#include <fe/mapping_q.h>

#include <fstream>

int main ()
{
  std::ofstream logfile("mapping_q4_3d.output");
  deallog.attach(logfile);
  deallog.depth_console(0);

  Triangulation<3> coarse_grid;
  GridGenerator::hyper_cube (coarse_grid, -1, 1);
  coarse_grid.refine_global (1);

  FE_Q<3> fe(1);
  DoFHandler<3> dof_handler (coarse_grid);
  dof_handler.distribute_dofs (fe);

  MappingQ<3> mapping(4);
  QGauss3<2> q_face;
  FEFaceValues<3> fe_face_values (mapping, fe, q_face,
                                  update_normal_vectors | update_JxW_values);
  fe_face_values.reinit (dof_handler.begin_active(), 0);
}

<commit_msg>Add "OK" marker.<commit_after>//----------------------------  mapping_q4_3d.cc  ---------------------------
//    $Id$
//    Version: $Name$
//
//    Copyright (C) 2003, 2004 by the deal.II authors
//
//    This file is subject to QPL and may not be  distributed
//    without copyright and license information. Please refer
//    to the file deal.II/doc/license.html for the  text  and
//    further information on this license.
//
//----------------------------  mapping_q4_3d.cc  ---------------------------

// this test used to fail somewhere in the 3d parts of MappingQ for fourth
// order mappings. it later turned out that the weird error was simply that
// something wasn't implemented, which is now the case

#include <base/logstream.h>
#include <base/quadrature_lib.h>
#include <grid/tria.h>
#include <grid/tria_accessor.h>
#include <grid/tria_iterator.h>
#include <grid/grid_generator.h>
#include <dofs/dof_handler.h>
#include <fe/fe_q.h>
#include <fe/fe_values.h>
#include <fe/mapping_q.h>

#include <fstream>

int main ()
{
  std::ofstream logfile("mapping_q4_3d.output");
  deallog.attach(logfile);
  deallog.depth_console(0);

  Triangulation<3> coarse_grid;
  GridGenerator::hyper_cube (coarse_grid, -1, 1);
  coarse_grid.refine_global (1);

  FE_Q<3> fe(1);
  DoFHandler<3> dof_handler (coarse_grid);
  dof_handler.distribute_dofs (fe);

  MappingQ<3> mapping(4);
  QGauss3<2> q_face;
  FEFaceValues<3> fe_face_values (mapping, fe, q_face,
                                  update_normal_vectors |
                                  update_JxW_values);
  fe_face_values.reinit (dof_handler.begin_active(), 0);

                                   // if we got here, we got past the previous
                                   // abort
  deallog << "OK" << std::endl;
}

<|endoftext|>