<commit_before>// Copyright Daniel Wallin 2008. Use, modification and distribution is
// subject to the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)

#if !BOOST_PP_IS_ITERATING

# ifndef LUABIND_TAG_FUNCTION_081129_HPP
#  define LUABIND_TAG_FUNCTION_081129_HPP

#  if LUABIND_MAX_ARITY <= 8
#   include <boost/mpl/vector/vector10.hpp>
#  else
#   include <boost/mpl/vector/vector50.hpp>
#  endif
#  include <boost/preprocessor/cat.hpp>
#  include <boost/preprocessor/iterate.hpp>
#  include <boost/preprocessor/repetition/enum_params.hpp>
#  include <boost/preprocessor/repetition/enum_trailing_params.hpp>

#include <luabind/lua_state_fwd.hpp>

namespace luabind {

namespace detail
{

  template <class Signature, class F>
  struct tagged_function
  {
      tagged_function(F f)
        : f(f)
      {}

      F f;
  };

  template <class Signature, class F>
  Signature deduce_signature(tagged_function<Signature, F> const&, ...)
  {
      return Signature();
  }

  template <class Signature, class F, class Policies>
  int invoke(
      lua_State* L, function_object const& self, invoke_context& ctx
    , tagged_function<Signature, F> const& tagged
    , Signature, Policies const& policies)
  {
      return invoke(L, self, ctx, tagged.f, Signature(), policies);
  }

  template <class Function>
  struct signature_from_function;

#  define BOOST_PP_ITERATION_PARAMS_1 \
  (3, (0, LUABIND_MAX_ARITY, <luabind/tag_function.hpp>))
#  include BOOST_PP_ITERATE()

} // namespace detail

template <class Signature, class F>
detail::tagged_function<
    typename detail::signature_from_function<Signature>::type
  , F
>
tag_function(F f)
{
    return f;
}

} // namespace luabind

# endif // LUABIND_TAG_FUNCTION_081129_HPP

#else // BOOST_PP_IS_ITERATING

# define N BOOST_PP_ITERATION()
# define NPLUS1 BOOST_PP_INC(N)

template <class R BOOST_PP_ENUM_TRAILING_PARAMS(N, class A)>
struct signature_from_function<R(BOOST_PP_ENUM_PARAMS(N, A))>
{
    typedef BOOST_PP_CAT(mpl::vector, NPLUS1)<
        R BOOST_PP_ENUM_TRAILING_PARAMS(N, A)
    > type;
};

#endif // BOOST_PP_IS_ITERATING
<commit_msg>fix header build for tag_function<commit_after>// Copyright Daniel Wallin 2008. Use, modification and distribution is
// subject to the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)

#if !BOOST_PP_IS_ITERATING

# ifndef LUABIND_TAG_FUNCTION_081129_HPP
#  define LUABIND_TAG_FUNCTION_081129_HPP

#  if LUABIND_MAX_ARITY <= 8
#   include <boost/mpl/vector/vector10.hpp>
#  else
#   include <boost/mpl/vector/vector50.hpp>
#  endif
#  include <boost/preprocessor/cat.hpp>
#  include <boost/preprocessor/iterate.hpp>
#  include <boost/preprocessor/repetition/enum_params.hpp>
#  include <boost/preprocessor/repetition/enum_trailing_params.hpp>

#include <luabind/lua_state_fwd.hpp>

namespace luabind {

namespace detail
{

  struct invoke_context;
  struct function_object;

  template <class Signature, class F>
  struct tagged_function
  {
      tagged_function(F f)
        : f(f)
      {}

      F f;
  };

  template <class Signature, class F>
  Signature deduce_signature(tagged_function<Signature, F> const&, ...)
  {
      return Signature();
  }

  template <class Signature, class F, class Policies>
  int invoke(
      lua_State* L, function_object const& self, invoke_context& ctx
    , tagged_function<Signature, F> const& tagged
    , Signature, Policies const& policies)
  {
      return invoke(L, self, ctx, tagged.f, Signature(), policies);
  }

  template <class Function>
  struct signature_from_function;

#  define BOOST_PP_ITERATION_PARAMS_1 \
  (3, (0, LUABIND_MAX_ARITY, <luabind/tag_function.hpp>))
#  include BOOST_PP_ITERATE()

} // namespace detail

template <class Signature, class F>
detail::tagged_function<
    typename detail::signature_from_function<Signature>::type
  , F
>
tag_function(F f)
{
    return f;
}

} // namespace luabind

# endif // LUABIND_TAG_FUNCTION_081129_HPP

#else // BOOST_PP_IS_ITERATING

# define N BOOST_PP_ITERATION()
# define NPLUS1 BOOST_PP_INC(N)

template <class R BOOST_PP_ENUM_TRAILING_PARAMS(N, class A)>
struct signature_from_function<R(BOOST_PP_ENUM_PARAMS(N, A))>
{
    typedef BOOST_PP_CAT(boost::mpl::vector, NPLUS1)<
        R BOOST_PP_ENUM_TRAILING_PARAMS(N, A)
    > type;
};

#endif // BOOST_PP_IS_ITERATING
<|endoftext|>


<commit_before>#ifndef CDEPENDENCYGROUP_HPP
#define CDEPENDENCYGROUP_HPP

#include "CFactoryMgr.hpp"

namespace urde
{
class CDependencyGroup
{
    std::vector<SObjectTag> x0_objectTags;
public:
    CDependencyGroup(CInputStream& in);
    void ReadFromStream(CInputStream& in);
};

CFactoryFnReturn FDependencyGroupFactory(const SObjectTag& tag, CInputStream& in, const CVParamTransfer& param);
}

#endif // CDEPENDENCYGROUP_HPP
<commit_msg>Add GetObjectTagVector<commit_after>#ifndef CDEPENDENCYGROUP_HPP
#define CDEPENDENCYGROUP_HPP

#include "CFactoryMgr.hpp"

namespace urde
{
class CDependencyGroup
{
    std::vector<SObjectTag> x0_objectTags;
public:
    CDependencyGroup(CInputStream& in);
    void ReadFromStream(CInputStream& in);
    std::vector<SObjectTag> GetObjectTagVector() const { return x0_objectTags; }
};

CFactoryFnReturn FDependencyGroupFactory(const SObjectTag& tag, CInputStream& in, const CVParamTransfer& param);
}

#endif // CDEPENDENCYGROUP_HPP
<|endoftext|>


<commit_before>#ifndef __ASTRAMEMORYAPI_HH__
#define __ASTRAMEMORYAPI_HH__
#include <cassert>
#include <fstream>
#include <iostream>
#include <string>
#include <cstdint>
#include "AstraNetworkAPI.hh"
class AstraNetworkAPI;
class AstraMemoryAPI{
    public:
        virtual  uint64_t mem_read(uint64_t size)=0;
        virtual  uint64_t mem_write(uint64_t size)=0;
        virtual  uint64_t npu_mem_read(uint64_t size)=0;
        virtual  uint64_t npu_mem_write(uint64_t size)=0;
        virtual  uint64_t nic_mem_read(uint64_t size)=0;
        virtual  uint64_t nic_mem_write(uint64_t size)=0;
        virtual ~AstraMemoryAPI()= default;
};
class SimpleMemory: public AstraMemoryAPI{
    public:
        double last_request_serviced;
        double npu_access_bw_GB;
        double nic_access_bw_GB;
        double access_latency;
        AstraNetworkAPI *NI;
        SimpleMemory(AstraNetworkAPI *NI,double access_latency,double npu_access_bw_GB,double nic_access_bw_GB){
            this->last_request_serviced=0;
            this->NI=NI;
            this->access_latency=access_latency;
            this->npu_access_bw_GB=npu_access_bw_GB;
            this->nic_access_bw_GB=nic_access_bw_GB;
        }
        void set_network_api(AstraNetworkAPI *astraNetworkApi){
            this->NI=astraNetworkApi;
        }
        uint64_t npu_mem_read(uint64_t size){
            timespec_t time=NI->sim_get_time();
            double time_ns=time.time_val;
            double delay=access_latency+(size/npu_access_bw_GB);
            double max=last_request_serviced;
            if(max<time_ns){
                max=time_ns;
            }
            double offset=(max+delay)-time_ns;
            this->last_request_serviced=max+delay;
            return (uint64_t)(offset);

        }
        uint64_t npu_mem_write(uint64_t size){
            timespec_t time=NI->sim_get_time();
            double time_ns=time.time_val;
            double delay=access_latency+(size/npu_access_bw_GB);
            double max=last_request_serviced;
            if(max<time_ns){
                max=time_ns;
            }
            double offset=(max+delay)-time_ns;
            this->last_request_serviced=max+delay;
            return (uint64_t)(offset);
        }
        uint64_t nic_mem_read(uint64_t size){
            timespec_t time=NI->sim_get_time();
            double time_ns=time.time_val;
            double delay=access_latency+(size/nic_access_bw_GB);
            double max=last_request_serviced;
            if(max<time_ns){
                max=time_ns;
            }
            double offset=(max+delay)-time_ns;
            this->last_request_serviced=max+delay;
            return (uint64_t)(offset);
        }
        uint64_t nic_mem_write(uint64_t size){
            timespec_t time=NI->sim_get_time();
            double time_ns=time.time_val;
            double delay=access_latency+(size/nic_access_bw_GB);
            double max=last_request_serviced;
            if(max<time_ns){
                max=time_ns;
            }
            double offset=(max+delay)-time_ns;
            this->last_request_serviced=max+delay;
            return (uint64_t)(offset);
        }
        uint64_t mem_read(uint64_t size){
            return nic_mem_read(size);
        }
        uint64_t mem_write(uint64_t size){
            return nic_mem_write(size);
        }
};
#endif
<commit_msg>updated<commit_after>#ifndef __ASTRAMEMORYAPI_HH__
#define __ASTRAMEMORYAPI_HH__
#include <cassert>
#include <fstream>
#include <iostream>
#include <string>
#include <cstdint>
#include "AstraNetworkAPI.hh"
struct timespec_t;
class AstraNetworkAPI;
class AstraMemoryAPI{
    public:
        virtual  uint64_t mem_read(uint64_t size)=0;
        virtual  uint64_t mem_write(uint64_t size)=0;
        virtual  uint64_t npu_mem_read(uint64_t size)=0;
        virtual  uint64_t npu_mem_write(uint64_t size)=0;
        virtual  uint64_t nic_mem_read(uint64_t size)=0;
        virtual  uint64_t nic_mem_write(uint64_t size)=0;
        virtual ~AstraMemoryAPI()= default;
};
class SimpleMemory: public AstraMemoryAPI{
    public:
        double last_request_serviced;
        double npu_access_bw_GB;
        double nic_access_bw_GB;
        double access_latency;
        AstraNetworkAPI *NI;
        SimpleMemory(AstraNetworkAPI *NI,double access_latency,double npu_access_bw_GB,double nic_access_bw_GB){
            this->last_request_serviced=0;
            this->NI=NI;
            this->access_latency=access_latency;
            this->npu_access_bw_GB=npu_access_bw_GB;
            this->nic_access_bw_GB=nic_access_bw_GB;
        }
        void set_network_api(AstraNetworkAPI *astraNetworkApi){
            this->NI=astraNetworkApi;
        }
        uint64_t npu_mem_read(uint64_t size){
            timespec_t time=NI->sim_get_time();
            double time_ns=time.time_val;
            double delay=access_latency+(size/npu_access_bw_GB);
            double max=last_request_serviced;
            if(max<time_ns){
                max=time_ns;
            }
            double offset=(max+delay)-time_ns;
            this->last_request_serviced=max+delay;
            return (uint64_t)(offset);

        }
        uint64_t npu_mem_write(uint64_t size){
            timespec_t time=NI->sim_get_time();
            double time_ns=time.time_val;
            double delay=access_latency+(size/npu_access_bw_GB);
            double max=last_request_serviced;
            if(max<time_ns){
                max=time_ns;
            }
            double offset=(max+delay)-time_ns;
            this->last_request_serviced=max+delay;
            return (uint64_t)(offset);
        }
        uint64_t nic_mem_read(uint64_t size){
            timespec_t time=NI->sim_get_time();
            double time_ns=time.time_val;
            double delay=access_latency+(size/nic_access_bw_GB);
            double max=last_request_serviced;
            if(max<time_ns){
                max=time_ns;
            }
            double offset=(max+delay)-time_ns;
            this->last_request_serviced=max+delay;
            return (uint64_t)(offset);
        }
        uint64_t nic_mem_write(uint64_t size){
            timespec_t time=NI->sim_get_time();
            double time_ns=time.time_val;
            double delay=access_latency+(size/nic_access_bw_GB);
            double max=last_request_serviced;
            if(max<time_ns){
                max=time_ns;
            }
            double offset=(max+delay)-time_ns;
            this->last_request_serviced=max+delay;
            return (uint64_t)(offset);
        }
        uint64_t mem_read(uint64_t size){
            return nic_mem_read(size);
        }
        uint64_t mem_write(uint64_t size){
            return nic_mem_write(size);
        }
};
#endif
<|endoftext|>


<commit_before>
// Copyright 2010-2012 University of Washington. All Rights Reserved.
// LICENSE_PLACEHOLDER
// This software was created with Government support under DE
// AC05-76RL01830 awarded by the United States Department of
// Energy. The Government has certain rights in the software.

#include <boost/test/unit_test.hpp>

#include "Grappa.hpp"
#include "Message.hpp"

BOOST_AUTO_TEST_SUITE( Message_tests );

struct Check {
  bool x;
  Check() : x( false ) {}
  void operator()() { BOOST_CHECK_EQUAL( x, true ); }
};

void user_main( void * args )
{

  {
    bool x0 = false;
    {
      // must run on this node
      auto f0 = [&x0]{ BOOST_CHECK_EQUAL( x0, true ); };
      Grappa::Message< decltype(f0) > m0( 0, f0 );
      //auto m1 = Grappa::message( 0, [&]{ x1 = true; } );
      m0.send();
      x0 = true;
      Grappa_flush( 0 );
    }
  }

  {
    bool x1 = false;
    {
      // must run on this node
      auto f1 = [&x1]{ x1 = true; };
      Grappa::Message< decltype(f1) > m1( 0, f1 );
      //auto m1 = Grappa::message( 0, [&]{ x1 = true; } );
      m1.send();
      Grappa_flush( 0 );
      Grappa_yield();
    }
    BOOST_CHECK_EQUAL( x1, true );
  }

  {
    // must run on this node
    Grappa::Message< Check > m2( 0, Check() );
    //auto m2 = Grappa::message( 0, Check() );
    m2->x = true;
    m2.send();
    Grappa_flush( 0 );
    Grappa_yield();
  }

  {
    Check x3;
    //auto m3 = Grappa::message( 0, &x3 );
    // must run on this node
    Grappa::ExternalMessage< Check > m3( 0, &x3 );
    m3->x = true;
    m3.send();
    Grappa_flush( 0 );
    Grappa_yield();
  }

  {
    bool x4 = false;
    {
      //auto m4 = Grappa::send_message( 0, [&]{ x4 = true; } );
      // must run on this node
      auto f4 = [&]{ x4 = true; };
      Grappa::SendMessage< decltype(f4) > m4( 0, f4 );
    }
    Grappa_flush( 0 );
    Grappa_yield();
    BOOST_CHECK_EQUAL( x4, true );
  }

  {
    bool x5 = false;
    // must run on this node
    auto f5 = [&x5] (void * payload, size_t payload_size) {
      bool * b = reinterpret_cast< bool * >( payload );
      BOOST_CHECK_EQUAL( *b, x5 );
    };

    {
      Grappa::SendPayloadMessage< decltype(f5) > m5( 0, f5, &x5, sizeof(x5) );
    }
    Grappa_flush( 0 );
    Grappa_yield();

    {
      x5 = true;
      Grappa::SendPayloadMessage< decltype(f5) > m5a( 0, f5, &x5, sizeof(x5) );
    }
    Grappa_flush( 0 );
    Grappa_yield();
  }

  //Grappa_merge_and_dump_stats();
}

BOOST_AUTO_TEST_CASE( test1 ) {

  Grappa_init( &(boost::unit_test::framework::master_test_suite().argc),
	       &(boost::unit_test::framework::master_test_suite().argv),
	       (1L << 20) );

  //Grappa::impl::global_rdma_aggregator.init();
  Grappa_activate();

  Grappa_run_user_main( &user_main, (void*)NULL );

  Grappa_finish( 0 );
}

BOOST_AUTO_TEST_SUITE_END();

<commit_msg>Improvements to new message tests<commit_after>
// Copyright 2010-2012 University of Washington. All Rights Reserved.
// LICENSE_PLACEHOLDER
// This software was created with Government support under DE
// AC05-76RL01830 awarded by the United States Department of
// Energy. The Government has certain rights in the software.

#include <boost/test/unit_test.hpp>

#include "Grappa.hpp"
#include "Message.hpp"

BOOST_AUTO_TEST_SUITE( Message_tests );

struct Check {
  bool x;
  Check() : x( false ) {}
  void operator()() { BOOST_CHECK_EQUAL( x, true ); }
};

void user_main( void * args )
{

  LOG(INFO) << "Test -2";
  {
    bool x0 = false;
    {
      // must run on this node
      auto f0 = [&x0]{ BOOST_CHECK_EQUAL( x0, true ); };
      Grappa::Message< decltype(f0) > m0( 0, f0 );
      //auto m1 = Grappa::message( 0, [&]{ x1 = true; } );
      m0.send();
      x0 = true;
    }
    Grappa_flush( 0 );
    Grappa_poll( );

    LOG(INFO) << "Test -1";
    x0 = false;
    {
      // must run on this node
      auto m0 = Grappa::message( 0, [&x0]{ BOOST_CHECK_EQUAL( x0, true ); } );
      m0.send();
      x0 = true;
    }
    Grappa_flush( 0 );
    Grappa_poll( );

    LOG(INFO) << "Test 0";
    x0 = false;
    {
      // must run on this node
      auto m0 = Grappa::send_message( 0, [&x0]{ BOOST_CHECK_EQUAL( x0, true ); } );

      // //auto l0 = [&x0]{ BOOST_CHECK_EQUAL( x0, true ); };
      // // Grappa::SendMessage< decltype(l0) > m0( 0, l0 );

      // auto l0a = [&x0](void * useless, size_t nothing){ BOOST_CHECK_EQUAL( x0, true ); };
      // int foo[10];
      // auto m0 = Grappa::send_message( 0, l0a, foo, sizeof(foo) );

      x0 = true;
    }
    Grappa_flush( 0 );
    Grappa_poll( );
  }

  LOG(INFO) << "Test 1";
  {
    bool x1 = false;
    {
      // must run on this node
      auto f1 = [&x1]{ x1 = true; };
      Grappa::Message< decltype(f1) > m1( 0, f1 );
      //auto m1 = Grappa::message( 0, [&]{ x1 = true; } );
      m1.send();
    }
    Grappa_flush( 0 );
    Grappa_poll();
    BOOST_CHECK_EQUAL( x1, true );
  }

  LOG(INFO) << "Test 2";
  {
    // must run on this node
    Grappa::Message< Check > m2( 0, Check() );
    //auto m2 = Grappa::message( 0, Check() );
    m2->x = true;
    m2.send();
    Grappa_flush( 0 );
    Grappa_poll();
  }

  LOG(INFO) << "Test 3";
  {
    Check x3;
    //auto m3 = Grappa::message( 0, &x3 );
    // must run on this node
    Grappa::ExternalMessage< Check > m3( 0, &x3 );
    m3->x = true;
    m3.send();
    Grappa_flush( 0 );
    Grappa_poll();
  }

  LOG(INFO) << "Test 4";
  {
    bool x4 = false;
    {
      //auto m4 = Grappa::send_message( 0, [&]{ x4 = true; } );
      // must run on this node
      auto f4 = [&]{ x4 = true; };
      Grappa::SendMessage< decltype(f4) > m4( 0, f4 );
    }
    Grappa_flush( 0 );
    Grappa_poll();
    BOOST_CHECK_EQUAL( x4, true );
  }

  LOG(INFO) << "Test 5";
  {
    bool x5 = false;
    // must run on this node
    auto f5 = [&x5] (void * payload, size_t payload_size) {
      bool * b = reinterpret_cast< bool * >( payload );
      BOOST_CHECK_EQUAL( *b, x5 );
    };

    {
      //Grappa::SendPayloadMessage< decltype(f5) > m5( 0, f5, &x5, sizeof(x5) );
      auto m5 = Grappa::send_message( 0, f5, &x5, sizeof(x5) );
    }
    Grappa_flush( 0 );
    Grappa_poll();

    {
      x5 = true;
      Grappa::SendPayloadMessage< decltype(f5) > m5a( 0, f5, &x5, sizeof(x5) );
    }
    Grappa_flush( 0 );
    Grappa_poll();
  }

  //Grappa_merge_and_dump_stats();
}

BOOST_AUTO_TEST_CASE( test1 ) {

  Grappa_init( &(boost::unit_test::framework::master_test_suite().argc),
	       &(boost::unit_test::framework::master_test_suite().argv),
	       (1L << 20) );

  //Grappa::impl::global_rdma_aggregator.init();
  Grappa_activate();

  Grappa_run_user_main( &user_main, (void*)NULL );

  Grappa_finish( 0 );
}

BOOST_AUTO_TEST_SUITE_END();

<|endoftext|>


<commit_before>#include <iostream>
#include <vector>

class BigInteger
{
public:
    BigInteger()
      : digits(1, 0)
    {}

    BigInteger(unsigned int x) {
        do {
            digits.push_back(x % 10);
            x /= 10;
        } while (x > 0);
    }

    BigInteger& operator++() {
        digits[0]++;
        HandleCarry();
        return *this;
    }

    BigInteger operator+(const BigInteger& o) {
        BigInteger res;
        res.digits.resize(std::max(this->digits.size(), o.digits.size()));
        for (int i = 0; i < res.digits.size(); ++i) {
            res.digits[i] = this->GetDigit(i) + o.GetDigit(i);
        }
        res.HandleCarry();
        return res;
    }

    bool operator==(const BigInteger& o) {
        if (o.digits.size() != this->digits.size())
            return false;
        for (int i = 0; i < this->digits.size(); ++i) {
            if (o.digits[i] != this->digits[i])
                return false;
        }
        return true;
    }

    friend std::ostream& operator<<(std::ostream& out, const BigInteger& num);
private:
    void HandleCarry() {
        for (int i = 0; i < digits.size(); ++i) {
            int carry = digits[i] / 10;
            digits[i] %= 10;
            if (i == digits.size() - 1 && carry != 0) {
                digits.push_back(carry);
            } else {
                digits[i + 1] += carry;
            }
        }
    }

    int GetDigit(int idx) const {
        if (idx < 0)
            throw std::exception(); // TODO
        if (idx > digits.size() - 1)
            return 0;
        return digits[idx];
    }
    // Digits in base 10
    // TODO: It is not very memory/cpu efficient
    // Little-Endian-ish
    std::vector<int> digits;
};

std::ostream& operator<<(std::ostream& out, const BigInteger& num){
   for (int i = num.digits.size() - 1; i >= 0; --i) {
       out << num.digits[i];
    }
   return out;
}

int main()
{
    BigInteger x = 1000000000;
    BigInteger y = 1000000000;
    std::cout << x << " " << y << std::endl;
    BigInteger z = x + y;
    std::cout << z << std::endl;
    BigInteger a = z + x + y;
    std::cout << a << std::endl;
}
<commit_msg>Multiplication, comparison operators, postfix ++<commit_after>#include <iostream>
#include <vector>

class BigInteger
{
public:
    BigInteger()
      : digits(1, 0)
    {}

    BigInteger(unsigned int x) {
        do {
            digits.push_back(x % 10);
            x /= 10;
        } while (x > 0);
    }

    BigInteger& operator++() {
        digits[0]++;
        HandleCarry();
        return *this;
    }

    BigInteger operator++(int) {
        BigInteger copy(*this);
        ++copy;
        return copy;
    }

    BigInteger operator+(const BigInteger& o) {
        BigInteger res;
        res.digits.resize(std::max(this->digits.size(), o.digits.size()));
        for (int i = 0; i < res.digits.size(); ++i) {
            res.digits[i] = this->GetDigit(i) + o.GetDigit(i);
        }
        res.HandleCarry();
        return res;
    }

    BigInteger operator*(const BigInteger& o) {
        BigInteger res;
        res.digits.resize(this->digits.size() + o.digits.size(), 0);
        for (int i = 0; i < this->digits.size(); ++i) {
            for (int j = 0; j < o.digits.size(); ++j) {
                res.digits[i + j] += this->digits[i] * o.digits[j];
            }
        }
        res.HandleCarry();
        res.RemoveLeadingZeroes();
        return res;
    }

    bool operator==(const BigInteger& o) const{
        if (o.digits.size() != this->digits.size())
            return false;
        for (int i = 0; i < this->digits.size(); ++i) {
            if (o.digits[i] != this->digits[i])
                return false;
        }
        return true;
    }

    bool operator!=(const BigInteger& o) const {
        return !(*this == o);
    }

    bool operator<(const BigInteger& o) const {
        if (this->digits.size() < o.digits.size())
            return true;
        if (this->digits.size() > o.digits.size())
            return false;

        for (int i = this->digits.size() - 1; i >= 0; --i) {
            if (this->digits[i] < o.digits[i])
                return true;
            if (this->digits[i] > o.digits[i])
                return false;
        }
        return false;
    }

    bool operator<=(const BigInteger& o) const{
        return *this < o || *this == o;
    }

    bool operator>(const BigInteger& o) const{
        return o < *this;
    }

    bool operator>=(const BigInteger& o) const{
        return o <= *this;
    }

    friend std::ostream& operator<<(std::ostream& out, const BigInteger& num);
private:
    void HandleCarry() {
        for (int i = 0; i < digits.size(); ++i) {
            int carry = digits[i] / 10;
            digits[i] %= 10;
            if (i == digits.size() - 1 && carry != 0) {
                digits.push_back(carry);
            } else {
                digits[i + 1] += carry;
            }
        }
    }

    void RemoveLeadingZeroes() {
        while (this->digits.size() > 1 && this->digits[this->digits.size() - 1] == 0)
            this->digits.pop_back();
    }

    int GetDigit(int idx) const {
        if (idx < 0)
            throw std::exception(); // TODO
        if (idx > digits.size() - 1)
            return 0;
        return digits[idx];
    }
    // Digits in base 10
    // TODO: It is not very memory/cpu efficient
    // Little-Endian-ish
    std::vector<int> digits;
};

std::ostream& operator<<(std::ostream& out, const BigInteger& num){
   for (int i = num.digits.size() - 1; i >= 0; --i) {
       out << num.digits[i];
    }
   return out;
}

int main()
{
    BigInteger x = 1000000000;
    BigInteger y = 1000000000;
    std::cout << x << " " << y << std::endl;
    BigInteger z = x + y;
    std::cout << z << std::endl;
    BigInteger a = z + x + y;
    std::cout << a << std::endl;
    std::cout << (z == 42) << std::endl;
    std::cout << "NON-EQ test" << std::endl;
    std::cout << (z != 42) << std::endl;
    std::cout << "NON-EQ test ended" << std::endl;
    std::cout << (z < 42) << std::endl;
    std::cout << "TEST" << std::endl;
    std::cout << (z + z + 1 < z + z + 2) << std::endl;
}
<|endoftext|>


<commit_before>/*=========================================================================

 Program:   ORFEO Toolbox
 Language:  C++
 Date:      $Date$
 Version:   $Revision$

 Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.
 See OTBCopyright.txt for details.

 This software is distributed WITHOUT ANY WARRANTY; without even
 the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
 PURPOSE.  See the above copyright notices for more information.

 =========================================================================*/
#include "otbWrapperApplication.h"
#include "otbWrapperApplicationFactory.h"

#include <fstream>

#include "otbChangeLabelImageFilter.h"

namespace otb
{
namespace Wrapper
{

class LabeledImageColorMapping: public Application
{
public:
/** Standard class typedefs. */
 typedef LabeledImageColorMapping      Self;
 typedef Application                   Superclass;
 typedef itk::SmartPointer<Self>       Pointer;
 typedef itk::SmartPointer<const Self> ConstPointer;

 /** Standard macro */
 itkNewMacro(Self);

 itkTypeMacro(LabeledImageColorMapping, otb::Application);

 typedef FloatImageType::PixelType   PixelType;
 typedef UInt16ImageType             LabelImageType;
 typedef LabelImageType::PixelType   LabelType;
 typedef UInt8VectorImageType        VectorImageType;
 typedef VectorImageType::PixelType  VectorPixelType;

 typedef otb::ChangeLabelImageFilter<LabelImageType, VectorImageType> ChangeLabelFilterType;

private:
 LabeledImageColorMapping()
  {
    SetName("LabeledImageColorMapping");
    SetDescription("Replace labels of a classification map with user defined 8-bits RGB colors. Unknown label are mapped to black by default.");
  }

  virtual ~LabeledImageColorMapping()
  {
  }

  void DoCreateParameters()
  {
    AddParameter(ParameterType_InputImage, "in", "Input Image.");
    AddParameter(ParameterType_OutputImage, "out", "Output Image.");
    AddParameter(ParameterType_Filename, "ct", "Color table");
    SetParameterDescription("ct",  "An ASCII file containing the color table\n"
                                   "with one color per line\n"
                                   "(for instance the line '1 255 0 0' means that all pixels with label 1 will be replaced by RGB color 255 0 0)\n"
                                   "Lines beginning with a # are ignored")
  }

  void DoUpdateParameters()
  {
    // Nothing to do here : all parameters are independent
  }

  void DoExecute()
  {

    m_LabeledImage = GetParameterUInt16Image("in");

    m_Mapper = ChangeLabelFilterType::New();
    m_Mapper->SetInput(m_LabeledImage);
    m_Mapper->SetNumberOfComponentsPerPixel(3);

    std::ifstream ifs;

    ifs.open(GetParameterString("ct").c_str());

    if (!ifs)
      {
      itkExceptionMacro("Can not read file " << GetParameterString("ct") << std::endl);
      }

    otbAppLogINFO("Parsing color map file " << GetParameterString("ct") << "." << std::endl);

    while (!ifs.eof())
      {
      std::string line;
      std::getline(ifs, line);

      // Avoid commented lines or too short ones
      if (!line.empty() && line[0] != '#')
        {
        // retrieve the label
        std::string::size_type pos = line.find_first_of(" ", 0);
        LabelType clabel = atoi(line.substr(0, pos).c_str());
        ++pos;
        // Retrieve the color
        VectorPixelType color(3);
        color.Fill(0);
        for (unsigned int i = 0; i < 3; ++i)
          {
          std::string::size_type nextpos = line.find_first_of(" ", pos);
          int value = atoi(line.substr(pos, nextpos).c_str());
          if (value < 0 || value > 255)
          otbAppLogWARNING("WARNING: color value outside 8-bits range (<0 or >255). Value will be clamped." << std::endl);
          color[i] = static_cast<PixelType> (value);
          pos = nextpos + 1;
          nextpos = line.find_first_of(" ", pos);
          }
        otbAppLogINFO("Adding color mapping " << clabel << " -> [" << (int) color[0] << " " << (int) color[1] << " "<< (int) color[2] << " ]" << std::endl);
        m_Mapper->SetChange(clabel, color);
        }
      }
    ifs.close();

    /***/
    SetParameterOutputImage<VectorImageType> ("out", m_Mapper->GetOutput());

  }

  ChangeLabelFilterType::Pointer m_Mapper;
  LabelImageType::Pointer m_LabeledImage;

};
}
}

OTB_APPLICATION_EXPORT(otb::Wrapper::LabeledImageColorMapping)

<commit_msg>COMP: fix compilation error<commit_after>/*=========================================================================

 Program:   ORFEO Toolbox
 Language:  C++
 Date:      $Date$
 Version:   $Revision$

 Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.
 See OTBCopyright.txt for details.

 This software is distributed WITHOUT ANY WARRANTY; without even
 the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
 PURPOSE.  See the above copyright notices for more information.

 =========================================================================*/
#include "otbWrapperApplication.h"
#include "otbWrapperApplicationFactory.h"

#include <fstream>

#include "otbChangeLabelImageFilter.h"

namespace otb
{
namespace Wrapper
{

class LabeledImageColorMapping: public Application
{
public:
/** Standard class typedefs. */
 typedef LabeledImageColorMapping      Self;
 typedef Application                   Superclass;
 typedef itk::SmartPointer<Self>       Pointer;
 typedef itk::SmartPointer<const Self> ConstPointer;

 /** Standard macro */
 itkNewMacro(Self);

 itkTypeMacro(LabeledImageColorMapping, otb::Application);

 typedef FloatImageType::PixelType   PixelType;
 typedef UInt16ImageType             LabelImageType;
 typedef LabelImageType::PixelType   LabelType;
 typedef UInt8VectorImageType        VectorImageType;
 typedef VectorImageType::PixelType  VectorPixelType;

 typedef otb::ChangeLabelImageFilter<LabelImageType, VectorImageType> ChangeLabelFilterType;

private:
 LabeledImageColorMapping()
  {
    SetName("LabeledImageColorMapping");
    SetDescription("Replace labels of a classification map with user defined 8-bits RGB colors. Unknown label are mapped to black by default.");
  }

  virtual ~LabeledImageColorMapping()
  {
  }

  void DoCreateParameters()
  {
    AddParameter(ParameterType_InputImage, "in", "Input Image.");
    AddParameter(ParameterType_OutputImage, "out", "Output Image.");
    AddParameter(ParameterType_Filename, "ct", "Color table");
    SetParameterDescription("ct",  "An ASCII file containing the color table\n"
                                   "with one color per line\n"
                                   "(for instance the line '1 255 0 0' means that all pixels with label 1 will be replaced by RGB color 255 0 0)\n"
                                   "Lines beginning with a # are ignored");
  }

  void DoUpdateParameters()
  {
    // Nothing to do here : all parameters are independent
  }

  void DoExecute()
  {

    m_LabeledImage = GetParameterUInt16Image("in");

    m_Mapper = ChangeLabelFilterType::New();
    m_Mapper->SetInput(m_LabeledImage);
    m_Mapper->SetNumberOfComponentsPerPixel(3);

    std::ifstream ifs;

    ifs.open(GetParameterString("ct").c_str());

    if (!ifs)
      {
      itkExceptionMacro("Can not read file " << GetParameterString("ct") << std::endl);
      }

    otbAppLogINFO("Parsing color map file " << GetParameterString("ct") << "." << std::endl);

    while (!ifs.eof())
      {
      std::string line;
      std::getline(ifs, line);

      // Avoid commented lines or too short ones
      if (!line.empty() && line[0] != '#')
        {
        // retrieve the label
        std::string::size_type pos = line.find_first_of(" ", 0);
        LabelType clabel = atoi(line.substr(0, pos).c_str());
        ++pos;
        // Retrieve the color
        VectorPixelType color(3);
        color.Fill(0);
        for (unsigned int i = 0; i < 3; ++i)
          {
          std::string::size_type nextpos = line.find_first_of(" ", pos);
          int value = atoi(line.substr(pos, nextpos).c_str());
          if (value < 0 || value > 255)
          otbAppLogWARNING("WARNING: color value outside 8-bits range (<0 or >255). Value will be clamped." << std::endl);
          color[i] = static_cast<PixelType> (value);
          pos = nextpos + 1;
          nextpos = line.find_first_of(" ", pos);
          }
        otbAppLogINFO("Adding color mapping " << clabel << " -> [" << (int) color[0] << " " << (int) color[1] << " "<< (int) color[2] << " ]" << std::endl);
        m_Mapper->SetChange(clabel, color);
        }
      }
    ifs.close();

    /***/
    SetParameterOutputImage<VectorImageType> ("out", m_Mapper->GetOutput());

  }

  ChangeLabelFilterType::Pointer m_Mapper;
  LabelImageType::Pointer m_LabeledImage;

};
}
}

OTB_APPLICATION_EXPORT(otb::Wrapper::LabeledImageColorMapping)

<|endoftext|>


<commit_before>/*
* This file is part of ATLAS. It is subject to the license terms in
* the LICENSE file found in the top-level directory of this distribution.
* (Also avialable at http://www.apache.org/licenses/LICENSE-2.0.txt)
* You may not use this file except in compliance with the License.
*/
#include <iostream>
#include <assimp/postprocess.h>
#include <assimp/scene.h>
#include "AssimpImporter.hpp"

namespace AssimpWorker {

	AssimpImporter::AssimpImporter() :
		importer()
	{
		return;
	}

	AssimpImporter::~AssimpImporter(){
		return;
	}

	const aiScene* AssimpImporter::importSceneFromFile(std::string fileName, Log& log){
		importer.SetPropertyBool(AI_CONFIG_PP_FD_REMOVE, true); //remove degenerate polys
		importer.SetPropertyBool(AI_CONFIG_IMPORT_NO_SKELETON_MESHES, true); //do not import skeletons
		importer.SetPropertyInteger(AI_CONFIG_PP_SBP_REMOVE, aiPrimitiveType_LINE | aiPrimitiveType_POINT); //Drop all primitives that aren't triangles
		const aiScene* scene = importer.ReadFile(fileName, aiProcessPreset_TargetRealtime_Quality);
		if (!scene) {
			log.error("Scene not imported: "+fileName);
		}
		log.error(importer.GetErrorString());
		return scene;
	}

}
<commit_msg>Assimp should ignore the up-axis<commit_after>/*
* This file is part of ATLAS. It is subject to the license terms in
* the LICENSE file found in the top-level directory of this distribution.
* (Also avialable at http://www.apache.org/licenses/LICENSE-2.0.txt)
* You may not use this file except in compliance with the License.
*/
#include <iostream>
#include <assimp/postprocess.h>
#include <assimp/scene.h>
#include "AssimpImporter.hpp"

namespace AssimpWorker {

	AssimpImporter::AssimpImporter() :
		importer()
	{
		return;
	}

	AssimpImporter::~AssimpImporter(){
		return;
	}

	const aiScene* AssimpImporter::importSceneFromFile(std::string fileName, Log& log){
		importer.SetPropertyBool(AI_CONFIG_PP_FD_REMOVE, true); //remove degenerate polys
		importer.SetPropertyBool(AI_CONFIG_IMPORT_NO_SKELETON_MESHES, true); //do not import skeletons
		importer.SetPropertyInteger(AI_CONFIG_PP_SBP_REMOVE, aiPrimitiveType_LINE | aiPrimitiveType_POINT); //Drop all primitives that aren't triangles
		importer.SetPropertyBool(AI_CONFIG_IMPORT_COLLADA_IGNORE_UP_DIRECTION, true);
		const aiScene* scene = importer.ReadFile(fileName, aiProcessPreset_TargetRealtime_Quality);
		if (!scene) {
			log.error("Scene not imported: "+fileName);
		}
		log.error(importer.GetErrorString());
		return scene;
	}

}
<|endoftext|>


<commit_before>/*=====================================================================

 QGroundControl Open Source Ground Control Station

 (c) 2009 - 2014 QGROUNDCONTROL PROJECT <http://www.qgroundcontrol.org>

 This file is part of the QGROUNDCONTROL project

 QGROUNDCONTROL 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.

 QGROUNDCONTROL 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 QGROUNDCONTROL. If not, see <http://www.gnu.org/licenses/>.

 ======================================================================*/

/// @file
///     @author Don Gagne <don@thegagnes.com>

#include "RadioComponent.h"
#include "PX4RCCalibration.h"
#include "PX4AutoPilotPlugin.h"

/// @brief Parameters which signal a change in setupComplete state
static const char* triggerParams[] = { "RC_MAP_ROLL", "RC_MAP_PITCH", "RC_MAP_YAW", "RC_MAP_THROTTLE", NULL };

RadioComponent::RadioComponent(UASInterface* uas, AutoPilotPlugin* autopilot, QObject* parent) :
    PX4Component(uas, autopilot, parent),
    _name(tr("Radio"))
{
}

QString RadioComponent::name(void) const
{
    return _name;
}

QString RadioComponent::description(void) const
{
    return tr("The Radio Component is used to setup which channels on your RC Transmitter you will use for each vehicle control such as Roll, Pitch, Yaw and Throttle. "
              "It also allows you to assign switches and dials to the various flight modes. "
              "Prior to flight you must also calibrate the extents for all of your channels.");
}

QString RadioComponent::iconResource(void) const
{
    return "RadioComponentIcon.png";
}

bool RadioComponent::requiresSetup(void) const
{
    return true;
}

bool RadioComponent::setupComplete(void) const
{
    for (size_t i=0; triggerParams[i] != NULL; i++) {
        QVariant value;
        if (_paramMgr->getParameterValue(_paramMgr->getDefaultComponentId(), triggerParams[0], value)) {
            if (value.toInt() == 0) {
                return false;
            }
        } else {
            Q_ASSERT(false);
            return false;
        }
    }

    return true;
}

QString RadioComponent::setupStateDescription(void) const
{
    const char* stateDescription;

    if (requiresSetup()) {
        stateDescription = "Requires calibration";
    } else {
        stateDescription = "Calibrated";
    }
    return QString(stateDescription);
}

const char** RadioComponent::setupCompleteChangedTriggerList(void) const
{
    return triggerParams;
}

QStringList RadioComponent::paramFilterList(void) const
{
    QStringList list;

    list << "RC*";

    return list;
}

QWidget* RadioComponent::setupWidget(void) const
{
    return new PX4RCCalibration;
}

QUrl RadioComponent::summaryQmlSource(void) const
{
    return QUrl::fromUserInput("qrc:/qml/RadioComponentSummary.qml");
}

QString RadioComponent::prerequisiteSetup(void) const
{
    PX4AutoPilotPlugin* plugin = dynamic_cast<PX4AutoPilotPlugin*>(_autopilot);
    Q_ASSERT(plugin);

    if (!plugin->airframeComponent()->setupComplete()) {
        return plugin->airframeComponent()->name();
    }

    return QString();
}
<commit_msg>Update radio cal triggers<commit_after>/*=====================================================================

 QGroundControl Open Source Ground Control Station

 (c) 2009 - 2014 QGROUNDCONTROL PROJECT <http://www.qgroundcontrol.org>

 This file is part of the QGROUNDCONTROL project

 QGROUNDCONTROL 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.

 QGROUNDCONTROL 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 QGROUNDCONTROL. If not, see <http://www.gnu.org/licenses/>.

 ======================================================================*/

/// @file
///     @author Don Gagne <don@thegagnes.com>

#include "RadioComponent.h"
#include "PX4RCCalibration.h"
#include "PX4AutoPilotPlugin.h"

RadioComponent::RadioComponent(UASInterface* uas, AutoPilotPlugin* autopilot, QObject* parent) :
    PX4Component(uas, autopilot, parent),
    _name(tr("Radio"))
{
}

QString RadioComponent::name(void) const
{
    return _name;
}

QString RadioComponent::description(void) const
{
    return tr("The Radio Component is used to setup which channels on your RC Transmitter you will use for each vehicle control such as Roll, Pitch, Yaw and Throttle. "
              "It also allows you to assign switches and dials to the various flight modes. "
              "Prior to flight you must also calibrate the extents for all of your channels.");
}

QString RadioComponent::iconResource(void) const
{
    return "RadioComponentIcon.png";
}

bool RadioComponent::requiresSetup(void) const
{
    return true;
}

bool RadioComponent::setupComplete(void) const
{
    // Check for mapped attitude controls
    QStringList attitudeMappings;
    attitudeMappings << "RC_MAP_ROLL" << "RC_MAP_PITCH" << "RC_MAP_YAW" << "RC_MAP_THROTTLE";
    foreach(QString mapParam, attitudeMappings) {
        QVariant value;
        if (_paramMgr->getParameterValue(_paramMgr->getDefaultComponentId(), mapParam, value)) {
            if (value.toInt() == 0) {
                return false;
            }
        } else {
            Q_ASSERT(false);
            return false;
        }
    }

    // Check for min/max/trim defaults for channel 1-4

    static const int rcMinDefault = 1000;
    static const int rcMaxDefault = 2000;
    static const int rcTrimDefault = 1500;

    for (int i=1; i<5; i++) {
        QVariant value;
        int rcMin, rcMax, rcTrim;

        QString param;

        param = QString("RC%1_MIN").arg(i);
        if (_paramMgr->getParameterValue(_paramMgr->getDefaultComponentId(), param, value)) {
            rcMin = value.toInt();
        } else {
            Q_ASSERT(false);
            return false;
        }

        param = QString("RC%1_MAX").arg(i);
        if (_paramMgr->getParameterValue(_paramMgr->getDefaultComponentId(), param, value)) {
            rcMax = value.toInt();
        } else {
            Q_ASSERT(false);
            return false;
        }

        param = QString("RC%1_TRIM").arg(i);
        if (_paramMgr->getParameterValue(_paramMgr->getDefaultComponentId(), param, value)) {
            rcTrim = value.toInt();
        } else {
            Q_ASSERT(false);
            return false;
        }

        if (rcMin == rcMinDefault && rcMax == rcMaxDefault && rcTrim == rcTrimDefault) {
            return false;
        }
    }

    return true;
}

QString RadioComponent::setupStateDescription(void) const
{
    const char* stateDescription;

    if (requiresSetup()) {
        stateDescription = "Requires calibration";
    } else {
        stateDescription = "Calibrated";
    }
    return QString(stateDescription);
}

QStringList RadioComponent::setupCompleteChangedTriggerList(void) const
{
    QStringList triggers;

    // The best we can do to detect the need for a radio calibration is look for trim/min/max still being
    // at defaults. We also look for attitude controls to be mapped. But since they default to channels
    // they are not a very reliable source.

    // Attitude control mapping is always a trigger
    triggers << "RC_MAP_ROLL" << "RC_MAP_PITCH" << "RC_MAP_YAW" << "RC_MAP_THROTTLE";

    // We also trigger on min/max/trim for channels 1-4 which would normally be the attitude
    // control channels. This may not always be the case, but it's the best we can
    triggers << "RC1_MIN" << "RC1_MAX" << "RC1_TRIM";
    triggers << "RC2_MIN" << "RC2_MAX" << "RC2_TRIM";
    triggers << "RC3_MIN" << "RC3_MAX" << "RC3_TRIM";
    triggers << "RC4_MIN" << "RC4_MAX" << "RC4_TRIM";

    return triggers;
}

QStringList RadioComponent::paramFilterList(void) const
{
    QStringList list;

    list << "RC*";

    return list;
}

QWidget* RadioComponent::setupWidget(void) const
{
    return new PX4RCCalibration;
}

QUrl RadioComponent::summaryQmlSource(void) const
{
    return QUrl::fromUserInput("qrc:/qml/RadioComponentSummary.qml");
}

QString RadioComponent::prerequisiteSetup(void) const
{
    PX4AutoPilotPlugin* plugin = dynamic_cast<PX4AutoPilotPlugin*>(_autopilot);
    Q_ASSERT(plugin);

    if (!plugin->airframeComponent()->setupComplete()) {
        return plugin->airframeComponent()->name();
    }

    return QString();
}
<|endoftext|>


<commit_before>/*

  Copyright 2009 University of Helsinki

  Licensed under the Apache License, Version 2.0 (the "License");
  you may not use this file except in compliance with the License.
  You may obtain a copy of the License at

  http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.

*/

/*
  This is a toy commandline utility for testing spellers on standard io.
 */

#if HAVE_CONFIG_H
#  include <config.h>
#endif
#if HAVE_GETOPT_H
#  include <getopt.h>
#endif

#include <time.h>
#include <sys/time.h>
#include <sys/resource.h>
#include <errno.h>

#include "ol-exceptions.h"
#include "ospell.h"
#include "ZHfstOspeller.h"

using hfst_ol::ZHfstOspeller;
using hfst_ol::Transducer;

static bool quiet = false;
static bool verbose = false;
static FILE* profile_file;
clock_t profile_start, profile_end;

bool print_usage(void)
{
    std::cerr <<
    "\n" <<
    "Usage: " << PACKAGE_NAME << " [OPTIONS] ERRORSOURCE LEXICON\n" <<
    "       " << PACKAGE_NAME << " [OPTIONS] ZHFST-ARCHIVE\n" <<
    "Run a composition of ERRORSOURCE and LEXICON on standard input and\n" <<
    "print corrected output\n" <<
    "Second form seeks error sources and lexicons from the ZHFST-ARCHIVE\n"
    "\n" <<
    "  -h, --help                  Print this help message\n" <<
    "  -V, --version               Print version information\n" <<
    "  -v, --verbose               Be verbose\n" <<
    "  -q, --quiet                 Don't be verbose (default)\n" <<
    "  -s, --silent                Same as quiet\n" <<
    "\n" <<
    "\n" <<
    "Report bugs to " << PACKAGE_BUGREPORT << "\n" <<
    "\n";
    return true;
}

bool print_version(void)
{
    std::cerr <<
    "\n" <<
    PACKAGE_STRING << std::endl <<
    __DATE__ << " " __TIME__ << std::endl <<
    "copyright (C) 2009 - 2011 University of Helsinki\n";
    return true;
}

bool print_short_help(void)
{
    print_usage();
    return true;
}

int
legacy_spell(const char* errmodel_filename, const char* acceptor_filename)
{
    FILE* mutator_file = fopen(errmodel_filename, "r");
    if (mutator_file == NULL) {
        std::cerr << "Could not open file " << errmodel_filename
              << std::endl;
        return EXIT_FAILURE;
    }
    FILE* lexicon_file = fopen(acceptor_filename, "r");
    if (lexicon_file == NULL) {
        std::cerr << "Could not open file " << acceptor_filename
              << std::endl;
        return EXIT_FAILURE;
    }
    hfst_ol::Transducer * mutator;
    hfst_ol::Transducer * lexicon;
    mutator = new hfst_ol::Transducer(mutator_file);
    if (!mutator->is_weighted()) {
        std::cerr << "Error source was unweighted, exiting\n\n";
        return EXIT_FAILURE;
    }
    lexicon = new hfst_ol::Transducer(lexicon_file);
    if (!lexicon->is_weighted()) {
        std::cerr << "Lexicon was unweighted, exiting\n\n";
        return EXIT_FAILURE;
    }

    hfst_ol::Speller * speller;

    try {
        speller = new hfst_ol::Speller(mutator, lexicon);
    } catch (hfst_ol::AlphabetTranslationException& e) {
        std::cerr <<
        "Unable to build speller - symbol " << e.what() << " not "
        "present in lexicon's alphabet\n";
        return EXIT_FAILURE;
    }
    std::cout << "This is basic HFST spellchecker read in legacy "
        "mode; use zhfst version to test new format" << std::endl;
    char * str = (char*) malloc(2000);

    while (!std::cin.eof()) {
        std::cin.getline(str, 2000);
        if (str[0] == '\0') {
        break;
        }
        if (speller->check(str)) {
        std::cout << "\"" << str << "\" is in the lexicon\n\n";
        } else {
        hfst_ol::CorrectionQueue corrections = speller->correct(str);
        if (corrections.size() > 0) {
            std::cout << "Corrections for \"" << str << "\":\n";
            while (corrections.size() > 0)
            {
            std::cout << corrections.top().first << "    " << corrections.top().second << std::endl;
            corrections.pop();
            }
            std::cout << std::endl;
        } else {
            std::cout << "Unable to correct \"" << str << "\"!\n\n";
        }
        }
    }
    return EXIT_SUCCESS;

}

int
zhfst_spell(char* zhfst_filename)
{
  ZHfstOspeller speller;
  try
    {
      speller.read_zhfst(zhfst_filename);
    }
  catch (hfst_ol::ZHfstZipReadingError zhzre)
    {
      std::cerr << "cannot read zhfst archive " << zhfst_filename << ":"
          << std::endl
          << zhzre.what() << "." << std::endl
          << "trying to read as legacy automata directory" << std::endl;
      speller.read_legacy(zhfst_filename);
    }
  catch (hfst_ol::ZHfstLegacyReadingError zhlre)
    {
      std::cerr << "cannot read legacy hfst speller dir " << zhfst_filename
          << ":" << std::endl
          << zhlre.what() << "." << std::endl;
      return EXIT_FAILURE;
    }

  if (verbose)
    {
      std::cout << "Following metadata was read from ZHFST archive:" << std::endl
                << speller.metadata_dump() << std::endl;
    }
  char * str = (char*) malloc(2000);

    while (!std::cin.eof()) {
        std::cin.getline(str, 2000);
        if (str[0] == '\0') {
        break;
        }
        if (speller.spell(str)) {
        std::cout << "\"" << str << "\" is in the lexicon\n\n";
        } else {
        hfst_ol::CorrectionQueue corrections = speller.suggest(str);
        if (corrections.size() > 0) {
            std::cout << "Corrections for \"" << str << "\":\n";
            while (corrections.size() > 0)
            {
            std::cout << corrections.top().first << "    " << corrections.top().second << std::endl;
            corrections.pop();
            }
            std::cout << std::endl;
        } else {
            std::cout << "Unable to correct \"" << str << "\"!\n\n";
        }
        }
    }
    return EXIT_SUCCESS;
  return EXIT_SUCCESS;
}

void
hfst_print_profile_line()
  {
    if (profile_file == 0)
      {
        return;
      }
    fprintf(profile_file, "ospell");
    clock_t profile_end = clock();
    fprintf(profile_file, "\t%f", ((float)(profile_end - profile_start))
                                               / CLOCKS_PER_SEC);
    struct rusage* usage = static_cast<struct rusage*>
        (malloc(sizeof(struct rusage)));
    errno = 0;
    int rv = getrusage(RUSAGE_SELF, usage);
    if (rv != -1)
      {
        fprintf(profile_file, "\t%lu.%lu\t%lu.%lu"
                "\t%ld\t%ld\t%ld"
                "\t%ld"
                "\t%ld\t%ld\t%ld"
                "\t%ld\t%ld"
                "\t%ld\t%ld"
                "\t%ld"
                "\t%ld\t%ld",
                usage->ru_utime.tv_sec, usage->ru_utime.tv_usec,
                usage->ru_stime.tv_sec, usage->ru_stime.tv_usec,
                usage->ru_maxrss, usage->ru_ixrss, usage->ru_idrss,
                usage->ru_isrss,
                usage->ru_minflt, usage->ru_majflt, usage->ru_nswap,
                usage->ru_inblock, usage->ru_oublock,
                usage->ru_msgsnd, usage->ru_msgrcv,
                usage->ru_nsignals,
                usage->ru_nvcsw, usage->ru_nivcsw);
      }
    else
      {
        fprintf(profile_file, "\tgetrusage: %s", strerror(errno));
      }
    fprintf(profile_file, "\n");
  }

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

    int c;

#if HAVE_GETOPT_H
    while (true) {
        static struct option long_options[] =
            {
            // first the hfst-mandated options
            {"help",         no_argument,       0, 'h'},
            {"version",      no_argument,       0, 'V'},
            {"verbose",      no_argument,       0, 'v'},
            {"quiet",        no_argument,       0, 'q'},
            {"silent",       no_argument,       0, 's'},
            {"profile",      required_argument, 0, 'p'},
            {0,              0,                 0,  0 }
            };

        int option_index = 0;
        c = getopt_long(argc, argv, "hVvqsp:", long_options, &option_index);

        if (c == -1) // no more options to look at
            break;

        switch (c) {
        case 'h':
            print_usage();
            return EXIT_SUCCESS;
            break;

        case 'V':
            print_version();
            return EXIT_SUCCESS;
            break;

        case 'v':
            verbose = true;
            quiet = false;
            break;

        case 'p':
            profile_file = fopen(optarg, "a");
            if (NULL == profile_file)
              {
                perror("Couldn't open profiling file for appending");
              }
            profile_start = clock();
            break;
        case 'q': // fallthrough
        case 's':
            quiet = true;
            verbose = false;
            break;

        default:
            std::cerr << "Invalid option\n\n";
            print_short_help();
            return EXIT_FAILURE;
            break;
        }
    }
#else
    int optind = 1;
#endif
    // no more options, we should now be at the input filenames
    int rv = EXIT_SUCCESS;
    if (optind == (argc - 2))
      {
        rv = legacy_spell(argv[optind], argv[optind+1]);
      }
    else if (optind == (argc - 1))
      {
        rv = zhfst_spell(argv[optind]);
      }
    else if (optind < (argc - 2))
      {
        std::cerr << "No more than two free parameters allowed" << std::endl;
        print_short_help();
        return EXIT_FAILURE;
      }
    else if (optind >= argc)
      {
        std::cerr << "Give full path to zhfst spellers or two automata"
            << std::endl;
        print_short_help();
        return EXIT_FAILURE;
      }
    hfst_print_profile_line();
    return rv;
  }
<commit_msg>fallback_spell()<commit_after>/*

  Copyright 2009 University of Helsinki

  Licensed under the Apache License, Version 2.0 (the "License");
  you may not use this file except in compliance with the License.
  You may obtain a copy of the License at

  http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.

*/

/*
  This is a toy commandline utility for testing spellers on standard io.
 */

#if HAVE_CONFIG_H
#  include <config.h>
#endif
#if HAVE_GETOPT_H
#  include <getopt.h>
#endif

#include <time.h>
#include <sys/time.h>
#include <sys/resource.h>
#include <errno.h>

#include "ol-exceptions.h"
#include "ospell.h"
#include "ZHfstOspeller.h"

using hfst_ol::ZHfstOspeller;
using hfst_ol::Transducer;

static bool quiet = false;
static bool verbose = false;
static FILE* profile_file;
clock_t profile_start, profile_end;

bool print_usage(void)
{
    std::cerr <<
    "\n" <<
    "Usage: " << PACKAGE_NAME << " [OPTIONS] ERRORSOURCE LEXICON\n" <<
    "       " << PACKAGE_NAME << " [OPTIONS] ZHFST-ARCHIVE\n" <<
    "Run a composition of ERRORSOURCE and LEXICON on standard input and\n" <<
    "print corrected output\n" <<
    "Second form seeks error sources and lexicons from the ZHFST-ARCHIVE\n"
    "\n" <<
    "  -h, --help                  Print this help message\n" <<
    "  -V, --version               Print version information\n" <<
    "  -v, --verbose               Be verbose\n" <<
    "  -q, --quiet                 Don't be verbose (default)\n" <<
    "  -s, --silent                Same as quiet\n" <<
    "\n" <<
    "\n" <<
    "Report bugs to " << PACKAGE_BUGREPORT << "\n" <<
    "\n";
    return true;
}

bool print_version(void)
{
    std::cerr <<
    "\n" <<
    PACKAGE_STRING << std::endl <<
    __DATE__ << " " __TIME__ << std::endl <<
    "copyright (C) 2009 - 2011 University of Helsinki\n";
    return true;
}

bool print_short_help(void)
{
    print_usage();
    return true;
}

int
legacy_spell(const char* errmodel_filename, const char* acceptor_filename)
{
    FILE* mutator_file = fopen(errmodel_filename, "r");
    if (mutator_file == NULL) {
        std::cerr << "Could not open file " << errmodel_filename
              << std::endl;
        return EXIT_FAILURE;
    }
    FILE* lexicon_file = fopen(acceptor_filename, "r");
    if (lexicon_file == NULL) {
        std::cerr << "Could not open file " << acceptor_filename
              << std::endl;
        return EXIT_FAILURE;
    }
    hfst_ol::Transducer * mutator;
    hfst_ol::Transducer * lexicon;
    mutator = new hfst_ol::Transducer(mutator_file);
    if (!mutator->is_weighted()) {
        std::cerr << "Error source was unweighted, exiting\n\n";
        return EXIT_FAILURE;
    }
    lexicon = new hfst_ol::Transducer(lexicon_file);
    if (!lexicon->is_weighted()) {
        std::cerr << "Lexicon was unweighted, exiting\n\n";
        return EXIT_FAILURE;
    }

    hfst_ol::Speller * speller;

    try {
        speller = new hfst_ol::Speller(mutator, lexicon);
    } catch (hfst_ol::AlphabetTranslationException& e) {
        std::cerr <<
        "Unable to build speller - symbol " << e.what() << " not "
        "present in lexicon's alphabet\n";
        return EXIT_FAILURE;
    }
    std::cout << "This is basic HFST spellchecker read in legacy "
        "mode; use zhfst version to test new format" << std::endl;
    char * str = (char*) malloc(2000);

    while (!std::cin.eof()) {
        std::cin.getline(str, 2000);
        if (str[0] == '\0') {
        break;
        }
        if (speller->check(str)) {
        std::cout << "\"" << str << "\" is in the lexicon\n\n";
        } else {
        hfst_ol::CorrectionQueue corrections = speller->correct(str);
        if (corrections.size() > 0) {
            std::cout << "Corrections for \"" << str << "\":\n";
            while (corrections.size() > 0)
            {
            std::cout << corrections.top().first << "    " << corrections.top().second << std::endl;
            corrections.pop();
            }
            std::cout << std::endl;
        } else {
            std::cout << "Unable to correct \"" << str << "\"!\n\n";
        }
        }
    }
    return EXIT_SUCCESS;

}

int
fallback_spell(const char* errmodel_filename1, const char* errmodel_filename2,
	     const char* acceptor_filename)
{
    FILE* mutator_file1 = fopen(errmodel_filename1, "r");
    if (mutator_file1 == NULL) {
        std::cerr << "Could not open file " << errmodel_filename1
              << std::endl;
        return EXIT_FAILURE;
    }
    FILE* mutator_file2 = fopen(errmodel_filename2, "r");
    if (mutator_file2 == NULL) {
        std::cerr << "Could not open file " << errmodel_filename2
              << std::endl;
        return EXIT_FAILURE;
    }
    FILE* lexicon_file = fopen(acceptor_filename, "r");
    if (lexicon_file == NULL) {
        std::cerr << "Could not open file " << acceptor_filename
              << std::endl;
        return EXIT_FAILURE;
    }
    hfst_ol::Transducer * mutator1;
    hfst_ol::Transducer * mutator2;
    hfst_ol::Transducer * lexicon;
    mutator1= new hfst_ol::Transducer(mutator_file1);
    if (!mutator1->is_weighted()) {
        std::cerr << "Error source was unweighted, exiting\n\n";
        return EXIT_FAILURE;
    }
    mutator2= new hfst_ol::Transducer(mutator_file2);
    if (!mutator2->is_weighted()) {
        std::cerr << "Error source was unweighted, exiting\n\n";
        return EXIT_FAILURE;
    }
    lexicon = new hfst_ol::Transducer(lexicon_file);
    if (!lexicon->is_weighted()) {
        std::cerr << "Lexicon was unweighted, exiting\n\n";
        return EXIT_FAILURE;
    }

    hfst_ol::Speller * speller1;
    hfst_ol::Speller * speller2;

    try {
        speller1 = new hfst_ol::Speller(mutator1, lexicon);
    } catch (hfst_ol::AlphabetTranslationException& e) {
        std::cerr <<
        "Unable to build speller - symbol " << e.what() << " not "
        "present in lexicon's alphabet\n";
        return EXIT_FAILURE;
    }
    try {
        speller2 = new hfst_ol::Speller(mutator2, lexicon);
    } catch (hfst_ol::AlphabetTranslationException& e) {
        std::cerr <<
        "Unable to build speller - symbol " << e.what() << " not "
        "present in lexicon's alphabet\n";
        return EXIT_FAILURE;
    }
    std::cout << "This is basic HFST spellchecker read in legacy "
        "mode; use zhfst version to test new format" << std::endl;
    char * str = (char*) malloc(2000);

    while (!std::cin.eof()) {
        std::cin.getline(str, 2000);
        if (str[0] == '\0') {
        break;
        }
        if (speller1->check(str)) {
        std::cout << "\"" << str << "\" is in the lexicon 1\n\n";
        } else {
        hfst_ol::CorrectionQueue corrections1 = speller1->correct(str);
        if (corrections1.size() > 0) {
            std::cout << "Corrections for \"" << str << "\" w/ source 1:\n";
            while (corrections1.size() > 0)
            {
            std::cout << corrections1.top().first << "    " << corrections1.top().second << std::endl;
            corrections1.pop();
            }
            std::cout << std::endl;
        } else {
	    hfst_ol::CorrectionQueue corrections2 = speller2->correct(str);
	    if (corrections2.size() > 0) {
		std::cout << "Corrections for \"" << str << "\" w/ source 2:\n";
		while (corrections2.size() > 0)
		{
		    std::cout << corrections2.top().first << "    " << corrections2.top().second << std::endl;
		    corrections2.pop();
		}
		std::cout << std::endl;
	    } else {
		std::cout << "Unable to correct \"" << str << "\"!\n\n";
	    }
        }
	}
    }
    return EXIT_SUCCESS;

}

int
zhfst_spell(char* zhfst_filename)
{
  ZHfstOspeller speller;
  try
    {
      speller.read_zhfst(zhfst_filename);
    }
  catch (hfst_ol::ZHfstZipReadingError zhzre)
    {
      std::cerr << "cannot read zhfst archive " << zhfst_filename << ":"
          << std::endl
          << zhzre.what() << "." << std::endl
          << "trying to read as legacy automata directory" << std::endl;
      speller.read_legacy(zhfst_filename);
    }
  catch (hfst_ol::ZHfstLegacyReadingError zhlre)
    {
      std::cerr << "cannot read legacy hfst speller dir " << zhfst_filename
          << ":" << std::endl
          << zhlre.what() << "." << std::endl;
      return EXIT_FAILURE;
    }

  if (verbose)
    {
      std::cout << "Following metadata was read from ZHFST archive:" << std::endl
                << speller.metadata_dump() << std::endl;
    }
  char * str = (char*) malloc(2000);

    while (!std::cin.eof()) {
        std::cin.getline(str, 2000);
        if (str[0] == '\0') {
        break;
        }
        if (speller.spell(str)) {
        std::cout << "\"" << str << "\" is in the lexicon\n\n";
        } else {
        hfst_ol::CorrectionQueue corrections = speller.suggest(str);
        if (corrections.size() > 0) {
            std::cout << "Corrections for \"" << str << "\":\n";
            while (corrections.size() > 0)
            {
            std::cout << corrections.top().first << "    " << corrections.top().second << std::endl;
            corrections.pop();
            }
            std::cout << std::endl;
        } else {
            std::cout << "Unable to correct \"" << str << "\"!\n\n";
        }
        }
    }
    return EXIT_SUCCESS;
  return EXIT_SUCCESS;
}

void
hfst_print_profile_line()
  {
    if (profile_file == 0)
      {
        return;
      }
    fprintf(profile_file, "ospell");
    clock_t profile_end = clock();
    fprintf(profile_file, "\t%f", ((float)(profile_end - profile_start))
                                               / CLOCKS_PER_SEC);
    struct rusage* usage = static_cast<struct rusage*>
        (malloc(sizeof(struct rusage)));
    errno = 0;
    int rv = getrusage(RUSAGE_SELF, usage);
    if (rv != -1)
      {
        fprintf(profile_file, "\t%lu.%lu\t%lu.%lu"
                "\t%ld\t%ld\t%ld"
                "\t%ld"
                "\t%ld\t%ld\t%ld"
                "\t%ld\t%ld"
                "\t%ld\t%ld"
                "\t%ld"
                "\t%ld\t%ld",
                usage->ru_utime.tv_sec, usage->ru_utime.tv_usec,
                usage->ru_stime.tv_sec, usage->ru_stime.tv_usec,
                usage->ru_maxrss, usage->ru_ixrss, usage->ru_idrss,
                usage->ru_isrss,
                usage->ru_minflt, usage->ru_majflt, usage->ru_nswap,
                usage->ru_inblock, usage->ru_oublock,
                usage->ru_msgsnd, usage->ru_msgrcv,
                usage->ru_nsignals,
                usage->ru_nvcsw, usage->ru_nivcsw);
      }
    else
      {
        fprintf(profile_file, "\tgetrusage: %s", strerror(errno));
      }
    fprintf(profile_file, "\n");
  }

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

    int c;

#if HAVE_GETOPT_H
    while (true) {
        static struct option long_options[] =
            {
            // first the hfst-mandated options
            {"help",         no_argument,       0, 'h'},
            {"version",      no_argument,       0, 'V'},
            {"verbose",      no_argument,       0, 'v'},
            {"quiet",        no_argument,       0, 'q'},
            {"silent",       no_argument,       0, 's'},
            {"profile",      required_argument, 0, 'p'},
            {0,              0,                 0,  0 }
            };

        int option_index = 0;
        c = getopt_long(argc, argv, "hVvqsp:", long_options, &option_index);

        if (c == -1) // no more options to look at
            break;

        switch (c) {
        case 'h':
            print_usage();
            return EXIT_SUCCESS;
            break;

        case 'V':
            print_version();
            return EXIT_SUCCESS;
            break;

        case 'v':
            verbose = true;
            quiet = false;
            break;

        case 'p':
            profile_file = fopen(optarg, "a");
            if (NULL == profile_file)
              {
                perror("Couldn't open profiling file for appending");
              }
            profile_start = clock();
            break;
        case 'q': // fallthrough
        case 's':
            quiet = true;
            verbose = false;
            break;

        default:
            std::cerr << "Invalid option\n\n";
            print_short_help();
            return EXIT_FAILURE;
            break;
        }
    }
#else
    int optind = 1;
#endif
    // no more options, we should now be at the input filenames
    int rv = EXIT_SUCCESS;
    if (optind == (argc - 3))
      {
	  rv = fallback_spell(argv[optind], argv[optind+1], argv[optind+2]);
      }
    if (optind == (argc - 2))
      {
        rv = legacy_spell(argv[optind], argv[optind+1]);
      }
    else if (optind == (argc - 1))
      {
        rv = zhfst_spell(argv[optind]);
      }
    else if (optind < (argc - 2))
      {
        std::cerr << "No more than two free parameters allowed" << std::endl;
        print_short_help();
        return EXIT_FAILURE;
      }
    else if (optind >= argc)
      {
        std::cerr << "Give full path to zhfst spellers or two automata"
            << std::endl;
        print_short_help();
        return EXIT_FAILURE;
      }
    hfst_print_profile_line();
    return rv;
  }
<|endoftext|>


<commit_before>/*
    This file is part of Akregator.

    Copyright (C) 2004 Frank Osterfeld <frank.osterfeld at kdemail.net>

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

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

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

    As a special exception, permission is given to link this program
    with any edition of Qt, and distribute the resulting executable,
    without including the source code for Qt in the source distribution.
*/

#include "actionmanager.h"
#include "folder.h"
#include "folderitem.h"
#include "treenode.h"

#include <QMenu>
#include <kaction.h>
#include <kiconloader.h>

namespace Akregator {

FolderItem::FolderItem(FolderItem* parent, Folder* node) : TreeNodeItem(parent, node)
{
    initialize(node);
}

FolderItem::FolderItem(FolderItem* parent, TreeNodeItem* after, Folder* node) : TreeNodeItem(parent, after, node)
{
    initialize(node);
}

FolderItem::FolderItem(K3ListView* parent, Folder* node) : TreeNodeItem(parent, node)
{
    initialize(node);
}

FolderItem::FolderItem(K3ListView* parent, TreeNodeItem* after, Folder* node) : TreeNodeItem(parent, after, node)
{
    initialize(node);
}

void FolderItem::initialize(Folder* node)
{
    setOpen(node->isOpen());
    setPixmap ( 0, KGlobal::iconLoader()->loadIcon("folder", K3Icon::Small) );
    if (node)
        setText(0, node->title());
}

Folder* FolderItem::node()
{
    return static_cast<Folder*> (m_node);
}

void FolderItem::setOpen(bool open)
{
    node()->setOpen(open);
    K3ListViewItem::setOpen(open);
}

FolderItem::~FolderItem()
{}

void FolderItem::showContextMenu(const QPoint& p)
{
    QWidget* w = ActionManager::getInstance()->container("feedgroup_popup");
    if (w)
        static_cast<QMenu *>(w)->exec(p);
}

} // namespace Akregator
<commit_msg>fix crash (CID 1502)<commit_after>/*
    This file is part of Akregator.

    Copyright (C) 2004 Frank Osterfeld <frank.osterfeld at kdemail.net>

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

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

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

    As a special exception, permission is given to link this program
    with any edition of Qt, and distribute the resulting executable,
    without including the source code for Qt in the source distribution.
*/

#include "actionmanager.h"
#include "folder.h"
#include "folderitem.h"
#include "treenode.h"

#include <QMenu>
#include <kaction.h>
#include <kiconloader.h>

namespace Akregator {

FolderItem::FolderItem(FolderItem* parent, Folder* node) : TreeNodeItem(parent, node)
{
    initialize(node);
}

FolderItem::FolderItem(FolderItem* parent, TreeNodeItem* after, Folder* node) : TreeNodeItem(parent, after, node)
{
    initialize(node);
}

FolderItem::FolderItem(K3ListView* parent, Folder* node) : TreeNodeItem(parent, node)
{
    initialize(node);
}

FolderItem::FolderItem(K3ListView* parent, TreeNodeItem* after, Folder* node) : TreeNodeItem(parent, after, node)
{
    initialize(node);
}

void FolderItem::initialize(Folder* node)
{
    setOpen(node && node->isOpen());
    setPixmap ( 0, KGlobal::iconLoader()->loadIcon("folder", K3Icon::Small) );
    if (node)
        setText(0, node->title());
}

Folder* FolderItem::node()
{
    return static_cast<Folder*> (m_node);
}

void FolderItem::setOpen(bool open)
{
    node()->setOpen(open);
    K3ListViewItem::setOpen(open);
}

FolderItem::~FolderItem()
{}

void FolderItem::showContextMenu(const QPoint& p)
{
    QWidget* w = ActionManager::getInstance()->container("feedgroup_popup");
    if (w)
        static_cast<QMenu *>(w)->exec(p);
}

} // namespace Akregator
<|endoftext|>


<commit_before>//------------------------------------------------------------------------------
// rewriter.cpp
// Simple tool that parses an input file and writes it back out; used
// for verifying the round-trip nature of the parse tree.
//
// File is under the MIT license; see LICENSE for details
//------------------------------------------------------------------------------

#include <cstdio>
#if defined(_WIN32)
#    include <fcntl.h>
#    include <io.h>
#endif

#include "slang/syntax/SyntaxPrinter.h"
#include "slang/syntax/SyntaxTree.h"

using namespace slang;

int main(int argc, char** argv) try {
    if (argc != 2) {
        fprintf(stderr, "usage: rewriter file");
        return 1;
    }

    // Make sure we reproduce newlines correctly on Windows:
#if defined(_WIN32)
    _setmode(_fileno(stdout), _O_BINARY);
#endif

    auto tree = SyntaxTree::fromFile(argv[1]);
    printf("%s", SyntaxPrinter::printFile(*tree).c_str());
    return 0;
}
catch (const std::exception& e) {
    printf("internal compiler error (exception): %s\n", e.what());
    return 2;
}<commit_msg>Add sanity checks to rewriter<commit_after>//------------------------------------------------------------------------------
// rewriter.cpp
// Simple tool that parses an input file and writes it back out; used
// for verifying the round-trip nature of the parse tree.
//
// File is under the MIT license; see LICENSE for details
//------------------------------------------------------------------------------

#include <cstdio>
#if defined(_WIN32)
#    include <fcntl.h>
#    include <io.h>
#endif

#include <filesystem>

#include "slang/syntax/SyntaxPrinter.h"
#include "slang/syntax/SyntaxTree.h"

using namespace slang;

int main(int argc, char** argv) try {
    if (argc != 2) {
        fprintf(stderr, "usage: rewriter file");
        return 1;
    }

    // Make sure we reproduce newlines correctly on Windows:
#if defined(_WIN32)
    _setmode(_fileno(stdout), _O_BINARY);
#endif

    if (!std::filesystem::exists(argv[1])) {
        fprintf(stderr, "File does not exist: %s\n", argv[1]);
        return 1;
    }

    if (!std::filesystem::is_regular_file(argv[1])) {
        fprintf(stderr, "%s is not a file\n", argv[1]);
        return 1;
    }

    auto tree = SyntaxTree::fromFile(argv[1]);
    printf("%s", SyntaxPrinter::printFile(*tree).c_str());
    return 0;
}
catch (const std::exception& e) {
    printf("internal compiler error (exception): %s\n", e.what());
    return 2;
}<|endoftext|>


<commit_before>#ifndef AMGCL_VALUE_TYPE_COMPLEX_HPP
#define AMGCL_VALUE_TYPE_COMPLEX_HPP

/*
The MIT License

Copyright (c) 2012-2015 Christoph Sohrmann

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

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

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

/**
 * \file   amgcl/value_type/complex.hpp
 * \author Christoph Sohrmann
 * \brief  Enable std::complex<T> as value type.
 */

#include <amgcl/backend/builtin.hpp>
#include <amgcl/value_type/interface.hpp>

namespace amgcl {
namespace backend {

/// Enable std::complex as a value-type.
template <typename T>
struct is_builtin_vector< std::vector<std::complex<T> > > : boost::true_type {};

} // namespace backend

namespace math {

/// Specialization that extracts the scalar type of a complex type.
template <class T>
struct scalar_of< std::complex<T> > {
    typedef T type;
};

/// Specialization of conjugate transpose for scalar complex arguments.
template <typename T>
struct adjoint_impl< std::complex<T> >
{
    typedef std::complex<T> return_type;

    static std::complex<T> get(std::complex<T> x) {
        return std::conj(x);
    }
};

/// Specialization of constant element for complex type.
template <typename T>
struct constant_impl< std::complex<T> >
{
    static std::complex<T> get(T c) {
        return std::complex<T>(c, c);
    }
};

}  // namespace math
} // namespace amgcl

namespace std {

template <typename V>
bool operator<(const std::complex<V> &a, const std::complex<V> &b) {
    return std::abs(a) < std::abs(b);
}

} // namespace std

#endif /* ENABLE_COMPLEX_HPP */
<commit_msg>Fix definition of complex inner product<commit_after>#ifndef AMGCL_VALUE_TYPE_COMPLEX_HPP
#define AMGCL_VALUE_TYPE_COMPLEX_HPP

/*
The MIT License

Copyright (c) 2012-2015 Christoph Sohrmann

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

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

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

/**
 * \file   amgcl/value_type/complex.hpp
 * \author Christoph Sohrmann
 * \brief  Enable std::complex<T> as value type.
 */

#include <amgcl/backend/builtin.hpp>
#include <amgcl/value_type/interface.hpp>

namespace amgcl {
namespace backend {

/// Enable std::complex as a value-type.
template <typename T>
struct is_builtin_vector< std::vector<std::complex<T> > > : boost::true_type {};

} // namespace backend

namespace math {

/// Specialization that extracts the scalar type of a complex type.
template <class T>
struct scalar_of< std::complex<T> > {
    typedef T type;
};

/// Specialization of conjugate transpose for scalar complex arguments.
template <typename T>
struct adjoint_impl< std::complex<T> >
{
    typedef std::complex<T> return_type;

    static std::complex<T> get(std::complex<T> x) {
        return std::conj(x);
    }
};

/// Default implementation for inner product
/** \note Used in adjoint() */
template <typename T>
struct inner_product_impl< std::complex<T> > {
    typedef std::complex<T> return_type;

    static return_type get(std::complex<T> x, std::complex<T> y) {
        return x * std::conj(y);
    }
};

/// Specialization of constant element for complex type.
template <typename T>
struct constant_impl< std::complex<T> >
{
    static std::complex<T> get(T c) {
        return std::complex<T>(c, c);
    }
};

}  // namespace math
} // namespace amgcl

namespace std {

template <typename V>
bool operator<(const std::complex<V> &a, const std::complex<V> &b) {
    return std::abs(a) < std::abs(b);
}

} // namespace std

#endif /* ENABLE_COMPLEX_HPP */
<|endoftext|>