<commit_before>// //////////////////////////////////////////////////////////////////////
// Import section
// //////////////////////////////////////////////////////////////////////
// STL
#include <cassert>
#include <sstream>
// Boost Date-Time
#include <boost/date_time/gregorian/formatters.hpp>
// Boost.Serialization
#include <boost/archive/text_iarchive.hpp>
#include <boost/archive/text_oarchive.hpp>
#include <boost/serialization/access.hpp>
// StdAir
#include <stdair/basic/BasConst_Inventory.hpp>
#include <stdair/basic/BasConst_BomDisplay.hpp>
#include <stdair/basic/BasConst_General.hpp>
#include <stdair/bom/OnDDateKey.hpp>
#include <stdair/bom/BomKeyManager.hpp>
#include <stdair/bom/Inventory.hpp>
#include <stdair/bom/FlightDate.hpp>
#include <stdair/bom/SegmentDate.hpp>
#include <stdair/bom/BomDisplay.hpp>

namespace stdair {

  // ////////////////////////////////////////////////////////////////////
  OnDDateKey::OnDDateKey()
    : _OnDStringList (DEFAULT_OND_STRING_LIST) {
    assert (false);
  }

  // ////////////////////////////////////////////////////////////////////
  OnDDateKey::OnDDateKey (const OnDStringList_T& iOnDStringList)
    : _OnDStringList (iOnDStringList) {
  }

  // ////////////////////////////////////////////////////////////////////
  OnDDateKey::OnDDateKey (const OnDDateKey& iKey)
    : _OnDStringList (iKey._OnDStringList) {
  }

  // ////////////////////////////////////////////////////////////////////
  OnDDateKey::~OnDDateKey() {
  }

  // ////////////////////////////////////////////////////////////////////
  const Date_T OnDDateKey::getDate() const {
    assert(!_OnDStringList.empty());
    OnDString_T lFrontOnDString = _OnDStringList.front();
    return BomKeyManager::extractFlightDateKey (lFrontOnDString).getDepartureDate();
  }

  // ////////////////////////////////////////////////////////////////////
  const AirportCode_T OnDDateKey::getOrigin() const {
    assert(!_OnDStringList.empty());
    OnDString_T lFrontOnDString = _OnDStringList.front();
    return BomKeyManager::extractSegmentDateKey (lFrontOnDString).getBoardingPoint();
  }

  // ////////////////////////////////////////////////////////////////////
  const AirportCode_T OnDDateKey::getDestination() const {
    assert(!_OnDStringList.empty());
    OnDString_T lLastOnDString = _OnDStringList.back();
    return BomKeyManager::extractSegmentDateKey (lLastOnDString).getOffPoint();
  }

  // ////////////////////////////////////////////////////////////////////
  void OnDDateKey::toStream (std::ostream& ioOut) const {
    ioOut << "OnDDateKey: " << toString();
  }

  // ////////////////////////////////////////////////////////////////////
  void OnDDateKey::fromStream (std::istream& ioIn) {
  }

  // ////////////////////////////////////////////////////////////////////
  const std::string OnDDateKey::toString() const {
    std::ostringstream oStr;
    for (OnDStringList_T::const_iterator itOnDString = _OnDStringList.begin();
         itOnDString != _OnDStringList.end(); ++itOnDString){
      oStr << *itOnDString << " ";
    }
    return oStr.str();
  }

  // ////////////////////////////////////////////////////////////////////
  void OnDDateKey::serialisationImplementation() {
    std::ostringstream oStr;
    boost::archive::text_oarchive oa (oStr);
    oa << *this;

    std::istringstream iStr;
    boost::archive::text_iarchive ia (iStr);
    ia >> *this;
  }

  // ////////////////////////////////////////////////////////////////////
  template<class Archive>
  void OnDDateKey::serialize (Archive& ioArchive,
                              const unsigned int iFileVersion) {
    /**
     * \note The serialised member should not be const (as, as far as
     *       I understand, they are tracked by Boost.Serialisation).
     */

  }

  // ////////////////////////////////////////////////////////////////////
  // Explicit template instantiation
  namespace ba = boost::archive;
  template void OnDDateKey::serialize<ba::text_oarchive> (ba::text_oarchive&,
                                                             unsigned int);
  template void OnDDateKey::serialize<ba::text_iarchive> (ba::text_iarchive&,
                                                             unsigned int);
  // ////////////////////////////////////////////////////////////////////

}
<commit_msg>[Dev] Declared a few variables as constant references in OnDDateKey.cpp.<commit_after>// //////////////////////////////////////////////////////////////////////
// Import section
// //////////////////////////////////////////////////////////////////////
// STL
#include <cassert>
#include <sstream>
// Boost Date-Time
#include <boost/date_time/gregorian/formatters.hpp>
// Boost.Serialization
#include <boost/archive/text_iarchive.hpp>
#include <boost/archive/text_oarchive.hpp>
#include <boost/serialization/access.hpp>
// StdAir
#include <stdair/basic/BasConst_Inventory.hpp>
#include <stdair/basic/BasConst_BomDisplay.hpp>
#include <stdair/basic/BasConst_General.hpp>
#include <stdair/bom/OnDDateKey.hpp>
#include <stdair/bom/BomKeyManager.hpp>
#include <stdair/bom/Inventory.hpp>
#include <stdair/bom/FlightDate.hpp>
#include <stdair/bom/SegmentDate.hpp>
#include <stdair/bom/BomDisplay.hpp>

namespace stdair {

  // ////////////////////////////////////////////////////////////////////
  OnDDateKey::OnDDateKey()
    : _OnDStringList (DEFAULT_OND_STRING_LIST) {
    assert (false);
  }

  // ////////////////////////////////////////////////////////////////////
  OnDDateKey::OnDDateKey (const OnDStringList_T& iOnDStringList)
    : _OnDStringList (iOnDStringList) {
  }

  // ////////////////////////////////////////////////////////////////////
  OnDDateKey::OnDDateKey (const OnDDateKey& iKey)
    : _OnDStringList (iKey._OnDStringList) {
  }

  // ////////////////////////////////////////////////////////////////////
  OnDDateKey::~OnDDateKey() {
  }

  // ////////////////////////////////////////////////////////////////////
  const Date_T OnDDateKey::getDate() const {
    assert(_OnDStringList.empty() == false);
    const OnDString_T& lFrontOnDString = _OnDStringList.front();
    return BomKeyManager::extractFlightDateKey (lFrontOnDString).getDepartureDate();
  }

  // ////////////////////////////////////////////////////////////////////
  const AirportCode_T OnDDateKey::getOrigin() const {
    assert(_OnDStringList.empty() == false);
    const OnDString_T& lFrontOnDString = _OnDStringList.front();
    return BomKeyManager::extractSegmentDateKey (lFrontOnDString).getBoardingPoint();
  }

  // ////////////////////////////////////////////////////////////////////
  const AirportCode_T OnDDateKey::getDestination() const {
    assert(_OnDStringList.empty() == false);
    const OnDString_T& lLastOnDString = _OnDStringList.back();
    return BomKeyManager::extractSegmentDateKey (lLastOnDString).getOffPoint();
  }

  // ////////////////////////////////////////////////////////////////////
  void OnDDateKey::toStream (std::ostream& ioOut) const {
    ioOut << "OnDDateKey: " << toString();
  }

  // ////////////////////////////////////////////////////////////////////
  void OnDDateKey::fromStream (std::istream& ioIn) {
  }

  // ////////////////////////////////////////////////////////////////////
  const std::string OnDDateKey::toString() const {
    std::ostringstream oStr;
    for (OnDStringList_T::const_iterator itOnDString = _OnDStringList.begin();
         itOnDString != _OnDStringList.end(); ++itOnDString){
      oStr << *itOnDString << " ";
    }
    return oStr.str();
  }

  // ////////////////////////////////////////////////////////////////////
  void OnDDateKey::serialisationImplementation() {
    std::ostringstream oStr;
    boost::archive::text_oarchive oa (oStr);
    oa << *this;

    std::istringstream iStr;
    boost::archive::text_iarchive ia (iStr);
    ia >> *this;
  }

  // ////////////////////////////////////////////////////////////////////
  template<class Archive>
  void OnDDateKey::serialize (Archive& ioArchive,
                              const unsigned int iFileVersion) {
    /**
     * \note The serialised member should not be const (as, as far as
     *       I understand, they are tracked by Boost.Serialisation).
     */

  }

  // ////////////////////////////////////////////////////////////////////
  // Explicit template instantiation
  namespace ba = boost::archive;
  template void OnDDateKey::serialize<ba::text_oarchive> (ba::text_oarchive&,
                                                             unsigned int);
  template void OnDDateKey::serialize<ba::text_iarchive> (ba::text_iarchive&,
                                                             unsigned int);
  // ////////////////////////////////////////////////////////////////////

}
<|endoftext|>


<commit_before>//
// Clutter.cpp
// Clutter
//
// Created by PM Bult on 24-01-2016
// Copyright (c) P.M. Bult. All rights reserved.
//
// Version 1.0
//

#include "Clutter.h"
#include "Utils.h"

namespace Clutter {

    //
    // Constructor
    //
    Clutter::Clutter( int argc, const char* argv[] )
    {
        // Initialize processing variables
        string              flag;
        string              tag;
        std::vector<string> values;

        // Loop over all tags in the command line
        for (int i = 1; i < argc; ++i) {
            // Convert the current entry to a tag
            string flag = string( argv[i] );

            // Ensure the tag is a flag-type
            if ( Utils::isValue( flag ) )
                throw "error: parsing error";

            // Ensure the flag does not alread exist
            if ( mCommandMap.count( flag ) > 0 )
                throw "error: duplicate flag";

            // Find the next flag (or the end of list)
            for (i++; i < argc; i++) {
                // Load the next tag
                tag = string( argv[i] );
                // Test of tag type
                if ( Utils::isFlag( tag ) ) break;                      // flag found: block is complete
                else                        values.push_back( tag );    // value found: add to current block
            }

            // Store the tag & values as a block
            mCommandMap.emplace( flag, CommandBlock(values) );

            // Clear the processing memory
            values.clear();

            // Continue with next block
            // ...
        }

        // Set help flag
        if ( this->has_flag("-h") || this->has_flag("--help") ) {
            mHelpFlag = true;
        }
    }

    //
    // Support function
    //
    bool Clutter::has_flag( string flag )
    {
        if ( mCommandMap.count( flag ) == 1 )
            return true;
        else
            return false;
    }

    //
    // Parse termination function
    //
    void Clutter::end_parse()
    {
        // Check the help flag
        if ( mHelpFlag ) {
            printf( "Required arguments:\n" );
            for ( auto& block : mHelpTree_required )
                block.print();

            printf( "Optional arguments:\n" );
            for ( auto& block : mHelpTree_requested )
                block.print();

            exit(0);
        }

        // Check orphan options
        for ( auto& block : mCommandMap ) {
            if ( !block.processed ) {
                throw "error: orphan options";
            }
        }
    }
}

<commit_msg>Fix CommandMap iterator<commit_after>//
// Clutter.cpp
// Clutter
//
// Created by PM Bult on 24-01-2016
// Copyright (c) P.M. Bult. All rights reserved.
//
// Version 1.0
//

#include "Clutter.h"
#include "Utils.h"

namespace Clutter {

    //
    // Constructor
    //
    Clutter::Clutter( int argc, const char* argv[] )
    {
        // Initialize processing variables
        string              flag;
        string              tag;
        std::vector<string> values;

        // Loop over all tags in the command line
        for (int i = 1; i < argc; ++i) {
            // Convert the current entry to a tag
            string flag = string( argv[i] );

            // Ensure the tag is a flag-type
            if ( Utils::isValue( flag ) )
                throw "error: parsing error";

            // Ensure the flag does not alread exist
            if ( mCommandMap.count( flag ) > 0 )
                throw "error: duplicate flag";

            // Find the next flag (or the end of list)
            for (i++; i < argc; i++) {
                // Load the next tag
                tag = string( argv[i] );
                // Test of tag type
                if ( Utils::isFlag( tag ) ) break;                      // flag found: block is complete
                else                        values.push_back( tag );    // value found: add to current block
            }

            // Store the tag & values as a block
            mCommandMap.emplace( flag, CommandBlock(values) );

            // Clear the processing memory
            values.clear();

            // Continue with next block
            // ...
        }

        // Set help flag
        if ( this->has_flag("-h") || this->has_flag("--help") ) {
            mHelpFlag = true;
        }
    }

    //
    // Support function
    //
    bool Clutter::has_flag( string flag )
    {
        if ( mCommandMap.count( flag ) == 1 )
            return true;
        else
            return false;
    }

    //
    // Parse termination function
    //
    void Clutter::end_parse()
    {
        // Check the help flag
        if ( mHelpFlag ) {
            printf( "Required arguments:\n" );
            for ( auto& block : mHelpTree_required )
                block.print();

            printf( "Optional arguments:\n" );
            for ( auto& block : mHelpTree_requested )
                block.print();

            exit(0);
        }

        // Check orphan options
        for ( auto& map : mCommandMap ) {
            if ( !map.second.processed ) {
                throw "error: orphan options";
            }
        }
    }
}

<|endoftext|>


<commit_before>// Clutter.cpp | Created on 24-01-2016
//
// Copyright (c) 2016 P.M. Bult
// This work is provided under the MIT license

#include <algorithm>

#include "Clutter.h"
#include "Utils.h"

namespace Clutter {

    //
    // Constructor
    //
    Clutter::Clutter( int argc, const char* argv[] )
    {
        // Initialize processing variables
        string              flag;
        string              argument;
        std::vector<string> values;

        // Store the executable name
        mExecutable = string( argv[0] );

        // Loop over all arguments in the command line
        // ~> Skip the executable name
        for (int i = 1; i < argc; ++i) {
            // Convert the current argument to a flag
            string flag = string( argv[i] );

            // Ensure the argument is indeed flag-type
            if ( Utils::isValue( flag ) )
                throw "parse error: invalid command line: option has no flag";

            // Ensure the flag does not alread exist
            if ( this->has_flag( flag ) )
                throw std::runtime_error("parse error: duplicate flag: " + flag);

            // Find the next flag (or the end of list)
            for (i++; i < argc; i++) {
                // Load the next argument
                argument = string( argv[i] );
                // Test the argument type
                if ( Utils::isFlag( argument ) ) { i--; break; }    // flag found: block is complete
                else values.push_back( argument );                  // value found: add to current block
            }

            // Store the flag & values as a CommandBlock
            mCommandMap.emplace( flag, CommandBlock(values) );

            // Clear the processing memory
            values.clear();

            // Continue with next block
            // ...
        }

        // Set help flag
        if ( this->has_flag("-h") || this->has_flag("--help") ) {
            mHelpFlag = true;
        }
    }

    //
    // Support function
    //
    bool Clutter::has_flag( string flag )
    {
        if ( mCommandMap.count( flag ) == 1 )
            return true;
        else
            return false;
    }

    bool Clutter::help_has_flag( string tag, string label )
    {
        // Search the required tree
        for ( auto& block : mHelpTree_required ) {
            if ( !block.tag.empty() && block.tag.compare(tag) == 0 )
                return true;

            if ( !block.label.empty() && block.label.compare(label) == 0 )
                return true;
        }

        // Search the requested tree
        for ( auto& block : mHelpTree_requested ) {
            if ( !block.tag.empty() && block.tag.compare(tag) == 0 )
                return true;

            if ( !block.label.empty() && block.label.compare(label) == 0 )
                return true;
        }

        // Flag not found
        return false;
    }

    Clutter::MapIterator Clutter::find_flag( string tag, string label )
    {
        // Search the Command Map for the tag position
        auto it_tag = mCommandMap.find( tag );

        // Search the Command Map for the label position
        auto it_label = mCommandMap.find( label );

        // Initialize final flag position
        auto it = mCommandMap.end();

        // Safeguard: check if tag and/or label are found
        if ( this->has_flag(tag) && this->has_flag(label) )
            // Duplicate flag in command line
            throw std::runtime_error("parse error: duplicate flag: " + tag + "/" + label);

        if ( it_tag == mCommandMap.end() && it_label == mCommandMap.end() )
            // Flag is missing
            return mCommandMap.end();

        if ( it_tag != mCommandMap.end() )
            // Set tag for processing
            return it_tag;

        if ( it_label != mCommandMap.end() )
            // Set label for processing
            return it_label;

        // Default exit: should not occur
        return it;
    }

    //
    // Parse templace specializations
    //
    // -> Boolian specialization
    template <>
        void Clutter::parse( bool& value, CommandBlock &block )
        {
            // Test block size
            if ( block.size() > 0 )
                throw std::runtime_error("orphan argument: " + block.values[0] );
                // printf( "warning: orhpan value\n" );

            // Flip value
            value = !value;

            // Mark as processed
            block.processed = true;
        }

    // -> String specialization
    template <>
        void Clutter::parse( string& value, CommandBlock &block )
        {
            // Test block size
            if ( block.size() == 0 )
                throw std::runtime_error("flag argument missing");
            if ( block.size() > 1 )
                throw std::runtime_error("orphan argument: " + block.values[1] );
                // printf( "warning: orhpan value\n" );

            // Flip value
            value = block.values[0];

            // Mark as processed
            block.processed = true;
        }

    //
    // Parse termination function
    //
    void Clutter::end_parse()
    {
        // Check the help flag
        if ( mHelpFlag ) {
            // Print the help table
            print_help();

            // Terminate program
            exit(0);
        }

        // Check orphan options
        for ( auto& map : mCommandMap ) {
            if ( !map.second.processed ) {
                throw std::runtime_error("parse error: unprocessed flag: " + map.first);
            }
        }
    }

    //
    // Redial function: store parameters to file
    //
    void Clutter::redial( std::string filename )
    {
        // Create the redial file
        FILE *os = fopen( filename.c_str(), "w" );

        // Set the program name
        fprintf( os, "%s ", mExecutable.c_str() );

        // Print the command map
        for ( auto& map : mCommandMap ) {
            // Print the key
            fprintf( os, "%s ", map.first.c_str() );
            // Print the values
            for ( auto& v : map.second.values )
                 fprintf( os, "%s ", v.c_str() );
        }
        // End the command line
        fprintf( os, "\n" );

        // Close the file stream
        fclose(os);
    }

    //
    // Print help table
    //
    void Clutter::print_help()
    {
        // Resolve label width
        unsigned long max_width = 0;

        // Search the required tree
        for ( auto& block : mHelpTree_required )
             max_width = std::max( max_width, block.label.size() );

        // Search the requested tree
        for ( auto& block : mHelpTree_requested )
             max_width = std::max( max_width, block.label.size() );

        // Add two characters
        max_width = std::max( (unsigned long)(16), max_width+2 );

        // Print the help table
        printf( "Required arguments:\n" );
        for ( auto& block : mHelpTree_required )
            block.print( 6, max_width );

        printf( "Optional arguments:\n" );
        for ( auto& block : mHelpTree_requested )
            block.print( 6, max_width );
    }
}
<commit_msg>Fix help print format<commit_after>// Clutter.cpp | Created on 24-01-2016
//
// Copyright (c) 2016 P.M. Bult
// This work is provided under the MIT license

#include <algorithm>

#include "Clutter.h"
#include "Utils.h"

namespace Clutter {

    //
    // Constructor
    //
    Clutter::Clutter( int argc, const char* argv[] )
    {
        // Initialize processing variables
        string              flag;
        string              argument;
        std::vector<string> values;

        // Store the executable name
        mExecutable = string( argv[0] );

        // Loop over all arguments in the command line
        // ~> Skip the executable name
        for (int i = 1; i < argc; ++i) {
            // Convert the current argument to a flag
            string flag = string( argv[i] );

            // Ensure the argument is indeed flag-type
            if ( Utils::isValue( flag ) )
                throw "parse error: invalid command line: option has no flag";

            // Ensure the flag does not alread exist
            if ( this->has_flag( flag ) )
                throw std::runtime_error("parse error: duplicate flag: " + flag);

            // Find the next flag (or the end of list)
            for (i++; i < argc; i++) {
                // Load the next argument
                argument = string( argv[i] );
                // Test the argument type
                if ( Utils::isFlag( argument ) ) { i--; break; }    // flag found: block is complete
                else values.push_back( argument );                  // value found: add to current block
            }

            // Store the flag & values as a CommandBlock
            mCommandMap.emplace( flag, CommandBlock(values) );

            // Clear the processing memory
            values.clear();

            // Continue with next block
            // ...
        }

        // Set help flag
        if ( this->has_flag("-h") || this->has_flag("--help") ) {
            mHelpFlag = true;
        }
    }

    //
    // Support function
    //
    bool Clutter::has_flag( string flag )
    {
        if ( mCommandMap.count( flag ) == 1 )
            return true;
        else
            return false;
    }

    bool Clutter::help_has_flag( string tag, string label )
    {
        // Search the required tree
        for ( auto& block : mHelpTree_required ) {
            if ( !block.tag.empty() && block.tag.compare(tag) == 0 )
                return true;

            if ( !block.label.empty() && block.label.compare(label) == 0 )
                return true;
        }

        // Search the requested tree
        for ( auto& block : mHelpTree_requested ) {
            if ( !block.tag.empty() && block.tag.compare(tag) == 0 )
                return true;

            if ( !block.label.empty() && block.label.compare(label) == 0 )
                return true;
        }

        // Flag not found
        return false;
    }

    Clutter::MapIterator Clutter::find_flag( string tag, string label )
    {
        // Search the Command Map for the tag position
        auto it_tag = mCommandMap.find( tag );

        // Search the Command Map for the label position
        auto it_label = mCommandMap.find( label );

        // Initialize final flag position
        auto it = mCommandMap.end();

        // Safeguard: check if tag and/or label are found
        if ( this->has_flag(tag) && this->has_flag(label) )
            // Duplicate flag in command line
            throw std::runtime_error("parse error: duplicate flag: " + tag + "/" + label);

        if ( it_tag == mCommandMap.end() && it_label == mCommandMap.end() )
            // Flag is missing
            return mCommandMap.end();

        if ( it_tag != mCommandMap.end() )
            // Set tag for processing
            return it_tag;

        if ( it_label != mCommandMap.end() )
            // Set label for processing
            return it_label;

        // Default exit: should not occur
        return it;
    }

    //
    // Parse templace specializations
    //
    // -> Boolian specialization
    template <>
        void Clutter::parse( bool& value, CommandBlock &block )
        {
            // Test block size
            if ( block.size() > 0 )
                throw std::runtime_error("orphan argument: " + block.values[0] );
                // printf( "warning: orhpan value\n" );

            // Flip value
            value = !value;

            // Mark as processed
            block.processed = true;
        }

    // -> String specialization
    template <>
        void Clutter::parse( string& value, CommandBlock &block )
        {
            // Test block size
            if ( block.size() == 0 )
                throw std::runtime_error("flag argument missing");
            if ( block.size() > 1 )
                throw std::runtime_error("orphan argument: " + block.values[1] );
                // printf( "warning: orhpan value\n" );

            // Flip value
            value = block.values[0];

            // Mark as processed
            block.processed = true;
        }

    //
    // Parse termination function
    //
    void Clutter::end_parse()
    {
        // Check the help flag
        if ( mHelpFlag ) {
            // Print the help table
            print_help();

            // Terminate program
            exit(0);
        }

        // Check orphan options
        for ( auto& map : mCommandMap ) {
            if ( !map.second.processed ) {
                throw std::runtime_error("parse error: unprocessed flag: " + map.first);
            }
        }
    }

    //
    // Redial function: store parameters to file
    //
    void Clutter::redial( std::string filename )
    {
        // Create the redial file
        FILE *os = fopen( filename.c_str(), "w" );

        // Set the program name
        fprintf( os, "%s ", mExecutable.c_str() );

        // Print the command map
        for ( auto& map : mCommandMap ) {
            // Print the key
            fprintf( os, "%s ", map.first.c_str() );
            // Print the values
            for ( auto& v : map.second.values )
                 fprintf( os, "%s ", v.c_str() );
        }
        // End the command line
        fprintf( os, "\n" );

        // Close the file stream
        fclose(os);
    }

    //
    // Print help table
    //
    void Clutter::print_help()
    {
        // Resolve label width
        unsigned long max_width = 0;

        // Search the required tree
        for ( auto& block : mHelpTree_required )
             max_width = std::max( max_width, block.label.size() );

        // Search the requested tree
        for ( auto& block : mHelpTree_requested )
             max_width = std::max( max_width, block.label.size() );

        // Add two characters
        max_width = std::max( (unsigned long)(16), max_width+2 );

        // Print the help table
        if ( mHelpTree_required.size() > 0 )
            printf( "Required arguments:\n" );
        for ( auto& block : mHelpTree_required )
            block.print( 6, max_width );

        if ( mHelpTree_requested.size() > 0 )
            printf( "Optional arguments:\n" );
        for ( auto& block : mHelpTree_requested )
            block.print( 6, max_width );

        std::cout << std::endl;
    }
}
<|endoftext|>


<commit_before>// -*- mode: c++, coding: utf-8 -*-
/**
 * tbrpg – Text based roll playing game
 *
 * Copyright © 2012  Mattias Andrée (maandree@kth.se)
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
#include "Creature.hpp"

/**
 * Text based roll playing game
 *
 * DD2387 Program construction with C++
 * Laboration 3
 *
 * @author  Mattias Andrée <maandree@kth.se>
 */
namespace tbrpg
{
  /**
   * Constructor
   */
  Creature::Creature() : Character()
  {
    this->class_inheritance.push_back(69);
    ////TODO implement constructor
    //this->hostile = false;
    //this->x = 0;
    //this->y = 0;
    //this->alive = false;
    //this->resurrect = false;
    //this->experience = 0;
  }

  /**
   * Copy constructor
   *
   * @param  original  The object to clone
   */
  Creature::Creature(const Creature& original) : Character(original)
  {
    (void) original;
    this->hostile = original.hostile;
    this->x = original.x;
    this->y = original.y;
    this->alive = original.alive;
    this->resurrect = original.resurrect;
    this->experience = original.experience;
  }

  /**
   * Copy constructor
   *
   * @param  original  The object to clone
   */
  Creature::Creature(Creature& original) : Character(original)
  {
    (void) original;
    this->hostile = original.hostile;
    this->x = original.x;
    this->y = original.y;
    this->alive = original.alive;
    this->resurrect = original.resurrect;
    this->experience = original.experience;
  }

  /**
   * Move constructor
   *
   * @param  original  The object to clone
   */
  Creature::Creature(Creature&& original) : Character(original)
  {
    (void) original;
    std::swap(this->hostile, original.hostile);
    std::swap(this->x, original.x);
    std::swap(this->y, original.y);
    std::swap(this->alive, original.alive);
    std::swap(this->resurrect, original.resurrect);
    std::swap(this->experience, original.experience);
  }

  /**
   * Destructor
   */
  Creature::~Creature()
  {
    ////TODO implement destructor
  }

  /**
   * Assignment operator
   *
   * @param   original  The reference object
   * @return            The invoked object
   */
  Creature& Creature::operator =(const Creature& original)
  {
    (void) original;
    Character::__copy__((Character&)*this, (Character&)original);    this->hostile = original.hostile;
    this->x = original.x;
    this->y = original.y;
    this->alive = original.alive;
    this->resurrect = original.resurrect;
    this->experience = original.experience;
    return *this;
  }

  /**
   * Assignment operator
   *
   * @param   original  The reference object
   * @return            The invoked object
   */
  Creature& Creature::operator =(Creature& original)
  {
    (void) original;
    Character::__copy__((Character&)*this, (Character&)original);    this->hostile = original.hostile;
    this->x = original.x;
    this->y = original.y;
    this->alive = original.alive;
    this->resurrect = original.resurrect;
    this->experience = original.experience;
    return *this;
  }

  /**
   * Move operator
   *
   * @param   original  The moved object, its resourced will be moved
   * @return            The invoked object
   */
  Creature& Creature::operator =(Creature&& original)
  {
    (void) original;
    std::swap((Character&)*this, (Character&)original);    std::swap(this->hostile, original.hostile);
    std::swap(this->x, original.x);
    std::swap(this->y, original.y);
    std::swap(this->alive, original.alive);
    std::swap(this->resurrect, original.resurrect);
    std::swap(this->experience, original.experience);
    return *this;
  }

  /**
   * Equality evaluator
   *
   * @param   other  The other comparand
   * @return         Whether the instances are equal
   */
  bool Creature::operator ==(const Creature& other) const
  {
    return this == &other;
  }

  /**
   * Copy method
   *
   * @param  self      The object to modify
   * @param  original  The reference object
   */
  void Creature::__copy__(Creature& self, const Creature& original)
  {
    self = original;
  }

  /**
   * Hash method
   *
   * @return  The object's hash code
   */
  size_t Creature::hash() const
  {
    return (size_t)this;
  }

}

<commit_msg>default values for creatures<commit_after>// -*- mode: c++, coding: utf-8 -*-
/**
 * tbrpg – Text based roll playing game
 *
 * Copyright © 2012  Mattias Andrée (maandree@kth.se)
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
#include "Creature.hpp"

/**
 * Text based roll playing game
 *
 * DD2387 Program construction with C++
 * Laboration 3
 *
 * @author  Mattias Andrée <maandree@kth.se>
 */
namespace tbrpg
{
  /**
   * Constructor
   */
  Creature::Creature() : Character()
  {
    this->class_inheritance.push_back(69);
    this->experience = 1;
    this->hostile = true;
    this->x = 0;
    this->y = 0;
    this->alive = true;
    this->resurrect = true;
  }

  /**
   * Copy constructor
   *
   * @param  original  The object to clone
   */
  Creature::Creature(const Creature& original) : Character(original)
  {
    (void) original;
    this->hostile = original.hostile;
    this->x = original.x;
    this->y = original.y;
    this->alive = original.alive;
    this->resurrect = original.resurrect;
    this->experience = original.experience;
  }

  /**
   * Copy constructor
   *
   * @param  original  The object to clone
   */
  Creature::Creature(Creature& original) : Character(original)
  {
    (void) original;
    this->hostile = original.hostile;
    this->x = original.x;
    this->y = original.y;
    this->alive = original.alive;
    this->resurrect = original.resurrect;
    this->experience = original.experience;
  }

  /**
   * Move constructor
   *
   * @param  original  The object to clone
   */
  Creature::Creature(Creature&& original) : Character(original)
  {
    (void) original;
    std::swap(this->hostile, original.hostile);
    std::swap(this->x, original.x);
    std::swap(this->y, original.y);
    std::swap(this->alive, original.alive);
    std::swap(this->resurrect, original.resurrect);
    std::swap(this->experience, original.experience);
  }

  /**
   * Destructor
   */
  Creature::~Creature()
  {
    ////TODO implement destructor
  }

  /**
   * Assignment operator
   *
   * @param   original  The reference object
   * @return            The invoked object
   */
  Creature& Creature::operator =(const Creature& original)
  {
    (void) original;
    Character::__copy__((Character&)*this, (Character&)original);    this->hostile = original.hostile;
    this->x = original.x;
    this->y = original.y;
    this->alive = original.alive;
    this->resurrect = original.resurrect;
    this->experience = original.experience;
    return *this;
  }

  /**
   * Assignment operator
   *
   * @param   original  The reference object
   * @return            The invoked object
   */
  Creature& Creature::operator =(Creature& original)
  {
    (void) original;
    Character::__copy__((Character&)*this, (Character&)original);    this->hostile = original.hostile;
    this->x = original.x;
    this->y = original.y;
    this->alive = original.alive;
    this->resurrect = original.resurrect;
    this->experience = original.experience;
    return *this;
  }

  /**
   * Move operator
   *
   * @param   original  The moved object, its resourced will be moved
   * @return            The invoked object
   */
  Creature& Creature::operator =(Creature&& original)
  {
    (void) original;
    std::swap((Character&)*this, (Character&)original);    std::swap(this->hostile, original.hostile);
    std::swap(this->x, original.x);
    std::swap(this->y, original.y);
    std::swap(this->alive, original.alive);
    std::swap(this->resurrect, original.resurrect);
    std::swap(this->experience, original.experience);
    return *this;
  }

  /**
   * Equality evaluator
   *
   * @param   other  The other comparand
   * @return         Whether the instances are equal
   */
  bool Creature::operator ==(const Creature& other) const
  {
    return this == &other;
  }

  /**
   * Copy method
   *
   * @param  self      The object to modify
   * @param  original  The reference object
   */
  void Creature::__copy__(Creature& self, const Creature& original)
  {
    self = original;
  }

  /**
   * Hash method
   *
   * @return  The object's hash code
   */
  size_t Creature::hash() const
  {
    return (size_t)this;
  }

}

<|endoftext|>


<commit_before>// DepthOp.cpp
/*
 * Copyright (c) 2009, Dan Heeks
 * This program is released under the BSD license. See the file COPYING for
 * details.
 */

#include "stdafx.h"
#include "DepthOp.h"
#include "CNCConfig.h"
#include "ProgramCanvas.h"
#include "Program.h"
#include "interface/PropertyInt.h"
#include "interface/PropertyDouble.h"
#include "interface/PropertyLength.h"
#include "tinyxml/tinyxml.h"
#include "interface/Tool.h"

CDepthOpParams::CDepthOpParams()
{
	m_tool_number = 0;
	m_tool_diameter = 0.0;
	m_clearance_height = 0.0;
	m_start_depth = 0.0;
	m_step_down = 0.0;
	m_final_depth = 0.0;
	m_rapid_down_to_height = 0.0;
	m_horizontal_feed_rate = 0.0;
	m_vertical_feed_rate = 0.0;
	m_spindle_speed = 0.0;
}

void CDepthOpParams::set_initial_values()
{
	CNCConfig config;
    config.Read(_T("DepthFixtureOffset"), &m_workplane,1);
	config.Read(_T("DepthOpToolNumber"), &m_tool_number, 1);
	config.Read(_T("DepthOpToolDiameter"), &m_tool_diameter, 3.0);
	config.Read(_T("DepthOpClearanceHeight"), &m_clearance_height, 5.0);
	config.Read(_T("DepthOpStartDepth"), &m_start_depth, 0.0);
	config.Read(_T("DepthOpStepDown"), &m_step_down, 1.0);
	config.Read(_T("DepthOpFinalDepth"), &m_final_depth, -1.0);
	config.Read(_T("DepthOpRapidDown"), &m_rapid_down_to_height, 2.0);
	config.Read(_T("DepthOpHorizFeed"), &m_horizontal_feed_rate, 100.0);
	config.Read(_T("DepthOpVertFeed"), &m_vertical_feed_rate, 100.0);
	config.Read(_T("DepthOpSpindleSpeed"), &m_spindle_speed, 7000);
}

void CDepthOpParams::write_values_to_config()
{
	CNCConfig config;
	config.Write(_T("DepthFixtureOffset"), m_workplane);
	config.Write(_T("DepthOpToolNumber"), m_tool_number);
	config.Write(_T("DepthOpToolDiameter"), m_tool_diameter);
	config.Write(_T("DepthOpClearanceHeight"), m_clearance_height);
	config.Write(_T("DepthOpStartDepth"), m_start_depth);
	config.Write(_T("DepthOpStepDown"), m_step_down);
	config.Write(_T("DepthOpFinalDepth"), m_final_depth);
	config.Write(_T("DepthOpRapidDown"), m_rapid_down_to_height);
	config.Write(_T("DepthOpHorizFeed"), m_horizontal_feed_rate);
	config.Write(_T("DepthOpVertFeed"), m_vertical_feed_rate);
	config.Write(_T("DepthOpSpindleSpeed"), m_spindle_speed);
}

static void on_set_workplane(int value, HeeksObj* object){((CDepthOp*)object)->m_depth_op_params.m_workplane = value;}
static void on_set_tool_number(int value, HeeksObj* object){((CDepthOp*)object)->m_depth_op_params.m_tool_number = value;}
static void on_set_tool_diameter(double value, HeeksObj* object){((CDepthOp*)object)->m_depth_op_params.m_tool_diameter = value;}
static void on_set_clearance_height(double value, HeeksObj* object){((CDepthOp*)object)->m_depth_op_params.m_clearance_height = value;}
static void on_set_step_down(double value, HeeksObj* object){((CDepthOp*)object)->m_depth_op_params.m_step_down = value;}
static void on_set_start_depth(double value, HeeksObj* object){((CDepthOp*)object)->m_depth_op_params.m_start_depth = value;}
static void on_set_final_depth(double value, HeeksObj* object){((CDepthOp*)object)->m_depth_op_params.m_final_depth = value;}
static void on_set_rapid_down_to_height(double value, HeeksObj* object){((CDepthOp*)object)->m_depth_op_params.m_rapid_down_to_height = value;}
static void on_set_horizontal_feed_rate(double value, HeeksObj* object){((CDepthOp*)object)->m_depth_op_params.m_horizontal_feed_rate = value;}
static void on_set_vertical_feed_rate(double value, HeeksObj* object){((CDepthOp*)object)->m_depth_op_params.m_vertical_feed_rate = value;}
static void on_set_spindle_speed(double value, HeeksObj* object){((CDepthOp*)object)->m_depth_op_params.m_spindle_speed = value;}

void CDepthOpParams::GetProperties(CDepthOp* parent, std::list<Property *> *list)
{
	list->push_back(new PropertyInt(_("fixture offset"), m_workplane, parent, on_set_workplane));
	list->push_back(new PropertyInt(_("tool number"), m_tool_number, parent, on_set_tool_number));
	list->push_back(new PropertyLength(_("tool diameter"), m_tool_diameter, parent, on_set_tool_diameter));
	list->push_back(new PropertyLength(_("clearance height"), m_clearance_height, parent, on_set_clearance_height));
	list->push_back(new PropertyLength(_("step down"), m_step_down, parent, on_set_step_down));
	list->push_back(new PropertyLength(_("start depth"), m_start_depth, parent, on_set_start_depth));
	list->push_back(new PropertyLength(_("final depth"), m_final_depth, parent, on_set_final_depth));
	list->push_back(new PropertyLength(_("rapid down to height"), m_rapid_down_to_height, parent, on_set_rapid_down_to_height));
	list->push_back(new PropertyDouble(_("horizontal feed rate"), m_horizontal_feed_rate, parent, on_set_horizontal_feed_rate));
	list->push_back(new PropertyDouble(_("vertical feed rate"), m_vertical_feed_rate, parent, on_set_vertical_feed_rate));
	list->push_back(new PropertyDouble(_("spindle speed"), m_spindle_speed, parent, on_set_spindle_speed));
}

void CDepthOpParams::WriteXMLAttributes(TiXmlNode* pElem)
{
	TiXmlElement * element = new TiXmlElement( "depthop" );
	pElem->LinkEndChild( element );
	element->SetAttribute("fixture offset", m_workplane);
	element->SetAttribute("tooln", m_tool_number);
	element->SetDoubleAttribute("toold", m_tool_diameter);
	element->SetDoubleAttribute("clear", m_clearance_height);
	element->SetDoubleAttribute("down", m_step_down);
	element->SetDoubleAttribute("startdepth", m_start_depth);
	element->SetDoubleAttribute("depth", m_final_depth);
	element->SetDoubleAttribute("r", m_rapid_down_to_height);
	element->SetDoubleAttribute("hfeed", m_horizontal_feed_rate);
	element->SetDoubleAttribute("vfeed", m_vertical_feed_rate);
	element->SetDoubleAttribute("spin", m_spindle_speed);
}

void CDepthOpParams::ReadFromXMLElement(TiXmlElement* pElem)
{
	TiXmlElement* depthop = TiXmlHandle(pElem).FirstChildElement("depthop").Element();
	if(depthop)
	{

		depthop->Attribute("fixture offset", &m_workplane);
		depthop->Attribute("tooln", &m_tool_number);
		depthop->Attribute("toold", &m_tool_diameter);
		depthop->Attribute("clear", &m_clearance_height);
		depthop->Attribute("down", &m_step_down);
		depthop->Attribute("startdepth", &m_start_depth);
		depthop->Attribute("depth", &m_final_depth);
		depthop->Attribute("r", &m_rapid_down_to_height);
		depthop->Attribute("hfeed", &m_horizontal_feed_rate);
		depthop->Attribute("vfeed", &m_vertical_feed_rate);
		depthop->Attribute("spin", &m_spindle_speed);
	}
}

void CDepthOp::WriteBaseXML(TiXmlElement *element)
{
	m_depth_op_params.WriteXMLAttributes(element);
	COp::WriteBaseXML(element);
}

void CDepthOp::ReadBaseXML(TiXmlElement* element)
{
	m_depth_op_params.ReadFromXMLElement(element);
	COp::ReadBaseXML(element);
}

void CDepthOp::GetProperties(std::list<Property *> *list)
{
	m_depth_op_params.GetProperties(this, list);
	COp::GetProperties(list);
}

void CDepthOp::AppendTextToProgram()
{
	COp::AppendTextToProgram();

	theApp.m_program_canvas->AppendText(_T("clearance = float("));
	theApp.m_program_canvas->AppendText(m_depth_op_params.m_clearance_height / theApp.m_program->m_units);
	theApp.m_program_canvas->AppendText(_T(")\n"));
	theApp.m_program_canvas->AppendText(_T("rapid_down_to_height = float("));
	theApp.m_program_canvas->AppendText(m_depth_op_params.m_rapid_down_to_height / theApp.m_program->m_units);
	theApp.m_program_canvas->AppendText(_T(")\n"));
	theApp.m_program_canvas->AppendText(_T("start_depth = float("));
	theApp.m_program_canvas->AppendText(m_depth_op_params.m_start_depth / theApp.m_program->m_units);
	theApp.m_program_canvas->AppendText(_T(")\n"));
	theApp.m_program_canvas->AppendText(_T("step_down = float("));
	theApp.m_program_canvas->AppendText(m_depth_op_params.m_step_down / theApp.m_program->m_units);
	theApp.m_program_canvas->AppendText(_T(")\n"));
	theApp.m_program_canvas->AppendText(_T("final_depth = float("));
	theApp.m_program_canvas->AppendText(m_depth_op_params.m_final_depth / theApp.m_program->m_units);
	theApp.m_program_canvas->AppendText(_T(")\n"));
	theApp.m_program_canvas->AppendText(_T("tool_diameter = float("));
	theApp.m_program_canvas->AppendText(m_depth_op_params.m_tool_diameter / theApp.m_program->m_units);
	theApp.m_program_canvas->AppendText(_T(")\n"));
	theApp.m_program_canvas->AppendText(_T("spindle("));
	theApp.m_program_canvas->AppendText(m_depth_op_params.m_spindle_speed);
	theApp.m_program_canvas->AppendText(_T(")\n"));
	theApp.m_program_canvas->AppendText(_T("feedrate_hv("));
	theApp.m_program_canvas->AppendText(m_depth_op_params.m_horizontal_feed_rate);
	theApp.m_program_canvas->AppendText(_T(", "));
	theApp.m_program_canvas->AppendText(m_depth_op_params.m_vertical_feed_rate);
	theApp.m_program_canvas->AppendText(_T(")\n"));
	theApp.m_program_canvas->AppendText(_T("tool_change("));
	theApp.m_program_canvas->AppendText(m_depth_op_params.m_tool_number);
	theApp.m_program_canvas->AppendText(_T(")\n"));
	theApp.m_program_canvas->AppendText(_T("workplane("));
	theApp.m_program_canvas->AppendText(m_depth_op_params.m_workplane);
	theApp.m_program_canvas->AppendText(_T(")\n"));
	theApp.m_program_canvas->AppendText(_T("flush_nc()\n"));

}

<commit_msg>the xml file didn't like 'fixture offset'-changed to 'fixture_offset'<commit_after>// DepthOp.cpp
/*
 * Copyright (c) 2009, Dan Heeks
 * This program is released under the BSD license. See the file COPYING for
 * details.
 */

#include "stdafx.h"
#include "DepthOp.h"
#include "CNCConfig.h"
#include "ProgramCanvas.h"
#include "Program.h"
#include "interface/PropertyInt.h"
#include "interface/PropertyDouble.h"
#include "interface/PropertyLength.h"
#include "tinyxml/tinyxml.h"
#include "interface/Tool.h"

CDepthOpParams::CDepthOpParams()
{
	m_tool_number = 0;
	m_tool_diameter = 0.0;
	m_clearance_height = 0.0;
	m_start_depth = 0.0;
	m_step_down = 0.0;
	m_final_depth = 0.0;
	m_rapid_down_to_height = 0.0;
	m_horizontal_feed_rate = 0.0;
	m_vertical_feed_rate = 0.0;
	m_spindle_speed = 0.0;
}

void CDepthOpParams::set_initial_values()
{
	CNCConfig config;
    config.Read(_T("DepthFixtureOffset"), &m_workplane,1);
	config.Read(_T("DepthOpToolNumber"), &m_tool_number, 1);
	config.Read(_T("DepthOpToolDiameter"), &m_tool_diameter, 3.0);
	config.Read(_T("DepthOpClearanceHeight"), &m_clearance_height, 5.0);
	config.Read(_T("DepthOpStartDepth"), &m_start_depth, 0.0);
	config.Read(_T("DepthOpStepDown"), &m_step_down, 1.0);
	config.Read(_T("DepthOpFinalDepth"), &m_final_depth, -1.0);
	config.Read(_T("DepthOpRapidDown"), &m_rapid_down_to_height, 2.0);
	config.Read(_T("DepthOpHorizFeed"), &m_horizontal_feed_rate, 100.0);
	config.Read(_T("DepthOpVertFeed"), &m_vertical_feed_rate, 100.0);
	config.Read(_T("DepthOpSpindleSpeed"), &m_spindle_speed, 7000);
}

void CDepthOpParams::write_values_to_config()
{
	CNCConfig config;
	config.Write(_T("DepthFixtureOffset"), m_workplane);
	config.Write(_T("DepthOpToolNumber"), m_tool_number);
	config.Write(_T("DepthOpToolDiameter"), m_tool_diameter);
	config.Write(_T("DepthOpClearanceHeight"), m_clearance_height);
	config.Write(_T("DepthOpStartDepth"), m_start_depth);
	config.Write(_T("DepthOpStepDown"), m_step_down);
	config.Write(_T("DepthOpFinalDepth"), m_final_depth);
	config.Write(_T("DepthOpRapidDown"), m_rapid_down_to_height);
	config.Write(_T("DepthOpHorizFeed"), m_horizontal_feed_rate);
	config.Write(_T("DepthOpVertFeed"), m_vertical_feed_rate);
	config.Write(_T("DepthOpSpindleSpeed"), m_spindle_speed);
}

static void on_set_workplane(int value, HeeksObj* object){((CDepthOp*)object)->m_depth_op_params.m_workplane = value;}
static void on_set_tool_number(int value, HeeksObj* object){((CDepthOp*)object)->m_depth_op_params.m_tool_number = value;}
static void on_set_tool_diameter(double value, HeeksObj* object){((CDepthOp*)object)->m_depth_op_params.m_tool_diameter = value;}
static void on_set_clearance_height(double value, HeeksObj* object){((CDepthOp*)object)->m_depth_op_params.m_clearance_height = value;}
static void on_set_step_down(double value, HeeksObj* object){((CDepthOp*)object)->m_depth_op_params.m_step_down = value;}
static void on_set_start_depth(double value, HeeksObj* object){((CDepthOp*)object)->m_depth_op_params.m_start_depth = value;}
static void on_set_final_depth(double value, HeeksObj* object){((CDepthOp*)object)->m_depth_op_params.m_final_depth = value;}
static void on_set_rapid_down_to_height(double value, HeeksObj* object){((CDepthOp*)object)->m_depth_op_params.m_rapid_down_to_height = value;}
static void on_set_horizontal_feed_rate(double value, HeeksObj* object){((CDepthOp*)object)->m_depth_op_params.m_horizontal_feed_rate = value;}
static void on_set_vertical_feed_rate(double value, HeeksObj* object){((CDepthOp*)object)->m_depth_op_params.m_vertical_feed_rate = value;}
static void on_set_spindle_speed(double value, HeeksObj* object){((CDepthOp*)object)->m_depth_op_params.m_spindle_speed = value;}

void CDepthOpParams::GetProperties(CDepthOp* parent, std::list<Property *> *list)
{
	list->push_back(new PropertyInt(_("fixture offset"), m_workplane, parent, on_set_workplane));
	list->push_back(new PropertyInt(_("tool number"), m_tool_number, parent, on_set_tool_number));
	list->push_back(new PropertyLength(_("tool diameter"), m_tool_diameter, parent, on_set_tool_diameter));
	list->push_back(new PropertyLength(_("clearance height"), m_clearance_height, parent, on_set_clearance_height));
	list->push_back(new PropertyLength(_("step down"), m_step_down, parent, on_set_step_down));
	list->push_back(new PropertyLength(_("start depth"), m_start_depth, parent, on_set_start_depth));
	list->push_back(new PropertyLength(_("final depth"), m_final_depth, parent, on_set_final_depth));
	list->push_back(new PropertyLength(_("rapid down to height"), m_rapid_down_to_height, parent, on_set_rapid_down_to_height));
	list->push_back(new PropertyDouble(_("horizontal feed rate"), m_horizontal_feed_rate, parent, on_set_horizontal_feed_rate));
	list->push_back(new PropertyDouble(_("vertical feed rate"), m_vertical_feed_rate, parent, on_set_vertical_feed_rate));
	list->push_back(new PropertyDouble(_("spindle speed"), m_spindle_speed, parent, on_set_spindle_speed));
}

void CDepthOpParams::WriteXMLAttributes(TiXmlNode* pElem)
{
	TiXmlElement * element = new TiXmlElement( "depthop" );
	pElem->LinkEndChild( element );
	element->SetAttribute("fixture_offset", m_workplane);
	element->SetAttribute("tooln", m_tool_number);
	element->SetDoubleAttribute("toold", m_tool_diameter);
	element->SetDoubleAttribute("clear", m_clearance_height);
	element->SetDoubleAttribute("down", m_step_down);
	element->SetDoubleAttribute("startdepth", m_start_depth);
	element->SetDoubleAttribute("depth", m_final_depth);
	element->SetDoubleAttribute("r", m_rapid_down_to_height);
	element->SetDoubleAttribute("hfeed", m_horizontal_feed_rate);
	element->SetDoubleAttribute("vfeed", m_vertical_feed_rate);
	element->SetDoubleAttribute("spin", m_spindle_speed);
}

void CDepthOpParams::ReadFromXMLElement(TiXmlElement* pElem)
{
	TiXmlElement* depthop = TiXmlHandle(pElem).FirstChildElement("depthop").Element();
	if(depthop)
	{

		depthop->Attribute("fixture offset", &m_workplane);
		depthop->Attribute("tooln", &m_tool_number);
		depthop->Attribute("toold", &m_tool_diameter);
		depthop->Attribute("clear", &m_clearance_height);
		depthop->Attribute("down", &m_step_down);
		depthop->Attribute("startdepth", &m_start_depth);
		depthop->Attribute("depth", &m_final_depth);
		depthop->Attribute("r", &m_rapid_down_to_height);
		depthop->Attribute("hfeed", &m_horizontal_feed_rate);
		depthop->Attribute("vfeed", &m_vertical_feed_rate);
		depthop->Attribute("spin", &m_spindle_speed);
	}
}

void CDepthOp::WriteBaseXML(TiXmlElement *element)
{
	m_depth_op_params.WriteXMLAttributes(element);
	COp::WriteBaseXML(element);
}

void CDepthOp::ReadBaseXML(TiXmlElement* element)
{
	m_depth_op_params.ReadFromXMLElement(element);
	COp::ReadBaseXML(element);
}

void CDepthOp::GetProperties(std::list<Property *> *list)
{
	m_depth_op_params.GetProperties(this, list);
	COp::GetProperties(list);
}

void CDepthOp::AppendTextToProgram()
{
	COp::AppendTextToProgram();

	theApp.m_program_canvas->AppendText(_T("clearance = float("));
	theApp.m_program_canvas->AppendText(m_depth_op_params.m_clearance_height / theApp.m_program->m_units);
	theApp.m_program_canvas->AppendText(_T(")\n"));
	theApp.m_program_canvas->AppendText(_T("rapid_down_to_height = float("));
	theApp.m_program_canvas->AppendText(m_depth_op_params.m_rapid_down_to_height / theApp.m_program->m_units);
	theApp.m_program_canvas->AppendText(_T(")\n"));
	theApp.m_program_canvas->AppendText(_T("start_depth = float("));
	theApp.m_program_canvas->AppendText(m_depth_op_params.m_start_depth / theApp.m_program->m_units);
	theApp.m_program_canvas->AppendText(_T(")\n"));
	theApp.m_program_canvas->AppendText(_T("step_down = float("));
	theApp.m_program_canvas->AppendText(m_depth_op_params.m_step_down / theApp.m_program->m_units);
	theApp.m_program_canvas->AppendText(_T(")\n"));
	theApp.m_program_canvas->AppendText(_T("final_depth = float("));
	theApp.m_program_canvas->AppendText(m_depth_op_params.m_final_depth / theApp.m_program->m_units);
	theApp.m_program_canvas->AppendText(_T(")\n"));
	theApp.m_program_canvas->AppendText(_T("tool_diameter = float("));
	theApp.m_program_canvas->AppendText(m_depth_op_params.m_tool_diameter / theApp.m_program->m_units);
	theApp.m_program_canvas->AppendText(_T(")\n"));
	theApp.m_program_canvas->AppendText(_T("spindle("));
	theApp.m_program_canvas->AppendText(m_depth_op_params.m_spindle_speed);
	theApp.m_program_canvas->AppendText(_T(")\n"));
	theApp.m_program_canvas->AppendText(_T("feedrate_hv("));
	theApp.m_program_canvas->AppendText(m_depth_op_params.m_horizontal_feed_rate);
	theApp.m_program_canvas->AppendText(_T(", "));
	theApp.m_program_canvas->AppendText(m_depth_op_params.m_vertical_feed_rate);
	theApp.m_program_canvas->AppendText(_T(")\n"));
	theApp.m_program_canvas->AppendText(_T("tool_change("));
	theApp.m_program_canvas->AppendText(m_depth_op_params.m_tool_number);
	theApp.m_program_canvas->AppendText(_T(")\n"));
	theApp.m_program_canvas->AppendText(_T("workplane("));
	theApp.m_program_canvas->AppendText(m_depth_op_params.m_workplane);
	theApp.m_program_canvas->AppendText(_T(")\n"));
	theApp.m_program_canvas->AppendText(_T("flush_nc()\n"));

}

<|endoftext|>


<commit_before>#include <Arduino.h>
#include "IOThing.h"

IOThing::IOThing(char * hostname)
{
    strcpy(this->_hostname, hostname);
    //this->items = new TickerSchedulerItem[size];
    //this->size = size;
}

bool IOThing::_use_mqtt(){
  return this->_mqtt_state != IOT_MQTT_DISABLED;
}

bool IOThing::_use_ota(){
  return this->_ota_state == IOT_OTA_READY;
}

void IOThing::loop(){
  // task scheduler
  //ts.update();
  // OTA updates
  if(this->_use_ota()) ArduinoOTA.handle();
  // mqtt client
  if(this->_use_mqtt()) this->client.loop();
  // ESP functions
  yield();
}

void IOThing::useOTA(){
  ArduinoOTA.setHostname(this->_hostname);
  ArduinoOTA.onStart([&]() {
    this->_ota_state = IOT_OTA_PROGRESS;
    //Serial.println("Start");
  });
  ArduinoOTA.onEnd([&]() {
    this->_ota_state = IOT_OTA_COMPLETE;
    //Serial.println("\nEnd");
  });
  ArduinoOTA.onProgress([&](unsigned int progress, unsigned int total) {
    this->_ota_state = IOT_OTA_PROGRESS;
    //Serial.printf("Progress: %u%%\r", (progress / (total / 100)));
  });
  ArduinoOTA.onError([&](ota_error_t error) {
    this->_ota_state = IOT_OTA_ERROR;
    //Serial.printf("Error[%u]: ", error);
    //if (error == OTA_AUTH_ERROR) Serial.println("Auth Failed");
    //else if (error == OTA_BEGIN_ERROR) Serial.println("Begin Failed");
    //else if (error == OTA_CONNECT_ERROR) Serial.println("Connect Failed");
    //else if (error == OTA_RECEIVE_ERROR) Serial.println("Receive Failed");
    //else if (error == OTA_END_ERROR) Serial.println("End Failed");
  });
  ArduinoOTA.begin();
  this->_ota_state = IOT_OTA_READY;
}

void IOThing::useWiFi(char * ssid, char * password){
  Serial.println("Connecting to WiFi");
  WiFi.mode(WIFI_STA);
  Serial.println("Wifi begin for " + String(ssid) + ":"+ String(password));
  WiFi.begin(ssid, password);
  while (WiFi.waitForConnectResult() != WL_CONNECTED) {
    Serial.println("Connection Failed! Rebooting...");
    delay(5000);
    ESP.restart();
  }
  Serial.println("Wifi OK");
}

void IOThing::_iot_settings_callback(String topic, String payload){
  if(topic == "dst") this->_dst = payload.toInt();
  if(topic == "timezone") this->_timezone = payload.toInt();
}

/*
  IOThing::_raw_mqtt_callback(topic, data, len)
  MQTT message received callback function, parse topic and match to
  one of our subscriptions. Once matched, run callback for this subscription,
  passing it the munged topic (sans. subscription substring) and payload.
*/
void IOThing::_raw_mqtt_callback(char * topic, byte * data, unsigned int len){
  // first munge the payload payload
  char buf[IOT_MQTT_PAYLOAD_MAXLEN+1] = "";
  int i = 0;
  for (i = 0; i < len; i++) {
    if(i >= IOT_MQTT_PAYLOAD_MAXLEN) break;
    buf[i] = (char)data[i];
  }
  buf[i] = '\0';
  String str_payload = String(buf);

  // now try to fit the topic to one of our subscriptions
  String str_topic = String(topic);

  // firstly, is it a settings call?
  String settings_topic = String(this->_hostname)+"/settings/";
  if(str_topic.startsWith(settings_topic)){
    //this is a setting
    str_topic.replace(settings_topic, "");
    this->_iot_settings_callback(str_topic, str_payload);
    this->_user_settings_callback(str_topic, str_payload);
  }

  int longest_match_len = 0;
  int longest_match_id = -1;
  String longest_match_sub = "";

  // find the longest subscription which matches this topic
  for(uint8_t i = 0; i < this->_subscriptionCount(); i++){
    String str_subscription = String(this->_mqtt_topics[i]);
    while(str_subscription.endsWith("#") || str_subscription.endsWith("/")){
      str_subscription = str_subscription.substring(0,str_subscription.length()-1);
    }
    int res = str_topic.indexOf(str_subscription);
    Serial.println("Compare " + String(topic) + " to pot: " + str_subscription);
    if(res != -1 && str_subscription.length() > longest_match_len) {
      longest_match_len = str_subscription.length();
      longest_match_id = i;
      longest_match_sub = str_subscription;
    }
  }

  // Check if we didn't match any of our topics (madness)
  if(longest_match_id == -1){
    // something went wrong, we should have been able to match this
    return;
  }

  // remove subscription from topic
  str_topic.replace(longest_match_sub, "");
  if(str_topic.startsWith("/")) str_topic = str_topic.substring(1, str_topic.length());

  // run callback function for this subscription
  // returning munged topic and payload as string
  this->_mqtt_callbacks[longest_match_id](str_topic, str_payload);
}

int IOThing::_mqtt_client_connect(){
  if(strlen(this->_mqtt_password)){
    return this->client.connect(this->_hostname, this->_mqtt_user, this->_mqtt_password);
  }else{
    return this->client.connect(this->_hostname);
  }
}

void IOThing::_reconnectMQTT(){
  if (!this->client.connected()) {
    Serial.print("Attempting MQTT connection...");
    // Attempt to connect
    if (this->_mqtt_client_connect()) {
      this->_mqtt_state = IOT_MQTT_CONNECTED;
      this->client.subscribe((String(this->_hostname) + "/settings/#").c_str());
    } else {
      delay(5000);
    }
  }
}

void IOThing::useMQTT(char * server, uint16_t port, char * username, char * password, IOT_MQTT_CALLBACK_SIGNATURE settings_callback){
  strncpy(this->_mqtt_user, username, 32);
  strncpy(this->_mqtt_password, password, 32);
  this->_mqtt_port = port;
  this->useMQTT(server, settings_callback);
}

void IOThing::useMQTT(char * server, IOT_MQTT_CALLBACK_SIGNATURE settings_callback){ //char * topic, IOT_MQTT_CALLBACK_SIGNATURE callback){
  // setup MQTT connection
  this->client = PubSubClient(this->espClient);
  this->client.setServer(server, this->_mqtt_port ? this->_mqtt_port : 1883);
  this->client.setCallback([&](char *topic, byte *data, unsigned int len) {
    this->_raw_mqtt_callback(topic, data, len);
  });
  this->_user_settings_callback = settings_callback;
  // connect to MQTT server
  this->_reconnectMQTT();

}

// used for determining the enxt unused MQTT topic slot
int IOThing::_subscriptionCount(){
  for(int i = 0; i < IOT_MAX_MQTT_SUBSCRIPTIONS; i++){
    if(_mqtt_topics_map[i] == false){
      return i;
    }
  }
  return -1;
}

/* IOThing::topicSubscribe(topic, callback)
    subscribe to a new MQTT topic
    The callback function should be of the form fn(String topic, String payload)
    as it will be called whenever a message is received on this topic / subscription
*/
int IOThing::topicSubscribe(char * topic, IOT_MQTT_CALLBACK_SIGNATURE callback){
  // get the id of the next free slot
  byte next_subscription = this->_subscriptionCount();
  // if we're full, barf
  if(next_subscription >= IOT_MAX_MQTT_SUBSCRIPTIONS) return -1;
  // Store the topic and callback function for same
  strcpy(this->_mqtt_topics[next_subscription], topic);
  this->_mqtt_callbacks[next_subscription]= callback;
  this->_mqtt_topics_map[next_subscription] = true;
  // Subscribe to the topic
  this->client.subscribe(topic);
  return 0;
};

void IOThing::_log(char * msg){
  this->client.publish(
    (String(this->_hostname)+"/debug").c_str(),
    msg
  );
}

void IOThing::useNTP(char * server){
  // set status
  this->_ntp_state = IOT_NTP_NOSYNC;
  // callback to be run when time sync is obtained
  NTP.onNTPSyncEvent([&](NTPSyncEvent_t error) {
    if (error) {
      Serial.print("Time Sync error: ");
      if (error == noResponse)
        Serial.println("NTP server not reachable");
      else if (error == invalidAddress)
        Serial.println("Invalid NTP server address");
    }else {
      //Serial.print("Got NTP time: ");
      //Serial.println(NTP.getTimeDateString(NTP.getLastNTPSync()));
      this->_ntp_state = IOT_NTP_SYNC;
    }

  });
  NTP.begin(server, 1, false);
  NTP.setInterval(IOT_NTP_SYNC_INTERVAL);
  NTP.setTimeZone(this->_timezone + this->_dst);
}

void IOThing::publish(String topic, String value){
  char _value[64];
  value.toCharArray(_value, 64);
  this->publish(topic, _value);
}

void IOThing::publish(String topic, float value){
  char _value[64];
  String(value,2).toCharArray(_value, 64);
  this->publish(topic, _value);
}

void IOThing::publish(String topic, char * value){
  this->client.publish((String(this->_hostname)+ "/" + topic).c_str(), value);
}
<commit_msg>Reconnect MQTT<commit_after>#include <Arduino.h>
#include "IOThing.h"

IOThing::IOThing(char * hostname)
{
    strcpy(this->_hostname, hostname);
    //this->items = new TickerSchedulerItem[size];
    //this->size = size;
}

bool IOThing::_use_mqtt(){
  return this->_mqtt_state != IOT_MQTT_DISABLED;
}

bool IOThing::_use_ota(){
  return this->_ota_state == IOT_OTA_READY;
}

void IOThing::loop(){
  // task scheduler
  //ts.update();
  // OTA updates
  if(this->_use_ota()) ArduinoOTA.handle();
  // mqtt client
  if(this->_use_mqtt()) this->client.loop();
  if(this->_use_mqtt()) this->_reconnectMQTT();
  // ESP functions
  yield();
}

void IOThing::useOTA(){
  ArduinoOTA.setHostname(this->_hostname);
  ArduinoOTA.onStart([&]() {
    this->_ota_state = IOT_OTA_PROGRESS;
    //Serial.println("Start");
  });
  ArduinoOTA.onEnd([&]() {
    this->_ota_state = IOT_OTA_COMPLETE;
    //Serial.println("\nEnd");
  });
  ArduinoOTA.onProgress([&](unsigned int progress, unsigned int total) {
    this->_ota_state = IOT_OTA_PROGRESS;
    //Serial.printf("Progress: %u%%\r", (progress / (total / 100)));
  });
  ArduinoOTA.onError([&](ota_error_t error) {
    this->_ota_state = IOT_OTA_ERROR;
    //Serial.printf("Error[%u]: ", error);
    //if (error == OTA_AUTH_ERROR) Serial.println("Auth Failed");
    //else if (error == OTA_BEGIN_ERROR) Serial.println("Begin Failed");
    //else if (error == OTA_CONNECT_ERROR) Serial.println("Connect Failed");
    //else if (error == OTA_RECEIVE_ERROR) Serial.println("Receive Failed");
    //else if (error == OTA_END_ERROR) Serial.println("End Failed");
  });
  ArduinoOTA.begin();
  this->_ota_state = IOT_OTA_READY;
}

void IOThing::useWiFi(char * ssid, char * password){
  Serial.println("Connecting to WiFi");
  WiFi.mode(WIFI_STA);
  Serial.println("Wifi begin for " + String(ssid) + ":"+ String(password));
  WiFi.begin(ssid, password);
  while (WiFi.waitForConnectResult() != WL_CONNECTED) {
    Serial.println("Connection Failed! Rebooting...");
    delay(5000);
    ESP.restart();
  }
  Serial.println("Wifi OK");
}

void IOThing::_iot_settings_callback(String topic, String payload){
  if(topic == "dst") this->_dst = payload.toInt();
  if(topic == "timezone") this->_timezone = payload.toInt();
}

/*
  IOThing::_raw_mqtt_callback(topic, data, len)
  MQTT message received callback function, parse topic and match to
  one of our subscriptions. Once matched, run callback for this subscription,
  passing it the munged topic (sans. subscription substring) and payload.
*/
void IOThing::_raw_mqtt_callback(char * topic, byte * data, unsigned int len){
  // first munge the payload payload
  char buf[IOT_MQTT_PAYLOAD_MAXLEN+1] = "";
  int i = 0;
  for (i = 0; i < len; i++) {
    if(i >= IOT_MQTT_PAYLOAD_MAXLEN) break;
    buf[i] = (char)data[i];
  }
  buf[i] = '\0';
  String str_payload = String(buf);

  // now try to fit the topic to one of our subscriptions
  String str_topic = String(topic);

  // firstly, is it a settings call?
  String settings_topic = String(this->_hostname)+"/settings/";
  if(str_topic.startsWith(settings_topic)){
    //this is a setting
    str_topic.replace(settings_topic, "");
    this->_iot_settings_callback(str_topic, str_payload);
    this->_user_settings_callback(str_topic, str_payload);
  }

  int longest_match_len = 0;
  int longest_match_id = -1;
  String longest_match_sub = "";

  // find the longest subscription which matches this topic
  for(uint8_t i = 0; i < this->_subscriptionCount(); i++){
    String str_subscription = String(this->_mqtt_topics[i]);
    while(str_subscription.endsWith("#") || str_subscription.endsWith("/")){
      str_subscription = str_subscription.substring(0,str_subscription.length()-1);
    }
    int res = str_topic.indexOf(str_subscription);
    Serial.println("Compare " + String(topic) + " to pot: " + str_subscription);
    if(res != -1 && str_subscription.length() > longest_match_len) {
      longest_match_len = str_subscription.length();
      longest_match_id = i;
      longest_match_sub = str_subscription;
    }
  }

  // Check if we didn't match any of our topics (madness)
  if(longest_match_id == -1){
    // something went wrong, we should have been able to match this
    return;
  }

  // remove subscription from topic
  str_topic.replace(longest_match_sub, "");
  if(str_topic.startsWith("/")) str_topic = str_topic.substring(1, str_topic.length());

  // run callback function for this subscription
  // returning munged topic and payload as string
  this->_mqtt_callbacks[longest_match_id](str_topic, str_payload);
}

int IOThing::_mqtt_client_connect(){
  if(strlen(this->_mqtt_password)){
    return this->client.connect(this->_hostname, this->_mqtt_user, this->_mqtt_password);
  }else{
    return this->client.connect(this->_hostname);
  }
}

void IOThing::_reconnectMQTT(){
  if (!this->client.connected()) {
    Serial.print("Attempting MQTT connection...");
    // Attempt to connect
    if (this->_mqtt_client_connect()) {
      this->_mqtt_state = IOT_MQTT_CONNECTED;
      this->client.subscribe((String(this->_hostname) + "/settings/#").c_str());
    }
  }
}

void IOThing::useMQTT(char * server, uint16_t port, char * username, char * password, IOT_MQTT_CALLBACK_SIGNATURE settings_callback){
  strncpy(this->_mqtt_user, username, 32);
  strncpy(this->_mqtt_password, password, 32);
  this->_mqtt_port = port;
  this->useMQTT(server, settings_callback);
}

void IOThing::useMQTT(char * server, IOT_MQTT_CALLBACK_SIGNATURE settings_callback){ //char * topic, IOT_MQTT_CALLBACK_SIGNATURE callback){
  // setup MQTT connection
  this->client = PubSubClient(this->espClient);
  this->client.setServer(server, this->_mqtt_port ? this->_mqtt_port : 1883);
  this->client.setCallback([&](char *topic, byte *data, unsigned int len) {
    this->_raw_mqtt_callback(topic, data, len);
  });
  this->_user_settings_callback = settings_callback;
  // connect to MQTT server
  this->_reconnectMQTT();

}

// used for determining the enxt unused MQTT topic slot
int IOThing::_subscriptionCount(){
  for(int i = 0; i < IOT_MAX_MQTT_SUBSCRIPTIONS; i++){
    if(_mqtt_topics_map[i] == false){
      return i;
    }
  }
  return -1;
}

/* IOThing::topicSubscribe(topic, callback)
    subscribe to a new MQTT topic
    The callback function should be of the form fn(String topic, String payload)
    as it will be called whenever a message is received on this topic / subscription
*/
int IOThing::topicSubscribe(char * topic, IOT_MQTT_CALLBACK_SIGNATURE callback){
  // get the id of the next free slot
  byte next_subscription = this->_subscriptionCount();
  // if we're full, barf
  if(next_subscription >= IOT_MAX_MQTT_SUBSCRIPTIONS) return -1;
  // Store the topic and callback function for same
  strcpy(this->_mqtt_topics[next_subscription], topic);
  this->_mqtt_callbacks[next_subscription]= callback;
  this->_mqtt_topics_map[next_subscription] = true;
  // Subscribe to the topic
  this->client.subscribe(topic);
  return 0;
};

void IOThing::_log(char * msg){
  this->client.publish(
    (String(this->_hostname)+"/debug").c_str(),
    msg
  );
}

void IOThing::useNTP(char * server){
  // set status
  this->_ntp_state = IOT_NTP_NOSYNC;
  // callback to be run when time sync is obtained
  NTP.onNTPSyncEvent([&](NTPSyncEvent_t error) {
    if (error) {
      Serial.print("Time Sync error: ");
      if (error == noResponse)
        Serial.println("NTP server not reachable");
      else if (error == invalidAddress)
        Serial.println("Invalid NTP server address");
    }else {
      //Serial.print("Got NTP time: ");
      //Serial.println(NTP.getTimeDateString(NTP.getLastNTPSync()));
      this->_ntp_state = IOT_NTP_SYNC;
    }

  });
  NTP.begin(server, 1, false);
  NTP.setInterval(IOT_NTP_SYNC_INTERVAL);
  NTP.setTimeZone(this->_timezone + this->_dst);
}

void IOThing::publish(String topic, String value){
  char _value[64];
  value.toCharArray(_value, 64);
  this->publish(topic, _value);
}

void IOThing::publish(String topic, float value){
  char _value[64];
  String(value,2).toCharArray(_value, 64);
  this->publish(topic, _value);
}

void IOThing::publish(String topic, char * value){
  this->client.publish((String(this->_hostname)+ "/" + topic).c_str(), value);
}
<|endoftext|>


<commit_before>#ifndef INTEGER_HPP
#define INTEGER_HPP

#include <cmath>
#include <algorithm>
#include <vector>
#include <map>

/*!
 * @brief Identify specified integer is prime or not.
 *
 * @tparam IntType  Integer type
 * @param [in] n  Integer to identify prime or not
 * @return  Return true if specified integer is true, otherwise return false
 */
template<typename IntType>
static bool
isPrime(IntType n)
{
  if (n < 2) {
    return false;
  } else if (n == 2) {
    return true;
  } else if (n % 2 == 0) {
    return false;
  }
  for (IntType i = 3; i * i <= n; i += 2) {
    if (n % i == 0) {
      return false;
    }
  }
  return true;
}

/*!
 * @brief Make prime table
 *
 * @tparam IntType  Integer type
 * @param [in] n  Upper limit
 *
 * @return  std::vector of prime table
 */
template<typename IntType>
static std::vector<bool>
makePrimeTable(IntType n)
{
  std::vector<bool> primeTable(n + 1, true);
  primeTable[0] = primeTable[1] = false;
  for (int i = 2; i * i <= n; i++) {
    if (primeTable[i]) {
      for (int j = i * 2; j <= n; j += i) {
        primeTable[i] = false;
      }
    }
  }
  return primeTable;
}

/*!
 * @brief Defactorize specified integer
 *
 * @tparam IntType  Integer type
 * @param [in] n  An integer
 *
 * @return  std::map of prime factors of specified integer
 */
template<typename IntType>
static std::map<IntType, int>
defactorize(IntType n)
{
  std::map<IntType, int> primeFactors;
  int cnt = 0;
  for (; n % 2 == 0; n /= 2, cnt++);
  if (cnt != 0) {
    primeFactors[2] = cnt;
  }
  for (IntType i = 3, iMax = static_cast<IntType>(std::sqrt(n)) + 2; i <= iMax; i += 2) {
    cnt = 0;
    for (; n % i == 0; n /= i, cnt++);
    if (cnt != 0) {
      primeFactors[i] = cnt;
      iMax = std::sqrt(n) + 2;
    }
  }
  if (n != 1) {
    primeFactors[n] = 1;
  }
  return primeFactors;
}

/*!
 * @brief Calculate divisors of specified integer
 *
 * @tparam IntType  Integer type
 * @param [in] n  An integer
 *
 * @return  std::vector of divisors of specified integer
 */
template <typename IntType>
std::vector<IntType>
divisors(IntType n)
{
  std::vector<IntType> divisors;
  for (IntType i = 1; i * i <= n; i++) {
    if (n % i == 0) {
      divisors.push_back(i);
      if (i != n / i) {
        divisors.push_back(n / i);
      }
    }
  }
  std::sort(divisors.begin(), divisors.end());
  return divisors;
}

/*!
 * @brief Extended Euclidean algorithm
 * Calculate (x, y) s.t. ax + by = gcd(a, b)
 *
 * @tparam SignedIntType  Signed integer type
 * @param [in]  a  First input parameter
 * @param [in]  b  Second input parameter
 * @param [out] x  First output parameter
 * @param [out] y  Second output parameter
 *
 * @return  GCD of a and b
 */
template<typename SignedIntType>
SignedIntType
extgcd(SignedIntType a, SignedIntType b, SignedIntType& x, SignedIntType& y)
{
  if (b == 0) {
    x = 1;
    y = 0;
    return a;
  } else {
    SignedIntType g = extgcd(b, a % b, y, x);
    y -= (a / b) * x;
    return g;
  }
}

/*!
 * @brief Euler's totient function
 * Calculate the number of disjoint integers i s.t. 1 <= i <= n
 *
 * @tparam IntType  Integer type
 * @param [in] n    Upper limit
 *
 * @return  The number of disjoint integers
 */
template<typename IntType>
int eulerTotient(IntType n)
{
  int nDisjoint = n;
  for (IntType i = 2; i * i <= n; i++) {
    if (n % i == 0) {
      nDisjoint = nDisjoint / i * (i - 1);
      while (n % i == 0) {
        n /= i;
      }
    }
  }
  if (n > 1) {
    nDisjoint = nDisjoint / n * (n - 1);
  }
  return nDisjoint;
}

#endif  // INTEGER_HPP
<commit_msg>Not to use std::sqrt() in defactorize()<commit_after>#ifndef INTEGER_HPP
#define INTEGER_HPP

#include <cmath>
#include <algorithm>
#include <vector>
#include <map>

/*!
 * @brief Identify specified integer is prime or not.
 *
 * @tparam IntType  Integer type
 * @param [in] n  Integer to identify prime or not
 * @return  Return true if specified integer is true, otherwise return false
 */
template<typename IntType>
static bool
isPrime(IntType n)
{
  if (n < 2) {
    return false;
  } else if (n == 2) {
    return true;
  } else if (n % 2 == 0) {
    return false;
  }
  for (IntType i = 3; i * i <= n; i += 2) {
    if (n % i == 0) {
      return false;
    }
  }
  return true;
}

/*!
 * @brief Make prime table
 *
 * @tparam IntType  Integer type
 * @param [in] n  Upper limit
 *
 * @return  std::vector of prime table
 */
template<typename IntType>
static std::vector<bool>
makePrimeTable(IntType n)
{
  std::vector<bool> primeTable(n + 1, true);
  primeTable[0] = primeTable[1] = false;
  for (int i = 2; i * i <= n; i++) {
    if (primeTable[i]) {
      for (int j = i * 2; j <= n; j += i) {
        primeTable[i] = false;
      }
    }
  }
  return primeTable;
}

/*!
 * @brief Defactorize specified integer
 *
 * @tparam IntType  Integer type
 * @param [in] n  An integer
 *
 * @return  std::map of prime factors of specified integer
 */
template<typename IntType>
static std::map<IntType, int>
defactorize(IntType n)
{
  std::map<IntType, int> primeFactors;
  int cnt = 0;
  for (; n % 2 == 0; n /= 2, cnt++);
  if (cnt != 0) {
    primeFactors[2] = cnt;
  }
  for (IntType i = 3, iMax = n; i * i <= iMax; i += 2) {
    cnt = 0;
    for (; n % i == 0; n /= i, cnt++);
    if (cnt != 0) {
      primeFactors[i] = cnt;
      iMax = n;
    }
  }
  if (n != 1) {
    primeFactors[n] = 1;
  }
  return primeFactors;
}

/*!
 * @brief Calculate divisors of specified integer
 *
 * @tparam IntType  Integer type
 * @param [in] n  An integer
 *
 * @return  std::vector of divisors of specified integer
 */
template <typename IntType>
std::vector<IntType>
divisors(IntType n)
{
  std::vector<IntType> divisors;
  for (IntType i = 1; i * i <= n; i++) {
    if (n % i == 0) {
      divisors.push_back(i);
      if (i != n / i) {
        divisors.push_back(n / i);
      }
    }
  }
  std::sort(divisors.begin(), divisors.end());
  return divisors;
}

/*!
 * @brief Extended Euclidean algorithm
 * Calculate (x, y) s.t. ax + by = gcd(a, b)
 *
 * @tparam SignedIntType  Signed integer type
 * @param [in]  a  First input parameter
 * @param [in]  b  Second input parameter
 * @param [out] x  First output parameter
 * @param [out] y  Second output parameter
 *
 * @return  GCD of a and b
 */
template<typename SignedIntType>
SignedIntType
extgcd(SignedIntType a, SignedIntType b, SignedIntType& x, SignedIntType& y)
{
  if (b == 0) {
    x = 1;
    y = 0;
    return a;
  } else {
    SignedIntType g = extgcd(b, a % b, y, x);
    y -= (a / b) * x;
    return g;
  }
}

/*!
 * @brief Euler's totient function
 * Calculate the number of disjoint integers i s.t. 1 <= i <= n
 *
 * @tparam IntType  Integer type
 * @param [in] n    Upper limit
 *
 * @return  The number of disjoint integers
 */
template<typename IntType>
int eulerTotient(IntType n)
{
  int nDisjoint = n;
  for (IntType i = 2; i * i <= n; i++) {
    if (n % i == 0) {
      nDisjoint = nDisjoint / i * (i - 1);
      while (n % i == 0) {
        n /= i;
      }
    }
  }
  if (n > 1) {
    nDisjoint = nDisjoint / n * (n - 1);
  }
  return nDisjoint;
}

#endif  // INTEGER_HPP
<|endoftext|>


<commit_before>/* Copyright (c) 2013 "Naftoreiclag" https://github.com/Naftoreiclag
 *
 * Distributed under the MIT License (http://opensource.org/licenses/mit-license.html)
 * See accompanying file LICENSE
 */

#include "util/Sysout.h"

#include "Game.h"

#include "Lua_5-2-2/lua.h"
#include "LuaBridge/luabridge.h"

// Initialize
void initialize()
{
    // Set the display width to 80 chars long (for word-wrap)
    Sysout::setDisplayWidth(80);

    // If we are in debug mode, then print that
    #ifdef DEBUG
    Sysout::println("Running in DEBUG mode!");
    Sysout::printDictionaryEntries();
    #endif
}

// Run
void run()
{
    bool running = true;

    while(running)
    {
        // Put a title screen here

        // Run a game
        Game* game = new Game();
        game->load();
        game->run();
        delete game;
    }
}

// Finalize
void finalize()
{

}

int main()
{
    // Initialize
    initialize();

    // Run
    run();

    // Clean-up
    finalize();

    // Died quietly
    return 0;
}
<commit_msg>Lua.h test<commit_after>/* Copyright (c) 2013 "Naftoreiclag" https://github.com/Naftoreiclag
 *
 * Distributed under the MIT License (http://opensource.org/licenses/mit-license.html)
 * See accompanying file LICENSE
 */

#include "util/Sysout.h"

#include "Game.h"

#include "Lua_5-2-2/lua.h"
//#include "LuaBridge/luabridge.h"

// Initialize
void initialize()
{
    // Set the display width to 80 chars long (for word-wrap)
    Sysout::setDisplayWidth(80);

    Sysout::println(LUA_TTABLE);

    // If we are in debug mode, then print that
    #ifdef DEBUG
    Sysout::println("Running in DEBUG mode!");
    Sysout::printDictionaryEntries();
    #endif
}

// Run
void run()
{
    bool running = true;

    while(running)
    {
        // Put a title screen here

        // Run a game
        Game* game = new Game();
        game->load();
        game->run();
        delete game;
    }
}

// Finalize
void finalize()
{

}

int main()
{
    // Initialize
    initialize();

    // Run
    run();

    // Clean-up
    finalize();

    // Died quietly
    return 0;
}
<|endoftext|>


<commit_before>

#include "ODSFile.hpp"
#include "FileInfo.hpp"
#include <QDebug>

static const QString nameValue = "name";
//static const QString typeValue = "type";
static const QString groupPkValue = "group_pk";
static const QString fileSizeValue = "file_size";
static const QString fileIdValue = "fileID";
static const QString expirationDateValue = "expiration_date";
static const QString classificationValue = "classification";
static const QString logMeValue = "log_me";
static const QString commentValue = "comment";
static const QString logDeValue = "log_de";

ODSFile::ODSFile(QObject *parent) {}

ODSFile::ODSFile(QVariantMap fileMap) :
				QObject(), mFilesMap(fileMap) {
	mName = mFilesMap.value(nameValue, "").toString();
	mId = mFilesMap.value(fileIdValue, 0).toInt();
	mComment = mFilesMap.value(commentValue, "").toString();
	mContainerId = mFilesMap.value(groupPkValue, 0).toInt();
	mFileSize = mFilesMap.value(fileSizeValue, 0).toInt();
	mClassification = mFilesMap.value(classificationValue, 1).toInt();
	mExpires = mFilesMap.value(expirationDateValue, "").toString();
	mCreatedBy = mFilesMap.value(logMeValue, "").toString();
	mCreatedAt = mFilesMap.value(logDeValue, "").toString();
	mDisplayType = "L";
	FileInfo fi;
	if (fi.isImage(mName)) {
		mDisplayIcon = "../images/image114.png";
	} else if (fi.isVideo(mName)) {
		mDisplayIcon = "../images/video114.png";
	} else if (fi.isAudio(mName)) {
		mDisplayIcon = "../images/audio114.png";
	} else if (fi.getSuffix(mName) == "pdf") {
		mDisplayIcon = "../images/pdf114.png";
	} else if (fi.isCompressed(mName)) {
		mDisplayIcon = "../images/zip114.png";
	} else if (fi.isDocument(mName)) {
		mDisplayIcon = "../images/files-icon.png";
	} else if (fi.isBook(mName)) {
		mDisplayIcon = "../images/ebook114.png";
	} else {
		mDisplayIcon = "../images/other114.png";
	}

}

QString ODSFile::name() const {
	return mName;
}
void ODSFile::setName(QString newName) {
	if (newName != mName) {
		mName = newName;
		emit nameChanged(newName);
	}
}

QString ODSFile::expires() const {
	return mExpires;
}
void ODSFile::setExpires(QString newExpires) {
	if (newExpires != mExpires) {
		mExpires = newExpires;
		emit expiresChanged(newExpires);
	}
}

QString ODSFile::comment() const {
	return mComment;
}
void ODSFile::setComment(QString newComment) {
	if (newComment != mComment) {
		mComment = newComment;
		emit commentChanged(newComment);
	}
}

QString ODSFile::createdBy() const {
	return mCreatedBy;
}
void ODSFile::setCreatedBy(QString newCreatedBy) {
	if (newCreatedBy != mCreatedBy) {
		mCreatedBy = newCreatedBy;
		emit createdByChanged(newCreatedBy);
	}
}

QString ODSFile::createdAt() const {
	return mCreatedAt;
}
void ODSFile::setCreatedAt(QString newCreatedAt) {
	if (newCreatedAt != mCreatedAt) {
		mCreatedAt = newCreatedAt;
		emit createdByChanged(newCreatedAt);
	}
}

int ODSFile::id() const {
	return mId;
}
void ODSFile::setId(int id) {
	if (id != mId) {
		mId = id;
		emit idChanged(id);
	}
}

int ODSFile::level() const {
	return mLevel;
}
void ODSFile::setLevel(int level) {
	if (level != mLevel) {
		mLevel = level;
		emit levelChanged(level);
	}
}

int ODSFile::containerId() const {
	return mContainerId;
}
void ODSFile::setContainerId(int containerId) {
	if (containerId != mContainerId) {
		mContainerId = containerId;
		emit containerIdChanged(containerId);
	}
}

int ODSFile::fileSize() const {
	return mContainerId;
}
void ODSFile::setFileSize(int fileSize) {
	if (fileSize != mContainerId) {
		mContainerId = fileSize;
		emit fileSizeChanged(fileSize);
	}
}

int ODSFile::classification() const {
	return mClassification;
}
void ODSFile::setClassification(int classification) {
	if (classification != mClassification) {
		mClassification = classification;
		emit classificationChanged(classification);
	}
}

QString ODSFile::displayType() const {
	return mDisplayType;
}

QString ODSFile::displayIcon() const {
	return mDisplayIcon;
}

ODSFile::~ODSFile() {
	//
}

<commit_msg>bug fix used wrong variable for fileSize<commit_after>

#include "ODSFile.hpp"
#include "FileInfo.hpp"
#include <QDebug>

static const QString nameValue = "name";
//static const QString typeValue = "type";
static const QString groupPkValue = "group_pk";
static const QString fileSizeValue = "file_size";
static const QString fileIdValue = "fileID";
static const QString expirationDateValue = "expiration_date";
static const QString classificationValue = "classification";
static const QString logMeValue = "log_me";
static const QString commentValue = "comment";
static const QString logDeValue = "log_de";

ODSFile::ODSFile(QObject *parent) {}

ODSFile::ODSFile(QVariantMap fileMap) :
				QObject(), mFilesMap(fileMap) {
	mName = mFilesMap.value(nameValue, "").toString();
	mId = mFilesMap.value(fileIdValue, 0).toInt();
	mComment = mFilesMap.value(commentValue, "").toString();
	mContainerId = mFilesMap.value(groupPkValue, 0).toInt();
	mFileSize = mFilesMap.value(fileSizeValue, 0).toInt();
	mClassification = mFilesMap.value(classificationValue, 1).toInt();
	mExpires = mFilesMap.value(expirationDateValue, "").toString();
	mCreatedBy = mFilesMap.value(logMeValue, "").toString();
	mCreatedAt = mFilesMap.value(logDeValue, "").toString();
	mDisplayType = "L";
	FileInfo fi;
	if (fi.isImage(mName)) {
		mDisplayIcon = "../images/image114.png";
	} else if (fi.isVideo(mName)) {
		mDisplayIcon = "../images/video114.png";
	} else if (fi.isAudio(mName)) {
		mDisplayIcon = "../images/audio114.png";
	} else if (fi.getSuffix(mName) == "pdf") {
		mDisplayIcon = "../images/pdf114.png";
	} else if (fi.isCompressed(mName)) {
		mDisplayIcon = "../images/zip114.png";
	} else if (fi.isDocument(mName)) {
		mDisplayIcon = "../images/files-icon.png";
	} else if (fi.isBook(mName)) {
		mDisplayIcon = "../images/ebook114.png";
	} else {
		mDisplayIcon = "../images/other114.png";
	}

}

QString ODSFile::name() const {
	return mName;
}
void ODSFile::setName(QString newName) {
	if (newName != mName) {
		mName = newName;
		emit nameChanged(newName);
	}
}

QString ODSFile::expires() const {
	return mExpires;
}
void ODSFile::setExpires(QString newExpires) {
	if (newExpires != mExpires) {
		mExpires = newExpires;
		emit expiresChanged(newExpires);
	}
}

QString ODSFile::comment() const {
	return mComment;
}
void ODSFile::setComment(QString newComment) {
	if (newComment != mComment) {
		mComment = newComment;
		emit commentChanged(newComment);
	}
}

QString ODSFile::createdBy() const {
	return mCreatedBy;
}
void ODSFile::setCreatedBy(QString newCreatedBy) {
	if (newCreatedBy != mCreatedBy) {
		mCreatedBy = newCreatedBy;
		emit createdByChanged(newCreatedBy);
	}
}

QString ODSFile::createdAt() const {
	return mCreatedAt;
}
void ODSFile::setCreatedAt(QString newCreatedAt) {
	if (newCreatedAt != mCreatedAt) {
		mCreatedAt = newCreatedAt;
		emit createdByChanged(newCreatedAt);
	}
}

int ODSFile::id() const {
	return mId;
}
void ODSFile::setId(int id) {
	if (id != mId) {
		mId = id;
		emit idChanged(id);
	}
}

int ODSFile::level() const {
	return mLevel;
}
void ODSFile::setLevel(int level) {
	if (level != mLevel) {
		mLevel = level;
		emit levelChanged(level);
	}
}

int ODSFile::containerId() const {
	return mContainerId;
}
void ODSFile::setContainerId(int containerId) {
	if (containerId != mContainerId) {
		mContainerId = containerId;
		emit containerIdChanged(containerId);
	}
}

int ODSFile::fileSize() const {
	return mFileSize;
}
void ODSFile::setFileSize(int fileSize) {
	if (fileSize != mFileSize) {
		mFileSize = fileSize;
		emit fileSizeChanged(fileSize);
	}
}

int ODSFile::classification() const {
	return mClassification;
}
void ODSFile::setClassification(int classification) {
	if (classification != mClassification) {
		mClassification = classification;
		emit classificationChanged(classification);
	}
}

QString ODSFile::displayType() const {
	return mDisplayType;
}

QString ODSFile::displayIcon() const {
	return mDisplayIcon;
}

ODSFile::~ODSFile() {
	//
}

<|endoftext|>