text:
/*
 * kaldi-io.cpp
 *
 *  Created on: Jul 29, 2014
 *      Author: chorows
 */

extern "C" {
#include "Python.h"
#include "numpy/arrayobject.h"
}

#include <boost/shared_ptr.hpp>
#include <boost/static_assert.hpp>

#include <boost/python.hpp>
#include <boost/python/operators.hpp>
#include <boost/python/stl_iterator.hpp>

#include <util/kaldi-io.h>
#include <util/kaldi-table.h>
#include <matrix/kaldi-matrix.h>
#include <matrix/kaldi-vector.h>
#include <util/table-types.h>

#include "python_wrappers.h"
#include "bp_converters.h"

using namespace std;

namespace bp = boost::python;

//keep a copy of the cPickle module in cache
struct PickleWrapper {
  PickleWrapper() {
    bp::object pickle = bp::import("cPickle");
    loads = pickle.attr("loads");
    dumps = pickle.attr("dumps");
  }

  bp::object loads, dumps;
};

//
// Holder for Python objects.
//
// In binary model uses Pickle to dump, the object is written as dump_length, pickled_string
// In text mode uses repr/eval (only single line), which works OK for simple types - lists, tuples, ints, but may fail for large arrays (as repr skips elemets for ndarray).
//
class PyObjectHolder {
 public:
  typedef bp::object T;

  PyObjectHolder() {
  }

  static bool Write(std::ostream &os, bool binary, const T &t) {
    kaldi::InitKaldiOutputStream(os, binary);  // Puts binary header if binary mode.
    try {
      if (binary) {  //pickle the object
        bp::object py_string = PW()->dumps(t,-1);
        int len = bp::extract<int>(py_string.attr("__len__")());
        const char* string = bp::extract<const char*>(py_string);
        kaldi::WriteBasicType(os, true, len);
        os.write(string, len);
      } else {  //use repr
        PyObject* repr = PyObject_Repr(t.ptr());
        os << PyString_AsString(repr) << '\n';
        Py_DECREF(repr);
      }
      return os.good();

    } catch (const std::exception &e) {
      KALDI_WARN<< "Exception caught writing Table object: " << e.what();
      if (!kaldi::IsKaldiError(e.what())) {std::cerr << e.what();}
      return false;  // Write failure.
    }
  }

  bool Read(std::istream &is) {
    bool is_binary;
    if (!kaldi::InitKaldiInputStream(is, &is_binary)) {
      KALDI_WARN << "Reading Table object [integer type], failed reading binary header\n";
      return false;
    }
    try {
      if (is_binary) {
        int len;
        kaldi::ReadBasicType(is, true, &len);
        std::auto_ptr<char> buf(new char[len]);
        is.read(buf.get(), len);
        bp::str py_string(buf.get(), len);
        t_ = PW()->loads(py_string);
      } else {
        std::string line;
        std::getline(is, line);
        bp::str repr(line);
        t_ = bp::eval(repr);
      }
      return true;
    } catch (std::exception &e) {
      KALDI_WARN << "Exception caught reading Table object";
      if (!kaldi::IsKaldiError(e.what())) {std::cerr << e.what();}
      return false;
    }
  }

  static bool IsReadInBinary() {return true;}

  const T &Value() const {return t_;}  // if t is a pointer, would return *t_;

  void Clear() {}

  ~PyObjectHolder() {}

private:
  KALDI_DISALLOW_COPY_AND_ASSIGN(PyObjectHolder);
  T t_;  // t_ may alternatively be of type T*.
  static PickleWrapper *PW_;
  static PickleWrapper * PW() {
    if (!PW_) {
      PW_ = new PickleWrapper();
    }
    return PW_;
  }
};

PickleWrapper * PyObjectHolder::PW_ = 0;

template<class Real>
struct MatrixToNdArrayConverter {
  typedef kaldi::KaldiObjectHolder<kaldi::Matrix<Real> > HR;
  typedef kaldi::KaldiObjectHolder<kaldi::NpWrapperMatrix<Real> > HW;

  static inline bp::object kaldi_to_python(const kaldi::Matrix<Real>& mat) {
    npy_intp dims[2];
    dims[0] = mat.NumRows();
    dims[1] = mat.NumCols();
    int nd = 2;
    int arr_type = kaldi::get_np_type<Real>();
    PyObject* ao = PyArray_SimpleNew(nd, dims, arr_type);
    bp::object arr=bp::object(bp::handle<>(
        ao
        ));
    kaldi::NpWrapperMatrix<Real> arr_wrap((PyArrayObject*)arr.ptr());
    arr_wrap.CopyFromMat(mat);
    return arr;
  }

  static inline kaldi::NpWrapperMatrix<Real>* python_to_kaldi(bp::object o) {
    PyObject* raw_arr = PyArray_FromAny(o.ptr(),PyArray_DescrFromType(kaldi::get_np_type<Real>()), 2, 2, NPY_C_CONTIGUOUS | NPY_FORCECAST, NULL);
    //why does this fail: bp::object arr(bp::handle<>(raw_arr));
    bp::object arr=bp::object(bp::handle<>(raw_arr));
    return new kaldi::NpWrapperMatrix<Real>((PyArrayObject*)arr.ptr());
  }
};

template<class Real>
struct VectorToNdArrayConverter {
  typedef kaldi::KaldiObjectHolder<kaldi::Vector<Real> > HR;
  typedef kaldi::KaldiObjectHolder<kaldi::NpWrapperVector<Real> > HW;

  static inline bp::object kaldi_to_python(const kaldi::Vector<Real>& vec) {
    npy_intp dims[1];
    dims[0] = vec.Dim();
    int nd = 1;

    int arr_type = kaldi::get_np_type<Real>();
    PyObject* ao = PyArray_SimpleNew(nd, dims, arr_type);
    bp::object arr=bp::object(bp::handle<>(
        ao
        ));
    kaldi::NpWrapperVector<Real> vec_wrap((PyArrayObject*)arr.ptr());
    vec_wrap.CopyFromVec(vec);
    return arr;
  }

  static inline kaldi::NpWrapperVector<Real>* python_to_kaldi(bp::object o) {
    PyObject* raw_arr = PyArray_FromAny(o.ptr(),PyArray_DescrFromType(kaldi::get_np_type<Real>()), 1, 1, NPY_C_CONTIGUOUS | NPY_FORCECAST, NULL);
    //why does this fail: bp::object arr(bp::handle<>(raw_arr));
    bp::object arr=bp::object(bp::handle<>(raw_arr));
    return new kaldi::NpWrapperVector<Real>((PyArrayObject*)arr.ptr());
  }
};

template<typename T>
struct VectorToNDArrayBPConverter {
  static PyObject* convert(std::vector<T> const& vec) {
    npy_intp dims[1];
    dims[0] = vec.size();
    int nd = 1;
    int arr_type = kaldi::get_np_type<T>();
    PyObject* ao = PyArray_SimpleNew(nd, dims, arr_type);
    bp::object arr=bp::object(bp::handle<>(
        ao
        ));
    std::copy(vec.begin(), vec.end(), (T*)PyArray_DATA(ao));
    return bp::incref(arr.ptr());
  }
};

template<class Obj, class HW_, class HR_>
struct BoostPythonconverter {
  typedef HW_ HW;
  typedef HR_ HR;

  static inline bp::object kaldi_to_python(const Obj& o) {
      return bp::object(o);
    }

    static inline Obj * python_to_kaldi(bp::object o) {
      return new Obj(bp::extract<Obj >(o));
    }
};

template<class Converter>
class PythonToKaldiHolder {
 public:
  typedef bp::object T;
  typedef typename Converter::HR HR;
  typedef typename Converter::HW HW;

  PythonToKaldiHolder() : h_() {
  }

  static bool Write(std::ostream &os, bool binary, const T &t) {
    try {
      auto_ptr<typename HW::T> obj(Converter::python_to_kaldi(t));
      return HW::Write(os, binary, (*obj));
    } catch (std::exception &e) {
      KALDI_WARN << "Exception caught reading Table object";
      if (!kaldi::IsKaldiError(e.what())) {std::cerr << e.what();}
      return false;
    }
  }

  bool Read(std::istream &is) {
    if (!h_.Read(is))
      return false;
    t_ = Converter::kaldi_to_python(h_.Value());
    return true;
  }

  static bool IsReadInBinary() {return true;}

  const T &Value() const {return t_;}  // if t is a pointer, would return *t_;

  void Clear() {}

  ~PythonToKaldiHolder() {}

private:
  KALDI_DISALLOW_COPY_AND_ASSIGN(PythonToKaldiHolder);
  HR h_;
  T t_;  // t_ may alternatively be of type T*.
};

template<class T>
struct VectorHolder {
  typedef PythonToKaldiHolder<BoostPythonconverter<std::vector<T>,
      kaldi::BasicVectorHolder<T>, kaldi::BasicVectorHolder<T> > > type;

  static void register_converters() {
    bp::to_python_converter<std::vector<T>, kaldi::VectorToListBPConverter<T> >();
    kaldi::VectorFromListBPConverter<T>();
  }
};

template<class T>
struct VectorNDArrayHolder {
  typedef PythonToKaldiHolder<BoostPythonconverter<std::vector<T>,
      kaldi::BasicVectorHolder<T>, kaldi::BasicVectorHolder<T> > > type;

  static void register_converters() {
    bp::to_python_converter<std::vector<T>, VectorToNDArrayBPConverter<T> >();
    kaldi::VectorFromListBPConverter<T>();
  }
};

template<class T>
struct VectorVectorHolder {
  typedef PythonToKaldiHolder<BoostPythonconverter<std::vector<std::vector<T> > ,
      kaldi::BasicVectorVectorHolder<T>, kaldi::BasicVectorVectorHolder<T> > > type;

  static void register_converters() {
    bp::to_python_converter<std::vector<std::vector<kaldi::int32> >, kaldi::VectorToListBPConverter<std::vector<kaldi::int32> > >();
    kaldi::VectorFromListBPConverter<std::vector<kaldi::int32> >();
  }
};

template<class T>
struct PairVectorHolder {
  typedef PythonToKaldiHolder<BoostPythonconverter<std::vector<std::pair<T,T> > ,
      kaldi::BasicPairVectorHolder<T>, kaldi::BasicPairVectorHolder<T> > > type;

  static void register_converters() {
    //register the pair first
    bp::to_python_converter<std::pair<kaldi::int32, kaldi::int32>,
      kaldi::PairToTupleBPConverter<kaldi::int32, kaldi::int32> >();
    kaldi::PairFromTupleBPConverter<kaldi::int32, kaldi::int32>();

    //next register the pair vector
    bp::to_python_converter<std::vector<std::pair<kaldi::int32, kaldi::int32> >,
    kaldi::VectorToListBPConverter<std::pair<kaldi::int32, kaldi::int32> > >();
    kaldi::VectorFromListBPConverter<std::pair<kaldi::int32, kaldi::int32> >();
  }
};

template<class T>
const T& get_self_ref(const T& t) {
  return t;
}

template<class T>
void exit(T& t, const bp::object& type,
              const bp::object& value, const bp::object& traceback) {
  t.Close();
}

template<class T>
bp::object sequential_reader_next(T& reader) {
  if (!reader.IsOpen() || reader.Done()) {
    PyErr_SetString(PyExc_StopIteration, "No more data.");
    bp::throw_error_already_set();
  }
  //if not done, extract the contents
  bp::str key(reader.Key());
  bp::object val(reader.Value());
  //move the reading head, the contents will be read with the next call to next!
  reader.Next();
  return bp::make_tuple(key,val);
}

template <class Reader>
class RandomAccessWrapper: public bp::class_<Reader> {
public:
  template <class DerivedT>
  inline RandomAccessWrapper(char const* name, bp::init_base<DerivedT> const& i)
          : bp::class_<Reader>(name, i) {
          (*this)
          .def("close", &Reader::Close)
          .def("is_open", &Reader::IsOpen)
          .def("__contains__", &Reader::HasKey)
          .def("has_key", &Reader::HasKey)
          .def("__getitem__", &Reader::Value,
               bp::return_value_policy<bp::copy_const_reference>())
          .def("value", &Reader::Value,
               bp::return_value_policy<bp::copy_const_reference>())
          .def("__enter__", &get_self_ref<Reader>,
               bp::return_internal_reference<1>())
          .def("__exit__", &exit<Reader>)
          ;
      }
};

template <class Reader>
class SequentialReaderWrapper: public bp::class_<Reader> {
public:
  template <class DerivedT>
  inline SequentialReaderWrapper(char const* name, bp::init_base<DerivedT> const& i)
          : bp::class_<Reader>(name, i) {
          (*this)
          .def("close", &Reader::Close)
          .def("is_open", &Reader::IsOpen)
          .def("__enter__", &get_self_ref<Reader>,
               bp::return_internal_reference<1>())
          .def("__iter__", &get_self_ref<Reader>,
               bp::return_internal_reference<1>())
          .def("next", sequential_reader_next<Reader>)
          .def("__exit__", &exit<Reader>)
          .def("done", &Reader::Done)
          .def("_kaldi_value", &Reader::Value,
                     bp::return_value_policy<bp::copy_const_reference>())
          .def("_kaldi_next", &Reader::Next)
          .def("_kaldi_key", &Reader::Key)
          ;
      }
};

template <class Writer>
class WriterWrapper: public bp::class_<Writer> {
public:
  template <class DerivedT>
  inline WriterWrapper(char const* name, bp::init_base<DerivedT> const& i)
          : bp::class_<Writer>(name, i) {
          (*this)
          .def("close", &Writer::Close)
          .def("is_open", &Writer::IsOpen)
          .def("flush", &Writer::Flush)
          .def("write", &Writer::Write)
          .def("__setitem__", &Writer::Write)
          .def("__enter__", &get_self_ref<Writer>,
               bp::return_internal_reference<1>())
          .def("__exit__",&exit<Writer>)
          ;
      }
};

PyObject* KALDI_BASE_FLOAT() {
  return (PyObject*)PyArray_DescrFromType(kaldi::get_np_type<kaldi::BaseFloat>());
}

BOOST_PYTHON_MODULE(kaldi_io_internal)
{
  import_array();

  bp::def("KALDI_BASE_FLOAT", &KALDI_BASE_FLOAT);

  //Python objects
  RandomAccessWrapper<kaldi::RandomAccessTableReader<PyObjectHolder> >("RandomAccessPythonReader", bp::init<std::string>());
  RandomAccessWrapper<kaldi::RandomAccessTableReaderMapped<PyObjectHolder> >("RandomAccessPythonReaderMapped", bp::init<std::string, std::string>());
  SequentialReaderWrapper<kaldi::SequentialTableReader<PyObjectHolder> >("SequentialPythonReader",bp::init<std::string>());
  WriterWrapper<kaldi::TableWriter<PyObjectHolder> >("PythonWriter", bp::init<std::string>());

  //Matrices as NdArrays
  RandomAccessWrapper<kaldi::RandomAccessTableReader<PythonToKaldiHolder<MatrixToNdArrayConverter<double> > > >("RandomAccessFloat64MatrixReader", bp::init<std::string>());
  RandomAccessWrapper<kaldi::RandomAccessTableReaderMapped<PythonToKaldiHolder<MatrixToNdArrayConverter<double> > > >("RandomAccessFloat64MatrixMapped",bp::init<std::string, std::string>());
  SequentialReaderWrapper<kaldi::SequentialTableReader<PythonToKaldiHolder<MatrixToNdArrayConverter<double> > > >("SequentialFloat64MatrixReader",bp::init<std::string>());
  WriterWrapper<kaldi::TableWriter<PythonToKaldiHolder<MatrixToNdArrayConverter<double> > > >("Float64MatrixWriter", bp::init<std::string>());

  RandomAccessWrapper<kaldi::RandomAccessTableReader<PythonToKaldiHolder<MatrixToNdArrayConverter<float> > > >("RandomAccessFloat32MatrixReader", bp::init<std::string>());
  RandomAccessWrapper<kaldi::RandomAccessTableReaderMapped<PythonToKaldiHolder<MatrixToNdArrayConverter<float> > > >("RandomAccessFloat32MatrixMapped",bp::init<std::string, std::string>());
  SequentialReaderWrapper<kaldi::SequentialTableReader<PythonToKaldiHolder<MatrixToNdArrayConverter<float> > > >("SequentialFloat32MatrixReader",bp::init<std::string>());
  WriterWrapper<kaldi::TableWriter<PythonToKaldiHolder<MatrixToNdArrayConverter<float> > > >("Float32MatrixWriter", bp::init<std::string>());

  //Vectors as NdArrays
  RandomAccessWrapper<kaldi::RandomAccessTableReader<PythonToKaldiHolder<VectorToNdArrayConverter<double> > > >("RandomAccessFloat64VectorReader", bp::init<std::string>());
  RandomAccessWrapper<kaldi::RandomAccessTableReaderMapped<PythonToKaldiHolder<VectorToNdArrayConverter<double> > > >("RandomAccessFloat64VectorReaderMapped",bp::init<std::string, std::string>());
  SequentialReaderWrapper<kaldi::SequentialTableReader<PythonToKaldiHolder<VectorToNdArrayConverter<double> > > >("SequentialFloat64VectorReader",bp::init<std::string>());
  WriterWrapper<kaldi::TableWriter<PythonToKaldiHolder<VectorToNdArrayConverter<double> > > >("Float64VectorWriter", bp::init<std::string>());

  RandomAccessWrapper<kaldi::RandomAccessTableReader<PythonToKaldiHolder<VectorToNdArrayConverter<float> > > >("RandomAccessFloat32VectorReader", bp::init<std::string>());
  RandomAccessWrapper<kaldi::RandomAccessTableReaderMapped<PythonToKaldiHolder<VectorToNdArrayConverter<float> > > >("RandomAccessFloat32VectorReaderMapped",bp::init<std::string, std::string>());
  SequentialReaderWrapper<kaldi::SequentialTableReader<PythonToKaldiHolder<VectorToNdArrayConverter<float> > > >("SequentialFloat32VectorReader",bp::init<std::string>());
  WriterWrapper<kaldi::TableWriter<PythonToKaldiHolder<VectorToNdArrayConverter<float> > > >("Float32VectorWriter", bp::init<std::string>());

  //Integers
  RandomAccessWrapper<kaldi::RandomAccessInt32Reader >("RandomAccessInt32Reader", bp::init<std::string>());
  SequentialReaderWrapper<kaldi::SequentialInt32Reader >("SequentialInt32Reader",bp::init<std::string>());
  WriterWrapper<kaldi::Int32Writer >("Int32Writer", bp::init<std::string>());

  // std::vector<int32> as ndarray
  VectorNDArrayHolder<kaldi::int32>::register_converters();
  RandomAccessWrapper<kaldi::RandomAccessTableReader<VectorNDArrayHolder<kaldi::int32>::type > >("RandomAccessInt32VectorReader", bp::init<std::string>());
  SequentialReaderWrapper<kaldi::SequentialTableReader<VectorNDArrayHolder<kaldi::int32>::type > >("SequentialInt32VectorReader",bp::init<std::string>());
  WriterWrapper<kaldi::TableWriter<VectorNDArrayHolder<kaldi::int32>::type > >("Int32VectorWriter", bp::init<std::string>());

//  Vector of simple types as lists
//  VectorHolder<kaldi::int32>::register_converters();
//  RandomAccessWrapper<kaldi::RandomAccessTableReader<VectorHolder<kaldi::int32>::type > >("RandomAccessInt32VectorReader", bp::init<std::string>());
//  SequentialReaderWrapper<kaldi::SequentialTableReader<VectorHolder<kaldi::int32>::type > >("SequentialInt32VectorReader",bp::init<std::string>());
//  WriterWrapper<kaldi::TableWriter<VectorHolder<kaldi::int32>::type > >("Int32VectorWriter", bp::init<std::string>());

  // std::vector<std::vector<int32> >
  VectorVectorHolder<kaldi::int32>::register_converters();
  RandomAccessWrapper<kaldi::RandomAccessTableReader<VectorVectorHolder<kaldi::int32>::type > >("RandomAccessInt32VectorVectorReader", bp::init<std::string>());
  SequentialReaderWrapper<kaldi::SequentialTableReader<VectorVectorHolder<kaldi::int32>::type > >("SequentialInt32VectorVectorReader",bp::init<std::string>());
  WriterWrapper<kaldi::TableWriter<VectorVectorHolder<kaldi::int32>::type > >("Int32VectorVectorWriter", bp::init<std::string>());

  // std::vector<std::pair<int32, int32> >
  PairVectorHolder<kaldi::int32>::register_converters();
  RandomAccessWrapper<kaldi::RandomAccessTableReader<PairVectorHolder<kaldi::int32>::type > >("RandomAccessInt32PairVectorReader", bp::init<std::string>());
  SequentialReaderWrapper<kaldi::SequentialTableReader<PairVectorHolder<kaldi::int32>::type > >("SequentialInt32PairVectorReader",bp::init<std::string>());
  WriterWrapper<kaldi::TableWriter<PairVectorHolder<kaldi::int32>::type > >("Int32PairVectorWriter", bp::init<std::string>());

}


text:
#include <gtest/gtest.h>

#include "celix/PushStreamProvider.h"

using celix::PushStreamProvider;

class TestException : public std::exception {
public:
    explicit TestException(const char* what) : w{what} {}
    explicit TestException(std::string what) : w{std::move(what)} {}

    TestException(const TestException&) = delete;
    TestException(TestException&&) noexcept = default;

    TestException& operator=(const TestException&) = delete;
    TestException& operator=(TestException&&) noexcept = default;

    [[nodiscard]] const char* what() const noexcept override { return w.c_str(); }
private:
    std::string w;
};

class EventObject {
public:
    EventObject() : val{0} {
    }

    explicit EventObject(int _val) : val{_val} {
    }

    EventObject(const EventObject& _val) = default;
    EventObject& operator=(const EventObject& other) = default;

    EventObject& operator=(int other) {
        val = other;
        return *this;
    };

    friend EventObject operator+(const EventObject &eo1, const EventObject  &eo2) {
        return EventObject{eo1.val + eo2.val};
    }
    friend int operator+(const int &eo1, const EventObject  &eo2) {
        return eo1 + eo2.val;
    }
    friend int operator+(const EventObject &eo1, const int  &eo2) {
        return eo1.val + eo2;
    }
    int val;
};

class PushStreamTestSuite : public ::testing::Test {
public:
    ~PushStreamTestSuite() noexcept override = default;

    PushStreamProvider psp {};
    std::unique_ptr<std::thread> t{};

    std::shared_ptr<celix::PromiseFactory> promiseFactory {std::make_shared<celix::PromiseFactory>()};
    std::mutex mutex{};
    std::condition_variable done{};
    std::atomic<bool> allEventsDone{false};

    template <typename T>
    std::shared_ptr<celix::AbstractPushEventSource<T>> createEventSource(T event, int publishCount, bool autoinc = false, bool syncSource = true) {
        allEventsDone = false;
        std::shared_ptr<celix::AbstractPushEventSource<T>> ses;
        if (syncSource)
            ses = psp.template createSynchronousEventSource<T>(promiseFactory);
        else
            ses = psp.template createAsynchronousEventSource<T>(promiseFactory);

        auto successLambda = [this, weakses = std::weak_ptr<celix::AbstractPushEventSource<T>>(ses), event, publishCount, autoinc](celix::Promise<void> p) -> celix::Promise<void> {
            t = std::make_unique<std::thread>([&, event, publishCount, autoinc]() {
                int counter = 0;
                T data {event};
                // Keep going as long as someone is listening
                while (counter < publishCount) {
                    auto ses = weakses.lock();
                    if (ses) {
                        ses->publish(data);
                    }
                    if (autoinc) {
                        data = data + 1;
                    }
                    counter++;
                }
            });

            t->join();
            std::unique_lock lk(mutex);
            allEventsDone = true;
            done.notify_one();
            return p;
        };

        auto x = ses->connectPromise().template then<void>(successLambda);

        return ses;
    }
};

TEST_F(PushStreamTestSuite, EventSourceCloseTest) {
    int onClosedReceived{0};
    int onErrorReceived{0};

    auto ses = psp.template createSynchronousEventSource<int>(promiseFactory);
    auto stream = psp.createUnbufferedStream<int>(ses, promiseFactory);

    auto streamEnded = stream->onClose([&](){
        onClosedReceived++;
    }).onError([&](){
        onErrorReceived++;
    }).forEach([&](int /*event*/) { });

    ses->close();

    streamEnded.wait();

    ASSERT_EQ(1, onClosedReceived);
    ASSERT_EQ(0, onErrorReceived);
}

TEST_F(PushStreamTestSuite, ChainedEventSourceCloseTest) {
    int onClosedReceived{0};
    int onErrorReceived{0};

    auto ses = psp.template createSynchronousEventSource<int>(promiseFactory);

    auto stream = psp.createUnbufferedStream<int>(ses, promiseFactory);
    auto& filteredStream = stream->filter([](const int& /*event*/) -> bool {
            return true;
        }).onClose([&](){
            onClosedReceived++;
        }).onError([&](){
            onErrorReceived++;
        });

    auto streamEnded = filteredStream.forEach([&](int /*event*/) { });

    ses->close();

    streamEnded.wait();

    ASSERT_EQ(1, onClosedReceived);
    ASSERT_EQ(0, onErrorReceived);
}

TEST_F(PushStreamTestSuite, StreamCloseTest) {
    int onClosedReceived{0};
    int onErrorReceived{0};

    auto ses = psp.createSynchronousEventSource<int>(promiseFactory);
    auto stream = psp.createUnbufferedStream<int>(ses, promiseFactory);
    auto streamEnded = stream->onClose([&](){
        onClosedReceived++;
    }).onError([&](){
        onErrorReceived++;
    }).forEach([&](int /*event*/) { });

    stream->close();

    streamEnded.wait();

    ASSERT_EQ(1, onClosedReceived);
    ASSERT_EQ(0, onErrorReceived);
}

TEST_F(PushStreamTestSuite, PublishAfterStreamCloseTest) {
    int onClosedReceived{0};
    int onErrorReceived{0};
    int onEventReceived{0};

    auto ses = psp.createSynchronousEventSource<int>(promiseFactory);
    auto stream = psp.createUnbufferedStream<int>(ses, promiseFactory);
    auto streamEnded = stream->onClose([&](){
        onClosedReceived++;
    }).onError([&](){
        onErrorReceived++;
    }).forEach([&](int /*event*/) {
        onEventReceived++;
    });

    stream->close();
    ses->publish(1);

    streamEnded.wait();

    ASSERT_EQ(1, onClosedReceived);
    ASSERT_EQ(0, onErrorReceived);
    ASSERT_EQ(0, onEventReceived);
}

TEST_F(PushStreamTestSuite, ChainedStreamCloseTest) {
    int onClosedReceived{0};
    int onErrorReceived{0};

    auto ses = psp.template createSynchronousEventSource<int>(promiseFactory);
    auto stream = psp.createUnbufferedStream<int>(ses, promiseFactory);
    auto streamEnded = stream->
            filter([](const int& /*event*/) -> bool {
                return true;
            }).onClose([&](){
                onClosedReceived++;
            }).onError([&](){
                onErrorReceived++;
            }).forEach([&](int /*event*/) { });

    stream->close();

    streamEnded.wait();

    ASSERT_EQ(1, onClosedReceived);
    ASSERT_EQ(0, onErrorReceived);
}

TEST_F(PushStreamTestSuite, ChainedStreamIntermedateCloseTest) {
    int onClosedReceived{0};
    int onErrorReceived{0};

    auto ses = psp.template createSynchronousEventSource<int>(promiseFactory);
    auto stream1 = psp.createUnbufferedStream<int>(ses, promiseFactory);
    stream1->onClose([&](){
        onClosedReceived++;
    });
    auto& stream2 = stream1->filter([](const int& /*event*/) -> bool {
                return true;
            }).onClose([&](){
                onClosedReceived++;
            }).onError([&](){
                onErrorReceived++;
            });
    auto streamEnded = stream2.forEach([&](int /*event*/) { });

    stream1->close();

    streamEnded.wait();

    ASSERT_EQ(2, onClosedReceived);
    ASSERT_EQ(0, onErrorReceived);
}

TEST_F(PushStreamTestSuite, ExceptionInStreamTest) {
    int onClosedReceived{0};
    int onErrorReceived{0};

    auto ses = psp.createSynchronousEventSource<int>(promiseFactory);
    auto stream = psp.createUnbufferedStream<int>(ses, promiseFactory);
    auto streamEnded = stream->onClose([&](){
        onClosedReceived++;
    }).onError([&](){
        onErrorReceived++;
    }).forEach([&](int /*event*/) {
        throw TestException("Oops");
    });

    ses->publish(1);

    streamEnded.wait();

    ASSERT_EQ(1, onClosedReceived);
    ASSERT_EQ(1, onErrorReceived);
}

TEST_F(PushStreamTestSuite, ExceptionInChainedStreamTest) {
    int onClosedReceived{0};
    int onErrorReceived{0};
    auto ses = psp.template createSynchronousEventSource<int>(promiseFactory);
    auto stream = psp.createUnbufferedStream<int>(ses, promiseFactory);
    auto streamEnded = stream->filter([](const int& /*event*/) -> bool {
                return true;
            }).onClose([&](){
                onClosedReceived++;
            }).onError([&](){
                onErrorReceived++;
            }).forEach([&](int /*event*/) {
        throw TestException("Oops");
    });

    ses->publish(1);

    streamEnded.wait();

    ASSERT_EQ(1, onClosedReceived);
    ASSERT_EQ(1, onErrorReceived);
}

//
///
/// forEach test
///
TEST_F(PushStreamTestSuite, ForEachTestBasicType) {
    for(int i = 0; i < 100; i++ ) {
        int consumeCount{0};
        int consumeSum{0};
        int lastConsumed{-1};
        std::unique_lock lk(mutex);

        auto ses = createEventSource<int>(0, 10'000, true);

        auto stream = psp.createUnbufferedStream<int>(ses, promiseFactory);
        auto streamEnded = stream->
                forEach([&](int event) {
                    GTEST_ASSERT_EQ(lastConsumed + 1, event);

                    lastConsumed = event;
                    consumeCount++;
                    consumeSum = consumeSum + event;
                });

        done.wait(lk, [&](){ return allEventsDone==true;});
        promiseFactory->getExecutor()->wait();
        ses->close();
        streamEnded.wait();

        GTEST_ASSERT_EQ(10'000, consumeCount);
        GTEST_ASSERT_EQ(49'995'000, consumeSum);
    }
}

///
/// forEach test
///
TEST_F(PushStreamTestSuite, ForEachTestBasicType_Buffered) {

    for(int i = 0; i < 100; i++ ) {
        int consumeCount{0};
        int consumeSum{0};
        int lastConsumed{-1};
        std::unique_lock lk(mutex);

        auto ses = createEventSource<int>(0, 10'000, true);

        auto stream = psp.createStream<int>(ses, promiseFactory);
        auto streamEnded = stream->
                forEach([&](int event) {
                    GTEST_ASSERT_EQ(lastConsumed + 1, event);

                    lastConsumed = event;
                    consumeCount++;
                    consumeSum = consumeSum + event;
                });

        done.wait(lk, [&](){ return allEventsDone==true;});
        promiseFactory->getExecutor()->wait();
        ses->close();
        streamEnded.wait();

        GTEST_ASSERT_EQ(10'000, consumeCount);
        GTEST_ASSERT_EQ(49'995'000, consumeSum);
    }

}

TEST_F(PushStreamTestSuite, ForEachTestObjectType) {
    std::atomic<int> consumeCount{0};
    std::atomic<int> consumeSum{0};
    std::unique_lock lk(mutex);

    auto ses = createEventSource<EventObject>(EventObject{2}, 10);

    auto stream = psp.createUnbufferedStream<EventObject>(ses, promiseFactory);
    auto streamEnded = stream->
            forEach([&](const EventObject& event) {
                consumeCount++;
                consumeSum = consumeSum + event;
            });

    done.wait(lk, [&](){ return allEventsDone==true;});
    promiseFactory->getExecutor()->wait();
    ses->close();
    streamEnded.wait();

    GTEST_ASSERT_EQ(10, consumeCount);
    GTEST_ASSERT_EQ(20, consumeSum);
}

//Filter Test
TEST_F(PushStreamTestSuite, FilterTestObjectType_true) {
    int consumeCount{0};
    int consumeSum{0};
    std::unique_lock lk(mutex);

    auto ses = createEventSource<EventObject>(EventObject{2}, 10);

    auto stream = psp.createUnbufferedStream<EventObject>(ses, promiseFactory);
    auto streamEnded = stream->
            filter([](const EventObject& /*event*/) -> bool {
               return true;
            }).
            forEach([&](EventObject event) {
                consumeCount++;
                consumeSum = consumeSum + event;
            });

    done.wait(lk, [&](){ return allEventsDone==true;});
    promiseFactory->getExecutor()->wait();
    ses->close();
    streamEnded.wait();

    GTEST_ASSERT_EQ(10, consumeCount);
    GTEST_ASSERT_EQ(20, consumeSum);
}

//Filter Test
TEST_F(PushStreamTestSuite, FilterTestObjectType_false) {
    int consumeCount{0};
    int consumeSum{0};
    std::unique_lock lk(mutex);

    auto ses = createEventSource<EventObject>(EventObject{2}, 10);

    auto stream = psp.createUnbufferedStream<EventObject>(ses, promiseFactory);
    auto streamEnded = stream->
            filter([](const EventObject& /*event*/) -> bool {
                return false;
            }).
            forEach([&](EventObject event) {
                consumeCount++;
                consumeSum = consumeSum + event;
            });

    done.wait(lk, [&](){ return allEventsDone==true;});
    promiseFactory->getExecutor()->wait();
    ses->close();
    streamEnded.wait();

    GTEST_ASSERT_EQ(0, consumeCount);
    GTEST_ASSERT_EQ(0, consumeSum);
}

TEST_F(PushStreamTestSuite, FilterTestObjectType_simple) {
    int consumeCount{0};
    int consumeSum{0};

    std::unique_lock lk(mutex);

    auto ses = createEventSource<EventObject>(EventObject{0}, 10, true);

    auto stream = psp.createUnbufferedStream<EventObject>(ses, promiseFactory);
    auto streamEnded = stream->
            filter([](const EventObject& event) -> bool {
                return event.val < 5;
            }).
            forEach([&](EventObject event) {
                consumeCount++;
                consumeSum = consumeSum + event;
            });

    done.wait(lk, [&](){ return allEventsDone==true;});
    promiseFactory->getExecutor()->wait();
    ses->close();
    streamEnded.wait();

    GTEST_ASSERT_EQ(5, consumeCount);
    GTEST_ASSERT_EQ( 0 + 1 + 2 + 3 + 4, consumeSum);
}

TEST_F(PushStreamTestSuite, FilterTestObjectType_and) {
    int consumeCount{0};
    int consumeSum{0};
    std::unique_lock lk(mutex);

    auto ses = createEventSource<EventObject>(EventObject{0}, 10, true);

    auto stream = psp.createUnbufferedStream<EventObject>(ses, promiseFactory);
    auto streamEnded = stream->
            filter([](const EventObject& predicate) -> bool {
                return predicate.val > 5;
            }).
            filter([](const EventObject& predicate) -> bool {
                return predicate.val < 8;
            }).
            forEach([&](const EventObject& event) {
                consumeCount++;
                consumeSum = consumeSum + event;
            });

    done.wait(lk, [&](){ return allEventsDone==true;});
    promiseFactory->getExecutor()->wait();
    ses->close();
    streamEnded.wait();

    GTEST_ASSERT_EQ(2, consumeCount);
    GTEST_ASSERT_EQ(6 + 7, consumeSum); // 0 + 1 + 2 + 3 + 4
}

TEST_F(PushStreamTestSuite, MapTestObjectType) {
    int consumeCount{0};
    int consumeSum{0};
    std::unique_lock lk(mutex);

    auto ses = createEventSource<EventObject>(EventObject{0}, 10, true);
    auto stream = psp.createUnbufferedStream<EventObject>(ses, promiseFactory);
    auto streamEnded = stream->
            map<int>([](const EventObject& event) -> int {
                return event.val;
            }).
            forEach([&](const int& event) {
                consumeCount++;
                consumeSum = consumeSum + event;
            });

    done.wait(lk, [&](){ return allEventsDone==true;});
    promiseFactory->getExecutor()->wait();
    ses->close();
    streamEnded.wait();

    GTEST_ASSERT_EQ(10, consumeCount);
    GTEST_ASSERT_EQ(45, consumeSum);
}

TEST_F(PushStreamTestSuite, MapTestObjectType_async) {
    for(int i = 0; i < 1000; i++) {
        std::atomic<int> consumeCount{0};
        std::atomic<int> consumeSum{0};
        std::unique_lock lk(mutex);

        auto ses = createEventSource<EventObject>(EventObject{0}, 10, true, false);
        auto stream = psp.createUnbufferedStream<EventObject>(ses, promiseFactory);
        auto streamEnded = stream->
                map<int>([](const EventObject &event) -> int {
            return event.val;
        }).
                forEach([&](const int &event) {
            consumeCount++;
            consumeSum += + event;
        });

        done.wait(lk, [&](){ return allEventsDone==true;});
        promiseFactory->getExecutor()->wait();
        ses->close();
        streamEnded.wait();

        GTEST_ASSERT_EQ(10, consumeCount);
        GTEST_ASSERT_EQ(45, consumeSum);
    }
}

TEST_F(PushStreamTestSuite, MultipleStreamsTest_CloseSource) {
    int onEventStream1{0};
    int onEventStream2{0};
    int onClosedReceived1{0};
    int onClosedReceived2{0};
    int onErrorReceived1{0};
    int onErrorReceived2{0};

    std::unique_lock lk(mutex);

    auto psp = PushStreamProvider();
    std::unique_ptr<std::thread> t{};
    auto ses = createEventSource<int>(0, 20, true);

    auto stream1 = psp.createUnbufferedStream<int>(ses, promiseFactory);
    auto streamEnded1 = stream1->
    filter([&](int event) -> bool {
        return (event > 10);
    }).
    filter([&](int event) -> bool {
        return (event < 15);
    }).onClose([&](){
        onClosedReceived1++;
    }).onError([&](){
        onErrorReceived1++;
    }).
    forEach([&](int /*event*/) {
        onEventStream1++;
    });

    auto stream2 = psp.createUnbufferedStream<int>(ses, promiseFactory);
    auto streamEnded2 = stream2->
    filter([&](int event) -> bool {
        return (event < 15);
    }).onClose([&](){
        onClosedReceived2++;
    }).onError([&](){
        onErrorReceived2++;
    }).forEach([&](int /*event*/) {
        onEventStream2++;
    });

    streamEnded1.onSuccess([]() {
    });

    streamEnded2.onSuccess([]() {
    });

    done.wait(lk, [&](){ return allEventsDone==true;});
    promiseFactory->getExecutor()->wait();
    ses->close();
    streamEnded1.wait();
    streamEnded2.wait();

    GTEST_ASSERT_EQ(4, onEventStream1);
    //The first stream will start the source, thus the number of receives in second is not guaranteed
    //GTEST_ASSERT_EQ(15, onEventStream2);

    GTEST_ASSERT_EQ(1, onClosedReceived1);
    GTEST_ASSERT_EQ(1, onClosedReceived2);
    GTEST_ASSERT_EQ(0, onErrorReceived1);
    GTEST_ASSERT_EQ(0, onErrorReceived2);
}

TEST_F(PushStreamTestSuite, MultipleStreamsTest_CloseStream) {
    int onEventStream1{0};
    int onEventStream2{0};
    auto psp = PushStreamProvider();
    std::unique_ptr<std::thread> t{};
    auto ses = psp.template createSynchronousEventSource<int>(promiseFactory);

    auto successLambda = [](celix::Promise<void> p) -> celix::Promise<void> {
        return p;
    };
    auto x = ses->connectPromise().template then<void>(successLambda);

    auto stream1 = psp.createUnbufferedStream<int>(ses, promiseFactory);

    auto streamEnded1 = stream1->
            filter([&](int event) -> bool {
                return (event > 10);
            }).
            filter([&](int event) -> bool {
                return (event < 15);
            }).
            forEach([&](int /*event*/) {
                onEventStream1++;
            });

    auto stream2 = psp.createUnbufferedStream<int>(ses, promiseFactory);
    auto streamEnded2 = stream2->
            filter([&](int event) -> bool {
                return (event < 15);
            }).
            forEach([&](int /*event*/) {
                onEventStream2++;
            });

    streamEnded1.onSuccess([]() {
    });

    streamEnded2.onSuccess([]() {
    });

    stream1->close();
    streamEnded1.wait();

    ses->publish(10);

    stream2->close();
    streamEnded2.wait();

    GTEST_ASSERT_EQ(0, onEventStream1);
    GTEST_ASSERT_EQ(1, onEventStream2);
}

TEST_F(PushStreamTestSuite, SplitStreamsTest) {
    std::map<int,int> counts{};
    counts[0] = 0;
    counts[1] = 0;
    int onClosedReceived{0};

    std::unique_lock lk(mutex);

    auto psp = PushStreamProvider();
    std::unique_ptr<std::thread> t{};
    auto ses = createEventSource<int>(0, 20, true);

    auto stream = psp.createUnbufferedStream<int>(ses, promiseFactory);
    auto splitStream = stream->
        split({
                            [&](int event) -> bool {
                                return (event > 10);
                            },
                            [&](int event) -> bool {
                                return (event < 12);
                            }
        });

    std::vector<celix::Promise<void>> streamEndeds{};

    for(long unsigned int i = 0; i < splitStream.size(); i++) {
        streamEndeds.push_back(splitStream[i]->onClose([&](){
            onClosedReceived++;
        }).forEach([&, i = i](int /*event*/) {
            counts[i] = counts[i] + 1;
        }));

        streamEndeds[i].onSuccess([]() {
        });
    }

    done.wait(lk, [&](){ return allEventsDone==true;});
    promiseFactory->getExecutor()->wait();
    ses->close();
    promiseFactory->getExecutor()->wait();

    GTEST_ASSERT_EQ(2, onClosedReceived);
    GTEST_ASSERT_EQ(9, counts[0]);
    //The first stream will start the source, thus the number of receives in second is not guaranteed
    //GTEST_ASSERT_EQ(12, counts[1]);
}

redpajama_set_name: RedPajamaGithub


text:
<!DOCTYPE html>

		<meta charset="utf-8">
	    <meta http-equiv="X-UA-Compatible" content="IE=edge">
		<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1,user-scalable=no">
		<meta name="apple-mobile-web-app-capable" content="yes">
	    <meta name="apple-mobile-web-app-status-bar-style" content="black">
		<title></title>

		<input type="text" id="institude" value="" readonly="readonly" placeholder="全部院级/系部"/>


text:
assert(not nn.Repeater, "update nnx package : luarocks install nnx")
local Repeater, parent = torch.class('nn.Repeater', 'nn.AbstractSequencer')

function Repeater:__init(rnn, nStep)
   parent.__init(self)
   assert(torch.type(nStep) == 'number', "expecting number value for arg 2")
   self.nStep = nStep
   self.rnn = rnn
   assert(torch.isTypeOf(rnn, "nn.AbstractRecurrent"), "expecting AbstractRecurrent instance for arg 1")
   self.modules[1] = rnn
   self.output = {}
end

function Repeater:updateOutput(input)
   self.rnn:forget()
   -- TODO make copy outputs optional
   for step=1,self.nStep do
      self.output[step] = nn.rnn.recursiveCopy(self.output[step], self.rnn:updateOutput(input))
   end
   return self.output
end

function Repeater:updateGradInput(input, gradOutput)
   assert(self.rnn.step - 1 == self.nStep, "inconsistent rnn steps")
   assert(torch.type(gradOutput) == 'table', "expecting gradOutput table")
   assert(#gradOutput == self.nStep, "gradOutput should have nStep elements")
   for step=1,self.nStep do
      self.rnn.step = step + 1
      self.rnn:updateGradInput(input, gradOutput[step])
   end
   -- back-propagate through time (BPTT)
   self.rnn:updateGradInputThroughTime()

   for i,currentGradInput in ipairs(self.rnn.gradInputs) do
      if i == 1 then
         self.gradInput = nn.rnn.recursiveCopy(self.gradInput, currentGradInput)
      else
         nn.rnn.recursiveAdd(self.gradInput, currentGradInput)
      end
   end

   return self.gradInput
end

function Repeater:accGradParameters(input, gradOutput, scale)
   assert(self.rnn.step - 1 == self.nStep, "inconsistent rnn steps")
   assert(torch.type(gradOutput) == 'table', "expecting gradOutput table")
   assert(#gradOutput == self.nStep, "gradOutput should have nStep elements")
   for step=1,self.nStep do
      self.rnn.step = step + 1
      self.rnn:accGradParameters(input, gradOutput[step], scale)
   end
   -- back-propagate through time (BPTT)
   self.rnn:accGradParametersThroughTime()
end

function Repeater:accUpdateGradParameters(input, gradOutput, lr)
   assert(self.rnn.step - 1 == self.nStep, "inconsistent rnn steps")
   assert(torch.type(gradOutput) == 'table', "expecting gradOutput table")
   assert(#gradOutput == self.nStep, "gradOutput should have nStep elements")
   for step=1,self.nStep do
      self.rnn.step = step + 1
      self.rnn:accGradParameters(input, gradOutput[step], 1)
   end
   -- back-propagate through time (BPTT)
   self.rnn:accUpdateGradParametersThroughTime(lr)
end

function Repeater:__tostring__()
   local tab = '  '
   local line = '\n'
   local str = torch.type(self) .. ' {' .. line
   str = str .. tab .. '[  input,    input,  ...,  input  ]'.. line
   str = str .. tab .. '     V         V             V     '.. line
   str = str .. tab .. tostring(self.modules[1]):gsub(line, line .. tab) .. line
   str = str .. tab .. '     V         V             V     '.. line
   str = str .. tab .. '[output(1),output(2),...,output('..self.nStep..')]' .. line
   str = str .. '}'
   return str
end


text:
package com.ctrip.xpipe.redis.checker.healthcheck;

import com.ctrip.xpipe.endpoint.HostPort;
import com.ctrip.xpipe.redis.checker.AbstractCheckerIntegrationTest;
import com.ctrip.xpipe.redis.checker.healthcheck.actions.ping.PingAction;
import com.ctrip.xpipe.redis.checker.healthcheck.actions.ping.PingActionContext;
import com.ctrip.xpipe.redis.core.entity.ClusterMeta;
import com.ctrip.xpipe.redis.core.entity.DcMeta;
import com.ctrip.xpipe.redis.core.entity.RedisMeta;
import com.ctrip.xpipe.redis.core.entity.ShardMeta;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;

/**
 * @author chen.zhu
 * <p>
 * Sep 06, 2018
 */
public class AbstractHealthCheckActionTest extends AbstractCheckerIntegrationTest {

    @Autowired
    private List<HealthCheckActionListener> listeners;

    @Autowired
    private HealthCheckInstanceManager instanceManager;

    @Test
    public void testOnActionWithPing() {
        DcMeta dcMeta = new DcMeta("dc");
        ClusterMeta clusterMeta = new ClusterMeta("cluster");
        ShardMeta shardMeta = new ShardMeta("shard");
        RedisMeta redisMeta = new RedisMeta().setIp("127.0.0.1").setPort(6379).setMaster(null);
        shardMeta.addRedis(redisMeta);
        clusterMeta.addShard(shardMeta);
        dcMeta.addCluster(clusterMeta);
        RedisHealthCheckInstance instance = instanceManager.getOrCreate(redisMeta);
        PingAction action = new PingAction(scheduled, instance, executors);
        action.addListeners(listeners);
        action.notifyListeners(new PingActionContext(instance, true));
        instanceManager.remove(new HostPort(instance.getEndpoint().getHost(), instance.getEndpoint().getPort()));
    }
}


text:
// Copyright (c) DotSpatial Team. All rights reserved.
// Licensed under the MIT license. See License.txt file in the project root for full license information.

using System;
using System.ComponentModel;

namespace DotSpatial.Controls
{
    /// <summary>
    /// A Brian Marchioni original toolstrip... preloaded with content.
    /// </summary>
    // This control will no longer be visible
    [ToolboxItem(false)]
    public partial class LayoutMapToolStrip : LayoutToolStrip
    {
        #region  Constructors

        /// <summary>
        /// Initializes a new instance of the <see cref="LayoutMapToolStrip"/> class.
        /// </summary>
        public LayoutMapToolStrip()
        {
            InitializeComponent();
        }

        #endregion

        #region Methods

        // Fires when the user clicks the pan button.
        private void BtnPanClick(object sender, EventArgs e)
        {
            LayoutControl.MouseMode = MouseMode.StartPanMap;
            SetChecked(_btnPan);
        }

        // Fires when the user clicks the zoom to full extent button
        private void BtnZoomFullExtentClick(object sender, EventArgs e)
        {
            (LayoutControl.SelectedLayoutElements[0] as LayoutMap)?.ZoomToFullExtent();
        }

        // Fires the zoom in control on the modeler
        private void BtnZoomInClick(object sender, EventArgs e)
        {
            (LayoutControl.SelectedLayoutElements[0] as LayoutMap)?.ZoomInMap();
        }

        // Fires the zoom out control on the modeler
        private void BtnZoomOutClick(object sender, EventArgs e)
        {
            (LayoutControl.SelectedLayoutElements[0] as LayoutMap)?.ZoomOutMap();
        }

        // Zoom the map to the extent of the layout
        private void BtnZoomViewExtentClick(object sender, EventArgs e)
        {
            (LayoutControl.SelectedLayoutElements[0] as LayoutMap)?.ZoomViewExtent();
        }

        // If the toolbar is disabled we disable the pan checked button state
        private void LayoutMapToolStripEnabledChanged(object sender, EventArgs e)
        {
            _btnPan.Checked = false;
        }

        #endregion
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<weblogic-web-app xmlns="http://xmlns.oracle.com/weblogic/weblogic-web-app">
	<weblogic-version>10.3.5</weblogic-version>

	<session-descriptor>
		<cookie-path>/fotorest-jsf2-pf</cookie-path>
		<persistent-store-type>memory</persistent-store-type>
	</session-descriptor>
	<context-root>fotorest-jsf2-pf</context-root>

	<library-ref>
		<library-name>jsf</library-name>
		<specification-version>2.0</specification-version>
		<implementation-version>1.0.0.0_2-0-2</implementation-version>
		<exact-match>true</exact-match>
	</library-ref>
	<library-ref>
		<library-name>jstl</library-name>
		<specification-version>1.2</specification-version>
		<implementation-version>1.2.0.1</implementation-version>
		<exact-match>true</exact-match>
	</library-ref>

	<container-descriptor>
		<prefer-web-inf-classes>true</prefer-web-inf-classes>
	</container-descriptor>

    <fast-swap>
        <enabled>false</enabled>
    </fast-swap>
</weblogic-web-app>


text:
require 'redmine'
require 'issue_templates_issues_hook'
require 'issue_templates_projects_helper_patch'

Redmine::Plugin.register :redmine_issue_templates do
  name 'Redmine Issue Templates plugin'
  author 'Akiko Takano'
  description 'Plugin to generate and use issue templates for each project to assist issue creation.'
  version '0.0.9'
  author_url 'http://twitter.com/akiko_pusu'
  requires_redmine :version_or_higher => '2.1.0'
  url 'https://bitbucket.org/akiko_pusu/redmine_issue_templates'

  menu :admin_menu, :redmine_issue_templates, { :controller => 'global_issue_templates', :action => 'index' },
       :caption => :global_issue_templates

  project_module :issue_templates do
    permission :edit_issue_templates, {:issue_templates => [:new, :edit, :destroy, :move]}
    permission :show_issue_templates, {:issue_templates => [:index, :show, :load, :set_pulldown]}
    permission :manage_issue_templates,
      {:issue_templates_settings => [:show, :edit]}, :require => :member
  end

  Rails.configuration.to_prepare do
    require_dependency 'projects_helper'
    unless ProjectsHelper.included_modules.include? IssueTemplatesProjectsHelperPatch
      ProjectsHelper.send(:include, IssueTemplatesProjectsHelperPatch)
    end
  end
end


text:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.x.cloudhub" android:versionCode="1" android:versionName="1.0" >
    <uses-sdk android:minSdkVersion="10" android:targetSdkVersion="14"/>
    <uses-permission android:name="android.permission.INTERNET"></uses-permission>
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"></uses-permission>
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"></uses-permission>
       <uses-feature android:name="android.hardware.camera" android:required="true" />
    <application android:icon="@drawable/ic_launcher" android:label="@string/app_name" >
        <activity android:label="@string/app_name" android:name=".MainActivity" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity android:name=".ChooseServiceActivity" android:label="@string/addservice"></activity>
        <activity android:name=".DownloadsActivity" android:label="Downloads"></activity>
        <activity android:name=".SetupActivity" android:label="Setup"></activity>
        <activity android:name=".ChooseMethodActivity" android:label="Configure Cloud"></activity>
        <activity android:name=".FileAccessActivity" android:label="File System"></activity>
        <activity android:name=".DebugActivity" android:label="Debug"></activity>
        <activity android:name=".UserInfoActivity" android:label="User Info"></activity>
        <activity android:name=".ProgressActivity" android:label="Progress" android:theme="@android:style/Theme.NoDisplay" android:excludeFromRecents="true" ></activity>
		<service android:name=".FileIOService" />
    </application>
</manifest>


text:
__author__ = 'rrusk'

import datetime
import pymongo

class MongoDatabase(object):
    DEFAULT_DB_NAME = "query_composer_development"

    ENDPOINTS_COLLECTION = "endpoints"
    QUERIES_COLLECTION = "queries"
    RESULTS_COLLECTION = "results"

    def __init__(self, db_name=DEFAULT_DB_NAME, host="localhost", port=27017):
        self._client = pymongo.MongoClient("mongodb://{host}:{port}".format(host=host, port=port))
        self._db = self._client[db_name]

    def _get_endpoints_collection(self):
        return self._db[self.ENDPOINTS_COLLECTION]

    def _get_queries_collection(self):
        return self._db[self.QUERIES_COLLECTION]

    def _get_results_collection(self):
        return self._db[self.RESULTS_COLLECTION]

    def get_endpoints(self):
        find_query = {}
        return list(self._get_endpoints_collection().find(find_query))

    def get_queries(self):
        find_query = {}
        return list(self._get_queries_collection().find(find_query))

    def get_results(self):
        find_query = {}
        return list(self._get_results_collection().find(find_query))

    def get_query(self, queryid):
        find_query = {'_id': queryid}
        return (list(self._get_queries_collection().find(find_query)))[0]

def select_result(execution_id, endpoint_id, results):
    for result in results:
        if result['execution_id'] == execution_id:
            if result['endpoint_id'] == endpoint_id:
                return result

def main():
    db = MongoDatabase()
    endpoints = db.get_endpoints()
    queries = db.get_queries()
    results = db.get_results()

    query_set = {}
    for query in queries:
        if (query['description'].startswith("STOPP Rule ") or query['description'].startswith("xSTOPP Rule ")) and \
                query['description'].endswith(' v2'):
            query_set[query['description']] = query['_id']
    query_desc = sorted(query_set)

    for desc in query_desc:  # want queries sorted by description
        queryid = query_set[desc]
        query = db.get_query(queryid)
        desc = query['description'].split()[2]
        print(desc + ':'),
        print(query['title'])
        executions = query['executions']
        for execution in executions:
            jstime = execution['time']
            dt = datetime.datetime.fromtimestamp(jstime)
            # if dt < datetime.datetime(2015, 2, 19, 12, 0, 0):
            if dt < datetime.datetime(2015, 4, 28, 10, 0, 0):
                continue
            # print "dt =", dt
            # print "date =", datetime.datetime(2015,2,19,12,0,0)
            execution_id = execution['_id']

            try:
                aggregate_result = execution['aggregate_result']
            except KeyError:
                continue
            if aggregate_result:
                keys = []
                reportline = "  "
                reportline += str(dt)
                reportline += " aggregate:"
                for key in aggregate_result:
                    reportline += ' ' + str(key) + ' ' + str(int(aggregate_result[key]))
                    keys.append(key)
                print(reportline)

                for endpoint in endpoints:
                    endpoint_id = endpoint['_id']
                    result = select_result(execution_id, endpoint_id, results)
                    if result:
                        reportline = '    ' + str(endpoint['name'])
                        try:
                            value = result['value']
                        except KeyError:
                            continue
                        for key in keys:
                            try:
                                reportline += ' ' + str(key) + ' ' + str(int(value[key]))
                            except KeyError:
                                continue
                        print(reportline)
        print("\n")

if __name__ == '__main__':
    main()


text:
namespace OneHourSport.Web.Models.Account
{
    using System.ComponentModel.DataAnnotations;
    using System.ComponentModel.DataAnnotations.Schema;
    using System.Web;

    public class RegisterViewModel
    {
        [Required]
        [EmailAddress]
        [Display(Name = "Email")]
        public string Email { get; set; }

        [Required]
        [StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)]
        [DataType(DataType.Password)]
        [Display(Name = "Password")]
        public string Password { get; set; }

        [DataType(DataType.Password)]
        [Display(Name = "Confirm password")]
        [Compare("Password", ErrorMessage = "The password and confirmation password do not match.")]
        public string ConfirmPassword { get; set; }

        [Required]
        [StringLength(50, ErrorMessage = "The {0} must be atleast {2} characters long.", MinimumLength = 2)]
        [Display(Name = "First name")]
        public string FirstName { get; set; }

        [Required]
        [StringLength(50, ErrorMessage = "The {0} must be atleast {2} characters long.", MinimumLength = 2)]
        [Display(Name = "Last name")]
        public string LastName { get; set; }

        [Required]
        [StringLength(9, ErrorMessage = "The Phone number must be exactly {2} characters long.", MinimumLength = 9)]
        [RegularExpression("^[0-9]*$", ErrorMessage = "Only diggits are alowed!")]
        [Display(Name = "Phone number: (+359)")]
        public string PhoneNumber { get; set; }

        [Required]
        [StringLength(50, ErrorMessage = "The {0} must be atleast {2} characters long.", MinimumLength = 5)]
        [Index(IsUnique = true)]
        [Display(Name = "Username")]
        public string UserName { get; set; }

        [Display(Name = "Have Complex?")]
        public bool IsComplex { get; set; }

        [Required]
        public HttpPostedFileBase ProfilePicture { get; set; }
    }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace OpenNLP.Tools.Util
{
    /// <summary>
    /// Just a single integer
    ///
    /// @author Kristina Toutanova (kristina@cs.stanford.edu)
    /// Code ...
    /// </summary>
    public class IntUni : IntTuple
    {
        public IntUni() : base(1)
        {
        }

        public IntUni(int src) : this()
        {
            elements[0] = src;
        }

        public int GetSource()
        {
            return elements[0];
        }

        public void SetSource(int src)
        {
            elements[0] = src;
        }

        public override IntTuple GetCopy()
        {
            var nT = new IntUni(elements[0]);
            return nT;
        }

        public void Add(int val)
        {
            elements[0] += val;
        }
    }
}


text:
from Cython.TestUtils import CythonTest
import Cython.Compiler.Errors as Errors
from Cython.Compiler.Nodes import *
from Cython.Compiler.ParseTreeTransforms import *
from Cython.Compiler.Buffer import *

class TestBufferParsing(CythonTest):
    # First, we only test the raw parser, i.e.
    # the number and contents of arguments are NOT checked.
    # However "dtype"/the first positional argument is special-cased
    #  to parse a type argument rather than an expression

    def parse(self, s):
        return self.should_not_fail(lambda: self.fragment(s)).root

    def not_parseable(self, expected_error, s):
        e = self.should_fail(lambda: self.fragment(s),  Errors.CompileError)
        self.assertEqual(expected_error, e.message_only)

    def test_basic(self):
        t = self.parse(u"cdef object[float, 4, ndim=2, foo=foo] x")
        bufnode = t.stats[0].base_type
        self.assert_(isinstance(bufnode, TemplatedTypeNode))
        self.assertEqual(2, len(bufnode.positional_args))
#        print bufnode.dump()
        # should put more here...

    def test_type_pos(self):
        self.parse(u"cdef object[short unsigned int, 3] x")

    def test_type_keyword(self):
        self.parse(u"cdef object[foo=foo, dtype=short unsigned int] x")

    def test_pos_after_key(self):
        self.not_parseable("Non-keyword arg following keyword arg",
                           u"cdef object[foo=1, 2] x")

# See also tests/error/e_bufaccess.pyx and tets/run/bufaccess.pyx
# THESE TESTS ARE NOW DISABLED, the code they test was pretty much
# refactored away
class TestBufferOptions(CythonTest):
    # Tests the full parsing of the options within the brackets

    def nonfatal_error(self, error):
        # We're passing self as context to transform to trap this
        self.error = error
        self.assert_(self.expect_error)

    def parse_opts(self, opts, expect_error=False):
        assert opts != ""
        s = u"def f():\n  cdef object[%s] x" % opts
        self.expect_error = expect_error
        root = self.fragment(s, pipeline=[NormalizeTree(self), PostParse(self)]).root
        if not expect_error:
            vardef = root.stats[0].body.stats[0]
            assert isinstance(vardef, CVarDefNode) # use normal assert as this is to validate the test code
            buftype = vardef.base_type
            self.assert_(isinstance(buftype, TemplatedTypeNode))
            self.assert_(isinstance(buftype.base_type_node, CSimpleBaseTypeNode))
            self.assertEqual(u"object", buftype.base_type_node.name)
            return buftype
        else:
            self.assert_(len(root.stats[0].body.stats) == 0)

    def non_parse(self, expected_err, opts):
        self.parse_opts(opts, expect_error=True)
#        e = self.should_fail(lambda: self.parse_opts(opts))
        self.assertEqual(expected_err, self.error.message_only)

    def __test_basic(self):
        buf = self.parse_opts(u"unsigned short int, 3")
        self.assert_(isinstance(buf.dtype_node, CSimpleBaseTypeNode))
        self.assert_(buf.dtype_node.signed == 0 and buf.dtype_node.longness == -1)
        self.assertEqual(3, buf.ndim)

    def __test_dict(self):
        buf = self.parse_opts(u"ndim=3, dtype=unsigned short int")
        self.assert_(isinstance(buf.dtype_node, CSimpleBaseTypeNode))
        self.assert_(buf.dtype_node.signed == 0 and buf.dtype_node.longness == -1)
        self.assertEqual(3, buf.ndim)

    def __test_ndim(self):
        self.parse_opts(u"int, 2")
        self.non_parse(ERR_BUF_NDIM, u"int, 'a'")
        self.non_parse(ERR_BUF_NDIM, u"int, -34")

    def __test_use_DEF(self):
        t = self.fragment(u"""
        DEF ndim = 3
        def f():
            cdef object[int, ndim] x
            cdef object[ndim=ndim, dtype=int] y
        """, pipeline=[NormalizeTree(self), PostParse(self)]).root
        stats = t.stats[0].body.stats
        self.assert_(stats[0].base_type.ndim == 3)
        self.assert_(stats[1].base_type.ndim == 3)

    # add exotic and impossible combinations as they come along...


text:
<?php

/**
 * Auto generated by MySQL Workbench Schema Exporter.
 * Version 2.1.6-dev (doctrine2-annotation) on 2016-02-25 22:56:30.
 * Goto https://github.com/johmue/mysql-workbench-schema-exporter for more
 * information.
 */

namespace ErpNET\App\Models\Doctrine\Entities;

use Doctrine\ORM\Mapping as ORM;
use Doctrine\Common\Collections\ArrayCollection;
use Gedmo\Mapping\Annotation as Gedmo;

/**
 * ErpNET\App\Models\Doctrine\Entities\ItemOrder
 *
 * @Gedmo\SoftDeleteable(fieldName="deletedAt", timeAware=false)
 * @ORM\Entity(repositoryClass="ItemOrderRepository")
 * @ORM\Table(name="item_orders", indexes={@ORM\Index(name="item_orders_mandante_index", columns={"mandante"}), @ORM\Index(name="item_orders_order_id_index", columns={"order_id"}), @ORM\Index(name="item_orders_cost_id_index", columns={"cost_id"}), @ORM\Index(name="item_orders_product_id_index", columns={"product_id"}), @ORM\Index(name="item_orders_currency_id_index", columns={"currency_id"}), @ORM\Index(name="item_orders_deleted_at_index", columns={"deleted_at"})})
 */
class ItemOrder extends EntityBase
{
    /**
     * @ORM\Id
     * @ORM\Column(type="integer", options={"unsigned":true})
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    protected $id;

    /**
     * @ORM\Column(type="string", length=255)
     */
    protected $mandante;

    /**
     * @ORM\Column(type="integer", nullable=true, options={"unsigned":true})
     */
    protected $order_id;

    /**
     * @ORM\Column(type="integer", nullable=true, options={"unsigned":true})
     */
    protected $cost_id;

    /**
     * @ORM\Column(type="integer", nullable=true, options={"unsigned":true})
     */
    protected $product_id;

    /**
     * @ORM\Column(type="integer", nullable=true, options={"unsigned":true})
     */
    protected $currency_id;

    /**
     * @ORM\Column(type="float", precision=8, scale=2)
     */
    protected $quantidade;

    /**
     * @ORM\Column(type="float", precision=8, scale=2)
     */
    protected $valor_unitario;

    /**
     * @ORM\Column(type="float", precision=8, scale=2, nullable=true)
     */
    protected $desconto_unitario;

    /**
     * @ORM\Column(type="text", nullable=true)
     */
    protected $descricao;

    /**
     * @ORM\OneToMany(targetEntity="ItemOrderSharedStat", mappedBy="itemOrder")
     * @ORM\JoinColumn(name="id", referencedColumnName="item_id", nullable=false)
     */
    protected $itemOrderSharedStats;

    /**
     * @ORM\ManyToOne(targetEntity="Order", inversedBy="itemOrders")
     * @ORM\JoinColumn(name="order_id", referencedColumnName="id")
     */
    protected $order;

    /**
     * @ORM\ManyToOne(targetEntity="CostAllocate", inversedBy="itemOrders")
     * @ORM\JoinColumn(name="cost_id", referencedColumnName="id")
     */
    protected $costAllocate;

    /**
     * @ORM\ManyToOne(targetEntity="Product", inversedBy="itemOrders")
     * @ORM\JoinColumn(name="product_id", referencedColumnName="id")
     */
    protected $product;

    /**
     * @ORM\ManyToOne(targetEntity="SharedCurrency", inversedBy="itemOrders")
     * @ORM\JoinColumn(name="currency_id", referencedColumnName="id")
     */
    protected $sharedCurrency;

    public function __construct()
    {
        $this->itemOrderSharedStats = new ArrayCollection();
    }

    /**
     * Set the value of id.
     *
     * @param integer $id
     * @return \ErpNET\App\Models\Doctrine\Entities\ItemOrder
     */
    public function setId($id)
    {
        $this->id = $id;

        return $this;
    }

    /**
     * Get the value of id.
     *
     * @return integer
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Set the value of mandante.
     *
     * @param string $mandante
     * @return \ErpNET\App\Models\Doctrine\Entities\ItemOrder
     */
    public function setMandante($mandante)
    {
        $this->mandante = $mandante;

        return $this;
    }

    /**
     * Get the value of mandante.
     *
     * @return string
     */
    public function getMandante()
    {
        return $this->mandante;
    }

    /**
     * Set the value of order_id.
     *
     * @param integer $order_id
     * @return \ErpNET\App\Models\Doctrine\Entities\ItemOrder
     */
    public function setOrderId($order_id)
    {
        $this->order_id = $order_id;

        return $this;
    }

    /**
     * Get the value of order_id.
     *
     * @return integer
     */
    public function getOrderId()
    {
        return $this->order_id;
    }

    /**
     * Set the value of cost_id.
     *
     * @param integer $cost_id
     * @return \ErpNET\App\Models\Doctrine\Entities\ItemOrder
     */
    public function setCostId($cost_id)
    {
        $this->cost_id = $cost_id;

        return $this;
    }

    /**
     * Get the value of cost_id.
     *
     * @return integer
     */
    public function getCostId()
    {
        return $this->cost_id;
    }

    /**
     * Set the value of product_id.
     *
     * @param integer $product_id
     * @return \ErpNET\App\Models\Doctrine\Entities\ItemOrder
     */
    public function setProductId($product_id)
    {
        $this->product_id = $product_id;

        return $this;
    }

    /**
     * Get the value of product_id.
     *
     * @return integer
     */
    public function getProductId()
    {
        return $this->product_id;
    }

    /**
     * Set the value of currency_id.
     *
     * @param integer $currency_id
     * @return \ErpNET\App\Models\Doctrine\Entities\ItemOrder
     */
    public function setCurrencyId($currency_id)
    {
        $this->currency_id = $currency_id;

        return $this;
    }

    /**
     * Get the value of currency_id.
     *
     * @return integer
     */
    public function getCurrencyId()
    {
        return $this->currency_id;
    }

    /**
     * Set the value of quantidade.
     *
     * @param float $quantidade
     * @return \ErpNET\App\Models\Doctrine\Entities\ItemOrder
     */
    public function setQuantidade($quantidade)
    {
        $this->quantidade = $quantidade;

        return $this;
    }

    /**
     * Get the value of quantidade.
     *
     * @return float
     */
    public function getQuantidade()
    {
        return $this->quantidade;
    }

    /**
     * Set the value of valor_unitario.
     *
     * @param float $valor_unitario
     * @return \ErpNET\App\Models\Doctrine\Entities\ItemOrder
     */
    public function setValorUnitario($valor_unitario)
    {
        $this->valor_unitario = $valor_unitario;

        return $this;
    }

    /**
     * Get the value of valor_unitario.
     *
     * @return float
     */
    public function getValorUnitario()
    {
        return $this->valor_unitario;
    }

    /**
     * Set the value of desconto_unitario.
     *
     * @param float $desconto_unitario
     * @return \ErpNET\App\Models\Doctrine\Entities\ItemOrder
     */
    public function setDescontoUnitario($desconto_unitario)
    {
        $this->desconto_unitario = $desconto_unitario;

        return $this;
    }

    /**
     * Get the value of desconto_unitario.
     *
     * @return float
     */
    public function getDescontoUnitario()
    {
        return $this->desconto_unitario;
    }

    /**
     * Set the value of descricao.
     *
     * @param string $descricao
     * @return \ErpNET\App\Models\Doctrine\Entities\ItemOrder
     */
    public function setDescricao($descricao)
    {
        $this->descricao = $descricao;

        return $this;
    }

    /**
     * Get the value of descricao.
     *
     * @return string
     */
    public function getDescricao()
    {
        return $this->descricao;
    }

    /**
     * Add ItemOrderSharedStat entity to collection (one to many).
     *
     * @param \ErpNET\App\Models\Doctrine\Entities\ItemOrderSharedStat $itemOrderSharedStat
     * @return \ErpNET\App\Models\Doctrine\Entities\ItemOrder
     */
    public function addItemOrderSharedStat(ItemOrderSharedStat $itemOrderSharedStat)
    {
        $this->itemOrderSharedStats[] = $itemOrderSharedStat;

        return $this;
    }

    /**
     * Remove ItemOrderSharedStat entity from collection (one to many).
     *
     * @param \ErpNET\App\Models\Doctrine\Entities\ItemOrderSharedStat $itemOrderSharedStat
     * @return \ErpNET\App\Models\Doctrine\Entities\ItemOrder
     */
    public function removeItemOrderSharedStat(ItemOrderSharedStat $itemOrderSharedStat)
    {
        $this->itemOrderSharedStats->removeElement($itemOrderSharedStat);

        return $this;
    }

    /**
     * Get ItemOrderSharedStat entity collection (one to many).
     *
     * @return \Doctrine\Common\Collections\Collection
     */
    public function getItemOrderSharedStats()
    {
        return $this->itemOrderSharedStats;
    }

    /**
     * Set Order entity (many to one).
     *
     * @param \ErpNET\App\Models\Doctrine\Entities\Order $order
     * @return \ErpNET\App\Models\Doctrine\Entities\ItemOrder
     */
    public function setOrder(Order $order = null)
    {
        $this->order = $order;

        return $this;
    }

    /**
     * Get Order entity (many to one).
     *
     * @return \ErpNET\App\Models\Doctrine\Entities\Order
     */
    public function getOrder()
    {
        return $this->order;
    }

    /**
     * Set CostAllocate entity (many to one).
     *
     * @param \ErpNET\App\Models\Doctrine\Entities\CostAllocate $costAllocate
     * @return \ErpNET\App\Models\Doctrine\Entities\ItemOrder
     */
    public function setCostAllocate(CostAllocate $costAllocate = null)
    {
        $this->costAllocate = $costAllocate;

        return $this;
    }

    /**
     * Get CostAllocate entity (many to one).
     *
     * @return \ErpNET\App\Models\Doctrine\Entities\CostAllocate
     */
    public function getCostAllocate()
    {
        return $this->costAllocate;
    }

    /**
     * Set Product entity (many to one).
     *
     * @param \ErpNET\App\Models\Doctrine\Entities\Product $product
     * @return \ErpNET\App\Models\Doctrine\Entities\ItemOrder
     */
    public function setProduct(Product $product = null)
    {
        $this->product = $product;

        return $this;
    }

    /**
     * Get Product entity (many to one).
     *
     * @return \ErpNET\App\Models\Doctrine\Entities\Product
     */
    public function getProduct()
    {
        return $this->product;
    }

    /**
     * Set SharedCurrency entity (many to one).
     *
     * @param \ErpNET\App\Models\Doctrine\Entities\SharedCurrency $sharedCurrency
     * @return \ErpNET\App\Models\Doctrine\Entities\ItemOrder
     */
    public function setSharedCurrency(SharedCurrency $sharedCurrency = null)
    {
        $this->sharedCurrency = $sharedCurrency;

        return $this;
    }

    /**
     * Get SharedCurrency entity (many to one).
     *
     * @return \ErpNET\App\Models\Doctrine\Entities\SharedCurrency
     */
    public function getSharedCurrency()
    {
        return $this->sharedCurrency;
    }

    public function __sleep()
    {
        return array('id', 'created_at', 'updated_at', 'deleted_at', 'mandante', 'order_id', 'cost_id', 'product_id', 'currency_id', 'quantidade', 'valor_unitario', 'desconto_unitario', 'descricao');
    }
}


text:
use std::any::{ Any };
use std::boxed::BoxAny;
use typedef::TypeDef;
use { Factory, Getter };

/// Proxy for initializing aggregate factory without caring about the type used.
///
/// Its intended use is as a container of factories that produce a
/// value of the same type. Then it can itself be used to create a new factory
/// that aggregates values from all its childs and returns all of them
/// in a `Vec<T>` type for single `take`.
///
/// The most convenient way to initialize a new aggregate is to use
/// `new_aggregate` method on a metafactory. It will make a correctly typed
/// aggregate based on the metafactory type.
///
/// ```
/// # extern crate metafactory;
/// use metafactory::{ metafactory, AsFactoryExt };
///
/// fn main() {
///     let true_metafactory = metafactory(|| true);
///     let false_metafactory = metafactory(|| false);
///
///     // Use any of metafactories to create an aggregate for bool.
///     let mut aggregate = false_metafactory.new_aggregate();
///
///     // We can then add both factories to the aggregate.
///     // and make a factory from aggregate.
///     let true_and_false = aggregate
///         .new_factory(vec![
///             true_metafactory.new(Vec::new()).ok().unwrap(),
///             false_metafactory.new(Vec::new()).ok().unwrap(),
///         ])
///         .as_factory_of::<Vec<bool>>().unwrap();
///
///     assert_eq!(vec![true, false], true_and_false.take());
/// }
/// ```
///
/// The example bellow show how to initialize and use aggregate without a
/// metafactory.
///
/// ```
/// # extern crate metafactory;
/// use std::any::Any;
/// use metafactory::{ metafactory, argless_as_factory, AsFactoryExt };
/// use metafactory::aggregate::Aggregate;
///
/// fn main() {
///     // Let's say we know that we will have bunch of `bool` factories.
///     // In that case we create a new aggregate for them:
///     let mut aggregate = Aggregate::new::<bool>();
///
///     // Once we actually have our factories, we can inject them into aggregate
///     // without dealing with types. Of course, we should make sure that types
///     // actually match before doing that in the code that is using this
///     // implementation.
///     // Then we can call `new_factory` to convert all dynamic stuff to
///     // statically constructed call hierarchy:
///     let anyed_bool_array_factory = aggregate
///         .new_factory(vec![
///             argless_as_factory(|| true),
///             argless_as_factory(true),
///             argless_as_factory(|| 4i == 8),
///         ]);
///
///     // Of course, that returns it anyed (`Box<Any>`), but we can easily get un-anyed version
///     // by downcasting to `Factory<Vec<bool>>` or using a convenience extension
///     // method for that:
///     let bool_array_factory = anyed_bool_array_factory
///         .as_factory_of::<Vec<bool>>().unwrap();
///
///     // Calling it should produce expected boolean vector:
///     assert_eq!(bool_array_factory.take(), vec![true, true, false]);
///
///     // Of course, the aggregate itself should be usable as argument
///     // for other factories:
///     let metafactory_all_true = metafactory(|values: Vec<bool>| {
///         values.iter().fold(true, |a, &i| a & i)
///     });
///
///     // We can pass it when constructing a factory for this lambda metafactory:
///     let factory_all_true = metafactory_all_true.new(vec![
///         box bool_array_factory.clone() as Box<Any>
///     ])
///         .ok().unwrap() // check for errors here
///         .as_factory_of::<bool>().unwrap() // same story with downcasting
///     ;
///
///     assert_eq!(factory_all_true.take(), false); // not all values are true
/// }
/// ```
pub struct Aggregate<'a> {
    typedef: TypeDef,
    container_typedef: TypeDef,
    do_new: Box<Fn<(Vec<Box<Any>>,),Box<Any>> + 'a>,
}

impl<'a> Aggregate<'a> {
    /// Create new aggregate instance for specified type.
    pub fn new<T: 'static>() -> Aggregate<'a> {
        Aggregate {
            typedef: TypeDef::of::<T>(),
            container_typedef: TypeDef::of::<Vec<T>>(),
            do_new: box |&: items: Vec<Box<Any>>| {
                box Factory::<Vec<T>>::new(
                    box AG::<T>::new(
                        items.into_iter()
                            .map(|i| *i.downcast::<Factory<T>>().ok().expect(
                                format!("failed to downcast factory child to Factory<{}>", TypeDef::name_of::<T>()).as_slice()
                            ))
                            .collect()
                    )
                )
            }
        }
    }

    /// Return aggregated type.
    pub fn get_arg_type(&self) -> TypeDef {
        self.typedef.clone()
    }

    /// Return container type.
    pub fn get_container_type(&self) -> TypeDef {
        self.container_typedef.clone()
    }

    /// Produces factory usable as argument for other factories.
    ///
    /// If inner factories make `int` values, this method will make factory
    /// that makes `Vec<int>` values.
    pub fn new_factory(&self, items: Vec<Box<Any>>) -> Box<Any> {
        (self.do_new).call((items,))
    }
}

struct AG<T: 'static> {
    factories: Vec<Factory<T>>,
}

impl<T> Clone for AG<T> {
    fn clone(&self) -> AG<T> {
        AG::<T> {
            factories: self.factories.clone()
        }
    }
}

impl<T> AG<T> {
    pub fn new(factories: Vec<Factory<T>>) -> AG<T> {
        AG::<T> {
            factories: factories
        }
    }
}

impl<T> Getter<Vec<T>> for AG<T> {
    fn take(&self) -> Vec<T> {

        // Reserve exact result size.
        let mut items = Vec::<T>::with_capacity(self.factories.len());

        // Construct results from factory results.
        items.extend(
            self.factories.iter()
                .map(|f| f.take())
        );

        items
    }

    fn boxed_clone(&self) -> Box<Getter<Vec<T>> + 'static> {
        box self.clone()
    }
}

#[cfg(test)]
mod test {
    use { argless_as_factory, metafactory, AsFactoryExt };
    use super::{ Aggregate };

    #[test]
    fn should_be_usable_as_vec_of_types() {
        let container = Aggregate::new::<int>();

        let parent_metafactory = metafactory(
            |items: Vec<int>|
                items.into_iter()
                    .map(|i| format!("{}", i))
                    .collect::<Vec<String>>()
                    .connect(", ")
        );

        let parent_getter = parent_metafactory
            .new(vec![
                container.new_factory(
                    vec![
                        argless_as_factory(5i),
                        argless_as_factory(13i)
                    ]
                )
            ]).ok().unwrap()
            .as_factory_of::<String>().unwrap()
        ;

        assert_eq!(parent_getter.take(), "5, 13");
    }
}


text:
/* @flow strict */

import React, { type Node } from 'react';
import PropTypes from 'prop-types';

// TODO: close button is not really only a close button, we should rename and update the import here
import { BpkButtonLink } from '../../bpk-component-link';
import { cssModules } from '../../bpk-react-utils';

import STYLES from './BpkNavigationBarButtonLink.module.scss';

const getClassName = cssModules(STYLES);

export type Props = {
  children: Node,
  onClick: (event: SyntheticEvent<>) => void,
  className: ?string,
};

const BpkNavigationBarButtonLink = ({
  children,
  className,
  ...rest
}: Props) => (
  // $FlowFixMe[cannot-spread-inexact] - inexact rest. See 'decisions/flowfixme.md'.
  <BpkButtonLink
    className={getClassName('bpk-navigation-bar-button-link', className)}
    {...rest}
  >
    {children}
  </BpkButtonLink>
);

BpkNavigationBarButtonLink.propTypes = {
  children: PropTypes.node.isRequired,
  onClick: PropTypes.func.isRequired,
  className: PropTypes.string,
};

BpkNavigationBarButtonLink.defaultProps = {
  className: null,
};

export default BpkNavigationBarButtonLink;


text:
   Tweet

   Like

   +1


text:
package com.microsoft.bingads.api.test.entities.ad_extension.site_link.write;

import org.junit.runner.RunWith;
import org.junit.runners.Suite;
import org.junit.runners.Suite.SuiteClasses;

@RunWith(Suite.class)
@SuiteClasses({BulkSiteLinkAdExtensionWriteToStreamTest.class})
public class BulkSiteLinkAdExtensionWriteTests {

}


text:
package org.springframework.cloud.zookeeper.discovery;

import org.junit.Test;
import org.junit.runner.RunWith;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.cloud.zookeeper.discovery.test.CommonTestConfig;
import org.springframework.cloud.zookeeper.serviceregistry.ZookeeperRegistration;
import org.springframework.cloud.zookeeper.test.ZookeeperTestingServer;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.context.annotation.Profile;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringRunner;

import static org.assertj.core.api.BDDAssertions.then;
import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.RANDOM_PORT;

/**
 * @author Marcin Grzejszczak
 */
@RunWith(SpringRunner.class)
@SpringBootTest(classes = ZookeeperDiscoverySecurePortTests.Config.class, properties = {
		"feign.hystrix.enabled=false",
		"spring.cloud.zookeeper.discovery.uriSpec={scheme}://{address}:{port}/contextPath",
		"spring.cloud.zookeeper.discovery.instance-ssl-port=8443" }, webEnvironment = RANDOM_PORT)
@ActiveProfiles("loadbalancer")
@DirtiesContext
@ContextConfiguration(loader = ZookeeperTestingServer.Loader.class)
public class ZookeeperDiscoverySecurePortTests {

	@Autowired
	private LoadBalancerClient loadBalancerClient;

	@Autowired
	private ZookeeperRegistration zookeeperRegistration;

	@Value("${spring.application.name}")
	private String springAppName;

	@Test
	public void isSecureIsTrue() {
		ServiceInstance instance = this.loadBalancerClient.choose(this.springAppName);
		then(instance.isSecure()).isTrue();
	}

	@Test
	public void shouldSetServiceInstanceSslPort() {
		then(this.zookeeperRegistration.getServiceInstance().getSslPort())
				.isEqualTo(8443);
	}

	@Configuration
	@EnableAutoConfiguration
	@Import(CommonTestConfig.class)
	@Profile("loadbalancer")
	static class Config {

	}

}


text:
#include "LineIterator.h"
#include "../Matrix.h"
#include "../types/Point.h"

namespace lineiterator_general_callback {
	std::shared_ptr<overload_resolution> overload;
	NAN_METHOD(callback) {
		if (overload == nullptr) {
			throw std::runtime_error("lineiterator_general_callback is empty");
		}
		return overload->execute("lineiterator", info);
	}
}

Nan::Persistent<FunctionTemplate> LineIterator::constructor;

std::string LineIterator::name;

void
LineIterator::Init(Handle<Object> target, std::shared_ptr<overload_resolution> overload) {
	lineiterator_general_callback::overload = overload;
	Local<FunctionTemplate> ctor = Nan::New<FunctionTemplate>(lineiterator_general_callback::callback);
	constructor.Reset(ctor);
	auto itpl = ctor->InstanceTemplate();
	itpl->SetInternalFieldCount(1);
	ctor->SetClassName(Nan::New("LineIterator").ToLocalChecked());

	overload->register_type<LineIterator>(ctor, "lineiterator", "LineIterator");

	//   /** @brief Line iterator
//
//    The class is used to iterate over all the pixels on the raster line
//    segment connecting two specified points.
//
//    The class LineIterator is used to get each pixel of a raster line. It
//    can be treated as versatile implementation of the Bresenham algorithm
//    where you can stop at each pixel and do some extra processing, for
//    example, grab pixel values along the line or draw a line with an effect
//    (for example, with XOR operation).
//
//    The number of pixels along the line is stored in LineIterator::count.
//    The method LineIterator::pos returns the current position in the image:
//
//    @code{.cpp}
//    // grabs pixels along the line (pt1, pt2)
//    // from 8-bit 3-channel image to the buffer
//    LineIterator it(img, pt1, pt2, 8);
//    LineIterator it2 = it;
//    vector<Vec3b> buf(it.count);
//
//    for(int i = 0; i < it.count; i++, ++it)
//        buf[i] = *(const Vec3b)*it;
//
//    // alternative way of iterating through the line
//    for(int i = 0; i < it2.count; i++, ++it2)
//    {
//        Vec3b val = img.at<Vec3b>(it2.pos());
//        CV_Assert(buf[i] == val);
//    }
//    @endcode
//    */
//    //class CV_EXPORTS LineIterator
//interface LineIteratorStatic {
//           /** @brief intializes the iterator
//
//            creates iterators for the line connecting pt1 and pt2
//            the line will be clipped on the image boundaries
//            the line is 8-connected or 4-connected
//            If leftToRight=true, then the iteration is always done
//            from the left-most point to the right most,
//            not to depend on the ordering of pt1 and pt2 parameters
//            */
//    new (img: _mat.Mat , pt1: _types.Point, pt2: _types.Point,
//        connectivity?: _st.int /* = 8*/, leftToRight?  : boolean /*= false*/): LineIterator;
	overload->addOverloadConstructor("lineiterator", "LineIterator", {
		make_param<Matrix*>("img","Mat") ,
		make_param<Point*>("pt1",Point::name),
		make_param<Point*>("pt2",Point::name),
		make_param<int>("connectivity","int", 8),
		make_param<bool>("leftToRight","bool", false)
	},New_pt );
//
//}
//interface LineIterator
//    {
////        public:
////        /** @brief returns pointer to the current pixel
////        */
////        uchar * operator * ();
////        /** @brief prefix increment operator (++it). shifts iterator to the next pixel
////        */
////        LineIterator & operator++();
////        /** @brief postfix increment operator (it++). shifts iterator to the next pixel
////        */
////        LineIterator operator ++(int);
////        /** @brief returns coordinates of the current pixel
////        */
////        Point pos() const;
//    each(cb : (pos: _types.Point) => void);
	overload->addOverload("lineiterator", "LineIterator", "each", {make_param<std::shared_ptr<overres::Callback>>("cb","Function")}, each);
////
////        uchar * ptr;
////        const uchar* ptr0;
////        int step, elemSize;
////        int err, count;
////        int minusDelta, plusDelta;
////        int minusStep, plusStep;
//};
//
//export var LineIterator: LineIteratorStatic = alvision_module.LineIterator;
//
//    //! @cond IGNORED
//
//    // === LineIterator implementation ===
//
////    inline
////    uchar * LineIterator::operator * ()
////    {
////        return ptr;
////    }
////
////    inline
////    LineIterator & LineIterator::operator++()
////{
////        int mask = err < 0 ? -1 : 0;
////        err += minusDelta + (plusDelta & mask);
////        ptr += minusStep + (plusStep & mask);
////        return *this;
////    }
////
////    inline
////    LineIterator LineIterator::operator++(int)
////{
////        LineIterator it = *this;
////        ++(*this);
////        return it;
////    }
////
////    inline
////    Point LineIterator::pos() const
////        {
////            Point p;
////    p.y = (int)((ptr - ptr0) / step);
////    p.x = (int)(((ptr - ptr0) - p.y * step) / elemSize);
////    return p;
////}
//
////! @endcond
//
////! @} imgproc_draw
//
////! @} imgproc
//
////} // cv
//
////#ifndef DISABLE_OPENCV_24_COMPATIBILITY
////#include "opencv2/imgproc/imgproc_c.h"
////#endif
//
////#endif

target->Set(Nan::New("LineIterator").ToLocalChecked(), ctor->GetFunction());

}

v8::Local<v8::Function> LineIterator::get_constructor() {
	assert(!constructor.IsEmpty() && "constructor is empty");
	return Nan::New(constructor)->GetFunction();
}

POLY_METHOD(LineIterator::New_pt){throw std::runtime_error("not implemented");}
POLY_METHOD(LineIterator::each){throw std::runtime_error("not implemented");}


text:
Legacy Guide
==============================================================================

This document describes the use of Ember Mocha with Ember's legacy testing
APIs, which have been superseded by the newer testing system based on the RFCs
[232](https://github.com/emberjs/rfcs/blob/master/text/0232-simplify-qunit-testing-api.md)
and
[268](https://github.com/emberjs/rfcs/blob/master/text/0268-acceptance-testing-refactor.md).

Usage
------------------------------------------------------------------------------

### Setting the Resolver

You'll typically want to set a single resolver for your test suite:

```javascript
import resolver from './helpers/resolver';
import { setResolver } from 'ember-mocha';

setResolver(resolver);
```

If you want to use multiple resolvers in your test suite, you can also
call `setResolver` in the `beforeSetup` callback of your test modules.

### Setup Tests

The `setupTest` function can be used to setup a unit test for any kind
of "module/unit" of your application that can be looked up in a container.

For example, the following is a unit test for the `SidebarController`:

```javascript
import { describe, it } from 'mocha';
import { setupTest } from 'ember-mocha';

describe('SidebarController', function() {
  setupTest('controller:sidebar', {
    // Specify the other units that are required for this test.
    // needs: ['controller:foo']
  });

  // Replace this with your real tests.
  it('exists', function() {
    var controller = this.subject();
    expect(controller).to.be.ok;
  });
});

```

The subject is specified as `controller:sidebar`, which is the key that will
be used to look up this controller in the isolated container that will be
created for this test.

#### Setup Component Tests

The `setupComponentTest` function is specifically designed to test components
and provides additional `render` and `$` helpers within a test's context.

```javascript
import { describe, it } from 'mocha';
import { setupComponentTest } from 'ember-mocha';

describe('GravatarImageComponent', function() {
  setupComponentTest('gravatar-image', {
    // specify the other units that are required for this test
    // needs: ['component:foo', 'helper:bar']
  });

  it('renders', function() {
    // creates the component instance
    var component = this.subject();
    expect(component._state).to.equal('preRender');

    // renders the component on the page
    this.render();
    expect(component._state).to.equal('inDOM');
  });
});
```

#### Setup Model Tests

The `setupModelTest` function can be used to test Ember Data models and
provides an additional `store` helper within a test's context.

```javascript
import { describe, it } from 'mocha';
import { setupModelTest } from 'ember-mocha';

describe('Contact', function() {
  setupModelTest('contact', {
    // Specify the other units that are required for this test.
    needs: []
  });

  // Replace this with your real tests.
  it('exists', function() {
    var model = this.subject();
    // var store = this.store();
    expect(model).to.be.ok;
  });
});
```

### Acceptance Tests

The `setupAcceptanceTest` function can be used to run acceptance
tests as the name suggests. It will automatically setup an
application instance for you, which is provided at `this.application`.

```javascript
import Ember from 'ember';
import { describe, it } from 'mocha';
import { setupAcceptanceTest } from 'ember-mocha';

var Application = Ember.Application.extend({
  rootElement: '#ember-testing',
});

describe('basic acceptance test', function() {
  setupAcceptanceTest({ Application });

  it('can visit /', function() {
    visit('/');

    andThen(() => {
      expect(currentURL()).to.equal('/');
    });
  });
});
```

#### Using `async/await`

In case your project supports the `async/await` feature of ES2016 you can
simplify the test function to this:

```js
it('can visit /', async function() {
  await visit('/');
  expect(currentURL()).to.equal('/');
});
```

- add the `async` keyword in front of the test `function`
- add `await` in front of all async test helper calls
- remove the `andThen()` wrappers


text:
import pytest

from dictfile.api import parser
from dictfile.api import exceptions
from dictfile.tests.resources import get_resource
from dictfile.api import constants

@pytest.mark.parametrize("resource,fmt,expected", [

    ("test_load_properties.properties", constants.PROPERTIES, {
        'key1': 'value1',
        'key2': 'value2',
        'key3': 'value3    ',
        'key4': 'first, second, third'
    }),

    ("test_load_json.json", constants.JSON, {
        'key1': 'value1',
        '   key2': '  value2  '
    }),

    ("test_load_yaml.yaml", constants.YAML, {
        'key1': 'value1',
        'key2': {
            'a': 'test1',
            'b': 'test2'
        }
    }),

    ("test_load_ini.ini", constants.INI, {
        'section1': {
            'key1': 'value1',
            'key2': 'value2'
        },
        'section2': {
            'key3': 'value3'
        }
    })

])
def test_load(resource, fmt, expected):

    actual = parser.load(file_path=get_resource(resource), fmt=fmt)

    assert expected == actual

@pytest.mark.parametrize("resource,fmt,expected", [

    ("test_load_properties.properties", constants.PROPERTIES, {
        'key1': 'value1',
        'key2': 'value2',
        'key3': 'value3    ',
        'key4': 'first, second, third'
    }),

    ("test_load_json.json", constants.JSON, {
        'key1': 'value1',
        '   key2': '  value2  '
    }),

    ("test_load_yaml.yaml", constants.YAML, {
        'key1': 'value1',
        'key2': {
            'a': 'test1',
            'b': 'test2'
        }
    }),

    ("test_load_ini.ini", constants.INI, {
        'section1': {
            'key1': 'value1',
            'key2': 'value2'
        },
        'section2': {
            'key3': 'value3'
        }
    })

])
def test_loads(resource, fmt, expected):

    with open(get_resource(resource)) as stream:
        string = stream.read()

    actual = parser.loads(string=string, fmt=fmt)

    assert expected == actual

# pylint: disable=fixme
# TODO figure out how to validate a properties file
# TODO seems like every string is acceptable
@pytest.mark.parametrize("fmt", [constants.JSON, constants.YAML, constants.INI])
def test_corrupt_file(fmt):

    with pytest.raises(exceptions.CorruptFileException):
        parser.load(get_resource('test_corrupt_file'), fmt=fmt)

def test_load_unsupported_format(temp_file):

    with pytest.raises(exceptions.UnsupportedFormatException):
        parser.load(file_path=temp_file, fmt='unsupported')

def test_loads_unsupported_format():

    with pytest.raises(exceptions.UnsupportedFormatException):
        parser.loads(string='dummy', fmt='unsupported')