<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: TableFieldControl.cxx,v $
 *
 *  $Revision: 1.9 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-08 16:41:26 $
 *
 *  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
 *
 ************************************************************************/
#ifndef DBAUI_TABLEFIELDCONTROL_HXX
#include "TableFieldControl.hxx"
#endif
#ifndef DBUI_TABLECONTROLLER_HXX
#include "TableController.hxx"
#endif
#ifndef DBAUI_TABLEDESIGNVIEW_HXX
#include "TableDesignView.hxx"
#endif
#ifndef DBAUI_TABLEEDITORCONTROL_HXX
#include "TEditControl.hxx"
#endif
#ifndef DBACCESS_SHARED_DBUSTRINGS_HRC
#include "dbustrings.hrc"
#endif
#ifndef _COM_SUN_STAR_SDBC_XDATABASEMETADATA_HPP_
#include <com/sun/star/sdbc/XDatabaseMetaData.hpp>
#endif
#ifndef _COM_SUN_STAR_BEANS_PROPERTYATTRIBUTE_HPP_
#include <com/sun/star/beans/PropertyAttribute.hpp>
#endif
#ifndef _COMPHELPER_TYPES_HXX_
#include <comphelper/types.hxx>
#endif
#ifndef DBAUI_TYPEINFO_HXX
#include "TypeInfo.hxx"
#endif
#ifndef DBAUI_TOOLS_HXX
#include "UITools.hxx"
#endif

using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::beans;
using namespace ::com::sun::star::util;
using namespace ::com::sun::star::lang;
using namespace ::com::sun::star::sdbc;
using namespace dbaui;
OTableFieldControl::OTableFieldControl( Window* pParent, OTableDesignHelpBar* pHelpBar) :OFieldDescControl(pParent,pHelpBar)
{
}
//------------------------------------------------------------------
void OTableFieldControl::CellModified(long nRow, sal_uInt16 nColId )
{
    GetCtrl()->CellModified(nRow,nColId);
}
//------------------------------------------------------------------
OTableEditorCtrl* OTableFieldControl::GetCtrl() const
{
    OTableDesignView* pDesignWin = static_cast<OTableDesignView*>(GetParent()->GetParent()->GetParent()->GetParent());
    OSL_ENSURE(pDesignWin,"no view!");
    return pDesignWin->GetEditorCtrl();
}
//------------------------------------------------------------------
sal_Bool OTableFieldControl::IsReadOnly()
{
    sal_Bool bRead(GetCtrl()->IsReadOnly());
    if( !bRead )
    {
        // Die Spalten einer ::com::sun::star::sdbcx::View knnen nicht verndert werden
        Reference<XPropertySet> xTable = GetCtrl()->GetView()->getController()->getTable();
        if(xTable.is() && ::comphelper::getString(xTable->getPropertyValue(PROPERTY_TYPE)) == ::rtl::OUString::createFromAscii("VIEW"))
            bRead = sal_True;
        else
        {
            OTableRow* pCurRow = GetCtrl()->GetActRow();
            if( pCurRow )
                bRead = pCurRow->IsReadOnly();
        }
    }
    return bRead;
}
//------------------------------------------------------------------
void OTableFieldControl::ActivateAggregate( EControlType eType )
{
    switch(eType)
    {
        case tpColumnName:
        case tpType:
            break;
        default:
            OFieldDescControl::ActivateAggregate(eType);
    }
}
//------------------------------------------------------------------
void OTableFieldControl::DeactivateAggregate( EControlType eType )
{
    switch(eType)
    {
        case tpColumnName:
        case tpType:
            break;
        default:
            OFieldDescControl::DeactivateAggregate(eType);
    }
}
// -----------------------------------------------------------------------------
void OTableFieldControl::SetModified(BOOL bModified)
{
    GetCtrl()->GetView()->getController()->setModified(bModified);
}
// -----------------------------------------------------------------------------
::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XConnection> OTableFieldControl::getConnection()
{
    return GetCtrl()->GetView()->getController()->getConnection();
}
// -----------------------------------------------------------------------------
::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XDatabaseMetaData> OTableFieldControl::getMetaData()
{
    Reference<XConnection> xCon = GetCtrl()->GetView()->getController()->getConnection();
    if(!xCon.is())
        return NULL;
    return xCon->getMetaData();
}
// -----------------------------------------------------------------------------
Reference< XNumberFormatter >   OTableFieldControl::GetFormatter() const
{
    return GetCtrl()->GetView()->getController()->getNumberFormatter();
}
// -----------------------------------------------------------------------------
TOTypeInfoSP OTableFieldControl::getTypeInfo(sal_Int32 _nPos)
{
    return GetCtrl()->GetView()->getController()->getTypeInfo(_nPos);
}
// -----------------------------------------------------------------------------
const OTypeInfoMap* OTableFieldControl::getTypeInfo() const
{
    return const_cast<OTableFieldControl*>(this)->GetCtrl()->GetView()->getController()->getTypeInfo();
}
// -----------------------------------------------------------------------------
Locale OTableFieldControl::GetLocale() const
{
    return const_cast<OTableFieldControl*>(this)->GetCtrl()->GetView()->getLocale();
}
// -----------------------------------------------------------------------------
sal_Bool OTableFieldControl::isAutoIncrementValueEnabled() const
{
    return const_cast<OTableFieldControl*>(this)->GetCtrl()->GetView()->getController()->isAutoIncrementValueEnabled();
}
// -----------------------------------------------------------------------------
::rtl::OUString OTableFieldControl::getAutoIncrementValue() const
{
    return const_cast<OTableFieldControl*>(this)->GetCtrl()->GetView()->getController()->getAutoIncrementValue();
}
// -----------------------------------------------------------------------------

<commit_msg>INTEGRATION: CWS dba203c (1.9.110); FILE MERGED 2006/04/13 13:57:19 oj 1.9.110.1: hold TableRow now with a shared_ptr<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: TableFieldControl.cxx,v $
 *
 *  $Revision: 1.10 $
 *
 *  last change: $Author: rt $ $Date: 2006-05-04 08:51:01 $
 *
 *  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
 *
 ************************************************************************/
#ifndef DBAUI_TABLEFIELDCONTROL_HXX
#include "TableFieldControl.hxx"
#endif
#ifndef DBUI_TABLECONTROLLER_HXX
#include "TableController.hxx"
#endif
#ifndef DBAUI_TABLEDESIGNVIEW_HXX
#include "TableDesignView.hxx"
#endif
#ifndef DBAUI_TABLEEDITORCONTROL_HXX
#include "TEditControl.hxx"
#endif
#ifndef DBACCESS_SHARED_DBUSTRINGS_HRC
#include "dbustrings.hrc"
#endif
#ifndef _COM_SUN_STAR_SDBC_XDATABASEMETADATA_HPP_
#include <com/sun/star/sdbc/XDatabaseMetaData.hpp>
#endif
#ifndef _COM_SUN_STAR_BEANS_PROPERTYATTRIBUTE_HPP_
#include <com/sun/star/beans/PropertyAttribute.hpp>
#endif
#ifndef _COMPHELPER_TYPES_HXX_
#include <comphelper/types.hxx>
#endif
#ifndef DBAUI_TYPEINFO_HXX
#include "TypeInfo.hxx"
#endif
#ifndef DBAUI_TOOLS_HXX
#include "UITools.hxx"
#endif

using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::beans;
using namespace ::com::sun::star::util;
using namespace ::com::sun::star::lang;
using namespace ::com::sun::star::sdbc;
using namespace dbaui;
OTableFieldControl::OTableFieldControl( Window* pParent, OTableDesignHelpBar* pHelpBar) :OFieldDescControl(pParent,pHelpBar)
{
}
//------------------------------------------------------------------
void OTableFieldControl::CellModified(long nRow, sal_uInt16 nColId )
{
    GetCtrl()->CellModified(nRow,nColId);
}
//------------------------------------------------------------------
OTableEditorCtrl* OTableFieldControl::GetCtrl() const
{
    OTableDesignView* pDesignWin = static_cast<OTableDesignView*>(GetParent()->GetParent()->GetParent()->GetParent());
    OSL_ENSURE(pDesignWin,"no view!");
    return pDesignWin->GetEditorCtrl();
}
//------------------------------------------------------------------
sal_Bool OTableFieldControl::IsReadOnly()
{
    sal_Bool bRead(GetCtrl()->IsReadOnly());
    if( !bRead )
    {
        // Die Spalten einer ::com::sun::star::sdbcx::View knnen nicht verndert werden
        Reference<XPropertySet> xTable = GetCtrl()->GetView()->getController()->getTable();
        if(xTable.is() && ::comphelper::getString(xTable->getPropertyValue(PROPERTY_TYPE)) == ::rtl::OUString::createFromAscii("VIEW"))
            bRead = sal_True;
        else
        {
             ::boost::shared_ptr<OTableRow>  pCurRow = GetCtrl()->GetActRow();
            if( pCurRow )
                bRead = pCurRow->IsReadOnly();
        }
    }
    return bRead;
}
//------------------------------------------------------------------
void OTableFieldControl::ActivateAggregate( EControlType eType )
{
    switch(eType)
    {
        case tpColumnName:
        case tpType:
            break;
        default:
            OFieldDescControl::ActivateAggregate(eType);
    }
}
//------------------------------------------------------------------
void OTableFieldControl::DeactivateAggregate( EControlType eType )
{
    switch(eType)
    {
        case tpColumnName:
        case tpType:
            break;
        default:
            OFieldDescControl::DeactivateAggregate(eType);
    }
}
// -----------------------------------------------------------------------------
void OTableFieldControl::SetModified(BOOL bModified)
{
    GetCtrl()->GetView()->getController()->setModified(bModified);
}
// -----------------------------------------------------------------------------
::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XConnection> OTableFieldControl::getConnection()
{
    return GetCtrl()->GetView()->getController()->getConnection();
}
// -----------------------------------------------------------------------------
::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XDatabaseMetaData> OTableFieldControl::getMetaData()
{
    Reference<XConnection> xCon = GetCtrl()->GetView()->getController()->getConnection();
    if(!xCon.is())
        return NULL;
    return xCon->getMetaData();
}
// -----------------------------------------------------------------------------
Reference< XNumberFormatter >   OTableFieldControl::GetFormatter() const
{
    return GetCtrl()->GetView()->getController()->getNumberFormatter();
}
// -----------------------------------------------------------------------------
TOTypeInfoSP OTableFieldControl::getTypeInfo(sal_Int32 _nPos)
{
    return GetCtrl()->GetView()->getController()->getTypeInfo(_nPos);
}
// -----------------------------------------------------------------------------
const OTypeInfoMap* OTableFieldControl::getTypeInfo() const
{
    return const_cast<OTableFieldControl*>(this)->GetCtrl()->GetView()->getController()->getTypeInfo();
}
// -----------------------------------------------------------------------------
Locale OTableFieldControl::GetLocale() const
{
    return const_cast<OTableFieldControl*>(this)->GetCtrl()->GetView()->getLocale();
}
// -----------------------------------------------------------------------------
sal_Bool OTableFieldControl::isAutoIncrementValueEnabled() const
{
    return const_cast<OTableFieldControl*>(this)->GetCtrl()->GetView()->getController()->isAutoIncrementValueEnabled();
}
// -----------------------------------------------------------------------------
::rtl::OUString OTableFieldControl::getAutoIncrementValue() const
{
    return const_cast<OTableFieldControl*>(this)->GetCtrl()->GetView()->getController()->getAutoIncrementValue();
}
// -----------------------------------------------------------------------------

<|endoftext|>


<commit_before>#include "testApp.h"
#include <iostream.h>

//--------------------------------------------------------------
void testApp::setup(){
    ofSetVerticalSync(true);

    video.loadMovie( "GoodHair_JFleurantin/Resources/GoodHair_JFleurantin.mov" );
    sound.loadSound( "GoodHair_short.mp3" );

//    BlurOne.allocate(ofGetWidth(), ofGetHeight());
//    BlurTwo.allocate(ofGetWidth(), ofGetHeight());

    shader1.load("shaders/pixelate");
//    shaderX.load("shaders/blur");
//    shaderY.load("shaders/blur2");

    kinect.init(false, false); // disable video image (faster fps)
    kinect.open();

    sound.play();
    sound.setVolume(0.8f);
    sound.setLoop(true);

    video.play();
    video.setVolume(0.0f);

    point.set(20, 20);

    angle = 0;
	kinect.setCameraTiltAngle(angle);

}

//--------------------------------------------------------------
void testApp::update(){
    ofSoundUpdate;
    kinect.update();
    video.update();

    int currentDepthPixel = 0;
    closestValue = 50;
    farthestValue = 1000;

    unsigned char* depthPixels = kinect.getDepthPixels();

//    int sumX = 0;
//    int sumY = 0;
//    int counter = 0;

    //I don't know if the bounds should be the Kinect, Video, or App Window
    for(int x = 0; x < kinect.getWidth(); x++){
        for(int y = 0; y < kinect.getHeight(); y++){
            int i = x + y * kinect.getWidth();
            int currentDepthPixel = depthPixels[i];
            // int currentDepthPixel = depthPixels[x + y * ofGetWindowWidth()]
            if(currentDepthPixel > closestValue && currentDepthPixel < farthestValue){
                // save its value
                closestValue = currentDepthPixel;

                // and save its position (both X and Y coordinates)
//                closestX = x;
//                closestY = y;
                closePixel.x = x;
                closePixel.y = y;

        }

    }
}
    cout<<"closestX: "<<closePixel.x<<"\tclosestY: "<<closePixel.y<<"\tclosestZ: "<<closestValue<<endl;

    kinectValue(closePixel.x, closePixel.y);

//    if(upLeftQuad || lowRightQuad){
//        BlurOne.begin();
//        video.draw(0, 0, ofGetWindowWidth(), ofGetWindowHeight());
//
//        ofSetColor(255);
//        for(int y = 0; y<ofGetWindowHeight(); y+=10)
//            for(int x=0; x<ofGetWindowWidth(); x+=10) {
//                ofRect(x, y, 5, 5);
//            }
//
//        BlurOne.end();
//    }

//    if(upLeftQuad || lowRightQuad){
//        int iterations = 5;
//        for (int i=0; i<iterations; i++){
//
//            BlurTwo.begin();
//            shaderX.begin();
//            shaderX.setUniform1f("amount", point.x);
//            BlurOne.draw(0, 0);
//            shaderX.end();
//            BlurTwo.end();
//
//            BlurOne.begin();
//            shaderY.begin();
//            shaderY.setUniform1f("amount", point.y);
//            BlurTwo.draw(0, 0);
//            shaderY.end();
//            BlurOne.end();
//        }
//    }

}

//--------------------------------------------------------------
void testApp::draw(){

//    if(upLeftQuad || lowRightQuad){
//
//        BlurOne.draw(0, 0, ofGetWindowWidth(), ofGetWindowHeight());
//    }
//
//    if((upRightQuad || lowLeftQuad)){
        shader1.begin();
        shader1.setUniform2f("sampleDivisor", point.x, point.y);
        shader1.setUniform2f("depthPoint", closePixel.x, closePixel.y);
        video.draw(0, 0, ofGetWindowWidth(), ofGetWindowHeight());
        shader1.end();
//    }
//
//    if(upLeftQuad || lowRightQuad){
//        BlurTwo.draw(0, 0, ofGetWindowWidth(), ofGetWindowHeight());
//    }

//    ofSetColor(20);
//    ofCircle( closePixel.x, closePixel.y, point.x );

}

//--------------------------------------------------------------
void testApp::kinectValue(int cx, int cy){

    float dist = ofDist(0, 0, cx, cy);
    float max = ofDist(0, 0, ofGetWindowWidth(), ofGetWindowHeight());
    float pixelSize = ofMap(dist, 0, max, 1, 50);
    point.x = pixelSize;
    point.y = pixelSize;

    float positionX = ofMap(dist, closePixel.x, 1000, 0, ofGetWindowWidth());
    float positionY = ofMap(dist, closePixel.y, 500, 0, ofGetWindowHeight());

//    float mapPlayback = (closestValue - 200) * 0.01;
//    float playback = ofMap(mapPlayback, 0, .55, 0, 1, true);
////    if(video.getPosition() == 1.0){
////        playback = 0;
////    }
//    video.setPosition(playback);

//    int counter = 0;
//    for (counter; counter < 5; counter++) {
//        int playheadAvg += mapPlayback;
//
//    } (mapPlayback) {
//        <#statements#>
//    }
//    cout<<"playhead\t"<<mapPlayback<<endl;

    quad1 = (positionX/2)-4;
    quad2 = (positionX/2)+4;
    quad3 = (positionY/2)-4;
    quad4 = (positionY/2)+4;

    if((cx % 5 == 0) && (cx % 3 != 0)) {

        if((closePixel.x > 0 && closePixel.x < quad1) && (closePixel.y > 0 && closePixel.y < quad3)){

            upLeftQuad = true;
            upRightQuad = false;
            lowLeftQuad = false;
            lowRightQuad = false;

        } else if((closePixel.x > quad2 && closePixel.x < ofGetWindowWidth()) && (closePixel.y > quad4 && closePixel.y < ofGetWindowHeight())){
            upLeftQuad = false;
            upRightQuad = false;
            lowLeftQuad = false;
            lowRightQuad = true;

        } else if((closePixel.x > 0 && closePixel.x < quad1) && (closePixel.y > quad4 && closePixel.y < ofGetWindowHeight())){

            upLeftQuad = false;
            upRightQuad = false;
            lowLeftQuad = true;
            lowRightQuad = false;

        }else if((closePixel.x > quad2 && closePixel.x < ofGetWindowWidth()) && (closePixel.y > 0 && closePixel.y < quad3)){

            upLeftQuad = false;
            upRightQuad = true;
            lowLeftQuad = false;
            lowRightQuad = false;

        }
    }
    if((cx % 3 == 0) || (cx % 5 != 0)){

        if((closePixel.x > 0 && closePixel.x < 510) && (closePixel.y > 0 && closePixel.y < 362)){

            upLeftQuad = false;
            upRightQuad = true;
            lowLeftQuad = false;
            lowRightQuad = false;

        } else if((closePixel.x > quad2 && closePixel.x < ofGetWindowWidth()) && (closePixel.y > quad4 && closePixel.y < ofGetWindowHeight())){
            upLeftQuad = false;
            upRightQuad = false;
            lowLeftQuad = true;
            lowRightQuad = false;

        } else if((closePixel.x > 0 && closePixel.x < quad1) && (closePixel.y > quad4 && closePixel.y < ofGetWindowHeight())){

            upLeftQuad = false;
            upRightQuad = false;
            lowLeftQuad = false;
            lowRightQuad = true;

        }else if((closePixel.x > quad2 && closePixel.x < ofGetWindowWidth()) && (closePixel.y > 0 && closePixel.y < quad3)){

            upLeftQuad = true;
            upRightQuad = true;
            lowLeftQuad = false;
            lowRightQuad = false;

        }
    }

}
//--------------------------------------------------------------
void testApp::exit() {
	kinect.setCameraTiltAngle(0); // zero the tilt on exit
	kinect.close();
}

//--------------------------------------------------------------
void testApp::keyPressed(int key){

}

//--------------------------------------------------------------
void testApp::keyReleased(int key){

}

//--------------------------------------------------------------
void testApp::mouseMoved(int x, int y ){

}

//--------------------------------------------------------------
void testApp::mouseDragged(int x, int y, int button){

}

//--------------------------------------------------------------
void testApp::mousePressed(int x, int y, int button){

}

//--------------------------------------------------------------
void testApp::mouseReleased(int x, int y, int button){

}

//--------------------------------------------------------------
void testApp::windowResized(int w, int h){

}

//--------------------------------------------------------------
void testApp::gotMessage(ofMessage msg){

}

//--------------------------------------------------------------
void testApp::dragEvent(ofDragInfo dragInfo){

}
<commit_msg>Update testApp.cpp<commit_after>#include "testApp.h"
#include <iostream.h>

//--------------------------------------------------------------
void testApp::setup(){
    ofSetVerticalSync(true);

    video.loadMovie( "MOVIE.mov" );
    sound.loadSound( "SOUND.mp3" );

    shader1.load("shaders/pixelate");

    kinect.init(false, false);
    kinect.open();

    sound.play();
    sound.setVolume(0.8f);
    sound.setLoop(true);

    video.play();
    video.setVolume(0.0f);

    point.set(20, 20);

    angle = 0;
    kinect.setCameraTiltAngle(angle);

}

//--------------------------------------------------------------
void testApp::update(){
    ofSoundUpdate;
    kinect.update();
    video.update();

    int currentDepthPixel = 0;
    closestValue = 50;
    farthestValue = 1000;

    unsigned char* depthPixels = kinect.getDepthPixels();

    for(int x = 0; x < kinect.getWidth(); x++){
        for(int y = 0; y < kinect.getHeight(); y++){
            int i = x + y * kinect.getWidth();
            int currentDepthPixel = depthPixels[i];
            if(currentDepthPixel > closestValue && currentDepthPixel < farthestValue){
                closestValue = currentDepthPixel;

                closePixel.x = x;
                closePixel.y = y;

        }

    }
}
    kinectValue(closePixel.x, closePixel.y);
}

//--------------------------------------------------------------
void testApp::draw(){

        shader1.begin();
        shader1.setUniform2f("sampleDivisor", point.x, point.y);
        shader1.setUniform2f("depthPoint", closePixel.x, closePixel.y);
        video.draw(0, 0, ofGetWindowWidth(), ofGetWindowHeight());
        shader1.end();

}

//--------------------------------------------------------------
void testApp::kinectValue(int cx, int cy){

    float dist = ofDist(0, 0, cx, cy);
    float max = ofDist(0, 0, ofGetWindowWidth(), ofGetWindowHeight());
    float pixelSize = ofMap(dist, 0, max, 1, 50);
    point.x = pixelSize;
    point.y = pixelSize;

    float positionX = ofMap(dist, closePixel.x, 1000, 0, ofGetWindowWidth());
    float positionY = ofMap(dist, closePixel.y, 500, 0, ofGetWindowHeight());

/*
     Mapping playback position

    float mapPlayback = (closestValue - 200) * 0.01;
    float playback = ofMap(mapPlayback, 0, .55, 0, 1, true);
    if(video.getPosition() == 1.0){
        playback = 0;
   }
   video.setPosition(playback);

   */

/*
    If swapping between shaders

    quad1 = (positionX/2)-4;
    quad2 = (positionX/2)+4;
    quad3 = (positionY/2)-4;
    quad4 = (positionY/2)+4;

    if((cx % 5 == 0) && (cx % 3 != 0)) {

        if((closePixel.x > 0 && closePixel.x < quad1) && (closePixel.y > 0 && closePixel.y < quad3)){

            upLeftQuad = true;
            upRightQuad = false;
            lowLeftQuad = false;
            lowRightQuad = false;

        } else if((closePixel.x > quad2 && closePixel.x < ofGetWindowWidth()) && (closePixel.y > quad4 && closePixel.y < ofGetWindowHeight())){
            upLeftQuad = false;
            upRightQuad = false;
            lowLeftQuad = false;
            lowRightQuad = true;

        } else if((closePixel.x > 0 && closePixel.x < quad1) && (closePixel.y > quad4 && closePixel.y < ofGetWindowHeight())){

            upLeftQuad = false;
            upRightQuad = false;
            lowLeftQuad = true;
            lowRightQuad = false;

        }else if((closePixel.x > quad2 && closePixel.x < ofGetWindowWidth()) && (closePixel.y > 0 && closePixel.y < quad3)){

            upLeftQuad = false;
            upRightQuad = true;
            lowLeftQuad = false;
            lowRightQuad = false;

        }
    }
    if((cx % 3 == 0) || (cx % 5 != 0)){

        if((closePixel.x > 0 && closePixel.x < 510) && (closePixel.y > 0 && closePixel.y < 362)){

            upLeftQuad = false;
            upRightQuad = true;
            lowLeftQuad = false;
            lowRightQuad = false;

        } else if((closePixel.x > quad2 && closePixel.x < ofGetWindowWidth()) && (closePixel.y > quad4 && closePixel.y < ofGetWindowHeight())){
            upLeftQuad = false;
            upRightQuad = false;
            lowLeftQuad = true;
            lowRightQuad = false;

        } else if((closePixel.x > 0 && closePixel.x < quad1) && (closePixel.y > quad4 && closePixel.y < ofGetWindowHeight())){

            upLeftQuad = false;
            upRightQuad = false;
            lowLeftQuad = false;
            lowRightQuad = true;

        }else if((closePixel.x > quad2 && closePixel.x < ofGetWindowWidth()) && (closePixel.y > 0 && closePixel.y < quad3)){

            upLeftQuad = true;
            upRightQuad = true;
            lowLeftQuad = false;
            lowRightQuad = false;

        }
    }
*/

}
//--------------------------------------------------------------
void testApp::exit() {
	kinect.setCameraTiltAngle(0);
	kinect.close();
}

//--------------------------------------------------------------
void testApp::keyPressed(int key){

}

//--------------------------------------------------------------
void testApp::keyReleased(int key){

}

//--------------------------------------------------------------
void testApp::mouseMoved(int x, int y ){

}

//--------------------------------------------------------------
void testApp::mouseDragged(int x, int y, int button){

}

//--------------------------------------------------------------
void testApp::mousePressed(int x, int y, int button){

}

//--------------------------------------------------------------
void testApp::mouseReleased(int x, int y, int button){

}

//--------------------------------------------------------------
void testApp::windowResized(int w, int h){

}

//--------------------------------------------------------------
void testApp::gotMessage(ofMessage msg){

}

//--------------------------------------------------------------
void testApp::dragEvent(ofDragInfo dragInfo){

}
<|endoftext|>


<commit_before>#include <cstring>
#include <string>

#include <boost/assign/list_of.hpp>

#include "constants.h"
#include "testnet.h"

static uint8_t      TESTNET_PROTOCOL_MAGIC_BYTES[sizeof(PROTOCOL_MAGIC_BYTES)] = { 0xe5, 0xcf, 0x81, 0xdf };

static char const * TESTNET_AUTO_DNS_SEEDS[][2]                                = { { "t-seed-a", "t-seed-a.neucoin.org" }, { 0, 0 } };
static uint32_t     TESTNET_AUTO_IP_SEEDS[]                                    = { 0 };

void ApplyTestnetParameters(void)
{
    COIN_PORT                  = 8742;
    RPC_PORT                   = 8743;

    std::memcpy(PROTOCOL_MAGIC_BYTES, &TESTNET_PROTOCOL_MAGIC_BYTES, sizeof(PROTOCOL_MAGIC_BYTES));

    AUTO_DNS_SEEDS             = TESTNET_AUTO_DNS_SEEDS;
    AUTO_IP_SEEDS              = TESTNET_AUTO_IP_SEEDS;

    PUBKEY_ADDRESS_PREFIX      =  65; // 'T'
    PRVKEY_ADDRESS_PREFIX      =  68; // 'U'
    SCRIPT_ADDRESS_PREFIX      = 127; // 't'

    GENESIS_MERKLE_HASH        = hash_t("0xa7fc40033828e0b0aa5f829ad35233efe8a15e5820d31e53d8e865a1c29cf024");
    GENESIS_HASH               = hash_t("0x000002f38bfabee423e760cbbbd2147984be70a531928b89e64d59531b136944");
    GENESIS_IDENT              = "06-15-15 :: LFG 887 :: We can still take them out for an overpriced dinner";
    GENESIS_TX_TIME            = 1345083810;
    GENESIS_BLOCK_TIME         = 1345084287;
    GENESIS_BLOCK_NONCE        = 2179980296;
    GENESIS_BLOCK_VERSION      = 1;

    BLOCK_CHECKPOINTS          = boost::assign::map_list_of(0, GENESIS_HASH)((8 * WEEK) / (10 * MINUTE) + (8 * WEEK) / (1 * MINUTE), hash_t("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"));
    STAKE_MODIFIER_CHECKPOINTS = boost::assign::map_list_of(0, 0xfd11f4e7);

    POW_MAX_BLOCK              = std::numeric_limits< blockheight_t >::max();

    COIN_PREMINE               = 0 * COIN;

    POW_INITIAL_TARGET         = target_t(~uint256(0) >> 20);
    POS_INITIAL_TARGET         = target_t(~uint256(0) >> 20);

    POW_MAX_TARGET             = target_t(~uint256(0) >> 20);
    POS_MAX_TARGET             = target_t(~uint256(0) >> 20);

    POW_TARGET_SPACING         = 10 * MINUTE / 10;
    POS_TARGET_SPACING         = 1 * MINUTE / 2;

    POW_BLOCK_REWARD           = 1141 * COIN;

    STAKE_MIN_AGE              = 138240 * SECOND / 2;
    STAKE_MAX_AGE              = 138240 * SECOND / 2;
    MODIFIER_INTERVAL_BASE     = 200 * MINUTE / 2;
    MODIFIER_INTERVAL_RATIO    = 18;
    STAKE_COIN_STEP            = 1 * COIN;
    STAKE_AGE_STEP             = 1 * DAY / 2;
    TARGET_TIMESPAN            = 2 * HOUR / 2;
}
<commit_msg>Pushing back end of testnet network<commit_after>#include <cstring>
#include <string>

#include <boost/assign/list_of.hpp>

#include "constants.h"
#include "testnet.h"

static uint8_t      TESTNET_PROTOCOL_MAGIC_BYTES[sizeof(PROTOCOL_MAGIC_BYTES)] = { 0xe5, 0xcf, 0x81, 0xdf };

static char const * TESTNET_AUTO_DNS_SEEDS[][2]                                = { { "t-seed-a", "t-seed-a.neucoin.org" }, { 0, 0 } };
static uint32_t     TESTNET_AUTO_IP_SEEDS[]                                    = { 0 };

void ApplyTestnetParameters(void)
{
    COIN_PORT                  = 8742;
    RPC_PORT                   = 8743;

    std::memcpy(PROTOCOL_MAGIC_BYTES, &TESTNET_PROTOCOL_MAGIC_BYTES, sizeof(PROTOCOL_MAGIC_BYTES));

    AUTO_DNS_SEEDS             = TESTNET_AUTO_DNS_SEEDS;
    AUTO_IP_SEEDS              = TESTNET_AUTO_IP_SEEDS;

    PUBKEY_ADDRESS_PREFIX      =  65; // 'T'
    PRVKEY_ADDRESS_PREFIX      =  68; // 'U'
    SCRIPT_ADDRESS_PREFIX      = 127; // 't'

    GENESIS_MERKLE_HASH        = hash_t("0xa7fc40033828e0b0aa5f829ad35233efe8a15e5820d31e53d8e865a1c29cf024");
    GENESIS_HASH               = hash_t("0x000002f38bfabee423e760cbbbd2147984be70a531928b89e64d59531b136944");
    GENESIS_IDENT              = "06-15-15 :: LFG 887 :: We can still take them out for an overpriced dinner";
    GENESIS_TX_TIME            = 1345083810;
    GENESIS_BLOCK_TIME         = 1345084287;
    GENESIS_BLOCK_NONCE        = 2179980296;
    GENESIS_BLOCK_VERSION      = 1;

    STAKE_MODIFIER_CHECKPOINTS = boost::assign::map_list_of(0, 0xfd11f4e7);

    POW_MAX_BLOCK              = std::numeric_limits< blockheight_t >::max();

    COIN_PREMINE               = 0 * COIN;

    POW_INITIAL_TARGET         = target_t(~uint256(0) >> 20);
    POS_INITIAL_TARGET         = target_t(~uint256(0) >> 20);

    POW_MAX_TARGET             = target_t(~uint256(0) >> 20);
    POS_MAX_TARGET             = target_t(~uint256(0) >> 20);

    POW_TARGET_SPACING         = 10 * MINUTE / 10;
    POS_TARGET_SPACING         = 1 * MINUTE / 2;

    POW_BLOCK_REWARD           = 1141 * COIN;

    STAKE_MIN_AGE              = 138240 * SECOND / 2;
    STAKE_MAX_AGE              = 138240 * SECOND / 2;
    MODIFIER_INTERVAL_BASE     = 200 * MINUTE / 2;
    MODIFIER_INTERVAL_RATIO    = 18;
    STAKE_COIN_STEP            = 1 * COIN;
    STAKE_AGE_STEP             = 1 * DAY / 2;
    TARGET_TIMESPAN            = 2 * HOUR / 2;

    BLOCK_CHECKPOINTS          = boost::assign::map_list_of(0, GENESIS_HASH)((8 * WEEK) / POW_TARGET_SPACING + (8 * WEEK) / POS_TARGET_SPACING, hash_t("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"));
}
<|endoftext|>


<commit_before>/*
 * Transform a TSV format factor graph file and output corresponding binary
 * format used in DeepDive
 */

#include "text2bin.h"
#include "binary_format.h"
#include <assert.h>
#include <fstream>
#include <iostream>
#include <sstream>
#include <stdint.h>
#include <stdlib.h>
#include <vector>

namespace dd {

constexpr char field_delim = '\t';  // tsv file delimiter

// read variables and convert to binary format
void load_var(std::string input_filename, std::string output_filename) {
  std::ifstream fin(input_filename);
  std::ofstream fout(output_filename, std::ios::binary | std::ios::out);
  num_variables_t count = 0;
  int is_evidence;
  uint16_t var_type;
  variable_id_t vid;
  variable_value_t initial_value;
  num_variable_values_t cardinality;
  while (fin >> vid >> is_evidence >> initial_value >> var_type >>
         cardinality) {
    write_be(fout, vid);
    write_be<uint8_t>(fout, is_evidence);
    write_be(fout, initial_value);
    write_be(fout, var_type);
    write_be(fout, cardinality);
    ++count;
  }
  std::cout << count << std::endl;
}

// convert weights
void load_weight(std::string input_filename, std::string output_filename) {
  std::ifstream fin(input_filename);
  std::ofstream fout(output_filename, std::ios::binary | std::ios::out);
  long count = 0;
  int isfixed;
  weight_id_t wid;
  weight_value_t initial_value;
  while (fin >> wid >> isfixed >> initial_value) {
    write_be(fout, wid);
    write_be<uint8_t>(fout, isfixed);
    write_be(fout, initial_value);
    ++count;
  }
  std::cout << count << std::endl;
}

static inline long parse_pgarray(
    std::istream &input, std::function<void(const std::string &)> parse_element,
    long expected_count = -1) {
  if (input.peek() == '{') {
    input.get();
    std::string element;
    bool ended = false;
    long count = 0;
    while (getline(input, element, ',')) {
      if (element.at(element.length() - 1) == '}') {
        ended = true;
        element = element.substr(0, element.length() - 1);
      }
      parse_element(element);
      count++;
      if (ended) break;
    }
    assert(expected_count < 0 || count == expected_count);
    return count;
  } else {
    return -1;
  }
}
static inline long parse_pgarray_or_die(
    std::istream &input, std::function<void(const std::string &)> parse_element,
    long expected_count = -1) {
  long count = parse_pgarray(input, parse_element, expected_count);
  if (count >= 0) {
    return count;
  } else {
    std::cerr << "Expected an array '{' but found: " << input.get()
              << std::endl;
    std::abort();
  }
}

// load factors
// wid, vids
void load_factor(std::string input_filename, std::string output_filename,
                 factor_function_type_t funcid, factor_arity_t arity_expected,
                 const std::vector<bool> &positives_vec) {
  std::ifstream fin(input_filename);
  std::ofstream fout(output_filename, std::ios::binary | std::ios::out);
  num_edges_t total_edges = 0;
  std::vector<variable_id_t> vids;
  std::vector<weight_id_t> vals_and_weights;  // FIXME separate the two
  std::string line;
  std::string array_piece;
  while (getline(fin, line)) {
    std::string field;
    istringstream ss(line);
    vids.clear();
    // factor type
    write_be<uint16_t>(fout, funcid);
    // variable ids
    factor_arity_t arity = 0;
    auto parse_variableid = [&vids, &arity,
                             &total_edges](const std::string &element) {
      vids.push_back(atol(element.c_str()));
      ++total_edges;
      ++arity;
    };
    for (factor_arity_t i = 0; i < arity_expected; ++i) {
      getline(ss, field, field_delim);
      // try parsing as an array first
      // FIXME remove this?  parsing vid arrays is probably broken since this
      // doesn't create a cross product of factors but simply widens the arity
      istringstream fieldinput(field);
      if (parse_pgarray(fieldinput, parse_variableid) < 0) {
        // otherwise, parse it as a single variable
        parse_variableid(field);
      }
    }
    write_be(fout, arity);
    for (factor_arity_t i = 0; i < vids.size(); ++i) {
      write_be(fout, vids[i]);
      variable_value_t should_equal_to = positives_vec.at(i) ? 1 : 0;
      write_be(fout, should_equal_to);
    }
    // weight ids
    switch (funcid) {
      case FUNC_AND_CATEGORICAL: {
        vals_and_weights.clear();
        // IN  Format: NUM_WEIGHTS [VAR1 VAL ID] [VAR2 VAL ID] ... [WEIGHT ID]
        // OUT Format: NUM_WEIGHTS [[VAR1_VALi, VAR2_VALi, ..., WEIGHTi]]
        // first, the run-length
        getline(ss, field, field_delim);
        factor_weight_key_t num_weightids = atol(field.c_str());
        write_be<uint32_t /*FIXME factor_weight_key_t*/>(fout, num_weightids);
        // second, parse var vals for each var
        // TODO: hard coding cid length (4) for now
        for (factor_arity_t i = 0; i < arity; ++i) {
          getline(ss, array_piece, field_delim);
          istringstream ass(array_piece);
          parse_pgarray_or_die(
              ass, [&vals_and_weights](const std::string &element) {
                variable_value_t cid = atoi(element.c_str());
                vals_and_weights.push_back(cid);
              }, num_weightids);
        }
        // third, parse weights
        parse_pgarray_or_die(
            ss, [&vals_and_weights](const std::string &element) {
              weight_id_t weightid = atol(element.c_str());
              vals_and_weights.push_back(weightid);
            }, num_weightids);
        // fourth, transpose into output format
        for (factor_weight_key_t i = 0; i < num_weightids; ++i) {
          for (factor_arity_t j = 0; j < arity; ++j) {
            variable_value_t cid =
                (variable_value_t)vals_and_weights[j * num_weightids + i];
            write_be(fout, cid);
          }
          weight_id_t weightid = vals_and_weights[arity * num_weightids + i];
          write_be(fout, weightid);
        }
        break;
      }
      default:
        // a single weight id
        getline(ss, field, field_delim);
        weight_id_t weightid = atol(field.c_str());
        write_be(fout, weightid);
    }
  }
  std::cout << total_edges << std::endl;
}

// read categorical variable domains and convert to binary format
void load_domain(std::string input_filename, std::string output_filename) {
  std::ifstream fin(input_filename);
  std::ofstream fout(output_filename, std::ios::binary | std::ios::out);
  std::string line;
  while (getline(fin, line)) {
    istringstream line_input(line);
    variable_id_t vid;
    num_variable_values_t cardinality;
    std::string domain;
    assert(line_input >> vid >> cardinality >> domain);
    write_be(fout, vid);
    write_be(fout, cardinality);
    // an array of domain values
    istringstream domain_input(domain);
    parse_pgarray_or_die(domain_input, [&fout](const std::string &subfield) {
      variable_value_t value = atoi(subfield.c_str());
      write_be(fout, value);
    }, cardinality);
  }
}

int text2bin(const CmdParser &args) {
  // common arguments
  if (args.text2bin_mode == "variable") {
    load_var(args.text2bin_input, args.text2bin_output);
  } else if (args.text2bin_mode == "weight") {
    load_weight(args.text2bin_input, args.text2bin_output);
  } else if (args.text2bin_mode == "factor") {
    load_factor(args.text2bin_input, args.text2bin_output,
                args.text2bin_factor_func_id, args.text2bin_factor_arity,
                args.text2bin_factor_positives_or_not);
  } else if (args.text2bin_mode == "domain") {
    load_domain(args.text2bin_input, args.text2bin_output);
  } else {
    std::cerr << "Unsupported type" << std::endl;
    return 1;
  }
  return 0;
}

}  // namespace dd
<commit_msg>Scrubs some types in text2bin<commit_after>/*
 * Transform a TSV format factor graph file and output corresponding binary
 * format used in DeepDive
 */

#include "text2bin.h"
#include "binary_format.h"
#include <assert.h>
#include <fstream>
#include <iostream>
#include <sstream>
#include <stdint.h>
#include <stdlib.h>
#include <vector>

namespace dd {

constexpr char field_delim = '\t';  // tsv file delimiter

// read variables and convert to binary format
void load_var(std::string input_filename, std::string output_filename) {
  std::ifstream fin(input_filename);
  std::ofstream fout(output_filename, std::ios::binary | std::ios::out);
  num_variables_t count = 0;
  int is_evidence;
  uint16_t var_type;
  variable_id_t vid;
  variable_value_t initial_value;
  num_variable_values_t cardinality;
  while (fin >> vid >> is_evidence >> initial_value >> var_type >>
         cardinality) {
    write_be(fout, vid);
    write_be<uint8_t>(fout, is_evidence);
    write_be(fout, initial_value);
    write_be(fout, var_type);
    write_be(fout, cardinality);
    ++count;
  }
  std::cout << count << std::endl;
}

// convert weights
void load_weight(std::string input_filename, std::string output_filename) {
  std::ifstream fin(input_filename);
  std::ofstream fout(output_filename, std::ios::binary | std::ios::out);
  num_weights_t count = 0;
  int isfixed;
  weight_id_t wid;
  weight_value_t initial_value;
  while (fin >> wid >> isfixed >> initial_value) {
    write_be(fout, wid);
    write_be<uint8_t>(fout, isfixed);
    write_be(fout, initial_value);
    ++count;
  }
  std::cout << count << std::endl;
}

static inline size_t parse_pgarray(
    std::istream &input, std::function<void(const std::string &)> parse_element,
    size_t expected_count = -1) {
  if (input.peek() == '{') {
    input.get();
    std::string element;
    bool ended = false;
    size_t count = 0;
    while (getline(input, element, ',')) {
      if (element.at(element.length() - 1) == '}') {
        ended = true;
        element = element.substr(0, element.length() - 1);
      }
      parse_element(element);
      count++;
      if (ended) break;
    }
    assert(expected_count == -1 || count == expected_count);
    return count;
  } else {
    return -1;
  }
}
static inline size_t parse_pgarray_or_die(
    std::istream &input, std::function<void(const std::string &)> parse_element,
    size_t expected_count = -1) {
  size_t count = parse_pgarray(input, parse_element, expected_count);
  if (count != -1) {
    return count;
  } else {
    std::cerr << "Expected an array '{' but found: " << input.get()
              << std::endl;
    std::abort();
  }
}

// load factors
// wid, vids
void load_factor(std::string input_filename, std::string output_filename,
                 factor_function_type_t funcid, factor_arity_t arity_expected,
                 const std::vector<bool> &positives_vec) {
  std::ifstream fin(input_filename);
  std::ofstream fout(output_filename, std::ios::binary | std::ios::out);
  num_edges_t total_edges = 0;
  std::vector<variable_id_t> vids;
  std::vector<weight_id_t> vals_and_weights;  // FIXME separate the two
  std::string line;
  std::string array_piece;
  while (getline(fin, line)) {
    std::string field;
    istringstream ss(line);
    vids.clear();
    // factor type
    write_be<uint16_t>(fout, funcid);
    // variable ids
    factor_arity_t arity = 0;
    auto parse_variableid = [&vids, &arity,
                             &total_edges](const std::string &element) {
      vids.push_back(atol(element.c_str()));
      ++total_edges;
      ++arity;
    };
    for (factor_arity_t i = 0; i < arity_expected; ++i) {
      getline(ss, field, field_delim);
      // try parsing as an array first
      // FIXME remove this?  parsing vid arrays is probably broken since this
      // doesn't create a cross product of factors but simply widens the arity
      istringstream fieldinput(field);
      if (parse_pgarray(fieldinput, parse_variableid) == -1) {
        // otherwise, parse it as a single variable
        parse_variableid(field);
      }
    }
    write_be(fout, arity);
    for (factor_arity_t i = 0; i < vids.size(); ++i) {
      write_be(fout, vids[i]);
      variable_value_t should_equal_to = positives_vec.at(i) ? 1 : 0;
      write_be(fout, should_equal_to);
    }
    // weight ids
    switch (funcid) {
      case FUNC_AND_CATEGORICAL: {
        vals_and_weights.clear();
        // IN  Format: NUM_WEIGHTS [VAR1 VAL ID] [VAR2 VAL ID] ... [WEIGHT ID]
        // OUT Format: NUM_WEIGHTS [[VAR1_VALi, VAR2_VALi, ..., WEIGHTi]]
        // first, the run-length
        getline(ss, field, field_delim);
        factor_weight_key_t num_weightids = atol(field.c_str());
        write_be<uint32_t /*FIXME factor_weight_key_t*/>(fout, num_weightids);
        // second, parse var vals for each var
        // TODO: hard coding cid length (4) for now
        for (factor_arity_t i = 0; i < arity; ++i) {
          getline(ss, array_piece, field_delim);
          istringstream ass(array_piece);
          parse_pgarray_or_die(
              ass, [&vals_and_weights](const std::string &element) {
                variable_value_t cid = atoi(element.c_str());
                vals_and_weights.push_back(cid);
              }, num_weightids);
        }
        // third, parse weights
        parse_pgarray_or_die(
            ss, [&vals_and_weights](const std::string &element) {
              weight_id_t weightid = atol(element.c_str());
              vals_and_weights.push_back(weightid);
            }, num_weightids);
        // fourth, transpose into output format
        for (factor_weight_key_t i = 0; i < num_weightids; ++i) {
          for (factor_arity_t j = 0; j < arity; ++j) {
            variable_value_t cid =
                (variable_value_t)vals_and_weights[j * num_weightids + i];
            write_be(fout, cid);
          }
          weight_id_t weightid = vals_and_weights[arity * num_weightids + i];
          write_be(fout, weightid);
        }
        break;
      }
      default:
        // a single weight id
        getline(ss, field, field_delim);
        weight_id_t weightid = atol(field.c_str());
        write_be(fout, weightid);
    }
  }
  std::cout << total_edges << std::endl;
}

// read categorical variable domains and convert to binary format
void load_domain(std::string input_filename, std::string output_filename) {
  std::ifstream fin(input_filename);
  std::ofstream fout(output_filename, std::ios::binary | std::ios::out);
  std::string line;
  while (getline(fin, line)) {
    istringstream line_input(line);
    variable_id_t vid;
    num_variable_values_t cardinality;
    std::string domain;
    assert(line_input >> vid >> cardinality >> domain);
    write_be(fout, vid);
    write_be(fout, cardinality);
    // an array of domain values
    istringstream domain_input(domain);
    parse_pgarray_or_die(domain_input, [&fout](const std::string &subfield) {
      variable_value_t value = atoi(subfield.c_str());
      write_be(fout, value);
    }, cardinality);
  }
}

int text2bin(const CmdParser &args) {
  // common arguments
  if (args.text2bin_mode == "variable") {
    load_var(args.text2bin_input, args.text2bin_output);
  } else if (args.text2bin_mode == "weight") {
    load_weight(args.text2bin_input, args.text2bin_output);
  } else if (args.text2bin_mode == "factor") {
    load_factor(args.text2bin_input, args.text2bin_output,
                args.text2bin_factor_func_id, args.text2bin_factor_arity,
                args.text2bin_factor_positives_or_not);
  } else if (args.text2bin_mode == "domain") {
    load_domain(args.text2bin_input, args.text2bin_output);
  } else {
    std::cerr << "Unsupported type" << std::endl;
    return 1;
  }
  return 0;
}

}  // namespace dd
<|endoftext|>


<commit_before>#include "internal.h"

/// Group of functions dedicated to handling of shaders
namespace ShaderHandler {

	static const char* readShader(char* path);
	static std::vector<Shader> shaders;
	static std::vector<GLuint> programs;
	static unsigned int currentProgram;

	///
	/// Adds shader to the shader vector.
	///
	/// @param type shaderType enum which represents the type of the shader
	/// @param filePath Filepath of the shader
	///
	/// @return ID of the shader
	unsigned int addShader(shaderType type, char* filePath)
	{
		//Adds a new shader to the vector and returns it's id
		shaders.push_back(*(new Shader(type, readShader(filePath))));
		return shaders.capacity() - 1;
	}

	///
	/// Adds program to the program vector and sets itself as the current program.
	///
	/// @return ID of the program
	///
	unsigned int addProgram()
	{
		//Adds a new program to the Programs Vertex and returns it's id
		GLuint i = glCreateProgram();
		programs.push_back(i);
		currentProgram = programs.size() - 1;
		return programs.size() - 1;
	}

	///
	/// Attaches shaders to the current program and links it
	///
	/// @param vertexShader ID of the vertex shader
	/// @param fragmentShader ID of the fragment shader
	///
	void bindProgram(unsigned int vertexShader, unsigned int fragmentShader)
	{
		//Attaches vertex and fragment shaders to program
		glAttachShader(programs[currentProgram], shaders[vertexShader].id);
		glAttachShader(programs[currentProgram], shaders[fragmentShader].id);
		//Links the program
		glLinkProgram(programs[currentProgram]);
	}

	///
	/// Attaches shaders to a program and links it.
	///
	/// @param program Program ID
	/// @param vertexShader ID of the vertex shader
	/// @param fragmentShader ID of the fragment shader
	///
	void bindProgram(unsigned int program, unsigned int vertexShader, unsigned int fragmentShader)
	{
		//Attaches vertex and fragment shaders to program
		glAttachShader(programs[program], shaders[vertexShader].id);
		glAttachShader(programs[program], shaders[fragmentShader].id);
		//Links the program
		glLinkProgram(programs[program]);
	}

	///
	/// Sets program that is in use to the current program
	///
	void useProgram(){
		glUseProgram(programs[currentProgram]);
	}
	///
	/// Sets program that is in use
	///
	/// @param program Program ID
	///
	void useProgram(unsigned int program){
		glUseProgram(programs[program]);
	}

	///
	/// Gets current program
	///
	unsigned int getProgram()
	{
		return programs[currentProgram];
	}

	///
	/// Gets a program
	///
	/// @param program Program ID
	///
	unsigned int getProgram(unsigned int program)
	{
		return programs[program];
	}

	Shader::Shader(shaderType type, const char* shader)
	{
		//Creates a new shader binds it to it's source and compiles it
		id = glCreateShader(type);
		glShaderSource(id, 1, &shader, NULL);
		glCompileShader(id);

		GLint b;
		GLint length;
		glGetShaderiv(id, GL_INFO_LOG_LENGTH, &length);
		GLchar* log = (GLchar*)malloc(length);

		glGetShaderInfoLog(id, 200, &length, log);

		printf("Log file: ");
		if (length>1){
			printf("%s\n", log);
		}

	}

	// Private functions which reads shader from file
	const char * readShader(char* path)
	{
		// Reads the shader into a string
		std::ifstream shader;
		shader.open(path, std::ios::in);
		std::string contents((std::istreambuf_iterator<char>(shader)),
			std::istreambuf_iterator<char>());
		shader.close();

		//Creates a new string from contents since returning contents will result in a Null pointer after it's deletion
		char* ptr = new char[contents.length() + 1];
		std::strcpy(ptr, contents.c_str());
		//#ifdef _DEBUG
		//	std::cout << std::endl << ptr;
		//#endif
		return ptr;
	}
}<commit_msg>Removed unused variable<commit_after>#include "internal.h"

/// Group of functions dedicated to handling of shaders
namespace ShaderHandler {

	static const char* readShader(char* path);
	static std::vector<Shader> shaders;
	static std::vector<GLuint> programs;
	static unsigned int currentProgram;

	///
	/// Adds shader to the shader vector.
	///
	/// @param type shaderType enum which represents the type of the shader
	/// @param filePath Filepath of the shader
	///
	/// @return ID of the shader
	unsigned int addShader(shaderType type, char* filePath)
	{
		//Adds a new shader to the vector and returns it's id
		shaders.push_back(*(new Shader(type, readShader(filePath))));
		return shaders.capacity() - 1;
	}

	///
	/// Adds program to the program vector and sets itself as the current program.
	///
	/// @return ID of the program
	///
	unsigned int addProgram()
	{
		//Adds a new program to the Programs Vertex and returns it's id
		GLuint i = glCreateProgram();
		programs.push_back(i);
		currentProgram = programs.size() - 1;
		return programs.size() - 1;
	}

	///
	/// Attaches shaders to the current program and links it
	///
	/// @param vertexShader ID of the vertex shader
	/// @param fragmentShader ID of the fragment shader
	///
	void bindProgram(unsigned int vertexShader, unsigned int fragmentShader)
	{
		//Attaches vertex and fragment shaders to program
		glAttachShader(programs[currentProgram], shaders[vertexShader].id);
		glAttachShader(programs[currentProgram], shaders[fragmentShader].id);
		//Links the program
		glLinkProgram(programs[currentProgram]);
	}

	///
	/// Attaches shaders to a program and links it.
	///
	/// @param program Program ID
	/// @param vertexShader ID of the vertex shader
	/// @param fragmentShader ID of the fragment shader
	///
	void bindProgram(unsigned int program, unsigned int vertexShader, unsigned int fragmentShader)
	{
		//Attaches vertex and fragment shaders to program
		glAttachShader(programs[program], shaders[vertexShader].id);
		glAttachShader(programs[program], shaders[fragmentShader].id);
		//Links the program
		glLinkProgram(programs[program]);
	}

	///
	/// Sets program that is in use to the current program
	///
	void useProgram(){
		glUseProgram(programs[currentProgram]);
	}
	///
	/// Sets program that is in use
	///
	/// @param program Program ID
	///
	void useProgram(unsigned int program){
		glUseProgram(programs[program]);
	}

	///
	/// Gets current program
	///
	unsigned int getProgram()
	{
		return programs[currentProgram];
	}

	///
	/// Gets a program
	///
	/// @param program Program ID
	///
	unsigned int getProgram(unsigned int program)
	{
		return programs[program];
	}

	Shader::Shader(shaderType type, const char* shader)
	{
		//Creates a new shader binds it to it's source and compiles it
		id = glCreateShader(type);
		glShaderSource(id, 1, &shader, NULL);
		glCompileShader(id);

		GLint length;
		glGetShaderiv(id, GL_INFO_LOG_LENGTH, &length);
		GLchar* log = (GLchar*)malloc(length);

		glGetShaderInfoLog(id, 200, &length, log);

		printf("Log file: ");
		if (length>1){
			printf("%s\n", log);
		}

	}

	// Private functions which reads shader from file
	const char * readShader(char* path)
	{
		// Reads the shader into a string
		std::ifstream shader;
		shader.open(path, std::ios::in);
		std::string contents((std::istreambuf_iterator<char>(shader)),
			std::istreambuf_iterator<char>());
		shader.close();

		//Creates a new string from contents since returning contents will result in a Null pointer after it's deletion
		char* ptr = new char[contents.length() + 1];
		std::strcpy(ptr, contents.c_str());
		//#ifdef _DEBUG
		//	std::cout << std::endl << ptr;
		//#endif
		return ptr;
	}
}<|endoftext|>


<commit_before>/*************************************************************************
 *
 * TIGHTDB CONFIDENTIAL
 * __________________
 *
 *  [2011] - [2012] TightDB Inc
 *  All Rights Reserved.
 *
 * NOTICE:  All information contained herein is, and remains
 * the property of TightDB Incorporated and its suppliers,
 * if any.  The intellectual and technical concepts contained
 * herein are proprietary to TightDB Incorporated
 * and its suppliers and may be covered by U.S. and Foreign Patents,
 * patents in process, and are protected by trade secret or copyright law.
 * Dissemination of this information or reproduction of this material
 * is strictly forbidden unless prior written permission is obtained
 * from TightDB Incorporated.
 *
 **************************************************************************/
#ifndef TIGHTDB_HPP
#define TIGHTDB_HPP

#include <tightdb/group_shared.hpp>
#include <tightdb/table_macros.hpp>
#include <tightdb/descriptor.hpp>
#include <tightdb/link_view.hpp>

#endif // TIGHTDB_HPP
<commit_msg>lr_sharedptr: Dummy commit to make jenkins re-test (edited a 2012 year to 2014)<commit_after>/*************************************************************************
 *
 * TIGHTDB CONFIDENTIAL
 * __________________
 *
 *  [2011] - [2014] TightDB Inc
 *  All Rights Reserved.
 *
 * NOTICE:  All information contained herein is, and remains
 * the property of TightDB Incorporated and its suppliers,
 * if any.  The intellectual and technical concepts contained
 * herein are proprietary to TightDB Incorporated
 * and its suppliers and may be covered by U.S. and Foreign Patents,
 * patents in process, and are protected by trade secret or copyright law.
 * Dissemination of this information or reproduction of this material
 * is strictly forbidden unless prior written permission is obtained
 * from TightDB Incorporated.
 *
 **************************************************************************/
#ifndef TIGHTDB_HPP
#define TIGHTDB_HPP

#include <tightdb/group_shared.hpp>
#include <tightdb/table_macros.hpp>
#include <tightdb/descriptor.hpp>
#include <tightdb/link_view.hpp>

#endif // TIGHTDB_HPP
<|endoftext|>


<commit_before><commit_msg>vcl wmf test: null terminate stream<commit_after><|endoftext|>


<commit_before>#include "BoundaryFlux3EqnGhostDensityVelocity.h"
#include "SinglePhaseFluidProperties.h"
#include "Numerics.h"
#include "THMIndices3Eqn.h"

registerMooseObject("THMApp", BoundaryFlux3EqnGhostDensityVelocity);

template <>
InputParameters
validParams<BoundaryFlux3EqnGhostDensityVelocity>()
{
  InputParameters params = validParams<BoundaryFlux3EqnGhostBase>();

  params.addClassDescription("Computes boundary flux from density and velocity for the 3-equation "
                             "model using a ghost cell approach.");

  params.addRequiredParam<Real>("rho", "Density");
  params.addRequiredParam<Real>("vel", "Velocity");

  params.addRequiredParam<UserObjectName>("fluid_properties",
                                          "1-phase fluid properties user object name");

  params.declareControllable("rho vel");

  return params;
}

BoundaryFlux3EqnGhostDensityVelocity::BoundaryFlux3EqnGhostDensityVelocity(
    const InputParameters & parameters)
  : BoundaryFlux3EqnGhostBase(parameters),

    _rho(getParam<Real>("rho")),
    _vel(getParam<Real>("vel")),

    _fp(getUserObjectByName<SinglePhaseFluidProperties>(
        getParam<UserObjectName>("fluid_properties")))
{
}

std::vector<Real>
BoundaryFlux3EqnGhostDensityVelocity::getGhostCellSolution(
    const std::vector<Real> & U_interior) const
{
  const Real rhoA = U_interior[THM3Eqn::CONS_VAR_RHOA];
  const Real rhouA = U_interior[THM3Eqn::CONS_VAR_RHOUA];
  const Real rhoEA = U_interior[THM3Eqn::CONS_VAR_RHOEA];
  const Real A = U_interior[THM3Eqn::CONS_VAR_AREA];

  // Get the pressure from the interior solution

  const Real rho = rhoA / A;
  const Real vel = rhouA / rhoA;
  const Real E = rhoEA / rhoA;
  const Real e = E - 0.5 * vel * vel;
  const Real p = _fp.p_from_v_e(1.0 / rho, e);

  // Compute remaining boundary quantities

  const Real e_b = _fp.e_from_p_rho(p, _rho);
  const Real E_b = e_b + 0.5 * _vel * _vel;

  // compute ghost solution

  std::vector<Real> U_ghost(THM3Eqn::N_CONS_VAR);
  U_ghost[THM3Eqn::CONS_VAR_RHOA] = _rho * A;
  U_ghost[THM3Eqn::CONS_VAR_RHOUA] = _rho * _vel * A;
  U_ghost[THM3Eqn::CONS_VAR_RHOEA] = _rho * E_b * A;
  U_ghost[THM3Eqn::CONS_VAR_AREA] = A;

  return U_ghost;
}

DenseMatrix<Real>
BoundaryFlux3EqnGhostDensityVelocity::getGhostCellSolutionJacobian(
    const std::vector<Real> & U_interior) const
{
  const Real rhoA = U_interior[THM3Eqn::CONS_VAR_RHOA];
  const Real rhouA = U_interior[THM3Eqn::CONS_VAR_RHOUA];
  const Real rhoEA = U_interior[THM3Eqn::CONS_VAR_RHOEA];
  const Real A = U_interior[THM3Eqn::CONS_VAR_AREA];

  // Get the pressures from the interior solution

  Real rho = rhoA / A;
  Real drho_drhoA = 1.0 / A;

  Real v, dv_drho;
  THM::v_from_rho(rho, v, dv_drho);
  const Real dv_drhoA = dv_drho * drho_drhoA;

  const Real vel = rhouA / rhoA;

  const Real E = rhoEA / rhoA;
  const Real e = E - 0.5 * vel * vel;
  const Real de_drhoA = THM::de_darhoA(rhoA, rhouA, rhoEA);
  const Real de_drhouA = THM::de_darhouA(rhoA, rhouA);
  const Real de_drhoEA = THM::de_darhoEA(rhoA);

  Real p, dp_dv, dp_de;
  _fp.p_from_v_e(v, e, p, dp_dv, dp_de);
  const Real dp_drhoA = dp_dv * dv_drhoA + dp_de * de_drhoA;
  const Real dp_drhouA = dp_de * de_drhouA;
  const Real dp_drhoEA = dp_de * de_drhoEA;

  // Compute remaining boundary quantities

  const Real rhoA_b = _rho * A;

  Real e_b, de_b_dp, de_b_drho_b;
  _fp.e_from_p_rho(p, _rho, e_b, de_b_dp, de_b_drho_b);
  const Real de_b_drhoA = de_b_dp * dp_drhoA;
  const Real de_b_drhouA = de_b_dp * dp_drhouA;
  const Real de_b_drhoEA = de_b_dp * dp_drhoEA;

  Real E_b, dE_b_de_b, dE_b_dvel_b;
  THM::E_from_e_vel(e_b, _vel, E_b, dE_b_de_b, dE_b_dvel_b);
  const Real dE_b_drhoA = dE_b_de_b * de_b_drhoA;
  const Real dE_b_drhouA = dE_b_de_b * de_b_drhouA;
  const Real dE_b_drhoEA = dE_b_de_b * de_b_drhoEA;

  const Real drhoEA_b_drhoA = rhoA_b * dE_b_drhoA;
  const Real drhoEA_b_drhouA = rhoA_b * dE_b_drhouA;
  const Real drhoEA_b_drhoEA = rhoA_b * dE_b_drhoEA;

  // compute ghost solution

  std::vector<Real> U_ghost(THM3Eqn::N_CONS_VAR);
  U_ghost[THM3Eqn::CONS_VAR_RHOA] = _rho * A;
  U_ghost[THM3Eqn::CONS_VAR_RHOUA] = _rho * _vel * A;
  U_ghost[THM3Eqn::CONS_VAR_RHOEA] = _rho * E_b * A;
  U_ghost[THM3Eqn::CONS_VAR_AREA] = A;

  // compute ghost solution Jacobian

  DenseMatrix<Real> J(THM3Eqn::N_EQ, THM3Eqn::N_EQ);

  J(THM3Eqn::EQ_ENERGY, THM3Eqn::EQ_MASS) = drhoEA_b_drhoA;
  J(THM3Eqn::EQ_ENERGY, THM3Eqn::EQ_MOMENTUM) = drhoEA_b_drhouA;
  J(THM3Eqn::EQ_ENERGY, THM3Eqn::EQ_ENERGY) = drhoEA_b_drhoEA;

  return J;
}
<commit_msg>Removing useless code<commit_after>#include "BoundaryFlux3EqnGhostDensityVelocity.h"
#include "SinglePhaseFluidProperties.h"
#include "Numerics.h"
#include "THMIndices3Eqn.h"

registerMooseObject("THMApp", BoundaryFlux3EqnGhostDensityVelocity);

template <>
InputParameters
validParams<BoundaryFlux3EqnGhostDensityVelocity>()
{
  InputParameters params = validParams<BoundaryFlux3EqnGhostBase>();

  params.addClassDescription("Computes boundary flux from density and velocity for the 3-equation "
                             "model using a ghost cell approach.");

  params.addRequiredParam<Real>("rho", "Density");
  params.addRequiredParam<Real>("vel", "Velocity");

  params.addRequiredParam<UserObjectName>("fluid_properties",
                                          "1-phase fluid properties user object name");

  params.declareControllable("rho vel");

  return params;
}

BoundaryFlux3EqnGhostDensityVelocity::BoundaryFlux3EqnGhostDensityVelocity(
    const InputParameters & parameters)
  : BoundaryFlux3EqnGhostBase(parameters),

    _rho(getParam<Real>("rho")),
    _vel(getParam<Real>("vel")),

    _fp(getUserObjectByName<SinglePhaseFluidProperties>(
        getParam<UserObjectName>("fluid_properties")))
{
}

std::vector<Real>
BoundaryFlux3EqnGhostDensityVelocity::getGhostCellSolution(
    const std::vector<Real> & U_interior) const
{
  const Real rhoA = U_interior[THM3Eqn::CONS_VAR_RHOA];
  const Real rhouA = U_interior[THM3Eqn::CONS_VAR_RHOUA];
  const Real rhoEA = U_interior[THM3Eqn::CONS_VAR_RHOEA];
  const Real A = U_interior[THM3Eqn::CONS_VAR_AREA];

  // Get the pressure from the interior solution

  const Real rho = rhoA / A;
  const Real vel = rhouA / rhoA;
  const Real E = rhoEA / rhoA;
  const Real e = E - 0.5 * vel * vel;
  const Real p = _fp.p_from_v_e(1.0 / rho, e);

  // Compute remaining boundary quantities

  const Real e_b = _fp.e_from_p_rho(p, _rho);
  const Real E_b = e_b + 0.5 * _vel * _vel;

  // compute ghost solution

  std::vector<Real> U_ghost(THM3Eqn::N_CONS_VAR);
  U_ghost[THM3Eqn::CONS_VAR_RHOA] = _rho * A;
  U_ghost[THM3Eqn::CONS_VAR_RHOUA] = _rho * _vel * A;
  U_ghost[THM3Eqn::CONS_VAR_RHOEA] = _rho * E_b * A;
  U_ghost[THM3Eqn::CONS_VAR_AREA] = A;

  return U_ghost;
}

DenseMatrix<Real>
BoundaryFlux3EqnGhostDensityVelocity::getGhostCellSolutionJacobian(
    const std::vector<Real> & U_interior) const
{
  const Real rhoA = U_interior[THM3Eqn::CONS_VAR_RHOA];
  const Real rhouA = U_interior[THM3Eqn::CONS_VAR_RHOUA];
  const Real rhoEA = U_interior[THM3Eqn::CONS_VAR_RHOEA];
  const Real A = U_interior[THM3Eqn::CONS_VAR_AREA];

  // Get the pressures from the interior solution

  Real rho = rhoA / A;
  Real drho_drhoA = 1.0 / A;

  Real v, dv_drho;
  THM::v_from_rho(rho, v, dv_drho);
  const Real dv_drhoA = dv_drho * drho_drhoA;

  const Real vel = rhouA / rhoA;

  const Real E = rhoEA / rhoA;
  const Real e = E - 0.5 * vel * vel;
  const Real de_drhoA = THM::de_darhoA(rhoA, rhouA, rhoEA);
  const Real de_drhouA = THM::de_darhouA(rhoA, rhouA);
  const Real de_drhoEA = THM::de_darhoEA(rhoA);

  Real p, dp_dv, dp_de;
  _fp.p_from_v_e(v, e, p, dp_dv, dp_de);
  const Real dp_drhoA = dp_dv * dv_drhoA + dp_de * de_drhoA;
  const Real dp_drhouA = dp_de * de_drhouA;
  const Real dp_drhoEA = dp_de * de_drhoEA;

  // Compute remaining boundary quantities

  const Real rhoA_b = _rho * A;

  Real e_b, de_b_dp, de_b_drho_b;
  _fp.e_from_p_rho(p, _rho, e_b, de_b_dp, de_b_drho_b);
  const Real de_b_drhoA = de_b_dp * dp_drhoA;
  const Real de_b_drhouA = de_b_dp * dp_drhouA;
  const Real de_b_drhoEA = de_b_dp * dp_drhoEA;

  Real E_b, dE_b_de_b, dE_b_dvel_b;
  THM::E_from_e_vel(e_b, _vel, E_b, dE_b_de_b, dE_b_dvel_b);
  const Real dE_b_drhoA = dE_b_de_b * de_b_drhoA;
  const Real dE_b_drhouA = dE_b_de_b * de_b_drhouA;
  const Real dE_b_drhoEA = dE_b_de_b * de_b_drhoEA;

  const Real drhoEA_b_drhoA = rhoA_b * dE_b_drhoA;
  const Real drhoEA_b_drhouA = rhoA_b * dE_b_drhouA;
  const Real drhoEA_b_drhoEA = rhoA_b * dE_b_drhoEA;

  // compute ghost solution Jacobian

  DenseMatrix<Real> J(THM3Eqn::N_EQ, THM3Eqn::N_EQ);

  J(THM3Eqn::EQ_ENERGY, THM3Eqn::EQ_MASS) = drhoEA_b_drhoA;
  J(THM3Eqn::EQ_ENERGY, THM3Eqn::EQ_MOMENTUM) = drhoEA_b_drhouA;
  J(THM3Eqn::EQ_ENERGY, THM3Eqn::EQ_ENERGY) = drhoEA_b_drhoEA;

  return J;
}
<|endoftext|>


<commit_before>#include <iostream>
#include <fstream>
#include <sstream>

#include "mcc/main.h"
#include "mcc/tac/tac.h"

using namespace mcc::tac;

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

	if(argc!=2) {
		std::cout << "usage: mC [file]" << std::endl;
		return -1;
	}

	std::ifstream input{argv[1]};
	std::stringstream buffer;
	buffer << input.rdbuf();
	auto source = buffer.str();

	auto tree = parser::parse(source);

	formatted_ostream out(std::cout);
	out << "Parsed:\n" << tree << "\n";

    // three adress code
    Tac tac;
    tac.convertAst(tree);
	std::cout << "Three-Adress Code:" << std::endl;
    std::cout << tac.toString() << std::endl;
}
<commit_msg>Added tac print after LVN<commit_after>#include <iostream>
#include <fstream>
#include <sstream>

#include "mcc/main.h"
#include "mcc/tac/tac.h"
#include "mcc/lvn/lvn.h"

using namespace mcc::tac;

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

	if(argc!=2) {
		std::cout << "usage: mC [file]" << std::endl;
		return -1;
	}

	std::ifstream input{argv[1]};
	std::stringstream buffer;
	buffer << input.rdbuf();
	auto source = buffer.str();

	auto tree = parser::parse(source);

	formatted_ostream out(std::cout);
	out << "Parsed:\n" << tree << "\n";

    // three adress code
    Tac tac;
    tac.convertAst(tree);
	std::cout << "Three-Adress Code:" << std::endl;
    std::cout << tac.toString() << std::endl;

    mcc::lvn::LVN::transform(tac);

    std::cout << std::endl << "Three-Adress Code after LVN:" << std::endl;
    std::cout << tac.toString() << std::endl;
}
<|endoftext|>


<commit_before>#include "clause.hpp"
#include "internal.hpp"
#include "iterator.hpp"
#include "macros.hpp"
#include "message.hpp"
#include "proof.hpp"

#include <algorithm>
#include <cmath>

namespace CaDiCaL {

// Code for conflict analysis, e.g., to generate the first UIP clause.  The
// main function is 'analyze' below.  It further uses 'minimize' to minimize
// the first UIP clause, which is in 'minimize.cpp'.  An important side
// effect of conflict analysis is to update the decision queue by bumping
// variables.  Similarly resolved clauses are bumped to mark them as active.

/*------------------------------------------------------------------------*/

void Internal::learn_empty_clause () {
  assert (!unsat);
  LOG ("learned empty clause");
  if (proof) proof->trace_empty_clause ();
  unsat = true;
}

void Internal::learn_unit_clause (int lit) {
  LOG ("learned unit clause %d", lit);
  if (proof) proof->trace_unit_clause (lit);
  iterating = true;
  stats.fixed++;
}

/*------------------------------------------------------------------------*/

// Important variables recently used in conflict analysis are 'bumped',
// which means to move them to the front of the VMTF decision queue.  The
// 'bumped' time stamp is updated accordingly.  It is used to determine
// whether the 'queue.assigned' pointer has to be moved in 'unassign'.

void Internal::bump_variable (int lit) {
  const int idx = vidx (lit);
  Link * l = ltab + idx;
  if (!l->next) return;
  queue.dequeue (ltab, l);
  queue.enqueue (ltab, l);
  btab[idx] = ++stats.bumped;
  if (var (idx).level == level) stats.bumplast++;
  LOG ("moved to front %d and bumped %ld", idx, btab[idx]);
  if (!vals[idx]) update_queue_unassigned (idx);
}

struct bumped_earlier {
  Internal * internal;
  bumped_earlier (Internal * i) : internal (i) { }
  bool operator () (int a, int b) {
    return internal->bumped (a) < internal->bumped (b);
  }
};

#if 0
struct bumped_plus_trail_earlier {
  Internal * internal;
  bumped_plus_trail_earlier (Internal * i) : internal (i) { }
  bool operator () (int a, int b) {
    long s = internal->bumped (a) + internal->var (a).trail;
    long t = internal->bumped (b) + internal->var (b).trail;
    return s < t;
  }
};
#endif

void Internal::bump_variables () {
  START (bump);

  if (percent (stats.bumplast, stats.bumped) > opts.bumprevlim &&
      propconf > opts.reverselim) {

    // There are some instances (for instance the 'newton...' instances),
    // which have a very high number of propagations per decision if we try
    // to maintain previous bump order as much as possible.  They go through
    // easily if more recent propagated variables are bumped last, which
    // also reduces propagations per decision by two orders of magnitude.
    // It seems that this is related to the high percentage of bumped
    // variables on the highest decision level.  So if this percentage is
    // hight we take the assignment order into account too by comparing with
    // respect to the sum of bumped and trail order. For the instances
    // mentioned above just comparing with respect to assignment order
    // (e.g., trail height when assigned) would work too, but is in general
    // less robust and thus we use the sum instead.

    reverse (analyzed.begin (), analyzed.end ());
#if 0
    stable_sort (analyzed.begin (),
                 analyzed.end (),
                 bumped_plus_trail_earlier (this));
#endif
    stats.reverse++;

  } else {

    // Otherwise the default is to bump the variable in the order they are
    // in the current decision queue.  This maintains relative order between
    // bumped variables in the queue and seems to work best for those
    // instance with smaller number of bumped variables on the last decision
    // level.

    sort (analyzed.begin (), analyzed.end (), bumped_earlier (this));
  }
  for (const_int_iterator i = analyzed.begin (); i != analyzed.end (); i++)
    bump_variable (*i);

  STOP (bump);
}

/*------------------------------------------------------------------------*/

// Clause activity is replaced by a move-to-front scheme as well with
// 'resolved' as time stamp.  Only long and high glue clauses are stamped
// since small or low glue clauses are kept anyhow (and do not actually have
// a 'resolved' field).  We keep the relative order of bumped clauses by
// sorting them first.

void Internal::bump_resolved_clauses () {
  if (!opts.resolve) { assert (resolved.empty ()); return; }
  START (bump);
  sort (resolved.begin (), resolved.end (), resolved_earlier ());
  for (const_clause_iterator i = resolved.begin (); i != resolved.end (); i++)
    (*i)->resolved () = ++stats.resolved;
  STOP (bump);
  resolved.clear ();
}

inline void Internal::resolve_clause (Clause * c) {
  if (!c->redundant) return;
  if (c->size <= opts.keepsize) return;
  if (c->glue <= opts.keepglue) return;
  assert (c->extended);
  resolved.push_back (c);
}

/*------------------------------------------------------------------------*/

// During conflict analysis literals not seen yet either become part of the
// first UIP clause (if on lower decision level), are dropped (if fixed),
// or are resolved away (if on the current decision level and different from
// the first UIP).  At the same time we update the number of seen literals on
// a decision level.  This helps conflict clause minimization.  The number
// of seen levels is the glucose level (also called glue, or LBD).

inline void Internal::analyze_literal (int lit, int & open) {
  assert (lit);
  Flags & f = flags (lit);
  if (f.seen ()) return;
  Var & v = var (lit);
  if (!v.level) return;
  assert (val (lit) < 0);
  if (v.level < level) clause.push_back (lit);
  Level & l = control[v.level];
  if (!l.seen++) {
    LOG ("found new level %d contributing to conflict", v.level);
    levels.push_back (v.level);
  }
  //if (v.trail < l.trail) l.trail = v.trail;
  f.set (SEEN);
  analyzed.push_back (lit);
  LOG ("analyzed literal %d assigned at level %d", lit, v.level);
  if (v.level == level) open++;
}

inline void
Internal::analyze_reason (int lit, Clause * reason, int & open) {
  assert (reason);
  if (opts.resolve) resolve_clause (reason);
  const const_literal_iterator end = reason->end ();
  const_literal_iterator j = reason->begin ();
  int other;
  while (j != end)
    if ((other = *j++) != lit)
      analyze_literal (other, open);
}

/*------------------------------------------------------------------------*/

void Internal::clear_seen () {
  for (const_int_iterator i = analyzed.begin (); i != analyzed.end (); i++)
    flags (*i).reset ();
  analyzed.clear ();
}

void Internal::clear_levels () {
  for (const_int_iterator i = levels.begin (); i != levels.end (); i++)
    control[*i].reset ();
  levels.clear ();
}

/*------------------------------------------------------------------------*/

struct level_greater {
  Internal * internal;
  level_greater (Internal * s) : internal (s) { }
  bool operator () (int a, int b) {
    return internal->var (a).level > internal->var (b).level;
  }
};

void Internal::analyze () {
  assert (conflict);
  if (!level) { learn_empty_clause (); conflict = 0; return; }

  START (analyze);

  // First derive the first UIP clause.
  //
  Clause * reason = conflict;
  LOG (reason, "analyzing conflict");
  int open = 0, uip = 0, other = 0;
  const_int_iterator i = trail.end ();
  for (;;) {
    if (reason) analyze_reason (uip, reason, open);
    else analyze_literal (other, open);
    while (!seen (uip = *--i))
      ;
    if (!--open) break;
    Var & v = var (uip);
    if (!(reason = v.reason)) other = v.other;
#ifdef LOGGING
    if (reason) LOG (reason, "analyzing %d reason", uip);
    else LOG ("analyzing %d binary reason %d %d", uip, uip, other);
#endif
  }
  LOG ("first UIP %d", uip);
  clause.push_back (-uip);
  reverse (clause.begin (), clause.end ());
  check_clause ();

  // Update glue statistics.
  //
  bump_resolved_clauses ();
  const int glue = (int) levels.size ();
  LOG ("1st UIP clause of size %ld and glue %d",
    (long) clause.size (), glue);
  UPDATE_AVG (fast_glue_avg, glue);
  UPDATE_AVG (slow_glue_avg, glue);

  if (lim.decision_level_at_last_restart) {
    double x = relative (level, lim.decision_level_at_last_restart);
    LOG ("last restart effectiveness %.2f", x);
    UPDATE_AVG (restarteff, x);
    lim.decision_level_at_last_restart = 0;
  }

  if (opts.minimize) minimize_clause ();     // minimize clause

  if (opts.shrink &&
      clause.size () <= (size_t) opts.shrinksize &&
      glue <= opts.shrinkglue)
    shrink_clause ();

  int size = (int) clause.size ();
  stats.units    += (size == 1);
  stats.binaries += (size == 2);
  UPDATE_AVG (size_avg, size);
  if (size > 1 && opts.sublast) eagerly_subsume_last_learned ();

  bump_variables ();                         // Update decision heuristics.

  // Determine back jump level, backtrack and assign flipped literal.
  //
  Clause * driving_clause = 0;
  int jump = 0;
  if (size > 1) {
    stable_sort (clause.begin (), clause.end (), level_greater (this));
    driving_clause = new_learned_clause (glue);
    jump = var (clause[1]).level;
  }
  UPDATE_AVG (jump_avg, jump);
  backtrack (jump);
  assign (-uip, driving_clause);

  // Clean up.
  //
  clear_seen ();
  clause.clear ();
  clear_levels ();
  conflict = 0;

  STOP (analyze);
}

// We wait reporting a learned unit until propagation of that unit is
// completed.  Otherwise the 'i' report line might prematurely give the
// number of remaining variables.

void Internal::iterate () { iterating = false; report ('i'); }

};
<commit_msg>Revert "fixed"<commit_after>#include "clause.hpp"
#include "internal.hpp"
#include "iterator.hpp"
#include "macros.hpp"
#include "message.hpp"
#include "proof.hpp"

#include <algorithm>
#include <cmath>

namespace CaDiCaL {

// Code for conflict analysis, e.g., to generate the first UIP clause.  The
// main function is 'analyze' below.  It further uses 'minimize' to minimize
// the first UIP clause, which is in 'minimize.cpp'.  An important side
// effect of conflict analysis is to update the decision queue by bumping
// variables.  Similarly resolved clauses are bumped to mark them as active.

/*------------------------------------------------------------------------*/

void Internal::learn_empty_clause () {
  assert (!unsat);
  LOG ("learned empty clause");
  if (proof) proof->trace_empty_clause ();
  unsat = true;
}

void Internal::learn_unit_clause (int lit) {
  LOG ("learned unit clause %d", lit);
  if (proof) proof->trace_unit_clause (lit);
  iterating = true;
  stats.fixed++;
}

/*------------------------------------------------------------------------*/

// Important variables recently used in conflict analysis are 'bumped',
// which means to move them to the front of the VMTF decision queue.  The
// 'bumped' time stamp is updated accordingly.  It is used to determine
// whether the 'queue.assigned' pointer has to be moved in 'unassign'.

void Internal::bump_variable (int lit) {
  const int idx = vidx (lit);
  Link * l = ltab + idx;
  if (!l->next) return;
  queue.dequeue (ltab, l);
  queue.enqueue (ltab, l);
  btab[idx] = ++stats.bumped;
  if (var (idx).level == level) stats.bumplast++;
  LOG ("moved to front %d and bumped %ld", idx, btab[idx]);
  if (!vals[idx]) update_queue_unassigned (idx);
}

struct bumped_earlier {
  Internal * internal;
  bumped_earlier (Internal * i) : internal (i) { }
  bool operator () (int a, int b) {
    return internal->bumped (a) < internal->bumped (b);
  }
};

#if 0
struct bumped_plus_trail_earlier {
  Internal * internal;
  bumped_plus_trail_earlier (Internal * i) : internal (i) { }
  bool operator () (int a, int b) {
    long s = internal->bumped (a) + internal->var (a).trail;
    long t = internal->bumped (b) + internal->var (b).trail;
    return s < t;
  }
};
#endif

void Internal::bump_variables () {
  START (bump);

  if (percent (stats.bumplast, stats.bumped) > opts.bumprevlim &&
      propconf > opts.reverselim) {

    // There are some instances (for instance the 'newton...' instances),
    // which have a very high number of propagations per decision if we try
    // to maintain previous bump order as much as possible.  They go through
    // easily if more recent propagated variables are bumped last, which
    // also reduces propagations per decision by two orders of magnitude.
    // It seems that this is related to the high percentage of bumped
    // variables on the highest decision level.  So if this percentage is
    // hight we take the assignment order into account too by comparing with
    // respect to the sum of bumped and trail order. For the instances
    // mentioned above just comparing with respect to assignment order
    // (e.g., trail height when assigned) would work too, but is in general
    // less robust and thus we use the sum instead.

#if 0
    reverse (analyzed.begin (), analyzed.end ());

    stable_sort (analyzed.begin (),
                 analyzed.end (),
                 bumped_plus_trail_earlier (this));
#endif

    stats.reverse++;

  } else {

    // Otherwise the default is to bump the variable in the order they are
    // in the current decision queue.  This maintains relative order between
    // bumped variables in the queue and seems to work best for those
    // instance with smaller number of bumped variables on the last decision
    // level.

    sort (analyzed.begin (), analyzed.end (), bumped_earlier (this));
  }
  for (const_int_iterator i = analyzed.begin (); i != analyzed.end (); i++)
    bump_variable (*i);

  STOP (bump);
}

/*------------------------------------------------------------------------*/

// Clause activity is replaced by a move-to-front scheme as well with
// 'resolved' as time stamp.  Only long and high glue clauses are stamped
// since small or low glue clauses are kept anyhow (and do not actually have
// a 'resolved' field).  We keep the relative order of bumped clauses by
// sorting them first.

void Internal::bump_resolved_clauses () {
  if (!opts.resolve) { assert (resolved.empty ()); return; }
  START (bump);
  sort (resolved.begin (), resolved.end (), resolved_earlier ());
  for (const_clause_iterator i = resolved.begin (); i != resolved.end (); i++)
    (*i)->resolved () = ++stats.resolved;
  STOP (bump);
  resolved.clear ();
}

inline void Internal::resolve_clause (Clause * c) {
  if (!c->redundant) return;
  if (c->size <= opts.keepsize) return;
  if (c->glue <= opts.keepglue) return;
  assert (c->extended);
  resolved.push_back (c);
}

/*------------------------------------------------------------------------*/

// During conflict analysis literals not seen yet either become part of the
// first UIP clause (if on lower decision level), are dropped (if fixed),
// or are resolved away (if on the current decision level and different from
// the first UIP).  At the same time we update the number of seen literals on
// a decision level.  This helps conflict clause minimization.  The number
// of seen levels is the glucose level (also called glue, or LBD).

inline void Internal::analyze_literal (int lit, int & open) {
  assert (lit);
  Flags & f = flags (lit);
  if (f.seen ()) return;
  Var & v = var (lit);
  if (!v.level) return;
  assert (val (lit) < 0);
  if (v.level < level) clause.push_back (lit);
  Level & l = control[v.level];
  if (!l.seen++) {
    LOG ("found new level %d contributing to conflict", v.level);
    levels.push_back (v.level);
  }
  //if (v.trail < l.trail) l.trail = v.trail;
  f.set (SEEN);
  analyzed.push_back (lit);
  LOG ("analyzed literal %d assigned at level %d", lit, v.level);
  if (v.level == level) open++;
}

inline void
Internal::analyze_reason (int lit, Clause * reason, int & open) {
  assert (reason);
  if (opts.resolve) resolve_clause (reason);
  const const_literal_iterator end = reason->end ();
  const_literal_iterator j = reason->begin ();
  int other;
  while (j != end)
    if ((other = *j++) != lit)
      analyze_literal (other, open);
}

/*------------------------------------------------------------------------*/

void Internal::clear_seen () {
  for (const_int_iterator i = analyzed.begin (); i != analyzed.end (); i++)
    flags (*i).reset ();
  analyzed.clear ();
}

void Internal::clear_levels () {
  for (const_int_iterator i = levels.begin (); i != levels.end (); i++)
    control[*i].reset ();
  levels.clear ();
}

/*------------------------------------------------------------------------*/

struct level_greater {
  Internal * internal;
  level_greater (Internal * s) : internal (s) { }
  bool operator () (int a, int b) {
    return internal->var (a).level > internal->var (b).level;
  }
};

void Internal::analyze () {
  assert (conflict);
  if (!level) { learn_empty_clause (); conflict = 0; return; }

  START (analyze);

  // First derive the first UIP clause.
  //
  Clause * reason = conflict;
  LOG (reason, "analyzing conflict");
  int open = 0, uip = 0, other = 0;
  const_int_iterator i = trail.end ();
  for (;;) {
    if (reason) analyze_reason (uip, reason, open);
    else analyze_literal (other, open);
    while (!seen (uip = *--i))
      ;
    if (!--open) break;
    Var & v = var (uip);
    if (!(reason = v.reason)) other = v.other;
#ifdef LOGGING
    if (reason) LOG (reason, "analyzing %d reason", uip);
    else LOG ("analyzing %d binary reason %d %d", uip, uip, other);
#endif
  }
  LOG ("first UIP %d", uip);
  clause.push_back (-uip);
  reverse (clause.begin (), clause.end ());
  check_clause ();

  // Update glue statistics.
  //
  bump_resolved_clauses ();
  const int glue = (int) levels.size ();
  LOG ("1st UIP clause of size %ld and glue %d",
    (long) clause.size (), glue);
  UPDATE_AVG (fast_glue_avg, glue);
  UPDATE_AVG (slow_glue_avg, glue);

  if (lim.decision_level_at_last_restart) {
    double x = relative (level, lim.decision_level_at_last_restart);
    LOG ("last restart effectiveness %.2f", x);
    UPDATE_AVG (restarteff, x);
    lim.decision_level_at_last_restart = 0;
  }

  if (opts.minimize) minimize_clause ();     // minimize clause

  if (opts.shrink &&
      clause.size () <= (size_t) opts.shrinksize &&
      glue <= opts.shrinkglue)
    shrink_clause ();

  int size = (int) clause.size ();
  stats.units    += (size == 1);
  stats.binaries += (size == 2);
  UPDATE_AVG (size_avg, size);
  if (size > 1 && opts.sublast) eagerly_subsume_last_learned ();

  bump_variables ();                         // Update decision heuristics.

  // Determine back jump level, backtrack and assign flipped literal.
  //
  Clause * driving_clause = 0;
  int jump = 0;
  if (size > 1) {
    stable_sort (clause.begin (), clause.end (), level_greater (this));
    driving_clause = new_learned_clause (glue);
    jump = var (clause[1]).level;
  }
  UPDATE_AVG (jump_avg, jump);
  backtrack (jump);
  assign (-uip, driving_clause);

  // Clean up.
  //
  clear_seen ();
  clause.clear ();
  clear_levels ();
  conflict = 0;

  STOP (analyze);
}

// We wait reporting a learned unit until propagation of that unit is
// completed.  Otherwise the 'i' report line might prematurely give the
// number of remaining variables.

void Internal::iterate () { iterating = false; report ('i'); }

};
<|endoftext|>