<commit_before>//////////////////////////////////////////////////////////////////////////
//
//  Copyright (c) 2011-2012, John Haddon. All rights reserved.
//  Copyright (c) 2011-2013, Image Engine Design Inc. 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 John Haddon nor the names of
//        any other contributors to this software 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 THE COPYRIGHT OWNER OR
//  CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
//  EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
//  PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
//  PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
//  LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
//  NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
//  SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
//////////////////////////////////////////////////////////////////////////

#include "boost/python.hpp"

#include "Gaffer/Node.h"

#include "GafferBindings/SignalBinding.h"

#include "GafferUI/GraphGadget.h"
#include "GafferUI/NodeGadget.h"
#include "GafferUI/ConnectionGadget.h"
#include "GafferUI/GraphLayout.h"

#include "GafferUIBindings/GraphGadgetBinding.h"
#include "GafferUIBindings/GadgetBinding.h"

using namespace boost::python;
using namespace GafferUIBindings;
using namespace GafferUI;

struct RootChangedSlotCaller
{
	boost::signals::detail::unusable operator()( boost::python::object slot, GraphGadgetPtr g, Gaffer::NodePtr n )
	{
		slot( g , n );
		return boost::signals::detail::unusable();
	}
};

static Gaffer::NodePtr getRoot( GraphGadget &graphGadget )
{
	return graphGadget.getRoot();
}

static Gaffer::SetPtr getFilter( GraphGadget &graphGadget )
{
	return graphGadget.getFilter();
}

static NodeGadgetPtr nodeGadget( GraphGadget &graphGadget, const Gaffer::Node *node )
{
	return graphGadget.nodeGadget( node );
}

static ConnectionGadgetPtr connectionGadget( GraphGadget &graphGadget, const Gaffer::Plug *dstPlug )
{
	return graphGadget.connectionGadget( dstPlug );
}

static list connectionGadgets1( GraphGadget &graphGadget, const Gaffer::Plug *plug, const Gaffer::Set *excludedNodes = 0 )
{
	std::vector<ConnectionGadget *> connections;
	graphGadget.connectionGadgets( plug, connections, excludedNodes );

	boost::python::list l;
	for( std::vector<ConnectionGadget *>::const_iterator it=connections.begin(), eIt=connections.end(); it!=eIt; ++it )
	{
		l.append( ConnectionGadgetPtr( *it ) );
	}
	return l;
}

static list connectionGadgets2( GraphGadget &graphGadget, const Gaffer::Node *node, const Gaffer::Set *excludedNodes = 0 )
{
	std::vector<ConnectionGadget *> connections;
	graphGadget.connectionGadgets( node, connections, excludedNodes );

	boost::python::list l;
	for( std::vector<ConnectionGadget *>::const_iterator it=connections.begin(), eIt=connections.end(); it!=eIt; ++it )
	{
		l.append( ConnectionGadgetPtr( *it ) );
	}
	return l;
}

static list upstreamNodeGadgets( GraphGadget &graphGadget, const Gaffer::Node *node, size_t degreesOfSeparation )
{
	std::vector<NodeGadget *> nodeGadgets;
	graphGadget.upstreamNodeGadgets( node, nodeGadgets, degreesOfSeparation );

	boost::python::list l;
	for( std::vector<NodeGadget *>::const_iterator it=nodeGadgets.begin(), eIt=nodeGadgets.end(); it!=eIt; ++it )
	{
		l.append( NodeGadgetPtr( *it ) );
	}
	return l;
}

static list downstreamNodeGadgets( GraphGadget &graphGadget, const Gaffer::Node *node, size_t degreesOfSeparation )
{
	std::vector<NodeGadget *> nodeGadgets;
	graphGadget.downstreamNodeGadgets( node, nodeGadgets, degreesOfSeparation );

	boost::python::list l;
	for( std::vector<NodeGadget *>::const_iterator it=nodeGadgets.begin(), eIt=nodeGadgets.end(); it!=eIt; ++it )
	{
		l.append( NodeGadgetPtr( *it ) );
	}
	return l;
}

static list connectedNodeGadgets( GraphGadget &graphGadget, const Gaffer::Node *node, Gaffer::Plug::Direction direction, size_t degreesOfSeparation )
{
	std::vector<NodeGadget *> nodeGadgets;
	graphGadget.connectedNodeGadgets( node, nodeGadgets, direction, degreesOfSeparation );

	boost::python::list l;
	for( std::vector<NodeGadget *>::const_iterator it=nodeGadgets.begin(), eIt=nodeGadgets.end(); it!=eIt; ++it )
	{
		l.append( NodeGadgetPtr( *it ) );
	}
	return l;
}

static void setLayout( GraphGadget &g, GraphLayoutPtr l )
{
	return g.setLayout( l );
}

static GraphLayoutPtr getLayout( GraphGadget &g )
{
	return g.getLayout();
}

static NodeGadgetPtr nodeGadgetAt( GraphGadget &g, const IECore::LineSegment3f lineSegmentInGadgetSpace )
{
	return g.nodeGadgetAt( lineSegmentInGadgetSpace );
}

static ConnectionGadgetPtr connectionGadgetAt( GraphGadget &g, const IECore::LineSegment3f lineSegmentInGadgetSpace )
{
	return g.connectionGadgetAt( lineSegmentInGadgetSpace );
}

void GafferUIBindings::bindGraphGadget()
{
	scope s = GadgetClass<GraphGadget>()
		.def( init<Gaffer::NodePtr, Gaffer::SetPtr>( ( arg_( "root" ), arg_( "filter" ) = object() ) ) )
		.def( "getRoot", &getRoot )
		.def( "setRoot", &GraphGadget::setRoot, ( arg_( "root" ), arg_( "filter" ) = object() ) )
		.def( "rootChangedSignal", &GraphGadget::rootChangedSignal, return_internal_reference<1>() )
		.def( "getFilter", &getFilter )
		.def( "setFilter", &GraphGadget::setFilter )
		.def( "nodeGadget", &nodeGadget )
		.def( "connectionGadget", &connectionGadget )
		.def( "connectionGadgets", &connectionGadgets1, ( arg_( "plug" ), arg_( "excludedNodes" ) = object() ) )
		.def( "connectionGadgets", &connectionGadgets2, ( arg_( "node" ), arg_( "excludedNodes" ) = object() ) )
		.def( "upstreamNodeGadgets", &upstreamNodeGadgets, ( arg( "node" ), arg( "degreesOfSeparation" ) = Imath::limits<size_t>::max() ) )
		.def( "downstreamNodeGadgets", &downstreamNodeGadgets, ( arg( "node" ), arg( "degreesOfSeparation" ) = Imath::limits<size_t>::max() ) )
		.def( "connectedNodeGadgets", &connectedNodeGadgets, ( arg( "node" ), arg( "direction" ) = Gaffer::Plug::Invalid, arg( "degreesOfSeparation" ) = Imath::limits<size_t>::max() ) )
		.def( "setNodePosition", &GraphGadget::setNodePosition )
		.def( "getNodePosition", &GraphGadget::getNodePosition )
		.def( "hasNodePosition", &GraphGadget::hasNodePosition )
		.def( "setNodeInputConnectionsMinimised", &GraphGadget::setNodeInputConnectionsMinimised )
		.def( "getNodeInputConnectionsMinimised", &GraphGadget::getNodeInputConnectionsMinimised )
		.def( "setNodeOutputConnectionsMinimised", &GraphGadget::setNodeOutputConnectionsMinimised )
		.def( "getNodeOutputConnectionsMinimised", &GraphGadget::getNodeOutputConnectionsMinimised )
		.def( "setLayout", &setLayout )
		.def( "getLayout", &getLayout )
		.def( "nodeGadgetAt", &nodeGadgetAt )
		.def( "connectionGadgetAt", &connectionGadgetAt )
	;

	GafferBindings::SignalClass<GraphGadget::RootChangedSignal, GafferBindings::DefaultSignalCaller<GraphGadget::RootChangedSignal>, RootChangedSlotCaller>( "RootChangedSignal" );

}
<commit_msg>GraphGadget binding : Move implementation to unnamed namespace.<commit_after>//////////////////////////////////////////////////////////////////////////
//
//  Copyright (c) 2011-2012, John Haddon. All rights reserved.
//  Copyright (c) 2011-2013, Image Engine Design Inc. 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 John Haddon nor the names of
//        any other contributors to this software 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 THE COPYRIGHT OWNER OR
//  CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
//  EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
//  PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
//  PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
//  LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
//  NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
//  SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
//////////////////////////////////////////////////////////////////////////

#include "boost/python.hpp"

#include "Gaffer/Node.h"

#include "GafferBindings/SignalBinding.h"

#include "GafferUI/GraphGadget.h"
#include "GafferUI/NodeGadget.h"
#include "GafferUI/ConnectionGadget.h"
#include "GafferUI/GraphLayout.h"

#include "GafferUIBindings/GraphGadgetBinding.h"
#include "GafferUIBindings/GadgetBinding.h"

using namespace boost::python;
using namespace GafferUIBindings;
using namespace GafferUI;

namespace
{

struct RootChangedSlotCaller
{
	boost::signals::detail::unusable operator()( boost::python::object slot, GraphGadgetPtr g, Gaffer::NodePtr n )
	{
		slot( g , n );
		return boost::signals::detail::unusable();
	}
};

Gaffer::NodePtr getRoot( GraphGadget &graphGadget )
{
	return graphGadget.getRoot();
}

Gaffer::SetPtr getFilter( GraphGadget &graphGadget )
{
	return graphGadget.getFilter();
}

NodeGadgetPtr nodeGadget( GraphGadget &graphGadget, const Gaffer::Node *node )
{
	return graphGadget.nodeGadget( node );
}

static ConnectionGadgetPtr connectionGadget( GraphGadget &graphGadget, const Gaffer::Plug *dstPlug )
{
	return graphGadget.connectionGadget( dstPlug );
}

list connectionGadgets1( GraphGadget &graphGadget, const Gaffer::Plug *plug, const Gaffer::Set *excludedNodes = 0 )
{
	std::vector<ConnectionGadget *> connections;
	graphGadget.connectionGadgets( plug, connections, excludedNodes );

	boost::python::list l;
	for( std::vector<ConnectionGadget *>::const_iterator it=connections.begin(), eIt=connections.end(); it!=eIt; ++it )
	{
		l.append( ConnectionGadgetPtr( *it ) );
	}
	return l;
}

list connectionGadgets2( GraphGadget &graphGadget, const Gaffer::Node *node, const Gaffer::Set *excludedNodes = 0 )
{
	std::vector<ConnectionGadget *> connections;
	graphGadget.connectionGadgets( node, connections, excludedNodes );

	boost::python::list l;
	for( std::vector<ConnectionGadget *>::const_iterator it=connections.begin(), eIt=connections.end(); it!=eIt; ++it )
	{
		l.append( ConnectionGadgetPtr( *it ) );
	}
	return l;
}

list upstreamNodeGadgets( GraphGadget &graphGadget, const Gaffer::Node *node, size_t degreesOfSeparation )
{
	std::vector<NodeGadget *> nodeGadgets;
	graphGadget.upstreamNodeGadgets( node, nodeGadgets, degreesOfSeparation );

	boost::python::list l;
	for( std::vector<NodeGadget *>::const_iterator it=nodeGadgets.begin(), eIt=nodeGadgets.end(); it!=eIt; ++it )
	{
		l.append( NodeGadgetPtr( *it ) );
	}
	return l;
}

list downstreamNodeGadgets( GraphGadget &graphGadget, const Gaffer::Node *node, size_t degreesOfSeparation )
{
	std::vector<NodeGadget *> nodeGadgets;
	graphGadget.downstreamNodeGadgets( node, nodeGadgets, degreesOfSeparation );

	boost::python::list l;
	for( std::vector<NodeGadget *>::const_iterator it=nodeGadgets.begin(), eIt=nodeGadgets.end(); it!=eIt; ++it )
	{
		l.append( NodeGadgetPtr( *it ) );
	}
	return l;
}

list connectedNodeGadgets( GraphGadget &graphGadget, const Gaffer::Node *node, Gaffer::Plug::Direction direction, size_t degreesOfSeparation )
{
	std::vector<NodeGadget *> nodeGadgets;
	graphGadget.connectedNodeGadgets( node, nodeGadgets, direction, degreesOfSeparation );

	boost::python::list l;
	for( std::vector<NodeGadget *>::const_iterator it=nodeGadgets.begin(), eIt=nodeGadgets.end(); it!=eIt; ++it )
	{
		l.append( NodeGadgetPtr( *it ) );
	}
	return l;
}

void setLayout( GraphGadget &g, GraphLayoutPtr l )
{
	return g.setLayout( l );
}

GraphLayoutPtr getLayout( GraphGadget &g )
{
	return g.getLayout();
}

NodeGadgetPtr nodeGadgetAt( GraphGadget &g, const IECore::LineSegment3f lineSegmentInGadgetSpace )
{
	return g.nodeGadgetAt( lineSegmentInGadgetSpace );
}

ConnectionGadgetPtr connectionGadgetAt( GraphGadget &g, const IECore::LineSegment3f lineSegmentInGadgetSpace )
{
	return g.connectionGadgetAt( lineSegmentInGadgetSpace );
}

} // namespace

void GafferUIBindings::bindGraphGadget()
{
	scope s = GadgetClass<GraphGadget>()
		.def( init<Gaffer::NodePtr, Gaffer::SetPtr>( ( arg_( "root" ), arg_( "filter" ) = object() ) ) )
		.def( "getRoot", &getRoot )
		.def( "setRoot", &GraphGadget::setRoot, ( arg_( "root" ), arg_( "filter" ) = object() ) )
		.def( "rootChangedSignal", &GraphGadget::rootChangedSignal, return_internal_reference<1>() )
		.def( "getFilter", &getFilter )
		.def( "setFilter", &GraphGadget::setFilter )
		.def( "nodeGadget", &nodeGadget )
		.def( "connectionGadget", &connectionGadget )
		.def( "connectionGadgets", &connectionGadgets1, ( arg_( "plug" ), arg_( "excludedNodes" ) = object() ) )
		.def( "connectionGadgets", &connectionGadgets2, ( arg_( "node" ), arg_( "excludedNodes" ) = object() ) )
		.def( "upstreamNodeGadgets", &upstreamNodeGadgets, ( arg( "node" ), arg( "degreesOfSeparation" ) = Imath::limits<size_t>::max() ) )
		.def( "downstreamNodeGadgets", &downstreamNodeGadgets, ( arg( "node" ), arg( "degreesOfSeparation" ) = Imath::limits<size_t>::max() ) )
		.def( "connectedNodeGadgets", &connectedNodeGadgets, ( arg( "node" ), arg( "direction" ) = Gaffer::Plug::Invalid, arg( "degreesOfSeparation" ) = Imath::limits<size_t>::max() ) )
		.def( "setNodePosition", &GraphGadget::setNodePosition )
		.def( "getNodePosition", &GraphGadget::getNodePosition )
		.def( "hasNodePosition", &GraphGadget::hasNodePosition )
		.def( "setNodeInputConnectionsMinimised", &GraphGadget::setNodeInputConnectionsMinimised )
		.def( "getNodeInputConnectionsMinimised", &GraphGadget::getNodeInputConnectionsMinimised )
		.def( "setNodeOutputConnectionsMinimised", &GraphGadget::setNodeOutputConnectionsMinimised )
		.def( "getNodeOutputConnectionsMinimised", &GraphGadget::getNodeOutputConnectionsMinimised )
		.def( "setLayout", &setLayout )
		.def( "getLayout", &getLayout )
		.def( "nodeGadgetAt", &nodeGadgetAt )
		.def( "connectionGadgetAt", &connectionGadgetAt )
	;

	GafferBindings::SignalClass<GraphGadget::RootChangedSignal, GafferBindings::DefaultSignalCaller<GraphGadget::RootChangedSignal>, RootChangedSlotCaller>( "RootChangedSignal" );

}
<|endoftext|>


<commit_before>#include <stdlib.h>
#include <argp.h>
#include <stdio.h>
#include <string>
#include <iostream>
#include "FatSystem.h"
#include "FatPath.h"
#include "FatChains.h"
#include "FatBackup.h"
#include "FatDiff.h"
#include "utils.h"

using namespace std;

void usage()
{
    cout << "fatcat v1.0, Gregwar <g.passault@gmail.com>" << endl;
    cout << endl;
    cout << "Usage: fatcat disk.img [options]" << endl;
    cout << "  -i: display information about disk" << endl;
    cout << endl;
    cout << "Browsing & extracting:" << endl;
    cout << "  -l [dir]: list files and directories in the given path" << endl;
    cout << "  -L [cluster]: list files and directories in the given cluster" << endl;
    cout << "  -r [path]: reads the file given by the path" << endl;
    cout << "  -R [cluster]: reads the data from given cluster" << endl;
    cout << "  -s [size]: specify the size of data to read from the cluster" << endl;
    cout << "  -d: enable listing of deleted files" << endl;
    cout << "  -x [directory]: extract all files to a directory, deleted files included if -d" << endl;
    cout << "                  will start with rootDirectory, unless -f is provided" << endl;
    cout << "  -f [cluster]: define the cluster starting point for the extraction" << endl;
    cout << "* -S: write scamble data in unallocated sectors" << endl;
    cout << "* -z: write scamble data in unallocated sectors" << endl;
    cout << endl;
    cout << "FAT Hacking" << endl;
    cout << "  -@ [cluster]: Get the cluster address and informations" << endl;
    cout << "  -2: analysis & compare the 2 FATs" << endl;
    cout << "  -b [file]: backup the FATs" << endl;
    cout << "* -p [file]: restore (patch) the FATs" << endl;
    cout << "* -w [cluster] -v [value]: write next cluster (see -T)" << endl;
    cout << "  -T [table]: specify which table to write (0:both, 1:first, 2:second)" << endl;
    cout << "* -m: merge the FATs" << endl;
    cout << "  -o: search for orphan files and directories" << endl;
    cout << endl;
    cout << "Entries hacking" << endl;
    cout << "  -e [path]: sets the entry to hack, combined with:" << endl;
    cout << "* -c [cluster]: sets the entry cluster" << endl;
    cout << "* -s [cluster]: sets the entry size" << endl;

    cout << endl;
    cout << "*: These flags writes on the disk, and may damage it, be careful" << endl;
    exit(EXIT_FAILURE);
}

int main(int argc, char *argv[])
{
    vector<string> arguments;
    char *image = NULL;
    int index;

    // -s, specify the size to be read
    int size = -1;

    // -i, display informations about the disk
    bool infoFlag = false;

    // -l, list directories in the given path
    bool listFlag = false;
    string listPath;

    // -c, listing for a direct cluster
    bool listClusterFlag = false;
    int listCluster;

    // -r, reads a file
    bool readFlag = false;
    string readPath;

    // -t, reads from cluster file
    bool clusterRead = false;
    int cluster = 0;

    // -d, lists deleted
    bool listDeleted = false;

    // -x: extract
    bool extract = false;
    string extractDirectory;

    // -2: compare two fats
    bool compare = false;

    // -@: get the cluster address
    bool address = false;

    // -k: analysis the chains
    bool chains = false;

    // -b: backup the fats
    bool backup = false;
    bool patch = false;
    string backupFile;

    // -w: write next cluster
    bool writeNext = false;

    // -m: merge the FATs
    bool merge = false;

    // -v: value
    bool hasValue = false;
    int value;

    // -T: FAT table to write
    int table = 0;

    // -S: write random data in unallocated sectors
    bool scramble = false;
    bool zero = false;

    // -e: entry hacking
    bool entry = false;
    string entryPath;
    bool clusterProvided;
    bool sizeProvided;

    // Parsing command line
    while ((index = getopt(argc, argv, "il:L:r:R:s:dc:hx:2@:ob:p:w:v:mT:f:Sze:")) != -1) {
        switch (index) {
            case 'e':
                entry = true;
                entryPath = string(optarg);
                break;
            case 'z':
                zero = true;
                break;
            case 'S':
                scramble = true;
                break;
            case 'T':
                table = atoi(optarg);
                break;
            case 'm':
                merge = true;
                break;
            case 'v':
                hasValue = true;
                value = atoi(optarg);
                break;
            case 'f':
                cluster = atoi(optarg);
                break;
            case 'w':
                writeNext = true;
                cluster = atoi(optarg);
                break;
            case '@':
                address = true;
                cluster = atoi(optarg);
                break;
            case 'o':
                chains = true;
                break;
            case 'i':
                infoFlag = true;
                break;
            case 'l':
                listFlag = true;
                listPath = string(optarg);
                break;
            case 'L':
                listClusterFlag = true;
                listCluster = atoi(optarg);
                break;
            case 'r':
                readFlag = true;
                readPath = string(optarg);
                break;
            case 'R':
                clusterRead = true;
                cluster = atoi(optarg);
                break;
            case 's':
                size = atoi(optarg);
                sizeProvided = true;
                break;
            case 'd':
                listDeleted = true;
                break;
            case 'c':
                cluster = atoi(optarg);
                clusterProvided = true;
                break;
            case 'x':
                extract = true;
                extractDirectory = string(optarg);
                break;
            case '2':
                compare = true;
                break;
            case 'b':
                backup = true;
                backupFile = string(optarg);
                break;
            case 'p':
                patch = true;
                backupFile = string(optarg);
                break;
            case 'h':
                usage();
                break;
        }
    }

    // Trying to get the FAT file or device
    if (optind != argc) {
        image = argv[optind];
    }

    if (!image) {
        usage();
    }

    // Getting extra arguments
    for (index=optind+1; index<argc; index++) {
        arguments.push_back(argv[index]);
    }

    // If the user did not required any actions
    if (!(infoFlag || listFlag || listClusterFlag ||
        readFlag || clusterRead || extract || compare || address ||
        chains || backup || patch || writeNext || merge ||
        scramble || zero || entry)) {
        usage();
    }

    try {
        // Openning the image
        FatSystem fat(image);

        fat.setListDeleted(listDeleted);

        if (fat.init()) {
            if (infoFlag) {
                fat.infos();
            } else if (listFlag) {
                cout << "Listing path " << listPath << endl;
                FatPath path(listPath);
                fat.list(path);
            } else if (listClusterFlag) {
                cout << "Listing cluster " << listCluster << endl;
                fat.list(listCluster);
            } else if (readFlag) {
                FatPath path(readPath);
                fat.readFile(path);
            } else if (clusterRead) {
                fat.readFile(cluster, size);
            } else if (extract) {
                fat.extract(cluster, extractDirectory);
            } else if (compare) {
                FatDiff diff(fat);
                diff.compare();
            } else if (address) {
                cout << "Cluster " << cluster << " address:" << endl;
                long long addr = fat.clusterAddress(cluster);
                int next1 = fat.nextCluster(cluster, 0);
                int next2 = fat.nextCluster(cluster, 1);
                printf("%llu (%08x)\n", addr, addr);
                cout << "Next cluster:" << endl;
                printf("FAT1: %u (%08x)\n", next1, next1);
                printf("FAT2: %u (%08x)\n", next2, next2);
            } else if (chains) {
                FatChains chains(fat);
                chains.chainsAnalysis();
            } else if (backup || patch) {
                FatBackup backupSystem(fat);

                if (backup) {
                    backupSystem.backup(backupFile);
                } else {
                    backupSystem.patch(backupFile);
                }
            } else if (writeNext) {
                if (!hasValue) {
                    throw string("You should provide a value with -v");
                }

                int prev = fat.nextCluster(cluster);
                printf("Writing next cluster of %u from %u to %u\n", cluster, prev, value);
                fat.enableWrite();

                if (table == 0 || table == 1) {
                    printf("Writing on FAT1\n");
                    fat.writeNextCluster(cluster, value, 0);
                }
                if (table == 0 || table == 2) {
                    printf("Writing on FAT2\n");
                    fat.writeNextCluster(cluster, value, 1);
                }
            } else if (merge) {
                FatDiff diff(fat);
                diff.merge();
            } else if (scramble) {
                fat.enableWrite();
                fat.rewriteUnallocated(1);
            } else if (zero) {
                fat.enableWrite();
                fat.rewriteUnallocated();
            } else if (entry) {
                cout << "Searching entry for " << entryPath << endl;
                FatPath path(entryPath);
                FatEntry entry;
                if (fat.findFile(path, entry)) {
                    printf("Entry address %016x\n", entry.address);
                    cout << "Found entry, cluster=" << entry.cluster;
                    if (entry.isDirectory()) {
                        cout << ", directory";
                    } else {
                        cout << ", file with size=" << entry.size << " (" << prettySize(entry.size) << ")";
                    }
                    cout << endl;

                    if (clusterProvided) {
                        cout << "Setting the cluster to " << cluster << endl;
                        entry.cluster = cluster;
                    }
                    if (sizeProvided) {
                        cout << "Setting the size to " << size << endl;
                        entry.size = size;
                    }
                    if (clusterProvided || sizeProvided) {
                        entry.updateData();
                        fat.enableWrite();
                        string data = entry.data;
                        fat.writeData(entry.address, data.c_str(), entry.data.size());
                    }
                } else {
                    cout << "Entry not found." << endl;
                }
            }
        } else {
            cout << "! Failed to init the FAT filesystem" << endl;
        }
    } catch (string error) {
        cerr << "Error: " << error << endl;
    }

    exit(EXIT_SUCCESS);
}
<commit_msg>Fixing unitialized values<commit_after>#include <stdlib.h>
#include <argp.h>
#include <stdio.h>
#include <string>
#include <iostream>
#include "FatSystem.h"
#include "FatPath.h"
#include "FatChains.h"
#include "FatBackup.h"
#include "FatDiff.h"
#include "utils.h"

using namespace std;

void usage()
{
    cout << "fatcat v1.0, Gregwar <g.passault@gmail.com>" << endl;
    cout << endl;
    cout << "Usage: fatcat disk.img [options]" << endl;
    cout << "  -i: display information about disk" << endl;
    cout << endl;
    cout << "Browsing & extracting:" << endl;
    cout << "  -l [dir]: list files and directories in the given path" << endl;
    cout << "  -L [cluster]: list files and directories in the given cluster" << endl;
    cout << "  -r [path]: reads the file given by the path" << endl;
    cout << "  -R [cluster]: reads the data from given cluster" << endl;
    cout << "  -s [size]: specify the size of data to read from the cluster" << endl;
    cout << "  -d: enable listing of deleted files" << endl;
    cout << "  -x [directory]: extract all files to a directory, deleted files included if -d" << endl;
    cout << "                  will start with rootDirectory, unless -f is provided" << endl;
    cout << "  -f [cluster]: define the cluster starting point for the extraction" << endl;
    cout << "* -S: write scamble data in unallocated sectors" << endl;
    cout << "* -z: write scamble data in unallocated sectors" << endl;
    cout << endl;
    cout << "FAT Hacking" << endl;
    cout << "  -@ [cluster]: Get the cluster address and informations" << endl;
    cout << "  -2: analysis & compare the 2 FATs" << endl;
    cout << "  -b [file]: backup the FATs" << endl;
    cout << "* -p [file]: restore (patch) the FATs" << endl;
    cout << "* -w [cluster] -v [value]: write next cluster (see -T)" << endl;
    cout << "  -T [table]: specify which table to write (0:both, 1:first, 2:second)" << endl;
    cout << "* -m: merge the FATs" << endl;
    cout << "  -o: search for orphan files and directories" << endl;
    cout << endl;
    cout << "Entries hacking" << endl;
    cout << "  -e [path]: sets the entry to hack, combined with:" << endl;
    cout << "* -c [cluster]: sets the entry cluster" << endl;
    cout << "* -s [cluster]: sets the entry size" << endl;

    cout << endl;
    cout << "*: These flags writes on the disk, and may damage it, be careful" << endl;
    exit(EXIT_FAILURE);
}

int main(int argc, char *argv[])
{
    vector<string> arguments;
    char *image = NULL;
    int index;

    // -s, specify the size to be read
    int size = -1;

    // -i, display informations about the disk
    bool infoFlag = false;

    // -l, list directories in the given path
    bool listFlag = false;
    string listPath;

    // -c, listing for a direct cluster
    bool listClusterFlag = false;
    int listCluster;

    // -r, reads a file
    bool readFlag = false;
    string readPath;

    // -t, reads from cluster file
    bool clusterRead = false;
    int cluster = 0;

    // -d, lists deleted
    bool listDeleted = false;

    // -x: extract
    bool extract = false;
    string extractDirectory;

    // -2: compare two fats
    bool compare = false;

    // -@: get the cluster address
    bool address = false;

    // -k: analysis the chains
    bool chains = false;

    // -b: backup the fats
    bool backup = false;
    bool patch = false;
    string backupFile;

    // -w: write next cluster
    bool writeNext = false;

    // -m: merge the FATs
    bool merge = false;

    // -v: value
    bool hasValue = false;
    int value;

    // -T: FAT table to write
    int table = 0;

    // -S: write random data in unallocated sectors
    bool scramble = false;
    bool zero = false;

    // -e: entry hacking
    bool entry = false;
    string entryPath;
    bool clusterProvided = false;
    bool sizeProvided = false;

    // Parsing command line
    while ((index = getopt(argc, argv, "il:L:r:R:s:dc:hx:2@:ob:p:w:v:mT:f:Sze:")) != -1) {
        switch (index) {
            case 'e':
                entry = true;
                entryPath = string(optarg);
                break;
            case 'z':
                zero = true;
                break;
            case 'S':
                scramble = true;
                break;
            case 'T':
                table = atoi(optarg);
                break;
            case 'm':
                merge = true;
                break;
            case 'v':
                hasValue = true;
                value = atoi(optarg);
                break;
            case 'f':
                cluster = atoi(optarg);
                break;
            case 'w':
                writeNext = true;
                cluster = atoi(optarg);
                break;
            case '@':
                address = true;
                cluster = atoi(optarg);
                break;
            case 'o':
                chains = true;
                break;
            case 'i':
                infoFlag = true;
                break;
            case 'l':
                listFlag = true;
                listPath = string(optarg);
                break;
            case 'L':
                listClusterFlag = true;
                listCluster = atoi(optarg);
                break;
            case 'r':
                readFlag = true;
                readPath = string(optarg);
                break;
            case 'R':
                clusterRead = true;
                cluster = atoi(optarg);
                break;
            case 's':
                size = atoi(optarg);
                sizeProvided = true;
                break;
            case 'd':
                listDeleted = true;
                break;
            case 'c':
                cluster = atoi(optarg);
                clusterProvided = true;
                break;
            case 'x':
                extract = true;
                extractDirectory = string(optarg);
                break;
            case '2':
                compare = true;
                break;
            case 'b':
                backup = true;
                backupFile = string(optarg);
                break;
            case 'p':
                patch = true;
                backupFile = string(optarg);
                break;
            case 'h':
                usage();
                break;
        }
    }

    // Trying to get the FAT file or device
    if (optind != argc) {
        image = argv[optind];
    }

    if (!image) {
        usage();
    }

    // Getting extra arguments
    for (index=optind+1; index<argc; index++) {
        arguments.push_back(argv[index]);
    }

    // If the user did not required any actions
    if (!(infoFlag || listFlag || listClusterFlag ||
        readFlag || clusterRead || extract || compare || address ||
        chains || backup || patch || writeNext || merge ||
        scramble || zero || entry)) {
        usage();
    }

    try {
        // Openning the image
        FatSystem fat(image);

        fat.setListDeleted(listDeleted);

        if (fat.init()) {
            if (infoFlag) {
                fat.infos();
            } else if (listFlag) {
                cout << "Listing path " << listPath << endl;
                FatPath path(listPath);
                fat.list(path);
            } else if (listClusterFlag) {
                cout << "Listing cluster " << listCluster << endl;
                fat.list(listCluster);
            } else if (readFlag) {
                FatPath path(readPath);
                fat.readFile(path);
            } else if (clusterRead) {
                fat.readFile(cluster, size);
            } else if (extract) {
                fat.extract(cluster, extractDirectory);
            } else if (compare) {
                FatDiff diff(fat);
                diff.compare();
            } else if (address) {
                cout << "Cluster " << cluster << " address:" << endl;
                long long addr = fat.clusterAddress(cluster);
                int next1 = fat.nextCluster(cluster, 0);
                int next2 = fat.nextCluster(cluster, 1);
                printf("%llu (%08x)\n", addr, addr);
                cout << "Next cluster:" << endl;
                printf("FAT1: %u (%08x)\n", next1, next1);
                printf("FAT2: %u (%08x)\n", next2, next2);
            } else if (chains) {
                FatChains chains(fat);
                chains.chainsAnalysis();
            } else if (backup || patch) {
                FatBackup backupSystem(fat);

                if (backup) {
                    backupSystem.backup(backupFile);
                } else {
                    backupSystem.patch(backupFile);
                }
            } else if (writeNext) {
                if (!hasValue) {
                    throw string("You should provide a value with -v");
                }

                int prev = fat.nextCluster(cluster);
                printf("Writing next cluster of %u from %u to %u\n", cluster, prev, value);
                fat.enableWrite();

                if (table == 0 || table == 1) {
                    printf("Writing on FAT1\n");
                    fat.writeNextCluster(cluster, value, 0);
                }
                if (table == 0 || table == 2) {
                    printf("Writing on FAT2\n");
                    fat.writeNextCluster(cluster, value, 1);
                }
            } else if (merge) {
                FatDiff diff(fat);
                diff.merge();
            } else if (scramble) {
                fat.enableWrite();
                fat.rewriteUnallocated(1);
            } else if (zero) {
                fat.enableWrite();
                fat.rewriteUnallocated();
            } else if (entry) {
                cout << "Searching entry for " << entryPath << endl;
                FatPath path(entryPath);
                FatEntry entry;
                if (fat.findFile(path, entry)) {
                    printf("Entry address %016x\n", entry.address);
                    cout << "Found entry, cluster=" << entry.cluster;
                    if (entry.isDirectory()) {
                        cout << ", directory";
                    } else {
                        cout << ", file with size=" << entry.size << " (" << prettySize(entry.size) << ")";
                    }
                    cout << endl;

                    if (clusterProvided) {
                        cout << "Setting the cluster to " << cluster << endl;
                        entry.cluster = cluster;
                    }
                    if (sizeProvided) {
                        cout << "Setting the size to " << size << endl;
                        entry.size = size;
                    }
                    if (clusterProvided || sizeProvided) {
                        entry.updateData();
                        fat.enableWrite();
                        string data = entry.data;
                        fat.writeData(entry.address, data.c_str(), entry.data.size());
                    }
                } else {
                    cout << "Entry not found." << endl;
                }
            }
        } else {
            cout << "! Failed to init the FAT filesystem" << endl;
        }
    } catch (string error) {
        cerr << "Error: " << error << endl;
    }

    exit(EXIT_SUCCESS);
}
<|endoftext|>


<commit_before>cd354e66-4b02-11e5-b6d5-28cfe9171a43<commit_msg>compiles now<commit_after>cd4050e1-4b02-11e5-b3a9-28cfe9171a43<|endoftext|>


<commit_before>#include <boost/lexical_cast.hpp>
#include <boost/function.hpp>
#include <boost/bind.hpp>
#include <boost/tuple/tuple.hpp>
#include <boost/any.hpp>
#include <boost/uuid/uuid.hpp>
#include <boost/uuid/uuid_generators.hpp>
#include <boost/uuid/uuid_io.hpp>
#include <sstream>
#include <string>
#include <algorithm>
#include <iostream>
#include <vector>
using namespace std;

void testVector();
void testLexicalCast();
void testFunction();
void testBind();
void testLambda();
void testTuple();
void testAny();
void testUUID();
void testBubbleSort();

int main()
{
	cout << "Hello, world!" << endl;

	//testLexicalCast();
	//testFunction();
	//testBind();
	//testLambda();
	//testTuple();
	//testAny();
    //testUUID();
	testBubbleSort();

	return 0;
}

void testVector()
{
	std::vector<int> numbers;
	numbers.push_back(1);
	numbers.push_back(2);
	for (int i = 0; i < (int)numbers.size(); ++i)
		cout << i << endl;
}

void testLexicalCast()
{
	// 以下会抛出异常
	//cout << boost::lexical_cast<int>("  123  ") << endl;
	//cout << boost::lexical_cast<int>("123  ") << endl;
	//cout << boost::lexical_cast<int>("12 3") << endl;
	//cout << boost::lexical_cast<int>("1 2 3") << endl;

	// 空字符串会抛出异常
	//cout << boost::lexical_cast<int>("") << endl;

	// 不支持十六进制
	//cout << boost::lexical_cast<int>("0x0362") << endl;

	// 十六进制字符串转成整数 0x前缀可有可无
	stringstream ss;
	ss << hex << "0x0362f"; // 13871
	int i;
	ss >> i;
	cout << i << endl;

	// 十六进制字符串转成整数 C++11 中的 std::stoi <string>
	cout << std::stoi("0x0362f", 0, 16) << endl;
	cout << std::stoi("0362f", 0, 16) << endl;
	//cout << std::stoi("", 0, 16) << endl; // 抛出异常

	// 字符串转换为bool 只支持 0 和 1，不支持true或false或其他整数值
	//cout << boost::lexical_cast<bool>("true") << endl;
	//cout << boost::lexical_cast<bool>("false") << endl;
	//cout << boost::lexical_cast<bool>("True") << endl;
 	//cout << boost::lexical_cast<bool>("-1") << endl;
 	//cout << boost::lexical_cast<bool>("2") << endl;
 	cout << boost::lexical_cast<bool>("1") << endl;
 	cout << boost::lexical_cast<bool>("0") << endl;

	// test
}

void func(int i)
{
	cout << i << endl;
}

class Test1
{
public:
	void func()
	{
		cout << "Test1::func()" << endl;
	}

	void func2(int i)
	{
		cout << "Test1::func()" << i << endl;
	}
};

void testFunction()
{
	boost::function<void (int)> f1 = &func;
	f1(12);

	Test1 t1;
	boost::function<void (Test1*)> f2 = &Test1::func;
	f2(&t1);

	boost::function<void (Test1*, int)> f3 = &Test1::func2;
	f3(&t1, 100);
}

void testBind()
{
	// auto c++11
	Test1 t1;
	auto f1 = boost::bind(&Test1::func2, &t1, _1);
	f1(100);
}

void testLambda()
{
	// c++11 Lambda表达式
	vector<int> vec;
	for (int i = 0; i < 5; ++i)
		vec.push_back(i);

	int a = 1;
	int b = 2;

	// []内的参数指的是Lambda表达式可以得到的外部变量
	// 如果在[]中传入=的话，表示可以取得所有的外部变量，如a、b
	// ()内的参数是每次调用函数时传入的参数
	// ->后加上的是Lambda表达式返回值的类型
	for_each(vec.begin(), vec.end(), [b](int& x){ cout << x + b << endl; });
	for_each(vec.begin(), vec.end(), [=](int& x){ cout << a + b << endl; });
	for_each(vec.begin(), vec.end(), [=](int& x)->int{ cout << a + b << endl; return x; });

}

void testTuple()
{
	boost::tuple<int, double> t1(1, 2.5);
	cout << t1.get<0>() << endl;
	cout << t1.get<1>() << endl;
}

void testAny()
{
	boost::any val = 12;
	cout << boost::any_cast<int>(val) << endl;

	val = 13.14;
	cout << boost::any_cast<double>(val) << endl;
}

void testUUID()
{
	boost::uuids::random_generator gen;
	boost::uuids::uuid u1 = gen();
	boost::uuids::uuid u2 = gen();
	cout << u1 << endl;
	cout << u2 << endl;
}

// 冒泡排序，从小到大排序
// 来自维基百科：
// https://zh.wikipedia.org/wiki/%E5%86%92%E6%B3%A1%E6%8E%92%E5%BA%8F
template<typename T>
void bubbleSort(T* arr, int len)
{
	for (int i = 0; i < len - 1; ++i)
	{
		for (int j = 0; j < len - 1 - i; ++j)
		{
			if (arr[j] > arr[j + 1])
				swap(arr[j], arr[j + 1]);
		}
	}
}

void testBubbleSort()
{
	int arr[] = { 12, 45, 12, 8, 0, 6, 5, 90, 86 };
	int len = sizeof(arr) / sizeof(int);
	bubbleSort(arr, len);
	for (int i = 0; i < len; ++i)
		cout << arr[i] << ' ';
	cout << endl;
}
<commit_msg>Add insertion sort algorithm<commit_after>#include <boost/lexical_cast.hpp>
#include <boost/function.hpp>
#include <boost/bind.hpp>
#include <boost/tuple/tuple.hpp>
#include <boost/any.hpp>
#include <boost/uuid/uuid.hpp>
#include <boost/uuid/uuid_generators.hpp>
#include <boost/uuid/uuid_io.hpp>
#include <sstream>
#include <string>
#include <algorithm>
#include <iostream>
#include <vector>
using namespace std;

void testVector();
void testLexicalCast();
void testFunction();
void testBind();
void testLambda();
void testTuple();
void testAny();
void testUUID();
void testBubbleSort();
void testInsertionSort();

int main()
{
	cout << "Hello, world!" << endl;

	//testLexicalCast();
	//testFunction();
	//testBind();
	//testLambda();
	//testTuple();
	//testAny();
    //testUUID();
	testBubbleSort();
	testInsertionSort();

	return 0;
}

void testVector()
{
	std::vector<int> numbers;
	numbers.push_back(1);
	numbers.push_back(2);
	for (int i = 0; i < (int)numbers.size(); ++i)
		cout << i << endl;
}

void testLexicalCast()
{
	// 以下会抛出异常
	//cout << boost::lexical_cast<int>("  123  ") << endl;
	//cout << boost::lexical_cast<int>("123  ") << endl;
	//cout << boost::lexical_cast<int>("12 3") << endl;
	//cout << boost::lexical_cast<int>("1 2 3") << endl;

	// 空字符串会抛出异常
	//cout << boost::lexical_cast<int>("") << endl;

	// 不支持十六进制
	//cout << boost::lexical_cast<int>("0x0362") << endl;

	// 十六进制字符串转成整数 0x前缀可有可无
	stringstream ss;
	ss << hex << "0x0362f"; // 13871
	int i;
	ss >> i;
	cout << i << endl;

	// 十六进制字符串转成整数 C++11 中的 std::stoi <string>
	cout << std::stoi("0x0362f", 0, 16) << endl;
	cout << std::stoi("0362f", 0, 16) << endl;
	//cout << std::stoi("", 0, 16) << endl; // 抛出异常

	// 字符串转换为bool 只支持 0 和 1，不支持true或false或其他整数值
	//cout << boost::lexical_cast<bool>("true") << endl;
	//cout << boost::lexical_cast<bool>("false") << endl;
	//cout << boost::lexical_cast<bool>("True") << endl;
 	//cout << boost::lexical_cast<bool>("-1") << endl;
 	//cout << boost::lexical_cast<bool>("2") << endl;
 	cout << boost::lexical_cast<bool>("1") << endl;
 	cout << boost::lexical_cast<bool>("0") << endl;

	// test
}

void func(int i)
{
	cout << i << endl;
}

class Test1
{
public:
	void func()
	{
		cout << "Test1::func()" << endl;
	}

	void func2(int i)
	{
		cout << "Test1::func()" << i << endl;
	}
};

void testFunction()
{
	boost::function<void (int)> f1 = &func;
	f1(12);

	Test1 t1;
	boost::function<void (Test1*)> f2 = &Test1::func;
	f2(&t1);

	boost::function<void (Test1*, int)> f3 = &Test1::func2;
	f3(&t1, 100);
}

void testBind()
{
	// auto c++11
	Test1 t1;
	auto f1 = boost::bind(&Test1::func2, &t1, _1);
	f1(100);
}

void testLambda()
{
	// c++11 Lambda表达式
	vector<int> vec;
	for (int i = 0; i < 5; ++i)
		vec.push_back(i);

	int a = 1;
	int b = 2;

	// []内的参数指的是Lambda表达式可以得到的外部变量
	// 如果在[]中传入=的话，表示可以取得所有的外部变量，如a、b
	// ()内的参数是每次调用函数时传入的参数
	// ->后加上的是Lambda表达式返回值的类型
	for_each(vec.begin(), vec.end(), [b](int& x){ cout << x + b << endl; });
	for_each(vec.begin(), vec.end(), [=](int& x){ cout << a + b << endl; });
	for_each(vec.begin(), vec.end(), [=](int& x)->int{ cout << a + b << endl; return x; });

}

void testTuple()
{
	boost::tuple<int, double> t1(1, 2.5);
	cout << t1.get<0>() << endl;
	cout << t1.get<1>() << endl;
}

void testAny()
{
	boost::any val = 12;
	cout << boost::any_cast<int>(val) << endl;

	val = 13.14;
	cout << boost::any_cast<double>(val) << endl;
}

void testUUID()
{
	boost::uuids::random_generator gen;
	boost::uuids::uuid u1 = gen();
	boost::uuids::uuid u2 = gen();
	cout << u1 << endl;
	cout << u2 << endl;
}

// 冒泡排序，从小到大排序
// 来自维基百科：
// https://zh.wikipedia.org/wiki/%E5%86%92%E6%B3%A1%E6%8E%92%E5%BA%8F
template<typename T>
void bubbleSort(T* arr, int len)
{
	for (int i = 0; i < len - 1; ++i)
	{
		for (int j = 0; j < len - 1 - i; ++j)
		{
			if (arr[j] > arr[j + 1])
				swap(arr[j], arr[j + 1]);
		}
	}
}

void testBubbleSort()
{
	int arr[] = { 12, 45, 12, 8, 0, 6, 5, 90, 86 };
	int len = sizeof(arr) / sizeof(int);
	bubbleSort(arr, len);
	for (int i = 0; i < len; ++i)
		cout << arr[i] << ' ';
	cout << endl;
}

// 插入排序
// 维基百科：
// https://zh.wikipedia.org/wiki/%E6%8F%92%E5%85%A5%E6%8E%92%E5%BA%8F
template<typename T>
void insertionSort(T* arr, int len)
{
	for (int i = 1; i < len; ++i)
	{
		T temp = arr[i];
		int j = i - 1;
		for (; j >= 0 && arr[j] > temp; --j)
			arr[j + 1] = arr[j];

		arr[j + 1] = temp;
	}
}

void testInsertionSort()
{
	int arr[] = { 12, 45, 12, 8, 0, 6, 5, 90, 86 };
	int len = sizeof(arr) / sizeof(int);
	insertionSort(arr, len);
	for (int i = 0; i < len; ++i)
		cout << arr[i] << ' ';
	cout << endl;
}
<|endoftext|>


<commit_before>b8db900a-2747-11e6-8c47-e0f84713e7b8<commit_msg>Does anyone even read these anymore???<commit_after>b8eb051e-2747-11e6-87ba-e0f84713e7b8<|endoftext|>


<commit_before>6bbb832e-ad5b-11e7-9556-ac87a332f658<commit_msg>add file<commit_after>6c651338-ad5b-11e7-9829-ac87a332f658<|endoftext|>


<commit_before>#include "stdafx.h"

// OpenARK Libraries
#include "version.h"
#ifdef PMDSDK_ENABLED
    #include "PMDCamera.h"
#endif
#ifdef RSSDK_ENABLED
    #include "SR300Camera.h"
#endif

#include "Webcam.h"
#include "Visualizer.h"
#include "Hand.h"
#include "FramePlane.h"
#include "Calibration.h"
#include "Util.h"
#include "UDPSender.h"
#include "FrameObject.h"
#include "StreamingAverager.h"

#include "HandClassifier.h"

using namespace ark;

int main() {
    printf("Welcome to OpenARK v %s Demo\n\n", ark::VERSION);
    printf("CONTROLS:\nQ or ESC to quit, P to show/hide planes, H to show/hide hands, SPACE to play/pause\n\n");
    printf("VIEWER BACKGROUNDS:\n1 = IR Image, 2 = Depth Image, 3 = Normal Map, 0 = None\n");
    boost::shared_ptr<DepthCamera> camera;

#ifdef PMDSDK_ENABLED
    if (!strcmp(OPENARK_CAMERA_TYPE, "pmd")) {
        camera = boost::make_shared<PMDCamera>();
    }
    else {
        return -1;
    }
#endif
#ifdef RSSDK_ENABLED
    if (!strcmp(OPENARK_CAMERA_TYPE, "sr300")) {
        camera = boost::make_shared<SR300Camera>();
    }
    else {
        return -1;
    }
#endif

    // seed rng
    srand(time(NULL));

    // store frame & FPS information
    int frame = 0;
    clock_t cycleStartTime = 0;

    const int FPS_FRAMES = 5;
    float currFps = 0;

    unsigned long long minFrameTime = 1000 / 120; // 1000 / FPS CAP

    // image layer flags
    bool handLayer = true, planeLayer = false;

    // background style: 0=none, 1=ir, 2=depth, 3=normal
    int backgroundStyle = 1;

    // if false, pauses picture
    bool playing = true;

    // turn on the camera
    camera->beginCapture(120, false);

    // main demo loop
    while (true)
    {
        // get latest images from the camera
        cv::Mat xyzMap = camera->getXYZMap();

        // query objects in the current frame
        ObjectParams params; // default parameters

        std::vector<ark::HandPtr> hands;
        std::vector<ark::FramePlanePtr> planes;

        if (handLayer || planeLayer) {
            planes = camera->getFramePlanes(&params);

            if (handLayer) {
                hands = camera->getFrameHands(&params);
            }
        }

        // construct visualizations
        cv::Mat handVisual;

        // background of visualization
        if (backgroundStyle == 1 && camera->hasIRMap()) {
            // IR background
            cv::cvtColor(camera->getIRMap(), handVisual, cv::COLOR_GRAY2BGR, 3);
            cv::imshow("IR",camera->getIRMap());
        }

        else if (backgroundStyle == 2) {
            // depth map background
            Visualizer::visualizeXYZMap(xyzMap, handVisual);
        }

        else if (backgroundStyle == 3) {
            // normal map background
            cv::Mat normalMap = camera->getNormalMap();
            Visualizer::visualizeNormalMap(normalMap, handVisual, params.normalResolution);
        }

        else {
            handVisual = cv::Mat::zeros(camera->getImageSize(), CV_8UC3);
        }

        const cv::Scalar WHITE(255, 255, 255);

        if (planeLayer) {
            // color all points on the screen close to a plane
            cv::Vec3s color;

            for (uint i = 0; i < planes.size(); ++i) {
                color = util::paletteColor(i);

                for (int row = 0; row < xyzMap.rows; ++row) {
                    const Vec3f * ptr = xyzMap.ptr<Vec3f>(row);
                    Vec3b * outPtr = handVisual.ptr<Vec3b>(row);

                    for (int col = 0; col < xyzMap.cols; ++col) {
                        const Vec3f & xyz = ptr[col];
                        if (xyz[2] == 0) continue;

                        float norm = util::pointPlaneNorm(xyz, planes[i]->equation);

                        float fact = std::max(0.0, 0.5f - norm / params.handPlaneMinNorm / 8.0f);
                        if (fact == 0.0f) continue;

                        outPtr[col] += (color - (cv::Vec3s)outPtr[col]) * fact;
                    }
                }

                // draw normal vector
                Point2i drawPt = planes[i]->getCenterIJ();
                cv::Vec3f normal = planes[i]->getNormalVector();
                Point2i arrowPt(drawPt.x + normal[0] * 100, drawPt.y - normal[1] * 100);
                cv::arrowedLine(handVisual, drawPt, arrowPt, WHITE, 4, cv::LINE_AA, 0, 0.2);
            }
        }

        // draw hands
        if (handLayer) {
            for (auto hand : hands) {
                Visualizer::visualizeHand(handVisual, handVisual, hand.get(),
                                          hand->getSVMConfidence(), &planes);
            }
        }

        if (handLayer && hands.size() > 0) {
            // show "N Hands" on top left
            cv::putText(handVisual, std::to_string(hands.size()) +
                util::pluralize(" Hand", hands.size()),
                Point2i(10, 25), 0, 0.5, WHITE);
        }

        if (planeLayer && planes.size() > 0) {
            // show "N Planes" on top left
            cv::putText(handVisual, std::to_string(planes.size()) +
                util::pluralize(" Plane", planes.size()),
                Point2i(10, 55), 0, 0.5, WHITE);
        }

        // update FPS
        if (cycleStartTime) {
            if (frame % FPS_FRAMES == 0) {
                currFps = (float)CLOCKS_PER_SEC  * (float)FPS_FRAMES / (clock() - cycleStartTime);
                cycleStartTime = clock();
            }

            if (frame > FPS_FRAMES && !camera->badInput()) {
                // show FPS on top right
                std::stringstream fpsDisplay;
                double fpsDisp = currFps;
                static char chr[32];
                sprintf(chr, "FPS: %02.3lf", fpsDisp);
                Point2i pos(handVisual.cols - 120, 25);
                cv::putText(handVisual, chr, pos, 0, 0.5, WHITE);
            }
        }
        else {
            cycleStartTime = clock();
        }

        int wait = 1;

        // show "NO SIGNAL" on each visual in case of bad input
        if (camera->badInput() || !playing) {
            // wait 50 ms, or pause
            wait = !playing ? 0 : 50;

            const int RECT_WID = (!playing ? 120 : 160), RECT_HI = 40;
            cv::Rect rect(handVisual.cols / 2 - RECT_WID / 2,
                handVisual.rows / 2 - RECT_HI / 2,
                RECT_WID, RECT_HI);

            const cv::Scalar RECT_COLOR = cv::Scalar(0, (!playing ? 160 : 50), 255);
            const std::string NO_SIGNAL_STR = (!playing ? "PAUSED" : "NO SIGNAL");
            const cv::Point STR_POS(handVisual.cols / 2 - (!playing ? 50 : 65), handVisual.rows / 2 + 7);

            // show on each visual
            cv::rectangle(handVisual, rect, RECT_COLOR, -1);
            cv::putText(handVisual, NO_SIGNAL_STR, STR_POS, 0, 0.8, WHITE, 1, cv::LINE_AA);
            if (xyzMap.rows) {
                cv::rectangle(xyzMap, rect, RECT_COLOR / 255.0, -1);
                cv::putText(xyzMap, NO_SIGNAL_STR, STR_POS, 0, 0.8, cv::Scalar(1.0f, 1.0f, 1.0f), 1, cv::LINE_AA);
            }
        }

        // show visualizations
        cv::imshow(camera->getModelName() + " Depth Map", xyzMap);
        cv::imshow("Demo Output - OpenARK v" + std::string(ark::VERSION), handVisual);

        // END HAND DETECTION

        /**** Start: Loop Break Condition ****/
        int c = cv::waitKey(wait);

        // 27 is ESC
        if (c == 'q' || c == 'Q' || c == 27) {
            break;
        }

        else if (c == 'p' || c == 'P') {
            planeLayer = !planeLayer;
        }

        else if (c == 'h' || c == 'H') {
            handLayer = !handLayer;
        }

        else if (c >= '0' && c <= '3') {
            backgroundStyle = c - '0';
        }

        else if (c == ' ') {
            // paused, any key to go to next frame (space to play)
            playing = !playing;
        }

        /**** End: Loop Break Condition ****/
        ++frame;
    }

    camera->endCapture();

    cv::destroyAllWindows();
    return 0;
}<commit_msg>removed debugging code main.cpp<commit_after>#include "stdafx.h"

// OpenARK Libraries
#include "version.h"
#ifdef PMDSDK_ENABLED
    #include "PMDCamera.h"
#endif
#ifdef RSSDK_ENABLED
    #include "SR300Camera.h"
#endif

#include "Webcam.h"
#include "Visualizer.h"
#include "Hand.h"
#include "FramePlane.h"
#include "Calibration.h"
#include "Util.h"
#include "UDPSender.h"
#include "FrameObject.h"
#include "StreamingAverager.h"

#include "HandClassifier.h"

using namespace ark;

int main() {
    printf("Welcome to OpenARK v %s Demo\n\n", ark::VERSION);
    printf("CONTROLS:\nQ or ESC to quit, P to show/hide planes, H to show/hide hands, SPACE to play/pause\n\n");
    printf("VIEWER BACKGROUNDS:\n1 = IR Image, 2 = Depth Image, 3 = Normal Map, 0 = None\n");
    boost::shared_ptr<DepthCamera> camera;

#ifdef PMDSDK_ENABLED
    if (!strcmp(OPENARK_CAMERA_TYPE, "pmd")) {
        camera = boost::make_shared<PMDCamera>();
    }
    else {
        return -1;
    }
#endif
#ifdef RSSDK_ENABLED
    if (!strcmp(OPENARK_CAMERA_TYPE, "sr300")) {
        camera = boost::make_shared<SR300Camera>();
    }
    else {
        return -1;
    }
#endif

    // seed rng
    srand(time(NULL));

    // store frame & FPS information
    int frame = 0;
    clock_t cycleStartTime = 0;

    const int FPS_FRAMES = 5;
    float currFps = 0;

    unsigned long long minFrameTime = 1000 / 120; // 1000 / FPS CAP

    // image layer flags
    bool handLayer = true, planeLayer = false;

    // background style: 0=none, 1=ir, 2=depth, 3=normal
    int backgroundStyle = 1;

    // if false, pauses picture
    bool playing = true;

    // turn on the camera
    camera->beginCapture(120, false);

    // main demo loop
    while (true)
    {
        // get latest images from the camera
        cv::Mat xyzMap = camera->getXYZMap();

        // query objects in the current frame
        ObjectParams params; // default parameters

        std::vector<ark::HandPtr> hands;
        std::vector<ark::FramePlanePtr> planes;

        if (handLayer || planeLayer) {
            planes = camera->getFramePlanes(&params);

            if (handLayer) {
                hands = camera->getFrameHands(&params);
            }
        }

        // construct visualizations
        cv::Mat handVisual;

        // background of visualization
        if (backgroundStyle == 1 && camera->hasIRMap()) {
            // IR background
            cv::cvtColor(camera->getIRMap(), handVisual, cv::COLOR_GRAY2BGR, 3);
        }

        else if (backgroundStyle == 2) {
            // depth map background
            Visualizer::visualizeXYZMap(xyzMap, handVisual);
        }

        else if (backgroundStyle == 3) {
            // normal map background
            cv::Mat normalMap = camera->getNormalMap();
            Visualizer::visualizeNormalMap(normalMap, handVisual, params.normalResolution);
        }

        else {
            handVisual = cv::Mat::zeros(camera->getImageSize(), CV_8UC3);
        }

        const cv::Scalar WHITE(255, 255, 255);

        if (planeLayer) {
            // color all points on the screen close to a plane
            cv::Vec3s color;

            for (uint i = 0; i < planes.size(); ++i) {
                color = util::paletteColor(i);

                for (int row = 0; row < xyzMap.rows; ++row) {
                    const Vec3f * ptr = xyzMap.ptr<Vec3f>(row);
                    Vec3b * outPtr = handVisual.ptr<Vec3b>(row);

                    for (int col = 0; col < xyzMap.cols; ++col) {
                        const Vec3f & xyz = ptr[col];
                        if (xyz[2] == 0) continue;

                        float norm = util::pointPlaneNorm(xyz, planes[i]->equation);

                        float fact = std::max(0.0, 0.5f - norm / params.handPlaneMinNorm / 8.0f);
                        if (fact == 0.0f) continue;

                        outPtr[col] += (color - (cv::Vec3s)outPtr[col]) * fact;
                    }
                }

                // draw normal vector
                Point2i drawPt = planes[i]->getCenterIJ();
                cv::Vec3f normal = planes[i]->getNormalVector();
                Point2i arrowPt(drawPt.x + normal[0] * 100, drawPt.y - normal[1] * 100);
                cv::arrowedLine(handVisual, drawPt, arrowPt, WHITE, 4, cv::LINE_AA, 0, 0.2);
            }
        }

        // draw hands
        if (handLayer) {
            for (ark::HandPtr hand : hands) {
                Visualizer::visualizeHand(handVisual, handVisual, hand.get(),
                                          hand->getSVMConfidence(), &planes);
            }
        }

        if (handLayer && hands.size() > 0) {
            // show "N Hands" on top left
            cv::putText(handVisual, std::to_string(hands.size()) +
                util::pluralize(" Hand", hands.size()),
                Point2i(10, 25), 0, 0.5, WHITE);
        }

        if (planeLayer && planes.size() > 0) {
            // show "N Planes" on top left
            cv::putText(handVisual, std::to_string(planes.size()) +
                util::pluralize(" Plane", planes.size()),
                Point2i(10, 55), 0, 0.5, WHITE);
        }

        // update FPS
        if (cycleStartTime) {
            if (frame % FPS_FRAMES == 0) {
                currFps = (float)CLOCKS_PER_SEC  * (float)FPS_FRAMES / (clock() - cycleStartTime);
                cycleStartTime = clock();
            }

            if (frame > FPS_FRAMES && !camera->badInput()) {
                // show FPS on top right
                std::stringstream fpsDisplay;
                double fpsDisp = currFps;
                static char chr[32];
                sprintf(chr, "FPS: %02.3lf", fpsDisp);
                Point2i pos(handVisual.cols - 120, 25);
                cv::putText(handVisual, chr, pos, 0, 0.5, WHITE);
            }
        }
        else {
            cycleStartTime = clock();
        }

        int wait = 1;

        // show "NO SIGNAL" on each visual in case of bad input
        if (camera->badInput() || !playing) {
            // wait 50 ms, or pause
            wait = !playing ? 0 : 50;

            const int RECT_WID = (!playing ? 120 : 160), RECT_HI = 40;
            cv::Rect rect(handVisual.cols / 2 - RECT_WID / 2,
                handVisual.rows / 2 - RECT_HI / 2,
                RECT_WID, RECT_HI);

            const cv::Scalar RECT_COLOR = cv::Scalar(0, (!playing ? 160 : 50), 255);
            const std::string NO_SIGNAL_STR = (!playing ? "PAUSED" : "NO SIGNAL");
            const cv::Point STR_POS(handVisual.cols / 2 - (!playing ? 50 : 65), handVisual.rows / 2 + 7);

            // show on each visual
            cv::rectangle(handVisual, rect, RECT_COLOR, -1);
            cv::putText(handVisual, NO_SIGNAL_STR, STR_POS, 0, 0.8, WHITE, 1, cv::LINE_AA);
            if (xyzMap.rows) {
                cv::rectangle(xyzMap, rect, RECT_COLOR / 255.0, -1);
                cv::putText(xyzMap, NO_SIGNAL_STR, STR_POS, 0, 0.8, cv::Scalar(1.0f, 1.0f, 1.0f), 1, cv::LINE_AA);
            }
        }

        // show visualizations
        cv::imshow(camera->getModelName() + " Depth Map", xyzMap);
        cv::imshow("Demo Output - OpenARK v" + std::string(ark::VERSION), handVisual);

        // END HAND DETECTION

        /**** Start: Loop Break Condition ****/
        int c = cv::waitKey(wait);

        // 27 is ESC
        if (c == 'q' || c == 'Q' || c == 27) {
            break;
        }

        else if (c == 'p' || c == 'P') {
            planeLayer = !planeLayer;
        }

        else if (c == 'h' || c == 'H') {
            handLayer = !handLayer;
        }

        else if (c >= '0' && c <= '3') {
            backgroundStyle = c - '0';
        }

        else if (c == ' ') {
            // paused, any key to go to next frame (space to play)
            playing = !playing;
        }

        /**** End: Loop Break Condition ****/
        ++frame;
    }

    camera->endCapture();

    cv::destroyAllWindows();
    return 0;
}<|endoftext|>


<commit_before>06063440-2748-11e6-bdc3-e0f84713e7b8<commit_msg>Added that feature we discussed on... Was it monday?<commit_after>06104f3d-2748-11e6-a692-e0f84713e7b8<|endoftext|>


<commit_before>#include "imgui.h"
#include "imgui-sfml.h"
#include <iostream>
#include <SFML/Graphics.hpp>
#include <SFML/System/Clock.hpp>

// TEMP
enum class Direction{
    HORIZONTAL,
    VERTICAL,
    BOTH
};

void drawLine(sf::RenderWindow &window, sf::RectangleShape &line,
              const sf::Color &color=sf::Color::White, const int step=10,
              const Direction direction=Direction::BOTH, const int lineWidth=1)
{
    if(direction == Direction::BOTH){
        drawLine(window, line, color, step, Direction::HORIZONTAL);
        drawLine(window, line, color, step, Direction::VERTICAL);
    }
    else{
        sf::Vector2u winSize{window.getSize()};
        int edge{0};

        line.setFillColor(color);

        switch(direction){
            case Direction::HORIZONTAL:
                edge = window.getSize().x;
                line.setSize(sf::Vector2f(edge,lineWidth));
                break;
            case Direction::VERTICAL:
                edge = window.getSize().y;
                line.setSize(sf::Vector2f(lineWidth,edge));
                break;
        }

        for(int i=0; i<edge; i+=step){
            switch(direction){
                case Direction::HORIZONTAL:
                    line.setPosition(0,i);
                    break;
                case Direction::VERTICAL:
                    line.setPosition(i,0);
                    break;
            }
            window.draw(line);
        }
    }

}

void drawGrid(sf::RenderWindow &window)
{
    sf::RectangleShape line;

    int steps[]{12, 24, 96};
    sf::Color colors[]{sf::Color {35,85,125},
                       sf::Color {40,90,130},
                       sf::Color {60,110,150}};

    for(int i=0;i<3;++i)
        drawLine(window, line,colors[i], steps[i]);
}

// Exist some problem with rounding of <Vector2i size> variable
// For example:
// if init <size.x> value = 200, is losed 2 pixel when program
// step into next recurtion level (200/3 -> 198)
void drawFigure(      sf::RenderWindow &window,
                const sf::Vector2i     &position,
                const sf::Vector2i     &size,
                const int              depth,
                const sf::Color        &fillColor=sf::Color::White,
                const int              outlineThickness=1,
                const sf::Color        &outlineColor=sf::Color(0,0,0,0))
{
    sf::RectangleShape element;

    sf::Vector2i outerSize(size.x/3, size.y/3);
    sf::Vector2i innerSize(outerSize.x - outlineThickness*2,
                           outerSize.y - outlineThickness*2);

    element.setSize(sf::Vector2f(innerSize.x,innerSize.y));
    element.setFillColor(fillColor);

    element.setOutlineThickness(outlineThickness);
    element.setOutlineColor(outlineColor);

    sf::Vector2i point(position);

    if (depth == 0){
        element.setSize(sf::Vector2f(size.x,size.y));
        element.setPosition(sf::Vector2f(position.x,position.y));
        window.draw(element);
        return;
    }

    for (int i=0; i<9; ++i)
    {
        if (i != 4){
            if (i!= 0 && !(i%3)){
                point.y += outerSize.x;
                point.x =  position.x;
            }

            element.setPosition(sf::Vector2f(point.x,point.y));

            if (depth == 1)
                window.draw(element);
            else{
                int thickness = outlineThickness > 1? outlineThickness/2 :
                                                      outlineThickness;
                drawFigure(window, point, outerSize, depth-1,
                           fillColor, thickness, outlineColor);
            }
         }
         point.x += outerSize.y;
    }
}

int main()
{
    sf::RenderWindow window(sf::VideoMode(800,600),"ReIGen", sf::Style::Titlebar|
                                                             sf::Style::Close);
    ImGui::SFML::Init(window);

    sf::Color bgColor(30,80,120);
    int uiWidth = 200;

    sf::Clock deltaClock;

    sf::Vector2i canvasCenter((window.getSize().x - uiWidth)/2,
                               window.getSize().y/2);
    sf::Vector2i figureSize(450,450);
    sf::Vector2i figurePosition(canvasCenter.x - figureSize.x/2,
                                canvasCenter.y - figureSize.y/2);

    while (window.isOpen())
    {
        sf::Event event;
        while (window.pollEvent(event))
        {
            ImGui::SFML::ProcessEvent(event);

            if (event.type == sf::Event::Closed)
                    window.close();
        }

        ImGui::SFML::Update(window, deltaClock.restart());

        ImGui::SetNextWindowPos(ImVec2(600,0));
        ImGui::SetNextWindowSize(ImVec2(uiWidth,600));
        ImGui::Begin("Settings", false, ImGuiWindowFlags_NoTitleBar|
                                        ImGuiWindowFlags_NoResize|
                                        ImGuiWindowFlags_NoMove|
                                        ImGuiWindowFlags_NoCollapse|
                                        ImGuiWindowFlags_ShowBorders);

        ImGui::End();

        window.clear(bgColor);
        drawGrid(window);
        drawFigure(window, figurePosition, figureSize, 0);
        ImGui::Render();
        window.display();
    }

    ImGui::SFML::Shutdown();
    return 0;
}
<commit_msg>Improve UI: add several simple controllers<commit_after>#include "imgui.h"
#include "imgui-sfml.h"
#include <iostream>
#include <SFML/Graphics.hpp>
#include <SFML/System/Clock.hpp>

#define IM_ARRAYSIZE(_ARR)  ((int)(sizeof(_ARR)/sizeof(*_ARR)))

// TEMP
enum class Direction{
    HORIZONTAL,
    VERTICAL,
    BOTH
};

void drawLine(sf::RenderWindow &window, sf::RectangleShape &line,
              const sf::Color &color=sf::Color::White, const int step=10,
              const Direction direction=Direction::BOTH, const int lineWidth=1)
{
    if(direction == Direction::BOTH){
        drawLine(window, line, color, step, Direction::HORIZONTAL);
        drawLine(window, line, color, step, Direction::VERTICAL);
    }
    else{
        sf::Vector2u winSize{window.getSize()};
        int edge{0};

        line.setFillColor(color);

        switch(direction){
            case Direction::HORIZONTAL:
                edge = window.getSize().x;
                line.setSize(sf::Vector2f(edge,lineWidth));
                break;
            case Direction::VERTICAL:
                edge = window.getSize().y;
                line.setSize(sf::Vector2f(lineWidth,edge));
                break;
        }

        for(int i=0; i<edge; i+=step){
            switch(direction){
                case Direction::HORIZONTAL:
                    line.setPosition(0,i);
                    break;
                case Direction::VERTICAL:
                    line.setPosition(i,0);
                    break;
            }
            window.draw(line);
        }
    }

}

void drawGrid(sf::RenderWindow &window)
{
    sf::RectangleShape line;

    int steps[]{12, 24, 96};
    sf::Color colors[]{sf::Color {35,85,125},
                       sf::Color {40,90,130},
                       sf::Color {60,110,150}};

    for(int i=0;i<3;++i)
        drawLine(window, line,colors[i], steps[i]);
}

// Exist some problem with rounding of <Vector2i size> variable
// For example:
// if init <size.x> value = 200, is losed 2 pixel when program
// step into next recurtion level (200/3 -> 198)
void drawFigure(      sf::RenderWindow &window,
                const sf::Vector2i     &position,
                const sf::Vector2i     &size,
                const int              depth,
                const sf::Color        &fillColor=sf::Color::White,
                const int              outlineThickness=1,
                const sf::Color        &outlineColor=sf::Color(0,0,0,0))
{
    sf::RectangleShape element;

    sf::Vector2i outerSize(size.x/3, size.y/3);
    sf::Vector2i innerSize(outerSize.x - outlineThickness*2,
                           outerSize.y - outlineThickness*2);

    element.setSize(sf::Vector2f(innerSize.x,innerSize.y));
    element.setFillColor(fillColor);

    element.setOutlineThickness(outlineThickness);
    element.setOutlineColor(outlineColor);

    sf::Vector2i point(position);

    if (depth == 0){
        element.setSize(sf::Vector2f(size.x,size.y));
        element.setPosition(sf::Vector2f(position.x,position.y));
        window.draw(element);
        return;
    }

    for (int i=0; i<9; ++i)
    {
        if (i != 4){
            if (i!= 0 && !(i%3)){
                point.y += outerSize.x;
                point.x =  position.x;
            }

            element.setPosition(sf::Vector2f(point.x,point.y));

            if (depth == 1)
                window.draw(element);
            else{
                int thickness = outlineThickness > 1? outlineThickness/2 :
                                                      outlineThickness;
                drawFigure(window, point, outerSize, depth-1,
                           fillColor, thickness, outlineColor);
            }
         }
         point.x += outerSize.y;
    }
}

int main()
{
    sf::RenderWindow window(sf::VideoMode(800,600),"ReIGen", sf::Style::Titlebar|
                                                             sf::Style::Close);
    ImGui::SFML::Init(window);

    sf::Color bgColor(30,80,120);
    int uiWidth = 200;

    sf::Clock deltaClock;

    sf::Vector2i canvasCenter((window.getSize().x - uiWidth)/2,
                               window.getSize().y/2);
    sf::Vector2i figureSize(450,450);
    sf::Vector2i figurePosition(canvasCenter.x - figureSize.x/2,
                                canvasCenter.y - figureSize.y/2);

    const char* type[]{"Curve","Gasket"};
    int typeIndex = 1;

    const char* gasketSubType[]{"Sierpinski sieves","Sierpinski carpet"};
    int gasketSubTypeIndex = 1;

    int recDepth = 5;

    sf::Color fillColor{255,255,255,255};
    int imGui_fillColor[4]{fillColor.r,
                           fillColor.g,
                           fillColor.b,
                           fillColor.a};

    sf::Color outlineColor{0,0,0,255};
    int imGui_outlineColor[4]{outlineColor.r,
                              outlineColor.g,
                              outlineColor.b,
                              outlineColor.a};

    int outlineThickness{0};

    ImGuiStyle& style = ImGui::GetStyle();
    style.WindowPadding.x = 32;
    // style.ItemSpacing.y   = 0;

    while (window.isOpen())
    {
        sf::Event event;
        while (window.pollEvent(event))
        {
            ImGui::SFML::ProcessEvent(event);

            if (event.type == sf::Event::Closed)
                    window.close();
        }

        ImGui::SFML::Update(window, deltaClock.restart());

        ImGui::SetNextWindowPos(ImVec2(600,0));
        ImGui::SetNextWindowSize(ImVec2(uiWidth,600));

        ImGui::Begin("Settings", false, ImGuiWindowFlags_NoTitleBar|
                                        ImGuiWindowFlags_NoResize|
                                        ImGuiWindowFlags_NoMove|
                                        ImGuiWindowFlags_NoCollapse|
                                        ImGuiWindowFlags_ShowBorders);
        ImGui::Text("");
        ImGui::Text("Type");
        ImGui::Combo("##Type", &typeIndex, type,
                     IM_ARRAYSIZE(type));

        ImGui::Text("");
        ImGui::Text("Subtype");
        ImGui::Combo("##Subtype", &gasketSubTypeIndex, gasketSubType,
                     IM_ARRAYSIZE(gasketSubType));

        ImGui::Text("");
        ImGui::Separator();
        ImGui::Text("");

        ImGui::Text("Recursion depth");
        ImGui::SliderInt("##Recursion depth", &recDepth, 0, 5);
        ImGui::Text("");

        ImGui::Separator();

        ImGui::Text("");
        ImGui::Text("Fill Color");
        if(ImGui::DragInt4("##Fill Color", imGui_fillColor, 1, 0, 255)){
            fillColor.r = imGui_fillColor[0];
            fillColor.g = imGui_fillColor[1];
            fillColor.b = imGui_fillColor[2];
            fillColor.a = imGui_fillColor[3];
        }
        ImGui::Text("Outline Color");
        if(ImGui::DragInt4("##Outline Color", imGui_outlineColor, 1, 0, 255)){
            outlineColor.r = imGui_outlineColor[0];
            outlineColor.g = imGui_outlineColor[1];
            outlineColor.b = imGui_outlineColor[2];
            outlineColor.a = imGui_outlineColor[3];
        }

        ImGui::Text("");
        ImGui::Text("Outline Thickness");
        ImGui::SliderInt("##outline Thickness", &outlineThickness, -16, 16);

        ImGui::End();

        window.clear(bgColor);
        drawGrid(window);
        drawFigure(window, figurePosition, figureSize, recDepth,
                    fillColor, outlineThickness, outlineColor);
        // ImGui::ShowTestWindow();
        ImGui::Render();
        window.display();
    }

    ImGui::SFML::Shutdown();
    return 0;
}
<|endoftext|>


<commit_before>/*
The MIT License (MIT)

Copyright (c) 2014 Alex Palcuie

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/

#include <string>
#include <cassert>
#include <algorithm>
#include <cstdio>
#include <vector>
#include <stdexcept>

using std::string;
using std::to_string;
using std::reverse;
using std::vector;

class BigNumber {
  public:
    vector<char> integerPart, fractionaryPart;
    bool sign = 0;

    explicit BigNumber(int x) : BigNumber(to_string(x)) { }
    BigNumber(int integerPart, int fractionaryPart) :
        BigNumber(to_string(integerPart) + "." + to_string(fractionaryPart)) { }

    explicit BigNumber(string v) {
        int i = 0;
        if (v[i] == '-') {
            sign = 1;
            i++;
        }
        while (i < v.size()) {
            if (isdigit(v[i])) {
                integerPart.push_back(v[i]);
            } else {
                if (v[i] != '.')
                    throw std::runtime_error("NaN");
                break;
            }
            i++;
        }
        if (v[i] == '.') {
            i++;
            while (i < v.size()) {
                if (isdigit(v[i]))
                    fractionaryPart.push_back(v[i]);
                else
                    throw std::runtime_error("NaN");
                i++;
            }
        }
        reverse(integerPart.begin(), integerPart.end());
        if (fractionaryPart.size())
            reverse(fractionaryPart.begin(), fractionaryPart.end());
    }

    string toString() {
        string answer;
        if (sign)
            answer += "-";
        string x = string(integerPart.data(), integerPart.size());
        reverse(x.begin(), x.end());
        answer += x;
        if (fractionaryPart.size()) {
            answer += ".";
            string x = string(fractionaryPart.data(), fractionaryPart.size());
            reverse(x.begin(), x.end());
            answer += x;
        }
        return answer;
    }

    void plus_one() {
        int i = 0;
        while (integerPart[i] == '9' && integerPart.size() > i) {
            // printf("i = %d\n", i);
            integerPart[i] = '0';
            i++;
        }
        if (integerPart.size() == i)
            integerPart.push_back('1');
        else
            integerPart[i]++;
    }

    void add(BigNumber x) {
        bool carry = 0;
        std::tie(carry, fractionaryPart) = addTwoVectors(fractionaryPart,
                                                         x.fractionaryPart);
        if (carry)
            plus_one();
        std::tie(carry, integerPart) = addTwoVectors(integerPart,
                                                     x.integerPart);
        if (carry)
            integerPart.push_back('1');
    }

  private:
    const int BASE = 10;

    std::tuple<bool, vector<char>> addTwoVectors(vector<char> base,
                                                 vector<char> visitor) {
        // TODO(alex): change these reverses
        reverse(base.begin(), base.end());
        reverse(visitor.begin(), visitor.end());

        while (base.size() < visitor.size())
            base.push_back('0');
        while (visitor.size() < base.size())
            visitor.push_back('0');

        reverse(base.begin(), base.end());
        reverse(visitor.begin(), visitor.end());

        bool carry = 0;
        for (int i = 0; i < base.size(); i++) {
            base[i] += visitor[i] + carry - '0';
            if (base[i] > '9') {
                carry = 1;
                base[i] -= '9';
            } else {
                carry = 0;
            }
        }

        return make_tuple(carry, base);
    }
};

int main() {
    assert(BigNumber(6, 9).toString() == "6.9");
    assert(BigNumber(3).toString() == "3");
    assert(BigNumber(-5).toString() == "-5");

    vector<string> v = {"10", "10.3", "-10.555", "69.34433434", "0", "2"};

    for (int i = 0; i < v.size(); i++)
        assert(BigNumber(v[i]).toString() == v[i]);

    BigNumber nineteen = BigNumber(19);
    nineteen.plus_one();
    assert(nineteen.toString() == "20");

    BigNumber x = BigNumber(8);
    x.plus_one();
    assert(x.toString() == "9");
    x.plus_one();
    assert(x.toString() == "10");
    BigNumber y = BigNumber("10.6");
    y.plus_one();
    assert(y.toString() == "11.6");

    BigNumber ten = BigNumber("5.1");
    ten.add(BigNumber("3.2"));
    assert(ten.toString() == "8.3");

    return 0;
}
<commit_msg>Add more tests<commit_after>/*
The MIT License (MIT)

Copyright (c) 2014 Alex Palcuie

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/

#include <string>
#include <cassert>
#include <algorithm>
#include <cstdio>
#include <vector>
#include <stdexcept>

using std::string;
using std::to_string;
using std::reverse;
using std::vector;

class BigNumber {
  public:
    vector<char> integerPart, fractionaryPart;
    bool sign = 0;

    explicit BigNumber(int x) : BigNumber(to_string(x)) { }
    BigNumber(int integerPart, int fractionaryPart) :
        BigNumber(to_string(integerPart) + "." + to_string(fractionaryPart)) { }

    explicit BigNumber(string v) {
        int i = 0;
        if (v[i] == '-') {
            sign = 1;
            i++;
        }
        while (i < v.size()) {
            if (isdigit(v[i])) {
                integerPart.push_back(v[i]);
            } else {
                if (v[i] != '.')
                    throw std::runtime_error("NaN");
                break;
            }
            i++;
        }
        if (v[i] == '.') {
            i++;
            while (i < v.size()) {
                if (isdigit(v[i]))
                    fractionaryPart.push_back(v[i]);
                else
                    throw std::runtime_error("NaN");
                i++;
            }
        }
        reverse(integerPart.begin(), integerPart.end());
        if (fractionaryPart.size())
            reverse(fractionaryPart.begin(), fractionaryPart.end());
    }

    string toString() {
        string answer;
        if (sign)
            answer += "-";
        string x = string(integerPart.data(), integerPart.size());
        reverse(x.begin(), x.end());
        answer += x;
        if (fractionaryPart.size()) {
            answer += ".";
            string x = string(fractionaryPart.data(), fractionaryPart.size());
            reverse(x.begin(), x.end());
            answer += x;
        }
        return answer;
    }

    void plus_one() {
        int i = 0;
        while (integerPart[i] == '9' && integerPart.size() > i) {
            // printf("i = %d\n", i);
            integerPart[i] = '0';
            i++;
        }
        if (integerPart.size() == i)
            integerPart.push_back('1');
        else
            integerPart[i]++;
    }

    void add(BigNumber x) {
        bool carry = 0;
        std::tie(carry, fractionaryPart) = addTwoVectors(fractionaryPart,
                                                         x.fractionaryPart);
        if (carry)
            plus_one();
        std::tie(carry, integerPart) = addTwoVectors(integerPart,
                                                     x.integerPart);
        if (carry)
            integerPart.push_back('1');
    }

  private:
    const int BASE = 10;

    std::tuple<bool, vector<char>> addTwoVectors(vector<char> base,
                                                 vector<char> visitor) {
        // TODO(alex): change these reverses
        reverse(base.begin(), base.end());
        reverse(visitor.begin(), visitor.end());

        while (base.size() < visitor.size())
            base.push_back('0');
        while (visitor.size() < base.size())
            visitor.push_back('0');

        reverse(base.begin(), base.end());
        reverse(visitor.begin(), visitor.end());

        bool carry = 0;
        for (int i = 0; i < base.size(); i++) {
            base[i] += visitor[i] + carry - '0';
            if (base[i] > '9') {
                carry = 1;
                base[i] -= '9';
            } else {
                carry = 0;
            }
        }

        return make_tuple(carry, base);
    }
};

int main() {
    assert(BigNumber(6, 9).toString() == "6.9");
    assert(BigNumber(3).toString() == "3");
    assert(BigNumber(-5).toString() == "-5");

    vector<string> v = {"10", "10.3", "-10.555", "69.34433434", "0", "2"};

    for (int i = 0; i < v.size(); i++)
        assert(BigNumber(v[i]).toString() == v[i]);

    BigNumber nineteen = BigNumber(19);
    nineteen.plus_one();
    assert(nineteen.toString() == "20");

    BigNumber x = BigNumber(8);
    x.plus_one();
    assert(x.toString() == "9");
    x.plus_one();
    assert(x.toString() == "10");
    BigNumber y = BigNumber("10.6");
    y.plus_one();
    assert(y.toString() == "11.6");

    BigNumber ten = BigNumber("5.1");
    ten.add(BigNumber("3.2"));
    assert(ten.toString() == "8.3");
    ten.add(BigNumber("1.12"));
    assert(ten.toString() == "9.42");
    ten.add(BigNumber("0.1"));
    assert(ten.toString() == "9.52");
    ten.add(BigNumber("0.000001"));
    assert(ten.toString() == "9.520001");

    return 0;
}
<|endoftext|>


<commit_before>#include <zmq.hpp>
#include <string>
#include <iostream>

int main(int argc, char* argv[]) {
	if (argc != 3) {
		std::cout << "ERROR: Usage <server> <token>." << std::endl;
		return 0;
	}
	// Connects to and authenticates with gameserver
	std::string server = std::string(argv[1]) + ":5557";
	std::string matchToken (argv[2]);
	zmq::context_t context(1);
	zmq::socket_t socket(context, ZMQ_REQ);
	socket.connect(server.c_str());
	zmq::message_t request (matchToken.size()+1);
	memcpy((void*)request.data(), matchToken.c_str(), matchToken.size());
	socket.send(request);

	zmq::message_t reply;
	socket.recv(&reply);
	std::cout << reply.data() << std::endl;

	return 0;
}

<commit_msg>Added logging info<commit_after>#include <zmq.hpp>
#include <string>
#include <iostream>

int main(int argc, char* argv[]) {
	if (argc != 3) {
		std::cout << "ERROR: Usage <server> <token>." << std::endl;
		return 0;
	}
	// Connects to and authenticates with gameserver
	std::string server = std::string(argv[1]) + ":5557";
	std::string matchToken (argv[2]);
	zmq::context_t context(1);
	zmq::socket_t socket(context, ZMQ_REQ);
	std::cout << "Connecting to server " << server << std::endl;
	socket.connect(server.c_str());
	std::cout << "Sending token " << matchToken << std::endl;
	zmq::message_t request (matchToken.size()+1);
	memcpy((void*)request.data(), matchToken.c_str(), matchToken.size());
	socket.send(request);

	std::cout << "Waiting for reply." << std::endl;
	zmq::message_t reply;
	socket.recv(&reply);
	std::cout << reply.data() << std::endl;

	return 0;
}

<|endoftext|>


<commit_before>e007fa8f-4b02-11e5-91a9-28cfe9171a43<commit_msg>my cat is cute<commit_after>e016c640-4b02-11e5-b9e9-28cfe9171a43<|endoftext|>


<commit_before>#include <iostream>
#include <SFML/Graphics.hpp>
#include <SFML/Audio.hpp>

int main()
{
    sf::RenderWindow App(sf::VideoMode(800, 600, 32), "Hello World - SFML");
    sf::SoundBuffer kickBuffer, snareBuffer, hihatBuffer;

    if (!kickBuffer.loadFromFile("data/kick.wav")) {
        std::cout << "[ERROR] Cannot load data/kick.wav" << std::endl;
        return 1;
    }

    if (!snareBuffer.loadFromFile("data/snare.wav")) {
        std::cout << "[ERROR] Cannot load data/snare.wav" << std::endl;
         return 1;
    }

    if (!hihatBuffer.loadFromFile("data/hihat.wav")) {
        std::cout << "[ERROR] Cannot load data/hihat.wav" << std::endl;
        return 1;
    }

    sf::Sound kickSound, snareSound , hihatSound;
    kickSound.setBuffer(kickBuffer);
    snareSound.setBuffer(snareBuffer);
    hihatSound.setBuffer(hihatBuffer);

    sf::CircleShape circle(50);
    circle.setFillColor(sf::Color(0, 200, 0));
    circle.setPosition(200, 200);

    while (App.isOpen())
    {
        sf::Event Event;
        while (App.pollEvent(Event))
        {
            if (Event.type == sf::Event::Closed) {
                App.close();
            } else if (Event.type == sf::Event::JoystickButtonPressed) {
                std::cout << "JoystickButtonEvent: " << Event.joystickButton.button << std::endl;

                switch (Event.joystickButton.button) {
                case 0:
                    kickSound.play();
                    break;

                case 1:
                    snareSound.play();
                    break;

                case 4:
                    hihatSound.play();
                    break;

                default: {}
                }
            }
        }

        App.clear(sf::Color(0, 0, 0));
        App.draw(circle);
        App.display();
    }

    return 0;
}
<commit_msg>Implemented simple transition.<commit_after>#include <istream>
#include <ostream>
#include <iostream>
#include <vector>
#include <SFML/Graphics.hpp>
#include <SFML/Audio.hpp>

struct State {
    float x, y, radius, r, g, b, a;

    State(float x, float y, float radius,
          float r, float g, float b, float a):
        x(x), y(y), radius(radius),
        r(r), g(g), b(b), a(a)
    {}
};

State operator+(const State &s1,
                const State &s2)
{
    return State(s1.x + s2.x,
                 s1.y + s2.y,
                 s1.radius + s2.radius,
                 s1.r + s2.r,
                 s1.g + s2.g,
                 s1.b + s2.b,
                 s1.a + s2.a);
}

State operator-(const State &s1,
                const State &s2)
{
    return State(s1.x - s2.x,
                 s1.y - s2.y,
                 s1.radius - s2.radius,
                 s1.r - s2.r,
                 s1.g - s2.g,
                 s1.b - s2.b,
                 s1.a - s2.a);
}

State operator*(const State &state, const float factor)
{
    return State(state.x * factor,
                 state.y * factor,
                 state.radius * factor,
                 state.r * factor,
                 state.g * factor,
                 state.b * factor,
                 state.a * factor);
}

sf::CircleShape stateToCircle(const State &state)
{
    sf::CircleShape circle(state.radius);
    circle.setFillColor(sf::Color(state.r, state.g, state.b, state.a));
    circle.setPosition(state.x - state.radius / 2.0f, state.y - state.radius / 2.0f);
    return circle;
}

std::ostream &operator<<(std::ostream &os, const State &state)
{
    os << "("
       << state.x << ", "
       << state.y << ", "
       << state.radius << ", "
       << state.r << ", "
       << state.g << ", "
       << state.b << ", "
       << state.a
       << ")";
    return os;
}

struct Transition
{
public:
    Transition(const State &initialState,
               sf::Int32 transitionTime,
               const State &finalState):
        currentState(initialState),
        timeLeft(transitionTime),
        finalState(finalState)
    {}

    State nextState(const sf::Int32 deltaTime)
    {
        std::cout << timeLeft << std::endl;
        if (deltaTime < timeLeft) {
            State deltaState = (finalState - currentState) * ((deltaTime + .0) / timeLeft);

            currentState = currentState + deltaState;
        } else {
            currentState = finalState;
        }

        timeLeft -= deltaTime;
        return currentState;
    }

    bool isFinished() const
    {
        return timeLeft <= 0.0f;
    }

    sf::Int32 getTimeLeft() const
    {
        return timeLeft;
    }

private:
    State currentState;
    sf::Int32 timeLeft;
    const State finalState;
};

int main()
{
    sf::RenderWindow App(sf::VideoMode(800, 600, 32), "Hello World - SFML");
    sf::SoundBuffer kickBuffer, snareBuffer, hihatBuffer;

    if (!kickBuffer.loadFromFile("data/kick.wav")) {
        std::cout << "[ERROR] Cannot load data/kick.wav" << std::endl;
        return 1;
    }

    if (!snareBuffer.loadFromFile("data/snare.wav")) {
        std::cout << "[ERROR] Cannot load data/snare.wav" << std::endl;
         return 1;
    }

    if (!hihatBuffer.loadFromFile("data/hihat.wav")) {
        std::cout << "[ERROR] Cannot load data/hihat.wav" << std::endl;
        return 1;
    }

    sf::Sound kickSound, snareSound , hihatSound;
    kickSound.setBuffer(kickBuffer);
    snareSound.setBuffer(snareBuffer);
    hihatSound.setBuffer(hihatBuffer);

    const State normalState(200.0f, 200.0f, 50.0f, 255.0f, 255.0f, 255.0f, 255.0f);
    Transition *transition = NULL;
    State state(200.0f, 200.0f, 50.0f, 255.0f, 255.0f, 255.0f, 255.0f);
    sf::Clock clock;

    while (App.isOpen())
    {
        // std::cout << state << std::endl;
        clock.restart();
        sf::Event Event;
        while (App.pollEvent(Event))
        {
            if (Event.type == sf::Event::Closed) {
                App.close();
            } else if (Event.type == sf::Event::JoystickButtonPressed) {
                // std::cout << "JoystickButtonEvent: " << Event.joystickButton.button << std::endl;

                switch (Event.joystickButton.button) {
                case 0:
                    state.radius = 70.0f;
                    state.r = 255.0f;
                    state.g = 0.0f;
                    state.b = 0.0f;

                    if (transition != NULL) {
                        delete transition;
                    }
                    transition = new Transition(state, 300, normalState);

                    kickSound.play();
                    break;

                case 1:
                    snareSound.play();
                    break;

                case 4:
                    hihatSound.play();
                    break;

                default: {}
                }
            }
        }

        App.clear(sf::Color(0, 0, 0));

        if (transition != NULL) {
            state = transition->nextState(clock.getElapsedTime().asMilliseconds());

            if (transition->isFinished()) {
                delete transition;
                transition = NULL;
            }
        }
        App.draw(stateToCircle(state));

        App.display();
    }

    return 0;
}
<|endoftext|>