text:
// Copyright (c) 2018-2022 Dr. Colin Hirsch and Daniel Frey
// Please see LICENSE for license or visit https://github.com/taocpp/PEGTL/

#include <algorithm>
#include <exception>
#include <iomanip>
#include <iostream>
#include <iterator>
#include <map>
#include <set>
#include <sstream>
#include <string>
#include <utility>
#include <vector>

#include <cassert>
#include <cctype>
#include <cstdlib>

#if defined( _MSC_VER )
#include <string.h>
#define TAO_PEGTL_STRCASECMP _stricmp
#else
#include <strings.h>
#define TAO_PEGTL_STRCASECMP strcasecmp
#endif

#include <tao/pegtl.hpp>
#include <tao/pegtl/contrib/abnf.hpp>
#include <tao/pegtl/contrib/parse_tree.hpp>

namespace TAO_PEGTL_NAMESPACE
{
   namespace abnf
   {
      using node_ptr = std::unique_ptr< parse_tree::node >;

      namespace
      {
         std::string prefix = "tao::pegtl::";

         std::set< std::string > keywords = {
            "alignas",
            "alignof",
            "and",
            "and_eq",
            "asm",
            "auto",
            "bitand",
            "bitor",
            "bool",
            "break",
            "case",
            "catch",
            "char",
            "char8_t",
            "char16_t",
            "char32_t",
            "class",
            "compl",
            "concept",
            "const",
            "consteval",
            "constexpr",
            "constinit",
            "const_cast",
            "continue",
            "co_await",
            "co_return",
            "co_yield",
            "decltype",
            "default",
            "delete",
            "do",
            "double",
            "dynamic_cast",
            "else",
            "enum",
            "explicit",
            "export",
            "extern",
            "false",
            "float",
            "for",
            "friend",
            "goto",
            "if",
            "inline",
            "int",
            "long",
            "mutable",
            "namespace",
            "new",
            "noexcept",
            "not",
            "not_eq",
            "nullptr",
            "operator",
            "or",
            "or_eq",
            "private",
            "protected",
            "public",
            "register",
            "reinterpret_cast",
            "return",
            "requires",
            "short",
            "signed",
            "sizeof",
            "static",
            "static_assert",
            "static_cast",
            "struct",
            "switch",
            "template",
            "this",
            "thread_local",
            "throw",
            "true",
            "try",
            "typedef",
            "typeid",
            "typename",
            "union",
            "unsigned",
            "using",
            "virtual",
            "void",
            "volatile",
            "wchar_t",
            "while",
            "xor",
            "xor_eq"
         };

         using rules_t = std::vector< std::string >;
         rules_t rules_defined;
         rules_t rules;

         // clang-format off
         struct one_tag {};
         struct string_tag {};
         struct istring_tag {};
         // clang-format on

         rules_t::reverse_iterator find_rule( rules_t& r, const std::string& v, const rules_t::reverse_iterator& rbegin )
         {
            return std::find_if( rbegin, r.rend(), [ & ]( const rules_t::value_type& p ) { return TAO_PEGTL_STRCASECMP( p.c_str(), v.c_str() ) == 0; } );
         }

         rules_t::reverse_iterator find_rule( rules_t& r, const std::string& v )
         {
            return find_rule( r, v, r.rbegin() );
         }

         bool append_char( std::string& s, const char c )
         {
            if( !s.empty() ) {
               s += ", ";
            }
            s += '\'';
            if( c == '\'' || c == '\\' ) {
               s += '\\';
            }
            s += c;
            s += '\'';
            return std::isalpha( c ) != 0;
         }

         std::string remove_leading_zeroes( const std::string& v )
         {
            const auto pos = v.find_first_not_of( '0' );
            if( pos == std::string::npos ) {
               return "";
            }
            return v.substr( pos );
         }

         void shift( internal::iterator& it, int delta )
         {
            it.data += delta;
            it.byte += delta;
            it.column += delta;
         }

      }  // namespace

      namespace grammar
      {
         // ABNF grammar according to RFC 5234, updated by RFC 7405, with
         // the following differences:
         //
         // To form a C++ identifier from a rulename, all minuses are
         // replaced with underscores.
         //
         // As C++ identifiers are case-sensitive, we remember the "correct"
         // spelling from the first occurrence of a rulename, all other
         // occurrences are automatically changed to that.
         //
         // Certain rulenames are reserved as their equivalent C++ identifier is
         // reserved as a keyword, an alternative token, by the standard or
         // for other, special reasons.
         //
         // When using numerical values (num-val, repeat), the values
         // must be in the range of the corresponding C++ data type.
         //
         // Remember we are defining a PEG, not a CFG. Simply copying some
         // ABNF from somewhere might lead to surprising results as the
         // alternations are now sequential, using the sor<> rule.
         //
         // PEGs also require two extensions: The and-predicate and the
         // not-predicate. They are expressed by '&' and '!' respectively,
         // being allowed (optionally, only one of them) before the
         // repetition. You can use braces for more complex expressions.
         //
         // Finally, instead of the pre-defined CRLF sequence, we accept
         // any type of line ending as a convenience extension.

         // clang-format off
         struct CRLF : sor< abnf::CRLF, CR, LF > {};

         struct comment_cont : until< CRLF, sor< WSP, VCHAR > > {};
         struct comment : seq< one< ';' >, comment_cont > {};
         struct c_nl : sor< comment, CRLF > {};
         struct req_c_nl : c_nl {};
         struct c_wsp : sor< WSP, seq< c_nl, WSP > > {};

         struct rulename : seq< ALPHA, star< ranges< 'a', 'z', 'A', 'Z', '0', '9', '-' > > > {};

         struct quoted_string_cont : until< DQUOTE, print > {};
         struct quoted_string : seq< DQUOTE, quoted_string_cont > {};
         struct case_insensitive_string : seq< opt< istring< '%', 'i' > >, quoted_string > {};
         struct case_sensitive_string : seq< istring< '%', 's' >, quoted_string > {};
         struct char_val : sor< case_insensitive_string, case_sensitive_string > {};

         struct prose_val_cont : until< one< '>' >, print > {};
         struct prose_val : seq< one< '<' >, prose_val_cont > {};

         template< char First, typename Digit >
         struct gen_val
         {
            struct value : plus< Digit > {};
            struct range : seq< one< '-' >, value > {};
            struct next_value : seq< value > {};
            struct type : seq< istring< First >, value, sor< range, star< one< '.' >, next_value > > > {};
         };

         using hex_val = gen_val< 'x', HEXDIG >;
         using dec_val = gen_val< 'd', DIGIT >;
         using bin_val = gen_val< 'b', BIT >;

         struct num_val_choice : sor< bin_val::type, dec_val::type, hex_val::type > {};
         struct num_val : seq< one< '%' >, num_val_choice > {};

         struct alternation;
         struct option_close : one< ']' > {};
         struct option : seq< one< '[' >, pad< alternation, c_wsp >, option_close > {};
         struct group_close : one< ')' > {};
         struct group : seq< one< '(' >, pad< alternation, c_wsp >, group_close > {};
         struct element : sor< rulename, group, option, char_val, num_val, prose_val > {};

         struct repeat : sor< seq< star< DIGIT >, one< '*' >, star< DIGIT > >, plus< DIGIT > > {};
         struct repetition : seq< opt< repeat >, element > {};
         struct req_repetition : seq< repetition > {};

         struct and_predicate : seq< one< '&' >, req_repetition > {};
         struct not_predicate : seq< one< '!' >, req_repetition > {};
         struct predicate : sor< and_predicate, not_predicate, repetition > {};

         struct concatenation : list< predicate, plus< c_wsp > > {};
         struct alternation : list< concatenation, pad< one< '/' >, c_wsp > > {};

         struct defined_as_op : sor< string< '=', '/' >, one< '=' > > {};
         struct defined_as : pad< defined_as_op, c_wsp > {};
         struct rule : seq< seq< rulename, defined_as, alternation >, star< c_wsp >, req_c_nl > {};
         struct rulelist : until< eof, sor< seq< star< c_wsp >, c_nl >, rule > > {};
         // clang-format on

      }  // namespace grammar

#if defined( __cpp_exceptions )
      // Using must_if<> we define a control class which is used for
      // the parsing run instead of the default control class.
      //
      // This improves the errors reported to the user.
      //
      // The following turns local errors into global errors, i.e.
      // if one of the rules for which a custom error message is
      // defined fails, it throws a parse_error exception (aka global
      // failure) instead of returning false (aka local failure).

      // clang-format off
      template< typename > inline constexpr const char* error_message = nullptr;

      template<> inline constexpr auto error_message< abnf::grammar::comment_cont > = "unterminated comment";

      template<> inline constexpr auto error_message< abnf::grammar::quoted_string_cont > = "unterminated string (missing '\"')";
      template<> inline constexpr auto error_message< abnf::grammar::prose_val_cont > = "unterminated prose description (missing '>')";

      template<> inline constexpr auto error_message< abnf::grammar::hex_val::value > = "expected hexadecimal value";
      template<> inline constexpr auto error_message< abnf::grammar::dec_val::value > = "expected decimal value";
      template<> inline constexpr auto error_message< abnf::grammar::bin_val::value > = "expected binary value";
      template<> inline constexpr auto error_message< abnf::grammar::num_val_choice > = "expected base specifier (one of 'bBdDxX')";

      template<> inline constexpr auto error_message< abnf::grammar::option_close > = "unterminated option (missing ']')";
      template<> inline constexpr auto error_message< abnf::grammar::group_close > = "unterminated group (missing ')')";

      template<> inline constexpr auto error_message< abnf::grammar::req_repetition > = "expected element";
      template<> inline constexpr auto error_message< abnf::grammar::concatenation > = "expected element";
      template<> inline constexpr auto error_message< abnf::grammar::alternation > = "expected element";

      template<> inline constexpr auto error_message< abnf::grammar::defined_as > = "expected '=' or '=/'";
      template<> inline constexpr auto error_message< abnf::grammar::req_c_nl > = "unterminated rule";
      template<> inline constexpr auto error_message< abnf::grammar::rule > = "expected rule";
      // clang-format on

      struct error
      {
         template< typename Rule >
         static constexpr auto message = error_message< Rule >;
      };

      template< typename Rule >
      using control = must_if< error >::control< Rule >;
#else
      template< typename Rule >
      using control = normal< Rule >;
#endif

      // Since we are going to generate a parse tree, we define a
      // selector that decides which rules will be included in our
      // parse tree, which rules will be omitted from the parse tree,
      // and which of the nodes will store the matched content.
      // Additionally, some nodes will fold when they have exactly
      // one child node. (see fold_one below)

      template< typename Rule >
      struct selector
         : parse_tree::selector<
              Rule,
              parse_tree::store_content::on<
                 grammar::rulename,
                 grammar::prose_val,
                 grammar::hex_val::value,
                 grammar::dec_val::value,
                 grammar::bin_val::value,
                 grammar::hex_val::range,
                 grammar::dec_val::range,
                 grammar::bin_val::range,
                 grammar::hex_val::type,
                 grammar::dec_val::type,
                 grammar::bin_val::type,
                 grammar::repeat,
                 grammar::defined_as_op >,
              parse_tree::remove_content::on<
                 grammar::option,
                 grammar::and_predicate,
                 grammar::not_predicate,
                 grammar::rule >,
              parse_tree::fold_one::on<
                 grammar::alternation,
                 grammar::group,
                 grammar::repetition,
                 grammar::concatenation > >
      {};

      // Besides the above "simple" list of selected rules,
      // we also provide special handling to some nodes.
      // When they are inserted into the parse tree, the
      // transform method allows additional tree transformations
      // in order to improve the generated tree.

      template<>
      struct selector< grammar::quoted_string >
         : std::true_type
      {
         template< typename... States >
         static void transform( node_ptr& n )
         {
            shift( n->m_begin, 1 );
            shift( n->m_end, -1 );

            const auto content = n->string_view();
            for( const auto c : content ) {
               if( std::isalpha( c ) != 0 ) {
                  n->set_type< istring_tag >();
                  return;
               }
            }
            if( content.size() == 1 ) {
               n->set_type< one_tag >();
            }
            else {
               n->set_type< string_tag >();
            }
         }
      };

      template<>
      struct selector< grammar::case_sensitive_string >
         : std::true_type
      {
         template< typename... States >
         static void transform( node_ptr& n )
         {
            n = std::move( n->children.back() );
            if( n->string_view().size() == 1 ) {
               n->set_type< one_tag >();
            }
            else {
               n->set_type< string_tag >();
            }
         }
      };

      std::string to_string( const node_ptr& n );
      std::string to_string( const std::vector< node_ptr >& v );

      std::string to_string_unwrap_seq( const node_ptr& n )
      {
         if( n->is_type< grammar::group >() || n->is_type< grammar::concatenation >() ) {
            return to_string( n->children );
         }
         return to_string( n );
      }

      namespace
      {
         std::string get_rulename( const node_ptr& n )
         {
            assert( n->is_type< grammar::rulename >() );
            std::string v = n->string();
            std::replace( v.begin(), v.end(), '-', '_' );
            return v;
         }

         std::string get_rulename( const node_ptr& n, const bool print_forward_declarations )
         {
            std::string v = get_rulename( n );
            const auto it = find_rule( rules, v );
            if( it != rules.rend() ) {
               return *it;
            }
            if( keywords.count( v ) != 0 || v.find( "__" ) != std::string::npos ) {
#if defined( __cpp_exceptions )
               throw parse_error( '\'' + n->string() + "' is a reserved rulename", n->begin() );
#else
               std::cerr << '\'' + n->string() + "' is a reserved rulename" << std::endl;
               std::terminate();
#endif
            }
            if( print_forward_declarations && find_rule( rules_defined, v ) != rules_defined.rend() ) {
               std::cout << "struct " << v << ";\n";
            }
            rules.push_back( v );
            return v;
         }

         template< typename T >
         std::string gen_val( const node_ptr& n )
         {
            if( n->children.size() == 2 ) {
               if( n->children.back()->is_type< T >() ) {
                  return prefix + "range< " + to_string( n->children.front() ) + ", " + to_string( n->children.back()->children.front() ) + " >";
               }
            }
            if( n->children.size() == 1 ) {
               return prefix + "one< " + to_string( n->children ) + " >";
            }
            return prefix + "string< " + to_string( n->children ) + " >";
         }

         struct ccmp
         {
            bool operator()( const std::string& lhs, const std::string& rhs ) const noexcept
            {
               return TAO_PEGTL_STRCASECMP( lhs.c_str(), rhs.c_str() ) < 0;
            }
         };

         std::map< std::string, parse_tree::node*, ccmp > previous_rules;

      }  // namespace

      template<>
      struct selector< grammar::rule >
         : std::true_type
      {
         template< typename... States >
         static void transform( node_ptr& n )
         {
            const auto rname = get_rulename( n->children.front() );
            assert( n->children.at( 1 )->is_type< grammar::defined_as_op >() );
            const auto op = n->children.at( 1 )->string();
            // when we insert a normal rule, we need to check for duplicates
            if( op == "=" ) {
               if( !previous_rules.try_emplace( rname, n.get() ).second ) {
#if defined( __cpp_exceptions )
                  throw parse_error( "rule '" + rname + "' is already defined", n->begin() );
#else
                  std::cerr << "rule '" + rname + "' is already defined" << std::endl;
                  std::terminate();
#endif
               }
            }
            // if it is an "incremental alternation", we need to consolidate the assigned alternations
            else if( op == "=/" ) {
               const auto p = previous_rules.find( rname );
               if( p == previous_rules.end() ) {
#if defined( __cpp_exceptions )
                  throw parse_error( "incremental alternation '" + rname + "' without previous rule definition", n->begin() );
#else
                  std::cerr << "incremental alternation '" + rname + "' without previous rule definition" << std::endl;
                  std::terminate();
#endif
               }
               auto& previous = p->second->children.back();

               // if the previous rule does not assign an alternation, create an intermediate alternation and move its assignee into it.
               if( !previous->is_type< abnf::grammar::alternation >() ) {
                  auto s = std::make_unique< parse_tree::node >();
                  s->set_type< abnf::grammar::alternation >();
                  s->source = previous->source;
                  s->m_begin = previous->m_begin;
                  s->m_end = previous->m_end;
                  s->children.emplace_back( std::move( previous ) );
                  previous = std::move( s );
               }

               // append all new options to the previous rule's assignee (which always is an alternation now)
               previous->m_end = n->children.back()->m_end;

               // if the new rule itself contains an alternation, append the individual entries...
               if( n->children.back()->is_type< abnf::grammar::alternation >() ) {
                  for( auto& e : n->children.back()->children ) {
                     previous->children.emplace_back( std::move( e ) );
                  }
               }
               // ...otherwise add the node itself as another option.
               else {
                  previous->children.emplace_back( std::move( n->children.back() ) );
               }
               n.reset();
            }
            else {
#if defined( __cpp_exceptions )
               throw parse_error( "invalid operator '" + op + "', this should not happen!", n->begin() );
#else
               std::cerr << "invalid operator '" + op + "', this should not happen!" << std::endl;
               std::terminate();
#endif
            }
         }
      };

      // Finally, the generated parse tree for each node is converted to
      // a C++ source code string.

      struct stringifier
      {
         using function_t = std::string ( * )( const node_ptr& n );
         function_t default_ = nullptr;

         std::map< std::string_view, function_t > map_;

         template< typename T >
         void add( const function_t& f )
         {
            map_.try_emplace( demangle< T >(), f );
         }

         std::string operator()( const node_ptr& n ) const
         {
            const auto it = map_.find( n->type );
            if( it != map_.end() ) {
               return it->second( n );
            }
            return default_( n );
         }
      };

      stringifier make_stringifier()
      {
         stringifier nrv;
         nrv.default_ = []( const node_ptr& n ) -> std::string {
#if defined( __cpp_exceptions )
            throw parse_error( "missing to_string() for " + std::string( n->type ), n->begin() );
#else
            std::cerr << "missing to_string() for " + std::string( n->type ) << std::endl;
            std::terminate();
#endif
         };

         nrv.add< grammar::rulename >( []( const node_ptr& n ) { return get_rulename( n, true ); } );

         nrv.add< grammar::rule >( []( const node_ptr& n ) {
            return "struct " + get_rulename( n->children.front(), false ) + " : " + to_string( n->children.back() ) + " {};";
         } );

         nrv.add< string_tag >( []( const node_ptr& n ) {
            const auto content = n->string_view();
            std::string s;
            for( const auto c : content ) {
               append_char( s, c );
            }
            return prefix + "string< " + s + " >";
         } );

         nrv.add< istring_tag >( []( const node_ptr& n ) {
            const auto content = n->string_view();
            std::string s;
            for( const auto c : content ) {
               append_char( s, c );
            }
            return prefix + "istring< " + s + " >";
         } );

         nrv.add< one_tag >( []( const node_ptr& n ) {
            const auto content = n->string_view();
            std::string s;
            for( const auto c : content ) {
               append_char( s, c );
            }
            return prefix + "one< " + s + " >";
         } );

         nrv.add< grammar::hex_val::value >( []( const node_ptr& n ) { return "0x" + n->string(); } );
         nrv.add< grammar::dec_val::value >( []( const node_ptr& n ) { return n->string(); } );
         nrv.add< grammar::bin_val::value >( []( const node_ptr& n ) {
            unsigned long long v = 0;
            const char* p = n->m_begin.data;
            // TODO: Detect overflow
            do {
               v <<= 1;
               v |= ( *p++ & 1 );
            } while( p != n->m_end.data );
            std::ostringstream oss;
            oss << v;
            return std::move( oss ).str();
         } );

         nrv.add< grammar::hex_val::type >( []( const node_ptr& n ) { return gen_val< grammar::hex_val::range >( n ); } );
         nrv.add< grammar::dec_val::type >( []( const node_ptr& n ) { return gen_val< grammar::dec_val::range >( n ); } );
         nrv.add< grammar::bin_val::type >( []( const node_ptr& n ) { return gen_val< grammar::bin_val::range >( n ); } );

         nrv.add< grammar::alternation >( []( const node_ptr& n ) { return prefix + "sor< " + to_string( n->children ) + " >"; } );
         nrv.add< grammar::option >( []( const node_ptr& n ) { return prefix + "opt< " + to_string( n->children ) + " >"; } );
         nrv.add< grammar::group >( []( const node_ptr& n ) { return prefix + "seq< " + to_string( n->children ) + " >"; } );

         nrv.add< grammar::prose_val >( []( const node_ptr& n ) { return "/* " + n->string() + " */"; } );

         nrv.add< grammar::and_predicate >( []( const node_ptr& n ) {
            assert( n->children.size() == 1 );
            return prefix + "at< " + to_string_unwrap_seq( n->children.front() ) + " >";
         } );

         nrv.add< grammar::not_predicate >( []( const node_ptr& n ) {
            assert( n->children.size() == 1 );
            return prefix + "not_at< " + to_string_unwrap_seq( n->children.front() ) + " >";
         } );

         nrv.add< grammar::concatenation >( []( const node_ptr& n ) {
            assert( !n->children.empty() );
            return prefix + "seq< " + to_string( n->children ) + " >";
         } );

         nrv.add< grammar::repetition >( []( const node_ptr& n ) -> std::string {
            assert( n->children.size() == 2 );
            const auto content = to_string_unwrap_seq( n->children.back() );
            const auto rep = n->children.front()->string();
            const auto star = rep.find( '*' );
            if( star == std::string::npos ) {
               const auto v = remove_leading_zeroes( rep );
               if( v.empty() ) {
#if defined( __cpp_exceptions )
                  throw parse_error( "repetition of zero not allowed", n->begin() );
#else
                  std::cerr << "repetition of zero not allowed" << std::endl;
                  std::terminate();
#endif
               }
               return prefix + "rep< " + v + ", " + content + " >";
            }
            const auto min = remove_leading_zeroes( rep.substr( 0, star ) );
            const auto max = remove_leading_zeroes( rep.substr( star + 1 ) );
            if( ( star != rep.size() - 1 ) && max.empty() ) {
#if defined( __cpp_exceptions )
               throw parse_error( "repetition maximum of zero not allowed", n->begin() );
#else
               std::cerr << "repetition maximum of zero not allowed" << std::endl;
               std::terminate();
#endif
            }
            if( min.empty() && max.empty() ) {
               return prefix + "star< " + content + " >";
            }
            if( !min.empty() && max.empty() ) {
               if( min == "1" ) {
                  return prefix + "plus< " + content + " >";
               }
               return prefix + "rep_min< " + min + ", " + content + " >";
            }
            if( min.empty() && !max.empty() ) {
               if( max == "1" ) {
                  return prefix + "opt< " + content + " >";
               }
               return prefix + "rep_max< " + max + ", " + content + " >";
            }
            unsigned long long min_val;
            unsigned long long max_val;
            {
               std::stringstream s;
               s.str( min );
               s >> min_val;
               s.clear();
               s.str( max );
               s >> max_val;
            }
            if( min_val > max_val ) {
#if defined( __cpp_exceptions )
               throw parse_error( "repetition minimum which is greater than the repetition maximum not allowed", n->begin() );
#else
               std::cerr << "repetition minimum which is greater than the repetition maximum not allowed" << std::endl;
               std::terminate();
#endif
            }
            if( ( min_val == 1 ) && ( max_val == 1 ) ) {
               // note: content can not be used here!
               return to_string( n->children.back() );
            }
            auto min_element = ( min_val == 1 ) ? content : ( prefix + "rep< " + min + ", " + content + " >" );
            if( min_val == max_val ) {
               return min_element;
            }
            std::ostringstream oss;
            oss << ( max_val - min_val );
            const auto max_element = prefix + ( ( max_val - min_val == 1 ) ? "opt< " : ( "rep_opt< " + std::move( oss ).str() + ", " ) ) + content + " >";
            return prefix + "seq< " + min_element + ", " + max_element + " >";
         } );

         return nrv;
      }

      std::string to_string( const node_ptr& n )
      {
         static stringifier s = make_stringifier();
         return s( n );
      }

      std::string to_string( const std::vector< node_ptr >& v )
      {
         std::string result;
         for( const auto& c : v ) {
            if( !result.empty() ) {
               result += ", ";
            }
            result += to_string( c );
         }
         return result;
      }

   }  // namespace abnf

}  // namespace TAO_PEGTL_NAMESPACE

int main( int argc, char** argv )  // NOLINT(bugprone-exception-escape)
{
   using namespace TAO_PEGTL_NAMESPACE;

   if( argc != 2 ) {
      std::cerr << "Usage: " << argv[ 0 ] << " SOURCE\n";
      return 1;
   }

   file_input in( argv[ 1 ] );
#if defined( __cpp_exceptions )
   try {
      const auto root = parse_tree::parse< abnf::grammar::rulelist, abnf::selector, nothing, abnf::control >( in );

      for( const auto& rule : root->children ) {
         abnf::rules_defined.push_back( abnf::get_rulename( rule->children.front() ) );
      }

      for( const auto& rule : root->children ) {
         std::cout << abnf::to_string( rule ) << '\n';
      }
   }
   catch( const parse_error& e ) {
      const auto p = e.positions().front();
      std::cerr << e.what() << '\n'
                << in.line_at( p ) << '\n'
                << std::setw( p.column ) << '^' << '\n';
   }
#else
   if( const auto root = parse_tree::parse< abnf::grammar::rulelist, abnf::selector, nothing, abnf::control >( in ) ) {
      for( const auto& rule : root->children ) {
         abnf::rules_defined.push_back( abnf::get_rulename( rule->children.front() ) );
      }

      for( const auto& rule : root->children ) {
         std::cout << abnf::to_string( rule ) << '\n';
      }
   }
   else {
      std::cerr << "error occurred" << std::endl;
      return 1;
   }
#endif

   return 0;
}


text:
<?php
use yii\helpers\Url;
use yii\bootstrap\Nav;
use yii\bootstrap\NavBar;
use yii\helpers\Html;

// Userbar code
if (Yii::$app->user->isGuest) {
    $user_bar =  "

                    signup

                    login

";
} else {
        $logout_code =
        Html::beginForm(['/site/logout'], 'post')
        . Html::submitButton(
            'Sign out', /* Yii::$app->user->identity->username */
            ['class' => 'btn btn-default btn-flat']
        )
        . Html::endForm();
        // $user_bar =  "
" .$logout_code . "
";
}
?>

                4

You have 4 messages

                                    <img src="<?= $assets->baseUrl ?>/dist/img/user2-160x160.jpg" class="img-circle" alt="User Image">

                                    Support Team
                                     5 mins

Why not buy a new awesome theme?

See All Messages

                10

You have 10 notifications

                                 5 new members joined today

View all

                9

You have 9 tasks

                                    Design some buttons
                                    20%

                                        20% Complete

                    View all tasks

        <?php if (!Yii::$app->user->isGuest) { ?>

                <img src="<?= $assets->baseUrl ?>/dist/img/user2-160x160.jpg" class="user-image" alt="User Image">

                <?= Yii::$app->user->identity->username ?>

                    <img src="<?= $assets->baseUrl ?>/dist/img/user2-160x160.jpg" class="img-circle" alt="User Image">

                        <?= Yii::$app->user->identity->username ?> - Web Developer
                        Member since Nov. 2012

                            Followers

                            Sales

                            Friends

                        Profile

                        <?=$logout_code?>

        <?php }
        else {
            echo $user_bar;
        }
        ?>

redpajama_set_name: RedPajamaGithub


text:
package com.redhat.rcm.maven.plugin.buildmetadata;

import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.Properties;

import org.apache.maven.execution.MavenSession;
import org.apache.maven.execution.RuntimeInformation;
import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
import org.apache.maven.project.MavenProject;
import org.sonatype.plexus.components.sec.dispatcher.SecDispatcher;

import com.redhat.rcm.maven.plugin.buildmetadata.common.Property;
import com.redhat.rcm.maven.plugin.buildmetadata.common.ScmInfo;
import com.redhat.rcm.maven.plugin.buildmetadata.data.MetaDataProvider;
import com.redhat.rcm.maven.plugin.buildmetadata.data.MetaDataProviderBuilder;
import com.redhat.rcm.maven.plugin.buildmetadata.data.Provider;
import com.redhat.rcm.maven.plugin.buildmetadata.io.BuildPropertiesFileHelper;
import com.redhat.rcm.maven.plugin.buildmetadata.util.ManifestHelper;
import com.redhat.rcm.maven.plugin.buildmetadata.util.MojoFileUtils;
import com.redhat.rcm.maven.plugin.buildmetadata.util.SettingsDecrypter;

/**
 * Base implementation for all build mojos.
 *
 * @author Robert Reiner
 * @version $Revision: 9143 $
 */
public abstract class AbstractBuildMojo extends AbstractMojo
{
  // ********************************* Fields *********************************

  // --- constants ------------------------------------------------------------

  // --- members --------------------------------------------------------------

  // ... Mojo infrastructure ..................................................

  /**
   * The Maven project.
   *
   * @parameter expression="${project}"
   * @required
   * @readonly
   * @since 1.0
   */
  protected MavenProject project;

  /**
   * The Maven session instance.
   *
   * @parameter expression="${session}"
   * @required
   * @readonly
   */
  protected MavenSession session;

  /**
   * The runtime information of the Maven instance being executed for the build.
   *
   * @component
   * @since 1.0
   */
  protected RuntimeInformation runtime;

  /**
   * The name of the properties file to write. Per default this value is
   * overridden by packaging dependent locations. Please refer to activatePropertyOutputFileMapping for details.
   *
   * @parameter default-value=
   *            "${project.build.outputDirectory}/META-INF/build.properties"
   * @since 1.0
   */
  protected File propertiesOutputFile;

  /**
   * Used to activate the default mapping that writes the build properties of
   * deployable units to
   * ${project.build.directory}/${project.build.finalName}/META-INF/build.properties
   * and for standard JAR files to
   * ${project.build.outputDirectory}/META-INF/build.properties.
   *

   * This property is used for the properties and XML build file.
   *

   *
   * @parameter default-value=true
   * @since 1.1
   */
  private boolean activateOutputFileMapping;

  /**
   * Maps a packaging to a location for the build meta data properties file.
   *

   * This mapping is especially useful for multi projects.
   *

   *
   * @parameter
   * @since 1.1
   */
  private List<FileMapping> propertyOutputFileMapping;

  /**
   * Maps a packaging to a location for the build meta data XML file.
   *

   * This mapping is especially useful for multi projects.
   *

   *
   * @parameter
   * @since 1.3
   */
  private List<FileMapping> xmlOutputFileMapping;

  /**
   * The name of the XML report file to write. If you want to include the XML
   * file in the artifact, use
   * ${project.build.outputDirectory}/META-INF/buildmetadata.xml.
   *

   * The handling is not in an analogous manner as that of the properties file.
   * The reason is this: we want to keep the artifact as small as possible per
   * default. Therefore we include the build.properties and
   * generate the XML report (see property createXmlReport to the
   * target folder (and not inside META-INF). The XML file can be
   * stored to the artifact server (with a couple of other reports) by the use
   * of the
   * projectmetadata-maven-plugin.
   *

   *
   * @parameter default-value= "${project.build.directory}/buildmetadata.xml"
   * @since 1.0
   */
  protected File xmlOutputFile;

  /**
   * The location of the Manifest file to add the buildmetadata properties to.
   *
   * @parameter default-value=
   *            "${project.build.outputDirectory}/META-INF/MANIFEST.MF"
   * @since 1.5
   */
  protected File manifestFile;

  /**
   * The name of the section within the Manifest file to write the
   * buildmetadata properties to. Use "Main" to write the the main
   * section.
   *
   * @parameter default-value="BuildMetaData"
   * @since 1.5
   */
  protected String manifestSection;

  /**
   * Flag to choose whether (true) or not (false) the
   * Manifest file should be created.
   *
   * @parameter default-value= "false"
   * @since 1.5
   */
  protected boolean createManifestFile;

  /**
   * Flag to choose whether (true) or not (false) the
   * build.properties file should be created.
   *

   * This will adjust the path of the propertiesOutputFile to
   * ${project.build.directory}/build.properties.
   *

   *
   * @parameter default-value= "true"
   * @since 1.2
   */
  protected boolean createPropertiesReport;

  /**
   * Flag to choose whether (true) or not (false) the
   * XML report should be created.
   *
   * @parameter default-value= "true"
   * @since 1.0
   */
  protected boolean createXmlReport;

  /**
   * Flag to choose whether (true) or not (false) to
   * write protect the generated buildmetadata files. Protecting them allows to
   * projects that copy files from different resources together to not override
   * them by other plugins.
   *
   * @parameter default-value= "false"
   * @since 1.5
   */
  protected boolean writeProtectFiles;

  /**
   * The list of meta data providers to launch that contribute to the meta data.
   *
   * @parameter
   */
  protected List<Provider> providers;

  /**
   * The list of a system properties or environment variables to be selected by
   * the user to include into the build meta data properties.
   *

   * The name is the name of the property, the section is relevant for placing
   * the property in one of the following sections:
   *

   *

   *
build.scm

   *
build.dateAndVersion

   *
build.runtime

   *
build.java

   *
build.maven

   *
project

   *
build.misc

   *

   *

   * If no valid section is given, the property is silently rendered in the
   * build.misc section.
   *

   *
   * @parameter
   * @since 1.0
   */
  protected List<Property> properties;

  /**
   * Flag to indicate whether or not the generated properties file should be
   * added to the projects filters.
   *

   * Filters are only added temporarily (read in-memory during the build) and
   * are not written to the POM.
   *

   *
   * @parameter expression="${buildMetaData.addToFilters}" default-value="true"
   * @since 1.0
   */
  protected boolean addToFilters;

  /**
   * The branch or tag version on the remote server to compare against. If
   * unset, the SCM status will be used to determine the differences.
   *

   * For SVN, leave it blank. For Git, set the version on the remote server (the
   * project's SCM URL points to).
   *

   *
   * @parameter
   * @since 1.4.0
   */
  protected String remoteVersion;

  /**
   * Helper to decrypt passwords from the settings.
   *
   * @component
   *            role="org.sonatype.plexus.components.sec.dispatcher.SecDispatcher"
   * @since 1.4.0
   */
  private SecDispatcher securityDispatcher;

  /**
   * The location of the settings-security.xml.
   *
   * @parameter expression="${user.home}/.m2/settings-security.xml"
   * @required
   * @since 1.4.0
   */
  private String settingsSecurityLocation;

  /**
   * Helper to decrypt passwords from the settings handling the location of the
   * settings-security.xml file.
   *
   * @since 1.4.0
   */
  protected SettingsDecrypter settingsDecrypter;

  // CHECKSTYLE:OFF
  public void execute() throws MojoExecutionException, MojoFailureException
  {
    // CHECKSTYLE:ON
    final String propertiesFileName =
        calcFileName(propertiesOutputFile, "build.properties");
    if (createPropertiesReport)
    {
      settingsDecrypter =
          securityDispatcher != null ? new SettingsDecrypter(
              securityDispatcher, settingsSecurityLocation) : null;

      final PropertyOutputFileMapper mapperProperties =
          new PropertyOutputFileMapper(project, propertyOutputFileMapping,
              propertiesFileName);
      this.propertyOutputFileMapping = mapperProperties.initOutputFileMapping();
      this.propertiesOutputFile =
          mapperProperties.getPropertiesOutputFile(activateOutputFileMapping,
              propertiesOutputFile);
    }
    else
    {
      // The properties file is required for project filtering even if only
      // the XML file is requested by the user.
      propertiesOutputFile =
          new File(project.getBuild().getDirectory(), propertiesFileName);
    }

    if (createXmlReport)
    {
      final String xmlFileName =
          calcFileName(xmlOutputFile, "buildmetadata.xml");
      final PropertyOutputFileMapper mapperXml =
          new PropertyOutputFileMapper(project, xmlOutputFileMapping,
              xmlFileName);
      this.xmlOutputFileMapping = mapperXml.initOutputFileMapping();
      this.xmlOutputFile =
          mapperXml.getPropertiesOutputFile(activateOutputFileMapping,
              xmlOutputFile);
    }
  }

  private static String calcFileName(final File file, final String defaultName)
  {
    final String fileName;
    if (file != null)
    {
      fileName = file.getName();
    }
    else
    {
      fileName = defaultName;
    }
    return fileName;
  }

  /**
   * Adds the information as build properties for each provider.
   *
   * @param buildMetaDataProperties the build meta data properties to add to.
   * @param scmInfo the information for the SCM provided to the build plugin.
   * @param providers the providers to iterate over.
   * @param runAtEndOfBuild checks if the provider is configured to be run at
   *          the end of the build. If a provider matches this value, it is run.
   * @throws MojoExecutionException on any problem running on the providers.
   */
  protected final void provideBuildMetaData(
      final Properties buildMetaDataProperties, final ScmInfo scmInfo,
      final List<Provider> providers, final boolean runAtEndOfBuild)
    throws MojoExecutionException
  {
    if (providers != null && !providers.isEmpty())
    {
      final MetaDataProviderBuilder builder =
          new MetaDataProviderBuilder(project, session, runtime, scmInfo);
      for (final Provider providerConfig : providers)
      {
        if (providerConfig.isRunAtEndOfBuild() == runAtEndOfBuild)
        {
          final MetaDataProvider provider = builder.build(providerConfig);
          provider.provideBuildMetaData(buildMetaDataProperties);
        }
      }
    }
  }

  /**
   * Updates the Maven runtime with build properties.
   *
   * @param buildMetaDataProperties the properties to add to the Maven project
   *          properties.
   * @param helper the project helper to use.
   * @throws MojoExecutionException if a requested Manifest file cannot be
   *           created.
   */
  protected final void updateMavenEnvironment(
      final Properties buildMetaDataProperties,
      final BuildPropertiesFileHelper helper) throws MojoExecutionException
  {
    final Properties projectProperties = helper.getProjectProperties(project);

    // Filters are only added temporarily and are not written to the POM...
    if (addToFilters)
    {
      project.getBuild().addFilter(propertiesOutputFile.getAbsolutePath());
    }

    if (createManifestFile)
    {
      final ManifestHelper manifestHelper =
          new ManifestHelper(manifestFile, manifestSection);
      try
      {
        MojoFileUtils.ensureExists(manifestFile.getParentFile());
        manifestHelper.createManifest(buildMetaDataProperties);
      }
      catch (final IOException e)
      {
        throw new MojoExecutionException("Cannot create Manifest file: "
                                         + manifestFile.getAbsolutePath(), e);
      }
    }

    projectProperties.putAll(buildMetaDataProperties);
  }

  // --- object basics --------------------------------------------------------

}


text:
package ui;

import java.util.concurrent.Callable;
import java.util.concurrent.CancellationException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import biz.CmdExecutor;
import biz.MyCmd;
import biz.iCmdListener;

import com.example.test4cmdpattern.R;

public class MainActivity extends Activity {
	private String TAG = "test";

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		Log.e(TAG, "thread id=" + Thread.currentThread().getId());
		findViewById(R.id.btn_toexeccmd).setOnClickListener(
				new OnClickListener() {

					@Override
					public void onClick(View v) {
						// TODO Auto-generated method stub
						CmdExecutor.exeInBackground(new MyCmd(),
								new iCmdListener() {

									@Override
									public void onSucess() {
										// TODO Auto-generated method stub
										Log.e(TAG, "onSucess, thread id="
												+ Thread.currentThread()
														.getId() + ", this="
												+ this);
									}

									@Override
									public void onPreExe() {
										// TODO Auto-generated method stub
										Log.e(TAG, "onPreExecute, thread id="
												+ Thread.currentThread()
														.getId() + ", this="
												+ this);
									}

									@Override
									public void onFail() {
										// TODO Auto-generated method stub
										Log.e(TAG, "onFaile, thread id="
												+ Thread.currentThread()
														.getId() + ", this="
												+ this);
									}

								});
					}
				});
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);

		{
			FutureTask<String> futureTask = new FutureTask<String>(
					new Callable<String>() {

						@Override
						public String call() throws Exception {
							// TODO Auto-generated method stub
							return null;
						}
					}) {

				@Override
				protected void done() {
					// TODO Auto-generated method stub
					super.done();
					try {
						get();
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} catch (ExecutionException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} catch (CancellationException e) {
						// TODO: handle exception
					}
				}
			};

		}
		return true;
	}

}


text:
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="HtmlUnderline.cs" company="">
//
// </copyright>
//
//   The html div.
//
// --------------------------------------------------------------------------------------------------------------------
namespace UX.Testing.Core.Controls
{
	/// The html div.
	public class HtmlUnderline : HtmlControl
	{
		#region Public Properties

		/// Gets the html tag.
		public override HtmlTag HtmlTag
		{
			get
			{
				return HtmlTag.u;
			}
		}

		#endregion
	}
}


text:
package com.thaiopensource.datatype.xsd;

import com.thaiopensource.xml.util.Naming;

class NmtokenDatatype extends TokenDatatype
{
  @Override
  public boolean lexicallyAllows (final String str)
  {
    return Naming.isNmtoken (str);
  }

  @Override
  public int getLength (final Object obj)
  {
    // Surrogates are not possible in an NMTOKEN.
    return ((String) obj).length ();
  }

  @Override
  public boolean alwaysValid ()
  {
    return false;
  }

  @Override
  String getLexicalSpaceKey ()
  {
    return "nmtoken";
  }
}


text:
package com.rhtsjz.codeinpractice;

/**
 * Hello world!
 *
 */
public class App
{
    public static void main( String[] args )
    {
        System.out.println( "Hello World!" );

    }
}


text:
@import url('https://fonts.googleapis.com/css?family=EB+Garamond:400,400i');
@import url('https://fonts.googleapis.com/css?family=Inconsolata');

body {
  font-family: 'EB Garamond', serif !important;
  font-size: 1.1em !important;
}

h1, h2, h3, h4, h5, h6 {
  font-family: 'EB Garamond', serif !important;
}

code {
  padding: 0.2em 0.1em !important;
  font-family: 'Inconsolata' !important;
}

span.viewcode-link {
  font-size: 0.85em !important;
}

dl.function, dl.class, dl.struct{
  padding-top: 2em !important;
  border-top: #aaa solid 2px !important;
}

div.highlight > pre {
  font-size: 0.75em !important;
  background-color: #f8fbff !important;
}

dl dl pre {
  margin-left: 0px;
  padding-left: 10px;
}

@media screen and (min-width: 875px) {
  div.document {
    width: 80% !important;
  }

  div.sphinxsidebar {
    width: 27% !important; /* should match the left margin of div.bodywrapper */
    font-size: .9em !important;
  }

  div.bodywrapper {
    margin: 0 0 0 27% !important; /* left margin should match width of sidebar */
    border-left: #ddd solid 2px !important;
  }

  div.sphinxsidebarwrapper {
    border-bottom: #ddd solid 2px !important;
    position: fixed !important;
    top: 0% !important;
    width: 19% !important;
  }

  /* lightbox */
  /* contains lightbox image */
  div.lb-outerContainer {
    float: left !important;
    margin: 1em !important;
    width: 75% !important;
  }
  img.lb-image {
    width: 100% !important;
    height: auto !important;
  }
  /* contains lightbox caption */
  div.lb-dataContainer {
    float: left !important;
    width: 20% !important;
    margin: 1em !important;
  }
  span.lb-caption {
    white-space: normal !important;
    font-size: 1em !important;
    line-height: 1.3em !important;
    font-weight: normal !important;
  }
}

blockquote {
  /* background-color: #f8fbff !important; */
  padding: 1em;
}

/* Turn off italic serif for function and class arguments. */
code.descname ~ em {
  font-family: monospace !important;
  font-style: normal !important;
}

/* Broken lower left menu on readthedocs.rog */
div.rst-versions.rst-badge {
  display: none;
}

div.figure{
  background: #e8e9f8 !important;
}

li.current ul {
  padding-left: .5em !important;
}


text:
package com.infosky.matrixdemo;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.drawable.BitmapDrawable;
import android.util.AttributeSet;
import android.view.KeyEvent;
import android.view.View;

/**
 * Created by PineChang on 2017/3/3.
 * 切记:matrix不仅可以控制图形,可以可控制View组件的平移,旋转,和缩放等
 */

public class MyView extends View{
    public MyView(Context context) {
        super(context);
    }
    //原始图片资源
    private Bitmap bitmap;
    private Matrix matrix  = new Matrix();

    //设置位图的宽和高
    private int width ,height;
    //设置倾斜度
    private float sx = 0.0f;
    //设置位图的缩放比例
    private float  scale = 1.0f;
    //判断是缩放还是旋转
    private boolean isScale = false;

    public MyView(Context context, AttributeSet attrs) {
        super(context, attrs);

        initView();
    }

    public MyView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        initView();
    }
    private void  initView(){
        bitmap = ((BitmapDrawable)getContext().getResources().getDrawable(R.drawable.ic_launcher)).getBitmap();
        width = bitmap.getWidth();
        height = bitmap.getHeight();
        //使当前视图获得焦点,这样就可以操纵他了
        this.setFocusable(true);
    }

    //将bitmap画进去

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        //重置清零Matrix
        matrix.reset();
        if (!isScale) {
            matrix.setSkew(sx, 0);
        } else {
            //在x,y方向上同时设置
            matrix.setScale(scale,scale);
        }
        //根据原始位图和Matrix重新创建图片
        //挖去整个bitmap位图并且加上matrix变形,创建了一个新的位图bitmap2;
        Bitmap bitmap2 = Bitmap.createBitmap(bitmap,0,10,width,height,matrix,true);
        //根据绘制新位图
        canvas.drawBitmap(bitmap2,40.0f,100.3f,null);

    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {

        switch (keyCode) {
            case KeyEvent.KEYCODE_A:
                isScale = false;
                sx +=0.1;
                postInvalidate();
                break;
            case KeyEvent.KEYCODE_S:
                isScale = true;
                if(scale<2.0f) scale -=0.1;
                postInvalidate();
                break;

        }
        return super.onKeyDown(keyCode, event);
    }
}


text:
/*
  DO NOT MODIFY - This file has been generated by https://github.com/flemay/Semantic-UI-Meteorize
*/

Package.describe({
  name: '<%= info.pkgData.name %>',
  version: '<%= info.pkgData.version %>',
  summary: 'Data package for Semantic UI Meteor',
  git: '<%= info.pkgData.git %>',
  documentation: 'README.md'
});

var definitions = <%= definitions %>;
var themes = <%= themes %>;
var sites = <%= sites %>;

Package.onUse(function(api) {
  api.versionsFrom('1.2.0.2');
  api.addFiles('semantic-ui-data.js', 'server');
  api.export(['semanticUiDataPackage']);

  api.addAssets(definitions, 'server');
  api.addAssets(themes, 'server');
  api.addAssets(sites, 'server');
  api.addAssets('<%= info.semantic.dest.themeLessFileRelativePath %>', 'server');
  api.addAssets('<%= info.semantic.dest.semanticLessFileRelativePath %>', 'server');
  api.addAssets('<%= info.semantic.dest.themeConfigFileRelativePath %>', 'server');
});


text:
require 'json'

module Clarify
  module Responses
    # An Insights class represents a list of links to insights which have been
    # processed by the API. This class is used to locate insight documents.
    #
    # You can enumerate over the insight URLs and get names / urls of insights.
    class Insights < Clarify::Response
      include Enumerable

      def each
        items.each { |name, insight| yield name, insight['href'] }
      end

      def items
        body['_links'].select { |name, _| name[0..7] == 'insight:' }
      end
    end
  end
end


text:
package io.spring.cloud.samples.brewery.common;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.collect.LinkedListMultimap;
import com.google.common.collect.Multimap;
import com.google.common.collect.Multimaps;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.sleuth.Span;
import org.springframework.cloud.sleuth.SpanReporter;
import org.springframework.cloud.sleuth.stream.StreamSpanReporter;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Collection;

import static org.springframework.cloud.sleuth.Span.hexToId;

/**
 * @author Marcin Grzejszczak
 */
@RestController
@Slf4j
public class StoringZipkinStreamSpanReporter implements SpanReporter {

	private final Multimap<Long, Span> sentSpans = Multimaps.synchronizedListMultimap(
			LinkedListMultimap.create());
	private final StreamSpanReporter delegate;
	private final ObjectMapper objectMapper = new ObjectMapper();

	@Autowired
	public StoringZipkinStreamSpanReporter(StreamSpanReporter delegate) {
		this.delegate = delegate;
	}

	@RequestMapping("/spans/{traceId}")
	public ResponseEntity<Collection<Span>> spans(@PathVariable String traceId) {
		Collection<Span> spansForTrace = sentSpans.get(hexToId(traceId));
		return ResponseEntity.ok(spansForTrace);
	}

	@RequestMapping("/spans")
	public ResponseEntity<Collection<Span>> spans() {
		return ResponseEntity.ok(sentSpans.values());
	}

	@Override
	public void report(Span span) {
		sentSpans.put(span.getTraceId(), span);
		try {
			log.info("Sending span [" + objectMapper.writeValueAsString(span) + "] to Zipkin");
		} catch (JsonProcessingException e) {
			e.printStackTrace();
		}
		delegate.report(span);
	}

}


text:
import * as q from 'q';
import * as webdriver from 'selenium-webdriver';

import {ProtractorBrowser} from './browser';
import {Config} from './config';
import {ConfigParser} from './configParser';
import {Logger} from './logger';
import {protractor} from './ptor';

let logger = new Logger('plugins');

export enum PromiseType {
  Q,
  WEBDRIVER
}

export interface PluginConfig {
  path?: string;
  package?: string;
  inline?: ProtractorPlugin;
  name?: string;
  [key: string]: any;
}

export interface ProtractorPlugin {
  /**
   * Sets up plugins before tests are run. This is called after the WebDriver
   * session has been started, but before the test framework has been set up.
   *
   * @this {Object} bound to module.exports.
   *
   * @throws {*} If this function throws an error, a failed assertion is added to
   *     the test results.
   *
   * @return {Promise=} Can return a promise, in which case protractor will wait
   *     for the promise to resolve before continuing.  If the promise is
   *     rejected, a failed assertion is added to the test results.
   */
  setup?(): void|Promise<void>;

  /**
   * This is called before the test have been run but after the test framework has
   * been set up.  Analogous to a config file's `onPreare`.
   *
   * Very similar to using `setup`, but allows you to access framework-specific
   * variables/funtions (e.g. `jasmine.getEnv().addReporter()`).
   *
   * @this {Object} bound to module.exports.
   *
   * @throws {*} If this function throws an error, a failed assertion is added to
   *     the test results.
   *
   * @return {Promise=} Can return a promise, in which case protractor will wait
   *     for the promise to resolve before continuing.  If the promise is
   *     rejected, a failed assertion is added to the test results.
   */
  onPrepare?(): void|Promise<void>;

  /**
   * This is called after the tests have been run, but before the WebDriver
   * session has been terminated.
   *
   * @this {Object} bound to module.exports.
   *
   * @throws {*} If this function throws an error, a failed assertion is added to
   *     the test results.
   *
   * @return {Promise=} Can return a promise, in which case protractor will wait
   *     for the promise to resolve before continuing.  If the promise is
   *     rejected, a failed assertion is added to the test results.
   */
  teardown?(): void|Promise<void>;

  /**
   * Called after the test results have been finalized and any jobs have been
   * updated (if applicable).
   *
   * @this {Object} bound to module.exports.
   *
   * @throws {*} If this function throws an error, it is outputted to the console.
   *     It is too late to add a failed assertion to the test results.
   *
   * @return {Promise=} Can return a promise, in which case protractor will wait
   *     for the promise to resolve before continuing.  If the promise is
   *     rejected, an error is logged to the console.
   */
  postResults?(): void|Promise<void>;

  /**
   * Called after each test block (in Jasmine, this means an `it` block)
   * completes.
   *
   * @param {boolean} passed True if the test passed.
   * @param {Object} testInfo information about the test which just ran.
   *
   * @this {Object} bound to module.exports.
   *
   * @throws {*} If this function throws an error, a failed assertion is added to
   *     the test results.
   *
   * @return {Promise=} Can return a promise, in which case protractor will wait
   *     for the promise to resolve before outputting test results.  Protractor
   *     will *not* wait before executing the next test, however.  If the promise
   *     is rejected, a failed assertion is added to the test results.
   */
  postTest?(passed: boolean, testInfo: any): void|Promise<void>;

  /**
   * This is called inside browser.get() directly after the page loads, and before
   * angular bootstraps.
   *
   * @param {ProtractorBrowser} browser The browser instance which is loading a page.
   *
   * @this {Object} bound to module.exports.
   *
   * @throws {*} If this function throws an error, a failed assertion is added to
   *     the test results.
   *
   * @return {webdriver.promise.Promise=} Can return a promise, in which case
   *     protractor will wait for the promise to resolve before continuing.  If
   *     the promise is rejected, a failed assertion is added to the test results.
   */
  onPageLoad?(browser: ProtractorBrowser): void|webdriver.promise.Promise<void>;

  /**
   * This is called inside browser.get() directly after angular is done
   * bootstrapping/synchronizing.  If `browser.ignoreSynchronization` is `true`,
   * this will not be called.
   *
   * @param {ProtractorBrowser} browser The browser instance which is loading a page.
   *
   * @this {Object} bound to module.exports.
   *
   * @throws {*} If this function throws an error, a failed assertion is added to
   *     the test results.
   *
   * @return {webdriver.promise.Promise=} Can return a promise, in which case
   *     protractor will wait for the promise to resolve before continuing.  If
   *     the promise is rejected, a failed assertion is added to the test results.
   */
  onPageStable?(browser: ProtractorBrowser): void|webdriver.promise.Promise<void>;

  /**
   * Between every webdriver action, Protractor calls browser.waitForAngular() to
   * make sure that Angular has no outstanding $http or $timeout calls.
   * You can use waitForPromise() to have Protractor additionally wait for your
   * custom promise to be resolved inside of browser.waitForAngular().
   *
   * @param {ProtractorBrowser} browser The browser instance which needs invoked `waitForAngular`.
   *
   * @this {Object} bound to module.exports.
   *
   * @throws {*} If this function throws an error, a failed assertion is added to
   *     the test results.
   *
   * @return {webdriver.promise.Promise=} Can return a promise, in which case
   *     protractor will wait for the promise to resolve before continuing. If the
   *     promise is rejected, a failed assertion is added to the test results, and
   *     protractor will continue onto the next command. If nothing is returned or
   *     something other than a promise is returned, protractor will continue
   *     onto the next command.
   */
  waitForPromise?(browser: ProtractorBrowser): webdriver.promise.Promise<void>;

  /**
   * Between every webdriver action, Protractor calls browser.waitForAngular() to
   * make sure that Angular has no outstanding $http or $timeout calls.
   * You can use waitForCondition() to have Protractor additionally wait for your
   * custom condition to be truthy.  If specified, this function will be called
   * repeatedly until truthy.
   *
   * @param {ProtractorBrowser} browser The browser instance which needs invoked `waitForAngular`.
   *
   * @this {Object} bound to module.exports.
   *
   * @throws {*} If this function throws an error, a failed assertion is added to
   *     the test results.
   *
   * @return {webdriver.promise.Promise<boolean>|boolean} If truthy, Protractor
   *     will continue onto the next command. If falsy, webdriver will
   *     continuously re-run this function until it is truthy.  If a rejected promise
   *     is returned, a failed assertion is added to the test results, and Protractor
   *     will continue onto the next command.
   */
  waitForCondition?(browser: ProtractorBrowser): webdriver.promise.Promise<boolean>|boolean;

  /**
   * Used to turn off default checks for angular stability
   *
   * Normally Protractor waits for all $timeout and $http calls to be processed
   * before executing the next command.  This can be disabled using
   * browser.ignoreSynchronization, but that will also disable any
   * <Plugin>.waitForPromise or <Plugin>.waitForCondition checks.  If you want
   * to disable synchronization with angular, but leave intact any custom plugin
   * synchronization, this is the option for you.
   *
   * This is used by plugin authors who want to replace Protractor's
   * synchronization code with their own.
   *
   * @type {boolean}
   */
  skipAngularStability?: boolean;

  /**
   * The name of the plugin.  Used when reporting results.
   *
   * If you do not specify this property, it will be filled in with something
   * reasonable (e.g. the plugin's path) by Protractor at runtime.
   *
   * @type {string}
   */
  name?: string;

  /**
   * The plugin's configuration object.
   *
   * Note: this property is added by Protractor at runtime.  Any pre-existing
   * value will be overwritten.
   *
   * Note: that this is not the entire Protractor config object, just the entry
   * in the `plugins` array for this plugin.
   *
   * @type {Object}
   */
  config?: PluginConfig;

  /**
   * Adds a failed assertion to the test's results.
   *
   * Note: this property is added by Protractor at runtime.  Any pre-existing
   * value will be overwritten.
   *
   * @param {string} message The error message for the failed assertion
   * @param {specName: string, stackTrace: string} options Some optional extra
   *     information about the assertion:
   *       - specName The name of the spec which this assertion belongs to.
   *            Defaults to `PLUGIN_NAME + ' Plugin Tests'`.
   *       - stackTrace The stack trace for the failure.  Defaults to undefined.
   *     Defaults to `{}`.
   *
   * @throws {Error} Throws an error if called after results have been reported
   */
  addFailure?(message?: string, info?: {specName?: string, stackTrace?: string}): void;

  /**
   * Adds a passed assertion to the test's results.
   *
   * Note: this property is added by Protractor at runtime.  Any pre-existing
   * value will be overwritten.
   *
   * @param {specName: string} options Extra information about the assertion:
   *       - specName The name of the spec which this assertion belongs to.
   *            Defaults to `PLUGIN_NAME + ' Plugin Tests'`.
   *     Defaults to `{}`.
   *
   * @throws {Error} Throws an error if called after results have been reported
   */
  addSuccess?(info?: {specName?: string}): void;

  /**
   * Warns the user that something is problematic.
   *
   * Note: this property is added by Protractor at runtime.  Any pre-existing
   * value will be overwritten.
   *
   * @param {string} message The message to warn the user about
   * @param {specName: string} options Extra information about the assertion:
   *       - specName The name of the spec which this assertion belongs to.
   *            Defaults to `PLUGIN_NAME + ' Plugin Tests'`.
   *     Defaults to `{}`.
   */
  addWarning?(message?: string, info?: {specName?: string}): void;
}

/**
 * The plugin API for Protractor.  Note that this API is unstable. See
 * plugins/README.md for more information.
 *
 * @constructor
 * @param {Object} config parsed from the config file
 */
export class Plugins {
  pluginObjs: ProtractorPlugin[];
  assertions: {[key: string]: AssertionResult[]};
  resultsReported: boolean;

  constructor(config: Config) {
    this.pluginObjs = [];
    this.assertions = {};
    this.resultsReported = false;
    if (config.plugins) {
      config.plugins.forEach((pluginConf, i) => {
        let path: string;
        if (pluginConf.path) {
          path = ConfigParser.resolveFilePatterns(pluginConf.path, true, config.configDir)[0];
          if (!path) {
            throw new Error('Invalid path to plugin: ' + pluginConf.path);
          }
        } else {
          path = pluginConf.package;
        }

        let pluginObj: ProtractorPlugin;
        if (path) {
          pluginObj = require(path) as ProtractorPlugin;
        } else if (pluginConf.inline) {
          pluginObj = pluginConf.inline;
        } else {
          throw new Error(
              'Plugin configuration did not contain a valid path or ' +
              'inline definition.');
        }

        this.annotatePluginObj(pluginObj, pluginConf, i);

        logger.debug('Plugin "' + pluginObj.name + '" loaded.');
        this.pluginObjs.push(pluginObj);
      });
    }
  };

  /**
   * Adds properties to a plugin's object
   *
   * @see docs/plugins.md#provided-properties-and-functions
   */
  private annotatePluginObj(obj: ProtractorPlugin, conf: PluginConfig, i: number): void {
    let addAssertion =
        (info: {specName?: string, stackTrace?: string}, passed: boolean, message?: string) => {
          if (this.resultsReported) {
            throw new Error(
                'Cannot add new tests results, since they were already ' +
                'reported.');
          }
          info = info || {};
          const specName = info.specName || (obj.name + ' Plugin Tests');
          const assertion: AssertionResult = {passed: passed};
          if (!passed) {
            assertion.errorMsg = message;
            if (info.stackTrace) {
              assertion.stackTrace = info.stackTrace;
            }
          }
          this.assertions[specName] = this.assertions[specName] || [];
          this.assertions[specName].push(assertion);
        };

    obj.name = obj.name || conf.name || conf.path || conf.package || ('Plugin #' + i);
    obj.config = conf;
    obj.addFailure = (message?, info?) => {
      addAssertion(info, false, message);
    };
    obj.addSuccess = (options?) => {
      addAssertion(options, true);
    };
    obj.addWarning = (message?, options?) => {
      options = options || {};
      logger.warn(
          'Warning ' +
          (options.specName ? 'in ' + options.specName : 'from "' + obj.name + '" plugin') + ': ' +
          message);
    };
  }

  private printPluginResults(specResults: SpecResult[]) {
    const green = '\x1b[32m';
    const red = '\x1b[31m';
    const normalColor = '\x1b[39m';

    const printResult = (message: string, pass: boolean) => {
      logger.info(pass ? green : red, '\t', pass ? 'Pass: ' : 'Fail: ', message, normalColor);
    };

    for (const specResult of specResults) {
      const passed = specResult.assertions.map(x => x.passed).reduce((x, y) => (x && y), true);
      printResult(specResult.description, passed);
      if (!passed) {
        for (const assertion of specResult.assertions) {
          if (!assertion.passed) {
            logger.error('\t\t' + assertion.errorMsg);
            if (assertion.stackTrace) {
              logger.error('\t\t' + assertion.stackTrace.replace(/\n/g, '\n\t\t'));
            }
          }
        }
      }
    }
  }

  /**
   * Gets the tests results generated by any plugins
   *
   * @see lib/frameworks/README.md#requirements for a complete description of what
   *     the results object must look like
   *
   * @return {Object} The results object
   */
  getResults() {
    const results = {failedCount: 0, specResults: [] as SpecResult[]};
    for (const specName in this.assertions) {
      results.specResults.push({description: specName, assertions: this.assertions[specName]});
      results.failedCount +=
          this.assertions[specName].filter(assertion => !assertion.passed).length;
    }
    this.printPluginResults(results.specResults);
    this.resultsReported = true;
    return results;
  };

  /**
   * Returns true if any loaded plugin has skipAngularStability enabled.
   *
   * @return {boolean}
   */
  skipAngularStability() {
    const result = this.pluginObjs.some(pluginObj => pluginObj.skipAngularStability);
    return result;
  };

  /**
   * @see docs/plugins.md#writing-plugins for information on these functions
   */
  setup = this.pluginFunFactory('setup', PromiseType.Q);
  onPrepare = this.pluginFunFactory('onPrepare', PromiseType.Q);
  teardown = this.pluginFunFactory('teardown', PromiseType.Q);
  postResults = this.pluginFunFactory('postResults', PromiseType.Q);
  postTest = this.pluginFunFactory('postTest', PromiseType.Q);
  onPageLoad = this.pluginFunFactory('onPageLoad', PromiseType.WEBDRIVER);
  onPageStable = this.pluginFunFactory('onPageStable', PromiseType.WEBDRIVER);
  waitForPromise = this.pluginFunFactory('waitForPromise', PromiseType.WEBDRIVER);
  waitForCondition = this.pluginFunFactory('waitForCondition', PromiseType.WEBDRIVER, true);

  /**
   * Calls a function from a plugin safely.  If the plugin's function throws an
   * exception or returns a rejected promise, that failure will be logged as a
   * failed test result instead of crashing protractor.  If the tests results have
   * already been reported, the failure will be logged to the console.
   *
   * @param {Object} pluginObj The plugin object containing the function to be run
   * @param {string} funName The name of the function we want to run
   * @param {*[]} args The arguments we want to invoke the function with
   * @param {PromiseType} promiseType The type of promise (WebDriver or Q) that
   *    should be used
   * @param {boolean} resultsReported If the results have already been reported
   * @param {*} failReturnVal The value to return if the function fails
   *
   * @return {webdriver.promise.Promise|Q.Promise} A promise which resolves to the
   *     function's return value
   */
  private safeCallPluginFun(
      pluginObj: ProtractorPlugin, funName: string, args: any[], promiseType: PromiseType,
      failReturnVal: any): q.Promise<any>|Promise<any>|webdriver.promise.Promise<any> {
    const resolver = (done: (result: any) => void) => {
      const logError = (e: any) => {
        if (this.resultsReported) {
          this.printPluginResults([{
            description: pluginObj.name + ' Runtime',
            assertions: [{
              passed: false,
              errorMsg: 'Failure during ' + funName + ': ' + (e.message || e),
              stackTrace: e.stack
            }]
          }]);
        } else {
          pluginObj.addFailure(
              'Failure during ' + funName + ': ' + e.message || e, {stackTrace: e.stack});
        }
        done(failReturnVal);
      };
      try {
        const result = (pluginObj as any)[funName].apply(pluginObj, args);
        if (webdriver.promise.isPromise(result)) {
          (result as PromiseLike<any>).then(done, logError);
        } else {
          done(result);
        }
      } catch (e) {
        logError(e);
      }
    };
    if (promiseType == PromiseType.Q) {
      return q.Promise(resolver);
    } else if (protractor.browser.controlFlowIsEnabled()) {
      return new webdriver.promise.Promise(resolver);
    } else {
      return new Promise(resolver);
    }
  }

  /**
   * Generates the handler for a plugin function (e.g. the setup() function)
   *
   * @param {string} funName The name of the function to make a handler for
   * @param {PromiseType} promiseType The type of promise (WebDriver or Q) that should be used
   * @param {boolean=} failReturnVal The value that the function should return if the plugin crashes
   *
   * @return The handler
   */
  private pluginFunFactory(funName: string, promiseType: PromiseType.Q, failReturnVal?: boolean):
      (...args: any[]) => q.Promise<any[]>;
  private pluginFunFactory(
      funName: string, promiseType: PromiseType.WEBDRIVER,
      failReturnVal?: boolean): (...args: any[]) => webdriver.promise.Promise<any[]>;
  private pluginFunFactory(funName: string, promiseType: PromiseType, failReturnVal?: boolean) {
    return (...args: any[]) => {
      const promises =
          this.pluginObjs.filter(pluginObj => typeof(pluginObj as any)[funName] === 'function')
              .map(
                  pluginObj =>
                      this.safeCallPluginFun(pluginObj, funName, args, promiseType, failReturnVal));
      return promiseType == PromiseType.Q ? q.all(promises) : webdriver.promise.all(promises);
    };
  }
}

export interface SpecResult {
  description: string;
  assertions: AssertionResult[];
}

export interface AssertionResult {
  passed: boolean;
  errorMsg?: string;
  stackTrace?: string;
}


text:
var fs = require('fs')
var path = require('path')

var EXT_NAME_ORDER = ['wx', 'wa', 'we', 'html', 'component', 'vue']

function find(name, env) {
  var elements = env.elements || {}
  var dir = env.path || '.'
  var el, content

  if (elements[name]) {
    el = elements[name]
  }
  else {
    EXT_NAME_ORDER.some(function (extName) {
      var p = path.join(dir, name + '.' + extName)
      if (fs.existsSync(p)) {
        el = {name: name, path: p, content: fs.readFileSync(p, {encoding: 'utf-8'})}
        return true
      }
    })
  }

  return el
}

exports.find = find


text:
/**
 * File Name    : BlacklistIpSqlServiceImpl
 * Creator      : 20160701688
 * Created Date : 2017/4/6
 * Comment      :
 */

package com.neo.usermgr.mybatis.service.impl;

import com.neo.common.util.string.StrOperate;
import com.neo.usermgr.common.model.BlacklistIp;
import com.neo.usermgr.common.util.regex.StrRegex;
import com.neo.usermgr.mybatis.dao.BlacklistIpMapper;
import com.neo.usermgr.mybatis.service.itf.BlacklistIpSqlServiceI;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class BlacklistIpSqlServiceImpl implements BlacklistIpSqlServiceI {
    @Autowired
    private BlacklistIpMapper blacklistIpMapper;

    @Override
    public BlacklistIp queryBlacklistIpById(int id) {
        return blacklistIpMapper.queryBlacklistIpById(id);
    }

    @Override
    public int getBlacklistIpCount(String ip) {
        String ipHeader = null;
        int ipTail = -1;
        if (!StrOperate.checkStringNull(ip)) {
            if (StrRegex.checkIp(ip)) {
                String[] ipStartArray = ip.split("\\.");
                ipTail = Integer.parseInt(ipStartArray[BlacklistIp.IP_TAIL_INDEX]);
                ipHeader = ip.substring(
                        0, ip.length() - ipStartArray[BlacklistIp.IP_TAIL_INDEX].length() - 1);
            } else {
                return -1;
            }
        }
        return blacklistIpMapper.getBlacklistIpCount(ipHeader, ipTail);
    }

    @Override
    public List<BlacklistIp> getBlacklistIpWithCondition(String ip, int offset, int count) {
        String ipHeader = null;
        int ipTail = -1;
        if (!StrOperate.checkStringNull(ip)) {
            if (StrRegex.checkIp(ip)) {
                String[] ipStartArray = ip.split("\\.");
                ipTail = Integer.parseInt(ipStartArray[BlacklistIp.IP_TAIL_INDEX]);
                ipHeader = ip.substring(
                        0, ip.length() - ipStartArray[BlacklistIp.IP_TAIL_INDEX].length() - 1);
            } else {
                return null;
            }
        }
        return blacklistIpMapper.getBlacklistIpWithCondition(ipHeader, ipTail, offset, count);
    }

    @Override
    public int deleteBlacklistIpByIdList(List<Integer> ipIdList) {
        return blacklistIpMapper.deleteBlacklistIpByIdList(ipIdList);
    }

    @Override
    public int insertBlacklistIp(BlacklistIp blacklistIp) {
        return blacklistIpMapper.insertBlacklistIp(blacklistIp);
    }
}


text:
package com.ack.adventureandconquer.game.creature.npc.swimmer;

import com.ack.adventureandconquer.game.creature.npc.IsNpcType;
import com.ack.adventureandconquer.game.creature.npc.Npc;

import java.util.List;

/**
 * Created by saskyrar on 18/01/15.
 */
public class GiantSquidType implements IsNpcType {
    @Override
    public boolean isLair(int number) {
        return false;
    }

    @Override
    public List<Npc> getNormalWildnessEncounter() {
        return null;
    }

    @Override
    public String getNormalWildnessEncounterName() {
        return null;
    }

    @Override
    public List<Npc> getLairWildnessEncounter() {
        return null;
    }

    @Override
    public String getLairWildnessEncounterName() {
        return null;
    }
}


text:
/**
 * This module is an extension to jQuery ui selectable, which scrolls when you try to select
 * outside the container, and the scrollables are not fitting it originally.
 *
 * Created by László Károlyi <http://linkedin.com/in/karolyi>
 * with the GPLv3 License: http://opensource.org/licenses/GPL-3.0
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
/*global jQuery*/
(function ($) {
  'use strict';
  $.widget('ui.selectableScroll', $.ui.selectable, {
    options: {
      // If an element is passed in here, use it for scrolling instead of widget's element
      scrollElement: null,
      // When the selection is that pixels near to the top/bottom edges, start to scroll
      scrollSnapX: 5,
      // When the selection is that pixels near to the side edges, start to scroll
      scrollSnapY: 5,
      scrollAmount: 25, // In pixels
      scrollIntervalTime: 100 // In milliseconds
    },

    /**
     * This is a slightly modified version of the original _create function,
     * we just add the element's relative positions too
     *
     * @return null
     */
    _create: function () {
      this.element.addClass('ui-selectable');
      this.dragged = false;
      this.helperClasses = ['no-top', 'no-right', 'no-bottom', 'no-left'];
      this.scrollElement = this.options.scrollElement || this.element;
      this.refresh();
      this._mouseInit();
      this.helper = $('

');
    },

    /**
     * Cache selectee children based on filter
     * @return null
     */
    refresh: function () {
      var elementOffset = this.scrollElement.offset();
      var scrollLeft = this.scrollElement.prop('scrollLeft');
      var scrollTop = this.scrollElement.prop('scrollTop');
      this.selectees = $(this.options.filter, this.scrollElement[0]);
      this.selectees.addClass('ui-selectee');
      this.selectees.each(function () {
        var $element = $(this),
          pos = $element.offset();
        $.data(this, 'selectable-item', {
          element: this,
          $element: $element,
          left: pos.left,
          top: pos.top,
          right: pos.left + $element.outerWidth(),
          bottom: pos.top + $element.outerHeight(),
          // Relative positions according to the element's 0.0
          relative: {
            left: pos.left - elementOffset.left + scrollLeft,
            top: pos.top - elementOffset.top + scrollTop,
            right: pos.left - elementOffset.left + scrollLeft +
              $element.outerWidth(),
            bottom: pos.top - elementOffset.top + scrollTop +
              $element.outerHeight()
          },
          startselected: false,
          selected: $element.hasClass('ui-selected'),
          selecting: $element.hasClass('ui-selecting'),
          unselecting: $element.hasClass('ui-unselecting')
        });
      });
    },

    /**
     * By starting dragging, calculate the element's current scroll states,
     * relative to the elements 0.0 offset
     *
     * @param  object  The mousedown event
     * @return boolean The parent's _mouseStart return value
     */
    _mouseStart: function (event) {
      var pos = this.scrollElement.offset();
      if (
        (event.pageX > this.scrollElement.prop('clientWidth') + pos.left) ||
        (event.pageY > this.scrollElement.prop('clientHeight') + pos.top)
      ) {
        return false;
      }
      var retValue = $.ui.selectable.prototype._mouseStart.call(this,
        event);
      this.lastDragEvent = null;
      this.scrollInfo = {
        // The element's 0.0 offset related to the document element
        elementOffset: this.scrollElement.offset(),
        // The maximum scrollable width (visible width + scrollLeft)
        scrollWidth: this.scrollElement.prop('scrollWidth'),
        // The maximum scrollable height (visible height + scrollTop)
        scrollHeight: this.scrollElement.prop('scrollHeight'),
        // The visible width (minus scrollbars)
        elementWidth: this.scrollElement.prop('clientWidth'),
        // The visible height (minus scrollbars)
        elementHeight: this.scrollElement.prop('clientHeight')
      };
      // Relative to element's 0
      this.scrollInfo.dragStartXPos = event.pageX - this.scrollInfo.elementOffset
        .left + this.scrollElement.prop('scrollLeft');
      // Relative to element's 0
      this.scrollInfo.dragStartYPos = event.pageY - this.scrollInfo.elementOffset
        .top + this.scrollElement.prop('scrollTop');
      this.scrollIntervalId = null;
      return retValue;
    },

    /**
     * Calculate/redraw the helper lasso, keep the helper within
     * the scrolled element
     *
     * @param  object The options object containing the relative positions of the selected rectangle
     * @return null
     */
    _updateHelper: function (options) {
      var x1, y1, x2, y2; // Absolute positions for the lasso helper
      var lassoClassesArray = [];
      if (options.x1 - options.scrollLeft < 0) {
        lassoClassesArray.push('no-left');
        x1 = this.scrollInfo.elementOffset.left;
      } else {
        x1 = this.scrollInfo.elementOffset.left + options.x1 - options.scrollLeft;
      }
      if (options.y1 - options.scrollTop < 0) {
        lassoClassesArray.push('no-top');
        y1 = this.scrollInfo.elementOffset.top;
      } else {
        y1 = this.scrollInfo.elementOffset.top + options.y1 - options.scrollTop;
      }
      if (options.x2 - options.scrollLeft > this.scrollInfo.elementWidth) {
        lassoClassesArray.push('no-right');
        x2 = this.scrollInfo.elementOffset.left + this.scrollInfo.elementWidth;
      } else {
        x2 = this.scrollInfo.elementOffset.left + options.x2 - options.scrollLeft;
      }
      if (options.y2 - options.scrollTop > this.scrollInfo.elementHeight) {
        lassoClassesArray.push('no-bottom');
        y2 = this.scrollInfo.elementOffset.top + this.scrollInfo.elementHeight;
      } else {
        y2 = this.scrollInfo.elementOffset.top + options.y2 - options.scrollTop;
      }
      for (var counter = 0; counter < this.helperClasses.length; counter++) {
        var className = this.helperClasses[counter];
        if ($.inArray(className, lassoClassesArray) !== -1) {
          this.helper.addClass(className);
        } else {
          this.helper.removeClass(className);
        }
      }
      this.helper.css({
        left: x1,
        top: y1,
        width: x2 - x1,
        height: y2 - y1
      });
    },

    /**
     * If the mouse is near to the edges of the elements area, scroll
     *
     * @return object The new scrollLeft and scrollTop values, and a
     * boolean if the element should keep scrolling
     */
    _scrollIfNeeded: function (options) {
      var scrollLeft = this.scrollElement.prop('scrollLeft');
      var scrollTop = this.scrollElement.prop('scrollTop');

      var keepScrolling = false;
      // Scroll if close to edges or over them
      if (this.lastDragEvent.pageX - this.scrollInfo.elementOffset.left <
        this.options.scrollSnapX && scrollLeft > 0) {
        scrollLeft = scrollLeft < this.options.scrollAmount ? 0 :
          scrollLeft - this.options.scrollAmount;
        this.scrollElement.prop('scrollLeft', scrollLeft);
        keepScrolling = true;
      }
      if (this.lastDragEvent.pageY - this.scrollInfo.elementOffset.top <
        this.options.scrollSnapY && scrollTop > 0) {
        scrollTop = scrollTop < this.options.scrollAmount ? 0 : scrollTop -
          this.options.scrollAmount;
        this.scrollElement.prop('scrollTop', scrollTop);
        keepScrolling = true;
      }
      if (this.lastDragEvent.pageX - this.scrollInfo.elementOffset.left >
        this.scrollInfo.elementWidth - this.options.scrollSnapX && this.scrollInfo
        .scrollWidth > scrollLeft + this.scrollInfo.elementWidth) {
        scrollLeft = scrollLeft + this.options.scrollAmount > this.scrollInfo
          .scrollWidth - this.scrollInfo.elementWidth ? this.scrollInfo.scrollWidth -
          this.scrollInfo.elementWidth : scrollLeft + this.options.scrollAmount;
        this.scrollElement.prop('scrollLeft', scrollLeft);
        keepScrolling = true;
      }
      if (this.lastDragEvent.pageY - this.scrollInfo.elementOffset.top >
        this.scrollInfo.elementHeight - this.options.scrollSnapY && this.scrollInfo
        .scrollHeight > scrollLeft + this.scrollInfo.elementHeight) {
        scrollTop = scrollTop + this.options.scrollAmount > this.scrollInfo
          .scrollHeight - this.scrollInfo.elementHeight ? this.scrollInfo
          .scrollHeight - this.scrollInfo.elementHeight : scrollTop +
          this.options.scrollAmount;
        this.scrollElement.prop('scrollTop', scrollTop);
        keepScrolling = true;
      }
      return {
        scrollLeft: scrollLeft,
        scrollTop: scrollTop,
        keepScrolling: keepScrolling
      };
    },

    /**
     * Calculate a relative position to the element's 0.0 offset,
     * from the original drag event's coordinates
     *
     * @param  object The absolute X and Y positions
     * @return object The relative X and Y positions
     */
    _calcRelativePosition: function (options) {
      var relXPos = options.x - this.scrollInfo.elementOffset.left +
        options.scrollLeft;
      var relYPos = options.y - this.scrollInfo.elementOffset.top +
        options.scrollTop;
      return {
        x: relXPos,
        y: relYPos
      };
    },

    /**
     * Calculate relative area positions to offset element
     *
     * @param  object The relative X and Y positions to the 0.0 of the element
     * @return object An object containing the relative area coordinates
     */
    _calcRelativeArea: function (options) {
      var relX1 = options.xPos < this.scrollInfo.dragStartXPos ? options.xPos :
        this.scrollInfo.dragStartXPos;
      var relY1 = options.yPos < this.scrollInfo.dragStartYPos ? options.yPos :
        this.scrollInfo.dragStartYPos;
      var relX2 = options.xPos > this.scrollInfo.dragStartXPos ? options.xPos :
        this.scrollInfo.dragStartXPos;
      var relY2 = options.yPos > this.scrollInfo.dragStartYPos ? options.yPos :
        this.scrollInfo.dragStartYPos;
      return {
        x1: relX1,
        y1: relY1,
        x2: relX2,
        y2: relY2
      };
    },

    /**
     * Update the selected elements
     *
     * @param  object The return value of _calcRelativeArea()
     * @return null
     */
    _updateSelectees: function (options) {
      var that = this;
      this.selectees.each(function () {
        var selectee = $.data(this, 'selectable-item'),
          hit = false;

        // Prevent helper from being selected if appendTo: selectable
        if (!selectee || selectee.element === that.element[0]) {
          return;
        }

        if (that.options.tolerance === 'touch') {
          hit = (!(selectee.relative.left > options.x2 || selectee.relative
            .right < options.x1 || selectee.relative.top > options.y2 ||
            selectee.relative.bottom < options.y1));
        } else if (that.options.tolerance === 'fit') {
          hit = (selectee.relative.left > options.x1 && selectee.relative
            .right < options.x2 && selectee.relative.top > options.y1 &&
            selectee.relative.bottom < options.y2);
        }

        if (hit) {
          // SELECT
          if (selectee.selected) {
            selectee.$element.removeClass('ui-selected');
            selectee.selected = false;
          }
          if (selectee.unselecting) {
            selectee.$element.removeClass('ui-unselecting');
            selectee.unselecting = false;
          }
          if (!selectee.selecting) {
            selectee.$element.addClass('ui-selecting');
            selectee.selecting = true;
            // selectable SELECTING callback
            that._trigger('selecting', that.lastDragEvent, {
              selecting: selectee.element
            });
          }
        } else {
          // UNSELECT
          if (selectee.selecting) {
            if ((that.lastDragEvent.metaKey || that.lastDragEvent.ctrlKey) &&
              selectee.startselected) {
              selectee.$element.removeClass('ui-selecting');
              selectee.selecting = false;
              selectee.$element.addClass('ui-selected');
              selectee.selected = true;
            } else {
              selectee.$element.removeClass('ui-selecting');
              selectee.selecting = false;
              if (selectee.startselected) {
                selectee.$element.addClass('ui-unselecting');
                selectee.unselecting = true;
              }
              // Selectable UNSELECTING callback
              that._trigger('unselecting', that.lastDragEvent, {
                unselecting: selectee.element
              });
            }
          }
          if (selectee.selected) {
            if (!that.lastDragEvent.metaKey && !that.lastDragEvent.ctrlKey && !
              selectee.startselected) {
              selectee.$element.removeClass('ui-selected');
              selectee.selected = false;

              selectee.$element.addClass('ui-unselecting');
              selectee.unselecting = true;
              // Selectable UNSELECTING callback
              that._trigger('unselecting', that.lastDragEvent, {
                unselecting: selectee.element
              });
            }
          }
        }
      });
    },

    /**
     * The original _mouseDrag function overvritten by our one
     *
     * @param  object  The original mousemove event
     * @return boolean Returning false, as the parent returns too
     */
    _mouseDrag: function (event) {
      this.dragged = true;
      if (this.options.disabled) {
        return;
      }
      this.lastDragEvent = event;

      var scrollObj = this._scrollIfNeeded();

      this._updateIntervals({
        keepScrolling: scrollObj.keepScrolling
      });
      this._updateUi({
        doUpdateHelper: true
      });

      return false;
    },

    /**
     * Do the actual calculating/updating of the positions/elements
     *
     * @param  object Options containing if the function should update the helper lasso
     * @return null
     */
    _updateUi: function (options) {
      var scrollObj = this._scrollIfNeeded({
        pageX: this.lastDragEvent.pageX,
        pageY: this.lastDragEvent.pageY
      });
      var relativePos = this._calcRelativePosition({
        x: this.lastDragEvent.pageX,
        y: this.lastDragEvent.pageY,
        scrollLeft: scrollObj.scrollLeft,
        scrollTop: scrollObj.scrollTop
      });
      var relativeArea = this._calcRelativeArea({
        xPos: relativePos.x,
        yPos: relativePos.y
      });
      if (options.doUpdateHelper) {
        this._updateHelper({
          scrollLeft: scrollObj.scrollLeft,
          scrollTop: scrollObj.scrollTop,
          x1: relativeArea.x1,
          y1: relativeArea.y1,
          x2: relativeArea.x2,
          y2: relativeArea.y2
        });
      }
      this._updateSelectees({
        x1: relativeArea.x1,
        y1: relativeArea.y1,
        x2: relativeArea.x2,
        y2: relativeArea.y2
      });
    },

    /**
     * Start the automatic scrolling if needed
     *
     * @param  object Options containing if the function should start the interval
     * @return null
     */
    _updateIntervals: function (options) {
      var that = this;
      if (options.keepScrolling && !this.scrollIntervalId) {
        this.scrollIntervalId = setInterval(function () {
          that._updateUi({
            doUpdateHelper: false
          });
        }, this.options.scrollIntervalTime);
      }
      if (!options.keepScrolling && this.scrollIntervalId)
        this._clearIntervals();
    },

    /**
     * Clear the autoscroll interval
     *
     * @return null
     */
    _clearIntervals: function () {
      // Stop scrolling
      if (this.scrollIntervalId)
        clearInterval(this.scrollIntervalId);
      this.scrollIntervalId = null;
    },

    /**
     * The original _mouseStop event extended with the interval clearer
     *
     * @param  object  The original mousestop event
     * @return boolean The parent's return value
     */
    _mouseStop: function (event) {
      this._clearIntervals();
      var retValue = $.ui.selectable.prototype._mouseStop.call(this,
        event);
      return retValue;
    }
  });
})(jQuery);


text:
using System;
using System.Collections.Generic;

namespace dBosque.Stub.Repository.StubDb.Entities
{
    public partial class Template
    {
        public Template()
        {
            Combination = new HashSet<Combination>();
            TemplateXpath = new HashSet<TemplateXpath>();
        }

        public long TemplateId { get; set; }
        public long MessageTypeId { get; set; }
        public string Description { get; set; }

        public virtual ICollection<Combination> Combination { get; set; }
        public virtual ICollection<TemplateXpath> TemplateXpath { get; set; }
        public virtual MessageType MessageType { get; set; }
    }
}