<commit_before>// This file is part of the dune-stuff project:
//   https://users.dune-project.org/projects/dune-stuff
// Copyright holders: Rene Milk, Felix Schindler
// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)

/**
   *  \file   stuff.hh
   *  \brief  contains some stuff
   **/
#ifndef DUNE_STUFF_COMMON_STRING_HH
#define DUNE_STUFF_COMMON_STRING_HH

#include <cstring>
#include <ctime>
#include <map>
#include <assert.h>
#include <algorithm>

#include <dune/common/array.hh>
#include <dune/common/deprecated.hh>
#include <ostream>
#include <iomanip>
#include <vector>
#include <string>
#include <ctime>

#include <boost/algorithm/string.hpp>
#include <boost/lexical_cast.hpp>

namespace Dune {
namespace Stuff {
namespace Common {

//! simple and dumb std::string to anything conversion
template< class ReturnType >
inline ReturnType fromString(const std::string s) {
  return boost::lexical_cast<ReturnType, std::string>(s);
} // fromString

#define DSC_FRSTR(tn,tns) \
template<> \
inline tn fromString<tn>(const std::string s) { \
  return std::sto##tns(s); \
}

DSC_FRSTR(int, i)
DSC_FRSTR(long, l)
DSC_FRSTR(long long, ll)
DSC_FRSTR(unsigned long, ul)
DSC_FRSTR(unsigned long long, ull)
DSC_FRSTR(float,f)
DSC_FRSTR(double,d)
DSC_FRSTR(long double,ld)

#undef DSC_FRSTR

inline std::string toString(const char* s) {
  return std::string(s);
} // toString

inline std::string toString(const std::string s) {
  return std::string(s);
} // toString

//! simple and dumb anything to std::string conversion
template< class InType >
inline std::string toString(const InType& s) {
  return std::to_string(s);
} // toString

/**
  \brief      Returns a string of lengths s' whitespace (or c chars).
  \param[in]  s
              std::string, defines the length of the return string
  \param[in]  whitespace
              char, optional argument, defines entries of return string
  \return     std::string
              Returns a string of lengths s' whitespace (or c chars).
  **/
template< class T >
std::string whitespaceify(const T& t, const char whitespace = ' ')
{
  const std::string s = toString(t);
  std::string ret = "";
  for (unsigned int i = 0; i < s.size(); ++i) {
    ret += whitespace;
  }
  return ret;
} // std::string whitespaceify(const std::string s, const char whitespace = ' ')

/** \brief convenience wrapper around boost::algorithm::split to split one string into a vector of strings
 * \param msg the spring to be split
 * \param seperators a list of seperaors, duh
 * \param mode token_compress_off --> potentially empty strings in return,
              token_compress_on --> empty tokens are discarded
 * \return all tokens in a vector, if msg contains no seperators, this'll contain msg as its only element
 **/
template < class T = std::string >
inline std::vector<T> tokenize( const std::string& msg,
                             const std::string& seperators,
                             const boost::algorithm::token_compress_mode_type mode = boost::algorithm::token_compress_off )
{
    std::vector<std::string> strings;
    boost::algorithm::split( strings, msg, boost::algorithm::is_any_of(seperators),
                             mode );
    std::vector<T> ret(strings.size());
    size_t i = 0;
    //special case for empty strings to avoid non-default init
    std::generate(std::begin(ret), std::end(ret), [&] (){ return strings[i++].empty() ? T() : fromString<T>(strings[i-1]); });
    return ret;
}

template < >
inline std::vector<std::string> tokenize( const std::string& msg,
                             const std::string& seperators,
                             const boost::algorithm::token_compress_mode_type mode )
{
    std::vector<std::string> strings;
    boost::algorithm::split( strings, msg, boost::algorithm::is_any_of(seperators),
                             mode );
    return strings;
}

//! returns string with local time in current locale's format
inline std::string stringFromTime(time_t cur_time = time(NULL)) {
  return ctime(&cur_time);
}

//! helper struct for lexical cast
template <typename ElemT>
struct HexToString {
  // see http://stackoverflow.com/a/2079728
  ElemT value;
  operator ElemT() const {return value;}
  friend std::istream& operator>>(std::istream& in, HexToString& out) {
    in >> std::hex >> out.value;
    return in;
  }
};

// some legacy stuff I'd like to keep for a while
namespace String {

template< class T >
DUNE_DEPRECATED_MSG("use DSC::fromString instead, removal with stuff 2.3") T from(const std::string& s)
{
  std::stringstream ss;
  ss << s;
  T t;
  ss >> t;
  return t;
}

template< class T >
DUNE_DEPRECATED_MSG("use DSC::toString instead, removal with stuff 2.3") std::string to(const T& t)
{
  std::stringstream ss;
  ss << t;
  std::string s;
  ss >> s;
  return s;
}

DUNE_DEPRECATED_MSG("use the constructor call directly")
inline std::vector< std::string > mainArgsToVector(int argc, char** argv)
{
  return std::vector< std::string >(argv, argv + argc);
}

inline char** vectorToMainArgs(const std::vector< std::string > args)
{
  char** argv = new char* [args.size()];
  for (unsigned int ii = 0; ii < args.size(); ++ii) {
    argv[ii] = new char[args[ii].length() + 1];
    strcpy(argv[ii], args[ii].c_str());
  }
  return argv;
} // char** vectorToMainArgs(const std::vector< std::string > args)

} // namespace String

} // namespace Common
} // namespace Stuff
} // namespace Dune

#endif // DUNE_STUFF_COMMON_STRING_HH
<commit_msg>[common.string] use std::stringstream instead of to_string<commit_after>// This file is part of the dune-stuff project:
//   https://users.dune-project.org/projects/dune-stuff
// Copyright holders: Rene Milk, Felix Schindler
// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)

/**
   *  \file   stuff.hh
   *  \brief  contains some stuff
   **/
#ifndef DUNE_STUFF_COMMON_STRING_HH
#define DUNE_STUFF_COMMON_STRING_HH

#include <cstring>
#include <ctime>
#include <map>
#include <assert.h>
#include <algorithm>

#include <dune/common/array.hh>
#include <dune/common/deprecated.hh>
#include <ostream>
#include <iomanip>
#include <vector>
#include <string>
#include <ctime>

#include <boost/algorithm/string.hpp>
#include <boost/lexical_cast.hpp>

namespace Dune {
namespace Stuff {
namespace Common {

//! simple and dumb std::string to anything conversion
template< class ReturnType >
inline ReturnType fromString(const std::string s) {
  return boost::lexical_cast<ReturnType, std::string>(s);
} // fromString

#define DSC_FRSTR(tn,tns) \
template<> \
inline tn fromString<tn>(const std::string s) { \
  return std::sto##tns(s); \
}

DSC_FRSTR(int, i)
DSC_FRSTR(long, l)
DSC_FRSTR(long long, ll)
DSC_FRSTR(unsigned long, ul)
DSC_FRSTR(unsigned long long, ull)
DSC_FRSTR(float,f)
DSC_FRSTR(double,d)
DSC_FRSTR(long double,ld)

#undef DSC_FRSTR

inline std::string toString(const char* s) {
  return std::string(s);
} // toString

inline std::string toString(const std::string s) {
  return std::string(s);
} // toString

//! simple and dumb anything to std::string conversion
template< class InType >
inline std::string toString(const InType& s) {
  std::stringstream ss;
  ss << std::setprecision(17) << s;
  return ss.str();
} // toString

/**
  \brief      Returns a string of lengths s' whitespace (or c chars).
  \param[in]  s
              std::string, defines the length of the return string
  \param[in]  whitespace
              char, optional argument, defines entries of return string
  \return     std::string
              Returns a string of lengths s' whitespace (or c chars).
  **/
template< class T >
std::string whitespaceify(const T& t, const char whitespace = ' ')
{
  const std::string s = toString(t);
  std::string ret = "";
  for (unsigned int i = 0; i < s.size(); ++i) {
    ret += whitespace;
  }
  return ret;
} // std::string whitespaceify(const std::string s, const char whitespace = ' ')

/** \brief convenience wrapper around boost::algorithm::split to split one string into a vector of strings
 * \param msg the spring to be split
 * \param seperators a list of seperaors, duh
 * \param mode token_compress_off --> potentially empty strings in return,
              token_compress_on --> empty tokens are discarded
 * \return all tokens in a vector, if msg contains no seperators, this'll contain msg as its only element
 **/
template < class T = std::string >
inline std::vector<T> tokenize( const std::string& msg,
                             const std::string& seperators,
                             const boost::algorithm::token_compress_mode_type mode = boost::algorithm::token_compress_off )
{
    std::vector<std::string> strings;
    boost::algorithm::split( strings, msg, boost::algorithm::is_any_of(seperators),
                             mode );
    std::vector<T> ret(strings.size());
    size_t i = 0;
    //special case for empty strings to avoid non-default init
    std::generate(std::begin(ret), std::end(ret), [&] (){ return strings[i++].empty() ? T() : fromString<T>(strings[i-1]); });
    return ret;
}

template < >
inline std::vector<std::string> tokenize( const std::string& msg,
                             const std::string& seperators,
                             const boost::algorithm::token_compress_mode_type mode )
{
    std::vector<std::string> strings;
    boost::algorithm::split( strings, msg, boost::algorithm::is_any_of(seperators),
                             mode );
    return strings;
}

//! returns string with local time in current locale's format
inline std::string stringFromTime(time_t cur_time = time(NULL)) {
  return ctime(&cur_time);
}

//! helper struct for lexical cast
template <typename ElemT>
struct HexToString {
  // see http://stackoverflow.com/a/2079728
  ElemT value;
  operator ElemT() const {return value;}
  friend std::istream& operator>>(std::istream& in, HexToString& out) {
    in >> std::hex >> out.value;
    return in;
  }
};

// some legacy stuff I'd like to keep for a while
namespace String {

template< class T >
DUNE_DEPRECATED_MSG("use DSC::fromString instead, removal with stuff 2.3") T from(const std::string& s)
{
  std::stringstream ss;
  ss << s;
  T t;
  ss >> t;
  return t;
}

template< class T >
DUNE_DEPRECATED_MSG("use DSC::toString instead, removal with stuff 2.3") std::string to(const T& t)
{
  std::stringstream ss;
  ss << t;
  std::string s;
  ss >> s;
  return s;
}

DUNE_DEPRECATED_MSG("use the constructor call directly")
inline std::vector< std::string > mainArgsToVector(int argc, char** argv)
{
  return std::vector< std::string >(argv, argv + argc);
}

inline char** vectorToMainArgs(const std::vector< std::string > args)
{
  char** argv = new char* [args.size()];
  for (unsigned int ii = 0; ii < args.size(); ++ii) {
    argv[ii] = new char[args[ii].length() + 1];
    strcpy(argv[ii], args[ii].c_str());
  }
  return argv;
} // char** vectorToMainArgs(const std::vector< std::string > args)

} // namespace String

} // namespace Common
} // namespace Stuff
} // namespace Dune

#endif // DUNE_STUFF_COMMON_STRING_HH
<|endoftext|>


<commit_before>#include <iostream>
#include <string>
#include <cstdlib>
#include <fstream>
#include <vector>
#include <cmath>
#include <sstream>
#include <stdio.h>
#include <unistd.h>
#include "Command.h"
using namespace std;

Command::Command()
{
    cmdVec.size() = 0;
}

void Command::addPart(string comm)
{
    cmdVec.push_back(comm);
}

int Command::execute()
{
    int pid = -1;

    pid = fork();
}<commit_msg>prototyped execute function<commit_after>#include <iostream>
#include <string>
#include <cstdlib>
#include <fstream>
#include <vector>
#include <cmath>
#include <sstream>
#include <stdio.h>
#include <unistd.h>
#include "Command.h"
using namespace std;

Command::Command()
{
    cmdVec.size() = 0;
}

void Command::addPart(string comm)
{
    cmdVec.push_back(comm);
}

int Command::execute()
{
    int status = 0;
    char *parameter;
    parameter = new char[cmdVec.size()];
    for(int i = 0; i < cmdVec.size(); ++i)
    {
        parameter[i] = cmdVec[i];
    }
    int pid = -1;

    pid = fork();

    if(pid == 0)
    {
        status = execvp(cmdVec[0], cmdVec);
    }
    else
    {
        wait(0);
        return status;
    }
}<|endoftext|>


<commit_before>/**
 * @file Cosa/OWI.hh
 * @version 1.0
 *
 * @section License
 * Copyright (C) 2012-2013, Mikael Patel
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General
 * Public License along with this library; if not, write to the
 * Free Software Foundation, Inc., 59 Temple Place, Suite 330,
 * Boston, MA  02111-1307  USA
 *
 * This file is part of the Arduino Che Cosa project.
 */

#ifndef __COSA_OWI_HH__
#define __COSA_OWI_HH__

#include "Cosa/Types.h"
#include "Cosa/Pins.hh"
#include "Cosa/ExternalInterrupt.hh"
#include "Cosa/IOStream.hh"

/**
 * 1-wire device driver support class. Allows device rom search
 * and connection to multiple devices on one-wire bus.
 *
 * @section Limitations
 * The driver will turn off interrupt handling during data read
 * from the device.
 */
class OWI : private IOPin {
public:
  /**
   * ROM Commands and Size
   */
  enum {
    SEARCH_ROM = 0xF0,
    READ_ROM = 0x33,
    MATCH_ROM = 0x55,
    SKIP_ROM = 0xCC,
    ALARM_SEARCH = 0xEC
  } __attribute__((packed));
  static const uint8_t ROM_MAX = 8;
  static const uint8_t ROMBITS = ROM_MAX * CHARBITS;

  /**
   * Driver for device connected to a one-wire bus.
   */
  class Driver {
    friend class OWI;
    friend IOStream& operator<<(IOStream& outs, OWI& owi);
    friend IOStream& operator<<(IOStream& outs, Driver& dev);
  public:
    enum {
      FIRST = -1,
      ERROR = -1,
      LAST = ROMBITS
    } __attribute__((packed));
  protected:
    uint8_t m_rom[ROM_MAX];
    const uint8_t* ROM;
    Driver* m_next;
    OWI* m_pin;

    /**
     * Search device rom given the last position of discrepancy.
     * Negative value for start from the beginning.
     * @param[in] last position of discrepancy.
     * @return position of difference or negative error code.
     */
    int8_t search(int8_t last = FIRST);

  public:
    /** Name of device driver instance */
    const char* NAME;

    /**
     * Construct one wire device driver. Use one wire bus on given pin.
     * @param[in] pin one wire bus.
     * @param[in] name of device driver instance.
     */
    Driver(OWI* pin, const char* name = 0) :
      ROM(0),
      m_next(0),
      m_pin(pin),
      NAME(name)
    {}

    /**
     * Construct one wire device driver. Use one wire bus on given pin,
     * and given rom identity in EEPROM (or NULL).
     * @param[in] pin one wire bus.
     * @param[in] rom identity.
     * @param[in] name of device driver instance.
     */
    Driver(OWI* pin, const uint8_t* rom, const char* name = 0);

    /**
     * Return pointer to device rom.
     * @return device rom buffer.
     */
    uint8_t* get_rom()
    {
      return (m_rom);
    }

    /**
     * Update the rom identity (in EEPROM). Return true(1) if
     * successful otherwise false(0). Typically used to save
     * configuration after connect().
     * return bool.
     */
    bool update_rom();

    /**
     * Search device rom given the last position of discrepancy.
     * Negative value for start from the beginning.
     * @param[in] last position of discrepancy.
     * @return position of difference or negative error code.
     */
    int8_t search_rom(int8_t last = FIRST);

    /**
     * Read device rom. This can only be used when there is only
     * one slave on the bus.
     * @return true(1) if successful otherwise false(0).
     */
    bool read_rom();

    /**
     * Match device rom. Address the slave device with the
     * rom code. Device specific function command should follow.
     * May be used to verify rom code.
     * @return true(1) if successful otherwise false(0).
     */
    bool match_rom();

    /**
     * Skip device rom for boardcast or single device access.
     * Device specific function command should follow.
     * @return true(1) if successful otherwise false(0).
     */
    bool skip_rom();

    /**
     * Search alarming device given the last position of discrepancy.
     * Negative value for start from the beginning.
     * @param[in] last position of discrepancy.
     * @return position of difference or negative error code.
     */
    int8_t alarm_search(int8_t last = FIRST);

    /**
     * Connect to one-wire device with given family code and index.
     * @param[in] family device family code.
     * @param[in] index device order.
     * @return true(1) if successful otherwise false(0).
     */
    bool connect(uint8_t family, uint8_t index);

    /**
     * @override
     * Callback on alarm dispatch. Default is empty function.
     */
    virtual void on_alarm() {}
  };

  /**
   * Alarm search iterator class.
   */
  class Search : private Driver {
  private:
    uint8_t m_family;
    int8_t m_last;
  public:
    /**
     * Initiate an alarm search iterator for the given one-wire bus and
     * device family code.
     * @param[in] owi one-wire bus.
     * @param[in] family code (default all).
     */
    Search(OWI* owi, uint8_t family = 0) :
      Driver(owi),
      m_family(family),
      m_last(FIRST)
    {
    }

    /**
     * Get the next device with an active alarm.
     * @return pointer to driver or null(0).
     */
    Driver* next();

    /**
     * Reset iterator.
     */
    void reset()
    {
      m_last = FIRST;
    }
  };

  /**
   * Act as slave device connected to a one-wire bus.
   */
  class Device : public ExternalInterrupt {
    friend class OWI;
  private:
    // One-wire slave pin mode
    enum Mode {
      OUTPUT_MODE = 0,
      INPUT_MODE = 1
    } __attribute__((packed));

    // One-wire slave states
    enum State {
      IDLE_STATE,
      RESET_STATE,
      PRESENCE_STATE,
      ROM_STATE,
      FUNCTION_STATE
    } __attribute__((packed));

    /**
     * Set slave device pin input/output mode.
     * @param[in] mode pin mode.
     */
    void set_mode(Mode mode)
    {
      synchronized {
	if (mode == OUTPUT_MODE)
	  *DDR() |= m_mask;
	else
	  *DDR() &= ~m_mask;
      }
    }

    /**
     * Set slave device pin.
     */
    void set()
    {
      synchronized {
	*PORT() |= m_mask;
      }
    }

    /**
     * Clear slave device pin.
     */
    void clear()
    {
      synchronized {
	*PORT() &= ~m_mask;
      }
    }

    /**
     * Read the given number of bits from the one wire bus (master).
     * Default number of bits is 8. Returns the value read LSB aligned.
     * or negative error code.
     * @param[in] bits to be read.
     * @return value read.
     */
    int read(uint8_t bits = CHARBITS);

    /**
     * Write the given value to the one wire bus. The bits are written
     * from LSB to MSB. Return true(1) if successful otherwise false(0).
     * @param[in] value.
     * @param[in] bits to be written.
     */
    bool write(uint8_t value, uint8_t bits);

    /**
     * @override
     * Slave device event handler function. Handle presence pulse and
     * rom/function command parsing.
     * @param[in] type the type of event.
     * @param[in] value the event value.
     */
    virtual void on_event(uint8_t type, uint16_t value);

    /**
     * @override
     * Slave device interrupt handler function. Detect reset and initiate
     * presence pulse. Push service_request event for further handling.
     * @param[in] arg argument from interrupt service routine.
     */
    virtual void on_interrupt(uint16_t arg = 0);

  protected:
    uint8_t* m_rom;
    volatile uint32_t m_time;
    volatile uint8_t m_crc;
    volatile State m_state;

  public:
    // Slave function codes
    enum {
      STATUS = 0x11
    } __attribute__((packed));

    /**
     * Construct one wire slave device connected to the given pin and
     * rom identity code. Note: crc is generated automatically.
     * @param[in] pin number.
     * @param[in] rom identity number.
     */
    Device(Board::ExternalInterruptPin pin, uint8_t* rom) :
      ExternalInterrupt(pin, ExternalInterrupt::ON_CHANGE_MODE),
      m_rom(rom),
      m_time(0),
      m_crc(0),
      m_state(IDLE_STATE)
    {
    }
  };

private:
  /** Number of devices */
  uint8_t m_devices;

  /** List of slave devices */
  Driver* m_device;

  /** Intermediate CRC sum */
  uint8_t m_crc;

public:
  /**
   * Construct one wire bus connected to the given pin.
   * @param[in] pin number.
   */
  OWI(Board::DigitalPin pin) :
    IOPin(pin),
    m_devices(0),
    m_device(0),
    m_crc(0)
  {}

  /**
   * Reset the one wire bus and check that at least one device is
   * presence.
   * @return true(1) if successful otherwise false(0).
   */
  bool reset();

  /**
   * Read the given number of bits from the one wire bus (slave).
   * Default number of bits is 8. Returns the value read LSB aligned.
   * @param[in] bits to be read.
   * @return value read.
   */
  uint8_t read(uint8_t bits = CHARBITS);

  /**
   * Read given number of bytes from one wire bus (slave) to given
   * buffer. Return true(1) if correctly read otherwise false(0).
   * @param[in] buf buffer pointer.
   * @param[in] size number of bytes to read.
   * @return bool.
   */
  bool read(void* buf, uint8_t size);

  /**
   * Write the given value to the one wire bus. The bits are written
   * from LSB to MSB. Pass true(1) for power parameter to allow
   * parasite devices to be powered. Should be turned off with power_off().
   * @param[in] value to write.
   * @param[in] bits to be written.
   * @param[in] power on for parasite device.
   */
  void write(uint8_t value, uint8_t bits = CHARBITS, bool power = false);

  /**
   * Write the given value and given number of bytes from buffer to
   * the one wire bus (slave).
   * @param[in] value to write.
   * @param[in] buf buffer pointer.
   * @param[in] size number of bytes to write.
   */
  void write(uint8_t value, void* buf, uint8_t size);

  /**
   * Turn off parasite powering of pin. See also write().
   */
  void power_off()
  {
    set_mode(INPUT_MODE);
    clear();
  }

  /**
   * Lookup the driver instance with the given rom address.
   * @return driver pointer or null(0).
   */
  Driver* lookup(uint8_t* rom);

  /**
   * Search drivers with alarm setting and call on_alarm().
   * Return true(1) if there was at least one driver with an alarm,
   * otherwise when no alarms false(0).
   * @return bool.
   */
  bool alarm_dispatch();
};

/**
 * Print device driver name and rom to output stream.
 * @param[in] outs stream to print to.
 * @param[in] dev owi device driver.
 * @return output stream.
 */
IOStream& operator<<(IOStream& outs, OWI::Driver& dev);

/**
 * Print list of connected devices on given stream.
 * @param[in] outs stream to print device information to.
 * @param[in] owi one-wire bus.
 * @return output stream.
 */
IOStream& operator<<(IOStream& outs, OWI& owi);

#endif

<commit_msg>Adjusting visibility of OWI::Search member variable for sub-classing.<commit_after>/**
 * @file Cosa/OWI.hh
 * @version 1.0
 *
 * @section License
 * Copyright (C) 2012-2013, Mikael Patel
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General
 * Public License along with this library; if not, write to the
 * Free Software Foundation, Inc., 59 Temple Place, Suite 330,
 * Boston, MA  02111-1307  USA
 *
 * This file is part of the Arduino Che Cosa project.
 */

#ifndef __COSA_OWI_HH__
#define __COSA_OWI_HH__

#include "Cosa/Types.h"
#include "Cosa/Pins.hh"
#include "Cosa/ExternalInterrupt.hh"
#include "Cosa/IOStream.hh"

/**
 * 1-wire device driver support class. Allows device rom search
 * and connection to multiple devices on one-wire bus.
 *
 * @section Limitations
 * The driver will turn off interrupt handling during data read
 * from the device.
 */
class OWI : private IOPin {
public:
  /**
   * ROM Commands and Size
   */
  enum {
    SEARCH_ROM = 0xF0,
    READ_ROM = 0x33,
    MATCH_ROM = 0x55,
    SKIP_ROM = 0xCC,
    ALARM_SEARCH = 0xEC
  } __attribute__((packed));
  static const uint8_t ROM_MAX = 8;
  static const uint8_t ROMBITS = ROM_MAX * CHARBITS;

  /**
   * Driver for device connected to a one-wire bus.
   */
  class Driver {
    friend class OWI;
    friend IOStream& operator<<(IOStream& outs, OWI& owi);
    friend IOStream& operator<<(IOStream& outs, Driver& dev);
  public:
    enum {
      FIRST = -1,
      ERROR = -1,
      LAST = ROMBITS
    } __attribute__((packed));
  protected:
    uint8_t m_rom[ROM_MAX];
    const uint8_t* ROM;
    Driver* m_next;
    OWI* m_pin;

    /**
     * Search device rom given the last position of discrepancy.
     * Negative value for start from the beginning.
     * @param[in] last position of discrepancy.
     * @return position of difference or negative error code.
     */
    int8_t search(int8_t last = FIRST);

  public:
    /** Name of device driver instance */
    const char* NAME;

    /**
     * Construct one wire device driver. Use one wire bus on given pin.
     * @param[in] pin one wire bus.
     * @param[in] name of device driver instance.
     */
    Driver(OWI* pin, const char* name = 0) :
      ROM(0),
      m_next(0),
      m_pin(pin),
      NAME(name)
    {}

    /**
     * Construct one wire device driver. Use one wire bus on given pin,
     * and given rom identity in EEPROM (or NULL).
     * @param[in] pin one wire bus.
     * @param[in] rom identity.
     * @param[in] name of device driver instance.
     */
    Driver(OWI* pin, const uint8_t* rom, const char* name = 0);

    /**
     * Return pointer to device rom.
     * @return device rom buffer.
     */
    uint8_t* get_rom()
    {
      return (m_rom);
    }

    /**
     * Update the rom identity (in EEPROM). Return true(1) if
     * successful otherwise false(0). Typically used to save
     * configuration after connect().
     * return bool.
     */
    bool update_rom();

    /**
     * Search device rom given the last position of discrepancy.
     * Negative value for start from the beginning.
     * @param[in] last position of discrepancy.
     * @return position of difference or negative error code.
     */
    int8_t search_rom(int8_t last = FIRST);

    /**
     * Read device rom. This can only be used when there is only
     * one slave on the bus.
     * @return true(1) if successful otherwise false(0).
     */
    bool read_rom();

    /**
     * Match device rom. Address the slave device with the
     * rom code. Device specific function command should follow.
     * May be used to verify rom code.
     * @return true(1) if successful otherwise false(0).
     */
    bool match_rom();

    /**
     * Skip device rom for boardcast or single device access.
     * Device specific function command should follow.
     * @return true(1) if successful otherwise false(0).
     */
    bool skip_rom();

    /**
     * Search alarming device given the last position of discrepancy.
     * Negative value for start from the beginning.
     * @param[in] last position of discrepancy.
     * @return position of difference or negative error code.
     */
    int8_t alarm_search(int8_t last = FIRST);

    /**
     * Connect to one-wire device with given family code and index.
     * @param[in] family device family code.
     * @param[in] index device order.
     * @return true(1) if successful otherwise false(0).
     */
    bool connect(uint8_t family, uint8_t index);

    /**
     * @override
     * Callback on alarm dispatch. Default is empty function.
     */
    virtual void on_alarm() {}
  };

  /**
   * Alarm search iterator class.
   */
  class Search : protected Driver {
  protected:
    uint8_t m_family;
    int8_t m_last;
  public:
    /**
     * Initiate an alarm search iterator for the given one-wire bus and
     * device family code.
     * @param[in] owi one-wire bus.
     * @param[in] family code (default all).
     */
    Search(OWI* owi, uint8_t family = 0) :
      Driver(owi),
      m_family(family),
      m_last(FIRST)
    {
    }

    /**
     * Get the next device with an active alarm.
     * @return pointer to driver or null(0).
     */
    Driver* next();

    /**
     * Reset iterator.
     */
    void reset()
    {
      m_last = FIRST;
    }
  };

  /**
   * Act as slave device connected to a one-wire bus.
   */
  class Device : public ExternalInterrupt {
    friend class OWI;
  private:
    // One-wire slave pin mode
    enum Mode {
      OUTPUT_MODE = 0,
      INPUT_MODE = 1
    } __attribute__((packed));

    // One-wire slave states
    enum State {
      IDLE_STATE,
      RESET_STATE,
      PRESENCE_STATE,
      ROM_STATE,
      FUNCTION_STATE
    } __attribute__((packed));

    /**
     * Set slave device pin input/output mode.
     * @param[in] mode pin mode.
     */
    void set_mode(Mode mode)
    {
      synchronized {
	if (mode == OUTPUT_MODE)
	  *DDR() |= m_mask;
	else
	  *DDR() &= ~m_mask;
      }
    }

    /**
     * Set slave device pin.
     */
    void set()
    {
      synchronized {
	*PORT() |= m_mask;
      }
    }

    /**
     * Clear slave device pin.
     */
    void clear()
    {
      synchronized {
	*PORT() &= ~m_mask;
      }
    }

    /**
     * Read the given number of bits from the one wire bus (master).
     * Default number of bits is 8. Returns the value read LSB aligned.
     * or negative error code.
     * @param[in] bits to be read.
     * @return value read.
     */
    int read(uint8_t bits = CHARBITS);

    /**
     * Write the given value to the one wire bus. The bits are written
     * from LSB to MSB. Return true(1) if successful otherwise false(0).
     * @param[in] value.
     * @param[in] bits to be written.
     */
    bool write(uint8_t value, uint8_t bits);

    /**
     * @override
     * Slave device event handler function. Handle presence pulse and
     * rom/function command parsing.
     * @param[in] type the type of event.
     * @param[in] value the event value.
     */
    virtual void on_event(uint8_t type, uint16_t value);

    /**
     * @override
     * Slave device interrupt handler function. Detect reset and initiate
     * presence pulse. Push service_request event for further handling.
     * @param[in] arg argument from interrupt service routine.
     */
    virtual void on_interrupt(uint16_t arg = 0);

  protected:
    uint8_t* m_rom;
    volatile uint32_t m_time;
    volatile uint8_t m_crc;
    volatile State m_state;

  public:
    // Slave function codes
    enum {
      STATUS = 0x11
    } __attribute__((packed));

    /**
     * Construct one wire slave device connected to the given pin and
     * rom identity code. Note: crc is generated automatically.
     * @param[in] pin number.
     * @param[in] rom identity number.
     */
    Device(Board::ExternalInterruptPin pin, uint8_t* rom) :
      ExternalInterrupt(pin, ExternalInterrupt::ON_CHANGE_MODE),
      m_rom(rom),
      m_time(0),
      m_crc(0),
      m_state(IDLE_STATE)
    {
    }
  };

private:
  /** Number of devices */
  uint8_t m_devices;

  /** List of slave devices */
  Driver* m_device;

  /** Intermediate CRC sum */
  uint8_t m_crc;

public:
  /**
   * Construct one wire bus connected to the given pin.
   * @param[in] pin number.
   */
  OWI(Board::DigitalPin pin) :
    IOPin(pin),
    m_devices(0),
    m_device(0),
    m_crc(0)
  {}

  /**
   * Reset the one wire bus and check that at least one device is
   * presence.
   * @return true(1) if successful otherwise false(0).
   */
  bool reset();

  /**
   * Read the given number of bits from the one wire bus (slave).
   * Default number of bits is 8. Returns the value read LSB aligned.
   * @param[in] bits to be read.
   * @return value read.
   */
  uint8_t read(uint8_t bits = CHARBITS);

  /**
   * Read given number of bytes from one wire bus (slave) to given
   * buffer. Return true(1) if correctly read otherwise false(0).
   * @param[in] buf buffer pointer.
   * @param[in] size number of bytes to read.
   * @return bool.
   */
  bool read(void* buf, uint8_t size);

  /**
   * Write the given value to the one wire bus. The bits are written
   * from LSB to MSB. Pass true(1) for power parameter to allow
   * parasite devices to be powered. Should be turned off with power_off().
   * @param[in] value to write.
   * @param[in] bits to be written.
   * @param[in] power on for parasite device.
   */
  void write(uint8_t value, uint8_t bits = CHARBITS, bool power = false);

  /**
   * Write the given value and given number of bytes from buffer to
   * the one wire bus (slave).
   * @param[in] value to write.
   * @param[in] buf buffer pointer.
   * @param[in] size number of bytes to write.
   */
  void write(uint8_t value, void* buf, uint8_t size);

  /**
   * Turn off parasite powering of pin. See also write().
   */
  void power_off()
  {
    set_mode(INPUT_MODE);
    clear();
  }

  /**
   * Lookup the driver instance with the given rom address.
   * @return driver pointer or null(0).
   */
  Driver* lookup(uint8_t* rom);

  /**
   * Search drivers with alarm setting and call on_alarm().
   * Return true(1) if there was at least one driver with an alarm,
   * otherwise when no alarms false(0).
   * @return bool.
   */
  bool alarm_dispatch();
};

/**
 * Print device driver name and rom to output stream.
 * @param[in] outs stream to print to.
 * @param[in] dev owi device driver.
 * @return output stream.
 */
IOStream& operator<<(IOStream& outs, OWI::Driver& dev);

/**
 * Print list of connected devices on given stream.
 * @param[in] outs stream to print device information to.
 * @param[in] owi one-wire bus.
 * @return output stream.
 */
IOStream& operator<<(IOStream& outs, OWI& owi);

#endif

<|endoftext|>


<commit_before>
<commit_msg>Update Cviko_5.cpp<commit_after>
#pragma once
#include "stdafx.h"
#include <iostream>

class Atributy
{
protected:
	int typ;
	double stranaA, stranaB, stranaC, stranaD, vyska, polomer;
public:
	Atributy(double A, double B, double C, double D, double v, double r) {
		stranaA = A;
		stranaB = B;
		stranaC = C;
		stranaD = D;
		vyska = v;
		polomer = r;
	}

	virtual double obvod() {
		double obvod = 0;
		obvod = stranaA + stranaB + stranaC + stranaD;
		return obvod;
	}

	virtual double obsah() {
		double obsah = 0;
		obsah = stranaA * stranaB;
		return obsah;
	}

	virtual string vypis_obvod(string obvod) {

		return string("obvod utvaru: " + obvod);
	}

	virtual string vypis_obsah(string obsah) {

		return string("obsah utvaru: " + obsah);
	}

	virtual string console_string(void) {
		return string("Strana A: " + stranaA + "Strana B: " + stranaB + "Strana C: " + stranaC + "vyska: " + vyska + "polomer: " + polomer);
	}
	void tisk(void) {
		printf("%lf", console_string);
	}
};

class Tvar : public Atributy
{
protected:
	char nazev;
public:
	Tvar(double A, double B, double C, double D, double v, double r, char n) : Atributy(A, B, C, D, v, r)
	{
		nazev = n;
	}

	virtual string console_string(void)
	{
		return string("Strana A : " + stranaA + "Strana B : " + stranaB + "Strana C : " + stranaC + "vyska : " + vyska + "polomer : " + polomer + "nazev: " + nazev);
	}

};

class Kruh : public Atributy
{
public:
	Kruh(double a) : Atributy(r);

};

<|endoftext|>


<commit_before>// Ouzel by Elviss Strazdins

#ifndef OUZEL_THREAD_SEMAPHORE_HPP
#define OUZEL_THREAD_SEMAPHORE_HPP

#include <system_error>
#ifdef _WIN32
#  pragma push_macro("WIN32_LEAN_AND_MEAN")
#  pragma push_macro("NOMINMAX")
#  ifndef WIN32_LEAN_AND_MEAN
#    define WIN32_LEAN_AND_MEAN
#  endif
#  ifndef NOMINMAX
#    define NOMINMAX
#  endif
#  include <Windows.h>
#  pragma pop_macro("WIN32_LEAN_AND_MEAN")
#  pragma pop_macro("NOMINMAX")
#elif defined(__APPLE__)
#  include <dispatch/dispatch.h>
#else
#  include <semaphore.h>
#endif

namespace ouzel::thread
{
    class Semaphore final
    {
    public:
        Semaphore(std::ptrdiff_t initValue = 0)
#ifdef _MSC_VER
            : semaphore{CreateSemaphore(nullptr, static_cast<LONG>(initValue), 0x7FFFFFFF, nullptr)}
#elif defined(__APPLE__)
            : semaphore{dispatch_semaphore_create(static_cast<ptrdiff_t>(initValue))}
#endif
        {
#ifdef _MSC_VER
            if (semaphore == INVALID_HANDLE_VALUE)
                throw std::system_error(GetLastError(), std::system_category(), "Failed to create semaphore");
#elif defined(__APPLE__)
            if (!semaphore)
                throw std::runtime_error("Failed to create semaphore");
#else
            if (sem_init(&semaphore, 0, static_cast<unsigned int>(initValue)) == -1)
                throw std::system_error(errno, std::system_category(), "Failed to open semaphore");
#endif
        }

        ~Semaphore()
        {
#ifdef _MSC_VER
            if (semaphore != INVALID_HANDLE_VALUE)
                CloseHandle(semaphore);
#elif defined(__APPLE__)
            if (semaphore)
                dispatch_release(semaphore);
#else
            if (semaphore != -1)
                sem_destroy(&semaphore);
#endif
        }

        Semaphore(const Semaphore&) = delete;
        Semaphore(Semaphore&& other) noexcept:
            semaphore{other.semaphore}
        {
#ifdef _MSC_VER
            other.semaphore = INVALID_HANDLE_VALUE;
#elif defined(__APPLE__)
            other.semaphore = nullptr;
#else
            other.semaphore = -1;
#endif
        }

        Semaphore& operator=(const Semaphore&) = delete;
        Semaphore& operator=(Semaphore&& other) noexcept
        {
            if (&other == this) return *this;

            semaphore = other.semaphore;

#ifdef _MSC_VER
            other.semaphore = INVALID_HANDLE_VALUE;
#elif defined(__APPLE__)
            other.semaphore = nullptr;
#else
            other.semaphore = -1;
#endif

            return *this;
        }

        void acquire()
        {
#ifdef _MSC_VER
            if (WaitForSingleObject(semaphore, INFINITE) == WAIT_FAILED)
                throw std::system_error(GetLastError(), std::system_category(), "Failed to wait for semaphore");
#elif defined(__APPLE__)
            if (dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER) != 0)
                throw std::runtime_error("Failed to wait for semaphore");
#else
            while (sem_wait(&semaphore) == -1)
                if (errno != EINTR)
                    throw std::system_error(errno, std::system_category(), "Failed to wait for semaphore");
#endif
        }

        void release(std::ptrdiff_t count = 1)
        {
#ifdef _MSC_VER
            if (!ReleaseSemaphore(semaphore, static_cast<LONG>(count), nullptr))
                throw std::system_error(GetLastError(), std::system_category(), "Failed to release semaphore");
#elif defined(__APPLE__)
            while (count-- > 0)
                if (dispatch_semaphore_signal(semaphore) != 0)
                    throw std::runtime_error("Failed to signal semaphore");
#else
            while (count-- > 0)
                if (sem_post(&semaphore) == -1)
                    throw std::system_error(errno, std::system_category(), "Failed to post semaphore");
#endif
        }

    private:
#ifdef _MSC_VER
        HANDLE semaphore = INVALID_HANDLE_VALUE;
#elif defined(__APPLE__)
        dispatch_semaphore_t semaphore = nullptr;
#else
        sem_t semaphore = -1;
#endif
    };
}

#endif // OUZEL_THREAD_SEMAPHORE_HPP
<commit_msg>Delete Semaphore's move constructor and assignment operator<commit_after>// Ouzel by Elviss Strazdins

#ifndef OUZEL_THREAD_SEMAPHORE_HPP
#define OUZEL_THREAD_SEMAPHORE_HPP

#include <system_error>
#ifdef _WIN32
#  pragma push_macro("WIN32_LEAN_AND_MEAN")
#  pragma push_macro("NOMINMAX")
#  ifndef WIN32_LEAN_AND_MEAN
#    define WIN32_LEAN_AND_MEAN
#  endif
#  ifndef NOMINMAX
#    define NOMINMAX
#  endif
#  include <Windows.h>
#  pragma pop_macro("WIN32_LEAN_AND_MEAN")
#  pragma pop_macro("NOMINMAX")
#elif defined(__APPLE__)
#  include <dispatch/dispatch.h>
#else
#  include <semaphore.h>
#endif

namespace ouzel::thread
{
    class Semaphore final
    {
    public:
        Semaphore(std::ptrdiff_t initValue = 0)
#ifdef _MSC_VER
            : semaphore{CreateSemaphore(nullptr, static_cast<LONG>(initValue), 0x7FFFFFFF, nullptr)}
#elif defined(__APPLE__)
            : semaphore{dispatch_semaphore_create(static_cast<ptrdiff_t>(initValue))}
#endif
        {
#ifdef _MSC_VER
            if (semaphore == INVALID_HANDLE_VALUE)
                throw std::system_error(GetLastError(), std::system_category(), "Failed to create semaphore");
#elif defined(__APPLE__)
            if (!semaphore)
                throw std::runtime_error("Failed to create semaphore");
#else
            if (sem_init(&semaphore, 0, static_cast<unsigned int>(initValue)) == -1)
                throw std::system_error(errno, std::system_category(), "Failed to open semaphore");
#endif
        }

        ~Semaphore()
        {
#ifdef _MSC_VER
                CloseHandle(semaphore);
#elif defined(__APPLE__)
                dispatch_release(semaphore);
#else
                sem_destroy(&semaphore);
#endif
        }

        Semaphore(const Semaphore&) = delete;
        Semaphore(Semaphore&& other) = delete;

        Semaphore& operator=(const Semaphore&) = delete;
        Semaphore& operator=(Semaphore&& other) = delete;

        void acquire()
        {
#ifdef _MSC_VER
            if (WaitForSingleObject(semaphore, INFINITE) == WAIT_FAILED)
                throw std::system_error(GetLastError(), std::system_category(), "Failed to wait for semaphore");
#elif defined(__APPLE__)
            if (dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER) != 0)
                throw std::runtime_error("Failed to wait for semaphore");
#else
            while (sem_wait(&semaphore) == -1)
                if (errno != EINTR)
                    throw std::system_error(errno, std::system_category(), "Failed to wait for semaphore");
#endif
        }

        void release(std::ptrdiff_t count = 1)
        {
#ifdef _MSC_VER
            if (!ReleaseSemaphore(semaphore, static_cast<LONG>(count), nullptr))
                throw std::system_error(GetLastError(), std::system_category(), "Failed to release semaphore");
#elif defined(__APPLE__)
            while (count-- > 0)
                if (dispatch_semaphore_signal(semaphore) != 0)
                    throw std::runtime_error("Failed to signal semaphore");
#else
            while (count-- > 0)
                if (sem_post(&semaphore) == -1)
                    throw std::system_error(errno, std::system_category(), "Failed to post semaphore");
#endif
        }

    private:
#ifdef _MSC_VER
        HANDLE semaphore;
#elif defined(__APPLE__)
        dispatch_semaphore_t semaphore;
#else
        sem_t semaphore;
#endif
    };
}

#endif // OUZEL_THREAD_SEMAPHORE_HPP
<|endoftext|>


<commit_before>// This file is part of the AliceVision project.
// Copyright (c) 2016 AliceVision contributors.
// This Source Code Form is subject to the terms of the Mozilla Public License,
// v. 2.0. If a copy of the MPL was not distributed with this file,
// You can obtain one at https://mozilla.org/MPL/2.0/.

#include "aliceVision/calibration/calibration.hpp"

#include <opencv2/calib3d.hpp>

#include <aliceVision/system/Logger.hpp>
#include <aliceVision/system/Timer.hpp>

#include <ctime>
#include <algorithm>
#include <iostream>

namespace aliceVision{
namespace calibration{

double computeReprojectionErrors(const std::vector<std::vector<cv::Point3f> >& objectPoints,
                                 const std::vector<std::vector<cv::Point2f> >& imagePoints,
                                 const std::vector<cv::Mat>& rvecs, const std::vector<cv::Mat>& tvecs,
                                 const cv::Mat& cameraMatrix, const cv::Mat& distCoeffs,
                                 std::vector<float>& perViewErrors)
{
  std::vector<cv::Point2f> imagePoints2;
  int totalPoints = 0;
  double totalErr = 0;
  perViewErrors.resize(objectPoints.size());

  for (std::size_t i = 0; i < (int) objectPoints.size(); i++)
  {
    cv::projectPoints(cv::Mat(objectPoints[i]), rvecs[i], tvecs[i],
                      cameraMatrix, distCoeffs, imagePoints2);
    const double err = cv::norm(cv::Mat(imagePoints[i]), cv::Mat(imagePoints2), cv::NORM_L2);
    const std::size_t n = (int) objectPoints[i].size();
    perViewErrors[i] = (float) std::sqrt(err * err / n);
    totalErr += err*err;
    totalPoints += n;
  }
  return std::sqrt(totalErr / totalPoints);
}

bool runCalibration(const std::vector<std::vector<cv::Point2f> >& imagePoints,
                    const std::vector<std::vector<cv::Point3f> >& objectPoints,
                    const cv::Size& imageSize,
                    float aspectRatio,
                    int cvCalibFlags,
                    cv::Mat& cameraMatrix,
                    cv::Mat& distCoeffs,
                    std::vector<cv::Mat>& rvecs,
                    std::vector<cv::Mat>& tvecs,
                    std::vector<float>& reprojErrs,
                    double& totalAvgErr)
{
  rvecs.resize(0);
  tvecs.resize(0);
  reprojErrs.resize(0);
  cameraMatrix = cv::Mat::eye(3, 3, CV_64F);
  if (cvCalibFlags & cv::CALIB_FIX_ASPECT_RATIO)
    cameraMatrix.at<double>(0, 0) = aspectRatio;

  distCoeffs = cv::Mat::zeros(8, 1, CV_64F);

  system::Timer durationrC;

  const double rms = cv::calibrateCamera(objectPoints, imagePoints, imageSize, cameraMatrix,
                                         distCoeffs, rvecs, tvecs, cvCalibFlags | cv::CALIB_FIX_K4 | cv::CALIB_FIX_K5 | cv::CALIB_FIX_K6);
  ALICEVISION_LOG_DEBUG("\tcalibrateCamera duration: " << system::prettyTime(durationrC.elapsedMs()));

  ALICEVISION_LOG_DEBUG("\tRMS error reported by calibrateCamera: " << rms);
  bool ok = cv::checkRange(cameraMatrix) && cv::checkRange(distCoeffs);

  durationrC.reset();

  totalAvgErr = computeReprojectionErrors(objectPoints, imagePoints,
                                          rvecs, tvecs, cameraMatrix, distCoeffs, reprojErrs);

  ALICEVISION_LOG_DEBUG("\tcomputeReprojectionErrors duration: " << durationrC.elapsedMs() << "ms");

  return ok;
}

bool calibrationIterativeOptimization(
                        const cv::Size& imageSize,
                        float aspectRatio,
                        int cvCalibFlags,
                        cv::Mat& cameraMatrix,
                        cv::Mat& distCoeffs,
                        std::vector<cv::Mat>& rvecs,
                        std::vector<cv::Mat>& tvecs,
                        std::vector<float>& reprojErrs,
                        double& totalAvgErr,
                        const double& maxTotalAvgErr,
                        const std::size_t& minInputFrames,
                        std::vector<std::size_t>& calibInputFrames,
                        std::vector<std::vector<cv::Point2f> >& calibImagePoints,
                        std::vector<std::vector<cv::Point3f> >& calibObjectPoints,
                        std::vector<float>& calibImageScore,
                        std::vector<std::size_t>& rejectInputFrames)
{
  std::size_t calibIteration = 0;
  bool calibSucceeded = false;
  do
  {
    // Estimate the camera calibration
    ALICEVISION_LOG_DEBUG("Calibration iteration " << calibIteration << " with " << calibImagePoints.size() << " frames.");
    calibSucceeded = runCalibration(calibImagePoints, calibObjectPoints, imageSize,
                                    aspectRatio, cvCalibFlags, cameraMatrix, distCoeffs,
                                    rvecs, tvecs, reprojErrs, totalAvgErr);

    if (totalAvgErr <= maxTotalAvgErr)
    {
      ALICEVISION_LOG_DEBUG("The calibration succeed with an average error that respects the maxTotalAvgErr.");
      break;
    }
    else if (calibInputFrames.size() < minInputFrames)
    {
      ALICEVISION_LOG_DEBUG("Not enough valid input image (" << calibInputFrames.size() << ") to continue the refinement.");
      break;
    }
    else if (calibSucceeded)
    {
      // Filter the successfully calibrated images to keep the best ones
      // in order to refine the calibration.
      // For instance, remove blurry images which introduce imprecision.

      std::vector<float> globalScores;
      for (std::size_t i = 0; i < calibInputFrames.size(); ++i)
      {
        globalScores.push_back(reprojErrs[i] * calibImageScore[i]);
      }

      const auto minMaxError = std::minmax_element(globalScores.begin(), globalScores.end());
      ALICEVISION_LOG_DEBUG("\terror min: " << *minMaxError.first << ", max: " << *minMaxError.second);
      if (*minMaxError.first == *minMaxError.second)
      {
        ALICEVISION_LOG_DEBUG("Same error on all images: " << *minMaxError.first);
        for (float f : globalScores)
          ALICEVISION_LOG_DEBUG("f: " << f);
        break;
      }
      // We only keep the frames with N% of the largest error.
      const float errorThreshold = *minMaxError.first + 0.8 * (*minMaxError.second - *minMaxError.first);
      std::vector<std::vector<cv::Point2f> > filteredImagePoints;
      std::vector<std::vector<cv::Point3f> > filteredObjectPoints;
      std::vector<std::size_t> filteredInputFrames;
      std::vector<std::size_t> tmpRejectInputFrames;
      std::vector<float> filteredImageScores;

      for (std::size_t i = 0; i < calibImagePoints.size(); ++i)
      {
        if (globalScores[i] < errorThreshold)
        {
          filteredImagePoints.push_back(calibImagePoints[i]);
          filteredObjectPoints.push_back(calibObjectPoints[i]);
          filteredInputFrames.push_back(calibInputFrames[i]);
          filteredImageScores.push_back(calibImageScore[i]);
        }
        else
        {
          // We collect rejected frames for debug purpose
          tmpRejectInputFrames.push_back(calibInputFrames[i]);
        }
      }
      if (filteredImagePoints.size() < minInputFrames)
      {
        ALICEVISION_LOG_DEBUG("Not enough filtered input images (filtered: " << filteredImagePoints.size() << ", rejected:" << tmpRejectInputFrames.size() << ") to continue the refinement.");
        break;
      }
      if (calibImagePoints.size() == filteredImagePoints.size())
      {
        // Convergence reached
        ALICEVISION_LOG_DEBUG("Convergence reached.");
        break;
      }
      calibImagePoints.swap(filteredImagePoints);
      calibObjectPoints.swap(filteredObjectPoints);
      calibInputFrames.swap(filteredInputFrames);
      calibImageScore.swap(filteredImageScores);
      rejectInputFrames.insert(rejectInputFrames.end(), tmpRejectInputFrames.begin(), tmpRejectInputFrames.end());
    }
    ++calibIteration;
  }
  while (calibSucceeded);

  ALICEVISION_LOG_DEBUG("Calibration done with " << calibIteration << " iterations.");
  ALICEVISION_LOG_DEBUG("Average reprojection error is " << totalAvgErr);
  ALICEVISION_LOG_DEBUG((calibSucceeded ? "Calibration succeeded" : "Calibration failed"));

  return calibSucceeded;
}

}//namespace calibration
}//namespace aliceVision
<commit_msg>[calibration] use float<commit_after>// This file is part of the AliceVision project.
// Copyright (c) 2016 AliceVision contributors.
// This Source Code Form is subject to the terms of the Mozilla Public License,
// v. 2.0. If a copy of the MPL was not distributed with this file,
// You can obtain one at https://mozilla.org/MPL/2.0/.

#include "aliceVision/calibration/calibration.hpp"

#include <opencv2/calib3d.hpp>

#include <aliceVision/system/Logger.hpp>
#include <aliceVision/system/Timer.hpp>

#include <ctime>
#include <algorithm>
#include <iostream>

namespace aliceVision{
namespace calibration{

double computeReprojectionErrors(const std::vector<std::vector<cv::Point3f> >& objectPoints,
                                 const std::vector<std::vector<cv::Point2f> >& imagePoints,
                                 const std::vector<cv::Mat>& rvecs, const std::vector<cv::Mat>& tvecs,
                                 const cv::Mat& cameraMatrix, const cv::Mat& distCoeffs,
                                 std::vector<float>& perViewErrors)
{
  std::vector<cv::Point2f> imagePoints2;
  int totalPoints = 0;
  double totalErr = 0;
  perViewErrors.resize(objectPoints.size());

  for (std::size_t i = 0; i < (int) objectPoints.size(); i++)
  {
    cv::projectPoints(cv::Mat(objectPoints[i]), rvecs[i], tvecs[i],
                      cameraMatrix, distCoeffs, imagePoints2);
    const double err = cv::norm(cv::Mat(imagePoints[i]), cv::Mat(imagePoints2), cv::NORM_L2);
    const std::size_t n = (int) objectPoints[i].size();
    perViewErrors[i] = (float) std::sqrt(err * err / n);
    totalErr += err*err;
    totalPoints += n;
  }
  return std::sqrt(totalErr / totalPoints);
}

bool runCalibration(const std::vector<std::vector<cv::Point2f> >& imagePoints,
                    const std::vector<std::vector<cv::Point3f> >& objectPoints,
                    const cv::Size& imageSize,
                    float aspectRatio,
                    int cvCalibFlags,
                    cv::Mat& cameraMatrix,
                    cv::Mat& distCoeffs,
                    std::vector<cv::Mat>& rvecs,
                    std::vector<cv::Mat>& tvecs,
                    std::vector<float>& reprojErrs,
                    double& totalAvgErr)
{
  rvecs.resize(0);
  tvecs.resize(0);
  reprojErrs.resize(0);
  cameraMatrix = cv::Mat::eye(3, 3, CV_64F);
  if (cvCalibFlags & cv::CALIB_FIX_ASPECT_RATIO)
    cameraMatrix.at<double>(0, 0) = aspectRatio;

  distCoeffs = cv::Mat::zeros(8, 1, CV_64F);

  system::Timer durationrC;

  const double rms = cv::calibrateCamera(objectPoints, imagePoints, imageSize, cameraMatrix,
                                         distCoeffs, rvecs, tvecs, cvCalibFlags | cv::CALIB_FIX_K4 | cv::CALIB_FIX_K5 | cv::CALIB_FIX_K6);
  ALICEVISION_LOG_DEBUG("\tcalibrateCamera duration: " << system::prettyTime(durationrC.elapsedMs()));

  ALICEVISION_LOG_DEBUG("\tRMS error reported by calibrateCamera: " << rms);
  bool ok = cv::checkRange(cameraMatrix) && cv::checkRange(distCoeffs);

  durationrC.reset();

  totalAvgErr = computeReprojectionErrors(objectPoints, imagePoints,
                                          rvecs, tvecs, cameraMatrix, distCoeffs, reprojErrs);

  ALICEVISION_LOG_DEBUG("\tcomputeReprojectionErrors duration: " << durationrC.elapsedMs() << "ms");

  return ok;
}

bool calibrationIterativeOptimization(
                        const cv::Size& imageSize,
                        float aspectRatio,
                        int cvCalibFlags,
                        cv::Mat& cameraMatrix,
                        cv::Mat& distCoeffs,
                        std::vector<cv::Mat>& rvecs,
                        std::vector<cv::Mat>& tvecs,
                        std::vector<float>& reprojErrs,
                        double& totalAvgErr,
                        const double& maxTotalAvgErr,
                        const std::size_t& minInputFrames,
                        std::vector<std::size_t>& calibInputFrames,
                        std::vector<std::vector<cv::Point2f> >& calibImagePoints,
                        std::vector<std::vector<cv::Point3f> >& calibObjectPoints,
                        std::vector<float>& calibImageScore,
                        std::vector<std::size_t>& rejectInputFrames)
{
  std::size_t calibIteration = 0;
  bool calibSucceeded = false;
  do
  {
    // Estimate the camera calibration
    ALICEVISION_LOG_DEBUG("Calibration iteration " << calibIteration << " with " << calibImagePoints.size() << " frames.");
    calibSucceeded = runCalibration(calibImagePoints, calibObjectPoints, imageSize,
                                    aspectRatio, cvCalibFlags, cameraMatrix, distCoeffs,
                                    rvecs, tvecs, reprojErrs, totalAvgErr);

    if (totalAvgErr <= maxTotalAvgErr)
    {
      ALICEVISION_LOG_DEBUG("The calibration succeed with an average error that respects the maxTotalAvgErr.");
      break;
    }
    else if (calibInputFrames.size() < minInputFrames)
    {
      ALICEVISION_LOG_DEBUG("Not enough valid input image (" << calibInputFrames.size() << ") to continue the refinement.");
      break;
    }
    else if (calibSucceeded)
    {
      // Filter the successfully calibrated images to keep the best ones
      // in order to refine the calibration.
      // For instance, remove blurry images which introduce imprecision.

      std::vector<float> globalScores;
      for (std::size_t i = 0; i < calibInputFrames.size(); ++i)
      {
        globalScores.push_back(reprojErrs[i] * calibImageScore[i]);
      }

      const auto minMaxError = std::minmax_element(globalScores.begin(), globalScores.end());
      ALICEVISION_LOG_DEBUG("\terror min: " << *minMaxError.first << ", max: " << *minMaxError.second);
      if (*minMaxError.first == *minMaxError.second)
      {
        ALICEVISION_LOG_DEBUG("Same error on all images: " << *minMaxError.first);
        for (float f : globalScores)
          ALICEVISION_LOG_DEBUG("f: " << f);
        break;
      }
      // We only keep the frames with N% of the largest error.
      const float errorThreshold = *minMaxError.first + 0.8f * (*minMaxError.second - *minMaxError.first);
      std::vector<std::vector<cv::Point2f> > filteredImagePoints;
      std::vector<std::vector<cv::Point3f> > filteredObjectPoints;
      std::vector<std::size_t> filteredInputFrames;
      std::vector<std::size_t> tmpRejectInputFrames;
      std::vector<float> filteredImageScores;

      for (std::size_t i = 0; i < calibImagePoints.size(); ++i)
      {
        if (globalScores[i] < errorThreshold)
        {
          filteredImagePoints.push_back(calibImagePoints[i]);
          filteredObjectPoints.push_back(calibObjectPoints[i]);
          filteredInputFrames.push_back(calibInputFrames[i]);
          filteredImageScores.push_back(calibImageScore[i]);
        }
        else
        {
          // We collect rejected frames for debug purpose
          tmpRejectInputFrames.push_back(calibInputFrames[i]);
        }
      }
      if (filteredImagePoints.size() < minInputFrames)
      {
        ALICEVISION_LOG_DEBUG("Not enough filtered input images (filtered: " << filteredImagePoints.size() << ", rejected:" << tmpRejectInputFrames.size() << ") to continue the refinement.");
        break;
      }
      if (calibImagePoints.size() == filteredImagePoints.size())
      {
        // Convergence reached
        ALICEVISION_LOG_DEBUG("Convergence reached.");
        break;
      }
      calibImagePoints.swap(filteredImagePoints);
      calibObjectPoints.swap(filteredObjectPoints);
      calibInputFrames.swap(filteredInputFrames);
      calibImageScore.swap(filteredImageScores);
      rejectInputFrames.insert(rejectInputFrames.end(), tmpRejectInputFrames.begin(), tmpRejectInputFrames.end());
    }
    ++calibIteration;
  }
  while (calibSucceeded);

  ALICEVISION_LOG_DEBUG("Calibration done with " << calibIteration << " iterations.");
  ALICEVISION_LOG_DEBUG("Average reprojection error is " << totalAvgErr);
  ALICEVISION_LOG_DEBUG((calibSucceeded ? "Calibration succeeded" : "Calibration failed"));

  return calibSucceeded;
}

}//namespace calibration
}//namespace aliceVision
<|endoftext|>


<commit_before>#pragma once

#include "cycling.cpp"
#include "pathfinding.cpp"

void cycling_all(Input& input, int cyclelength) {

	for(Balloon& balloon: input.balloons) {
		int t = balloon.r.size()-1;
		deque<int> tail_rs, tail_cs, tail_as, cycle_rs, cycle_cs, cycle_as;
		bool found = cyclefrom(input, balloon.r[t], balloon.c[t], balloon.h[t], cyclelength, tail_rs, tail_cs, tail_as, cycle_rs, cycle_cs, cycle_as);
		//use cycle
		if(found) {
			for(int i = 0; i < tail_rs.size(); i++) {
				balloon.r.push_back(tail_rs[i]);
				balloon.c.push_back(tail_cs[i]);
				balloon.h.push_back(tail_as[i]);
			}
			while(balloon.r.size() < input.t + 1) {
				for(int i = 0; i < cycle_rs.size(); i++) {
					balloon.r.push_back(cycle_rs[i]);
					balloon.c.push_back(cycle_cs[i]);
					balloon.h.push_back(cycle_as[i]);
				}
			}
		}
		//try to stay close to the cluster greedily
		else {
			pathfinding(input, balloon.id, input.clusters[balloon.cluster_id].center_r, input.clusters[balloon.cluster_id].center_c, -1);
		}
	}
}
<commit_msg>ignore lost balloons for function cyclefrom<commit_after>#pragma once

#include "cycling.cpp"
#include "pathfinding.cpp"

void cycling_all(Input& input, int cyclelength) {

	for(Balloon& balloon: input.balloons) {
		int t = balloon.r.size()-1;
		deque<int> tail_rs, tail_cs, tail_as, cycle_rs, cycle_cs, cycle_as;
		bool found = false;
		if(0 <= balloon.r[t] && balloon.r[t] < input.r) {
			//call cyclefrom only if the balloon is not lost yet
			found = cyclefrom(input, balloon.r[t], balloon.c[t], balloon.h[t], cyclelength, tail_rs, tail_cs, tail_as, cycle_rs, cycle_cs, cycle_as);
		}
		//use cycle
		if(found) {
			for(int i = 0; i < tail_rs.size(); i++) {
				balloon.r.push_back(tail_rs[i]);
				balloon.c.push_back(tail_cs[i]);
				balloon.h.push_back(tail_as[i]);
			}
			while(balloon.r.size() < input.t + 1) {
				for(int i = 0; i < cycle_rs.size(); i++) {
					balloon.r.push_back(cycle_rs[i]);
					balloon.c.push_back(cycle_cs[i]);
					balloon.h.push_back(cycle_as[i]);
				}
			}
		}
		//try to stay close to the cluster greedily
		else {
			pathfinding(input, balloon.id, input.clusters[balloon.cluster_id].center_r, input.clusters[balloon.cluster_id].center_c, -1);
		}
	}
}
<|endoftext|>


<commit_before>
#include <mdds/global.hpp>  // for MDDS_ASCII and MDDS_N_ELEMENTS
#include <mdds/trie_map.hpp>
#include <iostream>

using namespace std;

typedef mdds::packed_trie_map<mdds::trie::std_string_trait, int> trie_map_type;

int main()
{
    // Entries must be known prior to creating the instance, and they must be
    // sorted by the key in ascending order.
    trie_map_type::entry entries[] = {
        { MDDS_ASCII("Apex"),           42214 },
        { MDDS_ASCII("Asheville"),      87236 },
        { MDDS_ASCII("Burlington"),     51510 },
        { MDDS_ASCII("Cary"),          151088 },
        { MDDS_ASCII("Chapel Hill"),    59635 },
        { MDDS_ASCII("Charlotte"),     792862 },
        { MDDS_ASCII("Concord"),        83506 },
        { MDDS_ASCII("Durham"),        245475 },
        { MDDS_ASCII("Fayetteville"),  204408 },
        { MDDS_ASCII("Gastonia"),       73209 },
        { MDDS_ASCII("Goldsboro"),      36306 },
        { MDDS_ASCII("Greensboro"),    279639 },
        { MDDS_ASCII("Greenville"),     89130 },
        { MDDS_ASCII("Hickory"),        40361 },
        { MDDS_ASCII("High Point"),    107741 },
        { MDDS_ASCII("Huntersville"),   50458 },
        { MDDS_ASCII("Jacksonville"),   69079 },
        { MDDS_ASCII("Kannapolis"),     44359 },
        { MDDS_ASCII("Raleigh"),       431746 },
        { MDDS_ASCII("Rocky Mount"),    56954 },
        { MDDS_ASCII("Wilmington"),    112067 },
        { MDDS_ASCII("Wilson"),         49628 },
        { MDDS_ASCII("Winston-Salem"), 236441 },
    };

    // Cities in North Carolina and their populations in 2013.
    trie_map_type nc_cities(entries, MDDS_N_ELEMENTS(entries), -1); // Use -1 as the null value.

    cout << "Cities that start with 'Cha' and their populations:" << endl;
    auto matches = nc_cities.prefix_search(MDDS_ASCII("Cha"));
    for (const auto& kv : matches)
    {
        cout << "  " << kv.first << ": " << kv.second << endl;
    }

    cout << "Cities that start with 'W' and their populations:" << endl;
    matches = nc_cities.prefix_search(MDDS_ASCII("W"));
    for (const auto& kv : matches)
    {
        cout << "  " << kv.first << ": " << kv.second << endl;
    }

    cout << "Cities that start with 'C' and their populations:" << endl;
    matches = nc_cities.prefix_search(MDDS_ASCII("C"));
    for (const auto& kv : matches)
    {
        cout << "  " << kv.first << ": " << kv.second << endl;
    }

    // Individual search.
    int result = nc_cities.find(MDDS_ASCII("Wilmington"));
    cout << "Population of Wilmington: " << result << endl;

    // You get a "null value" when the container doesn't have specified key.
    result = nc_cities.find(MDDS_ASCII("Asheboro"));
    cout << "Population of Asheboro: " << result << endl;

    return EXIT_SUCCESS;
}
<commit_msg>Ditto for packed_trie_map.<commit_after>
#include <mdds/global.hpp>  // for MDDS_ASCII and MDDS_N_ELEMENTS
#include <mdds/trie_map.hpp>
#include <iostream>

using namespace std;

typedef mdds::packed_trie_map<mdds::trie::std_string_trait, int> trie_map_type;

int main()
{
    // Entries must be known prior to creating the instance, and they must be
    // sorted by the key in ascending order.
    trie_map_type::entry entries[] = {
        { MDDS_ASCII("Apex"),           42214 },
        { MDDS_ASCII("Asheville"),      87236 },
        { MDDS_ASCII("Burlington"),     51510 },
        { MDDS_ASCII("Cary"),          151088 },
        { MDDS_ASCII("Chapel Hill"),    59635 },
        { MDDS_ASCII("Charlotte"),     792862 },
        { MDDS_ASCII("Concord"),        83506 },
        { MDDS_ASCII("Durham"),        245475 },
        { MDDS_ASCII("Fayetteville"),  204408 },
        { MDDS_ASCII("Gastonia"),       73209 },
        { MDDS_ASCII("Goldsboro"),      36306 },
        { MDDS_ASCII("Greensboro"),    279639 },
        { MDDS_ASCII("Greenville"),     89130 },
        { MDDS_ASCII("Hickory"),        40361 },
        { MDDS_ASCII("High Point"),    107741 },
        { MDDS_ASCII("Huntersville"),   50458 },
        { MDDS_ASCII("Jacksonville"),   69079 },
        { MDDS_ASCII("Kannapolis"),     44359 },
        { MDDS_ASCII("Raleigh"),       431746 },
        { MDDS_ASCII("Rocky Mount"),    56954 },
        { MDDS_ASCII("Wilmington"),    112067 },
        { MDDS_ASCII("Wilson"),         49628 },
        { MDDS_ASCII("Winston-Salem"), 236441 },
    };

    // Cities in North Carolina and their populations in 2013.
    trie_map_type nc_cities(entries, MDDS_N_ELEMENTS(entries));

    cout << "Cities that start with 'Cha' and their populations:" << endl;
    auto results = nc_cities.prefix_search(MDDS_ASCII("Cha"));
    for_each(results.begin(), results.end(),
        [](const trie_map_type::key_value_type& kv)
        {
            cout << "  " << kv.first << ": " << kv.second << endl;
        }
    );

    cout << "Cities that start with 'W' and their populations:" << endl;
    results = nc_cities.prefix_search(MDDS_ASCII("W"));
    for_each(results.begin(), results.end(),
        [](const trie_map_type::key_value_type& kv)
        {
            cout << "  " << kv.first << ": " << kv.second << endl;
        }
    );

    cout << "Cities that start with 'C' and their populations:" << endl;
    results = nc_cities.prefix_search(MDDS_ASCII("C"));
    for_each(results.begin(), results.end(),
        [](const trie_map_type::key_value_type& kv)
        {
            cout << "  " << kv.first << ": " << kv.second << endl;
        }
    );

    // Individual search.
    auto it = nc_cities.find(MDDS_ASCII("Wilmington"));
    cout << "Population of Wilmington: " << it->second << endl;

    // You get an end position iterator when the container doesn't have the
    // specified key.
    it = nc_cities.find(MDDS_ASCII("Asheboro"));

    cout << "Population of Asheboro: ";

    if (it == nc_cities.end())
        cout << "not found";
    else
        cout << it->second;

    cout << endl;

    return EXIT_SUCCESS;
}
<|endoftext|>


<commit_before>#include <QFile>
#include <QTextStream>
#include <QSettings>
#include <QFileInfo>
#include <QDir>
#include <QFileDialog>
#include <QTableWidget>
#include <QTableWidgetItem>
#include <QHeaderView>
#include <QDebug>
#include <QMessageBox>
#include <QAbstractItemView>

#include "dialog_select_ros_topics.h"
#include "rule_editing.h"
#include "ui_dialog_select_ros_topics.h"

DialogSelectRosTopics::DialogSelectRosTopics(const std::vector<std::pair<QString, QString>>& topic_list,
                                             const Configuration &config,
                                             QWidget *parent) :
    QDialog(parent),
    ui(new Ui::dialogSelectRosTopics),
    _default_selected_topics(config.selected_topics),
    _select_all(QKeySequence(Qt::CTRL + Qt::Key_A), this),
    _deselect_all(QKeySequence(Qt::CTRL + Qt::SHIFT + Qt::Key_A), this)
{

    auto flags = this->windowFlags();
    this->setWindowFlags( flags | Qt::WindowStaysOnTopHint);

    ui->setupUi(this);

    ui->checkBoxEnableRules->setChecked( config.use_renaming_rules );
    ui->spinBoxArraySize->setValue( config.max_array_size );
    ui->checkBoxTimestamp->setChecked( config.use_header_stamp );

    if( config.discard_large_arrays )
    {
        ui->radioMaxDiscard->setChecked(true);
    }
    else{
        ui->radioMaxClamp->setChecked(true);
    }

    QStringList labels;
    labels.push_back("Topic name");
    labels.push_back("Datatype");

    ui->listRosTopics->setHorizontalHeaderLabels(labels);
    ui->listRosTopics->verticalHeader()->setVisible(false);

    updateTopicList(topic_list);

    if( ui->listRosTopics->rowCount() == 1)
    {
        ui->listRosTopics->selectRow(0);
    }
    ui->listRosTopics->setFocus();

    _select_all.setContext(Qt::WindowShortcut);
    _deselect_all.setContext(Qt::WindowShortcut);

    connect( &_select_all, &QShortcut::activated,
             ui->listRosTopics, &QAbstractItemView::selectAll );

    connect( &_deselect_all, &QShortcut::activated,
             ui->listRosTopics, &QAbstractItemView::clearSelection );

    on_spinBoxArraySize_valueChanged( ui->spinBoxArraySize->value() );

    QSettings settings;
    restoreGeometry(settings.value("DialogSelectRosTopics.geometry").toByteArray());

}

void DialogSelectRosTopics::updateTopicList(std::vector<std::pair<QString, QString> > topic_list )
{
    std::set<QString> newly_added;

    // add if not present
    for (const auto& it: topic_list)
    {
        const QString& topic_name = it.first ;
        const QString& type_name  = it.second ;

        bool found = false;
        for(int r=0; r < ui->listRosTopics->rowCount(); r++ )
        {
            const QTableWidgetItem *item = ui->listRosTopics->item(r,0);
            if( item->text() == topic_name){
                found = true;
                break;
            }
        }

        if( !found )
        {
            int new_row = ui->listRosTopics->rowCount();
            ui->listRosTopics->setRowCount( new_row+1 );

            // order IS important, don't change it
            ui->listRosTopics->setItem(new_row, 1, new QTableWidgetItem( type_name ));
            ui->listRosTopics->setItem(new_row, 0, new QTableWidgetItem( topic_name ));
            newly_added.insert(topic_name);
        }
    }

    ui->listRosTopics->horizontalHeader()->setSectionResizeMode(0, QHeaderView::Stretch);
    ui->listRosTopics->horizontalHeader()->setSectionResizeMode(1, QHeaderView::ResizeToContents);
    ui->listRosTopics->sortByColumn(0, Qt::AscendingOrder);
    //----------------------------------------------

    QModelIndexList selection = ui->listRosTopics->selectionModel()->selectedRows();

    for(int row=0; row < ui->listRosTopics->rowCount(); row++ )
    {
        const QTableWidgetItem *item = ui->listRosTopics->item(row,0);
        QString topic_name = item->text();

        if(newly_added.count(topic_name) &&  _default_selected_topics.contains( topic_name ) )
        {
            bool selected = false;
            for (const auto& selected_item: selection)
            {
                if( selected_item.row() == row)
                {
                    selected = true;
                    break;
                }
            }
            if( !selected ){
                ui->listRosTopics->selectRow(row);
            }
        }
    }

}

DialogSelectRosTopics::~DialogSelectRosTopics()
{
    QSettings settings;
    settings.setValue("DialogSelectRosTopics.geometry", saveGeometry());
    delete ui;
}

DialogSelectRosTopics::Configuration DialogSelectRosTopics::getResult() const
{
    Configuration config;
    config.selected_topics      = _topic_list;
    config.max_array_size       = ui->spinBoxArraySize->value();
    config.use_header_stamp     = ui->checkBoxTimestamp->isChecked();
    config.discard_large_arrays = ui->radioMaxDiscard->isChecked();
    config.use_renaming_rules   = ui->checkBoxEnableRules->isChecked();
    return config;
}

void DialogSelectRosTopics::on_buttonBox_accepted()
{
    QModelIndexList selected_indexes = ui->listRosTopics->selectionModel()->selectedIndexes();
    QString selected_topics;

    foreach(QModelIndex index, selected_indexes)
    {
        if(index.column() == 0){
            _topic_list.push_back( index.data(Qt::DisplayRole).toString() );
            selected_topics.append( _topic_list.back() ).append(" ");
        }
    }
}

void DialogSelectRosTopics::on_listRosTopics_itemSelectionChanged()
{
    QModelIndexList indexes = ui->listRosTopics->selectionModel()->selectedIndexes();

    ui->buttonBox->setEnabled( indexes.size() > 0) ;
}

void DialogSelectRosTopics::on_checkBoxEnableRules_toggled(bool checked)
{
    ui->pushButtonEditRules->setEnabled( checked );
}

void DialogSelectRosTopics::on_pushButtonEditRules_pressed()
{
    RuleEditing* rule_editing = new RuleEditing(this);
    rule_editing->exec();
}

nonstd::optional<double> FlatContainerContainHeaderStamp(const RosIntrospection::FlatMessage& flat_msg)
{
    for (const auto& it: flat_msg.value)
    {
        if( it.second.getTypeID() != RosIntrospection::TIME)
        {
            continue;
        }
        const RosIntrospection::StringTreeNode* leaf1 = it.first.node_ptr;
        const RosIntrospection::StringTreeNode* leaf2 = leaf1->parent();
        if( leaf2 && leaf2->value() == "header" && leaf1->value() == "stamp")
        {
            return it.second.convert<double>();
        }
    }
    return nonstd::optional<double>();
}

void DialogSelectRosTopics::on_maximumSizeHelp_pressed()
{
    QMessageBox msgBox;
    msgBox.setWindowTitle("Help");
    msgBox.setText("Maximum Size of Arrays:\n\n"
                   "If the size of an Arrays is larger than this maximum value, the entire array is skipped.\n\n"
                   "This parameter is used to prevent the user from loading HUGE arrays, "
                   "such as images, pointclouds, maps, etc.\n"
                   "The term 'array' refers to the array in a message field,\n\n"
                   " See http://wiki.ros.org/msg.\n\n"
                   "This is NOT about the duration of a time series!\n\n"
                   "MOTIVATION: pretend that a user tries to load a RGB image, which probably contains "
                   "a few millions pixels.\n"
                   "Plotjuggler would naively create a single time series for each pixel of the image! "
                   "That makes no sense, of course, and it would probably freeze your system.\n"
                   );
    msgBox.exec();
}

void DialogSelectRosTopics::on_lineEditFilter_textChanged(const QString& search_string)
{
    int visible_count = 0;
    bool updated = false;

    QStringList spaced_items = search_string.split(' ');

    for (int row=0; row < ui->listRosTopics->rowCount(); row++)
    {
        auto item = ui->listRosTopics->item(row,0);
        QString name = item->text();
        int pos = 0;
        bool toHide = false;

        for (const auto& item: spaced_items)
        {
            if( !name.contains(item) )
            {
                toHide = true;
                break;
            }
        }
        ui->listRosTopics->setRowHidden(row, toHide );
    }
}

void DialogSelectRosTopics::on_spinBoxArraySize_valueChanged(int value)
{

}

<commit_msg>fix issue #235<commit_after>#include <QFile>
#include <QTextStream>
#include <QSettings>
#include <QFileInfo>
#include <QDir>
#include <QFileDialog>
#include <QTableWidget>
#include <QTableWidgetItem>
#include <QHeaderView>
#include <QDebug>
#include <QMessageBox>
#include <QAbstractItemView>

#include "dialog_select_ros_topics.h"
#include "rule_editing.h"
#include "ui_dialog_select_ros_topics.h"

DialogSelectRosTopics::DialogSelectRosTopics(const std::vector<std::pair<QString, QString>>& topic_list,
                                             const Configuration &config,
                                             QWidget *parent) :
    QDialog(parent),
    ui(new Ui::dialogSelectRosTopics),
    _default_selected_topics(config.selected_topics),
    _select_all(QKeySequence(Qt::CTRL + Qt::Key_A), this),
    _deselect_all(QKeySequence(Qt::CTRL + Qt::SHIFT + Qt::Key_A), this)
{

    auto flags = this->windowFlags();
    this->setWindowFlags( flags | Qt::WindowStaysOnTopHint);

    ui->setupUi(this);

    ui->checkBoxEnableRules->setChecked( config.use_renaming_rules );
    ui->spinBoxArraySize->setValue( config.max_array_size );
    ui->checkBoxTimestamp->setChecked( config.use_header_stamp );

    if( config.discard_large_arrays )
    {
        ui->radioMaxDiscard->setChecked(true);
    }
    else{
        ui->radioMaxClamp->setChecked(true);
    }

    QStringList labels;
    labels.push_back("Topic name");
    labels.push_back("Datatype");

    ui->listRosTopics->setHorizontalHeaderLabels(labels);
    ui->listRosTopics->verticalHeader()->setVisible(false);

    updateTopicList(topic_list);

    if( ui->listRosTopics->rowCount() == 1)
    {
        ui->listRosTopics->selectRow(0);
    }
    ui->listRosTopics->setFocus();

    _select_all.setContext(Qt::WindowShortcut);
    _deselect_all.setContext(Qt::WindowShortcut);

    connect( &_select_all, &QShortcut::activated,
            ui->listRosTopics, [this]()
            {
              for (int row=0; row< ui->listRosTopics->rowCount(); row++)
              {
                if( !ui->listRosTopics->isRowHidden(row) &&
                    !ui->listRosTopics->item(row,0)->isSelected())
                {
                  ui->listRosTopics->selectRow(row);
                }
              }
            });

    connect( &_deselect_all, &QShortcut::activated,
             ui->listRosTopics, &QAbstractItemView::clearSelection );

    on_spinBoxArraySize_valueChanged( ui->spinBoxArraySize->value() );

    QSettings settings;
    restoreGeometry(settings.value("DialogSelectRosTopics.geometry").toByteArray());

}

void DialogSelectRosTopics::updateTopicList(std::vector<std::pair<QString, QString> > topic_list )
{
    std::set<QString> newly_added;

    // add if not present
    for (const auto& it: topic_list)
    {
        const QString& topic_name = it.first ;
        const QString& type_name  = it.second ;

        bool found = false;
        for(int r=0; r < ui->listRosTopics->rowCount(); r++ )
        {
            const QTableWidgetItem *item = ui->listRosTopics->item(r,0);
            if( item->text() == topic_name){
                found = true;
                break;
            }
        }

        if( !found )
        {
            int new_row = ui->listRosTopics->rowCount();
            ui->listRosTopics->setRowCount( new_row+1 );

            // order IS important, don't change it
            ui->listRosTopics->setItem(new_row, 1, new QTableWidgetItem( type_name ));
            ui->listRosTopics->setItem(new_row, 0, new QTableWidgetItem( topic_name ));
            newly_added.insert(topic_name);
        }
    }

    ui->listRosTopics->horizontalHeader()->setSectionResizeMode(0, QHeaderView::Stretch);
    ui->listRosTopics->horizontalHeader()->setSectionResizeMode(1, QHeaderView::ResizeToContents);
    ui->listRosTopics->sortByColumn(0, Qt::AscendingOrder);
    //----------------------------------------------

    QModelIndexList selection = ui->listRosTopics->selectionModel()->selectedRows();

    for(int row=0; row < ui->listRosTopics->rowCount(); row++ )
    {
        const QTableWidgetItem *item = ui->listRosTopics->item(row,0);
        QString topic_name = item->text();

        if(newly_added.count(topic_name) &&  _default_selected_topics.contains( topic_name ) )
        {
            bool selected = false;
            for (const auto& selected_item: selection)
            {
                if( selected_item.row() == row)
                {
                    selected = true;
                    break;
                }
            }
            if( !selected ){
                ui->listRosTopics->selectRow(row);
            }
        }
    }

}

DialogSelectRosTopics::~DialogSelectRosTopics()
{
    QSettings settings;
    settings.setValue("DialogSelectRosTopics.geometry", saveGeometry());
    delete ui;
}

DialogSelectRosTopics::Configuration DialogSelectRosTopics::getResult() const
{
    Configuration config;
    config.selected_topics      = _topic_list;
    config.max_array_size       = ui->spinBoxArraySize->value();
    config.use_header_stamp     = ui->checkBoxTimestamp->isChecked();
    config.discard_large_arrays = ui->radioMaxDiscard->isChecked();
    config.use_renaming_rules   = ui->checkBoxEnableRules->isChecked();
    return config;
}

void DialogSelectRosTopics::on_buttonBox_accepted()
{
    QModelIndexList selected_indexes = ui->listRosTopics->selectionModel()->selectedIndexes();
    QString selected_topics;

    foreach(QModelIndex index, selected_indexes)
    {
        if(index.column() == 0){
            _topic_list.push_back( index.data(Qt::DisplayRole).toString() );
            selected_topics.append( _topic_list.back() ).append(" ");
        }
    }
}

void DialogSelectRosTopics::on_listRosTopics_itemSelectionChanged()
{
    QModelIndexList indexes = ui->listRosTopics->selectionModel()->selectedIndexes();

    ui->buttonBox->setEnabled( indexes.size() > 0) ;
}

void DialogSelectRosTopics::on_checkBoxEnableRules_toggled(bool checked)
{
    ui->pushButtonEditRules->setEnabled( checked );
}

void DialogSelectRosTopics::on_pushButtonEditRules_pressed()
{
    RuleEditing* rule_editing = new RuleEditing(this);
    rule_editing->exec();
}

nonstd::optional<double> FlatContainerContainHeaderStamp(const RosIntrospection::FlatMessage& flat_msg)
{
    for (const auto& it: flat_msg.value)
    {
        if( it.second.getTypeID() != RosIntrospection::TIME)
        {
            continue;
        }
        const RosIntrospection::StringTreeNode* leaf1 = it.first.node_ptr;
        const RosIntrospection::StringTreeNode* leaf2 = leaf1->parent();
        if( leaf2 && leaf2->value() == "header" && leaf1->value() == "stamp")
        {
            return it.second.convert<double>();
        }
    }
    return nonstd::optional<double>();
}

void DialogSelectRosTopics::on_maximumSizeHelp_pressed()
{
    QMessageBox msgBox;
    msgBox.setWindowTitle("Help");
    msgBox.setText("Maximum Size of Arrays:\n\n"
                   "If the size of an Arrays is larger than this maximum value, the entire array is skipped.\n\n"
                   "This parameter is used to prevent the user from loading HUGE arrays, "
                   "such as images, pointclouds, maps, etc.\n"
                   "The term 'array' refers to the array in a message field,\n\n"
                   " See http://wiki.ros.org/msg.\n\n"
                   "This is NOT about the duration of a time series!\n\n"
                   "MOTIVATION: pretend that a user tries to load a RGB image, which probably contains "
                   "a few millions pixels.\n"
                   "Plotjuggler would naively create a single time series for each pixel of the image! "
                   "That makes no sense, of course, and it would probably freeze your system.\n"
                   );
    msgBox.exec();
}

void DialogSelectRosTopics::on_lineEditFilter_textChanged(const QString& search_string)
{
    int visible_count = 0;
    bool updated = false;

    QStringList spaced_items = search_string.split(' ');

    for (int row=0; row < ui->listRosTopics->rowCount(); row++)
    {
        auto item = ui->listRosTopics->item(row,0);
        QString name = item->text();
        int pos = 0;
        bool toHide = false;

        for (const auto& item: spaced_items)
        {
            if( !name.contains(item) )
            {
                toHide = true;
                break;
            }
        }
        ui->listRosTopics->setRowHidden(row, toHide );
    }
}

void DialogSelectRosTopics::on_spinBoxArraySize_valueChanged(int value)
{

}

<|endoftext|>


<commit_before>#include "cinder/app/App.h"
#include "cinder/app/RendererGl.h"
#include "cinder/gl/gl.h"
#include "cinder/Log.h"
#include "cinder/ImageIo.h"
#include "cinder/gl/Texture.h"

using namespace ci;
using namespace ci::app;
using namespace std;

class ImageFileBasicApp : public App {
  public:
	void setup() override;
	void keyDown( KeyEvent event ) override;
	void fileDrop( FileDropEvent event ) override;
	void draw() override;

	gl::TextureRef		mTexture;
};

void ImageFileBasicApp::setup()
{
	try {
		fs::path path = getOpenFilePath( "", ImageIo::getLoadExtensions() );
		if( ! path.empty() ) {
			mTexture = gl::Texture::create( loadImage( path ) );
		}
	}
	catch( Exception &exc ) {
		CI_LOG_EXCEPTION( "failed to load image.", exc );
	}
}

void ImageFileBasicApp::keyDown( KeyEvent event )
{
	if( event.getChar() == 'o' ) {
		fs::path path = getOpenFilePath( "", ImageIo::getLoadExtensions() );
		if( ! path.empty() )
			mTexture = gl::Texture::create( loadImage( path ) );
	}
	else if( event.getChar() == 's' ) {
		fs::path path = getSaveFilePath();
		if( ! path.empty() ) {
			Surface s8( mTexture->createSource() );
			writeImage( writeFile( path ), s8 );
		}
	}
}

void ImageFileBasicApp::fileDrop( FileDropEvent event )
{
	try {
		BufferRef fileData(new Buffer( loadFile( event.getFile( 0 ) ) ) );
		DataSourceRef ds = DataSourceBuffer::create( fileData );
//		Channel16u bonk( loadImage( ds, ImageSource::Options(), "exr" ) );
		mTexture = gl::Texture::create( loadImage( loadFile( event.getFile( 0 ) ) ) );
	}
	catch( Exception &exc ) {
		CI_LOG_EXCEPTION( "failed to load image: " << event.getFile( 0 ), exc );
	}
}

void ImageFileBasicApp::draw()
{
	gl::clear( Color( 0.5f, 0.5f, 0.5f ) );
	gl::enableAlphaBlending();

	if( mTexture ) {
		Rectf destRect = Rectf( mTexture->getBounds() ).getCenteredFit( getWindowBounds(), true ).scaledCentered( 0.85f );
		gl::draw( mTexture, destRect );
	}
}

CINDER_APP( ImageFileBasicApp, RendererGl )
<commit_msg>Minor fix to ImageFileBasic<commit_after>#include "cinder/app/App.h"
#include "cinder/app/RendererGl.h"
#include "cinder/gl/gl.h"
#include "cinder/Log.h"
#include "cinder/ImageIo.h"
#include "cinder/gl/Texture.h"

using namespace ci;
using namespace ci::app;
using namespace std;

class ImageFileBasicApp : public App {
  public:
	void setup() override;
	void keyDown( KeyEvent event ) override;
	void fileDrop( FileDropEvent event ) override;
	void draw() override;

	gl::TextureRef		mTexture;
};

void ImageFileBasicApp::setup()
{
	try {
		fs::path path = getOpenFilePath( "", ImageIo::getLoadExtensions() );
		if( ! path.empty() ) {
			mTexture = gl::Texture::create( loadImage( path ) );
		}
	}
	catch( Exception &exc ) {
		CI_LOG_EXCEPTION( "failed to load image.", exc );
	}
}

void ImageFileBasicApp::keyDown( KeyEvent event )
{
	if( event.getChar() == 'o' ) {
		fs::path path = getOpenFilePath( "", ImageIo::getLoadExtensions() );
		if( ! path.empty() )
			mTexture = gl::Texture::create( loadImage( path ) );
	}
	else if( event.getChar() == 's' ) {
		fs::path path = getSaveFilePath();
		if( ! path.empty() ) {
			Surface s8( mTexture->createSource() );
			writeImage( writeFile( path ), s8 );
		}
	}
}

void ImageFileBasicApp::fileDrop( FileDropEvent event )
{
	try {
		mTexture = gl::Texture::create( loadImage( loadFile( event.getFile( 0 ) ) ) );
	}
	catch( Exception &exc ) {
		CI_LOG_EXCEPTION( "failed to load image: " << event.getFile( 0 ), exc );
	}
}

void ImageFileBasicApp::draw()
{
	gl::clear( Color( 0.5f, 0.5f, 0.5f ) );
	gl::enableAlphaBlending();

	if( mTexture ) {
		Rectf destRect = Rectf( mTexture->getBounds() ).getCenteredFit( getWindowBounds(), true ).scaledCentered( 0.85f );
		gl::draw( mTexture, destRect );
	}
}

CINDER_APP( ImageFileBasicApp, RendererGl )
<|endoftext|>