<commit_before>#include <osg/GL>
#include <osgGLUT/glut>
#include <osgGLUT/Viewer>

#include <osg/Node>
#include <osg/Notify>

#include <osgUtil/Optimizer>

#include <osgDB/Registry>
#include <osgDB/ReadFile>

#include <osgGA/TrackballManipulator>
#include <osgGA/FlightManipulator>
#include <osgGA/DriveManipulator>

#include <osgTXP/TrPageArchive.h>
#include <osgTXP/TrPageViewer.h>

void write_usage(std::ostream& out,const std::string& name)
{
    out << std::endl;
    out <<"usage:"<< std::endl;
    out <<"    "<<name<<" [options] infile1 [infile2 ...]"<< std::endl;
    out << std::endl;
    out <<"options:"<< std::endl;
    out <<"    -l libraryName      - load plugin of name libraryName"<< std::endl;
    out <<"                          i.e. -l osgdb_pfb"<< std::endl;
    out <<"                          Useful for loading reader/writers which can load"<< std::endl;
    out <<"                          other file formats in addition to its extension."<< std::endl;
    out <<"    -e extensionName    - load reader/wrter plugin for file extension"<< std::endl;
    out <<"                          i.e. -e pfb"<< std::endl;
    out <<"                          Useful short hand for specifying full library name as"<< std::endl;
    out <<"                          done with -l above, as it automatically expands to"<< std::endl;
    out <<"                          the full library name appropriate for each platform."<< std::endl;
    out <<std::endl;
    out <<"    -stereo             - switch on stereo rendering, using the default of,"<< std::endl;
    out <<"                          ANAGLYPHIC or the value set in the OSG_STEREO_MODE "<< std::endl;
    out <<"                          environmental variable. See doc/stereo.html for "<< std::endl;
    out <<"                          further details on setting up accurate stereo "<< std::endl;
    out <<"                          for your system. "<< std::endl;
    out <<"    -stereo ANAGLYPHIC  - switch on anaglyphic(red/cyan) stereo rendering."<< std::endl;
    out <<"    -stereo QUAD_BUFFER - switch on quad buffered stereo rendering."<< std::endl;
    out <<std::endl;
    out <<"    -stencil            - use a visual with stencil buffer enabled, this "<< std::endl;
    out <<"                          also allows the depth complexity statistics mode"<< std::endl;
    out <<"                          to be used (press 'p' three times to cycle to it)."<< std::endl;
    out <<"    -f                  - start with a full screen, borderless window." << std::endl;
    out << std::endl;
}

using namespace txp;

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

    // initialize the GLUT
    glutInit( &argc, argv );

    if (argc<2)
    {
        write_usage(std::cout,argv[0]);
        return 0;
    }

    // create the commandline args.
    std::vector<std::string> commandLine;
    for(int i=1;i<argc;++i) commandLine.push_back(argv[i]);

    // initialize the viewer.
    PagingViewer *viewer = new PagingViewer();
    viewer->setWindowTitle(argv[0]);

    // configure the viewer from the commandline arguments, and eat any
    // parameters that have been matched.
    viewer->readCommandLine(commandLine);

    // configure the plugin registry from the commandline arguments, and
    // eat any parameters that have been matched.
    osgDB::readCommandLine(commandLine);

    // Initialize the TXP database
    bool loadAll = false;
    bool threadIt = false;
    std::string fileName;
    for(std::vector<std::string>::iterator itr=commandLine.begin();
        itr!=commandLine.end();
        ++itr)
    {
        if ((*itr)[0]!='-')
        {
	    fileName = (*itr);
        } else {
	    // Look for switches we want
	    if (!strcasecmp((*itr).c_str(),"-loadall")) {
			loadAll = true;
			continue;
	    }
	    if (!strcasecmp((*itr).c_str(),"-thread")) {
				threadIt = true;
				continue;
	    }
	}
    }
    if (fileName.empty()) {
	fprintf(stderr,"No TerraPage file specified on command line.\n");
	return 1;
    }
    // Open the TXP database
    TrPageArchive *txpArchive = new TrPageArchive();
    if (!txpArchive->OpenFile(fileName.c_str())) {
	fprintf(stderr,"Couldn't load TerraPage archive %s.\n",fileName.c_str());
	return 1;
    }
    // Note: Should be checking the return values
    txpArchive->LoadMaterials();
//	txpArchive->LoadModels();

	// Might need a page manager if we're paging
	OSGPageManager *pageManager = new OSGPageManager(txpArchive);
	osg::Group *rootNode=NULL;
	if (loadAll) {
		// Load the whole scenegraph
		rootNode = txpArchive->LoadAllTiles();
		if (!rootNode) {
			fprintf(stderr,"Couldn't load whole TerraPage archive %s.\n",fileName.c_str());
			return 1;
		}
		// add a viewport to the viewer and attach the scene graph.
		viewer->addViewport( rootNode );
	} else {
		viewer->Init(pageManager,(threadIt ? txp::OSGPageManager::ThreadFree : txp::OSGPageManager::ThreadNone));
		rootNode = new osg::Group();
		viewer->addViewport(rootNode);
	}

    // run optimization over the scene graph
//   osgUtil::Optimizer optimzer;
//    optimzer.optimize(rootnode);

    // register trackball, flight and drive.
    viewer->registerCameraManipulator(new osgGA::TrackballManipulator);
    viewer->registerCameraManipulator(new osgGA::FlightManipulator);
    viewer->registerCameraManipulator(new osgGA::DriveManipulator);

	// Recenter the camera to the middle of the database
	osg::Vec3 center;
	txpArchive->GetCenter(center);  center[2] += 200;
	osgUtil::SceneView *sceneView = viewer->getViewportSceneView(0);
	osg::Camera *camera = sceneView->getCamera();
	osg::Vec3 eyePt = center;
	eyePt[0] -= 1000;
	osg::Vec3 upVec( 0, 0, 1 );
	camera->setLookAt(eyePt,center,upVec);

    // open the viewer window.
    viewer->open();

    // fire up the event loop.
    viewer->run();

	// Close things down
	delete pageManager;
	delete txpArchive;
	delete viewer;

    return 0;
}
<commit_msg>Added comment for future reference about the validity of using delete in the demo code... should really by using ref_ptr<> etc.<commit_after>#include <osg/GL>
#include <osgGLUT/glut>
#include <osgGLUT/Viewer>

#include <osg/Node>
#include <osg/Notify>

#include <osgUtil/Optimizer>

#include <osgDB/Registry>
#include <osgDB/ReadFile>

#include <osgGA/TrackballManipulator>
#include <osgGA/FlightManipulator>
#include <osgGA/DriveManipulator>

#include <osgTXP/TrPageArchive.h>
#include <osgTXP/TrPageViewer.h>

void write_usage(std::ostream& out,const std::string& name)
{
    out << std::endl;
    out <<"usage:"<< std::endl;
    out <<"    "<<name<<" [options] infile1 [infile2 ...]"<< std::endl;
    out << std::endl;
    out <<"options:"<< std::endl;
    out <<"    -l libraryName      - load plugin of name libraryName"<< std::endl;
    out <<"                          i.e. -l osgdb_pfb"<< std::endl;
    out <<"                          Useful for loading reader/writers which can load"<< std::endl;
    out <<"                          other file formats in addition to its extension."<< std::endl;
    out <<"    -e extensionName    - load reader/wrter plugin for file extension"<< std::endl;
    out <<"                          i.e. -e pfb"<< std::endl;
    out <<"                          Useful short hand for specifying full library name as"<< std::endl;
    out <<"                          done with -l above, as it automatically expands to"<< std::endl;
    out <<"                          the full library name appropriate for each platform."<< std::endl;
    out <<std::endl;
    out <<"    -stereo             - switch on stereo rendering, using the default of,"<< std::endl;
    out <<"                          ANAGLYPHIC or the value set in the OSG_STEREO_MODE "<< std::endl;
    out <<"                          environmental variable. See doc/stereo.html for "<< std::endl;
    out <<"                          further details on setting up accurate stereo "<< std::endl;
    out <<"                          for your system. "<< std::endl;
    out <<"    -stereo ANAGLYPHIC  - switch on anaglyphic(red/cyan) stereo rendering."<< std::endl;
    out <<"    -stereo QUAD_BUFFER - switch on quad buffered stereo rendering."<< std::endl;
    out <<std::endl;
    out <<"    -stencil            - use a visual with stencil buffer enabled, this "<< std::endl;
    out <<"                          also allows the depth complexity statistics mode"<< std::endl;
    out <<"                          to be used (press 'p' three times to cycle to it)."<< std::endl;
    out <<"    -f                  - start with a full screen, borderless window." << std::endl;
    out << std::endl;
}

using namespace txp;

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

    // initialize the GLUT
    glutInit( &argc, argv );

    if (argc<2)
    {
        write_usage(std::cout,argv[0]);
        return 0;
    }

    // create the commandline args.
    std::vector<std::string> commandLine;
    for(int i=1;i<argc;++i) commandLine.push_back(argv[i]);

    // initialize the viewer.
    PagingViewer *viewer = new PagingViewer();
    viewer->setWindowTitle(argv[0]);

    // configure the viewer from the commandline arguments, and eat any
    // parameters that have been matched.
    viewer->readCommandLine(commandLine);

    // configure the plugin registry from the commandline arguments, and
    // eat any parameters that have been matched.
    osgDB::readCommandLine(commandLine);

    // Initialize the TXP database
    bool loadAll = false;
    bool threadIt = false;
    std::string fileName;
    for(std::vector<std::string>::iterator itr=commandLine.begin();
        itr!=commandLine.end();
        ++itr)
    {
        if ((*itr)[0]!='-')
        {
	    fileName = (*itr);
        } else {
	    // Look for switches we want
	    if (!strcasecmp((*itr).c_str(),"-loadall")) {
			loadAll = true;
			continue;
	    }
	    if (!strcasecmp((*itr).c_str(),"-thread")) {
				threadIt = true;
				continue;
	    }
	}
    }
    if (fileName.empty()) {
	fprintf(stderr,"No TerraPage file specified on command line.\n");
	return 1;
    }
    // Open the TXP database
    TrPageArchive *txpArchive = new TrPageArchive();
    if (!txpArchive->OpenFile(fileName.c_str())) {
	fprintf(stderr,"Couldn't load TerraPage archive %s.\n",fileName.c_str());
	return 1;
    }
    // Note: Should be checking the return values
    txpArchive->LoadMaterials();
//	txpArchive->LoadModels();

	// Might need a page manager if we're paging
	OSGPageManager *pageManager = new OSGPageManager(txpArchive);
	osg::Group *rootNode=NULL;
	if (loadAll) {
		// Load the whole scenegraph
		rootNode = txpArchive->LoadAllTiles();
		if (!rootNode) {
			fprintf(stderr,"Couldn't load whole TerraPage archive %s.\n",fileName.c_str());
			return 1;
		}
		// add a viewport to the viewer and attach the scene graph.
		viewer->addViewport( rootNode );
	} else {
		viewer->Init(pageManager,(threadIt ? txp::OSGPageManager::ThreadFree : txp::OSGPageManager::ThreadNone));
		rootNode = new osg::Group();
		viewer->addViewport(rootNode);
	}

    // run optimization over the scene graph
//   osgUtil::Optimizer optimzer;
//    optimzer.optimize(rootnode);

    // register trackball, flight and drive.
    viewer->registerCameraManipulator(new osgGA::TrackballManipulator);
    viewer->registerCameraManipulator(new osgGA::FlightManipulator);
    viewer->registerCameraManipulator(new osgGA::DriveManipulator);

	// Recenter the camera to the middle of the database
	osg::Vec3 center;
	txpArchive->GetCenter(center);  center[2] += 200;
	osgUtil::SceneView *sceneView = viewer->getViewportSceneView(0);
	osg::Camera *camera = sceneView->getCamera();
	osg::Vec3 eyePt = center;
	eyePt[0] -= 1000;
	osg::Vec3 upVec( 0, 0, 1 );
	camera->setLookAt(eyePt,center,upVec);

    // open the viewer window.
    viewer->open();

    // fire up the event loop.
    viewer->run();

	// Close things down
        // (note from Robert Osfield, umm.... we should be using ref_ptr<> for handling memory here, this isn't robust..)
	delete pageManager;
	delete txpArchive;
	delete viewer;

    return 0;
}
<|endoftext|>


<commit_before>
/*
 * Copyright 2011 Google Inc.
 *
 * Use of this source code is governed by a BSD-style license that can be
 * found in the LICENSE file.
 */
#include "SampleCode.h"
#include "SkView.h"
#include "SkBlurMaskFilter.h"
#include "SkCanvas.h"
#include "SkGradientShader.h"
#include "SkGraphics.h"
#include "SkImageDecoder.h"
#include "SkPath.h"
#include "SkRandom.h"
#include "SkRegion.h"
#include "SkShader.h"
#include "SkUtils.h"
#include "SkXfermode.h"
#include "SkColorPriv.h"
#include "SkColorFilter.h"
#include "SkTime.h"
#include "SkTypeface.h"
#include "SkTextBox.h"
#include "SkOSFile.h"
#include "SkStream.h"
#include "SkKey.h"

#ifdef SK_BUILD_FOR_WIN
extern SkTypeface* SkCreateTypefaceFromLOGFONT(const LOGFONT&);
#endif

static const char gText[] =
	"When in the Course of human events it becomes necessary for one people "
	"to dissolve the political bands which have connected them with another "
	"and to assume among the powers of the earth, the separate and equal "
	"station to which the Laws of Nature and of Nature's God entitle them, "
	"a decent respect to the opinions of mankind requires that they should "
	"declare the causes which impel them to the separation.";

class TextBoxView : public SampleView {
public:
	TextBoxView() {
#ifdef SK_BUILD_FOR_WIN
		LOGFONT lf;
		sk_bzero(&lf, sizeof(lf));
		lf.lfHeight = 9;
		SkTypeface* tf0 = SkCreateTypefaceFromLOGFONT(lf);
		lf.lfHeight = 12;
		SkTypeface* tf1 = SkCreateTypefaceFromLOGFONT(lf);
		// we assert that different sizes should not affect which face we get
		SkASSERT(tf0 == tf1);
		tf0->unref();
		tf1->unref();
#endif
	}

protected:
    // overrides from SkEventSink
    virtual bool onQuery(SkEvent* evt)  {
        if (SampleCode::TitleQ(*evt)) {
            SkString str("TextBox");
            SampleCode::TitleR(evt, str.c_str());
            return true;
        }
        return this->INHERITED::onQuery(evt);
    }

    virtual void onDrawContent(SkCanvas* canvas) {
		SkScalar margin = 20;
        SkTextBox tbox;
		tbox.setMode(SkTextBox::kLineBreak_Mode);
		tbox.setBox(margin, margin,
					this->width() - margin, this->height() - margin);
		tbox.setSpacing(SkIntToScalar(3)/3, 0);

		SkPaint paint;
		paint.setAntiAlias(true);
        paint.setLCDRenderText(true);
		tbox.setText(gText, strlen(gText), paint);

		for (int i = 9; i < 24; i += 2) {
			paint.setTextSize(SkIntToScalar(i));
			tbox.draw(canvas);
			canvas->translate(0, tbox.getTextHeight() + paint.getFontSpacing());
		}
    }

private:
    typedef SkView INHERITED;
};

//////////////////////////////////////////////////////////////////////////////

static SkView* MyFactory() { return new TextBoxView; }
static SkViewRegister reg(MyFactory);

<commit_msg>fix INHERITED to match class<commit_after>
/*
 * Copyright 2011 Google Inc.
 *
 * Use of this source code is governed by a BSD-style license that can be
 * found in the LICENSE file.
 */
#include "SampleCode.h"
#include "SkView.h"
#include "SkBlurMaskFilter.h"
#include "SkCanvas.h"
#include "SkGradientShader.h"
#include "SkGraphics.h"
#include "SkImageDecoder.h"
#include "SkPath.h"
#include "SkRandom.h"
#include "SkRegion.h"
#include "SkShader.h"
#include "SkUtils.h"
#include "SkXfermode.h"
#include "SkColorPriv.h"
#include "SkColorFilter.h"
#include "SkTime.h"
#include "SkTypeface.h"
#include "SkTextBox.h"
#include "SkOSFile.h"
#include "SkStream.h"
#include "SkKey.h"

#ifdef SK_BUILD_FOR_WIN
extern SkTypeface* SkCreateTypefaceFromLOGFONT(const LOGFONT&);
#endif

static const char gText[] =
	"When in the Course of human events it becomes necessary for one people "
	"to dissolve the political bands which have connected them with another "
	"and to assume among the powers of the earth, the separate and equal "
	"station to which the Laws of Nature and of Nature's God entitle them, "
	"a decent respect to the opinions of mankind requires that they should "
	"declare the causes which impel them to the separation.";

class TextBoxView : public SampleView {
public:
	TextBoxView() {
#ifdef SK_BUILD_FOR_WIN
		LOGFONT lf;
		sk_bzero(&lf, sizeof(lf));
		lf.lfHeight = 9;
		SkTypeface* tf0 = SkCreateTypefaceFromLOGFONT(lf);
		lf.lfHeight = 12;
		SkTypeface* tf1 = SkCreateTypefaceFromLOGFONT(lf);
		// we assert that different sizes should not affect which face we get
		SkASSERT(tf0 == tf1);
		tf0->unref();
		tf1->unref();
#endif
	}

protected:
    // overrides from SkEventSink
    virtual bool onQuery(SkEvent* evt)  {
        if (SampleCode::TitleQ(*evt)) {
            SkString str("TextBox");
            SampleCode::TitleR(evt, str.c_str());
            return true;
        }
        return this->INHERITED::onQuery(evt);
    }

    virtual void onDrawContent(SkCanvas* canvas) {
		SkScalar margin = 20;
        SkTextBox tbox;
		tbox.setMode(SkTextBox::kLineBreak_Mode);
		tbox.setBox(margin, margin,
					this->width() - margin, this->height() - margin);
		tbox.setSpacing(SkIntToScalar(3)/3, 0);

		SkPaint paint;
		paint.setAntiAlias(true);
        paint.setLCDRenderText(true);
		tbox.setText(gText, strlen(gText), paint);

		for (int i = 9; i < 24; i += 2) {
			paint.setTextSize(SkIntToScalar(i));
			tbox.draw(canvas);
			canvas->translate(0, tbox.getTextHeight() + paint.getFontSpacing());
		}
    }

private:
    typedef SampleView INHERITED;
};

//////////////////////////////////////////////////////////////////////////////

static SkView* MyFactory() { return new TextBoxView; }
static SkViewRegister reg(MyFactory);

<|endoftext|>


<commit_before>#ifndef __CLUSTERING_ADMINISTRATION_NAMESPACE_METADATA_HPP__
#define __CLUSTERING_ADMINISTRATION_NAMESPACE_METADATA_HPP__

#include <map>

#include "utils.hpp"
#include <boost/uuid/uuid.hpp>
#include <boost/bind.hpp>

#include "clustering/administration/datacenter_metadata.hpp"
#include "clustering/administration/json_adapters.hpp"
#include "clustering/administration/persistable_blueprint.hpp"
#include "clustering/immediate_consistency/branch/metadata.hpp"
#include "clustering/immediate_consistency/query/metadata.hpp"
#include "clustering/reactor/blueprint.hpp"
#include "clustering/reactor/directory_echo.hpp"
#include "clustering/reactor/metadata.hpp"
#include "http/json/json_adapter.hpp"
#include "rpc/semilattice/joins/deletable.hpp"
#include "rpc/semilattice/joins/macros.hpp"
#include "rpc/semilattice/joins/vclock.hpp"
#include "rpc/serialize_macros.hpp"

typedef boost::uuids::uuid namespace_id_t;

/* This is the metadata for a single namespace of a specific protocol. */
template<class protocol_t>
class namespace_semilattice_metadata_t {
public:
    vclock_t<persistable_blueprint_t<protocol_t> > blueprint;

    vclock_t<datacenter_id_t> primary_datacenter;

    vclock_t<std::map<datacenter_id_t, int> > replica_affinities;

    vclock_t<std::set<typename protocol_t::region_t> > shards;

    vclock_t<std::string> name;

    RDB_MAKE_ME_SERIALIZABLE_4(blueprint, primary_datacenter, replica_affinities, shards);
};

template<class protocol_t>
RDB_MAKE_SEMILATTICE_JOINABLE_4(namespace_semilattice_metadata_t<protocol_t>, blueprint, primary_datacenter, replica_affinities, shards);

template<class protocol_t>
RDB_MAKE_EQUALITY_COMPARABLE_4(namespace_semilattice_metadata_t<protocol_t>, blueprint, primary_datacenter, replica_affinities, shards);

//json adapter concept for namespace_semilattice_metadata_t
template <class ctx_t, class protocol_t>
typename json_adapter_if_t<ctx_t>::json_adapter_map_t get_json_subfields(namespace_semilattice_metadata_t<protocol_t> *target, const ctx_t &) {
    typename json_adapter_if_t<ctx_t>::json_adapter_map_t res;
    res["blueprint"] = boost::shared_ptr<json_adapter_if_t<ctx_t> >(new json_adapter_t<vclock_t<persistable_blueprint_t<protocol_t> >, ctx_t>(&target->blueprint));
    res["primary_uuid"] = boost::shared_ptr<json_adapter_if_t<ctx_t> >(new json_adapter_t<vclock_t<datacenter_id_t>, ctx_t>(&target->primary_datacenter));
    res["replica_affinities"] = boost::shared_ptr<json_adapter_if_t<ctx_t> >(new json_adapter_t<vclock_t<std::map<datacenter_id_t, int> >, ctx_t>(&target->replica_affinities));
    res["name"] = boost::shared_ptr<json_adapter_if_t<ctx_t> >(new json_adapter_t<vclock_t<std::string>, ctx_t>(&target->name));
    res["shards"] = boost::shared_ptr<json_adapter_if_t<ctx_t> >(new json_adapter_t<vclock_t<std::set<typename protocol_t::region_t> >, ctx_t>(&target->shards));
    return res;
}

template <class ctx_t, class protocol_t>
cJSON *render_as_json(namespace_semilattice_metadata_t<protocol_t> *target, const ctx_t &ctx) {
    return render_as_directory(target, ctx);
}

template <class ctx_t, class protocol_t>
void apply_json_to(cJSON *change, namespace_semilattice_metadata_t<protocol_t> *target, const ctx_t &ctx) {
    apply_as_directory(change, target, ctx);
}

template <class ctx_t, class protocol_t>
void on_subfield_change(namespace_semilattice_metadata_t<protocol_t> *, const ctx_t &) { }

/* This is the metadata for all of the namespaces of a specific protocol. */
template <class protocol_t>
class namespaces_semilattice_metadata_t {
public:
    typedef std::map<namespace_id_t, deletable_t<namespace_semilattice_metadata_t<protocol_t> > > namespace_map_t;
    namespace_map_t namespaces;

    branch_history_t<protocol_t> branch_history;

    RDB_MAKE_ME_SERIALIZABLE_2(namespaces, branch_history);
};

template<class protocol_t>
RDB_MAKE_SEMILATTICE_JOINABLE_2(namespaces_semilattice_metadata_t<protocol_t>, namespaces, branch_history);

template<class protocol_t>
RDB_MAKE_EQUALITY_COMPARABLE_2(namespaces_semilattice_metadata_t<protocol_t>, namespaces, branch_history);

//json adapter concept for namespaces_semilattice_metadata_t

template <class ctx_t, class protocol_t>
typename json_adapter_if_t<ctx_t>::json_adapter_map_t get_json_subfields(namespaces_semilattice_metadata_t<protocol_t> *target, const ctx_t &ctx) {
    return get_json_subfields(&target->namespaces, ctx);
}

template <class ctx_t, class protocol_t>
cJSON *render_as_json(namespaces_semilattice_metadata_t<protocol_t> *target, const ctx_t &ctx) {
    return render_as_json(&target->namespaces, ctx);
}

template <class ctx_t, class protocol_t>
void apply_json_to(cJSON *change, namespaces_semilattice_metadata_t<protocol_t> *target, const ctx_t &ctx) {
    apply_as_directory(change, &target->namespaces, ctx);
}

template <class ctx_t, class protocol_t>
void on_subfield_change(namespaces_semilattice_metadata_t<protocol_t> *target, const ctx_t &ctx) {
    on_subfield_change(&target->namespaces, ctx);
}

template <class protocol_t>
class namespaces_directory_metadata_t {
public:
    std::map<namespace_id_t, directory_echo_wrapper_t<reactor_business_card_t<protocol_t> > > reactor_bcards;
    std::map<namespace_id_t, std::map<master_id_t, master_business_card_t<protocol_t> > > master_maps;

    RDB_MAKE_ME_SERIALIZABLE_2(reactor_bcards, master_maps);
};

struct namespace_metadata_ctx_t {
    boost::uuids::uuid us;
    explicit namespace_metadata_ctx_t(boost::uuids::uuid _us)
        : us(_us)
    { }
};

#endif /* __CLUSTERING_ARCHITECT_METADATA_HPP__ */

<commit_msg>fixing namespace name syncing across the cluster<commit_after>#ifndef __CLUSTERING_ADMINISTRATION_NAMESPACE_METADATA_HPP__
#define __CLUSTERING_ADMINISTRATION_NAMESPACE_METADATA_HPP__

#include <map>

#include "utils.hpp"
#include <boost/uuid/uuid.hpp>
#include <boost/bind.hpp>

#include "clustering/administration/datacenter_metadata.hpp"
#include "clustering/administration/json_adapters.hpp"
#include "clustering/administration/persistable_blueprint.hpp"
#include "clustering/immediate_consistency/branch/metadata.hpp"
#include "clustering/immediate_consistency/query/metadata.hpp"
#include "clustering/reactor/blueprint.hpp"
#include "clustering/reactor/directory_echo.hpp"
#include "clustering/reactor/metadata.hpp"
#include "http/json/json_adapter.hpp"
#include "rpc/semilattice/joins/deletable.hpp"
#include "rpc/semilattice/joins/macros.hpp"
#include "rpc/semilattice/joins/vclock.hpp"
#include "rpc/serialize_macros.hpp"

typedef boost::uuids::uuid namespace_id_t;

/* This is the metadata for a single namespace of a specific protocol. */
template<class protocol_t>
class namespace_semilattice_metadata_t {
public:
    vclock_t<persistable_blueprint_t<protocol_t> > blueprint;

    vclock_t<datacenter_id_t> primary_datacenter;

    vclock_t<std::map<datacenter_id_t, int> > replica_affinities;

    vclock_t<std::set<typename protocol_t::region_t> > shards;

    vclock_t<std::string> name;

    RDB_MAKE_ME_SERIALIZABLE_5(blueprint, primary_datacenter, replica_affinities, shards, name);
};

template<class protocol_t>
RDB_MAKE_SEMILATTICE_JOINABLE_5(namespace_semilattice_metadata_t<protocol_t>, blueprint, primary_datacenter, replica_affinities, shards, name);

template<class protocol_t>
RDB_MAKE_EQUALITY_COMPARABLE_5(namespace_semilattice_metadata_t<protocol_t>, blueprint, primary_datacenter, replica_affinities, shards, name);

//json adapter concept for namespace_semilattice_metadata_t
template <class ctx_t, class protocol_t>
typename json_adapter_if_t<ctx_t>::json_adapter_map_t get_json_subfields(namespace_semilattice_metadata_t<protocol_t> *target, const ctx_t &) {
    typename json_adapter_if_t<ctx_t>::json_adapter_map_t res;
    res["blueprint"] = boost::shared_ptr<json_adapter_if_t<ctx_t> >(new json_adapter_t<vclock_t<persistable_blueprint_t<protocol_t> >, ctx_t>(&target->blueprint));
    res["primary_uuid"] = boost::shared_ptr<json_adapter_if_t<ctx_t> >(new json_adapter_t<vclock_t<datacenter_id_t>, ctx_t>(&target->primary_datacenter));
    res["replica_affinities"] = boost::shared_ptr<json_adapter_if_t<ctx_t> >(new json_adapter_t<vclock_t<std::map<datacenter_id_t, int> >, ctx_t>(&target->replica_affinities));
    res["name"] = boost::shared_ptr<json_adapter_if_t<ctx_t> >(new json_adapter_t<vclock_t<std::string>, ctx_t>(&target->name));
    res["shards"] = boost::shared_ptr<json_adapter_if_t<ctx_t> >(new json_adapter_t<vclock_t<std::set<typename protocol_t::region_t> >, ctx_t>(&target->shards));
    return res;
}

template <class ctx_t, class protocol_t>
cJSON *render_as_json(namespace_semilattice_metadata_t<protocol_t> *target, const ctx_t &ctx) {
    return render_as_directory(target, ctx);
}

template <class ctx_t, class protocol_t>
void apply_json_to(cJSON *change, namespace_semilattice_metadata_t<protocol_t> *target, const ctx_t &ctx) {
    apply_as_directory(change, target, ctx);
}

template <class ctx_t, class protocol_t>
void on_subfield_change(namespace_semilattice_metadata_t<protocol_t> *, const ctx_t &) { }

/* This is the metadata for all of the namespaces of a specific protocol. */
template <class protocol_t>
class namespaces_semilattice_metadata_t {
public:
    typedef std::map<namespace_id_t, deletable_t<namespace_semilattice_metadata_t<protocol_t> > > namespace_map_t;
    namespace_map_t namespaces;

    branch_history_t<protocol_t> branch_history;

    RDB_MAKE_ME_SERIALIZABLE_2(namespaces, branch_history);
};

template<class protocol_t>
RDB_MAKE_SEMILATTICE_JOINABLE_2(namespaces_semilattice_metadata_t<protocol_t>, namespaces, branch_history);

template<class protocol_t>
RDB_MAKE_EQUALITY_COMPARABLE_2(namespaces_semilattice_metadata_t<protocol_t>, namespaces, branch_history);

//json adapter concept for namespaces_semilattice_metadata_t

template <class ctx_t, class protocol_t>
typename json_adapter_if_t<ctx_t>::json_adapter_map_t get_json_subfields(namespaces_semilattice_metadata_t<protocol_t> *target, const ctx_t &ctx) {
    return get_json_subfields(&target->namespaces, ctx);
}

template <class ctx_t, class protocol_t>
cJSON *render_as_json(namespaces_semilattice_metadata_t<protocol_t> *target, const ctx_t &ctx) {
    return render_as_json(&target->namespaces, ctx);
}

template <class ctx_t, class protocol_t>
void apply_json_to(cJSON *change, namespaces_semilattice_metadata_t<protocol_t> *target, const ctx_t &ctx) {
    apply_as_directory(change, &target->namespaces, ctx);
}

template <class ctx_t, class protocol_t>
void on_subfield_change(namespaces_semilattice_metadata_t<protocol_t> *target, const ctx_t &ctx) {
    on_subfield_change(&target->namespaces, ctx);
}

template <class protocol_t>
class namespaces_directory_metadata_t {
public:
    std::map<namespace_id_t, directory_echo_wrapper_t<reactor_business_card_t<protocol_t> > > reactor_bcards;
    std::map<namespace_id_t, std::map<master_id_t, master_business_card_t<protocol_t> > > master_maps;

    RDB_MAKE_ME_SERIALIZABLE_2(reactor_bcards, master_maps);
};

struct namespace_metadata_ctx_t {
    boost::uuids::uuid us;
    explicit namespace_metadata_ctx_t(boost::uuids::uuid _us)
        : us(_us)
    { }
};

#endif /* __CLUSTERING_ARCHITECT_METADATA_HPP__ */

<|endoftext|>


<commit_before>/*============================================================================*/
/*
  Copyright (C) 2008 by Vinnie Falco, this file is part of VFLib.
  See the file GNU_GPL_v2.txt for full licensing terms.

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

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

  You should have received a copy of the GNU General Public License along with
  this program; if not, write to the Free Software Foundation, Inc., 51
  Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
*/
/*============================================================================*/

class MidiDevicesImp : public MidiDevices, private Timer, private Thread
{
private:
  struct CompareDevices
  {
    static int compareElements (Device const* const lhs, Device const* const rhs)
    {
      return lhs->getName ().compare (rhs->getName ());
    }

    static int compareElements (String const s, Device const* const rhs)
    {
      return s.compare (rhs->getName ());
    }
  };

  //============================================================================

  class InputImp : public Input
  {
  private:
    InputImp& operator= (InputImp const&);

    String const m_name;
    int m_deviceIndex;

  public:
    InputImp (String const name, int deviceIndex)
      : m_name (name)
      , m_deviceIndex (deviceIndex)
    {
    }

    String getName () const
    {
      return m_name;
    }

    int getDeviceIndex () const
    {
      return m_deviceIndex;
    }

    void setDeviceIndex (int newDeviceIndex)
    {
      m_deviceIndex = newDeviceIndex;
    }
  };

  //============================================================================

  class OutputImp : public Output
  {
  private:
    OutputImp& operator= (OutputImp const&);

    String const m_name;
    int m_deviceIndex;

  public:
    OutputImp (String const name, int deviceIndex)
      : m_name (name)
      , m_deviceIndex (deviceIndex)
    {
    }

    String getName () const
    {
      return m_name;
    }

    int getDeviceIndex () const
    {
      return m_deviceIndex;
    }

    void setDeviceIndex (int newDeviceIndex)
    {
      m_deviceIndex = newDeviceIndex;
    }
  };

private:
  //============================================================================

  struct State
  {
    OwnedArray <InputImp> inputs;
    OwnedArray <OutputImp> outputs;
  };

  typedef ConcurrentState <State> StateType;

  StateType m_state;
  vf::Listeners <Listener> m_listeners;

public:
  //============================================================================

  MidiDevicesImp () : Thread ("MidiDevices")
  {
    // This object must be created from the JUCE Message Thread.
    //
    vfassert (MessageManager::getInstance()->isThisTheMessageThread());

    //startTimer (1000);
    startThread ();
  }

  ~MidiDevicesImp ()
  {
    stopThread (-1);
  }

  void addListener (Listener* listener, CallQueue& thread)
  {
    m_listeners.add (listener, thread);
  }

  void removeListener (Listener* listener)
  {
    m_listeners.remove (listener);
  }

private:
  //----------------------------------------------------------------------------

  void scanInputDevices ()
  {
    StateType::WriteAccess state (m_state);

    // Make a copy of the currently connected devices.
    Array <InputImp*> disconnected;
    disconnected.ensureStorageAllocated (state->inputs.size ());
    for (int i = 0; i < state->inputs.size (); ++i)
    {
      InputImp* const device = state->inputs [i];
      if (device->getDeviceIndex () != -1)
        disconnected.add (device);
    }

    // Enumerate connected devices.
    StringArray const devices (juce::MidiInput::getDevices ());
    for (int deviceIndex = 0; deviceIndex < devices.size (); ++deviceIndex)
    {
      CompareDevices comp;
      String const deviceName (devices [deviceIndex]);

      // Remove this device from list of disconnected devices.
      {
        int const index = disconnected.indexOfSorted (comp, deviceName);
        if (index != -1)
          disconnected.remove (index);
      }

      // Find this device in our list.
      int const index = state->inputs.indexOfSorted (comp, deviceName);

      if (index != -1)
      {
        // Device already exists
        InputImp* const device = state->inputs [index];

        // Notify listeners with connected status.
        if (device->getDeviceIndex () == -1)
        {
          m_listeners.queue (&Listener::onMidiDevicesStatus, device, true);

          Logger::outputDebugString (device->getName () + ": connected");
        }

        device->setDeviceIndex (deviceIndex);
      }
      else
      {
        InputImp* const device = new InputImp (deviceName, deviceIndex);

        state->inputs.addSorted (comp, device);
      }
    }

    // Notify listeners with disconnected status.
    for (int i = 0; i < disconnected.size (); ++i)
    {
      InputImp* const device = disconnected [i];
      device->setDeviceIndex (-1);

      m_listeners.queue (&Listener::onMidiDevicesStatus, device, false);

      Logger::outputDebugString (device->getName () + ": disconnected");
    }
  }

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

  void scanOutputDevices ()
  {
    StateType::WriteAccess state (m_state);

    StringArray const devices (juce::MidiOutput::getDevices ());
  }

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

  void timerCallback ()
  {
    scanInputDevices ();
    scanOutputDevices ();
  }

  void run ()
  {
    do
    {
      wait (1000);

      scanInputDevices ();
      scanOutputDevices ();
    }
    while (!threadShouldExit ());
  }
};

//==============================================================================

MidiDevices* MidiDevices::createInstance ()
{
  return new MidiDevicesImp;
}
<commit_msg>Comment out MidiDevices function for changed JUCE api<commit_after>/*============================================================================*/
/*
  Copyright (C) 2008 by Vinnie Falco, this file is part of VFLib.
  See the file GNU_GPL_v2.txt for full licensing terms.

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

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

  You should have received a copy of the GNU General Public License along with
  this program; if not, write to the Free Software Foundation, Inc., 51
  Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
*/
/*============================================================================*/

class MidiDevicesImp : public MidiDevices, private Timer, private Thread
{
private:
  struct CompareDevices
  {
    static int compareElements (Device const* const lhs, Device const* const rhs)
    {
      return lhs->getName ().compare (rhs->getName ());
    }

    static int compareElements (String const s, Device const* const rhs)
    {
      return s.compare (rhs->getName ());
    }
  };

  //============================================================================

  class InputImp : public Input
  {
  private:
    InputImp& operator= (InputImp const&);

    String const m_name;
    int m_deviceIndex;

  public:
    InputImp (String const name, int deviceIndex)
      : m_name (name)
      , m_deviceIndex (deviceIndex)
    {
    }

    String getName () const
    {
      return m_name;
    }

    int getDeviceIndex () const
    {
      return m_deviceIndex;
    }

    void setDeviceIndex (int newDeviceIndex)
    {
      m_deviceIndex = newDeviceIndex;
    }
  };

  //============================================================================

  class OutputImp : public Output
  {
  private:
    OutputImp& operator= (OutputImp const&);

    String const m_name;
    int m_deviceIndex;

  public:
    OutputImp (String const name, int deviceIndex)
      : m_name (name)
      , m_deviceIndex (deviceIndex)
    {
    }

    String getName () const
    {
      return m_name;
    }

    int getDeviceIndex () const
    {
      return m_deviceIndex;
    }

    void setDeviceIndex (int newDeviceIndex)
    {
      m_deviceIndex = newDeviceIndex;
    }
  };

private:
  //============================================================================

  struct State
  {
    OwnedArray <InputImp> inputs;
    OwnedArray <OutputImp> outputs;
  };

  typedef ConcurrentState <State> StateType;

  StateType m_state;
  vf::Listeners <Listener> m_listeners;

public:
  //============================================================================

  MidiDevicesImp () : Thread ("MidiDevices")
  {
    // This object must be created from the JUCE Message Thread.
    //
    vfassert (MessageManager::getInstance()->isThisTheMessageThread());

    //startTimer (1000);
    startThread ();
  }

  ~MidiDevicesImp ()
  {
    stopThread (-1);
  }

  void addListener (Listener* listener, CallQueue& thread)
  {
    m_listeners.add (listener, thread);
  }

  void removeListener (Listener* listener)
  {
    m_listeners.remove (listener);
  }

private:
  //----------------------------------------------------------------------------

  void scanInputDevices ()
  {
#if 0
    StateType::WriteAccess state (m_state);

    // Make a copy of the currently connected devices.
    Array <InputImp*> disconnected;
    disconnected.ensureStorageAllocated (state->inputs.size ());
    for (int i = 0; i < state->inputs.size (); ++i)
    {
      InputImp* const device = state->inputs [i];
      if (device->getDeviceIndex () != -1)
        disconnected.add (device);
    }

    // Enumerate connected devices.
    StringArray const devices (juce::MidiInput::getDevices ());
    for (int deviceIndex = 0; deviceIndex < devices.size (); ++deviceIndex)
    {
      CompareDevices comp;
      String const deviceName (devices [deviceIndex]);

      // Remove this device from list of disconnected devices.
      {
        int const index = disconnected.indexOfSorted (comp, deviceName);
        if (index != -1)
          disconnected.remove (index);
      }

      // Find this device in our list.
      int const index = state->inputs.indexOfSorted (comp, deviceName);

      if (index != -1)
      {
        // Device already exists
        InputImp* const device = state->inputs [index];

        // Notify listeners with connected status.
        if (device->getDeviceIndex () == -1)
        {
          m_listeners.queue (&Listener::onMidiDevicesStatus, device, true);

          Logger::outputDebugString (device->getName () + ": connected");
        }

        device->setDeviceIndex (deviceIndex);
      }
      else
      {
        InputImp* const device = new InputImp (deviceName, deviceIndex);

        state->inputs.addSorted (comp, device);
      }
    }

    // Notify listeners with disconnected status.
    for (int i = 0; i < disconnected.size (); ++i)
    {
      InputImp* const device = disconnected [i];
      device->setDeviceIndex (-1);

      m_listeners.queue (&Listener::onMidiDevicesStatus, device, false);

      Logger::outputDebugString (device->getName () + ": disconnected");
    }
#else
    jassertfalse;
#endif
  }

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

  void scanOutputDevices ()
  {
    StateType::WriteAccess state (m_state);

    StringArray const devices (juce::MidiOutput::getDevices ());
  }

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

  void timerCallback ()
  {
    scanInputDevices ();
    scanOutputDevices ();
  }

  void run ()
  {
    do
    {
      wait (1000);

      scanInputDevices ();
      scanOutputDevices ();
    }
    while (!threadShouldExit ());
  }
};

//==============================================================================

MidiDevices* MidiDevices::createInstance ()
{
  return new MidiDevicesImp;
}
<|endoftext|>


<commit_before>/************************************************************************
	filename: 	CEGUIRenderer.cpp
	created:	20/2/2004
	author:		Paul D Turner

	purpose:	Some base class implementation for Renderer objects
*************************************************************************/
/*************************************************************************
    Crazy Eddie's GUI System (http://crayzedsgui.sourceforge.net)
    Copyright (C)2004 Paul D Turner (crayzed@users.sourceforge.net)

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

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

    You should have received a copy of the GNU Lesser General Public
    License along with this library; if not, write to the Free Software
    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
*************************************************************************/
#include "CEGUIRenderer.h"
#include "CEGUIEventSet.h"
#include "CEGUIEvent.h"
#include "CEGUIDefaultResourceProvider.h"

// Start of CEGUI namespace section
namespace CEGUI
{

/*************************************************************************
	Event name constants (static data definitions)
*************************************************************************/
const utf8	Renderer::EventDisplaySizeChanged[]		= "DisplayModeChanged";

/*************************************************************************
	Implementation constants
*************************************************************************/
const float	Renderer::GuiZInitialValue		= 1.0f;
const float	Renderer::GuiZElementStep		= 0.001f;		// this is enough for 1000 Windows.
const float	Renderer::GuiZLayerStep			= 0.0001f;		// provides space for 10 layers per Window.

/*************************************************************************
	Constructor
*************************************************************************/
Renderer::Renderer(void)
{
	// setup standard events available
	addEvent(EventDisplaySizeChanged);

	// default initialisation
	resetZValue();
}

/*************************************************************************
	Destructor
*************************************************************************/
Renderer::~Renderer(void)
{
    if(d_resourceProvider)
    {
        delete d_resourceProvider;
        d_resourceProvider = 0;
    }
}

ResourceProvider* Renderer::createResourceProvider(void)
{
    d_resourceProvider = new DefaultResourceProvider();
    return d_resourceProvider;
}

} // End of  CEGUI namespace section
<commit_msg>Initialise d_resourceProvider.<commit_after>/************************************************************************
	filename: 	CEGUIRenderer.cpp
	created:	20/2/2004
	author:		Paul D Turner

	purpose:	Some base class implementation for Renderer objects
*************************************************************************/
/*************************************************************************
    Crazy Eddie's GUI System (http://crayzedsgui.sourceforge.net)
    Copyright (C)2004 Paul D Turner (crayzed@users.sourceforge.net)

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

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

    You should have received a copy of the GNU Lesser General Public
    License along with this library; if not, write to the Free Software
    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
*************************************************************************/
#include "CEGUIRenderer.h"
#include "CEGUIEventSet.h"
#include "CEGUIEvent.h"
#include "CEGUIDefaultResourceProvider.h"

// Start of CEGUI namespace section
namespace CEGUI
{

/*************************************************************************
	Event name constants (static data definitions)
*************************************************************************/
const utf8	Renderer::EventDisplaySizeChanged[]		= "DisplayModeChanged";

/*************************************************************************
	Implementation constants
*************************************************************************/
const float	Renderer::GuiZInitialValue		= 1.0f;
const float	Renderer::GuiZElementStep		= 0.001f;		// this is enough for 1000 Windows.
const float	Renderer::GuiZLayerStep			= 0.0001f;		// provides space for 10 layers per Window.

/*************************************************************************
	Constructor
*************************************************************************/
Renderer::Renderer(void)
    : d_resourceProvider(0)
{
	// setup standard events available
	addEvent(EventDisplaySizeChanged);

	// default initialisation
	resetZValue();
}

/*************************************************************************
	Destructor
*************************************************************************/
Renderer::~Renderer(void)
{
    if(d_resourceProvider)
    {
        delete d_resourceProvider;
        d_resourceProvider = 0;
    }
}

ResourceProvider* Renderer::createResourceProvider(void)
{
    d_resourceProvider = new DefaultResourceProvider();
    return d_resourceProvider;
}

} // End of  CEGUI namespace section
<|endoftext|>


<commit_before>#include "opencv2/highgui/highgui.hpp"
#include "opencv2/imgproc/imgproc.hpp"

#include <iostream>

using namespace cv;
using namespace std;

static void help()
{
    cout << "\nThis program demonstrates circle finding with the Hough transform.\n"
            "Usage:\n"
            "./houghcircles <image_name>, Default is pic1.png\n" << endl;
}

int main(int argc, char** argv)
{
    const char* filename = argc >= 2 ? argv[1] : "board.jpg";

    Mat img = imread(filename, 0);
    if(img.empty())
    {
        help();
        cout << "can not open " << filename << endl;
        return -1;
    }

    Mat cimg;
    medianBlur(img, img, 5);
    cvtColor(img, cimg, COLOR_GRAY2BGR);

    vector<Vec3f> circles;
    HoughCircles(img, circles, CV_HOUGH_GRADIENT, 1, 10,
                 100, 30, 1, 30 // change the last two parameters
                                // (min_radius & max_radius) to detect larger circles
                 );
    for( size_t i = 0; i < circles.size(); i++ )
    {
        Vec3i c = circles[i];
        circle( cimg, Point(c[0], c[1]), c[2], Scalar(0,0,255), 3, CV_AA);
        circle( cimg, Point(c[0], c[1]), 2, Scalar(0,255,0), 3, CV_AA);
    }

    imshow("detected circles", cimg);
    waitKey();

    return 0;
}
<commit_msg>filename correction from #3217<commit_after>#include "opencv2/highgui/highgui.hpp"
#include "opencv2/imgproc/imgproc.hpp"

#include <iostream>

using namespace cv;
using namespace std;

static void help()
{
    cout << "\nThis program demonstrates circle finding with the Hough transform.\n"
            "Usage:\n"
            "./houghcircles <image_name>, Default is board.jpg\n" << endl;
}

int main(int argc, char** argv)
{
    const char* filename = argc >= 2 ? argv[1] : "board.jpg";

    Mat img = imread(filename, 0);
    if(img.empty())
    {
        help();
        cout << "can not open " << filename << endl;
        return -1;
    }

    Mat cimg;
    medianBlur(img, img, 5);
    cvtColor(img, cimg, COLOR_GRAY2BGR);

    vector<Vec3f> circles;
    HoughCircles(img, circles, CV_HOUGH_GRADIENT, 1, 10,
                 100, 30, 1, 30 // change the last two parameters
                                // (min_radius & max_radius) to detect larger circles
                 );
    for( size_t i = 0; i < circles.size(); i++ )
    {
        Vec3i c = circles[i];
        circle( cimg, Point(c[0], c[1]), c[2], Scalar(0,0,255), 3, CV_AA);
        circle( cimg, Point(c[0], c[1]), 2, Scalar(0,255,0), 3, CV_AA);
    }

    imshow("detected circles", cimg);
    waitKey();

    return 0;
}
<|endoftext|>


<commit_before>#include "common/lazyworld.h"
#include <cstdio>

void LazyWorld::DoStep() {
    // Collision check against player
}

void LazyWorld::CheckCollision(Entity *entity) {
    PositionedBlock *block;

    for (std::list<PositionedBlock*>::iterator it = VisibleBlocks.begin(); it != VisibleBlocks.end(); ++it) {
        block = *it;
        if (block->block->Type == 0) continue;

        if (entity->Pos.X + entity->Hitbox.X >= block->pos.X && entity->Pos.X <= block->pos.X + 1
         && entity->Pos.Y + entity->Hitbox.Y >= block->pos.Y && entity->Pos.Y <= block->pos.Y + 1
         && entity->Pos.Z + entity->Hitbox.Z >= block->pos.Z && entity->Pos.Z <= block->pos.Z + 1)
            entity->Collide(*block);
    }
}

PositionedBlock *LazyWorld::CheckAim(Player *player) {
    PositionedBlock *block;
    Ray ray = Ray(player);

    PositionedBlock *target = NULL;
    float dist, best = 5.f;

    for (std::list<PositionedBlock*>::iterator it = VisibleBlocks.begin(); it != VisibleBlocks.end(); ++it) {
        block = *it; // Blocks[i];

        dist = ray.CheckCollision(block);
        if (0.f < dist && dist < best) {
            best = dist;
            target = block;
        }
    }

    if (target != NULL)
        target->marked = true;

    return target;
}

void LazyWorld::DestroyTarget(Player *player) {
    PositionedBlock *block = CheckAim(player);
    if (!block) return;
    VisibleBlocks.remove(block);

    Vector3 chunkindex, pos;

    chunkindex.X = floor(block->pos.X / ChunkSize);
    chunkindex.Y = floor(block->pos.Y / ChunkSize);
    chunkindex.Z = floor(block->pos.Z / ChunkSize);
    pos = block->pos - (chunkindex * 16);

    std::map<Vector3, Block*> chunk = LoadedChunks[chunkindex];

    Block *blk;

    if (pos.X > 0 && chunk[pos - Vector3(1, 0, 0)]->Type > 0) {
        blk = chunk[pos - Vector3(1, 0, 0)];
        if (blk->faces == 0) VisibleBlocks.push_back(new PositionedBlock(blk, block->pos - Vector3(1, 0, 0), 1));
        blk->faces |= 0x08;
    }

    if (pos.Y > 0 && chunk[pos - Vector3(0, 1, 0)]->Type > 0) {
        blk = chunk[pos - Vector3(0, 1, 0)];
        if (blk->faces == 0) VisibleBlocks.push_back(new PositionedBlock(blk, block->pos - Vector3(0, 1, 0), 1));
        blk->faces |= 0x10;
    }

    if (pos.Z > 0 && chunk[pos - Vector3(0, 0, 1)]->Type > 0) {
        blk = chunk[pos - Vector3(0, 0, 1)];
        if (blk->faces == 0) VisibleBlocks.push_back(new PositionedBlock(blk, block->pos - Vector3(0, 0, 1), 1));
        blk->faces |= 0x20;
    }

    if (pos.X < 15 && chunk[pos + Vector3(1, 0, 0)]->Type > 0) {
        blk = chunk[pos + Vector3(1, 0, 0)];
        if (blk->faces == 0) VisibleBlocks.push_back(new PositionedBlock(blk, block->pos + Vector3(1, 0, 0), 1));
        blk->faces |= 0x01;
    }

    if (pos.Y < 15 && chunk[pos + Vector3(0, 1, 0)]->Type > 0) {
        blk = chunk[pos + Vector3(0, 1, 0)];
        if (blk->faces == 0) VisibleBlocks.push_back(new PositionedBlock(blk, block->pos + Vector3(0, 1, 0), 1));
        blk->faces |= 0x02;
    }

    if (pos.Z < 15 && chunk[pos + Vector3(0, 0, 1)]->Type > 0) {
        blk = chunk[pos + Vector3(0, 0, 1)];
        if (blk->faces == 0) VisibleBlocks.push_back(new PositionedBlock(blk, block->pos + Vector3(0, 0, 1), 1));
        blk->faces |= 0x04;
    }
}

bool contains(std::vector<Vector3> vector, Vector3 value) {
    for (int i = 0; i < vector.size(); i++)
        if (vector[i] == value) return true;

    return false;
}

void LazyWorld::LoadChunk(sf::Packet Packet) {
    int BlockCount;
    Vector3 ChunkIndex; // TODO: remove from request list, add to loaded list
    Packet >> ChunkIndex >> BlockCount;

    std::map<Vector3, Block*> chunk;

    sf::Uint8 type;
    Block *block;
    Vector3 Pos;
    float SideLength;

    printf("0 (%f, %f, %f)\n", ChunkIndex.X, ChunkIndex.Y, ChunkIndex.Z);

    for (int i = 0; i < BlockCount; i++) {
        Packet >> type >> Pos;

        if (type == 3)
            block = new GrassBlock();
        else
            block = new AirBlock();

        chunk[Vector3(Pos)] = block;
    }

    for (std::map<Vector3, Block*>::iterator it = chunk.begin(); it != chunk.end(); ++it) {
        if (it->second->Type == 0) continue;
        Pos = it->first;

        char sides = 0x3F;

        if (Pos.X > 0 && chunk[Pos - Vector3(1, 0, 0)]->Type > 0)
            sides &= (0xFE); // 0b00000001

        if (Pos.Y > 0 && chunk[Pos - Vector3(0, 1, 0)]->Type > 0)
            sides &= (0xFD); // 0b00000010

        if (Pos.Z > 0 && chunk[Pos - Vector3(0, 0, 1)]->Type > 0)
            sides &= (0xFB); // 0b00000100

        if (Pos.X < 15 && chunk[Pos + Vector3(1, 0, 0)]->Type > 0)
            sides &= (0xF7); // 0b00001000

        if (Pos.Y < 15 && chunk[Pos + Vector3(0, 1, 0)]->Type > 0)
            sides &= (0xEF); // 0b00010000

        if (Pos.Z < 15 && chunk[Pos + Vector3(0, 0, 1)]->Type > 0)
            sides &= (0xDF); // 0b00100000

        it->second->faces = sides;

        if (sides > 0)
            VisibleBlocks.push_back(new PositionedBlock(it->second, (ChunkIndex * 16) + Pos, 1));
    }

    LoadedChunks[ChunkIndex] = chunk;
}

void LazyWorld::HandleRequests(Vector3 Pos) {
    Vector3 CurrentChunk;

    CurrentChunk.X = floor(Pos.X / ChunkSize);
    CurrentChunk.Y = floor(Pos.Y / ChunkSize);
    CurrentChunk.Z = floor(Pos.Z / ChunkSize);

    RequestChunk(CurrentChunk);
    RequestChunk(CurrentChunk + Vector3(-1, 0,  0));
    RequestChunk(CurrentChunk + Vector3(-1, -1, 0));
    RequestChunk(CurrentChunk + Vector3(0,  -1, 0));
    RequestChunk(CurrentChunk + Vector3(1,  -1, 0));
    RequestChunk(CurrentChunk + Vector3(1,  0,  0));
    RequestChunk(CurrentChunk + Vector3(1,  1,  0));
    RequestChunk(CurrentChunk + Vector3(0,  1,  0));
    RequestChunk(CurrentChunk + Vector3(-1, 1,  0));
}

void LazyWorld::RequestChunk(Vector3 ChunkIndex) {
    if (contains(RequestedChunks, ChunkIndex)) return;

    // Send request to the server
    sf::Packet Packet;
    Packet << (sf::Uint8) 4 << ChunkIndex;
    Socket.Send(Packet);

    RequestedChunks.push_back(ChunkIndex);
}
<commit_msg>Hey look, more debug code<commit_after>#include "common/lazyworld.h"
#include <cstdio>

void LazyWorld::DoStep() {
    // Collision check against player
}

void LazyWorld::CheckCollision(Entity *entity) {
    PositionedBlock *block;

    for (std::list<PositionedBlock*>::iterator it = VisibleBlocks.begin(); it != VisibleBlocks.end(); ++it) {
        block = *it;
        if (block->block->Type == 0) continue;

        if (entity->Pos.X + entity->Hitbox.X >= block->pos.X && entity->Pos.X <= block->pos.X + 1
         && entity->Pos.Y + entity->Hitbox.Y >= block->pos.Y && entity->Pos.Y <= block->pos.Y + 1
         && entity->Pos.Z + entity->Hitbox.Z >= block->pos.Z && entity->Pos.Z <= block->pos.Z + 1)
            entity->Collide(*block);
    }
}

PositionedBlock *LazyWorld::CheckAim(Player *player) {
    PositionedBlock *block;
    Ray ray = Ray(player);

    PositionedBlock *target = NULL;
    float dist, best = 5.f;

    for (std::list<PositionedBlock*>::iterator it = VisibleBlocks.begin(); it != VisibleBlocks.end(); ++it) {
        block = *it; // Blocks[i];

        dist = ray.CheckCollision(block);
        if (0.f < dist && dist < best) {
            best = dist;
            target = block;
        }
    }

    if (target != NULL)
        target->marked = true;

    return target;
}

void LazyWorld::DestroyTarget(Player *player) {
    PositionedBlock *block = CheckAim(player);
    if (!block) return;
    VisibleBlocks.remove(block);

    Vector3 chunkindex, pos;

    chunkindex.X = floor(block->pos.X / ChunkSize);
    chunkindex.Y = floor(block->pos.Y / ChunkSize);
    chunkindex.Z = floor(block->pos.Z / ChunkSize);
    pos = block->pos - (chunkindex * 16);

    std::map<Vector3, Block*> chunk = LoadedChunks[chunkindex];

    Block *blk;

    if (pos.X > 0 && chunk[pos - Vector3(1, 0, 0)]->Type > 0) {
        blk = chunk[pos - Vector3(1, 0, 0)];
        if (blk->faces == 0) VisibleBlocks.push_back(new PositionedBlock(blk, block->pos - Vector3(1, 0, 0), 1));
        blk->faces |= 0x08;
    }

    if (pos.Y > 0 && chunk[pos - Vector3(0, 1, 0)]->Type > 0) {
        blk = chunk[pos - Vector3(0, 1, 0)];
        if (blk->faces == 0) VisibleBlocks.push_back(new PositionedBlock(blk, block->pos - Vector3(0, 1, 0), 1));
        blk->faces |= 0x10;
    }

    if (pos.Z > 0 && chunk[pos - Vector3(0, 0, 1)]->Type > 0) {
        blk = chunk[pos - Vector3(0, 0, 1)];
        if (blk->faces == 0) VisibleBlocks.push_back(new PositionedBlock(blk, block->pos - Vector3(0, 0, 1), 1));
        blk->faces |= 0x20;
    }

    if (pos.X < 15 && chunk[pos + Vector3(1, 0, 0)]->Type > 0) {
        blk = chunk[pos + Vector3(1, 0, 0)];
        if (blk->faces == 0) VisibleBlocks.push_back(new PositionedBlock(blk, block->pos + Vector3(1, 0, 0), 1));
        blk->faces |= 0x01;
    }

    if (pos.Y < 15 && chunk[pos + Vector3(0, 1, 0)]->Type > 0) {
        blk = chunk[pos + Vector3(0, 1, 0)];
        if (blk->faces == 0) VisibleBlocks.push_back(new PositionedBlock(blk, block->pos + Vector3(0, 1, 0), 1));
        blk->faces |= 0x02;
    }

    if (pos.Z < 15 && chunk[pos + Vector3(0, 0, 1)]->Type > 0) {
        blk = chunk[pos + Vector3(0, 0, 1)];
        if (blk->faces == 0) VisibleBlocks.push_back(new PositionedBlock(blk, block->pos + Vector3(0, 0, 1), 1));
        blk->faces |= 0x04;
    }
}

bool contains(std::vector<Vector3> vector, Vector3 value) {
    for (int i = 0; i < vector.size(); i++)
        if (vector[i] == value) return true;

    return false;
}

void LazyWorld::LoadChunk(sf::Packet Packet) {
    int BlockCount;
    Vector3 ChunkIndex; // TODO: remove from request list, add to loaded list
    Packet >> ChunkIndex >> BlockCount;

    std::map<Vector3, Block*> chunk;

    sf::Uint8 type;
    Block *block;
    Vector3 Pos;
    float SideLength;

    for (int i = 0; i < BlockCount; i++) {
        Packet >> type >> Pos;

        if (type == 3)
            block = new GrassBlock();
        else
            block = new AirBlock();

        chunk[Vector3(Pos)] = block;
    }

    for (std::map<Vector3, Block*>::iterator it = chunk.begin(); it != chunk.end(); ++it) {
        if (it->second->Type == 0) continue;
        Pos = it->first;

        char sides = 0x3F;

        if (Pos.X > 0 && chunk[Pos - Vector3(1, 0, 0)]->Type > 0)
            sides &= (0xFE); // 0b00000001

        if (Pos.Y > 0 && chunk[Pos - Vector3(0, 1, 0)]->Type > 0)
            sides &= (0xFD); // 0b00000010

        if (Pos.Z > 0 && chunk[Pos - Vector3(0, 0, 1)]->Type > 0)
            sides &= (0xFB); // 0b00000100

        if (Pos.X < 15 && chunk[Pos + Vector3(1, 0, 0)]->Type > 0)
            sides &= (0xF7); // 0b00001000

        if (Pos.Y < 15 && chunk[Pos + Vector3(0, 1, 0)]->Type > 0)
            sides &= (0xEF); // 0b00010000

        if (Pos.Z < 15 && chunk[Pos + Vector3(0, 0, 1)]->Type > 0)
            sides &= (0xDF); // 0b00100000

        it->second->faces = sides;

        if (sides > 0)
            VisibleBlocks.push_back(new PositionedBlock(it->second, (ChunkIndex * 16) + Pos, 1));
    }

    LoadedChunks[ChunkIndex] = chunk;
}

void LazyWorld::HandleRequests(Vector3 Pos) {
    Vector3 CurrentChunk;

    CurrentChunk.X = floor(Pos.X / ChunkSize);
    CurrentChunk.Y = floor(Pos.Y / ChunkSize);
    CurrentChunk.Z = floor(Pos.Z / ChunkSize);

    RequestChunk(CurrentChunk);
    RequestChunk(CurrentChunk + Vector3(-1, 0,  0));
    RequestChunk(CurrentChunk + Vector3(-1, -1, 0));
    RequestChunk(CurrentChunk + Vector3(0,  -1, 0));
    RequestChunk(CurrentChunk + Vector3(1,  -1, 0));
    RequestChunk(CurrentChunk + Vector3(1,  0,  0));
    RequestChunk(CurrentChunk + Vector3(1,  1,  0));
    RequestChunk(CurrentChunk + Vector3(0,  1,  0));
    RequestChunk(CurrentChunk + Vector3(-1, 1,  0));
}

void LazyWorld::RequestChunk(Vector3 ChunkIndex) {
    if (contains(RequestedChunks, ChunkIndex)) return;

    // Send request to the server
    sf::Packet Packet;
    Packet << (sf::Uint8) 4 << ChunkIndex;
    Socket.Send(Packet);

    RequestedChunks.push_back(ChunkIndex);
}
<|endoftext|>


<commit_before>// Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2019 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#include <outputtype.h>

#include <pubkey.h>
#include <script/script.h>
#include <script/sign.h>
#include <script/signingprovider.h>
#include <script/standard.h>
#include <util/vector.h>

#include <assert.h>
#include <string>

static const std::string OUTPUT_TYPE_STRING_LEGACY = "legacy";
static const std::string OUTPUT_TYPE_STRING_P2SH_SEGWIT = "p2sh-segwit";
static const std::string OUTPUT_TYPE_STRING_BECH32 = "bech32";

const std::array<OutputType, 3> OUTPUT_TYPES = {OutputType::LEGACY, OutputType::P2SH_SEGWIT, OutputType::BECH32};

bool ParseOutputType(const std::string& type, OutputType& output_type)
{
    if (type == OUTPUT_TYPE_STRING_LEGACY) {
        output_type = OutputType::LEGACY;
        return true;
    } else if (type == OUTPUT_TYPE_STRING_P2SH_SEGWIT) {
        output_type = OutputType::P2SH_SEGWIT;
        return true;
    } else if (type == OUTPUT_TYPE_STRING_BECH32) {
        output_type = OutputType::BECH32;
        return true;
    }
    return false;
}

const std::string& FormatOutputType(OutputType type)
{
    switch (type) {
    case OutputType::LEGACY: return OUTPUT_TYPE_STRING_LEGACY;
    case OutputType::P2SH_SEGWIT: return OUTPUT_TYPE_STRING_P2SH_SEGWIT;
    case OutputType::BECH32: return OUTPUT_TYPE_STRING_BECH32;
    default: assert(false);
    }
}

CTxDestination GetDestinationForKey(const CPubKey& key, OutputType type)
{
    switch (type) {
    case OutputType::LEGACY: return PKHash(key);
    case OutputType::P2SH_SEGWIT:
    case OutputType::BECH32: {
        if (!key.IsCompressed()) return PKHash(key);
        CTxDestination witdest = WitnessV0KeyHash(PKHash(key));
        CScript witprog = GetScriptForDestination(witdest);
        if (type == OutputType::P2SH_SEGWIT) {
            return ScriptHash(witprog);
        } else {
            return witdest;
        }
    }
    default: assert(false);
    }
}

std::vector<CTxDestination> GetAllDestinationsForKey(const CPubKey& key)
{
    PKHash keyid(key);
    CTxDestination p2pkh{keyid};
    if (key.IsCompressed()) {
        CTxDestination segwit = WitnessV0KeyHash(keyid);
        CTxDestination p2sh = ScriptHash(GetScriptForDestination(segwit));
        return Vector(std::move(p2pkh), std::move(p2sh), std::move(segwit));
    } else {
        return Vector(std::move(p2pkh));
    }
}

CTxDestination AddAndGetDestinationForScript(FillableSigningProvider& keystore, const CScript& script, OutputType type)
{
    // Add script to keystore
    keystore.AddCScript(script);
    ScriptHash sh(script);
    // Note that scripts over 520 bytes are not yet supported.
    switch (type) {
    case OutputType::LEGACY:
        keystore.AddCScript(GetScriptForDestination(sh));
        return sh;
    case OutputType::P2SH_SEGWIT:
    case OutputType::BECH32: {
        CTxDestination witdest = WitnessV0ScriptHash(script);
        CScript witprog = GetScriptForDestination(witdest);
        // Check if the resulting program is solvable (i.e. doesn't use an uncompressed key)
        if (!IsSolvable(keystore, witprog)) {
            // Since the wsh is invalid, add and return the sh instead.
            keystore.AddCScript(GetScriptForDestination(sh));
            return sh;
        }
        // Add the redeemscript, so that P2WSH and P2SH-P2WSH outputs are recognized as ours.
        keystore.AddCScript(witprog);
        if (type == OutputType::BECH32) {
            return witdest;
        } else {
            ScriptHash sh_w = ScriptHash(witprog);
            keystore.AddCScript(GetScriptForDestination(sh_w));
            return sh_w;
        }
    }
    default: assert(false);
    }
}
<commit_msg>Revert "Store p2sh scripts in AddAndGetDestinationForScript"<commit_after>// Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2019 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#include <outputtype.h>

#include <pubkey.h>
#include <script/script.h>
#include <script/sign.h>
#include <script/signingprovider.h>
#include <script/standard.h>
#include <util/vector.h>

#include <assert.h>
#include <string>

static const std::string OUTPUT_TYPE_STRING_LEGACY = "legacy";
static const std::string OUTPUT_TYPE_STRING_P2SH_SEGWIT = "p2sh-segwit";
static const std::string OUTPUT_TYPE_STRING_BECH32 = "bech32";

const std::array<OutputType, 3> OUTPUT_TYPES = {OutputType::LEGACY, OutputType::P2SH_SEGWIT, OutputType::BECH32};

bool ParseOutputType(const std::string& type, OutputType& output_type)
{
    if (type == OUTPUT_TYPE_STRING_LEGACY) {
        output_type = OutputType::LEGACY;
        return true;
    } else if (type == OUTPUT_TYPE_STRING_P2SH_SEGWIT) {
        output_type = OutputType::P2SH_SEGWIT;
        return true;
    } else if (type == OUTPUT_TYPE_STRING_BECH32) {
        output_type = OutputType::BECH32;
        return true;
    }
    return false;
}

const std::string& FormatOutputType(OutputType type)
{
    switch (type) {
    case OutputType::LEGACY: return OUTPUT_TYPE_STRING_LEGACY;
    case OutputType::P2SH_SEGWIT: return OUTPUT_TYPE_STRING_P2SH_SEGWIT;
    case OutputType::BECH32: return OUTPUT_TYPE_STRING_BECH32;
    default: assert(false);
    }
}

CTxDestination GetDestinationForKey(const CPubKey& key, OutputType type)
{
    switch (type) {
    case OutputType::LEGACY: return PKHash(key);
    case OutputType::P2SH_SEGWIT:
    case OutputType::BECH32: {
        if (!key.IsCompressed()) return PKHash(key);
        CTxDestination witdest = WitnessV0KeyHash(PKHash(key));
        CScript witprog = GetScriptForDestination(witdest);
        if (type == OutputType::P2SH_SEGWIT) {
            return ScriptHash(witprog);
        } else {
            return witdest;
        }
    }
    default: assert(false);
    }
}

std::vector<CTxDestination> GetAllDestinationsForKey(const CPubKey& key)
{
    PKHash keyid(key);
    CTxDestination p2pkh{keyid};
    if (key.IsCompressed()) {
        CTxDestination segwit = WitnessV0KeyHash(keyid);
        CTxDestination p2sh = ScriptHash(GetScriptForDestination(segwit));
        return Vector(std::move(p2pkh), std::move(p2sh), std::move(segwit));
    } else {
        return Vector(std::move(p2pkh));
    }
}

CTxDestination AddAndGetDestinationForScript(FillableSigningProvider& keystore, const CScript& script, OutputType type)
{
    // Add script to keystore
    keystore.AddCScript(script);
    // Note that scripts over 520 bytes are not yet supported.
    switch (type) {
    case OutputType::LEGACY:
        return ScriptHash(script);
    case OutputType::P2SH_SEGWIT:
    case OutputType::BECH32: {
        CTxDestination witdest = WitnessV0ScriptHash(script);
        CScript witprog = GetScriptForDestination(witdest);
        // Check if the resulting program is solvable (i.e. doesn't use an uncompressed key)
        if (!IsSolvable(keystore, witprog)) return ScriptHash(script);
        // Add the redeemscript, so that P2WSH and P2SH-P2WSH outputs are recognized as ours.
        keystore.AddCScript(witprog);
        if (type == OutputType::BECH32) {
            return witdest;
        } else {
            return ScriptHash(witprog);
        }
    }
    default: assert(false);
    }
}
<|endoftext|>


<commit_before>/*
 *  Copyright (c) 2012 The WebRTC project authors. All Rights Reserved.
 *
 *  Use of this source code is governed by a BSD-style license
 *  that can be found in the LICENSE file in the root of the source
 *  tree. An additional intellectual property rights grant can be found
 *  in the file PATENTS.  All contributing project authors may
 *  be found in the AUTHORS file in the root of the source tree.
 */

// Tests for the UdpSocketManager interface.
// Note: This tests UdpSocketManager together with UdpSocketWrapper,
// due to the way the code is full of static-casts to the platform dependent
// subtypes.
// It also uses the static UdpSocketManager object.
// The most important property of these tests is that they do not leak memory.

#include "udp_socket_wrapper.h"
#include "udp_socket_manager_wrapper.h"
#include "gtest/gtest.h"

TEST(UdpSocketManager, CreateCallsInitAndDoesNotLeakMemory) {
  WebRtc_Word32 id = 42;
  WebRtc_UWord8 threads = 1;
  webrtc::UdpSocketManager* mgr = webrtc::UdpSocketManager::Create(id, threads);
  // Create is supposed to have called init on the object.
  EXPECT_EQ(false, mgr->Init(id, threads))
      << "Init should return false since Create is supposed to call it.";
  webrtc::UdpSocketManager::Return();
}

// Creates a socket and adds it to the socket manager, and then removes it
// before destroying the socket manager.
TEST(UdpSocketManager, AddAndRemoveSocketDoesNotLeakMemory) {
  WebRtc_Word32 id = 42;
  WebRtc_UWord8 threads = 1;
  webrtc::UdpSocketManager* mgr = webrtc::UdpSocketManager::Create(id, threads);
  webrtc::UdpSocketWrapper* socket
       = webrtc::UdpSocketWrapper::CreateSocket(id,
                                                mgr,
                                                NULL,  // CallbackObj
                                                NULL,  // IncomingSocketCallback
                                                false,  // ipV6Enable
                                                false);  // disableGQOS
  // The constructor will do AddSocket on the manager.
  EXPECT_EQ(true, mgr->RemoveSocket(socket));
  webrtc::UdpSocketManager::Return();
}

// Creates a socket and add it to the socket manager, but does not remove it
// before destroying the socket manager.
// This should also destroy the socket.
TEST(UdpSocketManager, UnremovedSocketsGetCollectedAtManagerDeletion) {
  WebRtc_Word32 id = 42;
  WebRtc_UWord8 threads = 1;
  webrtc::UdpSocketManager* mgr = webrtc::UdpSocketManager::Create(id, threads);
  webrtc::UdpSocketWrapper* unused_socket
       = webrtc::UdpSocketWrapper::CreateSocket(id,
                                                mgr,
                                                NULL,  // CallbackObj
                                                NULL,  // IncomingSocketCallback
                                                false,  // ipV6Enable
                                                false);  // disableGQOS
  // The constructor will do AddSocket on the manager.
  unused_socket = NULL;
  webrtc::UdpSocketManager::Return();
}
<commit_msg>Disabled UnremovedSocketsGetCollectedAtManagerDeletion in UdpSocketManager unittest.<commit_after>/*
 *  Copyright (c) 2012 The WebRTC project authors. All Rights Reserved.
 *
 *  Use of this source code is governed by a BSD-style license
 *  that can be found in the LICENSE file in the root of the source
 *  tree. An additional intellectual property rights grant can be found
 *  in the file PATENTS.  All contributing project authors may
 *  be found in the AUTHORS file in the root of the source tree.
 */

// Tests for the UdpSocketManager interface.
// Note: This tests UdpSocketManager together with UdpSocketWrapper,
// due to the way the code is full of static-casts to the platform dependent
// subtypes.
// It also uses the static UdpSocketManager object.
// The most important property of these tests is that they do not leak memory.

#include "udp_socket_wrapper.h"
#include "udp_socket_manager_wrapper.h"
#include "gtest/gtest.h"

TEST(UdpSocketManager, CreateCallsInitAndDoesNotLeakMemory) {
  WebRtc_Word32 id = 42;
  WebRtc_UWord8 threads = 1;
  webrtc::UdpSocketManager* mgr = webrtc::UdpSocketManager::Create(id, threads);
  // Create is supposed to have called init on the object.
  EXPECT_EQ(false, mgr->Init(id, threads))
      << "Init should return false since Create is supposed to call it.";
  webrtc::UdpSocketManager::Return();
}

// Creates a socket and adds it to the socket manager, and then removes it
// before destroying the socket manager.
TEST(UdpSocketManager, AddAndRemoveSocketDoesNotLeakMemory) {
  WebRtc_Word32 id = 42;
  WebRtc_UWord8 threads = 1;
  webrtc::UdpSocketManager* mgr = webrtc::UdpSocketManager::Create(id, threads);
  webrtc::UdpSocketWrapper* socket
       = webrtc::UdpSocketWrapper::CreateSocket(id,
                                                mgr,
                                                NULL,  // CallbackObj
                                                NULL,  // IncomingSocketCallback
                                                false,  // ipV6Enable
                                                false);  // disableGQOS
  // The constructor will do AddSocket on the manager.
  EXPECT_EQ(true, mgr->RemoveSocket(socket));
  webrtc::UdpSocketManager::Return();
}

// Creates a socket and add it to the socket manager, but does not remove it
// before destroying the socket manager.
// This should also destroy the socket.
TEST(UdpSocketManager, DISABLED_UnremovedSocketsGetCollectedAtManagerDeletion) {
  WebRtc_Word32 id = 42;
  WebRtc_UWord8 threads = 1;
  webrtc::UdpSocketManager* mgr = webrtc::UdpSocketManager::Create(id, threads);
  webrtc::UdpSocketWrapper* unused_socket
       = webrtc::UdpSocketWrapper::CreateSocket(id,
                                                mgr,
                                                NULL,  // CallbackObj
                                                NULL,  // IncomingSocketCallback
                                                false,  // ipV6Enable
                                                false);  // disableGQOS
  // The constructor will do AddSocket on the manager.
  unused_socket = NULL;
  webrtc::UdpSocketManager::Return();
}
<|endoftext|>


<commit_before>/*
Copyright (c) 2013, Pierre KRIEGER
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
    * Redistributions of source code must retain the above copyright
      notice, this list of conditions and the following disclaimer.
    * 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.
    * Neither the name of the <organization> 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 COPYRIGHT HOLDERS AND CONTRIBUTORS "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 <COPYRIGHT HOLDER> 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.
*/

#ifndef INCLUDE_LUACONTEXTTHREAD_HPP
#define INCLUDE_LUACONTEXTTHREAD_HPP

#include "LuaContext.hpp"

/**
 *
 */
class LuaContextThread {
public:
    /**
     * Creates a thread in the LuaContext
     */
    explicit LuaContextThread(LuaContext* lua) :
        mLua(lua),
        mThread(lua->createThread())
    {
    }

    /**
     * Destroys the thread
     */
    ~LuaContextThread()
    {
        mLua->destroyThread(mThread);
    }

    /**
     *
     */
    void forkGlobals() const
    {
        mLua->forkGlobals(mThread);
    }

    /**
     *
     */
    template<typename TType, typename... TTypes>
    auto readVariable(TTypes&&... elements) const
        -> TType
    {
        return mLua->readVariable<TType>(mThread, std::forward<TTypes>(elements)...);
    }

    /**
     *
     */
    template<typename... TData>
    void writeVariable(TData&&... data) const
    {
        mLua->writeVariable(mThread, std::forward<TData>(data)...);
    }

    /**
     *
     */
    template<typename TFunctionType, typename... TData>
    void writeFunction(TData&&... data) const
    {
        mLua->writeFunction<TFunctionType>(mThread, std::forward<TData>(data)...);
    }

    /**
     *
     */
    template<typename... TData>
    void writeFunction(TData&&... data) const
    {
        mLua->writeFunction(mThread, std::forward<TData>(data)...);
    }

    /**
     *
     */
    template<typename TType, typename TCode>
    auto executeCode(TCode&& code) const
        -> decltype(mLua->executeCode<TType>(std::forward<TCode>(code)))
    {
        return mLua->executeCode<TType>(mThread, std::forward<TCode>(code));
    }

    /**
     *
     */
    template<typename TCode>
    void executeCode(TCode&& code) const
    {
        mLua->executeCode(mThread, std::forward<TCode>(code));
    }

private:
    LuaContext* const        mLua;
    LuaContext::ThreadID     mThread;       // TODO: const
};

#endif
<commit_msg>Compilation fix for LuaContextThread::executeCode<commit_after>/*
Copyright (c) 2013, Pierre KRIEGER
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
    * Redistributions of source code must retain the above copyright
      notice, this list of conditions and the following disclaimer.
    * 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.
    * Neither the name of the <organization> 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 COPYRIGHT HOLDERS AND CONTRIBUTORS "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 <COPYRIGHT HOLDER> 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.
*/

#ifndef INCLUDE_LUACONTEXTTHREAD_HPP
#define INCLUDE_LUACONTEXTTHREAD_HPP

#include "LuaContext.hpp"

/**
 *
 */
class LuaContextThread {
public:
    /**
     * Creates a thread in the LuaContext
     */
    explicit LuaContextThread(LuaContext* lua) :
        mLua(lua),
        mThread(lua->createThread())
    {
    }

    /**
     * Destroys the thread
     */
    ~LuaContextThread()
    {
        mLua->destroyThread(mThread);
    }

    /**
     *
     */
    void forkGlobals() const
    {
        mLua->forkGlobals(mThread);
    }

    /**
     *
     */
    template<typename TType, typename... TTypes>
    auto readVariable(TTypes&&... elements) const
        -> TType
    {
        return mLua->readVariable<TType>(mThread, std::forward<TTypes>(elements)...);
    }

    /**
     *
     */
    template<typename... TData>
    void writeVariable(TData&&... data) const
    {
        mLua->writeVariable(mThread, std::forward<TData>(data)...);
    }

    /**
     *
     */
    template<typename TFunctionType, typename... TData>
    void writeFunction(TData&&... data) const
    {
        mLua->writeFunction<TFunctionType>(mThread, std::forward<TData>(data)...);
    }

    /**
     *
     */
    template<typename... TData>
    void writeFunction(TData&&... data) const
    {
        mLua->writeFunction(mThread, std::forward<TData>(data)...);
    }

    /**
     *
     */
    template<typename TType, typename TCode>
    auto executeCode(TCode&& code) const
        -> TType
    {
        return mLua->executeCode<TType>(mThread, std::forward<TCode>(code));
    }

    /**
     *
     */
    template<typename TCode>
    void executeCode(TCode&& code) const
    {
        mLua->executeCode(mThread, std::forward<TCode>(code));
    }

private:
    LuaContext* const        mLua;
    LuaContext::ThreadID     mThread;       // TODO: const
};

#endif
<|endoftext|>


<commit_before>#include "swftStatusWindowWidget.h"
#include "ui_swftStatusWindowWidget.h"

#include <QHeaderView>
#include <QLineEdit>
#include <QStringList>

#include "vtkCommand.h"
#include "vtkEventQtSlotConnect.h"
#include <vtksys/SystemTools.hxx>

#include "vtkPVArrayInformation.h"
#include "vtkPVCompositeDataInformation.h"
#include "vtkPVDataInformation.h"
#include "vtkExecutive.h"
#include "vtkPVDataSetAttributesInformation.h"
#include "vtkSmartPointer.h"
#include "vtkSMDomain.h"
#include "vtkSMDomainIterator.h"
#include "vtkSMDoubleVectorProperty.h"
#include "vtkSMOutputPort.h"
#include "vtkSMPropertyIterator.h"
#include "vtkSelection.h"
#include "vtkSelectionNode.h"
#include "vtkSelectionRepresentation.h"

#include "pqActiveObjects.h"
#include "pqNonEditableStyledItemDelegate.h"
#include "pqOutputPort.h"
#include "pqPipelineSource.h"
#include "pqSMAdaptor.h"
#include "pqServer.h"
#include "pqTimeKeeper.h"

#include <QVariant>

class swftStatusWindowWidget::pqUi
        : public QObject, public Ui::swftStatusWindowWidget
{
public:
    pqUi(QObject* p) : QObject(p) {}
};

swftStatusWindowWidget::swftStatusWindowWidget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::swftStatusWindowWidget)
{
    ui->setupUi(this);

    ui->modelNameLabel->setText("... Please Load a Model Run to Start ...");

    this->VTKConnect = vtkEventQtSlotConnect::New();
    this->updateInformation();

    this->connect(&pqActiveObjects::instance(),
                  SIGNAL (portChanged(pqOutputPort*)),
                  this,
                  SLOT(setOutputPort(pqOutputPort*)));

}

swftStatusWindowWidget::~swftStatusWindowWidget()
{
    this->VTKConnect->Disconnect();
    this->VTKConnect->Delete();
    delete ui;
}

pqOutputPort *swftStatusWindowWidget::getOutputPort()
{

    return this->OutputPort;
}

void swftStatusWindowWidget::setOutputPort(pqOutputPort *source)
{
    if(this->OutputPort == source)
    {
        return;
    }

    this->VTKConnect->Disconnect();
    if (this->OutputPort)
    {
        //        QObject::disconnect((this->OutputPort->getSource(),
        //                             SIGNAL (dataUdated(pqPipelineSource*)),
        //                             this, SLOT(updateInformation())));

        //        this->ui->currentFileInfo->setText("N/A");
        //        this->ui->currentFilePathInfo->setText("N/A");
    }

    this->OutputPort = source;
    if(this->OutputPort)
    {
        QObject::connect(this->OutputPort->getSource(),
                         SIGNAL(dataUpdated(pqPipelineSource*)),
                         this, SLOT(updateInformation()));
    }

    this->updateInformation();

}

void swftStatusWindowWidget::fillDataInformation(vtkPVDataInformation *info)
{

//    std::cout << __FUNCTION__ << " " << __LINE__ << " has been triggered" << std::endl;
}

void swftStatusWindowWidget::updateInformation()
{

//    std::cout << "update Information triggered" << std::endl;

    vtkPVDataInformation *dataInformation = NULL;
    pqPipelineSource * source = NULL;

    if(this->OutputPort)
    {
        source = this->OutputPort->getSource();
        if(this->OutputPort->getOutputPortProxy())
        {
            dataInformation = this->OutputPort->getDataInformation();
        }
    }

    if(!source || !dataInformation)
    {
        this->fillDataInformation(0);
        return;
    }

    this->fillDataInformation(dataInformation);

    //need to get the required information

    //find the filename
    vtkSmartPointer<vtkSMPropertyIterator> piter;
    piter.TakeReference(source->getProxy()->NewPropertyIterator());
    for(piter->Begin(); !piter->IsAtEnd(); piter->Next())
    {
        vtkSMProperty *prop = piter->GetProperty();
        if(prop->IsA("vtkSMStringVectorProperty"))
        {

            vtkSmartPointer<vtkSMDomainIterator> diter;
            diter.TakeReference(prop->NewDomainIterator());

            for(diter->Begin(); !diter->IsAtEnd(); diter->Next())
            {
                if(diter->GetDomain()->IsA("vtkSMFileListDomain"))
                {
                    vtkSMProperty* smprop = piter->GetProperty();
                    if(smprop->GetInformationProperty())
                    {
                        smprop = smprop->GetInformationProperty();
                        source->getProxy()->UpdatePropertyInformation(smprop);
                    }

                    QString filename = pqSMAdaptor::getElementProperty(smprop).toString();
                    QString path = vtksys::SystemTools::GetFilenamePath(filename.toAscii().data()).c_str();

//                    std::cout << "Path: " << path.toAscii().data() << std::endl;
//                    std::cout << "filename: " << filename.toAscii().data() << std::endl;

                    ui->currentFileInfo->setText(vtksys::SystemTools::GetFilenameName(filename.toAscii().data()).c_str());
                    ui->currentFilePathInfo->setText(path);

                }

                if(!diter->IsAtEnd())
                {
                    break;
                }
            }
        }
    }

    vtkPVDataSetAttributesInformation* fieldInfo;

    fieldInfo = dataInformation->GetFieldDataInformation();

    for(int q=0; q < fieldInfo->GetNumberOfArrays(); q++)
    {
        vtkPVArrayInformation* arrayInfo;
        arrayInfo = fieldInfo->GetArrayInformation(q);

        int numComponents = arrayInfo->GetNumberOfComponents();

        QString name = arrayInfo->GetName();
        QString value;

//        std::cout << "Name: " << name.toAscii().data() << std::endl;

        for(int j = 0; j < numComponents; j++)
        {
            //look for the correct values
        }

    }

}

<commit_msg>vtkSpaceCraftInfo filter: Working on parsing XML. Please note that the way this works will be changing.  I am just getting a feel for the xml parser at the moment.<commit_after>#include "swftStatusWindowWidget.h"
#include "ui_swftStatusWindowWidget.h"

#include <QHeaderView>
#include <QLineEdit>
#include <QStringList>

#include "vtkCommand.h"
#include "vtkEventQtSlotConnect.h"
#include <vtksys/SystemTools.hxx>

#include "vtkPVArrayInformation.h"
#include "vtkPVCompositeDataInformation.h"
#include "vtkPVDataInformation.h"
#include "vtkExecutive.h"
#include "vtkPVDataSetAttributesInformation.h"
#include "vtkSmartPointer.h"
#include "vtkSMDomain.h"
#include "vtkSMDomainIterator.h"
#include "vtkSMDoubleVectorProperty.h"
#include "vtkSMOutputPort.h"
#include "vtkSMPropertyIterator.h"
#include "vtkSelection.h"
#include "vtkSelectionNode.h"
#include "vtkSelectionRepresentation.h"

#include "pqActiveObjects.h"
#include "pqNonEditableStyledItemDelegate.h"
#include "pqOutputPort.h"
#include "pqPipelineSource.h"
#include "pqSMAdaptor.h"
#include "pqServer.h"
#include "pqTimeKeeper.h"

#include <QVariant>

class swftStatusWindowWidget::pqUi
        : public QObject, public Ui::swftStatusWindowWidget
{
public:
    pqUi(QObject* p) : QObject(p) {}
};

swftStatusWindowWidget::swftStatusWindowWidget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::swftStatusWindowWidget)
{
    ui->setupUi(this);

    ui->modelNameLabel->setText("Enlil Model Information");

    this->VTKConnect = vtkEventQtSlotConnect::New();
    this->updateInformation();

    this->connect(&pqActiveObjects::instance(),
                  SIGNAL (portChanged(pqOutputPort*)),
                  this,
                  SLOT(setOutputPort(pqOutputPort*)));

}

swftStatusWindowWidget::~swftStatusWindowWidget()
{
    this->VTKConnect->Disconnect();
    this->VTKConnect->Delete();
    delete ui;
}

pqOutputPort *swftStatusWindowWidget::getOutputPort()
{

    return this->OutputPort;
}

void swftStatusWindowWidget::setOutputPort(pqOutputPort *source)
{
    if(this->OutputPort == source)
    {
        return;
    }

    this->VTKConnect->Disconnect();
    if (this->OutputPort)
    {
        //        QObject::disconnect((this->OutputPort->getSource(),
        //                             SIGNAL (dataUdated(pqPipelineSource*)),
        //                             this, SLOT(updateInformation())));

        //        this->ui->currentFileInfo->setText("N/A");
        //        this->ui->currentFilePathInfo->setText("N/A");
    }

    this->OutputPort = source;
    if(this->OutputPort)
    {
        QObject::connect(this->OutputPort->getSource(),
                         SIGNAL(dataUpdated(pqPipelineSource*)),
                         this, SLOT(updateInformation()));
    }

    this->updateInformation();

}

void swftStatusWindowWidget::fillDataInformation(vtkPVDataInformation *info)
{

//    std::cout << __FUNCTION__ << " " << __LINE__ << " has been triggered" << std::endl;
}

void swftStatusWindowWidget::updateInformation()
{

//    std::cout << "update Information triggered" << std::endl;

    vtkPVDataInformation *dataInformation = NULL;
    pqPipelineSource * source = NULL;

    if(this->OutputPort)
    {
        source = this->OutputPort->getSource();
        if(this->OutputPort->getOutputPortProxy())
        {
            dataInformation = this->OutputPort->getDataInformation();
        }
    }

    if(!source || !dataInformation)
    {
        this->fillDataInformation(0);
        return;
    }

    this->fillDataInformation(dataInformation);

    //need to get the required information

    //find the filename
    vtkSmartPointer<vtkSMPropertyIterator> piter;
    piter.TakeReference(source->getProxy()->NewPropertyIterator());
    for(piter->Begin(); !piter->IsAtEnd(); piter->Next())
    {
        vtkSMProperty *prop = piter->GetProperty();
        if(prop->IsA("vtkSMStringVectorProperty"))
        {

            vtkSmartPointer<vtkSMDomainIterator> diter;
            diter.TakeReference(prop->NewDomainIterator());

            for(diter->Begin(); !diter->IsAtEnd(); diter->Next())
            {
                if(diter->GetDomain()->IsA("vtkSMFileListDomain"))
                {
                    vtkSMProperty* smprop = piter->GetProperty();
                    if(smprop->GetInformationProperty())
                    {
                        smprop = smprop->GetInformationProperty();
                        source->getProxy()->UpdatePropertyInformation(smprop);
                    }

                    QString filename = pqSMAdaptor::getElementProperty(smprop).toString();
                    QString path = vtksys::SystemTools::GetFilenamePath(filename.toAscii().data()).c_str();

//                    std::cout << "Path: " << path.toAscii().data() << std::endl;
//                    std::cout << "filename: " << filename.toAscii().data() << std::endl;

                    ui->currentFileInfo->setText(vtksys::SystemTools::GetFilenameName(filename.toAscii().data()).c_str());
                    ui->currentFilePathInfo->setText(path);

                }

                if(!diter->IsAtEnd())
                {
                    break;
                }
            }
        }
    }

    vtkPVDataSetAttributesInformation* fieldInfo;

    fieldInfo = dataInformation->GetFieldDataInformation();

    for(int q=0; q < fieldInfo->GetNumberOfArrays(); q++)
    {
        vtkPVArrayInformation* arrayInfo;
        arrayInfo = fieldInfo->GetArrayInformation(q);

        int numComponents = arrayInfo->GetNumberOfComponents();

        QString name = arrayInfo->GetName();
        QString value;

//        std::cout << "Name: " << name.toAscii().data() << std::endl;

        for(int j = 0; j < numComponents; j++)
        {
            //look for the correct values
        }

    }

}

<|endoftext|>