<commit_before>/*
 * This file is part of QZeitgeist.
 *
 * Copyright (C) 2013 David Rosca <nowrep@gmail.com>
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 */
extern "C" {
#include <zeitgeist.h>
}

#include "monitor.h"
#include "resultset.h"
#include "tools.h"

namespace QZeitgeist
{

class MonitorPrivate
{
public:
    MonitorPrivate(const TimeRange &timeRange, const QList<Event> &eventTemplates, Monitor *q_);
    ~MonitorPrivate();

    void emitEventsDeleted(const TimeRange &tr, const QList<quint32> &ids);
    void emitEventsInserted(const TimeRange &tr, const ResultSet &res);

    Monitor *q;
    ZeitgeistMonitor *monitor;
};

// callbacks
static void on_events_deleted(ZeitgeistMonitor *, ZeitgeistTimeRange *time_range,
                              guint32 *event_ids, int events_length, MonitorPrivate *monitor)
{
    TimeRange tr = Tools::timeRangeFromHandle(time_range);
    QList<quint32> ids;

    for (int i = 0; i < events_length; ++i) {
        ids.append(event_ids[i]);
    }

    monitor->emitEventsDeleted(tr, ids);
}

static void on_events_inserted(ZeitgeistMonitor *, ZeitgeistTimeRange *time_range,
                               ZeitgeistResultSet *events, MonitorPrivate *monitor)
{
    TimeRange tr = Tools::timeRangeFromHandle(time_range);
    ResultSet resultSet = ResultSet::fromHandle(events);

    monitor->emitEventsInserted(tr, resultSet);
}

MonitorPrivate::MonitorPrivate(const TimeRange &timeRange, const QList<Event> &eventTemplates, Monitor *q_)
    : q(q_)
{
    ZeitgeistTimeRange *tr = (ZeitgeistTimeRange *)Tools::timeRangeCreateHandle(timeRange);
    GPtrArray *templates = Tools::eventsToPtrArray(eventTemplates);

    monitor = zeitgeist_monitor_new(tr, templates);
    g_signal_connect(monitor, "events-deleted", G_CALLBACK(on_events_deleted), this);
    g_signal_connect(monitor, "events-inserted", G_CALLBACK(on_events_inserted), this);

    g_object_unref(tr);
    g_ptr_array_unref(templates);

    Q_ASSERT(monitor);
}

MonitorPrivate::~MonitorPrivate()
{
    g_object_unref(monitor);
}

void MonitorPrivate::emitEventsDeleted(const TimeRange &tr, const QList<quint32> &ids)
{
    Q_EMIT q->eventsDeleted(tr, ids);
}

void MonitorPrivate::emitEventsInserted(const TimeRange &tr, const ResultSet &res)
{
    Q_EMIT q->eventsInserted(tr, res);
}

// class Monitor
Monitor::Monitor(const TimeRange &timeRange, const QList<Event> &eventTemplates, QObject *parent)
    : QObject(parent)
    , d(new MonitorPrivate(timeRange, eventTemplates, this))
{
}

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

QList<Event> Monitor::eventTemplates() const
{
    GPtrArray *templates = zeitgeist_monitor_get_event_templates(d->monitor);

    return Tools::eventsFromPtrArray(templates);
}

void Monitor::setEventTemplates(const QList<Event> &eventTemplates)
{
    GPtrArray *templates = Tools::eventsToPtrArray(eventTemplates);
    zeitgeist_monitor_set_event_templates(d->monitor, templates);

    g_ptr_array_unref(templates);
}

TimeRange Monitor::timeRange() const
{
    ZeitgeistTimeRange *tr = zeitgeist_monitor_get_time_range(d->monitor);

    return Tools::timeRangeFromHandle(tr);
}

void Monitor::setTimeRange(const TimeRange &timeRange)
{
    ZeitgeistTimeRange *tr = (ZeitgeistTimeRange *)Tools::timeRangeCreateHandle(timeRange);
    zeitgeist_monitor_set_time_range(d->monitor, tr);

    g_object_unref(tr);
}

HANDLE Monitor::getHandle() const
{
    return d->monitor;
}

} // namespace QZeitgeist

<commit_msg>Monitor: Fix crash when installing monitor into log<commit_after>/*
 * This file is part of QZeitgeist.
 *
 * Copyright (C) 2013 David Rosca <nowrep@gmail.com>
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 */
extern "C" {
#include <zeitgeist.h>
}

#include "monitor.h"
#include "resultset.h"
#include "tools.h"

namespace QZeitgeist
{

class MonitorPrivate
{
public:
    MonitorPrivate(const TimeRange &timeRange, const QList<Event> &eventTemplates, Monitor *q_);
    ~MonitorPrivate();

    void emitEventsDeleted(const TimeRange &tr, const QList<quint32> &ids);
    void emitEventsInserted(const TimeRange &tr, const ResultSet &res);

    Monitor *q;
    ZeitgeistMonitor *monitor;
};

// callbacks
static void on_events_deleted(ZeitgeistMonitor *, ZeitgeistTimeRange *time_range,
                              guint32 *event_ids, int events_length, MonitorPrivate *monitor)
{
    TimeRange tr = Tools::timeRangeFromHandle(time_range);
    QList<quint32> ids;

    for (int i = 0; i < events_length; ++i) {
        ids.append(event_ids[i]);
    }

    monitor->emitEventsDeleted(tr, ids);
}

static void on_events_inserted(ZeitgeistMonitor *, ZeitgeistTimeRange *time_range,
                               ZeitgeistResultSet *events, MonitorPrivate *monitor)
{
    TimeRange tr = Tools::timeRangeFromHandle(time_range);
    ResultSet resultSet = ResultSet::fromHandle(events);

    monitor->emitEventsInserted(tr, resultSet);
}

MonitorPrivate::MonitorPrivate(const TimeRange &timeRange, const QList<Event> &eventTemplates, Monitor *q_)
    : q(q_)
{
    ZeitgeistTimeRange *tr = (ZeitgeistTimeRange *)Tools::timeRangeCreateHandle(timeRange);
    GPtrArray *templates = Tools::eventsToPtrArray(eventTemplates);

    monitor = zeitgeist_monitor_new(tr, templates);
    g_signal_connect(monitor, "events-deleted", G_CALLBACK(on_events_deleted), this);
    g_signal_connect(monitor, "events-inserted", G_CALLBACK(on_events_inserted), this);

    g_object_unref(tr);

    Q_ASSERT(monitor);
}

MonitorPrivate::~MonitorPrivate()
{
    g_object_unref(monitor);
}

void MonitorPrivate::emitEventsDeleted(const TimeRange &tr, const QList<quint32> &ids)
{
    Q_EMIT q->eventsDeleted(tr, ids);
}

void MonitorPrivate::emitEventsInserted(const TimeRange &tr, const ResultSet &res)
{
    Q_EMIT q->eventsInserted(tr, res);
}

// class Monitor
Monitor::Monitor(const TimeRange &timeRange, const QList<Event> &eventTemplates, QObject *parent)
    : QObject(parent)
    , d(new MonitorPrivate(timeRange, eventTemplates, this))
{
}

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

QList<Event> Monitor::eventTemplates() const
{
    GPtrArray *templates = zeitgeist_monitor_get_event_templates(d->monitor);

    return Tools::eventsFromPtrArray(templates);
}

void Monitor::setEventTemplates(const QList<Event> &eventTemplates)
{
    GPtrArray *templates = Tools::eventsToPtrArray(eventTemplates);
    zeitgeist_monitor_set_event_templates(d->monitor, templates);

    g_ptr_array_unref(templates);
}

TimeRange Monitor::timeRange() const
{
    ZeitgeistTimeRange *tr = zeitgeist_monitor_get_time_range(d->monitor);

    return Tools::timeRangeFromHandle(tr);
}

void Monitor::setTimeRange(const TimeRange &timeRange)
{
    ZeitgeistTimeRange *tr = (ZeitgeistTimeRange *)Tools::timeRangeCreateHandle(timeRange);
    zeitgeist_monitor_set_time_range(d->monitor, tr);

    g_object_unref(tr);
}

HANDLE Monitor::getHandle() const
{
    return d->monitor;
}

} // namespace QZeitgeist

<|endoftext|>


<commit_before>/*
 * Copyright 2008 28msec, Inc.
 *
 * 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.
 */
#include <iostream>
#include <fstream>
#include <stdlib.h>
#include <libaws/aws.h>

using namespace aws;

bool createDomain (SDBConnectionPtr aSDB, const std::string &aDomainName) {
  try {
      CreateDomainResponsePtr lRes = aSDB->createDomain (aDomainName);
      std::cout << "domain created successfully" << std::endl;
    } catch (CreateDomainException &e) {
      std::cerr << e.what() << std::endl;
      return false;
    }
  return true;
}

bool deleteDomain (SDBConnectionPtr aSDB, const std::string &aDomainName) {
  try {
      DeleteDomainResponsePtr lRes = aSDB->deleteDomain (aDomainName);
      std::cout << "delete domain successfully" << std::endl;
    } catch (DeleteDomainException &e) {
      std::cerr << e.what() << std::endl;
      return false;
    }
  return true;
}

bool deleteAllDomains (SDBConnectionPtr aSDB, std::string aPrefix) {
  try {
      ListDomainsResponsePtr lRes = aSDB->listDomains();
      std::cout << "start deleting" << std::endl;
      lRes->open();
      std::string lDomain;
      while (lRes->next (lDomain)) {
        if(aPrefix.length() == 0 || lDomain.compare(0, aPrefix.length(),aPrefix) == 0){
            std::cout << "   " << lDomain  << std::endl;
            aSDB->deleteDomain (lDomain);
          }
        }
      lRes->close();
    } catch (PutAttributesException &e) {
      std::cerr << e.what() << std::endl;
      return false;
    }
  return true;
}

bool listDomains (SDBConnectionPtr aSDB, int aMaxNumberOfDomains, const std::string& aNextToken) {
  try {
    ListDomainsResponsePtr lRes = aSDB->listDomains(aMaxNumberOfDomains, aNextToken);
      std::cout << "list domains successfully" << std::endl;
      lRes->open();
      std::string lDomain;
      while (lRes->next (lDomain)) {
          std::cout << "   Domain: " << lDomain  << std::endl;
        }
      lRes->close();
    } catch (ListDomainsException &e) {
      std::cerr << e.what() << std::endl;
      return false;
    }
  return true;
}

bool putAttribute (SDBConnectionPtr aSDB, const std::string& aDomainName, const std::string& aItemName,
                   const std::string& aKey, const std::string& aValue, bool aReplace) {
  try {
      std::vector<aws::Attribute> lAttrs;
      aws::Attribute lAttr (aKey, aValue, aReplace);
      lAttrs.push_back (lAttr);
      PutAttributesResponsePtr lRes = aSDB->putAttributes (aDomainName, aItemName, lAttrs);
      std::cout << "put attribute successfully" << std::endl;
    } catch (PutAttributesException &e) {
      std::cerr << e.what() << std::endl;
      return false;
    }
  return true;
}

bool deleteAttribute (SDBConnectionPtr aSDB, const std::string& aDomainName, const std::string& aItemName,
                      const std::string& aKey, std::string aValue) {
  try {
      std::vector<aws::Attribute> lAttrs;
      aws::Attribute lAttr (aKey, aValue, false);
      lAttrs.push_back (lAttr);
      DeleteAttributesResponsePtr lRes = aSDB->deleteAttributes (aDomainName, aItemName, lAttrs);
      std::cout << "delete attribute successfully" << std::endl;
    } catch (PutAttributesException &e) {
      std::cerr << e.what()  << std::endl;
      return false;
    }
  return true;
}

bool getAttribute (SDBConnectionPtr aSDB, const std::string& aDomainName, const std::string& aItemName,
                   const std::string attributeName = "") {
  try {
      GetAttributesResponsePtr lRes = aSDB->getAttributes (aDomainName, aItemName, attributeName);
      std::cout << "get attribute successfully" << std::endl;
      lRes->open();
      std::pair<std::string, std::string> lAttr;
      while (lRes->next (lAttr)) {
          std::cout << "   Attr-Name: " << lAttr.first << "-> " <<  lAttr.second  << std::endl;
        }
      lRes->close();
    } catch (PutAttributesException &e) {
      std::cerr << e.what() << std::endl;
      return false;
    }
  return true;
}

bool listAll(SDBConnectionPtr aSDB){
  try {
    ListDomainsResponsePtr lRes = aSDB->listDomains();
    std::cout << "list domains successfully" << std::endl;
    lRes->open();
    std::string lDomain;
    while (lRes->next (lDomain)) {
      std::cout << "  Domain: " << lDomain  << std::endl;
      SDBQueryResponsePtr lRes = aSDB->query (lDomain, "");
      int lCounter = 0;
      lRes->open();
      std::string lItem;
      while (lRes->next (lItem)) {
        std::cout << "    " << ++lCounter << ". Item: " << lItem;
        GetAttributesResponsePtr lRes = aSDB->getAttributes (lDomain, lItem);
        lRes->open();
        std::pair<std::string, std::string> lAttr;
        while (lRes->next (lAttr)) {
          std::cout << " " << lAttr.first << ":" <<  lAttr.second ;
        }
        lRes->close();
        std::cout << std::endl;
      }
      lRes->close();
    }
    lRes->close();
  } catch (ListDomainsException &e) {
    std::cerr << e.what() << std::endl;
    return false;
  }
  return true;

}

bool query (SDBConnectionPtr aSDB, const std::string& aDomainName, const std::string& aQueryExpression, int aMaxNumberOfItems = 0,
            const std::string & aNextToken = "") {
  try {
    SDBQueryResponsePtr lRes = aSDB->query (aDomainName, aQueryExpression, aMaxNumberOfItems, aNextToken);
      std::cout << "query successfully" << std::endl;
      lRes->open();
      std::string lItem;
      while (lRes->next (lItem)) {
          std::cout << "   Item: " << lItem << std::endl;
        }
      lRes->close();
    } catch (PutAttributesException &e) {
      std::cerr << e.what() << std::endl;
      return false;
    }
  return true;
}

int
main (int argc, char** argv) {
  char* lAccessKeyId = 0;
  char* lSecretAccessKey = 0;
  char* lAction = 0;
  char* lDomain = 0;
  int   lMaxItems = 0;
  std::string lNextToken = "";
  char lEmpty[] = { '\0' };
  char* lNextTokenTmp = lEmpty;
  char* lAttrName = 0;
  char* lAttrValue = 0;
  char* lItem = 0;
  char* lQuery = 0;
  bool  lReplace = false;

  int c;
  opterr = 0;

  AWSConnectionFactory* lFactory = AWSConnectionFactory::getInstance();

  while ( (c = getopt (argc, argv, "hi:s:a:d:x:c:t:k:v:q:r")) != -1)
    switch (c) {
      case 'i':
        lAccessKeyId = optarg;
        break;
      case 's':
        lSecretAccessKey = optarg;
        break;
      case 'a':
        lAction = optarg;
        break;
      case 'd':
        lDomain = optarg;
        break;
      case 'x':
        lMaxItems = atoi (optarg);
        break;
      case 'c':
        lItem = optarg;
        break;
      case 't':
        lNextToken = optarg;
        break;
      case 'k':
        lAttrName = optarg;
        break;
      case 'v':
        lAttrValue = optarg;
        break;
      case 'q':
        lQuery = optarg;
        break;
      case 'r':
        lReplace = true;
        break;
      case 'h': {
          std::cout << "libaws version " << lFactory->getVersion() << std::endl;
          std::cout << "Usage: sqs <options>" << std::endl;
          std::cout << "  -i: AWS Access Key Id"  << std::endl;
          std::cout << "  -s: AWS Secret Access Key"  << std::endl;
          std::cout << "  -a action: Action to perform" << std::endl;
          std::cout << "             create-domain" << std::endl;
          std::cout << "             delete-domain" << std::endl;
          std::cout << "             delete-all-domains" << std::endl;
          std::cout << "             list-domains" << std::endl;
          std::cout << "             put-attribute" << std::endl;
          std::cout << "             delete-attribute" << std::endl;
          std::cout << "             get-attribute" << std::endl;
          std::cout << "             query" << std::endl;
          std::cout << "             list-all" << std::endl;
          std::cout << "  -d domain: A Domain Name"  << std::endl;
          std::cout << "  -c item/content: The item"  << std::endl;
          std::cout << "  -x #items: Max number of items/domains"  << std::endl;
          std::cout << "  -t next token: The next token" << std::endl;
          std::cout << "  -k key/attributes: An attribute" << std::endl;
          std::cout << "  -v value: An attribute value" << std::endl;
          std::cout << "  -q query: Replace Attribue" << std::endl;
          std::cout << "  -r replace: Replace Attribue" << std::endl;
          std::cout << "  -h help: display help" << std::endl;
          exit (1);
        }
      case '?':
        if (isprint (optopt))
          fprintf (stderr, "Unknown option `-%c'.\n", optopt);
        else
          fprintf (stderr,
                   "Unknown option character `\\x%x'.\n",
                   optopt);
        exit (1);
      default:
        exit (1);
      }

  if (!lAccessKeyId) {
      lAccessKeyId = getenv ("AWS_ACCESS_KEY");
    }

  if (!lSecretAccessKey) {
      lSecretAccessKey = getenv ("AWS_SECRET_ACCESS_KEY");
    }

  if (!lAccessKeyId) {
      std::cerr << "No Access Key given" << std::endl;
      std::cerr << "Either use -i as a command line argument or set AWS_ACCESS_KEY as an environmental variable" << std::endl;
      exit (1);
    }

  if (!lSecretAccessKey) {
      std::cerr << "No Secret Access Key given" << std::endl;
      std::cerr << "Either use -s as a command line argument or set AWS_SECRET_ACCESS_KEY as an environmental variable" << std::endl;
      exit (1);
    }

  SDBConnectionPtr lSDBRest;
  lSDBRest = lFactory->createSDBConnection (lAccessKeyId, lSecretAccessKey);

  if (!lAction) {
      std::cerr << "No Action parameter specified." << std::endl;
      std::cerr << "Use -a as a command line argument" << std::endl;
      exit (1);
    }
  std::string lActionString (lAction);

  if (lActionString.compare ("list-domains") == 0) {
    listDomains (lSDBRest, lMaxItems, lNextTokenTmp);
      exit (0);
    }
  if (lActionString.compare ("delete-all-domains") == 0) {
      deleteAllDomains (lSDBRest, lQuery==0?"":lQuery);
      exit (0);
    }
    if (lActionString.compare ("list-all") == 0) {
      listAll (lSDBRest);
      exit (0);
    }

  if (!lDomain) {
      std::cerr << "No domain provided." << std::endl;
      exit (1);
    }

  if (lActionString.compare ("create-domain") == 0) {
      createDomain (lSDBRest, lDomain);
      exit (0);
    }

  if (lActionString.compare ("delete-domain") == 0) {
      deleteDomain (lSDBRest, lDomain);
      exit (0);
    }

    if (lActionString.compare ("query") == 0) {
      query (lSDBRest, lDomain, lQuery, lMaxItems, lNextTokenTmp);
      exit(0);
    }

  if (!lItem) {
      std::cerr << "No item provided." << std::endl;
      exit (1);
    }

  if (lActionString.compare ("get-attribute") == 0) {
      if (lAttrName) {
          getAttribute (lSDBRest, lDomain, lItem, lAttrName);
        } else {
          getAttribute (lSDBRest, lDomain, lItem);
        }
    }

  if (!lAttrName) {
      std::cerr << "No attribute name provided." << std::endl;
      exit (1);
    }

  if (!lAttrValue) {
      std::cerr << "No attribute value provided." << std::endl;
      exit (1);
    }

  if (lActionString.compare ("put-attribute") == 0) {
      putAttribute (lSDBRest, lDomain, lItem, lAttrName, lAttrValue, lReplace);
    } else if (lActionString.compare ("delete-attribute") == 0) {
      deleteAttribute (lSDBRest, lDomain, lItem, lAttrName, lAttrValue);
    } else {
      std::cerr << "Command not recognized." << std::endl;
      exit (1);
    }

}

<commit_msg>copy & waste fixes<commit_after>/*
 * Copyright 2008 28msec, Inc.
 *
 * 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.
 */
#include <iostream>
#include <fstream>
#include <stdlib.h>
#include <libaws/aws.h>

using namespace aws;

bool createDomain (SDBConnectionPtr aSDB, const std::string &aDomainName) {
  try {
      CreateDomainResponsePtr lRes = aSDB->createDomain (aDomainName);
      std::cout << "domain created successfully" << std::endl;
    } catch (CreateDomainException &e) {
      std::cerr << e.what() << std::endl;
      return false;
    }
  return true;
}

bool deleteDomain (SDBConnectionPtr aSDB, const std::string &aDomainName) {
  try {
      DeleteDomainResponsePtr lRes = aSDB->deleteDomain (aDomainName);
      std::cout << "delete domain successfully" << std::endl;
    } catch (DeleteDomainException &e) {
      std::cerr << e.what() << std::endl;
      return false;
    }
  return true;
}

bool deleteAllDomains (SDBConnectionPtr aSDB, std::string aPrefix) {
  try {
      ListDomainsResponsePtr lRes = aSDB->listDomains();
      std::cout << "start deleting" << std::endl;
      lRes->open();
      std::string lDomain;
      while (lRes->next (lDomain)) {
        if(aPrefix.length() == 0 || lDomain.compare(0, aPrefix.length(),aPrefix) == 0){
            std::cout << "   " << lDomain  << std::endl;
            aSDB->deleteDomain (lDomain);
          }
        }
      lRes->close();
    } catch (PutAttributesException &e) {
      std::cerr << e.what() << std::endl;
      return false;
    }
  return true;
}

bool listDomains (SDBConnectionPtr aSDB, int aMaxNumberOfDomains, const std::string& aNextToken) {
  try {
    ListDomainsResponsePtr lRes = aSDB->listDomains(aMaxNumberOfDomains, aNextToken);
      std::cout << "list domains successfully" << std::endl;
      lRes->open();
      std::string lDomain;
      while (lRes->next (lDomain)) {
          std::cout << "   Domain: " << lDomain  << std::endl;
        }
      lRes->close();
    } catch (ListDomainsException &e) {
      std::cerr << e.what() << std::endl;
      return false;
    }
  return true;
}

bool putAttribute (SDBConnectionPtr aSDB, const std::string& aDomainName, const std::string& aItemName,
                   const std::string& aKey, const std::string& aValue, bool aReplace) {
  try {
      std::vector<aws::Attribute> lAttrs;
      aws::Attribute lAttr (aKey, aValue, aReplace);
      lAttrs.push_back (lAttr);
      PutAttributesResponsePtr lRes = aSDB->putAttributes (aDomainName, aItemName, lAttrs);
      std::cout << "put attribute successfully" << std::endl;
    } catch (PutAttributesException &e) {
      std::cerr << e.what() << std::endl;
      return false;
    }
  return true;
}

bool deleteAttribute (SDBConnectionPtr aSDB, const std::string& aDomainName, const std::string& aItemName,
                      const std::string& aKey, std::string aValue) {
  try {
      std::vector<aws::Attribute> lAttrs;
      aws::Attribute lAttr (aKey, aValue, false);
      lAttrs.push_back (lAttr);
      DeleteAttributesResponsePtr lRes = aSDB->deleteAttributes (aDomainName, aItemName, lAttrs);
      std::cout << "delete attribute successfully" << std::endl;
    } catch (PutAttributesException &e) {
      std::cerr << e.what()  << std::endl;
      return false;
    }
  return true;
}

bool getAttribute (SDBConnectionPtr aSDB, const std::string& aDomainName, const std::string& aItemName,
                   const std::string attributeName = "") {
  try {
      GetAttributesResponsePtr lRes = aSDB->getAttributes (aDomainName, aItemName, attributeName);
      std::cout << "get attribute successfully" << std::endl;
      lRes->open();
      std::pair<std::string, std::string> lAttr;
      while (lRes->next (lAttr)) {
          std::cout << "   Attr-Name: " << lAttr.first << "-> " <<  lAttr.second  << std::endl;
        }
      lRes->close();
    } catch (PutAttributesException &e) {
      std::cerr << e.what() << std::endl;
      return false;
    }
  return true;
}

bool listAll(SDBConnectionPtr aSDB){
  try {
    ListDomainsResponsePtr lRes = aSDB->listDomains();
    std::cout << "list domains successfully" << std::endl;
    lRes->open();
    std::string lDomain;
    while (lRes->next (lDomain)) {
      std::cout << "  Domain: " << lDomain  << std::endl;
      SDBQueryResponsePtr lRes = aSDB->query (lDomain, "");
      int lCounter = 0;
      lRes->open();
      std::string lItem;
      while (lRes->next (lItem)) {
        std::cout << "    " << ++lCounter << ". Item: " << lItem;
        GetAttributesResponsePtr lRes = aSDB->getAttributes (lDomain, lItem);
        lRes->open();
        std::pair<std::string, std::string> lAttr;
        while (lRes->next (lAttr)) {
          std::cout << " " << lAttr.first << ":" <<  lAttr.second ;
        }
        lRes->close();
        std::cout << std::endl;
      }
      lRes->close();
    }
    lRes->close();
  } catch (ListDomainsException &e) {
    std::cerr << e.what() << std::endl;
    return false;
  }
  return true;

}

bool query (SDBConnectionPtr aSDB, const std::string& aDomainName, const std::string& aQueryExpression, int aMaxNumberOfItems = 0,
            const std::string & aNextToken = "") {
  try {
    SDBQueryResponsePtr lRes = aSDB->query (aDomainName, aQueryExpression, aMaxNumberOfItems, aNextToken);
      std::cout << "query successfully" << std::endl;
      lRes->open();
      std::string lItem;
      while (lRes->next (lItem)) {
          std::cout << "   Item: " << lItem << std::endl;
        }
      lRes->close();
    } catch (PutAttributesException &e) {
      std::cerr << e.what() << std::endl;
      return false;
    }
  return true;
}

int
main (int argc, char** argv) {
  char* lAccessKeyId = 0;
  char* lSecretAccessKey = 0;
  char* lAction = 0;
  char* lDomain = 0;
  int   lMaxItems = 0;
  std::string lNextToken = "";
  char lEmpty[] = { '\0' };
  char* lNextTokenTmp = lEmpty;
  char* lAttrName = 0;
  char* lAttrValue = 0;
  char* lItem = 0;
  char* lQuery = 0;
  bool  lReplace = false;

  int c;
  opterr = 0;

  AWSConnectionFactory* lFactory = AWSConnectionFactory::getInstance();

  while ( (c = getopt (argc, argv, "hi:s:a:d:x:c:t:k:v:q:r")) != -1)
    switch (c) {
      case 'i':
        lAccessKeyId = optarg;
        break;
      case 's':
        lSecretAccessKey = optarg;
        break;
      case 'a':
        lAction = optarg;
        break;
      case 'd':
        lDomain = optarg;
        break;
      case 'x':
        lMaxItems = atoi (optarg);
        break;
      case 'c':
        lItem = optarg;
        break;
      case 't':
        lNextToken = optarg;
        break;
      case 'k':
        lAttrName = optarg;
        break;
      case 'v':
        lAttrValue = optarg;
        break;
      case 'q':
        lQuery = optarg;
        break;
      case 'r':
        lReplace = true;
        break;
      case 'h': {
          std::cout << "libaws version " << lFactory->getVersion() << std::endl;
          std::cout << "Usage: sdb <options>" << std::endl;
          std::cout << "  -i: AWS Access Key Id"  << std::endl;
          std::cout << "  -s: AWS Secret Access Key"  << std::endl;
          std::cout << "  -a action: Action to perform" << std::endl;
          std::cout << "             create-domain" << std::endl;
          std::cout << "             delete-domain" << std::endl;
          std::cout << "             delete-all-domains" << std::endl;
          std::cout << "             list-domains" << std::endl;
          std::cout << "             put-attribute" << std::endl;
          std::cout << "             delete-attribute" << std::endl;
          std::cout << "             get-attribute" << std::endl;
          std::cout << "             query" << std::endl;
          std::cout << "             list-all" << std::endl;
          std::cout << "  -d domain: A Domain Name"  << std::endl;
          std::cout << "  -c item/content: The item"  << std::endl;
          std::cout << "  -x #items: Max number of items/domains"  << std::endl;
          std::cout << "  -t next token: The next token" << std::endl;
          std::cout << "  -k key/attributes: An attribute" << std::endl;
          std::cout << "  -v value: An attribute value" << std::endl;
          std::cout << "  -q query: Replace Attribue" << std::endl;
          std::cout << "  -r replace: Replace Attribue" << std::endl;
          std::cout << "  -h help: display help" << std::endl;
          exit (1);
        }
      case '?':
        if (isprint (optopt))
          fprintf (stderr, "Unknown option `-%c'.\n", optopt);
        else
          fprintf (stderr,
                   "Unknown option character `\\x%x'.\n",
                   optopt);
        exit (1);
      default:
        exit (1);
      }

  if (!lAccessKeyId) {
      lAccessKeyId = getenv ("AWS_ACCESS_KEY");
    }

  if (!lSecretAccessKey) {
      lSecretAccessKey = getenv ("AWS_SECRET_ACCESS_KEY");
    }

  if (!lAccessKeyId) {
      std::cerr << "No Access Key given" << std::endl;
      std::cerr << "Either use -i as a command line argument or set AWS_ACCESS_KEY as an environmental variable" << std::endl;
      exit (1);
    }

  if (!lSecretAccessKey) {
      std::cerr << "No Secret Access Key given" << std::endl;
      std::cerr << "Either use -s as a command line argument or set AWS_SECRET_ACCESS_KEY as an environmental variable" << std::endl;
      exit (1);
    }

  SDBConnectionPtr lSDBRest;
  lSDBRest = lFactory->createSDBConnection (lAccessKeyId, lSecretAccessKey);

  if (!lAction) {
      std::cerr << "No Action parameter specified." << std::endl;
      std::cerr << "Use -a as a command line argument" << std::endl;
      exit (1);
    }
  std::string lActionString (lAction);

  if (lActionString.compare ("list-domains") == 0) {
    listDomains (lSDBRest, lMaxItems, lNextTokenTmp);
      exit (0);
    }
  if (lActionString.compare ("delete-all-domains") == 0) {
      deleteAllDomains (lSDBRest, lQuery==0?"":lQuery);
      exit (0);
    }
    if (lActionString.compare ("list-all") == 0) {
      listAll (lSDBRest);
      exit (0);
    }

  if (!lDomain) {
      std::cerr << "No domain provided." << std::endl;
      exit (1);
    }

  if (lActionString.compare ("create-domain") == 0) {
      createDomain (lSDBRest, lDomain);
      exit (0);
    }

  if (lActionString.compare ("delete-domain") == 0) {
      deleteDomain (lSDBRest, lDomain);
      exit (0);
    }

    if (lActionString.compare ("query") == 0) {
      query (lSDBRest, lDomain, lQuery, lMaxItems, lNextTokenTmp);
      exit(0);
    }

  if (!lItem) {
      std::cerr << "No item provided." << std::endl;
      exit (1);
    }

  if (lActionString.compare ("get-attribute") == 0) {
      if (lAttrName) {
          getAttribute (lSDBRest, lDomain, lItem, lAttrName);
        } else {
          getAttribute (lSDBRest, lDomain, lItem);
        }
    }

  if (!lAttrName) {
      std::cerr << "No attribute name provided." << std::endl;
      exit (1);
    }

  if (!lAttrValue) {
      std::cerr << "No attribute value provided." << std::endl;
      exit (1);
    }

  if (lActionString.compare ("put-attribute") == 0) {
      putAttribute (lSDBRest, lDomain, lItem, lAttrName, lAttrValue, lReplace);
    } else if (lActionString.compare ("delete-attribute") == 0) {
      deleteAttribute (lSDBRest, lDomain, lItem, lAttrName, lAttrValue);
    } else {
      std::cerr << "Command not recognized." << std::endl;
      exit (1);
    }

}

<|endoftext|>


<commit_before>#pragma once

#include <random>
#include <distributions/common.hpp>
#include <distributions/special.hpp>

namespace distributions
{

//typedef std::default_random_engine rng_t;
//typedef std::mt19937 rng_t;
typedef std::ranlux48 rng_t;

inline int sample_int (int low, int high, rng_t & rng)
{
    std::uniform_int_distribution<> sampler(low, high);
    return sampler(rng);
}

inline float sample_unif01 (rng_t & rng)
{
    std::uniform_real_distribution<float> sampler(0.0, 1.0);
    return sampler(rng);
}

// HACK std::gamma_distribution<float> appears to be broken
//typedef std::gamma_distribution<float> gamma_distribution_t;
typedef std::gamma_distribution<double> gamma_distribution_t;

inline float sample_gamma (
        float alpha,
        float beta,
        rng_t & rng)
{
    gamma_distribution_t sampler;
    gamma_distribution_t::param_type param(alpha, beta);
    return sampler(rng, param);
}

void sample_dirichlet (
        size_t dim,
        const float * alphas,
        float * ps,
        rng_t & rng);

int sample_discrete (
        size_t dim,
        const float * ps,
        rng_t & rng);

inline float fast_score_student_t (
        float x,
        float v,
        float mean,
        float lambda)
{
    float p = 0.f;
    p += fast_lgamma_nu(v);
    p += 0.5f * fast_log(lambda / (M_PIf * v));
    p += (-0.5f * v - 0.5f) * fast_log(1.f + (lambda * sqr(x - mean)) / v);
    return p;
}

inline float score_student_t (
        float x,
        float v,
        float mean,
        float lambda)
{
    float p = 0.f;
    p += lgammaf(v * 0.5f + 0.5f) - lgammaf(v * 0.5f);
    p += 0.5f * logf(lambda / (M_PIf * v));
    p += (-0.5f * v - 0.5f) * logf(1.f + (lambda * sqr(x - mean)) / v);
    return p;
}

} // namespace distributions
<commit_msg>Add sample_from_urn and sample_pair_from_urn<commit_after>#pragma once

#include <utility>
#include <random>
#include <distributions/common.hpp>
#include <distributions/special.hpp>

namespace distributions
{

//typedef std::default_random_engine rng_t;
//typedef std::mt19937 rng_t;
typedef std::ranlux48 rng_t;

inline int sample_int (int low, int high, rng_t & rng)
{
    std::uniform_int_distribution<> sampler(low, high);
    return sampler(rng);
}

inline float sample_unif01 (rng_t & rng)
{
    std::uniform_real_distribution<float> sampler(0.0, 1.0);
    return sampler(rng);
}

// HACK std::gamma_distribution<float> appears to be broken
//typedef std::gamma_distribution<float> gamma_distribution_t;
typedef std::gamma_distribution<double> gamma_distribution_t;

inline float sample_gamma (
        float alpha,
        float beta,
        rng_t & rng)
{
    gamma_distribution_t sampler;
    gamma_distribution_t::param_type param(alpha, beta);
    return sampler(rng, param);
}

void sample_dirichlet (
        size_t dim,
        const float * alphas,
        float * ps,
        rng_t & rng);

int sample_discrete (
        size_t dim,
        const float * ps,
        rng_t & rng);

inline float fast_score_student_t (
        float x,
        float v,
        float mean,
        float lambda)
{
    float p = 0.f;
    p += fast_lgamma_nu(v);
    p += 0.5f * fast_log(lambda / (M_PIf * v));
    p += (-0.5f * v - 0.5f) * fast_log(1.f + (lambda * sqr(x - mean)) / v);
    return p;
}

inline float score_student_t (
        float x,
        float v,
        float mean,
        float lambda)
{
    float p = 0.f;
    p += lgammaf(v * 0.5f + 0.5f) - lgammaf(v * 0.5f);
    p += 0.5f * logf(lambda / (M_PIf * v));
    p += (-0.5f * v - 0.5f) * logf(1.f + (lambda * sqr(x - mean)) / v);
    return p;
}

template<class T>
inline T sample_from_urn (
        const std::vector<T> & urn,
        rng_t & rng)
{
    DIST_ASSERT(urn.size() >= 1, "urn is too small to sample from");
    size_t f = sample_int(0, urn.size() - 1, rng);
    DIST_ASSERT(0 <= f and f < urn.size(), "bad value: " << f);
    return urn[f];
}

template<class T>
inline std::pair<T, T> sample_pair_from_urn (
        const std::vector<T> & urn,
        rng_t & rng)
{
    DIST_ASSERT(urn.size() >= 2, "urn is too small to sample pair from");
    size_t f1 = sample_int(0, urn.size() - 1, rng);
    size_t f2 = sample_int(0, urn.size() - 2, rng);
    if (f2 >= f1) {
        f2 += 1;
    }
    DIST_ASSERT(0 <= f1 and f1 < urn.size(), "bad value: " << f1);
    DIST_ASSERT(0 <= f2 and f2 < urn.size(), "bad value: " << f2);
    DIST_ASSERT(f1 != f2, "bad pair: " << f1 << ", " << f2);
    return std::make_pair(urn[f1], urn[f2]);
}

} // namespace distributions
<|endoftext|>


<commit_before>#ifndef UTILS_FACTORY_HPP
#define UTILS_FACTORY_HPP

#include <cassert>
#include <map>

template <class Base, class ID, class... Args>
class Factory
{
    public:
        typedef Base*(*CreatorFunction)(Args...);

    public:
        template <class Derive>
        static Base* defaultCreator(Args... args)
        {
            return new Derive(args...);
        }

    public:
        // TODO: consider using rvalue references and std::forward
        Base* create(const ID& id, Args&... args) const
        {
            assert(_makers.find(id) != _makers.end());
            return _makers.find(id)->second(args...);
        }

        void add(const ID& id, CreatorFunction callback)
        {
            _makers[id] = callback;
        }

        template <class Derive>
        void add(const ID& id)
        {
            add(id, defaultCreator<Derive>);
        }

        void del(const ID& id)
        {
            _makers.erase(id);
        }

        void clear()
        {
            _makers.clear();
        }

        size_t size() const
        {
            return _makers.size();
        }

    private:
        std::map<ID, CreatorFunction> _makers;
};

#endif
<commit_msg>Add haskey function<commit_after>#ifndef UTILS_FACTORY_HPP
#define UTILS_FACTORY_HPP

#include <cassert>
#include <map>

template <class Base, class ID, class... Args>
class Factory
{
    public:
        typedef Base*(*CreatorFunction)(Args...);

    public:
        template <class Derive>
        static Base* defaultCreator(Args... args)
        {
            return new Derive(args...);
        }

    public:
        // TODO: consider using rvalue references and std::forward
        Base* create(const ID& id, Args&... args) const
        {
            assert(_makers.find(id) != _makers.end());
            return _makers.find(id)->second(args...);
        }

        void add(const ID& id, CreatorFunction callback)
        {
            _makers[id] = callback;
        }

        template <class Derive>
        void add(const ID& id)
        {
            add(id, defaultCreator<Derive>);
        }

        void del(const ID& id)
        {
            _makers.erase(id);
        }

        bool haskey(const ID& id) const
        {
            return _makers.find(id) != _makers.end();
        }

        void clear()
        {
            _makers.clear();
        }

        size_t size() const
        {
            return _makers.size();
        }

    private:
        std::map<ID, CreatorFunction> _makers;
};

#endif
<|endoftext|>


<commit_before>/*****************************************************************************
 *
 * This file is part of Mapnik (c++ mapping toolkit)
 *
 * Copyright (C) 2014 Artem Pavlenko
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 *
 *****************************************************************************/

#ifndef MAPNIK_IMAGE_DATA_HPP
#define MAPNIK_IMAGE_DATA_HPP

// mapnik
#include <mapnik/global.hpp>
// stl
#include <algorithm>
#include <cassert>
#include <stdexcept>

namespace mapnik {

namespace detail {

struct buffer
{
    explicit buffer(std::size_t size)
        : size_(size),
          data_(static_cast<unsigned char*>(size_ != 0 ? ::operator new(size_) : nullptr))
    {}

    buffer(buffer && rhs) noexcept = default;
    buffer(buffer const& rhs)
        : size_(rhs.size_),
          data_(rhs.data_)
    {
        if (data_) std::copy(rhs.data_, rhs.data_ + rhs.size_, data_);
    }

    inline bool operator!() const { return (data_ == nullptr)? false : true; }
    ~buffer()
    {
        ::operator delete(data_);
    }

    inline unsigned char* data() { return data_; }
    inline unsigned char const* data() const { return data_; }
    inline std::size_t size() const { return size_; }
    std::size_t size_;
    unsigned char* data_;

};

}

template <typename T>
class image_data
{
public:
    using pixel_type = T;
    static constexpr std::size_t pixel_size = sizeof(pixel_type);

    image_data(std::size_t width, std::size_t height, bool initialize = true)
        : width_(width),
          height_(height),
          buffer_(width_ * height_ * pixel_size),
          pData_(reinterpret_cast<pixel_type*>(buffer_.data()))
    {
        if (pData_ && initialize) std::fill(pData_, pData_ + width_ * height_, 0);
    }

    image_data(image_data<pixel_type> const& rhs)
        : width_(rhs.width_),
          height_(rhs.height_),
          buffer_(rhs.buffer_),
          pData_(reinterpret_cast<pixel_type*>(buffer_.data()))
    {}

    image_data(image_data<pixel_type> && rhs) noexcept
        : width_(rhs.width_),
        height_(rhs.height_),
        buffer_(std::move(rhs.buffer_)),
        pData_(reinterpret_cast<pixel_type*>(buffer_.data()))
    {
        rhs.width_ = 0;
        rhs.height_ = 0;
        rhs.pData_ = nullptr;
    }

    image_data<pixel_type>& operator=(image_data<pixel_type> rhs)
    {
        swap(rhs);
        return *this;
    }

    void swap(image_data<pixel_type> & rhs)
    {
        std::swap(width_, rhs.width_);
        std::swap(height_, rhs.height_);
        std::swap(buffer_, rhs.buffer_);
    }

    inline pixel_type& operator() (std::size_t i, std::size_t j)
    {
        assert(i<width_ && j<height_);
        return pData_[j * width_ + i];
    }
    inline const pixel_type& operator() (std::size_t i, std::size_t j) const
    {
        assert(i < width_ && j < height_);
        return pData_[j * width_ + i];
    }
    inline std::size_t width() const
    {
        return width_;
    }
    inline std::size_t height() const
    {
        return height_;
    }
    inline void set(pixel_type const& t)
    {
        std::fill(pData_, pData_ + width_ * height_, t);
    }

    inline const pixel_type* getData() const
    {
        return pData_;
    }

    inline pixel_type* getData()
    {
        return pData_;
    }

    inline const unsigned char* getBytes() const
    {
        return buffer_.data();
    }

    inline unsigned char* getBytes()
    {
        return buffer_.data();
    }

    inline const pixel_type* getRow(unsigned row) const
    {
        return pData_ + row * width_;
    }

    inline pixel_type* getRow(unsigned row)
    {
        return pData_ + row * width_;
    }

    inline void setRow(std::size_t row, pixel_type const* buf, std::size_t size)
    {
        assert(row < height_);
        assert(size <= width_);
        std::copy(buf, buf + size, pData_ + row * width_);
    }
    inline void setRow(std::size_t row, std::size_t x0, std::size_t x1, pixel_type const* buf)
    {
        std::copy(buf, buf + (x1 - x0), pData_ + row * width_);
    }
private:
    std::size_t width_;
    std::size_t height_;
    detail::buffer buffer_;
    pixel_type *pData_;
};

using image_data_32 = image_data<std::uint32_t>;
using image_data_8 = image_data<byte> ;
}

#endif // MAPNIK_IMAGE_DATA_HPP
<commit_msg>port image_data fixes from image_data_any branch<commit_after>/*****************************************************************************
 *
 * This file is part of Mapnik (c++ mapping toolkit)
 *
 * Copyright (C) 2014 Artem Pavlenko
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 *
 *****************************************************************************/

#ifndef MAPNIK_IMAGE_DATA_HPP
#define MAPNIK_IMAGE_DATA_HPP

// mapnik
#include <mapnik/global.hpp>
// stl
#include <algorithm>
#include <cassert>
#include <stdexcept>

namespace mapnik {

namespace detail {

struct buffer
{
    explicit buffer(std::size_t size)
        : size_(size),
          data_(static_cast<unsigned char*>(size_ != 0 ? ::operator new(size_) : nullptr))
    {}

    buffer(buffer && rhs) noexcept
        : size_(std::move(rhs.size_)),
          data_(std::move(rhs.data_))
    {
        rhs.size_ = 0;
        rhs.data_ = nullptr;
    }

    buffer(buffer const& rhs)
        : size_(rhs.size_),
          data_(static_cast<unsigned char*>(size_ != 0 ? ::operator new(size_) : nullptr))
    {
        if (data_) std::copy(rhs.data_, rhs.data_ + rhs.size_, data_);
    }

    inline bool operator!() const { return (data_ == nullptr)? false : true; }
    ~buffer()
    {
        ::operator delete(data_);
    }

    inline unsigned char* data() { return data_; }
    inline unsigned char const* data() const { return data_; }
    inline std::size_t size() const { return size_; }
    std::size_t size_;
    unsigned char* data_;

};

}

template <typename T>
class image_data
{
public:
    using pixel_type = T;
    static constexpr std::size_t pixel_size = sizeof(pixel_type);

    image_data(std::size_t width, std::size_t height, bool initialize = true)
        : width_(width),
          height_(height),
          buffer_(width_ * height_ * pixel_size),
          pData_(reinterpret_cast<pixel_type*>(buffer_.data()))
    {
        if (pData_ && initialize) std::fill(pData_, pData_ + width_ * height_, 0);
    }

    image_data(image_data<pixel_type> const& rhs)
        : width_(rhs.width_),
          height_(rhs.height_),
          buffer_(rhs.buffer_),
          pData_(reinterpret_cast<pixel_type*>(buffer_.data()))
    {}

    image_data(image_data<pixel_type> && rhs) noexcept
        : width_(rhs.width_),
        height_(rhs.height_),
        buffer_(std::move(rhs.buffer_)),
        pData_(reinterpret_cast<pixel_type*>(buffer_.data()))
    {
        rhs.width_ = 0;
        rhs.height_ = 0;
        rhs.pData_ = nullptr;
    }

    image_data<pixel_type>& operator=(image_data<pixel_type> rhs)
    {
        swap(rhs);
        return *this;
    }

    void swap(image_data<pixel_type> & rhs)
    {
        std::swap(width_, rhs.width_);
        std::swap(height_, rhs.height_);
        std::swap(buffer_, rhs.buffer_);
    }

    inline pixel_type& operator() (std::size_t i, std::size_t j)
    {
        assert(i<width_ && j<height_);
        return pData_[j * width_ + i];
    }
    inline const pixel_type& operator() (std::size_t i, std::size_t j) const
    {
        assert(i < width_ && j < height_);
        return pData_[j * width_ + i];
    }
    inline std::size_t width() const
    {
        return width_;
    }
    inline std::size_t height() const
    {
        return height_;
    }
    inline void set(pixel_type const& t)
    {
        std::fill(pData_, pData_ + width_ * height_, t);
    }

    inline const pixel_type* getData() const
    {
        return pData_;
    }

    inline pixel_type* getData()
    {
        return pData_;
    }

    inline const unsigned char* getBytes() const
    {
        return buffer_.data();
    }

    inline unsigned char* getBytes()
    {
        return buffer_.data();
    }

    inline const pixel_type* getRow(unsigned row) const
    {
        return pData_ + row * width_;
    }

    inline pixel_type* getRow(unsigned row)
    {
        return pData_ + row * width_;
    }

    inline void setRow(std::size_t row, pixel_type const* buf, std::size_t size)
    {
        assert(row < height_);
        assert(size <= width_);
        std::copy(buf, buf + size, pData_ + row * width_);
    }
    inline void setRow(std::size_t row, std::size_t x0, std::size_t x1, pixel_type const* buf)
    {
        assert(row < height_);
        assert ((x1 - x0) <= width_ );
        std::copy(buf, buf + (x1 - x0), pData_ + row * width_ + x0);
    }
private:
    std::size_t width_;
    std::size_t height_;
    detail::buffer buffer_;
    pixel_type *pData_;
};

using image_data_32 = image_data<std::uint32_t>;
using image_data_8 = image_data<byte> ;
}

#endif // MAPNIK_IMAGE_DATA_HPP
<|endoftext|>


<commit_before>#ifndef KGR_KANGARU_INCLUDE_KANGARU_DETAIL_ERROR_HPP
#define KGR_KANGARU_INCLUDE_KANGARU_DETAIL_ERROR_HPP

#include "traits.hpp"
#include "single.hpp"
#include "service_traits.hpp"

namespace kgr {
namespace detail {

template<typename T, typename... Args>
struct ServiceError {
	template<typename Service = T, enable_if_t<
		is_service<Service>::value &&
		dependency_trait<is_override_convertible, Service>::value &&
		!is_override_convertible<Service>::value, int> = 0>
	ServiceError() {
		static_assert(false_t<Service>::value,
			"The service injected type cannot be converted to the overriding type. "
			"Check if the service is overriding the right service and if types are compatible."
		);
	}

	template<typename Arg, typename Service = T, enable_if_t<
		is_service<Service>::value &&
		dependency_trait<is_override_convertible, Service>::value &&
		!is_override_convertible<Service>::value, int> = 0>
	ServiceError(Arg&&) {
		static_assert(false_t<Service>::value,
			"The service injected type cannot be converted to the overriding type. "
			"Check if the service is overriding the right service and if types are compatible."
		);
	}

	template<typename Service = T, enable_if_t<
		is_service<Service>::value &&
		!dependency_trait<is_override_convertible, Service>::value, int> = 0>
	ServiceError() {
		static_assert(false_t<Service>::value,
			"One or more dependencies injected type cannot be converted to one of it's overriding type. "
			"Check if that service is overriding the right service and if types are compatible."
		);
	}

	template<typename Arg, typename Service = T, enable_if_t<
		is_service<Service>::value &&
		!dependency_trait<is_override_convertible, Service>::value, int> = 0>
	ServiceError(Arg&&) {
		static_assert(false_t<Service>::value,
			"One or more dependencies injected type cannot be converted to one of it's overriding type. "
			"Check if that service is overriding the right service and if types are compatible."
		);
	}

	//
	template<typename Service = T, enable_if_t<
		is_service<Service>::value &&
		dependency_trait<is_default_service_valid, Service>::value &&
		!is_default_service_valid<Service>::value &&
		is_default_convertible<Service>::value &&
		is_default_overrides_abstract<Service>::value, int> = 0>
	ServiceError() {
		static_assert(false_t<Service>::value,
			"The default implementation of this abstract service is not a well defined service. "
			"Please check that types are complete and exposing a valid service definition interface."
		);
	}

	template<typename Arg, typename Service = T, enable_if_t<
		is_service<Service>::value &&
		dependency_trait<is_default_service_valid, Service>::value &&
		!is_default_service_valid<Service>::value &&
		is_default_convertible<Service>::value &&
		is_default_overrides_abstract<Service>::value, int> = 0>
	ServiceError(Arg&&) {
		static_assert(false_t<Service>::value,
			"The default implementation of this abstract service is not a well defined service. "
			"Please check that types are complete and exposing a valid service definition interface."
		);
	}

	template<typename Service = T, enable_if_t<
		is_service<Service>::value &&
		dependency_trait<is_default_service_valid, Service>::value &&
		!is_default_service_valid<Service>::value &&
		!is_default_convertible<Service>::value &&
		is_default_overrides_abstract<Service>::value, int> = 0>
	ServiceError() {
		static_assert(false_t<Service>::value,
			"The service type of the default implementation of this abstract service is not convertible to the abstract service type. "
			"Please check that the service type of the default implementation of that abstract service is a compatible type."
		);
	}

	template<typename Arg, typename Service = T, enable_if_t<
		is_service<Service>::value &&
		dependency_trait<is_default_service_valid, Service>::value &&
		!is_default_service_valid<Service>::value &&
		!is_default_convertible<Service>::value &&
		is_default_overrides_abstract<Service>::value, int> = 0>
	ServiceError(Arg&&) {
		static_assert(false_t<Service>::value,
			"The service type of the default implementation of this abstract service is not convertible to the abstract service type. "
			"Please check that the service type of the default implementation of that abstract service is a compatible type."
		);
	}

	template<typename Service = T, enable_if_t<
		is_service<Service>::value &&
		dependency_trait<is_default_service_valid, Service>::value &&
		!is_default_service_valid<Service>::value &&
		!is_default_overrides_abstract<Service>::value, int> = 0>
	ServiceError() {
		static_assert(false_t<Service>::value,
			"The default implementation of this abstract service is not overriding that abstract service. "
			"Ensure that the default implementation really override this abstract service."
		);
	}

	template<typename Arg, typename Service = T, enable_if_t<
		is_service<Service>::value &&
		dependency_trait<is_default_service_valid, Service>::value &&
		!is_default_service_valid<Service>::value &&
		!is_default_overrides_abstract<Service>::value, int> = 0>
	ServiceError(Arg&&) {
		static_assert(false_t<Service>::value,
			"The default implementation of this abstract service is not overriding that abstract service. "
			"Ensure that the default implementation really override this abstract service."
		);
	}

	template<typename Service = T, enable_if_t<
		is_service<Service>::value &&
		!dependency_trait<is_default_service_valid, Service>::value, int> = 0>
	ServiceError() {
		static_assert(false_t<Service>::value,
			"The default implementation of a dependency is not valid. "
			"Ensure that every default implementation are valid services that override properly thier abstract services."
		);
	}

	template<typename Arg, typename Service = T, enable_if_t<
		is_service<Service>::value &&
		!dependency_trait<is_default_service_valid, Service>::value, int> = 0>
	ServiceError(Arg&&) {
		static_assert(false_t<Service>::value,
			"The default implementation of a dependency is not valid. "
			"Ensure that every default implementation are valid services that override properly thier abstract services."
		);
	}
	//

	template<typename Arg, typename Service = T, enable_if_t<
		is_service<Arg>::value &&
		dependency_trait<is_construct_function_callable, Service, Arg, Args...>::value &&
		!dependency_trait<is_service_constructible, Service, Arg, Args...>::value &&
		is_service_constructible<Service, Arg, Args...>::value, int> = 0>
	ServiceError(Arg&&) {
		static_assert(false_t<Arg>::value,
			"One or more dependencies are not constructible with it's dependencies as constructor argument. "
			"Please check that dependency's constructor and it's dependencies."
		);
	}

	template<typename Service = T, enable_if_t<
		is_service<Service>::value &&
		dependency_trait<is_construct_function_callable, Service>::value &&
		!dependency_trait<is_service_constructible, Service>::value &&
		is_service_constructible<Service>::value, int> = 0>
	ServiceError() {
		static_assert(false_t<Service>::value,
			"One or more dependencies are not constructible with it's dependencies as constructor argument. "
			"Please check that dependency's constructor and dependencies."
		);
	}

	template<typename Arg, typename Service = T, enable_if_t<
		is_service<Arg>::value &&
		!dependency_trait<is_construct_function_callable, Service, Arg, Args...>::value &&
		is_construct_function_callable<Service, Arg, Args...>::value &&
		is_service_constructible<Service, Arg, Args...>::value, int> = 0>
	ServiceError(Arg&&) {
		static_assert(false_t<Arg>::value,
			"One or more dependencies construct function cannot be called when calling kgr::Container::service<Dependency>(). "
			"Please check that dependency's construct function and ensure that is well formed."
		);
	}

	template<typename Service = T, enable_if_t<
		is_service<Service>::value &&
		!dependency_trait<is_construct_function_callable, Service>::value &&
		is_construct_function_callable<Service>::value &&
		is_service_constructible<Service>::value, int> = 0>
	ServiceError() {
		static_assert(false_t<Service>::value,
			"One or more dependencies construct function cannot be called when calling kgr::Container::service<Dependency>(). "
			"Please check that dependency's construct function and ensure that is well formed."
		);
	}

	template<typename Arg, typename Service = T, enable_if_t<
		is_service<Service>::value &&
		!is_service_constructible<Service, Arg, Args...>::value &&
		!is_service_constructible<Service>::value, int> = 0>
	ServiceError(Arg&&) {
		static_assert(false_t<Arg>::value,
			"The service type is not constructible given it's dependencies and passed arguments. "
			"Ensure that dependencies are correctly configured and you pass the right set of parameters."
		);
	}

	template<typename Arg, typename Service = T, enable_if_t<
		is_service<Service>::value &&
		!is_service_constructible<Service, Arg, Args...>::value &&
		is_service_constructible<Service>::value, int> = 0>
	ServiceError(Arg&&) {
		static_assert(false_t<Arg>::value, "The service type is not constructible given passed arguments to kgr::Container::service(...).");
	}

	template<typename Service = T, enable_if_t<
		is_service<Service>::value &&
		is_construct_function_callable<Service>::value &&
		!is_service_constructible<Service>::value, int> = 0>
	ServiceError() {
		static_assert(false_t<Service>::value,
			"The service type is not constructible given it's dependencies. "
			"Check if dependencies are configured correctly and if the service has the required constructor."
		);
	}

	template<typename Service = T, enable_if_t<
		is_service<Service>::value &&
		is_single<Service>::value &&
		!is_construct_function_callable<Service>::value, int> = 0>
	ServiceError() {
		static_assert(false_t<Service>::value,
			"The service construct function cannot be called. "
			"Check if the construct function is well formed, receive injected arguments first and additional parameters at the end."
		);
	}

	template<typename Service = T, enable_if_t<
		is_service<Service>::value &&
		!is_single<Service>::value &&
		!is_construct_function_callable<Service>::value, int> = 0>
	ServiceError() {
		static_assert(false_t<Service>::value,
			"The service construct function cannot be called without arguments, or is not well formed. "
			"Check if the construct function is well formed, receive injected arguments first and additional parameters at the end."
		);
	}

	template<typename Arg, typename Service = T, enable_if_t<
		is_service<Service>::value &&
		!is_single<Service>::value &&
		!is_construct_function_callable<Service, Arg, Args...>::value, int> = 0>
	ServiceError(Arg&&) {
		static_assert(false_t<Service>::value,
			"The service construct function cannot be called. "
			"Check if the construct function is well formed, receive injected arguments first and additional parameters at the end."
		);
	}

	template<typename Service = T, enable_if_t<!is_service<Service>::value && !has_forward<Service>::value, int> = 0>
	ServiceError() {
		static_assert(false_t<Service>::value, "The type sent to kgr::Container::service(...) is not a service.");
	}

	template<typename Service = T, enable_if_t<!is_service<Service>::value && has_forward<Service>::value, int> = 0>
	ServiceError() {
		static_assert(false_t<Service>::value, "The service type must not not contain any virtual function or must be abstract.");
	}
};

struct NotInvokableError {
	template<typename T = void>
	NotInvokableError(...) {
		static_assert(false_t<T>::value,
			"The function sent is not invokable. Ensure to include all services definitions "
			"you need and that received parameters are correct."
		);
	}
};

} // namespace detail
} // namespace kgr

#endif // KGR_KANGARU_INCLUDE_KANGARU_DETAIL_ERROR_HPP
<commit_msg>fixed some error messages<commit_after>#ifndef KGR_KANGARU_INCLUDE_KANGARU_DETAIL_ERROR_HPP
#define KGR_KANGARU_INCLUDE_KANGARU_DETAIL_ERROR_HPP

#include "traits.hpp"
#include "single.hpp"
#include "service_traits.hpp"

namespace kgr {
namespace detail {

template<typename T, typename... Args>
struct ServiceError {
	template<typename Service = T, enable_if_t<
		is_service<Service>::value &&
		!is_override_convertible<Service>::value, int> = 0>
	ServiceError() {
		static_assert(false_t<Service>::value,
			"The service injected type cannot be converted to the overriding type. "
			"Check if the service is overriding the right service and if types are compatible."
		);
	}

	template<typename Arg, typename Service = T, enable_if_t<
		is_service<Service>::value &&
		!is_override_convertible<Service>::value, int> = 0>
	ServiceError(Arg&&) {
		static_assert(false_t<Service>::value,
			"The service injected type cannot be converted to the overriding type. "
			"Check if the service is overriding the right service and if types are compatible."
		);
	}

	template<typename Service = T, enable_if_t<
		is_service<Service>::value &&
		!dependency_trait<is_override_convertible, Service>::value &&
		is_service_constructible<Service>::value, int> = 0>
	ServiceError() {
		static_assert(false_t<Service>::value,
			"One or more dependencies injected type cannot be converted to one of it's overriding type. "
			"Check if that service is overriding the right service and if types are compatible."
		);
	}

	template<typename Arg, typename Service = T, enable_if_t<
		is_service<Service>::value &&
		!dependency_trait<is_override_convertible, Service, Arg, Args...>::value &&
		is_service_constructible<Service>::value, int> = 0>
	ServiceError(Arg&&) {
		static_assert(false_t<Service>::value,
			"One or more dependencies injected type cannot be converted to one of it's overriding type. "
			"Check if that service is overriding the right service and if types are compatible."
		);
	}
	template<typename Service = T, enable_if_t<
		is_service<Service>::value &&
		dependency_trait<is_default_service_valid, Service>::value &&
		!is_default_service_valid<Service>::value &&
		is_default_convertible<Service>::value &&
		is_default_overrides_abstract<Service>::value, int> = 0>
	ServiceError() {
		static_assert(false_t<Service>::value,
			"The default implementation of this abstract service is not a well defined service. "
			"Please check that types are complete and exposing a valid service definition interface."
		);
	}

	template<typename Arg, typename Service = T, enable_if_t<
		is_service<Service>::value &&
		dependency_trait<is_default_service_valid, Service, Arg, Args...>::value &&
		!is_default_service_valid<Service>::value &&
		is_default_convertible<Service>::value &&
		is_default_overrides_abstract<Service>::value, int> = 0>
	ServiceError(Arg&&) {
		static_assert(false_t<Service>::value,
			"The default implementation of this abstract service is not a well defined service. "
			"Please check that types are complete and exposing a valid service definition interface."
		);
	}

	template<typename Service = T, enable_if_t<
		is_service<Service>::value &&
		dependency_trait<is_default_service_valid, Service>::value &&
		!is_default_service_valid<Service>::value &&
		!is_default_convertible<Service>::value &&
		is_default_overrides_abstract<Service>::value, int> = 0>
	ServiceError() {
		static_assert(false_t<Service>::value,
			"The service type of the default implementation of this abstract service is not convertible to the abstract service type. "
			"Please check that the service type of the default implementation of that abstract service is a compatible type."
		);
	}

	template<typename Arg, typename Service = T, enable_if_t<
		is_service<Service>::value &&
		dependency_trait<is_default_service_valid, Service, Arg, Args...>::value &&
		!is_default_service_valid<Service>::value &&
		!is_default_convertible<Service>::value &&
		is_default_overrides_abstract<Service>::value, int> = 0>
	ServiceError(Arg&&) {
		static_assert(false_t<Service>::value,
			"The service type of the default implementation of this abstract service is not convertible to the abstract service type. "
			"Please check that the service type of the default implementation of that abstract service is a compatible type."
		);
	}

	template<typename Service = T, enable_if_t<
		is_service<Service>::value &&
		dependency_trait<is_default_service_valid, Service>::value &&
		!is_default_service_valid<Service>::value &&
		!is_default_overrides_abstract<Service>::value, int> = 0>
	ServiceError() {
		static_assert(false_t<Service>::value,
			"The default implementation of this abstract service is not overriding that abstract service. "
			"Ensure that the default implementation really override this abstract service."
		);
	}

	template<typename Arg, typename Service = T, enable_if_t<
		is_service<Service>::value &&
		dependency_trait<is_default_service_valid, Service, Arg, Args...>::value &&
		!is_default_service_valid<Service>::value &&
		!is_default_overrides_abstract<Service>::value, int> = 0>
	ServiceError(Arg&&) {
		static_assert(false_t<Service>::value,
			"The default implementation of this abstract service is not overriding that abstract service. "
			"Ensure that the default implementation really override this abstract service."
		);
	}

	template<typename Service = T, enable_if_t<
		is_service<Service>::value &&
		!dependency_trait<is_default_service_valid, Service>::value, int> = 0>
	ServiceError() {
		static_assert(false_t<Service>::value,
			"The default implementation of a dependency is not valid. "
			"Ensure that every default implementation are valid services that override properly thier abstract services."
		);
	}

	template<typename Arg, typename Service = T, enable_if_t<
		is_service<Service>::value &&
		!dependency_trait<is_default_service_valid, Service, Arg, Args...>::value, int> = 0>
	ServiceError(Arg&&) {
		static_assert(false_t<Service>::value,
			"The default implementation of a dependency is not valid. "
			"Ensure that every default implementation are valid services that override properly thier abstract services."
		);
	}

	template<typename Arg, typename Service = T, enable_if_t<
		is_service<Arg>::value &&
		dependency_trait<is_construct_function_callable, Service, Arg, Args...>::value &&
		!dependency_trait<is_service_constructible, Service, Arg, Args...>::value &&
		is_service_constructible<Service, Arg, Args...>::value, int> = 0>
	ServiceError(Arg&&) {
		static_assert(false_t<Arg>::value,
			"One or more dependencies are not constructible with it's dependencies as constructor argument. "
			"Please check that dependency's constructor and it's dependencies."
		);
	}

	template<typename Service = T, enable_if_t<
		is_service<Service>::value &&
		dependency_trait<is_construct_function_callable, Service>::value &&
		!dependency_trait<is_service_constructible, Service>::value &&
		is_service_constructible<Service>::value, int> = 0>
	ServiceError() {
		static_assert(false_t<Service>::value,
			"One or more dependencies are not constructible with it's dependencies as constructor argument. "
			"Please check that dependency's constructor and dependencies."
		);
	}

	template<typename Arg, typename Service = T, enable_if_t<
		is_service<Arg>::value &&
		!dependency_trait<is_construct_function_callable, Service, Arg, Args...>::value &&
		is_construct_function_callable<Service, Arg, Args...>::value &&
		is_service_constructible<Service, Arg, Args...>::value, int> = 0>
	ServiceError(Arg&&) {
		static_assert(false_t<Arg>::value,
			"One or more dependencies construct function cannot be called when calling kgr::Container::service<Dependency>(). "
			"Please check that dependency's construct function and ensure that is well formed."
		);
	}

	template<typename Service = T, enable_if_t<
		is_service<Service>::value &&
		!dependency_trait<is_construct_function_callable, Service>::value &&
		is_construct_function_callable<Service>::value &&
		is_service_constructible<Service>::value, int> = 0>
	ServiceError() {
		static_assert(false_t<Service>::value,
			"One or more dependencies construct function cannot be called when calling kgr::Container::service<Dependency>(). "
			"Please check that dependency's construct function and ensure that is well formed."
		);
	}

	template<typename Arg, typename Service = T, enable_if_t<
		is_service<Service>::value &&
		!is_service_constructible<Service, Arg, Args...>::value &&
		!is_service_constructible<Service>::value, int> = 0>
	ServiceError(Arg&&) {
		static_assert(false_t<Arg>::value,
			"The service type is not constructible given it's dependencies and passed arguments. "
			"Ensure that dependencies are correctly configured and you pass the right set of parameters."
		);
	}

	template<typename Arg, typename Service = T, enable_if_t<
		is_service<Service>::value &&
		!is_service_constructible<Service, Arg, Args...>::value &&
		is_service_constructible<Service>::value, int> = 0>
	ServiceError(Arg&&) {
		static_assert(false_t<Arg>::value, "The service type is not constructible given passed arguments to kgr::Container::service(...).");
	}

	template<typename Service = T, enable_if_t<
		is_service<Service>::value &&
		is_construct_function_callable<Service>::value &&
		!is_service_constructible<Service>::value, int> = 0>
	ServiceError() {
		static_assert(false_t<Service>::value,
			"The service type is not constructible given it's dependencies. "
			"Check if dependencies are configured correctly and if the service has the required constructor."
		);
	}

	template<typename Service = T, enable_if_t<
		is_service<Service>::value &&
		is_single<Service>::value &&
		!is_construct_function_callable<Service>::value, int> = 0>
	ServiceError() {
		static_assert(false_t<Service>::value,
			"The service construct function cannot be called. "
			"Check if the construct function is well formed, receive injected arguments first and additional parameters at the end."
		);
	}

	template<typename Service = T, enable_if_t<
		is_service<Service>::value &&
		!is_single<Service>::value &&
		!is_construct_function_callable<Service>::value, int> = 0>
	ServiceError() {
		static_assert(false_t<Service>::value,
			"The service construct function cannot be called without arguments, or is not well formed. "
			"Check if the construct function is well formed, receive injected arguments first and additional parameters at the end."
		);
	}

	template<typename Arg, typename Service = T, enable_if_t<
		is_service<Service>::value &&
		!is_single<Service>::value &&
		!is_construct_function_callable<Service, Arg, Args...>::value, int> = 0>
	ServiceError(Arg&&) {
		static_assert(false_t<Service>::value,
			"The service construct function cannot be called. "
			"Check if the construct function is well formed, receive injected arguments first and additional parameters at the end."
		);
	}

	template<typename Service = T, enable_if_t<!is_service<Service>::value && !has_forward<Service>::value, int> = 0>
	ServiceError() {
		static_assert(false_t<Service>::value, "The type sent to kgr::Container::service(...) is not a service.");
	}

	template<typename Service = T, enable_if_t<!is_service<Service>::value && has_forward<Service>::value, int> = 0>
	ServiceError() {
		static_assert(false_t<Service>::value, "The service type must not not contain any virtual function or must be abstract.");
	}
};

struct NotInvokableError {
	template<typename T = void>
	NotInvokableError(...) {
		static_assert(false_t<T>::value,
			"The function sent is not invokable. Ensure to include all services definitions "
			"you need and that received parameters are correct."
		);
	}
};

} // namespace detail
} // namespace kgr

#endif // KGR_KANGARU_INCLUDE_KANGARU_DETAIL_ERROR_HPP
<|endoftext|>


<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*************************************************************************
 *
 * Copyright (c) 2015 Kohei Yoshida
 *
 * Permission is hereby granted, free of charge, to any person
 * obtaining a copy of this software and associated documentation
 * files (the "Software"), to deal in the Software without
 * restriction, including without limitation the rights to use,
 * copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following
 * conditions:
 *
 * The above copyright notice and this permission notice shall be
 * included in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
 * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
 * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
 * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
 * OTHER DEALINGS IN THE SOFTWARE.
 *
 ************************************************************************/

#include "mdds/global.hpp"

#include <cassert>
#include <algorithm>

#ifdef MDDS_TRIE_MAP_DEBUG
#include <iostream>
#endif

namespace mdds { namespace draft {

namespace detail {

struct trie_node
{
    char key;
    const void* value;

    std::deque<trie_node> children;

    trie_node(char _key) : key(_key), value(nullptr) {}
};

#ifdef MDDS_TRIE_MAP_DEBUG

template<typename _ValueT>
void dump_node(std::string& buffer, const trie_node& node)
{
    using namespace std;
    using value_type = _ValueT;

    if (node.value)
    {
        // This node has value.
        cout << buffer << ":" << *static_cast<const value_type*>(node.value) << endl;
    }

    std::for_each(node.children.begin(), node.children.end(),
        [&](const trie_node& node)
        {
            buffer.push_back(node.key);
            dump_node<value_type>(buffer, node);
            buffer.pop_back();
        }
    );
}

template<typename _ValueT>
void dump_trie(const trie_node& root)
{
    std::string buffer;
    dump_node<_ValueT>(buffer, root);
}

template<typename _ValueT>
void dump_packed_trie(const std::vector<uintptr_t>& packed)
{
    using namespace std;

    using value_type = _ValueT;

    cout << "packed size: " << packed.size() << endl;

    size_t n = packed.size();
    size_t i = 0;
    cout << i << ": root node offset: " << packed[i] << endl;
    ++i;

    while (i < n)
    {
        const value_type* value = reinterpret_cast<const value_type*>(packed[i]);
        cout << i << ": node value pointer: " << value;
        if (value)
            cout << ", value: " << *value;
        cout << endl;
        ++i;

        size_t index_size = packed[i];
        cout << i << ": index size: " << index_size << endl;
        ++i;
        index_size /= 2;

        for (size_t j = 0; j < index_size; ++j)
        {
            char key = packed[i];
            cout << i << ": key: " << key << endl;
            ++i;
            size_t offset = packed[i];
            cout << i << ": offset: " << offset << endl;
            ++i;
        }
    }
}

#endif

template<typename _EntryT>
void traverse_range(
    trie_node& root, const _EntryT* start, const _EntryT* end, size_t pos)
{
    using namespace std;
    using entry = _EntryT;

    const entry* p = start;
    const entry* range_start = start;
    const entry* range_end = nullptr;
    char range_char = 0;
    size_t range_count = 0;

    for (; p != end; ++p)
    {
        if (pos > p->keylen)
            continue;

        if (pos == p->keylen)
        {
            root.value = &p->value;
            continue;
        }

        ++range_count;
        char c = p->key[pos];

        if (!range_char)
            range_char = c;
        else if (range_char != c)
        {
            // End of current character range.
            range_end = p;

            root.children.emplace_back(range_char);
            traverse_range(root.children.back(), range_start, range_end, pos+1);
            range_start = range_end;
            range_char = range_start->key[pos];
            range_end = nullptr;
            range_count = 1;
        }
    }

    if (range_count)
    {
        assert(range_char);
        root.children.emplace_back(range_char);
        traverse_range(root.children.back(), range_start, end, pos+1);
    }
}

inline size_t compact_node(std::vector<uintptr_t>& packed, const trie_node& node)
{
    std::vector<std::tuple<size_t,char>> child_offsets;
    child_offsets.reserve(node.children.size());

    // Process child nodes first.
    std::for_each(node.children.begin(), node.children.end(),
        [&](const trie_node& node)
        {
            size_t child_offset = compact_node(packed, node);
            child_offsets.emplace_back(child_offset, node.key);
        }
    );

    // Process this node.
    size_t offset = packed.size();
    packed.push_back(uintptr_t(node.value));
    packed.push_back(uintptr_t(child_offsets.size()*2));

    std::for_each(child_offsets.begin(), child_offsets.end(),
        [&](const std::tuple<size_t,char>& v)
        {
            char key = std::get<1>(v);
            size_t child_offset = std::get<0>(v);
            packed.push_back(key);
            packed.push_back(offset-child_offset);
        }
    );

    return offset;
}

inline void compact(std::vector<uintptr_t>& packed, const trie_node& root)
{
    std::vector<uintptr_t> init(size_t(1), uintptr_t(0));
    packed.swap(init);

    size_t root_offset = compact_node(packed, root);
    packed[0] = root_offset;
}

}

template<typename _ValueT>
trie_map<_ValueT>::trie_map(
    const entry* entries, size_type entry_size, value_type null_value) :
    m_null_value(null_value)
{
    const entry* p = entries;
    const entry* p_end = p + entry_size;

    // Populate the normal tree first.
    detail::trie_node root(0);
    detail::traverse_range(root, p, p_end, 0);
#if defined(MDDS_TRIE_MAP_DEBUG) && defined(MDDS_TREI_MAP_DEBUG_DUMP_TRIE)
    detail::dump_trie<value_type>(root);
#endif

    // Compact the trie into a packed array.
    detail::compact(m_packed, root);
#if defined(MDDS_TRIE_MAP_DEBUG) && defined(MDDS_TREI_MAP_DEBUG_DUMP_PACKED)
    detail::dump_packed_trie<value_type>(m_packed);
#endif
}

#ifdef MDDS_TRIE_MAP_DEBUG

template<typename _ValueT>
void trie_map<_ValueT>::dump() const
{
    if (m_packed.empty())
        return;

    std::string buffer;
    size_t root_offset = m_packed[0];
    const uintptr_t* p = m_packed.data() + root_offset;
    dump_compact_trie_node(buffer, p);
}

template<typename _ValueT>
void trie_map<_ValueT>::dump_compact_trie_node(std::string& buffer, const uintptr_t* p) const
{
    using namespace std;

    const uintptr_t* p0 = p; // store the head offset position of this node.

    const value_type* v = reinterpret_cast<const value_type*>(*p);
    if (v)
        cout << buffer << ":" << *v << endl;

    ++p;
    size_t index_size = *p;
    size_t n = index_size / 2;
    ++p;
    for (size_t i = 0; i < n; ++i)
    {
        char key = *p++;
        size_t offset = *p++;
        buffer.push_back(key);
        const uintptr_t* p_child = p0 - offset;
        dump_compact_trie_node(buffer, p_child);
        buffer.pop_back();
    }
}

#endif

}}

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<commit_msg>Make type entry type more specific.<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*************************************************************************
 *
 * Copyright (c) 2015 Kohei Yoshida
 *
 * Permission is hereby granted, free of charge, to any person
 * obtaining a copy of this software and associated documentation
 * files (the "Software"), to deal in the Software without
 * restriction, including without limitation the rights to use,
 * copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following
 * conditions:
 *
 * The above copyright notice and this permission notice shall be
 * included in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
 * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
 * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
 * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
 * OTHER DEALINGS IN THE SOFTWARE.
 *
 ************************************************************************/

#include "mdds/global.hpp"

#include <cassert>
#include <algorithm>

#ifdef MDDS_TRIE_MAP_DEBUG
#include <iostream>
#endif

namespace mdds { namespace draft {

namespace detail {

struct trie_node
{
    char key;
    const void* value;

    std::deque<trie_node> children;

    trie_node(char _key) : key(_key), value(nullptr) {}
};

#ifdef MDDS_TRIE_MAP_DEBUG

template<typename _ValueT>
void dump_node(std::string& buffer, const trie_node& node)
{
    using namespace std;
    using value_type = _ValueT;

    if (node.value)
    {
        // This node has value.
        cout << buffer << ":" << *static_cast<const value_type*>(node.value) << endl;
    }

    std::for_each(node.children.begin(), node.children.end(),
        [&](const trie_node& node)
        {
            buffer.push_back(node.key);
            dump_node<value_type>(buffer, node);
            buffer.pop_back();
        }
    );
}

template<typename _ValueT>
void dump_trie(const trie_node& root)
{
    std::string buffer;
    dump_node<_ValueT>(buffer, root);
}

template<typename _ValueT>
void dump_packed_trie(const std::vector<uintptr_t>& packed)
{
    using namespace std;

    using value_type = _ValueT;

    cout << "packed size: " << packed.size() << endl;

    size_t n = packed.size();
    size_t i = 0;
    cout << i << ": root node offset: " << packed[i] << endl;
    ++i;

    while (i < n)
    {
        const value_type* value = reinterpret_cast<const value_type*>(packed[i]);
        cout << i << ": node value pointer: " << value;
        if (value)
            cout << ", value: " << *value;
        cout << endl;
        ++i;

        size_t index_size = packed[i];
        cout << i << ": index size: " << index_size << endl;
        ++i;
        index_size /= 2;

        for (size_t j = 0; j < index_size; ++j)
        {
            char key = packed[i];
            cout << i << ": key: " << key << endl;
            ++i;
            size_t offset = packed[i];
            cout << i << ": offset: " << offset << endl;
            ++i;
        }
    }
}

#endif

template<typename _ValueT>
void traverse_range(
    trie_node& root,
    const typename trie_map<_ValueT>::entry* start,
    const typename trie_map<_ValueT>::entry* end,
    size_t pos)
{
    using namespace std;
    using entry = typename trie_map<_ValueT>::entry;

    const entry* p = start;
    const entry* range_start = start;
    const entry* range_end = nullptr;
    char range_char = 0;
    size_t range_count = 0;

    for (; p != end; ++p)
    {
        if (pos > p->keylen)
            continue;

        if (pos == p->keylen)
        {
            root.value = &p->value;
            continue;
        }

        ++range_count;
        char c = p->key[pos];

        if (!range_char)
            range_char = c;
        else if (range_char != c)
        {
            // End of current character range.
            range_end = p;

            root.children.emplace_back(range_char);
            traverse_range<_ValueT>(root.children.back(), range_start, range_end, pos+1);
            range_start = range_end;
            range_char = range_start->key[pos];
            range_end = nullptr;
            range_count = 1;
        }
    }

    if (range_count)
    {
        assert(range_char);
        root.children.emplace_back(range_char);
        traverse_range<_ValueT>(root.children.back(), range_start, end, pos+1);
    }
}

inline size_t compact_node(std::vector<uintptr_t>& packed, const trie_node& node)
{
    std::vector<std::tuple<size_t,char>> child_offsets;
    child_offsets.reserve(node.children.size());

    // Process child nodes first.
    std::for_each(node.children.begin(), node.children.end(),
        [&](const trie_node& node)
        {
            size_t child_offset = compact_node(packed, node);
            child_offsets.emplace_back(child_offset, node.key);
        }
    );

    // Process this node.
    size_t offset = packed.size();
    packed.push_back(uintptr_t(node.value));
    packed.push_back(uintptr_t(child_offsets.size()*2));

    std::for_each(child_offsets.begin(), child_offsets.end(),
        [&](const std::tuple<size_t,char>& v)
        {
            char key = std::get<1>(v);
            size_t child_offset = std::get<0>(v);
            packed.push_back(key);
            packed.push_back(offset-child_offset);
        }
    );

    return offset;
}

inline void compact(std::vector<uintptr_t>& packed, const trie_node& root)
{
    std::vector<uintptr_t> init(size_t(1), uintptr_t(0));
    packed.swap(init);

    size_t root_offset = compact_node(packed, root);
    packed[0] = root_offset;
}

}

template<typename _ValueT>
trie_map<_ValueT>::trie_map(
    const entry* entries, size_type entry_size, value_type null_value) :
    m_null_value(null_value)
{
    const entry* p = entries;
    const entry* p_end = p + entry_size;

    // Populate the normal tree first.
    detail::trie_node root(0);
    detail::traverse_range<value_type>(root, p, p_end, 0);
#if defined(MDDS_TRIE_MAP_DEBUG) && defined(MDDS_TREI_MAP_DEBUG_DUMP_TRIE)
    detail::dump_trie<value_type>(root);
#endif

    // Compact the trie into a packed array.
    detail::compact(m_packed, root);
#if defined(MDDS_TRIE_MAP_DEBUG) && defined(MDDS_TREI_MAP_DEBUG_DUMP_PACKED)
    detail::dump_packed_trie<value_type>(m_packed);
#endif
}

#ifdef MDDS_TRIE_MAP_DEBUG

template<typename _ValueT>
void trie_map<_ValueT>::dump() const
{
    if (m_packed.empty())
        return;

    std::string buffer;
    size_t root_offset = m_packed[0];
    const uintptr_t* p = m_packed.data() + root_offset;
    dump_compact_trie_node(buffer, p);
}

template<typename _ValueT>
void trie_map<_ValueT>::dump_compact_trie_node(std::string& buffer, const uintptr_t* p) const
{
    using namespace std;

    const uintptr_t* p0 = p; // store the head offset position of this node.

    const value_type* v = reinterpret_cast<const value_type*>(*p);
    if (v)
        cout << buffer << ":" << *v << endl;

    ++p;
    size_t index_size = *p;
    size_t n = index_size / 2;
    ++p;
    for (size_t i = 0; i < n; ++i)
    {
        char key = *p++;
        size_t offset = *p++;
        buffer.push_back(key);
        const uintptr_t* p_child = p0 - offset;
        dump_compact_trie_node(buffer, p_child);
        buffer.pop_back();
    }
}

#endif

}}

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<|endoftext|>


<commit_before>#ifndef CRTIICS_NLL_HPP
#define CRTIICS_NLL_HPP

#include "critic.hpp"

namespace nnlib
{

/// \brief Negative log loss critic.
///
/// This critic requires matrix input and single-column matrix output.
template <typename T = double>
class NLL : public Critic<T>
{
public:
	NLL(bool average = true);

	bool average() const;
	NLL &average(bool ave);

	/// A convenience method for counting misclassifications, since we know the output will be categorical.
	size_t misclassifications(const Tensor<T> &input, const Tensor<T> &target);

	/// L = 1/n sum_i( -input(target(i)) )
	virtual T forward(const Tensor<T> &input, const Tensor<T> &target) override;

	/// dL/di = target == i ? -1/n : 0
	virtual Tensor<T> &backward(const Tensor<T> &input, const Tensor<T> &target) override;

protected:
	using Critic<T>::m_inGrad;

private:
	bool m_average;
};

}

#ifdef NN_REAL_T
	extern template class nnlib::NLL<NN_REAL_T>;
#else
	#include "detail/nnl.tpp"
#endif

#endif
<commit_msg>Fixed a typo.<commit_after>#ifndef CRTIICS_NLL_HPP
#define CRTIICS_NLL_HPP

#include "critic.hpp"

namespace nnlib
{

/// \brief Negative log loss critic.
///
/// This critic requires matrix input and single-column matrix output.
template <typename T = double>
class NLL : public Critic<T>
{
public:
	NLL(bool average = true);

	bool average() const;
	NLL &average(bool ave);

	/// A convenience method for counting misclassifications, since we know the output will be categorical.
	size_t misclassifications(const Tensor<T> &input, const Tensor<T> &target);

	/// L = 1/n sum_i( -input(target(i)) )
	virtual T forward(const Tensor<T> &input, const Tensor<T> &target) override;

	/// dL/di = target == i ? -1/n : 0
	virtual Tensor<T> &backward(const Tensor<T> &input, const Tensor<T> &target) override;

protected:
	using Critic<T>::m_inGrad;

private:
	bool m_average;
};

}

#ifdef NN_REAL_T
	extern template class nnlib::NLL<NN_REAL_T>;
#else
	#include "detail/nll.tpp"
#endif

#endif
<|endoftext|>