text:
#include <stdio.h>
#include <cstdlib>
#include <sstream>
#include <iostream>
#include <list>
#include <vector>
#include <memory>
#include <string>
#include <cstring>
#include <string.h>

#include "loki/TypeManip.h"
#include "loki/TypeTraits.h"

//#include "sqlite/sqlite3.h"
#include "sqlite3_wrapper.h"
#include "sqlite_exceptions.h"

#ifndef SQLITE_STRING_PROCESSOR_BASE_H
#define SQLITE_STRING_PROCESSOR_BASE_H

/// @defgroup SQLiteStringProcesor Generator of SQLite Query
/// @{

/*! @class AddBlockToString
 *  @brief helper to add a block into string
 */
class AddBlockToString{
    std::string& m_string;
    std::string m_blockClose;
public:
    /*! @brief constructor
    *   @param i_blockOpen in symbol which opens the block
    *   @param i_blockClose in symbol which closes the block
    *   @param i_string in a string which will be increased the block
     */
    AddBlockToString(const std::string& i_blockOpen, const std::string& i_blockClose, std::string& i_string)
    : m_string(i_string)
    , m_blockClose(i_blockClose){
        m_string += i_blockOpen;
    }
    ~AddBlockToString(){
        m_string += m_blockClose;
    }
};

/*! @fn inline std::string makeBlock(const std::string& i_dst,
            const std::string& i_blockOpen,
            const std::string& i_blockClose)
 *  @brief wrap a string into block symbols
 *  @param i_dst in a string which will be wrapped
 *  @param i_blockOpen in symbol which opens the block
 *  @param i_blockClose in symbol which closes the block
 *  @return wrapped string.
 */
inline std::string makeBlock(const std::string& i_dst,
        const std::string& i_blockOpen, const std::string& i_blockClose){
    if(i_dst == ""){
        return "";
    }
    std::string rez;
    {
        AddBlockToString block(i_blockOpen, i_blockClose, rez);
        rez += i_dst;
    }
    return rez;
}

/*! @fn inline std::string makeBrecetBlock(const std::string& i_dst)
 *  @brief wrap a string into brecets
 *  @param i_dst in a string which will be wrapped
 *  @return wrapped string.
 */
inline std::string makeBrecetBlock(const std::string& i_dst){
    return makeBlock(i_dst, "(", ")");
}

/*! @fn inline std::string makeSquareBrecetBlock(const std::string& i_dst)
 *  @brief wrap a string into square brecets
 *  @param i_dst in a string which will be wrapped
 *  @return wrapped string.
 */
inline std::string makeSquareBrecetBlock(const std::string& i_dst){
    return makeBlock(i_dst, "[", "]");
}

/*! @fn inline std::string makeSpaceBlock(const std::string& i_dst)
 *  @brief wrap a string into space
 *  @param i_dst in a string which will be wrapped
 *  @return wrapped string.
 */
inline std::string makeSpaceBlock(const std::string& i_dst){
    return makeBlock(i_dst, " ", " ");
}

/// @defgroup ToString Functions get string for different data
/// @ingroup SQLiteStringProcesor
/// @{
/*! @fn template<class T>
        static std::string toString(const T& i_data)
 *  @brief definition template to get a string serialization from a data
 *  @param i_data in a data
 *  @return string serialization
 */
template<class T>
static std::string toString(const T& i_data);
/// @}
/*! @class SQLiteStringProcessorBase
 *  @brief contains string constant and string process function to form SQLite queries
 */
class SQLiteStringProcessorBase{
    /*! @brief see definition of toString before
     *  @note friend definition to use protected helper function
     */
    template<class T>
    friend
    std::string toString(const T& i_data);

public:
    /// @defgroup SQLiteStringConstatnt SQLite string constants
    /// @ingroup SQLiteStringProcesor
    /// @{
    static const std::string CREATE_TABLE;
    static const std::string CREATE;
    static const std::string ALERT_TABLE;
    static const std::string INSERT;
    static const std::string SELECT;
    static const std::string UPDATE;
    static const std::string FROM;
    static const std::string WHERE;
    static const std::string GROUP_BY;
    static const std::string HAVING;
    static const std::string ORDER_BY;
    static const std::string LIMIT;
    static const std::string OFFSET;
    static const std::string SET;
    static const std::string DELETE_;
    static const std::string DROP_TABLE;
    static const std::string DROP;
    static const std::string JOIN;
    static const std::string USING;
    static const std::string INDEX;

    static const std::string IF_NOT_EXISTS;
    static const std::string DEFAULT;
    static const std::string VALUES;
    static const std::string AUTOINCREMENT;
    static const std::string UNIQUE;
    static const std::string PRIMARY_KEY;
    static const std::string FOREIGN_KEY;
    static const std::string REFERENCES;

    static const std::string INTO;
    static const std::string OR;
    static const std::string ROLLBACK;
    static const std::string ABORT;
    static const std::string REPLACE;
    static const std::string FAIL;
    static const std::string _IGNORE;

    static const std::string BLOB;
    static const std::string TEXT;
    static const std::string INTEGER;
    static const std::string REAL;

    static const std::string SPACE;
    static const std::string COMMA;
    static const std::string SEMICOLON;
    static const std::string BRECET_OPEN;

    static const std::string CROSS;
    static const std::string INNER;
    static const std::string ON;
    static const std::string NATURAL;
    static const std::string LEFT;
    static const std::string RIGHT;
    /// @}

    /// @addtogroup ToString
    /// @{
    /*! @brief get string type name in SQLite format
     *  @param i_data in a data which type is asked
     *  @return string name of type in SQLite format
     *  @note any type which couldn't resolved in SQLite type will be typed as BLOB
     */
    template<class T>
    static std::string getSQLiteTypeDataName(const T& i_data){
        return SQLiteStringProcessorBase::getSQLiteTypeDataName(
                Loki::Int2Type<Loki::TypeTraits<T>::isFundamental >(), i_data);
    }

    /*! @brief get string with blob data in Hex format
     *  @param i_data in a pointer to blob data
     *  @param i_size in size of the blob
     *  @return a string which contains hex format of the blob
     *  @note we aren't allowed to work with isn't alignment data
     */
    static std::string Hex2String(const char* i_data, size_t i_size){
        //if(i_size  % sizeof(int) == 0){
        return Hex2String(Loki::Int2Type<1>(), reinterpret_cast<const unsigned char*>(i_data),
                i_size);
        /*}
        assert(0);
        return std::string();*/
    }

    /*! @brief get pointer to blob data  from string in Hex format of the data
     *  @param i_data in a pointer the string
     *  @param i_size in size of the string
     *  @return a pair there is first is pointer to the blob
     *          second is a size of the blob
     */
    static std::pair<char*, size_t> HexString2Blob(const char* i_data, size_t i_size){
        //if(i_size  % sizeof(int) == 0){
            char* rez = new char[i_size >> 1];
            char data[] = "0xff";
            char* dstIterator = rez;
            const char* srcIterator = i_data;
            for(unsigned int i = 0; i < (i_size  >> 1) ; ++i){
                memcpy(data + 2, srcIterator, sizeof(char) << 1);
                int transformedData =  strtol(data, NULL, 16);
                memcpy(dstIterator, &transformedData, sizeof(char));
                dstIterator += sizeof(char);
                srcIterator += sizeof(char) << 1;
            }
            return std::make_pair(rez, i_size >> 1);
        //}
        //assert(0);
        //return std::make_pair<char *, size_t>(NULL, 0);
    }
    /// @}
private:
    /// @defgroup SQLiteStringTYPE The functions get SQLite type name
    /// @ingroup SQLiteStringProcesor
    /// @{
    static std::string getSQLiteTypeDataName(Loki::Int2Type<0> isFundamental, const std::string&){
        return TEXT;
    }
    static std::string getSQLiteTypeDataName(Loki::Int2Type<1> isFundamental, const char*){
        return TEXT;
    }
    static std::string getSQLiteTypeDataName(Loki::Int2Type<1> isFundamental, const int&){
        return INTEGER;
    }
    static std::string getSQLiteTypeDataName(Loki::Int2Type<1> isFundamental, const long&){
        return INTEGER;
    }
    static std::string getSQLiteTypeDataName(Loki::Int2Type<1> isFundamental, const long long&){
        return INTEGER;
    }
    static std::string getSQLiteTypeDataName(Loki::Int2Type<1> isFundamental, const double&){
        return REAL;
    }
    template<class T>
    static std::string getSQLiteTypeDataName(Loki::Int2Type<0> noFundamental, const T&){
        return BLOB;
    }
    /// @}

    /// @addtogroup ToString
    /// @{
     static std::string toString(Loki::Int2Type<0> isFundamental, const std::string& i_data){
        return i_data;
    }

    static std::string toString(Loki::Int2Type<1> isFundamental, const char* i_data){
        return std::string(i_data);
    }

    static std::string toString(Loki::Int2Type<1> isFundamental, const char& i_data){
		std::ostringstream buff;
		buff.setf(std::ios_base::dec, std::ios_base::basefield);
        buff<<(int)i_data;
        return buff.str();
    }

    template<typename Fundamental>
    static std::string toString(Loki::Int2Type<1> isFundamental, const Fundamental& i_data){
        std::ostringstream buff;
        buff.setf(std::ios_base::dec, std::ios_base::basefield);
        buff.setf(std::ios_base::fixed, std::ios_base::floatfield);
        buff.precision(6);

        buff<<i_data;
        return buff.str();
    }

    template<class T>
    static std::string toString(Loki::Int2Type<0> noFundamental, const T& i_data){
         //std::string blob;
        const unsigned char* data = reinterpret_cast<const unsigned char*>(&i_data);
        return makeBlock(
                Hex2String(Loki::Int2Type<sizeof(T) % sizeof(*data) == 0>(), data, sizeof(T) / sizeof(*data))
                , "\"", "\"");
    }

    static std::string Hex2String(const char& i_data){
        std::ostringstream buff;
        buff.setf(std::ios_base::hex, std::ios_base::basefield);
        buff.width(8);
        buff.fill('0');
        buff<<(int)i_data;
        std::string rez(buff.str());
        return rez.substr(6, 2);
    }
    /*! @brief there is a part checker of alignment data
     *  @details the function is call if if data is alignment to 32
     *  @param i_data in a pointer the string
     *  @param i_size in size of the string
     *  @return a pair there is first is pointer to the blob
     *          second is a size of the blob
     */
    static std::string Hex2String(Loki::Int2Type<1>, const unsigned char* i_data, size_t i_size){
        std::ostringstream buff;
        for(unsigned int i = 0; i != i_size; ++i){
            std::string data = Hex2String(*i_data);
            buff << data;
            i_data++;
        }
        return buff.str();
    }

    /*! @brief there is a part checker of alignment data
     *  @details if some code try to call the function a compiler return a error
     *  because the function isn't implemented. But the function is tried to call
     *  only if data isn't alignment to 32
     */
    static std::string Hex2String(Loki::Int2Type<0>, const unsigned int* i_data);
    /// @}
};
/// @addtogroup ToString
/// @{
/*! @fn template<class T>
            static T fromString(const std::string& i_data)
 *  @brief template to serialization a data from string
 *  @param i_data in a data
 *  @return string serialization
 */
template<class T>
static T fromString(const std::string& i_data){
	if (i_data.empty()) {
		return 0;
	}
    std::istringstream istream(i_data);
    T rez;
    istream >> rez;
    return rez;
}
/*! @fn template<class T>
            static T toString(const std::string& i_data)
 *  @brief template to get a string serialization from a data
 *  @param i_data in a data
 *  @return string serialization
 */
template<class T>
static std::string toString(const T& i_data){
    return SQLiteStringProcessorBase::toString(Loki::Int2Type<Loki::TypeTraits<T>::isFundamental >(), i_data);
}
/// @}

/// @defgroup SQLiteQueryGenerato Generator of SQLite queries
/// @ingroup SQLiteStringProcesor
/// @{
/*! @interface ISQLQuery
 *  @brief base interface class for all SQL queries classes
 */
class ISQLQuery {
public:
    virtual ~ISQLQuery() {}
    /// @brief query
    /// @return SQL query for the current class
    virtual std::string query() const =0;
    /// @brief virtual constructor
    virtual ISQLQuery* clone() const =0;
};

/// @brief operator equal for queries
inline bool operator == (const ISQLQuery& i_query1, const ISQLQuery& i_query2){
    return i_query1.query() == i_query2.query();
}

/// @brief factory to create shared pointer from reference to query
inline std::shared_ptr<ISQLQuery> makeSharedPtr(const ISQLQuery& i_query){
    return std::shared_ptr<ISQLQuery>(i_query.clone());
}

/*! @class SQLEmptyQuery
 *  @brief implement empty sql query
 */
class SQLEmptyQuery: virtual public ISQLQuery {
public:
    virtual std::string query() const {
        return "";
    }
    virtual ISQLQuery* clone() const {
        return new SQLEmptyQuery();
    }
};

/*! @interface ISQLNamedQuery
 *  increase of ISQLQuery to save and get named queries
 */
class ISQLStringExpressionQuery: virtual public ISQLQuery {
public:
    virtual const std::string& name() const = 0;
};

/*! @class SQLNamedQuery
 *  @brief the class encapsulated string field
 *  this is used to set column name
 */
class SQLStringExpressionQuery: virtual public ISQLStringExpressionQuery {
    std::string m_columnName;
public:
    SQLStringExpressionQuery(const SQLStringExpressionQuery& i_other)
    : m_columnName(i_other.m_columnName) {}

    SQLStringExpressionQuery(const std::string& i_columnName = std::string(""))
    : m_columnName(i_columnName) {}

    virtual std::string query() const {
        return /*std::move*/(m_columnName);
    }

    virtual ISQLQuery* clone() const {
        return new SQLStringExpressionQuery(*this);
    }

    virtual const std::string& name() const {
        return m_columnName;
    }
protected:
    void set(const std::string& i_data) {
        m_columnName = i_data;
    }
};

/*! @class template<T> SQLLiteralQuery
 *  @brief the class encapsulated any data
 *  this is used to save data between SQL DB and Application.
 *  This is base to create tuple of data.
 */
template<typename T>
class SQLLiteralQuery: virtual public ISQLQuery, public Loki::Type2Type<T> {
    T m_data;
public:
    SQLLiteralQuery(const SQLLiteralQuery& i_other)
    : m_data(i_other.m_data) {}

    SQLLiteralQuery(const T& i_data = T())
    : m_data(i_data) {}

    virtual std::string query() const {
        return /*std::move*/(toString(m_data));
    }

    virtual ISQLQuery* clone() const {
        return new SQLLiteralQuery<T>(*this);
    }

    /// @brief getter for value
    const T& value() const {
        return m_data;
    }

    /// @brief setter for value
    void set(const SQLLiteralQuery<T>& i_data) {
        m_data = i_data.value();
    }
};

/*! @class SQLLiteralQuery<std::string>
 *  @brief specialize of template<T> SQLLiteralQuery for string type
 */
template<>
class SQLLiteralQuery<std::string>: virtual public ISQLQuery, public Loki::Type2Type<std::string> {
    std::string m_data;
public:
    SQLLiteralQuery(const SQLLiteralQuery& i_other)
    : m_data(i_other.m_data) {}

    SQLLiteralQuery(const std::string& i_data = "")
    : m_data(i_data) {}

    virtual std::string query() const {
        return /*std::move*/("\"" + (m_data) + "\"");
    }

    virtual ISQLQuery* clone() const {
        return new SQLLiteralQuery<std::string>(*this);
    }

    const std::string& value() const {
        return m_data;
    }

    void set(const SQLLiteralQuery<std::string>& i_data) {
        m_data = i_data.value();
    }
};

/*! @class template<T> SQLTypeDataQuery
 *  @brief the class encapsulated type of any data
 *  this is used to add SQL type into SQL query.
 */
template<typename T>
class SQLTypeDataQuery: virtual public ISQLQuery, public Loki::Type2Type<T> {
public:
    virtual std::string query() const {
        return /*std::move*/(SQLiteStringProcessorBase::getSQLiteTypeDataName(T()));
    }

    virtual ISQLQuery* clone() const {
        return new SQLTypeDataQuery(*this);
    }
};

/*! @class template<T> SQLDefaultQuery
 *  @brief the class add default section into SQL CREATE query.
 */
template<typename T>
class SQLDefaultQuery: public SQLLiteralQuery<T> {
public:
    SQLDefaultQuery(const SQLDefaultQuery& i_other)
    : SQLLiteralQuery<T>(i_other) {}

    SQLDefaultQuery(const SQLLiteralQuery<T>& i_other)
    : SQLLiteralQuery<T>(i_other) {}

    SQLDefaultQuery(const T& i_data = T())
    : SQLLiteralQuery<T>(i_data) {}

    virtual std::string query() const {
        return /*std::move*/( SQLiteStringProcessorBase::DEFAULT
                + SQLiteStringProcessorBase::SPACE
                + SQLLiteralQuery<T>::query());
    }

    virtual ISQLQuery* clone() const {
        return new SQLDefaultQuery<T>(*this);
    }
};

/*! @class template<Container> SQLQueryCollections
 *  @brief this is wrapper under a collection of queries to generate General query.
 */
template<class Container>
class SQLQueryCollections: virtual public ISQLQuery, public Container, public Loki::Type2Type<Container> {
    std::string m_separatorSimbol;
public:
    SQLQueryCollections(const SQLQueryCollections& i_other)
    : Container(i_other)
    , m_separatorSimbol(i_other.m_separatorSimbol) {}

    SQLQueryCollections()
    : m_separatorSimbol(SQLiteStringProcessorBase::COMMA) {}

    SQLQueryCollections(const Container& data,
		const std::string& i_separatorSimbol = std::string(SQLiteStringProcessorBase::COMMA))
    : Container(data)
    , m_separatorSimbol(i_separatorSimbol) {}

    template<class Iterator>
    SQLQueryCollections(Iterator i_begin, Iterator i_end,
        const std::string& i_separatorSimbol =
                SQLiteStringProcessorBase::COMMA)
    : Container(i_begin, i_end)
    , m_separatorSimbol(i_separatorSimbol) {}

    virtual std::string query() const {
        std::string rezQuery;
        // TODO moiseenko.a Shell definition a type for '*'.
        if (this->empty() == true) {
            return "*";
        }
        for(typename Container::const_iterator x = this->begin(); x != this->end(); ++x) {
            rezQuery += getQuery(*x).query() + m_separatorSimbol;
        }
        rezQuery.erase(rezQuery.size() - m_separatorSimbol.size(), m_separatorSimbol.size());
        return rezQuery;
    }

    virtual ISQLQuery* clone() const {
        return new SQLQueryCollections(*this);
    }

    /// @brief set a symbol which is printed between different queries
    void setSeparatorSimbol(const std::string& i_separatorSimbol) {
        m_separatorSimbol = i_separatorSimbol;
    }

    /// @defgroup group of function to get a reference to query from different
    /// variant of collected data
    /// @{
    template<typename Query>
    static ISQLQuery& getQuery(std::shared_ptr<Query> i_query) {
        return *i_query;
    }

    static ISQLQuery& getQuery(ISQLQuery& i_query) {
        return i_query;
    }

    template<typename KeyType, typename Query>
    static ISQLQuery& getQuery(std::pair<KeyType, Query>& i_query) {
       return i_query.second;
    }

    template<typename KeyType, typename Query>
    static ISQLQuery& getQuery(std::pair<KeyType, std::shared_ptr<Query> >& i_query) {
        return *(i_query.second);
    }

    static const ISQLQuery& getQuery(const ISQLQuery& i_query) {
        return i_query;
    }

    template<typename KeyType, typename Query>
    static const ISQLQuery& getQuery(const std::pair<KeyType, Query>& i_query) {
       return i_query.second;
    }

    template<typename KeyType, typename Query>
    static const ISQLQuery& getQuery(const std::pair<KeyType, std::shared_ptr<Query> >& i_query) {
        return *(i_query.second);
    }
    /// @}
};

/*! @fn template<class Base, class Filtered>
        void FilterArg(std::vector<SHARED_PTR<Base> >& o_vector, const Base& arg)
 *  @brief the function collect element into container only if type of the
 *  element can be casted to Filtered type.
 *  @param Base in type of checked elements
 *  @param Filtered in type which data shell be collected
 *  @param o_vector out a reference to vector where collected data
 *  @param arg in candidate to collect
 */
template<class Base, class Filtered>
void FilterArg(std::vector<std::shared_ptr<Base> >& o_vector, const Base& arg) {
    if(NULL == dynamic_cast<const Filtered*>(&arg)) {
        o_vector.push_back(makeSharedPtr(arg));
    }
}

/*! @interface ISQLColumnDataQuery
 *  @brief increase of ISQLNamedQuery to save and get named column and data of the column
 */
class ISQLColumnDataQuery: virtual public ISQLStringExpressionQuery {
public:
    /*! @brief getter of value for the column
     *  @return shared pointer to ISQLQuery which shell be allowed to cast to SQLliteral
     */
    virtual std::shared_ptr<ISQLQuery> value() const =0;
    /*! @brief setter of value for the column
     *  @param i_data a query which contain data
     */
    virtual void set(const ISQLQuery& i_data) =0;
};

/*! @class SQLColumnDataQuery
 *  @brief implement of ISQLColumnDataQuery
 *  the class is used to save data of a SQL DB row field
 */
template<typename T>
class SQLColumnDataQuery: virtual  public ISQLColumnDataQuery, public Loki::Type2Type<T>, public SQLStringExpressionQuery {
    std::shared_ptr<ISQLQuery> m_data;
public:
    SQLColumnDataQuery(const SQLColumnDataQuery<T>& i_other)
    : SQLStringExpressionQuery(i_other)
    , m_data(i_other.m_data) {}

    SQLColumnDataQuery(const SQLStringExpressionQuery& i_columnName, const T& i_data = T())
    : SQLStringExpressionQuery(i_columnName)
    , m_data(std::shared_ptr<ISQLQuery>(new SQLLiteralQuery<T>(i_data))) {}

    SQLColumnDataQuery(const std::string& i_columnName, const T& i_data = T())
    : SQLStringExpressionQuery(i_columnName)
    , m_data(std::shared_ptr<ISQLQuery>(new SQLLiteralQuery<T>(i_data))) {}

    virtual std::string query() const {
        return /*std::move*/(SQLStringExpressionQuery::query()
                + " = "
                + m_data->query());
    }

    virtual const std::string& name() const {
        return SQLStringExpressionQuery::name();
    }

    virtual std::shared_ptr<ISQLQuery> value() const {
        return this->m_data;
    }

    virtual void set(const ISQLQuery& i_data) {
        const SQLLiteralQuery<T>* literal = dynamic_cast<const SQLLiteralQuery<T>*>(&i_data);
        if (literal != NULL) {
            m_data = std::shared_ptr<ISQLQuery>(this->dataSet(literal));
            return;
        }
        const SQLColumnDataQuery<T>* columnData = dynamic_cast<const SQLColumnDataQuery<T>*>(&i_data);
        if (columnData != NULL) {
            m_data = std::shared_ptr<ISQLQuery>(this->dataSet(columnData));
            return;
        }
        throw SQLiteException(
			"set data into SQLColumnDataQuery could be only from SQLLiteralQuery<T> or SQLColumnDataQuery<T>");
    }

    virtual ISQLQuery* clone() const {
        return (new SQLColumnDataQuery(*this));
    }
private:
    SQLLiteralQuery<T>* dataSet(const SQLLiteralQuery<T>* i_data) {
        return dynamic_cast<SQLLiteralQuery<T>*>(i_data->clone());
    }

    static SQLLiteralQuery<T>*  dataSet(const SQLColumnDataQuery<T>* i_data) {
        return dynamic_cast<SQLLiteralQuery<T>*>(dynamic_cast<const SQLLiteralQuery<T>& >(*(i_data->value())).clone());
    }
};

/*! @class SQLColumnDataQueryCollections
 *  @brief implement of ISQLColumnDataQuery
 *  the class is used to save row of SQL DB table
 */
template<template<class> class Container, class ColumnDataType = std::shared_ptr<ISQLColumnDataQuery> >
class SQLColumnDataQueryCollections: virtual  public ISQLColumnDataQuery,
    public SQLQueryCollections<Container<ColumnDataType> > {
    typedef Container<ColumnDataType > ColumnData;
    mutable std::string m_genericName;

public:
    typedef ColumnDataType ValueType;
    SQLColumnDataQueryCollections(const SQLColumnDataQueryCollections& i_other)
    : SQLQueryCollections<ColumnData>(i_other) {}

    SQLColumnDataQueryCollections()
    : SQLQueryCollections<ColumnData>() {}

    SQLColumnDataQueryCollections(const ColumnData& data,
            const std::string& i_separatorSimbol =
                    SQLiteStringProcessorBase::COMMA)
    :  SQLQueryCollections<ColumnData>(data, i_separatorSimbol) {}

    template<class Iterator>
    SQLColumnDataQueryCollections(Iterator i_begin, Iterator i_end,
                const std::string& i_separatorSimbol =
                        SQLiteStringProcessorBase::COMMA)
        :  SQLQueryCollections<ColumnData>(i_begin, i_end, i_separatorSimbol) {}

    virtual std::string query() const {
        return SQLQueryCollections<ColumnData>::query();
    }

    virtual ISQLQuery* clone() const {
        return (new SQLColumnDataQueryCollections(*this));
    }

    virtual std::shared_ptr<ISQLQuery> value() const {
        SQLQueryCollections<Container<std::shared_ptr<ISQLQuery> > > rez;
        rez.setSeparatorSimbol(SQLiteStringProcessorBase::COMMA);
        for(typename ColumnData::const_iterator i = this->begin();
            i != this->end(); ++i){
            const ISQLColumnDataQuery& columnData =
                    dynamic_cast<const ISQLColumnDataQuery&>(SQLQueryCollections<ColumnData>::getQuery(*i));
            rez.push_back(columnData.value());
        }
        return makeSharedPtr(rez);
    }

    virtual void set(const ISQLQuery& i_data){
        const SQLQueryCollections<Container<std::shared_ptr<ISQLQuery> > >& data =
                dynamic_cast<const SQLQueryCollections<Container<std::shared_ptr<ISQLQuery> > >& >(i_data);
        typename ColumnData::iterator dst = this->begin();
        typename SQLQueryCollections<Container<std::shared_ptr<ISQLQuery> > >::const_iterator src = data.begin();
        while(dst != this->end() && src != data.end()){
            ISQLColumnDataQuery& columnData =
                    dynamic_cast<ISQLColumnDataQuery&>(SQLQueryCollections<ColumnData>::getQuery(*dst));
            columnData.set(SQLQueryCollections<ColumnData>::getQuery(*src));
            ++dst, ++src;
        }
    }

    virtual const std::string& name() const{
        this->m_genericName = "";
        for(typename ColumnData::const_iterator i = this->begin();
            i != this->end(); ++i){
            this->m_genericName += dynamic_cast<ISQLColumnDataQuery&>(SQLQueryCollections<ColumnData>::getQuery(*i)).name()
                + SQLiteStringProcessorBase::COMMA;
        }
        this->m_genericName.erase(this->m_genericName.size() - SQLiteStringProcessorBase::COMMA.size(), SQLiteStringProcessorBase::COMMA.size());
        return this->m_genericName;
    }
};

/*! @class SQLIndexColumnQuery
 *  @brief specialisation of SQLCreatedColumnQuery<long> to definition
 *  the primary key column
 */
class SQLIndexColumnQuery: public ISQLQuery {
public:
    SQLIndexColumnQuery(const SQLIndexColumnQuery& i_other)
    : m_collection(i_other.m_collection) {}

    SQLIndexColumnQuery(const ISQLQuery& i_columnName,
           const ISQLQuery& i_cllate = SQLEmptyQuery(),
           const ISQLQuery& i_orderType = SQLEmptyQuery()) {
        m_args.push_back(makeSharedPtr(i_columnName));
        m_args.push_back(makeSharedPtr(i_cllate));
        m_args.push_back(makeSharedPtr(i_orderType));

        m_collection =
            SQLQueryCollections<std::vector<std::shared_ptr<ISQLQuery>>>(m_args, SQLiteStringProcessorBase::SPACE);
    }

    virtual std::string query() const {
        return /*std::move*/(m_collection.query());
    }

    virtual ISQLQuery* clone() const {
        return (new SQLIndexColumnQuery(*this));
    }
protected:
    std::vector<std::shared_ptr<ISQLQuery>> m_args;
    SQLQueryCollections<std::vector<std::shared_ptr<ISQLQuery>>> m_collection;

};

/*! @class SQLCreatedIndexQuery
 *  @brief specialisation of SQLCreatedColumnQuery<long> to definition
 *  the primary key column
 */
class SQLCreatedIndexQuery: public ISQLQuery {
public:
    SQLCreatedIndexQuery(const SQLCreatedIndexQuery& i_other)
    : m_columnNames(i_other.m_columnNames)
    , m_collection(i_other.m_collection) {}

    SQLCreatedIndexQuery(const ISQLQuery& i_indexName,
            const ISQLQuery& i_tableNames,
           const ISQLQuery& i_columnNames,
           const ISQLQuery& i_unique = SQLEmptyQuery(),
           const ISQLQuery& i_ifNotExists = SQLEmptyQuery())
    : m_columnNames(makeSharedPtr(i_columnNames)){
        m_args.push_back(makeSharedPtr(SQLStringExpressionQuery(SQLiteStringProcessorBase::CREATE)));
        m_args.push_back(makeSharedPtr(i_unique));
        m_args.push_back(makeSharedPtr(SQLStringExpressionQuery(SQLiteStringProcessorBase::INDEX)));
        m_args.push_back(makeSharedPtr(i_ifNotExists));
        m_args.push_back(makeSharedPtr(i_indexName));
        m_args.push_back(makeSharedPtr(SQLStringExpressionQuery(SQLiteStringProcessorBase::ON)));
        m_args.push_back(makeSharedPtr(i_tableNames));

        m_collection =
            SQLQueryCollections<std::vector<std::shared_ptr<ISQLQuery> > >(m_args, SQLiteStringProcessorBase::SPACE);
    }

    virtual std::string query() const {
        return /*std::move*/(m_collection.query()
                + makeBrecetBlock(m_columnNames->query()));
    }

    virtual ISQLQuery* clone() const {
        return (new SQLCreatedIndexQuery(*this));
    }

protected:
    std::shared_ptr<ISQLQuery> m_columnNames;
    std::vector<std::shared_ptr<ISQLQuery> > m_args;
    SQLQueryCollections<std::vector<std::shared_ptr<ISQLQuery> > > m_collection;
};

/*! @class SQLCreatedColumnQuery
 *  @brief implement of ISQLQuery
 *  the class is used to add a column definition into create table query
 */
template<typename T>
class SQLCreatedColumnQuery: virtual public ISQLQuery,
        protected SQLColumnDataQuery<T>,
        protected SQLTypeDataQuery<T>,
        protected SQLDefaultQuery<T> {
public:
    SQLCreatedColumnQuery(const SQLCreatedColumnQuery<T>& i_other)
    : SQLColumnDataQuery<T>(i_other)
    , SQLDefaultQuery<T>(i_other) {}

    SQLCreatedColumnQuery(const SQLColumnDataQuery<T>& i_other)
    : SQLColumnDataQuery<T>(i_other)
    , SQLDefaultQuery<T>(dynamic_cast<SQLLiteralQuery<T>& >(*i_other.value())) {}

    SQLCreatedColumnQuery(const std::string& i_columnName, const T& i_data = T())
    : SQLColumnDataQuery<T>(i_columnName, i_data)
    , SQLDefaultQuery<T>(i_data) {}

    virtual std::string query() const {
        return /*std::move*/(SQLColumnDataQuery<T>::name()
                + SQLiteStringProcessorBase::SPACE
                + SQLTypeDataQuery<T>::query()
                + SQLiteStringProcessorBase::SPACE
                + SQLDefaultQuery<T>::query()
        );
    }

    SQLColumnDataQuery<T> sqlColumnData() {
        return SQLColumnDataQuery<T>(*this);
    }

    virtual ISQLQuery* clone() const {
        return ( new SQLCreatedColumnQuery(*this));
    }
};

/*! @class SQLCreatedPrimaryKeyColumnQuery
 *  @brief specialisation of SQLCreatedColumnQuery<long> to definition
 *  the primary key column
 */
class SQLCreatedPrimaryKeyColumnQuery: public SQLCreatedColumnQuery<long> {
public:
    SQLCreatedPrimaryKeyColumnQuery(const SQLCreatedPrimaryKeyColumnQuery& i_other)
    : SQLCreatedColumnQuery<long>(i_other) {}

    SQLCreatedPrimaryKeyColumnQuery(const SQLColumnDataQuery<long>& i_other)
    : SQLCreatedColumnQuery<long>(i_other) {}

    SQLCreatedPrimaryKeyColumnQuery(const std::string& i_columnName)
    : SQLCreatedColumnQuery<long>(i_columnName) {}

    virtual std::string query() const {
        return /*std::move*/(SQLCreatedColumnQuery<long>::name()
        + SQLiteStringProcessorBase::SPACE
        + SQLTypeDataQuery<long>::query()
        + SQLiteStringProcessorBase::SPACE
        + SQLiteStringProcessorBase::PRIMARY_KEY);
    }

    virtual ISQLQuery* clone() const {
        return (new SQLCreatedPrimaryKeyColumnQuery(*this));
    }
};

/*! @class SQLCreatedUniqueColumnQuery
 *  @brief specialisation of SQLCreatedColumnQuery<T> to definition
 *  the column with unique values
 */
template<typename T>
class SQLCreatedUniqueColumnQuery: public SQLCreatedColumnQuery<T>{
public:
    SQLCreatedUniqueColumnQuery(const SQLCreatedUniqueColumnQuery& i_other)
    : SQLCreatedColumnQuery<T>(i_other){}
    SQLCreatedUniqueColumnQuery(const std::string& i_columnName)
    : SQLCreatedColumnQuery<T>(i_columnName){
    }
    SQLCreatedUniqueColumnQuery(const SQLColumnDataQuery<T>& i_other)
    : SQLCreatedColumnQuery<T>(i_other){
    }
    SQLCreatedUniqueColumnQuery(const SQLStringExpressionQuery& i_columnName, const T& i_data = T())
    : SQLCreatedColumnQuery<T>(i_columnName, i_data){
    }
    virtual std::string query() const {
        return /*std::move*/(SQLCreatedColumnQuery<T>::name()
        + SQLiteStringProcessorBase::SPACE
        + SQLTypeDataQuery<T>::query()
        + SQLiteStringProcessorBase::SPACE
        + SQLiteStringProcessorBase::UNIQUE);
    }

    virtual ISQLQuery* clone() const {
        return new SQLCreatedUniqueColumnQuery(*this);
    }
};

/*! @class SQLLimitOffsetQuery
 *  @brief implementation of ISQLQuery
 *  the class is base for classes which add limit/offset part into query
 */
class SQLLimitOffsetQuery: virtual public ISQLQuery{
    int m_limit;
public:
    SQLLimitOffsetQuery(const SQLLimitOffsetQuery& i_other)
    : m_limit(i_other.m_limit){
    }

    SQLLimitOffsetQuery(int i_limit)
    : m_limit(i_limit){
    }

    virtual std::string query() const {
        return /*std::move*/(toString(m_limit));
    }

    virtual ISQLQuery* clone() const {
        return new SQLLimitOffsetQuery(*this);
    }
};

/*! @class SQLOffsetdQuery
 *  @brief specialisation of SQLLimitOffsetQuery
 *  the class adds offset part into query
 */
class SQLOffsetdQuery: public SQLLimitOffsetQuery{
public:
    SQLOffsetdQuery(const SQLOffsetdQuery& i_other)
    : SQLLimitOffsetQuery(i_other){
    }

    SQLOffsetdQuery(int i_limit)
    : SQLLimitOffsetQuery(i_limit){
    }

    virtual std::string query() const {
        return /*std::move*/( SQLiteStringProcessorBase::OFFSET
               + SQLiteStringProcessorBase::SPACE
               + SQLLimitOffsetQuery::query());
    }

    virtual ISQLQuery* clone() const {
        return new SQLOffsetdQuery(*this);
    }
};

/*! @class SQLOffsetdQuery
 *  @brief specialisation of SQLLimitOffsetQuery
 *  the class adds limit part into query
 */
class SQLLimitededQuery: public SQLLimitOffsetQuery{
    std::shared_ptr<ISQLQuery> m_offest;
public:
    SQLLimitededQuery(const SQLLimitededQuery& i_other)
    : SQLLimitOffsetQuery(i_other)
    , m_offest(std::shared_ptr<ISQLQuery>(i_other.m_offest->clone())){
    }

    //TODO moiseenko.a: Add static type check
    SQLLimitededQuery(int i_limit, const ISQLQuery& i_offset = SQLEmptyQuery())
    : SQLLimitOffsetQuery(i_limit)
    , m_offest(makeSharedPtr(i_offset)){
    }

    virtual std::string query() const {
        return /*std::move*/( SQLiteStringProcessorBase::LIMIT
               + makeSpaceBlock(SQLLimitOffsetQuery::query())
               + m_offest->query());
    }

    virtual ISQLQuery* clone() const {
        return new SQLLimitededQuery(*this);
    }
};

/*! @class SQLOrderedColumnQuery
 *  @brief specialisation of SQLNamedQuery
 *  the class adds ordered path in to query
 */
class SQLOrderedColumnQuery: public SQLStringExpressionQuery{
    SQLStringExpressionQuery m_typeOredered;
public:
    SQLOrderedColumnQuery(const SQLOrderedColumnQuery& i_other)
    : SQLStringExpressionQuery(i_other)
    , m_typeOredered(i_other.m_typeOredered){
    }

    SQLOrderedColumnQuery(const SQLStringExpressionQuery& i_columnName,
            const SQLStringExpressionQuery& i_typeOredered =  SQLStringExpressionQuery("ASC"))
    : SQLStringExpressionQuery(i_columnName)
    , m_typeOredered(i_typeOredered){
    }

    virtual std::string query() const {
        return /*std::move*/(SQLiteStringProcessorBase::ORDER_BY
            + makeSpaceBlock(SQLStringExpressionQuery::query())
            + m_typeOredered.query());
    }

    virtual ISQLQuery* clone() const {
        return new SQLOrderedColumnQuery(*this);
    }
};

/*! @class SQLCrossColumnQuery CROSS
 *  @brief specialisation of SQLJoinConstraintQuery
 *  the class adds join constraint path in to query
 */
class SQLJoinConstraintQuery: public SQLStringExpressionQuery{
    std::shared_ptr<ISQLQuery> m_exprecion;
public:
    SQLJoinConstraintQuery(const SQLJoinConstraintQuery& i_other)
    : SQLStringExpressionQuery(i_other)
    , m_exprecion(i_other.m_exprecion){
    }

    SQLJoinConstraintQuery(const SQLStringExpressionQuery& i_typeConstraint,
            const ISQLQuery& i_exprecion)
    : SQLStringExpressionQuery(i_typeConstraint)
    , m_exprecion(makeSharedPtr(i_exprecion)){
    }

    virtual std::string query() const {
        return /*std::move*/(SQLStringExpressionQuery::query()
            + makeSpaceBlock(m_exprecion->query()));
    }

    virtual ISQLQuery* clone() const {
        return new SQLJoinConstraintQuery(*this);
    }
};

/*! @class SQLJoinColumnQuery
 *  @brief specialisation of SQLJoinQuery
 *  the class adds join path in to query
 */
class SQLJoinQuery: public ISQLQuery{
public:
    SQLJoinQuery(const SQLJoinQuery& i_other)
    : m_collection(i_other.m_collection) {}

    SQLJoinQuery(const ISQLQuery& i_firstSingleSource,
            const SQLStringExpressionQuery& i_joinTypeOp,
            const ISQLQuery& i_secondSingleSource,
            const ISQLQuery& i_joinConstraint = SQLEmptyQuery()) {
        m_args.push_back(makeSharedPtr(i_firstSingleSource));
        m_args.push_back(makeSharedPtr(i_joinTypeOp));
        m_args.push_back(makeSharedPtr(SQLStringExpressionQuery(SQLiteStringProcessorBase::JOIN)));
        m_args.push_back(makeSharedPtr(i_secondSingleSource));
        FilterArg<ISQLQuery, SQLEmptyQuery>(m_args, i_joinConstraint);
        m_collection =
            SQLQueryCollections<std::vector<std::shared_ptr<ISQLQuery> > >(m_args, SQLiteStringProcessorBase::SPACE);
    }

    virtual std::string query() const {
        return /*std::move*/(m_collection.query());
    }

    virtual ISQLQuery* clone() const {
        return new SQLJoinQuery(*this);
    }
protected:
    std::vector<std::shared_ptr<ISQLQuery> > m_args;
    SQLQueryCollections<std::vector<std::shared_ptr<ISQLQuery> > > m_collection;
};

/*! @class SQLFromQuery
 *  @brief the class adds from path in to query
 */
class SQLFromQuery: virtual public ISQLQuery {
    std::shared_ptr<ISQLQuery> m_tableNames;
public:
    SQLFromQuery(const SQLFromQuery& i_other)
    : m_tableNames(std::shared_ptr<ISQLQuery>(i_other.m_tableNames->clone())){
    }

    //TODO moiseenko.a: Add static type check
    SQLFromQuery(const ISQLQuery& i_joinSource)
    : m_tableNames(makeSharedPtr(i_joinSource)){
    }

    virtual std::string query() const {
        return /*std::move*/(SQLiteStringProcessorBase::FROM
                + SQLiteStringProcessorBase::SPACE
                + m_tableNames->query());
    }

    virtual ISQLQuery* clone() const {
        return new SQLFromQuery(*this);
    }
};

/*! @class SQLFromQuery
 *  @brief the class adds from path in to query
 */
class SQLUniqueSetQuery: virtual public ISQLQuery {
    std::shared_ptr<ISQLQuery> m_columnsNames;
public:
    SQLUniqueSetQuery(const SQLUniqueSetQuery& i_other)
    : m_columnsNames(std::shared_ptr<ISQLQuery>(i_other.m_columnsNames->clone())){
    }

    //TODO moiseenko.a: Add static type check
    SQLUniqueSetQuery(const ISQLQuery& i_columnsNames)
    : m_columnsNames(makeSharedPtr(i_columnsNames)){
    }

    virtual std::string query() const {
        return /*std::move*/(SQLiteStringProcessorBase::UNIQUE
                + makeBrecetBlock(m_columnsNames->query()));
    }

    virtual ISQLQuery* clone() const {
        return new SQLUniqueSetQuery(*this);
    }
};

/*! @class SQLFromQuery
 *  @brief the class adds from path in to query
 */
class SQLForeignKeyQuery: virtual public ISQLQuery {
    std::shared_ptr<ISQLQuery> m_columnsNames;
    SQLStringExpressionQuery m_foreignTableName;
    std::shared_ptr<ISQLQuery> m_foreignColumnsNames;

public:
    SQLForeignKeyQuery(const SQLForeignKeyQuery& i_other)
    : m_columnsNames(std::shared_ptr<ISQLQuery>(i_other.m_columnsNames->clone()))
    , m_foreignTableName(i_other.m_foreignTableName)
    , m_foreignColumnsNames(i_other.m_foreignColumnsNames){
    }

    //TODO moiseenko.a: Add static type check
    SQLForeignKeyQuery(const ISQLQuery& i_columnsNames = SQLEmptyQuery()
            , const SQLStringExpressionQuery& i_foreignTableName = SQLStringExpressionQuery()
            , const ISQLQuery& i_foreignColumnsNames = SQLEmptyQuery())
    : m_columnsNames(makeSharedPtr(i_columnsNames))
    , m_foreignTableName(i_foreignTableName)
    , m_foreignColumnsNames(makeSharedPtr(i_foreignColumnsNames)){
    }

    virtual std::string query() const {
        return /*std::move*/(SQLiteStringProcessorBase::FOREIGN_KEY
                + makeBrecetBlock(m_columnsNames->query())
                + makeSpaceBlock(SQLiteStringProcessorBase::REFERENCES)
                + m_foreignTableName.query()
                + makeBrecetBlock(m_foreignColumnsNames->query())
                + " ON DELETE CASCADE"
                " ON UPDATE CASCADE");

    }

    virtual ISQLQuery* clone() const {
        return new SQLForeignKeyQuery(*this);
    }
};

/*! @class SQLPredicateAscedColumnQuery
 *  @brief the class definition predicate which can be used into where part of a query
 */
class SQLPredicateAscedColumnQuery: virtual public ISQLQuery {

public:
    struct SQLPredicateOperator {
        enum PredicateOperator{
            EQUAL,
            LESS,
            GREATER,
            LESS_EQUAL,
            GREATE_EQUAL,
            NO_EQUAL,
            IS,
            IS_NOT,
            AND,
            OR,
            IN_,
            NOT_IN,
            BETWEEN,
            LIMIT_OPER  ///< definition error expression
        };
        SQLPredicateOperator(PredicateOperator i_operator = EQUAL)
        : m_operator(i_operator){
        }
        operator int() const {
            return int(m_operator);
        }
    private:
        PredicateOperator m_operator;
    };
    /// @enum SQLOperator
    /// @brief definition compare operators
    SQLPredicateAscedColumnQuery(const SQLPredicateAscedColumnQuery& i_other)
    : m_firstArg(std::shared_ptr<ISQLQuery>(i_other.m_firstArg->clone()))
    , m_secondArg(std::shared_ptr<ISQLQuery>(i_other.m_secondArg->clone()))
    , m_operation(i_other.m_operation) {}

    //TODO moiseenko.a: Add static type check
    /*! @brief constructor
     *  @param i_firstArg in first query of predicate
     *  @param i_operation in compare operator
     *  @param i_secondArg in second query of predicate
     */
    SQLPredicateAscedColumnQuery(const ISQLQuery& i_firstArg, SQLPredicateOperator i_operation, const ISQLQuery& i_secondArg)
    : m_firstArg(makeSharedPtr(i_firstArg))
    , m_secondArg(makeSharedPtr(i_secondArg))
    , m_operation(SQLPredicateOperator(i_operation)) {
        if (int(m_operation) >= SQLPredicateOperator::LIMIT_OPER) {
            throw SQLiteException("Unknown operation");
        }
    }

    virtual std::string query() const {
        return makeBrecetBlock(
                makeBrecetBlock(m_firstArg->query())
                + makeSpaceBlock(operation())
                + makeBrecetBlock(m_secondArg->query()));
    }

    virtual ISQLQuery* clone() const {
        return new SQLPredicateAscedColumnQuery(*this);
    }

    SQLPredicateAscedColumnQuery& operator= (const SQLPredicateAscedColumnQuery& i_other) {
        m_firstArg = (std::shared_ptr<ISQLQuery>(i_other.m_firstArg->clone()));
        m_secondArg = (std::shared_ptr<ISQLQuery>(i_other.m_secondArg->clone()));
        m_operation = (i_other.m_operation);
        return *this;
    }
private:
    std::shared_ptr<ISQLQuery> m_firstArg;
    std::shared_ptr<ISQLQuery> m_secondArg;
    SQLPredicateOperator m_operation;
    static const std::string OperationCollection[SQLPredicateOperator::LIMIT_OPER];
    const std::string& operation() const {
        return OperationCollection[m_operation];
    }
};

/*! @class SQLWhereQuery
 *  @brief the class adds where in to query
 */
class SQLWhereQuery: virtual public ISQLQuery {
    std::shared_ptr<ISQLQuery> m_predicate;
public:
    SQLWhereQuery(const SQLWhereQuery& i_other)
		: m_predicate(i_other.m_predicate) {}

    SQLWhereQuery(const ISQLQuery& i_predicate)
    : m_predicate(makeSharedPtr(i_predicate)) {}

    virtual std::string query() const {
        return /*std::move*/(SQLiteStringProcessorBase::WHERE
                + SQLiteStringProcessorBase::SPACE
                + m_predicate->query());
    }

    virtual ISQLQuery* clone() const {
        return new SQLWhereQuery(*this);
    }
};

/*! @class SQLWhereQuery
 *  @brief the class create query for create a table
 */
class SQLCreateTableQuery: virtual public ISQLQuery {
public:
    SQLCreateTableQuery(const SQLCreateTableQuery& i_other)
    : m_tableName(i_other.m_tableName)
    , m_tableDescriptions(std::shared_ptr<ISQLQuery>(i_other.m_tableDescriptions->clone())){}

    //TODO(moiseenko.a): Add static type check
    /*! @brief constructor
     *  @param i_tableName[i] name of the table which is packed into SQLNamedQuery obj
     *  @param i_columnsQuery[i] reference to collection of created query ojects (SQLCreatedColumnQuery<T>)
     *  @param i_tableConstrain[i] reference to Table Constrain
     */
    SQLCreateTableQuery(const SQLStringExpressionQuery& i_tableName,
        const ISQLQuery& i_tableDescriptions)
    : m_tableName(i_tableName)
    , m_tableDescriptions(makeSharedPtr(i_tableDescriptions)){}

    virtual std::string query() const {
        return /*std::move*/(SQLiteStringProcessorBase::CREATE_TABLE
            + makeSpaceBlock(m_tableName.query())
            + makeBrecetBlock(m_tableDescriptions->query()));
    }

    virtual ISQLQuery* clone() const {
        return new SQLCreateTableQuery(*this);
    }

private:
    SQLStringExpressionQuery m_tableName;
    std::shared_ptr<ISQLQuery> m_tableDescriptions;
};

/*! @class SQLSelectQuery
 *  @brief the class create query for select
 */
class SQLSelectQuery: virtual public ISQLQuery {
public:
    SQLSelectQuery(const SQLSelectQuery& i_other)
    : m_collection(i_other.m_collection) {}

    //  TODO(moiseenko.a): Add static type check
    /*! @brief constructor
     *  @param i_ascedQuery is collection of SQLNamedQuery or a SQLNamedQuery
     *  which contains names of columns which shell be read from DB
     *  @param i_fromQuery is collection of SQLFromQuery or a SQLFromQuery
     *  which contains names of asked tables
     *  @param i_predicateQuery shell contain a SQLWhereQuery or SQLEmptyQuery
     *  @param i_orderQuery shell contain SQLOrderedColumnQuery or SQLEmptyQuery
     *  @param i_limitQuery shell contain SQLLimitColumnQuery or SQLEmptyQuery
     */
    SQLSelectQuery(const ISQLQuery& i_ascedQuery,
        const ISQLQuery& i_fromQuery,
        const ISQLQuery& i_predicateQuery = SQLEmptyQuery(),
        const ISQLQuery& i_orderQuery = SQLEmptyQuery(),
        const ISQLQuery& i_limitQuery = SQLEmptyQuery()) {
        m_args.push_back(makeSharedPtr(i_ascedQuery));
        m_args.push_back(makeSharedPtr(i_fromQuery));
        FilterArg<ISQLQuery, SQLEmptyQuery>(m_args, i_predicateQuery);
        FilterArg<ISQLQuery, SQLEmptyQuery>(m_args, i_orderQuery);
        FilterArg<ISQLQuery, SQLEmptyQuery>(m_args, i_limitQuery);
        m_collection =
			SQLQueryCollections<std::vector<std::shared_ptr<ISQLQuery> > >(m_args, SQLiteStringProcessorBase::SPACE);
    }

    virtual std::string query() const {
        return /*std::move*/(SQLiteStringProcessorBase::SELECT
                + SQLiteStringProcessorBase::SPACE
                + m_collection.query());
    }

    virtual ISQLQuery* clone() const {
        return new SQLSelectQuery(*this);
    }

private:
    std::vector<std::shared_ptr<ISQLQuery> > m_args;
    SQLQueryCollections<std::vector<std::shared_ptr<ISQLQuery> > > m_collection;
};

/*! @class SQLInsertQuery
 *  @brief the class create query for insert data
 */
class SQLInsertQuery: virtual public ISQLQuery {
public:
    SQLInsertQuery(const SQLInsertQuery& i_other)
    : m_tableName(i_other.m_tableName)
	, m_insertedQuery(std::dynamic_pointer_cast<ISQLColumnDataQuery>(makeSharedPtr(*i_other.m_insertedQuery)))
    , m_insertType(i_other.m_insertType){}

    /*! @brief constructor
     *  @param i_tableName contain table name
     *  @param i_insertedQuery contain a collection of obj or individual obj
     *  which implement of  ISQLColumnDataQuery.
     *  There are data which shell be set into DB.
     */
    SQLInsertQuery(const SQLStringExpressionQuery& i_tableName,
        const ISQLColumnDataQuery& i_insertedQuery,
        const std::string& i_insertType = std::string(""))
    : m_tableName(i_tableName)
    , m_insertedQuery(std::dynamic_pointer_cast<ISQLColumnDataQuery>(makeSharedPtr(i_insertedQuery))){
        if(!i_insertType.empty()){
            m_insertType = makeSpaceBlock(SQLiteStringProcessorBase::OR) +
                i_insertType + SQLiteStringProcessorBase::SPACE + SQLiteStringProcessorBase::INTO;
        }
        else {
            m_insertType = SQLiteStringProcessorBase::SPACE + SQLiteStringProcessorBase::INTO;
        }
    }

    virtual std::string query() const {
        return /*std::move*/(SQLiteStringProcessorBase::INSERT
                + m_insertType
                + makeSpaceBlock(m_tableName.query())
                + makeBrecetBlock(m_insertedQuery->name())
                + makeSpaceBlock(SQLiteStringProcessorBase::VALUES)
                + makeBrecetBlock(m_insertedQuery->value()->query()));
    }

    virtual ISQLQuery* clone() const {
        return new SQLInsertQuery(*this);
    }

private:
    SQLStringExpressionQuery m_tableName;
    std::shared_ptr<ISQLColumnDataQuery> m_insertedQuery;
    std::string m_insertType;
};

/*! @class SQLSetQuery
 *  @brief the class adds set part into query
 */
class SQLSetQuery: virtual public ISQLQuery {
public:
    SQLSetQuery(const SQLSetQuery& i_other)
    :m_ascedQuery(std::dynamic_pointer_cast<ISQLColumnDataQuery>(makeSharedPtr(*i_other.m_ascedQuery))) {}

    /*! @brief constructor
     *  @param i_insertedQuery contain a collection of obj or individual obj
     *  which implement of  ISQLColumnDataQuery.
     *  There are data which shell be set into DB.
     */
    SQLSetQuery(const ISQLColumnDataQuery& i_insertedQuery)
    : m_ascedQuery(std::dynamic_pointer_cast<ISQLColumnDataQuery>(makeSharedPtr(i_insertedQuery))) {}

    virtual std::string query() const {
        return /*std::move*/(SQLiteStringProcessorBase::SET
                + makeSpaceBlock(m_ascedQuery->query()));
    }

    virtual ISQLQuery* clone() const {
        return new SQLSetQuery(*this);
    }

private:
    std::shared_ptr<ISQLColumnDataQuery> m_ascedQuery;
};

/*! @class SQLSetQuery
 *  @brief the class creates query of update
 */
class SQLUpdateQuery: virtual public ISQLQuery {
public:
    SQLUpdateQuery(const SQLUpdateQuery& i_other)
    : m_tableName(i_other.m_tableName)
    , m_setQuery(i_other.m_setQuery)
    , m_predicateQuery(makeSharedPtr(*i_other.m_predicateQuery)) {}

    //TODO moiseenko.a: Add static type check
    /*! @brief constructor
     *  @param i_tableName contains table name
     *  @param i_setQuery contains a collection of obj or individual obj
     *  which implement of  ISQLColumnDataQuery.
     *  There are data which shell be set into DB.
     *  @param i_predicateQuery contains a SQLWhereQuery or SQLEmptyQuery
     */
    SQLUpdateQuery(const SQLStringExpressionQuery& i_tableName,
            const SQLSetQuery& i_setQuery,
            const ISQLQuery& i_predicateQuery = SQLEmptyQuery())
    : m_tableName(i_tableName)
    , m_setQuery(i_setQuery)
    , m_predicateQuery(makeSharedPtr(i_predicateQuery)) {}

    virtual std::string query() const {
        return /*std::move*/(SQLiteStringProcessorBase::UPDATE
                + makeSpaceBlock(m_tableName.query())
                + m_setQuery.query()
                + SQLiteStringProcessorBase::SPACE
                + m_predicateQuery->query());
    }

    virtual ISQLQuery* clone() const {
        return new SQLUpdateQuery(*this);
    }

private:
    SQLStringExpressionQuery m_tableName;
    SQLSetQuery m_setQuery;
    std::shared_ptr<ISQLQuery> m_predicateQuery;
};

/*! @class SQLDeleteQuery
 *  @brief the class creates query of delete
 */
class SQLDeleteQuery: virtual public ISQLQuery {
public:
    SQLDeleteQuery(const SQLDeleteQuery& i_other)
    : m_args(i_other.m_args)
    , m_collection(i_other.m_collection) {}

    //TODO moiseenko.a: Add static type check
    SQLDeleteQuery(const SQLFromQuery& i_tableName,
            const ISQLQuery& i_predicateQuery = SQLEmptyQuery(),
            const ISQLQuery& i_orderQuery = SQLEmptyQuery(),
            const ISQLQuery& i_limitQuery = SQLEmptyQuery()) {
        m_args.push_back(makeSharedPtr(i_tableName));
        FilterArg<ISQLQuery, SQLEmptyQuery>(m_args, i_predicateQuery);
        FilterArg<ISQLQuery, SQLEmptyQuery>(m_args, i_orderQuery);
        FilterArg<ISQLQuery, SQLEmptyQuery>(m_args, i_limitQuery);
        m_collection =
			SQLQueryCollections<std::vector<std::shared_ptr<ISQLQuery> > >(m_args, SQLiteStringProcessorBase::SPACE);
    }

    virtual std::string query() const {
        return /*std::move*/(SQLiteStringProcessorBase::DELETE_
                + SQLiteStringProcessorBase::SPACE
                + m_collection.query());
    }

    virtual ISQLQuery* clone() const {
        return new SQLDeleteQuery(*this);
    }

private:
    std::vector<std::shared_ptr<ISQLQuery> > m_args;
    SQLQueryCollections<std::vector<std::shared_ptr<ISQLQuery> > > m_collection;
};

/*! @class SQLDropTableQuery
 *  @brief the class creates query of drop table index
 */
class SQLDropIndexQuery: virtual public ISQLQuery {
public:
    SQLDropIndexQuery(const SQLDropIndexQuery& i_other)
    : m_tableName(i_other.m_tableName) {}

    //TODO moiseenko.a: Add static type check
    SQLDropIndexQuery(const SQLStringExpressionQuery& i_tableName)
    : m_tableName(i_tableName) {}

    virtual std::string query() const {
        return /*std::move*/(SQLiteStringProcessorBase::DROP
                + SQLiteStringProcessorBase::SPACE
                + m_tableName.query());
    }

    virtual ISQLQuery* clone() const {
        return new SQLDropIndexQuery(*this);
    }

private:
    SQLStringExpressionQuery m_tableName;
};

/*! @class SQLDropTableQuery
 *  @brief the class creates query of drop table
 */
class SQLDropTableQuery: virtual public ISQLQuery {
public:
    SQLDropTableQuery(const SQLDropTableQuery& i_other)
    : m_indexName(i_other.m_indexName) {}

    //TODO moiseenko.a: Add static type check
    SQLDropTableQuery(const SQLStringExpressionQuery& i_indexName)
    : m_indexName(i_indexName) {}

    virtual std::string query() const {
        return /*std::move*/(SQLiteStringProcessorBase::DROP
                + makeSpaceBlock(SQLiteStringProcessorBase::INDEX)
                + m_indexName.query());
    }

    virtual ISQLQuery* clone() const {
        return new SQLDropTableQuery(*this);
    }

private:
    SQLStringExpressionQuery m_indexName;
};
/// @}

/// @defgroup FACTORYES Factories of query
/// @{
template<typename ColumnType>
inline std::shared_ptr<ISQLQuery> makeColumnQuery(const std::string& i_columnName, Loki::Type2Type<ColumnType> arg) {
    return std::shared_ptr<ISQLQuery>(new SQLCreatedColumnQuery<ColumnType>(std::string(i_columnName)));
}

inline std::shared_ptr<ISQLQuery> makeColumnQuery(const std::string& i_columnName) {
    return std::shared_ptr<ISQLQuery>(new SQLCreatedColumnQuery<std::string>(std::string(i_columnName)));
}

template<typename ColumnType>
inline std::shared_ptr<ISQLStringExpressionQuery> makeColumnQuery(const std::string& i_columnName,
        Loki::Type2Type<SQLCreatedUniqueColumnQuery<ColumnType> > arg) {
    return std::shared_ptr<ISQLStringExpressionQuery>(new SQLCreatedUniqueColumnQuery<ColumnType>(std::string(i_columnName)));
}

template<class SQLQueryType, template<class> class SQLContainer, template<class> class Container>
SQLContainer<SQLQueryType> makeSQLCollections(Container<SQLQueryType> i_container) {
    return SQLContainer<SQLQueryType>(i_container);
}

template<class SQLQueryType, template<class> class SQLContainer, class Arg1, template<class, class> class Container>
SQLContainer<SQLQueryType> makeSQLCollections(Container<SQLQueryType, Arg1> i_container) {
    return SQLContainer<SQLQueryType>(i_container);
}

template<class SQLQueryType, template<class> class SQLContainer, class Arg1, class Arg2,
	template<class, class, class> class Container>
SQLContainer<SQLQueryType> makeSQLCollections(Container<SQLQueryType, Arg1, Arg2> i_container) {
    return SQLContainer<SQLQueryType>(i_container);
}

template<class SQLQueryType, template<class> class SQLContainer, class Arg1, class Arg2, class Arg3,
	template<class, class, class, class> class Container>
SQLContainer<SQLQueryType> makeSQLCollections(Container<SQLQueryType, Arg1, Arg2, Arg3> i_container) {
    return SQLContainer<SQLQueryType>(i_container);
}

template<class SQLQueryType, template<class> class SQLContainer, class Key, class Arg1, class Arg2,
	template<class, class, class, class> class Container>
SQLContainer<SQLQueryType> makeSQLCollections(Container<Key, SQLQueryType, Arg1, Arg2> i_container) {
    return SQLContainer<SQLQueryType>(i_container);
}
/// @}
/// @}
#endif //SQLITE_STRING_PROCESSOR_BASE_H


text:
using namespace seqan;

int main()
{
    typedef String<AminoAcid> TAminoAcidString;
    TAminoAcidString sourceSeq = "MQDRVKRPMNAFIVWSRDQRRKMALEN";
//![create-string]
//![iterate-and-replace]
    typedef Iterator<TAminoAcidString>::Type TIter;

    TIter itEnd = end(sourceSeq);
    for (TIter it = begin(sourceSeq); it != itEnd; goNext(it))
    {
        if (value(it) == 'R')
            value(it) = 'A';
        std::cout << value(it) << ',';
    }
    std::cout << std::endl;
//![iterate-and-replace]
//![count-occurences]
    typedef Size<TAminoAcidString>::Type TSize;
    typedef String<TSize> TCounterString;
    TCounterString counter;
    TSize alphSize = ValueSize<AminoAcid>::VALUE;
    resize(counter, alphSize, 0);
    for (TIter it = begin(sourceSeq); it != itEnd; goNext(it))
        value(counter, ordValue(value(it))) += 1;
//![count-occurences]
//![frequency-table]
    typedef Iterator<TCounterString>::Type TCounterIter;
    TCounterIter countIt = begin(counter);
    TCounterIter countItEnd = end(counter);
    for (TSize pos = 0; countIt != countItEnd; ++countIt, ++pos)
        std::cout << AminoAcid(pos) << ':' << value(countIt) << std::endl;

    return 0;
}
//![frequency-table]

redpajama_set_name: RedPajamaGithub


text:
<?xml version="1.0" encoding="UTF-8"?>
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="ehcache.xsd" updateCheck="true" monitoring="autodetect" dynamicConfig="true">

	<diskStore path="java.io.tmpdir" />
	<!-- <diskStore path="E:/cachetmpdir" /> -->

	<!--
    name:Cache的唯一标识
    maxElementsInMemory:内存中最大缓存对象数
    maxElementsOnDisk:磁盘中最大缓存对象数,若是0表示无穷大
    eternal:Element是否永久有效,一但设置了,timeout将不起作用
    overflowToDisk:配置此属性,当内存中Element数量达到maxElementsInMemory时,Ehcache将会Element写到磁盘中
    timeToIdleSeconds:设置Element在失效前的允许闲置时间。仅当element不是永久有效时使用,可选属性,默认值是0,也就是可闲置时间无穷大
    timeToLiveSeconds:设置Element在失效前允许存活时间。最大时间介于创建时间和失效时间之间。仅当element不是永久有效时使用,默认是0.,也就是element存活时间无穷大
    diskPersistent:是否缓存虚拟机重启期数据
    diskExpiryThreadIntervalSeconds:磁盘失效线程运行时间间隔,默认是120秒
    diskSpoolBufferSizeMB:这个参数设置DiskStore(磁盘缓存)的缓存区大小。默认是30MB。每个Cache都应该有自己的一个缓冲区
    memoryStoreEvictionPolicy:当达到maxElementsInMemory限制时,Ehcache将会根据指定的策略去清理内存。默认策略是LRU(最近最少使用)。你可以设置为FIFO(先进先出)或是LFU(较少使用)
    -->

	<defaultCache maxElementsInMemory="10000" eternal="false" timeToIdleSeconds="120" timeToLiveSeconds="120" overflowToDisk="true" maxElementsOnDisk="10000000" diskPersistent="false" diskExpiryThreadIntervalSeconds="120" memoryStoreEvictionPolicy="LRU" />

	<cache name="TresourcetypeServiceCache" maxElementsInMemory="10000" maxElementsOnDisk="1000" eternal="false" overflowToDisk="true" diskSpoolBufferSizeMB="20" timeToIdleSeconds="300" timeToLiveSeconds="600" memoryStoreEvictionPolicy="LFU" />
</ehcache>


text:
(function($) {
	$(document).on('ready page:load', function() {
		$('time[data-time-ago]').timeago();
	});
})(jQuery);


text:
function process(image) {
    var resultImage = ImageFactory.buildEmptyImage(image);
    convolution(image, resultImage);
    return resultImage;
}

var xMask = [[1, 0, -1], [2, 0, -2], [1, 0, -1]];
var yMask = [[1, 2, 1], [0, 0, 0], [-1, -2, -1]];

function computePixel(image, channel, x, y) {
    var gradientX = 0;
    var gradientY = 0;
    for (var lx = 0; lx < 3; lx++) {
        for (var ly = 0; ly < 3; ly++) {
            var value = image.get(channel, x + lx - 1, y + ly - 1);
            gradientX += value * xMask[lx][ly];
            gradientY += value * yMask[lx][ly];
        }
    }
    var value = Math.floor(Math.sqrt(Math.pow(gradientX, 2) + Math.pow(gradientY, 2)));
    if (value > image.getPixelValueRange().getHigher()) {
        return image.getPixelValueRange().getHigher();
    }
    return value;
}

function convolution(image, resultImage) {
    for (var channel = 0; channel < image.getChannelCount(); channel++) {
        for (var x = 1; x < image.getWidth() - 1; x++) {
            for (var y = 1; y < image.getHeight() - 1; y++) {
                var newValue = computePixel(image, channel, x, y);
                resultImage.set(channel, x, y, newValue);
            }
        }
    }
}


text:
FactoryGirl.define do
  factory :comment do
    user
    post
    body { Forgery(:lorem_ipsum).words(20) }
  end
end


text:
package com.mortardata.api.v2;

import com.google.api.client.util.GenericData;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Represents the set of arguments needed to request a job run from the Mortar API.
 */
public class JobRequest {

    private String projectName;
    private String scriptName;
    private String gitRef;
    private int clusterSize;
    private boolean notifyOnJobFinish = true;
    private Clusters.ClusterType clusterType = Clusters.ClusterType.PERSISTENT;
    private Map<String, String> parameters = new HashMap<String, String>();
    private boolean isControlScript = false;
    private String clusterId;
    private Boolean isMortarProject;

    /**
     * Construct a Mortar Project JobRequest object for running a job on a new cluster.
     *
     * @param projectName Mortar project name
     * @param scriptName name of script to be run (without path or extension)
     * @param gitRef version of code (git hash or branch) to use
     * @param clusterSize size of hadoop cluster to launch (number of nodes)
     */
    public JobRequest(String projectName, String scriptName, String gitRef, int clusterSize) {
        this.projectName = projectName;
        this.scriptName = scriptName;
        this.gitRef = gitRef;
        this.clusterSize = clusterSize;
        this.isMortarProject = true;
    }

    /**
     * Construct a Mortar Project JobRequest object for running a job on an existing cluster.
     *
     * @param projectName Mortar project name
     * @param scriptName name of script to be run (without path or extension)
     * @param gitRef version of code (git hash or branch) to use
     * @param clusterId id of existing cluster
     */
    public JobRequest(String projectName, String scriptName, String gitRef, String clusterId) {
        this.projectName = projectName;
        this.scriptName = scriptName;
        this.gitRef = gitRef;
        this.clusterId = clusterId;
        this.isMortarProject = true;
    }

    /**
     * Construct a Web Project JobRequest object for running a job on a new cluster.
     *
     * @param scriptName name of script to be run (without path or extension)
     * @param clusterSize size of hadoop cluster to launch (number of nodes)
     */
    public JobRequest(String scriptName, int clusterSize) {
        this.scriptName = scriptName;
        this.clusterSize = clusterSize;
        this.isMortarProject = false;
    }

    /**
     * Construct a Web Project JobRequest object for running a job on an existing cluster.
     *
     * @param scriptName name of script to be run (without path or extension)
     * @param clusterId id of existing cluster
     */
    public JobRequest(String scriptName, String clusterId) {
        this.scriptName = scriptName;
        this.clusterId = clusterId;
        this.isMortarProject = false;
    }

    /**
     * Collect all job arguments into a form compatible with the Mortar API.
     *
     * @return GenericData object populated with all job run arguments
     */
    public GenericData getArguments() {
        GenericData arguments = new GenericData();
        arguments.put("project_name", projectName);
        arguments.put("git_ref", gitRef);
        if (clusterId != null) {
            arguments.put("cluster_id", clusterId);
        } else {
            arguments.put("cluster_type", clusterType.toString());
            arguments.put("cluster_size", clusterSize);
        }
        arguments.put("notify_on_job_finish", notifyOnJobFinish);
        if (isMortarProject) {
            arguments.put("parameters", convertParameters());
            if (isControlScript) {
                arguments.put("controlscript_name", scriptName);
            } else {
                arguments.put("pigscript_name", scriptName);
            }
        } else {
            arguments.put("parameters", parameters);
            arguments.put("script_name", scriptName);
        }
        return arguments;
    }

    /**
     * For all elements of parameters, put them in a form compatible with the Mortar Project API.
     *
     * @return List of Map objects with "name" as the key for the parameter name, and "value"
     * as the key for the parameter value.
     */
    private List<Map<String, String>> convertParameters() {
        List<Map<String, String>> params = new ArrayList<Map<String, String>>();
        for (String s : parameters.keySet()) {
            HashMap<String, String> valMap = new HashMap<String, String>();
            valMap.put("name", s);
            valMap.put("value", parameters.get(s));
            params.add(valMap);
        }
        return params;
    }

    /**
     * Whether the user should be notified via email when the job is complete.
     */
    public boolean isNotifyOnJobFinish() {
        return notifyOnJobFinish;
    }

    /**
     * Set whether the user should be notified via email when the job is complete.  Default is true.
     */
    public void setNotifyOnJobFinish(boolean notifyOnJobFinish) {
        this.notifyOnJobFinish = notifyOnJobFinish;
    }

    /**
     * Cluster type requested for the job, if job is requesting a new cluster.
     */
    public Clusters.ClusterType getClusterType() {
        return clusterType;
    }

    /**
     * Set cluster type if starting a new cluster.  Default is PERSISTENT.
     */
    public void setClusterType(Clusters.ClusterType clusterType) {
        this.clusterType = clusterType;
    }

    /**
     * Parameters for running the script.
     */
    public Map<String, String> getParameters() {
        return parameters;
    }

    /**
     * Set parameters needed for running the script.
     */
    public void setParameters(Map<String, String> parameters) {
        this.parameters = parameters;
    }

    /**
     * Whether the named script is a control script.
     *
     * Mortar Projects ONLY
     */
    public boolean isControlScript() {
        return isControlScript;
    }

    /**
     * Set whether the named script is a control script.  Default is false.
     *
     * Mortar Projects ONLY
     */
    public void setControlScript(boolean controlScript) {
        isControlScript = controlScript;
    }

    /**
     * Cluster id of cluster for the job to run on, if job is using existing cluster.
     */
    public String getClusterId() {
        return clusterId;
    }

    /**
     * Size of hadoop cluster to launch (number of nodes), if launching new cluster.
     */
    public int getClusterSize() {
        return clusterSize;
    }

    /**
     * Version of code (git hash or branch) to use.
     *
     * Mortar Projects ONLY
     */
    public String getGitRef() {
        return gitRef;
    }

    /**
     * Name of the script to be run.
     */
    public String getScriptName() {
        return scriptName;
    }

    /**
     * Name of the Mortar Project being run.
     *
     * Mortar Projects ONLY
     */
    public String getProjectName() {
        return projectName;
    }

    @Override
    public String toString() {
        return "JobRequest [" +
                "projectName='" + projectName + '\'' +
                ", scriptName='" + scriptName + '\'' +
                ", gitRef='" + gitRef + '\'' +
                ", clusterSize=" + clusterSize +
                ", notifyOnJobFinish=" + notifyOnJobFinish +
                ", clusterType=" + clusterType +
                ", parameters=" + parameters +
                ", isControlScript=" + isControlScript +
                ", clusterId='" + clusterId + '\'' +
                ']';
    }
}


text:
<!DOCTYPE HTML>

		<template>

Nice heading coming from template

		</template>

Only this will change color


text:
using System;
using System.Diagnostics;
using System.IO;
using System.Text;
using System.Threading.Tasks;

namespace Cosmos.Build.Builder.BuildTasks
{
    internal abstract class ProcessBuildTaskBase : IBuildTask
    {
        public abstract string Name { get; }

        private bool _waitForExit;
        private bool _createWindow;

        protected ProcessBuildTaskBase(bool waitForExit, bool createWindow)
        {
            _waitForExit = waitForExit;
            _createWindow = createWindow;
        }

        public Task RunAsync(ILogger logger)
        {
            var exePath = GetExePath();
            var args = GetArguments();

            logger.LogMessage($"\"{exePath}\" {args}");

            var process = new Process();
            var processStartInfo = new ProcessStartInfo(exePath, args);

            processStartInfo.CreateNoWindow = !_createWindow;
            processStartInfo.UseShellExecute = false;

            processStartInfo.RedirectStandardError = true;
            processStartInfo.RedirectStandardOutput = true;
            processStartInfo.StandardErrorEncoding = Encoding.UTF8;
            processStartInfo.StandardOutputEncoding = Encoding.UTF8;

            process.StartInfo = processStartInfo;
            process.Start();

            if (_waitForExit)
            {
                var standardOutputReaderTask = Task.Run(() => ReadOutputAsync(process.StandardOutput, logger));
                var standardErrorReaderTask = Task.Run(() => ReadOutputAsync(process.StandardError, logger));

                var waitForExitTask = Task.Run(() => WaitForExit(process));

                return Task.WhenAll(waitForExitTask, standardOutputReaderTask, standardErrorReaderTask);
            }

            return Task.CompletedTask;
        }

        protected abstract string GetExePath();
        protected abstract string GetArguments();

        private void WaitForExit(Process process)
        {
            process.WaitForExit();

            if (process.ExitCode != 0)
            {
                throw new Exception("The process failed to execute!");
            }
        }

        private async Task ReadOutputAsync(StreamReader reader, ILogger logger)
        {
            while (true)
            {
                var line = await reader.ReadLineAsync().ConfigureAwait(false);

                if (line == null)
                {
                    return;
                }

                logger.LogMessage(line);
            }
        }
    }
}


text:
package observer.data_modification_listener;

import java.util.ArrayList;
import java.util.List;

// Someone who says "Hello"
// Someone who says update "Data"
class Initiator implements HelloSpeaker, DataUpdater {

    private List<HelloListener> helloListeners = new ArrayList<HelloListener>();
    private List<DataListener> dataListeners = new ArrayList<DataListener>();

    private float temperature;
    private float humidity;
    private float pressure;

    @Override
    public void registerListener(HelloListener toAdd) {
        helloListeners.add(toAdd);
    }

    @Override
    public void removeListener(HelloListener toRemove) {
        helloListeners.remove(toRemove);
    }

    @Override
    public void sayHello() {
        System.out.println(this.getClass().getSimpleName() + "----> Hello!!");

        // Notify everybody that may be interested.
        for (HelloListener hl : helloListeners)
            hl.someoneSaidHello();
    }

    public void setMeasurements(float temperature, float humidity, float pressure) {
        System.out.println(this.getClass().getSimpleName() + "----> Changed data! " + temperature + " - " + humidity + " - " + pressure);
        this.temperature = temperature;
        this.humidity = humidity;
        this.pressure = pressure;
        measurementsChanged();
    }

    public void measurementsChanged() {
        updateData();
    }

    @Override
    public void registerListener(DataListener toAdd) {
        dataListeners.add(toAdd);
    }

    @Override
    public void removeListener(DataListener toRemove) {
        dataListeners.remove(toRemove);
    }

    @Override
    public void updateData() {
        for (DataListener listener : dataListeners) {
            listener.someoneUpdateData(temperature, humidity, pressure);
        }
    }
}


text:
package com.lostcode.javalib.entities.events.processes;

import com.lostcode.javalib.entities.Entity;
import com.lostcode.javalib.entities.events.EventCallback;
import com.lostcode.javalib.entities.processes.Process;
import com.lostcode.javalib.entities.processes.ProcessState;

/**
 * @author William The callback for ending processes.
 */
public class EndProcessCallback implements EventCallback {

	/**
	 * Initializes the callback with a process to be ended.
	 *
	 * @param callbackProcess
	 *            The internal process which will be ended once the callback is
	 *            invoked
	 * @param endState
	 *            The state with which the process will be ended
	 */
	public EndProcessCallback(Process callbackProcess, ProcessState endState) {
		this.callbackProcess = callbackProcess;
		this.endState = endState;
	}

	/** The internal process which will be ended once the callback is invoked. */
	private Process callbackProcess;

	/** The state with which the process will be ended */
	private ProcessState endState;

	@Override
	public void invoke(Entity e, Object... args) {
		// End the process with a state.
		callbackProcess.end(endState);

	}

}


text:
angular.module('components.jquery-ui-css', []).
	directive('tabs', function() {
		return {
			restrict: 'E',
			transclude: true,
			scope: {},
			controller: function($scope, $element) {
				var panes = $scope.panes = [];

				$scope.select = function(pane) {
					angular.forEach(panes, function(pane) {
					pane.selected = false;
					});
					pane.selected = true;
				};

				this.addPane = function(pane) {
					if (panes.length === 0) {
						$scope.select(pane);
					}
					panes.push(pane);
				};
			},
			template:
				'
' +
					'
' +
						'
' +
							' {{pane.heading}}' +
						'
' +
					'
' +
					'

' +
				'
',
			replace: true
		};
	}).
	directive('pane', function() {
		return {
			require: '^tabs',
			restrict: 'E',
			transclude: true,
			scope: {
				heading: '@',
				icon: '@'
			},
			link: function(scope, element, attrs, tabsCtrl) {
				tabsCtrl.addPane(scope);
			},
			template:
				'
' +
				'
',
			replace: true
		};
	}).
	directive('accordion', function() {
		return {
			restrict: 'E',
			transclude: true,
			scope: {},
			controller: function($scope, $element) {
				var panes = $scope.panes = [];

				this.addPane = function(pane) {
					if (panes.length === 0) {
						pane.selected = true;
					}
					panes.push(pane);
				};

				this.togglePane = function(pane) {
					var toggleState = !pane.selected;
					angular.forEach(panes, function(pane) {
						pane.selected = false;
					});
					pane.selected = toggleState;
				};
			},
			template:
				'
' +
				'
',
			replace: true
		};
	}).
	directive('accordionGroup', function() {
		return {
			require: '^accordion',
			restrict: 'E',
			transclude: true,
			scope: {
				heading: '@',
				hide: '@'
			},
			link: function(scope, element, attrs, accordionCtrl) {
				if(!scope.hide) {
					scope.hide = false;
				}
				accordionCtrl.addPane(scope);
				scope.toggle = function() {
					accordionCtrl.togglePane(scope);
				};
			},
			template:
				'
' +
					'
' +
					'' +
					'{{heading}}' +
					'
' +
					'
' +
					'
' +
				'
',
			replace: true
		};
	})
	.directive('smallButton', function() {
		return {
			restrict: 'E',
			transclude: true,
			scope: {
				text: '@',
				tooltip: '@',
				iconClass: '@',
				clickEvent: '&',
			},
			link: function(scope, element, attrs, accordionCtrl) {
				scope.active = false;
				scope.clickButton = function() {
					scope.clickEvent();
				};
				scope.hover = function(active) {
					scope.active = active;
				};
			},
			template:
				'<button title="{{ tooltip }}" ng-click="clickButton()" ng-mouseover="hover(true)" ng-mouseout="hover(false)"' +
					' class="ui-button ui-widget ui-state-default ui-corner-all ui-button-icon-only" ng-class="{\'ui-state-hover\' : active}">' +
					'' +
					'{{ text }}' +
				'</button>',
			replace: true
		};
	});


text:
						Name

						<input data-bind="dotvvm-textbox-text: Name" id="Name__input" onchange="dotvvm.postBack(this,["$parent.Entity"],"AjiQtOSjw+ymqfXh","",null,["timeout","suppressOnUpdating"],[],undefined).catch(dotvvm.log.logPostBackScriptError);event.stopPropagation();return false;" type="text">

						Email

						<input data-bind="dotvvm-textbox-text: Email" id="Email__input" required="required" type="email">

						Sometime

						Nah, I'm lazy and we don't support date times

						Age

						<input data-bind="dotvvm-textbox-text: Age" id="Age__input" max="150" min="0" type="number">


text:
ACCEPTED

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Bowditch, R. D. , Baumann, L. , and Baumann, P. "Description of Oceanospirillum kriegii sp. nov. and O. jannaschii sp. nov. and assignment of two species of Alteromonas to this genus as O. commune comb. nov. and O. vagum comb. nov. " Curr. Microbiol. (1984) 10:221-230.

#### Original name
null

### Remarks
null


text:
<?php
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/

Route::group(
    ['namespace' => 'Agrigender\Account\Auth'],
    function () {
        Route::get('/login', 'LoginController@showLoginForm')->name('login');
        Route::post('/login', 'LoginController@login');
        Route::get('/register', 'RegisterController@showRegistrationForm')->name('register');
        Route::post('/register', 'RegisterController@register');
        Route::post('logout', 'LoginController@logout')->name('logout');
        // Password reset link request routes...
        Route::get('password/email', 'ForgotPasswordController@showLinkRequestForm')->name('password.email');
        Route::post('password/email', 'ForgotPasswordController@sendResetLinkEmail');
        // Password reset routes...
        Route::get('password/reset/', 'ResetPasswordController@showResetForm')->name('password.request');
        Route::post('password/reset', 'ResetPasswordController@postReset')->name('password.reset');
    }
);

Route::group(
    ['namespace' => 'Agrigender\Publishing'],
    function () {
        Route::get('/', 'PublicationController@latestIssue')->name('latest-issue');
        Route::get('/publication/{slug}', 'PublicationController@fullPublication')->name('publication');
        Route::get('/download/publication/{id}', 'PublicationController@downloadPublication')->name('download');
        Route::get('/previous-issue', 'PublicationController@previousIssue')->name('previous-issue');
    }
);
Route::group(
    ['namespace' => 'Agrigender\Account'],
    function () {
        Route::get('/contacts', 'UserController@contactUs')->name('contacts');
        Route::get('/guidelines', 'UserController@authorGuideline')->name('guidelines');
        Route::get('/aims-and-scope', 'UserController@aimsAndScope')->name('scope');
        Route::get('/note-for-reviewers', 'UserController@noteForReviewers')->name('note-reviewers');
        Route::get('/editorial-board', 'UserController@editorialBoard')->name('editorial');
        Route::get('/special-issue', 'UserController@specialIssue')->name('special-issue');
        Route::get('/all-issue', 'UserController@allIssue')->name('all-issue');
    }
);
Route::group(
    ['prefix' => 'user'],
        function () {
            Route::group(
                ['namespace' => 'Agrigender\Account'],
                function () {
                    /* Main user account */
                    Route::get('/home', 'UserController@index')->name('home');
                    /*Edit Profile*/
                    Route::get('/edit/{id}', 'UserController@editProfile');
                    Route::post('/edit', 'UserController@postEditProfile')->name('post-edit');
                }
            );
            Route::group(
                ['namespace' => 'Agrigender\Publishing'],
                function () {
                    /* Publication submission*/
                    Route::get('/submit-paper', 'PublicationController@submitPaperPage')->name('submit-paper');
                    Route::post('/submit-paper', 'PublicationController@submitPaper')->name('submit-paper-post');
                }
            );
        }
);

Route::namespace('Agrigender\Account\Reviewer')
    ->middleware('reviewer.auth')
    ->prefix('reviewer')
    ->group(
        function () {
            /* Main reviewer account */
            Route::get('/home', 'ReviewerController@index')->name('reviewer');
            Route::get('/papers', 'ReviewerController@revisions')->name('revisions');
            Route::get('/papers/unrevised', 'ReviewerController@forRevision')->name('for-revision');
            Route::get('/papers/{pid}/submit-revision', 'ReviewerController@submitRevision')->name('submit-revision');
            /* Accept paper assignment*/
            Route::post('/paper/accept', 'ReviewerController@acceptAssignment');
            Route::post('/paper/decline', 'ReviewerController@declineAssignment');
            /*Download Main Text*/
            Route::get('/download/main-text/{id}', 'ReviewerController@downloadMaintext')->name('download-main-text');
            /*Download Tables*/
            Route::get('/download/tables/{id}', 'ReviewerController@downloadTables')->name('download-tables');
            /*Download Figures*/
            Route::get('/download/figures/{id}', 'ReviewerController@downloadFigures')->name('download-figures');

            /*Submit Feedback*/
            Route::post('/submit/feedback', 'ReviewerController@submitFeedback')->name('feedback');
        }
    );

Route::namespace('Agrigender\Account\Editor')
    ->prefix('admin')
    ->middleware('admin.auth')
    ->group(
    function () {
        /* Main admin account */
        Route::get('/home', 'EditorController@index')->name('admin');
        /* Setup Volume*/
        Route::get('/setup/volume', 'EditorController@getVolumes')->name('setup.volume.get');
        /* Registered Authors */
        Route::get('/authors', 'EditorController@authors')->name('authors');
        /* Registered Non-Authors */
        Route::get('/members', 'EditorController@members')->name('members');
        /* Registered Reviewers */
        Route::get('reviewers', 'EditorController@reviewers')->name('reviewers');
        /* Unpublished Papers */
        Route::get('/papers/unpublished', 'EditorController@unpublished')->name('unpublished');
        /* Rejected Papers */
        Route::get('/papers/unpublished/rejected', 'EditorController@rejected')->name('rejected');
        /* Assign Papers */
        Route::get('/papers/unpublished/assign', 'EditorController@forAssignment')->name('assign');
        /* Published Papers */
        Route::get('/papers/published', 'EditorController@published')->name('published');
        /* Deny submitted-unplublished paper */
        Route::post('/papers/unpublished/deny', 'EditorController@denyPaper');
        /* Accept submitted-unplublished paper */
        Route::post('/papers/unpublished/accept', 'EditorController@acceptPaper');
        /*Pick reviewer*/
        Route::get('/papers/{id}/pick-reviewer', 'EditorController@pickReviewer');
        Route::post('/papers/unpublished/assign/set-reviewer', 'EditorController@setReviewer');
        /* Setup paper ready for review */
        Route::post('/papers/unpublished/assign/setup', 'EditorController@setupPaper');
        /* Setup paper metadata then return reviewers for assignment*/
        Route::post('/papers/unpublished/assign/setup/metadata', 'EditorController@setupPaperMetaData');
        /* Confirm authorship order */
        Route::post('/papers/unpublished/assign/setup/order', 'EditorController@confirmOrder');
    }
    );


text:
class help {
	file = "core\modules\rmm_help";
	class functions {
		class display {};
		class onload {};
	};
};


text:
package views.changekeeper

import composition.TestHarness
import helpers.changekeeper.CookieFactoryForUISpecs
import org.openqa.selenium.{By, WebElement, WebDriver}
import org.scalatest.selenium.WebBrowser.{click, currentUrl, go}
import pages.changekeeper.{BeforeYouStartPage, VrmLockedPage}
import pages.changekeeper.VrmLockedPage.exit
import uk.gov.dvla.vehicles.presentation.common.testhelpers.{UiSpec, UiTag}

class VrmLockedUiSpec extends UiSpec with TestHarness {

  "go to page" should {
    "display the page" taggedAs UiTag in new WebBrowserForSelenium {
      go to BeforeYouStartPage
      cacheSetup
      go to VrmLockedPage

      currentUrl should equal(VrmLockedPage.url)
    }

    "contain the hidden csrfToken field" taggedAs UiTag in new WebBrowserForSelenium {
      go to VrmLockedPage
      val csrf: WebElement = webDriver.findElement(
        By.name(uk.gov.dvla.vehicles.presentation.common.filters.CsrfPreventionAction.TokenName)
      )
      csrf.getAttribute("type") should equal("hidden")
      csrf.getAttribute("name") should
        equal(uk.gov.dvla.vehicles.presentation.common.filters.CsrfPreventionAction.TokenName)
      csrf.getAttribute("value").length > 0 should equal(true)
    }

    "contain the time of locking" taggedAs UiTag in new WebBrowserForSelenium {
      go to BeforeYouStartPage
      cacheSetup
      go to VrmLockedPage
      val localTime: WebElement = webDriver.findElement(By.id("localTimeOfVrmLock"))
      localTime.isDisplayed should equal(true)
      localTime.getText should include regex "^(\\d|0\\d|1\\d|2[0-3]):[0-5]\\d".r
    }

    "contain the time of locking when JavaScript is disabled" taggedAs UiTag in new WebBrowserWithJsDisabled {
      go to BeforeYouStartPage
      cacheSetup
      go to VrmLockedPage
      val localTime: WebElement = webDriver.findElement(By.id("localTimeOfVrmLock"))
      localTime.isDisplayed should equal(true)
      localTime.getText should include regex "^(\\d|0\\d|1\\d|2[0-3]):[0-5]\\d".r
    }
  }

  "exit button" should {
    "redirect to feedback page" taggedAs UiTag in new WebBrowserForSelenium {
      go to BeforeYouStartPage
      cacheSetup()
      go to VrmLockedPage
      click on exit
      currentUrl should equal(BeforeYouStartPage.url)
    }
  }

  def cacheSetup()(implicit driver: WebDriver): Unit =
    CookieFactoryForUISpecs.
      vehicleAndKeeperDetails().
      bruteForcePreventionViewModel()
}


text:
.. _getting_started:

Getting Started Guide
#####################

Use this guide to get started with your :ref:`Zephyr <introducing_zephyr>`
development.

Set Up the Development Environment
**********************************

The Zephyr project supports these operating systems:

* Linux
* Mac OS
* Windows 8.1

Use the following procedures to create a new development environment.

.. toctree::
   :maxdepth: 1

   installation_linux.rst
   installation_mac.rst
   installation_win.rst

Checking Out the Source Code Anonymously
========================================

The code is hosted in a GitHub repo that supports
anonymous cloning via git.

To clone the repository anonymously, enter:

.. code-block:: console

   $ git clone https://github.com/zephyrproject-rtos/zephyr.git

You have successfully checked out a copy of the source code to your local
machine.

Building and Running an Application
***********************************

Using the 'Hello World' sample application as a base model, the following
section will describe the pieces necessary for creating a Zephyr application.

The processes to build and run a Zephyr application are the same across
operating systems. Nevertheless, the commands needed do differ from one OS to
the next. The following sections contain the commands used in a Linux
development environment. If you are using Mac OS please use the appropriate
commands for your OS.

Building a Sample Application
=============================

To build an example application follow these steps:

#. Make sure your environment is setup by exporting the following environment
   variables. When using the Zephyr SDK on Linux for example, type:

   .. code-block:: console

      $ export ZEPHYR_GCC_VARIANT=zephyr
      $ export ZEPHYR_SDK_INSTALL_DIR=<sdk installation directory>

#. Navigate to the main project directory:

   .. code-block:: console

      $ cd zephyr-project

#. Source the project environment file to set the project environment
   variables:

   .. code-block:: console

      $ source zephyr-env.sh

#. Build the :ref:`hello_world` example project, enter:

   .. code-block:: console

      $ cd $ZEPHYR_BASE/samples/hello_world
      $ make

The above invocation of make will build the :ref:`hello_world` sample application
using the default settings defined in the application's Makefile. You can
build for a different board by defining the variable BOARD with one of the
supported boards, for example:

.. code-block:: console

   $ make BOARD=arduino_101

For further information on the supported boards go see
:ref:`here <boards>`. Alternatively, run the following command to obtain a list
of the supported boards:

.. code-block:: console

   $ make help

Sample projects for different features of the project are available at
at :file:`$ZEPHYR_BASE/samples`.
After building an application successfully, the results can be found in the
:file:`outdir` sub-directory under the application root directory, in a
subdirectory that matches the BOARD string.

The ELF binaries generated by the build system are named by default
:file:`zephyr.elf`. This value can be overridden in the application
configuration The build system generates different names for different use cases
depending on the hardware and boards used.

.. _third_party_x_compilers:

Using Custom and 3rd Party Cross Compilers
==========================================

The Zephyr SDK is provided for convenience and ease of use. It provides
cross-compilers for all ports supported by the Zephyr OS and does not require
any extra flags when building applications or running tests.

If you have a custom cross-compiler or if you wish to use a vendor provided SDK,
follow the steps below to build with any custom or 3rd party cross-compilers:

#. To avoid any conflicts with the Zephyr SDK, enter the following commands.

   .. code-block:: console

      $ unset ZEPHYR_GCC_VARIANT
      $ unset ZEPHYR_SDK_INSTALL_DIR

#. We will use the `GCC ARM Embedded`_ compiler for this example, download the
   package suitable for your operating system from the `GCC ARM Embedded`_ website
   and extract it on your file system. This example assumes the compiler was
   extracted to: :file:`~/gcc-arm-none-eabi-5_3-2016q1/`.

#. Navigate to the main project directory:

   .. code-block:: console

      $ cd zephyr-project

#. Source the project environment file to set the project environment
   variables:

   .. code-block:: console

      $ source zephyr-env.sh

#. Build the example :ref:`hello_world` project and make sure you supply the
   CROSS_COMPILE on the command line, enter:

   .. code-block:: console

      $ export GCCARMEMB_TOOLCHAIN_PATH="~/gcc-arm-none-eabi-5_3-2016q1/"
      $ export ZEPHYR_GCC_VARIANT=gccarmemb
      $ cd $ZEPHYR_BASE/samples/hello_world
      $ make CROSS_COMPILE=~/gcc-arm-none-eabi-5_3-2016q1/bin/arm-none-eabi- BOARD=arduino_due

The above will build the sample using the toolchain downloaded from
`GCC ARM Embedded`_.

Alternatively, you can use the existing support for GCC ARM Embedded:

   .. code-block:: console

      $ export GCCARMEMB_TOOLCHAIN_PATH="~/gcc-arm-none-eabi-5_3-2016q1/"
      $ export ZEPHYR_GCC_VARIANT=gccarmemb
      $ cd zephyr-project
      $ source zephyr-env.sh
      $ cd $ZEPHYR_BASE/samples/hello_world
      $ make BOARD=arduino_due

Running a Sample Application in QEMU
====================================

To perform rapid testing of an application in the development environment you
can use the qemu emulation board configuration available for both X86 and ARM
Cortex-M3 architectures. This can be easily accomplished by calling a special
target when building an application that invokes QEMU once the build process is
completed.

To run an application using the x86 emulation board configuration (qemu_x86),
type:

.. code-block:: console

   $ make BOARD=qemu_x86 run

To run an application using the ARM qemu_cortex_m3 board configuration, type:

.. code-block:: console

   $ make BOARD=qemu_cortex_m3 run

QEMU is not supported on all boards and SoCs. When developing for a specific
hardware target you should always test on the actual hardware and should not
rely on testing in the QEMU emulation environment only.

.. _GCC ARM Embedded: https://launchpad.net/gcc-arm-embedded


text:
import template from './signup.html';

export default {
  template,
  bindings: {
    success: '&'
  },
  controller
};

controller.$inject = ['userService'];

function controller(userService){
  this.buttonText = 'Sign Up';
  this.error = '';
  this.credentials = {
    name: '',
    email: '',
    password: ''
  };

  this.authenticate = ()=>{
    this.buttonText = 'Processing';
    this.error = '';
    return userService.signup(this.credentials)
      .then(()=>{
        this.success();
        return true;
      })
      .catch(error=>{
        this.buttonText = 'Sign Up';
        this.error = error;
        return false;
      });
  };

}