<commit_before>#include <iostream>
#include <unordered_map>
#include "block.h"
#include "matrix.h"
namespace konstructs {
    Block::Block(const Vector3i position, const BlockData data):
        position(position), data(data) {}

    const std::unordered_map<const Vector3i, const uint8_t, matrix_hash<Vector3i>> vector_to_direction = {
        {Vector3i(0,1,0), DIRECTION_UP},
        {Vector3i(0,-1,0), DIRECTION_DOWN},
        {Vector3i(1,0,0), DIRECTION_RIGHT},
        {Vector3i(-1,0,0), DIRECTION_LEFT},
        {Vector3i(0,0,1), DIRECTION_BACKWARD},
        {Vector3i(0,0,-1), DIRECTION_FORWARD},

        // Edge cases (pointing on an edge or a corner)
        {Vector3i(1,1,0), DIRECTION_RIGHT},
        {Vector3i(1,-1,0), DIRECTION_RIGHT},
        {Vector3i(1,1,1), DIRECTION_RIGHT},
        {Vector3i(1,-1,1), DIRECTION_RIGHT},
        {Vector3i(1,1,-1), DIRECTION_RIGHT},
        {Vector3i(1,-1,-1), DIRECTION_RIGHT},
        {Vector3i(1,0,-1), DIRECTION_RIGHT},
        {Vector3i(1,0,1), DIRECTION_RIGHT},

        {Vector3i(-1,1,0), DIRECTION_LEFT},
        {Vector3i(-1,-1,0), DIRECTION_LEFT},
        {Vector3i(-1,1,1), DIRECTION_LEFT},
        {Vector3i(-1,-1,1), DIRECTION_LEFT},
        {Vector3i(-1,1,-1), DIRECTION_LEFT},
        {Vector3i(-1,-1,-1), DIRECTION_LEFT},
        {Vector3i(-1,0,-1), DIRECTION_LEFT},
        {Vector3i(-1,0,1), DIRECTION_LEFT},

        {Vector3i(0,1,1), DIRECTION_UP},
        {Vector3i(0,1,-1), DIRECTION_UP},

        {Vector3i(0,-1,1), DIRECTION_DOWN},
        {Vector3i(0,-1,-1), DIRECTION_DOWN}
    };

    const uint8_t direction_from_vector(const Vector3i &unit_vector) {
        return vector_to_direction.at(unit_vector);
    }

    const uint8_t direction_from_vector(const Vector3i &from, const Vector3i &to) {
        return direction_from_vector(from - to);
    }

    const uint8_t rotation_from_vector(const uint8_t direction, const Vector3f &vector) {
        switch(direction) {
        case DIRECTION_UP:
            if(fabs(vector(0)) > fabs(vector(2))) {
                if(vector(0) > 0) {
                    return ROTATION_RIGHT;
                } else {
                    return ROTATION_LEFT;
                }
            } else {
                if(vector(2) > 0) {
                    return ROTATION_IDENTITY;
                } else {
                    return ROTATION_HALF;
                }
            }
        case DIRECTION_DOWN:
            if(fabs(vector(0)) > fabs(vector(2))) {
                if(vector(0) <= 0) {
                    return ROTATION_RIGHT;
                } else {
                    return ROTATION_LEFT;
                }
            } else {
                if(vector(2) <= 0) {
                    return ROTATION_IDENTITY;
                } else {
                    return ROTATION_HALF;
                }
            }
        case DIRECTION_LEFT:
            if(fabs(vector(1)) > fabs(vector(2))) {
                if(vector(1) > 0) {
                    return ROTATION_RIGHT;
                } else {
                    return ROTATION_LEFT;
                }

            } else {
                if(vector(2) > 0) {
                    return ROTATION_IDENTITY;
                } else {
                    return ROTATION_HALF;
                }
            }
        case DIRECTION_RIGHT:
            if(fabs(vector(1)) > fabs(vector(2))) {
                if(vector(1) <= 0) {
                    return ROTATION_RIGHT;
                } else {
                    return ROTATION_LEFT;
                }
            } else {
                if(vector(2) <= 0) {
                    return ROTATION_HALF;
                } else {
                    return ROTATION_IDENTITY;
                }
            }
        case DIRECTION_FORWARD:
            if(fabs(vector(0)) > fabs(vector(1))) {
                if(vector(0) > 0) {
                    return ROTATION_RIGHT;
                } else {
                    return ROTATION_LEFT;
                }
            } else {
                if(vector(1) > 0) {
                    return ROTATION_IDENTITY;
                } else {
                    return ROTATION_HALF;
                }
            }
        case DIRECTION_BACKWARD:
            if(fabs(vector(0)) > fabs(vector(1))) {
                if(vector(0) <= 0) {
                    return ROTATION_RIGHT;
                } else {
                    return ROTATION_LEFT;
                }
            } else {
                if(vector(1) <= 0) {
                    return ROTATION_IDENTITY;
                } else {
                    return ROTATION_HALF;
                }
            }
        }
    }
};
<commit_msg>Flip left and right when upside down<commit_after>#include <iostream>
#include <unordered_map>
#include "block.h"
#include "matrix.h"
namespace konstructs {
    Block::Block(const Vector3i position, const BlockData data):
        position(position), data(data) {}

    const std::unordered_map<const Vector3i, const uint8_t, matrix_hash<Vector3i>> vector_to_direction = {
        {Vector3i(0,1,0), DIRECTION_UP},
        {Vector3i(0,-1,0), DIRECTION_DOWN},
        {Vector3i(1,0,0), DIRECTION_RIGHT},
        {Vector3i(-1,0,0), DIRECTION_LEFT},
        {Vector3i(0,0,1), DIRECTION_BACKWARD},
        {Vector3i(0,0,-1), DIRECTION_FORWARD},

        // Edge cases (pointing on an edge or a corner)
        {Vector3i(1,1,0), DIRECTION_RIGHT},
        {Vector3i(1,-1,0), DIRECTION_RIGHT},
        {Vector3i(1,1,1), DIRECTION_RIGHT},
        {Vector3i(1,-1,1), DIRECTION_RIGHT},
        {Vector3i(1,1,-1), DIRECTION_RIGHT},
        {Vector3i(1,-1,-1), DIRECTION_RIGHT},
        {Vector3i(1,0,-1), DIRECTION_RIGHT},
        {Vector3i(1,0,1), DIRECTION_RIGHT},

        {Vector3i(-1,1,0), DIRECTION_LEFT},
        {Vector3i(-1,-1,0), DIRECTION_LEFT},
        {Vector3i(-1,1,1), DIRECTION_LEFT},
        {Vector3i(-1,-1,1), DIRECTION_LEFT},
        {Vector3i(-1,1,-1), DIRECTION_LEFT},
        {Vector3i(-1,-1,-1), DIRECTION_LEFT},
        {Vector3i(-1,0,-1), DIRECTION_LEFT},
        {Vector3i(-1,0,1), DIRECTION_LEFT},

        {Vector3i(0,1,1), DIRECTION_UP},
        {Vector3i(0,1,-1), DIRECTION_UP},

        {Vector3i(0,-1,1), DIRECTION_DOWN},
        {Vector3i(0,-1,-1), DIRECTION_DOWN}
    };

    const uint8_t direction_from_vector(const Vector3i &unit_vector) {
        return vector_to_direction.at(unit_vector);
    }

    const uint8_t direction_from_vector(const Vector3i &from, const Vector3i &to) {
        return direction_from_vector(from - to);
    }

    const uint8_t rotation_from_vector(const uint8_t direction, const Vector3f &vector) {
        switch(direction) {
        case DIRECTION_UP:
            if(fabs(vector(0)) > fabs(vector(2))) {
                if(vector(0) > 0) {
                    return ROTATION_RIGHT;
                } else {
                    return ROTATION_LEFT;
                }
            } else {
                if(vector(2) > 0) {
                    return ROTATION_IDENTITY;
                } else {
                    return ROTATION_HALF;
                }
            }
        case DIRECTION_DOWN:
            if(fabs(vector(0)) > fabs(vector(2))) {
                if(vector(0) <= 0) {
                    return ROTATION_LEFT;
                } else {
                    return ROTATION_RIGHT;
                }
            } else {
                if(vector(2) <= 0) {
                    return ROTATION_HALF;
                } else {
                    return ROTATION_IDENTITY;
                }
            }
        case DIRECTION_LEFT:
            if(fabs(vector(1)) > fabs(vector(2))) {
                if(vector(1) > 0) {
                    return ROTATION_RIGHT;
                } else {
                    return ROTATION_LEFT;
                }

            } else {
                if(vector(2) > 0) {
                    return ROTATION_IDENTITY;
                } else {
                    return ROTATION_HALF;
                }
            }
        case DIRECTION_RIGHT:
            if(fabs(vector(1)) > fabs(vector(2))) {
                if(vector(1) <= 0) {
                    return ROTATION_RIGHT;
                } else {
                    return ROTATION_LEFT;
                }
            } else {
                if(vector(2) <= 0) {
                    return ROTATION_HALF;
                } else {
                    return ROTATION_IDENTITY;
                }
            }
        case DIRECTION_FORWARD:
            if(fabs(vector(0)) > fabs(vector(1))) {
                if(vector(0) > 0) {
                    return ROTATION_RIGHT;
                } else {
                    return ROTATION_LEFT;
                }
            } else {
                if(vector(1) > 0) {
                    return ROTATION_IDENTITY;
                } else {
                    return ROTATION_HALF;
                }
            }
        case DIRECTION_BACKWARD:
            if(fabs(vector(0)) > fabs(vector(1))) {
                if(vector(0) <= 0) {
                    return ROTATION_RIGHT;
                } else {
                    return ROTATION_LEFT;
                }
            } else {
                if(vector(1) <= 0) {
                    return ROTATION_IDENTITY;
                } else {
                    return ROTATION_HALF;
                }
            }
        }
    }
};
<|endoftext|>


<commit_before>/*
  This file is part of KOrganizer.

  Requires the Qt and KDE widget libraries, available at no cost at
  http://www.troll.no and http://www.kde.org respectively

  Copyright (c) 2003
  Reinhold Kainhofer <reinhold@kainhofer.com>

  This program is free software; you can redistribute it and/or modify
  it under the terms of the GNU General Public License as published by
  the Free Software Foundation; either version 2 of the License, or
  (at your option) any later version.

  This program is distributed in the hope that it will be useful,
  but WITHOUT ANY WARRANTY; without even the implied warranty of
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  GNU General Public License for more details.

  You should have received a copy of the GNU General Public License
  along with this program; if not, write to the Free Software
  Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
*/

#include <libkcal/incidence.h>
#include <libkcal/event.h>
#include <libkcal/todo.h>
#include <libkcal/journal.h>

#include <klocale.h>
#include "koincidencetooltip.h"

/**
@author Reinhold Kainhofer
some improvements by Mikolaj Machowski
*/

void KOIncidenceToolTip::add ( QWidget * widget, Incidence *incidence,
        QToolTipGroup * group, const QString & longText )
{
  if ( !widget || !incidence ) return;
  QString tipText;
  ToolTipVisitor v;
  v.act( incidence, &tipText, true );
  QToolTip::add(widget, tipText, group, longText);
}

QString ToolTipVisitor::dateRangeText( Event*event )
{
  QString ret;
  QString tmp;
  if ( event->isMultiDay() ) {

    tmp = "
" + i18n("Event start", "From: %1");
    if (event->doesFloat())
      ret += tmp.arg( event->dtStartDateStr().replace(" ", " ") );
    else
      ret += tmp.arg( event->dtStartStr().replace(" ", " ") );

    tmp = "
" + i18n("To: %1");
    if (event->doesFloat())
      ret += tmp.arg( event->dtEndDateStr().replace(" ", " ") );
    else
      ret += tmp.arg( event->dtEndStr().replace(" ", " ") );

  } else {

    ret += "
"+i18n("Date: %1").
        arg( event->dtStartDateStr().replace(" ", " ") );
    if ( !event->doesFloat() ) {
      // Hmm. Remove space here and add   for not breaking Time:
      // line. Note crucial lack of space after : . But even if
      // translators don't notice it is much better than a line break
      // between start and end time.
      tmp = "
" + i18n("time range for event,   to prevent ugly line breaks",
        "Time: %1 - %2").
        arg( event->dtStartTimeStr().replace(" ", " ") ).
        arg( event->dtEndTimeStr().replace(" ", " ") );
    }

  }
  return ret;
}

QString ToolTipVisitor::dateRangeText( Todo*todo )
{
  QString ret;
  bool floats( todo->doesFloat() );
  if (todo->hasStartDate())
    // No need to add  here. This is separated issue and each line
    // is very visible on its own. On the other hand... Yes, I like it
    // italics here :)
    ret += "
" + i18n("Start: %1").arg(
      (floats)
        ?(todo->dtStartDateStr().replace(" ", " "))
        :(todo->dtStartStr().replace(" ", " ")) ) ;
  if (todo->hasDueDate())
    ret += "
" + i18n("Due: %1").arg(
      (floats)
        ?(todo->dtDueDateStr().replace(" ", " "))
        :(todo->dtDueStr().replace(" ", " ")) );
  if (todo->isCompleted())
    ret += "
" + i18n("Completed: %1").arg( todo->completedStr().replace(" ", " ") );
  else
    ret += "
" + i18n("%1 % completed").arg(todo->percentComplete());

  return ret;
}

QString ToolTipVisitor::dateRangeText( Journal* )
{
  QString ret;
  return ret;
}

bool ToolTipVisitor::visit( Event *event )
{
  QString dtRangeText( dateRangeText( event ) );
  return generateToolTip( event, dtRangeText  );
}

bool ToolTipVisitor::visit( Todo *todo )
{
  QString dtRangeText( dateRangeText( todo ) );
  return generateToolTip( todo, dtRangeText  );
}

bool ToolTipVisitor::visit( Journal *journal )
{
  QString dtRangeText( dateRangeText( journal ) );
  return generateToolTip( journal, dtRangeText  );
}

bool ToolTipVisitor::generateToolTip( Incidence* incidence, QString dtRangeText )
{
  QString tipText = "<qt>"+ incidence->summary().replace("\n", "
")+"";

  tipText += dtRangeText;

  if (!incidence->location().isEmpty()) {
    // Put Location: in italics
    tipText += "
"+i18n("Location: %1").
      arg( incidence->location().replace("\n", "
") );
  }
  if (!incidence->description().isEmpty()) {
    QString desc(incidence->description());
    if (desc.length()>120) {
      desc = desc.left(120) + "...";
    }
    tipText += "

" + desc.replace("\n", "
");
  }
  tipText += "</qt>";
  *mTipText = tipText;
  return true;
}
<commit_msg>Generated the string displaying the times, but forgot to append it to the output :-(( Thanks to Martin Koller for telling me.<commit_after>/*
  This file is part of KOrganizer.

  Requires the Qt and KDE widget libraries, available at no cost at
  http://www.troll.no and http://www.kde.org respectively

  Copyright (c) 2003
  Reinhold Kainhofer <reinhold@kainhofer.com>

  This program is free software; you can redistribute it and/or modify
  it under the terms of the GNU General Public License as published by
  the Free Software Foundation; either version 2 of the License, or
  (at your option) any later version.

  This program is distributed in the hope that it will be useful,
  but WITHOUT ANY WARRANTY; without even the implied warranty of
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  GNU General Public License for more details.

  You should have received a copy of the GNU General Public License
  along with this program; if not, write to the Free Software
  Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
*/

#include <libkcal/incidence.h>
#include <libkcal/event.h>
#include <libkcal/todo.h>
#include <libkcal/journal.h>

#include <klocale.h>
#include "koincidencetooltip.h"

/**
@author Reinhold Kainhofer
some improvements by Mikolaj Machowski
*/

void KOIncidenceToolTip::add ( QWidget * widget, Incidence *incidence,
        QToolTipGroup * group, const QString & longText )
{
  if ( !widget || !incidence ) return;
  QString tipText;
  ToolTipVisitor v;
  v.act( incidence, &tipText, true );
  QToolTip::add(widget, tipText, group, longText);
}

QString ToolTipVisitor::dateRangeText( Event*event )
{
  QString ret;
  QString tmp;
  if ( event->isMultiDay() ) {

    tmp = "
" + i18n("Event start", "From: %1");
    if (event->doesFloat())
      ret += tmp.arg( event->dtStartDateStr().replace(" ", " ") );
    else
      ret += tmp.arg( event->dtStartStr().replace(" ", " ") );

    tmp = "
" + i18n("To: %1");
    if (event->doesFloat())
      ret += tmp.arg( event->dtEndDateStr().replace(" ", " ") );
    else
      ret += tmp.arg( event->dtEndStr().replace(" ", " ") );

  } else {

    ret += "
"+i18n("Date: %1").
        arg( event->dtStartDateStr().replace(" ", " ") );
    if ( !event->doesFloat() ) {
      tmp = "
" + i18n("time range for event,   to prevent ugly line breaks",
        "Time: %1 - %2").
        arg( event->dtStartTimeStr().replace(" ", " ") ).
        arg( event->dtEndTimeStr().replace(" ", " ") );
      ret += tmp;
    }

  }
  return ret;
}

QString ToolTipVisitor::dateRangeText( Todo*todo )
{
  QString ret;
  bool floats( todo->doesFloat() );
  if (todo->hasStartDate())
    // No need to add  here. This is separated issue and each line
    // is very visible on its own. On the other hand... Yes, I like it
    // italics here :)
    ret += "
" + i18n("Start: %1").arg(
      (floats)
        ?(todo->dtStartDateStr().replace(" ", " "))
        :(todo->dtStartStr().replace(" ", " ")) ) ;
  if (todo->hasDueDate())
    ret += "
" + i18n("Due: %1").arg(
      (floats)
        ?(todo->dtDueDateStr().replace(" ", " "))
        :(todo->dtDueStr().replace(" ", " ")) );
  if (todo->isCompleted())
    ret += "
" + i18n("Completed: %1").arg( todo->completedStr().replace(" ", " ") );
  else
    ret += "
" + i18n("%1 % completed").arg(todo->percentComplete());

  return ret;
}

QString ToolTipVisitor::dateRangeText( Journal* )
{
  QString ret;
  return ret;
}

bool ToolTipVisitor::visit( Event *event )
{
  QString dtRangeText( dateRangeText( event ) );
  return generateToolTip( event, dtRangeText  );
}

bool ToolTipVisitor::visit( Todo *todo )
{
  QString dtRangeText( dateRangeText( todo ) );
  return generateToolTip( todo, dtRangeText  );
}

bool ToolTipVisitor::visit( Journal *journal )
{
  QString dtRangeText( dateRangeText( journal ) );
  return generateToolTip( journal, dtRangeText  );
}

bool ToolTipVisitor::generateToolTip( Incidence* incidence, QString dtRangeText )
{
  QString tipText = "<qt>"+ incidence->summary().replace("\n", "
")+"";

  tipText += dtRangeText;

  if (!incidence->location().isEmpty()) {
    // Put Location: in italics
    tipText += "
"+i18n("Location: %1").
      arg( incidence->location().replace("\n", "
") );
  }
  if (!incidence->description().isEmpty()) {
    QString desc(incidence->description());
    if (desc.length()>120) {
      desc = desc.left(120) + "...";
    }
    tipText += "

" + desc.replace("\n", "
");
  }
  tipText += "</qt>";
  *mTipText = tipText;
  return true;
}
<|endoftext|>


<commit_before>#include <string.h>
#include <assert.h>
#include "reader.h"

using namespace hiredis;

static void *tryParentize(const redisReadTask *task, const Local<Value> &v) {
    Nan::HandleScope scope;

    Reader *r = reinterpret_cast<Reader*>(task->privdata);
    size_t pidx, vidx;

    if (task->parent != NULL) {
        pidx = (size_t)task->parent->obj;
        assert(pidx > 0 && pidx < 9);

        /* When there is a parent, it should be an array. */
        Local<Value> lvalue = Nan::New(r->handle[pidx]);
        assert(lvalue->IsArray());
        Local<Array> larray = lvalue.As<Array>();
        larray->Set(task->idx,v);

        /* Store the handle when this is an inner array. Otherwise, hiredis
         * doesn't care about the return value as long as the value is set in
         * its parent array. */
        vidx = pidx+1;
        if (v->IsArray()) {
            r->handle[vidx].Reset(v);
            return (void*)vidx;
        } else {
            /* Return value doesn't matter for inner value, as long as it is
             * not NULL (which means OOM for hiredis). */
            return (void*)0xcafef00d;
        }
    } else {
        /* There is no parent, so this value is the root object. */
        r->handle[1].Reset(v);
        return (void*)1;
    }
}

static void *createArray(const redisReadTask *task, int size) {
    Nan::HandleScope scope;

    return tryParentize(task, Nan::New<Array>(size));
}

static void *createString(const redisReadTask *task, char *str, size_t len) {
    Nan::HandleScope scope;

    Reader *r = reinterpret_cast<Reader*>(task->privdata);
    Local<Value> v(r->createString(str,len));

    if (task->type == REDIS_REPLY_ERROR)
        v = Exception::Error(v.As<String>());
    return tryParentize(task,v);
}

static void *createInteger(const redisReadTask *task, long long value) {
    Nan::HandleScope scope;
    return tryParentize(task, Nan::New<Number>(value));
}

static void *createNil(const redisReadTask *task) {
    Nan::HandleScope scope;
    return tryParentize(task, Nan::Null());
}

static redisReplyObjectFunctions v8ReplyFunctions = {
    createString,
    createArray,
    createInteger,
    createNil,
    0 /* No free function: cleanup is done in Reader::Get. */
};

Reader::Reader(bool return_buffers) :
    return_buffers(return_buffers)
{
    Nan::HandleScope scope;

    reader = redisReaderCreateWithFunctions(&v8ReplyFunctions);
    reader->privdata = this;

#if _USE_CUSTOM_BUFFER_POOL
    if (return_buffers) {
        Local<Object> global = Context::GetCurrent()->Global();
        Local<Value> bv = global->Get(String::NewSymbol("Buffer"));
        assert(bv->IsFunction());
        Local<Function> bf = Local<Function>::Cast(bv);
        buffer_fn = Persistent<Function>::New(bf);

        buffer_pool_length = 8*1024; /* Same as node */
        buffer_pool_offset = 0;

        node::Buffer *b = node::Buffer::New(buffer_pool_length);
        buffer_pool = Persistent<Object>::New(b->handle_);
    }
#endif
}

Reader::~Reader() {
    redisReaderFree(reader);
}

/* Don't declare an extra scope here, so the objects are created within the
 * scope inherited from the caller (Reader::Get) and we don't have to the pay
 * the overhead. */
inline Local<Value> Reader::createString(char *str, size_t len) {
    if (return_buffers) {
#if _USE_CUSTOM_BUFFER_POOL
        if (len > buffer_pool_length) {
            node::Buffer *b = node::Buffer::New(str,len);
            return Local<Value>::New(b->handle_);
        } else {
            return createBufferFromPool(str,len);
        }
#else
        return Nan::CopyBuffer(str,len).ToLocalChecked();
#endif
    } else {
        return Nan::New<String>(str,len).ToLocalChecked();
    }
}

#if _USE_CUSTOM_BUFFER_POOL
Local<Value> Reader::createBufferFromPool(char *str, size_t len) {
    HandleScope scope;
    Local<Value> argv[3];
    Local<Object> instance;

    assert(len <= buffer_pool_length);
    if (buffer_pool_length - buffer_pool_offset < len) {
        node::Buffer *b = node::Buffer::New(buffer_pool_length);
        buffer_pool.Dispose();
        buffer_pool = Persistent<Object>::New(b->handle_);
        buffer_pool_offset = 0;
    }

    memcpy(node::Buffer::Data(buffer_pool)+buffer_pool_offset,str,len);

    argv[0] = Local<Value>::New(buffer_pool);
    argv[1] = Integer::New(len);
    argv[2] = Integer::New(buffer_pool_offset);
    instance = buffer_fn->NewInstance(3,argv);
    buffer_pool_offset += len;
    return scope.Close(instance);
}
#endif

NAN_METHOD(Reader::New) {
    bool return_buffers = false;

    if (info.Length() > 0 && info[0]->IsObject()) {
        Local<Value> bv = Nan::Get(info[0].As<Object>(), Nan::New("return_buffers").ToLocalChecked()).ToLocalChecked();
        if (bv->IsBoolean())
            return_buffers = Nan::To<bool>(bv).FromJust();
    }

    Reader *r = new Reader(return_buffers);
    r->Wrap(info.This());
    info.GetReturnValue().Set(info.This());
}

NAN_MODULE_INIT(Reader::Initialize) {
    Nan::HandleScope scope;

    Local<FunctionTemplate> t = Nan::New<FunctionTemplate>(New);

    t->InstanceTemplate()->SetInternalFieldCount(1);
    Nan::SetPrototypeMethod(t, "feed", Feed);
    Nan::SetPrototypeMethod(t, "get", Get);
    Nan::Set(target, Nan::New("Reader").ToLocalChecked(), Nan::GetFunction(t).ToLocalChecked());
}

NAN_METHOD(Reader::Feed) {
    Reader *r = Nan::ObjectWrap::Unwrap<Reader>(info.This());

    if (info.Length() == 0) {
        Nan::ThrowTypeError("First argument must be a string or buffer");
    } else {
        if (node::Buffer::HasInstance(info[0])) {
            Local<Object> buffer_object = info[0].As<Object>();
            char *data;
            size_t length;

            data = node::Buffer::Data(buffer_object);
            length = node::Buffer::Length(buffer_object);

            /* Can't handle OOM for now. */
            assert(redisReaderFeed(r->reader, data, length) == REDIS_OK);
        } else if (info[0]->IsString()) {
            Nan::Utf8String str(info[0].As<String>());
            redisReplyReaderFeed(r->reader, *str, str.length());
        } else {
            Nan::ThrowError("Invalid argument");
        }
    }

    info.GetReturnValue().Set(info.This());
}

NAN_METHOD(Reader::Get) {
    Reader *r = Nan::ObjectWrap::Unwrap<Reader>(info.This());
    void *index = NULL;
    Local<Value> reply;
    int i;

    if (redisReaderGetReply(r->reader,&index) == REDIS_OK) {
        if (index == 0) {
            return;
        } else {
            /* Complete replies should always have a root object at index 1. */
            assert((size_t)index == 1);
            reply = Nan::New(r->handle[1]);

            /* Dispose and clear used handles. */
            for (i = 1; i < 3; i++) {
                r->handle[i].Reset();
            }
        }
    } else {
        Nan::ThrowError(r->reader->errstr);
    }

    info.GetReturnValue().Set(reply);
}
<commit_msg>Do not cast a potentially non-String value to String, use ToString() instead.<commit_after>#include <string.h>
#include <assert.h>
#include "reader.h"

using namespace hiredis;

static void *tryParentize(const redisReadTask *task, const Local<Value> &v) {
    Nan::HandleScope scope;

    Reader *r = reinterpret_cast<Reader*>(task->privdata);
    size_t pidx, vidx;

    if (task->parent != NULL) {
        pidx = (size_t)task->parent->obj;
        assert(pidx > 0 && pidx < 9);

        /* When there is a parent, it should be an array. */
        Local<Value> lvalue = Nan::New(r->handle[pidx]);
        assert(lvalue->IsArray());
        Local<Array> larray = lvalue.As<Array>();
        larray->Set(task->idx,v);

        /* Store the handle when this is an inner array. Otherwise, hiredis
         * doesn't care about the return value as long as the value is set in
         * its parent array. */
        vidx = pidx+1;
        if (v->IsArray()) {
            r->handle[vidx].Reset(v);
            return (void*)vidx;
        } else {
            /* Return value doesn't matter for inner value, as long as it is
             * not NULL (which means OOM for hiredis). */
            return (void*)0xcafef00d;
        }
    } else {
        /* There is no parent, so this value is the root object. */
        r->handle[1].Reset(v);
        return (void*)1;
    }
}

static void *createArray(const redisReadTask *task, int size) {
    Nan::HandleScope scope;

    return tryParentize(task, Nan::New<Array>(size));
}

static void *createString(const redisReadTask *task, char *str, size_t len) {
    Nan::HandleScope scope;

    Reader *r = reinterpret_cast<Reader*>(task->privdata);
    Local<Value> v(r->createString(str,len));

    if (task->type == REDIS_REPLY_ERROR)
        v = Exception::Error(v->ToString());
    return tryParentize(task,v);
}

static void *createInteger(const redisReadTask *task, long long value) {
    Nan::HandleScope scope;
    return tryParentize(task, Nan::New<Number>(value));
}

static void *createNil(const redisReadTask *task) {
    Nan::HandleScope scope;
    return tryParentize(task, Nan::Null());
}

static redisReplyObjectFunctions v8ReplyFunctions = {
    createString,
    createArray,
    createInteger,
    createNil,
    0 /* No free function: cleanup is done in Reader::Get. */
};

Reader::Reader(bool return_buffers) :
    return_buffers(return_buffers)
{
    Nan::HandleScope scope;

    reader = redisReaderCreateWithFunctions(&v8ReplyFunctions);
    reader->privdata = this;

#if _USE_CUSTOM_BUFFER_POOL
    if (return_buffers) {
        Local<Object> global = Context::GetCurrent()->Global();
        Local<Value> bv = global->Get(String::NewSymbol("Buffer"));
        assert(bv->IsFunction());
        Local<Function> bf = Local<Function>::Cast(bv);
        buffer_fn = Persistent<Function>::New(bf);

        buffer_pool_length = 8*1024; /* Same as node */
        buffer_pool_offset = 0;

        node::Buffer *b = node::Buffer::New(buffer_pool_length);
        buffer_pool = Persistent<Object>::New(b->handle_);
    }
#endif
}

Reader::~Reader() {
    redisReaderFree(reader);
}

/* Don't declare an extra scope here, so the objects are created within the
 * scope inherited from the caller (Reader::Get) and we don't have to the pay
 * the overhead. */
inline Local<Value> Reader::createString(char *str, size_t len) {
    if (return_buffers) {
#if _USE_CUSTOM_BUFFER_POOL
        if (len > buffer_pool_length) {
            node::Buffer *b = node::Buffer::New(str,len);
            return Local<Value>::New(b->handle_);
        } else {
            return createBufferFromPool(str,len);
        }
#else
        return Nan::CopyBuffer(str,len).ToLocalChecked();
#endif
    } else {
        return Nan::New<String>(str,len).ToLocalChecked();
    }
}

#if _USE_CUSTOM_BUFFER_POOL
Local<Value> Reader::createBufferFromPool(char *str, size_t len) {
    HandleScope scope;
    Local<Value> argv[3];
    Local<Object> instance;

    assert(len <= buffer_pool_length);
    if (buffer_pool_length - buffer_pool_offset < len) {
        node::Buffer *b = node::Buffer::New(buffer_pool_length);
        buffer_pool.Dispose();
        buffer_pool = Persistent<Object>::New(b->handle_);
        buffer_pool_offset = 0;
    }

    memcpy(node::Buffer::Data(buffer_pool)+buffer_pool_offset,str,len);

    argv[0] = Local<Value>::New(buffer_pool);
    argv[1] = Integer::New(len);
    argv[2] = Integer::New(buffer_pool_offset);
    instance = buffer_fn->NewInstance(3,argv);
    buffer_pool_offset += len;
    return scope.Close(instance);
}
#endif

NAN_METHOD(Reader::New) {
    bool return_buffers = false;

    if (info.Length() > 0 && info[0]->IsObject()) {
        Local<Value> bv = Nan::Get(info[0].As<Object>(), Nan::New("return_buffers").ToLocalChecked()).ToLocalChecked();
        if (bv->IsBoolean())
            return_buffers = Nan::To<bool>(bv).FromJust();
    }

    Reader *r = new Reader(return_buffers);
    r->Wrap(info.This());
    info.GetReturnValue().Set(info.This());
}

NAN_MODULE_INIT(Reader::Initialize) {
    Nan::HandleScope scope;

    Local<FunctionTemplate> t = Nan::New<FunctionTemplate>(New);

    t->InstanceTemplate()->SetInternalFieldCount(1);
    Nan::SetPrototypeMethod(t, "feed", Feed);
    Nan::SetPrototypeMethod(t, "get", Get);
    Nan::Set(target, Nan::New("Reader").ToLocalChecked(), Nan::GetFunction(t).ToLocalChecked());
}

NAN_METHOD(Reader::Feed) {
    Reader *r = Nan::ObjectWrap::Unwrap<Reader>(info.This());

    if (info.Length() == 0) {
        Nan::ThrowTypeError("First argument must be a string or buffer");
    } else {
        if (node::Buffer::HasInstance(info[0])) {
            Local<Object> buffer_object = info[0].As<Object>();
            char *data;
            size_t length;

            data = node::Buffer::Data(buffer_object);
            length = node::Buffer::Length(buffer_object);

            /* Can't handle OOM for now. */
            assert(redisReaderFeed(r->reader, data, length) == REDIS_OK);
        } else if (info[0]->IsString()) {
            Nan::Utf8String str(info[0].As<String>());
            redisReplyReaderFeed(r->reader, *str, str.length());
        } else {
            Nan::ThrowError("Invalid argument");
        }
    }

    info.GetReturnValue().Set(info.This());
}

NAN_METHOD(Reader::Get) {
    Reader *r = Nan::ObjectWrap::Unwrap<Reader>(info.This());
    void *index = NULL;
    Local<Value> reply;
    int i;

    if (redisReaderGetReply(r->reader,&index) == REDIS_OK) {
        if (index == 0) {
            return;
        } else {
            /* Complete replies should always have a root object at index 1. */
            assert((size_t)index == 1);
            reply = Nan::New(r->handle[1]);

            /* Dispose and clear used handles. */
            for (i = 1; i < 3; i++) {
                r->handle[i].Reset();
            }
        }
    } else {
        Nan::ThrowError(r->reader->errstr);
    }

    info.GetReturnValue().Set(reply);
}
<|endoftext|>


<commit_before>/* pattern.cc
 *
 * Copyright (C) 2002 The gtkmm Development Team
 *
 * 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, see <http://www.gnu.org/licenses/>.
 */

#include <glib.h>
#include <glibmm/pattern.h>

namespace Glib
{

PatternSpec::PatternSpec(const Glib::ustring& pattern)
: gobject_(g_pattern_spec_new(pattern.c_str()))
{
}

PatternSpec::PatternSpec(GPatternSpec* gobject) : gobject_(gobject)
{
}

PatternSpec::~PatternSpec() noexcept
{
  g_pattern_spec_free(gobject_);
}

bool
PatternSpec::match(const Glib::ustring& str) const
{
  return g_pattern_match(gobject_, str.bytes(), str.c_str(), nullptr);
}

bool
PatternSpec::match(const Glib::ustring& str, const Glib::ustring& str_reversed) const
{
  return g_pattern_match(gobject_, str.bytes(), str.c_str(), str_reversed.c_str());
}

bool
PatternSpec::operator==(const PatternSpec& rhs) const
{
  return g_pattern_spec_equal(gobject_, rhs.gobject_);
}

bool
PatternSpec::operator!=(const PatternSpec& rhs) const
{
  return !g_pattern_spec_equal(gobject_, rhs.gobject_);
}

} // namespace Glib
<commit_msg>Glib::PatternSpec: Ignore deprecation of g_pattern_match()<commit_after>/* pattern.cc
 *
 * Copyright (C) 2002 The gtkmm Development Team
 *
 * 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, see <http://www.gnu.org/licenses/>.
 */

#include <glib.h>
#include <glibmm/pattern.h>

namespace Glib
{

PatternSpec::PatternSpec(const Glib::ustring& pattern)
: gobject_(g_pattern_spec_new(pattern.c_str()))
{
}

PatternSpec::PatternSpec(GPatternSpec* gobject) : gobject_(gobject)
{
}

PatternSpec::~PatternSpec() noexcept
{
  g_pattern_spec_free(gobject_);
}

// g_pattern_match() is deprecated in glib 2.70.
// Its replacement, g_pattern_spec_match(), is new in glib 2.70.
G_GNUC_BEGIN_IGNORE_DEPRECATIONS
bool
PatternSpec::match(const Glib::ustring& str) const
{
  return g_pattern_match(gobject_, str.bytes(), str.c_str(), nullptr);
}

bool
PatternSpec::match(const Glib::ustring& str, const Glib::ustring& str_reversed) const
{
  return g_pattern_match(gobject_, str.bytes(), str.c_str(), str_reversed.c_str());
}
G_GNUC_END_IGNORE_DEPRECATIONS

bool
PatternSpec::operator==(const PatternSpec& rhs) const
{
  return g_pattern_spec_equal(gobject_, rhs.gobject_);
}

bool
PatternSpec::operator!=(const PatternSpec& rhs) const
{
  return !g_pattern_spec_equal(gobject_, rhs.gobject_);
}

} // namespace Glib
<|endoftext|>


<commit_before>/*
 * Copyright 2015 Aldebaran
 *
 * 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.
 *
*/

#ifndef CONVERTER_HPP
#define CONVERTER_HPP

#include <string>

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

#include <ros/ros.h>
#include <alrosbridge/message_actions.h>
#include <alrosbridge/tools.hpp>

namespace alros
{
namespace converter
{

/**
* @brief Converter concept interface
* @note this defines an private concept struct,
* which each instance has to implement
* @note a type erasure pattern in implemented here to avoid strict inheritance,
* thus each possible converter instance has to implement the virtual functions mentioned in the concept
*/
class Converter
{

public:

  /**
  * @brief Constructor for converter interface
  */
  template<typename T>
  Converter( T conv ):
    convPtr_( boost::make_shared<ConverterModel<T> >(conv) )
  {}

  /**
  * @brief getting the descriptive name for this converter instance
  * @return string with the name
  */
  std::string name() const
  {
    return convPtr_->name();
  }

  /**
  * @brief getting the assigned frequency of this converter instance
  * @return float value indicating the frequency
  */
  float frequency() const
  {
    return convPtr_->frequency();
  }

  Robot robot() const
  {
    return convPtr_->robot();
  }

  void reset()
  {
    convPtr_->reset();
  }

  void callAll( const std::vector<message_actions::MessageAction>& actions )
  {
    convPtr_->callAll(actions);
  }

  friend bool operator==( const Converter& lhs, const Converter& rhs )
  {
    // decision made for OR-comparison since we want to be more restrictive
    if ( lhs.name() == rhs.name() )
      return true;
    return false;
  }

private:

  /**
  * BASE concept struct
  */
  struct ConverterConcept
  {
    virtual ~ConverterConcept(){}
    virtual std::string name() const = 0;
    virtual float frequency() const = 0;
    virtual Robot robot() const = 0;
    virtual void reset() = 0;
    virtual void callAll( const std::vector<message_actions::MessageAction>& actions ) = 0;
  };

  /**
  * templated instances of base concept
  */
  template<typename T>
  struct ConverterModel : public ConverterConcept
  {
    ConverterModel( const T& other ):
      converter_( other )
    {}

    std::string name() const
    {
      return converter_->name();
    }

    float frequency() const
    {
      return converter_->frequency();
    }

    Robot robot() const
    {
      return converter_->robot();
    }

    void reset()
    {
      converter_->reset();
    }

    void callAll( const std::vector<message_actions::MessageAction>& actions )
    {
      converter_->callAll( actions );
    }

    T converter_;
  };

  boost::shared_ptr<ConverterConcept> convPtr_;

}; // class converter

} //converter
} //alros

#endif
<commit_msg>introduce time lapse measure<commit_after>/*
 * Copyright 2015 Aldebaran
 *
 * 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.
 *
*/

#ifndef CONVERTER_HPP
#define CONVERTER_HPP

#include <string>

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

#include <ros/ros.h>
#include <alrosbridge/message_actions.h>
#include <alrosbridge/tools.hpp>

namespace alros
{
namespace converter
{

/**
* @brief Converter concept interface
* @note this defines an private concept struct,
* which each instance has to implement
* @note a type erasure pattern in implemented here to avoid strict inheritance,
* thus each possible converter instance has to implement the virtual functions mentioned in the concept
*/
class Converter
{

public:

  /**
  * @brief Constructor for converter interface
  */
  template<typename T>
  Converter( T conv ):
    convPtr_( boost::make_shared<ConverterModel<T> >(conv) )
  {}

  /**
  * @brief getting the descriptive name for this converter instance
  * @return string with the name
  */
  std::string name() const
  {
    return convPtr_->name();
  }

  /**
  * @brief getting the assigned frequency of this converter instance
  * @return float value indicating the frequency
  */
  float frequency() const
  {
    return convPtr_->frequency();
  }

  Robot robot() const
  {
    return convPtr_->robot();
  }

  void reset()
  {
    convPtr_->reset();
  }

  void callAll( const std::vector<message_actions::MessageAction>& actions )
  {
    if ( actions.size() > 0 )
    {
      convPtr_->callAll(actions);
    }

    ros::Time after = ros::Time::now();
    lapse_time = after - before;
    before = after;
  }

  ros::Duration lapseTime() const
  {
    return lapse_time;
  }

  friend bool operator==( const Converter& lhs, const Converter& rhs )
  {
    // decision made for OR-comparison since we want to be more restrictive
    if ( lhs.name() == rhs.name() )
      return true;
    return false;
  }

private:

  ros::Time before;
  ros::Duration lapse_time;

  /**
  * BASE concept struct
  */
  struct ConverterConcept
  {
    virtual ~ConverterConcept(){}
    virtual std::string name() const = 0;
    virtual float frequency() const = 0;
    virtual Robot robot() const = 0;
    virtual void reset() = 0;
    virtual void callAll( const std::vector<message_actions::MessageAction>& actions ) = 0;
  };

  /**
  * templated instances of base concept
  */
  template<typename T>
  struct ConverterModel : public ConverterConcept
  {
    ConverterModel( const T& other ):
      converter_( other )
    {}

    std::string name() const
    {
      return converter_->name();
    }

    float frequency() const
    {
      return converter_->frequency();
    }

    Robot robot() const
    {
      return converter_->robot();
    }

    void reset()
    {
      converter_->reset();
    }

    void callAll( const std::vector<message_actions::MessageAction>& actions )
    {
      converter_->callAll( actions );
    }

    T converter_;
  };

  boost::shared_ptr<ConverterConcept> convPtr_;

}; // class converter

} //converter
} //alros

#endif
<|endoftext|>


<commit_before>// OpenCV
#include <opencv2/opencv.hpp>

// Boost includes
#include <boost/program_options.hpp>

// General C++ includes
#include <iostream>
#include <string>
#include <vector>
#include <map>
#include <cmath>
#include <sstream>
#include <thread>
#include <mutex>

// Defines
#define SCALE 0.4

// namespaces
using namespace std;
using namespace cv;
namespace po = boost::program_options;

// global variables
mutex mtx;

void disp_progress(float progress, int bar_width)
{
  cout << "[";
  int pos = bar_width * progress;
  for ( int i = 0; i < bar_width; ++i )
  {
    if ( i < pos )
    {
      cout << "=";
    }
    else if ( i == pos )
    {
      cout << ">";
    }
    else
    {
      cout << " ";
    }
  }
  cout << "] " << int(progress * 100.0) << "%\r" ;
  cout.flush();
}

void split_img( int split_num, int x, int y, int num_x, int num_y, int time_split, string fn, string out_dir ) {
  mtx.lock();
  cout << "worker " << x << "-" << y << "-" << split_num << " running." << endl;
  mtx.unlock();
  VideoCapture capture(fn);
  int max_frames = capture.get(CV_CAP_PROP_FRAME_COUNT);

  int rect_width = (int) capture.get(CV_CAP_PROP_FRAME_WIDTH)/num_x;
  int rect_height = (int) capture.get(CV_CAP_PROP_FRAME_HEIGHT)/num_y;

  int start_frame = split_num * (max_frames / time_split);

  capture.set(CV_CAP_PROP_POS_FRAMES, start_frame);
  Size sz = Size(rect_width, rect_height);

  stringstream out_key;
  out_key << y << "-" << x << "-" << split_num;
  VideoWriter writer;
  string out_fn = out_dir + "/" + out_key.str() + ".avi";
  writer.open(out_fn, CV_FOURCC('m','p','4','v'), capture.get(CV_CAP_PROP_FPS), sz, true);

  Mat src;
  Rect rect = Rect( x*rect_width, y*rect_height, rect_width, rect_height );

  int k = 0;
  while ( k < (max_frames / time_split)-1 )
  {
    capture >> src;
    if ( src.data == NULL )
      break;

    writer << Mat(src, rect);

    int percent = int(100 * ((float)k/(max_frames/time_split)));
    if ( percent % 5 == 0 )
    {
      mtx.lock();
      cout << "worker " << x << "-" << y << "-" << split_num << ": " << percent << "%" << endl;
      mtx.unlock();
    }
    k++;
  }
}

int main( int argc, char **argv ) {
  string fn, out_dir;
  int num_x, num_y, time_split, kthreads;
  try
  {
    po::options_description desc("Options");
    desc.add_options()
      ("help,h", "Print help messages")
      ("footage,f", po::value<string>(&fn)->required(), "footage file")
      ("numx,x", po::value<int>(&num_x)->required(), "number of x splits")
      ("numy,y", po::value<int>(&num_y)->required(), "number of y splits")
      ("timesplit,t", po::value<int>(&time_split)->default_value(1), "number of time splits")
      ("output,o", po::value<string>(&out_dir)->default_value("."), "output directory")
      ("threads,s", po::value<int>(&kthreads)->default_value(4), "number of threads");

    po::positional_options_description positionalOptions;
    positionalOptions.add("footage", 1);
    positionalOptions.add("numx", 1);
    positionalOptions.add("numy", 1);

    po::variables_map vm;

    // Parse command line arguments
    try
    {
      po::store(po::command_line_parser(argc, argv).options(desc).positional(positionalOptions).run(), vm);

      if ( vm.count( "help" ) )
      {
        cout << "This is the video splitting software for the gopro camera. " << endl << endl;
        cout << "Usage: " << argv[0] << " [options] <footage> <numx> <numy>" << endl  << endl << desc << endl;

        return 0;
      }

      po::notify(vm);
    }
    catch ( po::error& e )
    {
      cerr << "ERROR: " << e.what() << endl << endl;
      cerr << desc << endl;
      return 1;
    }

    vector <thread> workers;
    int kspawned = 0;
    for ( int time_num = 0; time_num < time_split; ++time_num )
    {
      for ( int ny = 0; ny < num_y; ++ny )
      {
        for ( int nx = 0; nx < num_x; ++nx )
        {
          if ( kspawned > 0 && kspawned % kthreads == 0 )
          {
            workers.back().join();
            workers.pop_back();
          }
          workers.push_back(thread(split_img, time_num, nx, ny, num_x, num_y, time_split, fn, out_dir));
          kspawned++;
        }
      }
    }

    while ( workers.size() > 0 )
    {
      workers.back().join();
      workers.pop_back();
    }
    cout << endl;
    return 0;
  }
  catch ( exception& e )
  {
    cerr << "Unhandled Exception reached the top of main: " << e.what() << ", application will now exit." << endl;
    return 2;
  }
  return 0;
}
<commit_msg>split_vid.cpp updated<commit_after>// OpenCV
#include <opencv2/opencv.hpp>

// Boost includes
#include <boost/program_options.hpp>

// General C++ includes
#include <iostream>
#include <string>
#include <vector>
#include <map>
#include <cmath>
#include <sstream>
#include <thread>
#include <mutex>

// Defines
#define SCALE 0.4

// namespaces
using namespace std;
using namespace cv;
namespace po = boost::program_options;

// global variables
mutex mtx;

void disp_progress(float progress, int bar_width)
{
  cout << "[";
  int pos = bar_width * progress;
  for ( int i = 0; i < bar_width; ++i )
  {
    if ( i < pos )
    {
      cout << "=";
    }
    else if ( i == pos )
    {
      cout << ">";
    }
    else
    {
      cout << " ";
    }
  }
  cout << "] " << int(progress * 100.0) << "%\r" ;
  cout.flush();
}

void split_img( int split_num, int x, int y, int num_x, int num_y, int time_split, string fn, string out_dir, int overlap) {
  mtx.lock();
  cout << "worker " << x << "-" << y << "-" << split_num << " running." << endl;
  mtx.unlock();
  VideoCapture capture(fn);
  int max_frames = capture.get(CV_CAP_PROP_FRAME_COUNT);

  int rect_width = (int) capture.get(CV_CAP_PROP_FRAME_WIDTH)/num_x;
  int rect_height = (int) capture.get(CV_CAP_PROP_FRAME_HEIGHT)/num_y;

  int start_frame = split_num * (max_frames / time_split);

  capture.set(CV_CAP_PROP_POS_FRAMES, start_frame);

  int this_x = x*rect_width;
  int this_y = y*rect_height;
  int this_width = rect_width;
  int this_height = rect_height;

  //Determine whether to add overlap to the quadrant.
  if (x > 0){
    this_x -= overlap;
    this_width += overlap;
  }
  if (y > 0) {
    this_y -= overlap;
    this_height += overlap;
  }
  if (x != num_x-1) {
    this_width += overlap;
  }
  if (y != num_y-1) {
    this_height += overlap;
  }

  Size sz = Size(this_width, this_height);

  stringstream out_key;
  out_key << y << "-" << x << "-" << split_num;
  VideoWriter writer;
  string out_fn = out_dir + "/" + out_key.str() + ".avi";
  writer.open(out_fn, CV_FOURCC('m','p','4','v'), capture.get(CV_CAP_PROP_FPS), sz, true);

  Mat src;
  Rect rect = Rect( this_x, this_y, this_width, this_height );

  int k = 0;
  while ( k < (max_frames / time_split)-1 )
  {
    capture >> src;
    if ( src.data == NULL )
      break;

    writer << Mat(src, rect);

    int percent = int(100 * ((float)k/(max_frames/time_split)));
    if ( percent % 5 == 0 )
    {
      mtx.lock();
      cout << "worker " << x << "-" << y << "-" << split_num << ": " << percent << "%" << endl;
      mtx.unlock();
    }
    k++;
  }
}

int main( int argc, char **argv ) {
  string fn, out_dir;
  int num_x, num_y, time_split, kthreads, overlap;
  try
  {
    po::options_description desc("Options");
    desc.add_options()
      ("help,h", "Print help messages")
      ("footage,f", po::value<string>(&fn)->required(), "footage file")
      ("numx,x", po::value<int>(&num_x)->required(), "number of x splits")
      ("numy,y", po::value<int>(&num_y)->required(), "number of y splits")
      ("timesplit,t", po::value<int>(&time_split)->default_value(1), "number of time splits")
      ("output,o", po::value<string>(&out_dir)->default_value("."), "output directory")
      ("threads,s", po::value<int>(&kthreads)->default_value(4), "number of threads")
      ("overlap,l", po::value<int>(&overlap)->default_value(0), "number of pixels to overlap spatially between splits");

    po::positional_options_description positionalOptions;
    positionalOptions.add("footage", 1);
    positionalOptions.add("numx", 1);
    positionalOptions.add("numy", 1);

    po::variables_map vm;

    // Parse command line arguments
    try
    {
      po::store(po::command_line_parser(argc, argv).options(desc).positional(positionalOptions).run(), vm);

      if ( vm.count( "help" ) )
      {
        cout << "This is the video splitting software for the gopro camera. " << endl << endl;
        cout << "Usage: " << argv[0] << " [options] <footage> <numx> <numy>" << endl  << endl << desc << endl;

        return 0;
      }

      po::notify(vm);
    }
    catch ( po::error& e )
    {
      cerr << "ERROR: " << e.what() << endl << endl;
      cerr << desc << endl;
      return 1;
    }

    vector <thread> workers;
    int kspawned = 0;
    for ( int time_num = 0; time_num < time_split; ++time_num )
    {
      for ( int ny = 0; ny < num_y; ++ny )
      {
        for ( int nx = 0; nx < num_x; ++nx )
        {
          if ( kspawned > 0 && kspawned % kthreads == 0 )
          {
            workers.back().join();
            workers.pop_back();
          }
          workers.push_back(thread(split_img, time_num, nx, ny, num_x, num_y, time_split, fn, out_dir, overlap));
          kspawned++;
        }
      }
    }

    while ( workers.size() > 0 )
    {
      workers.back().join();
      workers.pop_back();
    }
    cout << endl;
    return 0;
  }
  catch ( exception& e )
  {
    cerr << "Unhandled Exception reached the top of main: " << e.what() << ", application will now exit." << endl;
    return 2;
  }
  return 0;
}
<|endoftext|>


<commit_before>// -*- Mode: C++; tab-width: 2; -*-
// vi: set ts=2:
//
// $Id: version.C,v 1.9 2002/02/27 12:20:34 sturm Exp $

#include <BALL/COMMON/version.h>
#include <BALL/DATATYPE/string.h>

namespace BALL
{
	const char* VersionInfo::getVersion() throw()
	{
		return BALL_RELEASE_STRING " ("__DATE__", " __TIME__ ")";
	}

	int VersionInfo::getMinorRevision() throw(Exception::InvalidFormat)
	{
		static String release(BALL_RELEASE_STRING);
		String minor = release.getField(1, ".");
		minor.trimRight(String::CHARACTER_CLASS__ASCII_ALPHA);

		return minor.toInt();
	}

	int VersionInfo::getMajorRevision() throw(Exception::InvalidFormat)
	{
		static String release(BALL_RELEASE_STRING);
		return release.getField(0, ". ").toInt();
	}

	VersionInfo::Type VersionInfo::getType() throw()
	{
		static String release(BALL_RELEASE_STRING);

		// check for the suffix of the release string
		// a = alpha, b = beta, n = nonpublic, no letter = stable
		if (release.size() == 0)
		{
			return UNKNOWN;
		}
		char release_suffix = release[release.size() - 1];
		switch (release_suffix)
		{
			case 'a':
				return ALPHA;

			case 'b':
				return BETA;

			case 'n':
				return NONPUBLIC;

			case '0':
			case '1':
			case '2':
			case '3':
			case '4':
			case '5':
			case '6':
			case '7':
			case '8':
			case '9':
				return STABLE;

			default:
				return UNKNOWN;
		}
	}

	const char* VersionInfo::RELEASE_DATE_AND_TIME = "@(#)BALL kernel compiled on: " __DATE__ ", " __TIME__;
	const char* VersionInfo::RELEASE_WHAT_STRING = "@(#)BALL kernel version: V." BALL_RELEASE_STRING;

}
<commit_msg>changed policy: use "alpha" instead of a, etc.<commit_after>// -*- Mode: C++; tab-width: 2; -*-
// vi: set ts=2:
//
// $Id: version.C,v 1.10 2002/12/20 17:21:36 anker Exp $

#include <BALL/COMMON/version.h>
#include <BALL/DATATYPE/string.h>
#include <BALL/DATATYPE/stringHashMap.h>

namespace BALL
{
	const char* VersionInfo::getVersion() throw()
	{
		return BALL_RELEASE_STRING " ("__DATE__", " __TIME__ ")";
	}

	int VersionInfo::getMinorRevision() throw(Exception::InvalidFormat)
	{
		static String release(BALL_RELEASE_STRING);
		String minor = release.getField(1, ".");
		String tmp = minor;
		tmp.trimRight(String::CHARACTER_CLASS__ASCII_NUMERIC);
		if (tmp.size() > 0)
		{
			minor.trimRight(String::CHARACTER_CLASS__ASCII_NUMERIC);
		}
		minor.trimRight(String::CHARACTER_CLASS__ASCII_ALPHA);

		return minor.toInt();
	}

	int VersionInfo::getMajorRevision() throw(Exception::InvalidFormat)
	{
		static String release(BALL_RELEASE_STRING);
		return release.getField(0, ". ").toInt();
	}

	VersionInfo::Type VersionInfo::getType() throw()
	{
		StringHashMap<VersionInfo::Type> type_mapper;
		type_mapper.insert(pair<String, VersionInfo::Type>("alpha", ALPHA));
		type_mapper.insert(pair<String, VersionInfo::Type>("beta", BETA));
		type_mapper.insert(pair<String, VersionInfo::Type>("nonpublic", NONPUBLIC));
		type_mapper.insert(pair<String, VersionInfo::Type>("pre", PRERELEASE));
		type_mapper.insert(pair<String, VersionInfo::Type>("patch", PATCHLEVEL));

		static String release(BALL_RELEASE_STRING);

		// check for the suffix of the release string
		// a = alpha, b = beta, n = nonpublic, no letter = stable
		if (release.size() == 0)
		{
			return UNKNOWN;
		}

		String minor = release.getField(1, ".");
		String tmp = minor;
		tmp.trimRight(String::CHARACTER_CLASS__ASCII_NUMERIC);
		if (tmp.size() > 0)
		{
			return STABLE;
		}

		String type = minor.trimRight(String::CHARACTER_CLASS__ASCII_ALPHA);
		if (type_mapper.has(type))
		{
			return(type_mapper[type]);
		}
		else
		{
			return(UNKNOWN);
		}
	}

	const char* VersionInfo::RELEASE_DATE_AND_TIME = "@(#)BALL kernel compiled on: " __DATE__ ", " __TIME__;
	const char* VersionInfo::RELEASE_WHAT_STRING = "@(#)BALL kernel version: V." BALL_RELEASE_STRING;

}
<|endoftext|>


<commit_before>/*
    This file is part of kdepim.

    Copyright (c) 2004 Cornelius Schumacher <schumacher@kde.org>

    This program is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation; either version 2 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program; if not, write to the Free Software
    Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
*/

#include "webdavhandler.h"

#include <values.h>

#include <libkdepim/kpimprefs.h>

#include <kdebug.h>
#include <kconfig.h>

#include <qfile.h>

SloxItem::SloxItem()
  : status( Invalid )
{
}

WebdavHandler::WebdavHandler()
  : mLogCount( 0 )
{
  KConfig cfg( "sloxrc" );

  cfg.setGroup( "General" );
  mLogFile = cfg.readEntry( "LogFile" );

  kdDebug() << "LOG FILE: " << mLogFile << endl;
}

void WebdavHandler::log( const QString &text )
{
  if ( mLogFile.isEmpty() ) return;

  QString filename = mLogFile + "-" + QString::number( mLogCount );
  QFile file( filename );
  if ( !file.open( IO_WriteOnly ) ) {
    kdWarning() << "Unable to open log file '" << filename << "'" << endl;
    return;
  }

  QCString textUtf8 = text.utf8();
  file.writeBlock( textUtf8.data(), textUtf8.size() - 1 );

  if ( ++mLogCount > 5 ) mLogCount = 0;
}

QValueList<SloxItem> WebdavHandler::getSloxItems( const QDomDocument &doc )
{
  kdDebug() << "getSloxItems" << endl;

  QValueList<SloxItem> items;

  QDomElement docElement = doc.documentElement();

  QDomNode responseNode;
  for( responseNode = docElement.firstChild(); !responseNode.isNull();
       responseNode = responseNode.nextSibling() ) {
    QDomElement responseElement = responseNode.toElement();
    if ( responseElement.tagName() == "response" ) {
      QDomNode propstat = responseElement.namedItem( "propstat" );
      if ( propstat.isNull() ) {
        kdError() << "Unable to find propstat tag." << endl;
        continue;
      }

      QDomNode prop = propstat.namedItem( "prop" );
      if ( prop.isNull() ) {
        kdError() << "Unable to find WebDAV property" << endl;
        continue;
      }

      QDomNode sloxIdNode = prop.namedItem( "sloxid" );
      if ( sloxIdNode.isNull() ) {
        kdError() << "Unable to find SLOX id." << endl;
        continue;
      }
      QDomElement sloxIdElement = sloxIdNode.toElement();
      QString sloxId = sloxIdElement.text();

      QDomNode sloxStatus = prop.namedItem( "sloxstatus" );
      if ( sloxStatus.isNull() ) {
        kdError() << "Unable to find SLOX status." << endl;
        continue;
      }

      SloxItem item;
      item.sloxId = sloxId;
      item.domNode = prop;

      QDomElement sloxStatusElement = sloxStatus.toElement();
      if ( sloxStatusElement.text() == "DELETE" ) {
        item.status = SloxItem::Delete;
      } else if ( sloxStatusElement.text() == "CREATE" ) {
        item.status = SloxItem::Create;
      }

      items.append( item );
    }
  }

  return items;
}

QString WebdavHandler::qDateTimeToSlox( const QDateTime &dt )
{
  uint ticks = -dt.secsTo( QDateTime( QDate( 1970, 1, 1 ), QTime( 0, 0 ) ) );

  return QString::number( ticks ) + "000";
}

QString WebdavHandler::qDateTimeToSlox( const QDateTime &dt,
                                        const QString &timeZoneId )
{
  QDateTime utc = KPimPrefs::localTimeToUtc( dt, timeZoneId );

  uint ticks = -utc.secsTo( QDateTime( QDate( 1970, 1, 1 ), QTime( 0, 0 ) ) );

  return QString::number( ticks ) + "000";
}

QDateTime WebdavHandler::sloxToQDateTime( const QString &str )
{
  QString s = str.mid( 0, str.length() - 3 );

  bool preEpoch = s.startsWith("-");
  if (preEpoch)
     s = s.mid(1);

  unsigned long ticks = s.toULong();

  QDateTime dt;

  if (preEpoch) {
    dt.setTime_t( 0, Qt::UTC );
    if (ticks > MAXINT) {
      dt = dt.addSecs(-MAXINT);
      ticks -= MAXINT;
    }
    dt = dt.addSecs(-((long) ticks));
  }
  else
  {
    dt.setTime_t( ticks, Qt::UTC );
  }

  return dt;
}

QDateTime WebdavHandler::sloxToQDateTime( const QString &str,
                                          const QString &timeZoneId )
{
  return KPimPrefs::utcToLocalTime( sloxToQDateTime(str), timeZoneId );
}

QDomElement WebdavHandler::addElement( QDomDocument &doc, QDomNode &node,
                                       const QString &tag )
{
  QDomElement el = doc.createElement( tag );
  node.appendChild( el );
  return el;
}

QDomElement WebdavHandler::addDavElement( QDomDocument &doc, QDomNode &node,
                                          const QString &tag )
{
  QDomElement el = doc.createElementNS( "DAV", tag );
  node.appendChild( el );
  return el;
}

QDomElement WebdavHandler::addSloxElement( QDomDocument &doc, QDomNode &node,
                                           const QString &tag,
                                           const QString &text )
{
  QDomElement el = doc.createElementNS( "SLOX", tag );
  if ( !text.isEmpty() ) {
    QDomText textnode = doc.createTextNode( text );
    el.appendChild( textnode );
  }
  node.appendChild( el );
  return el;
}
<commit_msg>Backport Ade's FreeBSD build fixes from HEAD<commit_after>/*
    This file is part of kdepim.

    Copyright (c) 2004 Cornelius Schumacher <schumacher@kde.org>

    This program is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation; either version 2 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program; if not, write to the Free Software
    Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
*/

#include "webdavhandler.h"

#ifdef HAVE_VALUES_H
#include <values.h>
#else
#ifdef HAVE_SYS_LIMITS_H
#include <sys/limits.h>
#endif
#endif

#include <libkdepim/kpimprefs.h>

#include <kdebug.h>
#include <kconfig.h>

#include <qfile.h>

SloxItem::SloxItem()
  : status( Invalid )
{
}

WebdavHandler::WebdavHandler()
  : mLogCount( 0 )
{
  KConfig cfg( "sloxrc" );

  cfg.setGroup( "General" );
  mLogFile = cfg.readEntry( "LogFile" );

  kdDebug() << "LOG FILE: " << mLogFile << endl;
}

void WebdavHandler::log( const QString &text )
{
  if ( mLogFile.isEmpty() ) return;

  QString filename = mLogFile + "-" + QString::number( mLogCount );
  QFile file( filename );
  if ( !file.open( IO_WriteOnly ) ) {
    kdWarning() << "Unable to open log file '" << filename << "'" << endl;
    return;
  }

  QCString textUtf8 = text.utf8();
  file.writeBlock( textUtf8.data(), textUtf8.size() - 1 );

  if ( ++mLogCount > 5 ) mLogCount = 0;
}

QValueList<SloxItem> WebdavHandler::getSloxItems( const QDomDocument &doc )
{
  kdDebug() << "getSloxItems" << endl;

  QValueList<SloxItem> items;

  QDomElement docElement = doc.documentElement();

  QDomNode responseNode;
  for( responseNode = docElement.firstChild(); !responseNode.isNull();
       responseNode = responseNode.nextSibling() ) {
    QDomElement responseElement = responseNode.toElement();
    if ( responseElement.tagName() == "response" ) {
      QDomNode propstat = responseElement.namedItem( "propstat" );
      if ( propstat.isNull() ) {
        kdError() << "Unable to find propstat tag." << endl;
        continue;
      }

      QDomNode prop = propstat.namedItem( "prop" );
      if ( prop.isNull() ) {
        kdError() << "Unable to find WebDAV property" << endl;
        continue;
      }

      QDomNode sloxIdNode = prop.namedItem( "sloxid" );
      if ( sloxIdNode.isNull() ) {
        kdError() << "Unable to find SLOX id." << endl;
        continue;
      }
      QDomElement sloxIdElement = sloxIdNode.toElement();
      QString sloxId = sloxIdElement.text();

      QDomNode sloxStatus = prop.namedItem( "sloxstatus" );
      if ( sloxStatus.isNull() ) {
        kdError() << "Unable to find SLOX status." << endl;
        continue;
      }

      SloxItem item;
      item.sloxId = sloxId;
      item.domNode = prop;

      QDomElement sloxStatusElement = sloxStatus.toElement();
      if ( sloxStatusElement.text() == "DELETE" ) {
        item.status = SloxItem::Delete;
      } else if ( sloxStatusElement.text() == "CREATE" ) {
        item.status = SloxItem::Create;
      }

      items.append( item );
    }
  }

  return items;
}

QString WebdavHandler::qDateTimeToSlox( const QDateTime &dt )
{
  uint ticks = -dt.secsTo( QDateTime( QDate( 1970, 1, 1 ), QTime( 0, 0 ) ) );

  return QString::number( ticks ) + "000";
}

QString WebdavHandler::qDateTimeToSlox( const QDateTime &dt,
                                        const QString &timeZoneId )
{
  QDateTime utc = KPimPrefs::localTimeToUtc( dt, timeZoneId );

  uint ticks = -utc.secsTo( QDateTime( QDate( 1970, 1, 1 ), QTime( 0, 0 ) ) );

  return QString::number( ticks ) + "000";
}

QDateTime WebdavHandler::sloxToQDateTime( const QString &str )
{
  QString s = str.mid( 0, str.length() - 3 );

  bool preEpoch = s.startsWith("-");
  if (preEpoch)
     s = s.mid(1);

  unsigned long ticks = s.toULong();

  QDateTime dt;

  if (preEpoch) {
    dt.setTime_t( 0, Qt::UTC );
    if (ticks > INT_MAX) {
      dt = dt.addSecs(-INT_MAX);
      ticks -= INT_MAX;
    }
    dt = dt.addSecs(-((long) ticks));
  }
  else
  {
    dt.setTime_t( ticks, Qt::UTC );
  }

  return dt;
}

QDateTime WebdavHandler::sloxToQDateTime( const QString &str,
                                          const QString &timeZoneId )
{
  return KPimPrefs::utcToLocalTime( sloxToQDateTime(str), timeZoneId );
}

QDomElement WebdavHandler::addElement( QDomDocument &doc, QDomNode &node,
                                       const QString &tag )
{
  QDomElement el = doc.createElement( tag );
  node.appendChild( el );
  return el;
}

QDomElement WebdavHandler::addDavElement( QDomDocument &doc, QDomNode &node,
                                          const QString &tag )
{
  QDomElement el = doc.createElementNS( "DAV", tag );
  node.appendChild( el );
  return el;
}

QDomElement WebdavHandler::addSloxElement( QDomDocument &doc, QDomNode &node,
                                           const QString &tag,
                                           const QString &text )
{
  QDomElement el = doc.createElementNS( "SLOX", tag );
  if ( !text.isEmpty() ) {
    QDomText textnode = doc.createTextNode( text );
    el.appendChild( textnode );
  }
  node.appendChild( el );
  return el;
}
<|endoftext|>


<commit_before>/* IBM_PROLOG_BEGIN_TAG                                                   */
/* This is an automatically generated prolog.                             */
/*                                                                        */
/* $Source: src/import/chips/p9/procedures/hwp/perv/p9_ram_getreg.H $     */
/*                                                                        */
/* OpenPOWER HostBoot Project                                             */
/*                                                                        */
/* Contributors Listed Below - COPYRIGHT 2016,2019                        */
/* [+] International Business Machines Corp.                              */
/*                                                                        */
/*                                                                        */
/* 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.                         */
/*                                                                        */
/* IBM_PROLOG_END_TAG                                                     */
//-----------------------------------------------------------------------------------
///
/// @file p9_ram_getreg.H
/// @brief Utility to implement Get Register by ramming
///
//-----------------------------------------------------------------------------------
// *HWP HWP Owner        : Liu Yang Fan <shliuyf@cn.ibm.com>
// *HWP HWP Backup Owner : Gou Peng Fei <shgoupf@cn.ibm.com>
// *HWP FW Owner         : Thi Tran <thi@us.ibm.com>
// *HWP Team             : Perv
// *HWP Level            : 2
// *HWP Consumed by      : None (Cronus test only)
//-----------------------------------------------------------------------------------

#ifndef _P9_RAM_GETREG_H_
#define _P9_RAM_GETREG_H_

//-----------------------------------------------------------------------------------
// Includes
//-----------------------------------------------------------------------------------
#include <fapi2.H>
#include <p9_ram_core.H>

//function pointer typedef definition for HWP call support
typedef fapi2::ReturnCode (*p9_ram_getreg_FP_t) (const fapi2::Target<fapi2::TARGET_TYPE_CORE>& i_target,
        const uint8_t i_thread,
        const Enum_RegType i_type,
        const uint32_t i_reg_num,
        fapi2::buffer<uint64_t>* o_buffer);

extern "C" {
//-----------------------------------------------------------------------------------
// Function prototype
//-----------------------------------------------------------------------------------
// @brief Implement Get Register(GPR/FPR/VSR) by ramming
/// @param[in] i_target   => core target
/// @param[in] i_thread   => thread number
/// @param[in] i_type     => register access type (REG_GPR/REG_FPR/REG_VSR)
/// @param[in] i_reg_num  => register number
/// @param[out] o_buffer   => register value
/// @return FAPI_RC_SUCCESS if the setup completes successfully
//
    fapi2::ReturnCode p9_ram_getreg(const fapi2::Target<fapi2::TARGET_TYPE_CORE>& i_target,
                                    const uint8_t i_thread,
                                    const Enum_RegType i_type,
                                    const uint32_t i_reg_num,
                                    fapi2::buffer<uint64_t>* o_buffer);

} //extern"C"

#endif //_P9_RAM_GETREG_H_
<commit_msg>Update RAM procedures.<commit_after>/* IBM_PROLOG_BEGIN_TAG                                                   */
/* This is an automatically generated prolog.                             */
/*                                                                        */
/* $Source: src/import/chips/p9/procedures/hwp/perv/p9_ram_getreg.H $     */
/*                                                                        */
/* OpenPOWER HostBoot Project                                             */
/*                                                                        */
/* Contributors Listed Below - COPYRIGHT 2016,2019                        */
/* [+] International Business Machines Corp.                              */
/*                                                                        */
/*                                                                        */
/* 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.                         */
/*                                                                        */
/* IBM_PROLOG_END_TAG                                                     */
//-----------------------------------------------------------------------------------
///
/// @file p9_ram_getreg.H
/// @brief Utility to implement Get Register by ramming
///
//-----------------------------------------------------------------------------------
// *HWP HWP Owner        : Liu Yang Fan <shliuyf@cn.ibm.com>
// *HWP HWP Backup Owner : Gou Peng Fei <shgoupf@cn.ibm.com>
// *HWP FW Owner         : Thi Tran <thi@us.ibm.com>
// *HWP Team             : Perv
// *HWP Level            : 2
// *HWP Consumed by      : None (Cronus test only)
//-----------------------------------------------------------------------------------

#ifndef _P9_RAM_GETREG_H_
#define _P9_RAM_GETREG_H_

//-----------------------------------------------------------------------------------
// Includes
//-----------------------------------------------------------------------------------
#include <fapi2.H>
#include <p9_ram_core.H>

//function pointer typedef definition for HWP call support
typedef fapi2::ReturnCode (*p9_ram_getreg_FP_t) (const fapi2::Target<fapi2::TARGET_TYPE_CORE>& i_target,
        const uint8_t i_thread,
        const Enum_RegType i_type,
        const uint32_t i_reg_num,
        fapi2::buffer<uint64_t>* o_buffer);

extern "C" {
//-----------------------------------------------------------------------------------
// Function prototype
//-----------------------------------------------------------------------------------
// @brief Implement Get Register(GPR/FPR/VSR) by ramming
/// @param[in] i_target     => core target
/// @param[in] i_thread     => thread number
/// @param[in] i_type       => register access type (REG_GPR/REG_FPR/REG_VSR)
/// @param[in] i_reg_num    => register number
/// @param[out] o_buffer    => register value
/// @return FAPI_RC_SUCCESS if the setup completes successfully
//
    fapi2::ReturnCode p9_ram_getreg(const fapi2::Target<fapi2::TARGET_TYPE_CORE>& i_target,
                                    const uint8_t i_thread,
                                    const Enum_RegType i_type,
                                    const uint32_t i_reg_num,
                                    fapi2::buffer<uint64_t>* o_buffer);

} //extern"C"

#endif //_P9_RAM_GETREG_H_
<|endoftext|>


<commit_before><commit_msg>Planning: added back scenario debug info in open_space planer<commit_after><|endoftext|>


<commit_before>/* GNE - Game Networking Engine, a portable multithreaded networking library.
 * Copyright (C) 2001 Jason Winnebeck (gillius@mail.rit.edu)
 * Project website: http://www.rit.edu/~jpw9607/
 *
 * 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., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */

#include "gneintern.h"
#include "Address.h"
#include <ostream>

std::ostream& operator << (std::ostream& o, const GNE::Address& addr) {
	return o << addr.toString();
}

namespace GNE {

//##ModelId=3BB974B402E4
Address::Address(std::string address) {
	setAddressByName(address);
}

//##ModelId=3BB94B190168
Address::Address(const char* address) {
	setAddressByName(address);
}

Address::Address(NLaddress address) : addr(address) {
}

//##ModelId=3BB9282B0334
Address::~Address() {
}

//##ModelId=3BB974B40384
void Address::setAddressByName(std::string address) {
	nlGetAddrFromName((NLbyte*)address.c_str(), &addr);
}

//##ModelId=3BBA41220208
std::string Address::getNameByAddress() const {
	char buf[NL_MAX_STRING_LENGTH];
	nlGetNameFromAddr(&const_cast<Address*>(this)->addr, (NLbyte*)buf);
	return std::string(buf);
}

//##ModelId=3BB9282B0336
NLaddress Address::getAddress() const {
	return addr;
}

//##ModelId=3BB9282B0371
void Address::setAddress(NLaddress address) {
	addr = address;
}

//The totally lame const_casts are due to HawkNL's lack of const-correctness.
//##ModelId=3BB92893038E
std::string Address::toString() const {
	if (isValid()) {
		char buf[NL_MAX_STRING_LENGTH];
		nlAddrToString(&const_cast<Address*>(this)->addr, (NLbyte*)buf);
		return std::string(buf);
	} else
		return "invalid address";
}

//##ModelId=3BB94B1901D6
int Address::getPort() const {
	return (int)nlGetPortFromAddr(&const_cast<Address*>(this)->addr);
}

//##ModelId=3BB932340050
void Address::setPort(int port) {
	if (port < 0 || port > 65535)
		addr.valid = NL_FALSE;
	else
		nlSetAddrPort(&const_cast<Address*>(this)->addr, (NLushort)port);
}

//##ModelId=3BB934B4015E
bool Address::isValid() const {
	return (addr.valid == NL_TRUE);
}

//##ModelId=3BB934C5010E
Address::operator bool() const {
	return isValid();
}

//##ModelId=3BB934CC00BE
bool Address::operator ==(const Address& rhs) const {
	return (nlAddrCompare(&const_cast<Address*>(this)->addr, &const_cast<Address&>(rhs).addr) == NL_TRUE);
}

} //namespace GNE<commit_msg>gcc doesn't like "ostream"<commit_after>/* GNE - Game Networking Engine, a portable multithreaded networking library.
 * Copyright (C) 2001 Jason Winnebeck (gillius@mail.rit.edu)
 * Project website: http://www.rit.edu/~jpw9607/
 *
 * 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., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */

#include "gneintern.h"
#include "Address.h"
#include <iostream>

std::ostream& operator << (std::ostream& o, const GNE::Address& addr) {
	return o << addr.toString();
}

namespace GNE {

//##ModelId=3BB974B402E4
Address::Address(std::string address) {
	setAddressByName(address);
}

//##ModelId=3BB94B190168
Address::Address(const char* address) {
	setAddressByName(address);
}

Address::Address(NLaddress address) : addr(address) {
}

//##ModelId=3BB9282B0334
Address::~Address() {
}

//##ModelId=3BB974B40384
void Address::setAddressByName(std::string address) {
	nlGetAddrFromName((NLbyte*)address.c_str(), &addr);
}

//##ModelId=3BBA41220208
std::string Address::getNameByAddress() const {
	char buf[NL_MAX_STRING_LENGTH];
	nlGetNameFromAddr(&const_cast<Address*>(this)->addr, (NLbyte*)buf);
	return std::string(buf);
}

//##ModelId=3BB9282B0336
NLaddress Address::getAddress() const {
	return addr;
}

//##ModelId=3BB9282B0371
void Address::setAddress(NLaddress address) {
	addr = address;
}

//The totally lame const_casts are due to HawkNL's lack of const-correctness.
//##ModelId=3BB92893038E
std::string Address::toString() const {
	if (isValid()) {
		char buf[NL_MAX_STRING_LENGTH];
		nlAddrToString(&const_cast<Address*>(this)->addr, (NLbyte*)buf);
		return std::string(buf);
	} else
		return "invalid address";
}

//##ModelId=3BB94B1901D6
int Address::getPort() const {
	return (int)nlGetPortFromAddr(&const_cast<Address*>(this)->addr);
}

//##ModelId=3BB932340050
void Address::setPort(int port) {
	if (port < 0 || port > 65535)
		addr.valid = NL_FALSE;
	else
		nlSetAddrPort(&const_cast<Address*>(this)->addr, (NLushort)port);
}

//##ModelId=3BB934B4015E
bool Address::isValid() const {
	return (addr.valid == NL_TRUE);
}

//##ModelId=3BB934C5010E
Address::operator bool() const {
	return isValid();
}

//##ModelId=3BB934CC00BE
bool Address::operator ==(const Address& rhs) const {
	return (nlAddrCompare(&const_cast<Address*>(this)->addr, &const_cast<Address&>(rhs).addr) == NL_TRUE);
}

} //namespace GNE<|endoftext|>


<commit_before>/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserve.

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 "paddle/operators/label_smooth_op.h"

namespace paddle {
namespace operators {

class LabelSmoothOp : public framework::OperatorWithKernel {
 public:
  LabelSmoothOp(const std::string &type,
                const framework::VariableNameMap &inputs,
                const framework::VariableNameMap &outputs,
                const framework::AttributeMap &attrs)
      : OperatorWithKernel(type, inputs, outputs, attrs) {}

  void InferShape(framework::InferShapeContext *ctx) const override {
    PADDLE_ENFORCE(ctx->HasInput("X"),
                   "Input(X) of LabelSmoothOp should not be null.");
    PADDLE_ENFORCE(ctx->HasOutput("Out"),
                   "Output(Out) of LabelSmoothOp should not be null.");
    auto in_dims = ctx->GetInputDim("X");
    if (ctx->HasInput("PriorDist")) {
      auto noise_dims = ctx->GetInputDim("PriorDist");
      auto noise_numel = paddle::framework::product(noise_dims);
      PADDLE_ENFORCE(
          in_dims[1] == noise_numel,
          "The number of elements in Input(PriorDist) must be equal to the "
          "dimension of each label.");
    }
    ctx->ShareLoD("X", /*->*/ "Out");
    ctx->SetOutputDim("Out", in_dims);
  }
};

class LabelSmoothOpMaker : public framework::OpProtoAndCheckerMaker {
 public:
  LabelSmoothOpMaker(OpProto *proto, OpAttrChecker *op_checker)
      : OpProtoAndCheckerMaker(proto, op_checker) {
    AddInput("X",
             "(LoDTensor) The input labels of LabelSmooth operator. This "
             "input can be batched labels in one-hot encoding or output from "
             "softmax, with shape [N x K], where N is the batch size and K is "
             "the number of classes");
    AddInput("PriorDist",
             "(Tensor, optional)"
             "The prior distribution to be added to the smoothed label. It is "
             "fixed during training and the number of elements should be equal "
             "to the dimension K of each label. Default is uniform "
             "distribution and each element will be set to 1/K if not provided "
             "in input.")
        .AsDispensable();
    AddOutput("Out",
              "(loDTensor) The smoothed label of LabelSmooth operator. It has"
              "the same shape and LoD with the Input(LoDTensor).");
    AddAttr<float>("epsilon",
                   "(float, default 0.0f)"
                   "The smoothing parameter of LabelSmooth operator.")
        .SetDefault(0.0f);
    AddComment(R"DOC(
LabelSmooth Operator.

Label smoothing is a mechanism to regularize the classifier layer. In machine
learning, optimizing the log-likelihood of the correct label directly may
cause two problems. First, it may result in overfitting: if the model learns
to assign full probability to the ground-truth label for each training example,
it is not guaranteed to generalize. Second, it encourages the differences
between the largest logit and all others to become large, reducing the ability
of the model to adapt. Label smoothing is proposed to encourage the model to
be less confident, which replaces the ground-truth label $y$ with the weighted
sum of itselft and some fixed distribution $\mu$,
i.e.

$$
    \tilde{y} = (1 - \epsilon) * y + \epsilon * \mu,
$$

where $(1 - \epsilon)$ and $\epsilon$ are the weights respectively, and
$\tilde{y}$ is the smoothed label. Usually uniform distribution is used for
$\mu$. This change in the ground-truth label is called label-smoothing
regularization or LSR.

See more details about label smoothing in https://arxiv.org/abs/1512.00567.

)DOC");
  }
};

class LabelSmoothGradOp : public framework::OperatorWithKernel {
 public:
  LabelSmoothGradOp(const std::string &type,
                    const framework::VariableNameMap &inputs,
                    const framework::VariableNameMap &outputs,
                    const framework::AttributeMap &attrs)
      : OperatorWithKernel(type, inputs, outputs, attrs) {}

  void InferShape(framework::InferShapeContext *ctx) const override {
    PADDLE_ENFORCE(ctx->HasInput("X"), "Input(X) shouldn't be null.");
    PADDLE_ENFORCE(ctx->HasInput(framework::GradVarName("Out")),
                   "Input(Out@GRAD) shouldn't be null.");
    ctx->SetOutputDim(framework::GradVarName("X"), ctx->GetInputDim("X"));
  }
};

}  // namespace operators
}  // namespace paddle
namespace ops = paddle::operators;

REGISTER_OP(label_smooth, ops::LabelSmoothOp, ops::LabelSmoothOpMaker,
            label_smooth_grad, ops::LabelSmoothGradOp);
REGISTER_OP_CPU_KERNEL(
    label_smooth,
    ops::LabelSmoothKernel<paddle::platform::CPUDeviceContext, float>,
    ops::LabelSmoothKernel<paddle::platform::CPUDeviceContext, double>);
REGISTER_OP_CPU_KERNEL(
    label_smooth_grad,
    ops::LabelSmoothGradKernel<paddle::platform::CPUDeviceContext, float>,
    ops::LabelSmoothGradKernel<paddle::platform::CPUDeviceContext, double>);
<commit_msg>Fix typos in label_smooth_op<commit_after>/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserve.

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 "paddle/operators/label_smooth_op.h"

namespace paddle {
namespace operators {

class LabelSmoothOp : public framework::OperatorWithKernel {
 public:
  LabelSmoothOp(const std::string &type,
                const framework::VariableNameMap &inputs,
                const framework::VariableNameMap &outputs,
                const framework::AttributeMap &attrs)
      : OperatorWithKernel(type, inputs, outputs, attrs) {}

  void InferShape(framework::InferShapeContext *ctx) const override {
    PADDLE_ENFORCE(ctx->HasInput("X"),
                   "Input(X) of LabelSmoothOp should not be null.");
    PADDLE_ENFORCE(ctx->HasOutput("Out"),
                   "Output(Out) of LabelSmoothOp should not be null.");
    auto in_dims = ctx->GetInputDim("X");
    if (ctx->HasInput("PriorDist")) {
      auto noise_dims = ctx->GetInputDim("PriorDist");
      auto noise_numel = paddle::framework::product(noise_dims);
      PADDLE_ENFORCE(
          in_dims[1] == noise_numel,
          "The number of elements in Input(PriorDist) must be equal to the "
          "dimension of each label.");
    }
    ctx->ShareLoD("X", /*->*/ "Out");
    ctx->SetOutputDim("Out", in_dims);
  }
};

class LabelSmoothOpMaker : public framework::OpProtoAndCheckerMaker {
 public:
  LabelSmoothOpMaker(OpProto *proto, OpAttrChecker *op_checker)
      : OpProtoAndCheckerMaker(proto, op_checker) {
    AddInput("X",
             "(LoDTensor) The input labels of LabelSmooth operator. This "
             "input can be batched labels in one-hot encoding or output from "
             "softmax, with shape [N x K], where N is the batch size and K is "
             "the number of classes");
    AddInput("PriorDist",
             "(Tensor, optional)"
             "The prior distribution to be added to the smoothed label. It is "
             "fixed during training and the number of elements should be equal "
             "to the dimension K of each label. Default is uniform "
             "distribution and each element will be set to 1/K if not provided "
             "in input.")
        .AsDispensable();
    AddOutput("Out",
              "(loDTensor) The smoothed label of LabelSmooth operator. It has"
              "the same shape and LoD with the Input(LoDTensor).");
    AddAttr<float>("epsilon",
                   "(float, default 0.0f)"
                   "The smoothing parameter of LabelSmooth operator.")
        .SetDefault(0.0f);
    AddComment(R"DOC(
LabelSmooth Operator.

Label smoothing is a mechanism to regularize the classifier layer. In machine
learning, optimizing the log-likelihood of the correct label directly may
cause two problems. First, it may result in overfitting: if the model learns
to assign full probability to the ground-truth label for each training example,
it is not guaranteed to generalize. Second, it encourages the differences
between the largest logit and all others to become large, reducing the ability
of the model to adapt. Label smoothing is proposed to encourage the model to
be less confident, which replaces the ground-truth label $y$ with the weighted
sum of itself and some fixed distribution $\mu$, i.e.

$$
    \tilde{y} = (1 - \epsilon) * y + \epsilon * \mu,
$$

where $(1 - \epsilon)$ and $\epsilon$ are the weights respectively, and
$\tilde{y}$ is the smoothed label. Usually uniform distribution is used for
$\mu$. This change in the ground-truth label is called label-smoothing
regularization or LSR.

See more details about label smoothing in https://arxiv.org/abs/1512.00567.

)DOC");
  }
};

class LabelSmoothGradOp : public framework::OperatorWithKernel {
 public:
  LabelSmoothGradOp(const std::string &type,
                    const framework::VariableNameMap &inputs,
                    const framework::VariableNameMap &outputs,
                    const framework::AttributeMap &attrs)
      : OperatorWithKernel(type, inputs, outputs, attrs) {}

  void InferShape(framework::InferShapeContext *ctx) const override {
    PADDLE_ENFORCE(ctx->HasInput("X"), "Input(X) shouldn't be null.");
    PADDLE_ENFORCE(ctx->HasInput(framework::GradVarName("Out")),
                   "Input(Out@GRAD) shouldn't be null.");
    ctx->SetOutputDim(framework::GradVarName("X"), ctx->GetInputDim("X"));
  }
};

}  // namespace operators
}  // namespace paddle
namespace ops = paddle::operators;

REGISTER_OP(label_smooth, ops::LabelSmoothOp, ops::LabelSmoothOpMaker,
            label_smooth_grad, ops::LabelSmoothGradOp);
REGISTER_OP_CPU_KERNEL(
    label_smooth,
    ops::LabelSmoothKernel<paddle::platform::CPUDeviceContext, float>,
    ops::LabelSmoothKernel<paddle::platform::CPUDeviceContext, double>);
REGISTER_OP_CPU_KERNEL(
    label_smooth_grad,
    ops::LabelSmoothGradKernel<paddle::platform::CPUDeviceContext, float>,
    ops::LabelSmoothGradKernel<paddle::platform::CPUDeviceContext, double>);
<|endoftext|>