<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: tplcitem.cxx,v $
 *
 *  $Revision: 1.9 $
 *
 *  last change: $Author: obo $ $Date: 2006-09-17 16:37:24 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    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
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_sfx2.hxx"

// INCLUDE ---------------------------------------------------------------

#include <svtools/intitem.hxx>
#include <vcl/svapp.hxx>

#ifndef GCC
#endif

#include "templdlg.hxx"
#include "bindings.hxx"
#include "tplpitem.hxx"
#include "tplcitem.hxx"
#include "templdgi.hxx"

#include "sfx.hrc"
#include "dialog.hrc"

// STATIC DATA -----------------------------------------------------------

// Konstruktor

SfxTemplateControllerItem::SfxTemplateControllerItem(
        USHORT nSlotId,                 // ID
        SfxCommonTemplateDialog_Impl &rDlg, // Controller-Instanz, dem dieses Item zugeordnet ist.
        SfxBindings &rBindings):
    SfxControllerItem(nSlotId, rBindings),
    rTemplateDlg(rDlg),
    nWaterCanState(0xff),
    nUserEventId(0)
{
}
// -----------------------------------------------------------------------
SfxTemplateControllerItem::~SfxTemplateControllerItem()
{
    if(nUserEventId)
        Application::RemoveUserEvent(nUserEventId);
}

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

// Benachrichtigung "uber Status"anderung; wird an den
// im Konstruktor "ubergebenen Controller propagiert

void SfxTemplateControllerItem::StateChanged( USHORT nSID, SfxItemState eState,
                                              const SfxPoolItem* pItem )
{
    switch(nSID)
    {
        case SID_STYLE_FAMILY1:
        case SID_STYLE_FAMILY2:
        case SID_STYLE_FAMILY3:
        case SID_STYLE_FAMILY4:
        case SID_STYLE_FAMILY5:
        {
            FASTBOOL bAvailable = SFX_ITEM_AVAILABLE == eState;
            if ( !bAvailable )
                rTemplateDlg.SetFamilyState(GetId(), 0);
            else {
                const SfxTemplateItem *pStateItem = PTR_CAST(
                    SfxTemplateItem, pItem);
                DBG_ASSERT(pStateItem != 0, "SfxTemplateItem erwartet");
                rTemplateDlg.SetFamilyState( GetId(), pStateItem );
            }
            BOOL bDisable = eState == SFX_ITEM_DISABLED;
            // Familie Disablen
            USHORT nFamily = 0;
            switch( GetId())
            {
                case SID_STYLE_FAMILY1:
                    nFamily = 1; break;
                case SID_STYLE_FAMILY2:
                    nFamily = 2; break;
                case SID_STYLE_FAMILY3:
                    nFamily = 3; break;
                case SID_STYLE_FAMILY4:
                    nFamily = 4; break;
                case SID_STYLE_FAMILY5:
                    nFamily = 5; break;
                default: DBG_ERROR("unbekannte StyleFamily"); break;
            }
            rTemplateDlg.EnableFamilyItem( nFamily, !bDisable );
            break;
        }
        case SID_STYLE_WATERCAN:
        {
            if ( eState == SFX_ITEM_DISABLED )
                nWaterCanState = 0xff;
            else if( eState == SFX_ITEM_AVAILABLE )
            {
                const SfxBoolItem *pStateItem = PTR_CAST(SfxBoolItem, pItem);
                DBG_ASSERT(pStateItem != 0, "BoolItem erwartet");
                nWaterCanState = pStateItem->GetValue() ? 1 : 0;
            }
            //not necessary if the last event is still on the way
            if(!nUserEventId)
                nUserEventId = Application::PostUserEvent( STATIC_LINK(
                            this, SfxTemplateControllerItem, SetWaterCanStateHdl_Impl ) );
            break;
        }
        case SID_STYLE_EDIT:
            rTemplateDlg.EnableEdit( SFX_ITEM_DISABLED != eState );
            break;
        case SID_STYLE_DELETE:
            rTemplateDlg.EnableDel( SFX_ITEM_DISABLED != eState );
            break;
        case SID_STYLE_NEW_BY_EXAMPLE:

            rTemplateDlg.EnableExample_Impl(
                GetId(), SFX_ITEM_DISABLED != eState );
            break;
        case SID_STYLE_UPDATE_BY_EXAMPLE:
        {
            rTemplateDlg.EnableExample_Impl(
                GetId(), eState != SFX_ITEM_DISABLED );
            // Das Select Disabled dann, falls enabled und Style Readonly
/*          String aStr = rTemplateDlg.GetSelectedEntry();
            if( aStr.Len() ) rTemplateDlg.SelectStyle( aStr ); */
            break;
        }
        case SID_STYLE_NEW:
        {
            rTemplateDlg.EnableNew( SFX_ITEM_DISABLED != eState );
            break;
        }
        case SID_STYLE_DRAGHIERARCHIE:
        {
            rTemplateDlg.EnableTreeDrag( SFX_ITEM_DISABLED != eState );
            break;
        }
        case SID_STYLE_FAMILY :
        {
            const SfxUInt16Item *pStateItem = PTR_CAST( SfxUInt16Item, pItem);
            if (pStateItem)
                rTemplateDlg.SetFamily( pStateItem->GetValue() );
            break;
        }
    }
}
/* -----------------------------05.09.2001 10:48------------------------------

 ---------------------------------------------------------------------------*/
IMPL_STATIC_LINK(SfxTemplateControllerItem, SetWaterCanStateHdl_Impl,
                                    SfxTemplateControllerItem*, EMPTYARG)
{
    pThis->nUserEventId = 0;
    SfxBoolItem* pState = 0;
    switch(pThis->nWaterCanState)
    {
        case 0 :
        case 1 :
            pState = new SfxBoolItem(SID_STYLE_WATERCAN, pThis->nWaterCanState ? TRUE : FALSE);
        break;
    }
    pThis->rTemplateDlg.SetWaterCanState(pState);
    delete pState;
    return 0;
}

<commit_msg>INTEGRATION: CWS vgbugs07 (1.9.218); FILE MERGED 2007/06/04 13:34:51 vg 1.9.218.1: #i76605# Remove -I .../inc/module hack introduced by hedaburemove01<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: tplcitem.cxx,v $
 *
 *  $Revision: 1.10 $
 *
 *  last change: $Author: hr $ $Date: 2007-06-27 23:17:46 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    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
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_sfx2.hxx"

// INCLUDE ---------------------------------------------------------------

#include <svtools/intitem.hxx>
#include <vcl/svapp.hxx>

#ifndef GCC
#endif

#include <sfx2/templdlg.hxx>
#include <sfx2/bindings.hxx>
#include "tplpitem.hxx"
#include "tplcitem.hxx"
#include "templdgi.hxx"

#include <sfx2/sfx.hrc>
#include "dialog.hrc"

// STATIC DATA -----------------------------------------------------------

// Konstruktor

SfxTemplateControllerItem::SfxTemplateControllerItem(
        USHORT nSlotId,                 // ID
        SfxCommonTemplateDialog_Impl &rDlg, // Controller-Instanz, dem dieses Item zugeordnet ist.
        SfxBindings &rBindings):
    SfxControllerItem(nSlotId, rBindings),
    rTemplateDlg(rDlg),
    nWaterCanState(0xff),
    nUserEventId(0)
{
}
// -----------------------------------------------------------------------
SfxTemplateControllerItem::~SfxTemplateControllerItem()
{
    if(nUserEventId)
        Application::RemoveUserEvent(nUserEventId);
}

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

// Benachrichtigung "uber Status"anderung; wird an den
// im Konstruktor "ubergebenen Controller propagiert

void SfxTemplateControllerItem::StateChanged( USHORT nSID, SfxItemState eState,
                                              const SfxPoolItem* pItem )
{
    switch(nSID)
    {
        case SID_STYLE_FAMILY1:
        case SID_STYLE_FAMILY2:
        case SID_STYLE_FAMILY3:
        case SID_STYLE_FAMILY4:
        case SID_STYLE_FAMILY5:
        {
            FASTBOOL bAvailable = SFX_ITEM_AVAILABLE == eState;
            if ( !bAvailable )
                rTemplateDlg.SetFamilyState(GetId(), 0);
            else {
                const SfxTemplateItem *pStateItem = PTR_CAST(
                    SfxTemplateItem, pItem);
                DBG_ASSERT(pStateItem != 0, "SfxTemplateItem erwartet");
                rTemplateDlg.SetFamilyState( GetId(), pStateItem );
            }
            BOOL bDisable = eState == SFX_ITEM_DISABLED;
            // Familie Disablen
            USHORT nFamily = 0;
            switch( GetId())
            {
                case SID_STYLE_FAMILY1:
                    nFamily = 1; break;
                case SID_STYLE_FAMILY2:
                    nFamily = 2; break;
                case SID_STYLE_FAMILY3:
                    nFamily = 3; break;
                case SID_STYLE_FAMILY4:
                    nFamily = 4; break;
                case SID_STYLE_FAMILY5:
                    nFamily = 5; break;
                default: DBG_ERROR("unbekannte StyleFamily"); break;
            }
            rTemplateDlg.EnableFamilyItem( nFamily, !bDisable );
            break;
        }
        case SID_STYLE_WATERCAN:
        {
            if ( eState == SFX_ITEM_DISABLED )
                nWaterCanState = 0xff;
            else if( eState == SFX_ITEM_AVAILABLE )
            {
                const SfxBoolItem *pStateItem = PTR_CAST(SfxBoolItem, pItem);
                DBG_ASSERT(pStateItem != 0, "BoolItem erwartet");
                nWaterCanState = pStateItem->GetValue() ? 1 : 0;
            }
            //not necessary if the last event is still on the way
            if(!nUserEventId)
                nUserEventId = Application::PostUserEvent( STATIC_LINK(
                            this, SfxTemplateControllerItem, SetWaterCanStateHdl_Impl ) );
            break;
        }
        case SID_STYLE_EDIT:
            rTemplateDlg.EnableEdit( SFX_ITEM_DISABLED != eState );
            break;
        case SID_STYLE_DELETE:
            rTemplateDlg.EnableDel( SFX_ITEM_DISABLED != eState );
            break;
        case SID_STYLE_NEW_BY_EXAMPLE:

            rTemplateDlg.EnableExample_Impl(
                GetId(), SFX_ITEM_DISABLED != eState );
            break;
        case SID_STYLE_UPDATE_BY_EXAMPLE:
        {
            rTemplateDlg.EnableExample_Impl(
                GetId(), eState != SFX_ITEM_DISABLED );
            // Das Select Disabled dann, falls enabled und Style Readonly
/*          String aStr = rTemplateDlg.GetSelectedEntry();
            if( aStr.Len() ) rTemplateDlg.SelectStyle( aStr ); */
            break;
        }
        case SID_STYLE_NEW:
        {
            rTemplateDlg.EnableNew( SFX_ITEM_DISABLED != eState );
            break;
        }
        case SID_STYLE_DRAGHIERARCHIE:
        {
            rTemplateDlg.EnableTreeDrag( SFX_ITEM_DISABLED != eState );
            break;
        }
        case SID_STYLE_FAMILY :
        {
            const SfxUInt16Item *pStateItem = PTR_CAST( SfxUInt16Item, pItem);
            if (pStateItem)
                rTemplateDlg.SetFamily( pStateItem->GetValue() );
            break;
        }
    }
}
/* -----------------------------05.09.2001 10:48------------------------------

 ---------------------------------------------------------------------------*/
IMPL_STATIC_LINK(SfxTemplateControllerItem, SetWaterCanStateHdl_Impl,
                                    SfxTemplateControllerItem*, EMPTYARG)
{
    pThis->nUserEventId = 0;
    SfxBoolItem* pState = 0;
    switch(pThis->nWaterCanState)
    {
        case 0 :
        case 1 :
            pState = new SfxBoolItem(SID_STYLE_WATERCAN, pThis->nWaterCanState ? TRUE : FALSE);
        break;
    }
    pThis->rTemplateDlg.SetWaterCanState(pState);
    delete pState;
    return 0;
}

<|endoftext|>


<commit_before>#include "interlua.hh"

#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cstdarg>

namespace InterLua {

void die(const char *str, ...) {
	va_list va;
	va_start(va, str);
	std::vfprintf(stderr, str, va);
	va_end(va);
	std::abort();
}

void stack_dump(lua_State *L) {
      int i;
      int top = lua_gettop(L);
      printf("lua stack dump -------------\n");
      for (i = 1; i <= top; i++) {  /* repeat for each level */
        int t = lua_type(L, i);
        switch (t) {
          case LUA_TSTRING:  /* strings */
            printf("string: `%s'", lua_tostring(L, i));
            break;
          case LUA_TBOOLEAN:  /* booleans */
            printf(lua_toboolean(L, i) ? "boolean: true" : "boolean: false");
            break;
          case LUA_TNUMBER:  /* numbers */
            printf("number: %g", lua_tonumber(L, i));
            break;
          default:  /* other values */
            printf("other: %s", lua_typename(L, t));
            break;
        }
        printf(" | ");  /* put a separator */
      }
      printf("\n");  /* end the listing */
      printf("----------------------------\n");
}

int read_only_error(lua_State *L) {
	return luaL_error(L, "'%s' is read-only", lua_tostring(L, lua_upvalueindex(1)));
}

int const_read_only_error(lua_State *L) {
	return luaL_error(L, "'%s' is a read-only member of a const class instance",
		lua_tostring(L, lua_upvalueindex(1)));
}

// universal index metamethod, works for namespaces and all kinds of classes
// data the logic is simple:
//   1. get value from metatable if available, if not found proceed to (2)
//   2. get value using __propget function, if not found proceed to (3)
//   3. try to recurse into __parent, if not found return nil
static int index_meta_method(lua_State *L) {
	lua_getmetatable(L, 1); // push metatable of arg1 (++)
	for (;;) {
		lua_pushvalue(L, 2); // push key arg2 (++)
		lua_rawget(L, -2); // key lookup in the metatable (==)
		if (!lua_isnil(L, -1)) {
			// found something directly in the metatable, discard
			// metatable and return the value
			lua_remove(L, -2); // (--)
			return 1;
		}

		// otherwise let's try to find appropriate __propget
		lua_pop(L, 1); // discard nil (--)
		rawgetfield(L, -1, "__propget"); // __propget from metatable (++)
		lua_pushvalue(L, 2); // push key arg2 (++)
		lua_rawget(L, -2); // lookup key in __propget (==)
		lua_remove(L, -2); // discard __propget (--)
		if (lua_iscfunction(L, -1)) {
			lua_remove(L, -2); // discard metatable (--)
			lua_pushvalue(L, 1); // push arg1 (++)
			lua_call(L, 1, 1); // call cfunction
			return 1;
		}

		// not found, let's try parent
		lua_pop(L, 1); // discard nil (--)
		rawgetfield(L, -1, "__parent"); // (++)
		lua_remove(L, -2); // discard child's metatable (--)
		if (lua_isnil(L, -1)) {
			// no parent actually
			return 1;
		}
	}
}

static int newindex_meta_method(lua_State *L) {
	lua_getmetatable(L, 1); // push metatable of arg1 (++)
	for (;;) {
		rawgetfield(L, -1, "__propset"); // lookup __propset in metatable (++)
		lua_pushvalue(L, 2); // push key arg2 (++)
		lua_rawget(L, -2); // lookup key in __propset (==)
		lua_remove(L, -2); // discard __propset (--)
		if (lua_iscfunction(L, -1)) {
			lua_remove(L, -2); // discard metatable (--)
			lua_pushvalue(L, 3); // push new value arg3 (++)
			lua_call(L, 1, 0);
			return 0;
		}

		lua_pop(L, 1); // discard nil (--)
		rawgetfield(L, -1, "__parent"); // (++)
		lua_remove(L, -2); // discard child's metatable (--)
		if (lua_isnil(L, -1)) {
			// no parent, return an error
			lua_pop(L, 1); // discard nil (--)
			return luaL_error(L, "no writable variable '%s'",
				lua_tostring(L, 2));
		}
	}
}

static int class_newindex_meta_method(lua_State *L) {
	lua_getmetatable(L, 1); // push metatable of arg1 (++)
	for (;;) {
		rawgetfield(L, -1, "__propset"); // lookup __propset in metatable (++)
		lua_pushvalue(L, 2); // push key arg2 (++)
		lua_rawget(L, -2); // lookup key in __propset (==)
		lua_remove(L, -2); // discard __propset (--)
		if (lua_iscfunction(L, -1)) {
			lua_remove(L, -2); // discard metatable (--)
			lua_pushvalue(L, 1); // push userdata arg1 (++)
			lua_pushvalue(L, 3); // push new value arg3 (++)
			lua_call(L, 2, 0);
			return 0;
		}

		lua_pop(L, 1); // discard nil (--)
		rawgetfield(L, -1, "__parent"); // (++)
		lua_remove(L, -2); // discard child's metatable (--)
		if (lua_isnil(L, -1)) {
			// no parent, return an error
			lua_pop(L, 1); // discard nil (--)
			return luaL_error(L, "no writable variable '%s'",
				lua_tostring(L, 2));
		}
	}
}

void set_common_metamethods(lua_State *L,
	lua_CFunction index, lua_CFunction newindex)
{
	lua_pushcfunction(L, index);
	rawsetfield(L, -2, "__index");
	lua_pushcfunction(L, newindex);
	rawsetfield(L, -2, "__newindex");
	lua_newtable(L);
	rawsetfield(L, -2, "__propget");
	lua_newtable(L);
	rawsetfield(L, -2, "__propset");
}

void create_class_tables(lua_State *L, const char *name) {
	// TODO: method: .HideMetatable() or .HiddenMetatable()
	// lua_pushnil(L);
	// rawsetfield(L, -2, "__metatable");

	// -- const table --

	lua_newtable(L);
	lua_pushfstring(L, "const %s", name);
	rawsetfield(L, -2, "__type");
	set_common_metamethods(L, index_meta_method, class_newindex_meta_method);

	// -- class table --

	lua_newtable(L);
	lua_pushstring(L, name);
	rawsetfield(L, -2, "__type");
	set_common_metamethods(L, index_meta_method, class_newindex_meta_method);

	// a pointer to the const table, mutable value can become a const value
	lua_pushvalue(L, -2);
	rawsetfield(L, -2, "__const");

	// -- static table --

	lua_newtable(L);
	lua_pushvalue(L, -1);
	lua_setmetatable(L, -2);
	set_common_metamethods(L, index_meta_method, newindex_meta_method);

	// a pointer to the class table, we need this in Class registration
	// function to reuse the tables in case if the same class is being
	// registered twice
	lua_pushvalue(L, -2);
	rawsetfield(L, -2, "__class");
}

NSWrapper NSWrapper::Namespace(const char *name) {
	rawgetfield(L, -1, name);
	if (!lua_isnil(L, -1))
		return {L};

	// pop nil left from the rawgetfield call above
	lua_pop(L, 1);

	// create an empty table and make it a metatable of itself
	lua_newtable(L);
	lua_pushvalue(L, -1);
	lua_setmetatable(L, -2);

	set_common_metamethods(L, index_meta_method, newindex_meta_method);

	// namespace[name] = table
	lua_pushvalue(L, -1);
	rawsetfield(L, -3, name);
	return {L};
}

Userdata::~Userdata() {}

// expects two metatables on the stack (see get_userdata function):
//  -1 'absidx' metatable
//  -2 'base_class_key' metatable
// and formats a nice error message for these (even if 'absidx' mt is nil)
static void get_userdata_error(lua_State *L, int absidx, int idx, const char *str) {
	const char *expected, *got;
	rawgetfield(L, -2, "__type");
	expected = lua_tostring(L, -1);
	if (lua_isnil(L, -2)) {
		got = lua_typename(L, lua_type(L, absidx));
	} else {
		rawgetfield(L, -2, "__type");
		got = lua_tostring(L, -1);
	}
	const char *msg = lua_pushfstring(L, str, expected, got);
	luaL_argerror(L, idx, msg);
}

Userdata *get_userdata_typeless(lua_State *L, int idx) {
	auto ud = (Userdata*)lua_touserdata(L, idx);
	if (ud && lua_rawlen(L, idx) >= sizeof(Userdata) && ud->IsValid())
		return ud;
	return nullptr;
}

Userdata *get_userdata(lua_State *L, int idx, void *base_class_key, bool can_be_const) {
	// first check that 'idx' is userdata and its ours, also get the
	// 'is_const' state, because it's stored in the same place where we
	// check for userdata ownership
	auto ud = (Userdata*)lua_touserdata(L, idx);
	if (!ud) {
		// not a userdata, let's check if there is something at all
		luaL_checkany(L, idx);

		// perhaps just a wrong argument (string, number or whatever),
		// but we will report the error message after getting the
		// 'base_class_key' metatable
	}

	const int absidx = lua_absindex(L, idx);
	lua_rawgetp(L, LUA_REGISTRYINDEX, base_class_key); // class metatable
	if (lua_isnil(L, -1)) {
		luaL_argerror(L, idx,
			"trying to get an unregistered base class pointer");
		return nullptr;
	}

	// at this point we know that 'idx' contains something and
	// 'base_class_key' metatable is on the stack, but if 'idx' is not a
	// userdata, let's report an error right there
	if (!ud) {
		lua_pushnil(L);
		get_userdata_error(L, absidx, idx,
			"not userdata, class \"%s\" expected, got \"%s\" instead");
		return nullptr;
	}

	// at this point we have userdata at the 'absidx' and 'base_class_key'
	// metatable on the top of the stack, let's make sure userdata is ours
	if (lua_rawlen(L, absidx) < sizeof(Userdata) || !ud->IsValid()) {
		lua_pushnil(L);
		get_userdata_error(L, absidx, idx,
			"interlua class \"%s\" expected, got foreign userdata instead");
		return nullptr;
	}

	const bool is_const = ud->IsConst();

	// we're certain that our userdata has a valid metatable
	lua_getmetatable(L, absidx);
	if (is_const && !can_be_const) {
		// if the userdata is const and we need a mutable one, that's
		// an error
		get_userdata_error(L, absidx, idx,
			"mutable class \"%s\" required, got \"%s\" instead");
		return nullptr;
	}

	// at this point we have
	//  -1 'absidx' metatable
	//  -2 'base_class_key' metatable
	// let's replace 'base_class_key' metatable with a const one if
	// necessary
	if (is_const) {
		rawgetfield(L, -2, "__const");
		lua_replace(L, -3);
	}

	// go up the class hierarchy starting from 'absidx' metatable and see if
	// there are matching metatables
	for (;;) {
		if (lua_rawequal(L, -1, -2)) {
			// got a match
			lua_pop(L, 2);
			return ud;
		}

		// no match, let's try the parent
		rawgetfield(L, -1, "__parent");
		if (lua_isnil(L, -1)) {
			// no parent, means no match, cleanup the mess and get
			// back the original 'absidx' metatable
			lua_pop(L, 2);
			lua_getmetatable(L, absidx);
			get_userdata_error(L, absidx, idx,
				"type mismatch, \"%s\" expected, got \"%s\" instead");
			return nullptr;
		}
		lua_remove(L, -2); // remove the child metatable
	}
}

Userdata *get_userdata_unchecked(lua_State *L, int index) {
	return (Userdata*)lua_touserdata(L, index);
}

Error::~Error() {}

void Error::Set(int code, const char*) {
	this->code = code;
}

const char *Error::What() const {
	return "";
}

VerboseError::~VerboseError() {
	if (message)
		std::free(message);
}

void VerboseError::Set(int code, const char *msg) {
	this->code = code;

	if (message)
		std::free(message);
	message = (char*)std::malloc(std::strlen(msg)+1);
	if (!message)
		die("malloc failure");
	std::strcpy(message, msg);
}

const char *VerboseError::What() const {
	return message ? message : "";
}

void AbortError::Set(int code, const char *msg) {
	this->code = code;
	std::fprintf(stderr, "PANIC (%d): %s\n", code, msg);
	std::abort();
}

AbortError DefaultError;

} // namespace InterLua
<commit_msg>Be more specific in the type mismatch error message.<commit_after>#include "interlua.hh"

#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cstdarg>

namespace InterLua {

void die(const char *str, ...) {
	va_list va;
	va_start(va, str);
	std::vfprintf(stderr, str, va);
	va_end(va);
	std::abort();
}

void stack_dump(lua_State *L) {
      int i;
      int top = lua_gettop(L);
      printf("lua stack dump -------------\n");
      for (i = 1; i <= top; i++) {  /* repeat for each level */
        int t = lua_type(L, i);
        switch (t) {
          case LUA_TSTRING:  /* strings */
            printf("string: `%s'", lua_tostring(L, i));
            break;
          case LUA_TBOOLEAN:  /* booleans */
            printf(lua_toboolean(L, i) ? "boolean: true" : "boolean: false");
            break;
          case LUA_TNUMBER:  /* numbers */
            printf("number: %g", lua_tonumber(L, i));
            break;
          default:  /* other values */
            printf("other: %s", lua_typename(L, t));
            break;
        }
        printf(" | ");  /* put a separator */
      }
      printf("\n");  /* end the listing */
      printf("----------------------------\n");
}

int read_only_error(lua_State *L) {
	return luaL_error(L, "'%s' is read-only", lua_tostring(L, lua_upvalueindex(1)));
}

int const_read_only_error(lua_State *L) {
	return luaL_error(L, "'%s' is a read-only member of a const class instance",
		lua_tostring(L, lua_upvalueindex(1)));
}

// universal index metamethod, works for namespaces and all kinds of classes
// data the logic is simple:
//   1. get value from metatable if available, if not found proceed to (2)
//   2. get value using __propget function, if not found proceed to (3)
//   3. try to recurse into __parent, if not found return nil
static int index_meta_method(lua_State *L) {
	lua_getmetatable(L, 1); // push metatable of arg1 (++)
	for (;;) {
		lua_pushvalue(L, 2); // push key arg2 (++)
		lua_rawget(L, -2); // key lookup in the metatable (==)
		if (!lua_isnil(L, -1)) {
			// found something directly in the metatable, discard
			// metatable and return the value
			lua_remove(L, -2); // (--)
			return 1;
		}

		// otherwise let's try to find appropriate __propget
		lua_pop(L, 1); // discard nil (--)
		rawgetfield(L, -1, "__propget"); // __propget from metatable (++)
		lua_pushvalue(L, 2); // push key arg2 (++)
		lua_rawget(L, -2); // lookup key in __propget (==)
		lua_remove(L, -2); // discard __propget (--)
		if (lua_iscfunction(L, -1)) {
			lua_remove(L, -2); // discard metatable (--)
			lua_pushvalue(L, 1); // push arg1 (++)
			lua_call(L, 1, 1); // call cfunction
			return 1;
		}

		// not found, let's try parent
		lua_pop(L, 1); // discard nil (--)
		rawgetfield(L, -1, "__parent"); // (++)
		lua_remove(L, -2); // discard child's metatable (--)
		if (lua_isnil(L, -1)) {
			// no parent actually
			return 1;
		}
	}
}

static int newindex_meta_method(lua_State *L) {
	lua_getmetatable(L, 1); // push metatable of arg1 (++)
	for (;;) {
		rawgetfield(L, -1, "__propset"); // lookup __propset in metatable (++)
		lua_pushvalue(L, 2); // push key arg2 (++)
		lua_rawget(L, -2); // lookup key in __propset (==)
		lua_remove(L, -2); // discard __propset (--)
		if (lua_iscfunction(L, -1)) {
			lua_remove(L, -2); // discard metatable (--)
			lua_pushvalue(L, 3); // push new value arg3 (++)
			lua_call(L, 1, 0);
			return 0;
		}

		lua_pop(L, 1); // discard nil (--)
		rawgetfield(L, -1, "__parent"); // (++)
		lua_remove(L, -2); // discard child's metatable (--)
		if (lua_isnil(L, -1)) {
			// no parent, return an error
			lua_pop(L, 1); // discard nil (--)
			return luaL_error(L, "no writable variable '%s'",
				lua_tostring(L, 2));
		}
	}
}

static int class_newindex_meta_method(lua_State *L) {
	lua_getmetatable(L, 1); // push metatable of arg1 (++)
	for (;;) {
		rawgetfield(L, -1, "__propset"); // lookup __propset in metatable (++)
		lua_pushvalue(L, 2); // push key arg2 (++)
		lua_rawget(L, -2); // lookup key in __propset (==)
		lua_remove(L, -2); // discard __propset (--)
		if (lua_iscfunction(L, -1)) {
			lua_remove(L, -2); // discard metatable (--)
			lua_pushvalue(L, 1); // push userdata arg1 (++)
			lua_pushvalue(L, 3); // push new value arg3 (++)
			lua_call(L, 2, 0);
			return 0;
		}

		lua_pop(L, 1); // discard nil (--)
		rawgetfield(L, -1, "__parent"); // (++)
		lua_remove(L, -2); // discard child's metatable (--)
		if (lua_isnil(L, -1)) {
			// no parent, return an error
			lua_pop(L, 1); // discard nil (--)
			return luaL_error(L, "no writable variable '%s'",
				lua_tostring(L, 2));
		}
	}
}

void set_common_metamethods(lua_State *L,
	lua_CFunction index, lua_CFunction newindex)
{
	lua_pushcfunction(L, index);
	rawsetfield(L, -2, "__index");
	lua_pushcfunction(L, newindex);
	rawsetfield(L, -2, "__newindex");
	lua_newtable(L);
	rawsetfield(L, -2, "__propget");
	lua_newtable(L);
	rawsetfield(L, -2, "__propset");
}

void create_class_tables(lua_State *L, const char *name) {
	// TODO: method: .HideMetatable() or .HiddenMetatable()
	// lua_pushnil(L);
	// rawsetfield(L, -2, "__metatable");

	// -- const table --

	lua_newtable(L);
	lua_pushfstring(L, "const %s", name);
	rawsetfield(L, -2, "__type");
	set_common_metamethods(L, index_meta_method, class_newindex_meta_method);

	// -- class table --

	lua_newtable(L);
	lua_pushstring(L, name);
	rawsetfield(L, -2, "__type");
	set_common_metamethods(L, index_meta_method, class_newindex_meta_method);

	// a pointer to the const table, mutable value can become a const value
	lua_pushvalue(L, -2);
	rawsetfield(L, -2, "__const");

	// -- static table --

	lua_newtable(L);
	lua_pushvalue(L, -1);
	lua_setmetatable(L, -2);
	set_common_metamethods(L, index_meta_method, newindex_meta_method);

	// a pointer to the class table, we need this in Class registration
	// function to reuse the tables in case if the same class is being
	// registered twice
	lua_pushvalue(L, -2);
	rawsetfield(L, -2, "__class");
}

NSWrapper NSWrapper::Namespace(const char *name) {
	rawgetfield(L, -1, name);
	if (!lua_isnil(L, -1))
		return {L};

	// pop nil left from the rawgetfield call above
	lua_pop(L, 1);

	// create an empty table and make it a metatable of itself
	lua_newtable(L);
	lua_pushvalue(L, -1);
	lua_setmetatable(L, -2);

	set_common_metamethods(L, index_meta_method, newindex_meta_method);

	// namespace[name] = table
	lua_pushvalue(L, -1);
	rawsetfield(L, -3, name);
	return {L};
}

Userdata::~Userdata() {}

// expects two metatables on the stack (see get_userdata function):
//  -1 'absidx' metatable
//  -2 'base_class_key' metatable
// and formats a nice error message for these (even if 'absidx' mt is nil)
static void get_userdata_error(lua_State *L, int absidx, int idx, const char *str) {
	const char *expected, *got;
	rawgetfield(L, -2, "__type");
	expected = lua_tostring(L, -1);
	if (lua_isnil(L, -2)) {
		got = lua_typename(L, lua_type(L, absidx));
	} else {
		rawgetfield(L, -2, "__type");
		got = lua_tostring(L, -1);
	}
	const char *msg = lua_pushfstring(L, str, expected, got);
	luaL_argerror(L, idx, msg);
}

Userdata *get_userdata_typeless(lua_State *L, int idx) {
	auto ud = (Userdata*)lua_touserdata(L, idx);
	if (ud && lua_rawlen(L, idx) >= sizeof(Userdata) && ud->IsValid())
		return ud;
	return nullptr;
}

Userdata *get_userdata(lua_State *L, int idx, void *base_class_key, bool can_be_const) {
	// first check that 'idx' is userdata and its ours, also get the
	// 'is_const' state, because it's stored in the same place where we
	// check for userdata ownership
	auto ud = (Userdata*)lua_touserdata(L, idx);
	if (!ud) {
		// not a userdata, let's check if there is something at all
		luaL_checkany(L, idx);

		// perhaps just a wrong argument (string, number or whatever),
		// but we will report the error message after getting the
		// 'base_class_key' metatable
	}

	const int absidx = lua_absindex(L, idx);
	lua_rawgetp(L, LUA_REGISTRYINDEX, base_class_key); // class metatable
	if (lua_isnil(L, -1)) {
		luaL_argerror(L, idx,
			"trying to get an unregistered base class pointer");
		return nullptr;
	}

	// at this point we know that 'idx' contains something and
	// 'base_class_key' metatable is on the stack, but if 'idx' is not a
	// userdata, let's report an error right there
	if (!ud) {
		lua_pushnil(L);
		get_userdata_error(L, absidx, idx,
			"not userdata, class \"%s\" expected, got \"%s\" instead");
		return nullptr;
	}

	// at this point we have userdata at the 'absidx' and 'base_class_key'
	// metatable on the top of the stack, let's make sure userdata is ours
	if (lua_rawlen(L, absidx) < sizeof(Userdata) || !ud->IsValid()) {
		lua_pushnil(L);
		get_userdata_error(L, absidx, idx,
			"interlua class \"%s\" expected, got foreign userdata instead");
		return nullptr;
	}

	const bool is_const = ud->IsConst();

	// we're certain that our userdata has a valid metatable
	lua_getmetatable(L, absidx);
	if (is_const && !can_be_const) {
		// if the userdata is const and we need a mutable one, that's
		// an error
		get_userdata_error(L, absidx, idx,
			"mutable class \"%s\" required, got \"%s\" instead");
		return nullptr;
	}

	// at this point we have
	//  -1 'absidx' metatable
	//  -2 'base_class_key' metatable
	// let's replace 'base_class_key' metatable with a const one if
	// necessary
	if (is_const) {
		rawgetfield(L, -2, "__const");
		lua_replace(L, -3);
	}

	// go up the class hierarchy starting from 'absidx' metatable and see if
	// there are matching metatables
	for (;;) {
		if (lua_rawequal(L, -1, -2)) {
			// got a match
			lua_pop(L, 2);
			return ud;
		}

		// no match, let's try the parent
		rawgetfield(L, -1, "__parent");
		if (lua_isnil(L, -1)) {
			// no parent, means no match, cleanup the mess and get
			// back the original 'absidx' metatable
			lua_pop(L, 2);
			lua_getmetatable(L, absidx);
			get_userdata_error(L, absidx, idx,
				"class mismatch, \"%s\" expected, got \"%s\" instead");
			return nullptr;
		}
		lua_remove(L, -2); // remove the child metatable
	}
}

Userdata *get_userdata_unchecked(lua_State *L, int index) {
	return (Userdata*)lua_touserdata(L, index);
}

Error::~Error() {}

void Error::Set(int code, const char*) {
	this->code = code;
}

const char *Error::What() const {
	return "";
}

VerboseError::~VerboseError() {
	if (message)
		std::free(message);
}

void VerboseError::Set(int code, const char *msg) {
	this->code = code;

	if (message)
		std::free(message);
	message = (char*)std::malloc(std::strlen(msg)+1);
	if (!message)
		die("malloc failure");
	std::strcpy(message, msg);
}

const char *VerboseError::What() const {
	return message ? message : "";
}

void AbortError::Set(int code, const char *msg) {
	this->code = code;
	std::fprintf(stderr, "PANIC (%d): %s\n", code, msg);
	std::abort();
}

AbortError DefaultError;

} // namespace InterLua
<|endoftext|>


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

#include <fstream>
#include <iostream>
#include <limits>

#include "FeatureSqueeze/stringutil.hh"
#include "FeatureSqueeze/DataSet.hh"
#include "FeatureSqueeze/Logger.hh"
#include "FeatureSqueeze/feature_selection.hh"

#include "ProgramOptions.hh"

using namespace std;

void usage(string const &programName)
{
	cerr << "Usage: " << programName << " [OPTION] dataset" << endl << endl <<
		"  -a val\t Alpha convergence threshold (default: 1e-6)" << endl <<
		"  -f\t\t Fast selection algorithm (do not recalculate all gains)" << endl <<
		"  -g val\t Gain threshold (default: 1e-6)" << endl <<
		"  -n val\t Maximum number of features" << endl <<
		"  -o\t\t Find overlap (incompatible with -f)" << endl << endl;
}

int main(int argc, char *argv[])
{
	fsqueeze::ProgramOptions programOptions(argc, argv, "a:fg:n:o");

	if (programOptions.arguments().size() != 1)
	{
		usage(programOptions.programName());
		return 1;
	}

	if (programOptions.option('o') && programOptions.option('f'))
	{
		cerr << "Overlap detection (-o) and fast selection(-f) cannot be used " <<
			"simultaneausly!" << endl << endl;
		return 1;
	}

	double alphaThreshold = 1e-6;
	if (programOptions.option('a'))
		alphaThreshold = fsqueeze::parseString<double>(programOptions.optionValue('a'));

	double gradientThreshold = 1e-6;
	if (programOptions.option('g'))
		gradientThreshold = fsqueeze::parseString<double>(programOptions.optionValue('g'));

	size_t nFeatures = numeric_limits<size_t>::max();
	if (programOptions.option('n'))
		nFeatures = fsqueeze::parseString<size_t>(programOptions.optionValue('n'));

	cerr << "Reading data... ";

	ifstream dataStream(programOptions.arguments()[0].c_str());
	if (!dataStream)
	{
		cerr << "Error opening input file!" << endl;
		return 1;
	}

	fsqueeze::DataSet ds = fsqueeze::DataSet::readTADMDataSet(dataStream);

	cerr << "done!" << endl;

	fsqueeze::Logger logger(cout, cerr);
	if (programOptions.option('f'))
		fsqueeze::fastFeatureSelection(ds, logger, alphaThreshold, gradientThreshold, nFeatures);
	else
		fsqueeze::featureSelection(ds, logger, alphaThreshold, gradientThreshold, nFeatures,
			programOptions.option('o'));

	return 0;
}
<commit_msg>Output active and total number of features.<commit_after>/*
 * Copyright (c) 2009 Daniël de Kok
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
 * MA 02110-1301 USA
 */

#include <fstream>
#include <iostream>
#include <limits>

#include "FeatureSqueeze/stringutil.hh"
#include "FeatureSqueeze/DataSet.hh"
#include "FeatureSqueeze/Logger.hh"
#include "FeatureSqueeze/feature_selection.hh"

#include "ProgramOptions.hh"

using namespace std;

void usage(string const &programName)
{
	cerr << "Usage: " << programName << " [OPTION] dataset" << endl << endl <<
		"  -a val\t Alpha convergence threshold (default: 1e-6)" << endl <<
		"  -f\t\t Fast selection algorithm (do not recalculate all gains)" << endl <<
		"  -g val\t Gain threshold (default: 1e-6)" << endl <<
		"  -n val\t Maximum number of features" << endl <<
		"  -o\t\t Find overlap (incompatible with -f)" << endl << endl;
}

int main(int argc, char *argv[])
{
	fsqueeze::ProgramOptions programOptions(argc, argv, "a:fg:n:o");

	if (programOptions.arguments().size() != 1)
	{
		usage(programOptions.programName());
		return 1;
	}

	if (programOptions.option('o') && programOptions.option('f'))
	{
		cerr << "Overlap detection (-o) and fast selection(-f) cannot be used " <<
			"simultaneausly!" << endl << endl;
		return 1;
	}

	double alphaThreshold = 1e-6;
	if (programOptions.option('a'))
		alphaThreshold = fsqueeze::parseString<double>(programOptions.optionValue('a'));

	double gradientThreshold = 1e-6;
	if (programOptions.option('g'))
		gradientThreshold = fsqueeze::parseString<double>(programOptions.optionValue('g'));

	size_t nFeatures = numeric_limits<size_t>::max();
	if (programOptions.option('n'))
		nFeatures = fsqueeze::parseString<size_t>(programOptions.optionValue('n'));

	cerr << "Reading data... ";

	ifstream dataStream(programOptions.arguments()[0].c_str());
	if (!dataStream)
	{
		cerr << "Error opening input file!" << endl;
		return 1;
	}

	fsqueeze::DataSet ds = fsqueeze::DataSet::readTADMDataSet(dataStream);

	cerr << "done!" << endl;

	fsqueeze::Logger logger(cout, cerr);
	logger.error() << "Dynamic features: "<< ds.features().size() << "/" <<
		ds.nFeatures() << endl;

	if (programOptions.option('f'))
		fsqueeze::fastFeatureSelection(ds, logger, alphaThreshold, gradientThreshold, nFeatures);
	else
		fsqueeze::featureSelection(ds, logger, alphaThreshold, gradientThreshold, nFeatures,
			programOptions.option('o'));

	return 0;
}
<|endoftext|>


<commit_before>// -*- C++ -*-
//----------------------------------------------------------------------
//
//                  William S. Klug & Luigi Perotti
//                University of California Los Angeles
//                  (C) 2010 All Rights Reserved
//
//----------------------------------------------------------------------
#include <string>
#include <fstream>
#include <blitz/array-impl.h>
#include "VoomMath.h"
#include "ProteinBody.h"

#if defined(_OPENMP)
#include <omp.h>
#endif

#ifdef WITH_MPI
#include <mpi.h>
#endif

namespace voom
{
  ProteinBody::ProteinBody(vector<ProteinNode *> & Proteins, ProteinPotential * Mat, double SearchR):
    _proteins(Proteins), _mat(Mat), _searchR(SearchR)
  {

#ifdef WITH_MPI
    MPI_Comm_size( MPI_COMM_WORLD, &_nProcessors );
    MPI_Comm_rank( MPI_COMM_WORLD, &_processorRank );
#endif

    // // Initialize Body.h containers
    // _nodes.insert(_nodes.begin(), DefNodes.begin(), DefNodes.end() );
    // for(ConstNodeIterator n = _nodes.begin(); n != _nodes.end(); n++) {
    //   _dof+=(*n)->dof();
    // }

    // Initialize protein objects
    for(uint i = 0; i < Proteins.size(); i++)
    {
      ProteinNode * A = Proteins[i];
      vector<ProteinNode *> domain;
      // Find neighbors of A
      for(uint j = 0; j < Proteins.size(); j++)
      {
	if( i != j && A->getDistance(Proteins[j]) <= _searchR) {
	  domain.push_back(Proteins[j]);
	}
      }

      _elements.push_back(domain);
    }

  }; // ProteinBody constructor

  void ProteinBody::recomputeNeighbors(const double searchR) {
    _searchR = searchR;

    // Initialize protein objects
    for(uint i = 0; i < _proteins.size(); i++)
    {
      ProteinNode * A = _proteins[i];
      vector<ProteinNode *> domain;
      // Find neighbors of A
      for(uint j = 0; j < _proteins.size(); j++)
      {
	if( i != j && A->getDistance(_proteins[j]) <= _searchR) {
	  domain.push_back(_proteins[j]);
	}
      }

      _elements[i] = domain;
    }

  };

  //! Compute E0, E1, E2
  void ProteinBody::compute( bool f0, bool f1, bool f2 )
  {
    // Initialize energy to be zero
    if(f0) {
      _energy = 0.0;

      // Loop over material objects
      for (uint i = 0; i < _elements.size(); i++)
      {
	ProteinNode * A = _proteins[i];
	vector<ProteinNode *> domain = _elements[i];
	for (uint j = 0; j < domain.size(); j++)
	{
	  _energy += _mat->computeEnergy(A, domain[j]);
	}
      }
    }

    return;
  };

} // namespace voom
<commit_msg>Particle body<commit_after>// -*- C++ -*-
//----------------------------------------------------------------------
//
//                  William S. Klug & Luigi Perotti
//                University of California Los Angeles
//                  (C) 2010 All Rights Reserved
//
//----------------------------------------------------------------------
#include <string>
#include <fstream>
#include <blitz/array-impl.h>
#include "VoomMath.h"
#include "ProteinBody.h"

#if defined(_OPENMP)
#include <omp.h>
#endif

#ifdef WITH_MPI
#include <mpi.h>
#endif

namespace voom
{
  ProteinBody::ProteinBody(vector<ProteinNode *> & Proteins, ProteinPotential * Mat, double SearchR, double Pressure):
    _proteins(Proteins), _mat(Mat), _searchR(SearchR), _pressure(Pressure)
  {

#ifdef WITH_MPI
    MPI_Comm_size( MPI_COMM_WORLD, &_nProcessors );
    MPI_Comm_rank( MPI_COMM_WORLD, &_processorRank );
#endif

    // // Initialize Body.h containers
    // _nodes.insert(_nodes.begin(), DefNodes.begin(), DefNodes.end() );
    // for(ConstNodeIterator n = _nodes.begin(); n != _nodes.end(); n++) {
    //   _dof+=(*n)->dof();
    // }

    // Initialize protein objects
    for(uint i = 0; i < Proteins.size(); i++)
    {
      ProteinNode * A = Proteins[i];
      vector<ProteinNode *> domain;
      // Find neighbors of A
      for(uint j = 0; j < Proteins.size(); j++)
      {
	if( i != j && A->getDistance(Proteins[j]) <= _searchR) {
	  domain.push_back(Proteins[j]);
	}
      }

      _prElements.push_back(domain);
    }

  }; // ProteinBody constructor

  void ProteinBody::recomputeNeighbors(const double searchR) {
    _searchR = searchR;

    // Initialize protein objects
    for(uint i = 0; i < _proteins.size(); i++)
    {
      ProteinNode * A = _proteins[i];
      vector<ProteinNode *> domain;
      // Find neighbors of A
      for(uint j = 0; j < _proteins.size(); j++)
      {
	if( i != j && A->getDistance(_proteins[j]) <= _searchR) {
	  domain.push_back(_proteins[j]);
	}
      }

      _prElements[i] = domain;
    }

  };

  //! Compute E0, E1, E2
  void ProteinBody::compute( bool f0, bool f1, bool f2 )
  {
    // Initialize energy to be zero
    if(f0) {
      _energy = 0.0;

      // Loop over protein elements
      for (uint i = 0; i < _prElements.size(); i++)
      {
	ProteinNode * A = _proteins[i];
	vector<ProteinNode *> domain = _prElements[i];
	for (uint j = 0; j < domain.size(); j++)
	{
	  _energy += _mat->computeEnergy(A, domain[j]);
	}
      }
      _energy -= _pressure*pow(_mat->getEquilibriumR(), 2.0);
    } // if(f0) loop

  };

  double ProteinBody::computedWdEqPar()
  {
    double dWdEqPar = 0.0;
    // Loop over protein elements
    for (uint i = 0; i < _prElements.size(); i++)
    {
      ProteinNode * A = _proteins[i];
      vector<ProteinNode *> domain = _prElements[i];
      for (uint j = 0; j < domain.size(); j++)
      {
	dWdEqPar += _mat->computedWdEqPar(A, domain[j]);
      }
    }
    return dWdEqPar;
  };

  double ProteinBody::computeddWddEqPar()
  {
    double ddWddEqPar = 0.0;
    // Loop over protein elements
    for (uint i = 0; i < _prElements.size(); i++)
    {
      ProteinNode * A = _proteins[i];
      vector<ProteinNode *> domain = _prElements[i];
      for (uint j = 0; j < domain.size(); j++)
      {
	ddWddEqPar += _mat->computeddWddEqPar(A, domain[j]);
      }
    }
    return ddWddEqPar;
  }

  // reset Equilibrium parameter
  void ProteinBody::resetEquilibrium()
  {
    double a_prev = _mat->getEquilibriumParam(), a_new = 0.0;
    double a_initial = a_prev;
    double error = 1.0, tol = 1.0e-8;
    unsigned int iter = 0, MaxIter = 100;

    while (error > tol && iter < MaxIter)
    {
      a_new = a_prev - this->computedWdEqPar()/this->computeddWddEqPar();
      error = fabs(a_new-a_prev);
      iter++;
      a_prev = a_new;
      _mat->setEquilibriumParam(a_new);
    }

    cout << endl << "ProteinBody reset equilibrium" << endl;
    cout << "Iterations = " << iter << endl;
    cout << "Error      = " << error << endl;
    cout << "Previous EQ param. = " << a_initial << " New EQ param. = " << a_new << endl << endl;
  }

} // namespace voom
<|endoftext|>


<commit_before>/*
 *    Copyright (C) 2013, Jules Colding <jcolding@gmail.com>.
 *
 *    All Rights Reserved.
 */

/*
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 *     (1) Redistributions of source code must retain the above
 *     copyright notice, this list of conditions and the following
 *     disclaimer.
 *
 *     (2) Redistributions in binary form must reproduce the above
 *     copyright notice, this list of conditions and the following
 *     disclaimer in the documentation and/or other materials provided
 *     with the distribution.
 *
 *     (3) Neither the name of the copyright holder nor the names of
 *     its contributors may be used to endorse or promote products
 *     derived from this software without specific prior written
 *     permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS
 * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
 * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 */

#include <inttypes.h>
#include <stdlib.h>
#include <unistd.h>

#ifdef HAVE_CONFIG_H
    #include "ac_config.h"
#endif
#include "stdlib/log/log.h"
#include "db_utils.h"

#define CREATE_RECV_MSG_TABLE "CREATE TABLE IF NOT EXISTS RECV_MESSAGES (seqnum INTEGER PRIMARY KEY, timestamp INTEGER DEFAULT CURRENT_TIMESTAMP, msg BLOB)"
#define CREATE_SENT_MSG_TABLE "CREATE TABLE IF NOT EXISTS SENT_MESSAGES (seqnum INTEGER PRIMARY KEY, timestamp INTEGER DEFAULT CURRENT_TIMESTAMP, msg_type TEXT, partial_msg BLOB)"
#define INSERT_RECV_MESSAGE "INSERT INTO RECV_MESSAGES(seqnum, msg) VALUES(?1, ?2)"
#define INSERT_SENT_MESSAGE "INSERT INTO SENT_MESSAGES(seqnum, msg_type, partial_msg) VALUES(?1, ?2, ?3)"
#define SELECT_MAX_RECV_SEQNUM "SELECT MAX(seqnum) FROM RECV_MESSAGES"
#define SELECT_MAX_SENT_SEQNUM "SELECT MAX(seqnum) FROM SENT_MESSAGES"

int
MsgDB::open(void)
{
        int ret;
        char *err_msg = NULL;

        if (db_)
                return 1;

        if (!db_path_)
                return 0;

        ret = sqlite3_open(db_path_, &db_);
        if (SQLITE_OK != ret) {
                M_ALERT("could not open local database");
                goto err;
        }

        ret = sqlite3_exec(db_, CREATE_RECV_MSG_TABLE, NULL, NULL, &err_msg);
        if (SQLITE_OK != ret) {
                M_ALERT("could create recv_msg table");
                goto err;
        }

        ret = sqlite3_exec(db_, CREATE_SENT_MSG_TABLE, NULL, NULL, &err_msg);
        if (SQLITE_OK != ret) {
                M_ALERT("could create sent_msg table");
                goto err;
        }

        ret = sqlite3_prepare_v2(db_, INSERT_RECV_MESSAGE, -1,  &insert_recv_msg_statement, NULL);
        if (SQLITE_OK != ret) {
                M_ALERT("could prepare insert recv msg statement");
                goto err;
        }

        ret = sqlite3_prepare_v2(db_, INSERT_SENT_MESSAGE, -1,  &insert_sent_msg_statement, NULL);
        if (SQLITE_OK != ret) {
                M_ALERT("could prepare insert recv msg statement");
                goto err;
        }

        ret = sqlite3_prepare_v2(db_, SELECT_MAX_RECV_SEQNUM, -1,  &max_recv_seqnum_statement, NULL);
        if (SQLITE_OK != ret) {
                M_ALERT("could prepare max recv seqnum statement");
                goto err;
        }

        ret = sqlite3_prepare_v2(db_, SELECT_MAX_SENT_SEQNUM, -1,  &max_sent_seqnum_statement, NULL);
        if (SQLITE_OK != ret) {
                M_ALERT("could prepare max sent seqnum statement");
                goto err;
        }

        return 1;

err:
        if (SQLITE_OK != ret) {
                if (err_msg) {
                        M_ALERT("local database operation failed: %s", err_msg);
                } else {
                        M_ALERT("local database operation failed: %s", sqlite3_errstr(ret));
                }
        }
        sqlite3_free(err_msg);
        if (!this->close()) {
                M_ALERT("could not close local database - aborting");
                abort();
        }

        return 0;
}

int
MsgDB::close(void)
{
        int cnt = 0;
        int ret;

        if (!db_)
                return 1;

        sqlite3_finalize(insert_recv_msg_statement);
        sqlite3_finalize(insert_sent_msg_statement);
        sqlite3_finalize(max_recv_seqnum_statement);
        sqlite3_finalize(max_sent_seqnum_statement);
        insert_recv_msg_statement = NULL;
        insert_sent_msg_statement = NULL;
        max_recv_seqnum_statement = NULL;
        max_sent_seqnum_statement = NULL;

close_db:
        ret = sqlite3_close(db_);
        switch (ret) {
        case SQLITE_OK:
                break;
        case SQLITE_BUSY:
                ++cnt;
                if (5 == cnt) {
                        M_ALERT("SQLITE_BUSY for too long - aborting");
                        return 0;
                }
                sleep(1);
                goto close_db;
        case SQLITE_MISUSE:
                M_ALERT("could not close local cache: SQLITE_MISUSE");
                return 0;
        default:
                M_ALERT("trouble closing local cache: %s", sqlite3_errstr(ret));
                return 0;
        }
        db_ = NULL;

        return 1;
}

int
MsgDB::store_sent_msg(const uint64_t seqnum,
                      const uint64_t len,
                      const uint8_t * const msg,
                      const char * const msg_type)
{
        int ret = SQLITE_OK;

        if (!db_)
                return 0;

        ret = sqlite3_bind_int64(insert_sent_msg_statement, 1, seqnum);
        if (SQLITE_OK != ret) {
                M_ALERT("could not bind into sent msg statement: %s", sqlite3_errstr(ret));
                goto out;
        }

        ret = sqlite3_bind_text(insert_sent_msg_statement, 2, msg_type, -1, SQLITE_TRANSIENT);
        if (SQLITE_OK != ret) {
                M_ALERT("could not bind into sent msg statement: %s", sqlite3_errstr(ret));
                goto out;
        }

        ret = sqlite3_bind_blob(insert_sent_msg_statement, 3, msg, len, SQLITE_TRANSIENT);
        if (SQLITE_OK != ret) {
                M_ALERT("could not bind into sent msg statement: %s", sqlite3_errstr(ret));
                goto out;
        }

        ret = sqlite3_step(insert_sent_msg_statement);
        if (SQLITE_DONE != ret) {
                M_ALERT("could not step sent msg statement: (%d) %s - %s", ret, sqlite3_errstr(ret), sqlite3_errmsg(db_));
                goto out;
        }

out:
        sqlite3_clear_bindings(insert_sent_msg_statement);
        sqlite3_reset(insert_sent_msg_statement);

        return ((SQLITE_DONE == ret) ? 1 : 0);
}

int
MsgDB::store_recv_msg(const uint64_t seqnum,
                      const uint64_t len,
                      const uint8_t * const msg)
{
        int ret = SQLITE_OK;

        if (!db_)
                return 0;

        ret = sqlite3_bind_int64(insert_recv_msg_statement, 1, seqnum);
        if (SQLITE_OK != ret) {
                M_ALERT("could not bind into recv msg statement: %s", sqlite3_errstr(ret));
                goto out;
        }

        ret = sqlite3_bind_blob(insert_recv_msg_statement, 2, msg, len, SQLITE_TRANSIENT);
        if (SQLITE_OK != ret) {
                M_ALERT("could not bind into recv msg statement: %s", sqlite3_errstr(ret));
                goto out;
        }

        ret = sqlite3_step(insert_recv_msg_statement);
        if (SQLITE_DONE != ret) {
                M_ALERT("could not step recv msg statement: %s", sqlite3_errstr(ret));
                goto out;
        }

out:
        sqlite3_clear_bindings(insert_recv_msg_statement);
        sqlite3_reset(insert_recv_msg_statement);

        return ((SQLITE_DONE == ret) ? 1 : 0);
}

int
MsgDB::get_latest_recv_seqnum(uint64_t & seqnum) const
{
        int ret;

        if (!db_)
                return 0;

        ret = sqlite3_step(max_recv_seqnum_statement);
        switch (ret) {
        case SQLITE_ROW:
                break;
        case SQLITE_DONE:
                seqnum = 0;
                goto out;
        default:
                M_ALERT("error getting latest recv seqnum");
                goto err;
        }
        seqnum = sqlite3_column_int64(max_recv_seqnum_statement, 0);
out:
        sqlite3_reset(max_recv_seqnum_statement);
        return 1;

err:
        sqlite3_reset(max_recv_seqnum_statement);
        M_ALERT("could not get latest recv seqnum: %s", sqlite3_errstr(ret));
        return 0;
}

int
MsgDB::get_latest_sent_seqnum(uint64_t & seqnum) const
{
        int ret;

        ret = sqlite3_step(max_sent_seqnum_statement);
        switch (ret) {
        case SQLITE_ROW:
                break;
        case SQLITE_DONE:
                seqnum = 0;
                goto out;
        default:
                M_ALERT("error getting latest sent seqnum");
                goto err;
        }
        seqnum = sqlite3_column_int64(max_sent_seqnum_statement, 0);
out:
        sqlite3_reset(max_sent_seqnum_statement);
        return 1;

err:
        sqlite3_reset(max_sent_seqnum_statement);
        M_ALERT("could not get latest sent seqnum: %s", sqlite3_errstr(ret));
        return 0;
}

std::vector<std::vector<uint8_t> > *
MsgDB::get_recv_msgs(uint64_t /*start*/,
                     uint64_t /*end*/) const
{
        std::vector<std::vector<uint8_t> > *retv = NULL;

        if (!db_)
                return NULL;

        return retv;
}
<commit_msg>Changed sqlite mode to WAL<commit_after>/*
 *    Copyright (C) 2013, Jules Colding <jcolding@gmail.com>.
 *
 *    All Rights Reserved.
 */

/*
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 *     (1) Redistributions of source code must retain the above
 *     copyright notice, this list of conditions and the following
 *     disclaimer.
 *
 *     (2) Redistributions in binary form must reproduce the above
 *     copyright notice, this list of conditions and the following
 *     disclaimer in the documentation and/or other materials provided
 *     with the distribution.
 *
 *     (3) Neither the name of the copyright holder nor the names of
 *     its contributors may be used to endorse or promote products
 *     derived from this software without specific prior written
 *     permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS
 * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
 * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 */

#include <inttypes.h>
#include <stdlib.h>
#include <unistd.h>

#ifdef HAVE_CONFIG_H
    #include "ac_config.h"
#endif
#include "stdlib/log/log.h"
#include "db_utils.h"

#define CREATE_RECV_MSG_TABLE "CREATE TABLE IF NOT EXISTS RECV_MESSAGES (seqnum INTEGER PRIMARY KEY, timestamp INTEGER DEFAULT CURRENT_TIMESTAMP, msg BLOB)"
#define CREATE_SENT_MSG_TABLE "CREATE TABLE IF NOT EXISTS SENT_MESSAGES (seqnum INTEGER PRIMARY KEY, timestamp INTEGER DEFAULT CURRENT_TIMESTAMP, msg_type TEXT, partial_msg BLOB)"
#define INSERT_RECV_MESSAGE "INSERT INTO RECV_MESSAGES(seqnum, msg) VALUES(?1, ?2)"
#define INSERT_SENT_MESSAGE "INSERT INTO SENT_MESSAGES(seqnum, msg_type, partial_msg) VALUES(?1, ?2, ?3)"
#define SELECT_MAX_RECV_SEQNUM "SELECT MAX(seqnum) FROM RECV_MESSAGES"
#define SELECT_MAX_SENT_SEQNUM "SELECT MAX(seqnum) FROM SENT_MESSAGES"

int
MsgDB::open(void)
{
        int ret;
        char *err_msg = NULL;

        if (db_)
                return 1;

        if (!db_path_)
                return 0;

        ret = sqlite3_open(db_path_, &db_);
        if (SQLITE_OK != ret) {
                M_ALERT("could not open local database");
                goto err;
        }
	sqlite3_exec(db_, "PRAGMA journal_mode=WAL", NULL, NULL, &err_msg);
        if (SQLITE_OK != ret) {
                M_ALERT("could not enable WAL");
		/* continuing in default mode */
        }

        ret = sqlite3_exec(db_, CREATE_RECV_MSG_TABLE, NULL, NULL, &err_msg);
        if (SQLITE_OK != ret) {
                M_ALERT("could not create recv_msg table");
                goto err;
        }

        ret = sqlite3_exec(db_, CREATE_SENT_MSG_TABLE, NULL, NULL, &err_msg);
        if (SQLITE_OK != ret) {
                M_ALERT("could not create sent_msg table");
                goto err;
        }

        ret = sqlite3_prepare_v2(db_, INSERT_RECV_MESSAGE, -1,  &insert_recv_msg_statement, NULL);
        if (SQLITE_OK != ret) {
                M_ALERT("could not prepare insert recv msg statement");
                goto err;
        }

        ret = sqlite3_prepare_v2(db_, INSERT_SENT_MESSAGE, -1,  &insert_sent_msg_statement, NULL);
        if (SQLITE_OK != ret) {
                M_ALERT("could not prepare insert recv msg statement");
                goto err;
        }

        ret = sqlite3_prepare_v2(db_, SELECT_MAX_RECV_SEQNUM, -1,  &max_recv_seqnum_statement, NULL);
        if (SQLITE_OK != ret) {
                M_ALERT("could not prepare max recv seqnum statement");
                goto err;
        }

        ret = sqlite3_prepare_v2(db_, SELECT_MAX_SENT_SEQNUM, -1,  &max_sent_seqnum_statement, NULL);
        if (SQLITE_OK != ret) {
                M_ALERT("could not prepare max sent seqnum statement");
                goto err;
        }

        return 1;

err:
        if (SQLITE_OK != ret) {
                if (err_msg) {
                        M_ALERT("local database operation failed: %s", err_msg);
                } else {
                        M_ALERT("local database operation failed: %s", sqlite3_errstr(ret));
                }
        }
        sqlite3_free(err_msg);
        if (!this->close()) {
                M_ALERT("could not close local database - aborting");
                abort();
        }

        return 0;
}

int
MsgDB::close(void)
{
        int cnt = 0;
        int ret;

        if (!db_)
                return 1;

        sqlite3_finalize(insert_recv_msg_statement);
        sqlite3_finalize(insert_sent_msg_statement);
        sqlite3_finalize(max_recv_seqnum_statement);
        sqlite3_finalize(max_sent_seqnum_statement);
        insert_recv_msg_statement = NULL;
        insert_sent_msg_statement = NULL;
        max_recv_seqnum_statement = NULL;
        max_sent_seqnum_statement = NULL;

close_db:
        ret = sqlite3_close(db_);
        switch (ret) {
        case SQLITE_OK:
                break;
        case SQLITE_BUSY:
                ++cnt;
                if (5 == cnt) {
                        M_ALERT("SQLITE_BUSY for too long - aborting");
                        return 0;
                }
                sleep(1);
                goto close_db;
        case SQLITE_MISUSE:
                M_ALERT("could not close local cache: SQLITE_MISUSE");
                return 0;
        default:
                M_ALERT("trouble closing local cache: %s", sqlite3_errstr(ret));
                return 0;
        }
        db_ = NULL;

        return 1;
}

int
MsgDB::store_sent_msg(const uint64_t seqnum,
                      const uint64_t len,
                      const uint8_t * const msg,
                      const char * const msg_type)
{
        int ret = SQLITE_OK;

        if (!db_)
                return 0;

        ret = sqlite3_bind_int64(insert_sent_msg_statement, 1, seqnum);
        if (SQLITE_OK != ret) {
                M_ALERT("could not bind into sent msg statement: %s", sqlite3_errstr(ret));
                goto out;
        }

        ret = sqlite3_bind_text(insert_sent_msg_statement, 2, msg_type, -1, SQLITE_TRANSIENT);
        if (SQLITE_OK != ret) {
                M_ALERT("could not bind into sent msg statement: %s", sqlite3_errstr(ret));
                goto out;
        }

        ret = sqlite3_bind_blob(insert_sent_msg_statement, 3, msg, len, SQLITE_TRANSIENT);
        if (SQLITE_OK != ret) {
                M_ALERT("could not bind into sent msg statement: %s", sqlite3_errstr(ret));
                goto out;
        }

        ret = sqlite3_step(insert_sent_msg_statement);
        if (SQLITE_DONE != ret) {
                M_ALERT("could not step sent msg statement: (%d) %s - %s", ret, sqlite3_errstr(ret), sqlite3_errmsg(db_));
                goto out;
        }

out:
        sqlite3_clear_bindings(insert_sent_msg_statement);
        sqlite3_reset(insert_sent_msg_statement);

        return ((SQLITE_DONE == ret) ? 1 : 0);
}

int
MsgDB::store_recv_msg(const uint64_t seqnum,
                      const uint64_t len,
                      const uint8_t * const msg)
{
        int ret = SQLITE_OK;

        if (!db_)
                return 0;

        ret = sqlite3_bind_int64(insert_recv_msg_statement, 1, seqnum);
        if (SQLITE_OK != ret) {
                M_ALERT("could not bind into recv msg statement: %s", sqlite3_errstr(ret));
                goto out;
        }

        ret = sqlite3_bind_blob(insert_recv_msg_statement, 2, msg, len, SQLITE_TRANSIENT);
        if (SQLITE_OK != ret) {
                M_ALERT("could not bind into recv msg statement: %s", sqlite3_errstr(ret));
                goto out;
        }

        ret = sqlite3_step(insert_recv_msg_statement);
        if (SQLITE_DONE != ret) {
                M_ALERT("could not step recv msg statement: %s", sqlite3_errstr(ret));
                goto out;
        }

out:
        sqlite3_clear_bindings(insert_recv_msg_statement);
        sqlite3_reset(insert_recv_msg_statement);

        return ((SQLITE_DONE == ret) ? 1 : 0);
}

int
MsgDB::get_latest_recv_seqnum(uint64_t & seqnum) const
{
        int ret;

        if (!db_)
                return 0;

        ret = sqlite3_step(max_recv_seqnum_statement);
        switch (ret) {
        case SQLITE_ROW:
                break;
        case SQLITE_DONE:
                seqnum = 0;
                goto out;
        default:
                M_ALERT("error getting latest recv seqnum");
                goto err;
        }
        seqnum = sqlite3_column_int64(max_recv_seqnum_statement, 0);
out:
        sqlite3_reset(max_recv_seqnum_statement);
        return 1;

err:
        sqlite3_reset(max_recv_seqnum_statement);
        M_ALERT("could not get latest recv seqnum: %s", sqlite3_errstr(ret));
        return 0;
}

int
MsgDB::get_latest_sent_seqnum(uint64_t & seqnum) const
{
        int ret;

        ret = sqlite3_step(max_sent_seqnum_statement);
        switch (ret) {
        case SQLITE_ROW:
                break;
        case SQLITE_DONE:
                seqnum = 0;
                goto out;
        default:
                M_ALERT("error getting latest sent seqnum");
                goto err;
        }
        seqnum = sqlite3_column_int64(max_sent_seqnum_statement, 0);
out:
        sqlite3_reset(max_sent_seqnum_statement);
        return 1;

err:
        sqlite3_reset(max_sent_seqnum_statement);
        M_ALERT("could not get latest sent seqnum: %s", sqlite3_errstr(ret));
        return 0;
}

std::vector<std::vector<uint8_t> > *
MsgDB::get_recv_msgs(uint64_t /*start*/,
                     uint64_t /*end*/) const
{
        std::vector<std::vector<uint8_t> > *retv = NULL;

        if (!db_)
                return NULL;

        return retv;
}
<|endoftext|>


<commit_before>#include <iostream>
#include <vector>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <string.h>
#include <boost/tokenizer.hpp>

using namespace std;
using namespace boost;

bool validConnector(string);

typedef tokenizer<char_separator<char> > toknizer;
int main()
{
	while(1)
	{
		//prints simple prompt, gets user input
		cout << "$ ";
		string userinput;
		getline(cin,userinput);

		//declares tokenizer and storage for tokens
		string cmd=""; //gathers entire command until connector or end
		string cnntr=""; //will hold connector
		vector<string> cmdvect;

		char_separator<char> delim(" ","&|#;");
		toknizer parser(userinput,delim);

		for(toknizer::iterator it=parser.begin();it!=parser.end();++it)
		{
		//cout << "it: "<< *it << endl;
			if(*it=="exit")	{ exit(0);} //exits program
			if(*it=="#") { break; } //finish reading input if comment
			if(*it=="&" || *it=="|" || *it==";")
			{
				if(!cmd.empty())
				{
					cmdvect.push_back(cmd);
					cmd.clear();
					cnntr+=(*it);
				}
				else if(cmd.empty() && !cnntr.empty())
				{
					cnntr+=(*it);
				}
				//empty out cnntr for next time
				//cnntr.clear();
				//cmd.clear();
			}
			//if none of cases above apply, can be assumed to be command
			else
			{
				if(!cnntr.empty())
				{
					cmdvect.push_back(cnntr);
					cmd+=(*it);
					cnntr.clear();
				}
				else
				{
					cmd+=(*it);
				}
			}

		}

		cmdvect.push_back(cmd); //adds last of input

		cout << "---------------------------------" << endl;
		for(unsigned i=0;i<cmdvect.size();++i)
		{
			cout << cmdvect.at(i) << endl;
		}
		cout << "---------------------------------" << endl;
		//if exit command is found, exit shell
		//fork based on commands and connectors, then use execvp
		//once child processes succeed or fail, return to parent
		//print out newline and clear buffer?

	}
	//end of while loop

	return 0;
}

<commit_msg>Parser bugs fixed<commit_after>#include <iostream>
#include <vector>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <string.h>
#include <boost/tokenizer.hpp>

using namespace std;
using namespace boost;

bool validConnector(string);

typedef tokenizer<char_separator<char> > toknizer;
int main()
{
	while(1)
	{
		//prints simple prompt, gets user input
		cout << "$ ";
		string userinput;
		getline(cin,userinput);

		//declares tokenizer and storage for tokens
		string cmd=""; //gathers entire command until connector or end
		string cnntr=""; //will hold connector
		vector<string> cmdvect;

		char_separator<char> delim(" ","&|#;");
		toknizer parser(userinput,delim);

		for(toknizer::iterator it=parser.begin();it!=parser.end();++it)
		{
		//cout << "it: "<< *it << endl;
			//if(*it=="exit")	{ exit(0);}
			if(*it=="#") { break; } //finish reading input if comment
			if(*it=="&" || *it=="|" || *it==";")
			{
				if(!cmd.empty())
				{
					cmdvect.push_back(cmd);
					cmd.clear();
					cnntr+=(*it);
				}
				else if(cmd.empty() && !cnntr.empty())
				{
					cnntr+=(*it);
				}
				//empty out cnntr for next time
				//cnntr.clear();
				//cmd.clear();
			}
			//if none of cases above apply, can be assumed to be command
			else
			{
				if(!cnntr.empty())
				{
					cmdvect.push_back(cnntr);
					cmd+=(*it);
					cnntr.clear();
					//"empties" connector and resumes building command
				}
				else //otherwise, just keep building command
				{
					cmd+=(*it);
					cmd+=" "; //spaces out commands like "ls -a"
				}
			}

		}
		if(!cmd.empty())
		{
			cmdvect.push_back(cmd); //adds last of input
		}
		if(cnntr==";")
		{
			cmdvect.push_back(cnntr);//and trailing ; connectors
		}

		cout << "---------------------------------" << endl;
		for(unsigned i=0;i<cmdvect.size();++i)
		{
			cout << cmdvect.at(i) << endl;
		}
		cout << "---------------------------------" << endl;
		//if exit command is found, exit shell
		//fork based on commands and connectors, then use execvp
		//once child processes succeed or fail, return to parent
		//print out newline and clear buffer?

	}
	//end of while loop

	return 0;
}

<|endoftext|>


<commit_before>#include <iostream>
#include <vector>
#include <string>
#include <unistd.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <string.h>
#include <boost/tokenizer.hpp>

using namespace std;
using namespace boost;

bool isConnector(string&);
bool validConnector(string&);
void executor(vector<string> &vect);

typedef tokenizer<char_separator<char> > toknizer;
int main()
{
	while(1)
	{
		//prints simple prompt, gets user input
		cout << "$ ";
		string userinput;
		getline(cin,userinput);

		//declares tokenizer and storage for tokens
		string cmd=""; //gathers entire command until connector or end
		string cnntr=""; //will hold connector
		vector<string> cmdvect;

		char_separator<char> delim(" ","&|#;");
		toknizer parser(userinput,delim);

		for(toknizer::iterator it=parser.begin();it!=parser.end();++it)
		{
		//cout << "it: "<< *it << endl;
			//if(*it=="exit")	{ exit(0);}
			if(*it=="#") { break; } //finish reading input if comment
			if(*it=="&" || *it=="|" || *it==";")
			{
				if(!cmd.empty())
				{
					cmdvect.push_back(cmd);
					cmd.clear();
					cnntr+=(*it);
				}
				else if(cmd.empty() && !cnntr.empty())
				{
					cnntr+=(*it);
				}
				//empty out cnntr for next time
				//cnntr.clear();
				//cmd.clear();
			}
			//if none of cases above apply, can be assumed to be command
			else
			{
				if(!cnntr.empty())
				{
					cmdvect.push_back(cnntr);
					cmd+=(*it);
					cnntr.clear();
					//"empties" connector and resumes building command
				}
				else //otherwise, just keep building command
				{
					cmd+=(*it);
					cmd+=" "; //spaces out commands like "ls -a"
				}
			}

		}
		if(!cmd.empty())
		{
			cmdvect.push_back(cmd); //adds last of input
		}
		if(cnntr==";")
		{
			cmdvect.push_back(cnntr);//and trailing ; connectors
		}

		executor(cmdvect); //pass in parsed command to be executed (or not)
	}
	//end of while loop

	return 0;
}

void executor(vector<string> &vect)
{
	//bool success; //used in long compound statements
	for(unsigned i=0; i<vect.size();++i)
	{
		if(isConnector(vect.at(i)) && validConnector(vect.at(i)))
		{
			cout << vect.at(i) << "is connector" << endl;
		}
	}

	return;
}

bool isConnector(string &s)
{
	//function just checks if token is supposed to be a connector
	size_t i=s.find("&");
	size_t j=s.find("|");
	size_t k=s.find(";");

	if(i==string::npos && j==string::npos && k==string::npos)
	{
		return false;
	}
	return true;
}

bool validConnector(string &str)
{
	if(str=="&&") { return true; }
	else if(str=="||") { return true;}
	else if(str==";") { return true;}
	return false;
}
<commit_msg>Functions for handling connector syntax added/elaborated<commit_after>#include <iostream>
#include <vector>
#include <string>
#include <unistd.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <string.h>
#include <boost/tokenizer.hpp>

using namespace std;
using namespace boost;

int syntaxCheck(vector<string>&vect);
bool isConnector(string&);
bool validConnector(string&);
void executor(vector<string> &vect);

typedef tokenizer<char_separator<char> > toknizer;
int main()
{
	while(1)
	{
		//prints simple prompt, gets user input
		cout << "$ ";
		string userinput;
		getline(cin,userinput);

		//declares tokenizer and storage for tokens
		string cmd=""; //gathers entire command until connector or end
		string cnntr=""; //will hold connector
		vector<string> cmdvect;

		char_separator<char> delim(" ","&|#;");
		toknizer parser(userinput,delim);

		for(toknizer::iterator it=parser.begin();it!=parser.end();++it)
		{
			//if(*it=="exit")	{ exit(0);}
			if(*it=="#") { break; } //finish reading input if comment
			if(*it=="&" || *it=="|" || *it==";")
			{
				if(!cmd.empty())
				{
					cmdvect.push_back(cmd);
					cmd.clear();
					cnntr+=(*it);
				}
				else if(cmd.empty() && !cnntr.empty())
				{
					cnntr+=(*it);
				}
			}
			//if none of cases above apply, can be assumed to be command
			else
			{
				if(!cnntr.empty())
				{
					cmdvect.push_back(cnntr);
					cmd+=(*it);
					cnntr.clear();
					//"empties" connector and resumes building command
				}
				else //otherwise, just keep building command
				{
					cmd+=(*it);
					cmd+=" "; //spaces out commands like "ls -a"
				}
			}

		} //end tokenizer loop

		if(!cmd.empty())
		{
			cmdvect.push_back(cmd); //adds last of input
		}
		if(!cnntr.empty())
		{
			cmdvect.push_back(cnntr);//and trailing ; connectors
		}

		int x=syntaxCheck(cmdvect);
		if(x==0)
		{
			executor(cmdvect); //pass in parsed command to be executed
		}
	}
	//end of while loop

	return 0;
}

void executor(vector<string> &vect)
{
return;}

int syntaxCheck(vector<string> &vect)
{
	//checks input for invalid syntax in connectors
	for(unsigned i=0; i<vect.size();++i)
	{
		if(isConnector(vect.at(i)))
		{
			//ensures argument for && and || is complete
			if((i==0 || i+1==vect.size()) && vect.at(i)!=";")
			{
				cout << "Connector syntax error: missing argument\n";
				return -1;
			}
			if(!validConnector(vect.at(i)))
			{
				cout << "Connector syntax error: invalid connector\n";
				return -1;
			}
		}
	}
	return 0; //no syntax errors found
}

bool isConnector(string &s)
{
	//function just checks if token is supposed to be a connector
	size_t i=s.find("&");
	size_t j=s.find("|");
	size_t k=s.find(";");

	if(i==string::npos && j==string::npos && k==string::npos)
	{
		return false;
	}
	return true;
}

bool validConnector(string &str)
{
	//only supports few connectors now
	if(str=="&&") { return true; }
	else if(str=="||") { return true;}
	else if(str==";") { return true;}
	return false;
}
<|endoftext|>


<commit_before>#include<iostream>
#include<string.h>
#include<string>
#include<vector>
#include<sys/types.h>
#include<sys/wait.h>
#include<stdio.h>
#include<unistd.h>
#include<stdlib.h>
#include<cstring>
#include<boost/tokenizer.hpp>
#include<algorithm>
#include<iterator>
#include<sstream>

using namespace std;
using namespace boost;

void parse_line(char c_line[], char *command_line[]);
void run_line(char *command_line[]);

 int main()
{
	string str;
	string arg = "";
	 while(1)
	{
		str = "";
		char userName[100] = "";
		if(getlogin_r(userName, sizeof(userName)-1) != 0) //Getting username, and returns null if cant be found
		{
			perror("Error getting username");
		}
		cout << '['  << userName << '@';
		char hostName[100] = "";
		if(gethostname(hostName, sizeof(hostName)-1) != 0) // Getting host name, returns numm if it cannot be found
		{
			perror("Error getting hostname");
		}
		cout << hostName << ']';
		cout << "$";
		getline(cin,str);  //Gets a command
		if(str == "exit")  //If the command is exit the program stops
		{
			 break;
		}
		if(str.size() != 0 && str.at(0) == '#')
		{
			str = "";
		}
		if(str != "")
		{
			for(unsigned i = 0; i < str.size(); i++)
			{
				if(str.at(i) == '#')  //Removes all part of the command after the comment
				{
					str = str.substr(0,i);
				}
			}
			while(str.at(0) == ' ')
			{
				str = str.substr(1,str.size()-1);
			}
			if(str.at(str.size() - 1 ) == ' ')
			{
				str = str.substr(0,str.size()-2);
			}
			char c_line[100];
			char *command_line[64];
			strcpy(c_line,str.c_str());
			c_line[str.size()] = '\0';
			parse_line(c_line, command_line);
			run_line(command_line);
		}

	}
	  return 0;
}

void parse_line(char c_line[], char *command_line[])
{
	while(*c_line != '\0')
	{
		while(*c_line == ' ' || *c_line == '\n' || *c_line == '\t')
		{
			*c_line++ = '\0';
		}
		//if(*c_line == ';')
		//{
			//run_line(command_line);
			//for(int i = 0; i < 64; i++)
			//{
			//	command_line[i] = new char[16];
			//}
			//command_line = new char*[64];
			//for(int i = 0; i < 64; i++)
			//{
			//	delete [] command_line[i];
			//}
			//delete [] command_line;
			//c_line++;
		//}
		*command_line++ = c_line;
		while(*c_line != '\0' && *c_line != ' ' && *c_line != '\n' && *c_line != '\t')
		{
			c_line++;
		}
		*command_line = '\0';
	}
	return;
}

void run_line(char *command_line[])
{
	pid_t pid;
	int status;
	if((pid = fork()) < 0)
	{
		perror("forking failed");
	}
	else if(pid == 0)
	{
		if(execvp(*command_line,command_line) < 0)
		{
			perror("execvp failed");
			exit(1);
		}
	}
	else
	{
		while(wait(&status) != pid)
		;
	}
	return;
}
<commit_msg>took out boost library<commit_after>#include<iostream>
#include<string.h>
#include<string>
#include<vector>
#include<sys/types.h>
#include<sys/wait.h>
#include<stdio.h>
#include<unistd.h>
#include<stdlib.h>
#include<cstring>
#include<algorithm>
#include<iterator>
#include<sstream>

using namespace std;

void parse_line(char c_line[], char *command_line[]);
void run_line(char *command_line[]);

 int main()
{
	string str;
	string arg = "";
	 while(1)
	{
		str = "";
		char userName[100] = "";
		if(getlogin_r(userName, sizeof(userName)-1) != 0) //Getting username, and returns null if cant be found
		{
			perror("Error getting username");
		}
		cout << '['  << userName << '@';
		char hostName[100] = "";
		if(gethostname(hostName, sizeof(hostName)-1) != 0) // Getting host name, returns numm if it cannot be found
		{
			perror("Error getting hostname");
		}
		cout << hostName << ']';
		cout << "$";
		getline(cin,str);  //Gets a command
		if(str == "exit")  //If the command is exit the program stops
		{
			 break;
		}
		if(str.size() != 0 && str.at(0) == '#')
		{
			str = "";
		}
		if(str != "")
		{
			for(unsigned i = 0; i < str.size(); i++)
			{
				if(str.at(i) == '#')  //Removes all part of the command after the comment
				{
					str = str.substr(0,i);
				}
			}
			while(str.at(0) == ' ')
			{
				str = str.substr(1,str.size()-1);
			}
			if(str.at(str.size() - 1 ) == ' ')
			{
				str = str.substr(0,str.size()-2);
			}
			char c_line[100];
			char *command_line[64];
			strcpy(c_line,str.c_str());
			c_line[str.size()] = '\0';
			parse_line(c_line, command_line);
			run_line(command_line);
		}

	}
	  return 0;
}

void parse_line(char c_line[], char *command_line[])
{
	while(*c_line != '\0')
	{
		while(*c_line == ' ' || *c_line == '\n' || *c_line == '\t')
		{
			*c_line++ = '\0';
		}
		//if(*c_line == ';')
		//{
			//run_line(command_line);
			//for(int i = 0; i < 64; i++)
			//{
			//	command_line[i] = new char[16];
			//}
			//command_line = new char*[64];
			//for(int i = 0; i < 64; i++)
			//{
			//	delete [] command_line[i];
			//}
			//delete [] command_line;
			//c_line++;
		//}
		*command_line++ = c_line;
		while(*c_line != '\0' && *c_line != ' ' && *c_line != '\n' && *c_line != '\t')
		{
			c_line++;
		}
		*command_line = '\0';
	}
	return;
}

void run_line(char *command_line[])
{
	pid_t pid;
	int status;
	if((pid = fork()) < 0)
	{
		perror("forking failed");
	}
	else if(pid == 0)
	{
		if(execvp(*command_line,command_line) < 0)
		{
			perror("execvp failed");
			exit(1);
		}
	}
	else
	{
		while(wait(&status) != pid)
		;
	}
	return;
}
<|endoftext|>


<commit_before>
#include <iostream>

#include <chrono>
#include <random>

#include "matrix_connected_components/Algorithm.hpp"
#include "utils/containers/Matrix.hpp"

template <typename T>
struct StringRep {};

template <>
struct StringRep<uint64_t> {
  static constexpr std::string_view value{"uint64_t"};
};

template <>
struct StringRep<int64_t> {
  static constexpr std::string_view value{"int64_t"};
};

int main() {
  // using ValueType = uint64_t;
  // static constexpr int64_t width{6};
  // static constexpr int64_t height{5};
  // utils::containers::Matrix<ValueType> m{height, width, matrix_connected_components::kUnmarkedField<ValueType>};

  // std::vector<std::pair<int64_t, int64_t>> markedFields = {
  //     {0, 0}, {1, 0}, {1, 2}, {1, 3}, {2, 1}, {2, 3}, {3, 1}, {3, 2}, {3, 3}, {4, 4},
  // };

  // for (const auto &[row, column]: markedFields) {
  //   m.get(row, column) = matrix_connected_components::kMarkedField<ValueType>;
  // }
  // for (auto row = 0U; row < height; ++row) {
  //   for (auto column = 0U; column < width; ++column) {
  //     std::cout << static_cast<ValueType>(m.get(row, column)) << ' ';
  //   }
  //   std::cout << std::endl;
  // }
  // std::cout << std::endl;
  // matrix_connected_components::labelConnectedCompnents(m);
  // for (auto row = 0U; row < height; ++row) {
  //   for (auto column = 0U; column < width; ++column) {
  //     std::cout << static_cast<ValueType>(m.get(row, column)) << ' ';
  //   }
  //   std::cout << std::endl;
  // }

  static constexpr int64_t kDimension{20000};
  static constexpr int64_t kNumberOfFields{kDimension * kDimension};

  using ValueType = uint64_t;
  std::mt19937 mt(1); // NOLINTNEXTLINE(cert-msc32-c)
  std::uniform_int_distribution<int64_t> r1(0, kDimension - 1);
  utils::containers::Matrix<ValueType> matrix(kDimension, kDimension,
                                              matrix_connected_components::kUnmarkedField<ValueType>);

  static constexpr int64_t kIterations = kNumberOfFields / 5 * 2;
  for (auto i = 0; i < kIterations; ++i) {
    matrix.get(r1(mt), r1(mt)) = matrix_connected_components::kMarkedField<ValueType>;
  }

  std::cout << "Start " << StringRep<ValueType>::value << '\n';
  std::chrono::steady_clock::time_point begin = std::chrono::steady_clock::now();
  matrix_connected_components::countConnectedComponents(matrix);
  std::chrono::steady_clock::time_point end = std::chrono::steady_clock::now();
  std::cout << "Done\n";

  std::cout << "Time difference = " << std::chrono::duration_cast<std::chrono::milliseconds>(end - begin).count()
            << "[ms]" << std::endl;

  return 0;
}
<commit_msg>Pass the matrix by moving<commit_after>
#include <iostream>

#include <chrono>
#include <random>

#include "matrix_connected_components/Algorithm.hpp"
#include "utils/containers/Matrix.hpp"

template <typename T>
struct StringRep {};

template <>
struct StringRep<uint64_t> {
  static constexpr std::string_view value{"uint64_t"};
};

template <>
struct StringRep<int64_t> {
  static constexpr std::string_view value{"int64_t"};
};

int main() {
  // using ValueType = uint64_t;
  // static constexpr int64_t width{6};
  // static constexpr int64_t height{5};
  // utils::containers::Matrix<ValueType> m{height, width, matrix_connected_components::kUnmarkedField<ValueType>};

  // std::vector<std::pair<int64_t, int64_t>> markedFields = {
  //     {0, 0}, {1, 0}, {1, 2}, {1, 3}, {2, 1}, {2, 3}, {3, 1}, {3, 2}, {3, 3}, {4, 4},
  // };

  // for (const auto &[row, column]: markedFields) {
  //   m.get(row, column) = matrix_connected_components::kMarkedField<ValueType>;
  // }
  // for (auto row = 0U; row < height; ++row) {
  //   for (auto column = 0U; column < width; ++column) {
  //     std::cout << static_cast<ValueType>(m.get(row, column)) << ' ';
  //   }
  //   std::cout << std::endl;
  // }
  // std::cout << std::endl;
  // matrix_connected_components::labelConnectedCompnents(m);
  // for (auto row = 0U; row < height; ++row) {
  //   for (auto column = 0U; column < width; ++column) {
  //     std::cout << static_cast<ValueType>(m.get(row, column)) << ' ';
  //   }
  //   std::cout << std::endl;
  // }

  static constexpr int64_t kDimension{20000};
  static constexpr int64_t kNumberOfFields{kDimension * kDimension};

  using ValueType = uint64_t;
  std::mt19937 mt(1); // NOLINTNEXTLINE(cert-msc32-c)
  std::uniform_int_distribution<int64_t> r1(0, kDimension - 1);
  utils::containers::Matrix<ValueType> matrix(kDimension, kDimension,
                                              matrix_connected_components::kUnmarkedField<ValueType>);

  static constexpr int64_t kIterations = kNumberOfFields / 5 * 2;
  for (auto i = 0; i < kIterations; ++i) {
    matrix.get(r1(mt), r1(mt)) = matrix_connected_components::kMarkedField<ValueType>;
  }

  std::cout << "Start " << StringRep<ValueType>::value << '\n';
  std::chrono::steady_clock::time_point begin = std::chrono::steady_clock::now();
  matrix_connected_components::countConnectedComponents(std::move(matrix));
  std::chrono::steady_clock::time_point end = std::chrono::steady_clock::now();
  std::cout << "Done\n";

  std::cout << "Time difference = " << std::chrono::duration_cast<std::chrono::milliseconds>(end - begin).count()
            << "[ms]" << std::endl;

  return 0;
}
<|endoftext|>