<commit_before>#include <iostream>
#include <unordered_map>
#include <tuple>
#include <exception>
#include <vector>

namespace TM
{

enum SHIFT {
    LEFT = -1,
    RIGHT = 1,
    HOLD = 0
};

bool operator==(const std::tuple<int, char> &a,
                const std::tuple<int, char> &b)
{
    return std::get<0>(a) == std::get<0>(b) &&
           std::get<1>(a) == std::get<1>(b);
}

struct tuple_hash : public std::unary_function<std::tuple<int, char>,
                                               std::size_t>
{
    const int MOD = 666013;

    std::size_t operator()(const std::tuple<int, char> &k) const
    {
        return (std::get<0>(k) + std::get<1>(k)) % MOD;
    }
};

class MultipleValuesMappedToKey : public std::exception
{
private:
    virtual const char *what() const throw()
    {
        return "Cannot map multiple values to a key in an unordered_map";
    }
};

class KeyNotFound : public std::exception
{
private:
    virtual const char *what() const throw()
    {
        return "Key not found. Maybe first test using contains?";
    }
};

class TMTransition
{
public:
    typedef std::tuple<int, char> key_type;
    typedef std::tuple<int, char, SHIFT> value_type;

    void emplace(const key_type &k, const value_type &v) throw()
    {
        if (delta_.count(k))
            throw new MultipleValuesMappedToKey();

        delta_.emplace(k, v);
    }

    value_type get(const key_type &k) const
    {
        if (!delta_.count(k))
            throw new KeyNotFound();

        return delta_.find(k)->second;
    }

    bool contains(const key_type &k) const
    {
        return delta_.count(k);
    }

private:
    std::unordered_map<key_type, value_type, tuple_hash> delta_;
};

class TMConfiguration
{
public:
    TMConfiguration()
        : statesNr_(0)
    {
    }

    void addTransition(int state_in, char sym_in, int state_af,
                       char sym_af, SHIFT shift ) throw()
    {
        addTransition(std::make_tuple(state_in, sym_in),
                      std::make_tuple(state_af, sym_af, shift));

        // Educated guess. May change in the future - machines with multiple
        // final states.
        if (statesNr_ < state_in || statesNr_ < state_af)
            statesNr_ = std::max(state_af, state_in);
    }

    bool is_final(int state) const
    {
        return state >= statesNr_;
    }

    bool is_undefined(int state, char sym) const
    {
        return !delta_.contains(std::make_tuple(state, sym));
    }

    TMTransition::value_type getValue(int state, char sym) const
    {
        return delta_.get(std::make_tuple(state, sym));
    }

private:
    void addTransition(const TMTransition::key_type &k,
                       const TMTransition::value_type &v)
    {
        delta_.emplace(k, v);
    }

    TMTransition delta_;
    int statesNr_;
};

class TMRuntime
{
public:
    TMRuntime(const TMConfiguration &conf)
        : conf_(conf)
    {
    }

    std::string run(std::string tape) throw()
    {
        int tape_head = 1;
        int current_state = 0;

        while (!conf_.is_final(current_state)) {
#ifdef VERBOSE
            print(current_state, tape_head, tape);
#endif

            int curr_sym = static_cast<int>(tape[tape_head]);
            TMTransition::value_type val = conf_.getValue(current_state,
                                                          curr_sym);

            tape[tape_head] = std::get<1>(val);
            tape_head += std::get<2>(val);
            current_state = std::get<0>(val);
        }

#ifdef VERBOSE
        print(current_state, tape_head, tape);
#endif
        return tape;
    }

private:
    void print(int current_state, int tape_head,
               const std::string &current_tape)
    {
        std::string head_str(current_tape.size(), ' ');
        head_str[tape_head] = '^';

        if (conf_.is_final(current_state))
            std::cout << "Final state: ";
        else
            std::cout << "Current State: ";

        std::cout << current_state << std::endl;
        std::cout << current_tape << std::endl;
        std::cout << head_str;

        std::cout << std::endl;
    }

    TMConfiguration conf_;
};

#define TEST_OUTPUT(testNr, expected, actual)\
{\
    if (expected == actual)\
        std::cout << "Test " << testNr << " succeded" << std::endl;\
    else\
        std::cout << "Test " << testNr << " failed: "\
                  << "Expected: " << expected << "; "\
                  << "Actual: " << actual << std::endl;\
}

namespace unittest
{

class UnitTest
{
public:
    void runTest()
    {
        std::cout << "Running " << name() << std::endl;

        init();
        TMRuntime *tm_runtime = new TMRuntime(tmConf_);

        auto inouts = getInOuts();
        for (auto it = inouts.cbegin(); it != inouts.cend(); ++it)
            TEST_OUTPUT(it - inouts.cbegin() + 1, it->second,
                        tm_runtime->run(it->first))

        std::cout << std::endl;
        delete tm_runtime;
    }

protected:
    TMConfiguration tmConf_;

private:
    virtual const char *name() = 0;
    virtual void init() = 0;
    virtual std::vector<std::pair<std::string, std::string>> getInOuts() = 0;
};

}

}

using namespace TM;

class IncrementTest : public ::unittest::UnitTest
{
private:
    const char *name() override
    {
        return "IncrementTest";
    }

    void init() override
    {
        tmConf_.addTransition(0, '0', 0, '0', RIGHT);
        tmConf_.addTransition(0, '1', 0, '1', RIGHT);
        tmConf_.addTransition(0, '#', 1, '#', LEFT);
        tmConf_.addTransition(1, '0', 2, '1', LEFT);
        tmConf_.addTransition(1, '1', 1, '0', LEFT);
        tmConf_.addTransition(2, '0', 2, '0', LEFT);
        tmConf_.addTransition(2, '1', 2, '1', LEFT);
        tmConf_.addTransition(2, '>', 3, '>', HOLD);
    }

    std::vector<std::pair<std::string, std::string>> getInOuts() override
    {
        std::vector<std::pair<std::string, std::string>> ret;
        ret.emplace_back(">0001#", ">0010#");
        ret.emplace_back(">00010#", ">00011#");

        return ret;
    }
};

class PalindromeTest : public ::unittest::UnitTest
{
private:
    const char *name() override
    {
        return "PalindromeTest";
    }

    void init() override
    {
        // TODO
    }

    std::vector<std::pair<std::string, std::string>> getInOuts() override
    {
        std::vector<std::pair<std::string, std::string>> ret;
        // TODO

        return ret;
    }
};

// TODO
class MatrixTest : public ::unittest::UnitTest
{
    const char *name() override
    {
        return "MatrixTest";
    }

    void init() override
    {
        // TODO
    }

    std::vector<std::pair<std::string, std::string>> getInOuts() override
    {
        std::vector<std::pair<std::string, std::string>> ret;
        // TODO

        return ret;
    }
};

// TODO
class AnagramsTest : public ::unittest::UnitTest
{
    const char *name() override
    {
        return "AnagramsTest";
    }

    void init() override
    {
        // TODO
    }

    std::vector<std::pair<std::string, std::string>> getInOuts() override
    {
        std::vector<std::pair<std::string, std::string>> ret;
        // TODO

        return ret;
    }
};

// TODO
class CountZerosTest : public ::unittest::UnitTest
{
    const char *name() override
    {
        return "CountZerosTest";
    }

    void init() override
    {
        // TODO
    }

    std::vector<std::pair<std::string, std::string>> getInOuts() override
    {
        std::vector<std::pair<std::string, std::string>> ret;
        // TODO

        return ret;
    }
};

int main()
{
    unittest::UnitTest *test1 = new IncrementTest();
    unittest::UnitTest *test2 = new PalindromeTest();
    unittest::UnitTest *test3 = new MatrixTest();
    unittest::UnitTest *test4 = new AnagramsTest();
    unittest::UnitTest *test5 = new CountZerosTest();

    test1->runTest();
    test2->runTest();
    test3->runTest();
    test4->runTest();
    test5->runTest();

    return 0;
}
<commit_msg>Add move constructors optimizations<commit_after>#include <iostream>
#include <unordered_map>
#include <tuple>
#include <exception>
#include <vector>

namespace TM
{

enum SHIFT {
    LEFT = -1,
    RIGHT = 1,
    HOLD = 0
};

bool operator==(const std::tuple<int, char> &a,
                const std::tuple<int, char> &b)
{
    return std::get<0>(a) == std::get<0>(b) &&
           std::get<1>(a) == std::get<1>(b);
}

struct tuple_hash : public std::unary_function<std::tuple<int, char>,
                                               std::size_t>
{
    const int MOD = 666013;

    std::size_t operator()(const std::tuple<int, char> &k) const
    {
        return (std::get<0>(k) + std::get<1>(k)) % MOD;
    }
};

class MultipleValuesMappedToKey : public std::exception
{
private:
    virtual const char *what() const throw()
    {
        return "Cannot map multiple values to a key in an unordered_map";
    }
};

class KeyNotFound : public std::exception
{
private:
    virtual const char *what() const throw()
    {
        return "Key not found. Maybe first test using contains?";
    }
};

class TMTransition
{
public:
    typedef std::tuple<int, char> key_type;
    typedef std::tuple<int, char, SHIFT> value_type;

    void emplace(const key_type &k, const value_type &v) throw()
    {
        if (delta_.count(k))
            throw new MultipleValuesMappedToKey();

        delta_.emplace(k, v);
    }

    void emplace(key_type &&k, value_type &&v) throw()
    {
        if (delta_.count(k))
            throw new MultipleValuesMappedToKey();

        delta_.emplace(std::move(k), std::move(v));
    }

    value_type get(const key_type &k) const
    {
        if (!delta_.count(k))
            throw new KeyNotFound();

        return delta_.find(k)->second;
    }

    bool contains(const key_type &k) const
    {
        return delta_.count(k);
    }

private:
    std::unordered_map<key_type, value_type, tuple_hash> delta_;
};

class TMConfiguration
{
public:
    TMConfiguration()
        : statesNr_(0)
    {
    }

    void addTransition(int state_in, char sym_in, int state_af,
                       char sym_af, SHIFT shift ) throw()
    {
        addTransition(std::make_tuple(state_in, sym_in),
                      std::make_tuple(state_af, sym_af, shift));

        // Educated guess. May change in the future - machines with multiple
        // final states.
        if (statesNr_ < state_in || statesNr_ < state_af)
            statesNr_ = std::max(state_af, state_in);
    }

    bool is_final(int state) const
    {
        return state >= statesNr_;
    }

    bool is_undefined(int state, char sym) const
    {
        return !delta_.contains(std::make_tuple(state, sym));
    }

    TMTransition::value_type getValue(int state, char sym) const
    {
        return delta_.get(std::make_tuple(state, sym));
    }

private:
    void addTransition(const TMTransition::key_type &k,
                       const TMTransition::value_type &v)
    {
        delta_.emplace(k, v);
    }

    void addTransition(TMTransition::key_type &&k,
                       TMTransition::value_type &&v)
    {
        delta_.emplace(std::move(k), std::move(v));
    }

    TMTransition delta_;
    int statesNr_;
};

class TMRuntime
{
public:
    TMRuntime(const TMConfiguration &conf)
        : conf_(conf)
    {
    }

    std::string run(std::string tape) throw()
    {
        int tape_head = 1;
        int current_state = 0;

        while (!conf_.is_final(current_state)) {
#ifdef VERBOSE
            print(current_state, tape_head, tape);
#endif

            int curr_sym = static_cast<int>(tape[tape_head]);
            TMTransition::value_type val = conf_.getValue(current_state,
                                                          curr_sym);

            tape[tape_head] = std::get<1>(val);
            tape_head += std::get<2>(val);
            current_state = std::get<0>(val);
        }

#ifdef VERBOSE
        print(current_state, tape_head, tape);
#endif
        return tape;
    }

private:
    void print(int current_state, int tape_head,
               const std::string &current_tape)
    {
        std::string head_str(current_tape.size(), ' ');
        head_str[tape_head] = '^';

        if (conf_.is_final(current_state))
            std::cout << "Final state: ";
        else
            std::cout << "Current State: ";

        std::cout << current_state << std::endl;
        std::cout << current_tape << std::endl;
        std::cout << head_str;

        std::cout << std::endl;
    }

    TMConfiguration conf_;
};

#define TEST_OUTPUT(testNr, expected, actual)\
{\
    if (expected == actual)\
        std::cout << "Test " << testNr << " succeded" << std::endl;\
    else\
        std::cout << "Test " << testNr << " failed: "\
                  << "Expected: " << expected << "; "\
                  << "Actual: " << actual << std::endl;\
}

namespace unittest
{

class UnitTest
{
public:
    void runTest()
    {
        std::cout << "Running " << name() << std::endl;

        init();
        TMRuntime *tm_runtime = new TMRuntime(tmConf_);

        auto inouts = getInOuts();
        for (auto it = inouts.cbegin(); it != inouts.cend(); ++it)
            TEST_OUTPUT(it - inouts.cbegin() + 1, it->second,
                        tm_runtime->run(it->first))

        std::cout << std::endl;
        delete tm_runtime;
    }

protected:
    TMConfiguration tmConf_;

private:
    virtual const char *name() = 0;
    virtual void init() = 0;
    virtual std::vector<std::pair<std::string, std::string>> getInOuts() = 0;
};

}

}

using namespace TM;

class IncrementTest : public ::unittest::UnitTest
{
private:
    const char *name() override
    {
        return "IncrementTest";
    }

    void init() override
    {
        tmConf_.addTransition(0, '0', 0, '0', RIGHT);
        tmConf_.addTransition(0, '1', 0, '1', RIGHT);
        tmConf_.addTransition(0, '#', 1, '#', LEFT);
        tmConf_.addTransition(1, '0', 2, '1', LEFT);
        tmConf_.addTransition(1, '1', 1, '0', LEFT);
        tmConf_.addTransition(2, '0', 2, '0', LEFT);
        tmConf_.addTransition(2, '1', 2, '1', LEFT);
        tmConf_.addTransition(2, '>', 3, '>', HOLD);
    }

    std::vector<std::pair<std::string, std::string>> getInOuts() override
    {
        std::vector<std::pair<std::string, std::string>> ret;
        ret.emplace_back(">0001#", ">0010#");
        ret.emplace_back(">00010#", ">00011#");

        return ret;
    }
};

class PalindromeTest : public ::unittest::UnitTest
{
private:
    const char *name() override
    {
        return "PalindromeTest";
    }

    void init() override
    {
        // TODO
    }

    std::vector<std::pair<std::string, std::string>> getInOuts() override
    {
        std::vector<std::pair<std::string, std::string>> ret;
        // TODO

        return ret;
    }
};

// TODO
class MatrixTest : public ::unittest::UnitTest
{
    const char *name() override
    {
        return "MatrixTest";
    }

    void init() override
    {
        // TODO
    }

    std::vector<std::pair<std::string, std::string>> getInOuts() override
    {
        std::vector<std::pair<std::string, std::string>> ret;
        // TODO

        return ret;
    }
};

// TODO
class AnagramsTest : public ::unittest::UnitTest
{
    const char *name() override
    {
        return "AnagramsTest";
    }

    void init() override
    {
        // TODO
    }

    std::vector<std::pair<std::string, std::string>> getInOuts() override
    {
        std::vector<std::pair<std::string, std::string>> ret;
        // TODO

        return ret;
    }
};

// TODO
class CountZerosTest : public ::unittest::UnitTest
{
    const char *name() override
    {
        return "CountZerosTest";
    }

    void init() override
    {
        // TODO
    }

    std::vector<std::pair<std::string, std::string>> getInOuts() override
    {
        std::vector<std::pair<std::string, std::string>> ret;
        // TODO

        return ret;
    }
};

int main()
{
    unittest::UnitTest *test1 = new IncrementTest();
    unittest::UnitTest *test2 = new PalindromeTest();
    unittest::UnitTest *test3 = new MatrixTest();
    unittest::UnitTest *test4 = new AnagramsTest();
    unittest::UnitTest *test5 = new CountZerosTest();

    test1->runTest();
    test2->runTest();
    test3->runTest();
    test4->runTest();
    test5->runTest();

    return 0;
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: animobjs.hxx,v $
 *
 *  $Revision: 1.5 $
 *
 *  last change: $Author: obo $ $Date: 2004-01-20 11:47:42 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#ifndef SD_ANIMOBJS_HXX
#define SD_ANIMOBJS_HXX

#ifndef _SFXDOCKWIN_HXX //autogen
#include <sfx2/dockwin.hxx>
#endif
#ifndef _SV_FIXED_HXX //autogen
#include <vcl/fixed.hxx>
#endif
#ifndef _STDCTRL_HXX //autogen
#include <svtools/stdctrl.hxx>
#endif
#ifndef _SV_GROUP_HXX //autogen
#include <vcl/group.hxx>
#endif
#ifndef _SFXCTRLITEM_HXX //autogen
#include <sfx2/ctrlitem.hxx>
#endif

#ifndef _SV_BUTTON_HXX //autogen
#include <vcl/button.hxx>
#endif

#ifndef _SV_FIELD_HXX //autogen
#include <vcl/field.hxx>
#endif

#ifndef _SVX_DLG_CTRL_HXX //autogen
#include <svx/dlgctrl.hxx>
#endif
#ifndef _SFX_PROGRESS_HXX
#include <sfx2/progress.hxx>
#endif

#ifndef _SV_LSTBOX_HXX //autogen
#include <vcl/lstbox.hxx>
#endif

#ifndef _SD_SDRESID_HXX
#include "sdresid.hxx"
#endif

class SdDrawDocument;
class BitmapEx;

namespace sd {

class View;

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

enum BitmapAdjustment
{
    BA_LEFT_UP,
    BA_LEFT,
    BA_LEFT_DOWN,
    BA_UP,
    BA_CENTER,
    BA_DOWN,
    BA_RIGHT_UP,
    BA_RIGHT,
    BA_RIGHT_DOWN
};

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

class SdDisplay : public Control
{
private:
    BitmapEx    aBitmapEx;
    Fraction    aScale;

public:
    SdDisplay( ::Window* pWin, SdResId Id );
    ~SdDisplay();

    virtual void Paint( const Rectangle& rRect );

    void    SetBitmapEx( BitmapEx* pBmpEx );
    void    SetScale( const Fraction& rFrac );

    virtual void DataChanged( const DataChangedEvent& rDCEvt );
};

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

class AnimationWindow : public SfxDockingWindow
{
 friend class AnimationChildWindow;
 friend class AnimationControllerItem;

public:
    AnimationWindow( SfxBindings* pBindings, SfxChildWindow *pCW,
        ::Window* pParent, const SdResId& rSdResId );
    virtual ~AnimationWindow();

    void    AddObj( ::sd::View& rView );
    void    CreateAnimObj( ::sd::View& rView );

    virtual void DataChanged( const DataChangedEvent& rDCEvt );

protected:
    virtual BOOL    Close();
    virtual void    Resize();
    virtual void    FillInfo( SfxChildWinInfo& ) const;

private:
    SdDisplay       aCtlDisplay;
    ImageButton     aBtnFirst;
    ImageButton     aBtnReverse;
    ImageButton     aBtnStop;
    ImageButton     aBtnPlay;
    ImageButton     aBtnLast;
    NumericField    aNumFldBitmap;
    TimeField       aTimeField;
    ListBox         aLbLoopCount;

    ImageButton     aBtnGetOneObject;
    ImageButton     aBtnGetAllObjects;
    ImageButton     aBtnRemoveBitmap;
    ImageButton     aBtnRemoveAll;
    FixedText       aFtCount;
    FixedInfo       aFiCount;
    FixedLine       aGrpBitmap;

    RadioButton     aRbtGroup;
    RadioButton     aRbtBitmap;
    FixedText       aFtAdjustment;
    ListBox         aLbAdjustment;
    PushButton      aBtnCreateGroup;
    FixedLine       aGrpAnimation;

    ::Window*       pWin;
    List            aBmpExList;
    List            aTimeList;
    SdDrawDocument* pMyDoc;
    BitmapEx*       pBitmapEx;

    Size            aSize;
    Size            aFltWinSize;
    Size            aDisplaySize;
    Size            aBmpSize;
    BOOL            bMovie;
    BOOL            bAllObjects;

    SfxBindings*                pBindings;
    AnimationControllerItem*    pControllerItem;

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

    DECL_LINK( ClickFirstHdl, void * );
    DECL_LINK( ClickStopHdl, void * );
    DECL_LINK( ClickPlayHdl, void * );
    DECL_LINK( ClickLastHdl, void * );
    DECL_LINK( ClickGetObjectHdl, void * );
    DECL_LINK( ClickRemoveBitmapHdl, void * );
    DECL_LINK( ClickRbtHdl, void * );
    DECL_LINK( ClickCreateGroupHdl, void * );
    DECL_LINK( ModifyBitmapHdl, void * );
    DECL_LINK( ModifyTimeHdl, void * );

    void            UpdateControl( ULONG nPos, BOOL bDisableCtrls = FALSE );
    void            ResetAttrs();
    void            WaitInEffect( ULONG nMilliSeconds ) const;
    void            WaitInEffect( ULONG nMilliSeconds, ULONG nTime,
                                        SfxProgress* pStbMgr ) const;
    Fraction        GetScale();
};

/*************************************************************************
|*
|* ControllerItem fuer Animator
|*
\************************************************************************/

class AnimationControllerItem : public SfxControllerItem
{

public:
    AnimationControllerItem( USHORT, AnimationWindow*, SfxBindings* );

protected:
    virtual void StateChanged( USHORT nSId, SfxItemState eState,
        const SfxPoolItem* pState );
private:
    AnimationWindow* pAnimationWin;
};

} // end of namespace sd

#endif

<commit_msg>INTEGRATION: CWS gcc4fwdecl (1.5.480); FILE MERGED 2005/06/01 17:19:56 pmladek 1.5.480.1: #i50069# Fixed forward declarations for gcc4 in sd<commit_after>/*************************************************************************
 *
 *  $RCSfile: animobjs.hxx,v $
 *
 *  $Revision: 1.6 $
 *
 *  last change: $Author: obo $ $Date: 2005-06-14 16:23:40 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#ifndef SD_ANIMOBJS_HXX
#define SD_ANIMOBJS_HXX

#ifndef _SFXDOCKWIN_HXX //autogen
#include <sfx2/dockwin.hxx>
#endif
#ifndef _SV_FIXED_HXX //autogen
#include <vcl/fixed.hxx>
#endif
#ifndef _STDCTRL_HXX //autogen
#include <svtools/stdctrl.hxx>
#endif
#ifndef _SV_GROUP_HXX //autogen
#include <vcl/group.hxx>
#endif
#ifndef _SFXCTRLITEM_HXX //autogen
#include <sfx2/ctrlitem.hxx>
#endif

#ifndef _SV_BUTTON_HXX //autogen
#include <vcl/button.hxx>
#endif

#ifndef _SV_FIELD_HXX //autogen
#include <vcl/field.hxx>
#endif

#ifndef _SVX_DLG_CTRL_HXX //autogen
#include <svx/dlgctrl.hxx>
#endif
#ifndef _SFX_PROGRESS_HXX
#include <sfx2/progress.hxx>
#endif

#ifndef _SV_LSTBOX_HXX //autogen
#include <vcl/lstbox.hxx>
#endif

#ifndef _SD_SDRESID_HXX
#include "sdresid.hxx"
#endif

class SdDrawDocument;
class BitmapEx;

namespace sd {

class AnimationControllerItem;
class View;

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

enum BitmapAdjustment
{
    BA_LEFT_UP,
    BA_LEFT,
    BA_LEFT_DOWN,
    BA_UP,
    BA_CENTER,
    BA_DOWN,
    BA_RIGHT_UP,
    BA_RIGHT,
    BA_RIGHT_DOWN
};

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

class SdDisplay : public Control
{
private:
    BitmapEx    aBitmapEx;
    Fraction    aScale;

public:
    SdDisplay( ::Window* pWin, SdResId Id );
    ~SdDisplay();

    virtual void Paint( const Rectangle& rRect );

    void    SetBitmapEx( BitmapEx* pBmpEx );
    void    SetScale( const Fraction& rFrac );

    virtual void DataChanged( const DataChangedEvent& rDCEvt );
};

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

class AnimationWindow : public SfxDockingWindow
{
 friend class AnimationChildWindow;
 friend class AnimationControllerItem;

public:
    AnimationWindow( SfxBindings* pBindings, SfxChildWindow *pCW,
        ::Window* pParent, const SdResId& rSdResId );
    virtual ~AnimationWindow();

    void    AddObj( ::sd::View& rView );
    void    CreateAnimObj( ::sd::View& rView );

    virtual void DataChanged( const DataChangedEvent& rDCEvt );

protected:
    virtual BOOL    Close();
    virtual void    Resize();
    virtual void    FillInfo( SfxChildWinInfo& ) const;

private:
    SdDisplay       aCtlDisplay;
    ImageButton     aBtnFirst;
    ImageButton     aBtnReverse;
    ImageButton     aBtnStop;
    ImageButton     aBtnPlay;
    ImageButton     aBtnLast;
    NumericField    aNumFldBitmap;
    TimeField       aTimeField;
    ListBox         aLbLoopCount;

    ImageButton     aBtnGetOneObject;
    ImageButton     aBtnGetAllObjects;
    ImageButton     aBtnRemoveBitmap;
    ImageButton     aBtnRemoveAll;
    FixedText       aFtCount;
    FixedInfo       aFiCount;
    FixedLine       aGrpBitmap;

    RadioButton     aRbtGroup;
    RadioButton     aRbtBitmap;
    FixedText       aFtAdjustment;
    ListBox         aLbAdjustment;
    PushButton      aBtnCreateGroup;
    FixedLine       aGrpAnimation;

    ::Window*       pWin;
    List            aBmpExList;
    List            aTimeList;
    SdDrawDocument* pMyDoc;
    BitmapEx*       pBitmapEx;

    Size            aSize;
    Size            aFltWinSize;
    Size            aDisplaySize;
    Size            aBmpSize;
    BOOL            bMovie;
    BOOL            bAllObjects;

    SfxBindings*                pBindings;
    AnimationControllerItem*    pControllerItem;

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

    DECL_LINK( ClickFirstHdl, void * );
    DECL_LINK( ClickStopHdl, void * );
    DECL_LINK( ClickPlayHdl, void * );
    DECL_LINK( ClickLastHdl, void * );
    DECL_LINK( ClickGetObjectHdl, void * );
    DECL_LINK( ClickRemoveBitmapHdl, void * );
    DECL_LINK( ClickRbtHdl, void * );
    DECL_LINK( ClickCreateGroupHdl, void * );
    DECL_LINK( ModifyBitmapHdl, void * );
    DECL_LINK( ModifyTimeHdl, void * );

    void            UpdateControl( ULONG nPos, BOOL bDisableCtrls = FALSE );
    void            ResetAttrs();
    void            WaitInEffect( ULONG nMilliSeconds ) const;
    void            WaitInEffect( ULONG nMilliSeconds, ULONG nTime,
                                        SfxProgress* pStbMgr ) const;
    Fraction        GetScale();
};

/*************************************************************************
|*
|* ControllerItem fuer Animator
|*
\************************************************************************/

class AnimationControllerItem : public SfxControllerItem
{

public:
    AnimationControllerItem( USHORT, AnimationWindow*, SfxBindings* );

protected:
    virtual void StateChanged( USHORT nSId, SfxItemState eState,
        const SfxPoolItem* pState );
private:
    AnimationWindow* pAnimationWin;
};

} // end of namespace sd

#endif

<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: animobjs.hxx,v $
 *
 *  $Revision: 1.6 $
 *
 *  last change: $Author: obo $ $Date: 2005-06-14 16:23:40 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#ifndef SD_ANIMOBJS_HXX
#define SD_ANIMOBJS_HXX

#ifndef _SFXDOCKWIN_HXX //autogen
#include <sfx2/dockwin.hxx>
#endif
#ifndef _SV_FIXED_HXX //autogen
#include <vcl/fixed.hxx>
#endif
#ifndef _STDCTRL_HXX //autogen
#include <svtools/stdctrl.hxx>
#endif
#ifndef _SV_GROUP_HXX //autogen
#include <vcl/group.hxx>
#endif
#ifndef _SFXCTRLITEM_HXX //autogen
#include <sfx2/ctrlitem.hxx>
#endif

#ifndef _SV_BUTTON_HXX //autogen
#include <vcl/button.hxx>
#endif

#ifndef _SV_FIELD_HXX //autogen
#include <vcl/field.hxx>
#endif

#ifndef _SVX_DLG_CTRL_HXX //autogen
#include <svx/dlgctrl.hxx>
#endif
#ifndef _SFX_PROGRESS_HXX
#include <sfx2/progress.hxx>
#endif

#ifndef _SV_LSTBOX_HXX //autogen
#include <vcl/lstbox.hxx>
#endif

#ifndef _SD_SDRESID_HXX
#include "sdresid.hxx"
#endif

class SdDrawDocument;
class BitmapEx;

namespace sd {

class AnimationControllerItem;
class View;

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

enum BitmapAdjustment
{
    BA_LEFT_UP,
    BA_LEFT,
    BA_LEFT_DOWN,
    BA_UP,
    BA_CENTER,
    BA_DOWN,
    BA_RIGHT_UP,
    BA_RIGHT,
    BA_RIGHT_DOWN
};

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

class SdDisplay : public Control
{
private:
    BitmapEx    aBitmapEx;
    Fraction    aScale;

public:
    SdDisplay( ::Window* pWin, SdResId Id );
    ~SdDisplay();

    virtual void Paint( const Rectangle& rRect );

    void    SetBitmapEx( BitmapEx* pBmpEx );
    void    SetScale( const Fraction& rFrac );

    virtual void DataChanged( const DataChangedEvent& rDCEvt );
};

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

class AnimationWindow : public SfxDockingWindow
{
 friend class AnimationChildWindow;
 friend class AnimationControllerItem;

public:
    AnimationWindow( SfxBindings* pBindings, SfxChildWindow *pCW,
        ::Window* pParent, const SdResId& rSdResId );
    virtual ~AnimationWindow();

    void    AddObj( ::sd::View& rView );
    void    CreateAnimObj( ::sd::View& rView );

    virtual void DataChanged( const DataChangedEvent& rDCEvt );

protected:
    virtual BOOL    Close();
    virtual void    Resize();
    virtual void    FillInfo( SfxChildWinInfo& ) const;

private:
    SdDisplay       aCtlDisplay;
    ImageButton     aBtnFirst;
    ImageButton     aBtnReverse;
    ImageButton     aBtnStop;
    ImageButton     aBtnPlay;
    ImageButton     aBtnLast;
    NumericField    aNumFldBitmap;
    TimeField       aTimeField;
    ListBox         aLbLoopCount;

    ImageButton     aBtnGetOneObject;
    ImageButton     aBtnGetAllObjects;
    ImageButton     aBtnRemoveBitmap;
    ImageButton     aBtnRemoveAll;
    FixedText       aFtCount;
    FixedInfo       aFiCount;
    FixedLine       aGrpBitmap;

    RadioButton     aRbtGroup;
    RadioButton     aRbtBitmap;
    FixedText       aFtAdjustment;
    ListBox         aLbAdjustment;
    PushButton      aBtnCreateGroup;
    FixedLine       aGrpAnimation;

    ::Window*       pWin;
    List            aBmpExList;
    List            aTimeList;
    SdDrawDocument* pMyDoc;
    BitmapEx*       pBitmapEx;

    Size            aSize;
    Size            aFltWinSize;
    Size            aDisplaySize;
    Size            aBmpSize;
    BOOL            bMovie;
    BOOL            bAllObjects;

    SfxBindings*                pBindings;
    AnimationControllerItem*    pControllerItem;

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

    DECL_LINK( ClickFirstHdl, void * );
    DECL_LINK( ClickStopHdl, void * );
    DECL_LINK( ClickPlayHdl, void * );
    DECL_LINK( ClickLastHdl, void * );
    DECL_LINK( ClickGetObjectHdl, void * );
    DECL_LINK( ClickRemoveBitmapHdl, void * );
    DECL_LINK( ClickRbtHdl, void * );
    DECL_LINK( ClickCreateGroupHdl, void * );
    DECL_LINK( ModifyBitmapHdl, void * );
    DECL_LINK( ModifyTimeHdl, void * );

    void            UpdateControl( ULONG nPos, BOOL bDisableCtrls = FALSE );
    void            ResetAttrs();
    void            WaitInEffect( ULONG nMilliSeconds ) const;
    void            WaitInEffect( ULONG nMilliSeconds, ULONG nTime,
                                        SfxProgress* pStbMgr ) const;
    Fraction        GetScale();
};

/*************************************************************************
|*
|* ControllerItem fuer Animator
|*
\************************************************************************/

class AnimationControllerItem : public SfxControllerItem
{

public:
    AnimationControllerItem( USHORT, AnimationWindow*, SfxBindings* );

protected:
    virtual void StateChanged( USHORT nSId, SfxItemState eState,
        const SfxPoolItem* pState );
private:
    AnimationWindow* pAnimationWin;
};

} // end of namespace sd

#endif

<commit_msg>INTEGRATION: CWS ooo19126 (1.6.90); FILE MERGED 2005/09/05 13:22:54 rt 1.6.90.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: animobjs.hxx,v $
 *
 *  $Revision: 1.7 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-09 05:21:56 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#ifndef SD_ANIMOBJS_HXX
#define SD_ANIMOBJS_HXX

#ifndef _SFXDOCKWIN_HXX //autogen
#include <sfx2/dockwin.hxx>
#endif
#ifndef _SV_FIXED_HXX //autogen
#include <vcl/fixed.hxx>
#endif
#ifndef _STDCTRL_HXX //autogen
#include <svtools/stdctrl.hxx>
#endif
#ifndef _SV_GROUP_HXX //autogen
#include <vcl/group.hxx>
#endif
#ifndef _SFXCTRLITEM_HXX //autogen
#include <sfx2/ctrlitem.hxx>
#endif

#ifndef _SV_BUTTON_HXX //autogen
#include <vcl/button.hxx>
#endif

#ifndef _SV_FIELD_HXX //autogen
#include <vcl/field.hxx>
#endif

#ifndef _SVX_DLG_CTRL_HXX //autogen
#include <svx/dlgctrl.hxx>
#endif
#ifndef _SFX_PROGRESS_HXX
#include <sfx2/progress.hxx>
#endif

#ifndef _SV_LSTBOX_HXX //autogen
#include <vcl/lstbox.hxx>
#endif

#ifndef _SD_SDRESID_HXX
#include "sdresid.hxx"
#endif

class SdDrawDocument;
class BitmapEx;

namespace sd {

class AnimationControllerItem;
class View;

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

enum BitmapAdjustment
{
    BA_LEFT_UP,
    BA_LEFT,
    BA_LEFT_DOWN,
    BA_UP,
    BA_CENTER,
    BA_DOWN,
    BA_RIGHT_UP,
    BA_RIGHT,
    BA_RIGHT_DOWN
};

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

class SdDisplay : public Control
{
private:
    BitmapEx    aBitmapEx;
    Fraction    aScale;

public:
    SdDisplay( ::Window* pWin, SdResId Id );
    ~SdDisplay();

    virtual void Paint( const Rectangle& rRect );

    void    SetBitmapEx( BitmapEx* pBmpEx );
    void    SetScale( const Fraction& rFrac );

    virtual void DataChanged( const DataChangedEvent& rDCEvt );
};

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

class AnimationWindow : public SfxDockingWindow
{
 friend class AnimationChildWindow;
 friend class AnimationControllerItem;

public:
    AnimationWindow( SfxBindings* pBindings, SfxChildWindow *pCW,
        ::Window* pParent, const SdResId& rSdResId );
    virtual ~AnimationWindow();

    void    AddObj( ::sd::View& rView );
    void    CreateAnimObj( ::sd::View& rView );

    virtual void DataChanged( const DataChangedEvent& rDCEvt );

protected:
    virtual BOOL    Close();
    virtual void    Resize();
    virtual void    FillInfo( SfxChildWinInfo& ) const;

private:
    SdDisplay       aCtlDisplay;
    ImageButton     aBtnFirst;
    ImageButton     aBtnReverse;
    ImageButton     aBtnStop;
    ImageButton     aBtnPlay;
    ImageButton     aBtnLast;
    NumericField    aNumFldBitmap;
    TimeField       aTimeField;
    ListBox         aLbLoopCount;

    ImageButton     aBtnGetOneObject;
    ImageButton     aBtnGetAllObjects;
    ImageButton     aBtnRemoveBitmap;
    ImageButton     aBtnRemoveAll;
    FixedText       aFtCount;
    FixedInfo       aFiCount;
    FixedLine       aGrpBitmap;

    RadioButton     aRbtGroup;
    RadioButton     aRbtBitmap;
    FixedText       aFtAdjustment;
    ListBox         aLbAdjustment;
    PushButton      aBtnCreateGroup;
    FixedLine       aGrpAnimation;

    ::Window*       pWin;
    List            aBmpExList;
    List            aTimeList;
    SdDrawDocument* pMyDoc;
    BitmapEx*       pBitmapEx;

    Size            aSize;
    Size            aFltWinSize;
    Size            aDisplaySize;
    Size            aBmpSize;
    BOOL            bMovie;
    BOOL            bAllObjects;

    SfxBindings*                pBindings;
    AnimationControllerItem*    pControllerItem;

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

    DECL_LINK( ClickFirstHdl, void * );
    DECL_LINK( ClickStopHdl, void * );
    DECL_LINK( ClickPlayHdl, void * );
    DECL_LINK( ClickLastHdl, void * );
    DECL_LINK( ClickGetObjectHdl, void * );
    DECL_LINK( ClickRemoveBitmapHdl, void * );
    DECL_LINK( ClickRbtHdl, void * );
    DECL_LINK( ClickCreateGroupHdl, void * );
    DECL_LINK( ModifyBitmapHdl, void * );
    DECL_LINK( ModifyTimeHdl, void * );

    void            UpdateControl( ULONG nPos, BOOL bDisableCtrls = FALSE );
    void            ResetAttrs();
    void            WaitInEffect( ULONG nMilliSeconds ) const;
    void            WaitInEffect( ULONG nMilliSeconds, ULONG nTime,
                                        SfxProgress* pStbMgr ) const;
    Fraction        GetScale();
};

/*************************************************************************
|*
|* ControllerItem fuer Animator
|*
\************************************************************************/

class AnimationControllerItem : public SfxControllerItem
{

public:
    AnimationControllerItem( USHORT, AnimationWindow*, SfxBindings* );

protected:
    virtual void StateChanged( USHORT nSId, SfxItemState eState,
        const SfxPoolItem* pState );
private:
    AnimationWindow* pAnimationWin;
};

} // end of namespace sd

#endif

<|endoftext|>


<commit_before>/// @file
/// @copyright The code is licensed under the BSD License
///            <http://opensource.org/licenses/BSD-2-Clause>,
///            Copyright (c) 2012-2015 Alexandre Hamez.
/// @author Alexandre Hamez
#pragma once

#include <functional> // reference_wrapper
#include <limits>
#include <numeric>    // accumulate
#include <vector>

#include "sdd/order/order_builder.hh"
#include "sdd/order/strategies/force_hyperedge.hh"
#include "sdd/order/strategies/force_hypergraph.hh"
#include "sdd/order/strategies/force_vertex.hh"

namespace sdd { namespace force {

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

/// @internal
/// @brief An implementation of the FORCE ordering strategy
/// @see https://web.eecs.umich.edu/~karem/papers/Aloul-GLSVLSI03.pdf
template <typename C>
class worker
{
private:

  using id_type = typename C::Identifier;
  using vertex_type = vertex<id_type>;
  using hyperedge_type = hyperedge<id_type>;

  /// @brief
  std::deque<vertex_type>& vertices_;

  /// @brief The hyperedges that link together vertices.
  std::deque<hyperedge_type>& hyperedges_;

  /// @brief Keep all computed total spans for statistics.
  std::deque<double> spans_;

  /// @brief Reverse order.
  bool reverse_;

public:

  /// @brief Constructor.
  worker(hypergraph<C>& graph, bool reverse = false)
    : vertices_(graph.vertices()), hyperedges_(graph.hyperedges()), spans_(), reverse_(reverse)
  {}

  /// @brief Effectively apply the FORCE ordering strategy.
  order_builder<C>
  operator()(unsigned int iterations = 200)
  {
    std::vector<std::reference_wrapper<vertex_type>>
      sorted_vertices(vertices_.begin(), vertices_.end());

    // Keep a copy of the order with the smallest span.
    std::vector<std::reference_wrapper<vertex_type>> best_order(sorted_vertices);
    double smallest_span = std::numeric_limits<double>::max();

    while (iterations-- != 0)
    {
      // Compute the new center of gravity for every hyperedge.
      for (auto& edge : hyperedges_)
      {
        edge.compute_center_of_gravity();
      }

      // Compute the tentative new location of every vertex.
      for (auto& vertex : vertices_)
      {
        if (vertex.hyperedges().empty())
        {
          continue;
        }
        vertex.location() = std::accumulate( vertex.hyperedges().cbegin()
                                           , vertex.hyperedges().cend()
                                           , 0
                                           , [](double acc, const hyperedge_type* e)
                                               {return acc + e->center_of_gravity() * e->weight();}
                                           ) / vertex.hyperedges().size();
      }

      // Sort tentative vertex locations.
      std::sort( sorted_vertices.begin(), sorted_vertices.end()
               , [](vertex_type& lhs, vertex_type& rhs){return lhs.location() < rhs.location();});

      // Assign integer indices to the vertices.
      unsigned int pos = 0;
      std::for_each( sorted_vertices.begin(), sorted_vertices.end()
                   , [&pos](vertex_type& v){v.location() = pos++;});

      const double span = get_total_span();
      spans_.push_back(span);
      if (span < smallest_span)
      {
        // We keep the order that minimizes the span.
        best_order = sorted_vertices;
      }
    }

    order_builder<C> ob;
    if (reverse_)
    {
      for (auto rcit = best_order.rbegin(); rcit != best_order.rend(); ++rcit)
      {
        ob.push(rcit->get().id());
      }
    }
    else
    {
      for (const auto& vertex : best_order)
      {
        ob.push(vertex.get().id());
      }
    }
    return ob;
  }

  const std::deque<double>&
  spans()
  const noexcept
  {
    return spans_;
  }

private:

  /// @brief Add the span of all hyperedges.
  double
  get_total_span()
  const noexcept
  {
    return std::accumulate( hyperedges_.cbegin(), hyperedges_.cend(), 0
                          , [](double acc, const hyperedge_type& h){return acc + h.span();});
  }
};

} // namespace force

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

} // namespace sdd
<commit_msg>A better reference for FORCE: a fast and easy-to-implement variable-ordering heuristic<commit_after>/// @file
/// @copyright The code is licensed under the BSD License
///            <http://opensource.org/licenses/BSD-2-Clause>,
///            Copyright (c) 2012-2015 Alexandre Hamez.
/// @author Alexandre Hamez
#pragma once

#include <functional> // reference_wrapper
#include <limits>
#include <numeric>    // accumulate
#include <vector>

#include "sdd/order/order_builder.hh"
#include "sdd/order/strategies/force_hyperedge.hh"
#include "sdd/order/strategies/force_hypergraph.hh"
#include "sdd/order/strategies/force_vertex.hh"

namespace sdd { namespace force {

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

/// @internal
/// @brief An implementation of the FORCE ordering strategy
/// @see http://dx.doi.org/10.1145/764808.764839
template <typename C>
class worker
{
private:

  using id_type = typename C::Identifier;
  using vertex_type = vertex<id_type>;
  using hyperedge_type = hyperedge<id_type>;

  /// @brief
  std::deque<vertex_type>& vertices_;

  /// @brief The hyperedges that link together vertices.
  std::deque<hyperedge_type>& hyperedges_;

  /// @brief Keep all computed total spans for statistics.
  std::deque<double> spans_;

  /// @brief Reverse order.
  bool reverse_;

public:

  /// @brief Constructor.
  worker(hypergraph<C>& graph, bool reverse = false)
    : vertices_(graph.vertices()), hyperedges_(graph.hyperedges()), spans_(), reverse_(reverse)
  {}

  /// @brief Effectively apply the FORCE ordering strategy.
  order_builder<C>
  operator()(unsigned int iterations = 200)
  {
    std::vector<std::reference_wrapper<vertex_type>>
      sorted_vertices(vertices_.begin(), vertices_.end());

    // Keep a copy of the order with the smallest span.
    std::vector<std::reference_wrapper<vertex_type>> best_order(sorted_vertices);
    double smallest_span = std::numeric_limits<double>::max();

    while (iterations-- != 0)
    {
      // Compute the new center of gravity for every hyperedge.
      for (auto& edge : hyperedges_)
      {
        edge.compute_center_of_gravity();
      }

      // Compute the tentative new location of every vertex.
      for (auto& vertex : vertices_)
      {
        if (vertex.hyperedges().empty())
        {
          continue;
        }
        vertex.location() = std::accumulate( vertex.hyperedges().cbegin()
                                           , vertex.hyperedges().cend()
                                           , 0
                                           , [](double acc, const hyperedge_type* e)
                                               {return acc + e->center_of_gravity() * e->weight();}
                                           ) / vertex.hyperedges().size();
      }

      // Sort tentative vertex locations.
      std::sort( sorted_vertices.begin(), sorted_vertices.end()
               , [](vertex_type& lhs, vertex_type& rhs){return lhs.location() < rhs.location();});

      // Assign integer indices to the vertices.
      unsigned int pos = 0;
      std::for_each( sorted_vertices.begin(), sorted_vertices.end()
                   , [&pos](vertex_type& v){v.location() = pos++;});

      const double span = get_total_span();
      spans_.push_back(span);
      if (span < smallest_span)
      {
        // We keep the order that minimizes the span.
        best_order = sorted_vertices;
      }
    }

    order_builder<C> ob;
    if (reverse_)
    {
      for (auto rcit = best_order.rbegin(); rcit != best_order.rend(); ++rcit)
      {
        ob.push(rcit->get().id());
      }
    }
    else
    {
      for (const auto& vertex : best_order)
      {
        ob.push(vertex.get().id());
      }
    }
    return ob;
  }

  const std::deque<double>&
  spans()
  const noexcept
  {
    return spans_;
  }

private:

  /// @brief Add the span of all hyperedges.
  double
  get_total_span()
  const noexcept
  {
    return std::accumulate( hyperedges_.cbegin(), hyperedges_.cend(), 0
                          , [](double acc, const hyperedge_type& h){return acc + h.span();});
  }
};

} // namespace force

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

} // namespace sdd
<|endoftext|>


<commit_before>/*
    Copyright (c) 2011 Volker Krause <vkrause@kde.org>

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

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

    You should have received a copy of the GNU Library General Public License
    along with this library; see the file COPYING.LIB.  If not, write to the
    Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
    02110-1301, USA.
*/

#include "storagejanitor.h"

#include "storage/datastore.h"
#include "storage/selectquerybuilder.h"

#include <akdebug.h>
#include <libs/protocol_p.h>
#include <libs/xdgbasedirs_p.h>

#include <QStringBuilder>
#include <QtDBus/QDBusConnection>
#include <QtSql/QSqlQuery>
#include <QtSql/QSqlError>

#include <boost/bind.hpp>
#include <algorithm>
#include <QtCore/QDir>
#include <QtCore/qdiriterator.h>

using namespace Akonadi;

StorageJanitorThread::StorageJanitorThread(QObject* parent): QThread(parent)
{
}

void StorageJanitorThread::run()
{
  StorageJanitor* janitor = new StorageJanitor;
  exec();
  delete janitor;
}

StorageJanitor::StorageJanitor(QObject* parent) :
  QObject(parent),
  m_connection( QDBusConnection::connectToBus( QDBusConnection::SessionBus, QLatin1String(staticMetaObject.className()) ) )
{
  DataStore::self();
  m_connection.registerService( QLatin1String( AKONADI_DBUS_STORAGEJANITOR_SERVICE ) );
  m_connection.registerObject( QLatin1String( AKONADI_DBUS_STORAGEJANITOR_PATH ), this, QDBusConnection::ExportScriptableSlots | QDBusConnection::ExportScriptableSignals );
}

StorageJanitor::~StorageJanitor()
{
  m_connection.unregisterObject( QLatin1String( AKONADI_DBUS_STORAGEJANITOR_PATH ), QDBusConnection::UnregisterTree );
  m_connection.unregisterService( QLatin1String( AKONADI_DBUS_STORAGEJANITOR_SERVICE ) );
  m_connection.disconnectFromBus( m_connection.name() );

  DataStore::self()->close();
}

void StorageJanitor::check()
{
  inform( "Looking for collections not belonging to a valid resource..." );
  findOrphanedCollections();

  inform( "Checking collection tree consistency..." );
  const Collection::List cols = Collection::retrieveAll();
  std::for_each( cols.begin(), cols.end(), boost::bind( &StorageJanitor::checkPathToRoot, this, _1 ) );

  inform( "Looking for items not belonging to a valid collection..." );
  findOrphanedItems();

  inform( "Looking for item parts not belonging to a valid item..." );
  findOrphanedParts();

  inform( "Looking for overlapping external parts..." );
  findOverlappingParts();

  inform( "Verifying external parts..." );
  verifyExternalParts();

  inform( "Looking for dirty objects..." );
  findDirtyObjects();

  /* TODO some ideas for further checks:
   * the collection tree is non-cyclic
   * content type constraints of collections are not violated
   * find unused flags
   * find unused mimetypes
   * check for dead entries in relation tables
   * check if part size matches file size
   */

  inform( "Consistency check done." );
}

void StorageJanitor::findOrphanedCollections()
{
  SelectQueryBuilder<Collection> qb;
  qb.addJoin( QueryBuilder::LeftJoin, Resource::tableName(), Collection::resourceIdFullColumnName(), Resource::idFullColumnName() );
  qb.addValueCondition( Resource::idFullColumnName(), Query::Is, QVariant() );

  qb.exec();
  const Collection::List orphans = qb.result();
  if ( orphans.size() > 0 ) {
    inform( QLatin1Literal( "Found " ) + QString::number( orphans.size() ) + QLatin1Literal( " orphan collections." ) );
    // TODO: attach to lost+found resource
  }
}

void StorageJanitor::checkPathToRoot(const Akonadi::Collection& col)
{
  if ( col.parentId() == 0 )
    return;
  const Akonadi::Collection parent = col.parent();
  if ( !parent.isValid() ) {
    inform( QLatin1Literal( "Collection \"" ) + col.name() + QLatin1Literal( "\" (id: " ) + QString::number( col.id()  )
          + QLatin1Literal( ") has no valid parent." ) );
    // TODO fix that by attaching to a top-level lost+found folder
    return;
  }

  if ( col.resourceId() != parent.resourceId() ) {
    inform( QLatin1Literal( "Collection \"" ) + col.name() + QLatin1Literal( "\" (id: " ) + QString::number( col.id()  )
          + QLatin1Literal( ") belongs to a different resource than its parent." ) );
    // can/should we actually fix that?
  }

  checkPathToRoot( parent );
}

void StorageJanitor::findOrphanedItems()
{
  SelectQueryBuilder<PimItem> qb;
  qb.addJoin( QueryBuilder::LeftJoin, Collection::tableName(), PimItem::collectionIdFullColumnName(), Collection::idFullColumnName() );
  qb.addValueCondition( Collection::idFullColumnName(), Query::Is, QVariant() );

  qb.exec();
  const PimItem::List orphans = qb.result();
  if ( orphans.size() > 0 ) {
    inform( QLatin1Literal( "Found " ) + QString::number( orphans.size() ) + QLatin1Literal( " orphan items." ) );
    // TODO: attach to lost+found collection
  }
}

void StorageJanitor::findOrphanedParts()
{
  SelectQueryBuilder<Part> qb;
  qb.addJoin( QueryBuilder::LeftJoin, PimItem::tableName(), Part::pimItemIdFullColumnName(), PimItem::idFullColumnName() );
  qb.addValueCondition( PimItem::idFullColumnName(), Query::Is, QVariant() );

  qb.exec();
  const Part::List orphans = qb.result();
  if ( orphans.size() > 0 ) {
    inform( QLatin1Literal( "Found " ) + QString::number( orphans.size() ) + QLatin1Literal( " orphan items." ) );
    // TODO: create lost+found items for those? delete?
  }
}

void StorageJanitor::findOverlappingParts()
{
  QueryBuilder qb( Part::tableName(), QueryBuilder::Select );
  qb.addColumn( Part::dataColumn() );
  qb.addColumn( QLatin1Literal("count(") + Part::idColumn() + QLatin1Literal(") as cnt") );
  qb.addValueCondition( Part::externalColumn(), Query::Equals, true );
  qb.addValueCondition( Part::dataColumn(), Query::IsNot, QVariant() );
  qb.addGroupColumn( Part::dataColumn() );
  qb.addValueCondition( QLatin1Literal("count(") + Part::idColumn() + QLatin1Literal(")"), Query::Greater, 1, QueryBuilder::HavingCondition );
  qb.exec();

  int count = 0;
  while ( qb.query().next() ) {
    ++count;
    inform( QLatin1Literal( "Found overlapping item: " ) + qb.query().value( 0 ).toString() );
    // TODO: uh oh, this is bad, how do we recover from that?
  }

  if ( count > 0 )
    inform( QLatin1Literal( "Found " ) + QString::number( count ) + QLatin1Literal( " overlapping parts - bad." ) );
}

void StorageJanitor::verifyExternalParts()
{
  QSet<QString> existingFiles;
  QSet<QString> usedFiles;

  // list all files
  const QString dataDir = XdgBaseDirs::saveDir( "data", QLatin1String( "akonadi/file_db_data" ) );
  QDirIterator it( dataDir );
  while ( it.hasNext() )
    existingFiles.insert( it.next() );
  existingFiles.remove( QLatin1String( "." ) );
  existingFiles.remove( QLatin1String( ".." ) );
  inform( QLatin1Literal( "Found " ) + QString::number( existingFiles.size() ) + QLatin1Literal( " external files." ) );

  // list all parts from the db which claim to have an associated file
  QueryBuilder qb( Part::tableName(), QueryBuilder::Select );
  qb.addColumn( Part::dataColumn() );
  qb.addValueCondition( Part::externalColumn(), Query::Equals, true );
  qb.addValueCondition( Part::dataColumn(), Query::IsNot, QVariant() );
  qb.exec();
  while ( qb.query().next() ) {
    const QString partPath = qb.query().value( 0 ).toString();
    if ( existingFiles.contains( partPath ) ) {
      usedFiles.insert( partPath );
    } else {
      inform( QLatin1Literal( "Missing external file: " ) + partPath );
      // TODO: fix this, by clearing the data column?
    }
  }
  inform( QLatin1Literal( "Found " ) + QString::number( usedFiles.size() ) + QLatin1Literal( " external parts." ) );

  // see what's left
  foreach ( const QString &file, existingFiles - usedFiles ) {
    inform( QLatin1Literal( "Found unreferenced external file: " ) + file );
    // TODO: delete file?
  }
}

void StorageJanitor::findDirtyObjects()
{
  SelectQueryBuilder<Collection> cqb;
  cqb.setSubQueryMode( Query::Or);
  cqb.addValueCondition( Collection::remoteIdColumn(), Query::Is, QVariant() );
  cqb.addValueCondition( Collection::remoteIdColumn(), Query::Equals, QString() );
  cqb.exec();
  const Collection::List ridLessCols = cqb.result();
  foreach ( const Collection &col, ridLessCols )
    inform( QLatin1Literal( "Collection \"" ) + col.name() + QLatin1Literal( "\" (id: " ) + QString::number( col.id()  )
          + QLatin1Literal( ") has no RID." ) );
  inform( QLatin1Literal( "Found " ) + QString::number( ridLessCols.size() ) + QLatin1Literal( " collections without RID." ) );

  SelectQueryBuilder<PimItem> iqb1;
  iqb1.setSubQueryMode( Query::Or);
  iqb1.addValueCondition( PimItem::remoteIdColumn(), Query::Is, QVariant() );
  iqb1.addValueCondition( PimItem::remoteIdColumn(), Query::Equals, QString() );
  iqb1.exec();
  const PimItem::List ridLessItems = iqb1.result();
  foreach ( const PimItem &item, ridLessItems )
    inform( QLatin1Literal( "Item \"" ) + QString::number( item.id()  ) + QLatin1Literal( "\" has no RID." ) );
  inform( QLatin1Literal( "Found " ) + QString::number( ridLessItems.size() ) + QLatin1Literal( " items without RID." ) );

  SelectQueryBuilder<PimItem> iqb2;
  iqb2.addValueCondition( PimItem::dirtyColumn(), Query::Equals, true );
  iqb2.addValueCondition( PimItem::remoteIdColumn(), Akonadi::Query::IsNot, QVariant() );
  iqb2.exec();
  const PimItem::List dirtyItems = iqb2.result();
  foreach ( const PimItem &item, dirtyItems )
    inform( QLatin1Literal( "Item \"" ) + QString::number( item.id()  ) + QLatin1Literal( "\" has RID and is dirty." ) );
  inform( QLatin1Literal( "Found " ) + QString::number( dirtyItems.size() ) + QLatin1Literal( " dirty items." ) );
}

void StorageJanitor::vacuum()
{
  if ( DataStore::self()->database().driverName() == QLatin1String( "QMYSQL" ) ) {
    inform( "vacuuming database, that'll take some time and require a lot of temporary disk space..." );

    foreach ( const QString &table, Akonadi::allDatabaseTables() ) {
      inform( QString::fromLatin1( "optimizing table %1..." ).arg( table ) );
      const QString queryStr = QLatin1Literal( "OPTIMIZE TABLE " ) + table;
      QSqlQuery q( DataStore::self()->database() );
      if ( !q.exec( queryStr ) ) {
        akError() << "failed to optimize table" << table << ":" << q.lastError().text();
      }
    }
    inform( "vacuum done" );
  } else {
    inform( "Vacuum not supported for this database backend." );
  }
}

void StorageJanitor::inform(const char* msg)
{
  inform( QLatin1String(msg) );
}

void StorageJanitor::inform(const QString& msg)
{
  akDebug() << msg;
  emit information( msg );
}

<commit_msg>make akonadictl vacuum run with the PSQL backend<commit_after>/*
    Copyright (c) 2011 Volker Krause <vkrause@kde.org>

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

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

    You should have received a copy of the GNU Library General Public License
    along with this library; see the file COPYING.LIB.  If not, write to the
    Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
    02110-1301, USA.
*/

#include "storagejanitor.h"

#include "storage/datastore.h"
#include "storage/selectquerybuilder.h"

#include <akdebug.h>
#include <libs/protocol_p.h>
#include <libs/xdgbasedirs_p.h>

#include <QStringBuilder>
#include <QtDBus/QDBusConnection>
#include <QtSql/QSqlQuery>
#include <QtSql/QSqlError>

#include <boost/bind.hpp>
#include <algorithm>
#include <QtCore/QDir>
#include <QtCore/qdiriterator.h>

using namespace Akonadi;

StorageJanitorThread::StorageJanitorThread(QObject* parent): QThread(parent)
{
}

void StorageJanitorThread::run()
{
  StorageJanitor* janitor = new StorageJanitor;
  exec();
  delete janitor;
}

StorageJanitor::StorageJanitor(QObject* parent) :
  QObject(parent),
  m_connection( QDBusConnection::connectToBus( QDBusConnection::SessionBus, QLatin1String(staticMetaObject.className()) ) )
{
  DataStore::self();
  m_connection.registerService( QLatin1String( AKONADI_DBUS_STORAGEJANITOR_SERVICE ) );
  m_connection.registerObject( QLatin1String( AKONADI_DBUS_STORAGEJANITOR_PATH ), this, QDBusConnection::ExportScriptableSlots | QDBusConnection::ExportScriptableSignals );
}

StorageJanitor::~StorageJanitor()
{
  m_connection.unregisterObject( QLatin1String( AKONADI_DBUS_STORAGEJANITOR_PATH ), QDBusConnection::UnregisterTree );
  m_connection.unregisterService( QLatin1String( AKONADI_DBUS_STORAGEJANITOR_SERVICE ) );
  m_connection.disconnectFromBus( m_connection.name() );

  DataStore::self()->close();
}

void StorageJanitor::check()
{
  inform( "Looking for collections not belonging to a valid resource..." );
  findOrphanedCollections();

  inform( "Checking collection tree consistency..." );
  const Collection::List cols = Collection::retrieveAll();
  std::for_each( cols.begin(), cols.end(), boost::bind( &StorageJanitor::checkPathToRoot, this, _1 ) );

  inform( "Looking for items not belonging to a valid collection..." );
  findOrphanedItems();

  inform( "Looking for item parts not belonging to a valid item..." );
  findOrphanedParts();

  inform( "Looking for overlapping external parts..." );
  findOverlappingParts();

  inform( "Verifying external parts..." );
  verifyExternalParts();

  inform( "Looking for dirty objects..." );
  findDirtyObjects();

  /* TODO some ideas for further checks:
   * the collection tree is non-cyclic
   * content type constraints of collections are not violated
   * find unused flags
   * find unused mimetypes
   * check for dead entries in relation tables
   * check if part size matches file size
   */

  inform( "Consistency check done." );
}

void StorageJanitor::findOrphanedCollections()
{
  SelectQueryBuilder<Collection> qb;
  qb.addJoin( QueryBuilder::LeftJoin, Resource::tableName(), Collection::resourceIdFullColumnName(), Resource::idFullColumnName() );
  qb.addValueCondition( Resource::idFullColumnName(), Query::Is, QVariant() );

  qb.exec();
  const Collection::List orphans = qb.result();
  if ( orphans.size() > 0 ) {
    inform( QLatin1Literal( "Found " ) + QString::number( orphans.size() ) + QLatin1Literal( " orphan collections." ) );
    // TODO: attach to lost+found resource
  }
}

void StorageJanitor::checkPathToRoot(const Akonadi::Collection& col)
{
  if ( col.parentId() == 0 )
    return;
  const Akonadi::Collection parent = col.parent();
  if ( !parent.isValid() ) {
    inform( QLatin1Literal( "Collection \"" ) + col.name() + QLatin1Literal( "\" (id: " ) + QString::number( col.id()  )
          + QLatin1Literal( ") has no valid parent." ) );
    // TODO fix that by attaching to a top-level lost+found folder
    return;
  }

  if ( col.resourceId() != parent.resourceId() ) {
    inform( QLatin1Literal( "Collection \"" ) + col.name() + QLatin1Literal( "\" (id: " ) + QString::number( col.id()  )
          + QLatin1Literal( ") belongs to a different resource than its parent." ) );
    // can/should we actually fix that?
  }

  checkPathToRoot( parent );
}

void StorageJanitor::findOrphanedItems()
{
  SelectQueryBuilder<PimItem> qb;
  qb.addJoin( QueryBuilder::LeftJoin, Collection::tableName(), PimItem::collectionIdFullColumnName(), Collection::idFullColumnName() );
  qb.addValueCondition( Collection::idFullColumnName(), Query::Is, QVariant() );

  qb.exec();
  const PimItem::List orphans = qb.result();
  if ( orphans.size() > 0 ) {
    inform( QLatin1Literal( "Found " ) + QString::number( orphans.size() ) + QLatin1Literal( " orphan items." ) );
    // TODO: attach to lost+found collection
  }
}

void StorageJanitor::findOrphanedParts()
{
  SelectQueryBuilder<Part> qb;
  qb.addJoin( QueryBuilder::LeftJoin, PimItem::tableName(), Part::pimItemIdFullColumnName(), PimItem::idFullColumnName() );
  qb.addValueCondition( PimItem::idFullColumnName(), Query::Is, QVariant() );

  qb.exec();
  const Part::List orphans = qb.result();
  if ( orphans.size() > 0 ) {
    inform( QLatin1Literal( "Found " ) + QString::number( orphans.size() ) + QLatin1Literal( " orphan items." ) );
    // TODO: create lost+found items for those? delete?
  }
}

void StorageJanitor::findOverlappingParts()
{
  QueryBuilder qb( Part::tableName(), QueryBuilder::Select );
  qb.addColumn( Part::dataColumn() );
  qb.addColumn( QLatin1Literal("count(") + Part::idColumn() + QLatin1Literal(") as cnt") );
  qb.addValueCondition( Part::externalColumn(), Query::Equals, true );
  qb.addValueCondition( Part::dataColumn(), Query::IsNot, QVariant() );
  qb.addGroupColumn( Part::dataColumn() );
  qb.addValueCondition( QLatin1Literal("count(") + Part::idColumn() + QLatin1Literal(")"), Query::Greater, 1, QueryBuilder::HavingCondition );
  qb.exec();

  int count = 0;
  while ( qb.query().next() ) {
    ++count;
    inform( QLatin1Literal( "Found overlapping item: " ) + qb.query().value( 0 ).toString() );
    // TODO: uh oh, this is bad, how do we recover from that?
  }

  if ( count > 0 )
    inform( QLatin1Literal( "Found " ) + QString::number( count ) + QLatin1Literal( " overlapping parts - bad." ) );
}

void StorageJanitor::verifyExternalParts()
{
  QSet<QString> existingFiles;
  QSet<QString> usedFiles;

  // list all files
  const QString dataDir = XdgBaseDirs::saveDir( "data", QLatin1String( "akonadi/file_db_data" ) );
  QDirIterator it( dataDir );
  while ( it.hasNext() )
    existingFiles.insert( it.next() );
  existingFiles.remove( QLatin1String( "." ) );
  existingFiles.remove( QLatin1String( ".." ) );
  inform( QLatin1Literal( "Found " ) + QString::number( existingFiles.size() ) + QLatin1Literal( " external files." ) );

  // list all parts from the db which claim to have an associated file
  QueryBuilder qb( Part::tableName(), QueryBuilder::Select );
  qb.addColumn( Part::dataColumn() );
  qb.addValueCondition( Part::externalColumn(), Query::Equals, true );
  qb.addValueCondition( Part::dataColumn(), Query::IsNot, QVariant() );
  qb.exec();
  while ( qb.query().next() ) {
    const QString partPath = qb.query().value( 0 ).toString();
    if ( existingFiles.contains( partPath ) ) {
      usedFiles.insert( partPath );
    } else {
      inform( QLatin1Literal( "Missing external file: " ) + partPath );
      // TODO: fix this, by clearing the data column?
    }
  }
  inform( QLatin1Literal( "Found " ) + QString::number( usedFiles.size() ) + QLatin1Literal( " external parts." ) );

  // see what's left
  foreach ( const QString &file, existingFiles - usedFiles ) {
    inform( QLatin1Literal( "Found unreferenced external file: " ) + file );
    // TODO: delete file?
  }
}

void StorageJanitor::findDirtyObjects()
{
  SelectQueryBuilder<Collection> cqb;
  cqb.setSubQueryMode( Query::Or);
  cqb.addValueCondition( Collection::remoteIdColumn(), Query::Is, QVariant() );
  cqb.addValueCondition( Collection::remoteIdColumn(), Query::Equals, QString() );
  cqb.exec();
  const Collection::List ridLessCols = cqb.result();
  foreach ( const Collection &col, ridLessCols )
    inform( QLatin1Literal( "Collection \"" ) + col.name() + QLatin1Literal( "\" (id: " ) + QString::number( col.id()  )
          + QLatin1Literal( ") has no RID." ) );
  inform( QLatin1Literal( "Found " ) + QString::number( ridLessCols.size() ) + QLatin1Literal( " collections without RID." ) );

  SelectQueryBuilder<PimItem> iqb1;
  iqb1.setSubQueryMode( Query::Or);
  iqb1.addValueCondition( PimItem::remoteIdColumn(), Query::Is, QVariant() );
  iqb1.addValueCondition( PimItem::remoteIdColumn(), Query::Equals, QString() );
  iqb1.exec();
  const PimItem::List ridLessItems = iqb1.result();
  foreach ( const PimItem &item, ridLessItems )
    inform( QLatin1Literal( "Item \"" ) + QString::number( item.id()  ) + QLatin1Literal( "\" has no RID." ) );
  inform( QLatin1Literal( "Found " ) + QString::number( ridLessItems.size() ) + QLatin1Literal( " items without RID." ) );

  SelectQueryBuilder<PimItem> iqb2;
  iqb2.addValueCondition( PimItem::dirtyColumn(), Query::Equals, true );
  iqb2.addValueCondition( PimItem::remoteIdColumn(), Akonadi::Query::IsNot, QVariant() );
  iqb2.exec();
  const PimItem::List dirtyItems = iqb2.result();
  foreach ( const PimItem &item, dirtyItems )
    inform( QLatin1Literal( "Item \"" ) + QString::number( item.id()  ) + QLatin1Literal( "\" has RID and is dirty." ) );
  inform( QLatin1Literal( "Found " ) + QString::number( dirtyItems.size() ) + QLatin1Literal( " dirty items." ) );
}

void StorageJanitor::vacuum()
{
  const QString driverName = DataStore::self()->database().driverName();
  if( ( driverName == QLatin1String( "QMYSQL" ) ) || ( driverName == QLatin1String( "QPSQL" ) ) ) {
    inform( "vacuuming database, that'll take some time and require a lot of temporary disk space..." );
    foreach ( const QString &table, Akonadi::allDatabaseTables() ) {
      inform( QString::fromLatin1( "optimizing table %1..." ).arg( table ) );

      QString queryStr;
      if ( driverName == QLatin1String( "QMYSQL" ) ) {
        queryStr = QLatin1Literal( "OPTIMIZE TABLE " ) + table;
      } else {
        queryStr = QLatin1Literal( "VACUUM FULL ANALYZE " ) + table;
      }
      QSqlQuery q( DataStore::self()->database() );
      if ( !q.exec( queryStr ) ) {
        akError() << "failed to optimize table" << table << ":" << q.lastError().text();
      }
    }
      inform( "vacuum done" );
  } else {
    inform( "Vacuum not supported for this database backend." );
  }
}

void StorageJanitor::inform(const char* msg)
{
  inform( QLatin1String(msg) );
}

void StorageJanitor::inform(const QString& msg)
{
  akDebug() << msg;
  emit information( msg );
}

<|endoftext|>


<commit_before>#include "mainwindow.h"
#include "paramwindows.h"
#include "ui_mainwindow.h"

#include <QMessageBox>
#include <QDialog>
#include "windowstatistics.h"
#include "windowserveur.h"
#include "launchsologame.h"
#include "widgetchat.h"

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

    // Maximize the window
    showMaximized();

    //Show welcome message
    ui->statusBar->showMessage("Bienvenue sur BOMBERMAN.", 15000);

    // Linking buttons to action triggered
    connect(ui->actionDemarrerPartieSolo,SIGNAL(triggered()),this,SLOT(BeginPartySolo()));
    connect(ui->actionDemarrerPartieMulti,SIGNAL(triggered()),this,SLOT(BeginPartyMulti()));
    connect(ui->actionChargerPartieSolo,SIGNAL(triggered()),this,SLOT(LoadPartySolo()));
    connect(ui->actionChargerPartieMulti,SIGNAL(triggered()),this,SLOT(LoadPartyMulti()));
    connect(ui->actionSauvegarderPartieSolo,SIGNAL(triggered()),this,SLOT(SavePartySolo()));
    connect(ui->actionQuitter,SIGNAL(triggered()),this,SLOT(Quit()));
    connect(ui->actionCommandes_de_jeu,SIGNAL(triggered()),this,SLOT(GameControls()));
    connect(ui->actionAffichage,SIGNAL(triggered()),this,SLOT(DisplaySetting()));
    connect(ui->actionAudio,SIGNAL(triggered()),this,SLOT(AudioSetting()));
    connect(ui->actionAide,SIGNAL(triggered()),this,SLOT(Help()));
    connect(ui->actionA_propos,SIGNAL(triggered()),this,SLOT(Credits()));
    connect(ui->actionAffichageStatistics,SIGNAL(triggered()),this,SLOT(Statistics()));

}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::BeginPartySolo()
{
    /*QMessageBox msg;
    msg.setText("Vous venez de lancer une partie solo.");
    msg.exec();*/

    LaunchSoloGame* formsologame = new LaunchSoloGame(this);
    formsologame->show();
}

void MainWindow::BeginPartyMulti()
{

    windowserveur* windowServer;
    windowServer = new windowserveur(this);
    windowServer->exec();

    //Test du module chat
    //Ajout du widgetChat

    QList<QString> *listJoueur = new QList<QString>();
    listJoueur->insert(0,"toto");
    widgetChat *Chat = new widgetChat(this,listJoueur);
    Chat->setGeometry(10,40,590,500);
    Chat->show();

}

void MainWindow::LoadPartySolo()
{
    // Ouverture du dossier parent de la solution et filtre sur les fichiers de type texte pour sélection fichier à ouvrir
    QString fichier = QFileDialog::getOpenFileName(this, "Ouvrir un fichier", QString(), "Fichiers texte (*.txt)");

    // Message d'information provisoire indiquant le chemin d'accès au fichier à ouvrir
    QMessageBox::information(this, "Fichier", "Vous avez ouvert le fichier :\n" + fichier);

    // on déclare la variable de type fichier, puis on l'ouvre en mode "lecture seule"
    QFile fichierACharger(fichier);
    fichierACharger.open(QIODevice::ReadOnly | QIODevice::Text);
    QTextStream flux (&fichierACharger);

    QString ligne;

    // On parcours ensuite le fichier ligne par ligne en y appliquant un traitement : ici affichage d'une messageBox
    while(! flux.atEnd())
    {
        ligne = flux.readLine();

        QMessageBox msg;
        msg.setText(ligne);
        msg.exec();
    }
}

void MainWindow::LoadPartyMulti()
{
    QMessageBox msg;
    msg.setText("Vous venez de charger une partie multi.");
    msg.exec();
}

void MainWindow::SavePartySolo()
{
    // On ouvre une boite de dialogue permettant la sauvegarde d'un fichier
    QString fichier = QFileDialog::getSaveFileName(this, "Enregistrer un fichier", QString("*.txt"), "Fichiers texte (*.txt);; Tous les fichiers (*.*)");

    // Message d'information provisoire indiquant le chemin d'accès du fichier créé
    QMessageBox::information(this, "Fichier", "Vous avez sauvegardé le fichier :\n" + fichier);
}

void MainWindow::Quit()
{
    if (QMessageBox::Yes == QMessageBox(QMessageBox::Warning, "Confirmation de sortie.", "Êtes-vous sûr de vouloir quitter BomberMan ?", QMessageBox::Yes|QMessageBox::No).exec())
    {
        exit(true);
    }
}

void MainWindow::GameControls()
{
    ParamWindows* paramForm;
    paramForm = new ParamWindows(this, 2);
    paramForm->show();
}

void MainWindow::DisplaySetting()
{
    ParamWindows* paramForm;
    paramForm = new ParamWindows(this, 1);
    paramForm->show();
}

void MainWindow::AudioSetting()
{
    ParamWindows* paramForm;
    paramForm = new ParamWindows(this, 0);
    paramForm->show();
}

void MainWindow::Help()
{
    QString texte;
    QFile fichier("../Bomberman/Help.txt"); // Modification du chemin d'accès en chemin relatif
    if(fichier.open(QIODevice::ReadOnly | QIODevice::Text))
    {
        texte = fichier.readAll();
        QMessageBox msgHelp;
        msgHelp.setGeometry(10,100,400,200);
        msgHelp.information(this, "Fichier d'aide : ", texte);

        fichier.close();
    }
    else
    {
        // Tu veux du commentaire ! je vais t'en mettre ...
        // Modifié par Yann le 26 février 2014 car cela ne fonctionnait pas !!!!
        // Banzai !!!!!!!!!
        QMessageBox msg; //déclaration d'une variable msg de type QMessageBox
        msg.setText("Impossible d'ouvrir le fichier !"); // Modification de la variable avec du texte !
        msg.exec(); // Affichage de la QMessageBox pour le mec qui a besoin d'aide ;-)
        // Fin du commentaire par Yann
    }

}

void MainWindow::Credits()
{
    /*QMessageBox msg;
    msg.setText("Vous venez d'ouvrir les configurations audio.");
    msg.exec();*/

    QMessageBox::about(this, tr("BomberMAN"),
                 tr("The BomberMAN  is a strategic, maze-based video game franchise originally developed by Hudson Soft. The original game was published in 1983 and new games have been published at irregular intervals ever since.                Several titles in the 2000s were published by fellow Japanese game company Konami, who gained full control of the franchise when they purchased and absorbed Hudson in 2012. Today, Bomberman has featured in over 70 different games on numerous platforms (including all Nintendo platforms save for the 3DS and Wii U), as well as several anime and manga.His franchise is one of the most commercially successful of all time.
Realised by the Dream-Team :

Petra Kratochvilova

Thibaud Cutullic

Yoann Solacroup

Yann Damon

Gregoire Quincy

Roman Logvinov

Damien Moro
"));
}

void MainWindow::Statistics()
{
    windowstatistics* Stats;
    Stats = new windowstatistics(this);
    Stats->setGeometry(50,100,490,190);
    Stats->exec();
}

<commit_msg>Status Bar<commit_after>#include "mainwindow.h"
#include "paramwindows.h"
#include "ui_mainwindow.h"

#include <QMessageBox>
#include <QDialog>
#include "windowstatistics.h"
#include "windowserveur.h"
#include "launchsologame.h"
#include "widgetchat.h"

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

    // Maximize the window
    showMaximized();

    //Show welcome message
    ui->statusBar->showMessage("Bienvenue sur BOMBERMAN.", 15000);

    // Linking buttons to action triggered
    connect(ui->actionDemarrerPartieSolo,SIGNAL(triggered()),this,SLOT(BeginPartySolo()));
    connect(ui->actionDemarrerPartieMulti,SIGNAL(triggered()),this,SLOT(BeginPartyMulti()));
    connect(ui->actionChargerPartieSolo,SIGNAL(triggered()),this,SLOT(LoadPartySolo()));
    connect(ui->actionChargerPartieMulti,SIGNAL(triggered()),this,SLOT(LoadPartyMulti()));
    connect(ui->actionSauvegarderPartieSolo,SIGNAL(triggered()),this,SLOT(SavePartySolo()));
    connect(ui->actionQuitter,SIGNAL(triggered()),this,SLOT(Quit()));
    connect(ui->actionCommandes_de_jeu,SIGNAL(triggered()),this,SLOT(GameControls()));
    connect(ui->actionAffichage,SIGNAL(triggered()),this,SLOT(DisplaySetting()));
    connect(ui->actionAudio,SIGNAL(triggered()),this,SLOT(AudioSetting()));
    connect(ui->actionAide,SIGNAL(triggered()),this,SLOT(Help()));
    connect(ui->actionA_propos,SIGNAL(triggered()),this,SLOT(Credits()));
    connect(ui->actionAffichageStatistics,SIGNAL(triggered()),this,SLOT(Statistics()));

}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::BeginPartySolo()
{
    /*QMessageBox msg;
    msg.setText("Vous venez de lancer une partie solo.");
    msg.exec();*/

    LaunchSoloGame* formsologame = new LaunchSoloGame(this);
    formsologame->show();
    ui->statusBar->showMessage("Lancez une nouvelle partie solo.", 15000);
}

void MainWindow::BeginPartyMulti()
{

    windowserveur* windowServer;
    windowServer = new windowserveur(this);
    windowServer->exec();

    //Test du module chat
    //Ajout du widgetChat

    QList<QString> *listJoueur = new QList<QString>();
    listJoueur->insert(0,"toto");
    widgetChat *Chat = new widgetChat(this,listJoueur);
    Chat->setGeometry(10,40,590,500);
    Chat->show();
<<<<<<statusBar->showMessage("Vous avez lancé la partie multijoueur.", 15000);
>>>>>>> master
}

void MainWindow::LoadPartySolo()
{
    // Ouverture du dossier parent de la solution et filtre sur les fichiers de type texte pour sélection fichier à ouvrir
    QString fichier = QFileDialog::getOpenFileName(this, "Ouvrir un fichier", QString(), "Fichiers texte (*.txt)");

    // Message d'information provisoire indiquant le chemin d'accès au fichier à ouvrir
    QMessageBox::information(this, "Fichier", "Vous avez ouvert le fichier :\n" + fichier);

    // on déclare la variable de type fichier, puis on l'ouvre en mode "lecture seule"
    QFile fichierACharger(fichier);
    fichierACharger.open(QIODevice::ReadOnly | QIODevice::Text);
    QTextStream flux (&fichierACharger);

    QString ligne;

    // On parcours ensuite le fichier ligne par ligne en y appliquant un traitement : ici affichage d'une messageBox
    while(! flux.atEnd())
    {
        ligne = flux.readLine();

        QMessageBox msg;
        msg.setText(ligne);
        msg.exec();
    }
}

void MainWindow::LoadPartyMulti()
{
    QMessageBox msg;
    msg.setText("Vous venez de charger une partie multi.");
    msg.exec();
    ui->statusBar->showMessage("Vous avez chargé une partie multijoueur.", 15000);
}

void MainWindow::SavePartySolo()
{
    // On ouvre une boite de dialogue permettant la sauvegarde d'un fichier
    QString fichier = QFileDialog::getSaveFileName(this, "Enregistrer un fichier", QString("*.txt"), "Fichiers texte (*.txt);; Tous les fichiers (*.*)");

    // Message d'information provisoire indiquant le chemin d'accès du fichier créé
    QMessageBox::information(this, "Fichier", "Vous avez sauvegardé le fichier :\n" + fichier);

     ui->statusBar->showMessage("Vous avez sauvegardé la partie solo.", 15000);
}

void MainWindow::Quit()
{
    if (QMessageBox::Yes == QMessageBox(QMessageBox::Warning, "Confirmation de sortie.", "Êtes-vous sûr de vouloir quitter BomberMan ?", QMessageBox::Yes|QMessageBox::No).exec())
    {
        exit(true);
    }
}

void MainWindow::GameControls()
{
    ParamWindows* paramForm;
    paramForm = new ParamWindows(this, 2);
    paramForm->show();
}

void MainWindow::DisplaySetting()
{
    ParamWindows* paramForm;
    paramForm = new ParamWindows(this, 1);
    paramForm->show();
}

void MainWindow::AudioSetting()
{
    ParamWindows* paramForm;
    paramForm = new ParamWindows(this, 0);
    paramForm->show();
}

void MainWindow::Help()
{
    QString texte;
<<<<<<>>>>>> master
    if(fichier.open(QIODevice::ReadOnly | QIODevice::Text))
    {
        texte = fichier.readAll();
        QMessageBox msgHelp;
        msgHelp.setGeometry(10,100,400,200);
        msgHelp.information(this, "Fichier d'aide : ", texte);

        fichier.close();
        ui->statusBar->showMessage("Vous venez de fermer le fichier d'Aide.", 15000);
    }
    else
    {
        // Tu veux du commentaire ! je vais t'en mettre ...
        // Modifié par Yann le 26 février 2014 car cela ne fonctionnait pas !!!!
        // Banzai !!!!!!!!!
        QMessageBox msg; //déclaration d'une variable msg de type QMessageBox
        msg.setText("Impossible d'ouvrir le fichier !"); // Modification de la variable avec du texte !
        msg.exec(); // Affichage de la QMessageBox pour le mec qui a besoin d'aide ;-)
        // Fin du commentaire par Yann
    }

}

void MainWindow::Credits()
{
    /*QMessageBox msg;
    msg.setText("Vous venez d'ouvrir les configurations audio.");
    msg.exec();*/

    QMessageBox::about(this, tr("BomberMAN"),
                 tr("The BomberMAN  is a strategic, maze-based video game franchise originally developed by Hudson Soft. The original game was published in 1983 and new games have been published at irregular intervals ever since.                Several titles in the 2000s were published by fellow Japanese game company Konami, who gained full control of the franchise when they purchased and absorbed Hudson in 2012. Today, Bomberman has featured in over 70 different games on numerous platforms (including all Nintendo platforms save for the 3DS and Wii U), as well as several anime and manga.His franchise is one of the most commercially successful of all time.
Realised by the Dream-Team :

Petra Kratochvilova

Thibaud Cutullic

Yoann Solacroup

Yann Damon

Gregoire Quincy

Roman Logvinov

Damien Moro
"));
}

void MainWindow::Statistics()
{
    windowstatistics* Stats;
    Stats = new windowstatistics(this);
    Stats->setGeometry(50,100,490,190);
    Stats->exec();
    ui->statusBar->showMessage("Vous avez consulté les statistics.", 15000);
}

<|endoftext|>


<commit_before>#include "vmas.h"
#include "debug.h"
#include <stdlib.h>
#include <string.h>

VMAddrSpace::VMAddrSpace() {
    stack = NULL;
    code = NULL;
    data = NULL;
    stacksize = DEFAULT_STACKSIZE;
    codesize = DEFAULT_CODESIZE;
    datasize = DEFAULT_DATASIZE;
    allocate();
    return;
}

VMAddrSpace::VMAddrSpace(uint32_t ss, uint32_t cs, uint32_t ds) {
    stack = NULL;
    code = NULL;
    data = NULL;
    stacksize = ss;
    codesize = cs;
    datasize = ds;
    allocate();
    return;
}

VMAddrSpace::~VMAddrSpace() {
    if (stack) {
        delete[] stack;
    }
    if (code) {
        delete[] code;
    }
    if (data) {
        delete[] data;
    }
    return;
}

bool VMAddrSpace::allocate(void) {
    DBG_INFO(("Allocating sections...\n"));

    DBG_INFO(("\tcode...\n"));
    code = new uint8_t[codesize];
    DBG_INFO(("\tdata...\n"));
    data = new uint8_t[datasize];
    DBG_INFO(("\tstack...\n"));
    stack = new uint8_t[stacksize];

    if (code == NULL) {
        DBG_ERROR(("Couldn't allocate code section.\n"));
        return false;
    }
    if (data == NULL) {
        DBG_ERROR(("Couldn't allocate data section.\n"));
        return false;
    }
    if (stack == NULL) {
        DBG_ERROR(("Couldn't allocate stack section.\n"));
        return false;
    }

    memset(code, 0x0, codesize);
    memset(stack, 0x0, stacksize);
    memset(data, 0x0, datasize);
    DBG_SUCC(("Done!\n"));
    return true;
}

bool VMAddrSpace::insCode(uint8_t *buf, uint32_t size) {
    if (code) {
        DBG_INFO(("Copying buffer into code section.\n"));
        memcpy(code, buf, size);
    } else {
        DBG_ERROR(("Couldn't write into code section.\n"));
        return false;
    }
    return true;
}

bool VMAddrSpace::insStack(uint8_t *buf, uint32_t size) {
    if (stack) {
        DBG_INFO(("Copying buffer into stack section.\n"));
        memcpy(stack, buf, size);
    } else {
        DBG_ERROR(("Couldn't write into stack section.\n"));
        return false;
    }
    return true;
}

bool VMAddrSpace::insData(uint8_t *buf, uint32_t size) {
    if (this->code) {
        DBG_INFO(("Copying buffer into data section.\n"));
        memcpy(data, buf, size);
    } else {
        DBG_ERROR(("Couldn't write into data section.\n"));
        return false;
    }
    return true;
}

uint32_t VMAddrSpace::getStacksize() const {
    return stacksize;
}

uint32_t VMAddrSpace::getCodesize() const {
    return codesize;
}

uint32_t VMAddrSpace::getDatasize() const {
    return datasize;
}
<commit_msg>Injected data/stack/code size check<commit_after>#include "vmas.h"
#include "debug.h"
#include <stdlib.h>
#include <string.h>

VMAddrSpace::VMAddrSpace() {
    stack = NULL;
    code = NULL;
    data = NULL;
    stacksize = DEFAULT_STACKSIZE;
    codesize = DEFAULT_CODESIZE;
    datasize = DEFAULT_DATASIZE;
    allocate();
    return;
}

VMAddrSpace::VMAddrSpace(uint32_t ss, uint32_t cs, uint32_t ds) {
    stack = NULL;
    code = NULL;
    data = NULL;
    stacksize = ss;
    codesize = cs;
    datasize = ds;
    allocate();
    return;
}

VMAddrSpace::~VMAddrSpace() {
    if (stack) {
        delete[] stack;
    }
    if (code) {
        delete[] code;
    }
    if (data) {
        delete[] data;
    }
    return;
}

bool VMAddrSpace::allocate(void) {
    DBG_INFO(("Allocating sections...\n"));

    DBG_INFO(("\tcode...\n"));
    code = new uint8_t[codesize];
    DBG_INFO(("\tdata...\n"));
    data = new uint8_t[datasize];
    DBG_INFO(("\tstack...\n"));
    stack = new uint8_t[stacksize];

    if (code == NULL) {
        DBG_ERROR(("Couldn't allocate code section.\n"));
        return false;
    }
    if (data == NULL) {
        DBG_ERROR(("Couldn't allocate data section.\n"));
        return false;
    }
    if (stack == NULL) {
        DBG_ERROR(("Couldn't allocate stack section.\n"));
        return false;
    }

    memset(code, 0x0, codesize);
    memset(stack, 0x0, stacksize);
    memset(data, 0x0, datasize);
    DBG_SUCC(("Done!\n"));
    return true;
}

bool VMAddrSpace::insCode(uint8_t *buf, uint32_t size) {
    if (code) {
        if (size > codesize) {
            DBG_ERROR(("The injected code size is too big!\n"));
            return false;
        }
        DBG_INFO(("Copying buffer into code section.\n"));
        memcpy(code, buf, size);
    } else {
        DBG_ERROR(("Couldn't write into code section.\n"));
        return false;
    }
    return true;
}

bool VMAddrSpace::insStack(uint8_t *buf, uint32_t size) {
    if (stack) {
        if (size > stacksize) {
            DBG_ERROR(("The injected stack size is too big!\n"));
            return false;
        }
        DBG_INFO(("Copying buffer into stack section.\n"));
        memcpy(stack, buf, size);
    } else {
        DBG_ERROR(("Couldn't write into stack section.\n"));
        return false;
    }
    return true;
}

bool VMAddrSpace::insData(uint8_t *buf, uint32_t size) {
    if (data) {
        if (size > datasize) {
            DBG_ERROR(("The injected data size is too big!\n"));
            return false;
        }
        DBG_INFO(("Copying buffer into data section.\n"));
        memcpy(data, buf, size);
    } else {
        DBG_ERROR(("Couldn't write into data section.\n"));
        return false;
    }
    return true;
}

uint32_t VMAddrSpace::getStacksize() const {
    return stacksize;
}

uint32_t VMAddrSpace::getCodesize() const {
    return codesize;
}

uint32_t VMAddrSpace::getDatasize() const {
    return datasize;
}
<|endoftext|>


<commit_before>#include "photoeffects.hpp"

using namespace cv;

int fadeColor(cv::InputArray src, cv::OutputArray dst)
{
    return image.rows*image.cols;
}
<commit_msg>edit errors<commit_after>#include "photoeffects.hpp"

using namespace cv;

int fadeColor(cv::InputArray src, cv::OutputArray dst)
{
    return src.rows*src.cols;
}
<|endoftext|>